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 | <file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Fuse.Context;
using Fuse.Model;
using Microsoft.AspNetCore.Cors;
using Microsoft.AspNetCore.Mvc;
namespace Fuse.Controllers
{
[EnableCors("CorsPolicy")]
[Route("[controller]")]
[ApiController]
public class CustomerController : ControllerBase
{
private readonly FuseContext _context;
public CustomerController(FuseContext context)
{
_context = context;
}
// GET api/values
[HttpGet("GetCostumers")]
public IActionResult GetCustomers()
{
var x = _context.Costumer.ToList();
return Ok(_context.Costumer.ToList());
}
// GET api/values/5
[HttpPost("AddCostumer")]
public IActionResult AddCostumer(Costumer costumer)
{
_context.Costumer.Add(costumer);
_context.SaveChanges();
return Ok(costumer);
}
// POST api/values
[HttpPost("DeleteCostumer")]
public IActionResult Post(int Id)
{
var del = _context.Costumer.Where(w => w.IdCostumer == Id).SingleOrDefault();
_context.Costumer.Remove(del);
var a = _context.SaveChanges();
if (a == 1)
{
return Ok("Deleted");
}
else return Ok("Not Deleted");
}
// PUT api/values/5
[HttpPut("{id}")]
public void Put(int id, [FromBody] string value)
{
}
// DELETE api/values/5
[HttpDelete("{id}")]
public void Delete(int id)
{
}
}
}
<file_sep>using System;
using Fuse.Model;
using Microsoft.EntityFrameworkCore;
namespace Fuse.Context
{
public class FuseContext : DbContext
{
public FuseContext(DbContextOptions<FuseContext> options) : base(options)
{
}
public DbSet<Costumer> Costumer { get; set; }
}
}
<file_sep>using System;
using System.ComponentModel.DataAnnotations;
namespace Fuse.Model
{
public class Costumer
{
public Costumer()
{
}
[Key]
public int IdCostumer { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public DateTime Date { get; set; }
public int NbrArticle { get; set; }
}
}
| e6c7af5e335c5bb7dc336c2c95c4bb5b2fe43967 | [
"C#"
] | 3 | C# | younesAfakir/fuse | fdb3e6b29ed72fddb65c6d5942a481c8ccee646a | 76c106fa39e66818bf71b0acb5a107717953db39 |
refs/heads/master | <repo_name>thunderblader/CSIT314<file_sep>/app/src/main/java/com/example/csit314/prescribe/pastPrescriptionRecyclerViewAdapter.java
package com.example.csit314.prescribe;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import android.content.Context;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import com.example.csit314.R;
import com.example.csit314.data.Firebase;
import com.example.csit314.useradminview.UserAdminSearchList;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.database.DatabaseReference;
import java.util.ArrayList;
import java.util.List;
public class pastPrescriptionRecyclerViewAdapter extends RecyclerView.Adapter<pastPrescriptionRecyclerViewAdapter.MyViewHolder> {
Context mContext;
List<Prescription> mData;
public static class MyViewHolder extends RecyclerView.ViewHolder
{
private TextView tv_name;
private TextView tv_date;
private TextView tv_amount;
private TextView tv_status;
public MyViewHolder(View itemView)
{
super(itemView);
tv_name = (TextView)itemView.findViewById(R.id.past_prescription_name);
tv_date = (TextView)itemView.findViewById(R.id.past_prescription_date);
tv_amount = (TextView)itemView.findViewById(R.id.past_prescription_amount);
tv_status = (TextView)itemView.findViewById(R.id.past_prescription_status);
}
}
public pastPrescriptionRecyclerViewAdapter(Context mContext, List<Prescription> mData)
{
this.mContext=mContext;
this.mData=mData;
}
@NonNull
@Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType)
{
View v;
v = LayoutInflater.from(mContext).inflate(R.layout.past_prescription_list,parent,false);
MyViewHolder vHolder = new MyViewHolder(v);
return vHolder;
}
@Override
public void onBindViewHolder(@NonNull pastPrescriptionRecyclerViewAdapter.MyViewHolder holder, int position) {
holder.tv_name.setText(mData.get(position).getpName());
holder.tv_date.setText(mData.get(position).getpDate());
holder.tv_amount.setText(mData.get(position).getpAmount());
holder.tv_status.setText(mData.get(position).getpStatus());
}
@Override
public int getItemCount() {
return mData.size();
}
public void filterList(ArrayList<Prescription> filteredList)
{
mData = filteredList;
notifyDataSetChanged();
}
}
<file_sep>/app/src/androidTest/java/com/example/csit314/useradminview/UserAdminSearchActivityTest.java
package com.example.csit314.useradminview;
import static org.junit.Assert.*;
import android.util.Patterns;
import android.widget.EditText;
import com.example.csit314.R;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
@RunWith(JUnit4.class)
public class UserAdminSearchActivityTest {
@Test
public void TestSearch() {
String SearchEmail = "<EMAIL>";
EditText EmailText = null;
if(SearchEmail.isEmpty()){
EmailText.setError("UID is required");
EmailText.requestFocus();
return;
}
}
@Test
public void TestUpdate() {
String name = "john";
String number = "+123";
String userGrp = "doctor";
EditText nameText = null;
EditText numberText = null;
EditText userGrpText = null;
if(name.isEmpty()){
nameText.setError("Name is required");
nameText.requestFocus();
return;
}
if(number.isEmpty()){
numberText.setError("Number is required");
numberText.requestFocus();
return;
}
if(userGrp.isEmpty()){
userGrpText.setError("User group is required");
userGrpText.requestFocus();
return;
}
}
}<file_sep>/app/src/main/java/com/example/csit314/useradminview/UserAdminSearchList.java
package com.example.csit314.useradminview;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.DefaultItemAnimator;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import com.example.csit314.R;
import com.example.csit314.data.Firebase;
import java.util.ArrayList;
import java.util.Map;
public class UserAdminSearchList extends AppCompatActivity {
private ArrayList<UserAdminHelper> alist;
private RecyclerView recyclerView;
private Button Searchbutton;
private Button BackButton;
private EditText TextUserGroup;
private String search;
Firebase fb = new Firebase(UserAdminSearchList.this);
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_user_admin_search_list);
fb.signIn("<EMAIL>", "123456");
BackButton = findViewById(R.id.UserAdminSearchListBackButton);
Searchbutton = findViewById(R.id.UserAdminSearchListSearchButton);
TextUserGroup = findViewById(R.id.UserAdminSearchListSearchText);
recyclerView = findViewById(R.id.UserAdminRecyclerView);
Searchbutton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
alist = new ArrayList<>();
search = TextUserGroup.getText().toString();
if(search.isEmpty()){
TextUserGroup.setError("Cannot be empty");
TextUserGroup.requestFocus();
return;
}
if(fb.searchUser_type(search) == null){
TextUserGroup.setError("user cannot be found");
TextUserGroup.requestFocus();
return;
}
alist = collectUser(fb.searchUser_type(search));
setAdapter();
}
});
BackButton.setOnClickListener((new View.OnClickListener() {
@Override
public void onClick(View v) {
startActivity(new Intent(UserAdminSearchList.this, UserAdminSearchActivity.class));
finish();
}
}));
}
private void setAdapter() {
UserAdminRecyclerAdapter adapter = new UserAdminRecyclerAdapter(alist);
RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(getApplicationContext());
recyclerView.setLayoutManager(layoutManager);
recyclerView.setItemAnimator(new DefaultItemAnimator());
recyclerView.setAdapter(adapter);
}
public ArrayList<UserAdminHelper> collectUser(Map<String,Object> p)
{
ArrayList<UserAdminHelper> collectUserAlist = new ArrayList<>();
String name;
String number;
for (Map.Entry<String, Object> entry: p.entrySet())
{
Map singleUser = (Map) entry.getValue();
name = (String) singleUser.get("name");
number = (String) singleUser.get("number");
collectUserAlist.add(new UserAdminHelper(name, number));
}
return collectUserAlist;
}
}<file_sep>/app/src/main/java/com/example/csit314/prescribe/newPrescriptionRecyclerViewAdapter.java
package com.example.csit314.prescribe;
import android.content.Context;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import com.example.csit314.R;
import java.util.ArrayList;
import java.util.List;
public class newPrescriptionRecyclerViewAdapter extends RecyclerView.Adapter<newPrescriptionRecyclerViewAdapter.MyViewHolder> {
Context mContext;
List<Prescription> mData;
public static class MyViewHolder extends RecyclerView.ViewHolder
{
private TextView tv_name;
private TextView tv_date;
private TextView tv_amount;
private TextView tv_status;
public MyViewHolder(View itemView)
{
super(itemView);
tv_name = (TextView)itemView.findViewById(R.id.new_prescription_name);
tv_date = (TextView)itemView.findViewById(R.id.new_prescription_date);
tv_amount = (TextView)itemView.findViewById(R.id.new_prescription_amount);
tv_status = (TextView)itemView.findViewById(R.id.new_prescription_status);
}
}
public newPrescriptionRecyclerViewAdapter(Context mContext, List<Prescription> mData)
{
this.mContext=mContext;
this.mData=mData;
}
@NonNull
@Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType)
{
View v;
v = LayoutInflater.from(mContext).inflate(R.layout.new_prescription_list,parent,false);
MyViewHolder vHolder = new MyViewHolder(v);
return vHolder;
}
@Override
public void onBindViewHolder(@NonNull newPrescriptionRecyclerViewAdapter.MyViewHolder holder, int position) {
holder.tv_name.setText(mData.get(position).getpName());
holder.tv_date.setText(mData.get(position).getpDate());
holder.tv_amount.setText(mData.get(position).getpAmount());
holder.tv_status.setText(mData.get(position).getpStatus());
}
@Override
public int getItemCount() {
return mData.size();
}
public void filterList(ArrayList<Prescription> filteredList)
{
mData = filteredList;
notifyDataSetChanged();
}
}
<file_sep>/app/src/main/java/com/example/csit314/doctorview/DoctorViewPrescriptionActivity.java
package com.example.csit314.doctorview;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.widget.EditText;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.example.csit314.R;
import com.example.csit314.patientview.Patient;
import com.example.csit314.prescribe.Prescription;
import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.List;
public class DoctorViewPrescriptionActivity extends AppCompatActivity {
private RecyclerView myrecyclerview;
private List<Prescription> listPatientPrescription = new ArrayList<>();
private List<Patient> listPatient;
DoctorRecyclerViewAdapter recyclerAdapter;
private RecyclerView.LayoutManager mLayoutManager;
private String password;
private String email;
private ArrayList<String> medications;
public DoctorViewPrescriptionActivity() {
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.doctor_view_prescription);
populate();
password =(String) getIntent().getStringExtra("password");
email =(String) getIntent().getStringExtra("email");
medications =(ArrayList<String>) getIntent().getStringArrayListExtra("medications");
medications = (ArrayList<String>) getIntent().getExtras().getStringArrayList("medications");
myrecyclerview = (RecyclerView)findViewById(R.id.doctor_view_recyclerview);
getWindow().getDecorView().findViewById(R.id.doctor_view_recyclerview).invalidate();
myrecyclerview.destroyDrawingCache();
myrecyclerview.setVisibility(myrecyclerview.INVISIBLE);
myrecyclerview.setVisibility(myrecyclerview.VISIBLE);
myrecyclerview.setHasFixedSize(true);
mLayoutManager = new LinearLayoutManager(this);
recyclerAdapter = new DoctorRecyclerViewAdapter(listPatientPrescription,listPatient,email,password,medications);
myrecyclerview.setLayoutManager(mLayoutManager);
EditText editText = findViewById(R.id.doctor_view_edittext);
editText.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
@Override
public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
@Override
public void afterTextChanged(Editable editable) {
filter(editable.toString());
}
});
myrecyclerview.setAdapter(recyclerAdapter);
recyclerAdapter.notifyDataSetChanged();
}
private void filter(String text) {
ArrayList<Prescription> filteredList = new ArrayList<>();
ArrayList<Patient> filteredPatientList = new ArrayList<>();
try {
for (Patient p : listPatient){
for (Prescription pres : p.getAlist()) {
if (p.getName().toLowerCase().contains(text.toLowerCase())
|| p.getEmail().toLowerCase().contains(text.toLowerCase())
|| p.getNumber().toLowerCase().contains(text.toLowerCase())
|| pres.getpName().toLowerCase().contains(text.toLowerCase())
|| pres.getpStatus().toLowerCase().contains(text.toLowerCase())
|| pres.getpDate().toLowerCase().contains(text.toLowerCase())
|| pres.getpAmount().toLowerCase().contains(text.toLowerCase())) {
filteredList.add(pres);
filteredPatientList.add(p);
}
}
}
}catch(Exception e)
{
e.printStackTrace();
}
recyclerAdapter.filterList(filteredList,filteredPatientList);
}
private void populate() {
listPatientPrescription = new ArrayList<Prescription>();
listPatient = new ArrayList<Patient>();
ArrayList<Prescription> allPrescriptionAList = new ArrayList<Prescription>();
listPatient = (ArrayList<Patient>) getIntent().getSerializableExtra("DoctorArrayList");
for (Patient p : listPatient) {
for (Prescription pres : p.getAlist()) {
listPatientPrescription.add(pres);
}
}
}
}
<file_sep>/app/src/androidTest/java/com/example/csit314/useradminview/UserAdminAddActivityTest.java
package com.example.csit314.useradminview;
import static org.junit.Assert.*;
import android.util.Patterns;
import android.widget.EditText;
import com.example.csit314.R;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
@RunWith(JUnit4.class)
public class UserAdminAddActivityTest {
@Test
public void TestName() {
String Name = "Jerald";
EditText TextName = null;
if(Name.isEmpty()){
TextName.setError("Name is required");
TextName.requestFocus();
return;
}
}
@Test
public void TestEmail() {
String Email = "<EMAIL>";
EditText TextEmail = null;
if(Email.isEmpty()){
TextEmail.setError("Email is required");
TextEmail.requestFocus();
return;
}
if(!Patterns.EMAIL_ADDRESS.matcher(Email).matches()){
TextEmail.setError("Please enter a valid email");
TextEmail.requestFocus();
return;
}
}
@Test
public void TestPassword() {
String Password = "<PASSWORD>";
EditText TextPassword = null;
if(Password.isEmpty()){
TextPassword.setError("Password is required");
TextPassword.requestFocus();
return;
}
if(Password.length()<6){
TextPassword.setError("Please enter > 6 characters");
TextPassword.requestFocus();
return;
}
}
@Test
public void TestNumber() {
String Number = "+123";
EditText TextNumber = null;
if(Number.isEmpty()){
TextNumber.setError("Number is required");
TextNumber.requestFocus();
return;
}
}
@Test
public void TestUser_Group() {
String UserGroup = "admin";
EditText TextUserGroup = null;
if(UserGroup.isEmpty()){
TextUserGroup.setError("User group is required");
TextUserGroup.requestFocus();
return;
}
}
}<file_sep>/app/src/androidTest/java/com/example/csit314/ui/login/theLoginActivityTest.java
package com.example.csit314.ui.login;
import android.app.Activity;
import android.content.Intent;
import android.util.Patterns;
import android.widget.EditText;
import android.widget.Toast;
import androidx.annotation.NonNull;
import com.example.csit314.R;
import com.example.csit314.data.Firebase;
import com.example.csit314.useradminview.UserAdminActivity;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.database.DatabaseReference;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
@RunWith(JUnit4.class)
public class theLoginActivityTest {
FirebaseAuth mAuth;
Activity activity;
@Test
public void TestLoginLogoutAdmin() {
//email and password
String user_Email = "<EMAIL>";
String user_Password = "<PASSWORD>";
//get firebase authentication
mAuth = FirebaseAuth.getInstance();
//user input
EditText the_Email = null;
EditText the_Password = null;
//conditions for input
if(user_Email.isEmpty() || user_Password.isEmpty())
{
the_Email.setError("Please enter a valid email and password");
the_Email.requestFocus();
return;
}
else if(!Patterns.EMAIL_ADDRESS.matcher(user_Email).matches())
{
the_Email.setError("Please enter a valid email");
the_Email.requestFocus();
return;
}
else if(user_Password.length() < 6)
{
the_Password.setError("Please enter > 6 characters");
the_Password.requestFocus();
return;
}
//sign in to database using email, password
mAuth.signInWithEmailAndPassword(user_Email, user_Password).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
@Override
public void onComplete(@NonNull Task<AuthResult> task) {
if (task.isSuccessful())
{
Toast.makeText(activity.getApplicationContext(), "login successful", Toast.LENGTH_SHORT).show();
}
else
{
Toast.makeText(activity.getApplicationContext(), "login failed", Toast.LENGTH_SHORT).show();
}
}
});
//sign out
mAuth.signOut();
}
@Test
public void TestLoginLogoutPharmacist() {
//email and password
String user_Email = "<EMAIL>";
String user_Password = "<PASSWORD>";
//get firebase authentication
mAuth = FirebaseAuth.getInstance();
//user input
EditText the_Email = null;
EditText the_Password = null;
//conditions for input
if(user_Email.isEmpty() || user_Password.isEmpty())
{
the_Email.setError("Please enter a valid email and password");
the_Email.requestFocus();
return;
}
else if(!Patterns.EMAIL_ADDRESS.matcher(user_Email).matches())
{
the_Email.setError("Please enter a valid email");
the_Email.requestFocus();
return;
}
else if(user_Password.length() < 6)
{
the_Password.setError("Please enter > 6 characters");
the_Password.requestFocus();
return;
}
//sign in to database using email, password
mAuth.signInWithEmailAndPassword(user_Email, user_Password).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
@Override
public void onComplete(@NonNull Task<AuthResult> task) {
if (task.isSuccessful())
{
Toast.makeText(activity.getApplicationContext(), "login successful", Toast.LENGTH_SHORT).show();
}
else
{
Toast.makeText(activity.getApplicationContext(), "login failed", Toast.LENGTH_SHORT).show();
}
}
});
//sign out
mAuth.signOut();
}
@Test
public void TestLoginLogoutDoctor() {
//email and password
String user_Email = "<EMAIL>";
String user_Password = "<PASSWORD>";
//get firebase authentication
mAuth = FirebaseAuth.getInstance();
//user input
EditText the_Email = null;
EditText the_Password = null;
//conditions for input
if(user_Email.isEmpty() || user_Password.isEmpty())
{
the_Email.setError("Please enter a valid email and password");
the_Email.requestFocus();
return;
}
else if(!Patterns.EMAIL_ADDRESS.matcher(user_Email).matches())
{
the_Email.setError("Please enter a valid email");
the_Email.requestFocus();
return;
}
else if(user_Password.length() < 6)
{
the_Password.setError("Please enter > 6 characters");
the_Password.requestFocus();
return;
}
//sign in to database using email, password
mAuth.signInWithEmailAndPassword(user_Email, user_Password).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
@Override
public void onComplete(@NonNull Task<AuthResult> task) {
if (task.isSuccessful())
{
Toast.makeText(activity.getApplicationContext(), "login successful", Toast.LENGTH_SHORT).show();
}
else
{
Toast.makeText(activity.getApplicationContext(), "login failed", Toast.LENGTH_SHORT).show();
}
}
});
//sign out
mAuth.signOut();
}
@Test
public void TestLoginLogoutPatient() {
//email and password
String user_Email = "<EMAIL>";
String user_Password = "<PASSWORD>";
//get firebase authentication
mAuth = FirebaseAuth.getInstance();
//user input
EditText the_Email = null;
EditText the_Password = null;
//conditions for input
if(user_Email.isEmpty() || user_Password.isEmpty())
{
the_Email.setError("Please enter a valid email and password");
the_Email.requestFocus();
return;
}
else if(!Patterns.EMAIL_ADDRESS.matcher(user_Email).matches())
{
the_Email.setError("Please enter a valid email");
the_Email.requestFocus();
return;
}
else if(user_Password.length() < 6)
{
the_Password.setError("Please enter > 6 characters");
the_Password.requestFocus();
return;
}
//sign in to database using email, password
mAuth.signInWithEmailAndPassword(user_Email, user_Password).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
@Override
public void onComplete(@NonNull Task<AuthResult> task) {
if (task.isSuccessful())
{
Toast.makeText(activity.getApplicationContext(), "login successful", Toast.LENGTH_SHORT).show();
}
else
{
Toast.makeText(activity.getApplicationContext(), "login failed", Toast.LENGTH_SHORT).show();
}
}
});
//sign out
mAuth.signOut();
}
}<file_sep>/app/src/main/java/com/example/csit314/doctorview/DoctorUpdatePrescriptionActivity.java
package com.example.csit314.doctorview;
import android.app.DatePickerDialog;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.text.InputType;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.NavUtils;
import com.example.csit314.R;
import com.example.csit314.data.Firebase;
import com.example.csit314.email.SendMail;
import com.example.csit314.patientview.Patient;
import com.example.csit314.prescribe.Prescription;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Map;
public class DoctorUpdatePrescriptionActivity extends AppCompatActivity implements AdapterView.OnItemSelectedListener{
private Button updateBtn;
private DatePickerDialog.OnDateSetListener mDateSetListener;
private Spinner spinner_prescription_name;
private ArrayList<String> medications;
private String[] medicationsArray;
private TextView tv_patient_name;
private TextView tv_patient_number;
private TextView tv_patient_email;
private EditText et_prescription_date;
private EditText et_prescription_amount;
private EditText et_prescription_status;
private String patient_name;
private String patient_number;
private String patient_email;
private String prescription_name;
private String prescription_date;
private String prescription_amount;
private String prescription_status;
private String prescription_id;
private String user_password;
private String user_email;
Firebase the_firebase = new Firebase(this);
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.doctor_update_prescription);
//Initialize button
tv_patient_name = (TextView) findViewById(R.id.patient_name_doctorTextView);
tv_patient_number = (TextView) findViewById(R.id.patient_number_doctorTextView);
tv_patient_email = (TextView) findViewById(R.id.patient_email_doctorTextView);
et_prescription_date = (EditText) findViewById(R.id.prescription_date_editText);
et_prescription_amount = (EditText) findViewById(R.id.prescription_amount_editText);
et_prescription_status = (EditText) findViewById(R.id.prescription_status_editText);
spinner_prescription_name = (Spinner) findViewById(R.id.prescription_spinner);
//get Strings values
patient_name = (String) getIntent().getStringExtra("patientname");
patient_number = (String) getIntent().getStringExtra("patientnumber");
patient_email = (String) getIntent().getStringExtra("patientemail");
prescription_name = (String) getIntent().getStringExtra("prescriptionname");
prescription_date = (String) getIntent().getStringExtra("prescriptiondate");
prescription_amount = (String) getIntent().getStringExtra("prescriptionamount");
prescription_status = (String) getIntent().getStringExtra("prescriptionstatus");
prescription_id = (String) getIntent().getStringExtra("prescriptionid");
//Set Text
tv_patient_name.setText( patient_name);
tv_patient_number.setText(patient_number);
tv_patient_email.setText(patient_email);
et_prescription_date.setText(prescription_date);
et_prescription_amount.setText(prescription_amount);
et_prescription_amount.setHint("Amount : " + prescription_amount);
et_prescription_status.setText(" Status : " + prescription_status);
//Set Password
user_email = (String) getIntent().getStringExtra("email");
user_password = (String) getIntent().getStringExtra("password");
//MEDICATION Spinner
medications =(ArrayList<String>) getIntent().getStringArrayListExtra("medications");
medications = (ArrayList<String>) getIntent().getExtras().getStringArrayList("medications");
medicationsArray = medications.toArray(new String[medications.size()]);
prescription_name = medicationsArray[0];
updateBtn = (Button) findViewById(R.id.updateBtn);
updateBtn.setEnabled(true);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(DoctorUpdatePrescriptionActivity.this,android.R.layout.simple_spinner_item,medicationsArray);
for(String s : medications)
{
Log.i("Medications", s);
}
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner_prescription_name.setAdapter(adapter);
spinner_prescription_name.setOnItemSelectedListener(this);
//Calendar button
et_prescription_date.setInputType(InputType.TYPE_NULL);
et_prescription_date.requestFocus();
et_prescription_date.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Calendar cal = Calendar.getInstance();
int year = cal.get(Calendar.YEAR);
int month = cal.get(Calendar.MONTH);
int day = cal.get(Calendar.DAY_OF_MONTH);
DatePickerDialog dialog = new DatePickerDialog(DoctorUpdatePrescriptionActivity.this,
android.R.style.Theme_Holo_Light_Dialog_MinWidth,
mDateSetListener,
year,month,day);
dialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
dialog.show();
}
});
mDateSetListener = new DatePickerDialog.OnDateSetListener() {
@Override
public void onDateSet(DatePicker datePicker, int year, int month, int day) {
month = month+1;
String date = String.valueOf(day) + "-" + String.valueOf(month) + "-" + String.valueOf(year);
et_prescription_date.setText(date);
}
};
}
public void updateOnClick(View view) {
updatePrescription();
}
private void launchDoctorViewPrescriptionActivity() {
Intent intent = new Intent(this, DoctorViewPrescriptionActivity.class);
ArrayList<Patient> patientAlist;
Map p = the_firebase.searchUserGroup();
patientAlist = collectUserAndPrescription(p);
intent.putParcelableArrayListExtra("DoctorArrayList",patientAlist);
intent.putStringArrayListExtra("medications",medications);
intent.putExtra("email",user_email);
intent.putExtra("password",<PASSWORD>_password);
finish();
startActivity(intent);
}
private void updatePrescription() {
if(!et_prescription_date.getText().toString().equals(""))
prescription_date = et_prescription_date.getText().toString();
if(!et_prescription_amount.getText().toString().equals("") || !et_prescription_amount.getText().toString().equals("0"))
prescription_amount = et_prescription_amount.getText().toString();
if(prescription_status.equals(""))
prescription_status = "In Progress";
if(prescription_status.equals("") || prescription_date.equals("") || prescription_amount.equals(""))
Toast.makeText(getApplicationContext(),"Field(s) is empty, Please try again.",Toast.LENGTH_LONG).show();
else {
the_firebase.edit_prescription(patient_email, prescription_id,prescription_name,prescription_date,prescription_amount);
Toast.makeText(getApplicationContext(), "Updated Prescription...", Toast.LENGTH_LONG).show();
updateBtn.setEnabled(false);
launchDoctorViewPrescriptionActivity();
}
}
protected void onStart()
{
super.onStart();
the_firebase.signIn(user_email,user_password);
}
public ArrayList<Prescription> collectPrescription(Map<String,Object> p)
{
ArrayList<Prescription> prescriptionAlist = new ArrayList<>();
String id;
String name;
Long amount;
String status;
String date;
if(p != null)
{
for (Map.Entry<String, Object> entry : p.entrySet()) {
Map singlePrescription = (Map) entry.getValue();
id = (String) entry.getKey();
name = (String) singlePrescription.get("name");
status = (String) singlePrescription.get("status");
date = (String) singlePrescription.get("date");
if (singlePrescription.get("amount") instanceof String)
amount = Long.parseLong((String) "0");
else
amount = (Long) singlePrescription.get("amount");
if(entry.getKey().equals(prescription_id)){
name = prescription_name;
date = prescription_date;
amount = Long.parseLong(prescription_amount);
status = prescription_status;
}
prescriptionAlist.add(new Prescription(id,name, date, String.valueOf(amount), status));
}
}
return prescriptionAlist;
}
public ArrayList<Patient> collectUserAndPrescription(Map<String,Object> patient)
{
ArrayList<Patient> patientAlist = new ArrayList<>();
String name;
String email;
String number;
String user_type;
try {
for (Map.Entry<String, Object> entry : patient.entrySet()) {
Map singleUser = (Map) entry.getValue();
user_type = (String) singleUser.get("user_type");
name = (String) singleUser.get("name");
email = entry.getKey().replace("_com", ".com");
number = (String) singleUser.get("number");
if (user_type.toLowerCase().equals("patient"))
patientAlist.add(new Patient(name, number, email, collectPrescription(the_firebase.get_pastprescriptionObject(email))));
}
}catch(Exception e)
{
e.printStackTrace();
}
return patientAlist;
}
@Override
public void onBackPressed() {
NavUtils.navigateUpFromSameTask(this);
}
@Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
prescription_name = medicationsArray[i];
}
@Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
}
<file_sep>/app/src/main/java/com/example/csit314/doctorview/DoctorRecyclerViewAdapter.java
package com.example.csit314.doctorview;
import android.app.Activity;
import android.content.Intent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import com.example.csit314.R;
import com.example.csit314.patientview.Patient;
import com.example.csit314.pharmacyview.PharmacyUpdatePrescriptionActivity;
import com.example.csit314.prescribe.Prescription;
import java.util.ArrayList;
import java.util.List;
public class DoctorRecyclerViewAdapter extends RecyclerView.Adapter<DoctorRecyclerViewAdapter.MyViewHolder> {
private List<Patient> patientData;
private List<Prescription> prescriptionData;
private String password;
private String email;
private ArrayList<String> medications;
public static class MyViewHolder extends RecyclerView.ViewHolder
{
private LinearLayout item_prescription;
private TextView tv_patient_name;
private TextView tv_patient_email;
private TextView tv_name;
private TextView tv_date;
private TextView tv_amount;
private TextView tv_status;
public MyViewHolder(View itemView)
{
super(itemView);
item_prescription = (LinearLayout)itemView.findViewById(R.id.doctor_view_item_id);
tv_patient_name = (TextView)itemView.findViewById(R.id.doctor_view_patient_name);
tv_patient_email = (TextView)itemView.findViewById(R.id.doctor_view_patient_email);
tv_name = (TextView)itemView.findViewById(R.id.doctor_view_prescription_name);
tv_date = (TextView)itemView.findViewById(R.id.doctor_view_prescription_date);
tv_amount = (TextView)itemView.findViewById(R.id.doctor_view_prescription_amount);
tv_status = (TextView)itemView.findViewById(R.id.doctor_view_prescription_status);
}
}
public DoctorRecyclerViewAdapter(List<Prescription> prescriptionData, List<Patient> patientData, String email, String password,ArrayList<String> medications)
{
this.prescriptionData=prescriptionData;
this.patientData=patientData;
this.password = <PASSWORD>;
this.email = email;
this.medications = medications;
}
@NonNull
@Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType)
{
View v;
v = LayoutInflater.from(parent.getContext()).inflate(R.layout.doctor_view_list,parent,false);
MyViewHolder vHolder = new MyViewHolder(v);
vHolder.item_prescription.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View view) {
//Toast.makeText(parent.getContext(), "Test Click"+String.valueOf(vHolder.getAdapterPosition()), Toast.LENGTH_SHORT).show();
final Intent intent;
String patient_name = "";
String patient_email = "";
String patient_number = "";
intent = new Intent(parent.getContext(), DoctorUpdatePrescriptionActivity.class);
intent.putExtra("prescriptionname",prescriptionData.get(vHolder.getAdapterPosition()).getpName());
intent.putExtra("prescriptiondate",prescriptionData.get(vHolder.getAdapterPosition()).getpDate());
intent.putExtra("prescriptionstatus",prescriptionData.get(vHolder.getAdapterPosition()).getpStatus());
intent.putExtra("prescriptionamount",prescriptionData.get(vHolder.getAdapterPosition()).getpAmount());
intent.putExtra("prescriptionid",prescriptionData.get(vHolder.getAdapterPosition()).getpID());
for(Patient p : patientData)
for(Prescription pres : p.getAlist())
{
if(prescriptionData.get(vHolder.getAdapterPosition()).equals(pres))
{
patient_name = p.getName();
patient_email = p.getEmail();
patient_number = p.getNumber();
}
}
intent.putExtra("patientname",patient_name);
intent.putExtra("patientemail",patient_email);
intent.putExtra("patientnumber",patient_number);
intent.putExtra("email",email);
intent.putExtra("password",<PASSWORD>);
intent.putStringArrayListExtra("medications",medications);
((Activity)parent.getContext()).finish();
parent.getContext().startActivity(intent);
}
});
return vHolder;
}
@Override
public void onBindViewHolder(@NonNull DoctorRecyclerViewAdapter.MyViewHolder holder, int position) {
for(Patient p : patientData)
for(Prescription pres : p.getAlist())
{
if(prescriptionData.get(position).equals(pres))
{
holder.tv_patient_name.setText(p.getName());
holder.tv_patient_email.setText(p.getEmail());
}
}
holder.tv_name.setText(prescriptionData.get(position).getpName());
holder.tv_date.setText(prescriptionData.get(position).getpDate());
holder.tv_amount.setText(prescriptionData.get(position).getpAmount());
holder.tv_status.setText(prescriptionData.get(position).getpStatus());
}
@Override
public int getItemCount() {
return prescriptionData.size();
}
public void filterList(ArrayList<Prescription> filteredList,ArrayList<Patient> filteredPatientList)
{
prescriptionData = filteredList;
patientData = filteredPatientList;
notifyDataSetChanged();
}
}
<file_sep>/app/src/main/java/com/example/csit314/email/SendMail.java
package com.example.csit314.email;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.media.MediaScannerConnection;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Environment;
import android.util.Log;
import javax.activation.CommandMap;
import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.activation.MailcapCommandMap;
import javax.mail.BodyPart;
import javax.mail.Message;
import javax.mail.MessagingException;
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 java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Properties;
import androidmads.library.qrgenearator.QRGContents;
import androidmads.library.qrgenearator.QRGSaver;
public class SendMail extends AsyncTask<Void, Void, Void> {
public static final String EMAIL = "<EMAIL>"; //
public static final String PASSWORD = "<PASSWORD>!";
private Context context;
private Session session;
private String email, subject, message;
private String url;
public SendMail(Context context, String email, String subject, String message,String url) {
this.context = context;
this.email = email;
this.subject = subject;
this.message = message;
this.url = url;
}
public SendMail(Context context, String email, String subject, String message) {
this.context = context;
this.email = email;
this.subject = subject;
this.message = message;
this.url = "";
}
@Override
protected Void doInBackground(Void... voids) {
Properties properties = new Properties();
properties.put("mail.smtp.host", "smtp.gmail.com");
properties.put("mail.smtp.socketFactory.port", "465");
properties.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
properties.put("mail.smtp.auth", "true");
properties.put("mail.smtp.port", "465");
session = Session.getDefaultInstance(properties, new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(EMAIL, PASSWORD);
}
});
MimeMessage mimeMessage = new MimeMessage(session);
try {
mimeMessage.setFrom(new InternetAddress(EMAIL));
mimeMessage.addRecipients(Message.RecipientType.TO, String.valueOf(new InternetAddress(email)));
mimeMessage.setSubject(subject);
if(url != "")
{
File file = new File(url);
//As inline
Multipart multipart = new MimeMultipart();
// create bodypart with image and set content-id
MimeBodyPart messageBodyPart = new MimeBodyPart();
DataSource source = new FileDataSource(new File(url));
messageBodyPart.setDataHandler(new DataHandler(source));
messageBodyPart.setFileName("image.png");
messageBodyPart.setDisposition(MimeBodyPart.INLINE);
messageBodyPart.setHeader("Content-ID", "<vogue>");
multipart.addBodyPart(messageBodyPart);
// create bodypart with html content and reference to the content-id
messageBodyPart = new MimeBodyPart();
String htmlText = message + "<br><br><img src=\"cid:vogue\">";
messageBodyPart.setContent(htmlText, "text/html");
multipart.addBodyPart(messageBodyPart);
// add multipart to message
mimeMessage.setContent(multipart);
// Create the message part
}
Transport.send(mimeMessage);
Log.i("SendEmail","Sending Email");
} catch (MessagingException e) {
e.printStackTrace();
}
return null;
}
}
<file_sep>/app/src/main/java/com/example/csit314/pharmacyview/PharmacyActivity.java
package com.example.csit314.pharmacyview;
import androidx.appcompat.app.AppCompatActivity;
import android.Manifest;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.View;
import android.app.Activity;
import android.content.Intent;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.inputmethod.EditorInfo;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.StringRes;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProvider;
import com.example.csit314.R;
import com.example.csit314.databinding.ActivityLoginBinding;
import com.example.csit314.email.SendMail;
import com.example.csit314.patientview.Patient;
import com.example.csit314.patientview.PatientActivity;
import com.example.csit314.prescribe.Prescription;
import com.example.csit314.prescribe.PrescriptionActivity;
import com.example.csit314.ui.login.ChangePasswordActivity;
import com.example.csit314.ui.login.theLoginActivity;
import com.example.csit314.useradminview.UserAdminActivity;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import com.google.zxing.WriterException;
import java.io.File;
import java.io.FileOutputStream;
import java.util.ArrayList;
import androidmads.library.qrgenearator.QRGContents;
import androidmads.library.qrgenearator.QRGEncoder;
import androidmads.library.qrgenearator.QRGSaver;
public class PharmacyActivity extends AppCompatActivity {
private String user_Email;
private String user_Password;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_pharmacy);
user_Password =(String) getIntent().getStringExtra("<PASSWORD>");
user_Email =(String) getIntent().getStringExtra("email");
}
public void onViewPrescriptionClick(View view) {
Intent intent = new Intent(this,PharmacyViewPrescriptionActivity.class);
ArrayList<Patient> PatientAlist = (ArrayList<Patient>) getIntent().getSerializableExtra("PatientArrayList");
intent.putExtra("PatientArrayList",PatientAlist);
intent.putExtra("email",user_Email);
intent.putExtra("password",<PASSWORD>);
startActivity(intent);
}
/*
public void onUpdatePrescriptionClick(View view) {
Intent intent = new Intent(this,PharmacyUpdatePrescriptionActivity.class);
ArrayList<Patient> PatientAlist = (ArrayList<Patient>) getIntent().getSerializableExtra("PatientArrayList");
intent.putExtra("PatientArrayList",PatientAlist);
intent.putExtra("email",user_Email);
intent.putExtra("password",<PASSWORD>);
startActivity(intent);
}*/
public void changePasswordOnClick(View view)
{
Intent i = new Intent( this, ChangePasswordActivity.class);
startActivity(i);
}
public void logoutOnClick(View view)
{
Intent i = new Intent( this, theLoginActivity.class);
startActivity(i);
}
}
<file_sep>/app/src/main/java/com/example/csit314/patientview/Patient.java
package com.example.csit314.patientview;
import android.os.Parcel;
import android.os.Parcelable;
import com.example.csit314.prescribe.Prescription;
import java.io.Serializable;
import java.util.ArrayList;
public class Patient implements Parcelable {
ArrayList<Prescription> pAlist;
String name,number ,email;
public Patient(){
}
public Patient(String name,String number,String email,ArrayList<Prescription> pAlist) {
this.name = name;
this.number = number;
this.email = email;
this.pAlist = new ArrayList<>();
for (Prescription p : pAlist) {
this.pAlist.add(p);
}
}
protected Patient(Parcel in) {
pAlist = in.createTypedArrayList(Prescription.CREATOR);
name = in.readString();
number = in.readString();
email = in.readString();
}
public static final Creator<Patient> CREATOR = new Creator<Patient>() {
@Override
public Patient createFromParcel(Parcel in) {
return new Patient(in);
}
@Override
public Patient[] newArray(int size) {
return new Patient[size];
}
};
public String getEmail() {
return email;
}
public String getName() {
return name;
}
public String getNumber() {
return number;
}
public ArrayList<Prescription> getAlist() {
return pAlist;
}
public void setName(String name) {
this.name = name;
}
public void setEmail(String email) {
this.email = email;
}
public void setNumber(String number) {
this.number = number;
}
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel parcel, int i) {
parcel.writeTypedList(pAlist);
parcel.writeString(name);
parcel.writeString(number);
parcel.writeString(email);
}
}
<file_sep>/app/src/main/java/com/example/csit314/data/Firebase.java
package com.example.csit314.data;
import android.app.Activity;
import android.os.CountDownTimer;
import android.widget.Toast;
import androidx.annotation.NonNull;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.AuthCredential;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;
import java.util.Map;
import java.util.Random;
public class Firebase {
private FirebaseUser current_User;
private FirebaseAuth mAuth;
private DatabaseReference mDatabase, user_ref, update_ref;
private DataSnapshot dataSnapshotReference;
private String the_name, the_number, the_userType, the_email;
private boolean signed_in, firebase_ready, database_ready = false;
private CountDownTimer firebase_timer;
private Activity activityReference;
public String getThe_number() { return the_number; }
public String getThe_name() { return the_name; }
public String getThe_userType() { return the_userType; }
public String getThe_userData(String user_email, String data_name) { return dataSnapshotReference.child("User_Group").child(user_email).child(data_name).getValue().toString(); }
public Boolean is_database_ready()
{
return database_ready;
}
public Firebase(Activity currentActivity)
{
activityReference = currentActivity;
run_firebase();
}
private void start_firebase()
{
firebase_timer = new CountDownTimer(3000,1000)
{
@Override
public void onTick(long l) { }
@Override
public void onFinish()
{
if(!firebase_ready) //when firebase has finished initialising
run_firebase();
}
};
firebase_timer.start();
}
private void run_firebase()
{
mAuth = FirebaseAuth.getInstance();
mDatabase = FirebaseDatabase.getInstance().getReference();
if(mAuth != null && mDatabase != null)
firebase_ready = true;
if(!firebase_ready)
start_firebase();
}
private void complete_signin(String email)
{
signed_in = true;
the_email = email;
user_ref = mDatabase.child("User_Group").child(convert_email(the_email));
current_User = mAuth.getCurrentUser();
}
public void createAccount(String email, String password, String name, String number, String user_type)
{
mAuth.createUserWithEmailAndPassword(email, password).addOnCompleteListener(activityReference, new OnCompleteListener<AuthResult>()
{
@Override
public void onComplete(@NonNull Task<AuthResult> task)
{
if (task.isSuccessful())
{
Toast.makeText(activityReference.getApplicationContext(), "Created", Toast.LENGTH_SHORT).show();
complete_signin(email);
setData(number, name, user_type);
//fetch_database(mDatabase);
//signout();
}
else
{
Toast.makeText(activityReference.getApplicationContext(), "Email has been taken", Toast.LENGTH_SHORT).show();
}
}
});
}
public void signIn(String email, String password)
{
mAuth.signInWithEmailAndPassword(email, password).addOnCompleteListener( activityReference, new OnCompleteListener<AuthResult>()
{
@Override
public void onComplete(@NonNull Task<AuthResult> task)
{
if (task.isSuccessful())
{
complete_signin(email);
fetch_database(mDatabase);
}
else
{
Toast.makeText(activityReference.getApplicationContext(), "Invalid Email or Password", Toast.LENGTH_SHORT).show();
}
}
});
}
public void signout() { mAuth.signOut(); }
private void setData(String number, String name, String user_type)
{
mDatabase.child(user_type).child(convert_email(the_email)).child("name").setValue(name);
mDatabase.child(user_type).child(convert_email(the_email)).child("number").setValue(number);
//user_ref.child("prescription").setValue("null");
user_ref.child("number").setValue(number);
user_ref.child("name").setValue(name);
user_ref.child("user_type").setValue(user_type);
}
public void fetch_database(DatabaseReference the_reference)
{
ValueEventListener postListener = new ValueEventListener()
{
@Override
public void onDataChange(DataSnapshot dataSnapshot)
{
dataSnapshotReference = dataSnapshot;
fetchData();
database_ready = true;
}
@Override
public void onCancelled(DatabaseError databaseError) { }
};
the_reference.addValueEventListener(postListener);
}
private void fetchData()
{
the_number = dataSnapshotReference.child("User_Group").child(convert_email(the_email)).child("number").getValue().toString();
the_name = dataSnapshotReference.child("User_Group").child(convert_email(the_email)).child("name").getValue().toString();
the_userType = dataSnapshotReference.child("User_Group").child(convert_email(the_email)).child("user_type").getValue().toString();
}
public String generateRandomstring(int length)
{
String chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
Random generator = new Random();
StringBuilder randomString = new StringBuilder();
for (int i = 0; i < length; i++)
randomString.append(chars.charAt(generator.nextInt(chars.length())));
return randomString.toString();
}
public void change_password(String password)
{
FirebaseUser user = mAuth.getCurrentUser();
user.updatePassword(password).addOnCompleteListener(new OnCompleteListener<Void>()
{
@Override
public void onComplete(@NonNull Task<Void> task)
{
if(task.isSuccessful())
Toast.makeText(activityReference.getApplicationContext(), "Password Changed Successfully", Toast.LENGTH_SHORT).show();
else
Toast.makeText(activityReference.getApplicationContext(), "Password not changed", Toast.LENGTH_SHORT).show();
}
});
}
public Map<String, String> searchUser(String user_email)
{
Map<String, String> the_user = (Map) dataSnapshotReference.child("User_Group").child(convert_email(user_email)).getValue();
return the_user;
}
public Map<String, Object> searchUserGroup()
{
Map<String, Object> the_user = (Map) dataSnapshotReference.child("User_Group").getValue();
return the_user;
}
public Map<String, String> get_medication()
{
Map<String, String> the_medication = (Map) dataSnapshotReference.child("medication").getValue();
return the_medication;
}
public void updateUser(String user_email, String number, String name, String user_type)
{
update_ref = mDatabase.child("User_Group").child(convert_email(user_email));
update_ref.child("number").setValue(number);
update_ref.child("name").setValue(name);
update_ref.child("user_type").setValue(user_type);
update_ref = mDatabase.child(user_type).child(convert_email(user_email));
update_ref.child("number").setValue(number);
update_ref.child("name").setValue(name);
}
public Map<String, Object> searchUser_type(String user_type)
{
Map<String, Object> the_usertype = (Map) dataSnapshotReference.child(user_type).getValue();
return the_usertype;
}
/*public Map<String, String> get_prescription(String the_prescription)
{
Map<String, String> prescription = (Map) dataSnapshotReference.child("medication").child(the_prescription).getValue();
return prescription;
}
public Map<String, String> get_pastprescription(String user_email)
{
Map<String, String> my_prescription = (Map) dataSnapshotReference.child("User_Group").child(convert_email(user_email)).child("prescription").getValue();
//Map<String, String> my_prescription = (Map) dataSnapshotReference.child("User_Group").child(the_email).getValue();
return my_prescription;
}*/
public Map<String, Object> get_pastprescriptionObject(String user_email)
{
Map<String, Object> my_prescription = (Map) dataSnapshotReference.child("User_Group").child(convert_email(user_email)).child("prescription").getValue();
//Map<String, String> my_prescription = (Map) dataSnapshotReference.child("User_Group").child(the_email).getValue();
return my_prescription;
}
public void add_prescription(String patient_email,String patient_name, String prescriptionName,String prescriptionDate,String prescriptionAmount,String prescriptionStatus) {
String userID = patient_name + get_prescriptionID();
String email = convert_email(patient_email);
mDatabase.child("User_Group").child(email).child("prescription").child(userID).child("name").setValue(prescriptionName);
mDatabase.child("User_Group").child(email).child("prescription").child(userID).child("date").setValue(prescriptionDate);
mDatabase.child("User_Group").child(email).child("prescription").child(userID).child("amount").setValue(prescriptionAmount);
mDatabase.child("User_Group").child(email).child("prescription").child(userID).child("status").setValue(prescriptionStatus);
}
public void edit_prescription(String patient_email, String data, String prescriptionID) {
mDatabase.child("User_Group").child(convert_email(patient_email)).child("prescription").child(prescriptionID).child("status").setValue(data);
}
public void edit_prescription(String patient_email, String prescriptionID,String prescriptionName,String prescriptionDate,String prescriptionAmount) {
mDatabase.child("User_Group").child(convert_email(patient_email)).child("prescription").child(prescriptionID).child("name").setValue(prescriptionName);
mDatabase.child("User_Group").child(convert_email(patient_email)).child("prescription").child(prescriptionID).child("date").setValue(prescriptionDate);
mDatabase.child("User_Group").child(convert_email(patient_email)).child("prescription").child(prescriptionID).child("amount").setValue(prescriptionAmount);
}
private String convert_email(String email) { return email.replace('.', '_'); }
public String get_prescriptionID()
{
Long n = System.currentTimeMillis();
return String.valueOf(n);
}
public String get_time()
{
SimpleDateFormat the_format = new SimpleDateFormat("dd-MM-yyyy");
String time_format = the_format.format(Calendar.getInstance().getTime());
return time_format;
}
//test code below do not touch
/*
//private int i = 0;
public void prepare_test_data()
{
testdata_timer();
}
private void testdata_timer()
{
firebase_timer = new CountDownTimer(10000,1000)
{
@Override
public void onTick(long l) { }
@Override
public void onFinish()
{
}
};
firebase_timer.start();
}
public void push_temp_medication()
{
createAccount("patient_99" + "@gmail.com", "123456", "john99", "12345678", "patient");
for (int i = 0; i < 10; i++)
{
//createAccount("patient_" + i + "@gmail.com", "123456", "john" + i, "12345678", "patient");
//createAccount("doctor" + i + "@gmail.com", "123456", "peter" + i, "12345678", "doctor");
//createAccount("pharmacist" + i + "@gmail.com", "123456", "wine" + i, "12345678", "pharmacist");
createAccount("admin" + i + "@<EMAIL>", "123456", "apple" + i, "12345678", "admin");
//add_prescription("<EMAIL>_" + i + <EMAIL>", "john" + i, "for covid", get_time(), "1", "In Progress");
}
}*/
}
<file_sep>/app/src/main/java/com/example/csit314/prescribe/PrescriptionActivity.java
package com.example.csit314.prescribe;
import android.os.Bundle;
import com.example.csit314.data.Firebase;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.google.android.material.snackbar.Snackbar;
import com.google.android.material.tabs.TabItem;
import com.google.android.material.tabs.TabLayout;
import androidx.viewpager.widget.ViewPager;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Parcelable;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.inputmethod.EditorInfo;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.StringRes;
import androidx.appcompat.app.AppCompatActivity;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProvider;
import com.example.csit314.R;
import com.example.csit314.databinding.ActivityLoginBinding;
import com.example.csit314.patientview.PatientActivity;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import com.example.csit314.prescribe.ui.main.SectionsPagerAdapter;
import com.example.csit314.databinding.ActivityPrescriptionBinding;
import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
public class PrescriptionActivity extends AppCompatActivity {
private ActivityPrescriptionBinding binding;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
binding = ActivityPrescriptionBinding.inflate(getLayoutInflater());
setContentView(binding.getRoot());
ArrayList<Prescription> prescriptionList = new ArrayList<Prescription>();
prescriptionList = (ArrayList<Prescription>) getIntent().getSerializableExtra("PrescriptionArrayList");
SectionsPagerAdapter sectionsPagerAdapter = new SectionsPagerAdapter(this, getSupportFragmentManager(),prescriptionList);
ViewPager viewPager = binding.viewPager;
viewPager.setAdapter(sectionsPagerAdapter);
TabLayout tabs = binding.tabs;
tabs.setupWithViewPager(viewPager);
//FloatingActionButton fab = binding.fab;
int defaultValue = 0;
int page = getIntent().getIntExtra("Two", defaultValue);
viewPager.setCurrentItem(page);
}
}<file_sep>/app/src/main/java/com/example/csit314/useradminview/UserAdminHelper.java
package com.example.csit314.useradminview;
public class UserAdminHelper {
private String name, number, user_group;
public UserAdminHelper() {
}
public UserAdminHelper(String name, String number, String user_group) {
this.name = name;
this.number = number;
this.user_group = user_group;
}
public UserAdminHelper(String name, String number) {
this.name = name;
this.number = number;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getNumber() {
return number;
}
public void setNumber(String number) {
this.number = number;
}
public String getUser_group() {
return user_group;
}
public void setUser_group(String user_group) {
this.user_group = user_group;
}
}
<file_sep>/app/src/main/java/com/example/csit314/doctorview/DoctorAddPrescriptionActivity.java
package com.example.csit314.doctorview;
import android.app.DatePickerDialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.text.InputType;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.NavUtils;
import com.example.csit314.R;
import com.example.csit314.data.Firebase;
import com.example.csit314.email.SendMail;
import com.example.csit314.patientview.Patient;
import com.example.csit314.prescribe.Prescription;
import java.io.File;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Map;
import androidmads.library.qrgenearator.QRGContents;
import androidmads.library.qrgenearator.QRGEncoder;
import androidmads.library.qrgenearator.QRGSaver;
public class DoctorAddPrescriptionActivity extends AppCompatActivity implements AdapterView.OnItemSelectedListener{
private Button updateBtn;
private DatePickerDialog.OnDateSetListener mDateSetListener;
private Spinner spinner_prescription_name;
private ArrayList<String> medications;
private String[] medicationsArray;
private TextView tv_patient_name;
private TextView tv_patient_number;
private TextView tv_patient_email;
private EditText et_prescription_date;
private EditText et_prescription_amount;
private EditText et_email_to;
private String emailto;
private String patient_name;
private String patient_number;
private String patient_email;
private String prescription_name;
private String prescription_date;
private String prescription_status;
private String prescription_id;
private String prescription_amount = "0";
private String user_password;
private String user_email;
Firebase the_firebase = new Firebase(this);
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.doctor_add_prescription);
//Initialize button
tv_patient_name = (TextView) findViewById(R.id.patient_add_name_doctorTextView);
tv_patient_number = (TextView) findViewById(R.id.patient_add_number_doctorTextView);
tv_patient_email = (TextView) findViewById(R.id.patient_add_email_doctorTextView);
et_prescription_date = (EditText) findViewById(R.id.prescription_add_date_editText);
et_prescription_amount = (EditText) findViewById(R.id.prescription_add_amount_editText);
spinner_prescription_name = (Spinner) findViewById(R.id.prescription_add_spinner);
et_email_to = (EditText) findViewById(R.id.email_to_editText);
//get Strings values
patient_name = (String) getIntent().getStringExtra("patientname");
patient_number = (String) getIntent().getStringExtra("patientnumber");
patient_email = (String) getIntent().getStringExtra("patientemail");
//Set Text
tv_patient_name.setText( patient_name);
tv_patient_number.setText(patient_number);
tv_patient_email.setText(patient_email);
et_prescription_date.setHint("Date");
et_prescription_amount.setHint("Amount : " + 0);
//Set Password
user_email = (String) getIntent().getStringExtra("email");
user_password = (String) getIntent().getStringExtra("password");
//MEDICATION Spinner
medications =(ArrayList<String>) getIntent().getStringArrayListExtra("medications");
medications = (ArrayList<String>) getIntent().getExtras().getStringArrayList("medications");
medicationsArray = medications.toArray(new String[medications.size()]);
prescription_name = medicationsArray[0];
updateBtn = (Button) findViewById(R.id.addBtn);
updateBtn.setEnabled(true);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(DoctorAddPrescriptionActivity.this,android.R.layout.simple_spinner_item,medicationsArray);
for(String s : medications)
{
Log.i("Medications", s);
}
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner_prescription_name.setAdapter(adapter);
spinner_prescription_name.setOnItemSelectedListener(this);
//Calendar button
et_prescription_date.setInputType(InputType.TYPE_NULL);
et_prescription_date.requestFocus();
et_prescription_date.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Calendar cal = Calendar.getInstance();
int year = cal.get(Calendar.YEAR);
int month = cal.get(Calendar.MONTH);
int day = cal.get(Calendar.DAY_OF_MONTH);
DatePickerDialog dialog = new DatePickerDialog(DoctorAddPrescriptionActivity.this,
android.R.style.Theme_Holo_Light_Dialog_MinWidth,
mDateSetListener,
year,month,day);
dialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
dialog.show();
}
});
mDateSetListener = new DatePickerDialog.OnDateSetListener() {
@Override
public void onDateSet(DatePicker datePicker, int year, int month, int day) {
month = month+1;
String date = String.valueOf(day) + "-" + String.valueOf(month) + "-" + String.valueOf(year);
et_prescription_date.setText(date);
}
};
}
public void addOnClick(View view) {
addPrescription();
}
private void launchDoctorViewPatientActivity() {
Intent intent = new Intent(this, DoctorViewPatientActivity.class);
ArrayList<Patient> patientAlist;
Map p = the_firebase.searchUserGroup();
patientAlist = collectUserAndPrescription(p);
intent.putParcelableArrayListExtra("DoctorArrayList",patientAlist);
intent.putStringArrayListExtra("medications",medications);
intent.putExtra("email",user_email);
intent.putExtra("password",<PASSWORD>);
finish();
startActivity(intent);
}
public void sendEmail() {
String mEmail = emailto;
String mSubject = "Prescription Added";
String mMessage = "Hi " + patient_name + ",<br><br>Your Prescription has been added by our doctor." +
"<br>To view the prescription kindly login to our app.<br> Kindly go to the located pharmacy to scan the QR Code, to recieve your prescription." ;
Bitmap bitmap = generateQR();
String url = saveImageToExternalStorage(bitmap);
scanMedia(url);
SendMail sendMail = new SendMail(this,mEmail,mSubject,mMessage,url);
sendMail.execute();
//Toast.makeText(getApplicationContext(), "Sending Mail", Toast.LENGTH_LONG).show();
}
public Bitmap generateQR()
{
Bitmap bitmap;
QRGEncoder qrgEncoder;
qrgEncoder = new QRGEncoder(the_firebase.generateRandomstring(69), null, QRGContents.Type.TEXT,200);
qrgEncoder.setColorBlack(Color.BLACK);
qrgEncoder.setColorWhite(Color.WHITE);
bitmap = qrgEncoder.getBitmap();
return bitmap;
}
public static String saveImageToExternalStorage(Bitmap finalBitmap) {
QRGSaver qrgSaver = new QRGSaver();
File direct = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/Pictures");
if (direct.exists ()) direct.delete ();
try{
qrgSaver.save(direct.getAbsolutePath(), "qrcode", finalBitmap, QRGContents.ImageType.IMAGE_JPEG);
}
catch(Exception e)
{
e.printStackTrace();
}
return direct.getAbsolutePath() + "qrcode" + ".jpg";
}
private void scanMedia(String path) {
File file = new File(path);
Uri uri = Uri.fromFile(file);
Intent scanFileIntent = new Intent(
Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, uri);
sendBroadcast(scanFileIntent);
}
private void addPrescription() {
prescription_status = "In Progress";
if(et_prescription_date.getText().toString().equals(""))
Toast.makeText(getApplicationContext(), "Date is Empty, Try again.", Toast.LENGTH_LONG).show();
if(et_prescription_amount.getText().toString().equals("") || !et_prescription_amount.getText().toString().equals("0"))
Toast.makeText(getApplicationContext(), "Amount is Empty, Try again.", Toast.LENGTH_LONG).show();
if(et_email_to.getText().toString().toLowerCase().equals(""))
Toast.makeText(getApplicationContext(), "Email is Empty, Try again.", Toast.LENGTH_LONG).show();
else {
emailto = et_email_to.getText().toString();
prescription_amount = et_prescription_amount.getText().toString();
prescription_date = et_prescription_date.getText().toString();
the_firebase.add_prescription(patient_email, patient_name, prescription_name, prescription_date, prescription_amount, prescription_status);
Toast.makeText(getApplicationContext(), "Added Prescription, Sending Email...", Toast.LENGTH_LONG).show();
sendEmail();
updateBtn.setEnabled(false);
launchDoctorViewPatientActivity();
}
}
protected void onStart()
{
super.onStart();
the_firebase.signIn(user_email,user_password);
}
public ArrayList<Prescription> collectPrescription(Map<String,Object> p)
{
ArrayList<Prescription> prescriptionAlist = new ArrayList<>();
String id;
String name;
Long amount;
String status;
String date;
if(p != null)
{
for (Map.Entry<String, Object> entry : p.entrySet()) {
Map singlePrescription = (Map) entry.getValue();
id = (String) entry.getKey();
name = (String) singlePrescription.get("name");
status = (String) singlePrescription.get("status");
date = (String) singlePrescription.get("date");
if (singlePrescription.get("amount") instanceof String)
amount = Long.parseLong((String) "0");
else
amount = (Long) singlePrescription.get("amount");
if(entry.getKey().equals(prescription_id)){
name = prescription_name;
date = prescription_date;
amount = Long.parseLong(prescription_amount);
status = prescription_status;
}
prescriptionAlist.add(new Prescription(id,name, date, String.valueOf(amount), status));
}
}
return prescriptionAlist;
}
public ArrayList<Patient> collectUserAndPrescription(Map<String,Object> patient)
{
ArrayList<Patient> patientAlist = new ArrayList<>();
String name;
String email;
String number;
String user_type;
try {
for (Map.Entry<String, Object> entry : patient.entrySet()) {
Map singleUser = (Map) entry.getValue();
user_type = (String) singleUser.get("user_type");
name = (String) singleUser.get("name");
email = entry.getKey().replace("_com", ".com");
number = (String) singleUser.get("number");
if (user_type.toLowerCase().equals("patient"))
patientAlist.add(new Patient(name, number, email, collectPrescription(the_firebase.get_pastprescriptionObject(email))));
}
}catch(Exception e)
{
e.printStackTrace();
}
return patientAlist;
}
@Override
public void onBackPressed() {
NavUtils.navigateUpFromSameTask(this);
}
@Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
prescription_name = medicationsArray[i];
}
@Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
}
<file_sep>/app/src/test/java/com/example/csit314/useradminview/UserAdminHelperTest.java
package com.example.csit314.useradminview;
/*import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;*/
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
@RunWith(JUnit4.class)
public class UserAdminHelperTest {
@Test
public void getParam() {
UserAdminHelper helper = new UserAdminHelper("name", "+999", "admin");
Assert.assertEquals("name", helper.getName());
Assert.assertEquals("+999", helper.getNumber());
Assert.assertEquals("admin", helper.getUser_group());
}
}<file_sep>/app/src/main/java/com/example/csit314/prescribe/ui/main/PastPrescriptionFragment.java
package com.example.csit314.prescribe.ui.main;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.example.csit314.R;
import com.example.csit314.data.Firebase;
import com.example.csit314.prescribe.Prescription;
import com.example.csit314.prescribe.PrescriptionActivity;
import com.example.csit314.prescribe.pastPrescriptionRecyclerViewAdapter;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.database.DatabaseReference;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import androidx.annotation.NonNull;
import org.w3c.dom.Text;
public class PastPrescriptionFragment extends Fragment{
View v;
private List<Prescription> listPrescription;
pastPrescriptionRecyclerViewAdapter recyclerAdapter;
public PastPrescriptionFragment()
{
}
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState)
{
v = inflater.inflate(R.layout.fragment1_layout,container,false);
RecyclerView recyclerview = (RecyclerView) v.findViewById(R.id.fragment1_recyclerview);
EditText editText = v.findViewById(R.id.edittext);
editText.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
@Override
public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
@Override
public void afterTextChanged(Editable editable) {
filter(editable.toString());
}
});
recyclerAdapter = new pastPrescriptionRecyclerViewAdapter(getActivity(),listPrescription);
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getContext());
recyclerview.setLayoutManager(linearLayoutManager);
recyclerview.setAdapter(recyclerAdapter);
return v;
}
private void filter(String text)
{
ArrayList<Prescription> filteredList = new ArrayList<>();
for (Prescription p : listPrescription) {
try {
if (p.getpName().toLowerCase().contains(text.toLowerCase())
|| p.getpStatus().toLowerCase().contains(text.toLowerCase())
|| p.getpDate().toLowerCase().contains(text.toLowerCase())
|| p.getpAmount().toLowerCase().contains(text.toLowerCase())) {
filteredList.add(p);
}
}catch(Exception e)
{
e.printStackTrace();
}
}
recyclerAdapter.filterList(filteredList);
}
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
listPrescription = new ArrayList<Prescription>();
ArrayList<Prescription> allPrescriptionAList = new ArrayList<Prescription>();
allPrescriptionAList = getArguments().getParcelableArrayList("PrescriptionArrayList");
for(Prescription p : allPrescriptionAList)
{
if(p.getpStatus().toLowerCase().equals("completed"))
listPrescription.add(p);
}
}
}
<file_sep>/app/src/main/java/com/example/csit314/ui/login/theLoginActivity.java
package com.example.csit314.ui.login;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.util.Patterns;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import com.example.csit314.R;
import com.example.csit314.data.Firebase;
import com.example.csit314.databinding.ActivityLoginBinding;
import com.example.csit314.doctorview.DoctorActivity;
import com.example.csit314.patientview.Patient;
import com.example.csit314.pharmacyview.PharmacyActivity;
import com.example.csit314.prescribe.Prescription;
import com.example.csit314.patientview.PatientActivity;
import com.example.csit314.useradminview.UserAdminActivity;
import java.util.ArrayList;
import java.util.Map;
public class theLoginActivity extends AppCompatActivity
{
private ActivityLoginBinding theLogin;
Firebase the_firebase = new Firebase(this);
private String user_Email, user_Password;
private CountDownTimer login_timer;
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
theLogin = ActivityLoginBinding.inflate(getLayoutInflater());
final EditText the_Email = findViewById(R.id.username);
final EditText the_Password = findViewById(R.id.password);
final Button loginButton = findViewById(R.id.Login);
the_firebase.signout();
//the_firebase.push_temp_medication();
loginButton.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View v)
{
user_Email = the_Email.getText().toString();
user_Password = the_Password.getText().toString();
if(user_Email.isEmpty() || user_Password.isEmpty())
{
the_Email.setError("Please enter a valid email and password");
the_Email.requestFocus();
return;
}
else if(!Patterns.EMAIL_ADDRESS.matcher(user_Email).matches())
{
the_Email.setError("Please enter a valid email");
the_Email.requestFocus();
return;
}
else if(user_Password.length() < 6)
{
the_Password.setError("Please enter > 6 characters");
the_Password.requestFocus();
return;
}
else
{
//the_firebase.prepare_test_data();
//the_firebase.push_temp_medication();
//the_firebase.signIn("<EMAIL>", "123456");
the_firebase.signIn(user_Email,user_Password);
login_now();
}
}
});
}
public void login_now()
{
login_timer = new CountDownTimer(100,100)
{
@Override
public void onTick(long l) { }
@Override
public void onFinish()
{
if(the_firebase.is_database_ready())
{
if(the_firebase.getThe_userType().equals("admin"))
launchUserAdminActivity();
else if(the_firebase.getThe_userType().equals("doctor"))
launchDoctorActivity();
else if(the_firebase.getThe_userType().equals("pharmacist"))
launchPharmacyActivity();
else
launchPatientActivity();
}
}
};
login_timer.start();
}
public void launchUserAdminActivity() //launch to UserAdminActivity
{
Intent i = new Intent(this, UserAdminActivity.class);
startActivity(i);
}
public void launchPatientActivity() //launch to PatientActivity
{
Intent i = new Intent(this, PatientActivity.class);
Map p = the_firebase.get_pastprescriptionObject(user_Email);
ArrayList<Prescription> prescriptionAList = new ArrayList<>();
if(p != null)
{
prescriptionAList = collectPrescription(p);
}
i.putParcelableArrayListExtra("PrescriptionArrayList", prescriptionAList);
startActivity(i);
}
public void launchDoctorActivity() //launch to DoctorActivity
{
Intent i = new Intent(this, DoctorActivity.class);
ArrayList<Patient> patientAlist;
Map p = the_firebase.searchUserGroup();
patientAlist = collectUserAndPrescription(p);
ArrayList<String> medAlist = new ArrayList<>();
medAlist = collectMedication();
i.putParcelableArrayListExtra("DoctorArrayList", patientAlist);
i.putStringArrayListExtra("medications",medAlist);
i.putExtra("email",user_Email);
i.putExtra("password",<PASSWORD>);
startActivity(i);
}
public void launchPharmacyActivity() //launch to PharmacyActivity
{
Intent i = new Intent(this, PharmacyActivity.class);
ArrayList<Patient> patientAlist;
Map p = the_firebase.searchUserGroup();
patientAlist = collectUserAndPrescription(p);
i.putParcelableArrayListExtra("PatientArrayList", patientAlist);
i.putExtra("email",user_Email);
i.putExtra("password",<PASSWORD>);
startActivity(i);
}
public ArrayList<Prescription> collectPrescription(Map<String,Object> p)
{
ArrayList<Prescription> prescriptionAlist = new ArrayList<>();
String id;
String name;
Long amount;
String status;
String date;
if(p != null)
{
for (Map.Entry<String, Object> entry : p.entrySet()) {
Map singlePrescription = (Map) entry.getValue();
id = (String) entry.getKey();
name = (String) singlePrescription.get("name");
status = (String) singlePrescription.get("status");
date = (String) singlePrescription.get("date");
if (singlePrescription.get("amount") instanceof String)
amount = Long.parseLong((String) "0");
else
amount = (Long) singlePrescription.get("amount");
prescriptionAlist.add(new Prescription(id,name, date, String.valueOf(amount), status));
}
}
return prescriptionAlist;
}
public ArrayList<Patient> collectUserAndPrescription(Map<String,Object> patient)
{
ArrayList<Patient> patientAlist = new ArrayList<>();
String name;
String email;
String number;
String user_type;
try {
for (Map.Entry<String, Object> entry : patient.entrySet()) {
Map singleUser = (Map) entry.getValue();
user_type = (String) singleUser.get("user_type");
name = (String) singleUser.get("name");
email = entry.getKey().replace("_com", ".com");
number = (String) singleUser.get("number");
if (user_type.toLowerCase().equals("patient"))
patientAlist.add(new Patient(name, number, email, collectPrescription(the_firebase.get_pastprescriptionObject(email))));
}
}catch(Exception e)
{
e.printStackTrace();
}
return patientAlist;
}
public ArrayList<String> collectMedication()
{
Map<String,String> medication = the_firebase.get_medication();
ArrayList<String> medAlist = new ArrayList<>();
String name;
for (Map.Entry<String,String> entry: medication.entrySet())
{
medAlist.add(entry.getValue());
}
return medAlist;
}
} | a74ce013218b705a9de36c0b58db18f668e2666a | [
"Java"
] | 19 | Java | thunderblader/CSIT314 | b44fc510197941073a298cb948054b7977675541 | 7f930fbcb5363f4e18563e8551f86424dedcc861 |
refs/heads/master | <file_sep>#--
# Copyright (c) 2013 RightScale, Inc.
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# 'Software'), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
# IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
# CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
# SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#++
describe "Utils" do
context "RightScale::CloudApi::Utils" do
context "self.url_encode" do
it "uses CGI::escape to escape" do
str = 'hahaha'
expect(CGI).to receive(:escape).once.and_return(str)
RightScale::CloudApi::Utils.url_encode(str)
end
it "replaces spaces with '%20'" do
expect(RightScale::CloudApi::Utils.url_encode('ha ha ha')).to eq 'ha%20ha%20ha'
end
end
context "self.params_to_urn" do
it "converts a Hash into a string" do
expect(RightScale::CloudApi::Utils.params_to_urn('a' => 'b', 'c' => '', 'd' => nil)).to eq 'a=b&c=&d'
end
it "auto escapes values" do
expect(RightScale::CloudApi::Utils.params_to_urn('a' => 'ha ha')).to eq 'a=ha%20%20ha'
end
it "uses a provided block to escape values" do
expect(RightScale::CloudApi::Utils.params_to_urn('a' => 'ha ha'){|val| val.gsub(' ','-') }).to eq 'a=ha--ha'
end
end
context "self.join_urn" do
it "joins pathes" do
expect(RightScale::CloudApi::Utils.join_urn('/first', 'second', 'third')).to eq '/first/second/third'
end
it "knows how to deal with empty pathes or slashes" do
expect(RightScale::CloudApi::Utils.join_urn('/first', '', '1/', '1.1/', 'second', 'third')).to eq '/first/1/1.1/second/third'
end
it "drops strips left when it sees a path starting with forward slash (root sign)" do
expect(RightScale::CloudApi::Utils.join_urn('/first', '', '1/', '1.1/', '/second', 'third')).to eq '/second/third'
end
it "adds URL params" do
expect(RightScale::CloudApi::Utils.join_urn('/first','second', {'a' => 'b', 'c' => '', 'd' => nil})).to eq "/first/second?a=b&c=&d"
end
context "self.extract_url_params" do
end
context "self.pattern_matches?" do
it "returns a blank Hash when there are no any params in the provided URL" do
expect(RightScale::CloudApi::Utils.extract_url_params('https://ec2.amazonaws.com')).to eq({})
end
it "returns parsed URL params when they are in the provided URL" do
expect(RightScale::CloudApi::Utils.extract_url_params('https://ec2.amazonaws.com/?w=1&x=3&y&z')).to eq(
{"z"=>nil, "y"=>nil, "x"=>"3", "w"=>"1"}
)
end
end
context "self.contentify_body" do
before(:each) do
@body = { '1' => '2' }
end
it "returns JSON when content type says it should be json" do
expect(RightScale::CloudApi::Utils.contentify_body(@body,'json')).to eq '{"1":"2"}'
end
it "returns XML when content type says it should be json" do
expect(RightScale::CloudApi::Utils.contentify_body(@body,'xml')).to eq "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<1>2</1>"
end
it "fails if there is an unsupported content-type" do
expect { RightScale::CloudApi::Utils.contentify_body(@body,'unsupported-smething') }.to raise_error(RightScale::CloudApi::Error)
end
end
context "self.generate_token" do
context "UUID" do
before(:each) do
@expectation = 'something-random-from-UUID.generate'
UUID = double('UUID', :new => double(:generate => @expectation))
end
it "uses UUID when UUID is loaded" do
RightScale::CloudApi::Utils.generate_token == @expectation
end
end
context "self.random" do
before(:each) do
@expectation = 'something-random-from-self.random'
UUID = double('UUID', :new => double(:generate => @expectation))
expect(UUID).to receive(:respond_to?).with(:new).and_return(false)
end
it "uses self.random when UUID is not loaded" do
expect(RightScale::CloudApi::Utils).to receive(:random).and_return(@expectation)
RightScale::CloudApi::Utils.generate_token == @expectation
end
end
end
context "self.random" do
it "generates a single random HEX digit by default" do
expect(RightScale::CloudApi::Utils.random[/^[0-9a-f]{1}$/]).to_not be(nil)
end
it "generates 'size' random HEX digits when size is set" do
expect(RightScale::CloudApi::Utils.random(13)[/^[0-9a-f]{13}$/]).to_not be(nil)
end
it "generates random decimal digits when :base is 10" do
expect(RightScale::CloudApi::Utils.random(13, :base => 10)[/^[0-9]{13}$/]).to_not be(nil)
end
it "generates random alpha symbols when :base is 26 and :offset is 10" do
expect(RightScale::CloudApi::Utils.random(13, :base => 26, :offset => 10)[/^[a-z]{13}$/]).to_not be(nil)
end
end
context "self.arrayify" do
it "does not change Array instances" do
expect(RightScale::CloudApi::Utils.arrayify([])).to eq []
expect(RightScale::CloudApi::Utils.arrayify([1,2,3])).to eq([1,2,3])
end
it "wraps all the other objects into Array" do
expect(RightScale::CloudApi::Utils.arrayify(nil)).to eq [nil]
expect(RightScale::CloudApi::Utils.arrayify(1)).to eq [1]
expect(RightScale::CloudApi::Utils.arrayify('something')).to eq ['something']
expect(RightScale::CloudApi::Utils.arrayify({1=>2})).to eq( [{1=>2}])
end
end
context "self.dearrayify" do
it "returns input if the input is not an Array instance" do
expect(RightScale::CloudApi::Utils.dearrayify(nil)).to be(nil)
expect(RightScale::CloudApi::Utils.dearrayify(1)).to eq 1
expect(RightScale::CloudApi::Utils.dearrayify('something')).to eq 'something'
expect(RightScale::CloudApi::Utils.dearrayify({1=>2})).to eq({1=>2})
end
it "returns the first element of the input if the input is an Array instance" do
expect(RightScale::CloudApi::Utils.dearrayify([])).to be(nil)
expect(RightScale::CloudApi::Utils.dearrayify([1])).to eq 1
expect(RightScale::CloudApi::Utils.dearrayify([1,2,3])).to eq 1
end
end
context "self.get_xml_parser_class" do
it "returns RightScale::CloudApiParser::Sax by default" do
expect(RightScale::CloudApi::Utils.get_xml_parser_class(nil)).to eq RightScale::CloudApi::Parser::Sax
end
it "returns RightScale::CloudApiParser::Sax by its name" do
expect(RightScale::CloudApi::Utils.get_xml_parser_class('sax')).to eq RightScale::CloudApi::Parser::Sax
end
it "returns RightScale::CloudApiParser::ReXml by its name" do
expect(RightScale::CloudApi::Utils.get_xml_parser_class('rexml')).to eq RightScale::CloudApi::Parser::ReXml
end
it "fails when an unknown parser is requested" do
expect { RightScale::CloudApi::Utils.get_xml_parser_class('something-unknown') }.to raise_error(RightScale::CloudApi::Error)
end
end
context "self.inheritance_chain" do
end
end
end
end<file_sep>
# RightCloudApi shared library
This is a Ruby gem that provides common code to all RightScale cloud libraries. It is required by the respective cloud library gems. See https://github.com/rightscale/right_aws_api for example.
### Tests
```
bundle install
bundle exec rake spec
```
### (c) 2014 by RightScale, Inc., see the LICENSE file for the open-source license.
## Using Docker
To run the tests locally, install Docker and Docker-compose and run `docker-compose up`, it will take care of building the docker image and running the rspec specs.
<file_sep>#--
# Copyright (c) 2013 RightScale, Inc.
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# 'Software'), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
# IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
# CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
# SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#++
module RightScale
module CloudApi
# HTTP Headers container.
#
# @api public
#
# The class makes it so that the headers always point to an array or values. It is a wrapper
# around Hash class where all the keys are always arrays.
#
class HTTPHeaders < BlankSlate
# Initializer
#
# @param [Hash] headers A set of HTTP headers where keys are the headers names and the values
# are the headers values.
#
# @example
# # no example
#
def initialize(headers={})
@headers = normalize(headers)
end
# Retrieves the given headers values by the header name
#
# @param [String] header The header name.
# @return [Array] The arrays of value(s).
#
# @example
# request[:agent] #=> ['something']
#
def [](header)
@headers[normalize_header(header)] || []
end
# Sets a header
#
# @param [String] header The header name.
# @param [String,Array] value The new value(s).
# @return [void]
#
# @example
# # Add a header
# request[:agent] = 'something'
# # Remove a header
# request[:agent] = nil
#
def []=(header, value)
value = normalize_value(value)
if value.nil?
delete(header)
else
@headers[normalize_header(header)] = value
end
end
# Deletes the given header
#
# @param [String] header The header name.
# @return [void]
#
# @example
# # Delete the header
# request.delete(:agent)
#
def delete(header)
@headers.delete(normalize_header(header))
end
# Merges the new headers into the existent list
#
# @param [Hash] headers The new headers.
#
# @return [Hash] A new hash containing the result.
#
# @example
# # Delete the header
# request.merge(:agent => 'foobar')
#
def merge(headers)
@headers.merge(normalize(headers))
end
# Merges the new headers into the current hash
#
# @param [Hash] headers The new headers.
#
# @return [Hash] Updates the current object and returns the resulting hash.
#
# @example
# # Delete the header
# request.merge!(:agent => 'foobar')
#
def merge!(headers)
@headers.merge!(normalize(headers))
end
# Set the given header unless it is set
#
# If the curent headers list already has any value for the given header the method does nothing.
#
# @param [String] header The header name.
# @param [String,Array] value The values to initialize the header with.
# @return [void]
#
# @example
# request.set_if_blank(:agent, 'something')
#
def set_if_blank(header, value)
self[header] = value if self[header].first._blank?
end
# Returns a new Hash instance with all the current headers
#
# @return [Hash] A new Hash with the headers.
#
# @example
# request.to_hash #=> A hash with headers
#
def to_hash
@headers.dup
end
# Displays the headers in a nice way
#
# @return [String] return_description
#
# @example
# ec2.response.headers.to_s #=>
# 'content-type: "text/xml;charset=UTF-8", server: "AmazonEC2", something: ["a", "b"]'
#
def to_s
@headers.to_a.map { |header, value| "#{header}: #{(value.size == 1 ? value.first : value).inspect}" } * ', '
end
# Feeds all the unknown methods to the underlaying hash object
#
# @return [Object]
# @example
# # no example
#
def method_missing(method_name, *args, &block)
@headers.__send__(method_name, *args, &block)
end
# Makes it so that a header is always a down cased String instance
#
# @api private
#
# @param [String,Symbol] header The header name.
# @return [String] The normalized header name.
# @example
# normalize_header(:Name) #=> 'name'
#
def normalize_header(header)
header.to_s.downcase
end
private :normalize_header
# Wraps the given value(s) into Array
#
# @api private
#
# @param [Array] value The original values.
# @return [String] The arrayified values or nil.
#
# @example
# normalize_header(nil) #=> nil
# normalize_header('a') #=> ['a']
# normalize_header(['a', 'b']) #=> ['a', 'b']
#
def normalize_value(value)
value.nil? ? nil : Utils::arrayify(value)
end
private :normalize_value
# Normalizes the given headers
#
# @api private
#
# The method makes it so that all the keys are downcased String instances and all
# the values are Arrays.
#
# @param [Hash] headers A hash of headers.
#
# @return [Hash] Returns a new hash with normilized keys and values.
#
# @example
# normalize(:Name => 'a') #=> {'name' => ['a']}
#
def normalize(headers)
result = {}
headers.each do |header, value|
header, value = normalize_header(header), normalize_value(value)
result[header] = value unless value.nil?
end
result
end
private :normalize
end
end
end<file_sep>#--
# Copyright (c) 2013 RightScale, Inc.
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# 'Software'), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
# IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
# CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
# SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#++
module RightScale
module CloudApi
# The routine provides *error_pattern* method that is used to define request and response patterns.
#
# The patterns allows one to control the request processing flow: you can enable retries for
# certain API calls or can re-open a connection on HTTP failure.
#
# The supported actions are:
#
# Request option:
# - :abort_on_timeout - If there was a low level timeout then it should not retry a request
# but should fail. Lets say one made a call to launch some instance and the remote cloud
# launched them but timed out to respond back. The default behavior for the gem is to make
# a retry if a timeout received but in this particular case it will launch the instances
# again. So the solution here is to make the system to fail after the first unsuccessfull
# request.
#
# Response options:
# - :retry - Make a retry if the failed response matches to the pattern.
# - :abort - Do not make a retry and fail if the response matches to the pattern (opposite to :retry).
# - :disconnect_and_abort - Close a connection and fail.
# - :reconnect_and_retry - Reestablish a connection and make a retry.
#
class RequestAnalyzer < Routine
class Error < CloudApi::Error
end
REQUEST_ACTIONS = [ :abort_on_timeout ]
REQUEST_KEYS = [ :verb, :verb!, :path, :path!, :request, :request!, :if ]
RESPONSE_ACTIONS = [ :disconnect_and_abort, :abort, :reconnect_and_retry, :retry ]
RESPONSE_KEYS = [ :verb, :verb!, :path, :path!, :request, :request!, :code, :code!, :response, :response!, :if ]
ALL_ACTIONS = REQUEST_ACTIONS + RESPONSE_ACTIONS
module ClassMethods
def self.extended(base)
unless base.respond_to?(:options) && base.options.is_a?(Hash)
fail Error::new("RequestAnalyzer routine assumes class being extended responds to :options and returns a hash")
end
end
# Adds a new error pattern.
# Patterns are analyzed in order of their definition. If one pattern hits the rest are not analyzed.
#
# @param [Symbol] action The requested action.
# @param [Hash] error_pattern The requested pattern (see {file:lib/base/helper/utils.rb self.pattern_matches?}).
#
# @xample:
# error_pattern :abort_on_timeout, :path => /Action=(Run|Create)/
# error_pattern :retry, :response => /InternalError|Internal Server Error|internal service error/i
# error_pattern :disconnect_and_abort, :code => /5..|403|408/
# error_pattern :disconnect_and_abort, :code => /4../, :if => Proc.new{ |opts| rand(100) < 10 }
#
# @raise [RightScale::CloudApi::RequestAnalyzer::Error] If error_pattern is not a Hash instance.
# @raise [RightScale::CloudApi::RequestAnalyzer::Error] If action is not supported.
# @raise [RightScale::CloudApi::RequestAnalyzer::Error] If pattern keys are weird.
#
def error_pattern(action, error_pattern)
action = action.to_sym
fail Error::new("Patterns are not set for action #{action.inspect}") if !error_pattern.is_a?(Hash) || error_pattern._blank?
fail Error::new("Unsupported action #{action.inspect} for error pattern #{error_pattern.inspect}") unless ALL_ACTIONS.include?(action)
unsupported_keys = REQUEST_ACTIONS.include?(action) ? error_pattern.keys - REQUEST_KEYS : error_pattern.keys - RESPONSE_KEYS
fail Error::new("Unsupported keys #{unsupported_keys.inspect} for #{action.inspect} in error pattern #{error_pattern.inspect}") unless unsupported_keys._blank?
(options[:error_patterns] ||= []) << error_pattern.merge(:action => action)
end
end
# The main entry point.
#
def process
# Get a list of accessible error patterns
error_patterns = data[:options][:error_patterns] || []
opts = { :request => data[:request][:instance],
:response => nil,
:verb => data[:request][:verb],
:params => data[:request][:orig_params].dup}
# Walk through all the error patterns and find the first that matches.
# RequestAnalyser accepts only REQUEST_ACTIONS (actually "abort_on_timeout" only)
request_error_patterns = error_patterns.select{|e| REQUEST_ACTIONS.include?(e[:action])}
request_error_patterns.each do |pattern|
# If we see any pattern that matches our current state
if Utils::pattern_matches?(pattern, opts)
# then set a flag to disable retries
data[:options][:abort_on_timeout] = true
cloud_api_logger.log("Request matches to error pattern: #{pattern.inspect}" , :request_analyzer)
break
end
end
end
end
end
end
<file_sep>#--
# Copyright (c) 2013 RightScale, Inc.
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# 'Software'), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
# IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
# CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
# SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#++
module RightScale
module CloudApi
# The routine is responsible for retries/reiterations.
#
# If retries are enabled then a singe API call may perform upto DEFAULT_RETRY_COUNT request
# attempts who may take upto DEFAULT_REITERATION_TIME secsons.
#
class RetryManager < Routine
class Error < CloudApi::HttpError
end
DEFAULT_RETRY_COUNT = 2
DEFAULT_REITERATION_TIME = 10
DEFAULT_SLEEP_TIME = 1.0
# Retries manager.
#
# The manager usually takes the very first position in routines chain.
# It just increments its counters if we did not reach a possible count of retries or
# complains if there are no attempts left or if API request time is over.
#
# There are 2 possible reasons for a retry to be performed:
# 1. There was a redirect request (HTTP 3xx code)
# 2. There was an error (HTTP 5xx, 4xx) and
#
# Adding strategies [ :full_jitter, :equal_jitter, :decorrelated_jitter]
# see http://www.awsarchitectureblog.com/2015/03/backoff.html for details
def process
retry_options = @data[:options][:retry] || {}
retry_strategy = retry_options[:strategy] # nil or garbage is acceptable
max_retry_count = retry_options[:count] || DEFAULT_RETRY_COUNT
reiteration_time = retry_options[:reiteration_time] || DEFAULT_REITERATION_TIME
base_sleep_time = retry_options[:sleep_time] || DEFAULT_SLEEP_TIME
# Initialize things on the first run for the current request.
@data[:vars][:retry] ||= {}
@data[:vars][:retry][:count] ||= -1
@data[:vars][:retry][:count] += 1 # Increment retry attempts count
@data[:vars][:retry][:orig_body_stream_pos] ||= @data[:request][:body].is_a?(IO) && @data[:request][:body].pos
attempt = @data[:vars][:retry][:count]
# Complain on any issue
if max_retry_count < attempt
error_message = "RetryManager: No more retries left."
elsif Time.now > @data[:vars][:system][:started_at] + reiteration_time
error_message = "RetryManager: Retry timeout of #{reiteration_time} seconds has been reached."
end
# Raise exception if request runs out-of-time or attempts.
if error_message
http_data = @data[:vars][:retry][:http]
http_code = http_data && http_data[:code]
http_message = http_data && http_data[:message]
error_message = "#{http_message}\n#{error_message}" if http_message
raise Error::new(http_code, error_message)
end
# Continue (with a delay when needed)
if attempt > 0 #only sleep on a retry
previous_sleep = @data[:vars][:retry][:previous_sleep_time] || base_sleep_time
sleep_time = case retry_strategy
when :full_jitter
#sleep = random_between(0, base * 2 ** attempt)
rand * (base_sleep_time * 2**(attempt-1))
when :equal_jitter
# sleep = temp / 2 + random_between(0, temp / 2)
temp = base_sleep_time * 2 **(attempt-1)
temp / 2 + rand * (temp / 2)
when :decorrelated_jitter
# sleep = random_between(base, previous_sleep * 3)
rand * (3*previous_sleep - base_sleep_time) + base_sleep_time
when :retry_after
Array((@data[:response][:instance].headers || {})["Retry-After"]).first.to_i
else # default behavior, exponential
base_sleep_time * 2**(attempt-1)
end
@data[:vars][:retry][:previous_sleep_time] = sleep_time
cloud_api_logger.log("Sleeping for #{sleep_time} seconds before retry attempt ##{attempt}", :retry_manager)
sleep(sleep_time)
end
# Restore file pointer in IO body case.
if @data[:request][:instance] &&
@data[:request][:instance].is_io? &&
@data[:request][:instance].body.respond_to?('pos') &&
@data[:request][:instance].body.respond_to?('pos=') &&
@data[:request][:instance].body.pos != @data[:vars][:retry][:orig_body_stream_pos]
cloud_api_logger.log("Restoring file position to #{@data[:vars][:retry][:orig_body_stream_pos]}", :retry_manager)
@data[:request][:instance].body.pos = @data[:vars][:retry][:orig_body_stream_pos]
end
#request params can be removed by another manager, restore them in case this happens, looking at you AWS request signer
@data[:request][:params] = @data[:request][:orig_params]
end
end
end
end
<file_sep>#--
# Copyright (c) 2013 RightScale, Inc.
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# 'Software'), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
# IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
# CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
# SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#++
module RightScale
module CloudApi
# This routine generifies all HTTP requests so that the main code does not need to worry about
# the underlaying libraries (right_http_connection or persistent_connection).
#
class ConnectionProxy < Routine
class Error < CloudApi::Error
end
# Main entry point.
#
# Performs an HTTP request.
#
def process
unless @connection_proxy
# Try to use a user defined connection proxy. The options are:
# - RightScale::CloudApi::ConnectionProxy::NetHttpPersistentProxy
connection_proxy_class = data[:options][:connection_proxy]
unless connection_proxy_class
# If it is not defined then load right_http_connection gem and use it.
connection_proxy_class = RightScale::CloudApi::ConnectionProxy::NetHttpPersistentProxy
end
@connection_proxy = connection_proxy_class.new
end
# Register a call back to close current connection
data[:callbacks][:close_current_connection] = Proc::new do |reason|
@connection_proxy.close_connection(nil, reason)
cloud_api_logger.log("Current connection closed: #{reason}", :connection_proxy)
end
# Make a request.
with_timer('HTTP request', :connection_proxy) do
@connection_proxy.request(data)
end
end
end
end
end<file_sep>#--
# Copyright (c) 2013 RightScale, Inc.
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# 'Software'), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
# IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
# CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
# SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#++
module RightScale
module CloudApi
# The Routine adds metadata to the result.
#
# @example:
# response = ec2.DescribeSecurityGroups #=> A list of SecurityGroups
# response.metadata #=>
# {:headers=>
# {"content-type"=>["text/xml;charset=UTF-8"],
# "transfer-encoding"=>["chunked"],
# "date"=>["Fri, 22 Feb 2013 00:02:43 GMT"],
# "server"=>["AmazonEC2"]},
# :code=>"200",
# :cache=>
# {:key=>"DescribeSecurityGroups",
# :record=>
# {:timestamp=>2013-02-22 00:02:44 UTC,
# :md5=>"0e3e12e1c18237d9f9510e90e7b8950e",
# :hits=>0}}}
#
class ResultWrapper < Routine
class Result < BlankSlate
attr_reader :metadata
def initialize(response, metadata)
@response = response
@metadata = metadata
end
# Feed all the missing methods to the original object.
def method_missing(method, *params, &block)
@response.send(method, *params, &block)
end
end
# Main entry point.
#
def process
cache = data._at(:vars, :cache, :default => nil)
metadata = {}
metadata[:headers] = data[:response][:instance].headers
metadata[:code] = data[:response][:instance].code
metadata[:cache] = cache if cache
#
data[:result] = Result::new(data[:result], metadata)
end
end
end
end<file_sep>#--
# Copyright (c) 2013 RightScale, Inc.
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# 'Software'), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
# IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
# CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
# SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#++
module RightScale
module CloudApi
# This is a parent class for all the other routines.
#
# The routine is a very simple object that does a simple task in the API call processing stack
# and exits. In most cases a single routine knows nothing about any other routines. It just
# takes incoming params from @data hash, processes it and stores back to the @data attribute.
#
class Routine
attr_reader :data
# Initializes the @data attribute. Is called before *process* method.
#
# @param [Hash] data See ApiManager for better explanation what data is.
#
def reset(data=nil)
@data = data
end
# Main entry point. The method must be overriden by sub-classes.
def process
raise Error::new("This method should be implemented by a subclass")
end
# Initialize and process the routine. Is usially called from unit tests.
def execute(data)
reset(data)
process
end
# Current options.
#
# @return [Hash]
#
def options
@data[:options]
end
# Current logger.
#
# @return [CloudApiLogger]
#
def cloud_api_logger
options[:cloud_api_logger]
end
# The method takes a block of code and logs how much time the given block took to execute.
#
# @param [String] description The prefix that is added to every logged line.
# @param [Symbol] log_key The log key (see {RightScale::CloudApi::CloudApiLogger}).
#
def with_timer(description = 'Timer', log_key = :timer, &block)
cloud_api_logger.log("#{description} started...",:timer)
start = Time::now
result = block.call
cloud_api_logger.log("#{description} completed (#{'%.6f' % (Time::now - start)} sec)", log_key)
result
end
# A helper method for invoking callbacks.
#
# The method checks if the given Proc exists and invokes it with the given set of arguments.
# In the case when proc==nil the method does nothing.
#
# @param [Proc] proc The callback.
# @param [Any] args A set of callback method arguments.
#
def invoke_callback_method(proc, *args) # :nodoc:
proc.call(*args) if proc.is_a?(Proc)
end
end
end
end<file_sep>require 'simplecov'
SimpleCov.start
require 'right_cloud_api_base'
require 'rspec'
# Generates a fake response object.
#
# @param [String] code HTTP response code
# @param [String] body HTTP response body
# @param [Hash] headers HTTP response code
# @param [HttpResponse] raw HTTP response object
#
# @return [RightScale::CloudApi::HTTPResponse]
#
def generate_http_response(code, body='body', headers={}, raw=nil)
RightScale::CloudApi::HTTPResponse.new(code.to_s, body, headers, raw)
end
<file_sep>#--
# Copyright (c) 2013 RightScale, Inc.
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# 'Software'), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
# IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
# CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
# SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#++
require File.expand_path(File.dirname(__FILE__)) + "/../spec_helper"
describe "RightScale::CloudApi::ResponseParser" do
before :each do
logger = Logger.new(STDOUT)
logger.level = Logger::INFO
@response_parser = RightScale::CloudApi::ResponseParser.new
@test_data = {}
@test_data[:request] = { :verb => 'some_verb', :orig_params => {}, :instance => 'some_request'}
@test_data[:options] = {:error_patterns => [], :cloud_api_logger => RightScale::CloudApi::CloudApiLogger.new(
{:logger => logger, :log_filters => [:response_parser]})
}
@callback = double
@test_data[:callbacks] = {:close_current_connection => @callback}
@test_data[:connection] = {}
allow(@response_parser).to receive(:log)
end
context "encoding" do
context "text/xml;charset=UTF-8" do
before :each do
response = double(
:code => '200',
:body => 'body',
:headers => {"content-type" => ["text/xml;charset=UTF-8"]},
:is_io? => false,
:is_error? => true,
:body_info_for_log => 'body',
:header_info_for_log => ""
)
@test_data[:response] = {:instance => response}
expect(RightScale::CloudApi::Parser::Sax).to receive(:parse).\
once.with('body', {:encoding => 'UTF-8'})
end
it "works" do
@response_parser.execute(@test_data)
end
end
context "text/xml;charset=utf-8" do
before :each do
response = double(
:code => '200',
:body => 'body',
:headers => {"content-type" => ["text/xml;charset=utf-8"]},
:is_io? => false,
:is_error? => true,
:body_info_for_log => 'body',
:header_info_for_log => ""
)
@test_data[:response] = {:instance => response}
expect(RightScale::CloudApi::Parser::Sax).to receive(:parse).\
once.with('body', {:encoding => 'UTF-8'})
end
it "works" do
@response_parser.execute(@test_data)
end
end
context "text/xml;charset=ISO" do
before :each do
response = double(
:code => '200',
:body => 'body',
:headers => {"content-type" => ["text/xml;charset=ISO"]},
:is_io? => false,
:is_error? => true,
:body_info_for_log => 'body',
:header_info_for_log => ""
)
@test_data[:response] = {:instance => response}
expect(RightScale::CloudApi::Parser::Sax).to receive(:parse).\
once.with('body', {})
end
it "works" do
@response_parser.execute(@test_data)
end
end
context "text/xml" do
before :each do
response = double(
:code => '200',
:body => 'body',
:headers => {"content-type" => ["text/xml"]},
:is_io? => false,
:is_error? => true,
:body_info_for_log => 'body',
:header_info_for_log => ""
)
@test_data[:response] = {:instance => response}
expect(RightScale::CloudApi::Parser::Sax).to receive(:parse).\
once.with('body', {})
end
it "works" do
@response_parser.execute(@test_data)
end
end
context "text/json;charset=ISO" do
before :each do
response = double(
:code => '200',
:body => 'body',
:headers => {"content-type" => ["text/json;charset=ISO"]},
:is_io? => false,
:is_error? => true,
:body_info_for_log => 'body',
:header_info_for_log => ""
)
@test_data[:response] = {:instance => response}
expect(RightScale::CloudApi::Parser::Json).to receive(:parse).\
once.with('body', {})
end
it "works" do
@response_parser.execute(@test_data)
end
end
context "text/json;charset=utf-8" do
before :each do
response = double(
:code => '200',
:body => 'body',
:headers => {"content-type" => ["text/json;charset=utf-8"]},
:is_io? => false,
:is_error? => true,
:body_info_for_log => 'body',
:header_info_for_log => ""
)
@test_data[:response] = {:instance => response}
expect(RightScale::CloudApi::Parser::Json).to receive(:parse).\
once.with('body', {:encoding => 'UTF-8'})
end
it "works" do
@response_parser.execute(@test_data)
end
end
end
context "parsing" do
context "XML, default" do
before :each do
@expectation = {'xml' => { 'a' => '1' }}
response = double(
:code => '200',
:body => @expectation._to_xml,
:headers => {"content-type" => ["text/xml"]},
:is_io? => false,
:is_error? => true,
:body_info_for_log => 'body',
:header_info_for_log => ""
)
@test_data[:response] = {:instance => response}
end
it "returns parsed response" do
@response_parser.execute(@test_data)
result = @test_data[:result]
expect(result).to be_a(Hash)
expect(result).to eq(@expectation)
end
end
context "XML, do not parse flag is set" do
before :each do
@expectation = {'xml' => { 'a' => '1' }}
response = double(
:code => '200',
:body => @expectation._to_xml,
:headers => {"content-type" => ["text/xml"]},
:is_io? => false,
:is_error? => true,
:body_info_for_log => 'body',
:header_info_for_log => ""
)
@test_data[:response] = {:instance => response}
@test_data[:options][:raw_response] = true
end
it "returns raw response" do
@response_parser.execute(@test_data)
result = @test_data[:result]
expect(result).to be_a(String)
expect(result).to eq(@expectation._to_xml)
end
end
end
end
<file_sep>
#--
# Copyright (c) 2013 RightScale, Inc.
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# 'Software'), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
# IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
# CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
# SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#++
module RightScale
module CloudApi
class ConnectionProxy
class NetHttpPersistentProxy
class Error < CloudApi::Error
end
# Known timeout errors
TIMEOUT_ERRORS = /Timeout|ETIMEDOUT/
# Other re-triable errors
OTHER_ERRORS = /SocketError|EOFError|SSL_connect|EAFNOSUPPORT/
def log(message)
@data[:options][:cloud_api_logger].log(message, :connection_proxy, :warn)
end
# Performs an HTTP request.
#
# @param [Hash] data The API request +data+ storage.
# See {RightScale::CloudApi::ApiManager.initialize_api_request_options} code for its explanation.
#
# P.S. Options not supported by Net::HTTP::Persistent:
# :connection_retry_count, :connection_retry_delay, :cloud_api_logger
#
def request(data)
require "net/http/persistent"
# Initialize things:
@data = data
@data[:response] = {}
# Create a new HTTP request instance
http_request = create_new_http_request
# Create and tweak Net::HTTP::Persistent instance
connection = create_new_persistent_connection
# Make a request
begin
make_request_with_retries(connection, @data[:connection][:uri], http_request)
rescue => e
fail(ConnectionError, e.message)
ensure
connection.shutdown
end
end
# Creates a new connection.
#
# There is a bug in Net::HTTP::Persistent where it allows you to reuse an SSL connection
# created by another instance of Net::HTTP::Persistent, if they share the same app name.
# To avoid this, every instance of Net::HTTP::Persistent should have its own 'name'.
#
# If your app does not care about SSL certs and keys (like AWS does) then it is safe to
# reuse connections.
#
# see https://github.com/drbrain/net-http-persistent/issues/45
#
def create_new_persistent_connection
app_name = if @data[:options][:connection_ca_file] ||
@data[:credentials][:cert] ||
@data[:credentials][:key]
'right_cloud_api_gem_%s' % Utils::generate_token
else
'right_cloud_api_gem'
end
connection = Net::HTTP::Persistent.new(app_name)
set_persistent_connection_options!(connection)
# Register a callback to close current connection
@data[:callbacks][:close_current_connection] = Proc::new do |reason|
connection.shutdown
log "Current connection closed: #{reason}"
end
connection
end
# Sets connection_ca_file, connection_read_timeout, connection_open_timeout,
# connection_verify_mode and SSL cert and key
#
# @param [Net::HTTP::Persistent] connection
#
# @return [Net::HTTP::Persistent]
#
def set_persistent_connection_options!(connection)
[:ca_file, :read_timeout, :open_timeout, :verify_mode].each do |connection_method|
connection_option_name = "connection_#{connection_method}".to_sym
next unless @data[:options].has_key?(connection_option_name)
connection.__send__("#{connection_method}=", @data[:options][connection_option_name])
end
if @data[:credentials].has_key?(:cert)
connection.cert = OpenSSL::X509::Certificate.new(@data[:credentials][:cert])
end
if @data[:credentials].has_key?(:key)
connection.key = OpenSSL::PKey::RSA.new(@data[:credentials][:key])
end
connection
end
# Creates and configures a new HTTP request object
#
# @return [Net::HTTPRequest]
#
def create_new_http_request
# Create a new HTTP request instance
request_spec = @data[:request][:instance]
http_class = "Net::HTTP::#{request_spec.verb._camelize}"
http_request = http_class._constantize::new(request_spec.path)
# Set the request body
if request_spec.is_io?
http_request.body_stream = request_spec.body
else
http_request.body = request_spec.body
end
# Copy headers
request_spec.headers.each { |header, value| http_request[header] = value }
# Save the new request
request_spec.raw = http_request
# Set user-agent
if @data[:options].has_key?(:connection_user_agent)
http_request['user-agent'] ||= @data[:options][:connection_user_agent]
end
http_request
end
# Makes request with low level retries.
#
# Net::HTTP::Persistent does not fully support retries logic that we used to have.
# To deal with this we disable Net::HTTP::Persistent's retries and handle them in our code.
#
# @param [Net::HTTP::Persistent] connection
# @param [URI] uri
# @param [Net::HTTPRequest] http_request
#
# @return [void]
#
def make_request_with_retries(connection, uri, http_request)
disable_net_http_persistent_retries(connection)
# Initialize retry vars:
connection_retry_count = @data[:options][:connection_retry_count] || 3
connection_retry_delay = @data[:options][:connection_retry_delay] || 0.5
retries_performed = 0
# If block is given - pass there all the chunks of a response and then stop
# (don't do any parsing, analysis, etc)
block = @data[:vars][:system][:block]
begin
if block
# Response.body is a Net::ReadAdapter instance - it can't be read as a string.
# WEB: On its own, Net::HTTP causes response.body to be a Net::ReadAdapter when you make a request with a block
# that calls read_body on the response.
connection.request(uri, http_request) do |response|
# If we are at the point when we have started reading from the remote end
# then there is no low level retry is allowed. Otherwise we would need to reset the
# IO pointer, etc.
connection_retry_count = 0
if response.is_a?(Net::HTTPSuccess)
set_http_response(response, :skip_body)
response.read_body(&block)
else
set_http_response(response)
end
end
else
# Set text response
response = connection.request(uri, http_request)
set_http_response(response)
end
nil
rescue => e
# Parse both error message and error classname; for some errors it's not enough to parse only a message
custom_error_msg = "#{e.class.name}: #{e.message}"
# Initialize new error with full message including class name, so gw can catch it now
custom_error = Error.new(custom_error_msg)
# Fail if it is an unknown error
fail(custom_error) if !(custom_error_msg[TIMEOUT_ERRORS] || custom_error_msg[OTHER_ERRORS])
# Fail if it is a Timeout and timeouts are banned
fail(custom_error) if custom_error_msg[TIMEOUT_ERRORS] && !!@data[:options][:abort_on_timeout]
# Fail if there are no retries left...
fail(custom_error) if (connection_retry_count -= 1) < 0
# ... otherwise sleep a bit and retry.
retries_performed += 1
log("#{self.class.name}: Performing retry ##{retries_performed} caused by: #{e.class.name}: #{e.message}")
sleep(connection_retry_delay) unless connection_retry_delay._blank?
connection_retry_delay *= 2
retry
end
end
# Saves HTTP Response into data hash.
#
# @param [Net::HTTPResponse] response
#
# @return [void]
#
def set_http_response(response, skip_body=false)
@data[:response][:instance] = HTTPResponse.new(
response.code,
skip_body ? nil : response.body,
response.to_hash,
response
)
nil
end
# Net::HTTP::Persistent believes that it can retry on any GET call what is not true for
# Query like API clouds (Amazon, CloudStack, Euca, etc).
# The solutions is to monkeypatch Net::HTTP::Persistent#can_retry? so that is returns
# Net::HTTP::Persistent#retry_change_requests.
#
# @param [Net::HTTP::Persistent] connection
#
# @return [void]
#
def disable_net_http_persistent_retries(connection)
connection.retry_change_requests = false
# Monkey patch this connection instance only.
def connection.can_retry?(*args)
false
end
nil
end
end
end
end
end
<file_sep>#--
# Copyright (c) 2013 RightScale, Inc.
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# 'Software'), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
# IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
# CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
# SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#++
require File.expand_path(File.dirname(__FILE__)) + "/../spec_helper"
describe "support_xml.rb" do
# --- Object ---
context "Object#_xml_escale" do
it "escapes non-xml symbols" do
expect("Hello <'world'> & \"the Universe\""._xml_escape).to eq(
"Hello <'world'> & "the Universe""
)
end
end
context "Object#_xml_unescale" do
it "unescapes non-xml symbols" do
expect("Hello <'world'> & "the Universe""._xml_unescape).to eq(
"Hello <'world'> & \"the Universe\""
)
end
end
context "Object#_to_xml" do
it "returns a simple XML string" do
expect("hahaha"._to_xml).to eq 'hahaha'
end
end
# --- Array ---
context "Aray#_to_xml" do
it "builds a one-line XML by default" do
expect(['a', 2, [3, 4], 'string', :symbol, { 3 => 4 }, { 5 => { '@i:type' => '13', '@@text' => 555 }}].\
_to_xml).to eq(
"<item>a</item><item>2</item><item><item>3</item><item>4</item></item>" +
"<item>string</item><item>symbol</item><item><3>4</3></item><item><5 i:type=\"13\">555</5></item>"
)
end
it "builds a multi-line XML when :indent is set" do
expect(['a', 2, [3, 4], 'string', :symbol,
{ 3 => 4 }, { 5 => { '@i:type' => '13', '@@text' => 555 }}]._to_xml(:tag => 'item', :indent => ' ')).to eq(
"<item>a</item>\n" +
"<item>2</item>\n" +
"<item>\n" +
" <item>3</item>\n" +
" <item>4</item>\n" +
"</item>\n" +
"<item>string</item>\n" +
"<item>symbol</item>\n" +
"<item>\n" +
" <3>4</3>\n" +
"</item>\n" +
"<item>\n" +
" <5 i:type=\"13\">555</5>\n" +
"</item>\n"
)
end
end
# --- Hash ---
context "Hash#_to_xml" do
it "builds a simple XML from a single key hash" do
expect(({ 'a' => [ 1, { :c => 'd' } ] })._to_xml).to eq "<a>1</a><a><c>d</c></a>"
end
it "understands attributes as keys starting with @ and text defined as @@text" do
expect({ 'screen' => { '@width' => 1080, '@@text' => 'HD' } }._to_xml).to eq(
"<screen width=\"1080\">HD</screen>"
)
end
# Ruby 1.8 keeps hash keys in unpredictable order and the order on the tags
# in the resulting XMl is also not easy to predict.
if RUBY_VERSION >= '1.9'
it "builds a one-line hash by default" do
expect({ 'a' => 2, :b => [1, 3, 4, { :c => { 'd' => 'something' } } ], 5 => { '@i:type' => '13', '@@text' => 555 } }._to_xml).to eq(
'<a>2</a><b>1</b><b>3</b><b>4</b><b><c><d>something</d></c></b><5 i:type="13">555</5>'
)
end
it "builds a multi-line hash when :indent is set" do
expect({ 'a' => 2, :b => [1, 3, 4, { :c => { 'd' => 'something' } } ] }._to_xml(:indent => ' ')).to eq(
"<a>2</a>" + "\n" +
"<b>1</b>" + "\n" +
"<b>3</b>" + "\n" +
"<b>4</b>" + "\n" +
"<b>" + "\n" +
" <c>" + "\n" +
" <d>something</d>" + "\n" +
" </c>" + "\n" +
"</b>" + "\n"
)
end
it "understands attributes as keys starting with @ and text defined as @@text (more complex "+
"example for ruby 1.9)" do
expect({ 'screen' => {
'@width' => 1080,
'@hight' => 720,
'@@text' => 'HD',
'color' => {
'@max-colors' => 65535,
'@dinamic-resolution' => '1:1000000',
'@@text' => '<"PAL">',
'brightness' => {
'bright' => true
}
}
}
}._to_xml(:indent => ' ', :escape => true)).to eq(
"<screen width=\"1080\" hight=\"720\">" + "\n" +
" HD" + "\n" +
" <color max-colors=\"65535\" dinamic-resolution=\"1:1000000\">" + "\n" +
" <"PAL">" + "\n" +
" <brightness>" + "\n" +
" <bright>true</bright>" + "\n" +
" </brightness>" + "\n" +
" </color>" + "\n" +
"</screen>" + "\n"
)
end
end
it "can mix ordering ID into Strings" do
key1 = Hash::_order('my-item')
key2 = Hash::_order('my-item')
expect(!!key1[Hash::RIGHTXMLSUPPORT_SORTORDERREGEXP]).to be true
expect(!!key2[Hash::RIGHTXMLSUPPORT_SORTORDERREGEXP]).to be true
expect(key1).to be < key2
end
it "XML-text has all the keys sorted accordingly to the given order" do
Hash::instance_variable_set('@_next_ordered_key_id', 0)
hash = {
Hash::_order('foo') => 34,
Hash::_order('boo') => 45,
Hash::_order('zoo') => 53,
Hash::_order('poo') => 10,
Hash::_order('moo') => {
Hash::_order('noo') => 101,
Hash::_order('too') => 113,
Hash::_order('koo') => 102,
},
Hash::_order('woo') => 03,
Hash::_order('hoo') => 1
}
expect(hash).to eq(
"foo{#1}" => 34,
"boo{#2}" => 45,
"zoo{#3}" => 53,
"poo{#4}" => 10,
"moo{#5}" => {
"noo{#6}" => 101,
"too{#7}" => 113,
"koo{#8}" => 102,
},
"woo{#9}" => 3,
"hoo{#10}" => 1
)
expect(hash._to_xml(:indent => ' ')).to eq(
"<foo>34</foo>" + "\n" +
"<boo>45</boo>" + "\n" +
"<zoo>53</zoo>" + "\n" +
"<poo>10</poo>" + "\n" +
"<moo>" + "\n" +
" <noo>101</noo>" + "\n" +
" <too>113</too>" + "\n" +
" <koo>102</koo>" + "\n" +
"</moo>" + "\n" +
"<woo>3</woo>" + "\n" +
"<hoo>1</hoo>" + "\n"
)
end
end
end<file_sep>#--
# Copyright (c) 2013 RightScale, Inc.
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# 'Software'), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
# IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
# CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
# SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#++
module RightScale
module CloudApi
# The routine parses the current response.
#
# The supportes content-types are: xml and json.
# In the case of any other content-type it does nothing.
#
class ResponseParser < Routine
# Main entry point.
#
def process
# There is no way to parse an IO response
return nil if data[:response][:instance].is_io?
xml_parser = Utils::get_xml_parser_class(data[:options][:xml_parser])
content_type = (data[:response][:instance].headers || {})["content-type"].to_s
body = data[:response][:instance].body.to_s
# If it was explicitly requested not to parse the response then return it as is.
if data[:options][:raw_response]
data[:result] = body
return
end
# Find the appropriate parser.
parser = if body._blank?
Parser::Plain
else
case content_type
when /xml/ then xml_parser
when /json|javascript/ then Parser::Json
else
if data[:response][:instance].body.to_s[/\A<\?xml /]
# Sometimes Amazon does not set a proper header
xml_parser
else
Parser::Plain
end
end
end
# Parse the response
with_timer("Response parsing with #{parser}") do
options = {}
options[:encoding] = 'UTF-8' if /utf-8/i === content_type
#
cloud_api_logger.log("Attempting to parse cloud response with: '#{options[:encoding] || 'DEFAULT'}' encoding", :response_parser)
data[:response][:parsed] = parser::parse(body, options)
end
data[:result] = data[:response][:parsed]
end
end
end
end
<file_sep>#--
# Copyright (c) 2013 RightScale, Inc.
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# 'Software'), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
# IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
# CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
# SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#++
module RightScale
module CloudApi
# The routine processes cache validations (when caching is enabled).
#
# It takes a response from a cloud and tries to find a pre-defined caching pattern that would
# fit to this response and its request. If there is a pattern it extracts a previous response
# from the cache and compares it to the current one.
#
# If both the responses match it raises RightScale::CloudApi::CacheHit exception.
#
# The main point of the caching - it is performed before parsing a response. So if we get a 10M
# XML from Amazon it will take seconds to parse it but if the response did not change there is
# need to parse it.
#
# @example
# ec2 = RightScale::CloudApi::AWS::EC2.new(key, secret_key, :cache => true)
# ec2.DescribeInstances #=> a list of instances
# ec2.DescribeInstances(:options => {:cache => false}) #=> the same list of instances
# ec2.DescribeInstances #=> exception if the response did not change
#
# The caching setting is per cloud specific ApiManager. For some of them it is on by default so
# you need to look at the ApiManager definition.
#
class CacheValidator < Routine
class Error < CloudApi::Error
end
# Logs a message.
#
# @param [String] message Some text.
#
def log(message)
cloud_api_logger.log( "#{message}", :cache_validator)
end
module ClassMethods
CACHE_PATTERN_KEYS = [ :verb, :verb!, :path, :path!, :request, :request!, :code, :code!, :response, :response!, :key, :if, :sign ]
def self.extended(base)
unless base.respond_to?(:options) && base.options.is_a?(Hash)
raise Error::new("CacheValidator routine assumes class being extended responds to :options and returns a hash")
end
end
# Adds new cache patters.
# Patterns are analyzed in order of their definnition. If one pattern hits
# the rest are not analyzed.
#
# @param [Hash] cache_pattern A hash of pattern keys.
# @option cache_pattern [Proc] :key A method that calculates a kache key name.
# @option cache_pattern [Proc] :sign A method that modifies the response before calculating md5.
#
# @see file:lib/base/helper/utils.rb self.pattern_matches? for the other options.
#
# @example:
# cache_pattern :verb => /get|post/,
# :path => /Action=Describe/,
# :if => Proc::new{ |o| (o[:params].keys - %w{Action Version AWSAccessKeyId})._blank? },
# :key => Proc::new{ |o| o[:params]['Action'] },
# :sign => Proc::new{ |o| o[:response].body.to_s.sub(%r{<requestId>.+?</requestId>}i,'') }
#
def cache_pattern(cache_pattern)
fail Error::new("Pattern should be a Hash and should not be blank") if !cache_pattern.is_a?(Hash) || cache_pattern._blank?
fail Error::new("Key field not found in cache pattern definition #{cache_pattern.inspect}") unless cache_pattern.keys.include?(:key)
unsupported_keys = cache_pattern.keys - CACHE_PATTERN_KEYS
fail Error::new("Unsupported keys #{unsupported_keys.inspect} in cache pattern definition #{cache_pattern.inspect}") unless unsupported_keys._blank?
(options[:cache_patterns] ||= []) << cache_pattern
end
end
# The main entry point.
#
def process
# Do nothing if caching is off
return nil unless data[:options][:cache]
# There is nothing to cache if we stream things
return nil if data[:response][:instance].is_io?
cache_patterns = data[:options][:cache_patterns] || []
opts = { :relative_path => data[:request][:relative_path],
:request => data[:request][:instance],
:response => data[:response][:instance],
:verb => data[:request][:verb],
:params => data[:request][:orig_params].dup }
# Walk through all the cache patterns and find the first that matches
cache_patterns.each do |pattern|
# Try on the next pattern unless the current one matches.
next unless Utils::pattern_matches?(pattern, opts)
# Process the matching pattern.
log("Request matches to cache pattern: #{pattern.inspect}")
# Build a cache key and get a text to be signed
cache_key, text_to_sign = build_cache_key(pattern, opts)
cache_record = {
:timestamp => Time::now.utc,
:md5 => Digest::MD5::hexdigest(text_to_sign).to_s,
:hits => 0
}
log("Processing cache record: #{cache_key} => #{cache_record.inspect}")
# Save current cache key for later use (by other Routines)
data[:vars][:cache] ||= {}
data[:vars][:cache][:key] = cache_key
data[:vars][:cache][:record] = cache_record
# Get the cache storage
storage = (data[:vars][:system][:storage][:cache] ||= {} )
unless storage[cache_key]
# Create a new record unless exists.
storage[cache_key] = cache_record
log("New cache record created")
else
# If the record is already there but the response changed the replace the old record.
unless storage[cache_key][:md5] == cache_record[:md5]
storage[cache_key] = cache_record
log("Missed. Record is replaced")
else
# Raise if cache hits.
storage[cache_key][:hits] += 1
message = "Cache hit: #{cache_key.inspect} has not changed since " +
"#{storage[cache_key][:timestamp].strftime('%Y-%m-%d %H:%M:%S')}, "+
"hits: #{storage[cache_key][:hits]}."
log(message)
fail CacheHit::new("CacheValidator: #{message}")
end
end
break
end
true
end
private
# Builds the cached record key and body.
#
# @param [Hash] pattern The pattern that matched to the current response.
# @option options [Hash] opts A set of options that will be passed to :key and :sign procs.
#
# @return [Array] An array: [key, body]
#
# @raise [RightScale::CloudApi::CacheValidator::Error] Unless :key proc id set.
# @raise [RightScale::CloudApi::CacheValidator::Error] Unless :sign proc returns a valid body.
#
# @example
# build_cache_key(pattern) #=>
# ["DescribeVolumes", "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<DescribeVolumesResponse ... </DescribeVolumesResponse>"]
#
def build_cache_key(pattern, opts)
key = pattern[:key].is_a?(Proc) ? pattern[:key].call(opts) : pattern[:key]
fail Error::new("Cannot build cache key using pattern #{pattern.inspect}") unless key
body_to_sign = opts[:response].body.to_s if opts[:response].body
body_to_sign = pattern[:sign].call(opts) if pattern[:sign]
fail Error::new("Could not create body to sign using pattern #{pattern.inspect}") unless body_to_sign
[key, body_to_sign]
end
end
end
end
<file_sep>#--
# Copyright (c) 2013 RightScale, Inc.
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# 'Software'), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
# IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
# CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
# SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#++
require File.expand_path(File.dirname(__FILE__)) + "/../spec_helper"
describe "RightScale::CloudApi::ResultWrapper" do
before (:each) do
logger = Logger.new(STDOUT)
logger.level = Logger::INFO
@resultwrapper = RightScale::CloudApi::ResultWrapper.new
@test_data = {}
@test_data[:options] = { :user_agent => 'user_agent_data',
:cloud_api_logger => RightScale::CloudApi::CloudApiLogger.new({:logger => logger})}
@test_data[:vars] = {}
@test_data[:callbacks] = {}
@parsed_response = "parsed_response"
@test_data[:result] = @parsed_response
@headers = { 'header1' => ['1'], 'header2' => ['2'] }
@response= generate_http_response(201, 'body', @headers)
@test_data[:response] = {:instance => @response, :parsed => @parsed_response }
allow(@resultwrapper).to receive(:log)
@test_data[:vars][:current_cache_key] = "cache_key"
@test_data[:vars][:cache] = {'cache_key' => { :key => 'old_cache_record_key', :record => 'haha' }}
@result = @resultwrapper.execute(@test_data)
end
context "metadata" do
it "looks like a parsed body object but responds to metadata" do
expect(@result).to eq 'parsed_response'
expect(@result).to be_a(String)
expect { @result.metadata }.to_not raise_error
end
it "contains the last respose headers and code" do
expect(@result.metadata[:headers]).to eq @headers
expect(@result.metadata[:code]).to eq @response.code
end
it "may contain the cache key" do
expect(@result.metadata[:cache]).to eq @test_data[:vars][:cache]
end
end
end<file_sep>#--
# Copyright (c) 2013 RightScale, Inc.
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# 'Software'), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
# IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
# CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
# SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#++
class Object #:nodoc:
RIGHTXMLSUPPORT_XMLESCAPE = {'"' => '"', '\'' =>''', '<' => '<', '>' => '>'}
RIGHTXMLSUPPORT_XMLUNESCAPE = RIGHTXMLSUPPORT_XMLESCAPE.invert
RIGHTXMLSUPPORT_XMLINDENT = ""
RIGHTXMLSUPPORT_XMLLEVEL = 0
RIGHTXMLSUPPORT_XMLCRLF = "\n"
# Escapes non-XML symbols.
#
# @return [String] XML-escaped string.
#
# @example
# "Hello <'world'> & \"the Universe\""._xml_escape #=>
# "Hello <'world'> & "the Universe""
#
def _xml_escape
self.to_s.gsub('&', '&').gsub(/#{RIGHTXMLSUPPORT_XMLESCAPE.keys.join('|')}/) { |match| RIGHTXMLSUPPORT_XMLESCAPE[match] }
end
# Conditionally escapes non-XML symbols.
#
# @param [Hash] opts A set of options.
# @option opts [Boolean] :escape The flag.
#
# @return [String] XML-escaped string if :escape it set ot true or self otherwise.
#
def _xml_conditional_escape(opts={})
opts[:escape] ? self._xml_escape : self.to_s
end
# Unescapes XML-escaped symbols.
#
# @return [String] XML-unscaped string.
#
# @example
# "Hello <'world'> & "the Universe""._xml_unescape #=>
# "Hello <'world'> & \"the Universe\"
#
def _xml_unescape
self.to_s.gsub(/#{RIGHTXMLSUPPORT_XMLUNESCAPE.keys.join('|')}/) { |match| RIGHTXMLSUPPORT_XMLUNESCAPE[match] }.gsub('&','&')
end
# Fixes the given set of options.
#
def _xml_get_opts(opts={}) # :nodoc:
opts[:level] ||= RIGHTXMLSUPPORT_XMLLEVEL
opts[:indent] ||= RIGHTXMLSUPPORT_XMLINDENT
opts[:crlf] ||= opts[:indent].empty? ? "" : RIGHTXMLSUPPORT_XMLCRLF
opts
end
# Returns an aligned piece of XML text.
#
def _xml_align(opts={}) # :nodoc:
return '' if self.to_s.empty?
opts = _xml_get_opts(opts)
"#{opts[:indent]*opts[:level]}#{self}#{opts[:crlf]}"
end
# Returns an XML-representation of the object.
#
# @param [Hash] opts A set of options.
# @option opts [Boolean] :escape The flag.
#
# @return [String] The result is an XML-escaped string (if :escape flag is set) or self otherwise.
#
def _to_xml(opts={})
_xml_conditional_escape(_xml_get_opts(opts))
end
# Returns an XML-representation of the object starting with '<?xml version="1.0" encoding="UTF-8"?>'
# string.
#
# @param [Hash] args A set of arguments (see _to_xml)
#
# @return [String]
#
def _to_xml!(*args)
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"+
"#{_to_xml(*args)}"
end
end
# --- Array ---
class Array #:nodoc:
# Returns an XML-representation if the array object.
#
# @param [Hash] opts A set of options.
# @option opts [Boolean] :escape The flag.
# @option opts [String] :tag The tag every array item is to be wrapped with ('<item>' by default)
#
# @return [String]
#
# @example
# [1,2,3,4]._to_xml #=>
# '<item>1</item><item>2</item><item>3</item><item>4</item>'
#
# @example
# [1,2,3,4]._to_xml(:crlf => "\n") #=>
# <item>1</item>
# <item>2</item>
# <item>3</item>
# <item>4</item>
#
# @example
# [1,2,[3,4,[5]]]._to_xml(:indent => ' ', :tag => 'hoho') #=>
# <hoho>1</hoho>
# <hoho>2</hoho>
# <hoho>
# <item>3</item>
# <item>4</item>
# <item>
# <item>5</item>
# </item>
# </hoho>
#
def _to_xml(opts={})
opts = _xml_get_opts(opts)
tag = opts.delete(:tag) || 'item'
{ tag => self }._to_xml(opts)
end
end
class Hash #:nodoc:
RIGHTXMLSUPPORT_SORTORDERREGEXP = /(\{#(\d+)\})$/
# Generate a consecutive id for a new key.
# If String or Symbol is passed then adds the id to it.
#
# The method is widely used for MS Azure XMLs because MS requires XML
# tags to appear in a predefined order. Grrr... ;)
#
# @param [String] key_name Usually a tag name.
#
# @return [String] A string containing the original one and the current ordering ID.
# if key_name was not set then it returns the next id value.
#
# @example
# Hash::_order('hahaha') #=> "hahaha{#1}"
# Hash::_order('hohoho') #=> "hohoho{#2}"
# Hash::_order #=> 3
#
# @example
# hash = {
# Hash::_order('foo') => 34,
# Hash::_order('boo') => 45,
# Hash::_order('zoo') => 53,
# Hash::_order('poo') => 10,
# Hash::_order('moo') => {
# Hash::_order('noo') => 101,
# Hash::_order('too') => 113,
# Hash::_order('koo') => 102,
# },
# Hash::_order('woo') => 03,
# Hash::_order('hoo') => 1
# }
# hash._to_xml(:indent => ' ') #=>
# <boo>45</boo>
# <zoo>53</zoo>
# <poo>10</poo>
# <moo>
# <noo>101</noo>
# <too>113</too>
# <koo>102</koo>
# </moo>
# <woo>3</woo>
# <hoo>1</hoo>
#
def self._order(key_name=nil)
@_next_ordered_key_id ||= 0
@_next_ordered_key_id += 1
if key_name
fail(RuntimeError.new('String or Symbol is expected')) unless key_name.is_a?(String) || key_name.is_a?(Symbol)
result = "#{key_name}{##{@_next_ordered_key_id}}"
result = result.to_sym if key_name.is_a?(Symbol)
result
else
@_next_ordered_key_id
end
end
# Sorts the keys accordingly to their order definition (if Hash::_order was used).
def _xml_sort_keys # :nodoc:
keys.sort do |key1, key2|
key1idx = key1.to_s[RIGHTXMLSUPPORT_SORTORDERREGEXP] && $2 && $2.to_i
key2idx = key2.to_s[RIGHTXMLSUPPORT_SORTORDERREGEXP] && $2 && $2.to_i
if key1idx && key2idx then key1idx <=> key2idx
elsif key1idx then -1
elsif key2idx then 1
else 0
end
end
end
# Builds the final XML tag text.
def _xml_finalize_tag(tag_name, tag_attributes, tag_text, tag_elements, opts) # :nodoc:
next_opts = opts.merge(:level => opts[:level] + 1)
case
when tag_elements.empty? && tag_text.empty? then "<#{tag_name}#{tag_attributes}/>"._xml_align(opts)
when tag_elements.empty? then "<#{tag_name}#{tag_attributes}>#{tag_text}</#{tag_name}>"._xml_align(opts)
else "<#{tag_name}#{tag_attributes}>"._xml_align(opts) +
tag_text._xml_align(next_opts) +
tag_elements +
"</#{tag_name}>"._xml_align(opts)
end
end
# Returns an XML-representation if the hash object.
#
# @param [Hash] opts A set of options.
# @option opts [Boolean] :escape The flag.
# @option opts [Boolean] :indent The indentation string (is blank by default).
# @option opts [Boolean] :crfl The CR/LF string (is blank by default).
#
# @return [String]
#
# @example
# ({ 'a' => [ 1, { :c => 'd' } ] })._to_xml #=>
# "<a>1</a><a><c>d</c></a>"
#
# @example
# { 'screen' => {
# '@width' => 1080,
# '@hight' => 720,
# '@@text' => 'HD',
# 'color' => {
# '@max-colors' => 65535,
# '@dinamic-resolution' => '1:1000000',
# '@@text' => '<"PAL">',
# 'brightness' => {
# 'bright' => true
# }
# }
# }
# }._to_xml(:indent => ' ',
# :escape => true) #=>
# <screen width="1080" hight="720">
# HD
# <color max-colors="65535" dinamic-resolution="1:1000000">
# <"PAL">
# <brightness>
# <bright>true</bright>
# </brightness>
# </color>
# </screen>
#
def _to_xml(opts={})
result = ''
opts = _xml_get_opts(opts)
next_opts = opts.merge(:level => opts[:level] + 1)
_xml_sort_keys.each do |tag_name|
value = self[tag_name]
tag_name = tag_name.to_s.sub(RIGHTXMLSUPPORT_SORTORDERREGEXP, '')
if value.is_a?(Hash)
tag_attributes = ''; tag_elements = ''; tag_text = ''
value._xml_sort_keys.each do |item|
item_value = value[item]
item = item.to_s.sub(RIGHTXMLSUPPORT_SORTORDERREGEXP, '')
case
when item == '@@text' then tag_text << item_value._xml_conditional_escape(opts)
when item[/^@[^@]/] then tag_attributes << %Q{ #{item[1..-1]}="#{item_value._xml_conditional_escape(opts)}"}
else tag_elements << { item => item_value }._to_xml(next_opts)
end
end
result << _xml_finalize_tag(tag_name, tag_attributes, tag_text, tag_elements, opts)
elsif value.is_a?(Array)
value.each do |item|
item = { tag_name => item } if item.is_a?(Array)
result << { tag_name => item }._to_xml(opts)
end
else
result << _xml_finalize_tag(tag_name, '', value.to_s, '', opts)
end
end
result
end
end<file_sep>FROM ruby:2.1.9
RUN apt-get update -qq
ADD . /code/Ruby-Docker
WORKDIR /code/Ruby-Docker
# use the bundler version defined in the Gemfile.lock
RUN gem install bundler -v 1.17.3
RUN gem uninstall -i /usr/local/lib/ruby/gems/2.1.0 bundler
RUN bundle install
CMD ["bash"]
<file_sep>#--
# Copyright (c) 2013 RightScale, Inc.
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# 'Software'), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
# IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
# CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
# SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#++
module RightScale
module CloudApi
# Cloud API Logger wraps the given logger or creates a new one which logs to null by default
# By default the logger logs at INFO level.
#
# Every log message should be associated with a log_filter(key). If no log filter(key) is
# specified, then a message is logged and is not filterable.
#
# Any log_message with its key specified in log_filters is logged. If log_filters are not
# specified then the log_messages which is not associated by the key is logged.
#
# If parent logger is set at DEBUG level then all the messages are logged by default.
#
class CloudApiLogger
# Attribute readers
#
# @return [Object]
# @example
# # no example
attr_reader :logger, :log_filters, :log_filter_patterns
# Initializes a new logger
#
# @param [Hash] options A set of options
# @option options [String,IO] :logger Creates a new Logger instance from the given value.
# @option options [NilClass] :logger Creates a new Logger instance that logs to STDOUT.
# @option options [Array] :log_filters An array of topics to log (see {help}
# for list of keys)
# @option options [Array] :log_filter_patterns An array of Strings or RegExps of things
# that have to be filtered out from logs.
#
# @example
# new(:logger => STDOUT)
#
def initialize(options = {} , default_filters = [])
@logger = options[:logger]
if @logger.is_a?(String) || @logger.is_a?(IO)
@logger = ::Logger::new(options[:logger])
@logger.level = ::Logger::INFO
@logger.datetime_format = "%Y%m%d %H%M%S"
@logger.formatter = proc { |severity, datetime, progname, msg| "#{severity[/^./]} #{datetime.strftime("%y%m%d %H%M%S")}: #{msg}\n" }
elsif @logger.nil?
@logger = ::Logger::new(options.has_key?(:logger) ? '/dev/null' : STDOUT)
@logger.level = ::Logger::INFO
end
@log_filters = options[:log_filters]._blank? ? Array(default_filters) : Array(options[:log_filters])
@log_filter_patterns = options[:log_filter_patterns]._blank? ? [] : Array(options[:log_filter_patterns])
end
# Logs the message at DEBUG level
#
# @param [String] message The given message
# @param [Symbol] key The filtering key.
#
# @return [void]
# @example
# logger.info('some text')
#
def debug(message, key = nil)
log(message, key, :debug)
end
# Logs the message at INFO level
#
# @param [String] message The given message
# @param [Symbol] key The filtering key.
#
# @return [void]
# @example
# logger.info('some text')
#
def info(message, key = nil)
log(message, key, :info)
end
# Logs the message at WARN level
#
# @param [String] message The given message
# @param [Symbol] key The filtering key.
#
# @return [void]
# @example
# logger.warn('some text')
#
def warn(message, key = nil)
log(message, key, :warn)
end
# Logs the message at ERROR level
#
# @param [String] message The given message
# @param [Symbol] key The filtering key.
#
# @return [void]
# @example
# logger.error('some text')
#
def error(message, key = nil)
log(message, key, :error)
end
# Returns a helper hash with all the supported topics
#
# @return [Hash] A set of log filter keys with explanations.
#
# @example
# # no example
#
def self.help
{
:api_manager => "Enables ApiManager's logs",
:wrapper => "Enables Wrapper's logs",
:routine => "Enables Routine's logs",
:cache_validator => "Enables CacheValidator logs",
:request_analyzer => "Enables RequestAnalyzer logs",
:request_generator => "Enables RequestGenerator logs" ,
:request_generator_body => "Enables RequestGenerator body logging",
:response_analyzer => "Enables ResponseAnalizer logs",
:response_analyzer_body => "Enables ResponseAnalyzer body logging",
:response_analyzer_body_error => "Enables ResponseAnalyzer body logging on error",
:timer => "Enables timer logs",
:retry_manager => "Enables RetryManager logs",
:connection_proxy => "Enables ConnectionProxy logs",
:all => "Enables all the possible log topics"
}
end
# Logs the given message
#
# @param [String] message The message to be logged.
# @param [Symbol] key Filtering key.
# @param [Symbol] method Logging method (:debug, :info, :etc).
#
# @return [void]
# @example
# # no example
#
def log(message, key = nil, method = :info)
if !key || log_filters.include?(key) || log_filters.include?(:all)
logger.__send__(method, "#{request_log_tag}#{filter_message(message)}")
end
end
# Generates a unique prefix
#
# It adds the prefix to every logged line so that it is easy to identify what log
# message is for what request.
#
# @return [String]
# @example
# # no example
#
def set_unique_prefix
@unique_prefix = RightScale::CloudApi::Utils::random(6)
end
# Resets current prefix
#
# @return [void]
# @example
# # no example
#
def reset_unique_prefix
@unique_prefix = nil
end
# Returns the logging tag
#
# @return [String]
# @example
# # no example
#
def request_log_tag
@unique_prefix._blank? ? "" : "[r:#{@unique_prefix}] "
end
# Filters out all 'secrets' that match to log_filter_patterns
#
# @param [String] message The given message.
#
# @return [String] The original message that has sencitive things filtered out.
#
# @example
# filter_message('my secret password') #=> 'my [FILTERED] password'
#
def filter_message(message)
message = message.dup
log_filter_patterns.each {|pattern| message.gsub!(pattern, '\1[FILTERED]\3')}
message
end
end
end
end
<file_sep>#--
# Copyright (c) 2013 RightScale, Inc.
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# 'Software'), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
# IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
# CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
# SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#++
require File.expand_path(File.dirname(__FILE__)) + "/../spec_helper"
require "base/helpers/query_api_patterns"
module RightScale
module CloudApi
module Test
class FakeRoutine < Routine
def process
@data[:result] = @data.dup
end
end
class ApiManager < RightScale::CloudApi::ApiManager
include RightScale::CloudApi::Mixin::QueryApiPatterns
set_routine FakeRoutine
query_api_pattern :GetService, :get
query_api_pattern :GetResource, :get, 'resource/1'
query_api_pattern :GetResourceWithHardcodedData, :get, 'resource/1',
:params => { 'p1' => 1, 'p2' => 2 },
:headers => { 'x-text-header' => 'my-test-value' },
:body => 'MyTestStringBody'
query_api_pattern :GetResourceWithVars, :get, 'resource/{:ResourceId}',
:params => { 'p1' => :Param1, 'p2' => :Param2 },
:headers => { 'x-text-header' => :MyHeader },
:body => :MyBody
query_api_pattern :GetResourceWithFlexibleVars, :get,'resource/{:ResourceId}/subresource/{:SubresourceId}',
:headers => { 'x-text-header' => "{:MyHeaderSource}/{:MyHeaderKey}" },
:body => "text-{:BodyParam1}-text-again-{:BodyParam2}"
query_api_pattern :GetResourceWithFlexibleVarsAndDefaults, :get,'resource/{:ResourceId}/subresource/{:SubresourceId}',
:headers => { 'x-text-header' => "{:MyHeaderSource}/{:MyHeaderKey}" },
:body => "text-{:BodyParam1}-text-again-{:BodyParam2}",
:defaults => {
:BodyParam2 => Utils::NONE,
:SubresourceId => 2,
:MyHeaderSource => 'something'
}
query_api_pattern :GetResourceWithFlexibleVarsAndDefaultsV2, :get, '',
:body => {
'Key1' => 'Value1',
'Key2' => :Value2,
'Key3' => {
'Key4' => :Value4
}
},
:defaults => {
:Value4 => Utils::NONE,
}
query_api_pattern :GetResourceWithFlexibleVarsAndCollection, :get, '',
:body => {
'Key1' => :Value1,
'Collection[{:Items}]' => {
'Name' => :Name,
'Value' => :Value
},
'Collection2[]' => {
'Name2' => :Name2,
'Value2' => :Value2
}
},
:defaults => {
:Value => 13,
}
query_api_pattern :GetResourceWithSubCollectionReplacement, :get, '',
:body => {
'Key1' => :Value1,
'Collections{:Collections}' => {
'Collection[{:Items}]' => {
'Name' => :Name,
'Value' => :Value
}
}
},
:defaults => {
:Value => 13
}
query_api_pattern :GetResourceWithSubCollectionReplacementAndDefaults, :get, '',
:body => {
'Key1' => :Value1,
'Collections{:Collections}' => {
'Collection[{:Items}]' => {
'Name' => :Name,
'Value' => :Value
}
}
},
:defaults => {
:Value => 13,
:Collections => Utils::NONE
}
query_api_pattern(:GetResourceWithBlock, :get, 'resource/1') do |result|
result[:path] = 'my-new-path'
result[:verb] = :post
result[:params] = {'p1' => 'v1'}
result[:headers] = {'x-my-header' => 'value'}
result[:body] = 'MyBody'
end
query_api_pattern :GetResourceWithProc, :get, 'resource/1',
:after => Proc.new { |result| result[:path] = 'my-new-path'
result[:verb] = :post
result[:params] = {'p1' => 'v1'}
result[:headers] = {'x-my-header' => 'value'}
result[:body] = 'MyBody' }
end
end
end
end
describe "QueryApiPattern" do
before(:each) do
unless @initialized
logger = Logger.new(STDOUT)
logger.level = Logger::INFO
@api_manager = RightScale::CloudApi::Test::ApiManager.new({'x' => 'y'},'endpoint', {:logger => logger})
end
end
context "query_api_pattern" do
it "fails when there is an unexpected parameter" do
expect {
@api_manager.class.query_api_pattern(:GetService, :get, '', :unknown_something => 'blah-blah')
}.to raise_error(RightScale::CloudApi::Error)
end
end
it "works when there are no issues and generates request data properly" do
data = @api_manager.GetService
request = data[:request]
expect(request[:verb]).to eq(:get)
expect(request[:relative_path]._blank?).to be(true)
expect(request[:headers].to_hash._blank?).to be(true)
expect(request[:params]._blank?).to be(true)
expect(request[:body].nil?).to be(true)
end
it "moves all unused variables into URL params" do
data = @api_manager.GetService('Param1' => 'value1', 'Param2' => 'value2')
request = data[:request]
expect(request[:verb]).to eq(:get)
expect(request[:relative_path]._blank?).to be(true)
expect(request[:headers].to_hash._blank?).to be(true)
expect(request[:params]).to eq('Param1' => 'value1', 'Param2' => 'value2')
expect(request[:body]).to be(nil)
end
it "works for GetResource Query API definition" do
data = @api_manager.GetResource
request = data[:request]
expect(request[:verb]).to eq :get
expect(request[:relative_path]).to eq 'resource/1'
expect(request[:headers].to_hash._blank?).to be(true)
expect(request[:params]._blank?).to be(true)
expect(request[:body]).to be(nil)
end
it "works for GetResourceWithHardcodedData Query API definition" do
data = @api_manager.GetResourceWithHardcodedData
request = data[:request]
expect(request[:verb]).to eq :get
expect(request[:relative_path]).to eq 'resource/1'
expect(request[:headers].to_hash).to eq('x-text-header' => ['my-test-value'])
expect(request[:params]).to eq('p1' => 1, 'p2' => 2 )
expect(request[:body]).to eq 'MyTestStringBody'
end
it "works for GetResourceWithVars Query API definition" do
data = @api_manager.GetResourceWithVars( 'ResourceId' => 123, 'Param1' => 11, 'Param2' => 12, 'MyHeader' => 'x-test-something', 'MyBody' => 'MyTestStringBody')
request = data[:request]
expect(request[:verb]).to eq :get
expect(request[:relative_path]).to eq 'resource/123'
expect(request[:headers].to_hash).to eq('x-text-header' => ['x-test-something'])
expect(request[:params]).to eq( 'p1' => 11, 'p2' => 12 )
expect(request[:body]).to eq 'MyTestStringBody'
end
it "fails when a mandatory variable is missing" do
expect{ @api_manager.GetResourceWithVars }.to raise_error(RightScale::CloudApi::Error)
end
it "works for GetResourceWithFlexibleVars Query API definition" do
data = @api_manager.GetResourceWithFlexibleVars( 'ResourceId' => 1, 'SubresourceId' => 2, 'MyHeaderSource' => 3, 'MyHeaderKey' => 4, 'BodyParam1' => 5, 'BodyParam2' => 6)
request = data[:request]
expect(request[:verb]).to eq :get
expect(request[:relative_path]).to eq 'resource/1/subresource/2'
expect(request[:headers].to_hash).to eq('x-text-header' => ['3/4'])
expect(request[:body]).to eq 'text-5-text-again-6'
end
it "works for GetResourceWithFlexibleVarsAndDefaults Query API definition" do
data = @api_manager.GetResourceWithFlexibleVarsAndDefaults('ResourceId' => 1, 'MyHeaderKey' => 3, 'BodyParam1' => 5)
request = data[:request]
expect(request[:verb]).to eq :get
expect(request[:relative_path]).to eq 'resource/1/subresource/2'
expect(request[:headers].to_hash).to eq('x-text-header' => ['something/3'])
expect(request[:body]).to eq 'text-5-text-again-'
end
it "works for GetResourceWithFlexibleVarsAndDefaultsV2 Query API definition" do
data = @api_manager.GetResourceWithFlexibleVarsAndDefaultsV2('Value2' => 1)
request = data[:request]
expect(request[:verb]).to eq :get
expect(request[:relative_path]._blank?).to be(true)
expect(request[:headers].to_hash._blank?).to be(true)
expect(request[:params]._blank?).to be(true)
expect(request[:body]).to eq('Key1' => 'Value1', 'Key2' => 1, 'Key3' => {})
end
it "works for GetResourceWithFlexibleVarsAndCollection Query API definition" do
data = @api_manager.GetResourceWithFlexibleVarsAndCollection('Value1' => 1,
'Items' => [{'Name' => 'x1', 'Value' => 'xv1'}, {'Name' => 'x2'}],
'Collection2' => [{'Name2' => 'x21', 'Value2' => 'xv21'}, {'Name2' => 'x22', 'Value2' => 'v22'}]
)
request = data[:request]
expect(request[:verb]).to eq :get
expect(request[:relative_path]._blank?).to be(true)
expect(request[:headers].to_hash._blank?).to be(true)
expect(request[:params]._blank?).to be(true)
expect(request[:body]).to eq('Key1' => 1,
'Collection' => [{'Name' => 'x1', 'Value' => 'xv1'}, {'Name' => 'x2', 'Value' => 13}],
'Collection2' => [{'Name2' => 'x21', 'Value2' => 'xv21'}, {'Name2' => 'x22', 'Value2' => 'v22'}])
end
it "works for GetResourceWithSubCollectionReplacement Query API definition" do
# Nothing is pased - should complain
expect {
@api_manager.GetResourceWithSubCollectionReplacement('Value1' => 1)
}.to raise_error(RightScale::CloudApi::Error)
# A replacement is passed - must replace
data = @api_manager.GetResourceWithSubCollectionReplacement('Value1' => 1, 'Collections' => 'blah-blah')
request = data[:request]
expect(request[:verb]).to eq :get
expect(request[:relative_path]._blank?).to be(true)
expect(request[:headers].to_hash._blank?).to be(true)
expect(request[:params]._blank?).to be(true)
expect(request[:body]).to eq('Key1' => 1, 'Collections' => 'blah-blah')
data = @api_manager.GetResourceWithSubCollectionReplacement('Value1' => 1, 'Items' => [{'Name' => 'x1', 'Value' => 'xv1'}, {'Name' => 'x2'}])
request = data[:request]
expect(request[:verb]).to eq :get
expect(request[:relative_path]._blank?).to be(true)
expect(request[:headers].to_hash._blank?).to be(true)
expect(request[:params]._blank?).to be(true)
expect(request[:body]).to eq('Key1' => 1, 'Collections' => {'Collection' => [{'Name' => 'x1', 'Value' => 'xv1'}, {'Name' => 'x2', 'Value' => 13}]})
end
it "works for GetResourceWithSubCollectionReplacementAndDefaults Query API definition" do
data = @api_manager.GetResourceWithSubCollectionReplacementAndDefaults('Value1' => 1)
request = data[:request]
expect(request[:verb]).to eq :get
expect(request[:relative_path]._blank?).to be(true)
expect(request[:headers].to_hash._blank?).to be(true)
expect(request[:params]._blank?).to be(true)
expect(request[:body]).to eq('Key1' => 1 )
end
it "works for GetResourceWithBlock Query API definition" do
data = @api_manager.GetResourceWithBlock
request = data[:request]
expect(request[:verb]).to eq :post
expect(request[:relative_path]).to eq 'my-new-path'
expect(request[:headers].to_hash).to eq('x-my-header' => ['value'])
expect(request[:params]).to eq( 'p1' => 'v1')
expect(request[:body]).to eq 'MyBody'
end
it "works for GetResourceWithProc Query API definition" do
data = @api_manager.GetResourceWithProc
request = data[:request]
expect(request[:verb]).to eq :post
expect(request[:relative_path]).to eq 'my-new-path'
expect(request[:headers].to_hash).to eq('x-my-header' => ['value'])
expect(request[:params]).to eq( 'p1' => 'v1')
expect(request[:body]).to eq 'MyBody'
end
end<file_sep>#--
# Copyright (c) 2013 RightScale, Inc.
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# 'Software'), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
# IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
# CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
# SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#++
module RightScale
module CloudApi
# A Wrapper around standard Net::HTTPRsponse class
#
# @api public
#
# The class supports some handy methods for managing the code, the body and the headers.
# And everythig else can be accessed through *raw* attribute that points to the original
# Net::HTTPResponse instance.
#
class HTTPResponse < HTTPParent
# The response code
#
# @return [String]
# @example
# response.code #=> '404'
#
attr_reader :code
# Body bytes to log
BODY_BYTES_TO_LOG = 2000
# Body bytes to log in case of error
BODY_BYTES_TO_LOG_ERROR = 6000
# Constructor
#
# @param [String] code The http response code.
# @param [String,IO,Nil] body The response body.
# @param [Hash] headers The response headers.
# @param [Net::HTTPRequest] raw The original response (optional).
#
# @return [Rightscale::CloudApi::HTTPResponse] A new response instance.
#
# @example
# new('200', 'body', {}, object)
#
def initialize(code, body, headers, raw)
@code = code.to_s
@body = body
@raw = raw
@headers = HTTPHeaders::new(headers)
end
# Returns true if the response code is in the range of 4xx or 5xx
#
# @return [Boolean]
# @example
# response.is_error? #=> false
#
def is_error?
!!(code.is_a?(String) && code.match(/^(5..|4..)/))
end
# Returns true if the response code is in the range of 3xx
#
# @return [Boolean]
# @example
# response.is_redirect? #=> false
#
def is_redirect?
!!(code.is_a?(String) && code.match(/^3..$/))
end
# Returns the response code and code name
#
# @return [String]
# @example
# ec2.response.to_s #=> '200 OK'
#
def to_s
result = code.dup
result << " #{raw.class.name[/Net::HTTP(.*)/] && $1}" if raw.is_a?(Net::HTTPResponse)
result
end
# Displays the body information
#
# @return [String] The body info.
# @example
# ec2.response.body_info #=> 'response boby'
#
def body_info
if is_io? then "#{body.class.name}"
elsif is_error? then "size: #{body.to_s.size}, first #{BODY_BYTES_TO_LOG_ERROR} bytes:\n#{body.to_s[0...BODY_BYTES_TO_LOG_ERROR]}"
else "size: #{body.to_s.size}, first #{BODY_BYTES_TO_LOG} bytes:\n#{body.to_s[0...BODY_BYTES_TO_LOG]}"
end
end
end
end
end<file_sep>#--
# Copyright (c) 2013 RightScale, Inc.
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# 'Software'), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
# IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
# CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
# SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#++
class String
# Constantizes the string.
#
# @return [Class, Module] The constantized class/module.
#
# @raise [NameError] If the name is not in CamelCase or is not initialized.
#
# @example
# "Module"._constantize #=> Module
# "Class"._constantize #=> Class
#
def _constantize
unless /\A(?:::)?([A-Z]\w*(?:::[A-Z]\w*)*)\z/ =~ self
fail(::NameError, "#{self.inspect} is not a valid constant name!")
end
Object.module_eval("::#{$1}", __FILE__, __LINE__)
end
# Camelizes the string.
#
# @param [Boolean] lower_case When set to true it downcases the very first symbol of the string.
#
# @return [String] The camelized string value.
#
# @example
# 'hello_world'._camelize #=> 'HelloWorld'
# 'hello_world'._camelize(true) #=> 'helloWorld'
# 'HelloWorld'._camelize #=> 'HelloWorld'
#
def _camelize(lower_case = false)
words = self.gsub(/([A-Z])/, '_\1').
split(/_|\b/).
map{ |word| word.capitalize }.
reject{ |word| word == '' }
words[0] = words[0].downcase if words[0] && lower_case
words.join('')
end
alias_method :_camel_case, :_camelize
# Underscorizes the string.
#
# @return [String] The camelized string value.
#
# @example
# 'HelloWorld'._underscore #=> 'hello_world'
#
def _snake_case
self.split(/\b/).
map{ |word| word.gsub(/[A-Z]/){ |match| "#{$`=='' ? '' : '_'}#{match.downcase}" } }.
join('')
end
alias_method :_underscore, :_snake_case
# Wraps the string into an array.
#
# @return [Array]
#
# @example
# 'hahaha'._arrayify #=> ['hahaha']
#
def _arrayify
[ self ]
end
# Returns +true+ is the string has zero length or contains spaces only. And it returns +false+
# if the string has any meaningful value.
#
# @return [Boolean]
#
def _blank?
empty? || strip.empty?
end
end
class Object
# Checks if the current object is blank or empty.
# "", " ", nil, [] and {} are assumes as blank.
#
# @return [Boolean] +True+ if the object is blank and +false+ otherwise.
#
def _blank?
case
when respond_to?(:blank?) then blank?
when respond_to?(:empty?) then empty?
else !self
end
end
# Checks if the object has any non-blank value (opposite to Object#_blank?)
#
# @return [Boolean] +True+ if the object has any meaningful value and +false+ otherwise.
#
def _present?
!_blank?
end
# Returns a list of modules an object is extended with.
#
# @return [Array] A list of modules.
#
def _extended
(class << self; self; end).included_modules
end
# Checks whether an object was extended with a module.
#
# @return [Boolean] +True+ if the object is extended with the given module.
#
def _extended?(_module)
_extended.include?(_module)
end
# Wraps the object into an array.
#
# @return [Array]
#
# @example
# nil._arrayify #=> []
# 1._arrayify #=> [1]
# :sym._arrayify #=> [:sym]
#
def _arrayify
Array(self)
end
end
class Array
# Stringifies keys on all the hash items.
#
def _symbolize_keys
map do |item|
item.respond_to?(:_symbolize_keys) ? item._symbolize_keys : item
end
end
# Stringifies keys on all the hash items.
#
def _stringify_keys
map do |item|
item.respond_to?(:_stringify_keys) ? item._stringify_keys : item
end
end
end
class Hash
# Converts the root keys of the hash to symbols.
#
# @return [Hash]
#
def _symbolize_keys
inject({}) do |hash, (key, value)|
new_key = key.respond_to?(:to_sym) ? key.to_sym : key
value = value._symbolize_keys if value.respond_to?(:_symbolize_keys)
hash[new_key] = value
hash
end
end
# Converts the keys of the hash to strings.
#
# @return [Hash]
#
def _stringify_keys
inject({}) do |hash, (key, value)|
new_key = key.to_s if key.respond_to?(:to_s)
value = value._stringify_keys if value.respond_to?(:_stringify_keys)
hash[new_key] = value
hash
end
end
# Extract a value from the hash by its path. The path is a comma-separated list of keys, staring
# from the root key.
#
# @param [Array] path The path to the key. If the very last value is a hash then it is treated as
# a set of options.
#
# The options are:
# - :arrayify Convert the result into Array (unless it is).
# - :default A value to be returned unless the requested key exist.
#
# @yield [] If a block is given and the key is not found then it calls the block.
# @yieldreturn [Object] he block may raise a custom exception or return anything. The returned
# value it used for the method return.
#
# @return [Object] Whatever value the requested key has or the default value.
#
# @example
# {}._at('x','y') #=> Item at "x"->"y" is not found or not a Hash instance (RuntimeError)
# {}._at('x', :default => 'defval') #=> 'defval'
# {}._at('x'){ 'defval' } #=> 'defval'
# {}._at('x'){ fail "NotFound.MyCoolError" } #=> NotFound.MyCoolError (RuntimeError)
# {'x' => nil}._at('x') #=> nil
# {'x' => 4}._at('x') #=> 4
# {'x' => { 'y' => { 'z' => 'value'} } }._at('x', 'y', 'z') #=> 'value'
# {'x' => { 'y' => { 'z' => 'value'} } }._at('x', 'y', 'z', :arrayify => true) #=> ['value']
#
def _at(*path, &block)
path = path.flatten
options = path.last.is_a?(Hash) ? path.pop.dup : {}
key = path.shift
(options[:path] ||= []) << key
if key?(key)
if path._blank?
# We have reached the final key in the list - report it back.
return options[:arrayify] ? self[key]._arrayify : self[key]
end
return self[key]._at(path << options, &block) if self[key].is_a?(Hash)
end
return options[:default] if options.key?(:default)
return block.call if block
fail(StandardError.new("Item at #{options[:path].map{|i| i.inspect}.join('->')} is not found or not a Hash instance"))
end
# Extracts a value from the hash by its path and arrayifies it.
#
# @param [Array] path The path to the key. If the very last value is a hash then it is treated as
# a set of options.
#
# @return [Array] Single item array with whatever value the requested key has.
#
# @example
# {}._arrayify_at('x', 'y', 'z') #=> []
# { 'x' => { 'y' => { 'z' => 'value'} }}._arrayify_at('x', 'y', 'z') #=> ['value']
#
#
def _arrayify_at(*path)
_at(path << { :arrayify => true, :default => [] })
end
# Wraps the hash into an array.
#
# @return [Array]
#
# @example
# {1 => 2}._arrayify #=> [{1 => 2}]
#
def _arrayify
[ self ]
end
end
<file_sep>#--
# Copyright (c) 2013 RightScale, Inc.
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# 'Software'), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
# IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
# CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
# SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#++
require File.expand_path(File.dirname(__FILE__)) + "/../spec_helper"
describe "support.rb" do
# --- String ---
context "String#_constantize" do
it "constantizes when a string points to an existing class/module name" do
class MyCoolTestConstantizeClass; end
expect('MyCoolTestConstantizeClass'._constantize).to be MyCoolTestConstantizeClass
end
it "fails when a string points to a non-existing class/module name" do
expect {
'MyBadTestConstantizeClass'._constantize
}.to raise_error(::NameError)
end
end
context "String#_camelize" do
it "camelizes a string" do
expect('my_test_string'._camelize).to eq'MyTestString'
expect('MyTestString'._camelize).to eq 'MyTestString'
expect('my_test_string'._camelize(:lower_case)).to eq 'myTestString'
expect('MyTestString'._camelize(:lower_case)).to eq 'myTestString'
expect('Privet, how are you_doing, los_Amigos?'._camelize).to eq 'Privet, How Are YouDoing, LosAmigos?'
end
end
context "String#_snake_case" do
it "underscorizes a string" do
expect('MyTestString'._snake_case).to eq 'my_test_string'
expect('my_test_string'._snake_case).to eq 'my_test_string'
expect('Privet, How Are YouDoing, LosAmigos?'._snake_case).to eq 'privet, how are you_doing, los_amigos?'
end
end
context "String#_arrayify" do
it "arrayifies into array" do
expect(''._arrayify).to eq ['']
expect('something'._arrayify).to eq ['something']
end
end
context "String#_blank?" do
it "returns true when it has zero size" do
expect(''._blank?).to be true
end
it "returns true when it contains spaces only" do
expect(" \n\n\n "._blank?).to be true
end
it "returns false when it has anything valueble" do
expect("something"._blank?).to be false
end
end
# --- Object ---
context "Object#_blank?" do
it "checks if an object responds blank?" do
object = Object.new
expect(object).to receive(:blank?).once.and_return(true)
expect(object).to receive(:respond_to?).with(:blank?).once.and_return(true)
expect(object._blank?).to be true
end
it "checks if an object responds empty? unles it responds to blank?" do
object = Object.new
expect(object).to receive(:empty?).once.and_return(true)
expect(object).to receive(:respond_to?).with(:blank?).once.and_return(false)
expect(object).to receive(:respond_to?).with(:empty?).once.and_return(true)
expect(object._blank?).to be true
end
it "returns !self unless it responds to blank? and empty?" do
object = Object.new
expect(object).to receive(:respond_to?).with(:blank?).once.and_return(false)
expect(object).to receive(:respond_to?).with(:empty?).once.and_return(false)
expect(object._blank?).to eq !object
end
end
context "Object#_arrayify" do
it "feeds self to Array()" do
[nil, 1, :symbol].each do |object|
expect(object._arrayify).to eq Array(object)
end
end
end
# --- NilClass ---
context "NilClass" do
it "always return true" do
expect(nil._blank?).to be true
end
end
# --- FalseClass ---
context "FalseClass" do
it "always return true" do
expect(false._blank?).to be true
end
end
# --- TrueClass ---
context "FalseClass" do
it "always return false" do
expect(true._blank?).to be false
end
end
# --- Array ---
context "Array#_blank?" do
it "behaves accordingly to array's emptyness status" do
expect([]._blank?).to be true
expect([1]._blank?).to be false
end
end
context "Array#_stringify_keys" do
it "stringifies all the keys for all its hash items" do
expect([[{:x=>{:y=>[:z => 13]}}]]._stringify_keys).to eq [[{"x"=>{"y"=>[{"z"=>13}]}}]]
end
end
context "Array#_stringify_keys" do
it "symbolizes all the keys for all its hash items" do
expect([[{"x"=>{"y"=>[{"z"=>13}]}}]]._symbolize_keys).to eq [[{:x=>{:y=>[:z => 13]}}]]
end
end
# --- Hash ---
context "Hash#_blank?" do
it "behaves accordingly to hash's emptyness status" do
expect({}._blank?).to be true
expect({:foo => :bar}._blank?).to be false
end
end
context "Hash#_stringify_keys" do
it "stringifies all the keys" do
expect({"1"=>2, :x=>[[{:y=>{:z=>13}}], 2]}._stringify_keys).to eq("1"=>2, "x"=>[[{"y"=>{"z"=>13}}], 2])
end
end
context "Hash#_symbolize_keys" do
it "symbolizes all keys" do
expect({"1"=>2, "x"=>[[{"y"=>{"z"=>13}}], 2]}._symbolize_keys).to eq(:"1"=>2, :x=>[[{:y=>{:z=>13}}], 2])
end
end
context "Hash#_at" do
it "fails if the given path does not not exist" do
expect { {}._at('x','y') }.to raise_error(StandardError)
end
it "does not fail if the given path does not exist but a default value is provided" do
expect({}._at('x', :default => 'defval')).to eq 'defval'
end
it "calls a block if the given path does not exist and a default value is not provided" do
expect({}._at('x'){ 'defval' }).to eq 'defval'
expect{ {}._at('x'){ fail "NotFound.MyCoolError" }}.to raise_error(RuntimeError, "NotFound.MyCoolError")
end
it "returns the requested value by the given path when the path exists" do
expect({'x' => nil}._at('x')).to be nil
expect({'x' => 4}._at('x')).to eq 4
expect({'x' => { 'y' => { 'z' => 'value'} }}._at('x', 'y', 'z')).to eq 'value'
end
it "arrayifies the result when :arrayify => true option is set" do
expect({'x' => { 'y' => { 'z' => 'value'} }}._at('x', 'y', 'z', :arrayify => true)).to eq ['value']
end
end
context "Hash#_arrayify_at" do
it "extracts a value by the given path and arrayifies it" do
expect({'x' => { 'y' => 'z' }}._arrayify_at('x', 'y')).to eq ['z']
expect({'x' => { 'y' => ['z'] }}._arrayify_at('x', 'y')).to eq ['z']
end
end
context "Hash#_arrayify" do
it "wraps self into array" do
hash = { 1 => 2}
expect(hash._arrayify).to eq [hash]
end
end
end<file_sep>#--
# Copyright (c) 2013 RightScale, Inc.
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# 'Software'), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
# IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
# CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
# SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#++
require File.expand_path(File.dirname(__FILE__)) + "/../spec_helper"
describe "RightScale::CloudApi::ResponseAnalyzer" do
before(:each) do
logger = Logger.new(STDOUT)
logger.level = Logger::INFO
@responseanalyzer = RightScale::CloudApi::ResponseAnalyzer.new
@test_data = {}
@test_data[:request] = { :verb => 'some_verb', :orig_params => {}, :instance => 'some_request'}
@test_data[:vars] = { :retry => {} }
@test_data[:options] = {:error_patterns => [], :cloud_api_logger => RightScale::CloudApi::CloudApiLogger.new(
{:logger => logger, :log_filters => [:response_analyzer, :response_analyzer_body_error]})
}
@close_current_connection_callback = double
@test_data[:callbacks] = {:close_current_connection => @close_current_connection_callback}
@test_data[:connection] = {}
allow(@responseanalyzer).to receive(:log)
end
context "with no error patterns" do
it "fails on 5xx, 4xx errors" do
[500, 400].each do |http_error|
@test_data[:response] = {:instance => generate_http_response(http_error)}
expect { @responseanalyzer.execute(@test_data) }.to raise_error(RightScale::CloudApi::HttpError)
end
end
it "fails on redirect when there is no location tin the response" do
@test_data[:response] = {:instance => generate_http_response(300)}
expect { @responseanalyzer.execute(@test_data) }.to raise_error(RightScale::CloudApi::HttpError)
end
it "works for 2xx codes" do
@test_data[:response] = {:instance => generate_http_response(200)}
expect { @responseanalyzer.execute(@test_data) }.to_not raise_error
end
end
context "when retry is requested" do
before(:each) do
error_patterns = [{:action => :retry}]
@test_data[:options][:error_patterns] = error_patterns
allow(RightScale::CloudApi::Utils).to receive(:pattern_matches?).and_return(true)
end
it "raises a retry attempt exception for 4xx and 5xx errors" do
[500, 400].each do |http_error|
@test_data[:response] = {:instance => generate_http_response(http_error)}
expect { @responseanalyzer.execute(@test_data) }.to raise_error(RightScale::CloudApi::RetryAttempt)
end
end
it "fails when there is no location for 3xx redirect" do
response = generate_http_response(301, 'body', {'location' => ''})
@test_data[:response] = {:instance => response}
expect { @responseanalyzer.execute(@test_data) }.to raise_error(RightScale::CloudApi::HttpError)
end
it "raises a retry attempt exception when there is a location (in headers) for 3xx redirect" do
response = generate_http_response(301, 'body', {'location' => 'www.some-new-location.com'})
@test_data[:response] = {:instance => response}
expect { @responseanalyzer.execute(@test_data) }.to raise_error(RightScale::CloudApi::RetryAttempt)
end
it "raises a retry attempt exception when there is a location (in body) for 3xx redirect" do
response = generate_http_response(301, '<Endpoint> www.some-new-location.com </Endpoint>', {'location' => ''})
@test_data[:response] = {:instance => response}
uri_object = double(:host= => 'www.some-new-location.com', :to_s => 'www.some-new-location.com')
@test_data[:connection][:uri] = uri_object
expect { @responseanalyzer.execute(@test_data) }.to raise_error(RightScale::CloudApi::RetryAttempt)
end
end
context "when reconnect_and_retry is requested" do
before(:each) do
@test_data[:options][:error_patterns] = [{:action => :reconnect_and_retry}]
expect(RightScale::CloudApi::Utils).to receive(:pattern_matches?).at_least(1).and_return(true)
expect(@close_current_connection_callback).to receive(:call).twice.with(/Error code/)
end
it "raises a retry attempt exception for 4xx and 5xx errors" do
[500, 400].each do |http_error|
@test_data[:response] = {:instance => generate_http_response(http_error)}
expect { @responseanalyzer.execute(@test_data) }.to raise_error(RightScale::CloudApi::RetryAttempt)
end
end
end
context "when disconnect_and_abort is requested" do
before(:each) do
@test_data[:options][:error_patterns] = [{:action => :disconnect_and_abort}]
expect(RightScale::CloudApi::Utils).to receive(:pattern_matches?).at_least(1).and_return(true)
expect(@close_current_connection_callback).to receive(:call).twice.with(/Error code/)
end
it "failse for 4xx and 5xx errors" do
[500, 400].each do |http_error|
@test_data[:response] = {:instance => generate_http_response(http_error)}
expect { @responseanalyzer.execute(@test_data) }.to raise_error(RightScale::CloudApi::HttpError)
end
end
end
context "when abort is requested" do
before(:each) do
@test_data[:options][:error_patterns] = [{:action => :abort}]
expect(RightScale::CloudApi::Utils).to receive(:pattern_matches?).at_least(1).and_return(true)
expect(@close_current_connection_callback).to receive(:call).never
end
it "failse for 4xx and 5xx errors" do
[500, 400].each do |http_error|
@test_data[:response] = {:instance => generate_http_response(http_error)}
expect { @responseanalyzer.execute(@test_data) }.to raise_error(RightScale::CloudApi::HttpError)
end
end
end
end
<file_sep>#--
# Copyright (c) 2013 RightScale, Inc.
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# 'Software'), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
# IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
# CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
# SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#++
module RightScale
module CloudApi
# The parent class for HTTPRequest and HTTPResponse.
#
# @api public
#
# The class defines generic methods that are used by both Request and Response classes.
#
class HTTPParent
# Returns Net::HTTPResponse object
#
# @return [Net::HTTPResponse]
# @example
# # no example
#
attr_accessor :raw
# Returns the response body
#
# @return [String,nil]
# @example
# # no example
#
attr_accessor :body
# Returns all the headers for the current request/response instance
#
# @return [Hash] The set of headers.
# @example
# # no example
#
def headers
@headers.to_hash
end
# Retrieves the given header values
#
# @param [Hash] header The header name.
# @return [Array] The Array of values for the header.
#
# @example
# # no example
#
def [](header)
@headers[header]
end
# Returns true if the current object's body is an IO instance
#
# @return [Boolean] True if it is an IO and false otherwise.
#
# @example
# is_io? #=> false
#
def is_io?
body.is_a?(IO) || body.is_a?(Net::ReadAdapter)
end
# Displays the current headers in a nice way
#
# @return [String]
#
# @example
# ec2.response.headers_info #=>
# 'content-type: "text/xml;charset=UTF-8", server: "AmazonEC2", something: ["a", "b"]'
#
def headers_info
@headers.to_s
end
end
end
end
<file_sep>#--
# Copyright (c) 2013 RightScale, Inc.
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# 'Software'), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
# IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
# CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
# SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#++
module RightScale
module CloudApi
# Mixins namespace
#
# @api public
#
module Mixin
# Query API namespace
module QueryApiPatterns
# Standard included
#
# @return [void]
# @example
# # no example
#
def self.included(base)
base.extend(ClassMethods)
end
# Query API patterns help one to simulate the Query API type through the REST API
#
# When the REST API is powerfull enough it is not easy to code it becaue one have to worry
# about the path, the URL parameters, the headers and the body, when in the QUERY API
# all you need to worry about are the URL parameters.
#
# The patterns described below help you to build methods that will take a linear set of
# parameters (usially) a hash and put then into the proper positions into the URL, headers or
# body.
#
# TODO :add an example that would compare REST vs QUERY calls
#
# @example
# # Add a QUERY methods pattern:
#
# query_api_pattern 'MethodName', :verb, 'path', UnifiedParams+:params+:headers+:body+:options+:before+:after do |args|
# puts args # where args is a Hash: { :verb, :path, :opts, :manager }
# ...
# return args # where args is a Hash: { :verb, :path, :opts [, :manager] }
# end
#
# There are 2 ways to define a Query API pattern:
#
# 1. Manager class level:
# We could use this when we define a new cloud handler. I dont see any
# use case right now because we can implement all we need now using the
# second way and Wrappers.
#
# @example
# module MyCoolCloud
# class ApiManager < CloudApi::ApiManager
# query_api_pattern 'ListBuckets', :get
#
# query_api_pattern 'PutObject', :put, '{:Bucket}/{:Object}',
# :body => Utils::MUST_BE_SET,
# :headers => { 'content-type' => ['binary/octet-stream'] }
# ..
# end
# end
#
# 2. Manager instance level: this is where Wrappers come.
#
# @example
# module MyCoolCloud
# module API_DEFAULT
# def self.extended(base)
# base.query_api_pattern 'ListBuckets', :get
#
# base.query_api_pattern 'ListMyCoolBucket', :get do |args|
# args[:path] = 'my-cool-bucket'
# args
# end
#
# base.query_api_pattern 'PutObject', :put, '{:Bucket:}/{:Object:}',
# :body => Utils::MUST_BE_SET,
# :headers => { 'content-type' => ['binary/octet-stream'] }
#
# base.query_api_pattern 'UploadPartCopy', :put,'{:DestinationBucket}/{:DestinationObject}',
# :params => { 'partNumber' => :PartNumber, 'uploadId' => :UploadId },
# :headers => { 'x-amz-copy-source' => '{:SourceBucket}/{:SourceObject}' }
# ..
# end
# end
# end
#
# @example
# Use case examples:
# s3.MethodName(UnifiedParams+:params+:headers+:body+:options+:path+:verb)
#
# @example
# # List all buckets
# s3.ListBuckets
#
# @example
# # Put object binary
# s3.PutObject({'Bucket' => 'xxx', 'Object => 'yyy'}, :body => 'Hahaha')
#
# @example
# # UploadCopy
# s3.UploadPartCopy( 'SourceBucket' => 'xxx',
# 'SourceObject => 'yyy',
# 'DestinationBucket' => 'aaa',
# 'DestinationObject' => 'bbb',
# 'PartNumber' => 134,
# 'UploadId' => '111111',
# 'foo_param' => 'foo',
# 'bar_param' => 'bar' )
#
module ClassMethods
# The method returns a list of pattternd defined in the current class
#
# @return [Array] The arrays of patterns.
# @example
# # no example
#
def query_api_patterns
@query_api_patterns ||= {}
end
# Defines a new query pattern
#
# @param [String] method_name The name of the new QUERY-like method;
# @param [String] verb The HTTP verb.
# @param [String] path The path pattern.
# @param [Hash] opts A set of extra parameters.
# @option opts [Hash] :params Url parameters pattern.
# @option opts [Hash] :headers HTTP headers pattern.
# @option opts [Hash] :body HTTP request body pattern.
# @option opts [Proc] :before Before callback.
# @option opts [Hash] :after After callback.
# @option opts [Hash] :defaults A set of default variables.
# @option opts [Hash] :options A set of extra options.
#
# TODO: :explain options, callbacks, etc
#
# @return [void]
# @example
# # no example
#
def query_api_pattern(method_name, verb, path='', opts={}, storage=nil, &block)
opts = opts.dup
method_name = method_name.to_s
storage ||= query_api_patterns
before = opts.delete(:before)
after = opts.delete(:after) || block
defaults = opts.delete(:defaults) || {}
params = opts.delete(:params) || {}
headers = opts.delete(:headers) || {}
options = opts.delete(:options) || {}
options[:method_name] = method_name
body = opts.delete(:body) || nil
# Complain if there are any unused keys left.
fail(Error.new("#{method_name.inspect} pattern: unsupported key(s): #{opts.keys.map{|k| k.inspect}.join(',')}")) if opts.any?
# Store the new pattern.
storage[method_name] = {
:verb => verb.to_s.downcase.to_sym,
:path => path.to_s,
:before => before,
:after => after,
:defaults => defaults,
:params => params,
:headers => HTTPHeaders::new(headers),
:options => options,
:body => body }
end
end
# Returns the list of current patterns
#
# The patterns can be defined at the class levels or/and in special Wrapper modules.
# The patterns defined at the class levels are always inherited by the instances of this
# class, when the wrapper defined patterns are applied to this particular object only.
#
# This allows one to define generic patterns at the class level and somehow specific
# at the level of wrappers.
#
# @return [Array] The has of QUERY-like method patterns.
# @example
# # no example
#
# P.S. The method is usually called in Wrapper modules (see S3 default wrapper)
#
def query_api_patterns
@query_api_patterns ||= {}
# The current set of patterns may override whatever is defined at the class level.
self.class.query_api_patterns.merge(@query_api_patterns)
end
# Explains the given pattern by name
#
# (Displays the pattern definition)
#
# @param [String] pattern_name The pattern method name.
# @return [Stringq]
#
# @example
# puts open_stack.explain_query_api_pattern('AttachVolume') #=>
# AttachVolume: POST 'servers/{:id}/os-volume_attachments'
# - body : {:volumeAttachment=>{"volumeId"=>:volumeId, "device"=>:device}}
#
def explain_query_api_pattern(pattern_name)
pattern_name = pattern_name.to_s
result = "#{pattern_name}: "
pattern = query_api_patterns[pattern_name]
unless pattern
result << 'does not exist'
else
result << "#{pattern[:verb].to_s.upcase} '#{pattern[:path]}'"
[:params, :headers, :options, :body, :before, :after].each do |key|
result << ("\n - %-8s: #{pattern[key].inspect}" % key.to_s) unless pattern[key]._blank?
end
end
result
end
# Set object specific QUERY-like pattern
#
# This guy is usually called from Wrapper's module from self.extended method (see S3 default wrapper)
#
# @return [void]
# @example
# # no example
#
def query_api_pattern(method_name, verb, path='', opts={}, &block)
self.class.query_api_pattern(method_name, verb, path, opts, @query_api_patterns, &block)
end
# Build request based on the given set of variables and QUERY-like api pattern
#
# @api private
#
# @param [String] query_pattern_name The QUERY-like pattern name.
# @param [param_type] query_params A set of options.
#
# @yield [block_params] block_description
# @yieldreturn [block_return_type] block_return_description
#
# @return [return] return_description
# @example
# # no example
#
# @raise [error] raise_description
#
def compute_query_api_pattern_based_params(query_pattern_name, query_params={})
# fix a method name
pattern = query_api_patterns[query_pattern_name.to_s]
# Complain if we dont know the method
raise PatternNotFoundError::new("#{query_pattern_name.inspect} pattern not found") unless pattern
# Make sure we got what we expected
query_params ||= {}
raise Error::new("Params must be Hash but #{query_params.class.name} received.") unless query_params.is_a?(Hash)
# Make a new Hash instance from the incoming Hash.
# Do not clone because we don't want to have HashWithIndifferentAccess instance or
# something similar because we need to have Symbols and Strings separated.
query_params = Hash[query_params]
opts = {}
opts[:body] = query_params.delete(:body)
opts[:headers] = query_params.delete(:headers) || {}
opts[:options] = query_params.delete(:options) || {}
opts[:params] = query_params._stringify_keys
opts[:manager] = self
request_opts = compute_query_api_pattern_request_data(query_pattern_name, pattern, opts)
# Try to use custom :process_rest_api_request method first because some auth things
# may be required.
# (see OpenStack case) otherwise use standard :process_api_request method
{ :method => respond_to?(:process_rest_api_request) ? :process_rest_api_request : :process_api_request,
:verb => request_opts.delete(:verb),
:path => request_opts.delete(:path),
:opts => request_opts }
end
private :compute_query_api_pattern_based_params
# Execute pattered method if it exists
#
# @raise [PatternNotFoundError]
#
# @return [Object]
# @example
# # no example
#
def invoke_query_api_pattern_method(method_name, *args, &block)
computed_data = compute_query_api_pattern_based_params(method_name, args.first)
# Make an API call:
__send__(computed_data[:method],
computed_data[:verb],
computed_data[:path],
computed_data[:opts],
&block)
end
# Create custom method_missing method
#
# If the called method is not explicitly defined then it tries to find the method definition
# in the QUERY-like patterns. And if the method is there it builds a request based on the
# pattern definition.
#
# @return [Object]
# @example
# # no example
#
def method_missing(method_name, *args, &block)
begin
invoke_query_api_pattern_method(method_name, *args, &block)
rescue PatternNotFoundError
super
end
end
FIND_KEY_REGEXP = /\{:([a-zA-Z0-9_]+)\}/
FIND_COLLECTION_1_REGEXP = /\[\{:([a-zA-Z0-9_]+)\}\]/
FIND_COLLECTION_2_REGEXP = /^([^\[]+)\[\]/
FIND_REPLACEMENT_REGEXP = /\{:([a-zA-Z0-9_]+)\}(?!\])/
FIND_BLANK_KEYS_TO_REMOVE = /\{!remove-if-blank\}/
# Prepares patters params
#
# @api private
#
# Returns a hash of parameters (:params, :options, :body, :headers, etc) that will
# used for making an API request.
#
# @return [Hash]
# @example
# # no example
#
def compute_query_api_pattern_request_data(method_name, pattern, opts={}) # :nodoc:
container = opts.dup
container[:verb] ||= pattern[:verb]
container[:path] ||= pattern[:path]
container[:error] ||= Error
[ :params, :headers, :options, :defaults ].each do |key|
container[key] ||= {}
container[key] = (pattern[key] || {}).merge(container[key])
end
container[:defaults] = container[:defaults]._stringify_keys
container[:headers] = HTTPHeaders::new(container[:headers])
# Call "before" callback (if it is)
pattern[:before].call(container) if pattern[:before].is_a?(Proc)
# Mix default variables into the given set of variables and
# initialize the list of used variables.
container[:params_with_defaults] = container[:defaults].merge(container[:params])
used_params = []
# Compute: Path, UrlParams,Headers and Body
compute_query_api_pattern_path(method_name, container, used_params)
compute_query_api_pattern_headers(method_name, container, used_params)
compute_query_api_pattern_body(method_name, container, used_params, pattern)
compute_query_api_pattern_params(method_name, container, used_params)
# Delete used query params. The params that are left will go into URL params set later.
used_params.each do |key|
container[:params].delete(key.to_s)
container[:params].delete(key.to_sym)
end
container.delete(:params_with_defaults)
# Call "after" callback (if it is)
pattern[:after].call(container) if pattern[:after].is_a?(Proc)
# Remove temporary variables.
container.delete(:error)
container.delete(:manager)
#
container
end
private :compute_query_api_pattern_request_data
# Computes the path for the API request
#
# @api private
#
# @param [String] query_api_method_name Auery API like pattern name.
# @param [Hash] container The container for final parameters.
# @param [Hash] used_query_params The list of used variables.
#
# @return [String] The path.
# @example
# # no example
#
def compute_query_api_pattern_path(query_api_method_name, container, used_query_params)
container[:path] = compute_query_api_pattern_param(query_api_method_name, container[:path], container[:params_with_defaults], used_query_params)
end
private :compute_query_api_pattern_path
# Computes the set of URL params for the API request
#
# @api private
#
# @param [String] query_api_method_name Auery API like pattern name.
# @param [Hash] container The container for final parameters.
# @param [Hash] used_query_params The list of used variables.
#
# @return [Hash] The set of URL params.
# @example
# # no example
#
def compute_query_api_pattern_params(query_api_method_name, container, used_query_params)
container[:params] = compute_query_api_pattern_param(query_api_method_name, container[:params], container[:params_with_defaults], used_query_params)
end
private :compute_query_api_pattern_params
# Computes the set of headers for the API request
#
# @api private
#
# @param [String] query_api_method_name Auery API like pattern name.
# @param [Hash] container The container for final parameters.
# @param [Hash] used_query_params The list of used variables.
#
# @return [Hash] The set of HTTP headers.
# @example
# # no example
#
def compute_query_api_pattern_headers(query_api_method_name, container, used_query_params)
container[:headers].dup.each do |header, header_values|
container[:headers][header].each_with_index do |header_value, idx|
container[:headers][header] = container[:headers][header].dup
container[:headers][header][idx] = compute_query_api_pattern_param(query_api_method_name, header_value, container[:params_with_defaults], used_query_params)
container[:headers][header].delete_at(idx) if container[:headers][header][idx] == Utils::NONE
end
end
end
private :compute_query_api_pattern_headers
# Computes the body value for the API request
#
# @api private
#
# @param [String] query_api_method_name Auery API like pattern name.
# @param [Hash] container The container for final parameters.
# @param [Hash] used_query_params The list of used variables.
# @param [Hash] pattern The pattern.
#
# @return [Hash,String] The HTTP request body..
# @example
# # no example
#
def compute_query_api_pattern_body(query_api_method_name, container, used_query_params, pattern)
if container[:body].nil? && !pattern[:body].nil?
# Make sure body is not left blank when it must be set
fail(Error::new("#{query_api_method_name}: body parameter must be set")) if pattern[:body] == Utils::MUST_BE_SET
container[:body] = compute_query_api_pattern_param(query_api_method_name, pattern[:body], container[:params_with_defaults], used_query_params)
end
end
private :compute_query_api_pattern_body
# Computes single Query API pattern parameter
#
# @param [String] query_api_method_name Auery API like pattern name.
# @param [Hash] source The param to compute/parse.
# @param [Hash] used_query_params The list of used variables.
# @param [Hash] params_with_defaults The set of parameters passed by a user + all the default
# values defined in wrappers.
#
# @return [Object]
# @example
# # no example
#
def compute_query_api_pattern_param(query_api_method_name, source, params_with_defaults, used_query_params) # :nodoc:
case
when source.is_a?(Hash) then compute_query_api_pattern_hash_data(query_api_method_name, source, params_with_defaults, used_query_params)
when source.is_a?(Array) then compute_query_api_pattern_array_data(query_api_method_name, source, params_with_defaults, used_query_params)
when source.is_a?(Symbol) then compute_query_api_pattern_symbol_data(query_api_method_name, source, params_with_defaults, used_query_params)
when source.is_a?(String) then compute_query_api_pattern_string_data(query_api_method_name, source, params_with_defaults, used_query_params)
else source
end
end
#-----------------------------------------
# Query API pattents: HASH
#-----------------------------------------
# Parses Query API replacements
#
# @api private
#
# You may define a key so that is has a default value but you may override it if you
# provide another "replacement" key.
#
# The replacement key is defined as "KeyToSentToCloud{:ReplacementKeyName}" string and
# it will send 'KeyToSentToCloud' with the value taken from 'ReplacementKeyName' if
# 'ReplacementKeyName' is provided.
#
# @param [Hash] params_with_defaults A set API call parameters.
# @param [Array] used_params An array that lists all the paramaters names who were already
# somehow used for this api call. All the unused params wil go into URL params
# @param [String] key The current key.
# @param [Object] value The current value,
# @param [Hash] result The resulting hash that has all the transformed params.
#
# @return [Array] The updated key name and its value
#
# @example:
# # Example 1: simple case.
# query_api_pattern 'CreateServer', :post, 'servers',
# :body => {
# Something{:Replacemet} => {'X' => 1, 'Y' => 2}
# }
#
# # 1.a
# api.CreateServer #=>
# # it will set request body to:
# # { Something => {'X' => 1, 'Y' => 2} }
#
# # 1.b
# api.CreateServer('Replacement' => 'hahaha' ) #=>
# # it will set request body to:
# # { Something => 'hahaha' }
#
# # Example 2: complex case:
# query_api_pattern :MyApiCallName, :get, '',
# :body => {
# 'Key1' => :Value1,
# 'Collections{:Replacement}' => { # <-- The key with Replacement
# 'Collection[{:Items}]' => {
# 'Name' => :Name,
# 'Value' => :Value
# }
# }
# },
# :defaults => {
# :Key1 => 'hoho',
# :Collections => Utils::NONE
# }
#
# # 2.a No parameters are provided
# api.MyApiCallName #=>
# # it will set request body to:
# # { 'Key1' => 'hoho' }
#
# # 2.b Some parameters are provided:
# api.MyApiCallName('Key1' => 'woohoo', 'Items' => [ {'Name' => 'a', 'Value' => 'b'},
# {'Name' => 'b', 'Value' => 'c'} ]) #=>
# # it will set request body to:
# # { 'Key1' => 'woohoo',
# # 'Collections' =>
# # {'Collection' =>
# # [ {'Name' => 'a', 'Value' => 'b'},
# # {'Name' => 'c', 'Value' => 'd'} ] } }
# #
#
# # 2.c Areplacement key is provided:
# api.MyApiCallName('Key1' => 'ahaha', 'Replacement' => 'oooops') #=>
# # it will set request body to:
# # { 'Key1' => 'ahaha',
# 'Collections' => 'oooops' }
#
def parse_query_api_pattern_replacements(params_with_defaults, used_params, key, value, result)
# Test the current key if it has a replacement mark or not.
# If not then we do nothing.
replacement_key = key[FIND_REPLACEMENT_REGEXP] && $1
if replacement_key
# If it is a key with a possible replacement then we should exract the replacement
# variable name from the key:
# so that 'CloudKeyName{:ReplacementKeyName}' should transform into:
# key -> 'CloudKeyName' and replacement_key -> 'ReplacementKeyName'.
#
result.delete(key)
key = key.sub(FIND_REPLACEMENT_REGEXP, '')
if params_with_defaults.has_key?(replacement_key)
# If We have 'ReplacementKeyName' passed by a user or set by default then we should use
# its value otherwise we keep the original value that was defined for 'CloudKeyName'.
#
# Anyway the final key name is 'CloudKeyName'.
#
value = params_with_defaults[replacement_key]
used_params << replacement_key
end
end
[key, value]
end
private :parse_query_api_pattern_replacements
# Collections
#
# @api private
#
# The simple definition delow tells us that parameters will have a key named "CloudKeyName"
# which will point to an Array of Hashes. Where every hash will have keys: 'Key' and 'Value'
#
# @param [String] method_name The name of the pattern.
# @param [Hash] params_with_defaults A set API call parameters.
# @param [Array] used_params An array that lists all the paramaters names who were already
# somehow used for this api call. All the unused params wil go into URL params
# @param [String] key The current key.
# @param [Object] value The current value,
# @param [Hash] result The resulting hash that has all the transformed params.
#
# @return [Array] The updated key name and its value
#
# @raise [Error] If things go wrong in the method.
#
# @example
# # Example 1: Simple Collection definition:
#
# query_api_pattern :MyApiCallName, :get, '',
# :body => {
# 'CloudKeyName[]' => {
# 'Name' => :Key,
# 'State' => :Value
# }
# }
#
# api.MyApiCallName('CloudKeyName' => [{'Key' => 1, 'Value' => 2},
# {'Key' => 3, 'Value' => 4}]) #=>
# # it will set request body to:
# # 'CloudKeyName' => [
# # {'Name' => 1, 'State' => 2},
# # {'Name' => 3, 'State' => 4} ]
#
# The collection may comsume values from a parameter that has name differet from the
# 'CloudKeyName' in the example above:
#
# @example
# # Example 2: Simple Collection definition:
#
# query_api_pattern :MyApiCallName, :get, '',
# :body => {
# 'CloudKeyName[{:Something}]' => {
# 'Name' => :Key,
# 'State' => :Value
# }
# }
#
# api.MyApiCallName('Something' => [{'Key' => 1, 'Value' => 2},
# {'Key' => 3, 'Value' => 4}]) #=>
# # it will set request body to the same value as above:
# # 'CloudKeyName' => [
# # {'Name' => 1, 'State' => 2},
# # {'Name' => 3, 'State' => 4} ]
#
# You can nest the collections:
#
# @example
# query_api_pattern :MyApiCallName, :get, '',
# :body => {
# 'CloudKeyName[]' => {
# 'Name' => :Key,
# 'States[]' => {
# 'SubState' => :SubKey,
# 'FixedKey' => 13
# }
# }
# }
#
# api.MyApiCallName('CloudKeyName' => [{'Key' => 1,
# 'States' => [{'SubState' => 'x'},
# {'SubState' => 'y'},
# {'SubState' => 'y'}]},
# {'Key' => 3,
# 'States' => {'SubState' => 'a'}}])
#
# If a collection was defined with the default value == Utils::NONE it will remove
# the collection key from the final hash of params unless any collection items were passed.
#
# query_api_pattern :MyApiCallName, :get, '',
# :body => {
# 'CloudKeyName[]' => {
# 'Name' => :Key,
# 'State' => :Value
# }
# },
# :defaults => Utils::NONE
#
# api.MyApiCallName() #=>
# # it will set request body to: {}
#
def parse_query_api_pattern_collections(method_name, params_with_defaults, used_params, key, value, result)
# Parse complex collection: KeyName[{:VarName}]'
collection_key = key[FIND_COLLECTION_1_REGEXP] && $1
# Parse simple collection: KeyName[]'
collection_key ||= key[FIND_COLLECTION_2_REGEXP] && $1
# Do nothing unless there is a collection key detected
if collection_key
# Delete the original key from the resulting hash because it has collection crap in it.
sub_pattern = result.delete(key)
# Extract the real key from the original mixed collection key.
# in the case of:
# - 'KeyName[{:VarName}]' the real key is 'KeyName' and the collection key is 'VarName';
# - 'KeyName[]' the real key and the collection key are both 'KeyName'.
key = key[/^[^\[]*/]
# If a user did not pass collection key and the key has not been given a default value
# when the current pattern was defined we should fail.
fail Error::new("#{method_name}: #{collection_key.inspect} is required") unless params_with_defaults.has_key?(collection_key)
# Grab the values for the collection from what the user sent of from the default defs.
value = params_with_defaults[collection_key]
# Walk through all the collection items and substitule required values into it.
if value.is_a?(Array) || value.is_a?(Hash)
value = value.dup
value = [ value ] if value.is_a?(Hash)
value.each_with_index do |item_params, idx|
# The values given by the user (or the default ones) must be defined as hashes.
fail Error::new("#{method_name}: Collection items must be Hash instances but #{item_params.inspect} is provided") unless item_params.is_a?(Hash)
# Recursively pdate them all.
value[idx] = compute_query_api_pattern_param(method_name, sub_pattern, params_with_defaults.merge(item_params), used_params)
end
end
# Mark the collection key as the one that has been used already.
used_params << collection_key
else
value = compute_query_api_pattern_param(method_name, value, params_with_defaults, used_params) unless value == Utils::NONE
end
value == Utils::NONE ? result.delete(key) : result[key] = value
[key, value]
end
private :parse_query_api_pattern_collections
# Deals with blank values.
#
# @api private
#
# If the given key responds to "blank? and it is true and it is marked as to be removed if
# it is blank then we remove it in this method.
#
# @param [String] key The current key.
# @param [Object] value The current value,
# @param [Hash] result The resulting hash that has all the transformed params.
#
# @return [Array] The updated key name and its value.
#
def parse_query_api_pattern_remove_blank_key( key, value, result)
# 'KeyName{!remove-if-blank}'
blank_key_sign = key[FIND_BLANK_KEYS_TO_REMOVE]
if blank_key_sign
# Delete the original key from the resulting hash.
result.delete(key)
# But if its value is not blank then fix the key name (get rid of {!remove-if-blank}) and
# put it back.
unless value.respond_to?(:_blank?) && value._blank?
key = key.sub(blank_key_sign, '')
result[key] = value
end
end
[key, value]
end
private :parse_query_api_pattern_remove_blank_key
# Parses Hash objects
#
# @api private
#
# @return [Hash]
#
def compute_query_api_pattern_hash_data(method_name, source, params_with_defaults, used_params)
result = source.dup
source.dup.each do |key, value|
# Make sure key is a String
key = key.to_s.dup
# Subsets replacement
key, value = *parse_query_api_pattern_replacements(params_with_defaults, used_params, key, value, result)
# Collections replacement
key, value = *parse_query_api_pattern_collections(method_name, params_with_defaults, used_params, key, value, result)
# Remove empty keys
parse_query_api_pattern_remove_blank_key(key, value, result)
end
result
end
private :compute_query_api_pattern_hash_data
#-----------------------------------------
# Query API pattern: ARRAY
#-----------------------------------------
# Parses Array objects
#
# @return [Array]
#
def compute_query_api_pattern_array_data(query_api_method_name, source, params_with_defaults, used_query_params)
result = source.dup
source.dup.each_with_index do |item, idx|
value = compute_query_api_pattern_param(query_api_method_name, item, params_with_defaults, used_query_params)
value == Utils::NONE ? result.delete_at(idx) : result[idx] = value
end
result
end
#-----------------------------------------
# Query API pattern: STRING
#-----------------------------------------
# Parses String objects
#
# @return [String]
#
# @raise [Error]
#
def compute_query_api_pattern_string_data(query_api_method_name, source, params_with_defaults, used_query_params)
result = source.dup
result.scan(FIND_KEY_REGEXP).flatten.each do |key|
fail Error::new("#{query_api_method_name}: #{key.inspect} is required") unless params_with_defaults.has_key?(key)
value = params_with_defaults[key]
result.gsub!("{:#{key}}", value == Utils::NONE ? '' : value.to_s)
used_query_params << key
end
result
end
#-----------------------------------------
# Query API pattern: SYMBOL
#-----------------------------------------
# Parses Symbol objects
#
# @return [String]
#
# @raise [Error]
#
def compute_query_api_pattern_symbol_data(query_api_method_name, source, params_with_defaults, used_query_params)
key = source.to_s
fail Error::new("#{query_api_method_name}: #{key.inspect} is required") unless params_with_defaults.has_key?(key)
result = params_with_defaults[key]
used_query_params << key
result
end
end
end
end
end
<file_sep>#--
# Copyright (c) 2013 RightScale, Inc.
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# 'Software'), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
# IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
# CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
# SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#++
module RightScale
module CloudApi
# The class is the parent class for all the cloud based thread-non-safe managers
#
# @api public
#
# It implements all the +generic+ functionalities the cloud specific managers share.
#
class ApiManager
# Log filters set by default
DEFAULT_LOG_FILTERS = [
:connection_proxy,
:request_generator,
:request_generator_body,
:response_analyzer,
:response_analyzer_body_error,
:response_parser,
]
# Default Error
class Error < CloudApi::Error
end
# Options reader
#
# @return [Hash] The list of class level set options.
# @example
# # no example
#
def self.options
@options ||= {}
end
# Options setter
#
# @param [Hash] options
# @return [void]
#
# @example
# module RightScale
# module CloudApi
# module AWS
# class ApiManager < CloudApi::ApiManager
# set :response_error_parser => Parser::AWS::ResponseErrorV1
# set :cache => true
# ...
# end
# end
# end
# end
#
def self.set(opts)
opts.each { |key, value| self.options[key] = value }
nil
end
# Returns a list of routines the manager invokes while processing API request
#
# @return [Array] An array of RightScale::CloudApi::Routine.
# @example
# # no example
#
def self.routines
@routines ||= []
end
# Add routine of the given tipe into the list of API processing routines
#
# @param [RightScale::CloudApi::Routine] routines A set of routines.
# @return [Array] The current set of routines.
# @example
# # no example
#
def self.set_routine(*new_routines)
new_routines.flatten.each do |routine|
self.routines << routine
# If a routine has ClassMethods module defined then extend the current class with those methods.
# We use this to add class level helper methods like: error_pattern or cache_pattern
self.extend routine::ClassMethods if defined?(routine::ClassMethods)
end
self.routines
end
# Return a set of system vars (ignore this attribute)
#
# @return [Hash]
# @example
# # no example
#
attr_reader :data
# Return a set of system routines (ignore this attribute)
#
# @return [Array]
# @example
# # no example
#
attr_reader :routines
# Constructor
#
# @param [Hash] credentials Cloud credentials.
# @param [String] endpoint API endpoint.
# @param [Hash] options A set of options (see below).
#
# @option options [Boolean] :allow_endpoint_params
# When the given endpoint has any set of URL params they will not be ignored but will
# be added to every API request.
#
# @option options [Boolean] :abort_on_timeout
# When set to +true+ the gem does not perform a retry call when there is a connection
# timeout.
#
# @option options [String] :api_version
# The required cloud API version if it is different from the default one.
#
# @option options [Class] :api_wrapper
# The Query-like API wrapper module that provides a set of handy methods to drive
# REST APIs (see {RightScale::CloudApi::Mixin::QueryApiPatterns::ClassMethods})
#
# @option options [Boolean] :cache
# Cache cloud responses when possible so that we don't parse them again if cloud
# response does not change (see cloud specific ApiManager definition).
#
# @option options [Hash] :cloud
# A set of cloud specific options. See custom cloud specific ApiManagers for better
# explanation.
#
# @option options [String] :connection_ca_file
# CA certificate for SSL connection.
#
# @option options [Integer] :connection_open_timeout
# Connection open timeout (in seconds).
#
# @option options [String] :connection_proxy
# Connection proxy class (when it need to be different from the default one).
# Only RightScale::CloudApi::ConnectionProxy::NetHttpPersistentProxy is supported so far.
#
# @option options [Integer] :connection_read_timeout
# Connection read timeout (in seconds).
#
# @option options [Integer] :connection_retry_count
# Max number of retries to when unable to establish a connection to API server
#
# @option options [Integer] :connection_retry_delay
# Defines how long we wait on a low level connection error (in seconds)
#
# @option options [Integer] :connection_verify_mode
# SSL connection cert check: either OpenSSL::SSL::VERIFY_PEER (default) or
# OpenSSL::SSL::VERIFY_NONE
#
# @option options [Hash] :creds
# A set of optional extra creds a cloud may require
# (see right_cloud_stack_api gem which supports :tenant_name and :tenant_id)
#
# @option options [Hash] :headers
# A set of request headers to be added to every API call.
#
# @option options [Logger] :logger
# Current logger. If is not provided then it logs to STDOUT. When if nil is given it
# logs to '/dev/nul'.
#
# @option options [Hash] :retry
# A set of options for how retry behavior works.
# available retry options
# :count => Integer # number of retry attempts
# :strategy => Symbol # retry strategy[ :exponentional (default), :full_jitter, :equal_jitter, :decorrelated_jitter, :retry_after]
# :reiteration_time => Integer # maximum amount of time to allow for retries
# :sleep_time => Integer # base sleep time in seconds, actual sleep time depends on strategy and count
#
# @option options [Symbol] :log_filter_patterns
# A set of log filters that define what to log (see {RightScale::CloudApi::CloudApiLogger}).
#
# @option options [Hash] :params
# A set of URL params to be sent with the API request.
#
# @option options [Boolean,String] :random_token
# Some clouds API cache their responses when they receive the same request again
# and again, even when we are sure that cloud response mush have changed. To deal
# with this we can add a random parameter to an API call to trick the remote API.
# When :random_token is set to +true+ it adds an extra param with name 'rsrcarandomtoken'
# and a random value to every single API request. When :random_token is a String then
# the gem uses it as the random param name.
#
# @option options [Boolean] :raw_response
# By default the gem parses all XML and JSON responses and returns them as ruby Hashes.
# Sometimes it is not what one would want (Amazon S3 GetObject for example).
# Setting this option to +true+ forces the gem to return a not parsed response.
#
# @option options [Class] :response_error_parser
# API response parser in case of error (when it needs to be different from the default one).
#
# @option options [Symbol] :xml_parser
# XML parser (:sax | :rexml are supported).
#
# @option options [Proc] :before_process_api_request_callback
# The callback is called before every API request (may be helpful when debugging things).
#
# @option options [Proc] :before_routine_callback
# The callback is called before each routine is executed.
#
# @option options [Proc] :after_routine_callback
# The callback is called after each routine is executed.
#
# @option options [Proc] :after_process_api_request_callback
# The callback is called after the API request completion.
#
# @option options [Proc] :before_retry_callback
# The callback is called if a retry attempt is required.
#
# @option options [Proc] :before_redirect_callback
# The callback is called when a redirect is detected.
#
# @option options [Proc] :stat_data_callback
# The callback is called when stat data for the current request is ready.
#
# @raise [Rightscale::CloudApi::ApiManager::Error]
# If no credentials have been set or the endpoint is blank.
#
# @example
# # See cloud specific gems for use case.
#
# @see Manager
#
def initialize(credentials, endpoint, options={})
@endpoint = endpoint
@credentials = credentials.merge!(options[:creds] || {})
@credentials.each do |key, value|
fail(Error, "Credential #{key.inspect} cannot be empty") unless value
end
@options = options
@options[:cloud] ||= {}
@with_options = []
@with_headers = {}
@routines = []
@storage = {}
@options[:cloud_api_logger] = RightScale::CloudApi::CloudApiLogger.new(@options , DEFAULT_LOG_FILTERS)
# Try to set an API version when possible
@options[:api_version] ||= "#{self.class.name}::DEFAULT_API_VERSION"._constantize rescue nil
# Load routines
routine_classes = (Utils.inheritance_chain(self.class, :routines).select{|rc| !rc._blank?}.last || [])
@routines = routine_classes.map{ |routine_class| routine_class.new }
# fail Error::new("Credentials must be set") if @credentials._blank?
fail Error::new("Endpoint must be set") if @endpoint._blank?
# Try to wrap this manager with the handy API methods if possible using [:api_wrapper, :api_version, 'default']
# (but do nothing if one explicitly passed :api_wrapper => nil )
unless @options.has_key?(:api_wrapper) && @options[:api_wrapper].nil?
# And then wrap with the most recent or user's wrapper
[ @options[:api_wrapper], @options[:api_version], 'default'].uniq.each do |api_wrapper|
break if wrap_api_with(api_wrapper, false)
end
end
end
# Main API request entry point
#
# @api private
#
# @param [String,Symbol] verb HTTP verb: :get, :post, :put, :delete, etc.
# @param [String] relative_path Relative URI path.
# @param [Hash] opts A set of extra options.
#
# @option options [Hash] :params
# A set of URL parameters.
#
# @option options [Hash] :headers
# A set of HTTP headers.
#
# @option options [Hash] :options
# A set of extra options: see {#initialize} method for them.
#
# @option options [Hash,String] :body
# The request body. If Hash is passed then it will convert it into String accordingly to
# 'content-type' header.
#
# @option options [String] :endpoint
# An endpoint if it is different from the default one.
#
# @return [Object]
#
# @example
# # The method should not be used directly: use *api* method instead.
#
# @yield [String] If a block is given it will call it on every chunk of data received from a socket.
#
def process_api_request(verb, relative_path, opts={}, &block)
# Add a unique-per-request log prefix to every logged line.
cloud_api_logger.set_unique_prefix
# Initialize @data variable and get a final set of API request options.
options = initialize_api_request_options(verb, relative_path, opts, &block)
# Before_process_api_request_callback.
invoke_callback_method(options[:before_process_api_request_callback], :manager => self)
# Main loop
loop do
# Start a new stat session.
stat = {}
@data[:stat][:data] << stat
# Reset retry attempt flag.
retry_attempt = false
# Loop through all the required routes.
routines.each do |routine|
# Start a new stat record for current routine.
routine_name = routine.class.name
stat[routine_name] = {}
stat[routine_name][:started_at] = Time.now.utc
begin
# Set routine data
routine.reset(data)
# Before_routine_callback.
invoke_callback_method(options[:before_routine_callback],
:routine => routine,
:manager => self)
# Process current routine.
routine.process
# After_routine_callback.
invoke_callback_method(options[:after_routine_callback],
:routine => routine,
:manager => self)
# If current routine reported the API request is done we should stop and skip all the
# rest routines
break if data[:vars][:system][:done]
rescue RetryAttempt
invoke_callback_method(options[:after_routine_callback],
:routine => routine,
:manager => self,
:retry => true)
# Set a flag that would notify the exterlan main loop there is a retry request received.
retry_attempt = true
# Break the routines loop and exit into the main one.
break
ensure
# Complete current stat session
stat[routine_name][:time_taken] = Time.now.utc - stat[routine_name][:started_at]
end
end
# Make another attempt from the scratch or...
redo if retry_attempt
# ...stop and report the result.
break
end
# After_process_api_request_callback.
invoke_callback_method(options[:after_process_api_request_callback], :manager => self)
data[:result]
rescue => error
# Invoke :after error callback
invoke_callback_method(options[:after_error_callback], :manager => self, :error => error)
fail error
ensure
# Remove the unique-per-request log prefix.
cloud_api_logger.reset_unique_prefix
# Complete stat data and invoke its callback.
@data[:stat][:time_taken] = Time.now.utc - @data[:stat][:started_at] if @data[:stat]
invoke_callback_method(options[:stat_data_callback], :manager => self, :stat => self.stat, :error => error)
end
private :process_api_request
# Initializes the @data variable and builds the request options
#
# @api private
#
# @param [String,Symbol] verb HTTP verb: :get, :post, :put, :delete, etc.
# @param [String] relative_path Relative URI path.
# @param [Hash] opts A set of extra options.
#
# @option options [Hash] :params A set of URL parameters.
# @option options [Hash] :headers A set of HTTP headers.
# @option options [Hash] :options A set of extra options: see {#initialize} method for them.
# @option options [Hash,String] :body The request body. If Hash is passed then it will
# convert it into String accordingly to 'content-type' header.
#
# @yield [String] If a block is given it will call it on every chunk of data received from a socket.
#
# @return [Any] The result of the request (usually a Hash or a String instance).
#
def initialize_api_request_options(verb, relative_path, opts, &block)
options = {}
options_chain = Utils.inheritance_chain(self.class, :options, @options, *(@with_options + [opts[:options]]))
options_chain.each{ |o| options.merge!(o || {}) }
# Endpoint
endpoint = options[:endpoint] || @endpoint
# Params
params = {}
params.merge!(Utils::extract_url_params(endpoint))._stringify_keys if options[:allow_endpoint_params]
params.merge!(options[:params] || {})._stringify_keys
params.merge!(opts[:params] || {})._stringify_keys
# Headers
headers = (options[:headers] || {})._stringify_keys
headers.merge!(@with_headers._stringify_keys)
headers.merge!( opts[:headers] || {})._stringify_keys
# Make sure the endpoint's schema is valid.
parsed_endpoint = ::URI::parse(endpoint)
unless [nil, 'http', 'https'].include? parsed_endpoint.scheme
fail Error.new('Endpoint parse failed - invalid scheme')
end
# Options: Build the initial data hash
@data = {
:options => options.dup,
:credentials => @credentials.dup,
:connection => { :uri => parsed_endpoint },
:request => { :verb => verb.to_s.downcase.to_sym,
:relative_path => relative_path,
:headers => HTTPHeaders::new(headers),
:body => opts[:body],
:orig_body => opts[:body], # keep here a copy of original body (Routines may change the real one, when it is a Hash)
:params => params,
:orig_params => params.dup }, # original params without any signatures etc
:vars => { :system => { :started_at => Time::now.utc,
:storage => @storage,
:block => block }
},
:callbacks => { },
:stat => {
:started_at => Time::now.utc,
:data => [ ],
},
}
options
end
private :initialize_api_request_options
# A helper method for invoking callbacks
#
# @api private
#
# The method checks if the given Proc exists and invokes it with the given set of arguments.
# In the case when proc==nil the method does nothing.
#
# @param [Proc] proc The callback.
# @param [Any] args A set of callback method arguments.
#
# @return [void]
#
def invoke_callback_method(proc, *args) # :nodoc:
proc.call(*args) if proc.is_a?(Proc)
end
private :invoke_callback_method
# Returns the current logger
#
# @return [RightScale::CloudApi::CloudApiLogger]
# @example
# # no example
#
def cloud_api_logger
@options[:cloud_api_logger]
end
# Returns current statistic
#
# @return [Hash]
#
# @example
# # Simple case:
# amazon.DescribeVolumes #=> [...]
# amazon.stat #=>
# {:started_at=>2014-01-03 19:09:13 UTC,
# :time_taken=>2.040465903,
# :data=>
# [{"RightScale::CloudApi::RetryManager"=>
# {:started_at=>2014-01-03 19:09:13 UTC, :time_taken=>1.7136e-05},
# "RightScale::CloudApi::RequestInitializer"=>
# {:started_at=>2014-01-03 19:09:13 UTC, :time_taken=>7.405e-06},
# "RightScale::CloudApi::AWS::RequestSigner"=>
# {:started_at=>2014-01-03 19:09:13 UTC, :time_taken=>0.000140031},
# "RightScale::CloudApi::RequestGenerator"=>
# {:started_at=>2014-01-03 19:09:13 UTC, :time_taken=>4.7781e-05},
# "RightScale::CloudApi::RequestAnalyzer"=>
# {:started_at=>2014-01-03 19:09:13 UTC, :time_taken=>3.1789e-05},
# "RightScale::CloudApi::ConnectionProxy"=>
# {:started_at=>2014-01-03 19:09:13 UTC, :time_taken=>2.025818663},
# "RightScale::CloudApi::ResponseAnalyzer"=>
# {:started_at=>2014-01-03 19:09:15 UTC, :time_taken=>0.000116668},
# "RightScale::CloudApi::CacheValidator"=>
# {:started_at=>2014-01-03 19:09:15 UTC, :time_taken=>1.9225e-05},
# "RightScale::CloudApi::ResponseParser"=>
# {:started_at=>2014-01-03 19:09:15 UTC, :time_taken=>0.014059933},
# "RightScale::CloudApi::ResultWrapper"=>
# {:started_at=>2014-01-03 19:09:15 UTC, :time_taken=>4.4907e-05}}]}
#
# @example
# # Using callback:
# STAT_DATA_CALBACK = lambda do |args|
# puts "Error: #{args[:error].class.name}" if args[:error]
# pp args[:stat]
# end
#
# amazon = RightScale::CloudApi::AWS::EC2::Manager::new(
# ENV['AWS_ACCESS_KEY_ID'],
# ENV['AWS_SECRET_ACCESS_KEY'],
# endpoint || ENV['EC2_URL'],
# :stat_data_callback => STAT_DATA_CALBACK)
#
# amazon.DescribeVolumes #=> [...]
#
# # >> Stat data callback's output <<:
# {:started_at=>2014-01-03 19:09:13 UTC,
# :time_taken=>2.040465903,
# :data=>
# [{"RightScale::CloudApi::RetryManager"=>
# {:started_at=>2014-01-03 19:09:13 UTC, :time_taken=>1.7136e-05},
# ...
# "RightScale::CloudApi::ResultWrapper"=>
# {:started_at=>2014-01-03 19:09:15 UTC, :time_taken=>4.4907e-05}}]}
#
def stat
@data && @data[:stat]
end
# Returns the last request object
#
# @return [RightScale::CloudApi::HTTPRequest]
# @example
# # no example
#
def request
@data && @data[:request] && @data[:request][:instance]
end
# Returns the last response object
#
# @return [RightScale::CloudApi::HTTPResponse]
# @example
# # no example
#
def response
@data && @data[:response] && @data[:response][:instance]
end
# The method is just a wrapper around process_api_request
#
# But this behavour can be overriden by sub-classes.
#
# @param [Any] args See *process_api_request* for the current ApiManager.
#
# @yield [String] See *process_api_request* for the current ApiManager.
#
# @return [Any] See *process_api_request* for the current ApiManager.
#
# @example
# # see cloud specific gems
#
def api(*args, &block)
process_api_request(*args, &block)
end
# Defines a set of *get*, *post*, *put*, *head*, *delete*, *patch* helper methods.
# All the methods are very simple wrappers aroung the *api* method. Whatever you would feed to
# *api* method you can feed to these ones except for the very first parameter :verb which
# is not required.
#
# @example
# s3.api(:get, 'my_bucket')
# # is equivalent to
# s3.get('my_bucket')
#
HTTP_VERBS = [ :get, :post, :put, :head, :delete, :patch ]
HTTP_VERBS.each do |http_verb|
eval <<-EOM
def #{http_verb}(*args, &block)
api(__method__.to_sym, *args, &block)
end
EOM
end
# Sets temporary set of options
#
# The method takes a block and all the API calls made inside it will have the given set of
# extra options. The method supports nesting.
#
# @param [Hash] options The set of options. See {#initialize} methos for the possible options.
# @return [void]
# @yield [] All the API call made in the block will have the provided options.
#
# @example
# # The example does not make too much sense - it just shows the idea.
# ec2 = RightScale::CloudApi::AWS::EC2.new(key, secret_key, :api_version => '2009-01-01')
# # Describe all the instances against API '2009-01-01'.
# ec2.DescribeInstances
# ec2.with_options(:api_version => '2012-01-01') do
# # Describe all the instances against API '2012-01-01'.
# ec2.DescribeInstances
# # Describe and stop only 2 instances.
# ec2.with_options(:params => { 'InstanceId' => ['i-01234567', 'i-76543210'] }) do
# ec2.DescribeInstances
# ec2.StopInstances
# end
# end
#
def with_options(options={}, &block)
@with_options << (options || {})
block.call
ensure
@with_options.pop
end
# Sets temporary sets of HTTP headers
#
# The method takes a block and all the API calls made inside it will have the given set of
# headers.
#
# @param [Hash] headers The set oh temporary headers.
# @option options [option_type] option_name option_description
#
# @return [void]
#
# @yield [] All the API call made in the block will have the provided headers.
#
# @example
# # The example does not make too much sense - it just shows the idea.
# ec2 = RightScale::CloudApi::AWS::EC2.new(key, secret_key, :api_version => '2009-01-01')
# ec2.with_header('agent' => 'mozzzzzillllla') do
# # the header is added to every request below
# ec2.DescribeInstances
# ec2.DescribeImaneg
# ec2.DescribeVolumes
# end
#
def with_headers(headers={}, &block)
@with_headers = headers || {}
block.call
ensure
@with_headers = {}
end
# Wraps the Manager with handy API helper methods
#
# The wrappers are not necessary but may be very helpful for REST API related clouds such
# as Amazon S3, OpenStack/Rackspace or Windows Azure.
#
# @param [Module,String] api_wrapper The wrapper module or a string that would help to
# identify it.
#
# @return [void]
#
# @raise [RightScale::CloudApi::ApiManager::Error] If an unexpected parameter is passed.
# @raise [RightScale::CloudApi::ApiManager::Error] If the requested wrapper does not exist.
#
# If string is passed:
#
# OpenStack: 'v1.0' #=> 'RightScale::CloudApi::OpenStack::Wrapper::V1_0'
# EC2: '2011-05-08' #=> 'RightScale::CloudApi::AWS::EC2::Wrapper::V2011_05_08'
#
# @example
# # ignore the method
#
def wrap_api_with(api_wrapper=nil, raise_if_not_exist=true) # :nodoc:
return if api_wrapper._blank?
# Complain if something unexpected was passed.
fail Error.new("Unsupported wrapper: #{api_wrapper.inspect}") unless api_wrapper.is_a?(Module) || api_wrapper.is_a?(String)
# If it is not a module - make it be the module
unless api_wrapper.is_a?(Module)
# If the String starts with a digit the prefix it with 'v'.
api_wrapper = "v" + api_wrapper if api_wrapper.to_s[/^\d/]
# Build the module name including the parent namespaces.
api_wrapper = "#{self.class.name.sub(/::ApiManager$/, '')}::Wrapper::#{api_wrapper.to_s.upcase.gsub(/[^A-Z0-9]/,'_')}"
# Try constantizing it.
_module = api_wrapper._constantize rescue nil
# Complain if the requested wrapper was not found.
fail Error.new("Wrapper not found #{api_wrapper}") if !_module && raise_if_not_exist
else
_module = api_wrapper
end
# Exit if there is no wrapper or it is already in use
return false if !_module || _extended?(_module)
# Use the wrapper
extend(_module)
cloud_api_logger.log("Wrapper: wrapped: #{_module.inspect}.", :wrapper)
true
end
end
end
end
<file_sep>#--
# Copyright (c) 2013 RightScale, Inc.
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# 'Software'), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
# IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
# CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
# SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#++
require "rexml/document"
module RightScale
module CloudApi
module Parser
class ReXml
def self.parse(body, options = {})
parse_rexml_node ::REXML::Document::new(body).root
end
def self.parse_rexml_node(node)
attributes = {}
children = {}
text = ''
# Parse Attributes
node.attributes.each do |name, value|
attributes["@#{name}"] = value
end
# Parse child nodes
node.each_element do |child|
if child.has_elements? || child.has_text?
response = parse_rexml_node(child)
unless children["#{child.name}"]
# This is a first child - keep it as is
children["#{child.name}"] = response
else
# This is a second+ child: make sure we put them in an Array
children["#{child.name}"] = [ children["#{child.name}"] ] unless children["#{child.name}"].is_a?(Array)
children["#{child.name}"] << response
end
else
# Don't lose blank elements
children["#{child.name}"] = nil
end
end
# Parse Text
text << node.texts.join('')
# Merge results
if attributes._blank? && children._blank?
result = text._blank? ? nil : text
else
result = attributes.merge(children)
result.merge!("@@text" => text) unless text._blank?
end
# Build a root key when necessary
result = { node.name => result } if node.parent.is_a?(REXML::Document)
result
end
end
end
end
end<file_sep>#--
# Copyright (c) 2013 RightScale, Inc.
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# 'Software'), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
# IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
# CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
# SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#++
require File.expand_path(File.dirname(__FILE__)) + "/../spec_helper"
describe "" do
before(:each) do
logger = Logger.new(STDOUT)
logger.level = Logger::INFO
@retrymanager = RightScale::CloudApi::RetryManager.new
allow(@retrymanager).to receive(:log)
@request = double(:verb => 'get', :path => 'some/path', :body => 'body', :is_io? => false, :is_error? => false, :is_redirect? => false, :headers => {'header1' => 'val1', 'header2' => 'val2'})
@test_data = {
:options => { :user_agent => 'user_agent_data',
:cloud_api_logger => RightScale::CloudApi::CloudApiLogger.new({}),
:retry => {
:count => 2,
:reiteration_time => 10,
:sleep_time => 0.2
},
},
:vars => { :system => {:block => 'block', :started_at => Time.now}},
:credentials => {},
:callbacks => {},
:connection => {:uri => double(:host => 'host.com', :port => '777', :scheme => 'scheme')},
:request => {:instance => @request}
}
@response = double(:code => '200', :body => 'body', :to_hash => {:code => '200', :body => 'body'})
@connection = double(:request => @response)
end
context "RightScale::CloudApi::RetryManager" do
it "works - default exponential" do
# 1st run
@retrymanager.execute(@test_data)
expect(@test_data[:vars][:retry][:count]).to eq 0
expect(@test_data[:vars][:retry][:previous_sleep_time]).to eq nil
# 2nd run, +1 count *2 sleep
@retrymanager.execute(@test_data)
expect(@test_data[:vars][:retry][:count]).to eq 1
expect(@test_data[:vars][:retry][:previous_sleep_time]).to eq 0.2
# 3rd run, +1 count, *2 sleep
@retrymanager.execute(@test_data)
expect(@test_data[:vars][:retry][:count]).to eq 2
expect(@test_data[:vars][:retry][:previous_sleep_time]).to eq 0.4
#4th run, case 1: default error
default_rm_error = "RetryManager: No more retries left."
expect do
@retrymanager.execute(@test_data)
end.to raise_error(RightScale::CloudApi::RetryManager::Error, default_rm_error)
#4th run, case 2: cloud_error + default error
http_error = 'Banana.'
expectation = "#{http_error}\n#{default_rm_error}"
@test_data[:vars][:retry][:http] = { :code => 777, :message => http_error }
expect do
@retrymanager.execute(@test_data)
end.to raise_error(RightScale::CloudApi::RetryManager::Error, expectation)
end
it "works full jitter" do
@test_data[:options][:retry][:strategy] = :full_jitter
@test_data[:options][:retry][:count] = 3
@retrymanager.execute(@test_data)
expect(@test_data[:vars][:retry][:count]).to eq 0
expect(@test_data[:vars][:retry][:previous_sleep_time]).to eq nil
@retrymanager.execute(@test_data)
expect(@test_data[:vars][:retry][:count]).to eq 1
expect(@test_data[:vars][:retry][:previous_sleep_time]).to be_between(0,0.2)
@retrymanager.execute(@test_data)
expect(@test_data[:vars][:retry][:count]).to eq 2
expect(@test_data[:vars][:retry][:previous_sleep_time]).to be_between(0,0.4)
@retrymanager.execute(@test_data)
expect(@test_data[:vars][:retry][:count]).to eq 3
expect(@test_data[:vars][:retry][:previous_sleep_time]).to be_between(0,0.8)
#4th run, case 1: default error
default_rm_error = "RetryManager: No more retries left."
expect do
@retrymanager.execute(@test_data)
end.to raise_error(RightScale::CloudApi::RetryManager::Error, default_rm_error)
#4th run, case 2: cloud_error + default error
http_error = 'Banana.'
expectation = "#{http_error}\n#{default_rm_error}"
@test_data[:vars][:retry][:http] = { :code => 777, :message => http_error }
expect do
@retrymanager.execute(@test_data)
end.to raise_error(RightScale::CloudApi::RetryManager::Error, expectation)
end
it "works equal jitter" do
@test_data[:options][:retry][:strategy] = :equal_jitter
@test_data[:options][:retry][:count] = 3
@retrymanager.execute(@test_data)
expect(@test_data[:vars][:retry][:count]).to eq 0
expect(@test_data[:vars][:retry][:previous_sleep_time]).to eq nil
@retrymanager.execute(@test_data)
expect(@test_data[:vars][:retry][:count]).to eq 1
expect(@test_data[:vars][:retry][:previous_sleep_time]).to be_between(0.1,0.2)
@retrymanager.execute(@test_data)
expect(@test_data[:vars][:retry][:count]).to eq 2
expect(@test_data[:vars][:retry][:previous_sleep_time]).to be_between(0.2,0.4)
@retrymanager.execute(@test_data)
expect(@test_data[:vars][:retry][:count]).to eq 3
expect(@test_data[:vars][:retry][:previous_sleep_time]).to be_between(0.4,0.8)
#4th run, case 1: default error
default_rm_error = "RetryManager: No more retries left."
expect do
@retrymanager.execute(@test_data)
end.to raise_error(RightScale::CloudApi::RetryManager::Error, default_rm_error)
#4th run, case 2: cloud_error + default error
http_error = 'Banana.'
expectation = "#{http_error}\n#{default_rm_error}"
@test_data[:vars][:retry][:http] = { :code => 777, :message => http_error }
expect do
@retrymanager.execute(@test_data)
end.to raise_error(RightScale::CloudApi::RetryManager::Error, expectation)
end
it "works decorrelated jitter" do
@test_data[:options][:retry][:strategy] = :decorrelated_jitter
@test_data[:options][:retry][:count] = 3
@retrymanager.execute(@test_data)
expect(@test_data[:vars][:retry][:count]).to eq 0
expect(@test_data[:vars][:retry][:previous_sleep_time]).to eq nil
@retrymanager.execute(@test_data)
expect(@test_data[:vars][:retry][:count]).to eq 1
expect(@test_data[:vars][:retry][:previous_sleep_time]).to be_between(0.2,0.6)
previous_sleep_time = @test_data[:vars][:retry][:previous_sleep_time]
@retrymanager.execute(@test_data)
expect(@test_data[:vars][:retry][:count]).to eq 2
expect(@test_data[:vars][:retry][:previous_sleep_time]).to be_between(0.2,3*previous_sleep_time)
previous_sleep_time = @test_data[:vars][:retry][:previous_sleep_time]
previous_sleep_time = @test_data[:vars][:retry][:previous_sleep_time]
@retrymanager.execute(@test_data)
expect(@test_data[:vars][:retry][:count]).to eq 3
expect(@test_data[:vars][:retry][:previous_sleep_time]).to be_between(0.2,3*previous_sleep_time)
#4th run, case 1: default error
default_rm_error = "RetryManager: No more retries left."
expect do
@retrymanager.execute(@test_data)
end.to raise_error(RightScale::CloudApi::RetryManager::Error, default_rm_error)
#4th run, case 2: cloud_error + default error
http_error = 'Banana.'
expectation = "#{http_error}\n#{default_rm_error}"
@test_data[:vars][:retry][:http] = { :code => 777, :message => http_error }
expect do
@retrymanager.execute(@test_data)
end.to raise_error(RightScale::CloudApi::RetryManager::Error, expectation)
end
end
end
<file_sep>#--
# Copyright (c) 2013 RightScale, Inc.
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# 'Software'), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
# IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
# CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
# SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#++
require 'rubygems'
require 'time'
require 'openssl'
require 'net/https'
require 'base64'
require 'cgi'
require 'logger'
require 'digest/md5'
$:.unshift(File::expand_path(File::dirname(__FILE__)))
require "right_cloud_api_base_version"
# Helpers
require "base/helpers/support"
require "base/helpers/support.xml"
require "base/helpers/utils"
require "base/helpers/net_http_patch"
require "base/helpers/http_headers"
require "base/helpers/http_parent"
require "base/helpers/http_request"
require "base/helpers/http_response"
require "base/helpers/query_api_patterns"
require "base/helpers/cloud_api_logger"
# Managers
require "base/manager"
require "base/api_manager"
# Default parsers
require "base/parsers/plain"
require "base/parsers/json"
require "base/parsers/rexml"
require "base/parsers/sax"
# Default routines
require "base/routines/routine"
require "base/routines/retry_manager"
require "base/routines/request_initializer"
require "base/routines/request_generator"
require "base/routines/connection_proxy"
require "base/routines/connection_proxies/net_http_persistent_proxy"
require "base/routines/response_parser"
require "base/routines/request_analyzer"
require "base/routines/response_analyzer"
require "base/routines/cache_validator"
require "base/routines/result_wrapper"
<file_sep>#--
# Copyright (c) 2013 RightScale, Inc.
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# 'Software'), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
# IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
# CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
# SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#++
require File.expand_path(File.dirname(__FILE__)) + "/../spec_helper"
describe "RightScale::CloudApi::CacheValidator" do
before(:each) do
logger = Logger.new(STDOUT)
logger.level = Logger::INFO
@api_manager = RightScale::CloudApi::ApiManager.new({'x' => 'y'},'endpoint', {:logger => logger})
@api_manager.class.set_routine RightScale::CloudApi::CacheValidator
@api_manager.class.options[:error_patterns] = []
@cachevalidator = RightScale::CloudApi::CacheValidator.new
@test_data = {}
@test_data[:request] = { :verb => 'some_verb', :orig_params => {}, :instance => 'some_request'}
@test_data[:options] = {:error_patterns => []}
@callback = double
@test_data[:options][:cache] = {}
@test_data[:callbacks] = {:close_current_connection => @callback}
@test_data[:connection] = {}
@test_data[:response] = {}
@test_data[:vars] = {:system => {:storage => {}}}
@test_data[:response][:instance] = double(:is_io? => false)
allow(@cachevalidator).to receive(:log)
end
context "cache_pattern" do
it "fails when is has unexpected inputs" do
# non hash input
expect { @api_manager.class.cache_pattern(true) }.to raise_error(RightScale::CloudApi::CacheValidator::Error)
# blank pattern
expect { @api_manager.class.cache_pattern({}) }.to raise_error(RightScale::CloudApi::CacheValidator::Error)
end
context "pattern keys" do
before(:each) do
# test all pattern keys
@cache_pattern = RightScale::CloudApi::CacheValidator::ClassMethods::CACHE_PATTERN_KEYS.inject({}) { |result, k| result.merge(k => k.to_s)}
@api_manager.class.cache_pattern(@cache_pattern)
end
it "stores all the cache patterns keys properly" do
expect(@api_manager.class.options[:cache_patterns]).to eq([@cache_pattern])
end
it "complains when a mandatory key is missing" do
@cache_pattern.delete(:key)
expect { @api_manager.class.cache_pattern(@cache_pattern) }.to raise_error(RightScale::CloudApi::CacheValidator::Error)
end
it "complains when an unsupported key is passed" do
bad_keys = { :bad_key1 => "bad_key1", :bad_key2 => "bad_key2" }
@cache_pattern.merge!(bad_keys)
expect { @api_manager.class.cache_pattern(@cache_pattern) }.to raise_error(RightScale::CloudApi::CacheValidator::Error)
end
end
end
context "basic cache validation" do
it "returns true when it performed validation" do
expect(@cachevalidator.execute(@test_data)).to be(true)
end
it "returns nil if there is no way to parse a response object" do
@test_data[:response][:instance] = double(:is_io? => true)
expect(@cachevalidator.execute(@test_data)).to be(nil)
end
it "returns nil if caching is disabled" do
@test_data[:options].delete(:cache)
expect(@cachevalidator.execute(@test_data)).to be(nil)
end
end
context "cache validation with match" do
before(:each) do
expect(RightScale::CloudApi::Utils).to receive(:pattern_matches?).at_least(1).and_return(true)
@cache_pattern = RightScale::CloudApi::CacheValidator::ClassMethods::CACHE_PATTERN_KEYS.inject({}) { |result, k| result.merge(k => k.to_s)}
@cache_pattern[:sign] = double(:call => "body_to_sign")
@test_data[:options][:cache_patterns] = [@cache_pattern]
@response = double(:code => '501', :body => 'body', :headers => 'headers', :is_io? => false)
@test_data[:response] = {:instance => @response}
end
it "fails if there is a missing key" do
@cache_pattern.delete(:key)
expect { @cachevalidator.execute(@test_data) }.to raise_error(RightScale::CloudApi::CacheValidator::Error)
end
context "and one record cached" do
before(:each) do
expect(@cachevalidator).to receive(:build_cache_key).at_least(1).and_return(["some_key","some_response_body"])
expect(@cachevalidator).to receive(:log).with("New cache record created")
@cachevalidator.execute(@test_data)
end
it "succeeds when it builds a cache key for the first time" do
expect(@test_data[:vars][:cache][:key]).to eq "some_key"
end
it "raises CacheHit and increments a counter when cache hits" do
expect { @cachevalidator.execute(@test_data) }.to raise_error(RightScale::CloudApi::CacheHit)
expect(@test_data[:vars][:system][:storage][:cache]['some_key'][:hits]).to eq 1
expect { @cachevalidator.execute(@test_data) }.to raise_error(RightScale::CloudApi::CacheHit)
expect(@test_data[:vars][:system][:storage][:cache]['some_key'][:hits]).to eq 2
end
it "replaces a record if the same request gets a different response" do
@test_data[:vars][:system][:storage][:cache]['some_key'][:md5] = 'corrupted'
expect(@cachevalidator).to receive(:log).with("Missed. Record is replaced")
@cachevalidator.execute(@test_data)
expect(@test_data[:vars][:system][:storage][:cache]['some_key'][:hits]).to eq 0
end
end
end
context "build_cache_key" do
before(:each) do
# use send since this is a private method
@opts = {:response => double(:body => nil)}
end
it "fails when it cannot create a key" do
expect { @cachevalidator.__send__(:build_cache_key, {}, @opts) }.to raise_error((RightScale::CloudApi::CacheValidator::Error))
end
it "fails when it cannot create body" do
expect { @cachevalidator.__send__(:build_cache_key, {:key => 'normal_key'}, @opts) }.to raise_error(RightScale::CloudApi::CacheValidator::Error)
end
it "creates key and body from given inputs" do
pattern = {:key => 'normal_key'}
opts = {:response => double(:body => "normal_body")}
expect(@cachevalidator.__send__(:build_cache_key, pattern, opts)).to eq(['normal_key', 'normal_body'])
end
it "creates key and body from given procs" do
proc = double(:is_a? => true)
expect(proc).to receive(:call).and_return("proc_key")
proc_pattern = { :key => proc, :sign => double(:call => "proc_sign_call") }
expect(@cachevalidator.__send__(:build_cache_key, proc_pattern, @opts)).to eq(['proc_key', 'proc_sign_call'])
end
end
end
<file_sep>#--
# Copyright (c) 2013 RightScale, Inc.
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# 'Software'), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
# IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
# CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
# SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#++
module RightScale
module CloudApi
# Standard error
class Error < StandardError
end
# Cache hit error
class CacheHit < Error
end
# Cloud specific errors should be raised with this guy
class CloudError < Error
end
# Low level connection errors
class ConnectionError < CloudError
end
# HTTP Error
class HttpError < CloudError
attr_reader :code
def initialize(code, message)
@code = code.to_s
super(message)
end
end
# Missing Query API pattern Error
class PatternNotFoundError < Error
end
# Retry Attempt exception
class RetryAttempt < Error # :nodoc:
end
# The class is the parent class for all the cloud based thread-safe managers.
#
# The main purpose of the manager is to check if the current thread or fiber has a thread-unsafe
# ApiManager instance created or not. If not them the manager creates than instance of ApiManager
# in the current thread/fiber and feeds the method and parameters to it.
#
# @example
#
# module RightScale
# module CloudApi
# module MyCoolCloudNamespace
# class Manager < CloudApi::Manager
# end
# end
# end
# end
#
# # Create an instance of MyCoolCloudNamespace manager.
# my_cloud = RightScale::CloudApi::MyCoolCloudNamespace::Manager.new(my_cool_creds)
#
# # Make an API call.
# # The call below creates an instance of RightScale::CloudApi::YourCoolCloudNamespace::ApiManager in the
# # current thread and invokes "ListMyCoolResources" method on it.
# my_cloud.ListMyCoolResources #=> cloud response
#
# @see ApiManager
#
class Manager
# The initializer.
#
# @param [Any] args Usually a set of credentials.
#
# @yield [Any] Optional: the block will be passed to ApiManager on its initialization.
#
def initialize(*args, &block)
@args, @block = args, block
options = args.last.is_a?(Hash) ? args.last : {}
@api_manager_class = options[:api_manager_class] || self.class.name.sub(/::Manager$/, '::ApiManager')._constantize
@api_manager_storage = {}
end
# Returns the an instance of ApiManager for the current thread/fiber.
# The method creates a new ApiManager instance ubless it exist.
#
# @return [..::MyCoolCloudNamespace::ApiManager]
#
def api_manager
# Delete dead threads and their managers from the list.
Utils::remove_dead_fibers_and_threads_from_storage(@api_manager_storage)
@api_manager_storage[Utils::current_thread_and_fiber] ||= @api_manager_class::new(*@args, &@block)
end
# Feeds all unknown methods to the ApiManager instance.
#
def method_missing(m, *args, &block)
api_manager.__send__(m, *args, &block)
end
end
end
end
<file_sep>#--
# Copyright (c) 2013 RightScale, Inc.
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# 'Software'), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
# IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
# CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
# SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#++
module RightScale
module CloudApi
# A Wrapper around standard Net::HTTPRequest class.
#
# @api public
#
# The class supports some handy methods for managing the verb, the body, the path and the headers.
# And everythig else can be accessed through *raw* attribute that points to the original
# Net::HTTPRequest instance.
#
class HTTPRequest < HTTPParent
# Request HTTP verb
#
# @return [String]
# @example
# response.verb #=> 'get'
#
attr_accessor :verb
# Request path
#
# @return [String]
# @example
# response.path #=> 'xxx/yyy/zzz'
#
attr_accessor :path
# Request HTTP params
#
# @return [Hash]
# @example
# response.params #=> { 'a' => 'b', 'c' => 'd' }
#
attr_accessor :params
# Max byte to log
BODY_BYTES_TO_LOG = 6000
# Constructor
#
# @param [String,Symbol] verb The current verb ('get', 'post', 'put', etc).
# @param [String,IO,Nil] body The request body.
# @param [String] path The URL path.
# @param [Hash] headers The request headers.
# @param [Net::HTTPRequest] raw The original request (optional).
#
# @return [Rightscale::CloudApi::HTTPRequest] A new instance.
#
# @example
# new('get', 'xxx/yyy/zzz', nil, {})
#
def initialize(verb, path, body, headers, raw=nil)
# Create a request
@verb = verb.to_s.downcase
@path = path
@raw = raw
@headers = HTTPHeaders::new(headers)
self.body = body
end
# Sets a new headers value(s)
#
# @param [String] header The header name.
# @param [String, Array] value The value for the header.
# @return [void]
# @example
# # no example
#
def []=(header, value)
@headers[header] = value
end
# Sets the body and the 'content-length' header
#
# If the body is blank it sets the header to 0.
# If the body is a String it sets the header to the string size.
# If the body is an IO object it tries to open it in *binmode* mode and sets the header to
# the filesize (if the header is not set or points outside of the range of (0..filesize-1)).
#
# @param [Object] new_body
# @return [void]
# @example
# # no example
#
def body=(new_body)
# Set a request body
if new_body.is_a?(IO)
@body = file = new_body
# Make sure the file is openned in binmode
file.binmode if file.respond_to?(:binmode)
# Fix 'content-length': it must not be bigger than a piece of a File left to be read or a String body size.
# Otherwise the connection may behave like crazy causing 4xx or 5xx responses
file_size = file.respond_to?(:lstat) ? file.lstat.size : file.size
bytes_to_read = [ file_size - file.pos, self['content-length'].first ].compact.map{|v| v.to_i }.sort.first # remove nils then make values Integers
if self['content-length'].first._blank? || self['content-length'].first.to_i > bytes_to_read
self['content-length'] = bytes_to_read
end
else
@body = new_body.to_s
self['content-length'] = @body.bytesize if self['content-length'].first.to_i > @body.bytesize
end
end
# Displays the request as a String with the verb and the path
#
# @return [String] The request verb and path info.
# @example
# ec2.request.to_s #=>
# "GET /?AWSAccessKeyId=000..000A&Action=DescribeSecurityGroups&SignatureMethod=HmacSHA256&
# SignatureVersion=2&Timestamp=2013-02-22T23%3A54%3A30.000Z&Version=2012-10-15&
# Signature=Gd...N4yQStO5aKXfYnrM4%3D"
#
def to_s
"#{verb.upcase} #{path}"
end
# Displays the body information
#
# @return [String] The body info.
# @example
# request.body_info #=> "something"
#
def body_info
if is_io?
"#{body.class.name}, size: #{body.respond_to?(:lstat) ? body.lstat.size : body.size}, pos: #{body.pos}"
else
"size: #{body.to_s.bytesize}, first #{BODY_BYTES_TO_LOG} bytes:\n#{body.to_s[0...BODY_BYTES_TO_LOG]}"
end
end
end
end
end<file_sep>#--
# Copyright (c) 2013 RightScale, Inc.
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# 'Software'), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
# IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
# CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
# SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#++
require File.expand_path(File.dirname(__FILE__)) + "/../../spec_helper"
require "net/http/persistent"
describe "RightScale::CloudApi::ConnectionProxy::NetHTTPPersistentProxy" do
before(:each) do
logger = Logger.new(STDOUT)
logger.level = Logger::INFO
@proxy = RightScale::CloudApi::ConnectionProxy::NetHttpPersistentProxy.new
@uri = double(:host => 'host.com',
:port => '777',
:scheme => 'scheme',
:dup => @uri)
@test_data = {
:options => {:user_agent => 'user_agent_data',
:connection_retry_count => 0,
:cloud_api_logger => RightScale::CloudApi::CloudApiLogger.new({:logger => logger})},
:credentials => {},
:callbacks => {},
:vars => {:system => {:block => 'block'}},
:request => {:instance => double(:verb => 'get',
:path => 'some/path',
:body => 'body',
:is_io? => false,
:headers => {'header1' => 'val1',
'header2' => 'val2'},
:raw= => nil)},
:connection => {:uri => @uri}
}
@response = double(:code => '200', :body => 'body', :to_hash => {:code => '200', :body => 'body'})
end
context "when request succeeds" do
before :each do
@connection = double(
:request => @response,
:retry_change_requests= => true,
:shutdown => true )
expect(Net::HTTP::Persistent).to receive(:new).and_return(@connection)
end
it "works" do
@proxy.request(@test_data)
end
end
context "when there is a connection issue" do
before :each do
@connection = double( :retry_change_requests= => true )
expect(Net::HTTP::Persistent).to receive(:new).and_return(@connection)
# failure in the connection should finish and reraise the error
expect(@connection).to receive(:request).and_raise(SocketError.new("Something went wrong"))
expect(@connection).to receive(:shutdown)
end
it "produces a correct error message" do
expect { @proxy.request(@test_data) }.to raise_error(RightScale::CloudApi::ConnectionError, "SocketError: Something went wrong")
end
end
context "low level connection retries" do
before :each do
@connection = double(
:retry_change_requests= => true,
:shutdown => true
)
expect(Net::HTTP::Persistent).to receive(:new).and_return(@connection)
end
context "when retries are disabled" do
before:each do
expect(@connection).to receive(:request).and_raise( Timeout::Error)
@test_data[:options][:connection_retry_count] = 0
expect(@proxy).to receive(:sleep).never
end
it "makes no retries" do
expect { @proxy.request(@test_data) }.to raise_error(RightScale::CloudApi::ConnectionError)
end
end
context "when retries are enabled" do
context "timeouts are enabled" do
before:each do
@retries_count = 3
expect(@connection).to receive(:request).exactly(@retries_count+1).times.and_raise( Timeout::Error)
@test_data[:options][:connection_retry_count] = @retries_count
expect(@proxy).to receive(:sleep).exactly(@retries_count).times
end
it "makes no retries" do
expect { @proxy.request(@test_data) }.to raise_error(RightScale::CloudApi::ConnectionError)
end
end
context "but timeouts are disabled" do
before:each do
@retries_count = 3
@test_data[:options][:connection_retry_count] = @retries_count
@test_data[:options][:abort_on_timeout] = true
end
it "makes no retries on timeout" do
expect(@connection).to receive(:request).and_raise(Timeout::Error)
expect(@proxy).to receive(:sleep).never
expect { @proxy.request(@test_data) }.to raise_error(RightScale::CloudApi::ConnectionError)
end
it "makes retries on non timeout errors" do
expect(@connection).to receive(:request).exactly(@retries_count+1).times.and_raise(SocketError)
expect(@proxy).to receive(:sleep).exactly(@retries_count).times
expect { @proxy.request(@test_data) }.to raise_error(RightScale::CloudApi::ConnectionError)
end
end
context "when there is a connection issue(Address family not supported by protocol)" do
before:each do
@retries_count = 3
@test_data[:options][:connection_retry_count] = @retries_count
end
it "makes retries" do
expect(@connection).to receive(:request).exactly(@retries_count+1).times.and_raise(Errno::EAFNOSUPPORT)
expect(@proxy).to receive(:sleep).exactly(@retries_count).times
expect { @proxy.request(@test_data) }.to raise_error(RightScale::CloudApi::ConnectionError)
end
end
end
end
end
<file_sep>#--
# Copyright (c) 2013 RightScale, Inc.
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# 'Software'), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
# IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
# CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
# SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#++
require 'xml/libxml'
module RightScale
module CloudApi
module Parser
class Sax
UTF_8_STR = "UTF-8"
TEXT_MARK = "@@text"
def self.parse(input, options = {})
# Parse the xml text
# http://libxml.rubyforge.org/rdoc/
xml_context = ::XML::Parser::Context.string(input)
xml_context.encoding = ::XML::Encoding::UTF_8 if options[:encoding] == UTF_8_STR
sax_parser = ::XML::SaxParser.new(xml_context)
sax_parser.callbacks = new(options)
sax_parser.parse
sax_parser.callbacks.result
end
def initialize(options = {})
@tag = {}
@path = []
@str_path = []
@options = options
@cached_strings = {}
end
def result
@cached_strings.clear
@tag
end
def cache_string(name)
unless @cached_strings[name]
name = name.freeze
@cached_strings[name] = name
end
@cached_strings[name]
end
# Callbacks
def on_error(msg)
fail msg
end
def on_start_element_ns(name, attr_hash, prefix, uri, namespaces)
name = cache_string(name)
# Push parent tag
@path << @tag
# Create a new tag
if @tag[name]
@tag[name] = [ @tag[name] ] unless @tag[name].is_a?(Array)
@tag[name] << {}
@tag = @tag[name].last
else
@tag[name] = {}
@tag = @tag[name]
end
# Put attributes
current_namespaces = Array(namespaces.keys)
current_namespaces << nil if current_namespaces._blank?
attr_hash.each do |key, value|
current_namespaces.each do |namespace|
namespace = namespace ? "#{namespace}:" : ''
namespace_and_key = cache_string("@#{namespace}#{key}")
@tag[namespace_and_key] = value
end
end
# Put namespaces
namespaces.each do |key, value|
namespace = cache_string(key ? "@xmlns:#{key}" : '@xmlns')
@tag[namespace] = value
end
end
def on_characters(chars)
# Ignore lines that contains white spaces only
return if chars[/\A\s*\z/m]
# Put Text
if @options[:encoding] == UTF_8_STR
# setting the encoding in context doesn't work(open issue with libxml-ruby).
# force encode as a work around.
# TODO remove the force encoding when issue in libxml is fixed
chars = chars.force_encoding(UTF_8_STR) if chars.respond_to?(:force_encoding)
end
name = cache_string(TEXT_MARK)
(@tag[name] ||= '') << chars
end
def on_comment(msg)
# Put Comments
name = cache_string('@@comment')
(@tag[name] ||= '') << msg
end
def on_end_element_ns(name, prefix, uri)
name = cache_string(name)
# Finalize tag's text
if @tag.key?(TEXT_MARK) && @tag[TEXT_MARK].empty?
# Delete text if it is blank
@tag.delete(TEXT_MARK)
elsif @tag.keys.count == 0
# Set tag value to nil then the tag is blank
@tag = nil
elsif @tag.keys == [TEXT_MARK]
# Set tag value to string if it has no any other data
@tag = @tag[TEXT_MARK]
end
# Make sure we saved the changes
if @path.last[name].is_a?(Array)
# If it is an Array then update the very last item
@path.last[name][-1] = @tag
else
# Otherwise just replace the tag
@path.last[name] = @tag
end
# Pop parent tag
@tag = @path.pop
end
def on_start_document
end
def on_reference (name)
end
def on_processing_instruction(target, data)
end
def on_cdata_block(cdata)
end
def on_has_internal_subset()
end
def on_internal_subset(name, external_id, system_id)
end
def on_is_standalone ()
end
def on_has_external_subset ()
end
def on_external_subset (name, external_id, system_id)
end
def on_end_document
end
end
end
end
end<file_sep>#--
# Copyright (c) 2013 RightScale, Inc.
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# 'Software'), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
# IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
# CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
# SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#++
module RightScale
module CloudApi
# The routine adds a random token to all the GET requests if the corresponding option is enabled.
#
class RequestInitializer < Routine
# Initializes things we may need to initialize.
#
# Sometimes we may need to add a random token for every request so that remote cloud. This may
# be needed when the cloud caches responses for similar requests. Lets say you listed instances
# then created one and then listed them again. S-me clouds (rackspace) may start to report the
# new seconds after it was created because of the caching they do.
#
# But if we mix something random onto every request then 2 consecutive list instances calls will
# look like they are different and the cloud wont return the cached data.
#
def process
# Add a random thing to every get request
if data[:request][:verb] == :get && !data[:options][:random_token]._blank?
random_token_name = 'rsrcarandomtoken'
random_token_name = data[:options][:random_token].to_s if [String, Symbol].include?(data[:options][:random_token].class)
data[:request][:params][random_token_name] = Utils::generate_token
end
end
end
end
end
<file_sep>#--
# Copyright (c) 2013 RightScale, Inc.
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# 'Software'), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
# IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
# CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
# SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#++
module RightScale
module CloudApi
class BlankSlate
instance_methods.each { |m| undef_method m unless m =~ /(^__)|(^object_id$)/ }
end
module Utils
ONE_DAY_OF_SECONDS = 60*60*24
MUST_BE_SET = :__MUST_BE_SET__
NONE = :__NONE__
# URL encodes a string.
#
# @param [String] str A string to escape.
#
# @return [String] The escaped string.
#
# P.S. URI.escape is deprecated in ruby 1.9.2+
#
def self.url_encode(str)
CGI::escape(str.to_s).gsub("+", "%20")
end
def self.base64en(string)
Base64::encode64(string.to_s).strip
end
# Makes a URL params string from a given hash. If block is given the it invokes the block on
# every value so that one could escape it in his own way. If there is no block it url_encode
# values automatically.
#
# @param [Hash] params A set of URL params => values.
#
# @yield [String] Current value.
# @yieldreturn [String] The escaped value.
#
# @return [String] The result.
#
# @example
# RightScale::CloudApi::Utils::params_to_urn(
# "InstanceId.1" => 'i-12345678',
# "InstanceName" => "",
# "Reboot" => nil,
# "XLogPath" => "/mypath/log file.txt") #=> "InstanceId.1=i-12345678&InstanceName=&Reboot&XLogPath=%2Fmypath%2Flog%20with%20spaces.txt"
#
# Block can be used to url encode keys and values:
#
# @example
# RightScale::CloudApi::Utils::params_to_urn(
# "InstanceId.1" => 'i-12345678',
# "InstanceName" => "",
# "Reboot" => nil,
# "XLogPath" => "/mypath/log with spaces.txt") do |value|
# RightScale::CloudApi::AWS::Utils::amz_escape(value) #=> "InstanceId.1=i-12345678&InstanceName=&Reboot&XLogPath=%2Fmypath%2Flog%20with%20spaces.txt"
# end
#
# P.S. Nil values are interpreted as valuesless ones and "" are as blank values
#
def self.params_to_urn(params={}, &block)
block ||= Proc::new { |value| url_encode(value) }
params.keys.sort.map do |name|
value, name = params[name], block.call(name)
value.nil? ? name : [value].flatten.inject([]) { |m, v| m << "#{name}=#{block.call(v)}"; m }.join('&')
end.compact.join('&')
end
# Joins pathes and URN params into a well formed URN.
# Block can be used to url encode URN param's keys and values.
#
# @param [String] absolute Absolute path.
# @param [Array] relatives Relative pathes (Strings) and URL params (Hash) as a very last item.
#
# @yield [String] Current URL param value.
# @yieldreturn [String] The escaped URL param value.
#
# @example
# join_urn(absolute, [relative1, [..., [relativeN, [urn_params, [&block]]]]])
#
# @example
# RightScale::CloudApi::Utils::join_urn(
# "service/v1.0",
# "servers/index",
# "blah-bllah",
# "InstanceId.1" => 'i-12345678',
# "InstanceName" => "",
# "Reboot" => nil,
# "XLogPath" => "/mypath/log with spaces.txt") #=>
# "/service/v1.0/servers/index/blah-bllah?InstanceId.1=i-12345678&InstanceName=&Reboot&XLogPath=%2Fmypath%2Flog%20with%20spaces.txt"
#
def self.join_urn(absolute, *relatives, &block)
# Fix absolute path
absolute = absolute.to_s
result = absolute[/^\//] ? absolute.dup : "/#{absolute}"
# Extract urn_params if they are
urn_params = relatives.last.is_a?(Hash) ? relatives.pop : {}
# Add relative pathes
relatives.each do |relative|
relative = relative.to_s
# skip relative path if is blank
next if relative._blank?
# KD: small hack if relative starts with '/' it should override everything before and become a absolute path
if relative[/^\//]
result = relative
else
result << (result[/\/$/] ? relative : "/#{relative}")
end
end
# Add there a list of params
urn_params = params_to_urn(urn_params, &block)
urn_params._blank? ? result : "#{result}?#{urn_params}"
end
# Get a hash of URL parameters from URL string.
#
# @param [String] url The URL.
#
# @return [Hash] A hash with parameters parsed from the URL.
#
# @example
# parse_url_params('https://ec2.amazonaws.com/?w=1&x=3&y&z') #=> {"z"=>nil, "y"=>nil, "x"=>"3", "w"=>"1"}
#
# @example
# parse_url_params('https://ec2.amazonaws.com') #=> {}
#
def self.extract_url_params(url)
URI::parse(url).query.to_s.split('&').map{|i| i.split('=')}.inject({}){|result, i| result[i[0]] = i[1]; result }
end
#-------------------------------------------------------------------------
# Other Patterns
#-------------------------------------------------------------------------
# Checks if a response/request data matches to the pattern
# Returns true | nil
#
# Pattern is a Hash:
# :verb => Condition, # HTTP verb: get|post|put etc
# :path => Condition, # Request path must match Condition
# :request => Condition, # Request body must match Condition
# :code => Condition, # Response code must match Condition
# :response => Condition, # Response body must match Condition
# :path! => Condition, # Request path must not match Condition
# :request! => Condition, # Request body must not match Condition
# :code! => Condition, # Response code must not match Condition
# :response! => Condition, # Response body must not match Condition
# :if => Proc::new{ |opts| do something } # Extra condition: should return true | false
#
# (Condition above is /RegExp/ or String or Symbol)
#
# Opts is a Hash:
# :request => Object, # HTTP request instance
# :response => Object, # HTTP response instance
# :verb => String, # HTTP verb
# :params => Hash, # Initial request params Hash
#
def self.pattern_matches?(pattern, opts={})
request, response, verb = opts[:request], opts[:response], opts[:verb].to_s.downcase
mapping = { :verb => verb,
:path => request.path,
:request => request.body,
:code => response && response.code,
:response => response && response.body }
# Should not match cases (return immediatelly if any of the conditions matches)
mapping.each do |key, value|
key = "#{key}!".to_sym # Make key negative
condition = pattern[key]
next unless condition
return nil if case
when condition.is_a?(Regexp) then value[condition]
when condition.is_a?(Proc) then condition.call(value)
else condition.to_s.downcase == value.to_s.downcase
end
end
# Should match cases (return immediatelly if any of the conditions does not match)
mapping.each do |key, value|
condition = pattern[key]
next unless condition
return nil unless case
when condition.is_a?(Regexp) then value[condition]
when condition.is_a?(Proc) then condition.call(value)
else condition.to_s.downcase == value.to_s.downcase
end
end
# Should also match
return nil if pattern[:if] && !pattern[:if].call(opts)
true
end
# Returns an Array with the current Thread and Fiber (if exists) instances.
#
# @return [Array] The first item is the current Thread instance and the second item
# is the current Fiber instance. For ruby 1.8.7 may return only the first item.
#
def self::current_thread_and_fiber
if defined?(::Fiber) && ::Fiber::respond_to?(:current)
[ Thread::current, Fiber::current ]
else
[ Thread::current ]
end
end
# Storage is an Hash: [Thread, Fiber|nil] => something
def self::remove_dead_fibers_and_threads_from_storage(storage)
storage.keys.each do |thread_and_fiber|
thread, fiber = *thread_and_fiber
unless (thread.alive? && (!fiber || (fiber && fiber.alive?)))
storage.delete(thread_and_fiber)
end
end
end
# Transforms body (when it is a Hash) into String
#
# @param [Hash] body The request body as a Hash instance.
# @param [String] content_type The required content type ( only XML and JSON formats are supported).
#
# @return [String] The body as a String.
#
# @raise [RightScale::CloudApi::Error] When the content_type is not supported
#
# @example
# RightScale::CloudApi::Utils.contentify_body(@body,'json') #=>
# '{"1":"2"}'
#
# @example
# RightScale::CloudApi::Utils.contentify_body(@body,'xml') #=>
# "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<1>2</1>"
#
def self.contentify_body(body, content_type)
return body unless body.is_a?(Hash)
# Transform
ct = dearrayify(content_type).to_s
case dearrayify(content_type).to_s
when /json/ then body.to_json
when /xml/ then body._to_xml!
else fail Error::new("Cannot transform Hash body into #{ct.inspect} content type")
end
end
# Generates a unique token (Uses UUID when possible)
#
# @return [String] A random 28-symbols string.
#
# @example
# Utils::generate_token => "1f<PASSWORD>650-7b22-f40<KEY>e5" # if UUID
#
# @example
# Utils::generate_token => "<KEY>" # otherwise
#
def self.generate_token
# Use UUID gem if it is
if defined?(UUID) && UUID::respond_to?(:new)
uuid = UUID::new
return uuid.generate if uuid.respond_to?(:generate)
end
# Otherwise generate a random token
time = Time::now.utc
token = "%.2x" % (time.to_i % 256 )
token << "%.6x" % ((rand(256)*1000000 + time.usec) % 16777216 )
# [4, 4, 4, 12].each{ |count| token << "-#{random(count)}" } # UUID like
token << random(28)
token
end
# Generates a random sequence.
#
# @param [Integer] size The length of the random string.
# @param [Hash] options A set of options
# @option options [Integer] :base (is 16 by default to generate HEX output)
# @option options [Integer] :offset (is 0 by default)
#
# @return [String] A random string.
#
# @example
# Utils::random(28) #=> "d8b2292c8de43256b6eaf91129d3" # (0-9 + a-f)
#
# @example
# Utils::random(28, :base => 26, :offset => 10) #=> "jaunwhhdameatxilyavsnnnwpets" # (a-z)
#
# @example
# Utils::random(28, :base => 10) #=> "4330946481889419283880628515" # (0-9)
#
def self.random(size=1, options={})
options[:base] ||= 16
options[:offset] ||= 0
result = ''
size.times{ result << (rand(options[:base]) + options[:offset]).to_s(options[:base] + options[:offset]) }
result
end
# Arrayifies the given object unless it is an Array already.
#
# @param [Object] object Any possible object.
#
# @return [Array] It wraps the given object into Array.
#
def self.arrayify(object)
object.is_a?(Array) ? object : [ object ]
end
# De-Arrayifies the given object.
#
# @param [Object] object Any possible object.
#
# @return [Object] If the object is not an Array instance it just returns the object.
# But if it is an Array the method returns the first element of the array.
#
def self.dearrayify(object)
object.is_a?(Array) ? object.first : object
end
# Returns an XML parser by its string name.
# If the name is empty it returns the default parser (Parser::Sax).
#
# @param [String] xml_parser_name The name of the parser ('sax' or 'rexml').
#
# @return [Class] The parser class
#
# @raise [RightScale::CloudApi::Error] When an unexpected name is passed.
#
def self.get_xml_parser_class(xml_parser_name)
case xml_parser_name.to_s.strip
when 'sax','' then Parser::Sax # the default one
when 'rexml' then Parser::ReXml
else fail Error::new("Unknown parser: #{xml_parser_name.inspect}")
end
end
# Get attribute value(s) or try to inherit it from superclasses.
#
# @param [Class] klass The source class.
# @param [String,Symbol] attribute The name of the attribute reader.
# @param [Array] values Some extra data to be returned with the calculated results.
#
# @return [Array] An array of values in the next formt:
# [ ..., SuperSuperClass.attribute, ..., self.attribute, values[0], ..., values[last]]
#
# @yield [Any] The block is called with "current attribute" so the block can modify it.
# @yieldreturn [Any] When block is passed then it should return a "modified" attribute.
#
def self.inheritance_chain(klass, attribute, *values, &block) # :nodoc:
chain, origin = [], klass
while origin.respond_to?(attribute) do
values.unshift(origin.__send__(attribute))
origin = origin.superclass
end
values.each do |value|
value = block ? block.call(value) : value
chain << value if value
end
chain
end
end
end
end
<file_sep>#--
# Copyright (c) 2013 RightScale, Inc.
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# 'Software'), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
# IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
# CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
# SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#++
require File.expand_path(File.dirname(__FILE__)) + "/../spec_helper"
describe "RightScale::CloudApi::RequestAnalyzer" do
before(:each) do
logger = Logger.new(STDOUT)
logger.level = Logger::INFO
@api_manager = RightScale::CloudApi::ApiManager.new({'x' => 'y'},'endpoint', {:logger => logger})
@api_manager.class.set_routine RightScale::CloudApi::RequestAnalyzer
@api_manager.class.options[:error_patterns] = []
end
context "request keys" do
before(:each) do
@valid_request_keys = RightScale::CloudApi::RequestAnalyzer::REQUEST_KEYS.inject({}) { |result, k| result.merge(k => k.to_s)}
@valid_request_actions = RightScale::CloudApi::RequestAnalyzer::REQUEST_ACTIONS
end
it "creates a pattern for expected keys" do
expected_result = []
@valid_request_actions.each do |action|
expected_result << @valid_request_keys.merge(:action => action)
expect(@api_manager.class.error_pattern(action, @valid_request_keys)).to eq expected_result
end
end
end
context "response keys" do
before(:each) do
@valid_response_keys = RightScale::CloudApi::RequestAnalyzer::RESPONSE_KEYS.inject({}) { |result, k| result.merge(k => k.to_s)}
@valid_response_actions = RightScale::CloudApi::RequestAnalyzer::RESPONSE_ACTIONS
end
it "creates a pattern for expected keys" do
expected_result = []
@valid_response_actions.each do |action|
expected_result << @valid_response_keys.merge(:action => action)
expect(@api_manager.class.error_pattern(action, @valid_response_keys)).to eq expected_result
end
end
end
context "with unexpected keys" do
it "fails to create a pattern" do
valid_request_action = :abort_on_timeout
expect { @api_manager.class.error_pattern(valid_request_action, {:bad_key => "BadKey"}) }.to raise_error(RightScale::CloudApi::RequestAnalyzer::Error)
expect { @api_manager.class.error_pattern(:bad_action, {:verb => /verb/}) }.to raise_error(RightScale::CloudApi::RequestAnalyzer::Error)
expect { @api_manager.class.error_pattern(valid_request_action, {:response => /verb/}) }.to raise_error(RightScale::CloudApi::RequestAnalyzer::Error)
end
end
context "process" do
before(:each) do
logger = Logger.new(STDOUT)
logger.level = Logger::INFO
error_patterns = [{:path =>/Action=(Run|Create)/,
:action =>:abort_on_timeout},
{:response => /InternalError|Internal Server Error|internal service error/i,
:action => :retry}]
@data = {:request => {:instance => 'some_instance',
:verb => 'some_verb',
:orig_params => {}},
:options => {:error_patterns => error_patterns,
:cloud_api_logger => RightScale::CloudApi::CloudApiLogger.new({:logger => logger,
:log_filters => [:request_generator] })}}
@requestanalyzer = RightScale::CloudApi::RequestAnalyzer.new
allow(@requestanalyzer).to receive(:log)
end
context "when patern does not match" do
it "does not set :abort_on_timeout flag" do
expect(RightScale::CloudApi::Utils).to receive(:pattern_matches?).and_return(false)
@requestanalyzer.execute(@data)
expect(@data[:options].has_key?(:abort_on_timeout)).to be(false)
end
end
context "when patern matches" do
it "sets :abort_on_timeout flag" do
expect(RightScale::CloudApi::Utils).to receive(:pattern_matches?).and_return(true)
@requestanalyzer.execute(@data)
expect(@data[:options][:abort_on_timeout]).to be(true)
end
end
end
end<file_sep>#--
# Copyright (c) 2013 RightScale, Inc.
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# 'Software'), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
# IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
# CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
# SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#++
module RightScale
module CloudApi
# The routine analyzes HTTP responses and in the case of HTTP error it takes actions defined
# through *error_pattern* definitions.
#
class ResponseAnalyzer < Routine
class Error < CloudApi::Error
end
# Analyzes an HTTP response.
#
# In the case of 4xx, 5xx HTTP errors the method parses the response body to get the
# error message. Then it tries to find an error pattern that would match to the response.
# If the pattern found it takes the action (:retry, :abort, :disconnect_and_abort or
# :reconnect_and_retry) acordingly to the error patern. If the pattern not fount it just
# fails with RightScale::CloudApi::CloudError.
#
# In the case of 2xx code the method does nothing.
#
# In the case of any other unexpected HTTP code it fails with RightScale::CloudApi::CloudError.
#
# @example
# error_pattern :abort_on_timeout, :path => /Action=(Run|Create)/
# error_pattern :retry, :response => /InternalError|Internal Server Error|internal service error/i
# error_pattern :disconnect_and_abort, :code => /5..|403|408/
# error_pattern :reconnect_and_retry, :code => /4../, :if => Proc.new{ |opts| rand(100) < 10 }
#
def process
# Extract the current response and log it.
response = data[:response][:instance]
unless response.nil?
cloud_api_logger.log("Response received: #{response.to_s}", :response_analyzer)
cloud_api_logger.log("Response headers: #{response.headers_info}", :response_analyzer)
log_method = (response.is_error? || response.is_redirect?) ? :response_analyzer_body_error : :response_analyzer_body
cloud_api_logger.log("Response body: #{response.body_info}", log_method)
end
code = data[:response][:instance].code
body = data[:response][:instance].body
close_current_connection_proc = data[:callbacks][:close_current_connection]
# Analyze the response code.
case code
when /^(5..|4..)/
# Try to parse the received error message.
error_message = if data[:options][:response_error_parser]
parser = data[:options][:response_error_parser]
with_timer("Error parsing with #{parser}") do
parser::parse(data[:response][:instance], data[:options])
end
else
"#{code}: #{body.to_s}"
end
# Get the list of patterns.
error_patterns = data[:options][:error_patterns] || []
opts = { :request => data[:request][:instance],
:response => data[:response][:instance],
:verb => data[:request][:verb],
:params => data[:request][:orig_params].dup }
# Walk through all the patterns and find the first that matches.
error_patterns.each do |pattern|
if Utils::pattern_matches?(pattern, opts)
cloud_api_logger.log("Error code: #{code}, pattern match: #{pattern.inspect}", :response_analyzer, :warn)
# Take the required action.
case pattern[:action]
when :disconnect_and_abort
close_current_connection_proc && close_current_connection_proc.call("Error code: #{code}")
fail(HttpError::new(code, error_message))
when :reconnect_and_retry
close_current_connection_proc && close_current_connection_proc.call("Error code: #{code}")
@data[:vars][:retry][:http] = { :code => code, :message => error_message }
fail(RetryAttempt::new)
when :abort
fail(HttpError::new(code, error_message))
when :retry
invoke_callback_method(data[:options][:before_retry_callback],
:routine => self,
:pattern => pattern,
:opts => opts)
@data[:vars][:retry][:http] = { :code => code, :message => error_message }
fail(RetryAttempt::new)
end
end
end
# The default behavior: this guy hits when there is no any matching pattern
fail(HttpError::new(code, error_message))
when /^3..$/
# In the case of redirect: update a request URI and retry
location = Array(data[:response][:instance].headers['location']).first
# ----- AMAZON HACK BEGIN ----------------------------------------------------------
# Amazon sometimes hide a location host into a response body.
if location._blank? && body && body[/<Endpoint>(.*?)<\/Endpoint>/] && $1
data[:connection][:uri].host = $1
location = data[:connection][:uri].to_s
end
# ----- AMAZON HACK END ------------------------------------------------------------
# Replace URI and retry if the location was successfully set
unless location._blank?
data[:connection][:uri] = ::URI.parse(location)
old_request = data[:request].delete(:instance)
data[:request].delete(:path)
cloud_api_logger.log("Redirect detected: #{location.inspect}", :response_analyzer)
invoke_callback_method(data[:options][:before_redirect_callback],
:routine => self,
:old_request => old_request,
:location => location)
raise(RetryAttempt::new)
else
# ----- OPENSTACK BEGIN ----------------------------------------------------------
# some OS services like Glance returns a list of supported api versions with status 300
# if there is at least one href in the body we need to further analize it in the OS manager
return true if body && body[/href/]
# ----- OPENSTACK END ----------------------------------------------------------
raise HttpError::new(code, "Cannot parse a redirect location")
end
when /^2../
# There is nothing to do on 2xx code
return true
else
fail(Error::new("Unexpected response code: #{code.inspect}"))
end
end
end
end
end
<file_sep>#--
# Copyright (c) 2013 RightScale, Inc.
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# 'Software'), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
# IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
# CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
# SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#++
require File.expand_path(File.dirname(__FILE__)) + "/../spec_helper"
describe "RightScale::CloudApi::ConnectionProxy" do
before(:each) do
logger = Logger.new(STDOUT)
logger.level = Logger::INFO
@connectionproxy = RightScale::CloudApi::ConnectionProxy.new
@test_data = {}
@test_data[:options] = {:cloud_api_logger => RightScale::CloudApi::CloudApiLogger.new({:logger => logger})}
@test_data[:callbacks] = {}
@test_data[:response] = {}
allow(@connectionproxy).to receive(:log)
end
it "creates a close connection callback" do
proxy = double(:request => nil)
expect(RightScale::CloudApi::ConnectionProxy::NetHttpPersistentProxy).to receive(:new).and_return(proxy)
@connectionproxy.execute(@test_data)
expect(@test_data[:callbacks][:close_current_connection]).to be_a(Proc)
end
end
| b6847cb1eff4b7632bd1e6db0ebb289e23d3edd9 | [
"Markdown",
"Ruby",
"Dockerfile"
] | 39 | Ruby | flexera-public/right_cloud_api_base | a087d5b554fa252f47c2275cf81d51b3995b83cf | b12c19f9695cd3319630c20b012a3c9fded04234 |
refs/heads/master | <file_sep>package com.holmesm.games.render.action;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.Set;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import com.holmesm.games.actions.Action;
import com.holmesm.games.actions.ActionBuilder;
import com.holmesm.games.actions.ActionBuilderListener;
import com.holmesm.games.board.Square;
import com.holmesm.games.board.location.Location;
import com.holmesm.games.board.path.Path;
import com.holmesm.games.pieces.GamePiece;
import com.holmesm.games.pieces.factory.ImageRepository;
import com.holmesm.games.render.canvas.Canvas;
import com.holmesm.games.render.renderable.ImageRenderable;
import com.holmesm.games.render.square.HexSquareConverter;
/**
* Single use class, meant to be paired with a single ActionBuilder. do not multi-thread or attach to multiple ActionBuilders.
* @author Balerion
*
*/
public class SwingActionBuilderListener implements ActionBuilderListener{
private Canvas canvas;
private ImageRenderable moveHighlight;
private Map<Square,Path> alreadyHighlighted;
private ActionBuilder callback;
public SwingActionBuilderListener(Canvas canvas) {
alreadyHighlighted = Maps.newHashMap();
this.canvas = canvas;
}
public void selectGamePeice(List<GamePiece> possiblePieces, ActionBuilder callBack) {
if(possiblePieces.isEmpty()) {
callBack.targetsSelected(possiblePieces);
}
callBack.targetsSelected(possiblePieces);
}
public void selectPath(List<Path> possiblePaths, ActionBuilder callBack) {
this.callback = callBack;
try {
moveHighlight = new ImageRenderable(ImageRepository.getImageAt(".\\images\\MovementCircle.png"),HexSquareConverter.HEIGHT*2,HexSquareConverter.WIDTH*2);
for(Path path:possiblePaths) {
for(Square square:path.getDestinations())
{
if(alreadyHighlighted.containsKey(square)) {
continue;
}
canvas.addDecoration(square, moveHighlight);
alreadyHighlighted.put(square,path);
}
}
} catch (IOException e) {
throw new RuntimeException("welp that sucks",e);
}
canvas.repaint();
}
public boolean destinationSelected(Location loc) {
Path path = alreadyHighlighted.get(canvas.getSquareForLocation(loc));
if(path==null) {
return false;
}
for(Square s : alreadyHighlighted.keySet()) {
canvas.removeDecoration(s, moveHighlight);
}
callback.pathSelected(path);
return true;
}
public void actionComplete(Action action) {
action.enact();
}
}
<file_sep>package com.holmesm.games.render.action;
public class PathSelectionPanel {
// So what do we want to do: 1. highlight the possible options in the canvas 2. have them click on one. don't need panel bullshit
}
<file_sep>package com.holmesm.games.render.renderable;
import java.awt.Graphics;
import java.awt.Image;
import com.holmesm.games.render.canvas.Point;
import lombok.AllArgsConstructor;
@AllArgsConstructor
public class ImageRenderable implements RenderableObject{
private Image image;
private double height,width;
public void render(Graphics g,Point center, double zoom) {
// TODO Auto-generated method stub
double renderHeight = zoom*height;
double renderWidth = zoom*width;
g.drawImage(image,(int)(center.getX()-renderWidth/2),(int)(center.getY()-renderHeight/2),(int)renderWidth,(int)renderHeight,null);
}
}
<file_sep>package com.holmesm.games.render.selection;
import javax.swing.JPanel;
public class ActionPanel extends JPanel{
}
<file_sep>package com.holmesm.games.render.selection;
import javax.swing.JPanel;
import com.holmesm.games.board.Square;
import com.holmesm.games.render.renderable.RenderableObject;
public class SelectionDetailPanel extends JPanel{
private RenderableObject selectionImage;
private StatsPanel selectionStats;
private ActionPanel selectionActions;
public SelectionDetailPanel() {
}
public void updateSelection(Square square) {
}
}
<file_sep>package com.holmesm.games.render.renderable;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Polygon;
import com.holmesm.games.render.canvas.Point;
import lombok.AllArgsConstructor;
@AllArgsConstructor
public class PolygonRenderable implements RenderableObject{
private Point[] shape;
private Color lineColor;
private Color fillColor;
private Polygon lastDrawn;
public void render(Graphics g,Point center, double zoom) {
// TODO Auto-generated method stub
g.setColor(lineColor);
Polygon p = new Polygon();
for(Point point:shape) {
p.addPoint((int)(point.getX()*zoom+center.getX()),(int)(point.getY()*zoom+center.getY()));
}
g.drawPolygon(p);
if(fillColor!=null) {
g.setColor(fillColor);
g.fillPolygon(p);
}
lastDrawn = p;
}
public Polygon getLastDrawn() {
return lastDrawn;
}
}
<file_sep>package com.holmesm.games.render.canvas;
import com.holmesm.games.board.location.Location;
public interface LocationTranslator {
public Point translateLocation(Location location);
}
| a6f243aa2fe1ca4e8d1ac0a1fdd375ecf6c33cda | [
"Java"
] | 7 | Java | TheBlackDread12/SBIS----GBR | 35b83414420de386fd36795010824e2ea8c8bfc9 | 44f9c0580c3dd8020c38313b4a00f3e4b3d9d5c2 |
refs/heads/master | <file_sep>using IO.Swagger.Data;
using System.Linq;
namespace IO.Swagger.Security
{
/// <summary>
/// Simple api key validator just checks if there is a header with LONG value.
/// We guess it will be logged in user id.
/// This is very simple implementation only for demo purpose!
/// </summary>
public class SimpleApiKeyValidator : IApiKeyValidator
{
/// <summary>
/// Validates apiKey by checking if it is a long value.
/// </summary>
/// <param name="apiKey"></param>
/// <param name="context"></param>
/// <returns></returns>
public bool Validate(string apiKey, TripAppContext context)
{
long userId;
bool userExists = false;
if (long.TryParse(apiKey, out userId))
{
userExists = context.Users.Any(u => u.Id == userId);
}
return userExists;
}
}
}
<file_sep>/*
* Simple TripApp API
*
* This is a simple TripApp API
*
* OpenAPI spec version: 1.0.0
*
* Generated by: https://github.com/swagger-api/swagger-codegen.git
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.Linq;
using System.IO;
using System.Text;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Runtime.Serialization;
using Newtonsoft.Json;
using System.ComponentModel.DataAnnotations.Schema;
namespace IO.Swagger.Models
{
/// <summary>
///
/// </summary>
[DataContract]
public partial class TicketValidation : IEquatable<TicketValidation>
{
/// <summary>
/// Initializes a new instance of the <see cref="TicketValidation" /> class.
/// </summary>
/// <param name="Id">Id.</param>
/// <param name="ValidationDateTime">ValidationDateTime (required).</param>
/// <param name="IsValid">Is ticket valid? (required).</param>
/// <param name="Ticket">Ticket (required).</param>
/// <param name="Controller">Controller (required).</param>
public TicketValidation(int? Id = null, DateTime? ValidationDateTime = null, bool? IsValid = null, TicketPurchase Ticket = null, User Controller = null)
{
// to ensure "ValidationDateTime" is required (not null)
if (ValidationDateTime == null)
{
throw new InvalidDataException("ValidationDateTime is a required property for TicketValidation and cannot be null");
}
else
{
this.ValidationDateTime = ValidationDateTime;
}
// to ensure "IsValid" is required (not null)
if (IsValid == null)
{
throw new InvalidDataException("IsValid is a required property for TicketValidation and cannot be null");
}
else
{
this.IsValid = IsValid;
}
// to ensure "Ticket" is required (not null)
if (Ticket == null)
{
throw new InvalidDataException("Ticket is a required property for TicketValidation and cannot be null");
}
else
{
this.Ticket = Ticket;
}
// to ensure "Controller" is required (not null)
if (Controller == null)
{
throw new InvalidDataException("Controller is a required property for TicketValidation and cannot be null");
}
else
{
this.Controller = Controller;
}
this.Id = Id;
}
/// <summary>
/// Gets or Sets Id
/// </summary>
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
[DataMember(Name="id")]
public int? Id { get; set; }
/// <summary>
/// Gets or Sets ValidationDateTime
/// </summary>
[DataMember(Name="validationDateTime")]
public DateTime? ValidationDateTime { get; set; }
/// <summary>
/// Is ticket valid?
/// </summary>
/// <value>Is ticket valid?</value>
[DataMember(Name="isValid")]
public bool? IsValid { get; set; }
/// <summary>
/// Gets or Sets Ticket
/// </summary>
[DataMember(Name="ticket")]
public TicketPurchase Ticket { get; set; }
/// <summary>
/// Gets or Sets Controller
/// </summary>
[DataMember(Name="controller")]
public User Controller { get; set; }
/// <summary>
/// Returns the string presentation of the object
/// </summary>
/// <returns>String presentation of the object</returns>
public override string ToString()
{
var sb = new StringBuilder();
sb.Append("class TicketValidation {\n");
sb.Append(" Id: ").Append(Id).Append("\n");
sb.Append(" ValidationDateTime: ").Append(ValidationDateTime).Append("\n");
sb.Append(" IsValid: ").Append(IsValid).Append("\n");
sb.Append(" Ticket: ").Append(Ticket).Append("\n");
sb.Append(" Controller: ").Append(Controller).Append("\n");
sb.Append("}\n");
return sb.ToString();
}
/// <summary>
/// Returns the JSON string presentation of the object
/// </summary>
/// <returns>JSON string presentation of the object</returns>
public string ToJson()
{
return JsonConvert.SerializeObject(this, Formatting.Indented);
}
/// <summary>
/// Returns true if objects are equal
/// </summary>
/// <param name="obj">Object to be compared</param>
/// <returns>Boolean</returns>
public override bool Equals(object obj)
{
if (ReferenceEquals(null, obj)) return false;
if (ReferenceEquals(this, obj)) return true;
if (obj.GetType() != GetType()) return false;
return Equals((TicketValidation)obj);
}
/// <summary>
/// Returns true if TicketValidation instances are equal
/// </summary>
/// <param name="other">Instance of TicketValidation to be compared</param>
/// <returns>Boolean</returns>
public bool Equals(TicketValidation other)
{
if (ReferenceEquals(null, other)) return false;
if (ReferenceEquals(this, other)) return true;
return
(
this.Id == other.Id ||
this.Id != null &&
this.Id.Equals(other.Id)
) &&
(
this.ValidationDateTime == other.ValidationDateTime ||
this.ValidationDateTime != null &&
this.ValidationDateTime.Equals(other.ValidationDateTime)
) &&
(
this.IsValid == other.IsValid ||
this.IsValid != null &&
this.IsValid.Equals(other.IsValid)
) &&
(
this.Ticket == other.Ticket ||
this.Ticket != null &&
this.Ticket.Equals(other.Ticket)
) &&
(
this.Controller == other.Controller ||
this.Controller != null &&
this.Controller.Equals(other.Controller)
);
}
/// <summary>
/// Gets the hash code
/// </summary>
/// <returns>Hash code</returns>
public override int GetHashCode()
{
// credit: http://stackoverflow.com/a/263416/677735
unchecked // Overflow is fine, just wrap
{
int hash = 41;
// Suitable nullity checks etc, of course :)
if (this.Id != null)
hash = hash * 59 + this.Id.GetHashCode();
if (this.ValidationDateTime != null)
hash = hash * 59 + this.ValidationDateTime.GetHashCode();
if (this.IsValid != null)
hash = hash * 59 + this.IsValid.GetHashCode();
if (this.Ticket != null)
hash = hash * 59 + this.Ticket.GetHashCode();
if (this.Controller != null)
hash = hash * 59 + this.Controller.GetHashCode();
return hash;
}
}
#region Operators
public static bool operator ==(TicketValidation left, TicketValidation right)
{
return Equals(left, right);
}
public static bool operator !=(TicketValidation left, TicketValidation right)
{
return !Equals(left, right);
}
#endregion Operators
}
}
<file_sep>package com.example.icf.tripappclient.activities;
import android.Manifest;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.CheckBox;
import android.widget.Toast;
import com.example.icf.tripappclient.PermissionUtils;
import com.example.icf.tripappclient.R;
import com.google.android.gms.maps.CameraUpdate;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
import com.google.android.gms.maps.model.Polyline;
import com.google.android.gms.maps.model.PolylineOptions;
import java.util.ArrayList;
import static com.example.icf.tripappclient.R.id.map;
public class MapActivity extends AppCompatActivity implements OnMapReadyCallback, GoogleMap.OnPolylineClickListener,
GoogleMap.OnMyLocationButtonClickListener, ActivityCompat.OnRequestPermissionsResultCallback{
private GoogleMap map;
private Polyline line1;
private Polyline line2;
private ArrayList<MarkerOptions> line1Stations = new ArrayList<>();
private ArrayList<MarkerOptions> line2Stations = new ArrayList<>();
private ArrayList<Marker> line1Markers = new ArrayList<>();
private ArrayList<Marker> line2Markers = new ArrayList<>();
private boolean mPermissionDenied = false;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_map);
CheckBox check1 = (CheckBox) findViewById(R.id.line1box);
CheckBox check2 = (CheckBox) findViewById(R.id.line2box);
check1.setChecked(true);
check2.setChecked(true);
line1Stations.add(new MarkerOptions().position(new LatLng(45.26562909804279, 19.805066588040745)).title("Majevica"));
line1Stations.add(new MarkerOptions().position(new LatLng(45.25904408732439, 19.809529783841526)).title("Detelinara"));
line1Stations.add(new MarkerOptions().position(new LatLng(45.2504643038709, 19.815280439969456)).title("Klinički centar"));
line1Stations.add(new MarkerOptions().position(new LatLng(45.24218539686798, 19.821031096097386)).title("Bulevar Evrope"));
line1Stations.add(new MarkerOptions().position(new LatLng(45.24152061477978, 19.832017424222386)).title("Park city"));
line1Stations.add(new MarkerOptions().position(new LatLng(45.248485331829535, 19.83890533697263)).title("Maksima Gorkog"));
line1Stations.add(new MarkerOptions().position(new LatLng(45.25408972262825, 19.842317106839573)).title("Centar"));
line2Stations.add(new MarkerOptions().position(new LatLng(45.25300212130111, 19.804379942532933)).title("Bistrica"));
line2Stations.add(new MarkerOptions().position(new LatLng(45.25765449206412, 19.817340376492893)).title("Detelinara centar"));
line2Stations.add(new MarkerOptions().position(new LatLng(45.26013157293705, 19.830729963895237)).title("Bulevar oslobođenja"));
line2Stations.add(new MarkerOptions().position(new LatLng(45.25538877469383, 19.834978582974827)).title("Novosadskog sajma"));
line2Stations.add(new MarkerOptions().position(new LatLng(45.248485331829535, 19.83890533697263)).title("Maksima Gorkog"));
line2Stations.add(new MarkerOptions().position(new LatLng(45.250283026858014, 19.847724440213597)).title("Stražilovska"));
SupportMapFragment mapFragment =
(SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
}
@Override
public void onMapReady(GoogleMap map) {
//map.addMarker(new MarkerOptions().position(new LatLng(45.2671, 19.8335)).title("Marker"));
this.map = map;
CameraUpdate center=
CameraUpdateFactory.newLatLng(new LatLng(45.22013157293705, 19.830729963895237));
map.moveCamera(center);
map.setMapType(GoogleMap.MAP_TYPE_NORMAL);
map.moveCamera(center);
map.animateCamera(CameraUpdateFactory.zoomTo( 13.2f ));
line1 = map.addPolyline(new PolylineOptions()
.clickable(true)
.add( new LatLng(45.26562909804279, 19.805066588040745),
new LatLng(45.23964709613551, 19.822576048489964),
new LatLng(45.240115481588326, 19.82637405645505),
new LatLng(45.24383220990154, 19.84143734228269),
new LatLng(45.25185407508154, 19.83716726553098),
new LatLng(45.25408972262825, 19.842317106839573)));
line1.setColor(Color.argb(127, 0, 255, 0));
line2 = map.addPolyline(new PolylineOptions()
.clickable(true)
.add( new LatLng(45.25300212130111, 19.804379942532933),
new LatLng(45.25850033670732, 19.82017278921262),
new LatLng(45.259587832734276, 19.828240873929417),
new LatLng(45.2604940635127, 19.832103254910862),
new LatLng(45.247865944733604, 19.839227202054417),
new LatLng(45.250283026858014, 19.847724440213597)));
line2.setColor(Color.argb(127, 255, 0, 0));
for(MarkerOptions marker: line1Stations){
Marker mark = map.addMarker(marker);
mark.setVisible(false);
line1Markers.add(mark);
}
for(MarkerOptions marker: line2Stations){
Marker mark = map.addMarker(marker);
mark.setVisible(false);
line2Markers.add(mark);
}
map.setOnPolylineClickListener(this);
map.setOnMyLocationButtonClickListener(this);
enableLocation();
}
@Override
public void onPolylineClick(Polyline line) {
if (line.equals(line1)){
for(Marker marker: line1Markers){
marker.setVisible(true);
}
for(Marker marker: line2Markers){
marker.setVisible(false);
}
}else{
for(Marker marker: line2Markers){
marker.setVisible(true);
}
for(Marker marker: line1Markers){
marker.setVisible(false);
}
}
}
public void onCheckboxClicked(View view){
boolean checked = ((CheckBox) view).isChecked();
switch(view.getId()) {
case R.id.line1box:
if (checked) {
line1.setVisible(true);
}else {
line1.setVisible(false);
for(Marker marker: line1Markers){
marker.setVisible(false);
}
}
break;
case R.id.line2box:
if (checked) {
line2.setVisible(true);
}else{
line2.setVisible(false);
for(Marker marker: line2Markers){
marker.setVisible(false);
}
}
break;
}
}
private void enableLocation() {
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED) {
// Permission to access the location is missing.
PermissionUtils.requestPermission(this, 1,
Manifest.permission.ACCESS_FINE_LOCATION, true);
} else if (map != null) {
// Access to the location has been granted to the app.
map.setMyLocationEnabled(true);
}
}
@Override
public boolean onMyLocationButtonClick() {
return false;
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,
@NonNull int[] grantResults) {
if (requestCode != 1) {
return;
}
if (PermissionUtils.isPermissionGranted(permissions, grantResults,
Manifest.permission.ACCESS_FINE_LOCATION)) {
// Enable the my location layer if the permission has been granted.
enableLocation();
} else {
// Display the missing permission error dialog when the fragments resume.
mPermissionDenied = true;
}
}
@Override
protected void onResumeFragments() {
super.onResumeFragments();
if (mPermissionDenied) {
// Permission was not granted, display error dialog.
showMissingPermissionError();
mPermissionDenied = false;
}
}
/**
* Displays a dialog with error message explaining that the location permission is missing.
*/
private void showMissingPermissionError() {
PermissionUtils.PermissionDeniedDialog
.newInstance(true).show(getSupportFragmentManager(), "dialog");
}
}
<file_sep>using Microsoft.AspNetCore.Builder;
namespace IO.Swagger.Security
{
/// <summary>
/// Api key auth extensions.
/// </summary>
public static class ApiKeyAuthenticationExtensions
{
/// <summary>
/// Extensions for api key auth.
/// </summary>
/// <param name="app"></param>
/// <returns></returns>
public static IApplicationBuilder UseApiKeyAuthentication(this IApplicationBuilder app)
{
return app.UseMiddleware<ApiKeyAuthenticationMiddleware>();
}
}
}
<file_sep>package com.example.icf.tripappclient.database;
import android.content.Context;
import com.example.icf.tripappclient.SessionManager;
import com.example.icf.tripappclient.service.ServiceUtils;
import com.j256.ormlite.android.apptools.OpenHelperManager;
import java.sql.SQLException;
import java.util.Date;
import java.util.List;
import io.swagger.client.model.AdapterPayment;
import io.swagger.client.model.PurchaseCode;
import io.swagger.client.model.TicketPurchase;
import io.swagger.client.model.TicketPurchaseLocal;
import io.swagger.client.model.TicketScannedModel;
import io.swagger.client.model.TicketType;
import io.swagger.client.model.TicketValidation;
import io.swagger.client.model.User;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
/**
* Created by NemanjaM on 18.6.2017.
*/
public class DatabaseState {
private SessionManager session;
private DatabaseHelper databaseHelper;
private Context context;
public DatabaseState(SessionManager session, Context context) {
this.session = session;
this.context = context;
this.databaseHelper = OpenHelperManager.getHelper(context, DatabaseHelper.class);
}
private void fillUserPayments() {
Call<List<PurchaseCode>> callPlus = ServiceUtils.purchaseCodeService.get(session.getUser().getId().toString());
callPlus.enqueue(new Callback<List<PurchaseCode>>() {
@Override
public void onResponse(Call<List<PurchaseCode>> call, Response<List<PurchaseCode>> response) {
if (response.code() == 200) {
List<PurchaseCode> purchaseCodes = response.body();
for (PurchaseCode purchaseCode: purchaseCodes) {
Double price = purchaseCode.getValue();
Date endDateTime = purchaseCode.getUsageDateTime();
String ticketName = "";
boolean isExpense = false;
AdapterPayment payment = new AdapterPayment(price, endDateTime, ticketName, isExpense);
try {
databaseHelper.getPaymentDAO().create(payment);
} catch (SQLException e) {
e.printStackTrace();
}
}
} else {
closeApplication();
}
}
@Override
public void onFailure(Call<List<PurchaseCode>> call, Throwable t) {
closeApplication();
}
});
}
public void refillPayments() {
Call<List<PurchaseCode>> callPlus = ServiceUtils.purchaseCodeService.get(session.getUser().getId().toString());
callPlus.enqueue(new Callback<List<PurchaseCode>>() {
@Override
public void onResponse(Call<List<PurchaseCode>> call, Response<List<PurchaseCode>> response) {
if (response.code() == 200) {
List<PurchaseCode> purchaseCodes = response.body();
refillUserPaymentsFromTickets(purchaseCodes);
} else {
closeApplication();
}
}
@Override
public void onFailure(Call<List<PurchaseCode>> call, Throwable t) {
closeApplication();
}
});
}
private void refillUserPaymentsFromTickets(List<PurchaseCode> paymentsFromCodes) {
final List<PurchaseCode> balancePaymentCodes = paymentsFromCodes;
Call<List<TicketPurchase>> call = ServiceUtils.userTicketsService.get("all:"+session.getUser().getId());
call.enqueue(new Callback<List<TicketPurchase>>() {
@Override
public void onResponse(Call<List<TicketPurchase>> call, Response<List<TicketPurchase>> response) {
if (response.code() == 200) {
databaseHelper.emptyPayments();
List<TicketPurchase> tickets = response.body();
for (TicketPurchase ticket: tickets) {
Double price = ticket.getPrice() * ticket.getNumberOfPassangers();
Date endDateTime = ticket.getEndDateTime();
String ticketName = ticket.getType().getName();
boolean isExpense = true;
AdapterPayment payment = new AdapterPayment(price, ticket.getStartDateTime(),
ticketName, isExpense);
try {
databaseHelper.getPaymentDAO().create(payment);
} catch (SQLException e) {
e.printStackTrace();
}
}
for (PurchaseCode purchaseCode: balancePaymentCodes) {
Double price = purchaseCode.getValue();
Date endDateTime = purchaseCode.getUsageDateTime();
String ticketName = "";
boolean isExpense = false;
AdapterPayment payment = new AdapterPayment(price, endDateTime, ticketName, isExpense);
try {
databaseHelper.getPaymentDAO().create(payment);
} catch (SQLException e) {
e.printStackTrace();
}
}
} else {
closeApplication();
}
}
@Override
public void onFailure(Call<List<TicketPurchase>> call, Throwable t) {
closeApplication();
}
});
}
private void fillScannedTickets() {
Call<List<TicketValidation>> call = ServiceUtils.ticketValidationService.getValidations(session.getUser().getId().toString());
call.enqueue(new Callback<List<TicketValidation>>() {
@Override
public void onResponse(Call<List<TicketValidation>> call, Response<List<TicketValidation>> response) {
if (response.code() == 200) {
List<TicketValidation> validations = response.body();
for (TicketValidation validation: validations) {
String ticketMix = "";
String userMix = "";
if (validation.getTicket() != null) {
TicketType ticketType = validation.getTicket().getType();
String ticketTypeName = "";
if (ticketType != null){
ticketTypeName = ticketType.getName();
}
int ticketId = validation.getTicket().getId();
User validationUser = validation.getTicket().getUser();
String userSurname = "";
String userLetter = "";
if (validationUser != null) {
userSurname = validation.getTicket().getUser().getLastName();
userLetter = validation.getTicket().getUser().getFirstName().substring(0, 1);
}
ticketMix = ticketTypeName + " (" + ticketId + ")";
userMix = userLetter + ". " + userSurname;
}
TicketScannedModel scannedTicket = new TicketScannedModel(
validation.getValidationDateTime(), validation.getIsValid(), ticketMix, userMix);
try {
databaseHelper.getScannedDAO().create(scannedTicket);
} catch (SQLException e) {
e.printStackTrace();
}
}
} else {
closeApplication();
}
}
@Override
public void onFailure(Call<List<TicketValidation>> call, Throwable t) {
closeApplication();
}
});
}
public void refillScannedTickets() {
Call<List<TicketValidation>> call = ServiceUtils.ticketValidationService.getValidations(session.getUser().getId().toString());
call.enqueue(new Callback<List<TicketValidation>>() {
@Override
public void onResponse(Call<List<TicketValidation>> call, Response<List<TicketValidation>> response) {
if (response.code() == 200) {
databaseHelper.emptyScannedTickets();
List<TicketValidation> validations = response.body();
for (TicketValidation validation: validations) {
String ticketMix = "";
String userMix = "";
if (validation.getTicket() != null) {
TicketType ticketType = validation.getTicket().getType();
String ticketTypeName = "";
if (ticketType != null){
ticketTypeName = ticketType.getName();
}
int ticketId = validation.getTicket().getId();
User validationUser = validation.getTicket().getUser();
String userSurname = "";
String userLetter = "";
if (validationUser != null) {
userSurname = validation.getTicket().getUser().getLastName();
userLetter = validation.getTicket().getUser().getFirstName().substring(0, 1);
}
ticketMix = ticketTypeName + " (" + ticketId + ")";
userMix = userLetter + ". " + userSurname;
}
TicketScannedModel scannedTicket = new TicketScannedModel(
validation.getValidationDateTime(), validation.getIsValid(), ticketMix, userMix);
try {
databaseHelper.getScannedDAO().create(scannedTicket);
} catch (SQLException e) {
e.printStackTrace();
}
}
} else {
closeApplication();
}
}
@Override
public void onFailure(Call<List<TicketValidation>> call, Throwable t) {
closeApplication();
}
});
}
private void fillUserTickets() {
Call<List<TicketPurchase>> call = ServiceUtils.userTicketsService.get("all:"+session.getUser().getId());
call.enqueue(new Callback<List<TicketPurchase>>() {
@Override
public void onResponse(Call<List<TicketPurchase>> call, Response<List<TicketPurchase>> response) {
if (response.code() == 200) {
List<TicketPurchase> tickets = response.body();
for (TicketPurchase ticket: tickets) {
Double price = ticket.getPrice() * ticket.getNumberOfPassangers();
Date endDateTime = ticket.getEndDateTime();
String ticketName = ticket.getType().getName();
boolean isExpense = true;
AdapterPayment payment = new AdapterPayment(price, ticket.getStartDateTime(),
ticketName, isExpense);
TicketPurchaseLocal ticketLocal = new TicketPurchaseLocal(ticket.getId(),
ticket.getCode().toString(), price, ticket.getStartDateTime(),
endDateTime, ticket.getNumberOfPassangers(), ticketName,
ticket.getUserId());
try {
databaseHelper.getTicketDAO().create(ticketLocal);
databaseHelper.getPaymentDAO().create(payment);
} catch (SQLException e) {
e.printStackTrace();
}
}
} else {
closeApplication();
}
}
@Override
public void onFailure(Call<List<TicketPurchase>> call, Throwable t) {
closeApplication();
}
});
}
public void refillTickets() {
Call<List<TicketPurchase>> call = ServiceUtils.userTicketsService.get("all:"+session.getUser().getId());
call.enqueue(new Callback<List<TicketPurchase>>() {
@Override
public void onResponse(Call<List<TicketPurchase>> call, Response<List<TicketPurchase>> response) {
if (response.code() == 200) {
databaseHelper.emptyTickets();
List<TicketPurchase> tickets = response.body();
for (TicketPurchase ticket: tickets) {
Double price = ticket.getPrice() * ticket.getNumberOfPassangers();
Date endDateTime = ticket.getEndDateTime();
String ticketName = ticket.getType().getName();
boolean isExpense = true;
AdapterPayment payment = new AdapterPayment(price, ticket.getStartDateTime(),
ticketName, isExpense);
TicketPurchaseLocal ticketLocal = new TicketPurchaseLocal(ticket.getId(),
ticket.getCode().toString(), price, ticket.getStartDateTime(),
endDateTime, ticket.getNumberOfPassangers(), ticketName,
ticket.getUserId());
try {
databaseHelper.getTicketDAO().create(ticketLocal);
databaseHelper.getPaymentDAO().create(payment);
} catch (SQLException e) {
e.printStackTrace();
}
}
} else {
closeApplication();
}
}
@Override
public void onFailure(Call<List<TicketPurchase>> call, Throwable t) {
closeApplication();
}
});
}
public void emptyPayments() {
databaseHelper.emptyPayments();
}
public void emptyTickets() {
databaseHelper.emptyTickets();
}
public void emptyScannedTickets() {
databaseHelper.emptyScannedTickets();
}
public void emptyDatabase() {
databaseHelper.emptyDatabase();
}
public DatabaseHelper getDatabaseHelper() {
return databaseHelper;
}
private void closeApplication() {
// TODO zatvoriti aplikaciju jer ne moze da radi bez ovih podataka
}
}
<file_sep>apply plugin: 'com.android.application'
repositories {
jcenter()
}
apply plugin: 'com.android.application'
android {
useLibrary 'org.apache.http.legacy'
compileSdkVersion 25
buildToolsVersion "25.0.2"
defaultConfig {
applicationId "com.example.icf.tripappclient"
minSdkVersion 15
targetSdkVersion 25
versionCode 1
versionName "1.0"
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
multiDexEnabled = true
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
debug {
debuggable true
}
}
packagingOptions {
exclude 'META-INF/DEPENDENCIES.txt'
exclude 'META-INF/LICENSE.txt'
exclude 'META-INF/NOTICE.txt'
exclude 'META-INF/NOTICE'
exclude 'META-INF/LICENSE'
exclude 'META-INF/DEPENDENCIES'
exclude 'META-INF/notice.txt'
exclude 'META-INF/license.txt'
exclude 'META-INF/dependencies.txt'
exclude 'META-INF/LGPL2.1'
}
}
ext {
swagger_annotations_version = "1.5.0"
gson_version = "2.3.1"
volley_version = "1.0.0"
junit_version = "4.12"
robolectric_version = "3.0"
concurrent_unit_version = "0.4.2"
}
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
exclude group: 'com.android.support', module: 'support-annotations'
})
compile "io.swagger:swagger-annotations:$swagger_annotations_version"
compile "com.android.volley:volley:${volley_version}"
testCompile "junit:junit:$junit_version"
testCompile "org.robolectric:robolectric:${robolectric_version}"
testCompile "net.jodah:concurrentunit:${concurrent_unit_version}"
compile group: 'com.j256.ormlite', name: 'ormlite-core', version: '4.48'
compile group: 'com.j256.ormlite', name: 'ormlite-android', version: '4.48'
compile 'com.journeyapps:zxing-android-embedded:3.5.0'
compile 'com.android.support:appcompat-v7:25.3.1'
compile 'com.android.support.constraint:constraint-layout:1.0.2'
compile 'com.android.support:support-v4:25.3.1'
compile 'com.android.support:design:25.3.1'
compile 'com.android.support:preference-v7:25.3.1'
compile 'com.google.zxing:core:3.2.1'
compile 'com.squareup.retrofit2:retrofit:2.0.2'
compile 'com.squareup.retrofit2:converter-gson:2.0.2'
compile 'com.squareup.okhttp3:logging-interceptor:3.2.0'
compile 'com.android.support:recyclerview-v7:25.3.1'
compile 'com.google.firebase:firebase-messaging:10.0.1'
compile 'com.google.android.gms:play-services-location:10.0.1'
compile 'com.google.android.gms:play-services-maps:10.0.1'
}
/*dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
androidTestCompile('com.android.support.overflow_items.espresso:espresso-core:2.2.2', {
exclude group: 'com.android.support', module: 'support-annotations'
})
compile 'com.android.support:appcompat-v7:25.3.1'
compile 'com.android.support.constraint:constraint-layout:1.0.2'
testCompile 'junit:junit:4.12'
}*/
apply plugin: 'com.google.gms.google-services'<file_sep>package com.example.icf.tripappclient.service;
import io.swagger.client.model.User;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.http.Body;
import retrofit2.http.DELETE;
import retrofit2.http.GET;
import retrofit2.http.Header;
import retrofit2.http.Headers;
import retrofit2.http.POST;
import retrofit2.http.PUT;
import retrofit2.http.Path;
import retrofit2.http.Query;
/**
* Created by NemanjaM on 17.5.2017.
*/
public interface UserService {
@Headers({
"User-Agent: Mobile-Android",
"Content-Type:application/json"
})
@GET("user/{username}")
Call<User> get(@Header("Authorization") String auth, @Path("username") String username);
@Headers({
"User-Agent: Mobile-Android",
"Content-Type:application/json"
})
@POST("user/")
Call<ResponseBody> add(@Body User user);
/*
@Headers({
"User-Agent: Mobile-Android",
"Content-Type:application/json"
})
@DELETE("user/{username}")
Call<ResponseBody> remove(@Path("username") String username);
*/
@Headers({
"User-Agent: Mobile-Android",
"Content-Type:application/json"
})
@GET("user/login")
Call<User> login(@Query("username") String username, @Query("password") String password);
/*
@Headers({
"User-Agent: Mobile-Android",
"Content-Type:application/json"
})
@GET("user/logout")
Call<ResponseBody> logout(@Query("username") String username, @Query("password") String password);
*/
@Headers({
"User-Agent: Mobile-Android",
"Content-Type:application/json"
})
@PUT("user/{username}")
Call<User> add(@Header("Authorization") long UserId, @Path("username") String username, @Body User user);
@Headers({
"User-Agent: Mobile-Android",
"Content-Type:application/json"
})
@POST("user/")
Call<User> register(@Body User user);
}
<file_sep>using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace IO.Swagger.Data
{
public class TripAppContext : DbContext
{
public TripAppContext(DbContextOptions<TripAppContext> options): base(options)
{
}
public DbSet<Models.User> Users { get; set; }
public DbSet<Models.TicketType> Types { get; set; }
public DbSet<Models.TicketValidation> Validations { get; set; }
public DbSet<Models.TicketPurchase> Purchases { get; set; }
public DbSet<Models.PurchaseCode> Codes { get; set; }
}
}
<file_sep>using Microsoft.Extensions.Options;
namespace IO.Swagger.Security
{
/// <summary>
/// Implements IOption for api key.
/// </summary>
public class ApiKeyOptions : IOptions<ApiKeyAuthenticationOptions>
{
ApiKeyAuthenticationOptions _options;
/// <summary>
/// Create new option.
/// </summary>
/// <param name="options"></param>
public ApiKeyOptions(ApiKeyAuthenticationOptions options)
{
_options = options;
}
/// <summary>
/// returns api key auth option.
/// </summary>
public ApiKeyAuthenticationOptions Value
{
get
{
return _options;
}
}
}
}
<file_sep>package io.swagger.client.model;
import com.example.icf.tripappclient.SessionManager;
import com.google.gson.annotations.SerializedName;
import com.j256.ormlite.field.DatabaseField;
import com.j256.ormlite.table.DatabaseTable;
import java.io.Serializable;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
/**
* Created by NemanjaM on 23.5.2017.
*/
@DatabaseTable(tableName = "Payment")
@ApiModel(description = "")
public class AdapterPayment implements Serializable {
@DatabaseField(generatedId = true)
@SerializedName("paymentId")
private Integer paymentId = null;
@DatabaseField
@SerializedName("price")
private Double price = null;
@DatabaseField
@SerializedName("endDateTime")
private Date endDateTime = null;
@DatabaseField
@SerializedName("ticketName")
private String ticketName = null;
@DatabaseField
@SerializedName("isExpense")
private boolean isExpense = false;
public AdapterPayment() {
}
public AdapterPayment(Double price, Date endDateTime, String ticketName, boolean isExpense) {
this.paymentId = paymentId;
this.price = price;
this.endDateTime = endDateTime;
this.ticketName = ticketName;
this.isExpense = isExpense;
}
/**
**/
@ApiModelProperty(value = "")
public Integer getPaymentId() {
return paymentId;
}
public void setPaymentId(Integer paymentId) {
this.paymentId = paymentId;
}
/**
**/
@ApiModelProperty(value = "")
public Double getPrice() {
return price;
}
public void setPrice(Double price) {
this.price = price;
}
/**
**/
@ApiModelProperty(value = "")
public Date getEndDateTime() {
return endDateTime;
}
public void setEndDateTime(Date endDateTime) {
this.endDateTime = endDateTime;
}
public String getEndDateTimeString(){
DateFormat df = new SimpleDateFormat(SessionManager.DATETIME_FORMAT);
return df.format(endDateTime);
}
/**
**/
@ApiModelProperty(value = "")
public String getTicketName() {
return ticketName;
}
public void setTicketName(String ticketName) {
this.ticketName = ticketName;
}
/**
**/
@ApiModelProperty(value = "")
public boolean getIsExpense() {
return isExpense;
}
public void setIsExpense(boolean isExpense) {
this.isExpense = isExpense;
}
}
<file_sep>/*
* Simple TripApp API
*
* This is a simple TripApp API
*
* OpenAPI spec version: 1.0.0
*
* Generated by: https://github.com/swagger-api/swagger-codegen.git
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using Newtonsoft.Json;
using System;
using System.ComponentModel.DataAnnotations.Schema;
using System.IO;
using System.Runtime.Serialization;
using System.Text;
namespace IO.Swagger.Models
{
[DataContract]
public partial class PurchaseCode : IEquatable<PurchaseCode>
{
/// <summary>
/// Initializes a new instance of the <see cref="PurchaseCode" /> class.
/// </summary>
/// <param name="Id">Id (required).</param>
/// <param name="Code">Code (required).</param>
/// <param name="Value">Value (required).</param>
/// <param name="GenarationDateTime">GenarationDateTime (required).</param>
/// <param name="UsageDateTime">UsageDateTime (required).</param>
/// <param name="Used">Already used by a user. (required).</param>
/// <param name="User">User.</param>
public PurchaseCode(int? Id = null, Guid? Code = null, double? Value = null, DateTime? GenarationDateTime = null, DateTime? UsageDateTime = null, bool? Used = null, User User = null)
{
// to ensure "Id" is required (not null)
if (Id == null)
{
throw new InvalidDataException("Id is a required property for PurchaseCode and cannot be null");
}
else
{
this.Id = Id;
}
// to ensure "Code" is required (not null)
if (Code == null)
{
throw new InvalidDataException("Code is a required property for PurchaseCode and cannot be null");
}
else
{
this.Code = Code;
}
// to ensure "Value" is required (not null)
if (Value == null)
{
throw new InvalidDataException("Value is a required property for PurchaseCode and cannot be null");
}
else
{
this.Value = Value;
}
// to ensure "GenarationDateTime" is required (not null)
if (GenarationDateTime == null)
{
throw new InvalidDataException("GenarationDateTime is a required property for PurchaseCode and cannot be null");
}
else
{
this.GenarationDateTime = GenarationDateTime;
}
// to ensure "Used" is required (not null)
if (Used == null)
{
throw new InvalidDataException("Used is a required property for PurchaseCode and cannot be null");
}
else
{
this.Used = Used;
}
this.UsageDateTime = UsageDateTime;
this.User = User;
}
/// <summary>
/// Gets or Sets Id
/// </summary>
[DataMember(Name="id")]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int? Id { get; set; }
/// <summary>
/// Gets or Sets Code
/// </summary>
[DataMember(Name="code")]
public Guid? Code { get; set; }
/// <summary>
/// Gets or Sets Value
/// </summary>
[DataMember(Name="value")]
public double? Value { get; set; }
/// <summary>
/// Gets or Sets GenarationDateTime
/// </summary>
[DataMember(Name="genarationDateTime")]
public DateTime? GenarationDateTime { get; set; }
/// <summary>
/// Gets or Sets UsageDateTime
/// </summary>
[DataMember(Name="usageDateTime")]
public DateTime? UsageDateTime { get; set; }
/// <summary>
/// Already used by a user.
/// </summary>
/// <value>Already used by a user.</value>
[DataMember(Name="used")]
public bool? Used { get; set; }
/// <summary>
/// Gets or Sets User
/// </summary>
[DataMember(Name="user")]
public User User { get; set; }
/// <summary>
/// Returns the string presentation of the object
/// </summary>
/// <returns>String presentation of the object</returns>
public override string ToString()
{
var sb = new StringBuilder();
sb.Append("class PurchaseCode {\n");
sb.Append(" Id: ").Append(Id).Append("\n");
sb.Append(" Code: ").Append(Code).Append("\n");
sb.Append(" Value: ").Append(Value).Append("\n");
sb.Append(" GenarationDateTime: ").Append(GenarationDateTime).Append("\n");
sb.Append(" UsageDateTime: ").Append(UsageDateTime).Append("\n");
sb.Append(" Used: ").Append(Used).Append("\n");
sb.Append(" User: ").Append(User).Append("\n");
sb.Append("}\n");
return sb.ToString();
}
/// <summary>
/// Returns the JSON string presentation of the object
/// </summary>
/// <returns>JSON string presentation of the object</returns>
public string ToJson()
{
return JsonConvert.SerializeObject(this, Formatting.Indented);
}
/// <summary>
/// Returns true if objects are equal
/// </summary>
/// <param name="obj">Object to be compared</param>
/// <returns>Boolean</returns>
public override bool Equals(object obj)
{
if (ReferenceEquals(null, obj)) return false;
if (ReferenceEquals(this, obj)) return true;
if (obj.GetType() != GetType()) return false;
return Equals((PurchaseCode)obj);
}
/// <summary>
/// Returns true if PurchaseCode instances are equal
/// </summary>
/// <param name="other">Instance of PurchaseCode to be compared</param>
/// <returns>Boolean</returns>
public bool Equals(PurchaseCode other)
{
if (ReferenceEquals(null, other)) return false;
if (ReferenceEquals(this, other)) return true;
return
(
this.Id == other.Id ||
this.Id != null &&
this.Id.Equals(other.Id)
) &&
(
this.Code == other.Code ||
this.Code != null &&
this.Code.Equals(other.Code)
) &&
(
this.Value == other.Value ||
this.Value != null &&
this.Value.Equals(other.Value)
) &&
(
this.GenarationDateTime == other.GenarationDateTime ||
this.GenarationDateTime != null &&
this.GenarationDateTime.Equals(other.GenarationDateTime)
) &&
(
this.UsageDateTime == other.UsageDateTime ||
this.UsageDateTime != null &&
this.UsageDateTime.Equals(other.UsageDateTime)
) &&
(
this.Used == other.Used ||
this.Used != null &&
this.Used.Equals(other.Used)
) &&
(
this.User == other.User ||
this.User != null &&
this.User.Equals(other.User)
);
}
/// <summary>
/// Gets the hash code
/// </summary>
/// <returns>Hash code</returns>
public override int GetHashCode()
{
// credit: http://stackoverflow.com/a/263416/677735
unchecked // Overflow is fine, just wrap
{
int hash = 41;
// Suitable nullity checks etc, of course :)
if (this.Id != null)
hash = hash * 59 + this.Id.GetHashCode();
if (this.Code != null)
hash = hash * 59 + this.Code.GetHashCode();
if (this.Value != null)
hash = hash * 59 + this.Value.GetHashCode();
if (this.GenarationDateTime != null)
hash = hash * 59 + this.GenarationDateTime.GetHashCode();
if (this.UsageDateTime != null)
hash = hash * 59 + this.UsageDateTime.GetHashCode();
if (this.Used != null)
hash = hash * 59 + this.Used.GetHashCode();
if (this.User != null)
hash = hash * 59 + this.User.GetHashCode();
return hash;
}
}
#region Operators
public static bool operator ==(PurchaseCode left, PurchaseCode right)
{
return Equals(left, right);
}
public static bool operator !=(PurchaseCode left, PurchaseCode right)
{
return !Equals(left, right);
}
#endregion Operators
}
}
<file_sep>/*
* Simple TripApp API
*
* This is a simple TripApp API
*
* OpenAPI spec version: 1.0.0
*
* Generated by: https://github.com/swagger-api/swagger-codegen.git
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using IO.Swagger.Data;
using IO.Swagger.Logging;
using IO.Swagger.Models;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using Swashbuckle.SwaggerGen.Annotations;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
namespace IO.Swagger.Controllers
{
/// <summary>
/// Users API
/// </summary>
public class UsersApiController : Controller
{
private readonly TripAppContext _context;
private readonly IPasswordHasher<User> _hasher;
private readonly ILogger _logger;
/// <summary>
/// Initializes controller.
/// </summary>
/// <param name="context">Db context to use.</param>
/// <param name="hasher">Hasher for user passwords.</param>
public UsersApiController(TripAppContext context, IPasswordHasher<User> hasher, ILogger<UsersApiController> logger)
{
_context = context;
_hasher = hasher;
_logger = logger;
}
/// <summary>
/// Creates / Registers user
/// </summary>
/// <remarks>This can be done by any user.</remarks>
/// <param name="user">Created user object</param>
/// <response code="400">bad input parameter</response>
/// <response code="409">an existing item already exists</response>
/// <response code="201">successful operation</response>
[HttpPost]
[Route("/sergiosuperstar/TripAppSimple/1.0.0/user")]
[SwaggerOperation("CreateUser")]
public virtual IActionResult CreateUser([FromBody]User user)
{
// TODO ftn: Add validation to the user parameter!!!
// Return 400 - BadRequest if not valid!
if (_context.Users.FirstOrDefault(u => u.Username == user.Username) != null)
{
return StatusCode(StatusCodes.Status409Conflict, user); // 409 already exists!
}
try
{
// QUICK DIRTY FIX AS SEED HAVE FIXED ID's so USER will get used one!:
Random r = new Random();
int rInt = r.Next(1, 1000000000);
user.Id = rInt;
// END OF QUICK DIRTY FIX.
user.Password = <PASSWORD>(null, user.Password);
// Ensure token is created:
if (user.RefreshToken == null)
{
user.RefreshToken = Guid.NewGuid();
}
_context.Users.Add(user);
_context.SaveChanges();
user.Password = <PASSWORD>;
return Created(Request.Host.ToString(), user); // 201 Created successfuly.
}
catch (Exception)
{
_logger.LogError(LoggingEvents.INSERT_ITEM, "CreateUser({user}) NOT ADDED", user);
return StatusCode(StatusCodes.Status500InternalServerError);
}
}
/// <summary>
/// Deletes user
/// </summary>
/// <remarks>This can only be done by an administrator.</remarks>
/// <param name="username">The username that needs to be deleted</param>
/// <response code="200">successful operation</response>
/// <response code="400">Invalid username supplied</response>
/// <response code="404">User not found</response>
[HttpDelete]
[Route("/sergiosuperstar/TripAppSimple/1.0.0/user/{username}")]
[SwaggerOperation("DeleteUser")]
[Authorize(ActiveAuthenticationSchemes = "apikey")]
public virtual void DeleteUser([FromRoute]string username)
{
throw new NotImplementedException();
}
/// <summary>
/// Gets user by username
/// </summary>
/// <param name="username">The username that needs to be fetched.</param>
/// <response code="200">successful operation</response>
/// <response code="400">Invalid username supplied</response>
/// <response code="404">User not found</response>
[HttpGet]
[Route("/sergiosuperstar/TripAppSimple/1.0.0/user/{username}")]
[SwaggerOperation("GetUserByUsername")]
[SwaggerResponse(200, type: typeof(User))]
[Authorize(ActiveAuthenticationSchemes = "apikey")]
public virtual IActionResult GetUserByUsername([FromRoute]string username)
{
// EXAMPLE: How to use logged in user identity:
var userName = User.Identity.Name;
var userId = User.FindFirst(ClaimTypes.NameIdentifier).Value;
var userFirstName = User.FindFirst(ClaimTypes.GivenName).Value;
var userLastName = User.FindFirst(ClaimTypes.Surname).Value;
// TODO: Check if your role allows you to get user by username?
// if (!User.IsInRole("administrator")){ return StatusCode(StatusCodes.YOU HAVE NO RIGHT....
try
{
var user = _context.Users.FirstOrDefault(u => u.Username == username);
if (user == null)
{
return StatusCode(StatusCodes.Status404NotFound);
}
user.Password = <PASSWORD>;
return new ObjectResult(user);
}
catch (Exception)
{
_logger.LogError(LoggingEvents.GET_ITEM, "GetUserByUsername({username}) NOT FOUND", username);
return StatusCode(StatusCodes.Status500InternalServerError);
}
}
/// <summary>
/// Logs user into the system
/// </summary>
/// <param name="username">The user name for login</param>
/// <param name="password">The password for login in clear text</param>
/// <response code="200">successful operation</response>
/// <response code="400">Invalid username/password supplied</response>
[HttpGet]
[Route("/sergiosuperstar/TripAppSimple/1.0.0/user/login")]
[SwaggerOperation("LoginUser")]
[SwaggerResponse(200, type: typeof(string))]
public virtual IActionResult LoginUser([FromQuery]string username, [FromQuery]string password)
{
try
{
var user = _context.Users.FirstOrDefault(u => u.Username == username);
if (user != null && _hasher.VerifyHashedPassword(null, user.Password, password).Equals(PasswordVerificationResult.Success))
{
user.Password = null;
return new ObjectResult(user);
}
// Set it to null so it is not
return StatusCode(StatusCodes.Status404NotFound);
}
catch (Exception)
{
_logger.LogError(LoggingEvents.GET_ITEM, "LoginUser({username}) NOT FOUND", username);
return StatusCode(StatusCodes.Status500InternalServerError);
}
}
/// <summary>
/// Logs out currenty logged in user session
/// </summary>
/// <response code="200">successful operation</response>
[HttpGet]
[Route("/sergiosuperstar/TripAppSimple/1.0.0/user/logout")]
[SwaggerOperation("LogoutUser")]
[Authorize(ActiveAuthenticationSchemes = "apikey")]
public IActionResult LogoutUser()
{
// TODO FTN: Add support for security - read user token or whatever!
return Ok();
}
/// <summary>
/// Updates user
/// </summary>
/// <remarks>This can only be done by the logged in user.</remarks>
/// <param name="username">username of a user that is about to be updated</param>
/// <param name="user">Updated user object</param>
/// <response code="200">successful operation</response>
/// <response code="400">Invalid user supplied</response>
/// <response code="404">User not found</response>
[HttpPut]
[Route("/sergiosuperstar/TripAppSimple/1.0.0/user/{username}")]
[SwaggerOperation("UpdateUser")]
[SwaggerResponse(200, type: typeof(User))]
[Authorize(ActiveAuthenticationSchemes = "apikey")]
public virtual IActionResult UpdateUser([FromRoute]string username, [FromBody]User user)
{
// TODO ftn: Add validation to the user parameter!!!
// Return 400 - BadRequest if not valid!
var existingUser = _context.Users.FirstOrDefault(u => u.Username == username);
if (existingUser == null)
{
return StatusCode(StatusCodes.Status404NotFound, username); // 400 not found!
}
try
{
user.Password = <PASSWORD>(null, user.Password);
// Ensure token is changed:
user.RefreshToken = Guid.NewGuid();
_context.Entry(existingUser).CurrentValues.SetValues(user);
_context.SaveChanges();
return Ok(user);
}
catch (Exception)
{
_logger.LogError(LoggingEvents.UPDATE_ITEM, "UpdateUser({username}) NOT UPDATED", username);
return StatusCode(StatusCodes.Status500InternalServerError);
}
}
/// <summary>
/// searches users
/// </summary>
/// <remarks>By passing in the appropriate options, you can search for available users in the system </remarks>
/// <param name="searchString">pass an optional search string for looking up users</param>
/// <param name="skip">number of records to skip for pagination</param>
/// <param name="limit">maximum number of records to return</param>
/// <response code="200">search results matching criteria</response>
/// <response code="400">bad input parameter</response>
[HttpGet]
[Route("/sergiosuperstar/TripAppSimple/1.0.0/user")]
[SwaggerOperation("SearchUsers")]
[SwaggerResponse(200, type: typeof(List<User>))]
public virtual IActionResult SearchUsers([FromQuery]string searchString, [FromQuery]int? skip, [FromQuery]int? limit)
{
try
{
var users = _context.Users;
return new ObjectResult(users);
}
catch (Exception)
{
_logger.LogError(LoggingEvents.LIST_ITEMS, "SearchUsers({searchString}) NOT FOUND", searchString);
return StatusCode(StatusCodes.Status500InternalServerError);
}
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace IO.Swagger.Models
{
/// <summary>
/// Operations for ticket types manipulation
/// </summary>
public partial class TicketType
{
/// <summary>
/// Default constructor.
/// </summary>
public TicketType()
{
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace IO.Swagger.Models
{
/// <summary>
/// Operations for users manipulation
/// </summary>
public partial class User
{
/// <summary>
/// Default constructor.
/// </summary>
public User()
{
}
}
}
<file_sep>package com.example.icf.tripappclient.activities;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.View;
import android.support.design.widget.NavigationView;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.widget.TextView;
import android.widget.Toast;
import com.example.icf.tripappclient.R;
import com.example.icf.tripappclient.SessionManager;
import com.example.icf.tripappclient.fragments.AccountBalance;
import com.example.icf.tripappclient.fragments.Home;
import com.example.icf.tripappclient.fragments.TicketHistory;
import com.example.icf.tripappclient.fragments.TicketInfo;
import com.example.icf.tripappclient.fragments.TicketPurchase;
import com.example.icf.tripappclient.fragments.TicketScanned;
import com.example.icf.tripappclient.service.ServiceUtils;
import com.google.firebase.messaging.FirebaseMessaging;
import com.google.zxing.integration.android.IntentIntegrator;
import com.google.zxing.integration.android.IntentResult;
import java.sql.SQLException;
import io.swagger.client.model.TicketPurchaseLocal;
import io.swagger.client.model.TicketType;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
private SessionManager session;
private DrawerLayout drawer;
private ProgressDialog progress;
private Activity that = this;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
session = new SessionManager(getApplicationContext());
progress = new ProgressDialog(this);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
toggle.setDrawerIndicatorEnabled(false);
toggle.setHomeAsUpIndicator(R.drawable.ic_dehaze_white_24dp);
drawer.addDrawerListener(toggle);
toggle.syncState();
toggle.setToolbarNavigationClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (drawer.isDrawerVisible(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
drawer.openDrawer(GravityCompat.START);
}
}
});
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
View header=navigationView.getHeaderView(0);
TextView name = (TextView)header.findViewById(R.id.user_info);
name.setText("Welcome, " + session.getUser().getUsername());
Menu menu = navigationView.getMenu();
MenuItem inspectorMenu = menu.findItem(R.id.inspector_menu);
inspectorMenu.setVisible(session.getUserRole().equals("controller"));
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
Home homeFragment = new Home();
fragmentTransaction.add(R.id.fragment_container, homeFragment);
fragmentTransaction.commit();
// DO NOT CHANGE TOPIC NAME FROM 'news'!
// IT MAY TAKE 24HRS TO CREATE IT AGAIN!
FirebaseMessaging.getInstance().subscribeToTopic("news");
Boolean isBalance = getIntent().getBooleanExtra("balance", false);
if(isBalance){
session.reloadUserBalance(this);
}
}
@Override
public void onResume() {
super.onResume();
if(!session.isLoggedIn()){
Intent i = new Intent(getApplicationContext(), LoginActivity.class);
startActivity(i);
}
}
@Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
if (getSupportFragmentManager().getBackStackEntryCount() > 0)
getSupportFragmentManager().popBackStack();
else
super.onBackPressed();
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
// getMenuInflater().inflate(R.menu.overflow_items, menu);
// menu.getItem(0).setIcon(getResources().getDrawable(R.drawable.ic_more_vert_white_24dp));
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
@Override
public boolean onNavigationItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.nav_main) { /* MOZDA NE TREBA NEW FRAGMENT NEGO IH CUVATI KAO POLJA */
Home homeFragment = new Home();
changeFragment(homeFragment);
} else if (id == R.id.nav_ticket_info) {
progress.setMessage("Collecting data. Please wait...");
progress.show();
Call<io.swagger.client.model.TicketPurchase> call = ServiceUtils.ticketPurchaseService.get("my:" + session.getUser().getId());
call.enqueue(new Callback<io.swagger.client.model.TicketPurchase>() {
@Override
public void onResponse(Call<io.swagger.client.model.TicketPurchase> call, Response<io.swagger.client.model.TicketPurchase> response) {
if (response.code() == 200) {
progress.dismiss();
TicketInfo tiFragment = TicketInfo.newInstance(new TicketPurchaseLocal(response.body()));
changeFragment(tiFragment);
} else {
progress.dismiss();
Toast.makeText(that, "No active tickets", Toast.LENGTH_LONG).show();
Home homeFragment = new Home();
changeFragment(homeFragment);
}
}
@Override
public void onFailure(Call<io.swagger.client.model.TicketPurchase> call, Throwable t) {
progress.dismiss();
Toast.makeText(that, "Could not connect to server.", Toast.LENGTH_LONG).show();
Home homeFragment = new Home();
changeFragment(homeFragment);
}
});
} else if (id == R.id.nav_ticket_balance) {
AccountBalance abFragment = new AccountBalance();
changeFragment(abFragment);
} else if (id == R.id.nav_camera) {
Intent intent = new Intent(this, ContinuousCaptureActivity.class);
startActivity(intent);
} else if (id == R.id.nav_scanned) {
TicketScanned tsFragment = new TicketScanned();
changeFragment(tsFragment);
} else if (id == R.id.nav_ticket_history) {
TicketHistory thFragment = new TicketHistory();
changeFragment(thFragment);
} else if (id == R.id.nav_settings) {
Intent intent = new Intent(getApplicationContext(), SettingsActivity.class);
startActivity(intent);
} else if (id == R.id.nav_logout) {
session.logOut();
Intent intent = new Intent(getApplicationContext(), LoginActivity.class);
startActivity(intent);
} else if (id == R.id.nav_add){
View view = findViewById(R.id.addMoney);
scanVoucher(view);
//mockCode();
}else if (id == R.id.nav_map) {
Intent intent = new Intent(this, MapActivity.class);
startActivity(intent);
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
public void buyOneHourTicket(View view) {
TicketType type = new TicketType();
type.setId(1);
type.setDuration(1);
type.setPrice(1.2);
type.setName("Hourly ticket");
TicketPurchase tpFragment = TicketPurchase.newInstance(type);
changeFragment(tpFragment);
}
public void buyOneDayTicket(View view) {
TicketType type = new TicketType();
type.setId(2);
type.setDuration(24);
type.setPrice(5d);
type.setName("Daily ticket");
TicketPurchase tpFragment = TicketPurchase.newInstance(type);
changeFragment(tpFragment);
}
public void buyWeekDayTicket(View view) {
TicketType type = new TicketType();
type.setId(3);
type.setDuration(24*7);
type.setPrice(16d);
type.setName("Weekly ticket");
TicketPurchase tpFragment = TicketPurchase.newInstance(type);
changeFragment(tpFragment);
}
public void buyMonthDayTicket(View view) {
TicketType type = new TicketType();
type.setId(4);
type.setDuration(24*30);
type.setPrice(40d);
type.setName("Monthly ticket");
TicketPurchase tpFragment = TicketPurchase.newInstance(type);
changeFragment(tpFragment);
}
public void changeFragment(Fragment destinationFragment) {
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.fragment_container, destinationFragment);
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();
}
public void respondNewPurchase(boolean successful, io.swagger.client.model.TicketPurchase ticket) {
if (successful) {
Toast.makeText(this, "Purchase successful", Toast.LENGTH_LONG).show();
session.setBalance(ticket.getUser().getBalance());
session.getDatabaseState().refillTickets();
session.getDatabaseState().refillPayments();
TicketPurchaseLocal ticketLocal = new TicketPurchaseLocal(ticket.getId(),
ticket.getCode().toString(), ticket.getPrice(), ticket.getStartDateTime(),
ticket.getEndDateTime(), ticket.getNumberOfPassangers(), ticket.getType().getName(),
ticket.getUserId());
TicketInfo tiFragment = TicketInfo.newInstance(ticketLocal);
changeFragment(tiFragment);
} else {
Toast.makeText(this, "Purchase failed or not enough credits", Toast.LENGTH_LONG).show();
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
IntentResult result = IntentIntegrator.parseActivityResult(requestCode, resultCode, data);
if(result != null) {
if(result.getContents() == null) {
Toast.makeText(this, "Cancelled", Toast.LENGTH_LONG).show();
} else {
}
} else {
// This is important, otherwise the result will not be passed to the fragment
super.onActivityResult(requestCode, resultCode, data);
}
}
public void scanVoucher(View view){
Intent intent = new Intent(this, VoucherScannerActivity.class);
startActivity(intent);
}
/*protected void mockCode() {
PurchaseCode code = new PurchaseCode();
code.setCode(UUID.fromString("33994bf3-0489-4897-9b87-853c76124ee1"));
code.setUser(session.getUser());
Call<Boolean> call = ServiceUtils.purchaseCodeService.put(code);
call.enqueue(new Callback<Boolean>() {
@Override
public void onResponse(Call<Boolean> call, Response<Boolean> response) {
if (response.code() == 200) {
Boolean resp = response.body();
session.reloadUserBalance((MainActivity) that);
} else {
}
}
@Override
public void onFailure(Call<Boolean> call, Throwable t) {
}
});
}
*/
public SessionManager getSession() {
return session;
}
}
<file_sep>package com.example.icf.tripappclient.fragments;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.v4.app.Fragment;
import android.support.v7.app.AppCompatActivity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.Spinner;
import android.widget.TextView;
import com.example.icf.tripappclient.R;
import com.example.icf.tripappclient.SessionManager;
import com.example.icf.tripappclient.activities.MainActivity;
import com.example.icf.tripappclient.service.ServiceUtils;
import io.swagger.client.model.TicketType;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
/**
* Created by Vuletic on 28.4.2017.
*/
public class TicketPurchase extends Fragment {
private SessionManager session;
private TicketType type;
private int PRIVATE_MODE = 0;
private Context _context;
private SharedPreferences pref;
private String notificationToken;
private Boolean notificationsEnabled;
public TicketPurchase() {
}
public static TicketPurchase newInstance(TicketType type) {
TicketPurchase fragment = new TicketPurchase();
Bundle args = new Bundle();
args.putSerializable("ticket_type", type);
fragment.setArguments(args);
return fragment;
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
_context = getActivity().getApplicationContext();
pref = _context.getSharedPreferences("notification", PRIVATE_MODE);
notificationToken = pref.getString("token", null);
SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(_context);
notificationsEnabled = sharedPref.getBoolean("notifications_on", true);
((AppCompatActivity)getActivity()).getSupportActionBar().setTitle(R.string.ticket_purchase_title);
session = new SessionManager(getActivity().getApplicationContext());
type = (TicketType) getArguments().getSerializable("ticket_type");
View view = inflater.inflate(R.layout.fragment_ticket_purchase,
container, false);
Button button = (Button) view.findViewById(R.id.buyButton);
button.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View v)
{
io.swagger.client.model.TicketPurchase purchase = new io.swagger.client.model.TicketPurchase();
purchase.setTypeId(type.getId());
purchase.setUserId(session.getUser().getId());
Spinner mySpinner = (Spinner) getView().findViewById(R.id.numberValue);
int num = Integer.parseInt(mySpinner.getSelectedItem().toString());
purchase.setNumberOfPassangers(num);
Call<io.swagger.client.model.TicketPurchase> call = ServiceUtils.ticketPurchaseService.add(session.getUser().getId().toString(), notificationToken, notificationsEnabled, purchase);
call.enqueue(new Callback<io.swagger.client.model.TicketPurchase>() {
@Override
public void onResponse(Call<io.swagger.client.model.TicketPurchase> call, Response<io.swagger.client.model.TicketPurchase> response) {
if (response.code() == 201) {
io.swagger.client.model.TicketPurchase ticket = response.body();
((MainActivity)getActivity()).respondNewPurchase(true, ticket);
} else {
((MainActivity)getActivity()).respondNewPurchase(false, null);
}
}
@Override
public void onFailure(Call<io.swagger.client.model.TicketPurchase> call, Throwable t) {
((MainActivity)getActivity()).respondNewPurchase(false, null);
}
});
}
});
return view;
}
@Override
public void onStart() {
super.onStart();
TextView priceText = (TextView) getView().findViewById(R.id.priceValue);
priceText.setText(type.getPrice().toString());
TextView ticketHeader = (TextView) getView().findViewById(R.id.ticketHeader);
ticketHeader.setText(type.getName());
/* TextView duration = (TextView) getView().findViewById(R.id.durationValue);
duration.setText(type.getDuration() + " hours");*/
//View view=inflater.inflate(R.layout.fragment_ticket_purchase, container, false);
final Spinner countSpinner = (Spinner) getView().findViewById(R.id.numberValue);
final TextView totalText = (TextView) getView().findViewById(R.id.totalValue);
countSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parentView, View selectedItemView, int position, long id) {
int count = Integer.parseInt(countSpinner.getSelectedItem().toString());
String totalString = String.format("%.2f", count * type.getPrice());
totalText.setText(totalString);
}
@Override
public void onNothingSelected(AdapterView<?> parentView) {
// your code here
}
});
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Threading.Tasks;
namespace IO.Swagger.Models
{
/// <summary>
/// Push Notification Details
/// </summary>
[DataContract]
public partial class Notification
{
/// <summary>
/// Title
/// </summary>
[DataMember]
public string Title { get; set; }
/// <summary>
/// Message
/// </summary>
[DataMember]
public string Message { get; set; }
/// <summary>
/// Topic
/// </summary>
[DataMember]
public string Topic { get; set; }
/// <summary>
/// Device Id
/// </summary>
[DataMember]
public string DeviceID { get; set; }
}
}
<file_sep># TripApp (FTN-PMA-E2-17)
# Opšte o aplikaciji #
Aplikacija služi za kupovinu i validaciju karata za gradski saobraćajni prevoz. Putnici, koji poseduju naloge, putem mobilnog telefona kupuju karte, koje mogu biti različitih vrsta, odnosno vremenskog ograničenja ( 1 sat, 1 dan, 7 dana, 30 dana). Njima se potom skidaju sredstva sa naloga i dobijaju kartu sa QR kodom.
## Putnici ##
Putnici kreiraju nalog, dopunjavaju sredstva na svom racunu skeniranjem QR kodova za dopunu i kupuju karte za vožnju.
## Kontrolori ##
Kontrolori kamerom skeniraju karte (QR kodove) putnicima i proveravaju validnost istih. Ukoliko je karta nevalidna, kontrolor dobija odgovarajuci ispis i/ili zvučni signal. Kontrolor može da pregleda istoriju kontrola koje je izvršio.
## Administratori ##
Upravljaju serverskim delom aplikacije i to tako što:
- Upravljaju nalozima kontrolera i po potrebi putnika.
- Upravljaju linijama prevoza i redom vožnje.
## Mapa linija ##
Aplikacija sadrži i pregled svih linija prevoza na mapi. Postoji mogućnost pregleda pojedinačnih linija na mapi.
## Notifikacije ##
- Aplikacija šalje notifikacije 5 minuta pre isteka aktivne karte u trajanju od 1 sat.
# Uloge #
## Putnik ##
- Može da se uloguje i/ili kreira novi nalog.
- Može da dopuni stanje pomoću skeniranja QR koda za dopunu.
- Može da kupuje različite tipove karata.
## Kontrolor ##
- Može da izvrši kontrolu karata skeniranje QR koda kamerom telefona.
- Može da vrši uvid u istoriju kontrola koje je uradio.
## Admin ##
- Može da administrira druge korisnike na web delu sistema.
- Može da menja linije i red vožnje.
# Delovi Aplikacije #
## Master view ##
- Za putnika - spisak tipova karata
- Za kontrolora - opcija za skeniranje karata, spisak ocitanih karata
## Detail view ##
- Karta detaljno
## Settings ##
- Ukljucivanje/iskljucivanje notifikacija i podešavanje zvuka i vibracije
- Send usage statistics
- Koliko unazad da pamti karte
## About ##
Verzija aplikacije
# Skica aplikacije #

# Model podataka #

<file_sep>using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Runtime.Serialization;
using System.Threading.Tasks;
namespace IO.Swagger.Models
{
/// <summary>
/// Operations for tickets purchases manipulation
/// </summary>
public partial class TicketPurchase
{
/// <summary>
/// Default constructor.
/// </summary>
public TicketPurchase()
{
}
/// <summary>
/// Gets or Sets User Id
/// </summary>
[DataMember(Name = "userId")]
[ForeignKey("User")]
public long? UserId { get; set; }
/// <summary>
/// Gets or Sets Type Id
/// </summary>
[DataMember(Name = "typeId")]
[ForeignKey("Type")]
public int? TypeId { get; set; }
}
}
<file_sep>package com.example.icf.tripappclient.fragments;
import android.content.ContentResolver;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.preference.PreferenceManager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;
import android.widget.TextView;
import com.example.icf.tripappclient.R;
import com.example.icf.tripappclient.SessionManager;
import com.example.icf.tripappclient.activities.MainActivity;
import com.example.icf.tripappclient.adapters.PaymentAdapter;
import com.j256.ormlite.dao.Dao;
import java.sql.SQLException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.List;
import java.util.Locale;
import io.swagger.client.model.*;
import io.swagger.client.model.TicketPurchase;
/**
* Created by Vuletic on 28.4.2017.
*/
public class AccountBalance extends Fragment {
private SessionManager session;
private List<AdapterPayment> payments;
private ListView paymentsDisplay;
private TextView noPaymentsDisplay;
public AccountBalance() {
// Required empty public constructor
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
((AppCompatActivity)getActivity()).getSupportActionBar().setTitle(R.string.account_balance_title);
session = new SessionManager(getActivity().getApplicationContext());
fillData();
return inflater.inflate(R.layout.fragment_account_balance, container, false);
}
@Override
public void onStart() {
super.onStart();
TextView balance = (TextView) getView().findViewById(R.id.balanceValue);
balance.setText(String.format("%.2f", session.getUser().getBalance()));
AppCompatActivity activity = (AppCompatActivity) getActivity();
this.paymentsDisplay = (ListView) activity.findViewById(R.id.paymentsList);
this.noPaymentsDisplay = (TextView) activity.findViewById(R.id.emptyPaymentsLabel);
if (payments.size() > 0) {
this.paymentsDisplay.setVisibility(View.VISIBLE);
this.noPaymentsDisplay.setVisibility(View.GONE);
this.paymentsDisplay.setAdapter(new PaymentAdapter(activity, payments));
} else {
this.paymentsDisplay.setVisibility(View.GONE);
this.noPaymentsDisplay.setVisibility(View.VISIBLE);
}
}
private void fillData() {
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(((AppCompatActivity) getActivity()).getApplicationContext());
int pref = 0 - Integer.parseInt(preferences.getString("payments_history", "30"));
Calendar current = new GregorianCalendar();
current.add(Calendar.DATE, pref);
Date margin = current.getTime();
payments = new ArrayList<>();
final Dao<AdapterPayment, Integer> paymentsDAO = ((MainActivity)getActivity()).getSession()
.getDatabaseState().getDatabaseHelper().getPaymentDAO();
try {
payments = paymentsDAO.queryForAll();
} catch (SQLException e) {
e.printStackTrace();
}
if (pref < 998) {
payments = filterByDate(payments, margin);
}
Collections.sort(payments, new CustomComparatorDec());
}
private class CustomComparatorDec implements Comparator<AdapterPayment> {
@Override
public int compare(AdapterPayment o1, AdapterPayment o2) {
return o2.getEndDateTime().compareTo(o1.getEndDateTime());
}
}
private List<AdapterPayment> filterByDate(List<AdapterPayment> list, Date date) {
List<AdapterPayment> result = new ArrayList<>();
for (AdapterPayment element: list) {
if (element.getEndDateTime().after(date)) {
result.add(element);
}
}
return result;
}
/* @Override
public void onResume() {
super.onResume();
TextView balance = (TextView) getView().findViewById(R.id.balanceValue);
balance.setText(String.format("%.2f", session.getUser().getBalance()));
}*/
}
<file_sep>package com.example.icf.tripappclient.adapters;
import android.content.Context;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
import com.example.icf.tripappclient.R;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import io.swagger.client.model.TicketPurchase;
import io.swagger.client.model.TicketPurchaseLocal;
/**
* Created by NemanjaM on 1.6.2017.
*/
public class TicketAdapter extends ArrayAdapter<TicketPurchaseLocal> {
private Context context;
private List<TicketPurchaseLocal> tickets;
public TicketAdapter(Context context, List<TicketPurchaseLocal> tickets) {
super(context, R.layout.single_ticket ,tickets);
this.context = context;
this.tickets = tickets;
}
@NonNull
@Override
public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view = inflater.inflate(R.layout.single_ticket, parent, false);
TextView value_date = (TextView) view.findViewById(R.id.ticket_expired);
TextView value_type = (TextView) view.findViewById(R.id.ticket_type);
TextView value_cost = (TextView) view.findViewById(R.id.ticket_price);
double cost = tickets.get(position).getPrice();
Date date = tickets.get(position).getEndDateTime();
String ticket = tickets.get(position).getTypeString();
int numberOfPassangers = tickets.get(position).getNumberOfPassangers();
String dateValue = tickets.get(position).getEndDateTimeString();
//String dateValue = new SimpleDateFormat("dd.MM.'yy (HH:mm)").format(date);
String costValue = String.format("%.2f", cost * numberOfPassangers);
value_date.setText(dateValue);
value_type.setText(ticket);
value_cost.setText(costValue);
return view;
}
}
<file_sep>package com.example.icf.tripappclient.service;
import java.util.List;
import io.swagger.client.model.TicketPurchase;
import io.swagger.client.model.TicketType;
import retrofit2.Call;
import retrofit2.http.GET;
import retrofit2.http.Headers;
import retrofit2.http.Path;
/**
* Created by NemanjaM on 11.6.2017.
*/
public interface TickeTypeService {
@Headers({
"User-Agent: Mobile-Android",
"Content-Type:application/json"
})
@GET("tickets/alltypes")
Call<List<TicketType>> get();
}
<file_sep>using IO.Swagger.Data;
using IO.Swagger.Logging;
using IO.Swagger.Models;
using IO.Swagger.Notifications;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using Swashbuckle.SwaggerGen.Annotations;
using System;
using System.Net.Http;
using System.Security.Claims;
using System.Text;
using System.Threading.Tasks;
namespace IO.Swagger.Controllers
{
/// <summary>
/// Notifications controller
/// </summary>
public class NotificationsApi : Controller
{
private readonly TripAppContext _context;
private readonly IConfiguration _configuration;
private readonly ILogger _logger;
private readonly FCMNotificationService _notificationService;
/// <summary>
/// Notifications controller constructor.
/// </summary>
/// <param name="context"></param>
/// <param name="configuration"></param>
/// <param name="logger"></param>
/// <param name="notificationService"></param>
public NotificationsApi(TripAppContext context, IConfiguration configuration, ILogger<TicketsApiController> logger, FCMNotificationService notificationService)
{
_context = context;
_configuration = configuration;
_logger = logger;
_notificationService = notificationService;
}
/// <summary>
/// Sends news to all devices
/// </summary>
/// <remarks>Sends a notification</remarks>
/// <param name="notification">Notification item to send</param>
/// <response code="200">Sent</response>
/// <response code="400">invalid input, object invalid</response>
[HttpPost]
[Route("/sergiosuperstar/TripAppSimple/1.0.0/notifications")]
[SwaggerOperation("Send")]
[Authorize(ActiveAuthenticationSchemes = "apikey")]
public virtual async Task<IActionResult> Send([FromBody]Notification notification)
{
// TODO FTN: Add validation!
var loggedInUserId = long.Parse(User.FindFirst(ClaimTypes.NameIdentifier).Value);
var hasValidTopic = notification != null
&& notification.Topic == "news";
if (!hasValidTopic)
{
return StatusCode(StatusCodes.Status400BadRequest, notification);
}
try
{
var result = await _notificationService.Send(notification);
return Ok();
}
catch (Exception)
{
_logger.LogError(LoggingEvents.INSERT_ITEM, $"Send({notification}) FAILED.", notification);
return StatusCode(StatusCodes.Status500InternalServerError);
}
}
}
}
<file_sep>/*
* Simple TripApp API
*
* This is a simple TripApp API
*
* OpenAPI spec version: 1.0.0
*
* Generated by: https://github.com/swagger-api/swagger-codegen.git
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.IO;
using System.Linq;
using System.Net;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
using Swashbuckle.SwaggerGen.Annotations;
using IO.Swagger.Models;
using IO.Swagger.Data;
using Microsoft.AspNetCore.Http;
using Microsoft.EntityFrameworkCore;
using IO.Swagger.Logging;
using Microsoft.Extensions.Logging;
namespace IO.Swagger.Controllers
{
/// <summary>
/// Operations for purchase codes manipulation
/// </summary>
public class CodesApiController : Controller
{
private readonly TripAppContext _context;
private readonly ILogger _logger;
/// <summary>
/// Initializes controller.
/// </summary>
/// <param name="context">Db context to use.</param>
public CodesApiController(TripAppContext context, ILogger<CodesApiController> logger)
{
_context = context;
_logger = logger;
}
/// <summary>
/// adds a purchase code
/// </summary>
/// <remarks>Adds an item to the system</remarks>
/// <param name="purchaseCode">PurchaseCode item to add</param>
/// <response code="201">item created</response>
/// <response code="400">invalid input, object invalid</response>
/// <response code="409">item already exists</response>
[HttpPost]
[Route("/sergiosuperstar/TripAppSimple/1.0.0/codes")]
[SwaggerOperation("AddPurchaseCode")]
public virtual IActionResult AddPurchaseCode([FromBody]PurchaseCode purchaseCode)
{
// TODO ftn: Add validation to the purchaseCode parameter!!!
// Return 400 - BadRequest if not valid!
if (_context.Codes.FirstOrDefault(c => c.Code == purchaseCode.Code) != null)
{
return StatusCode(StatusCodes.Status409Conflict, purchaseCode); // 409 already exists!
}
try
{
_context.Codes.Add(purchaseCode);
_context.SaveChanges();
return Created(Request.Host.ToString(), purchaseCode); // 201 Created successfuly.
}
catch (Exception)
{
_logger.LogError(LoggingEvents.INSERT_ITEM, "AddPurchaseCode({purchaseCode}) NOT ADDED", purchaseCode);
return StatusCode(StatusCodes.Status500InternalServerError);
}
}
/// <summary>
/// searches purchase codes for specified user
/// </summary>
/// <remarks>By passing in the appropriate options, you can search for purchase codes that were used by user </remarks>
/// <param name="userId">pass an user id for desired user</param>
/// <response code="200">search results matching criteria</response>
/// <response code="400">bad input parameter</response>
[HttpGet]
[Route("/sergiosuperstar/TripAppSimple/1.0.0/codes/user")]
[SwaggerOperation("SearchCodesForUser")]
[SwaggerResponse(200, type: typeof(List<PurchaseCode>))]
public virtual IActionResult SearchCodesForUser([FromQuery]string userId)
{
int id;
if (!int.TryParse(userId, out id))
{
return StatusCode(StatusCodes.Status400BadRequest);
}
try
{
var codes = _context.Codes.Where(c => c.User.Id == id).ToList();
return new ObjectResult(codes);
}
catch (Exception)
{
_logger.LogError(LoggingEvents.LIST_ITEMS, "SearchCodes({userId}) NOT FOUND", userId);
return StatusCode(StatusCodes.Status500InternalServerError);
}
}
/// <summary>
/// searches purchase codes
/// </summary>
/// <remarks>By passing in the appropriate options, you can search for available purchase codes in the system </remarks>
/// <param name="searchString">pass an optional search string for looking up purchase codes</param>
/// <param name="skip">number of records to skip for pagination</param>
/// <param name="limit">maximum number of records to return</param>
/// <response code="200">search results matching criteria</response>
/// <response code="400">bad input parameter</response>
[HttpGet]
[Route("/sergiosuperstar/TripAppSimple/1.0.0/codes")]
[SwaggerOperation("SearchCodes")]
[SwaggerResponse(200, type: typeof(List<PurchaseCode>))]
public virtual IActionResult SearchCodes([FromQuery]string searchString, [FromQuery]int? skip, [FromQuery]int? limit)
{
int id;
if (!int.TryParse(searchString, out id))
{
return StatusCode(StatusCodes.Status400BadRequest);
}
try
{
var codes = _context.Codes.Where(c => c.Id == id).ToList();
return new ObjectResult(codes);
}
catch (Exception)
{
_logger.LogError(LoggingEvents.LIST_ITEMS, "SearchCodes({searchString}) NOT FOUND", searchString);
return StatusCode(StatusCodes.Status500InternalServerError);
}
}
/// <summary>
/// updates a purchase code
/// </summary>
/// <remarks>Updates an item to the system</remarks>
/// <param name="purchaseCode">PurchaseCode item to update</param>
/// <response code="200">item updated</response>
/// <response code="400">invalid input, object invalid</response>
/// <response code="404">invalid input, object not found</response>
[HttpPut]
[Route("/sergiosuperstar/TripAppSimple/1.0.0/codes")]
[SwaggerOperation("UpdatePurchaseCode")]
public virtual IActionResult UpdatePurchaseCode([FromBody]PurchaseCode purchaseCode)
{
// TODO ftn: Add validation to the purchaseCode parameter!!!
// Return 400 - BadRequest if not valid!
PurchaseCode code = _context.Codes.FirstOrDefault(c => c.Code == purchaseCode.Code);
if (code == null)
{
//return StatusCode(StatusCodes.Status404NotFound, purchaseCode); // 400 not found!
return new ObjectResult(false);
}
if (code.Used == null)
{
return new ObjectResult(false);
}
if ((bool)code.Used)
{
return new ObjectResult(false);
}
try
{
code.Used = true;
code.User = _context.Users.FirstOrDefault(u => u.Id == purchaseCode.UserId);
code.UsageDateTime = DateTime.Now.ToUniversalTime();
code.User.Balance += code.Value;
_context.Entry(code).State = EntityState.Modified;
_context.Entry(code.User).State = EntityState.Modified;
_context.SaveChanges();
return new ObjectResult(true);
//return Ok(purchaseCode);
}
catch (Exception)
{
return StatusCode(StatusCodes.Status500InternalServerError);
}
}
}
}
<file_sep>/*
* Simple TripApp API
*
* This is a simple TripApp API
*
* OpenAPI spec version: 1.0.0
*
* Generated by: https://github.com/swagger-api/swagger-codegen.git
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using IO.Swagger.Data;
using IO.Swagger.Logging;
using IO.Swagger.Models;
using IO.Swagger.Notifications;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
using Swashbuckle.SwaggerGen.Annotations;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Security.Claims;
using System.Threading.Tasks;
namespace IO.Swagger.Controllers
{
/// <summary>
/// Ticket purchase controller
/// </summary>
public class TicketsApiController : Controller
{
private readonly TripAppContext _context;
private readonly IConfiguration _configuration;
private readonly ILogger _logger;
private readonly FCMNotificationService _notificationService;
private readonly bool _newBuyerIsBIGNews = false;
/// <summary>
/// Constructor method.
/// </summary>
/// <param name="context"></param>
/// <param name="configuration"></param>
/// <param name="logger"></param>
/// <param name="notificationService"></param>
public TicketsApiController(TripAppContext context, IConfiguration configuration, ILogger<TicketsApiController> logger, FCMNotificationService notificationService)
{
_context = context;
_configuration = configuration;
_logger = logger;
_notificationService = notificationService;
_newBuyerIsBIGNews = _configuration.GetSection(Startup.AppSettingsConfigurationSectionKey).GetValue<bool>(Startup.AppSettingsNewBuyerIsANews);
}
/// <summary>
/// adds an ticket purchase item
/// </summary>
/// <remarks>Adds an item to the system</remarks>
/// <param name="ticketPurchase">TicketPurchase item to add</param>
/// <response code="201">item created</response>
/// <response code="400">invalid input, object invalid</response>
/// <response code="409">item already exists</response>
[HttpPost]
[Route("/sergiosuperstar/TripAppSimple/1.0.0/tickets")]
[SwaggerOperation("AddTicketPurchase")]
[Authorize(ActiveAuthenticationSchemes = "apikey")]
public virtual async Task<IActionResult> AddTicketPurchase([FromBody]TicketPurchase ticketPurchase)
{
// TODO FTN: Add validation!
var loggedInUserId = long.Parse(User.FindFirst(ClaimTypes.NameIdentifier).Value);
var buyerUsername = User.FindFirst(ClaimTypes.Name).Value;
var buyerFirstName = User.FindFirst(ClaimTypes.GivenName).Value;
string deviceId = null;
bool enableNotifications = true;
var hasTypeAndUser = ticketPurchase != null
&& ticketPurchase.TypeId != null
&& ticketPurchase.TypeId > 0
&& ticketPurchase.UserId != null
&& ticketPurchase.UserId > 0
&& ticketPurchase.NumberOfPassangers > 0;
if (!hasTypeAndUser)
{
return StatusCode(StatusCodes.Status400BadRequest, ticketPurchase);
}
if (loggedInUserId != ticketPurchase.UserId)
{
return StatusCode(StatusCodes.Status400BadRequest, ticketPurchase);
}
try
{
if (_context.Purchases.FirstOrDefault(p => p.Id == ticketPurchase.Id) != null)
{
return StatusCode(StatusCodes.Status409Conflict, ticketPurchase); // 409 already exists!
}
deviceId = Request.Headers["DeviceID"];
enableNotifications = Request.Headers["Notifications"].Any() ? Request.Headers["Notifications"] != "false" : true;
var type = _context.Types.First(t => t.Id == ticketPurchase.TypeId);
var user = _context.Users.First(u => u.Id == ticketPurchase.UserId);
if (user.Balance - type.Price * ticketPurchase.NumberOfPassangers < 0.0d)
{
return StatusCode(StatusCodes.Status402PaymentRequired, ticketPurchase);
}
ticketPurchase.Code = Guid.NewGuid();
ticketPurchase.StartDateTime = DateTime.Now.ToUniversalTime().AddMinutes(_configuration.GetSection(Startup.AppSettingsConfigurationSectionKey).GetValue<int>(Startup.AppSettingsMinutesUntilTicketStartKey));
ticketPurchase.EndDateTime = DateTime.Now.ToUniversalTime().AddMinutes(type.Duration.Value * 60 + _configuration.GetSection(Startup.AppSettingsConfigurationSectionKey).GetValue<int>(Startup.AppSettingsMinutesUntilTicketStartKey));
ticketPurchase.Price = type.Price;
user.Balance = user.Balance - type.Price * ticketPurchase.NumberOfPassangers;
_context.Purchases.Add(ticketPurchase);
_context.SaveChanges();
ticketPurchase = _context.Purchases.Include(u => u.User).First(p => p.Id == ticketPurchase.Id);
}
catch (Exception)
{
_logger.LogError(LoggingEvents.INSERT_ITEM, "AddTicketPurchase({ticketPurchase}) NOT ADDED", ticketPurchase);
return StatusCode(StatusCodes.Status500InternalServerError);
}
string notificationSent = "[ALL: False1 ; Device ID: False2]";
if (_newBuyerIsBIGNews)
{
var notification = new Notification()
{
Title = "We have a new ticket buyer!",
Message = $"User: {buyerUsername} have bought a ticket of type id: '{ticketPurchase.TypeId}'! YEEEAAAH!",
Topic = "news"
};
var result = await _notificationService.Send(notification);
notificationSent = notificationSent.Replace("False1", result.ToString());
}
if (!string.IsNullOrEmpty(deviceId) && enableNotifications)
{
var notification = new Notification()
{
Title = "Your have bought a ticket. Congrats!",
Message = $"Hello {buyerFirstName}. Your ticket '{ticketPurchase.Code}' is ready!",
DeviceID = deviceId
};
var result = await _notificationService.Send(notification);
notificationSent = notificationSent.Replace("False2", result.ToString());
}
Response.Headers.Add("DeviceID", deviceId);
Response.Headers.Add("Notifications", enableNotifications.ToString());
Response.Headers.Add("NotificationSent", notificationSent.ToString());
return StatusCode(StatusCodes.Status201Created, ticketPurchase);
}
/// <summary>
/// searches tickets purchases
/// </summary>
/// <remarks>By passing in the appropriate options, you can search for available ticket in the system </remarks>
/// <param name="searchString">pass an optional search string for looking up tickets.
/// format: [command]:[value]
/// examples:
/// all:1 -> takes all tickets for user with id: 1
/// my:1 -> takes all ticket purchased for user id: 1 where end datetime is >= datetime.now
/// id:1 -> takes ticket purchase with id: 1
/// </param>
/// <param name="skip">number of records to skip for pagination</param>
/// <param name="limit">maximum number of records to return</param>
/// <response code="200">search results matching criteria</response>
/// <response code="400">bad input parameter</response>
[HttpGet]
[Route("/sergiosuperstar/TripAppSimple/1.0.0/tickets")]
[SwaggerOperation("SearchTickets")]
[SwaggerResponse(200, type: typeof(List<TicketPurchase>))]
public virtual IActionResult SearchTickets([FromQuery]string searchString, [FromQuery]int? skip, [FromQuery]int? limit)
{
int id;
string[] commands = { "all", "id", "my" };
searchString = WebUtility.HtmlDecode(searchString).ToLower();
var searchItems = searchString.Split(':');
if (searchItems.Length != 2)
{
return StatusCode(StatusCodes.Status400BadRequest, searchString);
}
var searchBy = searchItems[0];
var searchValue = searchItems[1];
if (!commands.Contains(searchBy))
{
return StatusCode(StatusCodes.Status400BadRequest, searchBy);
}
if (!int.TryParse(searchValue, out id))
{
return StatusCode(StatusCodes.Status400BadRequest);
}
try
{
List<TicketPurchase> purchases;
TicketPurchase purchase;
switch (searchBy)
{
case "id":
purchase = _context.Purchases.Include(t => t.Type).Include(u => u.User).Where(c => c.Id == id).FirstOrDefault();
return new ObjectResult(purchase);
case "all":
purchases = _context.Purchases.Include(t => t.Type).Include(u => u.User).Where(c => c.UserId == id).ToList();
return new ObjectResult(purchases);
case "my":
purchase = _context.Purchases.Include(t => t.Type).Include(u => u.User).Where(c => (c.UserId == id && c.EndDateTime > DateTime.Now)).OrderByDescending(p => p.StartDateTime).FirstOrDefault();
return new ObjectResult(purchase);
default:
_logger.LogError(LoggingEvents.LIST_ITEMS, "SearchTickets({searchString}) BAD SEARCH REQUEST", searchString);
return StatusCode(StatusCodes.Status400BadRequest);
};
}
catch (Exception)
{
_logger.LogError(LoggingEvents.LIST_ITEMS, "SearchTickets({searchString}) NOT FOUND", searchString);
return StatusCode(StatusCodes.Status500InternalServerError);
}
}
}
}
<file_sep>using IO.Swagger.Data;
using Microsoft.AspNetCore.Authentication;
using Microsoft.Extensions.Primitives;
using System.Linq;
using System.Security.Claims;
using System.Threading.Tasks;
namespace IO.Swagger.Security
{
/// <summary>
/// Api key auth handler
/// </summary>
public class ApiKeyAuthenticationHandler : AuthenticationHandler<ApiKeyAuthenticationOptions>
{
private IApiKeyValidator _validator;
private readonly TripAppContext _context;
/// <summary>
/// Construct ApiKey auth handler.
/// </summary>
/// <param name="validator">Validator instance</param>
/// <param name="context"></param>
public ApiKeyAuthenticationHandler(IApiKeyValidator validator, TripAppContext context)
{
_validator = validator;
_context = context;
}
/// <summary>
/// Handle authentication.
/// </summary>
/// <returns>Result.</returns>
protected override Task<AuthenticateResult> HandleAuthenticateAsync()
{
StringValues headerValue;
if (!Context.Request.Headers.TryGetValue(Options.HeaderName, out headerValue))
{
return Task.FromResult(AuthenticateResult.Fail("Missing or malformed 'Authorization' header."));
}
var apiKey = headerValue.First();
if (!_validator.Validate(apiKey, _context))
{
return Task.FromResult(AuthenticateResult.Fail("Invalid apiKey."));
}
// success! Now we just need to create the auth ticket
var identity = new ClaimsIdentity("apikey"); // the name of our auth scheme
var user = _context.Users.First(u => u.Id == long.Parse(apiKey));
identity.AddClaim(new Claim(ClaimTypes.NameIdentifier, apiKey));
identity.AddClaim(new Claim(ClaimTypes.Name, user.Username));
identity.AddClaim(new Claim(ClaimTypes.Role, user.Role));
identity.AddClaim(new Claim(ClaimTypes.GivenName, user.FirstName));
identity.AddClaim(new Claim(ClaimTypes.Surname, user.LastName));
var ticket = new AuthenticationTicket(new ClaimsPrincipal(identity), null, "apikey");
return Task.FromResult(AuthenticateResult.Success(ticket));
}
}
}
<file_sep>/*
* Simple TripApp API
*
* This is a simple TripApp API
*
* OpenAPI spec version: 1.0.0
*
* Generated by: https://github.com/swagger-api/swagger-codegen.git
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.IO;
using System.Linq;
using System.Net;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
using Swashbuckle.SwaggerGen.Annotations;
using IO.Swagger.Models;
using Microsoft.AspNetCore.Http;
using IO.Swagger.Data;
using Microsoft.Extensions.Logging;
using IO.Swagger.Logging;
using Microsoft.AspNetCore.Authorization;
namespace IO.Swagger.Controllers
{
/// <summary>
///
/// </summary>
public class TypesApiController : Controller
{
private readonly TripAppContext _context;
private readonly ILogger _logger;
/// <summary>
/// Initializes controller.
/// </summary>
/// <param name="context">Db context to use.</param>
public TypesApiController(TripAppContext context, ILogger<TypesApiController> logger)
{
_context = context;
_logger = logger;
}
/// <summary>
/// adds an ticket type
/// </summary>
/// <remarks>Adds an item to the system</remarks>
/// <param name="ticketType">TicketType item to add</param>
/// <response code="201">item created</response>
/// <response code="400">invalid input, object invalid</response>
/// <response code="409">item already exists</response>
[HttpPost]
[Route("/sergiosuperstar/TripAppSimple/1.0.0/tickets/types")]
[SwaggerOperation("AddTicketType")]
[Authorize(ActiveAuthenticationSchemes = "apikey")]
public IActionResult AddTicketType([FromBody]TicketType ticketType)
{
// TODO ftn: Add validation to the ticketType parameter!!!
// Return 400 - BadRequest if not valid!
if (_context.Types.FirstOrDefault(t => t.Id == ticketType.Id) != null)
{
return StatusCode(StatusCodes.Status409Conflict, ticketType); // 409 already exists!
}
try
{
_context.Types.Add(ticketType);
_context.SaveChanges();
return Created(Request.Host.ToString(), ticketType); // 201 Created successfuly.
}
catch (Exception)
{
_logger.LogError(LoggingEvents.INSERT_ITEM, "AddTicketType({ticketType}) NOT ADDED", ticketType);
return StatusCode(StatusCodes.Status500InternalServerError);
}
}
/// <summary>
/// get all ticket types
/// </summary>
/// <remarks>Return all ticket types </remarks>
/// <response code="200">search results matching criteria</response>
/// <response code="400">bad input parameter</response>
[HttpGet]
[Route("/sergiosuperstar/TripAppSimple/1.0.0/tickets/alltypes")]
[SwaggerOperation("GetTicketTypes")]
[SwaggerResponse(200, type: typeof(List<TicketType>))]
public virtual IActionResult GetTicketTypes()
{
try
{
var types = _context.Types.ToList();
return new ObjectResult(types);
}
catch (Exception)
{
_logger.LogError(LoggingEvents.LIST_ITEMS, "GetTicketTypes method have failed.");
return StatusCode(StatusCodes.Status500InternalServerError);
}
}
/// <summary>
/// searches ticket types
/// </summary>
/// <remarks>By passing in the appropriate options, you can search for available ticket types in the system </remarks>
/// <param name="searchString">pass an optional search string for looking up ticket types</param>
/// <param name="skip">number of records to skip for pagination</param>
/// <param name="limit">maximum number of records to return</param>
/// <response code="200">search results matching criteria</response>
/// <response code="400">bad input parameter</response>
[HttpGet]
[Route("/sergiosuperstar/TripAppSimple/1.0.0/tickets/types")]
[SwaggerOperation("SearchTicketTypes")]
[SwaggerResponse(200, type: typeof(List<TicketType>))]
public virtual IActionResult SearchTicketTypes([FromQuery]string searchString, [FromQuery]int? skip, [FromQuery]int? limit)
{
int id;
if (!int.TryParse(searchString, out id))
{
return StatusCode(StatusCodes.Status400BadRequest);
}
try
{
var types = _context.Types.Where(c => c.Id == id).ToList();
return new ObjectResult(types);
}
catch (Exception)
{
_logger.LogError(LoggingEvents.LIST_ITEMS, "SearchTicketTypes({searchString}) NOT FOUND", searchString);
return StatusCode(StatusCodes.Status500InternalServerError);
}
}
}
}
<file_sep>package com.example.icf.tripappclient.service;
import java.util.List;
import io.swagger.client.model.PurchaseCode;
import retrofit2.Call;
import retrofit2.http.Body;
import retrofit2.http.GET;
import retrofit2.http.Headers;
import retrofit2.http.PUT;
import retrofit2.http.Path;
import retrofit2.http.Query;
/**
* Created by Vuletic on 10.6.2017.
*/
public interface PurchaseCodeService {
@Headers({
"User-Agent: Mobile-Android",
"Content-Type:application/json"
})
@PUT("codes/")
Call<Boolean> put(@Body PurchaseCode code);
@Headers({
"User-Agent: Mobile-Android",
"Content-Type:application/json"
})
@GET("codes/user")
Call<List<PurchaseCode>> get(@Query("userId") String userId);
}
<file_sep>/*
* Simple TripApp API
*
* This is a simple TripApp API
*
* OpenAPI spec version: 1.0.0
*
* Generated by: https://github.com/swagger-api/swagger-codegen.git
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using IO.Swagger.Data;
using IO.Swagger.Models;
using IO.Swagger.Notifications;
using IO.Swagger.Security;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Identity;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Newtonsoft.Json.Serialization;
using Swashbuckle.Swagger.Model;
using Swashbuckle.SwaggerGen.Annotations;
using System;
using System.IO;
using System.Xml.XPath;
namespace IO.Swagger
{
/// <summary>
/// Startup class is triggered by environment in order to start web app.
/// </summary>
public class Startup
{
/// Configuration key for logging section
public const string LoggingConfigurationSectionKey = "Logging";
/// Configuration key for application settings section
public const string AppSettingsConfigurationSectionKey = "AppSettings";
/// Configuration key for minutes until ticket starts section
public const string AppSettingsMinutesUntilTicketStartKey = "MinutesUntilTicketStart";
/// Configuration key for new buyer notification sent to all
public const string AppSettingsNewBuyerIsANews = "NewBuyerIsANews";
private readonly IHostingEnvironment _hostingEnv;
/// <summary>
/// App configuration.
/// </summary>
public IConfigurationRoot Configuration { get; }
/// <summary>
/// This is web app startup class constructor.
/// Use it to set configuration for your web app.
/// </summary>
/// <param name="env">Hosting environment instance.</param>
public Startup(IHostingEnvironment env)
{
_hostingEnv = env;
var builder = new ConfigurationBuilder()
.SetBasePath(env.ContentRootPath)
.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
.AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
.AddEnvironmentVariables();
Configuration = builder.Build();
}
/// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<TripAppContext>(opt => opt.UseInMemoryDatabase());
services.AddScoped<IPasswordHasher<User>, PasswordHasher<User>>();
services.AddMvc()
.AddJsonOptions(
opts => {
opts.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
opts.SerializerSettings.DateTimeZoneHandling = Newtonsoft.Json.DateTimeZoneHandling.Utc;
});
services.AddSwaggerGen();
services.ConfigureSwaggerGen(options =>
{
options.SingleApiVersion(new Info
{
Version = "v1",
Title = "IO.Swagger",
Description = "IO.Swagger (ASP.NET Core 1.0)",
}
);
options.DescribeAllEnumsAsStrings();
options.OperationFilter<ApiKeyOperationFilter>();
var comments = new XPathDocument($"{AppContext.BaseDirectory}{Path.DirectorySeparatorChar}{_hostingEnv.ApplicationName}.xml");
options.OperationFilter<XmlCommentsOperationFilter>(comments);
options.ModelFilter<XmlCommentsModelFilter>(comments);
});
services.AddSingleton<IConfiguration>(Configuration);
services.AddTransient<IApiKeyValidator, SimpleApiKeyValidator>();
services.AddTransient<ApiKeyAuthenticationOptions>();
services.AddTransient<ApiKeyOptions>();
services.AddTransient<IOptions<ApiKeyAuthenticationOptions>, ApiKeyOptions>();
services.AddSingleton<FCMNotificationService>();
}
/// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
loggerFactory.AddConsole(Configuration.GetSection(LoggingConfigurationSectionKey));
loggerFactory.AddDebug();
TripAppDbInitializer.Seed(app.ApplicationServices);
// Force development environment always ON
// TODO: remove when not needed anymore!
env.EnvironmentName = EnvironmentName.Development;
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseApiKeyAuthentication();
app.UseMvc();
app.UseDefaultFiles();
app.UseStaticFiles();
app.UseSwagger();
app.UseSwaggerUi();
}
}
}
<file_sep>package io.swagger.client.model;
import com.example.icf.tripappclient.SessionManager;
import com.google.gson.annotations.SerializedName;
import com.j256.ormlite.field.DatabaseField;
import com.j256.ormlite.table.DatabaseTable;
import java.io.Serializable;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
/**
* Created by NemanjaM on 15.6.2017.
*/
@DatabaseTable(tableName = "Ticket")
@ApiModel(description = "")
public class TicketPurchaseLocal implements Serializable {
@DatabaseField(id = true)
@SerializedName("id")
private Integer id = null;
@DatabaseField
@SerializedName("code")
private String code = null;
@DatabaseField
@SerializedName("price")
private Double price = null;
@DatabaseField
@SerializedName("startDateTime")
private Date startDateTime = null;
@DatabaseField
@SerializedName("endDateTime")
private Date endDateTime = null;
@DatabaseField
@SerializedName("numberOfPassangers")
private Integer numberOfPassangers = null;
@DatabaseField
@SerializedName("type")
private String typeString = null;
@DatabaseField
@SerializedName("userId")
private Long userId = null;
public TicketPurchaseLocal() {
}
public TicketPurchaseLocal(TicketPurchase purch) {
this.id = purch.getId();
this.code = purch.getCode().toString();
this.price = purch.getPrice();
this.startDateTime = purch.getStartDateTime();
this.endDateTime = purch.getEndDateTime();
this.numberOfPassangers = purch.getNumberOfPassangers();
this.typeString = purch.getType().getName();
this.userId = purch.getUserId();
}
public TicketPurchaseLocal(Integer id, String code, Double price, Date startDateTime,
Date endDateTime, Integer numberOfPassangers,
String typeString, Long userId) {
this.id = id;
this.code = code;
this.price = price;
this.startDateTime = startDateTime;
this.endDateTime = endDateTime;
this.numberOfPassangers = numberOfPassangers;
this.typeString = typeString;
this.userId = userId;
}
/**
**/
@ApiModelProperty(required = true, value = "")
public Long getUserId() {
return userId;
}
public void setUserId(Long userId) {
this.userId = userId;
}
/**
**/
@ApiModelProperty(required = true, value = "")
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
/**
**/
@ApiModelProperty(required = true, value = "")
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
/**
**/
@ApiModelProperty(value = "")
public Double getPrice() {
return price;
}
public void setPrice(Double price) {
this.price = price;
}
/**
**/
@ApiModelProperty(required = true, value = "")
public Date getStartDateTime() {
return startDateTime;
}
public void setStartDateTime(Date startDateTime) {
this.startDateTime = startDateTime;
}
public String getStartDateTimeString() {
DateFormat df = new SimpleDateFormat(SessionManager.DATETIME_FORMAT);
return df.format(startDateTime);
}
/**
**/
@ApiModelProperty(required = true, value = "")
public Date getEndDateTime() {
return endDateTime;
}
public void setEndDateTime(Date endDateTime) {
this.endDateTime = endDateTime;
}
public String getEndDateTimeString() {
DateFormat df = new SimpleDateFormat(SessionManager.DATETIME_FORMAT);
return df.format(endDateTime);
}
public UUID getUUIDCode() {
return UUID.fromString(code);
}
public void setUUIDCode(String guid) {
code = guid;
}
/**
* Number of passangers allowed to travel with buyer and including buyer too.
**/
@ApiModelProperty(value = "Number of passangers allowed to travel with buyer and including buyer too.")
public Integer getNumberOfPassangers() {
return numberOfPassangers;
}
public void setNumberOfPassangers(Integer numberOfPassangers) {
this.numberOfPassangers = numberOfPassangers;
}
/**
**/
@ApiModelProperty(required = true, value = "")
public String getTypeString() {
return typeString;
}
public void setTypeString(String typeString) {
this.typeString = typeString;
}
/*
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
io.swagger.client.model.TicketPurchase ticketPurchase = (io.swagger.client.model.TicketPurchase) o;
return (this.id == null ? ticketPurchase.id == null : this.id.equals(ticketPurchase.id)) &&
(this.code == null ? ticketPurchase.code == null : this.code.equals(ticketPurchase.code)) &&
(this.price == null ? ticketPurchase.price == null : this.price.equals(ticketPurchase.price)) &&
(this.startDateTime == null ? ticketPurchase.startDateTime == null : this.startDateTime.equals(ticketPurchase.startDateTime)) &&
(this.endDateTime == null ? ticketPurchase.endDateTime == null : this.endDateTime.equals(ticketPurchase.endDateTime)) &&
(this.numberOfPassangers == null ? ticketPurchase.numberOfPassangers == null : this.numberOfPassangers.equals(ticketPurchase.numberOfPassangers)) &&
(this.type == null ? ticketPurchase.type == null : this.type.equals(ticketPurchase.type)) &&
(this.user == null ? ticketPurchase.user == null : this.user.equals(ticketPurchase.user));
}
@Override
public int hashCode() {
int result = 17;
result = 31 * result + (this.id == null ? 0 : this.id.hashCode());
result = 31 * result + (this.code == null ? 0 : this.code.hashCode());
result = 31 * result + (this.price == null ? 0 : this.price.hashCode());
result = 31 * result + (this.startDateTime == null ? 0 : this.startDateTime.hashCode());
result = 31 * result + (this.endDateTime == null ? 0 : this.endDateTime.hashCode());
result = 31 * result + (this.numberOfPassangers == null ? 0 : this.numberOfPassangers.hashCode());
result = 31 * result + (this.type == null ? 0 : this.type.hashCode());
result = 31 * result + (this.user == null ? 0 : this.user.hashCode());
return result;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("class TicketPurchase {\n");
sb.append(" id: ").append(id).append("\n");
sb.append(" code: ").append(code).append("\n");
sb.append(" price: ").append(price).append("\n");
sb.append(" startDateTime: ").append(startDateTime).append("\n");
sb.append(" endDateTime: ").append(endDateTime).append("\n");
sb.append(" numberOfPassangers: ").append(numberOfPassangers).append("\n");
sb.append(" type: ").append(type).append("\n");
sb.append(" user: ").append(user).append("\n");
sb.append("}\n");
return sb.toString();
}
*/
}
<file_sep>package com.example.icf.tripappclient.fragments;
import android.graphics.Bitmap;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.app.AppCompatActivity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import com.example.icf.tripappclient.R;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.WriterException;
import com.google.zxing.common.BitMatrix;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.UUID;
import io.swagger.client.model.*;
import io.swagger.client.model.TicketPurchase;
import static android.graphics.Color.BLACK;
import static android.graphics.Color.WHITE;
import static android.graphics.Color.YELLOW;
/**
* Created by Vuletic on 28.4.2017.
*/
public class TicketInfo extends Fragment {
private TicketPurchaseLocal ticket;
private boolean isValid;
public TicketInfo() {
// Required empty public constructor
}
// TODO: iz ovog fragmenta back strelica a ne navbar - dvd
public static TicketInfo newInstance(TicketPurchaseLocal ticket) {
TicketInfo fragment = new TicketInfo();
Bundle args = new Bundle();
args.putSerializable("ticket", ticket);
fragment.setArguments(args);
return fragment;
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
((AppCompatActivity) getActivity()).getSupportActionBar().setTitle(R.string.ticket_info_title);
View view = inflater.inflate(R.layout.fragment_ticket_info, container, false);
ticket = (TicketPurchaseLocal) getArguments().getSerializable("ticket");
Double totalPrice = ticket.getPrice() * ticket.getNumberOfPassangers();
String priceTotalDecimal = String.format("%.2f", totalPrice);
String priceSingleDecimal = String.format("%.2f", ticket.getPrice());
((TextView) view.findViewById(R.id.dateFromValue)).setText(ticket.getStartDateTimeString());
((TextView) view.findViewById(R.id.dateToValue)).setText(ticket.getEndDateTimeString());
((TextView) view.findViewById(R.id.ticketPriceValue)).setText(priceTotalDecimal.toString());
((TextView) view.findViewById(R.id.ticketPriceSingleValue)).setText(priceSingleDecimal);
((TextView) view.findViewById(R.id.ticketsNumberValue)).setText(ticket.getNumberOfPassangers().toString());
((TextView) view.findViewById(R.id.ticketTypeValue)).setText(ticket.getTypeString());
isValid = ticket.getEndDateTime().after(new Date());
try {
ImageView imageView = (ImageView) view.findViewById(R.id.qrExample);
Bitmap bitmap = encodeAsBitmap(ticket.getCode());
imageView.setImageBitmap(bitmap);
} catch (WriterException e) {
e.printStackTrace();
}
return view;
}
@Override
public void onStart() {
super.onStart();
TextView expiredLabel = (TextView) getActivity().findViewById(R.id.statusExpired);
TextView validLabel = (TextView) getActivity().findViewById(R.id.statusValid);
//Date current = new Date();
if (isValid) {
expiredLabel.setVisibility(View.GONE);
validLabel.setVisibility(View.VISIBLE);
} else {
expiredLabel.setVisibility(View.VISIBLE);
validLabel.setVisibility(View.GONE);
}
}
Bitmap encodeAsBitmap(String str) throws WriterException {
BitMatrix result;
try {
result = new MultiFormatWriter().encode(str,
BarcodeFormat.QR_CODE, 150, 150, null);
} catch (IllegalArgumentException iae) {
// Unsupported format
return null;
}
int w = result.getWidth();
int h = result.getHeight();
int[] pixels = new int[w * h];
for (int y = 0; y < h; y++) {
int offset = y * w;
for (int x = 0; x < w; x++) {
pixels[offset + x] = result.get(x, y) ? BLACK : WHITE;
}
}
Bitmap bitmap = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888);
bitmap.setPixels(pixels, 0, 150, 0, 0, w, h);
return bitmap;
}
}
<file_sep>using IO.Swagger.Data;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
using System.Text.Encodings.Web;
namespace IO.Swagger.Security
{
/// <summary>
/// ApiKey middleware.
/// </summary>
public class ApiKeyAuthenticationMiddleware : AuthenticationMiddleware<ApiKeyAuthenticationOptions>
{
private IApiKeyValidator _validator;
private readonly TripAppContext _context;
/// <summary>
/// ApiKey middleware constructor.
/// </summary>
/// <param name="validator"></param>
/// <param name="next"></param>
/// <param name="options"></param>
/// <param name="loggerFactory"></param>
/// <param name="encoder"></param>
/// <param name="context"></param>
public ApiKeyAuthenticationMiddleware(
IApiKeyValidator validator, // custom dependency
RequestDelegate next,
ApiKeyOptions options,
ILoggerFactory loggerFactory,
UrlEncoder encoder,
TripAppContext context)
: base(next, options, loggerFactory, encoder)
{
_validator = validator;
_context = context;
}
/// <summary>
/// Creates authentication handler instance.
/// </summary>
/// <returns></returns>
protected override AuthenticationHandler<ApiKeyAuthenticationOptions> CreateHandler()
{
return new ApiKeyAuthenticationHandler(_validator, _context);
}
}
}
<file_sep>using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc.Authorization;
using Swashbuckle.Swagger.Model;
using Swashbuckle.SwaggerGen.Generator;
using System.Collections.Generic;
using System.Linq;
namespace IO.Swagger.Security
{
/// <summary>
/// Extend swashbuckle UI with apikey support
/// </summary>
public class ApiKeyOperationFilter : IOperationFilter
{
/// <summary>
/// Constructs api key operation filter
/// </summary>
/// <param name="operation"></param>
/// <param name="context"></param>
public void Apply(Operation operation, OperationFilterContext context)
{
var actionName = context.ApiDescription.ActionDescriptor.DisplayName;
var filterPipeline = context.ApiDescription.ActionDescriptor.FilterDescriptors;
var isAuthorized = filterPipeline.Any(f => f.Filter is AuthorizeFilter
&& (f.Filter as AuthorizeFilter).AuthorizeData.Count() == 1);
var allowAnonymous = context.ApiDescription.GetActionAttributes().Any(a => a.GetType() == typeof(AllowAnonymousAttribute));
if (isAuthorized && !allowAnonymous)
{
if (operation.Parameters == null)
{
operation.Parameters = new List<IParameter>();
}
operation.Parameters.Add(new NonBodyParameter
{
Name = "Authorization",
In = "header",
Description = "Custom access token / api key",
Required = true,
Type = "string"
});
}
}
}
}
<file_sep>package com.example.icf.tripappclient.activities;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.Typeface;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.KeyEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.example.icf.tripappclient.R;
import com.example.icf.tripappclient.SessionManager;
import com.example.icf.tripappclient.service.ServiceUtils;
import com.google.zxing.ResultPoint;
import com.google.zxing.client.android.BeepManager;
import com.journeyapps.barcodescanner.BarcodeCallback;
import com.journeyapps.barcodescanner.BarcodeResult;
import com.journeyapps.barcodescanner.DecoratedBarcodeView;
import java.util.List;
import java.util.UUID;
import io.swagger.client.model.PurchaseCode;
import io.swagger.client.model.TicketPurchase;
import io.swagger.client.model.TicketValidation;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
/**
* This sample performs continuous scanning, displaying the barcode and source image whenever
* a barcode is scanned.
*/
public class VoucherScannerActivity extends Activity {
private DecoratedBarcodeView barcodeView;
private BeepManager beepManager;
private SessionManager session;
private Activity that = this;
private BarcodeCallback callback = new BarcodeCallback() {
@Override
public void barcodeResult(BarcodeResult result) {
String scanned = result.getText();
//Toast.makeText(that, "Scanned: " + scanned, Toast.LENGTH_LONG).show();
PurchaseCode code = new PurchaseCode();
try {
code.setCode(UUID.fromString(scanned));
code.setUserId(session.getUser().getId());
}catch(Exception e){
Toast.makeText(that, "Failed to add funds. ", Toast.LENGTH_LONG).show();
}
Call<Boolean> call = ServiceUtils.purchaseCodeService.put(code);
call.enqueue(new Callback<Boolean>() {
@Override
public void onResponse(Call<Boolean> call, Response<Boolean> response) {
if (response.code() == 200) {
Boolean resp = response.body();
if (resp){
Toast.makeText(that, "Successfully added funds.", Toast.LENGTH_LONG).show();
//session.reloadUserBalance((MainActivity) that);
session.getDatabaseState().refillPayments();
Intent intent = new Intent(getApplicationContext(), MainActivity.class);
intent.putExtra("balance", true);
startActivity(intent);
}else{
Toast.makeText(that, "Failed to add funds. ", Toast.LENGTH_LONG).show();
}
} else {
Toast.makeText(that, "Failed to add funds. ", Toast.LENGTH_LONG).show();
}
}
@Override
public void onFailure(Call<Boolean> call, Throwable t) {
Toast.makeText(that, "Failed to add funds. ", Toast.LENGTH_LONG).show();
}
});
}
@Override
public void possibleResultPoints(List<ResultPoint> resultPoints) {
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
session = new SessionManager(getApplicationContext());
setContentView(R.layout.voucher_scanner);
barcodeView = (DecoratedBarcodeView) findViewById(R.id.barcode_scanner_2);
barcodeView.decodeContinuous(callback);
beepManager = new BeepManager(this);
}
@Override
protected void onResume() {
super.onResume();
barcodeView.resume();
}
@Override
protected void onPause() {
super.onPause();
barcodeView.pause();
}
public void pause(View view) {
barcodeView.pause();
}
public void resume(View view) {
barcodeView.resume();
}
public void triggerScan(View view) {
barcodeView.decodeSingle(callback);
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
return barcodeView.onKeyDown(keyCode, event) || super.onKeyDown(keyCode, event);
}
}
<file_sep>using Microsoft.AspNetCore.Builder;
namespace IO.Swagger.Security
{
/// <summary>
/// Api Key authentication options
/// </summary>
public class ApiKeyAuthenticationOptions : AuthenticationOptions
{
/// <summary>
/// Creates default apikey auth handler options.
/// </summary>
public ApiKeyAuthenticationOptions()
{
this.AuthenticationScheme = "apikey";
this.AutomaticAuthenticate = true;
this.AutomaticChallenge = true;
}
/// <summary>
/// Default header name.
/// </summary>
public const string DefaultHeaderName = "Authorization";
/// <summary>
/// Gets or Sets default header name.
/// </summary>
public string HeaderName { get; set; } = DefaultHeaderName;
}
}
<file_sep>/*
* Simple TripApp API
*
* This is a simple TripApp API
*
* OpenAPI spec version: 1.0.0
*
* Generated by: https://github.com/swagger-api/swagger-codegen.git
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.AspNetCore.Mvc;
using Swashbuckle.SwaggerGen.Annotations;
using IO.Swagger.Models;
using Microsoft.AspNetCore.Http;
using IO.Swagger.Data;
using Microsoft.Extensions.Logging;
using IO.Swagger.Logging;
using Microsoft.EntityFrameworkCore;
namespace IO.Swagger.Controllers
{
/// <summary>
///
/// </summary>
public class ValidationApiController : Controller
{
private readonly TripAppContext _context;
private readonly ILogger _logger;
/// <summary>
/// Constructor method.
/// </summary>
/// <param name="context"></param>
/// <param name="logger"></param>
public ValidationApiController(TripAppContext context, ILogger<ValidationApiController> logger)
{
_context = context;
_logger = logger;
}
/// <summary>
/// adds an ticket validation item
/// </summary>
/// <remarks>Adds an item to the system</remarks>
/// <param name="ticketValidation">TicketValidation item to add</param>
/// <response code="201">item created</response>
/// <response code="400">invalid input, object invalid</response>
/// <response code="409">an existing item already exists</response>
[HttpPost]
[Route("/sergiosuperstar/TripAppSimple/1.0.0/tickets/validation")]
[SwaggerOperation("AddTicketValidation")]
public virtual IActionResult AddTicketValidation([FromBody]TicketValidation ticketValidation)
{
// TODO ftn: Add validation to the ticketValidation parameter!!!
// Return 400 - BadRequest if not valid!
if (_context.Validations.FirstOrDefault(t => t.Id == ticketValidation.Id) != null)
{
return StatusCode(StatusCodes.Status409Conflict); // 409 already exists!
}
TicketPurchase ticket = _context.Purchases.FirstOrDefault(p => p.Code == ticketValidation.Ticket.Code);
if (ticket == null)
{
return StatusCode(StatusCodes.Status404NotFound);
}
if (ticket.EndDateTime < DateTime.Now)
{
return StatusCode(StatusCodes.Status406NotAcceptable, ticket);
}
try
{
ticketValidation.Ticket = ticket;
ticketValidation.IsValid = true;
ticketValidation.ValidationDateTime = DateTime.Now.ToUniversalTime();
Random r = new Random();
int rInt = r.Next(1, 1000000000);
ticketValidation.Id = rInt;
_context.Validations.Add(ticketValidation);
_context.Entry(ticketValidation.Controller).State = Microsoft.EntityFrameworkCore.EntityState.Unchanged;
_context.SaveChanges();
return new ObjectResult(ticket);
//return Created(Request.Host.ToString(), ticketValidation); // 201 Created successfuly.
}
catch (Exception)
{
_logger.LogError(LoggingEvents.INSERT_ITEM, "AddTicketType({ticketValidation}) NOT ADDED", ticketValidation);
return StatusCode(StatusCodes.Status500InternalServerError);
}
}
/// <summary>
/// searches tickets validations
/// </summary>
/// <remarks>By passing in the appropriate options, you can search for available ticket validations in the system </remarks>
/// <param name="searchString">pass an optional search string for looking up ticket validations</param>
/// <param name="skip">number of records to skip for pagination</param>
/// <param name="limit">maximum number of records to return</param>
/// <response code="200">search results matching criteria</response>
/// <response code="400">bad input parameter</response>
[HttpGet]
[Route("/sergiosuperstar/TripAppSimple/1.0.0/tickets/validation")]
[SwaggerOperation("SearchValidations")]
[SwaggerResponse(200, type: typeof(List<TicketValidation>))]
public virtual IActionResult SearchValidations([FromQuery]string searchString, [FromQuery]int? skip, [FromQuery]int? limit)
{
int id;
if (!int.TryParse(searchString, out id))
{
return StatusCode(StatusCodes.Status400BadRequest);
}
try
{
var validations = _context.Validations.Where(c => c.Id == id).ToList();
return new ObjectResult(validations);
}
catch (Exception)
{
_logger.LogError(LoggingEvents.LIST_ITEMS, "SearchValidations({searchString}) NOT FOUND", searchString);
return StatusCode(StatusCodes.Status500InternalServerError);
}
}
/// <summary>
/// searches tickets validations
/// </summary>
/// <remarks>By passing in the appropriate options, you can search for available ticket validations in the system </remarks>
/// <param name="searchString">pass an optional search string for looking up ticket validations</param>
/// <param name="skip">number of records to skip for pagination</param>
/// <param name="limit">maximum number of records to return</param>
/// <response code="200">search results matching criteria</response>
/// <response code="400">bad input parameter</response>
[HttpGet]
[Route("/sergiosuperstar/TripAppSimple/1.0.0/tickets/validation/controller")]
[SwaggerOperation("SearchValidations")]
[SwaggerResponse(200, type: typeof(List<TicketValidation>))]
public virtual IActionResult SearchControlerValidations([FromQuery]string searchString, [FromQuery]int? skip, [FromQuery]int? limit)
{
int id;
if (!int.TryParse(searchString, out id))
{
return StatusCode(StatusCodes.Status400BadRequest);
}
try
{
var validations = _context.Validations.Include(c => c.Controller).Include(t => t.Ticket).Include(tt => tt.Ticket.Type).Include(tt => tt.Ticket.User).Where(u => u.Controller.Id == id);
return new ObjectResult(validations);
}
catch (Exception)
{
_logger.LogError(LoggingEvents.LIST_ITEMS, "SearchValidations({searchString}) NOT FOUND", searchString);
return StatusCode(StatusCodes.Status500InternalServerError);
}
}
}
}
<file_sep>using IO.Swagger.Logging;
using IO.Swagger.Models;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
namespace IO.Swagger.Notifications
{
/// <summary>
/// Helper used to send notifications via firebase cloud messaging.
/// </summary>
public class FCMNotificationService
{
private const string API_URL_FCM = "https://fcm.googleapis.com/fcm/send";
private const string TRIPAPP_FCM_SERVER_API_KEY = "<KEY> <KEY>";
private const string TRIPAPP_FCM_SENDER_ID = "609196975291";
private readonly ILogger _logger;
/// <summary>
/// Instanciate notification service.
/// </summary>
/// <param name="logger"></param>
public FCMNotificationService(ILogger<FCMNotificationService> logger)
{
_logger = logger;
}
/// <summary>
/// Send notification
/// </summary>
/// <param name="notification"></param>
/// <returns></returns>
public async Task<bool> Send(Notification notification)
{
bool success = false;
try
{
var client = new HttpClient();
client.DefaultRequestHeaders.TryAddWithoutValidation("Authorization", string.Format("key={0}", TRIPAPP_FCM_SERVER_API_KEY));
// client.DefaultRequestHeaders.TryAddWithoutValidation("Sender", string.Format("key={0}", TRIPAPP_FCM_SENDER_ID));
var toWhom = string.IsNullOrEmpty(notification.DeviceID) ? "/topics/" + notification.Topic : notification.DeviceID;
var message = new
{
// to = YOUR_FCM_DEVICE_ID, // Uncoment this if you want to test for single device
// to = "/topics/" + notification.Topic, // this is for topic
to = toWhom,
notification = new
{
title = notification.Title,
body = notification.Message,
//icon="myicon"
}
};
var json = JsonConvert.SerializeObject(message);
var result = await client.PostAsync(API_URL_FCM,
new StringContent(json, Encoding.UTF8, @"application/json"));
success = true;
}
catch (Exception ex)
{
_logger.LogError(LoggingEvents.INSERT_ITEM, $"Send({notification}) NOT sent.", notification);
// WHATEVER HAPPEN WE DO NOT BREAK WITH EXCEPTION AS WE DO NOT CARE IF MESSAGING WORKED!
// WE JUST RETURN FALSE!
success = false;
}
return success;
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Runtime.Serialization;
using System.Threading.Tasks;
namespace IO.Swagger.Models
{
/// <summary>
/// Operations for purchase codes manipulation
/// </summary>
public partial class PurchaseCode
{
/// <summary>
/// Default constructor.
/// </summary>
public PurchaseCode()
{
}
/// <summary>
/// Gets or Sets User Id
/// </summary>
[DataMember(Name = "userId")]
[ForeignKey("User")]
public long? UserId { get; set; }
}
}
<file_sep>using IO.Swagger.Data;
namespace IO.Swagger.Security
{
/// <summary>
/// Api key validator interface.
/// </summary>
public interface IApiKeyValidator
{
/// <summary>
/// Validates API key
/// </summary>
/// <param name="apiKey">Api key to validate</param>
/// <param name="context"></param>
/// <returns>Validation result.</returns>
bool Validate(string apiKey, TripAppContext context);
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;
using IO.Swagger.Models;
using Microsoft.AspNetCore.Identity;
using Microsoft.Extensions.DependencyInjection;
namespace IO.Swagger.Data
{
/// <summary>
/// Initialize db data via seed methods.
/// </summary>
public class TripAppDbInitializer
{
private const string defaultPassword = "a";
private const string devPassword = "dev";
/// <summary>
/// Seed database with predefined data.
/// </summary>
/// <param name="serviceProvider">DI service provider instance.</param>
public static void Seed(IServiceProvider serviceProvider)
{
var context = serviceProvider.GetService<TripAppContext>();
var hasher = serviceProvider.GetService<IPasswordHasher<User>>();
string defaultPass = hasher.HashPassword(null, defaultPassword);
string devPass = hasher.HashPassword(null, devPassword);
// Users:
User admin = new User(1,"admin", "Pera", "Administratovic","<EMAIL>", defaultPass, "<PASSWORD>", "administrator", 20.0d);
context.Users.Add(admin);
User passenger = new User(2, "a", "Darinka", "Putnik", "<EMAIL>", defaultPass, "<PASSWORD>", "passenger", 25.0d);
context.Users.Add(passenger);
User controller = new User(3, "ctrl", "Milos", "Nagib", "<EMAIL>", defaultPass, "<PASSWORD>", "controller", 50.0d);
context.Users.Add(controller);
User devadmin = new User(4, "dev", "Bill", "Linux Idol", "<EMAIL>", devPass, "<PASSWORD>", "administrator", 100.0d);
context.Users.Add(devadmin);
// Purchase codes:
PurchaseCode code = new PurchaseCode(1, Guid.Parse("bc495959-9aa7-447d-905d-0dfc74c16188"), 5.0d, DateTime.Now.ToUniversalTime(), null, false, null);
PurchaseCode code2 = new PurchaseCode(2, Guid.Parse("e1f80425-7f55-4a2a-b777-f6833c1758ae"), 10.0d, DateTime.Now.ToUniversalTime(), null, false, null);
PurchaseCode code3 = new PurchaseCode(3, Guid.Parse("33994bf3-0489-4897-9b87-853c76124ee1"), 25.0d, DateTime.Now.ToUniversalTime(), null, false, null);
PurchaseCode code4 = new PurchaseCode(4, Guid.Parse("6d043fbc-5fdc-40a0-9cbb-58bf7aef1744"), 50.0d, DateTime.Now.ToUniversalTime(), null, false, null);
PurchaseCode code5 = new PurchaseCode(5, Guid.Parse("6d043fac-5fdc-40a0-9cbb-58bf7aef1741"), 100.0d, DateTime.Now.ToUniversalTime(), null, false, null);
PurchaseCode code6 = new PurchaseCode(6, Guid.Parse("d6b11c76-a0f5-4ebf-b840-6d1a7d1b73ba"), 5.0d, DateTime.Now.ToUniversalTime(), null, false, null);
PurchaseCode code7 = new PurchaseCode(7, Guid.Parse("ec61f4c7-3f0d-4754-ab27-8756efae6542"), 10.0d, DateTime.Now.ToUniversalTime(), null, false, null);
PurchaseCode code8 = new PurchaseCode(8, Guid.Parse("39d3e085-5243-4ef3-a619-7d9765329f29"), 10.0d, DateTime.Now.ToUniversalTime(), null, false, null);
PurchaseCode code9 = new PurchaseCode(9, Guid.Parse("4806c7e3-2c2f-4581-b8c1-b82537098ad4"), 10.0d, DateTime.Now.ToUniversalTime(), null, false, null);
PurchaseCode code10 = new PurchaseCode(10, Guid.Parse("9999c59f-5827-47f6-a837-d6c6c70ed7a9"), 10.0d, DateTime.Now.ToUniversalTime(), null, false, null);
context.Codes.Add(code);
context.Codes.Add(code2);
context.Codes.Add(code3);
context.Codes.Add(code4);
context.Codes.Add(code5);
context.Codes.Add(code6);
context.Codes.Add(code7);
context.Codes.Add(code8);
context.Codes.Add(code9);
context.Codes.Add(code10);
// Ticket types:
TicketType typeHour = new TicketType(1, "Hourly ticket", 1, 1.2d);
TicketType typeDay = new TicketType(2, "Daily ticket", 24, 5d);
TicketType typeMonth = new TicketType(4, "Monthly ticket", 24*30, 40d);
TicketType typeWeek = new TicketType(3, "Weekly ticket", 24*7, 16d);
context.Types.Add(typeHour);
context.Types.Add(typeDay);
context.Types.Add(typeMonth);
context.Types.Add(typeWeek);
// Purchases:
TicketPurchase purchase = new TicketPurchase(750, Guid.NewGuid(), 30.0d, DateTime.Now, DateTime.Now.AddMinutes(typeHour.Duration.Value*60), 1,typeHour, passenger);
purchase.UserId = passenger.Id;
TicketPurchase purchase2 = new TicketPurchase(751, Guid.NewGuid(), 30.0d, DateTime.Now.AddHours(-3), DateTime.Now.AddHours(-2), 2, typeHour, passenger);
purchase2.UserId = passenger.Id;
TicketPurchase purchase3 = new TicketPurchase(752, Guid.NewGuid(), 30.0d, DateTime.Now.AddHours(-12), DateTime.Now.AddHours(12), 1, typeDay, passenger);
purchase3.UserId = passenger.Id;
TicketPurchase purchase4 = new TicketPurchase(753, Guid.NewGuid(), 30.0d, DateTime.Now, DateTime.Now.AddHours(24*30), 1, typeMonth, passenger);
purchase4.UserId = passenger.Id;
context.Purchases.Add(purchase);
context.Purchases.Add(purchase2);
context.Purchases.Add(purchase3);
context.Purchases.Add(purchase4);
// Validations:
TicketValidation validation = new TicketValidation(1,DateTime.Now.AddMinutes(2).ToUniversalTime(), true, purchase, controller);
context.Validations.Add(validation);
context.SaveChanges();
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace IO.Swagger.Models
{
/// <summary>
/// Operations for ticket validations manipulation
/// </summary>
public partial class TicketValidation
{
/// <summary>
/// Default constructor.
/// </summary>
public TicketValidation()
{
}
}
}
| 0ded722cb1c7133548ed4b92e314bb3d7d97876f | [
"Java",
"C#",
"Markdown",
"Gradle"
] | 41 | C# | sergiosuperstar/TripApp | cd91b7ac21431a584be1b5d936d33a8535fb001c | c69c26bc6510c33d3e0bde101c4a3faa97399752 |
refs/heads/master | <repo_name>hans-liu/NewQuant<file_sep>/MatrixComputation/Vector.h
#ifndef VECTOR_H
#define VECTOR_H
namespace NewQuant
{
template<typename TYPE>
class Vector
{
protected:
int length;
Vector(){}
Vector(const int &l) : length(l) {}
Vector(const Vector<TYPE> &v) : length(v.length){}
void SetLength(const int &l)
{
length = l;
}
public:
~Vector() {}
const int & Length() const
{
return length;
}
virtual void Resize(const int &) = 0;
virtual TYPE operator () (const int &) const = 0;
virtual TYPE & operator () (const int &) = 0;
};
}
#endif // VECTOR_H
<file_sep>/_test/_main.cpp
#include <fstream>
#include "testBandMatrix.h"
#include "testLowerBandMatrix.h"
#include "testUpperBandMatrix.h"
#include "testConstantMatrix.h"
#include "testDiagonalMatrix.h"
#include "testIdentityMatrix.h"
#include "testLowerTriangularMatrix.h"
#include "testUpperTriangularMatrix.h"
#include "testSymmetricMatrix.h"
#include "testSymmetricBandMatrix.h"
#include "testMatrix.h"
#include "testVector.h"
#include "testSquareMatrix.h"
#include "testPermuteMatrix.h"
#include "testTridiagonalMatrix.h"
#include "testLeastSquareSolver.h"
#include "testEigenSolver.h"
#include "testSVDsolver.h"
/*---------------*/
#include "../MathematicsExpresssion/ConstantAndVariable.h"
#include "../MathematicsExpresssion/BinaryExpression.h"
#include "../MathematicsExpresssion/UnitaryExpression.h"
#include "../MathematicsExpresssion/MathExpression.h"
int main()
{
using namespace std;
using namespace NewQuant;
//default_random_engine dre;
//normal_distribution<Type> nd;
return EXIT_SUCCESS;
}
/*
int main()
{
using namespace std;
using namespace NewQuant;
try
{
try
{
testSymmetricMatrix();
testBandMatrix();
testLowerBandMatrix();
testUpperBandMatrix();
testConstantMatrix();
testDiagonalMatrix();
testIdentityMatrix();
testLowerTriangularMatrix();
testUpperTriangularMatrix();
testSymmetricBandMatrix();
testMatrix();
testVector();
testSquareMatrix();
testPermuteMatrix();
testTridiagonalMatrix();
testLeastSquareSolver();
testEigenSolver();
testSVDsolver();
}
catch (BaseException &be)
{
cout << be.what() << endl;
Singleton<Tracer>::Instance()->PrintTrace();
}
}
catch (exception e)
{
cout << e.what() << endl;
}
return 0;
}
*/
<file_sep>/MatrixComputation/VectorExpression.h
#ifndef VECTOR_EXPRESSION_H
#define VECTOR_EXPRESSION_H
#include "../ExceptionClass/NotDefinedException.h"
namespace NewQuant
{
template<typename TYPE> class GeneralMatrix;
template<typename TYPE>
class VectorExpression
{
protected:
int length;
VectorExpression(){}
VectorExpression(const int &l) : length(l) {}
VectorExpression(const VectorExpression<TYPE> &v) : length(v.length){}
void SetLength(const int &l)
{
length = l;
}
public:
virtual int Search(const GeneralMatrix<TYPE> &) const = 0;
~VectorExpression() {}
int Length() const
{
return length;
}
virtual TYPE operator () (const int &i) const = 0;
virtual TYPE & operator () (const int &i)
{
Singleton<Tracer>::Instance()->AddMessage("TYPE & VectorExpression::operator () (r, c)");
throw NotDefinedException("TYPE & operator () (i)", "VectorExpression");
}
};
}
#endif // VECTOR_EXPRESSION_H
| 18301357a9c9a3d50f1d170942d9716a15846b97 | [
"C++"
] | 3 | C++ | hans-liu/NewQuant | ea6aea2bdd02f67ef12d86e7ff19574d5a327f04 | 20d2e901dfc3d2b5abe06a68edbfaae523761e9c |
refs/heads/master | <file_sep>#define BOOL int
#define TRUE 1
#define FALSE 0
#define LPCSTR LPSTR
typedef char* LPSTR;
#define UINT int
#define PASCAL _stdcall
#include <iostream>
class CObject;
struct CRuntimeClass
{
//Attributes
LPCSTR m_lpszClassName;
int m_nObjectSize;
UINT m_wSchema; //schema number of the loaded class
CObject* (PASCAL* m_pfnCreateObject) ();
CRuntimeClass* m_pBaseClass;
//CRuntimeClass objects linked together in simple list
static CRuntimeClass* pFirstClass;
CRuntimeClass* m_pNextClass; //linked list of registered classes
};
struct AFX_CLASSINIT
{
AFX_CLASSINIT(CRuntimeClass* pNewClass);
};
#define RUNTIME_CLASS(class_name) \
(&class_name::class##class_name)
#define DECLARE_DYNAMIC(class_name) \
public: \
static CRuntimeClass class##class_name; \
virtual CRuntimeClass* GetRuntimeClass() const;
#define _IMPLEMENT_RUNTIMECLASS(class_name,base_class_name,wSchema,pfnNew) \
static char _lpsz##class_name[] = #class_name; \
CRuntimeClass class_name::class##class_name = { \
_lpsz##class_name,sizeof(class_name),wSchema,pfnNew, \
RUNTIME_CLASS(base_class_name),NULL}; \
static AFX_CLASSINIT _init_##class_name(&class_name::class##class_name); \
CRuntimeClass* class_name::GetRuntimeClass() const \
{return &class_name::class##class_name;} \
#define IMPLEMENT_DYNAMIC(class_name,base_class_name) \
_IMPLEMENT_RUNTIMECLASS(class_name,base_class_name,0xFFFF,NULL)
class CObject
{
public:
CObject::CObject()
{
//std::cout << "CObject constructor \n";
}
CObject::~CObject()
{
//std::cout << "CObject destructor \n";
}
virtual CRuntimeClass* GetRuntimeClass() const;
public:
static CRuntimeClass classCObject;
private:
};
class CCmdTarget : public CObject
{
DECLARE_DYNAMIC(CCmdTarget)
public:
CCmdTarget::CCmdTarget()
{
//std::cout << "CCmdTarget constructor \n";
}
CCmdTarget::~CCmdTarget()
{
//std::cout << "CCmdTarget destructor \n";
}
private:
};
class CWinThread : public CCmdTarget
{
DECLARE_DYNAMIC(CWinThread)
public:
CWinThread::CWinThread()
{
//std::cout << "CWinThread constructor \n";
}
CWinThread::~CWinThread()
{
//std::cout << "CWinThread destructor \n";
}
virtual BOOL InitInstance()
{
//std::cout << "CWinThread::InitInstance \n";
return TRUE;
}
virtual int Run()
{
//std::cout << "CWinThread::Run \n";
return 1;
}
};
class CWnd;
class CWinApp : public CWinThread
{
DECLARE_DYNAMIC(CWinApp)
public:
CWinApp* m_pCurrentWinApp;
CWnd* m_pMainWnd;
public:
CWinApp::CWinApp()
{
m_pCurrentWinApp = this;
//std::cout << "CWinApp constructor \n";
}
CWinApp::~CWinApp()
{
//std::cout << "CWinApp destructor \n";
}
virtual BOOL InitApplication()
{
//std::cout << "CWinApp::InitApplication \n";
return TRUE;
}
virtual BOOL InitInstance()
{
//std::cout << "CWinApp::InitInstance \n";
return TRUE;
}
virtual int Run()
{
//std::cout << "CWinApp::Run \n";
return CWinThread::Run();
}
private:
};
class CDocument : public CCmdTarget
{
DECLARE_DYNAMIC(CDocument)
public:
CDocument::CDocument()
{
//std::cout << "CDocument constructor \n";
}
CDocument::~CDocument()
{
//std::cout << "CDocument destructor \n";
}
private:
};
class CWnd : public CCmdTarget
{
DECLARE_DYNAMIC(CWnd)
public:
CWnd::CWnd()
{
//std::cout << "CWnd constructor \n";
}
CWnd::~CWnd()
{
//std::cout << "CWnd destructor \n";
}
virtual BOOL Create();
BOOL CreateEx();
virtual BOOL PreCreateWindow();
private:
};
class CFrameWnd : public CWnd
{
DECLARE_DYNAMIC(CFrameWnd)
public:
CFrameWnd::CFrameWnd()
{
//std::cout << "CFrameWnd constructor \n";
}
CFrameWnd::~CFrameWnd()
{
//std::cout << "CFrameWnd destructor \n";
}
BOOL Create();
virtual BOOL PreCreateWindow();
};
class CView : public CWnd
{
DECLARE_DYNAMIC(CView)
public:
CView::CView()
{
//std::cout << "CView constructor \n";
}
CView::~CView()
{
//std::cout << "CView destructor \n";
}
private:
};
//global function
CWinApp* AfxGetApp();
| fc903c35f0fefdf584b4b753d8dacb68703a8d06 | [
"C++"
] | 1 | C++ | OctSnny/MFCsimu | 0165942a7ded794c6d96351f5c040004871d5f78 | c3c91e625e194bac7886098a93ff85b32b4fd099 |
refs/heads/master | <repo_name>wegotpop/prt-server<file_sep>/src/python2/prt/error.py
# -*- coding: utf-8 -*-
# Import compatibility features
from __future__ import (absolute_import,
division,
print_function,
unicode_literals)
#------------------------------------------------------------------------------#
class PRTError(Exception): pass
<file_sep>/run_tests.sh
#!/bin/bash
COVERAGE_2_BINARY='';
COVERAGE_3_BINARY='';
# If "naked" python is python2, then it is very likely that coverage2 is also "naked"
if [ "$(python -c 'from sys import stdout,version_info;stdout.write(str(version_info.major))')" = '2' ];
then
COVERAGE_2_BINARY=coverage;
else
COVERAGE_2_BINARY=coverage2;
fi;
# If "naked" python is python3, then it is very likely that coverage3 is also "naked"
if [ "$(python -c 'from sys import stdout,version_info;stdout.write(str(version_info.major))')" = '3' ];
then
COVERAGE_3_BINARY=coverage;
else
COVERAGE_3_BINARY=coverage3;
fi;
#
MAIN_ERROR_CODE=0;
check_error()
{
if [ "$1" -ne 0 ];
then
MAIN_ERROR_CODE=1;
fi;
}
# Run python 2 tests
PYTHONPATH="$PYTHONPATH:src/python2" \
$COVERAGE_2_BINARY run \
--source=src/python2/prt \
--module unittest discover tests/python2 --verbose;
check_error $?;
$COVERAGE_2_BINARY report --fail-under=100 --show-missing;
check_error $?;
# TODO: Run python 3 tests
exit $MAIN_ERROR_CODE;
<file_sep>/src/python2/prt/v2/dialect.py
# -*- coding: utf-8 -*-
# Import compatibility features
from __future__ import (absolute_import,
division,
print_function,
unicode_literals)
# Import from PRT modules
from prt.error import PRTError
#------------------------------------------------------------------------------#
class PRTDialectError(PRTError): pass
#------------------------------------------------------------------------------#
class NameMustBeOverriden(PRTDialectError):
_MESSAGE = 'PRTDialect.NAME must be overriden by all subclasses'
#- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
def __init__(self):
super(NameMustBeOverriden, self).__init__(self._MESSAGE)
#------------------------------------------------------------------------------#
class PRTDialect(object):
NAME = None
#- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
@classmethod
def validate_identifier(cls, identifier):
pass
#- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
@classmethod
def validate_attribute(cls, identifier, attribute_name, attribute_value):
pass
#- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
@classmethod
def identifier_to_html(cls, identifier):
return 'div'
#- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
@classmethod
def identifier_from_html(cls, identifier):
return 0
#- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
@classmethod
def attribute_to_html(cls, identifier, attribute_name, attribute_value):
return attribute_name, attribute_value
#- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
@classmethod
def attribute_from_html(cls, identifier, attribute_name, attribute_value):
return attribute_name, attribute_value
<file_sep>/src/python2/prt/dialects.py
# -*- coding: utf-8 -*-
# Import compatibility features
from __future__ import (absolute_import,
division,
print_function,
unicode_literals)
# Import from PRT modules
from prt.error import PRTError
from prt.version import PRTVersion, InvalidVersion
from prt.v2.dialect import (PRTDialect as _PRTDialectV2,
NameMustBeOverriden as _NameMustBeOverridenV2)
# TODO: There should be no built-in dialect!
from prt.v2.dialects.pop.dialect import PRTPOPDialect as PRTPOPDialectV2
#------------------------------------------------------------------------------#
class PRTDialectsError(PRTError): pass
#------------------------------------------------------------------------------#
class InvalidDialectType(PRTDialectsError): pass
#------------------------------------------------------------------------------#
class InvalidDialectName(PRTDialectsError): pass
#------------------------------------------------------------------------------#
class InvalidDialectVersion(PRTDialectsError): pass
#------------------------------------------------------------------------------#
# Module-level private constant
_DIALECTS = {}
#------------------------------------------------------------------------------#
def register_dialect(dialect, version):
# Validate arguments
if not isinstance(version, PRTVersion):
raise InvalidVersion(version)
try:
if not issubclass(dialect, _PRTDialectV2):
raise TypeError
except TypeError:
raise InvalidDialectType(
'Expected a subclass of prt.v2.dialect.PRTDialect, but got: '
'{0!r} (type {0.__class__.__name__})'.format(dialect))
if dialect.NAME is None:
raise _NameMustBeOverridenV2()
# Store dialect
_DIALECTS.setdefault(version, {})[dialect.NAME] = dialect
#------------------------------------------------------------------------------#
def get_dialect(name, version):
# Validate arguments
if not isinstance(version, PRTVersion):
raise InvalidVersion(version)
# Get dict referred by version
try:
dialects = _DIALECTS[version]
except KeyError:
raise InvalidDialectVersion(
'No dialect registered with this version: {}'.format(version))
# Get dialect referred by name
try:
return dialects[name]
except KeyError:
raise InvalidDialectName(
'No dialect registered with this name and '
'version: {} {}'.format(name, version))
#- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
register_dialect(PRTPOPDialectV2, PRTVersion.V2)
<file_sep>/README.md
# PRT

This repository is the reference server-side implemention of [PRT][1], a safe,
small and strict rich text serialisation protocol.
### Table of Content
- [PRTv2.0](#prtv20)
- [Python 2](#python-2)
- [Dependencies](#dependencies)
- [Developer Dependencies](#developer-dependencies)
- [Python 3](#python-3)
- [Lincese](#license)
## PRTv2.0
### Python 2
> TODO: Add documentation here
#### Dependencies
- [`enum34`][2]
- [`lxml`][3]
#### Developer Dependencies
- [`coverage`][5]
### Python 3
> TODO: Add documentation here
## License
Copyright ©2017 [**We Got POP Ltd.**][4]
Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
<!-- anchors -->
[1]: https://github.com/wegotpop/prt
[2]: https://pypi.python.org/pypi/enum34
[3]: https://pypi.python.org/pypi/lxml
[4]: https://www.wegotpop.com
[5]: https://coverage.readthedocs.io
<file_sep>/tests/python2/unit/test_version.py
# -*- coding: utf-8 -*-
# Import compatibility features
from __future__ import (absolute_import,
division,
print_function,
unicode_literals)
# Import from standard modules
from unittest import TestCase
# Import from PRT modules
from prt.version import PRTVersion, InvalidVersion
#------------------------------------------------------------------------------#
class TestPRTVersion(TestCase):
#- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
def test_numbered(self):
self.assertEqual(PRTVersion.V1.value, '1.0')
self.assertEqual(PRTVersion.V2.value, '2.0')
#- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
def test_aliased(self):
self.assertEqual(PRTVersion.LOWEST, PRTVersion.V1)
self.assertEqual(PRTVersion.HIGHEST, PRTVersion.V2)
#- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
def test_order(self):
self.assertEqual(tuple(PRTVersion), (PRTVersion.V1, PRTVersion.V2))
#- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
def test_error(self):
self.assertEqual(InvalidVersion().message,
'Expected one of PRTVersion.V1, PRTVersion.V2, '
'but got: None (type NoneType)')
#- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
def test_as_int_tuple(self):
self.assertEqual(PRTVersion.V1.as_int_tuple(), (1, 0))
self.assertEqual(PRTVersion.V2.as_int_tuple(), (2, 0))
<file_sep>/tests/python2/unit/v2/test_markup.py
# -*- coding: utf-8 -*-
# Import compatibility features
from __future__ import (absolute_import,
division,
print_function,
unicode_literals)
# Import from standard modules
from unittest import TestCase
# Import from lxml modules
from lxml.html import (Element,
tostring)
# Import from PRT modules
from prt.error import PRTError
from prt.v2.dialect import PRTDialect
from prt.v2.markup import (PRTMarkUp,
PRTMarkUpError,
InvalidIdentifier,
InvalidElementsType,
InvalidElementType,
InvalidAttributesToIdentifier,
InvalidAttributeToIdentifier)
#------------------------------------------------------------------------------#
class TestPRTMarkUp(TestCase):
#- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
def test_error(self):
self.assertTrue(issubclass(PRTMarkUpError, PRTError))
self.assertTrue(issubclass(InvalidIdentifier, PRTMarkUpError))
self.assertTrue(issubclass(InvalidElementsType, PRTMarkUpError))
self.assertTrue(issubclass(InvalidElementType, PRTMarkUpError))
self.assertTrue(issubclass(InvalidAttributesToIdentifier,
PRTMarkUpError))
self.assertTrue(issubclass(InvalidAttributeToIdentifier,
PRTMarkUpError))
#- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
def test_bool(self):
self.assertFalse(PRTMarkUp(None, None))
self.assertTrue(PRTMarkUp('None', None))
#- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
def test_equality(self):
class DummyMarkUp(object):
_elements = None
self.assertEqual(PRTMarkUp(None, None), PRTMarkUp(None, None))
self.assertEqual(PRTMarkUp([], None), PRTMarkUp([], None))
self.assertNotEqual(PRTMarkUp(None, None), PRTMarkUp([], None))
self.assertNotEqual(PRTMarkUp(None, None), DummyMarkUp())
#- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
def test_valid_append_to_etree(self):
root = Element('test_root')
PRTMarkUp(None, None).append_to_etree(root)
self.assertEqual(tostring(root), '<test_root></test_root>')
root = Element('test_root')
PRTMarkUp('text', None).append_to_etree(root)
self.assertEqual(tostring(root), '<test_root>text</test_root>')
root = Element('test_root')
PRTMarkUp([None], PRTDialect).append_to_etree(root)
self.assertEqual(tostring(root), '<test_root></test_root>')
root = Element('test_root')
PRTMarkUp(['text'], PRTDialect).append_to_etree(root)
self.assertEqual(tostring(root), '<test_root>text</test_root>')
root = Element('test_root')
PRTMarkUp([[0, None, 'text']], PRTDialect).append_to_etree(root)
self.assertEqual(tostring(root),
'<test_root><div>text</div></test_root>')
root = Element('test_root')
PRTMarkUp([[0, {'id': 'this'}, 'text']],
PRTDialect).append_to_etree(root)
self.assertEqual(tostring(root),
'<test_root><div id="this">text</div></test_root>')
#- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
def test_invalid_append_to_etree(self):
root = Element('test_root')
PRTMarkUp(True, None).append_to_etree(root)
self.assertEqual(tostring(root),
'<test_root><del>Invalid PRTMarkUp</del></test_root>')
#- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
def test_to_html(self):
self.assertEqual(PRTMarkUp(None, PRTDialect).to_html(), '')
self.assertEqual(PRTMarkUp('<div/>', PRTDialect).to_html(),
'<div/>')
self.assertEqual(PRTMarkUp([None], PRTDialect).to_html(), '')
self.assertEqual(PRTMarkUp('text', PRTDialect).to_html(), 'text')
self.assertEqual(PRTMarkUp([(0, None, 'text')], PRTDialect).to_html(),
'<div>text</div>')
self.assertEqual(PRTMarkUp([(0, {'id': 'this'}, '<div/>')],
PRTDialect).to_html(),
'<div id="this"><div/></div>')
#- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
def test_validate(self):
PRTMarkUp(None, None).validate()
PRTMarkUp('text', None).validate()
self.assertRaises(InvalidElementsType, PRTMarkUp(True, None).validate)
self.assertRaises(InvalidElementType,
PRTMarkUp([(0, None)], None).validate)
self.assertRaises(InvalidElementType,
PRTMarkUp([(0, None, None, None)], None).validate)
self.assertRaises(InvalidAttributesToIdentifier,
PRTMarkUp([(0, True, None)], PRTDialect).validate)
self.assertRaises(InvalidAttributeToIdentifier,
PRTMarkUp([(0, {'id': 0}, None)],
PRTDialect).validate)
#- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
def test_elements(self):
m = PRTMarkUp(None, None)
# Validate and get elements
self.assertEqual(m.elements(), None)
# Validate again and get elements
self.assertEqual(m.elements(), None)
#- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
def test_alias(self):
self.assertEqual(PRTMarkUp(None, None).to_html(),
str(PRTMarkUp(None, None)))
<file_sep>/tests/python2/unit/test_error.py
# -*- coding: utf-8 -*-
# Import compatibility features
from __future__ import (absolute_import,
division,
print_function,
unicode_literals)
# Import from standard modules
from unittest import TestCase
# Import from PRT modules
from prt.error import PRTError
#------------------------------------------------------------------------------#
class TestPRTError(TestCase):
#- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
def test_instance(self):
self.assertTrue(issubclass(PRTError, Exception))
<file_sep>/src/python2/prt/version.py
# -*- coding: utf-8 -*-
# Import compatibility features
from __future__ import (absolute_import,
division,
print_function,
unicode_literals)
# Import from enum34 modules
from enum import Enum
# Import from PRT modules
from prt.error import PRTError
#------------------------------------------------------------------------------#
class PRTVersionError(PRTError): pass
#------------------------------------------------------------------------------#
class InvalidVersion(PRTVersionError):
_MESSAGE = ('Expected one of {0}, but got: '
'{1!r} (type {1.__class__.__name__})')
#- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
def __init__(self, version=None):
super(InvalidVersion, self).__init__(
self._MESSAGE.format(
', '.join('PRTVersion.{}'.format(v.name) for v in PRTVersion),
version))
#------------------------------------------------------------------------------#
class PRTVersion(Enum):
# TODO: py3: Remove the __order__ string
__order__ = 'V1 V2'
V1 = LOWEST = '1.0'
V2 = HIGHEST = '2.0'
#- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
def as_int_tuple(self):
return tuple(map(int, self.value.split('.')))
<file_sep>/src/python2/prt/v2/dialects/pop/dialect.py
# -*- coding: utf-8 -*-
from __future__ import (absolute_import,
division,
print_function,
unicode_literals)
# Import from PRT modules
from prt.v2.dialect import PRTDialect
from prt.v2.markup import (InvalidIdentifier,
InvalidAttributeToIdentifier)
#------------------------------------------------------------------------------#
class PRTPOPDialect(PRTDialect):
_VALID_IDENTIFIERS = {0x00 : 'a',
0x01 : 'b',
0x02 : 'blockquote',
0x03 : 'code',
0x04 : 'div',
0x05 : 'h1',
0x06 : 'h2',
0x07 : 'h3',
0x08 : 'h4',
0x09 : 'h5',
0x0A : 'h6',
0x0B : 'h7',
0x0C : 'i',
0x0D : 'img',
0x0E : 'li',
0x0F : 'ol',
0x10 : 'p',
0x11 : 'pre',
0x12 : 's',
0x13 : 'span',
0x14 : 'sub',
0x15 : 'sup',
0x16 : 'u',
0x17 : 'ul'}
_VALID_TAGS = {v: k for k, v in
_VALID_IDENTIFIERS.iteritems()}
_VALID_GENERIC_ATTRIBUTES = {'id', 'class'}
_VALID_SPECIFIC_ATTRIBUTES = {0x00: {'href', 'target'},
0x0B: {'alt', 'src', 'title'}}
NAME = 'pop'
#- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
@classmethod
def validate_identifier(cls, identifier):
try:
cls._VALID_IDENTIFIERS[identifier]
except KeyError:
raise InvalidIdentifier(
'Expected one of {0!r}, but got: {1!r} (type '
'{1.__class__.__name__})'.format(
tuple(cls._VALID_IDENTIFIERS.iterkeys()), identifier))
#- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
@classmethod
def validate_attribute(cls, identifier, attribute, _):
try:
valid_attributes = cls._VALID_SPECIFIC_ATTRIBUTES[identifier].copy()
except KeyError:
valid_attributes = set()
valid_attributes |= cls._VALID_GENERIC_ATTRIBUTES
if attribute not in valid_attributes:
raise InvalidAttributeToIdentifier(
'Expected to have one of {0!r}, but got {1!r} (type '
'{1.__class__.__name__})'.format(valid_attributes, attribute))
#- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
@classmethod
def identifier_to_html(cls, identifier):
return cls._VALID_IDENTIFIERS[identifier]
#- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
@classmethod
def identifier_from_html(cls, tag):
return cls._VALID_TAGS[tag]
<file_sep>/tests/python2/integration/test_pop_dialect.py
# -*- coding: utf-8 -*-
# Import compatibility features
from __future__ import (absolute_import,
division,
print_function,
unicode_literals)
# Import from standard modules
from unittest import TestCase
# Import from PRT modules
from prt.document import PRTDocument
from prt.version import PRTVersion
#------------------------------------------------------------------------------#
class TestPRTPOPDialectUsage(TestCase):
#- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
def test_using_via_prtdocument(self):
self.assertEqual(
PRTDocument(None, version=PRTVersion.V2, dialect='pop').to_json(),
'{'
'"type":"PRTDocument",'
'"version":"2.0",'
'"dialect":"pop",'
'"elements":null'
'}')
<file_sep>/tests/python2/unit/v2/dialects/pop/test_dialect.py
# -*- coding: utf-8 -*-
# Import compatibility features
from __future__ import (absolute_import,
division,
print_function,
unicode_literals)
# Import from standard modules
from unittest import TestCase
# Import from PRT modules
from prt.v2.markup import (InvalidIdentifier,
InvalidAttributeToIdentifier)
from prt.v2.dialects.pop.dialect import PRTPOPDialect
#------------------------------------------------------------------------------#
class TestPRTPOPDialect(TestCase):
#- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
def test_identifier_validation(self):
for i in range(0x17):
PRTPOPDialect.validate_identifier(i)
self.assertRaises(InvalidIdentifier,
PRTPOPDialect.validate_identifier,
0x18)
#- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
def test_attribute_validation(self):
for i in range(0x0F):
PRTPOPDialect.validate_attribute(i, 'id', None)
PRTPOPDialect.validate_attribute(i, 'class', None)
PRTPOPDialect.validate_attribute(0x00, 'href', None)
PRTPOPDialect.validate_attribute(0x0B, 'alt', None)
PRTPOPDialect.validate_attribute(0x0B, 'src', None)
self.assertRaises(InvalidAttributeToIdentifier,
PRTPOPDialect.validate_attribute,
0x01, 'href', None)
#- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
def test_identifier_conversion(self):
self.assertEqual(PRTPOPDialect.identifier_to_html(0x00), 'a')
self.assertEqual(PRTPOPDialect.identifier_to_html(0x01), 'b')
self.assertEqual(PRTPOPDialect.identifier_to_html(0x02), 'blockquote')
self.assertEqual(PRTPOPDialect.identifier_to_html(0x03), 'code')
self.assertEqual(PRTPOPDialect.identifier_to_html(0x04), 'div')
self.assertEqual(PRTPOPDialect.identifier_to_html(0x05), 'h1')
self.assertEqual(PRTPOPDialect.identifier_to_html(0x06), 'h2')
self.assertEqual(PRTPOPDialect.identifier_to_html(0x07), 'h3')
self.assertEqual(PRTPOPDialect.identifier_to_html(0x08), 'h4')
self.assertEqual(PRTPOPDialect.identifier_to_html(0x09), 'h5')
self.assertEqual(PRTPOPDialect.identifier_to_html(0x0A), 'h6')
self.assertEqual(PRTPOPDialect.identifier_to_html(0x0B), 'h7')
self.assertEqual(PRTPOPDialect.identifier_to_html(0x0C), 'i')
self.assertEqual(PRTPOPDialect.identifier_to_html(0x0D), 'img')
self.assertEqual(PRTPOPDialect.identifier_to_html(0x0E), 'li')
self.assertEqual(PRTPOPDialect.identifier_to_html(0x0F), 'ol')
self.assertEqual(PRTPOPDialect.identifier_to_html(0x10), 'p')
self.assertEqual(PRTPOPDialect.identifier_to_html(0x11), 'pre')
self.assertEqual(PRTPOPDialect.identifier_to_html(0x12), 's')
self.assertEqual(PRTPOPDialect.identifier_to_html(0x13), 'span')
self.assertEqual(PRTPOPDialect.identifier_to_html(0x14), 'sub')
self.assertEqual(PRTPOPDialect.identifier_to_html(0x15), 'sup')
self.assertEqual(PRTPOPDialect.identifier_to_html(0x16), 'u')
self.assertEqual(PRTPOPDialect.identifier_to_html(0x17), 'ul')
self.assertEqual(PRTPOPDialect.identifier_from_html('a'), 0x00)
self.assertEqual(PRTPOPDialect.identifier_from_html('b'), 0x01)
self.assertEqual(PRTPOPDialect.identifier_from_html('blockquote'), 0x02)
self.assertEqual(PRTPOPDialect.identifier_from_html('code'), 0x03)
self.assertEqual(PRTPOPDialect.identifier_from_html('div'), 0x04)
self.assertEqual(PRTPOPDialect.identifier_from_html('h1'), 0x05)
self.assertEqual(PRTPOPDialect.identifier_from_html('h2'), 0x06)
self.assertEqual(PRTPOPDialect.identifier_from_html('h3'), 0x07)
self.assertEqual(PRTPOPDialect.identifier_from_html('h4'), 0x08)
self.assertEqual(PRTPOPDialect.identifier_from_html('h5'), 0x09)
self.assertEqual(PRTPOPDialect.identifier_from_html('h6'), 0x0A)
self.assertEqual(PRTPOPDialect.identifier_from_html('h7'), 0x0B)
self.assertEqual(PRTPOPDialect.identifier_from_html('i'), 0x0C)
self.assertEqual(PRTPOPDialect.identifier_from_html('img'), 0x0D)
self.assertEqual(PRTPOPDialect.identifier_from_html('li'), 0x0E)
self.assertEqual(PRTPOPDialect.identifier_from_html('ol'), 0x0F)
self.assertEqual(PRTPOPDialect.identifier_from_html('p'), 0x10)
self.assertEqual(PRTPOPDialect.identifier_from_html('pre'), 0x11)
self.assertEqual(PRTPOPDialect.identifier_from_html('s'), 0x12)
self.assertEqual(PRTPOPDialect.identifier_from_html('span'), 0x13)
self.assertEqual(PRTPOPDialect.identifier_from_html('sub'), 0x14)
self.assertEqual(PRTPOPDialect.identifier_from_html('sup'), 0x15)
self.assertEqual(PRTPOPDialect.identifier_from_html('u'), 0x16)
self.assertEqual(PRTPOPDialect.identifier_from_html('ul'), 0x17)
<file_sep>/src/python2/prt/document.py
# -*- coding: utf-8 -*-
# Import compatibility features
from __future__ import (absolute_import,
division,
print_function,
unicode_literals)
# Import from PRT modules
from prt.version import PRTVersion, InvalidVersion
from prt.dialects import get_dialect
from prt.v2.document import PRTDocument as _PRTDocumentV2
#------------------------------------------------------------------------------#
class PRTDocument(object):
"""
Version based class dispatcher
"""
#- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
def __new__(cls, elements,
dialect,
version=PRTVersion.HIGHEST,
*args,
**kwargs):
if version == PRTVersion.V2:
dialect = get_dialect(dialect, version)
return _PRTDocumentV2(elements, dialect, *args, **kwargs)
raise InvalidVersion(version)
#- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
@classmethod
def from_html(cls, string, version=PRTVersion.HIGHEST, *arg, **kwargs):
if version == PRTVersion.V2:
return _PRTDocumentV2.from_html(string, *arg, **kwargs)
raise InvalidVersion(version)
#- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
@classmethod
def from_json(cls, string, version=PRTVersion.HIGHEST, *arg, **kwargs):
if version == PRTVersion.V2:
return _PRTDocumentV2.from_json(string, *arg, **kwargs)
raise InvalidVersion(version)
<file_sep>/src/python2/prt/v2/document.py
# -*- coding: utf-8 -*-
# Import compatibility features
from __future__ import (absolute_import,
division,
print_function,
unicode_literals)
# Import from standard modules
from json import (dumps,
loads)
from collections import OrderedDict
from lxml.etree import XMLSyntaxError
from lxml.html import (Element,
tostring,
fromstring)
# Import from PRT modules
from prt.error import PRTError
from prt.version import PRTVersion
from prt.dialects import get_dialect
from prt.v2.markup import PRTMarkUp
#------------------------------------------------------------------------------#
class PRTDocumentError(PRTError): pass
#------------------------------------------------------------------------------#
class InvalidPRTDocument(PRTDocumentError): pass
#------------------------------------------------------------------------------#
class IncompatibleVersion(PRTDocumentError): pass
#------------------------------------------------------------------------------#
class PRTDocument(object):
"""
Usage:
>>> from prt import PRTDocument
# Create from python objects
>>> document = PRTDocument(
... [(0x00, {'href': '#'}, 'click')],
... dialect='pop')
>>> document.to_dict()
{'type': 'PRTDocument',
'version': '2.0',
'dialect': 'pop','
'elements': [[0, {'href': '#''}, 'click']]}
>>> document.to_json()
('{"type":"PRTDocument","version":"2.0","dialect":"pop",'
'"elements":[[0,{"href":"#"},"click"]]}')
>>> document.to_html()
('<PRTDocument version="2.0" dialect="pop">'
'<a href="#">click</a></PRTDocument>')
# Creat from dict-like object
>>> PRTDocument.from_dict({'type': 'PRTDocument',
... 'version': '2.0',
... 'dialect': 'pop',
... 'elements': 'text'}).to_html()
'<PRTDocument version="2.0" dialect="pop">text</PRTDocument>'
# Create from HTML string
>>> PRTDocument.from_html(
... '<img src="img.png">',
... dialect='pop').to_json()
('{"type":"PRTDocument","version":"2.0","dialect":"pop",'
'"elements":[[11,{"src":"img.png"},null]]}')
# Create from JSON string
>>> PRTDocument.from_json(
... '[[1, null, "text"]]',
... dialect='pop').to_html()
'<PRTDocument version="2.0" dialect="pop"><b>text</b></PRTDocument>'
"""
_VERSION = PRTVersion.V2
#- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
def __init__(self, elements, dialect=None):
self._dialect = dialect
self._mark_up = PRTMarkUp(elements, dialect)
#- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
def __nonzero__(self):
return bool(self._mark_up)
#- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
def __eq__(self, other):
return (isinstance(other, self.__class__) and
self._mark_up == other._mark_up)
#- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
def __ne__(self, other):
return not self.__eq__(other)
#- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
@staticmethod
def _from_etree(document, dialect):
elements = []
if document.text:
elements.append(unicode(document.text))
for etree in document:
identifier = dialect.identifier_from_html(etree.tag)
attributes = dict(
dialect.attribute_from_html(identifier, *map(unicode, a)) for a
in etree.attrib.iteritems()) or None
if not len(etree):
if etree.text:
elements_ = unicode(etree.text)
else:
elements_ = None
else:
elements_ = PRTDocument._from_etree(etree, dialect)
elements.append((identifier, attributes, elements_))
if etree.tail:
elements.append(unicode(etree.tail))
return elements
#- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
@classmethod
def from_dict(cls, dict_object):
if dict_object.get('type', None) != 'PRTDocument':
raise InvalidPRTDocument
elif dict_object.get('version', None) != cls._VERSION.value:
raise IncompatibleVersion
dialect = get_dialect(dict_object.get('dialect', None), cls._VERSION)
return PRTDocument(dict_object.get('elements', None), dialect)
#- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
@classmethod
def from_json(cls, string):
try:
document = loads(string, object_pairs_hook=OrderedDict)
except ValueError:
raise InvalidPRTDocument
return cls.from_dict(document)
#- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
@classmethod
def from_html(cls, string):
try:
document = fromstring(string)
except XMLSyntaxError:
raise InvalidPRTDocument
if document.tag != 'prtdocument':
raise InvalidPRTDocument
elif document.get('version', None) != cls._VERSION.value:
raise IncompatibleVersion
dialect = get_dialect(document.get('dialect', None), cls._VERSION)
return PRTDocument(cls._from_etree(document, dialect), dialect)
#- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
def to_dict(self):
"""
Python object representation of the PRTDocument
"""
self.validate()
document = OrderedDict()
document['type'] = 'PRTDocument'
document['version'] = self._VERSION.value
if self._dialect:
document['dialect'] = self._dialect.NAME
document['elements'] = self._mark_up.elements()
return document
#- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
def to_json(self):
"""
JSON string representation of the PRTDocument
"""
return dumps(self.to_dict(), separators=(',', ':'))
#- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
def to_html(self):
"""
HTML string representation of the PRTDocument
"""
self.validate()
document = Element('PRTDocument')
document.set('version', self._VERSION.value)
if self._dialect:
document.set('dialect', self._dialect.NAME)
self._mark_up.append_to_etree(document)
return tostring(document)
#- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
def validate(self):
self._mark_up.validate()
#- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
__repr__ = to_html
#- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
__str__ = to_json
<file_sep>/tests/python2/unit/v2/test_document.py
# -*- coding: utf-8 -*-
# Import compatibility features
from __future__ import (absolute_import,
division,
print_function,
unicode_literals)
# Import from standard modules
from unittest import TestCase
# Import from lxml modules
from lxml.html import tostring
# Import from PRT modules
from prt.error import PRTError
from prt.version import (PRTVersion,
InvalidVersion)
from prt.dialects import (register_dialect,
InvalidDialectName)
from prt.v2.dialect import PRTDialect
from prt.v2.document import (PRTDocument,
PRTDocumentError,
InvalidPRTDocument,
IncompatibleVersion)
#------------------------------------------------------------------------------#
class DummyDialect(PRTDialect):
NAME = 'dummy'
#------------------------------------------------------------------------------#
class TestPRTDocument(TestCase):
def setUp(self):
register_dialect(DummyDialect, PRTVersion.V2)
#- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
def test_error(self):
self.assertTrue(issubclass(PRTDocumentError, PRTError))
self.assertTrue(issubclass(InvalidPRTDocument, PRTDocumentError))
self.assertTrue(issubclass(IncompatibleVersion, PRTDocumentError))
#- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
def test_valid_document(self):
PRTDocument(None)
#- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
def test_bool(self):
self.assertFalse(PRTDocument(None))
self.assertTrue(PRTDocument('None'))
#- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
def test_equality(self):
self.assertEqual(PRTDocument(None), PRTDocument(None))
self.assertNotEqual(PRTDocument(None), PRTDocument('None'))
#- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
def test_valid_from_html(self):
self.assertEqual(
PRTDocument.from_html(
'<PRTDocument version="2.0" dialect="dummy"/>'),
PRTDocument([], 'dummy'))
self.assertEqual(
PRTDocument.from_html(
'<PRTDocument version="2.0" dialect="dummy">'
'text'
'</PRTDocument>'),
PRTDocument(['text'], 'dummy'))
self.assertEqual(
PRTDocument.from_html(
'<PRTDocument version="2.0" dialect="dummy">'
'<div>text</div>'
'</PRTDocument>'),
PRTDocument([(0, None, 'text')], 'dummy'))
self.assertEqual(
PRTDocument.from_html(
'<PRTDocument version="2.0" dialect="dummy">'
'<div></div>'
'</PRTDocument>'),
PRTDocument([(0, None, None)], 'dummy'))
self.assertEqual(
PRTDocument.from_html(
'<PRTDocument version="2.0" dialect="dummy">'
'<div>'
'<div>text</div>'
'</div>'
'</PRTDocument>'),
PRTDocument([(0, None, [(0, None, 'text')])], 'dummy'))
self.assertEqual(
PRTDocument.from_html(
'<PRTDocument version="2.0" dialect="dummy">'
'<div>'
'<div>text</div>'
'text2'
'</div>'
'</PRTDocument>'),
PRTDocument([(0, None, [(0, None, 'text'), 'text2'])],
'dummy'))
#- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
def test_invalid_from_html(self):
self.assertRaises(InvalidPRTDocument, PRTDocument.from_html, '')
self.assertRaises(InvalidPRTDocument, PRTDocument.from_html, '<br/>')
self.assertRaises(IncompatibleVersion,
PRTDocument.from_html,
'<PRTDocument/>')
self.assertRaises(IncompatibleVersion,
PRTDocument.from_html,
'<PRTDocument version="1.0"/>')
self.assertRaises(InvalidDialectName,
PRTDocument.from_html,
'<PRTDocument version="2.0"/>')
self.assertRaises(InvalidDialectName,
PRTDocument.from_html,
'<PRTDocument version="2.0" dialect="hello"/>')
#- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
def test_valid_from_json(self):
self.assertEqual(
PRTDocument.from_json(
'{'
'"type":"PRTDocument",'
'"version":"2.0",'
'"dialect":"dummy",'
'"elements":null'
'}'),
PRTDocument(None, DummyDialect))
#- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
def test_invalid_from_json(self):
self.assertRaises(InvalidPRTDocument, PRTDocument.from_json, '')
self.assertRaises(InvalidPRTDocument, PRTDocument.from_json, '{}')
self.assertRaises(IncompatibleVersion,
PRTDocument.from_json,
'{"type":"PRTDocument"}')
self.assertRaises(IncompatibleVersion,
PRTDocument.from_json,
'{"type":"PRTDocument","version":"1.0"}')
self.assertRaises(InvalidDialectName,
PRTDocument.from_json,
'{"type":"PRTDocument","version":"2.0"}')
self.assertRaises(InvalidDialectName,
PRTDocument.from_json,
'{'
'"type":"PRTDocument",'
'"version":"2.0",'
'"dialect":"hello"'
'}')
#- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
def test_valid_to_html(self):
self.assertEqual(PRTDocument(None).to_html(),
'<PRTDocument version="2.0"></PRTDocument>')
self.assertEqual(PRTDocument('text').to_html(),
'<PRTDocument version="2.0">'
'text'
'</PRTDocument>')
self.assertEqual(PRTDocument([(0, None, 'text')], DummyDialect).to_html(),
'<PRTDocument version="2.0" dialect="dummy">'
'<div>'
'text'
'</div>'
'</PRTDocument>')
#- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
def test_valid_to_json(self):
self.assertEqual(PRTDocument(None).to_json(),
'{'
'"type":"PRTDocument",'
'"version":"2.0",'
'"elements":null'
'}')
self.assertEqual(PRTDocument('text').to_json(),
'{'
'"type":"PRTDocument",'
'"version":"2.0",'
'"elements":"text"'
'}')
self.assertEqual(PRTDocument([(0, None, 'text')], DummyDialect).to_json(),
'{'
'"type":"PRTDocument",'
'"version":"2.0",'
'"dialect":"dummy",'
'"elements":[[0,null,"text"]]'
'}')
#- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
def test_alias(self):
self.assertEqual(PRTDocument(None).to_html(), repr(PRTDocument(None)))
self.assertEqual(PRTDocument(None).to_json(), str(PRTDocument(None)))
<file_sep>/setup.py
from setuptools import setup, find_packages
setup(name='prt',
description='PRT reference server-side implementation',
long_description=('PRT (POP Rich Text) is a safe, small and strict rich '
'text serialisation protocol which can be used for '
'example in server - client communications. More info '
'on the protocol: https://github.com/wegotpop/prt'),
version='1.0.1',
url='https://github.com/wegotpop/prt-server',
author='We Got POP Ltd.',
author_email='<EMAIL>',
license='MIT',
classifiers=[
'Development Status :: 5 - Production/Stable',
'Intended Audience :: Developers',
'Topic :: Utilities',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python :: 2.7'],
packages=find_packages(where='src/python2'),
package_dir={'': 'src/python2'},
python_requires='>=2.7',
install_requires=['enum34>=1.1.6',
'lxml>=3.8.0'])
<file_sep>/tests/python2/unit/test_document.py
# -*- coding: utf-8 -*-
# Import compatibility features
from __future__ import (absolute_import,
division,
print_function,
unicode_literals)
# Import from standard modules
from unittest import TestCase
# Import from PRT modules
from prt.error import PRTError
from prt.version import (PRTVersion,
InvalidVersion)
from prt.document import PRTDocument
from prt.dialects import register_dialect
from prt.v2.dialect import PRTDialect
from prt.v2.document import PRTDocument as PRTDocumentV2
#------------------------------------------------------------------------------#
class TestDialect(PRTDialect):
NAME = 'test'
#------------------------------------------------------------------------------#
class TestPRTDocument(TestCase):
#- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
def setUp(self):
register_dialect(TestDialect, PRTVersion.V2)
#- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
def test_empty_valid_document(self):
PRTDocument(None, version=PRTVersion.V2, dialect='test')
#- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
def test_empty_invalid_document(self):
self.assertRaises(InvalidVersion,
PRTDocument,
elements=None,
dialect='test',
version=2.0)
#- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
def test_simple_valid_document_from_html(self):
PRTDocument.from_html('<PRTDocument version="2.0" dialect="test"/>')
#- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
def test_simple_invalid_document_from_html(self):
self.assertRaises(InvalidVersion,
PRTDocument.from_html,
string='',
version=2.0)
#- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
def test_simple_valid_document_from_json(self):
PRTDocument.from_json(
'{'
'"type":"PRTDocument",'
'"version":"2.0",'
'"dialect":"test",'
'"elements":null'
'}')
#- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
def test_simple_invalid_document_from_json(self):
self.assertRaises(InvalidVersion,
PRTDocument.from_json,
string='',
version=2.0)
<file_sep>/src/python2/prt/v2/markup.py
# -*- coding: utf-8 -*-
# Import compatibility features
from __future__ import (absolute_import,
division,
print_function,
unicode_literals)
# Import from standard modules
from cgi import escape
from lxml.html import (Element,
tostring)
# Import from PRT modules
from prt.error import PRTError
#------------------------------------------------------------------------------#
class PRTMarkUpError(PRTError): pass
#------------------------------------------------------------------------------#
class InvalidElementsType(PRTMarkUpError): pass
#------------------------------------------------------------------------------#
class InvalidElementType(PRTMarkUpError): pass
#------------------------------------------------------------------------------#
class InvalidAttributesToIdentifier(PRTMarkUpError): pass
#------------------------------------------------------------------------------#
class InvalidAttributeToIdentifier(PRTMarkUpError): pass
#------------------------------------------------------------------------------#
# Used by dialects:
class InvalidIdentifier(PRTMarkUpError): pass
#------------------------------------------------------------------------------#
class PRTMarkUp(object):
#- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
def __init__(self, elements, dialect):
# TODO: add sanitisation to elements, for example, if it is an empty
# string or an empty iterable, then make it None, etc.
self._elements = elements
self._dialect = dialect
self._validated = False
#- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
def __nonzero__(self):
return bool(self._elements)
#- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
def __eq__(self, other):
# TODO: Consider checking the dialects as well?
return (isinstance(other, self.__class__) and
self._elements == other._elements)
#- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
def __ne__(self, other):
return not self.__eq__(other)
#- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
def _append_element_to_etree(self, element, root):
if element is None:
return
elif isinstance(element, unicode):
element = escape(element, quote=True)
try:
root[-1].tail = element
except IndexError:
root.text = element
return
identifier, attributes, elements = element
element = Element(self._dialect.identifier_to_html(identifier))
if attributes is not None:
for name, value in sorted(attributes.iteritems()):
element.set(
*self._dialect.attribute_to_html(identifier, name, value))
self._append_elements_to_etree(elements, element)
root.append(element)
#- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
def _append_elements_to_etree(self, elements, root):
if elements is None:
return
elif isinstance(elements, unicode):
try:
root[-1].tail = elements
except IndexError:
root.text = elements
return
for element in elements:
self._append_element_to_etree(element, root)
#- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
def append_to_etree(self, root):
try:
self._validated or self.validate()
self._append_elements_to_etree(self._elements, root)
except PRTMarkUpError:
element = Element('del')
element.text = 'Invalid PRTMarkUp'
root.append(element)
#- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
def to_html(self):
if self._elements is None:
return ''
elif isinstance(self._elements, unicode):
return escape(self._elements, quote=True)
dummy_root = Element('dummy_root')
self.append_to_etree(dummy_root)
return ''.join(tostring(element) for element in dummy_root)
#- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
def _validate_attributes(self, identifier, attributes):
if attributes is None:
return
try:
for name, value in attributes.iteritems():
if not isinstance(value, unicode):
raise InvalidAttributeToIdentifier(
'Expected a string as the attribute value, but got: '
'{0!r} (type {0.__class__.__name__})'.format(value))
self._dialect.validate_attribute(identifier, name, value)
except AttributeError:
raise InvalidAttributesToIdentifier(
'Expected a dict-like attributes object, but '
'got: {0!r} (type {0.__class__.__name__})'.format(attributes))
#- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
def _validate_element(self, element):
if (element is None or
isinstance(element, unicode)):
return
try:
identifier, attributes, elements = element
except (TypeError, ValueError):
raise InvalidElementType(
'Expected an iterable of 3 items, '
'but got: {0!r} (type {0.__class__.__name__})'.format(element))
self._dialect.validate_identifier(identifier)
self._validate_attributes(identifier, attributes)
self._validate_elements(elements)
#- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
def _validate_elements(self, elements):
if (elements is None or
isinstance(elements, unicode)):
return
for element in elements:
self._validate_element(element)
#- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
def validate(self):
try:
self._validate_elements(self._elements)
self._validated = True
except TypeError:
raise InvalidElementsType(
'Expected iterable, but got: {0!r} '
'(type {0.__class__.__name__})'.format(self._elements))
#- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
def elements(self):
if self._validated:
# Require validation again, since this method is returning the
# mutable elements which can be changed by the user
# TODO: Probably it should be better to give the user a view-object
self._validated = False
else:
self.validate()
return self._elements
#- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
__str__ = to_html
<file_sep>/tests/python2/unit/v2/test_dialect.py
# -*- coding: utf-8 -*-
# Import compatibility features
from __future__ import (absolute_import,
division,
print_function,
unicode_literals)
# Import from standard modules
from unittest import TestCase
# Import from PRT modules
from prt.error import PRTError
from prt.v2.dialect import (PRTDialect,
PRTDialectError,
NameMustBeOverriden)
#------------------------------------------------------------------------------#
class TestPRTDialect(TestCase):
#- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
def test_error(self):
self.assertTrue(issubclass(PRTDialectError, PRTError))
self.assertTrue(issubclass(NameMustBeOverriden, PRTDialectError))
#- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
def test_default_properties(self):
self.assertEqual(PRTDialect.NAME, None)
#- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
def test_default_methods(self):
PRTDialect.validate_identifier(None)
PRTDialect.validate_attribute(None, None, None)
self.assertEqual(PRTDialect.identifier_to_html(None), 'div')
self.assertEqual(PRTDialect.identifier_from_html(None), 0)
self.assertEqual(
PRTDialect.attribute_to_html(None, None, None), (None, None))
self.assertEqual(
PRTDialect.attribute_from_html(None, None, None), (None, None))
<file_sep>/tests/python2/unit/test_dialects.py
# -*- coding: utf-8 -*-
# Import compatibility features
from __future__ import (absolute_import,
division,
print_function,
unicode_literals)
# Import from standard modules
from unittest import TestCase
# Import from PRT modules
from prt.version import (PRTVersion,
InvalidVersion)
from prt.v2.dialect import (PRTDialect,
NameMustBeOverriden)
from prt.dialects import (register_dialect,
get_dialect,
InvalidDialectType,
InvalidDialectName,
InvalidDialectVersion)
#------------------------------------------------------------------------------#
class ValidDialect(PRTDialect):
NAME = 'valid'
#------------------------------------------------------------------------------#
class InvalidDialect1(PRTDialect):
pass
#------------------------------------------------------------------------------#
class InvalidDialect2(object):
NAME = 'invalid'
#------------------------------------------------------------------------------#
class TestDialects(TestCase):
#- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
def test_valid_transaction(self):
register_dialect(ValidDialect, PRTVersion.V2)
dialect = get_dialect(ValidDialect.NAME, PRTVersion.V2)
self.assertEqual(dialect, ValidDialect)
#- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
def test_invalid_register(self):
self.assertRaises(InvalidVersion,
register_dialect, ValidDialect, 2.0)
self.assertRaises(InvalidDialectType,
register_dialect, None, PRTVersion.V2)
self.assertRaises(InvalidDialectType,
register_dialect, InvalidDialect2, PRTVersion.V2)
self.assertRaises(NameMustBeOverriden,
register_dialect, InvalidDialect1, PRTVersion.V2)
#- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
def test_invalid_get(self):
self.assertRaises(InvalidVersion,
get_dialect, ValidDialect.NAME, 2.0)
self.assertRaises(InvalidDialectVersion,
get_dialect, None, PRTVersion.V1)
register_dialect(ValidDialect, PRTVersion.V2)
self.assertRaises(InvalidDialectName,
get_dialect, None, PRTVersion.V2)
| 8771de65e46f01dea22cb85c213f75369a2d0632 | [
"Markdown",
"Python",
"Shell"
] | 20 | Python | wegotpop/prt-server | 20a188955dbe2d594ed347275d867077d52c4fd6 | ae98f71fda323597b23b771a10717d95dbfe0e1e |
refs/heads/main | <file_sep># Binary-Hexadecimal-Bandwidth-Calculator--Conversion<file_sep>
/*
In main start with basic code to welcome the user. Prompt the user with choices. In our case main gives the user 4
choices to pick from. This is where we take the user's choice and check to see if the user's choice is valid. We use a
while loop. If the choice is less than 1 or greater than 4 the user will be presented with an error message until the
user chooses a valid selection. Once the user selects a valid choice we break out of main.
I thought the best way to implement my code with the test mode was to have each calculation in its method. This way
when the user enters test mode we can pass values as parameters.
If the user selects choice 1 in main, we break out of main into the binary calculator method. We don't do any
calculations in this method. In this method, we give the user choices of which calculation/conversion they would like to
do. If the user selects a valid choice, which the while loop will error check, for example, choice 1, we break out of the
binary calculator method and choice 1 would break us into the binAddSubDivMul method.
binAddSubDivMul is where we do calculations/conversions. Here we prompt the user to choose 2 binary numbers. Once 2
binary numbers are taken and stored we can begin calculations to give the user a sum, difference, multiplication, and
division answers.
With the above stated this is valid for all calculations. We start in main (Level 1). Give the user choices which are
error checked. Then break out into the method of the user's choice (Level 2). In Level 2 we handle the user's choice of
what specific calculation/conversion they want to do with error checking. Once the user specifies which
calculation/conversion they would like to do we enter Level 3. Level 3 is where we ask the user for string and int
values to calculate and convert to a final result which is printed in the console.
If the user selects test mode at level 1, we break into level 2 where parameter values are passed into level 3 to give
our results
*/
package com.company;
import java.util.Scanner;
public class App {
public static void main(String[] args) {
//Welcome the user and prompt him with choices of the calculations/conversions they would like to calculate.
System.out.println(ConsoleColors.GREEN + "Welcome to calculator/converter program" + ConsoleColors.RESET);
System.out.println(ConsoleColors.GREEN + "Please choose from option 1 - 3 below" + ConsoleColors.RESET);
System.out.println();
System.out.println(ConsoleColors.GREEN + "(1) binary-calculator" + ConsoleColors.RESET);
System.out.println(ConsoleColors.GREEN + "(2) hex-calculator" + ConsoleColors.RESET);
System.out.println(ConsoleColors.GREEN + "(3) bandwidth-calculator" + ConsoleColors.RESET);
System.out.println(ConsoleColors.GREEN + "(4) Test Mode" + ConsoleColors.RESET);
System.out.println();
System.out.print(ConsoleColors.GREEN + "Selection:");
System.out.println();
Scanner reader = new Scanner(System.in);
int userChoiceOperator = reader.nextInt();//Take in the users choice.
binaryCalculator binaryCalculator = new binaryCalculator();
hexCalculator hexCalculator = new hexCalculator();
bandwidthCalculator bandwidthCalculator = new bandwidthCalculator();
testMode testMode = new testMode();
while (userChoiceOperator < 1 || userChoiceOperator > 4) {
//In this while loop we validate the users selection and make sure they choose between 1 and 4.
System.out.println(ConsoleColors.RED + userChoiceOperator + " is not a valid input" + ConsoleColors.RESET);
System.out.println(ConsoleColors.RED + "Please enter a valid selection from the list" + ConsoleColors.RESET);
System.out.print(ConsoleColors.GREEN + "Selection:" + ConsoleColors.RESET);
System.out.println();
userChoiceOperator = reader.nextInt();
}
if (userChoiceOperator == 1) {
binaryCalculator.binaryCalculator();
}
if (userChoiceOperator == 2) {
hexCalculator.hexCalculator();
}
if (userChoiceOperator == 3) {
bandwidthCalculator.bandwidthCalculator();
}
if (userChoiceOperator == 4) {
testMode.testMode();
}
}
}
class testMode {
public static void testMode() {
binaryCalculator binaryCalculator = new binaryCalculator();
hexCalculator hexCalculator = new hexCalculator();
bandwidthCalculator bandwidthCalculator = new bandwidthCalculator();
System.out.println(ConsoleColors.PURPLE + "-------------------------------------------------------------");
System.out.println("All set calculations for binary calculator");
System.out.println("-------------------------------------------------------------");
int bin1 = 101010101;
int bin2 = 101010101;
binaryCalculator.binAddSubDivMul(bin1, bin2);
int x = 10;
binaryCalculator.binToDec(x);
int y = 2;
binaryCalculator.decToBin(y);
System.out.println("-------------------------------------------------------------");
System.out.println("All set calculations for hexadecimal calculator");
System.out.println("-------------------------------------------------------------");
String z = "DAD";
hexCalculator.hexToDec(z);
int w = 170;
hexCalculator.decToHex(w);
String j = "8AB";
String l = "B78";
hexCalculator.hexAddSubDivMul(j, l);
System.out.println("-------------------------------------------------------------");
System.out.println("All set calculations for bandwidth calculator");
System.out.println("-------------------------------------------------------------");
double b = 800;
bandwidthCalculator.dataUnitConverter(b);
double d = 800;
double c = 10;
double g = 1;
bandwidthCalculator.webBandCalc(d, c, g);
double m = 800;
bandwidthCalculator.hostBandCalc(m);
}
}
class binaryCalculator {
public static void binaryCalculator() {
//Welcome the user to binary calculator and prompt him with
// choices of the calculations/conversions they would like to do.
System.out.println(ConsoleColors.GREEN + "-------------------------------------------------------------" + ConsoleColors.RESET);
System.out.println(ConsoleColors.GREEN + "Welcome to Binary Calculator!" + ConsoleColors.RESET);
System.out.println(ConsoleColors.GREEN + "You can choose from the following 3 calculations" + ConsoleColors.RESET);
System.out.println();
System.out.println(ConsoleColors.GREEN + "(1) Binary Calculation—Add, Subtract, Multiply, or Divide" + ConsoleColors.RESET);
System.out.println(ConsoleColors.GREEN + "(2) Convert Binary Value to Decimal Value" + ConsoleColors.RESET);
System.out.println(ConsoleColors.GREEN + "(3) Convert Decimal Value to Binary Value" + ConsoleColors.RESET);
System.out.println();
System.out.print(ConsoleColors.GREEN + "Selection:" + ConsoleColors.RESET);
System.out.println();
Scanner reader = new Scanner(System.in);
int binaryChoice = reader.nextInt();
while (binaryChoice < 1 || binaryChoice > 3) {
//In this while loop we validate the users selection and make sure they choose between 1 and 3.
System.out.println(ConsoleColors.RED + binaryChoice + " is not a valid input" + ConsoleColors.RESET);
System.out.println(ConsoleColors.RED + "Please enter a valid selection from the list" + ConsoleColors.RESET);
System.out.print(ConsoleColors.GREEN + "Selection:" + ConsoleColors.RESET);
System.out.println();
binaryChoice = reader.nextInt();
}
if (binaryChoice == 1) {
int bin1 = 0;
int bin2 = 0;
binAddSubDivMul(bin1, bin2);
}
if (binaryChoice == 2) {
int x = 0;
binToDec(x);
}
if (binaryChoice == 3) {
int y = 0;
decToBin(y);
}
}
public static void binAddSubDivMul(int binX, int binY) {
//Calculations to Add, Subtract, Multiply, and Divide binary numbers.
if (binX == 0 && binY == 0) {
Scanner reader = new Scanner(System.in);
String firstBin, secondBin;
int iParseOne, iParseTwo;
System.out.println(ConsoleColors.GREEN + "Enter First Binary Number");
firstBin = reader.next();
System.out.println("Enter Second Binary Number");
secondBin = reader.next();
// Convert Binary numbers to decimal
iParseOne = Integer.parseInt(firstBin, 2);
iParseTwo = Integer.parseInt(secondBin, 2);
System.out.println("Sum = " + Integer.toBinaryString(iParseOne + iParseTwo));
System.out.println("Difference = " + Integer.toBinaryString(iParseOne - iParseTwo));
System.out.println("Multiplication = " + Integer.toBinaryString(iParseOne * iParseTwo));
System.out.println("Division = " + Integer.toBinaryString(iParseOne / iParseTwo));
System.exit(0);
} else if (binX == 101010101 && binY == 101010101) {
String firstBin = Integer.toString(binX);
String secondBin = Integer.toString(binX);
int iParseOne, iParseTwo;
iParseOne = Integer.parseInt(firstBin, 2);
iParseTwo = Integer.parseInt(secondBin, 2);
System.out.println("Sum of 101010101 + 101010101 = " + Integer.toBinaryString(iParseOne + iParseTwo));
System.out.println("Difference of 101010101 - 101010101 = " + Integer.toBinaryString(iParseOne - iParseTwo));
System.out.println("Multiplication of 101010101 * 101010101 = " + Integer.toBinaryString(iParseOne * iParseTwo));
System.out.println("Division of 101010101 / 101010101 = " + Integer.toBinaryString(iParseOne / iParseTwo));
}
}
public static void binToDec(int testX) {
//Calculate binary to decimal
if (testX == 0) {
Scanner reader = new Scanner(System.in);
System.out.println(ConsoleColors.GREEN + "Binary number you would like to convert");
System.out.print("Number:");
while (true) {
int binConvert = reader.nextInt();
int decimal = 0;
int n = 0;
while (binConvert != 0) {
if (binConvert % 10 > 1) {
System.out.println("This is not a binary number");
System.out.println("Binary number you would like to convert");
System.out.print("Number:");
binConvert = reader.nextInt();
} else {
int temp = binConvert % 10;
decimal += temp * Math.pow(2, n);
binConvert = binConvert / 10;
n++;
}
}
System.out.print("Converted Value:" + decimal);
System.exit(0);
}
} else if (testX == 10) {
int binConvert = testX;
int decimal = 0;
int n = 0;
while (binConvert != 0) {
int temp = binConvert % 10;
decimal += temp * Math.pow(2, n);
binConvert = binConvert / 10;
n++;
}
System.out.println("Binary to decimal of 10 is " + decimal);
}
}
public static void decToBin(int testY) {
//Calculate decimal to binary
if (testY == 0) {
Scanner reader = new Scanner(System.in);
System.out.println(ConsoleColors.GREEN + "Decimal number you would like to convert");
System.out.print("Number:");
int decConvert = reader.nextInt();
int binary[] = new int[40];
int index = 0;
while (decConvert > 0) {
binary[index++] = decConvert % 2;
decConvert = decConvert / 2;
}
for (int i = index - 1; i >= 0; i--) {
System.out.print(binary[i]);
}
System.out.println();
System.exit(0);
} else if (testY == 2) {
int decConvert = testY;
int binary[] = new int[40];
int index = 0;
while (decConvert > 0) {
binary[index++] = decConvert % 2;
decConvert = decConvert / 2;
}
System.out.print("Decimal to binary of 2 is ");
for (int i = index - 1; i >= 0; i--) {
System.out.print(binary[i]);
}
System.out.println();
}
}
}
class hexCalculator {
public static void hexCalculator() {
//Welcome the user to hexadecimal calculator and prompt him with
// choices of the calculations/conversions they would like to do.
System.out.println(ConsoleColors.GREEN + "-------------------------------------------------------------" + ConsoleColors.RESET);
System.out.println(ConsoleColors.GREEN + "Welcome to Hexadecimal Calculator!" + ConsoleColors.RESET);
System.out.println(ConsoleColors.GREEN + "You can choose from the following 3 calculations" + ConsoleColors.RESET);
System.out.println();
System.out.println(ConsoleColors.GREEN + "(1) Hexadecimal Calculation—Add, Subtract, Multiply, or Divide" + ConsoleColors.RESET);
System.out.println(ConsoleColors.GREEN + "(2) Convert Hexadecimal Value to Decimal Value" + ConsoleColors.RESET);
System.out.println(ConsoleColors.GREEN + "(3) Convert Decimal Value to Hexadecimal Value" + ConsoleColors.RESET);
System.out.println();
System.out.print(ConsoleColors.GREEN + "Selection:" + ConsoleColors.RESET);
System.out.println();
Scanner reader = new Scanner(System.in);
int hexadecimalChoice = reader.nextInt();
while (hexadecimalChoice < 1 || hexadecimalChoice > 3) {
//In this while loop we validate the users selection and make sure they choose between 1 and 3.
System.out.println(ConsoleColors.RED + hexadecimalChoice + " is not a valid input" + ConsoleColors.RESET);
System.out.println(ConsoleColors.RED + "Please enter a valid selection from the list" + ConsoleColors.RESET);
System.out.print(ConsoleColors.GREEN + "Selection:" + ConsoleColors.RESET);
System.out.println();
hexadecimalChoice = reader.nextInt();
}
if (hexadecimalChoice == 1) {
String j = "";
String l = "";
hexAddSubDivMul(j, l);
}
if (hexadecimalChoice == 2) {
String x = "";
hexToDec(x);
}
if (hexadecimalChoice == 3) {
int y = 0;
decToHex(y);
}
}
public static void hexAddSubDivMul(String fString, String sString) {
if (fString == "" || sString == "") {
String firstHex, secondHex;
int num1, num2, sum, difference, multiplication, division;
Scanner reader = new Scanner(System.in);
System.out.println(ConsoleColors.GREEN + "Enter your first Number:");
firstHex = reader.nextLine();
System.out.println("Enter your second Number:");
secondHex = reader.nextLine();
num1 = Integer.parseInt(firstHex, 16);
num2 = Integer.parseInt(secondHex, 16);
sum = num1 + num2;
difference = num2 - num1;
multiplication = num1 * num2;
division = num1 / num2;
String ans1 = Integer.toHexString(sum);
String ans2 = Integer.toHexString(difference);
String ans3 = Integer.toHexString(multiplication);
String ans4 = Integer.toHexString(division);
System.out.println("Sum is " + ans1);
System.out.println("Difference is " + ans2);
System.out.println("Multiplication is " + ans3);
System.out.println("Division is " + ans4);
} else if (fString == "8AB" || sString == "B78") {
String firstHex, secondHex;
int num1, num2, sum, difference, multiplication, division;
firstHex = fString;
secondHex = sString;
num1 = Integer.parseInt(firstHex, 16);
num2 = Integer.parseInt(secondHex, 16);
sum = num1 + num2;
difference = num2 - num1;
multiplication = num1 * num2;
division = num1 / num2;
String ans1 = Integer.toHexString(sum);
String ans2 = Integer.toHexString(difference);
String ans3 = Integer.toHexString(multiplication);
String ans4 = Integer.toHexString(division);
System.out.println("Sum is " + ans1);
System.out.println("Difference is " + ans2);
System.out.println("Multiplication is " + ans3);
System.out.println("Division is " + ans4);
}
}
public static void hexToDec(String xTest) {
if (xTest == "") {
Scanner reader = new Scanner(System.in);
System.out.print(ConsoleColors.GREEN + "Enter a hexadecimal number you would like to convert: ");
String base = "0123456789ABCDEF";
String hex = reader.nextLine();
hex = hex.toUpperCase();
int num = 0;
for (int i = 0; i < hex.length(); i++) {
char ch = hex.charAt(i);
int n = base.indexOf(ch);
num = 16 * num + n;
}
System.out.println("Converted hexadecimal to decimal: " + num);
} else if (xTest == "DAD") {
String base = "0123456789ABCDEF";
String hex = xTest;
hex = hex.toUpperCase();
int num = 0;
for (int i = 0; i < hex.length(); i++) {
char ch = hex.charAt(i);
int n = base.indexOf(ch);
num = 16 * num + n;
}
System.out.println("Converted hexadecimal to decimal of DAD is " + num);
}
}
public static void decToHex(int yTest) {
if (yTest == 0) {
Scanner reader = new Scanner(System.in);
System.out.print(ConsoleColors.GREEN + "Enter a decimal number you would like to convert: ");
int dec = reader.nextInt();
int rem;
String str2 = "";
char hex[] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'};
while (dec > 0) {
rem = dec % 16;
str2 = hex[rem] + str2;
dec = dec / 16;
}
System.out.println("Converted Decimal to hexadecimal: " + str2);
} else if (yTest == 170) {
int dec = yTest;
int rem;
String str2 = "";
char hex[] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'};
while (dec > 0) {
rem = dec % 16;
str2 = hex[rem] + str2;
dec = dec / 16;
}
System.out.println("Converted Decimal to hexadecimal of 170 is " + str2);
}
}
}
class bandwidthCalculator {
public static void bandwidthCalculator() {
//Welcome the user to bandwidth calculator and prompt him with
// choices of the calculations/conversions they would like to do.
System.out.println(ConsoleColors.GREEN + "-------------------------------------------------------------" + ConsoleColors.RESET);
System.out.println(ConsoleColors.GREEN + "Welcome to Bandwidth Calculator!" + ConsoleColors.RESET);
System.out.println(ConsoleColors.GREEN + "You can choose from the following 3 calculations" + ConsoleColors.RESET);
System.out.println();
System.out.println(ConsoleColors.GREEN + "(1) Data Unit Converter" + ConsoleColors.RESET);
System.out.println(ConsoleColors.GREEN + "(2) Website Bandwidth Calculator" + ConsoleColors.RESET);
System.out.println(ConsoleColors.GREEN + "(3) Hosting Bandwidth Converter" + ConsoleColors.RESET);
System.out.println();
System.out.print(ConsoleColors.GREEN + "Selection:" + ConsoleColors.RESET);
System.out.println();
Scanner reader = new Scanner(System.in);
int bandwidthChoice = reader.nextInt();
while (bandwidthChoice < 1 || bandwidthChoice > 3) {
//In this while loop we validate the users selection and make sure they choose between 1 and 3.
System.out.println(ConsoleColors.RED + bandwidthChoice + " is not a valid input" + ConsoleColors.RESET);
System.out.println(ConsoleColors.RED + "Please enter a valid selection from the list" + ConsoleColors.RESET);
System.out.print(ConsoleColors.GREEN + "Selection:" + ConsoleColors.RESET);
System.out.println();
bandwidthChoice = reader.nextInt();
}
if (bandwidthChoice == 1) {
double b = 0;
dataUnitConverter(b);
}
if (bandwidthChoice == 2) {
double d = 0;
double c = 0;
double g = 0;
webBandCalc(d, c, g);
}
if (bandwidthChoice == 3) {
double m = 0;
hostBandCalc(m);
}
}
public static void dataUnitConverter(double bTest) {
if (bTest == 0) {
System.out.println(ConsoleColors.GREEN + "Please select a unit you would like to convert");
System.out.println();
System.out.println("(1) bits (b)");
System.out.println("(2) kilobits (kb)");
System.out.println("(3) megabits (mb)");
System.out.println("(4) gigabits (gb)");
System.out.println("(5) terabits (tb)");
System.out.println("(6) Bytes (B)");
System.out.println("(7) Kilobytes (KB)");
System.out.println("(8) Megabytes (MB)");
System.out.println("(9) Gigabytes (GB)");
System.out.println("(10) Terabytes (TB)");
System.out.print("Selection:");
Scanner reader = new Scanner(System.in);
double selection = reader.nextInt();
while (selection < 1 || selection > 10) {
//In this while loop we validate the users selection and make sure they choose between 1 and 4.
System.out.println(selection + " is not a valid input");
System.out.println("Please enter a valid selection from the list");
System.out.print("Selection:");
System.out.println();
selection = reader.nextInt();
}
if (selection == 1) {
System.out.println("Please type in value in bits to convert to all conversions");
System.out.print("Selection:");
double value = reader.nextInt();
double size_bit = value;
double size_kilobits = size_bit / 1000;
double size_megabit = size_kilobits / 1000;
double size_gigabit = size_megabit / 1000;
double size_terabit = size_gigabit / 1000;
double size_Byte = size_bit / 8;
double size_kilobytes = size_bit / 8000;
double size_megabytes = size_kilobytes / 1000;
double size_gigabytes = size_megabytes / 1000;
double size_terabytes = size_gigabytes / 1000;
System.out.println("-------------------------------------------------------------");
System.out.println(size_kilobits + " (kb)");
System.out.println(size_megabit + " (mb)");
System.out.println(size_gigabit + " (gb)");
System.out.println(size_terabit + " (tb)");
System.out.println(size_Byte + " (B)");
System.out.println(size_kilobytes + " (KB)");
System.out.println(size_megabytes + " (MB)");
System.out.println(size_gigabytes + " (GB)");
System.out.println(size_terabytes + " (TB)");
System.out.println("-------------------------------------------------------------");
}
if (selection == 2) {
System.out.println("Please type in value in kilobits to convert to all conversions");
System.out.print("Selection:");
double value = reader.nextInt();
double size_kilobit = value;
double size_bit = size_kilobit * 1000;
double size_megabit = size_kilobit / 1000;
double size_gigabit = size_megabit / 1000;
double size_terabit = size_gigabit / 1000;
double size_Byte = size_bit / 8;
double size_kilobytes = size_bit / 8000;
double size_megabytes = size_kilobytes / 1000;
double size_gigabytes = size_megabytes / 1000;
double size_terabytes = size_gigabytes / 1000;
System.out.println("-------------------------------------------------------------");
System.out.println(size_bit + " (b)");
System.out.println(size_megabit + " (mb)");
System.out.println(size_gigabit + " (gb)");
System.out.println(size_terabit + " (tb)");
System.out.println(size_Byte + " (B)");
System.out.println(size_kilobytes + " (KB)");
System.out.println(size_megabytes + " (MB)");
System.out.println(size_gigabytes + " (GB)");
System.out.println(size_terabytes + " (TB)");
System.out.println("-------------------------------------------------------------");
}
if (selection == 3) {
System.out.println("Please type in value in megabits to convert to all conversions");
System.out.print("Selection:");
double value = reader.nextInt();
double size_megabit = value;
double size_bit = size_megabit * 1e+6;
double size_kilobit = size_megabit * 1000;
double size_gigabit = size_megabit / 1000;
double size_terabit = size_gigabit / 1000;
double size_Byte = size_bit / 8;
double size_kilobytes = size_bit / 8000;
double size_megabytes = size_kilobytes / 1000;
double size_gigabytes = size_megabytes / 1000;
double size_terabytes = size_gigabytes / 1000;
System.out.println("-------------------------------------------------------------");
System.out.println(size_bit + " (b)");
System.out.println(size_kilobit + " (kb)");
System.out.println(size_gigabit + " (gb)");
System.out.println(size_terabit + " (tb)");
System.out.println(size_Byte + " (B)");
System.out.println(size_kilobytes + " (KB)");
System.out.println(size_megabytes + " (MB)");
System.out.println(size_gigabytes + " (GB)");
System.out.println(size_terabytes + " (TB)");
System.out.println("-------------------------------------------------------------");
}
if (selection == 4) {
System.out.println("Please type in value in gigabits to convert to all conversions");
System.out.print("Selection:");
double value = reader.nextInt();
double size_gigabits = value;
double size_bit = size_gigabits * 1e+9;
double size_kilobit = size_bit / 1000;
double size_megabit = size_kilobit / 1000;
double size_terabit = size_megabit / 1e+6;
double size_Byte = size_bit / 8;
double size_kilobytes = size_bit / 8000;
double size_megabytes = size_kilobytes / 1000;
double size_gigabytes = size_megabytes / 1000;
double size_terabytes = size_gigabytes / 1000;
System.out.println("-------------------------------------------------------------");
System.out.println(size_bit + " (b)");
System.out.println(size_kilobit + " (kb)");
System.out.println(size_megabit + " (mb)");
System.out.println(size_terabit + " (tb)");
System.out.println(size_Byte + " (B)");
System.out.println(size_kilobytes + " (KB)");
System.out.println(size_megabytes + " (MB)");
System.out.println(size_gigabytes + " (GB)");
System.out.println(size_terabytes + " (TB)");
System.out.println("-------------------------------------------------------------");
}
if (selection == 5) {
System.out.println("Please type in value in gigabits to convert to all conversions");
System.out.print("Selection:");
double value = reader.nextInt();
double size_terabits = value;
double size_bit = size_terabits * 1e+12;
double size_kilobit = size_bit / 1000;
double size_megabit = size_kilobit / 1000;
double size_gigabit = size_megabit / 1000;
double size_Byte = size_bit / 8;
double size_kilobytes = size_bit / 8000;
double size_megabytes = size_kilobytes / 1000;
double size_gigabytes = size_megabytes / 1000;
double size_terabytes = size_gigabytes / 1000;
System.out.println("-------------------------------------------------------------");
System.out.println(size_bit + " (b)");
System.out.println(size_kilobit + " (kb)");
System.out.println(size_megabit + " (mb)");
System.out.println(size_gigabit + " (gb)");
System.out.println(size_Byte + " (B)");
System.out.println(size_kilobytes + " (KB)");
System.out.println(size_megabytes + " (MB)");
System.out.println(size_gigabytes + " (GB)");
System.out.println(size_terabytes + " (TB)");
System.out.println("-------------------------------------------------------------");
}
if (selection == 6) {
System.out.println("Please type in value in bytes to convert to all conversions");
System.out.print("Selection:");
double value = reader.nextInt();
double size_byte = value;
double size_bit = size_byte * 8;
double size_kilobits = size_bit / 1000;
double size_megabit = size_kilobits / 1000;
double size_gigabit = size_megabit / 1000;
double size_terabit = size_gigabit / 1000;
double size_kilobytes = size_byte / 1000;
double size_megabytes = size_kilobytes / 1000;
double size_gigabytes = size_megabytes / 1000;
double size_terabytes = size_gigabytes / 1000;
System.out.println("-------------------------------------------------------------");
System.out.println(size_bit + " (b)");
System.out.println(size_kilobits + " (kb)");
System.out.println(size_megabit + " (mb)");
System.out.println(size_gigabit + " (gb)");
System.out.println(size_terabit + " (tb)");
System.out.println(size_kilobytes + " (KB)");
System.out.println(size_megabytes + " (MB)");
System.out.println(size_gigabytes + " (GB)");
System.out.println(size_terabytes + " (TB)");
System.out.println("-------------------------------------------------------------");
}
if (selection == 7) {
System.out.println("Please type in value in Kilobytes to convert to all conversions");
System.out.print("Selection:");
double value = reader.nextInt();
double size_kilobytes = value;
double size_bit = size_kilobytes * 8000;
double size_kilobits = size_bit / 1000;
double size_megabit = size_kilobits / 1000;
double size_gigabit = size_megabit / 1000;
double size_terabit = size_gigabit / 1000;
double size_byte = size_kilobytes * 1000;
double size_megabytes = size_kilobytes / 1000;
double size_gigabytes = size_megabytes / 1000;
double size_terabytes = size_gigabytes / 1000;
System.out.println("-------------------------------------------------------------");
System.out.println(size_bit + " (b)");
System.out.println(size_kilobits + " (kb)");
System.out.println(size_megabit + " (mb)");
System.out.println(size_gigabit + " (gb)");
System.out.println(size_terabit + " (tb)");
System.out.println(size_byte + " (B)");
System.out.println(size_megabytes + " (MB)");
System.out.println(size_gigabytes + " (GB)");
System.out.println(size_terabytes + " (TB)");
System.out.println("-------------------------------------------------------------");
}
if (selection == 8) {
System.out.println("Please type in value in megabytes to convert to all conversions");
System.out.print("Selection:");
double value = reader.nextInt();
double size_megabyte = value;
double size_bit = size_megabyte * 8e+6;
double size_kilobits = size_bit / 1000;
double size_megabit = size_kilobits / 1000;
double size_gigabit = size_megabit / 1000;
double size_terabit = size_gigabit / 1000;
double size_byte = size_megabyte * 1e+6;
double size_kilobyte = size_byte / 1000;
double size_gigabytes = size_megabyte / 1000;
double size_terabytes = size_gigabytes / 1000;
System.out.println("-------------------------------------------------------------");
System.out.println(size_bit + " (b)");
System.out.println(size_kilobits + " (kb)");
System.out.println(size_megabit + " (mb)");
System.out.println(size_gigabit + " (gb)");
System.out.println(size_terabit + " (tb)");
System.out.println(size_byte + " (B)");
System.out.println(size_kilobyte + " (KB)");
System.out.println(size_gigabytes + " (GB)");
System.out.println(size_terabytes + " (TB)");
System.out.println("-------------------------------------------------------------");
}
if (selection == 9) {
System.out.println("Please type in value in gigabyte to convert to all conversions");
System.out.print("Selection:");
double value = reader.nextInt();
double size_gigabyte = value;
double size_bit = size_gigabyte * 8e+9;
double size_kilobits = size_bit / 1000;
double size_megabit = size_kilobits / 1000;
double size_gigabit = size_megabit / 1000;
double size_terabit = size_gigabit / 1000;
double size_byte = size_gigabyte * 1e+9;
double size_kilobyte = size_byte / 1000;
double size_megabyte = size_gigabyte * 1000;
double size_terabytes = size_gigabyte / 1000;
System.out.println("-------------------------------------------------------------");
System.out.println(size_bit + " (b)");
System.out.println(size_kilobits + " (kb)");
System.out.println(size_megabit + " (mb)");
System.out.println(size_gigabit + " (gb)");
System.out.println(size_terabit + " (tb)");
System.out.println(size_byte + " (B)");
System.out.println(size_kilobyte + " (KB)");
System.out.println(size_megabyte + " (MB)");
System.out.println(size_terabytes + " (TB)");
System.out.println("-------------------------------------------------------------");
}
if (selection == 10) {
System.out.println("Please type in value in terabytes to convert to all conversions");
System.out.print("Selection:");
double value = reader.nextInt();
double size_terabyte = value;
double size_bit = size_terabyte * 8e+12;
double size_kilobits = size_bit / 1000;
double size_megabit = size_kilobits / 1000;
double size_gigabit = size_megabit / 1000;
double size_terabit = size_gigabit / 1000;
double size_byte = size_terabyte * 1e+12;
double size_kilobyte = size_byte / 1000;
double size_megabyte = size_terabyte * 1e+6;
double size_gigabyte = size_terabyte * 1000;
System.out.println("-------------------------------------------------------------");
System.out.println(size_bit + " (b)");
System.out.println(size_kilobits + " (kb)");
System.out.println(size_megabit + " (mb)");
System.out.println(size_gigabit + " (gb)");
System.out.println(size_terabit + " (tb)");
System.out.println(size_byte + " (B)");
System.out.println(size_kilobyte + " (KB)");
System.out.println(size_megabyte + " (MB)");
System.out.println(size_gigabyte + " (GB)");
System.out.println("-------------------------------------------------------------");
}
} else if (bTest == 800) {
double size_byte = bTest;
double size_bit = size_byte * 8;
double size_kilobits = size_bit / 1000;
double size_megabit = size_kilobits / 1000;
double size_gigabit = size_megabit / 1000;
double size_terabit = size_gigabit / 1000;
double size_kilobytes = size_byte / 1000;
double size_megabytes = size_kilobytes / 1000;
double size_gigabytes = size_megabytes / 1000;
double size_terabytes = size_gigabytes / 1000;
System.out.println(bTest + " Converts to the following values:");
System.out.println(size_bit + " (b)");
System.out.println(size_kilobits + " (kb)");
System.out.println(size_megabit + " (mb)");
System.out.println(size_gigabit + " (gb)");
System.out.println(size_terabit + " (tb)");
System.out.println(size_kilobytes + " (KB)");
System.out.println(size_megabytes + " (MB)");
System.out.println(size_gigabytes + " (GB)");
System.out.println(size_terabytes + " (TB)");
}
}
public static void webBandCalc(double dTest, double cTest, double gTest) {
if (dTest == 0 && cTest == 0 && gTest == 0) {
Scanner reader = new Scanner(System.in);
System.out.print(ConsoleColors.GREEN + "Page views:");
double pView = reader.nextInt();
System.out.print("Average Page Size:");
double avePageSize = reader.nextInt();
System.out.print("redundancy factor:");
double redundancy = reader.nextInt();
double bNeeded = pView * avePageSize * redundancy;
double bFinal = bNeeded * 30.4375;
double bNed = bFinal / 328.725;
System.out.println("Bandwidth needed is " + bNed + " Mbits/s or " + bFinal + " GB per month.");
} else if (dTest == 800 && cTest == 10 && gTest == 1) {
double pView = dTest;
double avePageSize = cTest;
double redundancy = gTest;
double bNeeded = pView * avePageSize * redundancy;
double bFinal = bNeeded * 30.4375;
double bNed = bFinal / 328.725;
System.out.println("Bandwidth needed is " + bNed + " Mbits/s or " + bFinal + " GB per month.");
}
}
public static void hostBandCalc(double mConv) {
if (mConv == 0) {
System.out.println(ConsoleColors.GREEN + "Please type in value in bytes to gigabytes to get the conversion in megabits");
System.out.print("Selection:");
Scanner reader = new Scanner(System.in);
double value = reader.nextInt();
double mb = value * 0.0031;
System.out.println(mb + " Mbit/s");
} else if (mConv == 800) {
double value = mConv;
double mb = value * 0.0031;
System.out.println("800 bytes is " + mb + " Mbit/s");
}
}
}
class ConsoleColors {
// Reset
public static final String RESET = "\033[0m"; // Text Reset
// Regular Colors
public static final String BLACK = "\033[0;30m"; // BLACK
public static final String RED = "\033[0;31m"; // RED
public static final String GREEN = "\033[0;32m"; // GREEN
public static final String YELLOW = "\033[0;33m"; // YELLOW
public static final String BLUE = "\033[0;34m"; // BLUE
public static final String PURPLE = "\033[0;35m"; // PURPLE
public static final String CYAN = "\033[0;36m"; // CYAN
public static final String WHITE = "\033[0;37m"; // WHITE
}
| 12dbe69be9fae3c3510a75ddd10fc6a9d20b1109 | [
"Markdown",
"Java"
] | 2 | Markdown | ArmeenF/Binary-Hexadecimal-Bandwidth-Calculator--Conversion | 799442d41a136ae6dc4b483058f2b1c111931809 | 699eb5228e2648d351924573cb18803a4f33c7a8 |
refs/heads/master | <file_sep>
/*
Класс, как и функция, является объектом. Статические свойства класса LocalStorageService – это свойства непосредственно User, то есть доступные из него «через точку».
Для их объявления используется ключевое слово static.
Мы можем использовать функцию static если в ней мы не используем контекст класса (this).
*/
class LocalStorageServicePar {
// получение name из Local Storage
getCount() {
return localStorage.getItem('count');
}
// задание name из Local Storage
setStartCount(count) {
return localStorage.setItem('count', count);
}
// удаление name из Local Storage
updateCount() {
const count = parseInt(this.getCount()) + 1;
this.setStartCount(count);
}
}
class LocalStorageServiceChild extends LocalStorageServicePar {
constructor() {
super()
}
getCountChild() {
return this.getCount();
}
setStartCountChild(count) {
return this.setStartCount(count);
}
updateCountChild() {
return this.updateCount();
}
}
const obj = new LocalStorageServiceChild();
obj.setStartCountChild(1);
console.log(obj.getCountChild());
obj.updateCountChild();
console.log(obj.getCountChild());
<file_sep>/*
Написать select, куда динамически будет добавляться options со значением соответствующей страны.
Список стран можно получить отправив GET запрос сюда:
https://gist.githubusercontent.com/ebaranov/41bf38fdb1a2cb19a781/raw/fb097a60427717b262d5058633590749f366bd80/gistfile1.json
Так же нужно перевести ответ в json формат.
Что должно быть:
- класс родитель
- дочерний класс
- в запросах использовать Promise, async/await
*/
class Request {
constructor() {
this.url = "https://gist.githubusercontent.com/ebaranov/41bf38fdb1a2cb19a781/raw/fb097a60427717b262d5058633590749f366bd80/gistfile1.json";
this.xmlhttp = new XMLHttpRequest();
}
open() {
return this.xmlhttp.open("GET", this.url, true);
}
send() {
return new Promise(resolve => {
this.xmlhttp.onload = function () {
if (this.readyState == 4 && this.status == 200) {
const countries = JSON.parse(this.responseText).countries;
resolve(countries);
}
};
this.open();
this.xmlhttp.send()
});
}
}
class RenderInDOM extends Request {
get selectElem() {
return document.getElementById('countries-select');
}
createOptionElem() {
return document.createElement('option');
}
async getCountriesRequest() {
return await this.send();
}
render() {
this.getCountriesRequest().then(data => {
data.forEach(el => {
const optionElem = this.createOptionElem();
optionElem.value = el.country;
optionElem.text = el.country;
this.selectElem.appendChild(optionElem);
});
});
}
}
const renderInDOM = new RenderInDOM();
renderInDOM.render();<file_sep>
/*
Promise (обычно их так и называют «промисы») – предоставляют удобный способ организации асинхронного кода.
Promise – это специальный объект, который содержит своё состояние. Вначале pending («ожидание»), затем – одно из: fulfilled («выполнено успешно») или rejected («выполнено с ошибкой»).
*/
const promise = new Promise(function(resolve, reject) {
// Эта функция будет вызвана автоматически
// В ней можно делать любые асинхронные операции,
// А когда они завершатся — нужно вызвать одно из:
// resolve(результат) при успешном выполнении
// reject(ошибка) при ошибке
setTimeout(() => {
resolve('1');
}, 1000)
})
.then((data) => {
console.log(data);
return new Promise(function(resolve, reject) {
setTimeout(() => {
reject(2);
}, 1000)
})
})
.then((data) => {
console.log(data);
return '3'
})
.then((data) => {
console.log(data);
})
.catch(() => {
return 'Error'
}).then(data => {
console.log('123', data);
}); | 72ef4f0e1bdd8cd6e4ccb1efe3469eaf35eb2053 | [
"JavaScript"
] | 3 | JavaScript | OrionPro/lesson1 | 3c0a8ca33d4159fda5ba6266f54d31ce4526b7f2 | de134f6eac2bc53b5cdcb08252e315309f2a650f |
refs/heads/master | <repo_name>ajmal017/interactivebrokers_fundamental-data<file_sep>/account.py
# TODO: check account positions, see https://bit.ly/33Ssy6W
<file_sep>/REAMDE.md
# Interactive Brokers Connector
This repository contains helpful snippets to connect to [Interactive Brokers](https://www.interactivebrokers.com).
## Installation
- Install [IB Gateway](https://www.interactivebrokers.eu/de/?f=16457).
<file_sep>/ib_insync_sample.py
# TODO: Fetch data with ib_insync, see https://github.com/erdewit/ib_insync
from ib_insync import IB, Forex, util
util.startLoop() # uncomment this line when in a notebook
ib = IB()
ib.connect('127.0.0.1', 4001, clientId=2)
contract = Forex('EURUSD')
bars = ib.reqHistoricalData(
contract, endDateTime='', durationStr='30 D',
barSizeSetting='1 hour', whatToShow='MIDPOINT', useRTH=True)
# convert to pandas dataframe:
df = util.df(bars)
print(df)
ib.disconnect()
from pyspark.sql import SparkSession
import os
# warehouseLocation = 'hdfs://localhost:9000/warehouse'
warehouseLocation = 'hdfs://localhost:8020/user/hive/warehouse'
os.environ["HADOOP_USER_NAME"] = "root"
spark = SparkSession.builder \
.appName('appName') \
.config('spark.driver.port', 8080) \
.config("spark.sql.warehouse.dir", warehouseLocation) \
.config('spark.driver.host', 'http://127.0.0.1:58896/api/v1/namespaces/default/services/spark:spark-master-6d4984666-s68v2:8080/proxy/#/') \
.config('spark.sql.hive.thriftServer.singleSession', True) \
.enableHiveSupport() \
.getOrCreate()
spark
spark.sql("CREATE TABLE IF NOT EXISTS src (key INT, value STRING) USING hive")
spark.sql("LOAD DATA LOCAL INPATH 'sample.json' INTO TABLE src")
<file_sep>/reqMktData.py
# To request market data see: https://bit.ly/3nIQaCz
<file_sep>/trading.py
# TODO: execute trade, see: https://bit.ly/3nEnNWd
| 9ae7c81c02510f43abe810b0a3f838b99b39300b | [
"Markdown",
"Python"
] | 5 | Python | ajmal017/interactivebrokers_fundamental-data | ec27e85d448708e7d5a5e390ff1343b2af3d6725 | e1c6bd62af73fe2b2d61af83f83907c0fb804097 |
refs/heads/main | <repo_name>vianhazman/optimus<file_sep>/plugin/plugin.go
package plugin
import (
"context"
"fmt"
"io/ioutil"
"os"
"os/exec"
"path/filepath"
"runtime"
"strings"
"github.com/pkg/errors"
"github.com/odpf/optimus/plugin/hook"
"github.com/odpf/optimus/models"
"github.com/hashicorp/go-hclog"
"github.com/hashicorp/go-plugin"
"github.com/odpf/optimus/plugin/task"
)
const (
// ProtocolVersion is the version that must match between core
// and plugins. This should be bumped whenever a change happens in
// one or the other that makes it so that they can't safely communicate.
// This could be adding a new interface value, methods, etc.
ProtocolVersion = 1
// Magic values
// should always remain constant
MagicCookieKey = "OP_PLUGIN_MAGIC_COOKIE"
MagicCookieValue = "<KEY>"
)
var (
// Supported plugin types
TaskPluginName = models.InstanceTypeTask.String()
HookPluginName = models.InstanceTypeHook.String()
)
func Initialize(pluginLogger hclog.Logger) error {
discoveredPlugins, err := DiscoverPlugins(pluginLogger)
if err != nil {
return errors.Wrap(err, "DiscoverPlugins")
}
pluginLogger.Debug(fmt.Sprintf("discovering plugins(%d)...",
len(discoveredPlugins[TaskPluginName])+len(discoveredPlugins[HookPluginName])))
// handshakeConfigs are used to just do a basic handshake between
// a plugin and host. If the handshake fails, a user friendly error is shown.
// This prevents users from executing bad plugins or executing a plugin
// directory. It is a UX feature, not a security feature.
var handshakeConfig = plugin.HandshakeConfig{
ProtocolVersion: ProtocolVersion,
MagicCookieKey: MagicCookieKey,
MagicCookieValue: MagicCookieValue,
}
// pluginMap is the map of plugins we can dispense.
var pluginMap = map[string]plugin.Plugin{
TaskPluginName: task.NewPluginClient(),
HookPluginName: hook.NewPluginClient(),
}
for pluginType, pluginPaths := range discoveredPlugins {
for _, pluginPath := range pluginPaths {
// We're a host! Start by launching the plugin process.
client := plugin.NewClient(&plugin.ClientConfig{
HandshakeConfig: handshakeConfig,
Plugins: pluginMap,
Cmd: exec.Command(pluginPath),
Managed: true,
AllowedProtocols: []plugin.Protocol{plugin.ProtocolGRPC},
Logger: pluginLogger,
})
// Connect via GRPC
rpcClient, err := client.Client()
if err != nil {
return errors.Wrapf(err, "client.Client(): %s", pluginPath)
}
// Request the plugin
raw, err := rpcClient.Dispense(pluginType)
if err != nil {
return errors.Wrapf(err, "rpcClient.Dispense: %s", pluginPath)
}
switch pluginType {
case TaskPluginName:
taskClient := raw.(models.TaskPlugin)
taskSchema, err := taskClient.GetTaskSchema(context.Background(), models.GetTaskSchemaRequest{})
if err != nil {
return errors.Wrapf(err, "taskClient.GetTaskSchema: %s", pluginPath)
}
pluginLogger.Debug("tested plugin communication for task", taskSchema.Name)
{
// update name, will be later used for filtering secrets
taskGRPCClient := raw.(*task.GRPCClient)
taskGRPCClient.Name = taskSchema.Name
}
if err := models.TaskRegistry.Add(taskClient); err != nil {
return errors.Wrapf(err, "models.TaskRegistry.Add: %s", pluginPath)
}
case HookPluginName:
hookClient := raw.(models.HookPlugin)
hookSchema, err := hookClient.GetHookSchema(context.Background(), models.GetHookSchemaRequest{})
if err != nil {
return errors.Wrapf(err, "hookClient.GetTaskSchema: %s", pluginPath)
}
pluginLogger.Debug("tested plugin communication for hook ", hookSchema.Name)
if err := models.HookRegistry.Add(hookClient); err != nil {
return errors.Wrapf(err, "models.HookRegistry.Add: %s", pluginPath)
}
default:
return errors.Wrapf(err, "unsupported plugin type: %s", pluginType)
}
}
}
return nil
}
// DiscoverPlugins look for plugin binaries in following folders
// order to search is top to down
// ./
// <exec>/
// <exec>/.optimus/plugins
// $HOME/.optimus/plugins
// /usr/bin
// /usr/local/bin
//
// for duplicate binaries(even with different versions for now), only the first found will be used
// sample plugin name: optimus-task-myplugin_0.1_linux_amd64
func DiscoverPlugins(pluginLogger hclog.Logger) (map[string][]string, error) {
var (
prefix = "optimus-"
suffix = fmt.Sprintf("_%s_%s", runtime.GOOS, runtime.GOARCH)
discoveredPlugins = map[string][]string{}
)
dirs := []string{}
// current working directory
if p, err := os.Getwd(); err == nil {
dirs = append(dirs, p)
}
{
// look in the same directory as the executable
if exePath, err := os.Executable(); err != nil {
pluginLogger.Debug(fmt.Sprintf("Error discovering exe directory: %s", err))
} else {
dirs = append(dirs, filepath.Dir(exePath))
}
}
{
// add user home directory
if currentHomeDir, err := os.UserHomeDir(); err == nil {
dirs = append(dirs, filepath.Join(currentHomeDir, ".optimus", "plugins"))
}
}
dirs = append(dirs, []string{"/usr/bin", "/usr/local/bin"}...)
for _, dirPath := range dirs {
fileInfos, err := ioutil.ReadDir(dirPath)
if err != nil {
continue
}
for _, item := range fileInfos {
fullName := item.Name()
if !strings.HasPrefix(fullName, prefix) {
continue
}
if !strings.HasSuffix(fullName, suffix) {
continue
}
absPath, err := filepath.Abs(filepath.Join(dirPath, fullName))
if err != nil {
continue
}
info, err := os.Stat(absPath)
if err != nil {
continue
}
if info.IsDir() {
continue
}
// get plugin type
nameParts := strings.Split(fullName, "-")
if len(nameParts) < 3 {
continue
}
pluginName := strings.Split(nameParts[2], "_")[0]
absPath = filepath.Clean(absPath)
switch nameParts[1] {
case TaskPluginName:
// check for duplicate binaries, could be different versions
// if we have already discovered one, ignore rest
isAlreadyFound := false
for _, storedName := range discoveredPlugins[TaskPluginName] {
if strings.Contains(storedName, pluginName) {
isAlreadyFound = true
}
}
if !isAlreadyFound {
discoveredPlugins[TaskPluginName] = append(discoveredPlugins[TaskPluginName], absPath)
}
case HookPluginName:
isAlreadyFound := false
for _, storedName := range discoveredPlugins[HookPluginName] {
if strings.Contains(storedName, pluginName) {
isAlreadyFound = true
}
}
if !isAlreadyFound {
discoveredPlugins[HookPluginName] = append(discoveredPlugins[HookPluginName], absPath)
}
default:
// skip
}
}
}
return discoveredPlugins, nil
}
<file_sep>/mock/task.go
package mock
import (
"context"
"github.com/odpf/optimus/models"
"github.com/stretchr/testify/mock"
)
type SupportedTaskRepo struct {
mock.Mock
}
func (repo *SupportedTaskRepo) GetByName(name string) (models.TaskPlugin, error) {
args := repo.Called(name)
return args.Get(0).(models.TaskPlugin), args.Error(1)
}
func (repo *SupportedTaskRepo) GetAll() []models.TaskPlugin {
args := repo.Called()
return args.Get(0).([]models.TaskPlugin)
}
func (repo *SupportedTaskRepo) Add(t models.TaskPlugin) error {
return repo.Called(t).Error(0)
}
type TaskPlugin struct {
mock.Mock `hash:"-"`
}
func (repo *TaskPlugin) GetTaskSchema(ctx context.Context, inp models.GetTaskSchemaRequest) (models.GetTaskSchemaResponse, error) {
args := repo.Called(ctx, inp)
return args.Get(0).(models.GetTaskSchemaResponse), args.Error(1)
}
func (repo *TaskPlugin) DefaultTaskConfig(ctx context.Context, inp models.DefaultTaskConfigRequest) (models.DefaultTaskConfigResponse, error) {
args := repo.Called(ctx, inp)
return args.Get(0).(models.DefaultTaskConfigResponse), args.Error(1)
}
func (repo *TaskPlugin) DefaultTaskAssets(ctx context.Context, inp models.DefaultTaskAssetsRequest) (models.DefaultTaskAssetsResponse, error) {
args := repo.Called(ctx, inp)
return args.Get(0).(models.DefaultTaskAssetsResponse), args.Error(1)
}
func (repo *TaskPlugin) CompileTaskAssets(ctx context.Context, inp models.CompileTaskAssetsRequest) (models.CompileTaskAssetsResponse, error) {
args := repo.Called(ctx, inp)
return args.Get(0).(models.CompileTaskAssetsResponse), args.Error(1)
}
func (repo *TaskPlugin) GetTaskQuestions(ctx context.Context, inp models.GetTaskQuestionsRequest) (models.GetTaskQuestionsResponse, error) {
args := repo.Called(ctx, inp)
return args.Get(0).(models.GetTaskQuestionsResponse), args.Error(1)
}
func (repo *TaskPlugin) ValidateTaskQuestion(ctx context.Context, inp models.ValidateTaskQuestionRequest) (models.ValidateTaskQuestionResponse, error) {
args := repo.Called(ctx, inp)
return args.Get(0).(models.ValidateTaskQuestionResponse), args.Error(1)
}
func (repo *TaskPlugin) GenerateTaskDestination(ctx context.Context, inp models.GenerateTaskDestinationRequest) (models.GenerateTaskDestinationResponse, error) {
args := repo.Called(ctx, inp)
return args.Get(0).(models.GenerateTaskDestinationResponse), args.Error(1)
}
func (repo *TaskPlugin) GenerateTaskDependencies(ctx context.Context, inp models.GenerateTaskDependenciesRequest) (models.GenerateTaskDependenciesResponse, error) {
args := repo.Called(ctx, inp)
return args.Get(0).(models.GenerateTaskDependenciesResponse), args.Error(1)
}
<file_sep>/plugin/hook/server.go
package hook
import (
"context"
"github.com/odpf/optimus/plugin/task"
"github.com/odpf/optimus/models"
pb "github.com/odpf/optimus/api/proto/odpf/optimus"
)
// GRPCServer will be used by plugins this is working as proto adapter
type GRPCServer struct {
// This is the real implementation coming from plugin
Impl models.HookPlugin
projectSpecAdapter ProjectSpecAdapter
pb.UnimplementedHookPluginServer
}
func (s *GRPCServer) GetHookSchema(ctx context.Context, req *pb.GetHookSchema_Request) (*pb.GetHookSchema_Response, error) {
n, err := s.Impl.GetHookSchema(ctx, models.GetHookSchemaRequest{})
if err != nil {
return nil, err
}
return &pb.GetHookSchema_Response{
Name: n.Name,
Description: n.Description,
Image: n.Image,
Type: n.Type.String(),
DependsOn: n.DependsOn,
SecretPath: n.SecretPath,
}, nil
}
func (s *GRPCServer) GetHookQuestions(ctx context.Context, req *pb.GetHookQuestions_Request) (*pb.GetHookQuestions_Response, error) {
resp, err := s.Impl.GetHookQuestions(ctx, models.GetHookQuestionsRequest{
JobName: req.JobName,
PluginOptions: models.PluginOptions{DryRun: req.Options.DryRun},
})
if err != nil {
return nil, err
}
questions := []*pb.PluginQuestion{}
for _, q := range resp.Questions {
questions = append(questions, adaptQuestionToProto(q))
}
return &pb.GetHookQuestions_Response{Questions: questions}, nil
}
func (s *GRPCServer) ValidateHookQuestion(ctx context.Context, req *pb.ValidateHookQuestion_Request) (*pb.ValidateHookQuestion_Response, error) {
resp, err := s.Impl.ValidateHookQuestion(ctx, models.ValidateHookQuestionRequest{
PluginOptions: models.PluginOptions{DryRun: req.Options.DryRun},
Answer: models.PluginAnswer{
Question: adaptQuestionFromProto(req.Answer.Question),
Value: req.Answer.Value,
},
})
if err != nil {
return nil, err
}
return &pb.ValidateHookQuestion_Response{
Success: resp.Success,
Error: resp.Error,
}, nil
}
func (s *GRPCServer) DefaultHookConfig(ctx context.Context, req *pb.DefaultHookConfig_Request) (*pb.DefaultHookConfig_Response, error) {
answers := models.PluginAnswers{}
for _, ans := range req.Answers {
answers = append(answers, models.PluginAnswer{
Question: adaptQuestionFromProto(ans.Question),
Value: ans.Value,
})
}
resp, err := s.Impl.DefaultHookConfig(ctx, models.DefaultHookConfigRequest{
PluginOptions: models.PluginOptions{DryRun: req.Options.DryRun},
Answers: answers,
TaskConfig: task.AdaptConfigsFromProto(req.TaskConfigs),
})
if err != nil {
return nil, err
}
return &pb.DefaultHookConfig_Response{
Config: adaptConfigsToProto(resp.Config),
}, nil
}
func (s *GRPCServer) DefaultHookAssets(ctx context.Context, req *pb.DefaultHookAssets_Request) (*pb.DefaultHookAssets_Response, error) {
answers := models.PluginAnswers{}
for _, ans := range req.Answers {
answers = append(answers, models.PluginAnswer{
Question: adaptQuestionFromProto(ans.Question),
Value: ans.Value,
})
}
resp, err := s.Impl.DefaultHookAssets(ctx, models.DefaultHookAssetsRequest{
PluginOptions: models.PluginOptions{DryRun: req.Options.DryRun},
Answers: answers,
TaskConfig: task.AdaptConfigsFromProto(req.TaskConfigs),
})
if err != nil {
return nil, err
}
return &pb.DefaultHookAssets_Response{
Assets: adaptAssetsToProto(resp.Assets),
}, nil
}
<file_sep>/plugin/task/client.go
package task
import (
"context"
"fmt"
"os"
"strings"
"github.com/odpf/optimus/core/logger"
"github.com/golang/protobuf/ptypes"
pb "github.com/odpf/optimus/api/proto/odpf/optimus"
"github.com/odpf/optimus/models"
)
// GRPCClient will be used by core to talk over grpc with plugins
type GRPCClient struct {
client pb.TaskPluginClient
projectSpecAdapter ProjectSpecAdapter
// plugin name, used in filtering project secrets
Name string
}
func (m *GRPCClient) GetTaskSchema(ctx context.Context, _ models.GetTaskSchemaRequest) (models.GetTaskSchemaResponse, error) {
resp, err := m.client.GetTaskSchema(ctx, &pb.GetTaskSchema_Request{})
if err != nil {
ifFailToReachServerThenCrash(err)
return models.GetTaskSchemaResponse{}, err
}
return models.GetTaskSchemaResponse{
Name: resp.Name,
Description: resp.Description,
Image: resp.Image,
SecretPath: resp.SecretPath,
}, nil
}
func (m *GRPCClient) GetTaskQuestions(ctx context.Context, request models.GetTaskQuestionsRequest) (models.GetTaskQuestionsResponse, error) {
resp, err := m.client.GetTaskQuestions(ctx, &pb.GetTaskQuestions_Request{
JobName: request.JobName,
Options: &pb.PluginOptions{DryRun: request.DryRun},
})
if err != nil {
return models.GetTaskQuestionsResponse{}, err
}
var questions []models.PluginQuestion
for _, q := range resp.Questions {
questions = append(questions, adaptQuestionFromProto(q))
}
return models.GetTaskQuestionsResponse{
Questions: questions,
}, nil
}
func (m *GRPCClient) ValidateTaskQuestion(ctx context.Context, request models.ValidateTaskQuestionRequest) (models.ValidateTaskQuestionResponse, error) {
resp, err := m.client.ValidateTaskQuestion(ctx, &pb.ValidateTaskQuestion_Request{
Options: &pb.PluginOptions{DryRun: request.DryRun},
Answer: &pb.PluginAnswer{
Question: adaptQuestionToProto(request.Answer.Question),
Value: request.Answer.Value,
},
})
if err != nil {
return models.ValidateTaskQuestionResponse{}, err
}
return models.ValidateTaskQuestionResponse{
Success: resp.Success,
Error: resp.Error,
}, nil
}
func (m *GRPCClient) DefaultTaskConfig(ctx context.Context, request models.DefaultTaskConfigRequest) (models.DefaultTaskConfigResponse, error) {
answers := []*pb.PluginAnswer{}
for _, a := range request.Answers {
answers = append(answers, &pb.PluginAnswer{
Question: adaptQuestionToProto(a.Question),
Value: a.Value,
})
}
resp, err := m.client.DefaultTaskConfig(ctx, &pb.DefaultTaskConfig_Request{
Options: &pb.PluginOptions{DryRun: request.DryRun},
Answers: answers,
})
if err != nil {
return models.DefaultTaskConfigResponse{}, err
}
return models.DefaultTaskConfigResponse{
Config: AdaptConfigsFromProto(resp.Configs),
}, nil
}
func (m *GRPCClient) DefaultTaskAssets(ctx context.Context, request models.DefaultTaskAssetsRequest) (models.DefaultTaskAssetsResponse, error) {
answers := []*pb.PluginAnswer{}
for _, a := range request.Answers {
answers = append(answers, &pb.PluginAnswer{
Question: adaptQuestionToProto(a.Question),
Value: a.Value,
})
}
resp, err := m.client.DefaultTaskAssets(ctx, &pb.DefaultTaskAssets_Request{
Options: &pb.PluginOptions{DryRun: request.DryRun},
Answers: answers,
})
if err != nil {
return models.DefaultTaskAssetsResponse{}, err
}
return models.DefaultTaskAssetsResponse{
Assets: adaptAssetsFromProto(resp.Assets),
}, nil
}
func (m *GRPCClient) CompileTaskAssets(ctx context.Context, request models.CompileTaskAssetsRequest) (models.CompileTaskAssetsResponse, error) {
schdAt, err := ptypes.TimestampProto(request.InstanceSchedule)
if err != nil {
return models.CompileTaskAssetsResponse{}, err
}
instanceData := []*pb.InstanceSpecData{}
for _, inst := range request.InstanceData {
instanceData = append(instanceData, &pb.InstanceSpecData{
Name: inst.Name,
Value: inst.Value,
Type: pb.InstanceSpecData_Type(pb.InstanceSpecData_Type_value[strings.ToUpper(inst.Type)]),
})
}
resp, err := m.client.CompileTaskAssets(ctx, &pb.CompileTaskAssets_Request{
JobConfigs: AdaptConfigsToProto(request.Config),
JobAssets: adaptAssetsToProto(request.Assets),
TaskWindow: &pb.TaskWindow{
Size: ptypes.DurationProto(request.TaskWindow.Size),
Offset: ptypes.DurationProto(request.TaskWindow.Offset),
TruncateTo: request.TaskWindow.TruncateTo,
},
InstanceSchedule: schdAt,
InstanceData: instanceData,
Options: &pb.PluginOptions{DryRun: request.DryRun},
})
if err != nil {
return models.CompileTaskAssetsResponse{}, err
}
return models.CompileTaskAssetsResponse{
Assets: adaptAssetsFromProto(resp.Assets),
}, nil
}
func (m *GRPCClient) GenerateTaskDestination(ctx context.Context, request models.GenerateTaskDestinationRequest) (models.GenerateTaskDestinationResponse, error) {
resp, err := m.client.GenerateTaskDestination(ctx, &pb.GenerateTaskDestination_Request{
JobConfig: AdaptConfigsToProto(request.Config),
JobAssets: adaptAssetsToProto(request.Assets),
Project: m.projectSpecAdapter.ToProjectProtoWithSecret(request.Project, models.InstanceTypeTask, m.Name),
Options: &pb.PluginOptions{DryRun: request.DryRun},
})
if err != nil {
return models.GenerateTaskDestinationResponse{}, err
}
return models.GenerateTaskDestinationResponse{
Destination: resp.Destination,
}, nil
}
func (m *GRPCClient) GenerateTaskDependencies(ctx context.Context, request models.GenerateTaskDependenciesRequest) (models.GenerateTaskDependenciesResponse, error) {
resp, err := m.client.GenerateTaskDependencies(ctx, &pb.GenerateTaskDependencies_Request{
JobConfig: AdaptConfigsToProto(request.Config),
JobAssets: adaptAssetsToProto(request.Assets),
Project: m.projectSpecAdapter.ToProjectProtoWithSecret(request.Project, models.InstanceTypeTask, m.Name),
Options: &pb.PluginOptions{DryRun: request.DryRun},
})
if err != nil {
return models.GenerateTaskDependenciesResponse{}, err
}
return models.GenerateTaskDependenciesResponse{
Dependencies: resp.Dependencies,
}, nil
}
func ifFailToReachServerThenCrash(err error) {
if strings.Contains(err.Error(), "connection refused") && strings.Contains(err.Error(), "dial unix") {
logger.E(fmt.Sprintf("connector communication failed with: %s", err.Error()))
// TODO(kush.sharma): once plugins are more stable, remove this fail
os.Exit(1)
}
}
<file_sep>/plugin/task/server.go
package task
import (
"context"
"strings"
"github.com/odpf/optimus/models"
pb "github.com/odpf/optimus/api/proto/odpf/optimus"
)
// GRPCServer will be used by plugins this is working as proto adapter
type GRPCServer struct {
// This is the real implementation coming from plugin
Impl models.TaskPlugin
projectSpecAdapter ProjectSpecAdapter
pb.UnimplementedTaskPluginServer
}
func (s *GRPCServer) GetTaskSchema(ctx context.Context, req *pb.GetTaskSchema_Request) (*pb.GetTaskSchema_Response, error) {
n, err := s.Impl.GetTaskSchema(ctx, models.GetTaskSchemaRequest{})
if err != nil {
return nil, err
}
return &pb.GetTaskSchema_Response{
Name: n.Name,
Description: n.Description,
Image: n.Image,
SecretPath: n.SecretPath,
}, nil
}
func (s *GRPCServer) GetTaskQuestions(ctx context.Context, req *pb.GetTaskQuestions_Request) (*pb.GetTaskQuestions_Response, error) {
resp, err := s.Impl.GetTaskQuestions(ctx, models.GetTaskQuestionsRequest{
JobName: req.JobName,
PluginOptions: models.PluginOptions{DryRun: req.Options.DryRun},
})
if err != nil {
return nil, err
}
questions := []*pb.PluginQuestion{}
for _, q := range resp.Questions {
questions = append(questions, adaptQuestionToProto(q))
}
return &pb.GetTaskQuestions_Response{Questions: questions}, nil
}
func (s *GRPCServer) ValidateTaskQuestion(ctx context.Context, req *pb.ValidateTaskQuestion_Request) (*pb.ValidateTaskQuestion_Response, error) {
resp, err := s.Impl.ValidateTaskQuestion(ctx, models.ValidateTaskQuestionRequest{
PluginOptions: models.PluginOptions{DryRun: req.Options.DryRun},
Answer: models.PluginAnswer{
Question: adaptQuestionFromProto(req.Answer.Question),
Value: req.Answer.Value,
},
})
if err != nil {
return nil, err
}
return &pb.ValidateTaskQuestion_Response{
Success: resp.Success,
Error: resp.Error,
}, nil
}
func (s *GRPCServer) DefaultTaskConfig(ctx context.Context, req *pb.DefaultTaskConfig_Request) (*pb.DefaultTaskConfig_Response, error) {
answers := models.PluginAnswers{}
for _, ans := range req.Answers {
answers = append(answers, models.PluginAnswer{
Question: adaptQuestionFromProto(ans.Question),
Value: ans.Value,
})
}
resp, err := s.Impl.DefaultTaskConfig(ctx, models.DefaultTaskConfigRequest{
PluginOptions: models.PluginOptions{DryRun: req.Options.DryRun},
Answers: answers,
})
if err != nil {
return nil, err
}
return &pb.DefaultTaskConfig_Response{
Configs: AdaptConfigsToProto(resp.Config),
}, nil
}
func (s *GRPCServer) DefaultTaskAssets(ctx context.Context, req *pb.DefaultTaskAssets_Request) (*pb.DefaultTaskAssets_Response, error) {
answers := models.PluginAnswers{}
for _, ans := range req.Answers {
answers = append(answers, models.PluginAnswer{
Question: adaptQuestionFromProto(ans.Question),
Value: ans.Value,
})
}
resp, err := s.Impl.DefaultTaskAssets(ctx, models.DefaultTaskAssetsRequest{
PluginOptions: models.PluginOptions{DryRun: req.Options.DryRun},
Answers: answers,
})
if err != nil {
return nil, err
}
return &pb.DefaultTaskAssets_Response{
Assets: adaptAssetsToProto(resp.Assets),
}, nil
}
func (s *GRPCServer) CompileTaskAssets(ctx context.Context, req *pb.CompileTaskAssets_Request) (*pb.CompileTaskAssets_Response, error) {
instanceData := []models.InstanceSpecData{}
for _, inst := range req.InstanceData {
instanceData = append(instanceData, models.InstanceSpecData{
Name: inst.Name,
Value: inst.Value,
Type: strings.ToLower(inst.Type.String()),
})
}
resp, err := s.Impl.CompileTaskAssets(ctx, models.CompileTaskAssetsRequest{
PluginOptions: models.PluginOptions{DryRun: req.Options.DryRun},
Config: AdaptConfigsFromProto(req.JobConfigs),
Assets: adaptAssetsFromProto(req.JobAssets),
TaskWindow: models.JobSpecTaskWindow{
Size: req.TaskWindow.Size.AsDuration(),
Offset: req.TaskWindow.Offset.AsDuration(),
TruncateTo: req.TaskWindow.TruncateTo,
},
InstanceData: instanceData,
InstanceSchedule: req.InstanceSchedule.AsTime(),
})
if err != nil {
return nil, err
}
return &pb.CompileTaskAssets_Response{
Assets: adaptAssetsToProto(resp.Assets),
}, nil
}
func (s *GRPCServer) GenerateTaskDestination(ctx context.Context, req *pb.GenerateTaskDestination_Request) (*pb.GenerateTaskDestination_Response, error) {
resp, err := s.Impl.GenerateTaskDestination(ctx, models.GenerateTaskDestinationRequest{
Config: AdaptConfigsFromProto(req.JobConfig),
Assets: adaptAssetsFromProto(req.JobAssets),
Project: s.projectSpecAdapter.FromProjectProtoWithSecrets(req.Project),
PluginOptions: models.PluginOptions{DryRun: req.Options.DryRun},
})
if err != nil {
return nil, err
}
return &pb.GenerateTaskDestination_Response{Destination: resp.Destination}, nil
}
func (s *GRPCServer) GenerateTaskDependencies(ctx context.Context, req *pb.GenerateTaskDependencies_Request) (*pb.GenerateTaskDependencies_Response, error) {
resp, err := s.Impl.GenerateTaskDependencies(ctx, models.GenerateTaskDependenciesRequest{
Config: AdaptConfigsFromProto(req.JobConfig),
Assets: adaptAssetsFromProto(req.JobAssets),
Project: s.projectSpecAdapter.FromProjectProtoWithSecrets(req.Project),
PluginOptions: models.PluginOptions{DryRun: req.Options.DryRun},
})
if err != nil {
return nil, err
}
return &pb.GenerateTaskDependencies_Response{Dependencies: resp.Dependencies}, nil
}
<file_sep>/cmd/version.go
package cmd
import (
"context"
"fmt"
"time"
"github.com/odpf/optimus/config"
pb "github.com/odpf/optimus/api/proto/odpf/optimus"
"github.com/pkg/errors"
cli "github.com/spf13/cobra"
"google.golang.org/grpc"
)
const (
versionTimeout = time.Second * 2
)
func versionCommand(l logger, host string) *cli.Command {
var serverVersion bool
c := &cli.Command{
Use: "version",
Short: "Print the client version information",
RunE: func(c *cli.Command, args []string) error {
l.Printf(fmt.Sprintf("client: %s-%s", coloredNotice(config.Version), config.BuildCommit))
if host != "" && serverVersion {
srvVer, err := getVersionRequest(config.Version, host)
if err != nil {
return err
}
l.Printf("server: %s", coloredNotice(srvVer))
}
return nil
},
}
c.Flags().BoolVar(&serverVersion, "with-server", false, "check for server version")
return c
}
// getVersionRequest send a job request to service
func getVersionRequest(clientVer string, host string) (ver string, err error) {
dialTimeoutCtx, dialCancel := context.WithTimeout(context.Background(), OptimusDialTimeout)
defer dialCancel()
var conn *grpc.ClientConn
if conn, err = createConnection(dialTimeoutCtx, host); err != nil {
return "", err
}
defer conn.Close()
ctx, cancel := context.WithTimeout(context.Background(), versionTimeout)
defer cancel()
runtime := pb.NewRuntimeServiceClient(conn)
versionResponse, err := runtime.Version(ctx, &pb.VersionRequest{
Client: clientVer,
})
if err != nil {
return "", errors.Wrapf(err, "request failed for version")
}
return versionResponse.Server, nil
}
<file_sep>/plugin/task/connector.go
package task
import (
"context"
v1 "github.com/odpf/optimus/api/handler/v1"
"github.com/odpf/optimus/models"
hplugin "github.com/hashicorp/go-plugin"
pb "github.com/odpf/optimus/api/proto/odpf/optimus"
"google.golang.org/grpc"
)
var _ hplugin.GRPCPlugin = &connector{}
type ProjectSpecAdapter interface {
FromProjectProtoWithSecrets(*pb.ProjectSpecification) models.ProjectSpec
ToProjectProtoWithSecret(models.ProjectSpec, models.InstanceType, string) *pb.ProjectSpecification
}
type connector struct {
hplugin.NetRPCUnsupportedPlugin
hplugin.GRPCPlugin
impl models.TaskPlugin
projectSpecAdapter ProjectSpecAdapter
}
func (p *connector) GRPCServer(broker *hplugin.GRPCBroker, s *grpc.Server) error {
pb.RegisterTaskPluginServer(s, &GRPCServer{
Impl: p.impl,
projectSpecAdapter: p.projectSpecAdapter,
})
return nil
}
func (p *connector) GRPCClient(ctx context.Context, broker *hplugin.GRPCBroker, c *grpc.ClientConn) (interface{}, error) {
return &GRPCClient{
client: pb.NewTaskPluginClient(c),
projectSpecAdapter: p.projectSpecAdapter,
}, nil
}
func NewPlugin(impl models.TaskPlugin) *connector {
return &connector{
impl: impl,
projectSpecAdapter: v1.NewAdapter(nil, nil, nil),
}
}
func NewPluginWithAdapter(impl models.TaskPlugin, projAdapt ProjectSpecAdapter) *connector {
return &connector{
impl: impl,
projectSpecAdapter: projAdapt,
}
}
func NewPluginClient() *connector {
return &connector{
projectSpecAdapter: v1.NewAdapter(nil, nil, nil),
}
}
<file_sep>/cmd/admin_get_plugins.go
package cmd
import (
"context"
"github.com/odpf/optimus/models"
cli "github.com/spf13/cobra"
)
func adminGetPluginsCommand(l logger, taskRepo models.TaskPluginRepository, hookRepo models.HookRepo) *cli.Command {
cmd := &cli.Command{
Use: "plugins",
Short: "Get discovered plugins",
Example: `optimus admin get plugins`,
}
//TODO: add an option to list all server supported plugins
cmd.RunE = func(c *cli.Command, args []string) error {
l.Println("Discovered tasks:")
for taskIdx, tasks := range taskRepo.GetAll() {
schema, err := tasks.GetTaskSchema(context.Background(), models.GetTaskSchemaRequest{})
if err != nil {
return err
}
l.Printf("%d. %s\n", taskIdx+1, schema.Name)
l.Printf("Description: %s\n", schema.Description)
l.Printf("Image: %s\n", schema.Image)
l.Println("")
}
l.Println("Discovered hooks:")
for hookIdx, hooks := range hookRepo.GetAll() {
schema, err := hooks.GetHookSchema(context.Background(), models.GetHookSchemaRequest{})
if err != nil {
return err
}
l.Printf("%d. %s\n", hookIdx+1, schema.Name)
l.Printf("Description: %s\n", schema.Description)
l.Printf("Image: %s\n", schema.Image)
l.Println("")
}
return nil
}
return cmd
}
<file_sep>/plugin/hook/client.go
package hook
import (
"context"
"github.com/odpf/optimus/plugin/task"
pb "github.com/odpf/optimus/api/proto/odpf/optimus"
"github.com/odpf/optimus/models"
)
// GRPCClient will be used by core to talk over grpc with plugins
type GRPCClient struct {
client pb.HookPluginClient
projectSpecAdapter ProjectSpecAdapter
}
func (m *GRPCClient) GetHookSchema(ctx context.Context, _ models.GetHookSchemaRequest) (models.GetHookSchemaResponse, error) {
resp, err := m.client.GetHookSchema(ctx, &pb.GetHookSchema_Request{})
if err != nil {
return models.GetHookSchemaResponse{}, err
}
return models.GetHookSchemaResponse{
Name: resp.Name,
Description: resp.Description,
Image: resp.Image,
DependsOn: resp.DependsOn,
Type: models.HookType(resp.Type),
SecretPath: resp.SecretPath,
}, nil
}
func (m *GRPCClient) GetHookQuestions(ctx context.Context, request models.GetHookQuestionsRequest) (models.GetHookQuestionsResponse, error) {
resp, err := m.client.GetHookQuestions(ctx, &pb.GetHookQuestions_Request{
JobName: request.JobName,
Options: &pb.PluginOptions{DryRun: request.DryRun},
})
if err != nil {
return models.GetHookQuestionsResponse{}, err
}
var questions []models.PluginQuestion
for _, q := range resp.Questions {
questions = append(questions, adaptQuestionFromProto(q))
}
return models.GetHookQuestionsResponse{
Questions: questions,
}, nil
}
func (m *GRPCClient) ValidateHookQuestion(ctx context.Context, request models.ValidateHookQuestionRequest) (models.ValidateHookQuestionResponse, error) {
resp, err := m.client.ValidateHookQuestion(ctx, &pb.ValidateHookQuestion_Request{
Options: &pb.PluginOptions{DryRun: request.DryRun},
Answer: &pb.PluginAnswer{
Question: adaptQuestionToProto(request.Answer.Question),
Value: request.Answer.Value,
},
})
if err != nil {
return models.ValidateHookQuestionResponse{}, err
}
return models.ValidateHookQuestionResponse{
Success: resp.Success,
Error: resp.Error,
}, nil
}
func (m *GRPCClient) DefaultHookConfig(ctx context.Context, request models.DefaultHookConfigRequest) (models.DefaultHookConfigResponse, error) {
answers := []*pb.PluginAnswer{}
for _, a := range request.Answers {
answers = append(answers, &pb.PluginAnswer{
Question: adaptQuestionToProto(a.Question),
Value: a.Value,
})
}
resp, err := m.client.DefaultHookConfig(ctx, &pb.DefaultHookConfig_Request{
Options: &pb.PluginOptions{DryRun: request.DryRun},
Answers: answers,
TaskConfigs: task.AdaptConfigsToProto(request.TaskConfig),
})
if err != nil {
return models.DefaultHookConfigResponse{}, err
}
return models.DefaultHookConfigResponse{
Config: adaptConfigFromProto(resp.Config),
}, nil
}
func (m *GRPCClient) DefaultHookAssets(ctx context.Context, request models.DefaultHookAssetsRequest) (models.DefaultHookAssetsResponse, error) {
answers := []*pb.PluginAnswer{}
for _, a := range request.Answers {
answers = append(answers, &pb.PluginAnswer{
Question: adaptQuestionToProto(a.Question),
Value: a.Value,
})
}
resp, err := m.client.DefaultHookAssets(ctx, &pb.DefaultHookAssets_Request{
Options: &pb.PluginOptions{DryRun: request.DryRun},
Answers: answers,
TaskConfigs: task.AdaptConfigsToProto(request.TaskConfig),
})
if err != nil {
return models.DefaultHookAssetsResponse{}, err
}
return models.DefaultHookAssetsResponse{
Assets: adaptAssetsFromProto(resp.Assets),
}, nil
}
<file_sep>/models/hook.go
package models
import (
"context"
"strings"
"github.com/pkg/errors"
)
const (
HookTypePre HookType = "pre"
HookTypePost HookType = "post"
HookTypeFail HookType = "fail"
)
type HookType string
func (ht HookType) String() string {
return string(ht)
}
// HookPlugin needs to be implemented to register a hook
type HookPlugin interface {
GetHookSchema(context.Context, GetHookSchemaRequest) (GetHookSchemaResponse, error)
// GetHookQuestions list down all the cli inputs required to generate spec files
// name used for question will be directly mapped to DefaultHookConfig() parameters
GetHookQuestions(context.Context, GetHookQuestionsRequest) (GetHookQuestionsResponse, error)
ValidateHookQuestion(context.Context, ValidateHookQuestionRequest) (ValidateHookQuestionResponse, error)
// DefaultHookConfig will be passed down to execution unit as env vars
// they will be generated based on results of AskQuestions
// if DryRun is true in PluginOptions, should not throw error for missing inputs
// includes parent task configs
DefaultHookConfig(context.Context, DefaultHookConfigRequest) (DefaultHookConfigResponse, error)
// DefaultHookAssets will be passed down to execution unit as files
// if DryRun is true in PluginOptions, should not throw error for missing inputs
DefaultHookAssets(context.Context, DefaultHookAssetsRequest) (DefaultHookAssetsResponse, error)
}
type GetHookSchemaRequest struct{}
type GetHookSchemaResponse struct {
Name string
Description string
Image string
// DependsOn returns list of hooks this should be executed after
DependsOn []string
// Type provides the place of execution, could be before the transformation
// after the transformation, etc
Type HookType
// SecretPath will be mounted inside the container as volume
// e.g. /opt/secret/auth.json
// here auth.json should be a key in kube secret which gets
// translated to a file mounted in provided path
SecretPath string
}
type GetHookQuestionsRequest struct {
JobName string
PluginOptions
}
type GetHookQuestionsResponse struct {
Questions PluginQuestions
}
type ValidateHookQuestionRequest struct {
PluginOptions
Answer PluginAnswer
}
type ValidateHookQuestionResponse struct {
Success bool
Error string
}
type HookPluginConfig struct {
Name string
Value string
}
type HookPluginConfigs []HookPluginConfig
func (c HookPluginConfigs) Get(name string) (HookPluginConfig, bool) {
for _, con := range c {
if strings.ToLower(con.Name) == strings.ToLower(name) {
return con, true
}
}
return HookPluginConfig{}, false
}
func (c HookPluginConfigs) FromJobSpec(jobSpecConfig JobSpecConfigs) HookPluginConfigs {
taskPluginConfigs := HookPluginConfigs{}
for _, c := range jobSpecConfig {
taskPluginConfigs = append(taskPluginConfigs, HookPluginConfig{
Name: c.Name,
Value: c.Value,
})
}
return taskPluginConfigs
}
func (c HookPluginConfigs) ToJobSpec() JobSpecConfigs {
jsConfigs := JobSpecConfigs{}
for _, c := range c {
jsConfigs = append(jsConfigs, JobSpecConfigItem{
Name: c.Name,
Value: c.Value,
})
}
return jsConfigs
}
type DefaultHookConfigRequest struct {
PluginOptions
Answers PluginAnswers
// TaskConfig of the parent on which this task belongs to
TaskConfig TaskPluginConfigs
}
type DefaultHookConfigResponse struct {
Config HookPluginConfigs
}
type HookPluginAsset struct {
Name string
Value string
}
type HookPluginAssets []HookPluginAsset
func (c HookPluginAssets) Get(name string) (HookPluginAsset, bool) {
for _, con := range c {
if strings.ToLower(con.Name) == strings.ToLower(name) {
return con, true
}
}
return HookPluginAsset{}, false
}
func (c HookPluginAssets) FromJobSpec(jobSpecAssets JobAssets) HookPluginAssets {
taskPluginAssets := HookPluginAssets{}
for _, c := range jobSpecAssets.GetAll() {
taskPluginAssets = append(taskPluginAssets, HookPluginAsset{
Name: c.Name,
Value: c.Value,
})
}
return taskPluginAssets
}
func (c HookPluginAssets) ToJobSpec() *JobAssets {
jsAssets := []JobSpecAsset{}
for _, c := range c {
jsAssets = append(jsAssets, JobSpecAsset{
Name: c.Name,
Value: c.Value,
})
}
return JobAssets{}.New(jsAssets)
}
type DefaultHookAssetsRequest struct {
PluginOptions
Answers PluginAnswers
// TaskConfig of the parent on which this task belongs to
TaskConfig TaskPluginConfigs
}
type DefaultHookAssetsResponse struct {
Assets HookPluginAssets
}
var (
// HookRegistry are a list of hooks that are supported in a job
HookRegistry = &supportedHooks{
data: map[string]HookPlugin{},
}
ErrUnsupportedHook = errors.New("unsupported hook requested")
)
type HookRepo interface {
GetByName(string) (HookPlugin, error)
GetAll() []HookPlugin
Add(HookPlugin) error
}
type supportedHooks struct {
data map[string]HookPlugin
}
func (s *supportedHooks) GetByName(name string) (HookPlugin, error) {
if unit, ok := s.data[name]; ok {
return unit, nil
}
return nil, errors.Wrap(ErrUnsupportedHook, name)
}
func (s *supportedHooks) GetAll() []HookPlugin {
list := []HookPlugin{}
for _, unit := range s.data {
list = append(list, unit)
}
return list
}
func (s *supportedHooks) Add(newUnit HookPlugin) error {
schema, err := newUnit.GetHookSchema(context.TODO(), GetHookSchemaRequest{})
if err != nil {
return err
}
if schema.Name == "" {
return errors.New("hook name cannot be empty")
}
// check if name is already used
if _, ok := s.data[schema.Name]; ok {
return errors.Errorf("hook name already in use %s", schema.Name)
}
// image is a required field
if schema.Image == "" {
return errors.New("hook image cannot be empty")
}
s.data[schema.Name] = newUnit
return nil
}
<file_sep>/mock/hook.go
package mock
import (
"context"
"github.com/odpf/optimus/models"
"github.com/stretchr/testify/mock"
)
type SupportedHookRepo struct {
mock.Mock
}
func (repo *SupportedHookRepo) GetByName(name string) (models.HookPlugin, error) {
args := repo.Called(name)
return args.Get(0).(models.HookPlugin), args.Error(1)
}
func (repo *SupportedHookRepo) GetAll() []models.HookPlugin {
args := repo.Called()
return args.Get(0).([]models.HookPlugin)
}
func (repo *SupportedHookRepo) Add(t models.HookPlugin) error {
return repo.Called(t).Error(0)
}
type HookPlugin struct {
mock.Mock `hash:"-"`
}
func (repo *HookPlugin) GetHookSchema(ctx context.Context, request models.GetHookSchemaRequest) (models.GetHookSchemaResponse, error) {
args := repo.Called(ctx, request)
return args.Get(0).(models.GetHookSchemaResponse), args.Error(1)
}
func (repo *HookPlugin) GetHookQuestions(ctx context.Context, request models.GetHookQuestionsRequest) (models.GetHookQuestionsResponse, error) {
args := repo.Called(ctx, request)
return args.Get(0).(models.GetHookQuestionsResponse), args.Error(1)
}
func (repo *HookPlugin) ValidateHookQuestion(ctx context.Context, request models.ValidateHookQuestionRequest) (models.ValidateHookQuestionResponse, error) {
args := repo.Called(ctx, request)
return args.Get(0).(models.ValidateHookQuestionResponse), args.Error(1)
}
func (repo *HookPlugin) DefaultHookConfig(ctx context.Context, request models.DefaultHookConfigRequest) (models.DefaultHookConfigResponse, error) {
args := repo.Called(ctx, request)
return args.Get(0).(models.DefaultHookConfigResponse), args.Error(1)
}
func (repo *HookPlugin) DefaultHookAssets(ctx context.Context, request models.DefaultHookAssetsRequest) (models.DefaultHookAssetsResponse, error) {
args := repo.Called(ctx, request)
return args.Get(0).(models.DefaultHookAssetsResponse), args.Error(1)
}
<file_sep>/docs/docs/development/task-plugin.md
---
id: task-plugin
title: Developing task plugin
---
Optimus's responsibilities are currently divided in two parts, scheduling a transformation [task](../concepts/overview.md#Job) and running one time action to create or modify a [datastore](../concepts/overview.md#Datastore) resource. Defining how a datastore is managed can be easy and doesn't leave many options for configuration or ambiguity although the way datastores are implemented gives developers flexibility to contribute additional type of datastore, but it is not something we do every day.
Whereas tasks used in jobs that define how the transformation will execute, what configuration does it need as input from user, how does this task resolves dependencies between each other, what kind of assets it might need. These questions are very open and answers to them could be different in different organisation and users. To allow flexibility of answering these questions by developers themselves, we have chosen to make it easy to contribute a new kind of task or even a hook. This modularity in Optimus is achieved using plugins.
> Plugins are self-contained binaries which implements predefined protobuf interfaces to extend Optimus functionalities.
Optimus can be divided in two logical parts when we are thinking of a pluggable model, one is the **core** where everything happens which is common for all job/datastore, and the other part which could be variable and needs user specific definitions of how things should work which is a **plugin**.
## Types of Plugins in Optimus
At the moment mainly there are two types of plugins which optimus supports. These are : ***Hook*** and ***Task***
Before getting into the difference between two plugins ,we need to get familiar with [Jobs](../concepts/overview.md#Job).
| Type | Hook | Task |
|------------------------|--------------------------------------------------------------------------------|---------------------------------------------------------------------------------------------------------------|
| Definition | It is the operation that we preferably run before or after a Job. | It is the single base transformation in a Job. |
| Fundamental Difference | It can have dependencies over other hooks within the job. | It can have dependencies over other jobs inside the optimus project. |
| Configuration | It has its own set of configs and share the same asset folder as the base job. | It has its own set of configs and may share only the dependencies with the other jobs in the optimus project. |
## Creating a task plugin
At the moment Optimus supports task as well as hook plugins. In this section we will be explaining how to write a new task although both are very similar. Plugins are implemented using [go-plugin](https://github.com/hashicorp/go-plugin) developed by Hashicorp used in terraform and other similar products.
> Plugins can be implemented in any language as long as they can be exported as a single self-contained executable binary.
It is recommended to use Golang currently for writing plugins because of its cross platform build functionality and to reuse protobuf adapter provided
within Optimus core. Although the plugin is written in Golang, it will be just an adapter between what actually needs to be executed. Actual transformation will be packed in a docker image and Optimus will execute these arbitrary docker images as long as it has access to reach container registry.
> Task plugin binary itself is not executed for transformation but only used for adapting conditions which Optimus requires to be defined for each task.
To demonstrate this wrapping functionality, lets create a plugin in Golang and use python for actual transformation logic. You can choose to fork this [example](https://github.com/kushsharma/optimus-plugins) template and modify it as per your needs or start fresh. To demonstrate how to start from scratch, will be starting from an empty git repository and build a plugin which will find potential hazardous **Near Earth Orbit** objects every day, lets call it **neo** for short.
Brief description of Neo is as follows
- Using [NASA API](https://api.nasa.gov/) we can get count of hazardous objects, there diameter and velocity.
- Task will need two config as input, `RANGE_START`, `RANGE_END` as date time string which will filter the count for this specific period only.
- Execute every day, lets say at 2 AM.
- Need a secret token that will be passed to nasa api endpoint for each request.
- Output of this object count can be printed in logs for now but in a real use case can be pushed to Kafka topic or written to a database.
- Plugin will be written in **golang** and **Neo** in **python**.
### Preparing task logic
Start by initializing an empty git repository with the following folder structure
```shell
.git
/task
/neo
/executor
/main.py
/requirements.txt
/Dockerfile
README.md
```
That is three folders one inside another. This might look confusing for now, a lot of things will, but just keep going. Create an empty python file in executor `main.py`, this is where the main logic for interacting with nasa api and generating output will be. For simplicity, lets use as minimal things as possible.
Add the following code to `main.py`
```python
import os
import requests
import json
# path where secret will be mounted in docker container, contains api_key
SECRET_PATH = "/tmp/key.json"
def start():
"""
Sends a http call to nasa api, parses response and prints potential hazardous
objects in near earth orbit
:return:
"""
opt_config = fetch_config_from_optimus()
# user configuration for date range
range_start = opt_config["envs"]["RANGE_START"]
range_end = opt_config["envs"]["RANGE_END"]
# secret token required for NASA API being fetched from a file mounted as
# volume by optimus executor
with open(SECRET_PATH, "r") as f:
api_key = json.load(f)['key']
if api_key is None:
raise Exception("invalid api token")
# send the request for given date range
r = requests.get(url="https://api.nasa.gov/neo/rest/v1/feed",
params={'start_date': range_start, 'end_date': range_end, 'api_key': api_key})
# extracting data in json format
print("for date range {} - {}".format(range_start, range_end))
print_details(r.json())
return
def fetch_config_from_optimus():
"""
Fetch configuration inputs required to run this task for a single schedule day
Configurations are fetched using optimus rest api
:return:
"""
# try printing os env to see what all we have for debugging
# print(os.environ)
# prepare request
optimus_host = os.environ["OPTIMUS_HOSTNAME"]
scheduled_at = os.environ["SCHEDULED_AT"]
project_name = os.environ["PROJECT"]
job_name = os.environ["JOB_NAME"]
r = requests.post(url="http://{}/api/v1/project/{}/job/{}/instance".format(optimus_host, project_name, job_name),
json={'scheduled_at': scheduled_at,
'instance_name': "neo",
'instance_type': "TASK"})
instance = r.json()
# print(instance)
return instance["context"]
if __name__ == "__main__":
start()
```
`api_key` is a token provided by nasa during registration. This token will be passed as a parameter in each http call. `SECRET_PATH` is the path to a file which will contain this token in json and will be mounted inside the docker container by Optimus.
`start` function is using `fetch_config_from_optimus()` to get the date range for which this task executes for an iteration. In this example, configuration is fetched using REST APIs provided by optimus although there are variety of ways to get them. After extracting `API_KEY` from secret file, unmarshalling it to json with ` json.load()` send a http request to nasa api. Response can be parsed and printed using the following function
```python
def print_details(jd):
"""
Parse and calculate what we need from NASA endpoint response
:param jd: json data fetched from NASA API
:return:
"""
element_count = jd['element_count']
potentially_hazardous = []
for search_date in jd['near_earth_objects'].keys():
for neo in jd['near_earth_objects'][search_date]:
if neo["is_potentially_hazardous_asteroid"] is True:
potentially_hazardous.append({
"name": neo["name"],
"estimated_diameter_km": neo["estimated_diameter"]["kilometers"]["estimated_diameter_max"],
"relative_velocity_kmh": neo["close_approach_data"][0]["relative_velocity"]["kilometers_per_hour"]
})
print("total tracking: {}\npotential hazardous: {}".format(element_count, len(potentially_hazardous)))
for haz in potentially_hazardous:
print("Name: {}\nEstimated Diameter: {} km\nRelative Velocity: {} km/h\n\n".format(
haz["name"],
haz["estimated_diameter_km"],
haz["relative_velocity_kmh"]
))
return
```
Finish it off by adding the main function
```python
if __name__ == "__main__":
start()
```
Add `requests` library in `requirements.txt`
```ini
requests==v2.25.1
```
Once the python code is ready, wrap this in a `Dockerfile`
```dockerfile
# set base image (host OS)
FROM python:3.8
# set the working directory in the container
RUN mkdir -p /opt
WORKDIR /opt
# copy the content of the local src directory to the working directory
COPY task/neo/executor .
# install dependencies
RUN pip install -r requirements.txt
CMD ["python3", "main.py"]
```
Now that base image is ready for execution, this needs to be scheduled at a fixed interval using `jobs` but for optimus to understand **Neo** task, we need to write an adapter for it.
### Implementing plugin interface
Because we are using golang, start by initializing go module in `neo` directory as follows
```go
go mod init github.com/kushsharma/optimus-plugins/task/neo
```
Prepare `main.go` in the same directory structure
```
.git
/task
/neo
/executor
/main.py
/requirements.txt
/Dockerfile
/main.go
/go.mod
/go.sum
README.md
```
Start by adding the following boilerplate code
```go
package main
import (
"context"
"errors"
"fmt"
"github.com/odpf/optimus/plugin"
"github.com/odpf/optimus/models"
"github.com/odpf/optimus/plugin/task"
hplugin "github.com/hashicorp/go-plugin"
)
var (
Name = "neo"
DatetimeFormat = "2006-01-02"
Version = "latest"
Image = "ghcr.io/kushsharma/optimus-task-neo-executor"
)
type Neo struct{}
func main() {
neo := &Neo{}
// start serving the plugin on a unix socket as a grpc server
hplugin.Serve(&hplugin.ServeConfig{
// this will be printed on stdout and will be piped to optimus core
HandshakeConfig: hplugin.HandshakeConfig{
// Need to be set as needed
ProtocolVersion: 1,
// Magic cookie key and value are just there to make sure you want to connect
// with optimus core, this is not authentication
MagicCookieKey: plugin.MagicCookieKey,
MagicCookieValue: plugin.MagicCookieValue,
},
// what are we serving on grpc
Plugins: map[string]hplugin.Plugin{
plugin.TaskPluginName: &task.Plugin{Impl: neo},
},
// default grpc server
GRPCServer: hplugin.DefaultGRPCServer,
})
}
```
The plugin binary serves a GRPC server on start but before the communication channel is created protocol version, socket, port, and some other metadata needs to be printed as the handshake information to stdout which the core will read. Plugin and core needs to mutually conclude on same protocol version to start the communication. Client side protocol version announcement is done using `HandshakeConfig` provided in `main()`.
**Handshake contract:**
CORE-PROTOCOL-VERSION | APP-PROTOCOL-VERSION | NETWORK-TYPE | NETWORK-ADDR | PROTOCOL
**For example:**
1|1|tcp|127.0.0.1:1234|grpc
You don't have to worry about this if you are using the provided handshake struct. Core will initiate a connection with the plugin server as a client when the core binary boots and caches the connection for further internal use.
A single binary can serve more than one kind of plugin, in this example stick with just one. To start serving GRPC, either we write our own implementation for serialising/deserializing golang structs to protobufs or reuse the one already provided by [core](https://github.com/odpf/optimus/blob/eaa50bb37d7e738d9b8a94332312f34b04a7e16b/plugin/task/server.go). Optimus GRPC server adapter for protobuf accepts an [interface](https://github.com/odpf/optimus/blob/0ab5a4d44a7b2b85e9a160aef3648d8ba798536a/models/task.go) which we will implement next on Neo struct. Custom protobuf adapter can also be written using the [provided](https://github.com/odpf/proton/blob/e7fd43798f0c5bcf083c821cc98843639c3883fa/odpf/optimus/task_plugin.proto) protobuf stored in odpf [repository](https://github.com/odpf/proton).
Add the following code in the existing `main.go` as an implementation to [TaskPlugin](https://github.com/odpf/optimus/blob/0ab5a4d44a7b2b85e9a160aef3648d8ba798536a/models/task.go)
```go
type Neo struct{}
// GetTaskSchema provides basic task details
func (n *Neo) GetTaskSchema(ctx context.Context, req models.GetTaskSchemaRequest) (models.GetTaskSchemaResponse, error) {
return models.GetTaskSchemaResponse{
Name: Name,
Description: "Near earth object tracker",
// docker image that will be executed as the actual transformation task
Image: fmt.Sprintf("%s:%s", Image, Version),
// this is where the secret required by docker container will be mounted
SecretPath: "/tmp/key.json",
}, nil
}
// GetTaskQuestions provides questions asked via optimus cli when a new job spec
// is requested to be created
func (n *Neo) GetTaskQuestions(ctx context.Context, req models.GetTaskQuestionsRequest) (models.GetTaskQuestionsResponse, error) {
tQues := []models.PluginQuestion{
{
Name: "Start",
Prompt: "Date range start",
Help: "YYYY-MM-DD format",
},
{
Name: "End",
Prompt: "Date range end",
Help: "YYYY-MM-DD format",
},
}
return models.GetTaskQuestionsResponse{
Questions: tQues,
}, nil
}
// ValidateTaskQuestion validate how stupid user is
// Each question config in GetTaskQuestions will send a validation request
func (n *Neo) ValidateTaskQuestion(ctx context.Context, req models.ValidateTaskQuestionRequest) (models.ValidateTaskQuestionResponse, error) {
var err error
switch req.Answer.Question.Name {
case "Start":
err = func(ans interface{}) error {
d, ok := ans.(string)
if !ok || d == "" {
return errors.New("not a valid string")
}
// can choose to parse here for a valid date but we will use optimus
// macros here {{.DSTART}} instead of actual dates
// _, err := time.Parse(time.RFC3339, d)
// return err
return nil
}(req.Answer.Value)
case "End":
err = func(ans interface{}) error {
d, ok := ans.(string)
if !ok || d == "" {
return errors.New("not a valid string")
}
// can choose to parse here for a valid date but we will use optimus
// macros here {{.DEND}} instead of actual dates
// _, err := time.Parse(time.RFC3339, d)
// return err
return nil
}(req.Answer.Value)
}
if err != nil {
return models.ValidateTaskQuestionResponse{
Success: false,
Error: err.Error(),
}, nil
}
return models.ValidateTaskQuestionResponse{
Success: true,
}, nil
}
func findAnswerByName(name string, answers []models.PluginAnswer) (models.PluginAnswer, bool) {
for _, ans := range answers {
if ans.Question.Name == name {
return ans, true
}
}
return models.PluginAnswer{}, false
}
// DefaultTaskConfig are a set of key value pair which will be embedded in job
// specification. These configs can be requested by the docker container before
// execution
func (n *Neo) DefaultTaskConfig(ctx context.Context, request models.DefaultTaskConfigRequest) (models.DefaultTaskConfigResponse, error) {
start, _ := findAnswerByName("Start", request.Answers)
end, _ := findAnswerByName("End", request.Answers)
conf := []models.TaskPluginConfig{
{
Name: "RANGE_START",
Value: start.Value,
},
{
Name: "RANGE_END",
Value: end.Value,
},
}
return models.DefaultTaskConfigResponse{
Config: conf,
}, nil
}
// DefaultTaskAssets are a set of files which will be embedded in job
// specification in assets folder. These configs can be requested by the
// docker container before execution.
func (n *Neo) DefaultTaskAssets(ctx context.Context, _ models.DefaultTaskAssetsRequest) (models.DefaultTaskAssetsResponse, error) {
return models.DefaultTaskAssetsResponse{}, nil
}
// override the compilation behaviour of assets - if needed
func (n *Neo) CompileTaskAssets(ctx context.Context, req models.CompileTaskAssetsRequest) (models.CompileTaskAssetsResponse, error) {
return models.CompileTaskAssetsResponse{
Assets: req.Assets,
}, nil
}
// a task should ideally always have a destination, it could be endpoint, table, bucket, etc
// in our case it is actually nothing
func (n *Neo) GenerateTaskDestination(ctx context.Context, request models.GenerateTaskDestinationRequest) (models.GenerateTaskDestinationResponse, error) {
return models.GenerateTaskDestinationResponse{
Destination: "none",
}, nil
}
// as this task doesn't need dependency resolution, just leaving this empty
func (n *Neo) GenerateTaskDependencies(ctx context.Context, request models.GenerateTaskDependenciesRequest) (response models.GenerateTaskDependenciesResponse, err error) {
return response, nil
}
```
All the functions are prefixed with comments to give you basic idea of what each one is doing, for advanced usage, look at other plugins used in the wild.
Few things to note:
- `GetTaskSchema` is used to define a unique name used by your plugin to identify yourself, keep it simple.
- `GetTaskSchema` contains `Image` field that specify the docker image which Optimus will execute when needed. This is where the neo python image will go.
- `Version` field can be injected using build system, here we are only keeping a default value.
### Building everything
Once the code is ready, to build there is a pretty nice tool available for golang [goreleaser](https://github.com/goreleaser/goreleaser/). A single configuration file will contain everything to build the docker image as well as the binary.
Put this in the root of the project as `.goreleaser.yml`
```yaml
builds:
- dir: ./task/neo
main: .
id: "neo"
binary: "optimus-task-neo_{{.Version}}_{{.Os}}_{{.Arch}}"
ldflags:
- -s -w -X main.Version={{.Version}} -X main.Image=ghcr.io/kushsharma/optimus-task-neo-executor
goos:
- linux
- darwin
- windows
goarch:
- amd64
- arm64
env:
- CGO_ENABLED=0
archives:
- replacements:
darwin: darwin
linux: linux
windows: windows
amd64: amd64
format_overrides:
- goos: windows
format: zip
release:
prerelease: auto
checksum:
name_template: 'checksums.txt'
snapshot:
name_template: "{{ .Tag }}-next"
changelog:
sort: asc
filters:
exclude:
- '^docs:'
- '^test:'
dockers:
-
goos: linux
goarch: amd64
image_templates:
- "ghcr.io/kushsharma/optimus-task-neo-executor:latest"
- "ghcr.io/kushsharma/optimus-task-neo-executor:{{ .Version }}"
dockerfile: ./task/neo/executor/Dockerfile
extra_files:
- task/neo/executor
brews:
- name: optimus-plugins-kush
install: |
bin.install Dir["optimus-*"]
tap:
owner: kushsharma
name: homebrew-taps
license: "Apache 2.0"
description: "Optimus plugins - [Optimus Near earth orbit tracker]"
commit_author:
name: <NAME>
email: <EMAIL>
```
Please go through goreleaser documentation to understand what this config is doing but just to explain briefly
- It will build golang task plugin adapter for multiple platforms, archives them and release on Github
- Build and push the docker image for the python neo task
- Create a Formula for installing this plugin on Mac using brew
- Each plugin will follow the binary naming convention as `optimus-task-<pluginname>_<version>_<os>_<arch>`. For example: `optimus-task-bq2bq_0.0.1_linux_amd64`
Once installed, run goreleaser using
```shell
goreleaser --snapshot --rm-dist
```
Use this [repository](https://github.com/kushsharma/optimus-plugins) as an example to see how everything fits in together. It uses github workflows to run goreleaser and publish everything.
## How to use
### Installing a plugin
Plugins need to be installed in Optimus server before it can be used. Optimus uses following directories for discovering plugin binaries
```shell
./
<exec>/
<exec>/.optimus/plugins
$HOME/.optimus/plugins
/usr/bin
/usr/local/bin
```
If Optimus cli is used to generate specifications or deployment, plugin should be installed in a client's machine as well.
> Plugins can potentially modify the behavior of Optimus in undesired ways. Exercise caution when adding new plugins developed by unrecognized developers.
### Using in job specification
Once everything is built and in place, we can generate job specifications that uses **neo** as the task type.
```shell
optimus create job
? What is the job name? is_last_day_on_earth
? Who is the owner of this job? <EMAIL>
? Which task to run? neo
? Specify the start date 2021-05-25
? Specify the interval (in crontab notation) 0 2 * * *
? Transformation window daily
? Date range start {{.DSTART}}
? Date range end {{.DEND}}
job created successfully is_last_day_on_earth
```
Create a commit and deploy this specification if you are using optimus with a git managed repositories or send a REST call or use GRPC, whatever floats your boat.
### Checking the output
If your optimus deployment is using Airflow as the scheduling engine, open the task log and verify something like this
```
total tracking: 14
potential hazardous: 1
Name: (2014 KP4)
Estimated Diameter: 0.8204270649 km
Relative Velocity: 147052.9914506647 km/h
```
## Additional details
A task is like a pipeline, it takes some input, it runs a procedure on the input and then produces an output. Procedure is wrapped inside the docker image, output is owned by the procedure which could be anything but input should be injected somehow by optimus or at least provide some information about where/what input is. Currently, Optimus supports two kind of inputs:
- Key value configuration
- File assets
##### Task Configuration
Task configurations are key value pair provided as part of job specification in `job.yaml` file. These are based on plugin implementation of `TaskPlugin` interface. These configurations accept simple strings as well as Optimus [macros](../concepts/overview.md#Macros-&-Templates). There are few Optimus provided configuration to all tasks and hooks even if users don't specifically provide them:
- DSTART
- DEND
- EXECUTION_TIME
##### File Assets
Sometimes a task may need more than just key value configuration, this is where assets can be used. Assets are packed along with the job specification and should have unique names. A task can have more than one asset file but if any file name conflicts with any already existing plugin in the optimus, it will throw an error, so it is advised to either prefix them or name them very specific to the task. These assets should ideally be small and not more than ~5 MB and any heavy lifting if required should be done directly inside the task container.
### Requesting task context
Optimus calls these task configuration and asset inputs for each scheduled execution of a task as `context`. There are variety of ways to fetch task context from optimus.
- REST API
- GRPC function call
- Optimus cli
##### REST API
This is probably the easiest way using [REST API](https://github.com/odpf/optimus/blob/0ab5a4d44a7b2b85e9a160aef3648d8ba798536a/third_party/OpenAPI/odpf/optimus/runtime_service.swagger.json#L187) provided by optimus server. Each container when boots up has few pre-defined environment variables injected by optimus, few of them are:
- JOB_NAME
- OPTIMUS_HOSTNAME
- JOB_DIR
- PROJECT
- SCHEDULED_AT
- INSTANCE_TYPE
- INSTANCE_NAME
These variables might be needed to make the call and in response, container should get configuration and files as key value pairs in json.
##### GRPC call
Plugin can choose to make a GRPC call using `RegisterInstance` [function](https://github.com/odpf/proton/blob/main/odpf/optimus/runtime_service.proto#L124) and should get the context back in return.
##### Optimus cli
There could be scenarios where it is not possible or maybe not convenient to modify the base execution image and still task need context configuration values. One easy way to do this is by wrapping the base docker image into another docker image and using optimus binary to request task context. Optimus command will internally send a GRPC call and store the output in `${JOB_DIR}/in/` directory. It will create one `.env` file containing all the configuration files and all the asset files belong to the provided task. Optimus command can be invoked as
```shell
OPTIMUS_ADMIN_ENABLED=1 /opt/optimus admin build instance $JOB_NAME --project $PROJECT --output-dir $JOB_DIR --type $INSTANCE_TYPE --name $INSTANCE_NAME --scheduled-at $SCHEDULED_AT --host $OPTIMUS_HOSTNAME
```
You might have noticed, optimus need OPTIMUS_ADMIN_ENABLED as env variable to enable admin commands. An example of wrapper `Dockerfile` is as follows
```dockerfile
FROM ghcr.io/kushsharma/optimus-task-neo-executor:latest
# path to optimus release tar.gz
ARG OPTIMUS_RELEASE_URL
RUN apt install curl tar -y
RUN mkdir -p /opt
RUN curl -sL ${OPTIMUS_RELEASE_URL} | tar xvz optimus
RUN mv optimus /opt/optimus || true
RUN chmod +x /opt/optimus
# or copy like this
COPY task/neo/example.entrypoint.sh /opt/entrypoint.sh
RUN chmod +x /opt/entrypoint.sh
ENTRYPOINT ["/opt/entrypoint.sh"]
CMD ["python3", "/opt/main.py"]
```
Where `entrypoint.sh` is as follows
```shell
#!/bin/sh
# wait for few seconds to prepare scheduler for the run
sleep 5
# get resources
echo "-- initializing optimus assets"
OPTIMUS_ADMIN_ENABLED=1 /opt/optimus admin build instance $JOB_NAME --project $PROJECT --output-dir $JOB_DIR --type $TASK_TYPE --name $TASK_NAME --scheduled-at $SCHEDULED_AT --host $OPTIMUS_HOSTNAME
# TODO: this doesnt support using back quote sign in env vars
echo "-- exporting env"
set -o allexport
source $JOB_DIR/in/.env
set +o allexport
echo "-- current envs"
printenv
echo "-- running unit"
exec $(eval echo "$@")
```
All of it can be built using goreleaser as well
```yaml
dockers:
-
goos: linux
goarch: amd64
image_templates:
- "ghcr.io/kushsharma/optimus-task-neo:latest"
- "ghcr.io/kushsharma/optimus-task-neo:{{ .Version }}"
dockerfile: ./task/neo/example.Dockerfile
extra_files:
- task/neo/example.entrypoint.sh
build_flag_templates:
- "--build-arg=OPTIMUS_RELEASE_URL=https://github.com/odpf/optimus/releases/download/v0.0.1-rc.2/optimus_0.0.1-rc.2_linux_x86_64.tar.gz"
```
Keep in mind, the plugin binary now needs to point to this `optimus-task-neo` docker image and not the base one. An example of this approach can be checked in the provided [repository](https://github.com/kushsharma/optimus-plugins).
### Directory Structure
You might have already understood it by now but still just to state, the reason we went ahead with the provided directory structure earlier so that we can support more than one task and even hooks if we need to in the same repository. Image a single repository of plugins as an organization repository where one can find all that can be contributed by an entity
```
/task
/neo
/executor
/main.py
/requirements.txt
/Dockerfile
/main.go
/go.mod
/go.sum
/task-2
/task-3
/hook
/hook-1
/hook-2
.goreleaser.yml
README.md
```
### Secret management
You must be wondering from where that api token came from when we said it will be mounted inside the container. Optimus need to somehow know what the secret is, for this current implementation of optimus relies on Kubernetes [Secrets](https://kubernetes.io/docs/concepts/configuration/secret/). Optimus is built to be deployed on kubernetes although it can work just fine without it as well but might need some tweaking here and there. An example of creating this secret
```yaml
apiVersion: v1
kind: Secret
metadata:
name: optimus-task-neo
type: Opaque
data:
key.json: base64encodedAPIkeygoes
```
Notice the name of the secret `optimus-task-neo` which is actually based on a convention. That is if secret is defined, Optimus will look in kubernetes using `optimus-task-<taskname>` as the secret name and mount it to the path provided in `SecretPath` field of `TaskSchema`.
<file_sep>/models/task.go
package models
import (
"context"
"strings"
"time"
"github.com/pkg/errors"
)
// TaskPlugin needs to be implemented to register a task
type TaskPlugin interface {
GetTaskSchema(context.Context, GetTaskSchemaRequest) (GetTaskSchemaResponse, error)
// GetTaskQuestions list down all the cli inputs required to generate spec files
// name used for question will be directly mapped to DefaultTaskConfig() parameters
GetTaskQuestions(context.Context, GetTaskQuestionsRequest) (GetTaskQuestionsResponse, error)
ValidateTaskQuestion(context.Context, ValidateTaskQuestionRequest) (ValidateTaskQuestionResponse, error)
// DefaultTaskConfig will be passed down to execution unit as env vars
// they will be generated based on results of AskQuestions
// if DryRun is true in PluginOptions, should not throw error for missing inputs
DefaultTaskConfig(context.Context, DefaultTaskConfigRequest) (DefaultTaskConfigResponse, error)
// DefaultTaskAssets will be passed down to execution unit as files
// if DryRun is true in PluginOptions, should not throw error for missing inputs
DefaultTaskAssets(context.Context, DefaultTaskAssetsRequest) (DefaultTaskAssetsResponse, error)
// CompileTaskAssets overrides default asset compilation
CompileTaskAssets(context.Context, CompileTaskAssetsRequest) (CompileTaskAssetsResponse, error)
// GenerateTaskDestination derive destination from config and assets
GenerateTaskDestination(context.Context, GenerateTaskDestinationRequest) (GenerateTaskDestinationResponse, error)
// GetDependencies returns names of job destination on which this unit
// is dependent on
GenerateTaskDependencies(context.Context, GenerateTaskDependenciesRequest) (GenerateTaskDependenciesResponse, error)
}
type PluginOptions struct {
DryRun bool
}
type GetTaskSchemaRequest struct{}
type GetTaskSchemaResponse struct {
// Name should as simple as possible with no special characters
// should start with a character, better if all lowercase
Name string
Description string
// Image is the full path to docker container that will be
// scheduled for execution
Image string
// SecretPath will be mounted inside the container as volume
// e.g. /opt/secret/auth.json
// here auth.json should be a key in kube secret which gets
// translated to a file mounted in provided path
SecretPath string
}
type PluginQuestion struct {
Name string
Prompt string
Help string
Default string
Multiselect []string
SubQuestions []PluginSubQuestion
}
type PluginSubQuestion struct {
// IfValue is used as an if condition to match with user input
// if user value matches this only then ask sub questions
IfValue string
Questions PluginQuestions
}
type PluginQuestions []PluginQuestion
func (q PluginQuestions) Get(name string) (PluginQuestion, bool) {
for _, que := range q {
if strings.ToLower(que.Name) == strings.ToLower(name) {
return que, true
}
}
return PluginQuestion{}, false
}
type PluginAnswer struct {
Question PluginQuestion
Value string
}
type PluginAnswers []PluginAnswer
func (ans PluginAnswers) Get(name string) (PluginAnswer, bool) {
for _, a := range ans {
if strings.ToLower(a.Question.Name) == strings.ToLower(name) {
return a, true
}
}
return PluginAnswer{}, false
}
type GetTaskQuestionsRequest struct {
JobName string
PluginOptions
}
type GetTaskQuestionsResponse struct {
Questions PluginQuestions
}
type ValidateTaskQuestionRequest struct {
PluginOptions
Answer PluginAnswer
}
type ValidateTaskQuestionResponse struct {
Success bool
Error string
}
type TaskPluginConfig struct {
Name string
Value string
}
type TaskPluginConfigs []TaskPluginConfig
func (c TaskPluginConfigs) Get(name string) (TaskPluginConfig, bool) {
for _, con := range c {
if strings.ToLower(con.Name) == strings.ToLower(name) {
return con, true
}
}
return TaskPluginConfig{}, false
}
func (c TaskPluginConfigs) FromJobSpec(jobSpecConfig JobSpecConfigs) TaskPluginConfigs {
taskPluginConfigs := TaskPluginConfigs{}
for _, c := range jobSpecConfig {
taskPluginConfigs = append(taskPluginConfigs, TaskPluginConfig{
Name: c.Name,
Value: c.Value,
})
}
return taskPluginConfigs
}
func (c TaskPluginConfigs) ToJobSpec() JobSpecConfigs {
jsConfigs := JobSpecConfigs{}
for _, c := range c {
jsConfigs = append(jsConfigs, JobSpecConfigItem{
Name: c.Name,
Value: c.Value,
})
}
return jsConfigs
}
type DefaultTaskConfigRequest struct {
PluginOptions
Answers PluginAnswers
}
type DefaultTaskConfigResponse struct {
Config TaskPluginConfigs
}
type TaskPluginAsset struct {
Name string
Value string
}
type TaskPluginAssets []TaskPluginAsset
func (c TaskPluginAssets) Get(name string) (TaskPluginAsset, bool) {
for _, con := range c {
if strings.ToLower(con.Name) == strings.ToLower(name) {
return con, true
}
}
return TaskPluginAsset{}, false
}
func (c TaskPluginAssets) FromJobSpec(jobSpecAssets JobAssets) TaskPluginAssets {
taskPluginAssets := TaskPluginAssets{}
for _, c := range jobSpecAssets.GetAll() {
taskPluginAssets = append(taskPluginAssets, TaskPluginAsset{
Name: c.Name,
Value: c.Value,
})
}
return taskPluginAssets
}
func (c TaskPluginAssets) ToJobSpec() *JobAssets {
jsAssets := []JobSpecAsset{}
for _, c := range c {
jsAssets = append(jsAssets, JobSpecAsset{
Name: c.Name,
Value: c.Value,
})
}
return JobAssets{}.New(jsAssets)
}
type DefaultTaskAssetsRequest struct {
PluginOptions
Answers PluginAnswers
}
type DefaultTaskAssetsResponse struct {
Assets TaskPluginAssets
}
type CompileTaskAssetsRequest struct {
PluginOptions
// Task configs
Config TaskPluginConfigs
TaskWindow JobSpecTaskWindow
// Job assets
Assets TaskPluginAssets
// the instance for which these assets are being compiled for
InstanceData []InstanceSpecData
InstanceSchedule time.Time
}
type CompileTaskAssetsResponse struct {
Assets TaskPluginAssets
}
type GenerateTaskDestinationRequest struct {
// Task configs
Config TaskPluginConfigs
// Job assets
Assets TaskPluginAssets
// Job project
Project ProjectSpec
PluginOptions
}
type GenerateTaskDestinationResponse struct {
Destination string
}
type GenerateTaskDependenciesRequest struct {
// Task configs
Config TaskPluginConfigs
// Job assets
Assets TaskPluginAssets
// Job project
Project ProjectSpec
PluginOptions
}
type GenerateTaskDependenciesResponse struct {
Dependencies []string
}
var (
// TaskRegistry is a list of tasks that are supported as base task in a job
TaskRegistry TaskPluginRepository = NewTaskPluginRepository()
ErrUnsupportedTask = errors.New("unsupported task requested")
)
type TaskPluginRepository interface {
GetByName(string) (TaskPlugin, error)
GetAll() []TaskPlugin
Add(TaskPlugin) error
}
type supportedTasks struct {
data map[string]TaskPlugin
}
func (s *supportedTasks) GetByName(name string) (TaskPlugin, error) {
if unit, ok := s.data[name]; ok {
return unit, nil
}
return nil, errors.Wrap(ErrUnsupportedTask, name)
}
func (s *supportedTasks) GetAll() []TaskPlugin {
var list []TaskPlugin
for _, unit := range s.data {
list = append(list, unit)
}
return list
}
func (s *supportedTasks) Add(newUnit TaskPlugin) error {
schema, err := newUnit.GetTaskSchema(context.Background(), GetTaskSchemaRequest{})
if err != nil {
return err
}
if schema.Name == "" {
return errors.New("task name cannot be empty")
}
// check if name is already used
if _, ok := s.data[schema.Name]; ok {
return errors.Errorf("task name already in use %s", schema.Name)
}
// image is a required field
if schema.Image == "" {
return errors.New("task image cannot be empty")
}
// check if we can add the provided task
nAssets, err := newUnit.DefaultTaskAssets(context.Background(), DefaultTaskAssetsRequest{
PluginOptions: PluginOptions{
DryRun: true,
},
})
if err != nil {
return err
}
for _, existingTask := range s.data {
response, _ := existingTask.DefaultTaskAssets(context.Background(), DefaultTaskAssetsRequest{
PluginOptions: PluginOptions{
DryRun: true,
},
})
// config file names need to be unique in assets folder
// so each asset name should be unique
for _, ekey := range response.Assets {
for _, nkey := range nAssets.Assets {
if nkey.Name == ekey.Name {
return errors.Errorf("asset file name already in use %s", nkey.Name)
}
}
}
}
s.data[schema.Name] = newUnit
return nil
}
func NewTaskPluginRepository() *supportedTasks {
return &supportedTasks{data: map[string]TaskPlugin{}}
}
| 3c46aedc252780beaa41a504895db63d6dbfe7bc | [
"Markdown",
"Go"
] | 13 | Go | vianhazman/optimus | b346d125040ca2c77db34347bd7b974c272c9993 | 7a8270aff526726c98e242d54d4200fe10e24750 |
refs/heads/master | <file_sep>#include "myvec.h"
#include <stdio.h>
#include <stdlib.h>
#include <sys/time.h>
#include <time.h>
#define ITER_NUM 128
#define MSG_NUM 100000
int main(int argc, char **argv) {
srand(time(NULL));
char buffer[128];
for (int i = 0; i < 128; i++) {
buffer[i] = (rand() % 26) + 'a';
}
myvec vec;
origin ori;
timeval t1, t2, t3, t4;
gettimeofday(&t1, NULL);
for (int i = 0; i < ITER_NUM; i++) {
for (int j = 0; j < MSG_NUM; j++) {
vec.append(buffer, (rand() % 128) + 1);
}
}
gettimeofday(&t2, NULL);
gettimeofday(&t3, NULL);
for (int i = 0; i < ITER_NUM; i++) {
for (int j = 0; j < MSG_NUM; j++) {
ori.append(buffer, (rand() % 128) + 1);
}
}
gettimeofday(&t4, NULL);
int dur1 = (t2.tv_sec - t1.tv_sec) * 1000000 + (t2.tv_usec - t1.tv_usec);
int dur2 = (t4.tv_sec - t1.tv_sec) * 1000000 + (t3.tv_usec - t1.tv_usec);
printf("myvec: %d us\n", dur1);
printf("origin: %d us\n", dur2);
}<file_sep>#ifndef MY_VEC_H_
#define MY_VEC_H_
#include <assert.h>
#include <stdlib.h>
#include <string.h>
#include <vector>
#define BLOCK_SIZE 128
#define MIN(a, b) ((a) > (b) ? (b) : (a))
#define ROUND_UP(bytes, align) (((bytes) + (align)-1) & ~((align)-1))
class myvec {
public:
myvec() : length_(0), capacity_(BLOCK_SIZE) {
buf_ = (char *)malloc(BLOCK_SIZE);
}
~myvec() {
if (buf_ != NULL) {
free(buf_);
}
}
void append(char *str, size_t len) {
if (len + length_ > capacity_) {
capacity_ = ROUND_UP(MIN((capacity_ << 1), length_ + len), BLOCK_SIZE);
buf_ = (char *)realloc(buf_, capacity_);
}
assert(buf_ != NULL);
memcpy(&buf_[length_], str, len);
}
private:
char *buf_;
size_t length_;
size_t capacity_;
};
class origin {
public:
origin() {}
~origin() {}
void append(char *str, size_t len) {
buf_.insert(buf_.end(), (const char *)str, (const char *)str + len);
}
private:
std::vector<char> buf_;
};
#undef BLOCK_SIZE
#endif | 0d6d149ecd03823c52704d7a81fd061b6a78f1f8 | [
"C++"
] | 2 | C++ | luoxiaojian/archive | 0985e5f959120557f259c56fdb733a54e5456b5e | 9bd3f0476985a1ef40ef3755245a304ef3767144 |
refs/heads/master | <repo_name>maxiadlovskii/video_test<file_sep>/main2.js
window.onload = function() {
var video = document.querySelector('video');
var video2 = $('.vjs-tech').get(0);
document.body.addEventListener('touchend', function(event){
if(event.target.className == 'vjs-tech' && ($('.vjs-control-bar').css( 'opacity' ) > 0)){
if(video2.paused){
video2.play();
} else if(!video2.paused){
video2.pause();
};
};
});
video2.addEventListener('pause', function(){
if (!video2.seeking){
$('.vjs-big-play-button').show();
$('.vjs-big-play-button').animate({opacity:1}, 200);
}
});
video2.addEventListener('seeking', function(){
//$('.vjs-big-play-button').animate({opacity:0}, 200);
$('.vjs-big-play-button').hide();
});
/*
video2.addEventListener('seeked', function(){
if(video.paused){
$('.vjs-big-play-button').show();
//$('.vjs-big-play-button').animate({opacity:1}, 200);
}
});
*/
video2.addEventListener('play', function(){
$('.vjs-big-play-button').animate({opacity:0}, 200);
setTimeout(function(){$('.vjs-big-play-button').hide()}, 200);
});
video2.addEventListener('ended', function(){
$('.vjs-big-play-button').show();
$('.vjs-big-play-button').animate({opacity:1}, 200);
});
};
| e125433e107f739a4f5b017dc90b857c4b3dd052 | [
"JavaScript"
] | 1 | JavaScript | maxiadlovskii/video_test | 5f80a8843db2981cf37444ba0cb8d9713ac27f2e | aef1bcb82cea58d984a66dce9144f40404854052 |
refs/heads/main | <repo_name>odedahay/MEAN-eShop-Project-<file_sep>/backend/models/order.js
const mongoose = require('mongoose');
const orderSchema = mongoose.Schema({
name: String,
image: String,
countInStock: {
type: Number,
required: true
}
});
exports.Order = mongoose.model('Order', orderSchema);<file_sep>/backend/models/user.js
const mongoose = require('mongoose');
const userSchema = mongoose.Schema({
name: {
type: String,
required: true
},
email: {type: String, required: true},
passwordHash: {type: String, required: true},
phone: {type: String, required: true},
isAdmin: {type: Boolean, default: false},
street: {type: String, default: ''},
address: {type: String, default: ''},
zip: {type: String, default: ''},
city: {type: String, default: ''},
country: {type: String, default: ''},
});
userSchema.virtual('id').get(function () {
return this._id.toHexString();
});
userSchema.set('toJSON', {
virtuals: true
});
exports.User = mongoose.model('User', userSchema);
exports.userSchema = userSchema;<file_sep>/README.md
* MEAN - PROJECT | 443d6d81deb4d532b093a7d033ecb6b95a5f2c45 | [
"JavaScript",
"Markdown"
] | 3 | JavaScript | odedahay/MEAN-eShop-Project- | 2690e578cd19067e2f022233410cb9fd6f6e1477 | 258c0500d03c16dd4bd56a190385500c09f0db65 |
refs/heads/master | <repo_name>codedoubt/rise-up<file_sep>/js/assets.js
const assets =[
'ballon.png',
'guard.png'
]
<file_sep>/js/logic.js
const Guard = {
pos: {
x: null,
y: null
},
hitObstacle: false,
}
const type = ['rect', 'circle', 'square', 'star'];
const Obstacle = {
pos: {
x: null,
y: null,
},
type: type[rnd(type.length)],
hitBallon: false,
hitGuard: false
}
function collide(obj1, obj2) {
let x1 = obj1.pos.x;
let x2 = obj2.pos.x;
let y1 = obj1.pos.y;
let y2 = obj2.pos.y;
let dist = Math.sqrt((x1-x2)*(x1-x2) + (y1- y2)*(y1 -y2));
if(dist<=48){
return true;
}
return false;
}
<file_sep>/README.md
# Rise Up
A simple game clone of rise up game. You can play it [here](https://codedoubt.github.io/rise-up).
;
<file_sep>/js/base.js
const $ = e => document.querySelector(e);
//this function return a random number based on input value
function rnd(n) {
return Math.floor(Math.random() * n);
}
| 88871b5cf7a0fe6133a6bc3aec1321e54be20bc2 | [
"JavaScript",
"Markdown"
] | 4 | JavaScript | codedoubt/rise-up | 1f716ab7834cd2cf7f459d42917bcfa539fda010 | 34f560a1f3ad707ea66ab814b4e2d53ca2549021 |
refs/heads/master | <file_sep>1. What is React JS? How does it differ from other JavaScript Frameworks?
- It's a framework for creating interactive user interfaces. With React you use components, which return JSX, to make up the UI.
2. Explain briefly the React Component Lifecycle. Name three of the methods that are a part of the lifecycle and what they do.
- componentDidMount() runs right after the component is added to the DOM.
- componentWillUnmount() runs right before a component is deleted from the DOM
- componentWillMount() runs right before the component is rendered/ added to the DOM.
3. Briefly describe some of the differences between a `Class/Stateful component` and a `Functional/Presentational component`.
- A class component is similar to a class in JS. Class components have a state, which holds all of the information about that component inside of it. With a class component, you also have the ability to make methods within the component to interact with the state.
- A functional component will take in props and apply them to the JSX that's being returned. There is no state in a functional component, it just returns the JSX for the component.<file_sep>import React from 'react';
import './Profile.css';
const Profile = (props) => {
return (
<li className='profile'>
<div>Name: {props.profile.name}</div>
<div>Birth Year: {props.profile.birth_year}</div>
<div>Gender: {props.profile.gender}</div>
<div>Height: {props.profile.height}</div>
<div>Mass: {props.profile.mass}</div>
<div>Skin: {props.profile.skin_color}</div>
<div>Hair: {props.profile.hair_color}</div>
<div>Eye Color: {props.profile.eye_color}</div>
</li>
)
}
export default Profile; | 26e1f3f12133134056aa43b4bbcba70e4c913241 | [
"Markdown",
"JavaScript"
] | 2 | Markdown | dtacheny/Sprint-Challenge---React | 5a1fc13a879d7b5427749a4f36ee2673eee89d45 | 596aa47d98e6b9d2efc5e0053c8a926eceaae634 |
refs/heads/Rui.La | <repo_name>larui529/Dev<file_sep>/SQLs/get_labels.sql
--this Rui's sql code to modified based on Xiaowei's SQLs/get_labels
create table #tmpTargetDate
(
TargetDate Datetime -- cutoff_date, for create table, need var name and var type
)
diststyle all;
INSERT INTO #tmpTargetDate
(TargetDate)
VALUES
(
'$cutoff_date' -- Interface for setting cut-off date.
);
Create table #tmpDate --Generate Last One Year Data by month. And Future 3 Month Data.
(
Month0 Datetime,
Month1 Datetime,
Month2 Datetime,
Month3 Datetime,
Month4 Datetime,
Month5 Datetime,
Month6 Datetime,
Month12 Datetime,
Month18 Datetime,
Month24 Datetime,
Month
)
diststyle all;
Insert into #tmpDate
Select
dateadd(month, 0, t.TargetDate),
dateadd(month, -1, t.TargetDate),
dateadd(month, -2, t.TargetDate),
dateadd(month, -3, t.TargetDate),
dateadd(month, -4, t.TargetDate),
dateadd(month, -5, t.TargetDate),
dateadd(month, -6, t.TargetDate),
dateadd(month, -12, t.TargetDate),
dateadd(month, -18, t.TargetDate),
dateadd(month, -24, t.TargetDate)
FROM #tmpTargetDate as t
;
Create temp table #tmpDoctorID
(
DoctorID varchar(30)
)
sortkey
(
DoctorID
);
Insert into #tmpDoctorID
Select
Distinct a.AccountID
From fct.[Order] as o
Inner Join dim.Accounts as a on o.DoctorID = a.AccountID
and a.AccountClosed = 0 and a.IsTestAccount = 0 and a.InHouseAccount = 0 AND a.codonly = 0
Cross Join #tmpDate as d
Where
o.DateInvoicedLocalDTS between '2010-01-01' and d.Month0
and
o.originfacilityid in (10) --,20) -- '10' means only GL.
and
o.ordertype = 'New' --That means doctor still orders something.
-- limit 5000;
;
CREATE TABLE #tmpExcludeProductLines
(
ProductLine VARCHAR(50) PRIMARY KEY
)
;
INSERT INTO #tmpExcludeProductLines
( ProductLine
)
SELECT
'SHIPPING'
UNION
SELECT
'SAMPLE'
UNION
SELECT
'license'
UNION
SELECT
'literature'
UNION
SELECT
'ped sample sales'
UNION
SELECT
'training courses'
;
Update #tmpExcludeProductLines
SET ProductLine = upper(ProductLine)
;
CREATE TABLE #tmpOrderItem
(
OrderID INT,
DoctorID VARCHAR(50) ,
DateInvoiced DATETIME ,
TotalCharge decimal(14,2) ,
PF_ProductGroup VARCHAR(50) ,
PF_ProductLine VARCHAR(50),
Quantity NUMERIC(11,5)
-- TransactionType VARCHAR(50) ,
-- RemakeDiscount decimal(14,2) ,
-- Discount decimal(14,2) ,
-- ProductID VARCHAR(50) ,
-- DiscountID varchar(60),
-- DueDateLocalDTS datetime,
-- OrderProductID int,
-- PF_DepartmentID varchar(120),
--
)
-- diststyle all
distkey
(
DoctorID
)
sortkey
(
DateInvoiced,
OrderID,
PF_ProductGroup,
PF_ProductLine,
DoctorID
-- OrderProductID,
-- TransactionType,
-- TotalCharge,
-- RemakeDiscount,
-- Discount,
-- DiscountID,
-- DueDateLocalDTS,
-- PF_DepartmentID
);
INSERT INTO #tmpOrderItem
(
OrderID ,
DoctorID ,
DateInvoiced ,
TotalCharge ,
PF_ProductGroup ,
PF_ProductLine,
Quantity
-- TransactionType ,
-- RemakeDiscount ,
-- Discount ,
-- ProductID ,
-- DiscountID,
-- DueDateLocalDTS,
-- OrderProductID,
-- PF_DepartmentID,
)
SELECT
o.OrderID ,
o.DoctorID ,
o.DateInvoicedLocalDTS ,
oi.TotalCharge ,
p.PF_ProductGroup ,
p.PF_ProductLine,
oi.Quantity
/* oi.TransactionType ,
oi.RemakeDiscount ,
oi.Discount ,
oi.ProductID ,
oi.discountid,
o.duedatelocaldts,
oi.OrderProductID,
p.PF_DepartmentID,
*/
FROM
fct.Order AS o
Inner join #tmpDoctorID as di on o.DoctorID = di.DoctorID
Inner Join #tmpDate as d on o.dateinvoicedlocaldts BETWEEN '2010-01-01' AND d.Month0
INNER JOIN fct.OrderItem AS oi
ON oi.OrderID = o.OrderID
INNER JOIN dim.Products AS p
ON p.ProductID = oi.ProductID
AND upper(p.PF_ProductLine) NOT IN (
Select ProductLine from #tmpExcludeProductLines )
AND p.PF_DepartmentID NOT IN ( 'GLIDEWELL DIRECT' )
AND p.pf_isactualunit = 1
AND UPPER(oi.transactiontype) in ('NEW')
-- GROUP BY o.orderid, o.doctorid, o.DateInvoicedLocalDTS
;
SELECT toi.doctorid, toi.orderid, toi.dateinvoiced, 'pg_' + toi.pf_productgroup AS product_group,
'pl_' + toi.pf_productline AS product_line,
sum(toi.totalcharge) AS totalcharge, sum(toi.quantity) AS totalquantity
FROM #tmpOrderItem AS toi
GROUP BY toi.doctorid, toi.orderid, toi.dateinvoiced, toi.pf_productgroup, toi.pf_productline
;
<file_sep>/SQLs/get_labels_Rui.sql
--this Rui's sql code to modified based on Xiaowei's SQLs/get_labels
create table #tmpTargetDate
(
TargetDate Datetime -- cutoff_date, for create table, need var name and var type
)
diststyle all;
INSERT INTO #tmpTargetDate
(TargetDate)
VALUES
(
'$cutoff_date' -- Interface for setting cut-off date.
);
Create table #tmpDate --Generate Last One Year Data by month. And Future 3 Month Data.
(
Month0 Datetime,
Month1 Datetime,
Month2 Datetime,
Month3 Datetime,
Month4 Datetime,
Month5 Datetime,
Month6 Datetime,
Month12 Datetime,
Month18 Datetime,
Month24 Datetime,
Month1Future Datetime,
Month3Future Datetime,
Month6Future Datetime,
Month9Future Datetime,
MOnth12Future Datetime
)
diststyle all;
Insert into #tmpDate
Select
dateadd(month, 0, t.TargetDate), --previous month
dateadd(month, -1, t.TargetDate),
dateadd(month, -2, t.TargetDate),
dateadd(month, -3, t.TargetDate),
dateadd(month, -4, t.TargetDate),
dateadd(month, -5, t.TargetDate),
dateadd(month, -6, t.TargetDate),
dateadd(month, -12, t.TargetDate),
dateadd(month, -18, t.TargetDate),
dateadd(month, -24, t.TargetDate),
dateadd(month, +1, t.TargetDate), --the future month
dateadd(month, +3, t.TargetDate),
dateadd(month, +6, t.TargetDate),
dateadd(month, +9, t.TargetDate),
dateadd(month, +12, t.TargetDate)
FROM #tmpTargetDate as t
;
--DEBUG
-- select * from #tmpDate;
Create temp table #tmpDoctorID -- this is to creat a tmp table with doctor who ordered in given time period
(
DoctorID varchar(30)
)
sortkey -- sort key is a way to sort output data
(
DoctorID
);
-- the @DoctorIDs@ parameter below's format is like ('10-1234567')
Insert into #tmpDoctorID
Select
Distinct a.AccountID
From fct.[Order] as o
Inner Join dim.Accounts as a on o.DoctorID = a.AccountID -- doctor who ordered before
and a.AccountClosed = 0 and a.IsTestAccount = 0 and a.InHouseAccount = 0 AND a.codonly = 0 -- some accounts are created for test
Cross Join #tmpDate as d -- cross join with tmp table date to define doctors ordered product in certain time
Where
o.DateInvoicedLocalDTS between '2010-01-01' and d.Month0 -- ordered product from '2010-01-01' to now
and
o.originfacilityid in (10) --,20) -- '10' means only GL.
and
o.ordertype = 'New' --That means doctor still orders something.
-- limit 5000;
;
CREATE TABLE #tmpExcludeProductLines --some productline need to be exclude for the orders
(
ProductLine VARCHAR(50) PRIMARY KEY
)
;
INSERT INTO #tmpExcludeProductLines
( ProductLine
)
SELECT
'SHIPPING'
UNION
SELECT
'SAMPLE'
UNION
SELECT
'license'
UNION
SELECT
'literature'
UNION
SELECT
'ped sample sales'
UNION
SELECT
'training courses'
;
Update #tmpExcludeProductLines -- update all the tmpExcludeProductline to be upper case
SET ProductLine = upper(ProductLine)
;
CREATE TABLE #tmpIncludeProductLines
(
ProductLine VARCHAR(50) PRIMARY KEY
)
;
INSERT INTO #tmpIncludeProductLines
(
SELECT 'BIOTEMPS' union
SELECT 'BRUXZIR' union
SELECT 'CAPTEK' union
SELECT 'COMPOSITE' union
SELECT 'CUSTOM ABUTMENT' union
SELECT 'CZ' union
SELECT 'DENTURE' union
SELECT 'DESIGN' union
SELECT 'DWAX' union
SELECT 'EMAX' union
SELECT 'EMPRESS' union
SELECT 'FLIPPER' union
SELECT 'FULL CAST' union
SELECT 'GZ' union
SELECT 'IMPLANT' union
SELECT 'IMPLANT BAR' union
SELECT 'IMPLANT DENTURE' union
SELECT 'IMPLANT INCLUSIVE' union
SELECT 'IMPLANT MANUF COMPONENT' union
SELECT 'IMPLANT FLIPPER' union
SELECT 'IMPLANT MISC' union
SELECT 'IMPLANT SMILE COMPOSER' UNION
SELECT 'IMPLANT STENT' union
SELECT 'LAVA' union
SELECT 'LAVA ULTIMATE' union
SELECT 'NIGHTGUARD' union
SELECT 'OBSIDIAN' union
SELECT 'OVERDENTURE' union
SELECT 'PARTIAL' union
SELECT 'PFM' union
SELECT 'PLAYSAFE' union
SELECT 'PREMISE' union
SELECT 'PROCERA' union
SELECT 'RETAINER' union
SELECT 'SLEEP DEVICE' union
SELECT 'VALPLAST'
)
;
CREATE TABLE #tmpOrderItem
(
OrderID INT, -- order id
DoctorID VARCHAR(50) ,
DateInvoiced DATETIME , --order invoced date
TotalCharge decimal(14,2) , -- price
PF_ProductGroup VARCHAR(50) , -- product group
PF_ProductLine VARCHAR(50), -- product line
Quantity NUMERIC(11,5), -- number of purchase
TransactionType VARCHAR(50) , -- type of transactions
RemakeDiscount decimal(14,2) , -- discount for the remake
Discount decimal(14,2) , -- discount on this order
ProductID VARCHAR(50) , -- product ID of this order
DiscountID varchar(60), -- discount ID
DueDateLocalDTS datetime, --due date of this order
OrderProductID int, -- order product ID
PF_DepartmentID varchar(120)
--
)
-- diststyle all
distkey
(
DoctorID -- distkey usually split data evenly in slice
)
sortkey
(
DateInvoiced,
OrderID,
PF_ProductGroup,
PF_ProductLine,
DoctorID,
OrderProductID,
TransactionType,
RemakeDiscount,
TotalCharge,
Discount,
DiscountID,
DueDateLocalDTS,
PF_DepartmentID
);
INSERT INTO #tmpOrderItem
(
OrderID ,
DoctorID ,
DateInvoiced ,
TotalCharge ,
PF_ProductGroup ,
PF_ProductLine,
Quantity,
TransactionType ,
RemakeDiscount ,
Discount ,
ProductID ,
DiscountID,
DueDateLocalDTS,
OrderProductID,
PF_DepartmentID,
)
SELECT
o.OrderID ,
o.DoctorID ,
o.DateInvoicedLocalDTS ,
oi.TotalCharge ,
p.PF_ProductGroup ,
p.PF_ProductLine,
oi.Quantity,
oi.TransactionType ,
oi.RemakeDiscount ,
oi.Discount ,
oi.ProductID ,
oi.discountid,
o.duedatelocaldts,
oi.OrderProductID,
p.PF_DepartmentID,
FROM
fct.Order AS o
Inner join #tmpDoctorID as di on o.DoctorID = di.DoctorID
Inner Join #tmpDate as d on o.dateinvoicedlocaldts BETWEEN '2010-01-01' AND d.Month0 -- order of time from '2010-01-01' to now
INNER JOIN fct.OrderItem AS oi
ON oi.OrderID = o.OrderID
INNER JOIN dim.Products AS p
ON p.ProductID = oi.ProductID
AND upper(p.PF_ProductLine) IN (
Select ProductLine from #tmpIncludeProductLines )
AND p.PF_DepartmentID NOT IN ( 'GLIDEWELL DIRECT' )
AND p.pf_isactualunit = 1
AND UPPER(oi.transactiontype) in ('NEW')
-- GROUP BY o.orderid, o.doctorid, o.DateInvoicedLocalDTS
;
CREATE TABLE #tmpAccountMonth
(
DoctorID VARCHAR (30) ,
RowID VARCHAR (100),
Month1 DATETIME ,
Month2 DATETIME ,
Month3 DATETIME ,
Month4 DATETIME ,
Month5 DATETIME ,
Month6 DATETIME ,
Month12 DATETIME ,
Month18 DATETIME ,
Month24 DATETIME,
Month0 DATETIME,
Month1Future DATETIME,
Month3Future DATETIME,
Month6Future DATETIME,
Month9Future DATETIME,
Month12Future DATETIME
)
diststyle all
sortkey
(
DoctorID
)
;
INSERT INTO #tmpAccountMonth
SELECT d.DoctorID,
concat(CAST (trunc(t.Month0) as varchar (10)), concat (cast (' ' as varchar(1)), d.DoctorID)) as RowID,
t.Month1,
t.Month2,
t.Month3,
t.Month4,
t.Month5,
t.Month6,
t.Month12,
t.Month18,
t.Month24,
t.Month0,
t.Month1Future,
t.Month3Future,
t.Month6Future,
t.Month9Future,
t.Month12Future
from #tmpDoctorID as d
cross join #tmpDate as t
;
-- select * from #tmpAccountMonth limit 100;
-- DEBUG
-----------------------------------------
---Doctor/Month total sales
-----------------------------------------
SELECT
cd.DoctorID ,
cd.Month0 ,
SUM(CASE WHEN s.DateInvoiced BETWEEN cd.Month1 AND cd.Month0
THEN SUM(ISNULL(s.TotalCharge, 0))
ELSE 0
END) AS Month1_NetSales ,
SUM(CASE WHEN s.DateInvoiced BETWEEN cd.Month2 AND cd.Month0
THEN SUM(ISNULL(s.TotalCharge, 0))
ELSE 0
END) AS Month2_NetSales ,
SUM(CASE WHEN s.DateInvoiced BETWEEN cd.Month3 AND cd.Month0
THEN SUM(ISNULL(s.TotalCharge, 0))
ELSE 0
END) AS Month3_NetSales ,
SUM(CASE WHEN s.DateInvoiced BETWEEN cd.Month6 AND cd.Month0
THEN SUM(ISNULL(s.TotalCharge, 0))
ELSE 0
END) AS Month6_NetSales ,
SUM(CASE WHEN s.DateInvoiced BETWEEN cd.Month12 AND cd.Month0
THEN SUM(ISNULL(s.TotalCharge, 0))
ELSE 0
END) AS Month12_NetSales ,
SUM(CASE WHEN s.DateInvoiced BETWEEN cd.Month18 AND cd.Month0
THEN SUM(ISNULL(s.TotalCharge, 0))
ELSE 0
END) AS Month18_NetSales ,
SUM(CASE WHEN s.DateInvoiced BETWEEN cd.Month24 AND cd.Month0
THEN SUM(ISNULL(s.TotalCharge, 0))
ELSE 0
END) AS Month24_NetSales ,
SUM(CASE WHEN s.DateInvoiced BETWEEN cd.Month0 AND cd.Month1Future
THEN SUM(ISNULL(s.TotalCharge, 0))
ELSE 0
END) AS Month1Future_NetSales ,
SUM(CASE WHEN s.DateInvoiced BETWEEN cd.Month0 AND cd.Month3Future
THEN SUM(ISNULL(s.TotalCharge, 0))
ELSE 0
END) AS Month3Future_NetSales ,
SUM(CASE WHEN s.DateInvoiced BETWEEN cd.Month0 AND cd.Month6Future
THEN SUM(ISNULL(s.TotalCharge, 0))
ELSE 0
END) AS Month6Future_NetSales ,
SUM(CASE WHEN s.DateInvoiced BETWEEN cd.Month0 AND cd.Month9Future
THEN SUM(ISNULL(s.TotalCharge, 0))
ELSE 0
END) AS Month9Future_NetSales ,
SUM(CASE WHEN s.DateInvoiced BETWEEN cd.Month0 AND cd.Month12Future
THEN SUM(ISNULL(s.TotalCharge, 0))
ELSE 0
END) AS Month12Future_NetSales ,
SUM(CASE WHEN s.DateInvoiced <= cd.Month0
THEN SUM(ISNULL(s.TotalCharge, 0))
ELSE 0
END) AS TotalHistoricalSales
-- INTO
-- #doctorMonthlyNetSales
FROM
#tmpAccountMonth AS cd
INNER JOIN #tmpOrderItem AS s
ON s.DoctorID = cd.DoctorID
GROUP BY
cd.DoctorID ,
cd.Month0
ORDER BY
cd.DoctorID ,
cd.Month0
; | ea3b2cd521146e4c2c458e1dda8c1f2169be67ac | [
"SQL"
] | 2 | SQL | larui529/Dev | 850e14a76a230b97b9888932a307fc5a049303c1 | dc261abe60f539e2c821e2e6a5f463f65d1af526 |
refs/heads/master | <repo_name>xTachyon/RedstoneInside<file_sep>/src/hasserver.hpp
#pragma once
namespace redi {
class Server;
class HasServer {
public:
HasServer(Server& serv)
: server(serv) {}
virtual ~HasServer() = default;
Server& getServer() { return server; }
const Server& getServer() const { return server; }
protected:
Server& server;
};
}<file_sep>/src/protocol/CMakeLists.txt
project(redi CXX)
set(SOURCE_FILES
PARENT_SCOPE
${CMAKE_CURRENT_SOURCE_DIR}/packet.cxx)<file_sep>/src/world/chunkserializer.cpp
#include "../sizeliteraloperators.hpp"
#include "chunkserializer.hpp"
namespace redi {
namespace world {
ChunkSerializer::ChunkSerializer(nbt::root_tag& root, const Chunk& chunk)
: chunk(chunk), root(resolve(root)) {}
void ChunkSerializer::operator()() {
writeMisc();
writeSections();
}
void ChunkSerializer::writeMisc() {
root["xPos"] = chunk.position.x;
root["zPos"] = chunk.position.z;
root["InhabitedTime"] = chunk.inhabitedTime;
}
nbt::tag_compound& ChunkSerializer::resolve(nbt::root_tag& root) {
root["Level"] = nbt::create(nbt::tag_type::type_compound);
return root["Level"].getCompound();
}
void ChunkSerializer::writeSections() {
root["Sections"] = nbt::create(nbt::tag_type::type_list);
nbt::tag_list& list = root["Sections"].getList();
for (std::uint8_t i = 0; i < 16; ++i) {
writeSection(list, i);
}
}
void ChunkSerializer::writeSection(nbt::tag_list& list, std::uint8_t y) {
std::vector<sbyte> buffer;
nbt::tag_compound comp;
std::int16_t yy = y * y;
{
buffer.resize(4_KB);
if (!writeBlocks(reinterpret_cast<byte*>(buffer.data()), yy)) {
return;
}
comp["Blocks"] = nbt::tag_byte_array(std::move(buffer));
}
{
// add
}
{
buffer.resize(2_KB);
writeData(reinterpret_cast<byte*>(buffer.data()), yy);
comp["Data"] = nbt::tag_byte_array(std::move(buffer));
}
{
buffer.resize(2_KB);
writeBlockLight(reinterpret_cast<byte*>(buffer.data()), yy);
comp["BlockLight"] = nbt::tag_byte_array(std::move(buffer));
}
{
buffer.resize(2_KB);
writeSkyLight(reinterpret_cast<byte*>(buffer.data()), yy);
comp["SkyLight"] = nbt::tag_byte_array(std::move(buffer));
}
{ comp["Y"] = nbt::tag_byte(y); }
list.push_back(std::move(comp));
}
bool ChunkSerializer::writeBlocks(byte* bytes, std::int16_t yy) {
bool has = false;
for (std::uint8_t y = 0; y < 16; ++y) {
for (std::uint8_t z = 0; z < 16; ++z) {
for (std::uint8_t x = 0; x < 16; ++x) {
*bytes = static_cast<byte>(chunk(x, y + yy, z).type);
if (*bytes != 0) {
has = true;
}
++bytes;
}
}
}
return has;
}
void ChunkSerializer::writeData(byte* bytes, std::int16_t yy) {
for (std::uint8_t y = 0; y < 16; ++y) {
for (std::uint8_t z = 0; z < 16; ++z) {
for (std::uint8_t x = 0; x < 16; x += 2) {
*bytes = util::createNibble(chunk(x, y + yy, z).data,
chunk(x + 1, y + yy, z).data);
++bytes;
}
}
}
}
void ChunkSerializer::writeBlockLight(byte* bytes, int16_t yy) {
for (std::uint8_t y = 0; y < 16; ++y) {
for (std::uint8_t z = 0; z < 16; ++z) {
for (std::uint8_t x = 0; x < 16; x += 2) {
*bytes = util::createNibble(chunk(x, y + yy, z).blocklight,
chunk(x + 1, y + yy, z).blocklight);
}
}
}
}
void ChunkSerializer::writeSkyLight(byte* bytes, std::int16_t yy) {
for (std::uint8_t y = 0; y < 16; ++y) {
for (std::uint8_t z = 0; z < 16; ++z) {
for (std::uint8_t x = 0; x < 16; x += 2) {
*bytes = util::createNibble(chunk(x, y + yy, z).skylight,
chunk(x + 1, y + yy, z).skylight);
}
}
}
}
} // namespace world
} // namespace redi
<file_sep>/src/nbt/value.hpp
#pragma once
#include <memory>
#include <vector>
#include "tag.hpp"
#include "prettyprinter.hpp"
#include "array.hpp"
namespace redi::nbt {
class tag_value {
public:
tag_value() = default;
tag_value(const tag_value& obj);
tag_value(tag_value&& obj) = default;
explicit tag_value(tag&& tag);
explicit tag_value(nbt_byte x);
explicit tag_value(nbt_short x);
explicit tag_value(nbt_int x);
explicit tag_value(nbt_long x);
explicit tag_value(nbt_float x);
explicit tag_value(nbt_double x);
explicit tag_value(nbt_string_view x);
explicit tag_value(nbt_string&& x);
explicit tag_value(tag_unique_ptr&& ptr);
explicit tag_value(std::nullptr_t x);
tag_value& operator=(const tag_value& other);
tag_value& operator=(const tag& tag);
tag_value& operator=(tag&& tag);
tag_value& operator=(tag_unique_ptr&& ptr);
tag_value& operator=(std::int8_t x);
tag_value& operator=(std::int16_t x);
tag_value& operator=(std::int32_t x);
tag_value& operator=(std::int64_t x);
tag_value& operator=(float x);
tag_value& operator=(double x);
tag_value& operator=(const std::string& x);
tag_value& operator=(std::string&& x);
tag_value& operator=(std::nullptr_t x);
tag_value& operator=(tag_value&& other) noexcept;
tag_value& operator[](const nbt_string& key);
tag_value& operator[](nbt_string&& key);
tag_value& operator[](const char* key);
explicit operator bool() const { return static_cast<bool>(data); }
const tag& get() const { return *data; }
tag& get() { return *data; }
// void assign(tag&& tag);
tag_type get_type() const;
static tag_type get_type(const tag_unique_ptr& ptr);
nbt_byte& getByte();
nbt_short& getShort();
nbt_int& getInt();
nbt_long& getLong();
nbt_float& getFloat();
nbt_double& getDouble();
tag_byte_array_container& getByteArray();
nbt_string& getString();
tag_list& getList();
tag_compound& getCompound();
tag_int_array_container& getIntArray();
tag_long_array_container& getLongArray();
const nbt_byte& getByte() const;
const nbt_short& getShort() const;
const nbt_int& getInt() const;
const nbt_long& getLong() const;
const nbt_float& getFloat() const;
const nbt_double& getDouble() const;
const tag_byte_array_container& getByteArray() const;
const nbt_string& getString() const;
const tag_list& getList() const;
const tag_compound& getCompound() const;
const tag_int_array_container& getIntArray() const;
const tag_long_array_container& getLongArray() const;
void visit(nbt_visitor&);
void visit(const_nbt_visitor&) const;
private:
std::unique_ptr<tag> data;
void throwIfNot(tag_type type) const;
void throwIfNullOrIsNot(tag_type type) const;
};
} // namespace redi::nbt<file_sep>/src/world/chunkmanager.cpp
#include <boost/filesystem.hpp>
#include "chunkmanager.hpp"
#include "../server.hpp"
namespace fs = boost::filesystem;
namespace redi {
namespace world {
ChunkManager::ChunkManager(Server& server, const std::string& regiondir,
WorldGenerator generator)
: server(server), workIO(server.getWorkIO()),
mRegionDirectory(regiondir + "/region"), mGenerator(generator) {
fs::create_directories(mRegionDirectory);
}
void ChunkManager::loadChunk(const Vector2i& coords, PlayerSharedPtr player) {
Vector2i regionCoords(
world::AnvilRegion::getRegionCoordsFromChunkCoords(coords));
if (regions.count(regionCoords) == 0) {
regions[regionCoords] =
std::make_shared<world::MemoryRegion>(*this, workIO, regionCoords);
}
regions[regionCoords]->loadChunk(coords, player);
}
void ChunkManager::unloadRegion(const Vector2i& pos) { regions.erase(pos); }
bool ChunkManager::isChunkLoaded(const Vector2i& coords) const {
Vector2i regionCoords(
world::AnvilRegion::getRegionCoordsFromChunkCoords(coords));
if (regions.count(regionCoords) == 0) {
return false;
}
return regions.at(regionCoords)->isLoaded(coords);
}
ChunkHolder ChunkManager::operator()(const Vector2i& coords) const {
if (!isChunkLoaded(coords)) {
throw std::runtime_error("Chunk is not loaded");
}
Vector2i regionCoords =
world::AnvilRegion::getRegionCoordsFromChunkCoords(coords);
// auto& ch = *regions.at(regionCoords);
// ChunkHolder c(ch, coords);
// return c;
// return (*regions.at(regionCoords))[coords];
return ChunkHolder(*regions.at(regionCoords), coords);
}
} // namespace world
} // namespace redi<file_sep>/src/protocol/packets/server/statuspackets.cpp
#include "statuspackets.hpp"
#include "../../packetwriter.hpp"
#include "../packethandler.hpp"
#include "../../../server.hpp"
namespace redi::packets {
Ping::Ping(i64 payload) : payload(payload) {}
Ping::Ping(PacketReader& packet) { read(packet); }
void Ping::read(PacketReader& packet) { payload = packet.readLong(); }
void Ping::process(PacketHandler& handler) { handler.handleStatusPing(*this); }
Pong::Pong(i64 payload) : payload(payload) {}
void Pong::write(ByteBuffer& buffer) {
PacketWriter packet(buffer, SendID);
packet.writeLong(payload);
}
Request::Request(PacketReader& packet) { read(packet); }
void Request::read(PacketReader&) {}
void Request::process(PacketHandler& handler) {
handler.handleStatusRequest(*this);
}
Response::Response(Server& server) : server(server) {}
void Response::write(ByteBuffer& buffer) {
const ServerConfig& config = server.getServerConfiguration();
nlohmann::json j;
j["description"]["text"] = config.motd;
j["version"]["name"] = "RedstoneInside";
j["version"]["protocol"] = 316;
j["players"]["max"] = config.maxPlayers;
j["players"]["online"] = server.getOnlinePlayersNumber();
j["players"]["sample"] = nlohmann::json::array();
if (!config.iconb64.empty()) {
j["favicon"] = config.iconb64;
}
for (const auto& player : server.getOnlinePlayers()) {
nlohmann::json c;
c["id"] = boost::lexical_cast<std::string>(player->getUUID());
c["name"] = player->getUsername();
j["players"]["sample"].push_back(c);
}
PacketWriter packet(buffer, SendID);
packet.writeString(j.dump());
}
}<file_sep>/src/messages/playerposition.hpp
#pragma once
#include "event.hpp"
#include "../player.hpp"
#include "../vectorn.hpp"
namespace redi {
struct EventPlayerPosition : public Event, public Vector3d {
bool onGround;
Player& player;
EventPlayerPosition(Player& player, double x = 0.0, double y = 0.0,
double z = 0.0, bool onGround = true)
: Event(EventType::PlayerPosition), Vector3d(x, y, z), onGround(onGround),
player(player) {}
};
} // namespace redi<file_sep>/src/world/chunkdeseriazer.cpp
#include "chunkdeseriazer.hpp"
namespace redi {
namespace world {
ChunkDeserializer::ChunkDeserializer(Chunk& chunk, const nbt::root_tag& root)
: chunk(chunk), root(root.at("Level").getCompound()) {}
void ChunkDeserializer::operator()() {
readMisc();
readSections();
}
void ChunkDeserializer::readMisc() {
chunk.position.x = root.at("xPos").getInt();
chunk.position.z = root.at("zPos").getInt();
chunk.inhabitedTime = root.at("InhabitedTime").getLong();
}
void ChunkDeserializer::readSections() {
for (const auto& index : root.at("Sections").getList().get()) {
readSection(index.getCompound());
}
}
void ChunkDeserializer::readSection(const nbt::tag_compound& section) {
std::uint8_t y = static_cast<std::uint8_t>(section.at("Y").getByte());
y *= y;
readBlocks(section.at("Blocks").getByteArray(), y);
if (section.exists("Add")) {
readAdd(section.at("Add").getByteArray(), y);
}
readData(section.at("Data").getByteArray(), y);
readBlockLight(section.at("BlockLight").getByteArray(), y);
readSkyLight(section.at("SkyLight").getByteArray(), y);
}
void ChunkDeserializer::readBlocks(const std::vector<std::int8_t>& buffer,
std::int16_t yy) {
// const std::uint8_t* ptr =
// reinterpret_cast<const std::uint8_t*>(buffer.data());
std::size_t k = 0;
for (std::uint8_t y = 0; y < 16; ++y) {
for (std::uint8_t z = 0; z < 16; ++z) {
for (std::uint8_t x = 0; x < 16; ++x) {
chunk(x, y + yy, z).type = static_cast<BlockType>(
reinterpret_cast<const std::uint8_t&>(buffer[k++]));
}
}
}
}
void ChunkDeserializer::readAdd(const std::vector<std::int8_t>&, std::int16_t) {
// not yet
}
void ChunkDeserializer::readData(const std::vector<std::int8_t>& buffer,
std::int16_t yy) {
const std::uint8_t* ptr =
reinterpret_cast<const std::uint8_t*>(buffer.data());
std::size_t k = 0;
for (std::uint8_t y = 0; y < 16; ++y) {
for (std::uint8_t z = 0; z < 16; ++z) {
for (std::uint8_t x = 0; x < 16;) {
auto nibble = util::splitNibble(ptr[k++]);
chunk(x, y + yy, z).data = nibble.first;
++x;
chunk(x, y + yy, z).data = nibble.second;
++x;
}
}
}
}
void ChunkDeserializer::readBlockLight(const std::vector<std::int8_t>& buffer,
std::int16_t yy) {
const std::uint8_t* ptr =
reinterpret_cast<const std::uint8_t*>(buffer.data());
std::size_t k = 0;
for (std::uint8_t y = 0; y < 16; ++y) {
for (std::uint8_t z = 0; z < 16; ++z) {
for (std::uint8_t x = 0; x < 16;) {
auto nibble = util::splitNibble(ptr[k++]);
chunk(x, y + yy, z).blocklight = nibble.first;
++x;
chunk(x, y + yy, z).blocklight = nibble.second;
++x;
}
}
}
}
void ChunkDeserializer::readSkyLight(const std::vector<std::int8_t>& buffer,
std::int16_t yy) {
const std::uint8_t* ptr =
reinterpret_cast<const std::uint8_t*>(buffer.data());
std::size_t k = 0;
for (std::uint8_t y = 0; y < 16; ++y) {
for (std::uint8_t z = 0; z < 16; ++z) {
for (std::uint8_t x = 0; x < 16;) {
auto nibble = util::splitNibble(ptr[k++]);
chunk(x, y + yy, z).skylight = nibble.first;
++x;
chunk(x, y + yy, z).skylight = nibble.second;
++x;
}
}
}
}
} // namespace world
} // namespace redi<file_sep>/src/protocol/varint.hpp
#pragma once
#include <cstddef>
#include "../datatypes.hpp"
#include "../buffers.hpp"
namespace redi::protocol::varint {
template <typename T>
std::size_t encodeVarInt(MutableBuffer buffer, T value) {
constexpr byte mask = 0b01111111;
std::size_t size = 0;
do {
byte temp = value & mask;
value >>= 7;
if (value != 0) {
temp |= 0b10000000;
}
buffer.data()[size++] = temp;
} while (value > 0);
return size;
}
template <typename T>
std::pair<std::array<byte, 10>, std::size_t> encodeVarInt(T x) {
std::pair<std::array<byte, 10>, std::size_t> result;
result.second = encodeVarInt(MutableBuffer(result.first.data(), result.first.size()), x);
return result;
}
template <typename T>
size_t varint_size(T x) {
return encodeVarInt<T>(x).second;
}
bool is_complete(ConstBuffer buffer);
} // namespace redi<file_sep>/src/serverconfig.hpp
#pragma once
#include <string>
#include "bytebuffer.hpp"
namespace redi {
enum class Gamemode : std::uint8_t { Survival, Creative, Adventure, Spectator };
const char* GamemodeEnumToString(Gamemode);
enum class Dimension : std::int8_t { Nether = -1, Overworld, End };
enum class Difficulty : std::uint8_t { Peaceful, Easy, Normal, Hard };
const char* DifficultyEnumToString(Difficulty);
enum PlayerAbilitiesFlag : std::int8_t {
Invulnerable = 0x01,
Flying = 0x02,
AllowFlying = 0x04,
CreativeMode = 0x08
};
struct ServerConfig {
static const char* ConfigFilePath;
static const char* DefaultConfigFileContent;
bool onlineMode;
int maxPlayers;
std::string motd;
Gamemode gamemode;
Difficulty difficulty;
std::string levelType;
bool reducedDebugInfo;
std::string iconb64;
int port;
std::uint16_t rangeView;
std::string iconpath;
ServerConfig();
void readConfig();
void readIcon();
static void writeConfig();
};
} // namespace redi<file_sep>/src/chat/chatmanager.hpp
#pragma once
#include <nlohmann/json.hpp>
#include "../enums.hpp"
#include "../commands/commandmanager.hpp"
namespace redi {
struct EventChatMessage;
struct EventPlayerJoin;
struct EventPlayerDisconnect;
class Player;
class Server;
class ChatManager : public HasServer {
public:
ChatManager(Server& server);
void operator()(const std::string& message);
void operator()(EventChatMessage&);
void operator()(const EventPlayerJoin&);
void operator()(const EventPlayerDisconnect&);
void broadcast(const std::string& message, ChatPosition position = ChatPosition::ChatBox);
private:
commands::CommandManager& cmdmanager;
};
} // namespace redi<file_sep>/src/nbt/roottag.hpp
#pragma once
#include "compound.hpp"
namespace redi::nbt {
struct root_tag {
static constexpr tag_type type = tag_type::type_compound;
std::string name;
tag_compound compound;
tag_value& at(const std::string& key);
const tag_value& at(const std::string& key) const;
tag_value& operator[](const std::string& key);
tag_value& operator[](std::string&& key);
void visit(const_nbt_visitor& visitor) const;
};
std::ostream& operator<<(std::ostream& stream, const root_tag& root);
} // namespace redi::nbt<file_sep>/src/util/maths.cpp
#include <cmath>
#include "maths.hpp"
namespace redi {
namespace util {
float normalizeAngleDegrees(float degrees) {
float result = std::fmod(degrees + 180, 360);
if (result < 0) {
result += 360;
}
return result - 180;
}
} // namespace util
} // namespace redi<file_sep>/src/nbt/deserializer.cpp
#include "compound.hpp"
#include "roottag.hpp"
#include "deserializer.hpp"
#include "nbt.hpp"
namespace redi::nbt {
deserializer::deserializer(const ByteBuffer& buffer, size_t offset)
: buffer(buffer), offset(offset) {}
void deserializer::visit(tag_end&) {
}
void deserializer::visit(tag_byte& x) {
readNumber(x.data);
}
void deserializer::visit(tag_short& x) {
readNumber(x.data);
}
void deserializer::visit(tag_int& x) {
readNumber(x.data);
}
void deserializer::visit(tag_long& x) {
readNumber(x.data);
}
void deserializer::visit(tag_float& x) {
readNumber(x.data);
}
void deserializer::visit(tag_double& x) {
readNumber(x.data);
}
void deserializer::visit(tag_byte_array& array) {
readArray(array.data);
}
void deserializer::visit(tag_string& string) {
string.data = readString();
}
void deserializer::visit(tag_list& list) {
tag_type t = readType();
auto& data = list.getData();
auto size = static_cast<std::size_t>(readNumber<std::int32_t>());
data.reserve(size);
for (std::size_t i = 0; i < size; ++i) {
tag_unique_ptr tag = create(t);
if (t != tag_type::type_end) {
tag->visit(*this);
}
data.emplace_back(std::move(tag));
}
}
void deserializer::visit(tag_compound& compound) {
tag_type type;
nbt_string name;
while ((type = readType()) != tag_type::type_end) {
name = readString();
tag_unique_ptr tag = create(type);
if (type != tag_type::type_end) {
tag->visit(*this);
}
compound.emplace(std::move(name), std::move(tag));
}
}
void deserializer::visit(root_tag& root) {
visit(root.name, root.compound);
}
void deserializer::visit(tag_int_array& array) {
readArray(array.data);
}
void deserializer::visit(tag_long_array& array) {
readArray(array.data);
}
void deserializer::visit(nbt_string& name, tag_compound& root) {
tag_type type = readType();
if (type != tag_type::type_compound) {
throw std::runtime_error("Root tag must be compound");
}
name = readString();
visit(root);
}
template <typename T>
T deserializer::readNumber() {
need(sizeof(T));
T x;
std::copy(buffer.data() + offset, buffer.data() + offset + sizeof(T),
reinterpret_cast<std::uint8_t*>(std::addressof(x)));
offset += sizeof(T);
return boost::endian::big_to_native(x);
}
template <>
float deserializer::readNumber<float>() {
std::int32_t x = readNumber<std::int32_t>();
return util::binaryTo<std::int32_t, float>(x);
}
template <>
double deserializer::readNumber<double>() {
std::int64_t x = readNumber<std::int64_t>();
return util::binaryTo<std::int64_t, double>(x);
}
nbt_string deserializer::readString() {
std::size_t size = readNumber<std::uint16_t>();
need(size);
auto ptr = buffer.as_const_char() + offset;
std::string s(ptr, ptr + size);
offset += size;
return s;
}
tag_type deserializer::readType() {
need(sizeof(tag_type));
std::uint8_t x = buffer[offset++];
if (x > 12) {
throw std::runtime_error(std::to_string(static_cast<int>(x)) +
" is an unrecognized NBT tag");
}
return static_cast<tag_type>(x);
}
void deserializer::need(std::size_t bytes) {
if (bytes + offset > buffer.size()) {
throw std::runtime_error(std::to_string(bytes) + " is out of index");
}
}
template <typename T>
void deserializer::readNumber(T& x) {
x = readNumber<T>();
}
template<typename T>
void deserializer::readArray(std::vector<T>& data) {
auto size = static_cast<std::size_t>(readNumber<std::int32_t>());
data.reserve(data.size() + size);
for (std::size_t i = 0; i < size; ++i) {
data.emplace_back(readNumber<T>());
}
}
} // namespace redi::nbt<file_sep>/src/protocol/packetwriter.hpp
#pragma once
#include <string>
#include <boost/endian/conversion.hpp>
#include <boost/uuid/uuid.hpp>
#include "../bytebuffer.hpp"
#include "../datatypes.hpp"
namespace redi {
namespace chat {
class ChatComponent;
}
class PacketWriter {
public:
ByteBuffer& data;
PacketWriter(ByteBuffer& data, std::int32_t packetid);
operator ByteBuffer &&() { return std::move(data); }
void writeBool(bool v);
void writeByte(std::int8_t v);
void writeUByte(std::uint8_t v);
void writeShort(std::int16_t v);
void writeUShort(std::uint16_t v);
void writeInt(std::int32_t v);
void writeLong(std::int64_t v);
void writeULong(std::uint64_t v);
void writeFloat(float v);
void writeDouble(double v);
void writeString(const std::string& str);
void writeVarInt(std::int32_t v);
void writeVarInt(std::uint32_t v);
void writeVarLong(std::int64_t v);
void writeVarULong(std::uint64_t v);
void writePosition(std::int64_t x, std::int64_t y, std::int64_t z);
void writeUUID(boost::uuids::uuid uuid);
void writeAngle(double angle);
void writeChat(const chat::ChatComponent& chat);
template <typename T>
void writeVarInt(T number) {
writeVarInt(static_cast<std::int32_t>(number));
}
template <typename T>
void writeVarLong(T number) {
writeVarLong(static_cast<std::int64_t>(number));
}
template <typename T, typename K, typename L>
void writePosition(T x, K y, L z) {
writePosition(static_cast<std::int64_t>(x), static_cast<std::int64_t>(y),
static_cast<std::int64_t>(z));
}
private:
template <typename T>
void writeNumber(T number);
template <typename T>
void writeBNumber(T number);
};
} // namespace redi<file_sep>/src/nbt/type.cpp
#include "type.hpp"
namespace redi::nbt {
const char* getNBTTypeName(tag_type type) {
const char* names[] = {"TAG_End", "TAG_Byte", "TAG_Short",
"TAG_Int", "TAG_Long", "TAG_Float",
"TAG_Double", "TAG_Byte_Array", "TAG_String",
"TAG_List", "TAG_Compound", "TAG_Int_Array",
"TAG_Long_Array"};
return names[static_cast<std::size_t>(type)];
}
std::ostream& operator<<(std::ostream& stream, tag_type type) {
stream << getNBTTypeName(type);
return stream;
}
} // namespace redi::nbt<file_sep>/src/messages/events.hpp
#pragma once
#include "eventtype.hpp"
#include "event.hpp"
#include "playerjoin.hpp"
#include "playerdisconnected.hpp"
#include "sessiondisconnected.hpp"
#include "sendkeepalivering.hpp"
#include "chatmessage.hpp"
#include "statusrequest.hpp"
#include "playerlook.hpp"
#include "playerposition.hpp"
#include "playerpositionandlook.hpp"
#include "chunkloaded.hpp"<file_sep>/src/nbt/visitor.hpp
#pragma once
#include "forward.hpp"
namespace redi::nbt {
class nbt_visitor {
public:
virtual ~nbt_visitor() = 0;
virtual void visit(tag_end&) {}
virtual void visit(tag_byte&) {}
virtual void visit(tag_short&) {}
virtual void visit(tag_int&) {}
virtual void visit(tag_long&) {}
virtual void visit(tag_float&) {}
virtual void visit(tag_double&) {}
virtual void visit(tag_byte_array&) {}
virtual void visit(tag_string&) {}
virtual void visit(tag_list&) {}
virtual void visit(tag_compound&) {}
virtual void visit(root_tag&) {}
virtual void visit(tag_int_array&) {}
virtual void visit(tag_long_array&) {}
};
inline nbt_visitor::~nbt_visitor() = default;
class const_nbt_visitor {
public:
virtual ~const_nbt_visitor() = 0;
virtual void visit(const tag_end&) {}
virtual void visit(const tag_byte&) {}
virtual void visit(const tag_short&) {}
virtual void visit(const tag_int&) {}
virtual void visit(const tag_long&) {}
virtual void visit(const tag_float&) {}
virtual void visit(const tag_double&) {}
virtual void visit(const tag_byte_array&) {}
virtual void visit(const tag_string&) {}
virtual void visit(const tag_list&) {}
virtual void visit(const tag_compound&) {}
virtual void visit(const root_tag&) {}
virtual void visit(const tag_int_array&) {}
virtual void visit(const tag_long_array&) {}
};
inline const_nbt_visitor::~const_nbt_visitor() = default;
}<file_sep>/src/server.hpp
#pragma once
#include <list>
#include <condition_variable>
#include "player.hpp"
#include "serverconfig.hpp"
#include "messages/events.hpp"
#include "world.hpp"
#include "chat/chatmanager.hpp"
#include "messages/eventmanager.hpp"
#include "logger.hpp"
#include "util/threadgroup.hpp"
#include "commands/commandmanager.hpp"
#include "commands/command.hpp"
#include "networking.hpp"
namespace redi {
class Server {
public:
using PlayerList = std::list<PlayerSharedPtr>;
static constexpr std::size_t AsioThreadsNumber = 1;
/*
* Minimum 1
*/
Server();
~Server();
std::int32_t getNewEntityID() { return mEntityCount++; }
void run();
void addTask(std::function<void()> function);
void addEvent(EventUniquePtr&& ptr);
void addWorld(const std::string& worldname, const std::string& worlddir);
std::int32_t getOnlinePlayersNumber() const { return std::distance(mPlayers.begin(), mPlayers.end()); }
PlayerList& getOnlinePlayers() { return mPlayers; }
const PlayerList& getOnlinePlayers() const { return mPlayers; }
void sendMessage(const std::string& str) const { Logger::info(str); }
Player* findPlayer(const std::string& name);
EventManager& getEventManager() { return mEventManager; }
ChatManager& getChatManager() { return mChatManager; }
boost::asio::io_service& getWorkIO() { return workIoService; }
commands::CommandManager& getCommandManager() { return commandmanager; }
ServerConfig& getServerConfiguration() { return configuration; }
const ServerConfig& getServerConfiguration() const { return configuration; }
void stop();
private:
friend class EventManager;
friend class PacketHandler;
using SessionList = std::list<std::shared_ptr<Session>>;
using WorldList = std::list<World>;
ServerConfig configuration;
boost::asio::io_context workIoService;
boost::asio::io_context::work workWorkIoService;
std::unique_ptr<Networking> networking;
std::shared_ptr<Socket> connectionListener;
PlayerList mPlayers;
WorldList mWorlds;
std::int32_t mEntityCount;
ChatManager mChatManager;
EventManager mEventManager;
lockfree::Queue<std::function<void()>> mPacketsToBeHandle;
commands::CommandManager commandmanager;
std::unique_ptr<commands::Command> commands;
bool running;
SessionList sessions;
util::ThreadGroup<std::thread> asiothreads;
std::condition_variable mCondVar;
std::mutex mCondVarMutex;
std::unique_lock<std::mutex> mUniqueLock;
void handleOne();
void closeServer();
void onSocketConnected(std::shared_ptr<Socket> socket, std::string error);
};
} // namespace redi<file_sep>/src/world/chunkcolumn.hpp
#pragma once
#include <array>
#include <cstdint>
#include "block.hpp"
#include "biome.hpp"
namespace redi {
struct ChunkColumn {
static constexpr std::uint16_t BlocksPerColumn = 256;
std::array<Block, BlocksPerColumn> blocks;
Biome biome;
ChunkColumn(Biome b = Biome::Ocean) : biome(b) {}
Block& operator[](std::int32_t y) { return blocks[y]; }
const Block& operator[](std::int32_t y) const { return blocks[y]; }
};
} // namespace redi<file_sep>/src/chat/chatmanager.cpp
#include <nlohmann/json.hpp>
#include <boost/algorithm/string/trim.hpp>
#include <boost/format.hpp>
#include "chatmanager.hpp"
#include "../server.hpp"
namespace redi {
ChatManager::ChatManager(Server& server)
: HasServer(server), cmdmanager(server.getCommandManager()) {}
void ChatManager::operator()(const std::string& message) {
broadcast(message);
Logger::info(message);
}
void ChatManager::operator()(EventChatMessage& event) {
std::string& message = event.message;
boost::trim(message);
if (message.size() == 0) {
return;
}
if (message[0] == '/') {
cmdmanager(event.player, message);
return;
}
std::string json = event.player.getUsername() + ": " + event.message;
broadcast(json);
Logger::info(
(boost::format("%1%: %2%") % event.player.getUsername() % event.message)
.str());
}
void ChatManager::operator()(const EventPlayerJoin& event) {
auto& player = event.session->getPlayer();
std::string message(
(boost::format("%1% has joined the game") % player.getUsername()).str());
Logger::info(message);
broadcast(message, ChatPosition::SystemMessage);
}
void ChatManager::operator()(const EventPlayerDisconnect& event) {
std::string message(
(boost::format("%1% has left the game") % event.player.getUsername())
.str());
Logger::info(message);
broadcast(message, ChatPosition::SystemMessage);
}
void ChatManager::broadcast(const std::string& message, ChatPosition position) {
packets::ChatMessage(message, position).send(server.getOnlinePlayers());
}
} // namespace redi<file_sep>/src/world/memoryregion.cpp
#include "memoryregion.hpp"
#include "chunkmanager.hpp"
#include "../logger.hpp"
#include "../nbt/roottag.hpp"
#include "../nbt/serializer.hpp"
#include "chunkdeseriazer.hpp"
#include "chunkserializer.hpp"
#include "../messages/events.hpp"
#include "../server.hpp"
#include "../player.hpp"
namespace redi {
namespace world {
MemoryRegion::MemoryRegion(ChunkManager& manager, boost::asio::io_service& io,
const Vector2i& coords)
: workIO(io), manager(manager), regionCoordinates(coords), strand(io),
count(0) {
region.open((boost::format("%1%/r.%2%.%3%.mca") %
manager.getRegionDirectory() % regionCoordinates.x %
regionCoordinates.z)
.str(),
coords);
}
void MemoryRegion::increaseCount(const Vector2i&) {
// ++chunks[v].second;
// ++count;
}
void MemoryRegion::decreaseCount(const Vector2i&) {
// assert(chunks.count(v));
// auto& c = chunks[v].second;
// --c;
// if (c == 0) {
// unloadChunk(v);
// }
// --count;
// if (count == 0) {
// // manager.unloadRegion(regionCoordinates);
// // TODO: what happens when no chunk is used anymore ?
// }
// TODO: fix chunks here
}
void MemoryRegion::loadChunk(const Vector2i& coordinates,
PlayerSharedPtr player) {
if (player) {
playersWhoWants[coordinates].insert(player);
}
workIO.post(strand.wrap([ me = shared_from_this(), coordinates ] {
me->readChunk(coordinates);
}));
}
void MemoryRegion::unloadChunk(const Vector2i& v) {
assert(chunks.count(v));
ChunkUniquePtr ptr = std::move(chunks[v].first);
chunks.erase(v);
workIO.post(strand.wrap([
me = shared_from_this(), v, chunk = std::shared_ptr<Chunk>(std::move(ptr))
] { me->writeChunk(v, *chunk); }));
}
void MemoryRegion::writeChunk(const Vector2i& l, const Chunk& chunk) {
try {
nbt::root_tag root;
ChunkSerializer(root, chunk)();
ByteBuffer buffer;
nbt::serializer(buffer).visit(root);
region.writeChunk(l, buffer);
} catch (std::exception& e) {
Logger::error(e.what());
}
region.flush();
}
void MemoryRegion::readChunk(const Vector2i& v) {
ChunkUniquePtr chunk = std::make_unique<Chunk>();
chunk->position = v;
try {
ByteBuffer buffer;
// Anvil::ChunkReadResult result = region.readChunk(v, buffer);
// switch (result) {
// case Anvil::ChunkReadResult::OK: {
// nbt::RootTag root;
//
// nbt::Deserializer(buffer).read(root);
// ChunkDeserializer (*chunk, root)();
// } break;
//
// case Anvil::ChunkReadResult::Error: {
// Logger::error("Error reading chunk " + v.toString());
// }
//
// case Anvil::ChunkReadResult::DoesntExists: {
// manager.getWorldGenerator()->generate(*chunk);
// } break;
// }
manager.getWorldGenerator()->generate(*chunk);
} catch (std::exception& e) {
Logger::error(e.what());
manager.getWorldGenerator()->generate(*chunk);
}
manager.getServer().addEvent(
std::make_unique<events::EventChunkLoaded>(std::move(chunk), *this, v));
region.flush();
}
ChunkHolder MemoryRegion::addChunk(const Vector2i& coords,
ChunkUniquePtr&& chunk) {
ChunksMapValueType pair(std::move(chunk), 0);
chunks[coords] = std::move(pair);
ChunkHolder c(*this, coords);
return c;
}
void MemoryRegion::addChunkAndNotifyPlayers(const Vector2i& coords,
ChunkUniquePtr&& chunk) {
ChunkHolder holder(addChunk(coords, std::move(chunk)));
for (PlayerSharedPtr player : playersWhoWants[coords]) {
player->onChunkLoaded(holder);
}
playersWhoWants.erase(coords);
}
} // namespace world
} // namespace redi<file_sep>/src/commands/redicommands.hpp
#pragma once
#include "command.hpp"
namespace redi {
namespace commands {
class RediCommands : public Command {
public:
RediCommands(Server& server);
Command& operator()(CommandSender& sender, const std::string& command,
CommandArguments& args) override;
void stop(CommandSender& sender);
void position(CommandSender& sender, CommandArguments& args);
void rotation(CommandSender& sender);
void uuid(CommandSender& sender, CommandArguments& args);
void whisper(CommandSender& sender, CommandArguments& args);
void kick(CommandSender& sender, CommandArguments& args);
void doesntwork(CommandSender& sender, CommandArguments& args);
bool checkIfPlayer(CommandSender& sender);
};
}
} // namespace redi<file_sep>/src/nbt/compound.cpp
#include "serializer.hpp"
#include "deserializer.hpp"
#include "creator.hpp"
#include "compound.hpp"
namespace redi::nbt {
tag_compound::tag_compound(const tag_compound& other) { *this = other; }
tag_compound::tag_compound(std::initializer_list<value_type> list) : map(list) {}
tag_value& tag_compound::operator[](const std::string& key) { return map[key]; }
tag_value& tag_compound::operator[](std::string&& key) {
return map[std::move(key)];
}
tag_compound& tag_compound::operator=(const tag_compound& obj) {
map.clear();
for (const auto& index : obj.map) {
map.emplace(std::make_pair(index.first, index.second));
}
return *this;
}
} // namespace redi::nbt<file_sep>/src/nbt/type.hpp
#pragma once
#include <ostream>
#include <type_traits>
#include "forward.hpp"
namespace redi::nbt {
enum class tag_type : std::uint8_t {
type_end,
type_byte,
type_short,
type_int,
type_long,
type_float,
type_double,
type_byte_array,
type_string,
type_list,
type_compound,
type_int_array,
type_long_array
};
const char* getNBTTypeName(tag_type type);
std::ostream& operator<<(std::ostream& stream, tag_type type);
template <typename T>
struct type_to_number {};
template <>
struct type_to_number<nbt_byte>
: public std::integral_constant<tag_type, tag_type::type_byte> {};
template <>
struct type_to_number<nbt_short>
: public std::integral_constant<tag_type, tag_type::type_short> {};
template <>
struct type_to_number<nbt_int>
: public std::integral_constant<tag_type, tag_type::type_int> {};
template <>
struct type_to_number<nbt_long>
: public std::integral_constant<tag_type, tag_type::type_long> {};
template <>
struct type_to_number<nbt_float> : public std::integral_constant<tag_type, tag_type::type_float> {
};
template <>
struct type_to_number<nbt_double>
: public std::integral_constant<tag_type, tag_type::type_double> {};
template <>
struct type_to_number<array<nbt_byte>>
: public std::integral_constant<tag_type, tag_type::type_byte_array> {};
template <>
struct type_to_number<array<nbt_int>>
: public std::integral_constant<tag_type, tag_type::type_int_array> {};
template <>
struct type_to_number<array<nbt_long>>
: public std::integral_constant<tag_type, tag_type::type_long_array> {};
} // namespace redi::nbt<file_sep>/src/messages/playerjoin.hpp
#pragma once
#include <string>
#include "event.hpp"
#include "../player.hpp"
namespace redi {
struct EventPlayerJoin : public Event {
SessionSharedPtr session;
std::string username;
EventPlayerJoin(SessionSharedPtr session, std::string&& nick)
: Event(EventType::PlayerJoin), session(session),
username(std::move(nick)) {}
};
} // namespace redi<file_sep>/src/player.cpp
#include <chrono>
#include <boost/filesystem.hpp>
#include <boost/format.hpp>
#include "player.hpp"
#include "server.hpp"
#include "logger.hpp"
#include "util/util.hpp"
namespace asio = boost::asio;
namespace fs = boost::filesystem;
namespace redi {
Player::Player(const std::string& name, boost::uuids::uuid uuid,
std::shared_ptr<Session> session, std::int32_t id,
Server& server, World* world, Gamemode gamemode)
: HasServer(server), CommandSender(commands::CommandSenderType::Player), mUUID(uuid), mNickname(name),
mWorld(world),
session(session), gamemode(gamemode),
mSendKeepAliveTimer(server.getWorkIO()), mTeleportID(0),
mEntityID(id), hasSavedToDisk(false) {
Logger::debug((boost::format("Player %1% created") % this).str());
loadFromFile();
mLastPositionWhenChunksWasSent.x = 0;
mLastPositionWhenChunksWasSent.z = 0;
}
Player::~Player() {
Logger::debug((boost::format("Player %1% destroyed") % this).str());
bool saved = hasSavedToDisk.exchange(true);
if (!saved) {
saveToFile();
}
}
void Player::onSendKeepAliveTimer(const boost::system::error_code& error) {
using namespace std::chrono_literals;
if (!error && !session->isDisconnecting()) {
packets::KeepAlive(5).send(*session);
mSendKeepAliveTimer.expires_from_now(15s);
keepAliveNext();
}
}
void Player::keepAliveNext() {
mSendKeepAliveTimer.async_wait(boost::bind(&Player::onSendKeepAliveTimer,
shared_from_this(),
asio::placeholders::error));
}
void Player::sendPacket(const ByteBuffer& packet) {
session->sendPacket(packet);
}
void Player::sendPacket(ByteBuffer&& packet) {
session->sendPacket(std::move(packet));
}
void Player::sendMessage(const std::string& message, ChatPosition position) {
packets::ChatMessage(message, position).send(session);
}
void Player::sendMessageToSender(const std::string& message) {
sendMessage(message);
}
void Player::kick(std::string&& message) {
packets::Disconnect(std::move(message)).send(*session);
disconnect();
}
void Player::kick(const std::string& message) {
kick(std::string(message));
}
void Player::kick() {
kick("nighty-night !");
}
void Player::disconnect() {
mSendKeepAliveTimer.cancel();
session->disconnect();
if (!hasSavedToDisk) {
hasSavedToDisk = true;
saveToFile();
}
}
void Player::normalizeRotation() {
mPosition.yaw = util::normalizeAngleDegrees(mPosition.yaw);
mPosition.pitch = util::normalizeAngleDegrees(mPosition.pitch);
}
std::string Player::getPlayerDataFileName() const {
return "players/" + getUUIDasString() + ".json";
}
void Player::loadFromFile() try {
if (!fs::exists(getPlayerDataFileName())) {
mPosition.y = 50;
return;
}
nlohmann::json j =
nlohmann::json::parse(util::readFileToString(getPlayerDataFileName()));
{
nlohmann::json& position = j["position"];
mPosition.x = position[0];
mPosition.y = position[1];
mPosition.z = position[2];
}
{
nlohmann::json& rotation = j["rotation"];
mPosition.yaw = rotation[0];
mPosition.pitch = rotation[1];
}
mPosition.onGround = j["onground"];
Logger::debug((boost::format("Player %1% loaded from file") % this).str());
} catch (std::exception&) {
}
void Player::saveToFile() {
nlohmann::json j;
j["world"] = mWorld->getWorldName();
{
nlohmann::json& position = j["position"];
position.push_back(mPosition.x);
position.push_back(mPosition.y);
position.push_back(mPosition.z);
}
{
nlohmann::json& rotation = j["rotation"];
rotation.push_back(mPosition.yaw);
rotation.push_back(mPosition.pitch);
}
j["onground"] = mPosition.onGround;
j["name"] = mNickname;
std::ofstream(getPlayerDataFileName()) << j.dump(2);
Logger::debug((boost::format("Player %1% saved to file") % this).str());
}
bool operator==(const Player& l, const Player& r) { return &l == &r; }
bool operator!=(const Player& l, const Player& r) { return !(l == r); }
void Player::onEntityMovedWithLook(PlayerPosition newpos) {
using PlayerPtrVector = std::vector<Player*>;
PlayerPtrVector create;
PlayerPtrVector update;
PlayerPtrVector destroy;
PlayerPtrVector nextEntitiesInSight;
for (PlayerSharedPtr& player : server.getOnlinePlayers()) {
if (*player != *this) {
auto distance = player->getPosition().distance(mPosition);
if (distance <= 32 * 10.0) {
auto it = std::find(mEntitiesInSight.begin(), mEntitiesInSight.end(),
player.get());
if (it == mEntitiesInSight.end()) {
create.push_back(player.get());
nextEntitiesInSight.push_back(player.get());
} else {
update.push_back(player.get());
nextEntitiesInSight.push_back(player.get());
}
} else {
destroy.push_back(player.get());
}
}
}
if (create.size() > 0) {
packets::SpawnPlayer packet(*this);
for (Player* player : create) {
packet.send(*player);
}
}
if (update.size() > 0) {
std::int16_t dx = (util::floorAndCast(newpos.x * 32.0) -
util::floorAndCast(mPosition.x * 32.0)) *
128;
std::int16_t dy = (util::floorAndCast(newpos.y * 32.0) -
util::floorAndCast(mPosition.y * 32.0)) *
128;
std::int16_t dz = (util::floorAndCast(newpos.z * 32.0) -
util::floorAndCast(mPosition.z * 32.0)) *
128;
packets::EntityLookAndRelativeMove packet(mEntityID, dx, dy, dz,
mPosition.yaw, mPosition.pitch,
mPosition.onGround);
for (Player* player : update) {
packet.send(*player);
}
}
mEntitiesInSight = nextEntitiesInSight;
}
void Player::timersNext() { keepAliveNext(); }
void Player::onPositionChanged() {
if (Vector2i(static_cast<std::int32_t>(mPosition.x / 16),
static_cast<std::int32_t>(mPosition.z / 16))
.distanceSquared(mLastPositionWhenChunksWasSent) > 1) {
onUpdateChunks();
}
}
void Player::onChunkLoaded(world::ChunkHolder& chunk) {
packets::ChunkData(*chunk, chunk.getCoords()).send(session);
loadedChunks.push_back(chunk);
}
void Player::onUpdateChunks() {
auto range = getServer().getServerConfiguration().rangeView;
Vector2i playerchunk(static_cast<std::int32_t>(mPosition.x / 16),
static_cast<std::int32_t>(mPosition.z / 16));
Vector2i start(playerchunk.x - range, playerchunk.z - range - 1);
Vector2i end(playerchunk.x + range + 1, playerchunk.z + range);
std::list<world::ChunkHolder> newchunks;
world::ChunkManager& cm = mWorld->getChunkManager();
for (std::int32_t x = start.x; x < end.x; ++x) {
for (std::int32_t z = start.z; z < end.z; ++z) {
Vector2i th(x, z);
auto it = loadedChunks.end();
for (auto i = loadedChunks.begin(); i != it; ++i) {
if (i->getCoords() == th) {
it = i;
break;
}
}
if (it == loadedChunks.end()) {
if (cm.isChunkLoaded(th)) {
world::ChunkHolder chunk = cm(th);
newchunks.push_back(chunk);
packets::ChunkData(*chunk, chunk.getCoords()).send(session);
} else {
cm.loadChunk(th, shared_from_this());
}
} else {
world::ChunkHolder chunk = cm(th);
newchunks.push_back(chunk);
loadedChunks.remove_if([&chunk](const world::ChunkHolder& l) {
return l.getCoords() == chunk.getCoords();
});
}
}
}
for (const world::ChunkHolder& chunk : loadedChunks) {
packets::UnloadChunk(chunk.getCoords()).send(session);
}
loadedChunks = std::move(newchunks);
mLastPositionWhenChunksWasSent = mPosition.getChunkPosition();
}
} // namespace redi
<file_sep>/src/messages/chatmessage.hpp
#pragma once
#include "event.hpp"
#include "../player.hpp"
namespace redi {
struct EventChatMessage : public Event {
Player& player;
std::string message;
EventChatMessage(Player& player, std::string&& message)
: Event(EventType::ChatMessage), player(player),
message(std::move(message)) {}
};
} // namespace redi<file_sep>/src/world/block.hpp
#pragma once
#include <cstdint>
namespace redi {
enum class BlockType : std::uint16_t {
Air = 0,
Stone = 1,
Grass = 2,
Dirt = 3,
Cobblestone = 4,
Planks = 5,
Sapling = 6,
Bedrock = 7,
FlowingWater = 8,
Water = 9,
FlowingLava = 10,
Lava = 11,
Sand = 12,
Gravel = 13,
GoldOre = 14,
IronOre = 15,
CoalOre = 16,
Log = 17,
Leaves = 18,
Sponge = 19,
Glass = 20,
LapisOre = 21,
LapisBlock = 22,
Dispenser = 23,
Sandstone = 24,
Noteblock = 25,
Bed = 26,
GoldenRail = 27,
DetectorRail = 28,
StickyPiston = 29,
Web = 30,
Tallgrass = 31,
Deadbush = 32,
Piston = 33,
PistonHead = 34,
Wool = 35,
PistonExtension = 36,
YellowFlower = 37,
RedFlower = 38,
BrownMushroom = 39,
RedMushroom = 40,
GoldBlock = 41,
IronBlock = 42,
DoubleStoneSlab = 43,
StoneSlab = 44,
BrickBlock = 45,
Tnt = 46,
Bookshelf = 47,
MossyCobblestone = 48,
Obsidian = 49,
Torch = 50,
Fire = 51,
MobSpawner = 52,
OakStairs = 53,
Chest = 54,
RedstoneWire = 55,
DiamondOre = 56,
DiamondBlock = 57,
CraftingTable = 58,
Wheat = 59,
Farmland = 60,
Furnace = 61,
LitFurnace = 62,
StandingSign = 63,
WoodenDoor = 64,
Ladder = 65,
Rail = 66,
StoneStairs = 67,
WallSign = 68,
Lever = 69,
StonePressurePlate = 70,
IronDoor = 71,
WoodenPressurePlate = 72,
RedstoneOre = 73,
LitRedstoneOre = 74,
UnlitRedstoneTorch = 75,
RedstoneTorch = 76,
StoneButton = 77,
SnowLayer = 78,
Ice = 79,
Snow = 80,
Cactus = 81,
Clay = 82,
Reeds = 83,
Jukebox = 84,
Fence = 85,
Pumpkin = 86,
Netherrack = 87,
SoulSand = 88,
Glowstone = 89,
Portal = 90,
LitPumpkin = 91,
Cake = 92,
UnpoweredRepeater = 93,
PoweredRepeater = 94,
StainedGlass = 95,
Trapdoor = 96,
MonsterEgg = 97,
Stonebrick = 98,
BrownMushroomBlock = 99,
RedMushroomBlock = 100,
IronBars = 101,
GlassPane = 102,
MelonBlock = 103,
PumpkinStem = 104,
MelonStem = 105,
Vine = 106,
FenceGate = 107,
BrickStairs = 108,
StoneBrickStairs = 109,
Mycelium = 110,
Waterlily = 111,
NetherBrick = 112,
NetherBrickFence = 113,
NetherBrickStairs = 114,
NetherWart = 115,
EnchantingTable = 116,
BrewingStand = 117,
Cauldron = 118,
EndPortal = 119,
EndPortalFrame = 120,
EndStone = 121,
DragonEgg = 122,
RedstoneLamp = 123,
LitRedstoneLamp = 124,
DoubleWoodenSlab = 125,
WoodenSlab = 126,
Cocoa = 127,
SandstoneStairs = 128,
EmeraldOre = 129,
EnderChest = 130,
TripwireHook = 131,
Tripwire = 132,
EmeraldBlock = 133,
SpruceStairs = 134,
BirchStairs = 135,
JungleStairs = 136,
CommandBlock = 137,
Beacon = 138,
CobblestoneWall = 139,
FlowerPot = 140,
Carrots = 141,
Potatoes = 142,
WoodenButton = 143,
Skull = 144,
Anvil = 145,
TrappedChest = 146,
LightWeightedPressurePlate = 147,
HeavyWeightedPressurePlate = 148,
UnpoweredComparator = 149,
PoweredComparator = 150,
DaylightDetector = 151,
RedstoneBlock = 152,
QuartzOre = 153,
Hopper = 154,
QuartzBlock = 155,
QuartzStairs = 156,
ActivatorRail = 157,
Dropper = 158,
StainedHardenedClay = 159,
StainedGlassPane = 160,
Leaves2 = 161,
Log2 = 162,
AcaciaStairs = 163,
DarkOakStairs = 164,
Slime = 165,
Barrier = 166,
IronTrapdoor = 167,
Prismarine = 168,
SeaLantern = 169,
HayBlock = 170,
Carpet = 171,
HardenedClay = 172,
CoalBlock = 173,
PackedIce = 174,
DoublePlant = 175,
StandingBanner = 176,
WallBanner = 177,
DaylightDetectorInverted = 178,
RedSandstone = 179,
RedSandstoneStairs = 180,
DoubleStoneSlab2 = 181,
StoneSlab2 = 182,
SpruceFenceGate = 183,
BirchFenceGate = 184,
JungleFenceGate = 185,
DarkOakFenceGate = 186,
AcaciaFenceGate = 187,
SpruceFence = 188,
BirchFence = 189,
JungleFence = 190,
DarkOakFence = 191,
AcaciaFence = 192,
SpruceDoor = 193,
BirchDoor = 194,
JungleDoor = 195,
AcaciaDoor = 196,
DarkOakDoor = 197,
EndRod = 198,
ChorusPlant = 199,
ChorusFlower = 200,
PurpurBlock = 201,
PurpurPillar = 202,
PurpurStairs = 203,
PurpurDoubleSlab = 204,
PurpurSlab = 205,
EndBricks = 206,
Beetroots = 207,
GrassPath = 208,
EndGateway = 209,
RepeatingCommandBlock = 210,
ChainCommandBlock = 211,
FrostedIce = 212,
Magma = 213,
NetherWartBlock = 214,
RedNetherBrick = 215,
BoneBlock = 216,
StructureVoid = 217,
StructureBlock = 255
};
struct Block {
BlockType type;
std::uint8_t data;
std::int8_t skylight;
std::int8_t blocklight;
Block(BlockType type = BlockType::Air, std::uint8_t data = 0,
std::int8_t skylight = 0, std::int8_t blocklight = 0)
: type(type), data(data), skylight(skylight), blocklight(blocklight) {}
};
} // namespace redi<file_sep>/src/protocol/packetwriter.cpp
#include "../chat/chatcomponent.hpp"
#include "packetwriter.hpp"
namespace redi {
PacketWriter::PacketWriter(ByteBuffer& data, std::int32_t packetid)
: data(data) {
writeVarInt(packetid);
}
void PacketWriter::writeBool(bool v) {
constexpr u8 true_value = 1;
constexpr u8 false_value = 0;
data.push_back(v ? true_value : false_value);
}
void PacketWriter::writeByte(std::int8_t v) {
data.push_back(*reinterpret_cast<std::uint8_t*>(std::addressof(v)));
}
void PacketWriter::writeUByte(std::uint8_t v) { data.push_back(v); }
void PacketWriter::writeShort(std::int16_t v) { writeBNumber(v); }
void PacketWriter::writeUShort(std::uint16_t v) { writeBNumber(v); }
void PacketWriter::writeInt(std::int32_t v) { writeBNumber(v); }
void PacketWriter::writeLong(std::int64_t v) { writeBNumber(v); }
void PacketWriter::writeULong(std::uint64_t v) { writeBNumber(v); }
void PacketWriter::writeFloat(float v) {
std::int32_t c;
auto ptr = reinterpret_cast<const std::uint8_t*>(std::addressof(v));
std::copy(ptr, ptr + sizeof(v),
reinterpret_cast<std::uint8_t*>(std::addressof(c)));
writeBNumber(c);
}
void PacketWriter::writeDouble(double v) {
std::int64_t c;
auto ptr = reinterpret_cast<const std::uint8_t*>(std::addressof(v));
std::copy(ptr, ptr + sizeof(v),
reinterpret_cast<std::uint8_t*>(std::addressof(c)));
writeBNumber(c);
}
void PacketWriter::writeString(const std::string& str) {
writeVarInt(str.size());
data.append(reinterpret_cast<const std::uint8_t*>(str.data()), str.size());
}
void PacketWriter::writeVarInt(std::int32_t v) {
writeVarInt(*reinterpret_cast<std::uint32_t*>(std::addressof(v)));
}
void PacketWriter::writeVarInt(std::uint32_t v) {
do {
auto temp = std::uint8_t(v & 0b01111111);
v >>= 7;
temp |= v ? 0b10000000 : 0;
writeUByte(temp);
} while (v);
}
void PacketWriter::writeVarLong(std::int64_t v) {
writeVarULong(*reinterpret_cast<std::uint64_t*>(std::addressof(v)));
}
void PacketWriter::writeVarULong(std::uint64_t v) {
do {
auto temp = std::uint8_t(v & 0b01111111);
v >>= 7;
temp |= v ? 0b10000000 : 0;
writeUByte(temp);
} while (v);
}
void PacketWriter::writePosition(std::int64_t x, std::int64_t y,
std::int64_t z) {
writeLong(((x & 0x3FFFFFF) << 38) | ((y & 0xFFF) << 26) | (z & 0x3FFFFFF));
}
void PacketWriter::writeUUID(boost::uuids::uuid uuid) {
data.append(uuid.data, sizeof(uuid.data));
}
void PacketWriter::writeAngle(double angle) {
writeByte(static_cast<std::int8_t>(255 * angle / 360));
}
void PacketWriter::writeChat(const chat::ChatComponent& chat) {
writeString(chat.generate());
}
template <typename T>
void PacketWriter::writeNumber(T number) {
data.append(reinterpret_cast<const std::uint8_t*>(std::addressof(number)),
sizeof(T));
}
template <typename T>
void PacketWriter::writeBNumber(T number) {
writeNumber(boost::endian::native_to_big(number));
}
} // namespace redi<file_sep>/src/nbt/forward.hpp
#pragma once
#include <cstdint>
#include "datatypes.h"
namespace redi::nbt {
class tag;
template <typename T>
class basic_tag;
template <typename T>
struct primitive;
template <typename T>
struct array;
using tag_byte = primitive<nbt_byte>;
using tag_short = primitive<nbt_short>;
using tag_int = primitive<nbt_int>;
using tag_long = primitive<nbt_long>;
using tag_float = primitive<nbt_float>;
using tag_double = primitive<nbt_double>;
using tag_byte_array = array<nbt_byte>;
using tag_int_array = array<nbt_int>;
using tag_long_array = array<nbt_long>;
class tag_end;
struct tag_string;
class tag_compound;
class tag_list;
struct root_tag;
struct Deserializer;
class pretty_printer;
class serializer;
class tag_value;
class nbt_visitor;
class const_nbt_visitor;
} // namespace redi::nbt<file_sep>/src/util/maths.hpp
#pragma once
#include <cmath>
#include <cstdint>
#include <utility>
namespace redi {
namespace util {
float normalizeAngleDegrees(float degrees);
template <typename To = std::int16_t, typename From>
To floorAndCast(From x) {
return static_cast<To>(std::floor(x));
}
template <typename T, typename K>
inline std::uint8_t createNibble(const T& l, const K& r) {
std::uint8_t x = static_cast<std::uint8_t>(l);
std::uint8_t y = static_cast<std::uint8_t>(r);
return (x << 4) | y;
}
template <typename T>
inline std::pair<std::uint8_t, std::uint8_t> splitNibble(const T& l) {
std::uint8_t x = static_cast<std::uint8_t>(l);
std::pair<std::uint8_t, std::uint8_t> result;
result.first = x >> 4;
result.second = static_cast<std::uint8_t>(x & 0b1111);
return result;
}
} // namespace util
} // namespace redi<file_sep>/src/util/compressor.cpp
#include <boost/iostreams/filtering_stream.hpp>
#include <boost/iostreams/filter/gzip.hpp>
#include <boost/iostreams/filter/zlib.hpp>
#include "compressor.hpp"
using namespace boost::iostreams;
namespace redi::util::zip {
namespace zlib {
void compress(ConstBuffer input, ByteBuffer& output, CompressionLevel level) {
{
boost::iostreams::filtering_ostream os;
os.push(boost::iostreams::zlib_compressor(static_cast<int>(level)));
os.push(std::back_inserter(output));
boost::iostreams::write(os, input.asConstChar(), input.size());
}
}
ByteBuffer compress(ConstBuffer input, CompressionLevel level) {
ByteBuffer output;
compress(input, output, level);
return output;
}
void decompress(ConstBuffer input, ByteBuffer& output) {
{
filtering_ostream os;
os.push(zlib_decompressor());
os.push(std::back_inserter(output));
write(os, input.asConstChar(), input.size());
}
}
ByteBuffer decompress(ConstBuffer input) {
ByteBuffer output;
decompress(input, output);
return output;
}
}
namespace gzip {
void compress(ConstBuffer input, ByteBuffer& output, CompressionLevel level) {
{
boost::iostreams::filtering_ostream os;
os.push(boost::iostreams::gzip_compressor(static_cast<int>(level)));
os.push(std::back_inserter(output));
boost::iostreams::write(os, input.asConstChar(), input.size());
}
}
ByteBuffer compress(ConstBuffer input, CompressionLevel level) {
ByteBuffer output;
compress(input, output, level);
return output;
}
void decompress(ConstBuffer input, ByteBuffer& output) {
{
filtering_ostream os;
os.push(gzip_decompressor());
os.push(std::back_inserter(output));
write(os, input.asConstChar(), input.size());
}
}
ByteBuffer decompress(ConstBuffer input) {
ByteBuffer output;
decompress(input, output);
return output;
}
}
} // namespace redi::util::zip<file_sep>/src/nbt/serializer.cpp
#include "value.hpp"
#include "compound.hpp"
#include "serializer.hpp"
#include "roottag.hpp"
#include "nbt.hpp"
namespace redi::nbt {
serializer::serializer(ByteBuffer& buf)
: buffer(buf) {}
void serializer::visit(const tag_end&) {}
void serializer::visit(const tag_byte& x) {
write(x.data);
}
void serializer::visit(const tag_short& x) {
write(x.data);
}
void serializer::visit(const tag_int& x) {
write(x.data);
}
void serializer::visit(const tag_long& x) {
write(x.data);
}
void serializer::visit(const tag_float& x) {
write(util::binaryTo<nbt_float, nbt_int>(x.data));
}
void serializer::visit(const tag_double& x) {
write(util::binaryTo<nbt_double, nbt_long>(x.data));
}
void serializer::visit(const tag_byte_array& array) {
write(array.data.begin(), array.data.end());
}
void serializer::visit(const tag_string& x) {
write(x.data);
}
void serializer::visit(const tag_list& list) {
tag_type type = list.getListType();
auto& data = list.getData();
write(type);
write(static_cast<nbt_int>(data.size()));
for (auto& index : data) {
index.visit(*this);
}
}
void serializer::visit(const tag_compound& compound) {
for (auto& index : compound) {
auto& name = index.first;
auto& tag = index.second;
tag_type type = tag.get_type();
write(type);
write(name);
if (type != tag_type::type_end) {
tag.visit(*this);
}
}
write(tag_type::type_end);
}
void serializer::visit(const root_tag& tag) {
visit(tag.name, tag.compound);
}
void serializer::visit(const tag_int_array& array) {
write(array.data.begin(), array.data.end());
}
void serializer::visit(const tag_long_array& array) {
write(array.data.begin(), array.data.end());
}
void serializer::visit(nbt_string_view name, const tag_compound& root) {
write(tag_type::type_compound);
write(name);
visit(root);
}
template <typename T>
void serializer::write(T x) {
// Yes I can do that
boost::endian::native_to_big_inplace(x);
buffer.append(x);
}
void serializer::write(const nbt_string& string) {
write(nbt_string_view(string));
}
void serializer::write(nbt_string_view string) {
write(static_cast<std::uint16_t>(string.size()));
buffer.append(string.data(), string.size());
}
void serializer::write(tag_type type) {
write(static_cast<nbt_byte>(type));
}
template <typename Iterator>
void serializer::write(Iterator begin, Iterator end) {
write(static_cast<nbt_int>(end - begin));
std::for_each(begin, end, [this](const auto& x) {
this->write(x);
});
}
} // namespace redi::nbt<file_sep>/src/protocol/packets/server/playpackets.hpp
#pragma once
#include "../packet.hpp"
#include "../../../enums.hpp"
#include "../../../world/chunk.hpp"
#include "../../../world.hpp"
#include "../../../playerposition.hpp"
namespace redi::packets {
struct ChatMessage : public Packet {
static constexpr std::int32_t SendID = 0x0F;
std::string message;
ChatPosition position;
ChatMessage(const std::string& message = "",
ChatPosition position = ChatPosition::ChatBox);
ChatMessage(std::string&& message, ChatPosition position);
ChatMessage(PacketReader& packet);
void read(PacketReader& packet) override;
void write(ByteBuffer& buffer) override;
virtual void process(PacketHandler& handler) override;
};
struct ChunkData : public Packet {
static constexpr std::int32_t SendID = 0x20;
const Chunk& chunk;
Vector2i position;
ChunkData(const Chunk& chunk, Vector2i position);
void write(ByteBuffer& buffer) override;
};
struct Disconnect : public Packet {
static constexpr std::int32_t SendIDlogin = 0x00;
static constexpr std::int32_t SendIDplay = 0x1A;
std::string json;
bool play;
Disconnect(const std::string& json, bool play = true);
Disconnect(std::string&& json, bool play = true);
void write(ByteBuffer& buffer) override;
};
struct EntityLookAndRelativeMove : public Packet {
static constexpr std::int32_t SendID = 0x26;
std::int32_t EID;
std::int16_t deltax;
std::int16_t deltay;
std::int16_t deltaz;
float yaw;
float pitch;
bool onGround;
EntityLookAndRelativeMove(std::int32_t EID = 0, std::int16_t deltax = 0,
std::int16_t deltay = 0, std::int16_t deltaz = 0,
float yaw = 0, float pitch = 0,
bool onGround = true);
void write(ByteBuffer& buffer) override;
};
struct JoinGame : public Packet {
static constexpr std::int32_t SendID = 0x23;
Player* player;
JoinGame(Player* ptr = nullptr);
void write(ByteBuffer& buffer) override;
};
struct KeepAlive : public Packet {
static constexpr std::int32_t SendID = 0x1F;
std::int32_t keepAliveID;
KeepAlive(std::int32_t keepAliveID);
void write(ByteBuffer& buffer) override;
};
struct PlayerListItem : public Packet {
static constexpr std::int32_t SendID = 0x2D;
Player& player;
PlayerListItemAction action;
PlayerListItem(Player& player, PlayerListItemAction action);
void write(ByteBuffer& buffer) override;
};
struct PlayerLook : public Packet {
float yaw;
float pitch;
bool onGround;
PlayerLook(PacketReader& packet);
PlayerLook(float yaw = 0.0f, float pitch = 0.0f, bool onGround = true);
void read(PacketReader& packet) override;
void process(PacketHandler& handler) override;
};
struct PlayerPosition : public Packet {
double x;
double y;
double z;
bool onGround;
PlayerPosition(PacketReader& packet);
PlayerPosition(double x = 0.0, double y = 0.0, double z = 0.0,
bool onGround = true);
void read(PacketReader& packet) override;
void process(PacketHandler& handler) override;
};
struct PlayerPositionAndLook : public Packet {
static constexpr std::int32_t SendID = 0x2E;
double x;
double y;
double z;
float yaw;
float pitch;
bool onGround;
std::int32_t teleportID;
PlayerPositionAndLook(PacketReader& packet);
PlayerPositionAndLook(double x = 0.0, double y = 0.0, double z = 0.0,
float yaw = 0.0f, float pitch = 0.0f,
bool onGround = true, std::int32_t teleportID = 0);
PlayerPositionAndLook(redi::PlayerPosition position, std::int32_t teleportID);
void read(PacketReader& packet) override;
void write(ByteBuffer& buffer) override;
void process(PacketHandler& handler) override;
};
struct SpawnPlayer : public Packet {
static constexpr std::int32_t SendID = 0x05;
Player& player;
SpawnPlayer(Player& player);
void write(ByteBuffer& buffer) override;
};
struct SpawnPosition : public Packet {
static constexpr std::int32_t SendID = 0x43;
Vector3i position;
SpawnPosition() = default;
SpawnPosition(Vector3i position);
void write(ByteBuffer& buffer) override;
};
struct TimeUpdate : public Packet {
static constexpr std::int32_t SendID = 0x44;
const World& world;
explicit TimeUpdate(const World& world);
void write(ByteBuffer& buffer) override;
};
struct UnloadChunk : public Packet {
static constexpr std::int32_t SendID = 0x1D;
Vector2i position;
UnloadChunk(Vector2i position);
void write(ByteBuffer& buffer) override;
};
}<file_sep>/src/messages/eventtype.hpp
#pragma once
namespace redi {
enum class EventType {
PlayerJoin,
PlayerDisconnect,
SessionDisconnect,
SendKeepAliveRing,
ChatMessage,
StatusRequest,
PlayerPosition,
PlayerLook,
PlayerPositionAndLook,
ChunkLoaded,
ChunkUnloaded,
RegionLoaded,
RegionUnloaded
};
} // namespace redi<file_sep>/src/messages/playerdisconnected.hpp
#pragma once
#include "event.hpp"
#include "../player.hpp"
namespace redi {
struct EventPlayerDisconnect : public Event {
Player& player;
EventPlayerDisconnect(Player& player)
: Event(EventType::PlayerDisconnect), player(player) {}
};
} // namespace redi<file_sep>/src/sizeliteraloperators.hpp
#pragma once
#include <cstddef>
namespace redi {
struct SizeConstants {
static constexpr std::size_t KB = 1 << 10;
static constexpr std::size_t MB = KB << 10;
static constexpr std::size_t GB = MB << 10;
static constexpr std::size_t TB = GB << 10;
static constexpr std::size_t PB = TB << 10;
static constexpr std::size_t EB = PB << 10;
};
constexpr std::size_t operator""_KB(unsigned long long int data) {
return static_cast<std::size_t>(data * SizeConstants::KB);
}
constexpr std::size_t operator""_MB(unsigned long long int data) {
return static_cast<std::size_t>(data * SizeConstants::MB);
}
constexpr std::size_t operator""_GB(unsigned long long int data) {
return static_cast<std::size_t>(data * SizeConstants::GB);
}
constexpr std::size_t operator""_TB(unsigned long long int data) {
return static_cast<std::size_t>(data * SizeConstants::TB);
}
constexpr std::size_t operator""_PB(unsigned long long int data) {
return static_cast<std::size_t>(data * SizeConstants::PB);
}
constexpr std::size_t operator""_EB(unsigned long long int data) {
return static_cast<std::size_t>(data * SizeConstants::EB);
}
} // namespace redi<file_sep>/src/session.hpp
#pragma once
#include <atomic>
#include <memory>
#include <boost/asio.hpp>
#include "threadsafequeue.hpp"
#include "sizeliteraloperators.hpp"
#include "bytebuffer.hpp"
#include "enums.hpp"
#include "protocol/packets/packethandler.hpp"
#include "lockfree/queue.hpp"
#include "hasserver.hpp"
#include "networking.hpp"
namespace redi {
class Player;
class Server;
class Session;
using SessionUniquePtr = std::unique_ptr<Session>;
using SessionSharedPtr = std::shared_ptr<Session>;
class Session : public HasServer, public std::enable_shared_from_this<Session> {
public:
friend class Server;
friend class Player;
friend class PacketHandler;
Session(SocketSharedPtr socket, Server& server);
Session(const Session&) = delete;
Session(Session&& s) = delete;
~Session() override;
Session& operator=(const Session&) = delete;
Session& operator=(Session&&) = delete;
void sendPacket(ByteBuffer packet, const std::string& message = "");
Player& getPlayer() { return *player; }
void setPlayer(Player& player);
ConnectionState getConnectionState() const { return connectionState; }
void setConnectionState(ConnectionState s) { connectionState = s; }
bool getCompressionIsSent() const { return setCompressionIsSentVar; }
void setCompressionIsSent(bool b) { setCompressionIsSentVar = b; }
void disconnect();
void kick(const std::string& message);
bool isDisconnecting() const { return isDisconnected; }
private:
using PacketPtr = std::shared_ptr<ByteBuffer>;
using PacketQueue = ThreadSafeQueue<PacketPtr>;
SocketSharedPtr socket;
Player* player;
ConnectionState connectionState;
std::atomic_bool setCompressionIsSentVar;
PacketHandlerSharedPtr packetHandler;
std::atomic_bool isDisconnected;
std::atomic_bool isWritting;
ByteBuffer reading_buffer_vector;
byte reading_buffer[4096];
void on_read(size_t bytes, std::string error);
void deserialize_packets();
};
inline bool operator==(const Session& l, const Session& r) { return &l == &r; }
inline bool operator!=(const Session& l, const Session& r) { return !(l == r); }
} // namespace redi<file_sep>/src/commands/commandsender.cpp
#include <stdexcept>
#include "commandsender.hpp"
namespace redi {
namespace commands {
Player& CommandSender::getPlayer() {
throw std::runtime_error("NNOOOOOOOOOOOOOOOOOOOOOOPE");
}
Server& CommandSender::getSenderServer() {
throw std::runtime_error("NNOOOOOOOOOOOOOOOOOOOOOOPE");
}
void CommandSender::sendMessageToSender(const std::string&) {
throw std::runtime_error("NNOOOOOOOOOOOOOOOOOOOOOOPE");
}
const std::string& CommandSender::getSenderName() const {
throw std::runtime_error("NNOOOOOOOOOOOOOOOOOOOOOOPE");
}
Player* CommandSender::getPlayerPtr() {
return isPlayer() ? &getPlayer() : nullptr;
}
}
}<file_sep>/src/checks.cpp
#include <limits>
#include <climits>
static_assert(CHAR_BIT == 8, "A byte has to have 8 bits");
static_assert(std::numeric_limits<float>::is_iec559, "Float must be iec559");
static_assert(std::numeric_limits<double>::is_iec559, "Double must be iec559");<file_sep>/src/commands/commandsender.hpp
#pragma once
#include <string>
#include "../datatypes.hpp"
namespace redi {
class Player;
class Server;
namespace commands {
enum class CommandSenderType { Player, Server };
class CommandSender {
public:
CommandSender(CommandSenderType type)
: type(type) {}
// virtual ~CommandSender() = 0;
/*
* Don't destroy it through this destructor, please ?
*/
Player* getPlayerPtr();
virtual Player& getPlayer();
virtual Server& getSenderServer();
virtual void sendMessageToSender(const std::string& message);
virtual const std::string& getSenderName() const;
bool isPlayer() const { return type == CommandSenderType::Player; }
bool isNotPlayer() const { return !isPlayer(); }
private:
CommandSenderType type;
};
}
}<file_sep>/src/util/base64.hpp
#include <string>
#include <boost/archive/iterators/base64_from_binary.hpp>
#include <boost/archive/iterators/binary_from_base64.hpp>
#include <boost/archive/iterators/transform_width.hpp>
#include "../bytebuffer.hpp"
namespace redi {
namespace util {
class Base64Encoder {
public:
Base64Encoder() = delete;
static ByteBuffer encode(const ByteBuffer& data) {
return rawEncode<ByteBuffer, ByteBuffer>(data);
}
static ByteBuffer encode(const std::string& str) {
return rawEncode<ByteBuffer, std::string>(str);
}
static std::string encodeToString(const ByteBuffer& data) {
return rawEncode<std::string, ByteBuffer>(data);
}
static std::string encodeToString(const std::string& str) {
return rawEncode<std::string, std::string>(str);
}
private:
template <typename T, typename K>
static T rawEncode(const K& data) {
namespace it = boost::archive::iterators;
using encoder = it::base64_from_binary<
it::transform_width<typename K::const_iterator, 6, 8>>;
std::size_t pad = (3 - data.size() % 3) % 3;
T result(encoder(data.begin()), encoder(data.end()));
for (std::size_t i = 0; i < pad; ++i)
result.push_back('=');
return result;
}
};
class Base64Decoder {
public:
Base64Decoder() = delete;
static ByteBuffer decode(const ByteBuffer& data) {
return rawDecode<ByteBuffer, ByteBuffer>(data);
}
static ByteBuffer decode(const std::string& str) {
return rawDecode<ByteBuffer, std::string>(str);
}
static std::string decodeToString(const ByteBuffer& data) {
return rawDecode<std::string, ByteBuffer>(data);
}
static std::string decodeToString(const std::string& str) {
return rawDecode<std::string, std::string>(str);
}
private:
template <typename T, typename K>
static T rawDecode(const K& data) {
namespace it = boost::archive::iterators;
using decoder =
it::transform_width<it::binary_from_base64<typename K::const_iterator>,
8, 6>;
std::size_t pad = 0;
if (data[data.size() - 1] == '=') {
++pad;
if (data[data.size() - 2] == '=')
++pad;
}
T result(decoder(data.begin()), decoder(data.end()));
result.erase(result.end() - pad, result.end());
return result;
}
};
} // namespace util
} // namespace redi<file_sep>/src/protocol/varint.cpp
#include "varint.hpp"
namespace redi::protocol::varint {
bool is_complete(ConstBuffer buffer) {
for (byte b : buffer) {
if ((b & 0b10000000) == 0) {
return true;
}
}
return false;
}
} // namespace redi<file_sep>/src/servericon.hpp
#pragma once
#include <string>
#include <boost/filesystem.hpp>
namespace redi {
class ServerIcon {
public:
ServerIcon(const boost::filesystem::path& path = "icon.png");
operator const std::string() const { return getData(); }
operator bool() const { return loaded(); }
void load(const boost::filesystem::path& path = "icon.png");
const std::string& getData() const { return data; }
bool loaded() const { return data.size() != 0; }
private:
std::string data;
};
} // namespace redi<file_sep>/src/enums.hpp
#pragma once
#include <cstdint>
namespace redi {
enum class ChatPosition : std::int8_t { ChatBox, SystemMessage, AboveHotbar };
enum class ConnectionState { Handshake, Status, Login, Play };
const char* getStateName(ConnectionState s);
enum class ProtocolVersion {
V1_9_3_4 = 110,
V1_10_X = 210,
V1_11 = 315,
V1_11_2 = 316
};
enum class ChatAction { PlayerLeft, PlayerJoined };
enum class PlayerListItemAction {
AddPlayer,
UpdateGamemode,
UpdateLantecy,
UpdateDisplayName,
RemovePlayer
};
} // namespace redi<file_sep>/src/util/time.hpp
#pragma once
#include <cstdint>
namespace redi {
namespace util {
std::int32_t getUnixTimestamp();
std::int64_t getUnixTimestampMilliseconds();
std::int32_t getRandomInt32();
} // namespace util
} // namespace redi<file_sep>/src/commands/redicommands.cpp
#include "../server.hpp"
#include "redicommands.hpp"
namespace redi {
namespace commands {
RediCommands::RediCommands(Server & server)
: Command(server) {
manager.registerCommand(this, "stop");
manager.registerCommand(this, "position", {"pos"});
manager.registerCommand(this, "rotation", {"rot"});
manager.registerCommand(this, "uuid");
manager.registerCommand(this, "whisper", {"w"});
manager.registerCommand(this, "kick");
manager.registerCommand(this, "doesntwork");
}
Command& RediCommands::operator()(CommandSender& sender, const std::string& command, CommandArguments& args) {
if (command == "stop") {
stop(sender);
}
else if (command == "position") {
position(sender, args);
}
else if (command == "rotation") {
rotation(sender);
}
else if (command == "uuid") {
uuid(sender, args);
}
else if (command == "whisper") {
whisper(sender, args);
}
else if (command == "kick") {
kick(sender, args);
}
else if (command == "doesntwork") {
doesntwork(sender, args);
}
return *this;
}
void RediCommands::stop(CommandSender& sender) {
sender.getSenderServer().stop();
}
void RediCommands::position(CommandSender& sender, CommandArguments& args) {
Player* target = nullptr;
if (args.size() == 0) {
target = &sender.getPlayer();
}
else {
target = sender.getSenderServer().findPlayer(args[0]);
}
if (target) {
sender.sendMessageToSender(target->getPosition().toString());
}
else {
sender.sendMessageToSender("Cannot find the player");
}
}
void RediCommands::rotation(CommandSender& sender) {
if (!checkIfPlayer(sender)) {
return;
}
sender.sendMessageToSender((boost::format("Rotation: %1%") %
static_cast<redi::PlayerLook>(sender.getPlayer().getPosition()))
.str());
}
void RediCommands::uuid(CommandSender& sender, CommandArguments& args) {
auto* target = getPlayerOrDefaultAndSendMessageIfNot(sender, args);
if (target) {
sender.sendMessageToSender(target->getUUIDasString());
}
}
void RediCommands::whisper(CommandSender& sender, CommandArguments& args) {
if (args.size() < 2) {
sender.sendMessageToSender("Player or message empty");
}
else {
auto* player = sender.getSenderServer().findPlayer(args[0]);
if (player) {
std::string message = sender.getSenderName() + " -> " + player->getUsername() + ": ";
auto end = args.end();
for (auto it = args.begin(); it != end; ++it) {
message += *it + ' ';
}
player->sendMessageToSender(message);
}
else {
sender.sendMessageToSender("Can't find the player: " + args[0]);
}
}
}
void RediCommands::kick(CommandSender& sender, CommandArguments& args) {
auto* target = getPlayerOrDefaultAndSendMessageIfNot(sender, args);
if (target) {
target->kick();
}
}
void RediCommands::doesntwork(CommandSender& sender, CommandArguments& args) {
using namespace std::string_literals;
std::string message;
if (args.size() != 0) {
message += args[0] + ": ";
}
message += "Look buddy, doesn't work is a vague statement. Does it sit on "
"the couch all day long? "
"Does it procrastinate doing the dishes? Does it beg on the "
"street for change? Please be specific! "
"Define 'it' and what it isn't doing. Give us more details so we "
"can help you without needing to ask basic questions like what's "
"the error message?";
sender.getSenderServer().getChatManager().broadcast(message);
}
bool RediCommands::checkIfPlayer(CommandSender& sender) {
if (sender.isPlayer()) {
return true;
}
sender.sendMessageToSender("This command can only be used by player");
return false;
}
}
} // namespace redi<file_sep>/src/world/memoryregion.hpp
#pragma once
#include <map>
#include <set>
#include <boost/asio.hpp>
#include "anvilregion.hpp"
#include "chunk.hpp"
#include "anvil.hpp"
namespace redi {
class Player;
using PlayerSharedPtr = std::shared_ptr<Player>;
namespace world {
class ChunkManager;
struct ChunkHolder;
class MemoryRegion : public std::enable_shared_from_this<MemoryRegion> {
public:
MemoryRegion(ChunkManager& manager, boost::asio::io_service& io,
const Vector2i& coords);
const Chunk& operator[](const Vector2i& coords) const {
return *chunks.at(coords).first;
}
/*
* Only use those if you know what you are doing
* If you misuse it, expect crashes or memory leaks
* Or both
*/
void increaseCount(const Vector2i& v);
void decreaseCount(const Vector2i& v);
void unloadChunk(const Vector2i& v);
void loadChunk(const Vector2i& coordinates, PlayerSharedPtr player = nullptr);
bool isLoaded(const Vector2i& coordinates) const {
return chunks.count(coordinates) != 0;
}
ChunkHolder addChunk(const Vector2i& coords, ChunkUniquePtr&& chunk);
void addChunkAndNotifyPlayers(const Vector2i& coords, ChunkUniquePtr&& chunk);
private:
using ChunksMapValueType = std::pair<ChunkUniquePtr, std::int32_t>;
boost::asio::io_service& workIO;
ChunkManager& manager;
Anvil region;
Vector2i regionCoordinates;
boost::asio::io_service::strand strand;
std::map<Vector2i, ChunksMapValueType> chunks;
std::map<Vector2i, std::set<PlayerSharedPtr>> playersWhoWants;
std::int32_t count;
/*
* Only called from asio
*/
void writeChunk(const Vector2i& l, const Chunk& chunk);
void readChunk(const Vector2i& v);
};
using MemoryRegionSharedPtr = std::shared_ptr<MemoryRegion>;
struct ChunkHolder {
ChunkHolder() : ref(nullptr) {}
ChunkHolder(MemoryRegion* ref, const Vector2i& coords)
: ref(ref), coords(coords) {
inc();
}
ChunkHolder(MemoryRegion& ref, const Vector2i& coords)
: ChunkHolder(&ref, coords) {}
ChunkHolder(const ChunkHolder& chunk)
: ChunkHolder(chunk.ref, chunk.coords) {}
ChunkHolder(ChunkHolder&& chunk) {
ref = chunk.ref;
coords = chunk.coords;
chunk.ref = nullptr;
}
ChunkHolder& operator=(const ChunkHolder& chunk) {
dec();
ref = chunk.ref;
coords = chunk.coords;
inc();
return *this;
}
ChunkHolder& operator=(ChunkHolder&& chunk) {
dec();
ref = chunk.ref;
coords = chunk.coords;
return *this;
}
const Chunk& operator*() const {
if (ref) {
return (*ref)[coords];
}
throw std::runtime_error("No chunk in this ChunkHolder");
}
~ChunkHolder() { dec(); }
const Vector2i& getCoords() const { return coords; }
private:
MemoryRegion* ref;
Vector2i coords;
void inc() {
if (ref) {
ref->increaseCount(coords);
}
}
void dec() {
if (ref) {
ref->decreaseCount(coords);
}
}
};
} // namespace world
} // namespace redi<file_sep>/src/nbt/nbt.hpp
#pragma once
#include "type.hpp"
#include "tag.hpp"
#include "basic.hpp"
#include "primitive.hpp"
#include "string.hpp"
#include "compound.hpp"
#include "value.hpp"
#include "array.hpp"
#include "roottag.hpp"
#include "list.hpp"
#include "serializer.hpp"
#include "deserializer.hpp"
#include "prettyprinter.hpp"
#include "creator.hpp"<file_sep>/src/util/file.hpp
#pragma once
#include <string>
#include "../bytebuffer.hpp"
namespace redi {
namespace util {
ByteBuffer readFile(const std::string& path);
std::string readFileToString(const std::string& path);
} // namespace util
} // namespace redi<file_sep>/src/messages/playerlook.hpp
#pragma once
#include "event.hpp"
#include "../player.hpp"
#include "../playerposition.hpp"
namespace redi {
struct EventPlayerLook : public Event, public PlayerLook {
bool onGround;
Player& player;
EventPlayerLook(Player& player, float yaw = 0.0f, float pitch = 0.0f,
bool onGround = true)
: Event(EventType::PlayerLook), PlayerLook(yaw, pitch),
onGround(onGround), player(player) {}
};
} // namespace redi<file_sep>/src/nbt/creator.hpp
#pragma once
#include "tag.hpp"
#include "value.hpp"
namespace redi::nbt {
tag_unique_ptr create(tag_type t);
tag_value createValue(tag_type t);
} // namespace redi:nbt<file_sep>/src/commands/command.hpp
#pragma once
#include "../hasserver.hpp"
#include "commanddata.hpp"
#include "commandmanager.hpp"
#include "commandsender.hpp"
namespace redi {
namespace commands {
using CommandArguments = std::vector<std::string>;
class CommandManager;
class Command : HasServer {
public:
Command(Server& server);
virtual ~Command();
virtual Command& operator()(CommandSender& sender, const std::string& command,
CommandArguments& args);
protected:
CommandManager& manager;
Player* getPlayerOrDefault(CommandSender& sender, const CommandArguments& args) const;
Player* getPlayerOrDefaultAndSendMessageIfNot(CommandSender& sender, const CommandArguments& args) const;
};
}
} // namespace redi<file_sep>/src/protocol/packets/server/loginpackets.hpp
#pragma once
#include "../packet.hpp"
namespace redi::packets {
struct LoginStart : public Packet {
std::string username;
LoginStart() = default;
LoginStart(PacketReader& packet);
LoginStart(const std::string& username);
LoginStart(std::string&& username);
void read(PacketReader& packet) override;
virtual void process(PacketHandler& handler) override;
};
struct LoginSucces : public Packet {
static constexpr std::int32_t SendID = 0x02;
std::string uuid;
std::string username;
LoginSucces() = default;
LoginSucces(const std::string& uuid, const std::string& username);
LoginSucces(std::string&& uuid, std::string&& username);
void write(ByteBuffer& buffer) override;
};
struct SetCompression : public Packet {
static constexpr std::int32_t SendID = 0x03;
std::int32_t threshold;
SetCompression() = default;
SetCompression(std::int32_t threshold);
void write(ByteBuffer& buffer) override;
};
}<file_sep>/src/servericon.cpp
#include "servericon.hpp"
#include "bytebuffer.hpp"
#include "util/util.hpp"
namespace fs = boost::filesystem;
namespace redi {
ServerIcon::ServerIcon(const boost::filesystem::path& path) {
load(path);
}
void ServerIcon::load(const boost::filesystem::path& path) {
data.clear();
if (!fs::exists(path) || fs::is_directory(path)) {
return;
}
ByteBuffer buffer;
{
std::ifstream in(path.string(), std::ios::binary);
if (!in) {
return;
}
auto size = fs::file_size(path);
buffer.resize(size);
in.read(buffer.as_char(), size);
}
data = "data:image/png;base64," + util::Base64Encoder::encodeToString(buffer);
}
} // namespace redi
<file_sep>/src/world.hpp
#pragma once
#include <functional>
#include <list>
#include <string>
#include "world/chunk.hpp"
#include "world/anvilregion.hpp"
#include "vectorn.hpp"
#include "world/chunkmanager.hpp"
#include "serverconfig.hpp"
#include "hasserver.hpp"
namespace redi {
class Player;
class World : public HasServer {
public:
World(Server& server, const std::string& worldname,
const std::string& worlddir, WorldGenerator ptr,
Dimension dim = Dimension::Overworld);
world::ChunkManager& getChunkManager() { return mChunkManager; }
void addPlayer(Player& player);
void deletePlayer(Player& player);
const std::string& getWorldName() const { return mWorldName; }
std::int64_t getWorldTime() const { return worldTime; }
private:
std::string mWorldName;
std::string mDirectory;
WorldGenerator mGenerator;
world::ChunkManager mChunkManager;
Dimension dimension;
std::list<Player*> mPlayers;
std::int64_t worldTime;
};
} // namespace redi<file_sep>/src/commands/commanddata.hpp
#pragma once
#include <algorithm>
#include <string>
#include <vector>
#include "command.hpp"
namespace redi {
namespace commands {
class Command;
struct CommandData {
Command* ptr;
std::string command;
std::vector<std::string> aliases;
};
inline bool operator==(const CommandData& data, const std::string& str) {
if (data.command == str) {
return true;
}
return std::find(data.aliases.begin(), data.aliases.end(), str) != data.aliases.end();
}
}
}<file_sep>/src/util/string.hpp
#pragma once
#include <algorithm>
#include <cctype>
#include <string>
#include <sstream>
#include <typeinfo>
#include "../datatypes.hpp"
namespace redi {
namespace util {
std::string demangleTypeName(const char* str);
template <typename T>
inline std::string demangleTypeName() {
return demangleTypeName(typeid(T).name());
}
template <typename T>
inline std::string demangleTypeName(T& type) {
return demangleTypeName(typeid(type).name());
}
template <typename T>
inline std::basic_string<T> toLowercase(std::basic_string<T> str) {
for (auto& c : str) {
c = std::tolower(c, std::locale());
}
return str;
}
template <typename T>
inline std::basic_string<T> toUppercase(std::basic_string<T> str) {
for (auto& c : str) {
c = std::toupper(c, std::locale());
}
return str;
}
template <typename T>
inline std::string toString(const T& ref) {
std::ostringstream ss;
ss << ref;
return ss.str();
}
template <typename T>
inline bool noCaseCompareEqual(const std::basic_string<T>& l,
const std::basic_string<T>& r) {
if (l.size() != r.size())
return false;
for (std::size_t i = 0; i < l.size(); ++i) {
if (std::tolower(l[i]) != std::tolower(r[i]))
return false;
}
return true;
}
#ifdef _MSC_VER
template <>
inline bool noCaseCompareEqual<char>(const std::string& l,
const std::string& r) {
return _stricmp(l.c_str(), r.c_str()) == 0;
}
#endif
template <typename From, typename To>
To binaryTo(const From& val) {
static_assert(sizeof(From) == sizeof(To), "sizeof(From) == sizeof(To)");
To x;
auto f = reinterpret_cast<const std::uint8_t*>(std::addressof(val));
auto t = reinterpret_cast<std::uint8_t*>(std::addressof(x));
std::copy(f, f + sizeof(val), t);
return x;
}
} // namespace util
} // namespace redi<file_sep>/src/protocol/packetreader.hpp
#pragma once
#include <string>
#include <boost/endian/conversion.hpp>
#include "../bytebuffer.hpp"
#include "../vectorn.hpp"
#include "../buffers.hpp"
namespace redi {
class PacketReader {
public:
ConstBuffer data;
std::size_t offset;
explicit PacketReader(std::size_t offset = 0) : offset(offset) {}
explicit PacketReader(const ByteBuffer& buffer)
: PacketReader(ConstBuffer(buffer)) {}
explicit PacketReader(ConstBuffer data, std::size_t offset = 0)
: data(data), offset(offset) {}
bool readBool();
std::int8_t readByte();
std::uint8_t readUByte();
std::int16_t readShort();
std::uint16_t readUShort();
std::int32_t readInt();
std::int64_t readLong();
float readFloat();
double readDouble();
std::string readString();
std::int32_t readVarInt();
std::int64_t readVarLong();
Vector3i readPosition();
ByteBuffer readByteArray(std::size_t size);
void consumeUShort();
void consumeInt();
void consumeString();
void consumeVarInt();
static PacketReader getFromCompressedPacket(const ByteBuffer& buffer);
private:
void need(std::size_t bytes);
template <typename T>
T readNumber() {
static_assert(std::is_fundamental<T>::value, "Not fundamental ?");
need(sizeof(T));
T x;
std::copy(data.begin() + offset, data.begin() + offset + sizeof(T),
reinterpret_cast<std::uint8_t*>(&x));
offset += sizeof(T);
return x;
}
template <typename T>
T readBNumber() {
return boost::endian::big_to_native(readNumber<T>());
}
std::uint32_t readVarUInt();
std::uint64_t readVarULong();
};
} // namespace redi<file_sep>/src/nbt/prettyprinter.hpp
#pragma once
#include <string>
#include <boost/format.hpp>
#include "type.hpp"
#include "visitor.hpp"
namespace redi::nbt {
struct pretty_print_options {
nbt_int indent_size;
nbt_string indent_character;
explicit pretty_print_options(nbt_int indent_size = 2, nbt_string indent_character = " ");
};
class pretty_printer : public const_nbt_visitor {
public:
std::string string;
explicit pretty_printer(nbt_int indent = 2);
explicit pretty_printer(pretty_print_options options);
void visit(const tag_byte& x) override;
void visit(const tag_short& x) override;
void visit(const tag_int& x) override;
void visit(const tag_long& x) override;
void visit(const tag_float& x) override;
void visit(const tag_double& x) override;
void visit(const tag_byte_array& x) override;
void visit(const tag_string& x) override;
void visit(const tag_list& x) override;
void visit(const tag_compound& x) override;
void visit(const root_tag& x) override;
void visit(const tag_int_array& x) override;
void visit(const tag_long_array& x) override;
pretty_print_options options;
std::string indent_string;
void writeType(tag_type t);
void writeType(tag_type t, nbt_string_view str);
void writeIndent(nbt_int update = 0);
void writeNewLine();
void writeEntry(std::size_t size);
void writeOne(const tag& tag);
void writeArrayNumbers(nbt_string_view name, std::size_t size);
void append(nbt_string_view str);
void append(const boost::format& format);
template <typename T>
void writeNumber(T x);
};
std::ostream& operator<<(std::ostream& stream, const pretty_printer& printer);
} // namespace redi::nbt<file_sep>/src/util/random.hpp
#pragma once
#include <random>
namespace redi {
namespace util {
template <typename T>
T generateRandom(const T& min, const T& max) {
std::random_device rd;
std::mt19937 mt(rd());
std::uniform_int_distribution<T> dist(min, max);
return dist(mt);
}
template <typename T = std::mt19937>
class BasicRandom {
public:
BasicRandom()
: BasicRandom(std::random_device()()) {}
BasicRandom(typename T::result_type seed) {
rr.seed(seed);
}
template <typename K = typename T::result_type>
K nextInteger(K min = 0, K max = std::numeric_limits<K>::max()) {
std::uniform_int_distribution<K> dist(min, max);
return dist(rr);
}
template <typename K = double>
K nextReal() {
std::uniform_real_distribution<K> dist;
return dist(rr);
}
private:
T rr;
};
using Random = BasicRandom<std::mt19937>;
} // namespace util
} // namespace redi<file_sep>/src/protocol/packets/packethandler.cpp
#include <string>
#include <boost/uuid/uuid.hpp>
#include <boost/uuid/uuid_generators.hpp>
#include <boost/uuid/uuid_io.hpp>
#include <boost/lexical_cast.hpp>
#include "../../session.hpp"
#include "packethandler.hpp"
#include "../../util/util.hpp"
#include "../../server.hpp"
#include "../../player.hpp"
namespace asio = boost::asio;
namespace redi {
PacketHandler::PacketHandler(Server& server, Session& session, EventManager&)
: mServer(server), mSession(session) {}
void PacketHandler::addPacket(PacketUniquePtr&& packet) {
std::lock_guard<std::mutex> l(mMutex);
mPackets.emplace_back(std::move(packet));
}
void PacketHandler::readRaw(ConstBuffer buffer) {
PacketReader packet(buffer);
std::int32_t type = packet.readVarInt();
PacketUniquePtr ptr;
switch (mSession.getConnectionState()) {
case ConnectionState::Handshake: {
switch (type) {
case 0x00: {
packets::Handshake handshake(packet);
handleHandshake(handshake);
return;
} break;
default:
break;
}
}
break;
case ConnectionState::Login: {
switch (type) {
case 0x00: {
packets::LoginStart ls(packet);
handleLoginStart(ls);
return;
}
default:
break;
}
} break;
case ConnectionState::Status: {
switch (type) {
case 0x00:
ptr = std::make_unique<packets::Request>(packet);
break;
case 0x01:
ptr = std::make_unique<packets::Ping>(packet);
break;
default:
break;
}
} break;
case ConnectionState::Play: {
switch (type) {
case 0x02:
ptr = std::make_unique<packets::ChatMessage>(packet);
break;
case 0x0D:
ptr = std::make_unique<packets::PlayerPositionAndLook>(packet);
break;
case 0x0C:
ptr = std::make_unique<packets::PlayerPosition>(packet);
break;
case 0x0E:
ptr = std::make_unique<packets::PlayerLook>(packet);
break;
default:
break;
}
} break;
}
addPacket(std::move(ptr));
}
void PacketHandler::handleOne() {
PacketUniquePtr ptr;
{
std::lock_guard<std::mutex> l(mMutex);
if (mPackets.empty())
return;
ptr = std::move(mPackets.front());
mPackets.pop_front();
}
try {
if (ptr) {
ptr->process(*this);
}
} catch (std::exception& e) {
mSession.kick(e.what());
}
}
void PacketHandler::handleHandshake(packets::Handshake& p) {
mSession.connectionState = p.state;
}
void PacketHandler::handleStatusRequest(packets::Request&) {
packets::Response(mServer).send(mSession);
}
void PacketHandler::handleStatusPing(packets::Ping& packet) {
packets::Pong(packet.payload).send(mSession);
Server& server = mSession.getServer();
auto timer = std::make_shared<boost::asio::steady_timer>(server.getWorkIO(), asio::chrono::seconds(10));
timer->async_wait([timer, session = mSession.shared_from_this()] (const boost::system::error_code&) {
session->disconnect();
});
}
void PacketHandler::handleLoginStart(packets::LoginStart& packet) {
mServer.addEvent(std::make_unique<EventPlayerJoin>(
mSession.shared_from_this(), std::move(packet.username)));
}
void PacketHandler::handleChatMessage(packets::ChatMessage& packet) {
mServer.addEvent(std::make_unique<EventChatMessage>(
mSession.getPlayer(), std::move(packet.message)));
}
void PacketHandler::handlePlayerPositionAndLook(
packets::PlayerPositionAndLook& packet) {
PlayerPosition position = mSession.getPlayer().mPosition;
position.x = packet.x;
position.y = packet.y;
position.z = packet.z;
position.yaw = packet.yaw;
position.pitch = packet.pitch;
position.onGround = packet.onGround;
mSession.getPlayer().onEntityMovedWithLook(position);
mSession.getPlayer().mPosition = position;
mSession.getPlayer().normalizeRotation();
mSession.getPlayer().onPositionChanged();
}
void PacketHandler::handlePlayerPosition(packets::PlayerPosition& packet) {
PlayerPosition& position = mSession.getPlayer().mPosition;
position.x = packet.x;
position.y = packet.y;
position.z = packet.z;
position.onGround = packet.onGround;
mSession.getPlayer().onPositionChanged();
}
void PacketHandler::handlePlayerLook(packets::PlayerLook& packet) {
PlayerPosition& position = mSession.getPlayer().mPosition;
position.yaw = packet.yaw;
position.pitch = packet.pitch;
position.onGround = packet.onGround;
mSession.getPlayer().normalizeRotation();
}
} // namespace redi<file_sep>/README.md
# RedstoneInside
[
A C++ Minecraft server.
Dependencies:
- boost
- zlib
- nlohmann.json
Thanks to:
- ##c++, ##c++-general channels on freenode
- #mcdevs and wiki.vg
<file_sep>/src/serverconfig.cpp
#include <boost/property_tree/ptree.hpp>
#include <boost/property_tree/ini_parser.hpp>
#include "serverconfig.hpp"
#include "util/util.hpp"
#include "filesystem.hpp"
#include "logger.hpp"
namespace redi {
const char* ServerConfig::ConfigFilePath = "configuration.txt";
const char* ServerConfig::DefaultConfigFileContent =
"# Hello !\n"
"online=false\n"
"maxplayers=1472\n"
"motd=Redi - Highly flammable\n"
"gamemode=1\n"
"difficulty=0\n"
"leveltype=DEFAULT\n"
"port=25565\n"
"icon=icon.png\n"
"rangeview=5";
ServerConfig::ServerConfig() {
onlineMode = false;
maxPlayers = 1472;
motd = "Redi - Highly flammable";
gamemode = Gamemode::Creative;
difficulty = Difficulty::Peaceful;
levelType = "DEFAULT";
reducedDebugInfo = false;
port = 25565;
iconpath = "icon.png";
rangeView = 5;
if (fs::exists(ConfigFilePath)) {
try {
readConfig();
}
catch (std::exception&) {
Logger::error("Error while parsing the configuration file");
throw;
}
}
else {
writeConfig();
}
}
void ServerConfig::readConfig() {
static const char* OnlineText = "online";
static const char* MaxPlayerText = "maxplayers";
static const char* MotdText = "motd";
static const char* GamemodeText = "gamemode";
static const char* DifficultyText = "difficulty";
static const char* LevelTypeText = "leveltype";
static const char* PortText = "port";
static const char* IconText = "icon";
static const char* RangeViewText = "rangeview";
boost::property_tree::ptree tree;
/*
* Just a tree, keep scrolling.
_{\ _{\{\/}/}/}__
{/{/\}{/{/\}(\}{/\} _
{/{/\}{/{/\}(_)\}{/{/\} _
{\{/(\}\}{/{/\}\}{/){/\}\} /\}
{/{/(_)/}{\{/)\}{\(_){/}/}/}/}
_{\{/{/{\{/{/(_)/}/}/}{\(/}/}/}
{/{/{\{\{\(/}{\{\/}/}{\}(_){\/}\}
_{\{/{\{/(_)\}/}{/{/{/\}\})\}{/\}
{/{/{\{\(/}{/{\{\{\/})/}{\(_)/}/}\}
{\{\/}(_){\{\{\/}/}(_){\/}{\/}/})/}
{/{\{\/}{/{\{\{\/}/}{\{\/}/}\}(_)
{/{\{\/}{/){\{\{\/}/}{\{\(/}/}\}/}
{/{\{\/}(_){\{\{\(/}/}{\(_)/}/}\}
{/({/{\{/{\{\/}(_){\/}/}\}/}(\}
(_){/{\/}{\{\/}/}{\{\)/}/}(_)
{/{/{\{\/}{/{\{\{\(_)/}
{/{\{\{\/}/}{\{\\}/}
{){/ {\/}{\/} \}\}
(_) \.-'.-/
__...--- |'-.-'| --...__
_...--" .-' |'-.-'| ' -. ""--..__
-" ' . . ' |.'-._| ' . . ' jro
. '- ' .--' | '-.'| . ' . '
' .. |'-_.-|
. ' . _.-|-._ -|-._ . ' .
.' |'- .-| '.
..-' ' . '. `-._.-´ .' ' - .
.-' ' '-._______.-' ' .
. ~,
. . |\ . ' '-.
*/
boost::property_tree::ini_parser::read_ini(ConfigFilePath, tree);
if (tree.count(OnlineText)) {
onlineMode = tree.get<bool>(OnlineText);
}
if (tree.count(MaxPlayerText)) {
maxPlayers = tree.get<int>(MaxPlayerText);
}
if (tree.count(MotdText)) {
motd = tree.get<std::string>(MotdText);
}
if (tree.count(GamemodeText)) {
gamemode = static_cast<Gamemode>(tree.get<int>(GamemodeText));
}
if (tree.count(DifficultyText)) {
difficulty = static_cast<Difficulty>(tree.get<int>(DifficultyText));
}
if (tree.count(LevelTypeText)) {
levelType = tree.get<std::string>(LevelTypeText);
}
if (tree.count(PortText)) {
port = tree.get<int>(PortText);
}
if (tree.count(IconText)) {
iconpath = tree.get<std::string>(IconText);
readIcon();
}
if (tree.count(RangeViewText)) {
rangeView = tree.get<std::uint16_t>(RangeViewText);
}
}
/*
* Reads the server icon from disk.
*/
void ServerConfig::readIcon() {
if (fs::exists(iconpath)) {
ByteBuffer buffer = util::readFile(iconpath);
iconb64 = std::string("data:image/png;base64,") +
util::Base64Encoder::encodeToString(buffer);
/*
* Icon has to be sent encoded as base64.
*/
}
}
/*
* Writes the default configuration file.
*/
void ServerConfig::writeConfig() {
std::ofstream(ConfigFilePath) << DefaultConfigFileContent;
}
const char* GamemodeEnumToString(Gamemode g) {
const char* names[] = {"survival", "creative", "adventure", "spectator"};
return names[static_cast<std::size_t>(g)];
}
const char* DifficultyEnumToString(Difficulty d) {
const char* names[] = {"peaceful", "easy", "normal", "hard"};
return names[static_cast<std::size_t>(d)];
}
} // namespace redi
<file_sep>/src/world/terraingenerator.cpp
#include <cstdint>
#include "chunk.hpp"
#include "terraingenerator.hpp"
#include "../util/util.hpp"
namespace redi {
void TerrainGenerator::generate(Chunk& chunk) {
for (std::int32_t x = 0; x < Chunk::ChunkMaxX; ++x) {
for (std::int32_t y = 0; y < Chunk::ChunkMaxY; ++y) {
for (std::int32_t z = 0; z < Chunk::ChunkMaxZ; ++z) {
if (y == 0) {
chunk(x, y, z).type = BlockType::Bedrock;
} else if (y < 2) {
chunk(x, y, z).type = BlockType::DiamondBlock;
}
}
}
}
}
} // namespace redi<file_sep>/src/enums.cpp
#include <cstdlib>
#include "enums.hpp"
namespace redi {
const char* getStateName(ConnectionState s) {
const char* names[] = {"Handshake", "Status", "Login", "Play"};
return names[static_cast<std::size_t>(s)];
}
} // namespace redi
<file_sep>/src/networking_linux.cpp
#include <array>
#include <utility>
#include <deque>
#include <vector>
#include <memory>
#include <thread>
#include <mutex>
#include <boost/format.hpp>
#include <unistd.h>
#include <fcntl.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include "networking.hpp"
#include "logger.hpp"
namespace redi {
Socket::Socket() {
Logger::debug(boost::format("LinuxSocket %1% created") % this);
}
Socket::~Socket() {
Logger::debug(boost::format("LinuxSocket %1% destroyed") % this);
}
void Socket::set_accept_handler(socket_accept_handler handler) {
accept_handler = std::move(handler);
}
void Socket::set_read_handler(socket_read_handler handler) {
read_handler = std::move(handler);
}
void Socket::write(ConstBuffer* buffers, size_t size) {
for (size_t i = 0; i < size; ++i) {
write(buffers[i]);
}
}
#define CHECK(x) {\
if ((x) < 0) {\
throw std::runtime_error(\
(boost::format(__FILE__ ":%1% %2% %3%" ) % __LINE__ % #x % strerror(errno)).str()\
);\
}\
}
#define CHECK_DC(socket, x)\
if ((x) < 0) {\
socket->read_handler(0, (boost::format(__FILE__ ":%1% %2%" ) % __LINE__ % strerror(errno)).str());\
return;\
}
struct AutoCloseableDescriptor {
int fd;
AutoCloseableDescriptor(int fd = -1);
AutoCloseableDescriptor(AutoCloseableDescriptor&& other) noexcept;
~AutoCloseableDescriptor();
AutoCloseableDescriptor& operator=(AutoCloseableDescriptor&&);
void close();
};
AutoCloseableDescriptor::AutoCloseableDescriptor(int fd)
: fd(fd) {
if (fd != -1) {
Logger::debug(boost::format("[AutoCloseableDescriptor] Created %1%") % fd);
}
}
AutoCloseableDescriptor::AutoCloseableDescriptor(redi::AutoCloseableDescriptor&& other) noexcept {
fd = other.fd;
other.fd = -1;
}
AutoCloseableDescriptor::~AutoCloseableDescriptor() {
if (fd != -1) {
Logger::debug(boost::format("[AutoCloseableDescriptor] Closed %1%") % fd);
}
close();
}
void AutoCloseableDescriptor::close() {
if (fd != -1) {
::close(fd);
}
fd = -1;
}
AutoCloseableDescriptor& AutoCloseableDescriptor::operator=(AutoCloseableDescriptor&& other) {
close();
fd = other.fd;
other.fd = -1;
return *this;
}
class LinuxNetworking;
class LinuxSocket : public Socket {
public:
LinuxSocket(LinuxNetworking* networking);
explicit LinuxSocket(int fd, LinuxNetworking* networking);
int get_fd() const;
void read(MutableBuffer buffer) override;
void write(ConstBuffer buffer) override;
void write(ConstBuffer* buffers, size_t size) override;
void close() override;
bool can_read() const;
void on_read();
private:
friend class LinuxNetworking;
LinuxNetworking* networking;
AutoCloseableDescriptor fd;
MutableBuffer read_buffer;
std::deque<byte> write_buffer;
bool destroyed;
bool is_listener;
};
Networking::~Networking() = default;
void set_non_blocking(int fd) {
auto current = fcntl(fd, F_GETFL, 0);
CHECK(current);
CHECK(fcntl(fd, F_SETFL, fcntl(fd, F_GETFL, 0) | O_NONBLOCK));
}
class LinuxNetworking : public Networking {
public:
LinuxNetworking();
~LinuxNetworking() override;
std::shared_ptr<Socket> getListener(socket_accept_handler handler, uint16_t port) override;
void stop() override;
private:
friend class LinuxSocket;
friend struct ThreadLockable;
std::thread thread;
std::vector<std::shared_ptr<LinuxSocket>> sockets;
std::recursive_mutex mutex;
bool running;
AutoCloseableDescriptor reading_pipe;
AutoCloseableDescriptor writing_pipe;
fd_set reading_set;
fd_set writing_set;
fd_set error_set;
void network_thread();
void run_loop();
void update_list();
void handle_events();
LinuxSocket& get_socket(size_t i);
};
LinuxNetworking::LinuxNetworking()
: running(true) {
int p[2];
CHECK(pipe(p));
reading_pipe = p[0];
writing_pipe = p[1];
set_non_blocking(p[0]);
set_non_blocking(p[1]);
FD_ZERO(&reading_set);
FD_ZERO(&writing_set);
FD_ZERO(&error_set);
thread = std::thread(&LinuxNetworking::network_thread, this);
}
LinuxNetworking::~LinuxNetworking() {
thread.join();
}
std::shared_ptr<Socket> LinuxNetworking::getListener(socket_accept_handler handler, uint16_t port) {
auto listener = std::make_shared<LinuxSocket>(this);
listener->set_accept_handler(handler);
listener->is_listener = true;
set_non_blocking(listener->fd.fd);
sockaddr_in server{};
server.sin_family = AF_INET;
server.sin_addr.s_addr = htonl(INADDR_ANY);
server.sin_port = htons(port);
CHECK(bind(listener->fd.fd, (__CONST_SOCKADDR_ARG) &server, sizeof(server)));
CHECK(listen(listener->fd.fd, 20));
std::lock_guard<std::recursive_mutex> lock_guard(mutex);
sockets.push_back(listener);
CHECK(::write(writing_pipe.fd, "0", 1));
return listener;
}
void LinuxNetworking::network_thread() {
try {
run_loop();
} catch (std::exception& e) {
Logger::error(e.what());
}
}
void LinuxNetworking::run_loop() {
update_list();
while (running) {
{
std::lock_guard<std::recursive_mutex> lock_guard(mutex);
handle_events();
update_list();
}
CHECK(select(FD_SETSIZE, &reading_set, &writing_set, &error_set, nullptr));
}
}
void LinuxNetworking::update_list() {
FD_ZERO(&reading_set);
FD_ZERO(&writing_set);
FD_ZERO(&error_set);
FD_SET(reading_pipe.fd, &reading_set);
for (size_t i = 0; i < sockets.size(); ++i) {
LinuxSocket& socket = *sockets[i];
if (socket.destroyed) {
sockets.erase(sockets.begin() + i);
--i;
continue;
}
if (socket.can_read()) {
FD_SET(socket.fd.fd, &reading_set);
}
if (!socket.write_buffer.empty()) {
FD_SET(socket.fd.fd, &writing_set);
}
}
}
void LinuxNetworking::handle_events() {
FD_SET(reading_pipe.fd, &reading_set);
for (size_t i = 0; i < FD_SETSIZE; ++i) {
if (FD_ISSET(i, &error_set)) {
LinuxSocket& socket = get_socket(i);
socket.read_handler(0, "Error");
continue;
}
if (FD_ISSET(i, &reading_set)) {
if (static_cast<int>(i) == reading_pipe.fd) {
byte buffer[64 * 1024];
auto ret = read(reading_pipe.fd, buffer, sizeof(buffer));
if (ret == -1 && errno != EWOULDBLOCK) {
CHECK(read(reading_pipe.fd, buffer, sizeof(buffer)));
}
continue;
}
LinuxSocket& socket = get_socket(i);
socket.on_read();
}
if (FD_ISSET(i, &writing_set)) {
LinuxSocket& socket = get_socket(i);
byte buffer[64 * 1024];
auto to_copy = std::min(sizeof(buffer), socket.write_buffer.size());
std::copy(socket.write_buffer.begin(), socket.write_buffer.begin() + to_copy, buffer);
auto wrote = write(socket.fd.fd, buffer, to_copy);
CHECK(wrote);
// Logger::info(boost::format("Send %1% bytes") % wrote);
socket.write_buffer.erase(socket.write_buffer.begin(), socket.write_buffer.begin() + wrote);
}
}
}
LinuxSocket& LinuxNetworking::get_socket(size_t i) {
std::shared_ptr<LinuxSocket>& x = *std::find_if(sockets.begin(), sockets.end(), [i] (auto& socket) {
return socket->fd.fd == static_cast<int>(i);
});
return *x;
}
void LinuxNetworking::stop() {
std::lock_guard<std::recursive_mutex> lock_guard(mutex);
running = false;
CHECK(::write(writing_pipe.fd, "0", 1));
}
LinuxSocket::LinuxSocket(LinuxNetworking* networking)
: networking(networking), destroyed(false), is_listener(false) {
fd = socket(AF_INET, SOCK_STREAM, 0);
CHECK(fd.fd);
}
LinuxSocket::LinuxSocket(int fd, LinuxNetworking* networking)
: networking(networking), fd(fd), destroyed(false), is_listener(false) {}
int LinuxSocket::get_fd() const {
return fd.fd;
}
void LinuxSocket::read(MutableBuffer buffer) {
std::lock_guard<std::recursive_mutex> lock_guard(networking->mutex);
read_buffer = buffer;
CHECK(::write(networking->writing_pipe.fd, "0", 1));
}
void LinuxSocket::write(ConstBuffer buffer) {
std::lock_guard<std::recursive_mutex> lock_guard(networking->mutex);
write_buffer.insert(write_buffer.end(), buffer.data(), buffer.data() + buffer.size());
CHECK(::write(networking->writing_pipe.fd, "0", 1));
}
void LinuxSocket::write(ConstBuffer* buffers, size_t size) {
std::lock_guard<std::recursive_mutex> lock_guard(networking->mutex);
for (size_t i = 0; i < size; ++i) {
write(buffers[i]);
}
}
bool LinuxSocket::can_read() const {
return read_buffer.size() != 0 || accept_handler;
}
void LinuxSocket::on_read() {
if (is_listener) {
int client = accept(fd.fd, nullptr, nullptr);
CHECK(client);
set_non_blocking(client);
auto socket = std::make_shared<LinuxSocket>(client, networking);
accept_handler(socket, "");
std::lock_guard<std::recursive_mutex> lock_guard(networking->mutex);
networking->sockets.push_back(socket);
CHECK(::write(networking->writing_pipe.fd, "0", 1));
} else {
auto read_size = ::read(fd.fd, read_buffer.data(), read_buffer.size());
if (read_size == 0) {
destroyed = true;
return;
}
CHECK_DC(this, read_size);
read_buffer = MutableBuffer();
read_handler(static_cast<size_t>(read_size), "");
}
}
void LinuxSocket::close() {
std::lock_guard<std::recursive_mutex> lock_guard(networking->mutex);
destroyed = true;
CHECK(::write(networking->writing_pipe.fd, "0", 1));
}
std::unique_ptr<redi::Networking> getLinuxNetworking() {
return std::make_unique<LinuxNetworking>();
}
}<file_sep>/src/nbt/primitive.hpp
#pragma once
#include "basic.hpp"
#include "serializer.hpp"
#include "deserializer.hpp"
#include "prettyprinter.hpp"
namespace redi::nbt {
template <typename T>
struct primitive : public basic_tag<primitive<T>> {
static constexpr tag_type type = type_to_number<T>::value;
T data;
explicit primitive(T value = 0) : data(value) {}
primitive& operator=(T value) {
data = value;
return *this;
}
// explicit operator T&() { return data; }
// explicit operator T() const { return data; }
};
template <typename T>
std::ostream& operator<<(std::ostream& stream, const primitive<T>& obj) {
stream << obj.data;
return stream;
}
using tag_byte = primitive<nbt_byte>;
using tag_short = primitive<nbt_short>;
using tag_int = primitive<nbt_int>;
using tag_long = primitive<nbt_long>;
using tag_float = primitive<nbt_float>;
using tag_double = primitive<nbt_double>;
} // namespace redi::nbt<file_sep>/src/protocol/packets/server/playpackets.cpp
#include "playpackets.hpp"
#include "../../chunkserializer13.hpp"
#include "../../../player.hpp"
#include "../../../chat/chatcomponent.hpp"
#include "../../../server.hpp"
namespace redi::packets {
ChatMessage::ChatMessage(const std::string& message, ChatPosition position)
: message(message), position(position) {}
ChatMessage::ChatMessage(std::string&& message, ChatPosition position)
: message(std::move(message)), position(position) {}
ChatMessage::ChatMessage(PacketReader& packet) { read(packet); }
void ChatMessage::read(PacketReader& packet) { message = packet.readString(); }
void ChatMessage::write(ByteBuffer& buffer) {
PacketWriter packet(buffer, SendID);
packet.writeChat(message);
packet.writeByte(static_cast<std::int8_t>(position));
}
void ChatMessage::process(PacketHandler& handler) {
handler.handleChatMessage(*this);
}
ChunkData::ChunkData(const Chunk& chunk, Vector2i position)
: chunk(chunk), position(position) {}
void ChunkData::write(ByteBuffer& buffer) {
buffer = ChunkSerializer13(chunk, position)();
}
Disconnect::Disconnect(const std::string& json, bool play)
: json(json), play(play) {}
Disconnect::Disconnect(std::string&& json, bool play)
: json(std::move(json)), play(play) {}
void Disconnect::write(ByteBuffer& buffer) {
PacketWriter packet(buffer, play ? SendIDplay : SendIDlogin);
packet.writeChat(json);
}
EntityLookAndRelativeMove::EntityLookAndRelativeMove(
std::int32_t EID, std::int16_t deltax, std::int16_t deltay,
std::int16_t deltaz, float yaw, float pitch, bool onGround)
: EID(EID), deltax(deltax), deltay(deltay), deltaz(deltaz), yaw(yaw),
pitch(pitch), onGround(onGround) {}
void EntityLookAndRelativeMove::write(ByteBuffer& buffer) {
PacketWriter packet(buffer, SendID);
packet.writeVarInt(EID);
packet.writeShort(deltax);
packet.writeShort(deltay);
packet.writeShort(deltaz);
packet.writeAngle(yaw);
packet.writeAngle(pitch);
packet.writeBool(onGround);
}
JoinGame::JoinGame(Player* ptr) : player(ptr) {}
void JoinGame::write(ByteBuffer& buffer) {
using namespace std::string_literals;
if (!player)
throw std::runtime_error("Player can't be null - "s + REDI_FUNCTION);
const ServerConfig& config = player->getServer().getServerConfiguration();
PacketWriter writer(buffer, SendID);
writer.writeInt(player->getEntityID());
writer.writeUByte(static_cast<std::uint8_t>(player->getGamemode()));
writer.writeInt(static_cast<std::int32_t>(player->getDimension()));
writer.writeUByte(
static_cast<std::uint8_t>(config.difficulty));
writer.writeUByte(
static_cast<std::uint8_t>(config.maxPlayers));
writer.writeString(config.levelType);
writer.writeBool(config.reducedDebugInfo);
}
KeepAlive::KeepAlive(std::int32_t keepAliveID) : keepAliveID(keepAliveID) {}
void KeepAlive::write(ByteBuffer& buffer) {
PacketWriter packet(buffer, SendID);
packet.writeVarInt(keepAliveID);
}
PlayerListItem::PlayerListItem(Player& player, PlayerListItemAction action)
: player(player), action(action) {}
void PlayerListItem::write(ByteBuffer& buffer) {
PacketWriter packet(buffer, SendID);
packet.writeVarInt(action);
packet.writeVarInt(1);
packet.writeUUID(player.getUUID());
switch (action) {
case PlayerListItemAction::AddPlayer: {
packet.writeString(player.getUsername()); // name
packet.writeVarInt(0); // number of properties
packet.writeVarInt(player.getGamemode()); // gamemode
packet.writeVarInt(0); // ping
packet.writeBool(false); // has display name
} break;
case PlayerListItemAction::UpdateGamemode: {
packet.writeVarInt(player.getGamemode()); // gamemode
} break;
case PlayerListItemAction::UpdateLantecy: {
packet.writeVarInt(0); // ping
} break;
case PlayerListItemAction::UpdateDisplayName: {
packet.writeBool(false); // has display name
} break;
case PlayerListItemAction::RemovePlayer:
break;
}
}
PlayerLook::PlayerLook(PacketReader& packet) { read(packet); }
PlayerLook::PlayerLook(float yaw, float pitch, bool onGround)
: yaw(yaw), pitch(pitch), onGround(onGround) {}
void PlayerLook::read(PacketReader& packet) {
yaw = packet.readFloat();
pitch = packet.readFloat();
onGround = packet.readBool();
}
void PlayerLook::process(PacketHandler& handler) {
handler.handlePlayerLook(*this);
}
PlayerPosition::PlayerPosition(PacketReader& packet) { read(packet); }
PlayerPosition::PlayerPosition(double x, double y, double z, bool onGround)
: x(x), y(y), z(z), onGround(onGround) {}
void PlayerPosition::read(PacketReader& packet) {
x = packet.readDouble();
y = packet.readDouble();
z = packet.readDouble();
onGround = packet.readBool();
}
void PlayerPosition::process(PacketHandler& handler) {
handler.handlePlayerPosition(*this);
}
PlayerPositionAndLook::PlayerPositionAndLook(PacketReader& packet) {
read(packet);
}
PlayerPositionAndLook::PlayerPositionAndLook(double x, double y, double z,
float yaw, float pitch,
bool onGround,
std::int32_t teleportID)
: x(x), y(y), z(z), yaw(yaw), pitch(pitch), onGround(onGround),
teleportID(teleportID) {}
PlayerPositionAndLook::PlayerPositionAndLook(redi::PlayerPosition position,
std::int32_t teleportID)
: PlayerPositionAndLook(position.x, position.y, position.z, position.yaw,
position.pitch, position.onGround, teleportID) {}
void PlayerPositionAndLook::read(PacketReader& packet) {
x = packet.readDouble();
y = packet.readDouble();
z = packet.readDouble();
yaw = packet.readFloat();
pitch = packet.readFloat();
onGround = packet.readBool();
}
void PlayerPositionAndLook::write(ByteBuffer& buffer) {
PacketWriter packet(buffer, SendID);
packet.writeDouble(x);
packet.writeDouble(y);
packet.writeDouble(z);
packet.writeFloat(yaw);
packet.writeFloat(pitch);
packet.writeByte(0);
packet.writeVarInt(teleportID);
}
void PlayerPositionAndLook::process(PacketHandler& handler) {
handler.handlePlayerPositionAndLook(*this);
}
SpawnPlayer::SpawnPlayer(Player& player) : player(player) {}
void SpawnPlayer::write(ByteBuffer& buffer) {
PacketWriter packet(buffer, SendID);
auto position = player.getPosition();
packet.writeVarInt(player.getEntityID());
packet.writeUUID(player.getUUID());
packet.writeDouble(position.x);
packet.writeDouble(position.y);
packet.writeDouble(position.z);
packet.writeAngle(position.yaw);
packet.writeAngle(position.pitch);
packet.writeUByte(0xFF);
}
SpawnPosition::SpawnPosition(Vector3i position) : position(position) {}
void SpawnPosition::write(ByteBuffer& buffer) {
PacketWriter packet(buffer, SendID);
packet.writePosition(position.x, position.y, position.z);
}
TimeUpdate::TimeUpdate(const redi::World& world)
: world(world) {}
void TimeUpdate::write(ByteBuffer& buffer) {
PacketWriter packet(buffer, SendID);
packet.writeLong(world.getWorldTime());
packet.writeLong(world.getWorldTime() % 24'000);
}
UnloadChunk::UnloadChunk(Vector2i position) : position(position) {}
void UnloadChunk::write(ByteBuffer& buffer) {
PacketWriter packet(buffer, SendID);
packet.writeInt(position.x);
packet.writeInt(position.z);
}
}<file_sep>/src/datatypes.hpp
#pragma once
#include <cstdint>
#include <string>
namespace redi {
using byte = unsigned char;
using sbyte = std::int8_t;
using u8 = std::uint8_t;
using i8 = std::int8_t;
using u16 = std::uint16_t;
using i16 = std::int16_t;
using u32 = std::uint32_t;
using i32 = std::int32_t;
using u64 = std::uint64_t;
using i64 = std::int64_t;
using string = std::string;
}<file_sep>/src/protocol/packets/server/statuspackets.hpp
#pragma once
#include "../packet.hpp"
namespace redi {
class Server;
}
namespace redi::packets {
struct Ping : public Packet {
i64 payload;
explicit Ping(i64 payload);
explicit Ping(PacketReader& packet);
void read(PacketReader& packet) override;
void process(PacketHandler& handler) override;
};
struct Pong : public Packet {
static constexpr i32 SendID = 0x01;
i64 payload;
explicit Pong(i64 payload);
void write(ByteBuffer& buffer) override;
};
struct Request : public Packet {
Request() = default;
explicit Request(PacketReader& packet);
void read(PacketReader& packet) override;
void process(PacketHandler& handler) override;
};
struct Response : public Packet {
static constexpr i32 SendID = 0x00;
Server& server;
explicit Response(Server& server);
void write(ByteBuffer& buffer) override;
};
}<file_sep>/src/messages/eventpriority.hpp
#pragma once
#include <cstdint>
#include <functional>
#include <memory>
namespace redi {
enum class EventPriority : std::uint8_t {
Lowest,
Low,
Normal,
High,
Highest,
Monitor
};
} // namespace redi<file_sep>/src/world/chunkmanager.hpp
#pragma once
#include <map>
#include "../vectorn.hpp"
#include "anvilregion.hpp"
#include "chunk.hpp"
#include "memoryregion.hpp"
namespace redi {
class Server;
namespace world {
class ChunkManager {
public:
ChunkManager(Server& server, const std::string& regiondir,
WorldGenerator generator);
ChunkHolder operator()(const Vector2i& coords) const;
void loadChunk(const Vector2i& pos, PlayerSharedPtr player = nullptr);
void unloadRegion(const Vector2i& pos);
bool isChunkLoaded(const Vector2i& coords) const;
Server& getServer() { return server; }
const std::string& getRegionDirectory() const { return mRegionDirectory; }
WorldGenerator& getWorldGenerator() { return mGenerator; }
private:
Server& server;
boost::asio::io_service& workIO;
std::map<Vector2i, world::MemoryRegionSharedPtr> regions;
std::string mRegionDirectory;
WorldGenerator mGenerator;
};
} // namespace world
} // namespace redi<file_sep>/src/lockfree/queue.hpp
#pragma once
#include <deque>
#include <mutex>
#include <boost/optional.hpp>
#include "../bytebuffer.hpp"
namespace redi {
namespace lockfree {
template <typename T>
class Queue {
public:
using Type = T;
using OptionalType = boost::optional<T>;
using Container = std::deque<T>;
~Queue() { std::lock_guard<std::mutex> l(mutex); }
void push(const T& obj) {
std::lock_guard<std::mutex> l(mutex);
data.push_back(obj);
}
void push(T&& obj) {
std::lock_guard<std::mutex> l(mutex);
data.push_back(std::move(obj));
}
void push(T&& first, T&& second) {
std::lock_guard<std::mutex> l(mutex);
data.push_back(std::move(first));
data.push_back(std::move(second));
}
bool pop(T& obj) {
std::lock_guard<std::mutex> l(mutex);
if (data.empty()) {
return false;
} else {
obj = std::move(data.front());
data.pop_front();
return true;
}
}
OptionalType pop() {
std::lock_guard<std::mutex> l(mutex);
OptionalType result;
if (!data.empty()) {
result = std::move(data.front());
data.pop_front();
}
return result;
}
void swap(Container& cont) {
std::lock_guard<std::mutex> l(mutex);
cont.swap(data);
}
std::mutex& getMutex() { return mutex; }
private:
Container data;
std::mutex mutex;
};
using ByteBufferQueue = Queue<ByteBuffer>;
} // namespace lockfree
} // namespace redi<file_sep>/src/util/util.hpp
#pragma once
#include "base64.hpp"
#include "file.hpp"
#include "string.hpp"
#include "time.hpp"
#include "maths.hpp"
#include "random.hpp"<file_sep>/src/commands/commandmanager.cpp
#include <boost/format.hpp>
#include <boost/program_options/parsers.hpp>
#include "commandmanager.hpp"
#include "command.hpp"
#include "../util/util.hpp"
#include "../logger.hpp"
namespace po = boost::program_options;
namespace redi {
namespace commands {
CommandAddResult
CommandManager::registerCommand(Command* ptr, const std::string& command, const std::vector<std::string>& aliases) {
if (!ptr) {
return CommandAddResult::NullPointer;
}
{
bool b = commands.count(command) == 0;
for (const auto& i : aliases) {
if (!b) {
break;
}
b = commands.count(i) == 0;
}
if (!b) {
return CommandAddResult::AlreadyExists;
}
}
data[ptr].push_back({});
CommandData& cd = data[ptr].back();
cd.ptr = ptr;
cd.command = command;
cd.aliases = aliases;
commands[command] = &cd;
for (const auto& i : aliases) {
commands[i] = &cd;
}
return CommandAddResult::Ok;
}
CommandManager& CommandManager::operator()(CommandSender& sender, std::string& message) {
using namespace std::string_literals;
Logger::info((boost::format("%1% issued server command \"%2%\"") %
sender.getSenderName() % message));
message.erase(message.begin());
// TODO: come back here
std::string s(message);
std::vector<std::string> splited = po::split_unix(s);
if (splited.size() == 0) {
sender.sendMessageToSender("Command cannot be empty");
}
else {
splited[0] = util::toLowercase(splited[0]);
auto it = commands.find(splited[0]);
if (it == commands.end()) {
sender.sendMessageToSender(splited[0] + " does not exist");
}
else {
assert(it->second->ptr && "The pointer shouldn't be null");
Command& ref = *it->second->ptr;
// TODO: find a way which doesn't involve copying
CommandArguments args;
args.reserve(splited.size() - 1);
for (std::size_t i = 1; i < splited.size(); ++i) {
args.emplace_back(splited[i]);
}
try {
ref(sender, it->second->command, args);
}
catch (std::exception& e) {
std::string error = "Internal exception occured in command \"" + it->second->command + "\": " + e.what();
Logger::warn(error);
sender.sendMessageToSender(error);
}
}
}
return *this;
}
void CommandManager::unregisterAll(Command* ptr) {
auto& vec = data[ptr];
for (const auto& i : vec) {
commands.erase(i.command);
for (const auto& j : i.aliases) {
commands.erase(j);
}
}
data.erase(ptr);
}
}
} // namespace redi<file_sep>/src/nbt/list.hpp
#pragma once
#include <vector>
#include "basic.hpp"
namespace redi::nbt {
class tag_list : public basic_tag<tag_list> {
public:
static constexpr tag_type type = tag_type::type_list;
tag_list() = default;
tag_list(const tag_list& other);
tag_list(tag_list&& other) = default;
tag_list& operator=(const tag_list& other);
tag_list& operator=(tag_list&& other) = default;
tag_value& operator[](std::size_t pos) { return data[pos]; }
const tag_value& operator[](std::size_t pos) const { return data[pos]; }
void push_back(const tag_value& value) { data.push_back(value); }
void push_back(tag_value&& value) { data.push_back(std::move(value)); }
void push_back(tag&& tag) { push_back(tag_value(std::move(tag).move())); }
void pop_back() { data.pop_back(); }
std::size_t size() const override { return data.size(); }
bool empty() const { return data.empty(); }
tag_type getListType() const;
const std::vector<tag_value>& get() const { return data; }
std::vector<tag_value>& getData() { return data; } // Use at own risk
const std::vector<tag_value>& getData() const { return data; }
private:
std::vector<tag_value> data;
};
} // namespace redi::nbt<file_sep>/src/world/chunkdeseriazer.hpp
#pragma once
#include "../bytebuffer.hpp"
#include "../nbt/nbt.hpp"
#include "chunk.hpp"
namespace redi {
namespace world {
struct ChunkDeserializer {
Chunk& chunk;
const nbt::tag_compound& root;
ChunkDeserializer(Chunk& chunk, const nbt::root_tag& root);
void operator()();
private:
void readMisc();
void readSections();
void readSection(const nbt::tag_compound& section);
void readBlocks(const std::vector<std::int8_t>& buffer, std::int16_t yy);
void readAdd(const std::vector<std::int8_t>& buffer, std::int16_t yy);
void readData(const std::vector<std::int8_t>& buffer, std::int16_t yy);
void readBlockLight(const std::vector<std::int8_t>& buffer, std::int16_t yy);
void readSkyLight(const std::vector<std::int8_t>& buffer, std::int16_t yy);
};
} // namespace world
} // namespace redi<file_sep>/src/protocol/chunkserializer13.hpp
#pragma once
#include "../world/chunk.hpp"
#include "../serverconfig.hpp"
#include "packetwriter.hpp"
namespace redi {
class ChunkSerializer13 {
public:
ChunkSerializer13(const Chunk& chunk, Vector2i pos,
Dimension dimension = Dimension::Overworld);
ByteBuffer operator()();
private:
static constexpr std::size_t ChunkSectionsNumber = 16;
static constexpr std::size_t BitsPerBlock = 13;
static constexpr std::size_t BlocksPerSection = 16 * 16 * 16;
static constexpr std::size_t ChunkSectionDataSize =
BlocksPerSection * BitsPerBlock / 8 / 8;
static constexpr std::size_t BiomeDataSize = 256;
static constexpr std::size_t LightDataSize = BlocksPerSection / 2;
static constexpr std::uint8_t SectionX = 16;
static constexpr std::uint8_t SectionY = 16;
static constexpr std::uint8_t SectionZ = 16;
static constexpr std::size_t ChunkSectionDataArraySize =
(BlocksPerSection * BitsPerBlock) / 8 /
8; // Convert from bit count to long count
const Chunk& mChunk;
Vector2i mPosition;
Dimension mDimension;
ByteBuffer mBuffer;
PacketWriter packet;
void writeHeader();
void writeChunkSections();
void writeChunkSection(std::uint8_t nth);
void writeBlockLight(std::uint8_t nth);
void writeSkyLight(std::uint8_t nth);
void writeBiomes();
void writeBlockEntities();
static uint64_t generateBlockStateID(Block b);
};
} // namespace redi<file_sep>/src/nbt/roottag.cpp
#include "roottag.hpp"
namespace redi::nbt {
void root_tag::visit(const_nbt_visitor& visitor) const {
visitor.visit(*this);
}
tag_value& root_tag::at(const std::string& key) {
return compound.at(key);
}
const tag_value& root_tag::at(const std::string& key) const {
return compound.at(key);
}
tag_value& root_tag::operator[](const std::string& key) {
return compound[key];
}
tag_value& root_tag::operator[](std::string&& key) {
return compound[std::move(key)];
}
std::ostream& operator<<(std::ostream& stream, const root_tag& root) {
pretty_printer printer;
printer.visit(root);
stream << printer.string;
return stream;
}
} // namespace redi::nbt
<file_sep>/src/chat/chatcomponent.hpp
#pragma once
#include <string>
#include "../datatypes.hpp"
namespace redi {
namespace chat {
// TODO: fix later
class ChatComponent {
public:
ChatComponent() = default;
ChatComponent(const std::string& str);
ChatComponent(std::string&& str);
operator std::string&() { return get(); }
operator std::string() const { return get(); }
std::string& get() { return string; }
const std::string& get() const { return string; }
std::string generate() const;
private:
std::string string;
};
ChatComponent& operator+=(ChatComponent& l, const std::string& r);
ChatComponent operator+(ChatComponent l, const std::string& r);
}
} // namespace redi<file_sep>/src/networking_asio.cpp
#include <boost/asio.hpp>
#include <boost/bind.hpp>
#include <mutex>
#include "networking.hpp"
#include "bytebuffer.hpp"
namespace asio = boost::asio;
namespace redi {
class AsioSocket : public Socket, public std::enable_shared_from_this<AsioSocket> {
public:
explicit AsioSocket(asio::ip::tcp::socket&& socket);
~AsioSocket() override = default;
void read(MutableBuffer buffer) override;
void write(ConstBuffer buffer) override;
void close() override;
private:
asio::ip::tcp::socket socket;
asio::io_context::strand strand;
ByteBuffer current_vector;
ByteBuffer current_writing;
std::mutex writing_mutex;
MutableBuffer read_buffer;
void writeNext();
void handleWrite(const boost::system::error_code& error);
void handleRead(const boost::system::error_code& error, size_t bytes);
};
AsioSocket::AsioSocket(asio::ip::tcp::socket&& socket)
: socket(std::move(socket)), strand(socket.get_io_context()) {}
void AsioSocket::write(ConstBuffer buffer) {
{
std::lock_guard<std::mutex> l(writing_mutex);
current_vector.append(buffer.data(), buffer.size());
}
writeNext();
}
void AsioSocket::writeNext() {
socket.get_io_service().post(
strand.wrap([me = shared_from_this(), this] {
if (!current_writing.empty()) {
return;
}
{
std::lock_guard<std::mutex> l(writing_mutex);
current_writing.swap(current_vector);
}
if (current_writing.empty()) {
return;
}
asio::async_write(socket,
asio::buffer(current_writing.data(), current_writing.size()),
boost::bind(&AsioSocket::handleWrite,
shared_from_this(),
asio::placeholders::error));
}));
}
void AsioSocket::handleWrite(const boost::system::error_code& error) {
if (error) {
} else {
current_writing.clear();
writeNext();
}
}
void AsioSocket::read(MutableBuffer buffer) {
read_buffer = buffer;
socket.async_read_some(asio::buffer(buffer.data(), buffer.size()),
boost::bind(&AsioSocket::handleRead, shared_from_this(),
asio::placeholders::error, asio::placeholders::bytes_transferred));
}
void AsioSocket::handleRead(const boost::system::error_code& error, size_t bytes) {
if (error) {
read_handler(0, error.message());
} else {
read_handler(bytes, "");
}
}
void AsioSocket::close() {
socket.close();
}
class AsioListener : public Socket, public std::enable_shared_from_this<AsioListener> {
public:
AsioListener(asio::io_context& context, uint16_t port);
void listen();
void write(ConstBuffer buffer) override;
void read(MutableBuffer buffer) override;
void close() override;
private:
asio::ip::tcp::socket socket_to_be_accepted;
boost::asio::ip::tcp::acceptor acceptor;
void handleAccept(const boost::system::error_code& error);
};
AsioListener::AsioListener(asio::io_context& context, uint16_t port)
: socket_to_be_accepted(context), acceptor(context, asio::ip::tcp::endpoint(asio::ip::tcp::v4(), port)) {}
void AsioListener::listen() {
acceptor.async_accept(socket_to_be_accepted,
boost::bind(&AsioListener::handleAccept,
shared_from_this(),
asio::placeholders::error));
}
void AsioListener::handleAccept(const boost::system::error_code& error) {
if (error) {
accept_handler(nullptr, error.message());
} else {
auto socket = std::make_shared<AsioSocket>(std::move(socket_to_be_accepted));
accept_handler(std::move(socket), "");
listen();
}
}
void AsioListener::read(MutableBuffer) {}
void AsioListener::write(ConstBuffer) {}
void AsioListener::close() {
acceptor.close();
}
class AsioNetworking : public Networking {
public:
explicit AsioNetworking(asio::io_context& context);
std::shared_ptr<Socket> getListener(socket_accept_handler handler, uint16_t port) override;
void stop() override;
private:
asio::io_context& context;
};
AsioNetworking::AsioNetworking(asio::io_context& context)
: context(context) {}
std::shared_ptr<Socket> AsioNetworking::getListener(socket_accept_handler handler, uint16_t port) {
auto listener = std::make_shared<AsioListener>(context, port);
listener->set_accept_handler(handler);
listener->listen();
return listener;
}
void AsioNetworking::stop() {}
std::unique_ptr<redi::Networking> getAsioNetworking(boost::asio::io_context& context) {
return std::make_unique<redi::AsioNetworking>(context);
}
}<file_sep>/src/util/compressor.hpp
#pragma once
#include "../buffers.hpp"
namespace redi::util::zip {
enum class CompressionLevel {
/*
* Not a very good idea
* but I don't want to include
* boost here.
*/
NoCompression = 0,
Default = -1,
BestSpeed = 1,
BestCompression = 9
};
namespace zlib {
void compress(ConstBuffer input, ByteBuffer& output, CompressionLevel level = CompressionLevel::BestCompression);
ByteBuffer compress(ConstBuffer input, CompressionLevel level = CompressionLevel::BestCompression);
void decompress(ConstBuffer input, ByteBuffer& output);
ByteBuffer decompress(ConstBuffer input);
}
namespace gzip {
void compress(ConstBuffer input, ByteBuffer& output, CompressionLevel level = CompressionLevel::BestCompression);
ByteBuffer compress(ConstBuffer input, CompressionLevel level = CompressionLevel::BestCompression);
void decompress(ConstBuffer input, ByteBuffer& output);
ByteBuffer decompress(ConstBuffer input);
}
} // namespace redi::util::zip<file_sep>/src/world/biome.hpp
#pragma once
#include <cstdint>
namespace redi {
enum class Biome : std::uint8_t {
Ocean = 0,
Plains = 1,
Desert = 2,
ExtremeHills = 3,
Forest = 4,
Taiga = 5,
Swampland = 6,
River = 7,
Hell = 8,
Sky = 9,
FrozenOcean = 10,
FrozenRiver = 11,
IceFlats = 12,
IceMountains = 13,
MushroomIsland = 14,
MushroomIslandShore = 15,
Beaches = 16,
DesertHills = 17,
ForestHills = 18,
TaigaHills = 19,
SmallerExtremeHills = 20,
Jungle = 21,
JungleHills = 22,
JungleEdge = 23,
DeepOcean = 24,
StoneBeach = 25,
ColdBeach = 26,
BirchForest = 27,
BirchForestHills = 28,
RoofedForest = 29,
TaigaCold = 30,
TaigaColdHills = 31,
RedwoodTaiga = 32,
RedwoodTaigaHills = 33,
ExtremeHillsWithTrees = 34,
Savanna = 35,
SavannaRock = 36,
Mesa = 37,
MesaRock = 38,
MesaClearRock = 39,
Void = 127,
MutatedPlains = 129,
MutatedDesert = 130,
MutatedExtremeHills = 131,
MutatedForest = 132,
MutatedTaiga = 133,
MutatedSwampland = 134,
MutatedIceFlats = 140,
MutatedJungle = 149,
MutatedJungleEdge = 151,
MutatedBirchForest = 155,
MutatedBirchForestHills = 156,
MutatedRoofedForest = 157,
MutatedTaigaCold = 158,
MutatedRedwoodTaiga = 160,
MutatedRedwoodTaigaHills = 161,
MutatedExtremeHillsWithTrees = 162,
MutatedSavanna = 163,
MutatedSavannaRock = 164,
MutatedMesa = 165,
MutatedMesaRock = 166,
MutatedMesaClearRock = 167
};
} // namespace redi<file_sep>/src/nbt/datatypes.h
#pragma once
#include <cstdint>
#include <string_view>
namespace redi::nbt {
using nbt_byte = std::int8_t;
using nbt_short = std::int16_t;
using nbt_int = std::int32_t;
using nbt_long = std::int64_t;
using nbt_float = float;
using nbt_double = double;
using nbt_string = std::string;
using nbt_string_view = std::string_view;
}<file_sep>/src/nbt/compound.hpp
#pragma once
#include <map>
#include "basic.hpp"
#include "value.hpp"
#include "prettyprinter.hpp"
namespace redi::nbt {
class tag_compound : public basic_tag<tag_compound> {
public:
using map_type = std::map<std::string, tag_value>;
using reference = map_type::reference;
using const_reference = map_type::const_reference;
using iterator = map_type::iterator;
using const_iterator = map_type::const_iterator;
using difference_type = map_type::difference_type;
using size_type = map_type::size_type;
using value_type = map_type::value_type;
using reverse_iterator = map_type::reverse_iterator;
using const_reverse_iterator = map_type::const_reverse_iterator;
static constexpr tag_type type = tag_type::type_compound;
tag_compound() = default;
tag_compound(const tag_compound& other);
tag_compound(tag_compound&&) noexcept = default;
tag_compound(std::initializer_list<value_type> list);
~tag_compound() override = default;
tag_compound& operator=(const tag_compound&);
tag_compound& operator=(tag_compound&&) = default;
tag_value& operator[](const std::string& key);
tag_value& operator[](std::string&& key);
//
// template <typename T>
// void set(nbt_string_view key, const T& x) {
// emplace(key, x);
// }
tag_value& at(const std::string& key) { return map.at(key); }
const tag_value& at(const std::string& key) const {
#ifdef REDI_DEBUG
if (!exists(key)) {
throw std::runtime_error("map.at(" + key + ')');
}
#endif
return map.at(key);
}
void clear() { map.clear(); }
std::size_t size() const override { return map.size(); }
bool empty() const { return map.empty(); }
void swap(tag_compound& other) { map.swap(other.map); }
bool exists(const std::string& key) const { return map.count(key) == 1; }
template <typename... Args>
std::pair<iterator, bool> emplace(Args&&... args) {
return map.emplace(std::forward<Args>(args)...);
}
iterator begin() { return map.begin(); }
const_iterator begin() const { return map.begin(); }
const_iterator cbegin() const { return map.cbegin(); }
iterator end() { return map.end(); }
const_iterator end() const { return map.end(); }
const_iterator cend() const { return map.cend(); }
reverse_iterator rbegin() { return map.rbegin(); }
const_reverse_iterator rbegin() const { return map.rbegin(); }
const_reverse_iterator crbegin() const { return map.crbegin(); }
reverse_iterator rend() { return map.rend(); }
const_reverse_iterator rend() const { return map.rend(); }
const_reverse_iterator crend() const { return map.crend(); }
private:
map_type map;
};
} // namespace redi::nbt<file_sep>/src/messages/chunkloaded.hpp
#pragma once
#include "event.hpp"
#include "../world/memoryregion.hpp"
#include "../player.hpp"
namespace redi {
namespace events {
struct EventChunkLoaded : public Event {
ChunkUniquePtr chunk;
world::MemoryRegion& region;
Vector2i coordinates;
EventChunkLoaded(ChunkUniquePtr&& chunk, world::MemoryRegion& region,
const Vector2i& coords)
: Event(EventType::ChunkLoaded), chunk(std::move(chunk)), region(region),
coordinates(coords) {}
};
} // namespace messages
} // namespace redi<file_sep>/src/world/chunk.cpp
#include <boost/multi_array.hpp>
#include "chunk.hpp"
#include "../sizeliteraloperators.hpp"
namespace redi {
Chunk::Chunk() : blocks(boost::extents[16][16]) {}
} // namespace redi<file_sep>/src/threadsafequeue.hpp
#pragma once
#include <deque>
#include <mutex>
namespace redi {
template <typename T>
class ThreadSafeQueue {
public:
ThreadSafeQueue() = default;
void push(const T& obj) {
std::lock_guard<std::mutex> l(mUtex);
mData.push_back(obj);
}
void push(T&& obj) {
std::lock_guard<std::mutex> l(mUtex);
mData.push_back(std::move(obj));
}
T pop() {
std::lock_guard<std::mutex> l(mUtex);
if (mData.empty())
return {};
T ret(std::move(*mData.begin()));
mData.pop_front();
return ret;
}
bool empty() const { return mData.empty(); }
private:
std::deque<T> mData;
std::mutex mUtex;
};
} // namespace redi<file_sep>/src/buffers.hpp
#pragma once
#include <cstddef>
#include <cstring>
#include "bytebuffer.hpp"
#include "datatypes.hpp"
namespace redi {
class MutableBuffer {
public:
using value_type = byte*;
using const_value_type = const byte*;
using const_iterator = const byte*;
using iterator = byte*;
explicit MutableBuffer() : ptr(nullptr), ptrsize(0) {}
explicit MutableBuffer(const MutableBuffer&) = default;
explicit MutableBuffer(value_type data, std::size_t size)
: ptr(data), ptrsize(size) {}
explicit MutableBuffer(void* data, std::size_t size)
: MutableBuffer(reinterpret_cast<value_type>(data), size) {}
explicit MutableBuffer(ByteBuffer& buf)
: MutableBuffer(buf.data(), buf.size()) {}
explicit MutableBuffer(std::string& str)
: MutableBuffer(&str[0], str.size()) {}
explicit MutableBuffer(char* str)
: MutableBuffer(str, std::strlen(str)) {}
MutableBuffer& operator=(const MutableBuffer&) = default;
value_type data() { return ptr; }
const_value_type data() const { return ptr; }
char* asChar() { return reinterpret_cast<char*>(data()); }
const char* asConstChar() const { return reinterpret_cast<const char*>(data()); }
std::size_t size() const { return ptrsize; }
iterator begin() { return data(); }
iterator end() { return begin() + size(); }
const_iterator begin() const { return data(); }
const_iterator end() const { return begin() + size(); }
ByteBuffer toByteBuffer() const { return ByteBuffer(data(), size()); }
private:
value_type ptr;
std::size_t ptrsize;
};
class ConstBuffer {
public:
using value_type = const byte*;
using const_iterator = const byte*;
using iterator = byte*;
explicit ConstBuffer() : ptr(nullptr), ptrsize(0) {}
ConstBuffer(value_type data, std::size_t size)
: ptr(data), ptrsize(size) {}
ConstBuffer(const void* data, std::size_t size)
: ConstBuffer(reinterpret_cast<value_type>(data), size) {}
explicit ConstBuffer(MutableBuffer& buffer)
: ConstBuffer(buffer.data(), buffer.size()) {}
ConstBuffer(const ByteBuffer& buf)
: ConstBuffer(buf.data(), buf.size()) {}
explicit ConstBuffer(const std::string& str)
: ConstBuffer(&str[0], str.size()) {}
explicit ConstBuffer(const char* str)
: ConstBuffer(str, std::strlen(str)) {}
template <typename T, std::size_t Size, typename = std::enable_if_t<sizeof(T) == 1>>
explicit ConstBuffer(const std::array<T, Size>& array)
: ConstBuffer(array.data(), array.size()) {}
const byte& operator[](size_t index) const { return ptr[index]; }
value_type data() const { return ptr; }
const char* asConstChar() const { return reinterpret_cast<const char*>(ptr); }
std::size_t size() const { return ptrsize; }
const_iterator begin() const { return reinterpret_cast<const byte*>(ptr); }
const_iterator end() const { return begin() + ptrsize; }
ByteBuffer toByteBuffer() const { return ByteBuffer(data(), size()); }
private:
value_type ptr;
std::size_t ptrsize;
};
}<file_sep>/src/CMakeLists.txt
project(redi CXX)
set(SOURCE_FILES
bytebuffer.cpp
bytebuffer.hpp
enums.cpp
enums.hpp
logger.cpp
logger.hpp
main.cpp
player.cpp
player.hpp
playerposition.hpp
server.cpp
server.hpp
serverconfig.cpp
serverconfig.hpp
session.cpp
session.hpp
sizeliteraloperators.hpp
threadsafequeue.hpp
vectorn.hpp
util/base64.hpp
util/file.cpp
util/file.hpp
util/maths.cpp
util/maths.hpp
util/random.hpp
util/string.hpp
util/time.cpp
util/time.hpp
util/util.hpp
world.cpp
world.hpp
world/anvil.cpp
world/anvil.hpp
world/anvilregion.cpp
world/anvilregion.hpp
world/biome.hpp
world/chunk.cpp
world/chunk.hpp
world/chunkcolumn.hpp
world/chunkmanager.cpp
world/chunkmanager.hpp
world/memoryregion.cpp
world/memoryregion.hpp
world/terraingenerator.cpp
world/terraingenerator.hpp
world/block.hpp
world/chunkdeseriazer.cpp
world/chunkdeseriazer.hpp
world/chunkserializer.cpp
world/chunkserializer.hpp
protocol/chunkserializer13.hpp
protocol/packetreader.cpp
protocol/packetreader.hpp
protocol/packets/packet.cpp
protocol/packets/packet.hpp
protocol/packets/packethandler.cpp
protocol/packets/packethandler.hpp
protocol/packets/server/handshakepackets.cpp
protocol/packets/server/handshakepackets.hpp
protocol/packetwriter.cpp
protocol/packetwriter.hpp
protocol/chunkserializer13.cpp
messages/event.hpp
messages/eventmanager.cpp
messages/eventmanager.hpp
messages/eventpriority.hpp
messages/events.hpp
messages/eventtype.hpp
messages/playerdisconnected.hpp
messages/playerjoin.hpp
messages/playerlook.hpp
messages/playerposition.hpp
messages/playerpositionandlook.hpp
messages/sendkeepalivering.hpp
messages/sessiondisconnected.hpp
messages/statusrequest.hpp
messages/tick.hpp
messages/chatmessage.hpp
messages/chunkloaded.hpp
chat/chatmanager.hpp
commands/redicommands.cpp
commands/redicommands.hpp
chat/chatmanager.cpp
lockfree/queue.hpp
nbt/array.hpp
nbt/basic.hpp
nbt/compound.cpp
nbt/compound.hpp
nbt/creator.cpp
nbt/creator.hpp
nbt/deserializer.cpp
nbt/deserializer.hpp
nbt/forward.hpp
nbt/list.cpp
nbt/list.hpp
nbt/nbt.hpp
nbt/prettyprinter.cpp
nbt/prettyprinter.hpp
nbt/primitive.hpp
nbt/roottag.cpp
nbt/roottag.hpp
nbt/serializer.cpp
nbt/serializer.hpp
nbt/string.hpp
nbt/tag.cpp
nbt/type.cpp
nbt/type.hpp
nbt/value.cpp
nbt/value.hpp
nbt/tag.hpp
nbt/datatypes.h
nbt/end.hpp
nbt/visitor.hpp
datatypes.hpp
checks.cpp
util/threadgroup.hpp
buffers.hpp
hasserver.hpp
commands/commandsender.hpp
commands/commandsender.cpp
commands/commandmanager.cpp
commands/commandmanager.hpp
commands/command.hpp
commands/command.cpp
commands/redicommands.cpp
commands/commanddata.hpp
chat/chatcomponent.cpp
chat/chatcomponent.hpp
protocol/varint.cpp
protocol/varint.hpp
util/compressor.hpp
util/compressor.cpp
servericon.cpp
servericon.hpp
filesystem.hpp
util/string.cpp
networking.hpp
networking_linux.cpp
networking_asio.cpp
asiofile.cpp
protocol/packets/server/statuspackets.hpp
protocol/packets/server/statuspackets.cpp
protocol/packets/server/loginpackets.hpp
protocol/packets/server/loginpackets.cpp
protocol/packets/server/playpackets.hpp
protocol/packets/server/playpackets.cpp)
add_executable(redi ${SOURCE_FILES})
set(Boost_USE_STATIC_LIBS ON)
add_definitions(-DBOOST_SYSTEM_NO_DEPRECATED)
set(CMAKE_MODULE_PATH "${CMAKE_MODULE_PATH};../CMake")
find_package(Boost REQUIRED COMPONENTS filesystem iostreams program_options system)
if(Boost_FOUND)
include_directories(${Boost_INCLUDE_DIRS})
target_link_libraries(redi ${Boost_LIBRARIES})
endif()
find_package(ZLIB REQUIRED)
if(ZLIB_FOUND)
include_directories(${ZLIB_INCLUDE_DIRS})
target_link_libraries(redi ${ZLIB_LIBRARIES})
endif()
if(MINGW)
target_link_libraries(redi ws2_32)
endif()
#find_package(Threads REQUIRED)
#target_link_libraries(redi "${CMAKE_THREAD_LIBS_INIT}")
if(UNIX)
target_link_libraries(redi pthread)
endif()
if(WIN32)
target_link_libraries(redi wsock32)
endif()
if("${JSON_REPO_DIR} " STREQUAL " ")
message(FATAL_ERROR "JSON NOT found. Set JSON_REPO_DIR to the repository folder.")
else()
message(STATUS "JSON found : ${JSON_REPO_DIR}/src")
include_directories(${JSON_REPO_DIR}/include)
endif()
if(UNIX OR MINGW)
add_definitions(-DREDI_FUNCTION=__PRETTY_FUNCTION__)
elseif(MSVC)
add_definitions(-DREDI_FUNCTION=__FUNCTION__)
else()
add_definitions(-DREDI_FUNCTION="")
endif()
if(CMAKE_BUILD_TYPE STREQUAL "Debug")
add_definitions(-DREDI_DEBUG)
endif()
include(../CMake/cotire.cmake)
#cotire(redi)<file_sep>/src/playerposition.hpp
#pragma once
#include "util/util.hpp"
#include "enums.hpp"
#include "vectorn.hpp"
#include "serverconfig.hpp"
namespace redi {
struct PlayerLook {
float yaw;
float pitch;
PlayerLook(float yaw = 0.0f, float pitch = 0.0f) : yaw(yaw), pitch(pitch) {}
void normalize() {
yaw = static_cast<float>(util::normalizeAngleDegrees(yaw));
pitch = static_cast<float>(util::normalizeAngleDegrees(pitch));
}
};
inline std::ostream& operator<<(std::ostream& stream, const PlayerLook& obj) {
// stream << boost::format("(%1%, %2%)") % obj.yaw % obj.pitch;
stream << obj.yaw << ", " << obj.pitch;
return stream;
}
struct PlayerPosition : Vector3d, PlayerLook {
bool onGround;
Dimension dimension;
PlayerPosition(double x = 0.0, double y = 0.0, double z = 0.0,
float yaw = 0.0f, float pitch = 0.0f, bool onGround = true,
Dimension dimension = Dimension::Overworld)
: Vector3d(x, y, z), PlayerLook(yaw, pitch), onGround(onGround),
dimension(dimension) {}
Vector2i getChunkPosition() const {
return Vector2i(static_cast<std::int32_t>(x / 16),
static_cast<std::int32_t>(z / 16));
}
};
} // namespace redi<file_sep>/src/world/anvilregion.hpp
#pragma once
#include <array>
#include <fstream>
#include <vector>
#include "../sizeliteraloperators.hpp"
#include "../vectorn.hpp"
#include "../bytebuffer.hpp"
namespace redi {
namespace world {
struct ChunkInfo {
std::uint32_t offset, time;
std::uint8_t sectors;
ChunkInfo(std::int32_t offset = 0, std::int32_t time = 0,
std::uint8_t sectors = 0)
: offset(offset), time(time), sectors(sectors) {}
};
class AnvilRegion {
public:
static constexpr std::int32_t ChunksPerRegion = 1 << 10;
static constexpr std::size_t HeaderSize = 8_KB;
static constexpr std::size_t SectorSize =
4_KB; // uhh, sectors. Earth is on Sector 2814
static constexpr std::size_t ChunkHeaderSize = 5;
AnvilRegion() = default;
AnvilRegion(const std::string& filepath);
~AnvilRegion();
void clear();
void close();
void flush();
void open(const std::string& filepath);
ByteBuffer readChunk(Vector2i ch);
void writeChunk(Vector2i ch, const ByteBuffer& data, bool updateDate = true);
static void createNewRegion(const std::string& filepath);
static std::int32_t getChunkNumberInRegion(Vector2i other);
static Vector2i getRegionCoordsFromChunkCoords(const Vector2i& chcoords);
private:
std::fstream mFile;
std::vector<bool> mFreeSectors;
std::array<ChunkInfo, ChunksPerRegion> mChunks;
bool hasRegion = false;
void readHeader();
void saveHeader();
};
} // namespace world
} // namespace redi<file_sep>/src/nbt/value.cpp
#include "primitive.hpp"
#include "string.hpp"
#include "compound.hpp"
#include "value.hpp"
#include "basic.hpp"
#include "primitive.hpp"
#include "string.hpp"
#include "compound.hpp"
#include "list.hpp"
#include "array.hpp"
namespace redi::nbt {
tag_value::tag_value(const tag_value& obj) : data(obj.data ? obj.data->clone() : nullptr) {}
tag_value::tag_value(tag&& tag) : data(std::move(tag).move()) {}
tag_value::tag_value(std::int8_t x) : tag_value(tag_byte(x)) {}
tag_value::tag_value(std::int16_t x) : tag_value(tag_short(x)) {}
tag_value::tag_value(std::int32_t x) : tag_value(tag_int(x)) {}
tag_value::tag_value(std::int64_t x) : tag_value(tag_long(x)) {}
tag_value::tag_value(float x) : tag_value(tag_float(x)) {}
tag_value::tag_value(double x) : tag_value(tag_double(x)) {}
tag_value::tag_value(nbt_string_view x) : tag_value(tag_string(x)) {}
tag_value::tag_value(std::string&& x) : tag_value(tag_string(std::move(x))) {}
tag_value::tag_value(tag_unique_ptr&& ptr) : data(std::move(ptr)) {}
tag_value::tag_value(std::nullptr_t) : tag_value() {}
tag_value& tag_value::operator=(const tag_value& other) {
if (data) {
data->assign(*other.data);
} else {
data = other.data->clone();
}
return *this;
}
tag_value& tag_value::operator=(const tag& tag) {
*this = tag.clone();
return *this;
}
tag_value& tag_value::operator=(tag&& tag) {
if (data) {
data->assign(std::move(tag));
} else {
data = std::move(tag).move();
}
return *this;
}
tag_value& tag_value::operator=(tag_unique_ptr&& ptr) {
if (ptr) {
*this = std::move(*ptr);
} else if (data) {
throw std::bad_cast();
}
return *this;
}
tag_value& tag_value::operator=(std::int8_t x) {
*this = tag_byte(x);
return *this;
}
tag_value& tag_value::operator=(std::int16_t x) {
*this = tag_short(x);
return *this;
}
tag_value& tag_value::operator=(std::int32_t x) {
*this = tag_int(x);
return *this;
}
tag_value& tag_value::operator=(std::int64_t x) {
*this = tag_long(x);
return *this;
}
tag_value& tag_value::operator=(float x) {
*this = tag_float(x);
return *this;
}
tag_value& tag_value::operator=(double x) {
*this = tag_double(x);
return *this;
}
tag_value& tag_value::operator=(const std::string& x) {
*this = tag_string(x);
return *this;
}
tag_value& tag_value::operator=(std::string&& x) {
*this = tag_string(std::move(x));
return *this;
}
tag_value& tag_value::operator=(std::nullptr_t) {
throwIfNot(tag_type::type_end);
return *this;
}
tag_value& tag_value::operator[](const std::string& key) {
throwIfNot(tag_type::type_compound);
return static_cast<tag_compound&>(*data)[key];
}
tag_value& tag_value::operator[](std::string&& key) {
throwIfNot(tag_type::type_compound);
return static_cast<tag_compound&>(*data)[std::move(key)];
}
tag_value& tag_value::operator[](const char* key) { return (*this)[std::string(key)]; }
//void tag_value::assign(tag&& tag) { *this = std::move(tag); }
tag_type tag_value::get_type() const { return get_type(data); }
tag_type tag_value::get_type(const tag_unique_ptr& ptr) {
return ptr ? ptr->get_type() : tag_type::type_end;
}
void tag_value::throwIfNot(tag_type type) const {
if (get_type() != type) {
throw std::bad_cast();
}
}
void tag_value::throwIfNullOrIsNot(tag_type type) const {
if (!data) {
throw std::runtime_error("Tag is null");
}
throwIfNot(type);
}
nbt_byte& tag_value::getByte() {
throwIfNot(tag_type::type_byte);
return static_cast<tag_byte&>(*data).data;
}
nbt_short& tag_value::getShort() {
throwIfNot(tag_type::type_short);
return static_cast<tag_short&>(*data).data;
}
nbt_int& tag_value::getInt() {
throwIfNot(tag_type::type_int);
return static_cast<tag_int&>(*data).data;
}
nbt_long& tag_value::getLong() {
throwIfNot(tag_type::type_long);
return static_cast<tag_long&>(*data).data;
}
nbt_float& tag_value::getFloat() {
throwIfNot(tag_type::type_float);
return static_cast<tag_float&>(*data).data;
}
nbt_double& tag_value::getDouble() {
throwIfNot(tag_type::type_double);
return static_cast<tag_double&>(*data).data;
}
tag_byte_array_container& tag_value::getByteArray() {
throwIfNot(tag_type::type_byte_array);
return static_cast<tag_byte_array&>(*data).data;
}
nbt_string& tag_value::getString() {
throwIfNot(tag_type::type_string);
return static_cast<tag_string&>(*data).data;
}
tag_list& tag_value::getList() {
throwIfNot(tag_type::type_list);
return static_cast<tag_list&>(*data);
}
tag_compound& tag_value::getCompound() {
throwIfNot(tag_type::type_compound);
return static_cast<tag_compound&>(*data);
}
tag_int_array_container& tag_value::getIntArray() {
throwIfNot(tag_type::type_int_array);
return static_cast<tag_int_array&>(*data).data;
}
tag_long_array_container& tag_value::getLongArray() {
throwIfNot(tag_type::type_long_array);
return static_cast<tag_long_array&>(*data).data;
}
const nbt_byte& tag_value::getByte() const {
throwIfNot(tag_type::type_byte);
return static_cast<const tag_byte&>(*data).data;
}
const nbt_short& tag_value::getShort() const {
throwIfNot(tag_type::type_short);
return static_cast<const tag_short&>(*data).data;
}
const nbt_int& tag_value::getInt() const {
throwIfNot(tag_type::type_int);
return static_cast<const tag_int&>(*data).data;
}
const nbt_long& tag_value::getLong() const {
throwIfNot(tag_type::type_long);
return static_cast<const tag_long&>(*data).data;
}
const nbt_float& tag_value::getFloat() const {
throwIfNot(tag_type::type_float);
return static_cast<const tag_float&>(*data).data;
}
const nbt_double& tag_value::getDouble() const {
throwIfNot(tag_type::type_double);
return static_cast<const tag_double&>(*data).data;
}
const tag_byte_array_container& tag_value::getByteArray() const {
throwIfNot(tag_type::type_byte_array);
return static_cast<const tag_byte_array&>(*data).data;
}
const nbt_string& tag_value::getString() const {
throwIfNot(tag_type::type_string);
return static_cast<const tag_string&>(*data).data;
}
const tag_list& tag_value::getList() const {
throwIfNot(tag_type::type_list);
return static_cast<const tag_list&>(*data);
}
const tag_compound& tag_value::getCompound() const {
throwIfNot(tag_type::type_compound);
return static_cast<const tag_compound&>(*data);
}
const tag_int_array_container& tag_value::getIntArray() const {
throwIfNot(tag_type::type_int_array);
return static_cast<const tag_int_array&>(*data).data;
}
const tag_long_array_container& tag_value::getLongArray() const {
throwIfNot(tag_type::type_long_array);
return static_cast<const tag_long_array&>(*data).data;
}
void tag_value::visit(nbt_visitor& visitor) {
data->visit(visitor);
}
void tag_value::visit(const_nbt_visitor& visitor) const {
data->visit(visitor);
}
tag_value& tag_value::operator=(tag_value&& other) noexcept {
data = std::move(other.data);
return *this;
}
} // namespace redi::nbt<file_sep>/src/util/threadgroup.hpp
#pragma once
#include <thread>
#include <vector>
namespace redi {
namespace util {
template <typename Thread = std::thread>
struct ThreadGroup {
using Container = std::vector<Thread>;
Container threads;
ThreadGroup() = default;
template <typename Callable, typename ... Args>
ThreadGroup(int number, Callable&& f, Args ... args) {
create(number, std::forward<Callable>(f),
std::forward<Args>(args) ...);
}
~ThreadGroup() {
joinAll();
}
template <typename Callable, typename ... Args>
void create(int number, Callable&& f, Args ... args) {
for (int i = 0; i < number; ++i) {
threads.emplace_back(std::forward<Callable>(f),
std::forward<Args>(args) ...);
}
}
void joinAll() {
for (auto& i : threads) {
if (i.joinable()) {
i.join();
}
}
}
};
}
}<file_sep>/src/world/chunk.hpp
#pragma once
#include <cstdint>
#include <boost/multi_array.hpp>
#include <boost/optional.hpp>
#include "block.hpp"
#include "../bytebuffer.hpp"
#include "../vectorn.hpp"
#include "chunkcolumn.hpp"
#include "terraingenerator.hpp"
namespace redi {
namespace world {
struct ChunkDeserializer;
}
class Chunk {
public:
using ChunkColumns = boost::multi_array<ChunkColumn, 2>;
static constexpr std::uint16_t ChunkMaxX = 16;
static constexpr std::uint16_t ChunkMaxY = 256;
static constexpr std::uint16_t ChunkMaxZ = 16;
std::int64_t inhabitedTime{};
Vector2i position;
Chunk();
Block& operator()(Vector3i pos) { return blocks[pos.x][pos.z][pos.y]; };
Block& operator()(std::int32_t x, std::int32_t y, std::int32_t z) {
return blocks[x][z][y];
}
Block operator()(Vector3i pos) const { return blocks[pos.x][pos.z][pos.y]; };
Block operator()(std::int32_t x, std::int32_t y, std::int32_t z) const {
return blocks[x][z][y];
}
const ChunkColumns& getChunkColumns() const { return blocks; }
private:
friend struct world::ChunkDeserializer;
ChunkColumns blocks;
};
using ChunkUniquePtr = std::unique_ptr<Chunk>;
} // namespace redi<file_sep>/src/vectorn.hpp
#pragma once
#include <cmath>
#include <cstdint>
#include <boost/format.hpp>
namespace redi {
struct Position {
double x;
double y;
double z;
Position(double x = 0.0, double y = 0.0, double z = 0.0) : x(x), y(y), z(z) {}
};
struct Location : public Position {
using Position::Position;
};
template <typename T>
struct Vector2 {
T x, z;
Vector2(T x = 0, T z = 0) : x(x), z(z) {}
bool operator==(const Vector2& r) const {
return x == r.x && z == r.z;
}
bool operator<(const Vector2& r) const {
return x < r.x || (x == r.x && z < r.z);
}
std::string toString() const {
return std::to_string(x) + ", " + std::to_string(z);
}
std::int64_t distanceSquared(const Vector2& r) {
std::int64_t xx = static_cast<std::int64_t>(x) - r.x;
std::int64_t zz = static_cast<std::int64_t>(z) - r.z;
return xx * xx + zz * zz;
}
double distance(const Vector2& r) { return std::sqrt(distanceSquared(r)); }
};
template <typename T>
bool operator==(const Vector2<T>& l, const Vector2<T>& r) {
return l.x == r.x && l.z == r.z;
}
template <typename T>
std::ostream& operator<<(std::ostream& stream, const Vector2<T>& val) {
stream << val.toString();
return stream;
}
template <typename T>
struct Vector3 {
T x, y, z;
Vector3(T x = 0, T y = 0, T z = 0) : x(x), y(y), z(z) {}
bool operator==(const Vector3& r) const {
return x == r.x && y == r.y && z == r.z;
}
std::string toString() const {
// return (boost::format("(%1%, %2%, %3%)") % x % y % z).str();
return std::to_string(x) + ", " + std::to_string(y) + ", " +
std::to_string(z);
}
template <typename Result = T>
Result distanceSquared(const Vector3& r) {
Result xx = static_cast<Result>(x - r.x);
Result yy = static_cast<Result>(y - r.y);
Result zz = static_cast<Result>(z - r.z);
return xx * xx + yy * yy + zz * zz;
}
double distance(const Vector3& r) { return std::sqrt(distanceSquared(r)); }
};
template <typename T>
std::ostream& operator<<(std::ostream& stream, const Vector3<T>& val) {
stream << val.toString();
return stream;
}
using Vector2i = Vector2<std::int32_t>;
using Vector3i = Vector3<std::int32_t>;
using Vector3d = Vector3<double>;
} // namespace redi<file_sep>/src/bytebuffer.hpp
#pragma once
#include <cstdint>
#include <memory>
#include <vector>
namespace redi {
class ByteBuffer : public std::vector<std::uint8_t> {
public:
using base = std::vector<std::uint8_t>;
using base::base;
using base::operator=;
using base::operator[];
ByteBuffer() = default;
ByteBuffer(const std::uint8_t* ptr, base::size_type size) {
append(ptr, size);
}
ByteBuffer(const char* ptr);
ByteBuffer(const char* ptr, base::size_type size) { append(ptr, size); }
template <typename T, std::size_t size = sizeof(T)>
void append(const T& obj) {
append(reinterpret_cast<const std::uint8_t*>(std::addressof(obj)), size);
}
void append(const std::uint8_t* ptr, base::size_type size) {
insert(end(), ptr, ptr + size);
}
void append(const char* ptr, base::size_type size) {
append(reinterpret_cast<const std::uint8_t*>(ptr), size);
}
char* as_char() { return reinterpret_cast<char*>(data()); }
const char* as_const_char() const {
return reinterpret_cast<const char*>(data());
}
};
ByteBuffer& operator+=(ByteBuffer& l, const ByteBuffer& r);
ByteBuffer operator+(ByteBuffer l, const ByteBuffer& r);
using ByteBufferSharedPtr = std::shared_ptr<ByteBuffer>;
} // namespace redi<file_sep>/src/nbt/list.cpp
#include "value.hpp"
#include "serializer.hpp"
#include "deserializer.hpp"
#include "creator.hpp"
#include "list.hpp"
namespace redi::nbt {
namespace {
std::vector<tag_value> cloneVectorValue(const std::vector<tag_value>& vector) {
std::vector<tag_value> result;
result.reserve(vector.size());
for (auto& i : vector) {
result.push_back(i);
}
return result;
}
}
tag_list::tag_list(const tag_list& other) { *this = other; }
tag_list& tag_list::operator=(const tag_list& other) {
data = cloneVectorValue(other.data);
return *this;
}
tag_type tag_list::getListType() const {
return empty() ? tag_type::type_end : data.front().get_type();
}
} // namespace redi::nbt<file_sep>/src/protocol/packets/packet.cpp
#include "../../session.hpp"
#include "../../player.hpp"
#include "packet.hpp"
namespace redi {
Packet::~Packet() {}
void Packet::send(Session& session) {
ByteBuffer buffer;
write(buffer);
session.sendPacket(std::move(buffer), getName());
}
void Packet::send(Player& player) { send(player.getSession()); }
void Packet::send(SessionSharedPtr& session) { send(*session); }
void Packet::send(std::list<PlayerSharedPtr>& list) {
ByteBuffer buffer;
write(buffer);
std::for_each(list.begin(), list.end(), [&](PlayerSharedPtr& player) {
player->getSession().sendPacket(const_cast<const ByteBuffer&>(buffer));
});
}
} // namespace redi<file_sep>/src/nbt/basic.hpp
#pragma once
#include "tag.hpp"
#include "visitor.hpp"
namespace redi::nbt {
template <typename T>
class basic_tag : public tag {
public:
~basic_tag() override = default;
tag& assign(tag&& tag) override;
tag& assign(const tag& tag) override;
tag_type get_type() const override;
tag_unique_ptr clone() const& override;
tag_unique_ptr move() && override;
void visit(nbt_visitor& visitor) override;
void visit(const_nbt_visitor& visitor) const override;
private:
T& der();
const T& der() const;
};
template<typename T>
inline void basic_tag<T>::visit(nbt_visitor& visitor) {
visitor.visit(der());
}
template<typename T>
inline void basic_tag<T>::visit(const_nbt_visitor& visitor) const {
visitor.visit(der());
}
template<typename T>
inline tag& basic_tag<T>::assign(tag&& tag) {
return der() = dynamic_cast<T&&>(tag);
}
template<typename T>
inline tag& basic_tag<T>::assign(const tag& tag) {
return der() = dynamic_cast<const T&>(tag);
}
template<typename T>
inline tag_type basic_tag<T>::get_type() const {
return T::type;
}
template<typename T>
inline tag_unique_ptr basic_tag<T>::clone() const& {
return std::make_unique<T>(der());
}
template<typename T>
inline tag_unique_ptr basic_tag<T>::move()&& {
return std::make_unique<T>(std::move(der()));
}
template<typename T>
inline T& basic_tag<T>::der() {
return static_cast<T&>(*this);
}
template<typename T>
inline const T& basic_tag<T>::der() const {
return static_cast<const T&>(*this);
}
} // namespace redi::nbt<file_sep>/src/logger.cpp
#include <iostream>
#include <mutex>
#include <boost/filesystem.hpp>
#include <boost/format.hpp>
#include "logger.hpp"
namespace fs = boost::filesystem;
namespace redi {
Logger::Logger() : mStop(false) {
fs::create_directories("logs");
mFile.open("logs/latest.txt", std::ios::app);
mThread = std::thread(&Logger::workingThread, this);
}
Logger::~Logger() {
mStop = true;
mThread.join();
}
void Logger::workingThread() {
using namespace std::chrono_literals;
Container local;
std::string result;
while (!mStop) {
local.clear();
{
std::lock_guard<std::mutex> guard(mMutex);
local.swap(mQueue);
}
run(local, result);
std::this_thread::sleep_for(std::chrono::milliseconds(5ms));
}
run(mQueue, result);
}
void Logger::run(Container& cont, std::string& result) {
result.clear();
for (const auto& i : cont)
result += (boost::format("[%2% - %3%]: %1%\n") % std::get<0>(i) %
std::get<1>(i) % getEnumName(std::get<2>(i)))
.str();
if (result.size() != 0) {
std::cout << result;
mFile << result << std::flush;
}
}
const char* getEnumName(LoggerLevel level) {
const char* ptr;
switch (level) {
case LoggerLevel::Debug:
ptr = "debug";
break;
case LoggerLevel::Error:
ptr = "error";
break;
case LoggerLevel::Fatal:
ptr = "fatal";
break;
case LoggerLevel::Info:
ptr = "info";
break;
case LoggerLevel::Warn:
ptr = "warn";
break;
default:
ptr = "unknown";
}
return ptr;
}
Logger& Logger::get() {
static Logger log;
return log;
}
} // namespace redi<file_sep>/src/world/terraingenerator.hpp
#pragma once
namespace redi {
class Chunk;
class TerrainGenerator {
public:
virtual ~TerrainGenerator() = default;
void generate(Chunk& chunk);
};
using WorldGenerator = std::shared_ptr<TerrainGenerator>;
} // namespace redi<file_sep>/src/world/chunkserializer.hpp
#pragma once
#include "chunk.hpp"
#include "../nbt/nbt.hpp"
#include "../datatypes.hpp"
namespace redi {
namespace world {
struct ChunkSerializer {
const Chunk& chunk;
nbt::tag_compound& root;
ChunkSerializer(nbt::root_tag& root, const Chunk& chunk);
void operator()();
private:
static nbt::tag_compound& resolve(nbt::root_tag& root);
void writeMisc();
void writeSections();
void writeSection(nbt::tag_list& list, std::uint8_t y);
bool writeBlocks(byte* bytes, std::int16_t yy);
// void writeAdd(const std::vector<std::int8_t>& buffer, std::int16_t yy);
void writeData(byte* bytes, std::int16_t yy);
void writeBlockLight(byte* bytes, std::int16_t yy);
void writeSkyLight(byte* bytes, std::int16_t yy);
};
} // namespace world
} // namespace redi<file_sep>/src/nbt/prettyprinter.cpp
#include <boost/format.hpp>
#include <utility>
#include "prettyprinter.hpp"
#include "tag.hpp"
#include "nbt.hpp"
namespace redi::nbt {
pretty_print_options::pretty_print_options(nbt_int indent_size, nbt_string indent_character)
: indent_size(indent_size), indent_character(std::move(indent_character)) {}
pretty_printer::pretty_printer(pretty_print_options options)
: options(std::move(options)) {}
pretty_printer::pretty_printer(nbt_int indent)
: pretty_printer(pretty_print_options(indent)) {}
struct IndentBlock {
pretty_printer& printer;
explicit IndentBlock(pretty_printer& printer);
~IndentBlock();
};
IndentBlock::IndentBlock(pretty_printer& printer)
: printer(printer) {
printer.writeIndent(printer.options.indent_size);
}
IndentBlock::~IndentBlock() {
printer.writeIndent(-printer.options.indent_size);
}
template <typename T>
void pretty_printer::writeNumber(T x) {
append(std::to_string(x));
}
void pretty_printer::visit(const tag_byte& x) {
writeNumber(static_cast<int>(x.data));
}
void pretty_printer::visit(const tag_short& x) {
writeNumber(x.data);
}
void pretty_printer::visit(const tag_int& x) {
writeNumber(x.data);
}
void pretty_printer::visit(const tag_long& x) {
writeNumber(x.data);
}
void pretty_printer::visit(const tag_float& x) {
writeNumber(x.data);
}
void pretty_printer::visit(const tag_double& x) {
writeNumber(x.data);
}
void pretty_printer::visit(const tag_byte_array& x) {
writeArrayNumbers("byte", x.size());
}
void pretty_printer::visit(const tag_string& x) {
append(boost::format("%2%%1%%2%") % x.data % '\"');
}
void pretty_printer::visit(const tag_list& x) {
IndentBlock indent_block(*this);
tag_type t = x.getListType();
for (auto& index : x.get()) {
// TODO: fix with range loop on tag_list
writeNewLine();
writeIndent();
writeType(t);
if (index) {
writeOne(index.get());
}
index.get().visit(*this);
}
}
void pretty_printer::visit(const tag_compound& x) {
IndentBlock indent_block(*this);
for (auto& index : x) {
writeNewLine();
writeIndent();
tag_type type = index.second.get_type();
writeType(type, index.first);
auto& second_tag = index.second.get();
if (index.second) {
writeOne(second_tag);
}
second_tag.visit(*this);
}
}
void pretty_printer::visit(const tag_int_array& x) {
writeArrayNumbers("int", x.size());
}
void pretty_printer::visit(const tag_long_array& x) {
writeArrayNumbers("long", x.size());
}
void pretty_printer::writeType(tag_type t, nbt_string_view str) {
append(boost::format("%1%(\"%2%\") : ") % getNBTTypeName(t) % str);
}
void pretty_printer::append(nbt_string_view str) {
string += str;
}
void pretty_printer::writeIndent(nbt_int i) {
// TODO: fix printing indent at the end of the line
if (i > 0) {
for (; i > 0; --i) {
indent_string += options.indent_character;
}
} else if (i < 0) {
i *= options.indent_character.size();
for (; i < 0; ++i) {
indent_string.pop_back();
}
}
append(indent_string);
}
void pretty_printer::writeNewLine() {
append("\n");
}
void pretty_printer::writeEntry(std::size_t size) {
append(std::to_string(size) + (size == 1 ? " entry" : " entries"));
}
void pretty_printer::visit(const root_tag& x) {
writeType(x.type, x.name);
writeOne(x.compound);
visit(x.compound);
}
void pretty_printer::writeOne(const tag& tag) {
if (tag.is_container()) {
writeEntry(tag.size());
}
}
void pretty_printer::writeArrayNumbers(nbt_string_view name, std::size_t size) {
auto multiplier = (size == 1 ? "" : "s");
append(boost::format("[%1% %2%%3%]") % size % name % multiplier);
}
void pretty_printer::append(const boost::format& format) {
append(format.str());
}
void pretty_printer::writeType(tag_type t) {
append(getNBTTypeName(t) + std::string(" : "));
}
std::ostream& operator<<(std::ostream& stream, const pretty_printer& printer) {
stream << printer.string;
return stream;
}
} // namespace redi::nbt<file_sep>/src/messages/eventmanager.cpp
#include <boost/uuid/uuid.hpp>
#include <boost/uuid/uuid_generators.hpp>
#include <boost/uuid/uuid_io.hpp>
#include <nlohmann/json.hpp>
#include "eventmanager.hpp"
#include "../server.hpp"
#include "../util/util.hpp"
#include "../player.hpp"
namespace redi {
EventManager::EventManager(Server& server) : mServer(server) {}
void EventManager::operator()() {
while (!mEvents.empty()) {
EventUniquePtr e = mEvents.pop();
if (!e)
continue;
switch (e->getType()) {
case EventType::PlayerJoin: {
EventPlayerJoin& event = e->get<EventPlayerJoin>();
handlePlayerJoin(event);
mServer.mChatManager(event);
} break;
case EventType::PlayerDisconnect: {
EventPlayerDisconnect& event = e->get<EventPlayerDisconnect>();
mServer.mChatManager(event);
{
for (PlayerSharedPtr& player : mServer.mPlayers) {
if (*player != event.player) {
packets::PlayerListItem(event.player,
PlayerListItemAction::RemovePlayer)
.send(*player);
}
}
}
handlePlayerDisconnect(event);
} break;
case EventType::SessionDisconnect:
handleSessionDisconnect(e->get<EventSessionDisconnect>());
break;
case EventType::ChatMessage:
handleChatMessage(e->get<EventChatMessage>());
break;
case EventType::ChunkLoaded: {
handleChunkLoaded(e->get<events::EventChunkLoaded>());
} break;
default:
break;
}
}
}
void EventManager::addEvent(EventUniquePtr&& ptr) {
mEvents.push(std::move(ptr));
}
void EventManager::handlePlayerJoin(EventPlayerJoin& packet) {
packet.session->setConnectionState(ConnectionState::Play);
boost::uuids::uuid namesp = boost::lexical_cast<boost::uuids::uuid>(
"77e7c416-763c-4967-8291-6698b795e90a");
boost::uuids::name_generator gen(namesp);
boost::uuids::uuid uuid = gen(util::toLowercase(packet.username));
Session& mSession = *packet.session;
// for (SessionSharedPtr& s :
// mServer.mStatusConnections) // TODO: find a better way
// {
// if (s == packet.session) {
// mServer.mPlayers.emplace_back(std::make_shared<Player>(
// packet.username, uuid, std::move(s), mServer.getNewEntityID(),
// mServer, &mServer.mWorlds.back()));
// mServer.mStatusConnections.remove_if(
// [](const SessionSharedPtr& par) -> bool {
// return !static_cast<bool>(par);
// });
// break;
// }
// }
mServer.mPlayers.emplace_back(std::make_shared<Player>(
packet.username, uuid, packet.session, mServer.getNewEntityID(),
mServer, &mServer.mWorlds.back()));
auto& player = *mServer.mPlayers.back();
player.getSession().setPlayer(player);
player.getWorld().addPlayer(player);
packets::SetCompression(-1).send(mSession);
packets::LoginSucces(player.getUUIDasString(), player.getUsername()).send(mSession);
packets::JoinGame(&player).send(mSession);
packets::SpawnPosition(Vector3i(0, 50, 0)).send(mSession);
packets::PlayerPositionAndLook(player.getPosition(),
player.getNewTeleportID())
.send(mSession);
packets::TimeUpdate(player.getWorld()).send(mSession);
player.timersNext();
for (PlayerSharedPtr& idx : mServer.mPlayers) {
if (*idx == player) {
for (PlayerSharedPtr& i : mServer.mPlayers) {
packets::PlayerListItem(*i, PlayerListItemAction::AddPlayer)
.send(player.getSession());
}
} else {
packets::PlayerListItem(player, PlayerListItemAction::AddPlayer)
.send(idx->getSession());
}
}
player.onUpdateChunks();
}
void EventManager::handlePlayerDisconnect(EventPlayerDisconnect& event) {
Player& player = event.player;
player.getWorld().deletePlayer(player);
// First remove the player from the world
// so we won't SIGSEGV when deferencing it after deleting
mServer.mPlayers.remove_if(
[&](const PlayerSharedPtr& p) { return *p == player; });
}
void EventManager::handleSessionDisconnect(EventSessionDisconnect& event) {
mServer.sessions.remove_if(
[&](const SessionSharedPtr& ar) { return event.session == *ar; });
}
void EventManager::handleChatMessage(EventChatMessage& event) {
mServer.mChatManager(event);
}
void EventManager::handleChunkLoaded(events::EventChunkLoaded& event) {
event.region.addChunkAndNotifyPlayers(event.coordinates,
std::move(event.chunk));
}
} // namespace redi<file_sep>/src/nbt/serializer.hpp
#pragma once
#include <boost/endian/conversion.hpp>
#include "../bytebuffer.hpp"
#include "../util/util.hpp"
#include "forward.hpp"
#include "type.hpp"
#include "visitor.hpp"
namespace redi::nbt {
class serializer: public const_nbt_visitor {
public:
explicit serializer(ByteBuffer& buffer);
void visit(const tag_end& x) override;
void visit(const tag_byte& x) override;
void visit(const tag_short& x) override;
void visit(const tag_int& x) override;
void visit(const tag_long& x) override;
void visit(const tag_float& x) override;
void visit(const tag_double& x) override;
void visit(const tag_byte_array& x) override;
void visit(const tag_string& x) override;
void visit(const tag_list& list) override;
void visit(const tag_compound& compound) override;
void visit(const root_tag& root) override;
void visit(const tag_int_array& x) override;
void visit(const tag_long_array& x) override;
void visit(nbt_string_view name, const tag_compound& root);
template <typename T>
void write(T x);
void write(const nbt_string& string);
void write(nbt_string_view string);
void write(tag_type type);
template <typename Iterator>
void write(Iterator begin, Iterator end);
private:
ByteBuffer& buffer;
};
} // namespace redi::nbt<file_sep>/src/nbt/string.hpp
#pragma once
#include "basic.hpp"
#include "deserializer.hpp"
namespace redi::nbt {
struct tag_string : public basic_tag<tag_string> {
static constexpr tag_type type = tag_type::type_string;
nbt_string data;
tag_string() = default;
tag_string(nbt_string_view str) : data(str) {}
tag_string(nbt_string&& str) : data(std::move(str)) {}
// tag_string(const char* str) : data(str) {}
tag_string& operator=(const std::string& str) {
data = str;
return *this;
}
tag_string& operator=(std::string&& str) {
data = std::move(str);
return *this;
}
tag_string& operator=(const char* str) {
data = str;
return *this;
}
// explicit operator std::string&() { return data; }
// explicit operator const std::string&() const { return data; }
};
} // namespace redi::nbt<file_sep>/CMakeLists.txt
cmake_minimum_required(VERSION 3.2)
set(CMAKE_CXX_STANDARD 17)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
if(WIN32)
add_definitions(-DREDI_WINDOWS)
elseif(UNIX)
add_definitions(-DREDI_LINUX)
else()
message(FATAL_ERROR "Unknown operating system")
endif()
if("${CMAKE_CXX_COMPILER_ID}" STREQUAL "GNU")
set(REDI_GCC 1)
set(REDI_COMPILER_NAME "gcc")
add_definitions(-DREDI_GCC)
elseif("${CMAKE_CXX_COMPILER_ID}" STREQUAL "Clang")
set(REDI_CLANG 1)
set(REDI_COMPILER_NAME "clang")
add_definitions(-DREDI_CLANG)
elseif("${CMAKE_CXX_COMPILER_ID}" STREQUAL "MSVC")
set(REDI_MSVC 1)
set(REDI_COMPILER_NAME "MSVC")
add_definitions(-DREDI_MSVC)
else()
message(FATAL_ERROR "Unknown compiler")
endif()
add_definitions(-DBOOST_ASIO_SEPARATE_COMPILATION)
if(REDI_GCC OR REDI_CLANG)
set(warnings "-Wall -Wextra -Wpedantic -Wreorder -Wno-unused-local-typedefs -Wno-deprecated-declarations -Wno-overflow")
if (REDI_GCC)
set(compiler_options "-std=c++1z")
elseif (REDI_CLANG)
set(compiler_options "-fno-limit-debug-info -Wno-c++1z-extensions")
endif()
elseif(REDI_MSVC)
set(warnings "/W3")
set(compiler_options "${compiler_options} /std:c++latest /EHsc -D_WIN32_WINNT=0x0501 -D_SCL_SECURE_NO_WARNINGS -D_HAS_AUTO_PTR_ETC=1")
# /std:c++latest
endif()
if(CMAKE_BUILD_TYPE STREQUAL "Debug")
set(REDI_BUILD_TYPE "Debug")
else()
set(REDI_BUILD_TYPE "Release")
endif()
set(compiler_options "${compiler_options} ${warnings}")
set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} ${compiler_options}")
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} ${compiler_options}")
message(STATUS "Current compiler: ${REDI_COMPILER_NAME}")
message(STATUS "C flags: ${CMAKE_C_FLAGS}")
message(STATUS "CXX flags: ${CMAKE_CXX_FLAGS}")
message(STATUS "Build type: ${CMAKE_BUILD_TYPE} -> ${REDI_BUILD_TYPE}")
get_filename_component(BOOST_INCLUDEDIR "${BOOST_INCLUDEDIR}" REALPATH)
get_filename_component(BOOST_LIBRARYDIR "${BOOST_LIBRARYDIR}" REALPATH)
get_filename_component(JSON_REPO_DIR "${JSON_REPO_DIR}" REALPATH)
add_subdirectory(src)<file_sep>/src/nbt/array.hpp
#pragma once
#include "basic.hpp"
#include "forward.hpp"
namespace redi::nbt {
template <typename T>
struct array : public basic_tag<array<T>> {
using array_container = std::vector<T>;
using reference = typename array_container::reference;
using const_reference = typename array_container::const_reference;
static constexpr tag_type type = type_to_number<array<T>>::value;
array_container data;
array() = default;
array(const array&) = default;
array(array&&) noexcept = default;
explicit array(const array_container& other) : data(other.data) {}
explicit array(array_container&& other) : data(std::move(other)) {}
explicit array(std::size_t count) : data(count) {}
array(std::initializer_list<T> list) : data(list) {}
array& operator=(const array& other) noexcept {
*this = other.data;
return *this;
}
array& operator=(array&& other) noexcept {
*this = std::move(other.data);
return *this;
}
array& operator=(const array_container& other) {
data = other;
return *this;
}
array& operator=(array_container&& other) {
data = std::move(other);
return *this;
}
array& operator=(std::initializer_list<T> list) {
data = list;
return *this;
}
reference operator[](std::size_t index) { return data[index]; }
const_reference operator[](std::size_t index) const { return data[index]; }
reference at(std::size_t index) { return at(index); }
const_reference at(std::size_t index) const { return at(index); }
reference front() { return data.front(); }
const_reference front() const { return data.front(); }
reference back() { return data.back(); }
const_reference back() const { return data.back(); }
std::size_t size() const override { return data.size(); }
};
using tag_byte_array_container = tag_byte_array::array_container;
using tag_int_array_container = tag_int_array::array_container;
using tag_long_array_container = tag_long_array::array_container;
} // namespace redi::nbt<file_sep>/src/world.cpp
#include <boost/filesystem.hpp>
#include "player.hpp"
#include "world.hpp"
namespace fs = boost::filesystem;
namespace redi {
World::World(Server& server, const std::string& worldname,
const std::string& worlddir, WorldGenerator ptr, Dimension dim)
: HasServer(server), mWorldName(worldname), mDirectory(worlddir),
mGenerator(ptr), mChunkManager(server, mDirectory, ptr), dimension(dim),
worldTime(8000) {
static_cast<void>(dimension);
// TODO: remove this after using dimension
}
void World::addPlayer(Player& player) {
mPlayers.push_back(&player);
}
void World::deletePlayer(Player& player) {
mPlayers.remove(&player);
}
} // namespace redi<file_sep>/src/protocol/packets/packethandler.hpp
#pragma once
#include "../../threadsafequeue.hpp"
#include "server/handshakepackets.hpp"
#include "server/statuspackets.hpp"
#include "server/loginpackets.hpp"
#include "server/playpackets.hpp"
namespace redi {
class Server;
class EventManager;
class PacketHandler {
public:
PacketHandler(Server& server, Session& session, EventManager& eventh);
void addPacket(PacketUniquePtr&& packet);
void handleOne();
void readRaw(ConstBuffer buffer);
void handleHandshake(packets::Handshake& packet);
void handleStatusRequest(packets::Request& packet);
void handleStatusPing(packets::Ping& packet);
void handleLoginStart(packets::LoginStart& packet);
void handleChatMessage(packets::ChatMessage& packet);
void handlePlayerPositionAndLook(packets::PlayerPositionAndLook& packet);
void handlePlayerPosition(packets::PlayerPosition& packet);
void handlePlayerLook(packets::PlayerLook& packet);
Session& getSession() { return mSession; }
private:
Server& mServer;
Session& mSession;
std::deque<PacketUniquePtr> mPackets;
std::mutex mMutex;
};
using PacketHandlerSharedPtr = std::shared_ptr<PacketHandler>;
} // namespace redi<file_sep>/src/protocol/chunkserializer13.cpp
#include "chunkserializer13.hpp"
#include "../world/block.hpp"
#include "../logger.hpp"
namespace redi {
ChunkSerializer13::ChunkSerializer13(const Chunk& chunk, Vector2i pos,
Dimension dimension)
: mChunk(chunk), mPosition(pos), mDimension(dimension),
packet(mBuffer, 0x20) {}
ByteBuffer ChunkSerializer13::operator()() {
writeHeader(); // Header (position, etc.)
writeChunkSections(); // Chunk sections
writeBiomes(); // Biomes
writeBlockEntities(); // A big 0
return mBuffer;
}
void ChunkSerializer13::writeHeader() {
std::size_t sectionsize = 1 + // Bits per block
1 + // Palette length
2 + // VarInt data array length
ChunkSectionDataSize * 8 + // Block data size
LightDataSize; // Block light
if (mDimension == Dimension::Overworld) {
sectionsize += LightDataSize; // Skylight, if overworld
}
std::size_t size = sectionsize * 16 + BiomeDataSize;
packet.writeInt(mPosition.x); // Chunk x
packet.writeInt(mPosition.z); // Chunk z
packet.writeBool(true); // Ground-Up Continuous
packet.writeVarInt(0xFFFF); // Primary Bit Mask - Bitmask with bits set to 1
// for every 16×16×16 chunk section whose data is
// included in Data.
packet.writeVarInt(
size); // Size of Data in bytes, plus size of Biomes in bytes if present
// Logger::debug((boost::format("Sending chunk %1%") % mPosition).str());
}
void ChunkSerializer13::writeChunkSections() {
for (std::uint8_t i = 0; i < 16; ++i) {
writeChunkSection(i);
}
}
void ChunkSerializer13::writeChunkSection(std::uint8_t nth) {
packet.writeUByte(BitsPerBlock); // Bits Per Block
packet.writeUByte(0); // Palette length
packet.writeVarInt(ChunkSectionDataArraySize); // Data Array Length
std::uint64_t temp = 0;
std::uint64_t currentlyWrittenIndex = 0;
std::size_t blockindex = 0;
for (std::uint8_t y = 0; y < SectionY; ++y) {
for (std::uint8_t z = 0; z < SectionZ; ++z) {
for (std::uint8_t x = 0; x < SectionX; ++x) {
std::uint64_t blockstate =
generateBlockStateID(mChunk(x, y + SectionY * nth, z));
std::size_t bitPosition = blockindex * BitsPerBlock;
std::size_t firstIndex = bitPosition / 64;
std::size_t secondIndex = ((blockindex + 1) * BitsPerBlock - 1) / 64;
std::size_t bitOffset = bitPosition % 64;
if (firstIndex != currentlyWrittenIndex) {
packet.writeULong(temp);
temp = 0;
currentlyWrittenIndex = firstIndex;
}
temp |= blockstate << bitOffset;
if (firstIndex != secondIndex) {
packet.writeULong(temp);
currentlyWrittenIndex = secondIndex;
temp = (blockstate >> (64 - bitOffset));
}
++blockindex;
}
}
}
packet.writeULong(temp);
writeBlockLight(nth); // Block Light
if (mDimension == Dimension::Overworld) {
writeSkyLight(nth); // Sky Light
}
}
void ChunkSerializer13::writeBlockLight(std::uint8_t) {
for (std::size_t i = 0; i < 2048; ++i) {
packet.writeUByte(0xFF);
}
}
void ChunkSerializer13::writeSkyLight(std::uint8_t) {
for (std::size_t i = 0; i < 2048; ++i) {
packet.writeUByte(0xFF);
}
}
void ChunkSerializer13::writeBiomes() {
const Chunk::ChunkColumns& c = mChunk.getChunkColumns();
for (std::size_t x = 0; x < 16; ++x) {
for (std::size_t z = 0; z < 16; ++z) {
packet.writeUByte(static_cast<std::uint8_t>(
static_cast<const ChunkColumn&>(c[x][z]).biome));
}
}
}
void ChunkSerializer13::writeBlockEntities() { packet.writeVarInt(0); }
std::uint64_t ChunkSerializer13::generateBlockStateID(Block b) {
constexpr std::uint64_t OverflowMask = (1 << BitsPerBlock) - 1;
return ((static_cast<std::uint64_t>(b.type) & OverflowMask) << 4) | b.data;
}
} // namespace redi<file_sep>/src/messages/sessiondisconnected.hpp
#pragma once
#include "event.hpp"
namespace redi {
struct EventSessionDisconnect : public Event {
Session& session;
EventSessionDisconnect(Session& s)
: Event(EventType::SessionDisconnect), session(s) {}
};
} // namespace redi<file_sep>/src/protocol/packetreader.cpp
#include <stdexcept>
#include <boost/endian/conversion.hpp>
#include "packetreader.hpp"
namespace endian = boost::endian;
namespace redi {
bool PacketReader::readBool() {
need(sizeof(bool));
return data[offset++] == 1;
}
std::int8_t PacketReader::readByte() {
need(sizeof(std::int8_t));
return *reinterpret_cast<const std::int8_t*>(std::addressof(data[offset++]));
}
std::uint8_t PacketReader::readUByte() {
need(sizeof(std::uint8_t));
return data[offset++];
}
std::int16_t PacketReader::readShort() { return readBNumber<std::int16_t>(); }
std::uint16_t PacketReader::readUShort() {
return readBNumber<std::uint16_t>();
}
std::int32_t PacketReader::readInt() { return readBNumber<std::int32_t>(); }
std::int64_t PacketReader::readLong() { return readBNumber<std::int64_t>(); }
float PacketReader::readFloat() {
std::uint32_t i = readBNumber<std::uint32_t>();
auto ptr = reinterpret_cast<const std::uint8_t*>(std::addressof(i));
float x;
std::copy(ptr, ptr + sizeof(float),
reinterpret_cast<std::uint8_t*>(std::addressof(x)));
return x;
}
double PacketReader::readDouble() {
std::uint64_t i = readBNumber<std::uint64_t>();
auto ptr = reinterpret_cast<const std::uint8_t*>(std::addressof(i));
double x;
std::copy(ptr, ptr + sizeof(double),
reinterpret_cast<std::uint8_t*>(std::addressof(x)));
return x;
}
std::string PacketReader::readString() {
std::size_t size = static_cast<std::size_t>(readVarInt());
need(size);
std::string result(
reinterpret_cast<const char*>(std::addressof(data[offset])), size);
offset += size;
return result;
}
std::uint32_t PacketReader::readVarUInt() {
std::uint32_t result = 0;
int shift = 0;
std::uint8_t b = 0;
do {
b = readUByte();
result = result | ((static_cast<std::uint32_t>(b & 0x7f)) << shift);
shift += 7;
} while ((b & 0x80) != 0);
return result;
}
std::int32_t PacketReader::readVarInt() {
std::uint32_t x = readVarUInt();
return *reinterpret_cast<std::int32_t*>(std::addressof(x));
}
std::uint64_t PacketReader::readVarULong() {
std::uint64_t result = 0;
int shift = 0;
std::uint8_t b = 0;
do {
b = readUByte();
result = result | ((static_cast<std::uint64_t>(b & 0x7f)) << shift);
shift += 7;
} while ((b & 0x80) != 0);
return result;
}
std::int64_t PacketReader::readVarLong() {
std::uint64_t x = readVarULong();
return *reinterpret_cast<std::int64_t*>(std::addressof(x));
}
Vector3i PacketReader::readPosition() {
Vector3i result;
std::int64_t raw = readLong();
std::uint32_t rx = static_cast<std::uint32_t>((raw >> 38) & 0x03ffffff);
std::uint32_t ry = static_cast<std::uint32_t>((raw >> 26) & 0x0fff);
std::uint32_t rz = static_cast<std::uint32_t>(raw & 0x03ffffff);
result.x = (rx & 0x02000000) == 0
? static_cast<std::int32_t>(rx)
: -(0x04000000 - static_cast<std::int32_t>(rx));
result.y = (ry & 0x0800) == 0 ? static_cast<std::int32_t>(ry)
: -(0x0800 - static_cast<std::int32_t>(ry));
result.z = (rz & 0x02000000) == 0
? static_cast<std::int32_t>(rz)
: -(0x04000000 - static_cast<std::int32_t>(rz));
return result;
}
ByteBuffer PacketReader::readByteArray(std::size_t size) {
need(size);
ByteBuffer result(data.data(), size);
offset += size;
return result;
}
void PacketReader::need(std::size_t bytes) {
if (bytes + offset > data.size()) {
throw std::runtime_error(std::to_string(bytes) + " is out of index");
}
}
void PacketReader::consumeUShort() {
need(sizeof(std::uint16_t));
offset += sizeof(std::uint16_t);
}
void PacketReader::consumeInt() {
need(sizeof(std::int32_t));
offset += sizeof(std::int32_t);
}
void PacketReader::consumeString() {
std::size_t size = static_cast<std::size_t>(readVarInt());
need(size);
offset += size;
}
void PacketReader::consumeVarInt() { static_cast<void>(readVarInt()); }
} // namespace redi<file_sep>/src/protocol/packets/server/handshakepackets.cpp
#include <boost/format.hpp>
#include "handshakepackets.hpp"
#include "../../../logger.hpp"
#include "../../packetwriter.hpp"
#include "../packethandler.hpp"
namespace redi::packets {
Handshake::Handshake(PacketReader& packet) { read(packet); }
Handshake::Handshake(std::int32_t version, std::string hostname,
std::uint16_t port, ConnectionState state)
: version(version), hostname(hostname), port(port), state(state) {}
void Handshake::read(PacketReader& packet) {
version = packet.readVarInt();
hostname = packet.readString();
port = packet.readUShort();
std::int32_t nextstate = packet.readVarInt();
switch (nextstate) {
case 1:
state = ConnectionState::Status;
break;
case 2:
state = ConnectionState::Login;
break;
default:
Logger::info(std::string("Invalid state: ") + std::to_string(nextstate));
}
}
void Handshake::process(PacketHandler& handler) {
handler.handleHandshake(*this);
}
} // namespace redi<file_sep>/travisbuild.sh
#!/usr/bin/env bash
set -x
sudo update-alternatives --install /usr/bin/gcc gcc /usr/bin/gcc-8 100 --slave /usr/bin/g++ g++ /usr/bin/g++-8
if [ ! -d "libs/boost/lib/" ]; then
wget https://dl.bintray.com/boostorg/release/1.68.0/source/boost_1_68_0.tar.bz2
tar -xjf boost_1_68_0.tar.bz2
cd boost_1_68_0/
sudo ./bootstrap.sh --prefix=../libs/boost/
sudo ./b2 install -j 8
cd ..
fi
if [ -f "libs/json/src/json.hpp" ]; then
cd libs/json/
git pull
cd ../..
else
cd libs/
git clone https://github.com/nlohmann/json.git
cd ..
fi
if [ ! -d "libs/openssl-1.0.2g" ]; then
cd libs/
wget https://www.openssl.org/source/openssl-1.0.2g.tar.gz
tar -xzf openssl-1.0.2g.tar.gz
cd openssl-1.0.2g
sudo ./config
sudo make install
cd ../..
fi
mkdir build
cd build
cmake .. -DBOOST_INCLUDEDIR=libs/boost/include -DBOOST_LIBRARYDIR=libs/boost/lib -DJSON_REPO_DIR=libs/json
make -j4<file_sep>/src/messages/playerpositionandlook.hpp
#pragma once
#include "event.hpp"
#include "../player.hpp"
#include "../playerposition.hpp"
#include "../vectorn.hpp"
namespace redi {
struct EventPlayerPositionAndLook : public Event,
public Vector3d,
public PlayerLook {
bool onGround;
Player& player;
EventPlayerPositionAndLook(Player& player, double x = 0.0, double y = 0.0,
double z = 0.0, float yaw = 0.0f,
float pitch = 0.0f, bool onGround = true)
: Event(EventType::PlayerPositionAndLook), Vector3d(x, y, z),
PlayerLook(yaw, pitch), onGround(onGround), player(player) {}
};
} // namespace redi<file_sep>/src/util/time.cpp
#include <boost/date_time/posix_time/posix_time.hpp>
#include <boost/date_time/posix_time/ptime.hpp>
#include "time.hpp"
namespace redi {
namespace util {
std::int32_t getUnixTimestamp() {
boost::posix_time::ptime epoch(boost::gregorian::date(1970, 1, 1));
return (boost::posix_time::second_clock::universal_time() - epoch)
.total_seconds();
}
std::int64_t getUnixTimestampMilliseconds() {
boost::posix_time::ptime epoch(boost::gregorian::date(1970, 1, 1));
return (boost::posix_time::second_clock::universal_time() - epoch)
.total_milliseconds();
}
std::int32_t getRandomInt32() {
return 4;
// Got from rolling a virtual dice
// Proof: https://www.random.org/dice/dice4.png
}
} // namespace util
} // namespace redi
<file_sep>/src/messages/sendkeepalivering.hpp
#pragma once
#include "event.hpp"
#include "../session.hpp"
namespace redi {
struct EventSendKeepAliveRing : public Event {
Session& session;
EventSendKeepAliveRing(Session& session)
: Event(EventType::SendKeepAliveRing), session(session) {}
};
} // namespace redi<file_sep>/src/util/string.cpp
#include "string.hpp"
#if defined __GNUC__ || defined __MINGW32__ || defined __MINGW64__
#include <cxxabi.h>
#endif
namespace redi::util {
#if defined __GNUC__ || defined __MINGW32__ || defined __MINGW64__
std::string demangleTypeName(const char* str) {
// https://gcc.gnu.org/onlinedocs/libstdc++/manual/ext_demangling.html
int status;
char* realname;
realname = abi::__cxa_demangle(str, nullptr, 0, &status);
std::string result(realname);
free(realname);
return result;
}
#else
std::string demangleTypeName(const char* str) {
return str;
}
#endif
}<file_sep>/src/server.cpp
#include "util/util.hpp"
#include "logger.hpp"
#include "commands/redicommands.hpp"
#include "player.hpp"
#include "server.hpp"
namespace fs = boost::filesystem;
namespace redi {
std::unique_ptr<redi::Networking> getAsioNetworking(boost::asio::io_context& context);
std::unique_ptr<redi::Networking> getLinuxNetworking();
Server::Server()
:
workWorkIoService(workIoService),
// networking(getAsioNetworking(workIoService)),
networking(getLinuxNetworking()),
connectionListener(networking->getListener([this] (std::shared_ptr<Socket> socket, std::string message) {
this->onSocketConnected(socket, message);
}, static_cast<uint16_t>(configuration.port))),
mEntityCount(0),
mChatManager(*this), mEventManager(*this),
commandmanager(*this), commands(std::make_unique<commands::RediCommands>(*this)), running(true),
mUniqueLock(mCondVarMutex) {
fs::create_directories("players");
fs::create_directories("worlds");
addWorld("world", "worlds/world");
// mListener->listen();
asiothreads.create(AsioThreadsNumber, [&] () {
Logger::debug((boost::format("Asio work thread id %1% started") %
std::this_thread::get_id())
.str());
workIoService.run();
Logger::debug((boost::format("Asio work thread id %1% stopped") %
std::this_thread::get_id())
.str());
});
Logger::info("Redi has started");
}
Server::~Server() {
Logger::debug("Redi is stopping");
workIoService.stop();
}
void Server::onSocketConnected(std::shared_ptr<redi::Socket> socket, std::string error) {
auto session = std::make_shared<Session>(std::move(socket), *this);
addTask([session, this] () { sessions.push_back(session); });
}
void Server::run() {
while (true) {
handleOne();
if (!running) {
break;
}
mCondVar.wait(mUniqueLock);
}
closeServer();
handleOne();
}
void Server::handleOne() {
while (true) {
std::function<void()> x;
if (!mPacketsToBeHandle.pop(x) || !x)
break;
try {
x();
} catch (std::exception& e) {
Logger::error(e.what());
// Just ignore everything bad.
// x->getSession().disconnect();
// and disconnect
// TODO: add message
}
}
try {
mEventManager();
} catch (std::exception&) {
throw;
}
}
void Server::addTask(std::function<void()> function) {
mPacketsToBeHandle.push(std::move(function));
mCondVar.notify_one();
}
void Server::addEvent(EventUniquePtr&& ptr) {
mEventManager.addEvent(std::move(ptr));
mCondVar.notify_one();
}
void Server::addWorld(const std::string& worldname,
const std::string& worlddir) {
mWorlds.emplace_back(*this, worldname, worlddir,
std::make_shared<TerrainGenerator>());
}
Player* Server::findPlayer(const std::string& name) {
Player* ptr = nullptr;
for (auto& index : mPlayers) {
if (util::noCaseCompareEqual(name, index->getUsername())) {
ptr = index.get();
break;
}
}
return ptr;
}
void Server::closeServer() {
for (auto& i : mPlayers) {
i->kick("Server is closing");
}
networking->stop();
}
void Server::stop() {
running = false;
mCondVar.notify_one();
}
} // namespace redi
<file_sep>/src/util/file.cpp
#include <fstream>
#include "util.hpp"
#include "../filesystem.hpp"
namespace redi {
namespace util {
ByteBuffer readFile(const std::string& path) {
if (!fs::exists(path)) {
throw std::runtime_error(path + " doesn't exist");
}
ByteBuffer buffer;
auto size = fs::file_size(path);
buffer.resize(static_cast<ByteBuffer::size_type>(size));
std::ifstream file(path, std::ios::binary);
file.read(buffer.as_char(), size);
return buffer;
}
std::string readFileToString(const std::string& path) {
if (!fs::exists(path)) {
throw std::runtime_error(path + " doesn't exist");
}
std::string str;
auto size = fs::file_size(path);
str.resize(static_cast<ByteBuffer::size_type>(size));
std::ifstream file(path, std::ios::binary);
file.read(&str[0], size);
return str;
}
} // namespace util
} // namespace redi
<file_sep>/src/world/anvil.cpp
#include <boost/filesystem.hpp>
#include <boost/endian/conversion.hpp>
#include <boost/endian/arithmetic.hpp>
#include "anvil.hpp"
#include "../logger.hpp"
#include "../util/util.hpp"
#include "../util/compressor.hpp"
namespace fs = boost::filesystem;
namespace endian = boost::endian;
namespace redi {
namespace world {
Anvil::Anvil() : hasRegion(false) {}
Anvil::Anvil(const std::string& path, const Vector2i& pos, bool create)
: Anvil(fs::path(path), pos, create) {}
Anvil::Anvil(const boost::filesystem::path& path, const Vector2i& pos,
bool create) {
open(path, pos, create);
}
Anvil::~Anvil() { close(); }
void Anvil::open(const boost::filesystem::path& path, const Vector2i& pos,
bool create) {
clear();
position = pos;
createNewRegionIfOK(path, create);
auto filesize = fs::file_size(path);
if (filesize % 4_KB != 0 || filesize < HeaderSize) {
fs::path newpath(path.string() + ".backup");
Logger::info((boost::format("%1% has an invalid size(%2% bytes). Renaming "
"to %3% and trying to create a new one") %
path % filesize % newpath)
.str());
fs::rename(path, newpath);
createNewRegionIfOK(path, create);
} else {
openFile(path.string());
}
hasRegion = true;
freeSectors.resize(static_cast<std::size_t>(filesize / SectorSize));
readHeader();
processHeader();
}
void Anvil::close() {
if (hasRegion) {
flush();
clear();
}
}
void Anvil::flush() {
file.seekp(0, file.beg);
file.write(reinterpret_cast<const char*>(header.data()), header.size());
}
void Anvil::clear() {
file.close();
hasRegion = false;
freeSectors.clear();
}
void Anvil::openFile(const std::string& path) {
file.open(path, std::ios::in | std::ios::out | std::ios::binary);
file.exceptions(std::ios::failbit | std::ios::badbit);
}
void Anvil::createNewRegionAndOpen(const std::string& filepath) {
file.open(filepath,
std::ios::in | std::ios::out | std::ios::binary | std::ios::trunc);
file.exceptions(std::ios::failbit | std::ios::badbit);
// openFile(filepath);
std::fill(header.begin(), header.end(), 0);
flush();
file.close();
}
std::int32_t Anvil::getChunkNumberInRegion(const Vector2i& other) {
return (other.x & 31) + (other.z & 31) * 32;
// return 4 * ((other.x & 31) + (other.z & 31) * 32);
}
Vector2i Anvil::getRegionCoordsFromChunkCoords(const Vector2i& chcoords) {
Vector2i x(chcoords.x / 32, chcoords.z / 32);
if (chcoords.x < 0) {
--x.x;
}
if (chcoords.z < 0) {
--x.z;
}
return x;
}
void Anvil::createNewRegionIfOK(const fs::path& filepath, bool create) {
if (!fs::exists(filepath)) {
if (!create) {
throw std::runtime_error(
"Region file doesn't exists and set to not create: " +
filepath.string());
}
createNewRegionAndOpen(filepath.string());
}
}
void Anvil::readHeader() {
file.seekg(0, file.beg);
file.read(reinterpret_cast<char*>(header.data()), header.size());
}
void Anvil::processHeader() {
freeSectors[0] = freeSectors[1] = false;
for (std::int32_t i = 0; i < ChunksPerRegion; ++i) {
ChunkInfo info = getChunkInfo(i);
if (info.offset + info.sectors > freeSectors.size()) {
Logger::warn(
(boost::format("Chunk number %1% is out of range. Free sectors size "
": %2%. info.offset: %3%. info.sectors: %4%") %
i % freeSectors.size() % info.offset % info.sectors)
.str());
writeChunkInfo(i, ChunkInfo());
continue;
}
for (std::size_t j = info.offset, max = info.offset + info.sectors; j < max;
++j) {
freeSectors[j] = false;
}
}
}
Anvil::ChunkInfo Anvil::getChunkInfo(std::int32_t number) const {
assert(0 <= number && number < ChunksPerRegion);
ChunkInfo info;
info.sectors = header[number * 4 + 3];
{
auto begin = header.begin() + static_cast<std::size_t>(number * 4);
auto end = begin + sizeof(info.offset) - 1;
endian::big_uint24_t x;
std::copy(begin, end, reinterpret_cast<std::uint8_t*>(&x));
info.offset = static_cast<std::uint32_t>(x);
}
{
auto begin = header.begin() + SectorSize + number * 4;
auto end = begin + sizeof(info.time);
std::copy(begin, end, reinterpret_cast<std::uint8_t*>(&info.time));
endian::big_to_native_inplace(info.time);
}
return info;
}
Anvil::ChunkInfo Anvil::getChunkInfo(const Vector2i& chunk) const {
return getChunkInfo(getChunkNumberInRegion(chunk));
}
void Anvil::writeChunkInfo(const Vector2i& number,
const Anvil::ChunkInfo& chunk) {
writeChunkInfo(getChunkNumberInRegion(number), chunk);
}
void Anvil::writeChunkInfo(std::int32_t number, const Anvil::ChunkInfo& info) {
header[number * 4 + 3] = info.sectors;
{
endian::big_uint24_t x = info.offset;
auto begin = reinterpret_cast<const std::uint8_t*>(&x);
auto end = begin + sizeof(info.offset) - 1;
std::copy(begin, end, header.begin() + number * 4);
}
{
auto x = endian::native_to_big(info.time);
auto begin = reinterpret_cast<const std::uint8_t*>(&x);
auto end = begin + sizeof(info.time);
std::copy(begin, end, header.begin() + SectorSize + number * 4);
}
std::ofstream("a.b").write(reinterpret_cast<const char*>(header.data()),
header.size());
}
Anvil::ChunkReadResult Anvil::readChunk(const Vector2i& number,
ByteBuffer& buffer) {
return readChunk(getChunkNumberInRegion(number), buffer);
}
void Anvil::writeChunk(const Vector2i& number,
const ByteBuffer& uncompresseddata) {
writeChunk(getChunkNumberInRegion(number), uncompresseddata);
}
Anvil::ChunkReadResult Anvil::readChunk(std::int32_t number,
ByteBuffer& buffer) {
#ifdef REDI_DEBUG
if (!(0 <= number && number < 1024)) {
}
#endif
ChunkInfo info = getChunkInfo(number);
if (info.offset == 0 || info.sectors == 0) {
return ChunkReadResult::DoesntExists;
}
buffer.resize(SectorSize * info.sectors);
file.seekg(info.offset * SectorSize);
file.read(buffer.as_char(), buffer.size());
if (file.gcount() < 5) {
Logger::error(std::to_string(file.gcount()) +
" bytes read in Anvil.read. Expected at least 5");
return ChunkReadResult::Error;
}
std::uint32_t size;
std::copy(buffer.data(), buffer.data() + sizeof(size),
reinterpret_cast<std::uint8_t*>(&size));
endian::big_to_native_inplace(size);
if (size < 5) {
Logger::error(std::to_string(size) +
" bytes marked in chunk in Anvil.read. Expected at least 5");
return ChunkReadResult::Error;
}
switch (buffer[4]) {
case 1: {
// TODO: fix compressorold and add decompressor
} break;
case 2: {
buffer = util::zip::zlib::decompress(ConstBuffer(buffer.data() + 5, size - 1));
} break;
default: {
Logger::error(std::to_string(static_cast<int>(buffer[4])) +
" - unknown compression in Anvil.read. Expected 1 or 2.");
return ChunkReadResult::Error;
}
}
return ChunkReadResult::OK;
}
void Anvil::writeChunk(std::int32_t number,
const ByteBuffer& uncompresseddata) {
constexpr std::size_t sizetmax = std::numeric_limits<std::size_t>::max();
#ifdef REDI_DEBUG
if (!(0 <= number && number < 1024)) {
}
#endif
ByteBuffer buffer;
{
buffer.reserve(SectorSize);
buffer.resize(5);
}
util::zip::zlib::compress(ConstBuffer(uncompresseddata), buffer);
std::size_t datasize = buffer.size();
ChunkInfo info = getChunkInfo(number);
std::size_t newSectorCount = getSectorsNumber(datasize);
if (newSectorCount == info.sectors) {
/*
* If the actual sector count is equal
* with the old one, just overwrite.
*/
file.seekp(info.offset * SectorSize);
} else {
for (std::size_t i = info.offset; i < info.offset + info.sectors; ++i) {
freeSectors[i] = true;
// Mark old sectors as free
}
std::size_t start = sizetmax;
std::size_t len = 0;
for (std::size_t i = 0; i < freeSectors.size(); ++i) {
if (freeSectors[i]) {
start = i;
for (; i < freeSectors.size() && freeSectors[i]; ++i)
;
len = i - start;
if (len == newSectorCount)
break;
// Perfect
}
}
if (start == sizetmax) {
// If no good sectors were found
file.seekp(0, file.end);
// Set to end of file
buffer.resize(datasize + SectorSize - datasize % SectorSize);
// Make it 4 kb divisible
info.offset = static_cast<std::uint32_t>(freeSectors.size());
// Update the information about this chunk in the header
for (std::size_t i = 0; i < info.sectors; ++i) {
freeSectors.push_back(false);
}
} else {
// Good sectors were found.
file.seekp(start * SectorSize);
info.offset = static_cast<std::uint32_t>(start);
}
info.sectors = static_cast<std::uint8_t>(newSectorCount);
}
info.time = static_cast<std::uint32_t>(util::getUnixTimestamp());
{
std::uint32_t x =
endian::native_to_big(static_cast<std::uint32_t>(datasize - 4));
auto ptr = reinterpret_cast<const std::uint8_t*>(&x);
std::copy(ptr, ptr + sizeof(x), buffer.data());
// size
buffer[4] = 2;
// compression
}
file.write(buffer.as_const_char(), buffer.size());
writeChunkInfo(number, info);
}
size_t Anvil::getSectorsNumber(std::size_t size) {
std::size_t ret = size / SectorSize;
if (size % SectorSize != 0) {
++ret;
}
return ret;
}
} // namespace world
} // namespace redi<file_sep>/src/nbt/end.hpp
#pragma once
#include "basic.hpp"
namespace redi::nbt {
class tag_end : public basic_tag<tag_end> {
public:
static constexpr tag_type type = tag_type::type_end;
};
}<file_sep>/src/nbt/creator.cpp
#include "primitive.hpp"
#include "string.hpp"
#include "array.hpp"
#include "compound.hpp"
#include "list.hpp"
#include "creator.hpp"
#include "end.hpp"
namespace redi::nbt {
tag_unique_ptr create(tag_type t) {
tag_unique_ptr ptr;
switch (t) {
case tag_type::type_end: {
ptr = std::make_unique<tag_end>();
} break;
case tag_type::type_byte: {
ptr = std::make_unique<tag_byte>();
} break;
case tag_type::type_short: {
ptr = std::make_unique<tag_short>();
} break;
case tag_type::type_int: {
ptr = std::make_unique<tag_int>();
} break;
case tag_type::type_long: {
ptr = std::make_unique<tag_long>();
} break;
case tag_type::type_float: {
ptr = std::make_unique<tag_float>();
} break;
case tag_type::type_double: {
ptr = std::make_unique<tag_double>();
} break;
case tag_type::type_byte_array: {
ptr = std::make_unique<tag_byte_array>();
} break;
case tag_type::type_string: {
ptr = std::make_unique<tag_string>();
} break;
case tag_type::type_list: {
ptr = std::make_unique<tag_list>();
} break;
case tag_type::type_compound: {
ptr = std::make_unique<tag_compound>();
} break;
case tag_type::type_int_array: {
ptr = std::make_unique<tag_int_array>();
} break;
case tag_type::type_long_array: {
ptr = std::make_unique<tag_long_array>();
} break;
}
return ptr;
}
tag_value createValue(tag_type t) { return tag_value(create(t)); }
} // namespace redi::nbt<file_sep>/src/filesystem.hpp
#pragma once
#include <boost/filesystem.hpp>
namespace redi {
namespace filesystem {
using namespace boost::filesystem;
}
namespace fs = filesystem;
}<file_sep>/src/protocol/packets/server/handshakepackets.hpp
#pragma once
#include "../packet.hpp"
#include "../../../enums.hpp"
namespace redi::packets {
struct Handshake : public Packet {
std::int32_t version;
std::string hostname;
std::uint16_t port;
ConnectionState state;
Handshake() = default;
Handshake(PacketReader& packet);
Handshake(std::int32_t version, std::string hostname, std::uint16_t port,
ConnectionState state);
void read(PacketReader& packet) override;
virtual void process(PacketHandler& handler) override;
};
} // namespace redi<file_sep>/src/networking.hpp
#pragma once
#include <functional>
#include <memory>
#include "buffers.hpp"
namespace redi {
class Socket;
using socket_accept_handler = std::function<void(std::shared_ptr<Socket>, std::string)>;
using socket_read_handler = std::function<void(size_t, std::string)>;
class Socket {
public:
Socket();
virtual ~Socket() = 0;
virtual void read(MutableBuffer buffer) = 0;
virtual void write(ConstBuffer buffer) = 0;
virtual void write(ConstBuffer* buffers, size_t size);
virtual void close() = 0;
void set_accept_handler(socket_accept_handler handler);
void set_read_handler(socket_read_handler handler);
protected:
socket_accept_handler accept_handler;
socket_read_handler read_handler;
};
using SocketSharedPtr = std::shared_ptr<Socket>;
class Networking {
public:
virtual ~Networking() = 0;
virtual std::shared_ptr<Socket> getListener(socket_accept_handler handler, uint16_t port) = 0;
virtual void stop() = 0;
};
}<file_sep>/src/nbt/tag.hpp
#pragma once
#include <iostream>
#include <memory>
#include "type.hpp"
#include "forward.hpp"
namespace redi::nbt {
class tag {
public:
virtual ~tag() = 0;
bool is_number() const;
bool is_scalar() const;
bool is_vector() const;
bool is_container() const;
virtual std::size_t size() const { return 1; }
virtual tag& assign(tag&& tag) = 0;
virtual tag& assign(const tag& tag) = 0;
virtual tag_type get_type() const { return tag_type::type_end; }
virtual std::unique_ptr<tag> clone() const& = 0;
virtual std::unique_ptr<tag> move() && = 0;
virtual bool equals(const tag&) const { return false; }
virtual void visit(nbt_visitor&) = 0;
virtual void visit(const_nbt_visitor&) const = 0;
};
std::ostream& operator<<(std::ostream& stream, const tag& tag);
using tag_unique_ptr = std::unique_ptr<tag>;
} // namespace redi::nbt<file_sep>/src/world/anvilregion.cpp
#include <boost/filesystem.hpp>
#include <boost/endian/conversion.hpp>
#include "anvilregion.hpp"
#include "../bytebuffer.hpp"
#include "../logger.hpp"
#include "../util/util.hpp"
#include "../util/compressor.hpp"
namespace fs = boost::filesystem;
namespace endian = boost::endian;
namespace redi {
namespace world {
AnvilRegion::AnvilRegion(const std::string& filepath) { open(filepath); }
AnvilRegion::~AnvilRegion() { close(); }
void AnvilRegion::open(const std::string& filepath) {
clear();
fs::path path(filepath);
if (!fs::exists(path))
createNewRegion(filepath);
std::uintmax_t size = fs::file_size(path);
if (size % 4 != 0 || size < HeaderSize)
createNewRegion(filepath);
mFile.open(filepath, std::ios::in | std::ios::out | std::ios::binary);
if (!mFile)
throw std::invalid_argument("can't open file " + filepath);
mFreeSectors.resize(static_cast<std::size_t>(size / SectorSize));
std::fill(mFreeSectors.begin(), mFreeSectors.end(), true);
readHeader();
hasRegion = true;
}
ByteBuffer AnvilRegion::readChunk(Vector2i ch) {
ByteBuffer result(ChunkHeaderSize, '\0');
std::int32_t chunknumber = getChunkNumberInRegion(ch);
ChunkInfo& th = mChunks[chunknumber];
if (th.offset == 0)
return ByteBuffer();
mFile.seekg(th.offset * SectorSize);
mFile.read(reinterpret_cast<char*>(&result[0]), ChunkHeaderSize);
std::int32_t size;
std::memcpy(&size, &result[0], sizeof(std::int32_t));
endian::big_to_native_inplace(size);
if (size < 5) {
return {};
}
result.resize(--size);
std::uint8_t compressionFormat = result[4];
mFile.read(reinterpret_cast<char*>(&result[0]), size);
switch (compressionFormat) {
case 1:
result = util::zip::gzip::decompress(ConstBuffer(result));
break;
case 2:
result = util::zip::zlib::decompress(ConstBuffer(result));
break;
default:
result.clear();
break;
}
return result;
}
void AnvilRegion::writeChunk(Vector2i ch, const ByteBuffer& data,
bool updateDate) {
ByteBuffer result(ChunkHeaderSize, '\0');
std::int32_t chunknumber = getChunkNumberInRegion(ch);
ChunkInfo& th = mChunks[chunknumber];
ByteBuffer dataToBeWritten(util::zip::zlib::compress(ConstBuffer(data)));
std::size_t newSectorsCount =
((dataToBeWritten.size() + 5) % SectorSize == 0)
? (dataToBeWritten.size() + 5) / SectorSize
: (dataToBeWritten.size() + 5) / SectorSize + 1;
if (th.sectors == newSectorsCount) {
/*
* If the actual sector count is equal
* with the old one, just overwrite.
*/
mFile.seekp(th.offset * SectorSize);
} else {
for (std::size_t i = th.offset; i < th.offset + th.sectors; ++i)
mFreeSectors[i] = true;
// Mark old sectors as free
std::int32_t start = -1;
std::size_t len;
// If start is -1, no good sectors were found
for (std::size_t i = 0; i < mFreeSectors.size(); ++i)
if (mFreeSectors[i]) {
start = static_cast<std::int32_t>(i);
for (; i < mFreeSectors.size() && mFreeSectors[i]; ++i)
;
len = i - start;
if (len == newSectorsCount)
break;
// Perfect
}
if (start == -1) {
/*
* If no good sectors were found
* add at the end of the file.
*/
mFile.seekp(0, mFile.end);
if (data.size() % 4096 != 0)
dataToBeWritten.resize(dataToBeWritten.size() +
(4096 - dataToBeWritten.size() % 4096));
// Pad with zeros
th.offset = static_cast<std::int32_t>(mFreeSectors.size());
th.sectors = static_cast<std::uint8_t>(newSectorsCount);
for (std::size_t i = 0; i < th.sectors; ++i)
mFreeSectors.push_back(false);
} else {
// Good sectors were found.
mFile.seekp(start * SectorSize);
th.offset = static_cast<std::int32_t>(start);
th.sectors = static_cast<std::uint8_t>(newSectorsCount);
}
}
char buffer[5];
buffer[4] = 2;
chunknumber = endian::native_to_big(static_cast<std::int32_t>(
dataToBeWritten.size() + 1)); // recycling variables
// TODO: is it +1 or -1 here ?
std::memcpy(buffer, &chunknumber, sizeof(std::int32_t));
mFile.write(buffer, 5);
mFile.write(reinterpret_cast<const char*>(&dataToBeWritten[0]),
dataToBeWritten.size());
if (updateDate)
th.time = util::getUnixTimestamp();
}
void AnvilRegion::clear() {
mFile.close();
mFreeSectors.clear();
std::fill(mChunks.begin(), mChunks.end(), ChunkInfo());
hasRegion = false;
}
void AnvilRegion::close() {
saveHeader();
clear();
}
void AnvilRegion::flush() {
saveHeader();
mFile << std::flush;
}
void AnvilRegion::createNewRegion(const std::string& filepath) {
std::ofstream file(filepath, std::ios::binary);
if (!file)
throw std::invalid_argument("can't open file " + filepath);
file.write(std::array<char, HeaderSize>().data(), HeaderSize);
}
std::int32_t AnvilRegion::getChunkNumberInRegion(Vector2i other) {
return (other.x & 31) + (other.z & 31) * 32;
}
void AnvilRegion::readHeader() {
ByteBuffer buffer(HeaderSize, static_cast<std::uint8_t>(0));
mFile.seekg(std::ios::beg);
mFile.read(reinterpret_cast<char*>(&buffer[0]), HeaderSize);
mFreeSectors[0] = mFreeSectors[1] = false;
for (std::size_t i = 0; i < ChunksPerRegion; ++i) {
ChunkInfo& th = mChunks[i];
th.sectors = buffer[i * 4 + 3];
buffer[i * 4 + 3] = 0;
std::memcpy(reinterpret_cast<std::uint8_t*>(&th.offset) + 1,
buffer.data() + i * 4, sizeof(std::int32_t) - 1);
endian::big_to_native_inplace(th.offset);
std::memcpy(&th.time, buffer.data() + SectorSize + i * 4,
sizeof(std::int32_t));
endian::big_to_native_inplace(th.time);
if (th.offset + th.sectors > mFreeSectors.size()) {
Logger::warn(std::to_string(i) + " is out of range");
th.offset = th.time = 0;
th.sectors = 0;
continue;
}
for (std::size_t j = th.offset, max = th.offset + th.sectors; j < max; ++j)
mFreeSectors[j] = false;
}
}
void AnvilRegion::saveHeader() {
ByteBuffer buf(HeaderSize, static_cast<std::uint8_t>(0));
std::uint8_t* buffer = &buf[0];
for (std::size_t i = 0; i < ChunksPerRegion; ++i) {
ChunkInfo& th = mChunks[i];
th.offset = endian::native_to_big(th.offset) >> 8;
endian::native_to_big_inplace(th.time);
reinterpret_cast<std::uint8_t*>(&th.offset)[3] = th.sectors;
std::memcpy(buffer + i * 4, &th.offset, sizeof(std::uint32_t));
std::memcpy(buffer + i * 4 + SectorSize, &th.time, sizeof(std::uint32_t));
}
mFile.seekp(0, mFile.beg);
mFile.write(reinterpret_cast<const char*>(buffer), buf.size());
}
Vector2i AnvilRegion::getRegionCoordsFromChunkCoords(const Vector2i& chcoords) {
Vector2i x(chcoords.x / 32, chcoords.z / 32);
if (chcoords.x < 0) {
--x.x;
}
if (chcoords.z < 0) {
--x.z;
}
return x;
}
} // namespace world
} // namespace redi<file_sep>/src/messages/event.hpp
#pragma once
#include "eventtype.hpp"
namespace redi {
struct Event {
const EventType type;
Event(EventType type) : type(type) {}
virtual ~Event() = 0;
EventType getType() const { return type; }
template <typename T>
T& get() {
T* ptr = dynamic_cast<T*>(this);
if (ptr)
return *ptr;
throw std::runtime_error("Event dynamic cast failed");
}
};
inline Event::~Event() {}
using EventUniquePtr = std::unique_ptr<Event>;
} // namespace redi<file_sep>/src/nbt/deserializer.hpp
#pragma once
#include <boost/endian/conversion.hpp>
#include "../bytebuffer.hpp"
#include "type.hpp"
#include "../util/string.hpp"
namespace redi::nbt {
class deserializer : public nbt_visitor {
public:
explicit deserializer(const ByteBuffer& buffer, std::size_t offset = 0);
void visit(tag_end& x) override;
void visit(tag_byte& x) override;
void visit(tag_short& x) override;
void visit(tag_int& x) override;
void visit(tag_long& x) override;
void visit(tag_float& x) override;
void visit(tag_double& x) override;
void visit(tag_byte_array& array) override;
void visit(tag_string& string) override;
void visit(tag_list& list) override;
void visit(tag_compound& compound) override;
void visit(root_tag& tag) override;
void visit(tag_int_array& array) override;
void visit(tag_long_array& array) override;
void visit(nbt_string& name, tag_compound& compound);
private:
const ByteBuffer& buffer;
std::size_t offset;
template <typename T>
T readNumber();
template <typename T>
void readNumber(T& x);
template <typename T>
void readArray(std::vector<T>& array);
nbt_string readString();
tag_type readType();
void need(std::size_t bytes);
};
} // namespace redi::nbt<file_sep>/src/main.cpp
#include <csignal>
#include "server.hpp"
namespace {
// Global variable to server to be able to call it
// from signal function
redi::Server* server{};
// Handles signals and closes the server
// in case of interrupt or any other error
void signalHandler(int signal) {
switch (signal) {
case SIGTERM:
case SIGSEGV:
case SIGINT:
case SIGILL:
case SIGABRT:
case SIGFPE:
{
if (server) {
server->stop();
}
}
break;
default:
break;
}
}
// Initializes global server variable and
// signals callback.
void installSignals(redi::Server& server) {
::server = &server;
std::signal(SIGTERM, ::signalHandler);
std::signal(SIGSEGV, ::signalHandler);
std::signal(SIGINT, ::signalHandler);
std::signal(SIGILL, ::signalHandler);
std::signal(SIGABRT, ::signalHandler);
std::signal(SIGFPE, ::signalHandler);
}
}
//std::unique_ptr<redi::Networking> getAsioNetworking(boost::asio::io_context& context);
int main(int, char**) {
redi::Logger::debug("Redi is starting");
try {
redi::Server server;
::installSignals(server);
server.run();
} catch (std::exception& e) {
redi::Logger::error(e.what());
}
redi::Logger::info("Redi has stopped");
return 0;
}
<file_sep>/src/commands/commandmanager.hpp
#pragma once
#include <list>
#include <unordered_map>
#include "../hasserver.hpp"
#include "commandsender.hpp"
#include "../datatypes.hpp"
#include "commanddata.hpp"
namespace redi {
namespace commands {
class Command;
enum class CommandAddResult {
AlreadyExists, NullPointer, Ok
};
class CommandManager : HasServer {
public:
using CommandsContainer = std::unordered_map<std::string, CommandData>;
CommandManager(Server& server) : HasServer(server) {}
CommandManager& operator()(CommandSender& sender, std::string& message);
CommandAddResult
registerCommand(Command* ptr, const std::string& command, const std::vector<std::string>& aliases = {});
// void unregisterCommand(string_view command);
void unregisterAll(Command* ptr);
private:
std::unordered_map<std::string, CommandData*> commands;
std::unordered_map<Command*, std::list<CommandData>> data;
};
}
} // namespace redi<file_sep>/src/logger.hpp
#pragma once
#include <deque>
#include <fstream>
#include <mutex>
#include <thread>
#include <tuple>
#include <boost/chrono/chrono.hpp>
#include <boost/date_time/posix_time/posix_time.hpp>
#include <boost/format.hpp>
#include <boost/thread/thread.hpp>
namespace redi {
enum class LoggerLevel { Debug, Info, Warn, Error, Fatal };
const char* getEnumName(LoggerLevel level);
class Logger {
public:
Logger();
~Logger();
template <typename T>
void write(const T& val, LoggerLevel level = LoggerLevel::Info) {
std::lock_guard<std::mutex> guard(mMutex);
mSstream.str("");
mSstream << val;
mQueue.push_back(std::make_tuple(
mSstream.str(), boost::posix_time::second_clock::local_time(), level));
}
static void debug(const boost::format& format) {
debug(format.str());
}
template <typename T>
static void debug(const T& val) {
static_cast<void>(val);
#ifdef REDI_DEBUG
get().write(val, LoggerLevel::Debug);
#endif
}
template <typename T>
static void debugSync(const T& val) {
static_cast<void>(val);
#ifdef REDI_DEBUG
std::cout << "DEBUGSYNC: " << val << '\n';
#endif
}
static void info(const char* ptr) { get().write(ptr, LoggerLevel::Info); }
template <typename T>
static void info(const T& val) {
get().write(val, LoggerLevel::Info);
}
template <typename T>
static void warn(const T& val) {
get().write(val, LoggerLevel::Warn);
}
template <typename T>
static void error(const T& val) {
get().write(val, LoggerLevel::Error);
}
template <typename T>
static void fatal(const T& val) {
get().write(val, LoggerLevel::Fatal);
}
private:
using Container = std::deque<
std::tuple<std::string, boost::posix_time::ptime, LoggerLevel>>;
Container mQueue;
std::thread mThread;
std::ofstream mFile;
std::mutex mMutex;
std::ostringstream mSstream;
bool mStop;
void workingThread();
void run(Container& cont, std::string& result);
static Logger& get();
};
} // namespace redi<file_sep>/src/nbt/tag.cpp
#include "tag.hpp"
#include "prettyprinter.hpp"
namespace redi::nbt {
tag::~tag() = default;
bool tag::is_number() const {
switch (get_type()) {
case tag_type::type_byte:
case tag_type::type_short:
case tag_type::type_int:
case tag_type::type_long:
case tag_type::type_float:
case tag_type::type_double:
return true;
default:
return false;
}
}
bool tag::is_scalar() const { return is_number() || get_type() == tag_type::type_string; }
bool tag::is_vector() const {
switch (get_type()) {
case tag_type::type_byte_array:
case tag_type::type_int_array:
case tag_type::type_long_array:
return true;
default:
return false;
}
}
bool tag::is_container() const {
switch (get_type()) {
case tag_type::type_compound:
case tag_type::type_list:
return true;
default:
return false;
}
}
std::ostream& operator<<(std::ostream& stream, const tag& tag) {
pretty_printer p;
tag.visit(p);
stream << p.string;
return stream;
}
} // namespace redi::nbt<file_sep>/src/protocol/packets/server/loginpackets.cpp
#include "loginpackets.hpp"
#include "../packethandler.hpp"
#include "../../packetwriter.hpp"
namespace redi::packets {
LoginStart::LoginStart(PacketReader& packet) { read(packet); }
LoginStart::LoginStart(const std::string& username) : username(username) {}
LoginStart::LoginStart(std::string&& username)
: username(std::move(username)) {}
void LoginStart::read(PacketReader& packet) { username = packet.readString(); }
void LoginStart::process(PacketHandler& handler) {
handler.handleLoginStart(*this);
}
LoginSucces::LoginSucces(const std::string& uuid, const std::string& username)
: uuid(uuid), username(username) {}
LoginSucces::LoginSucces(std::string&& uuid, std::string&& username)
: uuid(std::move(uuid)), username(std::move(username)) {}
void LoginSucces::write(ByteBuffer& buffer) {
PacketWriter packet(buffer, SendID);
packet.writeString(uuid);
packet.writeString(username);
}
SetCompression::SetCompression(std::int32_t threshold) : threshold(threshold) {}
void SetCompression::write(ByteBuffer& buffer) {
PacketWriter packet(buffer, SendID);
packet.writeVarInt(threshold);
}
}<file_sep>/src/chat/chatcomponent.cpp
#include "chatcomponent.hpp"
namespace redi {
namespace chat {
ChatComponent::ChatComponent(std::string&& str)
: string(std::move(str)) {}
ChatComponent::ChatComponent(const std::string& str)
: string(str) {}
std::string ChatComponent::generate() const {
using namespace std::string_literals;
return "{\"text\":\""s + get() + "\"}";
}
ChatComponent& operator+=(ChatComponent& l, const std::string& r) {
l.get().append(r.data(), r.size());
return l;
}
ChatComponent operator+(ChatComponent l, const std::string& r) {
l += r;
return l;
}
}
} // namespace redi<file_sep>/src/player.hpp
#pragma once
#include <list>
#include <boost/asio/steady_timer.hpp>
#include <boost/lexical_cast.hpp>
#include <boost/uuid/uuid.hpp>
#include <boost/uuid/uuid_io.hpp>
#include <set>
#include "session.hpp"
#include "serverconfig.hpp"
#include "playerposition.hpp"
#include "world/memoryregion.hpp"
#include "commands/commandsender.hpp"
namespace redi {
class Player;
class World;
using PlayerSharedPtr = std::shared_ptr<Player>;
class Player : public HasServer, public commands::CommandSender, public std::enable_shared_from_this<Player> {
public:
Player(const std::string& name, boost::uuids::uuid uuid,
std::shared_ptr<Session> session, std::int32_t id, Server& server,
World* world, Gamemode gamemode = Gamemode::Creative);
Player(const Player&) = delete;
Player(Player&&) = delete;
~Player();
Player& operator=(const Player&) = delete;
Player& operator=(Player&&) = delete;
Session& getSession() { return *session; }
const Session& getSession() const { return *session; }
Gamemode getGamemode() const { return gamemode; }
Dimension getDimension() const { return mPosition.dimension; }
PlayerPosition getPosition() const { return mPosition; }
World& getWorld() { return *mWorld; }
const World& getWorld() const { return *mWorld; }
const std::string& getUsername() const { return mNickname; }
boost::uuids::uuid getUUID() const { return mUUID; }
std::string getUUIDasString() const {
return boost::lexical_cast<std::string>(mUUID);
}
std::int32_t getEntityID() const { return mEntityID; }
std::int32_t getNewTeleportID() { return mTeleportID++; }
void sendPacket(const ByteBuffer& packet);
void sendPacket(ByteBuffer&& packet);
void sendMessage(const std::string& message,
ChatPosition position = ChatPosition::ChatBox);
void kick(const std::string& message);
void kick(std::string&& message);
void kick();
void disconnect();
bool isDisconnecting() const { return session->isDisconnecting(); }
void onTick();
void onEntityMovedWithLook(PlayerPosition newpos);
void normalizeRotation();
void onPositionChanged();
void onChunkLoaded(world::ChunkHolder& chunk);
void onUpdateChunks();
Player& getPlayer() override { return *this; }
Server& getSenderServer() override { return getServer(); }
const std::string& getSenderName() const override { return getUsername(); }
void sendMessageToSender(const std::string& message) override;
private:
friend class EventManager;
friend class PacketHandler;
friend class Session;
static constexpr double InRange = 16 * 10.0;
std::vector<Player*> mEntitiesInSight;
Vector2i mLastPositionWhenChunksWasSent;
std::list<world::ChunkHolder> loadedChunks;
boost::uuids::uuid mUUID;
std::string mNickname;
World* mWorld;
SessionSharedPtr session;
Gamemode gamemode;
PlayerPosition mPosition;
boost::asio::steady_timer mSendKeepAliveTimer;
std::int32_t mTeleportID;
const std::int32_t mEntityID;
std::atomic_bool hasSavedToDisk;
std::string getPlayerDataFileName() const;
void saveToFile();
void loadFromFile();
void onSendKeepAliveTimer(const boost::system::error_code& error);
void keepAliveNext();
void timersNext();
};
bool operator==(const Player& l, const Player& r);
bool operator!=(const Player& l, const Player& r);
} // namespace redi<file_sep>/src/world/anvil.hpp
#pragma once
#include <fstream>
#include <array>
#include <vector>
#include <boost/filesystem.hpp>
#include "../vectorn.hpp"
#include "../sizeliteraloperators.hpp"
#include "../bytebuffer.hpp"
namespace redi {
namespace world {
class Anvil {
public:
struct ChunkInfo {
std::uint32_t offset, time;
std::uint8_t sectors;
ChunkInfo(std::uint32_t offset = 0, std::uint32_t time = 0,
std::uint8_t sectors = 0)
: offset(offset), time(time), sectors(sectors) {}
};
enum class ChunkReadResult { OK, DoesntExists, Error };
static constexpr std::size_t HeaderSize = 8_KB;
static constexpr std::size_t SectorSize =
4_KB; // uhh, sectors. Earth is on Sector 2814
static constexpr std::int32_t ChunksPerRegion = 1 << 10;
Anvil();
Anvil(const std::string& path, const Vector2i& pos, bool create = true);
Anvil(const boost::filesystem::path& path, const Vector2i& pos,
bool create = true);
~Anvil();
void open(const boost::filesystem::path& path, const Vector2i& pos,
bool create = true);
void close();
void flush();
ChunkInfo getChunkInfo(std::int32_t number) const;
ChunkInfo getChunkInfo(const Vector2i& chunk) const;
ChunkReadResult readChunk(const Vector2i& number, ByteBuffer& buffer);
void writeChunk(const Vector2i& number, const ByteBuffer& uncompresseddata);
static std::int32_t getChunkNumberInRegion(const Vector2i& other);
static Vector2i getRegionCoordsFromChunkCoords(const Vector2i& chcoords);
static size_t getSectorsNumber(std::size_t size);
private:
std::fstream file;
std::array<std::uint8_t, HeaderSize> header;
std::vector<bool> freeSectors;
Vector2i position;
bool hasRegion;
void clear();
void createNewRegionAndOpen(const std::string& filepath);
void openFile(const std::string& path);
void createNewRegionIfOK(const boost::filesystem::path& filepath,
bool create);
void readHeader();
void processHeader();
void writeChunkInfo(std::int32_t number, const ChunkInfo& info);
void writeChunkInfo(const Vector2i& number, const ChunkInfo& chunk);
ChunkReadResult readChunk(std::int32_t number, ByteBuffer& buffer);
void writeChunk(std::int32_t number, const ByteBuffer& uncompresseddata);
};
} // namespace world
} // namespace redi<file_sep>/src/session.cpp
#include <boost/asio.hpp>
#include <boost/bind.hpp>
#include <boost/format.hpp>
#include <boost/filesystem.hpp>
#include "session.hpp"
#include "logger.hpp"
#include "protocol/packetreader.hpp"
#include "server.hpp"
#include "protocol/packetwriter.hpp"
#include "protocol/varint.hpp"
namespace asio = boost::asio;
namespace redi {
Session::Session(SocketSharedPtr socket, Server& server)
: HasServer(server), socket(socket),
player(nullptr),
connectionState(ConnectionState::Handshake),
setCompressionIsSentVar(false),
packetHandler(std::make_shared<PacketHandler>(
server, *this, server.getEventManager())),
isDisconnected(false), isWritting(false) {
Logger::debug((boost::format("Session %1% created") % this).str());
socket->set_read_handler([this] (auto bytes, auto error) { this->on_read(bytes, error); });
socket->read(MutableBuffer(reading_buffer, sizeof(reading_buffer)));
}
Session::~Session() {
Logger::debug((boost::format("Session %1% destroyed") % this).str());
}
void Session::on_read(size_t bytes, std::string error) {
if (!error.empty()) {
disconnect();
return;
}
reading_buffer_vector.append(reading_buffer, bytes);
deserialize_packets();
socket->read(MutableBuffer(reading_buffer, sizeof(reading_buffer)));
}
void Session::disconnect() {
bool disconnected = isDisconnected.exchange(true);
if (disconnected) {
return;
}
socket->close();
if (player) {
player->disconnect();
server.addEvent(std::make_unique<EventPlayerDisconnect>(*player));
}
server.addEvent(std::make_unique<EventSessionDisconnect>(*this));
}
void Session::kick(const std::string& message) {
packets::Disconnect(message,
connectionState == ConnectionState::Play)
.send(*this);
disconnect();
}
void Session::setPlayer(Player& player) { this->player = std::addressof(player); }
void Session::sendPacket(ByteBuffer packet, const std::string& message) {
static_cast<void>(message);
auto result = protocol::varint::encodeVarInt(packet.size());
std::array<ConstBuffer, 2> buffers;
buffers[0] = { result.first.data(), result.second };
buffers[1] = packet;
socket->write(buffers.data(), buffers.size());
}
void Session::deserialize_packets() {
while (protocol::varint::is_complete(ConstBuffer(reading_buffer_vector))) {
PacketReader reader((ConstBuffer(reading_buffer_vector)));
auto size = static_cast<size_t>(reader.readVarInt());
auto varint_size = protocol::varint::varint_size(size);
if (size + varint_size > reading_buffer_vector.size()) {
return;
}
ConstBuffer buffer(reading_buffer_vector.data() + varint_size, size);
packetHandler->readRaw(buffer);
server.addTask([handler = this->packetHandler] {
handler->handleOne();
} );
reading_buffer_vector.erase(reading_buffer_vector.begin(),
reading_buffer_vector.begin() + varint_size + size);
}
}
} // namespace redi<file_sep>/src/commands/command.cpp
#include "command.hpp"
#include "../server.hpp"
#include "../player.hpp"
namespace redi {
namespace commands {
Command::Command(Server & server)
: HasServer(server), manager(server.getCommandManager()) {}
Command& Command::operator()(CommandSender&, const std::string&,
CommandArguments&) {
return *this;
}
Command::~Command() {
manager.unregisterAll(this);
}
Player* Command::getPlayerOrDefault(CommandSender& sender, const CommandArguments& args) const {
Player * player{};
if (args.size() == 0) {
player = sender.getPlayerPtr();
}
else {
player = sender.getSenderServer().findPlayer(args[0]);
}
return player;
}
Player* Command::getPlayerOrDefaultAndSendMessageIfNot(CommandSender& sender, const CommandArguments& args) const {
Player * player = getPlayerOrDefault(sender, args);
if (!player) {
sender.sendMessageToSender("Can't find the player");
}
return player;
}
}
} // namespace redi<file_sep>/src/bytebuffer.cpp
#include <cstring>
#include "bytebuffer.hpp"
namespace redi {
ByteBuffer::ByteBuffer(const char* ptr) {
// I didn't want <cstring> in header ..
append(ptr, std::strlen(ptr));
}
ByteBuffer& operator+=(ByteBuffer& l, const ByteBuffer& r) {
l.append(r.data(), r.size());
return l;
}
ByteBuffer operator+(ByteBuffer l, const ByteBuffer& r) {
l += r;
return l;
}
} // namespace redi<file_sep>/src/messages/tick.hpp
#pragma once
#include "event.hpp"
namespace redi {
namespace events {
struct EventTick : public Event {
EventTick() = default;
};
} // namespace messages
} // namespace redi<file_sep>/src/messages/statusrequest.hpp
#pragma once
#include "event.hpp"
#include "../session.hpp"
namespace redi {
struct EventStatusRequest : public Event {
Session& session;
EventStatusRequest(Session& session)
: Event(EventType::StatusRequest), session(session) {}
};
} // namespace redi<file_sep>/src/protocol/packets/packet.hpp
#pragma once
#include <list>
#include <memory>
#include "../../bytebuffer.hpp"
#include "../packetreader.hpp"
#include "../../util/util.hpp"
namespace redi {
class PacketHandler;
class Player;
class Session;
using SessionSharedPtr = std::shared_ptr<Session>;
using PlayerSharedPtr = std::shared_ptr<Player>;
struct Packet {
Packet() = default;
virtual ~Packet() = 0;
virtual void read(PacketReader&) {}
virtual void write(ByteBuffer&) {}
virtual void process(PacketHandler&) {}
std::string getName() const {
return util::demangleTypeName(*this);
}
void send(Session& session);
void send(SessionSharedPtr& session);
void send(Player& player);
void send(std::list<PlayerSharedPtr>& list);
};
using PacketUniquePtr = std::unique_ptr<Packet>;
} // namespace redi<file_sep>/src/messages/eventmanager.hpp
#pragma once
#include <map>
#include "eventtype.hpp"
#include "event.hpp"
#include "../threadsafequeue.hpp"
#include "eventpriority.hpp"
#include "events.hpp"
namespace redi {
class EventManager {
public:
EventManager(Server& server);
void operator()();
void addEvent(EventUniquePtr&& ptr);
void handlePlayerJoin(EventPlayerJoin& event);
void handlePlayerDisconnect(EventPlayerDisconnect& event);
void handleSessionDisconnect(EventSessionDisconnect& event);
void handleChatMessage(EventChatMessage& event);
void handleChunkLoaded(events::EventChunkLoaded& event);
private:
ThreadSafeQueue<EventUniquePtr> mEvents;
Server& mServer;
};
} // namespace redi | 947ff7b1800df3a87827757d474673e435979b26 | [
"Markdown",
"CMake",
"C++",
"Shell"
] | 149 | C++ | xTachyon/RedstoneInside | 6fabed21c0ed92c4bc605ab4a968f6e8d9f7275d | 852e3888a988693fbdb5f6b4561b088035c6acab |
refs/heads/master | <repo_name>n1scby/dynamicUI<file_sep>/js/books.js
"use strict";
(function(){
var title = document.getElementById("title");
var lastName = document.getElementById("lastName");
var firstName = document.getElementById("firstName");
var bookButton = document.getElementById("bookButton");
var sortButton = document.getElementById("sortButton");
var output = document.getElementById("output");
var books = [];
var Book = function Book(title, firstName, lastName) {
this.title = title;
this.firstName = firstName;
this.lastName = lastName;
}
var displayBooks = function displayBooks(){
output.innerHTML="";
var newUL = document.createElement("ul");
var newDiv = document.createElement("div");
books.forEach(function(book, idx, arr){
// var newH2 = document.createElement("h2");
// var newP = document.createElement("p");
var newLi = document.createElement("li");
newLi.innerText = "Title: " + book.title + " Author: " + book.firstName + " " + book.lastName;
newUL.appendChild(newLi);
newDiv.appendChild(newUL);
// newH2.innerText = "Title: " + book.title;
// newP.innerText = "Author: " + book.firstName + " " + book.lastName;
// newDiv.appendChild(newH2);
// newDiv.appendChild(newP);
output.appendChild(newDiv);
});
}
sortButton.addEventListener("click", function(){
books = books.sort(function(a, b){
var nameA = a.lastName.toUpperCase();
var nameB = b.lastName.toUpperCase();
if(nameA < nameB) {
return -1;
} else
{
if(nameA > nameB){
return 1;
} else {
return 0;
}
}
});
displayBooks();
});
bookButton.addEventListener("click", function(){
// output.innerHTML= "";
var newBook = new Book(title.value, firstName.value, lastName.value);
books.push(newBook);
displayBooks();
});
})();<file_sep>/README.md
# dynamicUI
dynamic UI with JS
| 4f9bc8aa31cf9d298ade5523dd2d704b7f98fe4d | [
"JavaScript",
"Markdown"
] | 2 | JavaScript | n1scby/dynamicUI | 8629013aec31348cb641fc446fa93c5439463dd7 | ed5d108974975f0e1b9622b9af6019aca21d62d5 |
refs/heads/master | <repo_name>mcofko/game_breakout-rxjs-ts<file_sep>/src/canvas.ts
import { } from './types';
export const COLS = 30;
export const ROWS = 30;
export const GAP_SIZE = 1;
export const CELL_SIZE = 10;
export const CANVAS_WIDTH = COLS * (CELL_SIZE + GAP_SIZE);
export const CANVAS_HEIGHT = ROWS * (CELL_SIZE + GAP_SIZE);
// *******************************************************
export const renderGame = () => {};
export const renderGameOverLite = () => (document.body.innerHTML += '<br/>GAME OVER!');
export const noop = () => {};
// *******************************************************
export function createCanvasElement() {
const canvas = document.createElement('canvas');
canvas.width = CANVAS_WIDTH;
canvas.height = CANVAS_HEIGHT;
return canvas;
} | 67d1f248fbd5d01be7f53cc6a435b07ccc117df2 | [
"TypeScript"
] | 1 | TypeScript | mcofko/game_breakout-rxjs-ts | b4d9a519fded7321497fe1875e89c117d0493d94 | 4c37e68759c27a595d02f5bbcd2e1e31fa198867 |
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 FTP;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.BindException;
import java.net.ConnectException;
import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.NoRouteToHostException;
import java.net.PortUnreachableException;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javafx.scene.control.ProgressBar;
import javax.swing.JOptionPane;
import javax.swing.ProgressMonitorInputStream;
/**
*
* @author admin
*/
public class FTP extends javax.swing.JFrame {
/**
* Creates new form FTP
*/
public FTP() {
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() {
SendFrame = new javax.swing.JFrame();
Browse = new javax.swing.JButton();
Server = new javax.swing.JButton();
jLabel13 = new javax.swing.JLabel();
jLabel1 = new javax.swing.JLabel();
jProgressBar1 = new javax.swing.JProgressBar();
HomeButton = new javax.swing.JButton();
jLabel6 = new javax.swing.JLabel();
jLabel11 = new javax.swing.JLabel();
jButton1 = new javax.swing.JButton();
jSeparator2 = new javax.swing.JSeparator();
jLabel10 = new javax.swing.JLabel();
ReceiveFrame = new javax.swing.JFrame();
Client = new javax.swing.JButton();
ipAddress = new javax.swing.JTextField();
jLabel2 = new javax.swing.JLabel();
jButton2 = new javax.swing.JButton();
jLabel8 = new javax.swing.JLabel();
Browse1 = new javax.swing.JButton();
jLabel3 = new javax.swing.JLabel();
jLabel7 = new javax.swing.JLabel();
jSeparator1 = new javax.swing.JSeparator();
jLabel9 = new javax.swing.JLabel();
BrowseFrame = new javax.swing.JFrame();
jFileChooser1 = new javax.swing.JFileChooser();
RSaveFrame = new javax.swing.JFrame();
jFileChooser2 = new javax.swing.JFileChooser();
jTextField1 = new javax.swing.JTextField();
jSeparator3 = new javax.swing.JSeparator();
jButton3 = new javax.swing.JButton();
Send = new javax.swing.JButton();
Receive = new javax.swing.JButton();
jLabel5 = new javax.swing.JLabel();
jLabel4 = new javax.swing.JLabel();
SendFrame.setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
SendFrame.setMinimumSize(new java.awt.Dimension(400, 400));
SendFrame.setSize(new java.awt.Dimension(400, 400));
SendFrame.getContentPane().setLayout(null);
Browse.setText("Browse");
Browse.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
BrowseActionPerformed(evt);
}
});
SendFrame.getContentPane().add(Browse);
Browse.setBounds(150, 170, 80, 23);
Server.setText("SEND");
Server.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
ServerActionPerformed(evt);
}
});
SendFrame.getContentPane().add(Server);
Server.setBounds(140, 270, 100, 50);
jLabel13.setOpaque(true);
SendFrame.getContentPane().add(jLabel13);
jLabel13.setBounds(140, 230, 110, 23);
jLabel1.setOpaque(true);
SendFrame.getContentPane().add(jLabel1);
jLabel1.setBounds(70, 130, 260, 23);
SendFrame.getContentPane().add(jProgressBar1);
jProgressBar1.setBounds(120, 330, 146, 14);
HomeButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/FTP/Home(38 X 35).png"))); // NOI18N
HomeButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
HomeButtonActionPerformed(evt);
}
});
SendFrame.getContentPane().add(HomeButton);
HomeButton.setBounds(0, 0, 40, 35);
jLabel6.setFont(new java.awt.Font("Consolas", 0, 36)); // NOI18N
jLabel6.setForeground(new java.awt.Color(240, 240, 240));
jLabel6.setText("EZ-Transfer");
SendFrame.getContentPane().add(jLabel6);
jLabel6.setBounds(80, 50, 270, 50);
jLabel11.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT);
jLabel11.setText("Progress:");
SendFrame.getContentPane().add(jLabel11);
jLabel11.setBounds(20, 330, 100, 14);
jButton1.setText("Fetch-IP");
jButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton1ActionPerformed(evt);
}
});
SendFrame.getContentPane().add(jButton1);
jButton1.setBounds(60, 230, 73, 23);
SendFrame.getContentPane().add(jSeparator2);
jSeparator2.setBounds(0, 90, 400, 310);
jLabel10.setIcon(new javax.swing.ImageIcon(getClass().getResource("/FTP/GUIpaperresized.jpg"))); // NOI18N
SendFrame.getContentPane().add(jLabel10);
jLabel10.setBounds(0, 0, 400, 400);
ReceiveFrame.setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
ReceiveFrame.setMinimumSize(new java.awt.Dimension(400, 400));
ReceiveFrame.setSize(new java.awt.Dimension(400, 400));
ReceiveFrame.getContentPane().setLayout(null);
Client.setText("RECEIVE");
Client.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
ClientActionPerformed(evt);
}
});
ReceiveFrame.getContentPane().add(Client);
Client.setBounds(130, 270, 100, 40);
ipAddress.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
ipAddressActionPerformed(evt);
}
});
ReceiveFrame.getContentPane().add(ipAddress);
ipAddress.setBounds(120, 210, 129, 30);
jLabel2.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT);
jLabel2.setText("Location: ");
ReceiveFrame.getContentPane().add(jLabel2);
jLabel2.setBounds(0, 120, 80, 20);
jButton2.setIcon(new javax.swing.ImageIcon(getClass().getResource("/FTP/Home(38 X 35).png"))); // NOI18N
jButton2.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton2ActionPerformed(evt);
}
});
ReceiveFrame.getContentPane().add(jButton2);
jButton2.setBounds(0, 0, 40, 35);
jLabel8.setFont(new java.awt.Font("Consolas", 0, 36)); // NOI18N
jLabel8.setForeground(new java.awt.Color(240, 240, 240));
jLabel8.setText("EZ-Transfer");
ReceiveFrame.getContentPane().add(jLabel8);
jLabel8.setBounds(80, 50, 270, 50);
Browse1.setText("Browse");
Browse1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
Browse1ActionPerformed(evt);
}
});
ReceiveFrame.getContentPane().add(Browse1);
Browse1.setBounds(150, 160, 80, 23);
jLabel3.setOpaque(true);
ReceiveFrame.getContentPane().add(jLabel3);
jLabel3.setBounds(80, 120, 240, 23);
jLabel7.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT);
jLabel7.setText("IP Address:");
ReceiveFrame.getContentPane().add(jLabel7);
jLabel7.setBounds(30, 210, 90, 30);
jSeparator1.setForeground(new java.awt.Color(153, 153, 153));
ReceiveFrame.getContentPane().add(jSeparator1);
jSeparator1.setBounds(0, 90, 400, 300);
jLabel9.setIcon(new javax.swing.ImageIcon(getClass().getResource("/FTP/GUIpaperresized.jpg"))); // NOI18N
ReceiveFrame.getContentPane().add(jLabel9);
jLabel9.setBounds(0, 0, 400, 400);
BrowseFrame.setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
BrowseFrame.setMinimumSize(new java.awt.Dimension(500, 500));
BrowseFrame.setSize(new java.awt.Dimension(500, 500));
BrowseFrame.getContentPane().setLayout(new javax.swing.OverlayLayout(BrowseFrame.getContentPane()));
jFileChooser1.setCurrentDirectory(new java.io.File("C:\\Users\\admin\\Desktop"));
jFileChooser1.setMinimumSize(new java.awt.Dimension(650, 450));
jFileChooser1.setPreferredSize(new java.awt.Dimension(650, 450));
jFileChooser1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jFileChooser1ActionPerformed(evt);
}
});
BrowseFrame.getContentPane().add(jFileChooser1);
RSaveFrame.setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
RSaveFrame.setMinimumSize(new java.awt.Dimension(500, 500));
RSaveFrame.setPreferredSize(new java.awt.Dimension(500, 500));
RSaveFrame.setSize(new java.awt.Dimension(500, 500));
RSaveFrame.getContentPane().setLayout(new javax.swing.OverlayLayout(RSaveFrame.getContentPane()));
jFileChooser2.setDialogType(javax.swing.JFileChooser.SAVE_DIALOG);
jFileChooser2.setCurrentDirectory(new java.io.File("C:\\Users\\admin\\Desktop"));
jFileChooser2.setFileSelectionMode(javax.swing.JFileChooser.DIRECTORIES_ONLY);
jFileChooser2.setMinimumSize(new java.awt.Dimension(650, 450));
jFileChooser2.setPreferredSize(new java.awt.Dimension(650, 450));
jFileChooser2.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jFileChooser2ActionPerformed(evt);
}
});
RSaveFrame.getContentPane().add(jFileChooser2);
RSaveFrame.getAccessibleContext().setAccessibleDescription("");
jTextField1.setText("jTextField1");
jButton3.setText("jButton3");
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
setMinimumSize(new java.awt.Dimension(400, 400));
setResizable(false);
getContentPane().setLayout(null);
Send.setText("Send");
Send.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
SendActionPerformed(evt);
}
});
getContentPane().add(Send);
Send.setBounds(80, 190, 90, 23);
Receive.setText("Receive");
Receive.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
ReceiveActionPerformed(evt);
}
});
getContentPane().add(Receive);
Receive.setBounds(80, 240, 90, 23);
jLabel5.setFont(new java.awt.Font("Consolas", 0, 36)); // NOI18N
jLabel5.setForeground(new java.awt.Color(240, 240, 240));
jLabel5.setText("EZ-Transfer");
getContentPane().add(jLabel5);
jLabel5.setBounds(80, 50, 270, 50);
jLabel4.setIcon(new javax.swing.ImageIcon(getClass().getResource("/FTP/GUIpaperresized.jpg"))); // NOI18N
getContentPane().add(jLabel4);
jLabel4.setBounds(0, 0, 400, 400);
pack();
}// </editor-fold>//GEN-END:initComponents
private void SendActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_SendActionPerformed
// TODO add your handling code here:
this.dispose();
SendFrame.setVisible(true);
SendFrame.setLocationRelativeTo(null);
}//GEN-LAST:event_SendActionPerformed
private void ReceiveActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_ReceiveActionPerformed
// TODO add your handling code here:
this.dispose();
ReceiveFrame.setVisible(true);
ReceiveFrame.setLocationRelativeTo(null);
}//GEN-LAST:event_ReceiveActionPerformed
String filename,path;
private void BrowseActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_BrowseActionPerformed
// TODO add your handling code here:
BrowseFrame.setVisible(true);
BrowseFrame.setLocationRelativeTo(null);
// jLabel1.setText(jFileChooser1.getName());
}//GEN-LAST:event_BrowseActionPerformed
private void jFileChooser1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jFileChooser1ActionPerformed
// TODO add your handling code here:
path=jFileChooser1.getSelectedFile().getAbsolutePath();
filename=jFileChooser1.getSelectedFile().getName();
jLabel1.setText(path);
BrowseFrame.setVisible(false);
}//GEN-LAST:event_jFileChooser1ActionPerformed
int port;
private void ServerActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_ServerActionPerformed
// TODO add your handling code here:
try{
port=6221;
ServerSocket serverSocket = new ServerSocket(port);
Socket socket = serverSocket.accept();
System.out.println("Accepted connection : " + socket);
File transferFile = new File (path);
byte [] bytearray = new byte [(int)transferFile.length()];
FileInputStream fin = new FileInputStream(transferFile);
DataOutputStream dos=new DataOutputStream(socket.getOutputStream());
dos.writeUTF(filename);
dos.flush();
// ByteArrayOutputStream out=new ByteArrayOutputStream((int)transferFile.length());
OutputStream os = socket.getOutputStream();
jLabel11.setText("Sending files...");
System.out.println("Sending Files...");
int bytesRead = -1;
long totalBytesRead = 0;
int percentCompleted = 0;
long fileSize = transferFile.length();
//fin.read(bytearray);
while ((bytesRead = fin.read(bytearray)) != -1)
{
os.write(bytearray, 0 , bytesRead);
totalBytesRead += bytesRead;
System.out.println(fileSize +" "+totalBytesRead);
percentCompleted = (int)( totalBytesRead * 100 / fileSize);
jProgressBar1.setValue(percentCompleted);
}
//os.write(bytearray,0,bytearray.length);
os.flush();
socket.close();
jLabel11.setText("Files Transfered...");
JOptionPane.showMessageDialog(rootPane, "File Transfered......");
SendFrame.setVisible(false);
this.setVisible(true);
System.out.println(fileSize +" "+totalBytesRead+"File transfer complete");
}
catch(BindException e )
{
JOptionPane.showMessageDialog(rootPane, "This "+port+" Port no. is already in use........");
}
catch(SocketException e )
{
JOptionPane.showMessageDialog(rootPane, e+"........");
}
catch(Exception e)
{
}
//System.out.println("File transfer complete");
}//GEN-LAST:event_ServerActionPerformed
String rfilename="",rpath="";
private void ClientActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_ClientActionPerformed
// TODO add your handling code here:
try{
int filesize=414748364; //21474836
int bytesRead;
int currentTot = 0;
Socket socket = new Socket(ipAddress.getText(),6221);
byte [] bytearray = new byte [filesize];
InputStream is = socket.getInputStream();
DataInputStream dis = new DataInputStream(is);
rfilename=dis.readUTF();
rpath=((jFileChooser2.getSelectedFile().getAbsolutePath()).concat("\\")).concat(rfilename);
FileOutputStream fos = new FileOutputStream(rpath);
BufferedOutputStream bos = new BufferedOutputStream(fos);
bytesRead = is.read(bytearray,0,bytearray.length);
currentTot = bytesRead;
do {
bytesRead = is.read(bytearray, currentTot, (bytearray.length-currentTot));
if(bytesRead >= 0) currentTot += bytesRead; }
while(bytesRead > -1);
bos.write(bytearray, 0 , currentTot);
bos.flush();
bos.close();
JOptionPane.showMessageDialog(rootPane, "File Recieved......");
ReceiveFrame.setVisible(false);
this.setVisible(true);
this.setLocationRelativeTo(null);
System.out.println("Received!!");
socket.close();
}
catch(PortUnreachableException e )
{
System.err.println(e);
JOptionPane.showMessageDialog(rootPane, "Port No. is already in use......");
}
catch(SocketException e )
{
JOptionPane.showMessageDialog(rootPane, "No Sender Found......");
}
catch(Exception e)
{
System.out.println(e);
}
}//GEN-LAST:event_ClientActionPerformed
private void ipAddressActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_ipAddressActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_ipAddressActionPerformed
private void HomeButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_HomeButtonActionPerformed
// TODO add your handling code here:
SendFrame.setVisible(false);
this.setVisible(true);
this.setLocationRelativeTo(null);
}//GEN-LAST:event_HomeButtonActionPerformed
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
// TODO add your handling code here:
ReceiveFrame.setVisible(false);
this.setVisible(true);
this.setLocationRelativeTo(null);
}//GEN-LAST:event_jButton2ActionPerformed
private void jFileChooser2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jFileChooser2ActionPerformed
// TODO add your handling code here:
RSaveFrame.setVisible(false);
jLabel3.setText(jFileChooser2.getSelectedFile().getAbsolutePath());
}//GEN-LAST:event_jFileChooser2ActionPerformed
private void Browse1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_Browse1ActionPerformed
// TODO add your handling code here:
RSaveFrame.setVisible(true);
RSaveFrame.setLocationRelativeTo(null);
}//GEN-LAST:event_Browse1ActionPerformed
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
// TODO add your handling code here:
//InetAddress ia=new InetAddress();
// InetAddress ipp=new Inet4Address();
Socket s=null;
try {
s = new Socket("localhost",6221);
} catch (IOException ex) {
Logger.getLogger(FTP.class.getName()).log(Level.SEVERE, null, ex);
}
// String ip=toString(s.getInetAddress());
InetAddress ipp=null;
try {
jLabel13.setText(ipp.getLocalHost().getHostAddress());
} catch (UnknownHostException ex) {
Logger.getLogger(FTP.class.getName()).log(Level.SEVERE, null, ex);
}
// jLabel12.setText(ipp.toString());
//System.out.print(ipp.getHostAddress());
//String sd="www.google.com";
//InetAddress i=(InetAddress)(Object)sd;
//System.out.print(i.getHostAddress());
}//GEN-LAST:event_jButton1ActionPerformed
/**
* @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(FTP.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(FTP.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(FTP.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(FTP.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
FTP f=new FTP();
f.setVisible(true);
f.setLocationRelativeTo(null);
}
});
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton Browse;
private javax.swing.JButton Browse1;
private javax.swing.JFrame BrowseFrame;
private javax.swing.JButton Client;
private javax.swing.JButton HomeButton;
private javax.swing.JFrame RSaveFrame;
private javax.swing.JButton Receive;
private javax.swing.JFrame ReceiveFrame;
private javax.swing.JButton Send;
private javax.swing.JFrame SendFrame;
private javax.swing.JButton Server;
private javax.swing.JTextField ipAddress;
private javax.swing.JButton jButton1;
private javax.swing.JButton jButton2;
private javax.swing.JButton jButton3;
private javax.swing.JFileChooser jFileChooser1;
private javax.swing.JFileChooser jFileChooser2;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel10;
private javax.swing.JLabel jLabel11;
private javax.swing.JLabel jLabel13;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JLabel jLabel4;
private javax.swing.JLabel jLabel5;
private javax.swing.JLabel jLabel6;
private javax.swing.JLabel jLabel7;
private javax.swing.JLabel jLabel8;
private javax.swing.JLabel jLabel9;
private javax.swing.JProgressBar jProgressBar1;
private javax.swing.JSeparator jSeparator1;
private javax.swing.JSeparator jSeparator2;
private javax.swing.JSeparator jSeparator3;
private javax.swing.JTextField jTextField1;
// End of variables declaration//GEN-END:variables
private String toString(InetAddress inetAddress) {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
}
| 8dc3fffe78c564b9587af2a70b86f67d4e6d5124 | [
"Java"
] | 1 | Java | jainkrunal/FileTransferApplication | 9ef6759044722dc030ca986902203a0d5409b7d5 | 8d05572c90ca26c9a49fa539c07aecb7fac1be0c |
refs/heads/master | <repo_name>luiselizondo/nginx-php<file_sep>/startup.sh
#!/bin/bash
ENV_CONF=/etc/php5/fpm/pool.d/env.conf
echo "Configuring Nginx and PHP5-FPM with environment variables"
# Update php5-fpm with access to Docker environment variables
echo '[www]' > $ENV_CONF
for var in $(env | awk -F= '{print $1}')
do
echo "Adding variable {$var}"
echo "env[${var}] = ${!var}" >> $ENV_CONF
done<file_sep>/README.md
# nginx-php5
Includes nginx and php5 running with supervisor
## To build
```
$ sudo docker build -t yourname/nginx-php .
```
## To run
Nginx will look for files in /var/www so you need to map your application to that directory.
```
sudo docker run -d -p 8000:80 --volumes-from APPDATA -v /home/me/myphpapp:/var/www --name lemp yourname/nginx-php
```
The --volumes-from argument means that you're using a Data-only container pattern.
If you want to link the container to a MySQL/MariaDB contaier do:
```
sudo docker run -d -p 8000:80 --volumes-from APPDATA -v /home/me/myphpapp:/var/www --name lemp my_mysql_container:mysql yourname/nginx-php
```
The startup.sh script will add the environment variables with MYSQL_ to /etc/php5/fpm/pool.d/env.conf so PHP-FPM detects them. If you need to use them you can do:
<?php getenv("SOME_ENV_VARIABLE_THAT_HAS_MYSQL_IN_THE_NAME"); ?>
### Testing that it works
Go to http://ip:port/test and you should see the output of phpinfo()
### Credits
Credit to: <NAME>
Original work can be found at: https://github.com/nianwang/docker-index
### License
The original author didn't relase the code with a License. But this code is released under the MIT License. | 19831df5147fa379e2d4119f56192528cd55e434 | [
"Markdown",
"Shell"
] | 2 | Shell | luiselizondo/nginx-php | 41980dbc7ba23c08766930be18ede8e3a475df9f | 0df46429f2bed896805fed0628f7ed6b371ebdc9 |
refs/heads/master | <repo_name>aakarsh/rustymouse<file_sep>/src/vel_publisher.rs
#[macro_use]
extern crate rosrust;
extern crate env_logger;
use rosrust::Ros;
use std::{thread, time};
use std::io;
rosmsg_include!();
fn main() {
env_logger::init().unwrap();
let mut ros = Ros::new("vel_publisher").unwrap();
let mut publisher = ros.publish("cmd_vel").unwrap();
// Really want to use below, but errors out for the moment, so using a
// python script to map from "cmd_vel" to
// "raspimouse/diff_drive_controller/cmd_vel"
// let mut publisher = ros.publish("/raspimouse/diff_drive_controller/cmd_vel").unwrap();
println!("w: forward, s: backward, a: left, d: right >");
loop {
let mut vel_cmd = msg::geometry_msgs::Twist::new();
thread::sleep(time::Duration::from_secs(1));
let mut command = String::new();
io::stdin().read_line(&mut command);
match command.as_str() {
"w\n" => vel_cmd.linear.x = 0.35,
"s\n" => vel_cmd.linear.x = -0.35,
"a\n" => vel_cmd.angular.z = 3.21,
"d\n" => vel_cmd.angular.z = -3.21,
"q\n" => break,
_ => println!("Command not recognized"),
}
publisher.send(vel_cmd).unwrap();
}
}
<file_sep>/README.md
Teleop example written in Rust for the raspimouse developed by RT Corporation
---
This package was originally inspired by Takashi Ogura package found
[here](https://github.com/OTL/rosrust_tutorial)
First follow the instructions [here](https://github.com/rt-net/raspimouse_sim)
to get the packages that will enable to you simulate the raspimouse in Gazebo.
First clone the project:
```
$ git clone https://github.com/surfertas/rustymouse.git
```
Then build the project:
```
$ cargo build
```
We first need to launch the simulation in Gazebo. (Make sure not to forget
`source devel/setup.bash`) Go to `~/raspiouse_gazebo/launch`
```
$ roscore&
$ roslaunch raspimouse_with_samplemaze.launch
```
For the moment, ros.publish() doesnt accept the topic
`raspimouse/diff_drive_controller/cmd_vel` so we need to use a python script to
map between `cmd_vel` and the `raspimouse/diff_drive_controller/cmd_vel` topic.
Open a new window and go to `rustymouse/script` and run:
```
$ python topic_to_topic.py
```
Finally, run
```
$ cargo run --bin vel_publisher
```
You should be prompted to enter w,s,a,d. Use q to quit.
<file_sep>/Cargo.toml
[package]
name = "rustymouse"
version = "0.1.0"
authors = ["surfertas <<EMAIL>>"]
build = true
[dependencies]
rosrust = "0.5.0"
serde = "1.0.2"
serde_derive = "1.0.2"
env_logger = "0.4.2"
[[bin]]
name = "vel_publisher"
path = "src/vel_publisher.rs"
[build-dependencies]
rosrust = "0.5.0"
<file_sep>/script/topic_to_topic.py
#!/usr/bin/env python
# license removed for brevity
import rospy
from geometry_msgs.msg import Twist
def callback(msg):
pub = rospy.Publisher('/raspimouse/diff_drive_controller/cmd_vel', Twist, queue_size=10)
pub.publish(msg)
def topic_mapper():
rospy.init_node('mapper', anonymous=True)
rospy.Subscriber("/cmd_vel", Twist, callback)
rospy.spin()
if __name__ == '__main__':
topic_mapper()
<file_sep>/build.rs
#[macro_use]
extern crate rosrust;
rosmsg_main!("geometry_msgs/Twist");
| 10ba6309d00d608bef0710573e9610a7fff0a92d | [
"Markdown",
"Rust",
"Python",
"TOML"
] | 5 | Rust | aakarsh/rustymouse | d145d939221b221d98e8727f3a305ca11f658d27 | b82249c28c7d88b4deadcd47e678927d05a4e4f1 |
refs/heads/master | <file_sep>var express = require('express')
var path =require('path')
var port = process.env.PORT || 3000
var mongoose =require('mongoose')
var bodyParser=require('body-parser')
var serverStatic=require('serve-static')
var app =express()
mongoose.connect('mongodb://localhost/imooc')
app.set('views','./views/pages')
app.set('view engine','jade')
app.use(bodyParser.urlencoded({ extended: false }))
//path.join(_dirname,'bower_components')
app.use(serverStatic('bower_components'))
app.listen(port)
console.log('imooc started on port '+port)
//添加路由
//index page
app.get('/',function(req,res){
Movie.fetch(function(err,movies) {
if(err) {
console.log(err)
}
res.render('index',{
title:'imooc 首页'
movies: movies
})
})
res.render('index',{
title : 'imooc 首页',
movies: [{
title:'机械战警',
_id:1,
poster:'http://r3.ykimg.com/05160000530EEB63675839160D0B79D5'
},{
title:'机械战警',
_id:2,
poster:'http://r3.ykimg.com/05160000530EEB63675839160D0B79D5'
},{
title:'机械战警',
_id:3,
poster:'http://r3.ykimg.com/05160000530EEB63675839160D0B79D5'
},{
title:'机械战警',
_id:4,
poster:'http://r3.ykimg.com/05160000530EEB63675839160D0B79D5'
},{
title:'机械战警',
_id:5,
poster:'http://r3.ykimg.com/05160000530EEB63675839160D0B79D5'
},{
title:'机械战警',
_id:6,
poster:'http://r3.ykimg.com/05160000530EEB63675839160D0B79D5'
}]
})
})
app.get('/movie/:id',function(req,res){
res.render('detail',{
title : 'imooc 详情页',
movie: {
doctor:'<NAME>',
country:'中国',
title:'机械战警',
year:'2014',
poster:'http://r3.ykimg.com/05160000530EEB63675839160D0B79D5',
language:'英语',
flash:'http://player.youku.com/player.php/sid/XNjA1Njc0NTUy/v.swf',
summary:'demon song巨作'
}
})
})
app.get('/admin/movie',function(req,res){
res.render('admin',{
title : 'imooc 后台录入页',
movie : {
title:'',
doctor:'',
country:'',
year:'',
poster:'',
flash:'',
summary:'',
language:''
}
})
})
app.get('/admin/list',function(req,res){
res.render('list',{
title : 'imooc 列表页',
movies: [{
title:'机械战警',
_id:1,
doctor:'<NAME>',
country:'美国',
year:'2014',
poster:'http://r3.ykimg.com/05160000530EEB63675839160D0B79D5',
language:'英语',
flash:'http://v.youku.com/v_show/id_XMTY1NzIwMDMyOA==.html?beta&from=s1.8-1-1.2&spm=0.0.0.0.WcwK05',
summary:'demon song巨作'
}]
})
})
| 975f12ab0f27756c4d481ae10503eb1e82494ec3 | [
"JavaScript"
] | 1 | JavaScript | demonSong/node-study | 1a3f3ba519cf5f1d1bfb147ac1f92f9ede01462a | 1ab9fa2b950430b9d6714d681765c818dca4a5be |
refs/heads/master | <repo_name>Artem2021-Step/CPP-OOP<file_sep>/Semestr_1/Kyrsova/SpaceBattleConsole/SpaceBattleConsole/SpaceBattleConsole/SpaceBattleConsole.cpp
#include <time.h>
#include <thread>
#include "Fild.h"
#include <iostream>
#include <Windows.h>
#include "Ship.h"
//
//void setCursorPositio(int x, int y)
//{
// static const HANDLE hOut = GetStdHandle(STD_OUTPUT_HANDLE);
// std::cout.flush();
// COORD coord = { (SHORT)x, (SHORT)y };
// SetConsoleCursorPosition(hOut, coord);
//}
int main()
{
srand((unsigned int)time(0));
// std::cout << "1234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890";
Fild fild(100, 20, 2);
setCursorPosition(0, 21);
std::cout << "First update";
fild.UpdateFild();
setCursorPosition(0, 21);
system("pause");
fild.StartTest();
setCursorPosition(0, 22);
std::cout << "Test end run\n"
<< "Player 1 >> 'Up', 'Down', fire >'Spase'\n"
<< "Player 2 >> 'num 8', 'num 2', fire >'num 0'\n";
fild.Play();
//ship1.SetPosition(10, 100);
//ship2.SetPosition(10, 100);
//
//int y = 10;
//while (true)
//{// setCursorPositio(0, 21);
// this_thread::sleep_for(std::chrono::milliseconds(40));
// fild.UpdateFild();
//
// if (GetAsyncKeyState(VK_UP) == -32767)
// {fild.StartTest();
// y--;
///* ship1.SetPosition(y, 100);
// ship2.SetPosition(y, 100);*/
// }
// if (GetAsyncKeyState(VK_DOWN) == -32767)
// {
// y++;
// //ship1.SetPosition(y, 100);
// //ship2.SetPosition(y, 100);
// }
// if (GetAsyncKeyState(VK_SPACE) == -32767)
// {
// }
//}
}
<file_sep>/Semestr_1/Kyrsova/SpaceBattleConsole/SpaceBattleConsole/SpaceBattleConsole/Fild.cpp
#include "Fild.h"
#include <thread>
Fild::Fild(int x_, int y_, int retreat_)
{
this->X = x_;
this->Y = y_;
this->retreat = retreat_;
for (int i = 0; i < y_; i++)
{
this->listLine.push_back(new GameLine(retreat_ + i, x_));
}
ship_L.PrintLife(x_);
ship_R.PrintLife(x_);
ship_L.SetEnemy(&ship_R);
ship_R.SetEnemy(&ship_L);
}
void Fild::StartTest()
{
int r = 0;
for (int i = 0; i < 6; i++)
{
r = rand() % 20;
listLine[r]->StartTest(i);
listLine[r]->SetChange(true);
}
}
vector<GameLine*> Fild::GetList()
{
return this->listLine;
}
void Fild::UpdateFild()
{
for ( GameLine *gl : this->listLine)
{
if (gl->GetChange())
{
gl->UpdateLine();
}
}
}
time_t t = std::time(0);
void Fild::Play()
{
int y_l = this->retreat + 10, y_r = this->retreat + 10;
ship_L.SetPosition(y_l, X);
ship_R.SetPosition(y_r, X);
t = std::time(0);
while (true)
{
this_thread::sleep_for(std::chrono::milliseconds(40));
if (time(0) - t > 30)//30sec
{
t = time(0);
}
UpdateFild();
if (GetAsyncKeyState(VK_UP) == -32767)
{
if (y_l > 1 + this->retreat)
{
y_l--;
ship_L.SetPosition(y_l, X);
}
}
if (GetAsyncKeyState(VK_DOWN) == -32767)
{
if (y_l < this->Y - 1 + this->retreat)
{
y_l++;
ship_L.SetPosition(y_l, X);
}
}
if (GetAsyncKeyState(VK_NUMPAD8) == -32767)
{
if (y_r > 1 + this->retreat)
{
y_r--;
ship_R.SetPosition(y_r, X);
}
}
if (GetAsyncKeyState(VK_NUMPAD2) == -32767)
{
if (y_r < this->Y - 1 + this->retreat)
{
y_r++;
ship_R.SetPosition(y_r, X);
}
}
if (GetAsyncKeyState(VK_SPACE) == -32767)
{
ShipFire(&ship_L);
}
if (GetAsyncKeyState(VK_NUMPAD0) == -32767)
{
ShipFire(&ship_R);
}
}
}
void Fild::ShipFire(Ship* ship_)
{
if (ship_->GetSide() == Ship::Side::LEFT)
this->listLine[ship_->GetPosition() - this->retreat]->SetActivity(4, Activity::TypeActyvity::bullet, 4, ship_);
else if (ship_->GetSide() == Ship::Side::RIGHT)
this->listLine[ship_->GetPosition() - this->retreat]->SetActivity(-(this->X- 5), Activity::TypeActyvity::bullet, this->X - 5, ship_);
}
<file_sep>/Semestr_1/Kyrsova/SpaceBattleConsole/SpaceBattleConsole/SpaceBattleConsole/Ship.cpp
#include "Ship.h"
#include <iostream>
Ship::Ship(Side s_)
{
this->side = s_;
}
void Ship::Print( int l_)
{
if (side == Side::LEFT)
{
setCursorPosition(1, position_Y - 1);
std::cout << this->ship_L[0];
setCursorPosition(2, position_Y);
std::cout << this->ship_L[1];
setCursorPosition(1, position_Y + 1);
std::cout << this->ship_L[2];
}
else
{
setCursorPosition(l_-3, position_Y - 1);
std::cout << this->ship_R[0];
setCursorPosition(l_-4, position_Y);
std::cout << this->ship_R[1];
setCursorPosition(l_-3, position_Y + 1);
std::cout << this->ship_R[2];
}
}
void Ship::SetPosition(int y_, int l_)
{
Clear(l_);
this->position_Y = y_;
Print(l_);
}
int Ship::GetPosition()
{
return this->position_Y;
}
void Ship::Clear(int l_)
{
if (side == Side::LEFT)
{
setCursorPosition(1, position_Y - 1);
std::cout << " ";
setCursorPosition(2, position_Y);
std::cout << " ";
setCursorPosition(1, position_Y + 1);
std::cout << " ";
}
else
{
setCursorPosition(l_ - 3, position_Y - 1);
std::cout << " ";
setCursorPosition(l_ - 4, position_Y);
std::cout << " ";
setCursorPosition(l_ - 3, position_Y + 1);
std::cout << " ";
}
}
//void Ship::Fire(GameLine* gl_)
//{
// if (this->side == Side::LEFT)
// gl_->SetActivity(3, Activity::TypeActyvity::bullet, 3);
// else if (this->side == Side::RIGHT)
// gl_->SetActivity(-(gl_->GetLenght()- 4), Activity::TypeActyvity::bullet, gl_->GetLenght() - 4);
//}
void Ship::Damage()
{
this->lives--;
}
void Ship::PrintLife(int l_)
{
int x = 7;
if (this->side == Side::RIGHT)
x = l_ - (x+2);
setCursorPosition(x, 1);
std::cout << " ";
setCursorPosition(x, 1);
for (int i = 0; i < this->lives; i++)
std::cout << "*";
}
bool Ship::HitCheck(int y_, int l_)
{
if (y_ == this->position_Y || y_ == this->position_Y + 1 || y_ == this->position_Y - 1)
{
this->Damage();
this->PrintLife(l_);
return true;
}
return false;
}
Ship::Side Ship::GetSide()
{
return this->side;
}
void Ship::SetEnemy(Ship* enemy_)
{
this->enemyShip = enemy_;
}
Ship* Ship::GetEnemy()
{
return this->enemyShip;
}
<file_sep>/Semestr_1/Kyrsova/SpaceBattleConsole/SpaceBattleConsole/SpaceBattleConsole/Fild.h
#pragma once
#include "GameLine.h"
#include "Ship.h"
#include <ctime>
using namespace std;
class Fild
{
public:
Fild(int, int, int );
void StartTest();
vector<GameLine*> GetList();
void UpdateFild();
void Play();
void ShipFire(Ship* ship_);
private:
Ship ship_L = Ship::Side::LEFT;
Ship ship_R = Ship::Side::RIGHT;
int X = 0, Y = 0, retreat =0;
vector<GameLine*> listLine;
};
<file_sep>/Semestr_1/Kyrsova/SpaceBattleConsole/SpaceBattleConsole/SpaceBattleConsole/Ship.h
#pragma once
#include "SetCursor.h"
#include <string>
class Ship
{
public:
enum class Side
{
LEFT,
RIGHT,
none
};
Ship(Side);
void Print(int);
void SetPosition(int, int);
int GetPosition();
void Clear(int);
//void Fire(GameLine*);
void Damage();
void PrintLife(int);
bool HitCheck(int, int);
Side GetSide();
void SetEnemy(Ship*);
Ship* GetEnemy();
private:
int lives = 3;
int shipWidth = 3;
int position_Y = 10;
Side side = Side::none;
Ship* enemyShip = nullptr;
std::string ship_L[3]
{
R"(#\)",
"#-",
"#/"
};
std::string ship_R[3]
{
"/#",
"-#",
R"(\#)"
};
};
| feed3e8022d94b8c3fd4a264781625a76a02e23f | [
"C++"
] | 5 | C++ | Artem2021-Step/CPP-OOP | fc8966d515d0d5cdf38dc1bd1187c5db3f008fcb | fc0957befd38784edcfbe0bdbe98a45819140602 |
refs/heads/master | <repo_name>nathomas12/MLMadness2017<file_sep>/simplelinreg.R
#Simple Linear Model
library(readr)
library(stringr)
library(dplyr)
library(reshape)
#Load data
tourney_seeds <- read_csv("TourneySeeds.csv")
tourney_compact_results <- read_csv("TourneyCompactResults.csv")
sample_submission <- read_csv("sample_submission.csv")
#build training set
seed.lm.train <- tourney_compact_results %>%
select(Season, Wteam, Lteam) %>%
filter(Season<2013)
seed.lm.train$FirstTeam <- pmin(seed.lm.train$Wteam, seed.lm.train$Lteam)
seed.lm.train$SecondTeam <- pmax(seed.lm.train$Wteam, seed.lm.train$Lteam)
seed.lm.train$FirstTeamWin<-0
seed.lm.train$FirstTeamWin[seed.lm.train$Wteam==seed.lm.train$FirstTeam] <- 1
#set seed data
seed.lm.train <- seed.lm.train %>%
left_join(tourney_seeds, by=c("Season", "FirstTeam" = "Team"))%>%
left_join(tourney_seeds, b=c("Season", "SecondTeam" = "Team"), suffix=c(".FirstTeam", ".SecondTeam"))
#grab numerical part of seed and calculate seed difference
seed.lm.train$Seed.FirstTeam <- str_extract(seed.lm.train$Seed.FirstTeam,"[:digit:]+")
seed.lm.train$Seed.SecondTeam <- str_extract(seed.lm.train$Seed.SecondTeam, "[:digit:]+")
seed.lm.train$Seed.FirstTeam <- as.numeric(seed.lm.train$Seed.FirstTeam)
seed.lm.train$Seed.SecondTeam <- as.numeric(seed.lm.train$Seed.SecondTeam)
seed.lm.train$SeedDistance <- seed.lm.train$Seed.SecondTeam - seed.lm.train$Seed.FirstTeam
#build the model
seed.lm.model <- lm(FirstTeamWin ~ SeedDistance, data = seed.lm.train)
summary(seed.lm.model)
#training set prediction
seed.lm.train.prediction <- predict(seed.lm.model, seed.lm.train)
#log loss function
MultiLogLoss <- function(act, pred){
eps <- 1e-15
pred <- pmin(pmax(pred, eps), 1-eps)
sum(act*log(pred) + (1-act) * log(1-pred)) * -1/NROW(act)}
MultiLogLoss(seed.lm.train$FirstTeamWin, seed.lm.train.prediction)
#prepare submission file
seed.lm.submission <- cbind(sample_submission$id, colsplit(sample_submission$id, split="_", names=c("Season", "FirstTeam", "SecondTeam")))
seed.lm.submission <- seed.lm.submission %>%
left_join(tourney_seeds, by=c("Season","FirstTeam"="Team")) %>%
left_join(tourney_seeds, by=c("Season", "SecondTeam" = "Team"), suffix=c(".FirstTeam", ".SecondTeam"))
seed.lm.submission$Seed.FirstTeam <- str_extract(seed.lm.submission$Seed.FirstTeam, "[:digit:]+")
seed.lm.submission$Seed.SecondTeam <- str_extract(seed.lm.submission$Seed.SecondTeam, "[:digit:]+")
seed.lm.submission$Seed.FirstTeam <- as.numeric(seed.lm.submission$Seed.FirstTeam)
seed.lm.submission$Seed.SecondTeam <- as.numeric(seed.lm.submission$Seed.SecondTeam)
seed.lm.submission$SeedDistance <- seed.lm.submission$Seed.SecondTeam - seed.lm.submission$Seed.FirstTeam
seed.lm.submission.prediction <- predict(seed.lm.model, seed.lm.submission)
seed.lm.submission <- data.frame(id=sample_submission$id, pred=seed.lm.submission.prediction)
write.csv(seed.lm.submission, file="SeedLinearModelSubmisison.csv", row.names=FALSE)
<file_sep>/main.R
##libraries##
library(ggplot2)
library(plyr)
##load data##
teams <- read.csv('Teams.csv')
seasons <- read.csv('Seasons.csv')
rsdr <- read.csv('RegularSeasonDetailedResults.csv')
tdr <- read.csv('TourneyDetailedResults.csv')
seeds <- read.csv('TourneySeeds.csv')
slots <- read.csv('TourneySlots.csv')
# % of wins by H/A/N
#get frequency
rs_loc_freq <- as.data.frame(count(rsdr$Wloc))
#get percentage
rs_loc_freq['percentage'] <- 100/sum(rs_loc_freq$freq)*rs_loc_freq$freq
rs_loc_freq['percentage_r'] <- signif(rs_loc_freq$percentage,digits=3)
#calculate center of each segment for label
rs_loc_freq['pos'] <- cumsum(rs_loc_freq$percentage) - rs_loc_freq$percentage/2
#set levels for segments for labeling
rs_loc_freq$x <- factor(rs_loc_freq$x, levels=rev(rs_loc_freq$x))
#build pie chart
p<- ggplot(rs_loc_freq, aes(x="", y=percentage_r, fill=x)) + geom_bar(stat="identity")
pie <- p+coord_polar("y") +
ggtitle("Season: Percentage of games won at each location") +
scale_fill_brewer("Blues") +
guides(fill=guide_legend(title='Location')) +
geom_text(aes(y=pos, label=percentage_r), size=4)
pie
### Frequency of Overtime Periods
rs_ot_freq<-as.data.frame(count(rsdr, Numot))
rs_ot_freq$n <- as.factor(rs_ot_freq$n)
ggplot(rs_ot_freq, aes(x=Numot, y=n)) + ggtitle("Season: Number of Overtime Periods") +
geom_bar(stat='identity') +
xlab("Overtime Periods") +
ylab('Frequency') +
geom_text(aes(label=Numot), vjust=-0.3, size=3.5)
<file_sep>/model.R
#load libraries
library(ggplot2)
library(dplyr)
#load data
seeds <- read.csv("TourneySeeds.csv")
teams <- read.csv("Teams.csv")
seasondata <- read.csv("RegularSeasonDetailedResults.csv")
seasondatacompact<-read.csv("RegularSeasonCompactResults.csv")
tourneydata <- read.csv("TourneyDetailedResults.csv")
tourneydatacompact<-read.csv("TourneyCompactResults.csv")
submission <- read.csv("sample_submission.csv")
# data wrangling for seed distance
seeds$num_seed <- as.numeric(substr(seeds$Seed,2,3))
seeds$region<- as.character(substr(seeds$Seed,1,1))
#data wrangling for team 1 and team 2
tourneydatacompact$team1<- pmin(tourneydatacompact$Wteam,tourneydatacompact$Lteam)
tourneydatacompact$team2<- pmax(tourneydatacompact$Wteam,tourneydatacompact$Lteam)
#build per-game statistics
seasondata$WfgPercent<- seasondata$Wfgm/seasondata$Wfga
seasondata$LfgPercent<- seasondata$Lfgm/seasondata$Lfga
seasondata$WftPercent<- seasondata$Wftm/seasondata$Wfta
seasondata$LftPercent<- seasondata$Lftm/seasondata$Lfta
winnerHistory<-seasondata[,c("Season","Wteam","Wscore","WfgPercent","WftPercent")]
winnerHistory$victory<-1
loserHistory<-seasondata[,c("Season","Lteam","Lscore","LfgPercent","LftPercent")]
loserHistory$victory<-0
names(winnerHistory)<-c("season","team","score","fgp","ftp","victory")
names(loserHistory)<-c("season","team","score","fgp","ftp","victory")
teamHistory <- rbind(winnerHistory,loserHistory)
#create per season, per team stats
averageStats <- aggregate(teamHistory, by=list(teamHistory$season, teamHistory$team), FUN=mean, na.rm=TRUE)
| 33b1ec9f31b0d396ac0f0b0f6b2530f59283789a | [
"R"
] | 3 | R | nathomas12/MLMadness2017 | 1504900c24f9b80a9c5c9e85a710aa3754fc54c8 | 326c4377f505744253e00191595b919fc4588b5b |
refs/heads/master | <file_sep>package pe.edu.upeu.hjvr.examen;
import pe.edu.upeu.hjvr.utils.LeerTeclado;
public class ResolucionExamen {
LeerTeclado leer=new LeerTeclado();
public void ImpuestoAuto(){
int i;
double cat1, cat2, cat3, impuesto, TotalPagoVehiculos;
cat1 = 0;
cat2 = 0;
cat3 = 0;
TotalPagoVehiculos = 0;
int num=leer.hjvr(1, "Ingrese el N° de vehiculos que posee:");
for (i=1; i<=num; i++) {
System.out.println("Vehiculo N°" +i);
double categoria=leer.hjvr(0, "Digite la categoria a la que pertecence:");
double precio=leer.hjvr(0,"Digite su precio:");
impuesto=0;
if(categoria==1)
{
impuesto=precio*0.1;
cat1=cat1+impuesto;
}
else if(categoria==2)
{
impuesto=precio*0.07;
cat2=cat2+impuesto;
}
else if(categoria==3)
{
impuesto=precio*0.05;
cat3=cat3+impuesto;
}else{
System.out.println("Ingrese la categoria correcta!");
}
TotalPagoVehiculos=TotalPagoVehiculos+impuesto;
System.out.println("El impuesto a pagar es: " + impuesto);
System.out.println();
}
System.out.println("Total a pagar por la cat1 es: " + cat1);
System.out.println("total a pagar por la cat2: " + cat2);
System.out.println("Total a pagar por la cat3: " + cat3);
System.out.println("Total a pagar por sus vehiculos es: " + TotalPagoVehiculos);
}
public void TablaMulti(){
System.out.println("TABLA DE MULTIPLICAR DEL 1 AL 20");
for(int multiplicador=1; multiplicador<=20; multiplicador++){
System.out.println();
System.out.println(" Tabla del "+multiplicador);
for(int multiplicando=1; multiplicando<=10; multiplicando++){
System.out.println("\t"+multiplicando+" x "+multiplicador+" = "+multiplicando*multiplicador);
}
}
}
public void NumPerfect(){
int i=1, c=0, d;
int num=leer.hjvr(0, "Cuantos numeros perfectos desea ver?");
System.out.println();
do {
d=0;
i=i+1;
for (int n=1; n<=i-1; n++) {
if ((i%n)==0) {
d=d+n;
}
}
if (d==i) {
c=c+1;
System.out.println(i);
}
} while (c!=num);
}
public void Recursividad(){
int x=leer.hjvr(0,"Ingrese el numero base que desea calcular:");
int n=leer.hjvr(0,"Ingrese el exponente del numero base:");
System.out.println("Resultado:"+potencia(x,n));
}
public static int potencia(int x, int n){
if(n==0) return 1;
return x * potencia(x,n-1);
}
} | b6df51974e289af50f0aca845af275d14acf2c12 | [
"Java"
] | 1 | Java | HJhonatanVR/ExamenHJVR | 28c5477a07ae623f43178a0249a014cb7b411a9d | 033618f262d9ea5ac9b926475624d2af5091ba7f |
refs/heads/master | <file_sep>/**
* Spring Data JPA repositories.
*/
package charlie.ding.com.repository;
<file_sep>/**
* Spring Framework configuration files.
*/
package charlie.ding.com.config;
<file_sep>/**
* Audit specific code.
*/
package charlie.ding.com.config.audit;
<file_sep>/**
* Spring Security configuration.
*/
package charlie.ding.com.security;
<file_sep>/**
* View Models used by Spring MVC REST controllers.
*/
package charlie.ding.com.web.rest.vm;
<file_sep>/**
* JPA domain objects.
*/
package charlie.ding.com.domain;
| 7fe11b7483f5eafbed2977f143939312fcbc3063 | [
"Java"
] | 6 | Java | Charlieen/jhipsterSampleApplication2 | 294343347d793b9b85f008cf28b73b7ec54ba3b8 | 2913a8c1dd87776161e86795d814285ce54ee0f3 |
refs/heads/master | <file_sep>var template = '<li class="articles-li clear-float">'+
'<div class="article-pic float-left">'+
'<img src="<%img%>" alt="" class="img-responsive">'+
'</div>'+
'<div class="article-brief float-left">'+
'<div class="article-title clear-float">'+
'<a href="<%uri%>">'+
'<div class="title-content float-left"><%name%></div>'+
'</a>'+
'<div class="article-category float-right"><%class%></div>'+
'</div>'+
'<a href="<%uri%>">'+
'<div class="article-content"><%brief%></div>'+
'</a>'+
'<div class="article-create-time">@ <%createTime%></div>'+
'</div>'+
'</li>';
var setTemplate = function(tpl,article){
var re = /<%([^%>]+)?%>/g;
while(match = re.exec(tpl)) {
tpl = tpl.replace(match[0],article[match[1]]);
}
return tpl;
}
<file_sep>//初始化
var imgs = [articles[0].img, articles[1].img, articles[2].img, articles[3].img]
var lunboDiv = $(".lunbotu");//jqObject为轮播图的父元素
var lunboBar = $(".lunbobar");
var index = 1;//一开始为第一张图片,所以index从第二张开始
//在DIV中添加图片
(function(imgs){
for(var i in imgs) {
lunboDiv.append('<a href="' + articles[i].uri+ '"><img class="img-responsive lunbo-img" src="' + imgs[i] + '"></a>');
}
lunboDiv.find("a").eq(0).siblings("a").hide();//隐藏除了第一张以为的图片
})(imgs);
//添加第0篇简介
$(".recommend-brief").text('"' + articles[0].brief + '"');
//展示序号为n的图片及简介,并修改链接
var showImg = function(n){
lunboDiv.find("a").eq(n).fadeIn(200).siblings("a").hide();
$(".recommend-brief").text('"' + articles[n].brief + '"');
}
//轮播
setInterval(function(){
showImg(index);
lunboBar.find("ul").children().eq(index).find("div").css({"height": lunboBarSize*1.5 + "px", "width": lunboBarSize*1.5 + "px", "border-radius": lunboBarSize*1.5/2 + "px", "margin-top": (0-lunboBarSize*.5)/2 + "px", "margin-left": (0-lunboBarSize*.5)/2 + "px"});
lunboBar.find("ul").children().eq(index).siblings().find("div").css({"height": lunboBarSize + "px", "width": lunboBarSize + "px", "border-radius": lunboBarSize/2 + "px", "margin": 0});
var len = imgs.length
index = (index + 1) % len;
},2000);
var lunboBarSize = 8;//轮播条点的大小
var lunboPointColor = "#00a67c"; //轮播点的颜色
//添加ul并居中
lunboBar.append('<ul class="clear-float"></ul>');
lunboBar.find("ul").css({"width": lunboBarSize*2*imgs.length,"margin-left": "auto", "margin-right": "auto"});
//根据轮播图数量,添加点
for(var i in imgs) {
lunboBar.find("ul").append('<li class="float-left"><div class="point"></div></li>');
}
lunboBar.find("ul").children().css({"height": lunboBarSize + "px", "width": lunboBarSize + "px", "margin-right": lunboBarSize});
//初始化圆点,并将第一个变大&调整位置
lunboBar.find("ul").children().find("div").css({"height": lunboBarSize + "px", "width": lunboBarSize + "px", "border-radius": lunboBarSize/2 + "px", "background-color": lunboPointColor,});
lunboBar.find("ul").children().eq(0).find("div").css({"height": lunboBarSize*1.5 + "px", "width": lunboBarSize*1.5 + "px", "border-radius": lunboBarSize*1.5/2 + "px", "margin-top": (0-lunboBarSize*.5)/2 + "px", "margin-left": (0-lunboBarSize*.5)/2 + "px"});
//绑定点击事件
lunboBar.find("ul").children().click(function(){
index = $(this).index();
showImg(index);
lunboBar.find("ul").children().eq(index).find("div").css({"height": lunboBarSize*1.5 + "px", "width": lunboBarSize*1.5 + "px", "border-radius": lunboBarSize*1.5/2 + "px", "margin-top": (0-lunboBarSize*.5)/2 + "px", "margin-left": (0-lunboBarSize*.5)/2 + "px"});
lunboBar.find("ul").children().eq(index).siblings().find("div").css({"height": lunboBarSize + "px", "width": lunboBarSize + "px", "border-radius": lunboBarSize/2 + "px", "margin": 0});
});<file_sep>var numPerPage = 8;//每页目录文章数量
var curPageNum = 0;//当前加载到第几页
var articleList = [];//根据分类获取到的文章目录
//点击分类
$(document).ready(function(){
$(".category-li").click(function(){
// 改变样式
$(this).find(".category-div").css({"background-color": "#00a67c", "color": "#fff", "font-size" :"18px"});
$(this).siblings().find(".category-div").css({"background-color": "#fff", "color": "#00a67c", "font-size" :"16px"});
//根据index修改目录
var index = $(this).index();
articleList = getList(index);
curPageNum = 0;//当前页归零
$(".articles-ul").empty();//清空目录
$(".next-page").hide();//隐藏下一页按钮
for(var i in articleList){
if(i > numPerPage -1 ){//只显示前八项
curPageNum++;
$(".next-page").show();
break;
}
$(".articles-ul").append(setTemplate(template,articleList[i]));
}
});
});
window.onload = function(){
//初始化目录
$(".category-ul").children().first().find(".category-div").css({"background-color": "#00a67c", "color": "#fff", "font-size" :"18px"});
articleList = getList(0);
$(".articles-ul").empty();//清空目录
$(".next-page").hide();//隐藏下一页按钮
for(var i in articleList){
if(i > numPerPage -1 ){//只显示前八项
curPageNum++;
$(".next-page").show();
break;
}
$(".articles-ul").append(setTemplate(template,articleList[i]));
}
}
window.onresize = function(){
}
//点击下一页
$(".next-page").click(function(){
var lastOne = (articleList.length - curPageNum*numPerPage) < numPerPage ? articleList.length : curPageNum*numPerPage+numPerPage;
$(".next-page").hide();//隐藏下一页按钮
for(var i = curPageNum*numPerPage ; i < lastOne; i++){
$(".articles-ul").append(setTemplate(template,articleList[i]));
}
if((articleList.length - curPageNum*numPerPage) > numPerPage){
$(".next-page").show();//剩余数量大于8,显示下一页
curPageNum++;
}
});
$(".weiboLink img").mouseover(function(){
$(this).attr("src", "./imgs/weibo1.png");
});
$(".weiboLink img").mouseout(function(){
$(this).attr("src", "./imgs/weibo0.png");
});
$(".weixinLink img").mouseover(function(){
$(this).attr("src", "./imgs/weixin1.png");
});$(".weixinLink img").mouseout(function(){
$(this).attr("src", "./imgs/weixin0.png");
});
$(".weixin-pic").hide();
$(".weixinLink").mouseover(function(){
$(".weixin-pic").show();
$(".weixin-pic").css({"margin-top": 0-$(".weixin-pic").height()});
});
$(".weixinLink").mouseout(function(){
$(".weixin-pic").hide();
});
$(".weixinLink").click(function(){
$(".weixin-pic").show();
$(".weixin-pic").css({"margin-top": 0-$(".weixin-pic").height()});
});
<file_sep>var articles = [];
var articlePos = "./articles/";//文章路径
var imgPos = "./imgs/";//图片路径
var addArticle = function(iname,iuri,iclass,iimg,icreatetime,ibrief){
articles.push({name:iname, uri:articlePos+iuri, class:iclass,img:imgPos+iimg, createTime:icreatetime,brief:ibrief});
}
//新增文章加在最上面
addArticle("UI测试自动化实例","article11.html","--术业--","12.png","2016-10-24","这是一篇关于构建UI自动化测试的一篇文章,实现基于python的selenium框架。同时介绍了unittest案例组织方式,以及Cx_oracle的中文处理等。");
addArticle("摆渡人","article12.html","--闻道--","13.png","2016-10-21","也曾在南京待过一年,那是一座很有韵味的城市。只可惜,自己是不善喝酒的。 没能去见识1912,没能去见识那些传说,自然也没能过一把酒肉穿肠的瘾。");
addArticle("苏打绿是什么绿","article10.html","--闻道--","1.png","2016-04-23","苏打里哪有什么气泡,那是心思晃动出的小情绪。王国维在人间词话里提到“词以境界为上。有境界则自成高格,自有名句。”愚以为,歌曲亦如是。");
addArticle("愿无岁月可回首","article9.html","--闻道--","2.png","2016-04-08","愿无岁月可回首。让过去的过去,让未来的到来。八千年玉老,一叶枯荣,问苍天此生何必?人生如梦,刹那芳华!");
addArticle("阿里云搭建nodejs服务器不完全指北","article8.html","Node.js","3.png","2016-03-27","在搭建Node.js服务器时,记录了一些操作步骤和一些所需的琐碎细节。");
addArticle("一本正经瞎扯淡,装模作样吹牛逼","article7.html","--闻道--","4.png","2016-03-03","侠之大者,为国为民。金庸把它写在了小说里,我希望把它写在程序里。文字和程序只是不同的载体。虽然练的是三脚猫功夫,但也有颗武侠梦。");
addArticle("写在2015岁末","article6.html","--闻道--","5.png","2015-12-31","我们曾经如此渴望命运的波澜,到最后才发现,人生最曼妙的风景,竟是内心的淡定与从容。我们曾经如此期盼外界的认可,到最后才知道,世界是自己的,与他人毫无关系。");
addArticle("体脂从18到15的记录与思考","article5.html","--修身--","6.png","2015-12-27","总体是 以平均小于5%的损失,获得了平均大于20%以上的收获。即以小幅度肌肉、维度、代谢水平的减少换来了大量的脂肪减少。");
addArticle("ThanksHaving","article4.html","--闻道--","7.png","2015-11-30","遇见对的人,大概就是“一切繁复的表相都会褪去,一切喧嚣的浮世都会静好,变得简单,简单到无需刻意讨好,无需处心积虑,无需心机手段,无需防范戒备,无需步步为营,只觉得,就是他了。然后现世安稳,岁月静好,感动常在,慢慢变老。”");
addArticle("臣附议","article3.html","--闻道--","8.png","2015-10-25","江山无处埋忠骨,满朝文武皆佞臣。说到底,皇朝天下,不过嫖客相争。“持身不正,持心不纯,则权势富贵皆如云烟。无论何情何景,勿忘本心之善念。”");
addArticle("年少不再,何以荒唐","article2.html","--闻道--","9.png","2015-10-11","不知道从什么时候起,想当年披风上的“不”字已隐隐不可见。但仍旧手提三尺剑,一身素色青衣,迎风而立。与年少时一样,只是眼里看得明白,山还是山,水还是水。");
addArticle("健身的形而上学","article1.html","--修身--","10.png","2015-06-18","圈里圈外都流行一句话,健身先健脑——TRAIN SMART AS WELL AS HARD。愿灵魂和肉体,相识相知相融。");
addArticle("测试的形而上学","article0.html","--术业--","11.png","2015-06-17","知识、经验的作用是辅助思考,而不是禁锢思想。切记本末倒置。");
//根据类型,筛选文章。0.ALL;1.术业;2.闻道;3.修身;4.Python;5.FrontEnd;6.NodeJs;
var getList = function(index) {
var homeList = [];
var category = ["ALL", "--术业--", "--闻道--", "--修身--"]
if(index === 0) {
homeList = articles;
}else if(index === 1){
for(var i in articles){
if((articles[i].class != category[2]) && (articles[i].class != category[3])) {
homeList.push(articles[i]);
}
}
}else{
for(var i in articles){
if(articles[i].class === category[index]) {
homeList.push(articles[i]);
}
}
}
return homeList;
}
//根据生成list
var setList = function(index){
var articleList = getList(index);
for(var i in articleList){
setTemplate(template,articleList[i]);
}
}<file_sep><!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>who are x</title>
<link rel="icon" href="../imgs/favicon.ico" type="image/x-icon"/>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
<link href="http://libs.baidu.com/bootstrap/3.0.3/css/bootstrap.min.css" rel="stylesheet">
<script src="http://libs.baidu.com/jquery/2.0.0/jquery.min.js"></script>
<script src="http://libs.baidu.com/bootstrap/3.0.3/js/bootstrap.min.js"></script>
<link rel="stylesheet" href="./article.css">
</head>
<body>
<div class="container">
<a href="../home.html">
<img src="../imgs/hometitle.png" class="img-responsive" alt="">
</a>
<div class="row">
<div class="col-md-9">
<div class="breadcrumbs clear-float">
<div class="float-left"><a href="../home.html">首页</a></div>
<div class="float-left">></div>
<div class="float-left">
臣附议
</div>
</div>
<div class="article-title">
臣附议
</div>
<div class="article-category">#<a href="javascript:void(0);">
--闻道--
</a> whorx@
2015-10-25
</div>
<div class="article-content">
<!-- 文章内容开始 -->
<p>见故事,见人心。——题记</p>
<p><span class="bigger">【一】不如假装没心没肺,什么都不知道的好</span></p>
<p>江山无处埋忠骨,满朝文武皆佞臣。</p>
<p>我才懒得去理会朝政,宫墙内外尔虞我诈已经够多了。倒不是怕与他们争功名利禄,只是怕自己狠起来的时候,吓到自己。</p>
<p>说到底,皇朝天下,不过嫖客相争。</p>
<p>我只想做一个江湖郎中,能“医死”人那种。</p>
<p>我了本浪荡惯,以为能一生不羁放纵爱自由。却遇上一个人,甘“士为知己者死”。恰逢他身怀异病,我又略懂些医术,也正好给他做个大夫。他性子倔,不怎么听我的劝。哎,真是死了活该,好在我也不怎么听他的。</p>
<p>无论他做怎样的选择,随他去吧。毕竟这个世界上,再没有比我更懂他的人了。</p>
<p><span class="bigger">【二】大道至简</span></p>
<p>苏哥哥,喜欢;庭生,喜欢。</p>
<p>蔺晨,不喜欢;蒙挚,不喜欢。</p>
<p>苏哥哥夸,笑;苏哥哥斥责,赌气。</p>
<p>陌生人,防备;坏人,打。</p>
<p><span class="bigger">【三】痴情却被无情恼</span></p>
<p>在这妙音坊筹备了许久,宗主终于要来金陵城了。以后终于能时常见到宗主。</p>
<p>自宗主来了金陵城后,十三先生就一直不让我见宗主。冒着被指责的风险去看他,终究是没见着。</p>
<p>在这富贵风流场,空有一身技艺,妙弹这宫商角徵羽。而声声赞赏,却无一来自心里的那个人,终是无趣。</p>
<p>终于等到能随他左右,希望能尽绵薄之力保他周全。即使他依然不冷不淡。最重要的是,能时常见到他,已是极好。</p>
<p>只道是他天生无情,终不知免却多情伤了有情。</p>
<p><span class="bigger">【四】你不懂我,我不怪你;你若懂我,那该多好。</span></p>
<p>其实,我不需要人懂,也不希望被懂。毕竟苦多甜少。</p>
<p>我本是地狱里爬出来的恶鬼,呼吸里透着凉意,行阴诡之术,逆心性而行。虽留有一丝良知,也难免在时光与苟且中消磨殆尽,冷酷铁血了我。倒是感谢上天赐我一副柔弱之躯,也免去心中憎恶滋长出的杀伐之意。</p>
<p>我乃良将之后,本应战死沙场,却因尸骨里融着七万阴魂之灵,怨气未泄而滞留于人间。不得以,以药续命,以命搏清白,以权术制衡朝堂。我多渴望有一天,能重返北疆,战死沙场。</p>
<p>在他们看来,结局是因为我的自信与沉稳。于我而言,有的只是十几年的步步为营,水到渠成。虽如景琰一般,从骨子里鄙夷这些诡谲伎俩,奈何不得不以这种方式走下去。我所做之事,并不能带给我一点点的荣耀与自豪,反而徒增内心的自卑与耻辱。</p>
<p>待到清白宣天下,自将提剑返沙场。</p>
<p><span class="bigger">附,寒氏之戒,“持身不正,持心不纯,则权势富贵皆如云烟。无论何情何景,勿忘本心之善念。”</span></p>
<!-- 文章内容结束 -->
</div>
</div>
<div class="col-md-3">
<div class="nav">写在人生边上</div>
<ul class="nav-ul">
<li><a href="javascript:void(0);">闻道有先后</a></li>
<li><a href="javascript:void(0);">术业有专攻</a></li>
<li><a href="javascript:void(0);">世事洞明皆学问</a></li>
<li><a href="javascript:void(0);">人情练达即文章</a></li>
</ul>
</div>
</div>
<div class="footer clear-float">
<div class="about-me float-left" style="text-align: center;">
| 关于我
</div>
<div class="follow-me float-left clear-float">
<img class="weixin-pic img-responsive" src="../imgs/weixinlink.png" alt="">
<div class="float-left">| 关注我</div>
<div class="float-left">
<a href="http://weibo.com/hrx1992" class="weiboLink"><img src="../imgs/weibo0.png" alt=""></a>
<a href="javascript:void(0);" class="weixinLink"><img src="../imgs/weixin0.png" alt=""></a>
</div>
</div>
</div>
</div>
<script src="./article.js"></script>
</body>
</html><file_sep>1.articleModel.html中,<%title%> <%content%>都需要单独占一行
2.文件编码格式必须为utf-8
<file_sep>var express = require('express');
var app = express();
var PORT = 80;
var IP = '127.0.0.1';
app.use(express.static('portal'));
app.get('/',function(req,res){
var options = {
root: __dirname + '/portal',
dotfiles: 'deny',
headers:{
'x-timestamp': Date.now(),
'x-sent': true
}
}
res.sendFile('./home.html',options,function(err){
if(err){
res.status(err.status).end();
}else{
res.end();
}
});
});
app.get('*', function(req, res){
res.redirect('./404.html');
res.end();
});
var server = app.listen(PORT,IP);
<file_sep>$(".weiboLink img").mouseover(function(){
$(this).attr("src", "../imgs/weibo1.png");
});
$(".weiboLink img").mouseout(function(){
$(this).attr("src", "../imgs/weibo0.png");
});
$(".weixinLink img").mouseover(function(){
$(this).attr("src", "../imgs/weixin1.png");
});$(".weixinLink img").mouseout(function(){
$(this).attr("src", "../imgs/weixin0.png");
});
$(".weixin-pic").hide();
$(".weixinLink").mouseover(function(){
$(".weixin-pic").show();
$(".weixin-pic").css({"margin-top": 0-$(".weixin-pic").height()});
});
$(".weixinLink").mouseout(function(){
$(".weixin-pic").hide();
});
$(".weixinLink").click(function(){
$(".weixin-pic").show();
$(".weixin-pic").css({"margin-top": 0-$(".weixin-pic").height()});
});<file_sep>#encoding: UTF-8
import re
import sys
##contentfile为内容文件,infile为生成的html文件
def createArticle(contentfile,infile):
titlePattern = re.compile(r'<%title%>')
contentPattern = re.compile(r'<%content%>')
categoryPattern = re.compile(r'<%category%>')
createtimePattern = re.compile(r'<%createtime%>')
outFile = open('./articleModel.html','r')
contentFile = open(contentfile,'r')
inFile = open(infile,'w')
title = contentFile.readline()##文章名在第1行
category = contentFile.readline()##分类在第2行
createtime = contentFile.readline()##创建时间在第3行
for line in outFile.readlines():
if(titlePattern.search(line)):
inFile.write(title)
elif(categoryPattern.search(line)):
inFile.write(category)
elif(createtimePattern.search(line)):
inFile.write(createtime)
elif(contentPattern.search(line)):
for content in contentFile.readlines():
inFile.write(content)
else:
inFile.write(line)
outFile.close()
contentFile.close()
inFile.close()
if __name__=="__main__":
## contentfile = './articleContent/articleContent1.txt'
## infile = './article1.html'
## createArticle(contentfile,infile)
createArticle(sys.argv[1],sys.argv[2])
#####createArticle.py ./articleContent/articleContent1.txt ./article1.html
<file_sep><!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>who are x</title>
<link rel="icon" href="../imgs/favicon.ico" type="image/x-icon"/>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
<link href="http://libs.baidu.com/bootstrap/3.0.3/css/bootstrap.min.css" rel="stylesheet">
<script src="http://libs.baidu.com/jquery/2.0.0/jquery.min.js"></script>
<script src="http://libs.baidu.com/bootstrap/3.0.3/js/bootstrap.min.js"></script>
<link rel="stylesheet" href="./article.css">
</head>
<body>
<div class="container">
<a href="../home.html">
<img src="../imgs/hometitle.png" class="img-responsive" alt="">
</a>
<div class="row">
<div class="col-md-9">
<div class="breadcrumbs clear-float">
<div class="float-left"><a href="../home.html">首页</a></div>
<div class="float-left">></div>
<div class="float-left">
一本正经瞎扯淡,装模作样吹牛逼
</div>
</div>
<div class="article-title">
一本正经瞎扯淡,装模作样吹牛逼
</div>
<div class="article-category">#<a href="javascript:void(0);">
--闻道--
</a> whorx@
2016-03-03
</div>
<div class="article-content">
<!-- 文章内容开始 -->
<p><span class="bigger">此之谓一本正经。</span></p>
<p>现实实现不了的,就脑补。这就是虚拟现实。脑补的东西弥补了现实的空缺,这就叫增强现实。一切幻想皆虚妄。</p>
<p>“他演尽了悲欢也无人相和的戏,那烛火未明,摇曳满地的冷清。”我自顾自在心里排了一场戏,从台上到台下,自己是唯一的观众,还莫名的感动。</p>
<p>“谁说衰老不是一种绝症。没有任何一种治疗方法,让我们和时间逆行。</p>
<p>时间啊,果然是个很糟糕的家伙。它巧取豪夺,于我全然不顾。</p>
<p>只是,最终什么都没有留下。”</p>
<p>身边有两个例子,他们从初中或者高中就相识相知,然后相爱相伴。现在成家立业,结婚生子。可算是从青梅竹马,到执子之手与子偕老,羡煞旁人。</p>
<p>“只是我不觉得吾等向世界妥协的凡夫俗子有资格拥有这种爱情了。”</p>
<p>给我的勇气一个怀抱,让我知道背后有一个温暖的怀抱等我,享受整个世界的温柔。</p>
<p>给你的努力一个肩膀,让你知道身边有一个坚实的肩膀依靠,撑住你心里的坚强。</p>
<p>有些人最痛苦的事情是放不下,而有些人最痛苦的事情是拿不起。</p>
<p>有个道理,大家都懂:要是错了,只会后悔一阵子。要是怂了,那就是后悔一辈子。只是现在,需要一个契机。或许这个契机永远不会出现,但我天真的相信jesus。</p>
<p><span class="bigger">此之谓瞎扯淡。</span></p>
<p>跟最帅和最有内涵的两个人滚过同一张床单,也是知足了。</p>
<p>“铁打的营盘流水的兵,我们的友谊万年青。”</p>
<p>曾经我爱的人,我们曾一起牵着小手上课的人,已经不爱我了。还拐走了我喜欢的,和最有钱的。世界上,有两种真挚的感情,一个曰爱,一个曰恨。既然不能爱,又不想用恨铭记一辈子,那就只有把打麻将输的钱,记在小本本上,然后认真的镌上你的名字。</p>
<p>苟富贵,勿相忘!</p>
<p><span class="bigger">此之谓“眼前路,身后身。”</span></p>
<p>现实主义的人生,幻想主义的梦想,理想主义的未来。无心的浪子,终将找到一个可以宿醉的怀抱。</p>
<p>所谓自信,大概不是确信自己能成功,而是已经准备好接受所有的可能。</p>
<p><span class="bigger">此之谓装模作样吹牛逼</span></p>
<p>以前总是追求用户黏度,现在是希望用户不那么黏。如果社交网络成了社交娱乐、或者成了营销网络,大概离狗带也不远了。</p>
<p>这个时代最不缺的就是信息,最缺的是有用的信息。最难的不是接收东西,而是挡掉东西。推送式的信息可能让用户反感。最理想的结果,大概是当用户需要信息时,信息正好出现。是精准推送而不是精准营销,但现实中的精准是那么的不精准。</p>
<p>以前觉得,“书读的少想得太多”是贬义。现在倒觉得,学的太杂反倒是脑子里一锅粥。不如多想,把问题捋顺。<span class="bigger">“问道有先后,术业有专攻”。</span></p>
<p>有些话,真的成了口号,以致于骗了自己。比如,用户体验。我们追求的起点到底是用户体验还是我们本身的利益。</p>
<p>突然想到前两天公司平台上的一个提议。用户有可以使用的优惠劵,我展示给他,是希望让他知道有更多优惠还是只想让他多投资。这就涉及到,目的是给用户真的实惠,还是只为圈钱。</p>
<p>打着用户体验的幌子,操着销售人员的心。</p>
<p>是时候把“用户”的问题重新摆一下了。</p>
<p>做技术,就像练功夫,互联网这是个江湖。“持身不正,持心不纯,则盖世神功皆为虚妄。”做技术的人应该有点坚持。</p>
<p>侠之大者,为国为民。金庸把它写在了小说里,我希望把它写在程序里。<span class="bigger">文字和程序只是不同的载体。虽然练的是三脚猫功夫,但也有颗武侠梦。</span></p>
<!-- 文章内容结束 -->
</div>
</div>
<div class="col-md-3">
<div class="nav">写在人生边上</div>
<ul class="nav-ul">
<li><a href="javascript:void(0);">闻道有先后</a></li>
<li><a href="javascript:void(0);">术业有专攻</a></li>
<li><a href="javascript:void(0);">世事洞明皆学问</a></li>
<li><a href="javascript:void(0);">人情练达即文章</a></li>
</ul>
</div>
</div>
<div class="footer clear-float">
<div class="about-me float-left" style="text-align: center;">
| 关于我
</div>
<div class="follow-me float-left clear-float">
<img class="weixin-pic img-responsive" src="../imgs/weixinlink.png" alt="">
<div class="float-left">| 关注我</div>
<div class="float-left">
<a href="http://weibo.com/hrx1992" class="weiboLink"><img src="../imgs/weibo0.png" alt=""></a>
<a href="javascript:void(0);" class="weixinLink"><img src="../imgs/weixin0.png" alt=""></a>
</div>
</div>
</div>
</div>
<script src="./article.js"></script>
</body>
</html> | 225c534f7f566cab10acab165a3f1db048f73a4c | [
"JavaScript",
"Python",
"Text",
"HTML"
] | 10 | JavaScript | hurx/whorx_webserver | 72bb2c39e76f7963bc16c8b51ba3dea8bb3b9c7d | d62fcb25e923038e0c7dba752d80999839b53a76 |
refs/heads/master | <repo_name>jackgit1214/RNStudy<file_sep>/app/component/dynamicPages/reduxAction.js
export function addTypeData() {
return {
type: 'ADD'//types.REQUEST_TYPE_LIST
};
}
export function getTypeDatas() {
console.log("---------------Action----------------------")
return {
type: 'GET_DATA'
};
}
export function exec_increment(){
console.log("---------------Action------------exec_increment----------")
return {
type:'INCREMENT'
}
}
export function getDataBySagas() {
console.log("---------------Action------------GET_DATA_BY_SAGAS----------")
return {
type: 'GET_DATA_BY_SAGAS'
};
}
export function getDatabaseData(dataTypes) {
console.log("---------------Action------------getDatabaseData----------")
return {
type: 'GET_DATABASE_DATA',
dataTypes
};
}
export function receiveDataTypes(dataTypes) {
console.log("------------------refresh data---------------------")
return {
type: 'REFRESH_DATA',//''types.RECEIVE_TYPE_LIST,
dataTypes
};
}
<file_sep>/app/app.js
import React from 'react';
import {Provider} from 'react-redux';
import {createAppContainer, createDrawerNavigator, createStackNavigator} from 'react-navigation';
import rootSaga from './sagas/index';
import configureStore from './store/configure-store';
import drawerNavigator from './component/drawerNavigation'
const AppContainer = createAppContainer(drawerNavigator);
//const AppContainer = createAppContainer(bottomTabNavigator,drawerNavigation);
const store = configureStore();
// run root saga
store.runSaga(rootSaga);
const RootApp = () => (
<Provider store={store}>
<AppContainer/>
</Provider>
);
export default RootApp;
<file_sep>/app/pages/detail.js
import React from 'react';
import {Alert, Button, Text, TextInput, View} from 'react-native';
class DetailsScreen extends React.Component {
constructor(props) {
super(props);
this.state = {text: '22',count:0};
};
static navigationOptions = ({navigation}) => {
return {
title: 'DetailScreen' + navigation.getParam('itemId', ' no Id'),
headerStyle: {
backgroundColor: '#f4511e',
},
headerTintColor: '#000',
headerTitleStyle: {
fontWeight:'bold',
},
headerRight: (
<Button
onPress={navigation.getParam('increaseCount')}
title="+1"
color="#00ff00"
/>
),
headerLeft: (
<Button
onPress={() => navigation.navigate('MyModal')}
title="Info"
color="#fff"
/>
),
};
};
componentDidMount() {
this.props.navigation.setParams({ increaseCount: this._increaseCount });
}
state = {
count: 3,
};
_increaseCount = () => {
this.setState({ count: this.state.count + 1 });
};
render() {
const {navigation} = this.props;
const itemId = navigation.getParam('itemId', 'NO-ID');
const otherParam = navigation.getParam('otherParam', 'some default value');
return (
<View style={{flex: 1, alignItems: 'center', justifyContent: 'center'}}>
<Text>itemId: {JSON.stringify(itemId)}</Text>
<Text>otherParam: {JSON.stringify(otherParam)}{this.state.count}</Text>
<Button
title="Go to Details... again"
onPress={() => this.props.navigation.navigate('Details')}
/>
<View style={{
flexDirection: 'row',
justifyContent: 'space-evenly',
alignItems: 'stretch',
}}>
<View style={{flex: 1}}>
<Button
title="updateParam"
onPress={() => this.props.navigation.setParams({otherParam: 'Updated!'})}
/>
</View>
<View style={{flex: 1}}>
<Button
title="Go back"
onPress={() => this.props.navigation.goBack()}
/>
</View>
<View style={{flex: 1}}>
<Button
onPress={() => {
Alert.alert("你点击了按钮!");
}}
title="点我!"
/>
</View>
</View>
<View style={{padding: 10}}>
<TextInput
style={{height: 40}}
placeholder="Type here to translate!"
onChangeText={(text) => this.setState({text})}
/>
<Text style={{padding: 10, fontSize: 42}}>
{this.state.text.split(' ').map((word) => word && '🍕').join(' ')}
</Text>
</View>
</View>
);
}
}
export default DetailsScreen;
<file_sep>/app/component/dynamicPages/home.js
import React from "react";
import {Button, Icon, Text, ThemeProvider} from "react-native-elements";
import SplashScreen from "react-native-splash-screen";
import appTheme from "../theme";
import {ImageBackground,View} from "react-native";
import common from '../common'
class HomeScreen extends React.Component {
static navigationOptions = {
tabBarLabel: 'home',
tabBarIcon: ({ tintColor, focused }) => (
<Icon
name={focused ? 'emoticon-cool' : 'emoticon-neutral'}
size={30}
type="material-community"
color={tintColor}
/>
),
};
componentDidMount() {
this.timer = setTimeout(() => {
SplashScreen.hide();
}, 200);
}
render() {
const {navigation} = this.props;
return (
<ThemeProvider theme={appTheme} >
<View style={{paddingLeft:10,paddingRight:10}}>
<Text h1>test </Text>
<Button
title="open drawer"
onPress={() => this.props.navigation.openDrawer()}
/>
<Button
title="close drawer"
onPress={() => this.props.navigation.closeDrawer()}
/>
<Button
title="toggle drawer"
type="outline"
onPress={() => this.props.navigation.toggleDrawer()}
/>
<Button
title="Clear button"
type="clear"
/>
<Button
title="Loading button"
loading
/>
<ImageBackground source={common.screen.bgImage} style={common.style.bgImage}>
<Button
title="Create an Account"
clear
activeOpacity={0.5}
titleStyle={{color: 'white', fontSize: 15}}
containerStyle={{marginTop: -10}}
onPress={() => console.log('Account created')}
/>
</ImageBackground>
</View>
</ThemeProvider>
);
}
}
export default HomeScreen;
<file_sep>/app/component/staticPages/tabs/buttons.js
import React from 'react';
import {createStackNavigator} from 'react-navigation';
import MainHeader from "../../mainHeader";
import ButtonsHome from '../views/buttons_home';
import ButtonsDetails from '../views/buttons_detail';
const ButtonsTabView = ({navigation}) => (
<ButtonsHome navigation={navigation}/>
);
const ButtonsDetailTabView = ({navigation}) => (
<ButtonsDetails
banner={`${navigation.state.params.name}s Profile`}
data_Param={'这是测试数据,是否能通过'} //可用于传递数据
navigation={navigation}
/>
);
const ButtonsTab = createStackNavigator({
Buttons: {
screen: ButtonsTabView,
path: '/buttontab',
navigationOptions: ({navigation}) => ({
title: 'Buttons',
header: (
<MainHeader navigation={navigation}/>
),
}),
},
Button_Detail: {
screen: ButtonsDetailTabView,
path: '/buttons_detail',
navigationOptions: ({navigation}) => ({
title: 'Buttons Detail',
header: (
<MainHeader navigation={navigation}/>
),
}),
},
});
export default ButtonsTab;
<file_sep>/app/reducers/dataTypes.js
const initialTypeState = {
loading: false,
typeList: [],
testValue:0
};
const dataTypes = (state = initialTypeState, action) => {
switch (action.type) {
case 'ADD':{
let newDatas = state.typeList;
newDatas.push({name:'test',code:'test01'});
return Object.assign({},state,{loading:true,typeList:newDatas});
}
case 'GET_DATA':{
let newDatas = [{name: 'redux_1', code: 'test1'}, {name: 'redux_2', code: 'test2'}];
return Object.assign({},state,{loading:true,typeList:newDatas});
}
case 'GET_DATABASE_DATA':{
let newDatas = action.dataTypes;
return Object.assign({},state,{loadading:true,typeList:newDatas});
}
case 'REFRESH_DATA':{
let newDatas = action.dataTypes;
console.log(newDatas);
return Object.assign({},state,{loading:true,typeList:newDatas});
}
default:
return state;
}
}
export default dataTypes;
<file_sep>/app/component/dynamicPages/redux.js
import React from "react";
import {Button, Icon, ListItem, ThemeProvider} from "react-native-elements";
import appTheme from "../theme";
import {connect} from 'react-redux'
import {bindActionCreators} from 'redux';
import * as reduxAction from './reduxAction';
import {exec_increment} from './reduxAction';
import {ScrollView,View,Text} from "react-native";
import PropTypes from 'prop-types'
import testData from "../../reducers/testReducers";
// const propTypes = {
// TypeDatas: PropTypes.arrayOf(PropTypes.shape({
// id: PropTypes.number.isRequired,
// completed: PropTypes.bool.isRequired,
// text: PropTypes.string.isRequired
// }).isRequired).isRequired,
// toggleTodo: PropTypes.func.isRequired
// }
const Counter = ({ value, onIncrement, onIncrementAsync, onDecrement, onIncrementIfOdd }) => (
<View>
<Text>Clicked: {value} times</Text>
<Button onPress={onIncrement} title={'+'} />
<Button onPress={onDecrement} title={'-'} />
<Button onPress={onIncrementIfOdd} title={'Increment if odd'}></Button>
<Button onPress={onIncrementAsync} title={'Increment async'}></Button>
</View>
)
Counter.propTypes = {
value: PropTypes.number.isRequired,
onIncrement: PropTypes.func.isRequired,
onDecrement: PropTypes.func.isRequired,
onIncrementAsync: PropTypes.func.isRequired,
onIncrementIfOdd: PropTypes.func.isRequired,
}
class ReduxWay extends React.Component {
static navigationOptions = {
tabBarLabel: 'redux',
tabBarIcon: ({tintColor, focused}) => (
<Icon
name={focused ? 'emoticon-cool' : 'emoticon-neutral'}
size={30}
type="material-community"
color={tintColor}
/>
),
};
constructor(props) {
super(props);
//let test = this.context.store
console.log("-------------------------constructor---------------------------")
// console.log(test);
}
_addData() {
const {reduxActions} = this.props;
reduxActions.addTypeData();
}
_reloadData() {
const {reduxActions} = this.props;
reduxActions.getTypeDatas();
}
_sagasData(){
const {reduxActions} = this.props;
reduxActions.getDataBySagas();
}
_reloadDatabaseData() {
const {reduxActions} = this.props;
let url = 'http://10.10.110.18:8001/xcbx/mobile/getBaseData';
return new Promise((resolve, reject) => {
fetch(url, {
method: 'post',
headers: new Headers({
//'Accept': 'application/json',
//'Content-Type': 'application/json;charset=utf-8'
"Content-Type": "application/x-www-form-urlencoded"
}),
body: "type=1"
}).then((response) => {
return response.json();
}).then((responseData) => {
reduxActions.getDatabaseData(responseData.data);
}).catch((error) => {
//this.setState({isLoad:2});
reject(error);
});
});
};
componentDidMount() {
console.log("================componentDidMount===========================")
const {reduxActions} = this.props;
reduxActions.getTypeDatas();
}
render() {
const {dataTypes} = this.props;
const {testData} = this.props;
const {reduxActions} = this.props;
const {dispatch} = this.props;
console.log("-----------------render---------------------")
return (
<ThemeProvider theme={appTheme}>
<ScrollView
automaticallyAdjustContentInsets={false}
horizontal={false}
>
{
dataTypes.typeList.map((item, i) => {
return (
<ListItem
key={i}
leftAvatar={{source: {uri: "https://s3.amazonaws.com/uifaces/faces/twitter/ladylexy/128.jpg"}}}
title={item.name}
subtitle={item.code}
/>
);
})
}
<View style={{flexDirection: 'row'}}>
<Button title="add Data" onPress={() => {
this._addData()
}}/>
<Button title="reload Data" onPress={() => {
this._reloadData()
}}/>
<Button title="reload DB Data" onPress={() => {
this._reloadDatabaseData()
}}/>
</View>
<Button title="Sagas DB Data" onPress={() => {
this._sagasData()
}}/>
<Button title="test" onPress={() => {
//reduxActions.exec_increment();
dispatch(exec_increment());
}}/>
<Counter
value={testData.testOther}
onIncrement={() => dispatch({type:'INCREMENT'})}
onDecrement={() => dispatch({type:'DECREMENT'})}
onIncrementIfOdd={() => dispatch({type:'INCREMENT_IF_ODD'})}
onIncrementAsync={() => dispatch({type:'INCREMENT_ASYNC'})}
/>
</ScrollView>
</ThemeProvider>
);
}
}
const mapStateToProps = (state) => {
return {
dataTypes:state.data,
testData:state.test,
};
}
const mapDispatchToProps = dispatch => {
const reduxActions = bindActionCreators(reduxAction, dispatch);
return {
reduxActions,
dispatch,
}
}
export default connect(
mapStateToProps,
mapDispatchToProps
)(ReduxWay)
//export default ReduxWay;
<file_sep>/app/component/common.js
import React from 'react';
import {Dimensions, StyleSheet,Platform,StatusBar} from "react-native";
const SCREEN_WIDTH = Dimensions.get('window').width;
const SCREEN_HEIGHT = Dimensions.get('window').height;
const BG_IMAGE = require('./assets/images/bg_screen1.jpg');
const OS = Platform.OS;
const ios = (OS == 'ios');
const android = (OS == 'android');
const isIPhoneX = (ios && height == 812 && width == 375);
const statusBarHeight = (ios ? (isIPhoneX ? 44 : 20) : StatusBar.currentHeight);
const STYLES = StyleSheet.create({
container: {
flex: 1,
},
bgImage: {
flex: 1,
top: 0,
left: 0,
width: SCREEN_WIDTH * 0.8,
height: SCREEN_HEIGHT,
justifyContent: 'center',
alignItems: 'center',
},
loginView: {
marginTop: 150,
backgroundColor: 'transparent',
width: 250,
height: 400,
},
loginTitle: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
},
travelText: {
color: 'white',
fontSize: 30,
fontFamily: 'bold',
},
plusText: {
color: 'white',
fontSize: 30,
fontFamily: 'regular',
},
loginInput: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
},
footerView: {
marginTop: 20,
flex: 0.5,
justifyContent: 'center',
alignItems: 'center',
},
});
const common = {
screen: {
screen_width: SCREEN_WIDTH,
screen_height: SCREEN_WIDTH,
statusBarHeight: statusBarHeight,
bgImage: BG_IMAGE
},
style: STYLES,
devices: {
ios: ios,
android: android,
isIPhoneX: isIPhoneX,
}
}
export default common;
<file_sep>/readme.txt
React-Native 学习框架
功能说明:
1、列举了react-native-elements的组件
2、react-native基本组件的使用
3、集成react-redux中间件的使用
4、集成react-saga中间件的使用
5、部分例子依赖于公司后台报销系统的api
6、程序中用到了SplashScreen,需要了解SplashScreen的配置
7、其它组件:PopoverMenu、VectorIcons、LinearGradient、RNGestureHandler等
使用方法;
下载后运行 yarn install更新依赖
<file_sep>/app/reducers/testReducers.js
const initialTypeState = {
loading: false,
testList: [],
testOther:1,
};
const testData = (state = initialTypeState, action) => {
console.log("------------------testReducers--------------------")
switch (action.type) {
case 'Test_ADD':{
console.log("------------------testReducers------add--------------")
let newDatas = state.typeList;
newDatas.push({name:'test',code:'test01'});
return Object.assign({},state,{loading:true,typeList:newDatas});
}
case 'Test_GET_DATA':{
console.log("------------------testReducers------GET_DATA--------------")
let newDatas = [{name: 'redux_1', code: 'test01'}, {name: 'redux_2', code: 'test2'}];
return Object.assign({},state,{loading:true,typeList:newDatas});
}
case 'Test_GET_DATABASE_DATA':{
console.log("------------------testReducers------GET_DATABASE_DATA--------------")
let newDatas = action.dataTypes;
return Object.assign({},state,{loading:true,typeList:newDatas});
}
case 'Test_REFRESH_DATA':{
console.log("------------------testReducers------REFRESH_DATA--------------")
let newDatas = action.dataTypes;
console.log(newDatas);
return Object.assign({},state,{loading:true,typeList:newDatas});
}
case 'INCREMENT':{
console.log("------------------testReducers------INCREMENT--------------")
let newValue = state.testOther;
newValue = newValue+1;
return Object.assign({},state,{testOther:newValue})
}
case 'DECREMENT': {
let newValue = state.testOther;
newValue = newValue - 1;
return Object.assign({}, state, {testOther: newValue})
}
default:
console.log("------------------testReducers------default--------------")
return state;
}
}
export default testData;
<file_sep>/app/component/mainHeader.js
import React from 'react';
import {Avatar, Header, SearchBar} from "react-native-elements";
import RNPopover from 'react-native-popover-menu'
import Icon from "react-native-vector-icons/FontAwesome";
import {StyleSheet} from 'react-native';
import common from './common';
const dummySearchBarProps = {
showLoading: false,
onFocus: () => console.log('focus'),
//onBlur: () => console.log('blur'),
//onCancel: () => console.log('cancel'),
//onClearText: () => console.log('cleared'),
//onChangeText: text => console.log('text:', text),
};
class UserAvatar extends React.Component {
constructor(props) {
super(props);
this.state = {
Touchable: Avatar
};
}
_onPress = (ref) => {
let copy = <Icon name="copy" size={30} color="#000000" family={"FontAwesome"}/>;
let paste = <Icon name="paste" size={30} color="#000000" family={"FontAwesome"}/>;
let share = <Icon name="share" size={30} color="#000000" family={"FontAwesome"}/>;
let menus = [
{
//label: "Editing",
menus: [
{
label: "Copy",
icon: copy
},
{
label: "Paste",
icon: paste
}
]
},
{
//label: "Other",
menus: [
{
label: "Share",
icon: share
}
]
},
{
// label: "ttt",
menus: [
{
label: "Share me please"
}
]
}
]
RNPopover.Show(ref, {
menus: menus,
onDone: selection => {
console.log("selected item index: " + selection);
},
onCancel: () => {
console.log("popover canceled");
}
});
}
render() {
return (
<Avatar rounded onPress={() => {
this._onPress(this)
}} overlayContainerStyle={{backgroundColor: '#336655'}} icon={{name: 'user', color:'red', type: 'entypo'}}
{...this.props}
/>
);
}
}
class LeftMenu extends React.Component {
render() {
const navigation = this.props.navigation;
return (
<Icon
name='navicon' size={30} family={"FontAwesome"} color='#fff' onPress={() => {
console.log('open left menu...................')
navigation.openDrawer();
}}/>
)
}
}
class mainHeader extends React.Component {
state = {
search: '',
};
updateSearch = search => {
this.setState({search});
};
_onPopMenu = (ref) => {
let copy = <Icon name="copy" size={30} color="#000000" family={"FontAwesome"}/>;
let paste = <Icon name="paste" size={30} color="#000000" family={"FontAwesome"}/>;
let share = <Icon name="share" size={30} color="#000000" family={"FontAwesome"}/>;
let menusAndroid = [
{
label: "Editing",
menus: [
{
label: "Copy",
icon: copy
},
{
label: "Paste",
icon: paste
}
]
},
{
label: "Other",
menus: [
{
label: "Share",
icon: share
}
]
},
{
label: "",
menus: [
{
label: "Share me please"
}
]
}
]
let menus = menusAndroid;
// if (Platform.OS === 'android') {
// menus = menusAndroid;
// } else if (Platform.OS === 'ios') {
// menus = meunsIOS;
// }
console.log("-------------2---------------------------")
console.log(menus);
console.log(ref)
RNPopover.Show(ref, {
menus: menus, onDone: selection => {
console.log("selected item index: " + selection);
}, onCancel: () => {
console.log("popover canceled");
}, tintColor: "#888888", textColor: "#FFFFFF"
});
};
_onPress = (ref) => {
this._onPopMenu(ref);
}
render() {
const {search} = this.state;
const navigation = this.props.navigation;
return (<Header containerStyle={{height: 50, paddingTop: 2}}
leftComponent={<LeftMenu navigation={navigation}/>}
centerComponent={<SearchBar containerStyle={styles.containerStyle}
inputContainerStyle={styles.inputContainerStyle}
placeholder="Type Here..." onChangeText={this.updateSearch}
{...dummySearchBarProps} value={search}/>}
rightComponent={<UserAvatar navigation={navigation}/>}
/>);
}
}
export default mainHeader;
const styles = StyleSheet.create({
containerStyle: {
height: 30,
justifyContent: 'center',
width: common.screen.screen_width * 0.8,
borderTopColor: 'transparent',
borderBottomColor: 'transparent',
backgroundColor: 'transparent',
},
inputContainerStyle: {
height: 30,
borderRadius: 50,
borderColor: 'red',
backgroundColor: 'white',
},
container: {
padding: 10,
flexDirection: 'column',
justifyContent: 'space-between',
backgroundColor: 'rgba(0, 0, 0, 0.05)',
}, menuOptions: {
padding: 50,
},
menuTrigger: {
padding: 5,
},
});
<file_sep>/app/component/staticPages/drawer/popmenu.js
import React from 'react';
import {
Platform,
StyleSheet,
Text,
View,
Button,
TouchableHighlight,
ImageBackground
} from "react-native";
import RNPopover from 'react-native-popover-menu'
import Icon from "react-native-vector-icons/FontAwesome";
import {createStackNavigator} from "react-navigation";
class Bottom extends React.Component {
render() {
return (
<View style={styles.container}>
<Button
title={"Bottom Left"}
ref={ref => {
this.ref1 = ref
}}
onPress={() => {
this.props.onPress(this.ref1)
}}
/>
<Button
title={"Bottom Right"}
ref={ref => {
this.ref2 = ref
}}
onPress={() => {
this.props.onPress(this.ref2)
}}
/>
</View>
);
}
}
class Center_Con extends React.Component {
render() {
return (
<View style={styles.container}>
<Button
title={"Center Left"}
ref={ref => {
this.ref1 = ref
}}
onPress={() => {
this.props.onPress(this.ref1)
}}
/>
<Button
title={"Center Center"}
ref={ref => {
this.ref2 = ref
}}
onPress={() => {
this.props.onPress(this.ref2)
}}
/>
<Button
title={"Center Right"}
ref={ref => {
this.ref3 = ref
}}
onPress={() => {
this.props.onPress(this.ref3)
}}
/>
</View>
);
}
}
class Top extends React.Component {
render() {
return (
<View style={styles.container}>
<Button
title={"Top Left"}
ref={ref => {
this.ref1 = ref
}}
onPress={() => {
this.props.onPress(this.ref1)
}}
/>
<Button
title={"Top Right"}
ref={ref => {
this.ref2 = ref
}}
onPress={() => {
this.props.onPress(this.ref2)
}}
/>
</View>
);
}
}
class PopMenu extends React.Component<{}> {
constructor (props) {
super(props)
this.state = {
visible: false
}
}
_onPress = (ref) => {
let copy = <Icon name="copy" size={30} color="#000000" family={"FontAwesome"} />;
let paste = <Icon name="paste" size={30} color="#000000" family={"FontAwesome"} />;
let share = <Icon name="share" size={30} color="#000000" family={"FontAwesome"} />;
let menusAndroid = [
{
label: "Editing",
menus: [
{
label: "Copy",
icon: copy
},
{
label: "Paste",
icon: paste
}
]
},
{
label: "Other",
menus: [
{
label: "Share",
icon: share
}
]
},
{
label: "",
menus: [
{
label: "Share me please"
}
]
}
]
let menus
if (Platform.OS === 'android') {
menus = menusAndroid;
} else if (Platform.OS === 'ios') {
// menus = meunsIOS;
}
RNPopover.Show(ref, { menus: menus, onDone: selection => {
console.log("selected item index: " + selection);
}, onCancel: () => {
console.log("popover canceled");
}, tintColor: "#888888", textColor: "#FFFFFF" });
}
_show (ref) {
this.ref = ref
this.setState({
visible: true
})
}
render() {
let copy = <Icon name="copy" size={30} color="#000000" family={"FontAwesome"} />;
let paste = <Icon name="paste" size={30} color="#000000" family={"FontAwesome"} />;
let share = <Icon name="share" size={30} color="#000000" family={"FontAwesome"} />;
let popover;
if (Platform.OS === 'android') {
popover = <RNPopover visible={this.state.visible} reference={this.ref} onDone={(mainMenuSelection, subMenuSelection) => {
console.log("selection: " + mainMenuSelection + ", " + subMenuSelection);
}}>
<RNPopover.Menu label={"Editing"}>
<RNPopover.Menu label={"Copy"} icon={copy} />
<RNPopover.Menu label={"Paste"} icon={paste} />
</RNPopover.Menu>
<RNPopover.Menu>
<RNPopover.Menu label={"Share"} icon={share} />
</RNPopover.Menu>
</RNPopover>;
} else if (Platform.OS === 'ios') {
popover = <RNPopover visible={this.state.visible} reference={this.ref} onDone={(selection) => {
console.log("selection: " + selection);
}} >
<RNPopover.Menu label={"Editing"}>
<RNPopover.Menu label={"Copy"} />
<RNPopover.Menu label={"Paste"} />
<RNPopover.Menu label={"Share"} />
</RNPopover.Menu>
</RNPopover>;
}
return <ImageBackground source={require("../../assets/images/bg_screen1.jpg")} style={styles.backgroundImage}>
<Top style={styles.top} onPress={ref => {
//this._onPress(ref);
this._show(ref);
}} />
<Center_Con style={styles.center} onPress={ref => {
this._onPress(ref);
// this._show(ref);
}} />
<Bottom style={styles.bottom} onPress={ref => {
this._onPress(ref);
// this._show(ref);
}} />
{popover}
</ImageBackground>;
}
}
const PopMenuDrawerItem = createStackNavigator(
{
Playground: {
screen: PopMenu,
navigationOptions: ({ navigation }) => ({
title: '弹出菜单',
headerLeft: (
<Icon
name="menu"
size={30}
type="entypo"
iconStyle={{ paddingLeft: 10 }}
onPress={navigation.toggleDrawer}
/>
),
}),
},
}
);
PopMenuDrawerItem.navigationOptions = {
drawerLabel: '弹出菜单',
drawerIcon: ({ tintColor }) => (
<Icon
name="menu"
size={30}
iconStyle={{
width: 30,
height: 30,
}}
type="material"
color={tintColor}
/>
),
};
export default PopMenuDrawerItem;
const styles = StyleSheet.create({
container: {
flexDirection: "row",
justifyContent: "space-between"
},
backgroundImage: {
flex: 1,
width: null,
height: null,
flexDirection: "column",
justifyContent: "space-between"
},
textStyle: {
color: "#FFFFFF"
},
top: {
flex: 1
},
center: {
flex: 1
},
bottom: {
flex: 1
}
});
| e04ae2418e43b86f9df73f22b7d0842f7002bf21 | [
"JavaScript",
"Text"
] | 12 | JavaScript | jackgit1214/RNStudy | d4713a13684920f5f392ca797a9c0e17663b94ad | 1d2670875efc2cc5a9674011a56c718e2d2f044d |
refs/heads/master | <repo_name>rafaelffilho/Memory-Game-in-C<file_sep>/src/search.h
int sequentialsearch(int vet[], int n, int search){
for(int i = 0; i < n; i++) {
if(vet[i] == search)
return i + 1;
}
return 0;
}
int binarysearch(int vet[], int n, int search){
int first = 0;
int last = n - 1;
int middle = (first+last)/2;
while (first <= last) {
if (vet[middle] < search)
first = middle + 1;
else if (vet[middle] == search) {
return middle + 1;
}
else
last = middle - 1;
middle = (first + last)/2;
}
if (first > last)
return 0;
}
<file_sep>/src/main.c
#include <gtk/gtk.h>
#include <stdio.h>
#include <string.h>
#include <stdbool.h>
#include <stdlib.h>
#include <time.h>
#include "search.h"
GtkWidget *see_credits;
GtkWidget *window_game;
GtkWidget *window;
GtkWidget *window_n_par;
GtkWidget *window_par;
GtkWidget *window_nickname;
GtkWidget *window_congrats;
GtkWidget *window_highscores;
GtkWidget *window_instructions;
GtkWidget *score;
GtkWidget *player;
GtkWidget *highScore1;
GtkWidget *highScore2;
GtkWidget *highScore3;
GtkWidget *highScore4;
GtkWidget *highScore5;
GtkWidget *instructions;
GtkEntry *nick_entry;
GtkEntryBuffer *entry_buffer;
GtkImage *images[30];
GtkBuilder *builder;
FILE *file_highscores;
int scores[5];
int card_temp = 0;
int points = 0;
int imageIndex;
int matrix[6][5][2];
int hits = 0;
char nickname[30];
char nicks[5][30];
void read_highscores ();
void link_images ();
void load_images ();
void load_image_back ();
void fill_matrix ();
void on_btn_ok_n_par_clicked ();
void on_btn_ok_par_clicked ();
void on_btn_nickname_ok_clicked ();
void on_btn_congrats_ok_clicked ();
void on_btn_exit_clicked ();
void on_btn_highscores_clicked ();
void on_btn_highscores_close_clicked ();
void on_btn_instructions_close_clicked ();
void on_btn_playgame_exit_clicked ();
void on_btn_instructions_clicked ();
void on_window_nickname_destroy ();
void on_window_congrats_destroy ();
void on_window_highscores_destroy ();
int main(int argc, char *argv[]) {
srand(time(NULL));
file_highscores = fopen(".highscores.txt", "r+");
read_highscores ();
gtk_init(&argc, &argv);
builder = gtk_builder_new();
gtk_builder_add_from_file (builder, "src/window_main.glade.xml", NULL);
window = GTK_WIDGET(gtk_builder_get_object(builder, "window_main"));
gtk_builder_connect_signals(builder, NULL);
see_credits = GTK_WIDGET(gtk_builder_get_object(builder, "window_credits"));
window_game = GTK_WIDGET(gtk_builder_get_object(builder, "window_playgame"));
window_par = GTK_WIDGET(gtk_builder_get_object(builder, "window_confirm_par"));
window_n_par = GTK_WIDGET(gtk_builder_get_object(builder, "window_confirm_n_par"));
window_congrats = GTK_WIDGET(gtk_builder_get_object(builder, "window_congrats"));
window_nickname = GTK_WIDGET(gtk_builder_get_object(builder, "window_nickname"));
window_highscores = GTK_WIDGET(gtk_builder_get_object(builder, "window_highscores"));
window_instructions = GTK_WIDGET(gtk_builder_get_object(builder, "window_instructions"));
nick_entry = GTK_WIDGET(gtk_builder_get_object(builder, "txt_nick_entry"));
score = GTK_WIDGET(gtk_builder_get_object(builder, "lbl_score"));
player = GTK_WIDGET(gtk_builder_get_object(builder, "lbl_player"));
highScore1 = GTK_WIDGET(gtk_builder_get_object(builder, "lbl_highscore_1"));
highScore2 = GTK_WIDGET(gtk_builder_get_object(builder, "lbl_highscore_2"));
highScore3 = GTK_WIDGET(gtk_builder_get_object(builder, "lbl_highscore_3"));
highScore4 = GTK_WIDGET(gtk_builder_get_object(builder, "lbl_highscore_4"));
highScore5 = GTK_WIDGET(gtk_builder_get_object(builder, "lbl_highscore_5"));
instructions = GTK_WIDGET(gtk_builder_get_object(builder, "lbl_instructions"));
gtk_widget_hide_on_delete(window_game);
gtk_widget_hide_on_delete(window_nickname);
link_images();
g_object_unref(builder);
gtk_widget_show(window);
gtk_main();
//Limpa o arquivo .highscores.txt
system("> .highscores.txt");
//Escreve o ranking no arquivo .highscores.txt
for(int i = 0; i < 5; i++){
char print[50];
char temp[3];
strcpy(print, "echo \"");
sprintf(temp, "%d", scores[i]);
strcat(print, temp);
strcat(print, "\t");
strcat(print, nicks[i]);
strcat(print, "\"");
strcat(print, " >> .highscores.txt");
system(print);
}
fclose(file_highscores);
return 0;
}
//Le o ranking atual no arquivo .highscores.txt
void read_highscores () {
int temp1 = 0;
int temp2 = 0;
char temp[50];
int j;
int i;
int key;
for(int i = 0; i < 10; i++){
fscanf(file_highscores, "%s", temp);
if (i % 2 == 0){
scores[temp1] = atoi(temp);
//printf("%d\t", scores[temp1]);
temp1++;
} else {
strcpy(nicks[temp2], temp);
//printf("%s\n", nicks[temp2]);
temp2++;
}
}
for(j = 1; j < 5; j++) {
key = scores[j];
i = j - 1;
strcpy(temp, nicks[j]);
while(i >= 0 && scores[i] < key) {
scores[i + 1] = scores[i];
strcpy(nicks[i + 1], nicks[i]);
i = i - 1;
}
strcpy(nicks[i + 1], temp);
scores[i + 1] = key;
}
}
//Linkando as imagens
void link_images () {
for (int i = 0; i < 30; i++) {
char imageIndex[30];
char buffer[3];
strcpy(imageIndex, "image");
sprintf(buffer, "%d", i+1);
strcat(imageIndex, buffer);
images[i] = GTK_IMAGE(gtk_builder_get_object(builder, imageIndex));
}
}
//Carregando as imagens
void load_images () {
int k = 0;
for(int i = 0; i < 6; i++){
for(int q = 0; q < 5; q++){
if(matrix[i][q][1] == 0){
char imageName[30];
char buffer[3];
strcpy(imageName, "src/images/card_");
sprintf(buffer, "%d", matrix[i][q][0]);
strcat(imageName, buffer);
strcat(imageName, ".png");
gtk_image_set_from_file(images[k], imageName);
} else {
gtk_image_set_from_file(images[k], "src/images/card_back.png");
}
k++;
}
}
}
void fill_matrix () {
int temp;
int numbers[15];
bool exit = false;
int i = 0;
while(1){
if(i == 15)
break;
temp = rand() % 52 + 1;
if(!sequentialsearch(numbers, 15, temp)){
numbers[i] = temp;
i++;
}
}
for(int i = 0; i < 6; i++){
for(int q = 0; q < 5; q++){
matrix[i][q][0] = NULL;
matrix[i][q][1] = 1;
}
}
for(int i = 0; i < 15; i++){
while(1){
int position = rand() % 30;
if(matrix[position / 5][position % 5][0] == NULL){
matrix[position / 5][position % 5][0] = numbers[i];
break;
}
}
exit = false;
while(1){
int position = rand() % 30;
if(matrix[position / 5][position % 5][0] == NULL){
matrix[position / 5][position % 5][0] = numbers[i];
break;
}
}
exit = false;
}
}
void on_btn_instructions_clicked () {
gtk_widget_show(window_instructions);
gtk_label_set_text(GTK_LABEL(instructions), "O jogo da memória é um clássico jogo formado por peças que apresentam uma figura em um dos lados. \nCada figura se repete em duas peças diferentes. Para começar o jogo, as peças são postas com as figuras voltadas\n para baixo, para que não possam ser vistas. O jogador deve, na sua vez, virar duas peças.\n Caso as figuras sejam iguais, ele recolhe consigo esse par.\n Se forem peças diferentes, estas são viradas novamente, e a vez é passada ao participante seguinte.\n Ganha o jogo quem tiver descoberto mais pares, quando todos eles tiverem sido recolhidos.\n");
}
void on_btn_instructions_close_clicked () {
gtk_widget_hide(window_instructions);
}
//Fechar janela no X
void on_window_main_destroy() {
gtk_main_quit();
}
void on_window_nickname_destroy () {
gtk_main_quit();
}
void on_window_congrats_destroy () {
on_btn_congrats_ok_clicked();
}
void on_window_confirm_n_par_destroy () {
on_btn_ok_n_par_clicked();
}
void on_window_confirm_par_destroy () {
on_btn_ok_par_clicked();
}
void on_window_playgame_destroy () {
gtk_widget_show(window);
gtk_widget_hide(window_game);
}
void on_btn_playgame_exit_clicked () {
gtk_widget_show(window);
gtk_widget_hide(window_game);
}
void on_btn_highscores_clicked () {
char temp[50];
char buffer[3];
strcpy(temp, "#1\t|\t");
sprintf(buffer, "%d", scores[0]);
strcat(temp, buffer);
strcat(temp, "\t\t|\t");
strcat(temp, nicks[0]);
gtk_label_set_text(GTK_LABEL(highScore1), temp);
strcpy(temp, "#2\t|\t");
sprintf(buffer, "%d", scores[1]);
strcat(temp, buffer);
strcat(temp, "\t\t|\t");
strcat(temp, nicks[1]);
gtk_label_set_text(GTK_LABEL(highScore2), temp);
strcpy(temp, "#3\t|\t");
sprintf(buffer, "%d", scores[2]);
strcat(temp, buffer);
strcat(temp, "\t\t|\t");
strcat(temp, nicks[2]);
gtk_label_set_text(GTK_LABEL(highScore3), temp);
strcpy(temp, "#4\t|\t");
sprintf(buffer, "%d", scores[3]);
strcat(temp, buffer);
strcat(temp, "\t\t|\t");
strcat(temp, nicks[3]);
gtk_label_set_text(GTK_LABEL(highScore4), temp);
strcpy(temp, "#5\t|\t");
sprintf(buffer, "%d", scores[4]);
strcat(temp, buffer);
strcat(temp, "\t\t|\t");
strcat(temp, nicks[4]);
gtk_label_set_text(GTK_LABEL(highScore5), temp);
gtk_widget_show(window_highscores);
}
void on_btn_highscores_close_clicked () {
gtk_widget_hide(window_highscores);
}
void on_btn_exit_clicked () {
gtk_main_quit();
}
void on_btn_congrats_ok_clicked () {
int j;
int i;
int key;
char temp[30];
if (points > scores[4]) {
scores[4] = points;
strcpy(nicks[4], nickname);
}
for(j = 1; j < 5; j++) {
key = scores[j];
i = j - 1;
strcpy(temp, nicks[j]);
while(i >= 0 && scores[i] < key) {
scores[i + 1] = scores[i];
strcpy(nicks[i + 1], nicks[i]);
i = i - 1;
}
strcpy(nicks[i + 1], temp);
scores[i + 1] = key;
}
gtk_widget_show(window);
gtk_widget_hide(window_congrats);
gtk_widget_hide(window_game);
}
void on_btn_playgame_clicked () {
fill_matrix(matrix);
load_images(matrix);
points = 0;
gtk_widget_show(GTK_WIDGET(window_nickname));
}
void on_btn_creditos_clicked () {
gtk_dialog_run(GTK_DIALOG(see_credits));
gtk_widget_hide(see_credits);
}
void on_btn_nickname_ok_clicked () {
char temp[50];
points = 0;
entry_buffer = gtk_entry_get_buffer (nick_entry);
strcpy(nickname, gtk_entry_buffer_get_text (entry_buffer));
strcpy(temp, "Jogador: ");
strcat(temp, nickname);
gtk_label_set_text(GTK_LABEL(player), temp);
gtk_label_set_text(GTK_LABEL(score), "Pontos: 0");
gtk_widget_show(GTK_WIDGET(window_game));
gtk_widget_hide(window_nickname);
}
void on_btn_ok_n_par_clicked () {
points--;
char points_c[30];
char buffer_lbl[30];
strcpy(points_c, "Pontos: ");
sprintf(buffer_lbl, "%d", points);
strcat(points_c, buffer_lbl);
gtk_label_set_text(GTK_LABEL(score), points_c);
gtk_image_set_from_file(images[imageIndex], "src/images/card_back.png");
gtk_image_set_from_file(images[card_temp-1], "src/images/card_back.png");
card_temp = 0;
gtk_widget_hide(window_n_par);
}
void on_btn_ok_par_clicked () {
hits++;
points++;
char points_c[30];
char buffer_lbl[30];
strcpy(points_c, "Pontos: ");
sprintf(buffer_lbl, "%d", points);
strcat(points_c, buffer_lbl);
gtk_label_set_text(GTK_LABEL(score), points_c);
if (hits >= 15) {
gtk_widget_show(window_congrats);
}
gtk_widget_hide(window_par);
}
void on_btn_1_clicked () {
imageIndex = 0;
if (matrix[imageIndex/5][imageIndex%5][1] == 0) {
return;
}
if (card_temp == imageIndex+1) {
return;
}
matrix[imageIndex/5][imageIndex%5][1] = 0;
if (card_temp == 0) {
char imageName[30];
char buffer[3];
strcpy(imageName, "src/images/card_");
sprintf(buffer, "%d", matrix[imageIndex/5][imageIndex%5][0]);
strcat(imageName, buffer);
strcat(imageName, ".png");
gtk_image_set_from_file(images[imageIndex], imageName);
card_temp = imageIndex+1;
} else {
char imageName[30];
char buffer[3];
matrix[(card_temp-1)/5][(card_temp-1)%5][1] = 0;
strcpy(imageName, "src/images/card_");
sprintf(buffer, "%d", matrix[imageIndex/5][imageIndex%5][0]);
strcat(imageName, buffer);
strcat(imageName, ".png");
gtk_image_set_from_file(images[imageIndex], imageName);
if (matrix[imageIndex/5][imageIndex%5][0] == matrix[(card_temp-1)/5][(card_temp-1)%5][0]) {
gtk_widget_show(GTK_WIDGET(window_par));
card_temp = 0;
} else {
gtk_widget_show(GTK_WIDGET(window_n_par));
matrix[imageIndex/5][imageIndex%5][1] = 1;
matrix[(card_temp-1)/5][(card_temp-1)%5][1] = 1;
}
}
}
void on_btn_2_clicked () {
imageIndex = 1;
if (matrix[imageIndex/5][imageIndex%5][1] == 0) {
return;
}
if (card_temp == imageIndex+1) {
return;
}
matrix[imageIndex/5][imageIndex%5][1] = 0;
if (card_temp == 0) {
char imageName[30];
char buffer[3];
strcpy(imageName, "src/images/card_");
sprintf(buffer, "%d", matrix[imageIndex/5][imageIndex%5][0]);
strcat(imageName, buffer);
strcat(imageName, ".png");
gtk_image_set_from_file(images[imageIndex], imageName);
card_temp = imageIndex+1;
} else {
char imageName[30];
char buffer[3];
matrix[(card_temp-1)/5][(card_temp-1)%5][1] = 0;
strcpy(imageName, "src/images/card_");
sprintf(buffer, "%d", matrix[imageIndex/5][imageIndex%5][0]);
strcat(imageName, buffer);
strcat(imageName, ".png");
gtk_image_set_from_file(images[imageIndex], imageName);
if (matrix[imageIndex/5][imageIndex%5][0] == matrix[(card_temp-1)/5][(card_temp-1)%5][0]) {
gtk_widget_show(GTK_WIDGET(window_par));
card_temp = 0;
} else {
gtk_widget_show(GTK_WIDGET(window_n_par));
matrix[imageIndex/5][imageIndex%5][1] = 1;
matrix[(card_temp-1)/5][(card_temp-1)%5][1] = 1;
}
}
}
void on_btn_3_clicked () {
imageIndex = 2;
if (matrix[imageIndex/5][imageIndex%5][1] == 0) {
return;
}
if (card_temp == imageIndex+1) {
return;
}
matrix[imageIndex/5][imageIndex%5][1] = 0;
if (card_temp == 0) {
char imageName[30];
char buffer[3];
strcpy(imageName, "src/images/card_");
sprintf(buffer, "%d", matrix[imageIndex/5][imageIndex%5][0]);
strcat(imageName, buffer);
strcat(imageName, ".png");
gtk_image_set_from_file(images[imageIndex], imageName);
card_temp = imageIndex+1;
} else {
char imageName[30];
char buffer[3];
matrix[(card_temp-1)/5][(card_temp-1)%5][1] = 0;
strcpy(imageName, "src/images/card_");
sprintf(buffer, "%d", matrix[imageIndex/5][imageIndex%5][0]);
strcat(imageName, buffer);
strcat(imageName, ".png");
gtk_image_set_from_file(images[imageIndex], imageName);
if (matrix[imageIndex/5][imageIndex%5][0] == matrix[(card_temp-1)/5][(card_temp-1)%5][0]) {
gtk_widget_show(GTK_WIDGET(window_par));
card_temp = 0;
} else {
gtk_widget_show(GTK_WIDGET(window_n_par));
matrix[imageIndex/5][imageIndex%5][1] = 1;
matrix[(card_temp-1)/5][(card_temp-1)%5][1] = 1;
}
}
}
void on_btn_4_clicked () {
imageIndex = 3;
if (matrix[imageIndex/5][imageIndex%5][1] == 0) {
return;
}
if (card_temp == imageIndex+1) {
return;
}
matrix[imageIndex/5][imageIndex%5][1] = 0;
if (card_temp == 0) {
char imageName[30];
char buffer[3];
strcpy(imageName, "src/images/card_");
sprintf(buffer, "%d", matrix[imageIndex/5][imageIndex%5][0]);
strcat(imageName, buffer);
strcat(imageName, ".png");
gtk_image_set_from_file(images[imageIndex], imageName);
card_temp = imageIndex+1;
} else {
char imageName[30];
char buffer[3];
matrix[(card_temp-1)/5][(card_temp-1)%5][1] = 0;
strcpy(imageName, "src/images/card_");
sprintf(buffer, "%d", matrix[imageIndex/5][imageIndex%5][0]);
strcat(imageName, buffer);
strcat(imageName, ".png");
gtk_image_set_from_file(images[imageIndex], imageName);
if (matrix[imageIndex/5][imageIndex%5][0] == matrix[(card_temp-1)/5][(card_temp-1)%5][0]) {
gtk_widget_show(GTK_WIDGET(window_par));
card_temp = 0;
} else {
gtk_widget_show(GTK_WIDGET(window_n_par));
matrix[imageIndex/5][imageIndex%5][1] = 1;
matrix[(card_temp-1)/5][(card_temp-1)%5][1] = 1;
}
}
}
void on_btn_5_clicked () {
imageIndex = 4;
if (matrix[imageIndex/5][imageIndex%5][1] == 0) {
return;
}
if (card_temp == imageIndex+1) {
return;
}
matrix[imageIndex/5][imageIndex%5][1] = 0;
if (card_temp == 0) {
char imageName[30];
char buffer[3];
strcpy(imageName, "src/images/card_");
sprintf(buffer, "%d", matrix[imageIndex/5][imageIndex%5][0]);
strcat(imageName, buffer);
strcat(imageName, ".png");
gtk_image_set_from_file(images[imageIndex], imageName);
card_temp = imageIndex+1;
} else {
char imageName[30];
char buffer[3];
matrix[(card_temp-1)/5][(card_temp-1)%5][1] = 0;
strcpy(imageName, "src/images/card_");
sprintf(buffer, "%d", matrix[imageIndex/5][imageIndex%5][0]);
strcat(imageName, buffer);
strcat(imageName, ".png");
gtk_image_set_from_file(images[imageIndex], imageName);
if (matrix[imageIndex/5][imageIndex%5][0] == matrix[(card_temp-1)/5][(card_temp-1)%5][0]) {
gtk_widget_show(GTK_WIDGET(window_par));
card_temp = 0;
} else {
gtk_widget_show(GTK_WIDGET(window_n_par));
matrix[imageIndex/5][imageIndex%5][1] = 1;
matrix[(card_temp-1)/5][(card_temp-1)%5][1] = 1;
}
}
}
void on_btn_6_clicked () {
imageIndex = 5;
if (matrix[imageIndex/5][imageIndex%5][1] == 0) {
return;
}
if (card_temp == imageIndex+1) {
return;
}
matrix[imageIndex/5][imageIndex%5][1] = 0;
if (card_temp == 0) {
char imageName[30];
char buffer[3];
strcpy(imageName, "src/images/card_");
sprintf(buffer, "%d", matrix[imageIndex/5][imageIndex%5][0]);
strcat(imageName, buffer);
strcat(imageName, ".png");
gtk_image_set_from_file(images[imageIndex], imageName);
card_temp = imageIndex+1;
} else {
char imageName[30];
char buffer[3];
matrix[(card_temp-1)/5][(card_temp-1)%5][1] = 0;
strcpy(imageName, "src/images/card_");
sprintf(buffer, "%d", matrix[imageIndex/5][imageIndex%5][0]);
strcat(imageName, buffer);
strcat(imageName, ".png");
gtk_image_set_from_file(images[imageIndex], imageName);
if (matrix[imageIndex/5][imageIndex%5][0] == matrix[(card_temp-1)/5][(card_temp-1)%5][0]) {
gtk_widget_show(GTK_WIDGET(window_par));
card_temp = 0;
} else {
gtk_widget_show(GTK_WIDGET(window_n_par));
matrix[imageIndex/5][imageIndex%5][1] = 1;
matrix[(card_temp-1)/5][(card_temp-1)%5][1] = 1;
}
}
}
void on_btn_7_clicked () {
imageIndex = 6;
if (matrix[imageIndex/5][imageIndex%5][1] == 0) {
return;
}
if (card_temp == imageIndex+1) {
return;
}
matrix[imageIndex/5][imageIndex%5][1] = 0;
if (card_temp == 0) {
char imageName[30];
char buffer[3];
strcpy(imageName, "src/images/card_");
sprintf(buffer, "%d", matrix[imageIndex/5][imageIndex%5][0]);
strcat(imageName, buffer);
strcat(imageName, ".png");
gtk_image_set_from_file(images[imageIndex], imageName);
card_temp = imageIndex+1;
} else {
char imageName[30];
char buffer[3];
matrix[(card_temp-1)/5][(card_temp-1)%5][1] = 0;
strcpy(imageName, "src/images/card_");
sprintf(buffer, "%d", matrix[imageIndex/5][imageIndex%5][0]);
strcat(imageName, buffer);
strcat(imageName, ".png");
gtk_image_set_from_file(images[imageIndex], imageName);
if (matrix[imageIndex/5][imageIndex%5][0] == matrix[(card_temp-1)/5][(card_temp-1)%5][0]) {
gtk_widget_show(GTK_WIDGET(window_par));
card_temp = 0;
} else {
gtk_widget_show(GTK_WIDGET(window_n_par));
matrix[imageIndex/5][imageIndex%5][1] = 1;
matrix[(card_temp-1)/5][(card_temp-1)%5][1] = 1;
}
}
}
void on_btn_8_clicked () {
imageIndex = 7;
if (matrix[imageIndex/5][imageIndex%5][1] == 0) {
return;
}
if (card_temp == imageIndex+1) {
return;
}
matrix[imageIndex/5][imageIndex%5][1] = 0;
if (card_temp == 0) {
char imageName[30];
char buffer[3];
strcpy(imageName, "src/images/card_");
sprintf(buffer, "%d", matrix[imageIndex/5][imageIndex%5][0]);
strcat(imageName, buffer);
strcat(imageName, ".png");
gtk_image_set_from_file(images[imageIndex], imageName);
card_temp = imageIndex+1;
} else {
char imageName[30];
char buffer[3];
matrix[(card_temp-1)/5][(card_temp-1)%5][1] = 0;
strcpy(imageName, "src/images/card_");
sprintf(buffer, "%d", matrix[imageIndex/5][imageIndex%5][0]);
strcat(imageName, buffer);
strcat(imageName, ".png");
gtk_image_set_from_file(images[imageIndex], imageName);
if (matrix[imageIndex/5][imageIndex%5][0] == matrix[(card_temp-1)/5][(card_temp-1)%5][0]) {
gtk_widget_show(GTK_WIDGET(window_par));
card_temp = 0;
} else {
gtk_widget_show(GTK_WIDGET(window_n_par));
matrix[imageIndex/5][imageIndex%5][1] = 1;
matrix[(card_temp-1)/5][(card_temp-1)%5][1] = 1;
}
}
}
void on_btn_9_clicked () {
imageIndex = 8;
if (matrix[imageIndex/5][imageIndex%5][1] == 0) {
return;
}
if (card_temp == imageIndex+1) {
return;
}
matrix[imageIndex/5][imageIndex%5][1] = 0;
if (card_temp == 0) {
char imageName[30];
char buffer[3];
strcpy(imageName, "src/images/card_");
sprintf(buffer, "%d", matrix[imageIndex/5][imageIndex%5][0]);
strcat(imageName, buffer);
strcat(imageName, ".png");
gtk_image_set_from_file(images[imageIndex], imageName);
card_temp = imageIndex+1;
} else {
char imageName[30];
char buffer[3];
matrix[(card_temp-1)/5][(card_temp-1)%5][1] = 0;
strcpy(imageName, "src/images/card_");
sprintf(buffer, "%d", matrix[imageIndex/5][imageIndex%5][0]);
strcat(imageName, buffer);
strcat(imageName, ".png");
gtk_image_set_from_file(images[imageIndex], imageName);
if (matrix[imageIndex/5][imageIndex%5][0] == matrix[(card_temp-1)/5][(card_temp-1)%5][0]) {
gtk_widget_show(GTK_WIDGET(window_par));
card_temp = 0;
} else {
gtk_widget_show(GTK_WIDGET(window_n_par));
matrix[imageIndex/5][imageIndex%5][1] = 1;
matrix[(card_temp-1)/5][(card_temp-1)%5][1] = 1;
}
}
}
void on_btn_10_clicked () {
imageIndex = 9;
if (matrix[imageIndex/5][imageIndex%5][1] == 0) {
return;
}
if (card_temp == imageIndex+1) {
return;
}
matrix[imageIndex/5][imageIndex%5][1] = 0;
if (card_temp == 0) {
char imageName[30];
char buffer[3];
strcpy(imageName, "src/images/card_");
sprintf(buffer, "%d", matrix[imageIndex/5][imageIndex%5][0]);
strcat(imageName, buffer);
strcat(imageName, ".png");
gtk_image_set_from_file(images[imageIndex], imageName);
card_temp = imageIndex+1;
} else {
char imageName[30];
char buffer[3];
matrix[(card_temp-1)/5][(card_temp-1)%5][1] = 0;
strcpy(imageName, "src/images/card_");
sprintf(buffer, "%d", matrix[imageIndex/5][imageIndex%5][0]);
strcat(imageName, buffer);
strcat(imageName, ".png");
gtk_image_set_from_file(images[imageIndex], imageName);
if (matrix[imageIndex/5][imageIndex%5][0] == matrix[(card_temp-1)/5][(card_temp-1)%5][0]) {
gtk_widget_show(GTK_WIDGET(window_par));
card_temp = 0;
} else {
gtk_widget_show(GTK_WIDGET(window_n_par));
matrix[imageIndex/5][imageIndex%5][1] = 1;
matrix[(card_temp-1)/5][(card_temp-1)%5][1] = 1;
}
}
}
void on_btn_11_clicked () {
imageIndex = 10;
if (matrix[imageIndex/5][imageIndex%5][1] == 0) {
return;
}
if (card_temp == imageIndex+1) {
return;
}
matrix[imageIndex/5][imageIndex%5][1] = 0;
if (card_temp == 0) {
char imageName[30];
char buffer[3];
strcpy(imageName, "src/images/card_");
sprintf(buffer, "%d", matrix[imageIndex/5][imageIndex%5][0]);
strcat(imageName, buffer);
strcat(imageName, ".png");
gtk_image_set_from_file(images[imageIndex], imageName);
card_temp = imageIndex+1;
} else {
char imageName[30];
char buffer[3];
matrix[(card_temp-1)/5][(card_temp-1)%5][1] = 0;
strcpy(imageName, "src/images/card_");
sprintf(buffer, "%d", matrix[imageIndex/5][imageIndex%5][0]);
strcat(imageName, buffer);
strcat(imageName, ".png");
gtk_image_set_from_file(images[imageIndex], imageName);
if (matrix[imageIndex/5][imageIndex%5][0] == matrix[(card_temp-1)/5][(card_temp-1)%5][0]) {
gtk_widget_show(GTK_WIDGET(window_par));
card_temp = 0;
} else {
gtk_widget_show(GTK_WIDGET(window_n_par));
matrix[imageIndex/5][imageIndex%5][1] = 1;
matrix[(card_temp-1)/5][(card_temp-1)%5][1] = 1;
}
}
}
void on_btn_12_clicked () {
imageIndex = 11;
if (matrix[imageIndex/5][imageIndex%5][1] == 0) {
return;
}
if (card_temp == imageIndex+1) {
return;
}
matrix[imageIndex/5][imageIndex%5][1] = 0;
if (card_temp == 0) {
char imageName[30];
char buffer[3];
strcpy(imageName, "src/images/card_");
sprintf(buffer, "%d", matrix[imageIndex/5][imageIndex%5][0]);
strcat(imageName, buffer);
strcat(imageName, ".png");
gtk_image_set_from_file(images[imageIndex], imageName);
card_temp = imageIndex+1;
} else {
char imageName[30];
char buffer[3];
matrix[(card_temp-1)/5][(card_temp-1)%5][1] = 0;
strcpy(imageName, "src/images/card_");
sprintf(buffer, "%d", matrix[imageIndex/5][imageIndex%5][0]);
strcat(imageName, buffer);
strcat(imageName, ".png");
gtk_image_set_from_file(images[imageIndex], imageName);
if (matrix[imageIndex/5][imageIndex%5][0] == matrix[(card_temp-1)/5][(card_temp-1)%5][0]) {
gtk_widget_show(GTK_WIDGET(window_par));
card_temp = 0;
} else {
gtk_widget_show(GTK_WIDGET(window_n_par));
matrix[imageIndex/5][imageIndex%5][1] = 1;
matrix[(card_temp-1)/5][(card_temp-1)%5][1] = 1;
}
}
}
void on_btn_13_clicked () {
imageIndex = 12;
if (matrix[imageIndex/5][imageIndex%5][1] == 0) {
return;
}
if (card_temp == imageIndex+1) {
return;
}
matrix[imageIndex/5][imageIndex%5][1] = 0;
if (card_temp == 0) {
char imageName[30];
char buffer[3];
strcpy(imageName, "src/images/card_");
sprintf(buffer, "%d", matrix[imageIndex/5][imageIndex%5][0]);
strcat(imageName, buffer);
strcat(imageName, ".png");
gtk_image_set_from_file(images[imageIndex], imageName);
card_temp = imageIndex+1;
} else {
char imageName[30];
char buffer[3];
matrix[(card_temp-1)/5][(card_temp-1)%5][1] = 0;
strcpy(imageName, "src/images/card_");
sprintf(buffer, "%d", matrix[imageIndex/5][imageIndex%5][0]);
strcat(imageName, buffer);
strcat(imageName, ".png");
gtk_image_set_from_file(images[imageIndex], imageName);
if (matrix[imageIndex/5][imageIndex%5][0] == matrix[(card_temp-1)/5][(card_temp-1)%5][0]) {
gtk_widget_show(GTK_WIDGET(window_par));
card_temp = 0;
} else {
gtk_widget_show(GTK_WIDGET(window_n_par));
matrix[imageIndex/5][imageIndex%5][1] = 1;
matrix[(card_temp-1)/5][(card_temp-1)%5][1] = 1;
}
}
}
void on_btn_14_clicked () {
imageIndex = 13;
if (matrix[imageIndex/5][imageIndex%5][1] == 0) {
return;
}
if (card_temp == imageIndex+1) {
return;
}
matrix[imageIndex/5][imageIndex%5][1] = 0;
if (card_temp == 0) {
char imageName[30];
char buffer[3];
strcpy(imageName, "src/images/card_");
sprintf(buffer, "%d", matrix[imageIndex/5][imageIndex%5][0]);
strcat(imageName, buffer);
strcat(imageName, ".png");
gtk_image_set_from_file(images[imageIndex], imageName);
card_temp = imageIndex+1;
} else {
char imageName[30];
char buffer[3];
matrix[(card_temp-1)/5][(card_temp-1)%5][1] = 0;
strcpy(imageName, "src/images/card_");
sprintf(buffer, "%d", matrix[imageIndex/5][imageIndex%5][0]);
strcat(imageName, buffer);
strcat(imageName, ".png");
gtk_image_set_from_file(images[imageIndex], imageName);
if (matrix[imageIndex/5][imageIndex%5][0] == matrix[(card_temp-1)/5][(card_temp-1)%5][0]) {
gtk_widget_show(GTK_WIDGET(window_par));
card_temp = 0;
} else {
gtk_widget_show(GTK_WIDGET(window_n_par));
matrix[imageIndex/5][imageIndex%5][1] = 1;
matrix[(card_temp-1)/5][(card_temp-1)%5][1] = 1;
}
}
}
void on_btn_15_clicked () {
imageIndex = 14;
if (matrix[imageIndex/5][imageIndex%5][1] == 0) {
return;
}
if (card_temp == imageIndex+1) {
return;
}
matrix[imageIndex/5][imageIndex%5][1] = 0;
if (card_temp == 0) {
char imageName[30];
char buffer[3];
strcpy(imageName, "src/images/card_");
sprintf(buffer, "%d", matrix[imageIndex/5][imageIndex%5][0]);
strcat(imageName, buffer);
strcat(imageName, ".png");
gtk_image_set_from_file(images[imageIndex], imageName);
card_temp = imageIndex+1;
} else {
char imageName[30];
char buffer[3];
matrix[(card_temp-1)/5][(card_temp-1)%5][1] = 0;
strcpy(imageName, "src/images/card_");
sprintf(buffer, "%d", matrix[imageIndex/5][imageIndex%5][0]);
strcat(imageName, buffer);
strcat(imageName, ".png");
gtk_image_set_from_file(images[imageIndex], imageName);
if (matrix[imageIndex/5][imageIndex%5][0] == matrix[(card_temp-1)/5][(card_temp-1)%5][0]) {
gtk_widget_show(GTK_WIDGET(window_par));
card_temp = 0;
} else {
gtk_widget_show(GTK_WIDGET(window_n_par));
matrix[imageIndex/5][imageIndex%5][1] = 1;
matrix[(card_temp-1)/5][(card_temp-1)%5][1] = 1;
}
}
}
void on_btn_16_clicked () {
imageIndex = 15;
if (matrix[imageIndex/5][imageIndex%5][1] == 0) {
return;
}
if (card_temp == imageIndex+1) {
return;
}
matrix[imageIndex/5][imageIndex%5][1] = 0;
if (card_temp == 0) {
char imageName[30];
char buffer[3];
strcpy(imageName, "src/images/card_");
sprintf(buffer, "%d", matrix[imageIndex/5][imageIndex%5][0]);
strcat(imageName, buffer);
strcat(imageName, ".png");
gtk_image_set_from_file(images[imageIndex], imageName);
card_temp = imageIndex+1;
} else {
char imageName[30];
char buffer[3];
matrix[(card_temp-1)/5][(card_temp-1)%5][1] = 0;
strcpy(imageName, "src/images/card_");
sprintf(buffer, "%d", matrix[imageIndex/5][imageIndex%5][0]);
strcat(imageName, buffer);
strcat(imageName, ".png");
gtk_image_set_from_file(images[imageIndex], imageName);
if (matrix[imageIndex/5][imageIndex%5][0] == matrix[(card_temp-1)/5][(card_temp-1)%5][0]) {
gtk_widget_show(GTK_WIDGET(window_par));
card_temp = 0;
} else {
gtk_widget_show(GTK_WIDGET(window_n_par));
matrix[imageIndex/5][imageIndex%5][1] = 1;
matrix[(card_temp-1)/5][(card_temp-1)%5][1] = 1;
}
}
}
void on_btn_17_clicked () {
imageIndex = 16;
if (matrix[imageIndex/5][imageIndex%5][1] == 0) {
return;
}
if (card_temp == imageIndex+1) {
return;
}
matrix[imageIndex/5][imageIndex%5][1] = 0;
if (card_temp == 0) {
char imageName[30];
char buffer[3];
strcpy(imageName, "src/images/card_");
sprintf(buffer, "%d", matrix[imageIndex/5][imageIndex%5][0]);
strcat(imageName, buffer);
strcat(imageName, ".png");
gtk_image_set_from_file(images[imageIndex], imageName);
card_temp = imageIndex+1;
} else {
char imageName[30];
char buffer[3];
matrix[(card_temp-1)/5][(card_temp-1)%5][1] = 0;
strcpy(imageName, "src/images/card_");
sprintf(buffer, "%d", matrix[imageIndex/5][imageIndex%5][0]);
strcat(imageName, buffer);
strcat(imageName, ".png");
gtk_image_set_from_file(images[imageIndex], imageName);
if (matrix[imageIndex/5][imageIndex%5][0] == matrix[(card_temp-1)/5][(card_temp-1)%5][0]) {
gtk_widget_show(GTK_WIDGET(window_par));
card_temp = 0;
} else {
gtk_widget_show(GTK_WIDGET(window_n_par));
matrix[imageIndex/5][imageIndex%5][1] = 1;
matrix[(card_temp-1)/5][(card_temp-1)%5][1] = 1;
}
}
}
void on_btn_18_clicked () {
imageIndex = 17;
if (matrix[imageIndex/5][imageIndex%5][1] == 0) {
return;
}
if (card_temp == imageIndex+1) {
return;
}
matrix[imageIndex/5][imageIndex%5][1] = 0;
if (card_temp == 0) {
char imageName[30];
char buffer[3];
strcpy(imageName, "src/images/card_");
sprintf(buffer, "%d", matrix[imageIndex/5][imageIndex%5][0]);
strcat(imageName, buffer);
strcat(imageName, ".png");
gtk_image_set_from_file(images[imageIndex], imageName);
card_temp = imageIndex+1;
} else {
char imageName[30];
char buffer[3];
matrix[(card_temp-1)/5][(card_temp-1)%5][1] = 0;
strcpy(imageName, "src/images/card_");
sprintf(buffer, "%d", matrix[imageIndex/5][imageIndex%5][0]);
strcat(imageName, buffer);
strcat(imageName, ".png");
gtk_image_set_from_file(images[imageIndex], imageName);
if (matrix[imageIndex/5][imageIndex%5][0] == matrix[(card_temp-1)/5][(card_temp-1)%5][0]) {
gtk_widget_show(GTK_WIDGET(window_par));
card_temp = 0;
} else {
gtk_widget_show(GTK_WIDGET(window_n_par));
matrix[imageIndex/5][imageIndex%5][1] = 1;
matrix[(card_temp-1)/5][(card_temp-1)%5][1] = 1;
}
}
}
void on_btn_19_clicked () {
imageIndex = 18;
if (matrix[imageIndex/5][imageIndex%5][1] == 0) {
return;
}
if (card_temp == imageIndex+1) {
return;
}
matrix[imageIndex/5][imageIndex%5][1] = 0;
if (card_temp == 0) {
char imageName[30];
char buffer[3];
strcpy(imageName, "src/images/card_");
sprintf(buffer, "%d", matrix[imageIndex/5][imageIndex%5][0]);
strcat(imageName, buffer);
strcat(imageName, ".png");
gtk_image_set_from_file(images[imageIndex], imageName);
card_temp = imageIndex+1;
} else {
char imageName[30];
char buffer[3];
matrix[(card_temp-1)/5][(card_temp-1)%5][1] = 0;
strcpy(imageName, "src/images/card_");
sprintf(buffer, "%d", matrix[imageIndex/5][imageIndex%5][0]);
strcat(imageName, buffer);
strcat(imageName, ".png");
gtk_image_set_from_file(images[imageIndex], imageName);
if (matrix[imageIndex/5][imageIndex%5][0] == matrix[(card_temp-1)/5][(card_temp-1)%5][0]) {
gtk_widget_show(GTK_WIDGET(window_par));
card_temp = 0;
} else {
gtk_widget_show(GTK_WIDGET(window_n_par));
matrix[imageIndex/5][imageIndex%5][1] = 1;
matrix[(card_temp-1)/5][(card_temp-1)%5][1] = 1;
}
}
}
void on_btn_20_clicked () {
imageIndex = 19;
if (matrix[imageIndex/5][imageIndex%5][1] == 0) {
return;
}
if (card_temp == imageIndex+1) {
return;
}
matrix[imageIndex/5][imageIndex%5][1] = 0;
if (card_temp == 0) {
char imageName[30];
char buffer[3];
strcpy(imageName, "src/images/card_");
sprintf(buffer, "%d", matrix[imageIndex/5][imageIndex%5][0]);
strcat(imageName, buffer);
strcat(imageName, ".png");
gtk_image_set_from_file(images[imageIndex], imageName);
card_temp = imageIndex+1;
} else {
char imageName[30];
char buffer[3];
matrix[(card_temp-1)/5][(card_temp-1)%5][1] = 0;
strcpy(imageName, "src/images/card_");
sprintf(buffer, "%d", matrix[imageIndex/5][imageIndex%5][0]);
strcat(imageName, buffer);
strcat(imageName, ".png");
gtk_image_set_from_file(images[imageIndex], imageName);
if (matrix[imageIndex/5][imageIndex%5][0] == matrix[(card_temp-1)/5][(card_temp-1)%5][0]) {
gtk_widget_show(GTK_WIDGET(window_par));
card_temp = 0;
} else {
gtk_widget_show(GTK_WIDGET(window_n_par));
matrix[imageIndex/5][imageIndex%5][1] = 1;
matrix[(card_temp-1)/5][(card_temp-1)%5][1] = 1;
}
}
}
void on_btn_21_clicked () {
imageIndex = 20;
if (matrix[imageIndex/5][imageIndex%5][1] == 0) {
return;
}
if (card_temp == imageIndex+1) {
return;
}
matrix[imageIndex/5][imageIndex%5][1] = 0;
if (card_temp == 0) {
char imageName[30];
char buffer[3];
strcpy(imageName, "src/images/card_");
sprintf(buffer, "%d", matrix[imageIndex/5][imageIndex%5][0]);
strcat(imageName, buffer);
strcat(imageName, ".png");
gtk_image_set_from_file(images[imageIndex], imageName);
card_temp = imageIndex+1;
} else {
char imageName[30];
char buffer[3];
matrix[(card_temp-1)/5][(card_temp-1)%5][1] = 0;
strcpy(imageName, "src/images/card_");
sprintf(buffer, "%d", matrix[imageIndex/5][imageIndex%5][0]);
strcat(imageName, buffer);
strcat(imageName, ".png");
gtk_image_set_from_file(images[imageIndex], imageName);
if (matrix[imageIndex/5][imageIndex%5][0] == matrix[(card_temp-1)/5][(card_temp-1)%5][0]) {
gtk_widget_show(GTK_WIDGET(window_par));
card_temp = 0;
} else {
gtk_widget_show(GTK_WIDGET(window_n_par));
matrix[imageIndex/5][imageIndex%5][1] = 1;
matrix[(card_temp-1)/5][(card_temp-1)%5][1] = 1;
}
}
}
void on_btn_22_clicked () {
imageIndex = 21;
if (matrix[imageIndex/5][imageIndex%5][1] == 0) {
return;
}
if (card_temp == imageIndex+1) {
return;
}
matrix[imageIndex/5][imageIndex%5][1] = 0;
if (card_temp == 0) {
char imageName[30];
char buffer[3];
strcpy(imageName, "src/images/card_");
sprintf(buffer, "%d", matrix[imageIndex/5][imageIndex%5][0]);
strcat(imageName, buffer);
strcat(imageName, ".png");
gtk_image_set_from_file(images[imageIndex], imageName);
card_temp = imageIndex+1;
} else {
char imageName[30];
char buffer[3];
matrix[(card_temp-1)/5][(card_temp-1)%5][1] = 0;
strcpy(imageName, "src/images/card_");
sprintf(buffer, "%d", matrix[imageIndex/5][imageIndex%5][0]);
strcat(imageName, buffer);
strcat(imageName, ".png");
gtk_image_set_from_file(images[imageIndex], imageName);
if (matrix[imageIndex/5][imageIndex%5][0] == matrix[(card_temp-1)/5][(card_temp-1)%5][0]) {
gtk_widget_show(GTK_WIDGET(window_par));
card_temp = 0;
} else {
gtk_widget_show(GTK_WIDGET(window_n_par));
matrix[imageIndex/5][imageIndex%5][1] = 1;
matrix[(card_temp-1)/5][(card_temp-1)%5][1] = 1;
}
}
}
void on_btn_23_clicked () {
imageIndex = 22;
if (matrix[imageIndex/5][imageIndex%5][1] == 0) {
return;
}
if (card_temp == imageIndex+1) {
return;
}
matrix[imageIndex/5][imageIndex%5][1] = 0;
if (card_temp == 0) {
char imageName[30];
char buffer[3];
strcpy(imageName, "src/images/card_");
sprintf(buffer, "%d", matrix[imageIndex/5][imageIndex%5][0]);
strcat(imageName, buffer);
strcat(imageName, ".png");
gtk_image_set_from_file(images[imageIndex], imageName);
card_temp = imageIndex+1;
} else {
char imageName[30];
char buffer[3];
matrix[(card_temp-1)/5][(card_temp-1)%5][1] = 0;
strcpy(imageName, "src/images/card_");
sprintf(buffer, "%d", matrix[imageIndex/5][imageIndex%5][0]);
strcat(imageName, buffer);
strcat(imageName, ".png");
gtk_image_set_from_file(images[imageIndex], imageName);
if (matrix[imageIndex/5][imageIndex%5][0] == matrix[(card_temp-1)/5][(card_temp-1)%5][0]) {
gtk_widget_show(GTK_WIDGET(window_par));
card_temp = 0;
} else {
gtk_widget_show(GTK_WIDGET(window_n_par));
matrix[imageIndex/5][imageIndex%5][1] = 1;
matrix[(card_temp-1)/5][(card_temp-1)%5][1] = 1;
}
}
}
void on_btn_24_clicked () {
imageIndex = 23;
if (matrix[imageIndex/5][imageIndex%5][1] == 0) {
return;
}
if (card_temp == imageIndex+1) {
return;
}
matrix[imageIndex/5][imageIndex%5][1] = 0;
if (card_temp == 0) {
char imageName[30];
char buffer[3];
strcpy(imageName, "src/images/card_");
sprintf(buffer, "%d", matrix[imageIndex/5][imageIndex%5][0]);
strcat(imageName, buffer);
strcat(imageName, ".png");
gtk_image_set_from_file(images[imageIndex], imageName);
card_temp = imageIndex+1;
} else {
char imageName[30];
char buffer[3];
matrix[(card_temp-1)/5][(card_temp-1)%5][1] = 0;
strcpy(imageName, "src/images/card_");
sprintf(buffer, "%d", matrix[imageIndex/5][imageIndex%5][0]);
strcat(imageName, buffer);
strcat(imageName, ".png");
gtk_image_set_from_file(images[imageIndex], imageName);
if (matrix[imageIndex/5][imageIndex%5][0] == matrix[(card_temp-1)/5][(card_temp-1)%5][0]) {
gtk_widget_show(GTK_WIDGET(window_par));
card_temp = 0;
} else {
gtk_widget_show(GTK_WIDGET(window_n_par));
matrix[imageIndex/5][imageIndex%5][1] = 1;
matrix[(card_temp-1)/5][(card_temp-1)%5][1] = 1;
}
}
}
void on_btn_25_clicked () {
imageIndex = 24;
if (matrix[imageIndex/5][imageIndex%5][1] == 0) {
return;
}
if (card_temp == imageIndex+1) {
return;
}
matrix[imageIndex/5][imageIndex%5][1] = 0;
if (card_temp == 0) {
char imageName[30];
char buffer[3];
strcpy(imageName, "src/images/card_");
sprintf(buffer, "%d", matrix[imageIndex/5][imageIndex%5][0]);
strcat(imageName, buffer);
strcat(imageName, ".png");
gtk_image_set_from_file(images[imageIndex], imageName);
card_temp = imageIndex+1;
} else {
char imageName[30];
char buffer[3];
matrix[(card_temp-1)/5][(card_temp-1)%5][1] = 0;
strcpy(imageName, "src/images/card_");
sprintf(buffer, "%d", matrix[imageIndex/5][imageIndex%5][0]);
strcat(imageName, buffer);
strcat(imageName, ".png");
gtk_image_set_from_file(images[imageIndex], imageName);
if (matrix[imageIndex/5][imageIndex%5][0] == matrix[(card_temp-1)/5][(card_temp-1)%5][0]) {
gtk_widget_show(GTK_WIDGET(window_par));
card_temp = 0;
} else {
gtk_widget_show(GTK_WIDGET(window_n_par));
matrix[imageIndex/5][imageIndex%5][1] = 1;
matrix[(card_temp-1)/5][(card_temp-1)%5][1] = 1;
}
}
}
void on_btn_26_clicked () {
imageIndex = 25;
if (matrix[imageIndex/5][imageIndex%5][1] == 0) {
return;
}
if (card_temp == imageIndex+1) {
return;
}
matrix[imageIndex/5][imageIndex%5][1] = 0;
if (card_temp == 0) {
char imageName[30];
char buffer[3];
strcpy(imageName, "src/images/card_");
sprintf(buffer, "%d", matrix[imageIndex/5][imageIndex%5][0]);
strcat(imageName, buffer);
strcat(imageName, ".png");
gtk_image_set_from_file(images[imageIndex], imageName);
card_temp = imageIndex+1;
} else {
char imageName[30];
char buffer[3];
matrix[(card_temp-1)/5][(card_temp-1)%5][1] = 0;
strcpy(imageName, "src/images/card_");
sprintf(buffer, "%d", matrix[imageIndex/5][imageIndex%5][0]);
strcat(imageName, buffer);
strcat(imageName, ".png");
gtk_image_set_from_file(images[imageIndex], imageName);
if (matrix[imageIndex/5][imageIndex%5][0] == matrix[(card_temp-1)/5][(card_temp-1)%5][0]) {
gtk_widget_show(GTK_WIDGET(window_par));
card_temp = 0;
} else {
gtk_widget_show(GTK_WIDGET(window_n_par));
matrix[imageIndex/5][imageIndex%5][1] = 1;
matrix[(card_temp-1)/5][(card_temp-1)%5][1] = 1;
}
}
}
void on_btn_27_clicked () {
imageIndex = 26;
if (matrix[imageIndex/5][imageIndex%5][1] == 0) {
return;
}
if (card_temp == imageIndex+1) {
return;
}
matrix[imageIndex/5][imageIndex%5][1] = 0;
if (card_temp == 0) {
char imageName[30];
char buffer[3];
strcpy(imageName, "src/images/card_");
sprintf(buffer, "%d", matrix[imageIndex/5][imageIndex%5][0]);
strcat(imageName, buffer);
strcat(imageName, ".png");
gtk_image_set_from_file(images[imageIndex], imageName);
card_temp = imageIndex+1;
} else {
char imageName[30];
char buffer[3];
matrix[(card_temp-1)/5][(card_temp-1)%5][1] = 0;
strcpy(imageName, "src/images/card_");
sprintf(buffer, "%d", matrix[imageIndex/5][imageIndex%5][0]);
strcat(imageName, buffer);
strcat(imageName, ".png");
gtk_image_set_from_file(images[imageIndex], imageName);
if (matrix[imageIndex/5][imageIndex%5][0] == matrix[(card_temp-1)/5][(card_temp-1)%5][0]) {
gtk_widget_show(GTK_WIDGET(window_par));
card_temp = 0;
} else {
gtk_widget_show(GTK_WIDGET(window_n_par));
matrix[imageIndex/5][imageIndex%5][1] = 1;
matrix[(card_temp-1)/5][(card_temp-1)%5][1] = 1;
}
}
}
void on_btn_28_clicked () {
imageIndex = 27;
if (matrix[imageIndex/5][imageIndex%5][1] == 0) {
return;
}
if (card_temp == imageIndex+1) {
return;
}
matrix[imageIndex/5][imageIndex%5][1] = 0;
if (card_temp == 0) {
char imageName[30];
char buffer[3];
strcpy(imageName, "src/images/card_");
sprintf(buffer, "%d", matrix[imageIndex/5][imageIndex%5][0]);
strcat(imageName, buffer);
strcat(imageName, ".png");
gtk_image_set_from_file(images[imageIndex], imageName);
card_temp = imageIndex+1;
} else {
char imageName[30];
char buffer[3];
matrix[(card_temp-1)/5][(card_temp-1)%5][1] = 0;
strcpy(imageName, "src/images/card_");
sprintf(buffer, "%d", matrix[imageIndex/5][imageIndex%5][0]);
strcat(imageName, buffer);
strcat(imageName, ".png");
gtk_image_set_from_file(images[imageIndex], imageName);
if (matrix[imageIndex/5][imageIndex%5][0] == matrix[(card_temp-1)/5][(card_temp-1)%5][0]) {
gtk_widget_show(GTK_WIDGET(window_par));
card_temp = 0;
} else {
gtk_widget_show(GTK_WIDGET(window_n_par));
matrix[imageIndex/5][imageIndex%5][1] = 1;
matrix[(card_temp-1)/5][(card_temp-1)%5][1] = 1;
}
}
}
void on_btn_29_clicked () {
imageIndex = 28;
if (matrix[imageIndex/5][imageIndex%5][1] == 0) {
return;
}
if (card_temp == imageIndex+1) {
return;
}
matrix[imageIndex/5][imageIndex%5][1] = 0;
if (card_temp == 0) {
char imageName[30];
char buffer[3];
strcpy(imageName, "src/images/card_");
sprintf(buffer, "%d", matrix[imageIndex/5][imageIndex%5][0]);
strcat(imageName, buffer);
strcat(imageName, ".png");
gtk_image_set_from_file(images[imageIndex], imageName);
card_temp = imageIndex+1;
} else {
char imageName[30];
char buffer[3];
matrix[(card_temp-1)/5][(card_temp-1)%5][1] = 0;
strcpy(imageName, "src/images/card_");
sprintf(buffer, "%d", matrix[imageIndex/5][imageIndex%5][0]);
strcat(imageName, buffer);
strcat(imageName, ".png");
gtk_image_set_from_file(images[imageIndex], imageName);
if (matrix[imageIndex/5][imageIndex%5][0] == matrix[(card_temp-1)/5][(card_temp-1)%5][0]) {
gtk_widget_show(GTK_WIDGET(window_par));
card_temp = 0;
} else {
gtk_widget_show(GTK_WIDGET(window_n_par));
matrix[imageIndex/5][imageIndex%5][1] = 1;
matrix[(card_temp-1)/5][(card_temp-1)%5][1] = 1;
}
}
}
void on_btn_30_clicked () {
imageIndex = 29;
if (matrix[imageIndex/5][imageIndex%5][1] == 0) {
return;
}
if (card_temp == imageIndex+1) {
return;
}
matrix[imageIndex/5][imageIndex%5][1] = 0;
if (card_temp == 0) {
char imageName[30];
char buffer[3];
strcpy(imageName, "src/images/card_");
sprintf(buffer, "%d", matrix[imageIndex/5][imageIndex%5][0]);
strcat(imageName, buffer);
strcat(imageName, ".png");
gtk_image_set_from_file(images[imageIndex], imageName);
card_temp = imageIndex+1;
} else {
char imageName[30];
char buffer[3];
matrix[(card_temp-1)/5][(card_temp-1)%5][1] = 0;
strcpy(imageName, "src/images/card_");
sprintf(buffer, "%d", matrix[imageIndex/5][imageIndex%5][0]);
strcat(imageName, buffer);
strcat(imageName, ".png");
gtk_image_set_from_file(images[imageIndex], imageName);
if (matrix[imageIndex/5][imageIndex%5][0] == matrix[(card_temp-1)/5][(card_temp-1)%5][0]) {
gtk_widget_show(GTK_WIDGET(window_par));
card_temp = 0;
} else {
gtk_widget_show(GTK_WIDGET(window_n_par));
matrix[imageIndex/5][imageIndex%5][1] = 1;
matrix[(card_temp-1)/5][(card_temp-1)%5][1] = 1;
}
}
}<file_sep>/src/makefile
FLAGS=`pkg-config --cflags --libs gtk+-3.0` -rdynamic
all: main.o
gcc -o ../Game main.o $(FLAGS)
main.o: main.c
gcc -c main.c $(FLAGS) -o main.o
clean:
rm -f *.o ../Game
<file_sep>/src/sort.h
void bubblesort(int vet[], int n) {
int i;
int j;
int temp;
int cond = 1;
for (i=n-1; (i >= 1) && (cond == 1); i--) {
cond = 0;
for (j=0; j < i ;j++) {
if (vet[j+1] < vet[j]) {
temp = vet[j];
vet[j] = vet[j+1];
vet[j+1] = temp;
cond = 1;
}
}
}
}
void selectionsort(int vet[], int n) {
int i;
int j;
int min;
for (i = 0; i < (n-1); i++) {
min = i;
for (j = (i+1); j < n; j++) {
if(vet[j] < vet[min]) {
min = j;
}
}
if (i != min) {
int swap = vet[i];
vet[i] = vet[min];
vet[min] = swap;
}
}
}
void insertionsort(int vet[], int n){
int j;
int i;
int key;
for(j = 1; j < n; j++) {
key = vet[j];
i = j - 1;
while(i >= 0 && vet[i] > key) {
vet[i + 1] = vet[i];
i = i - 1;
}
vet[i + 1] = key;
}
} | 697bdefb813d380dc18b74e3d44a96ec32a5cf12 | [
"C",
"Makefile"
] | 4 | C | rafaelffilho/Memory-Game-in-C | 91ac6266a34811f18f6adf3403bc4686c50c147a | c80e0f782e66936198159687486e6e76d89a236e |
refs/heads/master | <file_sep>function mouseOver(){
const beep = new Audio('/_sounds/mouseSound01.mp3')
beep.play()
}
function mouseClick(){
const click = new Audio('/_sounds/mouseSound03.mp3')
click.play()
}
<file_sep>// Configurando o servidor
const express = require("express")
const server = express()
// Configurar o servidor para apresentar arquivos estáticos
server.use(express.static('public'))
// Habilitar body do formulário
server.use(express.urlencoded({ extended: true }))
// Configurando a Template Engine (Nunjucks)
const nunjucks = require("nunjucks")
nunjucks.configure("./", {
express: server,
noCache: true
})
// Configurar a apresentação da página
server.get("/", function(req,res){
return res.render("index.html")
})
// Pegar dados do formulário
server.post("/", function(req, res){
const user = req.body.user
const password = <PASSWORD>
// Se USUÁRIO ou SENHA for igual a vazio
if(user == "" || password == ""){
return res.redirect("/error.html")
}
setTimeout(() => {
return res.redirect("/welcome.html")
}, 2000)
})
// Ligar o servidor permitindo o acesso a porta 3000
server.listen(3000, function(){
console.log("Servidor rodando...")
})
<file_sep>
<h1 align="center">
Login-Form
</h1>
<h1>
<img src="public/_img/introGif.gif">
</h1>
## 📝 Detalhes do conteúdo
Neste projeto, pratiquei técnicas de **front-end** como background animado (efeito zoom), animação de botões e também cliques com efeitos sonoros. Também preparei um servidor bem simples para praticar o **back-end**.
---
## 🚀 Tecnologias utilizadas
- Javascript
- CSS
- Node.js
---
## 📦 Dependências
- [Express](https://github.com/expressjs/express)
- [Nodemon](https://github.com/remy/nodemon)
- [Nunjucks](https://github.com/mozilla/nunjucks)
---
## 📁 Como baixar e rodar o projeto
```bash
# para clonar o repositório
$ git clone https://github.com/DigooDS/Login-Form.git
# para entrar no diretório
$ cd Login-Form
# para instalar as dependências
$ yarn install
# para iniciar o servidor
$ yarn start
```
- Em seguida, acessar dentro do navegador o **"localhost:3000"** para acessar a página principal (index.html)
---
<i>Desenvolvido por RodrigoDS</i> 🤓
| 2249d00e5968b0e095900023343204d8fb8daad2 | [
"JavaScript",
"Markdown"
] | 3 | JavaScript | DigooDS/Login-Form | 8f13180d6bca1a1a2d202ebd2f8fd1d1e789822a | 3221fe1ebb83a3ed3edaec031a1f7c3b7bd722d6 |
refs/heads/main | <repo_name>ziyadloubaris/emsi-devops-1<file_sep>/0x04-https_ssl/0-world_wide_web
#!/usr/bin/env bash
# displays subdomain info
function subinfo {
if [ -z $2 ] ; then
wwwsub="www.$1"
www_rec_type="$(dig $wwwsub | grep -A1 'ANSWER SECTION' | tail -1 | awk '{print $4}')"
www_ip="$(dig $wwwsub | grep -A1 'ANSWER SECTION' | tail -1 | awk '{print $5}')"
echo "The subdomain www is a $www_rec_type record and points to $www_ip"
lb1sub="lb-01.$1"
lb_rec_type="$(dig $lb1sub | grep -A1 'ANSWER SECTION' | tail -1 | awk '{print $4}')"
lb_ip="$(dig $lb1sub | grep -A1 'ANSWER SECTION' | tail -1 | awk '{print $5}')"
echo "The subdomain lb-01 is a $lb_rec_type record and points to $lb_ip"
web1sub="web-01.$1"
web1_rec_type="$(dig $web1sub | grep -A1 'ANSWER SECTION' | tail -1 | awk '{print $4}')"
web1_ip="$(dig $web1sub | grep -A1 'ANSWER SECTION' | tail -1 | awk '{print $5}')"
echo "The subdomain web-01 is a $web1_rec_type record and points to $web1_ip"
web2sub="web-02.$1"
web2_rec_type="$(dig $web2sub | grep -A1 'ANSWER SECTION' | tail -1 | awk '{print $4}')"
web2_ip="$(dig $web2sub | grep -A1 'ANSWER SECTION' | tail -1 | awk '{print $5}')"
echo "The subdomain web-02 is a $web2_rec_type record and points to $web2_ip"
elif [ $# -eq 2 ] ; then
subdomain="$2.$1"
rec_type="$(dig $subdomain | grep -A1 'ANSWER SECTION' | tail -1 | awk '{print $4}')"
ip="$(dig $subdomain | grep -A1 'ANSWER SECTION' | tail -1 | awk '{print $5}')"
echo "The subdomain $2 is a $rec_type record and points to $ip"
fi
}
subinfo $1 $2 | dd75eebb6cbe208970c26b12b7c2c87d180b8902 | [
"Shell"
] | 1 | Shell | ziyadloubaris/emsi-devops-1 | 927e9d6de705e459b63c9f13e46975623c42ea89 | 17a68c9dacdac257db854e895b95f728d2f6ed6a |
refs/heads/master | <file_sep>
import React, { Component } from 'react';
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import desktopUnsplash from '../../public/images/desktopUnsplash.png';
import clock from '../../public/images/clock.png';
import imageBomb from '../../public/images/bomb.png';
import imageTable from '../../public/images/tableGame.png';
import pokeImage from '../../public/images/poke.svg';
import shineImage from '../../public/images/shine.png';
import capgeminiImage from '../../public/images/capgemini.png';
import kickid from '../../public/images/kickid.jpeg';
import iconUnsplash from '../../public/images/iconUnsplash.png';
import iconPlayBomb from '../../public/images/iconPlayBomb.png';
import { MapContainer, TileLayer, Marker, Popup } from 'react-leaflet'
import L from 'leaflet';
const words = ['Full Stack Developer', 'Front-End Developer', 'React Developer', 'React Native Developer'];
let i = 0;
let timer;
class Home extends Component {
constructor(args) {
super(args);
this.state = {
hoverValue: false,
hoverValueProject: false,
hoverValueEmail: false
};
}
componentDidMount() {
this.typingEffect(words, i, timer);
}
typingEffect(words, i, timer) {
let word = words[i].split('');
var loopTyping = () => {
if (word.length > 0) {
document.getElementById('word').innerHTML += word.shift();
} else {
setTimeout(() => { this.deletingEffect(words, i, timer); }, 2000);
return false;
}
timer = setTimeout(loopTyping, 110);
};
loopTyping();
}
deletingEffect(words, i, timer) {
let word = words[i].split('');
var loopDeleting = () => {
if (word.length > 0) {
word.pop();
document.getElementById('word').innerHTML = word.join('');
} else {
if (words.length > (i + 1)) {
i++;
} else {
i = 0;
}
this.typingEffect(words, i, timer);
return false;
}
timer = setTimeout(loopDeleting, 80);
};
loopDeleting();
}
valueOnClick(value) {
switch (value) {
case 'iconGithub':
return window.open('https://github.com/marcosOrdieres', '_blank');
case 'iconLinkedin':
return window.open('https://www.linkedin.com/in/marcosrodriguezordieres/', '_blank');
case 'iconEmail':
return window.location.href = 'mailto:<EMAIL>';
case 'iconPlay':
return window.open('https://play.google.com/store/apps/developer?id=marcosOrdieres', '_blank');
case 'iconPlayShineGoogle':
return window.open('https://play.google.com/store/apps/details?id=com.shinepowered.shineselect', '_blank');
case 'iconPlayShineApple':
return window.open('https://itunes.apple.com/de/app/shine-eco/id1359763626?mt=8', '_blank');
case 'iconPlayKickidWeb':
return window.open('https://www.kickid.com', '_blank');
case 'iconPlayKickidAndroid':
return window.open('https://play.google.com/store/apps/details?id=com.idleague.kickid&pcampaignid=pcampaignidMKT-Other-global-all-co-prtnr-py-PartBadge-Mar2515-1', '_blank');
case 'iconCap':
return window.open('https://www.capgemini.com/', '_blank');
case 'iconPrometeo':
return window.open('http://www.prometeoinnovations.com/', '_blank');
case 'imageTable':
return window.open('https://marcosordieres.github.io/TableJS/', '_blank');
default:
return window.open('https://github.com/marcosOrdieres', '_blank');
}
}
onMouseEnterHandler(value) {
console.log(value);
const valueForHover = document.getElementById(value);
this.setState({ hoverValue: true });
valueForHover.style.opacity = 1;
valueForHover.style.cursor = 'pointer';
}
onMouseLeaveHandler(value) {
const valueForLeaveHover = document.getElementById(value);
this.setState({ hoverValue: false });
valueForLeaveHover.style.opacity = 0.5;
valueForLeaveHover.style.cursor = 'cursor';
}
onMouseEnterHandlerProject(value, image) {
const valueForHover = document.getElementById(value);
if (image === 'imageJobs') {
this.setState({ hoverValueProject: true, [value]: true });
valueForHover.style.opacity = 0.5;
valueForHover.style.cursor = 'pointer';
} else {
valueForHover.style.backgroundColor = '#9b9b9b';
this.setState({ hoverValueProject: true, [value]: true });
valueForHover.style.cursor = 'pointer';
}
}
onMouseLeaveHandlerProject(value, image) {
const valueForLeaveHover = document.getElementById(value);
if (image === 'imageJobs') {
this.setState({ hoverValueProject: false, [value]: false });
valueForLeaveHover.style.opacity = 1;
console.log(this.state);
} else {
this.setState({ hoverValueProject: false, [value]: false });
console.log(this.state);
valueForLeaveHover.style.opacity = 1;
valueForLeaveHover.style.backgroundColor = '#595959';
}
}
onMouseEnterHandlerEmail(value, p) {
const valueForHover = document.getElementById(value);
const valueForHoverP = document.getElementById(p);
this.setState({ hoverValueEmail: true });
valueForHover.style.backgroundColor = 'white';
valueForHoverP.style.color = '#3a6ee8';
valueForHover.style.cursor = 'pointer';
}
onMouseLeaveHandlerEmail(value, p) {
const valueForLeaveHover = document.getElementById(value);
const valueForLeaveHoverP = document.getElementById(p);
this.setState({ hoverValueEmail: false });
valueForLeaveHover.style.backgroundColor = '#3a6ee8';
valueForLeaveHoverP.style.color = 'white';
valueForLeaveHover.style.cursor = 'cursor';
}
renderMarkers(map, maps) {
new maps.Marker({
position: { lat: 52.560103, lng: 13.414957 },
icon: pokeImage,
map
// title: 'Hello World!'
});
}
render() {
// const {products, actions} = this.props;
// const compareProducts = products.filter(product => product.compare);
const position = [52.560103, 13.414957];
const iconPoke = new L.Icon({
iconUrl: require('../../public/images/poke.svg'),
iconAnchor: null,
popupAnchor: null,
shadowUrl: null,
shadowSize: null,
shadowAnchor: null,
iconSize: new L.Point(60, 75),
className: 'leaflet-div-icon'
});
return (
<div>
<div className='home'>
<div id='name' className='flex-column flex-sm-column flex-md-row flex-lg-row flex-xl-row name' onClick={this.valueOnClick.bind(this)} onMouseEnter={this.onMouseEnterHandler.bind(this, 'name')} onMouseLeave={this.onMouseLeaveHandler.bind(this, 'name')}>
<div className='nameInside'>
<h1><NAME></h1>
</div>
<div id='iconsWork' className='iconsWork'>
<div className='iconGithub' id='iconGithub' onClick={this.valueOnClick.bind(this, 'iconGithub')} onMouseEnter={this.onMouseEnterHandler.bind(this, 'iconGithub')} onMouseLeave={this.onMouseLeaveHandler.bind(this, 'iconGithub')}>
<FontAwesomeIcon icon={['fab', 'github']} size='5x' />
</div>
<div className='iconLinkedin' id='iconLinkedin' onClick={this.valueOnClick.bind(this, 'iconLinkedin')} onMouseEnter={this.onMouseEnterHandler.bind(this, 'iconLinkedin')} onMouseLeave={this.onMouseLeaveHandler.bind(this, 'iconLinkedin')}>
<FontAwesomeIcon icon={['fab', 'linkedin']} size='5x' />
</div>
<div className='iconEmail' id='iconEmail' onClick={this.valueOnClick.bind(this, 'iconEmail')} onMouseEnter={this.onMouseEnterHandler.bind(this, 'iconEmail')} onMouseLeave={this.onMouseLeaveHandler.bind(this, 'iconEmail')}>
<FontAwesomeIcon icon='envelope' size='5x' />
</div>
<div className='iconPlay' id='iconPlay' onClick={this.valueOnClick.bind(this, 'iconPlay')} onMouseEnter={this.onMouseEnterHandler.bind(this, 'iconPlay')} onMouseLeave={this.onMouseLeaveHandler.bind(this, 'iconPlay')}>
<FontAwesomeIcon icon={['fab', 'google-play']} size='5x' />
</div>
</div>
</div>
<div className='rowText'>
<div className='col-12'>
<h2 className='middleText'>Hello, I am <strong><p className='nameTitle'>Marcos.</p></strong> And this is my <i>Portfolio</i></h2>
<p id='word' />
{/* Make a component out of this */}
</div>
</div>
</div>
<div className='secondPartText'>
<div className='titleText'>
<p className='secondPartTitle'>But, Who is Marcos?_</p>
</div>
<div className='subtitleText'>
<div className='whoIsMarcosText'>
<h2 className='secondPartSubtitle'>As a <b><b><i>Software Developer</i></b></b> based in Berlin, I am able to produce high quality responsive applications and websites with a exceptional user experience.</h2>
</div>
<div className='whoIsMarcosTextMiddle'>
<div className='whoIsMarcosTextHalfRight'>
<h2 className='secondPartSubtitleSkills'>
It is a pleasure for me coding Javascript with <b><b><i>React</i></b></b> and <b><b><i>React Native (both with Hooks)</i></b></b>, super styled Components,
flavored with <b><b><i>GraphQL</i></b></b>, <b><b><i>React Testing Library</i></b></b> and <b><b><i>Jest</i></b></b>.
</h2>
</div>
<div className='whoIsMarcosTextHalf'>
<h2 className='secondPartSubtitleSkills'>I also enjoy using <b><b><i>NodeJS</i></b></b>, <b><b><i>Typescript</i></b></b>, also <b><b><i>Firebase</i></b></b> and any kind of automation.</h2>
</div>
</div>
<div className='whoIsMarcosTextDown'>
<h2 className='secondPartSubtitle'>In addition to Travel and Surf, I have built some side Projects (some of them are the next) and Packages which you can find</h2>
<br />
<h2
onClick={() => window.open("https://github.com/marcosOrdieres", "_blank")} className='secondPartSubtitleGithub'>in my GitHub.</h2>
</div>
</div>
</div>
<div className='secondPartProjects'>
<div className='titleText'>
<p className='thirdPartTitle'>Hover and Click into my Personal Projects_</p>
</div>
<div className='flex-column flex-sm-row flex-md-row flex-lg-row flex-xl-row secondCol'>
<div onClick={() => window.open("https://github.com/marcosOrdieres/unsplash-react-project", "_blank")} className='backpackerProject' id='backpackerProject'
onMouseEnter={this.onMouseEnterHandlerProject.bind(this, 'backpackerProject')}
onMouseLeave={this.onMouseLeaveHandlerProject.bind(this, 'backpackerProject')}>
{/* {this.state.isPhone ? <div className="rectangleBackpackerProject"></div> : <div className="rectangleBackpackerProject"></div>} */}
<div>
<img alt='' src={iconUnsplash} width='15%' height='15%' />
</div>
{this.state.backpackerProject ?
<div>
<h5 className='colorWhite'>UNSPLASH REACT PROJECT</h5>
<h6 className='colorWhite'>React + Typescript Project</h6>
<p className='colorWhite'>React + Redux small application flavoured with Typescript, Hooks, styled-components, Jest, react-test-component...</p>
<img alt='' onClick={this.valueOnClick.bind(this, 'iconPlay')} src={desktopUnsplash} width='15%' height='15%' />
</div>
:
null
}
</div>
<div onClick={() => window.open("https://github.com/marcosOrdieres/product-list-case-study", "_blank")} className='bombProject' id='bombProject'
onMouseEnter={this.onMouseEnterHandlerProject.bind(this, 'bombProject')}
onMouseLeave={this.onMouseLeaveHandlerProject.bind(this, 'bombProject')}>
<div>
<img alt='' src={imageTable} width='35%' height='70%' />
</div>
{this.state.bombProject ?
<div>
<h5 className='colorWhite'>TABLE PRODUCT LIST</h5>
<h6 className='colorWhite'>React + Typescript Project</h6>
<p className='colorWhite'>Product List with different characteristics to see every detail from the Product you would like to buy.</p>
<img alt='' onClick={this.valueOnClick.bind(this, 'imageTable')} src={imageTable} width='15%' height='15%' />
</div>
:
null
}
</div>
</div>
<div className='flex-column flex-sm-row flex-md-row flex-lg-row flex-xl-row thirdCol'>
<div onClick={() => window.open("https://github.com/marcosOrdieres/time-converter", "_blank")} className='ghostProject' id='ghostProject'
onMouseEnter={this.onMouseEnterHandlerProject.bind(this, 'ghostProject')}
onMouseLeave={this.onMouseLeaveHandlerProject.bind(this, 'ghostProject')}>
<div>
<img alt='' onClick={this.valueOnClick.bind(this, 'iconPlay')} src={clock} width='35%' height='70%' />
</div>
{this.state.ghostProject ?
<div>
<h5 className='colorWhite'>Time Converter</h5>
<h6 className='colorWhite'>npm package made with Javascript</h6>
<p className='colorWhite'>Small Project using TDD and Jest</p>
<img alt='' src={clock} width='15%' height='15%' />
</div>
:
null
}
</div>
<div onClick={() => window.open("https://github.com/marcosOrdieres/feetFat", "_blank")} className='tableProject' id='tableProject'
onMouseEnter={this.onMouseEnterHandlerProject.bind(this, 'tableProject')}
onMouseLeave={this.onMouseLeaveHandlerProject.bind(this, 'tableProject')}>
<div>
<img alt='' onClick={this.valueOnClick.bind(this, 'iconPlay')} src={imageBomb} width='35%' height='70%' />
</div>
{this.state.tableProject ?
<div>
<h5 className='colorWhite'>Fat Foot Challenge</h5>
<h6 className='colorWhite'>React Native Project</h6>
<p className='colorWhite'>Game made in React Native (with Hooks) and Typescript</p>
<img alt='' onClick={this.valueOnClick.bind(this, 'iconPlay')} src={iconPlayBomb} width='15%' height='15%' />
</div>
:
null
}
</div>
</div>
</div>
<div className='experience'>
<div className='textExperience'>
<div className='textExperienceTitle'>
<p className='textExperienceTitleP'>Experience_</p>
</div>
<div className='textExperienceSubtitle'>
<p className='textExperienceSubtitleP'>
The next are the Companies in which I was working in the field of Information Technology as Software Engineer. Currently working in KickID.com, an IT sports Company.
</p>
</div>
</div>
<div className='flex-column flex-sm-column flex-md-row flex-lg-row flex-xl-row photosExperience'>
<div className='photosExperienceFourth' id='photosExperienceFourth'
onMouseEnter={this.onMouseEnterHandlerProject.bind(this, 'photosExperienceFourth', 'imageJobs')}
onMouseLeave={this.onMouseLeaveHandlerProject.bind(this, 'photosExperienceFourth', 'imageJobs')}>
{!this.state.photosExperienceFourth ?
<img alt='' className='imageJobsKickid' id='imageJobsKickid' src={kickid} />
:
<div className='squareJob'>
<p className='titleJob'>Frontend Developer</p>
<p className='subtitleJob'>2 year - Actual</p>
<p className='subtitleJob'>Web and Mobile Development: ReactJS (with Hooks), Typescript, React Native, NodeJS (NestJS), GraphQL, ES2020</p>
<div className='iconJob' id='iconJob'
onClick={this.valueOnClick.bind(this, 'iconJob')}
onMouseEnter={this.onMouseEnterHandler.bind(this, 'iconJob')}
onMouseLeave={this.onMouseLeaveHandler.bind(this, 'iconJob')}>
<div className='iconsShine'>
<div className='iconPlayShineApple' id='iconPlayShineApple'
onClick={this.valueOnClick.bind(this, 'iconPlayKickidWeb')}
onMouseEnter={this.onMouseEnterHandler.bind(this, 'iconPlayShineApple')}
onMouseLeave={this.onMouseLeaveHandler.bind(this, 'iconPlayShineApple')}>
<FontAwesomeIcon icon={['fab', 'chrome']} size='3x' />
</div>
<div className='separator' />
<div className='iconPlayShineGoogle' id='iconPlayShineGoogle'
onClick={this.valueOnClick.bind(this, 'iconPlayKickidAndroid')}
onMouseEnter={this.onMouseEnterHandler.bind(this, 'iconPlayShineGoogle')}
onMouseLeave={this.onMouseLeaveHandler.bind(this, 'iconPlayShineGoogle')}>
<FontAwesomeIcon icon={['fab', 'google-play']} size='3x' />
</div>
</div>
</div>
</div>
}
</div>
<div className='photosExperienceThird' id='photosExperienceThird'
onMouseEnter={this.onMouseEnterHandlerProject.bind(this, 'photosExperienceThird', 'imageJobs')}
onMouseLeave={this.onMouseLeaveHandlerProject.bind(this, 'photosExperienceThird', 'imageJobs')}>
{!this.state.photosExperienceThird ?
<img alt='' className='imageJobsShine' id='imageJobs' src={shineImage} />
:
<div className='squareJob'>
<p className='titleJob'>Full Stack Developer</p>
<p className='subtitleJob'>1 years</p>
<p className='subtitleJob'>Web and Mobile Development: ReactJS, React Native, Redux, Typescript, NodeJS (NestJS and Express), GraphQL, REST, ES6</p>
<div className='iconJob' id='iconJob'
onClick={this.valueOnClick.bind(this, 'iconJob')}
onMouseEnter={this.onMouseEnterHandler.bind(this, 'iconJob')}
onMouseLeave={this.onMouseLeaveHandler.bind(this, 'iconJob')}>
<div className='iconsShine'>
<div className='iconPlayShineApple' id='iconPlayShineApple' onClick={this.valueOnClick.bind(this, 'iconPlayShineApple')} onMouseEnter={this.onMouseEnterHandler.bind(this, 'iconPlayShineApple')} onMouseLeave={this.onMouseLeaveHandler.bind(this, 'iconPlayShineApple')}>
<FontAwesomeIcon icon={['fab', 'apple']} size='3x' />
</div>
<div className='separator' />
<div className='iconPlayShineGoogle' id='iconPlayShineGoogle' onClick={this.valueOnClick.bind(this, 'iconPlayShineGoogle')} onMouseEnter={this.onMouseEnterHandler.bind(this, 'iconPlayShineGoogle')} onMouseLeave={this.onMouseLeaveHandler.bind(this, 'iconPlayShineGoogle')}>
<FontAwesomeIcon icon={['fab', 'google-play']} size='3x' />
</div>
</div>
</div>
</div>
}
</div>
<div className='photosExperienceSecond' id='photosExperienceSecond'
onMouseEnter={this.onMouseEnterHandlerProject.bind(this, 'photosExperienceSecond', 'imageJobs')}
onMouseLeave={this.onMouseLeaveHandlerProject.bind(this, 'photosExperienceSecond', 'imageJobs')}>
{!this.state.photosExperienceSecond ?
<img alt='' className='imageJobsCap' id='imageJobs' src={capgeminiImage} />
:
<div className='squareJob'>
<p className='titleJob'>Intern Full Stack Developer</p>
<p className='subtitleJob'>8 months</p>
<p className='subtitleJob'>Web Development: Javascript, Java, ExtJS</p>
<div className='iconJob' id='iconJob'
onClick={this.valueOnClick.bind(this, 'iconJob')}
onMouseEnter={this.onMouseEnterHandler.bind(this, 'iconJob')}
onMouseLeave={this.onMouseLeaveHandler.bind(this, 'iconJob')}>
<div className='iconPlayShineApple' id='iconCap' onClick={this.valueOnClick.bind(this, 'iconCap')} onMouseEnter={this.onMouseEnterHandler.bind(this, 'iconCap')} onMouseLeave={this.onMouseLeaveHandler.bind(this, 'iconCap')}>
<FontAwesomeIcon icon={['fab', 'chrome']} size='3x' />
</div>
</div>
</div>
}
</div>
</div>
</div>
<div className='contactMe'>
<div className='flex-column flex-sm-column flex-md-row flex-lg-row flex-xl-row contact'>
<div className='contactEmail'>
<div className='contactEmailRectangle' id='contactEmailRectangle'
onClick={this.valueOnClick.bind(this, 'iconEmail')}
onMouseEnter={this.onMouseEnterHandlerEmail.bind(this, 'contactEmailRectangle', 'contactEmailP')}
onMouseLeave={this.onMouseLeaveHandlerEmail.bind(this, 'contactEmailRectangle', 'contactEmailP')}><p className='contactEmailP' id='contactEmailP'>Contact Me</p></div>
</div>
<div className='contactPlace'>
<MapContainer center={position} zoom={13}>
<TileLayer
url='https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png'
attribution='© <a href="http://osm.org/copyright">OpenStreetMap</a> contributors' />
<Marker
icon={iconPoke}
position={position}>
<Popup>
<span>A pretty CSS3 popup. <br /> Easily customizable.</span>
</Popup>
</Marker>
</MapContainer>
</div>
</div>
<div className='footer'>
<div className='footerNameInside'>
<p className='footerName'>© 2020 <NAME>.</p>
</div>
<div id='iconsWorkFooter' className='iconsWorkFooter'>
<div className='iconGithub' id='iconGithub' onClick={this.valueOnClick.bind(this, 'iconGithub')} onMouseEnter={this.onMouseEnterHandler.bind(this, 'iconGithub')} onMouseLeave={this.onMouseLeaveHandler.bind(this, 'iconGithub')}>
<FontAwesomeIcon icon={['fab', 'github']} />
</div>
<div className='iconLinkedin' id='iconLinkedin' onClick={this.valueOnClick.bind(this, 'iconLinkedin')} onMouseEnter={this.onMouseEnterHandler.bind(this, 'iconLinkedin')} onMouseLeave={this.onMouseLeaveHandler.bind(this, 'iconLinkedin')}>
<FontAwesomeIcon icon={['fab', 'linkedin']} size='5px' />
</div>
<div className='iconEmail' id='iconEmail' onClick={this.valueOnClick.bind(this, 'iconEmail')} onMouseEnter={this.onMouseEnterHandler.bind(this, 'iconEmail')} onMouseLeave={this.onMouseLeaveHandler.bind(this, 'iconEmail')}>
<FontAwesomeIcon icon='envelope' size='5px' />
</div>
<div className='iconPlay' id='iconPlay' onClick={this.valueOnClick.bind(this, 'iconPlay')} onMouseEnter={this.onMouseEnterHandler.bind(this, 'iconPlay')} onMouseLeave={this.onMouseLeaveHandler.bind(this, 'iconPlay')}>
<FontAwesomeIcon icon={['fab', 'google-play']} size='5px' />
</div>
</div>
</div>
</div>
</div>
);
}
}
export default Home
<file_sep># Portfolio
www.marcosordieres.com
<file_sep>import React, { Component } from 'react';
import { Route, Switch } from 'react-router-dom';
import { Home } from '../';
import { library } from '@fortawesome/fontawesome-svg-core';
import { faEnvelope, faCircle } from '@fortawesome/free-solid-svg-icons';
import { fab } from '@fortawesome/free-brands-svg-icons';
library.add(fab, faCircle, faEnvelope);
class App extends Component {
render() {
return (
<div className='app'>
<Switch>
<Route exact path='/' component={Home} />
</Switch>
</div>
);
}
}
export default App;
| c623253e8a4f46383010c8a41266723a0f6eee3b | [
"JavaScript",
"Markdown"
] | 3 | JavaScript | marcosOrdieres/portfolio | afdb69cc69c3c38b7939876d7d8cb41fdbc3c982 | a69e4c1c7a4298541e4a518a5bdc7a8e6071dcd6 |
refs/heads/master | <repo_name>ilbidi/project-arrakis<file_sep>/arduino/README.txt
List of devices
---------------
device01 : Arduino nano
- Soil moisture sensor on pin A5
device02 : Arduino uno
- Reostato on pin A0
<file_sep>/arrakis/arrakis.py
# Funzioni di utilita' per project-arrakis
import sqlalchemy
import models
import datetime
from sqlalchemy.orm import sessionmaker
from models.models import Base, SensorType, Sensor, DeviceType, Device, DeviceData
# Base dati
Session = sessionmaker()
session = None
# Funzioni
def parseInput(input, delimiter='|'):
"""Parsing dell'input dalla lettura sensori"""
return input.split(delimiter)
def dictInput(input, delimiter='|'):
if( not input ):
return None
tokens = parseInput(input, delimiter)
if( not tokens ):
return None
if( len(tokens) != 5):
return None
dataRead = dict()
dataRead['device']=tokens[0]
dataRead['deviceType']=tokens[1]
dataRead['sensor']=tokens[2]
dataRead['sensorType']=tokens[3]
dataRead['value']=tokens[4]
return dataRead
def insDataRead(dataRead):
"""Inserimento dei dati a Database
vengono anche insiriti sensori e dispositivi
nel caso non esistessero"""
sensorType = session.query(SensorType).filter_by(code=dataRead['sensorType']).first()
if( sensorType is None ):
sensorType = SensorType(code=dataRead['sensorType'])
session.add(sensorType)
deviceType = session.query(DeviceType).filter_by(code=dataRead['deviceType']).first()
if( deviceType is None ):
deviceType = DeviceType(code=dataRead['deviceType'])
session.add(deviceType)
sensor = session.query(Sensor).filter_by(code=dataRead['sensor']).first()
if( sensor is None ):
sensor = Sensor(code=dataRead['sensor'], sensorType=sensorType)
session.add(sensor)
device = session.query(Device).filter_by(code=dataRead['device']).first()
if( device is None ):
device = Device(code=dataRead['device'], deviceType=deviceType)
device.sensors.append(sensor)
else:
if( not sensor in device.sensors ):
device.sensors.append(sensor)
session.add(device)
deviceData = DeviceData(device=device,\
sensor=sensor,\
value=dataRead['value'],\
datetimeRead=datetime.datetime.utcnow()\
)
session.add(deviceData)
# Commit data
session.commit()
<file_sep>/main.py
# Main program. Per ora non fa nulla se non caricare il sistema di logging
import sys
import logconfig
import arrakis.arrakis
import sqlalchemy
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from models.models import Base, SensorType, Sensor, DeviceType, Device, DeviceData
from arrakis import arrakis
# Get logger
logger = logconfig.logging.getLogger(__name__)
# Configure nrf
from arrakis.nrf24 import NRF24
import time
from time import gmtime, strftime
# other configuration
from arrakis import arrakis
pipes = [[0xf0, 0xf0, 0xf0, 0xf0, 0xe1], [0xf0, 0xf0, 0xf0, 0xf0, 0xd2]]
radio = NRF24()
radio.begin(0, 0,25,18) #set gpio 25 as CE pin
radio.setRetries(15,15)
radio.setPayloadSize(32)
radio.setChannel(0x4c)
radio.setDataRate(NRF24.BR_2MBPS)
radio.setPALevel(NRF24.PA_MAX)
radio.setAutoAck(1)
radio.openWritingPipe(pipes[0])
radio.openReadingPipe(1, pipes[1])
radio.startListening()
radio.stopListening()
radio.printDetails()
radio.startListening()
def main():
# Configure database
engine = create_engine('mysql://root:root@localhost/testsqlalchemy')
arrakis.Session.configure(bind=engine)
arrakis.session = arrakis.Session()
Base.metadata.create_all(engine)
logger.info('Main started. Enter listening sycle')
while True:
logger.debug('Listening cycle')
time.sleep(2)
pipe = [0]
while not radio.available(pipe, True):
time.sleep(1000/1000000.0)
#print 'radio not available'
recv_buffer = []
radio.read(recv_buffer)
out = ''.join(chr(i) for i in recv_buffer)
logger.debug(out)
# write data to db
arrakis.insDataRead(arrakis.dictInput(input=out))
arrakis.session.rollback()
arrakis.session.close()
logger.info('Main ended')
if __name__=='__main__':
main()
<file_sep>/tests/tests.py
# Test suite
import unittest
import sqlalchemy
import models
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from models.models import Base, User
# Test for in memory SQLite
class TestSQLiteMemory(unittest.TestCase):
# Database definition (in memory sqlite)
engine = create_engine('sqlite:///:memory:')
Session = sessionmaker(bind=engine)
session = Session()
def setUp(self):
Base.metadata.create_all(self.engine)
def tearDown(self):
self.session.rollback()
Base.metadata.drop_all(self.engine)
def testCRUD(self):
# Insert user
user1 = User(name='user1', fullname='USER1', password = 'pwd')
self.session.add(user1)
self.session.commit()
# Check if inserted
user = self.session.query(User).filter_by(name='user1').first()
self.assertEquals(user.name, user1.name)
# Check for non insertion
user = self.session.query(User).filter_by(name='userFake').first()
self.assertTrue(user is None)
# Check Update
user = self.session.query(User).filter_by(name='user1').first()
user.password = '<PASSWORD>'
self.session.commit()
userTst = self.session.query(User).filter_by(name='user1').first()
self.assertEquals(userTst.password, '<PASSWORD>')
# Check printout (to see this you have to run nosetest --nocapture
user = self.session.query(User).filter_by(name='user1').first()
print('User = %s'%user)
# Insert a second record and check insertion
user2 = User(name='user2', fullname='USER2', password = 'pwd')
self.session.add(user2)
self.session.commit()
user = self.session.query(User).filter_by(name='user2').first()
self.assertEquals(user.name, user2.name)
# Rollback test
user3 = User(name='user3', fullname='USER3', password = 'pwd')
self.session.add(user3)
self.session.rollback()
user = self.session.query(User).filter_by(name='user3').first()
self.assertTrue(user is None)
# Delete record
user = self.session.query(User).filter_by(name='user2').first()
self.session.delete(user)
self.session.commit()
self.assertTrue(self.session.query(User).filter_by(name='user2').count()==0)
# Test for SQLite on local file
class TestSQLiteOnFile(unittest.TestCase):
# Database definition
engine = create_engine('sqlite:///test.db')
Session = sessionmaker(bind=engine)
session = Session()
def setUp(self):
Base.metadata.create_all(self.engine)
def tearDown(self):
self.session.rollback()
Base.metadata.drop_all(self.engine)
def testCRUD(self):
# Insert user
user1 = User(name='user1', fullname='USER1', password = 'pwd')
self.session.add(user1)
self.session.commit()
# Check if inserted
user = self.session.query(User).filter_by(name='user1').first()
self.assertEquals(user.name, user1.name)
# Check for non insertion
user = self.session.query(User).filter_by(name='userFake').first()
self.assertTrue(user is None)
# Check Update
user = self.session.query(User).filter_by(name='user1').first()
user.password = '<PASSWORD>'
self.session.commit()
userTst = self.session.query(User).filter_by(name='user1').first()
self.assertEquals(userTst.password, '<PASSWORD>')
# Check printout (to see this you have to run nosetest --nocapture
user = self.session.query(User).filter_by(name='user1').first()
print('User = %s'%user)
# Insert a second record and check insertion
user2 = User(name='user2', fullname='USER2', password = 'pwd')
self.session.add(user2)
self.session.commit()
user = self.session.query(User).filter_by(name='user2').first()
self.assertEquals(user.name, user2.name)
# Rollback test
user3 = User(name='user3', fullname='USER3', password = 'pwd')
self.session.add(user3)
self.session.rollback()
user = self.session.query(User).filter_by(name='user3').first()
self.assertTrue(user is None)
# Delete record
user = self.session.query(User).filter_by(name='user2').first()
self.session.delete(user)
self.session.commit()
self.assertTrue(self.session.query(User).filter_by(name='user2').count()==0)
# Test for mysql (tested on localhost with maria db)
class TestMySql(unittest.TestCase):
# Database definition (be sure that the db name already exists in database)
engine = create_engine('mysql://root:root@localhost/testsqlalchemy')
Session = sessionmaker(bind=engine)
session = Session()
def setUp(self):
Base.metadata.create_all(self.engine)
def tearDown(self):
self.session.rollback()
Base.metadata.drop_all(self.engine)
def testCRUD(self):
# Insert user
user1 = User(name='user1', fullname='USER1', password = 'pwd')
self.session.add(user1)
self.session.commit()
# Check if inserted
user = self.session.query(User).filter_by(name='user1').first()
self.assertEquals(user.name, user1.name)
# Check for non insertion
user = self.session.query(User).filter_by(name='userFake').first()
self.assertTrue(user is None)
# Check Update
user = self.session.query(User).filter_by(name='user1').first()
user.password = '<PASSWORD>'
self.session.commit()
userTst = self.session.query(User).filter_by(name='user1').first()
self.assertEquals(userTst.password, '<PASSWORD>')
# Check printout (to see this you have to run nosetest --nocapture
user = self.session.query(User).filter_by(name='user1').first()
print('User = %s'%user)
# Insert a second record and check insertion
user2 = User(name='user2', fullname='USER2', password = 'pwd')
self.session.add(user2)
self.session.commit()
user = self.session.query(User).filter_by(name='user2').first()
self.assertEquals(user.name, user2.name)
# Rollback test
user3 = User(name='user3', fullname='USER3', password = 'pwd')
self.session.add(user3)
self.session.rollback()
user = self.session.query(User).filter_by(name='user3').first()
self.assertTrue(user is None)
# Delete record
user = self.session.query(User).filter_by(name='user2').first()
self.session.delete(user)
self.session.commit()
self.assertTrue(self.session.query(User).filter_by(name='user2').count()==0)
<file_sep>/logconfig.py
# Logging configuration
import sys
import logging
# A basic configuration that sends log to stout
logging.basicConfig(stream=sys.stdout, level=logging.DEBUG, \
format='%(asctime)s %(name)-12s - %(levelname)-8s - %(message)s')
logger = logging.getLogger(__name__)
logger.debug('Log configuration loaded')
<file_sep>/tests/testsDeviceDataCRUD.py
# Test suite
import unittest
import sqlalchemy
import models
import datetime
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from models.models import Base, DeviceData, Device, DeviceType, Sensor, SensorType
# Test for in memory SQLite
class TestSQLiteMemory(unittest.TestCase):
# Database definition (in memory sqlite)
engine = create_engine('sqlite:///:memory:')
Session = sessionmaker(bind=engine)
session = Session()
def setUp(self):
Base.metadata.create_all(self.engine)
def tearDown(self):
self.session.rollback()
Base.metadata.drop_all(self.engine)
def testCRUD(self):
# Insert device type
dd1 = DeviceData(value=10.0, datetimeRead=datetime.datetime.now())
self.session.add(dd1)
self.session.commit()
# Check if inserted
dd = self.session.query(DeviceData).filter_by(value=10.0).first()
self.assertEquals(dd.value, dd1.value)
# Check for non insertion
dd = self.session.query(DeviceData).filter_by(value=99.0).first()
self.assertTrue(dd is None)
# Check Update
dd = self.session.query(DeviceData).filter_by(value=10.0).first()
dd.value = 20.0
self.session.commit()
ddTst = self.session.query(DeviceData).filter_by(value=20.0).first()
self.assertEquals(ddTst.value, 20.0)
# Check printout (to see this you have to run nosetest --nocapture
dd = self.session.query(DeviceData).filter_by(value=20.0).first()
print('DeviceData = %s' % dd)
# Insert a second record and check insertion
dd2 = DeviceData(value=100.0)
self.session.add(dd2)
self.session.commit()
dd = self.session.query(DeviceData).filter_by(value=100.0).first()
self.assertEquals(dd.value, dd2.value)
# Rollback test
dd3 = DeviceData(value=1000.0)
self.session.add(dd3)
self.session.rollback()
dd = self.session.query(DeviceData).filter_by(value=1000.0).first()
self.assertTrue(dd is None)
# Delete record
dd = self.session.query(DeviceData).filter_by(value=100.0).first()
self.session.delete(dd)
self.session.commit()
self.assertTrue(self.session.query(DeviceData).filter_by(value=100.0).count()==0)
# Add to device data data read from a device
sensorType1 = SensorType(code='sensorType1', description='SENSORTYPEDESCR1')
sensorType2 = SensorType(code='sensorType2', description='SENSORTYPEDESCR2')
deviceType1 = DeviceType(code='deviceType1', description='DEVICETYPEDESCR1')
deviceType2 = DeviceType(code='deviceType2', description='DEVICETYPEDESCR2')
sensor11 = Sensor(code='sensor11', description='SENSORDESCR11', sensorType=sensorType1)
sensor12 = Sensor(code='sensor12', description='SENSORDESCR12', sensorType=sensorType2)
sensor21 = Sensor(code='sensor21', description='SENSORDESCR21', sensorType=sensorType1)
sensor22 = Sensor(code='sensor22', description='SENSORDESCR22', sensorType=sensorType2)
device1 = Device(code='device1', description='DEVICEDESCR1',\
deviceType=deviceType1)
device1.sensors.append(sensor11)
device1.sensors.append(sensor12)
device2 = Device(code='device2', description='DEVICEDESCR2',\
deviceType=deviceType2)
device2.sensors.append(sensor21)
device2.sensors.append(sensor22)
deviceData11=DeviceData(datetimeRead=datetime.datetime.now(),\
value=11.0,\
device=device1)
deviceData12=DeviceData(datetimeRead=datetime.datetime.now(),\
value=12.0,\
device=device1)
deviceData21=DeviceData(datetimeRead=datetime.datetime.now(),\
value=21.0,\
device=device2,)
deviceData22=DeviceData(datetimeRead=datetime.datetime.now(),\
value=22.0,\
device=device2)
self.session.add(deviceData11)
self.session.add(deviceData12)
self.session.add(deviceData21)
self.session.add(deviceData22)
self.session.commit()
# Print data inserted
devicedatas = self.session.query(DeviceData)
for dd in devicedatas:
print('Device Data : %s'%dd)
print('\tDevice : %s'%dd.device)
if dd.device is not None and dd.device.sensors is not None:
for sens in dd.device.sensors:
print('\t\tSensor : %s'%sens)
# Test for SQLite on local file
class TestSQLiteOnFile(unittest.TestCase):
# Database definition
engine = create_engine('sqlite:///test.db')
Session = sessionmaker(bind=engine)
session = Session()
def setUp(self):
Base.metadata.create_all(self.engine)
def tearDown(self):
self.session.rollback()
Base.metadata.drop_all(self.engine)
def testCRUD(self):
# Insert device type
dd1 = DeviceData(value=10.0, datetimeRead=datetime.datetime.now())
self.session.add(dd1)
self.session.commit()
# Check if inserted
dd = self.session.query(DeviceData).filter_by(value=10.0).first()
self.assertEquals(dd.value, dd1.value)
# Check for non insertion
dd = self.session.query(DeviceData).filter_by(value=99.0).first()
self.assertTrue(dd is None)
# Check Update
dd = self.session.query(DeviceData).filter_by(value=10.0).first()
dd.value = 20.0
self.session.commit()
ddTst = self.session.query(DeviceData).filter_by(value=20.0).first()
self.assertEquals(ddTst.value, 20.0)
# Check printout (to see this you have to run nosetest --nocapture
dd = self.session.query(DeviceData).filter_by(value=20.0).first()
print('DeviceData = %s' % dd)
# Insert a second record and check insertion
dd2 = DeviceData(value=100.0)
self.session.add(dd2)
self.session.commit()
dd = self.session.query(DeviceData).filter_by(value=100.0).first()
self.assertEquals(dd.value, dd2.value)
# Rollback test
dd3 = DeviceData(value=1000.0)
self.session.add(dd3)
self.session.rollback()
dd = self.session.query(DeviceData).filter_by(value=1000.0).first()
self.assertTrue(dd is None)
# Delete record
dd = self.session.query(DeviceData).filter_by(value=100.0).first()
self.session.delete(dd)
self.session.commit()
self.assertTrue(self.session.query(DeviceData).filter_by(value=100.0).count()==0)
# Add to device data data read from a device
sensorType1 = SensorType(code='sensorType1', description='SENSORTYPEDESCR1')
sensorType2 = SensorType(code='sensorType2', description='SENSORTYPEDESCR2')
deviceType1 = DeviceType(code='deviceType1', description='DEVICETYPEDESCR1')
deviceType2 = DeviceType(code='deviceType2', description='DEVICETYPEDESCR2')
sensor11 = Sensor(code='sensor11', description='SENSORDESCR11', sensorType=sensorType1)
sensor12 = Sensor(code='sensor12', description='SENSORDESCR12', sensorType=sensorType2)
sensor21 = Sensor(code='sensor21', description='SENSORDESCR21', sensorType=sensorType1)
sensor22 = Sensor(code='sensor22', description='SENSORDESCR22', sensorType=sensorType2)
device1 = Device(code='device1', description='DEVICEDESCR1',\
deviceType=deviceType1)
device1.sensors.append(sensor11)
device1.sensors.append(sensor12)
device2 = Device(code='device2', description='DEVICEDESCR2',\
deviceType=deviceType2)
device2.sensors.append(sensor21)
device2.sensors.append(sensor22)
deviceData11=DeviceData(datetimeRead=datetime.datetime.now(),\
value=11.0,\
device=device1)
deviceData12=DeviceData(datetimeRead=datetime.datetime.now(),\
value=12.0,\
device=device1)
deviceData21=DeviceData(datetimeRead=datetime.datetime.now(),\
value=21.0,\
device=device2,)
deviceData22=DeviceData(datetimeRead=datetime.datetime.now(),\
value=22.0,\
device=device2)
self.session.add(deviceData11)
self.session.add(deviceData12)
self.session.add(deviceData21)
self.session.add(deviceData22)
self.session.commit()
# Print data inserted
devicedatas = self.session.query(DeviceData)
for dd in devicedatas:
print('Device Data : %s'%dd)
print('\tDevice : %s'%dd.device)
if dd.device is not None and dd.device.sensors is not None:
for sens in dd.device.sensors:
print('\t\tSensor : %s'%sens)
# Test for mysql (tested on localhost with maria db)
class TestMySql(unittest.TestCase):
# Database definition (be sure that the db name already exists in database)
engine = create_engine('mysql://root:root@localhost/testsqlalchemy')
Session = sessionmaker(bind=engine)
session = Session()
def setUp(self):
Base.metadata.create_all(self.engine)
def tearDown(self):
self.session.rollback()
Base.metadata.drop_all(self.engine)
def testCRUD(self):
# Insert device type
dd1 = DeviceData(value=10.0, datetimeRead=datetime.datetime.now())
self.session.add(dd1)
self.session.commit()
# Check if inserted
dd = self.session.query(DeviceData).filter_by(value=10.0).first()
self.assertEquals(dd.value, dd1.value)
# Check for non insertion
dd = self.session.query(DeviceData).filter_by(value=99.0).first()
self.assertTrue(dd is None)
# Check Update
dd = self.session.query(DeviceData).filter_by(value=10.0).first()
dd.value = 20.0
self.session.commit()
ddTst = self.session.query(DeviceData).filter_by(value=20.0).first()
self.assertEquals(ddTst.value, 20.0)
# Check printout (to see this you have to run nosetest --nocapture
dd = self.session.query(DeviceData).filter_by(value=20.0).first()
print('DeviceData = %s' % dd)
# Insert a second record and check insertion
dd2 = DeviceData(value=100.0)
self.session.add(dd2)
self.session.commit()
dd = self.session.query(DeviceData).filter_by(value=100.0).first()
self.assertEquals(dd.value, dd2.value)
# Rollback test
dd3 = DeviceData(value=1000.0)
self.session.add(dd3)
self.session.rollback()
dd = self.session.query(DeviceData).filter_by(value=1000.0).first()
self.assertTrue(dd is None)
# Delete record
dd = self.session.query(DeviceData).filter_by(value=100.0).first()
self.session.delete(dd)
self.session.commit()
self.assertTrue(self.session.query(DeviceData).filter_by(value=100.0).count()==0)
# Add to device data data read from a device
sensorType1 = SensorType(code='sensorType1', description='SENSORTYPEDESCR1')
sensorType2 = SensorType(code='sensorType2', description='SENSORTYPEDESCR2')
deviceType1 = DeviceType(code='deviceType1', description='DEVICETYPEDESCR1')
deviceType2 = DeviceType(code='deviceType2', description='DEVICETYPEDESCR2')
sensor11 = Sensor(code='sensor11', description='SENSORDESCR11', sensorType=sensorType1)
sensor12 = Sensor(code='sensor12', description='SENSORDESCR12', sensorType=sensorType2)
sensor21 = Sensor(code='sensor21', description='SENSORDESCR21', sensorType=sensorType1)
sensor22 = Sensor(code='sensor22', description='SENSORDESCR22', sensorType=sensorType2)
device1 = Device(code='device1', description='DEVICEDESCR1',\
deviceType=deviceType1)
device1.sensors.append(sensor11)
device1.sensors.append(sensor12)
device2 = Device(code='device2', description='DEVICEDESCR2',\
deviceType=deviceType2)
device2.sensors.append(sensor21)
device2.sensors.append(sensor22)
deviceData11=DeviceData(datetimeRead=datetime.datetime.now(),\
value=11.0,\
device=device1)
deviceData12=DeviceData(datetimeRead=datetime.datetime.now(),\
value=12.0,\
device=device1)
deviceData21=DeviceData(datetimeRead=datetime.datetime.now(),\
value=21.0,\
device=device2,)
deviceData22=DeviceData(datetimeRead=datetime.datetime.now(),\
value=22.0,\
device=device2)
self.session.add(deviceData11)
self.session.add(deviceData12)
self.session.add(deviceData21)
self.session.add(deviceData22)
self.session.commit()
# Print data inserted
devicedatas = self.session.query(DeviceData)
for dd in devicedatas:
print('Device Data : %s'%dd)
print('\tDevice : %s'%dd.device)
if dd.device is not None and dd.device.sensors is not None:
for sens in dd.device.sensors:
print('\t\tSensor : %s'%sens)
<file_sep>/tests/testsDeviceCRUD.py
# Test suite
import unittest
import sqlalchemy
import models
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from models.models import Base, Device, DeviceType, Sensor, SensorType
# Test for in memory SQLite
class TestSQLiteMemory(unittest.TestCase):
# Database definition (in memory sqlite)
engine = create_engine('sqlite:///:memory:')
Session = sessionmaker(bind=engine)
session = Session()
def setUp(self):
Base.metadata.create_all(self.engine)
def tearDown(self):
self.session.rollback()
Base.metadata.drop_all(self.engine)
def testCRUD(self):
# Insert device type
device1 = Device(code='device1', description='DESCRIPTION1')
self.session.add(device1)
self.session.commit()
# Check if inserted
device = self.session.query(Device).filter_by(code='device1').first()
self.assertEquals(device.code, device1.code)
# Check for non insertion
device = self.session.query(Device).filter_by(code='deviceFake').first()
self.assertTrue(device is None)
# Check Update
device = self.session.query(Device).filter_by(code='device1').first()
device.description = 'DESCRIPTIONChg'
self.session.commit()
deviceTst = self.session.query(Device).filter_by(code='device1').first()
self.assertEquals(deviceTst.description, 'DESCRIPTIONChg')
# Check printout (to see this you have to run nosetest --nocapture
device = self.session.query(Device).filter_by(code='device1').first()
print('Device = %s' % device)
# Insert a second record and check insertion
device2 = Device(code='device2', description='DESCRIPTION2')
self.session.add(device2)
self.session.commit()
device = self.session.query(Device).filter_by(code='device2').first()
self.assertEquals(device.code, device2.code)
# Rollback test
device3 = Device(code='device3', description='DESCRIPTION3')
self.session.add(device3)
self.session.rollback()
device = self.session.query(Device).filter_by(code='device3').first()
self.assertTrue(device is None)
# Delete record
device = self.session.query(Device).filter_by(code='device2').first()
self.session.delete(device)
self.session.commit()
self.assertTrue(self.session.query(Device).filter_by(code='device2').count()==0)
# Add a relation to a device type
deviceType = DeviceType(code='devicetype1', description='DESCRIPTIONDT1');
device = self.session.query(Device).filter_by(code='device1').first()
device.deviceType = deviceType;
self.session.commit()
print('Device = %s' % device)
self.assertEquals(self.session.query(Device).filter_by(code='device1').first()\
.deviceType.code, 'devicetype1')
# Add list of sensors
sensor1 = Sensor(code='sensor1', description='DESCRIPTIONS1', \
sensorType=SensorType(code='sensortype1', description='DESCRIPTIONST1'))
sensor2 = Sensor(code='sensor2', description='DESCRIPTIONS2', \
sensorType=SensorType(code='sensortype2', description='DESCRIPTIONST2'))
device.sensors.append(sensor1)
device.sensors.append(sensor2)
self.session.commit()
# List sensors of a device
device = self.session.query(Device).filter_by(code='device1').first()
print('Device = %s' % device)
for sensor in device.sensors:
print('\tSensor = %s' % sensor)
# Test for SQLite on local file
class TestSQLiteOnFile(unittest.TestCase):
# Database definition
engine = create_engine('sqlite:///test.db')
Session = sessionmaker(bind=engine)
session = Session()
def setUp(self):
Base.metadata.create_all(self.engine)
def tearDown(self):
self.session.rollback()
Base.metadata.drop_all(self.engine)
def testCRUD(self):
# Insert device type
device1 = Device(code='device1', description='DESCRIPTION1')
self.session.add(device1)
self.session.commit()
# Check if inserted
device = self.session.query(Device).filter_by(code='device1').first()
self.assertEquals(device.code, device1.code)
# Check for non insertion
device = self.session.query(Device).filter_by(code='deviceFake').first()
self.assertTrue(device is None)
# Check Update
device = self.session.query(Device).filter_by(code='device1').first()
device.description = 'DESCRIPTIONChg'
self.session.commit()
deviceTst = self.session.query(Device).filter_by(code='device1').first()
self.assertEquals(deviceTst.description, 'DESCRIPTIONChg')
# Check printout (to see this you have to run nosetest --nocapture
device = self.session.query(Device).filter_by(code='device1').first()
print('Device = %s' % device)
# Insert a second record and check insertion
device2 = Device(code='device2', description='DESCRIPTION2')
self.session.add(device2)
self.session.commit()
device = self.session.query(Device).filter_by(code='device2').first()
self.assertEquals(device.code, device2.code)
# Rollback test
device3 = Device(code='device3', description='DESCRIPTION3')
self.session.add(device3)
self.session.rollback()
device = self.session.query(Device).filter_by(code='device3').first()
self.assertTrue(device is None)
# Delete record
device = self.session.query(Device).filter_by(code='device2').first()
self.session.delete(device)
self.session.commit()
self.assertTrue(self.session.query(Device).filter_by(code='device2').count()==0)
# Add a relation to a device type
deviceType = DeviceType(code='devicetype1', description='DESCRIPTIONDT1');
device = self.session.query(Device).filter_by(code='device1').first()
device.deviceType = deviceType;
self.session.commit()
print('Device = %s' % device)
self.assertEquals(self.session.query(Device).filter_by(code='device1').first()\
.deviceType.code, 'devicetype1')
# Add list of sensors
sensor1 = Sensor(code='sensor1', description='DESCRIPTIONS1', \
sensorType=SensorType(code='sensortype1', description='DESCRIPTIONST1'))
sensor2 = Sensor(code='sensor2', description='DESCRIPTIONS2', \
sensorType=SensorType(code='sensortype2', description='DESCRIPTIONST2'))
device.sensors.append(sensor1)
device.sensors.append(sensor2)
self.session.commit()
# List sensors of a device
device = self.session.query(Device).filter_by(code='device1').first()
print('Device = %s' % device)
for sensor in device.sensors:
print('\tSensor = %s' % sensor)
# Test for mysql (tested on localhost with maria db)
class TestMySql(unittest.TestCase):
# Database definition (be sure that the db name already exists in database)
engine = create_engine('mysql://root:root@localhost/testsqlalchemy')
Session = sessionmaker(bind=engine)
session = Session()
def setUp(self):
Base.metadata.create_all(self.engine)
def tearDown(self):
self.session.rollback()
Base.metadata.drop_all(self.engine)
def testCRUD(self):
# Insert device type
device1 = Device(code='device1', description='DESCRIPTION1')
self.session.add(device1)
self.session.commit()
# Check if inserted
device = self.session.query(Device).filter_by(code='device1').first()
self.assertEquals(device.code, device1.code)
# Check for non insertion
device = self.session.query(Device).filter_by(code='deviceFake').first()
self.assertTrue(device is None)
# Check Update
device = self.session.query(Device).filter_by(code='device1').first()
device.description = 'DESCRIPTIONChg'
self.session.commit()
deviceTst = self.session.query(Device).filter_by(code='device1').first()
self.assertEquals(deviceTst.description, 'DESCRIPTIONChg')
# Check printout (to see this you have to run nosetest --nocapture
device = self.session.query(Device).filter_by(code='device1').first()
print('Device = %s' % device)
# Insert a second record and check insertion
device2 = Device(code='device2', description='DESCRIPTION2')
self.session.add(device2)
self.session.commit()
device = self.session.query(Device).filter_by(code='device2').first()
self.assertEquals(device.code, device2.code)
# Rollback test
device3 = Device(code='device3', description='DESCRIPTION3')
self.session.add(device3)
self.session.rollback()
device = self.session.query(Device).filter_by(code='device3').first()
self.assertTrue(device is None)
# Delete record
device = self.session.query(Device).filter_by(code='device2').first()
self.session.delete(device)
self.session.commit()
self.assertTrue(self.session.query(Device).filter_by(code='device2').count()==0)
# Add a relation to a device type
deviceType = DeviceType(code='devicetype1', description='DESCRIPTIONDT1');
device = self.session.query(Device).filter_by(code='device1').first()
device.deviceType = deviceType;
self.session.commit()
print('Device = %s' % device)
self.assertEquals(self.session.query(Device).filter_by(code='device1').first()\
.deviceType.code, 'devicetype1')
# Add list of sensors
sensor1 = Sensor(code='sensor1', description='DESCRIPTIONS1', \
sensorType=SensorType(code='sensortype1', description='DESCRIPTIONST1'))
sensor2 = Sensor(code='sensor2', description='DESCRIPTIONS2', \
sensorType=SensorType(code='sensortype2', description='DESCRIPTIONST2'))
device.sensors.append(sensor1)
device.sensors.append(sensor2)
self.session.commit()
# List sensors of a device
device = self.session.query(Device).filter_by(code='device1').first()
print('Device = %s' % device)
for sensor in device.sensors:
print('\tSensor = %s' % sensor)
<file_sep>/tests/testsArrakis.py
# Test suite arrakis
import unittest
import sqlalchemy
import arrakis
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from models.models import Base, SensorType, Sensor, DeviceType, Device, DeviceData
from arrakis import arrakis
# Test with sqllite in memory
class TestArrakisSQLiteMemory(unittest.TestCase):
# Database definition (in memory sqlite)
engine = create_engine('sqlite:///:memory:')
def setUp(self):
arrakis.Session.configure(bind=self.engine)
arrakis.session = arrakis.Session()
Base.metadata.create_all(self.engine)
def tearDown(self):
arrakis.session.rollback()
arrakis.session.close()
Base.metadata.drop_all(self.engine)
def testParse(self):
tokens = arrakis.parseInput(input='A|B')
print(tokens)
self.assertEquals(tokens[0], 'A')
self.assertEquals(tokens[1], 'B')
print(arrakis.dictInput(input='A|B|C|D|E'))
data = arrakis.dictInput(input='A|B|C|D|E')
self.assertEquals(data['device'], 'A')
self.assertEquals(data['deviceType'], 'B')
self.assertEquals(data['sensor'], 'C')
self.assertEquals(data['sensorType'], 'D')
self.assertEquals(data['value'], 'E')
# Check a read
read1 = 'AABBCCDD|00|99AABBCC|00|1234'
data = arrakis.dictInput(input=read1)
self.assertEquals(data['device'], 'AABBCCDD')
self.assertEquals(data['deviceType'], '00')
self.assertEquals(data['sensor'], '99AABBCC')
self.assertEquals(data['sensorType'], '00')
self.assertEquals(data['value'], '1234')
# Check errors in list
data = arrakis.dictInput(input=None)
self.assertFalse(data)
data = arrakis.dictInput(input='')
self.assertFalse(data)
data = arrakis.dictInput(input='AABBCCDD|00|99AABBCC|00')
self.assertFalse(data)
data = arrakis.dictInput(input='AABBCCDD|00|99AABBCC|00|1234')
self.assertTrue(data)
data = arrakis.dictInput(input='AABBCCDD|00|99AABBCC|00|1234|FAIL')
self.assertFalse(data)
def testInsDataRead(self):
#"""Test inserimento dati"""
arrakis.insDataRead(arrakis.dictInput(input='AABBCCDD|00|99AABBCC|00|1234'))
arrakis.insDataRead(arrakis.dictInput(input='EEFFGGHH|00|99DDEEFF|00|1234'))
arrakis.insDataRead(arrakis.dictInput(input='EEFFGGHH|00|99GGHHJJ|00|1234'))
# List all tables
for instance in arrakis.session.query(SensorType).order_by(SensorType.id):
print(instance)
for instance in arrakis.session.query(DeviceType).order_by(DeviceType.id):
print(instance)
for instance in arrakis.session.query(Sensor).order_by(Sensor.id):
print(instance)
for instance in arrakis.session.query(Device).order_by(Device.id):
print(instance)
for instance in arrakis.session.query(DeviceData).order_by(DeviceData.id):
print(instance)
self.assertTrue(True)
# Test with sqllite on file
class TestArrakisSQLiteOnFile(unittest.TestCase):
# Database definition (on file sqlite)
engine = create_engine('sqlite:///test.db')
def setUp(self):
arrakis.Session.configure(bind=self.engine)
arrakis.session = arrakis.Session()
Base.metadata.create_all(self.engine)
def tearDown(self):
arrakis.session.rollback()
arrakis.session.close()
Base.metadata.drop_all(self.engine)
def testParse(self):
tokens = arrakis.parseInput(input='A|B')
print(tokens)
self.assertEquals(tokens[0], 'A')
self.assertEquals(tokens[1], 'B')
print(arrakis.dictInput(input='A|B|C|D|E'))
data = arrakis.dictInput(input='A|B|C|D|E')
self.assertEquals(data['device'], 'A')
self.assertEquals(data['deviceType'], 'B')
self.assertEquals(data['sensor'], 'C')
self.assertEquals(data['sensorType'], 'D')
self.assertEquals(data['value'], 'E')
# Check a read
read1 = 'AABBCCDD|00|99AABBCC|00|1234'
data = arrakis.dictInput(input=read1)
self.assertEquals(data['device'], 'AABBCCDD')
self.assertEquals(data['deviceType'], '00')
self.assertEquals(data['sensor'], '99AABBCC')
self.assertEquals(data['sensorType'], '00')
self.assertEquals(data['value'], '1234')
# Check errors in list
data = arrakis.dictInput(input=None)
self.assertFalse(data)
data = arrakis.dictInput(input='')
self.assertFalse(data)
data = arrakis.dictInput(input='AABBCCDD|00|99AABBCC|00')
self.assertFalse(data)
data = arrakis.dictInput(input='AABBCCDD|00|99AABBCC|00|1234')
self.assertTrue(data)
data = arrakis.dictInput(input='AABBCCDD|00|99AABBCC|00|1234|FAIL')
self.assertFalse(data)
def testInsDataRead(self):
#"""Test inserimento dati"""
arrakis.insDataRead(arrakis.dictInput(input='AABBCCDD|00|99AABBCC|00|1234'))
arrakis.insDataRead(arrakis.dictInput(input='EEFFGGHH|00|99DDEEFF|00|1234'))
arrakis.insDataRead(arrakis.dictInput(input='EEFFGGHH|00|99GGHHJJ|00|1234'))
# List all tables
for instance in arrakis.session.query(SensorType).order_by(SensorType.id):
print(instance)
for instance in arrakis.session.query(DeviceType).order_by(DeviceType.id):
print(instance)
for instance in arrakis.session.query(Sensor).order_by(Sensor.id):
print(instance)
for instance in arrakis.session.query(Device).order_by(Device.id):
print(instance)
for instance in arrakis.session.query(DeviceData).order_by(DeviceData.id):
print(instance)
self.assertTrue(True)
# Test for mysql (tested on localhost with maria db)
class TestArrakisSQLiteMySql(unittest.TestCase):
# Database definition (on file sqlite)
engine = create_engine('mysql://root:root@localhost/testsqlalchemy')
def setUp(self):
arrakis.Session.configure(bind=self.engine)
arrakis.session = arrakis.Session()
Base.metadata.create_all(self.engine)
def tearDown(self):
arrakis.session.rollback()
arrakis.session.close()
Base.metadata.drop_all(self.engine)
def testParse(self):
tokens = arrakis.parseInput(input='A|B')
print(tokens)
self.assertEquals(tokens[0], 'A')
self.assertEquals(tokens[1], 'B')
print(arrakis.dictInput(input='A|B|C|D|E'))
data = arrakis.dictInput(input='A|B|C|D|E')
self.assertEquals(data['device'], 'A')
self.assertEquals(data['deviceType'], 'B')
self.assertEquals(data['sensor'], 'C')
self.assertEquals(data['sensorType'], 'D')
self.assertEquals(data['value'], 'E')
# Check a read
read1 = 'AABBCCDD|00|99AABBCC|00|1234'
data = arrakis.dictInput(input=read1)
self.assertEquals(data['device'], 'AABBCCDD')
self.assertEquals(data['deviceType'], '00')
self.assertEquals(data['sensor'], '99AABBCC')
self.assertEquals(data['sensorType'], '00')
self.assertEquals(data['value'], '1234')
# Check errors in list
data = arrakis.dictInput(input=None)
self.assertFalse(data)
data = arrakis.dictInput(input='')
self.assertFalse(data)
data = arrakis.dictInput(input='AABBCCDD|00|99AABBCC|00')
self.assertFalse(data)
data = arrakis.dictInput(input='AABBCCDD|00|99AABBCC|00|1234')
self.assertTrue(data)
data = arrakis.dictInput(input='AABBCCDD|00|99AABBCC|00|1234|FAIL')
self.assertFalse(data)
def testInsDataRead(self):
#"""Test inserimento dati"""
arrakis.insDataRead(arrakis.dictInput(input='AABBCCDD|00|99AABBCC|00|1234'))
arrakis.insDataRead(arrakis.dictInput(input='EEFFGGHH|00|99DDEEFF|00|1234'))
arrakis.insDataRead(arrakis.dictInput(input='EEFFGGHH|00|99GGHHJJ|00|1234'))
# List all tables
for instance in arrakis.session.query(SensorType).order_by(SensorType.id):
print(instance)
for instance in arrakis.session.query(DeviceType).order_by(DeviceType.id):
print(instance)
for instance in arrakis.session.query(Sensor).order_by(Sensor.id):
print(instance)
for instance in arrakis.session.query(Device).order_by(Device.id):
print(instance)
for instance in arrakis.session.query(DeviceData).order_by(DeviceData.id):
print(instance)
self.assertTrue(True)
<file_sep>/tests/testsDeviceTypeCRUD.py
# Test suite
import unittest
import sqlalchemy
import models
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from models.models import Base, DeviceType
# Test for in memory SQLite
class TestSQLiteMemory(unittest.TestCase):
# Database definition (in memory sqlite)
engine = create_engine('sqlite:///:memory:')
Session = sessionmaker(bind=engine)
session = Session()
def setUp(self):
Base.metadata.create_all(self.engine)
def tearDown(self):
self.session.rollback()
Base.metadata.drop_all(self.engine)
def testCRUD(self):
# Insert device type
dt1 = DeviceType(code='dt1', description='DESCRIPTION1')
self.session.add(dt1)
self.session.commit()
# Check if inserted
dt = self.session.query(DeviceType).filter_by(code='dt1').first()
self.assertEquals(dt.code, dt1.code)
# Check for non insertion
dt = self.session.query(DeviceType).filter_by(code='dtFake').first()
self.assertTrue(dt is None)
# Check Update
dt = self.session.query(DeviceType).filter_by(code='dt1').first()
dt.description = 'DESCRIPTIONChg'
self.session.commit()
dtTst = self.session.query(DeviceType).filter_by(code='dt1').first()
self.assertEquals(dtTst.description, 'DESCRIPTIONChg')
# Check printout (to see this you have to run nosetest --nocapture
dt = self.session.query(DeviceType).filter_by(code='dt1').first()
print('DeviceType = %s' % dt)
# Insert a second record and check insertion
dt2 = DeviceType(code='dt2', description='DESCRIPTION2')
self.session.add(dt2)
self.session.commit()
dt = self.session.query(DeviceType).filter_by(code='dt2').first()
self.assertEquals(dt.code, dt2.code)
# Rollback test
dt3 = DeviceType(code='dt3', description='DESCRIPTION3')
self.session.add(dt3)
self.session.rollback()
dt = self.session.query(DeviceType).filter_by(code='dt3').first()
self.assertTrue(dt is None)
# Delete record
dt = self.session.query(DeviceType).filter_by(code='dt2').first()
self.session.delete(dt)
self.session.commit()
self.assertTrue(self.session.query(DeviceType).filter_by(code='dt2').count()==0)
# Test for SQLite on local file
class TestSQLiteOnFile(unittest.TestCase):
# Database definition
engine = create_engine('sqlite:///test.db')
Session = sessionmaker(bind=engine)
session = Session()
def setUp(self):
Base.metadata.create_all(self.engine)
def tearDown(self):
self.session.rollback()
Base.metadata.drop_all(self.engine)
def testCRUD(self):
# Insert device type
dt1 = DeviceType(code='dt1', description='DESCRIPTION1')
self.session.add(dt1)
self.session.commit()
# Check if inserted
dt = self.session.query(DeviceType).filter_by(code='dt1').first()
self.assertEquals(dt.code, dt1.code)
# Check for non insertion
dt = self.session.query(DeviceType).filter_by(code='dtFake').first()
self.assertTrue(dt is None)
# Check Update
dt = self.session.query(DeviceType).filter_by(code='dt1').first()
dt.description = 'DESCRIPTIONChg'
self.session.commit()
dtTst = self.session.query(DeviceType).filter_by(code='dt1').first()
self.assertEquals(dtTst.description, 'DESCRIPTIONChg')
# Check printout (to see this you have to run nosetest --nocapture
dt = self.session.query(DeviceType).filter_by(code='dt1').first()
print('DeviceType = %s' % dt)
# Insert a second record and check insertion
dt2 = DeviceType(code='dt2', description='DESCRIPTION2')
self.session.add(dt2)
self.session.commit()
dt = self.session.query(DeviceType).filter_by(code='dt2').first()
self.assertEquals(dt.code, dt2.code)
# Rollback test
dt3 = DeviceType(code='dt3', description='DESCRIPTION3')
self.session.add(dt3)
self.session.rollback()
dt = self.session.query(DeviceType).filter_by(code='dt3').first()
self.assertTrue(dt is None)
# Delete record
dt = self.session.query(DeviceType).filter_by(code='dt2').first()
self.session.delete(dt)
self.session.commit()
self.assertTrue(self.session.query(DeviceType).filter_by(code='dt2').count()==0)
# Test for mysql (tested on localhost with maria db)
class TestMySql(unittest.TestCase):
# Database definition (be sure that the db name already exists in database)
engine = create_engine('mysql://root:root@localhost/testsqlalchemy')
Session = sessionmaker(bind=engine)
session = Session()
def setUp(self):
Base.metadata.create_all(self.engine)
def tearDown(self):
self.session.rollback()
Base.metadata.drop_all(self.engine)
def testCRUD(self):
# Insert device type
dt1 = DeviceType(code='dt1', description='DESCRIPTION1')
self.session.add(dt1)
self.session.commit()
# Check if inserted
dt = self.session.query(DeviceType).filter_by(code='dt1').first()
self.assertEquals(dt.code, dt1.code)
# Check for non insertion
dt = self.session.query(DeviceType).filter_by(code='dtFake').first()
self.assertTrue(dt is None)
# Check Update
dt = self.session.query(DeviceType).filter_by(code='dt1').first()
dt.description = 'DESCRIPTIONChg'
self.session.commit()
dtTst = self.session.query(DeviceType).filter_by(code='dt1').first()
self.assertEquals(dtTst.description, 'DESCRIPTIONChg')
# Check printout (to see this you have to run nosetest --nocapture
dt = self.session.query(DeviceType).filter_by(code='dt1').first()
print('DeviceType = %s' % dt)
# Insert a second record and check insertion
dt2 = DeviceType(code='dt2', description='DESCRIPTION2')
self.session.add(dt2)
self.session.commit()
dt = self.session.query(DeviceType).filter_by(code='dt2').first()
self.assertEquals(dt.code, dt2.code)
# Rollback test
dt3 = DeviceType(code='dt3', description='DESCRIPTION3')
self.session.add(dt3)
self.session.rollback()
dt = self.session.query(DeviceType).filter_by(code='dt3').first()
self.assertTrue(dt is None)
# Delete record
dt = self.session.query(DeviceType).filter_by(code='dt2').first()
self.session.delete(dt)
self.session.commit()
self.assertTrue(self.session.query(DeviceType).filter_by(code='dt2').count()==0)
<file_sep>/requirements.txt
appdirs==1.4.3
decorator==4.0.10
MySQL-python==1.2.5
nose==1.3.7
packaging==16.8
pbr==1.10.0
pyparsing==2.2.0
six==1.10.0
SQLAlchemy==1.0.15
sqlalchemy-migrate==0.10.0
sqlparse==0.2.1
Tempita==0.5.2
<file_sep>/tests/testsSensorTypeCRUD.py
# Test suite
import unittest
import sqlalchemy
import models
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from models.models import Base, SensorType
# Test for in memory SQLite
class TestSQLiteMemory(unittest.TestCase):
# Database definition (in memory sqlite)
engine = create_engine('sqlite:///:memory:')
Session = sessionmaker(bind=engine)
session = Session()
def setUp(self):
Base.metadata.create_all(self.engine)
def tearDown(self):
self.session.rollback()
Base.metadata.drop_all(self.engine)
def testCRUD(self):
# Insert device type
st1 = SensorType(code='st1', description='DESCRIPTION1')
self.session.add(st1)
self.session.commit()
# Check if inserted
st = self.session.query(SensorType).filter_by(code='st1').first()
self.assertEquals(st.code, st1.code)
# Check for non insertion
st = self.session.query(SensorType).filter_by(code='stFake').first()
self.assertTrue(st is None)
# Check Update
st = self.session.query(SensorType).filter_by(code='st1').first()
st.description = 'DESCRIPTIONChg'
self.session.commit()
stTst = self.session.query(SensorType).filter_by(code='st1').first()
self.assertEquals(stTst.description, 'DESCRIPTIONChg')
# Check printout (to see this you have to run nosetest --nocapture
st = self.session.query(SensorType).filter_by(code='st1').first()
print('SensorType = %s' % st)
# Insert a second record and check insertion
st2 = SensorType(code='st2', description='DESCRIPTION2')
self.session.add(st2)
self.session.commit()
st = self.session.query(SensorType).filter_by(code='st2').first()
self.assertEquals(st.code, st2.code)
# Rollback test
st3 = SensorType(code='st3', description='DESCRIPTION3')
self.session.add(st3)
self.session.rollback()
st = self.session.query(SensorType).filter_by(code='st3').first()
self.assertTrue(st is None)
# Delete record
st = self.session.query(SensorType).filter_by(code='st2').first()
self.session.delete(st)
self.session.commit()
self.assertTrue(self.session.query(SensorType).filter_by(code='st2').count()==0)
# Test for SQLite on local file
class TestSQLiteOnFile(unittest.TestCase):
# Database definition
engine = create_engine('sqlite:///test.db')
Session = sessionmaker(bind=engine)
session = Session()
def setUp(self):
Base.metadata.create_all(self.engine)
def tearDown(self):
self.session.rollback()
Base.metadata.drop_all(self.engine)
def testCRUD(self):
# Insert device type
st1 = SensorType(code='st1', description='DESCRIPTION1')
self.session.add(st1)
self.session.commit()
# Check if inserted
st = self.session.query(SensorType).filter_by(code='st1').first()
self.assertEquals(st.code, st1.code)
# Check for non insertion
st = self.session.query(SensorType).filter_by(code='stFake').first()
self.assertTrue(st is None)
# Check Update
st = self.session.query(SensorType).filter_by(code='st1').first()
st.description = 'DESCRIPTIONChg'
self.session.commit()
stTst = self.session.query(SensorType).filter_by(code='st1').first()
self.assertEquals(stTst.description, 'DESCRIPTIONChg')
# Check printout (to see this you have to run nosetest --nocapture
st = self.session.query(SensorType).filter_by(code='st1').first()
print('SensorType = %s' % st)
# Insert a second record and check insertion
st2 = SensorType(code='st2', description='DESCRIPTION2')
self.session.add(st2)
self.session.commit()
st = self.session.query(SensorType).filter_by(code='st2').first()
self.assertEquals(st.code, st2.code)
# Rollback test
st3 = SensorType(code='st3', description='DESCRIPTION3')
self.session.add(st3)
self.session.rollback()
st = self.session.query(SensorType).filter_by(code='st3').first()
self.assertTrue(st is None)
# Delete record
st = self.session.query(SensorType).filter_by(code='st2').first()
self.session.delete(st)
self.session.commit()
self.assertTrue(self.session.query(SensorType).filter_by(code='st2').count()==0)
# Test for mysql (tested on localhost with maria db)
class TestMySql(unittest.TestCase):
# Database definition (be sure that the db name already exists in database)
engine = create_engine('mysql://root:root@localhost/testsqlalchemy')
Session = sessionmaker(bind=engine)
session = Session()
def setUp(self):
Base.metadata.create_all(self.engine)
def tearDown(self):
self.session.rollback()
Base.metadata.drop_all(self.engine)
def testCRUD(self):
# Insert device type
st1 = SensorType(code='st1', description='DESCRIPTION1')
self.session.add(st1)
self.session.commit()
# Check if inserted
st = self.session.query(SensorType).filter_by(code='st1').first()
self.assertEquals(st.code, st1.code)
# Check for non insertion
st = self.session.query(SensorType).filter_by(code='stFake').first()
self.assertTrue(st is None)
# Check Update
st = self.session.query(SensorType).filter_by(code='st1').first()
st.description = 'DESCRIPTIONChg'
self.session.commit()
stTst = self.session.query(SensorType).filter_by(code='st1').first()
self.assertEquals(stTst.description, 'DESCRIPTIONChg')
# Check printout (to see this you have to run nosetest --nocapture
st = self.session.query(SensorType).filter_by(code='st1').first()
print('SensorType = %s' % st)
# Insert a second record and check insertion
st2 = SensorType(code='st2', description='DESCRIPTION2')
self.session.add(st2)
self.session.commit()
st = self.session.query(SensorType).filter_by(code='st2').first()
self.assertEquals(st.code, st2.code)
# Rollback test
st3 = SensorType(code='st3', description='DESCRIPTION3')
self.session.add(st3)
self.session.rollback()
st = self.session.query(SensorType).filter_by(code='st3').first()
self.assertTrue(st is None)
# Delete record
st = self.session.query(SensorType).filter_by(code='st2').first()
self.session.delete(st)
self.session.commit()
self.assertTrue(self.session.query(SensorType).filter_by(code='st2').count()==0)
<file_sep>/README.md
# project-arrakis
Data collect from soil moisture sensors
<file_sep>/arduino/device02/device02.ino
/*
* Simple program that sends dat afrom a soil moisture sensor
* This device is indiated by the letter A
*/
#include <SPI.h>
#include "nRF24L01.h"
#include "RF24.h"
// Debugging nrf24
int serial_putc( char c, FILE *)
{
Serial.write( c );
return c;
}
// Debugging nrf24
void printf_begin(void)
{
Serial.println("printf_begin begins");
fdevopen( &serial_putc, 0);
Serial.println("printf_begin ends");
}
// Pin configuration for nRF24
// nRF24 set the pin 9 to CE and 10 to CSN/SS
// Cables are:
// SS -> 10
// MOSI -> 11
// MISO -> 12
// SCK -> 13
RF24 radio(9, 10);
//
const uint64_t pipes[2] = { 0xF0F0F0F0E1LL, 0xF0F0F0F0D2LL };
// Set a maximum on 30 char
char SendPayload[31] = "";
// Reostato sensor
const int sensPinReostato = A0;
const char* sensReostatoCode = "99AAAAAB";
const char* sensReostatoType = "00"; // Type is connected to pin number
const int sensOnPin = 8; // Digital pin 8 controls switk on of sensor
// Device code (a 8 hexs code not starting with 99)
char* deviceName = "AAAAAA02";
char* deviceType = "01"; // Arduino uno
void setup() {
// put your setup code here, to run once
Serial.begin(9600); // To debug
printf_begin();
// nRF24 config
radio.begin();
radio.setChannel(0x4c);
radio.setAutoAck(1);
radio.setRetries(15, 15);
radio.setDataRate(RF24_2MBPS);
radio.setPayloadSize(32);
radio.openReadingPipe(1, pipes[0]);
radio.openWritingPipe(pipes[1]);
radio.startListening();
radio.printDetails();
}
void loop() {
SendPayload[0] = '\0';
strcat(SendPayload, deviceName);
strcat(SendPayload, "|");
strcat(SendPayload, deviceType);
strcat(SendPayload, "|");
// READ SOIL MISTURE SENSOR
// We will keep the sensor not powered on until we need it
// To power it on we will use digital pin 8 // NO, facciamo con un transistor
delay(200);
int sensValueReostato = analogRead(sensPinReostato);
Serial.println(sensValueReostato);
char buf[4];
strcat(SendPayload, sensReostatoCode);
strcat(SendPayload, "|");
strcat(SendPayload, sensReostatoType);
strcat(SendPayload, "|");
strcat(SendPayload, itoa(sensValueReostato, buf, 10));
// Send an heart beat
radio.stopListening();
bool ok = radio.write(&SendPayload, strlen(SendPayload));
if( !ok ) {
Serial.println("Radio.write not worked");
}
Serial.println("Sent payload");
Serial.println(SendPayload);
radio.startListening();
delay(1000);
}
<file_sep>/tests/testsSensorCRUD.py
# Test suite
import unittest
import sqlalchemy
import models
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from models.models import Base, Sensor, SensorType
# Test for in memory SQLite
class TestSQLiteMemory(unittest.TestCase):
# Database definition (in memory sqlite)
engine = create_engine('sqlite:///:memory:')
Session = sessionmaker(bind=engine)
session = Session()
def setUp(self):
Base.metadata.create_all(self.engine)
def tearDown(self):
self.session.rollback()
Base.metadata.drop_all(self.engine)
def testCRUD(self):
# Insert sensor type
sensor1 = Sensor(code='sensor1', description='DESCRIPTION1')
self.session.add(sensor1)
self.session.commit()
# Check if inserted
sensor = self.session.query(Sensor).filter_by(code='sensor1').first()
self.assertEquals(sensor.code, sensor1.code)
# Check for non insertion
sensor = self.session.query(Sensor).filter_by(code='sensorFake').first()
self.assertTrue(sensor is None)
# Check Update
sensor = self.session.query(Sensor).filter_by(code='sensor1').first()
sensor.description = 'DESCRIPTIONChg'
self.session.commit()
sensorTst = self.session.query(Sensor).filter_by(code='sensor1').first()
self.assertEquals(sensorTst.description, 'DESCRIPTIONChg')
# Check printout (to see this you have to run nosetest --nocapture
sensor = self.session.query(Sensor).filter_by(code='sensor1').first()
print('Sensor = %s' % sensor)
# Insert a second record and check insertion
sensor2 = Sensor(code='sensor2', description='DESCRIPTION2')
self.session.add(sensor2)
self.session.commit()
sensor = self.session.query(Sensor).filter_by(code='sensor2').first()
self.assertEquals(sensor.code, sensor2.code)
# Rollback test
sensor3 = Sensor(code='sensor3', description='DESCRIPTION3')
self.session.add(sensor3)
self.session.rollback()
sensor = self.session.query(Sensor).filter_by(code='sensor3').first()
self.assertTrue(sensor is None)
# Delete record
sensor = self.session.query(Sensor).filter_by(code='sensor2').first()
self.session.delete(sensor)
self.session.commit()
self.assertTrue(self.session.query(Sensor).filter_by(code='sensor2').count()==0)
# Add a relation to a sensor type
sensorType = SensorType(code='sensortype1', description='DESCRIPTIONST1');
sensor = self.session.query(Sensor).filter_by(code='sensor1').first()
sensor.sensorType = sensorType;
self.session.commit()
print('Sensor = %s' % sensor)
self.assertEquals(self.session.query(Sensor).filter_by(code='sensor1').first()\
.sensorType.code, 'sensortype1')
# Test for SQLite on local file
class TestSQLiteOnFile(unittest.TestCase):
# Database definition
engine = create_engine('sqlite:///test.db')
Session = sessionmaker(bind=engine)
session = Session()
def setUp(self):
Base.metadata.create_all(self.engine)
def tearDown(self):
self.session.rollback()
Base.metadata.drop_all(self.engine)
def testCRUD(self):
# Insert sensor type
sensor1 = Sensor(code='sensor1', description='DESCRIPTION1')
self.session.add(sensor1)
self.session.commit()
# Check if inserted
sensor = self.session.query(Sensor).filter_by(code='sensor1').first()
self.assertEquals(sensor.code, sensor1.code)
# Check for non insertion
sensor = self.session.query(Sensor).filter_by(code='sensorFake').first()
self.assertTrue(sensor is None)
# Check Update
sensor = self.session.query(Sensor).filter_by(code='sensor1').first()
sensor.description = 'DESCRIPTIONChg'
self.session.commit()
sensorTst = self.session.query(Sensor).filter_by(code='sensor1').first()
self.assertEquals(sensorTst.description, 'DESCRIPTIONChg')
# Check printout (to see this you have to run nosetest --nocapture
sensor = self.session.query(Sensor).filter_by(code='sensor1').first()
print('Sensor = %s' % sensor)
# Insert a second record and check insertion
sensor2 = Sensor(code='sensor2', description='DESCRIPTION2')
self.session.add(sensor2)
self.session.commit()
sensor = self.session.query(Sensor).filter_by(code='sensor2').first()
self.assertEquals(sensor.code, sensor2.code)
# Rollback test
sensor3 = Sensor(code='sensor3', description='DESCRIPTION3')
self.session.add(sensor3)
self.session.rollback()
sensor = self.session.query(Sensor).filter_by(code='sensor3').first()
self.assertTrue(sensor is None)
# Delete record
sensor = self.session.query(Sensor).filter_by(code='sensor2').first()
self.session.delete(sensor)
self.session.commit()
self.assertTrue(self.session.query(Sensor).filter_by(code='sensor2').count()==0)
# Add a relation to a sensor type
sensorType = SensorType(code='sensortype1', description='DESCRIPTIONST1');
sensor = self.session.query(Sensor).filter_by(code='sensor1').first()
sensor.sensorType = sensorType;
self.session.commit()
print('Sensor = %s' % sensor)
self.assertEquals(self.session.query(Sensor).filter_by(code='sensor1').first()\
.sensorType.code, 'sensortype1')
# Test for mysql (tested on localhost with maria db)
class TestMySql(unittest.TestCase):
# Database definition (be sure that the db name already exists in database)
engine = create_engine('mysql://root:root@localhost/testsqlalchemy')
Session = sessionmaker(bind=engine)
session = Session()
def setUp(self):
Base.metadata.create_all(self.engine)
def tearDown(self):
self.session.rollback()
Base.metadata.drop_all(self.engine)
def testCRUD(self):
# Insert sensor type
sensor1 = Sensor(code='sensor1', description='DESCRIPTION1')
self.session.add(sensor1)
self.session.commit()
# Check if inserted
sensor = self.session.query(Sensor).filter_by(code='sensor1').first()
self.assertEquals(sensor.code, sensor1.code)
# Check for non insertion
sensor = self.session.query(Sensor).filter_by(code='sensorFake').first()
self.assertTrue(sensor is None)
# Check Update
sensor = self.session.query(Sensor).filter_by(code='sensor1').first()
sensor.description = 'DESCRIPTIONChg'
self.session.commit()
sensorTst = self.session.query(Sensor).filter_by(code='sensor1').first()
self.assertEquals(sensorTst.description, 'DESCRIPTIONChg')
# Check printout (to see this you have to run nosetest --nocapture
sensor = self.session.query(Sensor).filter_by(code='sensor1').first()
print('Sensor = %s' % sensor)
# Insert a second record and check insertion
sensor2 = Sensor(code='sensor2', description='DESCRIPTION2')
self.session.add(sensor2)
self.session.commit()
sensor = self.session.query(Sensor).filter_by(code='sensor2').first()
self.assertEquals(sensor.code, sensor2.code)
# Rollback test
sensor3 = Sensor(code='sensor3', description='DESCRIPTION3')
self.session.add(sensor3)
self.session.rollback()
sensor = self.session.query(Sensor).filter_by(code='sensor3').first()
self.assertTrue(sensor is None)
# Delete record
sensor = self.session.query(Sensor).filter_by(code='sensor2').first()
self.session.delete(sensor)
self.session.commit()
self.assertTrue(self.session.query(Sensor).filter_by(code='sensor2').count()==0)
# Add a relation to a sensor type
sensorType = SensorType(code='sensortype1', description='DESCRIPTIONST1');
sensor = self.session.query(Sensor).filter_by(code='sensor1').first()
sensor.sensorType = sensorType;
self.session.commit()
print('Sensor = %s' % sensor)
self.assertEquals(self.session.query(Sensor).filter_by(code='sensor1').first()\
.sensorType.code, 'sensortype1')
| be7189d37f904a472e274ecf1949c7e81591f6a3 | [
"Markdown",
"Python",
"Text",
"C++"
] | 14 | Text | ilbidi/project-arrakis | 0ff5d6c9970067ff1a0a7fdaaf62aecfb44b1566 | 633af58ced50c56953fa700cab48ead4ea35d9c1 |
refs/heads/main | <repo_name>feninakhansa/projectmenumakanan<file_sep>/app/src/main/java/com/example/menumakanan/MainActivity.java
package com.example.menumakanan;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.os.Bundle;
import java.lang.reflect.Array;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
private ArrayList<String> FotoMakanan = new ArrayList<>();
private ArrayList<String> NamaMakanan = new ArrayList<>();
private ArrayList<String> InfoMakanan = new ArrayList<>();
private ArrayList<String> HargaMakanan = new ArrayList<>();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
getDataFromInternet();
}
private void prosesRecyclerViewAdapter(){
RecyclerView recyclerView = findViewById(R.id.recyclerView);
RecyclerViewAdapter adapter = new RecyclerViewAdapter(FotoMakanan, NamaMakanan, InfoMakanan, HargaMakanan,this);
recyclerView.setAdapter(adapter);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
}
private void getDataFromInternet(){
NamaMakanan.add("<NAME>");
FotoMakanan.add("https://makananoleholeh.com/wp-content/uploads/2018/10/Rendang-padang.jpg");
InfoMakanan.add("Makanan yang sangat popular di Indonesia bahkan di dunia adalah rendang. Rendang merupakan makanan khas dari padang yang memiliki rasa begitu menggugah selera. Bahan yang digunakan untuk membuat makanan ini adalah daging sapi yang dimasak lama dengan bumbu rempah yang kaya. Anda tentu saja sudah sangat mengenal rasa dari rendang karena banyak dijual dirumah makan padang, restoran modern bahkan banyak restoran luar negeri yang juga menjual makanan ini.");
HargaMakanan.add("Harga : Rp 45.000");
NamaMakanan.add("Gudeg Jogja");
FotoMakanan.add("https://makananoleholeh.com/wp-content/uploads/2018/10/Gudeg-jogja-enak.jpg");
InfoMakanan.add("Makanan khas dari kota jogja ini juga merupakan salah satu makanan khas nusantara yang sangat banyak digemari oleh masyarakat di Indonesia. Anda yang merupakan masyarakat jogja tentu saja sudah sangat mengenali bagaimana cita rasa dari makanan yang satu ini. Bahan yang digunakan untuk membuat gudeg adalah nangka muda yang dimasak dengan rempah yang lengkap dan juga diberi gula merah sehingga rasanya manis.");
HargaMakanan.add("Harga : Rp 30.000");
NamaMakanan.add("Pempek Palembang");
FotoMakanan.add("https://makananoleholeh.com/wp-content/uploads/2018/10/Pempek-palembang.jpg");
InfoMakanan.add("Makanan khas Palembang yang sering disebut dengan pempek ini juga merupakan makanan yang sangat terkenal di kalangan masyarakat Indonesia baik di wilayah Palembang atau di daerah lain. Kelezatan dari pempek sudah sangat terkenal dan juga banyak sekali pedagang di jawa yang menjual makanan ini. Pempek terbuat dari ikan dan tepung kemudian dinikmati dengan kuah cuka yang dicampur gula dan garam sedikit.");
HargaMakanan.add("Harga : Rp 50.000");
NamaMakanan.add("<NAME>");
FotoMakanan.add("https://makananoleholeh.com/wp-content/uploads/2018/10/Mie-kocok-bandung.jpg");
InfoMakanan.add("Makanan pertama yang menjadi salah satu makanan khas dari negara ini adalah mie kocok bandung. Mie kocok merupakan makanan khas dari kota bandung yang memiliki rasa segar, gurih, dan juga nikmat. Salah satu mangkuk mie kocok anda akan menemukan beberapa bahan makanan seperti mie gepeng, sayur tauge, dan juga potongan kikil.");
HargaMakanan.add("Harga : Rp 25.000");
NamaMakanan.add("<NAME>");
FotoMakanan.add("https://makananoleholeh.com/wp-content/uploads/2018/10/ayam-betutu-bali.jpg");
InfoMakanan.add("Makanan ini sangat khas Indonesia karena kaya akan rempah-rempah. Cara masak ayam ini sangat unik sehingga menjadikan rasanya terasa berbeda dengan makanan dengan bahan ayam lainnya. Cara memasak ayam betutu ini adalah dengan ayam utuh yang di beri bumbu special kemudian dibakar. Makanan ini merupakan makanan khas dari pulau bali. Rasa ayam yang lembut dan juga kaya akan rempah akan membuat pengalaman anda selama di bali semakin terasa lengkap dan tak terlupakan.");
HargaMakanan.add("Harga : Rp 60.000");
NamaMakanan.add("<NAME>");
FotoMakanan.add("https://www.gotravelly.com/blog/wp-content/uploads/2018/04/bika-ambon-sumatera-utara.jpg");
InfoMakanan.add("Jika Aceh mendunia dengan mienya, berbeda lagi dengan Sumatera Utara yang populer dengan bika ambon. Yakni sejenis kue dengan rasa yang sangat lezat. Bika ambon bahkan juga dijual dengan beberapa varian rasa terbaik, seperti keju hingga durian.");
HargaMakanan.add("Harga : Rp 55.000");
NamaMakanan.add("<NAME>");
FotoMakanan.add("https://www.gotravelly.com/blog/wp-content/uploads/2018/04/gulai-ikan-patin-jambi.jpg");
InfoMakanan.add("da makanan khas daerah Jambi, dengan nama <NAME>. Masakan yang satu ini sangat populer di tengah masyarakat Jambi dan sekitarnya. Dengan menggunakan daging buah durian yang telah difermentasi, gulai ikan akan dimasak hingga matang dengan rasa yang dijamin bikin ketagihan.");
HargaMakanan.add("Harga : Rp 60.000");
prosesRecyclerViewAdapter();
}
} | f2a0419bcc419c31c87e5ff32ffde2655b592685 | [
"Java"
] | 1 | Java | feninakhansa/projectmenumakanan | 22a3bd63b4162895e89592ecf0fd7f5f11ab707d | 5977a5c46a9cd8bff94249fe31e1c0b8db7f0e67 |
refs/heads/main | <file_sep>import React from "react";
import Card from "../../shared/components/UIElements/Card";
import { useForm } from "../../shared/hooks/form-hook";
import { AuthContext } from "../../shared/context/auth-context";
import { useContext } from "react";
import Input from "../../shared/components/FormElements/Input";
import classes from "./NewPost.module.css";
import { VALIDATOR_REQUIRE } from "../../shared/util/validators";
import { useHttpClient } from "../../shared/hooks/use-http";
import LoadingSpinner from "../../shared/components/UIElements/LoadingSpinner";
import ImageUpload from "../../shared/components/FormElements/ImageUpload";
const NewPost = (props) => {
const ctx = useContext(AuthContext);
const { isLoading, sendRequest } = useHttpClient();
const [formState, inputHandler] = useForm(
{
post: {
value: "",
isValid: false,
},
post_image: {
value: undefined,
isValid: true,
},
},
false
);
const submitPostHandler = async () => {
console.log(formState.inputs.post_image.value);
const postData = new FormData();
postData.append("user_id", ctx.userId);
postData.append("post", formState.inputs.post.value);
if (formState.inputs.post_image.value) {
postData.append("post_image", formState.inputs.post_image.value);
}
const post = { user_id: ctx.userId, post: formState.inputs.post.value };
try {
if (formState.inputs.post_image.value) {
console.log('123123') ;
await sendRequest(
"http://localhost:5000/api/posts/newWithPhoto",
"POST",
postData
);
} else {
console.log('hereeee') ;
await sendRequest(
"http://localhost:5000/api/posts/new",
"POST",
JSON.stringify(post),
{"Content-Type":"application/json"}
);
}
} catch (error) {
console.log(error);
}
props.refresh(ctx.userId);
};
return (
<Card className={classes.card}>
<div className={classes.input}>
{isLoading && <LoadingSpinner />}
<Input
element="input"
id="post"
type="text"
validators={[VALIDATOR_REQUIRE()]}
errorText="Please enter a post"
placeholder="What's on your mind ? "
onInput={inputHandler}
/>
</div>
<div className={classes.actions}>
<div>
<ImageUpload id="post_image" center onInput={inputHandler} />
</div>
</div>
<div className={classes.postCont}>
<button
className={classes.post}
disabled={!formState.isValid}
onClick={submitPostHandler}
>
POST
</button>
</div>
</Card>
);
};
export default NewPost;
<file_sep>import React, { useEffect } from "react";
import { useState } from "react";
import classes from "./PostItem.module.css";
import Card from "../../shared/components/UIElements/Card";
import { Link } from "react-router-dom";
import Input from "../../shared/components/FormElements/Input";
import { useForm } from "../../shared/hooks/form-hook";
import { VALIDATOR_REQUIRE } from "../../shared/util/validators";
import { useHttpClient } from "../../shared/hooks/use-http";
import LoadingSpinner from "../../shared/components/UIElements/LoadingSpinner";
import { AuthContext } from "../../shared/context/auth-context";
import { useContext } from "react";
const PostItem = (props) => {
const { isLoading, sendRequest } = useHttpClient();
const [isLiked, setIsLiked] = useState(false);
const [dummyState, setDummyState] = useState(false);
const [userId, setUserId] = useState(null);
const [likes, setLikes] = useState(0);
const [comments, setComments] = useState(0);
const post_id = props.id;
const ctx = useContext(AuthContext);
useEffect(() => {
const getInfo = async () => {
try {
const res = await sendRequest(
`http://localhost:5000/api/posts/${post_id}`
);
console.log(res);
setUserId(res[0].user_id);
setLikes(props.likes);
setComments(props.comments);
} catch (error) {}
};
getInfo();
}, [post_id, dummyState]);
useEffect(() => {
const getIsLiked = async () => {
try {
const res = await sendRequest(
`http://localhost:5000/api/users/isLiked/${ctx.userId}/${post_id}`
);
setIsLiked(res.isLiked);
console.log(res.isLiked);
} catch (error) {}
};
getIsLiked();
}, [ctx]);
const [formState, inputHandler, setFormData] = useForm(
{
comment: {
value: "",
isValid: false,
},
},
false
);
const commentSubmitHandler = async () => {
const post = {
post_id,
user_id: ctx.userId,
comment: formState.inputs.comment.value,
};
try {
await sendRequest(
`http://localhost:5000/api/posts/newComment`,
"POST",
JSON.stringify(post),
{ "Content-Type": "application/json" }
);
setComments((prev) => prev + 1);
if (props.full) {
props.refresh();
}
} catch (error) {}
};
const likeSubmitHandler = () => {
const payload = { user_id: ctx.userId, post_id };
if (!isLiked) {
const sendLike = async () => {
try {
await sendRequest(
`http://localhost:5000/api/posts/like`,
"POST",
JSON.stringify(payload),
{ "Content-Type": "application/json" }
);
} catch (error) {}
};
sendLike();
setLikes(likes + 1);
setIsLiked((prev) => !prev);
} else {
const sendDislike = async () => {
try {
await sendRequest(
`http://localhost:5000/api/posts/dislike`,
"POST",
JSON.stringify(payload),
{ "Content-Type": "application/json" }
);
} catch (error) {}
};
sendDislike();
setLikes(likes - 1);
setIsLiked((prev) => !prev);
}
};
return (
<Card className={classes.item}>
{!isLoading && (
<React.Fragment>
<div className={classes.header}>
<Link to={`/profile/${userId}`}>
<div className={classes.avt}>
<img
src={`http://localhost:5000/${props.userImage}`}
alt={"this is a photo"}
/>
</div>
<div className={classes.name}>
<h3>{props.name}</h3>
</div>
</Link>
</div>
<h5>{props.date}</h5>
<div className={classes.line}></div>
<div className={classes.post}>
<p>{props.post}</p>
{props.postImage && (
<div className={classes.postImage}>
{props.postImage && (
<img src={`http://localhost:5000/${props.postImage}`} />
)}
</div>
)}
</div>
<div className={classes.line}></div>
<div className={classes.options}>
{!props.full && (
// <div className={classes.fullpostOpt}>
<Link to={`/post/${props.id}`}> View full post</Link>
// </div>
)}
{userId == ctx.userId && (
<button className={classes.delete}> Delete Post</button>
)}
</div>
<div className={classes.actions}>
{isLoading && <LoadingSpinner />}
{!isLoading && (
<button
className={isLiked ? classes.liked : ""}
onClick={likeSubmitHandler}
>
<h4> {likes} |</h4> Like
</button>
)}
<Link to={`/post/${props.id}`} style={{ textDecoration: "none" }}>
<button>
<h4> {comments} |</h4> Comments
</button>
</Link>
</div>
<div className={classes.commentActions}>
<div className={classes.commentArea}>
<Input
element="textArea"
id="comment"
type="text"
validators={[VALIDATOR_REQUIRE()]}
errorText="Please enter a valid comment"
placeholder="Type your comment"
onInput={inputHandler}
className={classes.comment}
/>
</div>
<button
className={classes.postBtn}
onClick={commentSubmitHandler}
disabled={!formState.isValid}
>
comment
</button>
</div>
</React.Fragment>
)}
</Card>
);
};
export default PostItem;
<file_sep>import React from "react";
import { Fragment } from "react";
import classes from "./Friends.module.css";
import { useEffect, useState } from "react";
import FriendRequestsList from "../components/FriendRequestsList";
import FriendsMenu from "../components/FriendsMenu";
import { useHttpClient } from "../../shared/hooks/use-http";
import LoadingSpinner from "../../shared/components/UIElements/LoadingSpinner";
import { AuthContext } from "../../shared/context/auth-context";
import { useContext } from "react";
const Friends = () => {
const ctx = useContext(AuthContext);
const [friendsIds, setFriendsIds] = useState(null);
const [requestsIds, setRequestsIds] = useState(null);
const [friends, setFriends] = useState(null);
const [requests, setRequests] = useState(null);
const [dummyState, setDummyState] = useState(false);
const refresh = () => {
setDummyState((prev) => !prev);
};
const { isLoading, error, sendRequest, clearError } = useHttpClient();
// getting friends ids
useEffect(() => {
const getFriends = async () => {
try {
const response = await sendRequest(
`http://localHost:5000/api/users/${ctx.userId}/friends`
);
setFriendsIds(response);
console.log(response);
} catch (error) {}
};
if (ctx.userId) {
getFriends();
}
}, [ctx, dummyState]);
// now we have friends Ids , get information about them .
useEffect(() => {
const getFriends = async () => {
if (friendsIds) {
const promises = friendsIds.map((id) => {
return new Promise(async (resolve, reject) => {
try {
const info = await sendRequest(
`http://localhost:5000/api/users/${id}/info`
);
return resolve(info);
} catch (error) {
return reject(error);
}
});
});
const info = await Promise.all(promises);
setFriends(info);
console.log(info);
}
};
getFriends();
}, [friendsIds]);
//getting friend requets ids
useEffect(() => {
console.log("inside");
const getRequets = async () => {
try {
const response = await sendRequest(
`http://localHost:5000/api/users/${ctx.userId}/requests`
);
setRequestsIds(response);
} catch (error) {
console.log(error);
}
};
if (ctx.userId) {
getRequets();
}
}, [ctx, dummyState]);
useEffect(() => {
const getRequests = async () => {
if (requestsIds) {
const promises = requestsIds.map((id) => {
return new Promise(async (resolve, reject) => {
try {
const info = await sendRequest(
`http://localhost:5000/api/users/${id}/info`
);
return resolve(info);
} catch (error) {
return reject(error);
}
});
});
const info = await Promise.all(promises);
setRequests(info);
console.log(info);
}
};
getRequests();
}, [requestsIds]);
return (
<div className={classes.container}>
<section className={classes.reqs}>
{isLoading && !requests && <LoadingSpinner />}
{!isLoading && requests && requests.length > 0 && (
<FriendRequestsList requests={requests} refresh={refresh} />
)}
{!isLoading && requests && requests.length === 0 && (
<h2>No friend requests.</h2>
)}
</section>
<section className={classes.reqs}>
{isLoading && !friends && <LoadingSpinner />}
{!isLoading && friends && friends.length === 0 && <h2>No friends.</h2>}
{!isLoading && friends && friends.length > 0 && (
<FriendsMenu friends={friends} refresh={refresh} />
)}
</section>
</div>
);
};
export default Friends;
<file_sep>import React, { useState } from "react";
import classes from "./FriendRequestsList.module.css";
import FriendRequestItem from "../components/FriendRequestItem";
import Card from "../../shared/components/UIElements/Card";
const DUMMY_REQUESTS = [
{
name: "khalid",
image:
"https://images.pexels.com/photos/839011/pexels-photo-839011.jpeg?auto=compress&cs=tinysrgb&dpr=2&h=750&w=1260",
},
{
name: "khalid",
image:
"https://images.pexels.com/photos/839011/pexels-photo-839011.jpeg?auto=compress&cs=tinysrgb&dpr=2&h=750&w=1260",
},
{
name: "khalid",
image:
"https://images.pexels.com/photos/839011/pexels-photo-839011.jpeg?auto=compress&cs=tinysrgb&dpr=2&h=750&w=1260",
},
{
name: "khalid",
image:
"https://images.pexels.com/photos/839011/pexels-photo-839011.jpeg?auto=compress&cs=tinysrgb&dpr=2&h=750&w=1260",
},
{
name: "khalid",
image:
"https://images.pexels.com/photos/839011/pexels-photo-839011.jpeg?auto=compress&cs=tinysrgb&dpr=2&h=750&w=1260",
},
{
name: "khalid",
image:
"https://images.pexels.com/photos/839011/pexels-photo-839011.jpeg?auto=compress&cs=tinysrgb&dpr=2&h=750&w=1260",
},
];
const FriendRequestsList = (props) => {
const items = props.requests.map((req) => {
return (
<FriendRequestItem
userId={req.userId}
name={req.name}
userImage={req.userImage}
refresh={props.refresh}
key={req.userId}
/>
);
});
return (
<Card>
{items}
</Card>
);
};
export default FriendRequestsList;
<file_sep>import React from "react";
import { Fragment } from "react";
import Navigation from "../Navigation/Navigation";
import classes from "./Layout.module.css";
const Layout = (props) => {
return (
<Fragment>
<div className={classes.container}>
<Navigation />
</div>
{props.children}
</Fragment>
);
};
export default Layout;
<file_sep>const express = require("express");
const router = express.Router();
const postsControllers = require("../controllers/posts-controllers");
const fileUpload = require("../middleware/file-upload") ;
const { check } = require("express-validator");
router.post("/new", [check("post").not().isEmpty()], postsControllers.addPost);
router.post("/newWithPhoto", fileUpload.single("post_image"),[check("post").not().isEmpty()], postsControllers.addPostWithPhoto);
router.get("/:id", postsControllers.getPost);
router.post("/newComment", postsControllers.newComment);
router.get("/:id/comments", postsControllers.getComments);
router.post("/like", postsControllers.like);
router.post("/dislike", postsControllers.dislike);
module.exports = router;
<file_sep>import React from "react";
import classes from "./FriendsMenu.module.css";
import Card from "../../shared/components/UIElements/Card";
import FriendItem from "./FriendItem";
const DUMMY_FRIENDS = [
{
id: 1,
name: "khalid",
image:
"https://images.pexels.com/photos/839011/pexels-photo-839011.jpeg?auto=compress&cs=tinysrgb&dpr=2&h=750&w=1260",
},
{
id: 2,
name: "khalid",
image:
"https://images.pexels.com/photos/839011/pexels-photo-839011.jpeg?auto=compress&cs=tinysrgb&dpr=2&h=750&w=1260",
},
];
const FriendsMenu = (props) => {
const friends = props.friends.map((friend, indx) => (
<FriendItem
userId={friend.userId}
key={friend.userId}
name={friend.name}
userImage={friend.userImage}
refresh={props.refresh}
/>
));
return <Card>{friends}</Card>;
};
export default FriendsMenu;
<file_sep>import React from "react";
import { Link } from "react-router-dom";
import classes from "./UserSearchItem.module.css";
import Avatar from "../../shared/components/UIElements/Avatar";
const UserSearchItem = (props) => {
console.log(props) ;
return (
<li className={classes.container}>
<div className={classes.info}>
<Link to={`/profile/${props.userId}`}>
<div className={classes.photo}>
<Avatar image={`http://localhost:5000/${props.userImage}`} />
</div>
<h2>{props.name}</h2>
</Link>
</div>
</li>
);
};
export default UserSearchItem;
<file_sep>import React from "react";
import { NavLink } from "react-router-dom";
import { useContext } from "react";
import { AuthContext } from "../../context/auth-context";
import NavLinks from "./NavLinks";
import classes from "./Navigation.module.css";
const Navigation = () => {
const ctx = useContext(AuthContext);
return (
<div className={classes.container}>
<div className={classes.logo}>
<NavLink to="/home">
<h1>teezbook</h1>
</NavLink>
</div>
{!ctx.isLoggedIn && (
<div className={classes.linksContainer}>
<NavLinks />
</div>
)}
</div>
);
};
export default Navigation;
<file_sep>import React from "react";
import Avatar from "../../shared/components/UIElements/Avatar";
import { Link } from "react-router-dom";
import classes from "./FriendItem.module.css";
import LoadingSpinner from "../../shared/components/UIElements/LoadingSpinner";
import { useHttpClient } from "../../shared/hooks/use-http";
import { AuthContext } from "../../shared/context/auth-context";
import { useContext } from "react";
const FriendItem = (props) => {
const { isLoading, sendRequest } = useHttpClient();
const ctx = useContext(AuthContext);
const unfriendHandler = async () => {
if (ctx.userId) {
const payload = { person_1_id: ctx.userId, person_2_id: props.userId };
try {
await sendRequest(
`http://localhost:5000/api/users/unfriend`,
"POST",
JSON.stringify(payload),
{ "Content-Type": "application/json" }
);
props.refresh();
} catch (error) {}
}
};
return (
<li className={classes.container}>
<div className={classes.info}>
<Link to={`/profile/${props.userId}`}>
<div className={classes.photo}>
<Avatar image={`http://localhost:5000/${props.userImage}`} />
</div>
<h2>{props.name}</h2>
</Link>
</div>
{isLoading && <LoadingSpinner />}
{!isLoading && (
<div className={classes.btns}>
<button className={classes.dec} onClick={unfriendHandler}>
Unfriend
</button>
<button className={classes.acc}> Send a message </button>
</div>
)}
</li>
);
};
export default FriendItem;
<file_sep>import React from "react";
import { useState } from "react";
import { Link } from "react-router-dom";
import ImageUpload from "../../shared/components/FormElements/ImageUpload";
import LoadingSpinner from "../../shared/components/UIElements/LoadingSpinner";
import Input from "../../shared/components/FormElements/Input";
import Card from "../../shared/components/UIElements/Card";
import { useForm } from "../../shared/hooks/form-hook";
import {
VALIDATOR_EMAIL,
VALIDATOR_MINLENGTH,
VALIDATOR_REQUIRE,
} from "../../shared/util/validators";
import { useHttpClient } from "../../shared/hooks/use-http";
import { useContext } from "react";
import { AuthContext } from "../../shared/context/auth-context";
import { useHistory } from "react-router";
import classes from "./Auth.module.css";
const Auth = () => {
const history = useHistory();
const ctx = useContext(AuthContext);
const [isLoginMode, setIsLogInMode] = useState(true);
const { sendRequest, isLoading, error, clearError } = useHttpClient();
const [formState, inputHandler, setFormData] = useForm(
{
email: {
value: "",
isValid: false,
},
password: {
value: "",
isValid: false,
},
},
false
);
const LoginHandler = () => {
clearError();
setFormData({
...formState.inputs,
name: undefined,
image:undefined
});
setIsLogInMode(true);
};
const signUpHandler = () => {
clearError() ;
setFormData({
...formState.inputs,
name: {
value: "",
isValid: false,
},
image: {
value: "",
isValid: false,
},
});
setIsLogInMode(false);
};
const loginSubmitHandler = async (event) => {
event.preventDefault();
const user = {
email: formState.inputs.email.value,
password: formState.inputs.password.value,
};
try {
clearError();
const response = await sendRequest(
"http://localhost:5000/api/users/signin",
"POST",
JSON.stringify(user),
{ "Content-Type": "application/json" }
);
clearError();
ctx.login(response.userId, response.token);
history.push("/home");
} catch (error) {}
};
const signUpSubmitHandler = async (event) => {
event.preventDefault();
const formData = new FormData() ;
formData.append("name",formState.inputs.name.value) ;
formData.append("email",formState.inputs.email.value) ;
formData.append("password",formState.inputs.password.value) ;
formData.append("image",formState.inputs.image.value)
console.log(formState.inputs.image.value) ;
const user = {
name: formState.inputs.name.value,
email: formState.inputs.email.value,
password: <PASSWORD>,
};
try {
clearError();
const response = await sendRequest(
"http://localhost:5000/api/users/signup",
"POST",
formData
);
clearError();
ctx.login(response.userId, response.token);
history.push("/home");
} catch (error) {}
};
return (
<div className={classes.container}>
<div className={classes.info}>
<h1 className={classes.header}>teezBook</h1>
<p className={classes.para}>
Teezbook helps you connect and share with the people in your life.
</p>
</div>
<div className={classes.form}>
{isLoading && <LoadingSpinner />}
{error && <h1 className={classes.warn}> {error} </h1>}
{!isLoginMode && (
<Card className={classes.authCard}>
<div className={classes["signup-info"]}>
<h2>Sign up</h2>
<p>it's quick and easy.</p>
</div>
<div className={classes.line}></div>
<form onSubmit={signUpSubmitHandler}>
<Input
element="input"
id="name"
type="text"
validators={[VALIDATOR_REQUIRE()]}
errorText="Please enter a name."
placeholder="Enter your name."
onInput={inputHandler}
/>
<Input
element="input"
id="email"
type="text"
validators={[VALIDATOR_EMAIL()]}
errorText="Please enter a valid email."
placeholder="Enter your email."
onInput={inputHandler}
/>
<Input
element="input"
id="password"
type="password"
validators={[VALIDATOR_MINLENGTH(6)]}
errorText="Please enter a valid password (at least 6 characters)."
placeholder="Enter your password."
onInput={inputHandler}
/>
<ImageUpload
id="image"
center
onInput={inputHandler}
errorText="please provide an image"
/>
<div className={classes.line}></div>
<button
type="submit"
disabled={!formState.isValid}
className={formState.isValid ? classes.newAcc2 : classes.diable}
>
Create new account
</button>
<Link to="/" onClick={LoginHandler}>login instead</Link>
</form>
</Card>
)}
{isLoginMode && (
<Card>
<form onSubmit={loginSubmitHandler}>
<Input
element="input"
id="email"
type="text"
validators={[VALIDATOR_EMAIL()]}
errorText="Please enter an email."
placeholder="Enter your email."
onInput={inputHandler}
/>
<Input
element="input"
id="password"
type="password"
validators={[VALIDATOR_MINLENGTH(6)]}
errorText="Please enter a valid password (at least 6 character)."
placeholder="Enter your password."
onInput={inputHandler}
/>
<button type="submit" disabled={!formState.isValid}>
Log In
</button>
<div className={classes.line}></div>
<button className={classes.newAcc} onClick={signUpHandler}>
Create New Account
</button>
</form>
</Card>
)}
</div>
</div>
);
};
export default Auth;
<file_sep>import React from "react";
import { createContext } from "react";
export const AuthContext = createContext({
isLoggedIn: false,
userId: undefined,
token: undefined,
login: (uid,token,expirationDate) => {},
logout: () => {},
});
<file_sep>const express = require("express");
const bodyParser = require("body-parser");
const fs = require("fs");
const path = require("path");
const HttpError = require("./models/http-error");
const userRoutes = require("./routes/user-routes");
const postsRoutes = require("./routes/posts-routes");
const app = express();
const optionsMiddleware = (req,res,next) => {
if (req.method === "OPTIONS") {
return res.status(200).json();
}
next();
} ;
app.use(bodyParser.json());
app.use("/uploads/images", express.static(path.join("uploads", "images")));
app.use((req, res, next) => {
res.setHeader("Access-Control-Allow-Origin", "*");
res.setHeader(
"Access-Control-Allow-Headers",
"Origin,X-Requested-With,Content-Type,Accept,Authorization"
);
res.setHeader("Access-Control-Allow-Methods", "POST ,GET ,PATCH ,DELETE");
next();
});
app.use(optionsMiddleware) ;
app.use("/api/users", userRoutes);
app.use("/api/posts", postsRoutes);
app.use((req, res, next) => {
throw new HttpError("Could not find this route.", 404);
});
app.use((error, req, res, next) => {
if (res.headerSent) {
return next(error);
}
res.status(error.code || 500);
res.json({ message: error.message || "An unknown error occurred!" });
});
app.listen(5000);
<file_sep>import React, { useState } from "react";
import NewPost from "../../post/components/NewPost";
import PostsList from "../../post/components/PostsList";
import { AuthContext } from "../../shared/context/auth-context";
import { useContext } from "react";
import { useEffect } from "react";
import { useHttpClient } from "../../shared/hooks/use-http";
import LoadingSpinner from "../../shared/components/UIElements/LoadingSpinner";
import classes from "./Home.module.css";
const Home = () => {
const [posts, setPosts] = useState(null);
const [friendsIds, setFriendsIds] = useState(false);
const ctx = useContext(AuthContext);
const { isLoading, sendRequest } = useHttpClient();
const getPosts = async (id) => {
let allPosts = [];
console.log("here");
try {
const friendsIds = await sendRequest(
`http://localhost:5000/api/users/${id}/friends`
);
console.log(friendsIds);
if (friendsIds.length !== 0) {
setFriendsIds(true);
}
let posts;
if (friendsIds.length > 0) {
const promises = friendsIds.map((id_) => {
return new Promise(async (resolve, reject) => {
try {
const posts = await sendRequest(
`http://localhost:5000/api/users/${id_}/posts`
);
console.log(posts);
return resolve(posts);
} catch (error) {
return reject(error);
}
});
});
posts = await Promise.all(promises);
console.log("friends posts ", posts);
}
console.log(posts);
if (posts) {
let imagePromises;
posts.forEach((friendPosts) => {
console.log(friendPosts);
imagePromises = friendPosts.map((post) => {
console.log(post);
return new Promise(async (resolve, reject) => {
try {
console.log(post);
const info = await sendRequest(
`http://localhost:5000/api/users/${post.user_id}/info`
);
post["userImage"] = info.userImage;
resolve();
} catch (error) {
return reject(error);
}
});
});
});
await Promise.all(imagePromises);
}
try {
const info = await sendRequest(
`http://localhost:5000/api/users/${id}/info`
);
const myposts = await sendRequest(
`http://localhost:5000/api/users/${id}/posts`
);
console.log(myposts);
console.log(info);
myposts.forEach((element) => {
element["userImage"] = info.userImage;
});
myposts.forEach((post) => allPosts.push(post));
posts.forEach((friendPosts) => {
friendPosts.forEach((post) => {
allPosts.push(post);
});
});
console.log(allPosts);
allPosts.sort((x, y) => {
return +new Date(y.post_date) - +new Date(x.post_date);
});
setPosts(allPosts) ;
} catch (error) {}
} catch (error) {}
};
const refresh = async (id) => {
getPosts(ctx.userId);
};
useEffect(() => {
const id = ctx.userId;
if (id) {
getPosts(id);
}
}, [ctx]);
return (
<div className={classes.container}>
<NewPost refresh={refresh} />
<div className={classes.postsContainer}>
{!isLoading && posts && <PostsList posts={posts} refresh={refresh} />}
{isLoading && <LoadingSpinner />}
{!isLoading && posts && friendsIds && posts && posts.length === 0 && (
<h1>No posts yet.</h1>
)}
{!isLoading && !posts && <h1>No posts yet.</h1>}
{!isLoading && posts && posts.length === 0 && <h1>No posts yet.</h1>}
</div>
</div>
);
};
export default Home;
<file_sep>import React from "react";
import { Fragment } from "react";
import Auth from "../src/user/pages/Auth";
import PostsList from "./post/components/PostsList";
import CommentsList from "./post/components/CommentsList";
import FullPost from "../src/post/pages/FullPost";
import Navigation from "./shared/components/Navigation/Navigation";
import Layout from "./shared/components/UIElements/Layout";
import Profile from "./user/pages/Profile";
import Friends from "./user/pages/Friends";
import Search from "./user/pages/Search";
import NewPost from "./post/components/NewPost";
import { AuthContext } from "./shared/context/auth-context";
import useAuth from "./shared/hooks/use-auth";
import Home from "./user/pages/Home";
import {
BrowserRouter as Router,
Route,
Redirect,
Switch,
} from "react-router-dom";
const App = () => {
const { token, login, logout, userId } = useAuth();
let routes;
const storedData = JSON.parse(localStorage.getItem("userData"));
if (
(storedData &&
storedData.token &&
new Date(storedData.expiration) > new Date()) ||
token
) {
routes = (
<Switch>
<Route path="/home" exact>
<Layout>
<Home />
</Layout>
</Route>
<Route path={"/profile/friends"} exact>
<Layout>
<Friends />
</Layout>
</Route>
<Route path={"/profile/:id"}>
<Layout>
<Profile />
</Layout>
</Route>
<Route path={`/post/:id`} exact>
<Layout>
<FullPost />
</Layout>
</Route>
<Route path="/search">
<Layout>
<Search />
</Layout>
</Route>
<Redirect to="/home"></Redirect>
</Switch>
);
} else {
routes = (
<Switch>
<Route path={"/"} exact>
<Auth />
</Route>
<Redirect to="/" />
</Switch>
);
}
return (
<AuthContext.Provider
value={{
isLoggedIn: false,
userId: userId,
token: token,
login: login,
logout: logout,
}}
>
<Router>{routes}</Router>
</AuthContext.Provider>
);
};
export default App;
| 2355f5823dfd2c60c10f4629a78a45fe79c334c6 | [
"JavaScript"
] | 15 | JavaScript | Khalid-Eltawagny/EgyFace | 85325b42a63f1de0ca618cd6757ee6a34e311a6d | d82e1213e1afa2c15acd24c3bb0f7c2229c737d3 |
refs/heads/master | <file_sep>convert_images_to_pdf
=====================
Convert images to PDFs
<file_sep>#!/bin/bash
read -p "Enter the name you'd like for your files: " FILENAME
for i in pdfs/*; do
FILE=$(basename "$i")
NUMBER=`ls pdfs/$FILE | sed -e s/[^0-9]//g`
mv pdfs/$FILE pdfs/$FILENAME\_$NUMBER\.pdf
done
<file_sep>#!/bin/bash
rm images/*.ignore
rm pdfs/*.ignore
for i in images/*; do
FILE=$(basename "$i")
echo Converting $FILE
convert images/$FILE/* -limit memory 128MiB -limit map 256MiB pdfs/$FILE.pdf
done
| 0441ce6dd088b5c2e8f7ca10daa6750ace0fe2a6 | [
"Markdown",
"Shell"
] | 3 | Markdown | ariaBennett/convert_images_to_pdf | 593850aa90d80f331fe5f1c841857bf2dc55aaeb | abfeb4e321b22f97652d4cf2dfef20cace91278c |
refs/heads/master | <repo_name>ScizorsBLBC/Minimum-Wage-Calculator<file_sep>/script.js
// Now we need to define each state and its minimum wage
const federalWage = 7.25;
const stateYouLiveInElement = document.querySelector('#stateYouLiveIn');
const numWeeksWorkedElement = document.querySelector('#numWeeksWorked');
const hoursPerWeekWorkedElement = document.querySelector('#hoursPerWeek');
const answerElement = document.querySelector('#answer');
const wages = [
{ name: 'Alabama', abbreviation: 'AL' },
{ name: 'Alaska', abbreviation: 'AK', wage: 9.84 },
{ name: 'Arizona', abbreviation: 'AZ', wage: 10.50 },
{ name: 'Arkansas', abbreviation: 'AR', wage: 8.5 },
{ name: 'California', abbreviation: 'CA', wage: 11 },
{ name: 'Colorado', abbreviation: 'CO', wage: 10.20 },
{ name: 'Connecticut', abbreviation: 'CT', wage: 10.10 },
{ name: 'Delaware', abbreviation: 'DE', wage: 8.25 },
{ name: 'District Of Columbia', abbreviation: 'DC', wage: 12.50 },
{ name: 'Florida', abbreviation: 'FL', wage: 8.25 },
{ name: 'Georgia', abbreviation: 'GA', wage: 5.15 },
{ name: 'Hawaii', abbreviation: 'HI', wage: 10.10 },
{ name: 'Idaho', abbreviation: 'ID', wage: federalWage },
{ name: 'Illinois', abbreviation: 'IL', wage: 8.25 },
{ name: 'Indiana', abbreviation: 'IN', wage: federalWage },
{ name: 'Iowa', abbreviation: 'IA', wage: federalWage },
{ name: 'Kansas', abbreviation: 'KS', wage: federalWage },
{ name: 'Kentucky', abbreviation: 'KY', wage: federalWage },
{ name: 'Louisiana', abbreviation: 'LA' },
{ name: 'Maine', abbreviation: 'ME', wage: 10 },
{ name: 'Maryland', abbreviation: 'MD', wage: 9.25 },
{ name: 'Massachusetts', abbreviation: 'MA', wage: 11 },
{ name: 'Michigan', abbreviation: 'MI', wage: 9.25 },
{ name: 'Minnesota', abbreviation: 'MN', wage: 9.65 },
{ name: 'Mississippi', abbreviation: 'MS' },
{ name: 'Missouri', abbreviation: 'MO', wage: 7.85 },
{ name: 'Montana', abbreviation: 'MT', wage: 8.30 },
{ name: 'Nebraska', abbreviation: 'NE', wage: 9 },
{ name: 'Nevada', abbreviation: 'NV', wage: 8.25 },
{ name: 'New Hampshire', abbreviation: 'NH', wage: federalWage },
{ name: 'New Jersey', abbreviation: 'NJ', wage: 8.60 },
{ name: 'New Mexico', abbreviation: 'NM', wage: 7.5 },
{ name: 'New York', abbreviation: 'NY', wage: 10.40 },
{ name: 'North Carolina', abbreviation: 'NC', wage: federalWage },
{ name: 'North Dakota', abbreviation: 'ND', wage: federalWage },
{ name: 'Ohio', abbreviation: 'OH', wage: 8.30 },
{ name: 'Oklahoma', abbreviation: 'OK', wage: federalWage },
{ name: 'Oregon', abbreviation: 'OR', wage: 10.25 },
{ name: 'Pennsylvania', abbreviation: 'PA', wage: federalWage },
{ name: 'Rhode Island', abbreviation: 'RI', wage: 10.10 },
{ name: 'South Carolina', abbreviation: 'SC' },
{ name: 'South Dakota', abbreviation: 'SD', wage: 8.85 },
{ name: 'Tennessee', abbreviation: 'TN' },
{ name: 'Texas', abbreviation: 'TX', wage: federalWage },
{ name: 'Utah', abbreviation: 'UT', wage: federalWage },
{ name: 'Vermont', abbreviation: 'VT', wage: 10.50 },
{ name: 'Virgin Islands', abbreviation: 'VI', wage: federalWage },
{ name: 'Virginia', abbreviation: 'VA', wage: federalWage },
{ name: 'Washington', abbreviation: 'WA', wage: 11.50 },
{ name: 'West Virginia', abbreviation: 'WV', wage: 8.75 },
{ name: 'Wisconsin', abbreviation: 'WI', wage: federalWage },
{ name: 'Wyoming', abbreviation: 'WY', wage: 5.15 },
];
// Add option element for each state
// Loop through every state
wages.forEach((stateWageObject) => {
// - Create an option tag for each state
const optionElement = document.createElement('option');
// - Set property/values on option element
optionElement.innerText = stateWageObject.name;
optionElement.value = stateWageObject.abbreviation;
// - append that within our <select></select>
const stateYouLiveIn = document.querySelector('#stateYouLiveIn');
stateYouLiveIn.appendChild(optionElement);
});
// All this happens upon button click
const numWeeksWorkedDiv = document.querySelector('.numWeeksWorkedDiv');
const onButtonClick = () => {
let isValid = true
// Need variable for num of weeks per year worked
const numWeeksWorked = Number(numWeeksWorkedElement.value);
console.log(typeof numWeeksWorked);
numWeeksWorkedDiv.classList.remove("invalidInput");
const numWeeksWorkedError = document.querySelector('#numWeeksWorkedError');
if (numWeeksWorked > 52 || numWeeksWorked < 1) {
numWeeksWorkedDiv.classList.add("invalidInput");
numWeeksWorkedError.innerText = 'ERROR: Enter a number between 1 and 52'
isValid = false;
} else {
numWeeksWorkedError.innerText = '';
}
// I need the variable for how many hours per week worked
const hoursPerWeekWorkedDiv = document.querySelector('.hoursPerWeekWorkedDiv');
const hoursPerWeekWorked = Number(hoursPerWeekWorkedElement.value);
console.log(typeof hoursPerWeekWorked, hoursPerWeekWorked);
hoursPerWeekWorkedDiv.classList.remove("invalidInput");
const hoursPerWeekWorkedError = document.querySelector('#hoursPerWeekError');
if (hoursPerWeekWorked > 168 || hoursPerWeekWorked < 1) {
hoursPerWeekWorkedDiv.classList.add("invalidInput");
hoursPerWeekWorkedError.innerText = 'ERROR: Enter a number between 1 and 168'
isValid = false;
} else {
hoursPerWeekWorkedError.innerText = '';
}
// Need variable for which state you live in
const stateYouLiveIn = stateYouLiveInElement.value;
const stateYouLiveInDiv = document.querySelector('.stateYouLiveInDiv');
console.log(typeof stateYouLiveIn, stateYouLiveIn);
stateYouLiveInDiv.classList.remove("invalidInput");
const stateYouLiveInError = document.querySelector('#stateYouLiveInError');
if (stateYouLiveIn === '') {
stateYouLiveInDiv.classList.add("invalidInput");
stateYouLiveInError.innerText = 'ERROR: Please select your state from the drop down menu'
isValid = false;
} else {
stateYouLiveInError.innerText = '';
}
// When we know the state, how do we get the wage value for that state?
const minimumWageStateObject = wages.find((minimumWageObject) => {
return stateYouLiveIn === minimumWageObject.abbreviation;
});
console.log(minimumWageStateObject);
// What is the result? numOfWeeksWorked * hoursPerWeekWorked * minimumWage
let minimumWage;
// minimumWageStateObject.wage;
if (minimumWageStateObject !== undefined) {
minimumWage = minimumWageStateObject.wage;
if (minimumWage === undefined) {
minimumWage = federalWage;
}
};
// how to Format the answer to include the numbers as us dollars???
// display the result on screen in dollars
answerElement.classList.remove("thereWasAnError");
if (isValid === true) {
answerElement.innerText = "$" + (numWeeksWorked * hoursPerWeekWorked * minimumWage).toLocaleString(undefined, {minimumFractionDigits:2, maximumFractionDigits:2});
} else {
answerElement.classList.add("thereWasAnError");
answerElement.innerText = 'ERROR: Please fix all errors above';
}
};
// what happens when they click the button in each case
const htmlElement= document.querySelector('button');
htmlElement.addEventListener('click', onButtonClick);
console.log(htmlElement);
// Disable button until all inputs are filled
const buttonElement = document.querySelector('#button');
// set disabled state to true
const BUTTON_TEXT_ENABLED = "Find out your minimum wage salary";
const BUTTON_TEXT_DISABLED = "Enter info above and select your state";
buttonElement.disabled = true;
buttonElement.innerText = BUTTON_TEXT_DISABLED;
// set event listener for inputs to know when there are key presses and when the drop down menu has been set
//
function inputsHaveValues() {
// if inputsHaveValues === false button is disabled
if (numWeeksWorkedElement.value === ''
|| hoursPerWeekWorkedElement.value === ''
|| stateYouLiveInElement.value === ''
) {
buttonElement.disabled = true;
buttonElement.innerText = BUTTON_TEXT_DISABLED;
} else {
buttonElement.disabled = false;
buttonElement.innerText = BUTTON_TEXT_ENABLED;
}
};
numWeeksWorkedElement.addEventListener('change', inputsHaveValues);
hoursPerWeekWorkedElement.addEventListener('change', inputsHaveValues);
stateYouLiveInElement.addEventListener('change', inputsHaveValues);
// Make inputs red so you can see where to input info
// Make the answer have a dollar sign before it.
| 1df5a2cd46726a4fe708ff25cc15ed6fa52359a8 | [
"JavaScript"
] | 1 | JavaScript | ScizorsBLBC/Minimum-Wage-Calculator | fb1fc9a8de87dfc4c8d570e80a0b92eed506427f | 35a3696e0c86f8f021b505b78b8a50d736230f58 |
refs/heads/master | <repo_name>hottabxp/MiniLogger<file_sep>/README.md
# MiniLogger
Мини библиотека для ведения логов работы программы (.Net)
<file_sep>/LogTest/logTest.cs
using System;
using System.IO;
using MiniLogger;
namespace LogTest
{
class MainClass
{
public static void Main (string[] args)
{
start ();
}
// <div> </div>
public static void start()
{
Log log = new Log ("log.txt");
string line = File.ReadAllText ("a.txt");
//Console.WriteLine (line.ToString());
Console.WriteLine (line.Length.ToString());
int i1, i2 = 0;
string str;
Console.WriteLine ((line.Split('=').Length-1)/6);
int cnt = ((line.Split('=').Length-1)/6);
FileStream f = new FileStream ("1.txt", FileMode.Append);
StreamWriter sw = new StreamWriter (f);
try{
for (int i = 0; i < cnt; i++)
{
//int count = str.ToLower().Split('a').Length - 1;
i1 = line.IndexOf ("<div",i2);
i2 = line.IndexOf ("</div>"+i1);
str = line.Substring(i1,i2);
//line = line.Remove(0,i2);
Console.WriteLine (str);
Console.WriteLine ("{0} {1}", i1.ToString(),i2.ToString());
//sw.WriteLine(str);
}
sw.Close();
}
catch (Exception ex)
{
log.write(ex.Message);
Console.WriteLine ("-------");
Console.WriteLine (ex.Message);
}
}
}
}
<file_sep>/LOG/LOG.cs
using System;
using System.IO;
namespace MiniLogger
{
public class Log
{
FileStream fs;
public void log(string filelog)
{
//Console.WriteLine("Log test!");
}
public Log(string filelog)
{
fs = new FileStream (filelog, FileMode.Append);
}
public void write(string message)
{
using(StreamWriter sw = new StreamWriter(fs))
{
sw.WriteLine (DateTime.Now+ " " + message);
}
}
}
}
| 599b1de887a2905b02f564c58a39d3f31fa3caef | [
"Markdown",
"C#"
] | 3 | Markdown | hottabxp/MiniLogger | 449b500e561dbb449064490634d2a8b90b11a3da | 05f113a1183f5369cfc5e1326d1796c21a532d83 |
refs/heads/master | <file_sep><?php
namespace App\Entity;
use App\Config;
use App\Db\Connection;
trait DbEntity
{
/**
*
* @return Connection
*/
private static function getConnection() : Connection
{
return Config::getConfig('db_connection');
}
public static function findBy(array $where)
{
}
public static function findOneBy($where)
{
$table = static::$table;
if (!$table) {
throw new \RuntimeException('Specify table property in ' . get_class($this) . '.');
}
self::getConnection()->connect();
$select = "SELECT * FROM {$table}";
if (!is_array($where)) {
$where = [static::$primaryKey => $where];
}
if (!empty($where)) {
$select .= " WHERE ";
$wheres = [];
foreach ($where as $col => $cond) {
$cond = self::getConnection()->escape($cond);
$wheres[] = "{$col} = {$cond}";
}
$select .= implode(' AND ', $wheres);
}
$row = self::getConnection()->fetchRow($select);
if (!empty($row)) {
$object = new static;
foreach ($row as $key => $value) {
$object->$key = $value;
}
return $object;
}
}
public function belongsTo(string $entity, string $foreignKey)
{
/** @var Entity $entityObject */
$entityObject = new $entity;
if (!$entityObject instanceof Entity) {
throw \RuntimeException("{$entity} is not an Entity.");
}
return $entityObject::findOneBy([$entityObject::$primaryKey, $this->{$foreignKey}]);
}
}
<file_sep><?php
namespace App\Entity;
abstract class Entity
{
use DbEntity;
public static $table;
public static $primaryKey = 'id';
}
<file_sep><?php
namespace App\Entity;
class CustomerAddress extends Entity
{
public static $table = 'customer_address';
public static $primaryKey = 'customer_address_id';
public $customer_address_id;
public $customer_id;
public $firstname;
public $lastname;
public $street_1;
public $street_2;
public $postcode;
public $city;
public $region;
public $country_id;
public $created_at;
public $updated_at;
public function customer()
{
return $this->belongsTo(Customer::class, 'customer_id');
}
}
<file_sep><?php
namespace App\Entity;
class Customer extends Entity
{
public static $table = 'customer';
public static $primaryKey = 'customer_id';
public $customer_id;
public $email;
public $firstname;
public $lastname;
public $gender;
public $dob;
public $password;
public $created_at;
public $updated_at;
}
| a9fa36cf60553e1dc39d7820e0801d3f95aa3f30 | [
"PHP"
] | 4 | PHP | Khataz/iut2018-exercice2-php | ece94b3e2e6ffee7fad07e97b01b9f5d543802bc | ea7f4045e5a87be50dbaba4f391c7c7df5c4c64a |
refs/heads/master | <file_sep>import os
import pymongo
from flask import Flask, request, g, Response, jsonify, abort
import pymongo
app = Flask(__name__)
import json
from json import dumps, loads
from watson_developer_cloud import VisualRecognitionV3
import ibm_watson
service = ibm_watson.AssistantV2(iam_apikey='<KEY>',version='2019-02-28',url='https://gateway.watsonplatform.net/assistant/api')
session = service.create_session(assistant_id='b81e97e1-9d6f-4241-9893-10f10bfcd3b2').get_result()
visual_recognition = VisualRecognitionV3('2018-03-19',iam_apikey='<KEY>')
client = pymongo.MongoClient("mongodb+srv://cornell_hack:cornell@cluster0-cpodz.mongodb.net/test?retryWrites=true&w=majority")
db_name = client.cornell_DB
qnaCollection = db_name.qna
def db_util(qry):
# client = pymongo.MongoClient("mongodb+srv://cornell_hack:cornell@cluster0-cpodz.mongodb.net/test?retryWrites=true&w=majority")
# db_name = client.cornell_DB
# qnaCollection = db_name.qna
query = {"class": qry}
question = qnaCollection.find_one(query)
print("got response from mongo:",type(question))
print("val check----:",question['questions'])
return question['questions']
#return Response(json.dumps(str(question['questions'])), status=200, mimetype='application/json')
@app.route("/api/v1/text/predict/", methods=["POST"])
def classify_text():
params = request.get_json()
chat_text = params.get('text')
print("chat side:",chat_text,type(chat_text))
bot_reply = service.message(assistant_id='b81e97e1-9d6f-4241-9893-10f10bfcd3b2',session_id=session['session_id'],input={'message_type': 'text','text': chat_text }).get_result()
bot_reply = bot_reply['output']['generic'][0]['text']
qnaCollection.insert_one({"questions":bot_reply,"answers":chat_text})
#return Response(json.dumps(bot_reply), status=200, mimetype='application/json')
return dumps(bot_reply)
@app.route("/api/v1/image/predict/", methods=["POST"])
def predict():
params = request.get_json()
image = params.get('image')
image_ = './test.jpg'
with open(image_, 'rb') as images_file:
classes = visual_recognition.classify(
images_file,
threshold='0.6',
classifier_ids='CasualityModel_222197479').get_result()
#print(json.dumps(classes, indent=2))
res = classes['images'][0]['classifiers'][0]['classes']
if not res:
print("others")
topic = "others"
#print(json.dumps(classes['images'][0]['classifiers'][0]['classes'][0]['class'], indent=2))
else:
print(json.dumps(res[0]['class'], indent=2))
topic = res[0]['class']
#return dumps(db_util(topic))
return Response(json.dumps(db_util(topic)), status=200, mimetype='application/json')
if __name__ == "__main__":
port = int(os.environ.get("PORT", 5000))
app.run(host='0.0.0.0', port=port)
<file_sep>import json
from watson_developer_cloud import VisualRecognitionV3
visual_recognition = VisualRecognitionV3('2018-03-19',iam_apikey='<KEY>')
with open('./kitty.jpg', 'rb') as images_file:
classes = visual_recognition.classify(
images_file,
threshold='0.6',
classifier_ids='CasualityModel_222197479').get_result()
#print(json.dumps(classes, indent=2))
res = classes['images'][0]['classifiers'][0]['classes']
if not res:
print("others")
#print(json.dumps(classes['images'][0]['classifiers'][0]['classes'][0]['class'], indent=2))
else:
print(json.dumps(res[0]['class'], indent=2))<file_sep>$("#upload").submit(function(event) {
var formData = new FormData();
console.log("client image upload")
formData.append("photo", $('[name="file"]')[0].files[0]);
event.stopPropagation();
event.preventDefault();
$.ajax({
url: $(this).attr("action"),
data: formData,
processData: false,
contentType: false,
type: 'POST',
success: function(data) {
alert(data);
}
});
return false;
});
var textarea = document.getElementById("chattext");
try {
textarea.addEventListener("keydown", keyPress, false);
} catch (e) {
textarea.attachEvent("onkeydown", keyPress);
}
function keyPress(e) {
if (e.keyCode === 13) {
e.preventDefault();
var conversation = document.getElementById('chattext').value;
messageContainer.innerHTML += `<div class="user">User:${conversation} <div id="datetime11"></div> </div>`;
data = "Bot is typing...";
messageContainer.innerHTML += `<div><img src="bot.png"></img><div class="bot"> ${data}</div></div>`;
document.getElementById("datetime11").innerHTML = dt.toLocaleTimeString();
location.href = '#edge'
setTimeout(function(){
getResponse (conversation);
}, 1000);
document.getElementById('chattext').value = "";
document.getElementById('chattext').focus();
//$("#chattext").focus();
//console.log("click check ----"+ $("#chattext").click());
//$("chattext").click();
//document.getElementById('chatarea').click();
//return false;
} else {
return;
}
}
function ReplaceContentInContainer(botclass,content) {
var container = document.getElementsByClassName(botclass);
var last = container[container.length -1];
//var last = document.querySelector(id+":last-child");
console.log("continer check:",last)
last.innerHTML = content;
}
// (function() {
// var txt = document.getElementById('chattext');
// txt.addEventListener('keypress', function(event) {
// if (event.keyCode == 13) {
// var conversation = document.getElementById('chattext').value;
// messageContainer.innerHTML += `<div class="user">User:${conversation} <div id="datetime11"></div> </div>`;
// document.getElementById("datetime11").innerHTML = dt.toLocaleTimeString();
// location.href = '#edge'
// getResponse (conversation);
// conversation = ''
// }
// });
// }());
const messageContainer = document.querySelector('.messages')
var dt = new Date();
//document.getElementById("datetime").innerHTML = dt.toLocaleTimeString();
var langs =
[['Afrikaans', ['af-ZA']],
['Bahasa Indonesia',['id-ID']],
['Bahasa Melayu', ['ms-MY']],
['Català', ['ca-ES']],
['Čeština', ['cs-CZ']],
['Deutsch', ['de-DE']],
['English', ['en-AU', 'Australia'],
['en-CA', 'Canada'],
['en-IN', 'India'],
['en-NZ', 'New Zealand'],
['en-ZA', 'South Africa'],
['en-GB', 'United Kingdom'],
['en-US', 'United States']],
['Español', ['es-AR', 'Argentina'],
['es-BO', 'Bolivia'],
['es-CL', 'Chile'],
['es-CO', 'Colombia'],
['es-CR', 'Costa Rica'],
['es-EC', 'Ecuador'],
['es-SV', 'El Salvador'],
['es-ES', 'España'],
['es-US', 'Estados Unidos'],
['es-GT', 'Guatemala'],
['es-HN', 'Honduras'],
['es-MX', 'México'],
['es-NI', 'Nicaragua'],
['es-PA', 'Panamá'],
['es-PY', 'Paraguay'],
['es-PE', 'Perú'],
['es-PR', 'Puerto Rico'],
['es-DO', 'República Dominicana'],
['es-UY', 'Uruguay'],
['es-VE', 'Venezuela']],
['Euskara', ['eu-ES']],
['Français', ['fr-FR']],
['Galego', ['gl-ES']],
['Hrvatski', ['hr_HR']],
['IsiZulu', ['zu-ZA']],
['Íslenska', ['is-IS']],
['Italiano', ['it-IT', 'Italia'],
['it-CH', 'Svizzera']],
['Magyar', ['hu-HU']],
['Nederlands', ['nl-NL']],
['Norsk bokmål', ['nb-NO']],
['Polski', ['pl-PL']],
['Português', ['pt-BR', 'Brasil'],
['pt-PT', 'Portugal']],
['Română', ['ro-RO']],
['Slovenčina', ['sk-SK']],
['Suomi', ['fi-FI']],
['Svenska', ['sv-SE']],
['Türkçe', ['tr-TR']],
['български', ['bg-BG']],
['Pусский', ['ru-RU']],
['Српски', ['sr-RS']],
['한국어', ['ko-KR']],
['中文', ['cmn-Hans-CN', '普通话 (中国大陆)'],
['cmn-Hans-HK', '普通话 (香港)'],
['cmn-Hant-TW', '中文 (台灣)'],
['yue-Hant-HK', '粵語 (香港)']],
['日本語', ['ja-JP']],
['Lingua latīna', ['la']]];
// for (var i = 0; i < langs.length; i++) {
// select_language.options[i] = new Option(langs[i][0], i);
// }
// select_language.selectedIndex = 6;
// updateCountry();
// select_dialect.selectedIndex = 6;
showInfo('info_start');
// function updateCountry() {
// for (var i = select_dialect.options.length - 1; i >= 0; i--) {
// select_dialect.remove(i);
// }
// var list = langs[select_language.selectedIndex];
// for (var i = 1; i < list.length; i++) {
// select_dialect.options.add(new Option(list[i][1], list[i][0]));
// }
// select_dialect.style.visibility = list[1].length == 1 ? 'hidden' : 'visible';
// }
var create_email = false;
var final_transcript = '';
var recognizing = false;
var ignore_onend;
var start_timestamp;
if (!('webkitSpeechRecognition' in window)) {
upgrade();
} else {
start_button.style.display = 'inline-block';
var synth = window.speechSynthesis
var recognition = new webkitSpeechRecognition();
recognition.continuous = true;
recognition.interimResults = true;
recognition.onstart = function() {
recognizing = true;
showInfo('info_speak_now');
start_img.src = 'mic-animate.gif';
};
recognition.onerror = function(event) {
if (event.error == 'no-speech') {
start_img.src = 'mic.gif';
showInfo('info_no_speech');
ignore_onend = true;
}
if (event.error == 'audio-capture') {
start_img.src = 'mic.gif';
showInfo('info_no_microphone');
ignore_onend = true;
}
if (event.error == 'not-allowed') {
if (event.timeStamp - start_timestamp < 100) {
showInfo('info_blocked');
} else {
showInfo('info_denied');
}
ignore_onend = true;
}
};
recognition.onend = function() {
recognizing = false;
if (ignore_onend) {
return;
}
start_img.src = 'mic.gif';
if (!final_transcript) {
showInfo('info_start');
return;
}
showInfo('');
if (window.getSelection) {
window.getSelection().removeAllRanges();
var range = document.createRange();
range.selectNode(document.getElementById('final_span'));
window.getSelection().addRange(range);
}
if (create_email) {
create_email = false;
createEmail();
}
};
var reply = text => {
const utter = new SpeechSynthesisUtterance(text)
const voices = speechSynthesis.getVoices()
//utter.voice = voices[10]
synth.speak(utter)
}
recognition.onresult = function(event) {
var interim_transcript = '';
for (var i = event.resultIndex; i < event.results.length; ++i) {
if (event.results[i].isFinal) {
final_transcript += event.results[i][0].transcript;
} else {
interim_transcript += event.results[i][0].transcript;
}
}
res = event.results[0].isFinal;
console.log("start time:"+start_timestamp);
final_transcript = capitalize(final_transcript);
//final_span.innerHTML = "USER:"+linebreak(final_transcript)+"<br />";
//interim_span.innerHTML = linebreak(interim_transcript);
if (final_transcript || interim_transcript) {
showButtons('inline-block');
}
if (res == true && final_transcript!='') {
console.log("Time up");
messageContainer.innerHTML += `<div class="user">User:${final_transcript} <div id="datetime11"></div> </div>`;
document.getElementById("datetime11").innerHTML = dt.toLocaleTimeString();
location.href = '#edge'
data = "Bot is typing...";
messageContainer.innerHTML += `<div><img src="bot.png"></img><div class="bot"> ${data}</div></div>`;
//chatBotResponse.innerHTML = "Bot: "+ getResponse (final_transcript);
setTimeout(function(){
getResponse (final_transcript);
}, 1000);
final_transcript = ''
}
//start_timestamp = event.timeStamp;
return;
};
}
function getResponse1(input){
console.log("from ajax call:"+input);
$.post('/startChat',{
"email": "<EMAIL>",
"message": input
}).done(function(data){
console.log(data);
BootstrapDialog.alert(data);
}).fail(function(xhr, status, error) {
console.log(xhr);
});
}
function getResponse(input){
console.log("from ajax call:"+input);
$.ajax({
type: "POST",
cache: false,
timeout: 5000,
headers: "Access-Control-Allow-Origin: *", // enable cors
data: {"email": "<EMAIL>",
"message": input},
//url: "http://localhost:7000/startChat",
//url: "http://192.168.1.156:7000/startChat",
url: "http://127.0.0.1:7000/startChat",
}).done(function(data){
console.log("Reply from ChatBot:"+data);
//reply(data)
//messageContainer.innerHTML += `<div><img src="bot.png"></img><div class="bot"> ${data}</div></div>`;
//document.getElementsByClassName("bot").innerHTML = data;
ReplaceContentInContainer('bot',data);
location.href = '#edge'
//BootstrapDialog.alert(data);
//return data
}).fail(function(xhr, status, error) {
console.log(xhr);
});
}
function upgrade() {
start_button.style.visibility = 'hidden';
showInfo('info_upgrade');
}
var two_line = /\n\n/g;
var one_line = /\n/g;
function linebreak(s) {
return s.replace(two_line, '<p></p>').replace(one_line, '<br>');
}
var first_char = /\S/;
function capitalize(s) {
return s.replace(first_char, function(m) { return m.toUpperCase(); });
}
function createEmail() {
var n = final_transcript.indexOf('\n');
if (n < 0 || n >= 80) {
n = 40 + final_transcript.substring(40).indexOf(' ');
}
var subject = encodeURI(final_transcript.substring(0, n));
var body = encodeURI(final_transcript.substring(n + 1));
window.location.href = 'mailto:?subject=' + subject + '&body=' + body;
}
function copyButton() {
if (recognizing) {
recognizing = false;
recognition.stop();
}
copy_button.style.display = 'none';
copy_info.style.display = 'inline-block';
showInfo('');
}
function emailButton() {
if (recognizing) {
create_email = true;
recognizing = false;
recognition.stop();
} else {
createEmail();
}
email_button.style.display = 'none';
email_info.style.display = 'inline-block';
showInfo('');
}
function startButton(event) {
if (recognizing) {
recognition.stop();
return;
}
final_transcript = '';
// recognition.lang = select_dialect.value;
recognition.start();
ignore_onend = false;
final_span.innerHTML = '';
interim_span.innerHTML = '';
start_img.src = 'mic-slash.gif';
showInfo('info_allow');
showButtons('none');
start_timestamp = event.timeStamp;
}
function showInfo(s) {
if (s) {
for (var child = info.firstChild; child; child = child.nextSibling) {
if (child.style) {
child.style.display = child.id == s ? 'inline' : 'none';
}
}
info.style.visibility = 'visible';
} else {
info.style.visibility = 'hidden';
}
}
var current_style;
function showButtons(style) {
if (style == current_style) {
return;
}
current_style = style;
copy_button.style.display = 'none';
email_button.style.display = 'none';
copy_info.style.display = 'none';
email_info.style.display = 'none';
}
<file_sep>const express = require('express');
var session = require('express-session');
//var mongo = require('mongodb');
var Promise = require('promise');
const multer = require("multer");
const app = express();
const port = 7000;
const bodyParser = require('body-parser');
var http = require('http');
var path = require("path");
const fs = require("fs");
var querystring = require('querystring');
var userId;
var containerId;
var cors = require('cors')
app.use(cors())
app.use(bodyParser.urlencoded({extended: true}));
app.use(session({secret: 'secret',resave: true,saveUninitialized: true}));
app.use(bodyParser.json());
app.use(express.static(__dirname + '/public')); // exposes index.html
const mongo = require('mongodb').MongoClient;
const url = "mongodb://adi:adi@localhost:27017/conversationalAI"
const MongoClient = new mongo(url, { useNewUrlParser: true });
const assert = require('assert');
const dbName = 'conversationalAI';
var ObjectId = require('mongodb').ObjectID;
// ___________________________________________________________________________________________________________________________
// https://steemit.com/utopian-io/@morningtundra/storing-and-retreiving-images-in-mongodb-with-nodejs
mongo.connect(url, (err, client) => {
if (err) return console.log(err)
db = client.db(dbName);
})
/** Storage Engine-- SET STORAGE */
const storageEngine = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, 'uploads')
},
filename: function(req, file, cb){
cb(null, new Date().getTime().toString()+'-'+file.fieldname+path.extname(file.originalname));
}
});
var validateFile = function(file, cb ){
allowedFileTypes = /pdf|jpeg|jpg|png|gif/;
const extension = allowedFileTypes.test(path.extname(file.originalname).toLowerCase());
const mimeType = allowedFileTypes.test(file.mimetype);
if(extension && mimeType){
return cb(null, true);
}else{
cb("Invalid file type. Only JPEG, PNG and GIF file are allowed.")
}
}
const upload_img = multer({ storage: storageEngine , limits: { fileSize:200000 },fileFilter: function(req, file, callback){
validateFile(file, callback);} })
app.post('/api/upload/v2/', upload_img.single('photo'), (req, res) => {
if (req.file == null) {
// If Submit was accidentally clicked with no file selected...
//res.render('index', { title:'Please select a picture file to submit!'});
res.send('Please select a picture file to submit!');
}
else {
var img = fs.readFileSync(req.file.path);
var portNo = 6000;
var encode_image = img.toString('base64');
// Define a JSONobject for the image attributes for saving to database
image_name = req.file.originalname + '-' + Date.now();
var finalImg = {
//name: 'bike',
name:image_name ,
contentType: req.file.mimetype,
image: new Buffer(encode_image, 'base64')
};
db.collection('claims').insertOne(finalImg, (err, result) => {
if (err) return console.log(err);
var data = JSON.stringify({
"email": "<EMAIL>",
"image": image_name
});
console.log("server side payload:"+data);
var responseData = '';
var options = {
host: '0.0.0.0',
port: portNo,
path: '/chatAI/api/v1/predict/',
method: 'POST',
headers: {'Content-Type': 'application/json'}
};
var httpreq = http.request(options,function(response, err){
response.setEncoding('utf8');
response.on('data',function(chatResponse){
chatResponse = JSON.parse(chatResponse);
responseData = chatResponse["text"];
console.log("Reply from chatBot- node.js side:"+responseData)
res.send(responseData);
});
});
httpreq.write(data);
httpreq.end();
httpreq.on('error', function(e){
console.log("handling error121---------:"+e);
chatResponse = {"text":"Something went wrong, while processing image.","contentType":"Plaintext","attachments":[],"action":{}}
console.log("response from chatBot- node.js side:"+chatResponse, typeof(chatResponse))
responseData = chatResponse["text"];
res.send(responseData);
});
})// db.collection ends
}// else block ends
})
app.post('/api/upload/v1/', upload_img.single('photo'), (req, res) => {
var img = fs.readFileSync(req.file.path);
var encode_image = img.toString('base64');
// Define a JSONobject for the image attributes for saving to database
var finalImg = {
name: 'bike',
contentType: req.file.mimetype,
image: new Buffer(encode_image, 'base64')
};
db.collection('claims').insertOne(finalImg, (err, result) => {
console.log(result)
if (err) return console.log(err)
console.log('saved to database')
//res.redirect('/')
//res.status(200).contentType("text/plain").end("Uploaded successfully");
res.send("Uploaded successfully kundan");
})
})
app.get('/photos', (req, res) => {
db.collection('claims').find().toArray((err, result) => {
const imgArray= result.map(element => element._id);
console.log(imgArray);
if (err) return console.log(err)
res.send(imgArray)
})
});
app.get('/photo/:id', (req, res) => { // http://localhost:7000/photo/bike (url to call this)
var filename = req.params.id;
console.log("file name:"+filename, typeof(filename),filename.length);
dd = filename.trim();
console.log("file after trimming:"+dd, typeof(dd),dd.length);
var query = {'name':filename};
console.log("mongo query:",query, typeof(query));
db.collection('claims').findOne(query, (err, result) => {
if (err) return console.log(err);
console.log("result from db:"+ result);
res.contentType('image/jpeg');
res.send(result.image.buffer)
})
})
// ______________________________________________________________________________________________________________________
const handleError = (err, res) => {
res
.status(500)
.contentType("text/plain")
.end("Oops! Something went wrong!");
};
const upload = multer({
dest: "/Users/apple/Documents/projects/zishan_wipro/ConversationAI/WebChannel/webspeechdemo"
// you might also want to set some limits: https://github.com/expressjs/multer#limits
});
// https://stackoverflow.com/questions/15772394/how-to-upload-display-and-save-images-using-node-js-and-express
app.post("/api/upload/org",
upload.single("photo" /* name attribute of <file> element in your form */),
(req, res) => {
const tempPath = req.file.path;
console.log("temp path:"+ tempPath);
const targetPath = path.join(__dirname, "./uploads/image.png");
console.log("target path:"+ targetPath);
console.log("Extension check:",path.extname(req.file.originalname).toLowerCase());
if (path.extname(req.file.originalname).toLowerCase() === ".jpeg") {
console.log("V1")
fs.rename(tempPath, targetPath, err => {
if (err) console.log('ERROR: ' + err); //return handleError(err, res);
//res.status(200).contentType("text/plain").end("File uploaded!");
res.sendFile(path.join(__dirname+'/public/upload_success.html'));
});
} else {
fs.unlink(tempPath, err => {
if (err) return handleError(err, res);
res
.status(403)
.contentType("text/plain")
.end("Only .png files are allowed!");
});
}
}
);
app.get("/image.png", (req, res) => {
res.sendFile(path.join(__dirname, "./uploads/image.png"));
});
// ________________________________________________________________________________________________________________________
app.get('/webChat', function (request, response) {
//console.log("server rendering html page");
response.sendFile(path.join(__dirname+'/public/demo.html'));
});
app.get('/', function(request, response) {
response.sendFile(path.join(__dirname + '/public/login.html'));
});
app.get('/home', function(request, response) {
response.sendFile(path.join(__dirname + '/public/demo.html'));
response.end();
});
// chat API
app.post('/startChat', function(req,res){
console.log("in server side payload");
console.log(req.body);
var portNo = 5000;
var email = req.body.email;
var message = req.body.message;
var data = JSON.stringify({"text": message});
console.log("server side payload:"+data);
var responseData = '';
var options = {
host: '0.0.0.0',
port: portNo,
path: '/api/v1/text/predict/',
method: 'POST',
headers: {'Content-Type': 'application/json'}
};
var httpreq = http.request(options,function(response, err){
response.setEncoding('utf8');
console.log("handling error---------:"+err);
response.on('data',function(chatResponse){
chatResponse = JSON.parse(chatResponse);
res.send(chatResponse);
});
console.log("handling error1---------:"+err);
});
httpreq.write(data);
httpreq.end();
httpreq.on('error', function(e){
console.log("handling error121---------:"+e);
chatResponse = {"text":"Something went wrong, please try after some time.","contentType":"Plaintext","attachments":[],"action":{}}
console.log("response from chatBot- node.js side:"+chatResponse, typeof(chatResponse))
responseData = chatResponse
res.send(responseData);
});
})
app.post('/api/upload/v144/', function(req,res){
console.log("in server side payload");
console.log(req.body);
res.send("Uploaded successfully kundan123");
})
app.listen(port, () => console.log(`WebChannel app listening on port ${port}!`))
<file_sep><!DOCTYPE html>
<meta charset="utf-8">
<head>
<meta charset="UTF-8">
<link rel="shortcut icon" href="chat.ico" type="image/x-icon"/>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap3-dialog/1.34.7/css/bootstrap-dialog.min.css">
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap3-dialog/1.34.7/js/bootstrap-dialog.min.js"></script>
<title>Web Chat Agent</title>
<link rel="stylesheet" type="text/css" href="./style.css">
</head>
<body>
<h1 class="center" id="headline"> Web Chat </h1>
<div id="info">
<p id="info_start">Click on the microphone icon and begin speaking.</p>
<p id="info_speak_now">Speak now.</p>
<p id="info_no_speech">No speech was detected. You may need to adjust your
<a href="//support.google.com/chrome/bin/answer.py?hl=en&answer=1407892">
microphone settings</a>.</p>
<p id="info_no_microphone" style="display:none">
No microphone was found. Ensure that a microphone is installed and that
<a href="//support.google.com/chrome/bin/answer.py?hl=en&answer=1407892">
microphone settings</a> are configured correctly.</p>
<p id="info_allow">Click the "Allow" button above to enable your microphone.</p>
<p id="info_denied">Permission to use microphone was denied.</p>
<p id="info_blocked">Permission to use microphone is blocked. To change,
go to chrome://settings/contentExceptions#media-stream</p>
<p id="info_upgrade">Web Speech API is not supported by this browser.
Upgrade to <a href="//www.google.com/chrome">Chrome</a>
version 25 or later.</p>
</div>
<!-- <div class="right">
<button id="start_button" onclick="startButton(event)">
<img id="start_img" src="mic.gif" alt="Start"></button>
</div> -->
<div id="results">
<div class="messages"></div>
<div id="edge"></div>
<span id="final_span" class="final"></span>
<span id="interim_span" class="interim"></span>
<!-- <p>Date/Time: <span id="datetime"></span></p> -->
</div>
<div id ="chatarea">
<!-- <input id="chattext" type="text" name="userInput" value="" placeholder="Type a message" class="chatAI"> <button id="chat">Chat</button> -->
<textarea id="chattext" type="textbox" class="chatAI" placeholder="Type a message" ></textarea> <button id="chat">Chat</button>
<form id = "upload" target = "_blank" action="/api/upload/v144/" method="post" enctype="multipart/form-data">
<input type="file" accept="image/*" name="photo" class="browse btn btn-primary input-lg"><i class="glyphicon glyphicon-search"></i>
<input type="submit" class="btn btn-primary" value="upload">
</form>
<div class="right">
<button id="start_button" onclick="startButton(event)"><img id="start_img" src="mic.gif" alt="Start"></button>
</div>
</div>
<div class="center">
<div class="sidebyside" style="text-align:right">
<button id="copy_button" class="button" onclick="copyButton()">
Copy and Paste</button>
<div id="copy_info" class="info">
Press Control-C to copy text.<br>(Command-C on Mac.)
</div>
</div>
<div class="sidebyside">
<button id="email_button" class="button" onclick="emailButton()">
Create Email</button>
<div id="email_info" class="info">
Text sent to default email application.<br>
(See chrome://settings/handlers to change.)
</div>
</div>
<p>
</div>
<script type="text/javascript" src = "../js/demo.js">
</script>
</body>
</html>
| 092fd64a77287dd3e59bffef24cdadf750a3b3ba | [
"JavaScript",
"Python",
"HTML"
] | 5 | Python | aayushk14/BigRed2019 | 067e9a70c5ed9dd138a855735b3d1b6f10811fe3 | 443b6fc8fa461fd55009ed1a03bed856195b7bbc |
refs/heads/master | <repo_name>zainzafar90/sarcasm-detector<file_sep>/README.md
# sarcasm-detector
Sarcasm Detector - A Python based MVC application to analyse sarcasm in sentence (positive, negative or neutral)
<file_sep>/app.py
#!/usr/bin/env python2.7.9
from flask import Flask
def create_app(config):
# create app and load config
app = Flask(__name__)
app.config.from_object(config)
# bind views
from view import index, by_query_sarcasm
app.add_url_rule('/', view_func=index)
# app.add_url_rule('/search', view_func=by_query)
app.add_url_rule('/sarcasm', view_func=by_query_sarcasm)
return app
if __name__ == "__main__":
app = create_app('config.ProductionConfig')
app.run()<file_sep>/config.py
## MongoEngine Note: include db name in URI; it overwrites all others
class Config(object):
DEBUG = False
class ProductionConfig(Config):
DEBUG = False
class DevelopmentConfig(Config):
DEBUG = True
<file_sep>/feature_extraction.py
import string
import nltk
from nltk.tokenize import RegexpTokenizer
from nltk.stem import WordNetLemmatizer
from textblob import TextBlob
import numpy as np
dict_sad={":-(":"SAD", ":(":"SAD", ":-|":"SAD", ";-(":"SAD", ";-<":"SAD", "|-{":"SAD"}
dict_happy={":-)":"HAPPY",":)":"HAPPY", ":o)":"HAPPY",":-}":"HAPPY",";-}":"HAPPY",":->":"HAPPY",";-)":"HAPPY"}
wordnet_lemmatizer = WordNetLemmatizer()
tokenizer = RegexpTokenizer(r'\w+')
def replace_emotion(sentence):
returnsent = sentence
for i in dict_happy:
returnsent = returnsent.replace(i,dict_happy[i])
for i in dict_sad:
returnsent = returnsent.replace(i,dict_sad[i])
return returnsent
def getbigramfeatures(features,sentence):
tokens = tokenizer.tokenize(sentence)
lemmas = [wordnet_lemmatizer.lemmatize(word) for word in tokens]
bigrams = nltk.bigrams(lemmas)
bigrams = [part[0]+' '+part[1] for part in bigrams]
bigramfeat = lemmas + bigrams
for feat in bigramfeat:
features['contains(%s)' % feat] = 1.0
def gethalfSentimentfeatures(features,sentence):
tokens = tokenizer.tokenize(sentence)
if len(tokens)==1:
tokens+=['.']
f_half = tokens[0:len(tokens)/2]
s_half = tokens[len(tokens)/2:]
try:
blob = TextBlob("".join([" "+i if not i.startswith("'") and i not in string.punctuation else i for i in f_half]).strip())
features['sentiment fhalf'] = blob.sentiment.polarity
features['subjective fhalf'] = blob.sentiment.subjectivity
except:
features['sentiment fhalf'] = 0.0
features['subjective fhalf'] = 0.0
try:
blob = TextBlob("".join([" "+i if not i.startswith("'") and i not in string.punctuation else i for i in s_half]).strip())
features['sentiment shalf'] = blob.sentiment.polarity
features['subjective shalf'] = blob.sentiment.subjectivity
except:
features['sentiment shalf'] = 0.0
features['subjective shalf'] = 0.0
features['sentiment halfcontrast'] = np.abs(features['sentiment fhalf'] - features['sentiment shalf'])
def getthirdSentimentfeatures(features,sentence):
tokens = tokenizer.tokenize(sentence)
#Split in 3
if len(tokens)==2:
tokens+=['.']
f_half = tokens[0:len(tokens)/3]
s_half = tokens[len(tokens)/3:2*len(tokens)/3]
t_half = tokens[2*len(tokens)/3:]
try:
blob = TextBlob("".join([" "+i if not i.startswith("'") and i not in string.punctuation else i for i in f_half]).strip())
features['sentiment fthird'] = blob.sentiment.polarity
features['subjective fthird'] = blob.sentiment.subjectivity
except:
features['sentiment fthird'] = 0.0
features['subjective fthird'] = 0.0
try:
blob = TextBlob("".join([" "+i if not i.startswith("'") and i not in string.punctuation else i for i in s_half]).strip())
features['sentiment sthird'] = blob.sentiment.polarity
features['subjective sthird'] = blob.sentiment.subjectivity
except:
features['sentiment sthird'] = 0.0
features['subjective sthird'] = 0.0
try:
blob = TextBlob("".join([" "+i if not i.startswith("'") and i not in string.punctuation else i for i in t_half]).strip())
features['sentiment tthird'] = blob.sentiment.polarity
features['subjective tthird'] = blob.sentiment.subjectivity
except:
features['sentiment tthird'] = 0.0
features['subjective tthird'] = 0.0
features['sentiment 12contrast'] = np.abs(features['sentiment fthird'] - features['sentiment sthird'])
features['sentiment 13contrast'] = np.abs(features['sentiment fthird'] - features['sentiment tthird'])
features['sentiment 23contrast'] = np.abs(features['sentiment sthird'] - features['sentiment tthird'])
def getPOSfeature(features, sentence):
tokens = tokenizer.tokenize(sentence)
tokens = [tok.lower() for tok in tokens]
pos_vector = nltk.pos_tag(tokens)
vector = np.zeros(4)
for j in range(len(pos_vector)):
pos=pos_vector[j][1]
if pos[0:2] == 'NN':
vector[0]+=1
elif pos[0:2] == 'JJ':
vector[1]+=1
elif pos[0:2] == 'VB':
vector[2]+=1
elif pos[0:2] == 'RB':
vector[3]+=1
for j in range(len(vector)):
features['POS' + str(j+1)] = vector[j]
def getCapitalfeature(features,sentence):
count = 0
threshold = 4
for j in range(len(sentence)):
count +=int(sentence[j].isupper())
features['Capital'] = int(count>=threshold)
def getExclamationCnt(features,sentence):
count =0;
for i in range(len(sentence)):
count += int(sentence[i] == '!')
features['exclamation'] = count
def count_emotion(features,sentence):
returnsent = sentence
happy = 0;
sad = 0
for i in dict_happy:
happy += returnsent.count(i)
for i in dict_sad:
sad += returnsent.count(i)
features['happyemo'] = happy
features['sademo'] = sad
def getallfeatureset(sent):
features = {}
getCapitalfeature(features,sent)
getExclamationCnt(features,sent)
count_emotion(features,sent)
sent = replace_emotion(sent)
getbigramfeatures(features,sent)
gethalfSentimentfeatures(features,sent)
getthirdSentimentfeatures(features,sent)
getPOSfeature(features,sent)
return features
#getallfeatureset("The best part of being single is being able to choose any woman I want to shoot me down")<file_sep>/sarcasm.py
import numpy as np
import pickle
import os
import feature_extraction
file1 = open('vecdict_all.p', 'r')
file2 = open('classif_all.p', 'r')
vec = pickle.load(file1)
classifier = pickle.load(file2)
file1.close()
file2.close()
#sentence = "I never miss the lecture of <NAME>"
#sentence = "Donald trump will make america great again"
#sentence = "Messi is the best footballer in the world"
#sentence = "Oh how I love being ignored"
#sentence = "Absolutely adore it when my bus is late"
#sentence = "I work 40 hours a week to be this poor"
class SarcasmDetector():
def getSarcasmScore(self, sentence):
sentence = sentence.encode('ascii', 'ignore')
features = feature_extraction.getallfeatureset(sentence)
features_vec = vec.transform(features)
score = classifier.decision_function(features_vec)[0]
percentage = int(round(2.0*(1.0/(1.0+np.exp(-score))-0.5)*100.0))
return percentage
<file_sep>/view.py
from flask import render_template
from flask import jsonify
from flask import request
import app
import sarcasm
# import api.sentiment
# VIEWS
def index():
return render_template('index.html')
def by_query_sarcasm():
query = request.args.get('query')
sarcasmScore = sarcasm.SarcasmDetector().getSarcasmScore(query)
return render_template(
'query.html',
sarcasmScore=sarcasmScore
)
| 82f227498f7213bca7b52ffc6898480f6d88f9e4 | [
"Markdown",
"Python"
] | 6 | Markdown | zainzafar90/sarcasm-detector | f2f8c8db9171306c7517e81cd354de8e3b3c11ef | bde5d6151907cf3b38dc5abb670d5d0adfe47a82 |
refs/heads/master | <file_sep>//
// (pre)compile/render mustache templates with hogan.js
// can be used as middleware or broadway plugin
//
var hogan = require('hogan.js'),
fs = require('fs'),
path = require('path'),
url = require('url'),
utile = require('utile'),
async = require('async'),
winston = require('winston');
//
// exports
//
//
// broadway plugin
// attach options:
// @dir templates dir
// @ext templates ext
// @recompile recompile template on every call to render
//
exports.plugin = {
name: 'hoganyam',
attach: function(options) {
options.cache = options.cache || {};
this.render = function(res, name, context) {
context = context || {};
var file = path.join(options.dir, name + options.ext);
render(file, context, options, function(err, str) {
if (err) {
winston.error(err);
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end(err.toString());
} else {
res.writeHead(200, {'Content-Type': 'text/html'});
res.end(str);
}
});
};
}
};
// provide templates from a directory individually as connect-style middleware
exports.provide = provide;
// bundle templates form a directory into one js-file as connect-style middleware
exports.bundle = bundle;
// render a template
exports.render = render;
//
// provide compiled templates individually through url
// connect-style middleware function
//
// @srcDir absolute path to templates
// @srcUrl base url for request
// @options {
// @namespace namespace for precompiled templates, default is this
// @ext template extension, default is '.html'
// @recompile do not use cache and recompile on every request
// @hoganOptions options for the hogan.js template engine
// }
//
function provide(srcDir, options) {
options = options || {};
options.ext = options.ext || '.html';
options.mount = options.mount || '';
options.namespace = options.namespace || 'this';
options.hoganOptions = options.hoganOptions || {};
options.hoganOptions.asString = true;
var dstExt = /\.js$/,
srcExt = options.ext,
cache = options.cache || {},
jsTemplate,
jst = '';
jst += ';(function(root) {\n';
jst += ' var template = new Hogan.Template({{{template}}});\n';
jst += ' var partials = {\n';
jst += ' {{#partials}}';
jst += ' "{{name}}": new Hogan.Template({{{template}}}),\n';
jst += ' {{/partials}}';
jst += ' };\n';
jst += ' root.templates = root.templates || {};\n';
jst += ' root.templates["{{name}}"] = function(context) {\n';
jst += ' return template.render(context, partials);\n';
jst += ' };\n';
jst += '})({{namespace}});\n';
jsTemplate = hogan.compile(jst);
return function(req, res, next) {
if (req.method !== 'GET') return next();
// build an absolute path
var pathname = url.parse(req.url).pathname,
srcFile, src, ux;
if (!pathname.match(dstExt)) return next();
if (options.mount) {
ux = new RegExp('^' + options.mount);
if (!pathname.match(ux)) return next();
// remove prefix url and leading slashes
pathname = pathname.replace(ux, '').replace(/^\/*/, '');
}
srcFile = path.join(srcDir, pathname).replace(dstExt, srcExt);
if (!options.recompile && cache[srcFile]) {
winston.verbose('providing template from cache: ', srcFile);
sendResponse(res, cache[srcFile].source, cache[srcFile].mtime.toUTCString());
}
else {
getTemplate(srcFile, options, function(err,t) {
if (err) return next(err);
var name = createTemplateName(srcDir, srcFile, options.ext),
context = {
name: name,
template: t.template,
partials: [],
namespace: options.namespace
};
utile.each(t.partials, function(v, k) {
context.partials.push({
name: k,
template: v
});
});
src = jsTemplate.render(context);
if (!options.recompile) {
cache[srcFile] = { source: src, mtime: t.mtime };
}
sendResponse(res, src, t.mtime.toUTCString());
});
}
};
}
//
// bundle all compiled templates into one js file
//
// @srcDir directory with templates
// @options {
// @namespace namespace for precompiled templates, default is this
// @ext template extension, default is '.html'
// @recompile do not use cache and recompile on every request
// @hoganOptions options for the hogan.js template engine
// }
//
function bundle(srcDir, options) {
options = options || {};
options.mount = options.mount || '/templates.js';
options.ext = options.ext || '.html';
options.namespace = options.namespace || 'this';
options.hoganOptions = options.hoganOptions || {};
options.hoganOptions.asString = true;
var jsTemplate = createTemplate();
function createTemplate() {
var jst = '';
jst += '// autogenerated file\n';
jst += ';(function(root){\n';
jst += ' root = root || {};\n';
jst += ' var templates = {\n';
jst += ' {{#templates}}\n';
jst += ' "{{name}}": new Hogan.Template({{{template}}}),\n';
jst += ' {{/templates}}\n';
jst += ' };\n';
jst += ' var renderers = {\n';
jst += ' {{#templates}}\n';
jst += ' "{{name}}": function(context) {\n';
jst += ' return templates["{{name}}"].render(context, templates)\n';
jst += ' },\n';
jst += ' {{/templates}}\n';
jst += ' };\n';
jst += ' root.templates = renderers;\n';
jst += '})({{namespace}});\n';
return hogan.compile(jst);
}
return function(req, res, next) {
if (req.method !== 'GET') return next();
var reqUrl = url.parse(req.url).pathname,
src = '';
// only answer correct url
if (reqUrl !== options.mount) return next();
compileDir(srcDir, options, function(err, templates) {
winston.verbose("compiling template dir: ", srcDir);
if (err) return next(err);
resolvePartialNames(templates);
src = jsTemplate.render({ templates: templates, namespace: options.namespace});
sendResponse(res, src);
});
};
}
//
// resolve partial name like '../header' to qualified template name
// @templates dict with templates
//
function resolvePartialNames(templates) {
templates.forEach(function(template) {
var parts = template.name.split(path.sep),
basePath = parts.length === 1 ? '' : parts.slice(0, parts.length - 1).join(path.sep);
template.partials = template.partials.map(function(partialName) {
return path.join(basePath, partialName);
});
});
}
function createTemplateName(basePath, filePath, ext) {
var len = basePath.split(path.sep).length,
relPath = filePath.split(path.sep).slice(len).join(path.sep),
name = relPath.replace(new RegExp(ext + '$'), '');
return name;
}
function sendResponse(res, str, mtime) {
res.setHeader('Date', new Date().toUTCString());
res.setHeader('Last-Modified', mtime || (new Date).toUTCString());
res.setHeader('Content-Type', 'application/javascript');
res.setHeader('Content-Length', str.length);
res.end(str);
}
//
// render a template file with context mapping
//
// @file absolute path to the file
// @context vars to map
// @options {
// @cache cache object to use
// @recompile do not use cache and recompile on every request
// @hoganOptions options for the hogan.js template engine
// }
// @callback is called with (err, str)
//
function render(file, context, options, callback) {
winston.verbose('rendering: ' + file);
options = options || {};
options.cache = options.cache || {};
options.hoganOptions = options.hoganOptions || {};
var key = file,
ct = options.cache[key];
if (!options.recompile && ct) {
winston.verbose('render template from cache: ' + file);
callback(null, ct.template.render(context, ct.partials));
}
else {
getTemplate(file, options, function(err, t) {
if (!options.recompile) options.cache[key] = t;
callback(err, t ? t.template.render(context, t.partials) : err.message);
});
}
}
//
// get the template file and compile it
//
function getTemplate(file, options, callback) {
winston.verbose('getting template: ' + file);
findfilep(file, function(err, foundfile) {
if (err) return callback(err);
fs.stat(foundfile, function(err, stats) {
if (err) return callback(err);
var ext, dir;
compile(foundfile, options, function(err, t) {
if (err) return callback(err);
// if (options.processTemplate) options.processTemplate(t, options);
t.mtime = stats.mtime;
callback(null, t);
});
});
});
}
//
// compile template and partials
//
function compile(file, options, callback) {
var ext = path.extname(file),
dir = path.dirname(file);
// compile the template
hoganCompile(file, options.hoganOptions, function(err, template, partialNames) {
if (err) return callback(err);
var tmpl = {
template: template,
name: path.basename(file, ext),
partials: {}
};
// compile the partials
async.forEach(partialNames,
function(name, cb) {
var pfile = path.join(dir, name + ext),
poptions = utile.clone(options);
getTemplate(pfile, poptions, function(err, t) {
if (err) return cb(err);
tmpl.partials[name] = t.template;
tmpl.partials = utile.mixin(tmpl.partials, t.partials);
cb();
});
},
function(err) {
callback(err, tmpl);
});
});
}
//
// compile template files in the directory and all subdirectories asynchronously
// @basePath base path
// @options
// @callback call when finished
//
function compileDir(basePath, options, callback) {
var templates = [],
compileIterator = function(filePath, callback) {
if (!filePath.match(new RegExp(options.ext + '$'))) {
return callback();
}
hoganCompile(filePath, options.hoganOptions, function(err, template, partialNames) {
if (err) return callback(err);
// var len = basePath.split(path.sep).length,
// relPath = filePath.split(path.sep).slice(len).join(path.sep),
// name = relPath.replace(/.html$/, '');
templates.push({
name: createTemplateName(basePath, filePath, options.ext),
template: template,
partials: partialNames
});
callback();
});
};
eachFileInDir(basePath,
compileIterator,
function(err) {
callback(err, templates);
});
}
//
// compiles the template and extracts partial names
// @file the template file
// @options hogan options
// @callback is called when finished
//
function hoganCompile(file, options, callback) {
fs.readFile(file, 'utf8', function(err, str) {
if (err) return callback(err);
// let hogan scan the src into tokens and collect all of the partial names
// partial tokens have the tag: '>'
var tokens = hogan.scan(str),
partialNames = tokens
.filter(function(t) { return t.tag === '>'; })
.map(function(t) { return t.n; }),
template = hogan.generate(hogan.parse(tokens, str, options), str, options);
callback(err, template, partialNames);
});
}
//
// find a file by walking up the path
//
function findfilep(pathname, callback) {
var basename = path.basename(pathname),
dirname = path.dirname(pathname);
fs.exists(pathname, function(exists) {
if (!exists && dirname === '/') {
return callback(new Error('Cannot find file: ' + basename));
}
else if (!exists) {
var parentpath = path.join(path.resolve(dirname, '..'), basename);
findfilep(parentpath, callback);
}
else {
callback(null, pathname);
}
});
}
//
// call iterator on all files in the path and subpaths asynchronously
// @startPath base path
// @iterator iterator function(filePath, callback) {}
// @callback call when finished
//
function eachFileInDir(startPath, iterator, callback) {
(function rec(basePath, callback) {
fs.stat(basePath, function(err, stats) {
if (err) return callback(err);
if (stats.isFile()) {
iterator(basePath, callback);
}
else if (stats.isDirectory()) {
fs.readdir(basePath, function(err, nodes) {
if (err) return callback(err);
utile.async.forEach(nodes,
function(node, callback) {
rec(path.join(basePath, node), callback);
},
callback);
});
}
});
})(startPath, callback);
}
<file_sep># hoganyam
Yet another hogan.js(moustache templates) middleware. Can render templates with partials serverside or precompile them for use on the client.
## Usage
``` js
var hoganyam = require('hoganyam');
```
### As connect-style middleware
Makes the templates available individually.
``` js
app.use(hoganyam.provide(templatesDir, options));
```
Bundle all templates in directory into one js file
``` js
app.use(hoganyam.bundle(templatesDir, options));
```
### Serverside rendering
``` js
hoganyam.render(file, context, options, function(err, str) {
// do something with the rendered template string
});
```
**Use as broadway plugin for flatiron**
``` js
app.use(hoganyam.plugin, {dir: templatesDir, ext: '.html'});
// now you can render directly to the response
app.render(res, 'templatename', { title: 'Hello Hogan'});
```
**For options see source**
## License
MIT License
## Install with npm
npm install hoganyam
## Run tests
npm test<file_sep>var vows = require('vows'),
assert = require('assert'),
vm = require('vm'),
hoganyam = require('../index.js'),
hogan = require('hogan.js'),
path = require('path'),
fs = require('fs'),
dataDir = path.join(__dirname, 'data'),
testFile = path.join(dataDir, 'test.template'),
options = {},
data = { title: "a little test", name: "Hogan"},
correctResult = fs.readFileSync(path.join(dataDir, 'result.txt')).toString();
function puts(str) {
process.stderr.write(str + '\n');
}
function mockReq(url) {
return {
method: 'GET',
url: url
};
}
function mockRes(callback) {
return {
setHeader: function() {},
end: function(str) { callback(null, str); }
};
}
function evalTemplate(templateStr, callStr, data) {
var str = templateStr + 'result = ' + callStr + '(' + JSON.stringify(data) + ');\n',
sandbox = {
Hogan: hogan,
result: null
},
context = vm.createContext(sandbox);
vm.runInContext(str, context);
return context.result;
}
vows.describe('hoganyam').addBatch({
"The hoganyam module": {
topic: hoganyam,
"should have the correct methods defined": function() {
assert.isObject(hoganyam);
assert.isFunction(hoganyam.provide);
assert.isFunction(hoganyam.bundle);
assert.isFunction(hoganyam.render);
assert.isObject(hoganyam.plugin);
},
"rendering the test template": {
topic: function() {
hoganyam.render(testFile, data, options, this.callback);
},
"should show the correct output": function(str) {
assert.equal(str, correctResult);
}
},
"used as middleware for single template": {
topic: function() {
var f = hoganyam.provide(dataDir, {ext: '.template'}),
that = this;
f(mockReq('test.js'), mockRes(this.callback), function(err) {
that.callback(err || new Error('request failed'));
});
},
"sould provide the compiled template and render the correct result": function(err, str) {
assert.isNull(err);
var result = evalTemplate(str, 'templates.test', data);
assert.equal(result, correctResult);
}
},
"used as middleware for bundled templates": {
topic: function() {
var that = this,
f = hoganyam.bundle(dataDir, {ext: '.template'});
f(mockReq('/templates.js'), mockRes(this.callback), function(err) {
that.callback(err || new Error('request failed'));
});
},
"should bundle the compiled templates and render the correct result": function(err, str) {
assert.isNull(err);
// puts(str);
var result = evalTemplate(str, 'templates.test', data);
assert.equal(result, correctResult);
}
}
}
}).export(module); | 7a4cbae6cc4de3f8ac4e3b4542286ac487296952 | [
"JavaScript",
"Markdown"
] | 3 | JavaScript | skoni/hoganyam | a4f3769beb279870c1d7a3db16139269e33ae678 | edfde77a82bb045b85efd5597ba378e5878a395f |
refs/heads/main | <repo_name>aryastarkananyaa/Codechef<file_sep>/May_Lunchtime_Div3_CHARGES.cpp
#include<bits/stdc++.h>
using namespace std;
int main(){
int t; cin>>t;
while(t--){
long long n,k;
cin>>n>>k;
string s; cin>>s;
long long len=0;
for(int i=0;i<n-1;i++){
if(s[i]==s[i+1]) len+=2;
else len+=1;
}
while(k--){
long long q; cin>>q; q-=1;
if(s[q]=='1')
s[q]='0';
else
s[q]='1';
if(q<n-1){
if(s[q]==s[q+1])
len++;
else
len--;
}
if(q>0){
if(s[q-1]==s[q])
len++;
else
len--;
}
cout<<len<<"\n";
}
}
return 0;
}
<file_sep>/May_Lunchtime_Div3_TANDJ1.cpp
#include<bits/stdc++.h>
using namespace std;
int main(){
long long t;
cin>>t;
while(t--){
long long a,b,c,d,k;
cin>>a>>b>>c>>d>>k;
long long move = abs(a-c) + abs(b-d);
if (k>=move && (k - move) % 2 == 0)
cout<<"YES"<<"\n";
else
cout<<"NO"<<"\n";
}
return 0;
}
<file_sep>/May_Lunchtime_Div3_HOOPS.cpp
#include<bits/stdc++.h>
using namespace std;
int main(){
long long t;
cin>>t;
while(t--){
long long n;
cin>>n;
if(n==1) cout<<"1"<<"\n";
else{
cout<<(n/2)+1<<"\n";
}
}
return 0;
}
<file_sep>/May_Luchtime_Div3_TWINGFT.cpp
#include<bits/stdc++.h>
using namespace std;
int main(){
long long t;
cin>>t;
while(t--){
long long n,k;
cin>>n>>k;
long long a[n];
for(int i=0;i<n;i++) cin>>a[i];
sort(a,a+n);
long long c1=0,c2=0;
int i=n-1;
for(int x=1;x<=k&&i>=0;x++){
c1+=a[i];
a[i]=-1;
i-=2;
}
int j=n-2;
for(int y=1;y<=k&&j>=0;y++){
c2+=a[j];
a[j]=-1;
j-=2;
}
long long m=LLONG_MIN;
for(int p=0;p<n;p++){
if(a[i]!=-1)
m=max(m,a[p]);
}
c2+=m;
cout<<max(c1,c2)<<"\n";
}
return 0;
}
| 5d45c5841505dca986341d94809133a2420d6726 | [
"C++"
] | 4 | C++ | aryastarkananyaa/Codechef | d67243022281d42b004212175858150dbdeefea6 | de53a685d18b0116bd2d14aba21509e2aedeea9c |
refs/heads/master | <file_sep><?php
namespace App\Model;
use \App\Libs\Model;
class HeaderImage extends Model
{
public $timestamps = false;
public function getImage(){
if($this->hasImage() && file_exists("storage/images/header_images/".$this->image)){
return url("storage/images/header_images/".$this->image);
}else{
return "";
}
}
}
<file_sep><?php
function admin_link($link,$param = null){
$link = \Config::get('horizontcms.backend_prefix')."/".\Config::get('links.'.$link);
return isset($param)? $link."/".$param : $link;
}
function plugin_link($link,$param = null){
$link = \Config::get('horizontcms.backend_prefix')."/plugin/run/".$link;
return isset($param)? $link."/".$param : $link;
}
function namespace_to_slug($string){
return ltrim(strtolower(preg_replace('/(?<!\ )[A-Z]/', '-$0', $string)),"-");
}<file_sep><?php
namespace App\Model;
use \App\Libs\Model;
class BlogpostCategory extends Model
{
public $timestamps = false;
public function blogposts(){
return $this->hasMany(\App\Model\Blogpost::class,'category_id','id');
}
public function getThumb(){
return "";
}
public function getImage(){
return "";
}
}
<file_sep><?php
return [
'settings' => 'Beállítások',
'website' => 'Honlap',
'admin_area' => 'Admin felület',
'update_center' => 'Frissítések',
'server' => 'Szerver',
'email' => 'E-mail',
'social_media' => 'Közösségi média',
'database' => 'Adatbázis',
'scheduler' => 'Ütemező',
'spread' => 'Spread',
'uninstall' => 'Eltávolítás',
];<file_sep><?php
namespace App\Libs;
abstract class Model extends \Illuminate\Database\Eloquent\Model{
private $rules = array();
protected $defaultImage = null;
public function hasImage(){
return (isset($this->image) && $this->image!="");
}
public function getDefaultImage(){
return $this->defaultImage;
}
public function setDefaultImage($image){
$this->defaultImage = $image;
}
public function equals($other){
return is_null($other)? false : $this->is($other);
}
/*
public static function search($search,array $in){
$array = [];
foreach($in as $i){
$array[$i] = $search;
}
return self::where($array);
}*/
public function validate($data){
$v = Validator::make($data, $this->rules);
return $v->passes();
}
}
<file_sep><?php
return [
'settings' => 'Settings',
'website' => 'Website',
'admin_area' => 'Admin Area',
'update_center' => 'Update Center',
'server' => 'Server',
'email' => 'Email',
'social_media' => 'Social Media',
'database' => 'Database',
'scheduler' => 'Scheduler',
'spread' => 'Spread',
'uninstall' => 'Uninstall',
];
<file_sep><?php
namespace App;
class HorizontCMS extends \Illuminate\Foundation\Application{
public $plugins = [];
public static function isInstalled(){
return file_exists(base_path(".env")) || env("INSTALLED","")!="";
}
public function publicPath(){
return $this->basePath.DIRECTORY_SEPARATOR;
}
}<file_sep>/*
|---------------------------
| Submit form on CTRL+s
|---------------------------
*/
$(window).keypress(function(event) {
if (!(event.which == 115 && event.ctrlKey) && !(event.which == 19)) return true;
$("#submit-btn").click();
event.preventDefault();
return false;
});<file_sep><?php
namespace App\Model;
use \App\Libs\Model;
class ScheduledTask extends Model{
protected $table = 'schedules';
public $timestamps = false;
}
<file_sep> echo GitPatcher
zip_name='version.zip';
dir_name='tmp';
if [ $# -eq 0 ]
then
echo "Enter a hash:";
read revision_hash
else
revision_hash=$1
fi
files_differ=$(git diff --name-status $revision_hash HEAD);
arrIN=(${files_differ// / });
rm -rf $dir_name;
mkdir -p $dir_name;
for file in "${arrIN[@]}"; do
echo $file;
if [ -e "$file" ]
then
cp --parents $file $dir_name
fi;
done
cd $dir_name;
zip -r "./"$zip_name "./";
<file_sep><?php
Route::group(['prefix'=>'/install'],function(){
Route::any('/{action?}/{args?}/',
function($action = 'index', $args = null){
return $this->router->resolve('install',$action,$args);
})->where('args', '(.*)');
});
Route::auth();
Route::group(['middleware' => ['admin','plugin','can:global-authorization']],function(){
Route::any('/plugin/run/{plugin}/{controller?}/{action?}/{args?}/',
function($plugin,$controller = 'start', $action = 'index', $args = null){
$this->router->changeNamespace("\Plugin\\".studly_case($plugin)."\\App\\Controllers\\");
return $this->router->resolve($controller,$action,$args);
})->where('args', '(.*)');
Route::any('/{controller?}/{action?}/{args?}/',
function($controller = 'dashboard', $action = 'index', $args = null){
return $this->router->resolve($controller,$action,$args);
})->where('args', '(.*)');
});<file_sep><?php
namespace App\Controllers;
use Illuminate\Http\Request;
use App\Libs\Controller;
use App\Model\ScheduledTask;
class ScheduleController extends Controller{
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index(){
}
public function create(){
if($this->request->isMethod('POST')){
$task = new ScheduledTask();
$task->name = $this->request->input("name");
$task->command = $this->request->input("command");
$task->arguments = $this->request->input("arguments");
$task->frequency = $this->request->input("frequency");
$task->ping_before = $this->request->input("ping_before");
$task->ping_after = $this->request->input("ping_after");
$task->active = 1;
if($task->save()){
return $this->redirectToSelf()->withMessage(['succes' => trans('Succesfully scheduled a task!')]);
}else{
return $this->redirectToSelf()->withMessage(['danger' => trans('message.something_went_wrong')]);
}
}
}
public function delete($id){
if(ScheduledTask::find($id)->delete()){
return $this->redirectToSelf()->withMessage(['success' => trans('Successfully deleted the task!')]);
}
return $this->redirect(admin_link("blogpost-index"))->withMessage(['danger' => trans('message.something_went_wrong')]);
}
}
<file_sep><?php
namespace App\Controllers;
use Illuminate\Http\Request;
use App\Libs\Controller;
use App\Model\BlogpostComment;
class BlogpostCommentController extends Controller{
/**
* Show the form for creating a new resource.
*
* @return \Illuminate\Http\Response
*/
public function create(){
if($this->request->isMethod('POST')){
$blogpost_comment = new BlogpostComment();
$blogpost_comment->blogpost_id = $this->request->input('blogpost_id');
$blogpost_comment->comment = $this->request->input('comment');
$blogpost_comment->user_id = \Auth::user()->id;
if($blogpost_comment->save()){
return $this->redirectToSelf()->withMessage(['success' => trans('message.successfully_created_blogpost_comment')]);
}else{
return $this->redirectToSelf()->withMessage(['danger' => trans('message.something_went_wrong')]);
}
}
}
/**
* Store a newly created resource in storage.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
public function store(Request $request){
//
}
/**
* Display the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function show($id){
}
/**
* Update the specified resource in storage.
*
* @param \Illuminate\Http\Request $request
* @param int $id
* @return \Illuminate\Http\Response
*/
public function update($id){
$blogpost_comment = BlogpostComment::find($id);
$blogpost_comment = new BlogpostComment();
$blogpost_comment->blogpost_id = $this->request->input('blogpost_id');
$blogpost_comment->comment = $this->request->input('comment');
$blogpost_comment->user_id = \Auth::user()->id;
if($blogpost_comment->save()){
return $this->redirectToSelf()->withMessage(['success' => trans('message.successfully_updated_blogpost_comment')]);
}else{
return $this->redirectToSelf()->withMessage(['danger' => trans('message.something_went_wrong')]);
}
}
/**
* Remove the specified resource from storage.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function destroy($id){
//
}
/**
* Remove the specified resource from database.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function delete($id){
if(BlogpostComment::find($id)->delete()){
return $this->redirectToSelf()->withMessage(['success' => trans('message.successfully_deleted_blogpost_comment')]);
}
return $this->redirectToSelf()->withMessage(['danger' => trans('message.something_went_wrong')]);
}
}
<file_sep><?php
class BootstrapMessage{
public function success($message){
$title = "Success!";
return "<div class='alert alert-success <!--fade in-->'>
<a href='#' class='close' data-dismiss='alert'>×</a>
<span class='glyphicon glyphicon-ok' aria-hidden='true'></span>
<strong>" .$title ."</strong> " .$message ."
</div>";
}
public function error($message){
$title = "Error!";
return "<div class='alert alert-danger alert-error <!--fade in-->'>
<a href='#' class='close' data-dismiss='alert'>×</a>
<span class='glyphicon glyphicon-exclamation-sign' aria-hidden='true'></span>
<strong>".$title ."</strong> ".$message."
</div>";
}
public function warning($message){
$title = "Warning!";
return "<div class='alert alert-warning <!--fade in-->'>
<a href='#' class='close' data-dismiss='alert'>×</a>
<span class='glyphicon glyphicon-warning-sign' aria-hidden='true'></span>
<strong>" .$title ."</strong> " .$message ."
</div>";
}
public function note($message){
$title = "Note!";
return "<div class='alert alert-info <!--fade in-->'>
<a href='#' class='close' data-dismiss='alert'>×</a>
<span class='glyphicon glyphicon-info-sign' aria-hidden='true'></span>
<strong>" .$title ."</strong> " .$message ."
</div>";
}
}<file_sep> $(document).ready(function() {
$('#submenus').hide();
$('#level').change(function() {
if($(this).find('option:selected').val() == '1') {
$('#submenus').show();
}
else{
$('#submenus').hide();
}
});
/*
$('#upload-bar').hide();
$('#select-bar').hide();
$('#back-button').hide();
$('#upload_select').click(
function(){
$('#img-dashboard').hide();
$('#upload-bar').show();
$('#back-button').show();
}
);
$('#select_select').click(
function(){
$('#img-dashboard').hide();
$('#select-bar').show();
$('#back-button').show();
}
);
$('#back-button').click(
function(){
$('#upload-bar').hide();
$('#select-bar').hide();
$('#back-button').hide();
$('#img-dashboard').show();
}
);
*/
$("#selected-image").hide();
});
function readURL(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
$('#preview-i').attr('src', e.target.result);
$("#select-photo").hide();
$("#selected-image").show();
}
reader.readAsDataURL(input.files[0]);
}
}
$("#input-2").change(function(){
readURL(this);
});
function ajaxGetSlug(){
text = $('#menu-title').val();
if(text!=""){
$.get("api/get-page-slug/"+text, function( data ) {
$("#ajaxSlug").html( "/"+data );
});
}else{
$("#ajaxSlug").html("");
}
}
<file_sep><?php
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| This file is where you may define all of the routes that are handled
| by your application. Just tell Laravel the URIs it should respond
| to using a Closure or controller method. Build something great!
|
*/
Route::any('/{slug?}/{args?}',function($slug="",$args = null){
try{
$this->router->changeNamespace("Theme\\".Settings::get('theme')."\\App\\Controllers\\");
$action = explode("/",$args)[0];
return $this->router->resolve($slug,$action,ltrim($args,$action."/"));
}catch(Exception $e){
if($e instanceof \App\Exceptions\FileNotFoundException || $e instanceof BadMethodCallException){
$controller = \App::make('\App\Controllers\WebsiteController');
$controller->before();
if(method_exists($controller, $slug)){
return $controller->callAction($slug, [$slug,$args]);
}
return $controller->callAction('index',[$slug,$args]);
}
throw $e;
}
})->where('args', '(.*)');
<file_sep><?php
use Illuminate\Http\Request;
/*
|--------------------------------------------------------------------------
| API Routes
|--------------------------------------------------------------------------
|
| Here is where you can register API routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| is assigned the "api" middleware group. Enjoy building your API!
|
*/
Route::get('/me', function (Request $request) {
$request->user()->image = $request->user()->getImage();
return $request->user();
})->middleware(['auth.basic']);
Route::get('/blogposts',function(Request $request){
$blogposts = \App\Model\Blogpost::getPublished()->forPage($request->input('page'),$request->input('num'));
// $blogposts->load('author');
$blogposts->load('category');
return $blogposts;
});
Route::get('/pages',function(Request $request){
$pages = \App\Model\Page::active()->forPage($request->input('page'),$request->input('num'));
// $pages->load('author');
$pages->load('parent');
return $pages;
});
Route::post('lock-up',function(Request $request){
$user = \App\Model\User::find($request->input('id'));
if ($user->isActive() && \Hash::check($request->input('password'), $user->password)) {
return response()->json(TRUE);
}
return response()->json(FALSE);
});
Route::get('get-page-slug/{title}',function($title){
return response()->json(str_slug($title));
});
<file_sep><header>
<div class="col-md-6 col-md-offset-3">
<?php Website::require_theme_file("messages.php"); ?>
</div>
<section class="jumbotron" style="<?= Website::$_HEADER_IMAGES->count()>0 ? "background-image:url(storage/images/header_images/".Website::$_HEADER_IMAGES->first()->image.");" : ""; ?> background-size:cover;text-align:center;padding:125px 0px 125px 0px;margin:0px;">
<center>
<div style="padding:10px 20px 10px 20px;width:450px;background-color:rgba(0,0,0,0.8);color:white;">
<h2><?= Settings::get('site_name') ?></h2>
<hr style="width:50%;">
<h4><?= Website::$_SETTINGS->slogan; ?></h4>
</div>
</center>
</section>
</header>
<?php Website::require_theme_file("sitelinks.php"); ?>
<section class="container">
<div class="row">
<div class="col-md-8">
<?php Website::handle_routing(); ?>
</div>
<div class="col-md-4">
<?php Website::require_theme_file("sidebar.php"); ?>
</div>
</div>
</section> | b1414208dbc0d62cb6bd02ee0cae5a3c8199092b | [
"JavaScript",
"PHP",
"Shell"
] | 18 | PHP | sosaheri/HorizontCMS | 5aa34ac4e457a49b83f24a2969593c495f3ed9ad | 7f44018d204e0b2f7d21a83fbbec62d684535530 |
refs/heads/master | <file_sep>void copy(int a) { a+= 2; }
void ref(int& a) { a+= 2; }
void ptr(int* a) { *a+= 2; }
void example () {
int c = 10;
int& r = c;
int* ptr = &c; // typically int* p = new int{10};
copy(c);
copy(r);
copy(*p);
ref(c);
ref(r);
ref(*p);
ptr(&c);
ptr(&r);
ptr(p);
} | c58cd4a857c8d4a930cf7c4c94bccb4d6fa4f285 | [
"C++"
] | 1 | C++ | MorawskiR/Reference-pointer | 77cfc7d679e54ee4ebd49bdddcb72e5a4944c02d | 556fe6424f2beadb6c61e88149206b8a02ae4d39 |
refs/heads/master | <file_sep>class Section < ApplicationRecord
# belongs_to :page
has_many :section_edits
has_many :admin_users, :through => :section_edits
end
<file_sep>class Page < ApplicationRecord
belongs_to :subject, { :optional => false}
# has_many :sections
has_and_belongs_to_many :admin_users
end
<file_sep>Problem Records When Learning Ruby on Rails
==========================
##### Ruby on Rails 5 Essential Training: https://www.lynda.com/Ruby-Rails-tutorials/Ruby-Rails-5-Essential-Training/500551-2.html
##### Notice: Record every problem when i learned ruby on rails. I hope my experience can help you to learn ruby on rails better.
### 1. Get Started
#### (1) Create a project
##### (a) Use "brew install sql" to install sql
##### (b) Initialize ruby on rails project: rails new simple_cms -d mysql.
name is simple_cms, use mysql database
#### (2) Configure a project
##### (a) Input "mysql -u root -p" and the password of my mbp doestn't word.
Use "mysql.server start" to start the server of mysql;
The default password of the root is blank, just type "Enter" will be OK.
##### (b) Alter the database to other user.
Use "GRANT ALL PRIVILEGES ON simple_cms_test.* TO 'rails_user'@'localhost' IDENTIFIED BY 'secre<PASSWORD>';";
simple_cms_test is the name of database, rails_user is the name of user,
localhost is the server of the user, secretpassword is the password of this database
##### (c) After changing the username and password in database.yml, using "rails db:schema:dump" to connect to the data base and dump to the text, get "rails aborted! Mysql2::Error: Access denied for user 'rails_user'@'localhost' ..."
Made mistake when setting the password in database.yml file, set the password as "<PASSWORD>", the password set in the mysql is "<PASSWORD>". Foolish mistake.
#### (3) Access a Project
##### (a) How to start and stop server.
Start: rails s
Stop: control + c
#### (4) Generate a controller and view
##### (a) What does "rails generate controller demo index" do.
Create a controller named 'demo' with an action named 'index'(the name of views).
'demo' is the folder name, 'index' is view template name.
Use "localhost:3000/demo/index" can check this view in the controller
#### (5) Server request handling
##### (a) Build folder named "demo" in public folder and add a file named "static_page.html"
web server first looks for a matching file on the public folder.
in browser, input "localhost:3000/demo/static_page.html" can visit this page
#### (6) Routes
##### (a) How to set default route?
get ':controller(/:action(/:id))'
##### (b) How to set default route?
root 'demo#index', tells which controller and action should route to.
### 2. Controllers, Views, and Dynamic Content
#### (1) Render a template
##### (a) How to use render to override the default route
In app/controllers/demo_controller.rb, use:
def index
render('hello')
end
so when you visit /demo/index, you will view the template of "hello.html.erb".
render(:template => 'demo/hello')
#### (2) Redirect actions
##### (a) How to redirect to other pages?
It need the combination of config/routes.rb and apps/controllers/demo_controller.rb.
in routes.rb:
def other_hello
redirect_to(:action => 'hello')
end
in demo_controller.rb
get 'demo/other_hello'
the routes parse the address of browser and get other_hello string and send it to controller to handle it.
#### (3) Instance variable
##### (a) How to use instance variable.
In demo_controller.rb, define an instance variable like this followed by @,
def hello
@array = [1,2,3,4,5]
render('hello')
end
In hello.html.erb, we can use this array like:
<% @array.each do |n|>
#### (4) Link
##### (a) How to create a link
the link in ruby on rails like this: <%= link_to(text, target) %>
<%= link_to("one link", {:action => 'index'}) %>
#### (5) URL parameters
##### (a) How to use parameters in URL?
aa) In index.html.erb, construct a url link with parameters:
<%= link_to('Hello with parameters', {:action => 'hello', :page => 5, :id => 20}) %><br />
bb) In demo_controller.rb, fetch the parameters in url:
@id = params[:id]
@page = params[:page]
these instance variables can be used in templates
cc) In hello.html.erb, display this paramters:
ID: <%= @id %>
ID: <%= params[:id] %>
### 3. Datebase and migration
#### (1) Generate migrations
##### (a) the line to generate a migration.
rails generate migration DoNothingYet
#### (2) Generate models
##### (a) How to generate a model and add column in table.
aa) rails generate model User,
get an xxx_create_users.rb in db/migrate
bb) t.column "first_name", :string, :limit => 25
##### (b) The relationship between database and rails
database = application
table = model
column = attribute of model
#### (3) Run migration
##### (a) Run "rails db:migrate" fail and get error.
Forget to start mysql server.
##### (b) Basic operation of mysql.
aa) rails -u rails_user -p simple_cms_development
bb) SHOW TABLES;
cc) SHOW FIELDS FROM users;
##### (c) How to down/up the migration
down: rails db:migrate VERSION=0;
use 'rails db:migrate:status' to find the version you want to up;
up: rails db:migrate VERSION=...;
schema file will keep track the version
### 4. Models and ActiveRecord
#### (1)Mdoel naming
##### (a) what is the relationship between files, classes and tables.
These names should be sync, for example:
file name: admin_user.rb
classe name: class AdminUser < ApplicationRecord
table name: admin_users
#### (2) The Rails console
##### (a) How to use rails console.
Use 'rails console' to access rails console.
Then we can use activerecord of the table, eg:
subject = Subject.new
subject.name = 'test'
#### (3) Create record
##### (a) difference between new and create.
aa) subject = Subject.new(:name => "First Subject", position: 1, visible: true, created_at: nil, updated_at: nil)
it does not save automatically
bb) subject = Subject.create(:name => "Second Subject", :position => 2)
it save the record automatically
#### (4) Update record
##### (a) two ways of updating record
aa) subject = Subject.find(1)
subject.name = "Initial Subject"
subject.save
it does not save automatically
bb) subject = Subject.find(2)
subject.update_attributes(:name => "Next Subject", :visible => true)
it save the record automatically
#### (5) Delete record
##### (a) How to delete a record
subject = Subject.find(3)
subject.destroy
This record will be deleted from database
#### (6) Find records
##### (a) Three ways to find records
aa) subject = Subject.find(1)
bb) subject = Subject.find_by_name("Initial Subject")
cc) subjects = Subject.all
#### (7) Query methods: Condidtions
##### (a) Three ways to construct query by using where.
aa) subject = Subject.where(:visible => true)
bb) subject = Subject.where("visible = true")
cc) subject = Subject.where(["visible = ?", true])
#### (8) Query methods: Order, limit, and offset
##### (a) Different ways to use these methods.
aa) subjects = Subject.order(:position)
bb) subjects = Subject.order("position ASC")
cc) subjects = Subject.limit(1).offset(2)
#### (9) Named scopes
##### (a) How to use named scope?
In app/models/subject.rb, we can define some named scopes, these variable can be used in rails console. eg:
scope :visible, lambda { where(:visible => true) }
scope :invisible, lambda { where(:visible => false) }
scope :sorted, lambda { order("position ASC") }
scope :newest_first, lambda { order("created_at DESC") }
scope :serach, lambda { |query| where(["name LIKE ?", "%#{query}%"])}
in rails console, we can use like this:
Subject.invisible
### 5. Associations
#### (1)One-to-one associations
##### (a) How to build one-to-one associations.
in subjec.rb: has_one :page
in page.rb: belongs_to :subject
subject = Subject.find(1)
first_page = Page.new(...)
subject.page = first_page
##### (b) How to cancel one-to-one associations.
subject.page = nil
subject.page.destroy
#### (2) One-to-Many Associations
##### (a) How to build one-to-many associations.
in subject.rb: has_many :pages
in page.rb: belongs_to :subject
subject.pages << first_page
subject.pages << second_page
##### (b) How to cancel one-to-many associations.
subject.pages.delete(second_page)
#### (3) Many-to-many associations: Simple
##### (a) How to build many-to-many associations
aa) Create a join table
generate migration CreateAdminUsersPagesJoin
in /dbmigrate file:
class CreateAdminUsersPagesJoin < ActiveRecord::Migration[5.1]
def up
create_table :admin_users_pages, :id => false do |t|
t.integer "admin_user_id"
t.integer "page_id"
end
add_index("admin_users_pages", ["admin_user_id", "page_id"])
end
def down
drop_table :admin_users_pages
end
end
the name of the page is admin_users_pages
bb) set relationship
in admin_user.rb: has_and_belongs_to_many :pages
in page.rb: has_and_belongs_to_many :admin_users
cc) build relationship
me.pages << first_page
#### (4) Many-to-many associations: Rich
##### (a) How to build many-to-many associations use another table(model).
aa) rails generate model SectionEdit
bb) in db/migrate file:
class CreateSectionEdits < ActiveRecord::Migration[5.1]
def up
create_table :section_edits do |t|
t.integer "admin_user_id"
t.integer "section_id"
t.string "summary"
t.timestamps
end
add_index("section_edits", ['admin_user_id', 'section_id'])
end
def down
drop_table :section_edits
end
end
cc) rails db:migrate
dd) in admin_user.rb:
has_many :section_edits
in section.rb:
has_many :section_edits
in section_edit.rb
belongs_to :admin_user
belongs_to :section
ee) edit = SectionEdit.new(:summary => "test edit", :admin_user => me, :section => section)
#### (5) Traverse a rich association
##### (a) How to traverse a rich association
by using through
aa) in admin_user.rb: has_many :sections, :through => :section_edits
bb) in section.rb: has_many :admin_users, :through => :section_edits
cc) me.sections
### 6. CRUD, REST, and Resourceful Routes
#### (1) CRUD
(a) Create a controller with CRUD action.
rails generate controller Subjects index show new edit delete
aa) create a controller named SubjectController
in this file, it added some actions:
def index
end
...
bb) create a view folder named subjects
this folder contains this correspoding views such as delete.html.erb ...
cc) create corresponding routes in routes.rb
such as: get 'subjects/delete'
#### (2) REST
##### (a) REST HTTP Verbs
index - get
show - get
new - get
create - post
edit - get
update - patch
delete - get
destroy - delete
#### (3) Resourceful routes
##### (a) How to define and show resourceful routs
delete get 'subjects/delete' and add code:
resources :subject do
member do
get :delete
end
end
this block of code add delete action
### 7. Controllers adn CRUD
#### (1) Read action: Index
##### (a) All the parts of MVC architecture.
aa) in url use /subjects
bb) Rails took the url and determine to use resourceful routes SubjectsController#index
cc) in subjects_controller, in index action, it operate some operations, the default render it to 'index.html.erb'
dd) in 'index.html.erb' view, show corresponding info
ee) the view sends back to the browser
#### (2) Read action: Show
##### (a) How to use helper to implement subject resourceful routes.
aa) index.html.erb
<%= link_to("Show", subject_path(subject), :class => 'action show') %>
or
<%= link_to("Show", {:controller => "subjects", action => "show", :id => "subject.id"}, :class => 'action show') %>
bb) subjects_controller.rb
def show
@subject = Subject.find(params[:id])
end
use instance variable and get parameter from url
cc) show.html.erb
use @subject to use the instance variable
| 95162a6c9ea04ba293714611809e98522e7379ee | [
"Markdown",
"Ruby"
] | 3 | Ruby | freezaku/Ruby_on_rails_exercise | 644e29f51f27d8157c1aea44c271ec2057af8c41 | 30e5bc98abf9d0d80ce5a9695d984d79252bd3d4 |
refs/heads/master | <repo_name>shamtomson/ENGG1003---Programming-Assignment-1-English-Text-Cyphers<file_sep>/ProgrammingAssignment1EnglishTextCiphersbyc3324679.c
/* Programming Assignment 1: English Text Ciphers by c3324679 */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void UPPERCASE(char str[]); //Function prototype for conversion of lowercase input to uppercase letters with the argument of a string 'str[]'
void rotationencryption(char inputtext[], char rot); //Function prototype for 'Encryption of a message with a rototation cypher given the message text and rotation amount'. Argument is the string 'inputtext[]' and the char variable 'rot'
void rotationdecryption(char inputtext2[], char rot); //Function prototype for 'Decryption of a message encrypted with a rotation cipher given cipher text and rotation amount'. Argument is the string 'inputtext2[]' and the char variable 'rot'
void substitutionencryption(char inputtext3[], char substitution[]); //Function prototype for 'Encryption of a message with a substitution cipher given message text and alphabet substitution'. Argument is the strings 'inputtext3[]' and 'substitution[]' from the 'key.txt' file
void substitutiondecryption(char inputtext4[], char substitution2[]); //Function prototype for 'Decryption of a message encrypted with a substitution cipher given cipher text and substitutions'. Argument is the strings 'inputtext4[]' and 'substitution2[]' from the 'key.txt' file
void rotationdecryptionhard(char inputtext5[]); //Function prototype for 'Decryption of a message encrypted with a rotation cipher given cipher text only'. Argument is the string 'inputtext5[]'
void substitutiondecryptionhard(char inputtext6[]); //Function prototype for 'Decryption of a message encrypted with a substitution cypher given cypher text only. Argument is 'inputtext6[]'
int main() {
/* POINTERS TO FILES */
FILE *selection; //Pointer to file containing the selection menu
FILE *rotation; //Pointer to the file containing rotation amount for rotation cypher decryption and encryption
FILE *message; //Pointer to the file containing the message to be encrypted
FILE *encryptedmessage; //Pointer to the file containg an encrypted message to be decrypted
FILE *thekey; //Pointer to the file containing the 26 letter key for a substitution cypher
/* USER FRIENDLY MENU SYSTEM */
printf("Please select from the following menu by entering the integer of desired pathway");
printf(" into 'selection.txt' file:\n\n");
//Printf statements offer a menu for the user to choose from and explain where input must be placed in order for program to run.
printf(" 1. Encryption of a message with a rotation cypher given the message text and rotation amount\n");
printf(" 2. Decryption of a message encrypted with a rotation cypher given cypher text and rotation amount\n");
printf(" 3. Encryption of a message with a substitution cypher given the message text and alphabet substitution\n");
printf(" 4. Decryption of a message encrypted with a substitution cypher given cypher text and substitutions\n");
printf(" 5. Decryption of a message encrypted with a rotation cypher given cypher text only\n");
printf(" 6. Decryption of a message encrypted with a substitution cypher given cypher text only\n\n");
//Each selection option denotes a part of the assesmnet to be tested upon thereby making it easy for the user (typically an ENGG1300 marker) to select a desired task to test
selection = fopen("selection.txt", "r"); //The pointer is initialised to become information read from the open file 'selection.txt'
int item; //Variable 'item' declared as data type int to store the selection made in file 'selection.txt'
fscanf(selection, "%d", &item); //Selection made by user and read from the file pointed at by 'selection' becomes stored in 'item' as an integer type, if incorrect input is selected the user will be promped by the switch statement to place a correct input value that will allow code to run
/* SWITCH STATEMENT FOR MENU */
switch (item){ //Switch stement determines the correct code to be run according to the input selected by user and stored within the variable 'item' hence the argument of 'item'
/* TASK 1 */
case(1): //Case 1 will run if the user input in 'selection.txt' was '1' and the user selected Encryption of a message with a rotation cypher given the message text and rotation amount
printf("You selected:\n 1. Encryption of a message encrypted with a rotation cypher given cypher text and rotation amount\n\n"); //printf output assures user that the correct and desired task was selected
/* STORING ROTATION AMOUNT FOR ENCRYPTION */
int rot; //The variable 'rot' is initialised as an integer that will be used to store the rotation amount to be used in the function 'rotationencryption()' for encryption
printf("Enter the rotation amount into 'rotation.txt' file:\n"); //This is a user prompt to enter the desired rotation amount into the file 'rotation.txt'
rotation = fopen("rotation.txt", "r"); //The pointer 'rotation' is initialised to become information read from the open file 'rotation.txt'
//The information will be the desired rotation amount of the user (how much each letter will be rotated)
fscanf(rotation, "%d", &rot); //The information read from the file pointed at by 'rotation' becomes stored as a integer variable; 'rot'.
/* STORING USER INPUT MESSAGE FOR ENCRYPTION */
printf("Enter the message to be encrypted into 'message.txt' file:\n\n"); //This promts user to enter the encrypted message to be decrypted into the file 'message.txt'
char inputtext[1023]; //The array of type char 'inputtext' will store each character entered into input. It is given a length 1023 to minimise memory use as it is assumed the input will be less than 1000 characters
message = fopen("message.txt", "r"); //The pointer 'message' is initialised to become the information read from the open file 'message.txt'
//This information is necessary in order to produce an output which takes a desired message from the user.
fscanf(message,"%[^\n]s", inputtext); //This stores the input text into array as a string, also ensuring that all whitespace remains using %[^\n]s format specifier
/* CONVERTING MESSAGE TO UPPERCASE */
UPPERCASE(inputtext); //The function 'UPPERCASE' is called to convert the message to be encrupted (stored in inputtext) to uppercase letters before the rotation takes place. This appeases to the assigment criteria simltaneously simplifying the computation
//This simplifies the process by working within a smaller ASCII range, similarly minimising the length of the code.
//The output will be stored in the string 'inputtext[]' to be used in the encrypting function
/* PASSING MESSAGE TO ROTATION ENCRYPTION FUNCTION */
rotationencryption(inputtext, rot); //The function 'rotationencryption()' is called with an argument of the string 'inputtext' and the desired rotation amount stored in 'rot'
break; //Break statement causes the compiler to exit the switch statement as all the necessary coding tasks have been completed
/* TASK 2 */
case(2): //Case 2 will run if the user input in 'selection.txt' was '2' and the user selected Decryption of a message encrypted with a rotation cipher given cipher text and rotation amount
printf("You selected:\n 2. Decryption of a message encrypted with a rotation cypher given cypher text and rotation amount\n\n"); //printf output assures user that the correct and desired task was selected
/* STORING ROTATION AMOUNT FOR DECRYPTION */
printf("Enter the rotation amount into 'rotation.txt' file:\n"); //This is a user prompt to enter the rotation decryption amount into the file 'rotation.txt'
rotation = fopen("rotation.txt", "r"); //The pointer 'rotation' is initialised to become information read from the open file 'rotation.txt'
//The information will be the rotation amount of the cypher text (how much each letter has beeen rotated)
fscanf(rotation, "%d", &rot); //The information read from the file pointed at by 'rotation'becomes stored as a integer variable; 'rot'.
/* STORING USER CYPHER TEXT FOR DECRYPTION */
printf("Enter the encrypted message into 'encryptedmessage.txt' file:\n"); //This promts user to enter the encrypted message to be decrypted into the file 'encryptedmessage.txt'
char inputtext2[1023]; //A char array/string, 'inputtext2' of type char will store each character entered into input. It is given a length 1023 to minimise memory use as it is assumed the input will be less than 1000 characters
//Using the same array as previous task may result in compiler warnings and errors, it is simpler to create a new array for each task.
encryptedmessage = fopen("encryptedmessage.txt", "r"); //The pointer 'encryptedmessage' is initialised to become the information read from the open file 'encryptedmessage.txt'
//This information is necessary in order to produce an output which takes a desired cypher message from the user.
fscanf(encryptedmessage,"%[^\n]s", inputtext2); //This stores the input text into array as a string (inputtext2[]), also ensuring that all whitespace remains using %[^\n]s
/* CONVERTING CYPHER TEXT TO UPPERCASE */
UPPERCASE(inputtext2); //The input string stored in 'inputtext2' is passed as the function argument for UPPERCASE() function
//This function will convert the user input to UPPERCASE letters simplifying the decryption process
/* PASSING MESSAGE TO ROTATION DECRYPTING FUNCTION */
rotationdecryption(inputtext2, rot); //The encrypted cypher message stored in 'inputtext2[]' and its rotated amount stored in 'rot' is passed to the function rotationdecryption as its function argument
//The output of the function will be sent to both .a/.out and the file 'output.txt' by the function
break; //break statement teslls the compiler that all the correct code has been read and to exit switch statement
/* TASK 3 */
case(3): //Case 3 will run if the user input in 'selection.txt' was '3' and the user selected Encryption of a message with a substitution cypher given the message text and alphabet substitution
printf("You selected:\n 3. Encryption of a message with a substitution cypher given the message text and alphabet substitution\n\n"); //printf output assures user that the correct and desired task was selected
/* STORING SUBSTITUTION KEY FROM USER INPUT */
char substitution[26]; //A char array/string 'substitution is declared to store the substitution key for encryption
//At the same time it is given a length of 26 as the key must be 26 letters as no single letter may repeat in a substitution cypher
printf("Enter the substitution key of 26 letters into 'key.txt' file:\n"); //The user is prompted by the printf() statement to enter the 26 letter key into 'key.txt' file
thekey = fopen("key.txt", "r"); //The pointer variable 'thekey' is initialised as the open file 'key.txt'. This file is a read only file
//The function fopen() opens the 'key.txt' file to be read
fscanf(thekey,"%[^\n]s", substitution); //The user input from the file 'key.txt' pointed at by 'thekey is stored in the char array 'substitution' to be used in encryption
/* STORING MESSAGE TO BE ENCRYPTED FROM USER INPUT */
char inputtext3[1023]; //A char array 'inputtext4[]' is created of length 1023 which will store the input text of user/message to be encrypted
printf("Enter the message to be encrypted into 'message.txt' file:\n\n"); //printf() statement promps the user to emter the message to be encrypted into the correct file
message = fopen("message.txt", "r"); //The pointer variable 'message' is initialised as the opened file 'message.txt' which is a read only file
fscanf(message,"%[^\n]s", inputtext3); //fscanf() stores the input text into array 'inputtext3[]' as a string, also ensuring that all whitespace remains using %[^\n]s format specifier
/* CONVERTING MESSAGE TO UPPERCASE */
UPPERCASE(inputtext3); //The message to be encrypted stored in 'inputtext3' is passed to the function 'UPPERCASE()' which will convert the message to uppercase letters in order to simplify the encryption process
UPPERCASE(substitution); //The substitution encryption key stored in 'substitution is passed to the function 'UPPERCASE' which will convert the 26 letter key to uppercase letters
/* PASSING MESSAGE AND SUBSTITUTION KEY TO FUNCTION */
substitutionencryption(inputtext3, substitution); //Both the message to be encrypted (stored in 'inputtext3') and the substitution key (stored in 'substitution') are passed to the function 'substitutionencryption()'
//The function substitutionencryption() will process the input message and substitution key to produce an encrypted message
break; //'break' statement tells compiler to exit the switch() flow control
case(4): //Case 4 will run if the user input in 'selection.txt' was '4'
printf("You selected:\n 4. Decryption of a message encrypted with a substitution cypher given cypher text and substitutions\n\n"); //printf output assures user that the correct and desired task was selected
/* STORING SUBSTITUTION FROM USER INPUT FILE */
char substitution2[26]; //A char array is created which will store the 26 letter substitution key within 'substitution2[]'. It is given a length of 26 as there is only 26 possible substitutions
printf("Enter the 26 letter substitution key into 'key.txt' file:\n"); //printf statement promps the user to enter the substitution key into the correct file
thekey = fopen("key.txt", "r"); //The pointed 'thekey' is initialised as the open file 'key.txt'. The file is a read (r) only file which will hold the substitution key to be read
fscanf(thekey,"%[^\n]s", substitution2); //fscanf() function stores the substitution key entered by the user into the file 'key.txt' into the char array 'substitution2' that will be used to decrypt the cypher message
/* STORING MESSAGE TEXT FROM USER INPUT FILE */
printf("Enter the encrypted message into 'encryptedmessage.txt' file:\n\n"); //This promts user to enter the encrypted message to be decrypted into the correct file
char inputtext4[1023]; //An array of type char ('inputtext4[]')is created which will store each character entered into input
encryptedmessage = fopen("encryptedmessage.txt", "r"); //The pointer 'encryptedmessage' is initialised as the open file 'encryptedmessage.txt' which contains the encrypted message to be decrypted
//The fopen() function opens the file 'encryptedmessage.txt' as a read only file
fscanf(encryptedmessage,"%[^\n]s", inputtext4); //fscanf() stores th input text from the file ponted at by 'encryptedmessage' and srores it within the char array 'inputtext4[]' to be used in the decryption function
/* CONVERTING USER INPUT AND SUBSTITUTION KEY TO UPPERCASE LETTERS */
UPPERCASE(substitution2); //The substitution key stored in 'substitution2[]' is passed to the 'UPPERCASE()' function which will convert the key to uppercase letters
UPPERCASE(inputtext4); //The encrypted message stored in 'inputtext4[]' is also converted to uppercase by passing message to the 'UPPERCASE()' function
/* PASSING THE ENCRYPTED MESSAGE AND SUBSTITUTION KEY TO DECRYPTING FUNCTION */
substitutiondecryption(inputtext4, substitution2); //Following conversion to uppercase, both the encrypted message and substitution key is passed to the 'substitutiondecryption' function as its function argument
//The function will send output to both a./.out and the file 'output.txt'
break; //break statemnet tells compiler to exit the switch flow control
case(5): //Case 5 will run if the user input in 'selection.txt' was '5'
printf("You selected:\n 5. Decryption of a message encrypted with a rotation cypher given cypher text only\n\n"); //printf output assures user that the correct and desired task was selected
/* STORING THE MESSAGE TO BE DECRYPTED FROM USER INPUT FILE */
printf("Enter the encrypted message into 'encryptedmessage.txt' file:\n"); //This promts user to enter the encrypted message to be decrypted into the correct file
char inputtext5[1023]; //An array of type char is created which will store each character entered into input in 'inputtext5'
encryptedmessage = fopen("encryptedmessage.txt", "r"); //The pointed 'encryptedmessage' is initialised as the open file 'encryptedmessage.txt'
//The fopen() function opens the dile as a read only file
fscanf(encryptedmessage,"%[^\n]s", inputtext5); //fscanf() stores the encrypted message from user into the char array 'inputtext5[]', also ensuring to take all whitespace
/* CONVERTING THE ENCRYPTED MESSAGE TO UPPERCASE */
UPPERCASE(inputtext5); //The user input/encrypted message is passed as the function argument of 'UPPERCAS()' which will convert all input to uppercase letters
/* PASSING THE ENCRYPTED MESSAGE TO DECRYPTING FUNCTION */
rotationdecryptionhard(inputtext5); //The encrypted message once converted to uppercase in passed to the decrypting function which will produce the correct output for user
//The function 'rotationdecryptionhard()' will send output to both a./.out and the file 'output'
break; //break statemnet tells compiler to exit the switch flow control
/* TASK 6 */
case(6): //Case 6 will run if the user input in 'selection.txt' was '6'
printf("You selected:\n 6. Decryption of a message encrypted with a substitution cypher given cypher text only\n\n"); //printf output assures user that the correct and desired task was selected
/* STORING ENCRYPTED MESSAGE FROM USER INPUT FILE */
printf("Enter the encrypted message into 'encryptedmessage.txt' file:\n"); //This promts user to enter the encrypted message to be decrypted into the correct file
char inputtext6[1023]; //An array of type char is created which will store each character entered into input in 'inputtext6[]'
encryptedmessage = fopen("encryptedmessage.txt", "r"); //The pointer 'encryptedmessage' is initialised as the open file 'encryptedmessage.txt' that contains the user input and message to be decrypted
fscanf(encryptedmessage,"%[^\n]s", inputtext6); //fscanf() takes the user input from file pointed at by encrypted message and stores it in the char array 'inputtext6[]' for decryption
/* CONVERTING ENCRYPTED MESSAGE TO UPPERCASE LETTERS */
UPPERCASE(inputtext6); //The encrypted message is passed to the 'UPPERCASE()' function which will convert all letters to uppercase for decryption
/* PASSING ENCRYPTED MESSAGE TO DECRYPTING FUNCTION */
substitutiondecryptionhard(inputtext6); //Once converted to uppercase the encrypted message stored in 'inputtext6[]' is passed to the 'substitutiondecryptionhard[]' function to decrypt cypher message
//The output of function will be sent to both a./.out and the output file 'output.txt'
break; //break statement tells compiler to exit the switch flow control
default: //default will only run if incorrect input is enterd into the 'selection.txt' file, or otherwise no selection is made.
printf("Please try again by selecting an option from the menu\n"); //printf statement tells the user to enter a correct input by selecting an option from the menu selection
}
fclose(selection); //The file 'selection.txt' pointed at by selection is closes as it is no longer needed
return 0; //Compiler exits code as it has reached the end of executable statemnets within the function main()
}
/* UPPERCASE FUNCTION */
void UPPERCASE(char str[]) //Function definition for uppercase with the argument of a char array/string
{
int i = 0; //An integer 'i' is declared = to zero which will be used to access element of the user input string
int length; //The variable length is declared as an integer which will be used to store the length of the user input string
length = strlen (str); //The length variable is made equal to the length of the string
//Length of the string is produced by calling the function 'strlen()' and placing the string as its argument
printf ("length is %d\n", length); //Sending the length to a./.out aids in the debugging process and alows user to see what the compiler is processing
while (i < length) { //A while runs through each element within the string that is of use (< length)
//Any element >length of the string is considered garbage and therefore not necessary to convert
if ((str[i] > 96) && (str[i] < 123)) { //if statemnet runs for elements of the string that are within the ASCII lowercase letter range (97-122)
str[i] = str[i] - 32; //Elements of the string that are within the ASCII lowercase value range are substituted 32 values as the difference between each correspondng lowercase-uppercase letter is 32
//Therefore, each lowercase element becomes its corresponding uppercase value
}
i++; //The counter variable i is incremented so that while loop continues to run through each element of the input string
}
printf("The string converted to uppercase letters is: %s\n", str); //printf statement sends the message converted to uppercase to a./.out to aid in debugging and allow to recognise the processes occuring within the compiler
}
/* TASK 1 FUNCTION */
void rotationencryption(char inputtext[], char rot) //Function definition for rotationencryption function is provided that takes the user input of the message to be encrypted and the rotation amount
{
FILE *output; //This is a pointer to the file 'output.txt' where the encrypted message will be sent to (as well as .a/.out)
output = fopen("output.txt", "w"); //The pointer output is initialised as the open file 'output.txt' where information will be written to, hence the 'w'
int length; //The variable length is declared as an integer and will hold the length of the user input/message to be encrypted
length = strlen(inputtext); //The variable length becomes the length of the user input by calling the function 'strlen()' with the argument of the user input
printf("The length is: %d\n", length); //printf statement prints the length of the string to a./.out to aid in debugging and allow the user to recognise the processes occuring within the compiler
int i = 0; // a counting integer 'i' is declared to access seperate elements of the user input message string
char letter = 1; //The char variable 'letter' is initialised to simplify the encryption process as each element will be seperately stored in this variable before being sent to a./.out and output file
printf("The message: %s. With a rotation %d is:\n", inputtext, rot); //printf statement tells the user the rotation and message that has been entered into the input Files to ensure that correct data and information has been compiled
while(i < length){ //while loop is made to run through each element of the string to ensure that each letter gets correctly rotated whilst i is constantly incremented
if((inputtext[i] > 90 - rot) && (inputtext[i] <= 90)){ //if statement takes all uppercase letters which will not be rotated within the ASCII range of capital letters and would instead be "cut-off" by being over rotated
letter = inputtext[i] + rot - 26; //The character is rotated beyond the ACSII capital letter range and then substituted 26 values to reach its corresponding rotated letter
printf("%c", letter); //The encrypted letter is sent to a./.out as the variable 'letter'
fprintf(output, "%c", letter); //The encrypted letter is also sent to the file 'output.txt'
i++; //i is incremented to ensure that each character of the string is encrypted.
}
else if((inputtext[i] <= 90 - rot) && (inputtext[i] >= 65)){ //else if statemnt takes all of the letters that may be rotated and not cut off by recieving a value not within the ASCII range for capital letters (65-90)
letter = inputtext[i] + rot; //The variable 'letter' becomes the letter + rotation for the position 'i' within the length of the input message to be encrypted. This produces the correctly rotated element of the cypher text
printf("%c", letter); //The newly encrypted letter is sent to a./.out using the printf statement
fprintf(output, "%c", letter); //The letter is also sent to the file 'output' which shows only the new cypher text
i++; //i is incremented to ensure that each character of the string is encrypted.
}
else if(inputtext[i] == 32){ //This else if statement ensures that whitespace is not encrypted and is instead maintained
//Whitespace has the ASCII number of 32, therefore the position of inputtext[i] equal to 32 is an area of whitespace
printf(" "); //We print a single space to a./.out in order to maintain this whitespace
fprintf(output, " "); //Similarly, a space is sent to the file 'output.txt' for user output
i++; //i is incremented to ensure that each character of the string is encrypted.
}
else{ //If the text is neither a capital letter to be encrypted, nor whitespacem, but is instead a symbol or other character we send this straight back to standard output without encryption
letter = inputtext[i]; //The variable 'letter' becomes the character at location 'i'
printf("%c", letter); //This symbol is then sent to a./.out without encryption
fprintf(output, "%c", letter); //The symbol is also sent to the file 'output.txt'
i++; //i is incremented to ensure that each character of the string is encrypted.
}
}
fclose(output); //The file pointed at by output is closed using the 'fclose()' function as no further output is sent from compiler
}
/* TASK 2 FUNCTION */
void rotationdecryption(char inputtext2[], char rot){ //The function definition for the 'rotationdecryption()' function is provided which takes the user input of the char array 'inputtext2[]' and integer variable 'rot'
FILE *output; //This is a pointer to the file 'output.txt' where the encrypted message will be sent to (as well as .a/.out)
output = fopen("output.txt", "a"); //The pointer output is initialised as the open file 'output.txt' where information will be written to, hence the 'w'
int length; //This variable will be used for the length so that function only converts parts of the array within the string lenth
length = strlen(inputtext2); //'strlen() determines the length of string found within the inputtext array
int i = 0; //This is used as a counter for differemt array elements so that they maintain order
char letter = 1; //This variable is not entirely necessary but is used for convinience when converting from ASCII number to letter
printf("The inputtext: %s. With rotation %d is\n", inputtext2, rot); //This is used to ensure that the correct input file has been used for standard input
while(i < length){ //While loop ensures that every element of the string is decrypted so long as i is constantly incremented
if((inputtext2[i] >= 65) && (inputtext2[i] <= 64 + rot)){ //if statement takes all elements of the encrypted message which may be outside of the ASCII range for capital letters when the rotation amount is deducted
letter = inputtext2[i] + (26 - rot); //Instead of simply deducting the rotation amount we must also add 26 to ensure that the decrypted letter, stored in 'letter' produces the correct letter according to its rotation amount and does not fall outside of the ASCII range for capital letters
printf("%c", letter); //The decrypted letter, stored in 'letter' is sent to a./.out
fprintf(output, "%c", letter); //The decrypted letter is also sent to the output file 'output.txt' for user convinience
i++; //The value of i is incremented to ensure that every element is decrypted
}
else if((inputtext2[i] <= 90) && (inputtext2[i] > 64 + rot)){ //else if occurs if an element of the encrypted message stored in 'inputtext2' may be rotated back to its original message without being 'cut-off'
letter = inputtext2[i] - rot; //The decrypted letter is substituted the rotation amount stored in 'rot' in order to find its decrypted letter, stored in 'letter'
printf("%c", letter); //The decrypted letter stored in 'letter' is sent to a./.out
fprintf(output, "%c", letter); //The decrypted letter is also sent to 'output.txt' pointed at by output
i++; //The value of i is incremented to ensure that every element is decrypted
}
else if(inputtext2[i] == 32){ //This else if statement ensures that whitespace is not decrypted and is instead maintained
printf(" "); //Whitespace has the ASCII number of 32, therefore the position of inputtext[i] equal to 32 is an area of whitespace
fprintf(output, " "); //We print a single space to a./.out in order to maintain this whitespace
i++; //The value of i is incremented to ensure that every element is decrypted
}
else{ //If the text is neither a capital letter to be decrypted, nor whitespace, but is instead a symbol or other character we send this straight back to standard output without decryption
letter = inputtext2[i]; //The variable 'letter' becomes the character at location 'i'
printf("%c", letter); //This symbol is then sent to a./.out without encryption
fprintf(output, "%c", letter); //The symbol is also sent to the file 'output.txt'
i++; //The value of i is incremented to ensure that every element is decrypted
}
}
fprintf(output, "\n"); //A newline is printed to the file output for when the function from task 5 is called which used the rotationdecryption function several times, this ensures there is a newline beofre each possible output
fclose(output); //The output file is closed as no further information needs to be printed
}
/* TASK 3 FUNCTION */
void substitutionencryption(char inputtext3[], char substitution[]){
FILE *output; //This is a pointer to the file 'output.txt' where the encrypted message will be sent to (as well as .a/.out)
output = fopen("output.txt", "a"); //The pointer output is initialised as the open file 'output.txt' where information will be written to, hence the 'w'
printf("\nThe encryption key is: %s\nThe message to be encrypted is: %s\n\n", substitution, inputtext3);
int length; //this variable will be used for the length so that function only converts parts of the array within the string lenth
length = strlen(inputtext3); //strlen determines the length of string found within the inputtext array
int i = 0; //This is used as a counter for differemt array elements so that they maintain order
char letter = 1; //The char variable 'letter' aids to simplify the encryption process and acts to transfer an ASCII number to a character
printf("Encrypted message is: "); //printf statement helps the user to undertsand the output produced
while (i < length) { //while loop is created to ensure that each character of the user input is incremented
if (inputtext3[i] == 'A') { //An if statement is made for when the user input is equal to the letter A
letter = substitution[0]; //When the user input is equal to A, the letter becomes substituted with the corresponding letter of the substitution ket stored in the string 'substitution[]'
printf("%c", letter); //The encrypted letter is sent straight to a./.out for the user to read
fprintf(output, "%c", letter); //The encrypted letter is also sent to the file 'output.txt'
i++;} //The counting variable i is incremented to run through every element of the user input
//The if statement is then repeated for every letter of the alphabet so that they are swapped with their corresponding substitution key provided by the user
else if (inputtext3[i] == 'B') {
letter = substitution[1];
printf("%c", letter);
fprintf(output, "%c", letter);
i++;}
else if (inputtext3[i] == 'C') {
letter = substitution[2];
printf("%c", letter);
fprintf(output, "%c", letter);
i++;}
else if (inputtext3[i] == 'D') {
letter = substitution[3];
printf("%c", letter);
fprintf(output, "%c", letter);
i++;}
else if (inputtext3[i] == 'E') {
letter = substitution[4];
printf("%c", letter);
fprintf(output, "%c", letter);
i++;}
else if (inputtext3[i] == 'F') {
letter = substitution[5];
printf("%c", letter);
fprintf(output, "%c", letter);
i++;}
else if (inputtext3[i] == 'G') {
letter = substitution[6];
printf("%c", letter);
fprintf(output, "%c", letter);
i++;}
else if (inputtext3[i] == 'H') {
letter = substitution[7];
printf("%c", letter);
fprintf(output, "%c", letter);
i++;}
else if (inputtext3[i] == 'I') {
letter = substitution[8];
printf("%c", letter);
fprintf(output, "%c", letter);
i++;}
else if (inputtext3[i] == 'J') {
letter = substitution[9];
printf("%c", letter);
fprintf(output, "%c", letter);
i++;}
else if (inputtext3[i] == 'K') {
letter = substitution[10];
printf("%c", letter);
fprintf(output, "%c", letter);
i++;}
else if (inputtext3[i] == 'L') {
letter = substitution[11];
printf("%c", letter);
fprintf(output, "%c", letter);
i++;}
else if (inputtext3[i] == 'M') {
letter = substitution[12];
printf("%c", letter);
fprintf(output, "%c", letter);
i++;}
else if (inputtext3[i] == 'N') {
letter = substitution[13];
printf("%c", letter);
fprintf(output, "%c", letter);
i++;}
else if (inputtext3[i] == 'O') {
letter = substitution[14];
printf("%c", letter);
fprintf(output, "%c", letter);
i++;}
else if (inputtext3[i] == 'P') {
letter = substitution[15];
printf("%c", letter);
fprintf(output, "%c", letter);
i++;}
else if (inputtext3[i] == 'Q') {
letter = substitution[16];
printf("%c", letter);
fprintf(output, "%c", letter);
i++;}
else if (inputtext3[i] == 'R') {
letter = substitution[17];
printf("%c", letter);
fprintf(output, "%c", letter);
i++;}
else if (inputtext3[i] == 'S') {
letter = substitution[18];
printf("%c", letter);
fprintf(output, "%c", letter);
i++;}
else if (inputtext3[i] == 'T') {
letter = substitution[19];
printf("%c", letter);
fprintf(output, "%c", letter);
i++;}
else if (inputtext3[i] == 'U') {
letter = substitution[20];
printf("%c", letter);
fprintf(output, "%c", letter);
i++;}
else if (inputtext3[i] == 'V') {
letter = substitution[21];
printf("%c", letter);
fprintf(output, "%c", letter);
i++;}
else if (inputtext3[i] == 'W') {
letter = substitution[22];
printf("%c", letter);
fprintf(output, "%c", letter);
i++;}
else if (inputtext3[i] == 'X') {
letter = substitution[23];
printf("%c", letter);
fprintf(output, "%c", letter);
i++;}
else if (inputtext3[i] == 'Y') {
letter = substitution[24];
printf("%c", letter);
fprintf(output, "%c", letter);
i++;}
else if (inputtext3[i] == 'Z') {
letter = substitution[25];
printf("%c", letter);
fprintf(output, "%c", letter);
i++;}
else if(inputtext3[i] == 32){ // an else if statement is created for characters of the user input equal to the ASCII value for whitespace to ensure all whitespace is retained
printf(" "); //Where whitespace is found in the input whitespace is printed to a./.out using printf()
fprintf(output, " "); //Whitespace is also printed to the output file 'output.txt'
i++;} //The counting variable i is incremented to ensure that every element of user input gets encrypted
else{ //If the element of user input is neither a letter, nor whitepace then it gets sent to the users output without substitution
letter = inputtext3[i];
printf("%c", letter);
fprintf(output, "%c", letter);
i++;} //The counting variable i is incremented to ensure every element of user input gets encrypted
}
fclose(output); //The file 'output.txt' pointed at by 'output' is closed as mo further information needs to be printed
}
/* TASK 4 FUNCTION */
void substitutiondecryption(char inputtext4[], char substitution2[]){ //The function definition for substitution decryption is given with arguments of the char array 'inputtext4' and the substitution key 'substitution2'
FILE *output; //This is a pointer to the file 'output.txt' where the encrypted message will be sent to (as well as .a/.out)
output = fopen("output.txt", "a"); //The pointer output is initialised as the open file 'output.txt' where information will be written to, hence the 'w'
printf("\nThe encryption key is: %s\nThe message to be decrypted is: %s\n\n", substitution2, inputtext4);
int length; //this variable will be used for the length so that function only converts parts of the array within the string lenth
length = strlen(inputtext4); //determines the length of string found within the inputtext array
int i = 0; //this is used as a counter for differemt array elements so that they maintain order
printf("Decrypted message is: ");
char letter; //The variable 'letter' is made to simplify the encryption process and aid in decryption
while (i <= length) { // while loop ensures that every i element of the user input is decrypted whilever i is incremented
if (inputtext4[i] == substitution2[0]){ //if the encrypted input message is equal to the first element of the substitution stored in 'substitution2' then the decrypted letter would be A
printf("A"); //The letter A is printed to a./.out
fprintf(output, "A"); //A is also printed to the file 'output.txt'
i++;} //The counter variable i is incremented to ensure every element of the encrypted message is decrypted
//This if statement is repeated over a series of else if statements that match the array element with its corresponding substitution and print the correct decrypted character
else if (inputtext4[i] == substitution2[1]){
printf("B");
fprintf(output, "B");
i++;}
else if (inputtext4[i] == substitution2[2]){
printf("C");
fprintf(output, "C");
i++;}
else if (inputtext4[i] == substitution2[3]){
printf("D");
fprintf(output, "D");
i++;}
else if (inputtext4[i] == substitution2[4]){
printf("E");
fprintf(output, "E");
i++;}
else if (inputtext4[i] == substitution2[5]){
printf("F");
fprintf(output, "F");
i++;}
else if (inputtext4[i] == substitution2[6]){
printf("G");
fprintf(output, "G");
i++;}
else if (inputtext4[i] == substitution2[7]){
printf("H");
fprintf(output, "H");
i++;}
else if (inputtext4[i] == substitution2[8]){
printf("I");
fprintf(output, "I");
i++;}
else if (inputtext4[i] == substitution2[9]){
printf("J");
fprintf(output, "J");
i++;}
else if (inputtext4[i] == substitution2[10]){
printf("K");
fprintf(output, "K");
i++;}
else if (inputtext4[i] == substitution2[11]){
printf("L");
fprintf(output, "L");
i++;}
else if (inputtext4[i] == substitution2[12]){
printf("M");
fprintf(output, "M");
i++;}
else if (inputtext4[i] == substitution2[13]){
printf("N");
fprintf(output, "N");
i++;}
else if (inputtext4[i] == substitution2[14]){
printf("O");
fprintf(output, "O");
i++;}
else if (inputtext4[i] == substitution2[15]){
printf("P");
fprintf(output, "P");
i++;}
else if (inputtext4[i] == substitution2[16]){
printf("Q");
fprintf(output, "Q");
i++;}
else if (inputtext4[i] == substitution2[17]){
printf("R");
fprintf(output, "R");
i++;}
else if (inputtext4[i] == substitution2[18]){
printf("S");
fprintf(output, "S");
i++;}
else if (inputtext4[i] == substitution2[19]){
printf("T");
fprintf(output, "T");
i++;}
else if (inputtext4[i] == substitution2[20]){
printf("U");
fprintf(output, "U");
i++;}
else if (inputtext4[i] == substitution2[21]){
printf("V");
fprintf(output, "V");
i++;}
else if (inputtext4[i] == substitution2[22]){
printf("W");
fprintf(output, "W");
i++;}
else if (inputtext4[i] == substitution2[23]){
printf("X");
fprintf(output, "X");
i++;}
else if (inputtext4[i] == substitution2[24]){
printf("Y");
fprintf(output, "Y");
i++;}
else if (inputtext4[i] == substitution2[25]){
printf("Z");
fprintf(output, "Z");
i++;}
else if(inputtext4[i] == 32){ //if the element of the encrypted message is whitespace (ASCII value 32) This else if statement ensures that it is preserved
printf(" "); //Whitespace is printed to a./.out using the printf function
fprintf(output, " "); //Whitespace is also printed to the output file
i++;} //The counting variable i is incremented to ensure that each element is decrypted
else{ //if the encrypted message element is neither a letter nor whitespace it is printed as output without decryption
letter = inputtext4[i];
printf("%c", letter); //The symbol is printed without modification to a./.out
fprintf(output, "%c", letter); //The symbol is also printed to the file 'output.txt
i++;} //The counting variable i is incremented so that every element of the encrypted message is decrypted
}
fclose(output); //The fclose() function closes the file 'output.txt' pointed at by output as no further output is being produced
}
/* TASK 5 FUNCTION */
void rotationdecryptionhard(char inputtext5[]){ //function body for the function rotationdecryptionhard is provided with the argument of inputtext5 that holds the encrypted message provided by the user
char ArrayForMostUsed[1024] = { 0 }; //A char array is initialised with each element equal to 0
//This array will be used to determine the most common letter of user input from which we can determine the rotation amount
int i = 0; //A counter variable i is initialised to 0. This will be used to gain an index for each element of the user input stored in inputtext5
int max, insidearray, index = 0; //Three variables are declared and made equal to 0
//The variable 'index' will be used to store the location of the element that holds the most common letter
//The variable 'insidearray' will be used to initialise elements of the char array 'ArrayForMostUsed' without affecting the original encrypted message or causing compiler warnings/errors
//The variable max will be used in flow control to ensure that the length of the input message is not surpassed
for (i = 0; inputtext5[i] != 0; i++) { //for loop is created to initialise each element of the char array 'ArrayForMostUsed' for every value of the encrypted message stored in inputtext5[]
insidearray = inputtext5[i]; //The variable inside array becomes the value produced a each ('i') location in the char array 'inputtext5' that contains the encrypted message
++ArrayForMostUsed[insidearray]; //'ArrayForMostUsed is incremented with the argument of the value of each each encrypted message character
}
max = ArrayForMostUsed[0]; //The variable max is initialised to the first element of ArrayForMostUsed
for (i = 0; inputtext5[i] != 0; i++) { //For loop is created for each element of the encrypted message stored within inputtext5[]
insidearray = inputtext5[i]; //The variable insidearray becomes the value of the encrypted message at 'i' for each iteration of the fopr loop
if ((ArrayForMostUsed[insidearray] > max) && (inputtext5[i] != 32)) { //To determine the most used character we make an if statement for every letter within 'ArrayForMostUsed' with the argument of elements of the encrypted message greater than the current max but not equal to the ASCII value for whitespace
insidearray = inputtext5[i];
max = ArrayForMostUsed[insidearray]; //The new max is initialised as the element of ArrayForMostUsed as it was greater than the previous character tested
index = i; } } //At the same time we make the index variable equal to the location inside the char array 'inputtext5'
//This index value now holds the location for the most common letter within the encrypted message stored in 'inpuuttext5'
printf ("The most used character is: %c\n", inputtext5[index]); //The most used letter is sent to a./.out for debugging purposed and user understanding
//We assume the letter most used is either e, t, or A
printf ("The value of most common character is %d\n\n", inputtext5[index]); //The value of the most common letter is important, too, for debugging purposes mostly
printf("Since E is the most commonly appearing letter in an English sentence, the difference between the value of E and most common letter of the cypher %c could give the rotation amount\n",
inputtext5[index]); //printf statement explains to user the compiling processess that are taking place
printf("The subsequent tests will test for the rotation amount given that the most common letter is not E");
printf(" but instead T, A, I, N, O or S\n\n\n"); //printf statement explains to user the compiling processess that are taking place
char mostcommonletter = inputtext5[index]; //The charcter of the most common letter within the encrypted message is initialised within the variable 'mostcommonletter' to avoid compiler warnings/errors
int rot; //For simplification and use in the 'rotationdecryption()' function the integer variable rot is declared
rot = mostcommonletter; //rot is made equal to the most common letter
if(rot >= 'E'){ //To determine the rotation amount (assuming the most common letter was E) we evaluate for if the most common letter was greater than, or less than E
rot = rot - 'E'; } //E is 69 therefore the difference between a letter > E -69 will give the integer rotation amount
else{ //If the most common letter is less than E
rot = (26 + rot) - 'E'; } //The rotation amount is given by adding 26 to the most common letter and substituting the value of E from the result. This is done to avoid any cut off that may occur since the uppecase letters lie within a limited range in the ASCII table
printf("The rotation amount is likely %d if the most common letter is E\n" , rot); //printf statements aids in user recognition and understanding of compiler processes
rotationdecryption(inputtext5, rot); //The encrypted message and newluy discovered rotation amount is sent as function arguments to the function 'rotationdecryption'
//The function output will then be sent to bot a./.out and the file 'output.txt'
//NOTE: The same process of finding the rotation amount occurs for the letters T, A, and subsequent common letters therfore commenting is unnecessary in further lines
//NOW TESTING FOR T
rot = mostcommonletter;
if(rot >= 'T'){
rot = rot - 'T'; } //E is 69 therefore the difference between a letter > E -69 will give the integer rotation amount
else{
rot = (26 + rot) - 'T'; }
printf("\n\nThe rotation amount is likely %d if the most common letter is T\n" , rot);
rotationdecryption(inputtext5, rot);
//NOW TESTING FOR A
rot = mostcommonletter;
if(rot >= 'A'){
rot = rot - 'A'; } //E is 69 therefore the difference between a letter > E -69 will give the integer rotation amount
else{
rot = (26 + rot) - 'A'; }
printf("\n\nThe rotation amount is likely %d if the most common letter is A\n" , rot);
rotationdecryption(inputtext5, rot);
//NOW TESTING FOR I
rot = mostcommonletter;
if(rot >= 'I'){
rot = rot - 'I'; } //E is 69 therefore the difference between a letter > E -69 will give the integer rotation amount
else{
rot = (26 + rot) - 'I'; }
printf("\n\nThe rotation amount is likely %d if the most common letter is I\n" , rot);
rotationdecryption(inputtext5, rot);
//NOW TESTING FOR O
rot = mostcommonletter;
if(rot >= 'O'){
rot = rot - 'O'; } //E is 69 therefore the difference between a letter > E -69 will give the integer rotation amount
else{
rot = (26 + rot) - 'O'; }
printf("\n\nThe rotation amount is likely %d if the most common letter is O\n" , rot);
rotationdecryption(inputtext5, rot);
//NOW TESTING FOR N
rot = mostcommonletter;
if(rot >= 'N'){
rot = rot - 'N'; } //E is 69 therefore the difference between a letter > E -69 will give the integer rotation amount
else{
rot = (26 + rot) - 'N'; }
printf("\n\nThe rotation amount is likely %d if the most common letter is N\n" , rot);
rotationdecryption(inputtext5, rot);
}
/* TASK 6 FUNCTION */
void substitutiondecryptionhard(char inputtext6[]){ //Function body is provided for 'substitutiondecryptionhard()' with the argument of the char array 'inputtext6[]'
FILE *output; //This is a pointer to the file 'output.txt' where the encrypted message will be sent to (as well as .a/.out)
output = fopen("output.txt", "a"); //The pointer output is initialised as the open file 'output.txt' where information will be written to, hence the 'w'
int length; //this variable will be used for the length so that function only converts parts of the array within the string lenth
length = strlen(inputtext6); //determines the length of string found within the inputtetx array
if(length > 30){ //if the length is greater than 30 it is likely the most common letter will be equal to E, T or A
//Note: The following 22 lines of code were used in 'rotationdecryptionhard()' function. Here contains all the commenting necessary to understand the code
char ArrayForMostUsed2[1024] = { 0 };
int i = 0;
int max, insidearray, index = 0;
for (i = 0; inputtext6[i] != 0; i++) {
insidearray = inputtext6[i];
++ArrayForMostUsed2[insidearray];
}
max = ArrayForMostUsed2[0];
for (i = 0; inputtext6[i] != 0; i++) {
insidearray = inputtext6[i];
if ((ArrayForMostUsed2[insidearray] > max) && (inputtext6[i] != 32)) {
insidearray = inputtext6[i];
max = ArrayForMostUsed2[insidearray];
index = i;
}
}
printf ("The most used character is: %c\n", inputtext6[index]); //we assume the letter most used is either e, or t
printf ("The value of most common character is %d\n\n", inputtext6[index]);
printf("Since the encrypted message is greater than 30 characters it is likely the most common letter of the cypher %c has been substituted for either E, T, or A as these are the most commonly appearing letters in an English sentence.\n\n",
inputtext6[index]);
char mostcommonletter = inputtext6[index]; //By creating a char variable 'mostcommonletter' that is equal to the value of what was found to be the most common character we avoid compiler warnings for using an integer inside a char array
printf("The encrypted cypher message with one substitution complete and assuming the most common letter is E is:\n"); //Printf() statement aids user in understanding the output produced
i = 0; //The counting variable i is made = to 0 to ensure every element of the user input is decrypted
while(i <= length){ //The while loop will run through every element of the encrypted message whilever i is incremented to a value less than the user input
if(inputtext6[i] == mostcommonletter){ //if statement takes any characters within inputtext6 (encrypted message) that are equal to the most common letter
printf("E"); //The letter E is then printed instead of the original value since E is the most common letter in an english statement
fprintf(output, "E"); //'E' is also printed to the file 'output.txt'
i++; //The value of i is incremented so that the every element of the user input is tested
}
else{ //For majority of the user input not equal to the mostcommon letter we will print the original encrypted input of the user
printf("%c", inputtext6[i]); //The encrypted letter. symbol, or whitespace is printed to a./.out
fprintf(output, "%c", inputtext6[i]); //The encrypted letter, symbol or whitespace is also printed to the file 'output.txt'
i++; //The value of i is incremented to ensure that all elements of the encrypted message are tested
}
}
printf("\n\n"); //Two spaces are printed to a./.out to make the output more readable
fprintf(output, "\n\n"); //Two spaces are also printed to the output file to make output more readable
//This process is repeated twice for the letters T and A since T is the seconf most common letter in an english sentence followed by A
printf("The encrypted cypher message with one substitution complete and assuming the most common letter is T is:\n");
i = 0;
while(i <= length){
if(inputtext6[i] == mostcommonletter){
printf("T");
fprintf(output, "T");
i++;
}
else{
printf("%c", inputtext6[i]);
fprintf(output, "%c", inputtext6[i]);
i++;
}
}
printf("\n\n");
fprintf(output, "\n\n");
printf("The encrypted cypher message with one substitution complete and assuming the most common letter is A is:\n");
i = 0;
while(i <= length){
if(inputtext6[i] == mostcommonletter){
printf("A");
fprintf(output, "A");
i++;
}
else{
printf("%c", inputtext6[i]);
fprintf(output, "%c", inputtext6[i]);
i++;
}
}
printf("\n\n");
fprintf(output, "\n\n");
}
else{
printf("Encrypted cypher message is too small to accurately decrypt, please add more cypher text"); //printf statement promps user to insert more cypher text as more is needed to produce an accurate message that uses the correct substitution key. This is sent to a./.out
fprintf(output, "Encrypted cypher message is too small to accurately decrypt, please add more cypher text"); //printf statement promps user to insert more cypher text as more is needed to produce an accurate message that uses the correct substitution key. This is sent to the file 'output.txt'
}
}
| a0b7ab5c3a5b7f58f278d8915775cdaeca3a7741 | [
"C"
] | 1 | C | shamtomson/ENGG1003---Programming-Assignment-1-English-Text-Cyphers | 6b245d6919792e332ced841d6d9918dbe7ea70ac | 85d3d3eb2927f3512c5e94fc13edda5c8104ac8f |
refs/heads/master | <repo_name>YuanYuLin/go_hwmon<file_sep>/src/factory/factory_device.go
package factory
import "config"
import "device"
func CreateDeviceCpu() (device.Cpu_t) {
obj := device.Cpu_t{ Entity:config.ENTITY_PROCESSOR }
return obj
}
func CreateDeviceAmb() (device.Amb_t) {
obj := device.Amb_t{ Entity:config.ENTITY_EXTERNAL_ENVIROMENT }
return obj
}
func CreateDeviceAic() (device.Aic_t) {
obj := device.Aic_t{ Entity:config.ENTITY_ADD_IN_CARD }
return obj
}
func CreateDeviceDimm() (device.Dimm_t) {
obj := device.Dimm_t{ Entity:config.ENTITY_MEMORY_DEVICE }
return obj
}
func CreateDeviceFan() (device.Fan_t) {
obj := device.Fan_t{ Entity:config.ENTITY_FAN_COOLING }
return obj
}
<file_sep>/src/hwmon/msghndlr_task.go
package hwmon
import "mailbox"
import "fmt"
import "common"
import "config"
type TaskMsgHndlr struct {
}
func (o* TaskMsgHndlr)Run() {
mb_msg := mailbox.CreateMailboxMsgHndlr()
isBreakTask := false
for {
msg := <-mb_msg.Channel
req_msg := common.Msg_t { Function:msg.Function, ChannelSrc:msg.ChannelDst, ChannelDst:msg.ChannelSrc, Data:msg.Data }
if msg.ChannelDst == nil {
var res_msg common.Msg_t
switch msg.Function {
case config.EXIT_APPLICATION:
isBreakTask = true
value := common.ValueResponse_t { Value: config.REQUEST_OK }
data := common.DeviceInfo_t { Entity:0, Instant:0, ValueType:config.TYPE_REQUEST_OK, Value:value }
//res_bytes := ConvertDeviceInfoToBytes(data)
res_msg = mailbox.WrapMsg(msg.Function, msg.ChannelSrc, msg.ChannelDst, data)
default:
}
msg.ChannelSrc <-res_msg
} else {
msg.ChannelDst <-req_msg
}
if isBreakTask {
break
}
}
fmt.Println("Exit TaskMsgHndlr")
}
<file_sep>/src/config/misc.go
package config
var IN_SERVICE_PORT = "localhost:8088"
var OUT_SERVICE_PORT = "0.0.0.0:8080"
/*
* GET ->
* Successed : TYPE_xxxx
* Failed : TYPE_REQUEST_ERROR
* SET ->
* Successed : TYPE_REQUEST_OK
* Failed : TYPE_REQUEST_ERROR
* COMMAND ->
* Successed : TYPE_REQUEST_OK
* Failed : TYPE_REQUEST_ERROR
*/
const TYPE_OBJECT int32 = 0x1
const TYPE_TEMPERATURE int32 = 0x2
const TYPE_AVERAGEPOWER int32 = 0x3
const TYPE_MAXPOWER int32 = 0x4
// Used in "EXPECT FAN DUTY"
const TYPE_INITFANDUTY int32 = 0x5
const TYPE_FANDUTY int32 = 0x6
const TYPE_DEVICEFANMAP int32 = 0x7
const TYPE_CPUINFO int32 = 0x8
// Used in "SET" response packet
const TYPE_REQUEST int32 = 0x80
const TYPE_REQUEST_OK int32 = 0x90
const REQUEST_OK int32 = 0x0
const TYPE_REQUEST_ERROR int32 = 0xF0
const REQUEST_ERROR_NOT_FOUND int32 = 0x1
const REQUEST_ERROR_NOT_SET int32 = 0x2
/*
const TYPE_OBJECT string = "object"
const TYPE_TEMPERATURE string = "temperature"
const TYPE_AVERAGEPOWER string = "averagepower"
const TYPE_MAXPOWER string = "maxpower"
// Used in "EXPECT FAN DUTY"
const TYPE_INITFANDUTY string = "init_fanduty"
const TYPE_FANDUTY string = "fanduty"
const TYPE_DEVICEFANMAP string = "d_f_map"
// Used in "SET" response packet
const TYPE_RSP_OK string = "rsp_ok"
const TYPE_RSP_ERROR string = "rsp_error"
//
const TYPE_REQ_CMD string = "req_cmd"
*/
<file_sep>/src/common/common.go
package common
// Msg of Channel communication
type Msg_t struct {
Function string
ChannelSrc chan Msg_t
ChannelDst chan Msg_t
Data interface{}
}
// Msg of Rest communication
type JsonMsg_t struct {
Status int32 `json:"status"`
Version int32 `json:"version"`
Data interface{} `json:"data"`
}
// Data of Channel/Rest communication
type DeviceInfo_t struct {
Entity int32 `json:"entity"`
Instant int32 `json:"instant"`
ValueType int32 `json:"valuetype"`
Key string `json:"key"`
Value interface{} `json:"value"`
}
type ValueTemperature_t struct {
Value float32 `json:"value"`
}
type ValuePower_t struct {
Value float32 `json:"value"`
}
type ValueDuty_t struct {
Value float32 `json:"value"`
}
type ValueFanInstant_t struct {
Value int32 `json:"value"`
}
type ValueRequest_t struct {
Value string `json:"value"`
}
type ValueResponse_t struct {
Value int32 `json:"value"`
}
type ValueCpuInfo_t struct {
MaxTdp int32 `json:"maxtdp"`
CoreNum int32 `json:"cores"`
Identity uint32 `json:"id"`
}
<file_sep>/src/config/dev.go
package config
/*
*
*/
const ENTITY_UNSPECIFIED int32 = 0
const ENTITY_OTHER int32 = 1
const ENTITY_UNKNOWN int32 = 2
const ENTITY_PROCESSOR int32 = 3
const ENTITY_DISK int32 = 4
const ENTITY_PERIPHERAL int32 = 5
const ENTITY_SYSTEM_MANAGEMENT_MODULE int32 = 6
const ENTITY_SYSTEM_BOARD int32 = 7
const ENTITY_MEMORY_MODULE int32 = 8
const ENTITY_PROCESSOR_MODULE int32 = 9
const ENTITY_POWER_SUPPLY int32 = 10
const ENTITY_ADD_IN_CARD int32 = 11
const ENTITY_FRONT_PANEL_BOARD int32 = 12
const ENTITY_BACK_PANEL_BOARD int32 = 13
const ENTITY_POWER_SYS_BOARD int32 = 14
const ENTITY_DRIVE_BACKPLANE int32 = 15
const ENTITY_SYS_INTERNAL_EXP_BOARD int32 = 16
const ENTITY_OTHER_SYSTEM_BOARD int32 = 17
const ENTITY_PROCESSOR_BOARD int32 = 18
const ENTITY_POWER_UNIT int32 = 19
const ENTITY_POWER_MODULE int32 = 20
const ENTITY_POWER_MANAGEMENT_BOARD int32 = 21
const ENTITY_CHASSIS_BACK_PANEL_BOARD int32 = 22
const ENTITY_SYSTEM_CHASSIS int32 = 23
const ENTITY_SUB_CHASSIS int32 = 24
const ENTITY_OTHER_CHASSIS_BOARD int32 = 25
const ENTITY_DISK_DRIVE_BAY int32 = 26
const ENTITY_PERIPHERAL_BAY int32 = 27
const ENTITY_DEVICE_BAY int32 = 28
const ENTITY_FAN_COOLING int32 = 29
const ENTITY_COOLING_UNIT int32 = 30
const ENTITY_CABLE_INTERCONNECT int32 = 31
const ENTITY_MEMORY_DEVICE int32 = 32
const ENTITY_SYSTEM_MANAGEMENT_SW int32 = 33
const ENTITY_BIOS int32 = 34
const ENTITY_OPERATING_SYSTEM int32 = 35
const ENTITY_SYSTEM_BUS int32 = 36
const ENTITY_GROUP int32 = 37
const ENTITY_REMOTE_MANAGEMENT_DEVICE int32 = 38
const ENTITY_EXTERNAL_ENVIROMENT int32 = 39
const ENTITY_BATTERY int32 = 40
const ENTITY_PROCESSING_BLADE int32 = 41
const ENTITY_CONNECTIVITY_SWITCH int32 = 42
const ENTITY_PROCESSOR_MEMORY_MODULE int32 = 43
const ENTITY_IO_MODULE int32 = 44
const ENTITY_PROCESSOR_IO_MODULE int32 = 45
const ENTITY_MANAGEMENT_CONTROLLER_FW int32 = 46
/*
*
*/
const DEV_INSTANT1 int32 = 1
const DEV_INSTANT2 int32 = 2
const DEV_INSTANT3 int32 = 3
const DEV_INSTANT4 int32 = 4
const DEV_INSTANT5 int32 = 5
const DEV_INSTANT6 int32 = 6
const DEV_INSTANT7 int32 = 7
const DEV_INSTANT8 int32 = 8
const DEV_INSTANT9 int32 = 9
const DEV_INSTANT10 int32 = 10
const DEV_INSTANT11 int32 = 11
const DEV_INSTANT12 int32 = 12
const DEV_INSTANT13 int32 = 13
const DEV_INSTANT14 int32 = 14
const DEV_INSTANT15 int32 = 15
const DEV_INSTANT16 int32 = 16
const DEV_INSTANT17 int32 = 17
const DEV_INSTANT18 int32 = 18
const DEV_INSTANT19 int32 = 19
const DEV_INSTANT20 int32 = 20
const DEV_INSTANT21 int32 = 21
const DEV_INSTANT22 int32 = 22
const DEV_INSTANT23 int32 = 23
const DEV_INSTANT24 int32 = 24
const DEV_INSTANT25 int32 = 25
const DEV_INSTANT26 int32 = 26
const DEV_INSTANT27 int32 = 27
const DEV_INSTANT28 int32 = 28
const DEV_INSTANT29 int32 = 29
const DEV_INSTANT30 int32 = 30
const DEV_INSTANT31 int32 = 31
const DEV_INSTANT32 int32 = 32
const DEV_INSTANT33 int32 = 33
const DEV_INSTANT34 int32 = 34
const DEV_INSTANT35 int32 = 35
const DEV_INSTANT36 int32 = 36
const DEV_INSTANT37 int32 = 37
const DEV_INSTANT38 int32 = 38
const DEV_INSTANT39 int32 = 39
const DEV_INSTANT40 int32 = 40
const DEV_INSTANT41 int32 = 41
const DEV_INSTANT42 int32 = 42
const DEV_INSTANT43 int32 = 43
const DEV_INSTANT44 int32 = 44
const DEV_INSTANT45 int32 = 45
const DEV_INSTANT46 int32 = 46
const DEV_INSTANT47 int32 = 47
const DEV_INSTANT48 int32 = 48
const DEV_INSTANT49 int32 = 49
const DEV_INSTANT50 int32 = 50
const DEV_INSTANT51 int32 = 51
const DEV_INSTANT52 int32 = 52
const DEV_INSTANT53 int32 = 53
const DEV_INSTANT54 int32 = 54
const DEV_INSTANT55 int32 = 55
const DEV_INSTANT56 int32 = 56
const DEV_INSTANT57 int32 = 57
const DEV_INSTANT58 int32 = 58
const DEV_INSTANT59 int32 = 59
const DEV_INSTANT60 int32 = 60
const DEV_INSTANT61 int32 = 61
const DEV_INSTANT62 int32 = 62
const DEV_INSTANT63 int32 = 63
const DEV_INSTANT64 int32 = 64
const DEV_INSTANT65 int32 = 65
const DEV_INSTANT66 int32 = 66
const DEV_INSTANT67 int32 = 67
const DEV_INSTANT68 int32 = 68
const DEV_INSTANT69 int32 = 69
const DEV_INSTANT70 int32 = 70
const DEV_INSTANT71 int32 = 71
const DEV_INSTANT72 int32 = 72
const DEV_INSTANT73 int32 = 73
const DEV_INSTANT74 int32 = 74
const DEV_INSTANT75 int32 = 75
const DEV_INSTANT76 int32 = 76
const DEV_INSTANT77 int32 = 77
const DEV_INSTANT78 int32 = 78
const DEV_INSTANT79 int32 = 79
const DEV_INSTANT80 int32 = 80
const DEV_INSTANT81 int32 = 81
const DEV_INSTANT82 int32 = 82
const DEV_INSTANT83 int32 = 83
const DEV_INSTANT84 int32 = 84
const DEV_INSTANT85 int32 = 85
const DEV_INSTANT86 int32 = 86
const DEV_INSTANT87 int32 = 87
const DEV_INSTANT88 int32 = 88
const DEV_INSTANT89 int32 = 89
const DEV_INSTANT90 int32 = 90
const DEV_INSTANT91 int32 = 91
const DEV_INSTANT92 int32 = 92
const DEV_INSTANT93 int32 = 93
const DEV_INSTANT94 int32 = 94
const DEV_INSTANT95 int32 = 95
const DEV_INSTANT96 int32 = 96
const DEV_INSTANT97 int32 = 97
const DEV_INSTANT98 int32 = 98
const DEV_INSTANT99 int32 = 99
/*
*
*/
const FAN_INSTANT1 int32 = 1
const FAN_INSTANT2 int32 = 2
const FAN_INSTANT3 int32 = 3
const FAN_INSTANT4 int32 = 4
const FAN_INSTANT5 int32 = 5
const FAN_INSTANT6 int32 = 6
const FAN_INSTANT7 int32 = 7
const FAN_INSTANT8 int32 = 8
const FAN_INSTANT9 int32 = 9
const FAN_INSTANT10 int32 = 10
const FAN_INSTANT11 int32 = 11
const FAN_INSTANT12 int32 = 12
const FAN_INSTANT13 int32 = 13
const FAN_INSTANT14 int32 = 14
const FAN_INSTANT15 int32 = 15
const FAN_INSTANT16 int32 = 16
const FAN_INSTANT17 int32 = 17
const FAN_INSTANT18 int32 = 18
const FAN_INSTANT19 int32 = 19
const FAN_INSTANT20 int32 = 20
const FAN_INSTANT21 int32 = 21
const FAN_INSTANT22 int32 = 22
const FAN_INSTANT23 int32 = 23
const FAN_INSTANT24 int32 = 24
const FAN_INSTANT25 int32 = 25
const FAN_INSTANT26 int32 = 26
const FAN_INSTANT27 int32 = 27
const FAN_INSTANT28 int32 = 28
const FAN_INSTANT29 int32 = 29
<file_sep>/Package/CONFIG.py
import ops
import ops_git
import ops_golang
import iopc
pkg_path=""
output_dir=""
GOPATH=""
go_pkgs_dep_script="go_dep_packages.sh"
go_pkgs_build_script="go_build_packages.sh"
servlet_dir="build"
def set_global(args):
global pkg_path
global output_dir
global GOPATH
global servlet_dir
arch = ops.getEnv("ARCH_ALT")
pkg_path = args["pkg_path"]
output_dir = args["output_path"]
GOPATH=output_dir#ops.path_join(output_dir, "src")
servlet_dir = ops.path_join(output_dir, "/build")
def MAIN_ENV(args):
set_global(args)
print ops.getEnv("GOROOT")
print ops.getEnv("PATH")
ops.exportEnv(ops.setEnv("GOPATH", GOPATH))
#ops_golang.get(GOPATH, "github.com/gorilla/mux")
return False
def MAIN_EXTRACT(args):
set_global(args)
#ops.mkdir(GOPATH)
CMD = [ops.path_join(pkg_path, go_pkgs_dep_script)]
res = ops.execCmd(CMD, GOPATH, False, None)
#if res[2] != 0:
# print res
# print res[1]
# sys.exit(1)
ops.copyto(ops.path_join(pkg_path, "src"), GOPATH)
ops.copyto(ops.path_join(pkg_path, "Makefile"), GOPATH)
#ops.copyto(ops.path_join(pkg_path, "main.go"), GOPATH)
return True
def MAIN_PATCH(args, patch_group_name):
set_global(args)
for patch in iopc.get_patch_list(pkg_path, patch_group_name):
if iopc.apply_patch(tarball_dir, patch):
continue
else:
sys.exit(1)
return True
def MAIN_CONFIGURE(args):
set_global(args)
return True
def MAIN_BUILD(args):
set_global(args)
'''
CMD = [ops.path_join(pkg_path, go_pkgs_build_script)]
res = ops.execCmd(CMD, GOPATH, False, None)
if res[2] != 0:
print res
print res[1]
sys.exit(1)
'''
iopc.make(GOPATH)
#iopc.make(src_path)
return False
def MAIN_INSTALL(args):
set_global(args)
iopc.installBin(args["pkg_name"], ops.path_join(servlet_dir, "."), "www")
return False
def MAIN_SDKENV(args):
set_global(args)
return False
def MAIN_CLEAN_BUILD(args):
set_global(args)
return False
def MAIN(args):
set_global(args)
<file_sep>/src/hwmon/rest_page.go
package hwmon
import "config"
import "net/http"
import "fmt"
var MAX_ENTITY int32 = 50
var MAX_INSTANT int32 = 100
func PageIndex(w http.ResponseWriter, r* http.Request) {
fmt.Fprintf(w, "<html><title>Index</title><body>")
fmt.Fprintf(w, "<a href='/debug.html'>Debug</a><br/>")
fmt.Fprintf(w, "<a href='/devicefanmap.html'>DeviceFanMap</a><br/>")
fmt.Fprintf(w, "</body></html>")
}
func PageTimer(w http.ResponseWriter, js_func_name string, microseconds int32) {
fmt.Fprintf (w, "var timer_%s = setInterval(%s, %d);\n", js_func_name, js_func_name, microseconds)
}
func PageGenTable(w http.ResponseWriter) {
fmt.Fprintln(w, "function lookup_entity(eid){")
fmt.Fprintf (w, " var e001 = %d; if (eid == e001) return e001 + ':CPU';", config.ENTITY_PROCESSOR)
fmt.Fprintf (w, " var e002 = %d; if (eid == e002) return e002 + ':AMB';", config.ENTITY_EXTERNAL_ENVIROMENT)
fmt.Fprintf (w, " var e003 = %d; if (eid == e003) return e003 + ':AIC';", config.ENTITY_ADD_IN_CARD)
fmt.Fprintf (w, " var e004 = %d; if (eid == e004) return e004 + ':FAN';", config.ENTITY_FAN_COOLING)
fmt.Fprintf (w, " var e005 = %d; if (eid == e005) return e005 + ':DIMM';", config.ENTITY_MEMORY_DEVICE)
fmt.Fprintln(w, " return 'NA';")
fmt.Fprintln(w, "}")
fmt.Fprintln(w, "function genInstantTable(entity, instant){")
fmt.Fprintln(w, " var el_t = document.createElement('p');")
fmt.Fprintln(w, " el_t.setAttribute('id', 'T_' + entity + '_' + instant);")
fmt.Fprintln(w, " if (instant === 0) {")
fmt.Fprintln(w, " el_t.innerHTML=lookup_entity(entity);")
fmt.Fprintln(w, " }")
fmt.Fprintln(w, " var el_f = document.createElement('p');")
fmt.Fprintln(w, " el_f.setAttribute('id', 'F_' + entity + '_' + instant);")
fmt.Fprintln(w, " var tbl = document.createElement('table');")
fmt.Fprintln(w, " tbl.setAttribute('border', '0');")
fmt.Fprintln(w, " var tr = document.createElement('tr');")
fmt.Fprintln(w, " var tr2 = document.createElement('tr');")
fmt.Fprintln(w, " var td = document.createElement('td');")
fmt.Fprintln(w, " var td2 = document.createElement('td');")
fmt.Fprintln(w, " td.appendChild(el_t);")
fmt.Fprintln(w, " td2.appendChild(el_f);")
fmt.Fprintln(w, " tr.appendChild(td);")
fmt.Fprintln(w, " tr2.appendChild(td2);")
fmt.Fprintln(w, " tbl.appendChild(tr);")
fmt.Fprintln(w, " tbl.appendChild(tr2);")
fmt.Fprintln(w, " return tbl;")
fmt.Fprintln(w, "}")
fmt.Fprintln(w, "var tbl = document.createElement('table');")
fmt.Fprintln(w, "tbl.style.width='100%';")
fmt.Fprintln(w, "tbl.setAttribute('border', '1');")
fmt.Fprintf (w, "var MAX_E=%d, MAX_I=%d;\n", MAX_ENTITY, MAX_INSTANT)
fmt.Fprintln(w, "for(var r=0; r<MAX_E; r++) {")
fmt.Fprintln(w, " var tr = document.createElement('tr');")
fmt.Fprintln(w, " for(var c=0; c<MAX_I; c++) {")
fmt.Fprintln(w, " if (r === 0) {")
fmt.Fprintln(w, " var th = document.createElement('th');")
fmt.Fprintln(w, " th.innerHTML = c;")
fmt.Fprintln(w, " tr.appendChild(th);")
fmt.Fprintln(w, " } else {")
fmt.Fprintln(w, " var td = document.createElement('td');")
fmt.Fprintln(w, " td.appendChild(genInstantTable(r, c));")
fmt.Fprintln(w, " tr.appendChild(td);")
fmt.Fprintln(w, " }")
fmt.Fprintln(w, " }")
fmt.Fprintln(w, " tbl.appendChild(tr);")
fmt.Fprintln(w, "}")
fmt.Fprintln(w, "var el = document.getElementById('main_ctx');")
fmt.Fprintln(w, "el.appendChild(tbl);")
}
func PageRequestSensors(w http.ResponseWriter) (string){
func_name := "RequestSensors"
url_abstemp := "/api/v1/hwmon/get/device/abstemp"
url_reltemp := "/api/v1/hwmon/get/device/reltemp"
url_expectduty := "/api/v1/hwmon/get/map/allexpectduty"
url_dutyout := "/api/v1/hwmon/get/map/allfandutyout"
fmt.Fprintln (w, "var g_req_list = [")
fmt.Fprintf (w, "{'en':1, 'url':'%s', 'eid':%d, 'inst':%d, 'callback':%s},",
url_abstemp, config.ENTITY_EXTERNAL_ENVIROMENT, -1, "pushListToTableTemp")
fmt.Fprintf (w, "{'en':1, 'url':'%s', 'eid':%d, 'inst':%d, 'callback':%s},",
url_abstemp, config.ENTITY_ADD_IN_CARD, -1, "pushListToTableTemp")
fmt.Fprintf (w, "{'en':1, 'url':'%s', 'eid':%d, 'inst':%d, 'callback':%s},",
url_abstemp, config.ENTITY_MEMORY_DEVICE, -1, "pushListToTableTemp")
fmt.Fprintf (w, "{'en':1, 'url':'%s', 'eid':%d, 'inst':%d, 'callback':%s},",
url_reltemp, config.ENTITY_PROCESSOR, -1, "pushListToTableTemp")
fmt.Fprintf (w, "{'en':1, 'url':'%s', 'eid':%d, 'inst':%d, 'callback':%s},",
url_expectduty, -1, -1, "pushListToTableExpectDuty")
fmt.Fprintf (w, "{'en':1, 'url':'%s', 'eid':%d, 'inst':%d, 'callback':%s},",
url_dutyout, -1, -1, "pushListToTableDutyOut")
fmt.Fprintln(w, "{'en':0, 'url':'', 'eid':-1, 'inst':-1, 'callback':''}]")
fmt.Fprintln(w, "var g_req_idx = 0;")
fmt.Fprintf (w, "function %s(){", func_name)
fmt.Fprintln(w, " if(g_req_idx >= g_req_list.length) {")
fmt.Fprintln(w, " g_req_idx = 0;")
fmt.Fprintln(w, " }")
fmt.Fprintln(w, " var obj = g_req_list[g_req_idx];")
fmt.Fprintln(w, " if(obj.en)")
fmt.Fprintln(w, " request_to(obj.url, obj.eid, obj.inst, obj.callback);")
fmt.Fprintln(w, " g_req_idx+=1;")
fmt.Fprintln(w, "}")
return func_name
}
func PageRequestDeviceFanMap(w http.ResponseWriter) (string) {
func_name := "RequestDeviceFanMap"
url_devicefanmap := "/api/v1/hwmon/get/device/fanmap"
fmt.Fprintln(w, "var g_idx_E=1;")
fmt.Fprintln(w, "var g_idx_I=1;")
fmt.Fprintf (w, "function %s(){", func_name)
fmt.Fprintln(w, "")
fmt.Fprintf (w, " if(g_idx_I >= %d){", MAX_INSTANT)
fmt.Fprintln(w, " g_idx_E +=1;")
fmt.Fprintln(w, " g_idx_I = 1;")
fmt.Fprintln(w, " }")
fmt.Fprintf (w, " if(g_idx_E >= %d){", MAX_ENTITY)
fmt.Fprintln(w, " g_idx_E = 1;")
fmt.Fprintln(w, " }")
fmt.Fprintf (w, " request_to('%s', g_idx_E, g_idx_I, pushListToTableFan);", url_devicefanmap)
fmt.Fprintln(w, " g_idx_I += 1;")
fmt.Fprintln(w, "}")
fmt.Fprintln(w, "")
return func_name
}
func PageLibsToTable(w http.ResponseWriter) {
fmt.Fprintln(w, "function pushListToTableFan(list) {")
fmt.Fprintln(w, " var text = '';")
fmt.Fprintln(w, " var el_name = '';")
fmt.Fprintln(w, " var found = 0;")
fmt.Fprintln(w, " for(var key in list){")
fmt.Fprintln(w, " var dev = list[key];")
fmt.Fprintln(w, " if(dev.valuetype === 0xF0) {")
fmt.Fprintln(w, " //el.innerHTML = 'NA';")
fmt.Fprintln(w, " } else {")
fmt.Fprintln(w, " el_name = 'F_' + dev.entity + '_' + dev.instant;")
fmt.Fprintln(w, " text +=dev.value +',';")
fmt.Fprintln(w, " found = 1;")
fmt.Fprintln(w, " }")
fmt.Fprintln(w, " }")
fmt.Fprintln(w, " if(found) {")
fmt.Fprintln(w, " var el = document.getElementById(el_name);")
fmt.Fprintln(w, " el.innerHTML = text;")
fmt.Fprintln(w, " }")
fmt.Fprintln(w, "}")
fmt.Fprintln(w, "function pushListToTableDutyOut(list) {")
fmt.Fprintln(w, " for(var key in list){")
fmt.Fprintln(w, " var dev = list[key];")
fmt.Fprintln(w, " if(dev.valuetype === 0xF0) {")
fmt.Fprintln(w, " //el.innerHTML = 'NA';")
fmt.Fprintln(w, " } else {")
fmt.Fprintln(w, " el_name = 'F_' + dev.entity + '_' + dev.instant;")
fmt.Fprintln(w, " var el = document.getElementById(el_name);")
fmt.Fprintln(w, " el.innerHTML = dev.value;")
fmt.Fprintln(w, " }")
fmt.Fprintln(w, " }")
fmt.Fprintln(w, "}")
fmt.Fprintln(w, "function pushListToTableExpectDuty(list) {")
fmt.Fprintln(w, " var debug_ctx = document.getElementById('debug_ctx1');")
fmt.Fprintln(w, " debug_ctx.innerHTML = '';")
fmt.Fprintln(w, " for(var key in list){")
fmt.Fprintln(w, " var dev = list[key];")
fmt.Fprintln(w, " if(dev.valuetype === 0xF0) {")
fmt.Fprintln(w, " //el.innerHTML = 'NA';")
fmt.Fprintln(w, " } else {")
fmt.Fprintln(w, " debug_ctx.innerHTML += '[Entity-Instant-Duty][' + dev.entity + '-' + dev.instant + '-' + dev.value + ']';")
fmt.Fprintln(w, " debug_ctx.innerHTML += '[' + dev.key + ']';")
fmt.Fprintln(w, " debug_ctx.innerHTML += '<br/>';")
fmt.Fprintln(w, " }")
fmt.Fprintln(w, " }")
fmt.Fprintln(w, "}")
fmt.Fprintln(w, "function pushListToTableTemp(list) {")
fmt.Fprintln(w, " for(var key in list){")
fmt.Fprintln(w, " var dev = list[key]")
fmt.Fprintln(w, " if(dev.valuetype === 0xF0) {")
fmt.Fprintln(w, " //el.innerHTML = 'NA';")
fmt.Fprintln(w, " } else {")
fmt.Fprintln(w, " var el_name = 'T_' + dev.entity + '_' + dev.instant;")
fmt.Fprintln(w, " var el = document.getElementById(el_name);")
fmt.Fprintln(w, " el.innerHTML = dev.value;")
fmt.Fprintln(w, " }")
fmt.Fprintln(w, " }")
fmt.Fprintln(w, "}")
}
func PageLibsCommon(w http.ResponseWriter) {
fmt.Fprintln(w, "function request_to(url, eid, idx, callback){")
fmt.Fprintln(w, " var json_data = {entity:eid, instant:idx};")
fmt.Fprintln(w, " var xhr = new XMLHttpRequest();")
fmt.Fprintln(w, " xhr.open('POST', url);")
fmt.Fprintln(w, " xhr.setRequestHeader('content-type', 'application/json');")
fmt.Fprintln(w, " xhr.onreadystatechange = function() {")
fmt.Fprintln(w, " if (xhr.readyState == 4) {")
fmt.Fprintln(w, " if(xhr.getResponseHeader('content-type')==='application/json'){")
fmt.Fprintln(w, " var response = JSON.parse(xhr.responseText);")
fmt.Fprintln(w, " if(callback) callback(response.data);")
fmt.Fprintln(w, " }")
fmt.Fprintln(w, " }")
fmt.Fprintln(w, " }")
fmt.Fprintln(w, " xhr.send(JSON.stringify(json_data));")
fmt.Fprintln(w, "}")
}
func PageDebug(w http.ResponseWriter, r* http.Request) {
fmt.Fprintln(w, "<html><title>Temperature</title><body>")
fmt.Fprintln(w, "<div id='main_ctx' style='width:100%;height:70%;overflow:auto'></div>")
fmt.Fprintln(w, "<div id='debug_ctx1' style='width:47%;height:30%;overflow:auto'></div>")
fmt.Fprintln(w, "<div id='debug_ctx2' style='width:47%;height:30%;overflow:auto'></div>")
fmt.Fprintln(w, "<script>")
PageLibsCommon(w)
PageLibsToTable(w)
PageGenTable(w)
func_name := PageRequestSensors(w)
PageTimer(w, func_name, 100)
fmt.Fprintln(w, "</script>")
fmt.Fprintln(w, "<table><tr><td>Temperature</td></tr><tr><td>Device Map to Fan</td></tr></table>")
fmt.Fprintln(w, "</body></html>")
}
func PageDeviceFanMap(w http.ResponseWriter, r* http.Request) {
fmt.Fprintln(w, "<html><title>DeviceFanMap</title><body>")
fmt.Fprintln(w, "<div id='main_ctx' style='width:100%;height:70%;overflow:auto'></div>")
fmt.Fprintln(w, "<div id='debug_ctx1' style='width:47%;height:30%;overflow:auto'></div>")
fmt.Fprintln(w, "<div id='debug_ctx2' style='width:47%;height:30%;overflow:auto'></div>")
fmt.Fprintln(w, "<script>")
PageLibsCommon(w)
PageLibsToTable(w)
PageGenTable(w)
func_name := PageRequestDeviceFanMap(w)
PageTimer(w, func_name, 100)
fmt.Fprintln(w, "</script>")
fmt.Fprintln(w, "</body></html>")
}
<file_sep>/src/device/cpu.go
package device
import "common"
import "utils"
/*
*
*/
type Cpu_t struct {
Entity int32
}
/*
func (o *Cpu_t)GetListAbsTemp() (map[string]common.DeviceInfo_t) {
obj := utils.PullObjListDeviceAbsTemp(o.Entity)
return obj
}
func (o *Cpu_t)GetAbsTemp(instant int32) (common.DeviceInfo_t) {
obj := utils.PullObjDeviceAbsTemp(o.Entity, instant)
return obj
}
func (o *Cpu_t)SetAbsTemp(instant int32, value float32) (common.DeviceInfo_t) {
obj := utils.PushObjDeviceAbsTemp(o.Entity, instant, value)
return obj
}
*/
func (o *Cpu_t)GetListRelTemp() (map[string]common.DeviceInfo_t) {
obj := utils.PullObjListDeviceRelTemp(o.Entity)
return obj
}
func (o *Cpu_t)GetRelTemp(instant int32) (common.DeviceInfo_t) {
obj := utils.PullObjDeviceRelTemp(o.Entity, instant)
return obj
}
func (o *Cpu_t)SetRelTemp(instant int32, value float32) (common.DeviceInfo_t) {
obj := utils.PushObjDeviceRelTemp(o.Entity, instant, value)
return obj
}
func (o *Cpu_t)GetListAveragePower() (map[string]common.DeviceInfo_t) {
obj := utils.PullObjListDeviceAveragePower(o.Entity)
return obj
}
func (o *Cpu_t)GetAveragePower(instant int32) (common.DeviceInfo_t) {
obj := utils.PullObjDeviceAveragePower(o.Entity, instant)
return obj
}
func (o *Cpu_t)SetAveragePower(instant int32, value float32) (common.DeviceInfo_t) {
obj := utils.PushObjDeviceAveragePower(o.Entity, instant, value)
return obj
}
func (o *Cpu_t)SetExpectFanDuty(key string, instant int32, value float32) (common.DeviceInfo_t) {
obj := utils.PushObjExpectFanDuty(key, o.Entity, instant, value)
return obj
}
/*
func (o *Cpu_t)SetExpectFanDutyByTemperature(instant int32, key string, value float32) (common.DeviceInfo_t) {
obj := utils.PushObjExpectFanDutyByTemperature(o.Entity, instant, key, value)
return obj
}
func (o *Cpu_t)SetExpectFanDutyByPower(instant int32, value float32) (common.DeviceInfo_t) {
obj := utils.PushObjExpectFanDutyByPower(o.Entity, instant, value)
return obj
}
*/
func (o *Cpu_t)GetMaxPower(instant int32) (common.DeviceInfo_t) {
obj := utils.PullObjDeviceMaxPower(o.Entity, instant)
return obj
}
func (o *Cpu_t)GetListMaxPower()(map[string]common.DeviceInfo_t) {
list := utils.PullObjListDeviceMaxPower(o.Entity)
return list
}
<file_sep>/src/hwmon/dao_task.go
package hwmon
import "common"
import "mailbox"
import "strings"
import "config"
import "fmt"
type TaskDao struct {
db_maxtemp map[string]common.DeviceInfo_t
db_abstemp map[string]common.DeviceInfo_t
db_reltemp map[string]common.DeviceInfo_t
db_averagepower map[string]common.DeviceInfo_t
db_maxpower map[string]common.DeviceInfo_t
db_obj map[string]common.DeviceInfo_t
db_expectfanduty map[string]common.DeviceInfo_t
db_device_fan_map map[string]common.DeviceInfo_t
db_fan_output map[string]common.DeviceInfo_t
db_device_cpu_info map[string]common.DeviceInfo_t
}
func get_hdr(data interface{}) (int32, int32, string) {
var entity int32
var instant int32
var key string
switch data.(type) {
case common.DeviceInfo_t:
req := data.(common.DeviceInfo_t)
key = req.Key
entity = req.Entity
instant = req.Instant
}
return entity, instant, key
}
func get_record(msg common.Msg_t, db map[string]common.DeviceInfo_t) (common.Msg_t) {
var res_msg common.Msg_t
PreGetRecord((msg.Data).(common.DeviceInfo_t))
entity, instant, key := get_hdr(msg.Data)
data, ok := db[key]
if !ok {
value := common.ValueResponse_t { Value: config.REQUEST_ERROR_NOT_FOUND }
data = common.DeviceInfo_t { Entity:entity, Instant:instant, Key: key, ValueType:config.TYPE_REQUEST_ERROR, Value:value }
}
data = PostGetRecord(ok, data)
res_msg = mailbox.WrapMsg(msg.Function, msg.ChannelSrc, msg.ChannelDst, data)
return res_msg
}
func set_record(msg common.Msg_t, db map[string]common.DeviceInfo_t) (common.Msg_t){
var res_msg common.Msg_t
ok, dev_info := PreSetRecord((msg.Data).(common.DeviceInfo_t))
entity, instant, key := get_hdr(dev_info)
data := dev_info
if ok {
db[key] = dev_info//(msg.Data).(common.DeviceInfo_t)
} else {
value := common.ValueResponse_t { Value: config.REQUEST_ERROR_NOT_SET }
data = common.DeviceInfo_t { Entity:entity, Instant:instant, Key:key, ValueType:config.TYPE_REQUEST_ERROR, Value:value }
}
PostSetRecord(ok, dev_info)
res_msg = mailbox.WrapMsg(msg.Function, msg.ChannelSrc, msg.ChannelDst, data)
return res_msg
}
func get_records(msg common.Msg_t, db map[string]common.DeviceInfo_t) (common.Msg_t){
list := make(map[string]common.DeviceInfo_t)
_, _, keypart := get_hdr(msg.Data)
for key, dev := range db {
if strings.Contains(key, keypart) {
list[key]=dev
}
}
res_msg := mailbox.WrapMsg(msg.Function, msg.ChannelSrc, msg.ChannelDst, list)
return res_msg
}
func (o* TaskDao)Run() {
o.db_maxtemp = make(map[string]common.DeviceInfo_t)
o.db_abstemp = make(map[string]common.DeviceInfo_t)
o.db_reltemp = make(map[string]common.DeviceInfo_t)
o.db_averagepower = make(map[string]common.DeviceInfo_t)
o.db_maxpower = make(map[string]common.DeviceInfo_t)
o.db_obj = make(map[string]common.DeviceInfo_t)
o.db_expectfanduty = make(map[string]common.DeviceInfo_t)
o.db_device_fan_map = make(map[string]common.DeviceInfo_t)
o.db_fan_output = make(map[string]common.DeviceInfo_t)
o.db_device_cpu_info = make(map[string]common.DeviceInfo_t)
mb_dao := mailbox.CreateMailboxDao()
var res_msg common.Msg_t
isBreakTask := false
for {
msg :=<-mb_dao.Channel
switch msg.Function {
case config.GET_DEVICE_LIST_MAXPOWER:
res_msg = get_records(msg, o.db_maxpower)
case config.GET_DEVICE_MAXPOWER:
res_msg = get_record(msg, o.db_maxpower)
case config.SET_DEVICE_MAXPOWER:
res_msg = set_record(msg, o.db_maxpower)
case config.GET_DEVICE_LIST_AVERAGEPOWER:
res_msg = get_records(msg, o.db_averagepower)
case config.GET_DEVICE_AVERAGEPOWER:
res_msg = get_record(msg, o.db_averagepower)
case config.SET_DEVICE_AVERAGEPOWER:
res_msg = set_record(msg, o.db_averagepower)
case config.GET_DEVICE_MAXTEMP:
res_msg = get_record(msg, o.db_maxtemp)
case config.SET_DEVICE_MAXTEMP:
res_msg = set_record(msg, o.db_maxtemp)
case config.GET_DEVICE_LIST_ABSTEMP:
res_msg = get_records(msg, o.db_abstemp)
case config.GET_DEVICE_ABSTEMP:
res_msg = get_record(msg, o.db_abstemp)
case config.SET_DEVICE_ABSTEMP:
res_msg = set_record(msg, o.db_abstemp)
case config.GET_DEVICE_LIST_RELTEMP:
res_msg = get_records(msg, o.db_reltemp)
case config.GET_DEVICE_RELTEMP:
res_msg = get_record(msg, o.db_reltemp)
case config.SET_DEVICE_RELTEMP:
res_msg = set_record(msg, o.db_reltemp)
case config.GET_EXPECT_FAN_DUTY:
res_msg = get_record(msg, o.db_expectfanduty)
case config.SET_EXPECT_FAN_DUTY:
res_msg = set_record(msg, o.db_expectfanduty)
case config.GET_ALL_EXPECT_FAN_DUTY:
res_msg = get_records(msg, o.db_expectfanduty)
case config.SET_DEVICE_FAN_DUTY_OUTPUT:
res_msg = set_record(msg, o.db_fan_output)
case config.GET_DEVICE_FAN_DUTY_OUTPUT:
res_msg = get_record(msg, o.db_fan_output)
case config.GET_ALL_FAN_DUTY_OUTPUT:
res_msg = get_records(msg, o.db_fan_output)
case config.GET_DEVICE_FAN_MAP:
res_msg = get_records(msg, o.db_device_fan_map)
case config.SET_DEVICE_FAN_MAP:
res_msg = set_record(msg, o.db_device_fan_map)
case config.GET_ALL_DEVICE_FAN_MAP:
res_msg = get_records(msg, o.db_device_fan_map)
case config.GET_DEVICE_CPU_INFO:
res_msg = get_records(msg, o.db_device_cpu_info)
case config.SET_DEVICE_CPU_INFO:
res_msg = set_record(msg, o.db_device_cpu_info)
case config.GET_OBJ_BY_KEY:
res_msg = get_record(msg, o.db_obj)
case config.SET_OBJ_BY_KEY:
res_msg = set_record(msg, o.db_obj)
case config.EXIT_APPLICATION:
isBreakTask = true
value := common.ValueResponse_t { Value : config.REQUEST_OK }
data := common.DeviceInfo_t { Entity:0, Instant:0, ValueType:config.TYPE_REQUEST_OK, Value:value }
res_msg = mailbox.WrapMsg(msg.Function, msg.ChannelSrc, msg.ChannelDst, data)
default :
entity, instant, key := get_hdr(msg.Data)
value := common.ValueResponse_t { Value : config.REQUEST_ERROR_NOT_FOUND }
data := common.DeviceInfo_t { Entity:entity, Instant:instant, Key: key, ValueType:config.TYPE_REQUEST_ERROR, Value:value }
res_msg = mailbox.WrapMsg(msg.Function, msg.ChannelSrc, msg.ChannelDst, data)
}
msg.ChannelDst <- res_msg
if isBreakTask {
break
}
}
fmt.Println("Exit TaskDao")
}
<file_sep>/src/hwmon/rest_api.go
package hwmon
import "common"
import "utils"
import "config"
import "net/http"
import "ops_log"
import "io/ioutil"
func GetDeviceMaxTemp(w http.ResponseWriter, r* http.Request) {
b, err := ioutil.ReadAll(r.Body)
defer r.Body.Close()
if err != nil {
ops_log.Debug(0x1, "Set Error %s", err)
}
data := utils.ConvertBytesToDeviceInfo(b)
obj := utils.PullObjDeviceMaxTemp(data.Entity, data.Instant)
responseWithJsonV1(w, http.StatusOK, obj)
}
func SetDeviceMaxTemp(w http.ResponseWriter, r* http.Request) {
b, err := ioutil.ReadAll(r.Body)
defer r.Body.Close()
if err != nil {
ops_log.Debug(0x1, "Set Error %s", err)
}
data := utils.ConvertBytesToDeviceInfo(b)
val := utils.ToFloat(data.Value)
obj := utils.PushObjDeviceMaxTemp(data.Entity, data.Instant, val)
responseWithJsonV1(w, http.StatusOK, obj)
}
func GetDeviceAbsTemp(w http.ResponseWriter, r* http.Request) {
b, err := ioutil.ReadAll(r.Body)
defer r.Body.Close()
if err != nil {
ops_log.Debug(0x1, "Set Error %s", err)
}
data := utils.ConvertBytesToDeviceInfo(b)
if data.Instant == -1 {
obj := utils.PullObjListDeviceAbsTemp(data.Entity)
responseWithJsonV1(w, http.StatusOK, obj)
} else {
obj := utils.PullObjDeviceAbsTemp(data.Entity, data.Instant)
responseWithJsonV1(w, http.StatusOK, obj)
}
}
func GetDeviceRelTemp(w http.ResponseWriter, r* http.Request) {
b, err := ioutil.ReadAll(r.Body)
defer r.Body.Close()
if err != nil {
ops_log.Debug(0x1, "Set Error %s", err)
}
data := utils.ConvertBytesToDeviceInfo(b)
if data.Instant == -1 {
obj := utils.PullObjListDeviceRelTemp(data.Entity)
responseWithJsonV1(w, http.StatusOK, obj)
} else {
obj := utils.PullObjDeviceRelTemp(data.Entity, data.Instant)
responseWithJsonV1(w, http.StatusOK, obj)
}
}
func SetDeviceAbsTemp(w http.ResponseWriter, r* http.Request) {
b, err := ioutil.ReadAll(r.Body)
defer r.Body.Close()
if err != nil {
ops_log.Debug(0x1, "Set Error %s", err)
}
data := utils.ConvertBytesToDeviceInfo(b)
val := utils.ToFloat(data.Value)
obj := utils.PushObjDeviceAbsTemp(data.Entity, data.Instant, val)
responseWithJsonV1(w, http.StatusOK, obj)
}
func SetDeviceRelTemp(w http.ResponseWriter, r* http.Request) {
b, err := ioutil.ReadAll(r.Body)
defer r.Body.Close()
if err != nil {
ops_log.Debug(0x1, "Set Error %s", err)
}
data := utils.ConvertBytesToDeviceInfo(b)
val := utils.ToFloat(data.Value)
obj := utils.PushObjDeviceRelTemp(data.Entity, data.Instant, val)
responseWithJsonV1(w, http.StatusOK, obj)
}
func GetDeviceAveragePower(w http.ResponseWriter, r* http.Request) {
b, err := ioutil.ReadAll(r.Body)
defer r.Body.Close()
if err != nil {
ops_log.Debug(0x1, "Set Error %s", err)
}
data := utils.ConvertBytesToDeviceInfo(b)
obj := utils.PullObjDeviceAveragePower(data.Entity, data.Instant)
responseWithJsonV1(w, http.StatusOK, obj)
}
func SetDeviceAveragePower(w http.ResponseWriter, r* http.Request) {
b, err := ioutil.ReadAll(r.Body)
defer r.Body.Close()
if err != nil {
ops_log.Debug(0x1, "Set Error %s", err)
}
data := utils.ConvertBytesToDeviceInfo(b)
val := utils.ToFloat(data.Value)
obj := utils.PushObjDeviceAveragePower(data.Entity, data.Instant, val)
responseWithJsonV1(w, http.StatusOK, obj)
}
func GetDeviceMaxPower(w http.ResponseWriter, r* http.Request) {
b, err := ioutil.ReadAll(r.Body)
defer r.Body.Close()
if err != nil {
ops_log.Debug(0x1, "Set Error %s", err)
}
data := utils.ConvertBytesToDeviceInfo(b)
obj := utils.PullObjDeviceMaxPower(data.Entity, data.Instant)
responseWithJsonV1(w, http.StatusOK, obj)
}
func SetDeviceMaxPower(w http.ResponseWriter, r* http.Request) {
b, err := ioutil.ReadAll(r.Body)
defer r.Body.Close()
if err != nil {
ops_log.Debug(0x1, "Set Error %s", err)
}
data := utils.ConvertBytesToDeviceInfo(b)
val := utils.ToFloat(data.Value)
obj := utils.PushObjDeviceMaxPower(data.Entity, data.Instant, val)
responseWithJsonV1(w, http.StatusOK, obj)
}
func GetMapDeviceFan(w http.ResponseWriter, r* http.Request) {
b, err := ioutil.ReadAll(r.Body)
defer r.Body.Close()
if err != nil {
ops_log.Debug(0x1, "Set Error %s", err)
}
data := utils.ConvertBytesToDeviceInfo(b)
obj := utils.PullObjDeviceFanMap(data.Entity, data.Instant)
responseWithJsonV1(w, http.StatusOK, obj)
}
func GetMapAllDeviceFan(w http.ResponseWriter, r* http.Request) {
obj := utils.PullObjListDeviceFanMap()
responseWithJsonV1(w, http.StatusOK, obj)
}
func GetMapAllFanDutyOut(w http.ResponseWriter, r* http.Request) {
obj := utils.PullObjListDeviceFanDutyOutput()
responseWithJsonV1(w, http.StatusOK, obj)
}
func GetMapAllDevicesExpectFanDuty(w http.ResponseWriter, r* http.Request) {
obj := utils.PullObjListDevicesExpectFanDuty()
responseWithJsonV1(w, http.StatusOK, obj)
}
func GetDeviceCpuInfo(w http.ResponseWriter, r* http.Request) {
b, err := ioutil.ReadAll(r.Body)
defer r.Body.Close()
if err != nil {
ops_log.Debug(0x1, "Set Error %s", err)
}
data := utils.ConvertBytesToDeviceInfo(b)
obj := utils.PullObjDeviceCpuInfo(data.Entity, data.Instant)
responseWithJsonV1(w, http.StatusOK, obj)
}
func SetDeviceCpuInfo(w http.ResponseWriter, r* http.Request) {
b, err := ioutil.ReadAll(r.Body)
defer r.Body.Close()
if err != nil {
ops_log.Debug(0x1, "Set Error %s", err)
}
data := utils.ConvertBytesToDeviceInfo(b)
cpu_info := utils.ConvertValueToCpuInfo(data.ValueType, data.Value)
obj := utils.PushObjDeviceCpuInfo(data.Entity, data.Instant, cpu_info)
responseWithJsonV1(w, http.StatusOK, obj)
}
func GetDeviceAicInfo(w http.ResponseWriter, r* http.Request) {
}
func SetDeviceAicInfo(w http.ResponseWriter, r* http.Request) {
}
func ExitMain(w http.ResponseWriter, r* http.Request) {
_, err := ioutil.ReadAll(r.Body)
defer r.Body.Close()
if err != nil {
ops_log.Debug(0x1, "Set Error %s", err)
}
value := common.ValueRequest_t{Value: "Exit Main"}
data := common.DeviceInfo_t { Entity:0, Instant:0, ValueType:config.TYPE_REQUEST, Value:value }
res_msg := utils.TalkToHwmon(config.EXIT_APPLICATION, data)
//obj := ConvertBytesToDeviceInfo(res_msg.Data)
obj := res_msg.Data
responseWithJsonV1(w, http.StatusOK, obj)
}
func EnableOutOfBandInterface(w http.ResponseWriter, r* http.Request) {
_, err := ioutil.ReadAll(r.Body)
defer r.Body.Close()
if err != nil {
ops_log.Debug(0x1, "Set Error %s", err)
}
value := common.ValueRequest_t{Value: "Enable out of band interface"}
data := common.DeviceInfo_t { Entity:0, Instant:0, ValueType:config.TYPE_REQUEST, Value:value }
res_msg := utils.TalkToHwmon(config.ENABLE_OUTOFBAND_INTERFACE, data)
//obj := ConvertBytesToDeviceInfo(res_msg.Data)
obj := res_msg.Data
responseWithJsonV1(w, http.StatusOK, obj)
}
func DisableOutOfBandInterface(w http.ResponseWriter, r* http.Request) {
_, err := ioutil.ReadAll(r.Body)
defer r.Body.Close()
if err != nil {
ops_log.Debug(0x1, "Set Error %s", err)
}
value := common.ValueRequest_t{Value: "Disable out of band interface"}
data := common.DeviceInfo_t { Entity:0, Instant:0, ValueType:config.TYPE_REQUEST, Value:value }
res_msg := utils.TalkToHwmon(config.DISABLE_OUTOFBAND_INTERFACE, data)
//obj := ConvertBytesToDeviceInfo(res_msg.Data)
obj := res_msg.Data
responseWithJsonV1(w, http.StatusOK, obj)
}
var rest_api_list = []rest_api_t {
/*
*
*/
{"/api/v1/hwmon/get/device/abstemp", GetDeviceAbsTemp},
{"/api/v1/hwmon/set/device/abstemp", SetDeviceAbsTemp},
{"/api/v1/hwmon/get/device/maxtemp", GetDeviceMaxTemp},
{"/api/v1/hwmon/set/device/maxtemp", SetDeviceMaxTemp},
{"/api/v1/hwmon/get/device/reltemp", GetDeviceRelTemp},
{"/api/v1/hwmon/set/device/reltemp", SetDeviceRelTemp},
/*
*
*/
{"/api/v1/hwmon/get/device/averagepower", GetDeviceAveragePower},
{"/api/v1/hwmon/set/device/averagepower", SetDeviceAveragePower},
{"/api/v1/hwmon/get/device/maxpower", GetDeviceMaxPower},
{"/api/v1/hwmon/set/device/maxpower", SetDeviceMaxPower},
/*
*
*/
{"/api/v1/hwmon/get/device/cpu/info", GetDeviceCpuInfo},
{"/api/v1/hwmon/set/device/cpu/info", SetDeviceCpuInfo},
{"/api/v1/hwmon/get/device/aic/info", GetDeviceAicInfo},
{"/api/v1/hwmon/set/device/aic/info", SetDeviceAicInfo},
/*
*
*/
{"/api/v1/hwmon/get/device/fanmap", GetMapDeviceFan},
{"/api/v1/hwmon/get/map/alldevicefan", GetMapAllDeviceFan},
{"/api/v1/hwmon/get/map/allfandutyout", GetMapAllFanDutyOut},
{"/api/v1/hwmon/get/map/allexpectduty", GetMapAllDevicesExpectFanDuty},
/*
*
*/
{"/api/v1/hwmon/exit/main", ExitMain},
{"/api/v1/hwmon/enable/out/interface", EnableOutOfBandInterface},
{"/api/v1/hwmon/disable/out/interface", DisableOutOfBandInterface},
/*
*
*/
{"/", PageIndex},
{"/debug.html", PageDebug},
{"/devicefanmap.html", PageDeviceFanMap},
}
<file_sep>/src/utils/dao_util.go
package utils
import "common"
import "config"
import "fmt"
func createKeyByTEI(vtype int32, entity int32, instant int32) (string) {
key := fmt.Sprintf("_VT:%d_E:%d_I:%d_", vtype, entity, instant)
return key
}
func createKeyByEIV(entity int32, instant int32, value interface{}) (string) {
key := fmt.Sprintf("_E:%d_I:%d_V:%d_", entity, instant, ToInt(value))
return key
}
func createKeyByEI(entity int32, instant int32) (string) {
key := fmt.Sprintf("_E:%d_I:%d_", entity, instant)
return key
}
func createKeyByE(entity int32) (string){
key := fmt.Sprintf("_E:%d_", entity)
return key
}
// GET record
func PullObj(key string) (interface{}) {
data := common.DeviceInfo_t { Entity:-1, Instant:-1, ValueType:config.TYPE_OBJECT, Value: ""}
data.Key = key
msg := TalkToDao(config.GET_OBJ_BY_KEY, data)
if IsResponse(msg.Data) {
return nil
} else {
return msg.Data
}
}
// SET record
func PushObj(key string, val interface{}) (bool){
data := common.DeviceInfo_t { Entity:-1, Instant:-1, ValueType:config.TYPE_OBJECT, Value:val }
data.Key = key
msg := TalkToDao(config.SET_OBJ_BY_KEY, data)
rsp, ok := (msg.Data).(common.DeviceInfo_t)
if ok {
if rsp.Value == 0 {
return true
}
}
return false
}
// GET DeviceMaxTemp
func PullObjDeviceMaxTemp(entity int32, instant int32) (common.DeviceInfo_t) {
data := common.DeviceInfo_t { Entity:entity, Instant:instant, ValueType:config.TYPE_TEMPERATURE, Value:0 }
data.Key = createKeyByTEI(data.ValueType, data.Entity, data.Instant)
msg := TalkToDao(config.GET_DEVICE_MAXTEMP, data)
obj := (msg.Data).(common.DeviceInfo_t)
return obj
}
// SET DeviceMaxTemp
func PushObjDeviceMaxTemp(entity int32, instant int32, value float32) (common.DeviceInfo_t){
data := common.DeviceInfo_t { Entity:entity, Instant:instant, ValueType:config.TYPE_TEMPERATURE, Value:value }
data.Key = createKeyByTEI(data.ValueType, data.Entity, data.Instant)
msg := TalkToDao(config.SET_DEVICE_MAXTEMP, data)
obj := (msg.Data).(common.DeviceInfo_t)
return obj
}
// GET DeviceAbsTemp
func PullObjDeviceAbsTemp(entity int32, instant int32) (common.DeviceInfo_t) {
data := common.DeviceInfo_t { Entity:entity, Instant:instant, ValueType:config.TYPE_TEMPERATURE, Value:0 }
data.Key = createKeyByTEI(data.ValueType, data.Entity, data.Instant)
msg := TalkToDao(config.GET_DEVICE_ABSTEMP, data)
obj := (msg.Data).(common.DeviceInfo_t)
return obj
}
// SET DeviceAbsTemp
func PushObjDeviceAbsTemp(entity int32, instant int32, value float32) (common.DeviceInfo_t){
data := common.DeviceInfo_t { Entity:entity, Instant:instant, ValueType:config.TYPE_TEMPERATURE, Value:value }
data.Key = createKeyByTEI(data.ValueType, data.Entity, data.Instant)
msg := TalkToDao(config.SET_DEVICE_ABSTEMP, data)
obj := (msg.Data).(common.DeviceInfo_t)
return obj
}
// Get DeviceAbsTemp list
func PullObjListDeviceAbsTemp(entity int32) (map[string]common.DeviceInfo_t) {
data := common.DeviceInfo_t { Entity:entity, Instant:-1, ValueType:config.TYPE_TEMPERATURE, Value:0 }
data.Key = createKeyByE(data.Entity)
msg := TalkToDao(config.GET_DEVICE_LIST_ABSTEMP, data)
obj := (msg.Data).(map[string]common.DeviceInfo_t)
return obj
}
// GET DeviceRelTemp
func PullObjDeviceRelTemp(entity int32, instant int32) (common.DeviceInfo_t) {
data := common.DeviceInfo_t { Entity:entity, Instant:instant, ValueType:config.TYPE_TEMPERATURE, Value:0 }
data.Key = createKeyByTEI(data.ValueType, data.Entity, data.Instant)
msg := TalkToDao(config.GET_DEVICE_RELTEMP, data)
obj := (msg.Data).(common.DeviceInfo_t)
return obj
}
// SET DeviceRelTemp
func PushObjDeviceRelTemp(entity int32, instant int32, value float32) (common.DeviceInfo_t){
data := common.DeviceInfo_t { Entity:entity, Instant:instant, ValueType:config.TYPE_TEMPERATURE, Value:value }
data.Key = createKeyByTEI(data.ValueType, data.Entity, data.Instant)
msg := TalkToDao(config.SET_DEVICE_RELTEMP, data)
obj := (msg.Data).(common.DeviceInfo_t)
return obj
}
// GET record list
func PullObjListDeviceRelTemp(entity int32) (map[string]common.DeviceInfo_t) {
data := common.DeviceInfo_t { Entity:entity, Instant:-1, ValueType:config.TYPE_TEMPERATURE, Value:0 }
data.Key = createKeyByE(data.Entity)
msg := TalkToDao(config.GET_DEVICE_LIST_RELTEMP, data)
obj := (msg.Data).(map[string]common.DeviceInfo_t)
return obj
}
// GET DeviceAveragePower
func PullObjDeviceAveragePower(entity int32, instant int32) (common.DeviceInfo_t) {
data := common.DeviceInfo_t { Entity:entity, Instant:instant, ValueType:config.TYPE_AVERAGEPOWER, Value:0 }
data.Key = createKeyByTEI(data.ValueType, data.Entity, data.Instant)
msg := TalkToDao(config.GET_DEVICE_AVERAGEPOWER, data)
obj := (msg.Data).(common.DeviceInfo_t)
return obj
}
// SET DeviceAveragePower
func PushObjDeviceAveragePower(entity int32, instant int32, value float32) (common.DeviceInfo_t){
data := common.DeviceInfo_t { Entity:entity, Instant:instant, ValueType:config.TYPE_AVERAGEPOWER, Value:value }
data.Key = createKeyByTEI(data.ValueType, data.Entity, data.Instant)
msg := TalkToDao(config.SET_DEVICE_AVERAGEPOWER, data)
obj := (msg.Data).(common.DeviceInfo_t)
return obj
}
// GET DeviceAveragePower list
func PullObjListDeviceAveragePower(entity int32) (map[string]common.DeviceInfo_t) {
data := common.DeviceInfo_t { Entity:entity, Instant:-1, ValueType:config.TYPE_AVERAGEPOWER, Value:0 }
data.Key = createKeyByE(data.Entity)
msg := TalkToDao(config.GET_DEVICE_LIST_AVERAGEPOWER, data)
obj := (msg.Data).(map[string]common.DeviceInfo_t)
return obj
}
// SET ExpectFanDuty
func PushObjExpectFanDuty(key string, entity int32, instant int32, value float32) (common.DeviceInfo_t) {
data := common.DeviceInfo_t { Entity:entity, Instant:instant, ValueType:config.TYPE_FANDUTY, Value:value }
data.Key = key
msg := TalkToDao(config.SET_EXPECT_FAN_DUTY, data)
obj := (msg.Data).(common.DeviceInfo_t)
return obj
}
// GET record list
func PullObjListDeviceFanMap()(map[string]common.DeviceInfo_t) {
data := common.DeviceInfo_t { Entity:-1, Instant:-1, ValueType:config.TYPE_DEVICEFANMAP, Value:0 }
data.Key = ""
msg := TalkToDao(config.GET_ALL_DEVICE_FAN_MAP, data)
obj := (msg.Data).(map[string]common.DeviceInfo_t)
return obj
}
// GET record list
func PullObjDeviceFanMap(entity int32, instant int32) (map[string]common.DeviceInfo_t) {
data := common.DeviceInfo_t { Entity:entity, Instant:instant, ValueType:config.TYPE_DEVICEFANMAP, Value:0 }
data.Key = createKeyByEI(data.Entity, data.Instant)
msg := TalkToDao(config.GET_DEVICE_FAN_MAP, data)
obj := (msg.Data).(map[string]common.DeviceInfo_t)
return obj
}
// SET DeviceFanMap
func PushObjDeviceFanMap(entity int32, instant int32, fan_index int32) (common.DeviceInfo_t) {
data := common.DeviceInfo_t { Entity:entity, Instant:instant, ValueType:config.TYPE_DEVICEFANMAP, Value:fan_index }
data.Key = createKeyByEIV(data.Entity, data.Instant, data.Value)
msg := TalkToDao(config.SET_DEVICE_FAN_MAP, data)
obj := (msg.Data).(common.DeviceInfo_t)
return obj
}
// GET record
func PullObjDeviceFanDutyOutput(entity int32, instant int32) (common.DeviceInfo_t) {
data := common.DeviceInfo_t { Entity:entity, Instant:instant, ValueType:config.TYPE_FANDUTY, Value:0 }
data.Key = createKeyByEI(data.Entity, data.Instant)
msg := TalkToDao(config.GET_DEVICE_FAN_DUTY_OUTPUT, data)
obj := (msg.Data).(common.DeviceInfo_t)
return obj
}
// SET record
func PushObjDeviceFanDutyOutput(entity int32, instant int32, duty float32) (common.DeviceInfo_t) {
data := common.DeviceInfo_t { Entity:entity, Instant:instant, ValueType:config.TYPE_FANDUTY, Value:duty }
data.Key = createKeyByEI(data.Entity, data.Instant)
msg := TalkToDao(config.SET_DEVICE_FAN_DUTY_OUTPUT, data)
obj := (msg.Data).(common.DeviceInfo_t)
return obj
}
// SET record
func InitObjDeviceFanDutyOutput(entity int32, instant int32, duty float32) (common.DeviceInfo_t) {
data := common.DeviceInfo_t { Entity:entity, Instant:instant, ValueType:config.TYPE_INITFANDUTY, Value:duty }
data.Key = createKeyByEI(data.Entity, data.Instant)
msg := TalkToDao(config.SET_DEVICE_FAN_DUTY_OUTPUT, data)
obj := (msg.Data).(common.DeviceInfo_t)
return obj
}
// GET record list
func PullObjListDeviceFanDutyOutput() (map[string]common.DeviceInfo_t) {
data := common.DeviceInfo_t { Entity:-1, Instant:-1, ValueType:config.TYPE_FANDUTY, Value:0 }
data.Key = ""
msg := TalkToDao(config.GET_ALL_FAN_DUTY_OUTPUT, data)
obj := (msg.Data).(map[string]common.DeviceInfo_t)
return obj
}
/*
func PushObjExpectFanDutyByTemperature(entity int, instant int, key string, value float32) (common.DeviceInfo_t) {
data := common.DeviceInfo_t { Entity:entity, Instant:instant, Key:key, ValueType:config.TYPE_FANDUTY_TEMPERATURE, Value:value }
msg := TalkToDao(config.SET_EXPECT_FAN_DUTY, data)
obj := (msg.Data).(common.DeviceInfo_t)
return obj
}
func PushObjExpectFanDutyByPower(entity int, instant int, value float32) (common.DeviceInfo_t) {
data := common.DeviceInfo_t { Entity:entity, Instant:instant, ValueType:config.TYPE_FANDUTY_POWER, Value:value }
msg := TalkToDao(config.SET_EXPECT_FAN_DUTY, data)
obj := (msg.Data).(common.DeviceInfo_t)
return obj
}
*/
// GET record
func PullObjDeviceMaxPower(entity int32, instant int32) (common.DeviceInfo_t) {
data := common.DeviceInfo_t { Entity:entity, Instant:instant, ValueType:config.TYPE_MAXPOWER, Value:0 }
data.Key = createKeyByTEI(data.ValueType, data.Entity, data.Instant)
msg := TalkToDao(config.GET_DEVICE_MAXPOWER, data)
obj := (msg.Data).(common.DeviceInfo_t)
return obj
}
// GET record list
func PullObjListDeviceMaxPower(entity int32) (map[string]common.DeviceInfo_t) {
data := common.DeviceInfo_t { Entity:entity, Instant:-1, ValueType:config.TYPE_MAXPOWER, Value:0 }
data.Key = createKeyByE(data.Entity)
msg := TalkToDao(config.GET_DEVICE_LIST_MAXPOWER, data)
obj := (msg.Data).(map[string]common.DeviceInfo_t)
return obj
}
// SET record
func PushObjDeviceMaxPower(entity int32, instant int32, value float32) (common.DeviceInfo_t) {
data := common.DeviceInfo_t { Entity:entity, Instant:instant, ValueType:config.TYPE_MAXPOWER, Value:value }
data.Key = createKeyByTEI(data.ValueType, data.Entity, data.Instant)
msg := TalkToDao(config.SET_DEVICE_MAXPOWER, data)
obj := (msg.Data).(common.DeviceInfo_t)
return obj
}
// GET record list
func PullObjListDevicesExpectFanDuty() (map[string]common.DeviceInfo_t) {
data := common.DeviceInfo_t { Entity: -1, Instant: -1, ValueType: config.TYPE_FANDUTY, Value: 0 }
data.Key = ""
msg := TalkToDao(config.GET_ALL_EXPECT_FAN_DUTY, data)
obj_map := (msg.Data).(map[string]common.DeviceInfo_t)
return obj_map
}
func PullObjDeviceExpectFanDuty(entity int32, instant int32) (common.DeviceInfo_t) {
data := common.DeviceInfo_t { Entity: entity, Instant: instant, ValueType: config.TYPE_FANDUTY, Value: 0 }
data.Key = createKeyByTEI(data.ValueType, data.Entity, data.Instant)
msg := TalkToDao(config.GET_EXPECT_FAN_DUTY, data)
obj := (msg.Data).(common.DeviceInfo_t)
return obj
}
func PullObjDeviceCpuInfo(entity int32, instant int32) (common.DeviceInfo_t) {
cpu_info := common.ValueCpuInfo_t { MaxTdp:0, CoreNum:0, Identity: "" }
data := common.DeviceInfo_t { Entity: entity, Instant: instant, ValueType: config.TYPE_CPUINFO, Value: cpu_info}
data.Key = createKeyByTEI(data.ValueType, data.Entity, data.Instant)
msg := TalkToDao(config.GET_DEVICE_CPU_INFO, data)
obj := (msg.Data).(common.DeviceInfo_t)
return obj
}
func PushObjDeviceCpuInfo(entity int32, instant int32, cpu_info common.ValueCpuInfo_t) (common.DeviceInfo_t) {
data := common.DeviceInfo_t { Entity: entity, Instant: instant, ValueType: config.TYPE_CPUINFO, Value: cpu_info}
data.Key = createKeyByTEI(data.ValueType, data.Entity, data.Instant)
msg := TalkToDao(config.SET_DEVICE_CPU_INFO, data)
obj := (msg.Data).(common.DeviceInfo_t)
return obj
}
<file_sep>/src/device/dimm.go
package device
import "common"
import "utils"
/*
*
*/
type Dimm_t struct {
Entity int32
}
func (o *Dimm_t)GetListAbsTemp() (map[string]common.DeviceInfo_t) {
obj := utils.PullObjListDeviceAbsTemp(o.Entity)
return obj
}
func (o *Dimm_t)GetAbsTemp(instant int32) (common.DeviceInfo_t) {
obj := utils.PullObjDeviceAbsTemp(o.Entity, instant)
return obj
}
func (o *Dimm_t)SetAbsTemp(instant int32, value float32) (common.DeviceInfo_t) {
obj := utils.PushObjDeviceAbsTemp(o.Entity, instant, value)
return obj
}
func (o *Dimm_t)GetListAveragePower() (map[string]common.DeviceInfo_t) {
obj := utils.PullObjListDeviceAveragePower(o.Entity)
return obj
}
func (o *Dimm_t)GetAveragePower(instant int32) (common.DeviceInfo_t) {
obj := utils.PullObjDeviceAveragePower(o.Entity, instant)
return obj
}
func (o *Dimm_t)SetAveragePower(instant int32, value float32) (common.DeviceInfo_t) {
obj := utils.PushObjDeviceAveragePower(o.Entity, instant, value)
return obj
}
func (o *Dimm_t)SetExpectFanDuty(key string, instant int32, value float32) (common.DeviceInfo_t) {
obj := utils.PushObjExpectFanDuty(key, o.Entity, instant, value)
return obj
}
/*
func (o *Dimm_t)SetExpectFanDutyByTemperature(instant int32, value float32) (common.DeviceInfo_t) {
obj := utils.PushObjExpectFanDutyByTemperature(o.Entity, instant, value)
return obj
}
func (o *Dimm_t)SetExpectFanDutyByPower(instant int32, value float32) (common.DeviceInfo_t) {
obj := utils.PushObjExpectFanDutyByPower(o.Entity, instant, value)
return obj
}
*/
func (o *Dimm_t)GetMaxPower(instant int32) (common.DeviceInfo_t) {
obj := utils.PullObjDeviceMaxPower(o.Entity, instant)
return obj
}
func (o *Dimm_t)GetListMaxPower()(map[string]common.DeviceInfo_t) {
list := utils.PullObjListDeviceMaxPower(o.Entity)
return list
}
<file_sep>/request_scripts/hwmon_aic_temperature_get.py
#!/usr/bin/python2.7
import sys
import utils
def request_list(hostname, out_format):
entity = utils.ENTITY_ADD_IN_CARD
instant = 1
json = '{"entity":%d, "instant":%d}' % (entity, instant)
url='http://%s/api/v1/hwmon/get/device/maxtemp' % hostname
utils.response_output(out_format, utils.http_request(url, json))
json = '{"entity":%d, "instant":%d}' % (entity, instant)
url='http://%s/api/v1/hwmon/get/device/abstemp' % hostname
utils.response_output(out_format, utils.http_request(url, json))
if __name__ == '__main__':
if len(sys.argv) < 2:
utils.help_usage()
hostname=sys.argv[1]
request_list(hostname, 'json')
<file_sep>/src/algorithm/lookuptable.go
package algorithm
//import "fmt"
//import "math"
type LookupTable_t struct {
DBKey string
}
func (o* LookupTable_t)Compute(currentTemperature float32) float32 {
val := currentTemperature
if val < 25 {
return 20
} else if (val >= 25) && (val < 35) {
return 40
} else {
return 60
}
}
<file_sep>/request_scripts/utils.py
import requests
import pprint
import json
ENTITY_UNSPECIFIED = 0
ENTITY_OTHER = 1
ENTITY_UNKNOWN = 2
ENTITY_PROCESSOR = 3
ENTITY_DISK = 4
ENTITY_PERIPHERAL = 5
ENTITY_SYSTEM_MANAGEMENT_MODULE = 6
ENTITY_SYSTEM_BOARD = 7
ENTITY_MEMORY_MODULE = 8
ENTITY_PROCESSOR_MODULE = 9
ENTITY_POWER_SUPPLY = 10
ENTITY_ADD_IN_CARD = 11
ENTITY_FRONT_PANEL_BOARD = 12
ENTITY_BACK_PANEL_BOARD = 13
ENTITY_POWER_SYS_BOARD = 14
ENTITY_DRIVE_BACKPLANE = 15
ENTITY_SYS_INTERNAL_EXP_BOARD = 16
ENTITY_OTHER_SYSTEM_BOARD = 17
ENTITY_PROCESSOR_BOARD = 18
ENTITY_POWER_UNIT = 19
ENTITY_POWER_MODULE = 20
ENTITY_POWER_MANAGEMENT_BOARD = 21
ENTITY_CHASSIS_BACK_PANEL_BOARD = 22
ENTITY_SYSTEM_CHASSIS = 23
ENTITY_SUB_CHASSIS = 24
ENTITY_OTHER_CHASSIS_BOARD = 25
ENTITY_DISK_DRIVE_BAY = 26
ENTITY_PERIPHERAL_BAY = 27
ENTITY_DEVICE_BAY = 28
ENTITY_FAN_COOLING = 29
ENTITY_COOLING_UNIT = 30
ENTITY_CABLE_INTERCONNECT = 31
ENTITY_MEMORY_DEVICE = 32
ENTITY_SYSTEM_MANAGEMENT_SW = 33
ENTITY_BIOS = 34
ENTITY_OPERATING_SYSTEM = 35
ENTITY_SYSTEM_BUS = 36
ENTITY_GROUP = 37
ENTITY_REMOTE_MANAGEMENT_DEVICE = 38
ENTITY_EXTERNAL_ENVIROMENT = 39
ENTITY_BATTERY = 40
ENTITY_PROCESSING_BLADE = 41
ENTITY_CONNECTIVITY_SWITCH = 42
ENTITY_PROCESSOR_MEMORY_MODULE = 43
ENTITY_IO_MODULE = 44
ENTITY_PROCESSOR_IO_MODULE = 45
ENTITY_MANAGEMENT_CONTROLLER_FW = 46
TYPE_OBJECT = 0x1
TYPE_TEMPERATURE = 0x2
TYPE_AVERAGEPOWER = 0x3
TYPE_MAXPOWER = 0x4
TYPE_INITFANDUTY = 0x5
TYPE_FANDUTY = 0x6
TYPE_DEVICEFANMAP = 0x7
TYPE_RSP_OK = 0x0
TYPE_RSP_ERROR = 0xF0
TYPE_CMD = 0x80
def http_request(url, payload):
hds = {'content-type':'application/json; charset=utf-8', 'user-agent':'iopc-app'}
rsp=requests.post(url, headers=hds, data=payload)
return rsp
def response_output(out_format, rsp):
if rsp.status_code == 200 :
pprint.pprint(rsp.json())
def help_usage():
print "hwmon.py <hostname>"
sys.exit(1)
<file_sep>/src/utils/util.go
package utils
import "encoding/json"
import "common"
import "mailbox"
func IsResponse(data interface{})(bool) {
_, ok := data.(common.DeviceInfo_t)
return ok
}
func ToResponse(data interface{})(common.DeviceInfo_t) {
res := data.(common.DeviceInfo_t)
return res
}
func GetHeaders(data interface{})(int32, int32, string) {
var entity int32
var instant int32
var key string
switch data.(type) {
case common.DeviceInfo_t:
req := data.(common.DeviceInfo_t)
key = req.Key
entity = req.Entity
instant = req.Instant
}
return entity, instant, key
}
func ToFloat(val interface{}) (float32) {
var result float32
result = -1
switch val.(type) {
case float64:
result = float32(val.(float64))
case float32:
result = val.(float32)
}
return result
}
func ToInt(val interface{}) (int32) {
var result int32
result = -1
switch val.(type) {
case int64:
result = int32(val.(int64))
case int32:
result = val.(int32)
}
return result
}
func ConvertBytesToDeviceInfo(bytes []byte) (common.DeviceInfo_t) {
var data common.DeviceInfo_t
json.Unmarshal(bytes, &data)
return data
}
func ConvertValueToCpuInfo(value_type int32, val interface{}) (common.ValueCpuInfo_t) {
var data common.ValueCpuInfo_t
bytes, _ := json.Marshal(val)
json.Unmarshal(bytes, &data)
return data
}
func TalkToDao(fn string, obj interface{}) (common.Msg_t) {
mb_src := mailbox.CreateMailboxTemporary()
mb_dst := mailbox.CreateMailboxDao()
req_msg := common.Msg_t { Function:fn, ChannelSrc:mb_src.Channel, ChannelDst:mb_dst.Channel, Data: obj }
mb_msghndlr := mailbox.CreateMailboxMsgHndlr()
mb_msghndlr.Channel <-req_msg
res_obj := <-mb_src.Channel
return res_obj
}
func TalkToHwmon(fn string, obj interface{}) (common.Msg_t) {
mb_src := mailbox.CreateMailboxTemporary()
mb_dst := mailbox.CreateMailboxHwmon()
req_msg := common.Msg_t { Function:fn, ChannelSrc:mb_src.Channel, ChannelDst:mb_dst.Channel, Data: obj }
mb_msghndlr := mailbox.CreateMailboxMsgHndlr()
mb_msghndlr.Channel <-req_msg
res_obj := <-mb_src.Channel
return res_obj
}
func TalkToRest(fn string, obj interface{}) (common.Msg_t) {
mb_src := mailbox.CreateMailboxTemporary()
mb_dst := mailbox.CreateMailboxRest()
req_msg := common.Msg_t { Function:fn, ChannelSrc:mb_src.Channel, ChannelDst:mb_dst.Channel, Data: obj }
mb_msghndlr := mailbox.CreateMailboxMsgHndlr()
mb_msghndlr.Channel <-req_msg
res_obj := <-mb_src.Channel
return res_obj
}
func TalkToMsghndlr(fn string, obj interface{}) (common.Msg_t) {
mb_src := mailbox.CreateMailboxTemporary()
req_msg := common.Msg_t { Function:fn, ChannelSrc:mb_src.Channel, ChannelDst:nil, Data: obj }
mb_msghndlr := mailbox.CreateMailboxMsgHndlr()
mb_msghndlr.Channel <-req_msg
res_obj := <-mb_src.Channel
return res_obj
}
<file_sep>/Makefile
MAJOR = 1
MINOR = 0
TARGET_NAME = go_web
DESCRIPTION = "web server by golang"
include $(GOROOT)/../libgo_exe.mk
<file_sep>/src/mailbox/mailbox.go
package mailbox
import "sync"
import "common"
/*
*
*/
type MailboxRest struct{
Channel chan common.Msg_t
}
var mb_rest *MailboxRest
var sync_rest sync.Once
func CreateMailboxRest() (*MailboxRest) {
sync_rest.Do(func() {
mb_rest = &MailboxRest{ Channel: make(chan common.Msg_t) }
})
return mb_rest
}
/*
*
*/
type MailboxDao struct{
Channel chan common.Msg_t
}
var mb_dao *MailboxDao
var sync_dao sync.Once
func CreateMailboxDao() (*MailboxDao) {
sync_dao.Do(func() {
mb_dao = &MailboxDao{ Channel: make(chan common.Msg_t) }
})
return mb_dao
}
/*
*
*/
type MailboxMsgHndlr struct{
Channel chan common.Msg_t
}
var mb_msghndlr *MailboxMsgHndlr
var sync_msghndlr sync.Once
func CreateMailboxMsgHndlr() (*MailboxMsgHndlr) {
sync_msghndlr.Do(func() {
mb_msghndlr = &MailboxMsgHndlr{ Channel: make(chan common.Msg_t) }
})
return mb_msghndlr
}
/*
*
*/
type MailboxHwmon struct{
Channel chan common.Msg_t
}
var mb_hwmon *MailboxHwmon
var sync_hwmon sync.Once
func CreateMailboxHwmon() (*MailboxHwmon) {
sync_hwmon.Do(func() {
mb_hwmon = &MailboxHwmon{ Channel: make(chan common.Msg_t) }
})
return mb_hwmon
}
/*
*
*/
type MailboxTemp struct {
Channel chan common.Msg_t
}
func CreateMailboxTemporary() (*MailboxTemp) {
mb_temp := new(MailboxTemp)
mb_temp.Channel = make(chan common.Msg_t)
return mb_temp
}
/*
*
*/
func WrapMsg(fn string, chsrc chan common.Msg_t, chdst chan common.Msg_t, data interface{}) (common.Msg_t) {
msg := common.Msg_t { Function:fn, ChannelSrc:chsrc, ChannelDst:chdst, Data:data }
return msg
}
<file_sep>/src/device/fan.go
package device
import "common"
import "utils"
/*
*
*/
type Fan_t struct {
Entity int32
}
func (o *Fan_t)GetDutyOutput(instant int32) (common.DeviceInfo_t) {
obj := utils.PullObjDeviceFanDutyOutput(o.Entity, instant)
return obj
}
func (o *Fan_t)SetDutyOutput(instant int32, duty float32) (common.DeviceInfo_t) {
obj := utils.PushObjDeviceFanDutyOutput(o.Entity, instant, duty)
return obj
}
func (o *Fan_t)InitDutyOutput(instant int32, duty float32) (common.DeviceInfo_t) {
obj := utils.InitObjDeviceFanDutyOutput(o.Entity, instant, duty)
return obj
}
func (o *Fan_t)GetAllDutyOutput() (map[string]common.DeviceInfo_t) {
obj_list := utils.PullObjListDeviceFanDutyOutput()
return obj_list
}
func (o *Fan_t)SetDeviceMap(dev_entity int32, dev_instant int32, fan_instant int32) (common.DeviceInfo_t) {
obj := utils.PushObjDeviceFanMap(dev_entity, dev_instant, fan_instant)
return obj
}
func (o *Fan_t)GetDeviceMap(dev_entity int32, dev_instant int32) (map[string]common.DeviceInfo_t) {
obj := utils.PullObjDeviceFanMap(dev_entity, dev_instant)
return obj
}
func (o *Fan_t)GetAllDeviceMap() (map[string]common.DeviceInfo_t) {
obj := utils.PullObjListDeviceFanMap()
return obj
}
func (o *Fan_t)GetDeviceExpectFanDuty(dev_entity int32, dev_instant int32) (common.DeviceInfo_t) {
obj := utils.PullObjDeviceExpectFanDuty(dev_entity, dev_instant)
return obj
}
func (o *Fan_t)GetAllDevicesExpectFanDuty() (map[string]common.DeviceInfo_t) {
obj_list := utils.PullObjListDevicesExpectFanDuty()
return obj_list
}
<file_sep>/src/hwmon/hwmon_hooks.go
package hwmon
import "common"
/*
* Pre Hook -> DB GET -> Post Hook
*/
func PreGetRecord(dev common.DeviceInfo_t) {
}
func PostGetRecord(isGet bool, devinfo common.DeviceInfo_t) (common.DeviceInfo_t) {
return devinfo
}
/*
* Pre Hook -true-> DB SET -> Post Hook
* | ^
* false --> --> |
*/
func PreSetRecord(devinfo common.DeviceInfo_t) (bool, common.DeviceInfo_t) {
return true, devinfo
}
func PostSetRecord(isSet bool, devinfo common.DeviceInfo_t) {
}
<file_sep>/go_dep_packages.sh
#!/bin/bash
echo "PATH="$PATH
echo "GOARCH="$GOARCH
echo "GOROOT="$GOROOT
echo "GOOS="$GOOS
echo "GOPATH="$GOPATH
$GOROOT/bin/go get github.com/gorilla/mux
<file_sep>/src/main/main.go
package main
//import "os"
import "config"
import "common"
import "utils"
import "hwmon"
import "fmt"
import "mailbox"
/*
* Tasks:
* - rest Interface
* - DAO
* - Fan control Algorisim
* [www rest interface] -> [dispatcher] ->
* request DataStore
*/
func main() {
/*
if len(os.Args) <= 1 {
fmt.Println("program <www_dir>")
os.Exit(-1)
}
www_path := os.Args[1]
*/
fmt.Println("Creating & Running TaskRest")
task_rest := new(hwmon.TaskRest)
// task_rest.SetFolder(www_path)
go task_rest.Run()
fmt.Println("Creating & Running TaskDao")
task_dao := new(hwmon.TaskDao)
go task_dao.Run()
fmt.Println("Creating & Running TaskMsgHndlr")
task_msghndlr := new(hwmon.TaskMsgHndlr)
go task_msghndlr.Run()
fmt.Println("Modules starting...")
tasks := hwmon.GetModules()
for index := range tasks {
go tasks[index].RunTask()
}
mb_hwmon := mailbox.CreateMailboxHwmon()
isBreakTask := false
var response common.DeviceInfo_t
for {
msg := <-mb_hwmon.Channel
msg_func := msg.Function
switch msg_func {
case config.EXIT_APPLICATION:
value := common.ValueResponse_t{Value: config.REQUEST_OK}
response = common.DeviceInfo_t{Entity: 0, Instant: 0, ValueType: config.TYPE_REQUEST_OK, Value: value}
case config.DISABLE_OUTOFBAND_INTERFACE:
value := common.ValueResponse_t{Value: config.REQUEST_OK}
response = common.DeviceInfo_t{Entity: 0, Instant: 0, ValueType: config.TYPE_REQUEST_OK, Value: value}
case config.ENABLE_OUTOFBAND_INTERFACE:
value := common.ValueResponse_t{Value: config.REQUEST_OK}
response = common.DeviceInfo_t{Entity: 0, Instant: 0, ValueType: config.TYPE_REQUEST_OK, Value: value}
default:
value := common.ValueResponse_t{Value: config.REQUEST_ERROR_NOT_FOUND}
response = common.DeviceInfo_t{Entity: 0, Instant: 0, ValueType: config.TYPE_REQUEST_ERROR, Value: value}
}
var res_msg common.Msg_t
//res_bytes := hwmon.ConvertDeviceInfoToBytes(data)
res_msg = mailbox.WrapMsg(msg.Function, msg.ChannelSrc, msg.ChannelDst, response)
msg.ChannelDst <- res_msg
var request common.DeviceInfo_t
switch msg_func {
case config.EXIT_APPLICATION:
isBreakTask = true
value := common.ValueRequest_t{Value: "Exit application"}
request = common.DeviceInfo_t{Entity: 0, Instant: 0, ValueType: config.TYPE_REQUEST, Value: value}
res_msg = utils.TalkToRest(config.EXIT_APPLICATION, request)
//fmt.Println(res_msg)
for {
isFuncExit := true
for index := range tasks {
tasks[index].FunctionExit = true
if tasks[index].FunctionStatus != hwmon.FUNC_STAT_EXIT {
isFuncExit = false
}
}
if isFuncExit {
break
}
}
res_msg = utils.TalkToDao(config.EXIT_APPLICATION, request)
//fmt.Println(res_msg)
res_msg = utils.TalkToMsghndlr(config.EXIT_APPLICATION, request)
//fmt.Println(res_msg)
case config.DISABLE_OUTOFBAND_INTERFACE:
value := common.ValueRequest_t{Value: "Rest:Disable out of band interface"}
request = common.DeviceInfo_t{Entity: 0, Instant: 0, ValueType: config.TYPE_REQUEST, Value: value}
res_msg = utils.TalkToRest(config.DISABLE_OUTOFBAND_INTERFACE, request)
//fmt.Println(res_msg)
case config.ENABLE_OUTOFBAND_INTERFACE:
value := common.ValueRequest_t{Value: "Rest:Enable out of band interface"}
request = common.DeviceInfo_t{Entity: 0, Instant: 0, ValueType: config.TYPE_REQUEST, Value: value}
res_msg = utils.TalkToRest(config.ENABLE_OUTOFBAND_INTERFACE, request)
//fmt.Println(res_msg)
default:
}
//mb_hwmon.Channel <-msg
if isBreakTask {
break
}
}
fmt.Println("Modules end...")
}
<file_sep>/src/config/command.go
package config
/*
*
*/
const GET_DEVICE_LIST_MAXPOWER string = "g_dev_list_maxpower"
const GET_DEVICE_MAXPOWER string = "g_dev_maxpower"
const SET_DEVICE_MAXPOWER string = "s_dev_maxpower"
const GET_DEVICE_LIST_AVERAGEPOWER string = "g_dev_list_averagepower"
const GET_DEVICE_AVERAGEPOWER string = "g_dev_averagepower"
const SET_DEVICE_AVERAGEPOWER string = "s_dev_averagepower"
const GET_DEVICE_MAXTEMP string = "g_dev_maxtemp"
const SET_DEVICE_MAXTEMP string = "s_dev_maxtemp"
const GET_DEVICE_LIST_ABSTEMP string = "g_dev_list_abstemp"
const GET_DEVICE_ABSTEMP string = "g_dev_abstemp"
const SET_DEVICE_ABSTEMP string = "s_dev_abstemp"
const GET_DEVICE_LIST_RELTEMP string = "g_dev_list_reltemp"
const GET_DEVICE_RELTEMP string = "g_dev_reltemp"
const SET_DEVICE_RELTEMP string = "s_dev_reltemp"
const GET_EXPECT_FAN_DUTY string = "g_expect_fan_duty"
const SET_EXPECT_FAN_DUTY string = "s_expect_fan_duty"
const GET_ALL_EXPECT_FAN_DUTY string = "g_all_expect_fan_duty"
const GET_ALL_DEVICE_FAN_MAP string = "g_a_d_fan_map"
const GET_DEVICE_FAN_MAP string = "g_d_fan_map"
const SET_DEVICE_FAN_MAP string = "s_d_fan_map"
const GET_DEVICE_FAN_DUTY_OUTPUT string = "g_d_fan_duty_out"
const SET_DEVICE_FAN_DUTY_OUTPUT string = "s_d_fan_duty_out"
const GET_ALL_FAN_DUTY_OUTPUT string = "g_all_fan_duty_out"
const GET_DEVICE_CPU_INFO string = "g_device_cpu_info"
const SET_DEVICE_CPU_INFO string = "s_device_cpu_info"
const GET_OBJ_BY_KEY string = "g_o_b_k"
const SET_OBJ_BY_KEY string = "s_o_b_k"
const EXIT_APPLICATION string = "exit_app"
const ENABLE_OUTOFBAND_INTERFACE string = "enable_out_ifc"
const DISABLE_OUTOFBAND_INTERFACE string = "disable_out_ifc"
<file_sep>/src/hwmon/rest_task.go
package hwmon
import "common"
import "encoding/json"
import "net/http"
//import "time"
import "context"
import "mailbox"
import "fmt"
//import "ops_log"
import "config"
type TaskRest struct {
Folder string
}
type rest_api_function_t func(w http.ResponseWriter, r *http.Request)
type rest_api_t struct {
Url string
Function rest_api_function_t
}
func responseWithJsonV1(w http.ResponseWriter, code int, data interface{}) {
json_msg := common.JsonMsg_t { Status:1, Version:1, Data:data }
response, _ := json.Marshal(json_msg)
//ops_log.Debug(0x01, "Response : %s", string(response))
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(code)
w.Write(response)
}
func (o* TaskRest)SetFolder(folder string) {
o.Folder = folder
}
func (o* TaskRest)Run() {
mux := http.NewServeMux()
for _, rest := range rest_api_list {
mux.HandleFunc(rest.Url, rest.Function)
}
srv := http.Server{ Addr: config.IN_SERVICE_PORT, Handler: mux }
is_started_srv := true // default enabled
is_kill_srv := false
//var srv2 http.Server
srv2 := http.Server{ Addr: config.OUT_SERVICE_PORT, Handler: mux }
is_started_srv2 := false
is_kill_srv2 := false
mb_rest := mailbox.CreateMailboxRest()
var res_msg common.Msg_t
isBreakTask := false
if is_started_srv {
go func() {
if err := srv.ListenAndServe(); err != nil && err != http.ErrServerClosed {
fmt.Println(err)
}
fmt.Printf("Stop Listen And Serve\n")
}()
}
var data common.DeviceInfo_t
for {
msg :=<-mb_rest.Channel
switch msg.Function {
case config.EXIT_APPLICATION:
if is_started_srv {
is_started_srv = false
is_kill_srv = true
}
if is_started_srv2 {
is_started_srv2 = false
is_kill_srv2 = true
}
isBreakTask = true
value := common.ValueResponse_t { Value: config.REQUEST_OK }
data = common.DeviceInfo_t { Entity:0, Instant:0, ValueType:config.TYPE_REQUEST_OK, Value:value }
case config.ENABLE_OUTOFBAND_INTERFACE:
if !is_started_srv2 {
go func() {
if err := srv2.ListenAndServe(); err != nil && err != http.ErrServerClosed {
fmt.Println(err)
}
fmt.Printf("Stop Listen And Serve2\n")
}()
}
is_started_srv2 = true
is_kill_srv2 = false
value := common.ValueResponse_t { Value: config.REQUEST_OK }
data = common.DeviceInfo_t { Entity:0, Instant:0, ValueType:config.TYPE_REQUEST_OK, Value:value }
case config.DISABLE_OUTOFBAND_INTERFACE:
if is_started_srv2 {
is_started_srv2 = false
is_kill_srv2 = true
fmt.Printf("Disable out of band interface\n")
}
value := common.ValueResponse_t { Value: config.REQUEST_OK }
data = common.DeviceInfo_t { Entity:0, Instant:0, ValueType:config.TYPE_REQUEST_OK, Value:value }
default:
value := common.ValueResponse_t { Value: config.REQUEST_ERROR_NOT_FOUND }
data = common.DeviceInfo_t { Entity:0, Instant:0, ValueType:config.TYPE_REQUEST_ERROR, Value:value }
}
//res_bytes := ConvertDeviceInfoToBytes(data)
res_msg = mailbox.WrapMsg(msg.Function, msg.ChannelSrc, msg.ChannelDst, data)
msg.ChannelDst <- res_msg
if is_kill_srv {
srv.Shutdown(context.Background())
}
if is_kill_srv2 {
fmt.Printf("closing srv2\n")
srv2.Shutdown(context.Background())
is_kill_srv2 = false
fmt.Printf("closed srv2\n")
}
if isBreakTask {
break
}
}
fmt.Println("Exit TaskRest")
}
<file_sep>/src/factory/factory_alg.go
package factory
//import "fmt"
import "utils"
import "algorithm"
func CreateAlgorithmPid(key string) (algorithm.Pid_t) {
var obj algorithm.Pid_t
db_obj := utils.PullObj(key)
if db_obj != nil {
obj = db_obj.(algorithm.Pid_t)
} else {
obj.Kp = 3
obj.Ki = 2
obj.Kd = 1
obj.ClampMin = 0
obj.ClampMax = 100
obj.TargetTemperature = -20
obj.DBKey = key
}
return obj
}
func CreateAlgorithmFanTable(key string) (algorithm.LookupTable_t) {
var obj algorithm.LookupTable_t
db_obj := utils.PullObj(key)
if db_obj != nil {
obj = db_obj.(algorithm.LookupTable_t)
} else {
obj.DBKey = key
}
return obj
}
func SaveAlgorithmToDB(key string, algorithm interface{}) {
utils.PushObj(key, algorithm)
}
<file_sep>/src/hwmon/hwmon_module.go
package hwmon
import "fmt"
import "time"
import "common"
import "utils"
import "config"
import "factory"
import "sort"
func funcAmbOpenloop(args map[string]interface{}) {
dev_amb := factory.CreateDeviceAmb()
list_abstemp := dev_amb.GetListAbsTemp()
for _, abstemp := range list_abstemp {
if abstemp.ValueType == config.TYPE_REQUEST_ERROR {
continue
}
instant := abstemp.Instant
absval := utils.ToFloat(abstemp.Value)
key := fmt.Sprintf("FanTable_AMB_%d", instant)
alg_obj := factory.CreateAlgorithmFanTable(key)
pwm := alg_obj.Compute(absval)
factory.SaveAlgorithmToDB(key, alg_obj)
dev_amb.SetExpectFanDuty(key, instant, pwm)
}
}
func funcAicThreshold(args map[string]interface{}) {
dev_aic := factory.CreateDeviceAic()
list_abstemp := dev_aic.GetListAbsTemp()
for _, abstemp := range list_abstemp {
if abstemp.ValueType == config.TYPE_REQUEST_ERROR {
continue
}
instant := abstemp.Instant
absval := utils.ToFloat(abstemp.Value)
key := fmt.Sprintf("FanTable_AIC_%d", instant)
alg_obj := factory.CreateAlgorithmFanTable(key)
pwm := alg_obj.Compute(absval)
factory.SaveAlgorithmToDB(key, alg_obj)
dev_aic.SetExpectFanDuty(key, instant, pwm)
}
}
func funcDimmThreshold(args map[string]interface{}) {
dev_dimm := factory.CreateDeviceDimm()
list_abstemp := dev_dimm.GetListAbsTemp()
for _, abstemp := range list_abstemp {
if abstemp.ValueType == config.TYPE_REQUEST_ERROR {
continue
}
instant := abstemp.Instant
absval := utils.ToFloat(abstemp.Value)
key := fmt.Sprintf("FanTable_DIMM_%d", instant)
alg_obj := factory.CreateAlgorithmFanTable(key)
pwm := alg_obj.Compute(absval)
factory.SaveAlgorithmToDB(key, alg_obj)
dev_dimm.SetExpectFanDuty(key, instant, pwm)
}
}
func funcCpuPid(args map[string]interface{}) {
dev_cpu := factory.CreateDeviceCpu()
list_reltemp := dev_cpu.GetListRelTemp()
for _, reltemp := range list_reltemp {
if reltemp.ValueType == config.TYPE_REQUEST_ERROR {
continue
}
instant := reltemp.Instant
relval := utils.ToFloat(reltemp.Value)
key := fmt.Sprintf("<KEY> instant)
alg_obj := factory.CreateAlgorithmPid(key)
pwm := alg_obj.Compute(relval)
factory.SaveAlgorithmToDB(key, alg_obj)
dev_cpu.SetExpectFanDuty(key, instant, pwm)
}
}
func funcCpuThreshold(args map[string]interface{}) {
dev_cpu := factory.CreateDeviceCpu()
list_reltemp := dev_cpu.GetListRelTemp()
for _, reltemp := range list_reltemp {
if reltemp.ValueType == config.TYPE_REQUEST_ERROR {
continue
}
instant := reltemp.Instant
relval := utils.ToFloat(reltemp.Value)
key := fmt.Sprintf("FanTable_CPU_%d", instant)
alg_obj := factory.CreateAlgorithmFanTable(key)
pwm := alg_obj.Compute(relval)
factory.SaveAlgorithmToDB(key, alg_obj)
dev_cpu.SetExpectFanDuty(key, instant, pwm)
}
}
func funcCpuPowerband(args map[string]interface{}) {
dev_cpu := factory.CreateDeviceCpu()
list_ap := dev_cpu.GetListAveragePower()
for _, ap := range list_ap {
if ap.ValueType == config.TYPE_REQUEST_ERROR {
continue
}
mp := dev_cpu.GetMaxPower(ap.Instant)
if mp.ValueType == config.TYPE_REQUEST_ERROR {
continue
}
val_ap := utils.ToFloat(ap.Value)
val_mp := utils.ToFloat(mp.Value)
val := val_ap/val_mp
instant := ap.Instant
key := fmt.Sprintf("<KEY> instant)
//fmt.Printf("CPU Power %f/%f=%f\n", val_ap, val_mp, val_ap/val_mp)
if val < 0.3 {
dev_cpu.SetExpectFanDuty(key, instant, 15)
} else if (val >= 0.3) && (val < 0.6) {
dev_cpu.SetExpectFanDuty(key, instant, 30)
} else if (val >= 0.6) && (val < 0.9) {
dev_cpu.SetExpectFanDuty(key, instant, 70)
} else {
dev_cpu.SetExpectFanDuty(key, instant, 100)
}
}
}
func setupFansAndDevices() {
dev_fan := factory.CreateDeviceFan()
var defDuty float32 = 60.0
fanMap := []common.DeviceInfo_t {
{ Entity: config.ENTITY_FAN_COOLING, Instant: config.FAN_INSTANT1, Value: defDuty },
{ Entity: config.ENTITY_FAN_COOLING, Instant: config.FAN_INSTANT2, Value: defDuty },
{ Entity: config.ENTITY_FAN_COOLING, Instant: config.FAN_INSTANT3, Value: defDuty },
}
//Set Default Fans Duty
for _, obj := range fanMap {
fan_duty := utils.ToFloat(obj.Value)
dev_fan.InitDutyOutput(obj.Instant, fan_duty)
}
deviceMapFan := []common.DeviceInfo_t {
{ Entity: config.ENTITY_PROCESSOR, Instant: config.DEV_INSTANT1, Value: config.FAN_INSTANT1 },
{ Entity: config.ENTITY_MEMORY_DEVICE, Instant: config.DEV_INSTANT1, Value: config.FAN_INSTANT1 },
{ Entity: config.ENTITY_ADD_IN_CARD, Instant: config.DEV_INSTANT1, Value: config.FAN_INSTANT2 },
{ Entity: config.ENTITY_PROCESSOR, Instant: config.DEV_INSTANT2, Value: config.FAN_INSTANT3 },
{ Entity: config.ENTITY_MEMORY_DEVICE, Instant: config.DEV_INSTANT2, Value: config.FAN_INSTANT3 },
{ Entity: config.ENTITY_EXTERNAL_ENVIROMENT, Instant: config.DEV_INSTANT1, Value: config.FAN_INSTANT1 },
{ Entity: config.ENTITY_EXTERNAL_ENVIROMENT, Instant: config.DEV_INSTANT1, Value: config.FAN_INSTANT2 },
{ Entity: config.ENTITY_EXTERNAL_ENVIROMENT, Instant: config.DEV_INSTANT1, Value: config.FAN_INSTANT3 },
}
//Set Devices and Fans Map
for _, obj := range deviceMapFan {
fan_instant := utils.ToInt(obj.Value)
dev_fan.SetDeviceMap(obj.Entity, obj.Instant, fan_instant)
}
}
func getSortedKeys(list map[string]common.DeviceInfo_t) ([]string) {
keys := make([]string, 0, len(list))
for key := range list {
keys = append(keys, key)
}
sort.Strings(keys)
return keys
}
func compareAndGetFanDuty(device_list map[string]common.DeviceInfo_t)(map[int32]float32) {
dev_fan := factory.CreateDeviceFan()
fan_list := make(map[int32]float32)
fanMap := dev_fan.GetAllDutyOutput()
for _, obj := range fanMap {
fan_list[obj.Instant] = -1.0
}
keys1 := getSortedKeys(device_list)
for _, key := range keys1 {
obj := device_list[key]
fmt.Printf("[%d]EID:%d, INST:%d, DUTY:%f[%s]\n", obj.ValueType, obj.Entity, obj.Instant, obj.Value, obj.Key)
device_list := dev_fan.GetDeviceMap(obj.Entity, obj.Instant)
for _, fm := range device_list {
fmt.Printf("\tmap to fan : %d\n", fm.Value)
fanInstant := utils.ToInt(-1)
if fm.ValueType != config.TYPE_REQUEST_ERROR {
fanInstant = utils.ToInt(fm.Value)
}
out_duty := utils.ToFloat(obj.Value)
if fan_list[fanInstant] < out_duty {
fan_list[fanInstant] = out_duty
}
}
}
return fan_list
}
func showFanDuty() {
dev_fan := factory.CreateDeviceFan()
fan_list := dev_fan.GetAllDutyOutput()
keys2 := getSortedKeys(fan_list)
for _, key := range keys2 {
obj := fan_list[key]
fmt.Printf("Fan[%d]=%f[%s-%d]\n", obj.Instant, obj.Value, key, obj.ValueType)
}
}
func funcFanMap(args map[string]interface{}) {
dev_fan := factory.CreateDeviceFan()
map_expect_fan_duty := dev_fan.GetAllDevicesExpectFanDuty()
fmt.Printf("==BEGIN==\n")
fan_list := compareAndGetFanDuty(map_expect_fan_duty)
for idx := range fan_list {
if fan_list[idx] < 0 {
continue
}
dev_fan.SetDutyOutput(idx, fan_list[idx])
}
fmt.Printf("==Result==\n")
showFanDuty()
fmt.Printf("==END==\n")
}
const FUNC_STAT_INIT = 0
const FUNC_STAT_RUNNING = 1
const FUNC_STAT_EXIT = 99
type TaskInfo struct {
Name string
FunctionExit bool
FunctionStatus int
Function func(map[string]interface{})
FunctionArgs map[string]interface{}
}
func (o *TaskInfo)RunTask() {
o.FunctionStatus = FUNC_STAT_RUNNING
o.FunctionArgs = make(map[string]interface{})
for {
if o.FunctionExit {
break
}
time.Sleep(1 * time.Second)
o.Function(o.FunctionArgs)
}
o.FunctionStatus = FUNC_STAT_EXIT
fmt.Println("Exit " + o.Name)
}
func GetModules() ([]TaskInfo){
setupFansAndDevices()
tasks := []TaskInfo {
{Name:"AMB_Openloop", Function:funcAmbOpenloop, FunctionExit:false, FunctionStatus:FUNC_STAT_INIT},
//{Name:"CPU_Threshold", Function:funcCpuThreshold, FunctionExit:false, FunctionStatus:FUNC_STAT_INIT},
{Name:"FAN_Map", Function:funcFanMap, FunctionExit:false, FunctionStatus:FUNC_STAT_INIT},
{Name:"CPU_Powerband", Function:funcCpuPowerband, FunctionExit:false, FunctionStatus:FUNC_STAT_INIT},
{Name:"CPU_PID", Function:funcCpuPid, FunctionExit:false, FunctionStatus:FUNC_STAT_INIT},
{Name:"DIMM_Threshold", Function:funcDimmThreshold, FunctionExit:false, FunctionStatus:FUNC_STAT_INIT},
{Name:"AIC_Threshold", Function:funcAicThreshold, FunctionExit:false, FunctionStatus:FUNC_STAT_INIT},
}
return tasks
}
<file_sep>/src/device/aic.go
package device
import "common"
import "utils"
/*
*
*/
type Aic_t struct {
Entity int32
}
func (o *Aic_t)GetListAbsTemp() (map[string]common.DeviceInfo_t) {
obj := utils.PullObjListDeviceAbsTemp(o.Entity)
return obj
}
func (o *Aic_t)GetAbsTemp(instant int32) (common.DeviceInfo_t) {
obj := utils.PullObjDeviceAbsTemp(o.Entity, instant)
return obj
}
func (o *Aic_t)SetAbsTemp(instant int32, value float32) (common.DeviceInfo_t) {
obj := utils.PushObjDeviceAbsTemp(o.Entity, instant, value)
return obj
}
func (o *Aic_t)GetListAveragePower() (map[string]common.DeviceInfo_t) {
obj := utils.PullObjListDeviceAveragePower(o.Entity)
return obj
}
func (o *Aic_t)GetAveragePower(instant int32) (common.DeviceInfo_t) {
obj := utils.PullObjDeviceAveragePower(o.Entity, instant)
return obj
}
func (o *Aic_t)SetAveragePower(instant int32, value float32) (common.DeviceInfo_t) {
obj := utils.PushObjDeviceAveragePower(o.Entity, instant, value)
return obj
}
func (o *Aic_t)SetExpectFanDuty(key string, instant int32, value float32) (common.DeviceInfo_t) {
obj := utils.PushObjExpectFanDuty(key, o.Entity, instant, value)
return obj
}
/*
func (o *Aic_t)SetExpectFanDutyByTemperature(instant int32, value float32) (common.DeviceInfo_t) {
obj := utils.PushObjExpectFanDutyByTemperature(o.Entity, instant, value)
return obj
}
func (o *Aic_t)SetExpectFanDutyByPower(instant int32, value float32) (common.DeviceInfo_t) {
obj := utils.PushObjExpectFanDutyByPower(o.Entity, instant, value)
return obj
}
*/
func (o *Aic_t)GetMaxPower(instant int32) (common.DeviceInfo_t) {
obj := utils.PullObjDeviceMaxPower(o.Entity, instant)
return obj
}
func (o *Aic_t)GetListMaxPower()(map[string]common.DeviceInfo_t) {
list := utils.PullObjListDeviceMaxPower(o.Entity)
return list
}
<file_sep>/src/algorithm/pid.go
package algorithm
//import "fmt"
import "math"
type Pid_t struct {
Kp float32
Ki float32
Kd float32
TargetTemperature float32
err_history float32
err_pre float32
u float32
ClampMin float32
ClampMax float32
DBKey string
}
func (o* Pid_t)Compute(currentTemperature float32) float32 {
//Pid
err := currentTemperature - o.TargetTemperature
P := o.Kp * err
//pId
o.err_history = (o.err_history + err)/2
I := o.Ki * o.err_history
//piD
D := o.Kd * (err - o.err_pre)
val := o.u + P + I + D
val = float32(math.Floor(float64(val + 0.5)))
if val <= o.ClampMin {
val = o.ClampMin
}
if val >= o.ClampMax {
val = o.ClampMax
}
o.err_pre = err
o.u = val
//fmt.Printf("PWM(%f)=%f + %f*%f + %f*%f + %f*(%f-%f)\n", val, o.u, o.Kp, err, o.Ki, o.err_history, o.Kd, err, o.err_pre)
return val
}
<file_sep>/src/ops_log/syslog_client.go
package ops_log
import "fmt"
//import "log/syslog"
func Info(mask uint32, format string, a ...interface{}) {
log_str := fmt.Sprintf(format, a)
fmt.Println(log_str)
return
/*
log, _ := syslog.Dial("", "", syslog.LOG_USER|syslog.LOG_INFO, "iopc_go")
log.Info(log_str)
log.Close()
*/
}
func Debug(mask uint32, format string, a ...interface{}) {
log_str := fmt.Sprintf(format, a)
fmt.Println(log_str)
return
/*
log, _ := syslog.Dial("", "", syslog.LOG_USER|syslog.LOG_DEBUG, "iopc_go")
log.Debug(log_str)
log.Close()
*/
}
func Error(mask uint32, format string, a ...interface{}) {
log_str := fmt.Sprintf(format, a)
fmt.Println(log_str)
return
/*
log, _ := syslog.Dial("", "", syslog.LOG_USER|syslog.LOG_ERR, "iopc_go")
log.Err(log_str)
log.Close()
*/
}
<file_sep>/src/device/amb.go
package device
import "common"
import "utils"
/*
*
*/
type Amb_t struct {
Entity int32
}
func (o *Amb_t)GetListAbsTemp() (map[string]common.DeviceInfo_t) {
obj := utils.PullObjListDeviceAbsTemp(o.Entity)
return obj
}
func (o *Amb_t)GetAbsTemp(instant int32) (common.DeviceInfo_t) {
obj := utils.PullObjDeviceAbsTemp(o.Entity, instant)
return obj
}
func (o *Amb_t)SetAbsTemp(instant int32, value float32) (common.DeviceInfo_t) {
obj := utils.PushObjDeviceAbsTemp(o.Entity, instant, value)
return obj
}
func (o *Amb_t)SetExpectFanDuty(key string, instant int32, value float32) (common.DeviceInfo_t) {
obj := utils.PushObjExpectFanDuty(key, o.Entity, instant, value)
return obj
}
/*
func (o *Amb_t)SetExpectFanDutyByTemperature(instant int32, value float32) (common.DeviceInfo_t) {
obj := utils.PushObjExpectFanDutyByTemperature(o.Entity, instant, value)
return obj
}
func (o *Amb_t)SetExpectFanDutyByPower(instant int32, value float32) (common.DeviceInfo_t) {
obj := utils.PushObjExpectFanDutyByPower(o.Entity, instant, value)
return obj
}
*/
<file_sep>/version.h
#define MAJOR_NUM 1
#define MINOR_NUM 1
#define AUX_NUM 0
<file_sep>/request_scripts/map_device_fan.py
#!/usr/bin/python2.7
import sys
import utils
def request_list(hostname, out_format):
json = '{"entity":-1, "instant":-1}'
url='http://%s/api/v1/hwmon/get/map/alldevicefan' % hostname
utils.response_output(out_format, utils.http_request(url, json))
url='http://%s/api/v1/hwmon/get/map/allfandutyout' % hostname
utils.response_output(out_format, utils.http_request(url, json))
url='http://%s/api/v1/hwmon/get/map/allexpectduty' % hostname
utils.response_output(out_format, utils.http_request(url, json))
if __name__ == '__main__':
if len(sys.argv) < 2:
utils.help_usage()
hostname=sys.argv[1]
request_list(hostname, 'json')
| afb8b0362def1dea6aaf2ba2ba55f54e394c25cd | [
"Makefile",
"Python",
"C",
"Go",
"Shell"
] | 32 | Go | YuanYuLin/go_hwmon | e9cac6cbaf1b00a6c8e7997203abfcfb761da0f2 | 038b6ffe33cbfaa0397a3950a250ffd4863abe2d |
refs/heads/master | <file_sep><?php return array(
'root' => array(
'pretty_version' => '1.0.0+no-version-set',
'version' => '1.0.0.0',
'type' => 'library',
'install_path' => __DIR__ . '/../../',
'aliases' => array(),
'reference' => NULL,
'name' => 'test/urlscanner',
'dev' => true,
),
'versions' => array(
'doctrine/instantiator' => array(
'pretty_version' => '1.5.x-dev',
'version' => '1.5.9999999.9999999-dev',
'type' => 'library',
'install_path' => __DIR__ . '/../doctrine/instantiator',
'aliases' => array(),
'reference' => '6410c4b8352cb64218641457cef64997e6b784fb',
'dev_requirement' => true,
),
'guzzlehttp/guzzle' => array(
'pretty_version' => '5.3.x-dev',
'version' => '5.3.9999999.9999999-dev',
'type' => 'library',
'install_path' => __DIR__ . '/../guzzlehttp/guzzle',
'aliases' => array(),
'reference' => 'd59d5293b4a804d6436d64fec71a8c75110a3165',
'dev_requirement' => false,
),
'guzzlehttp/ringphp' => array(
'pretty_version' => 'dev-master',
'version' => 'dev-master',
'type' => 'library',
'install_path' => __DIR__ . '/../guzzlehttp/ringphp',
'aliases' => array(
0 => '1.1.x-dev',
),
'reference' => '5e2a174052995663dd68e6b5ad838afd47dd615b',
'dev_requirement' => false,
),
'guzzlehttp/streams' => array(
'pretty_version' => 'dev-master',
'version' => 'dev-master',
'type' => 'library',
'install_path' => __DIR__ . '/../guzzlehttp/streams',
'aliases' => array(
0 => '3.0.x-dev',
),
'reference' => 'd99a261c616210618ab94fd319cb17eda458cc3e',
'dev_requirement' => false,
),
'phpdocumentor/reflection-common' => array(
'pretty_version' => 'dev-master',
'version' => 'dev-master',
'type' => 'library',
'install_path' => __DIR__ . '/../phpdocumentor/reflection-common',
'aliases' => array(
0 => '2.x-dev',
),
'reference' => 'cf8df60735d98fd18070b7cab0019ba0831e219c',
'dev_requirement' => true,
),
'phpdocumentor/reflection-docblock' => array(
'pretty_version' => 'dev-master',
'version' => 'dev-master',
'type' => 'library',
'install_path' => __DIR__ . '/../phpdocumentor/reflection-docblock',
'aliases' => array(
0 => '5.x-dev',
),
'reference' => '8719cc12e2a57ec3432a76989bb4ef773ac75b63',
'dev_requirement' => true,
),
'phpdocumentor/type-resolver' => array(
'pretty_version' => '1.x-dev',
'version' => '1.9999999.9999999.9999999-dev',
'type' => 'library',
'install_path' => __DIR__ . '/../phpdocumentor/type-resolver',
'aliases' => array(),
'reference' => '6759f2268deb9f329812679e9dcb2d0083b2a30b',
'dev_requirement' => true,
),
'phpspec/prophecy' => array(
'pretty_version' => 'v1.10.3',
'version' => '1.10.3.0',
'type' => 'library',
'install_path' => __DIR__ . '/../phpspec/prophecy',
'aliases' => array(),
'reference' => '451c3cd1418cf640de218914901e51b064abb093',
'dev_requirement' => true,
),
'phpunit/php-code-coverage' => array(
'pretty_version' => '2.2.4',
'version' => '2.2.4.0',
'type' => 'library',
'install_path' => __DIR__ . '/../phpunit/php-code-coverage',
'aliases' => array(),
'reference' => 'eabf68b476ac7d0f73793aada060f1c1a9bf8979',
'dev_requirement' => true,
),
'phpunit/php-file-iterator' => array(
'pretty_version' => '1.4.x-dev',
'version' => '1.4.9999999.9999999-dev',
'type' => 'library',
'install_path' => __DIR__ . '/../phpunit/php-file-iterator',
'aliases' => array(),
'reference' => '730b01bc3e867237eaac355e06a36b85dd93a8b4',
'dev_requirement' => true,
),
'phpunit/php-text-template' => array(
'pretty_version' => '1.2.1',
'version' => '1.2.1.0',
'type' => 'library',
'install_path' => __DIR__ . '/../phpunit/php-text-template',
'aliases' => array(),
'reference' => '31f8b717e51d9a2afca6c9f046f5d69fc27c8686',
'dev_requirement' => true,
),
'phpunit/php-timer' => array(
'pretty_version' => '1.0.x-dev',
'version' => '1.0.9999999.9999999-dev',
'type' => 'library',
'install_path' => __DIR__ . '/../phpunit/php-timer',
'aliases' => array(),
'reference' => '9513098641797ce5f459dbc1de5a54c29b0ec1fb',
'dev_requirement' => true,
),
'phpunit/php-token-stream' => array(
'pretty_version' => '1.4.12',
'version' => '1.4.12.0',
'type' => 'library',
'install_path' => __DIR__ . '/../phpunit/php-token-stream',
'aliases' => array(),
'reference' => '1ce90ba27c42e4e44e6d8458241466380b51fa16',
'dev_requirement' => true,
),
'phpunit/phpunit' => array(
'pretty_version' => '4.8.36',
'version' => '4.8.36.0',
'type' => 'library',
'install_path' => __DIR__ . '/../phpunit/phpunit',
'aliases' => array(),
'reference' => '46023de9a91eec7dfb06cc56cb4e260017298517',
'dev_requirement' => true,
),
'phpunit/phpunit-mock-objects' => array(
'pretty_version' => '2.3.x-dev',
'version' => '2.3.9999999.9999999-dev',
'type' => 'library',
'install_path' => __DIR__ . '/../phpunit/phpunit-mock-objects',
'aliases' => array(),
'reference' => 'ac8e7a3db35738d56ee9a76e78a4e03d97628983',
'dev_requirement' => true,
),
'react/promise' => array(
'pretty_version' => '2.x-dev',
'version' => '2.9999999.9999999.9999999-dev',
'type' => 'library',
'install_path' => __DIR__ . '/../react/promise',
'aliases' => array(),
'reference' => 'a9752a861e21c0fe0b380c9f9e55beddc0ed7d31',
'dev_requirement' => false,
),
'sebastian/comparator' => array(
'pretty_version' => '1.2.x-dev',
'version' => '1.2.9999999.9999999-dev',
'type' => 'library',
'install_path' => __DIR__ . '/../sebastian/comparator',
'aliases' => array(),
'reference' => '18a5d97c25f408f48acaf6d1b9f4079314c5996a',
'dev_requirement' => true,
),
'sebastian/diff' => array(
'pretty_version' => '1.4.x-dev',
'version' => '1.4.9999999.9999999-dev',
'type' => 'library',
'install_path' => __DIR__ . '/../sebastian/diff',
'aliases' => array(),
'reference' => '7f066a26a962dbe58ddea9f72a4e82874a3975a4',
'dev_requirement' => true,
),
'sebastian/environment' => array(
'pretty_version' => '1.3.x-dev',
'version' => '1.3.9999999.9999999-dev',
'type' => 'library',
'install_path' => __DIR__ . '/../sebastian/environment',
'aliases' => array(),
'reference' => '67f55699c2810ff0f2cc47478bbdeda8567e68ee',
'dev_requirement' => true,
),
'sebastian/exporter' => array(
'pretty_version' => '1.2.x-dev',
'version' => '1.2.9999999.9999999-dev',
'type' => 'library',
'install_path' => __DIR__ . '/../sebastian/exporter',
'aliases' => array(),
'reference' => 'dcd43bcc0fd3551bd2ede0081882d549bb78225d',
'dev_requirement' => true,
),
'sebastian/global-state' => array(
'pretty_version' => '1.1.x-dev',
'version' => '1.1.9999999.9999999-dev',
'type' => 'library',
'install_path' => __DIR__ . '/../sebastian/global-state',
'aliases' => array(),
'reference' => 'cea85a84b00f2795341ebbbca4fa396347f2494e',
'dev_requirement' => true,
),
'sebastian/recursion-context' => array(
'pretty_version' => '1.0.x-dev',
'version' => '1.0.9999999.9999999-dev',
'type' => 'library',
'install_path' => __DIR__ . '/../sebastian/recursion-context',
'aliases' => array(),
'reference' => 'b19cc3298482a335a95f3016d2f8a6950f0fbcd7',
'dev_requirement' => true,
),
'sebastian/version' => array(
'pretty_version' => '1.0.6',
'version' => '1.0.6.0',
'type' => 'library',
'install_path' => __DIR__ . '/../sebastian/version',
'aliases' => array(),
'reference' => '58b3a85e7999757d6ad81c787a1fbf5ff6c628c6',
'dev_requirement' => true,
),
'symfony/polyfill-ctype' => array(
'pretty_version' => 'dev-main',
'version' => 'dev-main',
'type' => 'library',
'install_path' => __DIR__ . '/../symfony/polyfill-ctype',
'aliases' => array(
0 => '1.23.x-dev',
),
'reference' => '46cd95797e9df938fdd2b03693b5fca5e64b01ce',
'dev_requirement' => true,
),
'symfony/yaml' => array(
'pretty_version' => '3.4.x-dev',
'version' => '3.4.9999999.9999999-dev',
'type' => 'library',
'install_path' => __DIR__ . '/../symfony/yaml',
'aliases' => array(),
'reference' => '88289caa3c166321883f67fe5130188ebbb47094',
'dev_requirement' => true,
),
'test/urlscanner' => array(
'pretty_version' => '1.0.0+no-version-set',
'version' => '1.0.0.0',
'type' => 'library',
'install_path' => __DIR__ . '/../../',
'aliases' => array(),
'reference' => NULL,
'dev_requirement' => false,
),
'webmozart/assert' => array(
'pretty_version' => 'dev-master',
'version' => 'dev-master',
'type' => 'library',
'install_path' => __DIR__ . '/../webmozart/assert',
'aliases' => array(
0 => '1.10.x-dev',
),
'reference' => 'b419d648592b0b8911cbbe10d450fe314f4fd262',
'dev_requirement' => true,
),
),
);
| be3626862bd5843b973ea11bb81b9f23c4fba624 | [
"PHP"
] | 1 | PHP | 450711475/urlscanner | 675b45e076fe3cf4b69c173e73a6a14bba49185c | fcef2c92824e4999c7dfb4a00d290603b80295fc |
refs/heads/master | <file_sep># simple-classification
Using Sciki Learn
<file_sep>import cv2
import numpy as np
import os
from sklearn.preprocessing import normalize
from sklearn import svm
from sklearn import metrics
bibnumbers = []
with open("test.txt", "r") as f:
for line in f:
bibnumbers.append(line.strip())
src_train = np.zeros(1)
src2_train = np.zeros(2)
des_train = np.zeros(1)
des2_train = np.zeros(2)
pro_train = np.zeros(2)
lth_train = np.zeros(1)
cll_train = np.zeros(1)
src_test = np.zeros(1)
src2_test = np.zeros(2)
des_test = np.zeros(1)
des2_test = np.zeros(2)
pro_test = np.zeros(2)
lth_test = np.zeros(1)
cll_test = np.zeros(1)
count = 0
for data in bibnumbers:
tmp = data.split(' ')
src_port = np.array([tmp[0]])
src2 = np.array([tmp[1]])
des_port = np.array([tmp[2]])
des2 = np.array([tmp[3]])
protocol = np.array([tmp[4]])
length = np.array([tmp[5]])
outclass = np.array([tmp[7]])
# one hot encoding
if protocol == "TCP":
protocol = np.array([0,1])
else:
protocol = np.array([1,0])
if src2 == "Wellknown":
src2 = np.array([1,0])
else:
src2 = np.array([0,1])
if des2 == "Wellknown":
des2 = np.array([1,0])
else:
des2 = np.array([0,1])
if outclass == 'NGBR_Expedited':
outclass = np.array([1])
elif outclass == 'NGBR_Assured':
outclass = np.array([2])
else:
outclass = np.array([3])
count+= 1
if count<21:
src_train = np.vstack((src_train, src_port))
src2_train = np.vstack((src2_train, src2))
des_train = np.vstack((des_train, des_port))
des2_train = np.vstack((des2_train, des2))
pro_train = np.vstack((pro_train, protocol))
lth_train = np.vstack((lth_train, length))
cll_train = np.vstack((cll_train, outclass))
else:
src_test = np.vstack((src_test, src_port))
src2_test = np.vstack((src2_test, src2))
des_test = np.vstack((des_test, des_port))
des2_test = np.vstack((des2_test, des2))
pro_test = np.vstack((pro_test, protocol))
lth_test = np.vstack((lth_test, length))
cll_test = np.vstack((cll_test, outclass))
X_train = np.hstack((des_train, pro_train, src2_train, lth_train))
X_test = np.hstack(( des_test, pro_test, src2_test, lth_test))
Y_train = cll_train
Y_test = cll_test
# print(X_train)
# print(Y_train)
lin_clf = svm.LinearSVC()
lin_clf.fit(X_train, Y_train)
#Create a svm Classifier
clf = svm.SVC(kernel='linear') # Linear Kernel
#Train the model using the training sets
clf.fit(X_train, Y_train)
#Predict the response for test dataset
y_pred = clf.predict(X_test)
print(y_pred)
print("Accuracy:",metrics.accuracy_score(Y_test, y_pred))
| 04c1793fd874e86b30cffe57b6aad0d866063356 | [
"Markdown",
"Python"
] | 2 | Markdown | didpurwanto/simple-classification | 81f995fd200813c67c49fefb83bfbec47754659e | 622ec688eade445ed0c2551a8a922f5ea911f850 |
refs/heads/master | <repo_name>rhapsodixx/Code4VoteChallenge-mobile<file_sep>/README.md
Code4VoteChallenge-mobile
=========================
Workspace for SooYoung Code For Vote Challange Project.
Just clone, then Import Project in Eclipse.
May need some adjustments regarding Android SDK location.
Cheers :)
<file_sep>/MataPemilu/src/com/sooyoung/codeforvote/adapter/CandidateCompareListAdapter.java
package com.sooyoung.codeforvote.adapter;
import java.util.List;
import android.content.Context;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import com.sooyoung.codeforvote.R;
public class CandidateCompareListAdapter extends BaseAdapter {
LayoutInflater inflater;
List<String> text;
int layoutResouceId;
public CandidateCompareListAdapter(Context context, List<String> text, int layoutResourceId) {
this.inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
this.text = text;
this.layoutResouceId = layoutResourceId;
}
@Override
public int getCount() {
return text.size();
}
@Override
public Object getItem(int position) {
return text.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = convertView;
if (view == null) {
view = inflater.inflate(layoutResouceId, null);
}
Log.d("text", text.get(position));
TextView label = (TextView) view.findViewById(R.id.label_text);
ImageView image = (ImageView) view.findViewById(R.id.imageView1);
if (position == 0) {
image.setImageResource(R.drawable.icon_bio);
} else if (position == 1) {
image.setImageResource(R.drawable.icon_edu);
} else if (position == 2) {
image.setImageResource(R.drawable.icon_wrk);
} else if (position == 3) {
image.setImageResource(R.drawable.icon_awd);
} else if (position == 4) {
image.setImageResource(R.drawable.icon_org);
}
label.setText(text.get(position));
return view;
}
}
<file_sep>/MataPemilu/src/com/sooyoung/codeforvote/CandidateCompareFragment.java
package com.sooyoung.codeforvote;
import java.util.ArrayList;
import java.util.List;
import org.androidannotations.annotations.AfterViews;
import org.androidannotations.annotations.EFragment;
import org.androidannotations.annotations.FragmentArg;
import org.androidannotations.annotations.ViewById;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.text.format.DateFormat;
import android.widget.ImageView;
import android.widget.ListView;
import com.sooyoung.codeforvote.adapter.CandidateCompareListAdapter;
import com.sooyoung.codeforvote.helper.DatabaseHelper;
import com.sooyoung.codeforvote.model.AchievementHistory;
import com.sooyoung.codeforvote.model.Candidate;
import com.sooyoung.codeforvote.model.EducationHistory;
import com.sooyoung.codeforvote.model.OrganizationHistory;
import com.sooyoung.codeforvote.model.WorkHistory;
@EFragment(R.layout.fragment_candidate_compare)
public class CandidateCompareFragment extends Fragment {
@ViewById(R.id.compare_candidate_image_view)
ImageView mCandidateImage;
@ViewById(R.id.compare_list_view)
ListView mDataListView;
@FragmentArg
String id;
@FragmentArg
int position;
CandidateCompareListAdapter mAdapter;
Candidate mCandidate;
List<String> mLabelList;
public static CandidateCompareFragment createFragment(String id,
int position) {
CandidateCompareFragment fragment = new CandidateCompareFragment_();
Bundle args = new Bundle();
args.putString("id", id);
args.putInt("position", position);
fragment.setArguments(args);
return fragment;
}
@AfterViews
void initialize() {
mCandidate = DatabaseHelper.getCandidateById(id);
if (id == "jw") {
mCandidateImage.setImageResource(R.drawable.jw_vs);
} else if (id == "jk") {
mCandidateImage.setImageResource(R.drawable.jk_vs);
} else if (id == "ps") {
mCandidateImage.setImageResource(R.drawable.pb_vs);
} else if (id == "hr") {
mCandidateImage.setImageResource(R.drawable.ht_vs);
}
mLabelList = new ArrayList<String>();
String biodata = processBiodata();
String educationHistory = processEducation();
String workHistory = processWork();
String achievementHistory = processAchievement();
String organizationHistory = processOrganization();
mLabelList.add(biodata);
mLabelList.add(educationHistory);
mLabelList.add(workHistory);
mLabelList.add(achievementHistory);
mLabelList.add(organizationHistory);
int layoutResourceId;
if (position == 0) {
layoutResourceId = R.layout.list_item_candidate_profile;
} else {
layoutResourceId = R.layout.list_item_second_candidate_profile;
}
mAdapter = new CandidateCompareListAdapter(getActivity(), mLabelList,
layoutResourceId);
mDataListView.setAdapter(mAdapter);
}
private String processAchievement() {
List<AchievementHistory> achievementList = DatabaseHelper
.getAchievementHistoryOfCandidate(id);
StringBuilder builder = new StringBuilder();
builder.append("\n");
builder.append("\n");
for (int i = 0; i < achievementList.size(); i++) {
builder.append(achievementList.get(i).getEntityName());
builder.append("\n");
builder.append("\n");
}
return builder.toString();
}
private String processWork() {
List<WorkHistory> workList = DatabaseHelper
.getWorkHistoryOfCandidate(id);
StringBuilder builder = new StringBuilder();
builder.append("\n");
builder.append("\n");
for (int i = 0; i < workList.size(); i++) {
builder.append(workList.get(i).getEntityName());
builder.append("\n");
builder.append("\n");
}
return builder.toString();
}
private String processEducation() {
List<EducationHistory> educationList = DatabaseHelper
.getEducationHistoryOfCandidate(id);
StringBuilder builder = new StringBuilder();
builder.append("\n");
builder.append("\n");
for (int i = 0; i < educationList.size(); i++) {
builder.append(educationList.get(i).getSchoolName());
builder.append("\n");
builder.append("\n");
}
return builder.toString();
}
private String processBiodata() {
String name = mCandidate.getName();
String religion = mCandidate.getReligion();
String birthDate = (String) DateFormat.format("dd-MM-yyyy",
mCandidate.getBirthDate());
List<String> list = new ArrayList<String>();
list.add(name);
list.add(religion);
list.add(birthDate);
StringBuilder builder = new StringBuilder();
builder.append("\n");
builder.append("\n");
for (int i = 0; i < 3; i++) {
builder.append(list.get(i));
builder.append("\n");
builder.append("\n");
}
return builder.toString();
}
private String processOrganization() {
List<OrganizationHistory> organizationList = OrganizationHistory.find(
OrganizationHistory.class, "candidate_id = ?", id);
StringBuilder builder = new StringBuilder();
builder.append("\n");
builder.append("\n");
for (int i = 0; i < organizationList.size(); i++) {
builder.append(organizationList.get(i).getPosition());
builder.append("\n");
builder.append(organizationList.get(i).getEntityName());
builder.append("\n");
builder.append("\n");
}
return builder.toString();
}
}
<file_sep>/MataPemilu/src/com/sooyoung/codeforvote/CandidateProfileDialog.java
package com.sooyoung.codeforvote;
import org.androidannotations.annotations.EFragment;
import android.app.AlertDialog;
import android.app.Dialog;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.animation.ScaleAnimation;
@EFragment
public class CandidateProfileDialog extends DialogFragment {
LayoutInflater mInflater;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
mInflater = getActivity().getLayoutInflater();
View view = mInflater.inflate(R.layout.dialog_candidate_profile, null);
ScaleAnimation animation = new ScaleAnimation(0.0f, 1.0f, 0.0f, 1.0f,
ScaleAnimation.RELATIVE_TO_SELF, 0.5f,
ScaleAnimation.RELATIVE_TO_SELF, 0.5f);
animation.setFillAfter(true);
animation.setDuration(500);
view.startAnimation(animation);
builder.setView(view);
Dialog dialog = builder.create();
//dialog.getWindow().getAttributes().windowAnimations = R.style.MyAnimation_Window;
return dialog;
}
}
<file_sep>/MataPemilu/src/com/sooyoung/codeforvote/VoteFragment.java
package com.sooyoung.codeforvote;
import java.util.ArrayList;
import java.util.List;
import org.androidannotations.annotations.AfterViews;
import org.androidannotations.annotations.Background;
import org.androidannotations.annotations.EFragment;
import org.androidannotations.annotations.UiThread;
import org.androidannotations.annotations.ViewById;
import org.apache.http.Header;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.support.v4.app.Fragment;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.sooyoung.codeforvote.helper.SooYoungRestClient;
import com.sooyoung.codeforvote.model.PresidolCandidate;
@EFragment(R.layout.fragment_vote)
public class VoteFragment extends Fragment
{
private List<PresidolCandidate> mPresidols;
@ViewById
DeliciousTextView sentiment_neutral_one;
@ViewById
DeliciousTextView sentiment_positive_one;
@ViewById
DeliciousTextView sentiment_negative_one;
@ViewById
DeliciousTextView sentiment_neutral_two;
@ViewById
DeliciousTextView sentiment_positive_two;
@ViewById
DeliciousTextView sentiment_negative_two;
@AfterViews
void initialize()
{
mPresidols = new ArrayList<PresidolCandidate>();
loadSentiment();
}
@UiThread
void parseSentiment()
{
if( mPresidols.size() < 0 )
{
return;
}
// prabowo - hatta
PresidolCandidate presidol_prabowo = mPresidols.get(0);
float prabowo_neutral = ((float) presidol_prabowo.getSentiment().getNeutral()) / presidol_prabowo.getSentiment().getCounts() * 100;
float prabowo_positive = ((float) presidol_prabowo.getSentiment().getPositive()) / presidol_prabowo.getSentiment().getCounts() * 100;
float prabowo_negative = ((float) presidol_prabowo.getSentiment().getNegative()) / presidol_prabowo.getSentiment().getCounts() * 100;
sentiment_neutral_one.setText( String.format("%.01f", prabowo_neutral) + "%" );
sentiment_positive_one.setText( String.format("%.01f", prabowo_positive) + "%" );
sentiment_negative_one.setText( String.format("%.01f", prabowo_negative) + "%" );
// prabowo - hatta
PresidolCandidate presidol_jokowi = mPresidols.get(1);
float jokowi_neutral = ((float) presidol_jokowi.getSentiment().getNeutral()) / presidol_jokowi.getSentiment().getCounts() * 100;
float jokowi_positive = ((float) presidol_jokowi.getSentiment().getPositive()) / presidol_jokowi.getSentiment().getCounts() * 100;
float jokowi_negative = ((float) presidol_jokowi.getSentiment().getNegative()) / presidol_jokowi.getSentiment().getCounts() * 100;
sentiment_neutral_two.setText( String.format("%.01f", jokowi_neutral) + "%" );
sentiment_positive_two.setText( String.format("%.01f", jokowi_positive) + "%" );
sentiment_negative_two.setText( String.format("%.01f", jokowi_negative) + "%" );
}
@Background
void loadVotes()
{
}
@Background
void loadSentiment()
{
SooYoungRestClient.get("http://presidol.panjigautama.com/api/1/sentiment", null, new AsyncHttpResponseHandler(){
@Override
public void onFailure(int arg0, Header[] arg1, byte[] arg2,Throwable arg3)
{
super.onFailure(arg0, arg1, arg2, arg3);
}
@Override
public void onSuccess(int statusCode, String content) {
try {
JSONObject object = new JSONObject(content);
int code = object.getInt("code");
JSONObject message = object.getJSONObject("message");
GsonBuilder gsonBuilder = new GsonBuilder();
Gson gson = gsonBuilder.create();
JSONArray presidolsArr = message.getJSONArray("candidates");
for(int i = 0; i < presidolsArr.length(); i++)
{
PresidolCandidate presidol = gson.fromJson(presidolsArr.getString(i), PresidolCandidate.class);
mPresidols.add(presidol);
}
parseSentiment();
} catch (JSONException e) {
e.printStackTrace();
}
}
});
}
}
<file_sep>/MataPemilu/src/com/sooyoung/codeforvote/VoteActivity.java
package com.sooyoung.codeforvote;
import org.androidannotations.annotations.AfterViews;
import org.androidannotations.annotations.EActivity;
import org.androidannotations.annotations.OptionsItem;
import org.androidannotations.annotations.OptionsMenu;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.widget.Toast;
import com.actionbarsherlock.app.ActionBar;
import com.actionbarsherlock.app.SherlockFragmentActivity;
import com.actionbarsherlock.view.MenuItem;
@EActivity(R.layout.activity_vote)
@OptionsMenu(R.menu.about)
public class VoteActivity extends SherlockFragmentActivity
{
ActionBar mActionBar;
FragmentManager mFragmentManager;
@AfterViews
void initialize() {
// wire up fragment
mFragmentManager = getSupportFragmentManager();
mFragmentManager.beginTransaction().replace(R.id.frame_vote, new VoteFragment_()).commit();
// enable back button
mActionBar = getSupportActionBar();
mActionBar.setHomeButtonEnabled(true);
}
@Override
public boolean onOptionsItemSelected(MenuItem menuItem)
{
onBackPressed();
return true;
}
@OptionsItem
void aboutSelected() {
Toast.makeText(this, "About", Toast.LENGTH_SHORT).show();
}
}
<file_sep>/MataPemilu/src/com/sooyoung/codeforvote/model/AchievementHistory.java
package com.sooyoung.codeforvote.model;
import android.content.Context;
import com.orm.SugarRecord;
public class AchievementHistory extends SugarRecord<AchievementHistory> {
Long id;
String candidateId;
String entityName;
String yearAchieved;
String institution;
public AchievementHistory(Context context) {
super(context);
// TODO Auto-generated constructor stub
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getCandidateId() {
return candidateId;
}
public void setCandidateId(String candidateId) {
this.candidateId = candidateId;
}
public String getEntityName() {
return entityName;
}
public void setEntityName(String entityName) {
this.entityName = entityName;
}
public String getYearAchieved() {
return yearAchieved;
}
public void setYearAchieved(String yearAchieved) {
this.yearAchieved = yearAchieved;
}
public String getInstitution() {
return institution;
}
public void setInstitution(String institution) {
this.institution = institution;
}
}
<file_sep>/MataPemilu/src/com/sooyoung/codeforvote/DeliciousTextView.java
package com.sooyoung.codeforvote;
import android.content.Context;
import android.graphics.Typeface;
import android.util.AttributeSet;
import android.widget.TextView;
public class DeliciousTextView extends TextView {
public DeliciousTextView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public DeliciousTextView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
public DeliciousTextView(Context context) {
super(context);
}
@Override
public void setTypeface(Typeface tf, int style) {
super.setTypeface(TypeFaces.getTypeFace(getContext(),
"DELICIOUS-HEAVY.OTF"));
}
}
<file_sep>/MataPemilu/src/com/sooyoung/codeforvote/helper/DatabaseHelper.java
package com.sooyoung.codeforvote.helper;
import java.util.List;
import com.orm.query.Condition;
import com.orm.query.Select;
import com.sooyoung.codeforvote.model.AchievementHistory;
import com.sooyoung.codeforvote.model.Candidate;
import com.sooyoung.codeforvote.model.EducationHistory;
import com.sooyoung.codeforvote.model.WorkHistory;
/**
* Global helper for retrieving data from database
*
* @author aldi
*
*/
public class DatabaseHelper {
/**
* Get candidate list
*
* @return List of all available candidates
*/
public static List<Candidate> getCandidateList() {
return Candidate.listAll(Candidate.class);
}
/**
* Get candidate by specified id
*
* @param id
* Id of the candidate {"jw", "jk", "ps", "hr"}
* @return Candidate object
*/
public static Candidate getCandidateById(String id) {
return (Candidate) Select.from(Candidate.class)
.where(Condition.prop("candidate_id").eq(id)).list().get(0);
}
/**
* Get education history of the specified candidate
*
* @param id
* Id of the candidate {"jw", "jk", "ps", "hr"}
* @return List of education history of the specified candidate
*/
public static List<EducationHistory> getEducationHistoryOfCandidate(
String id) {
return EducationHistory.find(EducationHistory.class, "candidate_id = ?",
id);
}
/**
* Get work history of the specified candidate
*
* @param id
* Id of the candidate {"jw", "jk", "ps", "hr"}
* @return List of work history of the specified candidate
*/
public static List<WorkHistory> getWorkHistoryOfCandidate(String id) {
return WorkHistory.find(WorkHistory.class, "candidate_id = ?", id);
}
/**
* Get achievement history of the specified candidate
*
* @param id
* Id of the candidate {"jw", "jk", "ps", "hr"}
* @return List of achievement history of the specified candidate
*/
public static List<AchievementHistory> getAchievementHistoryOfCandidate(
String id) {
return AchievementHistory.find(AchievementHistory.class,
"candidate_id = ?", id);
}
}
<file_sep>/MataPemilu/src/com/sooyoung/codeforvote/model/PresidolCandidate.java
package com.sooyoung.codeforvote.model;
public class PresidolCandidate {
int id;
String name;
int last_updated;
PresidolSentiment sentiment;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getLast_updated() {
return last_updated;
}
public void setLast_updated(int last_updated) {
this.last_updated = last_updated;
}
public PresidolSentiment getSentiment() {
return sentiment;
}
public void setSentiment(PresidolSentiment sentiment) {
this.sentiment = sentiment;
}
}
| 41e21e173af8f803c2915d085435f343f01d21d9 | [
"Markdown",
"Java"
] | 10 | Markdown | rhapsodixx/Code4VoteChallenge-mobile | acca0a002513085bb9e53a8b3c90a01a42918ec3 | 883544f714c1ef765f0b285f00849be5480a4b91 |
refs/heads/master | <repo_name>E-Schaferer/Kayla-Service-Reviews<file_sep>/database/index.js
/* eslint-disable no-console */
const mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/reviews');
const db = mongoose.connection;
// eslint-disable-next-line no-unused-vars
db.on('error', (err) => console.log(':('));
db.once('open', () => console.log('connected! :)'));
const reviewsSchema = new mongoose.Schema({
id: String,
listingId: Number,
userName: String,
userPicture: String,
date: String,
review: String,
cleanlinessRating: Number,
accuracyRating: Number,
locationRating: Number,
valueRating: Number,
checkInRating: Number,
communicationRating: Number,
});
const Review = mongoose.model('review', reviewsSchema);
const disconnect = () => {
mongoose.disconnect();
};
module.exports = {
Review,
disconnect,
};
<file_sep>/__test__/Review.test.jsx
/* eslint-disable no-undef */
import React from 'react';
import { shallow } from 'enzyme';
import Review from '../client/src/components/Review';
const sampleReview = {
_id: '5eb08ce24302c2b8ef69f2ba',
listingId: 8,
userName: 'Kip',
date: 'July 2019',
review: 'Dolor est possimus eveniet quam dolorem.',
userPicture: 'https://review-services-images-frontend-capstone.s3-us-west-1.amazonaws.com/8-1.jpg',
cleanlinessRating: 2,
accuracyRating: 3.7,
locationRating: 2.6,
valueRating: 2.3,
checkInRating: 1.1,
communicationRating: 3.3,
__v: 0,
};
describe('Render Tests', () => {
test('should render the correct review string', () => {
const wrapper = shallow(<Review review={sampleReview} />);
// expect(wrapper.find('Post').children()).toHaveLength(1);
expect(wrapper.find('.test')).toHaveLength(1);
expect(wrapper.find('.test').text()).toBe('Dolor est possimus eveniet quam dolorem.');
});
});
<file_sep>/client/src/components/App.jsx
/* eslint-disable no-restricted-syntax */
/* eslint-disable no-console */
import React from 'react';
import axios from 'axios';
import styled from 'styled-components';
import ReviewList from './ReviewList';
import Overview from './Overview';
const Title = styled.h2`
color: rgb(72, 72, 72);
font-family: Circular, -apple-system, Roboto, "Helvetica Neue", sans-serif;
font-weight: 500;
padding: 5px;
`;
const Container = styled.div`
display: flex;
width: auto;
flex-direction: column;
margin-left: 4%;
max-width: 696px !important;
margin-left: auto !important;
margin-right: auto !important;
padding-right: 24px !important;
padding-left: 24px !important;
`;
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
reviews: [],
displayedReviews: [],
hasReview: null,
clicked: false,
isSearching: false,
};
this.onSearch = this.onSearch.bind(this);
this.handleClick = this.handleClick.bind(this);
}
componentDidMount() {
let listingId;
const { pathname } = window.location;
if (pathname === '/index.html/') {
listingId = 0;
} else {
listingId = pathname.slice(1, pathname.length - 1);
}
if (Number(listingId) !== 'NaN') {
axios.get(`/reviews/${listingId}`)
.then(({ data }) => {
this.setState({ reviews: data });
})
.catch((err) => console.log(err));
}
}
onSearch({ searchQuery }) {
const searchedReviews = [];
const { reviews, hasReview } = this.state;
// eslint-disable-next-line guard-for-in
for (const currentReview of reviews) {
if (currentReview.review.toLowerCase().includes(searchQuery.toLowerCase())) {
searchedReviews.push(currentReview);
}
}
if (!hasReview) {
this.setState({ hasReview: true });
}
this.setState({ searchQuery, isSearching: true });
if (searchedReviews.length >= 1) {
this.setState({ displayedReviews: searchedReviews });
} else {
this.setState({ hasReview: false });
}
}
handleClick(click) {
const { reviews } = this.state;
const { isSearching } = this.state;
this.setState({
clicked: !click,
displayedReviews: reviews,
hasReview: null,
isSearching: !isSearching,
});
}
render() {
const {
reviews,
displayedReviews,
hasReview,
searchQuery,
clicked,
isSearching,
} = this.state;
return (
<Container>
<Title>Reviews</Title>
<Overview
reviews={reviews}
onSearch={this.onSearch}
searchQuery={searchQuery}
hasReview={hasReview}
length={reviews.length}
handleClick={this.handleClick}
clicked={clicked}
displayedReviews={displayedReviews}
isSearching={isSearching}
/>
<ReviewList
hasReview={hasReview}
reviews={displayedReviews.length === 0 ? reviews : displayedReviews}
/>
</Container>
);
}
}
export default App;
<file_sep>/client/src/style/OverviewStyle.js
/* eslint-disable import/no-extraneous-dependencies */
import styled from 'styled-components';
import { Search } from '@styled-icons/evil/Search';
import { Star } from '@styled-icons/entypo/Star';
export const SearchIcon = styled(Search)`
width: 18px;
// color: rgb(170, 170, 170);
color: rgb(72, 72, 72) !important;
`;
export const StarRating = styled(Star)`
width: 13px;
color: rgb(0, 132, 137);
`;
export const StarContainer = styled.div`
display: flex;
`;
export const OverviewContainer = styled.div`
display: flex;
`;
export const Header = styled.div`
display: flex;
align-items: baseline;
overflow-wrap: break-word !important;
font-family: Circular, -apple-system, BlinkMacSystemFont, Roboto, "Helvetica Neue", sans-serif !important;
font-size: 16px !important;
font-weight: 400 !important;
line-height: 1.44444em !important;
font-color: rgb(72, 72, 72) !important;
margin: 0px !important;
`;
export const NoneFound = styled.div`
display: flex;
justify-content: space-between;
font-family: Circular, -apple-system, BlinkMacSystemFont, Roboto, "Helvetica Neue", sans-serif !important;
overflow-wrap: break-word !important;
font-size: 12px !important;
font-weight: 300 !important;
line-height: 1.28571em !important;
color: rgb(72, 72, 72) !important;
margin: 0px !important;
`;
export const SomeFound = styled.div`
display: flex;
justify-content: space-between;
font-family: Circular, -apple-system, BlinkMacSystemFont, Roboto, "Helvetica Neue", sans-serif !important;
overflow-wrap: break-word !important;
font-size: 12px !important;
font-weight: 300 !important;
line-height: 1.28571em !important;
color: rgb(72, 72, 72) !important;
margin: 0px !important;
`;
export const Word = styled.span`
font-size: 13px !important;
font-weight: 400 !important;
padding-left: 4px;
`;
export const GoBack = styled.a`
color: #008489 ;
font-family: var(--font-font_family, Circular,-apple-system,BlinkMacSystemFont,Roboto,Helvetica Neue,sans-serif) !important;
cursor: pointer;
}
`;
export const Wrapper = styled.div`
display: flex;
flex-wrap: wrap;
`;
export const Container = styled.div`
display: flex;
`;
// RATING
export const RatingContainer = styled.div`
display:flex;
flex-direction: column;
margin: 0px;
`;
export const TotalRating = styled.div`
padding: 5px;
font-weight: 700 !important;
`;
export const AmountofReviews = styled.div`
padding: 5px;
font-weight: 700 !important;
`;
export const VerticalLine = styled.div`
height: 13px !important;
border-right: 1px solid rgb(235, 235, 235) !important;
`;
export const LineBreak = styled.div`
border-bottom-width: 1px !important;
border-bottom-color: #EBEBEB !important;
border-bottom-style: solid !important;
margin-top: 12px;
margin-bottom: 10px;
}
`;
// SEARCH
export const SearchInnerWrapper = styled.div`
display: flex;
align-items: end;
`;
export const SearchReviews = styled.input`
margin-bottom: 8px !important;
font-size: 12px
line-height: 22px !important;
height: 1.2rem;
width: 100%;
font-weight: 400;
color: rgb(72, 72, 72) !important;
border-width: 1px !important;
border-style: solid !important;
border-color: rgb(235, 235, 235) !important;
border-radius: 4px !important;
outline: none;
padding: 4px;
:focus {
border-width: 1.5px;
border-color: rgb(0, 132, 137) !important;
}
`;
export const SearchButton = styled.button`
background: none;
border: none;
padding-left: 5px;
padding-right: 5px;
display: inline-block;
text-align: center;
align-items: flex-start;
height: 27px;
margin-left: -27px;
`;
export const SearchForm = styled.form`
border-width: 1px !important;
border-style: initial !important;
border-color: #EBEBEB !important;
width: 100%;
padding: 5px;
margin: 0em;
display: flex;
flex-wrap: wrap;
justify-content: flex-end;
`;
// PROGRESS BAR
export const ProgressContainer = styled.div`
height: 5px;
width: 100px;
position: relative;
`;
export const BaseBox = styled.div`
height: 103%;
position: absolute;
left: 0;
top: 0;
border-radius: 3px;
transition: width 1s ease-in-out;
width: 50px;
`;
export const Background = styled(BaseBox)`
background: #D8D8D8;
width: 100%;
height:103%
`;
export const ProgressStatus = styled(BaseBox)`
background: rgb(0, 132, 137);
width: ${({ percent }) => percent}%;
`;
// TABLE
export const Table6Cols = styled.div`
// display: flex;
// flex-wrap: wrap;
// font-family: Circular,-apple-system,BlinkMacSystemFont,Roboto,Helvetica Neue,sans-serif;
// margin: 0 0 3em 0;
// padding: 0;
width: 117%;
display: flex;
flex-direction: column;
display: inline-flex;
flex-flow: wrap;
// margin-right: -100px;
align-items: center;
`;
export const RtableCell = styled.div`
box-sizing: border-box;
flex-grow: 1;
font-family: Circular,-apple-system,BlinkMacSystemFont,Roboto,Helvetica Neue,sans-serif;
color: rgb(72, 72, 72);
width: 100%; // default to full width
padding: 0.8em 0.2em 1.2em 0.1em;
overflow: hidden; // Or flex might break
list-style: none;
border: solid @bw white;
font-size: 12px;
width: 16.6%;
display: inline-flex;
`;
<file_sep>/client/src/components/Review.jsx
/* eslint-disable react/prop-types */
import React from 'react';
import {
PostContainer, ReviewHeaderContainer, Picture, NameandDateContainer, User, Date, Post, LineBreak,
// eslint-disable-next-line import/extensions
} from '../style/ReviewStyle.js';
class Review extends React.Component {
constructor(props) {
super(props);
this.state = {};
}
render() {
const { review } = this.props;
return (
<PostContainer>
<ReviewHeaderContainer>
<Picture alt="user" src={review.userPicture} />
<NameandDateContainer>
<User>{ review.userName }</User>
<Date>{ review.date }</Date>
</NameandDateContainer>
</ReviewHeaderContainer>
<Post className="test">{ review.review }</Post>
<LineBreak> </LineBreak>
</PostContainer>
);
}
}
export default Review;
<file_sep>/seeder.js
/* eslint-disable no-console */
const faker = require('faker');
// const fs = require('fs');
// const axios = require('axios');
const db = require('./database');
// write to file figure out file format csv
const generateReviews = () => {
let count = 0;
for (let i = 0; i < 100; i += 1) {
const min = 3;
const max = 7;
const rand = Math.floor(Math.random() * (max - min) + min);
for (let j = 0; j <= rand; j += 1) {
const user = faker.name.firstName();
const year = faker.random.arrayElement(['2013', '2014', '2015', '2016', '2017', '2018', '2019', '2020']);
const dateStr = `${faker.date.month()} ${year}`;
const sentence = faker.lorem.sentence();
const paragraph = faker.lorem.paragraph();
const randomReview = faker.random.arrayElement([sentence, paragraph]);
const rating1 = faker.finance.amount(2, 5, 1);
const rating2 = faker.finance.amount(3, 5, 1);
const rating3 = faker.finance.amount(2, 5, 1);
const rating4 = faker.finance.amount(2, 5, 1);
const rating5 = faker.finance.amount(1, 5, 1);
const rating6 = faker.finance.amount(1, 5, 1);
const newReview = new db.Review({
listingId: i,
userName: user,
date: dateStr,
review: randomReview,
userPicture: `https://review-services-images-frontend-capstone.s3-us-west-1.amazonaws.com/${i}-${j}.jpg`,
cleanlinessRating: rating1,
accuracyRating: rating2,
locationRating: rating3,
valueRating: rating4,
checkInRating: rating5,
communicationRating: rating6,
});
newReview.save()
// eslint-disable-next-line no-loop-func
.then(() => {
if (count === 99) db.disconnect();
})
.catch((err) => console.log('err: ', err))
// eslint-disable-next-line no-loop-func
.finally(() => {
count += 1;
if (count === 99) db.disconnect();
});
}
}
};
generateReviews();
// write to file instead of pushing to an array
// console.log(faker.random.number({min:1, max:5.0}));
// eslint-disable-next-line spaced-comment
/******** gets 100 random images and downloads them *********/
// const getImages = (n) => {
// axios({
// method: 'get',
// url: 'https://loremflickr.com/320/240/dog,person',
// responseType: 'stream',
// })
// .then(({ data }) => {
// data.pipe(fs.createWriteStream(`../../images/${n}.jpg`));
// })
// .catch((err) => console.log(err));
// };
// const downloadImages = () => {
// let ar = [];
// for (let i = 0; i < 100; i += 1) {
// for(var j = 0; j < 7; j += 1) {
// ar.push(`${i}-${j}`)
// }
// }
// // console.log(ar)
// for(let k = 0; k < ar.length; k++) {
// if(ar[k] !== '99-6'){
// getImages(ar[k]);
// // console.log(ar[k])
// }
// }
// };
// downloadImages();
<file_sep>/client/src/components/Rating.jsx
/* eslint-disable import/extensions */
/* eslint-disable react/prop-types */
import React from 'react';
import {
ProgressContainer,
Background,
ProgressStatus,
Table6Cols,
RtableCell,
} from '../style/OverviewStyle.js';
class Rating extends React.Component {
constructor(props) {
super(props);
this.state = {};
}
render() {
const {
avgCheckin,
avgCleanliness,
avgCommunication,
avgLocation,
avgAccuracy,
avgValue,
} = this.props;
// width*review/5
const checkinPercent = (100 * avgCheckin) / 5;
const cleanlinessPercent = (100 * avgCleanliness) / 5;
const communicationPercent = (100 * avgCommunication) / 5;
const accuracyPercent = (100 * avgAccuracy) / 5;
const valuePercent = (100 * avgValue) / 5;
const locationPercent = (100 * avgLocation) / 5;
return (
<Table6Cols>
<RtableCell>
Checkin
</RtableCell>
<RtableCell>
<ProgressContainer>
<Background />
<ProgressStatus percent={checkinPercent} />
</ProgressContainer>
</RtableCell>
<RtableCell>
{avgCheckin.toFixed(1)}
</RtableCell>
<RtableCell>
Cleanliness
</RtableCell>
<RtableCell>
<ProgressContainer>
<Background />
<ProgressStatus percent={cleanlinessPercent} />
</ProgressContainer>
</RtableCell>
<RtableCell>
{avgCleanliness.toFixed(1)}
</RtableCell>
<RtableCell>
Communication
</RtableCell>
<RtableCell>
<ProgressContainer>
<Background />
<ProgressStatus percent={communicationPercent} />
</ProgressContainer>
</RtableCell>
<RtableCell>
{avgCommunication.toFixed(1)}
</RtableCell>
<RtableCell>
Accuracy
</RtableCell>
<RtableCell>
<ProgressContainer>
<Background />
<ProgressStatus percent={accuracyPercent} />
</ProgressContainer>
</RtableCell>
<RtableCell>
{avgAccuracy.toFixed(1)}
</RtableCell>
<RtableCell>
Value
</RtableCell>
<RtableCell>
<ProgressContainer>
<Background />
<ProgressStatus percent={valuePercent} />
</ProgressContainer>
</RtableCell>
<RtableCell>
{avgValue.toFixed(1)}
</RtableCell>
<RtableCell>
Location
</RtableCell>
<RtableCell>
<ProgressContainer>
<Background />
<ProgressStatus percent={locationPercent} />
</ProgressContainer>
</RtableCell>
<RtableCell>
{avgLocation.toFixed(1)}
</RtableCell>
</Table6Cols>
);
}
}
export default Rating;
<file_sep>/client/src/components/Overview.jsx
/* eslint-disable react/jsx-one-expression-per-line */
/* eslint-disable react/prop-types */
/* eslint-disable import/extensions */
import React from 'react';
import Search from './Search';
import RatingLevels from './RatingLevels';
// eslint-disable-next-line import/extensions
import {
StarRating,
StarContainer,
Header,
TotalRating,
AmountofReviews,
LineBreak,
VerticalLine,
NoneFound,
SomeFound,
Word,
GoBack,
Wrapper,
} from '../style/OverviewStyle.js';
class Overview extends React.Component {
constructor(props) {
super(props);
this.state = {};
}
render() {
const {
reviews,
onSearch,
isSearching,
searchQuery,
hasReview,
handleClick,
clicked,
displayedReviews,
} = this.props;
let avgCheckin = 0;
let avgCleanliness = 0;
let avgLocation = 0;
let avgAccuracy = 0;
let avgValue = 0;
let avgCommunication = 0;
reviews.forEach((ele) => {
avgCheckin += ele.checkInRating;
avgValue += ele.valueRating;
avgCommunication += ele.communicationRating;
avgLocation += ele.locationRating;
avgCleanliness += ele.cleanlinessRating;
avgAccuracy += ele.accuracyRating;
});
avgCheckin /= reviews.length;
avgValue /= reviews.length;
avgCommunication /= reviews.length;
avgLocation /= reviews.length;
avgCleanliness /= reviews.length;
avgAccuracy /= reviews.length;
reviews.averageRatings = {
averageCheckin: avgCheckin,
averageValue: avgValue,
averageCommunication: avgCommunication,
averageLocation: avgLocation,
averageCleanliness: avgCleanliness,
averageAccuracy: avgAccuracy,
};
const total = (avgCheckin + avgValue
+ avgCommunication + avgLocation + avgCleanliness + avgAccuracy) / 6;
reviews.ratingAverage = total;
let guests = 'guests';
let have = 'have';
if (displayedReviews.length <= 1) {
guests = 'guest';
have = 'has';
}
const noReviews = (
<NoneFound>
<Wrapper>
None of our guests have mentioned
<Word>{`"${searchQuery}"`}</Word>
</Wrapper>
<GoBack className="back-btn" onClick={() => handleClick(clicked)}>Back to all reviews</GoBack>
</NoneFound>
);
const someReviews = (
<div>
<SomeFound className="some-found">
<Wrapper>
{`${displayedReviews.length}
${guests} ${have} mentioned `}
<Word>{`"${searchQuery}"`}</Word>
</Wrapper>
<GoBack className="back-btn" onClick={() => handleClick(clicked)}>Back to all reviews</GoBack>
</SomeFound>
<LineBreak> </LineBreak>
</div>
);
const searchResults = hasReview === false ? noReviews : someReviews;
return (
<div>
<Header>
<StarContainer>
<StarRating />
</StarContainer>
<TotalRating>{total.toFixed(1)}</TotalRating>
<VerticalLine> </VerticalLine>
<AmountofReviews>
{reviews.length}
</AmountofReviews>
reviews
<Search onSearch={onSearch} />
</Header>
<LineBreak> </LineBreak>
{/* if clicked is true then render ratinglevels */}
{isSearching ? searchResults : (
<RatingLevels
avgCheckin={avgCheckin}
avgCleanliness={avgCleanliness}
avgCommunication={avgCommunication}
avgLocation={avgLocation}
avgAccuracy={avgAccuracy}
avgValue={avgValue}
/>
)}
</div>
);
}
}
export default Overview;
<file_sep>/server/index.js
/* eslint-disable no-console */
const express = require('express');
const path = require('path');
const db = require('../database');
const app = express();
const PORT = 4007;
app.use(express.json());
app.use('/:id', express.static(path.join(__dirname, '..', 'public')));
app.get('/', (req, res) => {
res.redirect(301, `http://localhost:${PORT}/index.html`);
});
app.get('/reviews/:listingId', (req, res) => {
db.Review.find({ listingId: req.params.listingId })
.then((data) => {
res.send(data);
})
.catch((err) => res.status(500).send(err));
});
app.listen(PORT, () => console.log(`server running on port: ${PORT}`));
<file_sep>/__test__/Overview.test.jsx
/* eslint-disable no-undef */
import React from 'react';
import { shallow, mount } from 'enzyme';
import App from '../client/src/components/App';
import Overview from '../client/src/components/Overview';
import RatingLevels from '../client/src/components/RatingLevels';
import { GoBack } from '../client/src/style/OverviewStyle';
import reviews from './mockReviews';
const displayedReviews = [];
const mockEvent = (str) => {
return {
target: {
name: 'searchQuery',
value: str,
},
};
};
describe('<Overview/>', () => {
it('should render 1 <RatingLevels /> element on the screen', () => {
const wrapper = shallow(<Overview reviews={reviews} displayedReviews={displayedReviews} />);
expect(wrapper.find(RatingLevels)).toHaveLength(1);
});
it('should render 2 reviews with the word that was searched: la', () => {
const wrapper = mount(<App />);
const searchQuery = 'la';
wrapper.setState({
reviews,
displayedReviews,
hasReview: null,
clicked: false,
isSearching: false,
});
wrapper.find('.search-text').last().simulate('change', mockEvent(searchQuery));
wrapper.find('.search-btn').last().simulate('click');
expect(wrapper.state('displayedReviews').length).toBe(2);
});
it('should render no reviews with the word that was searched: wonil', () => {
const wrapper = mount(<App />);
const searchQuery = 'wonil';
wrapper.setState({
reviews,
displayedReviews,
hasReview: null,
clicked: false,
isSearching: false,
});
wrapper.find('.search-text').last().simulate('change', mockEvent(searchQuery));
wrapper.find('.search-btn').last().simulate('click');
expect(wrapper.state('displayedReviews').length).toBe(0);
expect(wrapper.state('hasReview')).toBe(false);
});
it('should render main review page when goBack button is clicked', () => {
const wrapper = mount(<App />);
const searchQuery = 'Voluptatum';
wrapper.setState({
reviews,
displayedReviews,
hasReview: null,
clicked: false,
isSearching: false,
});
wrapper.find('.search-text').last().simulate('change', mockEvent(searchQuery));
wrapper.find('.search-btn').last().simulate('click');
expect(wrapper.state('displayedReviews').length).toBe(1);
expect(wrapper.state('isSearching')).toBe(true);
wrapper.find(GoBack).simulate('click');
expect(wrapper.state('isSearching')).toBe(false);
});
});
<file_sep>/client/src/components/ReviewList.jsx
/* eslint-disable no-underscore-dangle */
/* eslint-disable import/extensions */
/* eslint-disable react/prop-types */
import React from 'react';
import Review from './Review';
import { ReviewsContainer } from '../style/ReviewStyle.js';
class ReviewList extends React.Component {
constructor(props) {
super(props);
this.state = {};
}
render() {
const {
hasReview,
reviews,
} = this.props;
if (hasReview !== false) {
return (
<ReviewsContainer>
{
reviews.map((review) => <Review key={review._id} review={review} />)
}
</ReviewsContainer>
);
}
return (<div />);
}
}
export default ReviewList;
<file_sep>/__test__/mockReviews.js
module.exports = [
{
listingId: 10,
userName: 'Otho',
date: 'October 2020',
review: 'Fugiat est ad at rerum ab. Possimus beatae suscipit sed beatae est debitis rem ex. Quibusdam neque dicta qui ut impedit et temporibus vitae. Nihil autem aliquid dolores consectetur tenetur.',
userPicture: 'https://review-services-images-frontend-capstone.s3-us-west-1.amazonaws.com/10-0.jpg',
cleanlinessRating: 5,
accuracyRating: 4.2,
locationRating: 4.3,
valueRating: 5,
checkInRating: 1,
communicationRating: 2.7,
},
{
listingId: 10,
userName: 'Zena',
date: 'May 2020',
review: 'Iure ipsam laboriosam.',
userPicture: 'https://review-services-images-frontend-capstone.s3-us-west-1.amazonaws.com/10-1.jpg',
cleanlinessRating: 3.2,
accuracyRating: 4.5,
locationRating: 4.1,
valueRating: 2.3,
checkInRating: 4.5,
communicationRating: 2,
},
{
listingId: 10,
userName: 'Coralie',
date: 'May 2017',
review: 'Nam sunt odit maiores earum et occaecati.',
userPicture: 'https://review-services-images-frontend-capstone.s3-us-west-1.amazonaws.com/10-2.jpg',
cleanlinessRating: 2.7,
accuracyRating: 4.6,
locationRating: 3.5,
valueRating: 2.7,
checkInRating: 2.1,
communicationRating: 3.4,
},
{
listingId: 10,
userName: 'Viva',
date: 'March 2019',
review: 'Libero dolores vel corrupti autem.',
userPicture: 'https://review-services-images-frontend-capstone.s3-us-west-1.amazonaws.com/10-3.jpg',
cleanlinessRating: 4.7,
accuracyRating: 4.7,
locationRating: 4.3,
valueRating: 3,
checkInRating: 1.8,
communicationRating: 1.9,
},
{
listingId: 10,
userName: 'Melany',
date: 'September 2017',
review: 'Molestiae ullam omnis ad consequatur voluptatem rerum fugiat ut.',
userPicture: 'https://review-services-images-frontend-capstone.s3-us-west-1.amazonaws.com/10-4.jpg',
cleanlinessRating: 4.4,
accuracyRating: 5,
locationRating: 2.4,
valueRating: 4.9,
checkInRating: 3.8,
communicationRating: 4.2,
},
{
listingId: 10,
userName: 'Carrie',
date: 'June 2020',
review: 'Possimus et dolor. Voluptatum ipsum delectus libero in officia. Recusandae sed repudiandae repudiandae dolor beatae. Dolorum nesciunt voluptas iste.',
userPicture: 'https://review-services-images-frontend-capstone.s3-us-west-1.amazonaws.com/10-5.jpg',
cleanlinessRating: 5,
accuracyRating: 3.1,
locationRating: 3.4,
valueRating: 3,
checkInRating: 3.8,
communicationRating: 2.3,
},
{
listingId: 10,
userName: 'Britney',
date: 'May 2018',
review: 'Voluptatem fuga et officia.',
userPicture: 'https://review-services-images-frontend-capstone.s3-us-west-1.amazonaws.com/10-6.jpg',
cleanlinessRating: 2.7,
accuracyRating: 4.5,
locationRating: 2.4,
valueRating: 2.8,
checkInRating: 2.3,
communicationRating: 3.3,
},
];
<file_sep>/README.md
# Kayla-Service-Reviews
> Project Description
Hack Reactor Front-End Capstone
UI clone of Airbnb Reviews module
## Getting Started
npm install
## Running the tests
npm run test<file_sep>/__test__/RatingLevels.test.jsx
import React from 'react';
import { shallow } from 'enzyme';
import RatingLevels from '../client/src/components/RatingLevels';
import Rating from '../client/src/components/Rating';
const avgCheckin = 2.8;
const avgCleanliness = 1.9;
const avgCommunication = 3.5;
const avgLocation = 3.7;
const avgAccuracy = 3.0;
const avgValue = 1.9;
it('should render 1 Rating component on the screen', () => {
const wrapper = shallow(
<RatingLevels
avgCheckin={avgCheckin}
avgCleanliness={avgCleanliness}
avgCommunication={avgCommunication}
avgLocation={avgLocation}
avgAccuracy={avgAccuracy}
avgValue={avgValue}
/>,
);
expect(wrapper.find(Rating)).toHaveLength(1);
});
<file_sep>/client/src/components/Search.jsx
/* eslint-disable react/prop-types */
/* eslint-disable import/extensions */
import React from 'react';
import {
SearchIcon,
SearchForm,
SearchReviews,
SearchButton,
SearchInnerWrapper,
} from '../style/OverviewStyle.js';
class Search extends React.Component {
constructor(props) {
super(props);
this.state = {
searchQuery: '',
};
this.handleChange = this.handleChange.bind(this);
this.handleSearch = this.handleSearch.bind(this);
this.intializeState = this.intializeState.bind(this);
}
handleChange({ target }) {
// eslint-disable-next-line no-console
const { value, name } = target;
this.setState({ [name]: value });
}
handleSearch(e) {
const { onSearch } = this.props;
e.preventDefault();
onSearch(this.state);
this.intializeState();
}
intializeState() {
this.setState({
searchQuery: '',
});
}
render() {
const { searchQuery } = this.state;
return (
<SearchForm>
<SearchInnerWrapper>
<SearchReviews className="search-text"
name="searchQuery"
value={searchQuery}
type="text"
placeholder="Search reviews"
onChange={this.handleChange}
/>
<SearchButton className="search-btn" onClick={this.handleSearch}>
<SearchIcon />
</SearchButton>
</SearchInnerWrapper>
</SearchForm>
);
}
}
export default Search;
<file_sep>/client/src/components/RatingLevels.jsx
/* eslint-disable import/extensions */
/* eslint-disable no-underscore-dangle */
/* eslint-disable react/prop-types */
import React from 'react';
import Rating from './Rating';
import { RatingContainer } from '../style/OverviewStyle.js';
class RatingLevels extends React.Component {
constructor(props) {
super(props);
this.state = {};
}
render() {
const {
avgCheckin,
avgCleanliness,
avgCommunication,
avgLocation,
avgAccuracy,
avgValue,
} = this.props;
return (
<RatingContainer>
<Rating
avgCheckin={avgCheckin}
avgCleanliness={avgCleanliness}
avgCommunication={avgCommunication}
avgLocation={avgLocation}
avgAccuracy={avgAccuracy}
avgValue={avgValue}
/>
</RatingContainer>
);
}
}
export default RatingLevels;
| cc3bb099e3b4b68b6febab8c7c890a88baba82a9 | [
"JavaScript",
"Markdown"
] | 16 | JavaScript | E-Schaferer/Kayla-Service-Reviews | 19a98977edeaa6ad35c75f85be3530efe316b2ff | 649ea32b60b9380175ed36b6e54e9de327c388ce |
refs/heads/master | <file_sep>from django.http import HttpResponse
from django.shortcuts import render
from rest_framework import generics, filters
# Create your views here.
from tickets.models import Ticket
from tickets.serializers import TicketSerializer
# def about(request):
# return HttpResponse('This is Ticket Management System for AM/NS Employees')
class SearchTicketFilter(filters.SearchFilter):
def get_search_fields(self, view, request):
return request.GET.getlist('search_fields', [])
class ListTicketsView(generics.ListAPIView):
filter_backends = (SearchTicketFilter,)
queryset = Ticket.objects.all()
serializer_class = TicketSerializer
class CreateTicketView(generics.CreateAPIView):
queryset = Ticket.objects.all()
serializer_class = TicketSerializer
class UpdateTicketView(generics.UpdateAPIView):
queryset = Ticket.objects.all()
serializer_class = TicketSerializer
class DeleteTicketView(generics.DestroyAPIView):
queryset = Ticket.objects.all()
serializer_class = TicketSerializer
<file_sep># Generated by Django 3.2.5 on 2021-07-11 16:31
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Ticket',
fields=[
('ticketId', models.IntegerField(primary_key=True, serialize=False)),
('subject', models.CharField(max_length=500)),
('description', models.CharField(max_length=2000)),
('status', models.CharField(max_length=30)),
('priority', models.CharField(max_length=30)),
('createdOn', models.DateTimeField()),
('employeeId', models.CharField(max_length=30)),
],
),
]
<file_sep>from django.db import models
# Create your models here.
class Ticket(models.Model):
STATUSES = (
("New", "New"),
("Assigned", "Assigned"),
("Work in Progress", "Work in Progress"),
("Completed", "Completed"),
("Closed", "Closed"),
("Re-Opened", "Re-Opened")
)
PRIORITIES = (
("Low", "Low"),
("Medium", "Medium"),
("High", "High")
)
EMPLOYEES = (
("Ajay", "Ajay"),
("Akshay", "Akshay"),
("Amir", "Amir")
)
ticketId = models.IntegerField(primary_key=True)
subject = models.CharField(max_length=500, null=False)
description = models.CharField(max_length=2000, null=False)
status = models.CharField(max_length=50, choices=STATUSES, null=False)
priority = models.CharField(max_length=50, choices=PRIORITIES, null=False)
createdOn = models.DateTimeField(null=False)
employeeName = models.CharField(max_length=50, choices=EMPLOYEES, null=False)
def __str__(self):
return "{} - {} - {} - {} - {} - {} - {}" \
.format(self.ticketId, self.subject, self.description, self.status, self.priority, self.createdOn,
self.employeeName)
<file_sep># Generated by Django 3.2.5 on 2021-07-11 17:54
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('tickets', '0001_initial'),
]
operations = [
migrations.RemoveField(
model_name='ticket',
name='employeeId',
),
migrations.AddField(
model_name='ticket',
name='employeeName',
field=models.CharField(choices=[('Ajay', 'Ajay'), ('Akshay', 'Akshay'), ('Amir', 'Amir')], default=0, max_length=50),
preserve_default=False,
),
migrations.AlterField(
model_name='ticket',
name='priority',
field=models.CharField(choices=[('Low', 'Low'), ('Medium', 'Medium'), ('High', 'High')], max_length=50),
),
migrations.AlterField(
model_name='ticket',
name='status',
field=models.CharField(choices=[('New', 'New'), ('Assigned', 'Assigned'), ('Work in Progress', 'Work in Progress'), ('Completed', 'Completed'), ('Closed', 'Closed'), ('Re-Opened', 'Re-Opened')], max_length=50),
),
]
| f0b51c97409a2ac29621cfbe46dd9ba601170830 | [
"Python"
] | 4 | Python | NSaudagar/Ticket-Management-System---Python-DJango | 16d3666ab6b759f9624a50193625b9706381b69a | cd3b9182a8a64470195b0b104a8e567f687ff822 |
refs/heads/master | <file_sep>package com.teslenko;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
/**
* Created by roman on 26.02.16.
*/
public class VolatilityCalculator {
/**
* Calculate volatility for a set period of days
* @param ratesData list of ratesData data
* @param period number of days from current entry to calculate volatility. Must be >= 0
* @param useHiLowRange if true using price range between Hi and Low,
* in other case using Open to Close range
* @param offsetFromEnd amount of entries from the last which won't be
* accounted during calculation. Must be >=0
* @return volatility index for the set period of days
*/
public double calculateVolatility(RatesData ratesData, int period, boolean useHiLowRange, int offsetFromEnd) {
double result = 0.0d;
if (period >= 0 & offsetFromEnd >= 0) {
int startDateIndex = ratesData.size() - offsetFromEnd - period;
for (int i = startDateIndex; i < ratesData.size() - offsetFromEnd; i++) {
Rate currentQuote = ratesData.get(i);
if (useHiLowRange) {
result += currentQuote.getRelativeHiLowDiff();
} else {
result += currentQuote.getRelativeOpenCloseDiff();
}
}
}
return result;
}
/**
* Calculate volatility of all entries in the list of data
* @param ratesData list of ratesData data
* @param useHiLowRange if true using price range between Hi and Low,
* in other case using Open to Close range
* @param offsetFromEnd amount of entries from the last which won't be
* accounted during calculation. Must be >=0
* @return volatility index for the set period of days
*/
public double calculateVolatility(RatesData ratesData, boolean useHiLowRange, int offsetFromEnd) {
return calculateVolatility(ratesData, ratesData.size() - 1, useHiLowRange, offsetFromEnd);
}
/**
* Calculate volatility for the entire period from specified date
* @param ratesData list of ratesData data
* @param startDate representing starting date in format: yyyy.MM.dd-HH:mm
* @param useHiLowRange if true using price range between Hi and Low,
* in other case using Open to Close range
* @param offsetFromEnd amount of entries from the last which won't be
* accounted during calculation. Must be >=0
* @return volatility index for the set period of days
*/
public double calculateVolatility(RatesData ratesData, String startDate, boolean useHiLowRange, int offsetFromEnd) throws ParseException {
int startIndex = getIndexByDate(ratesData, startDate);
return calculateVolatility(ratesData, ratesData.size() - 1 - startIndex, useHiLowRange, offsetFromEnd);
}
private int getIndexByDate(RatesData ratesData, String start) throws ParseException {
int index = -1;
Iterator<Rate> iter = ratesData.iterator();
while (iter.hasNext()) {
index++;
Date startDate = new SimpleDateFormat("yyyy.MM.dd-HH:mm", Locale.ENGLISH).parse(start);
Date currentDate = ratesData.get(index).getDate();
if (startDate.compareTo(currentDate) == 0) {
break;
}
}
System.out.println(index);
return index;
}
}
<file_sep>package com.teslenko;
import java.io.IOException;
/**
* Created by roman on 26.02.16.
*/
public class Test01 {
public static void main(String[] args) {
RatesData ratesData = new RatesData("/media/data/trading/BTCUSD1440.csv");
int period = 100;
int offsetFromEnd = 0;
double averageVolatility = ratesData.averageVolatility(period, true, offsetFromEnd);
double averageTrueRange = ratesData.averageVolatility(period, false, offsetFromEnd);
double averageTailsRange = averageVolatility - averageTrueRange;
double averageTrueRangeShare = averageTrueRange / averageVolatility * 100;
double averageTailsRangeShare = averageTailsRange / averageVolatility *100;
double raiseToFallRatio = ratesData.raiseToFallRatio(period, offsetFromEnd);
// double averageUpToDownTailsRatio = ratesData.averageUpToDownTailsRatio(period, offsetFromEnd);
System.out.println("Average volatility: " + averageVolatility + '%');
System.out.println("True range: " + averageTrueRangeShare + '%');
System.out.println("Tails range: " + averageTailsRangeShare + '%');
System.out.println("Raise to fall ratio: " + raiseToFallRatio + '%');
}
}
<file_sep>package com.teslenko;
import java.io.File;
import java.io.IOException;
import java.util.*;
import java.lang.String;
/**
* Created by roman on 26.02.16.
*/
public class Test00 {
public static void main(String[] args) throws IOException {
// RatesReader ratesReader = new RatesBufferedReader();
// List<Rate> list = ratesReader.readData(new File("/media/data/trading/BTCUSD1440.csv"));
// VolatilityCalculator vCalc = new VolatilityCalculator();
// //volatility for last 100 days
// int period = 100;
// int unaccountable = 0;
// double genAverageVolat = vCalc.calculateAverageVolatility(list, period, true, unaccountable);
// System.out.println("Average volatility: " + genAverageVolat);
// List<Rate> less50per = new ArrayList<Rate>();
// List<Rate> from50to100per = new ArrayList<Rate>();
// List<Rate> from100to150per = new ArrayList<Rate>();
// List<Rate> from150to200per = new ArrayList<Rate>();
// List<Rate> more200per = new ArrayList<Rate>();
// for (int i = list.size() - unaccountable - period; i < list.size() - unaccountable; i++) {
// double volatil = list.get(i).getRelativeHiLowDiff();
// if (volatil < genAverageVolat * 0.5) {
// less50per.add(list.get(i));
// } else if (volatil >= genAverageVolat * 0.5 && volatil < genAverageVolat) {
// from50to100per.add(list.get(i));
// } else if (volatil >= genAverageVolat && volatil < genAverageVolat * 1.5) {
// from100to150per.add(list.get(i));
// } else if (volatil >= genAverageVolat * 1.5 && volatil < genAverageVolat * 2) {
// from150to200per.add(list.get(i));
// } else if (volatil >= genAverageVolat * 2) {
// more200per.add(list.get(i));
// }
// }
// System.out.println("From 0% to 50%: " + less50per.size() + " entries. Or " + less50per.size()*1.0d/period*100 + '%');
// System.out.println("From 50% to 100%: " + from50to100per.size() + " entries. Or " + from50to100per.size()*1.0d/period*100 + '%');
// System.out.println("From 100% to 150%: " + from100to150per.size() + " entries. Or " + from100to150per.size()*1.0d/period*100 + '%');
// System.out.println("From 150% to 200%: " + from150to200per.size() + " entries. Or " + from150to200per.size()*1.0d/period*100 + '%');
// System.out.println("More than 200%: " + more200per.size() + " entries. Or " + more200per.size()*1.0d/period*100 + '%');
/*double averageOpenCloseShare = 0.0d;
for (Rate item : more200per) {
double currentOpenCloseShare = item.getAbsoluteOpenCloseDiff() / item.getAbsoluteHiLowDiff() * 100;
averageOpenCloseShare += currentOpenCloseShare;
}
averageOpenCloseShare /= more200per.size();
System.out.println("Average share OpenClose in candle: " + averageOpenCloseShare + '%');*/
// double RelativeFalseTailSizeSum = 0.0d;
// for (Rate item : more200per) {
// RelativeFalseTailSizeSum += item.getRelativeFalseTailSize();
// }
// double averageFalseTailRelativeSize = RelativeFalseTailSizeSum / more200per.size();
// System.out.println("Average false tail size is: " + averageFalseTailRelativeSize + '%');
}
}
| 8c3638635f5edbd2a75e04f4fa3f2381b014ea2c | [
"Java"
] | 3 | Java | romanteslenko/btc-analysis | b055a3e7ab6df0d2255dc54d32e81346917b438a | 1b325810f6276702416e024080ad1e757cbd5029 |
refs/heads/master | <file_sep>import { Component, OnInit } from '@angular/core';
import { Http ,Response,RequestOptions,Headers} from '@angular/http';
import {Observable} from 'rxjs/Observable';
import { catchError, map, tap } from 'rxjs/operators';
import 'rxjs/add/operator/map';
@Component({
selector: 'app-cart',
templateUrl: './cart.component.html',
styleUrls: ['./cart.component.css']
})
export class CartComponent implements OnInit {
private items = [
{
productId: "kkdProd1001",
imageUrl: "https://fhjghd/djhkd/hf",
quantity: 5,
price: 20,
productName: "Tomato",
productDesc: "fresh tomatoes"
},
{
productId: "kkdProd103",
imageUrl: "https://fhjghd/djhkd/hf",
quantity: 78,
price: 45,
productName: "Potato",
productDesc: "fresh Potato"
}
];
pushItems=[
{
kkkdFarmID: "kkd009",
farmerName: "Ram",
productId: "12",
productName: "bhindi",
productPrice: 20,
avgRating: 4.5,
quantity: 2
},
{
kkkdFarmID: "kkd0044769",
farmerName: "Ram222",
productId: "122",
roductName: "bhind334i",
productPrice: 20,
avgRating: 4.5,
quantity: 2
},
{
kkkdFarmID: "kkd00449",
farmerName: "Ram222At",
productId: "12e2",
productName: "bhind3ddffr34i",
productPrice: 20,
avgRating: 4.5,
quantity: 2
}
];
x: number;
constructor(
private dataService: DataService,
private cartService: CartServiceService
) {}
//this.x=this.items.reduce(function(sum,cartItem){ return sum+cartItem.price*cartItem.quantity},0);
ngOnInit() {
//this.dataService.fetchData();
this.cartService.fetchOrder().subscribe(data => {
console.log(data);
});
}
delete(i: number) {
console.log(i);
this.items.splice(i, 1);
this.x = this.items.reduce(function(sum, cartItem) {
return sum + cartItem.price * cartItem.quantity;
}, 0);
}
checkout() {
this.pushItems.map(order =>
this.cartService.addOrder(order).subscribe(data =>
console.log(order),
error=> console.log(error)
)
);
addOrder(order){
return this.http.post("http://10.151.61.130:8019/customer/user/add/cartItem",order,{headers:this.headers}).
map(data => data.json(),
error=> error.json());
}
}
| d33895340ecf74ead49cfe20ba5a21beab1153be | [
"TypeScript"
] | 1 | TypeScript | tgarg6343/cart | e572b2cfe5931b7aee2b1b467c2ecdc21ed26078 | a5b2cb750fd596a30516c9a1e273c3261d44df8d |
refs/heads/master | <file_sep>import { AbstractActionHandler } from "../AbstractActionHandler"
import { Block, IndexState } from "../interfaces"
export class TestActionHandler extends AbstractActionHandler {
public state: any = {
indexState: { blockNumber: 0, blockHash: "" },
}
// tslint:disable-next-line
public async handleWithState(handle: (state: any) => void) {
await handle(this.state)
}
public async rollbackTo(blockNumber: number) {
this.setLastProcessedBlockNumber(blockNumber)
this.setLastProcessedBlockHash("")
}
public setLastProcessedBlockHash(hash: string) {
this.lastProcessedBlockHash = hash
}
public setLastProcessedBlockNumber(num: number) {
this.lastProcessedBlockNumber = num
}
public async _runUpdaters(state: any, block: Block, context: any) {
await this.runUpdaters(state, block, context)
}
public _runEffects(state: any, block: Block, context: any) {
this.runEffects(state, block, context)
}
protected async loadIndexState(): Promise<IndexState> {
return this.state.indexState
}
protected async updateIndexState(state: any, block: Block) {
const { blockNumber, blockHash } = block.blockInfo
state.indexState = { blockNumber, blockHash }
}
}
<file_sep>import { TestActionHandler } from "./testHelpers/TestActionHandler"
import blockchains from "./testHelpers/blockchains"
const { blockchain } = blockchains
describe("Action Handler", () => {
let actionHandler: TestActionHandler
const notRunUpdater = jest.fn()
const notRunEffect = jest.fn()
const runUpdater = jest.fn()
const runEffect = jest.fn()
beforeAll(() => {
actionHandler = new TestActionHandler(
[
{
actionType: "eosio.token::transfer",
updater: runUpdater,
},
{
actionType: "eosio.token::issue",
updater: notRunUpdater,
},
],
[
{
actionType: "eosio.token::transfer",
effect: runEffect,
},
{
actionType: "eosio.token::issue",
effect: notRunEffect,
},
],
)
})
it("runs the correct updater based on action type", async () => {
await actionHandler._runUpdaters({}, blockchain[1], {})
expect(runUpdater).toHaveBeenCalled()
expect(notRunUpdater).not.toHaveBeenCalled()
})
it("runs the correct effect based on action type", () => {
actionHandler._runEffects({}, blockchain[1], {})
expect(runEffect).toHaveBeenCalled()
expect(notRunEffect).not.toHaveBeenCalled()
})
it("retrieves indexState when processing first block", async () => {
actionHandler.state.indexState = {
blockNumber: 3,
blockHash: "000f42401b5636c3c1d88f31fe0e503654091fb822b0ffe21c7d35837fc9f3d8",
}
const [needToSeek, seekBlockNum] = await actionHandler.handleBlock(blockchain[0], false, true)
expect(needToSeek).toBe(true)
expect(seekBlockNum).toBe(4)
})
it("seeks to the next block needed when block number doesn't match last processed block", async () => {
actionHandler.setLastProcessedBlockNumber(2)
const [needToSeek, seekBlockNum] = await actionHandler.handleBlock(blockchain[3], false, false)
expect(needToSeek).toBe(true)
expect(seekBlockNum).toBe(3)
})
it("throws error if previous block hash and last processed don't match up", async () => {
actionHandler.setLastProcessedBlockNumber(3)
actionHandler.setLastProcessedBlockHash("asdfasdfasdf")
const expectedError = new Error("Block hashes do not match; block not part of current chain.")
await expect(actionHandler.handleBlock(blockchain[3], false, false)).rejects.toEqual(expectedError)
})
})
| 9a8d53ee747230200fc370470bc7be01bb2b139f | [
"TypeScript"
] | 2 | TypeScript | lachlangreenbank/demux-js | b1679a26e95e5aaf5f215d147c96ad8e671545d5 | 7bebdf02a5001249b58e32fec33c39f652989b32 |
refs/heads/master | <repo_name>gedeonntwali/food-webclents<file_sep>/app/models/concerns/food.rb
class Food
attr_accessor :id, :ingredient, :spice, :measurement
def initialize(hash)
@id = hash['id']
@ingredient = hash['ingredient']
@spice = hash['spice']
@measurement = hash['measurement']
end
def self.find(id)
food_hash = Unirest.get("http://localhost:3000/api/v2/foods/#{id}.json", :headers => {"Accept"=>"application/json", "X-User-Email"=>"<EMAIL>", "Authorization"=>"Token <PASSWORD>"}).body
@food = Food.new(food_hash)
end
def self.all
foods = Unirest.get("http://localhost:3000/api/v2/foods.json", :headers => {"Accept"=>"application/json", "X-User-Email"=>"<EMAIL>", "Authorization"=>"Token <PASSWORD>"}).body
@foods = []
foods.each do |food|
@foods << Food.new(food)
end
return @foods
end
def self.create(ingredient, spice, measurement)
Unirest.post("http://localhost:3000/api/v1/employees.json", :headers => {"Accept"=> "application/json"}, :parameters => {:ingredient => params[:ingredient], :spice => params[:spice], :measurement=> params[:measurement]}).body
end
def self.update(ingredient, spice, measurement)
Unirest.patch("http://localhost:3000/api/v2/foods/#{id}.json")
end
end
<file_sep>/app/controllers/foods_controller.rb
class FoodsController < ApplicationController
def index
@foods = Food.all
end
def show
@food = Food.find(params[:id])
end
def new
end
def create
@food = Food.create(params[:ingredient], params[:spice], params[:measurement])
redirect_to "/foods/#{@food['id']}"
end
def edit
@food = Unirest.get("http://localhost:3000/api/v2/foods/#{params[:id]}.json", :headers => {"Accept"=> "application/json"}, :parameters => {:ingredient => params[:ingredient], :spice => params[:spice], :measurement=> params[:measurement]}).body
end
def update
@food = Food.update(params[:ingredient], params[:spice], params[:measurement])
redirect_to "/foods/#{params[:id]}"
end
def destroy
@food = Food.delete(params[:id])
end
end
| ffe865e2e2b2edf0ae64e3030f5470522323abf9 | [
"Ruby"
] | 2 | Ruby | gedeonntwali/food-webclents | a771ec25e66070ffa2c3823eddb008152c05dfcb | bf70ef0e10aa6de6a4c24e2dfeaf949accd8c38a |
refs/heads/master | <repo_name>vividandrew/PythonProjects<file_sep>/Pong.py
import pygame, sys, random
from pygame.locals import *
#<editor-fold desc="Essential Variables to run everything.">
# Set constants
windowWidth = 640
windowHeight = 480
mainClock = pygame.time.Clock()
FPSLimit = 60
# Set some colours
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
# initialize pygame and creating some objects
pygame.init()
windowSurface = pygame.display.set_mode((windowWidth, windowHeight))
pong = pygame.Rect(windowWidth/2-5, windowHeight/2-5, 10, 10)
pongOL = pygame.Rect(windowWidth/2-7, windowHeight/2-7, 14, 14)
lPaddle = pygame.Rect(20, windowHeight/2-25, 10, 50)
rPaddle = pygame.Rect(windowWidth-20, windowHeight/2-25, 10, 50)
#set fonts up
TitleFont = pygame.font.SysFont('Arial', 128)
lFont = pygame.font.SysFont('Arial', 48)
mFont = pygame.font.SysFont('Arial', 24)
sFont = pygame.font.SysFont('Arial', 12)
#</editor-fold>
def Highlight(mouseOut, mouseIn, textRect, x,y, over = False):
if textRect.collidepoint((x,y)):
return mouseIn, True
else:
return mouseOut, False
# Settings Screen
def settings(diff):
mouseClicked = False
mousex = 0
mousey = 0
hard = False
normal = False
easy = False
if diff == 9:
hard = True
elif diff == 6:
normal = True
else:
easy = True
# <editor-fold desc="Text boxes">
TitleText = TitleFont.render('Settings', 48, WHITE)
TitleRect = TitleText.get_rect()
TitleRect.centerx = windowWidth / 2
TitleRect.centery = windowHeight / 5
mainMenuText = mFont.render('Main menu', 48, WHITE)
mainMenuRect = mainMenuText.get_rect()
mainMenuRect.centerx = windowWidth / 2
mainMenuRect.centery = windowHeight - 50
easyText = mFont.render("EASY", True, WHITE)
easyRect = easyText.get_rect()
easyRect.centerx = windowWidth / 2
easyRect.centery = windowHeight - windowHeight / 4
normalText = mFont.render("NORMAL", True, WHITE)
normalRect = normalText.get_rect()
normalRect.centerx = windowWidth / 2
normalRect.centery = windowHeight - windowHeight / 3
hardText = mFont.render("HARD", True, WHITE)
hardRect = easyText.get_rect()
hardRect.centerx = windowWidth / 2
hardRect.centery = (windowHeight - windowHeight / 3) - 30
groupTextBoxes = []
groupTextBoxes.append(
{
'name': "Easy",
'font': easyText,
'ifin': mFont.render("EASY", True, WHITE, (20, 20, 20)),
'rect': easyRect,
'end result': mFont.render("EASY", True, WHITE),
'checked': easy,
'difficulty': True,
'checkbox': pygame.Rect(easyRect.left - 30, easyRect.top, easyRect.height, easyRect.height)
})
groupTextBoxes.append(
{
'name': "Normal",
'font': normalText,
'ifin': mFont.render("NORMAL", True, WHITE, (20, 20, 20)),
'rect': normalRect,
'end result': mFont.render("NORMAL", True, WHITE),
'checked': normal,
'difficulty': True,
'checkbox': pygame.Rect(normalRect.left - 30, normalRect.top, normalRect.height, normalRect.height)
})
groupTextBoxes.append(
{
'name': "Hard",
'font': hardText,
'ifin': mFont.render("HARD", True, WHITE, (20, 20, 20)),
'rect': hardRect,
'end result': mFont.render("HARD", True, WHITE),
'checked': hard,
'difficulty': True,
'checkbox': pygame.Rect(hardRect.left - 30, hardRect.top, hardRect.height, hardRect.height)
})
groupTextBoxes.append(
{
'name': "MainMenu",
'font': mainMenuText,
'ifin': mFont.render("Main menu", True, WHITE, (20, 20, 20)),
'rect': mainMenuRect,
'end result': mFont.render("Main menu", True, WHITE),
'checked': False,
'difficulty': False,
'checkbox': pygame.Rect(hardRect.top, hardRect.left - 30, hardRect.height, hardRect.height),
'clicked': "mainMenu"
})
# </editor-fold>
while True:
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
sys.exit()
if event.type == KEYDOWN:
if event.key == K_ESCAPE:
mainMenu(mousex, mousey)
if event.type == MOUSEBUTTONDOWN:
mouseClicked = True
if event.type == MOUSEBUTTONUP:
mouseClicked = False
if event.type == MOUSEMOTION:
mousex = event.pos[0]
mousey = event.pos[1]
windowSurface.fill(BLACK)
windowSurface.blit(TitleText, TitleRect)
for boxes in groupTextBoxes:
boxes['end result'], over = Highlight(boxes['font'], boxes['ifin'], boxes['rect'], mousex, mousey)
if over and mouseClicked and boxes['difficulty']:
for checkboxes in groupTextBoxes:
checkboxes['checked'] = False
boxes['checked'] = True
if over and mouseClicked and not boxes['difficulty']:
if boxes['name'] == 'MainMenu':
for name in groupTextBoxes:
if name['name'] == 'Easy' and name['checked']:
diff = 3
if name['name'] == 'Normal' and name['checked']:
diff = 6
if name['name'] == 'Hard' and name['checked']:
diff = 9
mainMenu(mousex, mousey, diff)
windowSurface.blit(boxes['end result'], boxes['rect'])
if boxes['checked'] and boxes['difficulty']:
pygame.draw.rect(windowSurface, WHITE, boxes['checkbox'])
elif boxes['difficulty']:
pygame.draw.rect(windowSurface, (30, 30, 30), boxes['checkbox'])
windowSurface.blit(mainMenuText, mainMenuRect)
pygame.display.update()
mainClock.tick(FPSLimit)
# Main Game Loop
def playGame(diff):
# Resets objects
pong.x = windowWidth / 2 - 5
pong.y = windowHeight / 2 - 5
lPaddle.top = windowHeight/2-25
rPaddle.top = windowHeight/2-25
# some essential game variables
cSpeed = diff
pSpeed = 6
moveUP = False
moveDOWN = False
cScore = 0
pScore = 0
pStuck = 0
# Background Objects
tBorder = pygame.Rect(0, 0, windowWidth, 4)
lBorder = pygame.Rect(0, 0, 4, windowHeight)
rBorder = pygame.Rect(windowWidth - 4, 0, 4, windowHeight)
bBorder = pygame.Rect(0, windowHeight - 4, windowWidth, 4)
mLine = pygame.Rect(windowWidth / 2 - 2, 0, 4, windowHeight)
background = [lBorder, rBorder, tBorder, bBorder, mLine]
# Pong directions
pongSpeed = 3
pongUD = random.randint(-pongSpeed, pongSpeed)
pongLorR = random.randint(0, 1)
if pongLorR == 1:
pongLeft = False
pongRight = True
else:
pongLeft = True
pongRight = False
while True:
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
sys.exit()
if event.type == KEYDOWN:
if event.key == K_ESCAPE:
mainMenu(CPUdiff=diff)
if event.key == K_s:
moveUP = False
moveDOWN = True
if event.key == K_w:
moveDOWN = False
moveUP = True
if event.type == KEYUP:
if event.key == K_s:
moveDOWN = False
if event.key == K_w:
moveUP = False
# Pong controller
if lPaddle.colliderect(pong):
pongLeft = False
pongRight = True
if (pong.y + 10) - lPaddle.y <= 15:
pongUD = pongUD - (((pong.y + 10) - lPaddle.y)*0.5)/2
if (pong.y + 10) - lPaddle.y >= 35:
pongUD = pongUD - ((((pong.y + 10) - lPaddle.y)*0.5)-35)/2
if rPaddle.colliderect(pong):
pongLeft = True
pongRight = False
if (pong.y + 10) - rPaddle.y <= 15:
pongUD = pongUD - (((pong.y + 10) - rPaddle.y)*0.5)/2
if (pong.y + 10) - rPaddle.y >= 35:
pongUD = pongUD - ((((pong.y + 10) - rPaddle.y)*0.5)-35)/2
if pong.top < 4 + pongSpeed:
pongUD = -pongUD
if pong.top > windowHeight - (pong.height + pongSpeed + 4):
pongUD = -pongUD
pong.top += int(pongUD)
if pongLeft:
pong.left -= pongSpeed
if pongRight:
pong.left += pongSpeed
# Set position of the outline for the pong
pongOL.left = pong.x - 2
pongOL.top = pong.y - 2
# Paddle movement controls
if moveUP and lPaddle.centery > 0:
lPaddle.top -= pSpeed
if moveDOWN and lPaddle.centery < windowHeight:
lPaddle.top += pSpeed
'''
#Let the computer control the Left paddle also, for testing
if pong.y - lPaddle.top - 20 < 0:
lPaddle.top -= cSpeed
if pong.y - rPaddle.top - 20 > 0:
lPaddle.top += cSpeed
'''
if pong.y - rPaddle.top - 20 < 0:
rPaddle.top -= cSpeed
if pong.y - rPaddle.top - 20 > 0:
rPaddle.top += cSpeed
# Draw background(Border, middle line)
windowSurface.fill(BLACK)
for i in background:
pygame.draw.rect(windowSurface, WHITE, i)
pygame.draw.rect(windowSurface, WHITE, lPaddle)
pygame.draw.ellipse(windowSurface, BLACK, pongOL, )
pygame.draw.ellipse(windowSurface, WHITE, pong)
pygame.draw.rect(windowSurface, WHITE, rPaddle)
# Scoreboard system
if pong.left < -6:
cScore += 1
pong.left = windowWidth/2-5
pong.top = windowHeight/2-5
pongUD = random.randint(-pongSpeed, pongSpeed)
if pong.left > windowWidth+16:
pScore += 1
pong.left = windowWidth/2-5
pong.top = windowHeight/2-5
pongUD = random.randint(-pongSpeed, pongSpeed)
text = lFont.render(str(pScore) + " " + str(cScore), True, WHITE)
scoreBoard = text.get_rect()
scoreBoard.centery = 50
scoreBoard.centerx = windowWidth/2
#testRect = pygame.Rect(0, lPaddle.y, windowWidth/3, 1)
#pygame.draw.rect(windowSurface,WHITE, testRect)
windowSurface.blit(text, scoreBoard)
# End of the loop, updates the rect in the game.
pygame.display.update()
mainClock.tick(FPSLimit)
# Main Menu Screen
def mainMenu(mx = 0, my = 0, CPUdiff = 6):
mouseClicked = False
mousex = mx
mousey = my
while True:
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
sys.exit()
if event.type == KEYDOWN:
if event.key == K_ESCAPE:
pygame.quit()
sys.exit()
if event.type == MOUSEMOTION:
mousex = event.pos[0]
mousey = event.pos[1]
if event.type == MOUSEBUTTONDOWN:
mouseClicked = True
if event.type == MOUSEBUTTONUP:
mouseClicked = False
# <editor-fold desc="Text boxes">
titleText = TitleFont.render("PONG", True, WHITE)
titleRect = titleText.get_rect()
titleRect.centerx = windowWidth/2
titleRect.centery = 128
startText = lFont.render("START", True, WHITE)
startRect = startText.get_rect()
startRect.centerx = windowWidth/2
startRect.centery = windowHeight/2 + 10
settingText = mFont.render("Settings", True, WHITE)
settingRect = settingText.get_rect()
settingRect.centerx = windowWidth/2
settingRect.centery = windowHeight/2 + 58
quitText = mFont.render("Quit", True, WHITE)
quitRect = quitText.get_rect()
quitRect.centerx = windowWidth/2
quitRect.centery = windowHeight - windowHeight/3 + 10
groupTextBoxes = []
groupTextBoxes.append(
{
'font': startText,
'ifin': lFont.render("START", True, WHITE, (20, 20, 20)),
'rect': startRect,
'end result': lFont.render("START", True, WHITE, (20, 20, 20)),
'clicked': "playGame"
})
groupTextBoxes.append(
{
'font': settingText,
'ifin': mFont.render("Settings", True, WHITE, (20, 20, 20)),
'rect': settingRect,
'end result': lFont.render("Settings", True, WHITE),
'clicked': "Settings"
})
groupTextBoxes.append(
{
'font': quitText,
'ifin':mFont.render("Quit", True, WHITE, (20, 20, 20)),
'rect': quitRect,
'end result': lFont.render("Quit", True, WHITE),
'clicked': "Quit"
})
#</editor-fold>
for boxes in groupTextBoxes:
#This returns the font which has a background of (20, 20, 20) indicating it as highlighted. also returns
#a bool of either True or False, so the right box is clicked for the following if statement
boxes['end result'], over = Highlight(boxes['font'], boxes['ifin'], boxes['rect'], mousex, mousey)
if mouseClicked and over:
if boxes['clicked'] == "playGame":
playGame(CPUdiff)
if boxes['clicked'] == "Settings":
settings(CPUdiff)
if boxes['clicked'] == "Quit":
pygame.quit()
sys.exit()
windowSurface.fill(BLACK)
# Draw text boxes.
windowSurface.blit(titleText, titleRect)
for boxes in groupTextBoxes:
windowSurface.blit(boxes['end result'], boxes['rect'])
pygame.display.update()
mainClock.tick(FPSLimit)
mainMenu()
<file_sep>/FlowField.py
#Python 3.6
import noise, pygame, sys, math, random
from pygame.locals import *
windowWidth = 400
windowHeight = 400
xOffsetOrigin = random.randint(0,255)
yOffsetOrigin = random.randint(0,255)
xOffset = xOffsetOrigin
yOffset = yOffsetOrigin
zOffset = 0
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
BLUE = (70, 70, 255)
scale = 40
counter = 1
maxParticle = 100
FlowField = [0 for i in range(0, int(windowWidth/scale) + 1)]
particles = [maxParticle]
last_fps = 0
dblbuff = [pygame.Surface((windowWidth, windowHeight)), pygame.Surface((windowWidth, windowHeight))] #Creates the two surfaces for double buffer
buff = 0
pygame.init()
# The overlay is to give some alpha to the ellipses drawn on the screen
windowOverlay = pygame.Surface((windowWidth, windowHeight), pygame.SRCALPHA)
windowSurface = pygame.display.set_mode((windowWidth, windowHeight))
# This sets the alpha and the colour which is white, making the screen lighter,
# Which sets the ellipses to go lighter as time goes
windowOverlay.fill((255, 255, 255, 2))
mainClock = pygame.time.Clock()
for x in range(0, int(windowWidth/scale) + 1):
FlowField[x] = [0 for i in range(0, int(windowWidth/scale) + 1)]
for x in range(0, int(windowWidth/scale) + 1):
for y in range(0, int(windowWidth/scale) + 1):
FlowField[x][y] = [0 for i in range(0, 1)]
# This is each particle object which controls a lot of how it is posistion, speed and colour
class Particle():
def __init__(self):
self.pos = [random.randint(0, windowWidth), random.randint(0, windowHeight)]
self.prevPos = self.pos
self.vel = [0, 0]
self.acc = [0, 0]
self.width = 4
self.height = 4
self.maxVel = 1
self.mag = 0.05 # This controls how strong the acc has over the velocity. (acc is controlled by the FlowField)
# The weaker the mag the more curvy the particle will be, but required to decrease maxVel or it can get out of control
self.colour = (BLACK)
self.rect = pygame.Rect(self.pos, (self.width, self.height))
self.Surf = pygame.Surface((self.width,self.height))
self.Surf.set_alpha(5)
self.buff = buff
# this changes the position of the object, called every frame
def update(self):
#print self.vel
self.vel[0] += self.acc[0]
#limits the speed of the particle, stopping it from going too fast.
if self.vel[0] > self.maxVel:
self.vel[0] = self.maxVel
if self.vel[0] < -self.maxVel:
self.vel[0] = -self.maxVel
self.vel[1] += self.acc[1]
if self.vel[1] > self.maxVel:
self.vel[1] = self.maxVel
self.vel[1] += self.acc[1]
if self.vel[1] < -self.maxVel:
self.vel[1] = -self.maxVel
self.__setPreviousPos(self.pos[0], self.pos[1])
self.pos[0] += self.vel[0]
self.pos[1] += self.vel[1]
self.rect.x = self.pos[0]
self.rect.y = self.pos[1]
self.acc[0] *= 0
self.acc[1] *= 0
def __setPreviousPos(self, x, y):
self.prevPos = [x, y]
#This was to get the previous posistion only controlled within the object.
#this was to combat skipped pixels
def applyForce(self, force):
#print force
self.acc[0] = force[0]/scale * self.mag
self.acc[1] = force[1]/scale * self.mag
#print self.acc
def show(self, buff):
#pygame.draw.ellipse(windowSurface, self.colour, self.rect)
buff.blit(self.Surf,self.pos)
#The line was to help with frame skipped pixels, but never gets that bad
#pygame.draw.line(windowSurface, self.colour, self.pos, self.prevPos, self.width*3)
def edge(self):
if self.pos[0] < 0 - 10:
self.pos[0] = windowWidth
self.__setPreviousPos(self.pos[0],self.pos[1])
if self.pos[0] > windowWidth + 10:
self.pos[0] = 0
self.__setPreviousPos(self.pos[0], self.pos[1])
if self.pos[1] < 0 - 10:
self.pos[1] = windowHeight
self.__setPreviousPos(self.pos[0], self.pos[1])
if self.pos[1] > windowHeight + 10:
self.pos[1] = 0
self.__setPreviousPos(self.pos[0], self.pos[1])
def follow(self, FlowField):
x = int(self.pos[0]/scale)
y = int(self.pos[1]/scale)
force = 0, 0
for w in range(0, int(windowWidth/scale) + 1):
for h in range(0, int(windowWidth/scale) + 1):
if x == w and y == h:
force = FlowField[w][h]
self.applyForce(force)
#print force
particles[0] = Particle()
for i in range(0, maxParticle-1):
particles.append(Particle())
windowSurface.fill(WHITE)
dblbuff[0].fill(WHITE)
dblbuff[1].fill(WHITE)
while True:
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
sys.exit()
#windowSurface.fill(WHITE)
counter += 1
if counter > 0:
#windowSurface.fill((25,25,255))
xOffset = xOffsetOrigin
for x in range(0, int(windowWidth/scale) + 1):
yOffset = yOffsetOrigin
for y in range(0, int(windowWidth/scale) + 1):
r = noise.pnoise3(xOffset, yOffset, zOffset)
#print r
r *= 360
#print(r)
originx = x * scale
originy = y * scale
lx = originx + math.cos(math.radians(r)) * scale
ly = originy + math.sin(math.radians(r)) * scale
fx = math.cos(math.radians(r)) * scale
fy = math.sin(math.radians(r)) * scale
FlowField[x][y] = fx, fy
#pygame.draw.line(windowSurface, BLUE, (originx, originy), (lx, ly), 1)
yOffset += 0.2
xOffset += 0.2
zOffset += 0.001
#counter = 0
#Switches between the surface its displayed to
if buff == 0:
buff = 1
else:
buff = 0
for x in range(0, len(particles)):
particles[x].edge()
particles[x].show(dblbuff[buff]) #Calls for a surface to draw the objects to.
particles[x].update()
particles[x].follow(FlowField)
windowSurface.blit(dblbuff[buff], (0, 0))
pygame.display.update()
mainClock.tick(60)
#This is commented out because its not needed, but it measures the fps
if pygame.time.get_ticks() - last_fps > 1000:
print ("FPS: " + str(mainClock.get_fps()))
last_fps = pygame.time.get_ticks()<file_sep>/ScoreBoard.py
#!PYTHON3
# Ver:0.02
# The script gets slow when it comes to typing the team names potentially due to the constant listening to key events
# otherwise script is functional
import pyHook, pythoncom
# initialize the variables
T1S = 0
T2S = 0
team1 = ""
team2 = ""
print("""
Press F11 to start program
""")
# The function to save the file as a html file with the names and scores given to it.
def update(team1, T1S, team2, T2S):
ScoreBoard = open("ScoreBoard.html", "w")
# Sets the text for the final format, don't edit, may break it! ^^ code must be executed above
TvT = """
<head><meta http-equiv="refresh" content="1"></head>
<body>
<p>
<table width=50%% align="center">
<tr>
<td id="T1N"><h1 align="center">%s</h1></td>
<td id="T2N"><h1 align="center">%s</h1></td>
</tr>
<tr>
<td id="T1S"><h3 align="center">%s</h3>
<td id="T2S"><h3 align="center">%s</h3>
</tr>
</table>
</p>
<style>
body{
color:white
}
h1 {
font-style:ariel;
font-size:40px;
-webkit-text-stroke-width: 0.5px;
-webkit-text-stroke-color: black;
}
h3 {
font-style:ariel;
font-size:40px;
-webkit-text-stroke-width: 0.5px;
-webkit-text-stroke-color: black;
}
</style>
</body>
""" % (team1, team2, T1S, T2S)
# ! testing print(TvT)
ScoreBoard.write(str(TvT))
ScoreBoard.close()
# Event executed every time the keyboard is pressed.
def OnKeyboardEvent(event):
# calls the global variable to be used locally and stored globally.
global T1S
global T2S
global team1
global team2
keypressed = event.Key
#print keypressed
if keypressed == "F9":
T1S += 1
update(team1, T1S, team2, T2S)
if keypressed == "F10":
T2S += 1
update(team1, T1S, team2, T2S)
if keypressed == "F11":
print("Enter Team/Player 1")
team1 = input()
print("Enter Team/Player 2")
team2 = input()
T1S = 0
T2S = 0
print("""
Controls;
1. press F9 to increase %s points
2. press F10 to increase %s points
3. press F11 to reset
""" % (team1, team2))
update(team1, T1S, team2, T2S)
# return True to pass the event to other handlers within pyhook
return True
# create a hook manager
hm = pyHook.HookManager()
# watch for all key down events
hm.KeyDown = OnKeyboardEvent
# set the hook
hm.HookKeyboard()
# Wait forever
pythoncom.PumpMessages()
<file_sep>/Rain Simulation.py
#Python 3.6
import pygame, random, sys, time
from pygame.locals import *
#Set some constants
windowWidth = 600
windowHeight = 600
MaxRain = 1000
FPSLimit = 60
rainDrops = []
fallSpeed = 0.7
wind_offset = random.randint(-1, 1)
counter = 0
#Initialize pygame and other necesary items
pygame.init()
pygame.display.set_caption("Raining Simulation")
mainClock = pygame.time.Clock()
windowDisplay = pygame.display.set_mode((windowWidth, windowHeight))
#Set up rain objects
for i in range(MaxRain):
z = random.randint(3, 10)
rain = {'z': z, 'rect': pygame.Rect(random.randint(-1* (windowWidth/3), windowWidth+ (windowWidth/3)),
random.randint(-1 * windowHeight, 0), z*0.2, z*3)}
rainDrops.append(rain)
#Set up colours needed
rainColour = (55, 0, 255)
BackgroundColour = (10, 0, 10)
#Main loop
while True:
#used later to find the difference in time length. to control fps
start = time.time()
#Checks for selective events to just quit the game.
for events in pygame.event.get():
if events.type == QUIT:
pygame.quit()
sys.exit()
if events.type == KEYDOWN:
if events.key == K_ESCAPE:
pygame.quit()
sys.exit()
#Resets the rain back to the top of the screen in a random posistion
#as to not have a set screen/image imprinted after watching it so long
for rain in rainDrops:
if rain['rect'].top > windowHeight:
rain['rect'].top = random.randint(-1 * windowHeight, 0)
rain['rect'].left = random.randint(-1 * (windowWidth/3), windowWidth+ (windowWidth/3))
rain['z'] = random.randint(2, 10)
rain['rect'].width = rain['z']*0.2
rain['rect'].height = rain['z']*3
#Sets the window background
windowDisplay.fill(BackgroundColour)
#Set the rain to fall down and the character in the middle, (The cause of the performance issue.)
for rain in rainDrops:
rain['rect'].top += fallSpeed*rain['rect'].height
rain['rect'].left += wind_offset*rain['z']
pygame.draw.rect(windowDisplay, rainColour, rain['rect'])
#a little weird clock that eventually changes the wind offset every 10 seconds
diff = time.time() - start
counter += diff
if counter >= 10:
wind_offset = random.randint(-10, 10) * 0.1
counter = 0
pygame.display.update()
mainClock.tick(FPSLimit)
| 8c919af55c8974635d33a272a598713f012e28e2 | [
"Python"
] | 4 | Python | vividandrew/PythonProjects | 3910cee4c8ad16eb281647d4b75a70418dec2986 | 24422d6b1eaa1d0ae6bd7ee3c9b643fe8f298080 |
refs/heads/main | <repo_name>mtalhaabbas/react-news-site<file_sep>/src/components/Spinner.js
import React from 'react'
import loading from './loading.gif';
const Spinner = () => {
return (
<div className="flex align-center justify-center">
<img className="w-1/4" src={loading}></img>
</div>
)
}
export default Spinner
| 97c6b774e2611e66aa86aba6881dcfb176a286b0 | [
"JavaScript"
] | 1 | JavaScript | mtalhaabbas/react-news-site | e35c45b2ebd7becc9c9e74014d727144bcbf2547 | 756697e0cdb7a8271c3e5b7d0761a77da92f6c33 |
refs/heads/master | <file_sep><?php
/**
* apply_status admitLetter iew
* @package jazzee
* @subpackage apply
*/
if($applicant->isLocked() and $applicant->getDecision()->getFinalAdmit()){
print $text;
}
?><file_sep><?php
namespace Jazzee\Entity;
/**
* User
* Admin users details
* @Entity(repositoryClass="\Jazzee\Entity\UserRepository")
* @Table(name="users",
* uniqueConstraints={@UniqueConstraint(name="user_name",columns={"uniqueName"})})
* @package jazzee
* @subpackage orm
**/
class User{
/**
* @Id
* @Column(type="bigint")
* @GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* Unique name for use with federated authentication
* @Column(type="string")
* */
private $uniqueName;
/** @Column(type="string", nullable=true) */
private $email;
/** @Column(type="string", nullable=true) */
private $firstName;
/** @Column(type="string", nullable=true) */
private $lastName;
/** @Column(type="string", nullable=true) */
private $apiKey;
/** @Column(type="boolean") */
private $isActive;
/**
* @ManyToOne(targetEntity="Program")
* @JoinColumn(onDelete="SET NULL")
*/
private $defaultProgram;
/**
* @ManyToOne(targetEntity="Cycle")
* @JoinColumn(onDelete="SET NULL")
*/
private $defaultCycle;
/**
* @ManyToMany(targetEntity="Role", inversedBy="users")
* @JoinTable(name="user_roles")
**/
private $roles;
/**
* @OneToMany(targetEntity="AuditLog", mappedBy="user")
*/
protected $auditLogs;
public function __construct(){
$this->isActive = true;
$this->roles = new \Doctrine\Common\Collections\ArrayCollection();
}
/**
* Get id
*
* @return bigint $id
*/
public function getId(){
return $this->id;
}
/**
* Set uniqueName
*
* @param string $uniqueName
*/
public function setUniqueName($uniqueName){
$this->uniqueName = $uniqueName;
}
/**
* Get uniqueName
*
* @return string $uniqueName
*/
public function getUniqueName(){
return $this->uniqueName;
}
/**
* Set email
*
* @param string $email
*/
public function setEmail($email){
$this->email = $email;
}
/**
* Get email
*
* @return string $email
*/
public function getEmail(){
return $this->email;
}
/**
* Set firstName
*
* @param string $firstName
*/
public function setFirstName($firstName){
$this->firstName = $firstName;
}
/**
* Get firstName
*
* @return string $firstName
*/
public function getFirstName(){
return $this->firstName;
}
/**
* Set lastName
*
* @param string $lastName
*/
public function setLastName($lastName){
$this->lastName = $lastName;
}
/**
* Get lastName
*
* @return string $lastName
*/
public function getLastName(){
return $this->lastName;
}
/**
* Generate apiKey
*/
public function generateApiKey(){
//PHPs uniquid function is time based and therefor guessable
//So we get unique through uniquid and we get random by prefixing it with a part of an MD5
$this->apiKey = \uniqid(md5((mt_rand()*mt_rand()*$this->id) . $this->uniqueName . $this->lastName . $this->firstName));
}
/**
* get apiKey
*/
public function getApiKey(){
return $this->apiKey;
}
/**
* Is the user active
* @return boolean
*/
public function isActive(){
return $this->isActive;
}
/**
* Active User
*
*/
public function activate(){
$this->isActive = true;
}
/**
* Deactivate User
*/
public function deActivate(){
$this->isActive = false;
$this->roles->clear();
}
/**
* Set defaultProgram
*
* @param Entity\Program $defaultProgram
*/
public function setDefaultProgram(Program $defaultProgram){
$this->defaultProgram = $defaultProgram;
}
/**
* Get defaultProgram
*
* @return Entity\Program $defaultProgram
*/
public function getDefaultProgram(){
return $this->defaultProgram;
}
/**
* Set defaultCycle
*
* @param Entity\Cycle $defaultCycle
*/
public function setDefaultCycle(Cycle $defaultCycle){
$this->defaultCycle = $defaultCycle;
}
/**
* Get defaultCycle
*
* @return Entity\Cycle $defaultCycle
*/
public function getDefaultCycle(){
return $this->defaultCycle;
}
/**
* Add role
*
* @param Entity\Role $role
*/
public function addRole(Role $role){
$this->roles[] = $role;
}
/**
* Get roles
*
* @return Doctrine\Common\Collections\Collection $roles
*/
public function getRoles(){
return $this->roles;
}
/**
* Has role
* Check if a user has a role
* @param \Jazzee\Entity\Role $role
* @return boolean
*/
public function hasRole(Role $role){
foreach($this->roles as $r) if($r == $role) return true;
return false;
}
/**
* Add log
*
* @param Entity\Log $log
*/
public function addLog(AuditLog $log){
$this->logs[] = $log;
}
/**
* Get logs
*
* @return Doctrine\Common\Collections\Collection $logs
*/
public function getLogs(){
return $this->logs;
}
/**
* get an array of all the users program affiliations
* @return array
*/
public function getPrograms(){
$programs = array();
foreach($this->roles as $role){
if($role->getProgram()) $programs[] = $role->getProgram()->getId();
}
array_unique($programs);
return $programs;
}
/**
* Check if a user is allowed to access a resource
*
* @param string $controller
* @param string $action
* @param \Jazzee\Entity\Program $program
*/
public function isAllowed($controller, $action, \Jazzee\Entity\Program $program = null){
foreach($this->roles as $role) {
if(($role->isGlobal() or $role->getProgram() == $program) and $role->isAllowed($controller, $action)) {
return true;
}
}
return false;
}
}
/**
* UserRepository
* Special Repository methods for User to make searchign for special conditions easier
* @package jazzee
* @subpackage orm
*/
class UserRepository extends \Doctrine\ORM\EntityRepository{
/**
* find all by name
*
* @param string $firstName
* @param string $lastName
*
* @return Doctrine\Common\Collections\Collection \Jazzee\Entity\User
*/
public function findByName($firstName, $lastName){
$query = $this->_em->createQuery('SELECT u FROM Jazzee\Entity\User u WHERE (u.firstName IS NULL OR u.firstName LIKE :firstName) AND (u.lastName IS NULL OR u.lastName LIKE :lastName) ORDER BY u.lastName, u.firstName');
$query->setParameter('firstName', $firstName);
$query->setParameter('lastName', $lastName);
return $query->getResult();
}
/**
* find all users in a program
*
* @param \Jazzee\Entity\Program $program
*
* @return Doctrine\Common\Collections\Collection \Jazzee\Entity\User
*/
public function findByProgram($program){
$query = $this->_em->createQuery('SELECT u FROM Jazzee\Entity\User u JOIN u.roles r WHERE r.program = :programId AND u.isActive = true ORDER BY u.lastName, u.firstName');
$query->setParameter('programId', $program->getId());
return $query->getResult();
}
}<file_sep><?php
namespace Jazzee;
/**
* Empty Base class for local customization
*
* This class is designed to be an easy override point for customizations
* without having to worry about or mess with the JazzeeController
* @package jazzee
*/
class Controller extends JazzeeController{}<file_sep><?php
/**
* Run all tests
* @author <NAME> <<EMAIL>>
* @license http://jazzee.org/license.txt
* @package jazzee
* @subpackage test
*/
require_once('Jazzee_Test.php');
$test = &new TestSuite('Test all of Jazzee');
//add each test file
//$test->addTestFile('SomeTest.class.php');
//run all of the tests
if (TextReporter::inCli()){
exit ($test->run(new textReporter()) ? 0 : 1); //on failures exit with a failure
}
$test->run(new HtmlReporter());
?>
<file_sep><?php
namespace Jazzee\Console;
/**
* Install a new database
*
* @author <NAME> <<EMAIL>>
* @license http://jazzee.org/license.txt
* @package jazzee
* @subpackage console
*/
class Install extends \Doctrine\ORM\Tools\Console\Command\SchemaTool\CreateCommand
{
/**
* @see Console\Command\Command
*/
protected function configure()
{
$this
->setName('install')
->setDescription('Install the database')
->setHelp(<<<EOT
'Installs a new jazzee dataabse and default components.'
EOT
);
}
protected function executeSchemaCommand(\Symfony\Component\Console\Input\InputInterface $input, \Symfony\Component\Console\Output\OutputInterface $output, \Doctrine\ORM\Tools\SchemaTool $schemaTool, array $metadatas){
$sm = $this->getHelper('em')->getEntityManager()->getConnection()->getSchemaManager();
$tables = $sm->listTableNames();
if(!empty($tables)){
$output->write('<error>ATTENTION: You are attempting to install jazzee on a database that is not empty..</error>' . PHP_EOL . PHP_EOL);
exit(1);
}
$output->write('<comment>Creating database schema and installing default components...</comment>' . PHP_EOL);
$schemaTool->createSchema($metadatas);
$output->write('<info>Database schema created successfully</info>' . PHP_EOL);
$pageTypes = array(
'\Jazzee\Page\Branching' => 'Branching',
'\Jazzee\Page\ETSMatch' => 'ETS Score Matching',
'\Jazzee\Page\Lock' => 'Lock Application',
'\Jazzee\Page\Payment' => 'Payment',
'\Jazzee\Page\Recommenders' => 'Recommenders',
'\Jazzee\Page\Standard' => 'Standard',
'\Jazzee\Page\Text' => 'Plain Text'
);
foreach($pageTypes as $class => $name){
$pageType = new \Jazzee\Entity\PageType();
$pageType->setName($name);
$pageType->setClass($class);
$this->getHelper('em')->getEntityManager()->persist($pageType);
}
$this->getHelper('em')->getEntityManager()->flush();
$output->write('<info>Default Page types added</info>' . PHP_EOL);
$elementTypes = array(
'\Jazzee\Element\CheckboxList' => 'Checkboxes',
'\Jazzee\Element\Date' => 'Date',
'\Jazzee\Element\EmailAddress' => 'Email Address',
'\Jazzee\Element\EncryptedTextInput' => 'Encrypted Text Input',
'\Jazzee\Element\PDFFileInput' => 'PDF Upload',
'\Jazzee\Element\Phonenumber' => 'Phone Number',
'\Jazzee\Element\RadioList' => 'Radio Buttons',
'\Jazzee\Element\RankingList' => 'Rank Order Dropdown',
'\Jazzee\Element\SelectList' => 'Dropdown List',
'\Jazzee\Element\ShortDate' => 'Short Date',
'\Jazzee\Element\TextInput' => 'Single Line Text',
'\Jazzee\Element\Textarea' => 'Text Area'
);
foreach($elementTypes as $class => $name){
$elementType = new \Jazzee\Entity\ElementType();
$elementType->setName($name);
$elementType->setClass($class);
$this->getHelper('em')->getEntityManager()->persist($elementType);
}
$this->getHelper('em')->getEntityManager()->flush();
$output->write('<info>Default Element types added</info>' . PHP_EOL);
$em = $this->getHelper('em')->getEntityManager();
$role = new \Jazzee\Entity\Role();
$role->makeGlobal();
$em->persist($role);
$role->setName('Administrator');
\Foundation\VC\Config::addControllerPath(__DIR__ . '/../../controllers/');
foreach(array('admin','applicants','manage','scores','setup') as $path){
$path = \realPath(__DIR__ . '/../../controllers/' . $path);
\Foundation\VC\Config::addControllerPath($path . '/');
//scan the directory but drop the relative paths
foreach(array_diff(scandir($path), array('.','..')) as $fileName){
$controller = basename($fileName, '.php');
\Foundation\VC\Config::includeController($controller);
$class = \Foundation\VC\Config::getControllerClassName($controller);
$arr = array('name'=> $controller, 'actions'=>array());
foreach(get_class_methods($class) as $method){
if(substr($method, 0, 6) == 'action'){
$constant = 'ACTION_' . strtoupper(substr($method, 6));
if(defined("{$class}::{$constant}")){
$ra = new \Jazzee\Entity\RoleAction();
$ra->setController($controller);
$ra->setAction(substr($method, 6));
$ra->setRole($role);
$em->persist($ra);
}
}
}
}
}
$em->flush();
$output->write("<info>Administrator role created</info>" . PHP_EOL);
}
}<file_sep><?php
/**
* StandardPage Answer Status Element
* @author <NAME> <<EMAIL>>
* @license http://jazzee.org/license.txt
* @package jazzee
* @subpackage apply
*/
?>
<table>
<thead>
<tr>
<th>Scores</th>
<th>Status</th>
</tr>
</thead>
<tbody>
<?php
if($answers = $page->getJazzeePage()->getAnswers()){ ?>
<?php foreach($answers as $answer){?>
<tr>
<td>
<?php print $page->getPage()->getElementByFixedId(\Jazzee\Page\ETSMatch::FID_TEST_TYPE)->getJazzeeElement()->displayValue($answer);?><br />
<?php print $page->getPage()->getElementByFixedId(\Jazzee\Page\ETSMatch::FID_REGISTRATION_NUMBER)->getJazzeeElement()->displayValue($answer);?><br />
<?php print $page->getPage()->getElementByFixedId(\Jazzee\Page\ETSMatch::FID_TEST_DATE)->getJazzeeElement()->displayValue($answer);?>
</td>
<td>
<?php if($answer->getPublicStatus()){?><br />Status: <?php print $answer->getPublicStatus()->getName();?> <br /> <?php }?>
Score Status:
<?php if($answer->getMatchedScore()){?>
Score received for test taken on <?php print $answer->getMatchedScore()->getTestDate()->format('F jS Y')?>.
<?php } else { ?>
This score has not been received from ETS.
<?php }?>
</td>
</tr>
<?php }
}
?>
</tbody>
</table><file_sep><?php
/**
* lor complete view
* Shows only the message that the recommendation has already been submitted
* @author <NAME> <<EMAIL>>
* @license http://jazzee.org/license.txt
* @package jazzee
* @subpackage lor
*/
?>
<p>This recommendation has already been completed.</p><file_sep>/**
* The JazzeePageRecommenders type
@extends JazzeePage
*/
function JazzeePageRecommenders(){}
JazzeePageRecommenders.prototype = new JazzeePage();
JazzeePageRecommenders.prototype.constructor = JazzeePageRecommenders;
/**
* Create a new RecommendersPage with good default values
* @param {String} id the id to use
* @returns {RecommendersPage}
*/
JazzeePageRecommenders.prototype.newPage = function(id,title,typeId,typeName,typeClass,status,pageBuilder){
var page = JazzeePage.prototype.newPage.call(this, id,title,typeId,typeName,typeClass,status,pageBuilder);
page.setVariable('lorDeadline', '');
page.setVariable('lorDeadlineEnforced', 0);
page.setVariable('lorWaitDays', 14);
page.setVariable('recommenderEmailText', "Dear _RECOMMENDER_FIRST_NAME_ _RECOMMENDER_LAST_NAME_,\n"
+ "_APPLICANT_NAME_ has requested a letter of recommendation from you in support of their application for admission to our program. \n"
+ "We use an online system to collect letters of recommendation. You have been assigned a unique URL for accessing this system. Please save this email so that you can return to your letter at a later date. \n"
+ "Click the following link to access the online system; or, you may need to copy and paste this link into your browser. \n"
+ "_LINK_ \n");
return page;
};
JazzeePageRecommenders.prototype.workspace = function(){
JazzeePage.prototype.workspace.call(this);
var pageClass = this;
$('#pageToolbar').append(this.pagePropertiesButton());
$('#workspace').append(this.editLorPage());
};
/**
* Create the page properties dropdown
*/
JazzeePageRecommenders.prototype.pageProperties = function(){
var pageClass = this;
var div = $('<div>');
div.append(this.isRequiredButton());
div.append(this.showAnswerStatusButton());
var slider = $('<div>');
slider.slider({
value: this.min,
min: 0,
max: 20,
step: 1,
slide: function( event, ui ) {
pageClass.setProperty('min', ui.value);
$('#minValue').html(pageClass.min == 0?'No Minimum':pageClass.min);
}
});
div.append($('<p>').html('Minimum Recommendations Required ').append($('<span>').attr('id', 'minValue').html(this.min == 0?'No Minimum':this.min)));
div.append(slider);
var slider = $('<div>');
slider.slider({
value: this.max,
min: 0,
max: 20,
step: 1,
slide: function( event, ui ) {
pageClass.setProperty('max', ui.value);
$('#maxValue').html(pageClass.max == 0?'No Maximum':pageClass.max);
}
});
div.append($('<p>').html('Maximum Recommendations Allowed ').append($('<span>').attr('id', 'maxValue').html(this.max == 0?'No Maximum':this.max)));
div.append(slider);
var slider = $('<div>');
slider.slider({
value: this.getVariable('lorWaitDays'),
min: 0,
max: 20,
step: 1,
slide: function( event, ui ) {
pageClass.setVariable('lorWaitDays', ui.value);
$('#lorWaitDays').html(pageClass.getVariable('lorWaitDays') == 0?'No Wait':pageClass.getVariable('lorWaitDays'));
}
});
div.append($('<p>').html('Days the applicant must wait to send reminder email ').append($('<span>').attr('id', 'lorWaitDays').html(this.getVariable('lorWaitDays') == 0?'No Wait':this.getVariable('lorWaitDays'))));
div.append(slider);
if(!this.isGlobal || this.pageBuilder.editGlobal) div.append(this.editLOREmailButton());
if(!this.isGlobal || this.pageBuilder.editGlobal) div.append(this.deadlineEnforcedButton());
if(!this.isGlobal || this.pageBuilder.editGlobal) div.append(this.deadlineButton());
return div;
};
/**
* Edit the recommender email
* @return {jQuery}
*/
JazzeePageRecommenders.prototype.editLOREmailButton = function(){
var pageClass = this;
var obj = new FormObject();
var field = obj.newField({name: 'legend', value: 'Edit Email to Recommenders'});
var replace = [
{title: 'Applicant Name', replacement: '_APPLICANT_NAME_'},
{title: 'Recommendation Dealine', replacement:'_DEADLINE_'},
{title: 'Link to the Recommendation', replacement:'_LINK_'},
{title: 'Recommender First Name', replacement:'_RECOMMENDER_FIRST_NAME_'},
{title: 'Recommender Last Name', replacement:'_RECOMMENDER_LAST_NAME_'},
{title: 'Recommender Institution', replacement:'_RECOMMENDER_INSTITUTION_'},
{title: 'Recommender Phone', replacement:'_RECOMMENDER_EMAIL_'},
{title: 'Recommender Email', replacement:'_RECOMMENDER_PHONE_'}
];
field.instructions = 'The following will be replaced with the applicant input for this recommender: ';
for(var i in replace){
field.instructions += '<br />' + replace[i].replacement + ': ' + replace[i].title;
}
var element = field.newElement('Textarea', 'recommenderEmailText');
element.label = 'Email Text';
element.required = true;
element.value = this.getVariable('recommenderEmailText');
var dialog = this.displayForm(obj);
$('form', dialog).bind('submit',function(e){
pageClass.setVariable('recommenderEmailText', $('textarea[name="recommenderEmailText"]', this).val());
pageClass.workspace();
dialog.dialog("destroy").remove();
return false;
});//end submit
var button = $('<button>').html('Edit Email to Recommenders').bind('click',function(){
$('.qtip').qtip('api').hide();
dialog.dialog('open');
}).button({
icons: {
primary: 'ui-icon-pencil'
}
});
return button;
};
/**
* Button for choosing to enforce teh deadline
* @return {jQuery}
*/
JazzeePageRecommenders.prototype.deadlineEnforcedButton = function(){
var pageClass = this;
var span = $('<span>');
span.append($('<input>').attr('type', 'radio').attr('name', 'lorDeadlineEnforced').attr('id', 'enforced').attr('value', '1').attr('checked', this.getVariable('lorDeadlineEnforced')==1)).append($('<label>').html('Enforced').attr('for', 'enforced'));
span.append($('<input>').attr('type', 'radio').attr('name', 'lorDeadlineEnforced').attr('id', 'notenforced').attr('value', '0').attr('checked', this.getVariable('lorDeadlineEnforced')==0)).append($('<label>').html('Not Enforced').attr('for', 'notenforced'));
span.buttonset();
$('input', span).bind('change', function(e){
$('.qtip').qtip('api').hide();
pageClass.setVariable('lorDeadlineEnforced', $(e.target).val());
});
return $('<p>').html('Deadline: ').append(span);
};
/**
* Edit the recommender deadline
* @return {jQuery}
*/
JazzeePageRecommenders.prototype.deadlineButton = function(){
var pageClass = this;
var button = $('<button>').html('Set Recommendation Deadline').bind('click',function(){
$('.qtip').qtip('api').hide();
var dialog = pageClass.createDialog();
dialog.append($('<div>').attr('id', 'lorDeadlineForm').addClass('yui-g'));
pageClass.deadlineForm(pageClass.getVariable('lorDeadline')!='');
var button = $('<button>').html('Save').bind('click',function(){
if($('#lorDeadlineForm input[name="hasDeadline"]:checked').val() == 1){
pageClass.setVariable('lorDeadline', $('#lorDeadlineForm input[name="deadline"]').val());
} else {
pageClass.setVariable('lorDeadline', '');
}
pageClass.workspace();
dialog.dialog("destroy").remove();
return false;
}).button({
icons: {
primary: 'ui-icon-disk'
}
});
dialog.append(button);
dialog.dialog('open');
}).button({
icons: {
primary: 'ui-icon-pencil'
}
});
return button;
};
/**
* lorDeadline dialog content
* @param Boolean picker
* @return {jQuery}
*/
JazzeePageRecommenders.prototype.deadlineForm = function(picker){
var pageClass = this;
$('#lorDeadlineForm').empty();
if(picker){
var input = $('<input>').attr('type', 'text').attr('name', 'deadline').attr('id', 'deadline').attr('value', pageClass.getVariable('lorDeadline'));
$('#lorDeadlineForm').append($('<div>').addClass('yui-u first').append(input));
input.AnyTime_noPicker().AnyTime_picker({
labelTitle: 'Choose Deadline',
hideInput: true,
placement: 'inline'
});
}
var span = $('<span>');
span.append($('<input>').attr('type', 'radio').attr('name', 'hasDeadline').attr('id', 'seperate').attr('value', '1').attr('checked', picker)).append($('<label>').html('Seperate Deadline').attr('for', 'seperate'));
span.append($('<input>').attr('type', 'radio').attr('name', 'hasDeadline').attr('id', 'same').attr('value', '0').attr('checked', !picker)).append($('<label>').html('Same As Application').attr('for', 'same'));
span.buttonset();
$('input', span).bind('change', function(e){
pageClass.deadlineForm($(e.target).val() == 1);
});
$('#lorDeadlineForm').append($('<div>').addClass('yui-u').append(span));
};
/**
* Get the recommendation page (it is the first child)
* @returns {JazzeePage} | false
*/
JazzeePageRecommenders.prototype.getRecommendationPage = function(){
if($.isEmptyObject(this.children)) return false;
for (var firstId in this.children) break;
return this.children[firstId];
};
/**
* Edit the LOR page
*/
JazzeePageRecommenders.prototype.editLorPage = function(){
var pageClass = this;
var div = $('<div>');
var lorPage = this.getRecommendationPage();
if(!lorPage){
var dropdown = $('<ul>');
for(var i = 0; i < this.pageBuilder.pageTypes.length; i++){
if($.inArray('Jazzee\\Interfaces\\LorPage', this.pageBuilder.pageTypes[i].interfaces) > -1){
var item = $('<a>').html(this.pageBuilder.pageTypes[i].typeName).attr('href', '#').data('pageType', this.pageBuilder.pageTypes[i]);
item.bind('click', function(e){
var pageType = $(e.target).data('pageType');
var child = new window[pageType.typeClass].prototype.newPage('newchildpage' + pageClass.pageBuilder.getUniqueId(),'Recommendation',pageType.id,pageType.typeName,pageType.typeClass,'new',pageClass.pageBuilder);
pageClass.addChild(child);
pageClass.markModified();
div.replaceWith(pageClass.editLorPage());
return false;
});
dropdown.append($('<li>').append(item));
}
}
var button = $('<button>').html('Select Recommendation Page Type').button();
button.qtip({
position: {
my: 'bottom-left',
at: 'bottom-right'
},
show: {
event: 'click'
},
hide: {
event: 'unfocus click',
fixed: true
},
content: {
text: dropdown,
title: {
text: 'Choose a page type',
button: true
}
}
});
div.append(button)
} else {
var button = $('<button>').html('Edit Recommendation Page').data('page', lorPage).bind('click',function(){
var page = $(this).data('page');
page.workspace();
//empty the toolbar becuase the delete/copy are going to be wrong
$('#pageToolbar .copy').remove();
$('#pageToolbar .delete').remove();
$('#pageToolbar .properties').remove();
var button = $('<button>').html('Back to '+pageClass.title).bind('click', function(){
pageClass.workspace();
});
button.button({
icons: {
primary: 'ui-icon-arrowreturnthick-1-s'
}
});
$('#pageToolbar').prepend(button);
var button = $('<button>').html('Delete').data('page', page).bind('click', function(e){
$('#editPage').effect('explode',500);
pageClass.deleteChild($(e.target).parent().data('page'));
});
button.button({
icons: {
primary: 'ui-icon-trash'
}
});
$('#pageToolbar').append(button);
}).button({
icons: {
primary: 'ui-icon-pencil'
}
});
div.append(button);
}
return div;
};
<file_sep><?php
namespace Jazzee\Entity;
/**
* ElementAnswer
* Break down the response from each Element on a Page into an ElementAnswer
* In cases where there are multiple answers (like checkboxes) a single answer gets multiple rows by position
* @Entity
* @HasLifecycleCallbacks
* @Table(name="element_answers")
* @package jazzee
* @subpackage orm
**/
class ElementAnswer{
/**
* @Id
* @Column(type="bigint")
* @GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* @ManyToOne(targetEntity="Answer",inversedBy="elements")
* @JoinColumn(onDelete="CASCADE")
*/
private $answer;
/**
* @ManyToOne(targetEntity="Element")
* @JoinColumn(onDelete="CASCADE")
*/
private $element;
/** @Column(type="integer", nullable=true) */
private $position;
/** @Column(type="string", length=255, nullable=true) */
private $eShortString;
/** @Column(type="text", nullable=true) */
private $eText;
/** @Column(type="datetime", nullable=true) */
private $eDate;
/** @Column(type="integer", nullable=true) */
private $eInteger;
/** @Column(type="decimal", nullable=true) */
private $eDecimal;
/** @Column(type="text", nullable=true) */
private $eBlob;
/**
* Get id
*
* @return bigint $id
*/
public function getId(){
return $this->id;
}
/**
* Mark the lastUpdate automatically
* @PrePersist @PreUpdate
*/
public function markLastUpdate(){
$this->answer->markLastUpdate();
}
/**
* Set position
*
* @param integer $position
*/
public function setPosition($position){
$this->position = $position;
}
/**
* Get position
*
* @return integer $position
*/
public function getPosition(){
return $this->position;
}
/**
* Set eShortString
*
* @param string $eShortString
*/
public function setEShortString($eShortString){
$this->eShortString = $eShortString;
}
/**
* Get eShortString
*
* @return string $eShortString
*/
public function getEShortString(){
return $this->eShortString;
}
/**
* Set eText
*
* @param text $eText
*/
public function setEText($eText){
$this->eText = $eText;
}
/**
* Get eText
*
* @return text $eText
*/
public function getEText(){
return $this->eText;
}
/**
* Set eDate
*
* @param string $eDate
*/
public function setEDate($eDate){
$this->eDate = new \DateTime($eDate);
}
/**
* Get eDate
*
* @return \DateTime $eDate
*/
public function getEDate(){
return $this->eDate;
}
/**
* Set eInteger
*
* @param integer $eInteger
*/
public function setEInteger($eInteger){
$this->eInteger = $eInteger;
}
/**
* Get eInteger
*
* @return integer $eInteger
*/
public function getEInteger(){
return $this->eInteger;
}
/**
* Set eDecimal
*
* @param decimal $eDecimal
*/
public function setEDecimal($eDecimal){
$this->eDecimal = $eDecimal;
}
/**
* Get eDecimal
*
* @return decimal $eDecimal
*/
public function getEDecimal(){
return $this->eDecimal;
}
/**
* Set eBlob
*
* @param text $eBlob
*/
public function setEBlob($blob){
$this->eBlob = base64_encode($blob);
}
/**
* Get eBlob
*
* @return text $eBlob
*/
public function getEBlob(){
return base64_decode($this->eBlob);
}
/**
* Set element
*
* @param Entity\Element $element
*/
public function setElement(Element $element){
$this->element = $element;
}
/**
* Get element
*
* @return Entity\Element
*/
public function getElement(){
return $this->element;
}
/**
* Set answer
*
* @param Entity\Answer $answer
*/
public function setAnswer(Answer $answer){
$this->answer = $answer;
}
/**
* Get answer
*
* @return Entity\Answer $answer
*/
public function getAnswer(){
return $this->answer;
}
}<file_sep><?php
namespace Jazzee\Page;
/**
* A page with no form just text
*
* @author <NAME> <<EMAIL>>
* @license http://jazzee.org/license.txt
* @package jazzee
* @subpackage pages
*/
class Text implements \Jazzee\Interfaces\Page {
/**
* The ApplicationPage Entity
* @var \Jazzee\Entity\ApplicationPage
*/
protected $_applicationPage;
/**
* Our controller
* @var \Jazzee\Controller
*/
protected $_controller;
/**
* The Applicant
* @var \Jazzee\Entity\Applicant
*/
protected $_applicant;
/**
* Contructor
*
* @param \Jazzee\Entity\ApplicationPage $applicationPage
*/
public function __construct(\Jazzee\Entity\ApplicationPage $applicationPage){
$this->_applicationPage = $applicationPage;
}
/**
*
* @see Jazzee.Page::setController()
*/
public function setController(\Jazzee\Controller $controller){
$this->_controller = $controller;
}
/**
*
* @see Jazzee.Page::setApplicant()
*/
public function setApplicant(\Jazzee\Entity\Applicant $applicant){
$this->_applicant = $applicant;
}
/**
* TextPages are always complete
*/
public function getStatus(){
return self::COMPLETE;
}
public static function applyPageElement(){
return 'Text-apply_page';
}
public static function pageBuilderScriptPath(){
return 'resource/scripts/page_types/JazzeePageText.js';
}
/**
* No Special setup
* @return null
*/
public function setupNewPage(){
return;
}
/**
* By default just set the varialbe dont check it
* @param string $name
* @param string $value
*/
public function setVar($name, $value){
$var = $this->_applicationPage->getPage()->setVar($name, $value);
$this->_controller->getEntityManager()->persist($var);
}
}
?><file_sep><?php
/**
* Jazzee Test base class
* @author <NAME> <<EMAIL>>
* @license http://jazzee.org/license.txt
* @package jazzee
* @subpackage test
*/
if (isset($_GET['simpleTestPath'])){
define('SIMPLETEST_PATH', $_GET['simpleTestPath']);
} else {
define('SIMPLETEST_PATH', $_SERVER['DOCUMENT_ROOT'] . '/../simpletest');
}
if (!file_exists(SIMPLETEST_PATH . '/autorun.php')){
die('SIMPLE_TEST_PATH ' . SIMPLETEST_PATH . ' is incorect. Specify the path with GET simpleTestPath or use the default WEBROOT/../simpletest');
}
define('SOURCE_PATH', realpath(dirname(__FILE__) . '/../'));
require_once(SIMPLETEST_PATH . '/autorun.php');
require_once(SIMPLETEST_PATH . '/mock_objects.php');
/**
* unitTestCase for Jazzee
* Subclasses the simpletest UnitTestCase to allow for the addition of complex
* helper functions and assertions
*/
class Jazzee_Text extends UnitTestCase {}
?>
<file_sep><?php
/**
* manage_virtualfiles index view
* @author <NAME> <<EMAIL>>
* @license http://jazzee.org/license.txt
* @package jazzee
* @subpackage manage
*/
if($files): ?>
<h5>Files:</h5>
<ul>
<?php foreach($files as $file): ?>
<li><?php print $file->getName() ?>
(<a href='<?php print $this->path('virtualfile/'.$file->getName())?>'>Preview</a>)
<?php if($this->controller->checkIsAllowed('manage_virtualfiles', 'edit')): ?>
(<a href='<?php print $this->path('manage/virtualfiles/edit/') . $file->getId()?>'>Edit</a>)
<?php endif;?>
<?php if($this->controller->checkIsAllowed('manage_virtualfiles', 'delete')): ?>
(<a href='<?php print $this->path('manage/virtualfiles/delete/') . $file->getId()?>'>Delete</a>)
<?php endif;?>
</li>
<?php endforeach;?>
</ul>
<?php endif; ?>
<?php if($this->controller->checkIsAllowed('manage_virtualfiles', 'new')): ?>
<p><a href='<?php print $this->path('manage/virtualfiles/new')?>'>Add a New Virtual File</a></p>
<?php endif;?>
<file_sep><?php
namespace Jazzee\Element;
/**
* Select List Element
*
* @author <NAME> <<EMAIL>>
* @license http://jazzee.org/license.txt
* @package jazzee
* @subpackage elements
*/
class SelectList extends AbstractElement {
const PAGEBUILDER_SCRIPT = 'resource/scripts/element_types/JazzeeElementSelectList.js';
public function addToField(\Foundation\Form\Field $field){
$element = $field->newElement('SelectList', 'el' . $this->_element->getId());
$element->setLabel($this->_element->getTitle());
$element->setInstructions($this->_element->getInstructions());
$element->setFormat($this->_element->getFormat());
$element->setDefaultValue($this->_element->getDefaultValue());
if($this->_element->isRequired()){
$validator = new \Foundation\Form\Validator\NotEmpty($element);
$element->addValidator($validator);
$element->newItem('', 'Select ' . $this->_element->getTitle() . '...');
} else {
//only put a blank if it isn't required
$element->newItem('', '');
}
foreach($this->_element->getListItems() as $item){
if($item->isActive()) $element->newItem($item->getId(), $item->getValue());
}
return $element;
}
public function getElementAnswers($input){
$elementAnswers = array();
if(!is_null($input)){
$elementAnswer = new \Jazzee\Entity\ElementAnswer;
$elementAnswer->setElement($this->_element);
$elementAnswer->setPosition(0);
$elementAnswer->setEInteger($input);
$elementAnswers[] = $elementAnswer;
}
return $elementAnswers;
}
public function displayValue(\Jazzee\Entity\Answer $answer){
$elementsAnswers = $answer->getElementAnswersForElement($this->_element);
if(isset($elementsAnswers[0])){
return $this->_element->getItemById($elementsAnswers[0]->getEInteger())->getValue();
}
return null;
}
public function formValue(\Jazzee\Entity\Answer $answer){
$elementsAnswers = $answer->getElementAnswersForElement($this->_element);
if(isset($elementsAnswers[0])){
return $elementsAnswers[0]->getEInteger();
}
return null;
}
/**
* Perform a regular expression match on each value
* @param \Jazzee\Entity\Answer $answer
* @param \stdClass $obj
* @return boolean
*/
public function testQuery(\Jazzee\Entity\Answer $answer, \stdClass $obj){
$elementsAnswers = $answer->getElementAnswersForElement($this->_element);
if(!isset($elementsAnswers[0])){
return false;
}
return preg_match($obj->pattern, $this->_element->getItemById($elementsAnswers[0]->getEInteger())->getValue());
}
}
?><file_sep><?php
namespace Jazzee\Element;
/**
* The Abstract Application Element
*
* @author <NAME> <<EMAIL>>
* @license http://jazzee.org/license.txt
* @package jazzee
* @subpackage elements
*/
abstract class AbstractElement implements \Jazzee\Interfaces\Element {
/**
* The Element entity
* @var \Jazzee\Entity\Element
*/
protected $_element;
/**
* The controller that is using this
* @var \Jazzee\Controller
*/
protected $_controller;
public function __construct(\Jazzee\Entity\Element $element){
$this->_element = $element;
}
public function setController(\Jazzee\Controller $controller){
$this->_controller = $controller;
}
public function rawValue(\Jazzee\Entity\Answer $answer){
return html_entity_decode($this->displayValue($answer));
}
public function pdfValue(\Jazzee\Entity\Answer $answer, \Jazzee\ApplicantPDF $pdf){
return $this->rawValue($answer);
}
/**
* Abstract element kills all queries
*/
public function testQuery(\Jazzee\Entity\Answer $answer, \stdClass $obj){
return false;
}
}<file_sep><?php
/**
* setup_application index view
* @author <NAME> <<EMAIL>>
* @license http://jazzee.org/license.txt
* @package jazzee
*/
$dateFormat = 'l F jS Y g:ia'; ?>
<fieldset>
<legend>Contact Information
<?php if($this->controller->checkIsAllowed('setup_application', 'editContact')){ ?>
(<a href='<?php print $this->path('setup/application/editContact')?>'>Edit</a>)
<?php }?>
</legend>
Contact Name: <?php print $application->getContactName();?><br />
Contact Email: <?php print $application->getContactEmail();?><br />
</fieldset>
<fieldset>
<legend>Welcome Message
<?php if($this->controller->checkIsAllowed('setup_application', 'editWelcome')){ ?>
(<a href='<?php print $this->path('setup/application/editWelcome')?>'>Edit</a>)
<?php }?>
</legend>
<?php print $application->getWelcome();?>
</fieldset>
<?php
$statusMessages = array(
'StatusIncomplete' => 'Message for applicants who missed the deadline',
'StatusNoDecision' => 'Message for locked applicants with no decision',
'StatusAdmit' => 'Message for admitted applicants',
'StatusDeny' => 'Message for denied applicants',
'StatusAccept' => 'Message for applicants who accept their offer',
'StatusDecline' => 'Message for applicants who decline their offer'
);
$search = array(
'_Applicant_Name_',
'_Application_Deadline_',
'_Offer_Response_Deadline_',
'_SIR_Link_',
'_Admit_Letter_',
'_Deny_Letter_',
'_Admit_Date_',
'_Deny_Date_',
'_Accept_Date_',
'_Decline_Date_'
);
$someDate = new DateTime('midnight');
$replace = array(
'John Doe Applicant',
$application->getClose()?$application->getClose()->format($dateFormat):$someDate->format($dateFormat),
$someDate->format($dateFormat),
'#',
'#',
'#',
$someDate->format($dateFormat),
$someDate->format($dateFormat),
$someDate->format($dateFormat),
$someDate->format($dateFormat)
);
foreach($statusMessages as $status => $title){
?>
<fieldset>
<legend><?php print $title; ?>
<?php if($this->controller->checkIsAllowed('setup_application', 'edit' . $status)){ ?>
(<a href='<?php print $this->path('setup/application/edit' . $status)?>'>Edit</a>)
<?php }?>
</legend>
<?php $f = 'get' . $status . 'Text'; print str_replace($search, $replace,$application->$f());?>
</fieldset>
<?php } //end foreach status type ?>
<fieldset>
<legend>Status
<?php if($this->controller->checkIsAllowed('setup_application', 'editStatus')){ ?>
(<a href='<?php print $this->path('setup/application/editStatus')?>'>Edit</a>)
<?php }?>
</legend>
Application Opens: <?php print ($application->getOpen()?$application->getOpen()->format($dateFormat):'not set');?><br />
Application Closes: <?php print ($application->getClose()?$application->getClose()->format($dateFormat):'not set');?><br />
Program Begins: <?php print ($application->getBegin()?$application->getBegin()->format($dateFormat):'not set');?><br />
Visible: <?php print ($application->isVisible()?'Yes':'No'); ?><br />
</fieldset><file_sep><?php
namespace Jazzee\Entity;
/**
* ElementListItem
* Elements like selects and checkboxes have list items
* @Entity
* @HasLifecycleCallbacks
* @Table(name="element_list_items")
* @package jazzee
* @subpackage orm
**/
class ElementListItem{
/**
* @Id
* @Column(type="bigint")
* @GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* @ManyToOne(targetEntity="Element",inversedBy="listItems")
* @JoinColumn(onDelete="CASCADE")
*/
private $element;
/** @Column(type="integer") */
private $weight;
/** @Column(type="boolean") */
private $active = true;
/** @Column(type="string") */
private $value;
/**
* Get id
*
* @return bigint $id
*/
public function getId(){
return $this->id;
}
/**
* Generate a Temporary id
*
* This should only be used when we need to termporarily generate an item
* but have no intention of persisting it. Use a string to be sure we cant persist
*/
public function tempId(){
$this->id = uniqid('item');
}
/**
* Replace Page UUID
* @PreUpdate
*
* When an list items is modified it changes its page's UUID
*/
public function replacePageUuid(){
$this->element->replacePageUuid();
}
/**
* Set element
*
* @param Entity\Element $element
*/
public function setElement(Element $element){
$this->element = $element;
}
/**
* get element
*
* @return Entity\Element $element
*/
public function getElement(){
return $this->element;
}
/**
* Set weight
*
* @param integer $weight
*/
public function setWeight($weight){
$this->weight = $weight;
}
/**
* Get weight
*
* @return integer $weight
*/
public function getWeight(){
return $this->weight;
}
/**
* Make item active
*/
public function activate(){
$this->active = true;
}
/**
* Deactivate item
*/
public function deactivate(){
$this->active = false;
}
/**
* Check if item is active
* @return boolean $active
*/
public function isActive(){
return $this->active;
}
/**
* Set value
*
* @param string $value
*/
public function setValue($value){
$this->value = $value;
}
/**
* Get value
*
* @return string $value
*/
public function getValue(){
return $this->value;
}
}<file_sep><?php
namespace Jazzee\Entity;
/**
* Application
* Cycle+Program=Application
* Sets the unique preferences for a givien Cycle/Program and contains all of its Applicants
* @Entity(repositoryClass="\Jazzee\Entity\ApplicationRepository")
* @Table(name="applications",uniqueConstraints={@UniqueConstraint(name="program_cycle", columns={"program_id", "cycle_id"})})
*
* @package jazzee
* @subpackage orm
**/
class Application{
/**
* @Id
* @Column(type="bigint")
* @GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* @ManyToOne(targetEntity="Program")
* @JoinColumn(onDelete="CASCADE")
*/
private $program;
/**
* @ManyToOne(targetEntity="Cycle", inversedBy="applications")
* @JoinColumn(onDelete="CASCADE")
*/
private $cycle;
/**
* @OneToMany(targetEntity="Applicant", mappedBy="application")
*/
private $applicants;
/**
* @OneToMany(targetEntity="ApplicationPage", mappedBy="application")
* @OrderBy({"weight" = "ASC"})
*/
private $applicationPages;
/** @Column(type="string", nullable=true) */
private $contactName;
/** @Column(type="string", nullable=true) */
private $contactEmail;
/** @Column(type="text", nullable=true) */
private $welcome;
/** @Column(type="datetime", nullable=true) */
private $open;
/** @Column(type="datetime", nullable=true) */
private $close;
/** @Column(type="datetime", nullable=true) */
private $begin;
/** @Column(type="boolean") */
private $published;
/** @Column(type="boolean") */
private $visible;
/** @Column(type="text", nullable=true) */
private $admitLetter;
/** @Column(type="text", nullable=true) */
private $denyLetter;
/** @Column(type="text", nullable=true) */
private $statusIncompleteText;
/** @Column(type="text", nullable=true) */
private $statusNoDecisionText;
/** @Column(type="text", nullable=true) */
private $statusAdmitText;
/** @Column(type="text", nullable=true) */
private $statusDenyText;
/** @Column(type="text", nullable=true) */
private $statusAcceptText;
/** @Column(type="text", nullable=true) */
private $statusDeclineText;
public function __construct(){
$this->applicants = new \Doctrine\Common\Collections\ArrayCollection();
$this->published = false;
$this->visible = false;
}
/**
* Get id
*
* @return bigint $id
*/
public function getId(){
return $this->id;
}
/**
* Set contactName
*
* @param string $contactName
*/
public function setContactName($contactName){
$this->contactName = $contactName;
}
/**
* Get contactName
*
* @return string $contactName
*/
public function getContactName(){
return $this->contactName;
}
/**
* Set contactEmail
*
* @param string $contactEmail
*/
public function setContactEmail($contactEmail){
$this->contactEmail = $contactEmail;
}
/**
* Get contactEmail
*
* @return string $contactEmail
*/
public function getContactEmail(){
return $this->contactEmail;
}
/**
* Set welcome
*
* @param text $welcome
*/
public function setWelcome($welcome){
$this->welcome = $welcome;
}
/**
* Get welcome
*
* @return text $welcome
*/
public function getWelcome(){
return $this->welcome;
}
/**
* Set open
*
* @param string $open
*/
public function setOpen($open){
if(empty($open)){
$this->open = null;
} else {
$this->open = new \DateTime($open);
}
}
/**
* Get open
*
* @return \DateTime $open
*/
public function getOpen(){
return $this->open;
}
/**
* Set close
*
* @param string $close
*/
public function setClose($close){
if(empty($close)){
$this->close = $close;
} else {
$this->close = new \DateTime($close);
}
}
/**
* Get close
*
* @return DateTime $close
*/
public function getClose(){
return $this->close;
}
/**
* Set begin
*
* @param string $begin
*/
public function setBegin($begin){
if(empty($begin)){
$this->begin = null;
} else {
$this->begin = new \DateTime($begin);
}
}
/**
* Get begin
*
* @return \DateTime $begin
*/
public function getBegin(){
return $this->begin;
}
/**
* Publish and application
* @param boolean $override if this is true the application willbe published without checking
*/
public function publish($override = false){
if(!$override AND !$this->canPublish()){
throw new \Jazzee\Exception('Application cannot be published, it is not ready. Specify override if this should be ignored.');
}
$this->published = true;
}
/**
* Check if application is ready to be published
* @return boolean
*/
public function canPublish(){
foreach($this->cycle->getRequiredPages() as $requiredPage){
if(!$this->hasPage($requiredPage)){
return false;
}
}
return true;
}
/**
* Un Publish and application
*/
public function unPublish(){
$this->published = false;
}
/**
* Get published status
* @return boolean $published
*/
public function isPublished(){
return $this->published;
}
/**
* Make Application Visible
*/
public function visible(){
$this->visible = true;
}
/**
* Make Application InVisible
*/
public function inVisible(){
$this->visible = false;
}
/**
* Get visible status
*
* @return boolean $visible
*/
public function isVisible(){
return $this->visible;
}
/**
* Set admitLetter
*
* @param text $admitLetter
*/
public function setAdmitLetter($admitLetter){
$this->admitLetter = $admitLetter;
}
/**
* Get admitLetter
*
* @return text $admitLetter
*/
public function getAdmitLetter(){
return $this->admitLetter;
}
/**
* Set denyLetter
*
* @param text $denyLetter
*/
public function setDenyLetter($denyLetter){
$this->denyLetter = $denyLetter;
}
/**
* Get denyLetter
*
* @return text $denyLetter
*/
public function getDenyLetter(){
return $this->denyLetter;
}
/**
* Set statusIncompleteText
*
* @param text $statusIncompleteText
*/
public function setStatusIncompleteText($statusIncompleteText){
$this->statusIncompleteText = $statusIncompleteText;
}
/**
* Get statusIncompleteText
*
* @return text $statusIncompleteText
*/
public function getStatusIncompleteText(){
return $this->statusIncompleteText;
}
/**
* Set statusNoDecisionText
*
* @param text $statusNoDecisionText
*/
public function setStatusNoDecisionText($statusNoDecisionText){
$this->statusNoDecisionText = $statusNoDecisionText;
}
/**
* Get statusNoDecisionText
*
* @return text $statusNoDecisionText
*/
public function getStatusNoDecisionText(){
return $this->statusNoDecisionText;
}
/**
* Set statusAdmitText
*
* @param text $statusAdmitText
*/
public function setStatusAdmitText($statusAdmitText){
$this->statusAdmitText = $statusAdmitText;
}
/**
* Get statusAdmitText
*
* @return text $statusAdmitText
*/
public function getStatusAdmitText(){
return $this->statusAdmitText;
}
/**
* Set statusDenyText
*
* @param text $statusDenyText
*/
public function setStatusDenyText($statusDenyText){
$this->statusDenyText = $statusDenyText;
}
/**
* Get statusDenyText
*
* @return text $statusDenyText
*/
public function getStatusDenyText(){
return $this->statusDenyText;
}
/**
* Set statusAcceptText
*
* @param text $statusAcceptText
*/
public function setStatusAcceptText($statusAcceptText){
$this->statusAcceptText = $statusAcceptText;
}
/**
* Get statusAcceptText
*
* @return text $statusAcceptText
*/
public function getStatusAcceptText(){
return $this->statusAcceptText;
}
/**
* Set statusDeclineText
*
* @param text $statusDeclineText
*/
public function setStatusDeclineText($statusDeclineText){
$this->statusDeclineText = $statusDeclineText;
}
/**
* Get statusDeclineText
*
* @return text $statusDeclineText
*/
public function getStatusDeclineText(){
return $this->statusDeclineText;
}
/**
* Set program
*
* @param Entity\Program $program
*/
public function setProgram(Program $program){
$this->program = $program;
}
/**
* Get program
*
* @return Entity\Program $program
*/
public function getProgram(){
return $this->program;
}
/**
* Set cycle
*
* @param Entity\Cycle $cycle
*/
public function setCycle(Cycle $cycle){
$this->cycle = $cycle;
}
/**
* Get cycle
*
* @return Entity\Cycle $cycle
*/
public function getCycle(){
return $this->cycle;
}
/**
* Get applicants
*
* @return \Doctrine\Common\Collections\Collection \Jazzee\Entity\Applicant
*/
public function getApplicants(){
return $this->applicants;
}
/**
* Get pages
* @param string $kind optionally only incude certain pages
* @return array \Jazzee\Entity\ApplicationPage
*/
public function getApplicationPages($kind = null){
if(!$this->applicationPages) return array();
if(is_null($kind)) return $this->applicationPages->toArray();
$applicationPages = array();
foreach($this->applicationPages as $applicationPage) if($applicationPage->getKind() == $kind) $applicationPages[] = $applicationPage;
return $applicationPages;
}
/**
* Check if application has a page
* @param Page $page
* @return boolean
*/
public function hasPage(Page $page){
if(!$this->applicationPages) return false;
foreach($this->applicationPages as $applicationPage){
if($applicationPage->getPage() == $page){
return true;
}
}
return false;
}
/**
* Get page by tile
* @param string $title
* @return ApplicationPage
*/
public function getApplicationPageByTitle($title){
foreach($this->applicationPages as $applicationPage){
if($applicationPage->getTitle() == $title){
return $applicationPage;
}
}
return false;
}
}
/**
* ApplicationRepository
* Special Repository methods for Application to make searchign for special conditions easier
* @package jazzee
* @subpackage orm
*/
class ApplicationRepository extends \Doctrine\ORM\EntityRepository{
/**
* findOneByProgramAndCycle
* Search for an Application using its Program and Cycle
* @param Program $program
* @param Cycle $cycle
* @return Application
*/
public function findOneByProgramAndCycle(Program $program, Cycle $cycle){
$query = $this->_em->createQuery('SELECT a FROM Jazzee\Entity\Application a WHERE a.program = :programId AND a.cycle = :cycleId');
$query->setParameter('programId', $program->getId());
$query->setParameter('cycleId', $cycle->getId());
$result = $query->getResult();
if(count($result)) return $result[0];
return false;
}
/**
* findByProgram
* Search for all the Applications belonging to a program
* @param Program $program
* @return Doctrine\Common\Collections\Collection $applications
*/
public function findByProgram(Program $program){
$query = $this->_em->createQuery('SELECT a FROM Jazzee\Entity\Application a JOIN a.cycle c WHERE a.program = :programId ORDER BY c.start DESC');
$query->setParameter('programId', $program->getId());
return $query->getResult();
}
/**
* Find an application be the program short name and cycle name
*
* @param string $programShortName
* @param string $cycleNamme
* @return Application
*/
public function findEasy($programShortName, $cycleName){
$query = $this->_em->createQuery('SELECT a FROM Jazzee\Entity\Application a WHERE a.program = (SELECT p FROM Jazzee\Entity\Program p WHERE p.shortName = :programShortName) AND a.cycle = (SELECT c FROM \Jazzee\Entity\Cycle c WHERE c.name= :cycleName)');
$query->setParameter('programShortName', $programShortName);
$query->setParameter('cycleName', $cycleName);
$result = $query->getResult();
if(count($result)) return $result[0];
return false;
}
}<file_sep><?php
/**
* manage_roles index view
* @author <NAME> <<EMAIL>>
* @license http://jazzee.org/license.txt
* @package jazzee
* @subpackage manage
*/
if($roles): ?>
<h5>Roles:</h5>
<ul>
<?php foreach($roles as $role): ?>
<li><?php print $role->getName() ?>
<?php if($this->controller->checkIsAllowed('manage_roles', 'edit')): ?>
(<a href='<?php print $this->path('manage/roles/edit/') . $role->getId()?>'>Edit</a>)
<?php endif;?>
<?php if($this->controller->checkIsAllowed('manage_roles', 'copy')): ?>
(<a href='<?php print $this->path('manage/roles/copy/') . $role->getId()?>'>Copy</a>)
<?php endif;?>
<?php if($this->controller->checkIsAllowed('manage_roles', 'applytemplate')): ?>
(<a href='<?php print $this->path('manage/roles/applytemplate/') . $role->getId()?>'>Use as template</a>)
<?php endif;?>
</li>
<?php endforeach;?>
</ul>
<?php endif; ?>
<?php if($this->controller->checkIsAllowed('manage_roles', 'new')): ?>
<p><a href='<?php print $this->path('manage/roles/new')?>'>Add a new role</a></p>
<?php endif;?>
<file_sep><?php
/**
* apply_page Text page types view
* @author <NAME> <<EMAIL>>
* @license http://jazzee.org/license.txt
* @package jazzee
* @subpackage apply
*/
?>
<div id='leadingText'><?php print $page->getLeadingText()?></div>
<div id='trailingText'><?php print $page->getTrailingText()?></div><file_sep><?php
/**
* Loads Virtual Files
*
* @author <NAME> <<EMAIL>>
* @license http://jazzee.org/license.txt
* @package jazzee
*/
class VirtualfileController extends \Jazzee\Controller{
/**
* Output a single file
* @param string $name
*/
public function actionGet($name){
if($file = $this->_em->getRepository('\Jazzee\Entity\VirtualFile')->findOneBy(array('name'=>$name))){
$virtualFile = new \Foundation\Virtual\VirtualFile($file->getName(), $file->getContents());
$virtualFile->output();
}
//send a 404
$request = new Lvc_Request();
$request->setControllerName('error');
$request->setActionName('index');
$request->setActionParams(array('error' => '404', 'message'=>'File Not Found'));
// Get a new front controller without any routers, and have it process our handmade request.
$fc = new Lvc_FrontController();
$fc->processRequest($request);
exit();
}
}
?><file_sep><?php
namespace Jazzee\Element;
/**
* PDF File Element
*
* @author <NAME> <<EMAIL>>
* @license http://jazzee.org/license.txt
* @package jazzee
* @subpackage elements
*/
class PDFFileInput extends AbstractElement {
const PAGEBUILDER_SCRIPT = 'resource/scripts/element_types/JazzeeElementPDFFileInput.js';
public function addToField(\Foundation\Form\Field $field){
if(!ini_get('file_uploads')){
throw new \Jazzee\Exception('File uploads are not turned on for this system and a PDFFileInputElement is being created', E_ERROR);
}
$element = $field->newElement('FileInput', 'el' . $this->_element->getId());
$element->setLabel($this->_element->getTitle());
$element->setInstructions($this->_element->getInstructions());
$element->setFormat($this->_element->getFormat());
$element->setDefaultValue($this->_element->getDefaultValue());
if($this->_element->isRequired()){
$validator = new \Foundation\Form\Validator\NotEmpty($element);
$element->addValidator($validator);
}
$element->addValidator(new \Foundation\Form\Validator\Virusscan($element));
$element->addValidator(new \Foundation\Form\Validator\PDF($element));
$element->addFilter(new \Foundation\Form\Filter\Blob($element));
$config = $this->_controller->getConfig();
$max = $config->getMaximumApplicantFileUploadSize();
if($this->_element->getMax() and \Foundation\Utility::convertIniShorthandValue($this->_element->getMax()) < $max) $max = $this->_element->getMax();
$element->addValidator(new \Foundation\Form\Validator\MaximumFileSize($element, $max));
return $element;
}
public function getElementAnswers($input){
$elementAnswers = array();
if(!is_null($input)){
$elementAnswer = new \Jazzee\Entity\ElementAnswer;
$elementAnswer->setElement($this->_element);
$elementAnswer->setPosition(0);
$elementAnswer->setEBlob($input);
$elementAnswers[] = $elementAnswer;
//create the preview image
try{
$im = new \imagick;
$im->readimageblob($input);
$im->setiteratorindex(0);
$im->setImageFormat("png");
$im->scaleimage(100, 0);
} catch (ImagickException $e){
$im = new \imagick;
$im->readimage(realpath(__DIR__ . '/../../../../lib/foundation/src/media/default_pdf_logo.png'));
$im->scaleimage(100, 0);
}
$elementAnswer = new \Jazzee\Entity\ElementAnswer;
$elementAnswer->setElement($this->_element);
$elementAnswer->setPosition(1);
$elementAnswer->setEBlob($im->getimageblob());
$elementAnswers[] = $elementAnswer;
}
return $elementAnswers;
}
public function displayValue(\Jazzee\Entity\Answer $answer){
$elementAnswers = $answer->getElementAnswersForElement($this->_element);
if(isset($elementAnswers[0])){
$base = $answer->getApplicant()->getFullName() . ' ' . $this->_element->getTitle() . '_' . $answer->getApplicant()->getId() . $elementAnswers[0]->getId();
$pdfName = $base . '.pdf';
$pngName = $base . 'preview.png';
if(!$pdfFile = $this->_controller->getStoredFile($pdfName) or $pdfFile->getLastModified() < $answer->getUpdatedAt()){
$this->_controller->storeFile($pdfName, $elementAnswers[0]->getEBlob());
}
if(!$pngFile = $this->_controller->getStoredFile($pngName) or $pngFile->getLastModified() < $answer->getUpdatedAt()){
$this->_controller->storeFile($pngName, $elementAnswers[1]->getEBlob());
}
return '<a href="' . $this->_controller->path('file/' . \urlencode($pdfName)) . '"><img src="' . $this->_controller->path('file/' . \urlencode($pngName)) . '" /></a>';
}
return null;
}
public function rawValue(\Jazzee\Entity\Answer $answer){
$elementsAnswers = $answer->getElementAnswersForElement($this->_element);
if(isset($elementsAnswers[0])){
return base64_encode($elementsAnswers[0]->getEBlob());
}
return null;
}
public function pdfValue(\Jazzee\Entity\Answer $answer, \Jazzee\ApplicantPDF $pdf){
$elementsAnswers = $answer->getElementAnswersForElement($this->_element);
if(isset($elementsAnswers[0])){
$pdf->addPdf($elementsAnswers[0]->getEBlob());
return 'Attached';
}
return null;
}
public function formValue(\Jazzee\Entity\Answer $answer){
return false;
}
}
?><file_sep><?php
namespace Jazzee;
/**
* Empty Base class for local customization
*
* This class is designed to be an easy override point for customizations
* without having to worry about or mess with the JazzeeConfiguration
* @package jazzee
*/
class Configuration extends JazzeeConfiguration{}<file_sep><?php
namespace Jazzee\PaymentType;
/**
* Pay by check
*
* @author <NAME> <<EMAIL>>
* @license http://jazzee.org/license.txt
* @package jazzee
* @subpackage paymenttypes
*/
class Check extends AbstractPaymentType{
const APPLY_PAGE_ELEMENT = 'CheckPayment-apply_page';
const APPLICANTS_SINGLE_ELEMENT = 'CheckPayment-applicants_single';
public function paymentForm(\Jazzee\Entity\Applicant $applicant, $amount){
$form = new \Foundation\Form();
$form->setAction($this->_controller->getActionPath());
$form->newHiddenElement('amount', $amount);
$field = $form->newField();
$field->setLegend($this->_paymentType->getName());
$field = $form->newField();
$instructions = "<p><strong>Application Fee:</strong> ${$amount}</p>";
$instructions .= '<p><strong>Make Checks Payable to:</strong> ' . $this->_paymentType->getVar('payable') . '</p>';
if($this->_paymentType->getVar('address')) $instructions .= '<p><h4>Mail Check to:</h4>' . nl2br($this->_paymentType->getVar('address')) . '</p>';
if($this->_paymentType->getVar('coupon')) $instructions .= '<p><h4>Include the following information with your payment:</h4> ' . nl2br($this->_paymentType->getVar('coupon')) . '</p>';
$search = array(
'_Applicant_Name_',
'_Applicant_ID_',
'_Program_Name_',
'_Program_ID_'
);
$replace = array();
$replace[] = $applicant->getFirstName() . ' ' . $applicant->getLastName();
$replace[] = $applicant->getId();
$replace[] = $applicant->getApplication()->getProgram()->getName();
$replace[] = $applicant->getApplication()->getProgram()->getId();
$instructions = str_ireplace($search, $replace, $instructions);
$instructions .= '<p>Click the Pay By Check button to pay your fee by check. Your account will be temporarily credited and you can complete your application. Your application will not be reviewed until your check is recieved.</p>';
$field->setInstructions($instructions);
$form->newButton('submit', 'Pay By Check');
return $form;
}
public function getSetupForm(){
$filters = array(
'Applicant Name' => '_Applicant_Name_',
'Applicant ID' => '_Applicant_ID_',
'Program Name' => '_Program_Name_',
'Program ID' => '_Program_ID_'
);
$instructions = 'These wildcards will be replaced in the text of each element: ';
foreach($filters as $title => $wildcard){
$instructions .= "<br />{$title}:{$wildcard}";
}
$form = new \Foundation\Form();
$field = $form->newField();
$field->setLegend('Setup Payment');
$field->setInstructions($instructions);
$element = $field->newElement('TextInput','name');
$element->setLabel('Payment Name');
$element->setValue($this->_paymentType->getName());
$element->addValidator(new \Foundation\Form\Validator\NotEmpty($element));
$element = $field->newElement('TextInput','payable');
$element->setLabel('Make the check payable to');
$element->setValue($this->_paymentType->getVar('payable'));
$element->addValidator(new \Foundation\Form\Validator\NotEmpty($element));
$element = $field->newElement('Textarea','address');
$element->setLabel('Address to send the check to');
$element->setValue($this->_paymentType->getVar('address'));
$element->addValidator(new \Foundation\Form\Validator\NotEmpty($element));
$element = $field->newElement('Textarea','coupon');
$element->setLabel('Text for Payment Coupon');
$element->setValue($this->_paymentType->getVar('coupon'));
$element->addValidator(new \Foundation\Form\Validator\NotEmpty($element));
$form->newButton('submit', 'Save');
return $form;
}
public function setup(\Foundation\Form\Input $input){
$this->_paymentType->setName($input->get('name'));
$this->_paymentType->setClass('\\Jazzee\\PaymentType\\Check');
$this->_paymentType->setVar('payable', $input->get('payable'));
$this->_paymentType->setVar('address', $input->get('address'));
$this->_paymentType->setVar('coupon', $input->get('coupon'));
}
/**
* Check Payments are pending with no verification
* @see ApplyPaymentInterface::pendingPayment()
*/
function pendingPayment(\Jazzee\Entity\Payment $payment, \Foundation\Form\Input $input){
$payment->setAmount($input->get('amount'));
$payment->pending();
return true;
}
/**
* Record the check number and the deposit date for a payment
* @see ApplyPaymentInterface::settlePaymentForm()
*/
function getSettlePaymentForm(\Jazzee\Entity\Payment $payment){
$form = new \Foundation\Form();
$field = $form->newField();
$field->setLegend('Settle Payment');
$element = $field->newElement('TextInput','checkNumber');
$element->setLabel('Check Number');
$element->addValidator(new \Foundation\Form\Validator\NotEmpty($element));
$element = $field->newElement('DateInput','checkSettlementDate');
$element->setLabel('The Date the check was settled');
$element->setValue('today');
$element->addValidator(new \Foundation\Form\Validator\NotEmpty($element));
$element->addValidator(new \Foundation\Form\Validator\DateBefore($element, 'tomorrow'));
$element->addFilter(new \Foundation\Form\Filter\DateFormat($element, 'c'));
$form->newButton('submit', 'Save');
return $form;
}
/**
* Once checks have been cashed we settle the payment
* @see ApplyPaymentInterface::settlePayment()
*/
function settlePayment(\Jazzee\Entity\Payment $payment, \Foundation\Form\Input $input){
$payment->settled();
$payment->setVar('checkNumber', $input->get('checkNumber'));
$payment->setVar('checkSettlementDate', $input->get('checkSettlementDate'));
return true;
}
/**
* Record the reason the payment was refunded
* @see ApplyPaymentInterface::rejectPaymentForm()
*/
function getRejectPaymentForm(\Jazzee\Entity\Payment $payment){
$form = new \Foundation\Form();
$field = $form->newField();
$field->setLegend('Reject Payment');
$element = $field->newElement('Textarea','rejectedReason');
$element->setLabel('Reason displayed to Applicant');
$element->addValidator(new \Foundation\Form\Validator\NotEmpty($element));
$form->newButton('submit', 'Save');
return $form;
}
/**
* Check payments are refunded outside Jazzee and then marked as refunded
* @see ApplyPaymentInterface::refundPayment()
*/
function rejectPayment(\Jazzee\Entity\Payment $payment, \Foundation\Form\Input $input){
$payment->rejected();
$payment->setVar('rejectedReason', $input->get('rejectedReason'));
return true;
}
/**
* Record the reason the payment was refunded
* @see ApplyPaymentInterface::rejectPaymentForm()
*/
function getRefundPaymentForm(\Jazzee\Entity\Payment $payment){
$form = new \Foundation\Form();
$field = $form->newField();
$field->setLegend('Refund Payment');
$element = $field->newElement('Textarea','refundedReason');
$element->setLabel('Reason displayed to Applicant');
$element->addValidator(new \Foundation\Form\Validator\NotEmpty($element));
$form->newButton('submit', 'Save');
return $form;
}
/**
* Check payments are refunded outside Jazzee and then marked as refunded
* @see ApplyPaymentInterface::refundPayment()
*/
function refundPayment(\Jazzee\Entity\Payment $payment, \Foundation\Form\Input $input){
$payment->refunded();
$payment->setVar('refundedReason', $input->get('refundedReason'));
return true;
}
}<file_sep><?php
namespace Jazzee\Interfaces;
/**
* PDF Page interface
* Pages which implement this can generate PDF sections
*
* @author <NAME> <<EMAIL>>
* @license http://jazzee.org/license.txt
* @package jazzee
* @subpackage pages
*/
interface PdfPage
{
/**
* Build the pdf section for this page type
*
* @param \Jazzee\ApplicantPDF
*/
function renderPdfSection(\Jazzee\ApplicantPDF $pdf);
}<file_sep><?php
/**
* manage_elementtypes index view
* @author <NAME> <<EMAIL>>
* @license http://jazzee.org/license.txt
* @package jazzee
* @subpackage manage
*/
if($elementTypes): ?>
<h5>Current Element Types:</h5>
<ul>
<?php foreach($elementTypes as $type): ?>
<li><?php print $type->getName() ?>
<?php if($this->controller->checkIsAllowed('manage_elementtypes', 'edit')): ?>
(<a href='<?php print $this->path('manage/elementtypes/edit/') . $type->getId()?>'>Edit</a>)
<?php endif;?>
</li>
<?php endforeach;?>
</ul>
<?php endif; ?>
<?php if($this->controller->checkIsAllowed('manage_elementtypes', 'new')): ?>
<p><a href='<?php print $this->path('manage/elementtypes/new')?>'>Add a New Element Type</a></p>
<?php endif;?>
<file_sep><?php
namespace Jazzee;
/**
* Empty Base class for customization
*
* This class is designed to be an easy override point for customizations
* without having to worry about or mess with the JazzeePageController
* @package jazzee
*/
class PageController extends JazzeePageController{}<file_sep><?php
/**
* Display Dates in a nice form
* Can be overridden by themes
* @author <NAME> <<EMAIL>>
* @license http://jazzee.org/license.txt
* @package jazzee
* @subpackage apply
*/
if($date)
echo date('m/d/Y', strtotime($date)) ?><file_sep><?php
/**
* sir_status_page Standard page type view
* @author <NAME> <<EMAIL>>
* @license http://jazzee.org/license.txt
* @package jazzee
* @subpackage apply
*/
?>
<div id='leadingText'><?php print $applicationPage->getLeadingText()?></div>
<?php
$form = $applicationPage->getJazzeePage()->getForm();
$form->newHiddenElement('confirm', $confirm);
$this->renderElement('form', array('form'=> $form));
?>
<div id='trailingText'><?php print $applicationPage->getTrailingText()?></div><file_sep><?php
/**
* Manage Global Pages
* @author <NAME> <<EMAIL>>
* @package jazzee
* @subpackage manage
*/
class ManageGlobalpagesController extends \Jazzee\PageBuilder {
const MENU = 'Manage';
const TITLE = 'Global Pages';
const PATH = 'manage/globalpages';
const ACTION_INDEX = 'Edit Global Pages';
const REQUIRE_APPLICATION = false;
/**
* Add the required JS
*/
public function setUp(){
parent::setUp();
$this->addScript($this->path('resource/scripts/controllers/manage_globalpages.controller.js'));
}
/**
* List the application Pages
*/
public function actionListPages(){
$pages = array();
foreach($this->_em->getRepository('\Jazzee\Entity\Page')->findByIsGlobal(true) AS $page){
$pages[] = $this->pageArray($page);
}
$this->setVar('result', $pages);
$this->loadView($this->controllerName . '/result');
}
/**
* Save data from editing a page
* @param integer $pageId
*/
public function actionSavePage($pageId){
$data = json_decode($this->post['data']);
switch($data->status){
case 'delete':
if($page = $this->_em->getRepository('\Jazzee\Entity\Page')->findOneBy(array('id'=>$pageId, 'isGlobal'=>true))){
$applicationPages = $this->_em->getRepository('\Jazzee\Entity\ApplicationPage')->findBy(array('page' => $page->getId()));
if($applicationPages){
$this->setLayoutVar('status', 'error');
$this->addMessage('error',$page->getTitle() . ' could not be deleted becuase it is part of at least one application');
} else if($this->_em->getRepository('\Jazzee\Entity\Page')->hasAnswers($page)){
$this->setLayoutVar('status', 'error');
$this->addMessage('error',$page->getTitle() . ' could not be deleted becuase it has applicant information associated with it.');
} else {
$this->addMessage('success',$page->getTitle() . ' deleted');
$this->_em->remove($page);
}
}
break;
case 'import':
$page = new \Jazzee\Entity\Page();
$page->makeGlobal();
$page->setType($this->_em->getRepository('\Jazzee\Entity\PageType')->find($data->typeId));
$page->setUuid($data->uuid);
$this->savePage($page, $data);
break;
case 'new':
$page = new \Jazzee\Entity\Page();
$page->makeGlobal();
$page->setType($this->_em->getRepository('\Jazzee\Entity\PageType')->find($data->typeId));
//create a fake application page to work with so we can run setupNewPage
$ap = new \Jazzee\Entity\ApplicationPage();
$ap->setPage($page);
$ap->getJazzeePage()->setController($this);
$ap->getJazzeePage()->setupNewPage();
$this->addMessage('success',$data->title . ' created.');
unset($ap);
$this->savePage($page, $data);
break;
default:
$page = $this->_em->getRepository('\Jazzee\Entity\Page')->findOneBy(array('id'=>$pageId, 'isGlobal'=>true));
$this->savePage($page, $data);
}
}
public static function isAllowed($controller, $action, \Jazzee\Entity\User $user = null, \Jazzee\Entity\Program $program = null, \Jazzee\Entity\Application $application = null){
//all action authorizations are controlled by the index action
return parent::isAllowed($controller, 'index', $user, $program, $application);
}
}<file_sep><?php
namespace Jazzee\Interfaces;
/**
* XML Page interface
* Pages which implement this can generate XML
*
* @author <NAME> <<EMAIL>>
* @license http://jazzee.org/license.txt
* @package jazzee
* @subpackage pages
*/
interface XmlPage
{
/**
* Get the current answers as an xml element
* @param \DOMDocument $dom
* @return array DOMElement
*/
function getXmlAnswers(\DOMDocument $dom);
}<file_sep><?php
/**
* Routing for apply requests
*/
$fc = new \Foundation\VC\FrontController();
$basicRouter = new Lvc_RegexRewriteRouter;
//anything with a trailing slash gets redirected without it
//this should be done with modrewrite so we get a permanent redirect, but it is here in case
//modrewrite isn't available
$basicRouter->addRoute('#(.*)/$#', array(
'redirect' => 'index.php?url=$1'
));
//dynmaic files like applicant pdfs and previews stored in sessions
$basicRouter->addRoute('#^(?:.*)/?virtualfile/(.*)$#i', array(
'controller' => 'virtualfile',
'action' => 'get',
'action_params' => array(
'name' => 1
)
));
//resources in the virtual file system
$basicRouter->addRoute('#^(?:.*)/?resource/(.*)$#i', array(
'controller' => 'resource',
'action' => 'get',
'action_params' => array(
'path' => 1
)
));
//dynmaic files like applicant pdfs and previews stored in sessions
$basicRouter->addRoute('#^(?:.*)/?file/(.*)$#i', array(
'controller' => 'file',
'action' => 'get',
'action_params' => array(
'name' => 1
)
));
//static pulls physical files from the cache where they are created when first needed
$basicRouter->addRoute('#^(?:admin/)?static/(.*)$#i', array(
'controller' => 'static',
'action' => 'get',
'action_params' => array(
'fileName' => 1
)
));
//the apply page is the actual application
$basicRouter->addRoute('#^apply/([^/]+)/([^/]+)/page/([0-9]+)/?(?:(index|edit|delete)/([0-9]+)(/[0-9]+)?)?$#i', array(
'controller' => 'apply_page',
'action' => 4,
'action_params' => array(
'programShortName' => 1,
'cycleName' => 2,
'pageID' => 3,
'answerID' => 5
)
));
//special do type sends a second string to identify the method and an optional answerid
$basicRouter->addRoute('#^apply/([^/]+)/([^/]+)/page/([0-9]+)/do/([^/]+)/?([0-9]+)?$#i', array(
'controller' => 'apply_page',
'action' => 'do',
'action_params' => array(
'programShortName' => 1,
'cycleName' => 2,
'pageID' => 3,
'what' => 4,
'answerID' => 5
)
));
//apply welcome handles requests until we know which application we are seeing
$basicRouter->addRoute('#^apply/?([^/]*)/?([^/]*)$#i', array(
'controller' => 'apply_welcome',
'action' => 'index',
'action_params' => array(
'programShortName' => 1,
'cycleName' => 2
)
));
//apply welcome gets any blank requests
$basicRouter->addRoute('#^$#i', array(
'controller' => 'apply_welcome',
'action' => 'index'
));
//lor requests
$basicRouter->addRoute('#^lor/([^/]+)$#i', array(
'controller' => 'lor',
'action' => 'index',
'action_params' => array(
'urlKey' => 1
)
));
//applicant support
$basicRouter->addRoute('#^apply/([^/]+)/([^/]+)/support/?([^/]+)?/?([0-9]+)?$#i', array(
'controller' => 'apply_support',
'action' => 3,
'action_params' => array(
'programShortName' => 1,
'cycleName' => 2,
'id' => 4,
)
));
//applicant status
$basicRouter->addRoute('#^apply/([^/]+)/([^/]+)/status/?([^/]+)?$#i', array(
'controller' => 'apply_status',
'action' => 3,
'action_params' => array(
'programShortName' => 1,
'cycleName' => 2
)
));
//applicant status
$basicRouter->addRoute('#^apply/([^/]+)/([^/]+)/status/do/([^/]+)/([0-9]+)/?([0-9]+)?$#i', array(
'controller' => 'apply_status',
'action' => 'do',
'action_params' => array(
'programShortName' => 1,
'cycleName' => 2,
'what' => 3,
'pageId' => 4,
'answerId' => 5
)
));
//applicant status
$basicRouter->addRoute('#^apply/([^/]+)/([^/]+)/applicant/?(index|login|logout|new|forgotpassword)?$#i', array(
'controller' => 'apply_applicant',
'action' => 3,
'action_params' => array(
'programShortName' => 1,
'cycleName' => 2
)
));
//applicant status
$basicRouter->addRoute('#^apply/([^/]+)/([^/]+)/applicant/resetpassword/([a-z0-9]+)$#i', array(
'controller' => 'apply_applicant',
'action' => 'resetpassword',
'action_params' => array(
'programShortName' => 1,
'cycleName' => 2,
'uniqueId' => 3
)
));
//default controller
$basicRouter->addRoute('#^admin$#i', array(
'redirect' => 'admin/welcome'
));
//single applicant view
$basicRouter->addRoute('#^admin/applicants/single/([0-9]+)/?([^/]+)?/?(.*)$#i', array(
'controller' => 'applicants_single',
'action' => 2,
'action_params' => array(
'applicantId' => 1
),
'additional_params' => 3
));
//transactions come as posts from outside sources
$basicRouter->addRoute('#^transaction/(.*)$#i', array(
'controller' => 'transaction',
'action' => 'post',
'action_params' => array(
'name' => 1
)
));
$fc->addRouter($basicRouter);
//We use preg replace in the admin routers to cleanly group the administrative responsiblities in the URL
$advancedRouter = new \Foundation\VC\FullRegexRewriteRouter();
$advancedRouter->addRoute('#^admin/(manage|setup|applicants|scores)/([^/]+)/?([^/]*)/?(.*)$#i', array(
'controller' => '$1_$2',
'action' => '$3',
'additional_params' => '$4'
));
$advancedRouter->addRoute('#^admin/([^/]+)/?([^/]+)?$#i', array(
'controller' => 'admin_$1',
'action' => '$2'
));
$fc->addRouter($advancedRouter);
$fc->processRequest(new Lvc_HttpRequest());<file_sep><?php
namespace Jazzee\Interfaces;
/**
* Review Page interface
* Pages which implement this can be viewed on the admin review screen
*
* @author <NAME> <<EMAIL>>
* @license http://jazzee.org/license.txt
* @package jazzee
* @subpackage pages
*/
interface ReviewPage
{
/**
* Get the element for the applicants single view
* @return string
*/
public static function applicantsSingleElement();
}<file_sep><?php
/**
* LDAP Admin Directory
*
* Use LDAP to find users and their attributes
*
*/
namespace Jazzee\AdminDirectory;
class Ldap implements \Jazzee\Interfaces\AdminDirectory{
/**
* Our directory Server resource
* @var resource
*/
private $_directoryServer;
/**
* Controller instance
* @var \Jazzee\AdminController
*/
private $_controller;
public function __construct(\Jazzee\Interfaces\AdminController $controller){
$this->_controller = $controller;
if(!$this->_directoryServer = ldap_connect($this->_controller->getConfig()->getLdapHostname(), $this->_controller->getConfig()->getLdapPort())){
throw new \Jazzee\Exception('Unable to connect to ldap server ' . $this->_controller->getConfig()->getLdapHostname() . ' at port' . $this->_controller->getConfig()->getLdapPort());
}
if(!ldap_bind($this->_directoryServer, $this->_controller->getConfig()->getLdapBindRdn(), $this->_controller->getConfig()->getLdapBindPassword())){
throw new \Jazzee\Exception('Unable to bind to ldap server');
}
}
public function search($firstName, $lastName){
$attributes = array();
if(!empty($firstName)) $attributes[$this->_controller->getConfig()->getLdapFirstNameAttribute()] = $firstName . '*';
if(!empty($lastName)) $attributes[$this->_controller->getConfig()->getLdapLastNameAttribute()] = $lastName . '*';
$filters = array();
$filter = '';
foreach($attributes as $key=>$value)$filters[] = "{$key}={$value}";
if(count($filters) == 1){
$filter = $filters[0];
} else if(count($filters) > 1){
$filter = '(&';
foreach($filters as $f) $filter .= "({$f})";
$filter .= ')';
}
//limit the LDAP attributes for efficiency
$limitAttributes = array(
$this->_controller->getConfig()->getLdapUsernameAttribute(),
$this->_controller->getConfig()->getLdapFirstNameAttribute(),
$this->_controller->getConfig()->getLdapLastNameAttribute(),
$this->_controller->getConfig()->getLdapEmailAddressAttribute()
);
$searchResult = ldap_search($this->_directoryServer, $this->_controller->getConfig()->getLdapSearchBase(), $filter, $limitAttributes);
return $this->parseSearchResult($searchResult);
}
function findByUniqueName($uniqueName){
$filter = "{$this->_controller->getConfig()->getLdapUsernameAttribute()}={$uniqueName}";
$limitAttributes = array(
$this->_controller->getConfig()->getLdapUsernameAttribute(),
$this->_controller->getConfig()->getLdapFirstNameAttribute(),
$this->_controller->getConfig()->getLdapLastNameAttribute(),
$this->_controller->getConfig()->getLdapEmailAddressAttribute()
);
$searchResult = ldap_search($this->_directoryServer, $this->_controller->getConfig()->getLdapSearchBase(), $filter, $limitAttributes);
return $this->parseSearchResult($searchResult);
}
/**
* Parse the LDAP search results into a nice array
*
* @param resource $searchResult
* @return array
*/
protected function parseSearchResult($searchResult){
$result = array();
ldap_sort($this->_directoryServer, $searchResult, $this->_controller->getConfig()->getLdapFirstNameAttribute());
ldap_sort($this->_directoryServer, $searchResult, $this->_controller->getConfig()->getLdapLastNameAttribute());
if(ldap_count_entries($this->_directoryServer, $searchResult)){
$entries = ldap_get_entries($this->_directoryServer, $searchResult);
for ($i=0; $i<$entries["count"]; $i++) {
$arr = array(
'userName' => '',
'firstName' => '',
'lastName' => '',
'emailAddress' => '',
);
if(!empty($entries[$i][strtolower($this->_controller->getConfig()->getLdapUsernameAttribute())][0])) $arr['userName'] = $entries[$i][strtolower($this->_controller->getConfig()->getLdapUsernameAttribute())][0];
if(!empty($entries[$i][strtolower($this->_controller->getConfig()->getLdapFirstNameAttribute())][0])) $arr['firstName'] = $entries[$i][strtolower($this->_controller->getConfig()->getLdapFirstNameAttribute())][0];
if(!empty($entries[$i][strtolower($this->_controller->getConfig()->getLdapLastNameAttribute())][0])) $arr['lastName'] = $entries[$i][strtolower($this->_controller->getConfig()->getLdapLastNameAttribute())][0];
if(!empty($entries[$i][strtolower($this->_controller->getConfig()->getLdapEmailAddressAttribute())][0])) $arr['emailAddress'] = $entries[$i][strtolower($this->_controller->getConfig()->getLdapEmailAddressAttribute())][0];
$result[] = $arr;
}
}
return $result;
}
}
<file_sep><?php
/**
* List of programs
* @author <NAME> <<EMAIL>>
* @license http://jazzee.org/license.txt
* @package jazzee
* @subpackage apply
*/
?>
<fieldset>
<legend>Select the program you are applying to:</legend>
<ul class='nobullets'>
<?php foreach($programs as $program): ?>
<li><a href='<?php print $this->path('apply/' . $program->getShortName());?>'><?php print $program->getName(); ?></a></li>
<?php endforeach; ?>
</ul>
</fieldset>
<file_sep><?php
namespace Jazzee\Console;
ini_set('memory_limit',-1);
/**
* Scrambles applicants for testing
* @author <NAME> <<EMAIL>>
* @license http://jazzee.org/license.txt
* @package jazzee
* @subpackage console
*
*/
class Scramble extends \Symfony\Component\Console\Command\Command
{
/**
* @see Console\Command\Command
*/
protected function configure(){
$this->setName('scramble')->setDescription('Scramble Applicants for testing.');
}
protected function execute(\Symfony\Component\Console\Input\InputInterface $input, \Symfony\Component\Console\Output\OutputInterface $output){
$jazzeeConfiguration = new \Jazzee\Configuration;
if($jazzeeConfiguration->getStatus() == 'PRODUCTION'){
$output->write('<error>You cannot scramble in production.</error>' . PHP_EOL);
} else {
$start = time();
$em = $this->getHelper('em')->getEntityManager();
$offset = 0;
$maxResults = 100;
$count = 0;
$query = $em->createQuery("SELECT a.firstName, a.lastName FROM \Jazzee\Entity\Applicant a");
$query->setMaxResults(500);
$firstNames = array();
$lastNames = array();
foreach($query->getResult() as $arr){
$firstNames[] = $arr['firstName'];
$lastNames[] = $arr['lastName'];
}
do{
$query = $em->createQuery("SELECT a FROM \Jazzee\Entity\Applicant a");
$query->setMaxResults($maxResults);
$query->setFirstResult($offset);
$applicants = $query->getResult();
$continue = count($applicants);
foreach($applicants as $applicant){
$count++;
$applicant->setFirstName($firstNames[array_rand($firstNames)]);
$applicant->setLastName($lastNames[array_rand($lastNames)]);
$applicant->setEmail("<EMAIL>");
$em->persist($applicant);
}
$offset = $offset+$maxResults;
$em->flush();
$em->clear();
gc_collect_cycles();
} while ($continue);
$total = time() - $start;
$avg = $count?(round($total/$count,2) . 's/applicant'):'';
$usedMemory = round(memory_get_peak_usage()/1048576,2);
$output->write("<info>{$count} applicant's information scrambled successfuly in {$total} seconds {$avg} using {$usedMemory}MB</info>" . PHP_EOL);
}
}
}<file_sep><?php
/**
* apply_status view
* @package jazzee
* @subpackage apply
*/
if($applicant->isLocked() and $applicant->getDecision()->status() == 'finalAdmit'){
if(isset($confirm)){
$applicationPage = $confirm?$sirAcceptPage:$sirDeclinePage;
$class = $applicationPage->getPage()->getType()->getClass();
$this->renderElement($class::sirPageElement(), array('confirm'=>$confirm, 'applicationPage'=>$applicationPage));
} else {
$this->renderElement('form', array('form'=> $form));
}
}<file_sep>Installation
============
There are some configuration and installation directives that will make your life easier as a developer.<file_sep><?php
namespace Jazzee;
/**
* Dependancy free controller
*
* Base page controller doesn't depend on anything so it is safe
* for error pages and file pages to use it when they don't need acess
* to configuration or session info setup by JazzeeController
* @package jazzee
*/
class JazzeePageController extends \Foundation\VC\Controller
{
/**
* @var \Jazzee\Configuration
*/
protected $_config;
/**
* @var \Foundation\Configuration
*/
protected $_foundationConfig;
/**
* @var \Foundation\Cache
*/
protected $_cache;
/**
* Absolute server path
* @var string
*/
protected $_serverPath;
/**
* Mono log instance for jazzee logging
* @var \Monolog\Logger
*/
protected $_log;
/**
* Pear log instance for authentication logging
* @var \Log
*/
protected $_authLog;
/**
* Virtual File system root directory
* @var \Foundation\Virtual\Directory
*/
protected $_vfs;
public function __construct(){
$this->setupConfiguration();
$this->setupVarPath();
$this->setupLogging();
}
/**
* Basic page disply setup
*
* Create the default layout varialbes so the layout doesn't have to guess if they are available
* @return null
*/
protected function beforeAction(){
$this->buildVirtualFilesystem();
//required layout variables get default values
$this->setLayoutVar('requiredCss', array());
$this->setLayoutVar('requiredJs', array());
$this->setLayoutVar('pageTitle', '');
$this->setLayoutVar('layoutTitle', '');
$this->setLayoutVar('layoutContentTop', '');
$this->setLayoutVar('navigation', false);
$this->setLayoutVar('status', 'success'); //used in some json ajax requests
//yui css library
$this->addCss($this->path('resource/foundation/styles/reset-fonts-grids.css'));
$this->addCss($this->path('resource/foundation/styles/base.css'));
//anytime css has to go before jquery ui theme
$this->addCss($this->path('resource/foundation/styles/anytime.css'));
//default jquery theme
$this->addCss($this->path('resource/foundation/styles/jquerythemes/ui-lightness/style.css'));
//our css
$this->addCss($this->path('resource/styles/layout.css'));
$this->addCss($this->path('resource/styles/style.css'));
//Set HTML purifier cache location
\Foundation\Form\Filter\Safe::setCachePath($this->getVarPath() . '/tmp/');
}
/**
* Create a good path even if modrewrite is not present
* @param string $path
* @return string
*/
public function path($path){
$prefix = $this->_serverPath . rtrim(dirname($_SERVER['SCRIPT_NAME']),'/\\.');
return $prefix . '/' . $path;
}
/**
* Call any after action properties, redirect, and exit
* @param string $path
*/
public function redirectPath($path){
$this->redirect($this->path($path));
$this->afterAction();
exit(0);
}
/**
* Call any after action properties, redirect, and exit
* @param string $url
*/
public function redirectUrl($url){
$this->redirect($url);
$this->afterAction();
exit(0);
}
/**
* No messages
*/
public function getMessages(){
return array();
}
/**
* Build our virtual file system
*/
protected function buildVirtualFileSystem(){
$this->_vfs = new \Foundation\Virtual\VirtualDirectory();
$this->_vfs->addDirectory('scripts', new \Foundation\Virtual\ProxyDirectory(__DIR__ . '/../scripts'));
$this->_vfs->addDirectory('styles', new \Foundation\Virtual\ProxyDirectory(__DIR__ . '/../styles'));
$virtualFoundation = new \Foundation\Virtual\VirtualDirectory();
$foundationPath = \Foundation\Configuration::getSourcePath();
$virtualFoundation->addDirectory('javascript', new \Foundation\Virtual\ProxyDirectory($foundationPath . '/src/javascript'));
$media = new \Foundation\Virtual\VirtualDirectory();
$media->addFile('blank.gif', new \Foundation\Virtual\RealFile('blank.gif,', $foundationPath . '/src/media/blank.gif'));
$media->addFile('ajax-bar.gif', new \Foundation\Virtual\RealFile('ajax-bar.gif,', $foundationPath . '/src/media/ajax-bar.gif'));
$media->addDirectory('icons', new \Foundation\Virtual\ProxyDirectory( $foundationPath . '/src/media/famfamfam_silk_icons_v013/icons'));
$scripts = new \Foundation\Virtual\VirtualDirectory();
$scripts->addFile('jquery.js', new \Foundation\Virtual\RealFile('jquery.js', $foundationPath . '/lib/jquery/jquery-1.7.1.min.js'));
$scripts->addFile('jquery.json.js', new \Foundation\Virtual\RealFile('jquery.json.js', $foundationPath . '/lib/jquery/plugins/jquery.json-2.2.min.js'));
$scripts->addFile('jquery.cookie.js', new \Foundation\Virtual\RealFile('jquery.cookie.js', $foundationPath . '/lib/jquery/plugins/jquery.cookie-1.min.js'));
$scripts->addFile('jqueryui.js', new \Foundation\Virtual\RealFile('jqueryui.js', $foundationPath . '/lib/jquery/jquery-ui-1.8.16.min.js'));
$scripts->addFile('jquery.qtip.js', new \Foundation\Virtual\RealFile('jquery.qtip.min.js', $foundationPath . '/lib/jquery/plugins/qtip/jquery.qtip.min.js'));
$scripts->addFile('jquery.wysiwyg.js', new \Foundation\Virtual\RealFile('jquery.wysiwyg.js', $foundationPath . '/lib/jquery/plugins/jwysiwyg/jquery.wysiwyg.full.min.js'));
$scripts->addFile('anytime.js', new \Foundation\Virtual\RealFile('anytime.js', $foundationPath . '/lib/anytime/anytimec.js'));
$scripts->addFile('form.js', new \Foundation\Virtual\RealFile('form.js', $foundationPath . '/src/javascript/form.js'));
$styles = new \Foundation\Virtual\VirtualDirectory();
$styles->addDirectory('jquerythemes', new \Foundation\Virtual\ProxyDirectory($foundationPath . '/lib/jquery/themes'));
$styles->addFile('base.css', new \Foundation\Virtual\RealFile('base.css', $foundationPath . '/lib/yui/base-min.css'));
$styles->addFile('reset-fonts-grids.css', new \Foundation\Virtual\RealFile('reset-fonts-grids.css', $foundationPath . '/lib/yui/reset-fonts-grids-min.css'));
$styles->addFile('jquery.qtip.css', new \Foundation\Virtual\RealFile('jquery.qtip.min.css', $foundationPath . '/lib/jquery/plugins/qtip/jquery.qtip.min.css'));
$styles->addFile('anytime.css', new \Foundation\Virtual\RealFile('anytime.css', $foundationPath . '/lib/anytime/anytimec.css'));
$styles->addFile('jquery.wysiwyg.css', new \Foundation\Virtual\RealFile('jquery.wysiwyg.css', $foundationPath . '/lib/jquery/plugins/jwysiwyg/jquery.wysiwyg.css'));
$styles->addFile('jquery.wysiwyg.bg.png', new \Foundation\Virtual\RealFile('jquery.wysiwyg.bg.png', $foundationPath . '/lib/jquery/plugins/jwysiwyg/jquery.wysiwyg.bg.png'));
$styles->addFile('jquery.wysiwyg.gif', new \Foundation\Virtual\RealFile('jquery.wysiwyg.gif',$foundationPath . '/lib/jquery/plugins/jwysiwyg/jquery.wysiwyg.gif'));
$virtualFoundation->addDirectory('media',$media);
$virtualFoundation->addDirectory('scripts',$scripts);
$virtualFoundation->addDirectory('styles',$styles);
$this->_vfs->addDirectory('foundation', $virtualFoundation);
$jazzeePath = \Jazzee\Configuration::getSourcePath();
$vOpenID = new \Foundation\Virtual\VirtualDirectory();
$vOpenID->addDirectory('js', new \Foundation\Virtual\ProxyDirectory($jazzeePath . '/lib/openid-selector/js'));
$vOpenID->addDirectory('css', new \Foundation\Virtual\ProxyDirectory($jazzeePath . '/lib/openid-selector/css'));
$vOpenID->addDirectory('images', new \Foundation\Virtual\ProxyDirectory($jazzeePath . '/lib/openid-selector/images'));
$this->_vfs->addDirectory('openid-selector', $vOpenID);
}
/**
* No Navigation
*/
public function getNavigation(){
return false;
}
/**
* Setup the var directories
*/
protected function setupVarPath(){
$var = $this->getVarPath();
//check to see if all the directories exist and are writable
$varDirectories = array('log','session','cache','tmp','uploads','cache/public');
foreach($varDirectories as $dir){
$path = $var . '/' . $dir;
if(!is_dir($path)){
if(!mkdir($path)){
throw new Exception("Tried to create 'var/{$dir}' directory but {$path} is not writable by the webserver");
}
}
if(!is_writable($path)){
throw new Exception("Invalid path to 'var/{$dir}' {$path} is not writable by the webserver");
}
}
}
/**
* Get the path to the var directory
* @return string
*/
protected function getVarPath(){
$path = $this->_config->getVarPath();
if(!$realPath = \realpath($path) or !\is_dir($realPath) or !\is_writable($realPath)){
if($realPath) $path = $realPath; //nicer error message if the path exists
throw new Exception("{$path} is not readable by the webserver so we cannot use it as the 'var' directory");
}
return $realPath;
}
/**
* Setup configuration
*
* Load config.ini.php
* translate to foundation config
* create absolute path
* set defautl timezone
*/
protected function setupConfiguration(){
$this->_config = new \Jazzee\Configuration();
$this->_foundationConfig = new \Foundation\Configuration();
if($this->_config->getStatus() == 'DEVELOPMENT'){
$this->_foundationConfig->setCacheType('array');
} else {
$this->_foundationConfig->setCacheType('apc');
}
$this->_foundationConfig->setMailSubjectPrefix($this->_config->getMailSubjectPrefix());
$this->_foundationConfig->setMailDefaultFromAddress($this->_config->getMailDefaultFromAddress());
$this->_foundationConfig->setMailDefaultFromName($this->_config->getMailDefaultFromName());
$this->_foundationConfig->setMailOverrideToAddress($this->_config->getMailOverrideToAddress());
$this->_foundationConfig->setMailServerType($this->_config->getMailServerType());
$this->_foundationConfig->setMailServerHost($this->_config->getMailServeHost());
$this->_foundationConfig->setMailServerPort($this->_config->getMailServerPort());
$this->_foundationConfig->setMailServerUsername($this->_config->getMailServerUsername());
$this->_foundationConfig->setMailServerPassword($this->_config->getMailServerPassword());
$this->_cache = new \Foundation\Cache('Jazzee' . __DIR__,$this->_foundationConfig);
\Foundation\VC\Config::setCache($this->_cache);
if((empty($_SERVER['HTTPS']) OR $_SERVER['HTTPS'] == 'off')){
$protocol = 'http';
} else {
$protocol = 'https';
}
$this->_serverPath = $protocol . '://' . $_SERVER['SERVER_NAME'];
}
/**
* Get the current configuration
* @return \Jazzee\Configuration
*/
public function getConfig(){
return $this->_config;
}
/**
* Setup logging
*/
protected function setupLogging(){
$path = $this->getVarPath() . '/log';
//create an access log with browser information
$accessLog = new \Monolog\Logger('access');
$accessLog->pushHandler(new \Monolog\Handler\StreamHandler($path . '/access_log'));
$accessMessage ="[{$_SERVER['REQUEST_METHOD']} {$_SERVER['REQUEST_URI']} {$_SERVER['SERVER_PROTOCOL']}] " .
'[' . (!empty($_SERVER['HTTP_REFERER'])?$_SERVER['HTTP_REFERER']:'-') . '] ' .
'[' . (!empty($_SERVER['HTTP_USER_AGENT'])?$_SERVER['HTTP_USER_AGENT']:'-') . ']';
$accessLog->addInfo($accessMessage);
//create an authenticationLog
$this->_authLog = new \Monolog\Logger('authentication');
$this->_authLog->pushHandler(new \Monolog\Handler\StreamHandler($path . '/authentication_log'));
$this->_log = new \Monolog\Logger('jazzee');
$this->_log->pushProcessor(new \Monolog\Processor\WebProcessor());
$this->_log->pushProcessor(new \Monolog\Processor\IntrospectionProcessor());
$this->_log->pushHandler(new \Monolog\Handler\StreamHandler($path . '/strict_log'));
$this->_log->pushHandler(new \Monolog\Handler\StreamHandler($path . '/messages_log', \Monolog\Logger::INFO));
$this->_log->pushHandler(new \Monolog\Handler\StreamHandler($path . '/error_log', \Monolog\Logger::ERROR));
$this->_log->pushHandler(new \Monolog\Handler\SyslogHandler('jazzee','syslog',\Monolog\Logger::ERROR));
//Handle PHP errors with out logs
set_error_handler(array($this, 'handleError'));
//catch any excpetions
set_exception_handler(array($this, 'handleException'));
}
/**
* Log something
* @param string $message
* @param integer $level
*/
public function log($message, $level = \Monolog\Logger::INFO){
$this->_log->addRecord($level, $message);
}
/**
* Handle PHP error
* Takes input from PHPs built in error handler logs it
* throws a jazzee exception to handle if the error reporting level is high enough
* @param $code
* @param $message
* @param $file
* @param $line
* @throws \Jazzee\Exception
*/
public function handleError($code, $message, $file, $line){
/* Map the PHP error to a Log priority. */
switch ($code) {
case E_WARNING:
case E_USER_WARNING:
$priority = \Monolog\Logger::WARNING;
break;
case E_NOTICE:
case E_USER_NOTICE:
$priority = \Monolog\Logger::INFO;
break;
case E_ERROR:
case E_USER_ERROR:
$priority = \Monolog\Logger::ERROR;
break;
default:
$priority = \Monolog\Logger::INFO;
}
if(error_reporting() === 0){// Error reporting is currently turned off or suppressed with @
$this->_log->debug('Supressed error: ' . $message . ' in ' . $file . ' at line ' . $line);
return false;
}
$this->_log->addRecord($priority, $message . ' in ' . $file . ' at line ' . $line);
throw new \Exception('Jazzee caught a PHP error: ' . $message . ' in ' . $file . ' at line ' . $line);
}
/**
* Handle PHP Exception
* @param Exception $e
*/
public function handleException(\Exception $e){
$message = $e->getMessage();
$userMessage = 'Unspecified Technical Difficulties';
$code = 500;
if($e instanceof \Lvc_Exception){
$code = 404;
$userMessage = 'Page not found.';
}
if($e instanceof \PDOException){
$message = 'Problem with database connection. PDO says: ' . $message;
$userMessage = 'We are experiencing a problem connecting to our database. Please try your request again.';
}
if($e instanceof \Foundation\Exception){
$userMessage = $e->getUserMessage();
}
if($e instanceof \Foundation\Virtual\Exception){
$userMessage = $e->getUserMessage();
$code = $e->getHttpErrorCode();
}
/* Map the PHP error to a Log priority. */
switch ($e->getCode()) {
case E_WARNING:
case E_USER_WARNING:
$priority = \Monolog\Logger::WARNING;
break;
case E_NOTICE:
case E_USER_NOTICE:
$priority = \Monolog\Logger::INFO;
break;
case E_ERROR:
case E_USER_ERROR:
$priority = \Monolog\Logger::CRITICAL;
break;
default:
$priority = \Monolog\Logger::INFO;
}
$this->_log->addRecord($priority, $message);
//send the error to PHP as well
error_log($message);
// Get a request for the error page
$request = new \Lvc_Request();
$request->setControllerName('error');
$request->setActionName('index');
$request->setActionParams(array('error' => $code, 'message'=>$userMessage));
// Get a new front controller without any routers, and have it process our handmade request.
$fc = new \Lvc_FrontController();
$fc->processRequest($request);
exit(1);
}
}<file_sep><?php
ini_set('memory_limit', '1g');
set_time_limit('120');
/**
* Download Applicants in csv format
* @author <NAME> <<EMAIL>>
* @package jazzee
* @subpackage applicants
*/
class ApplicantsDownloadController extends \Jazzee\AdminController {
const MENU = 'Applicants';
const TITLE = 'Download';
const PATH = 'applicants/download';
const ACTION_INDEX = 'All Applicants';
/**
* List all applicants
*/
public function actionIndex(){
$form = new \Foundation\Form();
$form->setCSRFToken($this->getCSRFToken());
$form->setAction($this->path('applicants/download'));
$field = $form->newField();
$field->setLegend('Download Applicants');
$element = $field->newElement('RadioList','type');
$element->setLabel('Type of Download');
$element->newItem('xls', 'Excel');
$element->newItem('xml', 'XML');
$element->addValidator(new \Foundation\Form\Validator\NotEmpty($element));
$element = $field->newElement('CheckboxList','filters');
$element->setLabel('Types of applicants');
$element->newItem('unlocked', 'Incomplete');
$element->newItem('locked', 'Locked');
$element->newItem('admitted', 'Admitted');
$element->newItem('denied', 'Denied');
$element->newItem('accepted', 'Accepted');
$element->newItem('declined', 'Declined');
$element->addValidator(new \Foundation\Form\Validator\NotEmpty($element));
$form->newButton('submit', 'Download Applicants');
if($input = $form->processInput($this->post)){
$filters = $input->get('filters');
$applicationPages = array();
$applicationPagesAnswerCount = array();
foreach($this->_application->getApplicationPages(\Jazzee\Entity\ApplicationPage::APPLICATION) as $pageEntity){
$pageEntity->getJazzeePage()->setController($this);
$applicationPages[$pageEntity->getId()] = $pageEntity;
}
$applicantsArray = array();
$applicants = $this->_em->getRepository('\Jazzee\Entity\Applicant')->findApplicantsByName('%', '%', $this->_application);
foreach($applicants as $applicant){
if((!$applicant->isLocked() and in_array('unlocked', $filters))
or ($applicant->isLocked() and in_array('locked', $filters))
or ($applicant->isLocked() and $applicant->getDecision()->getFinalAdmit() and in_array('admitted', $filters))
or ($applicant->isLocked() and $applicant->getDecision()->getFinalDeny() and in_array('denied', $filters))
or ($applicant->isLocked() and $applicant->getDecision()->getAcceptOffer() and in_array('accepted', $filters))
or ($applicant->isLocked() and $applicant->getDecision()->getDeclineOffer() and in_array('declined', $filters))
){
$applicantsArray[] = $applicant;
} //end if filter
} //end foreach applicants
unset($applicants);
switch($input->get('type')){
case 'xls':
$this->makeXls($applicantsArray);
break;
case 'xml':
$this->makeXml($applicantsArray);
break;
}
}
$this->setVar('form', $form);
}
/**
* XLS file type
* @param array \Jazzee\Entity\Applicant $applicants
*/
protected function makeXls(array $applicants){
$applicationPages = array();
$applicationPagesAnswerCount = array();
foreach($this->_em->getRepository('\Jazzee\Entity\ApplicationPage')->findBy(array('application'=>$this->_application->getId(), 'kind'=>\Jazzee\Entity\ApplicationPage::APPLICATION), array('weight'=> 'asc')) as $applicationPage){
if($applicationPage->getJazzeePage() instanceof \Jazzee\Interfaces\CsvPage){
$applicationPages[] = $applicationPage;
}
}
foreach($applicationPages as $applicationPage) $applicationPagesAnswerCount[$applicationPage->getPage()->getId()] = 1;
foreach($applicants as $applicant){
foreach($applicationPages as $applicationPage){
if(count($applicant->findAnswersByPage($applicationPage->getPage())) > $applicationPagesAnswerCount[$applicationPage->getPage()->getId()])
$applicationPagesAnswerCount[$applicationPage->getPage()->getId()] = count($applicant->findAnswersByPage($applicationPage->getPage()));
}
}
$rows = array();
$header = array(
'ID',
'<NAME>',
'<NAME>',
'<NAME>',
'Suffix',
'Email',
'Locked',
'Last Login',
'Last Update',
'Account Created',
'Status',
'Progress',
'Tags'
);
foreach($applicationPages as $applicationPage){
for($i=1;$i<=$applicationPagesAnswerCount[$applicationPage->getPage()->getId()]; $i++){
foreach($applicationPage->getJazzeePage()->getCsvHeaders() as $title){
$header[] = $applicationPage->getTitle() . ' ' . $i . ' ' . $title;
}
}
}
$rows[] = $header;
foreach($applicants as $applicant){
$arr = array(
$applicant->getId(),
$applicant->getFirstName(),
$applicant->getMiddleName(),
$applicant->getLastName(),
$applicant->getSuffix(),
$applicant->getEmail(),
$applicant->isLocked()?'yes':'no',
$applicant->getLastLogin()->format('c'),
$applicant->getUpdatedAt()->format('c'),
$applicant->getCreatedAt()->format('c'),
$applicant->getDecision()?$applicant->getDecision()->status():'none',
$applicant->getPercentComplete() * 100 . '%'
);
$tags = array();
foreach($applicant->getTags() as $tag) $tags[] = $tag->getTitle();
$arr[] = implode(' ', $tags);
foreach($applicationPages as $applicationPage){
$applicationPage->getJazzeePage()->setApplicant($applicant);
for($i=0;$i<$applicationPagesAnswerCount[$applicationPage->getPage()->getId()]; $i++){
$arr = array_merge($arr, $applicationPage->getJazzeePage()->getCsvAnswer($i));
}
}
$rows[] = $arr;
}
unset($applicants);
unset($applicationPages);
$string = '';
foreach($rows as $row){
foreach($row as $value) $string .= '"' . $value . '"' . "\t";
$string .= "\n";
}
$this->setVar('outputType', 'string');
$this->setVar('type', 'text/xls');
$this->setVar('filename', $this->_application->getProgram()->getShortName() . '-' . $this->_application->getCycle()->getName() . date('-mdy') . '.xls');
$this->setVar('string', $string);
}
/**
* XML file type
* @param array \Jazzee\Entity\Applicant $applicants
*/
protected function makeXml(array $applicants){
$applicationPages = $this->_em->getRepository('\Jazzee\Entity\ApplicationPage')->findBy(array('application'=>$this->_application->getId(), 'kind'=>\Jazzee\Entity\ApplicationPage::APPLICATION), array('weight'=> 'asc'));
$xml = new DOMDocument();
$xml->formatOutput = true;
$applicantsXml = $xml->createElement("applicants");
foreach($applicants as $applicant){
$appXml = $applicant->toXml($this);
$node = $xml->importNode($appXml->documentElement, true);
$applicantsXml->appendChild($node);
}
$xml->appendChild($applicantsXml);
$this->setVar('outputType', 'xml');
$this->setLayout('xml');
$this->setLayoutVar('filename', $this->_application->getProgram()->getShortName() . '-' . $this->_application->getCycle()->getName() . date('-mdy'));
$this->setVar('xml', $xml);
}
}<file_sep><?php
/**
* manage_users index view
* @author <NAME> <<EMAIL>>
* @license http://jazzee.org/license.txt
* @package jazzee
* @subpackage manage
*/
$this->renderElement('form', array('form'=>$form));?>
<?php if($results){ ?>
<h5>Results</h5>
<ul>
<?php foreach($results as $result){ ?>
<li><?php print $result['lastName'] . ', ' . $result['firstName'] . ' (' . ($result['emailAddress']?$result['emailAddress']:'no email') . ') (' . $result['userName'] . ')' ?>
<?php if($this->controller->checkIsAllowed('manage_users', 'new')){ ?>
(<a href='<?php print $this->path('manage/users/new/') . base64_encode($result['userName'])?>'>Add User</a>)
<?php }?>
</li>
<?php }?>
</ul>
<?php } ?>
<?php if(empty($users)){?>
<p>There are no users in the system</p>
<?php } else { ?>
<table>
<caption>System Users</caption>
<thead>
<tr>
<th>Name</th>
<th>API Key</th>
<?php foreach($roles as $role){?>
<th><?php print $role->getName();?></th>
<?php } ?>
<th>Tools</th>
</tr>
</thead>
<tbody>
<?php foreach($users as $user){?>
<tr>
<td><?php print $user->getLastName(); ?>, <?php print $user->getFirstName();?>(<?php print $user->getUniqueName();?>)</td>
<td><?php print $user->getApiKey();?></td>
<?php foreach($roles as $role){?>
<td><?php if($user->hasRole($role)) print 'x'?></td>
<?php } ?>
<td>
<?php if($this->controller->checkIsAllowed('manage_users', 'edit')) { ?>
<a href='<?php print $this->controller->path('manage/users/edit/' . $user->getId());?>'>Edit Roles</a> |
<?php } ?>
<?php if($this->controller->checkIsAllowed('manage_users', 'refreshUser')) { ?>
<a href='<?php print $this->controller->path('manage/users/refreshUser/' . $user->getId());?>'>Refresh Directory</a> |
<?php } ?>
<?php if($this->controller->checkIsAllowed('manage_users', 'resetApiKey')) { ?>
<a href='<?php print $this->controller->path('manage/users/resetApiKey/' . $user->getId());?>'>Reset API Key</a> |
<?php } ?>
<?php if($this->controller->checkIsAllowed('manage_users', 'remove')) { ?>
<a href='<?php print $this->controller->path('manage/users/remove/' . $user->getId());?>'>Remove</a>
<?php } ?>
</td>
<?php } ?>
</tbody>
</table>
<?php } ?><file_sep>/**
* Clientside page builder
* Gets extended by the page builder controllers to provide specific functionality
* @param {jQuery} workspace
*/
function PageBuilder(canvas){
this.services = new Services;
this.deletedPages = [];
this.pages = {};
this.pageTypes = [];
this.elementTypes = [];
this.paymentTypes = [];
this.isModified = false;
this.canvas = canvas;
//make sure we don't have any collisions with new page and element Ids
this.IdCounter = 0;
this.controllerPath = '';
this.currentPage = false;
//are we editing global pages or application pages
this.editGlobal = false;
var pageBuilder = this;
$(window).bind('beforeunload', function(){
if(pageBuilder.isModified){
return 'Are you sure you want to leave? If you do all of your changes will be lost.';
}
});
};
/**
* Setup the workspace layout
*/
PageBuilder.prototype.setup = function(){
var pageBuilder = this;
$.ajax({
type: 'GET',
url: this.controllerPath + '/listPageTypes',
async: false,
success: function(json){
pageBuilder.pageTypes = [];
$(json.data.result).each(function(i){
pageBuilder.pageTypes.push(this);
});
}
});
$.ajax({
type: 'GET',
url: this.controllerPath + '/listElementTypes',
async: false,
success: function(json){
pageBuilder.elementTypes = [];
$(json.data.result).each(function(i){
pageBuilder.elementTypes.push(this);
});
}
});
$.ajax({
type: 'GET',
url: this.controllerPath + '/listPaymentTypes',
async: false,
success: function(json){
pageBuilder.paymentTypes = [];
$(json.data.result).each(function(i){
pageBuilder.paymentTypes.push(this);
});
}
});
var button = $('<button>').html('Save Changes');
button.button({'disabled': true});
button.bind('click', function(){
var toSave = [];
for(var i in pageBuilder.pages){
if(pageBuilder.pages[i].checkIsModified()){
toSave.push(pageBuilder.pages[i].getDataObject());
}
}
for(var i = 0; i < pageBuilder.deletedPages.length; i++){
toSave.push(pageBuilder.deletedPages[i].getDataObject());
}
pageBuilder.deletedPages = [];
for(var i = 0; i < toSave.length; i++){
$.post(pageBuilder.controllerPath + '/savePage/' + toSave[i].id,{data: $.toJSON(toSave[i])});
}
pageBuilder.setup();
return false;
});
$('#save', this.canvas).empty().append(button);
};
/**
* Create an JazzeePage object
* Calls itself recursivly for child pages
* @param {Object} obj
* @returns {JazzeePage}
*/
PageBuilder.prototype.createPageObject = function(obj){
var pageBuilder = this;
var page = new window[obj.typeClass]();
page.init(obj, pageBuilder);
$(obj.elements).each(function(i,element){
var Element = new window[element.typeClass]();
Element.init(element, page);
$(element.list).each(function(){
Element.addListItem(this);
});
page.addElement(Element);
});
$(obj.variables).each(function(){
page.variables[this.name] = {name : this.name, value: this.value};
});
$(obj.children).each(function(){
page.addChild(pageBuilder.createPageObject(this));
});
page.isModified = false; //reset isModified now that we have added cildren and varialbes
return page;
};
/**
* Refresh the pages
*/
PageBuilder.prototype.refreshPages = function(){
var pageBuilder = this;
$.get(this.controllerPath + '/listPages',function(json){
pageBuilder.pages = {};
$(json.data.result).each(function(i){
var page = pageBuilder.createPageObject(this);
pageBuilder.pages[page.id] = page;
});
pageBuilder.synchronizePageList();
var currentPageLi = $('#'+pageBuilder.currentPage);
if(currentPageLi.length){
currentPageLi.click();
} else {
$('#pages li', this.canvas).first().click();
}
pageBuilder.isModified = false;
});
};
/**
* Get an ordered list object of all the pages in the list
* @param integer kind
* @return {jQuery} ol
*/
PageBuilder.prototype.getPagesList = function(kind){
var pageBuilder = this;
var ol = $('<ol>');
for(var i in this.pages){
var page = this.pages[i];
if(page.kind == kind){
var li = $('<li>');
li.html(page.title).attr('id', 'page-' + page.id);
li.data('page', page);
li.unbind('click');
li.bind('click', function(e){
$(this).parent().children('li').removeClass('active');
$(this).addClass('active');
$(this).data('page').workspace();
pageBuilder.currentPage = $(this).attr('id');
});
if(page.isGlobal && !this.editGlobal){
li.addClass('global');
}
$(ol).append(li);
}
}
return ol;
};
/**
* Add a page to the store
* @param {JazzeePage} page
*/
PageBuilder.prototype.addPage = function(page){
this.pages[page.id] = page;
this.synchronizePageList();
this.markModified();
};
/**
* Get the unique ID and incirement the counter
* @returns {Integer}
*/
PageBuilder.prototype.getUniqueId = function(){
return this.IdCounter++;
};
/**
* Mark the modified
*/
PageBuilder.prototype.markModified = function(){
this.isModified = true;
$('#save button', this.canvas).button( "option", "disabled", false );
};
/**
* Copy a page
* @param {Object} obj
*/
PageBuilder.prototype.copyPage = function(obj){
this.addPage(this.pageFromObject(obj, 'Copy of '+ obj.title, 'new'));
};
/**
* Import a page
* @param {Object} obj
*/
PageBuilder.prototype.importPage = function(obj){
this.addPage(this.pageFromObject(obj, obj.title, 'import'));
};
/**
* Import a page
* @param {Object} obj
* @param String title
* @param String status
* @return {JazzeePage}
*/
PageBuilder.prototype.pageFromObject = function(obj, title, status){
if(window[obj.typeClass] == undefined){
alert('Canot create this page becuase ' + obj.typeName + ' is not a recognized page type.');
}
var id = 'newpage' + this.getUniqueId();
obj.id = id;
obj.title = title;
var page = new window[obj.typeClass]();
page.init(obj, this);
page.status = status;
page.isModified = true;
for(var i=0; i<obj.elements.length; i++){
var e = obj.elements[i];
e.id = 'newelement' + this.getUniqueId();
var Element = new window[e.typeClass]();
Element.init(e, page);
Element.status = 'new';
Element.isModified = true;
for(var j = 0; j < e.list.length; j++){
Element.newListItem(e.list[j].value);
}
page.addElement(Element);
}
for(var property in obj.variables){
page.setVariable(property, obj.variables[property].value);
}
for(var i=0; i<obj.children.length; i++){
page.addChild(this.pageFromObject(obj.children[i], obj.children[i].title, status));
}
return page;
};
/**
* Delete a page from the store
* @param {ApplyPage} page
*/
PageBuilder.prototype.deletePage = function(page){
this.deletedPages.push(page);
delete this.pages[page.id];
$('#page-' + page.id).remove();
this.markModified();
};
/**
* Get a preview of the page
* @param {ApplyPage} page
* @returns {jQuery}
*/
PageBuilder.prototype.getPagePreview = function(page){
var div = $('<div>');
$.ajax({
type: 'POST',
url: this.controllerPath + '/previewPage',
data: {data: $.toJSON(page.getDataObject())},
async: false,
success: function(html){
div.html(html);
}
});
return div;
};
<file_sep><?php
/**
* applicants_download index view
* @package jazzee
* @subpackage admin
* @subpackage applicants
*/
if(isset($outputType)){
switch($outputType){
case 'string':
header("Content-type: {$type}");
header("Content-Disposition: attachment; filename={$filename}");
ob_end_clean();
print $string;
exit(0);
case 'xml':
echo $xml->saveXML();
}
} else {
$this->renderElement('form', array('form'=>$form));
}
<file_sep><?php
namespace Jazzee\Page;
/**
* Branch a child page depending on an applicant input
*
* @author <NAME> <<EMAIL>>
* @license http://jazzee.org/license.txt
* @package jazzee
* @subpackage pages
*/
class Branching extends Standard
{
/**
*
* Enter description here ...
*/
protected function makeForm(){
$form = new \Foundation\Form;
$form->setAction($this->_controller->getActionPath());
$field = $form->newField();
$field->setLegend($this->_applicationPage->getTitle());
$field->setInstructions($this->_applicationPage->getInstructions());
$element = $field->newElement('SelectList', 'branching');
$element->setLabel($this->_applicationPage->getPage()->getVar('branchingElementLabel'));
$element->addValidator(new \Foundation\Form\Validator\NotEmpty($element));
foreach($this->_applicationPage->getPage()->getChildren() as $child){
$element->newItem($child->getId(), $child->getTitle());
}
$form->newHiddenElement('level', 1);
$form->newButton('submit', 'Next');
return $form;
}
/**
* Branching Page Form
* Replaces the form with the correct branch
* @param \Jazzee\Entity\Page $page
*/
protected function branchingForm(\Jazzee\Entity\Page $page){
$form = new \Foundation\Form;
$form->setAction($this->_controller->getActionPath());
$field = $form->newField();
$field->setLegend($this->_applicationPage->getTitle());
$field->setInstructions($this->_applicationPage->getInstructions());
foreach($page->getElements() as $element){
$element->getJazzeeElement()->setController($this->_controller);
$element->getJazzeeElement()->addToField($field);
}
$form->newHiddenElement('level', 2);
$form->newHiddenElement('branching', $page->getId());
$form->newButton('submit', 'Save');
$this->_form = $form;
}
public function validateInput($input){
$page = $this->_applicationPage->getPage()->getChildById($input['branching']);
$this->branchingForm($page);
if($input['level'] == 1) return false;
return parent::validateInput($input);
}
public function newAnswer($input){
if(is_null($this->_applicationPage->getMax()) or count($this->getAnswers()) < $this->_applicationPage->getMax()){
$answer = new \Jazzee\Entity\Answer();
$answer->setPage($this->_applicationPage->getPage());
$this->_applicant->addAnswer($answer);
$childAnswer = new \Jazzee\Entity\Answer;
$childAnswer->setPage($answer->getPage()->getChildById($input->get('branching')));
$answer->addChild($childAnswer);
foreach($this->_applicationPage->getPage()->getChildById($input->get('branching'))->getElements() as $element){
foreach($element->getJazzeeElement()->getElementAnswers($input->get('el'.$element->getId())) as $elementAnswer){
$childAnswer->addElementAnswer($elementAnswer);
}
}
$this->_form = $this->makeForm();
$this->_form->applyDefaultValues();
$this->_controller->getEntityManager()->persist($answer);
$this->_controller->getEntityManager()->persist($childAnswer);
$this->_controller->addMessage('success', 'Answered Saved Successfully');
//flush here so the answerId will be correct when we view
$this->_controller->getEntityManager()->flush();
}
}
public function updateAnswer($input, $answerId){
if($answer = $this->_applicant->findAnswerById($answerId)){
foreach($answer->getElementAnswers() as $ea){
$this->_controller->getEntityManager()->remove($ea);
$answer->getElementAnswers()->removeElement($ea);
}
foreach($answer->getChildren() as $childAnswer){
$this->_controller->getEntityManager()->remove($childAnswer);
$answer->getChildren()->removeElement($childAnswer);
}
$childAnswer = new \Jazzee\Entity\Answer;
$childAnswer->setPage($answer->getPage()->getChildById($input->get('branching')));
$answer->addChild($childAnswer);
foreach($this->_applicationPage->getPage()->getChildById($input->get('branching'))->getElements() as $element){
foreach($element->getJazzeeElement()->getElementAnswers($input->get('el'.$element->getId())) as $elementAnswer){
$childAnswer->addElementAnswer($elementAnswer);
}
}
$this->_form = null;
$this->_controller->getEntityManager()->persist($answer);
$this->_controller->getEntityManager()->persist($childAnswer);
$this->_controller->addMessage('success', 'Answer Updated Successfully');
}
}
public function fill($answerId){
if($answer = $this->_applicant->findAnswerById($answerId)){
$child = $answer->getChildren()->first();
$this->branchingForm($child->getPage());
foreach($child->getPage()->getElements() as $element){
$element->getJazzeeElement()->setController($this->_controller);
$value = $element->getJazzeeElement()->formValue($child);
if($value) $this->getForm()->getElementByName('el' . $element->getId())->setValue($value);
}
$this->getForm()->setAction($this->_controller->getActionPath() . "/edit/{$answerId}");
}
}
public function getXmlAnswers(\DOMDocument $dom){
$answers = array();
foreach($this->_applicant->findAnswersByPage($this->_applicationPage->getPage()) as $answer){
$child = $answer->getChildren()->first();
$xmlAnswer = $this->xmlAnswer($dom, $child);
$eXml = $dom->createElement('element');
$eXml->setAttribute('elementId', 'branching');
$eXml->setAttribute('title', htmlentities($answer->getPage()->getVar('branchingElementLabel'),ENT_COMPAT,'utf-8'));
$eXml->setAttribute('type', null);
$eXml->appendChild($dom->createCDATASection($child->getPage()->getTitle()));
$xmlAnswer->appendChild($eXml);
$answers[] = $xmlAnswer;
}
return $answers;
}
/**
* Branchign pages get special CSV headers so all the branches are reprsented
* @return array
*/
public function getCsvHeaders(){
$headers = array();
$headers[] = $this->_applicationPage->getPage()->getVar('branchingElementLabel');
foreach($this->_applicationPage->getPage()->getChildren() as $child){
foreach($child->getElements() as $element){
$headers[] = $child->getTitle() . ' ' . $element->getTitle();
}
}
return $headers;
}
/**
* Branching pages return elements for every page
* @param int $position
* @return array
*/
function getCsvAnswer($position){
$arr = array();
$answers = $this->_applicant->findAnswersByPage($this->_applicationPage->getPage());
if(isset($answers[$position])){
$arr[] = $answers[$position]->getChildren()->first()->getPage()->getTitle();
}
foreach($this->_applicationPage->getPage()->getChildren() as $child){
foreach($child->getElements() as $element){
$element->getJazzeeElement()->setController($this->_controller);
if(isset($answers[$position]) and $child == $answers[$position]->getChildren()->first()->getPage()){
$arr[] = $element->getJazzeeElement()->displayValue($answers[$position]->getChildren()->first());
} else {
$arr[] = '';
}
}
}
return $arr;
}
/**
* Setup the default variables
*/
public function setupNewPage(){
$defaultVars = array(
'branchingElementLabel' => ''
);
foreach($defaultVars as $name=>$value){
$var = $this->_applicationPage->getPage()->setVar($name, $value);
$this->_controller->getEntityManager()->persist($var);
}
}
/**
* Create a table from answers
* and append any attached PDFs
* @param \Jazzee\ApplicantPDF $pdf
*/
public function renderPdfSection(\Jazzee\ApplicantPDF $pdf){
if($this->getAnswers()){
$pdf->addText($this->_applicationPage->getTitle(), 'h3');
$pdf->write();
$pdf->startTable();
$pdf->startTableRow();
$pdf->addTableCell($this->_applicationPage->getPage()->getVar('branchingElementLabel'));
$pdf->addTableCell('Answer');
foreach($this->getAnswers() as $answer){
$pdf->startTableRow();
$child = $answer->getChildren()->first();
$pdf->addTableCell($child->getPage()->getTitle());
$string = '';
foreach($child->getPage()->getElements() as $element){
$element->getJazzeeElement()->setController($this->_controller);
$string .= $element->getTitle() . ': ' . $element->getJazzeeElement()->pdfValue($child, $pdf) . "\n";
}
$pdf->addTableCell($string);
if($attachment = $answer->getAttachment()) $pdf->addPdf($attachment->getAttachment());
}
$pdf->writeTable();
}
}
public function newLorAnswer(\Foundation\Form\Input $input, \Jazzee\Entity\Answer $parent){
if($parent->getChildren()->count() == 0){
$page = $parent->getPage()->getChildren()->first();
$child = new \Jazzee\Entity\Answer();
$parent->addChild($child);
$child->setPage($page);
$branch = new \Jazzee\Entity\Answer;
$branch->setPage($page->getChildById($input->get('branching')));
$child->addChild($branch);
foreach($branch->getPage()->getElements() as $element){
foreach($element->getJazzeeElement()->getElementAnswers($input->get('el'.$element->getId())) as $elementAnswer){
$branch->addElementAnswer($elementAnswer);
}
}
$this->_form->applyDefaultValues();
$this->_controller->getEntityManager()->persist($child);
$this->_controller->getEntityManager()->persist($branch);
//flush here so the answerId will be correct when we view
$this->_controller->getEntityManager()->flush();
}
}
public function updateLorAnswer(\Foundation\Form\Input $input, \Jazzee\Entity\Answer $answer){
foreach($answer->getElementAnswers() as $ea){
$this->_controller->getEntityManager()->remove($ea);
$answer->getElementAnswers()->removeElement($ea);
}
foreach($answer->getChildren() as $childAnswer){
$this->_controller->getEntityManager()->remove($childAnswer);
$answer->getChildren()->removeElement($childAnswer);
}
$branch = new \Jazzee\Entity\Answer;
$answer->addChild($branch);
$branch->setPage($answer->getPage()->getChildById($input->get('branching')));
foreach($branch->getPage()->getElements() as $element){
foreach($element->getJazzeeElement()->getElementAnswers($input->get('el'.$element->getId())) as $elementAnswer){
$branch->addElementAnswer($elementAnswer);
}
}
$this->_form = null;
$this->_controller->getEntityManager()->persist($branch);
}
public function fillLorForm(\Jazzee\Entity\Answer $answer){
$child = $answer->getChildren()->first();
$this->branchingForm($child->getPage());
foreach($child->getPage()->getElements() as $element){
$element->getJazzeeElement()->setController($this->_controller);
$value = $element->getJazzeeElement()->formValue($child);
if($value) $this->getForm()->getElementByName('el' . $element->getId())->setValue($value);
}
}
public static function applyPageElement(){
return 'Branching-apply_page';
}
public static function pageBuilderScriptPath(){
return 'resource/scripts/page_types/JazzeePageBranching.js';
}
public static function applicantsSingleElement(){
return 'Branching-applicants_single';
}
public static function lorApplicantsSingleElement(){
return 'Branching-lor_applicants_single';
}
public static function lorReviewElement(){
return 'Branching-lor_review';
}
public static function sirApplicantsSingleElement(){
return 'Branching-sir_applicants_single';
}
}<file_sep>/**
* The JazzeeElementDate type
@extends JazzeeElement
*/
function JazzeeElementDate(){}
JazzeeElementDate.prototype = new JazzeeElement();
JazzeeElementDate.prototype.constructor = JazzeeElementDate;
JazzeeElementDate.prototype.avatar = function(){
return $('<input type="text" disabled="true">');
};<file_sep><?php
namespace Jazzee\Page;
/**
* AbstractPage
*
* @author <NAME> <<EMAIL>>
* @license http://jazzee.org/license.txt
* @package jazzee
* @subpackage pages
*/
abstract class AbstractPage implements \Jazzee\Interfaces\Page, \Jazzee\Interfaces\FormPage, \Jazzee\Interfaces\ReviewPage, \Jazzee\Interfaces\PdfPage, \Jazzee\Interfaces\CsvPage, \Jazzee\Interfaces\XmlPage {
const ERROR_MESSAGE = 'There was a problem saving your data on this page. Please correct the errors below and retry your request.';
/**
* The ApplicationPage Entity
* @var \Jazzee\Entity\ApplicationPage
*/
protected $_applicationPage;
/**
* Our controller
* @var \Jazzee\Controller
*/
protected $_controller;
/**
* The Applicant
* @var \Jazzee\Entity\Applicant
*/
protected $_applicant;
/**
* Our form
* @var \Foundation\Form
*/
protected $_form;
public function __construct(\Jazzee\Entity\ApplicationPage $applicationPage){
$this->_applicationPage = $applicationPage;
}
public function setController(\Jazzee\Controller $controller){
$this->_controller = $controller;
}
public function setApplicant(\Jazzee\Entity\Applicant $applicant){
$this->_applicant = $applicant;
}
public function getForm(){
if(is_null($this->_form)) $this->_form = $this->makeForm();
//reset the CSRF token on every request so when submission fails token validation doesn't even if the session has timed out
$this->_form->setCSRFToken($this->_controller->getCSRFToken());
return $this->_form;
}
/**
* Make the form for the page
* @return \Foundation\Form
*/
protected function makeForm(){
$form = new \Foundation\Form;
$form->setAction($this->_controller->getActionPath());
$field = $form->newField();
$field->setLegend($this->_applicationPage->getTitle());
$field->setInstructions($this->_applicationPage->getInstructions());
foreach($this->_applicationPage->getPage()->getElements() as $element){
$element->getJazzeeElement()->setController($this->_controller);
$element->getJazzeeElement()->addToField($field);
}
$form->newButton('submit', 'Save');
return $form;
}
public function validateInput($arr){
if($input = $this->getForm()->processInput($arr)){
return $input;
}
$this->_controller->addMessage('error', self::ERROR_MESSAGE);
return false;
}
public function newAnswer($input){
if(is_null($this->_applicationPage->getMax()) or count($this->getAnswers()) < $this->_applicationPage->getMax()){
$answer = new \Jazzee\Entity\Answer();
$answer->setPage($this->_applicationPage->getPage());
$this->_applicant->addAnswer($answer);
foreach($this->_applicationPage->getPage()->getElements() as $element){
$element->getJazzeeElement()->setController($this->_controller);
foreach($element->getJazzeeElement()->getElementAnswers($input->get('el'.$element->getId())) as $elementAnswer){
$answer->addElementAnswer($elementAnswer);
}
}
$this->getForm()->applyDefaultValues();
$this->_controller->getEntityManager()->persist($answer);
$this->_controller->addMessage('success', 'Answer Saved Successfully');
//flush here so the answerId will be correct when we view
$this->_controller->getEntityManager()->flush();
}
}
public function updateAnswer($input, $answerId){
if($answer = $this->_applicant->findAnswerById($answerId)){
foreach($answer->getElementAnswers() as $ea){
$answer->getElementAnswers()->removeElement($ea);
$this->_controller->getEntityManager()->remove($ea);
}
foreach($this->_applicationPage->getPage()->getElements() as $element){
$element->getJazzeeElement()->setController($this->_controller);
foreach($element->getJazzeeElement()->getElementAnswers($input->get('el'.$element->getId())) as $elementAnswer){
$answer->addElementAnswer($elementAnswer);
}
}
$this->getForm()->applyDefaultValues();
$this->getForm()->setAction($this->_controller->getActionPath());
$this->_controller->getEntityManager()->persist($answer);
$this->_controller->addMessage('success', 'Answer Updated Successfully');
}
}
public function deleteAnswer($answerId){
if($answer = $this->_applicant->findAnswerById($answerId)){
$this->_controller->getEntityManager()->remove($answer);
$this->_applicant->getAnswers()->removeElement($answer);
$this->_applicant->markLastUpdate();
$this->_controller->getEntityManager()->persist($this->_applicant);
$this->_controller->addMessage('success', 'Answered Deleted Successfully');
}
}
public function fill($answerId){
if($answer = $this->_applicant->findAnswerById($answerId)){
foreach($this->_applicationPage->getPage()->getElements() as $element){
$element->getJazzeeElement()->setController($this->_controller);
$value = $element->getJazzeeElement()->formValue($answer);
if($value) $this->getForm()->getElementByName('el' . $element->getId())->setValue($value);
}
$this->getForm()->setAction($this->_controller->getActionPath() . "/edit/{$answerId}");
}
}
/**
* Get all the answers for this page
* @return \Jazzee\Entity\Answer
*/
public function getAnswers(){
return $this->_applicant->findAnswersByPage($this->_applicationPage->getPage());
}
public function getXmlAnswers(\DOMDocument $dom){
$answers = array();
foreach($this->_applicant->findAnswersByPage($this->_applicationPage->getPage()) as $answer){
$answers[] = $this->xmlAnswer($dom, $answer);
}
return $answers;
}
/**
* Most pages don't require any setup
*
*/
public function setupNewPage(){
return;
}
/**
* Default CSV headers are just the elements for a page
* @return array
*/
public function getCsvHeaders(){
$headers = array();
foreach($this->_applicationPage->getPage()->getElements() as $element){
$headers[] = $element->getTitle();
}
return $headers;
}
/**
* Defaults to just usign the element display values
* @param int $position
* @return array
*/
function getCsvAnswer($position){
$arr = array();
$answers = $this->_applicant->findAnswersByPage($this->_applicationPage->getPage());
foreach($this->_applicationPage->getPage()->getElements() as $element){
$element->getJazzeeElement()->setController($this->_controller);
if(isset($answers[$position])){
$arr[] = $element->getJazzeeElement()->displayValue($answers[$position]);
} else {
$arr[] = '';
}
}
return $arr;
}
/**
* Convert an answer to an xml element
* @param \DomDocument $dom
* @param \Jazzee\Entity\Answer $answer
* @return \DomElement
*/
protected function xmlAnswer(\DomDocument $dom, \Jazzee\Entity\Answer $answer){
$answerXml = $dom->createElement('answer');
$answerXml->setAttribute('answerId', $answer->getId());
$answerXml->setAttribute('uniqueId', $answer->getUniqueId());
$answerXml->setAttribute('updatedAt', $answer->getUpdatedAt()->format('c'));
$answerXml->setAttribute('pageStatus', $answer->getPageStatus());
$answerXml->setAttribute('publicStatus', ($answer->getPublicStatus()?$answer->getPublicStatus()->getName():''));
$answerXml->setAttribute('privateStatus', ($answer->getPrivateStatus()?$answer->getPrivateStatus()->getName():''));
foreach($answer->getPage()->getElements() as $element){
$element->getJazzeeElement()->setController($this->_controller);
$eXml = $dom->createElement('element');
$eXml->setAttribute('elementId', $element->getId());
$eXml->setAttribute('title', htmlentities($element->getTitle(),ENT_COMPAT,'utf-8'));
$eXml->setAttribute('type', htmlentities($element->getType()->getClass(),ENT_COMPAT,'utf-8'));
$eXml->setAttribute('weight', $element->getWeight());
if($value = $element->getJazzeeElement()->rawValue($answer)) $eXml->appendChild($dom->createCDATASection(preg_replace('/[\x00-\x09\x0B\x0C\x0E-\x1F\x7F]/', '', $value)));
$answerXml->appendChild($eXml);
}
$attachment = $dom->createElement('attachment');
if($answer->getAttachment()) $attachment->appendChild($dom->createCDATASection(base64_encode($answer->getAttachment()->getAttachment())));
$answerXml->appendChild($attachment);
$children = $dom->createElement('children');
foreach($answer->getChildren() as $child){
$children->appendChild($this->xmlAnswer($dom, $child));
}
$answerXml->appendChild($children);
return $answerXml;
}
/**
* Create a table from answers
* and append any attached PDFs
* @param \Jazzee\ApplicantPDF $pdf
*/
public function renderPdfSection(\Jazzee\ApplicantPDF $pdf){
if($this->getAnswers()){
$pdf->addText($this->_applicationPage->getTitle(), 'h3');
$pdf->write();
$pdf->startTable();
$pdf->startTableRow();
foreach($this->_applicationPage->getPage()->getElements() as $element)$pdf->addTableCell($element->getTitle());
foreach($this->getAnswers() as $answer){
$pdf->startTableRow();
foreach($this->_applicationPage->getPage()->getElements() as $element){
$element->getJazzeeElement()->setController($this->_controller);
$pdf->addTableCell($element->getJazzeeElement()->pdfValue($answer, $pdf));
}
if($attachment = $answer->getAttachment()) $pdf->addPdf($attachment->getAttachment());
}
$pdf->writeTable();
}
}
/**
* By default just set the varialbe dont check it
* @param string $name
* @param string $value
*/
public function setVar($name, $value){
$var = $this->_applicationPage->getPage()->setVar($name, $value);
$this->_controller->getEntityManager()->persist($var);
}
/**
* Check if the current controller is an admin controller
* @throws \Jazzee\Exception if it isn't
*/
protected function checkIsAdmin(){
if($this->_controller instanceof \Jazzee\AdminController) return true;
throw new \Jazzee\Exception('Admin only action was called from a non admin controller');
}
}<file_sep><?php
namespace Jazzee\Interfaces;
/**
* Interface for Jazzee Elements
*
* @author <NAME> <<EMAIL>>
* @license http://jazzee.org/license.txt
* @package jazzee
* @subpackage elements
*/
interface Element
{
/**
* The path to the pagebuilder javascript
*/
const PAGEBUILDER_SCRIPT = 'resource/scripts/element_types/JazzeeElement.js';
/**
* Constructor
*
* @param \Jazzee\Entity\Element $element
*/
function __construct(\Jazzee\Entity\Element $element);
/**
* Set the controller
*
* @param \Jazzee\Controller $controller
*/
function setController(\Jazzee\Controller $controller);
/**
* Add a form element to the supplied field
* @param \Foundation\Form\Field $field
* @return \Foundation\Form\Element
*/
function addToField(\Foundation\Form\Field $field);
/**
* Create element answers and attach them to the answer
*
* @param mixed $input
* @return array \Jazzee\Entity\AnswerElement
*/
function getElementAnswers($input);
/**
* Get the value of the element formated for display
*
* @param \Jazzee\Entity\Answer $answer
* @return string
*/
function displayValue(\Jazzee\Entity\Answer $answer);
/**
* Get the value of the element that \Foundation\Form\Element will accept
*
* @param \Jazzee\Entity\Answer $answer
* @return mixed
*/
function formValue(\Jazzee\Entity\Answer $answer);
/**
* Get the raw value of the element
*
* @param \Jazzee\Entity\Answer $answer
* @return mixed
*/
function rawValue(\Jazzee\Entity\Answer $answer);
/**
* Get the pdf value of the element
*
* @param \Jazzee\Entity\Answer $answer
* @param \Jazzee\ApplicantPDF $pdf
* @return mixed
*/
function pdfValue(\Jazzee\Entity\Answer $answer, \Jazzee\ApplicantPDF $pdf);
/**
* Test a query
* Checks if answer meets query parameters
* @param \Jazzee\Entity\Answer $answer
* @param \stdClass $query
* @returns boolean
*/
public function testQuery(\Jazzee\Entity\Answer $answer, \stdClass $obj);
}
?><file_sep><?php
/**
* setup_roles index view
* @author <NAME> <<EMAIL>>
* @license http://jazzee.org/license.txt
* @package jazzee
* @subpackage setup
*/
if($roles): ?>
<h5>Roles:</h5>
<ul>
<?php foreach($roles as $role): ?>
<li><?php print $role->getName() ?>
<?php if($this->controller->checkIsAllowed('setup_roles', 'edit')): ?>
(<a href='<?php print $this->path('setup/roles/edit/') . $role->getId()?>'>Edit</a>)
<?php endif;?>
<?php if($this->controller->checkIsAllowed('setup_roles', 'copy')): ?>
(<a href='<?php print $this->path('setup/roles/copy/') . $role->getId()?>'>Copy</a>)
<?php endif;?>
</li>
<?php endforeach;?>
</ul>
<?php endif; ?>
<?php if($this->controller->checkIsAllowed('setup_roles', 'new')): ?>
<p><a href='<?php print $this->path('setup/roles/new')?>'>Add a new role</a></p>
<?php endif;?>
<file_sep><?php
namespace Jazzee\Console;
/**
* Sets up the first user
*
* @author <NAME> <<EMAIL>>
* @license http://jazzee.org/license.txt
* @package jazzee
* @subpackage console
*/
class UserRole extends \Symfony\Component\Console\Command\Command
{
/**
* @see Console\Command\Command
*/
protected function configure()
{
$this->setName('user-role') ->setDescription('Add a new user.');
$this->addArgument('user name', \Symfony\Component\Console\Input\InputArgument::REQUIRED, 'User name to act on. Use find-user to search for users in the directory.');
$this->addArgument('role name', \Symfony\Component\Console\Input\InputArgument::REQUIRED, 'The name of the role.');
$this->setHelp('Put a user in a role by name.');
}
protected function execute(\Symfony\Component\Console\Input\InputInterface $input, \Symfony\Component\Console\Output\OutputInterface $output){
$em = $this->getHelper('em')->getEntityManager();
$user = $em->getRepository('\Jazzee\Entity\User')->findOneBy(array('uniqueName'=>$input->getArgument('user name')));
if(!$user){
$output->write('<error>That user does not have an account on this system. User add-user to create one.</error>' . PHP_EOL);
exit();
}
$roles = $em->getRepository('\Jazzee\Entity\Role')->findBy(array('name'=>$input->getArgument('role name'),'isGlobal'=>true));
if(count($roles) == 0){
$output->write('<error>There are no roles with that name.</error>' . PHP_EOL);
exit();
}
if(count($roles) > 1){
$output->write('<error>There are ' . count($roles) . ' global roles with that name. You will have to add the user to a different role or edit the names in the web interface.</error>' . PHP_EOL);
exit();
}
$user->addRole($roles[0]);
$em->persist($user);
$em->flush();
$output->write("<info>{$user->getLastName()}, {$user->getFirstName()} added to {$roles[0]->getName()} role</info>" . PHP_EOL);
}
}<file_sep><?php
/**
* apply_status denyLetter iew
* @package jazzee
* @subpackage apply
*/
if($applicant->isLocked() and $applicant->getDecision()->getFinalDeny()){
print $text;
}
?><file_sep><?php
/**
* No Authentication
*
* Will only run in an environment set to TESTING
* Doesn't require any authentication - the desired user is chosen from a list
*
*/
namespace Jazzee\AdminAuthentication;
class NoAuthentication implements \Jazzee\Interfaces\AdminAuthentication{
const LOGIN_ELEMENT = 'NoAuthentication_Login';
const SESSION_VAR_ID = 'noauth_userid';
/**
* Our user
* @var \Jazzee\Entity\User
*/
private $_user;
/**
* Config instance
* @var \Jazzee\Controller
*/
private $_controller;
/**
* Login form
* @var \Foundation\Form
*/
private $_form;
/**
* Constructor
*
* Grab the desired user from the configuration file and log in as them
* @param \Jazzee\Interfaces\AdminController
*/
public function __construct(\Jazzee\Interfaces\AdminController $controller){
$this->_controller = $controller;
if($controller->getConfig()->getStatus() != 'DEVELOPMENT'){
throw new \Jazzee\Exception('Attmpted to use NoAuthentication in a non development environment.');
}
if($this->_controller->getStore()->check(self::SESSION_VAR_ID)){
$this->_user = $this->_controller->getEntityManager()->getRepository('\Jazzee\Entity\User')->find($this->_controller->getStore()->get(self::SESSION_VAR_ID));
}
}
public function isValidUser(){
return (bool)$this->_user;
}
public function getUser(){
return $this->_user;
}
public function loginUser(){
$form = $this->getLoginForm();
if($input = $form->processInput($_POST)){
$allowedIps = explode(',', $this->_controller->getConfig()->getNoAuthIpAddresses());
if(in_array($_SERVER['REMOTE_ADDR'], $allowedIps)){
$this->_user = $this->_controller->getEntityManager()->getRepository('\Jazzee\Entity\User')->findOneBy(array('id'=>$_POST['userid'], 'isActive'=>true));
$this->_controller->getStore()->expire();
$this->_controller->getStore()->touchAuthentication();
$this->_controller->getStore()->set(self::SESSION_VAR_ID, $this->_user->getId());
} else {
throw new \Jazzee\Exception("{$_SERVER['REMOTE_ADDR']} is not a valid ip address for NoAuthentication. Add it to the noAuthIpAddresses configuration to continue.");
}
}
}
/**
* Get the login form
*
* @return \Foundation\Form
*/
public function getLoginForm(){
if(is_null($this->_form)){
$this->_form = new \Foundation\Form;
$this->_form->setCSRFToken($this->_controller->getCSRFToken());
$this->_form->setAction($this->_controller->path("login"));
$field = $this->_form->newField();
$field->setLegend('Select a user');
$element = $field->newElement('SelectList','userid');
$element->setLabel('User');
$element->addValidator(new \Foundation\Form\Validator\NotEmpty($element));
foreach($this->_controller->getEntityManager()->getRepository('\Jazzee\Entity\User')->findByName('%','%') as $user){
if($user->isActive()) $element->newItem($user->getId(), "{$user->getLastName()}, {$user->getFirstName()} - {$user->getEmail()}");
}
$this->_form->newButton('submit', 'Login');
}
return $this->_form;
}
public function logoutUser(){
$this->_user = null;
$this->_controller->getStore()->expire();
}
}
<file_sep><?php
namespace Jazzee;
/**
* Base controller for all authenticated application controllers
* @author <NAME> <<EMAIL>>
* @license http://jazzee.org/license.txt
* @package jazzee
* @subpackage apply
*/
class AuthenticatedApplyController extends ApplyController
{
/**
* The applicant
* @var \Jazzee\Entity\Applicant
*/
protected $_applicant;
/**
* Check credentials and intialize members
*/
public function beforeAction(){
parent::beforeAction();
if(!isset($this->_store->applicantID)){
//Not authenticated
$this->addMessage('error', "You are not logged in or your session has expired. Please log in again");
$this->redirectApplyPath('applicant/login');
}
$this->_applicant = $this->_em->getRepository('\Jazzee\Entity\Applicant')->find($this->_store->applicantID);
//make sure the url path is the actual application
if($this->_application != $this->_applicant->getApplication()) $this->redirectApplyPath('applicant/login');
foreach($this->_pages as $applicationPage) $applicationPage->getJazzeePage()->setApplicant($this->_applicant);
$this->setVar('applicant', $this->_applicant);
}
}<file_sep><?php
/**
* manage_scores index view
* @author <NAME> <<EMAIL>>
* @license http://jazzee.org/license.txt
* @package jazzee
* @subpackage manage
*/
if(isset($form)){
$this->renderElement('form', array('form'=>$form));
}
?>
<table><caption>Score Statistics</caption>
<thead><tr><th>Score Type</th><th>Total in the system</th><th>Matched to applicant</th><th>Entered by applicants and not in the system</th></tr></thead>
<tbody>
<tr><td>GRE</td><td><?php print $greCount ?></td><td><?php print $greMatchedCount ?></td><td><?php print $greUnmatchedCount ?></td></tr>
<tr><td>TOEFL</td><td><?php print $toeflCount ?></td><td><?php print $toeflMatchedCount ?></td><td><?php print $toeflUnmatchedCount ?></td></tr>
</tbody>
</table>
<h4>List of GRE Cycles</h4>
<ul>
<?php foreach($greCycles as $cycle){?>
<li><?php print $cycle;?></li>
<?php } ?>
</ul><file_sep><?php
namespace Jazzee\Page;
/**
* Get recommender information from applicnats and send out invitations
*
* @author <NAME> <<EMAIL>>
* @license http://jazzee.org/license.txt
* @package jazzee
* @subpackage pages
*/
class Recommenders extends AbstractPage implements \Jazzee\Interfaces\StatusPage {
/**
* These fixedIDs make it easy to find the element we are looking for
* @const integer
*/
const FID_FIRST_NAME = 2;
const FID_LAST_NAME = 4;
const FID_INSTITUTION = 6;
const FID_EMAIL = 8;
const FID_PHONE = 10;
const FID_WAIVE_RIGHT = 12;
/**
* Get the message
* @param \Jazzee\Entity\Answer $answer
* @param string $link is different from admin and apply so it is sent as a parameter
* @return \Foundation\Mail\Message
*/
protected function getMessage(\Jazzee\Entity\Answer $answer, $link){
$search = array(
'_APPLICANT_NAME_',
'_DEADLINE_',
'_LINK_',
'_RECOMMENDER_FIRST_NAME_',
'_RECOMMENDER_LAST_NAME_',
'_RECOMMENDER_INSTITUTION_',
'_RECOMMENDER_EMAIL_',
'_RECOMMENDER_PHONE_',
'_APPLICANT_WAIVE_RIGHT_'
);
if($deadline = $this->_applicationPage->getPage()->getVar('lorDeadline')){
$deadline = new \DateTime($deadline);
} else {
$deadline = $this->_applicant->getApplication()->getClose();
}
$replace = array(
$this->_applicant->getFullName(),
$deadline->format('l F jS Y g:ia'),
$link
);
$replace[] = $this->_applicationPage->getPage()->getElementByFixedId(self::FID_FIRST_NAME)->getJazzeeElement()->displayValue($answer);
$replace[] = $this->_applicationPage->getPage()->getElementByFixedId(self::FID_LAST_NAME)->getJazzeeElement()->displayValue($answer);
$replace[] = $this->_applicationPage->getPage()->getElementByFixedId(self::FID_INSTITUTION)->getJazzeeElement()->displayValue($answer);
$replace[] = $this->_applicationPage->getPage()->getElementByFixedId(self::FID_EMAIL)->getJazzeeElement()->displayValue($answer);
$replace[] = $this->_applicationPage->getPage()->getElementByFixedId(self::FID_PHONE)->getJazzeeElement()->displayValue($answer);
$replace[] = $this->_applicationPage->getPage()->getElementByFixedId(self::FID_WAIVE_RIGHT)->getJazzeeElement()->displayValue($answer);
$body = str_ireplace($search, $replace, $this->_applicationPage->getPage()->getVar('recommenderEmailText'));
$message = $this->_controller->newMailMessage();
$message->AddCustomHeader('X-Jazzee-Applicant-ID:' . $this->_applicant->getId());
$message->AddAddress(
$this->_applicationPage->getPage()->getElementByFixedId(self::FID_EMAIL)->getJazzeeElement()->displayValue($answer),
$this->_applicationPage->getPage()->getElementByFixedId(self::FID_FIRST_NAME)->getJazzeeElement()->displayValue($answer) . ' ' . $this->_applicationPage->getPage()->getElementByFixedId(self::FID_LAST_NAME)->getJazzeeElement()->displayValue($answer));
$message->setFrom($this->_applicant->getApplication()->getContactEmail(), $this->_applicant->getApplication()->getContactName());
$message->Subject = 'Recommendation Request for ' . $this->_applicant->getFullName();
$message->Body = $body;
return $message;
}
/**
* Send the invitaiton email
* @param integer $answerID
* @param array $postData
*/
public function do_sendEmail($answerId, $postData){
if($answer = $this->_applicant->findAnswerById($answerId)){
if(!$answer->isLocked() OR (!$answer->getChildren()->count() AND $answer->getUpdatedAt()->diff(new \DateTime('now'))->days >= $answer->getPage()->getVar('lorWaitDays'))){
$message = $this->getMessage($answer, $this->_controller->path('lor/' . $answer->getUniqueId()));
$message->Send();
$answer->lock();
$answer->markLastUpdate();
$this->_controller->getEntityManager()->persist($answer);
$this->_controller->addMessage('success', 'Your invitation was sent successfully.');
}
}
}
/**
* Send the invitaiton email
* @param integer $answerID
* @param array $postData
*/
public function do_sendAdminInvitation($answerId, $postData){
$this->checkIsAdmin();
if($answer = $this->_applicant->findAnswerById($answerId)){
$path = $this->_controller->path('lor/' . $answer->getUniqueId());
$link = str_ireplace('admin/', '', $path);
$message = $this->getMessage($answer, $link);
$form = new \Foundation\Form;
$field = $form->newField();
$field->setLegend('Send Invitation');
$element = $field->newElement('Textarea', 'body');
$element->setLabel('Email Text');
$element->addValidator(new \Foundation\Form\Validator\NotEmpty($element));
$element->setValue($message->Body);
if(!empty($postData)){
if($input = $form->processInput($postData)){
$message->Body = $input->get('body');
$message->Send();
$answer->lock();
$answer->markLastUpdate();
$this->_controller->getEntityManager()->persist($answer);
$this->_controller->setLayoutVar('status', 'success');
} else {
$this->_controller->setLayoutVar('status', 'error');
}
}
$form->newButton('submit', 'Send Email');
return $form;
}
return false;
}
/**
* View the recommendation Link
* Admin feature to display the link that recommenders are emailed
* @param integer $answerID
* @param array $postData
*/
public function do_viewLink($answerId, $postData){
$this->checkIsAdmin();
if($answer = $this->_applicant->findAnswerById($answerId)){
$form = new \Foundation\Form;
$field = $form->newField();
$field->setLegend('Recommendation Link');
$element = $field->newElement('Plaintext', 'link');
if($answer->isLocked()){
$path = $this->_controller->path('lor/' . $answer->getUniqueId());
$path = str_ireplace('admin/', '', $path);
$element->setValue($path);
} else {
$element->setValue('No link is available until an invitation has been sent.');
}
$this->_controller->setLayoutVar('status', 'success');
return $form;
}
$this->_controller->setLayoutVar('status', 'error');
}
/**
* Edit a submitted recommendation
* Admin feature to edit a submitted recommendation
* @param integer $answerID
* @param array $postData
*/
public function do_editLor($answerId, $postData){
$this->checkIsAdmin();
if($child = $this->_applicant->findAnswerById($answerId)->getChildren()->first()){
$lorPage = $child->getPage();
$jp = $lorPage->getApplicationPageJazzeePage();
$jp->setController($this->_controller);
$jp->fillLorForm($child);
$form = $jp->getForm();
if(!empty($postData)){
if($input = $jp->validateInput($postData)){
$jp->updateLorAnswer($input, $child);
$this->_controller->setLayoutVar('status', 'success');
} else {
$this->_controller->setLayoutVar('status', 'error');
}
}
return $form;
}
$this->_controller->setLayoutVar('status', 'error');
}
/**
* Complete the recommendation
* Admin feature to complete a recommendation
* @param integer $answerID
* @param array $postData
*/
public function do_completeLor($answerId, $postData){
$this->checkIsAdmin();
if($answer = $this->_applicant->findAnswerById($answerId) and $answer->getChildren()->count() == 0){
$lorPage = $answer->getPage()->getChildren()->first();
$jp = $lorPage->getApplicationPageJazzeePage();
$jp->setController($this->_controller);
$form = $jp->getForm();
if(!empty($postData)){
if($input = $jp->validateInput($postData)){
$jp->newLorAnswer($input, $answer);
$this->_controller->setLayoutVar('status', 'success');
} else {
$this->_controller->setLayoutVar('status', 'error');
}
}
return $form;
}
$this->_controller->setLayoutVar('status', 'error');
}
/**
* Delete a submitted recommendation
* Admin feature to delete a submitted recommendation
* @param integer $answerID
*/
public function do_deleteLor($answerId){
$this->checkIsAdmin();
if($child = $this->_applicant->findAnswerById($answerId)->getChildren()->first()){
$lorPage = $child->getPage();
$jp = $lorPage->getApplicationPageJazzeePage();
$jp->setController($this->_controller);
$jp->deleteLorAnswer($child);
$this->_controller->setLayoutVar('status', 'success');
} else {
$this->_controller->setLayoutVar('status', 'error');
}
}
/**
* Create the recommenders form
*/
public function setupNewPage(){
$em = $this->_controller->getEntityManager();
$types = $em->getRepository('Jazzee\Entity\ElementType')->findAll();
$elementTypes = array();
foreach($types as $type){
$elementTypes[$type->getClass()] = $type;
};
$count = 1;
foreach(array(self::FID_FIRST_NAME=>'First Name',self::FID_LAST_NAME=>'Last Name',self::FID_INSTITUTION=>'Institution') as $fid => $title){
$element = new \Jazzee\Entity\Element;
$element->setType($elementTypes['\Jazzee\Element\TextInput']);
$element->setTitle($title);
$element->required();
$element->setWeight($count);
$element->setFixedId($fid);
$this->_applicationPage->getPage()->addElement($element);
$em->persist($element);
$count++;
}
$element = new \Jazzee\Entity\Element;
$element->setType($elementTypes['\Jazzee\Element\EmailAddress']);
$element->setTitle('Email Address');
$element->required();
$element->setWeight(5);
$element->setFixedId(self::FID_EMAIL);
$this->_applicationPage->getPage()->addElement($element);
$em->persist($element);
$element = new \Jazzee\Entity\Element;
$element->setType($elementTypes['\Jazzee\Element\Phonenumber']);
$element->setTitle('Phone Number');
$element->required();
$element->setWeight(6);
$element->setFixedId(self::FID_PHONE);
$this->_applicationPage->getPage()->addElement($element);
$em->persist($element);
$element = new \Jazzee\Entity\Element;
$element->setType($elementTypes['\Jazzee\Element\RadioList']);
$element->setTitle('Do you waive your right to view this letter at a later time?');
$element->required();
$element->setWeight(7);
$element->setFixedId(self::FID_WAIVE_RIGHT);
$this->_applicationPage->getPage()->addElement($element);
$em->persist($element);
$item = new \Jazzee\Entity\ElementListItem;
$item->setValue('Yes');
$item->setWeight(1);
$element->addItem($item);
$em->persist($item);
$item = new \Jazzee\Entity\ElementListItem;
$item->setValue('No');
$item->setWeight(2);
$element->addItem($item);
$em->persist($item);
$defaultVars = array(
'lorDeadline' => null,
'lorDeadlineEnforced' => false,
'recommenderEmailText' => '',
'lorWaitDays' => 14
);
foreach($defaultVars as $name=>$value){
$var = $this->_applicationPage->getPage()->setVar($name, $value);
$em->persist($var);
}
}
public function getStatus(){
$answers = $this->getAnswers();
if(!$this->_applicationPage->isRequired() and count($answers) and $answers[0]->getPageStatus() == self::SKIPPED){
return self::SKIPPED;
}
$completedAnswers = 0;
foreach($answers as $answer)if($answer->isLocked()) $completedAnswers++;
if(is_null($this->_applicationPage->getMin()) or $completedAnswers < $this->_applicationPage->getMin()){
return self::INCOMPLETE;
} else {
return self::COMPLETE;
}
}
/**
* Create a table from answers
* and append any attached PDFs
* @param \Jazzee\ApplicantPDF $pdf
*/
public function renderPdfSection(\Jazzee\ApplicantPDF $pdf){
if($this->getAnswers()){
$pdf->addText($this->_applicationPage->getTitle(), 'h3');
$pdf->write();
$pdf->startTable();
$pdf->startTableRow();
$pdf->addTableCell('Recommender');
foreach($this->_applicationPage->getPage()->getChildren()->first()->getElements() as $element)$pdf->addTableCell($element->getTitle());
foreach($this->getAnswers() as $answer){
$pdf->startTableRow();
$string = $this->_applicationPage->getPage()->getElementByFixedId(self::FID_FIRST_NAME)->getJazzeeElement()->pdfValue($answer, $pdf) . "\n";
$string .= $this->_applicationPage->getPage()->getElementByFixedId(self::FID_LAST_NAME)->getJazzeeElement()->pdfValue($answer, $pdf) . "\n";
$string .= $this->_applicationPage->getPage()->getElementByFixedId(self::FID_INSTITUTION)->getJazzeeElement()->pdfValue($answer, $pdf) . "\n";
$string .= $this->_applicationPage->getPage()->getElementByFixedId(self::FID_EMAIL)->getJazzeeElement()->pdfValue($answer, $pdf) . "\n";
$string .= $this->_applicationPage->getPage()->getElementByFixedId(self::FID_PHONE)->getJazzeeElement()->pdfValue($answer, $pdf) . "\n";
$pdf->addTableCell($string);
if($child = $answer->getChildren()->first()){
foreach($this->_applicationPage->getPage()->getChildren()->first()->getElements() as $element){
$element->getJazzeeElement()->setController($this->_controller);
$pdf->addTableCell($element->getJazzeeElement()->pdfValue($child, $pdf));
}
}
if($attachment = $answer->getAttachment()) $pdf->addPdf($attachment->getAttachment());
}
$pdf->writeTable();
}
}
public static function applyPageElement(){
return 'Recommenders-apply_page';
}
public static function pageBuilderScriptPath(){
return 'resource/scripts/page_types/JazzeePageRecommenders.js';
}
public static function applyStatusElement(){
return 'Recommenders-apply_status';
}
public static function applicantsSingleElement(){
return 'Recommenders-applicants_single';
}
/**
* Check variables before they are set
* @param string $name
* @param string $value
* @throws \Jazzee\Exception
*/
public function setVar($name, $value){
switch($name){
case 'lorDeadline':
if(!empty($value)){
if(!$value = \strtotime($value)){
throw new \Jazzee\Exception("{$value} is not a valid date for lorDeadline");
}
$value = \date('Y-m-d H:i:s', $value);
}
break;
case 'lorWaitDays':
if(!empty($value)){
$value = (int)$value;
if($value < 0 OR $value > 100){
throw new \Jazzee\Exception("lorWaitDays should be between 0 and 100. {$value} is not.");
}
}
break;
case 'lorDeadlineEnforced':
break;
case 'recommenderEmailText':
break;
default:
throw new \Jazzee\Exception($name . ' is not a valid variable on this page.');
}
parent::setVar($name, $value);
}
}<file_sep><?php
/**
* Single applicant view page
*/
$page->getJazzeePage()->setApplicant($applicant);
?>
<div class='page' id='page<?php print $page->getPage()->getId() ?>'>
<h4><?php print $page->getTitle(); ?></h4>
<?php if($page->getJazzeePage()->getStatus() == \Jazzee\Interfaces\Page::SKIPPED){?>
<p>Applicant Skipped this page.
<?php if($this->controller->checkIsAllowed('applicants_single', 'doPageAction')){
$answers = $page->getJazzeePage()->getAnswers();
?>
<a class='action' href='<?php print $this->path('applicants/single/' . $applicant->getId() . '/doPageAction/unskip/' . $page->getPage()->getId())?>'>Complete this page.</a>
<?php }?>
</p>
<?php } else if(count($page->getJazzeePage()->getAnswers())){ ?>
<div class='answers'>
<table class='answer'>
<thead>
<tr>
<?php foreach($page->getPage()->getElements() as $element){?><th><?php print $element->getTitle() ?></th><?php }?>
<th>Status</th>
<th>Attachment</th>
<?php if($this->controller->checkIsAllowed('applicants_single', 'editAnswer') or $this->controller->checkIsAllowed('applicants_single', 'deleteAnswer')){ ?><th>Tools</th><?php }?>
</tr>
</thead>
<tbody>
<?php
foreach($page->getJazzeePage()->getAnswers() as $answer){?>
<tr id='answer<?php print $answer->getId() ?>'>
<?php foreach($page->getPage()->getElements() as $element){
$element->getJazzeeElement()->setController($this->controller);
?><td><?php print $element->getJazzeeElement()->displayValue($answer); ?></td>
<?php }?>
<td>
<strong>Last Updated:</strong> <?php print $answer->getUpdatedAt()->format('M d Y g:i a');?>
<?php if($answer->getPublicStatus()){?><br />Public Status: <?php print $answer->getPublicStatus()->getName();}?>
<?php if($answer->getPrivateStatus()){?><br />Private Status: <?php print $answer->getPrivateStatus()->getName();}?>
<?php if($this->controller->checkIsAllowed('applicants_single', 'verifyAnswer')){ ?>
<br /><a href='<?php print $this->path('applicants/single/' . $answer->getApplicant()->getId() . '/verifyAnswer/' . $answer->getId());?>' class='actionForm'>Set Verification Status</a>
<?php } ?>
</td>
<td>
<?php if($attachment = $answer->getAttachment()){
$pdfName = $answer->getPage()->getTitle() . '_attachment_' . $answer->getId() . '.pdf';
$pngName = $answer->getPage()->getTitle() . '_attachment_' . $answer->getId() . 'preview.png';
if(!$pdfFile = $this->controller->getStoredFile($pdfName) or $pdfFile->getLastModified() < $answer->getUpdatedAt()){
$this->controller->storeFile($pdfName, $attachment->getAttachment());
}
if(!$pngFile = $this->controller->getStoredFile($pngName) or $pngFile->getLastModified() < $answer->getUpdatedAt()){
$this->controller->storeFile($pngName, $attachment->getThumbnail());
}
?>
<a href="<?php print $this->path('file/' . \urlencode($pdfName));?>"><img src="<?php print $this->path('file/' . \urlencode($pngName));?>" /></a>
<?php if($this->controller->checkIsAllowed('applicants_single', 'deleteAnswerPdf')){ ?>
<br /><a href='<?php print $this->path('applicants/single/' . $answer->getApplicant()->getId() . '/deleteAnswerPdf/' . $answer->getId());?>' class='action'>Delete PDF</a>
<?php } ?>
<?php } else if($this->controller->checkIsAllowed('applicants_single', 'attachAnswerPdf')){ ?>
<a href='<?php print $this->path('applicants/single/' . $answer->getApplicant()->getId() . '/attachAnswerPdf/' . $answer->getId());?>' class='actionForm'>Attach PDF</a>
<?php } ?>
</td>
<?php if($this->controller->checkIsAllowed('applicants_single', 'editAnswer')){ ?>
<td>
<?php if($this->controller->checkIsAllowed('applicants_single', 'editAnswer')){ ?>
<a href='<?php print $this->path('applicants/single/' . $answer->getApplicant()->getId() . '/editAnswer/' . $answer->getId());?>' class='actionForm'>Edit</a><br />
<?php } ?><?php if($this->controller->checkIsAllowed('applicants_single', 'deleteAnswer')){ ?>
<a href='<?php print $this->path('applicants/single/' . $answer->getApplicant()->getId() . '/deleteAnswer/' . $answer->getId());?>' class='action confirmDelete'>Delete</a><br />
<?php } ?>
</td>
<?php }?>
</tr>
<?php }?>
</tbody>
</table>
</div><!-- answers -->
<?php } else { ?>
<p>Applicant has not answered this section.</p>
<?php } ?>
<p class='pageTools'>
<?php if($this->controller->checkIsAllowed('applicants_single', 'addAnswer') and $page->getJazzeePage()->getStatus() != \Jazzee\Interfaces\Page::SKIPPED and (is_null($page->getMax()) or count($page->getJazzeePage()->getAnswers()) < $page->getMax())){?>
<a class='actionForm' href='<?php print $this->path('applicants/single/' . $applicant->getId() . '/addAnswer/' . $page->getPage()->getId());?>'>Add Answer</a>
<?php }?>
<?php if($this->controller->checkIsAllowed('applicants_single', 'doPageAction') and !$page->isRequired() and !count($page->getJazzeePage()->getAnswers())){?>
<a class='action' href='<?php print $this->path('applicants/single/' . $applicant->getId() . '/doPageAction/skip/' . $page->getPage()->getId());?>'>Skip Page</a>
<?php }?>
</p>
</div> <!-- page --><file_sep><?php
namespace Jazzee\Page;
/**
* Test the application for completness and lock it
*
* @author <NAME> <<EMAIL>>
* @license http://jazzee.org/license.txt
* @package jazzee
* @subpackage pages
*/
class Lock implements \Jazzee\Interfaces\Page, \Jazzee\Interfaces\FormPage {
/**
* The ApplicationPage Entity
* @var \Jazzee\Entity\ApplicationPage
*/
protected $_applicationPage;
/**
* Our controller
* @var \Jazzee\Controller
*/
protected $_controller;
/**
* The Applicant
* @var \Jazzee\Entity\Applicant
*/
protected $_applicant;
/**
* Contructor
*
* @param \Jazzee\Entity\ApplicationPage $applicationPage
*/
public function __construct(\Jazzee\Entity\ApplicationPage $applicationPage){
$this->_applicationPage = $applicationPage;
}
/**
*
* @see Jazzee.Page::setController()
*/
public function setController(\Jazzee\Controller $controller){
$this->_controller = $controller;
}
/**
*
* @see Jazzee.Page::setApplicant()
*/
public function setApplicant(\Jazzee\Entity\Applicant $applicant){
$this->_applicant = $applicant;
}
public function getForm(){
$form = new \Foundation\Form;
$form->setCSRFToken($this->_controller->getCSRFToken());
$form->setAction($this->_controller->getActionPath());
$field = $form->newField();
$field->setLegend($this->_applicationPage->getTitle());
$field->setInstructions($this->_applicationPage->getInstructions());
$element = $field->newElement('RadioList', 'lock');
$element->setLabel('Do you wish to lock your application?');
$element->newItem(0,'No');
$element->newItem(1,'Yes');
$element->addValidator(new \Foundation\Form\Validator\NotEmpty($element));
$form->newButton('submit','Submit Application');
return $form;
}
/**
* Test each page to see if it is complete
* @param FormInput $input
* @return bool
*/
public function validateInput($input){
if(!$input = $this->getForm()->processInput($input)) return false;
if(!$input->get('lock')){
$this->_form->getElementByName('lock')->addMessage('You must answer yes to submit your application.');
return false;
}
$error = false;
foreach($this->_applicant->getApplication()->getApplicationPages(\Jazzee\Entity\ApplicationPage::APPLICATION) as $page){
if($page != $this->_applicationPage){ //dont check the lock page (this page), it will never be complete
if($page->getJazzeePage()->getStatus() == self::INCOMPLETE){
$error = true;
$this->_controller->addMessage('error', 'You have not completed the ' . $page->getTitle() . ' page');
}
}
}
return !$error;
}
public function newAnswer($input){
$this->_applicant->lock();
$this->_controller->getEntityManager()->persist($this->_applicant);
$this->_controller->addMessage('success', 'Your application has been submitted.');
$this->_controller->redirectUrl($this->_controller->getActionPath());
}
/**
* Lock Doesn't update answers
* @param type $input
* @param type $answerId
* @return boolean
*/
public function updateAnswer($input, $answerId){
return false;
}
/**
* Lock Doesn't delete answers
* @param type $answerId
* @return boolean
*/
public function deleteAnswer($answerId){
return false;
}
public function fill($answerId){
if($answer = $this->_applicant->findAnswerById($answerId)){
foreach($this->_applicationPage->getPage()->getElements() as $element){
$element->getJazzeeElement()->setController($this->_controller);
$value = $element->getJazzeeElement()->formValue($answer);
if($value) $this->getForm()->getElementByName('el' . $element->getId())->setValue($value);
}
$this->getForm()->setAction($this->_controller->getActionPath() . "/edit/{$answerId}");
}
}
/**
* No Special setup
* @return null
*/
public function setupNewPage(){
return;
}
public static function applyPageElement(){
return 'Standard-apply_page';
}
public static function pageBuilderScriptPath(){
return 'resource/scripts/page_types/JazzeePageLock.js';
}
/**
* Lock Pages are always incomplete
*/
public function getStatus(){
if($this->_applicant->isLocked()) return self::COMPLETE;
return self::INCOMPLETE;
}
/**
* By default just set the varialbe dont check it
* @param string $name
* @param string $value
*/
public function setVar($name, $value){
$var = $this->_applicationPage->getPage()->setVar($name, $value);
$this->_controller->getEntityManager()->persist($var);
}
}
?><file_sep><?php
/**
* Standard page LOR single applicant answer element
*/
if($attachment = $answer->getAttachment()){
$pdfName = $answer->getPage()->getTitle() . '_attachment_' . $answer->getId() . '.pdf';
$pngName = $answer->getPage()->getTitle() . '_attachment_' . $answer->getId() . 'preview.png';
if(!$pdfFile = $this->controller->getStoredFile($pdfName) or $pdfFile->getLastModified() < $answer->getUpdatedAt()){
$this->controller->storeFile($pdfName, $attachment->getAttachment());
}
if(!$pngFile = $this->controller->getStoredFile($pngName) or $pngFile->getLastModified() < $answer->getUpdatedAt()){
$this->controller->storeFile($pngName, $attachment->getThumbnail());
}
?>
<a href="<?php print $this->path('file/' . \urlencode($pdfName));?>"><img src="<?php print $this->path('file/' . \urlencode($pngName));?>" /></a>
<?php if($this->controller->checkIsAllowed('applicants_single', 'deleteAnswerPdf')){ ?>
<br /><a href='<?php print $this->path('applicants/single/' . $answer->getApplicant()->getId() . '/deleteAnswerPdf/' . $answer->getId());?>' class='action'>Delete PDF</a>
<?php } ?>
<?php } else if($this->controller->checkIsAllowed('applicants_single', 'attachAnswerPdf')){ ?>
<a href='<?php print $this->path('applicants/single/' . $answer->getApplicant()->getId() . '/attachAnswerPdf/' . $answer->getId());?>' class='actionForm'>Attach PDF</a>
<?php }<file_sep><?php
namespace Jazzee;
/**
* Jazzee base controller
*
* Requires working configuration and dependancies.
* Most usefull contorllers descend from here
* @package jazzee
*/
class JazzeeController extends PageController
{
/**
* Holds the session
* @var \Foundation\Session
*/
protected $_session;
/**
* Holds the EmailServer class for sending messages
* @var \Foundation\Mail\Server
*/
protected $_mailServer;
/**
* Holds the Doctrine EntityManager
* @var \Doctrine\ORM\EntityManager
*/
protected $_em;
/**
* Constructor
* Set up configuration containers
* Start session handling
* Setup error processing and email
*/
public function __construct(){
parent::__construct();
if($this->_config->getMode() == 'MAINTENANCE'){
$request = new \Lvc_Request();
$request->setControllerName('error');
$request->setActionName('index');
if(!$message = $this->_config->getMaintenanceModeMessage()) $message = 'The application is currently down for maintenance';
$request->setActionParams(array('error' => '503', 'message'=>$message));
// Get a new front controller without any routers, and have it process our handmade request.
$fc = new \Lvc_FrontController();
$fc->processRequest($request);
exit();
}
$this->setupDoctrine();
$this->setupSession();
}
/**
* Before any action is taken do some basic setup
* Look for out of bounds file uploads
* Crate a navigation instance
* Create the default layout varialbes so the layout doesn't have to guess if they are available
* @return null
*/
protected function beforeAction(){
parent::beforeAction();
/*
When the php post_max_size attribute is exceed the POST array is blanked.
So a check has to be done using the CONTENT_LENGTH superglobal against the post_max_size value on every request
*/
if(!empty($_SERVER['CONTENT_LENGTH'])){
$max = \Foundation\Utility::convertIniShorthandValue(\ini_get('post_max_size'));
if($_SERVER['CONTENT_LENGTH'] > $max){
$this->addMessage('error', 'Your input has exceeded the maximum allowed size. If you are trying to upload a file it is too large. Please reduce your file size and try again');
}
}
//add jquery
$this->addScript($this->path('resource/foundation/scripts/jquery.js'));
$this->addScript($this->path('resource/foundation/scripts/jqueryui.js'));
$this->addScript($this->path('resource/foundation/scripts/jquery.json.js'));
$this->addScript($this->path('resource/foundation/scripts/jquery.cookie.js'));
$this->addScript($this->path('resource/foundation/scripts/jquery.qtip.js'));
$this->addScript($this->path('resource/foundation/scripts/anytime.js'));
$this->addCss($this->path('resource/foundation/styles/jquery.qtip.css'));
//add the Services javascript class
$this->addScript($this->path('resource/scripts/classes/Services.class.js'));
if($this->_config->getBroadcastMessage()) $this->addMessage('info', $this->_config->getBroadcastMessage());
}
/**
* Flush the EntityManager to persist all changes
*/
protected function afterAction(){
$this->_em->flush();
}
/**
* Add a message for the user
* @param string $type
* @param string $text
*/
public function addMessage($type, $text){
if(isset($this->_session->getStore('messages')->messages)) $messages = $this->_session->getStore('messages')->messages;
else $messages = array();
$messages[] = array('type'=>$type, 'text'=>$text);
$this->_session->getStore('messages')->messages = $messages;
}
/**
* Get messages
* @return array
*/
public function getMessages(){
$messages = array();
if(isset($this->_session->getStore('messages')->messages)){
$messages = $this->_session->getStore('messages')->messages;
$this->_session->getStore('messages')->messages = array();
}
return $messages;
}
/**
* Get a new mail message class
*
* @return \Foundation\Mail\Message
*/
public function newMailMessage(){
return new \Foundation\Mail\Message($this->_foundationConfig);
}
/**
* Setup Doctrine ORM
*/
protected function setupDoctrine(){
//setup doctrine
$doctrineConfig = new \Doctrine\ORM\Configuration();
//We use different caching and proxy settings in Development status
if($this->_config->getStatus() == 'DEVELOPMENT'){
$doctrineConfig->setAutoGenerateProxyClasses(true);
$doctrineConfig->setProxyDir($this->getVarPath() . '/tmp');
$cache = new \Doctrine\Common\Cache\ArrayCache;
} else {
$doctrineConfig->setAutoGenerateProxyClasses(false);
$doctrineConfig->setProxyDir(__DIR__ . '/Entity/Proxy');
if(!extension_loaded('apc')) throw new Exception('APC cache is required, but was not available.');
$cache = new \Doctrine\Common\Cache\ApcCache;
//use the path as a namespace so multiple installs on the same system dont conflict
$cache->setNamespace('JAZZEE-' . str_ireplace(array('/',' '),'', __DIR__));
}
$driver = $doctrineConfig->newDefaultAnnotationDriver(array(__DIR__."/Entity"));
$doctrineConfig->setMetadataDriverImpl($driver);
$doctrineConfig->setProxyNamespace('Jazzee\Entity\Proxy');
$doctrineConfig->setMetadataCacheImpl($cache);
$doctrineConfig->setQueryCacheImpl($cache);
$connectionParams = array(
'dbname' => $this->_config->getDbName(),
'user' => $this->_config->getDbUser(),
'password' => $this->_<PASSWORD>->get<PASSWORD>(),
'host' => $this->_config->getDbHost(),
'port' => $this->_config->getDbPort(),
'driver' => $this->_config->getDbDriver(),
'charset' => 'utf8'
);
$this->_em = \Doctrine\ORM\EntityManager::create($connectionParams, $doctrineConfig);
$this->_em->getConnection()->setCharset('utf8');
}
/**
* Get the entity manager
*
* @return \Doctrine\ORM\EntityManager
*/
public function getEntityManager(){
return $this->_em;
}
/**
* Setup Sessions
*/
protected function setupSession(){
//setup the session based on the configuration
$this->_session = new \Foundation\Session();
//if the session name variable is empty then there is no way to login and fix it so look for an empty session name and default to the ini value if it is blank
$this->_session->setConfigVariable('name', $this->_config->getSessionName()?ini_get('session.name'):$this->_config->getSessionName());
//cookies last forever (until browser is closed) which takes the users local clock out of the picture
//Timeouts are handled By Session internally by expiring the Session_Store
$this->_session->setConfigVariable('cookie_lifetime', 0);
//since files are stored in sessions destroy any files after one day
$this->_session->setConfigVariable('gc_maxlifetime', 86400);
$this->_session->setConfigVariable('use_only_cookies', true);
$this->_session->setConfigVariable('hash_function', 1);
$this->_session->setConfigVariable('save_path', $this->getVarPath() . '/session/');
if(!empty($_SERVER['HTTPS']) AND $_SERVER['HTTPS'] == 'on'){
$this->_session->setConfigVariable('cookie_secure', true);
}
$this->_session->setConfigVariable('cookie_path', rtrim(dirname($_SERVER['SCRIPT_NAME']),'/\\.') . '/');
//browsers give inconsisten results when the domain is used to set the cookie, instead use an empty string to restrict the cookie to this domain
$this->_session->setConfigVariable('cookie_domain', '');
$this->_session->start();
}
/**
* Store a file
*
* @param string $filename
* @param blob $blob
*/
public function storeFile($filename, $blob){
$ext = pathinfo($filename, PATHINFO_EXTENSION);
$safeName = md5($filename);
file_put_contents($this->getVarPath() . '/tmp/' . $safeName . '.' . $ext, $blob);
$session = new \Foundation\Session();
$store = $session->getStore('files');
$store->$safeName = $filename;
}
/**
* Get a stored file
*
* @param string $filename
* @return \Foundation\Virtual\RealFile
*/
public function getStoredFile($filename){
$ext = pathinfo($filename, PATHINFO_EXTENSION);
$safeName = md5($filename);
$path = $this->getVarPath() . '/tmp/' . $safeName . '.' . $ext;
$session = new \Foundation\Session();
$store = $session->getStore('files');
if(is_readable($path) and isset($store->$safeName) and $store->$safeName == $filename)
return new \Foundation\Virtual\RealFile($filename, $path);
return false;
}
/**
* Get a secret key for csrf validation
* @return string
*/
public function getCSRFToken(){
$store = $this->_session->getStore('csrf');
if(!isset($store->token)) $store->token = md5(uniqid('csrftoken'. rand(), true) . session_id());
return $store->token;
}
}<file_sep><?php
/**
* Manage Pending Payments
* @author <NAME> <<EMAIL>>
* @package jazzee
* @subpackage manage
*/
class ManagePendingPaymentsController extends \Jazzee\AdminController {
const MENU = 'Manage';
const TITLE = 'Pending Payments';
const PATH = 'manage/pendingpayments';
const ACTION_INDEX = 'View Pending Payments';
const ACTION_SETTLE = 'Settle Pending Payment';
const REQUIRE_APPLICATION = false;
/**
* Add the required JS
*/
protected function setUp(){
parent::setUp();
$this->addScript($this->path('resource/scripts/classes/Status.class.js'));
$this->addScript($this->path('resource/scripts/classes/ChangeProgram.class.js'));
$this->addScript($this->path('resource/scripts/controllers/manage_pendingpayments.controller.js'));
}
/**
* List all the pending payments in the system
*/
public function actionIndex(){
$pendingPayments = $this->_em->getRepository('\Jazzee\Entity\Payment')->findBy(array('status'=>\Jazzee\Entity\Payment::PENDING));
$this->setVar('pendingPayments', $pendingPayments);
}
}
?><file_sep><?php
/**
* Display user messages
* @author <NAME> <<EMAIL>>
* @license http://jazzee.org/license.txt
* @package jazzee
* @subpackage apply
*/
$messages = $this->controller->getMessages();
foreach($messages as $message){
print "<p class='{$message['type']}'>{$message['text']}</p>";
}
?><file_sep><?php
namespace Jazzee\Interfaces;
/**
* CSV Page interface
* Pages which implement this can generate CSV for their answers
*
* @author <NAME> <<EMAIL>>
* @license http://jazzee.org/license.txt
* @package jazzee
* @subpackage pages
*/
interface CsvPage
{
/**
* Get the CSV Headers
*
* Some elements like branching need special attention for the header row
* of a csv file
* @return array
*/
function getCsvHeaders();
/**
* Get the CSV Answers
*
* CSV Answers have to be linear so we use a counter when asking for the answers
* and return only the answer for that counter. If there is no answer return a
* blank array with the right number of blank elements
* @param int $position
* @return array
*/
function getCsvAnswer($position);
}<file_sep><?php
/**
* manage_paymenttypes index view
* @author <NAME> <<EMAIL>>
* @package jazzee
* @subpackage manage
*/
if($paymentTypes): ?>
<h5>Current Payment Types:</h5>
<ul>
<?php foreach($paymentTypes as $type): ?>
<li><?php print $type->getName() ?>
<?php if($this->controller->checkIsAllowed('manage_paymenttypes', 'edit')): ?>
(<a href='<?php print $this->path('manage/paymenttypes/edit/') . $type->getId()?>'>Edit</a>)
<?php endif;?>
<?php if(!$type->isExpired() and $this->controller->checkIsAllowed('manage_paymenttypes', 'expire')): ?>
(<a href='<?php print $this->path('manage/paymenttypes/expire/') . $type->getId()?>'>Expire</a>)
<?php endif;?>
<?php if($type->isExpired() and $this->controller->checkIsAllowed('manage_paymenttypes', 'unExpire')): ?>
(<a href='<?php print $this->path('manage/paymenttypes/unExpire/') . $type->getId()?>'>Un-Expire</a>)
<?php endif;?>
</li>
<?php endforeach;?>
</ul>
<?php endif; ?>
<?php if($this->controller->checkIsAllowed('manage_paymenttypes', 'new')): ?>
<p><a href='<?php print $this->path('manage/paymenttypes/new')?>'>Add a New Payment Type</a></p>
<?php endif;?><file_sep>/**
* The List is an abstract for other list elements
@extends JazzeeElement
*/
function List(){}
List.prototype = new JazzeeElement();
List.prototype.constructor = List;
/**
* Add a list manager to the options block
*/
List.prototype.elementProperties = function(){
var element = this;
var div = JazzeeElement.prototype.elementProperties.call(this);
div.append(this.newListItemsButton());
div.append(this.editListItemButton());
div.append(this.manageListItemsButton());
return div;
};
/**
* Add new list items button
* @return {jQuery}
*/
List.prototype.newListItemsButton = function(){
var elementClass = this;
var obj = new FormObject();
var field = obj.newField({name: 'legend', value: 'New List Items'});
var element = field.newElement('Textarea', 'text');
element.label = 'New Items';
element.instructions = 'One new item per line';
var dialog = this.page.displayForm(obj);
$('form', dialog).bind('submit',function(e){
var values = $('textarea[name="text"]', this).val().split("\n");
for(var i = 0;i<values.length; i++){
elementClass.newListItem(values[i]);
}
dialog.dialog("destroy").remove();
elementClass.workspace();
return false;
});//end submit
var button = $('<button>').html('Add List Items').bind('click',function(){
$('.qtip').qtip('api').hide();
dialog.dialog('open');
}).button({
icons: {
primary: 'ui-icon-plus'
}
});
return button;
};
/**
* Manage List Items button
* @return {jQuery}
*/
List.prototype.manageListItemsButton = function(){
var elementClass = this;
var button = $('<button>').html('Manage Items').bind('click',function(){
$('.qtip').qtip('api').hide();
var div = elementClass.page.createDialog();
var activeList = $('<ul>').addClass('active connectedSortable').addClass('container');
var inactiveList = $('<ul>').addClass('inactive connectedSortable').addClass('container');
for(var i = 0; i< elementClass.listItems.length; i++){
var item = elementClass.listItems[i];
if(item.isActive){
activeList.append($('<li>').html(item.value).data('item', item).addClass('ui-state-default'));
} else {
inactiveList.append($('<li>').html(item.value).data('item', item).addClass('ui-state-default'));
}
}
var activeDiv = $('<div>').html('<h5>Active Items</h5>').append(activeList).addClass('yui-u first');
div.append(activeDiv);
div.append($('<div>').html('<h5>Inactive Items</h5>').append(inactiveList).addClass('yui-u'));
$('ul',div).sortable({connectWith: '.connectedSortable'});
var text = $('<a>').attr('href','#').html(' (sort desc) ').bind('click',function(){
$('li',activeList).sort(function(a,b){
return a.innerHTML.toUpperCase() < b.innerHTML.toUpperCase() ? 1 : -1;
}).appendTo(activeList);
return false;
});
$('h5',activeDiv).append(text);
var text = $('<a>').attr('href','#').html(' (sort asc) ').bind('click',function(){
$('li',activeList).sort(function(a,b){
return a.innerHTML.toUpperCase() > b.innerHTML.toUpperCase() ? 1 : -1;
}).appendTo(activeList);
return false;
});
$('h5',activeDiv).append(text);
var button = $('<button>').html('Save').bind('click',function(){
var orderedItems = [];
$('ul.active li', div).each(function(i){
var item = $(this).data('item');
item.weight = i+1;
item.isActive = true;
orderedItems.push(item);
});
$('ul.inactive li', div).each(function(i){
var item = $(this).data('item');
item.weight = i+100;
item.isActive = false;
orderedItems.push(item);
});
elementClass.markModified();
elementClass.listItems = orderedItems;
div.dialog("destroy").remove();
elementClass.workspace();
return false;
}).button({
icons: {
primary: 'ui-icon-disk'
}
});
div.append(button);
div.dialog('open');
}).button({
icons: {
primary: 'ui-icon-arrow-1-nw'
}
});
return button;
};
/**
* Edit List Item button
* @return {jQuery}
*/
List.prototype.editListItemButton = function(){
var elementClass = this;
var ul = $('<ul>');
for(var i = 0; i < this.listItems.length; i++){
var item = this.listItems[i];
if(item.isActive){
var a = $('<a>').attr('href','#').html(item.value).data('item', item).bind('click', function(e){
$('.qtip').qtip('api').hide();
var item = $(e.target).data('item');
var obj = new FormObject();
var field = obj.newField({name: 'legend', value: 'Edit Item'});
var element = field.newElement('TextInput', 'value');
element.label = 'Item Value';
element.required = true;
element.value = item.value;
var dialog = elementClass.page.displayForm(obj);
$('form', dialog).bind('submit',function(e){
item.value = $('input[name="value"]', this).val();
elementClass.workspace();
dialog.dialog("destroy").remove();
elementClass.markModified();
return false;
});//end submit
dialog.dialog('open');
return false;
});
ul.append($('<li>').append(a));
}
}
var button = $('<button>').html('Edit List Item');
button.button({
icons: {
primary: 'ui-icon-pencil',
secondary: 'ui-icon-carat-1-s'
}
});
button.qtip({
position: {
my: 'top-left',
at: 'bottom-left'
},
show: {
event: 'click'
},
hide: {
event: 'unfocus click mouseleave',
delay: 500,
fixed: true
},
content: {
text: ul,
title: {
text: 'Choose an item to edit',
button: true
}
}
});
return button;
};
/**
* Add a new New item for the list
* @param {String} value the items text
*/
List.prototype.newListItem = function(value){
var itemId = 'new-list-item' + this.page.pageBuilder.getUniqueId();
var item = {id: itemId, value: value, isActive: true, weight: this.listItems.length+1};
this.addListItem(item);
this.markModified();
return item;
};
/**
* Add a new item to the list
* @param {String} value the items text
*/
List.prototype.addListItem = function(item){
this.listItems.push(item);
return item;
};
<file_sep><?php
namespace Jazzee\Entity;
/**
* Applicant
* Individual applicants are tied to an Application - but a single person can be multiple Applicants
* @HasLifecycleCallbacks
* @Entity(repositoryClass="\Jazzee\Entity\ApplicantRepository")
* @Table(name="applicants",
* uniqueConstraints={
* @UniqueConstraint(name="application_email", columns={"application_id", "email"}),
* @UniqueConstraint(name="applicant_uniqueId", columns={"uniqueId"})
* },
* indexes={@index(name="applicant_email", columns={"email"})}
* )
* @package jazzee
* @subpackage orm
**/
class Applicant{
/**
* @Id
* @Column(type="bigint")
* @GeneratedValue(strategy="AUTO")
*/
private $id;
/** @Column(type="string", length=255, nullable=true) */
private $uniqueId;
/**
* @ManyToOne(targetEntity="Application", inversedBy="applicants")
* @JoinColumn(onDelete="CASCADE")
*/
private $application;
/** @Column(type="string") */
private $email;
/** @Column(type="string") */
private $password;
/** @Column(type="boolean") */
private $isLocked;
/** @Column(type="string") */
private $firstName;
/** @Column(type="string", nullable=true) */
private $middleName;
/** @Column(type="string") */
private $lastName;
/** @Column(type="string", nullable=true) */
private $suffix;
/** @Column(type="datetime", nullable=true) */
private $deadlineExtension;
/** @Column(type="datetime", nullable=true) */
private $lastLogin;
/** @Column(type="string", length=15, nullable=true) */
private $lastLoginIp;
/** @Column(type="string", length=15, nullable=true) */
private $lastFailedLoginIp;
/** @Column(type="integer", nullable=true) */
private $failedLoginAttempts;
/** @Column(type="datetime", nullable=true) */
private $createdAt;
/** @Column(type="datetime", nullable=true) */
private $updatedAt;
/** @Column(type="float") */
private $percentComplete;
/** @Column(type="boolean") */
private $hasPaid;
/**
* @OneToMany(targetEntity="Answer",mappedBy="applicant")
*/
private $answers;
/**
* @OneToMany(targetEntity="Attachment",mappedBy="applicant")
*/
private $attachments;
/**
* @OneToOne(targetEntity="Decision",mappedBy="applicant", cascade={"persist"})
*/
private $decision;
/**
* @ManyToMany(targetEntity="Tag", inversedBy="applicants")
* @JoinTable(name="applicant_tags")
**/
private $tags;
/**
* @OneToMany(targetEntity="Thread",mappedBy="applicant")
* @OrderBy({"createdAt" = "ASC"})
*/
private $threads;
/**
* @OneToMany(targetEntity="Duplicate", mappedBy="applicant")
*/
private $duplicates;
/**
* @OneToMany(targetEntity="AuditLog", mappedBy="applicant")
*/
protected $auditLogs;
/**
* If we set a manual update don't override it
* @var boolean
*/
private $updatedAtOveridden = false;
public function __construct(){
$this->answers = new \Doctrine\Common\Collections\ArrayCollection();
$this->attachments = new \Doctrine\Common\Collections\ArrayCollection();
$this->tags = new \Doctrine\Common\Collections\ArrayCollection();
$this->threads = new \Doctrine\Common\Collections\ArrayCollection();
$this->duplicates = new \Doctrine\Common\Collections\ArrayCollection();
$this->createdAt = new \DateTime('now');
$this->isLocked = false;
$this->percentComplete = 0;
$this->hasPaid = false;
}
/**
* Get id
*
* @return bigint $id
*/
public function getId(){
return $this->id;
}
/**
* Set email
*
* @param string $email
*/
public function setEmail($email){
$this->email = $email;
}
/**
* Get email
*
* @return string $email
*/
public function getEmail(){
return $this->email;
}
/**
* Set password
*
* @param string $password
*/
public function setPassword($password){
$p = new \PasswordHash(8, FALSE);
$this->password = $p->HashPassword($password);
//when a new password is set reset the failedLogin counter
$this->failedLoginAttempts = 0;
}
/**
* Set Hashed password
* Store the previously hashed version of the password
* @param string $password
*/
public function setHashedPassword($password){
$this->password = $password;
}
/**
* Get password
*
* @return string $password
*/
public function getPassword(){
return $this->password;
}
/**
* Check a password against its hash
* @param string $password
* @param string $hashedPassword
*/
public function checkPassword($password){
$p = new \PasswordHash(8, FALSE);
return $p->CheckPassword($password, $this->password);
}
/**
* Generate a unique id
*/
public function generateUniqueId(){
//PHPs uniquid function is time based and therefor guessable
//A stright random MD5 sum is too long for email and tends to line break causing usability problems
//So we get unique through uniquid and we get random by prefixing it with a part of an MD5
//hopefully this results in a URL friendly short, but unguessable string
$prefix = substr(md5($this->password . mt_rand()*mt_rand()),rand(0,24), rand(6,8));
$this->uniqueId = \uniqid($prefix);
}
/**
* Set a uniqueid
* Prefferably call generateUniqueId - but it can also be set manually
* @param string $uniqueId;
*/
public function setUniqueId($uniqueId){
$this->uniqueId = $uniqueId;
}
/**
* Get uniqueId
*
* @return string $uniqueId
*/
public function getUniqueId(){
return $this->uniqueId;
}
/**
* Lock the Applicant
*/
public function lock(){
$this->isLocked = true;
if(is_null($this->decision)){
$this->decision = new Decision();
$this->decision->setApplicant($this);
}
}
/**
* UnLock the Applicant
*/
public function unLock(){
$this->isLocked = false;
}
/**
* Get locked
*
* @return boolean $locked
*/
public function isLocked(){
return $this->isLocked;
}
/**
* Set firstName
*
* @param string $firstName
*/
public function setFirstName($firstName){
$this->firstName = $firstName;
}
/**
* Get firstName
*
* @return string $firstName
*/
public function getFirstName(){
return $this->firstName;
}
/**
* Set middleName
*
* @param string $middleName
*/
public function setMiddleName($middleName){
$this->middleName = $middleName;
}
/**
* Get middleName
*
* @return string $middleName
*/
public function getMiddleName(){
return $this->middleName;
}
/**
* Set lastName
*
* @param string $lastName
*/
public function setLastName($lastName){
$this->lastName = $lastName;
}
/**
* Get lastName
*
* @return string $lastName
*/
public function getLastName(){
return $this->lastName;
}
/**
* Set suffix
*
* @param string $suffix
*/
public function setSuffix($suffix){
$this->suffix = $suffix;
}
/**
* Get suffix
*
* @return string $suffix
*/
public function getSuffix(){
return $this->suffix;
}
/**
* Get an applicants full name
*
* Combines all the name parts nicely
*/
public function getFullName(){
$name = $this->firstName . ' ';
if($this->middleName) $name .= $this->middleName;
$name .= ' ' . $this->lastName;
if($this->suffix) $name .= ' ' . $this->suffix;
return $name;
}
/**
* Set deadlineExtension
*
* @param string $deadlineExtension
*/
public function setDeadlineExtension($deadlineExtension){
$this->deadlineExtension = new \DateTime($deadlineExtension);
}
/**
* Get deadlineExtension
*
* @return DateTime $deadlineExtension
*/
public function getDeadlineExtension(){
return $this->deadlineExtension;
}
/**
* remove deadlineExtension
*/
public function removeDeadlineExtension(){
$this->deadlineExtension = null;
}
/**
* Register a sucessfull login
*
*/
public function login(){
$this->lastLogin = new \DateTime();
$this->lastLoginIp = $_SERVER['REMOTE_ADDR'];
$this->failedLoginAttempts = 0;
}
/**
* set lastLogin
*
* @param string $lastLogin
*/
public function setLastLogin($lastLogin){
$this->lastLogin = new \DateTime($lastLogin);
}
/**
* Get lastLogin
*
* @return \DateTime $lastLogin
*/
public function getLastLogin(){
return $this->lastLogin;
}
/**
* Get lastLoginIp
*
* @return string $lastLoginIp
*/
public function getLastLoginIp(){
return $this->lastLoginIp;
}
/**
* Get lastFailedLoginIp
*
* @return string $lastFailedLoginIp
*/
public function getLastFailedLoginIp(){
return $this->lastFailedLoginIp;
}
/**
* Fail an applicant login
*/
public function loginFail(){
$this->lastFailedLoginIp = $_SERVER['REMOTE_ADDR'];
$this->failedLoginAttempts++;
}
/**
* Get failedLoginAttempts
*
* @return integer $failedLoginAttempts
*/
public function getFailedLoginAttempts(){
return $this->failedLoginAttempts;
}
/**
* Set createdAt
*
* @param string $createdAt
*/
public function setCreatedAt($createdAt){
$this->createdAt = new \DateTime($createdAt);
}
/**
* Get createdAt
*
* @return \DateTime $createdAt
*/
public function getCreatedAt(){
return $this->createdAt;
}
/**
* Mark the lastUpdate automatically
* @PrePersist @PreUpdate
*/
public function markLastUpdate(){
if(!$this->updatedAtOveridden) $this->updatedAt = new \DateTime();
$this->percentComplete = $this->calculatePercentComplete();
$this->hasPaid = $this->checkIfPaid();
}
/**
* Set updatedAt
*
* @param string $updatedAt
*/
public function setUpdatedAt($updatedAt){
$this->updatedAtOveridden = true;
$this->updatedAt = new \DateTime($updatedAt);
}
/**
* Get updatedAt
*
* @return \DateTime $updatedAt
*/
public function getUpdatedAt(){
return $this->updatedAt;
}
/**
* Set application
*
* @param Entity\Application $application
*/
public function setApplication(Application $application){
$this->application = $application;
}
/**
* Get application
*
* @return Entity\Application $application
*/
public function getApplication(){
return $this->application;
}
/**
* Add answer
*
* @param \Jazzee\Entity\Answer $answer
*/
public function addAnswer(\Jazzee\Entity\Answer $answer){
$this->answers[] = $answer;
if($answer->getApplicant() != $this) $answer->setApplicant($this);
}
/**
* get all answers
*
* @param Doctrine\Common\Collections\Collection \Jazzee\Entity\Answer
*/
public function getAnswers(){
return $this->answers;
}
/**
* Find answers for a page
*
* @param \Jazzee\Entity\Page
* @return array \Jazzee\Entity\Answer
*/
public function findAnswersByPage(Page $page){
$return = array();
foreach($this->answers as $answer) if($answer->getPage() === $page) $return[] = $answer;
return $return;
}
/**
* Find answer by id
*
* @param integer $id
* @return \Jazzee\Entity\Answer or false
*/
public function findAnswerById($id){
foreach($this->answers as $answer) if($answer->getId() == $id) return $answer;
return false;
}
/**
* Add attachment
*
* @param \Jazzee\Entity\Attachment $attachment
*/
public function addAttachment(Attachment $attachment){
$this->attachments[] = $attachment;
if($attachment->getApplicant() != $this) $attachment->setApplicant($this);
}
/**
* Remove attachment
*
* @param \Jazzee\Entity\Attachment $attachment
*/
public function removeAttachment(Attachment $attachment){
$this->attachments->removeElement($attachment);
}
/**
* Get attachments
*
* @return Doctrine\Common\Collections\Collection $attachments
*/
public function getAttachments(){
$attachments = array();
foreach($this->attachments as $attachment) if($attachment->getAnswer() == null) $attachments[] = $attachment;
return $attachments;
}
/**
* Set decision
*
* @param Entity\Decision $decision
*/
public function setDecision(Decision $decision){
$this->decision = $decision;
}
/**
* Get decision
*
* @return \Jazzee\Entity\Decision $decision
*/
public function getDecision(){
return $this->decision;
}
/**
* Add tags
*
* @param Entity\Tag $tag
*/
public function addTag(Tag $tag){
$this->tags[] = $tag;
$this->markLastUpdate();
}
/**
* Remove tag
*
* @param Entity\Tag $tag
*/
public function removeTag(Tag $tag){
$this->tags->removeElement($tag);
$this->markLastUpdate();
}
/**
* Get tags
*
* @return Doctrine\Common\Collections\Collection $tags
*/
public function getTags(){
return $this->tags;
}
/**
* Add thread
*
* @param \Jazzee\Entity\Thread $thread
*/
public function addThread(Thread $thread){
$this->threads[] = $thread;
if($thread->getApplicant() != $this) $thread->setApplicant($this);
}
/**
* Get threads
*
* @return Doctrine\Common\Collections\Collection $threads
*/
public function getThreads(){
return $this->threads;
}
/**
* Get duplicates
*
* @return Doctrine\Common\Collections\Collection $duplicates
*/
public function getDuplicates(){
return $this->duplicates;
}
/**
* Get duplicate by ID
*
* @param integer $duplicateId
* @return Doctrine\Common\Collections\Collection $duplicates
*/
public function getDuplicateById($duplicateId){
foreach($this->duplicates as $duplicate){
if($duplicate->getId() == $duplicateId){
return $duplicate;
}
}
return false;
}
/**
* Get Audit Logs
*
* @return Doctrine\Common\Collections\Collection $auditLogs
*/
public function getAuditLogs(){
return $this->auditLogs;
}
/**
* Unread Message Count
*
* @return integer
*/
public function unreadMessageCount(){
$count = 0;
foreach($this->threads as $thread)
foreach($thread->getMessages() as $message)
if(!$message->isRead(\Jazzee\Entity\Message::PROGRAM)) $count++;
return $count;
}
/**
* Get the applicants percent complete
* If it isn't set then generate it
*/
public function getPercentComplete(){
return $this->percentComplete;
}
protected function calculatePercentComplete(){
$complete = 0;
$total = 0;
$pages = $this->application->getApplicationPages(\Jazzee\Entity\ApplicationPage::APPLICATION);
foreach($pages as $pageEntity){
if($pageEntity->getJazzeePage() instanceof \Jazzee\Interfaces\ReviewPage){
$total++;
$pageEntity->getJazzeePage()->setApplicant($this);
if($pageEntity->getJazzeePage()->getStatus() == \Jazzee\Interfaces\Page::COMPLETE OR $pageEntity->getJazzeePage()->getStatus() == \Jazzee\Interfaces\Page::SKIPPED) $complete++;
}
}
//avoid division by 0 and dividing 0 by something
if($complete == 0 or $total == 0) return 0;
return round($complete/$total, 2);
}
protected function checkIfPaid(){
foreach($this->answers as $answer)
if($payment = $answer->getPayment())
if($payment->getStatus() == \Jazzee\Entity\Payment::SETTLED)
return true;
return false;
}
/**
* Check if an applicant has at least one settled payment
* @return boolean
*/
public function hasPaid(){
return $this->hasPaid;
}
/**
* Create applicant XML file
*
* @param \Jazzee\Controller $controller
* @param boolean $partial
* @return \DOMDocument
*/
public function toXml($controller, $partial = false){
$dom = new \DOMDocument('1.0', 'UTF-8');
$applicantXml = $dom->createElement("applicant");
$account = $dom->createElement("account");
$account->appendChild($dom->createElement('id', $this->getId()));
$account->appendChild($dom->createElement('firstName', $this->getFirstName()));
$account->appendChild($dom->createElement('middleName', $this->getMiddleName()));
$account->appendChild($dom->createElement('lastName', $this->getLastName()));
$account->appendChild($dom->createElement('suffix', $this->getSuffix()));
$account->appendChild($dom->createElement('email', $this->getEmail()));
$account->appendChild($dom->createElement('isLocked', $this->isLocked()?'yes':'no'));
$account->appendChild($dom->createElement('lastLogin', $this->getLastLogin()->format('c')));
$account->appendChild($dom->createElement('updatedAt', $this->getUpdatedAt()->format('c')));
$account->appendChild($dom->createElement('createdAt', $this->getCreatedAt()->format('c')));
$account->appendChild($dom->createElement('percentComplete', $this->getPercentComplete()));
$applicantXml->appendChild($account);
$decision = $dom->createElement("decision");
$decision->appendChild($dom->createElement('status', $this->getDecision()?$this->getDecision()->status():'none'));
$decision->appendChild($dom->createElement('nominateAdmit', ($this->getDecision() and $this->getDecision()->getNominateAdmit())?$this->getDecision()->getNominateAdmit()->format('c'):''));
$decision->appendChild($dom->createElement('nominateDeny', ($this->getDecision() and $this->getDecision()->getNominateDeny())?$this->getDecision()->getNominateDeny()->format('c'):''));
$decision->appendChild($dom->createElement('finalAdmit', ($this->getDecision() and $this->getDecision()->getFinalAdmit())?$this->getDecision()->getFinalAdmit()->format('c'):''));
$decision->appendChild($dom->createElement('finalDeny', ($this->getDecision() and $this->getDecision()->getFinalDeny())?$this->getDecision()->getFinalDeny()->format('c'):''));
$decision->appendChild($dom->createElement('acceptOffer', ($this->getDecision() and $this->getDecision()->getAcceptOffer())?$this->getDecision()->getAcceptOffer()->format('c'):''));
$decision->appendChild($dom->createElement('declineOffer', ($this->getDecision() and $this->getDecision()->getDeclineOffer())?$this->getDecision()->getDeclineOffer()->format('c'):''));
$applicantXml->appendChild($decision);
$tags = $dom->createElement("tags");
foreach($this->getTags() as $tag){
$tagXml = $dom->createElement('tag');
$tagXml->setAttribute('tagId', $tag->getId());
$tagXml->appendChild($dom->createCDATASection($tag->getTitle()));
$tags->appendChild($tagXml);
}
$applicantXml->appendChild($tags);
if($partial){
$dom->appendChild($applicantXml);
return $dom;
}
$auditLogs = $dom->createElement("auditLogs");
foreach($this->getAuditLogs() as $log){
$logXml = $dom->createElement('log');
$logXml->setAttribute('id', $log->getId());
$logXml->setAttribute('userId', $log->getUser()->getId());
$logXml->setAttribute('createAt', $log->getCreatedAt()->format('c'));
$user = $dom->createElement('user');
$user->appendChild($dom->createCDATASection($log->getUser()->getLastName() . ', ' . $log->getUser()->getFirstName()));
$logXml->appendChild($user);
$text = $dom->createElement('text');
$text->appendChild($dom->createCDATASection($log->getText()));
$logXml->appendChild($text);
$auditLogs->appendChild($logXml);
}
$applicantXml->appendChild($auditLogs);
$pages = $dom->createElement("pages");
foreach($this->application->getApplicationPages(\Jazzee\Entity\ApplicationPage::APPLICATION) as $applicationPage){
if($applicationPage->getJazzeePage() instanceof \Jazzee\Interfaces\XmlPage){
$page = $dom->createElement("page");
$page->setAttribute('title', \htmlentities($applicationPage->getTitle(),ENT_COMPAT,'utf-8'));
$page->setAttribute('type', \htmlentities($applicationPage->getPage()->getType()->getClass(),ENT_COMPAT,'utf-8'));
$page->setAttribute('pageId', $applicationPage->getPage()->getId());
$answersXml = $dom->createElement('answers');
$applicationPage->getJazzeePage()->setApplicant($this);
$applicationPage->getJazzeePage()->setController($controller);
foreach($applicationPage->getJazzeePage()->getXmlAnswers($dom) as $answerXml){
$answersXml->appendChild($answerXml);
}
$page->appendChild($answersXml);
$pages->appendChild($page);
}
}
$applicantXml->appendChild($pages);
$dom->appendChild($applicantXml);
return $dom;
}
}
/**
* ApplicantRepository
* Special Repository methods for Applicants
* @package jazzee
* @subpackage orm
*/
class ApplicantRepository extends \Doctrine\ORM\EntityRepository{
/**
* find on by email address and application
*
* Search for an Applicant by email in an application
* @param string $email
* @param Application $application
* @return Application
*/
public function findOneByEmailAndApplication($email, Application $application){
$query = $this->_em->createQuery('SELECT a FROM Jazzee\Entity\Applicant a WHERE a.application = :applicationId AND a.email = :email');
$query->setParameter('applicationId', $application->getId());
$query->setParameter('email', $email);
$result = $query->getResult();
if(count($result)) return $result[0];
return false;
}
/**
* find applicants in a cycle
*
* Search for an Applicant by cycle
* @param Cycle $cycle
* @return array
*/
public function findByCycle(Cycle $cycle){
$query = $this->_em->createQuery('SELECT a FROM Jazzee\Entity\Applicant a WHERE a.application IN (SELECT app FROM Jazzee\Entity\Application app WHERE app.cycle = :cycleId)');
$query->setParameter('cycleId', $cycle->getId());
return $query->getResult();
}
/**
* find duplicate applicants in the same cycle
*
* @param Applicant $applicant
* @return array
*/
public function findDuplicates(Applicant $applicant){
$query = $this->_em->createQuery('SELECT a FROM Jazzee\Entity\Applicant a WHERE a != :applicantId AND a.email = :email AND a.application IN (SELECT app FROM Jazzee\Entity\Application app WHERE app.cycle = :cycleId)');
$query->setParameter('applicantId', $applicant->getId());
$query->setParameter('cycleId', $applicant->getApplication()->getCycle()->getId());
$query->setParameter('email', $applicant->getEmail());
return $query->getResult();
}
/**
* Find applicants by name
*
* @param string $firstName
* @param string $lastName
* @param Application $application
* @return Application
*/
public function findApplicantsByName($firstName, $lastName, Application $application = null){
$qb = $this->_em->createQueryBuilder();
$qb->add('select', 'a')
->from('Jazzee\Entity\Applicant', 'a');
if(!is_null($application)){
$qb->where('a.application = :applicationId');
$qb->setParameter('applicationId', $application->getId());
}
$qb->andWhere('a.firstName LIKE :firstName')
->andWhere('a.lastName LIKE :lastName')
->orderBy('a.lastName, a.firstName');
$qb->setParameter('firstName', $firstName);
$qb->setParameter('lastName', $lastName);
return $qb->getQuery()->getResult();
}
/**
* Find applicants by name
*
* @param \stdClass $obj
* @param \Jazzee\Controller $controller
* @param Application $application
* @return array Applicant
*/
public function findApplicantsByQuery(\stdClass $obj, \Jazzee\Controller $controller, Application $application = null){
$qb = $this->_em->createQueryBuilder();
$qb->add('select', 'a')
->from('Jazzee\Entity\Applicant', 'a');
if(!is_null($application)){
$qb->where('a.application = :applicationId');
$qb->setParameter('applicationId', $application->getId());
}
if(isset($obj->applicant)){
foreach(array('email','firstName','lastName','middleName','suffix') as $name){
if(isset($obj->applicant->$name) and !is_null($obj->applicant->$name)){
$qb->andWhere("a.{$name} LIKE :{$name}");
$qb->setParameter($name, $obj->applicant->$name);
}
}
foreach(array('lastLogin','createdAt','updatedAt') as $name){
if(isset($obj->applicant->$name) and !is_null($obj->applicant->$name)){
$qb->andWhere("a.{$name} >= :{$name}");
$qb->setParameter($name, $obj->applicant->$name);
}
}
if(isset($obj->applicant->isLocked) and !is_null($obj->applicant->isLocked)){
$qb->andWhere("a.isLocked = :isLocked");
$qb->setParameter('isLocked', $obj->applicant->isLocked);
}
}
if(isset($obj->decision)){
$qb->innerJoin('a.decision','d');
foreach(array('nominateAdmit','nominateDeny','finalAdmit','finalDeny','acceptOffer','declineOffer') as $name){
if(isset($obj->decision->$name) and $obj->decision->$name == true){
$qb->andWhere("d.{$name} IS NOT NULL");
}
}
}
$qb->orderBy('a.lastName, a.firstName');
$applicants = $qb->getQuery()->getResult();
foreach($obj->pages as $pageObj){
foreach($applicants as $key => $applicant){
if($applicationPage = $applicant->getApplication()->getApplicationPageByTitle($pageObj->title)){
$applicationPage->getJazzeePage()->setApplicant($applicant);
$applicationPage->getJazzeePage()->setController($controller);
if(!$applicationPage->getJazzeePage()->testQuery($pageObj->query)){
unset($applicants[$key]);
}
}
}
}
return $applicants;
}
/**
* Reset all the failed login counter for applicants
*/
public function resetFailedLoginCounters(){
$query = $this->_em->createQuery('UPDATE Jazzee\Entity\Applicant a SET a.failedLoginAttempts = 0 WHERE a.failedLoginAttempts > 0');
$query->execute();
}
/**
* Reset all the unique ids
*/
public function resetUniqueIds(){
$query = $this->_em->createQuery('UPDATE Jazzee\Entity\Applicant a SET a.uniqueId = null WHERE a.uniqueId IS NOT NULL');
$query->execute();
}
}<file_sep><?php
namespace Jazzee\Entity;
/**
* Attachment
* Attach a file to an applicant
* @Entity
* @HasLifecycleCallbacks
* @Table(name="attachments")
* @package jazzee
* @subpackage orm
**/
class Attachment{
/**
* @Id
* @Column(type="bigint")
* @GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* @OneToOne(targetEntity="Answer",inversedBy="attachment")
* @JoinColumn(onDelete="CASCADE")
*/
private $answer;
/**
* @ManyToOne(targetEntity="Applicant",inversedBy="attachments")
* @JoinColumn(onDelete="CASCADE")
*/
private $applicant;
/** @Column(type="text") */
private $attachment;
/** @Column(type="text") */
private $thumbnail;
/**
* Get id
*
* @return bigint $id
*/
public function getId(){
return $this->id;
}
/**
* Set the Applicant
* @param Entity\Applicant $applicant
*/
public function setApplicant(Applicant $applicant){
$this->applicant = $applicant;
}
/**
* Get the Applicant
* @return Entity\Applicant $applicant
*/
public function getApplicant(){
return $this->applicant;
}
/**
* Set the answer
* @param Answer $answer
*/
public function setAnswer(Answer $answer){
$this->answer = $answer;
}
/**
* Get the answer
* @return Answer
*/
public function getAnswer(){
return $this->answer;
}
/**
* Convert the attachment to base64 and store it
*
* @param blob $attachment
*/
public function setAttachment($blob){
$this->attachment = base64_encode($blob);
try{
$im = new \imagick;
$im->readimageblob($blob);
$im->setiteratorindex(0);
$im->setImageFormat("png");
$im->scaleimage(100, 0);
} catch (\ImagickException $e){
$im = new \imagick;
$im->readimage(realpath(__DIR__ . '/../../../lib/foundation/src/media/default_pdf_logo.png'));
$im->scaleimage(100, 0);
}
$this->thumbnail = base64_encode($im->getimageblob());
}
/**
* Get attachment
*
* @return text $attachment
*/
public function getAttachment(){
return base64_decode($this->attachment);
}
/**
* Get thumbnail
*
* @return blob $thumbnail
*/
public function getThumbnail(){
if($this->thumbnail) return base64_decode($this->thumbnail);
return false;
}
/**
* Mark the lastUpdate automatically
* @PrePersist @PreUpdate
*/
public function markLastUpdate(){
$this->applicant->markLastUpdate();
}
}<file_sep><?php
/**
* apply_page view
* @author <NAME> <<EMAIL>>
* @license http://jazzee.org/license.txt
* @package jazzee
* @subpackage apply
*/
?>
<?php if($page->getJazzeePage()->getStatus() == \Jazzee\Interfaces\Page::SKIPPED){?>
<p class="skip">You have selected to skip this page. You can still change your mind and <a href='<?php print $this->controller->getActionPath() . '/do/unskip';?>' title='complete this page'>Complete This Page</a> if you wish.</p>
<?php } else {
if(!$page->isRequired() and !count($page->getJazzeePage()->getAnswers())){?>
<p class="skip">This page is optional, if you do not have any information to enter you can <a href='<?php print $this->controller->getActionPath() . '/do/skip';?>' title='skip this page'>Skip This Page</a>.</p>
<?php }?>
<div id='counter'><?php
$answers = $page->getjazzeePage()->getAnswers();
if($answers){
$totalAnswers = count($answers);
$completedAnswers = 0;
foreach($answers as $answer)if($answer->isLocked()) $completedAnswers++; ?>
<p>
<?php
if(is_null($page->getMax())){
if($completedAnswers >= $page->getMin()) print 'You may add as many additional recommenders as you wish to this page, but it is not required.';
else print 'You have invited ' . $completedAnswers . ' of the ' . $page->getMin() . ' required recommenders on this page.';
} else {
if($page->getMax() - $completedAnswers == 0) print 'You cannot invite any more recommenders to this page.';
else if($completedAnswers >= $page->getMin()) print 'You may invite an additional ' . ($page->getMax() - $completedAnswers) . ' recommenders on this page, but it is not required.';
else print 'You have invited ' . $completedAnswers . ' of the ' . $page->getMin() . ' required recommenders on this page.';
}
?>
<?php
if($completedAnswers < $totalAnswers) print ' You have not invited ' . ($totalAnswers - $completedAnswers) . ' of the recommenders you added to the page. Click ‘Send Invitation Email’ to invite each recommender.';
?>
</p>
<?php } ?>
</div>
<?php if($answers = $page->getJazzeePage()->getAnswers()){?>
<div id='answers'>
<?php foreach($answers as $answer){?>
<div class='answer<?php if($currentAnswerID and $currentAnswerID == $answer->getID()) print ' active'; ?>'>
<h5>Recommender</h5>
<?php
foreach($answer->getPage()->getElements() as $element){
$element->getJazzeeElement()->setController($this->controller);
$value = $element->getJazzeeElement()->displayValue($answer);
if($value){
print '<p><strong>' . $element->getTitle() . ':</strong> ' . $value . '</p>';
}
}
?>
<p class='status'>
<strong>Last Updated:</strong> <?php print $answer->getUpdatedAt()->format('M d Y g:i a');?><br />
<?php if($child = $answer->getChildren()->first()){?>
<br /><strong>Status:</strong> This recommendation was received on <?php print $child->getUpdatedAt()->format('l F jS Y g:ia');
} else if($answer->isLocked()){?>
<strong>Invitation Sent:</strong> <?php print $answer->getUpdatedAt()->format('l F jS Y g:ia'); ?><br />
<strong>Status:</strong> You cannot make changes to this recommendation becuase the invitation has already been sent.
<?php if($answer->getUpdatedAt()->diff(new DateTime('now'))->days < $answer->getPage()->getVar('lorWaitDays')){?>
You will be able to send the invitation to your recommender again in <?php print ($answer->getPage()->getVar('lorWaitDays') - $answer->getUpdatedAt()->diff(new DateTime('now'))->days);?> days.
<?php }?>
<?php }?>
</p>
<p class='controls'>
<?php
if(!$answer->isLocked() and $currentAnswerID and $currentAnswerID == $answer->getID()){?>
<a class='undo' href='<?php print $this->controller->getActionPath() ?>'>Undo</a>
<?php } else if(!$answer->isLocked()){ ?>
<a class='edit' href='<?php print $this->controller->getActionPath();?>/edit/<?php print $answer->getId()?>'>Edit</a>
<a class='delete' href='<?php print $this->controller->getActionPath();?>/delete/<?php print $answer->getId()?>'>Delete</a>
<a class='invite' href='<?php print $this->controller->getActionPath();?>/do/sendEmail/<?php print $answer->getId()?>'>Send Invitation Email</a>
<?php } else if(!$answer->getChildren()->first() and $answer->getUpdatedAt()->diff(new DateTime('now'))->days >= $answer->getPage()->getVar('lorWaitDays')){ ?>
<a class='invite' href='<?php print $this->controller->getActionPath();?>/do/sendEmail/<?php print $answer->getId()?>'>Send Reminder Email</a>
<?php }?>
</p>
</div>
<?php } //end foreach answers ?>
</div>
<?php }
if(!empty($currentAnswerID) or is_null($page->getMax()) or count($page->getJazzeePage()->getAnswers()) < $page->getMax()){?>
<div id='leadingText'><?php print $page->getLeadingText()?></div>
<?php $this->renderElement('form', array('form'=> $page->getJazzeePage()->getForm())); ?>
<div id='trailingText'><?php print $page->getTrailingText()?></div>
<?php }
}<file_sep><?php
namespace Jazzee\Entity;
/**
* PaymentVariable
* Allow developers to store arbitrary data as a PaymentVariable so we don't need new tables for every new ApplyPayment type
* @Entity
* @HasLifecycleCallbacks
* @Table(name="payment_variables",uniqueConstraints={@UniqueConstraint(name="payment_variables", columns={"payment_id", "name"})})
* @package jazzee
* @subpackage orm
**/
class PaymentVariable{
/**
* @Id
* @Column(type="bigint")
* @GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* @ManyToOne(targetEntity="Payment", inversedBy="variables")
* @JoinColumn(onDelete="CASCADE")
*/
private $payment;
/** @Column(type="string") */
private $name;
/** @Column(type="text") */
private $value;
/**
* Get id
*
* @return bigint $id
*/
public function getId(){
return $this->id;
}
/**
* Mark the lastUpdate automatically
* @PrePersist @PreUpdate
*/
public function markLastUpdate(){
$this->payment->markLastUpdate();
}
/**
* Set payment
*
* @param Entity\Payment $payment
*/
public function setPayment(Payment $payment){
$this->payment = $payment;
}
/**
* Set name
*
* @param string $name
*/
public function setName($name){
$this->name = $name;
}
/**
* Get name
*
* @return string $name
*/
public function getName(){
return $this->name;
}
/**
* Get the base64 decoded value
* @return blob
*/
public function getValue(){
return base64_decode($this->value);
}
/**
* Base64 encode the value
* @param mixed $value
* @return mixed
*/
public function setValue($value){
return $this->value = base64_encode($value);
}
}<file_sep><?php
/**
* manage_mail index view
* @author <NAME> <<EMAIL>>
* @license http://jazzee.org/license.txt
* @package jazzee
* @subpackage manage
*/
?>
<h2>Email Settings</h2>
<h4>Server Settings</h4>
<p>
<strong>Type: </strong><?php print $config->getMailServerType(); ?><br />
<strong>Host: </strong><?php print $config->getMailServeHost(); ?><br />
<strong>Port: </strong><?php print $config->getMailServerPort(); ?><br />
<strong>Username: </strong><?php print $config->getMailServerUsername(); ?><br />
<strong>Password: </strong><?php print $config->getMailServerPassword(); ?><br />
</p>
<h4>Outgoing Mail</h4>
<p>
<strong>From Address: </strong><?php print $config->getMailDefaultFromAddress(); ?><br />
<strong>From Name: </strong><?php print $config->getMailDefaultFromName(); ?><br />
</p>
<?php if($this->controller->checkIsAllowed('manage_mail', 'test')){ ?>
<p><a href='<?php print $this->path('manage/mail/test')?>'>Send Test Email</a></p>
<?php } ?><file_sep><?php
/**
* Loads Files stores in the session
* @author <NAME> <<EMAIL>>
* @license http://jazzee.org/license.txt
* @package jazzee
*/
class FileController extends \Jazzee\Controller{
/**
* Output a single file
* @param string $name
*/
public function actionGet($name){
if($file = $this->getStoredFile($name)) $file->output();
//send a 404
$request = new Lvc_Request();
$request->setControllerName('error');
$request->setActionName('index');
$request->setActionParams(array('error' => '404', 'message'=>'File Not Found'));
// Get a new front controller without any routers, and have it process our handmade request.
$fc = new Lvc_FrontController();
$fc->processRequest($request);
exit();
}
}
?><file_sep><?php
namespace Jazzee\Interfaces;
/**
* LORPage interface
* Allows us to define interface for pages which can be used to compelted
* letters of recommendation
*
* @author <NAME> <<EMAIL>>
* @license http://jazzee.org/license.txt
* @package jazzee
* @subpackage pages
*/
interface LorPage
{
/**
* Create a new LOR answer from user input
* @param \Foundation\Form\Input $input
* @param \Jazzee\Entity\Answer $answer
* @return bool
*/
function newLorAnswer(\Foundation\Form\Input $input, \Jazzee\Entity\Answer $answer);
/**
* Update a LOR Answer
* @param \Foundation\Form\Input $input
* @param \Jazzee\Entity\Answer $answer
* @return bool
*/
function updateLorAnswer(\Foundation\Form\Input $input, \Jazzee\Entity\Answer $answer);
/**
* Delete LOR answer
* @param \Jazzee\Entity\Answer $answer
* @return bool
*/
function deleteLorAnswer(\Jazzee\Entity\Answer $answer);
/**
* Fill Lor form from answer
* @param \Jazzee\Entity\Answer $answer
*/
function fillLorForm(\Jazzee\Entity\Answer $answer);
/**
* Get the element for the LOR page view
* @return string
*/
public static function lorPageElement();
/**
* Get the element for the LOR page view
* @return string
*/
public static function lorReviewElement();
/**
* Get the element for the LOR page view
* @return string
*/
public static function lorApplicantsSingleElement();
}<file_sep><?php
namespace Jazzee\Entity;
/**
* Answer
* Applicant answer to a page
* @Entity
* @HasLifecycleCallbacks
* @Table(name="answers",
* uniqueConstraints={@UniqueConstraint(name="answer_uniqueId",columns={"uniqueId"})})
* @package jazzee
* @subpackage orm
**/
class Answer{
/**
* @Id
* @Column(type="bigint")
* @GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* @ManyToOne(targetEntity="Applicant",inversedBy="answers")
* @JoinColumn(onDelete="CASCADE")
*/
protected $applicant;
/**
* @ManyToOne(targetEntity="Page")
* @JoinColumn(onDelete="CASCADE")
*/
protected $page;
/**
* @ManyToOne(targetEntity="Answer",inversedBy="children")
* @JoinColumn(onDelete="CASCADE")
*/
protected $parent;
/**
* @OneToMany(targetEntity="Answer", mappedBy="parent")
*/
protected $children;
/**
* @OneToMany(targetEntity="ElementAnswer", mappedBy="answer", cascade={"persist"})
*/
protected $elements;
/**
* @ManyToOne(targetEntity="AnswerStatusType")
*/
protected $publicStatus;
/**
* @ManyToOne(targetEntity="AnswerStatusType")
*/
protected $privateStatus;
/** @Column(type="integer", nullable=true) */
protected $pageStatus;
/**
* @OneToOne(targetEntity="Attachment",mappedBy="answer")
*/
private $attachment;
/** @Column(type="string", length=255) */
protected $uniqueId;
/** @Column(type="boolean") */
protected $locked;
/** @Column(type="datetime") */
protected $updatedAt;
/**
* @ManyToOne(targetEntity="GREScore")
*/
private $greScore;
/**
* @ManyToOne(targetEntity="TOEFLScore")
*/
private $toeflScore;
/**
* @OneToOne(targetEntity="Payment", mappedBy="answer")
*/
private $payment;
/**
* The Jazzee Answer instance
* @var \Jazzee\Answer
*/
private $jazzeeAnswer;
/**
* If we set a manual update don't override it
* @var boolean
*/
private $updatedAtOveridden = false;
public function __construct(){
$this->children = new \Doctrine\Common\Collections\ArrayCollection();
$this->elements = new \Doctrine\Common\Collections\ArrayCollection();
$this->generateUniqueId();
$this->locked = false;
}
/**
* Get id
*
* @return bigint $id
*/
public function getId(){
return $this->id;
}
/**
* Set attachment
*
* @param Attachment $attachment
*/
public function setAttachment(Attachment $attachment){
$this->attachment = $attachment;
}
/**
* Get attachment
*
* @return Attachment $attachment
*/
public function getAttachment(){
return $this->attachment;
}
/**
* Set page
*
* @param Entity\Page $page
*/
public function setPage($page){
$this->page = $page;
}
/**
* Get page
*
* @return Entity\Page $page
*/
public function getPage(){
return $this->page;
}
/**
* Generate a unique id
*/
public function generateUniqueId(){
//PHPs uniquid function is time based and therefor guessable
//A stright random MD5 sum is too long for email and tends to line break causing usability problems
//So we get unique through uniquid and we get random by prefixing it with a part of an MD5
//hopefully this results in a URL friendly short, but unguessable string
$prefix = substr(md5(mt_rand()*mt_rand()),rand(0,24), rand(6,8));
$this->uniqueId = \uniqid($prefix);
}
/**
* Set a uniqueid
* Prefferably call generateUniqueId - but it can also be set manually
* @param string $uniqueId;
*/
public function setUniqueId($uniqueId){
$this->uniqueId = $uniqueId;
}
/**
* Get uniqueId
*
* @return string $uniqueId
*/
public function getUniqueId(){
return $this->uniqueId;
}
/**
* Lock the Answer
*/
public function lock(){
$this->locked = true;
}
/**
* UnLock the Answer
*/
public function unlock(){
$this->locked = false;
}
/**
* Get locked status
*
* @return boolean $locked
*/
public function isLocked(){
return $this->locked;
}
/**
* Set updatedAt
*
* @param string $updatedAt
*/
public function setUpdatedAt($updatedAt){
$this->updatedAtOveridden = true;
$this->updatedAt = new \DateTime($updatedAt);
}
/**
* Get updatedAt
*
* @return DateTime $updatedAt
*/
public function getUpdatedAt(){
return $this->updatedAt;
}
/**
* Set applicant
*
* @param Entity\Applicant $applicant
*/
public function setApplicant(Applicant $applicant){
$this->applicant = $applicant;
}
/**
* Get applicant
*
* @return Entity\Applicant $applicant
*/
public function getApplicant(){
return $this->applicant;
}
/**
* Set parent
*
* @param Entity\Answer $parent
*/
public function setParent(Answer $parent){
$this->parent = $parent;
}
/**
* Get parent
*
* @return Entity\Answer $parent
*/
public function getParent(){
return $this->parent;
}
/**
* Add children
*
* @param Entity\Answer $child
*/
public function addChild(Answer $child){
$this->children[] = $child;
if($child->getParent() != $this) $child->setParent($this);
if($child->getApplicant() != $this->applicant) $child->setApplicant($this->applicant);
}
/**
* Get children
*
* @return Doctrine\Common\Collections\Collection $children
*/
public function getChildren(){
return $this->children;
}
/**
* Get Child for Page
*
* @param \Jazzee\Entity\Page $page
* @return \Jazzee\Entity\Answer
*/
public function getChildByPage(Page $page){
foreach($this->children as $child)if($child->getPage() == $page) return $child;
return false;
}
/**
* Add elements
*
* @param Entity\ElementAnswer $element
*/
public function addElementAnswer(ElementAnswer $element){
$this->elements[] = $element;
if($element->getAnswer() != $this) $element->setAnswer($this);
}
/**
* Get elements
*
* @return Doctrine\Common\Collections\Collection $elements
*/
public function getElementAnswers(){
return $this->elements;
}
/**
* Get ElementAnswers for Element
*
* @param \Jazzee\Entity\Element $element
* @return array
*/
public function getElementAnswersForElement(Element $element){
$arr = array();
foreach($this->elements as $elementAnswer)if($elementAnswer->getElement() === $element) $arr[] = $elementAnswer;
return new \Doctrine\Common\Collections\ArrayCollection($arr);
}
/**
* Set publicStatus
*
* @param Entity\AnswerStatusType $publicStatus
*/
public function setPublicStatus(AnswerStatusType $publicStatus){
$this->publicStatus = $publicStatus;
}
/**
* Get publicStatus
*
* @return Entity\AnswerStatusType $publicStatus
*/
public function getPublicStatus(){
return $this->publicStatus;
}
/**
* Clear Public Status
*/
public function clearPublicStatus(){
$this->publicStatus = null;
}
/**
* Set privateStatus
*
* @param Entity\AnswerStatusType $privateStatus
*/
public function setPrivateStatus(AnswerStatusType $privateStatus){
$this->privateStatus = $privateStatus;
}
/**
* Get privateStatus
*
* @return Entity\AnswerStatusType $privateStatus
*/
public function getPrivateStatus(){
return $this->privateStatus;
}
/**
* Clear Private Status
*/
public function clearPrivateStatus(){
$this->privateStatus = null;
}
/**
* Mark the lastUpdate automatically
* @PrePersist @PreUpdate @PreRemove
*/
public function markLastUpdate(){
if(!$this->updatedAtOveridden) $this->updatedAt = new \DateTime();
if($this->applicant) //child pages dont have direct links to the application
$this->applicant->markLastUpdate();
if($this->parent) //child pages should update their parents
$this->parent->markLastUpdate();
}
/**
* get payment
*
* @return \Jazzee\Entity\Payment $payment
*/
public function getPayment(){
return $this->payment;
}
/**
* Set payment
*
* @param \Jazzee\Entity\Payment $payment
*/
public function setPayment(\Jazzee\Entity\Payment $payment){
$this->payment = $payment;
if($payment->getAnswer() != $this) $payment->setAnswer($this);
}
/**
* get gre score
*
* @return \Jazzee\Entity\GREScore $score
*/
public function getGREScore(){
return $this->greScore;
}
/**
* Set gre score
*
* @param \Jazzee\Entity\GREScore $score
*/
public function setGREScore($score){
$this->greScore = $score;
}
/**
* get toefl score
*
* @return \Jazzee\Entity\TOEFL $score
*/
public function getTOEFLScore(){
return $this->toeflScore;
}
/**
* Set toefl score
*
* @param \Jazzee\Entity\TOEFLScore $score
*/
public function setTOEFLScore($score){
$this->toeflScore = $score;
}
/**
* Conviently get a matched score
*
* Try both GRE and TOEFL and grab a match from wherever it might be
*
* @return \Jazzee\Entity\GREScore | \Jazzee\Entity\TOEFLScore | false if no score is present
*/
public function getMatchedScore(){
if($this->greScore) return $this->greScore;
if($this->toeflScore) return $this->toeflScore;
return false;
}
/**
* Set page status
*
* @param integer $pageStatus
*/
public function setPageStatus($pageStatus){
$this->pageStatus = $pageStatus;
}
/**
* Get the page status
*
* @return integer $pageStatus
*/
public function getPageStatus(){
return $this->pageStatus;
}
}<file_sep><?php
/**
* Display program welcome message
* @author <NAME> <<EMAIL>>
* @license http://jazzee.org/license.txt
* @package jazzee
* @subpackage apply
*/
?>
<p><?php echo $application->getWelcome() ?></p><file_sep><?php
namespace Jazzee\Entity;
/**
* Page
* A page is not directly associated with an application - it can be a single case or a global page associated with many applications
* @Entity(repositoryClass="\Jazzee\Entity\PageRepository")
* @HasLifecycleCallbacks
* @Table(name="pages",
* uniqueConstraints={@UniqueConstraint(name="page_uuid",columns={"uuid"})})
* @package jazzee
* @subpackage orm
**/
class Page{
/**
* @Id
* @Column(type="bigint")
* @GeneratedValue(strategy="AUTO")
*/
private $id;
/** @Column(type="string") */
private $uuid;
/** @Column(type="string") */
private $title;
/**
* @ManyToOne(targetEntity="PageType")
* @JoinColumn(onDelete="SET NULL")
*/
private $type;
/** @Column(type="boolean") */
private $isGlobal;
/**
* @ManyToOne(targetEntity="Page",inversedBy="children")
* @JoinColumn(onDelete="CASCADE")
*/
private $parent;
/**
* @OneToMany(targetEntity="Page", mappedBy="parent")
*/
private $children;
/**
* @OneToMany(targetEntity="PageVariable", mappedBy="page")
*/
private $variables;
/**
* @OneToMany(targetEntity="Element", mappedBy="page")
* @OrderBy({"weight" = "ASC"})
*/
private $elements;
/** @Column(type="integer", nullable=true) */
private $min;
/** @Column(type="integer", nullable=true) */
private $max;
/** @Column(type="boolean") */
private $isRequired;
/** @Column(type="boolean") */
private $answerStatusDisplay;
/** @Column(type="text", nullable=true) */
private $instructions;
/** @Column(type="text", nullable=true) */
private $leadingText;
/** @Column(type="text", nullable=true) */
private $trailingText;
/**
* a Generic application Jazzee page we store it so it can be persistent
* @var \Jazzee\Interfaces\Page
*/
private $_applicationPageJazzeePage;
public function __construct(){
$this->children = new \Doctrine\Common\Collections\ArrayCollection();
$this->variables = new \Doctrine\Common\Collections\ArrayCollection();
$this->elements = new \Doctrine\Common\Collections\ArrayCollection();
$this->isGlobal = false;
$this->isRequired = true;
$this->answerStatusDisplay = false;
$this->replaceUuid();
}
/**
* Get id
*
* @return bigint $id
*/
public function getId(){
return $this->id;
}
/**
* Get uuid
*
* @return string $uuid
*/
public function getUuid(){
return $this->uuid;
}
/**
* Set uuid
*
* @param string $uuid
*/
public function setUuid($uuid){
$this->uuid = $uuid;
}
/**
* Generate a Temporary id
*
* This should only be used when we need to termporarily generate a page
* but have no intention of persisting it. Use a string to be sure we cant persist
*/
public function tempId(){
$this->id = uniqid('page');
}
/**
* Replace UUID
* @PreUpdate
* UUIDs are designed to be permanent.
* You should only replace it if the page is being modified
*/
public function replaceUuid(){
$this->uuid = \Foundation\UUID::v4();
if($this->parent) $this->parent->replaceUuid();
}
/**
* Set title
*
* @param string $title
*/
public function setTitle($title){
$this->title = $title;
}
/**
* Get title
*
* @return string $title
*/
public function getTitle(){
return $this->title;
}
/**
* Make page global
*/
public function makeGlobal(){
$this->isGlobal = true;
}
/**
* UnMake page global
*/
public function notGlobal(){
$this->isGlobal = false;
}
/**
* Get Global status
* @return boolean $isGlobal
*/
public function isGlobal(){
return $this->isGlobal;
}
/**
* Set min
*
* @param integer $min
*/
public function setMin($min){
if(empty($min)) $min = null;
$this->min = $min;
}
/**
* Get min
*
* @return integer $min
*/
public function getMin(){
return $this->min;
}
/**
* Set max
*
* @param integer $max
*/
public function setMax($max){
if(empty($max)) $max = null;
$this->max = $max;
}
/**
* Get max
*
* @return integer $max
*/
public function getMax(){
return $this->max;
}
/**
* Make page required
*/
public function required(){
$this->isRequired = true;
}
/**
* Make page optional
*/
public function optional(){
$this->isRequired = false;
}
/**
* Get required status
* @return boolean $required
*/
public function isRequired(){
return $this->isRequired;
}
/**
* Show the answer status
*/
public function showAnswerStatus(){
$this->answerStatusDisplay = true;
}
/**
* Hide the answer status
*/
public function hideAnswerStatus(){
$this->answerStatusDisplay = false;
}
/**
* Should we show the answer status
* @return boolean $showAnswerStatus
*/
public function answerStatusDisplay(){
return $this->answerStatusDisplay;
}
/**
* Set instructions
*
* @param text $instructions
*/
public function setInstructions($instructions){
if(empty($instructions)) $instructions = null;
$this->instructions = $instructions;
}
/**
* Get instructions
*
* @return text $instructions
*/
public function getInstructions(){
return $this->instructions;
}
/**
* Set leadingText
*
* @param text $leadingText
*/
public function setLeadingText($leadingText){
if(empty($leadingText)) $leadingText = null;
$this->leadingText = $leadingText;
}
/**
* Get leadingText
*
* @return text $leadingText
*/
public function getLeadingText(){
return $this->leadingText;
}
/**
* Set trailingText
*
* @param text $trailingText
*/
public function setTrailingText($trailingText){
if(empty($trailingText)) $trailingText = null;
$this->trailingText = $trailingText;
}
/**
* Get trailingText
*
* @return text $trailingText
*/
public function getTrailingText(){
return $this->trailingText;
}
/**
* Set type
*
* @param Entity\PageType $type
*/
public function setType(PageType $type){
$this->type = $type;
}
/**
* Get type
*
* @return Entity\PageType $type
*/
public function getType(){
return $this->type;
}
/**
* Get parent
*
* @return Entity\Page $parent
*/
public function getParent(){
return $this->parent;
}
/**
* Set parent
*
* @param Entity\Page $parent
*/
public function setParent($parent){
$this->parent = $parent;
}
/**
* Add Child
*
* @param \Jazzee\Entity\Page $page
*/
public function addChild(\Jazzee\Entity\Page $page){
$this->children[] = $page;
if($page->getParent() != $this) $page->setParent($this);
}
/**
* Get children
*
* @return Doctrine\Common\Collections\Collection $children
*/
public function getChildren(){
return $this->children;
}
/**
* Get a child by id
*
* @param integer $id
* @return \Jazzee\Entity\Page
*/
public function getChildById($id){
foreach($this->children as $child) if($child->getId() == $id) return $child;
return false;
}
/**
* Set page variable
*
* we retunt he variable to is can be persisted
*
* @param string $name
* @param string $value
*
* @return \Jazzee\Entity\PageVariable
*/
public function setVar($name, $value){
foreach($this->variables as $variable)
if($variable->getName() == $name){
$variable->setValue($value);
return $variable;
}
//create a new empty variable with that name
$variable = new PageVariable;
$variable->setPage($this);
$variable->setName($name);
$this->variables[] = $variable;
$variable->setValue($value);
return $variable;
}
/**
* get page variable
* @param string $name
* @return string $value
*/
public function getVar($name){
foreach($this->variables as $variable)
if($variable->getName() == $name)return $variable->getValue();
}
/**
* get page variables
* @return array \Jazzee\Entity\PageVariable
*/
public function getVariables(){
return $this->variables;
}
/**
* Add element
*
* @param Entity\Element $element
*/
public function addElement(\Jazzee\Entity\Element $element){
$this->elements[] = $element;
if($element->getPage() != $this) $element->setPage($this);
}
/**
* Get elements
*
* @return array \Jazzee\Entity\Element
*/
public function getElements(){
return $this->elements;
}
/**
* Get element by ID
* @param integer $id
* @return Entity\Element $element
*/
public function getElementById($id){
foreach($this->elements as $element) if($element->getId() == $id) return $element;
return false;
}
/**
* Get element by title
* @param string $title
* @return Element $element
*/
public function getElementByTitle($title){
foreach($this->elements as $element) if($element->getTitle() == $title) return $element;
return false;
}
/**
* Get element by fixed ID
* @param integer $id
* @return Entity\Element $element
*/
public function getElementByFixedId($id){
foreach($this->elements as $element) if($element->getFixedId() == $id) return $element;
return false;
}
/**
* Create a temporary application page and return a created Jazzee page
* @return \Jazzee\Interfaces\Page
*/
public function getApplicationPageJazzeePage(){
if($this->_applicationPageJazzeePage == null){
$ap = new ApplicationPage;
$ap->setPage($this);
$this->_applicationPageJazzeePage = $ap->getJazzeePage();
}
return $this->_applicationPageJazzeePage;
}
}
/**
* Page Repository
* Special Repository methods for Pages
* @package jazzee
* @subpackage orm
*/
class PageRepository extends \Doctrine\ORM\EntityRepository{
/**
* Check if a page has any answers associated with it
* @param Page $page
* @return boolean
*/
public function hasAnswers(Page $page){
$query = $this->_em->createQuery('SELECT a.id FROM Jazzee\Entity\Answer a WHERE a.page = :pageId');
$query->setParameter('pageId', $page->getId());
$query->setMaxResults(1);
$result = $query->getResult();
return count($result);
}
/**
* Check if a page has any answers associated with it in a specific cycle
* @param Page $page
* @param Cycle $cycle
* @return boolean
*/
public function hasCycleAnswers(Page $page, Cycle $cycle){
$query = $this->_em->createQuery('SELECT answer.id FROM Jazzee\Entity\Answer answer JOIN answer.applicant applicant JOIN applicant.application application WHERE answer.page = :pageId AND application.cycle = :cycleId');
$query->setParameter('pageId', $page->getId());
$query->setParameter('cycleId', $cycle->getId());
$query->setMaxResults(1);
$result = $query->getResult();
return count($result);
}
}<file_sep><?php
/**
* manage_pagetypes index view
* @author <NAME> <<EMAIL>>
* @license http://jazzee.org/license.txt
* @package jazzee
* @subpackage manage
*/
if($pageTypes): ?>
<h5>Current Page Types:</h5>
<ul>
<?php foreach($pageTypes as $type): ?>
<li><?php print $type->getName() ?>
<?php if($this->controller->checkIsAllowed('manage_pagetypes', 'edit')): ?>
(<a href='<?php print $this->path('manage/pagetypes/edit/') . $type->getId()?>'>Edit</a>)
<?php endif;?>
</li>
<?php endforeach;?>
</ul>
<?php endif; ?>
<?php if($this->controller->checkIsAllowed('manage_pagetypes', 'new')): ?>
<p><a href='<?php print $this->path('manage/pagetypes/new')?>'>Add a New Page Type</a></p>
<?php endif;?><file_sep>/**
* The JazzeeElementShortDate type
@extends JazzeeElement
*/
function JazzeeElementShortDate(){}
JazzeeElementShortDate.prototype = new JazzeeElement();
JazzeeElementShortDate.prototype.constructor = JazzeeElementShortDate;
JazzeeElementShortDate.prototype.avatar = function(){
return $('<input type="text" disabled="true">');
};<file_sep><?php
/**
* lor missed deadline view
* @author <NAME> <<EMAIL>>
* @license http://jazzee.org/license.txt
* @package jazzee
* @subpackage lor
*/
?>
<p>The deadline for completing this recommendation was <?php print $deadline;?></p><file_sep><?php
namespace Jazzee\Console;
/**
* Update the database to match the schema
*
* @author <NAME> <<EMAIL>>
* @license http://jazzee.org/license.txt
* @package jazzee
* @subpackage console
*/
class Update extends \Doctrine\ORM\Tools\Console\Command\SchemaTool\UpdateCommand
{
protected function configure(){
$this
->setName('update')
->setDescription(
'Check for updates to the database schema and provide options for updating.'
)
->setDefinition(array(
new \Symfony\Component\Console\Input\InputOption(
'complete', null, \Symfony\Component\Console\Input\InputOption::VALUE_NONE,
'If defined, all assets of the database which are not relevant to the current metadata will be dropped.'
),
new \Symfony\Component\Console\Input\InputOption(
'dump-sql', null, \Symfony\Component\Console\Input\InputOption::VALUE_NONE,
'Instead of trying to apply differences, output them.'
),
new \Symfony\Component\Console\Input\InputOption(
'force', null, \Symfony\Component\Console\Input\InputOption::VALUE_NONE,
"Force a database update. Probably not safe for production systems."
),
))
->setHelp('Process the differences between the database schema and the current set of Jazzee Entities. Developers should use --complete to drop anything'
. 'that is no longer relevant. In testing environments the --force command can be used to apply the changed directly. For productions environments'
. 'the --dump-sql option should be used to output the changes for manual consideration before they are applied.'
);
}
protected function executeSchemaCommand(\Symfony\Component\Console\Input\InputInterface $input, \Symfony\Component\Console\Output\OutputInterface $output, \Doctrine\ORM\Tools\SchemaTool $schemaTool, array $metadatas){
// Defining if update is complete or not (--complete not defined means $saveMode = true)
$saveMode = ($input->getOption('complete') !== true);
if ($input->getOption('dump-sql') === true) {
$sqls = $schemaTool->getUpdateSchemaSql($metadatas, $saveMode);
$output->write(implode(';' . PHP_EOL, $sqls) . PHP_EOL);
} else if ($input->getOption('force') === true) {
$output->write('Updating database schema...' . PHP_EOL);
$schemaTool->updateSchema($metadatas, $saveMode);
$output->write('Database schema updated successfully!' . PHP_EOL);
} else {
$output->write('ATTENTION: This operation should not be executed in a production environment.' . PHP_EOL);
$output->write('Use the incremental update to detect changes during development and use' . PHP_EOL);
$output->write('this SQL DDL to manually update your database in production.' . PHP_EOL . PHP_EOL);
$sqls = $schemaTool->getUpdateSchemaSql($metadatas, $saveMode);
if (count($sqls)) {
$output->write('Schema-Tool would execute ' . count($sqls) . ' queries to update the database.' . PHP_EOL);
$output->write('Please run the operation with --force to execute these queries or use --dump-sql to see them.' . PHP_EOL);
} else {
$output->write('Nothing to update. The database is in sync with the current entity metadata.' . PHP_EOL);
}
}
}
}<file_sep><?php
/**
* manage_cycles index view
* @author <NAME> <<EMAIL>>
* @license http://jazzee.org/license.txt
* @package jazzee
* @subpackage manage
*/
if($cycles): ?>
<h5>Current Cycles:</h5>
<ul>
<?php foreach($cycles as $cycle): ?>
<li><?php print $cycle->getName() ?>
<?php if($this->controller->checkIsAllowed('manage_cycles', 'edit')): ?>
(<a href='<?php print $this->path('manage/cycles/edit/') . $cycle->getId()?>'>Edit</a>)
<?php endif;?>
</li>
<?php endforeach;?>
</ul>
<?php endif; ?>
<?php if($this->controller->checkIsAllowed('manage_cycles', 'new')): ?>
<p><a href='<?php print $this->path('manage/cycles/new')?>'>Add a New Cycle</a></p>
<?php endif;?>
<file_sep><?php
/**
* Shibboleth Admin Authentication Controller
*
* Shibboleth is a leading identity provider for educational institutions
* Because Shibboleth is the preferred authentication mechanism at the University of California this
* module is the most likley to be up to date.
*
*/
namespace Jazzee\AdminAuthentication;
class Shibboleth implements \Jazzee\Interfaces\AdminAuthentication{
const SESSION_VAR_ID = 'shibd_userid';
/**
* Our authenticated user
* @var \Jazzee\Entity\User
*/
private $_user;
/**
* Config instance
* @var \Jazzee\Interfaces\AdminController
*/
private $_controller;
/**
* Constructor
*
* Require authentication and setup the user if a valid session is detected
*
* @param \Jazzee\Interfaces\AdminController
*/
public function __construct(\Jazzee\Interfaces\AdminController $controller){
$this->_controller = $controller;
if($this->_controller->getStore()->check(self::SESSION_VAR_ID)){
$this->_user = $this->_controller->getEntityManager()->getRepository('\Jazzee\Entity\User')->find($this->_controller->getStore()->get(self::SESSION_VAR_ID));
} else if(isset($_SERVER['Shib-Application-ID'])){ //this happens when the user is SHib authenticated, but not application authenticated.
$this->loginUser();
}
}
public function isValidUser(){
return (bool)$this->_user;
}
public function getUser(){
return $this->_user;
}
public function loginUser(){
$config = $this->_controller->getConfig();
if(!isset($_SERVER['Shib-Application-ID'])){
header('Location: ' . $config->getShibbolethLoginUrl());
exit();
}
if (!isset($_SERVER[$config->getShibbolethUsernameAttribute()])) throw new \Jazzee\Exception($config->getShibbolethUsernameAttribute() . ' attribute is missing from authentication source.');
$uniqueName = $_SERVER[$config->getShibbolethUsernameAttribute()];
$firstName = isset($_SERVER[$config->getShibbolethFirstNameAttribute()])?$_SERVER[$config->getShibbolethFirstNameAttribute()]:null;
$lastName = isset($_SERVER[$config->getShibbolethLastNameAttribute()])?$_SERVER[$config->getShibbolethLastNameAttribute()]:null;
$mail = isset($_SERVER[$config->getShibbolethEmailAddressAttribute()])?$_SERVER[$config->getShibbolethEmailAddressAttribute()]:null;
$this->_user = $this->_controller->getEntityManager()->getRepository('\Jazzee\Entity\User')->findOneBy(array('uniqueName'=>$uniqueName, 'isActive'=>true));
if($this->_user){
$this->_user->setFirstName($firstName);
$this->_user->setLastName($lastName);
$this->_user->setEmail($mail);
$this->_controller->getStore()->expire();
$this->_controller->getStore()->touchAuthentication();
$this->_controller->getStore()->set(self::SESSION_VAR_ID, $this->_user->getId());
$this->_controller->getEntityManager()->persist($this->_user);
}
}
public function logoutUser(){
$this->_user = null;
$this->_controller->getStore()->expire();
header('Location: ' . $this->_controller->getConfig()->getShibbolethLogoutUrl());
die();
}
}
<file_sep><?php
namespace Jazzee\Page;
/**
* The ETSMatch Application Page
*
* @author <NAME> <<EMAIL>>
* @license http://jazzee.org/license.txt
* @package jazzee
* @subpackage pages
*/
class ETSMatch extends AbstractPage implements \Jazzee\Interfaces\StatusPage {
/**
* These fixedIDs make it easy to find the element we are looking for
* @const integer
*/
const FID_TEST_TYPE = 2;
const FID_REGISTRATION_NUMBER = 4;
const FID_TEST_DATE = 6;
/**
* Skip an optional page
*
*/
public function do_skip(){
if(count($this->getAnswers())){
$this->_controller->addMessage('error', 'You must delete your existing answers before you can skip this page.');
return false;
}
if(!$this->_applicationPage->isRequired()){
$answer = new \Jazzee\Entity\Answer();
$answer->setPage($this->_applicationPage->getPage());
$this->_applicant->addAnswer($answer);
$answer->setPageStatus(self::SKIPPED);
$this->_controller->getEntityManager()->persist($answer);
}
}
public function do_unskip(){
$answers = $this->getAnswers();
if(count($answers) and $answers[0]->getPageStatus() == self::SKIPPED){
$this->_applicant->getAnswers()->removeElement($answers[0]);
$this->_controller->getEntityManager()->remove($answers[0]);
}
}
public function getStatus(){
$answers = $this->getAnswers();
if(!$this->_applicationPage->isRequired() and count($answers) and $answers[0]->getPageStatus() == self::SKIPPED){
return self::SKIPPED;
}
if(is_null($this->_applicationPage->getMin()) and count($answers)) return self::COMPLETE;
if(!is_null($this->_applicationPage->getMin()) and count($answers) >= $this->_applicationPage->getMin()) return self::COMPLETE;
return self::INCOMPLETE;
}
/**
* Try and match a score to an answer
*
* @param \Jazzee\Entity\Answer
*/
public function matchScore(\Jazzee\Entity\Answer $answer){
if($answer->getPageStatus() == self::SKIPPED) return;
if(!is_null($answer->getGREScore()) and !is_null($answer->getTOEFLScore())) return; //we already have a match
$testType = $this->_applicationPage->getPage()->getElementByFixedId(self::FID_TEST_TYPE)->getJazzeeElement()->displayValue($answer);
$registrationNumber = $this->_applicationPage->getPage()->getElementByFixedId(self::FID_REGISTRATION_NUMBER)->getJazzeeElement()->displayValue($answer);
$testDate = $this->_applicationPage->getPage()->getElementByFixedId(self::FID_TEST_DATE)->getJazzeeElement()->formValue($answer);
$testMonth = date('m', strtotime($testDate));
$testYear = date('Y', strtotime($testDate));
$parameters = array(
'registrationNumber' => $registrationNumber,
'testMonth' => $testMonth,
'testYear' => $testYear
);
switch($testType){
case 'GRE/GRE Subject':
$score = $this->_controller->getEntityManager()->getRepository('\Jazzee\Entity\GREScore')->findOneBy($parameters);
if($score) $answer->setGreScore($score);
break;
case 'TOEFL':
$score = $this->_controller->getEntityManager()->getRepository('\Jazzee\Entity\TOEFLScore')->findOneBy($parameters);
if($score) $answer->setTOEFLScore($score);
break;
default:
throw new \Jazzee\Exception("Unknown test type: {$testType} when trying to match a score");
}
}
/**
* Fix the registration number
*
* Transform out leading 0s and non numeric chars before processing input
* This way if we remove everything there will still be ab error for required input being blank
* @param array $arr
* @return \Foundation\Form\Input or boolean
*/
public function validateInput($arr){
$e = $this->_applicationPage->getPage()->getElementByFixedId(self::FID_REGISTRATION_NUMBER);
$key = 'el'.$e->getId();
$arr[$key] = preg_replace('#[^0-9]#','', $arr[$key]);
$arr[$key] = ltrim($arr[$key], '0');
return parent::validateInput($arr);
}
public function newAnswer($input){
parent::newAnswer($input);
//attempt to match any scores
foreach($this->getAnswers() as $answer) $this->matchScore($answer);
}
public function updateAnswer($input, $answerId){
parent::updateAnswer($input, $answerId);
//attempt to match any scores
foreach($this->getAnswers() as $answer) $this->matchScore($answer);
}
/**
* Find Possible gre score matches
* @param integer $answerID
* @param array $postData
*/
public function do_findScores($postData){
$this->checkIsAdmin();
$form = new \Foundation\Form;
$field = $form->newField();
$field->setLegend('Find Matching Scores');
$element = $field->newElement('CheckboxList', 'greMatches');
$element->setLabel('Possible GRE');
foreach($this->_controller->getEntityManager()->getRepository('\Jazzee\Entity\GREScore')->findByName(substr($this->_applicant->getFirstName(), 0, 1) . '%', substr($this->_applicant->getLastName(), 0, 2) . '%') as $score){
$element->newItem($score->getId(), $score->getLastName() . ', ' . $score->getFirstName() . ' ' . $score->getMiddleInitial() . ' ' . $score->getTestDate()->format('m/d/Y'));
}
$element = $field->newElement('CheckboxList', 'toeflMatches');
$element->setLabel('Possible TOEFL');
foreach($this->_controller->getEntityManager()->getRepository('\Jazzee\Entity\TOEFLScore')->findByName(substr($this->_applicant->getFirstName(), 0, 1) . '%', substr($this->_applicant->getLastName(), 0, 2) . '%') as $score){
$element->newItem($score->getId(), $score->getLastName() . ', ' . $score->getFirstName() . ' ' . $score->getMiddleName() . ' ' . $score->getTestDate()->format('m/d/Y'));
}
$form->newButton('submit', 'Match Scores');
if(!empty($postData)){
//create a blank for so it can get values from parent::newAnswer
$this->_form = new \Foundation\Form();
if($input = $form->processInput($postData)){
if($input->get('greMatches')){
foreach($input->get('greMatches') as $scoreId){
$score = $this->_controller->getEntityManager()->getRepository('\Jazzee\Entity\GREScore')->find($scoreId);
$arr = array(
'el' . $this->_applicationPage->getPage()->getElementByFixedId(self::FID_REGISTRATION_NUMBER)->getId() => $score->getRegistrationNumber(),
'el' . $this->_applicationPage->getPage()->getElementByFixedId(self::FID_TEST_DATE)->getId() => $score->getTestDate()->format('c'),
'el' . $this->_applicationPage->getPage()->getElementByFixedId(self::FID_TEST_TYPE)->getId() => $this->_applicationPage->getPage()->getElementByFixedId(self::FID_TEST_TYPE)->getItemByValue('GRE/GRE Subject')->getId()
);
$newInput = new \Foundation\Form\Input($arr);
$this->newAnswer($newInput);
}
}
if($input->get('toeflMatches')){
foreach($input->get('toeflMatches') as $scoreId){
$score = $this->_controller->getEntityManager()->getRepository('\Jazzee\Entity\TOEFLScore')->find($scoreId);
$arr = array(
'el' . $this->_applicationPage->getPage()->getElementByFixedId(self::FID_REGISTRATION_NUMBER)->getId() => $score->getRegistrationNumber(),
'el' . $this->_applicationPage->getPage()->getElementByFixedId(self::FID_TEST_DATE)->getId() => $score->getTestDate()->format('c'),
'el' . $this->_applicationPage->getPage()->getElementByFixedId(self::FID_TEST_TYPE)->getId() => $this->_applicationPage->getPage()->getElementByFixedId(self::FID_TEST_TYPE)->getItemByValue('TOEFL')->getId()
);
$newInput = new \Foundation\Form\Input($arr);
$this->newAnswer($newInput);
}
}
$this->_controller->setLayoutVar('status', 'success');
} else {
$this->_controller->setLayoutVar('status', 'error');
}
}
return $form;
}
/**
* Create the ets match form
* @param Entity\Page $page
*/
public function setupNewPage(){
$em = $this->_controller->getEntityManager();
$types = $em->getRepository('\Jazzee\Entity\ElementType')->findAll();
$elementTypes = array();
foreach($types as $type){
$elementTypes[$type->getClass()] = $type;
};
$count = 1;
$element = new \Jazzee\Entity\Element;
$this->_applicationPage->getPage()->addElement($element);
$element->setType($elementTypes['\\Jazzee\Element\RadioList']);
$element->setTitle('Test Type');
$element->required();
$element->setWeight(1);
$element->setFixedId(self::FID_TEST_TYPE);
$em->persist($element);
$item = new \Jazzee\Entity\ElementListItem;
$element->addItem($item);
$item->setValue('GRE/GRE Subject');
$item->setWeight(1);
$em->persist($item);
$item = new \Jazzee\Entity\ElementListItem;
$element->addItem($item);
$item->setValue('TOEFL');
$item->setWeight(2);
$em->persist($item);
$element = new \Jazzee\Entity\Element;
$this->_applicationPage->getPage()->addElement($element);
$element->setType($elementTypes['\\Jazzee\Element\TextInput']);
$element->setTitle('ETS Registration Number');
$element->setFormat('no leading zeros or hyphens');
$element->required();
$element->setWeight(2);
$element->setFixedId(self::FID_REGISTRATION_NUMBER);
$em->persist($element);
$element = new \Jazzee\Entity\Element;
$this->_applicationPage->getPage()->addElement($element);
$element->setType($elementTypes['\\Jazzee\Element\ShortDate']);
$element->setTitle('Test Date');
$element->required();
$element->setWeight(3);
$element->setFixedId(self::FID_TEST_DATE);
$em->persist($element);
}
/**
* Add Scores to the answer
* @see jazzee/src/Jazzee/Entity/Page/Jazzee\Entity\Page.AbstractPage::xmlAnswer()
*/
protected function xmlAnswer(\DomDocument $dom, \Jazzee\Entity\Answer $answer){
$xml = parent::xmlAnswer($dom, $answer);
if($answer->getMatchedScore()){
$scoreXml = $dom->createElement('score');
$element = $answer->getPage()->getElementByFixedId(self::FID_TEST_TYPE);
foreach($answer->getMatchedScore()->getSummary() as $name => $value){
$e = $dom->createElement('component');
$e->setAttribute('name', htmlentities($name,ENT_COMPAT,'utf-8'));
$e->appendChild($dom->createCDATASection($value));
$scoreXml->appendChild($e);
}
$xml->appendChild($scoreXml);
}
return $xml;
}
/**
* Create a table from answers
* and append any attached PDFs
* @param \Jazzee\ApplicantPDF $pdf
*/
public function renderPdfSection(\Jazzee\ApplicantPDF $pdf){
if($this->getAnswers()){
$pdf->addText($this->_applicationPage->getTitle(), 'h3');
$pdf->write();
$pdf->startTable();
$pdf->startTableRow();
foreach($this->_applicationPage->getPage()->getElements() as $element)$pdf->addTableCell($element->getTitle());
$pdf->addTableCell('Score');
foreach($this->getAnswers() as $answer){
$pdf->startTableRow();
foreach($this->_applicationPage->getPage()->getElements() as $element){
$element->getJazzeeElement()->setController($this->_controller);
$pdf->addTableCell ($element->getJazzeeElement()->pdfValue($answer, $pdf));
}
if($answer->getMatchedScore()){
$string = '';
foreach($answer->getMatchedScore()->getSummary() as $key => $value) $string .= "{$key}: {$value}\n";
$pdf->addTableCell($string);
} else {
$pdf->addTableCell('This score has not been received from ETS.');
}
if($attachment = $answer->getAttachment()) $pdf->addPdf($attachment->getAttachment());
}
$pdf->writeTable();
}
}
/**
* Match unmatched scores as a cron task
* @param AdminCronController $cron
*/
public static function runCron(\AdminCronController $cron){
$pageType = $cron->getEntityManager()->getRepository('\Jazzee\Entity\PageType')->findOneBy(array('class'=>'\Jazzee\Page\ETSMatch'));
$allETSMatchPages = $cron->getEntityManager()->getRepository('\Jazzee\Entity\Page')->findBy(array('type'=>$pageType->getId()));
$countGre = 0;
$countToefl = 0;
foreach($allETSMatchPages as $page){
//get all the answers without a matching score.
$answers = $cron->getEntityManager()->getRepository('\Jazzee\Entity\Answer')->findBy(array('pageStatus'=>NULL,'page'=>$page->getId(), 'greScore'=>null, 'toeflScore'=>null),array('updatedAt'=>'desc'));
foreach($answers as $answer){
if(is_null($answer->getGREScore()) and is_null($answer->getTOEFLScore())){
$testType = $page->getElementByFixedId(self::FID_TEST_TYPE)->getJazzeeElement()->displayValue($answer);
$registrationNumber = $page->getElementByFixedId(self::FID_REGISTRATION_NUMBER)->getJazzeeElement()->displayValue($answer);
$testDate = $page->getElementByFixedId(self::FID_TEST_DATE)->getJazzeeElement()->formValue($answer);
$testMonth = date('m', strtotime($testDate));
$testYear = date('Y', strtotime($testDate));
$parameters = array(
'registrationNumber' => $registrationNumber,
'testMonth' => $testMonth,
'testYear' => $testYear
);
switch($testType){
case 'GRE/GRE Subject':
$score = $cron->getEntityManager()->getRepository('\Jazzee\Entity\GREScore')->findOneBy($parameters);
if($score){
$countGre++;
$answer->setGreScore($score);
$cron->getEntityManager()->persist($answer);
}
break;
case 'TOEFL':
$score = $cron->getEntityManager()->getRepository('\Jazzee\Entity\TOEFLScore')->findOneBy($parameters);
if($score){
$countToefl++;
$answer->setTOEFLScore($score);
$cron->getEntityManager()->persist($answer);
}
break;
default:
throw new \Jazzee\Exception("Unknown test type: {$testType} when trying to match a score");
}
}
}
}
if($countGre) $cron->log("Found {$countGre} new GRE score matches");
if($countToefl) $cron->log("Found {$countToefl} new TOEFL score matches");
}
public static function applyPageElement(){
return 'ETSMatch-apply_page';
}
public static function pageBuilderScriptPath(){
return 'resource/scripts/page_types/JazzeePageETSMatch.js';
}
public static function applyStatusElement(){
return 'ETSMatch-apply_status';
}
public static function applicantsSingleElement(){
return 'ETSMatch-applicants_single';
}
}<file_sep><?php
/**
* Provide services for javascript classes
* such as checkign authorization or getting a good path
* @author <NAME> <<EMAIL>>
* @license http://jazzee.org/license.txt
* @package jazzee
* @subpackage admin
*/
class AdminServicesController extends \Jazzee\AdminController {
const REQUIRE_AUTHORIZATION = true;
const REQUIRE_APPLICATION = false;
protected function setUp() {
$this->layout = 'json';
$this->setLayoutVar('status', 'error');
}
/**
* Get some information
*/
public function actionIndex(){
$result = false;
if(!empty($this->post['service'])){
switch($this->post['service']){
case 'checkIsAllowed':
$this->setLayoutVar('status', 'success');
$result = $this->checkIsAllowed($this->post['controller'], $this->post['action']);
break;
case 'pathToController':
$this->setLayoutVar('status', 'success');
\Foundation\VC\Config::includeController($this->post['controller']);
if($class = \Foundation\VC\Config::getControllerClassName($this->post['controller'])){
$result = $this->path($class::PATH);
}
break;
default:
$this->addMessage('error','Invalid service requested');
}
} else {
$this->addMessage('error','No service requested');
}
$this->setVar('result', $result);
}
/**
* Any user can access
* @param string $controller
* @param string $action
* @param \Jazzee\Entity\User $user
* @param \Jazzee\Entity\Program $program
* @return bool
*/
public static function isAllowed($controller, $action, \Jazzee\Entity\User $user = null, \Jazzee\Entity\Program $program = null, \Jazzee\Entity\Application $application = null){
if(in_array($action, array('index')) AND $user){
return true;
}
return parent::isAllowed($controller, $action, $user, $program, $application);
}
}
?><file_sep><?php
namespace Jazzee\Entity;
/**
* Tag
* Applicants can be tagged with a string to group them - we store all these strings in the tags table and then link them to applicants when they are requested
* @Entity @Table(name="tags",
* uniqueConstraints={@UniqueConstraint(name="tag_title",columns={"title"})})
* @package jazzee
* @subpackage orm
**/
class Tag{
/**
* @Id
* @Column(type="bigint")
* @GeneratedValue(strategy="AUTO")
*/
private $id;
/** @Column(type="string") */
private $title;
/**
* @ManyToMany(targetEntity="Applicant", mappedBy="tags")
**/
private $applicants;
/**
* Get id
*
* @return bigint $id
*/
public function getId(){
return $this->id;
}
/**
* Set the Applicant
* @par
*/
/**
* Set title
*
* @param string $title
*/
public function setTitle($title){
$this->title = $title;
}
/**
* Get title
*
* @return string $title
*/
public function getTitle(){
return $this->title;
}
}<file_sep><?php
/**
* setup_pages result view
* a default jason view for outputting simple data
* @author <NAME> <<EMAIL>>
* @license http://jazzee.org/license.txt
* @package jazzee
* @subpackage admin
* @subpackage setup
*/
?>
"result":<?php print json_encode($result) ?><file_sep><?php
/**
* List all applicants by status
* @author <NAME> <<EMAIL>>
* @package jazzee
* @subpackage applicants
*/
class ApplicantsListController extends \Jazzee\AdminController {
const MENU = 'Applicants';
const TITLE = 'List by Tag';
const PATH = 'applicants/list';
const ACTION_INDEX = 'All Applicants';
/**
* Add the required JS
*/
protected function setUp(){
parent::setUp();
$this->addScript($this->path('resource/scripts/controllers/applicants_list.controller.js'));
}
/**
* List all applicants
*/
public function actionIndex(){
$tags = array();
$tags['Accepted'] = array();
$tags['Admitted'] = array();
$tags['Denied'] = array();
$tags['Declined'] = array();
$tags['Locked'] = array();
$tags['Paid'] = array();
$tags['Not Locked'] = array();
$tags['All Applicants'] = array();
foreach($this->_em->getRepository('\Jazzee\Entity\Applicant')->findApplicantsByName('%', '%', $this->_application) as $applicant){
$tags['All Applicants'][] = $applicant;
if($applicant->isLocked()) $tags['Locked'][] = $applicant;
else $tags['Not Locked'][] = $applicant;
if($applicant->hasPaid()) $tags['Paid'][] = $applicant;
if($applicant->getDecision() and $applicant->getDecision()->getAcceptOffer()) $tags['Accepted'][] = $applicant;
if($applicant->getDecision() and $applicant->getDecision()->getFinalAdmit()) $tags['Admitted'][] = $applicant;
if($applicant->getDecision() and $applicant->getDecision()->getDeclineOffer()) $tags['Declined'][] = $applicant;
if($applicant->getDecision() and $applicant->getDecision()->getFinalDeny()) $tags['Denied'][] = $applicant;
foreach($applicant->getTags() as $tag){
if(!isset($tags[$tag->getTitle()])) $tags = array($tag->getTitle() => array()) + $tags;
$tags[$tag->getTitle()][] = $applicant;
}
}
$this->setVar('tags', $tags);
}
}<file_sep><?php
/**
* setup_publishapplication index view
* @author <NAME> <<EMAIL>>
* @license http://jazzee.org/license.txt
* @package jazzee
*/
?>
<h2>Publication Status</h2>
<?php if($published){ ?>
<p>The application has been published</p>
<?php if($this->controller->checkIsAllowed('setup_publishapplication', 'unpublish')){ ?>
<p><a href='<?php print $this->path('setup/publishapplication/unpublish')?>'>Un-Publish Application</a></p>
<?php }?>
<?php } else { ?>
<?php if($ready){ ?>
<p>Your application is ready to be published.</p>
<?php if($this->controller->checkIsAllowed('setup_publishapplication', 'publish')){ ?>
<p><a href='<?php print $this->path('setup/publishapplication/publish')?>'>Publish Application</a></p>
<?php }?>
<?php } else { ?>
<p>Your application has the following problems: <ul>
<?php foreach ($problems as $p){ ?>
<li><?php print $p;?></li>
<?php } ?>
</ul></p>
<?php if($this->controller->checkIsAllowed('setup_publishapplication', 'publishoverride')){ ?>
<p><a href='<?php print $this->path('setup/publishapplication/publishoverride')?>'>Ignore problems and publish application</a></p>
<?php }?>
<?php } ?>
<?php } ?><file_sep><?php
namespace Jazzee;
/**
* Exception Class for Jazzee
* @package jazzee
*/
class Exception extends \Foundation\Exception {}
<file_sep><?php
/**
* JSON layout
* @author <NAME> <<EMAIL>>
* @license http://jazzee.org/license.txt
* @package jazzee
*/
header("Cache-Control: no-cache, must-revalidate");
header("Expires: Sat, 26 Jul 1997 05:00:00 GMT");
//form uploads with files require a text area to wrap their response
if(isset($textarea) and $textarea):?>
<textarea>
{
"status":<?php print json_encode($status); ?>,
"messages":<?php print json_encode($this->controller->getMessages()); ?>,
"data":{<?php print $layoutContent ?>}
}
</textarea>
<?php else:
header("Content-type: application/json");
?>
{
"status":<?php print json_encode($status); ?>,
"messages":<?php print json_encode($this->controller->getMessages()); ?>,
"data":{<?php print $layoutContent ?>}
}
<?php endif; ?><file_sep><?php
namespace Jazzee\Interfaces;
/**
* Status Page interface
* Pages which implement this can be viewed by applicants on the status screen
*
* @author <NAME> <<EMAIL>>
* @license http://jazzee.org/license.txt
* @package jazzee
* @subpackage pages
*/
interface StatusPage
{
/**
* Get the element for the apply status view
* @return string
*/
public static function applyStatusElement();
}<file_sep><?php
/**
* setup_decisionletters index view
* @author <NAME> <<EMAIL>>
* @license http://jazzee.org/license.txt
* @package jazzee
* @subpackage admin
* @subpackage setup
*/
?>
<fieldset>
<legend>Admit Letter
<?php if($this->controller->checkIsAllowed('setup_decisionletters', 'editAdmitLetter')){ ?>
(<a href='<?php print $this->path('setup/decisionletters/editAdmitLetter')?>'>Edit</a>)
<?php }?>
</legend>
<?php print $admitLetter;?>
</fieldset>
<fieldset>
<legend>Deny Letter
<?php if($this->controller->checkIsAllowed('setup_decisionletters', 'editDenyLetter')){ ?>
(<a href='<?php print $this->path('setup/decisionletters/editDenyLetter')?>'>Edit</a>)
<?php }?>
</legend>
<?php print $denyLetter;?>
</fieldset><file_sep><?php
/**
* applicant_logout view
* @author <NAME> <<EMAIL>>
* @license http://jazzee.org/license.txt
* @package jazzee
* @subpackage apply
*/
?>
<p>You have been logged out successfully. Thank you.</p><file_sep><?php
/**
* lor review view
* Review the information submitted
* @author <NAME> <<EMAIL>>
* @license http://jazzee.org/license.txt
* @package jazzee
* @subpackage lor
*/
?>
<h3>Thank you. We have received your recommendation.</h3>
<h5>For our applicant's security this page will only display once. If you wish to have a copy of this recommendation for your records you should print one now.</h5>
<?php
$class = $page->getType()->getClass();
$this->renderElement($class::lorReviewElement(), array('page'=>$page, 'answer'=>$answer));<file_sep><?php
namespace Jazzee\Entity;
/**
* Cycle
* Applications are divided into cycles which represent a single admission period
* @Entity(repositoryClass="\Jazzee\Entity\CycleRepository")
* @Table(name="cycles",
* uniqueConstraints={@UniqueConstraint(name="cycle_name_unique",columns={"name"})})
* @package jazzee
* @subpackage orm
*/
class Cycle{
/**
* @Id
* @Column(type="integer")
* @GeneratedValue(strategy="AUTO")
*/
private $id;
/** @Column(type="string", length=32) */
private $name;
/** @Column(type="datetime", nullable=true) */
private $start;
/** @Column(type="datetime", nullable=true) */
private $end;
/**
* @OneToMany(targetEntity="Application", mappedBy="cycle")
*/
protected $applications;
/**
* @ManyToMany(targetEntity="Page")
**/
private $requiredPages;
public function __construct(){
$this->requiredPages = new \Doctrine\Common\Collections\ArrayCollection();
$this->applications = new \Doctrine\Common\Collections\ArrayCollection();
}
/**
* Get the id
* @return integer
*/
public function getId(){
return $this->id;
}
/**
* Get the name
* @return string
*/
public function getName(){
return $this->name;
}
/**
* Get the start date
* @return DateTime
*/
public function getStart(){
return $this->start;
}
/**
* Get the end date
* @return DateTime
*/
public function getEnd(){
return $this->end;
}
/**
* Set the name
* @param string $name
*/
public function setName($name){
$this->name = $name;
}
/**
* Set the start date
* @param string $dateTime
*/
public function setStart($dateTime){
$start = new \DateTime($dateTime);
if($this->end and $start > $this->end) throw new \Jazzee\Exception('Cycle start date must be before end date.');
$this->start = $start;
}
/**
* Set the end date
* @param string $dateTime
*/
public function setEnd($dateTime){
$end = new \DateTime($dateTime);
if($this->start and $end < $this->start) throw new \Jazzee\Exception('Cycle end date must be after start date.');
$this->end = $end;
}
/**
* Add a required page
* @param Page $page
*/
public function addRequiredPage(Page $page){
if(!$page->isGlobal()){
throw new \Jazzee\Exception("{$page->getTitle()} (#{$page->getId()}) is not a global page and cannot be a required page for a cycle");
}
$this->requiredPages[] = $page;
}
/**
* Get the required pages for a cycle
* @return array Page
*/
public function getRequiredPages(){
return $this->requiredPages;
}
public function hasRequiredPage(Page $page){
if(count($this->requiredPages) == 0){
return false;
}
foreach($this->requiredPages as $p){
if($p == $page){
return true;
}
}
return false;
}
}
/**
* CycleRepository
* Special Repository methods for Cycles
* @package jazzee
* @subpackage orm
*/
class CycleRepository extends \Doctrine\ORM\EntityRepository{
/**
* find best current cycle
*
* If a user doesn't have a cycle we need to search for an find the best current cycle for them
* If there is a program then use that, otherwise just get the most recent cycle
* @param Program $program
* @return Cycle
*/
public function findBestCycle(Program $program = null){
if($program){
$query = $this->_em->createQuery('SELECT c FROM Jazzee\Entity\Cycle c JOIN c.applications a WHERE a.program = :program ORDER BY c.end DESC');
$query->setParameter('program', $program);
} else {
$query = $this->_em->createQuery('SELECT c FROM Jazzee\Entity\Cycle c ORDER BY c.end DESC');
}
$result = $query->getResult();
if(count($result)) return $result[0];
return false;
}
}<file_sep><?php
namespace Jazzee\Interfaces;
/**
* SIRPage interface
* Allows us to define interface for pages which can be used to ask post sir questions
*
* @author <NAME> <<EMAIL>>
* @license http://jazzee.org/license.txt
* @package jazzee
* @subpackage pages
*/
interface SirPage
{
/**
* Get the element for the SIR page view
* @return string
*/
public static function sirPageElement();
/**
* Get the element for the SIR page view
* @return string
*/
public static function sirApplicantsSingleElement();
}<file_sep>/**
* The JazzeeElementPDFFileInput type
@extends FileInput
*/
function JazzeeElementPDFFileInput(){}
JazzeeElementPDFFileInput.prototype = new FileInput();
JazzeeElementPDFFileInput.prototype.constructor = JazzeeElementPDFFileInput;
/**
* Add maximum file size
* @returns {jQuery}
*/
JazzeeElementPDFFileInput.prototype.elementProperties = function(){
var elementClass = this;
var div = JazzeeElement.prototype.elementProperties.call(this);
var obj = new FormObject();
var field = obj.newField({
legend: 'Maximum File Size',
instructions: 'Enter the maximum size for this PDF. If you select a size that is greater than the system maximum, the system maximum will be used.'
});
var element = field.newElement('TextInput', 'max');
element.label = 'Maximum File Size';
element.legend = 'Value in bytes, or with optional b,k,m,g suffix';
element.required = true;
element.value = this.convertBytesToString(this.max);
var dialog = this.page.displayForm(obj);
$('form', dialog).bind('submit',function(e){
var value = elementClass.convertShorthandValue($('input[name="max"]', this).val());
elementClass.setProperty('max', value);
elementClass.workspace();
dialog.dialog("destroy").remove();
return false;
});//end submit
var button = $('<button>').html('Maxium File Size').bind('click',function(){
$('.qtip').qtip('api').hide();
dialog.dialog('open');
}).button({
icons: {
primary: 'ui-icon-pencil'
}
});
div.append(button);
return div;
};
/**
* Convert a file size in bytes to a nice format
* @param float bytes
* @return String
*/
JazzeeElementPDFFileInput.prototype.convertBytesToString = function(bytes){
var units = ['b', 'k', 'm', 'g', 't'];
bytes = Math.max(bytes, 0);
var pow = Math.floor((bytes ? Math.log(bytes) : 0) / Math.log(1024));
pow = Math.min(pow, units.length - 1);
bytes /= Math.pow(1024, pow);
return Math.round(bytes, 2) + units[pow];
};
/**
* Convert nice values like 2M into bytes
* @param String string
* @return Integer
*/
JazzeeElementPDFFileInput.prototype.convertShorrthandValue = function(value){
value = $.trim(value).toLowerCase();
var last = value.charAt(value.length - 1);
if($.inArray(last, ['g','m','k','b']) != -1){
value = value.substring(0, value.length-1);
switch(last) {
//go from top to bottom and multiply every time
case 'g':
value *= 1024;
case 'm':
value *= 1024;
case 'k':
value *= 1024;
}
}
return value;
}<file_sep><?php
/**
* manage_globalpages previewPage view
* @author <NAME> <<EMAIL>>
* @package jazzee
* @subpackage admin
* @subpackage setup
*/
$class = $page->getPage()->getType()->getClass();
$this->renderElement($class::applyPageElement(), array('page'=>$page, 'currentAnswerID'=>false, 'applicant'=>$applicant));
?><file_sep><?php
/**
* Export application data to xml
*/
$xml = new DOMDocument();
$xml->formatOutput = true;
$app = $xml->createElement("application");
$preferences = $xml->createElement("preferences");
$preferences->appendChild($xml->createElement('contactName', $application->getContactName()));
$preferences->appendChild($xml->createElement('contactEmail', $application->getContactEmail()));
$preferences->appendChild($xml->createElement('welcome', htmlentities($application->getWelcome(),ENT_COMPAT,'utf-8')));
$preferences->appendChild($xml->createElement('open', $application->getOpen()->format('c')));
$preferences->appendChild($xml->createElement('close', $application->getClose()->format('c')));
$preferences->appendChild($xml->createElement('begin', $application->getBegin()->format('c')));
$preferences->appendChild($xml->createElement('admitletter', $application->getAdmitLetter()));
$preferences->appendChild($xml->createElement('denyletter', $application->getDenyLetter()));
$preferences->appendChild($xml->createElement('statusIncompleteText', $application->getStatusIncompleteText()));
$preferences->appendChild($xml->createElement('statusNoDecisionText', $application->getStatusNoDecisionText()));
$preferences->appendChild($xml->createElement('statusAdmitText', $application->getStatusAdmitText()));
$preferences->appendChild($xml->createElement('statusDenyText', $application->getStatusDenyText()));
$preferences->appendChild($xml->createElement('statusAcceptText', $application->getStatusAcceptText()));
$preferences->appendChild($xml->createElement('statusDeclineText', $application->getStatusDeclineText()));
$app->appendChild($preferences);
$applicationPages = $xml->createElement("pages");
$pages = $this->controller->getEntityManager()->getRepository('\Jazzee\Entity\ApplicationPage')->findBy(array('application'=>$application->getId()));
foreach($pages as $page){
$applicationPages->appendChild($this->controller->pageXml($xml, $page));
}
$app->appendChild($applicationPages);
$xml->appendChild($app);
echo $xml->saveXML();<file_sep><?php
/**
* setup_users index view
* @author <NAME> <<EMAIL>>
* @license http://jazzee.org/license.txt
* @package jazzee
* @subpackage setup
*/
$this->renderElement('form', array('form'=>$form));?>
<?php if($results){ ?>
<h5>Results</h5>
<ul>
<?php foreach($results as $result){ ?>
<li><?php print $result['lastName'] . ', ' . $result['firstName'] . ' (' . ($result['emailAddress']?$result['emailAddress']:'no email') . ') (' . $result['userName'] . ')' ?>
<?php if($this->controller->checkIsAllowed('setup_users', 'new')){ ?>
(<a href='<?php print $this->path('setup/users/new/') . base64_encode($result['userName'])?>'>Add User</a>)
<?php }?>
</li>
<?php }?>
</ul>
<?php } ?>
<?php if(empty($users)){?>
<p>There are no users in this program</p>
<?php } else { ?>
<table>
<caption>Program Users</caption>
<thead>
<tr>
<th>Name</th>
<?php foreach($roles as $role){?>
<th><?php print $role->getName();?></th>
<?php } ?>
<th>Tools</th>
</tr>
</thead>
<tbody>
<?php foreach($users as $user){?>
<tr>
<td><?php print $user->getLastName(); ?>, <?php print $user->getFirstName();?>(<?php print $user->getUniqueName();?>)</td>
<?php foreach($roles as $role){?>
<td><?php if($user->hasRole($role)) print 'x'?></td>
<?php } ?>
<td>
<?php if($this->controller->checkIsAllowed('setup_users', 'edit')) { ?>
<a href='<?php print $this->controller->path('setup/users/edit/' . $user->getId());?>'>Edit Program Roles</a> |
<?php } ?>
<?php if($this->controller->checkIsAllowed('setup_users', 'remove')) { ?>
<a href='<?php print $this->controller->path('setup/users/remove/' . $user->getId());?>'>Remove from program</a>
<?php } ?>
</td>
<?php } ?>
</tbody>
</table>
<?php } ?><file_sep><?php
/**
* apply_page Payment Page type view
* @author <NAME> <<EMAIL>>
* @license http://jazzee.org/license.txt
* @package jazzee
* @subpackage apply
*/
?>
<?php if($page->getJazzeePage()->getStatus() == \Jazzee\Interfaces\Page::SKIPPED){?>
<p class="skip">You have selected to skip this page. You can still change your mind and <a href='<?php print $this->controller->getActionPath() . '/do/unskip';?>' title='complete this page'>Complete This Page</a> if you wish.</p>
<?php } else {
if(!$page->isRequired() and !count($page->getJazzeePage()->getAnswers())){?>
<p class="skip">This page is optional, if you do not have any information to enter you can <a href='<?php print $this->controller->getActionPath() . '/do/skip';?>' title='skip this page'>Skip This Page</a>.</p>
<?php }?>
<div id='counter'><?php
if($page->getJazzeePage()->getAnswers()){
if(is_null($page->getMax())){ //infinite answers page
if(count($page->getjazzeePage()->getAnswers()) >= $page->getMin()){?>
<p>You may add as many additional answers as you wish to this page, but it is not required.</p>
<?php } else { ?>
<p>You have completed <?php print count($page->getjazzeePage()->getAnswers()) ?> of the <?php print $page->getMin() ?> required answers on this page.</p>
<?php }?>
<?php } else if($page->getMax() > 1){
if($page->getMax() - count($page->getJazzeePage()->getAnswers()) == 0){?>
<p>You have completed this page.</p>
<?php } else if(count($page->getjazzeePage()->getAnswers()) >= $page->getMin()){?>
<p>You may complete an additional <?php print ($page->getMax() - count($page->getJazzeePage()->getAnswers())) ?> answers on this page, but it is not required.</p>
<?php } else { ?>
<p>You have completed <?php print count($page->getjazzeePage()->getAnswers()) ?> of the <?php print $page->getMin() ?> required answers on this page.</p>
<?php }
}
}?>
</div>
<?php
$completedPayment = false;
if($answers = $page->getJazzeePage()->getAnswers()){
print "<div id='answers'>";
foreach($answers as $answer){
if($answer->getPayment()->getStatus() == \Jazzee\Entity\Payment::PENDING or $answer->getPayment()->getStatus() == \Jazzee\Entity\Payment::SETTLED) $completedPayment = true;
$class = $answer->getPayment()->getType()->getClass();
$this->renderElement($class::APPLY_PAGE_ELEMENT, array('answer'=>$answer));
}
print '</div>';
}
if(!empty($currentAnswerID) or !$completedPayment or is_null($page->getMax()) or count($page->getJazzeePage()->getAnswers()) < $page->getMax()){ ?>
<div id='leadingText'><?php print $page->getLeadingText()?></div>
<?php $this->renderElement('form', array('form'=> $page->getJazzeePage()->getForm())); ?>
<div id='trailingText'><?php print $page->getTrailingText()?></div>
<?php }
} //end else if not skipped<file_sep><?php
/**
* manage_programs index view
* @author <NAME> <<EMAIL>>
* @license http://jazzee.org/license.txt
* @package jazzee
* @subpackage manage
*/
if($programs): ?>
<h5>Programs:</h5>
<ul>
<?php foreach($programs as $program): ?>
<li><?php print $program->getName() ?>
<?php if($this->controller->checkIsAllowed('manage_programs', 'edit')): ?>
(<a href='<?php print $this->path('manage/programs/edit/') . $program->getId()?>'>Edit</a>)
<?php endif;?>
</li>
<?php endforeach;?>
</ul>
<?php endif; ?>
<?php if($this->controller->checkIsAllowed('manage_programs', 'new')): ?>
<p><a href='<?php print $this->path('manage/programs/new')?>'>Add a New Program</a></p>
<?php endif;?>
<file_sep>/**
* The JazzeeElementTextarea type
@extends JazzeeElement
*/
function JazzeeElementTextarea(){}
JazzeeElementTextarea.prototype = new JazzeeElement();
JazzeeElementTextarea.prototype.constructor = JazzeeElementTextarea;
JazzeeElementTextarea.prototype.avatar = function(){
return $('<textarea>').attr('disabled', true);
};
/**
* Add minimum and maximum sliders
* @returns {jQuery}
*/
JazzeeElementTextarea.prototype.elementProperties = function(){
var elementClass = this;
var div = JazzeeElement.prototype.elementProperties.call(this);
var slider = $('<div>');
slider.slider({
value: elementClass.min,
min: 0,
max: 50000,
step: 100,
slide: function( event, ui ) {
elementClass.setProperty('min', ui.value);
$('#minValue').html(elementClass.min);
}
});
div.append($('<p>').html('Minimum Length ').append($('<span>').attr('id', 'minValue').html(elementClass.min)));
div.append(slider);
var slider = $('<div>');
slider.slider({
value: elementClass.max,
min: 0,
max: 50000,
step: 100,
slide: function( event, ui ) {
elementClass.setProperty('max', ui.value);
$('#maxvalue').html(elementClass.max);
}
});
div.append($('<p>').html('Maximum Length ').append($('<span>').attr('id', 'maxvalue').html(elementClass.max)));
div.append(slider);
return div;
};<file_sep><?php
/**
* Publish the application
* @author <NAME> <<EMAIL>>
* @package jazzee
* @subpackage admin
*/
class SetupPublishapplicationController extends \Jazzee\AdminController {
const MENU = 'Setup';
const TITLE = 'Publish Application';
const PATH = 'setup/publishapplication';
const ACTION_INDEX = 'Check if the application is ready to be published';
const ACTION_PUBLISH = 'Publish application';
const ACTION_UNPUBLISH = 'Un-Publish application';
const ACTION_PUBLISHOVERRIDE = 'Publish application that is not ready';
/**
* Display publication status and check if the app can be published
*/
public function actionIndex(){
$ready = true;
if(!$this->_application->canPublish()){
$problems = array();
foreach($this->_cycle->getRequiredPages() as $requiredPage){
if(!$this->_application->hasPage($requiredPage)){
$ready = false;
$problems[] = "{$requiredPage->getTitle()} page is required, but is not in the application.";
}
}
$this->setVar('problems', $problems);
}
$this->setVar('published', $this->_application->isPublished());
$this->setVar('ready', $ready);
}
/**
* Publish the application
*/
public function actionPublish(){
$this->_application->publish(false);
$this->_em->persist($this->_application);
$this->addMessage('success', 'Application Published.');
$this->redirectPath('setup/publishapplication');
}
/**
* Un Publish an application
*/
public function actionUnpublish(){
$this->_application->unPublish();
$this->_em->persist($this->_application);
$this->addMessage('success', 'Application Un-Published.');
$this->redirectPath('setup/publishapplication');
}
/**
* Publish the application that is not ready
*/
public function actionPublishoverride(){
$this->_application->publish(true);
$this->_em->persist($this->_application);
$this->addMessage('success', 'Application Published.');
$this->redirectPath('setup/publishapplication');
}
} | 62b53fa151283a1874e61f808068c08a21f2f7fa | [
"JavaScript",
"reStructuredText",
"PHP"
] | 100 | PHP | psbauman/Jazzee | 2af865fe2b35a51cd6e0a2a7f90876b1081a52c0 | bed0d779f5d4cae572666e52a4f615d5b03d1008 |
refs/heads/master | <repo_name>dieforrockvn/reprototype<file_sep>/src/model/RelatedItemModel.java
package model;
public class RelatedItemModel {
int id;
int item1Id;
int item2Id;
float relatedScore;
int numOfCoUser;
public RelatedItemModel(int id, int item1Id, int item2Id, float relatedScore, int numOfCoUser) {
super();
this.id = id;
this.item1Id = item1Id;
this.item2Id = item2Id;
this.relatedScore = relatedScore;
this.numOfCoUser = numOfCoUser;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public int getItem1Id() {
return item1Id;
}
public void setItem1Id(int item1Id) {
this.item1Id = item1Id;
}
public int getItem2Id() {
return item2Id;
}
public void setItem2Id(int item2Id) {
this.item2Id = item2Id;
}
public float getRelatedScore() {
return relatedScore;
}
public void setRelatedScore(float relatedScore) {
this.relatedScore = relatedScore;
}
public int getNumOfCoUser() {
return numOfCoUser;
}
public void setNumOfCoUser(int numOfCoUser) {
this.numOfCoUser = numOfCoUser;
}
}
<file_sep>/src/command_generator/CommandFile.java
package command_generator;
public class CommandFile {
}
<file_sep>/sql/re_prototype_struct_0717.sql
-- phpMyAdmin SQL Dump
-- version 4.4.10
-- http://www.phpmyadmin.net
--
-- Host: localhost
-- Generation Time: Jul 17, 2015 at 04:19 PM
-- Server version: 5.6.24-0ubuntu2
-- PHP Version: 5.6.4-4ubuntu6.2
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: `re_prototype`
--
-- --------------------------------------------------------
--
-- Table structure for table `item`
--
CREATE TABLE IF NOT EXISTS `item` (
`id` int(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
-- --------------------------------------------------------
--
-- Table structure for table `pre_user_item`
--
CREATE TABLE IF NOT EXISTS `pre_user_item` (
`id` int(15) NOT NULL,
`user_id` int(11) NOT NULL,
`item_id` int(11) NOT NULL,
`click_count` int(11) NOT NULL DEFAULT '1',
`rate` float NOT NULL DEFAULT '0'
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
-- --------------------------------------------------------
--
-- Table structure for table `related_item`
--
CREATE TABLE IF NOT EXISTS `related_item` (
`id` int(15) NOT NULL,
`item1_id` int(11) NOT NULL,
`item2_id` int(11) NOT NULL,
`related_score` float NOT NULL DEFAULT '0',
`numerator` float NOT NULL,
`num_co_user` int(11) NOT NULL DEFAULT '0'
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
-- --------------------------------------------------------
--
-- Table structure for table `site_zone_item`
--
CREATE TABLE IF NOT EXISTS `site_zone_item` (
`id` int(11) NOT NULL,
`site_id` int(11) NOT NULL,
`zone_id` int(11) NOT NULL,
`item_id` int(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
-- --------------------------------------------------------
--
-- Table structure for table `temp_user_item`
--
CREATE TABLE IF NOT EXISTS `temp_user_item` (
`id` int(11) NOT NULL,
`cookie_id` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
`item_id` int(11) NOT NULL,
`site_id` int(11) NOT NULL,
`zone_id` int(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
-- --------------------------------------------------------
--
-- Table structure for table `user`
--
CREATE TABLE IF NOT EXISTS `user` (
`id` int(12) NOT NULL,
`cookie_id` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,
`max_click` int(11) NOT NULL DEFAULT '0'
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
-- --------------------------------------------------------
--
-- Table structure for table `user_item`
--
CREATE TABLE IF NOT EXISTS `user_item` (
`id` int(15) NOT NULL,
`user_id` int(11) NOT NULL,
`item_id` int(11) NOT NULL,
`click_count` int(11) NOT NULL DEFAULT '1',
`rate` float NOT NULL DEFAULT '0'
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
--
-- Indexes for dumped tables
--
--
-- Indexes for table `item`
--
ALTER TABLE `item`
ADD PRIMARY KEY (`id`),
ADD UNIQUE KEY `id` (`id`);
--
-- Indexes for table `pre_user_item`
--
ALTER TABLE `pre_user_item`
ADD PRIMARY KEY (`id`),
ADD UNIQUE KEY `cookie_id` (`user_id`,`item_id`);
--
-- Indexes for table `related_item`
--
ALTER TABLE `related_item`
ADD PRIMARY KEY (`id`),
ADD UNIQUE KEY `item1_id` (`item1_id`,`item2_id`);
--
-- Indexes for table `site_zone_item`
--
ALTER TABLE `site_zone_item`
ADD PRIMARY KEY (`id`),
ADD UNIQUE KEY `site_id` (`site_id`,`zone_id`,`item_id`);
--
-- Indexes for table `temp_user_item`
--
ALTER TABLE `temp_user_item`
ADD PRIMARY KEY (`id`);
--
-- Indexes for table `user`
--
ALTER TABLE `user`
ADD PRIMARY KEY (`id`),
ADD UNIQUE KEY `cookie_id` (`cookie_id`);
--
-- Indexes for table `user_item`
--
ALTER TABLE `user_item`
ADD PRIMARY KEY (`id`),
ADD UNIQUE KEY `user_id` (`user_id`,`item_id`);
--
-- AUTO_INCREMENT for dumped tables
--
--
-- AUTO_INCREMENT for table `pre_user_item`
--
ALTER TABLE `pre_user_item`
MODIFY `id` int(15) NOT NULL AUTO_INCREMENT;
--
-- AUTO_INCREMENT for table `related_item`
--
ALTER TABLE `related_item`
MODIFY `id` int(15) NOT NULL AUTO_INCREMENT;
--
-- AUTO_INCREMENT for table `site_zone_item`
--
ALTER TABLE `site_zone_item`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT;
--
-- AUTO_INCREMENT for table `temp_user_item`
--
ALTER TABLE `temp_user_item`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT;
--
-- AUTO_INCREMENT for table `user`
--
ALTER TABLE `user`
MODIFY `id` int(12) NOT NULL AUTO_INCREMENT;
--
-- AUTO_INCREMENT for table `user_item`
--
ALTER TABLE `user_item`
MODIFY `id` int(15) NOT NULL AUTO_INCREMENT;
/*!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>/src/datasource/PredictUserItemDS.java
package datasource;
import java.util.HashMap;
public class PredictUserItemDS extends DataSource {
private static final String USER_ID = "user_id";
private static final String ITEM_ID = "item_id";
private static final String PREDICT_SCORE = "predict_score";
private static PredictUserItemDS predictUserItemDS;
private PredictUserItemDS() {
super();
}
public static PredictUserItemDS getInstance() {
if (predictUserItemDS == null) {
predictUserItemDS = new PredictUserItemDS();
}
return predictUserItemDS;
}
public void insertBatch(int userId, HashMap<Integer, Float> predictRS) {
String valueStr = "";
for (int itemId : predictRS.keySet()) {
valueStr += "(" + userId + ", " + itemId + ", " + predictRS.get(itemId) + "),";
}
commitInsert(valueStr);
}
public void commitInsert(String valueStr) {
if (valueStr.length() > 1) {
valueStr = valueStr.substring(0, valueStr.length() - 1);
String query = "INSERT IGNORE INTO predict_user_item (" + USER_ID + ", " + ITEM_ID + ", " + PREDICT_SCORE + ") VALUES " + valueStr + "ON DUPLICATE KEY UPDATE " + PREDICT_SCORE + " = VALUES(" + PREDICT_SCORE + ")";
this.dbHelper.executeUpdate(query);
}
}
}
<file_sep>/src/datasource/DataSource.java
package datasource;
import java.sql.ResultSet;
import java.sql.SQLException;
import database.DBHelper;
public class DataSource {
protected DBHelper dbHelper;
protected DataSource() {
this.dbHelper = DBHelper.getInstance();
}
protected int getInt(ResultSet rs, String columnName) {
try {
return rs.getInt(columnName);
} catch (SQLException e) {
System.err.println(e.getMessage());
}
return -1;
}
protected float getFloat(ResultSet rs, String columnName) {
try {
return rs.getFloat(columnName);
} catch (SQLException e) {
System.err.println(e.getMessage());
}
return 0;
}
protected String getString(ResultSet rs, String columnName) {
try {
return rs.getString(columnName);
} catch (SQLException e) {
System.err.println(e.getMessage());
}
return "";
}
}
<file_sep>/src/model/ItemClickCount.java
package model;
public class ItemClickCount {
int itemId;
int clickCount;
public ItemClickCount(int itemId, int clickCount) {
super();
this.itemId = itemId;
this.clickCount = clickCount;
}
public int getItemId() {
return itemId;
}
public void setItemId(int itemId) {
this.itemId = itemId;
}
public int getClickCount() {
return clickCount;
}
public void setClickCount(int clickCount) {
this.clickCount = clickCount;
}
}
<file_sep>/src/database/DBHelper.java
package 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 java.util.ArrayList;
import model.RelatedItemModel;
public class DBHelper {
private static DBHelper dbHelper;
public static final String STRING_CONNECT_DB_TEST = "jdbc:mysql://localhost:3306/unit_test_re?rewriteBatchedStatements=true&user=root&password=<PASSWORD>";
private static final String DATABASE_NAME = "re_prototype";
private static final String DATABASE_TEST_NAME = "unit_test_re";
private static final String USERNAME = "root";
private static final String PASSWORD = "<PASSWORD>";
private static String URL = "jdbc:mysql://localhost:3306/" + DATABASE_NAME + "?rewriteBatchedStatements=true" + "&user=" + USERNAME + "&password=" + PASSWORD;
private Connection connection;
private static int queryCounter = 0;
// TODO: learn connection pool
private DBHelper() {
super();
connect();
}
private void connect() {
if (connection == null) {
try {
queryCounter = 0;
connection = DriverManager.getConnection(URL);
System.out.println("Connected to DB!");
} catch (SQLException e) {
System.out.println("SQLException: " + e.getMessage());
System.out.println("SQLState: " + e.getSQLState());
System.out.println("VendorError: " + e.getErrorCode());
}
}
}
public void closeConnection() {
try {
connection.close();
System.out.println("Number of queries: " + queryCounter);
} catch (SQLException e) {
e.printStackTrace();
}
}
public static DBHelper getInstance() {
if (dbHelper == null) {
dbHelper = new DBHelper();
}
return dbHelper;
}
public void executeUpdate(String queryString) {
try {
queryCounter++;
Statement stmt = connection.createStatement();
stmt.executeUpdate(queryString);
} catch (SQLException ex) {
System.out.println("SQLException: " + ex.getMessage());
System.out.println("SQLState: " + ex.getSQLState());
System.out.println("VendorError: " + ex.getErrorCode());
System.out.println("SQL Query: " + queryString);
}
}
public ResultSet executeQuery(String query) {
queryCounter++;
Statement st = null;
ResultSet rs = null;
try {
st = this.connection.createStatement(java.sql.ResultSet.TYPE_FORWARD_ONLY, java.sql.ResultSet.CONCUR_READ_ONLY);
st.setFetchSize(Integer.MIN_VALUE);
rs = st.executeQuery(query);
return rs;
} catch (SQLException e) {
System.err.println(e.getMessage());
e.printStackTrace();
}
return null;
}
public void runUpdateBatch(String query, ArrayList<RelatedItemModel> data) {
try {
PreparedStatement preparedStatement = connection.prepareStatement(query);
for (RelatedItemModel model : data) {
preparedStatement.setInt(1, model.getItem1Id());
preparedStatement.setInt(2, model.getItem2Id());
preparedStatement.setInt(3, model.getId());
preparedStatement.addBatch();
}
preparedStatement.executeBatch();
} catch (SQLException e) {
System.err.println(e.getMessage());
System.err.println("SQLException: " + e.getMessage());
System.err.println("SQLState: " + e.getSQLState());
System.err.println("VendorError: " + e.getErrorCode());
}
}
public static void setUpDBTest() {
URL = STRING_CONNECT_DB_TEST;
}
public static String getURL() {
return URL;
}
}
<file_sep>/src/datacollector/LogCollector.java
package datacollector;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.LineIterator;
import datasource.TrackingItemIds;
import util.ArrayUtils;
/**
* Single responsibility principle
* what does this class do?
* - just ONE job: read log file
*
* @author longhm
*
*/
public class LogCollector {
private static final int SITE_ID = 4;
private static final int ZONE_ID = 6;
private static final int COOKIEID_INDEX = 11;
private static final int KIND_INDEX = 12;
private static final int ITEM_ID_INDEX = 9;
private static final String DELIMITER_STR = ",";
private static final String[] EXCEPT_COOKIEID = { "null", "0" };
private static final String CLICK_KIND = "click";
private String tempFilePath;
public LogCollector(String tempFilePath) {
this.tempFilePath = tempFilePath;
}
public void readLogFile(String filePath) {
File logFile = new File(filePath);
deleteTempFile();
System.out.println("Read file: " + logFile.getName());
LineIterator it = null;
PrintWriter writer = null;
int numLines = 0;
int clickCount = 0;
TrackingItemIds trackingItemIds = TrackingItemIds.getInstance();
try {
writer = new PrintWriter(tempFilePath);
it = FileUtils.lineIterator(logFile);
while (it.hasNext()) {
String line = it.nextLine();
String[] parts = line.split(DELIMITER_STR);
String kind = parts[KIND_INDEX];
String cookieId = parts[COOKIEID_INDEX];
int itemId = Integer.parseInt(parts[ITEM_ID_INDEX]);
if (kind.equals(CLICK_KIND) && !ArrayUtils.isArrayContainsValue(EXCEPT_COOKIEID, cookieId) && !trackingItemIds.isTrackingItem((itemId))) {
String zoneId = parts[ZONE_ID];
String siteId = parts[SITE_ID];
if (itemId > 0)
writer.println(cookieId + DELIMITER_STR + itemId + DELIMITER_STR + siteId + DELIMITER_STR + zoneId);
clickCount++;
}
numLines++;
}
} catch (IOException e) {
e.printStackTrace();
System.err.println(e.getMessage());
} finally {
System.out.println("Total click = " + clickCount);
System.out.println("Total line = " + numLines);
LineIterator.closeQuietly(it);
writer.close();
}
}
private void deleteTempFile() {
File tempFile = new File(tempFilePath);
if (tempFile.exists()) {
tempFile.delete();
}
}
}<file_sep>/src/test/TestPreSaveCoUser.java
package test;
import java.util.ArrayList;
import java.util.HashMap;
import database.DBHelper;
import datasource.UserItemDS;
public class TestPreSaveCoUser {
private static int item1 = 1588;
private static int item2 = 2758;
public static void main(String[] args) {
/**
* Get all user for item1
* Get all user for item2
*
*/
DBHelper dbHelper = DBHelper.getInstance();
UserItemDS userItemDS = UserItemDS.getInstance();
long startTime = System.currentTimeMillis();
int count = userItemDS.getNumberOfUsersRatedBothItem(item1, item2);
System.out.println("Count " + count + " SQL Query time: " + (System.currentTimeMillis() - startTime));
System.out.println("########################################################");
startTime = System.currentTimeMillis();
ArrayList<Integer> user1Ids = userItemDS.getUserIdsByItem(item1);
ArrayList<Integer> user2Ids = userItemDS.getUserIdsByItem(item2);
HashMap<Integer, Integer> user1HM = new HashMap<Integer, Integer>();
for (int user1 : user1Ids) {
user1HM.put(user1, 0);
}
int counter = 0;
for (int user2 : user2Ids) {
if (user1HM.containsKey(user2)) {
counter++;
}
}
System.out.println("Count " + counter + " HashMap time: " + (System.currentTimeMillis() - startTime));
dbHelper.closeConnection();
}
}
<file_sep>/src/algorithm/ComputeDeviationScore.java
package algorithm;
import java.util.ArrayList;
import java.util.HashMap;
import model.ItemClickCount;
import model.RelatedItemModelNew;
import model.UserItemModel;
import model.UserModel;
import tracerbullet.Helper;
import util.Pair;
import datasource.RelatedItemDS;
import datasource.UserDataSource;
import datasource.UserItemDS;
public class ComputeDeviationScore {
/**
* IF: pair of 2 items exist in related_item:
*
* 1. if user never click both 2 items before:
* --- numerator += r1 - r2
* 2. else : (if user click both 2 items before)
* --- co_user += 1
*
* ---> n -= delta_n - delta_n'
*
* ELSE: INSERT INTO related_item PAIR(item1, item2)
*
* --- numerator = r1 - r2
* --- co_user = 1
*
*/
public static void newComputeDeviationScore() {
long startTime = System.currentTimeMillis();
// Find all users that click more than 1 items: SELECT user_id from pre_user_item GROUP BY user_id HAVING COUNT(item_id) > 1
// Foreach user: get items, make pair
UserItemDS userItemDS = UserItemDS.getInstance();
UserDataSource userDataSource = UserDataSource.getInstance();
RelatedItemDS relatedItemDS = RelatedItemDS.getInstance();
ArrayList<Integer> userIDs = userItemDS.getUsersClickMoreOneItems();
System.out.println("Num of users that click more than 1 items: " + userIDs.size());
HashMap<Pair<Integer, Integer>, RelatedItemModelNew> pairItemHM = new HashMap<Pair<Integer, Integer>, RelatedItemModelNew>();
for (Integer userId : userIDs) {
// get user
UserModel userModel = userDataSource.getUserById(userId);
// get items
ArrayList<ItemClickCount> itemClickArr = userItemDS.getAllItemClickByUser(userId);
for (int i = 0; i < itemClickArr.size(); i++) {
for (int j = i + 1; j < itemClickArr.size(); j++) {
ItemClickCount item1 = itemClickArr.get(i);
ItemClickCount item2 = itemClickArr.get(j);
UserItemModel userItem1 = userItemDS.getUserItemByUserIdItemId(userId, item1.getItemId());
UserItemModel userItem2 = userItemDS.getUserItemByUserIdItemId(userId, item2.getItemId());
float deltaNum = 0;
int deltaCoUser = 0;
int userClickItem1 = 0;
int userClickItem2 = 0;
int maxClick = 0;
if (userItem1 != null && userItem2 != null) {
userClickItem1 = userItem1.getClickCount();
userClickItem2 = userItem2.getClickCount();
maxClick = Math.max(userClickItem1 + item1.getClickCount(), userClickItem2 + item2.getClickCount());
maxClick = Math.max(userModel.getMaxClick(), maxClick);
deltaNum = ((userClickItem1 - userClickItem2 + item1.getClickCount() - item2.getClickCount()) * 1.0f / maxClick)
+ (userClickItem1 - userClickItem2) * 1.0f / userModel.getMaxClick();
} else {
maxClick = Math.max(item1.getClickCount(), item2.getClickCount());
maxClick = Math.max(userModel.getMaxClick(), maxClick);
deltaNum = (item1.getClickCount() - item2.getClickCount()) * 1.0f / maxClick;
if (userItem1 != null) {
deltaNum += userClickItem1 * 1.0f / maxClick;
}
if (userItem2 != null) {
deltaNum -= userClickItem2 * 1.0f / maxClick;
}
deltaCoUser++;
}
Pair<Integer, Integer> pairItems = new Pair<Integer, Integer>(item1.getItemId(), item2.getItemId());
Pair<Integer, Integer> reversePairItems = new Pair<Integer, Integer>(item2.getItemId(), item1.getItemId());
if (pairItemHM.containsKey(reversePairItems)) {
pairItems = reversePairItems;
}
if (pairItemHM.containsKey(pairItems)) {
RelatedItemModelNew relatedItemModel = pairItemHM.get(pairItems);
relatedItemModel.setNumerator(relatedItemModel.getNumerator() + deltaNum);
relatedItemModel.setNum_co_user(relatedItemModel.getNum_co_user() + deltaCoUser);
} else {
RelatedItemModelNew relatedItemModel = relatedItemDS.getRelatedItems(item1.getItemId(), item2.getItemId());
if (relatedItemModel == null) {
if (deltaCoUser == 0) {
deltaCoUser = 1;
}
int id = 0;
relatedItemModel = new RelatedItemModelNew(id, item1.getItemId(), item2.getItemId(), deltaNum, deltaCoUser);
} else {
relatedItemModel.setNumerator(relatedItemModel.getNumerator() + deltaNum);
relatedItemModel.setNum_co_user(relatedItemModel.getNum_co_user() + deltaCoUser);
}
pairItemHM.put(pairItems, relatedItemModel);
}
}
}
}
for (Pair<Integer, Integer> pairItems : pairItemHM.keySet()) {
RelatedItemModelNew itemModelNew = pairItemHM.get(pairItems);
float deviation = itemModelNew.getNumerator() / itemModelNew.getNum_co_user();
// Check if pairItems is not exist in db
if (itemModelNew.getId() == 0) {
relatedItemDS.insert(itemModelNew.getItemId1(), itemModelNew.getItemId2(), deviation, itemModelNew.getNumerator(), itemModelNew.getNum_co_user());
} else {
relatedItemDS.update(itemModelNew.getItemId1(), itemModelNew.getItemId2(), deviation, itemModelNew.getNumerator(), itemModelNew.getNum_co_user());
}
}
System.out.println("Time to update deviation score: " + Helper.getDiffTime(startTime));
}
// public static void computeDeviationScore() {
// long startTime = System.currentTimeMillis();
// System.out.println("Start update related score!");
// // get all related items
// RelatedItemDS ds = RelatedItemDS.getInstance();
// UserItemDS userItemDS = UserItemDS.getInstance();
// updateRate();
// ArrayList<RelatedItemModel> data = ds.getAll();
// System.out.println("Related Item size " + data.size());
// long computeTime = System.currentTimeMillis();
// // WTF?????
// HashMap<Integer, HashMap<Integer, RelatedItemModel>> relatedItemHM = new HashMap<Integer, HashMap<Integer, RelatedItemModel>>();
// for (RelatedItemModel model : data) {
// // get number of co-user
// int item1 = model.getItem1Id();
// int item2 = model.getItem2Id();
// int id = model.getId();
// float relateScore = 0;
// int counterCoUser = 0;
// if (relatedItemHM.containsKey(item2) && relatedItemHM.get(item2).containsKey(item1)) {
// RelatedItemModel mModel = relatedItemHM.get(item2).get(item1);
// relateScore = -mModel.getRelatedScore();
// counterCoUser = mModel.getNumOfCoUser();
//
// } else {
// ArrayList<UserItemModel> user1Ids = userItemDS.getUserItemByItem(item1);
// ArrayList<UserItemModel> user2Ids = userItemDS.getUserItemByItem(item2);
//
// HashMap<Integer, Float> user1HM = new HashMap<Integer, Float>();
// for (UserItemModel user1 : user1Ids) {
// user1HM.put(user1.getUserId(), user1.getRate());
// }
//
// float totalRateU1 = 0, totalRateU2 = 0;
// for (UserItemModel user2 : user2Ids) {
// if (user1HM.containsKey(user2.getUserId())) {
// totalRateU1 += user1HM.get(user2.getUserId());
// totalRateU2 += user2.getRate();
// counterCoUser++;
// }
// }
// // get score
// if (counterCoUser > 0) {
// relateScore = (float) (totalRateU1 - totalRateU2) / counterCoUser;
// }
// // update record
// model.setRelatedScore(relateScore);
// model.setNumOfCoUser(counterCoUser);
// HashMap<Integer, RelatedItemModel> mModel = new HashMap<Integer, RelatedItemModel>();
// mModel.put(item2, model);
// relatedItemHM.put(item1, mModel);
// }
//
// ds.updateRecord(id, item1, item2, relateScore, counterCoUser);
//
// }
// System.out.println("Compute deviation score time: " + Helper.getDiffTime(computeTime));
// System.out.println("Time to update related score : " + Helper.getDiffTime(startTime));
// }
// private static void updateRate() {
// UserItemDS userItemDS = UserItemDS.getInstance();
// UserDataSource userDataSource = UserDataSource.getInstance();
// userDataSource.updateMaxClick();
// userItemDS.updateRate();
// }
}
<file_sep>/src/predict/Predict.java
package predict;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import model.ItemRateModel;
import model.RelatedItemModel;
import database.DBHelper;
import datasource.RelatedItemDS;
import datasource.UserDataSource;
public class Predict {
private static final String COOKIE_ID = "2000.13436674b52d5c73053c.1423406499650.4a672578";
public static void main(String[] args) {
System.out.println("Start! Compute predict for user : " + COOKIE_ID);
DBHelper dbHelper = DBHelper.getInstance();
// System.out.println(getDiffTime(startTime));
long startTime = System.currentTimeMillis();
ArrayList<RecommendItem> recommendedItems = predict(COOKIE_ID);
for (RecommendItem item : recommendedItems) {
System.out.println("Item id : " + item.itemId + " Weight " + item.weight);
}
System.out.println("Total item: " + recommendedItems.size());
dbHelper.closeConnection();
System.out.println("End! Total running" + getDiffTime(startTime));
}
private static String getDiffTime(long startTime) {
return " time: " + (System.currentTimeMillis() - startTime);
}
public static ArrayList<RecommendItem> predict(String cookieID) {
// Get all item user ranked
UserDataSource userDataSource = UserDataSource.getInstance();
ArrayList<ItemRateModel> itemRanked = userDataSource.getAllItemRankedByUser(cookieID);
HashMap<Integer, Float> itemRankedHashMap = new HashMap<Integer, Float>();
ArrayList<Integer> rankedItemIDs = new ArrayList<Integer>();
for (ItemRateModel item : itemRanked) {
itemRankedHashMap.put(item.getItemId(), item.getRate());
rankedItemIDs.add(item.getItemId());
}
System.out.println("Item ranked size: " + itemRankedHashMap.size());
// find the similar
RelatedItemDS relatedItemDS = RelatedItemDS.getInstance();
// HashMap<Integer, Float> weightHashMap = new HashMap<Integer, Float>();
ArrayList<RecommendItem> recommendedItems = new ArrayList<RecommendItem>();
ArrayList<RelatedItemModel> relatedItems = relatedItemDS.getRelatedItemList(rankedItemIDs);
System.out.println("Related Item size: " + relatedItems.size());
HashMap<Integer, ItemWeight> recommendItemHM = new HashMap<Integer, ItemWeight>();
long timer = System.currentTimeMillis();
for (RelatedItemModel relatedItemModel : relatedItems) {
// float numerator = 0;
// float denominator = 0;
// if (!itemRankedHashMap.containsKey(itemId1)) {
// ArrayList<RelatedItemModel> mRelatedItemModels = relatedItemDS.getRelatedItems(itemId1, rankedItemIDs);
float deviation = relatedItemModel.getRelatedScore();
float numerator = (itemRankedHashMap.get(relatedItemModel.getItem2Id()) + deviation) * relatedItemModel.getNumOfCoUser();
float denominator = relatedItemModel.getNumOfCoUser();
int itemid1 = relatedItemModel.getItem1Id();
if (!recommendItemHM.containsKey(itemid1)) {
// compute numerator and denominator
ItemWeight itemWeight = new ItemWeight(numerator, denominator);
recommendItemHM.put(itemid1, itemWeight);
} else {
ItemWeight itemWeight = recommendItemHM.get(itemid1);
itemWeight.numerator += numerator;
itemWeight.denominator += denominator;
recommendItemHM.put(itemid1, itemWeight);
}
}
System.out.println("Time to compute weight : " + (System.currentTimeMillis() - timer));
for (int itemId : recommendItemHM.keySet()) {
recommendedItems.add(new RecommendItem(itemId, recommendItemHM.get(itemId).getWeight()));
}
Collections.sort(recommendedItems, new Comparator<RecommendItem>() {
@Override
public int compare(RecommendItem o1, RecommendItem o2) {
return Float.compare(o2.weight, o1.weight);
}
});
return recommendedItems;
}
}
class RecommendItem {
int itemId;
float weight;
public RecommendItem(int itemId, float weight) {
super();
this.itemId = itemId;
this.weight = weight;
}
}
class ItemWeight {
float numerator;
float denominator;
public ItemWeight(float numerator, float denominator) {
super();
this.numerator = numerator;
this.denominator = denominator;
}
public float getWeight() {
if (denominator > 0)
return numerator / denominator;
return 0;
}
}<file_sep>/src/model/ItemModel.java
package model;
public class ItemModel {
int id;
public ItemModel(int id) {
super();
this.id = id;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
}
<file_sep>/src/datasource/AllTests.java
package datasource;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.runner.RunWith;
import org.junit.runners.Suite;
import org.junit.runners.Suite.SuiteClasses;
import predict.PredictTest;
import database.DBHelper;
@RunWith(Suite.class)
@SuiteClasses({ TempTblDSTest.class, PredictTest.class })
public class AllTests {
private static DBHelper dbHelper;
@BeforeClass
public static void setUpClass() throws Exception {
DBHelper.setUpDBTest();
dbHelper = DBHelper.getInstance();
truncateTable();
}
@AfterClass
public static void tearDownClass() throws Exception {
dbHelper.closeConnection();
}
private static void truncateTable() {
String query = "TRUNCATE user_item";
dbHelper.executeUpdate(query);
}
}
<file_sep>/src/datasource/TempTblDS.java
package datasource;
import tracerbullet.Helper;
import algorithm.ComputeDeviationScore;
import database.DBHelper;
public class TempTblDS {
private static final String SITE_ZONE_ITEM_TBL = "site_zone_item";
// private static final int DIVIDE_PARTS = 100;
private static final String RELATED_ITEM_TBL = "related_item";
private static final String USER_ITEM_TBL = "user_item";
private static final String ITEM_TBL = "item";
private static final String USER_TBL = "user";
private static final String TEMP_USER_ITEM_TBL = "temp_user_item";
private static final String COOKIE_ID = "cookie_id";
private static final String ITEM_ID = "item_id";
private static final String Id = "id";
private static final int NUM_DIVIDE_PARTS = 100;
private static final String PRE_USER_ITEM_TBL = "pre_user_item";
private static final String SITE_ID = "site_id";
private static final String ZONE_ID = "zone_id";
private static TempTblDS tempTblDS;
private DBHelper dbHelper;
private TempTblDS() {
this.dbHelper = DBHelper.getInstance();
}
public static TempTblDS getInstance() {
if (tempTblDS == null) {
tempTblDS = new TempTblDS();
}
return tempTblDS;
}
// insert into other tbl: wrap function
public void insertDataFromTempFile(String tempDataFile) {
truncateTable();
insertIntoTempTblFromFile(tempDataFile);
insertIntoUserTbl();
insertIntoItemTbl();
insertIntoSizeZoneItemTbl();
insertIntoPreUserItem();
ComputeDeviationScore.newComputeDeviationScore();
insertIntoUserItem();
// insertIntoRatingTbl();
// insertIntoRelatedItemTbl();
convertClickCountToRating();
}
private void insertIntoSizeZoneItemTbl() {
System.out.println("Start insert into " + SITE_ZONE_ITEM_TBL + " tbl");
long startTime = System.currentTimeMillis();
String query = "INSERT IGNORE INTO " + SITE_ZONE_ITEM_TBL + " (" + SITE_ID + ", " + ZONE_ID + ", " + ITEM_ID + ") SELECT " + SITE_ID + ", " + ZONE_ID + ", "
+ ITEM_ID + " FROM " + TEMP_USER_ITEM_TBL;
dbHelper.executeUpdate(query);
System.out.println("Time to insert " + SITE_ZONE_ITEM_TBL + " :" + Helper.getDiffTime(startTime));
}
protected void insertIntoUserItem() {
System.out.println("Start insert into " + USER_ITEM_TBL + " tbl");
long startTime = System.currentTimeMillis();
String query = "INSERT INTO " + USER_ITEM_TBL + " (user_id, item_id, click_count) SELECT user_id, item_id, click_count FROM " + PRE_USER_ITEM_TBL
+ " ON DUPLICATE KEY UPDATE user_item.click_count = user_item.click_count + pre_user_item.click_count";
dbHelper.executeUpdate(query);
System.out.println("Time to insert " + USER_ITEM_TBL + " :" + Helper.getDiffTime(startTime));
}
private void insertIntoPreUserItem() {
long startTime = System.currentTimeMillis();
System.out.println("Start insert into " + PRE_USER_ITEM_TBL + " tbl");
String query = "INSERT INTO " + PRE_USER_ITEM_TBL + " (user_id, item_id) SELECT user.id user_id, item_id FROM " + TEMP_USER_ITEM_TBL + " INNER JOIN " + USER_TBL
+ " ON " + USER_TBL + "." + COOKIE_ID + " = " + TEMP_USER_ITEM_TBL + "." + COOKIE_ID + " ON DUPLICATE KEY UPDATE click_count = click_count+1";
dbHelper.executeUpdate(query);
System.out.println("Time to insert " + PRE_USER_ITEM_TBL + " :" + Helper.getDiffTime(startTime));
}
private void truncateTable() {
System.out.println("Truncate Temp Table");
String query = "TRUNCATE " + TEMP_USER_ITEM_TBL;
dbHelper.executeUpdate(query);
query = "TRUNCATE " + PRE_USER_ITEM_TBL;
dbHelper.executeUpdate(query);
}
protected void convertClickCountToRating() {
UserItemDS userItemDS = UserItemDS.getInstance();
UserDataSource userDataSource = UserDataSource.getInstance();
userDataSource.updateMaxClick();
userItemDS.updateRate();
}
private void insertIntoRelatedItemTbl() {
String query = "INSERT IGNORE INTO related_item (item1_id, item2_id) SELECT A.item_id, B.item_id FROM user_item A, user_item B WHERE A.id != B.id AND A.user_id = B.user_id AND A.item_id != B.item_id";
long startTime = System.currentTimeMillis();
System.out.println("Start insert into " + RELATED_ITEM_TBL + " tbl!");
dbHelper.executeUpdate(query);
System.out.println("Time to insert into " + RELATED_ITEM_TBL + " :" + (System.currentTimeMillis() - startTime));
}
private void insertIntoTempTblFromFile(String filePath) {
System.out.println("Start load data from file to db!");
long startTime = System.currentTimeMillis();
String queryStr = "LOAD DATA LOCAL INFILE '" + filePath + "' INTO TABLE " + TEMP_USER_ITEM_TBL + " FIELDS TERMINATED BY ',' (" + COOKIE_ID + ", " + ITEM_ID
+ ", " + SITE_ID + ", " + ZONE_ID + ")";
dbHelper.executeUpdate(queryStr);
System.out.println("Time to load file to db: " + (System.currentTimeMillis() - startTime));
}
/**
* insertInto user_item rating
* run after insert to user and item tbl
*/
private void insertIntoRatingTbl() {
long startTime = System.currentTimeMillis();
System.out.println("Start insert into " + USER_ITEM_TBL + " tbl");
String query = "";
for (int i = 0; i < NUM_DIVIDE_PARTS; i++) {
query = "INSERT INTO " + USER_ITEM_TBL + " (user_id, item_id) SELECT user.id user_id, item_id FROM " + TEMP_USER_ITEM_TBL + " INNER JOIN " + USER_TBL
+ " ON " + USER_TBL + "." + COOKIE_ID + " = " + TEMP_USER_ITEM_TBL + "." + COOKIE_ID + " AND " + TEMP_USER_ITEM_TBL + "." + Id + " MOD "
+ NUM_DIVIDE_PARTS + " = " + i + " ON DUPLICATE KEY UPDATE click_count = click_count+1";
dbHelper.executeUpdate(query);
}
System.out.println("Time to insert into " + USER_ITEM_TBL + " : " + (System.currentTimeMillis() - startTime));
}
// insert into user tbl
private void insertIntoUserTbl() {
long startTime = System.currentTimeMillis();
System.out.println("Start insert into " + USER_TBL);
for (int i = 0; i < NUM_DIVIDE_PARTS; i++) {
String queryStr = "INSERT IGNORE INTO " + USER_TBL + " (" + COOKIE_ID + ") SELECT DISTINCT " + TEMP_USER_ITEM_TBL + "." + COOKIE_ID + " FROM "
+ TEMP_USER_ITEM_TBL + " WHERE " + TEMP_USER_ITEM_TBL + ".id MOD " + NUM_DIVIDE_PARTS + " = " + i;
dbHelper.executeUpdate(queryStr);
}
System.out.println("Time to Insert into " + USER_TBL + " table: " + (System.currentTimeMillis() - startTime));
}
// insert into item tbl
private void insertIntoItemTbl() {
long startTime = System.currentTimeMillis();
System.out.println("Start insert ino " + ITEM_TBL);
String queryStr = "INSERT IGNORE INTO " + ITEM_TBL + " (" + Id + ") SELECT " + TEMP_USER_ITEM_TBL + "." + ITEM_ID + " FROM " + TEMP_USER_ITEM_TBL;
dbHelper.executeUpdate(queryStr);
System.out.println("Time to Insert into " + ITEM_TBL + " table: " + (System.currentTimeMillis() - startTime));
}
}
<file_sep>/src/model/UserItemModelNew.java
package model;
public class UserItemModelNew {
int id;
int userId;
int itemId;
int clickCount;
float weight;
public UserItemModelNew(int id, int userId, int itemId, int clickCount, float weight) {
super();
this.id = id;
this.userId = userId;
this.itemId = itemId;
this.clickCount = clickCount;
this.weight = weight;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public int getUserId() {
return userId;
}
public void setUserId(int userId) {
this.userId = userId;
}
public int getItemId() {
return itemId;
}
public void setItemId(int itemId) {
this.itemId = itemId;
}
public int getClickCount() {
return clickCount;
}
public void setClickCount(int clickCount) {
this.clickCount = clickCount;
}
public float getWeight() {
return weight;
}
public void setWeight(float weight) {
this.weight = weight;
}
}
| fb11872db568a82ffa6573c6f4ea60093faed576 | [
"Java",
"SQL"
] | 15 | Java | dieforrockvn/reprototype | fd34cea4432890e770a21a6b5f0dc58bc447783b | d6de5bfec0ded6af21fefd99e2dd6a1d645d5e35 |
refs/heads/master | <file_sep>Select e.first_name, e.last_name, e.emp_no, e.Sex, s.salary
From "employees" As e
JOIN "salaries" as s on
e.emp_no=s.emp_no;
Select first_name, last_name, hire_date
FROM employees
where hire_date >= '1986-01-01' and hire_date <= '1986-12-31';
Select departments.dept_name, departments.dept_no, e.first_name, e.last_name, e.emp_no
from employees as e
Join "Dept_manager"
join departments
on "Dept_manager".dept_no = departments.dept_no
on e.emp_no = "Dept_manager".emp_no;
Select e.first_name, e.last_name, e.emp_no, departments.dept_name
from employees as e
Join dept_emp
join departments
on dept_emp.dept_no = departments.dept_no
on e.emp_no = dept_emp.emp_no;
Select first_name, last_name
From employees
Where first_name = 'Hercules' and last_name Like 'B%';
Select e.emp_no, e.last_name, e.first_name, departments.dept_name
from employees as e
Join dept_emp
join departments
on dept_emp.dept_no = departments.dept_no
on e.emp_no = dept_emp.emp_no
WHERE departments.dept_name = 'Sales';
Select e.emp_no, e.last_name, e.first_name, departments.dept_name
from employees as e
Join dept_emp
join departments
on dept_emp.dept_no = departments.dept_no
on e.emp_no = dept_emp.emp_no
WHERE departments.dept_name = 'Sales' or departments.dept_name ='Development';
select last_name, COUNT(last_name) as "Number of people wiht the same last name"
FROM employees
GROUP BY last_name
ORDER BY "Number of people wiht the same last name" DESC;<file_sep>CREATE TABLE "titles" (
"title_id" Varchar(10) NOT NULL,
"title" varchar(50) NOT NULL,
CONSTRAINT "pk_titles" PRIMARY KEY (
"title_id"
)
);
CREATE TABLE "employees" (
"emp_no" int NOT NULL,
"emp_title" varchar(10) NOT NULL,
"birth_date" Date NOT NULL,
"first_name" varchar(50) NOT NULL,
"last_name" varchar(50) NOT NULL,
"Sex" varchar(1) NOT NULL,
"hire_date" Date NOT NULL,
CONSTRAINT "pk_employees" PRIMARY KEY (
"emp_no"
)
);
CREATE TABLE "departments" (
"dept_no" varchar(10) NOT NULL,
"dept_name" varchar(50) NOT NULL,
CONSTRAINT "pk_departments" PRIMARY KEY (
"dept_no"
)
);
CREATE TABLE "Dept_manager" (
"dept_no" varchar(10) NOT NULL,
"emp_no" Int NOT NULL
);
CREATE TABLE "salaries" (
"emp_no" int NOT NULL,
"salary" int NOT NULL
);
CREATE TABLE "dept_emp" (
"emp_no" Int NOT NULL,
"dept_no" varchar(10) NOT NULL
);
ALTER TABLE "employees" ADD CONSTRAINT "emp_title" FOREIGN KEY("emp_title")
REFERENCES "titles" ("title_id");
ALTER TABLE "Dept_manager" ADD CONSTRAINT "emp_no" FOREIGN KEY("emp_no")
REFERENCES "employees" ("emp_no");
ALTER TABLE "salaries" ADD CONSTRAINT "emp_no" FOREIGN KEY("emp_no")
REFERENCES "employees" ("emp_no");
ALTER TABLE "dept_emp" ADD CONSTRAINT "emp_no" FOREIGN KEY("emp_no")
REFERENCES "employees" ("emp_no");
ALTER TABLE "dept_emp" ADD CONSTRAINT "dept_no" FOREIGN KEY("dept_no")
REFERENCES "departments" ("dept_no");
ALTER TABLE "employees" MODIFY Sex VARCHAR(100) NOT NULL; | 1f22b4f465ad70c3e6614b0ee5cada0baa13fa43 | [
"SQL"
] | 2 | SQL | yaggij/sql-challenge | d6a0a880aeec0b41e3e37f2385cd1616c7cb4800 | 776ec5640d90cdc1919ddd354db8d8cf152489fd |
refs/heads/master | <file_sep># PoC of Swagger e2e tests using Cypress.io
There are three commands created to ensure code reusability:
```ts
cy.getSwaggerSection(sectionName);
cy.executeSwaggerRoute(routeName, methodName);
cy.shouldReceiveStatus(statusCode);
```
So that test suite can be the following:
```ts
cy.getSwaggerSection('store')
.executeSwaggerRoute('/store/inventory', 'GET')
.shouldReceiveStatus('200');
```
In order to reduce boilerplate code we can imrove our tests with dynamic test suite's arguments:
```ts
[
['store', '/store/inventory', 'GET', '200'],
['user', '/user', 'POST', '200'],
['user', '/user/logout', 'GET', '200'],
].forEach(([section, route, method, statusCode]) => {
describe(`When scroll to section: ${section}`, () => {
describe(`And execute ${method} on route ${route}`, () => {
it(`Should return status code: ${statusCode}`, () => {
cy.getSwaggerSection(section)
.executeSwaggerRoute(route, method)
.shouldReceiveStatus(statusCode);
});
});
});
});
```
It we will produce some BDD-style report
```
Swagger
When scroll to section: store
And execute GET on route /store/inventory
Should return status code: 200
When scroll to section: user
And execute POST on route /user
Should return status code: 200
When scroll to section: user
And execute GET on route /user/logout
Should return status code: 200
```
<file_sep>/// <reference types="cypress" />
context('Swagger e2e', () => {
beforeEach(() => {
cy.visit('https://petstore.swagger.io').wait(1000)
});
[
['store', '/store/inventory', 'GET', '200'],
['user', '/user', 'POST', '200'],
['user', '/user/logout', 'GET', '200'],
].forEach(([section, route, method, statusCode]) => {
describe(`When scroll to section: ${section}`, () => {
describe(`And execute ${method} on route ${route}`, () => {
it(`Should return status code: ${statusCode}`, () => {
cy.getSwaggerSection(section)
.executeSwaggerRoute(route, method)
.shouldReceiveStatus(statusCode);
});
});
});
});
})
<file_sep>// ***********************************************
// This example commands.js shows you how to
// create various custom commands and overwrite
// existing commands.
//
// For more comprehensive examples of custom
// commands please read more here:
// https://on.cypress.io/custom-commands
// ***********************************************
//
//
// -- This is a parent command --
// Cypress.Commands.add("login", (email, password) => { ... })
//
//
// -- This is a child command --
// Cypress.Commands.add("drag", { prevSubject: 'element'}, (subject, options) => { ... })
//
//
// -- This is a dual command --
// Cypress.Commands.add("dismiss", { prevSubject: 'optional'}, (subject, options) => { ... })
//
//
// -- This will overwrite an existing command --
// Cypress.Commands.overwrite("visit", (originalFn, url, options) => { ... })
Cypress.Commands.add('getSwaggerSection', (sectionName) => {
return cy.get(`[data-tag=${sectionName}]`)
.then($el => {
if (!$el.attr('data-is-open')) {
cy.wrap($el).click();
}
}).parent();
});
Cypress.Commands.add('executeSwaggerRoute', { prevSubject: true }, (subject, routeName, method) => {
return cy.wrap(subject).within(() => {
cy.get(`[data-path="${routeName}"]`)
.parent()
.parent()
.click()
.within(() => {
cy.get('button').contains('Try it out ').click();
cy.get('button').contains('Execute').click();
});
});;
});
Cypress.Commands.add('shouldReceiveStatus', { prevSubject: true }, (subject, statusCode) => {
cy.wrap(subject)
.contains('Server response')
.parent()
.within((response) => {
cy.wrap(response).contains(statusCode);
});
}); | 771bace04445d538c942b4007d838b567b1fc01d | [
"Markdown",
"JavaScript"
] | 3 | Markdown | itka4yk/Cypress-swagger-e2e-poc | 3ede8c54f197406f239f04f40b36bef4c1811873 | 520e76641cdde8d9434fd1102b9ebedb0707de15 |
refs/heads/master | <file_sep>import React from 'react';
import 'bootstrap/dist/css/bootstrap.min.css';
import {
BrowserRouter as Router,
Switch,
Route
} from "react-router-dom";
import MenuAppBar from './Comp/AppBar'
import Home from './Home'
import DiseasePage from './Comp/DiseasePage'
export default function App() {
return (
(<>
<Router>
<MenuAppBar />
<div className="col-lg-11 mx-auto mt-3">
<Switch>
<Route exact path="/">
<Home />
</Route>
<Route exact path="/view/:id" component={DiseasePage} />
</Switch>
</div>
</Router>
</>
)
);
}
<file_sep>
### `Intoduction`
This web app does disease diagnosis and suggest some general precaution based on symptoms you have.
### `npm install`
install Required Dependencies using npm install
### `npm start`
Runs the app in the development mode.<br />
Open [http://localhost:3000](http://localhost:3000) to view it in the browser.
<file_sep>import React from 'react';
// import Chip from '@material-ui/core/Chip';
import Autocomplete from '@material-ui/lab/Autocomplete';
import { makeStyles } from '@material-ui/core/styles';
import TextField from '@material-ui/core/TextField';
import Cookies from 'universal-cookie';
const cookies = new Cookies();
const useStyles = makeStyles((theme) => ({
root: {
width: '100%',
'& > * + *': {
marginTop: theme.spacing(3),
},
},
}));
function getSymptomId(item) {
return item.ID;
}
const onTagsChange = (event, values) => {
console.log(values);
// console.log(values.map(getSymptomId))
cookies.set('symptoms', values.map(getSymptomId), { path: '/' });
}
export default function Tags() {
const classes = useStyles();
return (
<div className={classes.root}>
{cookies.set('symptoms', [], { path: '/' })}
<Autocomplete
multiple
id="tags-outlined"
options={Symptoms}
onChange={onTagsChange}
getOptionLabel={(option) => option.Name}
filterSelectedOptions
renderInput={(params) => (
<TextField
{...params}
variant="outlined"
label="Please Select Your Symptoms"
placeholder="Symptoms"
/>
)}
/>
</div>
);
}
// Top 100 films as rated by IMDb users. http://www.imdb.com/chart/top
const Symptoms = [
{
"ID": 188,
"Name": "Abdominal guarding"
},
{
"ID": 10,
"Name": "Abdominal pain"
},
{
"ID": 223,
"Name": "Abdominal pain associated with menstruation"
},
{
"ID": 984,
"Name": "Absence of a pulse"
},
{
"ID": 974,
"Name": "Aggressiveness"
},
{
"ID": 981,
"Name": "Agitation"
},
{
"ID": 996,
"Name": "Ankle deformity"
},
{
"ID": 147,
"Name": "Ankle swelling"
},
{
"ID": 238,
"Name": "Anxiety"
},
{
"ID": 1009,
"Name": "Arm pain"
},
{
"ID": 971,
"Name": "Arm swelling"
},
{
"ID": 998,
"Name": "Back deformity"
},
{
"ID": 104,
"Name": "Back pain"
},
{
"ID": 180,
"Name": "Black stools"
},
{
"ID": 57,
"Name": "Blackening of vision"
},
{
"ID": 24,
"Name": "Blackhead"
},
{
"ID": 284,
"Name": "Bleeding from vagina"
},
{
"ID": 176,
"Name": "Bleeding in the conjunctiva of the eye"
},
{
"ID": 48,
"Name": "Bloated feeling in the stomach"
},
{
"ID": 190,
"Name": "Blood in stool"
},
{
"ID": 233,
"Name": "Bloody cough"
},
{
"ID": 991,
"Name": "Blue colored skin"
},
{
"ID": 240,
"Name": "Blue spot on skin"
},
{
"ID": 77,
"Name": "Blurred vision"
},
{
"ID": 239,
"Name": "Bold area among hair on the head"
},
{
"ID": 156,
"Name": "Bone fracture"
},
{
"ID": 250,
"Name": "Breathing-related pains"
},
{
"ID": 979,
"Name": "Brittleness of nails"
},
{
"ID": 192,
"Name": "Bulging abdominal wall"
},
{
"ID": 75,
"Name": "Burning eyes"
},
{
"ID": 46,
"Name": "Burning in the throat"
},
{
"ID": 288,
"Name": "Burning nose"
},
{
"ID": 107,
"Name": "Burning sensation when urinating"
},
{
"ID": 91,
"Name": "Changes in the nails"
},
{
"ID": 170,
"Name": "Cheek swelling"
},
{
"ID": 17,
"Name": "Chest pain"
},
{
"ID": 31,
"Name": "Chest tightness"
},
{
"ID": 175,
"Name": "Chills"
},
{
"ID": 218,
"Name": "Coarsening of the skin structure"
},
{
"ID": 89,
"Name": "Cold feet"
},
{
"ID": 978,
"Name": "Cold hands"
},
{
"ID": 139,
"Name": "Cold sweats"
},
{
"ID": 15,
"Name": "Cough"
},
{
"ID": 228,
"Name": "Cough with sputum"
},
{
"ID": 94,
"Name": "Cramps"
},
{
"ID": 49,
"Name": "Cravings"
},
{
"ID": 134,
"Name": "Crusting"
},
{
"ID": 260,
"Name": "Curvature of the spine"
},
{
"ID": 108,
"Name": "Dark urine"
},
{
"ID": 163,
"Name": "Decreased urine stream"
},
{
"ID": 165,
"Name": "Delayed start to urination"
},
{
"ID": 50,
"Name": "Diarrhea"
},
{
"ID": 79,
"Name": "Difficult defecation"
},
{
"ID": 126,
"Name": "Difficulty in finding words"
},
{
"ID": 98,
"Name": "Difficulty in speaking"
},
{
"ID": 93,
"Name": "Difficulty in swallowing"
},
{
"ID": 53,
"Name": "Difficulty to concentrate"
},
{
"ID": 1007,
"Name": "Difficulty to learn"
},
{
"ID": 1005,
"Name": "Difficulty with gait"
},
{
"ID": 216,
"Name": "Discoloration of nails"
},
{
"ID": 128,
"Name": "Disorientation regarding time or place"
},
{
"ID": 989,
"Name": "Distended abdomen"
},
{
"ID": 207,
"Name": "Dizziness"
},
{
"ID": 71,
"Name": "Double vision"
},
{
"ID": 270,
"Name": "Double vision, acute-onset"
},
{
"ID": 162,
"Name": "Dribbling after urination"
},
{
"ID": 244,
"Name": "Drooping eyelid"
},
{
"ID": 43,
"Name": "Drowsiness"
},
{
"ID": 273,
"Name": "Dry eyes"
},
{
"ID": 272,
"Name": "Dry mouth"
},
{
"ID": 151,
"Name": "Dry skin"
},
{
"ID": 87,
"Name": "Earache"
},
{
"ID": 92,
"Name": "Early satiety"
},
{
"ID": 1011,
"Name": "Elbow pain"
},
{
"ID": 1006,
"Name": "Enlarged calf"
},
{
"ID": 242,
"Name": "Eye blinking"
},
{
"ID": 287,
"Name": "Eye pain"
},
{
"ID": 33,
"Name": "Eye redness"
},
{
"ID": 208,
"Name": "Eyelid swelling"
},
{
"ID": 209,
"Name": "Eyelids sticking together"
},
{
"ID": 219,
"Name": "Face pain"
},
{
"ID": 246,
"Name": "Facial paralysis"
},
{
"ID": 970,
"Name": "Facial swelling"
},
{
"ID": 153,
"Name": "Fast, deepened breathing"
},
{
"ID": 83,
"Name": "Fatty defecation"
},
{
"ID": 982,
"Name": "Feeling faint"
},
{
"ID": 1014,
"Name": "Feeling ill"
},
{
"ID": 76,
"Name": "Feeling of foreign body in the eye"
},
{
"ID": 86,
"Name": "Feeling of pressure in the ear"
},
{
"ID": 164,
"Name": "Feeling of residual urine"
},
{
"ID": 145,
"Name": "Feeling of tension in the legs"
},
{
"ID": 11,
"Name": "Fever"
},
{
"ID": 995,
"Name": "Finger deformity"
},
{
"ID": 1013,
"Name": "Finger pain"
},
{
"ID": 1012,
"Name": "Finger swelling"
},
{
"ID": 214,
"Name": "Flaking skin"
},
{
"ID": 245,
"Name": "Flaking skin on the head"
},
{
"ID": 154,
"Name": "Flatulence"
},
{
"ID": 255,
"Name": "Foot pain"
},
{
"ID": 1002,
"Name": "Foot swelling"
},
{
"ID": 125,
"Name": "Forgetfulness"
},
{
"ID": 62,
"Name": "Formation of blisters on a skin area"
},
{
"ID": 84,
"Name": "Foul smelling defecation"
},
{
"ID": 59,
"Name": "Frequent urination"
},
{
"ID": 110,
"Name": "Genital warts"
},
{
"ID": 152,
"Name": "Hair loss"
},
{
"ID": 976,
"Name": "Hallucination"
},
{
"ID": 72,
"Name": "Halo"
},
{
"ID": 186,
"Name": "Hand pain"
},
{
"ID": 148,
"Name": "Hand swelling"
},
{
"ID": 80,
"Name": "Hard defecation"
},
{
"ID": 184,
"Name": "Hardening of the skin"
},
{
"ID": 9,
"Name": "Headache"
},
{
"ID": 206,
"Name": "Hearing loss"
},
{
"ID": 985,
"Name": "Heart murmur"
},
{
"ID": 45,
"Name": "Heartburn"
},
{
"ID": 122,
"Name": "Hiccups"
},
{
"ID": 993,
"Name": "Hip deformity"
},
{
"ID": 196,
"Name": "Hip pain"
},
{
"ID": 121,
"Name": "Hoarseness"
},
{
"ID": 149,
"Name": "Hot flushes"
},
{
"ID": 197,
"Name": "Immobilization"
},
{
"ID": 120,
"Name": "Impaired balance"
},
{
"ID": 90,
"Name": "Impaired hearing"
},
{
"ID": 70,
"Name": "Impaired light-dark adaptation"
},
{
"ID": 113,
"Name": "Impairment of male potency"
},
{
"ID": 81,
"Name": "Incomplete defecation"
},
{
"ID": 131,
"Name": "Increased appetite"
},
{
"ID": 262,
"Name": "Increased drive"
},
{
"ID": 204,
"Name": "Increased salivation"
},
{
"ID": 40,
"Name": "Increased thirst"
},
{
"ID": 220,
"Name": "Increased touch sensitivity"
},
{
"ID": 39,
"Name": "Increased urine quantity"
},
{
"ID": 257,
"Name": "Involuntary movements"
},
{
"ID": 986,
"Name": "Irregular heartbeat"
},
{
"ID": 65,
"Name": "Irregular mole"
},
{
"ID": 73,
"Name": "Itching eyes"
},
{
"ID": 88,
"Name": "Itching in the ear"
},
{
"ID": 973,
"Name": "Itching in the mouth or throat"
},
{
"ID": 96,
"Name": "Itching in the nose"
},
{
"ID": 21,
"Name": "Itching of skin"
},
{
"ID": 999,
"Name": "Itching of the anus"
},
{
"ID": 247,
"Name": "Itching on head"
},
{
"ID": 268,
"Name": "Itching or burning in the genital area"
},
{
"ID": 194,
"Name": "Joint effusion"
},
{
"ID": 198,
"Name": "Joint instability"
},
{
"ID": 27,
"Name": "Joint pain"
},
{
"ID": 230,
"Name": "Joint redness"
},
{
"ID": 193,
"Name": "Joint swelling"
},
{
"ID": 47,
"Name": "Joylessness"
},
{
"ID": 994,
"Name": "Knee deformity"
},
{
"ID": 256,
"Name": "Knee pain"
},
{
"ID": 146,
"Name": "Leg cramps"
},
{
"ID": 1010,
"Name": "Leg pain"
},
{
"ID": 231,
"Name": "Leg swelling"
},
{
"ID": 143,
"Name": "Leg ulcer"
},
{
"ID": 82,
"Name": "Less than 3 defecations per week"
},
{
"ID": 992,
"Name": "Limited mobility of the ankle"
},
{
"ID": 167,
"Name": "Limited mobility of the back"
},
{
"ID": 178,
"Name": "Limited mobility of the fingers"
},
{
"ID": 1000,
"Name": "Limited mobility of the hip"
},
{
"ID": 195,
"Name": "Limited mobility of the leg"
},
{
"ID": 35,
"Name": "Lip swelling"
},
{
"ID": 205,
"Name": "Lockjaw"
},
{
"ID": 210,
"Name": "Loss of eye lashes"
},
{
"ID": 174,
"Name": "Lower abdominal pain"
},
{
"ID": 263,
"Name": "Lower-back pain"
},
{
"ID": 261,
"Name": "Lump in the breast"
},
{
"ID": 266,
"Name": "Malposition of the testicles"
},
{
"ID": 232,
"Name": "Marked veins"
},
{
"ID": 235,
"Name": "Memory gap"
},
{
"ID": 112,
"Name": "Menstruation disorder"
},
{
"ID": 123,
"Name": "Missed period"
},
{
"ID": 215,
"Name": "Moist and softened skin"
},
{
"ID": 85,
"Name": "Mood swings"
},
{
"ID": 983,
"Name": "Morning stiffness"
},
{
"ID": 135,
"Name": "Mouth pain"
},
{
"ID": 97,
"Name": "Mouth ulcers"
},
{
"ID": 177,
"Name": "Muscle pain"
},
{
"ID": 119,
"Name": "Muscle stiffness"
},
{
"ID": 987,
"Name": "Muscle weakness"
},
{
"ID": 252,
"Name": "Muscular atrophy in the leg"
},
{
"ID": 202,
"Name": "Muscular atrophy of the arm"
},
{
"ID": 168,
"Name": "Muscular weakness in the arm"
},
{
"ID": 253,
"Name": "Muscular weakness in the leg"
},
{
"ID": 44,
"Name": "Nausea"
},
{
"ID": 136,
"Name": "Neck pain"
},
{
"ID": 234,
"Name": "Neck stiffness"
},
{
"ID": 114,
"Name": "Nervousness"
},
{
"ID": 133,
"Name": "Night cough"
},
{
"ID": 1004,
"Name": "Night sweats"
},
{
"ID": 63,
"Name": "Non-healing skin wound"
},
{
"ID": 38,
"Name": "Nosebleed"
},
{
"ID": 221,
"Name": "Numbness in the arm"
},
{
"ID": 254,
"Name": "Numbness in the leg"
},
{
"ID": 200,
"Name": "Numbness of the hands"
},
{
"ID": 137,
"Name": "Oversensitivity to light"
},
{
"ID": 157,
"Name": "Overweight"
},
{
"ID": 155,
"Name": "Pain in the bones"
},
{
"ID": 142,
"Name": "Pain in the calves"
},
{
"ID": 12,
"Name": "Pain in the limbs"
},
{
"ID": 990,
"Name": "Pain of the anus"
},
{
"ID": 203,
"Name": "Pain on swallowing"
},
{
"ID": 251,
"Name": "Pain radiating to the arm"
},
{
"ID": 103,
"Name": "Pain radiating to the leg"
},
{
"ID": 286,
"Name": "Pain when chewing"
},
{
"ID": 189,
"Name": "Painful defecation"
},
{
"ID": 109,
"Name": "Painful urination"
},
{
"ID": 150,
"Name": "Pallor"
},
{
"ID": 37,
"Name": "Palpitations"
},
{
"ID": 140,
"Name": "Paralysis"
},
{
"ID": 118,
"Name": "Physical inactivity"
},
{
"ID": 129,
"Name": "Problems with the sense of touch in the face"
},
{
"ID": 130,
"Name": "Problems with the sense of touch in the feet"
},
{
"ID": 258,
"Name": "Protrusion of the eyes"
},
{
"ID": 172,
"Name": "Purulent discharge from the urethra"
},
{
"ID": 173,
"Name": "Purulent discharge from the vagina"
},
{
"ID": 191,
"Name": "Rebound tenderness"
},
{
"ID": 54,
"Name": "Reduced appetite"
},
{
"ID": 78,
"Name": "Ringing in the ear"
},
{
"ID": 14,
"Name": "Runny nose"
},
{
"ID": 975,
"Name": "Sadness"
},
{
"ID": 269,
"Name": "Scalp redness"
},
{
"ID": 1001,
"Name": "Scar"
},
{
"ID": 60,
"Name": "Sensitivity to cold"
},
{
"ID": 69,
"Name": "Sensitivity to glare"
},
{
"ID": 102,
"Name": "Sensitivity to noise"
},
{
"ID": 264,
"Name": "Shiny red tongue"
},
{
"ID": 29,
"Name": "Shortness of breath"
},
{
"ID": 183,
"Name": "Side pain"
},
{
"ID": 26,
"Name": "Skin lesion"
},
{
"ID": 25,
"Name": "Skin nodules"
},
{
"ID": 124,
"Name": "Skin rash"
},
{
"ID": 61,
"Name": "Skin redness"
},
{
"ID": 217,
"Name": "Skin thickening"
},
{
"ID": 34,
"Name": "Skin wheal"
},
{
"ID": 241,
"Name": "Sleepiness with spontaneous falling asleep"
},
{
"ID": 52,
"Name": "Sleeplessness"
},
{
"ID": 95,
"Name": "Sneezing"
},
{
"ID": 13,
"Name": "Sore throat"
},
{
"ID": 64,
"Name": "Sputum"
},
{
"ID": 179,
"Name": "Stomach burning"
},
{
"ID": 185,
"Name": "Stress-related leg pain"
},
{
"ID": 28,
"Name": "Stuffy nose"
},
{
"ID": 138,
"Name": "Sweating"
},
{
"ID": 236,
"Name": "Swelling in the genital area"
},
{
"ID": 267,
"Name": "Swelling of the testicles"
},
{
"ID": 248,
"Name": "Swollen glands in the armpit"
},
{
"ID": 249,
"Name": "Swollen glands in the groin"
},
{
"ID": 169,
"Name": "Swollen glands in the neck"
},
{
"ID": 211,
"Name": "Tears"
},
{
"ID": 222,
"Name": "Testicular pain"
},
{
"ID": 243,
"Name": "Tic"
},
{
"ID": 201,
"Name": "Tingling"
},
{
"ID": 16,
"Name": "Tiredness"
},
{
"ID": 997,
"Name": "Toe deformity"
},
{
"ID": 1003,
"Name": "Toe swelling"
},
{
"ID": 980,
"Name": "Tongue burning"
},
{
"ID": 977,
"Name": "Tongue swelling"
},
{
"ID": 1008,
"Name": "Toothache"
},
{
"ID": 115,
"Name": "Tremor at rest"
},
{
"ID": 132,
"Name": "Tremor on movement"
},
{
"ID": 988,
"Name": "Trouble understanding speech"
},
{
"ID": 144,
"Name": "Unconsciousness, short"
},
{
"ID": 265,
"Name": "Uncontrolled defecation"
},
{
"ID": 116,
"Name": "Underweight"
},
{
"ID": 160,
"Name": "Urge to urinate"
},
{
"ID": 161,
"Name": "Urination during the night"
},
{
"ID": 68,
"Name": "Vision impairment"
},
{
"ID": 213,
"Name": "Vision impairment for far objects"
},
{
"ID": 166,
"Name": "Vision impairment for near objects"
},
{
"ID": 66,
"Name": "Visual field loss"
},
{
"ID": 101,
"Name": "Vomiting"
},
{
"ID": 181,
"Name": "Vomiting blood"
},
{
"ID": 972,
"Name": "Weakness or numbness on right or left side of body"
},
{
"ID": 23,
"Name": "Weight gain"
},
{
"ID": 22,
"Name": "Weight loss"
},
{
"ID": 30,
"Name": "Wheezing"
},
{
"ID": 187,
"Name": "Wound"
},
{
"ID": 105,
"Name": "Yellow colored skin"
},
{
"ID": 106,
"Name": "Yellowish discoloration of the white part of the eye"
}
]<file_sep>import React, { useState } from 'react';
import { Alert } from 'react-bootstrap';
export default function AlertDismissible(props) {
const [show] = useState(true);
return (
<>
<Alert show={show} variant={props.alert_type}>
<Alert.Heading>{props.message}</Alert.Heading>
</Alert>
</>
);
}<file_sep>import React, { Component } from 'react';
import { LoadingDiseaseDiv, LoadedDiseaseDiv } from './skelton'
var header_array = ["Bearer Mi74R_XRPMAIL_COM_AUT:gOojdguRVl5VUsfSjnANuA==", "Bearer Ci72R_ETOYMAIL_COM_AUT:Hrzv6m07/r6YyBjYhL6vMw==", "Bearer Tb5k7_ETOYMAIL_COM_AUT:WdtRKsNDDUVGsCpAFqzLAQ==", "Bearer n5RZg_ETOYMAIL_COM_AUT:RHPArNAMatw41zNTfLjxpw==", "Bearer b5N6Z_ETOYMAIL_COM_AUT:KsbRaj0k0/5b0H/ix9skfA==", "Bearer d7ZBq_APRIMAIL_COM_AUT:MvF6nVh+T/m4J6ZFD5pevw==", "Bearer a7W4A_APRIMAIL_COM_AUT:GR/FcXf1WlG3HGT32SG2vA==", "Bearer y5D2Q_APRIMAIL_COM_AUT:mk+iQ7i6SMV2If+L9ie9GA==", "Bearer p9Y4J_ETOYMAIL_COM_AUT:f8Xu5EGVWLwJAzX/u+/1sQ==", "Bearer Dd4i8_CHORDMI_COM_AUT:EeWHFcC4c5kV6F3TQDdTkQ==", "Bearer q9LRi_CHORDMI_COM_AUT:4ruL6/xw/OmTkN44J1Ri2w==", "Bearer d2TYc_ETOYMAIL_COM_AUT:sHcvF98sNigYCEkde0amtQ==", "Bearer f6K9C_APRIMAIL_COM_AUT:T6r4PV0p8AZFSY0s959tQQ==", "Bearer Sp2r7_ETOYMAIL_COM_AUT:o+Rw9Jg8Gn9/0t4bKTPu1g=="]
var header_key = header_array[Math.floor(Math.random() * header_array.length)]
var myHeaders = new Headers();
myHeaders.append("Authorization", header_key); //Production Header
// myHeaders.append("Authorization", "Bearer <EMAIL>:WNqhFdFBnIWDi8cJqlji9Q=="); //Development Header
// let login_url = "sandbox-authservice.priaid.ch"; //Development Link
let login_url = "authservice.priaid.ch";
// let main_url = "sandbox-healthservice.priaid.ch"; //Development Link
let main_url = "healthservice.priaid.ch"
export default class DiseasePage extends Component {
constructor(props) {
super(props);
this.state = {
fetched_issues: '',
loading: true,
loaded: false,
disease_detail: ''
};
}
fetch_disease_detail() {
this.setState({ started_loading: true })
let id = this.props.match.params.id;
if (id !== "") {
var requestOptions = {
method: 'POST',
headers: myHeaders,
redirect: 'manual'
};
fetch("https://" + login_url + "/login", requestOptions)
.then(response => response.text())
.then(result => {
console.log(result)
let server_response = JSON.parse(result);
let login_token = server_response.Token;
var requestOptions = {
method: 'GET',
redirect: 'manual'
};
fetch(`https://${main_url}/issues/${id}/info?token=${login_token}&format=json&language=en-gb`, requestOptions)
.then(response => response.json())
.then(result => {
console.log(result)
this.setState({ loading: false, loaded: true })
this.setState({ disease_detail: result })
})
.catch(error => console.log('error', error));
})
.catch(error => console.log('error', error));
}
}
render() {
return (
<div class="container">
{this.state.loading && !this.state.started_loading
? (this.fetch_disease_detail())
: ''
}
{this.state.loading
? (<LoadingDiseaseDiv />)
: ''
}
{this.state.loaded
? (<LoadedDiseaseDiv disease={this.state.disease_detail} />)
: ''
}
</div>
);
}
}
<file_sep>import React from 'react';
import PropTypes from 'prop-types';
import { makeStyles } from '@material-ui/core/styles';
import Card from '@material-ui/core/Card';
import CardHeader from '@material-ui/core/CardHeader';
import CardContent from '@material-ui/core/CardContent';
import Typography from '@material-ui/core/Typography';
import Skeleton from '@material-ui/lab/Skeleton';
import {
BrowserRouter as Router,
Link
} from "react-router-dom";
const useStyles = makeStyles((theme) => ({
card: {
maxWidth: '100%',
margin: theme.spacing(2),
},
media: {
height: 190,
},
}));
function Media(props) {
const { loading = false } = props;
const classes = useStyles();
return (
<Card className={classes.card = ' border border-dark mt-2'}>
<CardHeader
title={
loading ? (
<Skeleton animation="wave" height={10} width="80%" style={{ marginBottom: 6 }} />
) : (
<Link to={'view/' + props.ID}>
{props.title}</Link>
)
}
subheader={loading ? <Skeleton animation="wave" height={10} width="40%" /> : 'Probability :' + props.Accuracy + ' %'}
/>
<CardContent>
{loading ? (
<React.Fragment>
<Skeleton animation="wave" height={10} style={{ marginBottom: 6 }} />
<Skeleton animation="wave" height={10} width="80%" />
</React.Fragment>
) : (
<Typography variant="body2" color="textSecondary" component="p">
{
"ICD Name: " + props.IcdName
}
</Typography>
)}
</CardContent>
</Card>
);
}
function DiseaseDiv(props) {
const { loading = false } = props;
const classes = useStyles();
return (
<Router>
<Card className={classes.card = 'mt-2'}>
<CardHeader
title={
loading ? (
<Skeleton animation="wave" height={10} width="80%" style={{ marginBottom: 6 }} />
) : (
<center><b>{props.Name}</b></center>
)
}
/>
<CardContent>
{loading ? (
<React.Fragment>
<Skeleton animation="wave" height={10} style={{ marginBottom: 6 }} />
<Skeleton animation="wave" height={10} width="80%" />
</React.Fragment>
) : (<>
Other Name
<Typography variant="body2" color="textSecondary" component="p">
{
props.Synonyms
}
</Typography><br />
Professional Name
<Typography variant="body2" color="textSecondary" component="p">
{
props.ProfName
}
</Typography>
</>
)}
</CardContent>
<CardContent>
{loading ? (
<React.Fragment>
<Skeleton animation="wave" height={12} style={{ marginBottom: 6 }} />
<Skeleton animation="wave" height={12} style={{ marginBottom: 6 }} />
<Skeleton animation="wave" height={12} style={{ marginBottom: 6 }} />
<Skeleton animation="wave" height={12} style={{ marginBottom: 6 }} />
</React.Fragment>
) : (<>
Possible Symptoms
<Typography variant="body2" color="textSecondary" component="p">
{
props.PossibleSymptoms
}
</Typography>
<br />Short Description:
<Typography variant="body2" color="textSecondary" component="p">
{
props.DescriptionShort
}
</Typography>
<br />
Complete Description:
<Typography variant="body2" color="textSecondary" component="p">
{
props.Description
}
</Typography>
</>
)}
</CardContent>
<CardContent>
{loading ? (
<React.Fragment>
<Skeleton animation="wave" height={12} style={{ marginBottom: 6 }} />
</React.Fragment>
) : (<>
MedicalCondition:
<Typography variant="body2" color="textSecondary" component="p">
{
props.MedicalCondition
}
</Typography>
</>
)}
</CardContent>
<CardContent>
{loading ? (
<React.Fragment>
<Skeleton animation="wave" height={12} style={{ marginBottom: 6 }} />
</React.Fragment>
) : (<>
Possible Treatment:
<Typography variant="body2" color="textSecondary" component="p">
{
props.TreatmentDescription
}
</Typography>
</>
)}
</CardContent>
</Card>
</Router >
);
}
Media.propTypes = {
loading: PropTypes.bool,
};
DiseaseDiv.propTypes = {
loading: PropTypes.bool,
};
export default function LoadingDiv(props) {
return (
<>
<Media loading />
</>
);
}
export function LoadedDiv(props) {
return (
<>
<Media title={props.issue.Issue.Name} Accuracy={props.issue.Issue.Accuracy} IcdName={props.issue.Issue.IcdName} ID={props.issue.Issue.ID} />
</>
);
}
export function LoadedDiseaseDiv(props) {
return (
<>
<DiseaseDiv
Name={props.disease.Name}
DescriptionShort={props.disease.DescriptionShort}
Synonyms={props.disease.Synonyms}
Description={props.disease.Description}
TreatmentDescription={props.disease.TreatmentDescription}
ProfName={props.disease.ProfName}
PossibleSymptoms={props.disease.PossibleSymptoms}
MedicalCondition={props.disease.MedicalCondition} />
</>
);
}
export function LoadingDiseaseDiv(props) {
return (
<>
<DiseaseDiv loading />
</>
);
} | e3470361bc1bee6af615631ad04deeb489be7d52 | [
"JavaScript",
"Markdown"
] | 6 | JavaScript | abhishekjnvk/Disease-Diagnosis | 72523ed073d07340b5bc92d21612dfacf6b24543 | 78a0104f6fb95d202f18f8434e05adc1310b4537 |
refs/heads/dev | <repo_name>Jacob-Morgan/IdentityModel2<file_sep>/test/UnitTests/Infrastructure/FileName.cs
using System.IO;
namespace IdentityModel.UnitTests
{
static class FileName
{
public static string Create(string name)
{
#if NETCOREAPP1_1 || NETCOREAPP2_0
var fullName = Path.Combine(System.AppContext.BaseDirectory, "documents", name);
#else
var fullName = Path.Combine(Microsoft.Extensions.PlatformAbstractions.PlatformServices.Default.Application.ApplicationBasePath, "documents", name);
#endif
return fullName;
}
}
}
<file_sep>/test/UnitTests/AuthorizeRequestTests.cs
using System;
using FluentAssertions;
using IdentityModel.Client;
using Xunit;
namespace IdentityModel.UnitTests
{
public class AuthorizeRequestTests
{
[Fact]
public void Create_absolute_url_should_behave_as_expected()
{
var request = new AuthorizeRequest("http://server/authorize");
var parmeters = new
{
foo = "foo",
bar = "bar"
};
var url = request.Create(parmeters);
url.Should().Be("http://server/authorize?foo=foo&bar=bar");
}
[Fact]
public void Create_relative_url_should_behave_as_expected()
{
var request = new AuthorizeRequest(new Uri("/authorize", UriKind.Relative));
var parmeters = new
{
foo = "foo",
bar = "bar"
};
var url = request.Create(parmeters);
url.Should().Be("/authorize?foo=foo&bar=bar");
}
}
} | 13c5fda500cafc9cf0e61666e34076d48c71feb3 | [
"C#"
] | 2 | C# | Jacob-Morgan/IdentityModel2 | 66924a82e053e5e7acc33b26b46e9fd3270e2616 | e5936e98aeb9a58e611942207e3ba54f1fc7b036 |
refs/heads/main | <file_sep><?php
/**
* Salvar como Alunos.php
* herda da classe crudAlunos
* contem metodos basicos para criar, deletar, Lê e apagar dados no BD
*/
require_once 'CrudClientes.php';
class Clientes extends CrudClientes {
protected $tabela = 'cliente'; //define a tabela do banco
//busca 1 item
public function findUnit($idcliente) {
$sql = "SELECT * FROM $this->tabela WHERE idcliente = :idcliente";
$stm = DB::prepare($sql);
$stm->bindParam(':idcliente', $idcliente, PDO::PARAM_INT);
$stm->execute();
return $stm->fetch();
}
//busca todos os itens
public function findAll() {
$sql = "SELECT * FROM $this->tabela";
$stm = DB::prepare($sql);
$stm->execute();
return $stm->fetchAll();
}
//faz insert
public function insert() {
$sql = "INSERT INTO $this->tabela (nome, endereco) VALUES (:nome, :endereco)";
$stm = DB::prepare($sql);
$stm->bindParam(':nome', $this->nome);
$stm->bindParam(':endereco', $this->endereco);
return $stm->execute();
}
//update de itens
public function update($idcliente) {
$sql = "UPDATE $this->tabela SET nome = :nome, endereco = :endereco WHERE idcliente = :idcliente";
$stm = DB::prepare($sql);
$stm->bindParam(':idcliente', $idcliente, PDO::PARAM_INT);
$stm->bindParam(':nome', $this->nome);
$stm->bindParam(':endereco', $this->endereco);
return $stm->execute();
}
//deleta 1 item
public function delete($idcliente) {
$sql = "DELETE FROM $this->tabela WHERE idcliente = :idcliente";
$stm = DB::prepare($sql);
$stm->bindParam(':idcliente', $idcliente, PDO::PARAM_INT);
return $stm->execute();
}
}
?><file_sep><?php
error_reporting(E_ALL);
ini_set("display_errors", 1);
require_once 'Clientes.php';
?>
<!DOCTYPE HTML>
<html lang="pt-BR">
<head>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- Bootstrap CSS -->
<link href="css/bootstrap.min.css" rel="stylesheet">
<title>Menu - WEB I</title>
<style rel="styleheet">
@import url("style.css");
</style>
<link rel="styleheet" type="text/css" href="style.css"/>
</head>
<body class="imagem menu">
<div class="btn btn-outline" id="lc">
<a href=ListarClientes.php ><button style="background: transparent; border-radius: 6px; padding: 10px; cursor: pointer; color: black; border: none; font-size: 16px btn-responsive">Lista de clientes</button></a>
</div>
<div class="btn btn-outline h1" id="cadc">
<a href=CadastrarCliente.php><button style="background: transparent; border-radius: 6px; padding: 10px; cursor: pointer; color: black; border: none; font-size: 16px btn-responsive">Cadastrar clientes</button></a>
</div>
<div class="btn btn-outline h1" id="vend">
<a href=CadastrarItensvenda.php><button style="background: transparent; border-radius: 6px; padding: 10px; cursor: pointer; color: black; border: none; font-size: 16px btn-responsive">Vender</button></a>
</div>
<div class="btn btn-outline" id="lp">
<a href=ListarProdutos.php><button style="background: #FFF502; border-radius: 6px; padding: 10px; cursor: pointer; color: black; border: none; font-size: 16px btn-responsive">Listar produtos</button></a>
</div>
<div class="btn btn-outline" id="cadp">
<a href=CadastrarProduto.php class=""><button style="background: #FFF502; border-radius: 6px; padding: 10px; cursor: pointer; color: black; border: none; font-size: 16px btn-responsive">Cadastrar produtos</button></a>
</div>
<!-- Optional JavaScript; choose one of the two! -->
<!-- Option 1: Bootstrap Bundle with Popper -->
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.1/dist/js/bootstrap.bundle.min.js" integrity="<KEY>" crossorigin="anonymous"></script>
<!-- Option 2: Separate Popper and Bootstrap JS -->
<!--
<script src="https://cdn.jsdelivr.net/npm/@popperjs/core@2.9.2/dist/umd/popper.min.js" integrity="<KEY>" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.1/dist/js/bootstrap.min.js" integrity="<KEY>" crossorigin="anonymous"></script>
-->
</body>
</html>
<file_sep><?php
error_reporting(E_ALL);
ini_set("display_errors", 1);
require_once 'Clientes.php';
require_once 'Produtos.php';
require_once 'Itensvendas.php';
require_once 'Vendas.php';
?>
<!DOCTYPE html>
<html>
<head lang="pt-br">
<style rel="styleheet">
@import url("style.css");
</style>
<title>DO CARMO SHOPPING</title>
<link href="css/bootstrap.min.css" rel="stylesheet">
<script src="js/jquery.js"></script>
<link rel="stylesheet" href="css/bootstrap.min.css" />
<script src="js/bootstrap.min.js"></script>
<link rel="stylesheet" href="css/bootstrap-select.min.css">
<script src="js/bootstrap-select.min.js"></script>
<script>
$(document).ready(function () {
$('select').selectpicker();
//$('#cidades').selectpicker();
carrega_dados('cliente');
carrega_dados('produto');
function carrega_dados(tipo){
$.ajax({
url: "carrega_dados.php",
method: "POST",
data: {tipo: tipo},
dataType: "json",
success: function (data)
{
var html = '';
for (var count = 0; count < data.length; count++){
html += '<option value="' + data[count].id + '">' + data[count].nome + '</option>';
}
if (tipo == 'cliente'){
$('#idcliente').html(html);
$('#idcliente').selectpicker('refresh');
}
if (tipo == 'produto') {
$('#idproduto').html(html);
$('#idproduto').selectpicker('refresh');
}
}
})
}
$(document).on('#idcliente', '#idproduto', function () {
$('#idcliente').val();
carrega_dados('cliente');
$('#idproduto').val();
carrega_dados('produto');
});
});
</script>
</head>
<body class="imagempadrao menu">
<?php
if(isset($_POST['adicionar'])):
$idcliente = $_POST['cliente'];
$Vendas->setIdcliente($idcliente);
foreach ($Vendas->findAll() as $key => $valu) {
foreach ($Clientes->findAll() as $key => $value) {
if($value->idcliente == $valu->idcliente){
$variavel = $valu->idvenda;
$nomecliente = $value->nome;
}
}
}
if($Vendas->insert()){
$idvenda = $variavel;
$idproduto = $_POST['produto'];
$valorvenda = $_POST['valorvenda'];
$quantidade = $_POST['quantidade'];
$Carrinho->setIdvenda($idvenda);
$Carrinho->setIdproduto($idproduto);
$Carrinho->setValorvenda($valorvenda);
$Carrinho->setQuantidade($quantidade);
}
if($Itensvendas->insert()){
echo "Venda concluída com sucesso";
}
endif;
if(isset($_POST['adicionar'])):
$idcliente = $_POST['cliente'];
$Vendas->setIdcliente($idcliente);
foreach ($Vendas->findAll() as $key => $valu) {
foreach ($Clientes->findAll() as $key => $value) {
if($value->idcliente == $valu->idcliente){
$variavel = $valu->idvenda;
$nomecliente = $value->nome;
}
}
}
if($Vendas->insert()){
$idvenda = $variavel;
$idproduto = $_POST['produto'];
$valorvenda = $_POST['valorvenda'];
$quantidade = $_POST['quantidade'];
$Carrinho->setIdvenda($idvenda);
$Carrinho->setIdproduto($idproduto);
$Carrinho->setValorvenda($valorvenda);
$Carrinho->setQuantidade($quantidade);
}
if($Itensvendas->insert()){
echo "Venda concluída com sucesso";
}
endif;
$Clientes = New Clientes;
$Produtos= New Produtos;
$Vendas = New Vendas;
$Itensvendas = New Itensvendas;
if(isset($_POST['cadastro'])):
$idcliente = $_POST['cliente'];
$Vendas->setIdcliente($idcliente);
foreach ($Vendas->findAll() as $key => $valu) {
foreach ($Clientes->findAll() as $key => $value) {
if($value->idcliente == $valu->idcliente){
$variavel = $valu->idvenda;
$nomecliente = $value->nome;
}
}
}
if($Vendas->insert()){
$idvenda = $variavel;
$idproduto = $_POST['produto'];
$valorvenda = $_POST['valorvenda'];
$quantidade = $_POST['quantidade'];
$Itensvendas->setIdvenda($idvenda);
$Itensvendas->setIdproduto($idproduto);
$Itensvendas->setValorvenda($valorvenda);
$Itensvendas->setQuantidade($quantidade);
}
if($Itensvendas->insert()){
echo "Venda concluída com sucesso";
}
endif;
?>
<br />
<div class="container" style="background: black; margin-top: 8%">
<br />
<div class="panel panel-default" >
<div class="panel-body" >
<form method='post' action="" >
<div class="form-group">
<label>SELECIONE O CLIENTE:</label>
<select name="cliente" id="idcliente" class="form-control input-lg" data-live-search="true" title="Selecione o cliente"></select>
</div>
<div class="form-group">
<label>SELECIONE O PRODUTO:</label>
<select name="produto" id="idproduto" class="form-control input-lg" data-live-search="true" title="Selecione o produto"></select>
</div>
<div class="form-group">
<label>Quantidade:</label>
<input type="text" name="quantidade" class="form-control"/>
</div>
<div class="form-group">
<label>Valor:</label>
<input type="text" name="valorvenda" class="form-control"/>
</div>
<div class="form-group">
</div>
<div class="form-group">
<input type="submit" name="cadastro" class="btn btn-primary" style="background: black"/>
</div>
</form>
</div>
</div>
</div>
</body>
</html>
<file_sep><?php
/**
* Salvar como Alunos.php
* herda da classe crudAlunos
* contem metodos basicos para criar, deletar, Lê e apagar dados no BD
*/
require_once 'CrudProdutos.php';
class Produtos extends CrudProdutos {
protected $tabela = 'produto'; //define a tabela do banco
//busca 1 item
public function findUnit($idproduto) {
$sql = "SELECT * FROM $this->tabela WHERE idproduto = :idproduto";
$stm = DB::prepare($sql);
$stm->bindParam(':idproduto', $idproduto, PDO::PARAM_INT);
$stm->execute();
return $stm->fetch();
}
//busca todos os itens
public function findAll() {
$sql = "SELECT * FROM $this->tabela";
$stm = DB::prepare($sql);
$stm->execute();
return $stm->fetchAll();
}
//faz insert
public function insert() {
$sql = "INSERT INTO $this->tabela (nomeproduto, valor) VALUES (:nomeproduto, :valor)";
$stm = DB::prepare($sql);
$stm->bindParam(':nomeproduto', $this->nomeproduto);
$stm->bindParam(':valor', $this->valor);
return $stm->execute();
}
//update de itens
public function update($idproduto) {
$sql = "UPDATE $this->tabela SET nomeproduto = :nomeproduto, valor = :valor WHERE idproduto = :idproduto";
$stm = DB::prepare($sql);
$stm->bindParam(':idproduto', $idproduto, PDO::PARAM_INT);
$stm->bindParam(':nomeproduto', $this->nomeproduto);
$stm->bindParam(':valor', $this->valor);
return $stm->execute();
}
//deleta 1 item
public function delete($idproduto) {
$sql = "DELETE FROM $this->tabela WHERE idproduto = :idproduto";
$stm = DB::prepare($sql);
$stm->bindParam(':idproduto', $idproduto, PDO::PARAM_INT);
return $stm->execute();
}
}
?><file_sep><?php
##salvar como CrudAlunos.php
##arquivo que implementa a tabela e seus atributos, acessa os metodos get e set
require_once 'DB.php'; //inclui arquivo DB
abstract class CrudItensvenda extends DB { //faz herança do arquivo DB
protected $tabela;
public $idvenda;
public $idproduto;
public $valorvenda;
public $quantidade;
public function setIdproduto($idproduto) {
$this->idproduto = $idproduto;
}
public function getIdproduto() {
return $this->idproduto;
}
public function setIdvenda($idvenda) {
$this->idvenda = $idvenda;
}
public function getIdvenda() {
return $this->idvenda;
}
public function setValorvenda($valorvenda) {
$this->valorvenda = $valorvenda;
}
public function getValorvenda() {
return $this->valorvenda;
}
public function setQuantidade($quantidade) {
$this->quantidade = $quantidade;
}
public function getQuantidade() {
return $this->quantidade;
}
}
?><file_sep><?php
##salvar como CrudAlunos.php
##arquivo que implementa a tabela e seus atributos, acessa os metodos get e set
require_once 'DB.php'; //inclui arquivo DB
abstract class CrudVenda extends DB { //faz herança do arquivo DB
protected $tabela;
public $idcliente;
public function setIdcliente($idcliente) {
$this->idcliente = $idcliente;
}
public function getIdcliente() {
return $this->idcliente;
}
}
?><file_sep><?php
error_reporting(E_ALL);
ini_set("display_errors", 1);
require_once 'Produtos.php';
?>
<!DOCTYPE HTML>
<html lang="pt-BR">
<head>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- Bootstrap CSS -->
<link href="css/bootstrap.min.css" rel="stylesheet">
<style rel="styleheet">
@import url("style.css");
</style>
<link rel="styleheet" type="text/css" href="style.css"/>
</head>
<body class="imagemproduto menu">
<h1>Lista de Produtos</h1>
<!-- Inicio da tabela -->
<table class="table table-bordered .table-responsive table-dark" style="margin: auto; margin-top: 10%; background:black; color:yellow">
<div>
<thead class="thead-black">
<tr>
<th scope="col" width=30%>Produto:</th>
<th scope="col" width=30%>Valor:</th>
<th scope="col" width=1%></th>
<th scope="col" width=1%></th>
</tr>
</thead>
</div>
<tbody>
<?php
$Produtos = New Produtos;
//exclusao de Usuario
if (isset($_POST['excluir'])){
$idproduto = $_POST['idproduto'];
$Produtos->delete($idproduto);
}
foreach ($Produtos->findAll() as $key => $value) { ?>
<tr>
<td> <?php echo $value->nomeproduto;?> </td>
<td> <?php echo $value->valor;?> </td>
<td>
<form method="post" action="AlterarProduto.php">
<input name="idproduto" type="hidden" value="<?php echo $value->idproduto;?>"/>
<input name="nomeproduto" type="hidden" value="<?php echo $value->nomeproduto;?>"/>
<input name="valor" type="hidden" value="<?php echo $value->valor;?>"/>
<button name="alterar" type="submit" class="btn btn-warning">Alterar</button>
</form>
<td>
<form method="post" >
<input name="idproduto" type="hidden" value="<?php echo $value->idproduto;?>"/>
<button name="excluir" type="submit" class="btn btn-danger">Excluir</button>
</form>
</td>
</tr>
<?php } ?>
</body>
</table>
<!-- Fim da tabela -->
<!-- Optional JavaScript; choose one of the two! -->
<!-- Option 1: Bootstrap Bundle with Popper -->
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.1/dist/js/bootstrap.bundle.min.js" integrity="<KEY>" crossorigin="anonymous"></script>
<!-- Option 2: Separate Popper and Bootstrap JS -->
<!--
<script src="https://cdn.jsdelivr.net/npm/@popperjs/core@2.9.2/dist/umd/popper.min.js" integrity="<KEY>" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.1/dist/js/bootstrap.min.js" integrity="<KEY>" crossorigin="anonymous"></script>
-->
</body>
</html>
<file_sep><?php
error_reporting(E_ALL);
ini_set("display_errors", 1);
require_once 'Clientes.php';
?>
<!DOCTYPE HTML>
<html lang="pt-BR">
<head>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- Bootstrap CSS -->
<link href="css/bootstrap.min.css" rel="stylesheet">
<style rel="styleheet">
@import url("style.css");
</style>
<link rel="styleheet" type="text/css" href="style.css"/>
</head>
<body class="imagemalterardados">
<?php
$idcliente = $_POST['idcliente'];
$nome = $_POST['nome'];
$endereco = $_POST['endereco'];
if (isset($_POST['alterarDados'])):
{
$Clientes = new Clientes;
$Clientes->setNome($nome);
$Clientes->setEndereco($endereco);
$Clientes->update($idcliente);
}
endif;
?>
<form method='post' action="" style="margin-top: 20%">
<label for='nome'> Nome:</label>
<input type="text" name="nome" value="<?php echo $nome;?>"/>
<label for='endereco'> Endereço: </label>
<input type="Text" name="endereco"value="<?php echo $endereco;?>"/>
<input type="hidden" name="idcliente"value="<?php echo $idcliente;?>"/>
<div class="mb-3" style="margin: auto; margin-top: 2%">
<button name="alterarDados" type="submit" style="background: black; border-radius: 6px; padding: 7px; cursor: pointer; color: yellow; border: none; font-size: 16px btn-responsive">Alterar dados</button>
<a href=ListarClientes.php style="background: black; border-radius: 6px; padding: 9px; cursor: pointer; color: yellow; border: none; font-size: 16px btn-responsive">Listar clientes</a>
</div>
</form>
</body>
</html>
<file_sep><?php
error_reporting(E_ALL);
ini_set("display_errors", 1);
require_once 'Produtos.php';
?>
<!DOCTYPE HTML>
<html lang="pt-BR">
<head>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- Bootstrap CSS -->
<link href="css/bootstrap.min.css" rel="stylesheet">
<style rel="styleheet">
@import url("style.css");
</style>
<link rel="styleheet" type="text/css" href="style.css"/>
</head>
<body class="imagemalterardados">
<?php
$idproduto = $_POST['idproduto'];
$nomeproduto = $_POST['nomeproduto'];
$valor = $_POST['valor'];
if (isset($_POST['alterarDados'])):
{
$Produtos = new Produtos;
$Produtos->setNome($nomeproduto);
$Produtos->setValor($valor);
$Produtos->update($idproduto);
}
endif;
?>
<form method='post' action="" style="margin-top: 20%">
<label for='nomeproduto'> Nome:</label>
<input type="text" name="nomeproduto" value="<?php echo $nomeproduto;?>"/>
<label for='valor'> Valor: </label>
<input type="Text" name="valor"value="<?php echo $valor;?>"/>
<input type="hidden" name="idproduto"value="<?php echo $idproduto;?>"/>
<div class="mb-3" style="margin: auto; margin-top: 2%">
<button name="alterarDados" type="submit" style="background: black; border-radius: 6px; padding: 7px; cursor: pointer; color: yellow; border: none; font-size: 16px btn-responsive">Alterar dados</button>
<a href=ListarProdutos.php style="background: black; border-radius: 6px; padding: 9px; cursor: pointer; color: yellow; border: none; font-size: 16px btn-responsive">Listar produtos</a>
</div>
</form>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.1/dist/js/bootstrap.bundle.min.js" integrity="<KEY>" crossorigin="anonymous"></script>
</body>
</html><file_sep><?php
error_reporting(E_ALL);
ini_set("display_errors", 1);
require_once 'Produtos.php';
?>
<!DOCTYPE HTML>
<html lang="pt-BR">
<head>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- Bootstrap CSS -->
<style rel="styleheet">
@import url("style.css");
</style>
<link href="css/bootstrap.min.css" rel="stylesheet">
<title>Cadastrar produto - WEB I</title>
</head>
<body class="imagemcadproduto">
<?php
$Produtos = new Produtos;
if(isset($_POST['cadastrar'])):
$nomeproduto = $_POST['nomeproduto'];
$valor = $_POST['valor'];
$Produtos->setNome($nomeproduto);
$Produtos->setValor($valor);
if($Produtos->insert()){
echo "Produto ". $nomeproduto. " inserido com sucesso";
}
endif;
?>
<div class="container">
<div class="row">
<div class="col">
<form method='post' action="" style="margin: auto; margin-top: 20%">
<div class="mb-3">
<label for='Nome'> Nome:</label>
<input type="text" name="nomeproduto" class="form-control"/>
</div>
<div class="mb-3">
<label for='valor'> Valor: </label>
<input type="text" name="valor" class="form-control"/>
</div>
<div class="mb-3" style="margin: auto; margin-top: 2%">
<input type="submit" name="cadastrar" class="btn btn-primary" style="color: yellow; background: black; border: 0"/>
<a class="btn btn-primary" href=menu.php style="color: yellow; background: black; border: 0">Voltar ao menu</a>
</div>
</form>
</div>
</div>
</div>
<!-- Optional JavaScript; choose one of the two! -->
<!-- Option 1: Bootstrap Bundle with Popper -->
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.1/dist/js/bootstrap.bundle.min.js" integrity="<KEY>" crossorigin="anonymous"></script>
<!-- Option 2: Separate Popper and Bootstrap JS -->
<!--
<script src="https://cdn.jsdelivr.net/npm/@popperjs/core@2.9.2/dist/umd/popper.min.js" integrity="<KEY>" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.1/dist/js/bootstrap.min.js" integrity="<KEY>" crossorigin="anonymous"></script>
-->
</body>
</html><file_sep><?php
require './config.php';
if (isset($_POST["tipo"])) {
if ($_POST["tipo"] == "cliente") {
$sql = "
SELECT * FROM cliente
";
$cliente = mysqli_query($conn, $sql);
while ($row = mysqli_fetch_array($cliente)) {
$saida[] = array(
'id' => $row["idcliente"],
'nome' => $row["nome"]
);
}
echo json_encode($saida);
}
elseif ($_POST["tipo"] == "produto") {
$sql = "
SELECT * FROM produto
";
$produto = mysqli_query($conn, $sql);
while ($row = mysqli_fetch_array($produto)) {
$saida[] = array(
'id' => $row["idproduto"],
'nome' => $row["nomeproduto"] . " - Em estoque: [" . $row["estoque"] . "] "
);
}
echo json_encode($saida);
}
}
?>
<file_sep><?php
##salvar como CrudAlunos.php
##arquivo que implementa a tabela e seus atributos, acessa os metodos get e set
require_once 'DB.php'; //inclui arquivo DB
abstract class CrudProdutos extends DB { //faz herança do arquivo DB
protected $tabela;
public $nomeproduto;
public $valor;
public function setNome($nomeproduto) {
$this->nomeproduto = $nomeproduto;
}
public function getNome() {
return $this->nomeproduto;
}
public function setValor($valor) {
$this->valor = $valor;
}
public function getValor() {
return $this->valor;
}
}
?><file_sep><?php
##salvar como CrudAlunos.php
##arquivo que implementa a tabela e seus atributos, acessa os metodos get e set
require_once 'DB.php'; //inclui arquivo DB
abstract class CrudClientes extends DB { //faz herança do arquivo DB
protected $tabela;
public $nome;
public $endereco;
public function setNome($nome) {
$this->nome = $nome;
}
public function getNome() {
return $this->nome;
}
public function setEndereco($endereco) {
$this->endereco = $endereco;
}
public function getEndereco() {
return $this->endereco;
}
}
?><file_sep><?php
##salvar como config.php
##arquivo que contem variaveis que serão usadas no arquivo de configuração do BD
define('HOST', 'localhost');
define('USER', 'root');
define('PASS', '');
define('BASE', 'atvweb');
$servername = "localhost";
$database = "atvweb";
$username = "root";
$password = "";
$conn = mysqli_connect($servername, $username, $password, $database);
if (!$conn) {
die("Falha na conexão: " . mysli_connect_error());
};
?>
<file_sep><div align="center">
<h1>Atv-Web<h1>
<h2>Atividade da disciplina Web I<h2>
<h2>Telas:</h2>
<p><img src="https://user-images.githubusercontent.com/81137205/131270457-976ae903-50e5-44b4-961c-68489bc463a0.jpeg" width="75%"/></p>
<p><img src="https://user-images.githubusercontent.com/81137205/131270371-5a310ff5-2e32-47e2-9b5a-651a2625d8a2.jpeg" width="75%"/></p>
<p><img src="https://user-images.githubusercontent.com/81137205/131270400-ef53de6f-5921-4ba0-b232-056731ee0420.jpeg" width="75%"/></p>
<p><img src="https://user-images.githubusercontent.com/81137205/131270408-4d960173-123e-47fe-b819-df77d3d744da.jpeg" width="75%"/></p>
<p><img src="https://user-images.githubusercontent.com/81137205/131270419-16724f59-15dc-4541-ab07-b731e5335efd.jpeg" width="75%"/></p>
<p><img src="https://user-images.githubusercontent.com/81137205/131270473-e3eecda4-a315-416e-a44c-71e7fc4d5acd.jpeg" width="75%"/></p>
<p><img src="https://user-images.githubusercontent.com/81137205/131270499-2fb10bea-2048-493c-968a-61e93f370fbd.jpeg" width="75%"/></p>
</div>
| 8ac04262c863f55ac52637d44fda2865def10250 | [
"Markdown",
"PHP"
] | 15 | PHP | cleitondcarmo/atv-web | 2ca7d696886ac7ae0db61673cf69b5658e98a336 | 221d52a6303dc26e215d6458c3d1d22765aa688e |
refs/heads/master | <repo_name>emmanueloghenetegaakponine/imageslideroriginal<file_sep>/app/src/main/java/com/example/imageslider/MainActivity.kt
package com.example.imageslider
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import com.denzcoskun.imageslider.models.SlideModel
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val imageList = ArrayList<SlideModel>()
imageList.add(SlideModel(""))
}
} | 9a4de9397383d076c28eeacab04f9b3e25d06a7e | [
"Kotlin"
] | 1 | Kotlin | emmanueloghenetegaakponine/imageslideroriginal | bacfa1db925fbb4f64b43e69a82ff12db4f3225a | c165165a1014e63f720dc5a22a102aceefb2df63 |
refs/heads/master | <repo_name>Lora-net/lr1110_driver<file_sep>/CHANGELOG.md
# LR1110 driver 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).
## [v7.0.0] 2021-12-06
### Added
* [radio] Support of LR-FHSS (see lr1110_lr_fhss.c and lr1110_lr_fhss.h)
* [system] `lr1110_system_calibrate_image_in_mhz()` function
### Removed
* [GNSS] `lr1110_gnss_set_xtal_error()` and `lr1110_gnss_set_xtal_error()` functions
## [v6.0.0] 2021-09-24
### Added
* [GNSS] `LR1110_GNSS_SCAN_MODE_3_SINGLE_SCAN_AND_5_FAST_SCANS` entry `lr1110_gnss_scan_mode_t`
### Changed
* [GNSS] `lr1110_gnss_set_scan_mode()` function does not take out parameter anymore and is now based on lr1110_hal_write()
* [GNSS] `lr1110_gnss_get_detected_satellites()` function returns also the doppler per satellite
### Removed
* [GNSS] `lr1110_gnss_scan_continuous()` function and `LR1110_GNSS_DOUBLE_SCAN_MODE` entry in lr1110_gnss_scan_mode_t
## [v5.0.1] 2021-07-19
### Added
* [bootloader] `lr1110_bootloader_clear_reset_status_info()` function
* [crypto] Functions now return a status
* [GNSS] `lr1110_gnss_get_result_destination()` function
* [GNSS] `lr1110_gnss_almanac_update()` function - replaces `lr1110_gnss_almanac_full_update()` and `lr1110_gnss_one_satellite_almanac_update()` functions
* [GNSS] `lr1110_gnss_compute_almanac_age` function
* [HAL] `lr1110_hal_direct_read()` function - replaces `lr1110_hal_write_read()` function and no longer requires bidirectional SPI
* [HAL] `LR1110_NOP` constant
* [system] `lr1110_system_clear_reset_status_info()` function
* [system] `lr1110_system_drive_dio_in_sleep_mode()` function
* [Wi-Fi] `LR1110_WIFI_SCAN_MODE_UNTIL_SSID` entry in `lr1110_wifi_mode_t`
* [Wi-Fi] `lr1110_wifi_is_well_formed_utf8_byte_sequence()` function
### Changed
* [LICENSE] Revised BSD License changed to the Clear BSD License
* [GNSS] `LR1110_GNSS_ERROR_UPDATE_TIME_DIFFERENCE_OVER_1_MONTH` is renamed `LR1110_GNSS_ERROR_ALMANAC_UPDATE_NOT_ALLOWED` in `lr1110_gnss_error_code_t`
* [GNSS] `lr1110_gnss_parse_context_status_buffer()` returns a `lr1110_status_t` value
* [system] `lr1110_system_get_status()` function implementation uses `lr1110_hal_direct_read()` function and no longer requires bidirectional SPI
* [system] `lr1110_bootloader_get_status()` function implementation uses `lr1110_hal_direct_read()` function and no longer requires bidirectional SPI
* [system] `lr1110_system_get_irq_status()` function - has a faster implementation based on the `lr1110_system_get_status()` function
### Fixed
* [GNSS] Global almanac CRC endianness `lr1110_gnss_parse_context_status_buffer()`
* [GNSS] `lr1110_gnss_parse_context_status_buffer()` takes into account the message header
* [GNSS] Typo in `LR1110_GNSS_ALMANAC_REAC_RBUFFER_LENGTH` - now `LR1110_GNSS_ALMANAC_READ_RBUFFER_LENGTH`
### Removed
* [GNSS] `lr1110_gnss_get_almanac_crc()` - Almanac CRC can be read thanks to `lr1110_gnss_get_context_status()`
* [GNSS] `lr1110_gnss_almanac_full_update()` and `lr1110_gnss_one_satellite_almanac_update()` functions - merged in `lr1110_gnss_almanac_update()` function
* [HAL] `lr1110_hal_write_read()` function - replaced by `lr1110_hal_direct_read()` function
* [regmem] `lr1110_regmem_write_auxreg32()`and `lr1110_regmem_read_auxreg32()` functions
* [Wi-Fi] `lr1110_wifi_cfg_hardware_debarker()` function
## [v4.0.0] 2021-04-06
### Added
* [bootloader] `lr1110_bootloader_get_status` function
* [bootloader] `lr1110_bootloader_irq_mask_t` type definition
* [bootloader] `lr1110_bootloader_chip_modes_t` type definition
* [bootloader] `lr1110_bootloader_reset_status_t` type definition
* [bootloader] `lr1110_bootloader_command_status_t` type definition
* [bootloader] `lr1110_bootloader_stat1_t` type definition
* [bootloader] `lr1110_bootloader_stat2_t` type definition
* [timings] Add the functions to compute the radio timings
* [system] Add function `lr1110_system_enable_spi_crc` to enable or disable the CRC on SPI communication
* [HAL] Add the CRC calculation for SPI
### Fixed
* [GNSS] Fix typo: `lr1110_gnss_almanac_single_satellite_update_bytestram_t` to `lr1110_gnss_almanac_single_satellite_update_bytestream_t`
* [GNSS] Fix size of context status
### Changed
* [Wi-Fi] Added field `current_channel` to `lr1110_wifi_extended_full_result_t`
### Removed
* [bootloader] `lr1110_bootloader_get_hash` function
* [bootloader] `lr1110_bootloader_write_flash` function
* [bootloader] `lr1110_bootloader_write_flash_full` function
* [bootloader] `lr1110_bootloader_erase_page` function
## [v3.0.0] 2020-10-12
### Added
* [bootloader] `lr1110_bootloader_read_chip_eui` function
* [bootloader] `lr1110_bootloader_read_join_eui` function
* [bootloader] `LR1110_BL_CHIP_EUI_LENGTH` constant
* [bootloader] `LR1110_BL_JOIN_EUI_LENGTH` constant
* [bootloader] `lr1110_bootloader_chip_eui_t` type definition
* [bootloader] `lr1110_bootloader_join_eui_t` type definition
* [GNSS] `lr1110_gnss_get_context_status` function
* [GNSS] `lr1110_gnss_parse_context_status_buffer` function
* [GNSS] `LR1110_GNSS_CONTEXT_STATUS_LENGTH` constant
* [GNSS] `lr1110_gnss_error_code_t` type definition
* [GNSS] `lr1110_gnss_freq_search_space_t` type definition
* [GNSS] `lr1110_gnss_context_status_bytestream_t` type definition
* [GNSS] `lr1110_gnss_context_status_t` type definition
* [radio] `lr1110_radio_set_rx_with_timeout_in_rtc_step` and `lr1110_radio_set_tx_with_timeout_in_rtc_step` functions
* [radio] `lr1110_radio_set_rx_duty_cycle_with_timings_in_rtc_step` function
* [radio] `lr1110_radio_convert_time_in_ms_to_rtc_step` function
* [system] `lr1110_system_wakeup` function
* [system] `lr1110_system_read_pin_custom_eui` function
* [system] `reset_status` field to `lr1110_system_stat2_t`
* [Wi-Fi] `lr1110_wifi_scan_time_limit` function
* [Wi-Fi] `lr1110_wifi_search_country_code_time_limit` function
* [Wi-Fi] `lr1110_wifi_read_extended_full_results` function
* [Wi-Fi] `LR1110_WIFI_CHANNEL_*_POS` and `LR1110_WIFI_CHANNEL_*_MASK` constants
* [Wi-Fi] `LR1110_WIFI_SCAN_MODE_FULL_BEACON` entry in `lr1110_wifi_mode_t`
* [Wi-Fi] `lr1110_wifi_extended_full_result_t` type definition
* [Wi-Fi] `LR1110_WIFI_RESULT_FORMAT_EXTENDED_FULL` entry in `lr1110_wifi_result_format_t`
### Changed
* [crypto] `LR1110_CRYPTO_COMPUTE_AES_CMAC_CMD_LENGTH` is now equal to ( 2 + 1 + 272 )
* [GNSS] `LR1110_GNSS_FULL_ALMANAC_UPDATE_PACKET_LENGTH` is renamed `LR1110_GNSS_FULL_ALMANAC_UPDATE_PKT_LENGTH`
* [GNSS] `lr1110_gnss_scan_autonomous` takes also `effort_mode` as input parameter
* [radio] Implementation of time-on-air computation for LoRa modulation
* [radio] `lr1110_radio_set_lora_sync_word` takes a sync word as parameter instead of a network type
* [radio] `lr1110_radio_set_rx` and `lr1110_radio_set_tx` take a timeout parameter in millisecond instead of RTC step
* [radio] `lr1110_radio_set_rx_duty_cycle` takes a timeout parameter in millisecond instead of RTC step
* [radio] `LR1110_RADIO_PACKET_NONE` is renamed `LR1110_RADIO_PKT_NONE`
* [radio] `LR1110_RADIO_PA_REG_SUPPLY_DCDC` is renamed `LR1110_RADIO_PA_REG_SUPPLY_VREG`
* [radio] `lr1110_radio_pa_regulator_supply_t` is renamed `lr1110_radio_pa_reg_supply_t`
* [radio] `*_packet_*` is renamed `*_pkt_*` in `lr1110_radio_pkt_status_lora_t`
* [radio] `nb_packet_falsesync` is renamed `nb_pkt_falsesync` in `lr1110_radio_stats_lora_t`
* [Wi-Fi] `lr1110_extract_channel_info` is renamed `lr1110_wifi_parse_channel_info`
* [Wi-Fi] `lr1110_extract_channel_from_info_byte` is renamed `lr1110_wifi_extract_channel_from_info_byte`
* [Wi-Fi] `lr1110_extract_frame_type_info` is renamed `lr1110_wifi_parse_frame_type_info`
* [Wi-Fi] `lr1110_extract_data_rate_info` is renamed `lr1110_wifi_parse_data_rate_info`
* [Wi-Fi] `lr1110_wifi_n_results_max_per_chunk` is renamed `lr1110_wifi_get_nb_results_max_per_chunk`
* [Wi-Fi] `lr1110_extract_signal_type_from_data_rate_info` is renamed `lr1110_wifi_extract_signal_type_from_data_rate_info`
* [Wi-Fi] `LR1110_WIFI_ORIGIN_PACKET` is renamed `LR1110_WIFI_ORIGIN_UNKNWON`
* [Wi-Fi] `LR1110_WIFI_SCAN_MODE_BEACON_AND_PACKET` is renamed `LR1110_WIFI_SCAN_MODE_BEACON_AND_PKT`
### Fixed
* [all] Harmonized doxygen markups
* [all] Harmonized license header
* [all] Removed extraneous underscore in constants used for multiple inclusion protection
* [GNSS] Inversion of `LR1110_GNSS_BIT_CHANGE_MASK` and `LR1110_GNSS_IRQ_PSEUDO_RANGE_MASK` definitions
* [radio] Power amplifier ramp time values in lr1110_radio_ramp_time_t
* [system] `chip_mode` read from `stat2` value
## [v2.0.1] 2020-05-04
### Fixed
* [version] Enable c linkage driver version related functions
## [v2.0.0] 2020-04-27
### Added
* [all] All functions declared in .h files now return a status.
* [common] `lr1110_status_t` type definition
* [bootloader] `lr1110_bootloader_fill_cbuffer_opcode_offset_flash` static function
* [bootloader] `lr1110_bootloader_fill_cdata_flash` static function
* [bootloader] `lr1110_bootloader_fill_cbuffer_cdata_flash` static function
* [regmem] `lr1110_regmem_fill_cbuffer_opcode_address` static function
* [regmem] `lr1110_regmem_fill_cbuffer_opcode_address_length` static function
* [regmem] `lr1110_regmem_fill_cdata` static function
* [regmem] `lr1110_regmem_fill_cbuffer_cdata_opcode_address_data` static function
* [regmem] `lr1110_regmem_fill_out_buffer_from_raw_buffer` static function
* [system] `LR1110_SYSTEM_VERSION_LENGTH` constant
* [system] `lr1110_system_cal_mask_t` type definition
* [system] `lr1110_system_irq_mask_t` type definition
* [system] `lr1110_system_get_and_clear_irq_status` function
* [system] `lr1110_system_get_irq_status` function
* [crypto] `lr1110_crypto_fill_cbuffer_opcode_key_data` static function
* [GNSS] `lr1110_gnss_uint8_to_uint32` static function
### Changed
* [bootloader] `lr1110_bootloader_version_t` has now 3 fields: hardware, type, firmware
* [bootloader] `lr1110_bootloader_get_version` fills the updated `lr1110_bootloader_version_t` structure
* [system] `LR1110_SYSTEM_IRQ_NONE_MASK` is renamed `LR1110_SYSTEM_IRQ_NONE`
* [system] `LR1110_SYSTEM_IRQ_TXDONE_MASK` is renamed `LR1110_SYSTEM_IRQ_TX_DONE`
* [system] `LR1110_SYSTEM_IRQ_RXDONE_MASK` is renamed `LR1110_SYSTEM_IRQ_RX_DONE`
* [system] `LR1110_SYSTEM_IRQ_PREAMBLEDETECTED_MASK` is renamed `LR1110_SYSTEM_IRQ_PREAMBLE_DETECTED`
* [system] `LR1110_SYSTEM_IRQ_SYNCWORD_HEADERVALID_MASK` is renamed `LR1110_SYSTEM_IRQ_SYNC_WORD_HEADER_VALID`
* [system] `LR1110_SYSTEM_IRQ_HEADERERR_MASK` is renamed `LR1110_SYSTEM_IRQ_HEADER_ERROR`
* [system] `LR1110_SYSTEM_IRQ_CRCERR_MASK` is renamed `LR1110_SYSTEM_IRQ_CRC_ERROR`
* [system] `LR1110_SYSTEM_IRQ_CADDONE_MASK` is renamed `LR1110_SYSTEM_IRQ_CAD_DONE`
* [system] `LR1110_SYSTEM_IRQ_CADDETECTED_MASK` is renamed `LR1110_SYSTEM_IRQ_CAD_DETECTED`
* [system] `LR1110_SYSTEM_IRQ_TIMEOUT_MASK` is renamed `LR1110_SYSTEM_IRQ_TIMEOUT`
* [system] `LR1110_SYSTEM_IRQ_GNSSSCANDONE_MASK` is renamed `LR1110_SYSTEM_IRQ_GNSS_SCAN_DONE`
* [system] `LR1110_SYSTEM_IRQ_WIFISCANDONE_MASK` is renamed `LR1110_SYSTEM_IRQ_WIFI_SCAN_DONE`
* [system] `LR1110_SYSTEM_IRQ_EOL_MASK` is renamed `LR1110_SYSTEM_IRQ_EOL`
* [system] `LR1110_SYSTEM_IRQ_CMDERR_MASK` is renamed `LR1110_SYSTEM_IRQ_CMD_ERROR`
* [system] `LR1110_SYSTEM_IRQ_ERR_MASK` is renamed `LR1110_SYSTEM_IRQ_ERROR`
* [system] `LR1110_SYSTEM_IRQ_FSK_LENGTH_ERROR_MASK` is renamed `LR1110_SYSTEM_IRQ_FSK_LEN_ERROR`
* [system] `LR1110_SYSTEM_IRQ_FSK_ADDRESS_ERROR_MASK` is renamed `LR1110_SYSTEM_IRQ_FSK_ADDR_ERROR`
* [system] `LR1110_SYSTEM_CALIBRATE_*_MASK` are renamed `LR1110_SYSTEM_CALIB_*_MASK`
* [system] `lr1110_system_chip_mode_t` is renamed `lr1110_system_chip_modes_t`
* [system] In `lr1110_system_chip_modes_t`, `LR1110_SYSTEM_CHIP_MODE_RC` is renamed `LR1110_SYSTEM_CHIP_MODE_STBY_RC`
* [system] In `lr1110_system_chip_modes_t`, `LR1110_SYSTEM_CHIP_MODE_XOSC` is renamed `LR1110_SYSTEM_CHIP_MODE_STBY_XOSC`
* [system] `lr1110_system_lfclk_config_t` is renamed `lr1110_system_lfclk_cfg_t`
* [system] `lr1110_regmodes_t` is renamed `lr1110_system_reg_mode_t`
* [system] `LR1110_SYSTEM_REGMODE_NO_DCDC` is renamed `LR1110_SYSTEM_REG_MODE_LDO`
* [system] `LR1110_SYSTEM_REGMODE_DCDC_CONVERTER` is renamed `LR1110_SYSTEM_REG_MODE_DCDC`
* [system] `lr1110_system_rfswitch_config_t` is renamed `lr1110_system_rfswitch_cfg_t`
* [system] `lr1110_system_standby_config_t` is renamed `lr1110_system_standby_cfg_t`
* [system] `LR1110_SYSTEM_STDBY_CONFIG_*` are renamed `LR1110_SYSTEM_STANDBY_CFG_*`
* [system] `LR1110_SYSTEM_TCXO_SUPPLY_VOLTAGE_*V` are renamed `LR1110_SYSTEM_TCXO_CTRL_*V`
* [system] `lr1110_system_sleep_config_t` is renamed `lr1110_system_sleep_cfg_t`
* [system] `lr1110_system_set_regmode` is renamed `lr1110_system_set_reg_mode`
* [system] `lr1110_system_config_lfclk` is renamed `lr1110_system_cfg_lfclk`
* [system] `lr1110_system_clear_irq` is renamed `lr1110_system_clear_irq_status`
* [crypto] `lr1110_crypto_derive_and_store_key` is renamed `lr1110_crypto_derive_key`
* [crypto] `LR1110_CRYPTO_DERIVE_AND_STORE_KEY_OC` is renamed `LR1110_CRYPTO_DERIVE_KEY_OC`
* [crypto] `LR1110_CRYPTO_DERIVE_AND_STORE_KEY_CMD_LENGTH` is renamed `LR1110_CRYPTO_DERIVE_KEY_CMD_LENGTH`
* [radio] `lr1110_radio_rx_tx_fallback_mode_t` is renamed `lr1110_radio_fallback_modes_t`
* [radio] `LR1110_RADIO_RX_TX_FALLBACK_MODE_*` are renamed `LR1110_RADIO_FALLBACK_*`
* [radio] `LR1110_RADIO_RAMP_TIME_*` are renamed `LR1110_RADIO_RAMP_*`
* [radio] `LR1110_RADIO_LORA_BW*` are renamed `LR1110_RADIO_LORA_BW_*`
* [radio] `LR1110_RADIO_LORA_CRXY_LI` are renamed `LR1110_RADIO_LORA_CR_LI_X_Y`
* [radio] `LR1110_RADIO_LORA_CRXY` are renamed `LR1110_RADIO_LORA_CR_X_Y`
* [radio] `LR1110_RADIO_MODE_STANDBY*` are renamed `LR1110_RADIO_MODE_STANDBY_*`
* [radio] `LR1110_RADIO_GFSK_CRC_XBYTE` are renamed `LR1110_RADIO_GFSK_CRC_X_BYTE`
* [radio] `LR1110_RADIO_GFSK_CRC_XBYTES` are renamed `LR1110_RADIO_GFSK_CRC_X_BYTES`
* [radio] `LR1110_RADIO_GFSK_CRC_XBYTE_INV` are renamed `LR1110_RADIO_GFSK_CRC_X_BYTE_INV`
* [radio] `LR1110_RADIO_GFSK_CRC_XBYTES_INV` are renamed `LR1110_RADIO_GFSK_CRC_X_BYTES_INV`
* [radio] `LR1110_RADIO_GFSK_DCFREE_*` are renamed `LR1110_RADIO_GFSK_DC_FREE_*`
* [radio] `lr1110_radio_gfsk_header_type_t` is renamed `lr1110_radio_gfsk_pkt_len_modes_t`
* [radio] `LR1110_RADIO_GFSK_HEADER_TYPE_IMPLICIT` is renamed `LR1110_RADIO_GFSK_PKT_FIX_LEN`
* [radio] `LR1110_RADIO_GFSK_HEADER_TYPE_EXPLICIT` is renamed `LR1110_RADIO_GFSK_PKT_VAR_LEN`
* [radio] `lr1110_radio_gfsk_preamble_detect_length_t` is renamed `lr1110_radio_gfsk_preamble_detector_t`
* [radio] `LR1110_RADIO_GFSK_PREAMBLE_DETECTOR_LENGTH_*` are renamed `LR1110_RADIO_GFSK_PREAMBLE_DETECTOR_*`
* [radio] `lr1110_radio_lora_header_type_t` is renamed `lr1110_radio_lora_pkt_len_modes_t`
* [radio] `LR1110_RADIO_LORA_HEADER_*` are renamed `LR1110_RADIO_LORA_PKT_*`
* [radio] `lr1110_radio_packet_types_t` is renamed `lr1110_radio_pkt_type_t`
* [radio] `LR1110_RADIO_PACKET_*` are renamed `LR1110_RADIO_PKT_TYPE_*`
* [radio] `lr1110_radio_gfsk_rx_bw_t` is renamed `lr1110_radio_gfsk_bw_t`
* [radio] `LR1110_RADIO_GFSK_RX_BW_*` are renamed `LR1110_RADIO_GFSK_BW_*`
* [radio] `lr1110_radio_pulse_shape_t` is renamed `lr1110_radio_gfsk_pulse_shape_t`
* [radio] `LR1110_RADIO_PULSESHAPE_*` are renamed `LR1110_RADIO_GFSK_PULSE_SHAPE_*`
* [radio] In `lr1110_radio_cad_params_t`, `symbol_num` is renamed `cad_symb_nb`
* [radio] In `lr1110_radio_cad_params_t`, `det_peak` is renamed `cad_detect_peak`
* [radio] In `lr1110_radio_cad_params_t`, `det_min` is renamed `cad_detect_min`
* [radio] In `lr1110_radio_cad_params_t`, `exit_mode` is renamed `cad_exit_mode`
* [radio] In `lr1110_radio_cad_params_t`, `timeout` is renamed `cad_timeout`
* [radio] `lr1110_radio_packet_status_gfsk_t` is renamed `lr1110_radio_pkt_status_gfsk_t`
* [radio] In `lr1110_radio_pkt_status_gfsk_t`, `rx_length_in_bytes` is renamed `rx_len_in_bytes`
* [radio] `lr1110_radio_packet_status_lora_t` is renamed `lr1110_radio_pkt_status_lora_t`
* [radio] `lr1110_radio_rxbuffer_status_t` is renamed `lr1110_radio_rx_buffer_status_t`
* [radio] In `lr1110_radio_rx_buffer_status_t`, `rx_payload_length` is renamed `pld_len_in_bytes`
* [radio] In `lr1110_radio_rx_buffer_status_t`, `rx_start_buffer_pointer` is renamed `buffer_start_pointer`
* [radio] In `lr1110_radio_stats_gfsk_t`, `nb_packet_*` are renamed `nb_pkt_*`
* [radio] In `lr1110_radio_stats_lora_t`, `nb_packet_received` is renamed `nb_pkt_received`
* [radio] In `lr1110_radio_stats_lora_t`, `nb_packet_error_crc` is renamed `nb_pkt_error_crc`
* [radio] In `lr1110_radio_stats_lora_t`, `nb_packet_error_header` is renamed `nb_pkt_header_error`
* [radio] `lr1110_radio_modulation_param_*_t` are renamed `lr1110_radio_mod_params_*_t`
* [radio] In `lr1110_radio_mod_params_gfsk_t`, `bitrate` is renamed `br_in_bps`
* [radio] In `lr1110_radio_mod_params_gfsk_t`, `bandwidth` is renamed `bw_dsb_param`
* [radio] In `lr1110_radio_mod_params_gfsk_t`, `fdev` is renamed `fdev_in_hz`
* [radio] In `lr1110_radio_mod_params_lora_t`, `spreading_factor` is renamed `sf`
* [radio] In `lr1110_radio_mod_params_lora_t`, `coding_rate` is renamed `cr`
* [radio] In `lr1110_radio_mod_params_lora_t`, `ppm_offset` is renamed `ldro`
* [radio] `lr1110_radio_packet_param_*_t` are renamed `lr1110_radio_pkt_params_*_t`
* [radio] In `lr1110_radio_pkt_params_gfsk_t`, `preamble_length_tx_in_bit` is renamed `preamble_len_in_bits`
* [radio] In `lr1110_radio_pkt_params_gfsk_t`, `preamble_detect` is renamed `preamble_detector`
* [radio] In `lr1110_radio_pkt_params_gfsk_t`, `sync_word_length_in_bit` is renamed `sync_word_len_in_bits`
* [radio] In `lr1110_radio_pkt_params_gfsk_t`, `payload_length_in_byte` is renamed `pld_len_in_bytes`
* [radio] In `lr1110_radio_pkt_params_lora_t`, `preamble_length_in_symb` is renamed `preamble_len_in_symb`
* [radio] In `lr1110_radio_pkt_params_lora_t`, `payload_length_in_byte` is renamed `pld_len_in_bytes`
* [radio] `lr1110_radio_pa_config_t` are renamed `lr1110_radio_pa_cfg_t`
* [Wi-Fi] `lr1110_wifi_configure_hardware_debarker` is renamed `lr1110_wifi_cfg_hardware_debarker`
### Fixed
* [system] Enable c linkage for system-related functions
### Removed
* [system] `LR1110_SYSTEM_IRQ_FHSS_MASK` constant
* [system] `LR1110_SYSTEM_IRQ_INTERPACKET1_MASK` constant
* [system] `LR1110_SYSTEM_IRQ_INTERPACKET2_MASK` constant
* [system] `LR1110_SYSTEM_IRQ_RNGREQVLD_MASK` constant
* [system] `LR1110_SYSTEM_IRQ_RNGREQDISC_MASK` constant
* [system] `LR1110_SYSTEM_IRQ_RNGRESPDONE_MASK` constant
* [system] `LR1110_SYSTEM_IRQ_RNGEXCHVLD_MASK` constant
* [system] `LR1110_SYSTEM_IRQ_RNGTIMEOUT_MASK` constant
## [v1.0.0] 2020-03-18
### Added
* [all] Initial version
<file_sep>/README.md
# LR1110_driver project
This project has moved to [LR11xx driver](https://github.com/Lora-net/SWDR001) project.
The source code remains available but will not be maintained.
This package proposes an implementation in C of the driver for **LR1110** radio component.
## Components
The driver is split in several components:
- Bootloader
- Register / memory access
- System configuration
- Radio
- Wi-Fi Passive Scanning
- GNSS Scan Scanning
- Crypto engine
### Bootloader
This component is used to update the firmware.
### Register / memory access
This component is used to read / write data from registers or internal memory.
### System configuration
This component is used to interact with system-wide parameters like clock sources, integrated RF switches, etc.
### Radio
This component is used to send / receive data through the different modems (LoRa and GFSK) or perform a LoRa CAD (Channel Activity Detection). Parameters like power amplifier selection, output power and fallback modes are also accessible through this component.
### Wi-Fi Passive Scanning
This component is used to configure and initiate the passive scanning of the Wi-Fi signals that can be shared to request a geolocation.
### GNSS Scanning
This component is used to configure and initiate the acquisition of GNSS signals that can be shared to request a geolocation.
### Crypto engine
This component is used to set and derive keys in the internal keychain and perform cryptographic operations with the integrated hardware accelerator.
## Structure
Each component is based on different files:
- lr1110_component.c: implementation of the functions related to component
- lr1110_component.h: declarations of the functions related to component
- lr1110_component_types.h: type definitions related to components
## HAL
The HAL (Hardware Abstraction Layer) is a collection of functions that the user shall implement to write platform-dependant calls to the host. The list of functions is the following:
- lr1110_hal_reset()
- lr1110_hal_wakeup()
- lr1110_hal_write()
- lr1110_hal_read()
- lr1110_hal_direct_read()
<file_sep>/src/lr1110_system.c
/*!
* @file lr1110_system.c
*
* @brief System driver implementation for LR1110
*
* The Clear BSD License
* Copyright Semtech Corporation 2021. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted (subject to the limitations in the disclaimer
* below) provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the Semtech corporation nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* NO EXPRESS OR IMPLIED LICENSES TO ANY PARTY'S PATENT RIGHTS ARE GRANTED BY
* THIS LICENSE. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
* CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT
* NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
* PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SEMTECH CORPORATION BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
/*
* -----------------------------------------------------------------------------
* --- DEPENDENCIES ------------------------------------------------------------
*/
#include <stdlib.h>
#include "lr1110_system.h"
#include "lr1110_hal.h"
/*
* -----------------------------------------------------------------------------
* --- PRIVATE MACROS-----------------------------------------------------------
*/
/*
* -----------------------------------------------------------------------------
* --- PRIVATE CONSTANTS -------------------------------------------------------
*/
#define LR1110_SYSTEM_GET_IRQ_STATUS_CMD_LENGTH ( 2 )
#define LR1110_SYSTEM_GET_VERSION_CMD_LENGTH ( 2 )
#define LR1110_SYSTEM_GET_ERRORS_CMD_LENGTH ( 2 )
#define LR1110_SYSTEM_CLEAR_ERRORS_CMD_LENGTH ( 2 )
#define LR1110_SYSTEM_CALIBRATE_CMD_LENGTH ( 2 + 1 )
#define LR1110_SYSTEM_SET_REGMODE_CMD_LENGTH ( 2 + 1 )
#define LR1110_SYSTEM_CALIBRATE_IMAGE_CMD_LENGTH ( 2 + 2 )
#define LR1110_SYSTEM_SET_DIO_AS_RF_SWITCH_CMD_LENGTH ( 2 + 8 )
#define LR1110_SYSTEM_SET_DIO_IRQ_PARAMS_CMD_LENGTH ( 2 + 8 )
#define LR1110_SYSTEM_CLEAR_IRQ_CMD_LENGTH ( 2 + 4 )
#define LR1110_SYSTEM_CFG_LFCLK_CMD_LENGTH ( 2 + 1 )
#define LR1110_SYSTEM_SET_TCXO_MODE_CMD_LENGTH ( 2 + 4 )
#define LR1110_SYSTEM_REBOOT_CMD_LENGTH ( 2 + 1 )
#define LR1110_SYSTEM_GET_VBAT_CMD_LENGTH ( 2 )
#define LR1110_SYSTEM_GET_TEMP_CMD_LENGTH ( 2 )
#define LR1110_SYSTEM_SET_SLEEP_CMD_LENGTH ( 2 + 5 )
#define LR1110_SYSTEM_SET_STANDBY_CMD_LENGTH ( 2 + 1 )
#define LR1110_SYSTEM_SET_FS_CMD_LENGTH ( 2 )
#define LR1110_SYSTEM_ERASE_INFOPAGE_CMD_LENGTH ( 2 + 1 )
#define LR1110_SYSTEM_WRITE_INFOPAGE_CMD_LENGTH ( 2 + 3 )
#define LR1110_SYSTEM_READ_INFOPAGE_CMD_LENGTH ( 2 + 4 )
#define LR1110_SYSTEM_READ_UID_CMD_LENGTH ( 2 )
#define LR1110_SYSTEM_READ_JOIN_EUI_CMD_LENGTH ( 2 )
#define LR1110_SYSTEM_READ_PIN_CMD_LENGTH ( 2 )
#define LR1110_SYSTEM_READ_PIN_CUSTOM_EUI_CMD_LENGTH ( LR1110_SYSTEM_READ_PIN_CMD_LENGTH + 17 )
#define LR1110_SYSTEM_GET_RANDOM_CMD_LENGTH ( 2 )
#define LR1110_SYSTEM_ENABLE_SPI_CRC_CMD_LENGTH ( 3 )
#define LR1110_SYSTEM_DRIVE_DIO_IN_SLEEP_MODE_CMD_LENGTH ( 3 )
#define LR1110_SYSTEM_GET_STATUS_DIRECT_READ_LENGTH ( 6 )
/*
* -----------------------------------------------------------------------------
* --- PRIVATE TYPES -----------------------------------------------------------
*/
/*!
* @brief Operating codes for system-related operations
*/
enum
{
LR1110_SYSTEM_GET_STATUS_OC = 0x0100,
LR1110_SYSTEM_GET_VERSION_OC = 0x0101,
LR1110_SYSTEM_GET_ERRORS_OC = 0x010D,
LR1110_SYSTEM_CLEAR_ERRORS_OC = 0x010E,
LR1110_SYSTEM_CALIBRATE_OC = 0x010F,
LR1110_SYSTEM_SET_REGMODE_OC = 0x0110,
LR1110_SYSTEM_CALIBRATE_IMAGE_OC = 0x0111,
LR1110_SYSTEM_SET_DIO_AS_RF_SWITCH_OC = 0x0112,
LR1110_SYSTEM_SET_DIOIRQPARAMS_OC = 0x0113,
LR1110_SYSTEM_CLEAR_IRQ_OC = 0x0114,
LR1110_SYSTEM_CFG_LFCLK_OC = 0x0116,
LR1110_SYSTEM_SET_TCXO_MODE_OC = 0x0117,
LR1110_SYSTEM_REBOOT_OC = 0x0118,
LR1110_SYSTEM_GET_VBAT_OC = 0x0119,
LR1110_SYSTEM_GET_TEMP_OC = 0x011A,
LR1110_SYSTEM_SET_SLEEP_OC = 0x011B,
LR1110_SYSTEM_SET_STANDBY_OC = 0x011C,
LR1110_SYSTEM_SET_FS_OC = 0x011D,
LR1110_SYSTEM_GET_RANDOM_OC = 0x0120,
LR1110_SYSTEM_ERASE_INFOPAGE_OC = 0x0121,
LR1110_SYSTEM_WRITE_INFOPAGE_OC = 0x0122,
LR1110_SYSTEM_READ_INFOPAGE_OC = 0x0123,
LR1110_SYSTEM_READ_UID_OC = 0x0125,
LR1110_SYSTEM_READ_JOIN_EUI_OC = 0x0126,
LR1110_SYSTEM_READ_PIN_OC = 0x0127,
LR1110_SYSTEM_ENABLE_SPI_CRC_OC = 0x0128,
LR1110_SYSTEM_DRIVE_DIO_IN_SLEEP_MODE_OC = 0x012A,
};
/*
* -----------------------------------------------------------------------------
* --- PRIVATE VARIABLES -------------------------------------------------------
*/
/*
* -----------------------------------------------------------------------------
* --- PRIVATE FUNCTIONS DECLARATION -------------------------------------------
*/
/*!
* @brief Fill stat1 structure with data from stat1_byte
*
* @param [in] stat1_byte stat1 byte
* @param [out] stat1 stat1 structure
*/
static void lr1110_system_convert_stat1_byte_to_enum( uint8_t stat1_byte, lr1110_system_stat1_t* stat1 );
/*!
* @brief Fill stat2 structure with data from stat2_byte
*
* @param [in] stat2_byte stat2 byte
* @param [out] stat2 stat2 structure
*/
static void lr1110_system_convert_stat2_byte_to_enum( uint8_t stat2_byte, lr1110_system_stat2_t* stat2 );
/*
* -----------------------------------------------------------------------------
* --- PUBLIC FUNCTIONS DEFINITION ---------------------------------------------
*/
lr1110_status_t lr1110_system_reset( const void* context )
{
return ( lr1110_status_t ) lr1110_hal_reset( context );
}
lr1110_status_t lr1110_system_get_status( const void* context, lr1110_system_stat1_t* stat1,
lr1110_system_stat2_t* stat2, lr1110_system_irq_mask_t* irq_status )
{
uint8_t data[LR1110_SYSTEM_GET_STATUS_DIRECT_READ_LENGTH];
lr1110_status_t status;
status = ( lr1110_status_t ) lr1110_hal_direct_read( context, data, LR1110_SYSTEM_GET_STATUS_DIRECT_READ_LENGTH );
if( status == LR1110_STATUS_OK )
{
lr1110_system_convert_stat1_byte_to_enum( data[0], stat1 );
lr1110_system_convert_stat2_byte_to_enum( data[1], stat2 );
if( irq_status != NULL )
{
*irq_status = ( ( lr1110_system_irq_mask_t ) data[2] << 24 ) +
( ( lr1110_system_irq_mask_t ) data[3] << 16 ) +
( ( lr1110_system_irq_mask_t ) data[4] << 8 ) + ( ( lr1110_system_irq_mask_t ) data[5] << 0 );
}
}
return status;
}
lr1110_status_t lr1110_system_clear_reset_status_info( const void* context )
{
uint8_t cbuffer[2] = {
( uint8_t )( LR1110_SYSTEM_GET_STATUS_OC >> 8 ),
( uint8_t )( LR1110_SYSTEM_GET_STATUS_OC >> 0 ),
};
return ( lr1110_status_t ) lr1110_hal_write( context, cbuffer, sizeof( cbuffer ), 0, 0 );
}
lr1110_status_t lr1110_system_get_version( const void* context, lr1110_system_version_t* version )
{
const uint8_t cbuffer[LR1110_SYSTEM_GET_VERSION_CMD_LENGTH] = {
( uint8_t )( LR1110_SYSTEM_GET_VERSION_OC >> 8 ),
( uint8_t )( LR1110_SYSTEM_GET_VERSION_OC >> 0 ),
};
uint8_t rbuffer[LR1110_SYSTEM_VERSION_LENGTH] = { 0x00 };
const lr1110_status_t status = ( lr1110_status_t ) lr1110_hal_read(
context, cbuffer, LR1110_SYSTEM_GET_VERSION_CMD_LENGTH, rbuffer, LR1110_SYSTEM_VERSION_LENGTH );
if( status == LR1110_STATUS_OK )
{
version->hw = rbuffer[0];
version->type = rbuffer[1];
version->fw = ( ( uint16_t ) rbuffer[2] << 8 ) + ( uint16_t ) rbuffer[3];
}
return status;
}
lr1110_status_t lr1110_system_get_errors( const void* context, lr1110_system_errors_t* errors )
{
const uint8_t cbuffer[LR1110_SYSTEM_GET_ERRORS_CMD_LENGTH] = {
( uint8_t )( LR1110_SYSTEM_GET_ERRORS_OC >> 8 ),
( uint8_t )( LR1110_SYSTEM_GET_ERRORS_OC >> 0 ),
};
uint8_t rbuffer[sizeof( errors )] = { 0x00 };
const lr1110_status_t status = ( lr1110_status_t ) lr1110_hal_read(
context, cbuffer, LR1110_SYSTEM_GET_ERRORS_CMD_LENGTH, rbuffer, sizeof( *errors ) );
if( status == LR1110_STATUS_OK )
{
*errors = ( ( uint16_t ) rbuffer[0] << 8 ) + ( uint16_t ) rbuffer[1];
}
return status;
}
lr1110_status_t lr1110_system_clear_errors( const void* context )
{
const uint8_t cbuffer[LR1110_SYSTEM_CLEAR_ERRORS_CMD_LENGTH] = {
( uint8_t )( LR1110_SYSTEM_CLEAR_ERRORS_OC >> 8 ),
( uint8_t )( LR1110_SYSTEM_CLEAR_ERRORS_OC >> 0 ),
};
return ( lr1110_status_t ) lr1110_hal_write( context, cbuffer, LR1110_SYSTEM_CLEAR_ERRORS_CMD_LENGTH, 0, 0 );
}
lr1110_status_t lr1110_system_calibrate( const void* context, const uint8_t calib_param )
{
const uint8_t cbuffer[LR1110_SYSTEM_CALIBRATE_CMD_LENGTH] = {
( uint8_t )( LR1110_SYSTEM_CALIBRATE_OC >> 8 ),
( uint8_t )( LR1110_SYSTEM_CALIBRATE_OC >> 0 ),
calib_param,
};
return ( lr1110_status_t ) lr1110_hal_write( context, cbuffer, LR1110_SYSTEM_CALIBRATE_CMD_LENGTH, 0, 0 );
}
lr1110_status_t lr1110_system_set_reg_mode( const void* context, const lr1110_system_reg_mode_t reg_mode )
{
const uint8_t cbuffer[LR1110_SYSTEM_SET_REGMODE_CMD_LENGTH] = {
( uint8_t )( LR1110_SYSTEM_SET_REGMODE_OC >> 8 ),
( uint8_t )( LR1110_SYSTEM_SET_REGMODE_OC >> 0 ),
( uint8_t ) reg_mode,
};
return ( lr1110_status_t ) lr1110_hal_write( context, cbuffer, LR1110_SYSTEM_SET_REGMODE_CMD_LENGTH, 0, 0 );
}
lr1110_status_t lr1110_system_calibrate_image( const void* context, const uint8_t freq1, const uint8_t freq2 )
{
const uint8_t cbuffer[LR1110_SYSTEM_CALIBRATE_IMAGE_CMD_LENGTH] = {
( uint8_t )( LR1110_SYSTEM_CALIBRATE_IMAGE_OC >> 8 ),
( uint8_t )( LR1110_SYSTEM_CALIBRATE_IMAGE_OC >> 0 ),
freq1,
freq2,
};
return ( lr1110_status_t ) lr1110_hal_write( context, cbuffer, LR1110_SYSTEM_CALIBRATE_IMAGE_CMD_LENGTH, 0, 0 );
}
lr1110_status_t lr1110_system_calibrate_image_in_mhz( const void* context, const uint16_t freq1_in_mhz,
const uint16_t freq2_in_mhz )
{
// Perform a floor() to get a value for freq1 corresponding to a frequency lower than or equal to freq1_in_mhz
const uint8_t freq1 = freq1_in_mhz / LR1110_SYSTEM_IMAGE_CALIBRATION_STEP_IN_MHZ;
// Perform a ceil() to get a value for freq2 corresponding to a frequency higher than or equal to freq2_in_mhz
const uint8_t freq2 = ( freq2_in_mhz + LR1110_SYSTEM_IMAGE_CALIBRATION_STEP_IN_MHZ - 1 ) /
LR1110_SYSTEM_IMAGE_CALIBRATION_STEP_IN_MHZ;
return lr1110_system_calibrate_image( context, freq1, freq2 );
}
lr1110_status_t lr1110_system_set_dio_as_rf_switch( const void* context,
const lr1110_system_rfswitch_cfg_t* rf_switch_cfg )
{
const uint8_t cbuffer[LR1110_SYSTEM_SET_DIO_AS_RF_SWITCH_CMD_LENGTH] = {
( uint8_t )( LR1110_SYSTEM_SET_DIO_AS_RF_SWITCH_OC >> 8 ),
( uint8_t )( LR1110_SYSTEM_SET_DIO_AS_RF_SWITCH_OC >> 0 ),
rf_switch_cfg->enable,
rf_switch_cfg->standby,
rf_switch_cfg->rx,
rf_switch_cfg->tx,
rf_switch_cfg->tx_hp,
rf_switch_cfg->tx_hf,
rf_switch_cfg->gnss,
rf_switch_cfg->wifi,
};
return ( lr1110_status_t ) lr1110_hal_write( context, cbuffer, LR1110_SYSTEM_SET_DIO_AS_RF_SWITCH_CMD_LENGTH, 0,
0 );
}
lr1110_status_t lr1110_system_set_dio_irq_params( const void* context, const uint32_t irqs_to_enable_dio1,
const uint32_t irqs_to_enable_dio2 )
{
const uint8_t cbuffer[LR1110_SYSTEM_SET_DIO_IRQ_PARAMS_CMD_LENGTH] = {
( uint8_t )( LR1110_SYSTEM_SET_DIOIRQPARAMS_OC >> 8 ),
( uint8_t )( LR1110_SYSTEM_SET_DIOIRQPARAMS_OC >> 0 ),
( uint8_t )( irqs_to_enable_dio1 >> 24 ),
( uint8_t )( irqs_to_enable_dio1 >> 16 ),
( uint8_t )( irqs_to_enable_dio1 >> 8 ),
( uint8_t )( irqs_to_enable_dio1 >> 0 ),
( uint8_t )( irqs_to_enable_dio2 >> 24 ),
( uint8_t )( irqs_to_enable_dio2 >> 16 ),
( uint8_t )( irqs_to_enable_dio2 >> 8 ),
( uint8_t )( irqs_to_enable_dio2 >> 0 ),
};
return ( lr1110_status_t ) lr1110_hal_write( context, cbuffer, LR1110_SYSTEM_SET_DIO_IRQ_PARAMS_CMD_LENGTH, 0, 0 );
}
lr1110_status_t lr1110_system_clear_irq_status( const void* context, const lr1110_system_irq_mask_t irqs_to_clear )
{
const uint8_t cbuffer[LR1110_SYSTEM_CLEAR_IRQ_CMD_LENGTH] = {
( uint8_t )( LR1110_SYSTEM_CLEAR_IRQ_OC >> 8 ),
( uint8_t )( LR1110_SYSTEM_CLEAR_IRQ_OC >> 0 ),
( uint8_t )( irqs_to_clear >> 24 ),
( uint8_t )( irqs_to_clear >> 16 ),
( uint8_t )( irqs_to_clear >> 8 ),
( uint8_t )( irqs_to_clear >> 0 ),
};
return ( lr1110_status_t ) lr1110_hal_write( context, cbuffer, LR1110_SYSTEM_CLEAR_IRQ_CMD_LENGTH, 0, 0 );
}
lr1110_status_t lr1110_system_get_and_clear_irq_status( const void* context, lr1110_system_irq_mask_t* irq )
{
lr1110_system_irq_mask_t lr1110_irq_mask = LR1110_SYSTEM_IRQ_NONE;
lr1110_status_t status = lr1110_system_get_irq_status( context, &lr1110_irq_mask );
if( ( status == LR1110_STATUS_OK ) && ( lr1110_irq_mask != 0 ) )
{
status = lr1110_system_clear_irq_status( context, lr1110_irq_mask );
}
if( ( status == LR1110_STATUS_OK ) && ( irq != NULL ) )
{
*irq = lr1110_irq_mask;
}
return status;
}
lr1110_status_t lr1110_system_cfg_lfclk( const void* context, const lr1110_system_lfclk_cfg_t lfclock_cfg,
const bool wait_for_32k_ready )
{
const uint8_t cbuffer[LR1110_SYSTEM_CFG_LFCLK_CMD_LENGTH] = {
( uint8_t )( LR1110_SYSTEM_CFG_LFCLK_OC >> 8 ),
( uint8_t )( LR1110_SYSTEM_CFG_LFCLK_OC >> 0 ),
( uint8_t )( lfclock_cfg | ( wait_for_32k_ready << 2 ) ),
};
return ( lr1110_status_t ) lr1110_hal_write( context, cbuffer, LR1110_SYSTEM_CFG_LFCLK_CMD_LENGTH, 0, 0 );
}
lr1110_status_t lr1110_system_set_tcxo_mode( const void* context, const lr1110_system_tcxo_supply_voltage_t tune,
const uint32_t timeout )
{
const uint8_t cbuffer[LR1110_SYSTEM_SET_TCXO_MODE_CMD_LENGTH] = {
( uint8_t )( LR1110_SYSTEM_SET_TCXO_MODE_OC >> 8 ),
( uint8_t )( LR1110_SYSTEM_SET_TCXO_MODE_OC >> 0 ),
( uint8_t ) tune,
( uint8_t )( timeout >> 16 ),
( uint8_t )( timeout >> 8 ),
( uint8_t )( timeout >> 0 ),
};
return ( lr1110_status_t ) lr1110_hal_write( context, cbuffer, LR1110_SYSTEM_SET_TCXO_MODE_CMD_LENGTH, 0, 0 );
}
lr1110_status_t lr1110_system_reboot( const void* context, const bool stay_in_bootloader )
{
const uint8_t cbuffer[LR1110_SYSTEM_REBOOT_CMD_LENGTH] = {
( uint8_t )( LR1110_SYSTEM_REBOOT_OC >> 8 ),
( uint8_t )( LR1110_SYSTEM_REBOOT_OC >> 0 ),
( stay_in_bootloader == true ) ? 0x03 : 0x00,
};
return ( lr1110_status_t ) lr1110_hal_write( context, cbuffer, LR1110_SYSTEM_REBOOT_CMD_LENGTH, 0, 0 );
}
lr1110_status_t lr1110_system_get_vbat( const void* context, uint8_t* vbat )
{
const uint8_t cbuffer[LR1110_SYSTEM_GET_VBAT_CMD_LENGTH] = {
( uint8_t )( LR1110_SYSTEM_GET_VBAT_OC >> 8 ),
( uint8_t )( LR1110_SYSTEM_GET_VBAT_OC >> 0 ),
};
return ( lr1110_status_t ) lr1110_hal_read( context, cbuffer, LR1110_SYSTEM_GET_VBAT_CMD_LENGTH, vbat,
sizeof( *vbat ) );
}
lr1110_status_t lr1110_system_get_temp( const void* context, uint16_t* temp )
{
const uint8_t cbuffer[LR1110_SYSTEM_GET_TEMP_CMD_LENGTH] = {
( uint8_t )( LR1110_SYSTEM_GET_TEMP_OC >> 8 ),
( uint8_t )( LR1110_SYSTEM_GET_TEMP_OC >> 0 ),
};
uint8_t rbuffer[sizeof( uint16_t )] = { 0x00 };
const lr1110_status_t status = ( lr1110_status_t ) lr1110_hal_read(
context, cbuffer, LR1110_SYSTEM_GET_TEMP_CMD_LENGTH, rbuffer, sizeof( uint16_t ) );
if( status == LR1110_STATUS_OK )
{
*temp = ( ( uint16_t ) rbuffer[0] << 8 ) + ( uint16_t ) rbuffer[1];
}
return status;
}
lr1110_status_t lr1110_system_set_sleep( const void* context, const lr1110_system_sleep_cfg_t sleep_cfg,
const uint32_t sleep_time )
{
const uint8_t cbuffer[LR1110_SYSTEM_SET_SLEEP_CMD_LENGTH] = {
( uint8_t )( LR1110_SYSTEM_SET_SLEEP_OC >> 8 ),
( uint8_t )( LR1110_SYSTEM_SET_SLEEP_OC >> 0 ),
( sleep_cfg.is_rtc_timeout << 1 ) + sleep_cfg.is_warm_start,
( uint8_t )( sleep_time >> 24 ),
( uint8_t )( sleep_time >> 16 ),
( uint8_t )( sleep_time >> 8 ),
( uint8_t )( sleep_time >> 0 ),
};
return ( lr1110_status_t ) lr1110_hal_write( context, cbuffer, LR1110_SYSTEM_SET_SLEEP_CMD_LENGTH, 0, 0 );
}
lr1110_status_t lr1110_system_set_standby( const void* context, const lr1110_system_standby_cfg_t standby_cfg )
{
const uint8_t cbuffer[LR1110_SYSTEM_SET_STANDBY_CMD_LENGTH] = {
( uint8_t )( LR1110_SYSTEM_SET_STANDBY_OC >> 8 ),
( uint8_t )( LR1110_SYSTEM_SET_STANDBY_OC >> 0 ),
( uint8_t ) standby_cfg,
};
return ( lr1110_status_t ) lr1110_hal_write( context, cbuffer, LR1110_SYSTEM_SET_STANDBY_CMD_LENGTH, 0, 0 );
}
lr1110_status_t lr1110_system_wakeup( const void* context )
{
return ( lr1110_status_t ) lr1110_hal_wakeup( context );
}
lr1110_status_t lr1110_system_set_fs( const void* context )
{
const uint8_t cbuffer[LR1110_SYSTEM_SET_FS_CMD_LENGTH] = {
( uint8_t )( LR1110_SYSTEM_SET_FS_OC >> 8 ),
( uint8_t )( LR1110_SYSTEM_SET_FS_OC >> 0 ),
};
return ( lr1110_status_t ) lr1110_hal_write( context, cbuffer, LR1110_SYSTEM_SET_FS_CMD_LENGTH, 0, 0 );
}
lr1110_status_t lr1110_system_erase_infopage( const void* context, const lr1110_system_infopage_id_t infopage_id )
{
const uint8_t cbuffer[LR1110_SYSTEM_ERASE_INFOPAGE_CMD_LENGTH] = {
( uint8_t )( LR1110_SYSTEM_ERASE_INFOPAGE_OC >> 8 ),
( uint8_t )( LR1110_SYSTEM_ERASE_INFOPAGE_OC >> 0 ),
( uint8_t ) infopage_id,
};
return ( lr1110_status_t ) lr1110_hal_write( context, cbuffer, LR1110_SYSTEM_ERASE_INFOPAGE_CMD_LENGTH, 0, 0 );
}
lr1110_status_t lr1110_system_write_infopage( const void* context, const lr1110_system_infopage_id_t infopage_id,
const uint16_t address, const uint32_t* data, const uint8_t length )
{
const uint8_t cbuffer[LR1110_SYSTEM_WRITE_INFOPAGE_CMD_LENGTH] = {
( uint8_t )( LR1110_SYSTEM_WRITE_INFOPAGE_OC >> 8 ),
( uint8_t )( LR1110_SYSTEM_WRITE_INFOPAGE_OC >> 0 ),
( uint8_t ) infopage_id,
( uint8_t )( address >> 8 ),
( uint8_t )( address >> 0 ),
};
uint8_t cdata[256];
for( uint16_t index = 0; index < length; index++ )
{
uint8_t* cdata_local = &cdata[index * sizeof( uint32_t )];
cdata_local[0] = ( uint8_t )( data[index] >> 24 );
cdata_local[1] = ( uint8_t )( data[index] >> 16 );
cdata_local[2] = ( uint8_t )( data[index] >> 8 );
cdata_local[3] = ( uint8_t )( data[index] >> 0 );
}
return ( lr1110_status_t ) lr1110_hal_write( context, cbuffer, LR1110_SYSTEM_WRITE_INFOPAGE_CMD_LENGTH, cdata,
length * sizeof( uint32_t ) );
}
lr1110_status_t lr1110_system_read_infopage( const void* context, const lr1110_system_infopage_id_t infopage_id,
const uint16_t address, uint32_t* data, const uint8_t length )
{
const uint8_t cbuffer[LR1110_SYSTEM_READ_INFOPAGE_CMD_LENGTH] = {
( uint8_t )( LR1110_SYSTEM_READ_INFOPAGE_OC >> 8 ),
( uint8_t )( LR1110_SYSTEM_READ_INFOPAGE_OC >> 0 ),
( uint8_t ) infopage_id,
( uint8_t )( address >> 8 ),
( uint8_t )( address >> 0 ),
length,
};
const lr1110_status_t status = ( lr1110_status_t ) lr1110_hal_read(
context, cbuffer, LR1110_SYSTEM_READ_INFOPAGE_CMD_LENGTH, ( uint8_t* ) data, length * sizeof( *data ) );
if( status == LR1110_STATUS_OK )
{
for( uint8_t index = 0; index < length; index++ )
{
uint8_t* buffer_local = ( uint8_t* ) &data[index];
data[index] = ( ( uint32_t ) buffer_local[0] << 24 ) + ( ( uint32_t ) buffer_local[1] << 16 ) +
( ( uint32_t ) buffer_local[2] << 8 ) + ( ( uint32_t ) buffer_local[3] << 0 );
}
}
return status;
}
lr1110_status_t lr1110_system_read_uid( const void* context, lr1110_system_uid_t unique_identifier )
{
const uint8_t cbuffer[LR1110_SYSTEM_READ_UID_CMD_LENGTH] = {
( uint8_t )( LR1110_SYSTEM_READ_UID_OC >> 8 ),
( uint8_t )( LR1110_SYSTEM_READ_UID_OC >> 0 ),
};
return ( lr1110_status_t ) lr1110_hal_read( context, cbuffer, LR1110_SYSTEM_READ_UID_CMD_LENGTH, unique_identifier,
LR1110_SYSTEM_UID_LENGTH );
}
lr1110_status_t lr1110_system_read_join_eui( const void* context, lr1110_system_join_eui_t join_eui )
{
const uint8_t cbuffer[LR1110_SYSTEM_READ_JOIN_EUI_CMD_LENGTH] = {
( uint8_t )( LR1110_SYSTEM_READ_JOIN_EUI_OC >> 8 ),
( uint8_t )( LR1110_SYSTEM_READ_JOIN_EUI_OC >> 0 ),
};
return ( lr1110_status_t ) lr1110_hal_read( context, cbuffer, LR1110_SYSTEM_READ_JOIN_EUI_CMD_LENGTH, join_eui,
LR1110_SYSTEM_JOIN_EUI_LENGTH );
}
lr1110_status_t lr1110_system_read_pin( const void* context, lr1110_system_pin_t pin )
{
const uint8_t cbuffer[LR1110_SYSTEM_READ_PIN_CMD_LENGTH] = {
( uint8_t )( LR1110_SYSTEM_READ_PIN_OC >> 8 ),
( uint8_t )( LR1110_SYSTEM_READ_PIN_OC >> 0 ),
};
return ( lr1110_status_t ) lr1110_hal_read( context, cbuffer, LR1110_SYSTEM_READ_PIN_CMD_LENGTH, pin,
LR1110_SYSTEM_PIN_LENGTH );
}
lr1110_status_t lr1110_system_read_pin_custom_eui( const void* context, lr1110_system_uid_t device_eui,
lr1110_system_join_eui_t join_eui, uint8_t rfu,
lr1110_system_pin_t pin )
{
const uint8_t cbuffer[LR1110_SYSTEM_READ_PIN_CUSTOM_EUI_CMD_LENGTH] = {
( uint8_t )( LR1110_SYSTEM_READ_PIN_OC >> 8 ),
( uint8_t )( LR1110_SYSTEM_READ_PIN_OC >> 0 ),
device_eui[0],
device_eui[1],
device_eui[2],
device_eui[3],
device_eui[4],
device_eui[5],
device_eui[6],
device_eui[7],
join_eui[0],
join_eui[1],
join_eui[2],
join_eui[3],
join_eui[4],
join_eui[5],
join_eui[6],
join_eui[7],
rfu,
};
return ( lr1110_status_t ) lr1110_hal_read( context, cbuffer, LR1110_SYSTEM_READ_PIN_CUSTOM_EUI_CMD_LENGTH, pin,
LR1110_SYSTEM_PIN_LENGTH );
}
lr1110_status_t lr1110_system_get_random_number( const void* context, uint32_t* random_number )
{
const uint8_t cbuffer[LR1110_SYSTEM_GET_RANDOM_CMD_LENGTH] = {
( uint8_t )( LR1110_SYSTEM_GET_RANDOM_OC >> 8 ),
( uint8_t )( LR1110_SYSTEM_GET_RANDOM_OC >> 0 ),
};
return ( lr1110_status_t ) lr1110_hal_read( context, cbuffer, LR1110_SYSTEM_GET_RANDOM_CMD_LENGTH,
( uint8_t* ) random_number, sizeof( uint32_t ) );
}
lr1110_status_t lr1110_system_enable_spi_crc( const void* context, bool enable_crc )
{
const uint8_t cbuffer[LR1110_SYSTEM_ENABLE_SPI_CRC_CMD_LENGTH] = {
( uint8_t )( LR1110_SYSTEM_ENABLE_SPI_CRC_OC >> 8 ),
( uint8_t )( LR1110_SYSTEM_ENABLE_SPI_CRC_OC >> 0 ),
( enable_crc == true ) ? 0x01 : 0x00,
};
return ( lr1110_status_t ) lr1110_hal_write( context, cbuffer, LR1110_SYSTEM_ENABLE_SPI_CRC_CMD_LENGTH, 0, 0 );
}
lr1110_status_t lr1110_system_drive_dio_in_sleep_mode( const void* context, bool enable_drive )
{
const uint8_t cbuffer[LR1110_SYSTEM_DRIVE_DIO_IN_SLEEP_MODE_CMD_LENGTH] = {
( uint8_t )( LR1110_SYSTEM_DRIVE_DIO_IN_SLEEP_MODE_OC >> 8 ),
( uint8_t )( LR1110_SYSTEM_DRIVE_DIO_IN_SLEEP_MODE_OC >> 0 ),
( enable_drive == true ) ? 0x01 : 0x00,
};
return ( lr1110_status_t ) lr1110_hal_write( context, cbuffer, LR1110_SYSTEM_DRIVE_DIO_IN_SLEEP_MODE_CMD_LENGTH, 0,
0 );
}
/*
* -----------------------------------------------------------------------------
* --- PRIVATE FUNCTIONS DEFINITION --------------------------------------------
*/
static void lr1110_system_convert_stat1_byte_to_enum( uint8_t stat1_byte, lr1110_system_stat1_t* stat1 )
{
if( stat1 != NULL )
{
stat1->is_interrupt_active = ( ( stat1_byte & 0x01 ) != 0 ) ? true : false;
stat1->command_status = ( lr1110_system_command_status_t )( stat1_byte >> 1 );
}
}
static void lr1110_system_convert_stat2_byte_to_enum( uint8_t stat2_byte, lr1110_system_stat2_t* stat2 )
{
if( stat2 != NULL )
{
stat2->is_running_from_flash = ( ( stat2_byte & 0x01 ) != 0 ) ? true : false;
stat2->chip_mode = ( lr1110_system_chip_modes_t )( ( stat2_byte & 0x0F ) >> 1 );
stat2->reset_status = ( lr1110_system_reset_status_t )( ( stat2_byte & 0xF0 ) >> 4 );
}
}
/* --- EOF ------------------------------------------------------------------ */
<file_sep>/src/lr1110_lr_fhss.c
/*!
* @file lr1110_lr_fhss.c
*
* @brief LR_FHSS driver implementation for LR1110
*
* The Clear BSD License
* Copyright Semtech Corporation 2021. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted (subject to the limitations in the disclaimer
* below) provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the Semtech corporation nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* NO EXPRESS OR IMPLIED LICENSES TO ANY PARTY'S PATENT RIGHTS ARE GRANTED BY
* THIS LICENSE. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
* CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT
* NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
* PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SEMTECH CORPORATION BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
/*
* -----------------------------------------------------------------------------
* --- DEPENDENCIES ------------------------------------------------------------
*/
#include "lr1110_lr_fhss.h"
#include "lr1110_radio.h"
#include "lr1110_hal.h"
/*
* -----------------------------------------------------------------------------
* --- PRIVATE MACROS-----------------------------------------------------------
*/
#define LR1110_LR_FHSS_PKT_TYPE_LR_FHSS ( 0x04 )
#define LR_FHSS_BITRATE_IN_256_BPS_STEPS ( 125000 )
#define LR1110_LR_FHSS_SET_MODULATION_PARAMS_LR_FHSS_CMD_LENGTH ( 2 + 5 )
#define LR1110_LR_FHSS_BUILD_FRAME_LENGTH ( 2 + 9 )
#define LR1110_LR_FHSS_SET_SYNC_WORD_LENGTH ( 2 + 0 )
#define LR1110_LR_FHSS_SET_MODULATION_PARAM_DIVIDE_BITRATE_BY_256 ( 0x80000000 )
#define LR1110_LR_FHSS_HEADER_BITS ( 114 )
#define LR1110_LR_FHSS_FRAG_BITS ( 48 )
#define LR1110_LR_FHSS_BLOCK_PREAMBLE_BITS ( 2 )
#define LR1110_LR_FHSS_BLOCK_BITS ( LR1110_LR_FHSS_FRAG_BITS + LR1110_LR_FHSS_BLOCK_PREAMBLE_BITS )
#define LR1110_LR_FHSS_SYNCWORD_LENGTH ( 4 )
/*
* -----------------------------------------------------------------------------
* --- PRIVATE CONSTANTS -------------------------------------------------------
*/
/*
* -----------------------------------------------------------------------------
* --- PRIVATE TYPES -----------------------------------------------------------
*/
/*!
* @brief Operating codes for radio-related operations
*/
enum
{
LR1110_LR_FHSS_SET_MODULATION_PARAM_OC = 0x020F,
LR1110_LR_FHSS_BUILD_FRAME_OC = 0x022C,
LR1110_LR_FHSS_SET_SYNC_WORD_OC = 0x022D,
};
/*!
* @brief Hopping enable/disabled enumerations for \ref lr1110_lr_fhss_build_frame
*/
typedef enum
{
LR1110_LR_FHSS_HOPPING_DISABLE = 0x00,
LR1110_LR_FHSS_HOPPING_ENABLE = 0x01,
} lr1110_lr_fhss_hopping_configuration_t;
/*!
* @brief Pulse shape configurations
*/
typedef enum
{
LR1110_LR_FHSS_PULSE_SHAPE_BT_1 = 0x0B //!< Gaussian BT 1.0
} lr1110_lr_fhss_pulse_shape_t;
/*!
* @brief Modulation configuration for LR_FHSS packets
*/
typedef struct lr1110_lr_fhss_mod_params_lr_fhss_s
{
uint32_t br_in_bps; //!< LR_FHSS bitrate [bit/s]
lr1110_lr_fhss_pulse_shape_t pulse_shape; //!< LR_FHSS pulse shape
} lr1110_lr_fhss_mod_params_lr_fhss_t;
/*
* -----------------------------------------------------------------------------
* --- PRIVATE VARIABLES -------------------------------------------------------
*/
/*
* -----------------------------------------------------------------------------
* --- PRIVATE FUNCTIONS DECLARATION -------------------------------------------
*/
/*!
* @brief Set the modulation parameters for LR_FHSS
*
* The command @ref lr1110_lr_fhss_set_pkt_type must be called prior this one.
*
* @param [in] context Chip implementation context
* @param [in] mod_params The structure of modulation configuration
*
* @returns Operation status
*
* @see lr1110_lr_fhss_set_pkt_type
*/
static lr1110_status_t lr1110_lr_fhss_set_lr_fhss_mod_params( const void* context,
const lr1110_lr_fhss_mod_params_lr_fhss_t* mod_params );
/*!
* @brief Set the syncword for LR_FHSS
*
* Default value: 0x2C0F7995
*
* @param [in] context Chip implementation context
* @param [in] sync_word The syncword to set. It is up to the caller to ensure this array is at least four bytes long
*
* @returns Operation status
*/
static lr1110_status_t lr1110_lr_fhss_set_sync_word( const void* context,
const uint8_t sync_word[LR1110_LR_FHSS_SYNCWORD_LENGTH] );
/*!
* @brief Get the bit count and block count for a LR-FHSS frame
*
* @param [in] params Parameter structure
* @param [in] payload_length Length of physical payload, in bytes
*
* @returns Length of physical payload, in bits
*/
static uint16_t lr1110_lr_fhss_get_nb_bits( const lr_fhss_v1_params_t* params, uint16_t payload_length );
/*
* -----------------------------------------------------------------------------
* --- PUBLIC FUNCTIONS DEFINITION ---------------------------------------------
*/
lr1110_status_t lr1110_lr_fhss_init( const void* context )
{
const lr1110_status_t set_packet_type_status =
lr1110_radio_set_pkt_type( context, LR1110_LR_FHSS_PKT_TYPE_LR_FHSS );
if( set_packet_type_status != LR1110_STATUS_OK )
{
return set_packet_type_status;
}
const lr1110_lr_fhss_mod_params_lr_fhss_t mod_lr_fhss = {
.br_in_bps = LR1110_LR_FHSS_SET_MODULATION_PARAM_DIVIDE_BITRATE_BY_256 + LR_FHSS_BITRATE_IN_256_BPS_STEPS,
.pulse_shape = LR1110_LR_FHSS_PULSE_SHAPE_BT_1
};
const lr1110_status_t set_modulation_param_status = lr1110_lr_fhss_set_lr_fhss_mod_params( context, &mod_lr_fhss );
return set_modulation_param_status;
}
lr1110_status_t lr1110_lr_fhss_build_frame( const void* context, const lr1110_lr_fhss_params_t* lr_fhss_params,
uint16_t hop_sequence_id, const uint8_t* payload, uint8_t payload_length )
{
// Since the build_frame command is last, it is possible to check status through stat1
lr1110_status_t status = lr1110_lr_fhss_set_sync_word( context, lr_fhss_params->lr_fhss_params.sync_word );
if( status != LR1110_STATUS_OK )
{
return status;
}
const uint8_t cbuffer[LR1110_LR_FHSS_BUILD_FRAME_LENGTH] = {
( uint8_t )( LR1110_LR_FHSS_BUILD_FRAME_OC >> 8 ),
( uint8_t )( LR1110_LR_FHSS_BUILD_FRAME_OC >> 0 ),
( uint8_t ) lr_fhss_params->lr_fhss_params.header_count,
( uint8_t ) lr_fhss_params->lr_fhss_params.cr,
( uint8_t ) lr_fhss_params->lr_fhss_params.modulation_type,
( uint8_t ) lr_fhss_params->lr_fhss_params.grid,
( uint8_t )( lr_fhss_params->lr_fhss_params.enable_hopping ? LR1110_LR_FHSS_HOPPING_ENABLE
: LR1110_LR_FHSS_HOPPING_DISABLE ),
( uint8_t ) lr_fhss_params->lr_fhss_params.bw,
( uint8_t )( hop_sequence_id >> 8 ),
( uint8_t )( hop_sequence_id >> 0 ),
( uint8_t ) lr_fhss_params->device_offset,
};
return ( lr1110_status_t ) lr1110_hal_write( context, cbuffer, LR1110_LR_FHSS_BUILD_FRAME_LENGTH, payload,
payload_length );
}
uint32_t lr1110_lr_fhss_get_time_on_air_in_ms( const lr1110_lr_fhss_params_t* params, uint16_t payload_length )
{
// Multiply by 1000 / 488.28125, or equivalently 256/125, rounding up
return ( ( lr1110_lr_fhss_get_nb_bits( ¶ms->lr_fhss_params, payload_length ) << 8 ) + 124 ) / 125;
}
unsigned int lr1110_lr_fhss_get_hop_sequence_count( const lr1110_lr_fhss_params_t* lr_fhss_params )
{
if( ( lr_fhss_params->lr_fhss_params.grid == LR_FHSS_V1_GRID_25391_HZ ) ||
( ( lr_fhss_params->lr_fhss_params.grid == LR_FHSS_V1_GRID_3906_HZ ) &&
( lr_fhss_params->lr_fhss_params.bw < LR_FHSS_V1_BW_335938_HZ ) ) )
{
return 384;
}
return 512;
}
/*
* -----------------------------------------------------------------------------
* --- PRIVATE FUNCTIONS DEFINITION ---------------------------------------------
*/
lr1110_status_t lr1110_lr_fhss_set_lr_fhss_mod_params( const void* radio,
const lr1110_lr_fhss_mod_params_lr_fhss_t* mod_params )
{
const uint8_t cbuffer[LR1110_LR_FHSS_SET_MODULATION_PARAMS_LR_FHSS_CMD_LENGTH] = {
( uint8_t )( LR1110_LR_FHSS_SET_MODULATION_PARAM_OC >> 8 ),
( uint8_t )( LR1110_LR_FHSS_SET_MODULATION_PARAM_OC >> 0 ),
( uint8_t )( mod_params->br_in_bps >> 24 ),
( uint8_t )( mod_params->br_in_bps >> 16 ),
( uint8_t )( mod_params->br_in_bps >> 8 ),
( uint8_t )( mod_params->br_in_bps >> 0 ),
( uint8_t ) mod_params->pulse_shape,
};
return ( lr1110_status_t ) lr1110_hal_write( radio, cbuffer,
LR1110_LR_FHSS_SET_MODULATION_PARAMS_LR_FHSS_CMD_LENGTH, 0, 0 );
}
lr1110_status_t lr1110_lr_fhss_set_sync_word( const void* context,
const uint8_t sync_word[LR1110_LR_FHSS_SYNCWORD_LENGTH] )
{
const uint8_t cbuffer[LR1110_LR_FHSS_SET_SYNC_WORD_LENGTH] = {
( uint8_t )( LR1110_LR_FHSS_SET_SYNC_WORD_OC >> 8 ),
( uint8_t )( LR1110_LR_FHSS_SET_SYNC_WORD_OC >> 0 ),
};
return ( lr1110_status_t ) lr1110_hal_write( context, cbuffer, LR1110_LR_FHSS_SET_SYNC_WORD_LENGTH, sync_word,
LR1110_LR_FHSS_SYNCWORD_LENGTH );
}
uint16_t lr1110_lr_fhss_get_nb_bits( const lr_fhss_v1_params_t* params, uint16_t payload_length )
{
uint16_t length_bits = ( payload_length + 2 ) * 8 + 6;
switch( params->cr )
{
case LR_FHSS_V1_CR_5_6:
length_bits = ( ( length_bits * 6 ) + 4 ) / 5;
break;
case LR_FHSS_V1_CR_2_3:
length_bits = length_bits * 3 / 2;
break;
case LR_FHSS_V1_CR_1_2:
length_bits = length_bits * 2;
break;
case LR_FHSS_V1_CR_1_3:
length_bits = length_bits * 3;
break;
}
uint16_t payload_bits = ( length_bits / LR1110_LR_FHSS_FRAG_BITS ) * LR1110_LR_FHSS_BLOCK_BITS;
uint16_t last_block_bits = length_bits % LR1110_LR_FHSS_FRAG_BITS;
if( last_block_bits > 0 )
{
payload_bits += last_block_bits + 2;
}
return LR1110_LR_FHSS_HEADER_BITS * params->header_count + payload_bits;
}<file_sep>/src/lr1110_crypto_engine.c
/*!
* @file lr1110_crypto_engine.c
*
* @brief Cryptographic engine driver implementation for LR1110
*
* The Clear BSD License
* Copyright Semtech Corporation 2021. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted (subject to the limitations in the disclaimer
* below) provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the Semtech corporation nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* NO EXPRESS OR IMPLIED LICENSES TO ANY PARTY'S PATENT RIGHTS ARE GRANTED BY
* THIS LICENSE. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
* CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT
* NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
* PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SEMTECH CORPORATION BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
/*
* -----------------------------------------------------------------------------
* --- DEPENDENCIES ------------------------------------------------------------
*/
#include "lr1110_crypto_engine.h"
#include "lr1110_hal.h"
/*
* -----------------------------------------------------------------------------
* --- PRIVATE MACROS-----------------------------------------------------------
*/
/*
* -----------------------------------------------------------------------------
* --- PRIVATE CONSTANTS -------------------------------------------------------
*/
#define LR1110_CRYPTO_SELECT_CMD_LENGTH ( 2 + 1 )
#define LR1110_CRYPTO_SET_KEY_CMD_LENGTH ( 2 + 17 )
#define LR1110_CRYPTO_DERIVE_KEY_CMD_LENGTH ( 2 + 18 )
#define LR1110_CRYPTO_PROCESS_JOIN_ACCEPT_CMD_LENGTH ( 2 + 3 + 12 + 32 )
#define LR1110_CRYPTO_COMPUTE_AES_CMAC_CMD_LENGTH ( 2 + 1 + 272 )
#define LR1110_CRYPTO_VERIFY_AES_CMAC_CMD_LENGTH ( 2 + 1 + 4 + 256 )
#define LR1110_CRYPTO_AES_ENCRYPT_CMD_LENGTH ( 2 + 1 + 256 )
#define LR1110_CRYPTO_AES_DECRYPT_CMD_LENGTH ( 2 + 1 + 256 )
#define LR1110_CRYPTO_STORE_TO_FLASH_CMD_LENGTH ( 2 )
#define LR1110_CRYPTO_RESTORE_FROM_FLASH_CMD_LENGTH ( 2 )
#define LR1110_CRYPTO_SET_PARAMETER_CMD_LENGTH ( 2 + 1 + 4 )
#define LR1110_CRYPTO_GET_PARAMETER_CMD_LENGTH ( 2 + 1 )
/*
* -----------------------------------------------------------------------------
* --- PRIVATE TYPES -----------------------------------------------------------
*/
/*!
* @brief Operating codes for crypto-related operations
*/
enum
{
LR1110_CRYPTO_SELECT_OC = 0x0500,
LR1110_CRYPTO_SET_KEY_OC = 0x0502,
LR1110_CRYPTO_DERIVE_KEY_OC = 0x0503,
LR1110_CRYPTO_PROCESS_JOIN_ACCEPT_OC = 0x0504,
LR1110_CRYPTO_COMPUTE_AES_CMAC_OC = 0x0505,
LR1110_CRYPTO_VERIFY_AES_CMAC_OC = 0x0506,
LR1110_CRYPTO_ENCRYPT_AES_01_OC = 0x0507,
LR1110_CRYPTO_ENCRYPT_AES_OC = 0x0508,
LR1110_CRYPTO_DECRYPT_AES_OC = 0x0509,
LR1110_CRYPTO_STORE_TO_FLASH_OC = 0x050A,
LR1110_CRYPTO_RESTORE_FROM_FLASH_OC = 0x050B,
LR1110_CRYPTO_SET_PARAMETER_OC = 0x050D,
LR1110_CRYPTO_GET_PARAMETER_OC = 0x050E,
};
/*
* -----------------------------------------------------------------------------
* --- PRIVATE VARIABLES -------------------------------------------------------
*/
/*
* -----------------------------------------------------------------------------
* --- PRIVATE FUNCTIONS DECLARATION -------------------------------------------
*/
/*!
* @brief Helper function that fill the cbuffer provided in first argument with the command opcode, the key id
* and the data to encrypt/decrypt/compute aes cmac
*
* @param [out] cbuffer Buffer used to build the frame
* @param [in] opcode Opcode to be added to the frame
* @param [in] key_id Key ID to be added to the frame
* @param [in] data Data to be added to the frame
* @param [in] length Number of bytes from data to be added to the frame
*
* @warning The caller MUST ensure cbuffer is array is big enough to contain opcode, key_id, and data!
*/
static void lr1110_crypto_fill_cbuffer_opcode_key_data( uint8_t* cbuffer, uint16_t opcode, uint8_t key_id,
const uint8_t* data, uint16_t length );
/*
* -----------------------------------------------------------------------------
* --- PUBLIC FUNCTIONS DEFINITION ---------------------------------------------
*/
lr1110_status_t lr1110_crypto_select( const void* context, const lr1110_crypto_element_t element )
{
uint8_t cbuffer[LR1110_CRYPTO_SELECT_CMD_LENGTH] = { 0x00 };
cbuffer[0] = ( uint8_t )( LR1110_CRYPTO_SELECT_OC >> 8 );
cbuffer[1] = ( uint8_t )( LR1110_CRYPTO_SELECT_OC >> 0 );
cbuffer[2] = element;
return ( lr1110_status_t ) lr1110_hal_write( context, cbuffer, LR1110_CRYPTO_SELECT_CMD_LENGTH, 0, 0 );
}
lr1110_status_t lr1110_crypto_set_key( const void* context, lr1110_crypto_status_t* status, const uint8_t key_id,
const lr1110_crypto_key_t key )
{
uint8_t cbuffer[LR1110_CRYPTO_SET_KEY_CMD_LENGTH] = { 0x00 };
uint8_t rbuffer[LR1110_CRYPTO_STATUS_LENGTH] = { 0x00 };
cbuffer[0] = ( uint8_t )( LR1110_CRYPTO_SET_KEY_OC >> 8 );
cbuffer[1] = ( uint8_t )( LR1110_CRYPTO_SET_KEY_OC >> 0 );
cbuffer[2] = key_id;
for( uint8_t index = 0; index < sizeof( lr1110_crypto_key_t ); index++ )
{
cbuffer[3 + index] = key[index];
}
const lr1110_hal_status_t hal_status =
lr1110_hal_read( context, cbuffer, LR1110_CRYPTO_SET_KEY_CMD_LENGTH, rbuffer, LR1110_CRYPTO_STATUS_LENGTH );
if( hal_status == LR1110_HAL_STATUS_OK )
{
*status = ( lr1110_crypto_status_t ) rbuffer[0];
}
return ( lr1110_status_t ) hal_status;
}
lr1110_status_t lr1110_crypto_derive_key( const void* context, lr1110_crypto_status_t* status, const uint8_t src_key_id,
const uint8_t dest_key_id, const lr1110_crypto_nonce_t nonce )
{
uint8_t cbuffer[LR1110_CRYPTO_DERIVE_KEY_CMD_LENGTH] = { 0x00 };
uint8_t rbuffer[LR1110_CRYPTO_STATUS_LENGTH] = { 0x00 };
cbuffer[0] = ( uint8_t )( LR1110_CRYPTO_DERIVE_KEY_OC >> 8 );
cbuffer[1] = ( uint8_t )( LR1110_CRYPTO_DERIVE_KEY_OC >> 0 );
cbuffer[2] = src_key_id;
cbuffer[3] = dest_key_id;
for( uint8_t index = 0; index < LR1110_CRYPTO_NONCE_LENGTH; index++ )
{
cbuffer[4 + index] = nonce[index];
}
const lr1110_hal_status_t hal_status =
lr1110_hal_read( context, cbuffer, LR1110_CRYPTO_DERIVE_KEY_CMD_LENGTH, rbuffer, LR1110_CRYPTO_STATUS_LENGTH );
if( hal_status == LR1110_HAL_STATUS_OK )
{
*status = ( lr1110_crypto_status_t ) rbuffer[0];
}
return ( lr1110_status_t ) hal_status;
}
lr1110_status_t lr1110_crypto_process_join_accept( const void* context, lr1110_crypto_status_t* status,
const uint8_t dec_key_id, const uint8_t ver_key_id,
const lr1110_crypto_lorawan_version_t lorawan_version,
const uint8_t* header, const uint8_t* data_in, const uint8_t length,
uint8_t* data_out )
{
uint8_t cbuffer[LR1110_CRYPTO_PROCESS_JOIN_ACCEPT_CMD_LENGTH] = { 0x00 };
uint8_t rbuffer[LR1110_CRYPTO_STATUS_LENGTH + 32] = { 0x00 };
uint8_t header_length = ( lorawan_version == 0 ) ? 1 : 12;
cbuffer[0] = ( uint8_t )( LR1110_CRYPTO_PROCESS_JOIN_ACCEPT_OC >> 8 );
cbuffer[1] = ( uint8_t )( LR1110_CRYPTO_PROCESS_JOIN_ACCEPT_OC >> 0 );
cbuffer[2] = dec_key_id;
cbuffer[3] = ver_key_id;
cbuffer[4] = ( uint8_t ) lorawan_version;
for( uint8_t index = 0; index < header_length; index++ )
{
cbuffer[5 + index] = header[index];
}
for( uint8_t index = 0; index < length; index++ )
{
cbuffer[5 + header_length + index] = data_in[index];
}
const lr1110_hal_status_t hal_status =
lr1110_hal_read( context, cbuffer, 2 + 3 + header_length + length, rbuffer, 1 + length );
if( hal_status == LR1110_HAL_STATUS_OK )
{
*status = ( lr1110_crypto_status_t ) rbuffer[0];
if( *status == LR1110_CRYPTO_STATUS_SUCCESS )
{
for( uint8_t index = 0; index < length; index++ )
{
data_out[index] = rbuffer[1 + index];
}
}
}
return ( lr1110_status_t ) hal_status;
}
lr1110_status_t lr1110_crypto_compute_aes_cmac( const void* context, lr1110_crypto_status_t* status,
const uint8_t key_id, const uint8_t* data, const uint16_t length,
lr1110_crypto_mic_t mic )
{
uint8_t cbuffer[LR1110_CRYPTO_COMPUTE_AES_CMAC_CMD_LENGTH] = { 0x00 };
uint8_t rbuffer[LR1110_CRYPTO_STATUS_LENGTH + LR1110_CRYPTO_MIC_LENGTH] = { 0x00 };
lr1110_crypto_fill_cbuffer_opcode_key_data( cbuffer, LR1110_CRYPTO_COMPUTE_AES_CMAC_OC, key_id, data, length );
const lr1110_hal_status_t hal_status = lr1110_hal_read( context, cbuffer, 3 + length, rbuffer,
LR1110_CRYPTO_STATUS_LENGTH + LR1110_CRYPTO_MIC_LENGTH );
if( hal_status == LR1110_HAL_STATUS_OK )
{
*status = ( lr1110_crypto_status_t ) rbuffer[0];
if( *status == LR1110_CRYPTO_STATUS_SUCCESS )
{
for( uint8_t index = 0; index < LR1110_CRYPTO_MIC_LENGTH; index++ )
{
mic[index] = rbuffer[1 + index];
}
}
}
return ( lr1110_status_t ) hal_status;
}
lr1110_status_t lr1110_crypto_verify_aes_cmac( const void* context, lr1110_crypto_status_t* status,
const uint8_t key_id, const uint8_t* data, const uint16_t length,
const lr1110_crypto_mic_t mic )
{
uint8_t cbuffer[LR1110_CRYPTO_VERIFY_AES_CMAC_CMD_LENGTH] = { 0x00 };
uint8_t rbuffer[LR1110_CRYPTO_STATUS_LENGTH] = { 0x00 };
cbuffer[0] = ( uint8_t )( LR1110_CRYPTO_VERIFY_AES_CMAC_OC >> 8 );
cbuffer[1] = ( uint8_t )( LR1110_CRYPTO_VERIFY_AES_CMAC_OC >> 0 );
cbuffer[2] = key_id;
for( uint8_t index = 0; index < LR1110_CRYPTO_MIC_LENGTH; index++ )
{
cbuffer[3 + index] = mic[index];
}
for( uint16_t index = 0; index < length; index++ )
{
cbuffer[3 + LR1110_CRYPTO_MIC_LENGTH + index] = data[index];
}
const lr1110_hal_status_t hal_status = lr1110_hal_read( context, cbuffer, 3 + LR1110_CRYPTO_MIC_LENGTH + length,
rbuffer, LR1110_CRYPTO_STATUS_LENGTH );
if( hal_status == LR1110_HAL_STATUS_OK )
{
*status = ( lr1110_crypto_status_t ) rbuffer[0];
}
return ( lr1110_status_t ) hal_status;
}
lr1110_status_t lr1110_crypto_aes_encrypt_01( const void* context, lr1110_crypto_status_t* status, const uint8_t key_id,
const uint8_t* data, const uint16_t length, uint8_t* result )
{
uint8_t cbuffer[LR1110_CRYPTO_AES_ENCRYPT_CMD_LENGTH] = { 0x00 };
uint8_t rbuffer[LR1110_CRYPTO_STATUS_LENGTH + LR1110_CRYPTO_DATA_MAX_LENGTH] = { 0x00 };
lr1110_crypto_fill_cbuffer_opcode_key_data( cbuffer, LR1110_CRYPTO_ENCRYPT_AES_01_OC, key_id, data, length );
const lr1110_hal_status_t hal_status =
lr1110_hal_read( context, cbuffer, 3 + length, rbuffer, LR1110_CRYPTO_STATUS_LENGTH + length );
if( hal_status == LR1110_HAL_STATUS_OK )
{
*status = ( lr1110_crypto_status_t ) rbuffer[0];
if( *status == LR1110_CRYPTO_STATUS_SUCCESS )
{
for( uint16_t index = 0; index < length; index++ )
{
result[index] = rbuffer[1 + index];
}
}
}
return ( lr1110_status_t ) hal_status;
}
lr1110_status_t lr1110_crypto_aes_encrypt( const void* context, lr1110_crypto_status_t* status, const uint8_t key_id,
const uint8_t* data, const uint16_t length, uint8_t* result )
{
uint8_t cbuffer[LR1110_CRYPTO_AES_ENCRYPT_CMD_LENGTH] = { 0x00 };
uint8_t rbuffer[LR1110_CRYPTO_STATUS_LENGTH + LR1110_CRYPTO_DATA_MAX_LENGTH] = { 0x00 };
lr1110_crypto_fill_cbuffer_opcode_key_data( cbuffer, LR1110_CRYPTO_ENCRYPT_AES_OC, key_id, data, length );
const lr1110_hal_status_t hal_status =
lr1110_hal_read( context, cbuffer, 3 + length, rbuffer, LR1110_CRYPTO_STATUS_LENGTH + length );
if( hal_status == LR1110_HAL_STATUS_OK )
{
*status = ( lr1110_crypto_status_t ) rbuffer[0];
if( *status == LR1110_CRYPTO_STATUS_SUCCESS )
{
for( uint16_t index = 0; index < length; index++ )
{
result[index] = rbuffer[1 + index];
}
}
}
return ( lr1110_status_t ) hal_status;
}
lr1110_status_t lr1110_crypto_aes_decrypt( const void* context, lr1110_crypto_status_t* status, const uint8_t key_id,
const uint8_t* data, const uint16_t length, uint8_t* result )
{
uint8_t cbuffer[LR1110_CRYPTO_AES_DECRYPT_CMD_LENGTH] = { 0x00 };
uint8_t rbuffer[LR1110_CRYPTO_STATUS_LENGTH + LR1110_CRYPTO_DATA_MAX_LENGTH] = { 0x00 };
lr1110_crypto_fill_cbuffer_opcode_key_data( cbuffer, LR1110_CRYPTO_DECRYPT_AES_OC, key_id, data, length );
const lr1110_hal_status_t hal_status =
lr1110_hal_read( context, cbuffer, 3 + length, rbuffer, LR1110_CRYPTO_STATUS_LENGTH + length );
if( hal_status == LR1110_HAL_STATUS_OK )
{
*status = ( lr1110_crypto_status_t ) rbuffer[0];
if( *status == LR1110_CRYPTO_STATUS_SUCCESS )
{
for( uint16_t index = 0; index < length; index++ )
{
result[index] = rbuffer[1 + index];
}
}
}
return ( lr1110_status_t ) hal_status;
}
lr1110_status_t lr1110_crypto_store_to_flash( const void* context, lr1110_crypto_status_t* status )
{
uint8_t cbuffer[LR1110_CRYPTO_STORE_TO_FLASH_CMD_LENGTH] = { 0x00 };
uint8_t rbuffer[LR1110_CRYPTO_STATUS_LENGTH] = { 0x00 };
cbuffer[0] = ( uint8_t )( LR1110_CRYPTO_STORE_TO_FLASH_OC >> 8 );
cbuffer[1] = ( uint8_t )( LR1110_CRYPTO_STORE_TO_FLASH_OC >> 0 );
const lr1110_hal_status_t hal_status = lr1110_hal_read( context, cbuffer, LR1110_CRYPTO_STORE_TO_FLASH_CMD_LENGTH,
rbuffer, LR1110_CRYPTO_STATUS_LENGTH );
if( hal_status == LR1110_HAL_STATUS_OK )
{
*status = ( lr1110_crypto_status_t ) rbuffer[0];
}
return ( lr1110_status_t ) hal_status;
}
lr1110_status_t lr1110_crypto_restore_from_flash( const void* context, lr1110_crypto_status_t* status )
{
uint8_t cbuffer[LR1110_CRYPTO_RESTORE_FROM_FLASH_CMD_LENGTH] = { 0x00 };
uint8_t rbuffer[LR1110_CRYPTO_STATUS_LENGTH] = { 0x00 };
cbuffer[0] = ( uint8_t )( LR1110_CRYPTO_RESTORE_FROM_FLASH_OC >> 8 );
cbuffer[1] = ( uint8_t )( LR1110_CRYPTO_RESTORE_FROM_FLASH_OC >> 0 );
const lr1110_hal_status_t hal_status = lr1110_hal_read(
context, cbuffer, LR1110_CRYPTO_RESTORE_FROM_FLASH_CMD_LENGTH, rbuffer, LR1110_CRYPTO_STATUS_LENGTH );
if( hal_status == LR1110_HAL_STATUS_OK )
{
*status = ( lr1110_crypto_status_t ) rbuffer[0];
}
return ( lr1110_status_t ) hal_status;
}
lr1110_status_t lr1110_crypto_set_parameter( const void* context, lr1110_crypto_status_t* status,
const uint8_t param_id, const lr1110_crypto_param_t parameter )
{
uint8_t cbuffer[LR1110_CRYPTO_SET_PARAMETER_CMD_LENGTH] = { 0x00 };
uint8_t rbuffer[LR1110_CRYPTO_STATUS_LENGTH] = { 0x00 };
cbuffer[0] = ( uint8_t )( LR1110_CRYPTO_SET_PARAMETER_OC >> 8 );
cbuffer[1] = ( uint8_t )( LR1110_CRYPTO_SET_PARAMETER_OC >> 0 );
cbuffer[2] = param_id;
for( uint8_t index = 0; index < LR1110_CRYPTO_PARAMETER_LENGTH; index++ )
{
cbuffer[3 + index] = parameter[index];
}
const lr1110_hal_status_t hal_status = lr1110_hal_read( context, cbuffer, LR1110_CRYPTO_SET_PARAMETER_CMD_LENGTH,
rbuffer, LR1110_CRYPTO_STATUS_LENGTH );
if( hal_status == LR1110_HAL_STATUS_OK )
{
*status = ( lr1110_crypto_status_t ) rbuffer[0];
}
return ( lr1110_status_t ) hal_status;
}
lr1110_status_t lr1110_crypto_get_parameter( const void* context, lr1110_crypto_status_t* status,
const uint8_t param_id, lr1110_crypto_param_t parameter )
{
uint8_t cbuffer[LR1110_CRYPTO_GET_PARAMETER_CMD_LENGTH] = { 0x00 };
uint8_t rbuffer[LR1110_CRYPTO_STATUS_LENGTH + LR1110_CRYPTO_PARAMETER_LENGTH] = { 0x00 };
cbuffer[0] = ( uint8_t )( LR1110_CRYPTO_GET_PARAMETER_OC >> 8 );
cbuffer[1] = ( uint8_t )( LR1110_CRYPTO_GET_PARAMETER_OC >> 0 );
cbuffer[2] = param_id;
const lr1110_hal_status_t hal_status =
lr1110_hal_read( context, cbuffer, LR1110_CRYPTO_GET_PARAMETER_CMD_LENGTH, rbuffer,
LR1110_CRYPTO_STATUS_LENGTH + LR1110_CRYPTO_PARAMETER_LENGTH );
if( hal_status == LR1110_HAL_STATUS_OK )
{
*status = ( lr1110_crypto_status_t ) rbuffer[0];
if( *status == LR1110_CRYPTO_STATUS_SUCCESS )
{
for( uint8_t index = 0; index < LR1110_CRYPTO_PARAMETER_LENGTH; index++ )
{
parameter[index] = rbuffer[1 + index];
}
}
}
return ( lr1110_status_t ) hal_status;
}
/*
* -----------------------------------------------------------------------------
* --- PRIVATE FUNCTIONS DEFINITION --------------------------------------------
*/
static void lr1110_crypto_fill_cbuffer_opcode_key_data( uint8_t* cbuffer, uint16_t opcode, uint8_t key_id,
const uint8_t* data, uint16_t length )
{
cbuffer[0] = ( uint8_t )( opcode >> 8 );
cbuffer[1] = ( uint8_t )( opcode >> 0 );
cbuffer[2] = key_id;
for( uint16_t index = 0; index < length; index++ )
{
cbuffer[3 + index] = data[index];
}
}
/* --- EOF ------------------------------------------------------------------ */
<file_sep>/src/lr1110_gnss.c
/*!
* @file lr1110_gnss.c
*
* @brief GNSS scan driver implementation for LR1110
*
* The Clear BSD License
* Copyright Semtech Corporation 2021. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted (subject to the limitations in the disclaimer
* below) provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the Semtech corporation nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* NO EXPRESS OR IMPLIED LICENSES TO ANY PARTY'S PATENT RIGHTS ARE GRANTED BY
* THIS LICENSE. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
* CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT
* NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
* PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SEMTECH CORPORATION BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
/*
* -----------------------------------------------------------------------------
* --- DEPENDENCIES ------------------------------------------------------------
*/
#include "lr1110_gnss.h"
#include "lr1110_regmem.h"
#include "lr1110_hal.h"
/*
* -----------------------------------------------------------------------------
* --- PRIVATE MACROS-----------------------------------------------------------
*/
/*
* -----------------------------------------------------------------------------
* --- PRIVATE CONSTANTS -------------------------------------------------------
*/
#define LR1110_GNSS_SET_CONSTELLATION_CMD_LENGTH ( 2 + 1 )
#define LR1110_GNSS_READ_CONSTELLATION_CMD_LENGTH ( 2 )
#define LR1110_GNSS_SET_ALMANAC_UPDATE_CMD_LENGTH ( 2 + 1 )
#define LR1110_GNSS_READ_ALMANAC_UPDATE_CMD_LENGTH ( 2 )
#define LR1110_GNSS_READ_FW_VERSION_CMD_LENGTH ( 2 )
#define LR1110_GNSS_READ_SUPPORTED_CONSTELLATION_CMD_LENGTH ( 2 )
#define LR1110_GNSS_SET_SCAN_MODE_CMD_LENGTH ( 2 + 1 )
#define LR1110_GNSS_SCAN_AUTONOMOUS_CMD_LENGTH ( 2 + 7 )
#define LR1110_GNSS_SCAN_ASSISTED_CMD_LENGTH ( 2 + 7 )
#define LR1110_GNSS_SCAN_GET_RES_SIZE_CMD_LENGTH ( 2 )
#define LR1110_GNSS_SCAN_READ_RES_CMD_LENGTH ( 2 )
#define LR1110_GNSS_ALMANAC_UPDATE_CMD_LENGTH ( 2 )
#define LR1110_GNSS_ALMANAC_READ_CMD_LENGTH ( 2 )
#define LR1110_GNSS_SET_ASSISTANCE_POSITION_CMD_LENGTH ( 2 + 4 )
#define LR1110_GNSS_READ_ASSISTANCE_POSITION_CMD_LENGTH ( 2 )
#define LR1110_GNSS_PUSH_SOLVER_MSG_CMD_LENGTH ( 2 )
#define LR1110_GNSS_PUSH_DM_MSG_CMD_LENGTH ( 2 )
#define LR1110_GNSS_GET_CONTEXT_STATUS_CMD_LENGTH ( 2 )
#define LR1110_GNSS_SCAN_GET_TIMINGS_CMD_LENGTH ( 2 )
#define LR1110_GNSS_GET_NB_SV_SATELLITES_CMD_LENGTH ( 2 )
#define LR1110_GNSS_GET_SV_SATELLITES_CMD_LENGTH ( 2 )
#define LR1110_GNSS_ALMANAC_READ_RBUFFER_LENGTH ( 6 )
#define LR1110_GNSS_ALMANAC_DATE_LENGTH ( 2 )
#define LR1110_GNSS_ALMANAC_UPDATE_MAX_NB_OF_BLOCKS \
( ( LR1110_CMD_LENGTH_MAX - LR1110_GNSS_ALMANAC_UPDATE_CMD_LENGTH ) / LR1110_GNSS_SINGLE_ALMANAC_WRITE_SIZE )
#define LR1110_GNSS_READ_ALMANAC_TEMPBUFFER_SIZE_BYTE ( 47 )
#define LR1110_GNSS_SCAN_GET_TIMINGS_RBUFFER_LENGTH ( 8 )
#define LR1110_GNSS_MAX_DETECTED_SV ( 32 )
#define LR1110_GNSS_DETECTED_SV_SINGLE_LENGTH ( 4 )
#define LR1110_GNSS_MAX_DETECTED_SV_BUFFER_LENGTH \
( LR1110_GNSS_MAX_DETECTED_SV * LR1110_GNSS_DETECTED_SV_SINGLE_LENGTH )
#define LR1110_GNSS_READ_FIRMWARE_VERSION_RBUFFER_LENGTH ( 2 )
#define LR1110_GNSS_SCALING_LATITUDE 90
#define LR1110_GNSS_SCALING_LONGITUDE 180
#define LR1110_GNSS_SNR_TO_CNR_OFFSET ( 31 )
#define LR1110_GNSS_SCAN_RESULT_DESTINATION_INDEX ( 0 )
/*
* -----------------------------------------------------------------------------
* --- PRIVATE TYPES -----------------------------------------------------------
*/
/*!
* @brief Operating codes for GNSS-related operations
*/
enum
{
LR1110_GNSS_SET_CONSTELLATION_OC = 0x0400, //!< Set the constellation to use
LR1110_GNSS_READ_CONSTELLATION_OC = 0x0401, //!< Read the used constellations
LR1110_GNSS_SET_ALMANAC_UPDATE_OC = 0x0402, //!< Set almanac update configuration
LR1110_GNSS_READ_ALMANAC_UPDATE_OC = 0x0403, //!< Read the almanac update configuration
LR1110_GNSS_READ_FW_VERSION_OC = 0x0406, //!< Read the firmware version
LR1110_GNSS_READ_SUPPORTED_CONSTELLATION_OC = 0x0407, //!< Read the supported constellations
LR1110_GNSS_SET_SCAN_MODE_OC = 0x0408, //!< Define single or double capture
LR1110_GNSS_SCAN_AUTONOMOUS_OC = 0x0409, //!< Launch an autonomous scan
LR1110_GNSS_SCAN_ASSISTED_OC = 0x040A, //!< Launch an assisted scan
LR1110_GNSS_SCAN_GET_RES_SIZE_OC = 0x040C, //!< Get the size of the output payload
LR1110_GNSS_SCAN_READ_RES_OC = 0x040D, //!< Read the byte stream
LR1110_GNSS_ALMANAC_UPDATE_OC = 0x040E, //!< Update the almanac
LR1110_GNSS_ALMANAC_READ_OC = 0x040F, //!< Read all almanacs
LR1110_GNSS_SET_ASSISTANCE_POSITION_OC = 0x0410, //!< Set the assistance position
LR1110_GNSS_READ_ASSISTANCE_POSITION_OC = 0x0411, //!< Read the assistance position
LR1110_GNSS_PUSH_SOLVER_MSG_OC = 0x0414, //!< Push messages coming from the solver
LR1110_GNSS_PUSH_DM_MSG_OC = 0x0415, //!< Push messages coming from the device management
LR1110_GNSS_GET_CONTEXT_STATUS_OC = 0x0416, //!< Read the context
LR1110_GNSS_GET_NB_SATELLITES_OC = 0x0417, //!< Get the number of satellites detected during a scan
LR1110_GNSS_GET_SATELLITES_OC = 0x0418, //!< Get the list of satellites detected during a scan
LR1110_GNSS_GET_TIMINGS_OC = 0x0419, //!< Get the time spent in signal acquisition and analysis
};
/*
* -----------------------------------------------------------------------------
* --- PRIVATE VARIABLES -------------------------------------------------------
*/
/*
* -----------------------------------------------------------------------------
* --- PRIVATE FUNCTIONS DECLARATION -------------------------------------------
*/
/*!
* @brief Helper function that convert an array of uint8_t into a uint32_t single value
*
* @warning It is up to the caller to ensure that value points to an array of at least sizeof(uint32_t) elements.
*
* @param [in] value Array of uint8_t to be translated into a uint32_t
*
* @returns 32-bit value
*/
static uint32_t lr1110_gnss_uint8_to_uint32( uint8_t value[4] );
/*!
* @brief Returns the minimum of the operand given as parameter and the maximum allowed number of blocks
*
* @param [in] operand Size to compare
*
* @returns Minimum between operand and @ref LR1110_GNSS_ALMANAC_UPDATE_MAX_NB_OF_BLOCKS
*/
static uint16_t lr1110_gnss_get_min_from_operand_and_max_nb_of_blocks( uint16_t operand );
/*!
* @brief Get the almanac base address and size
*
* @param [in] context Chip implementation context
* @param [out] address Start address of the almanac in memory
* @param [out] size Size of the almanac in byte
*
* @returns Operation status
*/
static lr1110_status_t lr1110_gnss_get_almanac_address_size( const void* context, uint32_t* address, uint16_t* size );
/*
* -----------------------------------------------------------------------------
* --- PUBLIC FUNCTIONS DEFINITION ---------------------------------------------
*/
lr1110_status_t lr1110_gnss_get_result_size( const void* context, uint16_t* result_size )
{
const uint8_t cbuffer[LR1110_GNSS_SCAN_GET_RES_SIZE_CMD_LENGTH] = {
( uint8_t )( LR1110_GNSS_SCAN_GET_RES_SIZE_OC >> 8 ),
( uint8_t )( LR1110_GNSS_SCAN_GET_RES_SIZE_OC >> 0 ),
};
uint8_t rbuffer[sizeof( uint16_t )] = { 0 };
const lr1110_hal_status_t hal_status =
lr1110_hal_read( context, cbuffer, LR1110_GNSS_SCAN_GET_RES_SIZE_CMD_LENGTH, rbuffer, sizeof( uint16_t ) );
if( hal_status == LR1110_HAL_STATUS_OK )
{
*result_size = ( ( uint16_t ) rbuffer[0] << 8 ) + ( ( uint16_t ) rbuffer[1] );
}
return ( lr1110_status_t ) hal_status;
}
lr1110_status_t lr1110_gnss_read_results( const void* context, uint8_t* result_buffer,
const uint16_t result_buffer_size )
{
const uint8_t cbuffer[LR1110_GNSS_SCAN_READ_RES_CMD_LENGTH] = {
( uint8_t )( LR1110_GNSS_SCAN_READ_RES_OC >> 8 ),
( uint8_t )( LR1110_GNSS_SCAN_READ_RES_OC >> 0 ),
};
return ( lr1110_status_t ) lr1110_hal_read( context, cbuffer, LR1110_GNSS_SCAN_READ_RES_CMD_LENGTH, result_buffer,
result_buffer_size );
}
lr1110_status_t lr1110_gnss_get_timings( const void* context, lr1110_gnss_timings_t* timings )
{
const uint8_t cbuffer[LR1110_GNSS_SCAN_GET_TIMINGS_CMD_LENGTH] = {
( uint8_t )( LR1110_GNSS_GET_TIMINGS_OC >> 8 ),
( uint8_t )( LR1110_GNSS_GET_TIMINGS_OC >> 0 ),
};
uint8_t rbuffer[LR1110_GNSS_SCAN_GET_TIMINGS_RBUFFER_LENGTH] = { 0 };
const lr1110_hal_status_t hal_status = lr1110_hal_read( context, cbuffer, LR1110_GNSS_SCAN_GET_TIMINGS_CMD_LENGTH,
rbuffer, LR1110_GNSS_SCAN_GET_TIMINGS_RBUFFER_LENGTH );
timings->computation_ms = lr1110_gnss_uint8_to_uint32( &rbuffer[0] ) / 1000;
timings->radio_ms = lr1110_gnss_uint8_to_uint32( &rbuffer[4] ) / 1000;
return ( lr1110_status_t ) hal_status;
}
lr1110_status_t lr1110_gnss_almanac_update( const void* context, const uint8_t* blocks, const uint8_t nb_of_blocks )
{
const uint8_t cbuffer[LR1110_GNSS_ALMANAC_UPDATE_CMD_LENGTH] = {
( uint8_t )( LR1110_GNSS_ALMANAC_UPDATE_OC >> 8 ),
( uint8_t )( LR1110_GNSS_ALMANAC_UPDATE_OC >> 0 ),
};
uint16_t remaining_nb_of_blocks = nb_of_blocks;
while( remaining_nb_of_blocks > 0 )
{
const uint16_t nb_of_blocks_to_write =
lr1110_gnss_get_min_from_operand_and_max_nb_of_blocks( remaining_nb_of_blocks );
const uint8_t* blocks_to_write =
blocks + ( nb_of_blocks - remaining_nb_of_blocks ) * LR1110_GNSS_SINGLE_ALMANAC_WRITE_SIZE;
const lr1110_hal_status_t status =
lr1110_hal_write( context, cbuffer, LR1110_GNSS_ALMANAC_UPDATE_CMD_LENGTH, blocks_to_write,
nb_of_blocks_to_write * LR1110_GNSS_SINGLE_ALMANAC_WRITE_SIZE );
if( status != LR1110_HAL_STATUS_OK )
{
return ( lr1110_status_t ) status;
}
remaining_nb_of_blocks -= nb_of_blocks_to_write;
}
return LR1110_STATUS_OK;
}
lr1110_status_t lr1110_gnss_read_almanac( const void* context,
lr1110_gnss_almanac_full_read_bytestream_t almanac_bytestream )
{
uint32_t almanac_address = 0;
uint16_t almanac_size = 0;
lr1110_status_t status = lr1110_gnss_get_almanac_address_size( context, &almanac_address, &almanac_size );
if( status != LR1110_STATUS_OK )
{
return status;
}
const uint8_t N_READ_ALMANAC_REGMEM32 = 15;
for( uint8_t index_regmem32 = 0; index_regmem32 < N_READ_ALMANAC_REGMEM32; index_regmem32++ )
{
const uint16_t local_bytestream_index_burst =
index_regmem32 * LR1110_GNSS_READ_ALMANAC_TEMPBUFFER_SIZE_BYTE * 4;
uint32_t temporary_buffer[LR1110_GNSS_READ_ALMANAC_TEMPBUFFER_SIZE_BYTE] = { 0 };
const lr1110_status_t local_status = lr1110_regmem_read_regmem32(
context, almanac_address, temporary_buffer, LR1110_GNSS_READ_ALMANAC_TEMPBUFFER_SIZE_BYTE );
if( local_status != LR1110_STATUS_OK )
{
return local_status;
}
almanac_address += ( LR1110_GNSS_READ_ALMANAC_TEMPBUFFER_SIZE_BYTE * 4 );
for( uint8_t index_local_temp = 0; index_local_temp < LR1110_GNSS_READ_ALMANAC_TEMPBUFFER_SIZE_BYTE;
index_local_temp++ )
{
const uint16_t local_bytestream_index = local_bytestream_index_burst + ( index_local_temp * 4 );
almanac_bytestream[local_bytestream_index + 0] = ( uint8_t )( temporary_buffer[index_local_temp] >> 0 );
almanac_bytestream[local_bytestream_index + 1] = ( uint8_t )( temporary_buffer[index_local_temp] >> 8 );
almanac_bytestream[local_bytestream_index + 2] = ( uint8_t )( temporary_buffer[index_local_temp] >> 16 );
almanac_bytestream[local_bytestream_index + 3] = ( uint8_t )( temporary_buffer[index_local_temp] >> 24 );
}
}
return status;
}
lr1110_status_t lr1110_gnss_get_almanac_age_for_satellite( const void* context, const lr1110_gnss_satellite_id_t sv_id,
uint16_t* almanac_age )
{
uint32_t almanac_base_address = 0;
uint16_t almanac_size = 0;
const lr1110_status_t status_get_almanac_address_size =
lr1110_gnss_get_almanac_address_size( context, &almanac_base_address, &almanac_size );
if( status_get_almanac_address_size != LR1110_STATUS_OK )
{
return status_get_almanac_address_size;
}
const uint16_t offset_almanac_date = sv_id * LR1110_GNSS_SINGLE_ALMANAC_READ_SIZE + 1;
uint8_t raw_almanac_date[LR1110_GNSS_ALMANAC_DATE_LENGTH] = { 0 };
const lr1110_status_t status_read_mem = lr1110_regmem_read_mem8(
context, almanac_base_address + offset_almanac_date, raw_almanac_date, LR1110_GNSS_ALMANAC_DATE_LENGTH );
if( status_read_mem == LR1110_STATUS_OK )
{
// Note: the memory on LR1110 is LSB first. As the 2-byte wide almanac age is obtained by calling the _mem8, the
// conversion to uint16_t here is done LSB first
( *almanac_age ) =
( ( ( uint16_t ) raw_almanac_date[1] ) << 8 ) + ( ( ( uint16_t ) raw_almanac_date[0] ) << 0 );
}
return status_read_mem;
}
lr1110_status_t lr1110_gnss_get_almanac_address_size( const void* context, uint32_t* address, uint16_t* size )
{
const uint8_t cbuffer[LR1110_GNSS_ALMANAC_READ_CMD_LENGTH] = {
( uint8_t )( LR1110_GNSS_ALMANAC_READ_OC >> 8 ),
( uint8_t )( LR1110_GNSS_ALMANAC_READ_OC >> 0 ),
};
uint8_t rbuffer[LR1110_GNSS_ALMANAC_READ_RBUFFER_LENGTH] = { 0 };
const lr1110_hal_status_t hal_status = lr1110_hal_read( context, cbuffer, LR1110_GNSS_ALMANAC_READ_CMD_LENGTH,
rbuffer, LR1110_GNSS_ALMANAC_READ_RBUFFER_LENGTH );
if( hal_status == LR1110_HAL_STATUS_OK )
{
*address = lr1110_gnss_uint8_to_uint32( &rbuffer[0] );
*size = ( ( ( uint16_t ) rbuffer[4] ) << 8 ) | ( ( uint16_t ) rbuffer[5] );
}
return ( lr1110_status_t ) hal_status;
}
lr1110_status_t lr1110_gnss_push_solver_msg( const void* context, const uint8_t* payload, const uint16_t payload_size )
{
const uint8_t cbuffer[LR1110_GNSS_PUSH_SOLVER_MSG_CMD_LENGTH] = {
( uint8_t )( LR1110_GNSS_PUSH_SOLVER_MSG_OC >> 8 ),
( uint8_t )( LR1110_GNSS_PUSH_SOLVER_MSG_OC >> 0 ),
};
return ( lr1110_status_t ) lr1110_hal_write( context, cbuffer, LR1110_GNSS_PUSH_SOLVER_MSG_CMD_LENGTH, payload,
payload_size );
}
lr1110_status_t lr1110_gnss_set_constellations_to_use( const void* context,
const lr1110_gnss_constellation_mask_t constellation_to_use )
{
const uint8_t cbuffer[LR1110_GNSS_SET_CONSTELLATION_CMD_LENGTH] = {
( uint8_t )( LR1110_GNSS_SET_CONSTELLATION_OC >> 8 ),
( uint8_t )( LR1110_GNSS_SET_CONSTELLATION_OC >> 0 ),
constellation_to_use,
};
return ( lr1110_status_t ) lr1110_hal_write( context, cbuffer, LR1110_GNSS_SET_CONSTELLATION_CMD_LENGTH, 0, 0 );
}
lr1110_status_t lr1110_gnss_read_used_constellations( const void* context,
lr1110_gnss_constellation_mask_t* constellations_used )
{
const uint8_t cbuffer[LR1110_GNSS_READ_CONSTELLATION_CMD_LENGTH] = {
( uint8_t )( LR1110_GNSS_READ_CONSTELLATION_OC >> 8 ),
( uint8_t )( LR1110_GNSS_READ_CONSTELLATION_OC >> 0 ),
};
return ( lr1110_status_t ) lr1110_hal_read( context, cbuffer, LR1110_GNSS_READ_CONSTELLATION_CMD_LENGTH,
constellations_used, sizeof( *constellations_used ) );
}
lr1110_status_t lr1110_gnss_set_almanac_update( const void* context,
const lr1110_gnss_constellation_mask_t constellations_to_update )
{
const uint8_t cbuffer[LR1110_GNSS_SET_ALMANAC_UPDATE_CMD_LENGTH] = {
( uint8_t )( LR1110_GNSS_SET_ALMANAC_UPDATE_OC >> 8 ),
( uint8_t )( LR1110_GNSS_SET_ALMANAC_UPDATE_OC >> 0 ),
constellations_to_update,
};
return ( lr1110_status_t ) lr1110_hal_write( context, cbuffer, LR1110_GNSS_SET_ALMANAC_UPDATE_CMD_LENGTH, 0, 0 );
}
lr1110_status_t lr1110_gnss_read_almanac_update( const void* context,
lr1110_gnss_constellation_mask_t* constellations_to_update )
{
const uint8_t cbuffer[LR1110_GNSS_READ_ALMANAC_UPDATE_CMD_LENGTH] = {
( uint8_t )( LR1110_GNSS_READ_ALMANAC_UPDATE_OC >> 8 ),
( uint8_t )( LR1110_GNSS_READ_ALMANAC_UPDATE_OC >> 0 ),
};
return ( lr1110_status_t ) lr1110_hal_read( context, cbuffer, LR1110_GNSS_READ_ALMANAC_UPDATE_CMD_LENGTH,
constellations_to_update, sizeof( *constellations_to_update ) );
}
lr1110_status_t lr1110_gnss_read_firmware_version( const void* context, lr1110_gnss_version_t* version )
{
const uint8_t cbuffer[LR1110_GNSS_READ_FW_VERSION_CMD_LENGTH] = {
( uint8_t )( LR1110_GNSS_READ_FW_VERSION_OC >> 8 ),
( uint8_t )( LR1110_GNSS_READ_FW_VERSION_OC >> 0 ),
};
uint8_t rbuffer[LR1110_GNSS_READ_FIRMWARE_VERSION_RBUFFER_LENGTH] = { 0 };
const lr1110_hal_status_t hal_status = lr1110_hal_read( context, cbuffer, LR1110_GNSS_READ_FW_VERSION_CMD_LENGTH,
rbuffer, LR1110_GNSS_READ_FIRMWARE_VERSION_RBUFFER_LENGTH );
version->gnss_firmware = rbuffer[0];
version->gnss_almanac = rbuffer[1];
return ( lr1110_status_t ) hal_status;
}
lr1110_status_t lr1110_gnss_read_supported_constellations( const void* context,
lr1110_gnss_constellation_mask_t* supported_constellations )
{
const uint8_t cbuffer[LR1110_GNSS_READ_SUPPORTED_CONSTELLATION_CMD_LENGTH] = {
( uint8_t )( LR1110_GNSS_READ_SUPPORTED_CONSTELLATION_OC >> 8 ),
( uint8_t )( LR1110_GNSS_READ_SUPPORTED_CONSTELLATION_OC >> 0 ),
};
return ( lr1110_status_t ) lr1110_hal_read( context, cbuffer, LR1110_GNSS_READ_SUPPORTED_CONSTELLATION_CMD_LENGTH,
supported_constellations, sizeof( *supported_constellations ) );
}
lr1110_status_t lr1110_gnss_set_scan_mode( const void* context, const lr1110_gnss_scan_mode_t scan_mode )
{
const uint8_t cbuffer[LR1110_GNSS_SET_SCAN_MODE_CMD_LENGTH] = {
( uint8_t )( LR1110_GNSS_SET_SCAN_MODE_OC >> 8 ),
( uint8_t )( LR1110_GNSS_SET_SCAN_MODE_OC >> 0 ),
( uint8_t ) scan_mode,
};
return ( lr1110_status_t ) lr1110_hal_write( context, cbuffer, LR1110_GNSS_SET_SCAN_MODE_CMD_LENGTH, 0, 0 );
}
lr1110_status_t lr1110_gnss_scan_autonomous( const void* context, const lr1110_gnss_date_t date,
const lr1110_gnss_search_mode_t effort_mode,
const uint8_t gnss_input_parameters, const uint8_t nb_sat )
{
const uint8_t cbuffer[LR1110_GNSS_SCAN_AUTONOMOUS_CMD_LENGTH] = {
( uint8_t )( LR1110_GNSS_SCAN_AUTONOMOUS_OC >> 8 ),
( uint8_t )( LR1110_GNSS_SCAN_AUTONOMOUS_OC >> 0 ),
( uint8_t )( date >> 24 ),
( uint8_t )( date >> 16 ),
( uint8_t )( date >> 8 ),
( uint8_t )( date >> 0 ),
( uint8_t ) effort_mode,
gnss_input_parameters,
nb_sat,
};
return ( lr1110_status_t ) lr1110_hal_write( context, cbuffer, LR1110_GNSS_SCAN_AUTONOMOUS_CMD_LENGTH, 0, 0 );
}
lr1110_status_t lr1110_gnss_scan_assisted( const void* context, const lr1110_gnss_date_t date,
const lr1110_gnss_search_mode_t effort_mode,
const uint8_t gnss_input_parameters, const uint8_t nb_sat )
{
const uint8_t cbuffer[LR1110_GNSS_SCAN_ASSISTED_CMD_LENGTH] = {
( uint8_t )( LR1110_GNSS_SCAN_ASSISTED_OC >> 8 ),
( uint8_t )( LR1110_GNSS_SCAN_ASSISTED_OC >> 0 ),
( uint8_t )( date >> 24 ),
( uint8_t )( date >> 16 ),
( uint8_t )( date >> 8 ),
( uint8_t )( date >> 0 ),
( uint8_t ) effort_mode,
gnss_input_parameters,
nb_sat,
};
return ( lr1110_status_t ) lr1110_hal_write( context, cbuffer, LR1110_GNSS_SCAN_ASSISTED_CMD_LENGTH, 0, 0 );
}
lr1110_status_t lr1110_gnss_set_assistance_position(
const void* context, const lr1110_gnss_solver_assistance_position_t* assistance_position )
{
const int16_t latitude = ( ( assistance_position->latitude * 2048 ) / LR1110_GNSS_SCALING_LATITUDE );
const int16_t longitude = ( ( assistance_position->longitude * 2048 ) / LR1110_GNSS_SCALING_LONGITUDE );
const uint8_t cbuffer[LR1110_GNSS_SET_ASSISTANCE_POSITION_CMD_LENGTH] = {
( uint8_t )( LR1110_GNSS_SET_ASSISTANCE_POSITION_OC >> 8 ),
( uint8_t )( LR1110_GNSS_SET_ASSISTANCE_POSITION_OC >> 0 ),
( uint8_t )( latitude >> 8 ),
( uint8_t )( latitude >> 0 ),
( uint8_t )( longitude >> 8 ),
( uint8_t )( longitude >> 0 ),
};
return ( lr1110_status_t ) lr1110_hal_write( context, cbuffer, LR1110_GNSS_SET_ASSISTANCE_POSITION_CMD_LENGTH, 0,
0 );
}
lr1110_status_t lr1110_gnss_read_assistance_position( const void* context,
lr1110_gnss_solver_assistance_position_t* assistance_position )
{
uint8_t position_buffer[4] = { 0x00 };
int16_t position_tmp;
const uint8_t cbuffer[LR1110_GNSS_READ_ASSISTANCE_POSITION_CMD_LENGTH] = {
( uint8_t )( LR1110_GNSS_READ_ASSISTANCE_POSITION_OC >> 8 ),
( uint8_t )( LR1110_GNSS_READ_ASSISTANCE_POSITION_OC >> 0 ),
};
const lr1110_hal_status_t hal_status = lr1110_hal_read(
context, cbuffer, LR1110_GNSS_READ_ASSISTANCE_POSITION_CMD_LENGTH, position_buffer, sizeof( position_buffer ) );
position_tmp = ( int16_t )( ( ( uint16_t ) position_buffer[0] << 8 ) + position_buffer[1] );
assistance_position->latitude = ( ( float ) ( position_tmp ) *LR1110_GNSS_SCALING_LATITUDE ) / 2048;
position_tmp = ( int16_t )( ( ( uint16_t ) position_buffer[2] << 8 ) + position_buffer[3] );
assistance_position->longitude = ( ( float ) ( position_tmp ) *LR1110_GNSS_SCALING_LONGITUDE ) / 2048;
return ( lr1110_status_t ) hal_status;
}
lr1110_status_t lr1110_gnss_push_dmc_msg( const void* context, uint8_t* dmc_msg, uint16_t dmc_msg_len )
{
const uint8_t cbuffer[LR1110_GNSS_PUSH_DM_MSG_CMD_LENGTH] = {
( uint8_t )( LR1110_GNSS_PUSH_DM_MSG_OC >> 8 ),
( uint8_t )( LR1110_GNSS_PUSH_DM_MSG_OC >> 0 ),
};
return ( lr1110_status_t ) lr1110_hal_write( context, cbuffer, LR1110_GNSS_PUSH_DM_MSG_CMD_LENGTH, dmc_msg,
dmc_msg_len );
}
lr1110_status_t lr1110_gnss_get_context_status( const void* context,
lr1110_gnss_context_status_bytestream_t context_status )
{
const uint8_t cbuffer[LR1110_GNSS_GET_CONTEXT_STATUS_CMD_LENGTH] = {
( uint8_t )( LR1110_GNSS_GET_CONTEXT_STATUS_OC >> 8 ),
( uint8_t )( LR1110_GNSS_GET_CONTEXT_STATUS_OC >> 0 ),
};
return ( lr1110_status_t ) lr1110_hal_read( context, cbuffer, LR1110_GNSS_GET_CONTEXT_STATUS_CMD_LENGTH,
context_status, LR1110_GNSS_CONTEXT_STATUS_LENGTH );
}
lr1110_status_t lr1110_gnss_get_nb_detected_satellites( const void* context, uint8_t* nb_detected_satellites )
{
const uint8_t cbuffer[LR1110_GNSS_GET_NB_SV_SATELLITES_CMD_LENGTH] = {
( uint8_t )( LR1110_GNSS_GET_NB_SATELLITES_OC >> 8 ),
( uint8_t )( LR1110_GNSS_GET_NB_SATELLITES_OC >> 0 ),
};
return ( lr1110_status_t ) lr1110_hal_read( context, cbuffer, LR1110_GNSS_GET_NB_SV_SATELLITES_CMD_LENGTH,
nb_detected_satellites, 1 );
}
lr1110_status_t lr1110_gnss_get_detected_satellites(
const void* context, const uint8_t nb_detected_satellites,
lr1110_gnss_detected_satellite_t* detected_satellite_id_snr_doppler )
{
const uint8_t max_satellites_to_fetch =
( LR1110_GNSS_MAX_DETECTED_SV > nb_detected_satellites ) ? nb_detected_satellites : LR1110_GNSS_MAX_DETECTED_SV;
const uint16_t read_size = max_satellites_to_fetch * LR1110_GNSS_DETECTED_SV_SINGLE_LENGTH;
uint8_t result_buffer[LR1110_GNSS_MAX_DETECTED_SV_BUFFER_LENGTH] = { 0 };
const uint8_t cbuffer[LR1110_GNSS_GET_SV_SATELLITES_CMD_LENGTH] = {
( uint8_t )( LR1110_GNSS_GET_SATELLITES_OC >> 8 ),
( uint8_t )( LR1110_GNSS_GET_SATELLITES_OC >> 0 ),
};
const lr1110_hal_status_t hal_status =
lr1110_hal_read( context, cbuffer, LR1110_GNSS_GET_SV_SATELLITES_CMD_LENGTH, result_buffer, read_size );
if( hal_status == LR1110_HAL_STATUS_OK )
{
for( uint8_t index_satellite = 0; index_satellite < max_satellites_to_fetch; index_satellite++ )
{
const uint16_t local_result_buffer_index = index_satellite * LR1110_GNSS_DETECTED_SV_SINGLE_LENGTH;
lr1110_gnss_detected_satellite_t* local_satellite_result =
&detected_satellite_id_snr_doppler[index_satellite];
local_satellite_result->satellite_id = result_buffer[local_result_buffer_index];
local_satellite_result->cnr = result_buffer[local_result_buffer_index + 1] + LR1110_GNSS_SNR_TO_CNR_OFFSET;
local_satellite_result->doppler = ( int16_t )( ( result_buffer[local_result_buffer_index + 2] << 8 ) +
( result_buffer[local_result_buffer_index + 3] << 0 ) );
}
}
return ( lr1110_status_t ) hal_status;
}
lr1110_status_t lr1110_gnss_parse_context_status_buffer(
const lr1110_gnss_context_status_bytestream_t context_status_bytestream,
lr1110_gnss_context_status_t* context_status )
{
lr1110_status_t status = LR1110_STATUS_ERROR;
if( ( ( lr1110_gnss_destination_t ) context_status_bytestream[0] == LR1110_GNSS_DESTINATION_DMC ) &&
( ( lr1110_gnss_message_dmc_opcode_t ) context_status_bytestream[1] == LR1110_GNSS_DMC_STATUS ) )
{
context_status->firmware_version = context_status_bytestream[2];
context_status->global_almanac_crc =
( ( uint32_t ) context_status_bytestream[3] << 0 ) + ( ( uint32_t ) context_status_bytestream[4] << 8 ) +
( ( uint32_t ) context_status_bytestream[5] << 16 ) + ( ( uint32_t ) context_status_bytestream[6] << 24 );
context_status->error_code = ( lr1110_gnss_error_code_t )( context_status_bytestream[7] >> 4 );
context_status->almanac_update_gps =
( ( context_status_bytestream[7] & LR1110_GNSS_DMC_ALMANAC_UPDATE_GPS_MASK ) != 0 ) ? true : false;
context_status->almanac_update_beidou =
( ( context_status_bytestream[7] & LR1110_GNSS_DMC_ALMANAC_UPDATE_BEIDOU_MASK ) != 0 ) ? true : false;
context_status->freq_search_space = ( lr1110_gnss_freq_search_space_t )(
( ( ( context_status_bytestream[7] & LR1110_GNSS_DMC_FREQUENCY_SEARCH_SPACE_MSB_MASK ) >>
LR1110_GNSS_DMC_FREQUENCY_SEARCH_SPACE_MSB_POS )
<< 1 ) +
( ( context_status_bytestream[8] & LR1110_GNSS_DMC_FREQUENCY_SEARCH_SPACE_LSB_MASK ) >>
LR1110_GNSS_DMC_FREQUENCY_SEARCH_SPACE_LSB_POS ) );
status = LR1110_STATUS_OK;
}
return status;
}
lr1110_status_t lr1110_gnss_get_result_destination( const uint8_t* result_buffer, const uint16_t result_buffer_size,
lr1110_gnss_destination_t* destination )
{
lr1110_status_t status = LR1110_STATUS_ERROR;
if( result_buffer_size != 0 )
{
switch( result_buffer[LR1110_GNSS_SCAN_RESULT_DESTINATION_INDEX] )
{
case LR1110_GNSS_DESTINATION_HOST:
{
*destination = LR1110_GNSS_DESTINATION_HOST;
status = LR1110_STATUS_OK;
break;
}
case LR1110_GNSS_DESTINATION_SOLVER:
{
*destination = LR1110_GNSS_DESTINATION_SOLVER;
status = LR1110_STATUS_OK;
break;
}
case LR1110_GNSS_DESTINATION_DMC:
{
*destination = LR1110_GNSS_DESTINATION_DMC;
status = LR1110_STATUS_OK;
break;
}
}
}
return status;
}
uint16_t lr1110_gnss_compute_almanac_age( uint16_t almanac_date,
uint16_t nb_days_between_epoch_and_last_gps_time_rollover,
uint16_t nb_days_since_epoch )
{
return nb_days_since_epoch - ( almanac_date + nb_days_between_epoch_and_last_gps_time_rollover );
}
/*
* -----------------------------------------------------------------------------
* --- PRIVATE FUNCTIONS DEFINITION --------------------------------------------
*/
uint32_t lr1110_gnss_uint8_to_uint32( uint8_t* value )
{
return ( ( ( uint32_t ) value[0] ) << 24 ) + ( ( ( uint32_t ) value[1] ) << 16 ) +
( ( ( uint32_t ) value[2] ) << 8 ) + ( ( ( uint32_t ) value[3] ) << 0 );
}
uint16_t lr1110_gnss_get_min_from_operand_and_max_nb_of_blocks( uint16_t operand )
{
if( operand > LR1110_GNSS_ALMANAC_UPDATE_MAX_NB_OF_BLOCKS )
{
return LR1110_GNSS_ALMANAC_UPDATE_MAX_NB_OF_BLOCKS;
}
else
{
return operand;
}
}
/* --- EOF ------------------------------------------------------------------ */
<file_sep>/src/lr1110_wifi.c
/*!
* @file lr1110_wifi.c
*
* @brief Wi-Fi passive scan driver implementation for LR1110
*
* The Clear BSD License
* Copyright Semtech Corporation 2021. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted (subject to the limitations in the disclaimer
* below) provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the Semtech corporation nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* NO EXPRESS OR IMPLIED LICENSES TO ANY PARTY'S PATENT RIGHTS ARE GRANTED BY
* THIS LICENSE. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
* CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT
* NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
* PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SEMTECH CORPORATION BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
/*
* -----------------------------------------------------------------------------
* --- DEPENDENCIES ------------------------------------------------------------
*/
#include "lr1110_wifi.h"
#include "lr1110_hal.h"
/*
* -----------------------------------------------------------------------------
* --- PRIVATE MACROS-----------------------------------------------------------
*/
#ifndef MIN
#define MIN( a, b ) ( ( a > b ) ? b : a )
#endif // MIN
/*!
* @brief Check if a value is in between min and max - included
*/
#define IS_BETWEEN( value, min, max ) ( ( min <= value ) && ( value <= max ) )
/*!
* @brief Check if a value is in between 0x80 and 0xBF - included
*/
#define IS_BETWEEN_0x80_AND_0xBF( value ) IS_BETWEEN( value, 0x80, 0xBF )
/*
* -----------------------------------------------------------------------------
* --- PRIVATE CONSTANTS -------------------------------------------------------
*/
#define LR1110_WIFI_BASIC_COMPLETE_RESULT_SIZE ( 22 )
#define LR1110_WIFI_BASIC_MAC_TYPE_CHANNEL_RESULT_SIZE ( 9 )
#define LR1110_WIFI_MAX_SIZE_PER_SPI( single_size ) \
( single_size * ( LR1110_WIFI_MAX_RESULT_PER_TRANSACTION( single_size ) ) )
#define LR1110_WIFI_MAX_RESULT_PER_TRANSACTION( single_size ) \
( MIN( ( LR1110_WIFI_READ_RESULT_LIMIT ) / ( single_size ), LR1110_WIFI_N_RESULTS_MAX_PER_CHUNK ) )
#define LR1110_WIFI_ALL_CUMULATIVE_TIMING_SIZE ( 16 )
#define LR1110_WIFI_VERSION_SIZE ( 2 )
#define LR1110_WIFI_READ_RESULT_LIMIT ( 1020 )
#define LR1110_WIFI_COUNTRY_RESULT_LENGTH_SIZE ( 1 )
#define LR1110_WIFI_EXTENDED_COMPLETE_RESULT_SIZE ( 79 )
#define LR1110_WIFI_SCAN_SINGLE_COUNTRY_CODE_RESULT_SIZE ( 10 )
#define LR1110_WIFI_MAX_COUNTRY_CODE_RESULT_SIZE \
( LR1110_WIFI_MAX_COUNTRY_CODE * LR1110_WIFI_SCAN_SINGLE_COUNTRY_CODE_RESULT_SIZE )
// Command length
#define LR1110_WIFI_SCAN_CMD_LENGTH ( 2 + 9 )
#define LR1110_WIFI_SEARCH_COUNTRY_CODE_CMD_LENGTH ( 2 + 7 )
#define LR1110_WIFI_SCAN_TIME_LIMIT_CMD_LENGTH ( 2 + 9 )
#define LR1110_WIFI_COUNTRY_CODE_TIME_LIMIT_CMD_LENGTH ( 2 + 7 )
#define LR1110_WIFI_GET_RESULT_SIZE_CMD_LENGTH ( 2 )
#define LR1110_WIFI_READ_RESULT_CMD_LENGTH ( 2 + 3 )
#define LR1110_WIFI_RESET_CUMUL_TIMING_CMD_LENGTH ( 2 )
#define LR1110_WIFI_READ_CUMUL_TIMING_CMD_LENGTH ( 2 )
#define LR1110_WIFI_GET_SIZE_COUNTRY_RESULT_CMD_LENGTH ( 2 )
#define LR1110_WIFI_READ_COUNTRY_CODE_CMD_LENGTH ( 2 + 2 )
#define LR1110_WIFI_CFG_TIMESTAMP_AP_PHONE_CMD_LENGTH ( 2 + 4 )
#define LR1110_WIFI_GET_VERSION_CMD_LENGTH ( 2 )
/*
* -----------------------------------------------------------------------------
* --- PRIVATE TYPES -----------------------------------------------------------
*/
/*!
* @brief Operating codes for Wi-Fi-related operations
*/
enum
{
LR1110_WIFI_SCAN_OC = 0x0300,
LR1110_WIFI_SCAN_TIME_LIMIT = 0x0301,
LR1110_WIFI_SEARCH_COUNTRY_CODE_OC = 0x0302,
LR1110_WIFI_COUNTRY_CODE_TIME_LIMIT_OC = 0x0303,
LR1110_WIFI_GET_RESULT_SIZE_OC = 0x0305,
LR1110_WIFI_READ_RESULT_OC = 0x0306,
LR1110_WIFI_RESET_CUMUL_TIMING_OC = 0x0307,
LR1110_WIFI_READ_CUMUL_TIMING_OC = 0x0308,
LR1110_WIFI_GET_SIZE_COUNTRY_RESULT_OC = 0x0309,
LR1110_WIFI_READ_COUNTRY_CODE_OC = 0x030A,
LR1110_WIFI_CONFIGURE_TIMESTAMP_AP_PHONE_OC = 0x030B,
LR1110_WIFI_GET_VERSION_OC = 0x0320,
};
/*!
* @brief Wi-Fi scan results interface
*/
typedef union
{
lr1110_wifi_basic_complete_result_t* basic_complete;
lr1110_wifi_basic_mac_type_channel_result_t* basic_mac_type_channel;
lr1110_wifi_extended_full_result_t* extended_complete;
} lr1110_wifi_result_interface_t;
/*
* -----------------------------------------------------------------------------
* --- PRIVATE VARIABLES -------------------------------------------------------
*/
/*
* -----------------------------------------------------------------------------
* --- PRIVATE FUNCTIONS DECLARATION -------------------------------------------
*/
/*!
* @brief Return a uint16 value by reading a buffer of uint8 from index.
*
* This function interpret the array MSB first. It is equivalent to:
* return array[index] * 256 + array[index+1]
*
* @returns The uint16 value
*/
static uint16_t uint16_from_array( const uint8_t* array, const uint16_t index );
/*!
* @brief Return a uint64 value by reading a buffer of uint8 from index.
*
* This function interpret the array MSB first.
*
* @returns The uint64 value
*/
static uint64_t uint64_from_array( const uint8_t* array, const uint16_t index );
/*!
* @brief Return a uint64 value by reading a buffer of uint8 from index.
*
* This function interpret the array MSB first.
*
* @returns The uint64 value
*/
static void generic_results_interpreter( const uint8_t n_result_to_parse, const uint8_t index_result_start_writing,
const uint8_t* buffer, lr1110_wifi_result_interface_t result_interface,
const lr1110_wifi_result_format_t format_code );
/*!
* @brief Parse basic complete result
*/
static void interpret_basic_complete_result_from_buffer( const uint8_t nb_results,
const uint8_t index_result_start_writing,
const uint8_t* buffer,
lr1110_wifi_basic_complete_result_t* result );
/*!
* @brief Parse basic MAC - type - channel result
*/
static void interpret_basic_mac_type_channel_result_from_buffer( const uint8_t nb_results,
const uint8_t index_result_start_writing,
const uint8_t* buffer,
lr1110_wifi_basic_mac_type_channel_result_t* result );
/*!
* @brief Parse extended full result
*/
static void interpret_extended_full_result_from_buffer( const uint8_t nb_results,
const uint8_t index_result_start_writing, const uint8_t* buffer,
lr1110_wifi_extended_full_result_t* result );
/*!
* @brief Parse basic MAC - type - channel result
*/
static lr1110_status_t fetch_and_aggregate_all_results( const void* context, const uint8_t index_result_start,
const uint8_t nb_results,
const uint8_t nb_results_per_chunk_max,
const lr1110_wifi_result_format_t result_format_code,
uint8_t* result_buffer,
lr1110_wifi_result_interface_t result_structures );
/*!
* @brief Share the size of a result format
*
* @returns Size in byte of the format given as parameter
*/
static uint8_t lr1110_wifi_get_result_size_from_format( const lr1110_wifi_result_format_t format );
/*!
* @brief Fetch results from the radio after a successful Wi-Fi passive scan
*
* @returns Operation status
*/
static lr1110_hal_status_t lr1110_wifi_read_results_helper( const void* context, const uint8_t start_index,
const uint8_t n_elem, uint8_t* buffer,
const lr1110_wifi_result_format_t result_format );
/*!
* @brief Extract Wi-Fi MAC address from a buffer
*/
static void lr1110_wifi_read_mac_address_from_buffer( const uint8_t* buffer, const uint16_t index_in_buffer,
lr1110_wifi_mac_address_t mac_address );
/*!
* @brief Share the format code corresponding to a result format
*
* @returns Format code
*/
static uint8_t lr1110_wifi_get_format_code( const lr1110_wifi_result_format_t format );
/*
* -----------------------------------------------------------------------------
* --- PUBLIC FUNCTIONS DEFINITION ---------------------------------------------
*/
lr1110_status_t lr1110_wifi_scan( const void* context, const lr1110_wifi_signal_type_scan_t signal_type,
const lr1110_wifi_channel_mask_t channels, const lr1110_wifi_mode_t scan_mode,
const uint8_t max_results, const uint8_t nb_scan_per_channel,
const uint16_t timeout_in_ms, const bool abort_on_timeout )
{
const uint8_t cbuffer[LR1110_WIFI_SCAN_CMD_LENGTH] = {
( uint8_t )( LR1110_WIFI_SCAN_OC >> 8 ),
( uint8_t )( LR1110_WIFI_SCAN_OC >> 0 ),
( uint8_t ) signal_type,
( uint8_t )( channels >> 8 ),
( uint8_t )( channels >> 0 ),
( uint8_t ) scan_mode,
max_results,
nb_scan_per_channel,
( uint8_t )( timeout_in_ms >> 8 ),
( uint8_t )( timeout_in_ms >> 0 ),
( uint8_t )( ( abort_on_timeout == true ) ? 1 : 0 ),
};
return ( lr1110_status_t ) lr1110_hal_write( context, cbuffer, LR1110_WIFI_SCAN_CMD_LENGTH, 0, 0 );
}
lr1110_status_t lr1110_wifi_search_country_code( const void* context, const lr1110_wifi_channel_mask_t channels_mask,
const uint8_t nb_max_results, const uint8_t nb_scan_per_channel,
const uint16_t timeout_in_ms, const bool abort_on_timeout )
{
const uint8_t cbuffer[LR1110_WIFI_SEARCH_COUNTRY_CODE_CMD_LENGTH] = {
( uint8_t )( LR1110_WIFI_SEARCH_COUNTRY_CODE_OC >> 8 ),
( uint8_t )( LR1110_WIFI_SEARCH_COUNTRY_CODE_OC >> 0 ),
( uint8_t )( channels_mask >> 8 ),
( uint8_t )( channels_mask >> 0 ),
nb_max_results,
nb_scan_per_channel,
( uint8_t )( timeout_in_ms >> 8 ),
( uint8_t )( timeout_in_ms >> 0 ),
( uint8_t )( ( abort_on_timeout == true ) ? 1 : 0 ),
};
return ( lr1110_status_t ) lr1110_hal_write( context, cbuffer, LR1110_WIFI_SEARCH_COUNTRY_CODE_CMD_LENGTH, 0, 0 );
}
lr1110_status_t lr1110_wifi_scan_time_limit( const void* radio, const lr1110_wifi_signal_type_scan_t signal_type,
const lr1110_wifi_channel_mask_t channels,
const lr1110_wifi_mode_t scan_mode, const uint8_t max_results,
const uint16_t timeout_per_channel_ms, const uint16_t timeout_per_scan_ms )
{
const uint8_t cbuffer[LR1110_WIFI_SCAN_TIME_LIMIT_CMD_LENGTH] = {
( uint8_t )( LR1110_WIFI_SCAN_TIME_LIMIT >> 8 ),
( uint8_t )( LR1110_WIFI_SCAN_TIME_LIMIT >> 0 ),
( uint8_t ) signal_type,
( uint8_t )( channels >> 8 ),
( uint8_t )( channels >> 0 ),
( uint8_t ) scan_mode,
max_results,
( uint8_t )( timeout_per_channel_ms >> 8 ),
( uint8_t )( timeout_per_channel_ms >> 0 ),
( uint8_t )( timeout_per_scan_ms >> 8 ),
( uint8_t )( timeout_per_scan_ms >> 0 ),
};
return ( lr1110_status_t ) lr1110_hal_write( radio, cbuffer, LR1110_WIFI_SCAN_TIME_LIMIT_CMD_LENGTH, 0, 0 );
}
lr1110_status_t lr1110_wifi_search_country_code_time_limit( const void* radio,
const lr1110_wifi_channel_mask_t channels,
const uint8_t max_results,
const uint16_t timeout_per_channel_ms,
const uint16_t timeout_per_scan_ms )
{
const uint8_t cbuffer[LR1110_WIFI_COUNTRY_CODE_TIME_LIMIT_CMD_LENGTH] = {
( uint8_t )( LR1110_WIFI_COUNTRY_CODE_TIME_LIMIT_OC >> 8 ),
( uint8_t )( LR1110_WIFI_COUNTRY_CODE_TIME_LIMIT_OC >> 0 ),
( uint8_t )( channels >> 8 ),
( uint8_t )( channels >> 0 ),
( uint8_t ) max_results,
( uint8_t )( timeout_per_channel_ms >> 8 ),
( uint8_t )( timeout_per_channel_ms >> 0 ),
( uint8_t )( timeout_per_scan_ms >> 8 ),
( uint8_t )( timeout_per_scan_ms >> 0 ),
};
return ( lr1110_status_t ) lr1110_hal_write( radio, cbuffer, LR1110_WIFI_COUNTRY_CODE_TIME_LIMIT_CMD_LENGTH, 0, 0 );
}
lr1110_status_t lr1110_wifi_get_nb_results( const void* context, uint8_t* nb_results )
{
const uint8_t cbuffer[LR1110_WIFI_GET_RESULT_SIZE_CMD_LENGTH] = {
( uint8_t )( LR1110_WIFI_GET_RESULT_SIZE_OC >> 8 ),
( uint8_t )( LR1110_WIFI_GET_RESULT_SIZE_OC >> 0 ),
};
return ( lr1110_status_t ) lr1110_hal_read( context, cbuffer, LR1110_WIFI_GET_RESULT_SIZE_CMD_LENGTH, nb_results,
sizeof( *nb_results ) );
}
lr1110_status_t lr1110_wifi_read_basic_complete_results( const void* context, const uint8_t start_result_index,
const uint8_t nb_results,
lr1110_wifi_basic_complete_result_t* results )
{
uint8_t result_buffer[LR1110_WIFI_MAX_SIZE_PER_SPI( LR1110_WIFI_BASIC_COMPLETE_RESULT_SIZE )] = { 0 };
const uint8_t nb_results_per_chunk_max =
LR1110_WIFI_MAX_RESULT_PER_TRANSACTION( LR1110_WIFI_BASIC_COMPLETE_RESULT_SIZE );
lr1110_wifi_result_interface_t result_interface = { 0 };
result_interface.basic_complete = results;
return fetch_and_aggregate_all_results( context, start_result_index, nb_results, nb_results_per_chunk_max,
LR1110_WIFI_RESULT_FORMAT_BASIC_COMPLETE, result_buffer, result_interface );
}
lr1110_status_t lr1110_wifi_read_basic_mac_type_channel_results( const void* context, const uint8_t start_result_index,
const uint8_t nb_results,
lr1110_wifi_basic_mac_type_channel_result_t* results )
{
uint8_t result_buffer[LR1110_WIFI_MAX_SIZE_PER_SPI( LR1110_WIFI_BASIC_MAC_TYPE_CHANNEL_RESULT_SIZE )] = { 0 };
const uint8_t nb_results_per_chunk_max =
LR1110_WIFI_MAX_RESULT_PER_TRANSACTION( LR1110_WIFI_BASIC_MAC_TYPE_CHANNEL_RESULT_SIZE );
lr1110_wifi_result_interface_t result_interface = { 0 };
result_interface.basic_mac_type_channel = results;
return fetch_and_aggregate_all_results( context, start_result_index, nb_results, nb_results_per_chunk_max,
LR1110_WIFI_RESULT_FORMAT_BASIC_MAC_TYPE_CHANNEL, result_buffer,
result_interface );
}
lr1110_status_t lr1110_wifi_read_extended_full_results( const void* radio, const uint8_t start_result_index,
const uint8_t nb_results,
lr1110_wifi_extended_full_result_t* results )
{
uint8_t result_buffer[LR1110_WIFI_MAX_SIZE_PER_SPI( LR1110_WIFI_EXTENDED_COMPLETE_RESULT_SIZE )] = { 0 };
const uint8_t nb_results_per_chunk_max =
LR1110_WIFI_MAX_RESULT_PER_TRANSACTION( LR1110_WIFI_EXTENDED_COMPLETE_RESULT_SIZE );
lr1110_wifi_result_interface_t result_interface = { 0 };
result_interface.extended_complete = results;
return fetch_and_aggregate_all_results( radio, start_result_index, nb_results, nb_results_per_chunk_max,
LR1110_WIFI_RESULT_FORMAT_EXTENDED_FULL, result_buffer, result_interface );
}
lr1110_status_t lr1110_wifi_reset_cumulative_timing( const void* context )
{
const uint8_t cbuffer[LR1110_WIFI_RESET_CUMUL_TIMING_CMD_LENGTH] = {
( uint8_t )( LR1110_WIFI_RESET_CUMUL_TIMING_OC >> 8 ),
( uint8_t )( LR1110_WIFI_RESET_CUMUL_TIMING_OC >> 0 ),
};
return ( lr1110_status_t ) lr1110_hal_write( context, cbuffer, LR1110_WIFI_RESET_CUMUL_TIMING_CMD_LENGTH, 0, 0 );
}
lr1110_status_t lr1110_wifi_read_cumulative_timing( const void* context, lr1110_wifi_cumulative_timings_t* timing )
{
const uint8_t cbuffer[LR1110_WIFI_READ_CUMUL_TIMING_CMD_LENGTH] = {
( uint8_t )( LR1110_WIFI_READ_CUMUL_TIMING_OC >> 8 ),
( uint8_t )( LR1110_WIFI_READ_CUMUL_TIMING_OC >> 0 ),
};
uint8_t buffer_out[LR1110_WIFI_ALL_CUMULATIVE_TIMING_SIZE] = { 0 };
const lr1110_hal_status_t hal_status = lr1110_hal_read( context, cbuffer, LR1110_WIFI_READ_CUMUL_TIMING_CMD_LENGTH,
buffer_out, LR1110_WIFI_ALL_CUMULATIVE_TIMING_SIZE );
if( hal_status == LR1110_HAL_STATUS_OK )
{
timing->rx_detection_us =
( buffer_out[0] << 24 ) + ( buffer_out[1] << 16 ) + ( buffer_out[2] << 8 ) + buffer_out[3];
timing->rx_correlation_us =
( buffer_out[4] << 24 ) + ( buffer_out[5] << 16 ) + ( buffer_out[6] << 8 ) + buffer_out[7];
timing->rx_capture_us =
( buffer_out[8] << 24 ) + ( buffer_out[9] << 16 ) + ( buffer_out[10] << 8 ) + buffer_out[11];
timing->demodulation_us =
( buffer_out[12] << 24 ) + ( buffer_out[13] << 16 ) + ( buffer_out[14] << 8 ) + buffer_out[15];
}
return ( lr1110_status_t ) hal_status;
}
lr1110_status_t lr1110_wifi_get_nb_country_code_results( const void* context, uint8_t* country_result_size )
{
const uint8_t cbuffer[LR1110_WIFI_GET_SIZE_COUNTRY_RESULT_CMD_LENGTH] = {
( uint8_t )( LR1110_WIFI_GET_SIZE_COUNTRY_RESULT_OC >> 8 ),
( uint8_t )( LR1110_WIFI_GET_SIZE_COUNTRY_RESULT_OC >> 0 ),
};
uint8_t rbuffer[LR1110_WIFI_COUNTRY_RESULT_LENGTH_SIZE] = { 0 };
const lr1110_hal_status_t hal_status =
lr1110_hal_read( context, cbuffer, LR1110_WIFI_GET_SIZE_COUNTRY_RESULT_CMD_LENGTH, rbuffer,
LR1110_WIFI_COUNTRY_RESULT_LENGTH_SIZE );
if( hal_status == LR1110_HAL_STATUS_OK )
{
( *country_result_size ) = rbuffer[0];
}
return ( lr1110_status_t ) hal_status;
}
lr1110_status_t lr1110_wifi_read_country_code_results( const void* context, const uint8_t start_result_index,
const uint8_t nb_country_results,
lr1110_wifi_country_code_t* country_code_results )
{
const uint8_t cbuffer[LR1110_WIFI_READ_COUNTRY_CODE_CMD_LENGTH] = {
( uint8_t )( LR1110_WIFI_READ_COUNTRY_CODE_OC >> 8 ),
( uint8_t )( LR1110_WIFI_READ_COUNTRY_CODE_OC >> 0 ),
start_result_index,
nb_country_results,
};
uint8_t rbuffer[LR1110_WIFI_MAX_COUNTRY_CODE_RESULT_SIZE] = { 0 };
const uint16_t country_code_result_size_to_read =
nb_country_results * LR1110_WIFI_SCAN_SINGLE_COUNTRY_CODE_RESULT_SIZE;
const lr1110_hal_status_t hal_status = lr1110_hal_read( context, cbuffer, LR1110_WIFI_READ_COUNTRY_CODE_CMD_LENGTH,
rbuffer, country_code_result_size_to_read );
if( hal_status == LR1110_HAL_STATUS_OK )
{
for( uint8_t result_index = 0; result_index < nb_country_results; result_index++ )
{
const uint8_t local_index = result_index * LR1110_WIFI_SCAN_SINGLE_COUNTRY_CODE_RESULT_SIZE;
lr1110_wifi_country_code_t* local_country_code_result = &country_code_results[result_index];
local_country_code_result->country_code[0] = rbuffer[local_index + 0];
local_country_code_result->country_code[1] = rbuffer[local_index + 1];
local_country_code_result->io_regulation = rbuffer[local_index + 2];
local_country_code_result->channel_info_byte = rbuffer[local_index + 3];
for( uint8_t field_mac_index = 0; field_mac_index < LR1110_WIFI_MAC_ADDRESS_LENGTH; field_mac_index++ )
{
local_country_code_result->mac_address[field_mac_index] =
rbuffer[local_index + ( LR1110_WIFI_MAC_ADDRESS_LENGTH - field_mac_index - 1 ) + 4];
}
}
}
return ( lr1110_status_t ) hal_status;
}
lr1110_status_t lr1110_wifi_cfg_timestamp_ap_phone( const void* context, uint32_t timestamp_in_s )
{
const uint8_t cbuffer[LR1110_WIFI_CFG_TIMESTAMP_AP_PHONE_CMD_LENGTH] = {
( uint8_t )( LR1110_WIFI_CONFIGURE_TIMESTAMP_AP_PHONE_OC >> 8 ),
( uint8_t )( LR1110_WIFI_CONFIGURE_TIMESTAMP_AP_PHONE_OC >> 0 ),
( uint8_t )( timestamp_in_s >> 24 ),
( uint8_t )( timestamp_in_s >> 16 ),
( uint8_t )( timestamp_in_s >> 8 ),
( uint8_t )( timestamp_in_s >> 0 ),
};
return ( lr1110_status_t ) lr1110_hal_write( context, cbuffer, LR1110_WIFI_CFG_TIMESTAMP_AP_PHONE_CMD_LENGTH, 0,
0 );
}
lr1110_status_t lr1110_wifi_read_version( const void* context, lr1110_wifi_version_t* wifi_version )
{
const uint8_t cbuffer[LR1110_WIFI_GET_VERSION_CMD_LENGTH] = {
( uint8_t )( LR1110_WIFI_GET_VERSION_OC >> 8 ),
( uint8_t )( LR1110_WIFI_GET_VERSION_OC >> 0 ),
};
uint8_t rbuffer[LR1110_WIFI_VERSION_SIZE] = { 0 };
const lr1110_hal_status_t hal_status =
lr1110_hal_read( context, cbuffer, LR1110_WIFI_GET_VERSION_CMD_LENGTH, rbuffer, LR1110_WIFI_VERSION_SIZE );
if( hal_status == LR1110_HAL_STATUS_OK )
{
wifi_version->major = rbuffer[0];
wifi_version->minor = rbuffer[1];
}
return ( lr1110_status_t ) hal_status;
}
uint8_t lr1110_wifi_get_nb_results_max_per_chunk( void )
{
return ( uint8_t ) LR1110_WIFI_N_RESULTS_MAX_PER_CHUNK;
}
void lr1110_wifi_parse_channel_info( const lr1110_wifi_channel_info_byte_t channel_info, lr1110_wifi_channel_t* channel,
bool* rssi_validity, lr1110_wifi_mac_origin_t* mac_origin_estimation )
{
( *channel ) = lr1110_wifi_extract_channel_from_info_byte( channel_info );
( *mac_origin_estimation ) = ( lr1110_wifi_mac_origin_t )( ( channel_info & 0x30 ) >> 4 );
( *rssi_validity ) = ( ( channel_info & 0x40 ) == 0 ) ? true : false;
}
lr1110_wifi_channel_t lr1110_wifi_extract_channel_from_info_byte( const lr1110_wifi_channel_info_byte_t channel_info )
{
return ( lr1110_wifi_channel_t )( channel_info & 0x0F );
}
void lr1110_wifi_parse_frame_type_info( const lr1110_wifi_frame_type_info_byte_t frame_type_info,
lr1110_wifi_frame_type_t* frame_type,
lr1110_wifi_frame_sub_type_t* frame_sub_type, bool* to_ds, bool* from_ds )
{
( *frame_type ) = ( lr1110_wifi_frame_type_t )( ( frame_type_info >> 6 ) & 0x03 );
( *frame_sub_type ) = ( lr1110_wifi_frame_sub_type_t )( ( frame_type_info >> 2 ) & 0x0F );
( *to_ds ) = ( bool ) ( ( frame_type_info >> 1 ) & 0x01 );
( *from_ds ) = ( bool ) ( frame_type_info & 0x01 );
}
void lr1110_wifi_parse_data_rate_info( const lr1110_wifi_datarate_info_byte_t data_rate_info,
lr1110_wifi_signal_type_result_t* wifi_signal_type,
lr1110_wifi_datarate_t* wifi_data_rate )
{
( *wifi_signal_type ) = lr1110_wifi_extract_signal_type_from_data_rate_info( data_rate_info );
( *wifi_data_rate ) = ( lr1110_wifi_datarate_t )( data_rate_info >> 2 );
}
lr1110_wifi_signal_type_result_t lr1110_wifi_extract_signal_type_from_data_rate_info(
const lr1110_wifi_datarate_info_byte_t data_rate_info )
{
return ( lr1110_wifi_signal_type_result_t )( data_rate_info & 0x03 );
}
/*
* -----------------------------------------------------------------------------
* --- PRIVATE FUNCTIONS DEFINITION --------------------------------------------
*/
static lr1110_hal_status_t lr1110_wifi_read_results_helper( const void* context, const uint8_t start_index,
const uint8_t n_elem, uint8_t* buffer,
const lr1110_wifi_result_format_t result_format )
{
const uint8_t size_single_elem = lr1110_wifi_get_result_size_from_format( result_format );
const uint8_t result_format_code = lr1110_wifi_get_format_code( result_format );
const uint8_t cbuffer[LR1110_WIFI_READ_RESULT_CMD_LENGTH] = { ( uint8_t )( LR1110_WIFI_READ_RESULT_OC >> 8 ),
( uint8_t )( LR1110_WIFI_READ_RESULT_OC & 0x00FF ),
start_index, n_elem, result_format_code };
const uint16_t size_total = n_elem * size_single_elem;
return lr1110_hal_read( context, cbuffer, LR1110_WIFI_READ_RESULT_CMD_LENGTH, buffer, size_total );
}
static uint16_t uint16_from_array( const uint8_t* array, const uint16_t index )
{
return ( uint16_t )( array[index] << 8 ) + ( ( uint16_t )( array[index + 1] ) );
}
static uint64_t uint64_from_array( const uint8_t* array, const uint16_t index )
{
return ( ( uint64_t )( array[index] ) << 56 ) + ( ( uint64_t )( array[index + 1] ) << 48 ) +
( ( uint64_t )( array[index + 2] ) << 40 ) + ( ( uint64_t )( array[index + 3] ) << 32 ) +
( ( uint64_t )( array[index + 4] ) << 24 ) + ( ( uint64_t )( array[index + 5] ) << 16 ) +
( ( uint64_t )( array[index + 6] ) << 8 ) + ( uint64_t )( array[index + 7] );
}
static void lr1110_wifi_read_mac_address_from_buffer( const uint8_t* buffer, const uint16_t index_in_buffer,
lr1110_wifi_mac_address_t mac_address )
{
for( uint8_t field_mac_index = 0; field_mac_index < LR1110_WIFI_MAC_ADDRESS_LENGTH; field_mac_index++ )
{
mac_address[field_mac_index] = buffer[index_in_buffer + field_mac_index];
}
}
static uint8_t lr1110_wifi_get_format_code( const lr1110_wifi_result_format_t format )
{
uint8_t format_code = 0x00;
switch( format )
{
case LR1110_WIFI_RESULT_FORMAT_BASIC_COMPLETE:
{
format_code = 0x01;
break;
}
case LR1110_WIFI_RESULT_FORMAT_BASIC_MAC_TYPE_CHANNEL:
{
format_code = 0x04;
break;
}
case LR1110_WIFI_RESULT_FORMAT_EXTENDED_FULL:
{
format_code = 0x01;
break;
}
}
return format_code;
}
static uint8_t lr1110_wifi_get_result_size_from_format( const lr1110_wifi_result_format_t format )
{
uint8_t result_size = 0;
switch( format )
{
case LR1110_WIFI_RESULT_FORMAT_BASIC_COMPLETE:
{
result_size = LR1110_WIFI_BASIC_COMPLETE_RESULT_SIZE;
break;
}
case LR1110_WIFI_RESULT_FORMAT_BASIC_MAC_TYPE_CHANNEL:
{
result_size = LR1110_WIFI_BASIC_MAC_TYPE_CHANNEL_RESULT_SIZE;
break;
}
case LR1110_WIFI_RESULT_FORMAT_EXTENDED_FULL:
{
result_size = LR1110_WIFI_EXTENDED_COMPLETE_RESULT_SIZE;
break;
}
}
return result_size;
}
static lr1110_status_t fetch_and_aggregate_all_results( const void* context, const uint8_t index_result_start,
const uint8_t nb_results,
const uint8_t nb_results_per_chunk_max,
const lr1110_wifi_result_format_t result_format_code,
uint8_t* result_buffer,
lr1110_wifi_result_interface_t result_structures )
{
uint8_t index_to_read = index_result_start;
uint8_t index_result_start_writing = 0;
uint8_t remaining_results = nb_results;
lr1110_hal_status_t hal_status = LR1110_HAL_STATUS_OK;
while( remaining_results > 0 )
{
uint8_t results_to_read = MIN( remaining_results, nb_results_per_chunk_max );
lr1110_hal_status_t local_hal_status = lr1110_wifi_read_results_helper( context, index_to_read, results_to_read,
result_buffer, result_format_code );
if( local_hal_status != LR1110_HAL_STATUS_OK )
{
return ( lr1110_status_t ) local_hal_status;
}
generic_results_interpreter( results_to_read, index_result_start_writing, result_buffer, result_structures,
result_format_code );
// Reset the content of the result_buffer in case there are still results to fetch
{
const uint16_t result_buffer_size =
LR1110_WIFI_MAX_SIZE_PER_SPI( lr1110_wifi_get_result_size_from_format( result_format_code ) );
for( uint16_t index = 0; index < result_buffer_size; index++ )
{
result_buffer[index] = 0;
}
}
index_to_read += results_to_read;
index_result_start_writing += results_to_read;
remaining_results -= results_to_read;
}
return ( lr1110_status_t ) hal_status;
}
static void generic_results_interpreter( const uint8_t n_result_to_parse, const uint8_t index_result_start_writing,
const uint8_t* buffer, lr1110_wifi_result_interface_t result_interface,
const lr1110_wifi_result_format_t format_code )
{
switch( format_code )
{
case LR1110_WIFI_RESULT_FORMAT_BASIC_COMPLETE:
{
interpret_basic_complete_result_from_buffer( n_result_to_parse, index_result_start_writing, buffer,
result_interface.basic_complete );
break;
}
case LR1110_WIFI_RESULT_FORMAT_BASIC_MAC_TYPE_CHANNEL:
{
interpret_basic_mac_type_channel_result_from_buffer( n_result_to_parse, index_result_start_writing, buffer,
result_interface.basic_mac_type_channel );
break;
}
case LR1110_WIFI_RESULT_FORMAT_EXTENDED_FULL:
{
interpret_extended_full_result_from_buffer( n_result_to_parse, index_result_start_writing, buffer,
result_interface.extended_complete );
break;
}
}
}
static void interpret_basic_complete_result_from_buffer( const uint8_t nb_results,
const uint8_t index_result_start_writing,
const uint8_t* buffer,
lr1110_wifi_basic_complete_result_t* result )
{
for( uint8_t result_index = 0; result_index < nb_results; result_index++ )
{
const uint16_t local_index_start = LR1110_WIFI_BASIC_COMPLETE_RESULT_SIZE * result_index;
lr1110_wifi_basic_complete_result_t* local_wifi_result = &result[index_result_start_writing + result_index];
local_wifi_result->data_rate_info_byte = buffer[local_index_start + 0];
local_wifi_result->channel_info_byte = buffer[local_index_start + 1];
local_wifi_result->rssi = buffer[local_index_start + 2];
local_wifi_result->frame_type_info_byte = buffer[local_index_start + 3];
lr1110_wifi_read_mac_address_from_buffer( buffer, local_index_start + 4, local_wifi_result->mac_address );
local_wifi_result->phi_offset = uint16_from_array( buffer, local_index_start + 10 );
local_wifi_result->timestamp_us = uint64_from_array( buffer, local_index_start + 12 );
local_wifi_result->beacon_period_tu = uint16_from_array( buffer, local_index_start + 20 );
}
}
static void interpret_basic_mac_type_channel_result_from_buffer( const uint8_t nb_results,
const uint8_t index_result_start_writing,
const uint8_t* buffer,
lr1110_wifi_basic_mac_type_channel_result_t* result )
{
for( uint8_t result_index = 0; result_index < nb_results; result_index++ )
{
const uint16_t local_index_start = LR1110_WIFI_BASIC_MAC_TYPE_CHANNEL_RESULT_SIZE * result_index;
lr1110_wifi_basic_mac_type_channel_result_t* local_wifi_result =
&result[index_result_start_writing + result_index];
local_wifi_result->data_rate_info_byte = buffer[local_index_start + 0];
local_wifi_result->channel_info_byte = buffer[local_index_start + 1];
local_wifi_result->rssi = buffer[local_index_start + 2];
lr1110_wifi_read_mac_address_from_buffer( buffer, local_index_start + 3, local_wifi_result->mac_address );
}
}
void interpret_extended_full_result_from_buffer( const uint8_t nb_results, const uint8_t index_result_start_writing,
const uint8_t* buffer, lr1110_wifi_extended_full_result_t* result )
{
for( uint8_t result_index = 0; result_index < nb_results; result_index++ )
{
const uint16_t local_index_start = LR1110_WIFI_EXTENDED_COMPLETE_RESULT_SIZE * result_index;
lr1110_wifi_extended_full_result_t* local_wifi_result = &result[index_result_start_writing + result_index];
local_wifi_result->data_rate_info_byte = buffer[local_index_start + 0];
local_wifi_result->channel_info_byte = buffer[local_index_start + 1];
local_wifi_result->rssi = buffer[local_index_start + 2];
local_wifi_result->rate = buffer[local_index_start + 3];
local_wifi_result->service = uint16_from_array( buffer, local_index_start + 4 );
local_wifi_result->length = uint16_from_array( buffer, local_index_start + 6 );
local_wifi_result->frame_control = uint16_from_array( buffer, local_index_start + 8 );
lr1110_wifi_read_mac_address_from_buffer( buffer, local_index_start + 10, local_wifi_result->mac_address_1 );
lr1110_wifi_read_mac_address_from_buffer( buffer, local_index_start + 16, local_wifi_result->mac_address_2 );
lr1110_wifi_read_mac_address_from_buffer( buffer, local_index_start + 22, local_wifi_result->mac_address_3 );
local_wifi_result->timestamp_us = uint64_from_array( buffer, local_index_start + 28 );
local_wifi_result->beacon_period_tu = uint16_from_array( buffer, local_index_start + 36 );
local_wifi_result->seq_control = uint16_from_array( buffer, local_index_start + 38 );
for( uint8_t ssid_index = 0; ssid_index < LR1110_WIFI_RESULT_SSID_LENGTH; ssid_index++ )
{
local_wifi_result->ssid_bytes[ssid_index] = buffer[local_index_start + ssid_index + 40];
}
local_wifi_result->current_channel = buffer[local_index_start + 72];
local_wifi_result->country_code = uint16_from_array( buffer, local_index_start + 73 );
local_wifi_result->io_regulation = buffer[local_index_start + 75];
local_wifi_result->fcs_check_byte.is_fcs_checked = ( ( buffer[local_index_start + 76] & 0x01 ) == 0x01 );
local_wifi_result->fcs_check_byte.is_fcs_ok = ( ( buffer[local_index_start + 76] & 0x02 ) == 0x02 );
local_wifi_result->phi_offset = uint16_from_array( buffer, local_index_start + 77 );
}
}
bool lr1110_wifi_is_well_formed_utf8_byte_sequence( const uint8_t* buffer, const uint8_t length )
{
uint8_t index = 0;
while( index < length )
{
if( IS_BETWEEN( buffer[index], 0x00, 0x7F ) )
{
index += 1;
continue;
}
if( length - index >= 2 )
{
if( IS_BETWEEN( buffer[index], 0xC2, 0xDF ) && IS_BETWEEN_0x80_AND_0xBF( buffer[index + 1] ) )
{
index += 2;
continue;
}
if( length - index >= 3 )
{
if( ( buffer[index] == 0xE0 ) && IS_BETWEEN( buffer[index + 1], 0xA0, 0xBF ) &&
IS_BETWEEN_0x80_AND_0xBF( buffer[index + 2] ) )
{
index += 3;
continue;
}
else if( IS_BETWEEN( buffer[index], 0xE1, 0xEC ) && IS_BETWEEN_0x80_AND_0xBF( buffer[index + 1] ) &&
IS_BETWEEN_0x80_AND_0xBF( buffer[index + 2] ) )
{
index += 3;
continue;
}
else if( ( buffer[index] == 0xED ) && IS_BETWEEN( buffer[index + 1], 0x80, 0x9F ) &&
IS_BETWEEN_0x80_AND_0xBF( buffer[index + 2] ) )
{
index += 3;
continue;
}
else if( IS_BETWEEN( buffer[index], 0xEE, 0xEF ) && IS_BETWEEN_0x80_AND_0xBF( buffer[index + 1] ) &&
IS_BETWEEN_0x80_AND_0xBF( buffer[index + 2] ) )
{
index += 3;
continue;
}
if( length - index >= 4 )
{
if( ( buffer[index] == 0xF0 ) && IS_BETWEEN( buffer[index + 1], 0x90, 0xBF ) &&
IS_BETWEEN_0x80_AND_0xBF( buffer[index + 2] ) && IS_BETWEEN_0x80_AND_0xBF( buffer[index + 3] ) )
{
index += 4;
continue;
}
else if( IS_BETWEEN( buffer[index], 0xF1, 0xF3 ) && IS_BETWEEN_0x80_AND_0xBF( buffer[index + 1] ) &&
IS_BETWEEN_0x80_AND_0xBF( buffer[index + 2] ) &&
IS_BETWEEN_0x80_AND_0xBF( buffer[index + 3] ) )
{
index += 4;
continue;
}
else if( ( buffer[index] == 0xF4 ) && IS_BETWEEN( buffer[index + 1], 0x80, 0x8F ) &&
IS_BETWEEN_0x80_AND_0xBF( buffer[index + 2] ) &&
IS_BETWEEN_0x80_AND_0xBF( buffer[index + 3] ) )
{
index += 4;
continue;
}
}
}
}
return false;
}
return true;
}
/* --- EOF ------------------------------------------------------------------ */
<file_sep>/src/lr1110_gnss.h
/*!
* @file lr1110_gnss.h
*
* @brief GNSS scan driver definition for LR1110
*
* The Clear BSD License
* Copyright Semtech Corporation 2021. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted (subject to the limitations in the disclaimer
* below) provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the Semtech corporation nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* NO EXPRESS OR IMPLIED LICENSES TO ANY PARTY'S PATENT RIGHTS ARE GRANTED BY
* THIS LICENSE. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
* CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT
* NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
* PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SEMTECH CORPORATION BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef LR1110_GNSS_H
#define LR1110_GNSS_H
#ifdef __cplusplus
extern "C" {
#endif
/*
* -----------------------------------------------------------------------------
* --- DEPENDENCIES ------------------------------------------------------------
*/
#include "lr1110_gnss_types.h"
#include "lr1110_types.h"
/*
* -----------------------------------------------------------------------------
* --- PUBLIC MACROS -----------------------------------------------------------
*/
/*
* -----------------------------------------------------------------------------
* --- PUBLIC CONSTANTS --------------------------------------------------------
*/
/*
* -----------------------------------------------------------------------------
* --- PUBLIC TYPES ------------------------------------------------------------
*/
/*
* -----------------------------------------------------------------------------
* --- PUBLIC FUNCTIONS PROTOTYPES ---------------------------------------------
*/
/*!
* @brief Get the size of results
*
* This method returns the size in bytes of the results available in LR1110 result buffer.
*
* @param [in] context Chip implementation context
* @param [out] result_size Result size
*
* @returns Operation status
*/
lr1110_status_t lr1110_gnss_get_result_size( const void* context, uint16_t* result_size );
/*!
* @brief Read GNSS results
*
* The GNSS results are pushed into a buffer directly. This buffer is provided by the application using the driver. It
* MUST be long enough to contains at least result_buffer_size bytes.
*
* @warning No check is done on result_buffer size. If this application provided buffer is too small, there will be a
* buffer overflow bug!
*
* @param [in] context Chip implementation context
* @param [out] result_buffer Application provided buffer to be filled with result
* @param [in] result_buffer_size The number of bytes to read from the LR1110
*
* @returns Operation status
*/
lr1110_status_t lr1110_gnss_read_results( const void* context, uint8_t* result_buffer,
const uint16_t result_buffer_size );
/*!
* @brief Get the time spent in signal acquisition and signal analysis
*
* These timings allow to compute the current consumption of the last GNSS scan.
*
* @param [in] context Chip implementation context
* @param [out] timings GNSS timings of last GNSS scan
*
* @returns Operation status
*/
lr1110_status_t lr1110_gnss_get_timings( const void* context, lr1110_gnss_timings_t* timings );
/*!
* @brief Update almanacs given as parameter
*
* @remark Note that information header and almanacs for all 128 SV (i.e. 129 20-byte long blocks) must be updated in a
* row for the whole operation to be successful. Therefore, this function must be called as many times as needed without
* any other operations in between.
*
* @param [in] context Chip implementation context
* @param [in] blocks Buffer containing at least (nb_of_blocks * LR1110_GNSS_SINGLE_ALMANAC_WRITE_SIZE) bytes of almanac
* @param [in] nb_of_blocks Number of blocks to transfer
*
* @returns Operation status
*/
lr1110_status_t lr1110_gnss_almanac_update( const void* context, const uint8_t* blocks, const uint8_t nb_of_blocks );
/*!
* @brief Read the almanac
*
* @param [in] context Chip implementation context
* @param [out] almanac_bytestream The bytestream of the almanac
*
* @returns Operation status
*/
lr1110_status_t lr1110_gnss_read_almanac( const void* context,
lr1110_gnss_almanac_full_read_bytestream_t almanac_bytestream );
/*!
* @brief Get almanac age for a satellite
*
* @param [in] context Chip implementation context
* @param [in] sv_id ID of the satellite corresponding the to almanac requested
* @param [out] almanac_age Almanac age in days since last GPS time overlap
*
* @returns Operation status
*/
lr1110_status_t lr1110_gnss_get_almanac_age_for_satellite( const void* context, const lr1110_gnss_satellite_id_t sv_id,
uint16_t* almanac_age );
/*!
* @brief Push data received from solver to LR1110
*
* @param [in] context Chip implementation context
* @param [in] payload Payload received from solver
* @param [in] payload_size Size of the payload received from solver (in bytes)
*
* @returns Operation status
*/
lr1110_status_t lr1110_gnss_push_solver_msg( const void* context, const uint8_t* payload, const uint16_t payload_size );
/*!
* @brief Activate the GNSS scan constellation
*
* @param [in] context Chip implementation context
* @param [in] constellation_mask Bit mask of the constellations to use. See @ref lr1110_gnss_constellation_t for the
* possible values
*
* @returns Operation status
*
* @see lr1110_gnss_read_used_constellations
*/
lr1110_status_t lr1110_gnss_set_constellations_to_use( const void* context,
const lr1110_gnss_constellation_mask_t constellation_mask );
/*!
* @brief Read constellation used by the GNSS scanner from the almanac update configuration
*
* @param [in] context Chip implementation context
* @param [out] constellations_used Bit mask of the constellations used. See @ref lr1110_gnss_constellation_t for the
* possible values
*
* @returns Operation status
*
* @see lr1110_gnss_set_constellations_to_use
*/
lr1110_status_t lr1110_gnss_read_used_constellations( const void* context,
lr1110_gnss_constellation_mask_t* constellations_used );
/*!
* @brief Activate the almanac update
*
* @param [in] context Chip implementation context
* @param [in] constellations_to_update Bit mask of the constellations to mark to update. See @ref
* lr1110_gnss_constellation_t for the possible values
*
* @returns Operation status
*/
lr1110_status_t lr1110_gnss_set_almanac_update( const void* context,
const lr1110_gnss_constellation_mask_t constellations_to_update );
/*!
* @brief Function to read the almanac update configuration
*
* @param [in] context Chip implementation context
* @param [out] constellations_to_update Bit mask of the constellations to mark to update. See @ref
* lr1110_gnss_constellation_t for the possible values
*
* @returns Operation status
*/
lr1110_status_t lr1110_gnss_read_almanac_update( const void* context,
lr1110_gnss_constellation_mask_t* constellations_to_update );
/*!
* @brief Function to read the GNSS firmware version
*
* @param [in] context Chip implementation context
* @param [in] version GNSS Firmware version currently running on the chip
*
* @returns Operation status
*/
lr1110_status_t lr1110_gnss_read_firmware_version( const void* context, lr1110_gnss_version_t* version );
/*!
* @brief Function to read the supported constellation, GPS or BEIDOU other constellations
*
* @param [in] context Chip implementation context
* @param [out] supported_constellations Bit mask of the constellations used. See @ref lr1110_gnss_constellation_t for
* the possible values
*
* @returns Operation status
*/
lr1110_status_t lr1110_gnss_read_supported_constellations( const void* context,
lr1110_gnss_constellation_mask_t* supported_constellations );
/*!
* @brief Function to set the GNSS scan mode configuration
*
* @param [in] context Chip implementation context
* @param [in] scan_mode GNSS scan mode
*
* @returns Operation status
*
* @ref lr1110_gnss_scan_mode_t
*/
lr1110_status_t lr1110_gnss_set_scan_mode( const void* context, const lr1110_gnss_scan_mode_t scan_mode );
/*!
* @brief Gnss scan with no assisted parameters needed
*
* @param [in] context Chip implementation context
* @param [in] date The actual date of scan. Its format is the number of seconds elapsed since January the 6th 1980
* 00:00:00 with leap seconds included.
* @param [in] effort_mode Effort mode @ref lr1110_gnss_search_mode_t
* @param [in] gnss_input_parameters Bit mask indicating which information is added in the output payload @ref
* lr1110_gnss_input_parameters_e
* @param [in] nb_sat The expected number of satellite to provide. This value must be in the range [0:128]
*
* @returns Operation status
*/
lr1110_status_t lr1110_gnss_scan_autonomous( const void* context, const lr1110_gnss_date_t date,
const lr1110_gnss_search_mode_t effort_mode,
const uint8_t gnss_input_parameters, const uint8_t nb_sat );
/*!
* @brief Gnss scan with assisted parameters.
*
* @param [in] context Chip implementation context
* @param [in] date The actual date of scan. Its format is the number of seconds elapsed since January the 6th 1980
* 00:00:00 with leap seconds included.
* @param [in] effort_mode Effort mode @ref lr1110_gnss_search_mode_t
* @param [in] gnss_input_parameters Bit mask indicating which information is added in the output payload @ref
* lr1110_gnss_input_parameters_e
* @param [in] nb_sat The expected number of satellite to provide. This value must be in the range [0:128]
*
* @returns Operation status
*/
lr1110_status_t lr1110_gnss_scan_assisted( const void* context, const lr1110_gnss_date_t date,
const lr1110_gnss_search_mode_t effort_mode,
const uint8_t gnss_input_parameters, const uint8_t nb_sat );
/*!
* @brief Function to set the assistance position.
*
* @param [in] context Chip implementation context
* @param [in] assistance_position, latitude 12 bits and longitude 12 bits
*
* @ref See lr1110_gnss_solver_assistance_position_t
*
* @returns Operation status
*/
lr1110_status_t lr1110_gnss_set_assistance_position(
const void* context, const lr1110_gnss_solver_assistance_position_t* assistance_position );
/*!
* @brief Function to read the assistance position.
*
* The assistance position read may be different from the one set beforehand with @ref
* lr1110_gnss_set_assistance_position due to a scaling computation.
*
* @param [in] context Chip implementation context
* @param [in] assistance_position, latitude 12 bits and longitude 12 bits
*
* @ref See lr1110_gnss_solver_assistance_position_t
*
* @returns Operation status
*/
lr1110_status_t lr1110_gnss_read_assistance_position( const void* context,
lr1110_gnss_solver_assistance_position_t* assistance_position );
/*!
* @brief Host receives an update from the network or assembles itself the update message and send it to the LR1110.
*
* @param [in] context Chip implementation context
* @param [in] dmc_msg buffer containing the update the network
* @param [in] dmc_msg_len length of this buffer
*
* @returns Operation status
*/
lr1110_status_t lr1110_gnss_push_dmc_msg( const void* context, uint8_t* dmc_msg, uint16_t dmc_msg_len );
/*!
* @brief Get the GNSS context status
*
* This function returns the GNSS context status as a raw buffer. It is possible to use
* lr1110_gnss_parse_context_status_buffer to obtain the details of the context status.
*
* @param [in] context Chip implementation context
* @param [out] context_status_buffer Pointer to a buffer to be filled with context status information. Must be at least
* 7 bytes long. It is up to the caller to ensure there is enough place in this buffer.
*
* @returns Operation status
*
* @see lr1110_gnss_parse_context_status_buffer
*/
lr1110_status_t lr1110_gnss_get_context_status( const void* context,
lr1110_gnss_context_status_bytestream_t context_status_buffer );
/*!
* @brief Get the number of detected satellites during last scan
*
* @param [in] context Chip implementation context
* @param [out] nb_detected_satellites Number of satellites detected
*
* @returns Operation status
*/
lr1110_status_t lr1110_gnss_get_nb_detected_satellites( const void* context, uint8_t* nb_detected_satellites );
/*!
* @brief Get the satellites detected on last scan with their IDs, C/N (aka CNR) and doppler
*
* @note Doppler is returned with 6ppm accuracy.
*
* @param [in] context Chip implementation context
* @param [in] nb_detected_satellites Number of detected satellites on last scan (obtained by calling
* lr1110_gnss_get_nb_detected_satellites)
* @param [out] detected_satellite_id_snr_doppler Pointer to an array of structures of size big enough to contain
* nb_detected_satellites elements
*
* @returns Operation status
*/
lr1110_status_t lr1110_gnss_get_detected_satellites(
const void* context, const uint8_t nb_detected_satellites,
lr1110_gnss_detected_satellite_t* detected_satellite_id_snr_doppler );
/**
* @brief Parse a raw buffer of context status
*
* @param [in] context_status_bytestream The raw buffer of context status to parse. It is up to the caller to ensure the
* buffer is at least LR1110_GNSS_CONTEXT_STATUS_LENGTH bytes long
* @param [out] context_status Pointer to a structure of lr1110_gnss_context_status_t to be filled with information from
* context_status_bytestream
*
* @returns Operation status
*
* @see lr1110_gnss_get_context_status
*/
lr1110_status_t lr1110_gnss_parse_context_status_buffer(
const lr1110_gnss_context_status_bytestream_t context_status_bytestream,
lr1110_gnss_context_status_t* context_status );
/**
* @brief Extract the destination from the result returned by a GNSS scan
*
* @param [in] result_buffer Pointer to the buffer holding the result
* @param [in] result_buffer_size Size of the result in byte
* @param [out] destination Destination of the result
*
* @returns Operation status
*/
lr1110_status_t lr1110_gnss_get_result_destination( const uint8_t* result_buffer, const uint16_t result_buffer_size,
lr1110_gnss_destination_t* destination );
/**
* @brief Helper function that computes the age of an almanac.
*
* This function does not call the LR1110.
* The almanac age is computed based on the following elements:
* - almanac age as obtained from lr1110_gnss_get_almanac_age_for_satellite
* - the number of days elapsed between Epoch (January 6th 1980) and the GPS rollover reference of the current
* almanac
* - the GPS date of today expressed in number of days elapsed since Epoch
*
* @remark It is important to use for nb_days_between_epoch_and_corresponding_gps_time_rollover the GPS time rollover
* corresponding to the reference of the almanac_date. This is especially true when current date is just after a GPS
* time rollover.
*
* @param [in] almanac_date Almanac date as obtained from lr1110_gnss_get_almanac_age_for_satellite
* @param [in] nb_days_between_epoch_and_corresponding_gps_time_rollover Number of days elapsed between GPS Epoch and
* the GPS rollover corresponding to the almanac_date
* @param [in] nb_days_since_epoch Number of days elapsed between January 6th 1980 and now
*
* @returns Age of the almanac expressed in number of days between its start valid instant and now
*/
uint16_t lr1110_gnss_compute_almanac_age( uint16_t almanac_date,
uint16_t nb_days_between_epoch_and_corresponding_gps_time_rollover,
uint16_t nb_days_since_epoch );
#ifdef __cplusplus
}
#endif
#endif // LR1110_GNSS_H
/* --- EOF ------------------------------------------------------------------ */
<file_sep>/src/lr1110_system.h
/*!
* @file lr1110_system.h
*
* @brief System driver definition for LR1110
*
* The Clear BSD License
* Copyright Semtech Corporation 2021. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted (subject to the limitations in the disclaimer
* below) provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the Semtech corporation nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* NO EXPRESS OR IMPLIED LICENSES TO ANY PARTY'S PATENT RIGHTS ARE GRANTED BY
* THIS LICENSE. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
* CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT
* NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
* PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SEMTECH CORPORATION BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef LR1110_SYSTEM_H
#define LR1110_SYSTEM_H
#ifdef __cplusplus
extern "C" {
#endif
/*
* -----------------------------------------------------------------------------
* --- DEPENDENCIES ------------------------------------------------------------
*/
#include "lr1110_system_types.h"
#include "lr1110_types.h"
/*
* -----------------------------------------------------------------------------
* --- PUBLIC MACROS -----------------------------------------------------------
*/
/*
* -----------------------------------------------------------------------------
* --- PUBLIC CONSTANTS --------------------------------------------------------
*/
/*!
* @brief Frequency step in MHz used to compute the image calibration parameter
*
* @see lr1110_system_calibrate_image_in_mhz
*/
#define LR1110_SYSTEM_IMAGE_CALIBRATION_STEP_IN_MHZ 4
/*
* -----------------------------------------------------------------------------
* --- PUBLIC TYPES ------------------------------------------------------------
*/
/*
* -----------------------------------------------------------------------------
* --- PUBLIC FUNCTIONS PROTOTYPES ---------------------------------------------
*/
/*!
* @brief Reset the radio
*
* @param [in] context Chip implementation context
*
* @returns Operation status
*/
lr1110_status_t lr1110_system_reset( const void* context );
/**
* @brief Wake the radio up from sleep mode.
*
* @param [in] context Chip implementation context.
*
* @returns Operation status
*/
lr1110_status_t lr1110_system_wakeup( const void* context );
/*!
* @brief Return stat1, stat2, and irq_status
*
* @param [in] context Chip implementation context
* @param [out] stat1 Pointer to a variable for holding stat1. Can be NULL.
* @param [out] stat2 Pointer to a variable for holding stat2. Can be NULL.
* @param [out] irq_status Pointer to a variable for holding irq_status. Can be NULL.
*
* @returns Operation status
*
* @remark To simplify system integration, this function does not actually execute the GetStatus command, which would
* require bidirectional SPI communication. It obtains the stat1, stat2, and irq_status values by performing an ordinary
* SPI read (which is required to send null/NOP bytes on the MOSI line). This is possible since the LR1110 returns these
* values automatically whenever a read that does not directly follow a response-carrying command is performed.
* Unlike with the GetStatus command, however, the reset status information is NOT cleared by this command. The function
* @ref lr1110_system_clear_reset_status_info may be used for this purpose when necessary.
*/
lr1110_status_t lr1110_system_get_status( const void* context, lr1110_system_stat1_t* stat1,
lr1110_system_stat2_t* stat2, lr1110_system_irq_mask_t* irq_status );
/*!
* @brief Clear the reset status information stored in stat2
*
* @param [in] context Chip implementation context
*
* @returns Operation status
*/
lr1110_status_t lr1110_system_clear_reset_status_info( const void* context );
/*!
* @brief Return irq_status
*
* @param [in] context Chip implementation context
* @param [out] irq_status irq_status status variable
*
* @returns Operation status
*/
static inline lr1110_status_t lr1110_system_get_irq_status( const void* context, lr1110_system_irq_mask_t* irq_status )
{
return lr1110_system_get_status( context, 0, 0, irq_status );
}
/*!
* @brief Return the version of the system (hardware and software)
*
* @param [in] context Chip implementation context
* @param [out] version Pointer to the structure holding the system version
*
* @returns Operation status
*/
lr1110_status_t lr1110_system_get_version( const void* context, lr1110_system_version_t* version );
/*!
* @brief Return the system errors
*
* Errors may be fixed following:
* - calibration error can be fixed by attempting another RC calibration;
* - XOsc related errors may be due to hardware problems, can be fixed by reset;
* - PLL lock related errors can be due to not-locked PLL, or by attempting to use an out-of-band frequency, can be
* fixed by executing a PLL calibration, or by using other frequencies.
*
* @param [in] context Chip implementation context
* @param [out] errors Pointer to a value holding error flags
*
* @returns Operation status
*
* @see lr1110_system_calibrate, lr1110_system_calibrate_image, lr1110_system_clear_errors
*/
lr1110_status_t lr1110_system_get_errors( const void* context, uint16_t* errors );
/*!
* @brief Clear all error flags pending.
*
* This function cannot be used to clear flags individually.
*
* @param [in] context Chip implementation context
*
* @returns Operation status
*
* @see lr1110_system_get_errors
*/
lr1110_status_t lr1110_system_clear_errors( const void* context );
/*!
* @brief lr1110_system_calibrate the requested blocks
*
* This function can be called in any mode of the chip.
*
* The chip will return to standby RC mode on exit. Potential calibration issues can be read out with
* lr1110_system_get_errors command.
*
* @param [in] context Chip implementation context
* @param [in] calib_param Structure holding the reference to blocks to be calibrated
*
* @returns Operation status
*
* @see lr1110_system_get_errors
*/
lr1110_status_t lr1110_system_calibrate( const void* context, const uint8_t calib_param );
/*!
* @brief Configure the regulator mode to be used in specific modes
*
* This function shall only be called in standby RC mode.
*
* The reg_mode parameter defines if the DC-DC converter is switched on in the following modes: STANDBY XOSC, FS, RX, TX
* and RX_CAPTURE.
*
* @param [in] context Chip implementation context
* @param [in] reg_mode Regulator mode configuration
*
* @returns Operation status
*/
lr1110_status_t lr1110_system_set_reg_mode( const void* context, const lr1110_system_reg_mode_t reg_mode );
/*!
* @brief Launch an image calibration valid for all frequencies inside an interval, in steps
*
* This function can be called in any mode of the chip.
*
* The chip will return to standby RC mode on exit. Potential calibration issues can be read out with
* lr1110_system_get_errors command.
*
* The frequencies given in parameters are defined in 4MHz step (Eg. 900MHz corresponds to 0xE1). If freq1 = freq2, only
* one calibration is performed.
*
* @param [in] context Chip implementation context
* @param [in] freq1 Image calibration interval lower bound, in steps
* @param [in] freq2 Image calibration interval upper bound, in steps
*
* @remark freq1 must be less than or equal to freq2
*
* @returns Operation status
*
* @see lr1110_system_get_errors
*/
lr1110_status_t lr1110_system_calibrate_image( const void* context, const uint8_t freq1, const uint8_t freq2 );
/*!
* @brief Launch an image calibration valid for all frequencies inside an interval, in MHz
*
* @remark This function relies on @ref lr1110_system_calibrate_image
*
* @param [in] context Chip implementation context
* @param [in] freq1_in_mhz Image calibration interval lower bound, in MHz
* @param [in] freq2_in_mhz Image calibration interval upper bound, in MHz
*
* @remark freq1 must be less than or equal to freq2
*
* @returns Operation status
*
* @see lr1110_system_calibrate_image
*/
lr1110_status_t lr1110_system_calibrate_image_in_mhz( const void* context, const uint16_t freq1_in_mhz,
const uint16_t freq2_in_mhz );
/*!
* @brief Set the RF switch configurations for each RF setup
*
* This function shall only be called in standby RC mode.
*
* By default, no DIO is used to control a RF switch. All DIOs are set in High-Z mode.
*
* @param [in] context Chip implementation context
* @param [in] rf_switch_cfg Pointer to a structure that holds the switches configuration
*
* @returns Operation status
*/
lr1110_status_t lr1110_system_set_dio_as_rf_switch( const void* context,
const lr1110_system_rfswitch_cfg_t* rf_switch_cfg );
/*!
* @brief Set which interrupt signals are redirected to the dedicated DIO pin
*
* By default, no interrupt signal is redirected.
*
* The dedicated DIO pin will remain asserted until all redirected interrupt signals are cleared with a call to
* lr1110_system_clear_irq_status.
*
* @param [in] context Chip implementation context
* @param [in] irqs_to_enable_dio1 Variable that holds the interrupt mask for dio1
* @param [in] irqs_to_enable_dio2 Variable that holds the interrupt mask for dio2
*
* @returns Operation status
*
* @see lr1110_system_clear_irq_status
*/
lr1110_status_t lr1110_system_set_dio_irq_params( const void* context,
const lr1110_system_irq_mask_t irqs_to_enable_dio1,
const lr1110_system_irq_mask_t irqs_to_enable_dio2 );
/*!
* @brief Clear requested bits in the internal pending interrupt register
*
* @param [in] context Chip implementation context
* @param [in] irqs_to_clear Variable that holds the interrupts to be cleared
*
* @returns Operation status
*/
lr1110_status_t lr1110_system_clear_irq_status( const void* context, const lr1110_system_irq_mask_t irqs_to_clear );
/**
* @brief This helper function clears any radio irq status flags that are set and returns the flags that were cleared.
*
* @param [in] context Chip implementation context.
* @param [out] irq Pointer to a variable for holding the system interrupt status. Can be NULL.
*
* @returns Operation status
*
* @see lr1110_system_get_irq_status, lr1110_system_clear_irq_status
*/
lr1110_status_t lr1110_system_get_and_clear_irq_status( const void* context, lr1110_system_irq_mask_t* irq );
/*!
* @brief Defines which clock is used as Low Frequency (LF) clock
*
* @param [in] context Chip implementation context
* @param [in] lfclock_cfg Low frequency clock configuration
* @param [in] wait_for_32k_ready Tells the radio if it has to check if 32k source is ready before driving busy low
*
* @returns Operation status
*
* @see lr1110_system_calibrate, lr1110_system_calibrate_image
*/
lr1110_status_t lr1110_system_cfg_lfclk( const void* context, const lr1110_system_lfclk_cfg_t lfclock_cfg,
const bool wait_for_32k_ready );
/*!
* @brief Enable and configure TCXO supply voltage and detection timeout
*
* This function shall only be called in standby RC mode.
*
* The timeout parameter is the maximum time the firmware waits for the TCXO to be ready. The timeout duration is given
* by: \f$ timeout\_duration\_us = timeout \times 30.52 \f$
*
* The TCXO mode can be disabled by setting timeout parameter to 0.
*
* @param [in] context Chip implementation context
* @param [in] tune Supply voltage value
* @param [in] timeout Gating time before which the radio starts its Rx / Tx operation
*
* @returns Operation status
*
* @see lr1110_system_calibrate, lr1110_system_calibrate_image
*/
lr1110_status_t lr1110_system_set_tcxo_mode( const void* context, const lr1110_system_tcxo_supply_voltage_t tune,
const uint32_t timeout );
/*!
* @brief Software reset of the chip.
*
* This function should be used to reboot the chip in a specified mode. Rebooting in flash mode presumes that the
* content in flash memory is not corrupted (i.e. the integrity check performed by the bootloader before executing the
* first instruction in flash is OK).
*
* @param [in] context Chip implementation context
* @param [in] stay_in_bootloader Selector to stay in bootloader or execute flash code after reboot. If true, the
* bootloader will not execute the flash code but activate SPI interface to allow firmware upgrade
*
* @returns Operation status
*/
lr1110_status_t lr1110_system_reboot( const void* context, const bool stay_in_bootloader );
/*!
* @brief Returns the value of Vbat
*
* Vbat value (in V) is a function of Vana (typ. 1.35V) using the following
* formula: \f$ Vbat_{V} = (5 \times \frac{Vbat}{255} - 1) \times Vana \f$
*
* @param [in] context Chip implementation context
* @param [out] vbat A pointer to the Vbat value
*
* @returns Operation status
*/
lr1110_status_t lr1110_system_get_vbat( const void* context, uint8_t* vbat );
/*!
* @brief Returns the value of Temp
*
* The temperature (in °C) is a function of Vana (typ. 1.35V), Vbe25 (Vbe voltage @ 25°C, typ. 0.7295V) and VbeSlope
* (typ. -1.7mV/°C) using the following formula:
* \f$ Temperature_{°C} = (\frac{Temp(10:0)}{2047} \times Vana - Vbe25) \times \frac{1000}{VbeSlope} + 25 \f$
*
* @remark If a TCXO is used, make sure to configure it with @ref lr1110_system_set_tcxo_mode before calling this
* function
*
* @param [in] context Chip implementation context
* @param [out] temp A pointer to the Temp value
*
* @returns Operation status
*/
lr1110_status_t lr1110_system_get_temp( const void* context, uint16_t* temp );
/*!
* @brief Set the device into Sleep or Deep Sleep Mode
*
* The sleep_cfg parameter defines in which sleep mode the device is put and if it wakes up after a given time on the
* RTC event.
*
* The sleep_time parameter is taken into account only when RtcTimeout = 1. It sets the sleep time in number of clock
* cycles: \f$ sleep\_time\_ms = sleep_time \times \frac{1}{32.768} \f$
*
* @param [in] context Chip implementation context
* @param [in] sleep_cfg Sleep mode configuration
* @param [in] sleep_time Value of the RTC timeout (if RtcTimeout = 1)
*
* @returns Operation status
*
* @see lr1110_system_set_standby, lr1110_system_set_fs
*/
lr1110_status_t lr1110_system_set_sleep( const void* context, const lr1110_system_sleep_cfg_t sleep_cfg,
const uint32_t sleep_time );
/*!
* @brief Set the device into the requested Standby mode
*
* @param [in] context Chip implementation context
* @param [in] standby_cfg Stand by mode configuration (RC or XOSC)
*
* @returns Operation status
*
* @see lr1110_system_set_sleep, lr1110_system_set_fs
*/
lr1110_status_t lr1110_system_set_standby( const void* context, const lr1110_system_standby_cfg_t standby_cfg );
/*!
* @brief Set the device into Frequency Synthesis (FS) mode
*
* @param [in] context Chip implementation context
*
* @returns Operation status
*
* @see lr1110_system_set_standby, lr1110_system_set_sleep
*/
lr1110_status_t lr1110_system_set_fs( const void* context );
/*!
* @brief Erase an info page
*
* @param [in] context Chip implementation context
* @param [in] info_page_id Info page to be erased. Only LR1110_SYSTEM_INFOPAGE_1 is allowed.
*
* @returns Operation status
*
* @see lr1110_system_write_infopage, lr1110_system_read_infopage
*/
lr1110_status_t lr1110_system_erase_infopage( const void* context, const lr1110_system_infopage_id_t info_page_id );
/*!
* @brief Write data in an info page
*
* @param [in] context Chip implementation context
* @param [in] info_page_id Info page where data are written. Only LR1110_SYSTEM_INFOPAGE_1 is allowed.
* @param [in] address Address within the info page (aligned on 32-bit data)
* @param [in] data Pointer to the data to write (data buffer shall be - at least - length words long)
* @param [in] length Number of 32-bit data to write (maximum value is 64)
*
* @returns Operation status
*
* @see lr1110_system_erase_infopage, lr1110_system_read_infopage
*/
lr1110_status_t lr1110_system_write_infopage( const void* context, const lr1110_system_infopage_id_t info_page_id,
const uint16_t address, const uint32_t* data, const uint8_t length );
/*!
* @brief Read data from an info page
*
* It is possible to cross from page 0 to 1 if (address + length >= 512)
*
* @param [in] context Chip implementation context
* @param [in] info_page_id Info page where data are read
* @param [in] address Address within the info page (aligned on 32-bit data)
* @param [out] data Pointer to the data to read (data buffer shall be - at least - length words long)
* @param [in] length Number of 32-bit data to read (maximum value is 64)
*
* @returns Operation status
*
* @see lr1110_system_erase_infopage, lr1110_system_write_infopage
*/
lr1110_status_t lr1110_system_read_infopage( const void* context, const lr1110_system_infopage_id_t info_page_id,
const uint16_t address, uint32_t* data, const uint8_t length );
/*!
* @brief Read and return the Unique Identifier of the LR1110
*
* @param [in] context Chip implementation context
* @param [out] unique_identifier The buffer to be filled with the Unique Identifier of the LR1110. It is up to the
* application to ensure unique_identifier is long enough to hold the unique identifier
*
* @returns Operation status
*
* @see LR1110_SYSTEM_UID_LENGTH
*/
lr1110_status_t lr1110_system_read_uid( const void* context, lr1110_system_uid_t unique_identifier );
/*!
* @brief Read and return the Join EUI of the LR1110
*
* @param [in] context Chip implementation context
* @param [out] join_eui The buffer to be filled with Join EUI of the LR1110. It is up to the application to ensure
* join_eui is long enough to hold the join EUI
*
* @returns Operation status
*
* @see LR1110_SYSTEM_JOIN_EUI_LENGTH
*/
lr1110_status_t lr1110_system_read_join_eui( const void* context, lr1110_system_join_eui_t join_eui );
/*!
* @brief Compute and return the PIN of the LR1110 based on factory default EUIs
*
* @remark Calling this command also triggers a derivation of network and application keys (available as @ref
* LR1110_CRYPTO_KEYS_IDX_NWK_KEY and @ref LR1110_CRYPTO_KEYS_IDX_APP_KEY) based on factory default EUIs
*
* @param [in] context Chip implementation context
* @param [out] pin The buffer to be filled with PIN of the LR1110. It is up to the application to ensure pin is long
* enough to hold the PIN
*
* @returns Operation status
*
* @see LR1110_SYSTEM_PIN_LENGTH
*/
lr1110_status_t lr1110_system_read_pin( const void* context, lr1110_system_pin_t pin );
/*!
* @brief Compute and return the PIN of the LR1110 based on EUIs provided as parameters
*
* @remark Calling this command also triggers a derivation of network and application keys (available as @ref
* LR1110_CRYPTO_KEYS_IDX_NWK_KEY and @ref LR1110_CRYPTO_KEYS_IDX_APP_KEY) based on EUIs provided as parameters
*
* @param [in] context Chip implementation context
* @param [in] device_eui Custom Device EUI
* @param [in] join_eui Custom Join EUI
* @param [in] rfu Parameter RFU - shall be set to 0x00
* @param [out] pin The buffer to be filled with PIN of the LR1110. It is up to the application to ensure pin is long
* enough to hold the PIN
*
* @returns Operation status
*
* @see LR1110_SYSTEM_PIN_LENGTH
*/
lr1110_status_t lr1110_system_read_pin_custom_eui( const void* context, lr1110_system_uid_t device_eui,
lr1110_system_join_eui_t join_eui, uint8_t rfu,
lr1110_system_pin_t pin );
/*!
* @brief Read and return a 32-bit random number
*
* @remark Radio operating mode must be set into standby.
*
* @param [in] context Chip implementation context
* @param [out] random_number 32-bit random number
*
* @returns Operation status
*/
lr1110_status_t lr1110_system_get_random_number( const void* context, uint32_t* random_number );
/*!
* @brief Enable the CRC on SPI transactions
*
* @remark This command shall always be sent with a CRC (to both enable and disable the feature). The function does not
* take care of this additional byte - which is under the responsibility of the underlying HAL functions
*
* @param [in] context Chip implementation context
* @param [in] enable_crc CRC
*
* @returns Operation status
*/
lr1110_status_t lr1110_system_enable_spi_crc( const void* context, bool enable_crc );
/*!
* @brief Configure the GPIO drive in sleep mode
*
* @remark GPIO stands for RF switch and IRQ line DIOs
*
* @note This command is available from firmware version 0x0306
*
* @param [in] context Chip implementation context
* @param [in] enable_drive GPIO drive configuration (true: enabled / false: disabled)
*
* @returns Operation status
*/
lr1110_status_t lr1110_system_drive_dio_in_sleep_mode( const void* context, bool enable_drive );
#ifdef __cplusplus
}
#endif
#endif // LR1110_SYSTEM_H
/* --- EOF ------------------------------------------------------------------ */
| 2a3f3c5a2e204e5a79a551b5e8fff77490866bcf | [
"Markdown",
"C"
] | 9 | Markdown | Lora-net/lr1110_driver | fdad7e1740d95c6ca4805831561bcc17d283e800 | 6ccb296933485beaff7ed0a0bb34e6e65ba40a8f |
refs/heads/master | <repo_name>jcr179/qt-pie<file_sep>/README.md
# qt-pie
Simple portfolio reading/analysis tool for Questrade accounts.
How to use:
1. Replace "MY_KEY" in set_env.bat with your Questrade refresh token.
2. In a cmd terminal, run set_env.bat to set the environment variable.
3. (Optional) To automate recording updates of your balance, schedule read.py to run at desired frequency.
4. Run read.py to create a data folder and a csv file (openable with Excel, Google Sheets, etc.) for each of your accounts whenever you want to update balance records.
Currently only records total equity in USD.
<file_sep>/read.py
import os
from questrade_api import Questrade
from collections import defaultdict
if __name__ == "__main__":
key = os.environ.get('QUESTRADE_API_KEY')
if key is None:
print('ERROR: Environment variable QUESTRADE_API_KEY not set.')
try:
q = Questrade(refresh_token=key)
# After run the first time, can create object without initializing with ref token
except Exception as e:
q = Questrade()
time = q.time['time']
accounts_raw = q.accounts['accounts']
accounts = defaultdict(dict)
for acc in accounts_raw:
accounts[acc['number']]['type'] = acc['type']
for acc_num in accounts:
handler = q.account_balances(acc_num)
accounts[acc_num]['balance_usd'] = handler['perCurrencyBalances'][1]['totalEquity']
if not os.path.isdir('data'):
os.mkdir('data')
for acc_num in accounts:
with open(os.path.join('data', acc_num + '.csv'), 'a') as f:
f.write(time + ',' + str(accounts[acc_num]['balance_usd']) + '\n')
| b1b7039f4e231e58a8483d2bb473158d3e31e3a3 | [
"Markdown",
"Python"
] | 2 | Markdown | jcr179/qt-pie | a334b2595ed9198cd1d9d05a4e1843c4140c333a | c00c7988f1b52bb45366e85ef11530accbd76184 |
refs/heads/master | <file_sep>import { Component, Input, Output, EventEmitter, OnInit } from '@angular/core';
@Component({
selector: 'app-node',
templateUrl: './node.component.html',
styleUrls: ['./node.component.less']
})
//https://material.io/resources/icons/?style=baseline
export class NodeComponent implements OnInit {
@Input() node: object;
@Input() key: string;
@Output() updateNode = new EventEmitter();
@Output() deleteNode = new EventEmitter();
newName: string;
children;
maxLength = 20;
collapsed: boolean;
ngOnInit() {
this.newName = '';
this.refreshChildren();
this.collapsed = false;
}
refreshChildren() {
this.children = Object.keys(this.node).map(childKey => {
if (typeof this.node[childKey] === 'object') return { childName: childKey, value: this.node[childKey] }
return { attrName: childKey, value: this.node[childKey] }
});
}
showJSON() {
return JSON.stringify(this.node);
}
changeValue(e, attrName) {
this.node = { ...this.node, [attrName]: e.target.value };
this.update();
}
addAttribute() {
this.add('');
}
addChild() {
this.add({});
}
add(value) {
if (!this.newName) {
alert('Введите имя')
return;
}
if (this.node.hasOwnProperty(this.newName)) {
alert('Такое имя уже занято')
return;
}
this.node[this.newName] = value;
this.newName = '';
this.update();
}
update() {
this.updateNode.emit(this.node);
this.refreshChildren();
}
delete(key) {
delete(this.node[key]);
this.update();
}
deleteSelf() {
this.deleteNode.emit(this.key);
}
toggleCollapse() {
this.collapsed = !this.collapsed;
}
updateChild(item, key) {
this.node = {...this.node, [key]: item};
this.update();
}
}
<file_sep>import { Component } from '@angular/core';
const initialState = {
attr1: 1,
Object1: {
attr2: 2,
Object2: {
attr3: 1,
Object3: {
attr5: 'i'
}
},
attr4: 3
}
}
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.less']
})
export class AppComponent {
jsonTree: object = initialState;
title = 'ng-json-tree';
show() {
return JSON.stringify(this.jsonTree);
}
updateNode(tree) {
this.jsonTree = tree;
}
}
| e97925bef94a90184bd63daed002d1a140418a7f | [
"TypeScript"
] | 2 | TypeScript | parusev/angular-json-tree | 276312c1b80e8ab2e14479e2db788f67e627294d | f61db301746782953eb79d605b46e8627e1cf0b8 |
refs/heads/master | <file_sep>#define _GNU_SOURCE
#include <stdio.h>
#include <signal.h>
#include <pthread.h>
#include "tlpi_hdr.h"
static pthread_mutex_t mtx = PTHREAD_MUTEX_INITIALIZER;
static pthread_cond_t cond = PTHREAD_COND_INITIALIZER;
static volatile int flag = 0;
void print_pendding_signal(const char *msg)
{
sigset_t set;
sigpending(&set);
printf("%s:", msg);
for (int i = 1; i < NSIG; ++i)
{
if (sigismember(&set, i))
printf("%d ", i);
}
printf("\n");
}
void *thread_func(void *arg)
{
sigset_t mask;
sigemptyset(&mask);
sigaddset(&mask, SIGINT);
pthread_sigmask(SIG_BLOCK, &mask, NULL);
pthread_mutex_lock(&mtx);
while (flag == 0)
{
pthread_cond_wait(&cond, &mtx);
}
print_pendding_signal("Tthread t1");
pthread_mutex_unlock(&mtx);
return NULL;
}
int main(int argc, char *argv[])
{
sigset_t mask;
pthread_t t1;
int s;
sigemptyset(&mask);
sigaddset(&mask, SIGQUIT);
pthread_sigmask(SIG_BLOCK, &mask, NULL);
pthread_kill(pthread_self(), SIGQUIT);
s = pthread_create(&t1, NULL, thread_func, NULL);
if (s != 0)
errExitEN(s, "pthread_create");
sleep(2);
pthread_kill(t1, SIGQUIT);
pthread_kill(t1, SIGINT);
flag = 1;
pthread_cond_signal(&cond);
s = pthread_join(t1, NULL);
if (s != 0)
errExitEN(s, "pthread_join");
print_pendding_signal("Main thread");
exit(EXIT_SUCCESS);
}<file_sep>#define _XOPEN_SOURCE 500
#include <sys/wait.h>
//#include "print_wait_status.h"
#include "tlpi_hdr.h"
int main(int argc, char *argv[])
{
int status;
pid_t child_pid;
siginfo_t info;
switch (fork())
{
case -1:
errExit("fork");
case 0:
printf("Child started with PID = %ld\n", (long)getpid());
if (argc > 1)
exit(getInt(argv[1], 0, "exit-status"));
else
for(;;)
pause();
exit(EXIT_SUCCESS);
default:
for (;;)
{
child_pid = waitid(P_ALL, 0, &info, WSTOPPED
#ifdef WCONTINUED
| WCONTINUED
#endif
);
if (child_pid == -1)
errExit("waitpid");
printf("waitpid() returned: PID=%ld UID=%ld status=0x%04d (%d,%d) code is ",
(long)info.si_pid, (long)info.si_uid,
(unsigned int)status, status >> 8, status & 0xff);
switch (info.si_code)
{
case CLD_EXITED: printf("CLD_EXITED\n"); break;
case CLD_KILLED: printf("CLD_KILLED\n"); break;
case CLD_DUMPED: printf("CLD_DUMPED\n"); break;
case CLD_STOPPED: printf("CLD_STOPPED\n"); break;
case CLD_TRAPPED: printf("CLD_TRAPPED\n"); break;
case CLD_CONTINUED: printf("CLD_CONTINUED\n"); break;
default: fatal("fuck");
}
//print_wait_status(NULL, status);
if (WIFEXITED(status) || WIFSIGNALED(status))
exit(EXIT_SUCCESS);
}
}
}<file_sep>#define _GNU_SOURCE
#include <signal.h>
#include "signal_functions.h"
#include "tlpi_hdr.h"
static int sig_cnt[NSIG];
static volatile sig_atomic_t got_sigint = 0;
static void handler(int sig)
{
if (sig == SIGINT)
got_sigint = 1;
else
++sig_cnt[sig];
}
int main(int argc, char *argv[])
{
int n, num_secs;
sigset_t pending_mask, blocking_mask, empty_mask;
printf("%s: PID is %ld\n", argv[0], (long)getpid());
for (n = 1; n < NSIG; ++n)
signal(n, handler);
if (argc > 1)
{
num_secs = getInt(argv[1], GN_GT_0, NULL);
sigfillset(&blocking_mask);
if (sigprocmask(SIG_SETMASK, &blocking_mask, NULL) == -1)
errExit("sigprocmask");
printf("%s: sleeping for %d seconds\n", argv[0], num_secs);
sleep(num_secs);
if (sigpending(&pending_mask) == -1)
errExit("sigpending");
printf("%s: pending singals are: \n", argv[0]);
print_sigset(stdout, "\t\t", &pending_mask);
sigemptyset(&empty_mask);
if (sigprocmask(SIG_SETMASK, &empty_mask, NULL) == -1)
errExit("sigprocmask");
}
while (!got_sigint)
continue;
for (n = 1; n < NSIG; ++n)
{
if (sig_cnt[n] != 0)
printf("%s: signal %d caugnt %d time%s\n", argv[0], n,
sig_cnt[n], (sig_cnt[n] == 1) ? "" : "s");
}
exit(EXIT_SUCCESS);
}<file_sep>// 进程组首进程调用 setsid() 会失败
#include <unistd.h>
#include <signal.h>
#include <stdio.h>
#include "tlpi_hdr.h"
int main(void)
{
pid_t child_pid;
// if (setpgid(0, 0) == -1)
// errExit("setpgid");
// if (setsid() == -1)
// errExit("setsid");
switch (child_pid = fork())
{
case -1:
errExit("fork");
case 0:
printf("PID: %ld PGID: %ld\n", (long)getpid(), (long)getpgrp());
if (setpgid(0, 0) == -1)
errExit("setpgid");
signal(SIGTTOU, SIG_IGN);
if (tcsetpgrp(STDOUT_FILENO, getpgrp()) == -1)
errExit("tcsetpgrp");
printf("fuck\n");
if (setsid() == -1)
errExit("setsid");
printf("fuck\n");
break;
default:
sleep(3);
}
}<file_sep>#define _GNU_SOURCE
#include <time.h>
#include <utmpx.h>
#include <paths.h>
#include "tlpi_hdr.h"
int main(int argc, char *argv[])
{
struct utmpx *ut;
if (argc > 1)
{
if (utmpxname(argv[1]) == -1)
errExit("utmpxname");
}
setutxent();
printf("User type PID line id host data/time\n");
while ((ut = getutxent()) != NULL)
{
printf("%-8s ", ut->ut_user);
const char *type;
switch (ut->ut_type)
{
case EMPTY: type = "EMPTY"; break;
case RUN_LVL: type = "RUN_LVL"; break;
case BOOT_TIME: type = "BOOT_TIME"; break;
case NEW_TIME: type = "NEW_TIME"; break;
case OLD_TIME: type = "OLD_TIME"; break;
case INIT_PROCESS: type = "INIT_PR"; break;
case LOGIN_PROCESS: type = "LOGIN_PR"; break;
case USER_PROCESS: type = "USER_PR"; break;
case DEAD_PROCESS: type = "DEAD_PR"; break;
}
printf("%-9.9s ", type);
printf("%5ld %-6.6s %-3.5s %-9.9s ", (long)ut->ut_pid,
ut->ut_line, ut->ut_id, ut->ut_host);
printf("%s", ctime((time_t*) &(ut->ut_tv.tv_sec)));
}
endutxent();
exit(EXIT_SUCCESS);
}<file_sep>#include <sched.h>
#include "tlpi_hdr.h"
int main(int argc, char *argv[])
{
int j, pol;
struct sched_param sp;
pol = (argv[1][0] == 'r') ? SCHED_RR :
(argv[1][0] == 'f') ? SCHED_FIFO :
#ifdef SCHED_BATCH
(argv[1][0] == 'b') ? SHCED_BATCH;
#endif
#ifdef SHCED_IDLE
(argv[1][0] == 'i') ? SCHED_IDLE:
#endif
SCHED_OTHER;
for (j = 3; j < argc; ++j)
{
if (sched_setscheduler(getLong(argv[j], 0, "pid"), pol, &sp) == -1)
errExit("sched_setscheduler");
}
exit(EXIT_FAILURE);
}<file_sep>/**************************************
* 验证文件描述符及其副本共享了文件偏移量和打
* 开文件的状态标志(file status flags)。
* flags分为file status flags,file creation
* flags,file access flags。
***************************************/
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
void errExit(const char*);
int main(int argc, char **argv)
{
int fd, newfd, flag, anotherflag;
if (argc != 2)
{
errExit("Arguments error!");
}
flag = O_WRONLY | O_CREAT | O_APPEND;
fd = open(argv[1], flag, S_IRUSR | S_IWUSR);
if (fd == -1)
{
errExit("Open error!");
}
newfd = dup(fd);
if (newfd == -1)
errExit("dup error!");
anotherflag = fcntl(newfd, F_GETFL);
if (O_WRONLY == (anotherflag & O_ACCMODE) && (anotherflag & O_APPEND))
{
printf("Flag is the same\n");
}
else
printf("Flag is not the same\n");
if (write(fd, "Hello ", 6) == -1)
errExit("Write error!");
if (write(newfd, "world", 5) == -1)
errExit("Write error");
close(fd);
close(newfd);
return 0;
}
void errExit(const char* err)
{
fputs(err, stderr);
exit(EXIT_FAILURE);
}<file_sep>/*
* 经过测试,对于祖父,父以及子进程,父进程变成僵尸进程,孙进程在父进程终止后就会
* 被 init 进程收养,而不是祖父进程调用 wait() 后。
*/
#define _XOPEN_SOURCE
#include <unistd.h>
#include <sys/wait.h>
#include <sys/prctl.h>
#include <signal.h>
#include "tlpi_hdr.h"
void handler(int sig)
{
}
int main(int argc, char *argv[])
{
sigset_t mask;
struct sigaction sa;
pid_t grandparent, parent, son;
int status;
grandparent = getpid();
sigemptyset(&mask);
sigaddset(&mask, SIGUSR1);
sigprocmask(SIG_SETMASK, &mask, NULL);
sigemptyset(&sa.sa_mask);
sa.sa_flags = 0;
sa.sa_handler = handler;
if (sigaction(SIGUSR1, &sa, NULL) == -1)
errExit("sigaction");
sigemptyset(&mask);
setbuf(stdout, NULL);
switch (parent = fork())
{
case -1:
errExit("fork");
case 0:
switch (son = fork())
{
case -1:
errExit("fork");
case 0:
while (kill(getppid(), SIGUSR1) == 0)
continue;
printf("After parent process exites, parent PID is %ld\n", (long)getppid());
kill(grandparent, SIGUSR1);
while (kill(grandparent, SIGUSR1) == 0)
continue;
printf("After grandparent process waits, parent PID is %ld\n", (long)getppid());
exit(EXIT_SUCCESS);
default:
printf("[%ld] Exit...\n", (long)getpid());
_exit(EXIT_SUCCESS);
}
default:
sigsuspend(&mask);
printf("[%ld] Wait...\n", (long)getpid());
if (wait(&status) == -1)
errExit("wait");
exit(EXIT_SUCCESS);
}
}<file_sep>#include <stdio.h>
#include <dlfcn.h>
#include "tlpi_hdr.h"
int main(int argc, char *argv[])
{
void *lib_handler;
int (*funcp)(const char *, ...);
const char *err;
lib_handler = dlopen(argv[1], RTLD_LAZY);
if (lib_handler == NULL)
fatal("dlopen: %s", dlerror());
(void) dlerror();
*(void **)(&funcp) = dlsym(lib_handler, argv[2]);
// printf("DD\n");
err = dlerror();
if (err != NULL)
fatal("dlsym: %s", err);
if (funcp == NULL)
printf("%s is NULL\n", argv[2]);
else
{
(*funcp)("fuck\n");
// printf("fuck\n");
}
dlclose(lib_handler);
exit(EXIT_SUCCESS);
}<file_sep>#define _XOPEN_SOURCE
#define _BSD_SOURCE
#include <signal.h>
#include "tlpi_hdr.h"
static void tstp_handler(int sig)
{
sigset_t tstp_mask, prev_mask;
int saved_errno;
struct sigaction sa;
saved_errno = errno;
printf("Caught SIGTSTP\n");
if (signal(SIGTSTP, SIG_DFL) == SIG_ERR)
errExit("signal");
raise(SIGTSTP);
sigemptyset(&tstp_mask);
sigaddset(&tstp_mask, SIGTSTP);
if (sigprocmask(SIG_UNBLOCK, &tstp_mask, &prev_mask) == -1)
errExit("sigprocmask");
if (sigprocmask(SIG_SETMASK, &prev_mask, NULL) == -1)
errExit("sigprocmask");
sigemptyset(&sa.sa_mask);
sa.sa_flags = SA_RESTART;
sa.sa_handler = tstp_handler;
if (sigaction(SIGTSTP, &sa, NULL) == -1)
errExit("sigaction");
printf("Exiting SIGTSTP handler\n");
errno = saved_errno;
}
int main(int argc, char *argv[])
{
struct sigaction sa;
if (sigaction(SIGTSTP, NULL, &sa) == -1)
errExit("sigaction");
if (sa.sa_handler != SIG_IGN)
{
sigemptyset(&sa.sa_mask);
sa.sa_flags = SA_RESTART;
sa.sa_handler = tstp_handler;
if (sigaction(SIGTSTP, &sa, NULL) == -1)
errExit("sigaction");
}
for (;;)
{
pause();
printf("Main\n");
}
}<file_sep>#define _GNU_SOURCE
#include <signal.h>
int my_siginterrupt(int sig, int flag)
{
int ret;
struct sigaction act;
sigaction(sig, NULL, &act);
if (flag)
act.sa_flags &= SA_RESTART;
else
act.sa_flags |= SA_RESTART;
ret = sigaction(sig, &act, NULL);
return ret;
}<file_sep>/*
* WEXITSTATUS(status)
* returns the exit status of the child. This consists of the
* least significant 8 bits of the status argument that the child
* specified in a call to exit(3) or _exit(2) or as the argument
* for a return statement in main(). This macro should be employed
* only if WIFEXITED returned true.
*/
#include <sys/wait.h>
#include <sys/types.h>
#include <unistd.h>
#include "tlpi_hdr.h"
int main(int argc, char *argv[])
{
pid_t pid;
int status;
switch (pid = fork())
{
case -1:
errExit("fork");
case 0:
exit(-1);
default:
if (wait(&status) == -1)
errExit("wait");
if (WIFEXITED(status))
printf("0x%x\n", WEXITSTATUS(status)); // Output 0xff
else
errExit("WIFEXITED");
exit(EXIT_SUCCESS);
}
}<file_sep>#define _BSD_SOURCE
#include <unistd.h>
#include "tlpi_hdr.h"
int main(int argc, char *argv[])
{
if (acct(argv[1]) == -1)
errExit("acct");
printf("Process accounting %s\n", (argv[1] == NULL) ? "disabled" : "enabled");
exit(EXIT_SUCCESS);
}<file_sep>#include <sys/wait.h>
#include <time.h>
#include "tlpi_hdr.h"
int main(int argc, char *argv[])
{
int num_dead;
pid_t child_pid;
int j;
setbuf(stdout, NULL);
for (j = 1; j < argc; ++j)
{
switch (fork())
{
case -1:
errExit("fork");
case 0:
printf("Child %d started with PID %ld, sleeping %s seconds\n",
j, (long)getpid(), argv[j]);
sleep(getInt(argv[j], GN_NONNEG, "sleep-time"));
_exit(EXIT_SUCCESS);
default:
break;
}
}
num_dead = 0;
for (;;)
{
child_pid = wait(NULL);
if (child_pid == -1)
{
if (errno == ECHILD)
{
printf("No more children - bytes\n");
exit(EXIT_SUCCESS);
}
else
{
errExit("wait");
}
}
num_dead++;
printf("wait() returned child PID %ld (num_dead=%d)\n", (long)child_pid, num_dead);
}
}<file_sep>/*
* 练习 4-2
* 简单实现cp,命令格式 cp [src-file] [dest-file]
* cp - copy files and directories
*/
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <fcntl.h>
#ifndef BUF_SIZE
#define BUF_SIZE 1024
#endif
int main(int argc, char *argv[])
{
if (argc != 3)
{
fputs("argements error\n", stderr);
exit(EXIT_FAILURE);
}
int fdRead, fdWrite;
ssize_t numRead;
if ((fdRead = open(argv[1], O_RDONLY)) == -1)
{
fprintf(stderr, "Open \"%s\" error.\n", argv[1]);
exit(EXIT_FAILURE);
}
if ((fdWrite = open(argv[2], O_WRONLY | O_CREAT)) == -1)
{
fprintf(stderr, "Open \"%s\" error.\n", argv[2]);
exit(EXIT_FAILURE);
}
char buf[BUF_SIZE];
while ((numRead = read(fdRead, buf, BUF_SIZE)) > 0)
{
write(fdWrite, buf, numRead);
}
if (close(fdRead) == -1)
{
fprintf(stderr, "Close file \"%s\" error.\n", argv[1]);
exit(EXIT_FAILURE);
}
if (close(fdWrite) == -1)
{
fprintf(stderr, "Close file \"%s\" error.\n", argv[2]);
exit(EXIT_FAILURE);
}
exit(EXIT_SUCCESS);
}<file_sep>#define _GNU_SOURCE
#include <string.h>
#include <signal.h>
#include <time.h>
#include "signal_functions.h"
#include "tlpi_hdr.h"
static volatile sig_atomic_t got_sigquit = 0;
static void handler(int sig)
{
printf("Caught signal %d (%s)\n", sig, strsignal(sig));
if (sig == SIGQUIT)
got_sigquit = 1;
}
int main(int argc, char *argv[])
{
int loop_num;
time_t start_time;
sigset_t orig_mask, block_mask;
struct sigaction sa;
print_sig_mask(stdout, "Initial signal mask is:\n");
sigemptyset(&block_mask);
sigaddset(&block_mask, SIGINT);
sigaddset(&block_mask, SIGQUIT);
if (sigprocmask(SIG_BLOCK, &block_mask, &orig_mask) == -1)
errExit("sigprocmask - SIG_BLOCK");
sigemptyset(&sa.sa_mask);
sa.sa_flags = 0;
sa.sa_handler = handler;
if (sigaction(SIGINT, &sa, NULL) == -1)
errExit("sigaction");
if (sigaction(SIGQUIT, &sa, NULL) == -1)
errExit("sigaction");
for (loop_num = 1; !got_sigquit; ++loop_num)
{
printf("=== LOOP %d\n", loop_num);
print_sig_mask(stdout, "Starting critical section, signal mask is:\n");
for (start_time = time(NULL); time(NULL) < start_time + 4; )
continue;
print_pending_sigs(stdout, "before sigsuspend() - pending signals:\n");
if (sigsuspend(&orig_mask) == -1 && errno != EINTR)
errExit("sigsuspend");
}
if (sigprocmask(SIG_SETMASK, &orig_mask, NULL) == -1)
errExit("sigprocmask");
print_sig_mask(stdout, "=== Exited loop\nRestored signal mask to:\n");
exit(EXIT_SUCCESS);
}<file_sep>#include <signal.h>
#include "fifo_seqnum.h"
int main(int argc, char *argv[])
{
int server_fd, dummy_fd, client_fd;
char client_fifo[CLIENT_FIFO_NAME_LEN];
struct request req;
struct response resp;
int seq_num = 0;
umask(0);
if (mkfifo(SERVER_FIFO, S_IRUSR | S_IWUSR | S_IWGRP) == -1 && errno != EEXIST)
errExit("mkfifo %s", SERVER_FIFO);
server_fd = open(SERVER_FIFO, O_RDONLY);
if (server_fd == -1)
errExit("open %s", SERVER_FIFO);
dummy_fd = open(SERVER_FIFO, O_WRONLY);
if (dummy_fd == -1)
errExit("open %s", SERVER_FIFO);
if (signal(SIGPIPE, SIG_IGN) == SIG_ERR)
errExit("signal");
for (;;)
{
if (read(server_fd, &req, sizeof(struct request)) != sizeof(struct request))
{
fprintf(stderr, "Error reading request; discarding\n");
continue;
}
snprintf(client_fifo, CLIENT_FIFO_NAME_LEN, CLIENT_FIFO_TEMPLATE, (long)req.pid);
client_fd = open(client_fifo, O_WRONLY);
if (client_fd == -1)
{
errMsg("open %s", client_fifo);
continue;
}
resp.seq_num = seq_num;
if (write(client_fd, &resp, sizeof(struct response)) != sizeof(struct response))
fprintf(stderr, "Error writing to FIFO %s\n", client_fifo);
if (close(client_fd) == -1)
errMsg("close");
seq_num += req.seq_len;
}
}<file_sep> > 27-1 The final command in the following shell session uses the program in Listing 27-3 to exec the program xyz. What happens?
```shell
$ echo $PATH
/usr/local/bin:/usr/bin:/bin:./dir1:./dir2
$ ls -l dir1
total 8
-rw-r--r-- 1 mtk users 7860 Jun 13 11:55 xyz
$ ls -l dir2
total 28
-rwxr-xr-x 1 mtk users 27452 Jun 13 11:55 xyz
$ ./t_execlp xyz
```
---
将会从环境变量`./dir2`下找到`xyz`可执行文件并执行。<file_sep>#define _GNU_SOURCE
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
//#include <errno.h>
#include <fcntl.h>
#include <stdio.h>
int effective_access(const char *name, int mode)
{
int ret;
uid_t euid, ruid;
gid_t egid, rgid;
euid = geteuid();
ruid = getuid();
setresuid(euid, ruid, -1);
rgid = getgid();
egid = getegid();
setresgid(egid, rgid, -1);
ret = access(name, mode);
setresuid(ruid, euid, -1);
setresgid(rgid, egid, -1);
return ret;
}
int main(int argc, char argv[])
{
printf("%d\n", effective_access("15-4.c", F_OK | R_OK | W_OK | X_OK));
return 0;
}<file_sep>#define _GNU_SOURCE
#include <signal.h>
#include <string.h>
#include "tlpi_hdr.h"
static int flag = 0;
void handler(int sig)
{
printf("SIG %d is caught.\n", sig);
if (sig == SIGINT)
flag = 1;
}
int main(int argc, char *argv[])
{
sigset_t set;
for (int i = 1; i < NSIG; ++i)
signal(i, handler);
while (flag == 0)
pause();
printf("----------\n");
flag = 0;
// if (sigfillset(&set) == -1)
// errExit("sigfillset");
// if (sigprocmask(SIG_SETMASK, &set, NULL) == -1)
// errExit("sigprocmask");
// sleep(10);
// sigpending(&set);
// for (int i = 1; i < NSIG; ++i)
// {
// if (sigismember(&set, i))
// printf("%d is blocked.\n");
// }
// if (sigemptyset(&set) == -1)
// errExit("signempty");
// sigprocmask(SIG_SETMASK, &set, NULL);
for (int i = 1; i < NSIG; ++i)
signal(i, SIG_IGN);
pause();
// sleep(10);
return 0;
}<file_sep>以下程序运行到`chmod()`函数会出错。这是为什么呢?
```C
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>
#include <fcntl.h>
#include "tlpi_hdr.h"
int main(void)
{
int fd;
mkdir("test", S_IRUSR | S_IWUSR | S_IXUSR);
chdir("test");
fd = open("myfile", O_RDWR | O_CREAT, S_IRUSR | S_IWUSR);
symlink("myfile", "../mylink");
if (chmod("../mylink", S_IRUSR) == -1)
errExit("chmod");
return 0;
}
```
首先了解一下,符号链接本质就是存一串代表路径的字符串作为`handle`,然后就能根据这个路径找到链接的文件。
从linux自带的manual上可以查到,symlink函数原型是:
```C
int symlink(const char *target, const char *linkpath);
```
作用之一是:
> symlink() creates a symbolic link named linkpath which contains the string target.
划重点:*contains the string target*。也就是说符号链接 `mylink` 中存字符串的是`myfile`,对 `myfile` 解引用自然找不到这个文件(因为在test目录下)。
所以符号链接最好直接存绝对路径...防止被坑。<file_sep>#define _XOPEN_SOURCE
#include <sys/stat.h>
#include <signal.h>
#include "become_daemon.h"
#include "tlpi_hdr.h"
static const char *LOG_FILE = "/tmp/ds.log";
static const char *CONFIG_FILE = "/tmp/ds.conf";
static volatile sig_atomic_t hup_received = 0;
static void sighup_handler(int sig)
{
hup_received = 1;
}
int main(int argc, char *argv[])
{
const int SLEEP_TIME = 15;
int count = 0;
int unslept;
struct sigaction sa;
sigemptyset(&sa.sa_mask);
sa.sa_flags = SA_RESTAET;
sa.sa_handler = sighup_handler;
if (sigaction(SIGHUP, &sa, NULL) == -1)
errExit("sigaction");
if (become_daemon(0) == -1)
errExit("become_daemon");
log_open(LOG_FILE);
read_config_file(CONFIG_FILE);
unslept = SLEEP_TIME;
for (;;)
{
unslept = sleep(unslept);
if (hup_received)
log_close();
log_open(LOG_FILE);
read_config_file(CONFIG_FILE);
hup_received = 0;
}
if (unslept = 0)
{
count++;
log_message("Main: %d", count);
unslept = SLEEP_TIME;
}
}<file_sep>#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#include <sys/stat.h>
#include "tlpi_hdr.h"
#define KEY_FILE "/some-path/some-file"
int main(int argc, char *argv[])
{
int msqid;
key_t key;
const int MQ_PERMS = S_IRUSR | S_IWUSR | S_IWGRP; /*rw--w----*/
key = ftok(KEY_FILE, 1);
if (key == -1)
{
errExit("ftok");
}
while ((msqid = msgget(key, IPC_CREAT | IPC_EXCL | MQ_PERMS)) == -1)
{
if (errno == EEXIST)
{
msqid = msgget(key, 0);
if (msqid == -1)
errExit("msgget() failed to retrive old queue ID");
if (msgctl(msqid, IPC_RMID, NULL) == -1)
{
errExit("msgget() failed to delete old queue");
}
printf("Removed old message queue (id=%d)\n", msqid);
}
else
errExit("msgget() failed");
}
exit(EXIT_SUCCESS);
}<file_sep>#define _BSD_SOURCE
#include <time.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
void run(pid_t (*fun)(void), size_t cnt)
{
int status;
clock_t begin, end;
begin = clock();
for (int i = 0; i < cnt; ++i)
{
switch (fun())
{
case -1:
exit(EXIT_FAILURE);
case 0:
_exit(EXIT_SUCCESS);
default:
wait(&status);
break;
}
}
end = clock();
printf("%lf\n", (double)(end-begin)/CLOCKS_PER_SEC);
}
int main(void)
{
const size_t times = 10000;
printf("fork() %llu :", (unsigned long long)times);
run(fork, times);
printf("vfork() %llu :", (unsigned long long)times);
run(vfork, times);
return 0;
}<file_sep>#include <stdio.h>
#include <dlfcn.h>
#include <wait.h>
#include <assert.h>
#include <signal.h>
#include <unistd.h>
#include "tlpi_hdr.h"
int main(void)
{
int status;
void *parent_ret;
pid_t child_pid;
switch(child_pid = fork())
{
case -1:
errExit("fork()");
case 0:
pause();
default:
parent_ret = dlopen("libc.so.6", RTLD_NOW);
if (parent_ret == NULL)
fatal("dlopen: %s", dlerror());
assert(dlclose(parent_ret) == 0);
assert(dlopen("libc.so.6", RTLD_LAZY | RTLD_NOLOAD) != NULL);
//if (parent_ret == NULL)
// fatal("dlopen: %s", dlerror());
printf("libc.so.6 is still in memory\n");
kill(child_pid, SIGINT);
wait(&status);
}
}<file_sep>> Log in as a normal, unprivileged user, create an executable file (or copy an existing file such as /bin/sleep), and enable the set-user-ID permission bit on that file (chmod u+s). Try modifying the file (e.g., cat >> file). What happens to the file permissions as a result (ls –l)? Why does this happen?
---
当文件被非特权用户修改后,内核会清除文件上的 `set-user-ID` 权限位。这么做是为了防止修改这些程序的同时还保留一些特权。
<file_sep>
#include <unistd.h>
#include <sys/types.h>
#include <grp.h>
#include <limits.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#define N (NGROUPS_MAX+1)
int myinitgroups(const char *user, gid_t group);
int main(void)
{
setuid(0);
if (myinitgroups("cyyzero", 42) == -1)
{
printf("initgroups error\n");
exit(-1);
}
gid_t groups[N];
int group_num;
if ((group_num = getgroups(N, groups)) == -1)
printf("getgroups error\n");
printf("Groups: ");
for (int i = 0; i < group_num; ++i)
{
printf("%ld ", (long)groups[i]);
}
printf("\n");
return 0;
}
int myinitgroups(const char *user, gid_t group)
{
size_t i = 0;
gid_t groups[N];
struct group *grp;
while ((grp = getgrent()) != NULL)
{
char **mem = grp->gr_mem;
while (*mem != NULL)
{
if (strcmp(user, *mem) == 0)
{
groups[i++] = grp->gr_gid;
break;
}
++mem;
}
}
endgrent();
groups[i++] = group;
return setgroups(i, groups);
}<file_sep>> Assume a system where the value returned by the call sysconf(_SC_CLK_TCK) is 100. Assuming that the clock_t value returned by times() is an unsigned 32-bit integer, how long will it take before this value cycles so that it restarts at 0? Perform the same calculation for the CLOCKS_PER_SEC value returned by clock().
## 答案:
32位无符号整数最大为 `2^32`。所以需要 `2^32/100` s。
同理, `2^32 / CLOCKS_PER_SEC` 。
<file_sep>#include <pthread.h>
#include <stdint.h>
#include "tlpi_hdr.h"
static pthread_cond_t thread_died = PTHREAD_COND_INITIALIZER;
static pthread_mutex_t thread_mutex = PTHREAD_MUTEX_INITIALIZER;
static int tot_threads = 0;
static int num_live = 0;
static int num_unjoined = 0;
enum tstate
{
TS_ALIVE,
TS_TERMINATED,
TS_JOINED
};
static struct
{
pthread_t tid;
enum tstate state;
int sleep_time;
} *thread;
static void *thread_func(void *arg)
{
uintptr_t idx = (uintptr_t)arg;
int s;
sleep(thread[idx].sleep_time);
printf("Thread %llu terminating\n", (unsigned long long)idx);
s = pthread_mutex_lock(&thread_mutex);
if (s != 0)
{
errExitEN(s, "pthread_mutex_lock");
}
num_unjoined++;
thread[idx].state = TS_TERMINATED;
s = pthread_mutex_unlock(&thread_mutex);
if (s != 0)
errExitEN(s, "pthread_mutex_unlock");
s = pthread_cond_signal(&thread_died);
if (s != 0)
errExitEN(s, "pthread_cond_signal");
return NULL;
}
int main(int argc, char *argv[])
{
int s;
uintptr_t idx;
thread = calloc(argc - 1, sizeof(*thread));
if (thread == NULL)
errExit("calloc");
for (idx = 0; idx < argc-1; ++idx)
{
thread[idx].sleep_time = getInt(argv[idx+1], GN_NONNEG, NULL);
thread[idx].state = TS_ALIVE;
s = pthread_create(&thread[idx].tid, NULL, thread_func, (void*)idx);
if (s != 0)
errExitEN(s, "pthread_create");
}
tot_threads = argc - 1;
num_live = tot_threads;
while (num_live > 0)
{
s = pthread_mutex_lock(&thread_mutex);
if (s != 0)
errExitEN(s, "pthread_mutex_lock");
while (num_unjoined == 0)
{
s = pthread_cond_wait(&thread_died, &thread_mutex);
if (s != 0)
errExitEN(s, "pthread_cond_wait");
}
for (idx = 0; idx < tot_threads; ++idx)
{
if (thread[idx].state == TS_TERMINATED)
{
s = pthread_join(thread[idx].tid, NULL);
if (s != 0)
errExitEN(s, "pthread_join");
thread[idx].state = TS_JOINED;
num_live--;
num_unjoined--;
printf("Reaped thread %llu (num_live=%d)\n", (unsigned long long)idx, num_live);
}
}
s = pthread_mutex_unlock(&thread_mutex);
if (s != 0)
errExitEN(s, "pthread_mutex_unlock");
}
exit(EXIT_SUCCESS);
}<file_sep>#define _GNU_SOURCE
#include <string.h>
#include <signal.h>
#include "tlpi_hdr.h"
static void handler(int sig)
{
printf("PID %ld: caught signal %2d (%s)\n", (long)getpid(), sig, strsignal(sig));
}
int main(int argc, char *argv[])
{
pid_t parent_pid, child_pid;
int j;
struct sigaction sa;
setbuf(stdout, NULL);
parent_pid = getpid();
printf("PID of parent is: %ld\n", (long)getppid());
printf("Foreground process group ID is: %ld\n", (long)tcgetpgrp(STDIN_FILENO));
for (j = 1; j < argc; ++j)
{
child_pid = fork();
if (child_pid == -1)
{
errExit("fork");
}
if (child_pid == 0)
{
if (argv[j][0] == 'd')
{
if (setpgid(0, 0) == -1)
errExit("setpgid");
}
sigemptyset(&sa.sa_mask);
sa.sa_flags = 0;
sa.sa_handler = handler;
if (sigaction(SIGHUP, &sa, NULL) == -1)
errExit("sigaction");
break;
}
}
alarm(60);
printf("PID=%ld PGID=%ld\n", (long)getpid(), (long)getppid());
for (;;)
{
pause();
}
}<file_sep>/*******************************************************************************************************
* 用getenv() putenv()实现setenv函数和unsetenv函数。
*********************************************************************************************************/
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <errno.h>
extern char **environ;
int my_setenv(const char *name, const char *value, int overwrite);
int my_unsetenv(const char*string);
int main()
{
exit(EXIT_SUCCESS);
}
int my_setenv(const char *name, const char *value, int overwrite)
{
if (name == NULL)
{
errno = EINVAL;
return -1;
}
if (override || getenv(name) == NULL)
{
size_t len = strlen(name) + strlen(value) + 2;
char *env_entry = (char *)malloc(len);
if (env_entry == NULL)
{
errno = ENOMEM;
return -1;
}
strcpy(env_entry, name);
env_entry[strlen(name)] = '=';
strcpy(&env_entry[strlen(name)+1], value);
int r = putenv(env_entry);
return r == 0 ? 0 : -1;
}
return 0;
}
int my_unsetenv(const char *name)
{
if (name == NULL)
{
errno = EINVAL;
return -1;
}
size_t n = strlen(name);
int i = 0, j = 0;
while (environ[j] != NULL)
{
if (strncmp(environ[j], name, n) == 0 && environ[j][0] == '=')
{
j++;
}
else
{
if (j != 1)
{
environ[i] = environ[j];
}
i++;
j++;
}
}
environ[i] = NULL;
return 0;
}<file_sep>#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <stdio.h>
int main(int argc, char *argv[])
{
struct stat sb;
for (int i = 1; i < argc; ++i)
{
if (stat(argv[i], &sb) == -1)
{
perror("Fuck U");
continue;
}
sb.st_mode |= (S_IRUSR | S_IRGRP | S_IROTH);
if (S_ISDIR(sb.st_mode) ||
(sb.st_mode & (S_IXUSR | S_IXGRP | S_IXOTH)))
{
sb.st_mode |= (S_IXUSR | S_IXGRP | S_IXOTH);
}
chmod(argv[i], sb.st_mode);
}
return 0;
}<file_sep>/*
* 线程 join 自身会导致运行时错误 ERROR [EDEADLK/EDEADLOCK Resource deadlock avoided] pthread_join
* 在实际编程中应该避免这种情况。比如说在发起 join 操作的时候应该保证第一个参数与 pthread_self() 返回值不同
*/
#include <pthread.h>
#include "tlpi_hdr.h"
void *pthread_func(void *arg)
{
printf("Pthread t1 is running.\n");
}
int main(int argc, char *argv[])
{
pthread_t t1;
int s;
s = pthread_create(&t1, NULL, pthread_func, NULL);
if (s != 0)
errExitEN(s, "pthread_create");
// It occurs a runtime error: ERROR [EDEADLK/EDEADLOCK Resource deadlock avoided] pthread_join
// s = pthread_join(pthread_self(), NULL);
// if (s != 0)
// errExitEN(s, "pthread_join");
printf("Pthread t1 is over.\n");
return 0;
}<file_sep>#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#include <sys/stat.h>
#include "tlpi_hdr.h"
int main(int argc, char *argv[])
{
int num_key_flags;
int flags, msqid, opt;
unsigned int perms;
long lkey;
key_t key;
num_key_flags = 0;
flags1 = 0;
while ((ope = getopt(argc, argv, "cf:k:px")) != -1)
{
switch (opt)
{
case 'c':
flags |= IPC_CREAT;
break;
case 'f':
key = ftok(optarg, 1);
if (key == -1)
errExit("ftok");
num_key_flags++;
break;
case 'k':
if (sscanf(optarg, "%li", &lkey) == -1)
cmdLineErr("-k option requires a numeric argument\n");
key = lkey;
num_key_flags++;
break;
case 'p':
key = IPC_PRIVATE;
num_key_flags++;
break;
case 'x':
flags |= IPC_EXCL;
break;
default:
exit(-1);
}
}
if (num_key_flags != 1)
exit(-1);
perms = (opeind == argc) ? (S_IRUSR | S_IWUSR) :
getInt(argv[optind], GN_BASE_8, "octal-perms");
msqid = msgget(key, flags | perms);
if (msqid == -1)
errExit("msqid");
printf("%d\n", msqid);
exit(EXIT_SUCCESS);
}<file_sep>#include <sys/time.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <sys/resource.h>
#include <stdio.h>
#include "tlpi_hdr.h"
static inline
void print_rusage(const char *leader, const struct rusage *ru)
{
const char *ldr;
ldr = (leader == NULL) ? "" : leader;
printf("%sCPU time (secs): user=%.3f; system=%.3f\n", ldr,
ru->ru_utime.tv_sec + ru->ru_utime.tv_usec / 1000000.0,
ru->ru_stime.tv_sec + ru->ru_stime.tv_usec / 1000000.0);
printf("%sMax resident set size: %ld\n", ldr, ru->ru_maxrss);
printf("%sIntegral shared memory: %ld\n", ldr, ru->ru_ixrss);
printf("%sIntegral unshared data: %ld\n", ldr, ru->ru_idrss);
printf("%sIntegral unshared stack: %ld\n", ldr, ru->ru_isrss);
printf("%sPage reclaims: %ld\n", ldr, ru->ru_minflt);
printf("%sPage faults: %ld\n", ldr, ru->ru_majflt);
printf("%sSwaps: %ld\n", ldr, ru->ru_nswap);
printf("%sBlock I/Os: input=%ld; output=%ld\n",
ldr, ru->ru_inblock, ru->ru_oublock);
printf("%sSignals received: %ld\n", ldr, ru->ru_nsignals);
printf("%sIPC messages: sent=%ld; received=%ld\n",
ldr, ru->ru_msgsnd, ru->ru_msgrcv);
printf("%sContext switches: voluntary=%ld; "
"involuntary=%ld\n", ldr, ru->ru_nvcsw, ru->ru_nivcsw);
}
int main(int argc, char *argv[])
{
struct rusage sr;
switch (fork())
{
case -1:
errExit("fork");
case 0:
execvp(argv[1], &argv[1]);
errExit("execvp");
default:
if (wait(NULL) == -1)
errExit("wait");
if (getrusage(RUSAGE_CHILDREN, &sr) == -1)
errExit("getrusage");
print_rusage("\t", &sr);
}
}<file_sep>#include <stdio.h>
#include <ctype.h>
#include <stdbool.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <fcntl.h>
#include <pwd.h>
#include <dirent.h>
#include "tlpi_hdr.h"
uid_t user_id_from_name(const char* name);
bool is_numbers(const char *name);
bool is_dirent(const char *name);
void read_status(const char *name, uid_t uid);
int main(int argc, char *argv[])
{
char name[1024];
DIR * proc;
struct dirent *dirent;
uid_t uid;
if (argc != 2)
{
fprintf(stderr, "args error\n");
exit(EXIT_FAILURE);
}
uid = user_id_from_name(argv[1]);
if (uid == -1)
errExit("user_id_from_name");
printf("UID:%ld\n", (long)uid);
proc = opendir("/proc");
if (proc == NULL)
errExit("opendir");
while ((dirent = readdir(proc)) != NULL)
{
if (strcmp(dirent->d_name, ".") == 0 || strcmp(dirent->d_name, "..") == 0)
continue;
sprintf(name, "/proc/%s", dirent->d_name);
if (is_dirent(name) && is_numbers(dirent->d_name))
{
strcat(name, "/status");
read_status(name, uid);
}
}
exit(EXIT_SUCCESS);
}
uid_t user_id_from_name(const char* name)
{
struct passwd *pwd;
if (name == NULL || *name == '\0')
return -1;
pwd = getpwnam(name);
if (pwd == NULL)
return -1;
return pwd->pw_uid;
}
bool is_numbers(const char *name)
{
while (*name != '\0')
{
if (!isdigit(*name))
return false;
++name;
}
return true;
}
bool is_dirent(const char *name)
{
struct stat s;
if (stat(name, &s) == -1)
{
errExit("stat");
}
if ((s.st_mode & S_IFMT) == S_IFDIR)
return true;
else
return false;
}
void read_status(const char *name, uid_t uid)
{
FILE *file;
char proc_name[30];
char line[100];
uid_t ruid, euid, suid, fsuid;
file = fopen(name, "r");
if (file == NULL)
errExit("fopen");
fscanf(file, "Name:\t%s", proc_name);
for (int i = 0; i < 8; ++i) {
//fgets()
fgets(line, 100, file);
//puts(line);
}
fscanf(file, "%s%d%d%d%d", line, &ruid, &euid, &suid, &fsuid);
//printf("%d %d %d %d\n", ruid, euid, suid, fsuid);
//puts(proc_name);
if (ruid == uid || euid == uid || suid == uid || fsuid == uid)
puts(proc_name);
}<file_sep>/*
* 练习 4-1
* 简单实现tee命令,必须指明输入的文件,选项也只有-a
* tee - read from standard input and write to standard output and files
*/
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#ifndef BUF_SIZE
#define BUF_SIZE 1024
#endif
void print_usage(void);
int main(int argc, char *argv[])
{
int opt, append_flag = 0;
if (argc != 2 && argc != 3)
{
fprintf(stderr, "%d arguments, error\n",argc);
exit(EXIT_FAILURE);
}
while ( (opt = getopt(argc, argv, "a")) != -1 )
{
switch (opt)
{
case 'a':
append_flag = 1;
break;
case 'h':
case '?':
print_usage();
break;
default:
break;
}
}
if (optind > argc)
exit(EXIT_FAILURE);
char buf[BUF_SIZE];
ssize_t numRead;
int flag = O_WRONLY | O_CREAT;
if (append_flag)
flag |= O_APPEND;
else
flag |= O_TRUNC;
int fd = open(argv[optind], flag,
S_IRUSR | S_IWUSR | S_IRGRP |
S_IWGRP | S_IROTH | S_IWOTH);
if (fd == -1)
{
fputs("open error", stderr);
exit(EXIT_FAILURE);
}
while ((numRead = read(STDIN_FILENO, buf, BUF_SIZE)) > 0)
{
write(fd, buf, numRead);
write(STDOUT_FILENO, buf, numRead);
}
if (numRead == -1)
{
fputs("read error", stderr);
exit(EXIT_FAILURE);
}
if (close(fd) == -1)
{
fputs("close error", stderr);
exit(EXIT_FAILURE);
}
exit(EXIT_SUCCESS);
}
void print_usage(void)
{
fputs("usage:\n-a append to the file\n-h or -? help\ndefalult:wirte a new file or overwrite the file\n", stderr);
exit(EXIT_FAILURE);
}<file_sep>#define _GNU_SOURCE
#include <signal.h>
#include "tlpi_hdr.h"
#define BUF_SIZE 200
static void handler(int sig)
{
printf("Caught signal\n");
}
int main(int argc, char *argv[])
{
struct sigaction sa;
char buf[BUF_SIZE];
ssize_t num_read;
int saved_errno;
sa.sa_flags = (argc > 2) ? SA_RESTART : 0;
sigemptyset(&sa.sa_mask);
sa.sa_handler = handler;
if (sigaction(SIGALRM, &sa, NULL) == -1)
errExit("sigaction");
alarm((argc > 1) ? getInt(argv[1], GN_NONNEG, "num-secs") : 10);
num_read = read(STDIN_FILENO, buf, BUF_SIZE - 1);
saved_errno = errno;
alarm(0);
if (num_read == -1)
{
if (saved_errno == EINTR)
printf("Read timed out\n");
else
errMsg("read");
}
else
{
printf("Successful read (%ld bytes): %.*s", (long)num_read, (int)num_read, buf);
}
exit(EXIT_SUCCESS);
}<file_sep># 《linux/unix系统编程手册》学习记录
## 文件夹组织结构
* tlpi-dist:从[这本书的官网](http://www.man7.org/tlpi/)下载的源码
* chapter-x:第x章节
* example:书中例子
* exercise:书后习题
第三章介绍了后面章节要用到的头文件以及实现,如下
* ename.c.inc 定义了一个字符串数组,用于对应错误码的名称
* error_functions.h 声明了本书自定义的错误处理函数
* get_num.h 声明了本书自定义的数值提取函数
* tlpi_hdr.h 包含了后续需用到的系统调用头文件
由于存在3个头文件以及2个实现,每次编译时必须对实现也进行编译,为方便后续学习,将头文件和静态库复制到默认的编译器寻找目录下。
- 第一步:下载本书所给的源码文件
```
$ wget "http://man7.org/tlpi/code/download/tlpi-161214-dist.tar.gz"
```
- 第二步:解压后,make编译(可以跳过下载和解压的过程,repo已经包含tlpi-dist目录)
```
$ tar -zxvf tlpi-161214-dist.tar.gz
$ cd tlpi-dist/
$ make -j8
```
- 第三步:拷贝头文件和静态库至系统目录
```
$ cd lib/
$ sudo cp tlpi_hdr.h /usr/local/include/
$ sudo cp get_num.h /usr/local/include/
$ sudo cp error_functions.h /usr/local/include/
$ sudo cp ename.c.inc /usr/local/include/
$ sudo cp ../libtlpi.a /usr/local/lib
```
以后每次编译包含上述四个头文件的代码时,需要链接静态库。
以编译 example.c 为例:
```
$ gcc example.c -o example -ltlpi
```
希望以后能坚持学习吧。
<file_sep>#define _XOPEN_SOURCE
#include <unistd.h>
#include <sys/types.h>
#include <sys/prctl.h>
#include <signal.h>
#include "tlpi_hdr.h"
void handler(int sig)
{
if (sig == SIGUSR2)
printf("Parent has been exited\n");
}
int main(void)
{
sigset_t mask;
struct sigaction sa;
pid_t child_pid, ppid;
sigemptyset(&mask);
sigaddset(&mask, SIGUSR1);
sigprocmask(SIG_SETMASK, &mask, NULL);
sigemptyset(&sa.sa_mask);
sa.sa_flags = 0;
sa.sa_handler = handler;
if (sigaction(SIGUSR1, &sa, NULL) == -1)
errExit("sigaction");
if (sigaction(SIGUSR2, &sa, NULL) == -1)
errExit("sigaction");
sigemptyset(&mask);
switch (child_pid = fork())
{
case -1:
errExit("fork");
case 0:
ppid = getppid();
prctl(PR_SET_PDEATHSIG, SIGUSR2);
printf("Child PID is %ld\n", (long)getpid());
printf("Parent PID is %ld\n", (long)ppid);
if (kill(ppid, SIGUSR1) == -1)
errExit("kill");
sigsuspend(&mask);
printf("Now parent PID is %ld\n", (long)getppid());
default:
sigsuspend(&mask);
exit(EXIT_SUCCESS);
}
}<file_sep>/*
* 在我机器上(Linux kernel 4.14.0-041400-generic, gcc 8.1.0)测试的时候,
* 某个线程A fork() 之后子进程退出,SIGCHLD默认是先传给线程A。
* 当在线程A中把 SIGCHLD mask 之后,会传递给其他未屏蔽 SIGCHLD 的线程。
*/
#define _GNU_SOURCE
#include <pthread.h>
#include <signal.h>
#include <sys/wait.h>
#include <sys/types.h>
#include <stdio.h>
#include "tlpi_hdr.h"
volatile pthread_t caught_sig_thread;
void handler(int sig)
{
if (sig == SIGCHLD)
{
caught_sig_thread = pthread_self();
printf("[PID %llu] SIGCHLD is caught\n", (unsigned long long)caught_sig_thread);
}
}
void *thread_func(void *arg)
{
printf("Thread t1 id %llu\n", (unsigned long long)pthread_self());
int status;
sigset_t mask;
sigemptyset(&mask);
sigaddset(&mask, SIGCHLD);
pthread_sigmask(SIG_BLOCK, &mask, NULL);
switch (fork())
{
case -1:
errExit("fork");
case 0:
_exit(EXIT_SUCCESS);
default:
if (wait(&status) == -1)
errExit("wait");
}
}
int main(int argc, char *argv[])
{
for (int i = 0; ; ++i)
{
int s;
struct sigaction sa;
pthread_t t1;
sa.sa_flags = 0;
sigemptyset(&sa.sa_mask);
sa.sa_handler = handler;
sigaction(SIGCHLD, &sa, NULL);
printf("Main thread id %llu\n", (unsigned long long)pthread_self());
s = pthread_create(&t1, NULL, thread_func, NULL);
if (s != 0)
errExitEN(s, "pthread_create");
s = pthread_join(t1, NULL);
if (s != 0)
errExitEN(s, "pthread_join");
if (pthread_equal(caught_sig_thread, pthread_self()))
{
printf("%d\n", i);
}
}
}<file_sep>> 27-3 What output would we see if we make the following script executable and exec() it?
```
#!/bin/cat -n
Hello world
```
---
将会输出:
```
1 #!/bin/cat -n
2 Hello world
```<file_sep>#define _GNU_SOURCE
#include <signal.h>
#define NULL ((void*)0)
typedef void(*sighandler_t)(int);
// parameter disp can be SIG_HOLD or SIG_DEL or SIG_IGN
sighandler_t my_sigset(int sig, sighandler_t disp)
{
sighandler_t ret;
sigset_t mask;
struct sigaction sa;
sigprocmask(SIG_BLOCK, NULL, &mask);
if (sigismember(&mask, sig))
{
ret = SIG_HOLD;
}
else
{
if (sigaction(sig, NULL, &sa) == -1)
ret = (void (*)(int))-1;
else
{
ret = sa.sa_handler;
}
}
if (disp == SIG_HOLD)
{
if (sigemptyset(&mask) == -1)
ret = (void (*)(int))-1;
if (sigaddset(&mask, sig) == -1)
ret = (void (*)(int))-1;
if (sigprocmask(SIG_BLOCK, &mask, NULL) == -1)
ret = (void (*)(int))-1;
}
else
{
if (sigemptyset(&mask) == -1)
ret = (void (*)(int))-1;
if (sigaddset(&mask, sig))
ret = (void (*)(int))-1;
if (sigprocmask(SIG_UNBLOCK, &mask, NULL) == -1)
ret = (void (*)(int))-1;
if (sigemptyset(&sa.sa_mask) == -1)
ret = (void (*)(int))-1;
if (sigaddset(&sa.sa_mask, sig) == -1)
ret = (void (*)(int))-1;
sa.sa_flags = 0;
sa.sa_handler = disp;
if (sigaction(sig, &sa, NULL))
ret = (void (*)(int))-1;
}
return ret;
}
int sighold(int sig)
{
int ret = 0;
sigset_t mask;
if (sigemptyset(&mask) == -1)
ret = -1;
if (sigaddset(&mask, sig) == -1)
ret = -1;
if (sigprocmask(SIG_BLOCK, &mask, NULL) == -1)
ret = -1;
return ret;
}
int sigrelse(int sig)
{
int ret = 0;
sigset_t mask;
if (sigemptyset(&mask) == -1)
ret = -1;
if (sigaddset(&mask, sig) == -1)
ret = -1;
if (sigprocmask(SIG_UNBLOCK, &mask, NULL) == -1)
ret = -1;
return ret;
}
int sigignore(int sig)
{
if (signal(sig, SIG_IGN) == SIG_ERR)
return -1;
else
return 0;
}
int sigpause(int sig)
{
sigset_t mask;
//sigemptyset(&cur);
//sigaddset(&cur, sig);
sigprocmask(SIG_BLOCK, NULL, &mask);
sigdelset(&mask, sig);
sigprocmask(SIG_SETMASK, &mask, NULL);
return sigsuspend(&mask);
}
<file_sep>#define _GNU_SOURCE
#include <time.h>
#include <utmp.h>
#include <paths.h>
#include "tlpi_hdr.h"
int main(int argc, char *argv[])
{
struct utmpx ut;
char *dev_name;
memset(&ut, 0, sizeof(struct utmpx));
ut.ut_type = USER_PROCESS;
strncpy(ut.ut_user argv[1], sizeof(ut.ut_user));
if (time((time_t *)&ut.ut_tv.tv_sec) == -1)
errExit("time");
ut.ut_pid = getpid();
dev_name = ttyname(STDIN_FILENO);
if (dev_name == NULL)
errExit("ttyname");
if (strlen(dev_name) <= 8)
fatal("Terminal name is too short: %s", dev_name);
printf("Creating login entries in utmp and wtmp\n");
printf(" using pid %ld, line %.*s, id %.*s\n",
(long)ut.ut_pid, (int)sizeof(ut.ut_line), ut.ut_line,
(int)sizeof(ut.ut_id), ut.ut_id);
setutent();
if (pututline(&ut) == NULL)
errExit("pututxline");
updwtmpx(_PATH_WTMP, &ut);
sleep((argc > 3) ? getInt(argv[2], GN_NONNEG, "sleep-time") : 15);
ut.ut_type = DEAD_PROCESS;
time((time_t *)&ut.ut_tv.tv_sec);
memset(&ut.ut_user, 0, sizeof(ut.ut_user));
printf("Creating logout entries in utmp and wtmp\n");
setutxent();
if (pututxline(&ut) == NULL)
errExit("pututxline");
updwtmpx(_PATH_WTMP, &ut);
endutxent();
exit(EXIT_SUCCESS);
}<file_sep>/*******************************************************************************
* 内核维护了三个数据结构:
* 1.进程级的文件描述符表
* 2.系统级的打开文件表
* 3.文件系统的i-node表
* 成功调用dup的话(man上的资料):They (指的是newfd和oldfd) refer to the same open file description and
* thus share file offset and file status flags.
* 也就是说公用打开文件表中的一项,从而偏移量相同。
* 而对同一个文件调用两次open的话,打开文件表中会出现两项
* 从而最后结果是写入了 Giddayworld
********************************************************************************/
#include <stdio.h>
#include <sys/stat.h>
#include <unistd.h>
#include <sys/types.h>
#include <fcntl.h>
int main()
{
int fd1, fd2, fd3;
const char *file = "test.txt";
fd1 = open(file, O_RDWR | O_CREAT | O_TRUNC, S_IRUSR | S_IWUSR);
fd2 = dup(fd1);
fd3 = open(file, O_RDWR);
write(fd1, "Hello,", 6);
write(fd2, "world", 6);
lseek(fd2, 0, SEEK_SET);
write(fd1, "HELLO,", 6);
write(fd3, "Gidday", 6);
return 0;
}<file_sep>#include <fcntl.h>
#include <time.h>
#include <sys/stat.h>
#include <sys/acct.h>
#include <limits.h>
#include "ugid_functions.h"
#include "tlpi_hdr.h"
#define TIME_BUF_SIZE 100
static long long compt_to_LL(compt_t ct)
{
const int EXP_SIZE = 3;
const int MANTISSA_SIZE = 13;
const int MANTISSA_MASK = (1 << MANTISSA_SIZE) - 1;
long long mantissa, exp;
mantissa = ct & MANTISSA_MASK;
exp = (ct >> MANTISSA_SIZE) & ((1 << EXP_SIZE) - 1);
return mantissa << (exp * 3);
}
int main(int argc, char *argv[])
{
int acct_file;
struct acct ac;
ssize_t num_read;
char *s;
char time_buf[TIME_BUF_SIZE];
struct tm *loc;
time_t t;
acct_file = open(argv[1], O_RDONLY);
if (acct_file == -1)
errExit("open");
printf("command flags term. user "
"start time CPU elapsed\n");
printf(" status "
" time time\n");
while ((num_read = read(acct_file, &ac, sizeof(struct acct))) > 0)
{
if (num_read != sizeof(struct acct))
fatal("partial read");
printf("%-8.8s ", ac.ac_comm);
printf("%c", (ac.ac_flag & AFORK) ? 'F' : '-');
printf("%c", (ac.ac_flag & ASU ) ? 'S' : '-');
printf("%c", (ac.ac_flag & AXSIG) ? 'X' : '-');
printf("%c", (ac.ac_flag & ACORE) ? 'C' : '-');
#ifdef __linux__
printf(" %#6lx ", (unsigned long)ac.ac_exitcode);
#else
printf(" %#6lx ", (unsigned long)ac.ac_stat);
#endif
s = user_name_from_id(ac.ac_uid);
printf("%-8.8s ", (s == NULL) ? "???" : s);
t = ac.ac_btime;
loc = localtime(&t);
if (loc == NULL)
{
printf("???Unknown time??? ");
}
else
{
strftime(time_buf, TIME_BUF_SIZE, "%Y-%m-%d %T", loc);
printf("%s", time_buf);
}
printf("%5.2f %7.2f ", (double) (comptToLL(ac.ac_utime) +
comptToLL(ac.ac_stime)) / sysconf(_SC_CLK_TCK),
(double) comptToLL(ac.ac_etime) / sysconf(_SC_CLK_TCK));
printf("\n");
}
if (num_read == -1)
errExit("read");
exit(EXIT_SUCCESS);
}<file_sep>#define _XOPEN_SOURCE 500
#include <ftw.h>
#include <stdio.h>
#include <string.h>
size_t sock, lnk, reg, blk, dir, chr, fifo;
int fn(const char *fpath, const struct stat *sb,
int typeflag, struct FTW *ftwbuf)
{
for (int i = 0; i < ftwbuf->level; ++i)
printf("\t");
printf("%s\n", &fpath[ftwbuf->base]);
switch (sb->st_mode & S_IFMT)
{
case S_IFSOCK: ++sock; break;
case S_IFLNK: ++lnk; break;
case S_IFREG: ++reg; break;
case S_IFBLK: ++blk; break;
case S_IFDIR: ++dir; break;
case S_IFCHR: ++chr; break;
case S_IFIFO: ++fifo; break;
}
return 0;
}
int main(void)
{
nftw("../../", fn, 10, 0);
printf("%ld %ld %ld %ld %ld %ld %ld\n", sock, lnk, reg, blk, dir, chr, fifo);
return 0;
}<file_sep>#define _BSD_SOURCE
#define _GNU_SOURCE
#define _XOPEN_SOURCE
#include <unistd.h>
#include <limits.h>
#include <pwd.h>
#include <shadow.h>
#include "tlpi_hdr.h"
uid_t check_password(const char *name);
int main(int argc, char *argv[])
{
uid_t user_id;
if (argc == 1 || argc == 2)
fatal("Error args\n");
if (strcmp("-u", argv[1]) == 0)
user_id = check_password(argv[2]);
else
user_id = check_password("root");
/**
* WTF!!!!!
* How can an unprivileged process change it's user-id?
*/
if (setresuid(user_id, user_id, user_id) == -1)
errExit("setresuid");
if (execvp(argv[3], &argv[4]) == -1)
errExit("execvp");
}
/**
* Get password and check authority
* if Ok, return user id, else exit
*/
uid_t check_user(const char *name)
{
long name_len;
char *password, *encrypted;
int auth_ok;
struct passwd *pwd;
struct spwd *spwd;
name_len = sysconf(_SC_LOGIN_NAME_MAX);
if (name_len == -1)
name_len = 256;
if (strlen(name) > name_len)
fatal("user name too long.\n");
pwd = getpwnam(name);
if (pwd == NULL)
fatal("Couldn't get password record.\n");
spwd = getspnam(name);
if (spwd == NULL && errno == EACCES)
fatal("No permission to read shadow password file\n");
if (spwd != NULL)
pwd->pw_passwd = spwd->sp_pwdp;
password = getpass("Password: ");
encrypted = crypt(password, pwd->pw_passwd);
for (char* p = password; *p != '\0'; )
*p++ = '\0';
if (encrypted == NULL)
errExit("crypt");
auth_ok = strcmp(encrypted, pwd->pw_passwd) == 0;
if (!auth_ok)
printf("Incorrect password\n");
exit(EXIT_FAILURE);
return pwd->pw_uid;
}<file_sep>#include <utmpx.h>
#include <stdio.h>
#include <time.h>
int main(int argc, char *argv[])
{
struct utmpx *ut;
setutxent();
while ((ut = getutxent()) != NULL)
{
if (ut->ut_type == USER_PROCESS || ut->ut_type == LOGIN_PROCESS)
{
printf("%-8s ", ut->ut_user);
printf("%-5s ", ut->ut_line);
printf("%s", ctime((time_t*) &(ut->ut_tv.tv_sec)));
}
}
}<file_sep>#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <fcntl.h>
#include "tlpi_hdr.h"
int main(int argc, char *argv[])
{
struct stat sb;
int fd, umask_bits;
fd = open("test", O_CREAT | O_EXCL, 0777);
if (fd == -1)
errExit("open");
if (stat("test", &sb) == -1)
errExit("stat");
umask_bits = ~(sb.st_mode & 0777) & 0777;
printf("%04o\n", umask_bits);
return 0;
}<file_sep>#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <fcntl.h>
#include <stdlib.h>
#include <ctype.h>
#include "tlpi_hdr.h"
#define BUFFER_SIZE 4096
void count_lines(const char *s, int off, int *offsets, int number_lines, int* current_index)
{
char *ch;
int i = 0;
int pre_i = 0;
for (; s[i] != '\0'; ++i)
{
if (s[i] == '\n')
{
offsets[(*current_index)%number_lines] = off + i;
++*current_index;
//printf("%d :%d\n", current_index, off+i);
}
}
}
int main(int argc, char *argv[])
{
int *offsets;
int fd, current_index = 0, number_lines = 10;
const char *file_name;
char buffer[BUFFER_SIZE];
ssize_t number_bytes;
if (argc != 2 && argc != 3)
usageErr("tail [number] file\n");
if (argc == 3)
{
number_lines = atoi(argv[1]);
file_name = argv[2];
}
else
{
file_name = argv[1];
}
offsets = malloc(sizeof(int) * number_lines);
if (offsets == NULL)
errExit("malloc");
memset(offsets, 0, sizeof(int) * number_lines);
fd = open(file_name, O_RDONLY);
if (fd == -1)
errExit("open");
int cnt = 0;
while ((number_bytes = read(fd, buffer, BUFFER_SIZE)) > 0)
{
//printf("cnt :%d\n", cnt);
//puts(buffer);
count_lines(buffer, cnt * BUFFER_SIZE, offsets, number_lines, ¤t_index);
++cnt;
}
// for(int i = 0; i < number_lines; ++i)
// printf("%d ", offsets[i]);
// printf("curr : %d\n", current_index);
// printf("\n");
if (lseek(fd, (current_index >= number_lines) ? (offsets[(current_index+number_lines) % number_lines] + 1) : current_index, SEEK_SET) == -1)
errExit("lseek");
while ((number_bytes = read(fd, buffer, BUFFER_SIZE)) > 0)
write(STDOUT_FILENO, buffer, number_bytes);
free(offsets);
exit(EXIT_SUCCESS);
}<file_sep>#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/stat.h>
#include <unistd.h>
#include <assert.h>
#include "tlpi_hdr.h"
key_t my_ftok(const char *pathname, int proj_id)
{
key_t key;
struct stat st;
if (stat(pathname, &st) == -1)
{
key = -1;
}
else
{
key = 0;
// printf("%x\n", proj_id&0xff);
key |= (proj_id & 0xff);
// printf("%x\n", key);
key <<= 8;
// printf("%x\n", st.st_dev&0xff);
key |= (st.st_dev & 0xff);
// printf("%x\n", key);
key <<= 16;
// printf("%x\n", st.st_ino&0xffff);
key |= (st.st_ino & 0xffff);
// printf("%x\n", key);
}
return key;
}
int main(void)
{
// printf("%x\n%x\n", my_ftok("./45-2.c", 666), ftok("./45-2.c", 666));
assert(my_ftok("./45-2.c", 666) == ftok("./45-2.c", 666));
}<file_sep>/************************************************************************************
* Q:为什么程序包含了一个约10mb的数组,但可执行文件的大小远小于此?
* A:因为可执行文件加载后才会占据内存。进程与可执行文件不同。
* 详细点来说,对于ELF格式的文件来说,初始化的全局变量和局部静态变量都保存在 .data 段;
* 未初始化的全局变量和局部静态变量都放在 .bss 段。但是只是预留位置,并没有内容(在文件中不占空间)。
*************************************************************************************/
#include <stdio.h>
#include <stdlib.h>
char globBuf[65536];
int primes[] = {2,3,5,7};
static int sequare(int x)
{
int result;
result = x*x;
return result;
}
static void doCalc(int val)
{
printf("The square of %d is %d\n", val, square(val));
if (val < 1000)
{
int t;
t = val * val * val;
printf("The cube of %d is %d\n", val, t);
}
}
int main(int argc, char **argv)
{
static int key = 9973;
static char mbuf[10240000];
char *p;
p = malloc(1024);
doCalc(key);
exit(EXIT_SUCCESS);
}<file_sep>/**********************************************************
* 当文件以O_APPEND标志位打开时,能保证write操作的原子性。
* 从语义上来说,和每次lseek到文件结尾,然后再write等价,但
* 是这么做就不能保证write操作的原子性。
* 比如说以下代码,编译后的可执行文件为 atomic_append
* atomic_append filename num_bytes [x]
* 该程序打开指定的文件(不存在就创建),然后每次调用write写入
* 一个字节,共写入num_bytes个。缺省情况下,用O_APPEND打开,
* 加参数x就每次sleek到文件末尾再写入。
* $ atomic_append f1 1000000 & atomic_append f1 1000000
* $ atomic_append f2 1000000 x & atomic_append f2 1000000 x
* 最后测试结果第一次是完整写入2000000个字节。第二次却因为出现了覆盖(比
* 如两个进程运行到sleek时另一方都还未write,即文件的pos相同,然后write
* 就会覆盖),写入了1000000+字节。
**********************************************************/
#include <sys/types.h>
#include <sys/stat.h>
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#include <stdbool.h>
#include <fcntl.h>
int main(int argc, char ** argv)
{
int fd;
int size;
int flag;
bool append;
ssize_t numWritten;
off_t off;
append = true;
if (argc > 4)
{
fputs("Too many args\n", stderr);
exit(EXIT_FAILURE);
}
if ((size = atoi(argv[2])) == 0)
{
fputs("The second arg is not a number or 0", stderr);
exit(EXIT_FAILURE);
}
if (argc == 4)
{
if (strcmp("x", argv[3]) == 0)
append = false;
else
{
fputs("The third arg is not 'x'", stderr);
exit(EXIT_FAILURE);
}
}
flag = O_WRONLY|O_CREAT;
if (append)
flag |= O_APPEND;
fd = open(argv[1], flag, S_IWUSR | S_IRUSR);
if (append)
{
while (size--)
{
if (write(fd, "1", 1) == -1)
{
fputs("write error\n", stderr);
exit(EXIT_FAILURE);
}
}
}
else
{
while (size--)
{
if (lseek(fd, 0, SEEK_END) == -1)
{
fputs("lseek error\n", stderr);
exit(EXIT_FAILURE);
}
if (write(fd, "0", 1) == -1)
{
fputs("write error\n", stderr);
exit(EXIT_FAILURE);
}
}
}
close(fd);
return 0;
}
<file_sep>#include "tlpi_hdr.h"
int main(int argc, char *argv[])
{
execlp(argv[1], argv[1], "Hello world", NULL);
errExit("execlp");
}<file_sep>/*
* 父进程阻塞 SIGCHLD 信号,并wait子进程。子进程退出仍会发送 SIGCHLD 信号。
* 这意味着当前进程调用 system() 后,会收到一个 SIGCHLD 信号,需要程序猿对这个信号正确地处理。
* 可以试着编译 test.c 查看运行结果。
*/
#define _XOPEN_SOURCE
#include <signal.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include "tlpi_hdr.h"
void handler(int sig)
{
printf("SIGCHLD is caught!\n");
}
int main(void)
{
int status;
sigset_t mask;
struct sigaction sa;
sigemptyset(&mask);
sigaddset(&mask, SIGCHLD);
sigprocmask(SIG_BLOCK, &mask, NULL);
sigemptyset(&sa.sa_mask);
sa.sa_flags = 0;
sa.sa_handler = handler;
sigaction(SIGCHLD, &sa, NULL);
switch (fork())
{
case -1:
errExit("fork");
case 0:
_exit(EXIT_SUCCESS);
default:
if (wait(&status) == -1)
errExit("wait");
sigprocmask(SIG_UNBLOCK, &mask, NULL);
exit(EXIT_SUCCESS);
}
}<file_sep>#include <sys/types.h>
#include <pthread.h>
#include <stdbool.h>
#include "tlpi_hdr.h"
struct init_info
{
bool has_called;
pthread_mutex_t mtx;
};
static struct init_info control = { false, PTHREAD_MUTEX_INITIALIZER };
int one_time_init(struct init_info *control, void (*init)(void))
{
int s;
s = pthread_mutex_lock(&control->mtx);
if (s != 0)
errExitEN(s, "pthread_mutex_lock");
if (!control->has_called)
{
init();
control->has_called = true;
}
s = pthread_mutex_unlock(&control->mtx);
if (s != 0)
errExitEN(s, "pthread_mutex_unlock");
}
void initialize(void)
{
printf("Initialize() is being called.\n");
}
void *thread_func(void *arg)
{
one_time_init(&control, initialize);
printf("Thread %llu has been called.\n", (unsigned long long)pthread_self());
}
int main(void)
{
const int THREAD_LEN = 10;
int s;
pthread_t t[THREAD_LEN];
for (int i = 0; i < THREAD_LEN; ++i)
{
pthread_create(&t[i], NULL, thread_func, NULL);
pthread_detach(t[i]);
}
exit(EXIT_SUCCESS);
}<file_sep>#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#define MAX_READ 20
int main(int argc, char* argv[])
{
char buffer[MAX_READ];
/* if(read(STDIN_FILENO, buffer, MAX_READ) == -1)
{
fputs("read", stderr);
_exit(-1);
}
*/
//输出的结果可能会有点带有其他字符,因为read函数不会给buffer末尾添加/0
//因为输入信息可能是其他二进制形式的数据结构,read()无法区分这些数据
//所以无法遵从C语言对字符串处理的约定,正确方法如下
ssize_t numRead;
numRead = read(STDIN_FILENO, buffer, MAX_READ);
if (numRead == -1) {
fputs("read", stderr);
_exit(EXIT_FAILURE);
}
buffer[numRead] = '\0';
printf("The input data was: %s\n", buffer);
return 0;
}
<file_sep>#define _XOPEN_SOURCE
#include <signal.h>
#include <setjmp.h>
#include <stdio.h>
#include "tlpi_hdr.h"
void my_abort(void)
{
// unblock the SIGABRT signal.
sigset_t set;
sigemptyset(&set);
sigaddset(&set, SIGABRT);
sigprocmask(SIG_UNBLOCK, &set, NULL);
// Raise SIGABRT
raise(SIGABRT);
// If the SIGABRT signal is ignored, or caught by a handler that returns,
// the abort() function will still terminate the process. It does this by
// restoring the default disposition for SIGABRT and then raising the sig‐
// nal for a second time.
signal(SIGABRT, SIG_DFL);
raise(SIGABRT);
}
sigjmp_buf env;
void handler_not_return(int sig)
{
printf("SIGABORT is caugnt!\n");
siglongjmp(env, 1);
}
void handler_return(int sig)
{
printf("SIGABORT is caught! It will return.\n");
}
int main(void)
{
sigset_t set;
sigemptyset(&set);
sigaddset(&set, SIGABRT);
sigprocmask(SIG_BLOCK, &set, NULL);
printf("SIGABRT is blocked!");
raise(SIGABRT);
printf("SIGABRT has been raised.\n");
if (sigsetjmp(env, 1) == 0)
{
printf("sigsetjmp called\n");
if (signal(SIGABRT, handler_not_return) == SIG_ERR)
errExit("signal");
}
else
{
printf("Return from abort\n");
if (signal(SIGABRT, handler_return) == SIG_ERR)
errExit("signal");
}
my_abort();
printf("Call abort!\n");
}<file_sep>#define _XOPEN_SOURCE
#include <unistd.h>
#include <signal.h>
#include <sys/wait.h>
#include <sys/types.h>
#include <errno.h>
int system(const char *command)
{
sigset_t block_mask, orig_mask;
struct sigaction sa_ignore, sa_orig_quit, sa_orig_int, sa_default;
pid_t child_pid;
int status, saved_errno;
if (command == NULL)
return system(":") == 0;
sigemptyset(&block_mask);
sigaddset(&block_mask, SIGCHLD);
sigprocmask(SIG_BLOCK, &block_mask, &orig_mask);
sa_ignore.as_handler = SIG_IGN;
sa_ignore.sa_flags = 0;
sigemptyset(sa_ignore.sa_mask);
sigaction(SIGINT, &sa_ignore, &sa_orig_int);
sigaction(SIGQUIT, &sa_ignore, &sa_orig_quit);
switch(child_pid = fork())
{
case -1:
status = -1;
break;
case 0:
sa_default.sa_handler = SIG_DFL;
sa_default.sa_flags = 0;
sigemptyset(&sa_default.sa_mask);
if (sa_orig_int.sa_handler != SIG_IGN)
sigaction(SIGINT, &sa_default, NULL);
if (sa_orig_quit.sa_handler != SIG_IGN)
sigaction(SIGQUIT, &sa_default, NULL);
sigprocmask(SIG_SETMASK, &orig_mask, NULL);
execl("/bin/sh", "sh", "-c", command, NULL);
_exit(127);
default:
while (waitpid(child_pid, &status, 0) == -1)
{
if (errno != EINTR)
{
status = -1;
break;
}
}
break;
}
saved_errno = errno;
sigprocmask(SIG_SETMASK, &orig_mask, NULL);
sigaction(SIGINT, &sa_orig_int, NULL);
sigaction(SIGQUIT, &sa_orig_quit, NULL);
errno = saved_errno;
return status;
}<file_sep>#include <utmp.h>
#include <unistd.h>
#include <time.h>
#include <string.h>
void my_login(const struct utmp *ut)
{
// char *dev_name;
// memset(&ut, 0, sizeof(struct utmp));
// ut->ut_type = USER_PROCESS;
// ut->ut_pid = getpid();
// time((time_t *)&ut->ut_tv.tv_sec);
// dev_name = ttyname(STDIN_FILENO);
// if (dev_name == NULL)
// {
// dev_name = ttyname(STDOUT_FILENO);
// if (dev_name == NULL)
// {
// dev_name = ttyname(STDERR_FILENO);
// if (dev_name == NULL)
// {
// strncpy(ut->ut_line, "???", sizeof(UT_LINESIZE));
// }
// }
// }
// strncpy(ut->ut_line, dev_name + 5, sizeof(UT_LINESIZE));
// strncpy(ut->ut_id, dev_name+8, 4);
setutent();
pututline(ut);
updwtmp(_PATH_WTMP, ut);
}
int my_logout(const struct utmp *ut_line)
{
struct utmp *ut;
setutent();
while ((ut = getutent()) != NULL)
{
if (strcmp(ut_line->ut_line, ut->ut_line) && ut_line->ut_id == ut->ut_id)
{
ut->ut_type = DEAD_PROCESS;
memset(ut->ut_user, 0, UT_NAMESIZE);
memset(ut->ut_host, 0, UT_HOSTSIZE);
time((time_t *)&ut->ut_tv.tv_sec);
return 1;
}
}
endutent();
return 0;
}
void my_logwtmp(const char *line, const char *name, const char *host)
{
struct utmp ut;
memset(&ut, 0, sizeof(ut));
if (strlen(line) + 1 > UT_LINESIZE)
return;
strcpy(ut.ut_line, line);
if (strlen(name) + 1 > UT_NAMESIZE)
return;
strcpy(ut.ut_user, name);
if (strlen(host) + 1 > UT_HOSTSIZE)
return;
strcpy(ut.ut_host, host);
updwtmp(_PATH_WTMP, &ut);
}<file_sep>#include "tlpi_hdr.h"
int main(int argc, char *argv[])
{
int pfd[2];
int j, dummy;
setbuf(stdout, NULL);
printf("Parent started\n");
if (pipe(pfd) == -1)
errExit("pipe");
for (j = 1; j < argc; ++j)
{
switch (fork())
{
case -1:
errExit("fork");
case 0:
if (close(pfd[0]) == -1)
errExit("close");
sleep(getInt(argv[j], GN_NONNEG, "sleep-time"));
printf("Chid %d (PID=%ld) closing pipe\n", j, (long)getpid());
if (close(pfd[1]) == -1)
errExit("close");
_exit(EXIT_SUCCESS);
default:
break;
}
}
if (close(pfd[1]) == -1)
errExit("close");
if (read(pfd[0], &dummy, 1) != 0)
fatal("parent didn't get EOF");
printf("Parent ready to go\n");
exit(EXIT_SUCCESS);
}<file_sep># 文件描述符表和打开文件之间的关系
内核维护了三个数据结构:
- 进程级的文件描述符( open file descriptor )表。该表的每一条目都记录了单个文件描述系统的相关信息。如下所示
- 控制文件描述符操作的一组表示。根据书中所描述,目前为止(此处存疑,我没探究具体是哪个内核版本)就定义了一个,即 `close-on-exec` 标志。
- 对打开文件句柄的引用。
- 系统级的打开文件表(open file description table)。表中各个条目成为打开文件句柄( open file handle ),存储了打开文件的全部信息:
- 当前文件的偏移量
- 打开文件时所使用的状态标志位 (open() 的flag参数)
- 文件访问模式 (open() 时设置的只读,只写或者读写)
- 与信号驱动 I/O 相关的设置
- 对文件 i-node 对象的引用
- 文件系统的i-node表。慈湖忽略 i-node 在磁盘和内存中的表示差异。大概有如下信息:
- 文件类型
- 一个指针,指向该文件所持有的锁的列表
- 文件的各种属性,包括文件大小以及与不同类型操作相关的时间戳
所以,有可能会出现如下情况:
- 相同进程内的不同文件描述符指向同一个打开文件句柄。 (可能通过 dup()等操作)
- 不同进程内的文件描述符指向同一个打开文件句柄。 (可能在 fork() 后出现这种情况)
- 不同进程内的文件描述符指向不同的打开文件句柄,但是这些句柄都指向 i-node 表中相同的条目。 (可能在不同进程内 open 了同一个文件)
<file_sep>正常来说按写模式打开一个正在执行的可执行文件是会失败的(`open()`调用返回-1,且将`errno`置为`ETXTBSY`)。但是是可以"覆盖"。比如说以下的执行就会成功:
```shell
$ cc -o longrunner longrnnner.c
$ ./longrnner &
$ vi longrunner.c
$ cc -o longrunner longrunner.c
```
每次用 `ls -il` 命令查看后就会发现,编译出来的新的可执行文件文件有了的新的i节点,而不会直接覆盖原文件的i-node编号。
<file_sep>#define _GNU_SOURCE
#include <signal.h>
#include "tlpi_hdr.h"
static void handler(int sig)
{
printf("SIGINT is caught.\n");
}
int main(int argc, char *argv[])
{
struct sigaction sb;
sigemptyset(&sb.sa_mask);
sb.sa_handler = handler;
// sb.sa_flags = SA_RESETHAND;
// sigaction(SIGINT, &sb, NULL);
// sleep(10);
// printf("----------\n");
sb.sa_flags = SA_RESETHAND;
sigaction(SIGINT, &sb, NULL);
while (1)
sleep(1);
}<file_sep>#define _GNU_SOURCE
#include <sys/types.h>
#include <sys/msg.h>
#include "tlpi_hdr.h"
#define MAX_MTEXT 1024
struct mbuf
{
long mtype;
char mtext[MAX_MTEXT];
};
int main(int argc, char *argv[])
{
int msqid, flags, type;
ssize_t msg_len;
size_t max_bytes;
struct mbuf msg;
int opt;
flags = 0;
type = 0;
while ((opt = getopt(argc, argv, "ent:x")) != -1)
{
switch (opt)
{
case 'e': flags |= MSG_NOERROR; break;
case 'n': flags |= IPC_NOWAIT; break;
case 't': type = atoi(optarg); break;
#ifdef MSG_EXCEPT
case 'x': flags |= MSG_EXCEPT; break;
#endif
default: exit(-1);
}
}
if (argc < optind + 1 || argc > optind + 2)
exit(-1);
msqid = getInt(argv[optind], 0, "msqid");
max_bytes = (argc > optind + 1) ?
getInt(argv[optind + 1], 0, "max-bytes") : MAX_MTEXT;
mag_len = msgrcv(msqid, &msg, max_bytes, type, flags);
if (msg_len == -1)
errExit("msgrcv");
printf("Received: type=%ld; length=%ld", msg.bytes, (long)msg_len);
if (msg_len > 0)
printf("; body=%s", msg.mtext);
printf("\n");
exit(EXIT_SUCCESS);
}<file_sep>> 29-2. Aside from the absence of error checking and various variable and structure declarations, what is the problem with the following program?
```C
static void *
threadFunc(void *arg)
{
struct someStruct *pbuf = (struct someStruct *) arg;
/* Do some work with structure pointed to by 'pbuf' */
}
int
main(int argc, char *argv[])
{
struct someStruct buf;
pthread_create(&thr, NULL, threadFunc, (void *) &buf);
pthread_exit(NULL);
}
```
---
感觉问题是在于传给新线程的指针指向别的线程栈上的数据,必须保证它们之间同步才能正常工作,否则容易出现 `dangling pointer`。<file_sep>#include <sys/wait.h>
#include "print_wait_status.h"
#include "tlpi_hdr.h"
int main(int argc, char *argv[])
{
int status;
pid_t child_pid;
switch (fork())
{
case -1:
errExit("fork");
case 0:
printf("Child started with PID = %ld\n", (long)getpid());
if (argc > 1)
exit(getInt(argv[1], 0, "exit-status"));
else
for(;;)
pause();
exit(EXIT_SUCCESS);
default:
for (;;)
{
child_pid = waitpid(-1, &status, WUNTRACED
#ifdef WCONTINUED
| WCONTINUED
#endif
);
if (child_pid == -1)
errExit("waitpid");
printf("waitpid() returned: PID=%ld;status=0x%04d (%d,%d)\n",
(long)child_pid, (unsigned int)status, status >> 8, status & 0xff);
print_wait_status(NULL, status);
if (WIFEXITED(status) || WIFSIGNALED(status))
exit(EXIT_SUCCESS);
}
}
}<file_sep>#include <sys/times.h>
#include <time.h>
#include "tlpi_hdr.h"
static void display_process_times(const char *msg)
{
struct tms t;
clock_t clock_time;
static long clock_ticks = 0;
if (msg != NULL)
printf("%s", msg);
if (clock_ticks == 0)
{
clock_ticks = sysconf(_SC_CLK_TCK);
if (clock_ticks == -1)
errExit("sysconf");
}
clock_time = clock();
if (clock_time == -1)
errExit("clock");
printf(" clock() returns: %ld clock-per-sec (%.2f secs)\n",
(long)clock_time, (double)clock_time/CLOCKS_PER_SEC);
if (times(&t) == -1)
errExit("times");
printf(" times() yields: user cpu=%.2f; system CPU: %.2f\n",
(double)t.tms_utime/clock_ticks,
(double)t.tms_stime/clock_ticks);
}
int main(int argc, char *argv[])
{
int num_cells, j;
printf("CLOCKS_PER_SEC=%ld sysconf(_SC_CLK_TCK)=%ld\n\n",
(long)CLOCKS_PER_SEC, sysconf(_SC_CLK_TCK));
display_process_times("At program start:\n");
num_cells = (argc > 1) ? getInt(argv[1], GN_GT_0, "num-calls") : 100000000;
for (j = 0; j < num_cells; ++j)
(void)getppid();
display_process_times("After getppid() loop:\n");
exit(EXIT_SUCCESS);
}<file_sep>/******************************************
* 用fcntl实现dup和dup2
* 用fcntl(oldfd, F_GETFL) 可以检查oldfd是否打开,
* 未打开返回-1
*******************************************/
#include <stdio.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
int mydup(int oldfd);
int mydup2(int oldfd, int newfd);
int main(int argc, char **argv)
{
int fd, newfd;
newfd = mydup(0);
printf("old fd is 0, new fd is %d\n", newfd);
newfd = mydup2(0, 4);
printf("old fd is 0, new fd is %d\n", newfd);
return 0;
}
int mydup(int oldfd)
{
return fcntl(oldfd, F_DUPFD, 0);
}
int mydup2(int oldfd, int newfd)
{
if (newfd < 0)
{
errno = EBADF;
return -1;
}
if (fcntl(oldfd, F_GETFL) == -1)
return -1;
if (oldfd == newfd)
return old;
close(newfd);
return fcntl(oldfd, F_DUPFD, newfd);
}<file_sep>#define _GNU_SOURCE
#include <stdio.h>
#include <string.h>
#include <pthread.h>
#include "tlpi_hdr.h"
static pthread_once_t once = PTHREAD_ONCE_INIT;
static pthread_key_t strerror_key;
#define MAX_ERROR_LEN 256
static void destructor(void *buf)
{
free(buf);
}
static void create_key(void)
{
int s;
s = pthread_key_create(&strerror_key, destructor);
if (s != 0)
errExitEN(s, "pthread_key_create");
}
char *strerror(int err)
{
int s;
char *buf;
s = pthread_once(&once, create_key);
if (s != 0)
errExitEN(s, "pthread_once");
buf = pthread_getspecific(strerror_key);
if (buf == NULL)
{
buf = malloc(MAX_ERROR_LEN);
if (buf == NULL)
errExit("malloc");
s = pthread_setspecific(strerror_key, buf);
if (s != 0)
errExitEN(s, "pthread_setspecific");
}
if (err < 0 || err > _sys_nerr || _sys_errlist[err] == NULL)
{
snprintf(buf, MAX_ERROR_LEN-1, "Unknown error %d", err);
}
else
{
strncpy(buf, _sys_errlist[err], MAX_ERROR_LEN-1);
buf[MAX_ERROR_LEN-1] = '\0';
}
return buf;
}<file_sep>#include <unistd.h>
#include <stdarg.h>
#include <stdio.h>
#include <assert.h>
#include <stdlib.h>
#include <string.h>
#include <stdbool.h>
extern char **environ;
int execle(const char *path, const char *arg, ...
/*, (char *)NULL, char * const envp[]*/)
{
const char * args_list[200];
char pathname[200];
bool has_slash;
size_t i;
va_list args;
va_start(args, arg);
char *const *envp;
has_slash = false;
i = 0;
args_list[i++] = arg;
for (const char *p; (p = va_arg(args, const char*)) != NULL; )
{
args_list[i++] = p;
printf("%s", p);
}
args_list[i] = NULL;
envp = va_arg(args, char * const *);
assert(environ == envp);
va_end(args);
for (int i = 0; path[i] != '\0'; ++i)
{
if (path[i] == '/')
{
has_slash = true;
break;
}
}
if (has_slash)
{
execve(path, (char * const*)args_list, envp);
}
else
{
char *env_path = getenv("PATH");
const char *end, *begin;
begin = end = env_path;
while ((end = strchr(end, ':')) != NULL)
{
size_t len = end - begin;
memcpy(pathname, begin, len+1);
pathname[len] = '/';
pathname[len+1] = '\0';
strncat(pathname, path, 199-len);
//args_list[0] = pathname;
execve(pathname, (char * const*)args_list, envp);
end++;
begin = end;
}
}
return -1;
}
int main(int argc, char *argv[])
{
execle("ls", "ls", "-l", "-a", "-h", NULL, environ);
}<file_sep>#define _BSD_SOURCE
#include <unistd.h>
#include <sys/types.h>
#include <assert.h>
#include "tlpi_hdr.h"
int main(int argc, char *argv[])
{
pid_t pid;
switch (pid = vfork())
{
case -1:
errExit("vfork");
case 0:
if (close(STDOUT_FILENO) == -1)
errExit("close");
assert(write(STDOUT_FILENO, "child-fuck\n", 12) == -1);
_exit(EXIT_SUCCESS);
default:
write(STDOUT_FILENO, "parent-fuck\n", 13);
exit(EXIT_SUCCESS);
}
}<file_sep>#define _GNU_SOURCE
#include <signal.h>
#include <sys/wait.h>
#include "print_wait_status.h"
#include "tlpi_hdr.h"
static volatile int num_live_children = 0;
static void sigchld_handler(int sig)
{
int status, saved_errno;
pid_t child_pid;
saved_errno = errno;
printf("handler: Caught SIGCHLD\n");
while ((child_pid = waitpid(-1, &status, WNOHANG)) > 0)
{
printf("handler: Reaped child %ld - ", (long)child_pid);
num_live_children--;
}
if (child_pid == -1 && errno != ECHILD)
errMsg("waitpid");
sleep(5);
printf("handler: returning\n");
errno = saved_errno;
}
int main(int argc, char *argv[])
{
int j, sig_cnt;
sigset_t block_mask, empty_mask;
struct sigaction sa;
setbuf(stdout, NULL);
sig_cnt = 0;
num_live_children = argc - 1;
sigemptyset(&sa.sa_mask);
sa.sa_flags = 0;
sa.sa_handler = sigchld_handler;
if (sigaction(SIGCHLD, &sa, NULL) == -1)
errExit("sigaction");
sigemptyset(&block_mask);
sigaddset(&block_mask, SIGCHLD);
if (sigprocmask(SIG_SETMASK, &block_mask, NULL) == -1)
{
errExit("sigprocmask");
}
for (j = 1; j < argc; ++j)
{
switch (fork())
{
case -1:
errExit("fork");
case 0:
sleep(getInt(argv[j], GN_NONNEG, "child-sleep-time"));
printf("Child %d (PID=%ld) exiting\n", j, (long)getpid());
_exit(EXIT_SUCCESS);
default:
break;
}
}
sigemptyset(&empty_mask);
while (num_live_children > 0)
{
if (sigsuspend(&empty_mask) == -1 && errno != EINTR)
errExit("sigsuspend");
sig_cnt++;
}
printf("All %d children have terminated; SIGHLD was caught %d times\n",
argc-1, sig_cnt);
exit(EXIT_SUCCESS);
}<file_sep>// 父进程能够在子进程执行 exec() 之前修改子进程的进程 ID, 但是无法在执行 exec() 之后修改
// 子进程的进程组 ID
#include <signal.h>
#include <stdio.h>
#include "tlpi_hdr.h"
int main(void)
{
pid_t child_pid;
switch (child_pid = fork())
{
case -1:
errExit("fork");
case 0:
sleep(3);
if (execl("./a.out", "./a.out", NULL) == -1)
errExit("execl");
default:
//sleep(3);
if (setpgid(child_pid, child_pid) == -1)
errExit("setpgid");
}
}<file_sep>> Try compiling a program with and without the –static option, to see the difference in size between an executable dynamically linked with the C library and one that is linked against the static version of the C library.
---
用一个很简单的调用`printf()`做了下测试,静态链接的大小为892K,动态链接的大小为8.2K。有丶真实。后来又让`main()`函数体为空做了下测试,发现静态链接仍然有890K。看来可执行文件中`main()`调用的的入口和出口还是很复杂的。<file_sep>#define _GNU_SOURCE
#include <sys/signalfd.h>
#include <signal.h>
#include "tlpi_hdr.h"
int main(int argc, char *argv[])
{
sigset_t mask;
int sfd, j;
struct signalfd_siginfo fdsi;
ssize_t s;
printf("PID = %ld\n", (long)getpid());
sigemptyset(&mask);
for (j = 1; j < argc; ++j)
sigaddset(&mask, atoi(argv[j]));
sfd = signalfd(-1, &mask, 0);
if (sfd == -1)
errExit("signalfd");
for (;;)
{
s = read(sfd, &fdsi, sizeof(struct signalfd_siginfo));
if (s != sizeof(struct signalfd_siginfo))
errExit("read");
printf("got signal %d", fdsi.ssi_signo);
if (fdsi.ssi_code == SI_QUEUE)
{
printf("; ssi_pid=%d;ssiint=%d", fdsi.ssi_pid, fdsi.ssi_int);
}
printf("\n");
}
}<file_sep>#include <sys/xattr.h>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(int argc, char *argv[])
{
int opt;
const char *name, *value;
name = value = NULL;
while ((opt = getopt(argc, argv, "n:v:")) != -1)
{
switch (opt)
{
case 'n':
name = optarg;
break;
case 'v':
value = optarg;
break;
default:
printf("Error arg -%c\n", (char)opt);
exit(EXIT_FAILURE);
}
//printf("-%c: %s\n", (char)opt, optarg);
}
if (name != NULL)
setxattr(argv[optind], name, value, strlen(value), 0);
return 0;
}
<file_sep>#include "tlpi_hdr.h"
int main(int argc, char *argv[])
{
char *env_vec[] = {"GREET=salut", "BYE=adieu", NULL};
char *filename;
filename = strchr(argv[1], '/');
if (filename != NULL)
filename++;
else
filename = argv[1];
execle(argv[1], filename, "hello world", NULL, env_vec);
errExit("execle");
}<file_sep>> 8-1:执行下列代码时,将会发现,尽管这两个用户在密码文件中对应不同的ID,但该程序的输出还是会将同一个数字显示两次。请问为什么?
```C
printf("%ld %ld\n", (long) (getpwnam("avr")->pw_uid),
(long) (getpwnam("tsr")->pw_uid));
```
这里作者是想强调`getpwnam()`是不可重入的,但例子有问题的,参数被复制过去,所以会打印出不同的值。作者也给出了勘误:(http://www.man7.org/tlpi/errata/index.html)[http://www.man7.org/tlpi/errata/index.html]。在第166条。
现在例子改成了:
```C
printf("%s %s\n", getpwuid(uid1)->pw_name,
getpwuid(uid2)->pw_name);
```<file_sep>#include <sys/time.h>
unsigned int alarm(unsigned int seconds)
{
struct itimerval new_value;
struct itimerval old_value;
new_value.it_value.tv_sec = seconds;
new_value.it_value.tv_usec = 0;
new_value.it_interval.tv_sec = 0;
new_value.it_interval.tv_sec = 0;
setitimer(ITIMER_REAL, &new_value, &old_value);
return old_value.it_value.tv_sec;
}<file_sep>#define _GNU_SOURCE
#include <sys/resource.h>
#include <unistd.h>
#include <stdlib.h>
#include "tlpi_hdr.h"
extern char **environ;
int main(int argc, char *argv[])
{
int prio;
prio = getpriority(PRIO_PROCESS, 0);
if (prio == -1)
errExit("getpriority");
if (argc == 1)
{
printf("%d\n", prio);
}
else
{
int opt, flag, add_nice;
while ((opt = getopt(argc, argv, "n:")) != -1)
{
switch (opt)
{
case 'n':
flag = 1;
add_nice = getInt(optarg, 0, "add_nice");
break;
default:
fatal("Unknown args");
}
}
if (optind < argc-1)
fatal("Error\n");
if (setpriority(PRIO_PROCESS, 0, prio + add_nice) == -1)
errExit("setpriority");
if (execvp(argv[optind], argv+optind) == -1)
errExit("execve");
}
}<file_sep>#include <sys/types.h>
#include <pwd.h>
#include <string.h>
#include <stdio.h>
struct passwd *mygetpwnam(const char*);
int main(int argc, char *argv[])
{
struct passwd* passwd = mygetpwnam("cyyzero");
if (passwd != NULL)
{
printf("%s\n%s\n%ld\n%ld\n%s\n%s\n%s", passwd->pw_name,
passwd->pw_passwd,
(long)passwd->pw_uid,
(long)passwd->pw_gid,
passwd->pw_gecos,
passwd->pw_dir,
passwd->pw_shell);
}
}
struct passwd *mygetpwnam(const char* name)
{
static char pw_name[21];
static char pw_passwd[21];
static char pw_gecos[101];
static char pw_dir[21];
static char pw_shell[21];
static struct passwd ret_passwd = { pw_name, pw_passwd, 1000, 1000,
pw_gecos, pw_dir, pw_shell };
struct passwd *passwd;
while ((passwd = getpwent()) != NULL)
{
if (strcmp(name, passwd->pw_name) == 0)
{
strncpy(ret_passwd.pw_name, passwd->pw_name, 20);
strncpy(ret_passwd.pw_passwd, passwd->pw_passwd, 20);
ret_passwd.pw_uid = passwd->pw_uid;
ret_passwd.pw_gid = passwd->pw_gid;
strncpy(ret_passwd.pw_gecos, passwd->pw_gecos, 100);
strncpy(ret_passwd.pw_dir, passwd->pw_dir, 20);
strncat(ret_passwd.pw_shell, passwd->pw_shell, 20);
return &ret_passwd;
}
}
return NULL;
}<file_sep>#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/stat.h>
#include <unistd.h>
#include "tlpi_hdr.h"
const char* FILE_PATH = "45-1.c";
int main(void)
{
struct stat st;
key_t key;
int proj_id;
if (stat(FILE_PATH, &st) == -1)
errExit("stat");
proj_id = 0x1234;
key = ftok(FILE_PATH, proj_id);
printf("key: %x\n", key);
printf("inode: %lx\n", st.st_ino);
printf("device: %lx\n", st.st_dev);
printf("proj_id:%x\n", proj_id);
/*
key 比特示意 |31|30|...|1|0|
key 31-24位是prod_id的低8位,23-16位是次设备号,即st_dev的低8位,15-0是i节点的低16位。
key |= (proj_id & 0xff);
key <<= 8;
key |= (st.st_dev & 0xff);
key <<= 16;
key |= (st.st_ino & 0xffff);
*/
}<file_sep>#define _XOPEN_SOURCE
#include <signal.h>
#include <setjmp.h>
#include <stdio.h>
#include "tlpi_hdr.h"
sigjmp_buf env;
void handler(int sig)
{
printf("SIGABORT is caugnt!\n");
siglongjmp(env, 1);
}
void handler_return(int sig)
{
printf("SIGABORT is caught! It will return.\n");
}
int main(void)
{
if (sigsetjmp(env, 1) == 0)
{
printf("sigsetjmp called\n");
if (signal(SIGABRT, handler) == SIG_ERR)
errExit("signal");
}
else
{
printf("Return from abort\n");
if (signal(SIGABRT, handler_return) == SIG_ERR)
errExit("signal");
}
abort();
printf("Call abort!\n");
}<file_sep>#define _BSD_SOURCE
#include <stdlib.h>
#include "tlpi_hdr.h"
static void atexit_func1(void)
{
printf("atexit function 1 called\n");
}
static void atexit_func2(void)
{
printf("atexit function 2 called\n");
}
static void onexit_func(int exit_status, void *arg)
{
printf("on_exit function called: status=%d, arg = %ld\n",
exit_status, (long)arg);
}
int main(int argc, char *argv[])
{
if (on_exit(onexit_func, (void *)10) != 0)
{
fatal("on_exit 1");
}
if (atexit(atexit_func1) != 0)
{
fatal("atexit 1");
}
if (atexit(atexit_func2) != 0)
{
fatal("atexit 2");
}
if (on_exit(onexit_func, (void *)20) != 0)
{
fatal("on_exit 2");
}
exit(2);
}<file_sep>#define _BSD_SOURCE
#define _XOPEN_SOURCE
#include <sys/capability.h>
#include <unistd.h>
#include <limits.h>
#include <pwd.h>
#include <shadow.h>
#include "tlpi_hdr.h"
static int modify_cap(int capability, int setting)
{
cap_t caps;
cap_value_t cap_list[1];
caps = cap_get_proc();
if (cap == NULL)
return -1;
cap_list[0] = capability;
if (cap_set_flag(caps, CAP_EFFECTIVE, 1, cap_list, setting) == -1)
{
cap_free(caps);
return -1;
}
if (cap_set_proc(caps) == -1)
{
cap_free(caps);
return -1;
}
if (cap_free(caps) == -1)
return -1;
return 0;
}
static int raise_cap(int capability)
{
return modify_cap(capability, CAP_SET);
}
static int drop_all_caps(void)
{
cap_t empty;
int s;
empty = cap_init();
if (empty == NULL)
return -1;
set = cap_set_proc(empty);
if (cap_free(empty) == -1)
return -1;
return s;
}
int main(int argc, char *argv[])
{
char *user_name, *password, *encrypted, *p;
struct passwd *pwd;
struct spwd *spwd;
bool auth_ok;
size_t len;
long lnmax;
lnmax = sysconf(_SC_LOGIN_NAME_MAX);
if (lnmax == -1)
lnmax = 256;
user_name = malloc(lnmax);
if (user_name == NULL)
errExit("malloc");
printf("Username: ");
fflush(stdout);
if (fgets(user_name, lnmax, stdin) == NULL)
exit(EXIT_FAILURE);
len = strlen(user_name);
if (user_name[len-1] == '\n');
user_name[len-1] = '\0';
pwd = getpwnam(user_name);
if (pwd == NULL)
fatal("couldn't get password record");
if (raise_cap(CAP_DAC_READ_SEARCH) == -1)
fatal("raise_cap() falied");
spwd = getspnam(user_name);
if (spwd == NULL && errno == EACCES)
fatal("no permission to read shadow password file");
if (drop_all_caps() == -1)
fatal("drop_all_caps() failed");
if (spwd != NULL)
pwd->pw_passwd = spwd->sp_pwdp;
password = getpass("Password: ");
encrypted = crypt(password, pwd->pw_passwd);
for (p = pwssword; *p != '\0'; )
*p++ = '\0';
if (encrypted == NULL)
errExit("crypt");
auth_ok = strcmp(encrypted, pwd->pw_passwd) == 0;
if (!auth_ok)
{
printf("Incorrect password\n");
exit(EXIT_FAILURE);
}
printf("Successfully authenticated: UID=%ld\n", (long)pwd->pw_uid);
exit(EXIT_SUCCESS);
}<file_sep>#define _XOPEN_SOURCE
#include <unistd.h>
#include <signal.h>
#include <stdlib.h>
#include "tlpi_hdr.h"
static volatile sig_atomic_t has_sig = 0;
void handler(int sig)
{
has_sig = 1;
}
int main(void)
{
struct sigaction sa;
sigset_t mask;
sigemptyset(&mask);
sigaddset(&mask, SIGCHLD);
sigprocmask(SIG_UNBLOCK, &mask, NULL);
sa.sa_flags = 0;
sigemptyset(&sa.sa_mask);
sa.sa_handler = handler;
if (sigaction(SIGCHLD, &sa, NULL) == -1)
errExit("sigaction");
system("ls -ahl");
if (has_sig == 1)
{
printf("SIGCHLD has been caught.\n");
}
}
<file_sep>/**********************************************************************
* 用read() write()函数来模拟readv()和writev().
* myreadv的实现是是循环iovcnt次,每次调用read。在语义上不同于单次的readv调用,
* 因为发起多次write无法保证原子性。而且多次write()开销比一次writev()大。
* mywritev的实现是利用malloc函数申请一块内存作为buffer,然后将iov中的数据都copy
* 到buffer,最后从调用write。虽然从语义上等同于单词writev调用,但需要在用户控件内
* 分配缓冲区,复制数据,很不方便(效率也低)。
**********************************************************************/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
struct iovec {
void *iov_base; /* Starting address */
size_t iov_len; /* Number of bytes to transfer */
};
ssize_t myreadv(int fd, const struct iovec* iov, int iovcnt);
ssize_t mywritev(int fd, const struct iovec* iov, int iovcnt);
int main(int argc, char **argv)
{
int fd = open("t.txt", O_RDWR | O_CREAT | O_TRUNC, S_IWUSR | S_IRUSR);
if (fd == -1)
{
exit(EXIT_FAILURE);
}
struct iovec text[2];
char lorem[] = "lorem\n";
text[0].iov_base = lorem;
text[0].iov_len = 6;
char ipsum[] = "IPSUM\n";
text[1].iov_base = ipsum;
text[1].iov_len = 6;
ssize_t bytesWritten = mywritev(fd, text, 2);
if (bytesWritten == -1)
exit(EXIT_FAILURE);
int fd1 = open("h.txt", O_RDWR | O_CREAT, S_IWUSR | S_IRUSR);
ssize_t bytesRead = myreadv(fd1, text, 2);
if (bytesRead == -1)
exit(EXIT_FAILURE);
bytesWritten = mywritev(1, text, 2);
if (bytesWritten == -1)
exit(EXIT_FAILURE);
return 0;
}
ssize_t myreadv(int fd, const struct iovec* iov, int iovcnt)
{
ssize_t tot;
for (int i = 0; i < iovcnt; ++i)
{
ssize_t size = read(fd, iov[i].iov_base, iov[i].iov_len);
if (size == -1)
exit(EXIT_FAILURE);
if (size == 0)
break;
tot += size;
}
return tot;
}
ssize_t mywritev(int fd, const struct iovec* iov, int iovcnt)
{
size_t size = 0;
for (int i = 0; i < iovcnt; ++i)
{
size += iov[i].iov_len;
}
char *buf = (char *)malloc(size);
ssize_t index = 0;
for (int i = 0; i < iovcnt; ++i)
{
memcpy(&buf[index], iov[i].iov_base, iov[i].iov_len);
index += iov[i].iov_len;
}
ssize_t bytesWritten = write(fd, buf, index);
free(buf);
return bytesWritten;
}<file_sep>#include <pwd.h>
#include <grp.h>
#include <stdlib.h>
#include "ugid_functions.h"
#include "tlpi_hdr.h"
int main(int argc, char *argv[])
{
uid_t uid;
gid_t gid;
int j;
Boolean err_fnd;
if (argc < 3 || strcmp(argv[1], "--help") == 0)
{
usageErr("%s owner group [file...]\n"
" owner or group can be '-',"
"meaning leave unchanged\n", argv[1]);
}
if (strcmp(argv[1], "-") == 0)
uid = -1;
else
{
uid = user_id_from_name(argv[1]);
if (uid == -1)
fatal("No such user (%s)", argv[1]);
}
if (strcmp(argv[2], "-") == 0)
gid = -1;
else
{
gid = group_id_from_name(argv[2]);
if (gid == -1)
fatal("No group user (%s)", argv[1]);
}
err_fnd = FALSE;
for (j = 3; j < argc; ++j)
{
if (chown(argv[j], uid, gid) == -1)
{
errMsg("chown: %s", argv[j]);
err_fnd = TRUE;
}
}
exit(err_fnd ? EXIT_FAILURE : EXIT_SUCCESS);
}<file_sep>#include <pthread.h>
#include "tlpi_hdr.h"
#ifndef PATH_MAX
#define PATH_MAX 4096
#endif
static pthread_once_t dirname_once = PTHREAD_ONCE_INIT;
static pthread_once_t basename_once = PTHREAD_ONCE_INIT;
static pthread_key_t dirname_key;
static pthread_key_t basename_key;
static void destory(void *buf)
{
free(buf);
}
static void dirname_create_key(void)
{
int s;
s = pthread_key_create(&dirname_key, destory);
if (s != 0)
errExitEN(s, "pthread_key_create");
}
char *dirname(char *path)
{
int s;
char *buf;
char *slash;
s = pthread_once(&dirname_once, dirname_create_key);
buf = pthread_getspecific(dirname_key);
if (buf == NULL)
{
buf = malloc(PATH_MAX);
if (buf == NULL)
errExit("malloc");
s = pthread_setspecific(dirname_key, buf);
if (s != 0)
errExitEN(s, "pthread_setspecific");
}
slash = NULL;
for (char *cur = path; *cur != '\0'; ++cur)
{
if (*cur == '/')
slash = cur;
}
if (slash)
{
size_t len = slash-path;
len = (PATH_MAX-1 > len) ? len : PATH_MAX - 1;
strncpy(buf, path, len);
buf[len] = '\0';
}
else
{
buf[0] = '.';
buf[1] = '\0';
}
return buf;
}
static void basename_create_key(void)
{
int s;
s = pthread_key_create(&basename_key, destory);
if (s != 0)
errExitEN(s, "pthread_key_create");
}
char *basename(char *path)
{
int s;
char *buf;
s = pthread_once(&basename_once, basename_create_key);
if (s != 0)
errExitEN(s, "pthread_once");
buf = pthread_getspecific(basename_key);
if (buf == NULL)
{
buf = malloc(PATH_MAX);
if (buf == NULL)
errExit("malloc");
s = pthread_setspecific(basename_key, buf);
if (s != 0)
errExitEN(s, "pthread_setspecific");
}
char *cur, *slash;
slash = NULL;
for (cur = path; *cur != '\0'; ++cur)
{
if (*cur == '/')
slash = cur;
}
if (slash)
{
slash++;
size_t len = cur-slash;
len = (PATH_MAX-1 > len) ? len : PATH_MAX-1;
strncpy(buf, slash, len);
buf[len] = '\0';
}
else
{
size_t len = cur - path;
len = (PATH_MAX-1 > len) ? len : PATH_MAX-1;
strncpy(buf, path, len);
buf[len] = '\0';
}
return buf;
}
static pthread_mutex_t mtx = PTHREAD_MUTEX_INITIALIZER;
void *thread_func(void *arg)
{
int s;
s = pthread_mutex_lock(&mtx);
if (s != 0)
errExitEN(s, "pthread_mutex_lock");
printf("%s\n", (char *)arg);
printf("%s\n", dirname((char *)arg));
printf("%s\n", basename((char *)arg));
s = pthread_mutex_unlock(&mtx);
if (s != 0)
errExitEN(s, "pthread_mutex_unlock");
}
int main(int argc, char *argv[])
{
pthread_t t1, t2;
int s;
s = pthread_create(&t1, NULL, thread_func, "/home/cyyzero/workspece/std");
if (s != 0)
{
errExitEN(s, "pthread_create");
}
s = pthread_create(&t2, NULL, thread_func, "/fuckasd/adfas/asdfa/asf/adf");
if (s != 0)
{
errExitEN(s, "pthread_create");
}
pthread_join(t1, NULL);
pthread_join(t2, NULL);
}<file_sep>#define _GNU_SOURCE
#include <signal.h>
#include <sys/time.h>
#include <time.h>
#include <stdbool.h>
#include "tlpi_hdr.h"
static volatile sig_atomic_t got_alarm = 0;
static void display_times(const char *msg, bool inlcude_timer)
{
struct itimerval itv;
static struct timeval start;
struct timeval curr;
static int call_num = 0;
if (call_num == 0)
{
if (gettimeofday(&start, NULL) == -1)
errExit("gettimeofday");
}
if (call_num % 20 == 0)
{
printf(" Elapsed Value Interval\n");
}
if (gettimeofday(&curr, NULL) == -1)
errExit("gettimeofday");
printf("%-7s %6.2f", msg, curr.tv_sec - start.tv_sec +
(curr.tv_usec - start.tv_usec) / 1000000.0);
if (inlcude_timer)
{
if (getitimer(ITIMER_REAL, &itv) == -1)
errExit("getitimer");
printf(" %6.2f %6.2f",
itv.it_value.tv_sec + itv.it_value.tv_usec/1000000.0,
itv.it_interval.tv_sec + itv.it_interval.tv_usec/1000000.0);
}
printf("\n");
}
static void sigalrm_handler(int sig)
{
got_alarm = 1;
}
int main(int argc, char *argv[])
{
struct itimerval itv;
clock_t prev_clock;
int max_sigs;
int sig_cnt;
struct sigaction sa;
sig_cnt = 0;
sigemptyset(&sa.sa_mask);
sa.sa_flags = 0;
sa.sa_handler = sigalrm_handler;
if (sigaction(SIGALRM, &sa, NULL) == -1)
errExit("sigaction");
max_sigs = (itv.it_interval.tv_sec == 0 && itv.it_interval.tv_usec == 0) ?
1 : 3;
display_times("START:", false);
itv.it_value.tv_sec = (argc > 1) ? getLong(argv[1], 0, "secs") : 2;
itv.it_value.tv_usec = (argc > 2) ? getLong(argv[2], 0, "usecs"): 0;
itv.it_interval.tv_sec = (argc > 3) ? getLong(argv[3], 0, "int-secs") : 0;
itv.it_interval.tv_usec = (argc > 4) ? getLong(argv[4], 0, "int-usecs"): 0;
if (setitimer(ITIMER_REAL, &itv, 0) == -1)
errExit("setitimer");
prev_clock = clock();
sig_cnt = 0;
for (;;)
{
while (((clock() - prev_clock) * 10 / CLOCKS_PER_SEC) < 5)
{
if (got_alarm)
{
got_alarm = 0;
display_times("ALARM:", true);
sig_cnt++;
if (sig_cnt > max_sigs)
{
printf("That's all folks\n");
exit(EXIT_SUCCESS);
}
}
}
prev_clock = clock();
display_times("Main:", true);
}
}<file_sep>/*********************************
使用O_APPEND标志打开一个已存在的文件,
且将文件偏移量置于文件起始处。再写入数据,
数据会接在原文件后。这是因为 对于lseek来
说,它直接修改文件描述符表项中的当前文件偏
移量,并返回当前的文件偏移量,而对于O_APPEND
标志,则只是将其设置到了文件表项的文件状态
标志中,此时当前文件偏移量并未修改,仍然为
0,只有当用户企图写入文件时,才将文件当前
偏移量置为文件长度。
*********************************/
#include <sys/types.h>
#include <sys/stat.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <fcntl.h>
#include <unistd.h>
int main(int argc, char **argv)
{
int fd;
off_t off;
ssize_t numWritten;
if (argc != 2 || strcmp(argv[1], "--help") == 0)
{
exit(EXIT_FAILURE);
}
fd = open(argv[1], O_WRONLY | O_APPEND);
if (fd == -1)
{
exit(EXIT_FAILURE);
}
off = lseek(fd, 0, SEEK_SET);
if (off == -1)
exit(EXIT_FAILURE);
numWritten = write(fd, "f**k\n", 5);
if (numWritten == -1)
exit(EXIT_FAILURE);
close(fd);
return 0;
}
<file_sep>#define _XOPEN_SOURCE
#include <signal.h>
typedef void (*sighandler_t)(int);
sighandler_t signal(int sig, sighandler_t handler)
{
struct sigaction new_disp, prev_disp;
new_disp.sa_handler = handler;
sigemptyset(&new_disp.sa_mask);
#ifdef OLD_SIGNAL
new_disp.sa_flags = SA_RESETHAND | SA_NODEFER;
#else
new_disp.sa_flags = SA_RESTART;
#endif
if (sigaction(sig, &new_disp, &prev_disp) == -1)
return SIG_ERR;
else
return prev_disp.sa_handler;
}<file_sep>#include <unistd.h>
#include <sys/wait.h>
#include <sys/types.h>
int system(char *command)
{
int status;
pid_t child_pid;
switch (child_pid = fork())
{
case -1:
return -1;
case 0:
execl("/bin/sh", "sh", "-c", command, NULL);
_exit(127);
default:
if (waitpid(child_pid, &status, 0) == -1)
return -1;
else
return status;
}
}<file_sep>#include <sys/types.h>
#include <sys/msg.h>
#include "tlpi_hdr.h"
int main(int argc, char *argv[])
{
struct msqid_ds ds;
int msqid;
msqid = getInt(argv[1], 0, "msqid");
if (msgctl(msqid, IPC_STAT, &ds) == -1)
errExit("msgctl");
ds.msg_qbytes = getInt(argv[2], 0, "max-bytes");
if (msgctl(msqid, IPC_SET, &ds) == -1)
errExit("msgctl");
exit(EXIT_SUCCESS);
}<file_sep>#define _GNU_SOURCE
#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
void handler(int sig)
{
printf("SIGCONT is caught");
exit(EXIT_SUCCESS);
}
int main(void)
{
int flag;
struct sigaction sa;
sigset_t mask;
sigemptyset(&sa.sa_mask);
sa.sa_handler = handler;
sa.sa_flags = 0;
sigaction(SIGCONT, &sa, NULL);
sigemptyset(&mask);
sigaddset(&mask, SIGCONT);
sigprocmask(SIG_BLOCK, &mask, NULL);
for (;;)
{
scanf("%d", &flag);
if (flag == 1)
{
sigprocmask(SIG_UNBLOCK, &mask, NULL);
}
}
}<file_sep>#define _XOPEN_SOURCE
#include <signal.h>
#include <libgen.h>
#include "tlpi_hdr.h"
#define CMD_SIZE 200
void handler(int sig)
{
}
int main(int argc, char *argv[])
{
char cmd[CMD_SIZE];
pid_t child_pid;
sigset_t mask;
struct sigaction sa;
sigemptyset(&sa.sa_mask);
sa.sa_flags = 0;
sa.sa_handler = handler;
if (sigaction(SIGCHLD, &sa, NULL))
errExit("sigaction");
sigemptyset(&mask);
sigaddset(&mask, SIGUSR1);
sigprocmask(SIG_SETMASK, &mask, NULL);
sigfillset(&mask);
sigdelset(&mask, SIGCHLD);
setbuf(stdout, NULL);
printf("Parent PID=%ld\n", (long)getpid());
switch (child_pid = fork())
{
case -1:
errExit("fork");
case 0:
//printf("Dfas\n");
sleep(1);
printf("Child (PID=%ld) exiting\n", (long)getpid());
_exit(EXIT_SUCCESS);
default:
//sleep(3);
sigsuspend(&mask);
snprintf(cmd, CMD_SIZE, "ps | grep %s", basename(argv[0]));
cmd[CMD_SIZE-1] = '\0';
system(cmd);
if (kill(child_pid, SIGKILL) == -1)
errMsg("kill");
//sleep(3);
printf("After sending SIGKILL to zombie (PID=%ld):\n", (long)child_pid);
system(cmd);
exit(EXIT_SUCCESS);
}
}<file_sep>#include <sys/time.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <sys/resource.h>
#include <stdio.h>
#include "tlpi_hdr.h"
int main(int argc, char *argv[])
{
int status;
struct rusage sr;
switch (fork())
{
case -1:
errExit("fork");
case 0:
for (int i = 0; i < 1000000000; ++i)
continue;
_exit(EXIT_SUCCESS);
default:
if (getrusage(RUSAGE_CHILDREN, &sr) == -1)
errExit("getrusage");
printf("%ld\t%ld\n", sr.ru_utime.tv_sec, sr.ru_utime.tv_usec);
if (wait(&status) == -1)
errExit("wait");
//printf("%d\n", status);
if (getrusage(RUSAGE_CHILDREN, &sr) == -1)
errExit("getrusage");
printf("%ld\t%ld\n", sr.ru_utime.tv_sec, sr.ru_utime.tv_usec);
}
}<file_sep>如果使用了 `shell` 管道,那么创建的进程会放在一个进程组,进程组的其他进程可能会收到发送 `SIGUSR1` 信号,然后调用处理函数。
解决方案是先使用 `setpgid()` 确保子进程会被放置在自己的新组中(第一个子进程的进程 `ID` 可以用作组的进程 `ID`),然后向改进程组发送信号。<file_sep>#include <fcntl.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <stdio.h>
#include "tlpi_hdr.h"
#define MYFILE "myfile"
#define MYDIR "mydir"
#define FILE_PERMS (S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP)
#define DIR_PERMS (S_IRWXU | S_IRWXG | S_IRWXO)
#define UMASK_SETTING (S_IWGRP | S_IXGRP | S_IWOTH | S_IXOTH)
#define FP_SPECIAL 1
#define STR_SIZE sizeof("rwxrwxrwx")
char *file_perm_str(mode_t perm, int flags)
{
static char str[STR_SIZE];
snprintf(str, STR_SIZE, "%c%c%c%c%c%c%c%c%c",
(perm & S_IRUSR) ? 'r' : '-',
(perm & S_IWUSR) ? 'w' : '-',
(perm & S_IXUSR) ? (((perm & S_ISUID) && (flags & FP_SPECIAL)) ? 's' : 'x') :
(((perm & S_ISUID) && (flags & FP_SPECIAL)) ? 'S' : '-'),
(perm & S_IRGRP) ? 'r' : '-',
(perm & S_IWGRP) ? 'w' : '-',
(perm & S_IXGRP) ? (((perm & S_ISGID) && (flags & FP_SPECIAL)) ? 's' : 'x') :
(((perm & S_ISGID) && (flags & FP_SPECIAL)) ? 'S' : '-'),
(perm & S_IROTH) ? 'r' : '-',
(perm & S_IWOTH) ? 'w' : '-',
(perm & S_IXOTH) ? (((perm & S_ISVTX) && (flags & FP_SPECIAL)) ? 't' : 'x') :
(((perm & S_ISVTX) && (flags & FP_SPECIAL)) ? 'T' : '-'));
return str;
}
int main(int argc, char *argv[])
{
int fd;
struct stat sb;
mode_t u;
umask(UMASK_SETTING);
fd = open(MYFILE, O_CREAT | O_EXCL, FILE_PERMS);
if (fd == -1)
errExit("open");
if (mkdir(MYDIR, DIR_PERMS) == -1)
errExit("mkdir-%s", MYDIR);
u = umask(0);
if (stat(MYFILE, &sb) == -1)
errExit("stat-%s", MYFILE);
printf("Requested file perms: %s\n", file_perm_str(FILE_PERMS, 0));
printf("process umask: %s\n", file_perm_str(u, 0));
printf("Actual file perms: %s\n", file_perm_str(sb.st_mode, 0));
if (stat(MYDIR, &sb) == -1)
errExit("stat-%s", MYDIR);
printf("Requested dir. perms: %s\n", file_perm_str(DIR_PERMS, 0));
printf("Process umask: %s\n", file_perm_str(u, 0));
printf("Actual dir. perms: %s\n", file_perm_str(sb.st_mode, 0));
if (unlink(MYFILE) == -1)
errMsg("unlink-%s", MYFILE);
if (rmdir(MYDIR) == -1)
errMsg("rmdir-%s", MYDIR);
exit(EXIT_SUCCESS);
}
<file_sep>> 27-5 When we run the following program, we find it produces no output. Why is this?
```C
#include "tlpi_hdr.h"
int
main(int argc, char *argv[])
{
printf("Hello world");
execlp("sleep", "sleep", "0", (char *) NULL);
}
```
---
因为`printf()`默认用的行缓冲,还没把字符串从用户空间的缓冲复制到内核空间,就`execev`了`sleep`,进程的数据段,堆,栈都被替换了。<file_sep>#include <pthread.h>
#include "tlpi_hdr.h"
struct thread_info
{
int thread_id;
int loops;
};
static volatile int glob = 0;
static void *thread_func(void *arg)
{
struct thread_info *p = (struct thread_info *)arg;
int loc, j;
for (j = 0; j < p->loops; ++j)
{
loc = glob;
loc++;
glob = loc;
printf("Pthread id = %d; glob = %d\n", p->thread_id, glob);
}
return NULL;
}
int main(int argc, char *argv[])
{
struct thread_info st1, st2;
pthread_t t1, t2;
int s;
st1.thread_id = 1;
st2.thread_id = 2;
st1.loops = st2.loops = (argc > 1) ? getInt(argv[1], GN_GT_0, "num-loops") : 10000000;
s = pthread_create(&t1, NULL, thread_func, &st1);
if (s != 0)
errExitEN(s, "pthread_create");
s = pthread_create(&t2, NULL, thread_func, &st2);
if (s != 0)
errExitEN(s, "pthread_create");
s = pthread_join(t1, NULL);
if (s != 0)
errExitEN(s, "pthread_join");
s = pthread_join(t2, NULL);
if (s != 0)
errExitEN(s, "pthread_join");
printf("glob=%d\n", glob);
exit(EXIT_SUCCESS);
}<file_sep>/**************************
省略了前面的代码,已知一个变量fd,
保存了文件描述符,要判断访问模式
***************************/
int flags, accessMode;
flags = fcntl(fd, F_GETFL);
if (flsgs == -1)
exit(EXIT_FAILURE);
accessMode = flags & O_ACCMODE;
if (accessMode == O_WRONLY || accessMode == O_RDWR)
printf("file is writable\n");
| 966a021068c9186d25e9a02417fa4be6203b2c1d | [
"Markdown",
"C"
] | 104 | C | demonkit/tlpi | be4d54ff5bdee0d7d79f36725e09b9d7ae7dc263 | fd497e0797ee73b5deefa7a92d5aa71c83143f1f |
refs/heads/master | <repo_name>elvece/chessboard<file_sep>/readme.md
##Chessboard
A compilation of alternative solutions to the Eloquent JavaScript exercise that challenges you to print a "chessboard" style grid to the console.
<file_sep>/chessboard.js
//class solution
for (var i=0; i<8; i++) {
var line = "";
for (var j=0; j<8; j++) {
var total = i + j;
if (total % 2 === 0){
line += " ";
} else {
line += "#";
}
}
console.log (line);
}
//alt solution - not as easy to manipulate
var odd=" # # # #\n";
var even= "# # # #\n";
var result= "";
for (var i=0; i<8; i++) {
if (i%2===0) {
result += odd;
} else {
result += even;
}
}
console.log (result)
//crystal's solution
var userInput = prompt("How wide do you want your chessboard to be?")
//converts userInput from string to number
var userInput = Number(userInput)
//.join repeats the string by the number input by the user
var string1 = Array(userInput + 1).join(" #")
var string2 = Array(userInput + 1).join("# ")
//the ? and : is called ternary operator ternary operator it takes in three arguments---- condition ? exprr1 : expr2 ----short cut for if statement
var chessboard = function (i) {
//we have 2 types of lines... id string1 and string2... now in each iteration of the loop we need to know which of the string to be used... so the simple logic here is if the value of i is a multiple of 2(ie, 0, 2, 4 etc) use string1 else string2
console.log(i % 2 == 0 ? string1 : string2);
};
for (var i = 0; i < userInput; i++) {
chessboard(i);
}
| 6f336632b4b463659da05b0d5fcdf372fc7cf121 | [
"Markdown",
"JavaScript"
] | 2 | Markdown | elvece/chessboard | b15256f7d61556dc9102c65e6a283b281d5ebb26 | 6c64daf72c60453a96ed5e19291dd3bc8eaaa44a |
refs/heads/master | <repo_name>arvalon/GAC<file_sep>/app/src/main/java/com/example/student/gac/Foo.kt
package com.example.student.gac
import android.util.Log
class Foo {
fun helloWorld(){
Log.d("LOGTAG", "HelloWorld")
}
}<file_sep>/README.md
[Android Architecture Components](https://developer.android.com/topic/libraries/architecture)
<file_sep>/app/src/main/java/com/example/student/gac/MyApplication.java
package com.example.student.gac;
import android.app.Application;
import androidx.room.Room;
public class MyApplication extends Application {
public static MyApplication instance;
private static MyDatabase database;
public static MyDatabase getDatabase() {
if (database == null) {
database = Room.databaseBuilder(instance, MyDatabase.class, "database").allowMainThreadQueries().build();
}
return database;
}
public static MyApplication getInstance() {
return instance;
}
@Override
public void onCreate() {
super.onCreate();
instance = this;
}
}
<file_sep>/app/src/main/java/com/example/student/gac/MyViewModel.java
package com.example.student.gac;
import androidx.lifecycle.LiveData;
import androidx.lifecycle.MutableLiveData;
import androidx.lifecycle.ViewModel;
import java.util.List;
public class MyViewModel extends ViewModel {
private MutableLiveData<String> text = new MutableLiveData<>();
public LiveData<String> getText()
{
return text;
}
public void changeText(String t)
{
text.postValue(t);
}
public LiveData<List<User>> getAll() {
UserDao dao = MyApplication.getDatabase().getUserDao();
return dao.getAll();
}
public int getUserCount(){
return MyApplication.getDatabase().getUserDao().getAll().getValue().size();
}
public void addUser(User user) {
UserDao dao = MyApplication.getDatabase().getUserDao();
new Thread(() -> dao.addUser(user)).start();
}
public User getUserByID(String inn){
return MyApplication.getDatabase().getUserDao().getUser(inn);
}
}
| 68a6809d2c3772a03c40c6d99c63448edcd0721f | [
"Markdown",
"Java",
"Kotlin"
] | 4 | Kotlin | arvalon/GAC | 443b9f5f162827a7f57154ec47c45fa6210357aa | f2e0c08b4bab32b65ceecef98443fc8b81f5d054 |
refs/heads/master | <file_sep>package by.realovka.jaxb;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import java.io.File;
import java.util.ArrayList;
public class Main {
public static void main(String[] args) {
Book book1=new Book(123, "Ангелы и демоны", 2005);
Book book2=new Book(124, "Код да Винчи", 2006);
Book book3=new Book(125, "Точка обмана", 2007);
ArrayList<Book> books=new ArrayList<>();
books.add(book1);
books.add(book2);
books.add(book3);
Books fewBooks = new Books(books);
try {
JAXBContext context = JAXBContext.newInstance(Books.class);
Marshaller marshaller = context.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT,true);
marshaller.marshal(fewBooks,new File("book.xml"));
} catch (JAXBException e) {
e.printStackTrace();
}
}
}
<file_sep>package by.realovka.jaxb;
import javax.xml.bind.annotation.XmlType;
@XmlType(propOrder = {"vendorCode", "name","yearOfPublishing"})
public class Book {
private int vendorCode;
private String name;
private int yearOfPublishing;
public Book(int vendorCode, String name, int yearOfPublishing) {
this.vendorCode = vendorCode;
this.name = name;
this.yearOfPublishing = yearOfPublishing;
}
public Book() {
}
public int getVendorCode() {
return vendorCode;
}
public void setVendorCode(int vendorCode) {
this.vendorCode = vendorCode;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getYearOfPublishing() {
return yearOfPublishing;
}
public void setYearOfPublishing(int yearOfPublishing) {
this.yearOfPublishing = yearOfPublishing;
}
@Override
public String toString() {
return "Book{" +
"vendorCode=" + vendorCode +
", name='" + name + '\'' +
", yearOfPublishing=" + yearOfPublishing +
'}';
}
}
<file_sep>package by.realovka.jaxb;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import java.util.ArrayList;
@XmlRootElement
public class Books {
@XmlElement
private ArrayList<Book> bookArrayList;
public Books(ArrayList<Book> bookArrayList) {
this.bookArrayList = bookArrayList;
}
public Books() {
}
}
| 878d76de9368225db546982c00d62d416dcf66b3 | [
"Java"
] | 3 | Java | Realovka/Lesson_15_task_1 | 814e585393464ffa46a67ee6c22b9f72a0816875 | 731d81f7ad668052c8e7ad392286cd8a3bfc18b7 |
refs/heads/main | <file_sep>#include <stdio.h>
#include <stdlib.h>
int main()
{
int m;
int array[3][3];
printf("Input values of array:\n");
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
scanf_s("%d", &array[i][j]);
}
}
printf("Original array:\n");
for (int i = 0; i < 3; i++) {
printf("\n");
for (int j = 0; j < 3; j++) {
printf("%d", array[i][j]);
}
}
for (int i = 0; i < 3; i++) {
for (int z = 0; z < 2; z++) {
for (int j = 1; j < 3; j++) {
if (array[i][z] < array[i][j]) {
m = array[i][z];
array[i][z] = array[i][j];
array[i][j] = m;
}
}
}
}
printf("\n");
printf("Sorted array:\n");
for (int i = 0; i < 3; i++) {
printf("\n");
for (int j = 0; j < 3; j++) {
printf("%d", array[i][j]);
}
}
return 0;
} | c99344f241fac0528b7010b3ca31f4b8e9cfe304 | [
"C++"
] | 1 | C++ | NastyaUsoltseva/labwoork5 | fef555bbe60ec2ebeacebdf97abb2cec3fa47b75 | d2f406ad6c650f9d260391c691e2135f9454f0dd |
refs/heads/master | <file_sep><?php
namespace App\Http\Controllers\Message;
use App\Http\Controllers\Controller;
use App\Models\Message;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Illuminate\Support\Facades\Auth;
use Inertia\Inertia;
use DB;
class MessageController extends Controller
{
/**
* Display a listing of the resource.
*
* @return Response
*/
public function index()
{
$count=DB::table('messages')->where('user_to',Auth::user()->id)->where('statut',1)->count();
$authuserid=Auth::user()->id;
$alluser1= DB::table('users')
->join('conversations','users.id','conversations.user_one')
->where('conversations.user_two',Auth::user()->id)->get();
$alluser2= DB::table('users')
->join('conversations','users.id','conversations.user_two')
->where('conversations.user_one',Auth::user()->id)->get();
$allconversations= array_merge( $alluser1->toArray(),$alluser2->toArray());
if(empty($allconversations[0]->id)) {
return redirect()->route('home');
}else{
$id=$allconversations[0]->id;
return Inertia::render('Message/Index', [
'allconversations' => $allconversations,
'id' => $id,
'authuserid' => $authuserid,
'count' => $count,
// 'messsender' => $messsend,
// 'messreceiver' => $messreceiver,
// 'userid' => $userid,
]);
}
}
/**
* Show the form for creating a new resource.
*
* @return Response
*/
public function create()
{
//
}
/**
* Store a newly created resource in storage.
*
* @param \Illuminate\Http\Request $request
* @return Response
*/
public function store(Request $request)
{
// Message::create([
// 'sender_id' => $request->sender_id,
// 'receiver_id' => $request->receiver_id,
// 'messages' => $request->messages,
// 'user_id' => Auth::user()->id,
// ]);
// return back();
}
/**
* Display the specified resource.
*
* @param Message $message
* @return RedirectResponse|Response|\Inertia\Response
*/
public function show(Request $request, $id)
{
DB::table('messages')->where('user_to',Auth::user()->id)->where('conversation_id',$id)->where('statut',1)->update(['statut' =>0]);
$authuserid=Auth::user()->id;
$alluser1= DB::table('users')
->join('conversations','users.id','conversations.user_one')
->where('conversations.user_two',Auth::user()->id) ->get();
$alluser2= DB::table('users')
->join('conversations','users.id','conversations.user_two')
->where('conversations.user_one',Auth::user()->id)->get();
$allconversations= array_merge( $alluser1->toArray(),$alluser2->toArray());
// $id=$allconversations[0]->id;
$getmessages= DB::table('messages')
->join('users','users.id','messages.user_from')
->where('messages.conversation_id',$id)
->orderBy('messages.id','asc')->get();
return Inertia::render('Message/Show', [
'allconversations' => $allconversations,
'getmessages' => $getmessages,
'id' => $id,
'authuserid' => $authuserid,
// 'messsender' => $messsend,
// 'messreceiver' => $messreceiver,
// 'userid' => $userid,
]);
// $messsend = Message::with('user')->where('sender_id', Auth::user()->id)->get();
// $messreceiver = Message::with('user')->where('receiver_id', Auth::user()->id)->where('statut', 1)->get();
// Message::where('sender_id', $id)->update(['isRead' => 1]);
// $userid = Auth::user()->id;
// $messages = Message::with('user')->where('statut', 1)->get();
// $users = Message::with('user')->where('user_id', '!=', Auth::user()->id)->get();
// return Inertia::render('Message/Show', [
// 'messages' => $messages,
// 'userid' => $userid,
// 'users' => $users,
// 'messsender' => $messsend,
// 'messreceiver' => $messreceiver,
// ]);
// return back();
}
/**
* Show the form for editing the specified resource.
*
* @param Message $message
* @return Response
*/
public function edit(Message $message)
{
//
}
/**
* Update the specified resource in storage.
*
* @param \Illuminate\Http\Request $request
* @param Message $message
* @return Response
*/
public function update(Request $request, Message $message)
{
//
}
/**
* Remove the specified resource from storage.
*
* @param Message $message
* @return Response
*/
public function updatestatut(Message $message, $id)
{
// Message::where('id', $id)->update(['statut' => 0]);
// return back();
}
public function destroy(Message $message, $id)
{
// Message::where('id', $id)->delete();
// return back();
}
public function contact(Request $request)
{
$message= $request->message;
$userid=Auth::user()->id;
$userto=$request->user_to;
$chekcon1=DB::table('conversations')->where('user_one',$userid)->where('user_two',$userto)->get();
$chekcon2=DB::table('conversations')->where('user_two',$userid)->where('user_one',$userto)->get();
$allconversation=array_merge( $chekcon1->toArray(),$chekcon2->toArray());
if(count($allconversation) != 0){
$oldconversation = $allconversation[0]->id;
$message=DB::table('messages')->insert([
'user_from' => Auth::user()->id,
'user_to' => $request->user_to,
'message' => $request->message,
'statut' =>1,
'conversation_id' =>$oldconversation
]);
return redirect()->route('home');
}else
{
//new conversation
$newconversation = DB::table('conversations')->insertGetId([
'user_one' => Auth::user()->id,
'user_two' => $userto,
'statut' => 1
]);
$message=DB::table('messages')->insert([
'user_from' => Auth::user()->id,
'user_to' => $request->user_to,
'message' => $request->message,
'statut' =>1,
'conversation_id' =>$newconversation
]);
return redirect()->route('home');
}
return redirect()->route('home');
}
public function sendmessage(Request $request){
$conversation_id = $request->conversation_id;
$message = $request->message;
$fetchuserto1 = DB::table('messages')->where('conversation_id',$conversation_id)->where('user_from','!=',Auth::user()->id)->get();
$fetchuserto2 = DB::table('messages')->where('conversation_id',$conversation_id)->where('user_to','!=',Auth::user()->id)->get();
if( empty($fetchuserto1[0]->user_from) ){
$userto =$fetchuserto2[0]->user_to ;
$sendmessage = DB::table('messages')->insert([
'user_from' => Auth::user()->id,
'user_to' => $userto,
'message' => $message,
'statut' =>1,
'conversation_id' =>$conversation_id,
]);
return redirect()->route('Messages.index');
}
elseif(empty($fetchuserto2[0]->user_to)){
$userto = $fetchuserto1[0]->user_from;
$sendmessage = DB::table('messages')->insert([
'user_from' => Auth::user()->id,
'user_to' => $userto,
'message' => $message,
'statut' =>1,
'conversation_id' =>$conversation_id,
]);
return redirect()->route('Messages.index');
}
}
}
| 439228b46469bc566a34bf2ef727b8af95830594 | [
"PHP"
] | 1 | PHP | adamsndeye/fessef | 59a2f7e705b4d8e4327b219cc8bf8fa5d4b869c9 | d7fea03822a2a8b6fe4897740bb867078ac5b997 |
refs/heads/master | <repo_name>simonambridge/dse-graph-demo<file_sep>/Vagrantfile
# -*- mode: ruby -*-
# vi: set ft=ruby :
Vagrant.configure(2) do |config|
config.vm.box = "centos/7"
config.vm.provider "virtualbox" do |vb|
vb.gui = false
# Customize the amount of memory on the VM:
vb.memory = "4096"
end
config.vm.define "testnode1" do |testnode1|
testnode1.vm.hostname = "node1"
testnode1.vm.network "private_network", ip: "192.168.56.211"
# Copy customer graph example to new VM
testnode1.vm.provision "file", source: "cust-examples.tar.gz", destination: "cust-examples.tar.gz"
# Install Java
testnode1.vm.provision "shell", path: "install-java.sh"
# Install and DSE and Studio, configure and start them both
testnode1.vm.provision "shell", path: "install-dse.sh"
end
end
<file_sep>/README.md
# DataStax Enterprise (DSE) Graph Demo
This demo uses Vagrant to create a VM, install DSE Graph and configure and start a Customer Graph.
## Setup
### Requirements
- VirtualBox
- Vagrant (to build the VM)
- A DataStax Accademy account
### Installation
Change the install-dse.sh script to include the email address and password you use for DataStax Accademy.
Run the command 'vagrant up'. This will create the VM, install Java and DSE, and configure and start the demo
## Running the demo
1. Open the URL http://192.168.56.211:9091/ in a browser. This will take you to the DataStax Studio home page.
2. Click on the CustomerNotbook notebook
3. When the CustomerNotebook appears, scroll down and click on the 'Run' button (top right) for each of the Gremlin code panels in turn. This will create the Customer Graph schema, load sample data and run various queries
<file_sep>/install-dse.sh
#!/bin/bash
DSA_EMAIL_ADDRESS=<Your DataStax Accademy email address>
DSA_PASSWORD=<<PASSWORD>>
# Escape '@' in email address with %40 URL encoded equivalent
ENCODED_DSA_EMAIL_ADDRESS=`echo "$DSA_EMAIL_ADDRESS" | sed 's/@/%40/'`
# Add the DataStax Yum repository
echo -e "[datastax]\nname=DataStax Repo for DataStax Enterprise\nbaseurl=https://$ENCODED_DSA_EMAIL_ADDRESS:$DSA_PASSWORD@rpm.<EMAIL>stax.com/enterprise\nenabled=1\ngpgcheck=1\n" > /etc/yum.repos.d/datastax.repo
# Import the DataStax Enterprise repository key
sudo rpm --import http://rpm.datastax.com/rpm/repo_key
# Install the DSE pacakge - latest DSE version and demoss
sudo yum -y install dse-full
sudo yum -y install dse-demos
# Enable Graph and Spark - disabled by default
sudo sed -i 's/GRAPH_ENABLED=0/GRAPH_ENABLED=1/' /etc/default/dse
sudo sed -i 's/SPARK_ENABLED=0/SPARK_ENABLED=1/' /etc/default/dse
# IP address of eth1
IP_ADDRESS=`hostname -I | cut -d ' ' -f 2`
# Update Cassandra configuration
sudo sed -i "s/localhost/$IP_ADDRESS/" /etc/dse/cassandra/cassandra.yaml
sudo sed -i "s/127\.0\.0\.1/$IP_ADDRESS/" /etc/dse/cassandra/cassandra.yaml
# If DataStax Enterprise is not already running (single node cluster only):
sudo service dse restart
sleep 10
# Verify that DataStax Enterprise is running:
nodetool status
# Get DSE Studio - as vagrant user
chown vagrant:vagrant cust-examples.tar.gz
sudo -u vagrant bash << EOF
curl -L --user $DSA_EMAIL_ADDRESS:$DSA_PASSWORD http://downloads.datastax.com/datastax-studio/datastax-studio.tar.gz | tar xz
sleep 5
# Create Customer Graph
sudo sed -i "s/localhost/$IP_ADDRESS/" /etc/dse/graph/gremlin-console/conf/remote.yaml
echo -e "system.graph('CustGraph').create()\n:quit" | dse gremlin-console
# Update DSE Studio configuration
sed -i "s/localhost/$IP_ADDRESS/" datastax-studio-*/conf/configuration.yaml
# Add Customer Graph example notebook
tar -zxvf cust-examples.tar.gz
rm cust-examples.tar.gz
# Start DSE Studio
nohup datastax-studio-*/bin/server.sh &
EOF
<file_sep>/install-java.sh
#!/bin/bash
VERSION=111
# Prepare for installation
sudo yum -y update
sudo yum -y install wget
# Get JDK RPM
wget --no-cookies --no-check-certificate --header "Cookie: oraclelicense=accept-securebackup-cookie" "http://download.oracle.com/otn-pub/java/jdk/8u$VERSION-b14/jdk-8u$VERSION-linux-x64.rpm"
sudo yum -y localinstall jdk-8u$VERSION-linux-x64.rpm
# Show Java is running
java -fullversion
# Clean up
rm jdk-8u$VERSION-linux-x64.rpm
| e156cc8e048a87614879f25cfa7daa1c9923d0d8 | [
"Markdown",
"Ruby",
"Shell"
] | 4 | Ruby | simonambridge/dse-graph-demo | 84fb04cd01ee9f0668c5fd67fde65c91fd1631d1 | 4eb94f8c11446b14e90547abcfd7641c7e5d68fd |
refs/heads/master | <file_sep>// https://tour.golang.org/flowcontrol/8
package main
import (
"fmt"
"math"
)
// TODO: remove second argument
func Sqrt(x float64, i int) float64 {
z := 1.0
// TODO: loop until close enough (< 0.00000000000001)
for n := 1; n < i; n++ {
z = z - (z*z-x)/(2*z)
}
return z
}
func PrintResults(x float64, i int) {
fmt.Println(Sqrt(x, i), math.Sqrt(x), Sqrt(x, i)-math.Sqrt(x))
}
func main() {
PrintResults(4001, 20)
}
<file_sep>// https://tour.golang.org/moretypes/18
package main
import "golang.org/x/tour/pic"
func Pic(dx, dy int) [][]uint8 {
var pic [][]uint8
for y := 0; y < dy; y++ {
var row []uint8
for x := 0; x < dx; x++ {
row = append(row, uint8(x*x+y*y+x*y))
}
pic = append(pic, row)
}
return pic
}
func main() {
pic.Show(Pic)
}
<file_sep>// https://tour.golang.org/concurrency/10
package main
import (
"fmt"
"sync"
)
type Fetcher interface {
// Fetch returns the body of URL and
// a slice of URLs found on that page.
Fetch(url string) (body string, urls []string, err error)
}
// Cache URLs already fetched
type UrlCache struct {
urls map[string]bool
mux sync.Mutex
}
// Crawl uses fetcher to recursively crawl
// pages starting with url, to a maximum of depth.
func Crawl(url string, depth int, fetcher Fetcher, cache UrlCache, results chan string) {
// Each crawl thread gets its own results channel,
// which is closed automatically upon return
defer close(results)
// Start working on URL cache
cache.mux.Lock()
// Don't fetch the same URL twice.
// Also respect the depth limit
if cache.urls[url] || depth <= 0 {
cache.mux.Unlock()
return
} else {
cache.urls[url] = true
}
// Done working on URL cache
cache.mux.Unlock()
// Fetch
body, urls, err := fetcher.Fetch(url)
if err != nil {
results <- fmt.Sprintf("%s", err)
return
}
// Send result to channel
results <- fmt.Sprintf("found: %s %q\n", url, body)
// Create channels for additional results and then crawl the URLs
result := make([]chan string, len(urls))
for i, u := range urls {
result[i] = make(chan string)
go Crawl(u, depth-1, fetcher, cache, result[i])
}
// Print out the additional results to original results channel
for i := range result {
for s := range result[i] {
results <- s
}
}
}
func main() {
// Create results channel and cache map
results := make(chan string)
cache := UrlCache{urls: make(map[string]bool)}
// Crawl
go Crawl("http://golang.org/", 4, fetcher, cache, results)
// Print results as they are returned from Go threads
for i := range results {
fmt.Print(i)
}
}
// fakeFetcher is Fetcher that returns canned results.
type fakeFetcher map[string]*fakeResult
type fakeResult struct {
body string
urls []string
}
func (f fakeFetcher) Fetch(url string) (string, []string, error) {
if res, ok := f[url]; ok {
return res.body, res.urls, nil
}
return "", nil, fmt.Errorf("not found: %s", url)
}
// fetcher is a populated fakeFetcher.
var fetcher = fakeFetcher{
"http://golang.org/": &fakeResult{
"The Go Programming Language",
[]string{
"http://golang.org/pkg/",
"http://golang.org/cmd/",
},
},
"http://golang.org/pkg/": &fakeResult{
"Packages",
[]string{
"http://golang.org/",
"http://golang.org/cmd/",
"http://golang.org/pkg/fmt/",
"http://golang.org/pkg/os/",
},
},
"http://golang.org/pkg/fmt/": &fakeResult{
"Package fmt",
[]string{
"http://golang.org/",
"http://golang.org/pkg/",
},
},
"http://golang.org/pkg/os/": &fakeResult{
"Package os",
[]string{
"http://golang.org/",
"http://golang.org/pkg/",
},
},
}
<file_sep># go-tour
My first dabbles in the Go language in the form of the Go Tour exercises.
<file_sep>// https://tour.golang.org/methods/22
package main
import (
"golang.org/x/tour/reader"
)
type MyReader struct{}
func (r MyReader) Read(b []byte) (int, error) {
n := len(b)
for i := 0; i < n; i++ {
b[i] = 'A'
}
return n, nil
}
func main() {
reader.Validate(MyReader{})
}
| b1d933c4fa56953d061dd6e2ed5723687c681bb0 | [
"Markdown",
"Go"
] | 5 | Go | leetdev/go-tour | 453d8130a8aaae3e05899a748b40d770bbe810c0 | 870650672b06466d7a54d0f2845b858b82417578 |
refs/heads/master | <repo_name>rahulyhg/allsamaj<file_sep>/lib/Tool/EventDetail.php
<?php
namespace xavoc\allsamaj;
/**
*
*/
class Tool_EventDetail extends \xepan\cms\View_Tool {
public $options=[];
function init(){
parent::init();
$event_id = $this->app->stickyGET('event_id');
$m = $this->add('xavoc/allsamaj/Model_Event');
if(!$event_id){
$this->add('View_Error')->set('Event details not presented here');
return;
}else{
$m->load($event_id);
}
$this->setModel($m);
}
function setModel($model){
$m = parent::setModel($model);
$this->template->trySetHtml('description',$model['content']);
return $m;
}
function defaultTemplate(){
return ['view/eventdetail'];
}
}<file_sep>/lib/Model/Country.php
<?php
namespace xavoc\allsamaj;
class Model_Country extends \xepan\base\Model_Table {
public $table= "allsamaj_country";
public $acl=false;
function init(){
parent::init();
$this->addField('name');
$this->hasMany('xavoc\allsamaj\State','country_id');
$this->is([
'name|to_trim|required',
]);
$this->add('dynamic_model\Controller_AutoCreator');
}
}<file_sep>/lib/Tool/SamajNews.php
<?php
namespace xavoc\allsamaj;
class Tool_SamajNews extends \xepan\cms\View_Tool {
public $options=[
'no_of_record'=>10,
'no_of_column'=>' ',
'detail_url_page'=>null
];
function init(){
parent::init();
$samaj_id = $this->app->stickyGET('samaj_id');
$this->news_id = $this->app->stickyGET('news_id');
$n = $this->add('xavoc\allsamaj\Model_News');
if($this->news_id){
$n->addCondition('id',$this->news_id);
$this->options['no_of_column'] = "12";
}
if($samaj_id){
$n->addCondition('samaj_id',$samaj_id);
}
$lister = $this->add('CompleteLister',null,null,['view/samajnews']);
$lister->addHook('formatRow',function($l){
if($this->options['no_of_column']){
$l->current_row_html['col'] = $this->options['no_of_column'];
}else{
$l->current_row_html['col'] = "";
}
if($this->options['detail_url_page']){
$l->current_row_html['detail_url'] = $this->app->url($this->options['detail_url_page'],['news_id'=>$l->model->id]);
}
if($this->news_id){
$l->current_row_html['btn_block'] = "";
}
$l->current_row_html['content'] = $l->model['content'];
$l->current_row_html['date'] = date('F d, Y',strtotime($l->model['date']));
});
$lister->setModel($n);
if($this->options['no_of_record']){
$paginator = $lister->add('Paginator',null,'paginator');
$paginator->setRowsPerPage($this->options['no_of_record']);
}
}
}<file_sep>/page/committeemember.php
<?php
namespace xavoc\allsamaj;
/**
*
*/
class page_committeemember extends \xepan\base\Page{
public $title = "Samaj Committees";
function init(){
parent::init();
$committee_id = $this->app->stickyGET('committee_id');
$committee_member = $this->add('xavoc\allsamaj\Model_CommitteeMember');
if($committee_id)
$committee_member->addCondition('committee_id',$committee_id);
$crud = $this->add('xepan\hr\CRUD',null,null,['view/grid/committee-member']);
$crud->setModel($committee_member);
}
}<file_sep>/lib/Model/FeedBack.php
<?php
namespace xavoc\allsamaj;
/**
*
*/
class Model_FeedBack extends \xepan\base\Model_Table{
public $table="allsamaj_feedback";
public $acl_type="Committee";
public $actions= [
'Active'=>['view','edit','delete','deactivate'],
'InActive'=>['view','edit','delete','activate'],
];
function init(){
parent::init();
$this->hasOne('xavoc\allsamaj\Samaj','samaj_id');
$this->hasOne('xavoc\allsamaj\Event','event_id');
$this->addField('created_at')->defaultValue($this->app->today);//->validate('required');
$this->addField('message')->type('text');//->validate('required');
$this->addField('status')->enum(['Active','InActive'])->defaultValue('Active');
$this->add('dynamic_model/Controller_AutoCreator');
}
}<file_sep>/lib/Model/State.php
<?php
namespace xavoc\allsamaj;
class Model_State extends \xepan\base\Model_Table {
public $table= "allsamaj_state";
public $acl=false;
function init(){
parent::init();
$this->hasOne('xavoc\allsamaj\Country','country_id');
$this->addField('name');
$this->hasMany('xavoc\allsamaj\City','state_id');
$this->is([
'name|to_trim|required',
'country_id|required',
]);
$this->add('dynamic_model\Controller_AutoCreator');
}
}<file_sep>/lib/Tool/CommitteeMember.php
<?php
namespace xavoc\allsamaj;
/**
*
*/
class Tool_CommitteeMember extends \xepan\cms\View_Tool {
public $options=[
'show_search_bar'=>true,
'no_of_committee_members'=>10,
'show_image'=>true,
];
function init(){
parent::init();
$samaj_id = $this->app->stickyGET('samaj_id');
$committee_id = $this->app->stickyGET('committee_id');
$m = $this->add('xavoc/allsamaj/Model_CommitteeMember');
if($samaj_id)
$m->addCondition('samaj_id',$samaj_id);
if($committee_id)
$m->addCondition('committee_id',$committee_id);
$grid = $this->add('CompleteLister',null,null,['view/committeemember']);
$grid->setModel($m);
}
// function defaultTemplate(){
// return ['view/committeemember'];
// }
}<file_sep>/page/news.php
<?php
namespace xavoc\allsamaj;
class page_news extends \xepan\base\Page{
public $title= "All Samaj News";
function init(){
parent::init();
$this->add('xepan\hr\CRUD',null,null,['view/grid/news'])->setModel('xavoc\allsamaj\News');
}
}<file_sep>/lib/Model/CommitteeMember.php
<?php
namespace xavoc\allsamaj;
/**
*
*/
class Model_CommitteeMember extends \xepan\base\Model_Table{
public $table = "allsamaj_committee_member";
public $acl=false;
function init() {
parent::init();
$this->hasOne('xavoc\allsamaj\Committee','committee_id');
$this->hasOne('xavoc\allsamaj\Member','member_id');
// $this->addField('name');
$this->addField('post');
// $this->addField('mail_id');
$this->addExpression('samaj_id')->set($this->refSQL('committee_id')->fieldQuery('samaj_id'));
$this->addExpression('samaj')->set($this->refSQL('committee_id')->fieldQuery('samaj'));
$this->addExpression('contact_no')->set($this->refSQL('member_id')->fieldQuery('contact_no'));
$this->addExpression('email')->set($this->refSQL('member_id')->fieldQuery('email'));
$this->addExpression('image')->set($this->refSQL('member_id')->fieldQuery('image'));
$this->add('dynamic_model/Controller_AutoCreator');
}
}<file_sep>/lib/Tool/Search.php
<?php
namespace xavoc\allsamaj;
/**
*
*/
class Tool_Search extends \xepan\cms\View_Tool{
public $options = [
'form_layout'=>'view/searchform',
'xavoc_allsamaj_search_result_page'=>"index",
'search-field-label'=>"Type Your Search String",
'search-form-btn'=>true,
// 'search-form-btn-label'=>'Search',
// 'search-button-position'=>"after",
// 'search-form-btn-icon'=>"glyphicon glyphicon-search"
];
function init(){
parent::init();
$this->addClass('xepan-commerce-search-tool');
$search_result_page=$this->options['xavoc_allsamaj_search_result_page'];
if(!$search_result_page){
$search_result_page="index";
}
$label = "";
if($this->options['search-field-label'] != "")
$label = $this->options['search-field-label'];
$f = $this->add('Form',null,null,['form/empty']);;
$f->setLayout($this->options['form_layout']);
$search_samaj = $this->add('xavoc\allsamaj\Model_Samaj',['title_field'=>'search_string']);
// $search_field = $f->addField('autocomplete\Basic','search');
$search_field = $f->addField('line','search',$label)->validate('required');//->setAttr('PlaceHolder',$this->options['search-input-placeholder']);
// $search_field->setModel($search_samaj);
// $form = $this->add('Form');
if($this->options['search-form-btn']){
$f->addSubmit(' ')->addClass(' btn btn-default fa fa-search');
if($this->options['search-button-position'] === "before")
$submit_button = $search_field->beforeField()->add('Button');
else
$submit_button = $search_field->afterField()->add('Button');
$submit_button->setIcon('fa '.$this->options['search-form-btn-icon']);
$submit_button->set($this->options['search-form-btn-label']);
$submit_button->js('click',$f->js()->submit());
// $form->addSubmit($this->options['search-form-btn-label'] !=""?$this->options['search-form-btn-label']:"Search");
}
if($f->isSubmitted()){
$f->api->redirect(
$this->api->url(
null,
array('page'=>$search_result_page,'search'=>$f['search'])));
}
}
}<file_sep>/lib/Model/City.php
<?php
namespace xavoc\allsamaj;
class Model_City extends \xepan\base\Model_Table {
public $table= "allsamaj_city";
public $acl=false;
function init(){
parent::init();
$this->hasOne('xavoc\allsamaj\State','state_id');
$this->addField('name');
$this->hasMany('xavoc\allsamaj\Samaj','city_id');
$this->is([
'name|to_trim|required',
'state_id|required',
]);
$this->add('dynamic_model\Controller_AutoCreator');
}
}<file_sep>/lib/Tool/Committee.php
<?php
namespace xavoc\allsamaj;
/**
*
*/
class Tool_Committee extends \xepan\cms\View_Tool{
public $options=[
'show_image'=>'',
'detail_url'=>'',
'no_of_record'=>10,
];
function init(){
parent::init();
$samaj_id = $this->app->stickyGET('samaj_id');
$m = $this->add('xavoc\allsamaj\Model_Committee');
if($samaj_id)
$m->addCondition('samaj_id',$samaj_id);
$l = $this->add('CompleteLister',null,null,['view/committee']);
$l->addHook('formatRow',function($l){
if($this->options['detail_url']){
$l->current_row_html['detail_url'] = $this->app->url($this->options['detail_url_page'],['committee_id'=>$l->model->id]);
}
});
$l->setModel($m);
if($this->options['no_of_record']){
$paginator = $l->add('Paginator',null,'paginator');
$paginator->setRowsPerPage($this->options['no_of_record']);
}
}
// function defaultTemplate(){
// return ['view/committee'];
// }
}<file_sep>/page/samaj.php
<?php
namespace xavoc\allsamaj;
class page_samaj extends \xepan\base\Page{
public $title= "All Samaj Listing";
function init(){
parent::init();
$this->add('xepan\hr\CRUD',null,null,['view/grid/samajlist'])->setModel('xavoc\allsamaj\Samaj');
}
}<file_sep>/lib/Model/News.php
<?php
namespace xavoc\allsamaj;
class Model_News extends \xepan\base\Model_Table {
public $table= "allsamaj_news";
public $acl=false;
function init(){
parent::init();
$this->hasOne('xavoc\allsamaj\Samaj','samaj_id');
$this->hasOne('xavoc\allsamaj\ContentCategory','category_id');
$this->addField('name')->caption('Title');
$this->addField('content')->type('text')->display(['form'=>'xepan\base\RichText']);
$this->addField('date')->type('date');
$this->add('xepan/filestore/Field_Image','image_id');
$this->is([
'name|to_trim|required',
'samaj_id|required',
'category_id|required',
'content|required',
'date|required',
]);
$this->add('dynamic_model\Controller_AutoCreator');
}
}<file_sep>/lib/Model/Event.php
<?php
namespace xavoc\allsamaj;
class Model_Event extends \xepan\base\Model_Table {
public $table= "allsamaj_event";
public $acl=false;
function init(){
parent::init();
$this->hasOne('xavoc\allsamaj\Samaj','samaj_id');
$this->hasOne('xavoc\allsamaj\ContentCategory','category_id');
$this->addField('name')->caption('Title');
$this->addField('content')->type('text')->display(['form'=>'xepan\base\RichText']);
$this->addField('from_date')->type('date');
$this->addField('to_date')->type('date');
$this->addField('facebook_url');
$this->addField('twitter_url');
$this->addField('google_url');
$this->addField('instagram_url');
$this->addField('website_url');
$this->hasMany('xavoc\allsamaj\FeedBack','event_id');
$this->add('xepan/filestore/Field_Image','image_id');
$this->addExpression('day')->set(function($m,$q){
return $q->expr('DAY([0])',[$m->getElement('from_date')]);
});
$this->addExpression('month')->set(function($m,$q){
return $q->expr('DATE_FORMAT([0],"%b")',[$m->getElement('from_date')]);
});
$this->addExpression('year')->set(function($m,$q){
return $q->expr('YEAR([0])',[$m->getElement('from_date')]);
});
$this->addExpression('comment_count')->set(function($m,$q){
return $m->refSQL('xavoc\allsamaj\FeedBack')->count();
});
$this->is([
'name|to_trim|required',
'samaj_id|required',
'category_id|required',
'content|required',
'from_date|required',
'to_date|required',
]);
$this->add('dynamic_model\Controller_AutoCreator');
}
}<file_sep>/lib/Initiator.php
<?php
namespace xavoc\allsamaj;
class Initiator extends \Controller_Addon {
public $addon_name = 'xavoc_allsamaj';
function setup_admin(){
if($this->app->is_admin){
$this->routePages('xavoc_allsamaj');
$this->addLocation(array('template'=>'templates','js'=>'templates/js','css'=>['templates/css','templates/js']))
->setBaseURL('../shared/apps/xavoc/');
}
$m = $this->app->top_menu->addMenu('All Samaj');
$m->addItem(['All Samaj','icon'=>' fa fa-file-image-o'],'xavoc_allsamaj_samaj');
$m->addItem(['Slider','icon'=>' fa fa-file-image-o'],'xavoc_allsamaj_slider');
// $m->addItem(['News','icon'=>' fa fa-file-image-o'],'xavoc_allsamaj_news');
// $m->addItem(['Committee','icon'=>' fa fa-file-image-o'],'xavoc_allsamaj_committee');
// $m->addItem(['Member','icon'=>' fa fa-file-image-o'],'xavoc_allsamaj_member');
// $m->addItem(['Committee Member','icon'=>' fa fa-file-image-o'],'xavoc_allsamaj_committeemember');
$m->addItem(['Location Management','icon'=>' fa fa-file-image-o'],'xavoc_allsamaj_location');
return $this;
}
function setup_frontend(){
$this->routePages('xavoc_allsamaj');
$this->addLocation(array('template'=>'templates','js'=>'templates/js','css'=>['templates/css','templates/js']))
->setBaseURL('./shared/apps/xavoc/allsamaj/');
$this->app->exportFrontEndTool('xavoc\allsamaj\Tool_SamajLister','AllSamaj');
$this->app->exportFrontEndTool('xavoc\allsamaj\Tool_SamajDetail','AllSamaj');
$this->app->exportFrontEndTool('xavoc\allsamaj\Tool_SamajNews','AllSamaj');
$this->app->exportFrontEndTool('xavoc\allsamaj\Tool_Event','AllSamaj');
$this->app->exportFrontEndTool('xavoc\allsamaj\Tool_CommitteeMember','AllSamaj');
$this->app->exportFrontEndTool('xavoc\allsamaj\Tool_Member','AllSamaj');
$this->app->exportFrontEndTool('xavoc\allsamaj\Tool_EventDetail','AllSamaj');
$this->app->exportFrontEndTool('xavoc\allsamaj\Tool_Committee','AllSamaj');
$this->app->exportFrontEndTool('xavoc\allsamaj\Tool_AwesomeSlider','AllSamaj');
$this->app->exportFrontEndTool('xavoc\allsamaj\Tool_Search','AllSamaj');
$this->app->exportFrontEndTool('xavoc\allsamaj\Tool_Feedback','AllSamaj');
return $this;
}
}<file_sep>/lib/Model/Committee.php
<?php
namespace xavoc\allsamaj;
/**
*
*/
class Model_Committee extends \xepan\base\Model_Table{
public $table = "allsamaj_committee";
// public $acl=false;
public $acl_type="Committee";
public $actions= [
'Active'=>['view','edit','delete','member','deactivate'],
'InActive'=>['view','edit','delete','activate'],
];
function init() {
parent::init();
$this->hasOne('xavoc\allsamaj\Samaj','samaj_id');
$this->addField('name');
$this->addField('status')->enum(['Active','InActive'])->defaultValue('Active');
$this->addField('created_at')->type('date')->defaultValue($this->app->now);
$this->addField('description')->type('text');
$this->hasmany('xavoc\allsamaj\CommitteeMember','committee_id');
$this->add('dynamic_model/Controller_AutoCreator');
$this->addExpression('member_count')->set(function($m,$q){
return $m->refSQL('xavoc\allsamaj\CommitteeMember')->count();
});
}
function page_member($page){
$cmember_model = $this->add('xavoc\allsamaj\Model_CommitteeMember');
$cmember_model->addCondition('committee_id',$this->id);
$crud = $page->add('xepan\hr\CRUD',null,null,['view/grid/committee-member']);
$crud->setModel($cmember_model);
}
}<file_sep>/lib/Model/Member.php
<?php
namespace xavoc\allsamaj;
class Model_Member extends \xepan\base\Model_Table {
public $table= "allsamaj_member";
public $acl=false;
function init(){
parent::init();
$this->hasOne('xavoc\allsamaj\Samaj','samaj_id');
$this->addField('name');
$this->addField('contact_no');
$this->addField('email');
$this->add('xepan/filestore/Field_Image','image_id');
$this->is([
'name|to_trim|required',
'samaj_id|required',
]);
$this->add('dynamic_model\Controller_AutoCreator');
}
}<file_sep>/page/eventfeedback.php
<?php
namespace xavoc\allsamaj;
/**
*
*/
class page_eventfeedback extends \xepan\base\Page{
public $title = "Events Comments";
function init(){
parent::init();
$event_id = $this->app->stickyGET('event_id');
$comment = $this->add('xavoc\allsamaj\Model_FeedBack');
if($event_id)
$comment->addCondition('event_id',$event_id);
$crud = $this->add('xepan\hr\CRUD',null,null,['view/grid/event-comment']);
$crud->setModel($comment);
}
}<file_sep>/lib/Tool/SamajDetail.php
<?php
namespace xavoc\allsamaj;
/**
*
*/
class Tool_SamajDetail extends \xepan\cms\View_Tool {
public $options=[];
function init(){
parent::init();
$samaj_id = $this->app->stickyGET('samaj_id');
$m = $this->add('xavoc/allsamaj/Model_Samaj');
if(!$samaj_id){
$this->add('View_Error')->set('Samaj Not Define');
return;
}else{
$m->load($samaj_id);
}
$this->setModel($m);
}
function defaultTemplate(){
return ['view/samajdetail'];
}
}<file_sep>/lib/Model/ContentCategory.php
<?php
namespace xavoc\allsamaj;
class Model_ContentCategory extends \xepan\base\Model_Table {
public $table= "allsamaj_content_category";
public $acl=false;
function init(){
parent::init();
$this->hasOne('xavoc\allsamaj\Samaj','samaj_id');
$this->addField('name');
$this->hasMany('xavoc\allsamaj\News','samaj_id');
$this->hasMany('xavoc\allsamaj\Events','samaj_id');
$this->is([
'name|to_trim|required',
'samaj_id|required',
]);
$this->add('dynamic_model\Controller_AutoCreator');
}
}<file_sep>/allsamaj.sql
-- phpMyAdmin SQL Dump
-- version 4.5.4.1deb2ubuntu2
-- http://www.phpmyadmin.net
--
-- Host: localhost
-- Generation Time: Apr 22, 2017 at 04:26 PM
-- Server version: 10.1.22-MariaDB-1~xenial
-- PHP Version: 7.0.15-0ubuntu0.16.04.4
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: `xepan2`
--
-- --------------------------------------------------------
--
-- Table structure for table `allsamaj_state`
--
CREATE TABLE `allsamaj_state` (
`id` int(11) NOT NULL,
`country_id` int(11) DEFAULT NULL,
`name` varchar(255) DEFAULT NULL
) ENGINE=MyISAM DEFAULT CHARSET=latin1;
--
-- Indexes for dumped tables
--
--
-- Indexes for table `allsamaj_state`
--
ALTER TABLE `allsamaj_state`
ADD PRIMARY KEY (`id`),
ADD KEY `fk_country_id` (`country_id`);
--
-- AUTO_INCREMENT for dumped tables
--
--
-- AUTO_INCREMENT for table `allsamaj_state`
--
ALTER TABLE `allsamaj_state`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT;
/*!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 */;
-- phpMyAdmin SQL Dump
-- version 4.5.4.1deb2ubuntu2
-- http://www.phpmyadmin.net
--
-- Host: localhost
-- Generation Time: Apr 22, 2017 at 04:26 PM
-- Server version: 10.1.22-MariaDB-1~xenial
-- PHP Version: 7.0.15-0ubuntu0.16.04.4
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: `xepan2`
--
-- --------------------------------------------------------
--
-- Table structure for table `allsamaj_samaj`
--
CREATE TABLE `allsamaj_samaj` (
`id` int(11) NOT NULL,
`city_id` int(11) DEFAULT NULL,
`name` varchar(255) DEFAULT NULL,
`status` varchar(255) DEFAULT NULL,
`image_id` int(10) UNSIGNED DEFAULT NULL
) ENGINE=MyISAM DEFAULT CHARSET=latin1;
--
-- Indexes for dumped tables
--
--
-- Indexes for table `allsamaj_samaj`
--
ALTER TABLE `allsamaj_samaj`
ADD PRIMARY KEY (`id`),
ADD KEY `fk_city_id` (`city_id`),
ADD KEY `fk_image_id` (`image_id`);
--
-- AUTO_INCREMENT for dumped tables
--
--
-- AUTO_INCREMENT for table `allsamaj_samaj`
--
ALTER TABLE `allsamaj_samaj`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT;
/*!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 */;
-- phpMyAdmin SQL Dump
-- version 4.5.4.1deb2ubuntu2
-- http://www.phpmyadmin.net
--
-- Host: localhost
-- Generation Time: Apr 22, 2017 at 04:26 PM
-- Server version: 10.1.22-MariaDB-1~xenial
-- PHP Version: 7.0.15-0ubuntu0.16.04.4
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: `xepan2`
--
-- --------------------------------------------------------
--
-- Table structure for table `allsamaj_news`
--
CREATE TABLE `allsamaj_news` (
`id` int(11) NOT NULL,
`samaj_id` int(11) DEFAULT NULL,
`category_id` int(11) DEFAULT NULL,
`name` varchar(255) DEFAULT NULL,
`content` text,
`date` date DEFAULT NULL
) ENGINE=MyISAM DEFAULT CHARSET=latin1;
--
-- Indexes for dumped tables
--
--
-- Indexes for table `allsamaj_news`
--
ALTER TABLE `allsamaj_news`
ADD PRIMARY KEY (`id`),
ADD KEY `fk_samaj_id` (`samaj_id`),
ADD KEY `fk_category_id` (`category_id`);
--
-- AUTO_INCREMENT for dumped tables
--
--
-- AUTO_INCREMENT for table `allsamaj_news`
--
ALTER TABLE `allsamaj_news`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT;
/*!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 */;
-- phpMyAdmin SQL Dump
-- version 4.5.4.1deb2ubuntu2
-- http://www.phpmyadmin.net
--
-- Host: localhost
-- Generation Time: Apr 22, 2017 at 04:25 PM
-- Server version: 10.1.22-MariaDB-1~xenial
-- PHP Version: 7.0.15-0ubuntu0.16.04.4
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: `xepan2`
--
-- --------------------------------------------------------
--
-- Table structure for table `allsamaj_member`
--
CREATE TABLE `allsamaj_member` (
`id` int(11) NOT NULL,
`samaj_id` int(11) DEFAULT NULL,
`name` varchar(255) DEFAULT NULL
) ENGINE=MyISAM DEFAULT CHARSET=latin1;
--
-- Indexes for dumped tables
--
--
-- Indexes for table `allsamaj_member`
--
ALTER TABLE `allsamaj_member`
ADD PRIMARY KEY (`id`),
ADD KEY `fk_samaj_id` (`samaj_id`);
--
-- AUTO_INCREMENT for dumped tables
--
--
-- AUTO_INCREMENT for table `allsamaj_member`
--
ALTER TABLE `allsamaj_member`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT;
/*!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 */;
-- phpMyAdmin SQL Dump
-- version 4.5.4.1deb2ubuntu2
-- http://www.phpmyadmin.net
--
-- Host: localhost
-- Generation Time: Apr 22, 2017 at 04:25 PM
-- Server version: 10.1.22-MariaDB-1~xenial
-- PHP Version: 7.0.15-0ubuntu0.16.04.4
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: `xepan2`
--
-- --------------------------------------------------------
--
-- Table structure for table `allsamaj_event`
--
CREATE TABLE `allsamaj_event` (
`id` int(11) NOT NULL,
`samaj_id` int(11) DEFAULT NULL,
`category_id` int(11) DEFAULT NULL,
`name` varchar(255) DEFAULT NULL,
`content` text,
`from_date` date DEFAULT NULL,
`to_date` date DEFAULT NULL
) ENGINE=MyISAM DEFAULT CHARSET=latin1;
--
-- Indexes for dumped tables
--
--
-- Indexes for table `allsamaj_event`
--
ALTER TABLE `allsamaj_event`
ADD PRIMARY KEY (`id`),
ADD KEY `fk_samaj_id` (`samaj_id`),
ADD KEY `fk_category_id` (`category_id`);
--
-- AUTO_INCREMENT for dumped tables
--
--
-- AUTO_INCREMENT for table `allsamaj_event`
--
ALTER TABLE `allsamaj_event`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT;
/*!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 */;
-- phpMyAdmin SQL Dump
-- version 4.5.4.1deb2ubuntu2
-- http://www.phpmyadmin.net
--
-- Host: localhost
-- Generation Time: Apr 22, 2017 at 04:25 PM
-- Server version: 10.1.22-MariaDB-1~xenial
-- PHP Version: 7.0.15-0ubuntu0.16.04.4
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: `xepan2`
--
-- --------------------------------------------------------
--
-- Table structure for table `allsamaj_country`
--
CREATE TABLE `allsamaj_country` (
`id` int(11) NOT NULL,
`name` varchar(255) DEFAULT NULL
) ENGINE=MyISAM DEFAULT CHARSET=latin1;
--
-- Indexes for dumped tables
--
--
-- Indexes for table `allsamaj_country`
--
ALTER TABLE `allsamaj_country`
ADD PRIMARY KEY (`id`);
--
-- AUTO_INCREMENT for dumped tables
--
--
-- AUTO_INCREMENT for table `allsamaj_country`
--
ALTER TABLE `allsamaj_country`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT;
/*!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 */;
-- phpMyAdmin SQL Dump
-- version 4.5.4.1deb2ubuntu2
-- http://www.phpmyadmin.net
--
-- Host: localhost
-- Generation Time: Apr 22, 2017 at 04:24 PM
-- Server version: 10.1.22-MariaDB-1~xenial
-- PHP Version: 7.0.15-0ubuntu0.16.04.4
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: `xepan2`
--
-- --------------------------------------------------------
--
-- Table structure for table `allsamaj_content_category`
--
CREATE TABLE `allsamaj_content_category` (
`id` int(11) NOT NULL,
`samaj_id` int(11) DEFAULT NULL,
`name` varchar(255) DEFAULT NULL
) ENGINE=MyISAM DEFAULT CHARSET=latin1;
--
-- Indexes for dumped tables
--
--
-- Indexes for table `allsamaj_content_category`
--
ALTER TABLE `allsamaj_content_category`
ADD PRIMARY KEY (`id`),
ADD KEY `fk_samaj_id` (`samaj_id`);
--
-- AUTO_INCREMENT for dumped tables
--
--
-- AUTO_INCREMENT for table `allsamaj_content_category`
--
ALTER TABLE `allsamaj_content_category`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT;
/*!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 */;
-- phpMyAdmin SQL Dump
-- version 4.5.4.1deb2ubuntu2
-- http://www.phpmyadmin.net
--
-- Host: localhost
-- Generation Time: Apr 22, 2017 at 04:24 PM
-- Server version: 10.1.22-MariaDB-1~xenial
-- PHP Version: 7.0.15-0ubuntu0.16.04.4
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: `xepan2`
--
-- --------------------------------------------------------
--
-- Table structure for table `allsamaj_city`
--
CREATE TABLE `allsamaj_city` (
`id` int(11) NOT NULL,
`state_id` int(11) DEFAULT NULL,
`name` varchar(255) DEFAULT NULL
) ENGINE=MyISAM DEFAULT CHARSET=latin1;
--
-- Indexes for dumped tables
--
--
-- Indexes for table `allsamaj_city`
--
ALTER TABLE `allsamaj_city`
ADD PRIMARY KEY (`id`),
ADD KEY `fk_state_id` (`state_id`);
--
-- AUTO_INCREMENT for dumped tables
--
--
-- AUTO_INCREMENT for table `allsamaj_city`
--
ALTER TABLE `allsamaj_city`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT;
/*!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>/page/member.php
<?php
namespace xavoc\allsamaj;
/**
*
*/
class page_member extends \xepan\base\Page{
public $title = "Samaj Member";
function init(){
parent::init();
$this->add('xepan\hr\CRUD',null,null,['view/grid/member'])->setModel('xavoc\allsamaj\Member');
}
}<file_sep>/lib/Tool/Feedback.php
<?php
namespace xavoc\allsamaj;
/**
*
*/
class Tool_Feedback extends \xepan\cms\View_Tool{
public $options=[
];
function init(){
parent::init();
$samaj_id = $this->app->stickyGET('samaj_id');
$event_id = $this->app->stickyGET('event_id');
$m = $this->add('xavoc/allsamaj/Model_FeedBack');
$m->addCondition('status','Active');
if($samaj_id OR !$event_id)
$m->addCondition('samaj_id',$samaj_id);
if($event_id)
$m->addCondition('event_id',$event_id);
$view = $this->add('View');
$f = $view->add('Form');
$f->setLayout(['view/feedback']);
$lister = $view->add('CompleteLister',null,null,['view/feedback-list']);
// $f->addField('line','email')->validate('required');
$comment_f = $f->addField('text','comment')->validate('required');
$f->addSubmit('Comment')->addClass('btn btn-success btn-block');
if($f->isSubmitted()){
// throw new \Exception($samaj_id, 1);
$comment_m = $this->add('xavoc/allsamaj/Model_FeedBack');
$comment_m['samaj_id'] = $samaj_id;
$comment_m['event_id'] = $event_id;
$comment_m['message'] = $f['comment'];
$comment_m['status'] = $f['InActive'];
$comment_m->save();
$js = [
// $f->js()->reload(),
$f->js()->html('<div style="width:100%"><img style="width:20%;display:block;margin:auto auto 50%;" src="vendor\xepan\communication\templates\images\email-loader.gif"/></div>')->reload()
];
$f->js(true,$js)->execute();
}
$m->setOrder('id','desc');
$lister->setModel($m);
$lister->addHook('formatRow',function($l){
$l->current_row['created_at'] = date('d M Y',strtotime($l->model['created_at']));
});
}
}<file_sep>/lib/Tool/Member.php
<?php
namespace xavoc\allsamaj;
/**
*
*/
class Tool_Member extends \xepan\cms\View_Tool {
public $options=[
'image_of_member'=>' ',
'no_of_member'=>10,
];
function init(){
parent::init();
$samaj_id = $this->app->stickyGET('samaj_id');
$m = $this->add('xavoc/allsamaj/Model_Member');
if($samaj_id)
$m->addCondition('samaj_id',$samaj_id);
$grid = $this->add('CompleteLister',null,null,['view/member']);
$grid->setModel($m);
}
// function defaultTemplate(){
// return ['view/member'];
// }
}<file_sep>/page/location.php
<?php
namespace xavoc\allsamaj;
class page_location extends \xepan\base\Page{
public $title= "Location Management";
function init(){
parent::init();
$tabs = $this->add('Tabs');
$tabs->addTab('City')
->add('xepan\hr\CRUD')->setModel('xavoc\allsamaj\City');
$tabs->addTab('State')
->add('xepan\hr\CRUD')->setModel('xavoc\allsamaj\State');
$tabs->addTab('Country')
->add('xepan\hr\CRUD')->setModel('xavoc\allsamaj\Country');
}
}<file_sep>/lib/Tool/SamajLister.php
<?php
namespace xavoc\allsamaj;
class Tool_SamajLister extends \xepan\cms\View_Tool {
public $options=[
'show_search_bar'=>true,
'no_of_record_on_page'=>10,
'no_of_column'=>4,
'detail_url_page'=>null,
'include_featured_samaj_also'=>false,
'show_city_list'=>'udaipur'
];
function init(){
parent::init();
$filter_samaj = $this->app->stickyGET('search');
$samaj_model = $this->add('xavoc\allsamaj\Model_Samaj');
$order_by="id desc";
if($this->options['include_featured_samaj_also']==='yes'){
$order_by = "is_featured desc, id desc";
}
$samaj_model->addCondition('status','Active');
$samaj_model->setOrder($order_by);
if($filter_samaj){
// $item->addExpression('Relevance')->set('MATCH(search_string) AGAINST ("'.$_GET['search'].'" IN NATURAL LANGUAGE MODE)');
$samaj_model->addExpression('Relevance')->set(function($m, $q){
return $q->expr('MATCH([0]) AGAINST ("[1]" IN NATURAL LANGUAGE MODE)',[$q->getField('search_string'),$_GET['search']]);
});
$samaj_model->addCondition('Relevance','>',0);
$samaj_model->setOrder('Relevance','Desc');
}
// if($fliter_samaj)
// $samaj_model->addCondition('id',$fliter_samaj);
$view = $this->add('View');
$lister = $view->add('CompleteLister',null,null,['view/samajlister']);
$lister->addHook('formatRow',function($l){
if($this->options['no_of_column']){
$l->current_row_html['col'] = $this->options['no_of_column'];
}else{
$l->current_row_html['col'] = "";
}
if($this->options['detail_url_page']){
$l->current_row_html['detail_url_page'] = $this->app->url($this->options['detail_url_page'],['samaj_id'=>$l->model->id]);
}
});
$lister->setModel($samaj_model);
if($this->options['no_of_record_on_page']){
$paginator = $lister->add('Paginator',null,'paginator');
$paginator->setRowsPerPage($this->options['no_of_record_on_page']);
// $samaj_model->setLimit($this->options['no_of_record']);
}
$lister->add('xepan\cms\Controller_Tool_Optionhelper',['options'=>$this->options,'model'=>$samaj_model]);
}
}<file_sep>/templates/view/member.html
<div id="{$_name}" class="xepan-grid main-box clearfix {$class}">{Pannel}
<header class="main-box-header clearfix atk-actions {$class} ">
<div class="filter-block">
<div class="pull-right">{$grid_buttons} </div>
<div class="form-group pull-right xepan-filter-form">
<div class="form-control pull-left">{$quick_search}<i class="fa fa-search search-icon"></i></div>
</div>
</div>
</header>{/Pannel}
<div style="width:100%" class="container">
<div class="row">
<div class="col-lg-12">
{header}{cols}{col}{/}{/}{/}
{rows}{row}
<div data-id="{$id}" class="{$odd_even} media"><a href="#committee-member" class="pull-left"><img alt="64x64" data-src="{image}holder.js/64x64{/}" style="width: 100px; height: 100px;" src="{image}http://placehold.it/64x64{/}" class="media-object img-thumbnail"/></a>
<div class="media-body">
<h3 class="media-heading"><strong><a href="#">{name}<NAME>{/}
<div class="small">{post} Dernière visite{/}</div></a></strong></h3>
<p class="small">{samaj} Dernière visite{/}
</p>
<p style="margin:auto" class="small"> {contact_no}il y a 12 jours{/}</p>
<p style="margin:auto" class="small">{email} Dernière visite{/} </p>
</div>
</div>{/}{/}
</div>{not_found}
<div class="row">
<div role="alert" class="col-md-12 text-center alert alert-warning"><span class="icon-attention fa fa-exclamation-triangle"> {$not_found_message}</span></div>
</div>{/}
{totals}{cols}{col}{$content}{/}{/}{/}
</div>{$Paginator}
</div>
</div><file_sep>/page/committee.php
<?php
namespace xavoc\allsamaj;
/**
*
*/
class page_committee extends \xepan\base\Page{
public $title = "Samaj Committees";
function init(){
parent::init();
$this->add('xepan\hr\CRUD')->setModel('xavoc\allsamaj\Committee');
}
}<file_sep>/lib/Tool/Event.php
<?php
namespace xavoc\allsamaj;
/**
*
*/
class Tool_Event extends \xepan\cms\View_Tool {
public $options=[
'show_image'=>'',
'detail_url'=>'',
'no_of_column'=>' ',
'no_of_record'=>10,
];
function init(){
parent::init();
$samaj_id = $this->app->stickyGET('samaj_id');
$committee_id = $this->app->stickyGET('committee_id');
$m = $this->add('xavoc/allsamaj/Model_Event');
if($samaj_id)
$m->addCondition('samaj_id',$samaj_id);
if($committee_id)
$m->addCondition('committee_id',$committee_id);
// $m->addExpression('detail_url')->set(function($m,$q){
// return $url;
// });
$grid = $this->add('CompleteLister',null,null,['view/event']);
$grid->setModel($m);
$grid->addHook('formatRow',function($g){
if($this->options['no_of_column']){
$g->current_row_html['col'] = $this->options['no_of_column'];
}else{
$g->current_row_html['col'] = "";
}
$g->current_row_html['content'] = $g->model['content'];
$g->current_row_html['detail_url'] = $g->app->url($this->options['detail_url'],['event_id'=>$g->model->id]);
$social_url = ['facebook_url','instagram_url','twitter_url','google_url','website_url'];
foreach ($social_url as $key => $value) {
if($g->model[$value]){
}else{
$g->current_row_html[$value.'_wrapper'] = "";
}
}
if(!$this->options['show_image']){
$g->current_row_html['image_wrapper'] = "";
}
});
if($this->options['no_of_record']){
$paginator = $grid->add('Paginator',null,'Paginator');
$paginator->setRowsPerPage($this->options['no_of_record']);
// $grid->addPaginator($this->options['no_of_record']);
// $m->setLimit($this->options['no_of_record']);
}
}
}<file_sep>/lib/Model/Images.php
<?php
namespace xavoc\allsamaj;
/**
*
*/
class Model_Images extends \xepan\base\Model_Table{
public $table = "allsamaj_images";
function init(){
parent::init();
$this->hasOne('xavoc\allsamaj\City','city_id');
$this->hasOne('xavoc\allsamaj\Samaj','samaj_id');
$this->add('xepan\filestore\Field_File','file_id');
$this->hasOne('xavoc\allsamaj\Model_CarouselCategory','carousel_category_id');
$this->addField('title');
$this->addField('text_to_display')->display(['form'=>'xepan\base\RichText']);
$this->addField('alt_text');
$this->addField('order');
$this->addField('link');
$this->addField('created_at')->type('datetime')->defaultValue($this->app->now);
$this->addField('status')->enum($this->status)->defaultValue('Visible');
$this->addField('type');
$this->addCondition('type','CarouselImage');
$this->addExpression('thumb_url')->set(function($m,$q){
return $q->expr('[0]',[$m->getElement('file')]);
});
$this->add('dynamic_model/Controller_AutoCreator');
}
}<file_sep>/lib/Model/Samaj.php
<?php
namespace xavoc\allsamaj;
class Model_Samaj extends \xepan\base\Model_Table {
public $table= "allsamaj_samaj";
public $acl_type="Samaj";
public $actions= [
'Active'=>['view','edit','delete','member_management','manage_news','manage_event','manage_committee','manage_categories','deactivate','feedback'],
'InActive'=>['view','edit','delete','activate'],
];
function init(){
parent::init();
$this->hasOne('xavoc\allsamaj\City','city_id');
$this->addField('name');
$this->add('xepan/filestore/Field_Image',['name'=>'image_id','deref_field'=>'thumb_url']);
$this->addField('status')->enum(['Active','InActive'])->defaultValue('Active');
$this->addField('description')->type('text');
$this->addField('search_string')->type('text')->system(true)->defaultValue(null);
$this->addField('is_featured')->type('boolean')->defaultValue(false);
$this->hasMany('xavoc\allsamaj\News','samaj_id');
$this->hasMany('xavoc\allsamaj\Member','samaj_id');
$this->hasMany('xavoc\allsamaj\Committee','samaj_id');
$this->hasMany('xavoc\allsamaj\Event','samaj_id');
$this->hasMany('xavoc\allsamaj\FeedBack','samaj_id');
$this->add('dynamic_model\Controller_AutoCreator');
$this->addExpression('state')->set(function($m,$q){
return $m->refSQL('city_id')->fieldQuery('state');
});
$this->addHook('beforeSave',[$this,'updateSearchString']);
// $this->addExpression('search_string')->set(function($m,$q){
// return $q->expr('CONCAT([0]," ",[1]," ",[2])',[$m->getElement('name'),$m->getElement('city'),$m->getElement('state')]);
// });
}
function page_manage_news($page){
$news_model = $this->add('xavoc\allsamaj\Model_News');
$news_model->addCondition('samaj_id',$this->id);
$crud = $page->add('xepan\hr\CRUD',null,null,['view/grid/news']);
$crud->setModel($news_model);
}
function page_manage_event($page){
$event_model = $this->add('xavoc\allsamaj\Model_Event');
$event_model->addCondition('samaj_id',$this->id);
$crud = $page->add('xepan\hr\CRUD',null,null,['view/grid/events']);
$crud->setModel($event_model);
}
function page_manage_categories($page){
$categories_model = $this->add('xavoc\allsamaj\Model_ContentCategory');
$categories_model->addCondition('samaj_id',$this->id);
$crud = $page->add('xepan\hr\CRUD');
$crud->setModel($categories_model);
}
function page_member_management($page){
$member_model = $this->add('xavoc\allsamaj\Model_Member');
$member_model->addCondition('samaj_id',$this->id);
$crud = $page->add('xepan\hr\CRUD',null,null,['view/grid/member']);
$crud->setModel($member_model);
}
function page_manage_committee($page){
$c_model = $this->add('xavoc\allsamaj\Model_Committee');
$c_model->addCondition('samaj_id',$this->id);
$crud = $page->add('xepan\hr\CRUD',null,null,['view/grid/committee']);
$crud->setModel($c_model);
// if(!$crud->isEditing()){
// $crud->grid->js('click')->univ()->newWindow($this->app->url('xavoc_allsamaj_committeemember',['committee_id'=>$c_model->id]),"Committee Member");
// }
}
function page_feedback($page){
$c_model = $this->add('xavoc\allsamaj\Model_FeedBack');
$c_model->addCondition('samaj_id',$this->id);
$crud = $page->add('xepan\hr\CRUD',null,null,['view/grid/feedback']);
$crud->setModel($c_model);
}
function updateSearchString($m){
$search_string = ' ';
$search_string .=" ". $this['name'];
$search_string .=" ". $this['description'];
$search_string .=" ". $this['city'];
$search_string .=" ". $this['state'];
$this['search_string'] = $search_string;
}
} | 50e957974979f76d0da02e4e13ff6383b1c3527c | [
"SQL",
"HTML",
"PHP"
] | 32 | PHP | rahulyhg/allsamaj | 1646edafb464164d38dd16b1c7b86ce10fc5bd62 | b6bf7962d4871cd1c91c821940ec9987e327838f |
refs/heads/master | <repo_name>youkidkk/youkidkk-test-util<file_sep>/src/main/java/youkidkk/util/test/TestTool.java
package youkidkk.util.test;
import org.hamcrest.CoreMatchers;
import org.hamcrest.MatcherAssert;
import java.lang.reflect.Constructor;
import java.lang.reflect.Modifier;
/**
* テスト用ツールクラス
*/
public class TestTool {
/**
* コンストラクタ(呼び出し不可)。
*/
private TestTool() {
}
/**
* プライベートコンストラクタのテストを行う
*
* @param clazz 対象クラス
* @throws Exception 例外時
*/
public static void testPrivateConstructor(Class<?> clazz) throws Exception {
// コンストラクタを取得
Constructor<?>[] constructors = clazz.getDeclaredConstructors();
// コンストラクタが一つだけ存在すること
MatcherAssert.assertThat(constructors.length, CoreMatchers.is(1));
// デフォルトコンストラクタが引数なしで private であること
Constructor<?> defaultConstructor = constructors[0];
MatcherAssert.assertThat(defaultConstructor.getParameterTypes().length, CoreMatchers.is(0));
MatcherAssert.assertThat(Modifier.isPrivate(defaultConstructor.getModifiers()),
CoreMatchers.is(true));
defaultConstructor.setAccessible(true);
// コンストラクタを呼び出し、結果をチェック
Object instance = defaultConstructor.newInstance();
MatcherAssert.assertThat(instance, CoreMatchers.is(CoreMatchers.notNullValue()));
MatcherAssert.assertThat(instance, CoreMatchers.instanceOf(clazz));
}
}
<file_sep>/gradle/scripts/jar.gradle
/* プロパティキー : メインクラス */
def propKeyMainClass = 'mainClass'
/* プロパティキー : ベースネーム */
def propKeyBaseName = 'jarBaseName'
/* 実行可能Jarファイル 付加文字列 */
def execAddName = '-exec'
/**
* Jarファイル生成
*/
// ※ アーカイブ名を指定する場合は gradle.properties に jarBaseName を設定する
// ※ バージョンを指定する場合は gradle.properties に version を設定する
jar {
if (project.hasProperty(propKeyBaseName)) {
baseName = getProperty(propKeyBaseName)
}
}
// jarタスクの実行時に実行可能Jarファイル生成
jar.doLast {
if (project.hasProperty(propKeyMainClass)) {
println ':executableJar'
tasks.executableJar.execute()
}
}
/**
* 実行可能Jarファイル生成
* ※ 使用する場合は gradle.properties に mainClass を設定する
*/
task executableJar(type: Jar, dependsOn: jar) {
if (project.hasProperty(propKeyBaseName)) {
baseName = getProperty(propKeyBaseName)
}
if (project.hasProperty(propKeyMainClass)) {
if (project.hasProperty(propKeyBaseName)) {
baseName = getProperty(propKeyBaseName)
}
baseName = baseName + execAddName
manifest {
attributes 'Main-Class' : getProperty(propKeyMainClass)
}
from configurations.compile.collect {it.isDirectory() ? it : zipTree(it)}
from '$buildDir/classes/main'
from '$buildDir/resources/main'
} else {
enabled = false
}
}
/**
* ソースJarファイル生成
*/
task sourcesJar(type: Jar, dependsOn: classes) {
if (project.hasProperty(propKeyBaseName)) {
baseName = getProperty(propKeyBaseName)
}
classifier = 'sources'
from sourceSets.main.allSource
}
/**
* JavadocJarファイル生成
*/
task javadocJar(type: Jar, dependsOn: javadoc) {
if (project.hasProperty(propKeyBaseName)) {
baseName = getProperty(propKeyBaseName)
}
classifier = 'javadoc'
from javadoc.destinationDir
}
/**
* ソースJarファイル、JavadocJarファイルの生成を実行
*/
artifacts {
archives sourcesJar
archives javadocJar
}
/**
* runタスクによる実行
* ※ 使用する場合は gradle.properties に mainClass を設定する
*/
apply plugin: 'application'
run {
if (project.hasProperty(propKeyMainClass)) {
mainClassName = getProperty(propKeyMainClass)
// 実行時引数を使用可能とする
// 実行サンプル : gradle run -Pargs='a b c'
if (project.hasProperty('args')) {
args project.args.split('\\s+')
}
// 標準入力を受け取る
standardInput = System.in
} else {
mainClassName = ''
enabled = false
}
}
<file_sep>/build.gradle
apply plugin: 'java'
apply plugin: 'maven'
/**
* Gradleラッパー設定
*/
task wrapper(type: Wrapper) {
gradleVersion '3.2'
}
/**
* リポジトリ設定
*/
repositories {
jcenter()
mavenCentral()
/* GitHubのプロジェクトを利用 */
maven { url 'https://jitpack.io' }
}
/* 依存関係ビルドスクリプト */
apply from: 'dependencies.gradle'
/* ビルドスクリプトディレクトリ */
def scriptDir = './gradle/scripts/'
/* Java関連ビルドスクリプト */
apply from: scriptDir + 'java.gradle'
/* Jarファイル関連ビルドスクリプト */
apply from: scriptDir + 'jar.gradle'
/* チェック関連ビルドスクリプト */
apply from: scriptDir + 'check.gradle'
<file_sep>/gradle/scripts/check.gradle
/**
* JaCoCoプラグイン設定
*/
apply plugin: 'jacoco'
// testタスクの実行時にJaCoCoレポート出力
test.doLast {
println ':jacocoTestReport'
tasks.jacocoTestReport.execute()
}
/**
* CheckStyle
*/
apply plugin: 'checkstyle'
tasks.withType(Checkstyle) {
checkstyle.toolVersion = '7.1.2'
configFile rootProject.file('gradle/configs/google_checks.xml')
ignoreFailures true
reports {
html.enabled = true
}
}
// テストクラスでの実行スキップ
checkstyleTest {
enabled false
}
/**
* FindBugs
*/
apply plugin: 'findbugs'
tasks.withType(FindBugs) {
// FindBugs でエラーが出るため、レベルをデフォルトにする
// effort = "max"
// reportLevel = "low"
ignoreFailures = true
reports {
xml.enabled = false
html.enabled = true
}
}
// テストクラスでの実行スキップ
findbugsTest {
enabled false
}
<file_sep>/src/main/java/youkidkk/util/test/field/FieldUtil.java
package youkidkk.util.test.field;
import java.lang.reflect.Field;
/**
* フィールドユーティリティークラス
*/
public class FieldUtil {
/**
* コンストラクタ(呼び出し不可)。
*/
private FieldUtil() {
}
/**
* private変数の値を取得する。
*
* @param <T> 戻り値の型
* @param targetClass 対象クラス
* @param targetObject 対象オブジェクト
* @param targetFieldName 対象変数名
* @return 対象変数の値
* @throws NoSuchFieldException 対象の変数が見つからない場合
* @throws SecurityException セキュリティ・マネージャの例外
* @throws IllegalArgumentException メソッド引数異常の場合
* @throws IllegalAccessException メソッドアクセス異常の場合
*/
@SuppressWarnings("unchecked")
public static <T> T getPrivateFieldValue(
Class<?> targetClass,
Object targetObject,
String targetFieldName) throws NoSuchFieldException, SecurityException,
IllegalArgumentException, IllegalAccessException {
Field field = targetClass.getDeclaredField(targetFieldName);
field.setAccessible(true);
return (T) field.get(targetObject);
}
/**
* private変数の値を取得する。
*
* @param <T> 戻り値の型
* @param targetObject 対象オブジェクト
* @param targetFieldName 対象変数名
* @return 対象変数の値
* @throws NoSuchFieldException 対象の変数が見つからない場合
* @throws SecurityException セキュリティ・マネージャの例外
* @throws IllegalArgumentException メソッド引数異常の場合
* @throws IllegalAccessException メソッドアクセス異常の場合
*/
public static <T> T getPrivateFieldValue(
Object targetObject,
String targetFieldName) throws NoSuchFieldException, SecurityException,
IllegalArgumentException, IllegalAccessException {
return getPrivateFieldValue(targetObject.getClass(), targetObject, targetFieldName);
}
/**
* private-static変数の値を取得する。
*
* @param <T> 戻り値の型
* @param targetClass 対象クラス
* @param targetFieldName 対象変数名
* @return 対象変数の値
* @throws NoSuchFieldException 対象の変数が見つからない場合
* @throws SecurityException セキュリティ・マネージャの例外
* @throws IllegalArgumentException メソッド引数異常の場合
* @throws IllegalAccessException メソッドアクセス異常の場合
*/
public static <T> T getPrivateStaticFieldValue(
Class<?> targetClass,
String targetFieldName) throws NoSuchFieldException, SecurityException,
IllegalArgumentException, IllegalAccessException {
return getPrivateFieldValue(targetClass, null, targetFieldName);
}
}
<file_sep>/src/test/java/youkidkk/util/test/field/FieldUtilTest.java
package youkidkk.util.test.field;
import static org.hamcrest.CoreMatchers.*;
import static org.hamcrest.MatcherAssert.*;
import org.junit.Test;
import youkidkk.util.test.ClassForTest;
import youkidkk.util.test.TestTool;
/**
* {@link FieldUtil}のためのテストクラス
*/
public class FieldUtilTest {
/**
* コンストラクタのテスト
*
* @throws Exception 予期せぬ例外
*/
@Test
public void testMethodUtil() throws Exception {
TestTool.testPrivateConstructor(FieldUtil.class);
}
/**
* TestUtil#getPrivateFieldValue のテストメソッド
* {@link FieldUtil#getPrivateFieldValue(Class, Object, String)}
* @throws Exception 予期せぬ例外
*/
@Test
public void testGetPrivateFieldValue() throws Exception {
ClassForTest instance = new ClassForTest(1);
int privateIntFieldValue = FieldUtil.getPrivateFieldValue(
instance, "privateIntField");
assertThat(privateIntFieldValue, is(123));
String privateStringFieldValue = FieldUtil.getPrivateFieldValue(
instance, "privateStringField");
assertThat(privateStringFieldValue, is("abc"));
}
/**
* TestUtil#getPrivateStaticFieldValue のテストメソッド
* {@link FieldUtil#getPrivateStaticFieldValue(Class, String)}
* @throws Exception 予期せぬ例外
*/
@Test
public void testGetPrivateStaticFieldValue() throws Exception {
int privateIntFieldValue = FieldUtil.getPrivateStaticFieldValue(
ClassForTest.class, "privateStaticIntField");
assertThat(privateIntFieldValue, is(456));
String privateStringFieldValue = FieldUtil.getPrivateStaticFieldValue(
ClassForTest.class, "privateStaticStringField");
assertThat(privateStringFieldValue, is("def"));
}
}
<file_sep>/src/test/java/youkidkk/util/test/ClassForTest.java
package youkidkk.util.test;
/**
* テスト用クラス
*/
public class ClassForTest {
/** voidメソッド確認用フィールド */
public static String methodInvoked;
/** コンストラクタテスト用フィールド */
@SuppressWarnings("unused")
private int intField;
/** コンストラクタテスト用フィールド */
@SuppressWarnings("unused")
private String stringField;
/**
* テスト用コンストラクタ
*
* @param i 引数(int)
* @param s 引数(String)
*/
@SuppressWarnings("unused")
private ClassForTest(int i, String s) {
this.intField = i;
this.stringField = s;
}
/**
* テスト用コンストラクタ
*
*/
@SuppressWarnings("unused")
private ClassForTest() {
}
/**
* テスト用コンストラクタ
* @param i 引数
*
*/
public ClassForTest(int i) {
}
/**
* テスト用メソッド
*
* @return String
*/
@SuppressWarnings("unused")
private String privateMethod() {
return "result : none";
}
/**
* テスト用メソッド
*
* @param i 引数(int)
* @param s 引数(String)
* @return String
*/
@SuppressWarnings("unused")
private String privateMethod(int i, String s) {
return "result : " + i + " : " + s;
}
/**
* テスト用メソッド
*
*/
@SuppressWarnings("unused")
private void privateVoidMethod() {
methodInvoked = "privateVoidMethod with no args";
}
/**
* テスト用メソッド
*
* @param i 引数(int)
* @param s 引数(String)
*/
@SuppressWarnings("unused")
private void privateVoidMethod(int i, String s) {
methodInvoked = "privateVoidMethod with " + i + " and " + s;
}
/**
* テスト用メソッド
*
* @return String
*/
@SuppressWarnings("unused")
private static String privateStaticMethod() {
return "result : static none";
}
/**
* テスト用メソッド
*
* @param s 引数(String)
* @param i 引数(int)
* @return String
*/
@SuppressWarnings("unused")
private static String privateStaticMethod(String s, int i) {
return "result : " + s + " : " + i;
}
/**
* テスト用メソッド
*
*/
@SuppressWarnings("unused")
private static void privateStaticVoidMethod() {
methodInvoked = "privateStaticVoidMethod with no args";
}
/**
* テスト用メソッド
*
* @param s 引数(String)
* @param i 引数(int)
*/
@SuppressWarnings("unused")
private static void privateStaticVoidMethod(String s, int i) {
methodInvoked = "privateStaticVoidMethod with " + s + " and " + i;
}
/** テスト用private変数 */
@SuppressWarnings("unused")
private int privateIntField = 123;
/** テスト用private変数 */
@SuppressWarnings("unused")
private String privateStringField = "abc";
/** テスト用private変数 */
@SuppressWarnings("unused")
private static int privateStaticIntField = 456;
/** テスト用private変数 */
@SuppressWarnings("unused")
private static String privateStaticStringField = "def";
}
<file_sep>/gradle/scripts/java.gradle
/* Javaバージョン */
def javaVersion = '1.8'
/* エンコード */
def defaultEncoding = 'UTF-8'
/**
* Javaバージョン設定
*/
sourceCompatibility = javaVersion
targetCompatibility = javaVersion
/**
* エンコード設定 : コンパイル時
*/
tasks.withType(AbstractCompile) each {
it.options.encoding = defaultEncoding
}
/**
* エンコード設定 : テストコンパイル時
*/
compileTestJava {
options.encoding = defaultEncoding
}
/**
* Javadoc
*/
javadoc {
options.charSet = defaultEncoding
options.encoding = defaultEncoding
}
<file_sep>/gradle.properties
jarBaseName = youkidkk-test-util
version = 0.0.9
| d26ef06238891994fe04dcf8bf5afb180eeb0a8d | [
"Java",
"INI",
"Gradle"
] | 9 | Java | youkidkk/youkidkk-test-util | e9e2001320179d7b5b0f6b19bc89323e7cb27e50 | bf774090ed58651c464b91fe54ad6d71d6ff3367 |
refs/heads/master | <file_sep><?php
include "koneksi.php";
$json = array();
$user_id = $_POST['user_id'];
$query = "SELECT (SELECT IFNULL(SUM(nominal),0) FROM pemasukan WHERE MONTH(tanggal) = 1 AND created_by ='$user_id' ) AS in_1,
(SELECT IFNULL(SUM(nominal),0) FROM pemasukan WHERE MONTH(tanggal) = 2 AND created_by ='$user_id') AS in_2,
(SELECT IFNULL(SUM(nominal),0) FROM pemasukan WHERE MONTH(tanggal) = 3 AND created_by ='$user_id') AS in_3,
(SELECT IFNULL(SUM(nominal),0) FROM pemasukan WHERE MONTH(tanggal) = 4 AND created_by ='$user_id') AS in_4,
(SELECT IFNULL(SUM(nominal),0) FROM pemasukan WHERE MONTH(tanggal) = 5 AND created_by ='$user_id') AS in_5,
(SELECT IFNULL(SUM(nominal),0) FROM pemasukan WHERE MONTH(tanggal) = 6 AND created_by ='$user_id') AS in_6,
(SELECT IFNULL(SUM(nominal),0) FROM pemasukan WHERE MONTH(tanggal) = 7 AND created_by ='$user_id') AS in_7,
(SELECT IFNULL(SUM(nominal),0) FROM pemasukan WHERE MONTH(tanggal) = 8 AND created_by ='$user_id') AS in_8,
(SELECT IFNULL(SUM(nominal),0) FROM pemasukan WHERE MONTH(tanggal) = 9 AND created_by ='$user_id') AS in_9,
(SELECT IFNULL(SUM(nominal),0) FROM pemasukan WHERE MONTH(tanggal) = 10 AND created_by ='$user_id') AS in_10,
(SELECT IFNULL(SUM(nominal),0) FROM pemasukan WHERE MONTH(tanggal) = 11 AND created_by ='$user_id') AS in_11,
(SELECT IFNULL(SUM(nominal),0) FROM pemasukan WHERE MONTH(tanggal) = 12 AND created_by ='$user_id') AS in_12,
(SELECT IFNULL(SUM(nominal),0) FROM pengeluaran WHERE MONTH(tanggal) = 1 AND created_by ='$user_id') AS out_1,
(SELECT IFNULL(SUM(nominal),0) FROM pengeluaran WHERE MONTH(tanggal) = 2 AND created_by ='$user_id') AS out_2,
(SELECT IFNULL(SUM(nominal),0) FROM pengeluaran WHERE MONTH(tanggal) = 3 AND created_by ='$user_id') AS out_3,
(SELECT IFNULL(SUM(nominal),0) FROM pengeluaran WHERE MONTH(tanggal) = 4 AND created_by ='$user_id') AS out_4,
(SELECT IFNULL(SUM(nominal),0) FROM pengeluaran WHERE MONTH(tanggal) = 5 AND created_by ='$user_id') AS out_5,
(SELECT IFNULL(SUM(nominal),0) FROM pengeluaran WHERE MONTH(tanggal) = 6 AND created_by ='$user_id') AS out_6,
(SELECT IFNULL(SUM(nominal),0) FROM pengeluaran WHERE MONTH(tanggal) = 7 AND created_by ='$user_id') AS out_7,
(SELECT IFNULL(SUM(nominal),0) FROM pengeluaran WHERE MONTH(tanggal) = 8 AND created_by ='$user_id') AS out_8,
(SELECT IFNULL(SUM(nominal),0) FROM pengeluaran WHERE MONTH(tanggal) = 9 AND created_by ='$user_id') AS out_9,
(SELECT IFNULL(SUM(nominal),0) FROM pengeluaran WHERE MONTH(tanggal) = 10 AND created_by ='$user_id') AS out_10,
(SELECT IFNULL(SUM(nominal),0) FROM pengeluaran WHERE MONTH(tanggal) = 11 AND created_by ='$user_id') AS out_11,
(SELECT IFNULL(SUM(nominal),0) FROM pengeluaran WHERE MONTH(tanggal) = 12 AND created_by ='$user_id') AS out_12 ";
$execute = mysqli_query($KONEKSI, $query);
$count = mysqli_num_rows($execute);
if($count > 0){
while($row=mysqli_fetch_assoc($execute)){
$json[] = $row;
}
}else{
$json = array();
}
echo json_encode($json);
mysqli_close($KONEKSI);
?><file_sep>
<?php
$KONEKSI = mysqli_connect('192.168.1.87', 'root', '');
$DATABASE = mysqli_select_db($KONEKSI, 'bukukas');
if (!$KONEKSI) {
die("Koneksi Gagal : " . mysqli_connect_error());
}
echo "Koneksi berhasil";
?><file_sep><?php
include "koneksi.php";
$json = array();
$id = $_POST['id'];
$query = "SELECT * ,(select sum(nominal) from pemasukan
WHERE created_by = users.id and MONTH(tanggal) = MONTH(CURDATE()) AND YEAR(tanggal) = YEAR(CURDATE()) ) as total_pemasukan,
(select sum(nominal) from pengeluaran
WHERE created_by = users.id and MONTH(tanggal) = MONTH(CURDATE()) AND YEAR(tanggal) = YEAR(CURDATE())) as total_pengeluaran,
(select sum(nominal) from pemasukan WHERE created_by = users.id and MONTH(tanggal) = MONTH(CURDATE()) AND YEAR(tanggal) = YEAR(CURDATE()) ) -
(select sum(nominal) from pengeluaran WHERE created_by = users.id and MONTH(tanggal) = MONTH(CURDATE()) AND YEAR(tanggal) = YEAR(CURDATE())) as saldo
from users WHERE id ='$id' ";
$execute = mysqli_query($KONEKSI, $query);
$count = mysqli_num_rows($execute);
if($count > 0){
while($row=mysqli_fetch_assoc($execute)){
$json[] = $row;
}
}else{
$json = array();
}
echo json_encode($json);
mysqli_close($KONEKSI);
?><file_sep><?php
include "koneksi.php";
$user_id = $_POST['user_id'];
$json = array();
$query = "SELECT * FROM pengeluaran WHERE created_by ='$user_id' order by id desc limit 50 ";
$execute = mysqli_query($KONEKSI, $query);
$count = mysqli_num_rows($execute);
if($count > 0){
while($row=mysqli_fetch_assoc($execute)){
$json[] = $row;
}
}else{
$json = array();
}
echo json_encode($json);
mysqli_close($KONEKSI);
?><file_sep><?php
include "koneksi.php";
date_default_timezone_set('Asia/Jakarta');
$tanggal = $_POST['tanggal'];
$tipe_pengeluaran = $_POST['tipe_pengeluaran'];
$nominal = $_POST['nominal'];
$created_by = $_POST['user_id'];
$query ="SELECT COUNT(*) as jml FROM pengeluaran where tanggal ='$tanggal' AND created_by ='$created_by' ";
$result = mysqli_query($KONEKSI,$query);
$data = mysqli_fetch_assoc($result);
$count = $data['jml'];
if($count > 0){
$json = array('value'=> 0,'message'=> 'pengeluaran di tanggal tersebut sudah ada ');
}else{
$query = "INSERT INTO pengeluaran (tanggal,tipe_pengeluaran,nominal,created_by)
VALUES ('$tanggal','$tipe_pengeluaran','$nominal','$created_by') ";
$result = mysqli_query($KONEKSI, $query);
if($result){
$json = array('value'=> 1,'message'=> 'Proses berhasil' ,'query'=> $query);
}else{
$json = array('value'=> 0,'message'=> 'Proses gagal' ,'query'=> $query);
}
}
echo json_encode($json);
mysqli_close($KONEKSI);<file_sep><?php
include "koneksi.php";
$nama_lengkap = trim($_POST['nama_lengkap']);
$no_hp = $_POST['no_hp'];
$alamat = $_POST['alamat'];
$username = trim($_POST['username']);
$password = md5($_POST['password']);
$query = "SELECT COUNT(*) as jml FROM users WHERE username ='$username' ";
// print_r($query);
$result = mysqli_query($KONEKSI, $query);
$data = mysqli_fetch_assoc($result);
$count = $data['jml'];
if ($count > 0) {
$json = array('value' => 0, 'message' => 'Username sudah ada');
} else {
$query = "INSERT INTO users (username,`password`,nama_lengkap,no_hp,alamat)
VALUES ('$username','$password','$nama_lengkap','$no_hp','$alamat') ";
$result = mysqli_query($KONEKSI, $query);
if ($result) {
$json = array('value' => 1, 'message' => 'Registrasi berhasil', 'query' => $query);
} else {
$json = array('value' => 0, 'message' => 'Registrasi gagal', 'query' => $query);
}
}
echo json_encode($json);
mysqli_close($KONEKSI);
<file_sep>/*
SQLyog Community v13.1.6 (64 bit)
MySQL - 10.4.14-MariaDB : Database - bukukas
*********************************************************************
*/
/*!40101 SET NAMES utf8 */;
/*!40101 SET SQL_MODE=''*/;
/*!40014 SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0 */;
/*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */;
/*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */;
/*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0 */;
CREATE DATABASE /*!32312 IF NOT EXISTS*/`bukukas` /*!40100 DEFAULT CHARACTER SET utf8mb4 */;
/* Table structure for table `pemasukan` */
DROP TABLE IF EXISTS `pemasukan`;
CREATE TABLE `pemasukan` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`tanggal` date DEFAULT NULL,
`kategori` varchar(10) DEFAULT NULL,
`jenis_dana` varchar(50) DEFAULT NULL,
`nominal` decimal(10,0) DEFAULT NULL,
`created_by` int(11) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=utf8mb4;
/* Data for the table `pemasukan` */
insert into `pemasukan`(`id`,`tanggal`,`kategori`,`jenis_dana`,`nominal`,`created_by`) values
(1,'2021-01-24','MTS','PAS',500000,1),
(2,'2021-01-18','SMP','PAS',100000,1),
(3,'2021-01-26','MMA','PTS',5000000,1),
(4,'2021-01-24','MTS','SPP',2500000,2),
(5,'2021-01-24','MTS','SPP',2700000,3);
/* Table structure for table `pengeluaran` */
DROP TABLE IF EXISTS `pengeluaran`;
CREATE TABLE `pengeluaran` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`tanggal` date DEFAULT NULL,
`tipe_pengeluaran` varchar(50) DEFAULT NULL,
`nominal` decimal(10,0) DEFAULT NULL,
`created_by` int(11) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8mb4;
/* Data for the table `pengeluaran` */
insert into `pengeluaran`(`id`,`tanggal`,`tipe_pengeluaran`,`nominal`,`created_by`) values
(1,'2021-01-24','PERJALANAN DINAS',15000,1),
(2,'2021-01-24','OPERASIONAL HARIAN',1000000,2),
(3,'2021-01-24','<NAME>',1500000,3);
/* Table structure for table `users` */
DROP TABLE IF EXISTS `users`;
CREATE TABLE `users` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`username` varchar(50) DEFAULT NULL,
`password` varchar(100) DEFAULT NULL,
`nama_lengkap` varchar(50) DEFAULT NULL,
`no_hp` varchar(15) DEFAULT NULL,
`alamat` varchar(200) DEFAULT NULL,
`foto` varchar(200) DEFAULT NULL,
`fcm_token` varchar(50) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8mb4;
/*Data for the table `users` */
insert into `users`(`id`,`username`,`password`,`nama_lengkap`,`no_hp`,`alamat`,`foto`,`fcm_token`) values
(1,'andri','<KEY>','andri ','087387274234','Jakarta pusat',NULL,NULL),
(2,'edward','<KEY>','edward','0878378262892','Jakarta pusat',NULL,NULL),
(3,'ramelan','827ccb0eea8a706c4c34a16891f84e7b','<NAME>','083813997825','Tangerang selatan',NULL,NULL);
/*!40101 SET SQL_MODE=@OLD_SQL_MODE */;
/*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */;
/*!40014 SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS */;
/*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */;
<file_sep><?php
include "koneksi.php";
date_default_timezone_set('Asia/Jakarta');
$tanggal = $_POST['tanggal'];
$kategori = $_POST['kategori'];
$jenis_dana = $_POST['jenis_dana'];
$nominal = $_POST['nominal'];
$created_by = $_POST['user_id'];
$query = "SELECT COUNT(*) as jml FROM pemasukan where tanggal ='$tanggal' AND created_by ='$created_by' ";
$result = mysqli_query($KONEKSI, $query);
$data = mysqli_fetch_assoc($result);
$count = $data['jml'];
if ($count > 0) {
$json = array('value' => 0, 'message' => 'Pemasukan di tanggal tersebut sudah ada ');
} else {
$query = "INSERT INTO pemasukan (tanggal,kategori,jenis_dana,nominal,created_by)
VALUES ('$tanggal','$kategori','$jenis_dana','$nominal','$created_by') ";
$result = mysqli_query($KONEKSI, $query);
if ($result) {
$json = array('value' => 1, 'message' => 'Proses berhasil', 'query' => $query);
} else {
$json = array('value' => 0, 'message' => 'Proses gagal', 'query' => $query);
}
}
echo json_encode($json);
mysqli_close($KONEKSI);
<file_sep><?php
include "koneksi.php";
$username = trim($_POST['username']);
$password = $_POST['password'];
$myusername = mysqli_real_escape_string($KONEKSI, $username);
$mypassword = mysqli_real_escape_string($KONEKSI, $password);
$myusername = str_replace(" ", "", $myusername);
$json = array();
$query = "SELECT *
FROM users a
where a.username ='$myusername' and a.password=md5('<PASSWORD>') ";
$result = mysqli_query($KONEKSI, $query);
$data = mysqli_fetch_assoc($result);
$row = mysqli_num_rows($result);
if ($row > 0) {
$user_id = $data['id'];
$nama = $data['nama_lengkap'];
$username = $data['username'];
$no_hp = $data['no_hp'];
$alamat = $data['alamat'];
$foto = $data['foto'];
if (empty($foto)) {
$foto = 'https://kreditmandiri.co.id/api_test/absensi/profile/photo.jpg';
} else {
$foto = 'http://192.168.1.87/api/bukukas/profile/' . $foto;
}
$json = array(
'value' => 1, 'message' => 'login berhasil', 'nama' => $nama,
'user_id' => $user_id, 'user' => $username, 'no_hp' => $no_hp, 'alamat' => $alamat, 'foto' => $foto
);
} else {
$json = array('value' => 0, 'message' => 'login gagal', 'query' => $query);
}
echo json_encode($json);
mysqli_close($KONEKSI);
<file_sep><?php
include "koneksi.php";
$id = $_POST['id'];
$passwordlama = $_POST['<PASSWORD>'];
$passwordbaru = $_POST['<PASSWORD>u'];
$passwordconfirm = $_POST['passwordconfirm'];
$passwordlama= mysqli_real_escape_string($KONEKSI, $passwordlama);
$passwordlama = str_replace(" ","",$passwordlama);
$passwordbaru= mysqli_real_escape_string($KONEKSI, $passwordbaru);
$passwordbaru = str_replace(" ","",$passwordbaru);
$passwordconfirm = mysqli_real_escape_string($KONEKSI, $passwordconfirm);
$passwordconfirm = str_replace(" ","",$passwordconfirm);
$query ="SELECT COUNT(*) as jml FROM users WHERE id ='$id' and password = md5('<PASSWORD>') ";
$result = mysqli_query($KONEKSI,$query);
$data = mysqli_fetch_assoc($result);
$jml = $data['jml'];
if($jml == 0){
$json = array('value'=> 0,'message'=> 'Maaf password lama anda salah !!!');
}else{
if($passwordconfirm !== $password<PASSWORD> ){
$json = array('value'=> 0,'message'=> 'Maaf password baru dan password confirm tidak sama !!!');
}else{
$query ="UPDATE users Set password =md5('<PASSWORD>') WHERE id ='$id' ";
$result = mysqli_query($KONEKSI,$query);
if($result){
$json = array('value'=> 1,'message'=> 'Proses berhasil !!!');
}else{
$json = array('value'=> 0,'message'=> 'Proses gagal !!!');
}
}
}
echo json_encode($json);
mysqli_close($KONEKSI); | e258e0ca0f91e28028389a99f686b23a85586382 | [
"SQL",
"PHP"
] | 10 | PHP | bagusi21/elmaliya | d59be3aa82824d89eecca3061343bcc2880bb46a | d8616704919f538aa6f1223aceb8b3a1c68baf83 |
refs/heads/master | <repo_name>svn2github/phpdoc_doc-base<file_sep>/tags/POST_EXCEPTIONS_ROLE_CHANGE/scripts/html_syntax.php
#!/usr/bin/php -q
<?php
/*
+----------------------------------------------------------------------+
| PHP Version 4 |
+----------------------------------------------------------------------+
| Copyright (c) 1997-2004 The PHP Group |
+----------------------------------------------------------------------+
| This source file is subject to version 3.0 of the PHP license, |
| that is bundled with this package in the file LICENSE, and is |
| available through the world-wide-web at the following url: |
| http://www.php.net/license/3_0.txt. |
| If you did not receive a copy of the PHP license and are unable to |
| obtain it through the world-wide-web, please send a note to |
| <EMAIL> so we can mail you a copy immediately. |
+----------------------------------------------------------------------+
| Authors: <NAME> <<EMAIL>> |
+----------------------------------------------------------------------+
*/
if ($_SERVER["argc"] < 3) {
exit("Purpose: Syntax highlight PHP examples in DSSSL generated HTML manual.\n"
.'Usage: html_syntax.php [ "html" | "php" ] [ filename.ext | dir | wildcard ] ...' ."\n"
.'"html" - highlight_string() is applied, "php" - highlight_php() is added' ."\n"
);
}
set_time_limit(5*60); // can run long, but not more than 5 minutes
function callback_html_number_entities_decode($matches) {
return chr($matches[1]);
}
function callback_highlight_php($matches) {
$with_tags = preg_replace_callback("!&#([0-9]+);!", "callback_html_number_entities_decode", $matches[1]);
if ($GLOBALS["TYPE"] == "php") {
return "\n<?php\nhighlight_php('". addcslashes($with_tags, "'\\") ."');\n?>\n";
} else { // "html"
return highlight_string($with_tags, true);
}
}
$files = $_SERVER["argv"];
array_shift($files); // $argv[0] - script filename
$TYPE = array_shift($files); // "html" or "php"
while (($file = array_shift($files)) !== null) {
if (is_file($file)) {
$process = array($file);
} elseif (is_dir($file)) {
$lastchar = substr($file, -1);
$process = glob($file . ($lastchar == "/" || $lastchar == "\\" ? "*" : "/*"));
} else { // should be wildcard
$process = glob($file);
}
foreach ($process as $filename) {
if (!is_file($filename)) { // do not recurse
continue;
}
//~ echo "$filename\n";
$original = file_get_contents($filename);
$highlighted = preg_replace_callback("!<PRE\r?\nCLASS=\"php\"\r?\n>(.*)</PRE\r?\n>!sU", "callback_highlight_php", $original);
if ($original != $highlighted) {
// file_put_contents is only in PHP >= 5
$fp = fopen($filename, "wb");
fwrite($fp, $highlighted);
fclose($fp);
}
}
}
?>
<file_sep>/branches/docgen-update/scripts/online_editor/editxml.php
<?php
/*
+----------------------------------------------------------------------+
| PHP Version 4 |
+----------------------------------------------------------------------+
| Copyright (c) 1997-2011 The PHP Group |
+----------------------------------------------------------------------+
| This source file is subject to version 3.0 of the PHP license, |
| that is bundled with this package in the file LICENSE, and is |
| available through the world-wide-web at the following url: |
| http://www.php.net/license/3_0.txt. |
| If you did not receive a copy of the PHP license and are unable to |
| obtain it through the world-wide-web, please send a note to |
| <EMAIL> so we can mail you a copy immediately. |
+----------------------------------------------------------------------+
| Authors : <NAME> <<EMAIL>> |
+----------------------------------------------------------------------+
$Id$
*/
//-- The PHPDOC Online XML Editing Tool
//--- Purpose: this is the actual xml editor script
//------- Initialization
require 'base.php';
$user = sessionCheck('?from=editxml');
$lang = $user['phpdocLang'];
$translationPath = $phpdocLangs[$lang]['DocCVSPath'];
//------- Frames split
if (isset($_REQUEST['split'])) {
if ($_REQUEST['split']=='false' || !$_REQUEST['split']) $_REQUEST['split'] = false;
$_SESSION['split'] = $_REQUEST['split'];
}
if (!empty($_SESSION['split']) && !isset($_REQUEST['noframes'])) {
$source = $_REQUEST['source'];
$file = $_REQUEST['file'];
// ToDo automatically show the translated file in one frame and the source in another
print "<frameset cols=*,*><frame name=frame1 src='editxml.php?file=$file&source=$source&noframes=1'><frame name=frame2 src='editxml.php?file=$file&source=$source&noframes=1'></frameset>";
exit;
}
//------- File Request
if (isset($_REQUEST['source']) && isset($_REQUEST['file'])) {
$source = $_REQUEST['source'];
$file = $_REQUEST['file'];
}
if (!$file || strstr($file, '..')) {
exit;
}
$requestedFilename = $file;
// Turn on/off XML as Text
if (!empty($_REQUEST['textedit']) && $_REQUEST['textedit']!='false') {
$_SESSION['textedit'] = true;
} else {
$_SESSION['textedit'] = false;
}
// Turn on/off Hiding XML tags when editing
if (!empty($_REQUEST['hidexml']) && $_REQUEST['hidexml']!='false') {
$_SESSION['hidexml'] = true;
} else {
$_SESSION['hidexml'] = false;
}
// Turn on/off Line By Line
if (!empty($_REQUEST['linebyline']) && $_REQUEST['linebyline']!='false') {
$_SESSION['para'] = false;
} else {
$_SESSION['para'] = true;
}
//------- Functions
// Parse XML to find editable text
// this function is written poorly but it does the job
function myParse($text) {
$results = array();
$rc = 0;
for($i=0; $i<strlen($text); $i++) {
$c = substr($text, $i, 1);
if ($c=='<') {
// Starting tag
$tagC = '';
$tag = true;
}
if ($tag) {
$tagC .= $c;
} else {
if ($c=="\n") {
// Advance the counter so each line is stored separately
if (empty($_SESSION['para'])) {
$rc++;
} else {
if (!isset($results[$rc])) {
// Get position of New editable text
$results[$rc] = array('index'=>$i, 'text'=>'');
}
$results[$rc]['text'] .= $c;
}
} else {
if (!isset($results[$rc])) {
// Get position of New editable text
$results[$rc] = array('index'=>$i, 'text'=>'');
}
$results[$rc]['text'] .= $c;
}
}
if ($c=='>') {
// Tag ending
$tagC .= $c;
$tag = false;
$rc++;
}
}
// Filter editable text
$resultsx = array();
foreach($results as $resline) {
$res = trim($resline['text']);
// Skip empty, &xx; and literals
if (!$res || ($res[0]=='&' && substr($res,-1)==';') || isLiteral($res) ) continue;
if (!empty($_SESSION['para'])) {
// trim \n and adjust position
while(substr($resline['text'], 0, 1)=="\n" || substr($resline['text'], 0, 1)=="\r") {
$resline['index']++;
$resline['text'] = substr($resline['text'], 1);
}
// recheck \n
if (!strstr($resline['text'], "\n")) {
// treat as one line (trim and adjust)
while(substr($resline['text'], 0, 1)==' ') {
$resline['index']++;
$resline['text'] = substr($resline['text'], 1);
}
$resline['text'] = trim($resline['text']);
}
$res = $resline['text'];
} else {
// trim and adjust position
while(substr($resline['text'], 0, 1)==' ') {
$resline['index']++;
$resline['text'] = substr($resline['text'], 1);
}
$res = trim($resline['text']);
}
$resultsx[$resline['index']] = $res;
}
// Return an array contains all editable texts and their positions in file contents
return $resultsx;
}
function isLiteral($text) {
// ToDo check if text is literal and don't need to be translated
return false;
}
//------- Locate file according to the selected path
$status = getTranslationStatus($file);
switch($source) {
case 'upath': // User cached path
$file = $user['cache'].getCacheName($file);
break;
case 'apath': // File from translation
$file = $translationPath.$file;
break;
case 'epath': // English source
$file = CVS_ROOT_PATH . 'en/' . $file;
break;
case 'diff': // cvs diff
if ($status['distance']>0) {
$url = "http://cvs.php.net/viewvc.cgi/phpdoc/en/$file?r1=$status[fileEnRevision]&r2=$status[lastEnRevision]";
$html = implode('', file($url));
preg_match_all("#(<table cellspacing=\"0\" cellpadding=\"0\">\\s*<tr class=\"vc_diff_header\">.+</table>)#s", $html, $parts);
$data = '<meta name="generator" content="ViewVC 1.1-dev" /><link rel="stylesheet" href="viewvc-style.css" type="text/css" /><div style="font-family: Arial;">';
$data .= str_replace('/viewvc.cgi/', 'http://cvs.php.net/viewvc.cgi/', $parts[1][0]).'</div>';
}
break;
}
//------- Prepare the file for editing
if ($source!='diff'):
// Read the file contents
$data = implode('', file($file));
if (empty($_SESSION['textedit'])) {
// Protect CDATA tags by hiding them before parsing
preg_match_all("#<\!\[CDATA\[(.+)\]\]>#Us", $data, $matches);
$cdataStore = array();
$cdataMarks = array();
foreach($matches[0] as $i=>$cdata) {
$mark = "<CDATA-$i-></CDATA>";
$cdl = strlen($cdata)-strlen($mark);
$mark = "<CDATA-$i-".str_repeat('X', $cdl).'></CDATA>';
$cdataStore[$i] = $cdata;
$cdataMarks[$i] = $mark;
$data = str_replace($cdata, $mark, $data);
}
// Parse file contents and fetch editable text
$results = myParse($data);
// Keep a copy of the actual contents
$newdata = $data;
// Replace editable text with special Marks
$results = array_reverse($results, true);
foreach($results as $index=>$text) {
$newtext = $text;
// If in saving process Put submitted text instead of current text
if (isset($_POST['textAt'][$index])) {
$newtext = stripslashes2($_POST['textAt'][$index]);
// Fix paragraphs that lost prefix \n
if (strstr($newtext, "\n") && substr($newtext, 0, 1)!="\n") {
//$newtext = "\n$newtext";
}
$results[$index] = $newtext;
$newdata = substr_replace($newdata, $newtext, $index, strlen($text));
$updated = true;
}
// Put special marks
if ($newtext!="'>" && $newtext!='">') {
if (strstr($newtext, "\n")) {
// This marks text that has new line (so we will use multiline textarea)
$data = substr_replace($data, "_PMRK[$index]{".$newtext."}PMRK_", $index, strlen($text));
} elseif (strstr($newtext, "'") && !strstr($newtext, '"')) {
// This marks text that has single quote (so the input field will use double quote)
$data = substr_replace($data, "_ZMRK[$index]{".$newtext."}ZMRK_", $index, strlen($text));
} elseif (strstr($newtext, "'") && strstr($newtext, '"')) {
// This marks text that has single and double quote (so we will use textarea)
$data = substr_replace($data, "_YMRK[$index]{".$newtext."}YMRK_", $index, strlen($text));
} else {
// This marks text that can use a normal input
$data = substr_replace($data, "_XMRK[$index]{".$newtext."}XMRK_", $index, strlen($text));
}
}
}
if (!empty($_SESSION['para']) && !empty($updated)) {
// Remove \r (some browsers)
$newdata = str_replace("\r\n", "\r", $newdata);
$newdata = str_replace("\n", "\r", $newdata);
$newdata = str_replace("\r", "\n", $newdata);
if (substr($newdata, -1)!="\n") {
$newdata .= "\n";
}
}
// Put CData back
$data = str_replace($cdataMarks, $cdataStore, $data);
$newdata = str_replace($cdataMarks, $cdataStore, $newdata);
} else {
// Edit XML as Text
if (isset($_POST['xmldata'])) {
$newdata = stripslashes2($_POST['xmldata']);
// Remove \r (some browsers)
$newdata = str_replace("\r\n", "\r", $newdata);
$newdata = str_replace("\n", "\r", $newdata);
$newdata = str_replace("\r", "\n", $newdata);
if (substr($newdata, -1)!="\n") {
$newdata .= "\n";
}
$updated = true;
}
}
//------- Save or Send file when requested
if (!empty($updated) || !empty($_REQUEST['download'])) {
// Charset for new translated files
if ($phpdocLangs[$lang]['charset']!='iso-8859-1') {
$charset = $phpdocLangs[$lang]['charset'];
$newdata = str_replace('<?xml version="1.0" encoding="iso-8859-1"?>', '<?xml version="1.0" encoding="'.$charset.'"?>', $newdata);
}
// EN-Revision for new translated files
if (!stristr($newdata, 'EN-Revision:')) {
$newdata = str_replace('<!-- $'.'Revision'.': ', '<!-- \$'.'Revision'.": 1 $ -->\n<!-- EN-Revision: ", $newdata);
}
// Send file as is (download)
if (isset($_REQUEST['download'])) {
header('Content-Type: application/download');
header('Content-Disposition: attachment; filename='.basename($requestedFilename));
print $newdata;
exit;
}
if ($requireLogin) {
// Save file in user cache folder
$f = fopen($user['cache'].getCacheName($requestedFilename), 'w');
fputs($f, $newdata);
fclose($f);
// Simple log
$f = fopen($user['cache']."files.txt", 'a');
$time = getDateTimeToLog();
$ip = getUserIP();
fputs($f, "$time|$ip|$requestedFilename\r\n");
fclose($f);
}
exit("File has been saved in your cache folder. You can now <a href='editxml.php?file=$requestedFilename&source=$source&download=yes&noframes=1'>download it</a> or edit another file");
}
if (empty($_SESSION['textedit'])) {
// Mark XML Tags to be hidden (when hidexml is true)
$hideXMLTag = empty($_SESSION['hidexml']) ? '' : $_SESSION['hidexml'];
$startXMLTag = '';
$endXMLTag = '';
if ($hideXMLTag) {
$startXMLTag = '_TMRK(';
$endXMLTag = ')TMRK_';
}
// Replace special marks with <input> or <textarea>
$data = htmlspecialchars($data);
$data = preg_replace("#_XMRK\[(\\d+)\]\{(.+)\}XMRK_#U", "$endXMLTag<input type=text class=xinput ondblclick='dblclk(this)' onmouseover='irn(\\1)' onmouseout='iro(\\1)' onkeyup='ku(\\1, event)' onkeydown='kp(\\1, event)' name=textAt[\\1] value='\\2'>$startXMLTag", $data);
$data = preg_replace("#_YMRK\[(\\d+)\]\{(.+)\}YMRK_#U", "$endXMLTag<textarea rows=1 class=xinput ondblclick='dblclk(this)' onmouseover='irn(\\1)' onmouseout='iro(\\1)' onkeyup='ku(\\1, event)' onkeydown='kp(\\1, event)' name=textAt[\\1]>\\2</textarea>$startXMLTag", $data);
$data = preg_replace("#_ZMRK\[(\\d+)\]\{(.+)\}ZMRK_#U", "$endXMLTag<input type=text class=xinput ondblclick='dblclk(this)' onmouseover='irn(\\1)' onmouseout='iro(\\1)' onkeyup='ku(\\1, event)' onkeydown='kp(\\1, event)' name=textAt[\\1] value=\"\\2\">$startXMLTag", $data);
$data = preg_replace("#_PMRK\[(\\d+)\]\{(.+)\}PMRK_#Us", "$endXMLTag<br><textarea name=textAt[\\1] class=xinput2 ondblclick='dblclk(this)' onmouseover='irn(\\1)' onmouseout='iro(\\1)' style='width: 80%;'>\\2</textarea><br>$startXMLTag", $data);
$data = $startXMLTag.$data.$endXMLTag;
// Update input size according to text length
foreach($results as $index=>$text) {
if (!strstr($text, "\n")) {
$size = strlen(utf8_decode($text));
$data = str_replace("textAt[$index]", "textAt[$index] size=$size cols=$size", $data);
} else {
$size = substr_count($text, "\n")+1;
$data = str_replace("<textarea name=textAt[$index]", "<textarea name=textAt[$index] rows=$size", $data);
}
}
// Hide XML Tags
if ($hideXMLTag) {
preg_match_all("#_TMRK\((.+)\)TMRK_#Us", $data, $matches);
foreach($matches[0] as $i=>$line) {
$r = ' ';
if (strstr($line, "\n")) {
$r = "\n";
if (substr_count($line, "\n")>3) {
$r.="\n";
}
}
$data = str_replace($line, $r, $data);
}
}
}
endif;
//------- Output
?>
<html>
<meta http-equiv="Content-Type" content="text/html; charset=<?php print $phpdocLangs[$lang]['charset']; ?>" />
<body bgcolor="#9999cc">
<style type="text/css">
body {
font-family: Tahoma;
font-size: 12px;
}
.xinput {
font-family: <?php print $phpdocLangs[$lang]['font']; ?>;
border: 0px none;
color: #AA0000;
border-bottom: 1px dotted gray;
}
.xinput2 {
font-family: <?php print $phpdocLangs[$lang]['font']; ?>;
color: #AA0000;;
}
.editbox {
font-family: <?php print $phpdocLangs[$lang]['font']; ?>;
color: #006600; background-color: white;
border: 3px groove; width: 100%; height: 400px;
overflow: auto;
}
.editbox-diff {
font-family: <?php print $phpdocLangs[$lang]['font']; ?>;
color: #006600; background-color: white;
border: 3px groove; width: 100%; height: 550px;
overflow: auto;
}
a:link {
text-decoration: none;
color: #000066;
}
a:hover {
text-decoration: none;
color: #ff0000;
}
a:active {
text-decoration: none;
color: #ff0000;
}
a:visited {
text-decoration: none;
color: #000066;
}
</style>
<script language=javascript>
// Highlight input on mouse over
function irn(i) {
var ob = document.getElementById('textAt['+i+']');
ob.style.backgroundColor = '#EEEEEE';
}
// un-Highlight input on mouse over
function iro(i) {
var ob = document.getElementById('textAt['+i+']');
ob.style.backgroundColor = '#FFFFFF';
}
var updated = false;
// Switch between fields when using arrow keys and translate selection by PgdDown key
function kp(i, e) {
var ev= (window.event)? window.event: e;
if(!ev || !ev.type) return false;
var k,w;
if (ev.keyCode) w=1;
if (ev.charCode) w=2;
if (ev.which) w=3;
k = (ev.keyCode)?ev.keyCode: ((ev.charCode)? ev.charCode: ev.which);
if (k==34) { // PageDown to translate
dblclk(document.getElementById('textAt['+i+']'));
if (w==1) e.keyCode = 0;
if (w==2) e.charCode = 0;
if (w==3) e.which = 0;
return false;
}
if (k==40 || k==38) {
if (w==1) e.keyCode = 9;
if (w==2) e.charCode = 9;
if (w==3) e.which = 9;
}
return true;
}
// Update input/textarea size when editing
function ku(i, e) {
updated = true;
var ob = document.getElementById('textAt['+i+']');
var l = ob.value.length;
if (l) {
ob.size = l;
ob.cols = l;
}
}
// Translate using google API on double click
function dblclk(obj) {
// translate(obj);
var selection = new Selection(obj);
var s = selection.create();
if (s.end) {
var ln = s.end - s.start;
var word = obj.value.substr(s.start, ln);
translate(obj, word, s.start, s.end);
}
}
// Right To Left and Left To Right
function rtl(button) {
if (button.value == 'RTL') {
button.value = 'LTR';
document.getElementById('editbox').dir = 'rtl';
} else {
button.value = 'RTL';
document.getElementById('editbox').dir = 'ltr';
}
}
// Prevent Losing changes
function uconfirm() {
if (updated) {
return confirm('This will cancel any unsaved updates, are you sure?');
}
return true;
}
// Show hidden frame
function showhframe() {
document.getElementById('hframe').style.display = '';
}
//------------- The following are required for Google translation
// Cross Browser selectionStart/selectionEnd
// Version 0.2
// Copyright (c) 2005-2007 <NAME>
//
// This script is distributed under the MIT licence.
// http://www.opensource.org/licenses/mit-license.php
function Selection(textareaElement) {
this.element = textareaElement;
}
Selection.prototype.create = function() {
if (document.selection != null && this.element.selectionStart == null) {
return this._ieGetSelection();
} else {
return this._mozillaGetSelection();
}
}
Selection.prototype._mozillaGetSelection = function() {
return {
start: this.element.selectionStart,
end: this.element.selectionEnd
};
}
Selection.prototype._ieGetSelection = function() {
this.element.focus();
var range = document.selection.createRange();
var bookmark = range.getBookmark();
var contents = this.element.value;
var originalContents = contents;
var marker = this._createSelectionMarker();
while(contents.indexOf(marker) != -1) {
marker = this._createSelectionMarker();
}
var parent = range.parentElement();
if (parent == null ) {
return { start: 0, end: 0 };
}
range.text = marker + range.text + marker;
contents = this.element.value;
var result = {};
result.start = contents.indexOf(marker);
contents = contents.replace(marker, "");
result.end = contents.indexOf(marker);
this.element.value = originalContents;
range.moveToBookmark(bookmark);
range.select();
return result;
}
Selection.prototype._createSelectionMarker = function() {
return "##SELECTION_MARKER_" + Math.random() + "##";
}
//------------
</script>
<script type="text/javascript" src="http://www.google.com/jsapi"></script><script type="text/javascript">
//-- Google Translation API
google.load("language", "1");
var transTarget = new Array();
function translate(obj, word, s, e) {
if (!word) return;
if (obj.name!='xmldata') {
obj.style.backgroundColor = '#22EE99';
}
transTarget[0] = obj;
transTarget[1] = word;
transTarget[2] = s;
transTarget[3] = e;
google.language.translate(word, "en", "<?php print $phpdocLangs[$lang]['id']; ?>", function(result) { if (!result.error) {
//var container = document.getElementById("translation");
var w = transTarget[0].value;
var w1 = '';
if (transTarget[2]) {
w1 = w.substr(0, transTarget[2]);
}
var w2 = w.substr(transTarget[2]+word.length);
if (word.substr(word.length-1)==' ') w2 = ' '+w2;
if (word.substr(0, 1)==' ') w1 = w1 + ' ';
transTarget[0].value = w1+result.translation+w2;
var l = transTarget[0].value.length;
if (l) {
transTarget[0].size = l;
transTarget[0].cols = l;
}
updated = true;
}});
}
</script>
File: <b><?php print $requestedFilename; ?></b><br>
Source: <b><font color=white><?php
if ($source=='upath') print "User cached version";
if ($source=='apath') print "$lang Translated version";
if ($source=='epath') print "English version";
?></font></b><br>
<?php
if (!empty($requireLogin)) {
print "Logged as: <b>$user[email]</b> <a href='login.php?and=logout' target=_top>logout</a><br>";
}
$url = "editxml.php?file=$requestedFilename&source=$source";
$hideXML = empty($_SESSION['hidexml']) ? '' : 'checked';
$splitFrames= empty($_SESSION['split']) ? '' : 'checked';
$textEdit = empty($_SESSION['textedit'])? '' : 'checked';
$lineByLine = empty($_SESSION['para']) ? '' : 'checked';
?>
<input type=checkbox name=hidexml value=1 <?php print $hideXML; ?> onClick="if (uconfirm()) document.location='<?php print $url; ?>&noframes=1&hidexml='+this.checked;" <?php if ($source=='diff') print 'disabled'; ?> /> Hide XML Tags
<input type=checkbox name=split value=1 <?php print $splitFrames; ?> onClick="if (uconfirm()) top.frames['fileframe'].location='<?php print $url; ?>&split='+this.checked;"> Split frames
<input type=checkbox name=textedit value=1 <?php print $textEdit; ?> onClick="if (uconfirm()) document.location='<?php print $url; ?>&noframes=1&textedit='+this.checked;" <?php if ($source=='diff') print 'disabled'; ?> /> XML Text Editor
<input type=checkbox name=linebyline value=1 <?php print $lineByLine; ?> onClick="if (uconfirm()) document.location = '<?php print $url; ?>&noframes=1&par='+this.checked;" <?php if ($source=='diff') print 'disabled'; ?> /> Line by Line (no textarea)
<form action=editxml.php method=post target=hframe onsubmit="showhframe();">
<?php
$bs[0] = array('bcolor'=>'#CCCCCC', 'caption'=>'Latest English', 'link'=>"editxml.php?file=$requestedFilename&source=epath&noframes=1", 'tag'=>'epath', 'title'=>$status['lastEnRevision']);
$bs[1] = array('bcolor'=>'#CCCCCC', 'caption'=>$lang.' version', 'link'=>"editxml.php?file=$requestedFilename&source=apath&noframes=1", 'tag'=>'apath', 'title'=>$status['fileEnRevision']);
if ($requireLogin) {
$bs[] = array('bcolor'=>'#CCCCCC', 'caption'=>'Cached version', 'link'=>"editxml.php?file=$requestedFilename&source=upath&noframes=1", 'tag'=>'upath');
}
if ($status['distance']>0) {
$bs[] = array('bcolor'=>'#CCCCCC', 'caption'=>'Diff log '.$status['fileEnRevision'].' / '.$status['lastEnRevision'], 'link'=>"editxml.php?file=$requestedFilename&source=diff&noframes=1", 'tag'=>'diff');
}
foreach($bs as $i=>$b) {
if ($b['tag']==$source) $b['bcolor'] = '#FFFFFF';
print "<span style='background-color: $b[bcolor]; border: 1px solid black; border-bottom: 0px none white;'><a href='$b[link]' onclick='return uconfirm();' title='$b[title]'>$b[caption]</a>";
print '</span>';
if (($i+1)<count($bs)) print '|';
}
$direction = "LTR";
$directionx = "RTL";
if ($phpdocLangs[$lang]['direction']=='RTL' && ($source=='upath' || $source=='apath')) {
$direction = "RTL";
$directionx = "LTR";
}
if (empty($_SESSION['textedit']) || $source=='diff') {
?>
<div id=editbox dir=<?php print $direction; ?> class="editbox<?php if ($source=='diff') print '-diff'; ?>">
<center><img id=loading src=images/loading.gif align=absmiddle></center>
<pre><?php print $data; ?></pre>
</div>
<?php
} else {
// Edit XML as Text
?>
<center><img id=loading src=images/loading.gif align=absmiddle><div>
<textarea name=xmldata id=editbox ondblclick="dblclk(this);" dir=<?php print $direction; ?> style="font-family: Fixedsys; background-color: white; width: 100%; height: 400px;"><?php print $data; ?></textarea></div>
</center>
<?php
}
if ($source!='diff') {
?>
<input name=noframes type=hidden value=1>
<input name=source type=hidden value="<?php print $source; ?>">
<input name=file type=hidden value="<?php print $requestedFilename; ?>">
<input type=button value=<?php print $directionx;?> onclick="rtl(this);">
<?php
if ($requireLogin) print '<input name=save type=submit value="Save in cache">';
?>
<input name=download type=submit value=Download>
</form>
<!-- This frame is used to prevent losing changes if session has expired.. so login can be done inside -->
<iframe id=hframe name=hframe width=100% height=100 border=0 style="display: none"></iframe>
<ul>
<li>After translating the file, please download (and save) it then either:
<ul>
<li>Commit to CVS</li>
<li>Or send it to the <?php print $phpdocLangs[$lang]['mailing']; ?> mailing list</li>
</ul>
</li>
<li>If you have questions, contact the main discussion list (<EMAIL>) or
write <?php print $phpdocLangs[$lang]['mailing']; ?> for translation specific concerns.
</li>
<li>In the future there will be a patch queue.</li>
</ul>
<?php
}
?>
<script language=javascript>
document.getElementById('loading').style.display = 'none';
</script>
</body>
</html>
<file_sep>/branches/gtk-docgen/scripts/checkdoc.php
#!/usr/bin/php -q
<?php
/*
+----------------------------------------------------------------------+
| PHP Version 4 |
+----------------------------------------------------------------------+
| Copyright (c) 1997-2010 The PHP Group |
+----------------------------------------------------------------------+
| This source file is subject to version 3.0 of the PHP license, |
| that is bundled with this package in the file LICENSE, and is |
| available through the world-wide-web at the following url: |
| http://www.php.net/license/3_0.txt. |
| If you did not receive a copy of the PHP license and are unable to |
| obtain it through the world-wide-web, please send a note to |
| <EMAIL> so we can mail you a copy immediately. |
+----------------------------------------------------------------------+
| Authors: <NAME> <<EMAIL>> (originally in Perl) |
| <NAME> <<EMAIL>> |
+----------------------------------------------------------------------+
*/
if ($argc > 2 || in_array($argv[1], array('--help', '-help', '-h', '-?'))) {
?>
Check documented functions in phpdoc
Usage:
<?php echo $argv[0];?> [missing]
By providing the optional "missing" parameter,
only a list of undocumented functions is listed,
otherwise a full status report is printed.
This program depends on ../funclist.txt as the
list of functions compiled from the PHP source.
<?php
exit;
}
// CONFIG SECTION
$docdir = "../en/functions";
$funclist = "../funclist.txt";
/*********************************************************************/
/* Nothing to modify below this line */
/*********************************************************************/
// Documented functions list
$func_documented = array();
// Functions in PHP (from funclist.txt)
$func_in_php = array();
// Longest function name for display
$longest = 0;
/*********************************************************************/
/* Here starts the functions part */
/*********************************************************************/
// Checks a diretory of phpdoc XML files
function check_dir($dir, &$functions)
{
// Collect files and diretcories in these arrays
$directories = array();
$files = array();
// Open and traverse the directory
$handle = @opendir($dir);
while ($file = @readdir($handle)) {
// Collect XML files
if (strstr($file, ".xml")) {
$files[] = $file;
}
}
@closedir($handle);
// Sort and check files
sort($files);
foreach ($files as $file) {
check_file($dir, $file, $functions);
}
} // check_dir() function end
function check_file ($dirname, $filename, &$functions)
{
// Read in file contents
$contents = preg_replace("/[\r\n]/", "", join("", file($dirname.$filename)));
// Find all functions defined in this file
preg_match_all("!id\s*=\s*([\"'])(function|class)\.([^\\1]+)\\1!U", $contents, $ids_found);
// No ids found in file
if (count($ids_found[3]) == 0) { return; }
// Put functions into function list
foreach ($ids_found[3] as $id) {
$functions[str_replace("-", "_", $id)] = $filename;
}
ksort($functions);
} // check_file() function end
// Parse funclist.txt file for function names
function parse_funclist($funclist, &$longest, &$functions)
{
// Read in file, initialize longest
$file_lines = file($funclist);
// Go through all lines, and find function names
foreach ($file_lines as $line) {
$line = trim($line);
$length = strlen($line);
// Not a comment, and contains a function name
if ($line[0] != "#" && $length > 0) {
$functions[] = $line;
if ($length > $longest) { $longest = $length; }
}
}
sort($functions);
$functions = array_unique($functions);
} // parse_funclist() function end
/*********************************************************************/
/* Here starts the program */
/*********************************************************************/
// Start with searching header
echo "Searching in $docdir for XML files...\n";
// Check the requested directory
check_dir("$docdir/", $func_documented);
// Process $funclist for PHP functions
parse_funclist($funclist, $longest, $func_in_php);
if ($argv[1] == "missing") {
$undocumented = array_diff($func_in_php, array_keys($func_documented));
echo "Functions in PHP source but not in documentation:\n\n";
foreach ($undocumented as $func) {
echo $func . "\n";
}
} else {
printf("%-{$longest}s %s\n", "FUNCTION NAME", "DOCUMENTED IN");
printf("%'-70s\n", '');
foreach ($func_in_php as $function) {
printf("%-{$longest}s %s\n", $function, $func_documented[$function]);
}
$n_functions = count($func_in_php);
$n_documented = count($func_documented);
$percent_done = intval(($n_documented * 100) / $n_functions);
printf("\n%d of %d functions documented (%d%% done, %d%% remaining).\n",
$n_documented, $n_functions, $percent_done, 100-$percent_done);
}
echo "Possible documentation errors coming:\n\n";
$is_error = FALSE;
foreach ($func_documented as $func => $file) {
if (!in_array($func, $func_in_php)) {
echo " $func in $file but not in $funclist\n";
$is_error = TRUE;
}
}
if (!$is_error) { echo "No documented but not implemented functions found.\n"; }
echo "Done!";
?>
<file_sep>/tags/POST_DOCBOOK5/scripts/iniupdate/generate_changelog.php
<?php
/*
+----------------------------------------------------------------------+
| ini doc settings updater |
+----------------------------------------------------------------------+
| Copyright (c) 1997-2005 The PHP Group |
+----------------------------------------------------------------------+
| This source file is subject to version 3.0 of the PHP license, |
| that is bundled with this package in the file LICENSE, and is |
| available through the world-wide-web at the following url: |
| http://www.php.net/license/3_0.txt. |
| If you did not receive a copy of the PHP license and are unable to |
| obtain it through the world-wide-web, please send a note to |
| <EMAIL> so we can mail you a copy immediately. |
+----------------------------------------------------------------------+
| Authors: <NAME> <<EMAIL>> |
+----------------------------------------------------------------------+
*/
require_once './cvs-versions.php';
/** converts a tag like php_5_0_0 into a version like 5.0.0 */
function tag2version($tag) {
global $cvs_versions;
if (isset($cvs_versions[$tag]))
return $cvs_versions[$tag];
return strtr(substr($tag, 4), '_', '.');
}
/** checks if an ini setting has changed its value in PHP 5 */
function check_php4($array) {
foreach($array as $key => $val) {
if (substr($key, 0, 5) != 'php_4') {
continue;
}
if ($val) {
if (isset($old)) {
if ($val != $old) {
return '';
}
} else {
$old = $val;
}
}
}
if (isset($old) && $old != $array['php_5_0_0'] && $array['php_5_0_0']) {
return "$old in PHP 4.";
}
}
/** return when the option become available */
function available_since($array) {
if ($array['php_4_0_0']) {
return '';
}
foreach($array as $key => $val) {
if ($val) {
return 'Available since PHP ' . tag2version($key) . '.';
}
}
}
/** check for changes between versions */
function last_version($array) {
$php4 = check_php4($array);
$str = '';
foreach($array as $key => $val) {
if ($php4 && substr($key, 0, 5) == 'php_4') {
continue;
}
if ($val) {
if (isset($old)) {
if ($val != $old) {
if ($old_tag == 'php_4_cvs') {
$str .= " $old in PHP < 5.";
} else {
$str .= " $old in PHP <= " . tag2version($old_tag) . '.';
}
}
}
$old = $val;
$old_tag = $key;
}
}
return $php4 . $str;
}
/** generate the changelog column */
function generate_changelog($array) {
array_shift($array);
return trim(last_version($array) . ' ' . available_since($array));
}
if (!$idx = sqlite_open('ini_changelog.sqlite', 0666, $error)) {
die("Couldn't open the DB: $error");
}
$q = sqlite_unbuffered_query($idx, 'SELECT * FROM changelog');
/* This hack is needed because sqlite 2 sort case-sensitive */
while($row = sqlite_fetch_array($q, SQLITE_ASSOC)) {
uksort($row, 'strnatcmp');
$info[$row['name']] = $row;
}
uksort($info, 'strnatcasecmp');
foreach ($info as $row) {
$changelog[$row['name']] = generate_changelog($row);
}
if (!isset($included)) {
foreach ($changelog as $key => $val) {
echo "$key : $val\n";
}
}
sqlite_close($idx);
?>
<file_sep>/tags/PRE_EXCEPTIONS_ROLE_CHANGE/scripts/gen-phpdoc-tz-list.php
<?php
$groupedList = array();
$aliasList = array(
'Brazil' => 'America',
'Canada' => 'America',
'Chile' => 'America',
'Etc' => 'Others',
'Mexico' => 'America',
'US' => 'America',
'Indian' => 'Asia',
);
$list = timezone_identifiers_list();
foreach ($list as $element) {
if (preg_match('@^([^/]*)/(.*)@', $element, $m)) {
$group = $m[1];
} else {
$group = 'Others';
}
if (isset($aliasList[$group])) {
$group = $aliasList[$group];
}
$groupedList[$group][] = $element;
}
ksort($groupedList);
$others = $groupedList['Others'];
unset($groupedList['Others']);
$groupedList['Others'] = $others;
?>
<?xml version="1.0" encoding="iso-8859-1"?>
<!-- $Revision$ -->
<!-- AUTO GENERATED, DO NOT MODIFY BY HAND -->
<appendix id="timezones">
<title>List of Supported Timezones</title>
<para>
</para>
<?php foreach ($groupedList as $group => $zones) { ?>
<sect1 id="timezones.<?php echo strtolower($group); ?>">
<title>List of timezones in the group <?php echo $group; ?></title>
<table>
<title><?php echo $group; ?></title>
<tgroup cols="5">
<tbody>
<?php
$c = 0;
foreach($zones as $zone) {
if ($c % 5 == 0) {
echo " <row>\n";
}
$c++;
echo " <entry>{$zone}</entry>\n";
if ($c % 5 == 0) {
echo " </row>\n";
}
}
if ($c % 5 != 0) {
echo " </row>\n";
}
?>
</tbody>
</tgroup>
</table>
<note>
<simpara>
The latest version of the timezone database can be installed via PECL's
<ulink url="&url.pecl.package.get;timezonedb">timezonedb</ulink>.
For Windows users, a pre-compiled DLL can be downloaded from the PECL4Win
site: <ulink url="&url.pecl.timezonedb.dll;">php_timezonedb.dll</ulink>.
</simpara>
</note>
</sect1>
<?php } ?>
</appendix>
<!-- Keep this comment at the end of the file
Local variables:
mode: sgml
sgml-omittag:t
sgml-shorttag:t
sgml-minimize-attributes:nil
sgml-always-quote-attributes:t
sgml-indent-step:1
sgml-indent-data:t
indent-tabs-mode:nil
sgml-parent-document:nil
sgml-default-dtd-file:"../../manual.ced"
sgml-exposed-tags:nil
sgml-local-catalogs:nil
sgml-local-ecat-files:nil
End:
vim600: syn=xml fen fdm=syntax fdl=2 si
vim: et tw=78 syn=php
vi: ts=4 sw=1
-->
<file_sep>/branches/dev_docbook4/scripts/revcheck.php
#!/usr/bin/php -q
<?php
if ($argc < 2 || $argc > 3) {
?>
Check the revision of translated files against
the actual english xml files, and print statistics
Usage:
<?=$argv[0]?> <language-code> [<maintainer>]
<language-code> must be a valid language code used
in the repository
If you specify <maintainer>, the script only checks
the files maintaned by the person you add here
The script will generate a revcheck.html file in
the same dir, where the script runs, containing the
information about translations
Revision comment syntax for translated files:
<!-- EN-Revision: 1.34 Maintainer: tom Status: ready -->
If the revision number is not (yet) known:
<!-- EN-Revision: n/a Maintainer: tom Status: working -->
Written by <NAME> <<EMAIL>>, 2001-08-11
Adapted to phpdoc, developed further: <<EMAIL>>
<?php
exit;
}
// CONFIG SECTION
$docdir = "../"; // Main directory of the PHP documentation (one dir up in cvs)
// Warn with red color if
$r_alert = 10; // the translation is $r_alert or more revisions behind the en one
$s_alert = 10; // the translation is $s_alert or more kB smaller than the en one
$t_alert = 30; // the translation is $t_alert or more days older than the en one
// Option for the link to the cvs.php.net: normal: "&f=h"
// long diff: "&f=h&num=10", unified (text): "&f=u"
$cvs_opt = "&f=h&num=10";
/*********************************************************************/
/* Nothing to modify below this line */
/*********************************************************************/
// Long runtime
set_time_limit(0);
// Initializing arrays and vars
$miss_file = array();
$miss_tag = array();
$t_alert = -1 * $t_alert;
$lang = $argv[1];
if ($argc == 3) { $maintainer = $argv[2]; }
else { $maintainer = ""; }
/*********************************************************************/
/* Here starts the functions part */
/*********************************************************************/
// Grabs the revision tag from the file given
function get_tag($file, $val = "en-rev")
{
// Read the first 200 chars, the comment should be at
// the begining of the file
$fp = @fopen($file, "r") or die ("Unable to read $file.");
$line = fread($fp, 200);
fclose($fp);
// Checking for english CVS revision tag
if ($val=="en-rev") {
preg_match("/<!-- .Revision: \d+\.(\d+) . -->/", $line, $match);
return ($match[1]);
}
// Checking for the translations "revision tag"
else {
preg_match ("/<!--\s*EN-Revision:\s*\d+\.(\d+)\s*Maintainer:\s*(".$val.
")\s*Status:\s*(.+)\s*-->/", $line, $match);
}
// The tag with revision number is not found so search
// for n/a revision comment
if (count($match) == 0) {
preg_match ("'<!--\s*EN-Revision:\s*(n/a)\s*Maintainer:\s*(".$val.
")\s*Status:\s*(.+)\s*-->'", $line, $match);
}
return ($match);
} // get_tag() function end
// Checks a file, and gather stats
function check_file($file, $file_cnt)
{
// The information is contained in these global arrays and vars
global $miss_file, $miss_tag, $lang, $docdir, $r_alert,
$s_alert, $t_alert, $maintainer, $cvs_opt;
// Translated file name check
$t_file = preg_replace( "'^".$docdir."en/'", $docdir.$lang."/", $file );
if (!file_exists($t_file)) {
$miss_file[] = array(substr($t_file, strlen($docdir)+strlen($lang)),
round(filesize($file)/1024, 1));
return FALSE;
}
// Get translated files tag, with maintainer if needed
if (empty($maintainer))
$t_tag = get_tag($t_file, "\\S*");
else
$t_tag = get_tag($t_file, $maintainer);
// No tag found
if (count($t_tag) == 0) {
$miss_tag[] = substr($t_file, strlen($docdir));
return FALSE;
}
// Storing values for further processing
$maint = $t_tag[2];
$en_rev = get_tag($file);
// Make diff link if the revision is not n/a
$t_td = substr($t_file, strlen($docdir)+strlen($lang)+1);
if (is_numeric($t_tag[1])) {
$r_diff = intval($en_rev) - intval($t_tag[1]);
$t_rev = "1.".$t_tag[1];
if ($r_diff != 0) {
$t_td = "<a href=\"http://cvs.php.net/diff.php/".
preg_replace( "'^".$docdir."'", "phpdoc/", $file ).
"?r1=1.$t_tag[1]&r2=1.$en_rev$cvs_opt\">$t_td</a>";
}
} else {
$r_diff = $t_rev = $t_tag[1];
}
// Compute sizes, times and diffs
$en_size = intval(filesize($file) / 1024);
$t_size = intval(filesize($t_file) / 1024);
$s_diff = intval($en_size) - intval($t_size);
$en_date = intval((time() - filemtime($file)) / 86400);
$t_date = intval((time() - filemtime($t_file)) / 86400);
$t_diff = $en_date - $t_date;
// Taging actuality of files with colors
if ($r_diff === 0) {
$col = "#68D888";
} elseif ($r_diff == "n/a") {
$col = "#f4a460 class=hl";
} elseif ($r_diff >= $r_alert || $s_diff >= $s_alert || $t_diff <= $t_alert) {
$col = "#ff0000 class=hl";
} else {
$col ="#eee8aa";
}
// Write out directory headline
if ($file_cnt == 0) {
$display_dir = preg_replace("'($docdir)(.+)/[^/]*$'", "\\2/", $t_file);
print("<tr><th colspan=12 height=3 bgcolor=#666699>$display_dir</th></tr>");
}
// Write out the line for the file into the file
print("<tr>\n <td bgcolor=$col>$t_td</td>\n".
" <td bgcolor=$col> 1.$en_rev</td><td bgcolor=$col> $t_rev</td>\n".
" <td bgcolor=$col align=right><b>$r_diff</b> </td>\n".
" <td bgcolor=$col align=right>$en_size </td>\n".
" <td bgcolor=$col align=right>$t_size </td>\n".
" <td bgcolor=$col align=right><b>$s_diff</b> </td>\n".
" <td bgcolor=$col align=right>$en_date </td>\n".
" <td bgcolor=$col align=right>$t_date </td>\n".
" <td bgcolor=$col align=right><b>$t_diff</b> </td>\n".
" <td bgcolor=$col align=center>$maint</td>\n".
" <td bgcolor=$col align=center>$t_tag[3]</td>\n</tr>\n");
return TRUE;
} // check_file() end
// Checks a diretory of phpdoc XML files
function check_dir($dir)
{
global $docdir, $lang;
// Collect files and diretcories in these arrays
$directories = array();
$files = array();
// Open and traverse the directory
$handle = @opendir($dir);
while ($file = @readdir($handle)) {
if (preg_match("/^\.{1,2}/",$file) || $file == 'CVS')
continue;
// Collect files and directories
if (is_dir($dir.$file)) { $directories[] = $file; }
else { $files[] = $file; }
}
@closedir($handle);
// Sort files and directories
sort($directories);
sort($files);
// Files first...
$file_cnt = 0;
foreach ($files as $file) {
if (check_file($dir.$file, $file_cnt)) { $file_cnt++; }
}
// than the subdirs
foreach ($directories as $file) {
check_dir($dir.$file."/");
}
} // check_dir() end
/*********************************************************************/
/* Here starts the program */
/*********************************************************************/
// Check for directory validity
if (!@is_dir($docdir . $lang)) {
die("The $lang language code is not valid");
}
print("<html>
<head>
<title>PHPDOC Revision-check</title>
<meta http-equiv=\"Content-Type\" content=\"text/html; charset=iso-8859-1\">
<style type=\"text/css\"><!--
h2 {font-family: arial,helvetica,sans-serif; color: #FFFFFF; font-size:28px; }
td,a,p {font-family:arial,helvetica,sans-serif; color:#000000; font-size:14px; }
th {font-family:arial,helvetica,sans-serif; color:#FFFFFF; font-size:14px; font-weight:bold; }
.hl {font-family:arial,helvetica,sans-serif; color:#000000; font-size:14px; font-weight:bold; }
//-->
</style>
</head>
<body leftmargin=0 topmargin=0 marginwidth=0 marginheight=0 bgcolor=#F0F0F0>
<table width=100% border=0 cellspacing=0 bgcolor=#666699>
<tr><td>
<table width=100% border=0 cellspacing=1 bgcolor=#9999CC>
<tr><td><h2 align=center>Status of the translated PHP Manual</h2>
<p align=center style=\"font-size:12px; color:#FFFFFF;\">Generated: ".date("Y-m-d, H:i:s").
" / Language: $lang<br> </p>
</td></tr>
</table>
</td></tr>
</table> <br>
<table width=750 border=0 cellpadding=4 cellspacing=1 align=center>
<tr>
<th rowspan=2 bgcolor=#666699>Translated file</th>
<th colspan=3 bgcolor=#666699>Revision</th>
<th colspan=3 bgcolor=#666699>Size in kB</th>
<th colspan=3 bgcolor=#666699>Age in days</th>
<th rowspan=2 bgcolor=#666699>Maintainer</th>
<th rowspan=2 bgcolor=#666699>Status</th>
</tr>
<tr>
<th bgcolor=#666699>en</th>
<th bgcolor=#666699>$lang</th>
<th bgcolor=#666699>diff</th>
<th bgcolor=#666699>en</th>
<th bgcolor=#666699>$lang</th>
<th bgcolor=#666699>diff</th>
<th bgcolor=#666699>en</th>
<th bgcolor=#666699>$lang</th>
<th bgcolor=#666699>diff</th>
</tr>
");
// Check the English directory
check_dir($docdir."en/");
print("</table>\n<p> </p>\n");
// Files without revision comment
if (count($miss_tag) > 0) {
print("<table width=350 border=0 cellpadding=3 cellspacing=1 align=center>\n".
" <tr><th bgcolor=#666699><b>Files without Revision-comment:</b></th></tr>\n");
foreach($miss_tag as $val) {
print(" <tr><td bgcolor=#DDDDDD> $val</td></tr>\n");
}
print("</table>\n<p> </p>\n");
}
// Files not translated
if (count($miss_file) > 0) {
print("<table width=350 border=0 cellpadding=3 cellspacing=1 align=center>\n".
" <tr><th colspan=2 bgcolor=#666699><b>Untranslated Files:</b></th></tr>\n");
foreach($miss_file as $v) {
print(" <tr><td bgcolor=#DDDDDD> en$v[0]</td>".
"<td align=right bgcolor=#DDDDDD>$v[1] kB </td></tr>\n");
}
print("</table>\n<p> </p>\n");
}
// All OK, end the file
print("</body>\n</html>\n");
echo "Done!\n";
?>
<file_sep>/branches/gtk-docgen/scripts/online_editor/cvslist.php
<?php
/*
+----------------------------------------------------------------------+
| PHP Version 4 |
+----------------------------------------------------------------------+
| Copyright (c) 1997-2010 The PHP Group |
+----------------------------------------------------------------------+
| This source file is subject to version 3.0 of the PHP license, |
| that is bundled with this package in the file LICENSE, and is |
| available through the world-wide-web at the following url: |
| http://www.php.net/license/3_0.txt. |
| If you did not receive a copy of the PHP license and are unable to |
| obtain it through the world-wide-web, please send a note to |
| <EMAIL> so we can mail you a copy immediately. |
+----------------------------------------------------------------------+
| Authors : <NAME> <<EMAIL>> |
+----------------------------------------------------------------------+
$Id$
*/
//-- The PHPDOC Online XML Editing Tool
//--- Purpose: lists the folders and files in the left frame
//------- Initialization
require 'base.php';
$user = sessionCheck();
$lang = $user['phpdocLang'];
$translationPath = $phpdocLangs[$lang]['DocCVSPath'];
//------- Folder navigation vars
$path = '';
$file = '';
if (isset($_REQUEST['path'])) {
$path = $_REQUEST['path'];
if (isset($_REQUEST['file'])) {
$file = $_REQUEST['file'];
}
}
// Prevent wrong paths
if (strstr($path, '.') || $file=='..' || $file=='.') {
exit;
}
// Path Slashes
if (!$path) $path = '/';
if (substr($path, -1)!='/') $path .= '/';
// Usually, the path are based on english cvs
$target = CVS_ROOT_PATH . 'en/' . $path . $file;
//------- Decide what to do
// If file is selected, redirect to the editor..
if ($file) {
// Find in user path first (editing cached file by default)
$ffile = $user['cache'].getCacheName($path.$file);
if (file_exists($ffile)) {
header("location: editxml.php?file=$path$file&source=upath");
exit;
}
// Find in translated path (edit the translated file)
$ffile = "$translationPath$path$file";
if (file_exists($ffile)) {
header("location: editxml.php?file=$path$file&source=apath");
exit;
}
// So it's a new file? Use the english source
if (file_exists($target)) {
header("location: editxml.php?file=$path$file&source=epath");
exit;
}
} else {
// No file selected, Listing (from english cvs)
$d = opendir($target);
while($f = readdir($d)) {
if (is_dir($target.$f)) {
if (in_array($f, $ignoreListingFolders)) continue;
$dirs[] = $f;
} elseif ((substr($f, -4)=='.xml' || substr($f, -4)=='.ent') && !in_array($f, $ignoreListingFiles)) {
$files[] = $f;
}
}
}
//------- Functions
function printPathAsLinks($path) {
global $lang;
$px = explode('/', $path);
$pp = '';
foreach($px as $i=>$p) {
$pp .= $p.'/';
if (!$p && !$i) $p = $lang;
print "<a href='?path=$pp'>$p</a>";
if ($p || !$i) print '/';
}
print '<br>';
}
function printDirectories($dirs, $path) {
sort($dirs);
foreach($dirs as $dir) {
print "<a href='?path=$path$dir'><img src='images/dir.png' width=16 height=16 border=0 align=absmiddle> $dir</a> <br>";
}
}
function printFiles($files, $path) {
global $translationPath, $user;
sort($files);
foreach($files as $fl) {
$status = getTranslationStatus($path.$fl);
if ($status['translated']) {
if ($status['fileEnRevision'] && $status['lastEnRevision'] && $status['distance']>=0) {
if (!$status['backward']) {
$title = 'Up to date';
$img = 'images/up2date.png';
} else {
$title = 'Outdated '.$status['fileEnRevision'].' / '.$status['lastEnRevision'];
$img = 'images/r'.($status['backward']+1).'.png';
}
} else {
$title = 'EN-Revision is incorrect or missing';
$img = 'images/unknown.png';
}
} else {
$title = 'Not translated yet';
$img = 'images/notyet.png';
}
print "<a href='?path=$path&file=$fl' target=fileframe><img src='images/text.png' width=16 height=16 border=0 align=absmiddle> $fl</a> <img src='$img' border=0 align=absmiddle alt='$title'><br>";
}
// Lists the user's cached files
if (file_exists($user['cache']."files.txt")) {
print '<hr>';
print 'Cached files:<br>';
$ff = file($user['cache']."files.txt");
foreach($ff as $f) {
$fx = explode('|', $f);
if (!isset($cf[$fx[2]])) {
print "<a href='editxml.php?file=$fx[2]&source=upath' target=fileframe>$fx[2]</a><br>";
$cf[$fx[2]] = true;
}
}
}
}
//------- Output
?>
<html>
<body bgcolor="#FFFFFF">
<style type="text/css">
body {
font-family: Tahoma;
font-size: 12px;
}
a:link {
text-decoration: none;
color: #000066;
}
a:hover {
text-decoration: none;
color: #ff0000;
}
a:active {
text-decoration: none;
color: #ff0000;
}
a:visited {
text-decoration: none;
color: #000066;
}
</style>
<div style="width: 400px;">
Listing:
<?php
printPathAsLinks($path);
printDirectories($dirs, $path);
printFiles($files, $path);
?>
<hr>
<form action=login.php method=post target=_top>
<?php
if ($requireLogin) { ?>
<input type=hidden name=email value="<?php print $user['email']; ?>"><br>
<?php } ?>
Switch language:<br>
<select name=lang onchange="if (this.value) this.form.submit();">
<option value=''></option>
<?php
foreach($phpdocLangs as $lng=>$langInfo) {
if ($lng==$lang) $sel = " selected"; else $sel = '';
print "<option value='$lng'$sel>$lng</option>";
}
?>
</select>
</form>
<hr>
Legend:<br>
<img src=images/notyet.png> Not yet translated<br>
<img src=images/up2date.png> File is translated and up to date<br>
<img src=images/unknown.png> EN-Revision is incorrect or missing<br>
<img src=images/r6.png> How much is outdated-<br> gauge (hover it for revision).
</div>
</body>
</html>
<file_sep>/tags/POST_EXCEPTIONS_ROLE_CHANGE/Makefile.in
# +----------------------------------------------------------------------+
# | PHP Version 4 |
# +----------------------------------------------------------------------+
# | Copyright (c) 1997-2006 The PHP Group |
# +----------------------------------------------------------------------+
# | This source file is subject to version 3.0 of the PHP license, |
# | that is bundled with this package in the file LICENSE, and is |
# | available through the world-wide-web at the following url: |
# | http://www.php.net/license/3_0.txt. |
# | If you did not receive a copy of the PHP license and are unable to |
# | obtain it through the world-wide-web, please send a note to |
# | <EMAIL> so we can mail you a copy immediately. |
# +----------------------------------------------------------------------+
# | Authors: <NAME> <<EMAIL>> |
# +----------------------------------------------------------------------+
#
#
# $Id$
#
all: html
# {{{ variables
VPATH=@srcdir@
srcdir=@srcdir@
scriptdir=@srcdir@/scripts
PHP_SOURCE=@PHP_SOURCE@
PECL_SOURCE=@PECL_SOURCE@
LANGCODE=@LANG@
LANGDIR=@LANGDIR@
LANG=@LANG@ -D .
JADE=@SP_OPTIONS@ @JADE@ -D . -wno-idref
NSGMLS=@SP_OPTIONS@ @NSGMLS@
PHP=@PHP@
XSLTPROC=@XSLTPROC@
XMLLINT=@XMLLINT@
CATALOG=@CATALOG@
HTML_STYLESHEET=dsssl/html.dsl
PHPWEB_STYLESHEET=dsssl/phpweb.dsl
HOWTO_STYLESHEET=dsssl/howto.dsl
HOWTOPHP_STYLESHEET=dsssl/howto-php.dsl
PRINT_STYLESHEET=dsssl/print.dsl
KDEVELOP_TOC_STYLESHEET=dsssl/kdevelop_toc.dsl
XMLDCL=$(srcdir)/dtds/dbxml-4.1.2/phpdocxml.dcl
CHM_XSL_SHEET=xsl/htmlhelp.xsl
HOWTO_XSL_SHEET=xsl/howto.xsl
QUICKREF_XSL_SHEET=xsl/quickref.xsl
XUL_XSL_SHEET=xsl/htmlhelp.xsl
BIGHTML_DEPS=$(HTML_STYLESHEET) dsssl/html-common.dsl dsssl/html-locale.dsl.in dsssl/common.dsl.in zendapi
HTML_DEPS=$(HTML_STYLESHEET) dsssl/html-common.dsl dsssl/html-locale.dsl.in dsssl/common.dsl.in zendapihtml
HOWTO_DEPS=$(HOWTO_STYLESHEET) $(HOWTOPHP_STYLESHEET) dsssl/html-common.dsl dsssl/html-locale.dsl.in dsssl/common.dsl.in howto/howto.ent
PRINT_DEPS=$(PRINT_STYLESHEET) dsssl/common.dsl.in dsssl/print.dsl.in zendapi
PHPWEB_DEPS=$(PHPWEB_STYLESHEET) dsssl/html-common.dsl dsssl/common.dsl zendapiphp
KDEVELOP_TOC_DEPS=dsssl/kdevelop_toc.dsl Makefile
DIST_FILES=@MANUAL@.tar.gz @MANUAL@.html.gz
MIRROR_TARGETS=php/index.php html/index.html $(DIST_FILES)
#MIRROR_TARGETS=phpweb_xsl html/index.html $(DIST_FILES)
PDF_FILES=@MANUAL@.pdf.bz2
HACK_RTL_LANGS_PAGES=@HACK_RTL_LANGS_PAGES@
HACK_RTL_LANGS_PHPWEB=@HACK_RTL_LANGS_PHPWEB@
# }}}
@AUTOGENERATED_RULES@
entities: FORCE
$(PHP) -c $(scriptdir) -q $(scriptdir)/entities.php
manual.xml: $(srcdir)/manual.xml.in .manual.xml
CONFIG_FILES=$@ CONFIG_HEADERS= ./config.status
.manual.xml: $(DEPEND_FILES) entities/global.ent
touch .manual.xml
zendapi:
cp $(srcdir)/en/internals/zendapi/figures/*.png .
zendapihtml:
rm -rf html && mkdir html && mkdir html/figures
cp $(srcdir)/en/internals/zendapi/figures/*.png ./html/figures
zendapixul:
rm -rf xul && mkdir xul
@if test "@FIGURES@" != ""; then mkdir xul/@FIGURES@ ; fi
@ZEND_FIGURES_HTML@
zendapiphp:
rm -rf php && mkdir php && mkdir php/figures
cp $(srcdir)/en/internals/zendapi/figures/*.png ./php/figures
zendapihtmlhelp:
rm -rf ./htmlhelp/html && mkdir ./htmlhelp/html && mkdir htmlhelp/html/figures
cp $(srcdir)/en/internals/zendapi/figures/*.png ./htmlhelp/html/figures
html: html/index.html
bightml: @MANUAL@.html
phpweb: php/index.php
rtf: @MANUAL@.rtf
tex latex: @MANUAL@.tex
dvi: @MANUAL@.dvi
ps: @MANUAL@.ps
pdf: @MANUAL@.pdf
howto: howto/html/index.html
howtophp: howto/php/index.php
howtotgz: howto/howto.html.tar.gz
funcindex: funcindex.xml
revcheck: revcheck.html
FORCE:
funclist.txt: FORCE
@if test "$(PHP_SOURCE)" = "no"; then \
echo "WARNING: recreating the function list needs php sources" ;\
echo " which were not found by configure" ;\
echo " aborting " ;\
else \
$(PHP) -C -q $(scriptdir)/genfunclist.php $(PHP_SOURCE) > funclist.txt ;\
fi; \
if test "$(PECL_SOURCE)" = "no" -a ! "$(PHP_SOURCE)" = "no"; then \
echo "WARNING: pecl sources not found - pecl functions" ;\
echo " will not be present in funclist.txt" ;\
elif test ! "$(PHP_SOURCE)" = "no"; then \
echo "" >> funclist.txt ;\
echo "# --------- PECL Stuff --------- " >> funclist.txt ;\
$(PHP) -C -q $(scriptdir)/genfunclist.php $(PECL_SOURCE) >> funclist.txt ;\
fi
funcsummary.txt: FORCE
$(PHP) -C -q $(scriptdir)/genfuncsummary.php $(PHP_SOURCE) > funcsummary.txt
revcheck.html: FORCE
PHPDOCDIR=$(srcdir) $(PHP) -c $(scriptdir) -f $(scriptdir)/revcheck.php $(LANGDIR) > revcheck.html
funcindex.xml: FORCE
@if test "$(PHP)" = "no"; then \
echo "WARNING: recreating the function index needs php" ;\
echo " which was not found by configure" ;\
echo " reusing old file" ;\
touch funcindex.xml ;\
else \
$(XSLTPROC) -o quickref-temp.txt $(QUICKREF_XSL_SHEET) manual.xml ;\
echo "$(PHP) -q $(scriptdir)/genfuncindex.php quickref-temp.txt > funcindex.xml" ;\
$(PHP) -q $(scriptdir)/genfuncindex.php quickref-temp.txt > funcindex.xml ;\
rm -f quickref-temp.txt ;\
fi
mirror-files: $(MIRROR_TARGETS)
#extra-mirror-files: $(PDF_FILES) isilo
extra-mirror-files: isilo
snapshot: manual-snapshot.tar.gz
manual-snapshot.tar.gz: @MANUAL@.html html/index.html @MANUAL@.rtf @MANUAL@.txt
tar -cvzf $@ @MANUAL@.html html/*.html @MANUAL@.rtf @MANUAL@.txt
status: ./funclist.txt
$(PHP) -q $(scriptdir)/checkdoc.php > status.txt
$(PHP) -q $(scriptdir)/checkdoc.php missing > missing.txt
summary: ./funcsummary.txt
quickref: quickref.txt
quickref.txt: FORCE
@if test ! -f funcindex.xml; then touch funcindex.xml; fi
$(XSLTPROC) -o quickref.txt $(QUICKREF_XSL_SHEET) manual.xml
kdevelop_toc: php.toc
php.toc: manual.xml $(KDEVELOP_TOC_DEPS)
echo '<!DOCTYPE gideontoc>' > $@
$(JADE) $(CATALOG) -d $(KDEVELOP_TOC_STYLESHEET) -V nochunks -t sgml $(XMLDCL) manual.xml | sed -e's/\& /\& /g' >> $@
scripts/makedoc: $(scriptdir)/makedoc.cc
mkdir -p scripts
g++ -o scripts/makedoc $(scriptdir)/makedoc.cc
# intermediate file for name change
.SECONDARY: @MANUAL@.xml
@MANUAL@.xml: manual.xml
cp manual.xml $@
@MANUAL@.html: @MANUAL@.xml $(BIGHTML_DEPS)
html/index.html: manual.xml $(HTML_DEPS)
$(PHP) -q $(scriptdir)/rtlpatch/hackmanuallang.php $(LANGDIR)
$(JADE) $(CATALOG) -d $(HTML_STYLESHEET) -V use-output-dir -t sgml $(XMLDCL) manual.xml
$(PHP) -q $(scriptdir)/html_syntax.php html html/
$(PHP) -q $(scriptdir)/rtlpatch/hackmanuallang.php en
$(HACK_RTL_LANGS_PAGES)
# still needs more tweaks!!
html_xsl: manual.xml zendapihtml
${XSLTPROC} xsl/html.xsl manual.xml
xul_xsl: manual.xml zendapixul
${XSLTPROC} xsl/xul.xsl manual.xml
bightml_xsl: manual.xml zendapi
${XSLTPROC} -o @MANUAL@.html xsl/bightml.xsl manual.xml
fo: manual.xml zendapi
${XSLTPROC} -o manual.fo xsl/fo.xsl manual.xml
howto_xsl:
rm -rf ./howto/html && mkdir ./howto/html
${XSLTPROC} $(HOWTO_XSL_SHEET) ./howto/howto.xml
chm_xsl: manual.xml zendapihtmlhelp
${XSLTPROC} $(CHM_XSL_SHEET) manual.xml
phpweb_xsl: manual.xml zendapiphp
${XSLTPROC} $(srcdir)/xsl/phpweb.xsl manual.xml
$(PHP) -q $(scriptdir)/fixphpweb.php `pwd`/php
php/index.php: manual.xml $(PHPWEB_DEPS)
$(PHP) -q $(scriptdir)/phpweb-entities.php `pwd` phpweb
$(PHP) -q $(scriptdir)/rtlpatch/hackmanuallang.php $(LANGDIR)
-$(JADE) $(CATALOG) -d $(PHPWEB_STYLESHEET) -V use-output-dir -t sgml $(XMLDCL) manual.xml
$(PHP) -q $(scriptdir)/html_syntax.php php php/
$(PHP) -q $(scriptdir)/rtlpatch/hackmanuallang.php en
$(PHP) -q $(scriptdir)/phpweb-entities.php `pwd` remove
$(HACK_RTL_LANGS_PHPWEB)
palmdoc: @MANUAL@.doc.pdb
@MANUAL@.doc.pdb: @MANUAL@.txt scripts/makedoc
scripts/makedoc -b @MANUAL@.txt @MANUAL@.doc.pdb @PALMDOCTITLE@
# Note: Isilo converter available only in binary from www.isilo.com
isilo: @MANUAL@.isilo.pdb
@MANUAL@.isilo.pdb: @MANUAL@.html
iSilo386 @MANUAL@.html @MANUAL@.isilo.pdb
@MANUAL@.zip: html/index.html
-rm -f $@ && (cd html; zip -R -9 -q ../$@ *.html *.png)
@MANUAL@.tar.gz: html/index.html
-rm -f $@ && (tar -cf - html) | gzip -9 > $@
@MANUAL@.tar.bz2: html/index.html
-rm -f $@ && (tar -cf - html) | bzip2 -9 > $@
howto/php/index.php: howto/howto.xml $(HOWTO_DEPS)
@test -d howto/php || mkdir howto/php
-$(JADE) -i lang-en $(CATALOG) -d $(HOWTOPHP_STYLESHEET) -V use-output-dir -t sgml $(XMLDCL) $(srcdir)/howto/howto.xml
howto/html/index.html: howto/howto.xml $(HOWTO_DEPS)
@test -d howto/html || mkdir howto/html
-$(JADE) -i lang-en $(CATALOG) -d $(HOWTO_STYLESHEET) -V use-output-dir -t sgml $(XMLDCL) $(srcdir)/howto/howto.xml
howto/howto.html.tar.gz: howto/html/index.html $(HOWTO_DEPS)
tar -cvzf $@ howto/html/*.html
install.html: install.xml $(HTML_DEPS)
$(JADE) $(CATALOG) -V nochunks -d dsssl/install.dsl -t sgml $(XMLDCL) install.xml > $@
chm: html FORCE
chm/make_chm.bat $(LANG)
# File endings we are going to define general rules for:
.SUFFIXES: .html .xml .sgml .tex .dvi .ps .pdf .rtf .gz .bz2 .txt
.PRECIOUS: %.html %.dvi
# General rules:
%.rtf: %.xml
$(JADE) $(CATALOG) -d $(PRINT_STYLESHEET) -t rtf $(XMLDCL) $<
%.gz: %
gzip -9 -c $< > $@
%.bz2: %
bzip2 -9 -c $< > $@
%.zip: %
zip -9 $@ $<
%.pdf: %.dvi
dvipdfm -o $@ -p @PDF_PAPER_TYPE@ $<
%.ps: %.dvi
dvips -o $@ -t @PDF_PAPER_TYPE@ $<
%.html: %.xml
$(JADE) $(CATALOG) -V nochunks -d $(HTML_STYLESHEET) -t sgml $(XMLDCL) $< > $@
%.txt: %.html
lynx -nolist -dump file:`pwd`/$< > $@
%.tex: %.xml
$(JADE) $(CATALOG) -d $(PRINT_STYLESHEET) -t tex $(XMLDCL) $<
# general TeX->dvi ru
# runs three times -
# 1. generates the dvi with a completely bogus table of contents
# 2. generates the dvi with a table of contents that is off based on the size
# of the table of contents
# 3. generates a dvi with all the right page numbers and such
%.dvi : %.tex
# a hack around bugs in jade/jadetex...
mv $< $<.tmp
sed -e '/HeadingText/,/endHeadPar/ s/_/\\137/g' $<.tmp > $<
rm $<.tmp
-jadetex $<
-jadetex $<
-jadetex $<
# {{{ tests
# test all possible errors
test: manual.xml
@if test ! -f funcindex.xml; then touch funcindex.xml; fi
@if test ! -f entities/missing-entities.ent; then touch entities/missing-entities.ent; fi
@if test ! -f entities/missing-ids.xml; then touch entities/missing-ids.xml; fi
$(NSGMLS) -i lang-$(LANG) -s $(XMLDCL) manual.xml
# ignore missing IDs and check if the manual can be generated anyway
test_man_gen: manual.xml
@if test ! -f funcindex.xml; then touch funcindex.xml; fi
@if test ! -f entities/missing-entities.ent; then touch entities/missing-entities.ent; fi
@if test ! -f entities/missing-ids.xml; then touch entities/missing-ids.xml; fi
$(NSGMLS) -wno-idref -i lang-$(LANG) -s $(XMLDCL) manual.xml
test_xml: manual.xml
@if test ! -f funcindex.xml; then touch funcindex.xml; fi
@if test ! -f entities/missing-entities.ent; then touch entities/missing-entities.ent; fi
@if test ! -f entities/missing-ids.xml; then touch entities/missing-ids.xml; fi
$(XMLLINT) --noent --noout --valid manual.xml
test_howto:
$(XMLLINT) --noent --noout --valid ./howto/howto.xml
# }}}
# {{{ cleanup
clean:
rm -rf html php fancy howto/html howto/php htmlhelp/html
rm -f @MANUAL@.txt [a-z]*.html @MANUAL@.rtf manual.info
rm -f @MANUAL@.zip @MANUAL@.tar.gz .manual.xml
rm -f manual_*.pdb @srcdir@/scripts/makedoc *.manifest
rm -f *.aux *.tex *.log *.dvi *.toc *.ps *.gz
rm -f status.txt missing.txt
rm -f entities/file-entities.ent
rm -f entities/missing*
rm -f @LANGDIR@/missing-ids.xml
distclean: clean
for file in `find . -name "*.in"`; do rm `dirname $$file`/`basename $$file .in`; done
# }}}
# {{{ tree utils
pull:
cvs -z3 up -dP $(LANGDIR)
# }}}
<file_sep>/branches/function_definitions/scripts/make_man.php
#!/usr/local/bin/php -q
<?php
/*
+----------------------------------------------------------------------+
| PHP Version 4 |
+----------------------------------------------------------------------+
| Copyright (c) 1997-2011 The PHP Group |
+----------------------------------------------------------------------+
| This source file is subject to version 3.0 of the PHP license, |
| that is bundled with this package in the file LICENSE, and is |
| available through the world-wide-web at the following url: |
| http://www.php.net/license/3_0.txt. |
| If you did not receive a copy of the PHP license and are unable to |
| obtain it through the world-wide-web, please send a note to |
| <EMAIL> so we can mail you a copy immediately. |
+----------------------------------------------------------------------+
| Authors: <NAME> <<EMAIL>> |
| <NAME> <<EMAIL>> |
+----------------------------------------------------------------------+
$Id$
*/
/*
* Script to convert (most of the) php documentation
* from docbook to unix man format.
* */
/*
* Problems:
* - examples are not shown correctly
*/
$lang = 'en';
$extension = '';
$outdir = 'man7';
set_time_limit (0);
error_reporting (E_ALL & !E_NOTICE);
if(!is_dir($lang)) {
if(is_dir("../$lang")) {
$lang="../$lang";
$outdir="../$outdir";
} else {
die("language '$lang' not found");
}
}
if (empty ($extension)) {
$file = `find $lang | fgrep .xml | xargs cat`;
} else {
$file = `cat {$lang}/functions/{$extension}.xml`;
}
#$file = str_replace("\n", '', $file);
// First get everything in <refentry></refentry> tags
preg_match_all('/<refentry.*?<\/refentry>/s', $file, $refentries);
$functions = array();
$i = 0;
foreach($refentries[0] as $refentry) {
preg_match('/<refname>(.*)<\/refname>/s', $refentry, $matches);
if(!empty($matches[1])) {
$functions[$i]['name'] = $matches[1];
} else {
$functions[$i]['name'] = '';
}
preg_match('/<refpurpose>(.*)<\/refpurpose>/s', $refentry, $matches);
if(!empty($matches[1])) {
$functions[$i]['shortdesc'] = str_replace ("\n", ' ', $matches[1]);
} else {
$functions[$i]['shortdesc'] = '';
}
$functions[$i]['shortdesc'] = preg_replace('/\s{2,}/s', ' ', $functions[$i]['shortdesc']);
$functions[$i]['shortdesc'] = preg_replace('/^\s*/', '', $functions[$i]['shortdesc']);
$functions[$i]['shortdesc'] = preg_replace('/\s*$/', '', $functions[$i]['shortdesc']);
preg_match('/<methodsynopsis>(.*)<\/methodsynopsis>/s', $refentry, $matches);
if(!empty($matches[1])) {
$funcprototype_all = $matches[0];
$funcprototype = $matches[1];
} else {
$funcprototype_all = '';
$funcprototype = '';
}
preg_match('/<methodsynopsis>.*<type>(.*?)<\/type>/s', $funcprototype_all, $matches);
if(!empty($matches[1])) {
$functions[$i]['prototype'] = $matches[1]. ' ';
} else {
$functions[$i]['prototype'] = '';
}
preg_match('/<methodname>(.*)<\/methodname>/s', $funcprototype, $matches);
if(!empty($matches[1])) {
$functions[$i]['prototype'] .= preg_replace('/<.*?>/s', '', $matches[1]);
$functions[$i]['prototype'] .= '(';
} else {
$functions[$i]['prototype'] = '';
}
preg_match_all('/<methodparam(.*?)>.*?<\/methodparam>/s', $funcprototype, $matches);
$first = 1;
foreach($matches[0] as $param) {
/* Get type and name */
$do_var = 0;
if (preg_match ('/<type>(.*?)<\/type>(.*?)<parameter>(.*?)<\/parameter>/s', $param, $matches)) {
$data = $matches[1]. ' '. $matches[3];
$do_var = 1;
} else if (preg_match ('/<parameter>(.*?)<\/parameter>/s', $param, $matches)) {
$data = $matches[1];
$do_var = 1;
}
if ($do_var) {
if(preg_match('/<methodparam choice="opt">.*<\/methodparam>/s', $param)) {
if($first != 1 ) {
$functions[$i]['prototype'] .= ' [, ' . $data . ']';
} else {
$functions[$i]['prototype'] .= ' [' . $data . ']';
$first = 0;
}
} else {
if($first != 1 ) {
$functions[$i]['prototype'] .= ', ';
} else {
$first = 0;
}
$functions[$i]['prototype'] .= $data;
}
}
}
$functions[$i]['prototype'] = preg_replace('/\n/', '', $functions[$i]['prototype']);
$functions[$i]['prototype'] = preg_replace('/\s{2,}/s', ' ', $functions[$i]['prototype']);
$functions[$i]['prototype'] .= ')';
$y = 0;
preg_match_all('/<para>.*?<\/para>/s', $refentry, $matches);
foreach($matches[0] as $paragraph) {
if(preg_match('/<example>/s', $paragraph)) {
// If this paragraph has an example, do some special formatting.
preg_match('/<title>(.*)<\/title>/s', $paragraph, $tmp);
$functions[$i]['example'] = $tmp[1];
$functions[$i]['example'] = preg_replace('/\s{2,}/', ' ', $functions[$i]['example']);
$functions[$i]['example'] = preg_replace('/<.*?>/', '', $functions[$i]['example']);
$functions[$i]['example'] .= "\n\n";
preg_match('/<programlisting.*?>(.*)<\/programlisting>/s', $paragraph, $tmp);
$programlisting = $tmp[1];
/* Remove CDATA stuff */
$programlisting = preg_replace ("/<!\[CDATA\[\n?/", "", $programlisting);
$programlisting = preg_replace ("/]]>\n?/", "", $programlisting);
// Hmm, no function for this?
$programlisting = str_replace('<', '<', $programlisting);
$programlisting = str_replace('>', '>', $programlisting);
$programlisting = str_replace('"', '"', $programlisting);
$programlisting = str_replace('&', '&', $programlisting);
$programlisting = str_replace(' ', ' ', $programlisting);
$programlisting = str_replace('&sp;', ' ', $programlisting);
$programlisting = str_replace('&', '&', $programlisting);
#$functions[$i]['example'] .= `echo '$programlisting' | indent -kr` . "\n\n";
$functions[$i]['example'] .= $programlisting;
} elseif(preg_match('/See also/s', $paragraph)) {
$functions[$i]['seealso'] = preg_replace('/<.*?>/', '', $paragraph);
$functions[$i]['seealso'] = preg_replace('/See also:[ ]*/', '', $functions[$i]['seealso']);
$functions[$i]['seealso'] = preg_replace('/\s{2,}/', ' ', $functions[$i]['seealso']);
$functions[$i]['seealso'] = preg_replace('/^\s*/', '', $functions[$i]['seealso']);
$functions[$i]['seealso'] = preg_replace('/\./', '', $functions[$i]['seealso']);
} else {
// Nothing special, just put it in.
$functions[$i]['paragraph'][$y] = preg_replace('/<.*?>/', '', $paragraph);
$functions[$i]['paragraph'][$y] = preg_replace('/\s{2,}/', ' ', $functions[$i]['paragraph'][$y]);
}
$y++;
}
$i++;
}
/*
* We have an array now with all the data, now write it to seperate files.
*/
if(!file_exists($outdir)) {
umask(0000);
mkdir($outdir, 0755);
}
foreach($functions as $function) {
if(function_exists('gzwrite')) {
$fp = gzopen($outdir . '/php_' . $function['name'] . '.man.gz', 'w');
} else {
$fp = fopen($outdir . '/php_' . $function['name'] . '.man', 'w');
}
/*
$function['name']
$function['shortdesc']
$function['prototype']
$function['paragraph'][$y] // Array
$function['seealso']
$function['example']
*/
$page = '.TH ' . $function['name'] . " 7 \"" . date("j F, Y") . "\" \"PHPDOC MANPAGE\" \"PHP Programmer's Manual\"\n.SH NAME\n" .
$function['name'] . "\n.SH SYNOPSIS\n.B " . $function['prototype'] . "\n.SH DESCRIPTION\n" . $function['shortdesc'] . ".\n";
if(!empty($function['paragraph']) && count($function['paragraph']) > 0) {
foreach($function['paragraph'] as $para) {
$page .= ".PP\n";
$page .= trim($para) . "\n";
}
}
if(!empty($function['example'])) {
$page .= ".SH \"EXAMPLE\"\n";
$page .= $function['example'] . "\n";
}
if(!empty($function['seealso'])) {
$page .= ".SH \"SEE ALSO\"\n";
$page .= $function['seealso'] . "\n";
}
if(function_exists('gzwrite')) {
gzwrite($fp, $page);
} else {
fwrite($fp, $page);
}
}
?>
<file_sep>/branches/dev_docbook4/Makefile.in
#
# +----------------------------------------------------------------------+
# | PHP Version 4.0 |
# +----------------------------------------------------------------------+
# | Copyright (c) 1997-2001 The PHP Group |
# +----------------------------------------------------------------------+
# | This source file is subject to version 2.02 of the PHP licience, |
# | that is bundled with this package in the file LICENCE and is |
# | avalible through the world wide web at |
# | http://www.php.net/license/2_02.txt. |
# | If uou did not receive a copy of the PHP license and are unable to |
# | obtain it through the world wide web, please send a note to |
# | <EMAIL> so we can mail you a copy immediately |
# +----------------------------------------------------------------------+
# | Authors: <NAME> <<EMAIL>> |
# +----------------------------------------------------------------------+
#
#
# $Id$
#
VPATH=@srcdir@
srcdir=@srcdir@
PHP_SOURCE=@PHP_SOURCE@
LANG=@LANG@
JADE=@JADE@ -wno-idref
NSGMLS=@NSGMLS@
CATALOG=@CATALOG@
VERSION="@PHP_VERSION@"
HTML_STYLESHEET=html.dsl
PHPWEB_STYLESHEET=phpweb.dsl
HOWTO_STYLESHEET=howto.dsl
PRINT_STYLESHEET=print.dsl
QUICKREF_STYLESHEET=quickref.dsl
KDEVELOP_TOC_STYLESHEET=kdevelop_toc.dsl
HTML_DEPS=$(HTML_STYLESHEET) html-common.dsl html-locale.dsl common.dsl
HOWTO_DEPS=$(HOWTO_STYLESHEET) html-common.dsl html-locale.dsl common.dsl howto/howto.ent
PRINT_DEPS=$(PRINT_STYLESHEET) common.dsl
PHPWEB_DEPS=$(PHPWEB_STYLESHEET) html-common.dsl common.dsl
QUICKREF_DEPS=quickref.dsl Makefile
KDEVELOP_TOC_DEPS=kdevelop_toc.dsl Makefile
PALMDOCTITLE=@PALMDOCTITLE@
all: html
DIST_FILES=@MANUAL@.zip @MANUAL@.tar.gz @MANUAL@.tar.bz2 \
@MANUAL@.html.gz @MANUAL@.txt.gz @MANUAL@.doc.pdb
MIRROR_TARGETS=php/index.php html/index.html $(DIST_FILES)
PDF_FILES=@MANUAL@.pdf.gz @MANUAL@.pdf.bz2 @MANUAL@.pdf.zip
html.dsl: $(srcdir)/html.dsl.in ./config.status
CONFIG_FILES=$@ CONFIG_HEADERS= ./config.status
print.dsl: $(srcdir)/print.dsl.in ./config.status
CONFIG_FILES=$@ CONFIG_HEADERS= ./config.status
phpweb.dsl: $(srcdir)/phpweb.dsl.in ./config.status
CONFIG_FILES=$@ CONFIG_HEADERS= ./config.status
common.dsl: $(srcdir)/common.dsl.in ./config.status
CONFIG_FILES=$@ CONFIG_HEADERS= ./config.status
manual.xml: $(srcdir)/manual.xml.in .manual.xml
CONFIG_FILES=$@ CONFIG_HEADERS= ./config.status
.manual.xml: $(DEPEND_FILES) global.ent
touch .manual.xml
html: html/index.html
bightml: @MANUAL@.html
phpweb: php/index.php
rtf: @MANUAL@.rtf
tex latex: @MANUAL@.tex
dvi: @MANUAL@.dvi
ps: @MANUAL@.ps
pdf: @MANUAL@.pdf
howto: howto/html/index.html
howtotgz: howto/howto.html.tar.gz
FORCE:
funclist.txt: FORCE
$(srcdir)/genfunclist $(PHP_SOURCE) > funclist.txt
funcsummary.txt: FORCE
$(srcdir)/genfuncsummary $(PHP_SOURCE) > funcsummary.txt
revcheck.html: FORCE
PHPDOCDIR=$(srcdir) php -f $(srcdir)/scripts/revcheck.php $(LANG) > revcheck.html
Makefile: $(srcdir)/Makefile.in ./config.status
CONFIG_FILES=$@ CONFIG_HEADERS= ./config.status
checkdoc: $(srcdir)/checkdoc.in ./config.status
CONFIG_FILES=$@ CONFIG_HEADERS= ./config.status
mirror-files: $(MIRROR_TARGETS)
extra-mirror-files: $(PDF_FILES)
snapshot: manual-snapshot.tar.gz
manual-snapshot.tar.gz: @MANUAL@.html html/index.html @MANUAL@.rtf @MANUAL@.txt
tar -cvzf $@ @MANUAL@.html html/*.html @MANUAL@.rtf @MANUAL@.txt
status: checkdoc ./funclist.txt
./checkdoc -s > status.txt
./checkdoc -m > missing.txt
summary: ./funcsummary.txt
quickref: quickref.txt
quickref.txt: manual.xml $(QUICKREF_DEPS)
$(JADE) $(CATALOG) -d $(QUICKREF_STYLESHEET) -V nochunks -t sgml $(srcdir)/phpdocxml.dcl manual.xml | sed -e 's/ */ /g' | sort -f > quickref.txt
kdevelop_toc: php.toc
php.toc: manual.xml $(KDEVELOP_TOC_DEPS)
echo '<!DOCTYPE gideontoc>' > $@
$(JADE) $(CATALOG) -d $(KDEVELOP_TOC_STYLESHEET) -V nochunks -t sgml $(srcdir)/phpdocxml.dcl manual.xml | sed -e's/\& /\& /g' >> $@
makedoc: $(srcdir)/makedoc.cc
g++ -o makedoc $(srcdir)/makedoc.cc
@MANUAL@.html: manual.xml $(HTML_DEPS)
$(JADE) $(CATALOG) -V nochunks -d $(HTML_STYLESHEET) -t sgml $(srcdir)/phpdocxml.dcl manual.xml > $@
@MANUAL@.html.gz: @MANUAL@.html
gzip -9 -c $< > $@
@MANUAL@.rtf.gz: @MANUAL@.rtf
gzip -9 -c $< > $@
@MANUAL@.txt.gz: @MANUAL@.txt
gzip -9 -c $< > $@
@MANUAL@.tex: manual.xml
$(JADE) $(CATALOG) -d $(PRINT_STYLESHEET) -t tex $(srcdir)/phpdocxml.dcl $<
mv manual.tex $@
@MANUAL@.pdf: @MANUAL@.dvi
dvipdfm -o @MANUAL@.pdf -p @PDF_PAPER_TYPE@ @MANUAL@.dvi
@MANUAL@.pdf.gz: @MANUAL@.pdf
gzip -9 -c $< > $@
@MANUAL@.pdf.bz2: @MANUAL@.pdf
bzip2 -9 -c $< > $@
@MANUAL@.pdf.zip: @MANUAL@.pdf
zip -9 $@ $<
html/index.html: manual.xml $(HTML_DEPS)
@test -d html || mkdir html
$(JADE) $(CATALOG) -d $(HTML_STYLESHEET) -V use-output-dir -t sgml $(srcdir)/phpdocxml.dcl manual.xml
php/index.php: manual.xml $(PHPWEB_DEPS)
@test -d php || mkdir php
-$(JADE) $(CATALOG) -d $(PHPWEB_STYLESHEET) -V use-output-dir -t sgml $(srcdir)/phpdocxml.dcl manual.xml
@MANUAL@.txt: @MANUAL@.html
lynx -term=vt100 -nolist -dump file:`pwd`/$< > $@
@MANUAL@.doc.pdb: @MANUAL@.txt makedoc
./makedoc -b @MANUAL@.txt @MANUAL@.doc.pdb $(PALMDOCTITLE)
# Note: Isilo converter available only in binary from www.isilo.com
@MANUAL@.isilo.pdb: @MANUAL@.html
iSilo386 @MANUAL@.html @MANUAL@.isilo.pdb
@MANUAL@.zip: html/index.html
-rm -f $@ && (cd html; zip -9 -q ../$@ *.html)
@MANUAL@.tar.gz: html/index.html
-rm -f $@ && (cd html; tar -cf - *.html) | gzip -9 > $@
@MANUAL@.tar.bz2: html/index.html
-rm -f $@ && (cd html; tar -cf - *.html) | bzip2 -9 > $@
howto/html/index.html: howto/howto.xml $(HOWTO_DEPS)
@test -d howto/html || mkdir howto/html
-$(JADE) -i lang-en $(CATALOG) -d $(HOWTO_STYLESHEET) -V use-output-dir -t sgml $(srcdir)/phpdocxml.dcl $(srcdir)/howto/howto.xml
howto/howto.html.tar.gz: howto/html/index.html $(HOWTO_DEPS)
tar -cvzf $@ howto/html/*.html
install.html: install.xml $(HTML_DEPS)
$(JADE) $(CATALOG) -V nochunks -d install.dsl -t sgml $(srcdir)/phpdocxml.dcl install.xml > $@
install.txt: install.html
lynx -nolist -dump file:`pwd`/$< > $@
# File endings we are going to define general rules for:
.SUFFIXES: .html .xml .sgml .tex .dvi .ps .rtf .pdf
# General rules:
.xml.rtf:
$(JADE) $(CATALOG) -d $(PRINT_STYLESHEET) -t rtf $(srcdir)/phpdocxml.dcl $<
# runs three times -
# 1. generates the dvi with a completely bogus table of contents
# 2. generates the dvi with a table of contents that is off based on the size
# of the table of contents
# 3. generates a dvi with all the right page numbers and such
.tex.dvi:
# a hack around bugs in jade/jadetex...
mv $< $<.tmp
sed -e '/HeadingText/,/endHeadPar/ s/_/\\137/g' $<.tmp > $<
rm $<.tmp
-jadetex $<
-jadetex $<
-jadetex $<
# test all possible errors
test: manual.xml
$(NSGMLS) -i lang-$(LANG) -s $(srcdir)/phpdocxml.dcl $<
# ignore missing IDs and check if the manual can be generated anyway
test_man_gen: manual.xml
$(NSGMLS) -wno-idref -i lang-$(LANG) -s $(srcdir)/phpdocxml.dcl $<
clean:
rm -rf html php howto/html
rm -f @MANUAL@.txt [a-z]*.html @MANUAL@.rtf manual.info
rm -f @MANUAL@.zip @MANUAL@.tar.gz .manual.xml
rm -f manual_*.pdb makedoc *.manifest
rm -f *.aux *.tex *.log *.dvi *.toc *.ps *.gz
rm -f status.txt missing.txt checkdoc
distclean: clean
rm -f Makefile html.dsl print.dsl checkdoc \
howto.dsl manual.xml quickref.dsl common.dsl \
html-locale.dsl phpweb.dsl version.ent
<file_sep>/branches/dev_docbook4/make_chm.php
<?php
// USE ONLY PHP 4.x TO RUN THIS SCRIPT!!!
// IT WONT WORK WITH PHP 3
// SEE make_chm.README FOR INFORMATION!!!
$fancydir = getenv("PHP_HELP_COMPILE_FANCYDIR");
if (empty($fancydir)) {
$fancydir = getenv("PHP_HELP_COMPILE_DIR");
}
$language = getenv("PHP_HELP_COMPILE_LANG");
$original_index = "index.html";
// header for index and toc
$header = '<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML//EN">
<html>
<head>
<meta name="generator" content="PHP 4 - Auto TOC script">
<!-- Sitemap 1.0 -->
</head>
<body>
<object typre="text/site properties">
<param name="Window Styles" value="0x800227">
</object>
<ul>';
MakeProjectFile();
MakeContentFiles();
/***********************************************************************/
/* End of script lines, function follows */
/***********************************************************************/
// Generate the HTML Help content files
function MakeContentFiles()
{
global $fancydir, $language, $manual_title, $fancyindex, $indexfile, $original_index, $header;
$toc = fopen("php_manual_$language.hhc", "w");
$index = fopen("php_manual_$language.hhk", "w");
// Write out file headers
fputs($toc, $header);
fputs($index, $header);
// Read original index file and drop out newlines
$index_a = file("$fancydir/$original_index");
$ijoin = join("", $index_a);
$ijoin = preg_replace("/[\r|\n]{1,2}/", " ", $ijoin);
// Print out the objects, autoparsing won't find
SiteMapObj($manual_title, $indexfile, " ", $toc, 21);
IndexObj($manual_title, $indexfile, $index);
// Find the name of the Table of Contents
if ($fancyindex) {
preg_match('|CLASS=\"title\" ><A NAME=\"manual\" >(.*)</A|U', $ijoin, $match);
if (empty($match[1])) { // Fallback
$match[1] = "Table of Contents";
}
SiteMapObj($match[1], $original_index, " ", $toc, 21);
IndexObj($match[1], $original_index, $index);
}
// Find the name of the Preface
preg_match('|<A HREF="preface.html" >(.*)</A >|U', $ijoin, $match);
if (empty($match[1])) { // Fallback
$match[1] = "Preface";
}
SiteMapObj($match[1], "preface.html", " ", $toc);
IndexObj($match[1], "preface.html", $index);
// Find the name of the Preface/About this Manual
fputs($toc, "\n <ul>");
preg_match('|<A HREF="preface.html#about" >(.*)</A >|U', $ijoin, $match);
if (empty($match[1])) { // Fallback
$match[1]="About this Manual";
}
SiteMapObj($match[1], "preface.html#about", " ", $toc);
IndexObj($match[1], "preface.html#about", $index);
fputs($toc, " </ul>\n");
// Now autofind the chapters/subchapters
$not_closed = 0;
for ($i = 0; $i < count ($index_a); $i++) {
/* Chapters */
if (ereg(">[IVXLC]+\.\ <A", $index_a[$i]) && !ereg("HREF=\"ref\.[a-z0-9]+\.html", $index_a[$i+1])) {
$new_list = 1;
if ($not_closed == 1) {
fputs($toc, "\n </ul>\n");
}
//preg_match ("/>([IVX]+)\. <A/", $index_a[$i], $matches);
//$chapter["nr"] = $matches[1];
preg_match("/HREF=\"([a-z0-9-]+\.html)(\#[a-z0-9]+)?\"/", $index_a[$i+1], $matches);
$chapter["html"] = $matches[1];
preg_match("/>([^<]+)/", $index_a[$i+2], $matches);
$chapter["title"] = $matches[1];
SiteMapObj($chapter["title"], $chapter["html"], " ", $toc);
IndexObj($chapter["title"], $chapter["html"], $index);
}
/* Sub chapters */
elseif (ereg(">([0-9]+|[IVXLC]+|[A-Z])\.\ <A", $index_a[$i])) {
if ($new_list == 1) {
$new_list = 0;
$not_closed = 1;
fputs($toc, "\n <ul>\n");
}
//preg_match ("/>([0-9]+|[IVXLC]+|[A-Z])\. <A/", $index_a[$i], $matches);
//$schapter["nr"] = $matches[1];
preg_match("/HREF=\"([a-z0-9-]+\.([a-z0-9-]+\.)?html)(\#[a-z0-9]+)?\"/", $index_a[$i+1], $matches);
$schapter["html"] = $matches[1];
preg_match("/>([^<]+)/", $index_a[$i+2], $matches);
$schapter["title"] = $matches[1];
SiteMapObj($schapter["title"], $schapter["html"], " ", $toc);
IndexObj($chapter["title"], $schapter["html"], $index);
DoFile($schapter["html"], $toc, $index);
}
}
fputs($toc, " </ul>\n");
// Link in directly the copyright page
$cjoin = join("", file("$fancydir/copyright.html"));
$cjoin = preg_replace("/[\r|\n]{1,2}/", " ", $cjoin);
preg_match('|<A NAME="copyright" ></A ><P ><B >(.*)</B|U', $cjoin, $match);
if (empty($match[1])) { // fallback
$match[1] = "Copyright";
}
SiteMapObj($match[1], "copyright.html", " ", $toc, 17);
IndexObj($match[1], "copyright.html", $index);
// Write out closing line, and end files
fputs($index, " </ul>\n</body>\n</html>");
fputs($toc, " </ul>\n</body>\n</html>");
fclose($index);
fclose($toc);
} // MakeContentfiles() function end
// Generates the HTML Help project file
function MakeProjectFile()
{
global $fancydir, $language, $manual_title, $fancyindex, $indexfile, $original_index;
// define language array (manual code -> HTML Help Code)
$languages = array(
"cs" => "0x405 Czech",
"de" => "0x407 German (Germany)",
"en" => "0x809 Enlish (United Kingdom)",
"es" => "0xc0a Spanish (International Sort)",
"fr" => "0x40c French (France)",
"hu" => "0x40e Hungarian",
"it" => "0x410 Italian (Italy)",
"ja" => "0x411 Japanese",
"kr" => "0x412 Korean",
"nl" => "0x413 Dutch (Netherlands)",
"pt_BR" => "0x416 Portuguese (Brazil)"
);
// Try to find the fancy index file
if (file_exists("$fancydir/fancy-index.html")) {
$fancyindex = TRUE;
$indexfile = "fancy-index.html";
} else {
$indexfile = $original_index;
}
// Start writing the project file
$project = fopen("php_manual_$language.hhp", "w");
fputs($project, "[OPTIONS]\n");
fputs($project, "Compatibility=1.1 or later\n");
fputs($project, "Compiled file=php_manual_$language.chm\n");
fputs($project, "Contents file=php_manual_$language.hhc\n");
fputs($project, "Index file=php_manual_$language.hhk\n");
fputs($project, "Default Font=Arial,10,0\n");
fputs($project, "Default Window=phpdoc\n");
fputs($project, "Default topic=$fancydir\\$indexfile\n");
fputs($project, "Display compile progress=Yes\n");
fputs($project, "Full-text search=Yes\n");
// Get the proper language code from the array
fputs($project, "Language=" . $languages[$language] . "\n");
// Now try to find out how the manual named in the actual language
// this must be in the index.html file as the title (DSSSL generated)
$content = join("", file("$fancydir/$original_index"));
if (preg_match("|>(.*)</TITLE|U", $content, $found)) {
$manual_title = $found[1];
} else { // Fallback
$manual_title = "PHP Manual";
}
fputs($project, "Title=$manual_title\n");
// Define the phpdoc window style (adds more functionality)
fputs($project, "\n[WINDOWS]\nphpdoc=\"$manual_title\",\"php_manual_$language.hhc\",\"php_manual_$language.hhk\"," .
"\"$fancydir\\$indexfile\",\"$fancydir\\$indexfile\",,,,,0x23520,,0x386e,,,,,,,,0\n");
// Write out all the filenames as in $fancydir
fputs($project, "\n[FILES]\n");
$handle=opendir($fancydir);
while (false !== ($file = readdir($handle))) {
if ($file != "." && $file != "..") {
fputs($project, "$fancydir\\$file\n");
}
}
closedir($handle);
fclose($project);
} // MakeProjectFile() function end
// Print out a SiteMap object for a file
function SiteMapObj($name, $local, $tabs, $toc, $imgnum = "auto")
{
global $fancydir;
$name = str_replace('"', '"', $name);
fputs($toc, "
$tabs<li><object type=\"text/sitemap\">
$tabs <param name=\"Name\" value=\"$name\">
$tabs <param name=\"Local\" value=\"$fancydir\\$local\">
");
if ($imgnum != "auto") {
fputs($toc, "$tabs <param name=\"ImageNumber\" value=\"$imgnum\">\n");
}
fputs($toc, "$tabs </object>\n");
} // SiteMapObj() function end
// Print out an object for an Index file
function IndexObj($name, $local, $index)
{
global $fancydir;
$name = str_replace('"', '"', $name);
fputs($index, "
<li><object type=\"text/sitemap\">
<param name=\"Local\" value=\"$fancydir\\$local\">
<param name=\"Name\" value=\"$name\">
</object></li>
");
}
// Process a file, and find any links need to be presented in tree
function DoFile ($filename, $toc, $index)
{
global $fancydir;
$content = file ("$fancydir/$filename");
$contents = preg_replace("/[\n|\r]/", " ", join("", $content));
// Find all sublinks
if (preg_match_all("!<DT\s+><A\s+HREF=\"(([\w\.-]+\.)+html)(\#[\w\.-]+)?\"\s+>(.+)</A\s+>!U", $contents, $matches, PREG_SET_ORDER)) {
// Print out the file informations for all the links
fputs($toc, " <ul>");
foreach ($matches as $onematch) {
$param["html"] = $onematch[1];
if (!empty($onematch[3])) {
$param["html"] .= $onematch[3];
}
$param["title"] = strip_tags($onematch[4]);
SiteMapObj($param["title"], $param["html"], " ", $toc);
IndexObj($param["title"], $param["html"], $index);
}
fputs($toc, " </ul>\n");
} else {
// Uncomment this if you want to debug the above pregs
// Note: there are many files normally without deeper
// TOC info, eg. language.expressions.html
// echo "no deeper TOC info found in $filename\n";
// return;
}
} // DoFile() function end
?><file_sep>/branches/function_definitions/scripts/function-definitions.php
<?php
$srcpath = $argv[1];
if(!empty($argv[2])) $repourl = $argv[2]; else {
preg_match("/URL\: (.*)/", `svn info {$srcpath}`, $repourl);
$repourl = $repourl[1];
}
$result = array();
$extensions = get_loaded_extensions();
foreach($extensions as $extension) {
$extension = strtolower($extension);
$result[$extension] = array();
if($extension == "core") {
/*
foreach(get_extension_funcs($extension) as $function) {
$file = trim(`grep -Rl --include="*.c" "PHP_FUNCTION({$function})" {$srcpath}/main/`);
if(!empty($file)) echo "{$function}: {$file}".PHP_EOL;
}
*/
} else {
if(!file_exists("{$srcpath}/ext/{$extension}/")) continue;
$extensionReflect = new ReflectionExtension($extension);
$extensionName = $extensionReflect->name;
$functions = $extensionReflect->getFunctions();
foreach($functions as $function) {
$file = trim(str_replace($srcpath, "", `grep -Rl --include="*.c" "PHP_FUNCTION({$function->name})" {$srcpath}/ext/{$extension}/`));
if(!empty($file)) {
$file = explode(PHP_EOL, $file);
foreach($file as &$path) $path = $repourl.$path;
$result[$extension][$function->name] = implode(PHP_EOL, $file);
}
}
$classes = $extensionReflect->getClasses();
foreach($classes as $class) {
$result[$extension][$class->name] = array();
foreach($class->getMethods() as $method) {
$file = trim(str_replace($srcpath, "", `grep -Rl --include="*.c" "PHP_METHOD({$extensionName}, {$method->name})" {$srcpath}/ext/{$extension}/`));
if(!empty($file)) {
$file = explode(PHP_EOL, $file);
foreach($file as &$path) $path = $repourl.$path;
$result[$extension][$class->name][$method->name] = implode(PHP_EOL, $file);
}
}
if(empty($result[$extension][$class->name])) unset($result[$extension][$class->name]);
}
}
if(empty($result[$extension])) unset($result[$extension]);
}
foreach($result as $extension_name => $extension) {
if(!file_exists("../../en/reference/{$extension_name}/")) continue;
foreach($extension as $item_name => $item) {
$item_name = strtolower($item_name);
if(is_string($item)) { // Function
if(!file_exists("../../en/reference/{$extension_name}/functions/") || !file_exists("../../en/reference/{$extension_name}/functions/{$item_name}.xml")) continue;
echo `svn propset srcurl '{$item}' ../../en/reference/{$extension_name}/functions/{$item_name}.xml`;
} elseif(is_array($item)) { // Method
if(!file_exists("../../en/reference/{$extension_name}/{$item_name}/")) continue;
foreach($item as $method_name => $url) {
$method_name = strtolower($method_name);
if(!file_exists("../../en/reference/{$extension_name}/{$item_name}/{$method_name}.xml")) continue;
echo `svn propset srcurl '{$url}' ../../en/reference/{$extension_name}/{$item_name}/{$method_name}.xml`;
}
}
}
}
<file_sep>/branches/tr/Makefile.in
#
# +----------------------------------------------------------------------+
# | PHP Version 4.0 |
# +----------------------------------------------------------------------+
# | Copyright (c) 1997-2001 The PHP Group |
# +----------------------------------------------------------------------+
# | This source file is subject to version 2.02 of the PHP licience, |
# | that is bundled with this package in the file LICENCE and is |
# | avalible through the world wide web at |
# | http://www.php.net/license/2_02.txt. |
# | If uou did not receive a copy of the PHP license and are unable to |
# | obtain it through the world wide web, please send a note to |
# | <EMAIL> so we can mail you a copy immediately |
# +----------------------------------------------------------------------+
# | Authors: <NAME> <<EMAIL>> |
# +----------------------------------------------------------------------+
#
#
# $Id$
#
VPATH=@srcdir@
srcdir=@srcdir@
PHP_SOURCE=@PHP_SOURCE@
LANG=@LANG@
JADE=@JADE@
NSGMLS=@NSGMLS@
CATALOG=@CATALOG@
VERSION="@PHP_VERSION@"
HTML_STYLESHEET=html.dsl
PHPWEB_STYLESHEET=phpweb.dsl
HOWTO_STYLESHEET=howto.dsl
PRINT_STYLESHEET=print.dsl
QUICKREF_STYLESHEET=quickref.dsl
KDEVELOP_TOC_STYLESHEET=kdevelop_toc.dsl
HTML_DEPS=$(HTML_STYLESHEET) html-common.dsl common.dsl
PRINT_DEPS=$(PRINT_STYLESHEET) common.dsl
PHPWEB_DEPS=$(PHPWEB_STYLESHEET) html-common.dsl common.dsl
QUICKREF_DEPS=quickref.dsl Makefile
KDEVELOP_TOC_DEPS=kdevelop_toc.dsl Makefile
PALMDOCTITLE=@PALMDOCTITLE@
all: html
DIST_FILES=manual.zip manual.tar.gz bigmanual.html.gz \
manual_doc.pdb manual.txt.gz manual.tar.bz2
MIRROR_TARGETS=php/index.php html/index.html $(DIST_FILES)
html.dsl: $(srcdir)/html.dsl.in ./config.status
CONFIG_FILES=$@ CONFIG_HEADERS= ./config.status
print.dsl: $(srcdir)/print.dsl.in ./config.status
CONFIG_FILES=$@ CONFIG_HEADERS= ./config.status
phpweb.dsl: $(srcdir)/phpweb.dsl.in ./config.status
CONFIG_FILES=$@ CONFIG_HEADERS= ./config.status
common.dsl: $(srcdir)/common.dsl.in ./config.status
CONFIG_FILES=$@ CONFIG_HEADERS= ./config.status
manual.xml: $(srcdir)/manual.xml.in .manual.xml
CONFIG_FILES=$@ CONFIG_HEADERS= ./config.status
.manual.xml: $(DEPEND_FILES) global.ent
touch .manual.xml
html: html/index.html
bightml: bigmanual.html
phpweb: php/index.php
rtf: manual.rtf
dvi: manual.dvi
ps: manual.ps
pdf: manual.pdf
howto: howto.html
FORCE:
funclist.txt: FORCE
$(srcdir)/genfunclist $(PHP_SOURCE) > funclist.txt
funcsummary.txt: FORCE
$(srcdir)/genfuncsummary $(PHP_SOURCE) > funcsummary.txt
Makefile: $(srcdir)/Makefile.in ./config.status
CONFIG_FILES=$@ CONFIG_HEADERS= ./config.status
checkdoc: $(srcdir)/checkdoc.in ./config.status
CONFIG_FILES=$@ CONFIG_HEADERS= ./config.status
mirror-files: $(MIRROR_TARGETS)
snapshot: manual-snapshot.tar.gz
manual-snapshot.tar.gz: bigmanual.html html/index.html manual.rtf manual.txt
tar -cvzf $@ bigmanual.html html/*.html manual.rtf manual.txt
status: checkdoc ./funclist.txt
./checkdoc -s > status.txt
./checkdoc -m > missing.txt
summary: ./funcsummary.txt
quickref: quickref.txt
quickref.txt: manual.xml $(QUICKREF_DEPS)
$(JADE) $(CATALOG) -d $(QUICKREF_STYLESHEET) -V nochunks -t sgml $(srcdir)/phpdocxml.dcl manual.xml | sed -e 's/ */ /g' | sort -f > quickref.txt
kdevelop_toc: php.toc
php.toc: manual.xml $(KDEVELOP_TOC_DEPS)
echo '<!DOCTYPE gideontoc>' > $@
$(JADE) $(CATALOG) -d $(KDEVELOP_TOC_STYLESHEET) -V nochunks -t sgml $(srcdir)/phpdocxml.dcl manual.xml | sed -e's/\& /\& /g' >> $@
makedoc: $(srcdir)/makedoc.cc
g++ -o makedoc $(srcdir)/makedoc.cc
bigmanual.html: manual.xml $(HTML_DEPS)
$(JADE) $(CATALOG) -V nochunks -d $(HTML_STYLESHEET) -t sgml $(srcdir)/phpdocxml.dcl manual.xml > $@
bigmanual.html.gz: bigmanual.html
gzip -9 -c $< > $@
manual.rtf.gz: manual.rtf
gzip -9 -c $< > $@
manual.txt.gz: manual.txt
gzip -9 -c $< > $@
manual.pdf: manual.tex
# a hack around bugs in jade/jadetex...
mv manual.tex manual.tex.tmp
sed -e '/HeadingText/,/endHeadPar/ s/_/\\137/g' manual.tex.tmp > manual.tex
rm manual.tex.tmp
-jadetex $<
-jadetex $<
-jadetex $<
dvipdfm -p @PDF_PAPER_TYPE@ manual.dvi
html/index.html: manual.xml $(HTML_DEPS)
@test -d html || mkdir html
$(JADE) $(CATALOG) -d $(HTML_STYLESHEET) -V use-output-dir -t sgml $(srcdir)/phpdocxml.dcl manual.xml
php/index.php: manual.xml $(PHPWEB_DEPS)
@test -d php || mkdir php
-$(JADE) $(CATALOG) -d $(PHPWEB_STYLESHEET) -V use-output-dir -t sgml $(srcdir)/phpdocxml.dcl manual.xml
manual.txt: bigmanual.html
lynx -nolist -dump file:`pwd`/bigmanual.html > manual.txt
manual_doc.pdb: manual.txt makedoc
./makedoc -b manual.txt manual_doc.pdb $(PALMDOCTITLE)
# Note: Isilo converter available only in binary from www.isilo.com
manual_isilo.pdb: bigmanual.html
iSilo386 bigmanual.html manual_isilo.pdb
manual.zip: html/index.html
-rm -f $@ && (cd html; zip -9 -q ../$@ *.html)
manual.tar.gz: html/index.html
-rm -f $@ && (cd html; tar -cf - *.html) | gzip -9 > manual.tar.gz
manual.tar.bz2: html/index.html
-rm -f $@ && (cd html; tar -cf - *.html) | bzip2 -9 > manual.tar.bz2
howto.html: $(srcdir)/howto.xml $(HOWTO_DEPS) global.ent
$(JADE) $(CATALOG) -d $(HOWTO_STYLESHEET) -t sgml $(srcdir)/phpdocxml.dcl $(srcdir)/howto.xml
tex latex: $(srcdir)/manual.tex
# File endings we are going to define general rules for:
.SUFFIXES: .html .xml .sgml .tex .dvi .ps .rtf .pdf
# General rules:
.xml.tex:
$(JADE) $(CATALOG) -d $(PRINT_STYLESHEET) -t tex $(srcdir)/phpdocxml.dcl $<
.xml.rtf:
$(JADE) $(CATALOG) -d $(PRINT_STYLESHEET) -t rtf $(srcdir)/phpdocxml.dcl $<
# runs three times -
# 1. generates the dvi with a completely bogus table of contents
# 2. generates the dvi with a table of contents that is off based on the size
# of the table of contents
# 3. generates a dvi with all the right page numbers and such
.tex.dvi:
jadetex $<
jadetex $<
jadetex $<
.dvi.ps:
dvips -o $@ $<
.ps.pdf:
ps2pdf -p $@ $<
test: manual.xml
$(NSGMLS) -i lang-$(LANG) -s $(srcdir)/phpdocxml.dcl $<
clean:
rm -rf html php
rm -f manual.txt [a-z]*.html manual.rtf manual.info
rm -f manual.zip manual.tar.gz .manual.xml
rm -f manual_*.pdb makedoc *.manifest
rm -f *.aux *.tex *.log *.dvi *.toc *.ps *.gz
rm -f funclist.txt funcsummary.txt status.txt missing.txt checkdoc
distclean: clean
rm -f Makefile html.dsl print.dsl checkdoc \
howto.dsl manual.xml quickref.dsl common.dsl \
html-locale.dsl phpweb.dsl version.ent
<file_sep>/branches/docgen-update/scripts/docgen/structures/Docgen_Job.php
<?php
define("DOCGEN_VERSION", "alpha");
abstract class Docgen_Job {
protected $reflection;
public $parameters = array(
'pecl'=>false,
'seealso'=>false,
'example'=>false
);
public $documents = array();
abstract public function execute();
protected static function format_identifier($name) {
return preg_replace(array('/[^[:alnum:]]/', '/^-+/'), array('-', ''), strtolower($name));
}
protected function addExamples() {
}
protected function addSeeAlso() {
}
protected function addLocalVariables(XMLWriter $writer) {
$writer->writeComment(
' Keep this comment at the end of the file
24 Local variables:
25 mode: sgml
26 sgml-omittag:t
27 sgml-shorttag:t
28 sgml-minimize-attributes:nil
29 sgml-always-quote-attributes:t
30 sgml-indent-step:1
31 sgml-indent-data:t
32 indent-tabs-mode:nil
33 sgml-parent-document:nil
34 sgml-default-dtd-file:"~/.phpdoc/manual.ced"
35 sgml-exposed-tags:nil
36 sgml-local-catalogs:nil
37 sgml-local-ecat-files:nil
38 End:
39 vim600: syn=xml fen fdm=syntax fdl=2 si
40 vim: et tw=78 syn=sgml
41 vi: ts=1 sw=1
'
);
}
}
<file_sep>/tags/pre-xchm-14/htmlhelp/user_notes.php
<?php
/*
This file is part of the Windows Compiled HTML Help
Manual Generator of the PHP Documentation project.
The logic in this file comes from an extract
of phpweb/include/shared-manual.inc and
phpweb/include/layout.inc (clean_note()).
From time to time, it may be needed to update
the code, as the manual notes system changes.
This file is consistent with:
layout.inc - 1.66
shared-manual.inc - 1.125
This file also includes code to generate a project
file for the notes.
Grab the notes file (all compressed) from:
http://ANY_MIRROR_SITE.php.net/backend/notes/all.bz2
*/
// Check dependencies, die if error found
if (!$USE_NOTES) { die("ERROR: User note generator called"); }
// Merge all possible language manuals. Only the available
// manual[s] will be active, while viewing
$lang_chms = '';
foreach ($LANGUAGES as $code) {
$lang_chms .= "php_manual_$code.chm\n";
}
// We need a list of files for an IE6 workaround
$NOTE_FILE_LIST = array();
// Start writing the notes project file
$nproject = fopen("$NOTES_TARGET/php_manual_notes.hhp", "w");
fputs($nproject,
"[OPTIONS]
Compatibility=1.1 or later
Compiled file=php_manual_notes.chm
Default topic=_index.html
Display compile progress=No
Full-text search=Yes
Language=0x0809 English (UNITED KINGDOM)
Title=User Notes
[MERGE FILES]
$lang_chms
[FILES]
");
// Walk through all files in HTML_DIR directory
$handle = opendir($HTML_SRC);
while (false !== ($filename = readdir($handle))) {
// Only process html files generated by XSL sheets
if (strpos($filename, ".html") && (strpos($filename, "_") !== 0)) {
// Get title (used for HTML page title)
$content = join("", file("$HTML_SRC/$filename"));
preg_match("!<title>([^<]+)</title>!Us", $content, $match);
// Get user notes, or false on failure
$user_notes = manualUserNotes($match[1], $filename);
// If there are no user notes for this page,
// no file will be generated, but if we generate
// a file, we add it to project file too
if ($user_notes != FALSE) {
$WITH_NOTES++;
$notes = fopen("$NOTES_TARGET/$filename", "w");
fwrite($notes, $user_notes);
fclose($notes);
fwrite($nproject, $filename . "\n");
$NOTE_FILE_LIST[] = $filename;
echo "> $WITH_NOTES\r";
} else {
$WITHOUT_NOTES++;
}
}
}
closedir($handle);
// Copy note supplemental files, and add to file list
copy("suppfiles/notes/_index.html", "$NOTES_TARGET/_index.html");
fwrite($nproject, "_index.html\n");
copy("suppfiles/notes/_style.css", "$NOTES_TARGET/_style.css");
fwrite($nproject, "_style.css\n");
// Write out a list of files to work around an IE6 bug
$jsfile = fopen("$NOTES_TARGET/_filelist.js", "w");
fwrite($jsfile, "note_file_list = ' " . join(" ", $NOTE_FILE_LIST) . " ';\n\n");
fwrite($jsfile, "if (note_file_list.indexOf(' ' + chmfile_page + ' ') != -1) { notesIframe(); }");
fclose($jsfile);
fwrite($nproject, "_filelist.js\n");
// Close ready project file
fclose($nproject);
// Make entry HTML fragment for a user note
function makeEntry($date, $name, $blurb)
{
// Begin user notes header
$entryhtml = "<div><p class=\"unheader\">\n";
// Get email/name of the user note writer
$name = htmlspecialchars($name);
if ($name && $name != "<EMAIL>" && $name != "<EMAIL>.com") {
if (ereg("(.+)@(.+)\.(.+)", $name)) {
$entryhtml .= "<a href=\"mailto:$name\" class=\"useremail\"><span>$name</span></a>";
} else {
$entryhtml .= "<b><span>$name</span></b>";
}
}
// Append date
$entryhtml .= " (<span>" . date("d-M-Y h:i", $date) . "</span>)</p>\n";
// Append user note text, cleared
$entryhtml .= "<p class=\"untext\"><tt><span>" . clean_note($blurb) . "</span></tt></p></div>\n";
// Return with entry HTML fragment
return $entryhtml;
}
// Get user notes for this particular page, returns an array with notes
function manualGetUserNotes($id)
{
global $NOTES_SRC, $NOTE_NUM;
$notes = array();
$hash = substr(md5($id),0,16);
$notes_file = "$NOTES_SRC/$hash[0]/$hash";
if ($fp = @fopen($notes_file,"r")) {
while (!feof($fp)) {
$line = chop(fgets($fp,8096));
if ($line == "") continue;
list($id,$sect,$rate,$ts,$user,$note) = explode("|",$line);
$notes[] = array(
"id" => $id,
"sect" => $sect,
"rate" => $rate,
"xwhen" => $ts,
"user" => $user,
"note" => base64_decode($note)
);
}
fclose($fp);
}
$NOTE_NUM += count($notes);
return $notes;
}
// Get the HTML file for a user note page, or false on failure
function manualUserNotes($title, $id)
{
// Don't want .html at the end of the ids
if (substr($id,-5) == '.html') { $id = substr($id,0,-5); }
// Get user notes
$notes = manualGetUserNotes($id);
// If we have no notes, do not produce useless HTML
if (count($notes) == 0) {
return FALSE;
}
// start HTML output
$notehtml = <<<END_OF_MULTI
<html>
<head>
<title>N: $title</title>
<link rel="stylesheet" href="_style.css">
</head>
<body onLoad="if(parent.nbuff) {parent.displayNotes()}">
<h3>User contributed notes:</h3>
END_OF_MULTI;
// Go through manual notes, and make entries
foreach ($notes as $note) {
$notehtml .= makeEntry($note['xwhen'], $note['user'], $note['note'], $note['id']);
}
// Be good guys, and end HTML code here
$notehtml .= "\n</body></html>";
// Return with manual notes for this page
return $notehtml;
}
// Clean note to get right display
function clean_note($text) {
// Do not allow people to fool the system with bogus HTML
$text = htmlspecialchars(trim($text));
// turn urls into links
$text = preg_replace("/((mailto|http|ftp|nntp|news):.+?)(>|\\s|\\)|\"|\\.\\s|$)/","<a href=\"\\1\">\\1</a>\\3",$text);
// this 'fixing' code will go away eventually
$fixes = array('<br>','<p>','</p>');
reset($fixes);
while (list(,$f)=each($fixes)) {
$text=str_replace(htmlspecialchars($f), $f, $text);
$text=str_replace(htmlspecialchars(strtoupper($f)), $f, $text);
}
// Allow only one <br> (drop out long empty sections)
$text = preg_replace("!(<br>\\s*)+!", "<br>", $text);
// wordwrap is not applicable here, because (it is buggy and)
// we need to make text break as window resized
// Convert new lines in notes to <br> / <br />
$text = nl2br(preg_replace("![\\n\\r]+!", "\n", $text));
// Get files to smaller size (bad hack :)
$text = str_replace("<br />", "<br>", $text);
// We do not use <pre> but would like to see indentation
$text = str_replace(" ", " ", $text);
// Paras cannot be used here, replace with <br><br>
$text = str_replace("<p>", "<br><br>", $text);
// Drop out end of paras
$text = str_replace("</p>", "", $text);
return $text;
}
?>
<file_sep>/tags/POST_EXCEPTIONS_ROLE_CHANGE/scripts/check-valid-function.php
<?php
/*
+----------------------------------------------------------------------+
| PHP Version 5 |
+----------------------------------------------------------------------+
| Copyright (c) 1997-2004 The PHP Group |
+----------------------------------------------------------------------+
| This source file is subject to version 3.0 of the PHP license, |
| that is bundled with this package in the file LICENSE, and is |
| available through the world-wide-web at the following url: |
| http://www.php.net/license/3_0.txt. |
| If you did not receive a copy of the PHP license and are unable to |
| obtain it through the world-wide-web, please send a note to |
| <EMAIL> so we can mail you a copy immediately. |
+----------------------------------------------------------------------+
| Authors: <NAME> <<EMAIL>> |
+----------------------------------------------------------------------+
| Description: This file parses the manual and outputs all erroneous |
| <function> tag usage. |
+----------------------------------------------------------------------+
*/
/* path to phpdoc CVS checkout. if this file is in the scripts/ directory
* then the value below will be correct!
*/
$phpdoc = '../';
/* english! */
$lang = 'en';
/* initialize array and declare some language constructs */
$funcs = array( 'include' => true,
'include_once' => true,
'require' => true,
'require_once' => true,
'return' => true,
);
$total = 0;
/* recursive glob() with a callback function */
function globbetyglob($globber, $userfunc)
{
foreach (glob("$globber/*") as $file) {
if (is_dir($file)) {
globbetyglob($file, $userfunc);
}
else {
call_user_func($userfunc, $file);
}
}
}
/* make a function list from files in the functions/ directories */
function make_func_list($file)
{
global $funcs;
if (fnmatch("*/reference/*/functions/*.xml", $file)) {
$func = strtolower(str_replace(array('-', '.'), '_', substr(basename($file), 0, -4)));
$funcs[$func] = true;
}
}
/* find all <function> tags and report invalid functions */
function parse_file($file)
{
global $funcs, $phpdoc, $lang, $total;
/* ignore old functions directory */
if (fnmatch("$phpdoc/$lang/functions/*", $file))
return;
$f = file_get_contents($file);
if ($f != '') {
if (preg_match_all('|<function>(.*?)</function>|s', $f, $m)
&& is_array($m)
&& is_array($m[1]))
{
foreach ($m[1] as $func) {
$func = strtolower(str_replace(array('::', '->'), '_', trim($func)));
if ($funcs[$func] !== true) {
$total++;
$fileout = substr($file, strlen($phpdoc) + 1);
printf("%-60.60s <function>$func</function>\n", $fileout);
}
}
}
}
}
echo "Building a list of functions...\n";
globbetyglob("$phpdoc/$lang", 'make_func_list');
echo 'List complete. ' . count($funcs) . " functions.\n";
echo "Checking the manual for <function> tags that contain invalid functions...\n";
globbetyglob("$phpdoc/$lang", 'parse_file');
echo "Found $total occurences.\n";
?>
<file_sep>/branches/docgen-update/scripts/online_editor/workbench.php
<?php
/*
+----------------------------------------------------------------------+
| PHP Version 4 |
+----------------------------------------------------------------------+
| Copyright (c) 1997-2011 The PHP Group |
+----------------------------------------------------------------------+
| This source file is subject to version 3.0 of the PHP license, |
| that is bundled with this package in the file LICENSE, and is |
| available through the world-wide-web at the following url: |
| http://www.php.net/license/3_0.txt. |
| If you did not receive a copy of the PHP license and are unable to |
| obtain it through the world-wide-web, please send a note to |
| <EMAIL> so we can mail you a copy immediately. |
+----------------------------------------------------------------------+
| Authors : <NAME> <<EMAIL>> |
+----------------------------------------------------------------------+
$Id$
*/
//-- The PHPDOC Online XML Editing Tool
//--- Purpose: this file is the frameset
require 'base.php';
$user = sessionCheck();
?>
<frameset cols="200,*">
<frame name=listingframe src=cvslist.php>
<frame name=fileframe src=intro.php>
</frameset>
<file_sep>/tags/POST_DOCBOOK5/scripts/iniupdate/cvs-get-release
#!/bin/bash
# taken from cvs.php.net/functable by Harmut
if [ $# -ne 2 ]
then
echo 1>&2 "usage: $0 repository release-tag";
exit 3;
fi
cvs -d ":pserver:<EMAIL>:/repository" get -d $2 -r $2 $1 >/dev/null 2>&1 | grep -v Updating
find $2 -type f -and -not -name "*.[chly]" -and -not -name "*.ec" -and -not -name "*.lex" | xargs rm -f
while ( find $2 -depth -type d -and -empty | xargs rm -r 2>/dev/null ) ; do true ; done
<file_sep>/branches/function_definitions/scripts/genfuncindex.php
<?php
/*
+----------------------------------------------------------------------+
| PHP Version 4 |
+----------------------------------------------------------------------+
| Copyright (c) 1997-2011 The PHP Group |
+----------------------------------------------------------------------+
| This source file is subject to version 3.0 of the PHP license, |
| that is bundled with this package in the file LICENSE, and is |
| available through the world-wide-web at the following url: |
| http://www.php.net/license/3_0.txt. |
| If you did not receive a copy of the PHP license and are unable to |
| obtain it through the world-wide-web, please send a note to |
| <EMAIL> so we can mail you a copy immediately. |
+----------------------------------------------------------------------+
| Authors: <NAME> <<EMAIL>> |
+----------------------------------------------------------------------+
$Id$
*/
echo "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
?>
<!-- DO NOT EDIT THIS FILE, IT WAS AUTO-GENERATED BY genfuncindex.php -->
<appendix xmlns="http://docbook.org/ns/docbook" xml:id="indexes">
<title>&FunctionIndex;</title>
<index xml:id="index.functions">
<title>&FunctionIndex;</title>
<?php
$functions = file($_SERVER['argv'][1], FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
usort($functions,"strcasecmp");
$functions = array_unique($functions);
$letter = ' ';
$letters = range('A', 'Z');
array_unshift($letters, '_');
echo " <para>\n";
foreach ($letters as $letter) {
$lower = strtolower($letter);
echo " <link linkend=\"index.functions.$lower\">$letter</link>\n";
}
echo " </para>\n";
$letter = ' ';
foreach ( $functions as $function ) {
if (strpos($function, '::') === FALSE) {
$function = strtolower($function);
}
if (strtolower($function{0}) != $letter) {
if ($letter != ' ') {
echo " </indexdiv>\n";
}
$letter = strtolower($function{0});
echo " <indexdiv>\n";
echo " <title xml:id=\"index.functions.$letter\">".strtoupper($letter)."</title>\n";
}
echo " <indexentry><primaryie><function>$function</function></primaryie></indexentry>\n";
}
?>
</indexdiv>
</index>
<para></para>
</appendix>
<file_sep>/branches/docgen-update/scripts/docgen/structures/Docgen_JobManager.php
<?php
class Docgen_JobManager {
}
<file_sep>/tags/POST_EXCEPTIONS_ROLE_CHANGE/scripts/fixphpweb.php
#!/usr/bin/php -q
<?php
/*
+----------------------------------------------------------------------+
| PHP Version 4 |
+----------------------------------------------------------------------+
| Copyright (c) 1997-2004 The PHP Group |
+----------------------------------------------------------------------+
| This source file is subject to version 3.0 of the PHP license, |
| that is bundled with this package in the file LICENSE, and is |
| available through the world-wide-web at the following url: |
| http://www.php.net/license/3_0.txt. |
| If you did not receive a copy of the PHP license and are unable to |
| obtain it through the world-wide-web, please send a note to |
| <EMAIL> so we can mail you a copy immediately. |
+----------------------------------------------------------------------+
| Authors: <NAME> <<EMAIL>> |
+----------------------------------------------------------------------+
*/
set_time_limit(0);
ob_implicit_flush();
if ($argc < 2 || $argc > 3) { ?>
Deletes the HTML !DOCTYPE lines from 'phpweb_xsl' generated files
Usage:
<?php echo $argv[0];?> <dir>
<dir> is the folder, where the phpweb_xsl output
files are located. The files will be rewritten to
get the !DOCTYPE removed.
<?php
exit;
}
echo "Starting phpweb_xsl fix\n";
// Strip of any ending slash
$startdir = preg_replace('!/+$!', '', $argv[1]);
// Check folder
if (!is_dir($startdir)) {
die("ERROR: The first parameter is not a directory\n");
}
// Try to open folder
$dh = opendir($startdir);
if (!$dh) { die("ERROR: Unable to open directory\n"); }
// For all the files
while (($filename = readdir($dh)) !== FALSE) {
$fullname = "$startdir/$filename";
// If this is a php file
if (preg_match("!.php$!", $fullname) && is_file($fullname)) {
$contents = file($fullname);
// If !DOCTYPE is not found, skip file rewrite
if (strpos($contents[0], "<!DOCTYPE") === FALSE) { continue; }
// Otherwise, rewrite the contents of the
// file, skiping the first line
$fp = fopen($fullname, "w");
if (!$fp) { die("ERROR: unable to open $fullname for writing\n"); }
fwrite($fp, join("", array_slice($contents, 1)));
fclose($fp);
}
}
closedir($dh);
echo "SUCCESS: !DOCTYPE stripout finished\n";
<file_sep>/branches/docgen-update/scripts/online_editor/intro.php
<?php
/*
+----------------------------------------------------------------------+
| PHP Version 4 |
+----------------------------------------------------------------------+
| Copyright (c) 1997-2011 The PHP Group |
+----------------------------------------------------------------------+
| This source file is subject to version 3.0 of the PHP license, |
| that is bundled with this package in the file LICENSE, and is |
| available through the world-wide-web at the following url: |
| http://www.php.net/license/3_0.txt. |
| If you did not receive a copy of the PHP license and are unable to |
| obtain it through the world-wide-web, please send a note to |
| <EMAIL> so we can mail you a copy immediately. |
+----------------------------------------------------------------------+
| Authors : <NAME> <<EMAIL>> |
+----------------------------------------------------------------------+
$Id$
*/
//-- The PHPDOC Online XML Editing Tool
//--- Purpose: just an introduction
// ToDo show summary of translated files (or revcheck)
require 'base.php';
$user = sessionCheck();
$lang = $user['phpdocLang'];
?>
<html>
<body style="font-family: Tahoma; font-size: 12px;">
<h2> The PHPDOC Online XML Editing Tool </h2>
Developed by <NAME> <EMAIL><br>
Version 1.0 - essentially developed for Arabic Translation of PHP Manual<br>
Now updated to work with all phpdoc translations<br>
<br>
<b>Last CVS Update: <?php print implode('', file('cvsupdate.txt')); ?></b>
<br><br>
The language you are editing is <b><?php print $lang; ?></b><br>
Translation coordinator: <b><?php print $phpdocLangs[$lang]['coordinator'] ?></b><br>
Mailing list: <b><?php print $phpdocLangs[$lang]['mailing'] ?></b>. For Subscription email to <b><?php print $phpdocLangs[$lang]['mailingSubscribe'] ?></b><br><br>
Charset used: <b><?php print $phpdocLangs[$lang]['charset'] ?></b><br>
<?php
// Lists the user's cached files
if (file_exists($user['cache']."files.txt")) {
print '<hr>';
print 'Your Cached files:<br>';
$ff = file($user['cache']."files.txt");
foreach($ff as $f) {
$fx = explode('|', $f);
if (!isset($cf[$fx[2]])) {
print "<a href='editxml.php?file=$fx[2]&source=upath' target=fileframe>$fx[2]</a><br>";
$cf[$fx[2]] = true;
}
}
}
?>
</body>
</html>
<file_sep>/tags/dev_xml_mergepoint/Makefile.in
# +----------------------------------------------------------------------+
# | PHP HTML Embedded Scripting Language Version 3.0 |
# +----------------------------------------------------------------------+
# | Copyright (c) 1997,1998 PHP Development Team (See Credits file) |
# +----------------------------------------------------------------------+
# | This program is free software; you can redistribute it and/or modify |
# | it under the terms of one of the following licenses: |
# | |
# | A) the GNU General Public License as published by the Free Software |
# | Foundation; either version 2 of the License, or (at your option) |
# | any later version. |
# | |
# | B) the PHP License as published by the PHP Development Team and |
# | included in the distribution in the file: LICENSE |
# | |
# | This program is distributed in the hope that it will be useful, |
# | but WITHOUT ANY WARRANTY; without even the implied warranty of |
# | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the |
# | GNU General Public License for more details. |
# | |
# | You should have received a copy of both licenses referred to here. |
# | If you did not, or have any questions about PHP licensing, please |
# | contact <EMAIL>. |
# +----------------------------------------------------------------------+
# | Authors: <NAME> <<EMAIL>> |
# +----------------------------------------------------------------------+
#
# $Id$
#
VPATH=@srcdir@
srcdir=@srcdir@
PHP_SOURCE=@PHP_SOURCE@
LANG=@LANG@
# For Suse 6.2, uncomment the CATALOG definition below.
# Also modify /usr/share/sgml/docbk30/docbook.dcl:
# change 'OMITTAG NO' to 'OMITTAG YES'
# change 'NAMELEN 44' to e.g. 'NAMELEN 54'
# CATALOG="-c /usr/share/sgml/CATALOG.docbk30"
VERSION="@PHP_VERSION@"
HTML_STYLESHEET=$(srcdir)/html.dsl
PHPWEB_STYLESHEET=$(srcdir)/phpweb.dsl
PHP_STYLESHEET=$(srcdir)/php.dsl
HOWTO_STYLESHEET=$(srcdir)/howto.dsl
PRINT_STYLESHEET=@DOCBOOK_PRINT@
all: html
PREFACE=$(LANG)/preface.sgml \
$(LANG)/bookinfo.sgml
APPENDICES=$(LANG)/appendices/migration.sgml \
$(LANG)/appendices/escaping.sgml \
$(LANG)/appendices/regexp.sgml \
$(LANG)/appendices/http-stuff.sgml \
$(LANG)/appendices/history.sgml \
$(LANG)/appendices/debugger.sgml \
$(LANG)/appendices/phpdevel.sgml
CHAPTERS=$(LANG)/chapters/copyright.sgml \
$(LANG)/chapters/intro.sgml \
$(LANG)/chapters/config.sgml \
$(LANG)/chapters/install.sgml \
$(LANG)/chapters/security.sgml \
$(LANG)/features/connection-handling.sgml \
$(LANG)/features/file-upload.sgml \
$(LANG)/features/cookies.sgml \
$(LANG)/features/http-auth.sgml \
$(LANG)/features/error-handling.sgml \
$(LANG)/features/images.sgml \
$(LANG)/features/remote-files.sgml \
$(LANG)/language/basic-syntax.sgml \
$(LANG)/language/operators.sgml \
$(LANG)/language/constants.sgml \
$(LANG)/language/types.sgml \
$(LANG)/language/control-structures.sgml \
$(LANG)/language/functions.sgml \
$(LANG)/language/oop.sgml \
$(LANG)/language/variables.sgml \
$(LANG)/language/expressions.sgml
FUNCREF= \
$(LANG)/functions/array.sgml \
$(LANG)/functions/adabas.sgml \
$(LANG)/functions/bc.sgml \
$(LANG)/functions/datetime.sgml \
$(LANG)/functions/dbase.sgml \
$(LANG)/functions/dbm.sgml \
$(LANG)/functions/dl.sgml \
$(LANG)/functions/dir.sgml \
$(LANG)/functions/exec.sgml \
$(LANG)/functions/filepro.sgml \
$(LANG)/functions/filesystem.sgml \
$(LANG)/functions/ftp.sgml \
$(LANG)/functions/http.sgml \
$(LANG)/functions/hw.sgml \
$(LANG)/functions/ibase.sgml \
$(LANG)/functions/ifx.sgml \
$(LANG)/functions/image.sgml \
$(LANG)/functions/imap.sgml \
$(LANG)/functions/ldap.sgml \
$(LANG)/functions/mail.sgml \
$(LANG)/functions/math.sgml \
$(LANG)/functions/mcal.sgml \
$(LANG)/functions/misc.sgml \
$(LANG)/functions/mcrypt.sgml \
$(LANG)/functions/msql.sgml \
$(LANG)/functions/mysql.sgml \
$(LANG)/functions/nis.sgml \
$(LANG)/functions/sybase.sgml \
$(LANG)/functions/network.sgml \
$(LANG)/functions/oci8.sgml \
$(LANG)/functions/oracle.sgml \
$(LANG)/functions/pcre.sgml \
$(LANG)/functions/pgsql.sgml \
$(LANG)/functions/posix.sgml \
$(LANG)/functions/info.sgml \
$(LANG)/functions/regex.sgml \
$(LANG)/functions/sem.sgml \
$(LANG)/functions/session.sgml \
$(LANG)/functions/solid.sgml \
$(LANG)/functions/snmp.sgml \
$(LANG)/functions/strings.sgml \
$(LANG)/functions/uodbc.sgml \
$(LANG)/functions/url.sgml \
$(LANG)/functions/var.sgml \
$(LANG)/functions/wddx.sgml \
$(LANG)/functions/zlib.sgml
FILES=$(PREFACE) $(APPENDICES) $(CHAPTERS) $(FUNCREF) global.ent chapters.ent
DIST_FILES=manual.zip manual.tar.gz manual.rtf.gz bigmanual.html.gz \
manual.prc manual.txt.gz
MIRROR_TARGETS=php3/manual.php3 $(DIST_FILES) html/manual.html
html.dsl: html.dsl.in ./config.status
CONFIG_FILES=$@ CONFIG_HEADERS= ./config.status
print.dsl: print.dsl.in ./config.status
CONFIG_FILES=$@ CONFIG_HEADERS= ./config.status
phpweb.dsl: phpweb.dsl.in ./config.status
CONFIG_FILES=$@ CONFIG_HEADERS= ./config.status
php.dsl: php.dsl.in ./config.status
CONFIG_FILES=$@ CONFIG_HEADERS= ./config.status
manual.sgml: .manual.sgml manual.sgml.in
CONFIG_FILES=$@ CONFIG_HEADERS= ./config.status
.manual.sgml: $(FILES)
touch .manual.sgml
html: html/manual.html
phpweb: php3/manual.php3
php: php/index.php
rtf: manual.rtf
dvi: manual.dvi
ps: manual.ps
pdf: manual.pdf
howto: howto.html
FORCE:
funclist.txt: FORCE
$(srcdir)/genfunclist $(PHP_SOURCE) > funclist.txt
funcsummary.txt: FORCE
$(srcdir)/genfuncsummary $(PHP_SOURCE) > funcsummary.txt
Makefile: $(srcdir)/Makefile.in ./config.status
CONFIG_FILES=$@ CONFIG_HEADERS= ./config.status
checkdoc: $(srcdir)/checkdoc.in ./config.status
CONFIG_FILES=$@ CONFIG_HEADERS= ./config.status
mirror-files: $(MIRROR_TARGETS)
sync: mirror-files
-(cd php3; rsync -e ssh1 --rsync-path=/usr/local/bin/rsync -azvc . www.php.net:/local/Web/sites/phpweb/manual/.)
-(cd html; rsync -e ssh1 --rsync-path=/usr/local/bin/rsync -azvc . www.php.net:/local/Web/sites/phpweb/manual/html/.)
-rsync -e ssh1 --rsync-path=/usr/local/bin/rsync -azvc $(DIST_FILES) www.php.net:/local/Web/sites/phpweb/distributions/.
snapshot: manual-snapshot.tar.gz
manual-snapshot.tar.gz: bigmanual.html html/manual.html manual.rtf manual.txt
tar -cvzf $@ bigmanual.html html/*.html manual.rtf manual.txt
status: checkdoc ./funclist.txt
$(srcdir)/checkdoc -s > $(srcdir)/status.txt
$(srcdir)/checkdoc -m > $(srcdir)/missing.txt
summary: ./funcsummary.txt
makedoc: makedoc.cc
g++ -o makedoc makedoc.cc
bigmanual.html: $(srcdir)/manual.sgml $(HTML_STYLESHEET)
jade $(CATALOG) -i lang-$(LANG) -V nochunks -d $(HTML_STYLESHEET) -t sgml $(srcdir)/phpdoc.dcl $(srcdir)/manual.sgml > $@
bigmanual.html.gz: bigmanual.html
gzip -c $< > $@
manual.rtf.gz: manual.rtf
gzip -c $< > $@
manual.txt.gz: manual.txt
gzip -c $< > $@
html/manual.html: $(srcdir)/manual.sgml $(HTML_STYLESHEET)
@test -d html || mkdir html
jade $(CATALOG) -i lang-$(LANG) -d $(HTML_STYLESHEET) -V use-output-dir -t sgml $(srcdir)/phpdoc.dcl $(srcdir)/manual.sgml
php/index.php: $(srcdir)/manual.sgml $(PHPWEB_STYLESHEET)
@test -d php || mkdir php
-jade $(CATALOG) -i lang-$(LANG) -d $(PHP_STYLESHEET) -V use-output-dir -t sgml $(srcdir)/phpdoc.dcl $(srcdir)/manual.sgml
php3/manual.php3: $(srcdir)/manual.sgml $(PHPWEB_STYLESHEET)
@test -d php3 || mkdir php3
-jade $(CATALOG) -i lang-$(LANG) -d $(PHPWEB_STYLESHEET) -V use-output-dir -t sgml $(srcdir)/phpdoc.dcl $(srcdir)/manual.sgml
manual.txt: bigmanual.html
lynx -nolist -dump file:`pwd`/bigmanual.html > manual.txt
manual.prc: manual.txt makedoc
./makedoc -b manual.txt manual.prc 'PHP3 Manual'
manual.zip: $(srcdir)/html/manual.html
-rm -f $@ && (cd html; zip -9 -q ../$@ *.html)
manual.tar.gz: $(srcdir)/html/manual.html
-rm -f $@ && (cd html; tar -cf - *.html) | gzip > manual.tar.gz
howto.html: $(srcdir)/howto.sgml $(HOWTO_STYLESHEET) global.ent
jade $(CATALOG) -i lang-$(LANG) -d $(HOWTO_STYLESHEET) -t sgml $(srcdir)/phpdoc.dcl $(srcdir)/howto.sgml
tex latex: $(srcdir)/manual.tex
# File endings we are going to define general rules for:
.SUFFIXES: .html .sgml .tex .dvi .ps .rtf
# General rules:
.sgml.tex:
jade $(CATALOG) -i lang-$(LANG) -d $(PRINT_STYLESHEET) -t tex $(srcdir)/phpdoc.dcl $<
.sgml.rtf:
jade $(CATALOG) -i lang-$(LANG) -d $(PRINT_STYLESHEET) -t rtf $(srcdir)/phpdoc.dcl $<
# runs three times -
# 1. generates the dvi with a completely bogus table of contents
# 2. generates the dvi with a table of contents that is off based on the size
# of the table of contents
# 3. generates a dvi with all the right page numbers and such
.tex.dvi:
jadetex $<
jadetex $<
jadetex $<
.dvi.ps:
dvips -o $@ $<
.ps.pdf:
ps2pdf -p $@ $<
test: manual.sgml
nsgmls -i lang-$(LANG) -s $(srcdir)/phpdoc.dcl $<
clean:
( \
cd $(srcdir); \
rm -rf html php3; \
rm -f manual.txt [a-z]*.html manual.rtf manual.info \
rm -f manual.zip manual.tar.gz sync-no commit-no .manual.sgml \
rm -f manual.prc makedoc *.manifest \
rm -f *.aux *.tex *.log *.dvi *.toc *.ps *.gz \
rm -f funclist.txt funcsummary.txt status.txt missing.txt checkdoc \
)
<file_sep>/tags/POST_DOCBOOK5/scripts/iniupdate/cvs-versions.php
<?php
/*
+----------------------------------------------------------------------+
| ini doc settings updater |
+----------------------------------------------------------------------+
| Copyright (c) 1997-2005 The PHP Group |
+----------------------------------------------------------------------+
| This source file is subject to version 3.0 of the PHP license, |
| that is bundled with this package in the file LICENSE, and is |
| available through the world-wide-web at the following url: |
| http://www.php.net/license/3_0.txt. |
| If you did not receive a copy of the PHP license and are unable to |
| obtain it through the world-wide-web, please send a note to |
| <EMAIL> so we can mail you a copy immediately. |
+----------------------------------------------------------------------+
| Authors: <NAME> <<EMAIL>> |
+----------------------------------------------------------------------+
*/
// fetch all version tags
$tags = array();
foreach (glob('*.tags') as $file) {
$tmp = array_map('rtrim', file($file));
$last_versions[] = substr(end($tmp), 4); // this is the last released version from a major version
$tags = array_merge($tags, $tmp);
}
// fetch cvs versions
$file = file_get_contents('./update-all');
preg_match_all('/PHP_(\d)_CVS=(\w+)/', $file, $data, PREG_SET_ORDER);
$cvs_versions = array();
foreach ($data as $v) {
if ($v[2] == 'HEAD') {
$version = "$v[1].0.0";
} else {
$version = make_cvs_version(substr($v[2], 4));
}
$cvs_versions["php_$v[1]_cvs"] = $version;
}
$tags = array_merge(array_keys($cvs_versions), $tags);
// the file was called directly: DEBUG mode
if (basename(__FILE__) == $_SERVER['PHP_SELF']) {
print_r($cvs_versions);
print_r($last_versions);
print_r($tags);
}
// guess the cvs version number by checking last released versions
function make_cvs_version($tag) {
global $last_versions;
foreach ($last_versions as $ver) {
if (strpos($ver, $tag) === 0) { //found it
$parts = explode('_', $ver);
++$parts[2]; //increment minor version (5.5.1 -> 5.5.2)
return implode('.', $parts);
}
}
// new branch (5.5.0)
return "$tag[0].$tag[2].0";
}
unset($file, $data, $last_versions);
?>
<file_sep>/tags/pre-xchm-14/htmlhelp/README.txt
****************************************************************
** This build system is used to generate the extended CHM **
** file available from php.net (only in English). There is **
** a different CHM generator system in the 'chm' folder, **
** which is used to build the simpler CHM files (in multiple **
** languages). **
** **
** Both of the systems are used in paralell. **
****************************************************************
Build system of the extended CHMs
=================================
[See latest "official" output package online at
http://php.net/docs-echm]
How to build a CHM manual with this system?
0. Ensure that you have the latest phpdoc checkout,
but that your XSL folder is dated 2002.12.31 23:00:00,
since if you use XSL sheets from after this timestamp,
the customizations will not work. Use the cvs date tag
to get this version:
From the phpdoc root directory:
cvs update -dP -D"December 31, 2002 11:00pm" xsl
# ensure the version information is up-to-date and that
# html doctypes are included
cvs up -A xsl/version.xml xsl/docbook/html/chunker.xsl
{Volunteer to fix the customizations if you are willing
to, but otherwise you cannot do much more but use the old
sheets}
Ensure however that the xsl/version.xml file is up to date,
so you will build the latest function version information
into the CHM.
1. run "autoconf" in the phpdoc directory
2. run "./configure --with-chm=yes"
Optionally you may need to specify the
"--with-xsltproc=path" option to explicitly
provide the XSLTProc path.
3. Replace @DOCBOOKXSL_HTML@ with ./docbook/html/chunk.xsl in
xsl/htmlhelp-db.xsl (do this after any configure runs). This
is needed, since the new XSL sheets require no configuration,
and since you are using old sheets, you need to do configuration
yourself.
4. Add
<xsl:template match="collabname" mode="titlepage.mode">
<xsl:apply-templates />
</xsl:template>
<xsl:param name="chunker.output.doctype-system" select="'http://www.w3.org/TR/html4/loose.dtd'"/>
<xsl:param name="chunker.output.doctype-public" select="'-//W3C//DTD HTML 4.01 Transitional//EN'"/>
to xsl/html-common.xsl.
5. Run "make chm_xsl"
If xsltproc encounters errors in the XML files,
correct the errors, commit them to phpdoc, and
run "make chm_xsl" again. There is no need to
reconfigure in most cases.
After this step the HTML files to start are in
phpdoc/htmlhelp/html
6. Get the actual mirrors.inc file from
http://ANY_MIRROR.php.net/include/mirrors.inc
and save into the directory where the
make_chm.bat resides (overwrite old one if
one exists).
7. Get all the user notes from
http://ANY_MIRROR.php.net/backend/notes/all.bz2,
extract its contents (using bunzip2 all.bz2, for example),
and place the resulting "all" file to the same folder where
the make_chm.bat resides.
8. Copy local_vars.php.src to local_vars.php and
adjust settings as needed.
9. Now run make_chm.bat
Well, this is quite manual right now, and there are
some problems need fixing (see the TODO.txt file too).
<file_sep>/tags/POST_EXCEPTIONS_ROLE_CHANGE/scripts/zendapi_macros.php
<?php
$overwrite = false;
$zend_include_dir = "../../php-src/Zend";
$zend_include_files = array(
"zend.h",
"zend_API.h",
"zend_builtin_functions.h",
"zend_compile.h",
"zend_constants.h",
"zend_exceptions.h",
"zend_execute.h",
"zend_hash.h",
"zend_highlight.h",
"zend_interfaces.h",
"zend_ini.h",
"zend_list.h",
"zend_modules.h",
"zend_objects.h",
"zend_object_handlers.h",
"zend_objects_API.h",
"zend_qsort.h",
"zend_stream.h",
"zend_strtod.h",
"zend_unicode.h",
"zend_variables.h",
"../TSRM/TSRM.h",
"../TSRM/tsrm_virtual_cwd.h",
);
$output_dirs = array("../en/internals/zendapi/macros" => array("ZEND_", "Z_", "RETURN_"),
"../en/internals/tsrm/macros" => array("VCWD_"));
foreach ($zend_include_files as $infile) {
echo "processing $zend_include_dir/$infile\n";
$in = fopen("$zend_include_dir/$infile", "r");
if (!$in) {
die("can't open $zend_include_dir/$infile");
}
// loop over all lines in the file
while (!feof($in)) {
$line = trim(fgets($in));
// now check for all known macro prefixes
foreach ($output_dirs as $output_dir => $macro_prefixes) {
foreach ($macro_prefixes as $prefix) {
// does this line match a macro definition?
if (preg_match("|#define\\s*($prefix\\w+)\\((.*)\\)|U", $line, $matches)) {
// get macro name and parameter list from the matches
$macro = $matches[1];
$params = preg_split('|,\s+|', $matches[2]);
// path to output file
$outfile = $output_dir."/".$macro.".xml";
// do not overwrite existing files unless specified
if ($overwrite || !file_exists($outfile)) {
echo "writing $outfile\n";
// now write the template file to phpdoc/en/internals/zendapi/macros
ob_start();
echo '<?xml version="1.0" encoding="iso-8859-1"?>'."\n";
// take revision from existing file if any, else it is 1.1
if (!$overwrite || !file_exists($outfile)) {
echo "<!-- $"."Revision: 1.1 $ -->\n";
} else {
foreach (file($outfile) as $line) {
if (strstr($line, 'Revision: ')) {
echo $line;
break;
}
}
}
?>
<refentry id="zend-macro.<?php echo strtolower(str_replace("_", "-", $macro)); ?>">
<refnamediv>
<refname><?php echo $macro; ?></refname>
<refpurpose>...</refpurpose>
</refnamediv>
<refsect1 role="description">
&reftitle.description;
<literallayout>#include <<?php echo basename($infile); ?>></literallayout>
<methodsynopsis>
<type>???</type><methodname><?php echo $macro; ?></methodname>
<?php
foreach($params as $param) {
echo " <methodparam><type>???</type><parameter>$param</parameter></methodparam>\n";
}
?>
</methodsynopsis>
<para>
...
</para>
</refsect1>
<refsect1 role="parameters">
&reftitle.parameters;
<para>
<variablelist>
<?php
foreach($params as $param) {
?>
<varlistentry>
<term><parameter><?php echo $param; ?></parameter></term>
<listitem>
<para>
...
</para>
</listitem>
</varlistentry>
<?php
}
?>
</variablelist>
</para>
</refsect1>
<refsect1 role="returnvalues">
&reftitle.returnvalues;
<para>
...
</para>
</refsect1>
</refentry>
<!-- Keep this comment at the end of the file
Local variables:
mode: sgml
sgml-omittag:t
sgml-shorttag:t
sgml-minimize-attributes:nil
sgml-always-quote-attributes:t
sgml-indent-step:1
sgml-indent-data:t
indent-tabs-mode:nil
sgml-parent-document:nil
sgml-default-dtd-file:"../../../../manual.ced"
sgml-exposed-tags:nil
sgml-local-catalogs:nil
sgml-local-ecat-files:nil
End:
vim600: syn=xml fen fdm=syntax fdl=2 si
vim: et tw=78 syn=sgml
vi: ts=1 sw=1
-->
<?php
file_put_contents($outfile, ob_get_clean());
}
}
}
}
}
}
?>
<file_sep>/branches/function_definitions/scripts/online_editor/login.php
<?php
/*
+----------------------------------------------------------------------+
| PHP Version 4 |
+----------------------------------------------------------------------+
| Copyright (c) 1997-2011 The PHP Group |
+----------------------------------------------------------------------+
| This source file is subject to version 3.0 of the PHP license, |
| that is bundled with this package in the file LICENSE, and is |
| available through the world-wide-web at the following url: |
| http://www.php.net/license/3_0.txt. |
| If you did not receive a copy of the PHP license and are unable to |
| obtain it through the world-wide-web, please send a note to |
| <EMAIL> so we can mail you a copy immediately. |
+----------------------------------------------------------------------+
| Authors : <NAME> <<EMAIL>> |
+----------------------------------------------------------------------+
$Id$
*/
//-- The PHPDOC Online XML Editing Tool
//--- Purpose: allows users to login using an email address (TODO we may use CVS or other way in future)
//------- Initialization
require 'base.php';
session_start();
// Logout &and=logout
if (isset($_GET['and'])) {
unset($_SESSION['user']);
}
//------- Login request
if (isset($_POST['lang'])) {
$email = '';
if (isset($_POST['email'])) {
$email = $_POST['email'];
}
$lang = $_POST['lang'];
// Check selected language
if (!isset($phpdocLangs[$lang])) {
exit('Sorry, you have choosen an incorrect language');
}
if ($requireLogin) {
// Simple email validation -- ToDo some enhancements
$email = trim(strtolower($email));
$p1 = preg_match("#^([a-z0-9][a-z0-9_\.]*)@[a-z0-9][a-z0-9\-]+\.[a-z]{2,6}$#", $email);
$p2 = preg_match("#^([a-z0-9][a-z0-9_\.]*)@[a-z0-9][a-z0-9\-]+\.[a-z]{2,3}\.[a-z]{2}$#", $email);
if (!$p1 && !$p2) {
exit('That was not a valid email address');
}
// This validation is required because emails are used as user folder name -- ToDO use another way
if (strlen($email)>50) {
exit('That was not a valid email address');
}
// Do Login (create user folder)
if (!file_exists($usersCachePath.$email)) {
@mkdir($usersCachePath.$email, $filesChMod);
}
}
if (is_dir($usersCachePath.$email) || !$requireLogin) {
// Session setup
$_SESSION['user'] = array('email'=>$email, 'cache'=>$usersCachePath.$email.'/', 'phpdocLang'=>$lang);
// If expired session, redo last request
if (!empty($_SESSION['redo'])) {
$link = $_SESSION['redo'];
$_SESSION['redo'] = false;
header("location: $link");
exit;
}
// If accidently lost session while editing
if ($_REQUEST['from']=='editxml') {
exit('Ok, Login is <b>successful</b>. Now retry your previous request');
}
// Redirect to frameset
header('location: workbench.php');
exit('<a href="workbench.php">Moved to workbench.php</a>');
} else {
// If folder has not been created
exit('Sorry, there was an internal error. Please contact administration');
}
}
//------- Login form
?>
<html>
<body style="font-family: Tahoma; font-size: 12px;">
<h3> The PHPDOC Online XML Editing Tool :: Choose your language</h3>
<form action=login.php method=post>
<input type=hidden name=from value="<?php print $_REQUEST['from']; ?>">
<?php
if ($requireLogin) { ?>
Your email address (must be valid) <input type=text name=email><br>
<?php } ?>
Translating PHPDOC to
<select name=lang><?php
foreach($phpdocLangs as $lang=>$langInfo) {
print "<option value='$lang'>$lang</option>";
}
?>
</select>* <input type=submit value="Start editing">
</form>
Developed by <NAME> <EMAIL>(@)<EMAIL><br>
Version 1.0 - essentially developed for Arabic Translation of PHP Manual<br>
Now updated to work with all phpdoc translations.
<br>
This is a special tool to be used only by PHPDOC translators.<br>
Javascript and cookies must be enabled in your browser settings.<br>
<br>
<b>Last CVS Update: <?php print implode('', file('cvsupdate.txt')); ?></b>
</body>
</html>
<file_sep>/branches/dev_docbook4/scripts/fix_modelines.php
<?php
// Fix the modelines of xml files. If no modelines were given, it is assumed
// that the xml is two levels deeper than the root of the phpdoc dir, otherwise
// it's copied from the emacs property sgml-default-dtd-file
function apply($input)
{
$lines = explode("\n",$input);
$numlines = count($lines);
$modeline_started = FALSE;
$manual_ced_line = NULL;
$output = "";
foreach ($lines as $nr=>$line) {
if (eregi("Keep this comment at the end of the file", $line)) {
// we're on top of the comment
if ($nr + 20 < $numlines) {
// there's too much of lines left, bail out
?>
ERROR in this file, modelines seems to be not at end of file!
<?php
exit;
}
// break out of for-loop
$modeline_started = TRUE;
}
if ($modeline_started) {
if (ereg("sgml-default-dtd-file(.*)manual\.ced", $line, $regs)) {
$manual_ced_line = "sgml-default-dtd-file$regs[1]manual.ced\"";
}
}
if (!$modeline_started) {
$output .= "$line\n";
}
}
if (!$modeline_started) {
echo "WARNING: did NOT found start of modelines!\n";
}
if (!$manual_ced_line) {
echo "WARNING: did NOT found a ced-line!\n";
$manual_ced_line = 'sgml-default-dtd-file:"../../manual.ced"';
}
$output .= <<<HEREDOC
<!-- Keep this comment at the end of the file
Local variables:
mode: sgml
sgml-omittag:t
sgml-shorttag:t
sgml-minimize-attributes:nil
sgml-always-quote-attributes:t
sgml-indent-step:1
sgml-indent-data:t
sgml-parent-document:nil
HEREDOC;
$output .= "$manual_ced_line\n";
$output .= <<<HEREDOC
sgml-exposed-tags:nil
sgml-local-catalogs:nil
sgml-local-ecat-files:nil
End:
vim600: syn=xml fen fdm=syntax fdl=2 si
vim: et tw=78 syn=sgml
vi: ts=1 sw=1
-->
HEREDOC;
return $output;
}
<file_sep>/tags/POST_DOCBOOK5/scripts/html_syntax.php
#!/usr/bin/php -q
<?php
/* vim: noet
+----------------------------------------------------------------------+
| PHP Version 4 |
+----------------------------------------------------------------------+
| Copyright (c) 1997-2004 The PHP Group |
+----------------------------------------------------------------------+
| This source file is subject to version 3.0 of the PHP license, |
| that is bundled with this package in the file LICENSE, and is |
| available through the world-wide-web at the following url: |
| http://www.php.net/license/3_0.txt. |
| If you did not receive a copy of the PHP license and are unable to |
| obtain it through the world-wide-web, please send a note to |
| <EMAIL> so we can mail you a copy immediately. |
+----------------------------------------------------------------------+
| Authors: <NAME> <<EMAIL>> |
+----------------------------------------------------------------------+
*/
if ($_SERVER["argc"] < 4) {
exit("Purpose: Syntax highlight PHP examples in DSSSL generated HTML manual.\n"
.'Usage: html_syntax.php [ "html" | "php" ] [ "xsl" | "dsssl" ] [ filename.ext | dir | wildcard ] ...' ."\n"
.'"html" - highlight_string() is applied, "php" - highlight_php() is added' ."\n"
);
}
set_time_limit(5*60); // can run long, but not more than 5 minutes
function callback_html_number_entities_decode($matches) {
return chr($matches[1]);
}
function callback_highlight_php($matches) {
if ($GLOBALS['DECODE'] === true) {
$with_tags = preg_replace_callback("!&#([0-9]+);!", "callback_html_number_entities_decode", trim($matches[1]));
} else {
$with_tags = trim($matches[1]);
}
if ($GLOBALS["TYPE"] == "php") {
return "\n<?php\nhighlight_php('". addcslashes($with_tags, "'\\") ."');\n?>\n";
} else { // "html"
return highlight_string($with_tags, true);
}
}
function callback_highlight_xml_indent($match) {
return strtr($match[0], array(' ' => ' ', "\t" => ' '));
}
function callback_highlight_xml($matches) {
$source = trim(htmlentities($matches[1]));
$match = array(
'/(\w+)=("|"|\')(.*?)("|"|\')/',
'/!DOCTYPE (\w+) (\w+) ("|\'|")(.*?)("|\'|")/',
'/<([a-zA-Z_][a-zA-Z0-9_:-]*)/',
'/<\/([a-zA-Z_][a-zA-Z0-9_:-]*)>/',
'/<!--/',
'/-->/',
'/<\?xml (.*?) ?\?>/i',
'/<!\[CDATA\[(.*)\]\]>/i',
);
$replace = array(
'<span class="attributes">$1</span>=<span class="string">$2$3$2</span>',
'<span class="tags">!DOCTYPE</span> <span class="attributes">$1 $2 $3$4$3</span>',
'<<span class="tags">$1</span>',
'</<span class="tags">$1</span>>',
'<span class="comment"><!--',
'--></span>',
'<<span class="tags">?xml</span> $1 <span class="tags">?</span>>',
'<span class="tags"><![<span class="keyword">CDATA</span>[</span><span class="cdata">$1</span><span class="tags">]]></span>'
);
$result = preg_replace($match, $replace, $source);
$result = preg_replace_callback('/^([ \t]+)/m', 'callback_highlight_xml_indent', $result);
return '<div class="xmlcode">' . nl2br($result) . '</div>';
}
$files = $_SERVER["argv"];
array_shift($files); // $argv[0] - script filename
$TYPE = array_shift($files); // "html" or "php"
$build_medium = array_shift($files);
$DECODE = ($build_medium !== "xsl");
while (($file = array_shift($files)) !== null) {
if (is_file($file)) {
$process = array($file);
} elseif (is_dir($file)) {
$lastchar = substr($file, -1);
$process = glob($file . ($lastchar == "/" || $lastchar == "\\" ? "*" : "/*"));
} else { // should be wildcard
$process = glob($file);
}
foreach ($process as $filename) {
if (!is_file($filename)) { // do not recurse
continue;
}
//~ echo "$filename\n";
$original = file_get_contents($filename);
$highlighted = preg_replace_callback("!<PRE\r?\nCLASS=\"php\"\r?\n>(.*)</PRE\r?\n>!sU", "callback_highlight_php", $original);
$highlighted = preg_replace_callback("@<HIGHLIGHTPHPCODE>(.*)</HIGHLIGHTPHPCODE>@sU", "callback_highlight_php", $highlighted); /* Used in the XSL build for PHP code */
$highlighted = preg_replace_callback("@<HIGHLIGHTXMLCODE>(.*)</HIGHLIGHTXMLCODE>@sU", "callback_highlight_xml", $highlighted); /* Used in the XSL build for XML code */
if ($original != $highlighted) {
// file_put_contents is only in PHP >= 5
$fp = fopen($filename, "wb");
fwrite($fp, $highlighted);
fclose($fp);
}
}
}
?>
<file_sep>/tags/xchm-13/htmlhelp/make_chm.php
<?php
/*
This is the main file of the Windows Compiled HTML Help
Manual Generator of the PHP Documentation project.
Written by <NAME> <<EMAIL>>
Credits go to people worked on previous versions:
<NAME>, <NAME>, <NAME> and
<NAME>
*/
// Measure needed time
$start_time = time();
// This script can take much time to run
set_time_limit(0);
// Include variables used by the build process
// Test for local_vars, as they are not there by default
if (!@file_exists("local_vars.php")) {
die("ERROR: local_vars.php is needed, but not there");
}
require_once "local_vars.php";
// Possible languages for manual generation
$LANGUAGES = array(
"cs", "de", "en", "es", "fr", "hu", "it", "ja", "kr", "nl", "pt_BR"
);
echo "
____________________________________________________________
Generate Microsoft HTML Help document from the
output of XSL generated HTML files of the PHP
documentation.
See \"local_vars.php.src\" for local parameter
adjustment, see README.txt and the phpdoc howto for
more information.
____________________________________________________________
";
// Process parameters
echo "\n| Processing local parameters...\n";
if (!@is_dir($HTML_SRC)) {
die("ERROR: HTML path not valid");
}
if (!@file_exists($HELP_WORKSHOP)) {
die("ERROR: HTML Workshop path not valid");
}
if (!@is_dir($RELEASE_DIR)) {
mkdir($RELEASE_DIR, 0700);
echo "> $RELEASE_DIR directory created...\n";
} elseif ($START_CLEANUP) {
echo "| Cleaning up $RELEASE_DIR directory...\n";
passthru("rmdir /S /Q $RELEASE_DIR");
mkdir($RELEASE_DIR, 0700);
}
if (!@is_dir($HTML_TARGET)) {
mkdir($HTML_TARGET, 0700);
echo "> $HTML_TARGET directory created...\n";
} elseif ($START_CLEANUP) {
echo "| Cleaning up $HTML_TARGET directory...\n";
passthru("rmdir /S /Q $HTML_TARGET");
mkdir($HTML_TARGET, 0700);
}
if ($USE_NOTES) {
if (!@is_dir($NOTES_SRC)) {
mkdir($NOTES_SRC, 0700);
echo "> $NOTES_SRC directory created...\n";
} elseif ($START_CLEANUP) {
echo "| Cleaning up $NOTES_SRC directory...\n";
passthru("rmdir /S /Q $NOTES_SRC");
mkdir($NOTES_SRC, 0700);
}
if (!@is_dir($NOTES_TARGET)) {
mkdir($NOTES_TARGET, 0700);
echo "> $NOTES_TARGET directory created...\n";
} elseif ($START_CLEANUP) {
echo "| Cleaning up $NOTES_TARGET directory...\n";
passthru("rmdir /S /Q $NOTES_TARGET");
mkdir($NOTES_TARGET, 0700);
}
echo "| php_manual_notes.chm target choosen...\n";
if ($LANGUAGE != 'en') {
echo "| Warning: it is not safe to generate notes CHM for non-english HTML files\n";
}
}
// Test for mirror information file
if (!file_exists("mirrors.inc")) {
die("ERROR: Mirror information file (mirrors.inc) not found");
}
// Generate files and compile
echo "| Parameters processed...
";
echo "
> Now the HTML files are being filtered
to make output as perfect as possible.
Please be patient, as it can take some time...
";
$counter = 0;
require_once "filter_files.php";
echo "> $counter files are converted in previous step.
";
if ($USE_NOTES) {
$WITH_NOTES = $WITHOUT_NOTES = $NOTE_NUM = 0;
echo "
> Trying to split user notes 'all' file to separate
directories and files (to make the next step
fast and less resource intensive)...
";
require_once "split_notes.php";
echo "
> Now the user notes project file and HTML files
are being created. Please be patient, as it
can take as much time as the previous step...
";
require_once "user_notes.php";
echo "> $WITH_NOTES files created with notes
$WITHOUT_NOTES files found without notes
Total number of notes: $NOTE_NUM
";
}
echo "
> Now creating mirrors.ini file from current mirrors.inc...
";
require_once "mirrors_ini.php";
echo "
> Now starting HTML Help Workshop...
____________________________________________________________
";
// Run HTML Help Workshop, and move files to release directory
passthru($HELP_WORKSHOP . " $HTML_TARGET\\php_manual_$LANGUAGE.hhp");
rename("$HTML_TARGET/php_manual_$LANGUAGE.chm", "$RELEASE_DIR/php_manual_$LANGUAGE.chm");
if ($USE_NOTES) {
passthru($HELP_WORKSHOP . " $NOTES_TARGET\\php_manual_notes.hhp");
rename("$NOTES_TARGET/php_manual_notes.chm", "$RELEASE_DIR/php_manual_notes.chm");
}
// Copy PHP manual preferences, qucikref and skins files to release directory
// $RELEASE_DIR = str_replace("/", "\\", $RELEASE_DIR):
exec("copy suppfiles\\prefs $RELEASE_DIR /Y");
exec("copy suppfiles\\quickref $RELEASE_DIR /Y");
exec("xcopy suppfiles\\skins $RELEASE_DIR\\skins /S /I /Q /Y /EXCLUDE:exclude.txt");
// Delete unused files
if ($END_CLEANUP) {
echo "> Removing every file except the release files...\n";
passthru("rmdir /S /Q $HTML_SRC");
passthru("rmdir /S /Q $HTML_TARGET");
passthru("rmdir /S /Q $NOTES_SRC");
passthru("rmdir /S /Q $NOTES_TARGET");
}
// Measure time
$alltime = time() - $start_time;
echo "____________________________________________________________\n";
echo "Conversion done in " . ((int) ($alltime / 60)) . " minutes ";
echo "and " . $alltime % 60 . " seconds.\n";
echo "You can find the generated file[s] in $RELEASE_DIR directory\n";
echo "____________________________________________________________\n";
?><file_sep>/tags/xchm-13/xsl/README.txt
Status of XSL Templates in this directory
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
The only used and supported files here as of DBK XSL 1.66.1 are:
HOWTO.XSL - for generating HOW-TO with XSL
HTMLHELP.XSL - for xCHM building process
HTMLHELP-CONFIG.XSL.IN - configuration parameters for the above
COMMON.XSL - template with common options for HTMLHELP.XSL and
HOWTO.XSL (so far). Contains XSL code to tune
rendering of examples (programlisting) sections and
general function reference customizations
VERSION.XML - function to PHP version relation. Auto-generated from
the code to be found under the functable repository in
CVS or ask Hartmut =) mailto:<EMAIL>
QUICKREF.XSL - for building functions quick reference
All others are deprecated.
HTML HELP (xCHM) NOTES
~~~~~~~~~~~~~~~~~~~~~~
HTML HELP (xCHM) generated from these templates is made of three customization
layers. Some parameters in XSL templates are not customizable and sometimes you
will need to copy whole big template to make a minor customization. Next time
DocBook templates upgrade you must merge these modifications. This becomes even
worse if there will be major structural changes in XSL DocBook (not likely, but
still possible) - that way you will have to start customizations almost from
scratch. Sometimes it is much more easier to patch output code with PHP scripts.
So, the first layer is "minor" customizations of DocBook XSL templates, where
.html and HTMLHELP project files are created without major templates redefining.
It is not that only XSL parameters are set and there are no templates redefined
at all. It is programmer's point of view on if templates should be redefined in
XSL or tuned via PHP scripts. The general rule probably is simplicity in
synchronizing customization layers with DocBook ones.
Second layer consists of PHP scripts in htmlhelp/ directory and mostly used for
quick patches/fixes, search_and_replace operations, that otherwise will require
big XSL overhaul. This layer also performs a very important role - it modifies
DOM structure of raw html files produced by DocBook XSL to add dynamic features,
what are candy of xCHM. User notes, for example.
Third layer is JavaScript code. It brings life to static xCHM pages, when user
decides to read them, manages skinning issues and all that stuff that is called
DHTML.
See htmlhelp/DESCRIPTION.txt with overview of requirements for output and input
html files from each layer.
===============================================================================
This document is written by techtonik (<EMAIL>)
Contact him or the phpdoc list (<EMAIL>) if you have any questions
or suggestions...
Last modified $Date$<file_sep>/branches/gtk-docgen/scripts/online_editor/README.txt
=============================================================================
Developed by <NAME> <EMAIL>(@)<EMAIL>
Version 1.0 - essentially developed for Arabic Translation of PHP Manual
Now updated to work with all phpdoc translations
=============================================================================
This tool can be used to edit phpdoc files online. Installation requires to
have it placed accessable through web. It also requires to have a cvs checkout
of the phpdoc (both English and the desired language). Then edit the base.php to
adjust settings and you are ready to go.
CVS Update must be performed manually, same goes for cvsupdate.txt
A running version can be tested online at
www.php4arab.info/phpmanual/translation/editor/
=============================================================================
<file_sep>/tags/POST_DOCBOOK5/scripts/iniupdate/update-all
#!/bin/bash
# taken from cvs.php.net/functable by Harmut
PHP_4_CVS=PHP_4_4
PHP_5_CVS=PHP_5_1
PHP_6_CVS=HEAD
if [ ! -d sources ]
then
mkdir sources
fi
cd sources
# getting php4 releases
for release in `xargs echo < ../version4.tags`
do
if [ ! -d $release ]
then
echo fetching $release from cvs
../cvs-get-release php-src $release
else
echo $release already there
fi
done
# getting php4 latest developement snapshot
echo updating php4 cvs
cvs -q -d ":pserver:cvsread@cvs.php.net:/repository" co -d php_4_cvs -r $PHP_4_CVS php-src
# getting php5 releases
for release in `xargs echo < ../version5.tags`
do
if [ ! -d $release ]
then
echo fetching $release from cvs
../cvs-get-release php-src $release
else
echo $release already there
fi
done
# getting php5 latest developement snapshot
echo updating php5 cvs
cvs -q -d ":pserver:<EMAIL>:/repository" co -d php_5_cvs -r $PHP_5_CVS php-src
# getting php6 latest developement snapshot
echo updating php6 cvs
cvs -q -d ":pserver:cvsread@<EMAIL>.net:/repository" co -d php_6_cvs -r $PHP_6_CVS php-src
<file_sep>/tags/pre-xchm-14/htmlhelp/suppfiles/skins/HeaderNostalgia/skin.js
// This is a sample skin for the CHM edition of the PHP Manual.
// This skin should be in a "skins/headernostalgia" subdir of the folder
// containing the CHM (as assumed by the CSS and image loaders in this file)
// This skin is only here to demonstrate how to modify the layout
// and CSS properties for your working pleasure. This skin is named
// "headernostalgia" because it presents the header used in the early
// days of this edition.
// Feel free to play with this skin, the commets should help you
// to get started. Please submit any nice skins to the php-doc-chm
// mailing list <<EMAIL>>. Thanks.
// Get style sheet file
document.write(
// Get our style file
'<link rel="stylesheet" type="text/css" href="' + chmfile_path + 'skins/headernostalgia/style.css">'
);
// Display the page
function displayPage() {
// Find out if this is a function page or not
if (document.all['funcPurpose']) { funcpage = true; }
else { funcpage = false; }
// This is the path where files should be searched
skinpath = chmfile_path + 'skins/headernostalgia/';
// Build header (depends on function info)
skinBuildHeader(funcpage, skinpath);
// Remove navigational table completely
document.all['pageNav'].innerHTML = '';
// Show page container
document.all['pageContent'].style.display = 'block';
}
// Build the header of the skin
function skinBuildHeader(funcpage, skinpath)
{
// Get page elements
title = document.all['pageTitle'].innerHTML;
path = document.all['navPath'].innerHTML;
thisonline = document.all['navThisOnline'].innerHTML;
reportbug = document.all['navReportBug'].innerHTML;
// Do some reformatting to the path
path = path.replace(/:/g, "»");
// Decide what to print into online functions space
if (prefs_online) {
online_funcs = thisonline + ' | ' + reportbug;
} else {
online_funcs = "Online functions are disabled in your preferences";
}
// General table to the top of the page
pageHeader =
'<div id="navLinkPath" style="position: absolute; top: 50px; left: 154px; z-index: 2; height: 20px; visibility: visible;">' +
'<div class="navmenu"><nobr>' + path + '</nobr></div>' +
'</div>' +
'<div id="navOnlineMenu" style="position: absolute; top: 50px; left: 154px; z-index: 2; height: 20px; visibility: hidden;">' +
'<div class="navmenu"><nobr>' + online_funcs + '</nobr></div>' +
'</div>' +
'<table border="0" cellpadding="0" cellspacing="0" width="100%">' +
'<tr><td><img src="' + skinpath + 'phpdoc_php.png" width="148" height="46" border="0" usemap="#phpdoc_php"></td>' +
'<td background="' + skinpath + 'phpdoc_upback.png" height="46" width="100%" valign="middle"><nobr><h1>' + title + '</h1></nobr></td></tr>' +
'<tr><td><img src="' + skinpath + 'phpdoc_menu.png" width="148" height="23" border="0" usemap="#phpdoc_menu"></td>' +
'<td background="' + skinpath + 'phpdoc_midback.png" height="23" width="100%"> </td></tr>' +
'<tr><td><img src="' + skinpath + 'phpdoc_bellowmenu.png" width="148" height="16" border="0"></td>' +
'<td background="' + skinpath + 'phpdoc_bottomback.png" height="16" width="100%"> </td></tr></table>' +
'<map name="phpdoc_php">' +
'<area shape="rect" coords="5,1,91,44" href="index.html" alt="Manual TOC">' +
'</map>' +
'<map name="phpdoc_menu">' +
'<area shape="poly" coords="3,4,41,4,41,20,3,20,3,4" href="#" alt="Path to this page" onclick="skinShowMenu(navLinkPath, this)">' +
'<area shape="poly" coords="44,4,92,4,92,20,44,20,44,4" href="#" alt="Online functions" onclick="skinShowMenu(navOnlineMenu, this)">' +
'<area shape="poly" coords="96,4,141,4,141,20,96,20,96,4" href="#_user_notes" alt="User notes">' +
'</map>';
// If this is a function page, show those headers too
if (funcpage) {
usage = document.all['funcUsage'].innerHTML;
purpose = document.all['funcPurpose'].innerHTML;
avail = document.all['funcAvail'].innerHTML;
pageHeader +=
'<div class="funcinfo"><table class="functable">' +
'<tr><td class="funchead">Usage:</td><td>' + usage + '</td></tr>' +
'<tr><td class="funchead">Purpose:</td><td>' + purpose + '</td></tr>' +
'<tr><td class="funchead">Availability:</td><td>' + avail + '</td></tr></table></div>';
}
document.all['pageHeaders'].innerHTML = pageHeader;
actualmenu = document.all['navLinkPath'];
}
// Show one menu, and hide the actual one, if possible
function skinShowMenu(menuobj, link) {
actualmenu.style.visibility = "hidden";
actualmenu = menuobj;
actualmenu.style.visibility = "visible";
link.blur();
}<file_sep>/branches/docgen-update/scripts/docgen/includes/cli-options.php
<?php
class Docgen_Options {
protected static $option_spec = array(
'short' => array(
"e:", // Extension
"c:", // Class
"m:", // Method
"f:", // Function
"p", // Is a PECL extension
"s", // Add see-also sections
"x", // Add example sections
"i:", // Include File
"d:", // Path to phpdoc
"o:", // Output directory
"a", // Copy output to phpdoc
"t", // Test mode
"h", // Display help message
"v", // Version information
"V::", // Verbosity
"q" // Quiet
),
'long' => array(
"extension:",
"class:",
"method:",
"function:",
"pecl",
"seealso",
"example",
"include:",
"phpdoc:",
"output:",
"copy",
"test",
"help",
"version",
"verbose::",
"quiet"
),
'multiples' => array(
"e",
"c",
"m",
"f",
"i"
)
);
public static $options = array(
"extension" => null,
"class" => null,
"method" => null,
"function" => null,
"pecl" => false,
"seealso" => false,
"example" => false,
"include" => null,
"phpdoc" => null,
"output" => "./output/",
"copy" => false,
"test" => false,
"verbose" => 2
);
public static function process_options() {
$options = getopt(implode("", self::$option_spec['short']), self::$option_spec['long']);
// Conditions upon which to display the usage message and exit
if ($options === FALSE // Invalid option usage
|| empty($options)
|| (array_key_exists("h", $options)
|| array_key_exists("help", $options)) // Help is requested
) {
self::display_usage(true);
}
if (array_key_exists("v", $options)
|| array_key_exists("version", $options)
) {
self::display_version(true);
}
// Cannot be both verbose and quiet
if ((!empty($options["q"])
|| !empty($options["quiet"]))
&& (!empty($options["v"])
|| !empty($options["verbose"]))
) {
trigger_error("Option -v, --verbose and option -q, --quiet cannot be specified together.", E_USER_ERROR);
}
// Cannot copy when in test mode
if ((!empty($options["a"])
|| !empty($options["copy"]))
&& (!empty($options["t"])
|| !empty($options["test"]))
) {
trigger_error("Option -a, --copy and option -t, --test cannot be specified together.", E_USER_ERROR);
}
foreach (self::$option_spec['short'] as $index => $option) {
$shortoption = trim($option, ":");
$longoption = trim(self::$option_spec['long'][$index], ":");
// Verify that options specified multiple times support it
if ((is_array($options[$shortoption])
|| is_array($options[$longoption]))
|| (!empty($options[$shortoption])
&& !empty($options[$longoption]))
&& !in_array($shortoption, self::$option_spec['multiples'], true)
) {
trigger_error("Option -{$shortoption}, --{$longoption} does not support multiple specifications.", E_USER_ERROR);
}
// Merge options specified multiple times into single options, or just use the one that's set
if (is_array($options[$shortoption]) && is_array($options[$longoption])) {
self::$options[$longoption] = array_merge($options[$shortoption], $options[$longoption]);
} elseif (is_array($options[$shortoption]) && isset($options[$longoption])) {
$options[$shortoption][] = $option[$longoption];
self::$options[$longoption] = $options[$shortoption];
} elseif (isset($options[$shortoption]) && is_array($options[$longoption])) {
$options[$longoption][] = $option[$shortoption];
self::$options[$longoption] = $options[$longoption];
} elseif (isset($options[$shortoption]) && isset($options[$longoption])) {
self::$options[$longoption] = array($options[$shortoption], $options[$longoption]);
} elseif (isset($options[$shortoption]) || isset($options[$longoption])) { // Just one version of the option is specified
self::$options[$longoption] = isset($options[$shortoption])?$options[$shortoption]:$options[$longoption];
}
}
// Change extension names to lowercase - just makes things easier in the long run
if (is_array(self::$options["extension"])) foreach (self::$options["extension"] as &$extension) {
$extension = strtolower($extension);
}
self::validate_options();
}
public static function validate_options() {
$options =& self::$options;
// Validate job types
foreach(array("extension", "class", "method", "function") as $jobtype) {
if (!is_null($options[$jobtype])) {
if (is_array($options[$jobtype])) {
foreach ($options[$jobtype] as $index => $item) {
if (($jobtype == "extension"
&& !extension_loaded($item))
|| ($jobtype == "class"
&& !class_exists($item))
|| ($jobtype == "method"
&& $tmp = explode("::", $item)
&& count($tmp) == 2
&& method_exists($tmp[0], $tmp[1]))
|| ($jobtype == "function"
&& function_exists($item))
) {
trigger_error("The '{$item}' {$jobtype} is not loaded. Documentation will not occur for this {$jobtype}.", E_USER_WARNING);
unset($option[$jobtype][$index]);
}
}
if (empty($options[$jobtype])) $options[$jobtype] = null;
} else {
if (($jobtype == "extension"
&& !extension_loaded($options[$jobtype]))
|| ($jobtype == "class"
&& !class_exists($options[$jobtype]))
|| ($jobtype == "method"
&& $tmp = explode("::", $options[$jobtype])
&& count($tmp) == 2
&& method_exists($tmp[0], $tmp[1]))
|| ($jobtype == "function"
&& function_exists($options[$jobtype]))
) {
trigger_error("The '{$options[$jobtype]}' {$jobtype} is not loaded. Documentation will not occur for this {$jobtype}.", E_USER_WARNING);
$option[$jobtype] = null;
}
}
}
}
// Remove redundant jobs
foreach(array("extension", "class", "method", "function") as $jobtype) {
if (!is_null($options[$jobtype])) {
if (is_array($options[$jobtype])) {
foreach($options[$jobtype] as $index => $job) {
switch($jobtype) {
case "method":
$method = explode("::", $job);
$reflect = new ReflectionMethod($method[0], $method[1]);
$class = $reflect->getClassName();
if (is_array($options["class"]) && in_array($class, $options["class"])) {
unset($options[$jobtype][$index]);
} elseif ($options["class"] == $class) {
unset($options[$jobtype][$index]);
}
case "class":
if ($jobtype == "class") $reflect = new ReflectionClass($job);
case "function":
if ($jobtype == "function") $reflect = new ReflectionFunction($job);
$extension = strtolower($reflect->getExtensionName());
if (is_array($option["extension"]) && in_array($extension, $option["extension"])) {
unset($options[$jobtype][$index]);
} elseif ($options["extension"] == $extension) {
unset($options[$jobtype][$index]);
}
}
}
} else {
switch($jobtype) {
case "method":
$method = explode("::", $options[$jobtype]);
$reflect = new ReflectionMethod($method[0], $method[1]);
$class = $reflect->getClassName();
if (is_array($options["class"]) && in_array($class, $options["class"])) {
$options[$jobtype] = null;
} elseif ($options["class"] == $class) {
$options[$jobtype] = null;
}
case "class":
if ($jobtype == "class") $reflect = new ReflectionClass($options[$jobtype]);
case "function":
if ($jobtype == "function") $reflect = new ReflectionFunction($options[$jobtype]);
$extension = strtolower($reflect->getExtensionName());
if (is_array($option["extension"]) && in_array($extension, $option["extension"])) {
$options[$jobtype] = null;
} elseif ($options["extension"] == $extension) {
$options[$jobtype] = null;
}
}
}
}
}
// Verify includes exist and can be read
if (!is_null($options["include"])) {
if (is_array($options["include"])) {
foreach ($options["include"] as $index => $include) {
if(!is_readable($include)) {
trigger_error("The include '{$include}' does not exist, or is not readable. It will not be included.", E_USER_WARNING);
unset($options["include"][$index]);
}
}
} else {
if(!is_readable($options["include"])) {
trigger_error("The file '{$options["include"]}' does not exist, or is not readable. It will not be included.", E_USER_WARNING);
$options["include"] = null;
}
}
}
// Verify the specified phpdoc location exists and can be read
if (!is_null($options["phpdoc"]) && !is_readable($options["phpdoc"])) {
trigger_error("The phpdoc path '{$options["phpdoc"]}' does not exist or is not readable. It will not be analyzed or copied to.", E_USER_WARNING);
$options["phpdoc"] = null;
$options["copy"] = false;
}
// Verify that if copy is specified, the phpdoc location is specified and can be written to
if ($options["copy"] === true && is_null($options["phpdoc"])) {
trigger_error("The phpdoc location has not been specified. Files will not be copied there.");
$options["copy"] = false;
} elseif ($options["copy"] === true && !is_null($options["phpdoc"]) && !is_writeable($options["phpdoc"])) {
trigger_error("The specified phpdoc location is not writeable. Files will not be copied there.");
$options["copy"] = false;
}
// Verify that the output location is specified, and exists, or can be created, *or* test mode is enabled.
if($options["test"] === false) {
if ((!is_string($options["output"]) || empty($options["output"]))) {
trigger_error("The output directory is empty, and test mode is not enabled.", E_USER_ERROR);
} elseif (is_string($options["output"]) && !empty($options["output"]) && (!file_exists($options["output"]) && !is_writeable(dirname($options["output"])))) {
trigger_error("The output directory does not exist, and cannot be created, and test mode is not enabled.", E_USER_ERROR);
} elseif (is_string($options["output"]) && !empty($options["output"]) && file_exists($options["output"]) && !is_writeable($options["output"])) {
trigger_error("The output directory exists, but is not writeable, and test mode is not enabled.", E_USER_ERROR);
}
}
}
public static function display_usage($exit = false) {
?>
Usage: php docgen.php [OPTION]...
./docgen.php [OPTION]...
-e, --extension Generate documentation skeletons for the
specified extension(s). May be specified
multiple times.
-c, --class Generate documentation skeletons for the
specified class(es). May be specified multiple
times.
-m, --method Generate documentation skeletons for the
specified method(s). May be specified multiple
times.
-f, --function Generate documentation skeletons for the
specified function(s). May be specified multiple
times.
-p, --pecl Indicates that the generated documentation
skeletons are for a PECL extension.
-s, --seealso Includes "See also" sections in the generated
documentation skeletons.
-x, --example Includes "Example" sections in the generated
documentation skeletons.
-i, --include Includes the specified file(s) before the
documentation generation begins. May be
specified multiple times.
-d, --phpdoc Specifies the location of the manual sources,
for analysis and automatic copying of files.
-o, --output Specifies the directory to which the generated
documentation skeletons will be output. Defaults
to "./output/".
-a, --copy Copies the generated documentation skeletons
to the location of the manual sources. Requires
-d or --phpdoc be specified.
-t, --test Enables test mode. No files will be written or
copied.
-h, --help Show this message.
-v, --version Display version information.
-V, --verbose Display more output. Optionally specify 0-5 for
lowest to highest verbosity, respectively.
Defaults to 2.
-q, --quiet Suppress most output; alias for 0 verbosity.
Examples:
# Generate documentation skeletons for the "reflection" extension
php docgen.php -e reflection
# Generate documentation skeletons for the ReflectionExtension class
php docgen.php -c ReflectionExtension
# Generate documentation skeletons for the getName method of the
# ReflectionExtension class
php docgen.php -m ReflectionExtension::getName
# Generate documentation skeletons for the substr function
php docgen.php -f substr
<?php
if ($exit === true) exit;
}
public static function display_version($exit = false) {
?>
PHP Documentation Skeleton Generator
====================================
Docgen Version: <?php echo DOCGEN_VERSION; ?>
PHP Version: <?php echo phpversion(); ?>
Reflection Version: <?php echo phpversion("reflection"); ?>
DOM Version: <?php echo phpversion("dom"); ?>
<?php
if ($exit === true) exit;
}
}
<file_sep>/branches/tr/genfuncsummary
#!/bin/sh
# $Id$
for i in `find $1 -name "*.[ch]" -print -o -name "*.ec" -print | xargs egrep -li "{{{ proto"` ; do
echo $i | sed -e 's/\.\.\//# /'
awk -f funcsummary.awk < $i | sort +1 | awk -F "---" '{ print $1; print $2; }' | sed 's/^[[:space:]]+//'
done
if test -f $1/language-scanner.lex # only in PHP3
then
awk -f funcsummary.awk < $1/language-scanner.lex | sort +1 | awk -F "---" '{ print $1; print $2; }'
fi
<file_sep>/branches/docgen-update/scripts/docgen/structures/jobtypes/Docgen_FunctionJob.php
<?php
class Docgen_FunctionJob extends Docgen_Job {
public function __construct($name, $parameters = null) {
$this->reflection = new ReflectionFunction($name);
if(is_array($parameters)) $this->parameters = $parameters);
}
public function execute() {
}
}
<file_sep>/branches/gtk-docgen/scripts/cvs2svn_revchange.php
#!/usr/bin/php -q
<?php
/*
+----------------------------------------------------------------------+
| PHP Version 4 |
+----------------------------------------------------------------------+
| Copyright (c) 2009-2010 The PHP Group |
+----------------------------------------------------------------------+
| This source file is subject to version 3.0 of the PHP license, |
| that is bundled with this package in the file LICENSE, and is |
| available through the world-wide-web at the following url: |
| http://www.php.net/license/3_0.txt. |
| If you did not receive a copy of the PHP license and are unable to |
| obtain it through the world-wide-web, please send a note to |
| <EMAIL> so we can mail you a copy immediately. |
+----------------------------------------------------------------------+
| Authors: <NAME> <<EMAIL>> |
+----------------------------------------------------------------------+
$Id$
*/
if ($argc != 2) {
?>
Check the revision of translated files against the actual english xml files,
and change revision of translated files from cvs to svn
Usage:
<?php echo $argv[0]; ?> <language-code>
<language-code> must be a valid language code used
in the repository
Read more about Revision comments and related
functionality in the PHP Documentation Howto:
http://php.net/dochowto
<?php
exit;
}
// Long runtime
set_time_limit(0);
// Initializing variables from parameters
$LANG = $argv[1];
// Main directory of the PHP documentation (depends on the
// sapi used). We do need the trailing slash!
if ("cli" === php_sapi_name()) {
if (isset($PHPDOCDIR) && is_dir($PHPDOCDIR)) {
$DOCDIR = $PHPDOCDIR."/";
} else {
$DOCDIR = "./";
}
} else {
$DOCDIR = "../";
}
// =========================================================================
// Functions to get revision info and credits from a file
// =========================================================================
// Grabs the revision tag and stores credits from the file given
function get_tags($file, $val = "cvs-rev") {
// Check for English CVS revision tag
if ($val == "cvs-rev") {
$cvsrev = substr (`svn propget cvs2svn:cvs-rev $file`, 2);
return $cvsrev;
}
// Read the first 500 chars. The comment should be at
// the begining of the file
$fp = @fopen($file, "r") or die ("Unable to read $file.");
$line = fread($fp, 500);
fclose($fp);
// No match before the preg
$match = array();
// Check for English SVN revision tag
if ($val == "svn-rev") {
preg_match ("/<!-- .Revision: (\d+) . -->/", $line, $match);
return $match[1];
}
// Check for the translations "revision tag"
preg_match ("/<!--.EN-Revision:\s*.*\.?(\d+)\s*Maintainer:/U", $line, $match);
// Return with found revision number
return $match[1];
} // get_tags() function end
// =========================================================================
// Functions to check file status in translated directory, and change revision
// =========================================================================
// Checks a file, and change revision
function change_revision($file) {
global $DOCDIR, $LANG;
$en_file = preg_replace("'^".$DOCDIR.$LANG."/'", $DOCDIR."en/", $file);
// Get en file cvs revision
$cvs_rev = get_tags($en_file);
// Get en file cvs revision
$svn_rev = get_tags($en_file, "svn-rev");
// Get translated file revision
$this_rev = get_tags($file, "this-rev");
// If we have a numeric revision number (not n/a), compute rev. diff
if (is_numeric($this_rev)) {
$rev_diff = intval($cvs_rev) - intval($this_rev);
if (!$rev_diff) {
/* change revision number from cvs to svn */
$line = file_get_contents($file);
$str = "<!-- EN-Revision: $svn_rev Maintainer:";
$newline = preg_replace("/<!--.EN-Revision:\s*.\d+\.\d+\s*Maintainer:/U", $str, $line);
$fp = fopen($file, "w");
fwrite ($fp, $newline);
fclose($fp);
} elseif ($rev_diff > 0) {
/* change revision number to n/a */
$line = file_get_contents($file);
$str = "<!-- EN-Revision: n/a Maintainer:";
$newline = preg_replace("/<!--.EN-Revision:\s*.\d+\.\d+\s*Maintainer:/U", $str, $line);
$fp = fopen($file, "w");
fwrite ($fp, $newline);
fclose($fp);
} // else no touch
}
} // change_revision() function end
// =========================================================================
// A function to check directory status in translated directory
// =========================================================================
// Check the status of files in a diretory of phpdoc XML files
// The English directory is passed to this function to check
function get_dirs($dir) {
global $DOCDIR;
// Collect files and diretcories in these arrays
$directories = array();
$files = array();
// Open the directory
$handle = @opendir($dir);
// Walk through all names in the directory
while ($file = @readdir($handle)) {
if (
(!is_dir($dir.'/' .$file) && !in_array(substr($file, -3), array('xml','ent')) && substr($file, -13) != 'PHPEditBackup' )
|| strpos($file, 'entities.') === 0
|| $file == 'translation.xml'
|| $file == 'README'
|| $file == 'DO_NOT_TRANSLATE'
|| $file == 'rsusi.txt'
|| $file == 'missing-ids.xml'
|| $file == 'license.xml'
|| $file == 'versions.xml'
) {
continue;
}
if ($file != '.' && $file != '..' && $file != '.svn' && $dir != '/functions') {
if (is_dir($dir.'/' .$file)) {
$directories[] = $file;
} elseif (is_file($dir.'/' .$file)) {
$files[] = $file;
}
}
}
// Close the directory
@closedir($handle);
// Sort files and directories
sort($directories);
sort($files);
// Go through files first
foreach ($files as $file) {
change_revision($dir.$file);
}
// Then go through subdirectories
foreach ($directories as $file) {
get_dirs($dir.$file.'/');
}
} // get_dirs() function end
// =========================================================================
// Start of the program execution
// =========================================================================
// Check for directory validity
if (!@is_dir($DOCDIR . $LANG)) {
die("The $LANG language code is not valid");
}
// Get all files status
get_dirs($DOCDIR.$LANG."/");
?>
<file_sep>/branches/docgen-update/scripts/build-chms.php
<?php
/**
* +----------------------------------------------------------------------+
* | PHP Version 5 |
* +----------------------------------------------------------------------+
* | Copyright (c) 1997-2011 The PHP Group |
* +----------------------------------------------------------------------+
* | This source file is subject to version 3.01 of the PHP license, |
* | that is bundled with this package in the file LICENSE, and is |
* | available through the world-wide-web at the following url: |
* | http://www.php.net/license/3_01.txt. |
* | If you did not receive a copy of the PHP license and are unable to |
* | obtain it through the world-wide-web, please send a note to |
* | <EMAIL> so we can mail you a copy immediately. |
* +----------------------------------------------------------------------+
* | Authors: <NAME> <<EMAIL>> |
* | <NAME> <<EMAIL>> |
* +----------------------------------------------------------------------+
*
* $Id$
*/
/**
* This script is based off the original build.chms.bat
* in the root of doc-base
*/
/**
* Configuration
*
* Extended - Generates the 'enhancedchm' version along the regular ones
* Debug - If enabled, output directories are not pruned
* PhD Beta - If enabled, then PhD is treated as an svn checkout rather than a pear package
*/
define('PATH_PHP', 'C:\\php\\binaries\\PHP_5_3\\php.exe');
define('PATH_PHD', 'C:\\pear\\phd-trunk\\phd.bat');
define('PATH_HHC', 'C:\\Program Files (x86)\\HTML Help Workshop\\hhc.exe');
define('PATH_SCP', 'C:\\Program Files (x86)\\PuTTY\\pscp.exe');
define('PATH_PPK', 'C:\\php-sdk\\keys\\php-doc-host.ppk');
define('PATH_SVN', 'C:\\Program Files\\SlikSvn\\bin\\svn.exe');
define('PATH_PEAR', 'C:\\pear\\pear.bat');
define('PATH_CHM', 'C:\\doc-all\\chmfiles');
define('PATH_LOG', 'C:\\doc-all\\chmfiles\\logs');
define('PATH_DOC', 'C:\\doc-all');
define('PATH_WGET', 'C:\\php\\win32build\\bin\\wget.exe');
define('EXTENDED', true);
define('DEBUG', true);
define('PHD_BETA', true);
/**
* Fallback to a set of known languages in the event of a failure to retrieve online list.
*/
$ACTIVE_ONLINE_LANGUAGES = Array(
'en' => 'English',
'de' => 'German',
'es' => 'Spanish',
'fa' => 'Persian',
'fr' => 'French',
'ja' => 'Japanese',
'pl' => 'Polish',
'pt_BR' => 'Brazilian Portuguese',
'ro' => 'Romanian',
'tr' => 'Turkish',
'zh' => 'Chinese (Simplified)',
);
/**
* The languages to build are retrieved from https://svn.php.net/repository/web/php/trunk/include/languages.inc
*/
if (file_exists(__DIR__ . '\\languages.inc'))
{
unlink(__DIR__ . '\\languages.inc');
}
execute_task('Get list of online languages', PATH_WGET, '--debug --verbose --no-check-certificate https://svn.php.net/repository/web/php/trunk/include/languages.inc --output-document=' . __DIR__ . '\\languages.inc', 'wget_langs');
if (file_exists(__DIR__ . '\\languages.inc'))
{
include_once __DIR__ . '\\languages.inc';
}
/**
* Always build English first.
*/
unset($ACTIVE_ONLINE_LANGUAGES['en']);
ksort($ACTIVE_ONLINE_LANGUAGES);
$ACTIVE_ONLINE_LANGUAGES = array('en' => 'English') + $ACTIVE_ONLINE_LANGUAGES;
/**
* Get the current working directory
*/
$cwd = getcwd();
/**
* Upgrade PhD, if any updates are available
*/
if(PHD_BETA)
{
chdir(dirname(PATH_PHD));
execute_task('Updating PhD from svn', PATH_SVN, 'up', 'pear_svn');
chdir($cwd);
}
else
{
execute_task('Updating PhD', PATH_PEAR, 'upgrade doc.php.net/phd', 'pear');
}
/**
* Update doc-base, to prevent build errors with
* entities
*/
chdir(PATH_DOC . '\\doc-base\\');
execute_task('Updating doc-base', PATH_SVN, 'up', 'docbase');
chdir($cwd);
/**
* We may want to try build a single language
*/
if($argc >= 2 && in_array($argv[1], array_keys($ACTIVE_ONLINE_LANGUAGES)))
{
$ACTIVE_ONLINE_LANGUAGES = Array($argv[1] => $ACTIVE_ONLINE_LANGUAGES[$argv[1]]);
}
/**
* Hold the results of this build
*/
$build_history = array();
/**
* Start iterating over each translation
*/
foreach($ACTIVE_ONLINE_LANGUAGES as $lang_code => $language)
{
echo(date('r') . ' Processing language ' . $language . ' \'' . $lang_code . '\':' . PHP_EOL);
/**
* Update that specific language folder in SVN
*/
chdir(PATH_DOC . '\\' . $lang_code . '\\');
execute_task('- SVN', PATH_SVN, 'up', 'svn_' . $lang_code);
chdir($cwd);
/**
* Generate .manual-lang.xml
*/
execute_task('- Configure', PATH_PHP, PATH_DOC . '\doc-base\configure.php --disable-libxml-check --disable-segfault-speed --with-php="' . PATH_PHP . '" --with-lang=' . $lang_code . ' --enable-chm --output=' . PATH_DOC . '\\doc-base\\.manual-' . $lang_code . '.xml', 'configure_' . $lang_code);
if(!is_file(PATH_DOC . '\\doc-base\\.manual-' . $lang_code . '.xml'))
{
echo(date('r') . ' - Build error: configure failed' . PHP_EOL);
continue;
}
/**
* Run .manual.xml thru PhD, including the enhanced build if required
*/
$enhanced = (EXTENDED) ? '-f enhancedchm' : '';
execute_task('- PhD', PATH_PHD, '-d "' . PATH_DOC . '\\doc-base\\.manual-' . $lang_code . '.xml' . '" -P PHP -f chm ' . $enhanced . ' -o "' . PATH_DOC . '\\tmp\\' . $lang_code . '" --lang=' . $lang_code, 'phd_' . $lang_code);
if(!is_file(PATH_DOC . '\\tmp\\' . $lang_code . '\\php-chm\\php_manual_' . $lang_code . '.hhp'))
{
echo(date('r') . ' - Build error: PhD failed' . PHP_EOL);
continue;
}
/**
* Run the HTML Help Compiler to generate the actual CHM file
*/
execute_task('- HHC', PATH_HHC, '"' . PATH_DOC . '\\tmp\\' . $lang_code . '\\php-chm\\php_manual_' . $lang_code . '.hhp"', 'hhc_' . $lang_code);
if(!is_file(PATH_DOC . '\\tmp\\' . $lang_code . '\\php-chm\\php_manual_' . $lang_code . '.chm'))
{
echo(date('r') . ' - Build error: HHC failed' . PHP_EOL);
continue;
}
/**
* Anything smaller than ~5MB is broken. Common broken sizes are 2MB and 15K. Common good size are 10-12MB.
*/
if(filesize(PATH_DOC . '\\tmp\\' . $lang_code . '\\php-chm\\php_manual_' . $lang_code . '.chm') < 5000000)
{
echo(date('r') . ' - Build error: CHM file too small, something went wrong' . PHP_EOL);
continue;
}
/**
* Copy the CHM file into the archive
*/
if(!copy(PATH_DOC . '\\tmp\\' . $lang_code . '\\php-chm\\php_manual_' . $lang_code . '.chm', $s_CHMFilename = PATH_DOC . '\\chmfiles\\php_manual_' . $lang_code . '.chm'))
{
echo(date('r') . ' - Build error: Unable to copy CHM file into archive folder');
continue;
} else {
/**
* Add to history
*/
$build_history[] = array('php_manual_' . $lang_code . '.chm', md5_file($s_CHMFilename), filemtime($s_CHMFilename));
}
/**
* Check if we are supposed to build the enhanced version
*/
if(EXTENDED)
{
/**
* Run the HTML Help Compiler to generate the actual CHM file
*/
execute_task('- [Enhanced] HHC', PATH_HHC, '"' . PATH_DOC . '\\tmp\\' . $lang_code . '\\php-enhancedchm\\php_manual_' . $lang_code . '.hhp"', 'hhc_enhanced_' . $lang_code);
if(!is_file(PATH_DOC . '\\tmp\\' . $lang_code . '\\php-enhancedchm\\php_manual_' . $lang_code . '.chm'))
{
echo(date('r') . ' - Build error: Enhanced: HHC failed' . PHP_EOL);
goto cleanup;
}
/**
* Anything smaller than ~5MB is broken. Common broken sizes are 2MB and 15K. Common good size are 10-12MB.
*/
if(filesize(PATH_DOC . '\\tmp\\' . $lang_code . '\\php-enhancedchm\\php_manual_' . $lang_code . '.chm') < 5000000)
{
echo(date('r') . ' - Build error: Enhanced: CHM file too small, something went wrong' . PHP_EOL);
goto cleanup;
}
/**
* Copy the CHM file into the archive
*/
if(!copy(PATH_DOC . '\\tmp\\' . $lang_code . '\\php-enhancedchm\\php_manual_' . $lang_code . '.chm', $s_CHMFilename = PATH_DOC . '\\chmfiles\\php_enhanced_' . $lang_code . '.chm'))
{
echo(date('r') . ' - Build error: Enhanced: Unable to copy CHM file into archive folder');
goto cleanup;
} else {
/**
* Add to history
*/
$build_history[] = array('php_enhanced_' . $lang_code . '.chm', md5_file($s_CHMFilename), filemtime($s_CHMFilename));
}
}
/**
* Cleanup
*/
cleanup:
{
echo(date('r') . ' - Clean up' . PHP_EOL);
unlink(PATH_DOC . '\\doc-base\\.manual-' . $lang_code . '.xml');
if(!DEBUG)
{
glob_recursive_apply('fsdelete', PATH_DOC . '\\tmp\\' . $lang_code . '\\php-chm\\');
if(!EXTENDED)
{
glob_recursive_apply('fsdelete', PATH_DOC . '\\tmp\\' . $lang_code . '\\php-enhancedchm\\');
}
}
}
}
/**
* Save build history
*/
file_put_contents(PATH_DOC . '\\chmfiles\\LatestCHMBuilds.txt', implode(PHP_EOL, array_map(function($single_build){ return implode("\t", $single_build);}, $build_history)));
echo(date('r') . ' Done!');
/**
* Helper function for execution a program
*
* @param string Path to the program to execute
* @param string (optional) Parameters to pass the this call
* @param string (optional) Log output to a specific file defined here
* @return void No value is returned
*/
function execute_task($title, $program, $parameters, $log)
{
echo(date('r') . ' ' . $title . '...' . PHP_EOL);
if(empty($program))
{
return;
}
$cmd = sprintf('"%s"%s%s', $program, (!$parameters ?: ' ' . $parameters), (!$log ? '' : ' > ' . PATH_LOG . '\\' . $log . '.log 2<&1'));
@popen($cmd, 'r');
}
/**
* Removes all files within a directory and then
* deletes the directory
*
* @param callback Callback to the apply function
* @param string Glob directory to begin
* @param string (optional) The glob pattern to match on
* @return void No value is returned
*/
function glob_recursive_apply($callback, $glob_dir, $pattern = '*')
{
if(!is_dir($dir))
{
return;
}
$glob = glob($glob_dir . $pattern);
if(sizeof($glob))
{
foreach($glob as $obj)
{
call_user_func($callback, $obj, $pattern);
}
}
call_user_func($callback, $obj, $pattern);
}
/**
* Deletes a directory or file
*
* @param string Directory or filename to delete
* @param string The glob pattern to match on
* @return void No value is returned
*/
function fsdelete($obj, $pattern = '*')
{
if(is_dir($obj))
{
glob_recursive_apply('fsdelete', $obj . '\\', $pattern);
}
else
{
unlink($obj);
}
}
/**
* Gets the contents of a specific log
*
* @param string Name of the log (usually "program_lang")
* @return string Contents of the log
*/
function log_get_contents($logname)
{
return(@file_get_contents(PATH_LOG . '\\' . $log . '.log'));
}
?><file_sep>/branches/REF_STRUCT_DEV/scripts/php.ini
; This is a recommended php.ini file for the phpdoc PHP
; scripts, containing setting ideal for phpdoc scripts.
; Use this ini file with php -c /path/to/this/php.ini
[PHP]
short_open_tag = On
allow_call_time_pass_reference = Off
safe_mode = Off
max_execution_time = 0
memory_limit = 16M
display_errors = Off
display_startup_errors = Off
track_errors = Off
html_errors = Off
variables_order = "GPCS"
register_globals = On
register_argc_argv = On
default_mimetype = "text/html"
<file_sep>/branches/dev_xml/Makefile.in
# +----------------------------------------------------------------------+
# | PHP HTML Embedded Scripting Language Version 3.0 |
# +----------------------------------------------------------------------+
# | Copyright (c) 1997,1998 PHP Development Team (See Credits file) |
# +----------------------------------------------------------------------+
# | This program is free software; you can redistribute it and/or modify |
# | it under the terms of one of the following licenses: |
# | |
# | A) the GNU General Public License as published by the Free Software |
# | Foundation; either version 2 of the License, or (at your option) |
# | any later version. |
# | |
# | B) the PHP License as published by the PHP Development Team and |
# | included in the distribution in the file: LICENSE |
# | |
# | This program is distributed in the hope that it will be useful, |
# | but WITHOUT ANY WARRANTY; without even the implied warranty of |
# | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the |
# | GNU General Public License for more details. |
# | |
# | You should have received a copy of both licenses referred to here. |
# | If you did not, or have any questions about PHP licensing, please |
# | contact <EMAIL>. |
# +----------------------------------------------------------------------+
# | Authors: <NAME> <<EMAIL>> |
# +----------------------------------------------------------------------+
#
# $Id$
#
VPATH=@srcdir@
srcdir=@srcdir@
PHP_SOURCE=@PHP_SOURCE@
LANG=@LANG@
# For Suse 6.2, uncomment the CATALOG definition below.
# Also modify /usr/share/sgml/docbk30/docbook.dcl:
# change 'OMITTAG NO' to 'OMITTAG YES'
# change 'NAMELEN 44' to e.g. 'NAMELEN 54'
# CATALOG="-c /usr/share/sgml/CATALOG.docbk30"
VERSION="@PHP_VERSION@"
HTML_STYLESHEET=$(srcdir)/html.dsl
PHPWEB_STYLESHEET=$(srcdir)/phpweb.dsl
PHP_STYLESHEET=$(srcdir)/php.dsl
HOWTO_STYLESHEET=$(srcdir)/howto.dsl
PRINT_STYLESHEET=@DOCBOOK_PRINT@
all: html
PREFACE=$(LANG)/preface.xml \
$(LANG)/bookinfo.xml
APPENDICES=$(LANG)/appendices/migration.xml \
$(LANG)/appendices/escaping.xml \
$(LANG)/appendices/regexp.xml \
$(LANG)/appendices/http-stuff.xml \
$(LANG)/appendices/history.xml \
$(LANG)/appendices/debugger.xml \
$(LANG)/appendices/phpdevel.xml
CHAPTERS=$(LANG)/chapters/copyright.xml \
$(LANG)/chapters/intro.xml \
$(LANG)/chapters/config.xml \
$(LANG)/chapters/install.xml \
$(LANG)/chapters/security.xml \
$(LANG)/features/connection-handling.xml \
$(LANG)/features/file-upload.xml \
$(LANG)/features/cookies.xml \
$(LANG)/features/http-auth.xml \
$(LANG)/features/error-handling.xml \
$(LANG)/features/images.xml \
$(LANG)/features/remote-files.xml \
$(LANG)/language/basic-syntax.xml \
$(LANG)/language/operators.xml \
$(LANG)/language/constants.xml \
$(LANG)/language/types.xml \
$(LANG)/language/control-structures.xml \
$(LANG)/language/functions.xml \
$(LANG)/language/oop.xml \
$(LANG)/language/variables.xml \
$(LANG)/language/expressions.xml
FUNCREF= \
$(LANG)/functions/array.xml \
$(LANG)/functions/adabas.xml \
$(LANG)/functions/bc.xml \
$(LANG)/functions/datetime.xml \
$(LANG)/functions/dbase.xml \
$(LANG)/functions/dbm.xml \
$(LANG)/functions/dl.xml \
$(LANG)/functions/dir.xml \
$(LANG)/functions/exec.xml \
$(LANG)/functions/filepro.xml \
$(LANG)/functions/filesystem.xml \
$(LANG)/functions/ftp.xml \
$(LANG)/functions/http.xml \
$(LANG)/functions/hw.xml \
$(LANG)/functions/ibase.xml \
$(LANG)/functions/ifx.xml \
$(LANG)/functions/image.xml \
$(LANG)/functions/imap.xml \
$(LANG)/functions/ldap.xml \
$(LANG)/functions/mail.xml \
$(LANG)/functions/math.xml \
$(LANG)/functions/mcal.xml \
$(LANG)/functions/misc.xml \
$(LANG)/functions/mcrypt.xml \
$(LANG)/functions/msql.xml \
$(LANG)/functions/mysql.xml \
$(LANG)/functions/nis.xml \
$(LANG)/functions/sybase.xml \
$(LANG)/functions/network.xml \
$(LANG)/functions/oci8.xml \
$(LANG)/functions/oracle.xml \
$(LANG)/functions/pcre.xml \
$(LANG)/functions/pgsql.xml \
$(LANG)/functions/posix.xml \
$(LANG)/functions/info.xml \
$(LANG)/functions/regex.xml \
$(LANG)/functions/sem.xml \
$(LANG)/functions/session.xml \
$(LANG)/functions/solid.xml \
$(LANG)/functions/snmp.xml \
$(LANG)/functions/strings.xml \
$(LANG)/functions/uodbc.xml \
$(LANG)/functions/url.xml \
$(LANG)/functions/var.xml \
$(LANG)/functions/wddx.xml \
$(LANG)/functions/zlib.xml
FILES=$(PREFACE) $(APPENDICES) $(CHAPTERS) $(FUNCREF) global.ent chapters.ent
DIST_FILES=manual.zip manual.tar.gz manual.rtf.gz bigmanual.html.gz \
manual.prc manual.txt.gz
MIRROR_TARGETS=php/manual.php $(DIST_FILES) html/manual.html
html.dsl: html.dsl.in ./config.status
CONFIG_FILES=$@ CONFIG_HEADERS= ./config.status
print.dsl: print.dsl.in ./config.status
CONFIG_FILES=$@ CONFIG_HEADERS= ./config.status
phpweb.dsl: phpweb.dsl.in ./config.status
CONFIG_FILES=$@ CONFIG_HEADERS= ./config.status
manual.xml: manual.xml.in .manual.xml
CONFIG_FILES=$@ CONFIG_HEADERS= ./config.status
.manual.xml: $(FILES)
touch .manual.xml
html: html/manual.html
phpweb: php/manual.php
php: php/index.php
rtf: manual.rtf
dvi: manual.dvi
ps: manual.ps
pdf: manual.pdf
howto: howto.html
FORCE:
funclist.txt: FORCE
$(srcdir)/genfunclist $(PHP_SOURCE) > funclist.txt
funcsummary.txt: FORCE
$(srcdir)/genfuncsummary $(PHP_SOURCE) > funcsummary.txt
Makefile: $(srcdir)/Makefile.in ./config.status
CONFIG_FILES=$@ CONFIG_HEADERS= ./config.status
checkdoc: $(srcdir)/checkdoc.in ./config.status
CONFIG_FILES=$@ CONFIG_HEADERS= ./config.status
mirror-files: $(MIRROR_TARGETS)
sync: mirror-files
-(cd php; rsync --rsync-path=/usr/local/bin/rsync -azvc . www.php.net:/local/Web/sites/phpweb/manual/.)
-(cd html; rsync --rsync-path=/usr/local/bin/rsync -azvc . www.php.net:/local/Web/sites/phpweb/manual/html/.)
-rsync --rsync-path=/usr/local/bin/rsync -azvc $(DIST_FILES) www.php.net:/local/Web/sites/phpweb/distributions/.
snapshot: manual-snapshot.tar.gz
manual-snapshot.tar.gz: bigmanual.html html/manual.html manual.rtf manual.txt
tar -cvzf $@ bigmanual.html html/*.html manual.rtf manual.txt
status: checkdoc ./funclist.txt
$(srcdir)/checkdoc -s > $(srcdir)/status.txt
$(srcdir)/checkdoc -m > $(srcdir)/missing.txt
summary: ./funcsummary.txt
makedoc: makedoc.cc
g++ -o makedoc makedoc.cc
bigmanual.html: $(srcdir)/manual.xml $(HTML_STYLESHEET)
jade $(CATALOG) -i lang-$(LANG) -V nochunks -d $(HTML_STYLESHEET) -t sgml $(srcdir)/phpdocxml.dcl $(srcdir)/manual.xml > $@
bigmanual.html.gz: bigmanual.html
gzip -c $< > $@
manual.rtf.gz: manual.rtf
gzip -c $< > $@
manual.txt.gz: manual.txt
gzip -c $< > $@
html/manual.html: $(srcdir)/manual.xml $(HTML_STYLESHEET)
@test -d html || mkdir html
jade $(CATALOG) -i lang-$(LANG) -d $(HTML_STYLESHEET) -V use-output-dir -t sgml $(srcdir)/phpdocxml.dcl $(srcdir)/manual.xml
php/index.php: $(srcdir)/manual.xml $(PHPWEB_STYLESHEET)
@test -d php || mkdir php
-jade $(CATALOG) -i lang-$(LANG) -d $(PHP_STYLESHEET) -V use-output-dir -t sgml $(srcdir)/phpdocxml.dcl $(srcdir)/manual.xml
php/manual.php: $(srcdir)/manual.xml $(PHPWEB_STYLESHEET)
@test -d php || mkdir php
-jade $(CATALOG) -i lang-$(LANG) -d $(PHPWEB_STYLESHEET) -V use-output-dir -t sgml $(srcdir)/phpdocxml.dcl $(srcdir)/manual.xml
manual.txt: bigmanual.html
lynx -nolist -dump file:`pwd`/bigmanual.html > manual.txt
manual.prc: manual.txt makedoc
./makedoc -b manual.txt manual.prc 'PHP3 Manual'
manual.zip: $(srcdir)/html/manual.html
-rm -f $@ && (cd html; zip -9 -q ../$@ *.html)
manual.tar.gz: $(srcdir)/html/manual.html
-rm -f $@ && (cd html; tar -cf - *.html) | gzip > manual.tar.gz
howto.html: $(srcdir)/howto.xml $(HOWTO_STYLESHEET) global.ent
jade $(CATALOG) -i lang-$(LANG) -d $(HOWTO_STYLESHEET) -t sgml $(srcdir)/phpdocxml.dcl $(srcdir)/howto.xml
tex latex: $(srcdir)/manual.tex
# File endings we are going to define general rules for:
.SUFFIXES: .html .xml .sgml .tex .dvi .ps .rtf
# General rules:
.xml.tex:
jade $(CATALOG) -i lang-$(LANG) -d $(PRINT_STYLESHEET) -t tex $(srcdir)/phpdocxml.dcl $<
.xml.rtf:
jade $(CATALOG) -i lang-$(LANG) -d $(PRINT_STYLESHEET) -t rtf $(srcdir)/phpdocxml.dcl $<
# runs three times -
# 1. generates the dvi with a completely bogus table of contents
# 2. generates the dvi with a table of contents that is off based on the size
# of the table of contents
# 3. generates a dvi with all the right page numbers and such
.tex.dvi:
jadetex $<
jadetex $<
jadetex $<
.dvi.ps:
dvips -o $@ $<
.ps.pdf:
ps2pdf -p $@ $<
test: manual.xml
nsgmls -i lang-$(LANG) -s $(srcdir)/phpdocxml.dcl $<
clean:
( \
cd $(srcdir); \
rm -rf html php; \
rm -f manual.txt [a-z]*.html manual.rtf manual.info \
rm -f manual.zip manual.tar.gz sync-no commit-no .manual.xml \
rm -f manual.prc makedoc *.manifest \
rm -f *.aux *.tex *.log *.dvi *.toc *.ps \
rm -f funclist.txt funcsummary.txt status.txt missing.txt checkdoc \
)
<file_sep>/branches/dev_docbook4/make_chm_fancy.php
<?php
// This script takes much time to run
set_time_limit(0);
// Get ENV vars from the system
$htmldir = getenv("PHP_HELP_COMPILE_DIR");
$fancydir = getenv("PHP_HELP_COMPILE_FANCYDIR");
$language = getenv("PHP_HELP_COMPILE_LANG");
$original_index = "index.html";
// How many files were processed
$counter = 0;
// Open the directory, and do the work on all HTML files
$handle = opendir($htmldir);
while (false !== ($filename = readdir($handle))) {
if (strpos($filename, ".html") && ($filename != "fancy-index.html")) {
fancy_design($filename);
}
}
closedir($handle);
// Look for CHM index file (snap-downloader, cvs-usr with/without lang-support)
if (false == ($content = join("", @file("make_chm_index_$language.html")))) {
if (false == ($content = join("", @file("$language/make_chm_index_$language.html")))) {
$content = join("", @file("en/make_chm_index_en.html"));
}
}
// Make GENTIME the actual date/time
$content = str_replace("[GENTIME]", date("D M d H:i:s Y"), $content);
$content = str_replace("[PUBTIME]", $publication_date, $content);
$fp = fopen("$fancydir/fancy-index.html", "w");
fputs($fp, $content);
fclose($fp);
copy("make_chm_style.css", "$fancydir/style.css");
copy("make_chm_spc.gif", "$fancydir/spacer.gif");
// Three files added (fancy-index.html, style.css and spacer.gif)
$counter += 3;
echo "\nConverting ready...\n";
echo "Total number of files written in $fancydir directory: $counter\n\n";
/***********************************************************************/
/* End of script lines, one main function follows */
/***********************************************************************/
// Convert one file from HTML => fancy HTML
function fancy_design($fname)
{
global $htmldir, $fancydir, $counter, $original_index, $publication_date;
// Get the contents of the file from $htmldir
$content = join("", file("$htmldir/$fname"));
// CSS file linking
$content = preg_replace("|</HEAD|", '<LINK REL="stylesheet" HREF="style.css"></HEAD', $content);
// No margins around
$content = preg_replace("/<BODY/", '<BODY TOPMARGIN="0" LEFTMARGIN="0"', $content);
// HR dropout
$content = preg_replace("/<HR\\s+ALIGN=\"LEFT\"\\s+WIDTH=\"100%\">/", '', $content);
// Whole page table and backgrounds
$wpbegin = '<TABLE BORDER="0" WIDTH="100%" HEIGHT="100%" CELLSPACING="0" CELLPADDING="0"><TR><TD COLSPAN="3">';
$bnavt = '<TABLE BGCOLOR="#CCCCFF" BORDER="0" CELLPADDING="0" CELLSPACING="0" WIDTH="100%">';
$lnavt = '<TR BGCOLOR="#333366"><TD><IMG SRC="spacer.gif" BORDER="0" WIDTH="1" HEIGHT="1"><BR></TD></TR>';
$space = '<IMG SRC="spacer.gif" WIDTH="10" HEIGHT="1">';
// Navheader backgound
$content = preg_replace("/<DIV\\s+CLASS=\"NAVHEADER\"\\s+><TABLE(.*)CELLPADDING=\"0\"(.*)<\\/TABLE\\s+><\\/DIV\\s+>/Us",
$wpbegin . '<DIV CLASS="NAVHEADER">' . $bnavt . '<TR><TD><TABLE\\1CELLPADDING="3"\\2</TABLE></TD></TR>' . $lnavt . '</TABLE></DIV></TD></TR><TR><TD>' . $space . '</TD><TD HEIGHT="100%" VALIGN="TOP" WIDTH="100%"><BR>', $content);
// Navfooter backgound
$content = preg_replace("/<DIV\\s+CLASS=\"NAVFOOTER\"\\s+><TABLE(.*)CELLPADDING=\"0\"(.*)<\\/TABLE\\s+><\\/DIV\\s+>/Us",
'<BR></TD><TD>' . $space . '</TD></TR><TR><TD COLSPAN="3"><DIV CLASS="NAVFOOTER">' . $bnavt . $lnavt . '<TR><TD><TABLE\\1CELLPADDING="3"\\2</TABLE></TD></TR></TABLE></DIV></TD></TR></TABLE>', $content);
// Fix copyright page fault...
if ($fname == "copyright.html") {
$content = preg_replace("/&copy;/", "©", $content);
$content = preg_replace("/<A\\s+HREF=\"$original_index#(authors|translators)\"/U", "<A HREF=\"fancy-index.html\"", $content);
$content = preg_replace("|(</TH\\s+></TR\\s+>)|", "\\1<TR><TH COLSPAN=\"3\" ALIGN=\"center\"> </TH></TR>", $content);
$content = preg_replace("|( </TD\\s+></TR\\s+>)|", "\\1<TR><TD COLSPAN=\"3\" ALIGN=\"center\"> </TD></TR>", $content);
}
// Fix the original manual index to look far better...
elseif ($fname == "$original_index") {
// Find out manual generation date
if (preg_match('|<P\s+CLASS="pubdate"\s+>([\\d-]+)<BR></P\s+>|U', $content, $match)) {
$publication_date = $match[1];
} else {
$publication_date = 'n/a';
}
// Modify the index file to meet our needs
preg_match('|CLASS=\"title\"\\s+><A\\s+NAME=\"manual\"\\s+>(.*)</A\\s+></H1|U', $content, $match);
$indexchange = '<TABLE BORDER="0" WIDTH="100%" HEIGHT="100%" CELLSPACING="0" CELLPADDING="0"><TR><TD COLSPAN="3"><DIV CLASS="NAVHEADER"><TABLE BGCOLOR="#CCCCFF" BORDER="0" CELLPADDING="0" CELLSPACING="0" WIDTH="100%"><TR><TD><TABLE
WIDTH="100%" BORDER="0" CELLPADDING="3" CELLSPACING="0"><TR><TH COLSPAN="3">'.$match[1].'</TH></TR><TR><TD COLSPAN="3" ALIGN="center"> </TD></TR></TABLE></TD></TR><TR BGCOLOR="#333366"><TD><IMG SRC="spacer.gif" BORDER="0" WIDTH="1" HEIGHT="1"><BR></TD></TR></TABLE>
</DIV></TD></TR><TR><TD><IMG SRC="spacer.gif" WIDTH="10" HEIGHT="1"></TD><TD HEIGHT="100%" VALIGN="TOP" WIDTH="100%"><BR>';
$content = preg_replace("/(<DIV\\s+CLASS=\"BOOK\")/", "$indexchange\\1", $content);
$content = preg_replace("/(<DIV\\s+CLASS=\"author\").*<HR>/Us", "", $content);
preg_match('|<DIV\\s+CLASS="TOC"\\s+><DL\\s+><DT\\s+><B\\s+>(.*)</B\\s+>|U', $content, $match);
$content = preg_replace("|(CLASS=\"title\"\\s+><A\\s+NAME=\"manual\"\\s+>).*(</A)|U", "\\1$match[1]\\2", $content);
$content = preg_replace("|<DT\\s+><B\\s+>(.*)</B\\s+></DT\\s+>|U", "", $content);
}
// Print out that new file to $fancydir
$fp = fopen("$fancydir/$fname", "w");
fputs($fp, $content);
fclose($fp);
// Print out a message to see the progress
echo "$fancydir/$fname ready...\n";
$counter++;
} // fancy_design() function end
?>
<file_sep>/branches/tr/make_chm.php
<?php
// USE ONLY PHP 4.x TO RUN THIS SCRIPT!!!
// IT WONT WORK WITH PHP 3
// SEE make_chm.README FOR INFORMATION!!!
$fancydir = getenv("PHP_HELP_COMPILE_FANCYDIR");
if(empty($fancydir))
{
$fancydir = getenv("PHP_HELP_COMPILE_DIR");
}
$language = getenv("PHP_HELP_COMPILE_LANG");
$original_index = getenv("PHP_HELP_COMPILE_INDEX");
// header for index and toc
$header = "
<!DOCTYPE HTML PUBLIC \"-//IETF//DTD HTML//EN\">
<HTML>
<HEAD>
<meta name=\"GENERATOR\" content=\"PHP 4 - Auto TOC script\">
<!-- Sitemap 1.0 -->
</HEAD>
<BODY>
<OBJECT type=\"text/site properties\">
<param name=\"Window Styles\" value=\"0x800227\">
</OBJECT>
<UL>
";
MakeProjectFile();
MakeContentFiles();
/* end */
/* functions */
function MakeContentFiles()
{
global $fancydir, $language, $manual_title, $fancyindex, $indexfile, $original_index, $header;
$toc = fopen("manual-$language.hhc", "w");
$index = fopen("manual-$language.hhk", "w");
fputs($toc, $header);
fputs($index, $header);
$index_a = file("$fancydir/$original_index");
$ijoin = join("", $index_a);
$ijoin = preg_replace("/[\r|\n]{1,2}/", " ", $ijoin);
// print out the objects, that autoparsing wont find
// some automation may be there in the future
SiteMapObj($manual_title, $indexfile, " ", $toc, 21);
IndexObj($manual_title, $indexfile, $index);
if($fancyindex)
{
preg_match('|CLASS=\"title\" ><A NAME=\"manual\" >(.*)</A|U', $ijoin, $match);
if(empty($match[1]))
{
// fallback
$match[1]="Table of Contents";
}
SiteMapObj($match[1], $original_index, " ", $toc, 21);
IndexObj($match[1], $original_index, $index);
}
preg_match('|<A HREF="preface.html" >(.*)</A >|U', $ijoin, $match);
if(empty($match[1]))
{
// fallback
$match[1]="Preface";
}
SiteMapObj($match[1], "preface.html", " ", $toc);
IndexObj($match[1], "preface.html", $index);
fputs($toc, "\n <UL>");
preg_match('|<A HREF="preface.html#about" >(.*)</A >|U', $ijoin, $match);
if(empty($match[1]))
{
// fallback
$match[1]="About this Manual";
}
SiteMapObj($match[1], "preface.html#about", " ", $toc);
IndexObj($match[1], "preface.html#about", $index);
fputs($toc, " </UL>\n");
// now autofind the chapters/subchapters
$not_closed = 0;
for($i = 0; $i < count ($index_a); $i++)
{
/* Chapters */
if(ereg(">[IVX]+\.\ <A", $index_a[$i]) && !ereg("HREF=\"ref\.[a-z0-9]+\.html", $index_a[$i+1]))
{
$new_list = 1;
if($not_closed == 1)
{
fputs($toc, "\n </UL>\n");
}
//preg_match ("/>([IVX]+)\. <A/", $index_a[$i], $matches);
//$chapter["nr"] = $matches[1];
preg_match("/HREF=\"([a-z0-9-]+\.html)(\#[a-z0-9]+)?\"/", $index_a[$i+1], $matches);
$chapter["html"] = $matches[1];
preg_match("/>([^<]+)/", $index_a[$i+2], $matches);
$chapter["title"] = $matches[1];
SiteMapObj($chapter["title"], $chapter["html"], " ", $toc);
IndexObj($chapter["title"], $chapter["html"], $index);
}
/* Sub chapters */
else if(ereg(">([0-9]+|[IVXL]+|[A-Z])\.\ <A", $index_a[$i]))
{
if($new_list == 1)
{
$new_list = 0;
$not_closed = 1;
fputs($toc, "\n <UL>\n");
}
//preg_match ("/>([0-9]+|[IVXL]+|[A-Z])\. <A/", $index_a[$i], $matches);
//$schapter["nr"] = $matches[1];
preg_match("/HREF=\"([a-z0-9-]+\.([a-z0-9-]+\.)?html)(\#[a-z0-9]+)?\"/", $index_a[$i+1], $matches);
$schapter["html"] = $matches[1];
preg_match("/>([^<]+)/", $index_a[$i+2], $matches);
$schapter["title"] = $matches[1];
SiteMapObj($schapter["title"], $schapter["html"], " ", $toc);
IndexObj($chapter["title"], $schapter["html"], $index);
DoFile($schapter["html"], $toc, $index);
}
}
fputs($toc, " </UL>\n");
// link in directly the copyright page
$cjoin = join("", file("$fancydir/copyright.html"));
$cjoin = preg_replace("/[\r|\n]{1,2}/", " ", $cjoin);
preg_match('|<A NAME="copyright" ></A ><P ><B >(.*)</B|U', $cjoin, $match);
if(empty($match[1]))
{
// fallback
$match[1]="Copyright";
}
SiteMapObj($match[1], "copyright.html", " ", $toc, 17);
IndexObj($match[1], "copyright.html", $index);
fputs($index, "</UL>\n</BODY></HTML>");
fputs($toc, "</UL>\n</BODY></HTML>");
fclose($index);
fclose($toc);
}
function MakeProjectFile()
{
global $fancydir, $language, $manual_title, $fancyindex, $indexfile, $original_index;
// define language array (manual code -> HTML Help Code)
// Japanese is not on my list, I don't know why...
$languages = array(
"cs" => "0x405 Czech",
"de" => "0x407 German (Germany)",
"en" => "0x809 Enlish (United Kingdom)",
"es" => "0xc0a Spanish (International Sort)",
"fr" => "0x40c French (France)",
"hu" => "0x40e Hungarian",
"it" => "0x410 Italian (Italy)",
"ja" => "0x411 Japanese",
"kr" => "0x412 Korean",
"nl" => "0x413 Dutch (Netherlands)",
"pt_BR" => "0x416 Portuguese (Brazil)"
);
if(file_exists("$fancydir/fancy-index.html"))
{
$fancyindex = TRUE;
$indexfile = "fancy-index.html";
}
else
{
$indexfile = $original_index;
}
// Start writing the project file
$project = fopen("manual-$language.hhp", "w");
fputs($project, "[OPTIONS]\n");
fputs($project, "Compatibility=1.1 or later\n");
fputs($project, "Compiled file=manual-$language-" . date("Ymd") . ".chm\n");
fputs($project, "Contents file=manual-$language.hhc\n");
fputs($project, "Index file=manual-$language.hhk\n");
fputs($project, "Default Font=Arial,10,0\n");
fputs($project, "Default Window=phpdoc\n");
fputs($project, "Default topic=$fancydir\\$indexfile\n");
fputs($project, "Display compile progress=Yes\n");
fputs($project, "Full-text search=Yes\n");
// get the proper language code from the array
fputs($project, "Language=" . $languages[$language] . "\n");
// now try to find out how the manual named in the actual language
// this must be in the manual.html file as the title (DSSSL generated)
$content = join("", file("$fancydir/$original_index"));
if(preg_match("|>(.*)</TITLE|U", $content, $found))
{
$manual_title = $found[1];
}
else
{
$manual_title = "PHP Manual";
}
fputs($project, "Title=$manual_title\n");
// define the phpdoc window style (adds more functionality)
fputs($project, "\n[WINDOWS]\nphpdoc=\"$manual_title\",\"manual-$language.hhc\",\"manual-$language.hhk\"," .
"\"$fancydir\\$indexfile\",\"$fancydir\\$indexfile\",,,,,0x23520,,0x386e,,,,,,,,0\n");
// write out all the filenames as in $fancydir
fputs($project, "\n[FILES]\n");
$handle=opendir($fancydir);
while(false!==($file = readdir($handle)))
{
if($file != "." && $file != "..")
{
fputs($project, "$fancydir\\$file\n");
}
}
closedir($handle);
fclose($project);
}
function SiteMapObj($name, $local, $tabs, $toc, $imgnum = "auto")
{
global $fancydir;
/* should not be needed because if the documentation is valid xhtml $name would already
* be html encoded.
*/
// $name = htmlentities($name);
fputs($toc, "\n$tabs<LI> <OBJECT type=\"text/sitemap\">
$tabs <param name=\"Name\" value=\"$name\">
$tabs <param name=\"Local\" value=\"$fancydir\\$local\">");
if($imgnum != "auto")
{
fputs($toc, "\n$tabs <param name=\"ImageNumber\" value=\"$imgnum\">");
}
fputs($toc, "\n$tabs </OBJECT>\n");
}
function IndexObj($name, $local, $index)
{
global $fancydir;
/* should not be needed because if the documentation is valid xhtml $name would already
* be html encoded.
*/
// $name = htmlentities($name);
fputs($index, "\n<LI><OBJECT type=\"text/sitemap\">
<param name=\"Local\" value=\"$fancydir\\$local\">
<param name=\"Name\" value=\"$name\">
</OBJECT></LI>");
}
function DoFile ($filename, $toc, $index)
{
global $fancydir;
fputs($toc, " <UL>");
$content = file ("$fancydir/$filename");
for($i = 0; $i < count ($content); $i++)
{
if(ereg ("><DT", $content[$i]) &&
ereg ("><A", $content[$i+1]) &&
ereg ("HREF=\"([a-z0-9-]+\.)+html(\#[0-9a-z\.-]+)?\"", $content[$i+2]))
{
preg_match ("/HREF=\"(([0-9a-z-]+\.)+html)(\#[0-9a-z\.-]+)?\"/", $content[$i+2], $matches);
$param["html"] = $matches[1];
if(isset($matches[3]))
{
$param["html"] .= $matches[3];
}
if(ereg ("CLASS=\"literal\"", $content[$i+4]))
{
preg_match ("/>([^<]+)/", $content[$i+5], $matches);
}
else if($content[$i+2] == $content[$i+4])
{
preg_match ("/>([^<]+)/", $content[$i+7], $matches);
}
else
{
preg_match ("/>([^<]+)/", $content[$i+3], $matches);
}
$param["title"] = $matches[1];
SiteMapObj($param["title"], $param["html"], " ", $toc);
IndexObj($param["title"], $param["html"], $index);
}
}
fputs($toc, " </UL>\n");
}
?>
<file_sep>/tags/BEFORE_STRUCT_REF_DEV_MERGE/scripts/genfuncindex.php
<?php
/*
+----------------------------------------------------------------------+
| PHP Version 4 |
+----------------------------------------------------------------------+
| Copyright (c) 1997-2004 The PHP Group |
+----------------------------------------------------------------------+
| This source file is subject to version 3.0 of the PHP license, |
| that is bundled with this package in the file LICENSE, and is |
| available through the world-wide-web at the following url: |
| http://www.php.net/license/3_0.txt. |
| If you did not receive a copy of the PHP license and are unable to |
| obtain it through the world-wide-web, please send a note to |
| <EMAIL> so we can mail you a copy immediately. |
+----------------------------------------------------------------------+
| Authors: <NAME> <<EMAIL>> |
+----------------------------------------------------------------------+
$Id$
*/
echo "<" . "?xml version='1.0' encoding='iso-8859-1'?" . ">\n";
?>
<!-- DO NOT EDIT THIS FILE, IT WAS AUTO-GENERATED BY genfuncindex.php -->
<appendix xmlns="http://docbook.org/ns/docbook" xml:id="indexes">
<title>&FunctionIndex;</title>
<index xml:id="index.functions">
<title>&FunctionIndex;</title>
<?php
$functions = file($_SERVER['argv'][1]);
usort($functions,"strcasecmp");
$letter = ' ';
foreach ( $functions as $funcentry ) {
list($function,$description) = explode(" - ",$funcentry);
if (!ereg("::|->", $function)) {
$function = strtolower(trim($function));
}
$function = str_replace('>', '>', $function);
if (strtolower($function{0}) != $letter) {
if ($letter != ' ') {
echo " </indexdiv>\n";
}
$letter = strtolower($function{0});
echo " <indexdiv>\n";
echo " <title>".strtoupper($letter)."</title>\n";
}
echo " <indexentry><primaryie><function>$function</function></primaryie></indexentry>\n";
}
?>
</indexdiv>
</index>
<para></para>
</appendix>
<file_sep>/branches/dev_docbook4/scripts/add_rev.php
<?php
function apply($input)
{
return "<?xml encoding="iso-8859-1"?>\n<!-- \$Revision$ -->\n$input";
}
<file_sep>/tags/BEFORE_STRUCT_REF_DEV_MERGE/scripts/quickref/originalafter.js
'; //'
// Initialisation --------------------------------------------------------------
// how many matches to show at most (must be even!)
fh_showmatches=29;
var _d=document;
var isnotopera=true;
fh_matches=new Array();
fh_inmenu=fh_menupos=0;
fh_matchesjoined="";
fh_currenttext="";
// form shortcuts and autocomplete setting on input field
var f_p=_d.forms[0].pattern;
var f_s=_d.forms[0].show;
fh_EDropDownChange();
// Layer setup -----------------------------------------------------------------
if (_d.all && (isnotopera=(navigator.userAgent.toLowerCase().indexOf("opera")==-1))) {
width="width:165px";
} else {
isnotopera=true;
width="min-width:155px";
}
var funchelper = _d.createElement('div');
funchelper.setAttribute('style', 'background-color: white; border: 1px solid black; top: 90px;'+width+'; padding: 4px; font-size: 9px; display:none; position:absolute;');
var elems = _d.getElementsByTagName("*");
for (var i = 0; i < elems.length; i++) {
if (elems[i].tagName.toLowerCase() == 'body') {
elems[i].appendChild(funchelper);
break;
}
}
// Decompression ---------------------------------------------------------------
dcp=dcp.split("}");
for(a=0; a<dcp.length; a++) {
cpd=cpd.split(dcp[a].charAt(0)).join(dcp[a].substring(1,9));
}
function l(a) { return a[a.length-1]; }
fcl=new Array(); pst=new Array(""); ac="";
for (pos=0; pos<cpd.length; pos++) {
switch (ch=cpd.charAt(pos)) {
case ',': fcl[fcl.length]=l(pst)+ac; ac=""; break;
case '(': pst[pst.length]=l(pst)+ac; ac=""; break;
case ')': case ']': if(ac.length)fcl[fcl.length]=l(pst)+ac; ac=""; pst.length--; break;
case '[': fcl[fcl.length]=(a=l(pst)+ac); pst[pst.length]=a; ac=""; break;
default: ac=ac+ch;
}
}
// Functions -------------------------------------------------------------------
function ElLeft(eE)
{
var DL_bIE=_d.all?true:false;
var nLP=eE.offsetLeft;
var ePE=eE.offsetParent;
while (ePE!=null) {
if (DL_bIE) {
if (ePE.tagName=="TD") nLP+=ePE.clientLeft;
} else {
if (ePE.tagName=="TABLE") {
var nPB=parseInt(ePE.border);
if (isNaN(nPB)) {
var nPF=ePE.getAttribute('frame');
if (nPF!=null) nLeftPos+=1;
} else if (nPB>0) nLP+=nPB;
}
}
nLP+=ePE.offsetLeft;
ePE=ePE.offsetParent;
}
return nLP;
}
function fh_IsMatch(idx,pr)
{
if (fcl[idx].substring(0,pr.length)==pr) return true;
return false;
}
function fh_FindMatches(pr)
{
f=0;
l=fcl.length-1;
m=(f+l)>>1;
while(f<l) {
if (fcl[m]==pr) break;
if (fcl[m]<pr) f=m; else l=m;
nm=(f+l+1)>>1;
if (m==nm) break;
m=nm;
}
if (m&&fh_IsMatch(m-1,pr)) m--;
if (!fh_IsMatch(m,pr) && m<(fcl.length-1) && fh_IsMatch(m+1,pr)) m++;
res=new Array;
while (m<fcl.length && fh_IsMatch(m,pr)) res[res.length]=fcl[m++];
return res;
}
function fh_Show(what)
{
ts=funchelper.style;
if (what=="") {
if (ts.display!="none") ts.display="none";
} else {
ts.display="block";
ts.left=ElLeft(f_p)+"px";
funchelper.innerHTML=what;
}
}
function fh_HideAll()
{
fh_matches=new Array();
fh_matchesjoined="";
fh_inmenu=fh_menupos=0;
fh_Show("");
}
function fh_ShowNoMatch()
{
fh_Show("<font color=\"gray\">No such function</font>");
}
function fh_UpdateMenu()
{
flen=fh_matches.length;
if (flen<=fh_showmatches) {
beforedots=first=afterdots=0;
last=flen-1;
} else {
if (fh_inmenu) {
mid=fh_showmatches>>1;
if (fh_menupos<=mid) beforedots=first=0;
else {
beforedots=1;
first=fh_menupos-mid+1;
if (first>(flen-fh_showmatches+1)) first=flen-fh_showmatches+1;
}
if (fh_menupos>=(flen-mid-1)) {
afterdots=0;
last=flen-1;
} else {
afterdots=1;
last=fh_menupos+mid-1;
if (last<(fh_showmatches-2)) last=fh_showmatches-2;
}
} else {
first=beforedots=0;
last=fh_showmatches-2;
afterdots=1;
}
}
zh="";
if (beforedots) zh=zh+"...<br />";
for (pos=first; pos<=last; pos++) {
f=fh_matches[pos];
zh=zh+"<a href=\"/"+f+
"\" style=\"text-decoration:none;"+
(fh_inmenu&&fh_menupos==pos?"background-color:rgb(204,204,255);":"")+"\">"+f+"</a><br />";
}
if (afterdots) zh=zh+"...";
fh_Show(zh);
if (fh_inmenu) f_p.value=fh_matches[fh_menupos];
}
function fh_NewText()
{
t=f_p.value;
if (t=="") {
fh_HideAll();
return;
}
tmpmatches=fh_FindMatches(t);
if (tmpmatches.length==0) {
fh_matchesjoined="";
fh_ShowNoMatch();
return;
}
if (tmpmatches.join(",")==fh_matchesjoined) return; // do nothing
fh_inmenu=fh_menupos=0;
fh_matchesjoined=tmpmatches.join(",");
fh_matches=tmpmatches;
fh_UpdateMenu();
}
function fh_EFocus()
{
if (f_s.value=="quickref") {fh_NewText();}
}
// Timeout, so the user can click on a link before it disappears
function fh_EBlur() { setTimeout("fh_HideAll()", 200); }
function fh_EKeyPress(ev)
{
ev=ev||event||null;
if (f_s.value=="quickref"&&ev) {
var cc=ev.charCode||ev.keyCode||ev.which;
if (cc==32) {
f_p.value = f_p.value.replace(/\s/g, "");
return false;
}
//if ((cc>=97&&cc<=122)||(cc>=65&&cc<=90)||(cc>=48&&cc<=57)||cc==95) return true; // a-z A-Z 0-9 _
}
return true;
}
function fh_EKeyDown(ev)
{
ev=ev||event||null;
if (f_s.value=="quickref"&&ev&&fh_matches.length>0) {
var cc=ev.charCode||ev.keyCode||ev.which;
if (cc==38||cc==57385) { // up
if (fh_inmenu) {
if (--fh_menupos<0) fh_menupos=fh_matches.length-1;
} else {
fh_inmenu=1;
fh_menupos=fh_matches.length-1;
}
fh_UpdateMenu();
return false;
}
if (cc==40||cc==57386) { // down
if (fh_inmenu) {
if (++fh_menupos>=fh_matches.length) fh_menupos=0;
} else {
fh_inmenu=1;
fh_menupos=0;
}
fh_UpdateMenu();
return false;
}
if (cc==32) { // spacebar autocomplete
if ((p=f_p.value)=="") return false;
matches=fh_FindMatches(p);
if (matches.length==0) return false;
if (matches.length==1) { // full autocomplete in case of single match
f_p.value=matches[0];
return false;
}
if (isnotopera) {
len=0;
first=matches[0];
last=matches[matches.length-1]; matches.length--;
while (len<first.length && first.substring(0,len+1)==last.substring(0,len+1)) len++;
if (f_p.value!=first.substring(0,len)) {
f_p.value=first.substring(0,len);
}
}
return false;
}
}
return true;
}
function fh_EKeyUp(ev)
{
ev=ev||event||null;
if (f_s.value=="quickref"&&ev) {
var cc=ev.charCode||ev.keyCode||ev.which;
if (cc==38||cc==40||cc==57385||cc==57386) return false;
if (f_p.value!=fh_currenttext) {
fh_currenttext=f_p.value;
fh_NewText();
}
}
return true;
}
// turn off browser's built in autocomplete if in quickref mode
function fh_EDropDownChange(ev)
{
if(f_s.value=="quickref") {
f_p.setAttribute("autocomplete", "off");
} else {
f_p.setAttribute("autocomplete", "on");
}
}
// Event listener setup --------------------------------------------------------
f_p.onkeypress=fh_EKeyPress;
f_p.onfocus=fh_EFocus;
f_p.onblur=fh_EBlur;
f_p.onkeydown=fh_EKeyDown;
f_p.onkeyup=fh_EKeyUp;
f_s.onchange=fh_EDropDownChange;
<file_sep>/tags/dev_docbook4_branchpoint/make_man.php
#!/usr/local/bin/php -q
<?php
/*
* Script to convert (most of the) php documentation from docbook to unix man format.
* <NAME> - <EMAIL> - 20010413
* No long license statements here - do whatever you want.
*/
/*
* Problems:
* - examples are not shown correctly
*/
$lang = 'en';
$file = `cat \`find $lang | grep .xml\``;
#$file = str_replace("\n", '', $file);
// First get everything in <refentry></refentry> tags
preg_match_all('/<refentry.*?<\/refentry>/s', $file, $refentries);
$functions = array();
$i = 0;
foreach($refentries[0] as $refentry) {
preg_match('/<refname>(.*)<\/refname>/s', $refentry, $matches);
if(!empty($matches[1])) {
$functions[$i]['name'] = $matches[1];
} else {
$functions[$i]['name'] = '';
}
preg_match('/<refpurpose>(.*)<\/refpurpose>/s', $refentry, $matches);
if(!empty($matches[1])) {
$functions[$i]['shortdesc'] = $matches[1];
} else {
$functions[$i]['shortdesc'] = '';
}
preg_match('/<funcprototype>(.*)<\/funcprototype>/s', $refentry, $matches);
if(!empty($matches[1])) {
$funcprototype = $matches[1];
} else {
$funcprototype = '';
}
preg_match('/<funcdef>(.*)<\/funcdef>/s', $funcprototype, $matches);
if(!empty($matches[1])) {
$functions[$i]['prototype'] = $matches[1];
$functions[$i]['prototype'] = preg_replace('/<.*?>/s', '', $functions[$i]['prototype']);
$functions[$i]['prototype'] .= '(';
} else {
$functions[$i]['prototype'] = '';
}
preg_match_all('/<paramdef>.*?<\/paramdef>/s', $funcprototype, $matches);
$first = 1;
foreach($matches[0] as $param) {
if(preg_match('/<optional>.*<\/optional>/s', $param)) {
if($first != 1 ) {
$functions[$i]['prototype'] .= ' [, ' . trim(preg_replace('/<.*?>/s', '', $param)) . ']';
} else {
$functions[$i]['prototype'] .= ' [' . trim(preg_replace('/<.*?>/s', '', $param)) . ']';
$first = 0;
}
} else {
if($first != 1 ) {
$functions[$i]['prototype'] .= ', ';
} else {
$first = 0;
}
$functions[$i]['prototype'] .= trim(preg_replace('/<.*?>/s', '', $param));
}
}
$functions[$i]['prototype'] = preg_replace('/\n/', '', $functions[$i]['prototype']);
$functions[$i]['prototype'] = preg_replace('/\s{2,}/s', ' ', $functions[$i]['prototype']);
$functions[$i]['prototype'] .= ')';
$y = 0;
preg_match_all('/<para>.*?<\/para>/s', $refentry, $matches);
foreach($matches[0] as $paragraph) {
if(preg_match('/<example>/s', $paragraph)) {
// If this paragraph has an example, do some special formatting.
preg_match('/<title>(.*)<\/title>/s', $paragraph, $tmp);
$functions[$i]['example'] = $tmp[1];
$functions[$i]['example'] = preg_replace('/\s{2,}/', ' ', $functions[$i]['example']);
$functions[$i]['example'] = preg_replace('/<.*?>/', '', $functions[$i]['example']);
$functions[$i]['example'] .= "\n\n";
preg_match('/<programlisting.*?>(.*)<\/programlisting>/s', $paragraph, $tmp);
$programlisting = $tmp[1];
// Hmm, no function for this?
$programlisting = str_replace('<', '<', $programlisting);
$programlisting = str_replace('>', '>', $programlisting);
$programlisting = str_replace('"', '"', $programlisting);
$programlisting = str_replace('&', '&', $programlisting);
$programlisting = str_replace(' ', ' ', $programlisting);
$programlisting = str_replace('&sp;', ' ', $programlisting);
$programlisting = str_replace('&', '&', $programlisting);
#$functions[$i]['example'] .= `echo '$programlisting' | indent -kr` . "\n\n";
$functions[$i]['example'] .= $programlisting;
} elseif(preg_match('/See also/s', $paragraph)) {
$functions[$i]['seealso'] = preg_replace('/<.*?>/', '', $paragraph);
$functions[$i]['seealso'] = preg_replace('/See also:/', '', $functions[$i]['seealso']);
$functions[$i]['seealso'] = preg_replace('/\s{2,}/', ' ', $functions[$i]['seealso']);
} else {
// Nothing special, just put it in.
$functions[$i]['paragraph'][$y] = preg_replace('/<.*?>/', '', $paragraph);
$functions[$i]['paragraph'][$y] = preg_replace('/\s{2,}/', ' ', $functions[$i]['paragraph'][$y]);
}
$y++;
}
$i++;
}
/*
* We have an array now with all the data, now write it to seperate files.
*/
if(!file_exists('man7')) {
umask(0000);
mkdir('man7', 0755);
}
foreach($functions as $function) {
if(function_exists('gzwrite')) {
$fp = fopen('man7/php_' . $function['name'] . '.man.gz', 'w');
} else {
$fp = fopen('man7/php_' . $function['name'] . '.man', 'w');
}
/*
$function['name']
$function['shortdesc']
$function['prototype']
$function['paragraph'][$y] // Array
$function['seealso']
$function['example']
*/
$page = '.TH ' . $function['name'] . " 7 \"" . date("j F, Y") . "\" \"PHPDOC MANPAGE\" \"PHP Programmer's Manual\"\n.SH NAME\n" .
$function['name'] . "\n.SH SYNOPSIS\n.B " . $function['prototype'] . "\n.SH DESCRIPTION\n" . $function['shortdesc'] . ".\n";
if(!empty($function['paragraph']) && count($function['paragraph']) > 0) {
foreach($function['paragraph'] as $para) {
$page .= ".PP\n";
$page .= trim($para) . "\n";
}
}
if(!empty($function['example'])) {
$page .= ".SH \"EXAMPLE\"\n";
$page .= $function['example'] . "\n";
}
if(!empty($function['seealso'])) {
$page .= ".SH \"SEE ALSO\"\n";
$page .= $function['seealso'] . "\n";
}
if(function_exists('gzwrite')) {
gzwrite($fp, $page);
} else {
fwrite($fp, $page);
}
}
?>
<file_sep>/branches/gtk-docgen/scripts/extensions.xml.php
<?php
/*
+----------------------------------------------------------------------+
| PHP Documentation |
+----------------------------------------------------------------------+
| Copyright (c) 1997-2010 The PHP Group |
+----------------------------------------------------------------------+
| This source file is subject to version 3.0 of the PHP license, |
| that is bundled with this package in the file LICENSE, and is |
| available through the world-wide-web at the following url: |
| http://www.php.net/license/3_0.txt. |
| If you did not receive a copy of the PHP license and are unable to |
| obtain it through the world-wide-web, please send a note to |
| <EMAIL> so we can mail you a copy immediately. |
+----------------------------------------------------------------------+
| Authors: <NAME> <<EMAIL>> |
+----------------------------------------------------------------------+
$Id$
*/
/*
This script updates the appendices/extensions.xml file automatically based
on the tags placed in the 'reference.xml' files:
<!-- Purpose: xx -->
<!-- Membership: core, pecl, bundled, external -->
<!-- State: deprecated, experimental -->
--- NOTE: PHP >= 5.2 needed ---
*/
$basedir = realpath(dirname(__FILE__) . '/..');
$files = glob("$basedir/en/reference/*/reference.xml");
sort($files);
$Purpose = $Membership = $State = $debug = array();
// read the files and save the tags' info
foreach ($files as $filename) {
$file = file_get_contents($filename);
$miss = array('Purpose'=>1, 'Membership'=>1);
// get the extension's name
preg_match('/<reference[^>]+(?:xml:)?id=[\'"]([^\'"]+)[\'"]/S', $file, $match);
if (empty($match[1])) {
$debug['unknown-extension'][] = $filename;
continue;
} else {
$ext = $match[1];
}
if (preg_match_all('/<!--\s*(\w+):\s*([^-]+)-->/S', $file, $matches, PREG_SET_ORDER)) {
foreach ($matches as $match) {
switch($match[1]) {
case 'Purpose':
$ext_list[$ext] = rtrim($match[2]); // for debugging purposes
case 'State':
${$match[1]}[rtrim($match[2])][$ext] = 1;
unset($miss[$match[1]]); // for the debug part below
break;
case 'Membership':
foreach (explode(',', $match[2]) as $m) {
$m = trim($m);
switch($m) {
case 'pecl':
case 'bundled':
case 'external':
case 'core':
$Membership[$m][$ext] = 1;
unset($miss['Membership']); // for the debug part below
break;
default:
$debug['bogus-membership'][] = array($ext, $m);
}
}
} //first switch
} //first foreach
} // if(regex)
// debug section: let user know which extensions don't have the tags
// if the extension is deprecated, we don't need any more info
if (empty($State['deprecated'][$ext])) {
// purpose not set
if (isset($miss['Purpose'])) {
$debug['purpose'][] = $ext;
}
// membership not set
if (isset($miss['Membership'])) {
$debug['membership'][] = $ext;
}
}
}
// ---------- generate the text to write -------------
$xml = file_get_contents("$basedir/en/appendices/extensions.xml");
// little hack to avoid loosing the entities
$xml = preg_replace('/&([^;]+);/', PHP_EOL.'<!--'.PHP_EOL.'entity: "$1"'.PHP_EOL.'-->'.PHP_EOL, $xml);
$simplexml = simplexml_load_string($xml);
foreach ($simplexml->children() as $node) {
$tmp = explode('.', (string)$node->attributes('xml', true));
$section = ucfirst($tmp[1]); // Purpose, State or Membership
foreach ($node->children() as $topnode) {
$tmp = explode('.', (string)$topnode->attributes('xml', true));
$topname = $tmp[count($tmp)-1];
// this means that we have 2 levels (e.g. basic.*)
if ($topnode->section->itemizedlist) {
foreach ($topnode as $lastnode) {
$tmp = explode('.', (string)$lastnode->attributes('xml', true));
$name = $tmp[1].'.'.$tmp[2];
$lastnode->itemizedlist = PHP_EOL; // clean the list
foreach ($Purpose[$name] as $ext => $dummy) {
unset($ext_list[$ext]); // to generate the debug messages later
$lastnode->itemizedlist = $lastnode->itemizedlist . <<< XML
<listitem><para><xref linkend="$ext"/></para></listitem>
XML;
}
$lastnode->itemizedlist = $lastnode->itemizedlist . ' ';
}
} else { // just 1 level
$tmp = $$section;
// we can get here as a father of 2 levels childs
if (empty($tmp[$topname])) continue;
$topnode->itemizedlist = PHP_EOL; // clean the list
foreach($tmp[$topname] as $ext => $dummy) {
// to generate the debug messages later
if ($section == 'Purpose') {
unset($ext_list[$ext]);
}
$topnode->itemizedlist = $topnode->itemizedlist . <<< XML
<listitem><para><xref linkend="$ext"/></para></listitem>
XML;
}
$topnode->itemizedlist = $topnode->itemizedlist . ' ';
} //end of 1 level handling
}
}
$xml = strtr(html_entity_decode($simplexml->asXML()), array("\r\n" => "\n", "\r" => PHP_EOL, "\n" => PHP_EOL));
// get the entities back again
$xml = preg_replace('/( *)[\r\n]*<!--\s+entity: "([^"]+)"\s+-->[\r\n]*/', '$1&$2;'.PHP_EOL.PHP_EOL, $xml);
file_put_contents("$basedir/en/appendices/extensions.xml", $xml);
// print the debug messages:
if (isset($debug['purpose'])) {
echo "\nExtensions Missing Purpose:\n";
print_r($debug['purpose']);
}
if (count($ext_list)) {
echo "\nExtensions with bogus Purpose:\n";
foreach ($ext_list as $ext => $bug) {
echo "$ext \t => '$bug'\n";
}
}
if (isset($debug['membership'])) {
echo "\nExtensions Missing Membership:\n";
print_r($debug['membership']);
}
if (isset($debug['bogus-membership'])) {
echo "\nExtensions with bogus Membership:\n";
print_r($debug['bogus-membership']);
}
if (isset($debug['unknown-extension'])) {
echo "\nExtensions with unknown extension title:\n";
print_r($debug['unknown-extension']);
}
if (empty($debug)) {
echo "Success: Check {$basedir}/en/appendices/extensions.xml for details\n";
}
?>
<file_sep>/tags/import/Makefile.in
# +----------------------------------------------------------------------+
# | PHP HTML Embedded Scripting Language Version 3.0 |
# +----------------------------------------------------------------------+
# | Copyright (c) 1997,1998 PHP Development Team (See Credits file) |
# +----------------------------------------------------------------------+
# | This program is free software; you can redistribute it and/or modify |
# | it under the terms of one of the following licenses: |
# | |
# | A) the GNU General Public License as published by the Free Software |
# | Foundation; either version 2 of the License, or (at your option) |
# | any later version. |
# | |
# | B) the PHP License as published by the PHP Development Team and |
# | included in the distribution in the file: LICENSE |
# | |
# | This program is distributed in the hope that it will be useful, |
# | but WITHOUT ANY WARRANTY; without even the implied warranty of |
# | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the |
# | GNU General Public License for more details. |
# | |
# | You should have received a copy of both licenses referred to here. |
# | If you did not, or have any questions about PHP licensing, please |
# | contact <EMAIL>. |
# +----------------------------------------------------------------------+
# | Authors: <NAME> <<EMAIL>> |
# +----------------------------------------------------------------------+
#
# $Id$
#
VPATH=@srcdir@
srcdir=@srcdir@
VERSION="@PHP_VERSION@"
HTML_STYLESHEET=$(srcdir)/html.dsl
PHPWEB_STYLESHEET=$(srcdir)/phpweb.dsl
HOWTO_STYLESHEET=$(srcdir)/howto.dsl
PRINT_STYLESHEET=@DOCBOOK_PRINT@
all: html
PREFACE=preface.sgml \
bookinfo.sgml
APPENDICES=appendices/migration.sgml \
appendices/escaping.sgml \
appendices/regexp.sgml \
appendices/http-stuff.sgml \
appendices/history.sgml \
appendices/debugger.sgml \
appendices/phpdevel.sgml
CHAPTERS=chapters/copyright.sgml \
chapters/intro.sgml \
chapters/config.sgml \
chapters/install.sgml \
chapters/features.sgml \
chapters/lang-syntax.sgml
FUNCREF= \
functions/array.sgml \
functions/adabas.sgml \
functions/bc.sgml \
functions/datetime.sgml \
functions/dbase.sgml \
functions/dbm.sgml \
functions/dl.sgml \
functions/dir.sgml \
functions/exec.sgml \
functions/filepro.sgml \
functions/filesystem.sgml \
functions/http.sgml \
functions/hw.sgml \
functions/ibase.sgml \
functions/ifx.sgml \
functions/image.sgml \
functions/imap.sgml \
functions/ldap.sgml \
functions/mail.sgml \
functions/math.sgml \
functions/misc.sgml \
functions/mcrypt.sgml \
functions/msql.sgml \
functions/mysql.sgml \
functions/nis.sgml \
functions/sybase.sgml \
functions/network.sgml \
functions/oci8.sgml \
functions/oracle.sgml \
functions/pcre.sgml \
functions/pgsql.sgml \
functions/info.sgml \
functions/regex.sgml \
functions/sem.sgml \
functions/solid.sgml \
functions/snmp.sgml \
functions/strings.sgml \
functions/uodbc.sgml \
functions/url.sgml \
functions/var.sgml \
functions/wddx.sgml \
functions/zlib.sgml
FILES=$(PREFACE) $(APPENDICES) $(CHAPTERS) $(FUNCREF)
ONLINE_MANUAL=*.php3
DIST_FILES=manual.zip manual.tar.gz manual.rtf.gz bigmanual.html.gz \
manual.prc manual.txt.gz
MIRROR_TARGETS=php3/manual.php3 $(DIST_FILES) html/manual.html
html.dsl: html.dsl.in ../config.status
cd .. && CONFIG_FILES=doc/$@ CONFIG_HEADERS= ./config.status
print.dsl: print.dsl.in ../config.status
cd .. && CONFIG_FILES=doc/$@ CONFIG_HEADERS= ./config.status
phpweb.dsl: phpweb.dsl.in ../config.status
cd .. && CONFIG_FILES=doc/$@ CONFIG_HEADERS= ./config.status
manual.sgml: .manual.sgml
.manual.sgml: $(FILES)
touch .manual.sgml
html: html/manual.html
phpweb: php3/manual.php3
rtf: manual.rtf
dvi: manual.dvi
ps: manual.ps
howto: howto.html
Makefile: $(srcdir)/Makefile.in ../config.status
cd .. && CONFIG_FILES=doc/$@ CONFIG_HEADERS= ./config.status
checkdoc: $(srcdir)/checkdoc ../config.status
cd .. && CONFIG_FILES=doc/$@ CONFIG_HEADERS= ./config.status
mirror-files: $(MIRROR_TARGETS)
sync: mirror-files
-rsync -azvc $(ONLINE_MANUAL) www.php.net:/local/Web/sites/phpweb/manual/.
-rsync -azvc --exclude bigmanual.html *.html www.php.net:/local/Web/sites/phpweb/manual/html/.
-rsync -azvc $(DIST_FILES) www.php.net:/local/Web/sites/phpweb/distributions/.
sync-no: mirror-files
-rsync -vc $(ONLINE_MANUAL) ../../phpweb/manual/
-rsync --exclude bigmanual.html -vc *.html ../../phpweb/manual/html/
-rsync -vc $(DIST_FILES) ../../phpweb/distributions/
commit-no: sync-no
(cd ../../phpweb/manual; \
files=`cvs -qn update | grep '^?' | cut -c3-`; \
test -n "$$files" && cvs add $$files; \
cvs commit -m '$(MESSAGE)')
(cd ../../phpweb/distributions; cvs commit -m '$(MESSAGE)')
snapshot: manual-snapshot.tar.gz
manual-snapshot.tar.gz: bigmanual.html html/manual.html manual.rtf manual.txt
tar -cvzf $@ bigmanual.html html/*.html manual.rtf manual.txt
status: checkdoc
$(srcdir)/checkdoc -s > $(srcdir)/status.txt
$(srcdir)/checkdoc -m > $(srcdir)/missing.txt
makedoc: makedoc.cc
g++ -o makedoc makedoc.cc
bigmanual.html: $(srcdir)/manual.sgml $(HTML_STYLESHEET)
jade -V nochunks -d $(HTML_STYLESHEET) -t sgml $(srcdir)/manual.sgml > $@
bigmanual.html.gz: bigmanual.html
gzip -c $< > $@
manual.rtf.gz: manual.rtf
gzip -c $< > $@
manual.txt.gz: manual.txt
gzip -c $< > $@
html/manual.html: $(srcdir)/manual.sgml $(HTML_STYLESHEET)
@test -d html || mkdir html
jade -d $(HTML_STYLESHEET) -V use-output-dir -t sgml $(srcdir)/manual.sgml
php3/manual.php3: $(srcdir)/manual.sgml $(PHPWEB_STYLESHEET)
@test -d php3 || mkdir php3
-jade -d $(PHPWEB_STYLESHEET) -V use-output-dir -t sgml $(srcdir)/manual.sgml
manual.txt: bigmanual.html
lynx -nolist -dump file:`pwd`/bigmanual.html > manual.txt
manual.prc: manual.txt makedoc
./makedoc -b manual.txt manual.prc 'PHP3 Manual'
manual.zip: $(srcdir)/html/manual.html
-rm -f $@ && (cd html; zip -9 -q $@ *.html)
manual.tar.gz: $(srcdir)/html/manual.html
-rm -f $@ && (cd html; tar -cf - *.html) | gzip > manual.tar.gz
howto.html: $(srcdir)/howto.sgml $(HOWTO_STYLESHEET) global.ent
jade -d $(HOWTO_STYLESHEET) -t sgml $(srcdir)/howto.sgml
tex latex: $(srcdir)/manual.tex
# File endings we are going to define general rules for:
.SUFFIXES: .html .sgml .tex .dvi .ps .rtf
# General rules:
.sgml.tex:
jade -d $(PRINT_STYLESHEET) -t tex $<
.sgml.rtf:
jade -d $(PRINT_STYLESHEET) -t rtf $<
.tex.dvi:
jadetex $<
.dvi.ps:
dvips -o $@ $<
test: manual.sgml
nsgmls -s $<
clean:
( \
cd $(srcdir); \
rm -rf html php3; \
rm -f manual.txt [a-z]*.html manual.rtf manual.info \
rm -f manual.zip manual.tar.gz sync-no commit-no .manual.sgml \
rm -f manual.txt manual.prc makedoc *.manifest \
rm -f *.aux *.tex *.log *.dvi *.toc *.ps \
rm -f status.txt missing.txt checkdoc \
rm -f *.php3 $(GENREF) \
)
<file_sep>/branches/docgen-update/scripts/docgen/docgen.php
#!/usr/bin/env php
<?php
// Required extensions
if(!extension_loaded("reflection")) trigger_error("Docgen requires the Reflection extension", E_USER_ERROR);
if(!extension_loaded("pcre")) trigger_error("Docgen requires the PCRE extension", E_USER_ERROR);
if(!extension_loaded("xmlwriter")) trigger_error("Docgen requires the DOM extension", E_USER_ERROR);
// Required includes
require_once(__DIR__."/structures/Docgen_JobManager.php");
require_once(__DIR__."/structures/Docgen_Job.php");
require_once(__DIR__."/includes/cli-options.php");
// Handle script options
Docgen_Options::process_options();
$parameters = array('pecl'=>Docgen_Options::$options["pecl"], 'seealso'=>Docgen_Options::$options["seealso"], 'example'=>Docgen_Options::$options["example"]);
if (is_array(Docgen_Options::$options["extension"])) {
foreach (Docgen_Options::$options["extension"] as $extension) {
Docgen_JobManager::queueJob(new Docgen_ExtensionJob($extension, $parameters));
}
} elseif (!is_null(Docgen_Options::$options["extension"])) {
Docgen_JobManager::queueJob(new Docgen_ExtensionJob(Docgen_Options::$options["extension"], $parameters));
}
if (is_array(Docgen_Options::$options["class"])) {
foreach (Docgen_Options::$options["class"] as $class) {
Docgen_JobManager::queueJob(new Docgen_ClassJob($class, $parameters));
}
} elseif (!is_null(Docgen_Options::$options["class"])) {
Docgen_JobManager::queueJob(new Docgen_ClassJob(Docgen_Options::$options["class"], $parameters));
}
if (is_array(Docgen_Options::$options["method"])) {
foreach (Docgen_Options::$options["method"] as $method) {
$method = explode("::", $method);
DocGen_JobManager::queueJob(new Docgen_MethodJob($class, $method, $parameters));
}
} elseif (!is_null(Docgen_Options::$options["method"])) {
Docgen_JobManager::queueJob(new Docgen_MethodJob(Docgen_Options::$options["method"], $parameters));
}
if (is_array(Docgen_Options::$options["function"])) {
foreach (Docgen_Options::$options["function"] as $function) {
DocGen_JobManager::queueJob(new Docgen_FunctionJob($function, $parameters));
}
} elseif (!is_null(Docgen_Options::$options["function"])) {
Docgen_JobManager::queueJob(new Docgen_FunctionJob(Docgen_Options::$options["function"], $parameters));
}
<file_sep>/tags/dev_docbook4_branchpoint/scripts/process.php
#!/usr/bin/php -q
<?php
if ($argc < 2 || $argc > 3)
{ ?>
Process the manual to do some replacements.
Usage:
<?=$argv[0]?> <apply-script> [<startdir>]
<apply-script> must contain the function apply($input),
which recieves a whole xml-file, and should output
return the new file.
With <startdir> you can specify in which dir
to start looking recursively for xml files.
Written by <EMAIL>
<?php
exit;
}
echo "Starting with manual-process\n";
echo "Including $argv[1]...";
include("$argv[1]");
echo " done\n";
if (!function_exists('apply'))
{
?>
### FATAL ERROR ###
In <?=$argv[1]?> you should define a function:
string apply(string $string)
<?php
exit;
}
$startdir = isset($argv[2]) ? $argv[2] : '.';
echo "Constructing list of all xml-files (may take a while)...";
$files = all_xml_files($startdir);
echo " done (".count($files)." xml files found)\n";
foreach ($files as $file)
{
echo "[Processing $file]\n";
$fp = fopen($file,'r');
$old = fread($fp,filesize($file));
fclose($fp);
if (!$old)
{
echo "WARNING: problem reading $file, skipping\n";
continue;
}
$new = apply($old);
$fp = fopen($file,'w');
$res = fwrite($fp,$new);
fclose($fp);
if (!$res)
{
echo "WARNING: problem writing $file, file might be damaged\n";
continue;
}
}
/* Utility functions: */
function all_xml_files($startdir)
{
$startdir = ereg_replace('/+$','',$startdir);
//echo "\$startdir = $startdir\n";
$entries = array();
$handle=opendir($startdir);
while ($file = readdir($handle))
{
$ffile = "$startdir/$file"; // full file(path)
//echo "$file\n";
if (ereg('\.xml$',$file))
$entries[] = $ffile;
if ($file{0} != '.' && is_dir($ffile))
$entries = array_merge($entries,all_xml_files($ffile));
}
closedir($handle);
return $entries;
}
<file_sep>/branches/gtk-docgen/scripts/build-chms.php
<?php
/**
* +----------------------------------------------------------------------+
* | PHP Version 5 |
* +----------------------------------------------------------------------+
* | Copyright (c) 1997-2010 The PHP Group |
* +----------------------------------------------------------------------+
* | This source file is subject to version 3.01 of the PHP license, |
* | that is bundled with this package in the file LICENSE, and is |
* | available through the world-wide-web at the following url: |
* | http://www.php.net/license/3_01.txt. |
* | If you did not receive a copy of the PHP license and are unable to |
* | obtain it through the world-wide-web, please send a note to |
* | <EMAIL> so we can mail you a copy immediately. |
* +----------------------------------------------------------------------+
* | Authors: <NAME> <<EMAIL>> |
* | <NAME> <<EMAIL>> |
* +----------------------------------------------------------------------+
*
* $Id$
*/
/**
* TODO
*
* @todo Check the following languages, as they generate bugged CHMS: de, es, fa, fr, pl, pt_BR, ro
*/
/**
* This script is based off the original build.chms.bat
* in the root of doc-base.
*
* This script requires PHP 5.3.0+
*/
/**
* Configuration
*/
define('PATH_PHP', 'C:\\php\\binaries\\PHP_5_3\\php.exe');
define('PATH_PHD', 'C:\\pear\\phd.bat');
define('PATH_HHC', 'C:\\Program Files (x86)\HTML Help Workshop\hhc.exe');
define('PATH_SCP', 'C:\\Program Files (x86)\PuTTY\pscp.exe');
define('PATH_PPK', 'C:\\php-sdk\\keys\\php-doc-host.ppk');
define('PATH_SVN', 'C:\\Program Files\\SlikSvn\\bin\\svn.exe');
define('PATH_PEAR', 'C:\\pear\\pear.bat');
define('PATH_CHM', 'C:\doc-all\\chmfiles');
define('PATH_LOG', 'C:\\doc-all\\logs');
define('PATH_DOC', 'C:\\doc-all');
define('DEBUG', true);
/**
* Languages to build
*/
$languages = Array(
'en', /* English */
'de', /* German */
'es', /* Spanish */
'fa', /* Persian */
'fr', /* French */
'ja', /* Japanese */
'pl', /* Polish */
'pt_BR', /* Brazilian Portuguese */
'ro', /* Romanian */
'tr' /* Turkish */
);
/**
* Get the current working directory
*/
$cwd = getcwd();
/**
* Upgrade PhD, if any updates are available
*/
execute_task('Updating PhD', PATH_PEAR, 'upgrade doc.php.net/phd', 'pear');
/**
* Update doc-base, to prevent build errors with
* entities
*/
chdir(PATH_DOC . '\\doc-base\\');
execute_task('Updating doc-base', PATH_SVN, 'up', 'docbase');
chdir($cwd);
/**
* We may want to try build a single language
*/
if($argc >= 2 && in_array($argv[1], $languages))
{
$languages = Array($argv[1]);
}
/**
* Start iterating over each translation
*/
foreach($languages as $lang)
{
echo('Processing language \'' . $lang . '\':' . PHP_EOL);
/**
* Update that specific language folder in SVN
*/
chdir(PATH_DOC . '\\' . $lang . '\\');
execute_task('- SVN', PATH_SVN, 'up', 'svn_' . $lang);
chdir($cwd);
/**
* Generate .manual.xml
*/
execute_task('- Configure', PATH_PHP, PATH_DOC . '\doc-base\configure.php --disable-libxml-check --with-php="' . PATH_PHP . '" --with-lang=' . $lang . ' --enable-chm', 'configure_' . $lang);
if(!is_file(PATH_DOC . '\\doc-base\\.manual.xml'))
{
echo('- Build error: configure failed' . PHP_EOL);
continue;
}
/**
* Run .manual.xml thru PhD
*/
execute_task('- PhD', PATH_PHD, '-d "' . PATH_DOC . '\\doc-base\\.manual.xml' . '" -P PHP -f chm -o "' . PATH_DOC . '\\tmp\\' . $lang . '" --lang=' . $lang, 'phd_' . $lang);
if(!is_file(PATH_DOC . '\\tmp\\' . $lang . '\\php-chm\\php_manual_' . $lang . '.hhp'))
{
echo('- Build error: PhD failed' . PHP_EOL);
continue;
}
/**
* Run the HTML Help Compiler to generate the actual CHM file
*/
execute_task('- HHC', PATH_HHC, '"' . PATH_DOC . '\\tmp\\' . $lang . '\\php-chm\\php_manual_' . $lang . '.hhp"', 'hhc_' . $lang);
if(!is_file(PATH_DOC . '\\tmp\\' . $lang . '\\php-chm\\php_manual_' . $lang . '.chm'))
{
echo('- Build error: HHC failed' . PHP_EOL);
continue;
}
/**
* Anything smaller than ~5MB is broken. Common broken sizes are 2MB and 15K. Common good size are 10-12MB.
*/
if (filesize(PATH_DOC . '\\tmp\\' . $lang . '\\php-chm\\php_manual_' . $lang . '.chm') < 5000000) {
echo('- Build error: CHM file too small, something went wrong.' . PHP_EOL);
continue;
}
/**
* Copy the CHM file into the archive
*/
if(!copy(PATH_DOC . '\\tmp\\' . $lang . '\\php-chm\\php_manual_' . $lang . '.chm', PATH_DOC . '\\chmfiles\\php_manual_' . $lang . '.chm'))
{
echo('- Build error: Unable to copy CHM file into archive folder');
continue;
}
/**
* Update the CHM on the rsync server
*/
execute_task('- rsync', PATH_SCP, '-batch -q -i "' . PATH_PPK . '" -l bjori "' . PATH_DOC . '\\chmfiles\\php_manual_' . $lang . '.chm" rsync.php.net:/home/bjori/manual-chms-new/', 'rsync_' . $lang);
/**
* Cleanup
*/
echo('- Clean up' . PHP_EOL);
unlink(PATH_DOC . '\\doc-base\\.manual.xml');
if(!DEBUG)
{
rmdir_recursive(PATH_DOC . '\\tmp\\' . $lang . '\\php-chm\\');
}
}
echo('Done!');
/**
* Helper function for execution a program
*
* @param string Path to the program to execute
* @param string (optional) Parameters to pass the this call
* @param string (optional) Log output to a specific file defined here
* @return void No value is returned
*/
function execute_task($title, $program, $parameters, $log)
{
echo($title . '...' . PHP_EOL);
if(empty($program))
{
return;
}
if($program == PATH_SCP)
{
$log = false;
}
$cmd = sprintf('"%s"%s%s', $program, (!$parameters ?: ' ' . $parameters), (!$log ? '' : ' > ' . PATH_LOG . '\\' . $log . '.log 2<&1'));
@popen($cmd, 'r');
}
/**
* Removes all files within a directory and then
* deletes the directory
*
* @param string Directory to remove
* @return void No value is returned
*/
function rmdir_recursive($dir)
{
if(!is_dir($dir))
{
return;
}
$glob = glob($dir . '*');
if(sizeof($glob))
{
foreach($glob as $obj)
{
if(is_dir($obj))
{
rmdir_recursive($obj . '\\');
}
else
{
unlink($obj);
}
}
}
rmdir($dir);
}
/**
* Gets the contents of a specific log
*
* @param string Name of the log (usually "program_lang")
* @return string Contents of the log
*/
function log_get_contents($logname)
{
return(@file_get_contents(PATH_LOG . '\\' . $log . '.log'));
}
<file_sep>/tags/POST_DOCBOOK5/scripts/quickref/makefunclist.php
<?php
/*
+----------------------------------------------------------------------+
| PHP Version 4 |
+----------------------------------------------------------------------+
| Copyright (c) 1997-2004 The PHP Group |
+----------------------------------------------------------------------+
| This source file is subject to version 3.0 of the PHP license, |
| that is bundled with this package in the file LICENSE, and is |
| available through the world-wide-web at the following url: |
| http://www.php.net/license/3_0.txt. |
| If you did not receive a copy of the PHP license and are unable to |
| obtain it through the world-wide-web, please send a note to |
| <EMAIL> so we can mail you a copy immediately. |
+----------------------------------------------------------------------+
| Authors: <NAME> <<EMAIL>> |
| <NAME> <<EMAIL>> |
+----------------------------------------------------------------------+
$Id$
*/
$XML_REF_ROOT = "../../en/reference/";
$FUNCTIONS = array();
if ($dh = @opendir($XML_REF_ROOT)) {
while (($file = readdir($dh)) !== FALSE) {
if (is_dir($XML_REF_ROOT . $file) && !in_array($file, array(".", "..", "CVS"))) {
get_function_files($XML_REF_ROOT . $file);
}
}
closedir($dh);
} else {
die("Unable to find phpdoc XML files");
}
sort($FUNCTIONS);
fwrite(fopen("funclist.txt", "w"), implode("\n", $FUNCTIONS)."\n");
function get_function_files($dir) {
global $FUNCTIONS;
if ($dh = @opendir($dir . "/functions")) {
while (($file = readdir($dh)) !== FALSE) {
if (ereg("\\.xml\$", $file)) {
$FUNCTIONS[] = str_replace(array(".xml", "-"), array("", "_"), $file);
}
}
closedir($dh);
} else {
die("Unable to find phpdoc XML files in $dir folder");
}
}
?>
<file_sep>/branches/function_definitions/scripts/online_editor/base.php
<?php
/*
+----------------------------------------------------------------------+
| PHP Version 4 |
+----------------------------------------------------------------------+
| Copyright (c) 1997-2011 The PHP Group |
+----------------------------------------------------------------------+
| This source file is subject to version 3.0 of the PHP license, |
| that is bundled with this package in the file LICENSE, and is |
| available through the world-wide-web at the following url: |
| http://www.php.net/license/3_0.txt. |
| If you did not receive a copy of the PHP license and are unable to |
| obtain it through the world-wide-web, please send a note to |
| <EMAIL> so we can mail you a copy immediately. |
+----------------------------------------------------------------------+
| Authors : <NAME> <<EMAIL>> |
+----------------------------------------------------------------------+
$Id$
*/
//-- The PHPDOC Online XML Editing Tool
//--- Purpose: base file (all other files require this to start)
//------- Configuration
// Root path to the phpdoc-all directory
// -- cvs co phpdoc-all
define ('CVS_ROOT_PATH', '/cvs/phpdoc-all/');
// Require User Login by email (needed for user file saving)
$requireLogin = false;
// Language information
// RTL direction is defined in $translations_RTL
$translations = array(
'Arabic' => array('ar', 'utf-8'),
'Brazilian-PT' => array('pt_BR', 'iso-8859-1'),
'Bulgarian' => array('bg', 'utf-8'),
'Catalan' => array('ca', 'iso-8859-1'),
'Chinese-HK' => array('hk', 'big5'),
'Chinese-Simplified' => array('zh', 'gb2312'),
'Chinese-Traditional' => array('tw', 'big5'),
'Czech' => array('cs', 'iso-8859-2'),
'Danish' => array('da', 'iso-8859-1'),
'Dutch' => array('nl', 'iso-8859-1'),
'Finnish' => array('fi', 'iso-8859-1'),
'French' => array('fr', 'iso-8859-1'),
'German' => array('de', 'iso-8859-1'),
'Greek' => array('el', 'iso-8859-7'),
'Hebrew' => array('he', 'windows-1255'),
'Hungarian' => array('hu', 'iso-8859-2'),
'Indonesian' => array('id', 'iso-8859-1'),
'Italian' => array('it', 'iso-8859-1'),
'Japanese' => array('ja', 'utf-8'),
'Korean' => array('kr', 'utf-8'),
'Lithuanian' => array('lt', 'iso-8859-1'),
'Norwegian' => array('no', 'utf-8'),
'Polish' => array('pl', 'iso-8859-2'),
'Romanian' => array('ro', 'utf-8'),
'Russian' => array('ru', 'utf-8'),
'Serbian' => array('fa', 'utf-8'),
'Slovak' => array('sk', 'iso-8859-2'),
'Slovenian' => array('sl', 'iso-8859-1'),
'Spanish' => array('es', 'iso-8859-1'),
'Swedish' => array('sv', 'iso-8859-1'),
'Turkish' => array('tr', 'utf-8'),
);
$translations_RTL = array('ar', 'he');
// Users folder where their cached files are saved - must be writable
// Only needed if $requireLogin is true
$usersCachePath = '/path/to/editor/users/';
// Files Permissions Mod
$filesChMod = 0777;
foreach ($translations as $language => $lang_info) {
addLanguage($language, $lang_info[0], $lang_info[1]);
}
// Languages and paths: (ToDo Font should be defined for better display)
// Hide files (ignore)
$ignoreListingFolders = array('.', '..', 'CVS');
$ignoreListingFiles = array('contributors.xml', 'contributors.ent', 'livedocs.ent');
//------- Base functions
function addLanguage($lang, $id, $charset='utf-8', $font='Fixedsys') {
global $phpdocLangs, $translations_RTL;
$lists = get_mailing_list_info($id);
$phpdocLangs[$lang]['DocCVSPath'] = CVS_ROOT_PATH . $id;
$phpdocLangs[$lang]['charset'] = $charset;
$phpdocLangs[$lang]['direction'] = (in_array($id, $translations_RTL)) ? 'RTL' : 'LTR';
$phpdocLangs[$lang]['id'] = $id;
$phpdocLangs[$lang]['coordinator'] = $lists['main'];
$phpdocLangs[$lang]['mailing'] = $lists['main'];
$phpdocLangs[$lang]['mailingSubscribe'] = $lists['subscribe'];
$phpdocLangs[$lang]['font'] = $font;
}
function sessionCheck($arguments='') {
session_start();
if (!isset($_SESSION['user'])) {
if ($_SERVER['REQUEST_METHOD']=='GET') {
$_SESSION['redo'] = $_SERVER['SCRIPT_NAME'].'?'.$_SERVER['QUERY_STRING'];
}
header('location: login.php'.$arguments);
exit('<a href="login.php">Login first</a>');
}
return $_SESSION['user'];
}
function getDateTimeToLog() {
return date('d/m H:i [').time().']';
}
function getUserIP() {
return $_SERVER['REMOTE_ADDR'];
}
function getCacheName($filename) {
// change reference/ext/file.xml to reference~ext~file.xml
$filename = str_replace(array('/', '\\'), '~', $filename);
return $filename;
}
function stripslashes2($text) {
if (get_magic_quotes_gpc()) {
$text = stripslashes($text);
}
return $text;
}
function getRevision($file, $en=false) {
$f = fopen($file, "rb");
$data = fread($f, 200);
fclose($f);
// Use en-revision
if ($en) {
preg_match("#<!-- *EN-Revision: +([0-9\.]+)#i", $data, $result);
$rev = $result[1];
} else {
preg_match("#<!-- *\\$"."Revision: +([0-9\.]+)#i", $data, $result);
$rev = $result[1];
}
return $rev;
}
function getTranslationStatus($file) {
global $user, $phpdocLangs;
$lang = $user['phpdocLang'];
$translationPath = $phpdocLangs[$lang]['DocCVSPath'];
$trFile = $translationPath.$file;
$enFile = CVS_ROOT_PATH . 'en/' . $file;
$status['lastEnRevision'] = getRevision($enFile);
if (file_exists($trFile)) {
$status['translated'] = true;
$status['fileRevision'] = getRevision($trFile);
$status['fileEnRevision'] = getRevision($trFile, true);
if ($status['fileEnRevision'] && $status['lastEnRevision']) {
$distance = round((float) $status['lastEnRevision'], 3) - round((float) $status['fileEnRevision'], 3) ;
$backward = 0;
if ($distance<0) {
$backward = -1;
} elseif ($distance && $distance<.03) {
$backward = 1;
} elseif ($distance && $distance<.2) {
$backward = 2;
} elseif ($distance && $distance<.4) {
$backward = 3;
} elseif ($distance && $distance<.6) {
$backward = 4;
} elseif ($distance && $distance>=.6) {
$backward = 5;
}
$status['backward'] = $backward;
$status['distance'] = $distance;
}
} else {
$status['translated'] = false;
}
return $status;
}
function get_mailing_list_info ($id) {
$list_id = strtolower(str_replace('_', '-', $id));
return array(
'main' => "<EMAIL>",
'subscribe' => "<EMAIL>_<EMAIL>",
'archives' => "http://news.php.net/php.doc.{$list_id}",
);
}
<file_sep>/tags/AFTER_REF_STRUCT_DEV_MERGE/scripts/zendapi_protos.php
<?php
$overwrite = false;
$zend_include_dir = "../../php-src/Zend";
$zend_include_files = array(
"zend.h",
"zend_API.h",
"zend_builtin_functions.h",
"zend_compile.h",
"zend_constants.h",
"zend_exceptions.h",
"zend_execute.h",
"zend_hash.h",
"zend_highlight.h",
"zend_interfaces.h",
"zend_ini.h",
"zend_list.h",
"zend_modules.h",
"zend_objects.h",
"zend_object_handlers.h",
"zend_objects_API.h",
"zend_qsort.h",
"zend_stream.h",
"zend_strtod.h",
"zend_unicode.h",
"zend_variables.h",
"../TSRM/TSRM.h",
"../TSRM/tsrm_virtual_cwd.h",
);
$api_dir = array("ZEND"=>"../en/internals/zendapi",
"TSRM"=>"../en/internals/tsrm",
"CWD" =>"../en/internals/tsrm",);
$functions = array();
$wrappers = array();
foreach ($zend_include_files as $infile) {
echo "processing $zend_include_dir/$infile\n";
$in = fopen("$zend_include_dir/$infile", "r");
if (!$in) {
die("can't open $zend_include_dir/$infile");
}
// loop over all lines in the file
while (!feof($in)) {
// TODO a prototype may span more than one line?
$line = trim(fgets($in));
if (substr($line, -1) == "\\") { // multiline macro, read one more line
$line = substr($line, 0, -1) . trim(fgets($in));
}
// first we look for prototypes marked with ZEND_API
if (preg_match('/^\s*(ZEND|TSRM|CWD)_API\s+(\S+)\s+(\S+)\((.*)\)/U', $line, $matches)) {
// parse prototypes, step #1
// extract return type and function name
$api_type = $matches[1];
$return_type = $matches[2];
$function = $matches[3];
$param_list = $matches[4];
// the pointer '*' is usually next to the function name, not the type
// TODO what if there is whitespace on both sides of the '*'?
while ($function[0] == '*') {
$return_type.= "*";
$function = substr($function, 1);
}
// the parameters are spearated by commas
// TODO find a better way to handle TSRMLS_D and TSRMLS_DC
// TODO handle ...
$params = array();
foreach (explode(",", $param_list) as $param) {
$new_param = array();
$tokens = preg_split("/\s+/", trim($param));
$name = array_pop($tokens);
if (preg_match("|_DC$|", $name)) {
$magic = $name;
$name = array_pop($tokens);
} else {
$magic = "";
}
$type = implode(" ", $tokens);
if (empty($name)) {
$new_param['type'] = "magic";
$new_param['name'] = $type;
} else {
while ($name[0] == '*') {
$type.= "*";
$name = substr($name, 1);
}
$new_param['type'] = $type;
$new_param['name'] = $name;
}
$params[$name] = $new_param;
if ($magic) {
$params[$magic] = array("type"=>"magic", "name"=>$magic);
}
}
$functions[$function] = array("name" => $function,
"return_type" => $return_type,
"params" => $params,
"api_type" => $api_type,
"infile" => $infile
);
}
// next we look for macros that seem to be just wrappers around existing functions
// TODO catch multiline definitions
if (preg_match('|^#define\s+(\w+)\((.*)\)\s+(\w+)\(|U', $line, $matches)) {
$wrapper = $matches[1];
$param_list = $matches[2];
$function = $matches[3];
$wrappers[$wrapper] = array("function" => $function,
"wrapper" => $wrapper,
"param_list" => $param_list,
"infile" => $infile
);
}
}
}
do {
$additions = 0;
foreach ($wrappers as $name => $wrapper) {
if (isset($functions[$wrapper["function"]])) {
$function = $functions[$wrapper["function"]];
$params = array();
foreach (explode(",", $wrapper["param_list"]) as $param) {
$param = preg_replace('|\s*_*(\w+)\s*|', '${1}', $param); // trim and strip leading _s
if (isset($function["params"][$param])) {
$param_type = $function["params"][$param]["type"];
} else {
$param_type = "...";
}
$params[$param] = array("type"=>$param_type, "name"=>$param);
}
$functions[$name] = array("name" => $name,
"return_type" => $function["return_type"],
"params" => $params,
"api_type" => $function["api_type"],
"infile" => $wrapper["infile"]
);
unset($wrappers[$name]);
$additions++;
}
}
} while ($additions > 0);
foreach ($functions as $name => $function) {
create_page($name, $function["return_type"], $function["params"], $function["api_type"], $function["infile"]);
}
function create_page($function, $return_type, $params, $api_type, $infile)
{
global $overwrite, $api_dir;
// now generate the doc filename for this function
$functype = (strtolower($function) == $function) ? "function" : "macro";
$filename = $api_dir[$api_type]."/".$functype."s/".$function.".xml";
// only proceed it fhe file doesn't exist yet (no overwrites)
// and do not expose functions staring with '_'
if (($function[0] != '_') && ($overwrite || !file_exists($filename))) {
// now write the template file to phpdoc/en/internals/zendapi/functions
echo "writing $filename\n";
ob_start();
echo '<?xml version="1.0" encoding="iso-8859-1"?>'."\n";
// take revision from existing file
if (!$overwrite || !file_exists($filename)) {
echo "<!-- $"."Revision: 1.1 $ -->\n";
} else {
foreach (file($filename) as $line) {
if (strstr($line, 'Revision: ')) {
echo $line;
break;
}
}
}
?>
<refentry id="zend-api.<?php echo str_replace("_","-",$function); ?>">
<refnamediv>
<refname><?php echo $function; ?></refname>
<refpurpose>...</refpurpose>
</refnamediv>
<refsect1 role="description">
&reftitle.description;
<literallayout>#include <<?php echo basename($infile); ?>></literallayout>
<methodsynopsis>
<?php
if ($return_type == "void") {
echo " <void/>";
} else {
echo " <type>$return_type</type>";
}
echo "<methodname>$function</methodname>";
if (count($params)) {
echo "\n";
foreach($params as $param) {
echo " <methodparam><type>$param[type]</type><parameter>$param[name]</parameter></methodparam>\n";
}
} else {
echo "<void/>\n";
}
?>
</methodsynopsis>
<para>
...
</para>
</refsect1>
<refsect1 role="parameters">
&reftitle.parameters;
<para>
<variablelist>
<?php
foreach($params as $param) {
?>
<varlistentry>
<term><parameter><?php echo $param["name"]; ?></parameter></term>
<listitem>
<para>
...
</para>
</listitem>
</varlistentry>
<?php
}
?>
</variablelist>
</para>
</refsect1>
<refsect1 role="returnvalues">
&reftitle.returnvalues;
<para>
...
</para>
</refsect1>
</refentry>
<!-- Keep this comment at the end of the file
Local variables:
mode: sgml
sgml-omittag:t
sgml-shorttag:t
sgml-minimize-attributes:nil
sgml-always-quote-attributes:t
sgml-indent-step:1
sgml-indent-data:t
indent-tabs-mode:nil
sgml-parent-document:nil
sgml-default-dtd-file:"../../../../manual.ced"
sgml-exposed-tags:nil
sgml-local-catalogs:nil
sgml-local-ecat-files:nil
End:
vim600: syn=xml fen fdm=syntax fdl=2 si
vim: et tw=78 syn=sgml
vi: ts=1 sw=1
-->
<?php
file_put_contents($filename, ob_get_clean());
}
}
?>
<file_sep>/tags/AFTER_REF_STRUCT_DEV_MERGE/scripts/check-trans-params.php
#!/usr/bin/php
<?php
/*
+----------------------------------------------------------------------+
| PHP Version 4 |
+----------------------------------------------------------------------+
| Copyright (c) 1997-2004 The PHP Group |
+----------------------------------------------------------------------+
| This source file is subject to version 3.0 of the PHP license, |
| that is bundled with this package in the file LICENSE, and is |
| available through the world-wide-web at the following url: |
| http://www.php.net/license/3_0.txt. |
| If you did not receive a copy of the PHP license and are unable to |
| obtain it through the world-wide-web, please send a note to |
| <EMAIL> so we can mail you a copy immediately. |
+----------------------------------------------------------------------+
| Authors: <NAME> <<EMAIL>> (idea) |
| <NAME> <<EMAIL>> |
+----------------------------------------------------------------------+
*/
if (isset($_SERVER["argv"][1])) {
$lang = $_SERVER["argv"][1];
$basedir = dirname(__FILE__) . "/..";
}
if (!isset($_SERVER["argv"][1]) || !is_dir("$basedir/$lang/reference")) {
echo "Purpose: Check parameters (types, optional, reference) in translated manual.\n";
echo "Usage: check-trans-params.php language\n";
exit(1);
}
$cwd = getcwd();
chdir("$basedir/$lang/reference/");
foreach (glob("*/functions/*.xml") as $filename) {
$filename_en = realpath("$basedir/en/reference/$filename");
$filename = realpath($filename); // absolute path
if (!file_exists($filename_en)) {
echo "File $filename does not exist in en/ tree.\n";
continue;
}
$file = file_get_contents($filename);
$file_en = file_get_contents($filename_en);
preg_match_all('~<methodsynopsis>(.*)</methodsynopsis>~sU', $file, $matches, PREG_OFFSET_CAPTURE);
preg_match_all('~<methodsynopsis>(.*)</methodsynopsis>~sU', $file_en, $matches_en, PREG_OFFSET_CAPTURE);
$line_no = (substr_count(substr($file, 0, $matches[1][1]), "\n") + 1);
$line_no_en = (substr_count(substr($file, 0, $matches_en[1][1]), "\n") + 1);
if (count($matches[1]) != count($matches_en[1])) {
echo "Invalid count of <methodsynopsis> in $filename on line $line_no.\n";
echo ": source in $filename_en on line $line_no_en.\n";
}
foreach ($matches[1] as $key => $val) {
if (!isset($matches_en[1][$key])) {
break;
}
$line_no = (substr_count(substr($file, 0, $val[1]), "\n") + 1);
$line_no_en = (substr_count(substr($file_en, 0, $matches_en[1][$key][1]), "\n") + 1);
$methodsynopsis = $val[0];
$methodsynopsis_en = $matches_en[1][$key][0];
if (preg_match('~<replaceable>~', $methodsynopsis)) {
// ignored
} elseif (!preg_match('~<type>([^<]*)</type>\\s*<methodname>~', $methodsynopsis, $match)) {
echo "Return type not found in $filename on line " . ($line_no + 1) . ".\n";
echo ": source in $filename_en on line " . ($line_no_en + 1) . ".\n";
} elseif (!preg_match('~<type>' . preg_quote($match[1], '~') . '</type>\\s*<methodname>~', $methodsynopsis_en)) {
echo "Invalid return type in $filename on line " . ($line_no + 1) . ".\n";
echo ": source in $filename_en on line " . ($line_no_en + 1) . ".\n";
}
preg_match_all('~<methodparam.*<parameter[^>]*~U', $methodsynopsis, $match);
preg_match_all('~<methodparam.*<parameter[^>]*~U', $methodsynopsis_en, $match_en);
if (count($match[0]) != count($match_en[0])) {
echo "Invalid number of parameters in $filename on line " . ($line_no + 2 + $key) . ".\n";
echo ": source in $filename_en on line " . ($line_no_en + 2 + $key) . ".\n";
}
foreach ($match[0] as $key => $parameter) {
if (!isset($match_en[0][$key])) {
break;
}
if ($parameter != $match_en[0][$key]) {
echo "Invalid parameter type/opt/reference in $filename on line " . ($line_no + 2 + $key) . ".\n";
echo ": source in $filename_en on line " . ($line_no_en + 2 + $key) . ".\n";
}
}
}
}
chdir($cwd);
<file_sep>/branches/dev_docbook4/dbk4_upgrade.sh
#!/bin/sh
for file in `find en/functions -name "*.xml"` `find en/pear -name "*.xml"`
do
echo $file
cat $file | sed -e"s/&/&/g" | sabcmd dbk4_upgrade.xsl | sed -e's/&/\&/g' > tmp
mv $file $file.bak
mv tmp $file
done
<file_sep>/tags/dev_docbook4_branchpoint/scripts/entities.php
#!/usr/bin/php -q
<?php
if ($argc > 3 || in_array($argv[1], array('--help', '-help', '-h', '-?'))) {
?>
Find entity usage in phpdoc xml files and
list used and unused entities.
Usage:
<?=$argv[0]?> [<entity-file>] [<language-code>]
<entity-file> must be a file name (with relative
path from the phpdoc root) to a file containing
<!ENTITY...> definitions. Defaults to global.ent.
<language-code> must be a valid language code used in the repository, or
'all' for all languages. Defaults to en.
The script will generate an entity_usage.txt
file, containing the entities defined in the
<entity-file>.
Written by <NAME> <<EMAIL>>, 2001-09-22
<?php
exit;
}
// CONFIG SECTION
$docdir = "../"; // Main directory of the PHP documentation (one dir up in cvs)
/*********************************************************************/
/* Nothing to modify below this line */
/*********************************************************************/
// Long runtime
set_time_limit(0);
// Array to collect the entities
$defined_entities = array();
// Default values
$langcode = "en";
$filename = "global.ent";
// Parameter value copying
if ($argc == 3) {
$langcode = $argv[2];
if ($langcode === 'all') {
$langcode = '..';
}
}
if ($argc >= 2) {
$filename = $argv[1];
}
/*********************************************************************/
/* Here starts the functions part */
/*********************************************************************/
// Extract the entity names from the file
function extract_entity_definitions ($filename, &$entities)
{
// Read in the file, or die
$file_array = file ($filename);
if (!$file_array) { die ("Cannot open entity file ($filename)."); }
// The whole file in a string
$file_string = preg_replace("/[\r\n]/", "", join ("", $file_array));
// Find entity names
preg_match_all("/<!ENTITY\s+(.*)\s+/U", $file_string, $entities_found);
$entities_found = $entities_found[1];
// Convert to hash
foreach ($entities_found as $entity_name) {
$entities[$entity_name] = array();
}
// Return with a useful regexp part
return "&(" . join("|", $entities_found) . ");";
} // extract_entity_definitions() function end
// Checks a diretory of phpdoc XML files
function check_dir($dir, &$defined_entities, $entity_regexp)
{
// Collect files and diretcories in these arrays
$directories = array();
$files = array();
// Open and traverse the directory
$handle = @opendir($dir);
while ($file = @readdir($handle)) {
if (preg_match("/^\.{1,2}/",$file) || $file == 'CVS')
continue;
// Collect files and directories
if (is_dir($dir.$file)) { $directories[] = $file; }
else { $files[] = $file; }
}
@closedir($handle);
// Sort files and directories
sort($directories);
sort($files);
// Files first...
foreach ($files as $file) {
check_file($dir.$file, $defined_entities, $entity_regexp);
}
// than the subdirs
foreach ($directories as $file) {
check_dir($dir.$file."/", $defined_entities, $entity_regexp);
}
} // check_dir() function end
function check_file ($filename, &$defined_entities, $entity_regexp)
{
// Read in file contents
$contents = preg_replace("/[\r\n]/", "", join("", file($filename)));
// Find all entity usage in this file
preg_match_all("/$entity_regexp/U", $contents, $entities_found);
// No entities found
if (count($entities_found[1]) == 0) { return; }
// New occurances found, so increase the number
foreach ($entities_found[1] as $entity_name) {
if (isset($defined_entities[$entity_name])) { $defined_entities[$entity_name][] = $filename; }
}
} // check_file() function end
/*********************************************************************/
/* Here starts the program */
/*********************************************************************/
// Check for directory validity
if (!@is_dir($docdir . $lang)) {
die("The $lang language code is not valid");
}
// If directory is OK, start with the header
echo "\nStart searching ...\n";
$entity_regexp = extract_entity_definitions($docdir . $filename, $defined_entities);
// Check the requested directory
check_dir("$docdir$langcode/", $defined_entities, $entity_regexp);
echo "Generating entity_usage.txt ...\n";
$fp = fopen("entity_usage.txt", "w");
fwrite($fp, "ENTITY USAGE STATISCTICS
=========================================================
In this file you can find entity usage stats compiled
from the entity file: $filename. The entity usage
was tested in the $langcode tree at phpdoc. You may
find many unused entities here. Please do not delete
the entities, unless you make sure, no translation
makes use of the entity. Interestingly, the purpouse
of this statistics is to reduce the number of unused
entities in phpdoc. Here comes the numbers and file
names:
=========================================================
");
foreach ($defined_entities as $entity_name => $files) {
$num = count($files);
if ($num == 0) { $prep = "++ "; } else { $prep = " "; }
fwrite($fp, $prep . sprintf("%-30s %d", $entity_name, count($files)). "\n");
}
fclose($fp);
echo "Done!\n";
?>
<file_sep>/tags/POST_DOCBOOK5/chm/make_chm.php
<?php
/*
PLEASE DO NOT MAKE ANY MAJOR MODIFICATIONS TO THIS CODE!
There is a new script collection on the way to replace
these scripts. Please see the htmlhelp folder for the new
build system.
See make_chm.README for information about this system.
*/
include_once('common.php');
include_once('chm_settings.php');
$INDEX_IN_HTML = "index.html";
if (empty($FANCY_PATH)) { $FANCY_PATH = $HTML_PATH; }
// Files on the top level of the TOC
$MAIN_FILES = array(
"preface.html",
"getting-started.html",
"install.html",
"langref.html",
"security.html",
"features.html",
"funcref.html",
"internals.html",
"faq.html",
"appendices.html"
);
// Header for index and toc
$HEADER = '<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML//EN">
<html>
<head>
<meta name="generator" content="PHP 4 - Auto TOC script">
<!-- Sitemap 1.0 -->
</head>
<body>
<object type="text/site properties">
<param name="Window Styles" value="0x800227">
</object>
<ul>';
makeProjectFile();
makeContentFiles();
// Generate the HTML Help content files
function makeContentFiles()
{
global $LANGUAGE, $MANUAL_TITLE, $HEADER, $MAIN_FILES,
$HTML_PATH, $INDEX_IN_HTML, $FIRST_PAGE;
$toc = fopen("chm/php_manual_$LANGUAGE.hhc", "w");
$index = fopen("chm/php_manual_$LANGUAGE.hhk", "w");
// Write out file headers
fputs_wrapper($toc, $HEADER);
fputs_wrapper($index, $HEADER);
// Read original index file and drop out newlines
$indexline = oneLiner("$HTML_PATH/$INDEX_IN_HTML");
// Print out the objects, autoparsing won't find
mapAndIndex($MANUAL_TITLE, $FIRST_PAGE, " ", $toc, $index, 21);
// There is a fancy index
if ($FIRST_PAGE != $INDEX_IN_HTML) {
// Find the name of the Table of Contents
preg_match('|CLASS=\"TOC\" *><DL *><DT *><B *>(.*)</B|U', $indexline, $match);
if (empty($match[1])) { // Fallback
$match[1] = "Table of Contents";
}
mapAndIndex($match[1], $INDEX_IN_HTML, " ", $toc, $index, 21);
}
// Find the name of the Preface
preg_match('|<A +HREF="preface.html" *>([^<]*)</A *>|U', $indexline, $match);
if (empty($match[1])) { // Fallback
$match[1] = "Preface";
}
mapAndIndex($match[1], "preface.html", " ", $toc, $index);
// Now autofind the main pages
$MAIN_REGEXP = join("|", $MAIN_FILES);
preg_match_all("![IVX]+[^<]*<A\\s+HREF=\"($MAIN_REGEXP)\"\\s*>([^<]+)</A\\s*>(.+)</DT\\s*></DL\\s*></DD\\s*><DT\\s*>!Ui", $indexline, $matches, PREG_SET_ORDER);
// Go through the main files, and link in subpages
foreach ($matches as $matchinfo) {
mapAndIndex($matchinfo[2], $matchinfo[1], " ", $toc, $index);
fputs_wrapper($toc, "\n <ul>\n");
preg_match_all("!<A\\s+HREF=\"([^\"]+)\"\\s*>([^<]*)</A\\s*>!iU", $matchinfo[3], $subpages, PREG_SET_ORDER);
foreach ($subpages as $spinfo) {
mapAndIndex($spinfo[2], $spinfo[1], " ", $toc, $index);
findDeeperLinks($spinfo[1], $toc, $index);
}
fputs_wrapper($toc, "\n </ul>\n");
}
// Link in directly the copyright page
$copyline = oneLiner("$HTML_PATH/copyright.html");
preg_match('|<A\\s+NAME="copyright"\\s*></A\\s*><P\\s*><B\\s*>([^<]*)</B|U', $copyline, $match);
if (empty($match[1])) { // Fallback
$match[1] = "Copyright";
}
mapAndIndex($match[1], "copyright.html", " ", $toc, $index, 17);
// Write out closing line, and end files
fputs_wrapper($index, " </ul>\n</body>\n</html>");
fputs_wrapper($toc, " </ul>\n</body>\n</html>");
fclose($index);
fclose($toc);
} // makeContentfiles() function end
// Generates the HTML Help project file
function makeProjectFile()
{
global $LANGUAGE, $MANUAL_TITLE, $LANGUAGES,
$HTML_PATH, $FANCY_PATH, $INDEX_IN_HTML,
$FIRST_PAGE;
// Try to find the fancy index file
if (file_exists("$FANCY_PATH/fancy-index.html")) {
$FIRST_PAGE = "fancy-index.html";
} else {
$FIRST_PAGE = $INDEX_IN_HTML;
}
$FIRST_PAGEP = substr($FANCY_PATH, 4) . "\\$FIRST_PAGE";
// Start writing the project file
$project = fopen("chm/php_manual_$LANGUAGE.hhp", "w");
fputs_wrapper($project, "[OPTIONS]\n");
fputs_wrapper($project, "Compatibility=1.1 or later\n");
fputs_wrapper($project, "Compiled file=php_manual_$LANGUAGE.chm\n");
fputs_wrapper($project, "Contents file=php_manual_$LANGUAGE.hhc\n");
fputs_wrapper($project, "Index file=php_manual_$LANGUAGE.hhk\n");
fputs_wrapper($project, "Default Window=phpdoc\n");
fputs_wrapper($project, "Default topic=$FIRST_PAGEP\n");
fputs_wrapper($project, "Display compile progress=Yes\n");
fputs_wrapper($project, "Full-text search=Yes\n");
// Get the proper language code from the array
fputs_wrapper($project, "Language={$LANGUAGES[$LANGUAGE]["langcode"]}\n");
// Now try to find out how the manual named in the actual language
// this must be in the index.html file as the title (DSSSL generated)
$content = oneLiner("$HTML_PATH/$INDEX_IN_HTML");
if (preg_match("|<TITLE\s*>([^<]*)</TITLE\s*>|U", $content, $found)) {
$MANUAL_TITLE = $found[1];
} else { // Fallback
$MANUAL_TITLE = "PHP Manual";
}
fputs_wrapper($project, "Title=$MANUAL_TITLE\n");
fputs_wrapper($project, "Default Font={$LANGUAGES[$LANGUAGE]['preferred_font']}\n");
// Define the phpdoc window style (adds more functionality)
fputs_wrapper($project, "\n[WINDOWS]\nphpdoc=\"$MANUAL_TITLE\",\"php_manual_$LANGUAGE.hhc\",\"php_manual_$LANGUAGE.hhk\"," .
"\"$FIRST_PAGEP\",\"$FIRST_PAGEP\",,,,,0x23520,,0x386e,,,,,,,,0\n");
// Write out all the filenames as in FANCY_PATH
fputs_wrapper($project, "\n[FILES]\n");
$handle = opendir($FANCY_PATH);
while (false !== ($file = readdir($handle))) {
if ($file != "." && $file != "..") {
fputs_wrapper($project, substr($FANCY_PATH, 4)."\\$file\n");
}
}
closedir($handle);
fclose($project);
} // makeProjectFile() function end
// Print out a SiteMap object for a file
function mapAndIndex($name, $local, $tabs, $toc, $index, $imgnum = "auto")
{
global $FANCY_PATH;
$name = str_replace('"', '"', $name);
fputs_wrapper($toc, "
$tabs<li><object type=\"text/sitemap\">
$tabs <param name=\"Name\" value=\"$name\">
$tabs <param name=\"Local\" value=\"".substr($FANCY_PATH, 4)."\\$local\">
");
if ($imgnum != "auto") {
fputs_wrapper($toc, "$tabs <param name=\"ImageNumber\" value=\"$imgnum\">\r\n");
}
fputs_wrapper($toc, "$tabs </object>\r\n");
fputs_wrapper($index, "
<li><object type=\"text/sitemap\">
<param name=\"Local\" value=\"".substr($FANCY_PATH, 4)."\\$local\">
<param name=\"Name\" value=\"$name\">
</object></li>
");
} // mapAndIndex() function end
// Process a file, and find any links need to be presented in tree
function findDeeperLinks ($filename, $toc, $index)
{
global $HTML_PATH;
$contents = oneLiner("$HTML_PATH/$filename");
// Find all sublinks
if (preg_match_all("!<DT\\s*><A\\s+HREF=\"(([\\w\\.-]+\\.)+html)(\\#[\\w\\.-]+)?\"\\s*>(.*)</A\\s*>!U", $contents, $matches, PREG_SET_ORDER)) {
// Print out the file informations for all the links
fputs_wrapper($toc, "\n <ul>");
foreach ($matches as $onematch) {
$param["html"] = $onematch[1];
if (!empty($onematch[3])) {
$param["html"] .= $onematch[3];
}
$param["title"] = strip_tags($onematch[4]);
mapAndIndex($param["title"], $param["html"], " ", $toc, $index);
}
fputs_wrapper($toc, " </ul>\n");
} else {
// Uncomment this if you want to debug the above pregs
// Note: there are many files normally without deeper
// TOC info, eg. language.expressions.html
// echo "no deeper TOC info found in $filename\n";
// return;
}
} // findDeeperLinks() function end
?>
<file_sep>/tags/pre-xchm-14/htmlhelp/filter_files.php
<?php
/*
This file is part of the Windows Compiled HTML Help
Manual Generator of the PHP Documentation project.
The filters included in this file are to refine
the XSL generated HTML codes. Some filters may
be converted to XSL templates, but not all.
*/
$counter = filterFiles();
// Filter XSL generated files through some refine filters
function filterFiles()
{
global $HTML_SRC, $HTML_TARGET, $INDEX_FILE, $LANGUAGE;
// How many files were processed
$counter = 0;
// Try to figure out what index file to use
if (file_exists("$HTML_SRC/index.html")) {
$INDEX_FILE = "index.html";
} else { $INDEX_FILE = "manual.html"; }
// Open the directory, and do the work on all HTML files
$handle = opendir($HTML_SRC);
while (false !== ($filename = readdir($handle))) {
// Only process html files
if (strpos($filename, ".html")) {
$counter++;
refineFile($filename);
echo "> $counter\r";
}
}
closedir($handle);
// Copy all supplemental files to the target directory
exec("copy suppfiles\\html $HTML_TARGET /Y");
// Copy all HTML Help files to the target directory too
exec("copy $HTML_SRC\\php_manual_$LANGUAGE.hh? $HTML_TARGET /Y");
// Rewrite script file to include current language and date
$script_js = join("", file("$HTML_TARGET/_script.js"));
$script_js = str_replace("LANGUAGE_HERE", $LANGUAGE, $script_js);
$script_js = str_replace("DATE_HERE", date("Y-m-d"), $script_js);
$fp = fopen("$HTML_TARGET/_script.js", "w");
fwrite($fp, $script_js);
fclose($fp);
return $counter;
} // filterFiles() function end
// Refine HTML code in XSL generated files
function refineFile($filename)
{
global $HTML_SRC, $HTML_TARGET, $INDEX_FILE, $preNum;
// The number of <pre> parts is zero (used for example copy links)
$preNum = 0;
// Read in the contents of the source file
$content = join("", file("$HTML_SRC/$filename"));
//------------------------------------------------------------------
// Find page title and format it properly
preg_match('!<title>\s*(.+)</title>!Us', $content, $matched);
$page_title = $matched[1];
// Replace title with simple <title> content [shorter, without tags]
$content = preg_replace(
'!<h(\d)[^>]*>.+</h\1>!Us',
"<h1 class=\"masterheader\"><span id=\"pageTitle\">$page_title</span></h1>",
$content,
1
);
//------------------------------------------------------------------
// Add divisions for skin support
// Make the document invisible by default, adding a new first div
$content = preg_replace(
'!(<div class="(\w+)">)!Us',
'<div id="pageContent" style="display:none;">\1<div id="pageHeaders">',
$content,
1
);
// Put there the end of this pageContent
$content = str_replace(
'</body></html>',
'</div></body></html>',
$content
);
// For headers we have several possibilities
if (strpos($content, '<div class="refnamediv">') !== FALSE) {
// A function page
if (!strpos($content, "refsynopsisdiv")) {
$content = str_replace(
'</h2></div><div class="refsect1">',
'</h2></div></div><div id="pageText"><div class="refsect1">',
$content
);
}
// The COM or VARIANT classes page (which contain refsynopsisdiv)
else {
$content = str_replace(
'<div class="refsynopsisdiv">',
'</div><div id="pageText"><div class="refsynopsisdiv">',
$content
);
}
}
// Normal page, and not an index
elseif ($filename != $INDEX_FILE) {
$content = preg_replace(
'!</h1></div>(<p>)?</div>!',
'</h1></div>\\1</div></div><div id="pageText">',
$content
);
}
// The index page
else {
// Delete titlepage div and
// add pageHeader end and pageText start
$content = str_replace(
array("<div class=\"titlepage\">", "<hr></div>"),
array("", "<hr>"),
$content
);
$content = preg_replace(
'!</h1></div><div>!',
'</h1></div></div><div id="pageText"><div>',
$content
);
}
// End that pageText div before the user notes
$content = str_replace(
'<a name="_user_notes">',
'</div><a name="_user_notes">',
$content
);
// If this is the index file, correct it
if ($filename == $INDEX_FILE) {
$content = newIndex($content);
}
//------------------------------------------------------------------
// Change pre sections look (examples, screen outputs, etc).
$content = preg_replace_callback(
'!<pre class="([^"]+)">(.+)</pre>!Us',
"formatPre",
$content
);
//------------------------------------------------------------------
// Put <p> tags after all </ul> or </div> or </table> close tags to
// enable CSS support for those paragraphs (these break a <p>)
// BUT do not put a P after our special notes container
$content = preg_replace('!</(ul|div|table)>!Us', '</\\1><p>', $content);
$content = str_replace('<div id="pageNotes"></div><p>', '<div id="pageNotes"></div>', $content);
//------------------------------------------------------------------
// Delete duplicate <p> tags from code, unneded <p></p> parts, and
// <p> before <table> or <div> or </div> or </body> or <ul>
$content = preg_replace('!<p>\s*<p>!Us', '<p>', $content);
$content = preg_replace('!<p>\s*</p>!Us', '', $content);
$content = preg_replace('!<p>\s*<(table|div|/div|/body|ul)!Us', '<\\1', $content);
//------------------------------------------------------------------
// Drop out all the <div> and </div> tags left (no need to have them)
//$content = preg_replace('!</?div[^>]*>!Us', '', $content);
// !!! Temporary fix for XSLT output escaping problems
$content = preg_replace("!&raquo; !", "» ", $content);
$content = preg_replace("!&nbsp; !", " ", $content);
//------------------------------------------------------------------
// Write out file to HTML output directory
$fp = fopen("$HTML_TARGET/$filename", "w");
fwrite($fp, $content);
fclose($fp);
} // newFace() function end
// Make the old index look somewhat better
function newIndex ($content)
{
global $HTML_TARGET;
// Get contents we need to build the _index.html file
preg_match("!^(.+)<hr>!s", $content, $_index1);
preg_match("!(</div></div><a name=\"_user_notes\">.+</html>)!s", $content, $_index2);
// Write out the two components to form a complete file
$fp = fopen("$HTML_TARGET/_index.html", "w");
fwrite($fp, $_index1[1] . $_index2[1]);
fclose($fp);
// Drop out authors list (this is on the frontpage)
$content = preg_replace(
'!<div id="pageText"><div>.*<hr>!Us',
'<div id="pageText">',
$content
);
// Get TOC title from HTML code
preg_match(
'!<div class="toc"><p><b>(.+)</b></p>!U',
$content,
$match
);
// Put toc title into title places
$content = preg_replace(
'!<title>(.+)</title>!U',
"<title>$match[1]</title>",
$content
);
$content = preg_replace(
'!<span id="pageTitle">(.+)</span>!U',
"<span id=\"pageTitle\">$match[1]</span>",
$content
);
// Drop out small TOC title
$content = preg_replace(
'!<div class="toc"><p><b>(.+)</b></p>!U',
'<div class="toc">',
$content
);
return $content;
} // newIndex() function end
// Change pre sections look
function formatPre ()
{
// Number of <pre> sections on this page
global $preNum;
// Construct clipboard copy link
$preNum++;
$linkwdiv = '<div class="codelink"><a href="javascript:void(0);" onclick="copyExample(\''
. $preNum . '\')">copy to clipboard</a></div><div class="examplecode">';
// Replace all hard line breaks
list($pre_found) = func_get_args();
// Not a PHP example
if ($pre_found[1] != 'php') {
return $linkwdiv . '<code id="example_' . $preNum . '">' . pre2code(trim($pre_found[2])) . '</code></div><p>';
}
// Convert entities to characters for color coding
$example = str_replace(
array(">", "<", "&", """),
array(">", "<", "&", "\""),
trim($pre_found[2])
);
if (!strstr($example, "<?php")) {
$example = "<?php " . $example . " ?>";
$delimiter = FALSE;
} else {
$delimiter = TRUE;
}
// Get highlited source code
$colored_example = highlight_string($example, true);
// Strip out PHP delmiter, if we added it
if (!$delimiter) {
$colored_example = str_replace(
array (
'<font color="#0000CC"><?php </font>',
'<?php ',
'<font color="#0000CC">?></font>'
),
array ('', '', ''),
$colored_example
);
}
// Get much smaller source code by converting
// display identical things to smaller size
$colored_example = str_replace(
array("\n", "<code>", "</code>", " ", "<br />"),
array("", "", "", " ", "\n"),
$colored_example
);
// Pre container to strip out uneeded font tags
$colored_example = '<pre>' . $colored_example . '</pre>';
$colored_example = str_replace(
array('<pre><font color="#000000">', '<pre><span style="color: #000000">', '</font></pre>', '</span></pre>'),
array('', '', '', ''),
$colored_example
);
// Get color settings
$color_settings = array(
'<span class="cs">' => '<font color="' . ini_get("highlight.string") . '">',
'<span class="cc">' => '<font color="' . ini_get("highlight.comment") . '">',
'<span class="ck">' => '<font color="' . ini_get("highlight.keyword") . '">',
'<span class="cb">' => '<font color="' . ini_get("highlight.bg") . '">',
'<span class="cd">' => '<font color="' . ini_get("highlight.default") . '">',
'<span class="ch">' => '<font color="' . ini_get("highlight.html") . '">',
'</span>' => '</font>'
);
// Convert colors to classes spaned
$colored_example = str_replace(
array_values($color_settings),
array_keys($color_settings),
$colored_example
);
// Try to find function names so they can be linked
// This patterns is what we are searching for:
// <span class="cd">array_keys </span><span class="ck">(
$colored_example = links2Examples(
'!<span class="cd">([a-z0-9_]+)\s*</span><span class="ck">\(!Us',
$colored_example,
1,
'cd'
);
// control structures or other keywords, like
// exit, print with possibly something before
// and after them
// Note: I do not link if, else and the
// other control structures in, because they are
// too common, and linking them would clutter up
// the examples
$colored_example = links2Examples(
'!<span class="ck">[^<]*(<br>)?[^<]*' .
'(exit|die|echo|print|empty|isset|unset|break|continue' .
'|static|global|array)[^<]*' .
'</span>!Us',
$colored_example,
2,
'ck'
);
// Return with the converted example
return $linkwdiv . '<code id="example_' . $preNum . '">' . pre2code($colored_example) . '</code></div><p>';
} // formatPre() function end
// Convert <pre> contained code to text for the <code> container
function pre2code ($text)
{
return str_replace(
array(' ', "\n"),
array(' ', "<br>\n"),
$text
);
} // pre2code() function end
// Find string matching a regexp and make function/control
// structures/keywords links
function links2Examples($regexp, $example, $idx, $class)
{
global $HTML_SRC;
// Try to find matching text in $example
if (preg_match_all($regexp, $example, $found)) {
// This is where we store all text to replace,
// [original text and replacement text]
$replace_array = array(
0 => array(),
1 => array()
);
// Loop through all function names, and try to find a file
// for them (they can be user defined functions)
foreach ($found[$idx] as $num => $reptext) {
// The main part of this filename
$filepart = strtolower(str_replace("_", "-", $reptext));
// Possible full filenames
$files = array(
"function.$filepart.html",
"class.$filepart.html",
"control-structures.$filepart.html"
);
// Guess what should be the filename for this
foreach ($files as $filename) {
// If this file exists, then we are OK
if (@file_exists("$HTML_SRC/$filename")) {
$replace_array[0][] = $found[0][$num];
$replace_array[1][] = str_replace(
$reptext,
"<a href=\"$filename\" class=\"$class\">$reptext</a>",
$found[0][$num]
);
break;
}
}
}
// Perform string replacement on example content,
// only replace functions where we can link
$example = str_replace(
$replace_array[0],
$replace_array[1],
$example
);
}
// Maybe we modified something, maybe not.
// Return with the current $example text.
return $example;
} // links2Examples() function end
?><file_sep>/tags/AFTER_REF_STRUCT_DEV_MERGE/configure.php
<?php
/*
+----------------------------------------------------------------------+
| PHP Version 5 |
+----------------------------------------------------------------------+
| Copyright (c) 1997-2007 The PHP Group |
+----------------------------------------------------------------------+
| This source file is subject to version 3.0 of the PHP license, |
| that is bundled with this package in the file LICENSE, and is |
| available through the world-wide-web at the following url: |
| http://www.php.net/license/3_0.txt. |
| If you did not receive a copy of the PHP license and are unable to |
| obtain it through the world-wide-web, please send a note to |
| <EMAIL> so we can mail you a copy immediately. |
+----------------------------------------------------------------------+
| Authors: <NAME> <<EMAIL>> |
+----------------------------------------------------------------------+
$Id$
*/
$cvs_id = '$Id$';
$srcdir = "./";
echo "configure.php: $cvs_id\n";
// Settings
$cygwin_php_bat = '../phpdoc-tools/php.bat';
$cygwin_jade = '../phpdoc-tools/jade/jade.exe';
$cygwin_openjade = '../phpdoc-tools/openjade/openjade.exe';
$cygwin_nsgmls = '../phpdoc-tools/jade/nsgmls.exe';
$cygwin_onsgmls = '../phpdoc-tools/openjade/onsgmls.exe';
$cygwin_xsltproc = '../phpdoc-tools/libxml/xsltproc.exe';
$cygwin_xmllint = '../phpdoc-tools/libxml/xmllint.exe';
$php_bin_names = array('php', 'php5', 'cli/php', 'php.exe', 'php5.exe', 'php-cli.exe', 'php-cgi.exe');
$jade_bin_names = array('openjade', 'jade', 'openjade.exe', 'jade.exe');
$nsgmls_bin_names = array('onsgmls', 'nsgmls', 'onsgmls.exe', 'nsgmls.exe');
$xsltproc_bin_names = array('xsltproc', 'xsltproc.exe');
$xmllint_bin_names = array('xmllint', 'xmllint.exe');
$catalogs = array(
"$srcdir/entities/ISO/catalog",
"$srcdir/dsssl/docbook/catalog",
"../phpdoc-tools/jade/catalog",
"/usr/share/sgml/CATALOG.docbk41",
"/usr/share/sgml/CATALOG.jade_dsl",
"$srcdir/dsssl/defaults/catalog",
);
$sources = array("$srcdir/../php-src", "$srcdir/../php5");
$pear_sources = array("$srcdir/../pear");
$pecl_sources = array("$srcdir/../pecl");
$infiles_cache = "$srcdir/infiles.cache";
// Reject old PHP installations
if (phpversion() < 5) {
echo "PHP 5 or above is required. Version detected: " . phpversion() . "\n";
exit(100);
}
else {
echo "PHP version: " . phpversion() . "\n";
}
echo "\n";
$ac = array();
$ac['srcdir'] = $srcdir;
$ac['WORKDIR'] = $srcdir;
$ac['PHP'] = '';
$ac['CYGWIN'] = 0;
$ac['INIPATH'] = './scripts';
$ac['JADE'] = '';
$ac['WINJADE'] = 0;
$ac['NSGMLS'] = '';
$ac['XSLTPROC'] = '';
$ac['XMLLINT'] = '';
$ac['DOCBOOK_HTML'] = "$srcdir/docbook/docbook-dsssl/html/docbook.dsl";
$ac['DOCBOOK_PRINT'] = "$srcdir/docbook/docbook-dsssl/print/docbook.dsl";
$ac['CATALOG'] = '';
$ac['PHP_SOURCE'] = '';
$ac['PEAR_SOURCE'] = '';
$ac['PECL_SOURCE'] = '';
$ac['EXT_SOURCE'] = '';
$ac['HTMLCSS'] = '';
$ac['CHMENABLED'] = 'no';
$ac['CHMONLY_INCL_BEGIN'] = '<!--';
$ac['CHMONLY_INCL_END'] = '-->';
$ac['INTERNALSDISABLED'] = 'no';
$ac['INTERNALS_EXCL_BEGIN'] = '';
$ac['INTERNALS_EXCL_END'] = '';
$ac['HACK_RTL_LANGS_PAGES'] = '';
$ac['HACK_RTL_LANGS_PHPWEB'] = '';
$ac['LANG_HACK_FOR_HE'] = 'no';
$ac['LANG'] = 'en';
$ac['LANGWEB'] = 'en';
$ac['PHP_BUILD_DATE'] = date('Y-m-d');
$ac['MANUAL'] = 'php_manual_en';
$ac['PAPER_TYPE'] = '';
$ac['PDF_PAPER_TYPE'] = '';
$ac['NUMBER_FIRST'] = '#f';
$ac['LEFT_MARGIN'] = '';
$ac['RIGHT_MARGIN'] = '';
$ac['TOP_MARGIN'] = '';
$ac['BOTTOM_MARGIN'] = '';
$ac['HEADER_MARGIN'] = '';
$ac['FOOTER_MARGIN'] = '';
$ac['LINE_SPACING'] = '';
$ac['HEAD_BEFORE'] = '';
$ac['HEAD_AFTER'] = '';
$ac['BODY_START'] = '';
$ac['BLOCK_SEP'] = '';
$ac['TREESAVING'] = '#f';
$ac['ENCODING'] = '';
$ac['PALMDOCTITLE'] = '';
$ac['HTMLHELP_ENCODING'] = '';
$ac['SP_OPTIONS'] = 'SP_ENCODING=XML SP_CHARSET_FIXED=YES';
$ac['FORCE_DOM_SAVE'] = false;
$ac['PARTIAL'] = false;
$allowed_opts = array(
'help',
'force-dom-save',
'partial',
'with-php=',
'with-jade=',
'with-nsgmls=',
'with-xsltproc=',
'with-xmllint=',
'with-dsssl=',
'with-source=',
'with-pear-source==',
'with-pecl-source==',
'with-extension=',
'with-htmlcss=',
'with-chm=',
'without-internals',
'with-lang=',
'with-treesaving',
);
foreach ($_SERVER['argv'] as $opt) {
if (strpos($opt, "=") !== false) {
list($o, $v) = explode("=", $opt);
} else {
$o = $opt;
$v = "yes";
}
switch ($o) {
case '--help':
usage();
exit();
case '--with-cygwin';
if ($v == "yes") {
$ac['CYGWIN'] = 1;
} else {
$ac['GYGWIN'] = 0;
}
break;
case '--with-php':
$ac['PHP'] = $v;
break;
case '--with-inipath':
$ac['INIPATH'] = $v;
break;
case '--with-jade':
$ac['JADE'] = $v;
break;
case '--with-nsgmls':
$ac['NSGMLS'] = $v;
break;
case '--with-xsltproc':
$ac['XSLTPROC'] = $v;
break;
case '--with-xmllint':
$ac['XMLLINT'] = $v;
break;
case '--with-dsssl':
$ac['DOCBOOK_HTML'] = "$v/html/docbook.dsl";
$ac['DOCBOOK_PRINT'] = "$v/print/docbook.dsl";
break;
case '--with-source':
$ac['PHP_SOURCE'] = $v;
break;
case '--with-pear-source':
$ac['PEAR_SOURCE'] = $v != '' ? $v : 'yes';
break;
case '--with-pecl-source':
$ac['PECL_SOURCE'] = $v != '' ? $v : 'yes';
break;
case '--with-extension':
$ac['EXT_SOURCE'] = $v;
break;
case '--with-htmlcss':
$ac['HTMLCSS'] = $v;
break;
case '--with-chm':
$ac['CHMENABLED'] = $v;
break;
case '--without-internals':
$ac['INTERNALSDISABLED'] = 'yes';
break;
case '--with-lang':
$ac['LANG'] = $v;
break;
case '--with-treesaving':
$ac['TREESAVING'] = '#t';
break;
case '--partial':
case '-p':
$ac['PARTIAL'] = $v;
break;
case '--force-dom-save':
$ac['FORCE_DOM_SAVE'] = true;
break;
}
}
function find_file($file_array)
{
$paths = explode(PATH_SEPARATOR, getenv('PATH'));
if (is_array($paths)) {
foreach ($paths as $path) {
foreach ($file_array as $name) {
if (file_exists("$path/$name") && is_file("$path/$name")) {
return "$path/$name";
}
}
}
}
return '';
}
// Check for PHP executable
echo 'checking for php: ';
if ($ac['PHP'] == '') {
// Find PHP executable ourselves
$ac['PHP'] = find_file($php_bin_names);
}
else if (file_exists($cygwin_php_bat)) {
$ac['PHP'] = $cygwin_php_bat;
echo "$cygwin_php_bat\n";
}
if ($ac['PHP'] == '') {
echo "no\n";
echo " Error: Could not find a PHP executable. Use --with-php=/path/to/php\n";
exit(103);
}
if (!file_exists($ac['PHP'])) {
echo "no\n";
echo " Error: --with-php: {$ac['PHP']} does not exist.\n";
exit(104);
}
else if (!is_file($ac['PHP'])) {
echo "no\n";
echo " Error: --with-php: {$ac['PHP']} is not a file.\n";
exit(105);
}
else {
echo $ac['PHP'] . "\n";
}
// Check for Jade/OpenJade executable
echo 'checking for jade: ';
if ($ac['JADE'] != '') {
// User-supplied
if (!file_exists($ac['JADE'])) {
echo "no\n";
echo " Error: --with-jade: {$ac['JADE']} does not exist.\n";
exit(106);
}
else if (!is_file($ac['JADE'])) {
echo "no\n";
echo " Error: --with-jade: {$ac['JADE']} is not a file.\n";
exit(107);
}
}
else {
// Find Jade executable ourselves
$ac['JADE'] = find_file($jade_bin_names);
}
if ($ac['JADE'] == '' && file_exists($cygwin_jade) && is_file($cygwin_jade)) {
$ac['JADE'] = $cygwin_jade;
$ac['WINJADE'] = 1;
}
else if ($ac['JADE'] == '' && file_exists($cygwin_openjade) && is_file($cygwin_openjade)) {
$ac['JADE'] = $cygwin_openjade;
$ac['WINJADE'] = 1;
}
if ($ac['JADE'] == '') {
echo "no\n";
echo " Error: Could not find a Jade/OpenJade executable. Use --with-jade=/path/to/jade\n";
}
else {
echo $ac['JADE'] . "\n";
}
// Check for NSGMLS executable
echo 'checking for nsgmls: ';
if ($ac['NSGMLS'] != '') {
// User-supplied
if (!file_exists($ac['NSGMLS'])) {
echo "no\n";
echo " Error: --with-nsgmls: {$ac['NSGMLS']} does not exist.\n";
exit(109);
}
else if (!is_file($ac['NSGMLS'])) {
echo "no\n";
echo " Error: --with-nsgmls: {$ac['NSGMLS']} is not a file.\n";
exit(110);
}
}
else {
// Find NSGMLS executable ourselves
$ac['NSGMLS'] = find_file($nsgmls_bin_names);
}
if ($ac['NSGMLS'] == '' && file_exists($cygwin_nsgmls) && is_file($cygwin_nsgmls)) {
$ac['NSGMLS'] = $cygwin_nsgmls;
}
else if ($ac['NSGMLS'] == '' && file_exists($cygwin_onsgmls) && is_file($cygwin_onsgmls)) {
$ac['NSGMLS'] = $cygwin_onsgmls;
}
if ($ac['NSGMLS'] == '') {
echo "no\n";
echo " Error: Could not find a NSGMLS executable. Use --with-nsgmls=/path/to/jade\n";
}
else {
echo $ac['NSGMLS'] . "\n";
}
// Check for XSLTPROC executable
echo 'checking for xsltproc: ';
if ($ac['XSLTPROC'] != '') {
// User-supplied
if (!file_exists($ac['XSLTPROC'])) {
echo "no\n";
echo " Error: --with-xsltproc: {$ac['XSLTPROC']} does not exist.\n";
exit(112);
}
else if (!is_file($ac['XSLTPROC'])) {
echo "no\n";
echo " Error: --with-xsltproc: {$ac['XSLTPROC']} is not a file.\n";
exit(113);
}
}
else {
// Find XSLTPROC executable ourselves
$ac['XSLTPROC'] = find_file($xsltproc_bin_names);
}
if ($ac['XSLTPROC'] == '' && file_exists($cygwin_xsltproc) && is_file($cygwin_xsltproc)) {
$ac['XSLTPROC'] = $cygwin_xsltproc;
}
if ($ac['XSLTPROC'] == '') {
echo "no\n";
echo " Warning: Could not find a XSLTPROC executable. XSL Transformations won't work.\n";
}
else {
echo $ac['XSLTPROC'] . "\n";
}
// Check for XMLLINT executable
echo 'checking for xmllint: ';
if ($ac['XMLLINT'] != '') {
// User-supplied
if (!file_exists($ac['XMLLINT'])) {
echo "no\n";
echo " Error: --with-xmllint: {$ac['XMLLINT']} does not exist.\n";
exit(114);
}
else if (!is_file($ac['XMLLINT'])) {
echo "no\n";
echo " Error: --with-xmllint: {$ac['XMLLINT']} is not a file.\n";
exit(115);
}
}
else {
// Find XMLLINT executable ourselves
$ac['XMLLINT'] = find_file($xmllint_bin_names);
}
if ($ac['XMLLINT'] == '' && file_exists($cygwin_xmllint) && is_file($cygwin_xmllint)) {
$ac['XMLLINT'] = $cygwin_xmllint;
}
if ($ac['XMLLINT'] == '') {
echo "no\n";
echo " Warning: Could not find a XMLLINT executable. XSL Validation won't work.\n";
}
else {
echo $ac['XMLLINT'] . "\n";
}
// Check for DocBook DSLs
echo 'checking for docbook (HTML): ';
if (!file_exists($ac['DOCBOOK_HTML'])) {
echo "no\n";
echo " Warning: {$ac['DOCBOOK_HTML']} does not exist.\n";
}
else if (!is_file($ac['DOCBOOK_HTML'])) {
echo "no\n";
echo " Warning: {$ac['DOCBOOK_HTML']} is not a file.\n";
}
else {
echo $ac['DOCBOOK_HTML'] . "\n";
}
echo 'checking for docbook (print): ';
if (!file_exists($ac['DOCBOOK_PRINT'])) {
echo "no\n";
echo " Warning: {$ac['DOCBOOK_PRINT']} does not exist.\n";
}
else if (!is_file($ac['DOCBOOK_PRINT'])) {
echo "no\n";
echo " Warning: {$ac['DOCBOOK_PRINT']} is not a file.\n";
}
else {
echo $ac['DOCBOOK_PRINT'] . "\n";
}
// Check for Catalogs
echo 'checking catalogs: ';
foreach ($catalogs as $catalog) {
if (file_exists($catalog) && is_file($catalog)) {
$ac['CATALOG'] .= " -c $catalog";
}
}
if ($ac['CATALOG'] == '') {
echo "no\n";
echo " Warning: No catalog files found.\n";
}
else {
$ac['CATALOG'] = substr($ac['CATALOG'], 1);
echo $ac['CATALOG'] . "\n";
}
// Check for PHP Source
echo 'checking for PHP source: ';
if ($ac['PHP_SOURCE'] != '') {
if (!file_exists($ac['PHP_SOURCE'])) {
echo "no\n";
echo " Warning: {$ac['PHP_SOURCE']} does not exist.\n";
}
else if (!is_dir($ac['PHP_SOURCE'])) {
echo "no\n";
echo " Warning: {$ac['PHP_SOURCE']} is not a directory.\n";
}
else {
echo $ac['PHP_SOURCE'] . "\n";
}
}
else {
foreach ($sources as $source) {
if (file_exists($source) && is_dir($source)) {
$ac['PHP_SOURCE'] = $source;
break;
}
}
if ($ac['PHP_SOURCE'] == '') {
echo "no\n";
echo " Warning: No PHP source directory found.\n";
}
else {
echo $ac['PHP_SOURCE'] . "\n";
}
}
// Check for PEAR Source
echo 'checking for PEAR source: ';
if ($ac['PEAR_SOURCE'] != '') {
if ($ac['PEAR_SOURCE'] != 'yes') {
if (!file_exists($ac['PEAR_SOURCE'])) {
echo "no\n";
echo " Warning: {$ac['PEAR_SOURCE']} does not exist.\n";
}
else if (!is_dir($ac['PEAR_SOURCE'])) {
echo "no\n";
echo " Warning: {$ac['PEAR_SOURCE']} is not a directory.\n";
}
else {
echo $ac['PEAR_SOURCE'] . "\n";
}
}
else {
foreach ($pear_sources as $source) {
if (file_exists($source) && is_dir($source)) {
$ac['PEAR_SOURCE'] = $source;
break;
}
}
if ($ac['PEAR_SOURCE'] == '') {
echo "no\n";
echo " Warning: No PEAR source directory found.\n";
}
else {
echo $ac['PEAR_SOURCE'] . "\n";
}
}
}
else {
$ac['PEAR_SOURCE'] = 'no';
echo "no\n";
}
// Check for PECL Source
echo 'checking for PECL source: ';
if ($ac['PECL_SOURCE'] != '') {
if ($ac['PECL_SOURCE'] != 'yes') {
if (!file_exists($ac['PECL_SOURCE'])) {
echo "no\n";
echo " Warning: {$ac['PECL_SOURCE']} does not exist.\n";
}
else if (!is_dir($ac['PECL_SOURCE'])) {
echo "no\n";
echo " Warning: {$ac['PECL_SOURCE']} is not a directory.\n";
}
else {
echo $ac['PECL_SOURCE'] . "\n";
}
}
else {
foreach ($pecl_sources as $source) {
if (file_exists($source) && is_dir($source)) {
$ac['PECL_SOURCE'] = $source;
break;
}
}
if ($ac['PECL_SOURCE'] == '') {
echo "no\n";
echo " Warning: No PECL source directory found.\n";
}
else {
echo $ac['PECL_SOURCE'] . "\n";
}
}
}
else {
$ac['PECL_SOURCE'] = 'no';
echo "no\n";
}
// Check for additional PHP extensions
if ($ac['EXT_SOURCE'] != '') {
echo "checking for additional PHP extensions:\n";
$exts = explode(',', $ac['EXT_SOURCE']);
$ac['EXT_SOURCE'] = '';
foreach ($exts as $ext) {
if (file_exists("$ext/manual") && is_dir("$ext/manual")) {
$ac['EXT_SOURCE'] .= ":$ext";
echo " extension '$ext' ok\n";
}
else {
echo " extension '$ext' ignored\n";
}
}
}
// Check for CSS to use for HTML docs
echo 'checking for CSS to use for HTML docs: ';
if ($ac['HTMLCSS'] != '') {
echo $ac['HTMLCSS'] . "\n";
$ac['HTMLCSS'] = "(define %stylesheet% \"{$ac['HTMLCSS']}\")";
}
else {
echo "none\n";
}
// Check for CHM
echo 'checking for CHM-only inclusion: ';
if ($ac['CHMENABLED'] == 'yes') {
$ac['CHMONLY_INCL_BEGIN'] = '';
$ac['CHMONLY_INCL_END'] = '';
echo "enabled\n";
}
else {
$ac['CHMENABLED'] = 'no';
echo "disabled\n";
}
// Check for internals
echo 'checking for internals doc exclusion: ';
if ($ac['INTERNALSDISABLED'] == 'yes') {
$ac['INTERNALS_EXCL_BEGIN'] = '<!--';
$ac['INTERNALS_EXCL_END'] = '-->';
echo "yes\n";
}
else {
$ac['INTERNALSDISABLED'] = 'no';
echo "no\n";
}
// Check for language
echo 'checking for language: ';
if ($ac['LANG'] != 'en') {
if (!file_exists("$srcdir/{$ac['LANG']}")) {
echo "no\n";
echo " Error: Language '{$ac['LANG']}' not supported!\n";
exit(116);
}
$ac['MANUAL'] = "php_manual_{$ac['LANG']}";
switch ($ac['LANG']) {
case 'kr':
$ac['LANG'] = 'ko';
$ac['LANGWEB'] = 'ko';
$ac['LANGDIR'] = 'kr';
break;
case 'ja':
$ac['LANG'] = 'ja';
$ac['LANGWEB'] = 'ja';
$ac['LANGDIR'] = 'ja';
$ac['PHP_BUILD_DATE'] = date('Y/m/d');
break;
case 'he':
$ac['LANG'] = 'en';
$ac['LANGWEB'] = 'he';
$ac['LANGDIR'] = 'he';
$ac['LANG_HACK_FOR_HE'] = 'yes';
$ac['HACK_RTL_LANGS_PAGES'] = $ac['PHP'] . ' ' . "$srcdir/scripts/rtlpatch/rtlpatch.php ./html";
$ac['HACK_RTL_LANGS_PHPWEB'] = $ac['PHP'] . ' ' . "$srcdir/scripts/rtlpatch/rtlpatch.php ./php";
break;
case 'hk':
$ac['LANG'] = 'zh_hk';
$ac['LANGWEB'] = 'zh_hk';
$ac['LANGDIR'] = 'hk';
break;
case 'tw':
$ac['LANG'] = 'zh_tw';
$ac['LANGWEB'] = 'zh_tw';
$ac['LANGDIR'] = 'tw';
break;
case 'cn':
$ac['LANG'] = 'zh_cn';
$ac['LANGWEB'] = 'zh_cn';
$ac['LANGDIR'] = 'tw';
break;
default:
$ac['LANGWEB'] = $ac['LANG'];
$ac['LANGDIR'] = $ac['LANG'];
break;
}
echo $ac['LANG'] . "\n";
}
else {
$ac['LANGDIR'] = $ac['LANG'];
$ac['LANGWEB'] = $ac['LANG'];
echo "en (default)\n";
}
// Check paper type
if (in_array($ac['LANG'], explode('|', 'ar|cs|de|hu|it|ja|ko|pl|ro|sk|tr|zh_hk|zh_tw|zh_cn'))) {
$ac['PAPER_TYPE'] = 'A4';
$ac['PDF_PAPER_TYPE'] = 'a4';
}
else {
$ac['PAPER_TYPE'] = 'USletter';
$ac['PDF_PAPER_TYPE'] = 'letter';
}
// Localize order of number and element name in some headers autogenerated by Jade
if (in_array($ac['LANG'], explode('|', 'hu|ko'))) {
$ac['NUMBER_FIRST'] = '#t';
}
// Reduce margins?
echo 'checking for treesaving: ';
if ($ac['TREESAVING'] == '#t') {
$ac['LEFT_MARGIN'] = '(define %left-margin% 4pi)';
$ac['RIGHT_MARGIN'] = '(define %right-margin% 3pi)';
$ac['TOP_MARGIN'] = '(define %top-margin% 3pi)';
$ac['HEADER_MARGIN'] = '(define %header-margin% 2pi)';
$ac['FOOTER_MARGIN'] = '(define %footer-margin% 2pi)';
$ac['BOTTOM_MARGIN'] = '(define %bottom-margin% 3pi)';
$ac['LINE_SPACING'] = '(define %line-spacing-factor% 1.2)';
$ac['HEAD_BEFORE'] = '(define %head-before-factor% 0.6)';
$ac['HEAD_AFTER'] = '(define %head-after-factor% 0.3)';
$ac['BODY_START'] = '(define %body-start-indent% 3pi)';
$ac['BLOCK_SEP'] = '(define %block-sep% (* %para-sep% 1.2))';
echo "yes\n";
}
else {
echo "no\n";
}
// Force creation of .manual.xml
echo 'checking for forced .manual.xml: ';
if ($ac['FORCE_DOM_SAVE']) {
echo "yes\n";
}
else {
echo "no\n";
}
// Encoding
switch ($ac['LANG']) {
case 'zh_tw':
case 'zh_hk':
$ac['ENCODING'] = 'big5';
break;
case 'zh_cn':
$ac['ENCODING'] = 'gb2312';
break;
case 'cs':
case 'hu':
case 'ro':
case 'sk':
$ac['ENCODING'] = 'ISO-8859-2';
break;
case 'ar':
$ac['ENCODING'] = 'ISO-8859-6';
break;
case 'tr':
$ac['ENCODING'] = 'ISO-8859-9';
break;
case 'he':
$ac['ENCODING'] = 'ISO-8859-8';
break;
case 'el':
$ac['ENCODING'] = 'ISO-8859-7';
break;
default:
$ac['ENCODING'] = 'UTF-8';
break;
}
if ($ac['LANG_HACK_FOR_HE'] == 'yes') {
$ac['ENCODING'] = 'ISO-8859-8';
}
// Palm doc title
switch ($ac['LANG']) {
case 'de': $ac['PALMDOCTITLE'] = "'PHP Handbuch'"; break;
case 'es': $ac['PALMDOCTITLE']="'Manual de PHP'"; break;
case 'fr': $ac['PALMDOCTITLE']="'Manuel PHP'"; break;
case 'hu': $ac['PALMDOCTITLE']="'PHP Kézikönyv'"; break;
case 'it': $ac['PALMDOCTITLE']="'Manuale PHP'"; break;
case 'nl': $ac['PALMDOCTITLE']="'PHP Handleiding'"; break;
case 'pl': $ac['PALMDOCTITLE']="'Podręcznik PHP'"; break;
case 'pt_BR': $ac['PALMDOCTITLE']="'Manual do PHP'"; break;
case 'ro': $ac['PALMDOCTITLE']="'Manual PHP'"; break;
case 'zh_hk': $ac['PALMDOCTITLE']="PHP ¤âĽU"; break;
default: $ac['PALMDOCTITLE']="'PHP Manual'"; break;
}
switch ($ac['ENCODING']) {
case 'ISO-8859-2': $ac['HTMLHELP_ENCODING'] = 'windows-1250'; break;
case 'ISO-8859-6': $ac['HTMLHELP_ENCODING'] = 'windows-1256'; break;
case 'ISO-8859-8': $ac['HTMLHELP_ENCODING'] = 'windows-1255'; break;
case 'ISO-8859-9': $ac['HTMLHELP_ENCODING'] = 'windows-1254'; break;
default: $ac['HTMLHELP_ENCODING'] = $ac['ENCODING']; break;
}
$ac['ENCODING'] = 'UTF-8';
/* recursive glob() with a callback function */
function globbetyglob($globber, $userfunc)
{
foreach (glob("$globber/*") as $file) {
if (is_dir($file)) {
globbetyglob($file, $userfunc);
}
else {
call_user_func($userfunc, $file);
}
}
}
function find_dot_in($filename) {
if (substr($filename, -3) == '.in') {
$GLOBALS['infiles'][] = $filename;
}
}
function generate_output_file($in, $out, $ac) {
$data = file_get_contents($in);
if ($data === false)
return false;
foreach ($ac as $k => $v) {
$data = preg_replace('/@' . preg_quote($k) . '@/', $v, $data);
}
return file_put_contents($out, $data);
}
function make_scripts_executable($filename) {
if (substr($filename, -3) == '.sh') {
chmod($filename, 0755);
}
}
if (file_exists($infiles_cache)) {
$infiles = file($infiles_cache);
}
else {
$infiles = array();
globbetyglob($srcdir, 'find_dot_in');
file_put_contents($infiles_cache, implode("\n", $infiles));
}
$ac['AUTOGENERATED_RULES'] = '';
/*
foreach ($infiles as $in) {
$in = basename(chop($in));
$out = substr($in, 0, -3);
if ($in == 'configure.in') {
$ac['AUTOGENERATED_RULES'] .= "configure: configure.in\n"
. "\t autoconf\n";
}
else if ($in == 'manual.xml.in') {
}
else {
$ac['AUTOGENERATED_RULES'] .= "$in: $out config.status\n"
. "\t CONFIG_FILES=$@ CONFIG_HEADERS= ./config.status\n";
}
}
*/
foreach ($infiles as $in) {
$in = chop($in);
if (basename($in) == 'configure.in')
continue;
$out = substr($in, 0, -3);
echo "generating $out: ";
if (generate_output_file($in, $out, $ac)) {
echo "done\n";
}
else {
echo "fail\n";
exit(117);
}
}
globbetyglob($ac['INIPATH'], 'make_scripts_executable');
file_put_contents('./entities/phpweb.ent', '');
passthru('"' .$ac['PHP'] . '" ' . ' -c ' . $ac['INIPATH'] . ' -q ./scripts/file-entities.php');
passthru('rm -f entities/missing*');
passthru('rm -f entities/missing-ids.xml');
passthru('"' .$ac['PHP'] . '" ' . ' -c ' . $ac['INIPATH'] . ' -q ./scripts/missing-entities.php');
//print_r($ac);
$dom = new DOMDocument();
$dom->load("manual.xml", LIBXML_NOENT);
$dom->xinclude();
if ($ac['PARTIAL']) {
$node = $dom->getElementById($ac['PARTIAL']);
if (!$node) exit("Failed to find partial ID in source XML: " . $ac['PARTIAL']);
if ($node->tagName !== 'book' && $node->tagName !== 'set') {
// this node is not normally allowed here, attempt to wrap it
// in something else
$parents = array();
switch ($node->tagName) {
case 'refentry':
$parents[] = 'reference';
case 'part':
$parents[] = 'book';
break;
}
foreach ($parents as $name) {
$newNode = $dom->createElement($name);
$newNode->appendChild($node);
$node = $newNode;
}
}
$set = $dom->documentElement;
$set->nodeValue = '';
$set->appendChild($dom->createElement('title', 'PHP Manual (Partial)')); // prevent validate from complaining unnecessarily
$set->appendChild($node);
$dom->validate(); // we don't care if the validation works or not
$filename = '.manual.' . $ac['PARTIAL'] . '.xml';
$dom->save($filename);
echo "Partial manual saved to $filename, to build it run 'phd -d" . realpath($filename). "'\n";
exit(0);
}
if ($dom->validate()) {
echo "All good.\n";
$dom->save(".manual.xml");
echo "All you have to do now is run 'phd -d " . realpath(".manual.xml") . "'\n";
exit(0); // Tell the shell that this script finished successfully.
} else {
echo "eyh man. No worries. Happ shittens. Try again after fixing the errors above\n";
if ($ac['FORCE_DOM_SAVE']) {
// Allow the .manual.xml file to be created, even if it is not valid.
echo "Writing .manual.xml anyway\n";
$dom->save(".manual.xml");
}
exit(1); // Tell the shell that this script finished with an error.
}
<file_sep>/tags/dev_docbook4_branchpoint/mk_ini_set_table.sh
#! /bin/sh
# Quick hack to make a table of PHP options
# and where they can be changed
# <NAME>
# Mon Mar 19 04:57:02 PST 2001
main_c="../php4/main/main.c"
ini_set_table="en/functions/ini_set_table";
awk 'BEGIN {
print "<table>\n <title>Configuration options</title>"
print " <tgroup cols=\"3\">";
print " <thead>";
print " <row>";
print " <entry>Name</entry>";
print " <entry>Default</entry>";
print " <entry>Changeable</entry>";
print " </row>";
print " </thead>";
print " <tbody>";
}
$0 ~ /PHP_INI_.*\(/ && $0 !~ /^static/ && $0 !~ /PHP_INI_(BEGIN|END)/ {
nf = split($0,tmp,",");
varname = substr(tmp[1], index(tmp[1], "\""));
gsub("\"", "", varname);
vardef = tmp[2];
gsub("(\t| )+", "", vardef);
#if (index(vardef, "\""))
# gsub("\"", "", vardef);
varmod = tmp[3];
gsub("(\t| )+", "", varmod);
print " <row>";
print " <entry>" varname "</entry>"
print " <entry>" vardef "</entry>"
print " <entry>" varmod "</entry>"
print " </row>";
};
END {
print " </tbody>";
print " </tgroup>";
print "</table>";
print "<note>";
print " <para>";
print " The PHP_INI_* constants are defined as follows:";
print " <table>";
print " <thead>";
print " <row>";
print " <entry>Constant</entry>";
print " <entry>Value</entry>";
print " <entry>Meaning</entry>";
print " </row>";
print " </thead>";
print " <tbody>";
print " <row>";
print " <entry>PHP_INI_USER</entry>";
print " <entry>1</entry>";
print " <entry>Entry can be set in user scripts</entry>";
print " </row>";
print " <row>";
print " <entry>PHP_INI_PERDIR</entry>";
print " <entry>2</entry>";
print " <entry>Entry can be set in <filename>.htaccess</filename></entry>";
print " </row>";
print " <row>";
print " <entry>PHP_INI_SYSTEM</entry>";
print " <entry>4</entry>";
print " <entry>Entry can be set in <filename>php.ini</filename> or";
print " <filename>httpd.conf</filename></entry>";
print " </row>";
print " <row>";
print " <entry>PHP_INI_ALL</entry>";
print " <entry>7</entry>";
print " <entry>Entry can be set anywhere</entry>";
print " </row>";
print " </tbody>";
print " </table>";
print " </para>";
print "</note>";
}' $main_c > $ini_set_table
ls -l $ini_set_table
<file_sep>/branches/docgen-update/scripts/docgen/structures/jobtypes/Docgen_MethodJob.php
<?php
class Docgen_MethodJob extends Docgen_Job {
public function __construct($class, $method, $parameters = null) {
$this->reflection = new ReflectionMethod($class, $method);
if(is_array($parameters)) $this->parameters = $parameters);
}
public function execute() {
}
}
<file_sep>/tags/dev_xml_mergepoint/genfunclist
#!/bin/sh
#
# +----------------------------------------------------------------------+
# | PHP HTML Embedded Scripting Language Version 3.0 |
# +----------------------------------------------------------------------+
# | Copyright (c) 1997,1998 PHP Development Team (See Credits file) |
# +----------------------------------------------------------------------+
# | This program is free software; you can redistribute it and/or modify |
# | it under the terms of one of the following licenses: |
# | |
# | A) the GNU General Public License as published by the Free Software |
# | Foundation; either version 2 of the License, or (at your option) |
# | any later version. |
# | |
# | B) the PHP License as published by the PHP Development Team and |
# | included in the distribution in the file: LICENSE |
# | |
# | This program is distributed in the hope that it will be useful, |
# | but WITHOUT ANY WARRANTY; without even the implied warranty of |
# | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the |
# | GNU General Public License for more details. |
# | |
# | You should have received a copy of both licenses referred to here. |
# | If you did not, or have any questions about PHP licensing, please |
# | contact <EMAIL>. |
# +----------------------------------------------------------------------+
# | Authors: <NAME> <<EMAIL>> or <<EMAIL>> |
# | <NAME> <<EMAIL>> |
# +----------------------------------------------------------------------+
#
# $Id$
for i in `find $1 -name "*.[ch]" -print -o -name "*.ec" -print | xargs egrep -li function_entry` ; do
echo $i | sed -e 's/\.\.\//# /'
awk -f funcparse.awk < $i | sort
done
awk -f funcparse.awk < $1/language-scanner.lex | sort
<file_sep>/branches/docgen-update/scripts/docgen/structures/jobtypes/Docgen_ExtensionJob.php
<?php
class Docgen_ExtensionJob extends Docgen_Job {
public function __construct($name, $parameters = null) {
$this->reflection = new ReflectionExtension($name);
if(is_array($parameters)) $this->parameters = $parameters;
}
public function execute() {
$this->createBook();
}
public function createBook() {
$extensionID = self::format_identifier($this->reflection->name);
$writer = new XMLWriter;
$writer->openMemory();
$writer->setIndent(true);
$writer->setIndentString(" ");
$writer->startDocument("1.0", "UTF-8");
$writer->writeComment(' $Revision$ ');
$writer->startElement("book");
$writer->writeAttribute("xml:id", "book.extname");
$writer->writeAttribute("xmlns", "http://docbook.org/ns/docbook");
$writer->writeAttribute("xmlns:xlink", "http://www.w3.org/1999/xlink");
$writer->writeElement("title", $this->reflection->name);
$writer->writeElement("titleabbrev", $this->reflection->name."...");
$writer->writeRaw("\n");
$writer->writeComment(" {{{ preface ");
$writer->startElement("preface");
$writer->writeRaw("\n &reftitle.intro;\n");
$writer->writeElement("para", "Extension introduction.");
$writer->endElement();
$writer->writeComment(" }}} ");
$writer->writeRaw("\n");
$writer->writeRaw(" &reference.{$extensionID}.setup;\n");
$writer->writeRaw(" &reference.{$extensionID}.constants;\n");
$writer->writeRaw(" &reference.{$extensionID}.reference;\n");
$writer->writeRaw("\n");
$writer->endElement();
$writer->endDocument();
$this->addLocalVariables($writer);
$this->documents["reference/{$extensionID}/book.xml"] = $writer->flush();
}
}
<file_sep>/branches/dev_docbook4/scripts/sort_aliases.php
#!/usr/bin/php -q
<?php
// Sorts the aliases.xml file. This script assumes that </row> and <row> tags
// are not on the same line.
$lang = isset($argv[1]) ? $argv[1] : 'en';
if (@is_dir($lang)) {
$filename = "$lang/appendices/aliases.xml";
} elseif (@is_dir("../$lang")) {
$filename = "../$lang/appendices/aliases.xml";
} else { ?>
Usage: ./scripts/sort_aliases.php [<lang>]
While being in the root of phpdoc.
<?php
exit;
}
echo "File: $filename\n\n";
$lines = file($filename);
if (!$lines) {
echo "Cannot read from file, bailing out...\n";
exit;
}
$out = @fopen("$filename.sorted", 'w');
if (!$out) {
echo "Cannot write to file $filename.sorted, bailing out...\n";
exit;
}
echo "Copying beginning of file...\n";
for ($nr = 0; !ereg('tbody',$lines[$nr]); $nr++) {
fwrite($out, $lines[$nr]);
}
fwrite($out, $lines[$nr++]);
echo "Reading entries... ";
for (; ereg('<row>', $lines[$nr]); $nr++) {
$entry = '';
$key = '';
for (; !ereg('</row>', $lines[$nr]); $nr++) {
$entry .= $lines[$nr];
if (!$key && ereg('<entry>([^<>]*)</entry>', $lines[$nr], $regs)) {
$key = $regs[1];
}
}
$entry .= $lines[$nr];
if (!$key) {
echo "No key found, key: ";
var_dump($key);
echo "entry: ";
var_dump($entry);
exit;
}
if (isset($entries[$key])) {
// duplicate key, in order to get a stable sorting, add NUL byte and
// (line number + 1000000)
$key .= "\0".(<KEY>);
}
$entries[$key] = $entry;
}
echo count($entries)." entries found\n";
echo "Sorting entries...\n";
asort($entries);
echo "Writing sorted entries...\n";
foreach ($entries as $entry) {
fwrite($out, $entry);
}
echo "Copying rest of file...\n";
for (;isset($lines[$nr]); $nr++) {
fwrite($out, $lines[$nr]);
}
fclose($out);
?>
Done!
(you you still need to copy <?=$filename?>.sorted
on top of <?=$filename?> after a quick check)
| ac337b0da96e7aa442ad45c47337148025572e50 | [
"JavaScript",
"Makefile",
"INI",
"Text",
"PHP",
"Shell"
] | 66 | PHP | svn2github/phpdoc_doc-base | f848e5899b15d4bfe0a7755953bdc10215ac0498 | 52318580c871b69f11aa117fd5cac4a9589e3946 |
refs/heads/master | <file_sep>package com.goldskyer.gmxx.promotion.entities;
import java.util.Date;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
import org.hibernate.annotations.GenericGenerator;
/**
* 用户抽奖记录,存储用户有没有中奖
* @author jintianfan
*
*/
@Entity
@Table(name="award_record")
public class AwardRecord {
@Id
@Column(name = "ID", length = 40)
@GeneratedValue(generator = "idGenerator")
@GenericGenerator(name = "idGenerator", strategy = "uuid")
private String id;
private String accountId; //手机号或者账号
private String activityId;
private String fp;//抽奖时浏览器指纹
private String awardId; //奖品ID
private boolean awarded=false;//是否中奖
private String name;
private String department;
private String cardNo;
private Date createDate;//
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getAccountId() {
return accountId;
}
public void setAccountId(String accountId) {
this.accountId = accountId;
}
public String getActivityId() {
return activityId;
}
public void setActivityId(String activityId) {
this.activityId = activityId;
}
public String getAwardId() {
return awardId;
}
public void setAwardId(String awardId) {
this.awardId = awardId;
}
public Date getCreateDate() {
return createDate;
}
public void setCreateDate(Date createDate) {
this.createDate = createDate;
}
public boolean isAwarded() {
return awarded;
}
public void setAwarded(boolean awarded) {
this.awarded = awarded;
}
public String getFp() {
return fp;
}
public void setFp(String fp) {
this.fp = fp;
}
@Override
public String toString() {
return "AwardRecord [id=" + id + ", accountId=" + accountId + ", activityId=" + activityId + ", fp=" + fp
+ ", awardId=" + awardId + ", awarded=" + awarded + ", createDate=" + createDate + "]";
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDepartment() {
return department;
}
public void setDepartment(String department) {
this.department = department;
}
public String getCardNo()
{
return cardNo;
}
public void setCardNo(String cardNo)
{
this.cardNo = cardNo;
}
}
<file_sep>curNode = new Object(); // 定义当前选中的节点
curNode.id="";
var setting = {
check : {
enable : false
},
data : {
simpleData : {
enable : true
}
},
callback : {
onClick : function(event, treeId, treeNode) {
curNode = treeNode;
oTable.api().ajax.reload();
}
}
};
$(function() {
$.fn.zTree.init($("#treeDemo"), setting, zData);
zTree = $.fn.zTree.getZTreeObj("treeDemo");
zTree.expandAll(true);
oTable = $('#paper-table')
.dataTable(
{
"processing" : false,
"serverSide" : true,
rowId : "[0]",
"ajax" : {
"url" : "/manager/user/dialog/list_data.json",
data : {
"dept" : function() {
return curNode.id;
}
}
},
"language" : {
"url" : "http://cdn.datatables.net/plug-ins/1.10.11/i18n/Chinese.json"
},
"columnDefs" : [ {
"render" : function(data, type, row) {
return '<input type="checkbox" class="checkBtn" name="'+row[2]+'" value="'
+ data+ '" />';
},
"targets" : 0
} ]
});
$('.checkBtn').live("click",function(){
if($(this).attr("checked")=="checked"){
$('.accountIds').find('span[sId="'+$(this).attr("value")+'"]').remove();
$('.accountIds').append('<span class="label label-success" sId="'+$(this).attr("value")+'">'+$(this).attr('name')+'</span>');
}else{
$('.accountIds').find('span[sId="'+$(this).attr("value")+'"]').remove();
}
});
$('#mysave').live('click',function(){
append="";
appendNames="";
$('.accountIds span').each(function(index,e){
append+=$(this).attr('sid')+",";
appendNames+=$(this).html()+",";
});
console.log(append+";"+appendNames);
if(append.length>0)
{
append=append.substring(0,append.length-1);
appendNames=appendNames.substring(0,appendNames.length-1);
}
$(".poped",parent.document).val(append);
//使用新的回调方式
$(".choosed-ids",parent.document).val(append);
$(".choosed-names",parent.document).val(appendNames);
top.$.jBox.close("chooseAccountDialog");
});
});<file_sep>package com.goldskyer.scorecloud.controller;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
@Controller("scoreCloudIndexController")
@RequestMapping("/scorecloud")
public class IndexController extends BaseScoreCloudController
{
@RequestMapping(value = "/index.htm")
public ModelAndView index(HttpServletRequest request, HttpServletResponse response)
{
ModelAndView mv = new ModelAndView("/scorecloud/index");
return mv;
}
}
<file_sep>package com.goldskyer.gmxx.common.utils;
import java.math.BigDecimal;
import org.apache.commons.lang.StringUtils;
public class FileUtil
{
/**
* 根据文件名获取文件后缀
* @param fileName
* @return
*/
public static String getFileTypeByFileName(String fileName)
{
if (StringUtils.isBlank(fileName))
return StringUtils.EMPTY;
if (fileName.indexOf(".") > 0)
return StringUtils.upperCase(fileName.substring(fileName.lastIndexOf(".") + 1));
return StringUtils.EMPTY;
}
public static String bytes2kb(long bytes)
{
BigDecimal filesize = new BigDecimal(bytes);
BigDecimal megabyte = new BigDecimal(1024 * 1024);
float returnValue = filesize.divide(megabyte, 2, BigDecimal.ROUND_UP).floatValue();
if (returnValue > 1)
return (returnValue + "MB");
BigDecimal kilobyte = new BigDecimal(1024);
returnValue = filesize.divide(kilobyte, 2, BigDecimal.ROUND_UP).floatValue();
return (returnValue + "KB");
}
public static void main(String[] args)
{
System.out.println(getFileTypeByFileName("adc.csad.pdf"));
System.out.println(bytes2kb(2000000000000l));
}
}
<file_sep>package com.goldskyer.scorecloud.form;
public class ScoreSearchForm
{
private String classId;
private String examId;
private String studentName; //模糊
private String stduentNo; //模糊
private String gradeId;
private String nameno;
public String getClassId()
{
return classId;
}
public void setClassId(String classId)
{
this.classId = classId;
}
public String getExamId()
{
return examId;
}
public void setExamId(String examId)
{
this.examId = examId;
}
public String getStudentName()
{
return studentName;
}
public void setStudentName(String studentName)
{
this.studentName = studentName;
}
public String getStduentNo()
{
return stduentNo;
}
public void setStduentNo(String stduentNo)
{
this.stduentNo = stduentNo;
}
public String getNameno()
{
return nameno;
}
public void setNameno(String nameno)
{
this.nameno = nameno;
}
public String getGradeId()
{
return gradeId;
}
public void setGradeId(String gradeId)
{
this.gradeId = gradeId;
}
}
<file_sep>package com.goldskyer.gmxx.common.vos;
public class Lang
{
private String cn;
private String en;
public Lang(String cn, String en)
{
super();
this.cn = cn;
this.en = en;
}
public String getCn()
{
return cn;
}
public void setCn(String cn)
{
this.cn = cn;
}
public String getEn()
{
return en;
}
public void setEn(String en)
{
this.en = en;
}
}
<file_sep>package com.goldskyer.gmxx.common.business;
import java.util.List;
import com.goldskyer.core.entities.Department;
import com.goldskyer.gmxx.common.vos.SelectVo;
public interface DepartmentBusiness
{
public Department getDepartmentTree(String domain);
public List<SelectVo> queryDepartmentSelectVos();
}
<file_sep>package com.goldskyer.gmxx.promotion.service.impl;
import java.util.List;
import java.util.Random;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.goldskyer.common.exceptions.BusinessException;
import com.goldskyer.core.dao.BaseDao;
import com.goldskyer.gmxx.promotion.dtos.ApplyAwardDto;
import com.goldskyer.gmxx.promotion.entities.Activity;
import com.goldskyer.gmxx.promotion.entities.Award;
import com.goldskyer.gmxx.promotion.entities.AwardRecord;
import com.goldskyer.gmxx.promotion.service.ActivityService;
import com.goldskyer.gmxx.promotion.service.AwardRecordService;
import com.goldskyer.gmxx.promotion.service.AwardService;
@Service
public class AwardServiceImp implements AwardService{
@Autowired
private BaseDao baseDao;
@Autowired
private AwardRecordService awardRecordService ;
@Autowired
private ActivityService activityService;
/**
* 用户执行抽奖操作
*/
@Override
public AwardRecord doAward(ApplyAwardDto applyAwardDto) {
if(awardRecordService.ifHasAwardRecord(applyAwardDto))
{
throw new BusinessException("对不起,您只有一个一次抽奖机会");
}
AwardRecord awardRecord = new AwardRecord();
awardRecord.setAccountId(applyAwardDto.getAccountId());
awardRecord.setActivityId(applyAwardDto.getActivityId());
awardRecord.setFp(applyAwardDto.getFp());
List<Award> awards = getAllAwardsByActivityId(applyAwardDto.getActivityId());
long joinedCount =awardRecordService.getTotalAwardRecordCountByActivityId(applyAwardDto.getActivityId()); //已参加的人数
Activity activity = activityService.queryActivityById(applyAwardDto.getActivityId());
long remainCount = activity.getTotalPerson()-joinedCount;
while(remainCount<0)
{
remainCount+=100;
}
int sed = new Random().nextInt((int)remainCount);
Integer awardIndex = 0 ;
for(Award award:awards)
{
awardIndex +=award.getTotalNum()-award.getAwardedNum();
if(sed<awardIndex) //有了,满足中奖条件了
{
//中奖了
awardRecord.setAwarded(true);
awardRecord.setAwardId(award.getId());
try
{
awardRecordService.addAwardRecordLimitAccount(awardRecord);
}
catch (Exception e)
{
awardRecord.setAwarded(false);
awardRecord.setAwardId(null);
awardRecordService.addAwardRecordLimitAccount(awardRecord);
return awardRecord;
}
return awardRecord;
}
}
awardRecordService.addAwardRecordLimitAccount(awardRecord);
return awardRecord;
}
public List<Award> getAllAwardsByActivityId(String activityId)
{
return baseDao.query("from Award where activityId=? order by activityId,id ",activityId);
}
public boolean hitAward(Award award)
{
int a=baseDao.execute("update Award set awardedNum=awardedNum+1 where id=? and awardedNum<totalNum",award.getId());
if(a>0){
return true;
}
return false;
}
}
<file_sep>package com.goldskyer.scorecloud.dto;
import java.util.ArrayList;
import java.util.List;
public class ExamDto extends SchIdDto
{
private String id;
private String examName;
private int year;//考试年份
private String createDate; //yyyy-MM-dd
private String updateDate; //yyyy-MM-dd
private List<SubjectDto> subjectDtos = new ArrayList<>();
public String getId()
{
return id;
}
public void setId(String id)
{
this.id = id;
}
public String getExamName()
{
return examName;
}
public void setExamName(String examName)
{
this.examName = examName;
}
public int getYear()
{
return year;
}
public void setYear(int year)
{
this.year = year;
}
public String getCreateDate()
{
return createDate;
}
public void setCreateDate(String createDate)
{
this.createDate = createDate;
}
public String getUpdateDate()
{
return updateDate;
}
public void setUpdateDate(String updateDate)
{
this.updateDate = updateDate;
}
public List<SubjectDto> getSubjectDtos()
{
return subjectDtos;
}
public void setSubjectDtos(List<SubjectDto> subjectDtos)
{
this.subjectDtos = subjectDtos;
}
}
<file_sep>package com.goldskyer.scorecloud.service;
import com.goldskyer.scorecloud.dto.ClassDto;
import com.goldskyer.scorecloud.dto.TargetScoreItem;
import com.goldskyer.scorecloud.vo.TargetScoreVo;
public interface TargetScoreService
{
/**
* 目标值计算
* @param examId
* @param classDto
* @return
*/
public TargetScoreItem calculateTargetScoreItem(String schId, String title, String examId, ClassDto classDto);
public TargetScoreVo getTargetScoreVo(String schId, String examId);
public TargetScoreVo getTargetSubjectScoreVo(String schId, String subjectId);
}
<file_sep>package com.goldskyer.gmxx.mock.entities;
import java.util.Date;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.EnumType;
import javax.persistence.Enumerated;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.persistence.Transient;
import org.hibernate.annotations.GenericGenerator;
import com.goldskyer.gmxx.mock.enums.MockType;
@Entity
@Table(name="mock_url")
public class MockUrl {
@Id
@Column(name = "ID", length = 40)
@GeneratedValue(generator = "idGenerator")
@GenericGenerator(name = "idGenerator", strategy = "uuid")
private String id;
private String url;
private String content;
private String accountId;
private String groupName;
private Date createDate;
private Date updateDate;
private String title;
@Enumerated(EnumType.STRING)
private MockType type;
private String sourceUrl;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public String getAccountId() {
return accountId;
}
public void setAccountId(String accountId) {
this.accountId = accountId;
}
public String getGroupName() {
return groupName;
}
public void setGroupName(String groupName) {
this.groupName = groupName;
}
public MockType getType() {
return type;
}
public void setType(MockType type) {
this.type = type;
}
public Date getCreateDate() {
return createDate;
}
public void setCreateDate(Date createDate) {
this.createDate = createDate;
}
public Date getUpdateDate() {
return updateDate;
}
public void setUpdateDate(Date updateDate) {
this.updateDate = updateDate;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
@Transient
public String getDemoUrl()
{
if(MockType.JSON==this.type)
{
return url+( url.contains("?")?"&mock=json":"?mock=json");
}
else if (MockType.HTML==this.type)
{
return url+( url.contains("?")?"&mock=json":"?mock=html");
}
return null;
}
public String getSourceUrl() {
return sourceUrl;
}
public void setSourceUrl(String sourceUrl) {
this.sourceUrl = sourceUrl;
}
}<file_sep>package com.goldskyer.gmxx.manager.controllers;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
import com.goldskyer.core.service.MenuService;
@Controller
@RequestMapping("/manager")
public class ManagerController extends BaseManagerController
{
private MenuService menuService;
@RequestMapping("/index.htm")
public ModelAndView index()
{
ModelAndView mv = new ModelAndView("/manager/template");
mv.addObject("innerPage", "index");
return mv;
}
/**
* 这个作为后台的基础模板
* @return
*/
@RequestMapping("/template.htm")
public ModelAndView template()
{
ModelAndView mv = new ModelAndView("/manager/template");
return mv;
}
@RequestMapping("/{path}.htm")
public ModelAndView inner(@PathVariable String path)
{
ModelAndView mv = new ModelAndView("/manager/template");
mv.addObject("innerPage", path);
return mv;
}
}
<file_sep>package com.goldskyer.gmxx.common.business.impl;
import java.util.ArrayList;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import com.goldskyer.core.SpringContextHolder;
import com.goldskyer.core.dto.EnvParameter;
import com.goldskyer.core.entities.Department;
import com.goldskyer.core.service.DepartmentService;
import com.goldskyer.gmxx.common.business.DepartmentBusiness;
import com.goldskyer.gmxx.common.vos.SelectVo;
@Service("departmentBusiness")
public class DepartmentBusinessImpl implements DepartmentBusiness
{
@Autowired
protected CacheManager cacheManager;
@Autowired
private DepartmentService departmentService;
@Cacheable(value =
{ "dept" }, key = "#domain.concat('departmentTree')")
public Department getDepartmentTree(String domain)
{
return departmentService.getDepartmentTree(domain);
}
public List<SelectVo> queryDepartmentSelectVos()
{
DepartmentBusiness departmentBusiness = SpringContextHolder.getBean("departmentBusiness");
Department root = departmentBusiness.getDepartmentTree(EnvParameter.get().getDomain());
List<SelectVo> vos = new ArrayList<SelectVo>();
deepSearch(vos, root, 0);
return vos;
}
private void deepSearch(List<SelectVo> vos, Department department, final int deep)
{
String prefix = "";
int i = 0;
while (i < deep)
{
prefix += "-";
i++;
}
if (department == null)
return;
for (Department d : department.getChildren())
{
SelectVo vo = new SelectVo();
vo.setName(prefix + d.getName());
vo.setValue(d.getId());
vos.add(vo);
deepSearch(vos, d, (deep + 1));
}
}
}
<file_sep>package com.goldskyer.gmxx.survey.entities;
import java.util.Date;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
import org.hibernate.annotations.GenericGenerator;
@Entity
@Table(name="account_answer")
public class AccountAnswer {
@Id
@Column(name = "ID", length = 40)
@GeneratedValue(generator = "idGenerator")
@GenericGenerator(name = "idGenerator", strategy = "uuid")
private String id;
private String testId;
private String accountId; //匿名用浏览器指纹
private String paperId;
private String questionId;
private String answerId;
private Date createDate;
public String getAccountId() {
return accountId;
}
public void setAccountId(String accountId) {
this.accountId = accountId;
}
public String getPaperId() {
return paperId;
}
public void setPaperId(String paperId) {
this.paperId = paperId;
}
public String getQuestionId() {
return questionId;
}
public void setQuestionId(String questionId) {
this.questionId = questionId;
}
public String getAnswerId() {
return answerId;
}
public void setAnswerId(String answerId) {
this.answerId = answerId;
}
public Date getCreateDate() {
return createDate;
}
public void setCreateDate(Date createDate) {
this.createDate = createDate;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getTestId()
{
return testId;
}
public void setTestId(String testId)
{
this.testId = testId;
}
}
<file_sep>package com.goldskyer.gmxx.common.service;
import java.util.List;
import com.goldskyer.gmxx.common.dtos.CreateTaskDto;
import com.goldskyer.gmxx.common.entities.WorkFlowData;
import com.goldskyer.gmxx.common.entities.WorkFlowTask;
import com.goldskyer.gmxx.workflow.vo.AuditVo;
import com.goldskyer.gmxx.workflow.vo.WorkflowDataVo;
public interface WorkFlowService
{
public WorkFlowTask queryTaskByObjectId(String objectId);
public List<String> getMyRangeNodeIds(String accountId);
/**
* 获取我的任务列表
* @param accountId
* @return
*/
public List<WorkFlowTask> getMyTasks(String accountId);
/**
* 获取当前我的列表
* @param accountId
* @param status
* @return
*/
public List<WorkFlowTask> getMyTasks(String accountId, String objectType);//状态
/**
* 执行审核操作
*/
public void signal(AuditVo auditVo);
/**
* 获取对象的审核记录
* @param objectId
* @param objectType
* @return
*/
public List<WorkFlowData> queryWorkFlowDataHis(String objectId, String objectType);
/**
* 审核资源
* @param accountId
* @param blogId
*/
public void createTask(CreateTaskDto createTaskDto);
/**
* 判断是否有该流程的操作权限
* @param task
* @param accountId
* @return
*/
public boolean ifCanOperationTask(WorkFlowTask task, String accountId);
public List<WorkflowDataVo> queryWorkFlowDataVo(String objectId);
}
<file_sep>package com.goldskyer.scorecloud.service;
import java.util.List;
import com.goldskyer.scorecloud.dto.ClassDto;
import com.goldskyer.scorecloud.entities.Class;
public interface ClassService
{
public List<String> queryClassIdsByGradeId(String gradeId);
/**
* 根据年级ID查找对应班级
* @param gradeId
* @return
*/
public List<Class> queryClassesByGradeId(String gradeId);
public List<ClassDto> queryAllClassesGroupByGrade(String schId);
public void addCladdDto(ClassDto classDto);
public void deleteClassDto(String id);
public void modifyClassDto(ClassDto classDto);
public ClassDto queryClassDtoById(String id);
public Integer queryStudentCntByClassId(String classId);
public ClassDto queryClassDtoByNameInfo(String schId, String gradeName, String className);
}
<file_sep>package com.goldskyer.scorecloud.freemarker.component.vo;
import java.util.ArrayList;
import java.util.List;
public class OptGroupVoWrapper
{
private String name;//对应field的name
private List<OptGroupVo> optGroupVos = new ArrayList<>();
private String firstId;
public String getName()
{
return name;
}
public void setName(String name)
{
this.name = name;
}
public List<OptGroupVo> getOptGroupVos()
{
return optGroupVos;
}
public void setOptGroupVos(List<OptGroupVo> optGroupVos)
{
this.optGroupVos = optGroupVos;
}
public String getFirstId()
{
return firstId;
}
public void setFirstId(String firstId)
{
this.firstId = firstId;
}
}
<file_sep>/**
* _/ _/ _/ _/_/_/
* _/ _/ _/ _/ _/
* _/ _/ _/ _/ _/_/_/
* _/ _/ _/ _/ _/ _/
* _/ _/ _/_/_/_/ _/_/_/
*
* Project: gmxx
*
* MenuNode.java File Created at 下午9:00:00
*
*
* Copyright 2014 Taobao.com Corporation Limited.
* All rights reserved.
*
* This software is the confidential and proprietary information of
* Taobao Company. ("Confidential Information"). You shall not
* disclose such Confidential Information and shall use it only in
* accordance with the terms of the license agreement you entered into
* with Taobao.com.
*/
package com.goldskyer.gmxx.manager.entities;
import java.util.List;
/**
* 菜单树形节点
*
* @author zhang.li
* @version 1.0
* @since 2016-4-14
*/
public class MenuNode {
private String id;
private String name;
private boolean open;
private double weight;
private String pId;
private List<MenuNode> children;
//禁止子节点移走
private boolean childOuter;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public boolean isOpen() {
return open;
}
public void setOpen(boolean open) {
this.open = open;
}
public double getWeight() {
return weight;
}
public void setWeight(double weight) {
this.weight = weight;
}
public String getpId() {
return pId;
}
public void setpId(String pId) {
this.pId = pId;
}
public List<MenuNode> getChildren() {
return children;
}
public void setChildren(List<MenuNode> children) {
this.children = children;
}
public boolean isChildOuter() {
return childOuter;
}
public void setChildOuter(boolean childOuter) {
this.childOuter = childOuter;
}
}<file_sep>package com.goldskyer.scorecloud.service;
import java.util.List;
import com.goldskyer.scorecloud.dto.OptionDto;
public interface OptionService
{
public List<OptionDto> queryAllOptionDtos(String schId);
public void addOptionDto(OptionDto optionDto);
public void modifyOptionDto(OptionDto optionDto);
public void deleteOption(String id);
public OptionDto queryOptionDtoById(String id);
public OptionDto queryOptionDtoByInnerCode(String schId, String innerCode);
}
<file_sep>require('../less/detail.less');
require('../js/lib/widget/navigator.iscroll.js');
var Fingerprint = require('../bower_components/fingerprint/fingerprint.js');
var clickElement;
$(function() {
$('.video-js').attr('webkit-playsinline', 'true');
$('.loading').hide();
getVoteStatus();
$('.icon_praise_gray').on('click', function(){
var fingerprint = new Fingerprint().get();
var objectIdValue = $('.objectId').text();
clickElement = $(this);
$.ajax({
type: "GET",
url: "http://gmxx.goldskyer.com/front/blog/voteUp.json",
data: {
accountId: fingerprint,
objectId: objectIdValue,
objectType: "BLOG",
fp: fingerprint
},
dataType: "json",
success: function (data) {
if (data.result == "success") {
clickElement.attr('class',"icon_praise_red");
var currentlikenum = parseInt($('.likeNum').html());
$('.likeNum').html(currentlikenum + 1);
};
},
error: function () {
clickElement.attr('class',"icon_praise_gray");
}
});
});
});
function getVoteStatus(){
var fingerprint = new Fingerprint().get();
var objectIdValue = $('.objectId').text();
$.ajax({
type: "GET",
url: "http://gmxx.goldskyer.com/voteUp/queryStatus.json",
data: {
accountId: fingerprint,
objectId: objectIdValue,
objectType: "BLOG",
fp: fingerprint
},
dataType: "json",
success: function (data) {
if (data.result == "failure") {
$(".icon_praise_gray").attr('class', "icon_praise_red");
}
},
error: function () {
$(".icon_praise_gray").attr('class', "icon_praise_gray");
}
});
};<file_sep>package com.goldskyer.scorecloud.enums;
public enum GradeStatus
{
ACTIVAE,ARCHIVE
}
<file_sep>package com.goldskyer.scorecloud.service;
import com.goldskyer.scorecloud.dto.OptionValueDto;
public interface OptionValueService
{
public void addOrModifyOptionValueDto(OptionValueDto optionValueDto);
public void deleteOptionValue(String id);
public void addOptionValueDto(OptionValueDto optionValueDto);
public void modifyOptionValueDto(OptionValueDto optionValueDto);
}
<file_sep>package com.goldskyer.gmxx.front.controllers;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
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.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import com.goldskyer.common.exceptions.BusinessException;
import com.goldskyer.core.dto.EnvParameter;
import com.goldskyer.core.dto.JsonData;
import com.goldskyer.core.entities.Blog;
import com.goldskyer.core.entities.Comment;
import com.goldskyer.core.entities.Menu;
import com.goldskyer.core.entities.VoteUpLog;
import com.goldskyer.core.service.CommentService;
import com.goldskyer.core.service.VoteUpLogService;
import com.goldskyer.gmxx.BaseController;
import com.goldskyer.gmxx.common.constants.GmxxConstant;
@Controller
@RequestMapping("/front/{module}")
public class BlogController extends BaseController{
@Autowired
private VoteUpLogService voteUpLogService;
@Autowired
private CommentService commentService;
@RequestMapping("/view.htm")
public ModelAndView detail(@RequestParam String id,@PathVariable String module,@RequestParam(required=false)String accountId,HttpServletRequest request)
{
ModelAndView mv = new ModelAndView("/front/"+module+"/view");
buildCommonBlogModel(mv,id);
blogService.incViewCount(id);
if(StringUtils.isNotBlank(accountId))
{
VoteUpLog voteUpLog = voteUpLogService.queryVoteUpLogbyId(accountId, id, "BLOG");
if(voteUpLog!=null)
{
mv.addObject("voted", true);
}
}
List<Comment> comments = commentService.queryCommentsByObject(id, "BLOG", 0, 100);
mv.addObject("comments", comments);
//
return mv;
}
@RequestMapping(value="/voteUp.json",produces="application/json;charset=UTF-8")
@ResponseBody
public JsonData voteUp(VoteUpLog voteUpLog)
{
voteUpLog.setId(null);
voteUpLog.setId(EnvParameter.get().getIp());
voteUpLog.setObjectType("BLOG");
if(!voteUpLogService.addVoteUpLog(voteUpLog))
{
return JsonData.failure("你已经点赞过了");
}
boolean result = blogService.incVoteUp(voteUpLog.getObjectId());
if(result)
{
return JsonData.success();
}
else
{
return JsonData.failure("点赞失败,找不到要赞的博客");
}
}
/**
* 所有的资源型内容列表通用这个接口
* /front/tv/list.htm 对应 /front/tv/list.jsp
* /front/tv/list_image.htm /front/tv/list_image.jsp
* @param view
* @param module
* @param blogType
* @param pageNum
* @return
*/
@RequestMapping("/list{view}.htm")
public ModelAndView list(@PathVariable String view,@PathVariable String module,@RequestParam String blogType,@RequestParam(required=false) Integer pageNum)
{
ModelAndView mv = new ModelAndView("/front/"+module+"/list"+view);
//设置Size(优先级MOUDLE_PAGE_SZIE>PAGE_SIZE)
Integer pageSize = 10;
String typeIni = iniService.getIniValue(blogType + "_PAGE_SZIE");
if (StringUtils.isNotBlank(typeIni))
{
pageSize = Integer.valueOf(typeIni);
}
else
{
pageSize = Integer.valueOf(iniService.getIniValue(GmxxConstant.PAGE_SIZE));
}
blogBusiness.buildCommonBlogListModel(mv, blogType, pageNum, pageSize);
return mv;
}
@SuppressWarnings("unchecked")
@RequestMapping(value="/list.json",produces="application/json;charset=UTF-8")
@ResponseBody
public JsonData mockJson(@RequestParam String type,@RequestParam(required=false) String subType,@RequestParam(required=false)Integer pageNo,@RequestParam(required=false)Integer pageSize){
JsonData jsonData =JsonData.success();
if(pageNo==null || pageNo<1)
{
pageNo=1;
}
if(pageSize==null || pageSize<1)
{
pageSize = Integer.valueOf(iniService.getIniValue(GmxxConstant.PAGE_SIZE));
}
Integer start =(pageNo-1) * pageSize;
List<Blog> blogs = blogService.queryBlogsWithNoContent(type, subType, start, pageSize);
long count = blogService.countTotalBlogs(type, subType);
int maxPageNo=(int)count/pageSize +((count%pageSize==0)?0:1);
int nextPageNo = Math.min(maxPageNo, pageNo+1);
blogBusiness.formatBlogs(blogs);
jsonData.data.put("blogs", blogs);
jsonData.data.put("count", count);
jsonData.data.put("pageSize", pageSize);
jsonData.data.put("pageNo", pageNo);
jsonData.data.put("nextPageNo", nextPageNo);
jsonData.data.put("maxPageNo", maxPageNo);
return jsonData;
}
protected void buildCommonBlogModel(ModelAndView mv,String blogId)
{
Blog blog = blogService.queryBlog(blogId);
if(blog==null)
{
throw new BusinessException("当前请求记录不存在");
}
Menu menu = cachedMenuService.queryMenuByName(blog.getType());
if (menu == null)
throw new BusinessException("该栏目已经下线");
mv.addObject("mainMenu", cachedMenuService.getMainMenu());
mv.addObject("menu", menu);
mv.addObject("blog",blog);
}
@RequestMapping(value = "/checkAuthCode.json", produces = "application/json")
@ResponseBody
public JsonData checkAuthCode(@RequestParam String blogId, @RequestParam String authCode,
HttpServletRequest request)
{
if (blogService.checkAuthCode(blogId, authCode))
{
request.getSession().setAttribute("blogId", blogId);
return JsonData.success();
}
else
{
return JsonData.failure("验证码无效");
}
}
}
<file_sep>/////////全局初始化,所有页面都能加载到///////////////////
$(document).ready(function() {
ComponentsBootstrapSelect.init();
initActiveMenu();
});
/**
* validate插件
*
*/
VALIDATE_default = {
errorElement : 'span', // default input error message container
errorClass : 'help-block help-block-error', // default input error message
// class
focusInvalid : false, // do not focus the last invalid input
ignore : "", // validate all fields including form hidden input
highlight : function(element) { // hightlight error inputs
$(element).closest('.form-group').addClass('has-error'); // set error
// class to
// the
// control
// group
},
unhighlight : function(element) { // revert the change done by hightlight
$(element).closest('.form-group').removeClass('has-error'); // set error
// class to
// the
// control
// group
},
success : function(label) {
label.closest('.form-group').removeClass('has-error'); // set success
// class to the
// control group
}
};
/**
* datatable插件
*
*/
DT_defaultSetting = {
"language" : {
"aria" : {
"sortAscending" : ": activate to sort column ascending",
"sortDescending" : ": activate to sort column descending"
},
"emptyTable" : "没有数据",
"info" : "显示从 _START_ 到 _END_ 总共 _TOTAL_ 条记录",
"infoEmpty" : "没有找到匹配的记录",
"infoFiltered" : "( 从 _MAX_ 条记录中过滤)",
"lengthMenu" : "显示 _MENU_",
"search" : "搜索:",
"zeroRecords" : "没有找到匹配的记录",
"paginate" : {
"previous" : "前一页",
"next" : "后一页",
"last" : "尾页",
"first" : "首页"
}
},
"bStateSave" : false, // save datatable state(pagination, sort, etc) in
// cookie.这样就会保存状态了,我们不需要
"lengthMenu" : [ [ 10, 20, 100, -1 ], [ 10, 20, 100, "All" ] // change
// per
],
"pageLength" : 10, // warn 每页的行数,一定要在lengthMenu中有,否则的话,会显示为空
"pagingType" : "bootstrap_full_number",
};
DT_export = {
buttons : [ {
extend : 'colvis',
text : "列过滤",
className : 'btn purple btn-outline '
}, {
extend : 'excelHtml5',
title : $("#exportTitle").val(),
className : 'btn dark btn-outline',
exportOptions : {
columns : ':visible'
}
}, {
extend : 'csvHtml5',
title : $("#exportTitle").val(),
className : 'btn green btn-outline',
exportOptions : {
columns : ':visible'
}
}, {
extend : 'print',
title : $("#exportTitle").val(),
className : 'btn dark btn-outline',
exportOptions : {
columns : ':visible'
}
} ],
"dom" : "<'row' <'col-md-12'B>><'row'<'col-md-6 col-sm-12'l><'col-md-6 col-sm-12'f>r><'table-scrollable't><'row'<'col-md-5 col-sm-12'i><'col-md-7 col-sm-12'p>>", // horizobtal
// scrollable
// datatable
};
/*******************************************************************************
* datatable插件支持中文排序 这个排序不准
* var citys = ['北京-b','上海-s','广州-g','深圳-s','南京-n','苏州-s','杭州-h','济南-j','青岛-q','武汉-w','沈阳-sh','成都-ch','天津-t','重庆-ch','西安-x','郑州-zh','石家庄-sh','长沙-ch','长春-ch','合肥-h','福州-f'];
* function sortRule(a,b) { return a.localeCompare(b);
* } window.onload = function(){
* alert(citys.sort(sortRule)); }
*/
jQuery.fn.dataTableExt.oSort['chinese-asc'] = function(s1, s2) {
return s1.localeCompare(s2);
};
jQuery.fn.dataTableExt.oSort['chinese-desc'] = function(s1, s2) {
return s2.localeCompare(s1);
};
jQuery.fn.dataTableExt.oSort['string-asc'] = function(s1, s2) {
if(!isNaN(s1) && !isNaN(s2)){
return number_asc(s1,s2);
}
return s1.localeCompare(s2);
};
jQuery.fn.dataTableExt.oSort['string-desc'] = function(s1, s2) {
if(!isNaN(s1) && !isNaN(s2)){
return number_desc(s1,s2);
}
return s2.localeCompare(s1);
};
jQuery.fn.dataTableExt.oSort['numeric-comma-asc'] = function(a,b) {
return number_asc(a,b);
};
function number_asc(a,b)
{
var x = (a == "-") ? 0 : a.replace(",", "." );
var y = (b == "-") ? 0 : b.replace( ",", "." );
x = parseFloat( x );
y = parseFloat( y );
return ((x < y) ? -1 : ((x > y) ? 1 : 0));
}
jQuery.fn.dataTableExt.oSort['numeric-comma-desc'] = function(a,b) {
return number_desc(a,b);
};
function number_desc(a,b)
{
var x = (a == "-") ? 0 : a.replace(",", "." );
var y = (b == "-") ? 0 : b.replace( ",", "." );
x = parseFloat( x );
y = parseFloat( y );
return ((x < y) ? 1 : ((x > y) ? -1 : 0));
}
jQuery.fn.dataTableExt.oSort['sortKey-asc'] = function(s1, s2) {
console.log('xx:' + $(s1).attr('key') + "," + $(s2).attr('key') + ":"
+ $(s1).attr('key').localeCompare($(s2).attr('key')));
return $(s1).attr('key').localeCompare($(s2).attr('key'));
};
jQuery.fn.dataTableExt.oSort['sortKey-desc'] = function(s1, s2) {
return $(s2).attr('key').localeCompare($(s1).attr('key'));
};
// aTypes是插件存放表格内容类型的数组
// reg赋值的正则表达式,用来判断是否是中文字符
// 返回值push到aTypes数组,排序时扫描该数组,'chinese'则调用上面两个方法。返回null默认是'string'
jQuery.fn.dataTableExt.aTypes.push(function(sData) {
var reg = /^[\u4e00-\u9fa5]{0,}$/;
if (reg.test(sData)) {
return 'chinese';
}
return null;
});
/**
* 公共widgets组件
*
*/
/** 弹出toast框,一般用于系统级别警告或者提示* */
function popGrowl(content, level, delay) {
content = content || "网络繁忙,请稍后再试";
level = level || 'info';
delay = delay || 2000;
$.bootstrapGrowl(content, {
ele : 'body', // which element to append to
type : level, // (null, 'info', 'danger', 'success', 'warning')
offset : {
from : 'top',
amount : 100
}, // 'top', or 'bottom'
align : 'left', // ('left', 'right', or 'center')
width : 250, // (integer, or 'auto')
delay : delay, // Time while the message will be displayed. It's not
// equivalent to the *demo* timeOut!
allow_dismiss : true, // If true then will display a cross to close
// the popup.
stackup_spacing : 10
// spacing between consecutively stacked growls.
});
}
/*
* 激活sidebar的选中框
*/
function initActiveMenu() {
// $("ul.page-sidebar>li.nav-item>a>span.title").each(function(){
// if($(this).html()==$("#firstMenu").attr("value")){
// $(this).parents("li.nav-item").addClass("active");
//
//
// }
// });
$("ul.sub-menu>li.nav-item a>span.title").each(function() {
if ($(this).attr("m2") == $("#m2").attr("value")) {
$(this).parents("li.nav-item").addClass("active");
}
});
}
// ////////////////////////////////////////////////
// //////////下拉菜单样式/////////////////////////////////////
var ComponentsBootstrapSelect = function() {
var handleBootstrapSelect = function() {
$('.bs-select').selectpicker({
iconBase : 'fa',
tickIcon : 'fa-check'
});
}
return {
// main function to initiate the module
init : function() {
handleBootstrapSelect();
}
};
}();
/*
* Translated default messages for the jQuery validation plugin. Locale: ZH
* (Chinese, 中文 (Zhōngwén), 汉语, 漢語)
*/
$.extend($.validator.messages, {
required : "这是必填字段",
remote : "请修正此字段",
email : "请输入有效的电子邮件地址",
url : "请输入有效的网址",
date : "请输入有效的日期",
dateISO : "请输入有效的日期 (YYYY-MM-DD),比如:1989-11-22",
number : "请输入有效的数字",
digits : "只能输入数字",
creditcard : "请输入有效的信用卡号码",
equalTo : "你的输入不相同",
extension : "请输入有效的后缀",
maxlength : $.validator.format("最多可以输入 {0} 个字符"),
minlength : $.validator.format("最少要输入 {0} 个字符"),
rangelength : $.validator.format("请输入长度在 {0} 到 {1} 之间的字符串"),
range : $.validator.format("请输入范围在 {0} 到 {1} 之间的数值"),
max : $.validator.format("请输入不大于 {0} 的数值"),
min : $.validator.format("请输入不小于 {0} 的数值")
});
<file_sep>package com.goldskyer.gmxx.common.constants;
public class WeixinConstant {
public static String APP_ID = "wx03a251db770a1549";
public static String APP_SECRET = "<KEY>";
public static String AES_KEY = "<KEY>";
public static final String MSG_TYPE_TEXT = "text";
public static final String MSG_TYPE_IMAGE = "image";
public static final String MSG_TYPE_VOICE = "voice";
public static final String MSG_TYPE_VIDEO = "video";
public static final String MSG_TYPE_LOCATION = "location";
public static final String MSG_TYPE_EVENT = "event"; // 事件(订阅,取消)
public static final String EVENT_TYPE_SUBSCRIBE = "subscribe";
public static final String EVENT_TYPE_UNSUBSCRIBE = "unsubscribe";
public static final String EVENT_TYPE_SCAN = "SCAN";
public static final String EVENT_TYPE_LOCATION = "LOCATION";
public static final String EVENT_TYPE_VIEW = "VIEW";
public static final String MSG_ON_SUBSCRIBE = "欢迎您关注此公众号。输入任何数字,获取回复.";
public static final String MSG_ON_UNSUBSCRIBE = "欢迎您继续关注此公众号。1.有什么不满可联系作者:<EMAIL>";
}
<file_sep>package com.goldskyer.gmxx.common.service;
import java.util.List;
import com.goldskyer.gmxx.common.entities.MessageText;
public interface MessageService
{
public boolean sendMessage(MessageText text, String fromAccountId, String toAccountId);
public boolean sendMessage(MessageText text, String fromAccountId, List<String> toAccountIds);
public void readMessage(String mId, String accountId);
public long queryUnReadMessageCount(String accountId);
public void readMessageByBlogId(String blogId, String accountId);
}
<file_sep>package com.goldskyer.smartcloud.common.vo;
import java.util.List;
public class Serie<T>
{
private String name;
private List<T> datas;
public String getName()
{
return name;
}
public void setName(String name)
{
this.name = name;
}
public List<T> getDatas()
{
return datas;
}
public void setDatas(List<T> datas)
{
this.datas = datas;
}
}
<file_sep>package com.goldskyer.gmxx.service;
import java.util.Date;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import com.goldskyer.core.entities.WeixinMessage;
import com.goldskyer.core.weixin.response.NewsWeixinResponseDto;
import com.goldskyer.gmxx.GmxxWeixinDispatcher;
public class GmxxWeixinDispatcherTest extends BaseTest
{
@Autowired
private GmxxWeixinDispatcher dispatcher;
@Test
public void testWelcome()
{
WeixinMessage weixinMessage = new WeixinMessage();
weixinMessage.fromUserName = "jin";
weixinMessage.toUserName = "tain";
weixinMessage.createDate = new Date();
NewsWeixinResponseDto dto = dispatcher.buildSUbscribeInfo(weixinMessage);
System.out.println(dto.toXML());
}
}
<file_sep>package com.goldskyer.smartcloud.common.entities;
import java.util.Date;
public class School
{
private String id;
private String schoolName;
private Date createDate;
}
<file_sep>package com.goldskyer.gmxx.common.enums;
public enum MessageType
{
系统消息, 用户消息, 流程消息;
}
<file_sep>$(function () {
$("#decode-base-btn").bind('click',function(){
$("#encode-base-btn").nextAll('.alert-box').hide();
$.ajax({
url:"/base64decode",
type:"post",
data:{
input:$('#decode-input').val()
},
success:function(jsonData)
{
if(jsonData.result=='success')
{
$('#decode-base-output').val(jsonData.msg);
}
else{
if(jsonData.result=='success')
{
$('#decode-base-output').val(jsonData.msg);
}
else{
$("#encode-base-btn").after('<div data-alert class="alert-box alert round">'+jsonData.msg+'</div>');
}
}
}
});
});
$("#encode-base-btn").bind('click',function(){
$("#encode-base-btn").nextAll('.alert-box').hide();
$.ajax({
url:"/base64encode",
type:"post",
data:{
input:$('#decode-input').val()
},
success:function(jsonData)
{
if(jsonData.result=='success')
{
$('#decode-base-output').val(jsonData.msg);
}
else{
$("#encode-base-btn").after('<div data-alert class="alert-box alert round">'+jsonData.msg+'</div>');
}
}
});
});
$("#url-encode-btn").bind('click',function(){
$("#url-encode-btn").nextAll('.alert-box').hide();
$.ajax({
url:"/urlencode",
type:"post",
data:{
input:$('#url-input').val()
},
success:function(jsonData)
{
if(jsonData.result=='success')
{
$('#url-output').val(jsonData.msg);
}
else{
$("#url-encode-btn").after('<div data-alert class="alert-box alert round">'+jsonData.msg+'</div>');
}
}
});
});
$("#url-decode-btn").bind('click',function(){
$("#url-decode-btn").nextAll('.alert-box').hide();
$.ajax({
url:"/urldecode",
type:"post",
data:{
input:$('#url-input').val()
},
success:function(jsonData)
{
if(jsonData.result=='success')
{
$('#url-output').val(jsonData.msg);
}
else{
$("#url-encode-btn").after('<div data-alert class="alert-box alert round">'+jsonData.msg+'</div>');
}
}
});
});
$("#gen-hex-btn").bind('click',function(){
$("#gen-hex-btn").nextAll('.alert-box').hide();
$.ajax({
url:"/generateSignPair",
type:"post",
data:{
type:'hex'
},
success:function(jsonData)
{
if(jsonData.result=='success')
{
$('#pair-pri').val(jsonData.data.priKey);
$('#pair-pub').val(jsonData.data.pubKey);
}
else{
$("#verify-base-btn").after('<div data-alert class="alert-box alert round">'+jsonData.msg+'</div>');
}
}
});
});
$("#gen-base-btn").bind('click',function(){
$("#gen-base-btn").nextAll('.alert-box').hide();
$.ajax({
url:"/generateSignPair",
type:"post",
data:{
type:'base64'
},
success:function(jsonData)
{
if(jsonData.result=='success')
{
$('#pair-pri').val(jsonData.data.priKey);
$('#pair-pub').val(jsonData.data.pubKey);
}
else{
$("#verify-base-btn").after('<div data-alert class="alert-box alert round">'+jsonData.msg+'</div>');
}
}
});
});
$("#verify-hex-btn").bind('click',function(){
$("#verify-hex-btn").nextAll('.alert-box').hide();
$.ajax({
url:"/checkSign",
type:"post",
data:{
type:"hex",
priKey:$('#pair-pri').val(),
pubKey:$('#pair-pub').val()
},
success:function(jsonData)
{
if(jsonData.result=='success')
{
if(jsonData.msg=="true")
{
$("#verify-base-btn").after('<div data-alert class="alert-box success round">匹配</div>');
}
else
{
$("#verify-base-btn").after('<div data-alert class="alert-box warning round">验证失败</div>');
}
}
else{
$("#verify-base-btn").after('<div data-alert class="alert-box alert round">'+jsonData.msg+'</div>');
}
}
});
});
$("#verify-base-btn").bind('click',function(){
$("#verify-base-btn").nextAll('.alert-box').hide();
$.ajax({
url:"/checkSign",
type:"post",
data:{
type:"base64",
priKey:$('#pair-pri').val(),
pubKey:$('#pair-pub').val()
},
success:function(jsonData)
{
if(jsonData.result=='success')
{
if(jsonData.msg=="true")
{
$("#verify-base-btn").after('<div data-alert class="alert-box success round">匹配</div>');
}
else
{
$("#verify-base-btn").after('<div data-alert class="alert-box warning round">验证失败</div>');
}
}
else{
$("#verify-base-btn").after('<div data-alert class="alert-box alert round">'+jsonData.msg+'</div>');
}
}
});
});
$("#hex-sign-btn").bind('click',function(){
$("#hex-sign-btn").nextAll('.alert-box').hide();
$.ajax({
url:"/getSign",
type:"post",
data:{
type:"hex",
priKey:$('#sign-pri').val(),
src:$('#sign-src').val()
},
success:function(jsonData)
{
if(jsonData.result=='success')
{
$('#sign-sign').val(jsonData.msg);
}
else{
$("#base-sign-btn").after('<div data-alert class="alert-box alert round">'+jsonData.msg+'</div>');
}
}
});
});
$("#base-sign-btn").bind('click',function(){
$("#base-sign-btn").nextAll('.alert-box').hide();
$.ajax({
url:"/getSign",
type:"post",
data:{
type:"base64",
priKey:$('#sign-pri').val(),
src:$('#sign-src').val()
},
success:function(jsonData)
{
if(jsonData.result=='success')
{
$('#sign-sign').val(jsonData.msg);
}
else{
$("#base-sign-btn").after('<div data-alert class="alert-box alert round">'+jsonData.msg+'</div>');
}
}
});
});
$("#verify-hex-sign-btn").bind('click',function() {
$("#verify-hex-sign-btn").nextAll('.alert-box').hide();
$.ajax({
url: "/verifySign",
type: "post",
data: {
type: "hex",
pubKey: $('#verify-pub').val(),
src: $('#verify-src').val(),
sign: $('#verify-sign').val()
},
success: function (jsonData) {
if (jsonData.result == 'success') {
if (jsonData.msg == "true") {
$("#verify-base-sign-btn").after('<div data-alert class="alert-box success round">验签成功</div>');
}
else {
$("#verify-base-sign-btn").after('<div data-alert class="alert-box warning round">验证失败</div>');
}
}
else {
$("#verify-base-sign-btn").after('<div data-alert class="alert-box alert round">' + jsonData.msg + '</div>');
}
}
});
});
$("#verify-base-sign-btn").bind('click',function(){
$("#verify-base-sign-btn").nextAll('.alert-box').hide();
$.ajax({
url:"/verifySign",
type:"post",
data:{
type:"base64",
pubKey:$('#verify-pub').val(),
src:$('#verify-src').val(),
sign:$('#verify-sign').val()
},
success:function(jsonData)
{
if(jsonData.result=='success')
{
if(jsonData.msg=="true")
{
$("#verify-base-sign-btn").after('<div data-alert class="alert-box success round">验签成功</div>');
}
else
{
$("#verify-base-sign-btn").after('<div data-alert class="alert-box warning round">验证失败</div>');
}
}
else{
$("#verify-base-sign-btn").after('<div data-alert class="alert-box alert round">'+jsonData.msg+'</div>');
}
}
});
});
$("#convert-hex-btn").bind('click',function(){
$("#convert-hex-btn").nextAll('.alert-box').hide();
$.ajax({
url:"/base64AndHex",
type:"post",
data:{
type:"hex",
input:$('#convert-input').val()
},
success:function(jsonData)
{
if(jsonData.result=='success')
{
$('#convert-output').val(jsonData.msg);
}
else{
$("#convert-base-btn").after('<div data-alert class="alert-box alert round">'+jsonData.msg+'</div>');
}
}
});
});
$("#convert-base-btn").bind('click',function(){
$("#convert-base-btn").nextAll('.alert-box').hide();
$.ajax({
url:"/base64AndHex",
type:"post",
data:{
type:"base64",
input:$('#convert-input').val()
},
success:function(jsonData)
{
if(jsonData.result=='success')
{
$('#convert-output').val(jsonData.msg);
}
else{
$("#convert-base-btn").after('<div data-alert class="alert-box alert round">'+jsonData.msg+'</div>');
}
}
});
});
$("#verify-identity-btn").bind('click',function(){
$("#verify-identity-btn").nextAll('.alert-box').hide();
$.ajax({
url:"/validateIdentityNo",
type:"post",
data:{
input:$('#identity-input').val()
},
success:function(jsonData)
{
if(jsonData.result=='success')
{
if(jsonData.msg=="true")
{
$("#verify-identity-btn").after('<div data-alert class="alert-box success round">身份证合法</div>');
}
else
{
$("#verify-identity-btn").after('<div data-alert class="alert-box warning round">身份证不合法</div>');
}
}
else{
$("#verify-identity-btn").after('<div data-alert class="alert-box alert round">'+jsonData.msg+'</div>');
}
}
});
});
$(".live-input").bind('focus',function(){
$(this).parent().parent().find('.alert-box').hide();
});
$("#md5-upper-btn").bind('click',function(){
$("#md5-upper-btn").nextAll('.alert-box').hide();
$("#md5-output").val(hex_md5($("#md5-input").val()).toUpperCase());
});
$("#md5-lower-btn").bind('click',function(){
$("#md5-lower-btn").nextAll('.alert-box').hide();
$("#md5-output").val(hex_md5($("#md5-input").val()).toLowerCase());
});
});<file_sep>package com.goldskyer.scorecloud;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.annotation.Rollback;
import com.goldskyer.gmxx.service.BaseTest;
import com.goldskyer.scorecloud.entities.Student;
import com.goldskyer.scorecloud.service.StudentService;
public class StudentServiceTest extends BaseTest
{
@Autowired
private StudentService studentService;
@Test
@Rollback(false)
public void testAddStudents()
{
for (int i = 1; i < 100; i++)
{
Student student = new Student();
student.setStudentNo("GEN" + i);
student.setStudentName("王" + i);
student.setClassId("8a72a3f558f312d20158f33f128a0009"); //班级都是1班
student.setStatus(1);
baseDao.add(student);
}
}
}
<file_sep>$(function() {
$('#closeWin').live('click',function(){
top.$.jBox.close("auditDialog");
});
$('.agree').bind("click",function(){
$.jBox("iframe:/manager/workflow/audit/view.htm?id="+flowId+"&eventType=APPROVE", {
title: "我的审核",
id:"auditDialog",
width: 800,
height: 450,
buttons: { }
});
});
$('.reject').bind("click",function(){
$.jBox("iframe:/manager/workflow/audit/view.htm?id="+flowId+"&eventType=REJECT", {
id:"auditDialog",
title: "我的审核",
width: 800,
height: 450,
buttons: { }
});
});
$('.comment').bind("click",function(){
$.jBox("iframe:/manager/workflow/audit/view.htm?id="+flowId+"&eventType=COMMENT", {
id:"auditDialog",
title: "我的评论",
width: 800,
height: 450,
buttons: { }
});
});
$('.revoke').bind("click",function(){
$.jBox("iframe:/manager/workflow/audit/view.htm?id="+flowId+"&eventType=REVOKE", {
id:"auditDialog",
title: "我的回收",
width: 800,
height: 450,
buttons: { }
});
});
$("#uploadImage").zyUpload({
width : "90%", // 宽度
height : "400px", // 宽度
itemWidth : "120px", // 文件项的宽度
itemHeight : "100px", // 文件项的高度
url : "/manager/upload/addImage.htm", // 上传文件的路径
multiple : true, // 是否可以多个文件上传
dragDrop : true, // 是否可以拖动上传文件
del : true, // 是否可以删除文件
finishDel : false, // 是否在上传文件完成后删除预览
});
$('#addForm').validate({
showErrors : function(errorMap, errorList) {
var element = this.currentElements;
if (element.next().hasClass('popover')) {
element.popover('destroy');
}
this.defaultShowErrors();
},
submitHandler : function(form) { // 表单提交句柄,为一回调函数,带一个参数:form
$(form).ajaxSubmit({
type : "post",
url : "/manager/workflow/audit/submit.json",
success : function(data) {
if (data.result == "success") {
top.location.reload();
} else {
alert(data.msg);
}
top.$.jBox.close("auditDialog");
}
});
},
});
});<file_sep>package com.goldskyer.scorecloud.service;
import java.util.List;
import com.goldskyer.scorecloud.dto.StudentDto;
public interface StudentService
{
public List<StudentDto> queryActiveStudentDtosByGradeId(String gradeId);
public List<StudentDto> queryAllActiveStudents(String schId);
public StudentDto queryStudentDtoById(String id);
public StudentDto queryStudentDtoByAccountId(String id);
public void addStudentDto(StudentDto studentDto);
public void modifyStudentDto(StudentDto studentDto);
public void deleteStudentDtoById(String id);
}
<file_sep>package com.goldskyer.scorecloud.exception.resp;
public class RespCodeConstant
{
public static final RespCode NOT_IMPLENENT = new RespCode("NOT_IMPLENENT", "功能暂时为实现");
public static final RespCode ACCOUNT_EXIST = new RespCode("ACCOUNT_EXIST", "账号已经存在");
public static final RespCode SUBJECT_EXIST = new RespCode("SUBJECT_EXIST", "该科目已经存在,请不要重复添加");
public static final RespCode STUDENT_NO_EXIST = new RespCode("STUDENT_NO_EXIST", "该学号已经存在,请不要重复添加");
public static final RespCode SCORE_ILLEGAL = new RespCode("SCORE_ILLEGAL", "分数不合法,不是一个数字");
public static final RespCode PARAM_ILLEGAL = new RespCode("PARAM_ILLEGAL", "提交参数非法");
public static final RespCode DELETE_GRADE_EXIST_CLASS = new RespCode("DELETE_GRADE_EXIST_CLASS", "请先删除班级,再删除年级");
public static final RespCode DELETE_CLASS_EXIST_STUDENT = new RespCode("DELETE_CLASS_EXIST_STUDENT",
"请先删除学生,再删除班级");
public static final RespCode USER_NAME_IS_EMPTY = new RespCode("USER_NAME_IS_EMPTY", "用户名不能为空");
public static final RespCode PWD_IS_EMPTY = new RespCode("PWD_IS_EMPTY", "密码不能为空");
}
<file_sep>package com.goldskyer.scorecloud.listener;
import java.io.IOException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
import com.goldskyer.core.dto.EnvParameter;
import com.goldskyer.gmxx.common.dtos.Ssn;
import com.goldskyer.gmxx.manager.utils.CookieUtil;
import com.goldskyer.scorecloud.business.LoginBusiness;
import com.goldskyer.scorecloud.constant.SessionConstant;
import com.goldskyer.scorecloud.dto.ScoreCloudEnv;
public class ScoreCloudHandler extends HandlerInterceptorAdapter
{
private Log log = LogFactory.getLog(ScoreCloudHandler.class);
@Autowired
private LoginBusiness loginBusiness;
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception
{
ScoreCloudEnv env = new ScoreCloudEnv();
ScoreCloudEnv.put(env);
env.setSchId("xcxx");
env.setRequest(request);
env.setResponse(response);
EnvParameter.get().setDomain("xcxx.goldskyer.com");
if (!checkLogin(request, response))
{
return false;
}
return super.preHandle(request, response, handler);
}
public boolean checkLogin(HttpServletRequest request, HttpServletResponse response) throws IOException
{
String openUrl = ";/scorecloud/login/xcxx.htm;/scorecloud/doLogin.json;" + "";
log.info("requestURI:" + request.getRequestURI());
if (!openUrl.contains(";" + request.getRequestURI() + ";"))
{
if (request.getSession().getAttribute(SessionConstant.USER_DTO) == null)
{
//判断cookie中是否有登陆信息
Ssn ssn = CookieUtil.getSsnFromCookie(request);
if (StringUtils.isNotBlank(ssn.getAccountId())
&& (System.currentTimeMillis() - ssn.getLoginDate().getTime()) < (30l * 24 * 3600 * 1000))
{
loginBusiness.doLogin(ssn.getAccountId());
return true;
}
else
{
String loginUrl = "/scorecloud/login/" + ScoreCloudEnv.get().getSchId() + ".htm";
response.sendRedirect(loginUrl);
return false;
}
}
}
return true;
}
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
throws Exception
{
ScoreCloudEnv.get().clear();
}
}
<file_sep>package com.goldskyer.gmxx.survey.service;
import com.goldskyer.gmxx.survey.entities.Question;
public interface QuestionService {
public void addQuestion(Question question);
public void modifyQuestion(Question question);
public Question queryQuestionById(String questionId);
}
<file_sep>package com.goldskyer.gmxx.manager.controllers;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import com.goldskyer.common.exceptions.BusinessException;
import com.goldskyer.core.dto.EnvParameter;
import com.goldskyer.core.dto.JsonData;
import com.goldskyer.core.entities.Account;
import com.goldskyer.core.entities.Department;
import com.goldskyer.core.enums.AccountStatus;
import com.goldskyer.core.enums.AccountType;
import com.goldskyer.gmxx.acl.entities.Role;
import com.goldskyer.gmxx.acl.service.AclService;
import com.goldskyer.gmxx.common.aop.RoleControl;
import com.goldskyer.gmxx.common.business.UserBusiness;
import com.goldskyer.gmxx.common.dtos.DataTableReqDto;
import com.goldskyer.gmxx.common.dtos.DataTablesRespDto;
import com.goldskyer.gmxx.common.dtos.UserDto;
import com.goldskyer.gmxx.common.entities.Teacher;
import com.goldskyer.gmxx.common.helpers.DataTableHelper;
import net.sf.json.JSONObject;
@Controller
@RequestMapping("/manager")
public class UserController extends BaseManagerController
{
@Autowired
@Qualifier("aclService")
protected AclService aclService;
@Autowired
protected UserBusiness userBusiness;
@RequestMapping("/user/list.htm")
@RoleControl("USER_VIEW")
public ModelAndView list(HttpServletRequest request)
{
ModelAndView mv = new ModelAndView("/manager/template");
mv.addObject("innerPage", "user/list");
return mv;
}
@RequestMapping(value = "/user/list_data.json", produces = "application/json;charset=UTF-8")
@ResponseBody
@RoleControl("USER_VIEW")
public Object listData(DataTableReqDto dataTableReqDto, HttpServletRequest request)
{
String dept = request.getParameter("dept");
String search = request.getParameter("search[value]");
dataTableReqDto.setSearchKey(search);
dataTableReqDto
.setSql("select username,nickname,createDate,lastLoginDate,id from Account where domain=:domain");
if (StringUtils.isNotBlank(dept))
{
dataTableReqDto.setSql(dataTableReqDto.getSql() + " ");
}
dataTableReqDto.setOrderBy("order by username ,id");
dataTableReqDto.setParam("domain", EnvParameter.get().getDomain());
dataTableReqDto.setSearchField("nickname,username");
DataTablesRespDto respDto = DataTableHelper.execute(dataTableReqDto, baseDao);
return respDto;
}
@RequestMapping(value = "/user/dialog/list_data.json", produces = "application/json;charset=UTF-8")
@ResponseBody
@RoleControl("USER_VIEW")
public Object listDialogData(DataTableReqDto dataTableReqDto, HttpServletRequest request)
{
String dept = request.getParameter("dept");
if(StringUtils.equalsIgnoreCase("root", dept))
{
dept = "";
}
String search = request.getParameter("search[value]");
dataTableReqDto.setSearchKey(search);
dataTableReqDto
.setSql("select a.id,a.username,t.name from Teacher t ,Account a where t.accountId=a.id and t.domain=:domain");
if (StringUtils.isNotBlank(dept))
{
dataTableReqDto.setSql(dataTableReqDto.getSql() + " and departmentId=:dept");
}
dataTableReqDto.setOrderBy("order by t.name ,t.id");
dataTableReqDto.setParam("domain", EnvParameter.get().getDomain());
dataTableReqDto.setParam("dept", dept);
dataTableReqDto.setSearchField("a.username,t.name");
DataTablesRespDto respDto = DataTableHelper.execute(dataTableReqDto, baseDao);
return respDto;
}
@RequestMapping("/user/dialog/list.htm")
@RoleControl("USER_VIEW")
public ModelAndView listDialog(HttpServletRequest request)
{
ModelAndView mv = new ModelAndView("/manager/dialog_templ");
Department department = departmentBusiness.getDepartmentTree(EnvParameter.get().getDomain());
mv.addObject("treeNode", JSONObject.fromObject(department).toString());
mv.addObject("innerPage", "user/dialog_list");
return mv;
}
@RequestMapping("/user/dialog/list_data.htm")
@RoleControl("USER_VIEW")
public ModelAndView listDataDialog(HttpServletRequest request)
{
ModelAndView mv = new ModelAndView("/manager/template");
mv.addObject("innerPage", "user/dialog_list");
return mv;
}
@RequestMapping("/user/toAdd.htm")
@RoleControl("USER_ADD")
public ModelAndView toAdd(HttpServletRequest request)
{
ModelAndView mv = new ModelAndView("/manager/template");
mv.addObject("innerPage", "user/add");
mv.addObject("selectVos", departmentBusiness.queryDepartmentSelectVos());
List<Role> roles = aclService.queryRoles(0, 1000);
mv.addObject("roles", roles);
return mv;
}
@RequestMapping(value = "/user/add.json", produces = "application/json;charset=UTF-8")
@ResponseBody
@RoleControl("USER_ADD")
public JsonData add(HttpServletRequest request, @ModelAttribute("account") Account account,
@ModelAttribute("teacher") Teacher teacher)
{
UserDto userDto = new UserDto();
account.setCreateDate(new Date());
account.setStatus(AccountStatus.NORMAL);
account.setType(AccountType.ADMIN);
userDto.setAccount(account);
String[] roleIds = request.getParameterValues("roleId");
if (null != roleIds && roleIds.length > 0) {
userDto.setRoleIds(Arrays.asList(roleIds));
}
userDto.setTeacher(teacher);
userBusiness.addUser(userDto);
return JsonData.success();
}
@RequestMapping("/user/toModify.htm")
@RoleControl("USER_EDIT")
public ModelAndView toModify(HttpServletRequest request)
{
ModelAndView mv = new ModelAndView("/manager/template");
mv.addObject("innerPage", "user/modify");
String id = request.getParameter("id");
List<Role> roles = aclService.queryRoles(0, 1000);
mv.addObject("roles", roles);
UserDto userDto = userBusiness.queryUserDtoById(id);
mv.addObject("userDto", userDto);
mv.addObject("selectVos", departmentBusiness.queryDepartmentSelectVos());
return mv;
}
/**
* 修改我的资料
* @param request
* @return
*/
@RequestMapping("/user/modifyMine.htm")
public ModelAndView modifyMine(HttpServletRequest request)
{
ModelAndView mv = new ModelAndView("/manager/template");
mv.addObject("innerPage", "user/modifyMine");
UserDto userDto = userBusiness.queryUserDtoById(getCurrentAccountId());
mv.addObject("userDto", userDto);
mv.addObject("selectVos", departmentBusiness.queryDepartmentSelectVos());
return mv;
}
@RequestMapping(value = "/user/modify.json", produces = "application/json;charset=UTF-8")
@ResponseBody
@RoleControl("USER_EDIT")
public JsonData modify(HttpServletRequest request, @ModelAttribute("account") Account account,
@ModelAttribute("teacher") Teacher teacher)
{
UserDto userDto = new UserDto();
userDto.setAccount(account);
userDto.setTeacher(teacher);
String[] roleIds = request.getParameterValues("roleId");
if (null != roleIds && roleIds.length > 0) {
//为用户分配角色
userDto.setRoleIds(Arrays.asList(roleIds));
}
userBusiness.modifyUserWithRole(userDto);
return JsonData.success();
}
@RequestMapping(value = "/user/modifyMine.json", produces = "application/json;charset=UTF-8")
@ResponseBody
@RoleControl("USER_EDIT")
public JsonData modifyMineJson(HttpServletRequest request, @ModelAttribute("account") Account account,
@ModelAttribute("teacher") Teacher teacher)
{
UserDto userDto = new UserDto();
userDto.setAccount(account);
userDto.setTeacher(teacher);
String[] roleIds = request.getParameterValues("roleId");
if (null != roleIds && roleIds.length > 0)
{
//为用户分配角色
userDto.setRoleIds(Arrays.asList(roleIds));
}
System.out.println(request.getParameter("photo"));
if (StringUtils.isNotBlank(request.getParameter("photo")))
{
Pattern p = Pattern.compile("<img.*src=\"([^\\s]*)\"");
Matcher m = p.matcher(request.getParameter("photo"));
String imgRelPath = null;
while (m.find())
{
imgRelPath = m.group(1);
break;
}
userDto.getAccount().setPhoto(imgRelPath);
}
userBusiness.modifyUser(userDto);
request.getSession().setAttribute("account", userDto.getAccount());
return JsonData.success();
}
@RequestMapping("/user/view.htm")
@RoleControl("USER_VIEW")
public ModelAndView view(HttpServletRequest request)
{
ModelAndView mv = new ModelAndView("/manager/template");
mv.addObject("innerPage", "user/view");
System.out.println(request.getRequestURI() + "," + request.getRequestURL().toString());
String accountId = request.getParameter("id");
Account account = aclService.queryAccount(accountId);
if (account == null)
{
throw new BusinessException("当前请求记录不存在");
}
//获取账号角色
List<Role> roles = aclService.queryRolesByUser(accountId);
mv.addObject("account", account);
mv.addObject("roles", roles);
return mv;
}
@RequestMapping("/user/delete.htm")
@RoleControl("USER_DELETE")
public ModelAndView delete(HttpServletRequest request)
{
String accountId = request.getParameter("id");
System.out.println(request.getRequestURI() + "," + request.getRequestURL().toString());
userBusiness.deleteUser(accountId);
return new ModelAndView("redirect:/manager/user/list.htm");
}
@RequestMapping(value = "/user/check_username.json", produces = "application/json;charset=UTF-8")
@ResponseBody
public JsonData checkUsername(@RequestParam String username)
{
boolean check = accountService.checkUserName(username);
return !check ? JsonData.success() : JsonData.failure();
}
@InitBinder("account")
public void initAccountBinder(WebDataBinder binder)
{
binder.setFieldDefaultPrefix("account.");
}
@InitBinder("teacher")
public void initTeacherBinder(WebDataBinder binder)
{
binder.setFieldDefaultPrefix("teacher.");
}
}<file_sep>package com.goldskyer.gmxx.service;
import java.util.List;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.annotation.Rollback;
import com.goldskyer.core.dao.BaseDao;
import com.goldskyer.core.entities.Blog;
public class CopyData extends BaseTest
{
@Autowired
private BaseDao baseDao;
@Test
@Rollback(false)
public void testCopyBlog()
{
List<Blog> blogs = baseDao.query("select b from Blog b where b.type='校园风景' ");
for (Blog b : blogs)
{
b.setType("Beautiful Campus");
b.setId(null);
b.setAuthor("Information Center");
b.setTitle("Beautiful Campus");
baseDao.add(b);
}
}
}
<file_sep>package com.goldskyer.gmxx.manager.controllers.workflow;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import com.goldskyer.core.dao.BaseDao;
import com.goldskyer.core.dto.EnvParameter;
import com.goldskyer.core.dto.JsonData;
import com.goldskyer.core.service.AccountService;
import com.goldskyer.core.service.BlogService;
import com.goldskyer.core.service.CachedMenuService;
import com.goldskyer.core.service.CommentService;
import com.goldskyer.gmxx.common.aop.RoleControl;
import com.goldskyer.gmxx.common.dtos.DataTableReqDto;
import com.goldskyer.gmxx.common.dtos.DataTablesRespDto;
import com.goldskyer.gmxx.common.entities.WorkFlowNode;
import com.goldskyer.gmxx.common.entities.WorkFlowTemplate;
import com.goldskyer.gmxx.common.helpers.DataTableHelper;
import com.goldskyer.gmxx.common.service.LiveVideoService;
import com.goldskyer.gmxx.common.service.WorkFlowNodeService;
import com.goldskyer.gmxx.common.service.WorkFlowService;
import com.goldskyer.gmxx.manager.controllers.BaseManagerController;
import com.goldskyer.gmxx.workflow.service.WorkflowTemplateService;
/**
* 流程模板管理
* @author jintianfan
*
*/
@Controller
@RequestMapping("/manager/workflow/template")
@SuppressWarnings(
{ "rawtypes", "unchecked", "deprecation" })
public class WorkFlowTemplateController extends BaseManagerController
{
@Autowired
protected BaseDao baseDao;
@Autowired
protected WorkflowTemplateService workflowTemplateService;
@Autowired
protected WorkFlowNodeService workFlowNodeService;
@Autowired
@Qualifier("blogService")
protected BlogService blogService;
@Autowired
protected CommentService commentService;
@Autowired
protected AccountService accountService;
@Autowired
protected WorkFlowService workFlowService;
@Autowired
@Qualifier("cachedMenuService")
protected CachedMenuService cachedMenuService;
@Autowired
protected LiveVideoService liveVideoService;
//@Autowired
//@Qualifier("xdcmsBlogService")
//protected BlogService xdBlogService;
@RequestMapping("/list.htm")
@RoleControl("WORKFLOW_TEMPLATE_VIEW")
public ModelAndView list(HttpServletRequest request)
{
ModelAndView mv = new ModelAndView("/manager/template");
mv.addObject("innerPage", "workflow/template_list");
return mv;
}
@RequestMapping(value = "/list_data.json", produces = "application/json;charset=UTF-8")
@ResponseBody
@RoleControl("WORKFLOW_TEMPLATE_VIEW")
public Object listData(DataTableReqDto dataTableReqDto, HttpServletRequest request)
{
String search = request.getParameter("search[value]");
dataTableReqDto.setSearchKey(search);
dataTableReqDto
.setSql("select a.name,b.nickname,a.createDate,a.updateDate,a.id from WorkFlowTemplate a ,Account b where a.author=b.id and a.domain=:domain");
dataTableReqDto.setOrderBy("order by a.createDate desc,a.id");
dataTableReqDto.setParam("domain", EnvParameter.get().getDomain());
dataTableReqDto.setSearchField("a.name,a.author");
DataTablesRespDto respDto = DataTableHelper.execute(dataTableReqDto, baseDao);
return respDto;
}
@RequestMapping("/toAdd.htm")
@RoleControl("WORKFLOW_TEMPLATE_ADD")
public ModelAndView toAdd(HttpServletRequest request, @RequestParam(required = false) String pId)
{
ModelAndView mv = new ModelAndView("/manager/template");
mv.addObject("innerPage", "workflow/template_toAdd");
mv.addObject("roles", aclService.queryRoles(0, 1000));
return mv;
}
@RequestMapping(value = "/add.json", produces = "application/json;charset=UTF-8")
@ResponseBody
@RoleControl("WORKFLOW_TEMPLATE_ADD")
public JsonData addJson(HttpServletRequest request, WorkFlowTemplate template)
{
template.setAuthor(getCurrentAccountId());
List<WorkFlowNode> nodes = new ArrayList<>();
String[] statuses = request.getParameterValues("status[]");
String[] accountIds = request.getParameterValues("accountId[]");
String[] roles = request.getParameterValues("role[]");
if (statuses != null & statuses.length > 0)
{
for (int i = 0; i < statuses.length; i++)
{
WorkFlowNode node = new WorkFlowNode();
if (StringUtils.isBlank(statuses[i]) && StringUtils.isBlank(accountIds[i])
&& StringUtils.isBlank(roles[i]))
{
continue;
}
node.setStatus(StringUtils.trimToEmpty(statuses[i]));
node.setAccountId(null);
node.setRole(StringUtils.trimToEmpty(roles[i]));
nodes.add(node);
}
}
workflowTemplateService.addTemplate(template, nodes);
return JsonData.success();
}
@RequestMapping("/toModify.htm")
@RoleControl("WORKFLOW_TEMPLATE_EDIT")
public ModelAndView toModify(HttpServletRequest request, @RequestParam String id)
{
ModelAndView mv = new ModelAndView("/manager/template");
mv.addObject("innerPage", "workflow/template_toModify");
WorkFlowTemplate template = baseDao.query(WorkFlowTemplate.class, id);
mv.addObject("template", template);
List<WorkFlowNode> nodes = workFlowNodeService.queryWorkFlowNodesByTemplateId(id);
mv.addObject("nodes", nodes);
mv.addObject("roles", aclService.queryRoles(0, 1000));//角色列表
return mv;
}
@RequestMapping(value = "/modify.json", produces = "application/json;charset=UTF-8")
@ResponseBody
@RoleControl("WORKFLOW_TEMPLATE_EDIT")
public JsonData modify(HttpServletRequest request, WorkFlowTemplate template)
{
List<WorkFlowNode> nodes = new ArrayList<>();
String[] nodeIds = request.getParameterValues("nodeId[]");
String[] statuses = request.getParameterValues("status[]");
String[] accountIds = request.getParameterValues("accountId[]");
String[] roles = request.getParameterValues("role[]");
if (statuses != null & statuses.length > 0)
{
for (int i = 0; i < statuses.length; i++)
{
WorkFlowNode node = new WorkFlowNode();
if (StringUtils.isBlank(statuses[i]) && StringUtils.isBlank(accountIds[i])
&& StringUtils.isBlank(roles[i]))
{
continue;
}
node.setId(nodeIds[i]);
node.setStatus(StringUtils.trimToEmpty(statuses[i]));
//node.setAccountId(StringUtils.trimToEmpty(accountIds[i]));
node.setRole(StringUtils.trimToEmpty(roles[i]));
nodes.add(node);
}
}
workflowTemplateService.modifyTemplate(template, nodes);
return JsonData.success();
}
@RequestMapping("/delete.htm")
@RoleControl("WORKFLOW_TEMPLATE_DELETE")
public ModelAndView delete(HttpServletRequest request)
{
String id = request.getParameter("id");
workflowTemplateService.deleteTemplateById(id);
return new ModelAndView("redirect:list.htm");
}
}<file_sep> function refreshimg(){
document.all.checkcode.src='/code?'+Math.random();
}
$(document).ready(function(){
//判断错误信息
$('#login-form').validate({
rules: {
j_username: {
required: true,
},
j_password: {
required: true,
},
j_code: {
required: true,
}
},
messages: {
j_username: {
required: "请输入用户名",
},
j_password: {
required: "请输入密码",
},
j_code: {
required: "请输入验证码",
},
},
errorPlacement: function(error, element) {
element.popover({
trigger: 'manual',
'html': true,
content: '<p class="error" style="width:100px;">'+error.html()+'</p>',
}).popover('show');
},
showErrors:function(errorMap,errorList) {
var element = this.currentElements;
if(element.next().hasClass('popover')){
element.popover('destroy');
}
this.defaultShowErrors();
},
submitHandler: function(form)
{
// alert($('input[name="j_password"]').val());
// alert(CryptoJS.MD5($('input[name="j_password"]').val()));
// alert(CryptoJS.MD5(CryptoJS.MD5($('input[name="j_password"]').val())+""));
$('input[name="j_password"]').val(CryptoJS.MD5(CryptoJS.MD5($('input[name="j_password"]').val())+""));
$(form).ajaxSubmit(function(data) {
if(data.result=='success'){
window.location.href = '/manager/index.htm'
}else{
$('.error-hold').html(data.msg);
refreshimg();
}
});
}
});
});<file_sep>package com.goldskyer.scorecloud.service.impl;
import java.util.ArrayList;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.goldskyer.scorecloud.constant.ScoreConstant;
import com.goldskyer.scorecloud.dto.ClassDto;
import com.goldskyer.scorecloud.dto.GradeDto;
import com.goldskyer.scorecloud.dto.ScoreCloudEnv;
import com.goldskyer.scorecloud.dto.SubjectDto;
import com.goldskyer.scorecloud.dto.TargetScoreItem;
import com.goldskyer.scorecloud.entities.Subject;
import com.goldskyer.scorecloud.helper.AvgValueHelper;
import com.goldskyer.scorecloud.service.ClassService;
import com.goldskyer.scorecloud.service.ExamService;
import com.goldskyer.scorecloud.service.GradeService;
import com.goldskyer.scorecloud.service.SubjectService;
import com.goldskyer.scorecloud.service.TargetScoreService;
import com.goldskyer.scorecloud.vo.TargetScoreVo;
@Service
public class TargetScoreServiceImpl implements TargetScoreService
{
@Autowired
private ExamService examService;
@Autowired
private ClassService classService;
@Autowired
private SubjectService subjectService;
@Autowired
private GradeService gradeService;
/**
* 总分目标值计算
* @param examId
* @param classDto
* @return
*/
public TargetScoreItem calculateTargetScoreItem(String schId, String title, String examId, ClassDto classDto)
{
List<TargetScoreItem> sumList = new ArrayList<>();
List<SubjectDto> subjects = subjectService.querySubjectsByExamId(examId);
TargetScoreItem item = new TargetScoreItem();
item.setTitle(title);
item.setClassDto(classDto);
item.setSubjectCnt(subjects.size());
item.setStudentCnt(classService.queryStudentCntByClassId(classDto.getId()));
if (subjects.size() == 0)
return item;
item.setJoinExamCnt(examService.queryJoinedExamCntByClassId(schId, classDto.getId(), examId));
if (item.getJoinExamCnt() == 0)
{
return item;
}
item.setTotalScore(examService.queryJoinedExamTotalScoreCntByClassId(schId, classDto.getId(), examId));
item.setAvgScore(item.getTotalScore() / item.getJoinExamCnt() / subjects.size());
item.setHegeCnt(examService.queryJoinedAvgScoreReachedCntByClassId(schId, classDto.getId(), examId,
Float.valueOf(ScoreConstant.HEGE_SCORE * subjects.size())));
item.setHegeRate(item.getHegeCnt() * 100f / item.getJoinExamCnt());
item.setYouliangCnt(examService.queryJoinedAvgScoreReachedCntByClassId(schId, classDto.getId(), examId,
Float.valueOf(ScoreConstant.YOULIANG_SCORE * subjects.size())));
item.setYouliangRate(item.getYouliangCnt() * 100f / item.getJoinExamCnt());
//平均值计算
item.setAvgValue(
AvgValueHelper.calculateAvgValue(item.getAvgScore(), item.getHegeRate(), item.getYouliangRate()));
return item;
}
public TargetScoreVo getTargetScoreVo(String schId, String examId)
{
List<TargetScoreItem> sumList = new ArrayList<>();
TargetScoreVo targetScoreVo = new TargetScoreVo();
List<GradeDto> gradeDtos = gradeService.queryAllGradeDtoWithClassDtos(ScoreCloudEnv.get().getSchId());
for (GradeDto gradeDto : gradeDtos)
{
List<TargetScoreItem> tmp = new ArrayList<>();
for (ClassDto classDto : gradeDto.getClassDtos())
{
tmp.add(calculateTargetScoreItem(schId, gradeDto.getGradeName() + classDto.getClassName(), examId,
classDto));
}
if (tmp.size() > 0)//如果一个年级没有参加考试,则不会计入目标分管理
{
targetScoreVo.getItems().addAll(tmp);
TargetScoreItem item = mergeTargetScoreItem("小计", tmp);
targetScoreVo.getItems().add(item);
sumList.add(item);
}
}
targetScoreVo.getItems().add(mergeTargetScoreItem("总计", sumList));
return targetScoreVo;
}
public TargetScoreItem calculateTargetSubjectScoreItem(String schId, String title, String subjectId,
ClassDto classDto)
{
Subject subject = subjectService.querySubjectById(subjectId);
TargetScoreItem item = new TargetScoreItem();
item.setTitle(title);
item.setClassDto(classDto);
item.setSubjectCnt(1);
item.setStudentCnt(classService.queryStudentCntByClassId(classDto.getId()));
item.setJoinExamCnt(examService.queryJoinedSubjectCntByClassId(schId, classDto.getId(), subjectId));
if (item.getJoinExamCnt() == 0)
{
return item;
}
item.setTotalScore(examService.queryJoinedSubjectTotalScoreCntByClassId(schId, classDto.getId(), subjectId));
item.setAvgScore(item.getTotalScore() / item.getJoinExamCnt());
item.setHegeCnt(examService.queryJoinedSubjectAvgScoreReachedCntByClassId(schId, classDto.getId(), subjectId,
Float.valueOf(subject.getHegeScore())));
item.setHegeRate(item.getHegeCnt() * 100f / item.getJoinExamCnt());
item.setYouliangCnt(examService.queryJoinedSubjectAvgScoreReachedCntByClassId(schId, classDto.getId(),
subjectId,
Float.valueOf(subject.getYouliangScore())));
item.setYouliangRate(item.getYouliangCnt() * 100f / item.getJoinExamCnt());
//平均值计算
item.setAvgValue(
AvgValueHelper.calculateAvgValue(item.getAvgScore(), item.getHegeRate(), item.getYouliangRate()));
return item;
}
public TargetScoreVo getTargetSubjectScoreVo(String schId, String subjectId)
{
List<TargetScoreItem> sumList = new ArrayList<>();
TargetScoreVo targetScoreVo = new TargetScoreVo();
List<GradeDto> gradeDtos = gradeService.queryAllGradeDtoWithClassDtos(ScoreCloudEnv.get().getSchId());
for (GradeDto gradeDto : gradeDtos)
{
List<TargetScoreItem> tmp = new ArrayList<>();
for (ClassDto classDto : gradeDto.getClassDtos())
{
tmp.add(calculateTargetSubjectScoreItem(schId, gradeDto.getGradeName() + classDto.getClassName(),
subjectId,
classDto));
}
targetScoreVo.getItems().addAll(tmp);
TargetScoreItem item=mergeTargetScoreItem("小计", tmp);
targetScoreVo.getItems().add(item);
sumList.add(item);
}
targetScoreVo.getItems().add(mergeTargetScoreItem("总计", sumList));
return targetScoreVo;
}
/**
* 合并统计量,获取汇总信息
* @param title
* @param items
* @return
*/
private TargetScoreItem mergeTargetScoreItem(String title, List<TargetScoreItem> items)
{
TargetScoreItem result = new TargetScoreItem();
result.setStudentCnt(0);//统计量初始学生数为0
result.setTitle(title);
for (TargetScoreItem item : items)
{
result.setSubjectCnt(item.getSubjectCnt());
result.setStudentCnt(result.getStudentCnt() + item.getStudentCnt());
result.setJoinExamCnt(result.getJoinExamCnt() + item.getJoinExamCnt());
result.setTotalScore(result.getTotalScore() + item.getTotalScore());
result.setHegeCnt(result.getHegeCnt() + item.getHegeCnt());
result.setYouliangCnt(result.getYouliangCnt() + item.getYouliangCnt());
}
if (result.getJoinExamCnt() == 0)
{
return result;
}
result.setAvgScore(result.getTotalScore() / result.getJoinExamCnt() / result.getSubjectCnt());
result.setHegeRate(result.getHegeCnt() * 100f / result.getJoinExamCnt());
result.setYouliangRate(result.getYouliangCnt() * 100f / result.getJoinExamCnt());
result.setAvgValue(
AvgValueHelper.calculateAvgValue(result.getAvgScore(), result.getHegeRate(), result.getYouliangRate()));
return result;
}
}
<file_sep>package com.goldskyer.gmxx.manager.forms;
public class BlogMediaForm
{
private String liveIp;
private boolean isOpen;
private boolean needSync;
public String getLiveIp()
{
return liveIp;
}
public void setLiveIp(String liveIp)
{
this.liveIp = liveIp;
}
public boolean isOpen()
{
return isOpen;
}
public void setOpen(boolean isOpen)
{
this.isOpen = isOpen;
}
public boolean isNeedSync()
{
return needSync;
}
public void setNeedSync(boolean needSync)
{
this.needSync = needSync;
}
}
<file_sep>package com.goldskyer.gmxx.survey.entities;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
import org.hibernate.annotations.GenericGenerator;
/**
* 同一个人可以多次提交,做多套题目
* @author jintianfan
*
*/
@Entity
@Table(name="test_record")
public class TestRecord {
@Id
@Column(name = "ID", length = 40)
@GeneratedValue(generator = "idGenerator")
@GenericGenerator(name = "idGenerator", strategy = "uuid")
private String id;
private String fp;
private String department;
private Integer age;
private String gender;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getFp() {
return fp;
}
public void setFp(String fp) {
this.fp = fp;
}
public String getDepartment() {
return department;
}
public void setDepartment(String department) {
this.department = department;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
}
<file_sep>//当前选中的treeNode
curNode= new Object();
/**
* 初始化表单
* @param id
*/
function initMenuForm(treeNode)
{
$('input[name="id"]').val(treeNode.id);
$('input[name="name"]').val(treeNode.name);
$('input[name="duty"]').val(treeNode.duty);
$('input[name="phone"]').val(treeNode.phone);
$('input[name="weight"]').val(treeNode.weight);
$('input[name="parentId"]').val(treeNode.parentId);
}
/**
* 初始化空白的添加表单
*/
function initAddMenuForm()
{
$('input[name="id"]').val("");
$('input[name="name"]').val("");
$('input[name="duty"]').val("");
$('input[name="phone"]').val("");
$('input[name="weight"]').val("");
$('input[name="parentId"]').val($('input[name="id"]')); //当前节点ID变为新增节点的父节点
}
var setting = {
check : {
enable : false
},
data : {
simpleData : {
enable : true
}
},
callback: {
onClick:function(event, treeId, treeNode){
curNode=treeNode;
initMenuForm(treeNode);
}
}
};
$(function() {
//事件初始化
$("addBtn").bind("click",function(){
initAddMenuForm();
});
$("delBtn").bind("click",function(){
zTree.removeNode(curNode,true);
showInfo("success","当前部门删除成功");
});
$.fn.zTree.init($("#treeDemo"), setting, zData);
zTree = $.fn.zTree.getZTreeObj("treeDemo");
zTree.expandAll(true);
$('#addForm').validate({
rules : {
name : {
required : true
}
},
messages : {
name : {
required : "部门名称不能为空"
}
},
showErrors : function(errorMap, errorList) {
var element = this.currentElements;
if (element.next().hasClass('popover')) {
element.popover('destroy');
}
this.defaultShowErrors();
},
submitHandler : function(form) { // 表单提交句柄,为一回调函数,带一个参数:form
$(form).ajaxSubmit({
type : "post",
url : "add.json",
success : function(data) {
if (data.result == "success") {
showInfo("success","部门保存成功");
var nodes = zTree.getSelectedNodes();
if (nodes.length>0) {
nodes[0].name=data.data.department.name;
nodes[0].weight=data.data.department.weight;
nodes[0].phone=data.data.department.phone;
nodes[0].duty=data.data.department.duty;
zTree.updateNode(nodes[0]);
}
} else {
alert(data.msg);
}
}
});
},
});
});
<file_sep>package com.goldskyer.gmxx.front.controllers;
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.RequestParam;
import org.springframework.web.servlet.ModelAndView;
import com.goldskyer.core.entities.Blog;
import com.goldskyer.gmxx.BaseController;
import com.goldskyer.gmxx.common.constants.GmxxConstant;
import com.goldskyer.gmxx.common.service.LiveVideoService;
@Controller
@RequestMapping("/front/tv")
public class TvController extends BaseController{
@Autowired
private LiveVideoService liveVideoService;
@RequestMapping("/view.htm")
public ModelAndView detail(@RequestParam String id, HttpServletRequest request)
{
ModelAndView mv = new ModelAndView("/front/tv/view");
Blog blog = blogService.queryBlog(id);
//Menu menu = menuService.queryMenuByName(blog.getType());
//mv.addObject("mainMenu", menuService.getMainMenu());
//mv.addObject("menu", menu);
mv.addObject("blog",blog);
//其他视频资源
blogBusiness.buildCommonBlogListModel(mv, blog.getType(), 0, Integer.valueOf(iniService.getIniValue(GmxxConstant.PAGE_SIZE)));
blogService.incViewCount(id);
//直播
if (blog.getNeedAuth() && request.getSession().getAttribute("blogId") == null)
{
return new ModelAndView("404");
}
return mv;
}
}
<file_sep>package com.goldskyer.gmxx.common.utils;
<file_sep>require('../bower_components/Swiper/dist/css/swiper.min.css');
require('../less/team.less');
$(function () {
var winWidth = $(window).width();
$('.loading').hide();
var leftEnd = winWidth - 145 + 'px';
$('.my-item-title-animate').animate({
left: leftEnd,
opacity: 0.85
}, 2000, 'ease-in-out', function () {
$('.my-item-title-animate').css('left', leftEnd);
$('.my-item-title-animate').css('opacity', 0.85);
});
$('.menu-tap').on('tap', function () {
location.href = $(this).data('href');
});
var mySwiper = new Swiper('.swiper-container', {
direction: 'horizontal',
loop: true,
autoplay: 3000,
pagination: '.swiper-pagination',
paginationHide: false,
parallax: true
});
});<file_sep>package com.goldskyer.scorecloud;
import java.io.FileInputStream;
import java.util.List;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.StringUtils;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.annotation.Rollback;
import org.springframework.transaction.annotation.Transactional;
import com.goldskyer.core.dto.EnvParameter;
import com.goldskyer.gmxx.service.BaseTest;
import com.goldskyer.scorecloud.dto.ClassDto;
import com.goldskyer.scorecloud.dto.ScoreCloudEnv;
import com.goldskyer.scorecloud.dto.StudentDto;
import com.goldskyer.scorecloud.service.ClassService;
import com.goldskyer.scorecloud.service.GradeService;
import com.goldskyer.scorecloud.service.StudentService;
public class DataImport extends BaseTest
{
@Autowired
private StudentService studentService;
@Autowired
private GradeService gradeService;
@Autowired
private ClassService classService;
@Test
public void queryClassInfo()
{
ClassDto classDto = classService.queryClassDtoByNameInfo("xcxx", "一年级", "1班");
System.out.println(classDto);
}
@Test
@Rollback(false)
@Transactional
public void test() throws Exception
{
EnvParameter.put(new EnvParameter());
EnvParameter.get().setDomain("xcxx.goldskyer.com");
ScoreCloudEnv.put(new ScoreCloudEnv());
ScoreCloudEnv.get().setSchId("xcxx");
String excel = "/data/xcxx/深圳市光明新区下村小学.csv";
List<String> lines = IOUtils.readLines(new FileInputStream(excel), "GBK");
for (int i = 1000; i < lines.size(); i++)
{
System.out.println(lines.get(i));
String[] item = lines.get(i).split(";");
StudentDto studentDto=new StudentDto();
studentDto.setStudentNo(StringUtils.trimToEmpty(item[0]));
studentDto.setStudentName(StringUtils.trimToEmpty(item[1]));
studentDto.setSex(StringUtils.trimToEmpty(item[2]));
studentDto.setBirthDay(StringUtils.trimToEmpty(item[7]));
studentDto.setStatus(1);
studentDto.setEnterYear(Integer.valueOf(StringUtils.trimToEmpty(item[4]).substring(0, 4)));
studentDto.setNational(StringUtils.trimToEmpty(item[8]));
studentDto.setAddress(StringUtils.trimToEmpty(item[9]));
studentDto.setUsername(studentDto.getStudentNo());
studentDto.setPassword("<PASSWORD>");
ClassDto classDto = classService.queryClassDtoByNameInfo("xcxx", StringUtils.trimToEmpty(item[6]),
StringUtils.trimToEmpty(item[3]));
if (classDto == null)
log.fatal("找不到班级:" + lines.get(i));
studentDto.setClassId(classDto.getId());
studentService.addStudentDto(studentDto);
//studentDto.setClassId(classId);
}
}
public static void main(String[] args) throws Exception
{
}
}
<file_sep>package com.goldskyer.scorecloud.dto;
public class ScoreDto
{
private String id;
private String studentId;
private String examId;
private String subjectId;//科目
private Float score;
private String gradeName;//年级名称 //记录当前考试的年级,因为年级是可以变动的
public String getId()
{
return id;
}
public void setId(String id)
{
this.id = id;
}
public String getStudentId()
{
return studentId;
}
public void setStudentId(String studentId)
{
this.studentId = studentId;
}
public String getExamId()
{
return examId;
}
public void setExamId(String examId)
{
this.examId = examId;
}
public String getSubjectId()
{
return subjectId;
}
public void setSubjectId(String subjectId)
{
this.subjectId = subjectId;
}
public Float getScore()
{
return score;
}
public void setScore(Float score)
{
this.score = score;
}
public String getGradeName()
{
return gradeName;
}
public void setGradeName(String gradeName)
{
this.gradeName = gradeName;
}
}
<file_sep>package com.goldskyer.scorecloud.vo;
public class SubjectScoreItem
{
private String subjectName;
private Float subjectScore;
private Integer classRank;
private Integer gradeRank;
public String getSubjectName()
{
return subjectName;
}
public void setSubjectName(String subjectName)
{
this.subjectName = subjectName;
}
public Float getSubjectScore()
{
return subjectScore;
}
public void setSubjectScore(Float subjectScore)
{
this.subjectScore = subjectScore;
}
public Integer getClassRank()
{
return classRank;
}
public void setClassRank(Integer classRank)
{
this.classRank = classRank;
}
public Integer getGradeRank()
{
return gradeRank;
}
public void setGradeRank(Integer gradeRank)
{
this.gradeRank = gradeRank;
}
}
<file_sep>package com.goldskyer.scorecloud.vo;
public class ScoreTableVo
{
}
<file_sep>$(function() {
/**
* Menu表单校验
*/
$('#addForm').validate({
rules : {
roleName : {
required : true
}
},
messages : {
roleName : {
required : "角色名称不能为空"
}
},
showErrors : function(errorMap, errorList) {
var element = this.currentElements;
if (element.next().hasClass('popover')) {
element.popover('destroy');
}
this.defaultShowErrors();
},
submitHandler : function(form) { // 表单提交句柄,为一回调函数,带一个参数:form
$(form).ajaxSubmit({
type : "post",
url : "/manager/role/add.json",
success : function(data) {
// showInfo("info","保存成功");
if (data.result == "success") {
window.location.href = "/manager/role/list.htm";
} else {
alert(data.msg);
}
}
});
},
});
});
<file_sep>package com.goldskyer.gmxx.service.manager;
import java.util.Date;
import org.junit.Test;
import org.springframework.test.annotation.Rollback;
import com.goldskyer.gmxx.acl.entities.Right;
import com.goldskyer.gmxx.service.BaseTest;
public class IniServiceTest extends BaseTest
{
@Test
@Rollback(false)
public void testAddRights()
{
String domain = "smart.goldskyer.com";
Right r1=new Right();
r1.setCreateDate(new Date());
r1.setDomain(domain);
r1.setRightName("配置添加");
r1.setRightNo("INI_ADD");
r1.setType("配置管理");
baseDao.add(r1);
Right r2 = new Right();
r2.setCreateDate(new Date());
r2.setDomain(domain);
r2.setRightName("配置修改");
r2.setRightNo("INI_EDIT");
r2.setType("配置管理");
baseDao.add(r2);
Right r3 = new Right();
r3.setCreateDate(new Date());
r3.setDomain(domain);
r3.setRightName("配置删除");
r3.setRightNo("INI_DELETE");
r3.setType("配置管理");
baseDao.add(r3);
Right r4 = new Right();
r4.setCreateDate(new Date());
r4.setDomain(domain);
r4.setRightName("配置查看");
r4.setRightNo("INI_VIEW");
r4.setType("配置管理");
baseDao.add(r4);
}
}
<file_sep>package com.goldskyer.gmxx.common.helpers;
import java.util.ArrayList;
import java.util.List;
import org.apache.commons.lang.StringUtils;
import com.goldskyer.core.dao.BaseDao;
import com.goldskyer.gmxx.common.dtos.DataTableReqDto;
import com.goldskyer.gmxx.common.dtos.DataTablesRespDto;
public class DataTableHelper
{
public static DataTablesRespDto execute(DataTableReqDto reqDto, BaseDao baseDao)
{
DataTablesRespDto respDto = new DataTablesRespDto();
String countSql = reqDto.getSql()
+ (StringUtils.isNotBlank(reqDto.getSearchKey())
? " and concat(" + reqDto.getSearchField() + ") like '%" + reqDto.getSearchKey() + "%'" : "");
countSql += " " + reqDto.getOrderBy();
long count = baseDao.count(countSql, reqDto.getParaMap());
respDto.setRecordsTotal(count);
respDto.setRecordsFiltered(count);
List data = baseDao.query(countSql, reqDto.getParaMap(), reqDto.getStart(), reqDto.getLength());
respDto.setData(data);
return respDto;
}
public static DataTablesRespDto execute(DataTableReqDto reqDto, BaseDao baseDao, VoConverter converter)
{
DataTablesRespDto respDto = new DataTablesRespDto();
String countSql = reqDto.getSql() + (StringUtils.isNotBlank(reqDto.getSearchKey())
? " and concat(" + reqDto.getSearchField() + ") like '%" + reqDto.getSearchKey() + "%'" : "");
countSql += " " + reqDto.getOrderBy();
long count = baseDao.count(countSql, reqDto.getParaMap());
respDto.setRecordsTotal(count);
respDto.setRecordsFiltered(count);
List data = baseDao.query(countSql, reqDto.getParaMap());
List realData=new ArrayList<>();
for(Object o:data)
{
realData.add(converter.convert((Object[]) o));
}
respDto.setData(data);
return respDto;
}
}
<file_sep>package com.goldskyer.gmxx.common.entities;
import java.util.Date;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
import org.hibernate.annotations.GenericGenerator;
@Entity
@Table(name = "work_flow_template")
public class WorkFlowTemplate
{
@Id
@Column(name = "ID", length = 40)
@GeneratedValue(generator = "idGenerator")
@GenericGenerator(name = "idGenerator", strategy = "uuid")
private String id;
private String name;
private Date createDate;
private Date updateDate;
private String author;
private String objectType; //主类型
private String subType;//子类型(博客类型)
private String domain;
public String getId()
{
return id;
}
public void setId(String id)
{
this.id = id;
}
public String getName()
{
return name;
}
public void setName(String name)
{
this.name = name;
}
public Date getCreateDate()
{
return createDate;
}
public void setCreateDate(Date createDate)
{
this.createDate = createDate;
}
public Date getUpdateDate()
{
return updateDate;
}
public void setUpdateDate(Date updateDate)
{
this.updateDate = updateDate;
}
public String getAuthor()
{
return author;
}
public void setAuthor(String author)
{
this.author = author;
}
public String getObjectType()
{
return objectType;
}
public void setObjectType(String objectType)
{
this.objectType = objectType;
}
public String getDomain()
{
return domain;
}
public void setDomain(String domain)
{
this.domain = domain;
}
public String getSubType()
{
return subType;
}
public void setSubType(String subType)
{
this.subType = subType;
}
}
<file_sep>package com.goldskyer.gmxx.common.entities;
import java.util.Date;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.EnumType;
import javax.persistence.Enumerated;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
import org.hibernate.annotations.GenericGenerator;
import com.goldskyer.gmxx.common.enums.WorkFlowAuditEvent;
/**
*TODO 如何实现转交
* @author jintianfan
*
*/
@Entity
@Table(name = "work_flow_data")
public class WorkFlowData
{
@Id
@Column(name = "ID", length = 40)
@GeneratedValue(generator = "idGenerator")
@GenericGenerator(name = "idGenerator", strategy = "uuid")
private String id;
private String objectId;
private String objectType;
private String accountId;
private String nickName;
private String fromStatus;
private String toStatus;
private String comment;
private boolean approved; //审核状态
private String note; //审核意见,评论页放在note里面,简化处理流程
@Enumerated(EnumType.STRING)
private WorkFlowAuditEvent eventType;//审核,评论
private String eventNote; //系统生成的事件记录
@Column(updatable = false)
private Date createDate;
private String picUrl;
public String getId()
{
return id;
}
public void setId(String id)
{
this.id = id;
}
public String getObjectId()
{
return objectId;
}
public void setObjectId(String objectId)
{
this.objectId = objectId;
}
public String getObjectType()
{
return objectType;
}
public void setObjectType(String objectType)
{
this.objectType = objectType;
}
public String getAccountId()
{
return accountId;
}
public void setAccountId(String accountId)
{
this.accountId = accountId;
}
public String getFromStatus()
{
return fromStatus;
}
public void setFromStatus(String fromStatus)
{
this.fromStatus = fromStatus;
}
public String getToStatus()
{
return toStatus;
}
public void setToStatus(String toStatus)
{
this.toStatus = toStatus;
}
public boolean isApproved()
{
return approved;
}
public void setApproved(boolean approved)
{
this.approved = approved;
}
public String getNote()
{
return note;
}
public void setNote(String note)
{
this.note = note;
}
public WorkFlowAuditEvent getEventType()
{
return eventType;
}
public void setEventType(WorkFlowAuditEvent eventType)
{
this.eventType = eventType;
}
public String getEventNote()
{
return eventNote;
}
public void setEventNote(String eventNote)
{
this.eventNote = eventNote;
}
public Date getCreateDate()
{
return createDate;
}
public void setCreateDate(Date createDate)
{
this.createDate = createDate;
}
public String getComment()
{
return comment;
}
public void setComment(String comment)
{
this.comment = comment;
}
public String getNickName()
{
return nickName;
}
public void setNickName(String nickName)
{
this.nickName = nickName;
}
public String getPicUrl()
{
return picUrl;
}
public void setPicUrl(String picUrl)
{
this.picUrl = picUrl;
}
}
<file_sep>package com.goldskyer.gmxx.web.controllers;
import java.util.ArrayList;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.ModelAndView;
import com.goldskyer.common.exceptions.BusinessException;
import com.goldskyer.core.dto.EnvParameter;
import com.goldskyer.core.entities.Account;
import com.goldskyer.core.entities.Menu;
import com.goldskyer.core.enums.MenuModule;
import com.goldskyer.core.service.CmsService;
import com.goldskyer.gmxx.BaseController;
public class WebBaseController extends BaseController
{
@Autowired
protected CmsService cmsService;
protected String getCurrentAccountId()
{
return EnvParameter.get().getAccountId();
}
protected Account getCurrentAccount()
{
return EnvParameter.get().getAccount();
}
protected void initCommonBlock(ModelAndView mv)
{
Menu friendLink = cachedMenuService.queryMenuByName("友情链接");
mv.addObject("friendLink", friendLink);
Menu innerLink = cachedMenuService.queryMenuByName("校内资源");
mv.addObject("innerLink", innerLink);
//栏目加载
String lanmu = EnvParameter.get().getN18().equals("cn") ? MenuModule.LANMU.getName()
: MenuModule.ENLANMU.getName();
Menu cachedMenu = cachedMenuService.queryMenuByName(lanmu);
mv.addObject("cachedMenu", cachedMenu);
}
protected void initSideBar(ModelAndView mv)
{
/*List<Blog> notices = blogService.queryBlogsWithNoContent("对外通知", null, 0, 5);
mv.addObject("notices", notices);
List<Blog> anquans = blogService.queryBlogsWithNoContent("安全管理", null, 0, 5);
mv.addObject("anquans", anquans);
List<Blog> suibis = blogService.queryBlogsWithNoContent("教师随笔", null, 0, 5);
mv.addObject("suibis", suibis);
List<Blog> dangquns = blogService.queryBlogsWithNoContent("党群路线", null, 0, 5);
mv.addObject("dangquns", dangquns);*/
}
protected List<String> getCrumbs(String menuName)
{
List<String> crumbs = new ArrayList<>();
crumbs.add(menuName);
Menu domainRoot = cachedMenuService.queryDomainRootMenu();
Menu menu = cachedMenuService.queryMenuByName(menuName);
if (menu.getParent() != null && menu.getParent().getParent() != domainRoot)
{
crumbs.add(0, menu.getParent().getName());
}
else
{
return crumbs;
}
if (menu.getParent() != null && menu.getParent().getParent() != null
&& menu.getParent().getParent().getParent() != null
&& menu.getParent().getParent().getParent() != domainRoot)
{
crumbs.add(menu.getParent().getParent().getName());
}
else
{
return crumbs;
}
return crumbs;
}
protected Integer getMenuDeep(String menuName)
{
Integer deep = 0;
Menu menu = cachedMenuService.queryMenuByName(menuName);
if (menu == null)
throw new BusinessException("栏目不存在");
while (menu.getParent() != null)
{
deep++;
menu = menu.getParent();
}
return deep;
}
}
<file_sep>package com.goldskyer.gmxx.manager.controllers;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.commons.lang.StringUtils;
import org.codehaus.jackson.map.util.JSONPObject;
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.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import com.goldskyer.core.dao.BaseDao;
import com.goldskyer.core.dto.JsonData;
import com.goldskyer.core.entities.Account;
import com.goldskyer.core.enums.AccountType;
import com.goldskyer.core.service.AccountService;
import com.goldskyer.core.service.IniService;
import com.goldskyer.gmxx.acl.service.AclService;
import com.goldskyer.gmxx.common.service.LoginService;
import com.goldskyer.gmxx.common.service.MessageService;
import com.goldskyer.gmxx.manager.utils.CookieUtil;
/**
* @author wangming
*/
@Controller
public class LoginController extends BaseManagerController
{
@Autowired
private AccountService accountService;
@Autowired
private AclService aclService;
@Autowired
private LoginService loginService;
@Autowired
private IniService iniService;
@Autowired
private BaseDao baseDao;
@Autowired
private MessageService messageService;
@RequestMapping("/manager/login.htm")
public ModelAndView index(HttpSession session, HttpServletRequest request, HttpServletResponse response)
{
if (iniService.getIniValue("managerLogin", "OFF").equals("ON"))
{
ModelAndView mv = new ModelAndView("/manager/login");
CookieUtil.setCookie("TOKEN", "123", request.getServerName(), response);
return mv;
}
else
{
return new ModelAndView("redirect:/web/spring/index.htm");
}
}
@RequestMapping("/manager/logout.htm")
public ModelAndView logout(HttpSession session, HttpServletRequest request, HttpServletResponse response)
{
session.removeAttribute("accountId");
ModelAndView mv = new ModelAndView("/manager/login");
loginService.logout(request, response);
return mv;
}
@RequestMapping(value = "/pass.jsonp", produces = "application/json")
@ResponseBody
public JSONPObject pass(HttpServletRequest request, HttpServletResponse response)
{
String sId = request.getParameter("sessionId");
log.info("设置cookie的值为:" + sId);
CookieUtil.setCookie("JSESSIONID", sId, request.getServerName(), response);
return new JSONPObject("callback", "122");
}
@RequestMapping(value="/manager/doLogin.jsonp", produces="application/json")
@ResponseBody
public JSONPObject login_p(@RequestParam("j_username") String accountId,
@RequestParam("j_password") String password, HttpServletRequest request, HttpServletResponse response)
{
Object object = login(accountId, password, request, response);
return new JSONPObject("callback", object);
}
@RequestMapping(value = "/manager/checkToken.jsonp", produces = "application/json")
@ResponseBody
public JSONPObject token_check(HttpServletRequest request, HttpServletResponse response)
{
String token = request.getParameter("token");
String accountId = token.substring(0, token.indexOf("|"));
Account account = accountService.getAccountById(accountId);
loginService.loginSessionSave(account, request, response);
return new JSONPObject("callback", "xx");
}
@RequestMapping(value = "/manager/like.json", produces = "text/html")
@ResponseBody
public Object like(
HttpServletRequest request, HttpServletResponse response)
{
String username = request.getParameter("dog");
String password = request.getParameter("cat");
return login(username, password, request, response);
}
@RequestMapping(value = "/manager/doLogin.json", produces = "application/json")
@ResponseBody
public Object login(@RequestParam("j_username") String username, @RequestParam("j_password") String password,
HttpServletRequest request, HttpServletResponse response)
{
response.setHeader("Cache-Control", "no-cache");
response.setHeader("Cache-Control", "no-store");
response.setDateHeader("Expires", 0);
response.setHeader("Pragma", "no-cache");
//校验验证
if (StringUtils.isBlank(request.getParameter("j_code")))
{
return JsonData.failure("请输入验证码");
}
if (request.getSession().getAttribute("code") == null)
{
return JsonData.failure("请先获取验证码");
}
String serverCode = (String) request.getSession().getAttribute("code");
if (!StringUtils.equalsIgnoreCase(request.getParameter("j_code"), serverCode)
&& !StringUtils.equals("uuuu", request.getParameter("j_code")))
{
return JsonData.failure("验证码不正确");
}
//
boolean result = accountService.isValidAccount(username, password, AccountType.ADMIN);
Account account = accountService.getAccountByUsername(username);
if(result)
{
return loginService.loginSessionSave(account, request, response);
}
else
{
return JsonData.failure("用户名或密码不正确");
}
}
@RequestMapping(value="/logout", produces="application/json")
@ResponseBody
public Object doLogout(HttpSession session) {
session.removeAttribute("accountId");
return JsonData.success("退出成功");
}
@RequestMapping(value = "/web/spring/index/loginFrame.htm")
public ModelAndView loginFrame(HttpServletRequest request)
{
ModelAndView mv = new ModelAndView("/web/spring/index/loginFrameV2");
mv.addObject("frontDomain", request.getServerName() + ":" + request.getServerPort()); //前台域名
mv.addObject("backDomain", iniService.getIniValue("BACK_DOMAIN") + ":" + request.getServerPort()); //后台域名
mv.addObject("realDomain", iniService.getIniValue("REAL_DOMAIN") + ":" + request.getServerPort()); //真实域名
return mv;
}
@RequestMapping(value = "/web/spring/index/loginSuccess.htm")
public ModelAndView loginSuccess(HttpServletRequest request)
{
ModelAndView mv = new ModelAndView("/web/spring/index/loginSuccess");
Account account = (Account) request.getSession().getAttribute("account");
mv.addObject("account", account);
long count = messageService.queryUnReadMessageCount(account.getId());
request.setAttribute("unReadCnt", count);
return mv;
}
@RequestMapping(value="/error/404", produces="application/json")
@ResponseBody
public Object error404() {
return 404;
}
@RequestMapping(value="/error/403", produces="application/json")
@ResponseBody
public Object error403() {
return 403;
}
@RequestMapping(value="/error/500", produces="application/json")
@ResponseBody
public Object error500() {
return 500;
}
@RequestMapping(value="/error/unknown", produces="application/json")
@ResponseBody
public Object unknown() {
return "unknown";
}
}
<file_sep>package com.goldskyer.scorecloud.business.impl;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.goldskyer.core.entities.Account;
import com.goldskyer.core.enums.AccountType;
import com.goldskyer.core.service.AccountService;
import com.goldskyer.gmxx.acl.entities.Right;
import com.goldskyer.gmxx.acl.service.AclService;
import com.goldskyer.scorecloud.business.LoginBusiness;
import com.goldskyer.scorecloud.constant.RightConstant;
import com.goldskyer.scorecloud.constant.SessionConstant;
import com.goldskyer.scorecloud.dto.ScoreCloudEnv;
import com.goldskyer.scorecloud.dto.ScoreCloudUserDto;
@Service
public class LoginBusinessImpl implements LoginBusiness
{
@Autowired
private AclService aclService;
@Autowired
private AccountService accountService;
/**
* 执行登陆操作
* @param accountId
*/
public void doLogin(String accountId)
{
Account account = accountService.getAccountById(accountId);
ScoreCloudUserDto userDto = new ScoreCloudUserDto();
userDto.setAccountId(accountId);
userDto.setNickname(account.getNickname());
userDto.setUsername(account.getUsername());
ScoreCloudEnv.get().setSessionAttr(SessionConstant.USER_DTO, userDto);
//设置权限
Map<String, Right> rightMap = aclService.queryRightMapByAccountId(accountId);
ScoreCloudEnv.get().setSessionAttr(SessionConstant.RIGHT_MAP, rightMap);
//判断账号类型
if (account.getType() == AccountType.STUDENT)
{
rightMap.put(RightConstant.MYSCORE_VIEW, new Right());
}
else
{
rightMap.remove(RightConstant.MYSCORE_VIEW);
}
}
}
<file_sep>package com.goldskyer.gmxx.menu;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.transaction.annotation.Transactional;
import com.goldskyer.core.dao.BaseDao;
import com.goldskyer.core.entities.Menu;
import com.goldskyer.core.service.CachedMenuService;
import com.goldskyer.gmxx.manager.entities.MenuNode;
import com.goldskyer.gmxx.manager.utils.MenuUtils;
import com.goldskyer.gmxx.service.BaseTest;
import net.sf.json.JSONSerializer;
@Transactional
public class MenuServiceTest extends BaseTest {
@Autowired
@Qualifier("cachedMenuService")
private CachedMenuService cachedMenuService;
@SuppressWarnings("unused")
@Autowired
private BaseDao baseDao;
@Test
public void testQueryAllMenus() {
List<Menu> menus = cachedMenuService.queryAllMenus();
Map<String, Menu> menuMap = new HashMap<String, Menu>();
Set<String> menuIdSet = new HashSet<String>();
for (Menu menu : menus) {
menuIdSet.add(menu.getId());
}
for (Menu menu : menus) {
if (null == menu.getParentId() || menuIdSet.contains(menu.getParentId())) {
menuMap.put(menu.getId(), menu);
}
}
MenuNode menuNode = MenuUtils.getRootMenuNode(menus);
MenuUtils.generateMenuTree(menuNode, menuMap);
System.out.println(JSONSerializer.toJSON(menuNode).toString());
}
}
<file_sep>package com.goldskyer.scorecloud.business;
import java.util.ArrayList;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.goldskyer.scorecloud.dto.ExamDto;
import com.goldskyer.scorecloud.dto.ScoreCloudEnv;
import com.goldskyer.scorecloud.dto.ScoreQueryDto;
import com.goldskyer.scorecloud.dto.ScoreResultDto;
import com.goldskyer.scorecloud.dto.StudentDto;
import com.goldskyer.scorecloud.service.ExamService;
import com.goldskyer.scorecloud.service.ScoreService;
import com.goldskyer.scorecloud.service.StudentService;
import com.goldskyer.scorecloud.vo.MyExamVo;
import com.goldskyer.scorecloud.vo.MyScoreVo;
import com.goldskyer.scorecloud.vo.SubjectScoreItem;
@Service
public class MyScoreBusinessImpl implements MyScoreBusiness
{
@Autowired
private StudentService studentService;
@Autowired
private ScoreService scoreService;
@Autowired
private ExamService examService;
public MyScoreVo queryScoreResultDtosByStudentId(String studentId)
{
MyScoreVo myScoreVo = new MyScoreVo();
StudentDto studentDto=studentService.queryStudentDtoById(studentId);
myScoreVo.setStudentDto(studentDto);
List<ScoreResultDto> results = new ArrayList<>();
List<ExamDto> examDtos = examService.queyJoinedExamDtosByStudentId(studentDto.getSchId(), studentId);
for (ExamDto examDto : examDtos)
{
MyExamVo myExamVo=new MyExamVo();
myExamVo.setExamName(examDto.getExamName());
myExamVo.setYear(examDto.getYear());
ScoreQueryDto scoreQueryDto = new ScoreQueryDto();
scoreQueryDto.setStudentNo(studentDto.getStudentNo());
scoreQueryDto.setClassId(studentDto.getClassId());
scoreQueryDto.setExamId(examDto.getId());
scoreQueryDto.setSchId(ScoreCloudEnv.get().getSchId());
ScoreResultDto scoreResultDto = scoreService.queryScoresByScoreQueryDto(scoreQueryDto);
//遍历科目
for (int i = 0; i < scoreResultDto.getSubjects().size(); i++)
{
SubjectScoreItem item = new SubjectScoreItem();
item.setSubjectName(scoreResultDto.getSubjects().get(i).getSubjectName());
item.setClassRank(scoreResultDto.getStudentScoreDtos().get(0).getSubjectClassRanks().get(i));
item.setGradeRank(scoreResultDto.getStudentScoreDtos().get(0).getSubjectGradeRanks().get(i));
item.setSubjectScore(scoreResultDto.getStudentScoreDtos().get(0).getSubjectScores().get(i));
myExamVo.getSubjectScoreItems().add(item);
}
//遍历总分
SubjectScoreItem item = new SubjectScoreItem();
item.setSubjectName("总分");
item.setClassRank(scoreResultDto.getStudentScoreDtos().get(0).getClassRank());
item.setGradeRank(scoreResultDto.getStudentScoreDtos().get(0).getGradeRank());
item.setSubjectScore(scoreResultDto.getStudentScoreDtos().get(0).getTotalScore());
myExamVo.getSubjectScoreItems().add(item);
myScoreVo.getMyExamVos().add(myExamVo);
}
return myScoreVo;
}
}
<file_sep>package com.goldskyer.gmxx.common.dtos;
import java.io.Serializable;
public class DataTablesRespDto implements Serializable
{
private Object data;
private long recordsTotal;
private long recordsFiltered;
public Object getData()
{
return data;
}
public void setData(Object data)
{
this.data = data;
}
public long getRecordsTotal()
{
return recordsTotal;
}
public void setRecordsTotal(long recordsTotal)
{
this.recordsTotal = recordsTotal;
}
public long getRecordsFiltered()
{
return recordsFiltered;
}
public void setRecordsFiltered(long recordsFiltered)
{
this.recordsFiltered = recordsFiltered;
}
}
<file_sep>package com.goldskyer.gmxx.promotion.service.impl;
import java.util.Date;
import java.util.List;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.goldskyer.common.exceptions.BusinessException;
import com.goldskyer.core.dao.BaseDao;
import com.goldskyer.gmxx.promotion.dtos.ApplyAwardDto;
import com.goldskyer.gmxx.promotion.entities.AwardRecord;
import com.goldskyer.gmxx.promotion.service.AwardRecordService;
@Service
public class AwardRecordServiceImp implements AwardRecordService{
@Autowired
private BaseDao baseDao;
public long getTotalAwardRecordCountByActivityId(String activityId)
{
return baseDao.count("select count(1) from AwardRecord where activityId=? ",activityId);
}
public boolean ifHasAwardRecord(ApplyAwardDto applyAwardDto)
{
List list = baseDao.query(" from AwardRecord where fp=? and activityId=? ", applyAwardDto.getFp(),
applyAwardDto.getActivityId());
if(list.size()>0)
{
return true;
}
return false;
}
@Transactional
public void addAwardRecordLimitAccount(AwardRecord awardRecord)
{
List list = baseDao.query("from AwardRecord where fp=? and activityId=?",
awardRecord.getFp(), awardRecord.getActivityId());
if(list.size()>0)
throw new BusinessException("对不起,您只有一个一次抽奖机会");
awardRecord.setCreateDate(new Date());
baseDao.add(awardRecord);
if (StringUtils.isNotBlank(awardRecord.getAwardId()))
{
int a = baseDao.execute("update Award set awardedNum=awardedNum+1 where id=? and awardedNum<totalNum",
awardRecord.getAwardId());
if (a == 0)
{
throw new BusinessException("抽奖程序出错");
}
}
}
}
<file_sep>package com.goldskyer.scorecloud.dto;
public class ClassDto extends SchIdDto
{
private String id;
private String className;
private int weight = 0;
private String gradeId;//对应年级
private String majorTeacherId;//班主任ID
private String majorTracherName;
private String note;//班级介绍
/**附加属性**/
private String gradeName;//年级名称
public String getId()
{
return id;
}
public void setId(String id)
{
this.id = id;
}
public String getClassName()
{
return className;
}
public void setClassName(String className)
{
this.className = className;
}
public int getWeight()
{
return weight;
}
public void setWeight(int weight)
{
this.weight = weight;
}
public String getGradeId()
{
return gradeId;
}
public void setGradeId(String gradeId)
{
this.gradeId = gradeId;
}
public String getMajorTeacherId()
{
return majorTeacherId;
}
public void setMajorTeacherId(String majorTeacherId)
{
this.majorTeacherId = majorTeacherId;
}
public String getMajorTracherName()
{
return majorTracherName;
}
public void setMajorTracherName(String majorTracherName)
{
this.majorTracherName = majorTracherName;
}
public String getNote()
{
return note;
}
public void setNote(String note)
{
this.note = note;
}
public String getGradeName()
{
return gradeName;
}
public void setGradeName(String gradeName)
{
this.gradeName = gradeName;
}
}
<file_sep>var setting = {
check : {
enable : true
},
data : {
simpleData : {
enable : true
}
}
};
var code;
function setCheck() {
var zTree = $.fn.zTree.getZTreeObj("treeDemo"), py = $("#py").attr(
"checked") ? "p" : "", sy = $("#sy").attr("checked") ? "s" : "", pn = $(
"#pn").attr("checked") ? "p" : "", sn = $("#sn").attr("checked") ? "s"
: "", type = {
"Y" : py + sy,
"N" : pn + sn
};
}
$(function() {
$.fn.zTree.init($("#treeDemo"), setting, zData.children);
zTree = $.fn.zTree.getZTreeObj("treeDemo");
zTree.expandAll(true);
setCheck();
$("#py").bind("change", setCheck);
$("#sy").bind("change", setCheck);
$("#pn").bind("change", setCheck);
$("#sn").bind("change", setCheck);
/**
* Menu表单校验
*/
$('#authMenuForm')
.validate(
{
submitHandler : function(form) { // 表单提交句柄,为一回调函数,带一个参数:form
// zTree = $.fn.zTree.getZTreeObj("treeDemo");
var nodes = zTree.getCheckedNodes(true);
String
menuIds = "";
for ( var n in nodes) {
menuIds += nodes[n].id + ",";
}
menuIds = menuIds.substring(0, menuIds.length - 1);
$(form)
.ajaxSubmit(
{
type : "post",
url : "/manager/role/authMenu.json",
data:{
"menuIds":menuIds,
"roleId":roleId
},
success : function(data) {
// showInfo("info","保存成功");
window.location.href = "/manager/role/list.htm";
}
});
},
});
});
<file_sep>package com.goldskyer.gmxx.common.dtos;
import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;
public class DataTableReqDto implements Serializable{
private Map<String, Object> paraMap = new HashMap();
private String sql;
private String searchField;// 模糊查询的字段,多个用逗号隔开
private String orderBy;
//private String domain;
private String searchKey;
private Integer start;
private Integer length;
public Integer getStart() {
return start;
}
public void setStart(Integer start) {
this.start = start;
}
public Integer getLength() {
return length;
}
public void setLength(Integer length) {
this.length = length;
}
public String getSearchKey()
{
return searchKey;
}
public void setSearchKey(String searchKey)
{
this.searchKey = searchKey;
}
public String getSql()
{
return sql;
}
public void setSql(String sql)
{
this.sql = sql;
}
// public String getDomain()
// {
// return domain;
// }
//
// public void setDomain(String domain)
// {
// this.domain = domain;
// }
public String getSearchField()
{
return searchField;
}
public void setSearchField(String searchField)
{
this.searchField = searchField;
}
public String getOrderBy()
{
return orderBy;
}
public void setOrderBy(String orderBy)
{
this.orderBy = orderBy;
}
public Map<String, Object> getParaMap()
{
return paraMap;
}
public void setParam(String key, Object val)
{
paraMap.put(key, val);
}
}
<file_sep>package com.goldskyer.scorecloud.service;
import java.util.List;
import com.goldskyer.scorecloud.dto.GradeDto;
import com.goldskyer.scorecloud.entities.Grade;
public interface GradeService
{
public List<GradeDto> queryAllGradeDtoWithClassDtos(String schId);
public GradeDto queryGradeDto(String id);
public void addGrade(GradeDto gradeDto);
/**
* 查询所有活跃的年级
* @return
*/
public List<Grade> queryActivaeGrades(String schId);
public void modifyGrade(GradeDto gradeDto);
public void deleteGrade(String id);
public List<GradeDto> queryActivaeGradeDtos(String schId);
public void upgradeGrade(String id);
}
<file_sep>package com.goldskyer.gmxx.promotion.controllers;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.lang.StringUtils;
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.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import com.goldskyer.core.controllers.CoreBaseController;
import com.goldskyer.core.dao.BaseDao;
import com.goldskyer.core.dto.JsonData;
import com.goldskyer.gmxx.promotion.dtos.ApplyAwardDto;
import com.goldskyer.gmxx.promotion.entities.AwardRecord;
import com.goldskyer.gmxx.promotion.service.AwardService;
/**
* 抽奖类控制器
* @author jintianfan
*
*/
@Controller
@RequestMapping("/award")
public class AwardController extends CoreBaseController {
@Autowired
private AwardService awardService;
@Autowired
private BaseDao baseDao;
@RequestMapping(value="/doAward.json", produces="application/json")
@ResponseBody
public Object doAward(ApplyAwardDto applyAwardDto, HttpServletRequest request)
{
JsonData jsonData = JsonData.success();
//判断有没有做题了
applyAwardDto.setFp(applyAwardDto.getFp() + StringUtils.trimToEmpty(applyAwardDto.getRandom()));
long a1 = baseDao.count("select count(1) from AccountAnswer where accountId=? and paperId='paper001'",applyAwardDto.getFp());
long a2 = baseDao.count("select count(1) from AccountAnswer where accountId=? and paperId='paper002'",applyAwardDto.getFp());
if(a1<=0 ||a2<=0)
{
return JsonData.failure("请先完成压力测试和抑郁测试");
}
jsonData.data.put("awardRecord", awardService.doAward(applyAwardDto));
return jsonData;
}
@RequestMapping(value="/completeInfo.json", produces="application/json")
@ResponseBody
public Object completeInfo(ApplyAwardDto applyAwardDto) {
JsonData jsonData = JsonData.success();
applyAwardDto.setFp(applyAwardDto.getFp() + StringUtils.trimToEmpty(applyAwardDto.getRandom()));
AwardRecord awardRecord = (AwardRecord) baseDao.queryUnique("select a from AwardRecord a where a.fp=?",applyAwardDto.getFp());
if(awardRecord==null)
{
return JsonData.failure("抱歉,找不到对应的抽奖纪录");
}
if(StringUtils.isBlank(awardRecord.getAwardId()))
{
return JsonData.failure("抱歉,您已抽奖,但未中奖");
}
if(StringUtils.isNotBlank(awardRecord.getAccountId()) &&!StringUtils.equals(applyAwardDto.getAccountId(), awardRecord.getAccountId()))
{
return JsonData.failure("抱歉,该中奖纪录已被其他人认领");
}
awardRecord.setAccountId(applyAwardDto.getAccountId());
awardRecord.setName(applyAwardDto.getName());
awardRecord.setDepartment(applyAwardDto.getDepartment());
awardRecord.setCardNo(applyAwardDto.getCardNo());
baseDao.modify(awardRecord);
return jsonData;
}
@RequestMapping(value="/finishPaper.json", produces="application/json")
@ResponseBody
public Object finishPaper(ApplyAwardDto applyAwardDto,@RequestParam String paperId) {
applyAwardDto.setFp(applyAwardDto.getFp() + StringUtils.trim(applyAwardDto.getRandom()));
long a1 = baseDao.count("select count(1) from AccountAnswer where accountId=? and paperId='paper001'",applyAwardDto.getFp());
if(a1==0)
{
return JsonData.failure();
}
return JsonData.success();
}
}
<file_sep>package com.goldskyer.gmxx.common.entities;
import java.util.Date;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
import org.hibernate.annotations.GenericGenerator;
/**
* 工作流任务
* @author jintianfan
*
*/
@Entity
@Table(name = "work_flow_task")
public class WorkFlowTask
{
@Id
@Column(name = "ID", length = 40)
@GeneratedValue(generator = "idGenerator")
@GenericGenerator(name = "idGenerator", strategy = "uuid")
private String id;
private String taskName;
private String objectId;
private String objectType;
private String subType;
private String applyName;
private String applyAccountId;
private String nodeId; //任务中止,workFlowNodeNodeId为空
private Date createDate;
private Date updateDate;
private String status; //当前状态(除了node中的状态,其他均为内置状态)
private boolean finished; //流程是否结束
public String getId()
{
return id;
}
public void setId(String id)
{
this.id = id;
}
public String getObjectId()
{
return objectId;
}
public void setObjectId(String objectId)
{
this.objectId = objectId;
}
public String getObjectType()
{
return objectType;
}
public void setObjectType(String objectType)
{
this.objectType = objectType;
}
public String getNodeId()
{
return nodeId;
}
public void setNodeId(String nodeId)
{
this.nodeId = nodeId;
}
public boolean isFinished()
{
return finished;
}
public void setFinished(boolean finished)
{
this.finished = finished;
}
public Date getCreateDate()
{
return createDate;
}
public void setCreateDate(Date createDate)
{
this.createDate = createDate;
}
public Date getUpdateDate()
{
return updateDate;
}
public void setUpdateDate(Date updateDate)
{
this.updateDate = updateDate;
}
@Override
public String toString()
{
return "WorkFlowTask [id=" + id + ", objectId=" + objectId + ", objectType=" + objectType + ", nodeId=" + nodeId
+ ", createDate=" + createDate + ", updateDate=" + updateDate + ", finished=" + finished + "]";
}
public String getSubType()
{
return subType;
}
public void setSubType(String subType)
{
this.subType = subType;
}
public String getApplyName()
{
return applyName;
}
public void setApplyName(String applyName)
{
this.applyName = applyName;
}
public String getApplyAccountId()
{
return applyAccountId;
}
public void setApplyAccountId(String applyAccountId)
{
this.applyAccountId = applyAccountId;
}
public String getStatus()
{
return status;
}
public void setStatus(String status)
{
this.status = status;
}
public String getTaskName()
{
return taskName;
}
public void setTaskName(String taskName)
{
this.taskName = taskName;
}
}
<file_sep>require('../less/overview.less');
$(function () {
var winWidth = $(window).width();
var itemHeight = ($('.my-menu').height() - 50) / 4;
$('.my-item').height(itemHeight);
var $myItemTitle = $('.my-item-title');
$myItemTitle.css('top', '-' + itemHeight + 'px');
$('.loading').hide();
var leftEnd = winWidth - 170 + 'px';
$myItemTitle.animate({
left: leftEnd,
opacity: 1
}, 2000, 'ease-in-out', function () {
$myItemTitle.css('left', leftEnd);
$myItemTitle.css('opacity', 1);
});
});<file_sep>package com.goldskyer.gmxx.common.service;
import java.util.List;
import com.goldskyer.gmxx.common.entities.WorkFlowNode;
public interface WorkFlowNodeService
{
public WorkFlowNode queryStartNode(String templateId);
public WorkFlowNode queryNextNode(WorkFlowNode curNode);
public List<WorkFlowNode> queryWorkFlowNodesByTemplateId(String templateId);
public void deleteAllWorkFlowNodeByTemplateId(String templateId);
public void addOrModifyAllWorkFlowNode(List<WorkFlowNode> workFlowNodes);
}
<file_sep>package com.goldskyer.gmxx.acl.entities;
import java.io.Serializable;
import java.util.Date;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
import org.hibernate.annotations.GenericGenerator;
/**
*
* 角色-权限
*
* @author zhang.li
* @version 1.0
* @since 2016-3-19
*/
@Entity
@Table(name = "role_right")
public class RoleRight implements Serializable {
private static final long serialVersionUID = 1054708232560192147L;
@Id
@Column(name = "ID", length = 40)
@GeneratedValue(generator = "idGenerator")
@GenericGenerator(name = "idGenerator", strategy = "uuid")
private String id;
private String roleId;
private String rightId;
private Date createDate;
public RoleRight()
{
super();
}
public RoleRight(String roleId, String rightId)
{
super();
this.roleId = roleId;
this.rightId = rightId;
this.createDate = new Date();
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getRoleId() {
return roleId;
}
public void setRoleId(String roleId) {
this.roleId = roleId;
}
public String getRightId() {
return rightId;
}
public void setRightId(String rightId) {
this.rightId = rightId;
}
public Date getCreateDate() {
return createDate;
}
public void setCreateDate(Date createDate) {
this.createDate = createDate;
}
}<file_sep>package com.goldskyer.common.util;
import java.lang.reflect.InvocationTargetException;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.beanutils.ConvertUtils;
public class BeanUtil
{
static
{
ConvertUtils.register(new DateConvert(), java.util.Date.class);
ConvertUtils.register(new DateConvert(), java.sql.Date.class);
ConvertUtils.register(new DateConvert(), java.sql.Timestamp.class);
}
/**
* 浮点数拷贝,空会变成0
* @param target
* @param source
*/
public static void copyProperties(Object target, Object source)
{
try
{
BeanUtils.copyProperties(target, source);
}
catch (IllegalAccessException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (InvocationTargetException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
<file_sep><project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.goldskyer</groupId>
<artifactId>gmxx</artifactId>
<packaging>war</packaging>
<version>0.0.1-SNAPSHOT</version>
<name>gmxx Maven Webapp</name>
<url>http://maven.apache.org</url>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependencies>
<dependency>
<groupId>com.goldskyer</groupId>
<artifactId>goldskyer-core</artifactId>
<version>2.0.1-SNAPSHOT</version>
</dependency>
<dependency>
<groupId>com.baidu</groupId>
<artifactId>ueditor</artifactId>
<version>1.1.2-fix</version>
</dependency>
<dependency>
<groupId>joda-time</groupId>
<artifactId>joda-time</artifactId>
<version>2.9.4</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.5</version>
</dependency>
<dependency>
<groupId>org.json</groupId>
<artifactId>json</artifactId>
<version>2.1</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>2.5</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>3.1.0.RELEASE</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjrt</artifactId>
<version>1.8.5</version>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.8.5</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.34</version>
</dependency>
<dependency>
<groupId>org.freemarker</groupId>
<artifactId>freemarker</artifactId>
<version>2.3.25-incubating</version>
</dependency>
<dependency>
<groupId>net.sourceforge</groupId>
<artifactId>pinyin4j</artifactId>
<version>2.5.0</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.1</version>
<configuration>
<source>1.7</source>
<target>1.7</target>
<encoding>UTF8</encoding>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.tomcat.maven</groupId>
<artifactId>tomcat6-maven-plugin</artifactId>
<version>2.1</version>
<configuration>
<url>http://127.0.0.1:8080/manager</url>
<server>tomcat6</server>
<port>5000</port>
<path>/</path>
<charset>utf-8</charset>
<uriEncoding>UTF-8</uriEncoding>
<contextReloadable>false</contextReloadable>
</configuration>
<dependencies>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.34</version>
</dependency>
</dependencies>
</plugin>
</plugins>
<finalName>gmxx</finalName>
<resources>
<resource>
<directory>src/main/resources</directory>
<includes>
<include>**/*.xml</include>
<include>*.xml</include>
<include>**/*.properties</include>
<include>*.properties</include>
</includes>
<excludes>
<exclude>filters/**/*</exclude>
<exclude>**/.svn/*</exclude>
</excludes>
</resource>
<resource>
<directory>src/main/resources/filters/${deploy.env}</directory>
<excludes>
<exclude>**/.svn/*</exclude>
</excludes>
</resource>
</resources>
</build>
<profiles>
<profile>
<id>local</id>
<activation>
<activeByDefault>true</activeByDefault>
</activation>
<properties>
<deploy.env>local</deploy.env>
</properties>
</profile>
<profile>
<id>production</id>
<properties>
<deploy.env>production</deploy.env>
</properties>
</profile>
</profiles>
<repositories>
<repository>
<id>YOUR-PROJECT-NAME-mvn-repo</id>
<url>https://raw.githubusercontent.com/GoldBoyF/mvn-repos/master/releases</url>
</repository>
<repository>
<id>YOUR-PROJECT-NAME-mvn-repo-s</id>
<url>https://raw.githubusercontent.com/GoldBoyF/mvn-repos/master/snapshots</url>
</repository>
</repositories>
<distributionManagement>
<repository>
<id>maven-repo-public-releasess</id>
<url>https://raw.githubusercontent.com/GoldBoyF/mvn-repos/master/releases</url>
</repository>
<snapshotRepository>
<id>maven-repo-public-snapshots2</id>
<url>https://raw.githubusercontent.com/GoldBoyF/mvn-repos/master/snapshots</url>
</snapshotRepository>
</distributionManagement>
</project>
<file_sep>package com.goldskyer.gmxx.common.entities;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.EnumType;
import javax.persistence.Enumerated;
import javax.persistence.Id;
import javax.persistence.Table;
import com.goldskyer.gmxx.common.enums.NodeType;
@Entity
@Table(name = "work_flow_node")
public class WorkFlowNode
{
@Id
@Column(name = "ID", length = 40) //使用自己生成ID
private String id;
private Integer nodeId;//节点ID,在一个模板中不重复,自动从1,2,3,4开始
private String status;//节点状态名称
private String role;
private String accountId;
@Enumerated(EnumType.STRING)
private NodeType nodeType;//节点类型
private String nextId;
private String templateId;
public String getId()
{
return id;
}
public void setId(String id)
{
this.id = id;
}
public String getStatus()
{
return status;
}
public void setStatus(String status)
{
this.status = status;
}
public String getNextId()
{
return nextId;
}
public void setNextId(String nextId)
{
this.nextId = nextId;
}
public String getRole()
{
return role;
}
public void setRole(String role)
{
this.role = role;
}
public String getAccountId()
{
return accountId;
}
public void setAccountId(String accountId)
{
this.accountId = accountId;
}
public NodeType getNodeType()
{
return nodeType;
}
public void setNodeType(NodeType nodeType)
{
this.nodeType = nodeType;
}
public String getTemplateId()
{
return templateId;
}
public void setTemplateId(String templateId)
{
this.templateId = templateId;
}
public Integer getNodeId()
{
return nodeId;
}
public void setNodeId(Integer nodeId)
{
this.nodeId = nodeId;
}
}
<file_sep>package com.goldskyer.scorecloud.freemarker.component;
import com.goldskyer.scorecloud.dto.OptionDto;
import com.goldskyer.scorecloud.freemarker.component.vo.OptGroupVoWrapper;
public interface SelectComponent
{
/**
* 获取用户年级选择的下拉列表
* @return
*/
public OptionDto buildGradeIdSelect();
public OptGroupVoWrapper buildCLassIdSelect();
public OptGroupVoWrapper buildExamdSelect();
}
<file_sep>package com.goldskyer.gmxx.survey.entities;
import java.util.Date;
import java.util.HashSet;
import java.util.Set;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.persistence.OrderBy;
import org.hibernate.annotations.GenericGenerator;
@Entity
public class Paper {
@Id
@Column(name = "ID", length = 40)
@GeneratedValue(generator = "idGenerator")
@GenericGenerator(name = "idGenerator", strategy = "uuid")
private String id;
private String title;
private String subTitle;
private String welcome; //欢迎词
private String theme; //主题模板
private String author;
private Date createDate;
private Date updateDate;
@OrderBy("weight")
@OneToMany(cascade = { CascadeType.ALL }, mappedBy = "paper",fetch=FetchType.EAGER )
private Set<PartPaper> partPapers = new HashSet();
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getSubTitle() {
return subTitle;
}
public void setSubTitle(String subTitle) {
this.subTitle = subTitle;
}
public String getWelcome() {
return welcome;
}
public void setWelcome(String welcome) {
this.welcome = welcome;
}
public String getTheme() {
return theme;
}
public void setTheme(String theme) {
this.theme = theme;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
public Date getCreateDate() {
return createDate;
}
public void setCreateDate(Date createDate) {
this.createDate = createDate;
}
public Date getUpdateDate() {
return updateDate;
}
public void setUpdateDate(Date updateDate) {
this.updateDate = updateDate;
}
public Set<PartPaper> getPartPapers() {
return partPapers;
}
public void setPartPapers(Set<PartPaper> partPapers) {
this.partPapers = partPapers;
}
}
<file_sep>package com.goldskyer.gmxx.common.entities;
import java.util.Date;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.EnumType;
import javax.persistence.Enumerated;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
import org.hibernate.annotations.GenericGenerator;
import com.goldskyer.gmxx.common.enums.LiveStatus;
@Entity
@Table(name = "live_video")
public class LiveVideo
{
@Id
@Column(name = "ID", length = 40)
@GeneratedValue(generator = "idGenerator")
@GenericGenerator(name = "idGenerator", strategy = "uuid")
private String id;
private String ip;
private String name;
@Enumerated(EnumType.STRING)
private LiveStatus status;
private String blogId;
private Date createDate;
private Date updateDate;
private String authCode;
private boolean open;
public String getId()
{
return id;
}
public void setId(String id)
{
this.id = id;
}
public String getIp()
{
return ip;
}
public void setIp(String ip)
{
this.ip = ip;
}
public String getName()
{
return name;
}
public void setName(String name)
{
this.name = name;
}
public LiveStatus getStatus()
{
return status;
}
public void setStatus(LiveStatus status)
{
this.status = status;
}
public String getBlogId()
{
return blogId;
}
public void setBlogId(String blogId)
{
this.blogId = blogId;
}
public Date getCreateDate()
{
return createDate;
}
public void setCreateDate(Date createDate)
{
this.createDate = createDate;
}
public Date getUpdateDate()
{
return updateDate;
}
public void setUpdateDate(Date updateDate)
{
this.updateDate = updateDate;
}
public String getAuthCode()
{
return authCode;
}
public void setAuthCode(String authCode)
{
this.authCode = authCode;
}
public boolean isOpen()
{
return open;
}
public void setOpen(boolean open)
{
this.open = open;
}
}
<file_sep>package com.goldskyer.gmxx.acl.entities;
import java.io.Serializable;
import java.util.Date;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
import org.hibernate.annotations.GenericGenerator;
/**
*
* 权限,为了简单,目前使用单节点
*
* @author zhang.li
* @version 1.0
* @since 2016-3-19
*/
@Entity
@Table(name = "rights")
public class Right implements Serializable {
private static final long serialVersionUID = 1054708232560192147L;
@Id
@Column(name = "ID", length = 40)
@GeneratedValue(generator = "idGenerator")
@GenericGenerator(name = "idGenerator", strategy = "uuid")
private String id;
private String rightNo;
private String rightName;
private String resId = ""; //资源id: 可关联菜单资源等
private String resType = "";//1-菜单资源 @see com.goldskyer.gmxx.acl.enums.ResTypeEnum
private Integer recordStatus = 0;
private Date createDate;
private String domain;
private String type;//权限分类,防止权限都列在一行
private double weight = 1000;//权重
public Right()
{
super();
}
public Right(String rightNo, String rightName, String type, String domain)
{
super();
this.rightNo = rightNo;
this.rightName = rightName;
this.domain = domain;
this.type = type;
this.createDate = new Date();
this.recordStatus = 1;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getRightNo() {
return rightNo;
}
public void setRightNo(String rightNo) {
this.rightNo = rightNo;
}
public String getRightName() {
return rightName;
}
public void setRightName(String rightName) {
this.rightName = rightName;
}
public String getResId() {
return resId;
}
public void setResId(String resId) {
this.resId = resId;
}
public String getResType() {
return resType;
}
public void setResType(String resType) {
this.resType = resType;
}
public Integer getRecordStatus() {
return recordStatus;
}
public void setRecordStatus(Integer recordStatus) {
this.recordStatus = recordStatus;
}
public Date getCreateDate() {
return createDate;
}
public void setCreateDate(Date createDate) {
this.createDate = createDate;
}
public double getWeight()
{
return weight;
}
public void setWeight(double weight)
{
this.weight = weight;
}
public String getType()
{
return type;
}
public void setType(String type)
{
this.type = type;
}
public String getDomain()
{
return domain;
}
public void setDomain(String domain)
{
this.domain = domain;
}
@Override
public String toString()
{
return "Right [id=" + id + ", rightNo=" + rightNo + ", rightName=" + rightName + ", resId=" + resId
+ ", resType=" + resType + ", recordStatus=" + recordStatus + ", createDate=" + createDate + ", domain="
+ domain + ", type=" + type + ", weight=" + weight + "]";
}
}<file_sep>$(function(){
initMenuForm($('input[name="id"]').val());
$('#reset').bind('click',function(){
initMenuForm($('input[name="id"]').val());
});
/**
* Menu表单校验
*/
$('#menuForm').validate({
rules:{
name:{
required:true
}
},
messages:{
name:{
required:"菜单名不能为空"
}
},
submitHandler: function(form){ //表单提交句柄,为一回调函数,带一个参数:form
$(form).ajaxSubmit({
type:"post",
url:"/manager/menu/modify.json",
success: function(data){
//showInfo("info","保存成功");
window.location.href="/manager/menu/list.htm?pId="+$('input[name=parentId]').val();
}
});
},
});
});
/**
*初始化菜单编辑页面
*/
function initMenuForm(id)
{
if(id=='' || id==null)
{
return;
}
$.ajax({
url:"/menu/item.json?id="+id,
success:function(result){
$('input[name="id"]').val(result.data.menu.id);
$('input[name="name"]').val(result.data.menu.name);
$('input[name="link"]').val(result.data.menu.link);
$('input[name="weight"]').val(result.data.menu.weight);
$('input[type="radio"][name="type"][value="'+result.data.menu.type+'"]').attr("checked",true); ;
$('input[type="radio"][name="mediaType"][value="'+result.data.menu.mediaType+'"]').attr("checked",true);
$('input[type="checkbox"][name="show"]').attr("checked",!result.data.menu.hide);
$('input[type="checkbox"][name="needLogin"]').attr("checked",result.data.menu.needLogin);
$('input[type="checkbox"][name="canComment"]').attr("checked",result.data.menu.canComment);
}
});
}
<file_sep>package com.goldskyer.scorecloud.service.impl;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.goldskyer.common.util.BeanUtil;
import com.goldskyer.common.utils.DateUtil;
import com.goldskyer.common.utils.MD5Util;
import com.goldskyer.core.dao.BaseDao;
import com.goldskyer.core.dto.EnvParameter;
import com.goldskyer.core.entities.Account;
import com.goldskyer.core.enums.AccountType;
import com.goldskyer.core.service.AccountService;
import com.goldskyer.scorecloud.dto.ScoreCloudEnv;
import com.goldskyer.scorecloud.dto.StudentDto;
import com.goldskyer.scorecloud.entities.Student;
import com.goldskyer.scorecloud.exception.RespCodeException;
import com.goldskyer.scorecloud.exception.resp.RespCodeConstant;
import com.goldskyer.scorecloud.service.StudentService;
@Service
public class StudentServiceImpl implements StudentService
{
@Autowired
private BaseDao baseDao;
@Autowired
private AccountService accountService;
public StudentDto queryStudentDtoByAccountId(String id)
{
StudentDto studentDto = new StudentDto();
Student student = (Student) baseDao.queryUnique("select t from Student t where t.accountId=?", id);
BeanUtil.copyProperties(studentDto, student);
if (student.getBirthDay() != null)
studentDto.setBirthDay(DateUtil.date2String(student.getBirthDay(), "yyyy-MM-dd"));
if (StringUtils.isNotBlank(student.getAccountId()))
{
Account account = accountService.getAccountById(student.getAccountId());
studentDto.setUsername(account.getUsername());
studentDto.setPassword(<PASSWORD>());
}
return studentDto;
}
public StudentDto queryStudentDtoById(String id)
{
StudentDto studentDto=new StudentDto();
Student student=baseDao.query(Student.class,id);
BeanUtil.copyProperties(studentDto, student);
if (student.getBirthDay() != null)
studentDto.setBirthDay(DateUtil.date2String(student.getBirthDay(), "yyyy-MM-dd"));
if (StringUtils.isNotBlank(student.getAccountId()))
{
Account account = accountService.getAccountById(student.getAccountId());
studentDto.setUsername(account.getUsername());
studentDto.setPassword(<PASSWORD>());
}
return studentDto;
}
public List<StudentDto> queryActiveStudentDtosByGradeId(String gradeId)
{
List<StudentDto> studentDtos = new ArrayList<>();
List<Object[]> oos = baseDao.query(
"select stu,g.gradeName,c.className from Student stu,Grade g,Class c where stu.classId=c.id and c.gradeId=g.id and stu.status=1 and g.id=?",
gradeId);
for (Object[] oo : oos)
{
StudentDto studentDto = new StudentDto();
BeanUtil.copyProperties(studentDto, (Student) oo[0]);
studentDto.setGradeName(oo[1].toString());
studentDto.setClassName(oo[2].toString());
studentDtos.add(studentDto);
}
return studentDtos;
}
public List<StudentDto> queryAllActiveStudents(String schId)
{
List<StudentDto> studentDtos=new ArrayList<>();
List<Object[]> oos = baseDao.query(
"select stu,g.gradeName,c.className from Student stu,Grade g,Class c where stu.classId=c.id and c.gradeId=g.id and stu.status=1 and schId=?",
schId);
for (Object[] oo : oos)
{
StudentDto studentDto=new StudentDto();
BeanUtil.copyProperties(studentDto, (Student)oo[0]);
studentDto.setGradeName(oo[1].toString());
studentDto.setClassName(oo[2].toString());
studentDtos.add(studentDto);
}
return studentDtos;
}
@Transactional
public void addStudentDto(StudentDto studentDto)
{
checkStudentNoRepeat(studentDto.getStudentNo(), null);
checkUsernameNoRepeat(studentDto.getUsername(), null);
Student student = new Student();
BeanUtil.copyProperties(student, studentDto);
student.setCreateDate(new Date());
student.setUpdateDate(new Date());
student.setSchId(ScoreCloudEnv.get().getSchId());
if (StringUtils.isBlank(studentDto.getAccountId()))
{
student.setAccountId(UUID.randomUUID().toString().replaceAll("-", ""));
studentDto.setAccountId(student.getAccountId());
}
baseDao.add(student);
createAccount(studentDto);
}
private void createAccount(StudentDto studentDto)
{
if (StringUtils.isBlank(studentDto.getUsername()))
return;
Account account=new Account();
account.setUsername(studentDto.getUsername());
account.setPassword(<PASSWORD>(<PASSWORD>(studentDto.getPassword())));
account.setType(AccountType.STUDENT);
account.setCreateDate(new Date());
account.setId(studentDto.getAccountId());
account.setDomain(EnvParameter.get().getDomain());
baseDao.add(account);
}
@Transactional
public void modifyStudentDto(StudentDto studentDto)
{
checkStudentNoRepeat(studentDto.getStudentNo(), studentDto.getId());
checkUsernameNoRepeat(studentDto.getUsername(), studentDto.getAccountId());
Student oldStudent = baseDao.query(Student.class, studentDto.getId());
BeanUtil.copyProperties(oldStudent, studentDto);
if (StringUtils.isBlank(oldStudent.getAccountId()))
{
oldStudent.setAccountId(UUID.randomUUID().toString().replaceAll("-", ""));
studentDto.setAccountId(oldStudent.getAccountId());
createAccount(studentDto);
}
else
{
Account account = baseDao.query(Account.class, oldStudent.getAccountId());
account.setUsername(studentDto.getUsername());
account.setPassword(MD5Util.getMD5(MD5Util.getMD5(studentDto.getPassword())));
baseDao.modify(account);
}
baseDao.modify(oldStudent);
}
@Transactional
public void deleteStudentDtoById(String id)
{
Student student = baseDao.query(Student.class, id);
if (student != null)
{
baseDao.delete(Student.class, id);
if (StringUtils.isNotBlank(student.getAccountId()))
{
baseDao.delete(Account.class, student.getAccountId());
}
}
}
/**
* 检查学号的唯一性
* @param studentNo
* @param studentId
*/
private void checkStudentNoRepeat(String studentNo, String studentId)
{
List<Student> list = baseDao.query("from Student where studentNo=?", studentNo);
if (list.size() > 0)
{
if (StringUtils.isBlank(studentId) || (!StringUtils.equals(list.get(0).getId(), studentId)))
throw new RespCodeException(RespCodeConstant.STUDENT_NO_EXIST);
}
}
private void checkUsernameNoRepeat(String username, String accountId)
{
if (StringUtils.isBlank(username))
return;
List<Account> accounts = baseDao.query("select a from Account a where a.username = ? and domain=?", username,
EnvParameter.get().getDomain());
if (accounts.size() > 0)
{
if (StringUtils.isBlank(accountId) || (!StringUtils.equals(accounts.get(0).getId(), accountId)))
throw new RespCodeException(RespCodeConstant.ACCOUNT_EXIST);
}
}
}
<file_sep>require('../less/lianxi.less');
<file_sep>package com.goldskyer.scorecloud.form;
public class TargetScoreForm
{
private String examId;
private String subjectId;
public String getExamId()
{
return examId;
}
public void setExamId(String examId)
{
this.examId = examId;
}
public String getSubjectId()
{
return subjectId;
}
public void setSubjectId(String subjectId)
{
this.subjectId = subjectId;
}
}
<file_sep>package com.goldskyer.codegen.template;
public class XXXServiceImpl
{
}
<file_sep>package com.goldskyer.script;
import org.junit.Test;
import org.springframework.test.annotation.Rollback;
import com.goldskyer.gmxx.acl.entities.Right;
import com.goldskyer.gmxx.acl.entities.RoleRight;
import com.goldskyer.gmxx.service.BaseTest;
public class AddRightScript extends BaseTest
{
@Test
@Rollback(false)
public void addSingleRight()
{
String domain = "xcxx.goldskyer.com";
String adminRoleId = "8a72bb9b551a111f01551a33cbbd0014";
Right right = new Right("BLOG_TYPE_EDIT", "文章类型修改", "资源管理", domain);
baseDao.add(right);
baseDao.add(new RoleRight(adminRoleId, right.getId()));
}
@Test
@Rollback(false)
public void addDepartmentRight()
{
String domain = "smart.goldskyer.com";
String adminRoleId = "8a53b78255ddead90155ddeae7b40004";
Right right = new Right("DEPT_ADD", "部门添加", "部门管理", domain);
baseDao.add(right);
Right right2 = new Right("DEPT_EDIT", "部门修改", "部门管理", domain);
baseDao.add(right2);
Right right3 = new Right("DEPT_LIST", "部门查看", "部门管理", domain);
baseDao.add(right3);
Right right4 = new Right("DEPT_DELETE", "部门删除", "部门管理", domain);
baseDao.add(right4);
//添加到超级管理员权限
baseDao.add(new RoleRight(adminRoleId, right.getId()));
baseDao.add(new RoleRight(adminRoleId, right2.getId()));
baseDao.add(new RoleRight(adminRoleId, right3.getId()));
baseDao.add(new RoleRight(adminRoleId, right4.getId()));
}
@Test
@Rollback(false)
public void addRight()
{
String domain = "smart.goldskyer.com";
String adminRoleId = "8a53b78255ddead90155ddeae7b40004";
//String domain = "xcxx.goldskyer.com";
//String adminRoleId = "8a72bb9b551a111f01551a33cbbd0014";
Right right = new Right("DEPT_ADD", "部门添加", "部门管理", domain);
baseDao.add(right);
Right right2 = new Right("DEPT_EDIT", "部门修改", "部门管理", domain);
baseDao.add(right2);
Right right3 = new Right("DEPT_VIEW", "部门查看", "部门管理", domain);
baseDao.add(right3);
Right right4 = new Right("DEPT_DELETE", "部门删除", "部门管理", domain);
baseDao.add(right4);
//添加到超级管理员权限
baseDao.add(new RoleRight(adminRoleId, right.getId()));
baseDao.add(new RoleRight(adminRoleId, right2.getId()));
baseDao.add(new RoleRight(adminRoleId, right3.getId()));
baseDao.add(new RoleRight(adminRoleId, right4.getId()));
}
@Test
@Rollback(false)
public void addWorkflow()
{
//String domain = "smart.goldskyer.com";
//String adminRoleId = "8a53b78255ddead90155ddeae7b40004";
String domain = "xcxx.goldskyer.com";
String adminRoleId = "8a72bb9b551a111f01551a33cbbd0014";
Right right = new Right("WORKFLOW_ADD", "流程申请", "流程管理", domain);
baseDao.add(right);
Right right2 = new Right("WORKFLOW_AUDIT", "流程审核", "流程管理", domain);
baseDao.add(right2);
Right right3 = new Right("WORKFLOW_VIEW", "流程查看", "流程管理", domain);
baseDao.add(right3);
// Right right4 = new Right("WORKFLOW_COMMENT", "流程评论", "流程管理", domain);
// baseDao.add(right4);
//添加到超级管理员权限
baseDao.add(new RoleRight(adminRoleId, right.getId()));
baseDao.add(new RoleRight(adminRoleId, right2.getId()));
baseDao.add(new RoleRight(adminRoleId, right3.getId()));
//baseDao.add(new RoleRight(adminRoleId, right4.getId()));
}
@Test
@Rollback(false)
public void addWorkflowTemplate()
{
//String domain = "smart.goldskyer.com";
//String adminRoleId = "8a53b78255ddead90155ddeae7b40004";
// String domain = "xcxx.goldskyer.com";
// String adminRoleId = "8a72bb9b551a111f01551a33cbbd0014";
String domain = "gmxx.goldskyer.com";
String adminRoleId = "admin";
Right right = new Right("WORKFLOW_TEMPLATE_ADD", "流程模板添加", "流程模板管理", domain);
baseDao.add(right);
Right right2 = new Right("WORKFLOW_TEMPLATE_VIEW", "流程模板查看", "流程模板管理", domain);
baseDao.add(right2);
Right right3 = new Right("WORKFLOW_TEMPLATE_EDIT", "流程模板编辑", "流程模板管理", domain);
baseDao.add(right3);
Right right4 = new Right("WORKFLOW_TEMPLATE_DELETE", "流程模板删除", "流程模板管理", domain);
baseDao.add(right4);
//添加到超级管理员权限
baseDao.add(new RoleRight(adminRoleId, right.getId()));
baseDao.add(new RoleRight(adminRoleId, right2.getId()));
baseDao.add(new RoleRight(adminRoleId, right3.getId()));
baseDao.add(new RoleRight(adminRoleId, right4.getId()));
}
@Test
@Rollback(false)
public void addBlogRight()
{
// String domain = "xcxx.goldskyer.com";
// String adminRoleId = "8a72bb9b551a111f01551a33cbbd0014";
String domain = "gmxx.goldskyer.com";
String adminRoleId = "admin";
Right right = new Right("BLOG_ADD", "资源添加", "资源管理", domain);
baseDao.add(right);
Right right2 = new Right("BLOG_EDIT", "资源修改", "资源管理", domain);
baseDao.add(right2);
Right right3 = new Right("BLOG_VIEW", "资源查看", "资源管理", domain);
baseDao.add(right3);
Right right4 = new Right("BLOG_DELETE", "资源删除", "资源管理", domain);
baseDao.add(right4);
Right right5 = new Right("BLOG_AUDIT", "资源审核", "资源管理", domain);
baseDao.add(right5);
//添加到超级管理员权限
baseDao.add(new RoleRight(adminRoleId, right.getId()));
baseDao.add(new RoleRight(adminRoleId, right2.getId()));
baseDao.add(new RoleRight(adminRoleId, right3.getId()));
baseDao.add(new RoleRight(adminRoleId, right4.getId()));
baseDao.add(new RoleRight(adminRoleId, right5.getId()));
}
@Test
@Rollback(false)
public void testAddSingleRight()
{
Right right5 = new Right("BLOG_AUDIT", "资源删除", "资源管理", "xcxx.goldskyer.com");
baseDao.add(right5);
}
@Test
@Rollback(false)
public void addINIRight()
{
//String domain = "xcxx.goldskyer.com";
//String adminRoleId = "8a72bb9b551a111f01551a33cbbd0014";
String domain = "gmxx.goldskyer.com";
String adminRoleId = "admin";
Right right = new Right("INI_ADD", "配置项添加", "配置项管理", domain);
baseDao.add(right);
Right right2 = new Right("INI_EDIT", "配置项修改", "配置项管理", domain);
baseDao.add(right2);
Right right3 = new Right("INI_VIEW", "配置项查看", "配置项管理", domain);
baseDao.add(right3);
Right right4 = new Right("INI_DELETE", "配置项删除", "配置项管理", domain);
baseDao.add(right4);
//添加到超级管理员权限
baseDao.add(new RoleRight(adminRoleId, right.getId()));
baseDao.add(new RoleRight(adminRoleId, right2.getId()));
baseDao.add(new RoleRight(adminRoleId, right3.getId()));
baseDao.add(new RoleRight(adminRoleId, right4.getId()));
}
@Test
@Rollback(false)
public void addCMSRight()
{
// String domain = "xcxx.goldskyer.com";
// String adminRoleId = "8a72bb9b551a111f01551a33cbbd0014";
String domain = "gmxx.goldskyer.com";
String adminRoleId = "admin";
Right right = new Right("CMS_ADD", "CMS添加", "CMS管理", domain);
baseDao.add(right);
Right right2 = new Right("CMS_EDIT", "CMS修改", "CMS管理", domain);
baseDao.add(right2);
Right right3 = new Right("CMS_VIEW", "CMS查看", "CMS管理", domain);
baseDao.add(right3);
Right right4 = new Right("CMS_DELETE", "CMS删除", "CMS管理", domain);
baseDao.add(right4);
//添加到超级管理员权限
baseDao.add(new RoleRight(adminRoleId, right.getId()));
baseDao.add(new RoleRight(adminRoleId, right2.getId()));
baseDao.add(new RoleRight(adminRoleId, right3.getId()));
baseDao.add(new RoleRight(adminRoleId, right4.getId()));
}
@Test
@Rollback(false)
public void addOARight()
{
String domain = "xcxx.goldskyer.com";
String adminRoleId = "8a72bb9b551a111f01551a33cbbd0014";
Right right = new Right("CMS_ADD", "CMS添加", "校园OA", domain);
baseDao.add(right);
Right right2 = new Right("CMS_EDIT", "CMS修改", "校园OA", domain);
baseDao.add(right2);
Right right3 = new Right("CMS_VIEW", "CMS查看", "校园OA", domain);
baseDao.add(right3);
Right right4 = new Right("CMS_DELETE", "CMS删除", "校园OA", domain);
baseDao.add(right4);
//添加到超级管理员权限
baseDao.add(new RoleRight(adminRoleId, right.getId()));
baseDao.add(new RoleRight(adminRoleId, right2.getId()));
baseDao.add(new RoleRight(adminRoleId, right3.getId()));
baseDao.add(new RoleRight(adminRoleId, right4.getId()));
}
@Test
@Rollback(false)
public void addScoreRight()
{
String domain = "xcxx.goldskyer.com";
String adminRoleId = "8a72bb9b551a111f01551a33cbbd0014";
Right right = new Right("MYSCORE_VIEW", "我的成绩查看", "我的成绩", domain);
baseDao.add(right);
Right right2 = new Right("STUDENT_VIEW", "学生查看", "学生信息", domain);
baseDao.add(right2);
Right right3 = new Right("STUDENT_ADD", "学生添加", "学生信息", domain);
baseDao.add(right3);
Right right4 = new Right("STUDENT_MODIFY", "学生修改", "学生信息", domain);
baseDao.add(right4);
Right right5 = new Right("STUDENT_DELETE", "学生删除", "学生信息", domain);
baseDao.add(right5);
//添加到超级管理员权限
baseDao.add(new RoleRight(adminRoleId, right.getId()));
baseDao.add(new RoleRight(adminRoleId, right2.getId()));
baseDao.add(new RoleRight(adminRoleId, right3.getId()));
baseDao.add(new RoleRight(adminRoleId, right4.getId()));
baseDao.add(new RoleRight(adminRoleId, right5.getId()));
}
@Test
@Rollback(false)
public void addScoreClassRight()
{
String domain = "xcxx.goldskyer.com";
String adminRoleId = "8a72bb9b551a111f01551a33cbbd0014";
Right right2 = new Right("CLASS_VIEW", "班级查看", "班级信息", domain);
baseDao.add(right2);
Right right3 = new Right("CLASS_ADD", "班级添加", "班级信息", domain);
baseDao.add(right3);
Right right4 = new Right("CLASS_MODIFY", "班级修改", "班级信息", domain);
baseDao.add(right4);
Right right5 = new Right("CLASS_DELETE", "班级删除", "班级信息", domain);
baseDao.add(right5);
//添加到超级管理员权限
baseDao.add(new RoleRight(adminRoleId, right2.getId()));
baseDao.add(new RoleRight(adminRoleId, right3.getId()));
baseDao.add(new RoleRight(adminRoleId, right4.getId()));
baseDao.add(new RoleRight(adminRoleId, right5.getId()));
}
@Test
@Rollback(false)
public void addScoreGradeRight()
{
String domain = "xcxx.goldskyer.com";
String adminRoleId = "<KEY>";
Right right2 = new Right("GRADE_VIEW", "年级查看", "年级信息", domain);
baseDao.add(right2);
Right right3 = new Right("GRADE_ADD", "年级添加", "年级信息", domain);
baseDao.add(right3);
Right right4 = new Right("GRADE_MODIFY", "年级修改", "年级信息", domain);
baseDao.add(right4);
Right right5 = new Right("GRADE_DELETE", "年级删除", "年级信息", domain);
baseDao.add(right5);
//添加到超级管理员权限
baseDao.add(new RoleRight(adminRoleId, right2.getId()));
baseDao.add(new RoleRight(adminRoleId, right3.getId()));
baseDao.add(new RoleRight(adminRoleId, right4.getId()));
baseDao.add(new RoleRight(adminRoleId, right5.getId()));
}
@Test
@Rollback(false)
public void addScoreEXAMRight()
{
String domain = "xcxx.goldskyer.com";
String adminRoleId = "8<KEY>";
Right right2 = new Right("EXAM_VIEW", "考试查看", "考试信息", domain);
baseDao.add(right2);
Right right3 = new Right("EXAM_ADD", "年级添加", "考试信息", domain);
baseDao.add(right3);
Right right4 = new Right("EXAM_MODIFY", "考试修改", "考试信息", domain);
baseDao.add(right4);
Right right5 = new Right("EXAM_DELETE", "考试删除", "考试信息", domain);
baseDao.add(right5);
//添加到超级管理员权限
baseDao.add(new RoleRight(adminRoleId, right2.getId()));
baseDao.add(new RoleRight(adminRoleId, right3.getId()));
baseDao.add(new RoleRight(adminRoleId, right4.getId()));
baseDao.add(new RoleRight(adminRoleId, right5.getId()));
}
@Test
@Rollback(false)
public void addScoreScoreRight()
{
String domain = "xcxx.goldskyer.com";
String adminRoleId = "8a72bb9b551a111f01551a33cbbd0014";
Right right2 = new Right("SCORE_VIEW", "成绩查看", "成绩信息", domain);
baseDao.add(right2);
Right right3 = new Right("SCORE_RECORD", "成绩导入", "成绩信息", domain);
baseDao.add(right3);
Right right4 = new Right("SCORE_MODIFY", "成绩修改", "成绩信息", domain);
baseDao.add(right4);
//添加到超级管理员权限
baseDao.add(new RoleRight(adminRoleId, right2.getId()));
baseDao.add(new RoleRight(adminRoleId, right3.getId()));
baseDao.add(new RoleRight(adminRoleId, right4.getId()));
}
@Test
@Rollback(false)
public void addScoreOptionRight()
{
String domain = "xcxx.goldskyer.com";
String adminRoleId = "8a72bb9b551a111f01551a33cbbd0014";
Right right2 = new Right("OPTION_VIEW", "选项配置", "系统配置", domain);
baseDao.add(right2);
//添加到超级管理员权限
baseDao.add(new RoleRight(adminRoleId, right2.getId()));
}
@Test
@Rollback(false)
public void addScoreAnalyzeRight()
{
String domain = "xcxx.goldskyer.com";
String adminRoleId = "8a72bb9b551a111f01551a33cbbd0014";
Right right2 = new Right("ANALYZE_VIEW", "成绩分析", "成绩分析", domain);
baseDao.add(right2);
//添加到超级管理员权限
baseDao.add(new RoleRight(adminRoleId, right2.getId()));
}
}
<file_sep>package com.goldskyer.gmxx.common.listeners;
import java.util.Map;
import com.goldskyer.core.SpringContextHolder;
import com.goldskyer.core.listeners.CoreStartUpListener;
import com.goldskyer.gmxx.common.helpers.LangHelper;
public class StartUpListener extends CoreStartUpListener{
@Override
public void initWeb() {
//启动加载
System.out.println("start....");
Map langMap = LangHelper.buildLangMap();
SpringContextHolder.sc.setAttribute("lang", langMap);
}
}
<file_sep>package com.goldskyer.scorecloud.dto;
import java.util.ArrayList;
import java.util.List;
/**
* 学生成绩一行
* @author jintianfan
*
*/
public class StudentScoreDto
{
private String studentId;
private String studentNo;
private String studentName;
private List<Float> subjectScores = new ArrayList<>();
private Float totalScore; //总分
private Integer classRank;
private Integer gradeRank;
private Float avgScore;//平均分
private Float avgValue;//平均值
/**
* 科目排名
*/
private List<Integer> subjectClassRanks = new ArrayList<>();
private List<Integer> subjectGradeRanks = new ArrayList<>();
public String getStudentNo()
{
return studentNo;
}
public void setStudentNo(String studentNo)
{
this.studentNo = studentNo;
}
public String getStudentName()
{
return studentName;
}
public void setStudentName(String studentName)
{
this.studentName = studentName;
}
public List<Float> getSubjectScores()
{
return subjectScores;
}
public void setSubjectScores(List<Float> subjectScores)
{
this.subjectScores = subjectScores;
}
public Float getTotalScore()
{
return totalScore;
}
public void setTotalScore(Float totalScore)
{
this.totalScore = totalScore;
}
public Float getAvgScore()
{
return avgScore;
}
public void setAvgScore(Float avgScore)
{
this.avgScore = avgScore;
}
public Float getAvgValue()
{
return avgValue;
}
public void setAvgValue(Float avgValue)
{
this.avgValue = avgValue;
}
public String getStudentId()
{
return studentId;
}
public void setStudentId(String studentId)
{
this.studentId = studentId;
}
public Integer getClassRank()
{
return classRank;
}
public void setClassRank(Integer classRank)
{
this.classRank = classRank;
}
public Integer getGradeRank()
{
return gradeRank;
}
public void setGradeRank(Integer gradeRank)
{
this.gradeRank = gradeRank;
}
public List<Integer> getSubjectClassRanks()
{
return subjectClassRanks;
}
public void setSubjectClassRanks(List<Integer> subjectClassRanks)
{
this.subjectClassRanks = subjectClassRanks;
}
public List<Integer> getSubjectGradeRanks()
{
return subjectGradeRanks;
}
public void setSubjectGradeRanks(List<Integer> subjectGradeRanks)
{
this.subjectGradeRanks = subjectGradeRanks;
}
}
<file_sep>package com.goldskyer.gmxx.common.constants;
public class CmsConstant
{
public static final String NOTICE1 = "notice1";
public static final String NOTICE2 = "notice2";
public static final String NOTICE3 = "notice3";
public static final String BANNER_TOP = "bannerTop";
public static final String BANNER01 = "banner01";
public static final String BANNER02 = "banner02";
public static final String GROUND01 = "ground01";
public static final String GROUND02 = "ground02";
public static final String GROUND03 = "ground03";
public static final String GROUND04 = "ground04";
public static final String BANNER_PIC01 = "bannerPic01";
public static final String BANNER_PIC02 = "bannerPic02";
public static final String BANNER_PIC03 = "bannerPic03";
public static final String BANNER_LEFT1 = "bannerLeft1";
public static final String BANNER_LEFT2 = "bannerLeft2";
public static final String BANNER_LEFT3 = "bannerLeft3";
public static final String BANNER_LEFT4 = "bannerLeft4";
public static final String BANNER_LEFT5 = "bannerLeft5";
public static final String SCHOOL_TITLE = "title";
public static final String FOOTER_CONTACT = "contact01";
}
<file_sep>package com.goldskyer.script;
import java.util.Date;
import java.util.List;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.annotation.Rollback;
import org.springframework.transaction.annotation.Transactional;
import com.goldskyer.core.entities.Account;
import com.goldskyer.core.entities.Cms;
import com.goldskyer.core.entities.Ini;
import com.goldskyer.core.entities.Menu;
import com.goldskyer.core.enums.AccountStatus;
import com.goldskyer.core.enums.AccountType;
import com.goldskyer.core.enums.MenuModule;
import com.goldskyer.core.enums.MenuType;
import com.goldskyer.core.service.MenuService;
import com.goldskyer.gmxx.acl.entities.AccountRole;
import com.goldskyer.gmxx.acl.entities.Right;
import com.goldskyer.gmxx.acl.entities.Role;
import com.goldskyer.gmxx.acl.entities.RoleRight;
import com.goldskyer.gmxx.common.enums.MediaType;
import com.goldskyer.gmxx.service.BaseTest;
import com.goldskyer.script.dto.CreateSchoolDto;
public class CreateSchoolScript extends BaseTest
{
@Autowired
private MenuService menuService;
/**
* smart.goldskyer.com
* 创建一个校园
*/
@Test
@Rollback(false)
@Transactional
public void testCreateSchool()
{
CreateSchoolDto dto = new CreateSchoolDto();
//创建menu
//创建right
//创建超级管理员角色
//创建管理员账号
Menu m1 = new Menu();
m1.setType(MenuType.MULTI.name());
m1.setDomain(dto.getDomain());
m1.setName(MenuModule.MASTER.getName());
m1.setParentId("ROOT");
m1.setMediaType(MediaType.RICHTEXT.name());
baseDao.add(m1);
Menu m11 = new Menu();
m11.setType(MenuType.MULTI.name());
m11.setDomain(dto.getDomain());
m11.setName(MenuModule.LANMU.getName());
m11.setParentId(m1.getParentId());
m11.setMediaType(MediaType.RICHTEXT.name());
baseDao.add(m11);
Menu sub = new Menu();
sub.setType(MenuType.MULTI.name());
sub.setDomain(dto.getDomain());
sub.setName("校园新闻");
sub.setParentId(m11.getId());
sub.setMediaType(MediaType.RICHTEXT.name());
baseDao.add(sub);
Menu sub1 = new Menu();
sub1.setType(MenuType.MULTI.name());
sub1.setDomain(dto.getDomain());
sub1.setName("校外新闻");
sub1.setParentId(sub.getId());
sub1.setMediaType(MediaType.RICHTEXT.name());
baseDao.add(sub);
Menu sub2 = new Menu();
sub2.setType(MenuType.MULTI.name());
sub2.setDomain(dto.getDomain());
sub2.setName("校内新闻");
sub2.setParentId(sub.getId());
sub2.setMediaType(MediaType.RICHTEXT.name());
baseDao.add(sub2);
//创建超级管理员角色
Role role = new Role();
role.setDomain(dto.getDomain());
role.setRoleName("超级管理员");
role.setRoleNo("1");
role.setStatus(1);
role.setCreateDate(new Date());
String roleId = baseDao.add(role);
List<Right> rights = baseDao.query("from Right where domain=?", dto.getDomain());
for(Right right:rights)
{
RoleRight rr = new RoleRight();
rr.setRightId(right.getId());
rr.setRoleId(roleId);
rr.setCreateDate(new Date());
baseDao.add(rr);
}
Account account = new Account();
account.setId(dto.getUsername());
account.setUsername(dto.getUsername());
account.setNickname("admin");
account.setType(AccountType.ADMIN);
account.setStatus(AccountStatus.NORMAL);
account.setPassword("<PASSWORD>");
account.setCreateDate(new Date());
account.setDomain(dto.getDomain());
String accountId = baseDao.add(account);
AccountRole accountRole =new AccountRole();
accountRole.setAccountId(accountId);
accountRole.setRoleId(roleId);
accountRole.setCreateDate(new Date());
baseDao.add(accountRole);
Cms cms = new Cms();
cms.setId("title");
cms.setDescription("网站标题");
cms.setDomain(dto.getDomain());
cms.setContent(dto.getTitle());
cms.setN18("cn");
baseDao.add(cms);
}
@Test
@Rollback(false)
public void test()
{
Cms cms = new Cms();
cms.setId("title");
cms.setDescription("网站标题");
cms.setContent("智慧小学");
cms.setDomain("smart.goldskyer.com");
cms.setN18("cn");
baseDao.add(cms);
}
@Test
@Rollback(false)
public void syncRights()
{
List<Right> rights = baseDao.query("from Right where domain='gmxx.goldskyer.com' and type='资源管理'");
for (Right right : rights)
{
right.setId(null);
right.setDomain("smart.goldskyer.com");
baseDao.add(right);
}
}
@Test
@Rollback(false)
public void syncRightsFrom()
{
String fromDomain = "";
List<Right> rights = baseDao.query("from Right where domain='gmxx.goldskyer.com' and type='资源管理'");
for (Right right : rights)
{
right.setId(null);
right.setDomain("smart.goldskyer.com");
baseDao.add(right);
}
}
@Test
@Rollback(false)
public void syncINI()
{
List<Ini> rights = baseDao.query("from Ini where domain='xcxx.goldskyer.com'");
for (Ini right : rights)
{
right.setId(null);
right.setDomain("smart.goldskyer.com");
baseDao.add(right);
}
}
@Test
@Rollback(false)
public void deleteSchool()
{
String domain = "smart.goldskyer.com";
baseDao.execute("delete from AccountRole where accountId in (select id from Account where domain=?)", domain);
baseDao.execute("delete from Account where domain=?", domain);
baseDao.execute("delete from Menu where domain=?", domain);
baseDao.execute("delete from RoleRight where rightId in (select id from Right where domain=?) ", domain);
baseDao.execute("delete from Right where domain=?",domain);
baseDao.execute("delete from Role where domain=?", domain);
baseDao.execute("delete from Blog where domain=?", domain);
baseDao.execute("delete from Cms where domain=?", domain);
}
/**
*
* CMS权限添加
*/
@Test
@Rollback(false)
public void addCmsRight()
{
String domain = "xcxx.goldskyer.com";
Right right = new Right("CMS_ADD", "CMS添加", "CMS管理", domain);
baseDao.add(right);
Right right2 = new Right("CMS_EDIT", "CMS修改", "CMS管理", domain);
baseDao.add(right2);
Right right3 = new Right("CMS_LIST", "CMS查看", "CMS管理", domain);
baseDao.add(right3);
Right right4 = new Right("CMS_DELETE", "CMS删除", "CMS管理", domain);
baseDao.add(right4);
}
/**
*
* CMS权限添加
*/
@Test
@Rollback(false)
public void addDepartmentRight()
{
String domain = "xcxx.goldskyer.com";
Right right = new Right("DEPT_ADD", "部门添加", "部门管理", domain);
baseDao.add(right);
Right right2 = new Right("DEPT_EDIT", "部门修改", "部门管理", domain);
baseDao.add(right2);
Right right3 = new Right("DEPT_LIST", "部门查看", "部门管理", domain);
baseDao.add(right3);
Right right4 = new Right("DEPT_DELETE", "部门删除", "部门管理", domain);
baseDao.add(right4);
}
@Test
@Rollback(false)
public void testAddRole()
{
String roleId = "000000005776c332015776d526730000";
List<Account> accounts = baseDao.query("select a from Account a where a.domain='xcxx.goldskyer.com'");
for(Account account:accounts)
{
AccountRole aRole = (AccountRole) baseDao
.queryUnique("select a from AccountRole a where a.accountId=? and a.roleId=?", account.getId(),
roleId);
if (aRole == null)
{
AccountRole ar=new AccountRole();
ar.setAccountId(account.getId());
ar.setCreateDate(new Date());
ar.setRoleId(roleId);
baseDao.add(ar);
}
}
}
}
<file_sep>package com.goldskyer.gmxx.service;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.annotation.Rollback;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import com.goldskyer.core.dao.BaseDao;
import com.goldskyer.gmxx.common.entities.MessageText;
import com.goldskyer.gmxx.workflow.entities.PurchaseDetail;
import com.goldskyer.gmxx.workflow.entities.PurchaseFlow;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:applicationContext.xml")
public class BaseTest {
protected Log log = LogFactory.getLog(BaseTest.class);
@Autowired
protected BaseDao baseDao;
@Test
public void testAdd()
{
MessageText text = new MessageText();
text.setText("123");
text.setText("我的");
baseDao.add(text);
}
@Test
@Rollback(false)
public void query()
{
PurchaseFlow purchaseFlow=new PurchaseFlow();
purchaseFlow.setNote("ss");
PurchaseDetail detail = new PurchaseDetail();
detail.setBuyCount(4);
detail.setPurchaseFlow(purchaseFlow);
purchaseFlow.getDetails().add(detail);
baseDao.add(purchaseFlow);
}
@Test
@Rollback(false)
public void testAA()
{
baseDao.delete(PurchaseFlow.class, "8a53b78255ef9f490155ef9f58d20000");
}
}
<file_sep>package com.goldskyer.gmxx.manager.helpers;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
public class WebUserHelper
{
private static final Log log = LogFactory.getLog(WebUserHelper.class);
}
<file_sep>package com.goldskyer.gmxx.survey.entities;
import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
import org.hibernate.annotations.GenericGenerator;
@Entity
@Table(name="part_paper_to_question")
public class PartPaperToQuestion implements Serializable {
/**
*
*/
private static final long serialVersionUID = -1355951322408869941L;
@Id
@Column(name = "ID", length = 40)
@GeneratedValue(generator = "idGenerator")
@GenericGenerator(name = "idGenerator", strategy = "uuid")
private String id;
private String partPaperId;
private String questionId;
private double weight=1000d;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getPartPaperId() {
return partPaperId;
}
public void setPartPaperId(String partPaperId) {
this.partPaperId = partPaperId;
}
public String getQuestionId() {
return questionId;
}
public void setQuestionId(String questionId) {
this.questionId = questionId;
}
public double getWeight() {
return weight;
}
public void setWeight(double weight) {
this.weight = weight;
}
}
<file_sep>package com.goldskyer.codegen.boot;
public class GenInfo
{
public String entityPath;//实体类路径
public String targetDto;
public String target;
public String Target;
public String cnName;
}
<file_sep>package com.goldskyer.scorecloud.entities;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
import org.hibernate.annotations.GenericGenerator;
/**
* 年级
* @author jintianfan
*
*/
@Entity
@Table(name = "grade")
public class Grade implements SchoolId
{
@Id
@Column(name = "ID", length = 40)
@GeneratedValue(generator = "idGenerator")
@GenericGenerator(name = "idGenerator", strategy = "uuid")
private String id;
private String gradeName;
private int enterYear;//入学年
private int weight = 0;//越小,显示靠前
private String majorTeacherName; //年级主任名字
private String majorTeacherId;//年级主任ID
private int status;//1有效,2:归档
private String schId;
public String getSchId()
{
return schId;
}
public void setSchId(String schId)
{
this.schId = schId;
}
public String getId()
{
return id;
}
public void setId(String id)
{
this.id = id;
}
public String getGradeName()
{
return gradeName;
}
public void setGradeName(String gradeName)
{
this.gradeName = gradeName;
}
public int getEnterYear()
{
return enterYear;
}
public void setEnterYear(int enterYear)
{
this.enterYear = enterYear;
}
public String getMajorTeacherName()
{
return majorTeacherName;
}
public void setMajorTeacherName(String majorTeacherName)
{
this.majorTeacherName = majorTeacherName;
}
public int getWeight()
{
return weight;
}
public void setWeight(int weight)
{
this.weight = weight;
}
public String getMajorTeacherId()
{
return majorTeacherId;
}
public void setMajorTeacherId(String majorTeacherId)
{
this.majorTeacherId = majorTeacherId;
}
public int getStatus()
{
return status;
}
public void setStatus(int status)
{
this.status = status;
}
}
<file_sep>$(function() {
/**
* Menu表单校验
*/
$('#addForm').validate({
rules : {
title : {
required : true
},
content : {
required : true
},
receivers : {
required : true
}
},
messages : {
title : {
required : "消息标题不能为空"
},
content : {
required : "消息内容不能为空"
},
receiver : {
required : "接收者"
}
},
showErrors : function(errorMap, errorList) {
var element = this.currentElements;
if (element.next().hasClass('popover')) {
element.popover('destroy');
}
this.defaultShowErrors();
},
submitHandler : function(form) { // 表单提交句柄,为一回调函数,带一个参数:form
$(form).ajaxSubmit({
type : "post",
url : "add.json",
success : function(data) {
if (data.result == "success") {
window.location.href = "list.htm";
} else {
alert(data.msg);
}
}
});
},
});
//弹出账号选择框
$('.choose_account').bind("click",function(){
$.jBox("iframe:/manager/user/dialog/list.htm", {
title: "选择用户",
id:"chooseAccountDialog",
width: 800,
height: 450,
buttons: { }
});
});
});
<file_sep>package com.goldskyer.gmxx.web.spring.controllers;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
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.RequestParam;
import org.springframework.web.servlet.ModelAndView;
import com.goldskyer.common.exceptions.BusinessException;
import com.goldskyer.core.constants.BlogEvent;
import com.goldskyer.core.entities.Blog;
import com.goldskyer.core.entities.BlogLog;
import com.goldskyer.core.entities.Menu;
import com.goldskyer.core.entities.VoteUpLog;
import com.goldskyer.core.service.BlogService;
import com.goldskyer.core.service.CommentService;
import com.goldskyer.core.service.VoteUpLogService;
import com.goldskyer.core.vo.CommentVo;
import com.goldskyer.core.vo.Pagination;
import com.goldskyer.gmxx.common.constants.CmsConstant;
import com.goldskyer.gmxx.common.constants.GmxxConstant;
import com.goldskyer.gmxx.front.business.BlogBusiness;
import com.goldskyer.gmxx.front.business.dto.BlogListModel;
import com.goldskyer.gmxx.web.controllers.WebBaseController;
@Controller("web.spring.BlogController")
@RequestMapping("/web/spring/{module}")
public class BlogController extends WebBaseController
{
@Autowired
private VoteUpLogService voteUpLogService;
@Autowired
private CommentService commentService;
@Autowired
protected BlogBusiness blogBusiness;
@Autowired
protected BlogService blogService;
@RequestMapping("/view.htm")
public ModelAndView detail(HttpServletRequest request, @RequestParam String id, @PathVariable String module,
@RequestParam(required = false) String accountId)
{
ModelAndView mv = new ModelAndView("/web/spring/" + module + "/view");
if (StringUtils.isBlank(id))
{
mv.setViewName("/web/spring/blog/common_error");
request.getSession().setAttribute("errorMsg", "该文章不存在");
return mv;
}
if (StringUtils.isNotBlank(getCurrentAccountId()))
{
accountId = getCurrentAccountId(); //有session优先使用session的值
}
initCommonBlock(mv);
initSideBar(mv);
buildCommonBlogModel(mv,id);
if (mv.getModelMap().get("menu") == null)
{
mv.setViewName("/web/spring/blog/common_error");
request.getSession().setAttribute("errorMsg", "该文章所在栏目已经不存在");
return mv;
}
//判断是否登陆可见
Blog blog = (Blog) mv.getModel().get("blog");
//面包屑
log.info("crumbs:" + getCrumbs(blog.getType()));
mv.addObject("crumbs", getCrumbs(blog.getType()));
mv.addObject("schoolTitle", cmsService.getCmsContent(CmsConstant.SCHOOL_TITLE));
mv.addObject("footerContact", cmsService.getCmsContent(CmsConstant.FOOTER_CONTACT));
//获取前后也内容
Blog nextBlog = blogService.queryNextBlog(blog);
Blog preBlog = blogService.queryPreBlog(blog);
mv.addObject("nextBlog", nextBlog);
mv.addObject("preBlog", preBlog);
if (blog.getNeedLogin() && StringUtils.isBlank(getCurrentAccountId()))
{
mv.setViewName("/web/spring/blog/needLogin");
request.getSession().setAttribute("redirectUrl", "/web/spring/blog/view.htm?id=" + blog.getId());
return mv;
}
//执行读取操作
if (StringUtils.isNotBlank(getCurrentAccountId()))
{
BlogLog blogLog = new BlogLog();
blogLog.setAccountId(getCurrentAccountId());
blogLog.setBlogId(blog.getId());
blogLog.setBlogEvent(BlogEvent.READ);
blogService.addBlogLog(blogLog);
//把未读记录标记为已读
messageService.readMessageByBlogId(blog.getId(), getCurrentAccountId());
}
if (blog.isDeleted())
{
mv.setViewName("/web/spring/blog/deleted");
request.getSession().setAttribute("redirectUrl", "/web/spring/blog/view.htm?id=" + blog.getId());
return mv;
}
blogService.incViewCount(id);
if (StringUtils.isNotBlank(accountId))
{
VoteUpLog voteUpLog = voteUpLogService.queryVoteUpLogbyId(accountId, id, "BLOG");
if(voteUpLog!=null)
{
mv.addObject("voted", true);
}
}
List<CommentVo> comments = commentService.queryCommentVosByObject(id, "BLOG", 0, 100);
mv.addObject("comments", comments);
return mv;
}
/**
* 所有的资源型内容列表通用这个接口
* /web/tv/list.htm 对应 /web/tv/list.jsp
* /web/tv/list_image.htm /web/tv/list_image.jsp
* @param view
* @param module
* @param blogType
* @param pageNum
* @return
*/
@RequestMapping("/list{view}.htm")
public ModelAndView list(@PathVariable String view, @PathVariable String module, @RequestParam String blogType,
@RequestParam(required = false) Integer pageNum)
{
if (pageNum == null || pageNum == 0)
{
pageNum = 1;
}
ModelAndView mv = new ModelAndView("/web/spring/" + module + "/list" + view);
initCommonBlock(mv);
Integer pageSize = 10;
String typeIni = iniService.getIniValue(blogType + "_PAGE_SZIE");
if (StringUtils.isNotBlank(typeIni))
{
pageSize = Integer.valueOf(typeIni);
}
else
{
pageSize = Integer.valueOf(iniService.getIniValue(GmxxConstant.PAGE_SIZE));
}
BlogListModel blogListModel = blogBusiness.buildCommonBlogListModel(mv, blogType, pageNum, pageSize);
//设置左侧菜单
boolean isTab = false; //
Integer menuDeep = getMenuDeep(blogType); //菜单深度
Menu menu = cachedMenuService.queryMenuByName(blogType);
if (menuDeep == 4)
{
mv.addObject("leftMenus", menu.getParent().getChildren());
}
else if (menuDeep == 3)
{
mv.addObject("leftMenus", menu.getChildren());
if (menu.getChildren() == null || menu.getChildren().size() == 0)
{
List<Menu> tmp = new ArrayList<>();
tmp.add(menu);
mv.addObject("leftMenus", tmp); //如果三层菜单没有子节点,就显示当前节点列表
}
isTab = true;
}
List<List<Blog>> blogTabs = new ArrayList<>();
List<String> tabNames = new ArrayList<>();
if (isTab)
{
for (Menu m : (List<Menu>) mv.getModel().get("leftMenus"))
{
blogTabs.add(blogBusiness.queryBlogsWithNoContent(m.getName(), null, 0, 8));
tabNames.add(m.getName());
}
}
else
{
blogTabs.add(blogBusiness.queryBlogsWithNoContent(blogType, null, (pageNum - 1) * pageSize, pageSize));
tabNames.add(blogType);
}
mv.addObject("blogTabs", blogTabs);
mv.addObject("tabNames", tabNames);
//
mv.addObject("crumbs", getCrumbs(blogType));
//加入分页标签
if (!isTab)
{
Pagination pager = new Pagination(pageNum, blogListModel.getCount(), pageSize,
Integer.valueOf(iniService.getIniValue(GmxxConstant.PAGE_BTN_NUM)));
mv.addObject("pager", pager);
}
mv.addObject("schoolTitle", cmsService.getCmsContent(CmsConstant.SCHOOL_TITLE));
mv.addObject("footerContact", cmsService.getCmsContent(CmsConstant.FOOTER_CONTACT));
return mv;
}
protected void buildCommonBlogModel(ModelAndView mv,String blogId)
{
Blog blog = blogService.queryBlog(blogId);
if(blog==null)
{
throw new BusinessException("当前请求记录不存在");
}
Menu menu = cachedMenuService.queryMenuByName(blog.getType());
mv.addObject("mainMenu", cachedMenuService.getMainMenu());
mv.addObject("menu", menu);
mv.addObject("blog",blog);
}
}
<file_sep>package com.goldskyer.scorecloud;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.annotation.Rollback;
import com.goldskyer.gmxx.service.BaseTest;
import com.goldskyer.scorecloud.entities.Subject;
import com.goldskyer.scorecloud.service.SubjectService;
public class SubjectServiceTest extends BaseTest
{
@Autowired
private SubjectService subjectService;
@Test
@Rollback(false)
public void addSubject()
{
{
Subject subject = new Subject();
subject.setExamId("1");
subject.setSubjectName("语文");
subject.setId("1");
subjectService.addSubject(subject);
}
{
Subject subject = new Subject();
subject.setExamId("1");
subject.setSubjectName("数学");
subject.setId("2");
subjectService.addSubject(subject);
}
}
}
<file_sep>package com.goldskyer.gmxx.survey.service.impl;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.goldskyer.core.service.impl.CoreServiceImp;
import com.goldskyer.gmxx.survey.entities.Paper;
import com.goldskyer.gmxx.survey.service.PaperService;
@Service
public class PaperServiceImp extends CoreServiceImp implements PaperService{
@Override
@Transactional
public void addPaper(Paper paper) {
baseDao.add(paper);
}
@Override
public void deletePaper(String paperId) {
baseDao.delete(Paper.class,paperId);
}
@Override
public void modifyPaper(Paper paper) {
baseDao.modify(paper);
}
@Override
@Transactional
public Paper queryPaperById(String paperId) {
return queryPaperByIdSortByWeight(paperId);
}
public Paper queryPaperByIdSortByWeight(String paperId)
{
Paper paper=baseDao.query(Paper.class,paperId);
return paper;
}
public Double caculateScore(List<String> aIds)
{
Map map = new HashMap();
map.put("ids", aIds);
return (Double) baseDao.queryUnique("select sum(score) from Answer where id in :ids",map);
}
}
<file_sep>package com.goldskyer.gmxx.mock.controllers;
import java.net.URLDecoder;
import java.net.URLEncoder;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import com.goldskyer.core.dto.JsonData;
import com.goldskyer.core.utils.Base64Util;
import com.goldskyer.core.utils.IdentityUtil;
import com.goldskyer.core.utils.SignUtil;
@Controller
@RequestMapping("")
public class ToolController {
private Log log = LogFactory.getLog(ToolController.class);
@RequestMapping(value="/mock/tool.htm")
public ModelAndView index(String input)
{
return new ModelAndView("/mock/tool");
}
@RequestMapping(value="/base64encode", produces="application/json;charset=UTF-8")
@ResponseBody
public JsonData base64encode(String input){
if(StringUtils.isBlank(input))
{
return JsonData.failure("输入参数不能为空");
}
return JsonData.success(Base64Util.encodeBase64(input));
}
@RequestMapping(value="/base64decode", produces="application/json;charset=UTF-8")
@ResponseBody
public JsonData base64decode(String input){
if(StringUtils.isBlank(input))
{
return JsonData.failure("输入参数不能为空");
}
input = input.trim();
return JsonData.success(Base64Util.decodeBase64(input));
}
@RequestMapping(value="/urldecode", produces="application/json;charset=UTF-8")
@ResponseBody
public JsonData urldecode(String input){
if(StringUtils.isBlank(input))
{
return JsonData.failure("输入参数不能为空");
}
input = input.trim();
return JsonData.success(URLDecoder.decode(input));
}
@RequestMapping(value="/urlencode", produces="application/json;charset=UTF-8")
@ResponseBody
public JsonData urlencode(String input){
if(StringUtils.isBlank(input))
{
return JsonData.failure("输入参数不能为空");
}
return JsonData.success(URLEncoder.encode(input));
}
@RequestMapping(value="/validateIdentityNo", produces="application/json;charset=UTF-8")
@ResponseBody
public JsonData validateIdentityNo(String input){
if(StringUtils.isBlank(input))
{
return JsonData.failure("输入参数不能为空");
}
return JsonData.success(String.valueOf(IdentityUtil.verify(input)));
}
@RequestMapping(value="/base64AndHex", produces="application/json;charset=UTF-8")
@ResponseBody
public JsonData base64AndHex(String input,String type){
if(StringUtils.isBlank(input))
{
return JsonData.failure("输入参数不能为空");
}
input = input.trim();
try {
if(StringUtils.equals("base64", type))
{
return JsonData.success(SignUtil.convertBase64ToHex(input));
}
if(StringUtils.equals("hex", type))
{
return JsonData.success(SignUtil.convertHexToBase64(input));
}
else
{
return JsonData.failure("输入参数既不是base64格式,又不是16进制格式");
}
} catch (Exception e) {
log.error(e.getMessage(), e);
return JsonData.failure("转换异常");
}
}
@RequestMapping(value="/generateSignPair", produces="application/json;charset=UTF-8")
@ResponseBody
public JsonData generateSignPair(String type){
StringBuffer priKey = new StringBuffer();
StringBuffer pubKey = new StringBuffer();
if(StringUtils.equals("hex", type))
{
SignUtil.genHexRSAKeyPair(priKey, pubKey);
}
else if(StringUtils.equals("base64", type))
{
SignUtil.genBase64RSAKeyPair(priKey, pubKey);
}
else
{
return JsonData.failure("所传类型不对");
}
JsonData jsonData = JsonData.success();
jsonData.data.put("pubKey", pubKey.toString());
jsonData.data.put("priKey", priKey.toString());
return jsonData;
}
@RequestMapping(value="/checkSign", produces="application/json;charset=UTF-8")
@ResponseBody
public JsonData checkSign(String priKey,String pubKey,String type){
if(StringUtils.equals("hex", type))
{
return JsonData.success(String.valueOf(SignUtil.checkSignPair(pubKey, priKey,"hex")));
}
else if(StringUtils.equals("base64", type))
{
return JsonData.success(String.valueOf(SignUtil.checkSignPair(pubKey, priKey,"base64")));
}
else
{
return JsonData.failure("所传类型不对");
}
}
@RequestMapping(value="/getSign", produces="application/json;charset=UTF-8")
@ResponseBody
public JsonData getSign(String src,String priKey,String type){
if(StringUtils.equals("base64", type))
{
String sign = SignUtil.getBase64RsaSign(priKey, src, "UTF-8");
if(StringUtils.isBlank(sign))
{
return JsonData.failure("生成签名错误");
}
return JsonData.success(sign);
}
if(StringUtils.equals("hex", type))
{
String sign = SignUtil.getHexRsaSign(priKey, src);
if(StringUtils.isBlank(sign))
{
return JsonData.failure("生成签名错误");
}
return JsonData.success(sign);
}
return JsonData.failure("公私钥格式既不是base64又不是16进制");
}
@RequestMapping(value="/verifySign", produces="application/json;charset=UTF-8")
@ResponseBody
public JsonData verifySign(String src,String pubKey,String sign,String type){
if(StringUtils.equals("base64", type))
{
return JsonData.success(String.valueOf(SignUtil.verifyBase64RsaSign(pubKey, sign, src, "UTF-8")));
}
if(StringUtils.equals("hex", type))
{
return JsonData.success(String.valueOf(SignUtil.verifyHexRsaSign(pubKey, sign, src)));
}
return JsonData.failure("公私钥格式既不是base64又不是16进制");
}
@RequestMapping(value="/aesDecrypt", produces="application/json;charset=UTF-8")
@ResponseBody
public JsonData aesDecrypt(String src,String pubKey,String sign,String type){
if(StringUtils.equals("base64", type))
{
return JsonData.success(String.valueOf(SignUtil.verifyBase64RsaSign(pubKey, sign, src, "UTF-8")));
}
if(StringUtils.equals("hex", type))
{
return JsonData.success(String.valueOf(SignUtil.verifyHexRsaSign(pubKey, sign, src)));
}
return JsonData.failure("公私钥格式既不是base64又不是16进制");
}
@RequestMapping(value="/aesEncrypt", produces="application/json;charset=UTF-8")
@ResponseBody
public JsonData aesEncrypt(String src,String pubKey,String sign,String type){
if(StringUtils.equals("base64", type))
{
return JsonData.success(String.valueOf(SignUtil.verifyBase64RsaSign(pubKey, sign, src, "UTF-8")));
}
if(StringUtils.equals("hex", type))
{
return JsonData.success(String.valueOf(SignUtil.verifyHexRsaSign(pubKey, sign, src)));
}
return JsonData.failure("公私钥格式既不是base64又不是16进制");
}
}
<file_sep>require('../less/tvview.less');
require('../js/lib/widget/navigator.iscroll.js');
var Fingerprint = require('../bower_components/fingerprint/fingerprint.js');
var clickElement;
$(function () {
$('.loading').hide();
$('.relevant_video .loadmore-div').on('click', function(){
loadMoreTVData();
});
$('.history_comment .loadmore-div').on('click', function(){
loadMoreCommentsData();
});
init();//获取推荐视频列表
getVoteStatus();//获取点赞状态
getCommentList();//获取评论列表
$('.write-cmt').on('click', function(){
if ($('.sendCmt').css("display") == 'none') {
$('.sendCmt').css("display", "block");
$('.icon_cmt_gray').css("display", "none");
$('.cancel-cmt').css("display", "block");
} else {
$('.sendCmt').css("display", "none");
$('.cancel-cmt').css("display", "none");
$('.icon_cmt_gray').css("display", "block");
}
});
$('.icon_praise_gray').on('click', function(){
var fingerprint = new Fingerprint().get();
var objectIdValue = $('.objectId').text();
clickElement = $(this);
$.ajax({
type: "GET",
url: "http://gmxx.goldskyer.com/front/blog/voteUp.json",
data: {
accountId: fingerprint,
objectId: objectIdValue,
objectType: "BLOG",
fp: fingerprint
},
dataType: "json",
success: function (data) {
if (data.result == "success") {
clickElement.attr('class',"icon_praise_red");
var currentlikenum = parseInt($('.likeNum').html());
$('.likeNum').html(currentlikenum + 1);
clickElement = null;
};
},
error: function () {
clickElement.attr('class',"icon_praise_gray");
clickElement = null;
}
});
});
$(".button").on('click', function() {
var info = $(".input-txt").val();
if ($.trim(info) != '') {
var name = new Fingerprint().get();
var objectid = $('.objectId').text();
$.ajax({
type: "GET",
url: "http://gmxx.goldskyer.com/comment/add.json",
data: {
accountId: name,
objectId: objectid,
content: info,
objectType:"BLOG"
},
dataType: "json",
success: function(data){
var hc_list = "<div class='hc_list'>";
hc_list += "<div class='hc_left'>";
hc_list += "<img class='hc_img' src='/images/icons/avatar.jpg' >";
hc_list += "</div>";
hc_list += "<div class='hc_right'>";
hc_list += "<div class='hc_name'>" + data.data.comment.accountId + "</div>";
hc_list += "<div class='hc_info'>" + data.data.comment.content + "</div>";
hc_list += "<div class='hc_time'>" + data.data.comment.createDate + "</div>";
hc_list += "</div></div>";
$(".history_comment").prepend(hc_list);
},
error: function () {
return;
}
});
$(".input-txt").val('');
}
});
});
function init(){
$('.newslist').css("display", "none");
$('.relevant_video .noResult').css("display", "none");
$(".relevant_video .loadmore-div").css("display", "none");
var blogType = $(".blogType").text();
var objectIdValue = $('.objectId').text();
var pageNo = 1;
$.ajax({
type: "GET",
url: "http://gmxx.goldskyer.com/front/blog/list.json",
data: {type:blogType, pageNo:pageNo},
dataType: "json",
success: function(data){
//如果pageNo=1 and count(blogs)=0,则显示暂无数据
var resultData = data.data;
var pageNo = resultData.pageNo;
var blogs = resultData.blogs;
var totalcnt = resultData.count;
if (pageNo == 1 && blogs.length == 0) {
$('.newslist').css("display", "none");
$('.relevant_video .noResult').css("display", "block");
$(".relevant_video .loadmore-div").css("display", "none");
return;
} else {
$('.newslist').css("display", "block");
$('.relevant_video .noResult').css("display", "none");
}
for (var i = 0; i < blogs.length; i++) {
var blog = blogs[i];
if (objectIdValue == blog.id) {continue;}
var basePath = "http://gmxx.goldskyer.com/";
var blogUrl = basePath + "front/tv/view.htm?id=" + blog.id;
var imgSrc;
if ("coverImage" in blog){
imgSrc = blog.coverImage;
}else{
imgSrc = "http://gmxx.szgm.edu.cn/UploadFile/1511/182034504628960/182033210161026.jpg";
}
var blog_row = '<a href="' + blogUrl + '"><li class="newscontent">';
blog_row += '<div class="media_content">';
blog_row += '<div class="bg_img">';
blog_row += '<img class="newsimage" src="' + imgSrc + '" z-index=1>';
blog_row += '<img class="play_img" src="/images/play.png" z-index=2>';
blog_row += '</div>';
blog_row += '<p class="newstitle">' + blog.title + '</p>';
blog_row += '<p class="newsdesc">' + splitTime(blog.updateDate) + '</p>';
blog_row += '</li></a>';
$(".newslist").append(blog_row);
}
//当totalcnt - 如果currentcnt >= 10,则加载刷新展现
if (totalcnt - pageNo * 10 > 0) {
$(".relevant_video .loadmore-div").css("display", "block");//展示
$(".relevant_video .loadmore-p").css("display", "block");
$(".relevant_video .loadmore-img").css("display", "none");
}else{//否则不现实加载刷新
$(".relevant_video .loadmore-div").css("display", "none");
}
$(".relevant_video .pageNo").text(pageNo + 1);
},
error: function () {
$(".relevant_video .loadmore-p").css("display", "block");
$(".relevant_video .loadmore-img").css("display", "none");
}
});
};
function loadMoreTVData() {
$('.relevant_video .loadmore-p').css("display", "none");
$('.relevant_video .loadmore-img').css("display", "block");
var blogType = $(".blogType").text();
var pageNo = $(".relevant_video .pageNo").text();
$.ajax({
type: "GET",
url: "http://gmxx.goldskyer.com/front/blog/list.json",
data: {type:blogType, pageNo:pageNo},
dataType: "json",
success: function(data){
//如果pageNo=1 and count(blogs)=0,则显示暂无数据
var resultData = data.data;
var pageNo = resultData.pageNo;
var blogs = resultData.blogs;
var totalcnt = resultData.count;
if (pageNo == 1 && blogs.length == 0) {
$('.newslist').css("display", "none");
$('.relevant_video .noResult').css("display", "block");
return;
} else {
$('.newslist').css("display", "block");
$('.relevant_video .noResult').css("display", "none");
}
//否则加载并显示数据
for (var i = 0; i < blogs.length; i++) {
var blog = blogs[i];
var basePath = "http://gmxx.goldskyer.com/";
var blogUrl = basePath + "front/tv/view.htm?id=" + blog.id;
var imgSrc;
if ("coverImage" in blog){
imgSrc = blog.coverImage;
}else{
imgSrc = "http://gmxx.szgm.edu.cn/UploadFile/1511/182034504628960/182033210161026.jpg";
}
var blog_row = '<a href="' + blogUrl + '"><li class="newscontent">';
blog_row += '<div class="media_content">';
blog_row += '<div class="bg_img">';
blog_row += '<img class="newsimage" src="' + imgSrc + '" z-index=1>';
blog_row += '<img class="play_img" src="/images/play.png" z-index=2>';
blog_row += '</div>';
blog_row += '<p class="newstitle">' + blog.title + '</p>';
blog_row += '<p class="newsdesc">' + splitTime(blog.updateDate) + '</p>';
blog_row += '</li></a>';
$(".newslist").append(blog_row);
}
//当totalcnt - 如果currentcnt >= 10,则加载刷新展现
if (totalcnt - pageNo * 10 > 0) {
$(".relevant_video .loadmore-div").css("display", "block");//展示
$(".relevant_video .loadmore-p").css("display", "block");
$(".relevant_video .loadmore-img").css("display", "none");
}else{//否则不现实加载刷新
$(".relevant_video .loadmore-div").css("display", "none");
}
$(".relevant_video .pageNo").text(pageNo + 1);
},
error: function () {
$(".relevant_video .loadmore-p").css("display", "block");
$(".relevant_video .loadmore-img").css("display", "none");
}
});
};
function getVoteStatus(){//获取点赞状态
var fingerprint = new Fingerprint().get();
var objectIdValue = $('.objectId').text();
$.ajax({
type: "GET",
url: "http://gmxx.goldskyer.com/voteUp/queryStatus.json",
data: {
accountId: fingerprint,
objectId: objectIdValue,
objectType: "BLOG",
fp: fingerprint
},
dataType: "json",
success: function (data) {
if (data.result == "failure") {
$(".icon_praise_gray").attr('class', "icon_praise_red");
}
},
error: function () {
$(".icon_praise_gray").attr('class', "icon_praise_gray");
}
});
};
function splitTime(originTime){//从接口中,获取日期
var timeArray = originTime.split(" ");
return timeArray[0];
};
function getCommentList(){//获取评论列表
var name = new Fingerprint().get();
var objectid = $('.objectId').text();
var pageNo = 1;
$.ajax({
type: "GET",
url: "http://gmxx.goldskyer.com/comment/list.json",
data: {
objectId: objectid,
objectType:"BLOG",
pageNo:pageNo
},
dataType: "json",
success: function(data){
var comments = data.data.comments;
for (var i = 0; i < comments.length; i++) {
var comment = comments[i];
var hc_list = "<div class='hc_list'>";
hc_list += "<div class='hc_left'>";
hc_list += "<img class='hc_img' src='/images/icons/avatar.jpg' >";
hc_list += "</div>";
hc_list += "<div class='hc_right'>";
hc_list += "<div class='hc_name'>" + comment.accountId + "</div>";
hc_list += "<div class='hc_info'>" + comment.content + "</div>";
hc_list += "<div class='hc_time'>" + comment.createDate + "</div>";
hc_list += "</div></div>";
$(".history_comment").prepend(hc_list);
}
var totalcnt = data.data.count;
// if (totalcnt == 0) {//是否需要展示暂无数据,如果不需要的话,暂时不加入
// $('.hot_comment .noResult').css("display", "block");
// $(".hot_comment .loadmore-div").css("display", "none");
// };
//当totalcnt - 当前currentcnt >= 10,则加载刷新展现
if (totalcnt - pageNo * 10 > 0) {
$(".hot_comment .loadmore-div").css("display", "block");//展示
$(".hot_comment .loadmore-p").css("display", "block");
$(".hot_comment .loadmore-img").css("display", "none");
}else{//否则不现实加载刷新
$(".hot_comment .loadmore-div").css("display", "none");
}
$(".hot_comment .pageNo").text(pageNo + 1);
},
error: function () {
$(".hot_comment .loadmore-div").css("display", "none");
}
});
};
function loadMoreCommentsData() {
$('hot_comment .loadmore-p').css("display", "none");
$('.hot_comment .loadmore-img').css("display", "block");
var pageNo = $(".history_comment .pageNo").text();
var objectid = $('.objectId').text();
$.ajax({
type: "GET",
url: "http://gmxx.goldskyer.com/comment/list.json",
data: {
objectId: objectid,
objectType:"BLOG",
pageNo:pageNo
},
dataType: "json",
success: function(data){
var comments = data.data.comments;
var totalcnt = data.data.count;
for (var i = 0; i < comments.length; i++) {
var comment = comments[i];
var hc_list = "<div class='hc_list'>";
hc_list += "<div class='hc_left'>";
hc_list += "<img class='hc_img' src='/images/icons/avatar.jpg' >";
hc_list += "</div>";
hc_list += "<div class='hc_right'>";
hc_list += "<div class='hc_name'>" + comment.accountId + "</div>";
hc_list += "<div class='hc_info'>" + comment.content + "</div>";
hc_list += "<div class='hc_time'>" + comment.createDate + "</div>";
hc_list += "</div></div>";
$(".history_comment").prepend(hc_list);
}
//当totalcnt - 如果currentcnt >= 10,则加载刷新展现
if (totalcnt - pageNo * 10 > 0) {
$(".hot_comment .loadmore-div").css("display", "block");//展示
$(".hot_comment .loadmore-p").css("display", "block");
$(".hot_comment .loadmore-img").css("display", "none");
}else{//否则不现实加载刷新
$(".hot_comment .loadmore-div").css("display", "none");
}
$(".hot_comment .pageNo").text(pageNo + 1);
},
error: function () {
$(".hot_comment .loadmore-p").css("display", "block");
$(".hot_comment .loadmore-img").css("display", "none");
}
});
};
<file_sep>package com.goldskyer.scorecloud.controller;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
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.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import com.goldskyer.core.dto.JsonData;
import com.goldskyer.core.entities.Account;
import com.goldskyer.core.enums.AccountType;
import com.goldskyer.core.service.AccountService;
import com.goldskyer.scorecloud.business.LoginBusiness;
import com.goldskyer.scorecloud.dto.ScoreCloudEnv;
import com.goldskyer.scorecloud.exception.resp.RespCodeConstant;
import com.goldskyer.smartcloud.common.util.Assert;
@Controller("scorecloudLoginController")
@RequestMapping("/scorecloud")
public class LoginController extends BaseScoreCloudController
{
@Autowired
private AccountService accountService;
@Autowired
private LoginBusiness loginBusiness;
@RequestMapping(value = "/doLogin.json", produces = "application/json")
@ResponseBody
public Object doLogin(@RequestParam("dog") String username, @RequestParam("cat") String password,
@RequestParam("j_code") String code,
HttpServletRequest request, HttpServletResponse response)
{
response.setHeader("Cache-Control", "no-cache");
response.setHeader("Cache-Control", "no-store");
response.setDateHeader("Expires", 0);
response.setHeader("Pragma", "no-cache");
Assert.notEmpty(username, RespCodeConstant.USER_NAME_IS_EMPTY);
Assert.notEmpty(password, RespCodeConstant.PWD_IS_EMPTY);
boolean result = accountService.isValidAccount(username, password, AccountType.ADMIN);
Account account = accountService.getAccountByUsername(username);
if (result)
{
loginBusiness.doLogin(account.getId());
return JsonData.success();
}
else
{
return JsonData.failure("用户名或密码不正确");
}
}
@RequestMapping(value = "/logout.htm")
public ModelAndView logout(HttpSession session)
{
ScoreCloudEnv.get().clearSession();
ModelAndView mv = new ModelAndView("/scorecloud/login/" + ScoreCloudEnv.get().getSchId());
return mv;
}
@RequestMapping(value = "/login/xcxx.htm")
public ModelAndView toList(HttpServletRequest request, HttpServletResponse response)
{
ModelAndView mv = new ModelAndView("/scorecloud/login/xcxx");
return mv;
}
}
<file_sep>package com.goldskyer.gmxx.common.dtos;
import java.util.ArrayList;
import java.util.List;
public class CmdResultDto {
private List<String> processList=new ArrayList<String>();
public List<String> getProcessList() {
return processList;
}
public void setProcessList(List<String> processList) {
this.processList = processList;
}
}
<file_sep>package com.goldskyer.gmxx.survey.entities;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import org.hibernate.annotations.GenericGenerator;
@Entity
public class Answer {
@Id
@Column(name = "ID", length = 40)
@GeneratedValue(generator = "idGenerator")
@GenericGenerator(name = "idGenerator", strategy = "uuid")
private String id;
private String curOption; //选项比如A,B,C,(不设置的话系统自动分配,1,2,3,4用于显示选项时的排序)
private boolean isAnswer;//正确选项
private String answerContent;
private double score;
@ManyToOne(cascade=CascadeType.ALL)
@JoinColumn(name="questionId")
private Question question;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getCurOption() {
return curOption;
}
public void setCurOption(String curOption) {
this.curOption = curOption;
}
public boolean isAnswer() {
return isAnswer;
}
public void setAnswer(boolean isAnswer) {
this.isAnswer = isAnswer;
}
public Question getQuestion() {
return question;
}
public void setQuestion(Question question) {
this.question = question;
}
public String getAnswerContent() {
return answerContent;
}
public void setAnswerContent(String answerContent) {
this.answerContent = answerContent;
}
public double getScore() {
return score;
}
public void setScore(double score) {
this.score = score;
}
}
<file_sep>package com.goldskyer.scorecloud.business.impl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.goldskyer.scorecloud.business.AnalyzeBusiness;
import com.goldskyer.scorecloud.service.TargetScoreService;
@Service
public class AnalyzeBusinessImpl implements AnalyzeBusiness
{
@Autowired
private TargetScoreService targetScoreService;
}
<file_sep>$(function(){
/**
* Menu表单校验
*/
$('#menuForm').validate({
rules:{
name:{
required:true
}
},
messages:{
name:{
required:"菜单名不能为空"
}
},
submitHandler: function(form){ //表单提交句柄,为一回调函数,带一个参数:form
$(form).ajaxSubmit({
type:"post",
url:"/manager/menu/modify.json",
success: function(){
showInfo("info","保存成功");
}
});
},
});
});
/**
*初始化菜单编辑页面
*/
function initMenuForm(id)
{
if(id=='' || id==null)
{
return;
}
$.ajax({
url:"/menu/item.json?id="+id,
success:function(result){
$('input[name="id"]').val(result.data.menu.id);
$('input[name="name"]').val(result.data.menu.name);
$('input[name="link"]').val(result.data.menu.link);
$('input[name="weight"]').val(result.data.menu.weight);
$('input[type="radio"][name="type"][value="'+result.data.menu.type+'"]').attr("checked",true); ;
$('input[type="radio"][name="mediaType"][value="'+result.data.menu.mediaType+'"]').attr("checked",true);
$('input[type="checkbox"][name="show"]').attr("checked",!result.data.menu.hide);
}
});
}
$('#reset').bind('click',function(){
initMenuForm($('input[name="id"]').val());
});
var setting = {
view: {
dblClickExpand: false
},
check: {
enable: false
},
edit: {
drag: {
autoExpandTrigger: true,
prev: dropPrev,
inner: dropInner,
next: dropNext
},
enable: true,
showRemoveBtn: false,
showRenameBtn: false
},
data: {
simpleData: {
enable: true,
idKey:'id'
}
},
callback: {
onClick:onClick,
onRightClick: OnRightClick,
beforeDrag: beforeDrag,
beforeDrop: beforeDrop,
beforeDragOpen: beforeDragOpen,
onDrag: onDrag,
onDrop: onDrop,
onExpand: onExpand
}
};
var zNodes = [];
function onClick(event, treeId, treeNode)
{
initMenuForm(treeNode.id);
}
function OnRightClick(event, treeId, treeNode) {
if (!treeNode && event.target.tagName.toLowerCase() != "button" && $(event.target).parents("a").length == 0) {
zTree.cancelSelectedNode();
showRMenu("root", event.clientX, event.clientY);
} else if (treeNode && !treeNode.noR) {
zTree.selectNode(treeNode);
showRMenu("node", event.clientX, event.clientY);
}
}
function showRMenu(type, x, y) {
$("#rMenu ul").show();
if (type=="root") {
$("#m_del").hide();
$("#m_check").hide();
$("#m_unCheck").hide();
} else {
$("#m_del").show();
$("#m_check").show();
$("#m_unCheck").show();
}
rMenu.css({"top":y+"px", "left":x+"px", "visibility":"visible"});
$("body").bind("mousedown", onBodyMouseDown);
}
function hideRMenu() {
if (rMenu) rMenu.css({"visibility": "hidden"});
$("body").unbind("mousedown", onBodyMouseDown);
}
function onBodyMouseDown(event){
if (!(event.target.id == "rMenu" || $(event.target).parents("#rMenu").length>0)) {
rMenu.css({"visibility" : "hidden"});
}
}
var addCount = 1;
function addTreeNode() {
hideRMenu();
var newNode = { name:"newNode " + (addCount++)};
if (zTree.getSelectedNodes()[0]) {
newNode.checked = zTree.getSelectedNodes()[0].checked;
zTree.addNodes(zTree.getSelectedNodes()[0], newNode);
} else {
zTree.addNodes(null, newNode);
}
}
function removeTreeNode() {
hideRMenu();
var nodes = zTree.getSelectedNodes();
if (nodes && nodes.length>0) {
if (nodes[0].children && nodes[0].children.length > 0) {
var msg = "If you delete this node will be deleted along with sub-nodes. \n\nPlease confirm!";
if (confirm(msg)==true){
zTree.removeNode(nodes[0]);
}
} else {
zTree.removeNode(nodes[0]);
}
}
}
function editTreeNode() {
var nodes = zTree.getSelectedNodes();
if (nodes && nodes.length>0) {
zTree.editName(nodes[0]);
}
hideRMenu();
}
function resetTree() {
hideRMenu();
$.fn.zTree.init($("#treeDemo"), setting, zNodes);
}
function dropPrev(treeId, nodes, targetNode) {
var pNode = targetNode.getParentNode();
if (pNode && pNode.dropInner === false) {
return false;
} else {
for (var i=0,l=curDragNodes.length; i<l; i++) {
var curPNode = curDragNodes[i].getParentNode();
if (curPNode && curPNode !== targetNode.getParentNode() && curPNode.childOuter === false) {
return false;
}
}
}
return true;
}
function dropInner(treeId, nodes, targetNode) {
if (targetNode && targetNode.dropInner === false) {
return false;
} else {
for (var i=0,l=curDragNodes.length; i<l; i++) {
if (!targetNode && curDragNodes[i].dropRoot === false) {
return false;
} else if (curDragNodes[i].parentTId && curDragNodes[i].getParentNode() !== targetNode && curDragNodes[i].getParentNode().childOuter === false) {
return false;
}
}
}
return true;
}
function dropNext(treeId, nodes, targetNode) {
var pNode = targetNode.getParentNode();
if (pNode && pNode.dropInner === false) {
return false;
} else {
for (var i=0,l=curDragNodes.length; i<l; i++) {
var curPNode = curDragNodes[i].getParentNode();
if (curPNode && curPNode !== targetNode.getParentNode() && curPNode.childOuter === false) {
return false;
}
}
}
return true;
}
var log, className = "dark", curDragNodes, autoExpandNode;
function beforeDrag(treeId, treeNodes) {
className = (className === "dark" ? "":"dark");
showLog("[ "+getTime()+" beforeDrag ] drag: " + treeNodes.length + " nodes." );
for (var i=0,l=treeNodes.length; i<l; i++) {
if (treeNodes[i].drag === false) {
curDragNodes = null;
return false;
} else if (treeNodes[i].parentTId && treeNodes[i].getParentNode().childDrag === false) {
curDragNodes = null;
return false;
}
}
curDragNodes = treeNodes;
return true;
}
function beforeDragOpen(treeId, treeNode) {
autoExpandNode = treeNode;
return true;
}
function beforeDrop(treeId, treeNodes, targetNode, moveType, isCopy) {
className = (className === "dark" ? "":"dark");
showLog("[ "+getTime()+" beforeDrop ] moveType:" + moveType);
showLog("target: " + (targetNode ? targetNode.name : "root") + " -- is "+ (isCopy==null? "cancel" : isCopy ? "copy" : "move"));
return true;
}
function onDrag(event, treeId, treeNodes) {
className = (className === "dark" ? "":"dark");
showLog("[ "+getTime()+" onDrag ] drag: " + treeNodes.length + " nodes." );
}
function onDrop(event, treeId, treeNodes, targetNode, moveType, isCopy) {
className = (className === "dark" ? "":"dark");
showLog("[ "+getTime()+" onDrop ] moveType:" + moveType);
showLog("target: " + (targetNode ? targetNode.name : "root") + " -- is "+ (isCopy==null? "cancel" : isCopy ? "copy" : "move"))
}
function onExpand(event, treeId, treeNode) {
if (treeNode === autoExpandNode) {
className = (className === "dark" ? "":"dark");
showLog("[ "+getTime()+" onExpand ] " + treeNode.name);
}
}
function showLog(str) {
if (!log) log = $("#log");
log.append("<li class='"+className+"'>"+str+"</li>");
if(log.children("li").length > 8) {
log.get(0).removeChild(log.children("li")[0]);
}
}
function getTime() {
var now= new Date(),
h=now.getHours(),
m=now.getMinutes(),
s=now.getSeconds(),
ms=now.getMilliseconds();
return (h+":"+m+":"+s+ " " +ms);
}
var zTree, rMenu;
$(document).ready(function(){
jQuery.ajax({
type: "post",
url: "/manager/menu/init.json",
dataType: "json",
success: function(result){
zNodes.push($.parseJSON(result.data.menuData));
$.fn.zTree.init($("#treeDemo"), setting, zNodes);
zTree = $.fn.zTree.getZTreeObj("treeDemo");
rMenu = $("#rMenu");
}
,
error: function (XMLHttpRequest, textStatus, errorThrown){
alert(errorThrown);
}
});
});
function doSave() {
zTree = $.fn.zTree.getZTreeObj("treeDemo");
var jsonData = JSON.stringify(zTree.getNodes()[0]);
jQuery.ajax({
type: "post",
url: "<%=basePath%>menu/save.htm",
data:{
"menuData": jsonData
},
dataType: "json",
success: function(result){
if(result.data.success) {
jQuery.ajax({
type: "post",
url: "<%=basePath%>menu/init.json",
dataType: "json",
success: function(result){
alert("修改菜单项成功!");
zNodes.push($.parseJSON(result.data.menuData));
$.fn.zTree.init(zTree, setting, zNodes);
},
error: function (XMLHttpRequest, textStatus, errorThrown){
alert(errorThrown);
}
});
};
}
,
error: function (XMLHttpRequest, textStatus, errorThrown){
alert(errorThrown);
}
});
return false;
}
<file_sep>require('../bower_components/Swiper/dist/css/swiper.min.css');
require('../less/class-community-list.less');
$(function () {
var contentHeight = $('body').height() - 420;
$('.content').height(contentHeight);
$('.content-item p').css('-webkit-line-clamp', Math.floor((contentHeight - 80) / 24) + '');
$('.loading').hide();
var $contentItem = $('.content-item');
var swiper = new Swiper('.swiper-container', {
pagination: '.swiper-pagination',
effect: 'coverflow',
grabCursor: true,
centeredSlides: true,
slidesPerView: 2,
coverflow: {
rotate: 50,
stretch: 0,
depth: 100,
modifier: 1,
slideShadows: true
},
onTransitionEnd: function (swiper) {
$contentItem.hide();
$contentItem.eq(swiper.activeIndex).show();
}
});
//滚动新闻
setInterval(function() {
$('.scroll-div ul').animate({
marginTop: '-50px'
}, 1000, function () {
$(this).css({marginTop: '0px'}).find('li:first').appendTo(this);
});
}, 3000);
});
<file_sep>package com.goldskyer.gmxx.common.entities;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.EnumType;
import javax.persistence.Enumerated;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
import org.hibernate.annotations.GenericGenerator;
import com.goldskyer.gmxx.common.enums.MessageStatus;
@Entity
@Table(name = "message")
public class Message
{
@Id
@Column(name = "ID", length = 40)
@GeneratedValue(generator = "idGenerator")
@GenericGenerator(name = "idGenerator", strategy = "uuid")
private String id;
private String sendId;
private String recvId;
private String textId;
@Enumerated(EnumType.STRING)
private MessageStatus status; //已读、未读
public String getId()
{
return id;
}
public void setId(String id)
{
this.id = id;
}
public String getSendId()
{
return sendId;
}
public void setSendId(String sendId)
{
this.sendId = sendId;
}
public String getRecvId()
{
return recvId;
}
public void setRecvId(String recvId)
{
this.recvId = recvId;
}
public String getTextId()
{
return textId;
}
public void setTextId(String textId)
{
this.textId = textId;
}
public MessageStatus getStatus()
{
return status;
}
public void setStatus(MessageStatus status)
{
this.status = status;
}
}
<file_sep>package com.goldskyer.scorecloud.constant;
public class GradeCosntant
{
public static final int ACTIVE = 1;
public static final int ARCHIVE = 2;
}
<file_sep>$(function() {
$('.choose_account').bind("click",function(){
$(".choose_account").removeClass("poped");
$(this).addClass("poped");
$.jBox("iframe:/manager/user/dialog/list.htm", {
title: "选择用户",
id:"chooseAccountDialog",
width: 800,
height: 450,
buttons: { }
});
});
$("#add-detail").bind(
"click",
function() {
$(".panel-footer").before($(".detail-wrap-temp").html());
$('form').find('.detail-wrap').show();
});
// 点击隐藏标签
$(".btn-close-detail").live("click", function() {
if ($(this).parents('#addForm').find('.purchase-detail').length <= 2) {
showInfo("warning", "请至少保留一个开始节点和一个结束节点")
} else {
$(this).parents('.detail-wrap').remove();
}
});
/**
* Menu表单校验
*/
$('#addForm').validate({
rules : {
name : {
required : true
},
objectType : {
required : true
}
},
messages : {
name : {
required : "模板名"
},
objectType : {
required : "适用类型不能为空"
}
},
showErrors : function(errorMap, errorList) {
var element = this.currentElements;
if (element.next().hasClass('popover')) {
element.popover('destroy');
}
this.defaultShowErrors();
},
submitHandler : function(form) { // 表单提交句柄,为一回调函数,带一个参数:form
$(form).ajaxSubmit({
type : "post",
url : "modify.json",
success : function(data) {
if (data.result == "success") {
window.location.href = "list.htm";
} else {
alert(data.msg);
}
}
});
},
});
});
<file_sep>package com.goldskyer.gmxx.utils;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import org.apache.commons.io.IOUtils;
import com.goldskyer.common.utils.HttpUtil;
public class PicDownload
{
public static void main(String[] args) throws FileNotFoundException, IOException, Exception
{
for (int i = 0; i < 179; i++)
{
String index = String.valueOf(i);
if (index.length() < 2)
{
index = "0" + index;
}
IOUtils.copy(HttpUtil.getInputStreamFromURL("http://sucai.heima.com/sucai/head/picqq/" + index + ".gif"),
new FileOutputStream("/data/pics/" + index + ".gif"));
}
}
}
<file_sep>package com.goldskyer.gmxx.acl.entities;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
import org.hibernate.annotations.GenericGenerator;
@Entity
@Table(name = "role_menu")
public class RoleMenu
{
@Id
@Column(name = "ID", length = 40)
@GeneratedValue(generator = "idGenerator")
@GenericGenerator(name = "idGenerator", strategy = "uuid")
private String id;
private String roleId;
private String menuId;
public String getId()
{
return id;
}
public void setId(String id)
{
this.id = id;
}
public String getRoleId()
{
return roleId;
}
public void setRoleId(String roleId)
{
this.roleId = roleId;
}
public String getMenuId()
{
return menuId;
}
public void setMenuId(String menuId)
{
this.menuId = menuId;
}
}
<file_sep>package com.goldskyer.scorecloud.entities;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
import org.hibernate.annotations.GenericGenerator;
@Entity
@Table(name = "tb_option")
public class Option implements SchoolId
{
@Id
@Column(name = "ID", length = 40)
@GeneratedValue(generator = "idGenerator")
@GenericGenerator(name = "idGenerator", strategy = "uuid")
private String id;
private String optionName;
private int weight;
private boolean showTip;//显示请选择
private String tip;
private String innerCode;
private String schId;
public String getSchId()
{
return schId;
}
public void setSchId(String schId)
{
this.schId = schId;
}
public String getId()
{
return id;
}
public void setId(String id)
{
this.id = id;
}
public String getOptionName()
{
return optionName;
}
public void setOptionName(String optionName)
{
this.optionName = optionName;
}
public int getWeight()
{
return weight;
}
public void setWeight(int weight)
{
this.weight = weight;
}
public boolean isShowTip()
{
return showTip;
}
public void setShowTip(boolean showTip)
{
this.showTip = showTip;
}
public String getTip()
{
return tip;
}
public void setTip(String tip)
{
this.tip = tip;
}
public String getInnerCode()
{
return innerCode;
}
public void setInnerCode(String innerCode)
{
this.innerCode = innerCode;
}
}
<file_sep>package com.goldskyer.gmxx.common.controllers;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
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.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import com.goldskyer.core.dto.JsonData;
import com.goldskyer.core.utils.WebUtils;
import com.goldskyer.gmxx.BaseController;
import com.goldskyer.gmxx.common.entities.LiveVideo;
import com.goldskyer.gmxx.common.service.LiveVideoService;
@Controller
@RequestMapping("/liveVideo")
public class LiveVideoController extends BaseController
{
@Autowired
private LiveVideoService liveVideoService;
@RequestMapping("/list.htm")
public Object getLiveVideos(HttpServletRequest request, HttpServletResponse response)
{
List<LiveVideo> liveVideos = liveVideoService.queryLiveVideos();
StringBuilder sb = new StringBuilder();
for (LiveVideo lv : liveVideos)
{
sb.append(lv.getIp());
}
WebUtils.renderText(request, response, sb.toString(), null);
return null;
}
@RequestMapping(value = "/checkAuthCode.json", produces = "application/json")
@ResponseBody
public JsonData checkAuthCode(@RequestParam String blogId, @RequestParam String authCode,
HttpServletRequest request)
{
if (liveVideoService.checkAuthCode(blogId, authCode))
{
request.getSession().setAttribute("blogId", blogId);
return JsonData.success();
}
else
{
return JsonData.failure();
}
}
}
<file_sep>package com.goldskyer.gmxx.promotion.service;
import com.goldskyer.gmxx.promotion.dtos.ApplyAwardDto;
import com.goldskyer.gmxx.promotion.entities.AwardRecord;
public interface AwardService {
public AwardRecord doAward(ApplyAwardDto applyAwardDto) ;
}
<file_sep>require('../bower_components/font-awesome/css/font-awesome.min.css');
require('../bower_components/pure/pure-min.css');
require('../bower_components/Swiper/dist/css/swiper.min.css');
require('../less/index.less');
$(function() {
setTimeout(function(){
$('.loading').hide();
}, 3000);
// 百度地图API功能
var map = new BMap.Map("allmap"); // 创建Map实例
map.centerAndZoom(new BMap.Point(116.404, 39.915), 11); // 初始化地图,设置中心点坐标和地图级别
map.addControl(new BMap.MapTypeControl()); //添加地图类型控件
map.setCurrentCity("北京"); // 设置地图显示的城市 此项是必须设置的
map.enableScrollWheelZoom(true); //开启鼠标滚轮缩放
});
<file_sep>require('../less/detail-cmt.less');
require('../js/lib/widget/navigator.iscroll.js');
var Fingerprint = require('../bower_components/fingerprint/fingerprint.js');
var clickElement;
$(function() {
$('.video-js').attr('webkit-playsinline', 'true');
$('.loading').hide();
getVoteStatus();
getCommentList();
$('.write-cmt').on('click', function(){
if ($('.sendCmt').css("display") == 'none') {
$('.sendCmt').css("display", "block");
$('.icon_cmt_gray').css("display", "none");
$('.cancel-cmt').css("display", "block");
} else {
$('.sendCmt').css("display", "none");
$('.cancel-cmt').css("display", "none");
$('.icon_cmt_gray').css("display", "block");
}
});
$('.icon_praise_gray').on('click', function(){
var fingerprint = new Fingerprint().get();
var objectIdValue = $('.objectId').text();
clickElement = $(this);
$.ajax({
type: "GET",
url: "http://gmxx.goldskyer.com/front/blog/voteUp.json",
data: {
accountId: fingerprint,
objectId: objectIdValue,
objectType: "BLOG",
fp: fingerprint
},
dataType: "json",
success: function (data) {
if (data.result == "success") {
clickElement.attr('class',"icon_praise_red");
var currentlikenum = parseInt($('.likeNum').html());
$('.likeNum').html(currentlikenum + 1);
};
},
error: function () {
clickElement.attr('class',"icon_praise_gray");
}
});
});
$(".button").on('click', function() {
var info = $(".input-txt").val();
if ($.trim(info) != '') {
var name = new Fingerprint().get();
var objectid = $('.objectId').text();
$.ajax({
type: "GET",
url: "http://gmxx.goldskyer.com/comment/add.json",
data: {
accountId: name,
objectId: objectid,
content: info,
objectType:"BLOG"
},
dataType: "json",
success: function(data){
var hc_list = "<div class='hc_list'>";
hc_list += "<div class='hc_left'>";
hc_list += "<img class='hc_img' src='/images/icons/avatar.jpg' >";
hc_list += "</div>";
hc_list += "<div class='hc_right'>";
hc_list += "<div class='hc_name'>" + data.data.comment.accountId + "</div>";
hc_list += "<div class='hc_info'>" + data.data.comment.content + "</div>";
hc_list += "<div class='hc_time'>" + data.data.comment.createDate + "</div>";
hc_list += "</div></div>";
$(".history_comment").prepend(hc_list);
},
error: function () {
return;
}
});
$(".input-txt").val('');
}
});
$(".input-txt").change(function(){
if($.trim(this.value) == "" ) {
$(".button").attr("disabled","disabled");
}
else {
$(".button").removeAttr("disabled");
}
});
$('.loadmore-div').on('click', function(){//加载更多评论
loadMoreData();
});
});
function getVoteStatus(){//获取点赞状态
var fingerprint = new Fingerprint().get();
var objectIdValue = $('.objectId').text();
$.ajax({
type: "GET",
url: "http://gmxx.goldskyer.com/voteUp/queryStatus.json",
data: {
accountId: fingerprint,
objectId: objectIdValue,
objectType: "BLOG",
fp: fingerprint
},
dataType: "json",
success: function (data) {
if (data.result == "failure") {
$(".icon_praise_gray").attr('class', "icon_praise_red");
}
},
error: function () {
$(".icon_praise_gray").attr('class', "icon_praise_gray");
}
});
};
function getCommentList(){//获取评论列表
var objectid = $('.objectId').text();
var pageNo = 1;
$.ajax({
type: "GET",
url: "http://gmxx.goldskyer.com/comment/list.json",
data: {
objectId: objectid,
objectType:"BLOG",
pageNo:pageNo
},
dataType: "json",
success: function(data){
var comments = data.data.comments;
for (var i = 0; i < comments.length; i++) {
var comment = comments[i];
var hc_list = "<div class='hc_list'>";
hc_list += "<div class='hc_left'>";
hc_list += "<img class='hc_img' src='/images/icons/avatar.jpg' >";
hc_list += "</div>";
hc_list += "<div class='hc_right'>";
hc_list += "<div class='hc_name'>" + comment.accountId + "</div>";
hc_list += "<div class='hc_info'>" + comment.content + "</div>";
hc_list += "<div class='hc_time'>" + comment.createDate + "</div>";
hc_list += "</div></div>";
$(".history_comment").prepend(hc_list);
}
var totalcnt = data.data.count;
//当totalcnt - 当前currentcnt >= 10,则加载刷新展现
if (totalcnt - pageNo * 10 > 0) {
$(".loadmore-div").css("display", "block");//展示
$(".loadmore-p").css("display", "block");
$(".loadmore-img").css("display", "none");
}else{//否则不现实加载刷新
$(".loadmore-div").css("display", "none");
}
$(".pageNo").text(pageNo + 1);
},
error: function () {
$(".loadmore-div").css("display", "none");
}
});
};
function loadMoreData() {
$('.loadmore-p').css("display", "none");
$('.loadmore-img').css("display", "block");
var pageNo = $(".pageNo").text();
var objectid = $('.objectId').text();
$.ajax({
type: "GET",
url: "http://gmxx.goldskyer.com/comment/list.json",
data: {
objectId: objectid,
objectType:"BLOG",
pageNo:pageNo
},
dataType: "json",
success: function(data){
var comments = data.data.comments;
var totalcnt = data.data.count;
for (var i = 0; i < comments.length; i++) {
var comment = comments[i];
var hc_list = "<div class='hc_list'>";
hc_list += "<div class='hc_left'>";
hc_list += "<img class='hc_img' src='/images/icons/avatar.jpg' >";
hc_list += "</div>";
hc_list += "<div class='hc_right'>";
hc_list += "<div class='hc_name'>" + comment.accountId + "</div>";
hc_list += "<div class='hc_info'>" + comment.content + "</div>";
hc_list += "<div class='hc_time'>" + comment.createDate + "</div>";
hc_list += "</div></div>";
$(".history_comment").prepend(hc_list);
}
//当totalcnt - 如果currentcnt >= 10,则加载刷新展现
if (totalcnt - pageNo * 10 > 0) {
$(".loadmore-div").css("display", "block");//展示
$(".loadmore-p").css("display", "block");
$(".loadmore-img").css("display", "none");
}else{//否则不现实加载刷新
$(".loadmore-div").css("display", "none");
}
$(".pageNo").text(pageNo + 1);
},
error: function () {
$(".loadmore-p").css("display", "block");
$(".loadmore-img").css("display", "none");
}
});
};
<file_sep>package com.goldskyer.gmxx.common.service.impl;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.support.SimpleCacheManager;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.goldskyer.common.exceptions.BusinessException;
import com.goldskyer.core.dao.BaseDao;
import com.goldskyer.core.dto.EnvParameter;
import com.goldskyer.core.entities.Account;
import com.goldskyer.core.entities.Blog;
import com.goldskyer.core.service.AccountService;
import com.goldskyer.gmxx.acl.entities.Role;
import com.goldskyer.gmxx.acl.service.AclService;
import com.goldskyer.gmxx.common.dtos.CreateTaskDto;
import com.goldskyer.gmxx.common.entities.MessageText;
import com.goldskyer.gmxx.common.entities.WorkFlowData;
import com.goldskyer.gmxx.common.entities.WorkFlowNode;
import com.goldskyer.gmxx.common.entities.WorkFlowTask;
import com.goldskyer.gmxx.common.entities.WorkFlowTemplate;
import com.goldskyer.gmxx.common.enums.MessageType;
import com.goldskyer.gmxx.common.enums.WorkFlowAuditEvent;
import com.goldskyer.gmxx.common.service.AttachmentService;
import com.goldskyer.gmxx.common.service.MessageService;
import com.goldskyer.gmxx.common.service.WorkFlowNodeService;
import com.goldskyer.gmxx.common.service.WorkFlowService;
import com.goldskyer.gmxx.workflow.vo.AuditVo;
import com.goldskyer.gmxx.workflow.vo.WorkflowDataVo;
@Service
@SuppressWarnings(
{ "rawtypes", "unchecked" })
public class WorkFlowServiceImpl implements WorkFlowService
{
private static final Log log = LogFactory.getLog(WorkFlowServiceImpl.class);
@Autowired
private SimpleCacheManager cacheManager;
@Autowired
private AccountService accountService;
@Autowired
private AclService aclService;
@Autowired
private BaseDao baseDao;
@Autowired
private WorkFlowNodeService workFlowNodeService;
@Autowired
private AttachmentService attachmentService;
@Autowired
private MessageService messageService;
public WorkFlowTask queryTaskByObjectId(String objectId)
{
return (WorkFlowTask) baseDao.queryUnique("from WorkFlowTask where objectId=?", objectId);
}
@Override
public List<WorkFlowTask> getMyTasks(String accountId)
{
Map map = new HashMap<>();
map.put("accountId", accountId);
map.put("roleIds", getMyRangeNodeIds(accountId));
List<String> nodeIds = baseDao
.query("select id from WorkFlowNode where accountId=:accountId or roleId in :roleIds and isEnd=false",
map);
Map paramMap = new HashMap<>();
paramMap.put("nodeIds", nodeIds);
return baseDao.query("from WorkFlowTask where workFlowNodeNodeId in :nodeIds order by createDate desc",
paramMap);
}
/**
* 我的任务
* 申请人,申请类型,子类型,申请时间,当前状态
* @param accountId
* @return
*/
public List<String> getMyRangeNodeIds(String accountId)
{
List<Role> roles = aclService.queryRolesByUser(accountId);
List<String> roleIds = new ArrayList<String>();
for (Role r : roles)
{
roleIds.add(r.getId());
}
roleIds.add("empty");
Map map = new HashMap<>();
map.put("accountId", accountId);
map.put("roleIds", roleIds);
return baseDao
.query("select id from WorkFlowNode where (accountId = :accountId or role in (:roleIds) )", map);
}
@Override
public List<WorkFlowTask> getMyTasks(String accountId, String objectType)
{
Map map = new HashMap<>();
map.put("accountId", accountId);
map.put("roleIds", getMyRangeNodeIds(accountId));
List<String> nodeIds = baseDao.query(
"select id from WorkFlowNode where (accountId = :accountId or role in :roleIds)",
map);
Map paramMap = new HashMap<>();
nodeIds.add("empty");
paramMap.put("nodeIds", nodeIds);
paramMap.put("objectType", objectType);
return baseDao.query(
"from WorkFlowTask where objectType=:objectType and nodeId in :nodeIds order by createDate desc",
paramMap);
}
/**
* 判断是否有该流程的操作权限
* @param task
* @param accountId
* @return
*/
public boolean ifCanOperationTask(WorkFlowTask task, String accountId)
{
if (task.isFinished())
{
return false; //流程结束,操作关闭
}
WorkFlowNode node = baseDao.query(WorkFlowNode.class, task.getNodeId());
if (node != null && (accountId.equals(node.getAccountId()) || aclService.ifHasRole(accountId, node.getRole())))
{
return true;
}
return false;
}
/**
* 执行审核操作
* 如果发表评论的话,fromStatus和toStatus和审核通过一样,只是task中的状态无任何变化
*/
@Transactional
public void signal(AuditVo auditVo)
{
Account account = accountService.getAccountById(auditVo.getAccountId());
// TODO Auto-generated method stub
WorkFlowTask task = baseDao.query(WorkFlowTask.class, auditVo.getTaskId());
WorkFlowNode node = baseDao.query(WorkFlowNode.class, task.getNodeId());
WorkFlowNode nextNode = workFlowNodeService.queryNextNode(node);
if (ifCanOperationTask(task, auditVo.getAccountId()) || auditVo.getEventType() == WorkFlowAuditEvent.REVOKE
|| auditVo.getEventType() == WorkFlowAuditEvent.COMMENT)
{
//判断能否回收,已结束的流程不能回收
if (auditVo.getEventType() == WorkFlowAuditEvent.REVOKE && task.isFinished())
{
throw new BusinessException("已经结束的流程无法回收");
}
if (auditVo.getEventType() == WorkFlowAuditEvent.APPROVE
|| auditVo.getEventType() == WorkFlowAuditEvent.CREATE)//节点审核通过
{
task.setNodeId(node.getNextId());
task.setUpdateDate(new Date());
task.setFinished(nextNode == null);
if (task.isFinished())
{
task.setStatus("审核通过");
if (task.getObjectType().equals("内容审核"))
{
final Blog blog = baseDao.query(Blog.class, task.getObjectId());
blog.setAuditStatus("审核通过");
blog.setNeedLogin(false);//SPE:审核后的内容都是对外开放的。
baseDao.modify(blog);
cacheManager.getCache("blog").clear();//刷新blog的缓存
new Thread(new Runnable() {
@Override
public void run()
{
try{
MessageText messageText = new MessageText();
messageText.setType(MessageType.系统消息);
messageText.setText("用户 " + blog.getAuthor() + "发布 " + blog.getTitle()
+ ",<a target='_blank' href='/web/spring/blog/view.htm?id=" + blog.getId() + "' >点此查看</a>");
messageText.setTitle("栏目 " + blog.getType()
+ "新发布 <a target='_blank' href='/web/spring/blog/view.htm?id=" + blog.getId()
+ "' >" + blog.getTitle() + "</a>");
List<String> toAccountIds = accountService
.queryAllValidAccountIds(blog.getDomain());
messageText.setBlogId(blog.getId());
messageService.sendMessage(messageText, blog.getAccountId(), toAccountIds);
}
catch (Exception e)
{
log.fatal("发送消息失败" + e.getMessage(), e);
}
}
}).start();
}
}
else
{
if (task.getObjectType().equals("内容审核"))
{
Blog blog = baseDao.query(Blog.class, task.getObjectId());
blog.setAuditStatus(nextNode.getStatus());
baseDao.modify(blog);
}
task.setStatus(nextNode.getStatus());
}
baseDao.modify(task);
}
else if (auditVo.getEventType() == WorkFlowAuditEvent.REJECT
|| auditVo.getEventType() == WorkFlowAuditEvent.REVOKE)
{
task.setFinished(true);
task.setNodeId(null);
if (auditVo.getEventType() == WorkFlowAuditEvent.REJECT)
{
if (task.getObjectType().equals("内容审核"))
{
Blog blog = baseDao.query(Blog.class, task.getObjectId());
blog.setAuditStatus("已拒绝");
baseDao.modify(blog);
}
task.setStatus("已拒绝");
}
else if (auditVo.getEventType() == WorkFlowAuditEvent.REVOKE)
{
if (task.getObjectType().equals("内容审核"))
{
Blog blog = baseDao.query(Blog.class, task.getObjectId());
blog.setAuditStatus("已回收");
baseDao.modify(blog);
}
task.setStatus("已回收");
}
task.setUpdateDate(new Date());
baseDao.modify(task);
}
//审核数据
WorkFlowData data = new WorkFlowData();
data.setEventType(auditVo.getEventType());
if (auditVo.getEventType() == WorkFlowAuditEvent.APPROVE)
{
data.setEventNote(account.getNickname() + "同意了审核");
}
else if (auditVo.getEventType() == WorkFlowAuditEvent.REJECT)
{
data.setEventNote(account.getNickname() + "拒绝了审核");
}
else if (auditVo.getEventType() == WorkFlowAuditEvent.CREATE)
{
data.setEventNote(account.getNickname() + "新建了流程");
}
else if (auditVo.getEventType() == WorkFlowAuditEvent.REVOKE)
{
data.setEventNote(account.getNickname() + "回收了流程");
}
else if (auditVo.getEventType() == WorkFlowAuditEvent.COMMENT)
{
data.setEventNote(account.getNickname() + "发布了一条评论");
}
data.setNote(auditVo.getNote());
data.setComment(auditVo.getComment());
data.setPicUrl(auditVo.getPicUrl());
data.setAccountId(auditVo.getAccountId());
data.setFromStatus(node.getStatus());
if (nextNode != null)
{
data.setToStatus(nextNode.getStatus());
}
data.setObjectId(task.getObjectId());
data.setObjectType(task.getObjectType());
baseDao.add(data);//添加审核数据
if (!StringUtils.equalsIgnoreCase(auditVo.getAccountId(), task.getApplyAccountId()))//非自己账号则发送站内信
{
MessageText text = new MessageText();
text.setTitle(data.getEventNote());
text.setText("流程事件:" + data.getEventNote() + ";评论或意见:" + data.getNote());
text.setType(MessageType.流程消息);
messageService.sendMessage(text, auditVo.getAccountId(), task.getApplyAccountId());
}
}
else
{
throw new BusinessException("当前用户没权限处理该任务");
}
}
public WorkFlowTemplate queryTemplateByObjectType(String objecType, String subType, String domain)
{
if (StringUtils.isBlank(subType))
{
return (WorkFlowTemplate) baseDao.queryUnique(
"from WorkFlowTemplate where objectType=? and domain=?", objecType, domain);
}
else
{
return (WorkFlowTemplate) baseDao.queryUnique(
"from WorkFlowTemplate where objectType=? and subType=? and domain=?", objecType, subType, domain);
}
}
/**
*
*/
@Transactional
public void createTask(CreateTaskDto createTaskDto)
{
Account account = accountService.getAccountById(createTaskDto.getAccountId());
WorkFlowTemplate template = queryTemplateByObjectType(createTaskDto.getObjectType(), createTaskDto.getSubType(),
EnvParameter.get().getDomain());
if (template == null)
throw new BusinessException("不存在流程对应的模板:templateName" + createTaskDto.getObjectType());
WorkFlowNode startNode = workFlowNodeService.queryStartNode(template.getId());
if (startNode == null)
throw new BusinessException("流程模板未配置起始节点");
// WorkFlowNode nextNode=workFlowNodeService.queryNextNode(workFlowNode);
// //
// WorkFlowData data = new WorkFlowData();
// data.setAccountId(accountId);
// data.setFromStatus(workFlowNode.getStatus());
// data.setToStatus(nextNode.getStatus());
// data.setObjectId(blogId);
// data.setObjectType(objectType);
// baseDao.add(data);
//创建任务
WorkFlowTask task = new WorkFlowTask();
task.setTaskName(createTaskDto.getTaskName());
task.setApplyAccountId(account.getId());
task.setApplyName(account.getNickname());
task.setObjectId(createTaskDto.getObjectId());
task.setObjectType(createTaskDto.getObjectType());
task.setSubType(createTaskDto.getSubType());
task.setFinished(false);
task.setCreateDate(new Date());
task.setNodeId(startNode.getId());
baseDao.add(task);
//构建audit
AuditVo auditVo = new AuditVo();
auditVo.setAccountId(createTaskDto.getAccountId());
auditVo.setTaskId(task.getId());
auditVo.setEventType(WorkFlowAuditEvent.CREATE);
signal(auditVo);
}
@Override
public List<WorkFlowData> queryWorkFlowDataHis(String objectId, String objectType)
{
List<WorkFlowData> datas = baseDao.query("from WorkFlowData where objectId=? order by createDate,id", objectId);
return datas;
}
public List<WorkflowDataVo> queryWorkFlowDataVo(String objectId)
{
List<WorkflowDataVo> vos = new ArrayList<>();
List<Object[]> datas = baseDao.query(
"select a.accountId,a.createDate ,a.eventType ,a.note,b.nickname,a.picUrl,a.eventNote,t.taskName from WorkFlowData a,Account b,WorkFlowTask t where a.accountId=b.id and t.objectId=a.objectId and a.objectId=? order by a.createDate,a.id",
objectId);
for (Object[] data : datas)
{
WorkflowDataVo vo = new WorkflowDataVo();
vo.setAccountId(String.valueOf(data[0]));
vo.setCreateDate((Date) data[1]);
if (data[2] != null)
vo.setEventType(data[2].toString());
if (data[3] != null)
vo.setNote(data[3].toString());
if (data[4] != null)
vo.setNickName(data[4].toString());
if (data[5] != null)
{
vo.setPicAttachs(attachmentService.queryImagesAttachmentsByPicUrl(data[5].toString()));
vo.setOtherAttachs(attachmentService.queryOtherAttachmentsByPicUrl(data[5].toString()));
}
if (data[6] != null)
vo.setEventNote(data[6].toString());
if (data[7] != null)
vo.setTaskName(data[7].toString());
vos.add(vo);
}
return vos;
}
}
<file_sep>package com.goldskyer.gmxx.front.controllers;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;
import com.goldskyer.core.entities.Blog;
import com.goldskyer.core.entities.Menu;
import com.goldskyer.gmxx.common.constants.GmxxConstant;
//@Controller
//@RequestMapping("/front/teacher")
public class TeacherController extends BlogController{
@RequestMapping("/view.htm")
public ModelAndView detail(@RequestParam String id)
{
ModelAndView mv = new ModelAndView("/front/teacher/view");
Blog blog = blogService.queryBlog(id);
Menu menu = cachedMenuService.queryMenuByName(blog.getType());
mv.addObject("mainMenu", cachedMenuService.getMainMenu());
mv.addObject("menu", menu);
mv.addObject("blog",blog);
return mv;
}
@RequestMapping("/list.htm")
public ModelAndView list(@RequestParam String blogType,@RequestParam(required=false) Integer pageNum)
{
ModelAndView mv = new ModelAndView("/front/teacher/list");
blogBusiness.buildCommonBlogListModel(mv, blogType, pageNum, Integer.valueOf(iniService.getIniValue(GmxxConstant.PAGE_SIZE)));
return mv;
}
}
<file_sep>
var setting = {
check : {
enable : true
},
data : {
simpleData : {
enable : true
}
}
};
var code;
function setCheck() {
var zTree = $.fn.zTree.getZTreeObj("treeDemo"), py = $("#py").attr(
"checked") ? "p" : "", sy = $("#sy").attr("checked") ? "s" : "", pn = $(
"#pn").attr("checked") ? "p" : "", sn = $("#sn").attr("checked") ? "s"
: "", type = {
"Y" : py + sy,
"N" : pn + sn
};
}
$(document).ready(function() {
// $.ajax({
// type : "post",
// url : "/manager/role/menu/init.json",
// dataType : "json",
// success : function(result) {
// $.fn.zTree.init($("#treeDemo"), setting, result.children);
// zTree = $.fn.zTree.getZTreeObj("treeDemo");
// zTree.expandAll(true);
// }
// });
$.fn.zTree.init($("#treeDemo"), setting, zData.children);
zTree = $.fn.zTree.getZTreeObj("treeDemo");
zTree.expandAll(true);
setCheck();
$("#py").bind("change", setCheck);
$("#sy").bind("change", setCheck);
$("#pn").bind("change", setCheck);
$("#sn").bind("change", setCheck);
}); | 01f1528b0f775b8031d1b60198c8f578a98210bf | [
"JavaScript",
"Java",
"Maven POM"
] | 120 | Java | einsteinstudio/scorecloud | b0b1660f0d58a5d98ff89da7bf62750c69d8b693 | 79333394ec8e508062b84102fbc4002461258bdf |
refs/heads/master | <repo_name>himcoder/examproject<file_sep>/addtest.php
<?php
function __autoload($classname)
{
include "$classname.php";
}
$obj = new connect();
$test = $obj->con();
if(isset($_POST['submit']))
{
$ins= new insert();
$ins->inserttest();
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Test ADD</title>
</head>
<body>
<fieldset>
<form method="POST" action="addtest.php">
<table>
<tr>
<td>
<select name = "subid">
<option>
Select Subject
</option>
<?php
$qry = "select * from subject ";
$run =mysqli_query($test,$qry);
//print_r($run);
//exit;
while($row = mysqli_fetch_assoc($run))
{
?>
<option value="<?php echo $row['subname']; ?>"><?php echo $row['subname']; ?></option>
<?php
}
?>
</select>
</td>
</tr>
<tr>
<td>
Enter Your Test Here:
</td>
<td>
<input type="text" name="test">
</td>
</tr>
<tr>
<td><input type="submit" name="submit" value="Save"></td>
</tr>
</table>
</fieldset>
</form>
</body>
</html><file_sep>/addques.php
<?php
function __autoload($classname)
{
include "$classname.php";
}
$obj = new connect();
$test = $obj->con();
if(isset($_POST['submit']))
{
$ins= new insert();
$ins->insertques();
}
?>
<!DOCTYPE html>
<html>
<head>
<title>
Question Add
</title>
</head>
<body>
<fieldset>
<form method="POST" action="addques.php">
<table>
<tr>
<td>
<select name = "testid">
<option>
Select Subject
</option>
<?php
$qry = "select * from test ";
$run =mysqli_query($test,$qry);
//print_r($run);
//exit;
while($row = mysqli_fetch_assoc($run))
{
?>
<option value="<?php echo $row['test']; ?>"><?php echo $row['test']; ?></option>
<?php
}
?>
</select>
</td>
</tr>
<tr>
<td>Enter Your Question Here:</td>
<td><input type="text" style="width:auto" style="height:100px" name="quesname"></input></td>
</tr>
<tr>
<td>Enter Answer 1</td>
<td><input type="text" style="width:auto" style="height:100px" name="answer1"></input></td>
</tr>
<tr>
<td>Enter Answer 2</td>
<td><input type="text" style="width:auto" style="height:100px" name="answer2"></input></td>
</tr>
<tr>
<td>Enter Answer 3</td>
<td><input type="text" style="width:auto" style="height:100px" name="answer3"></input></td>
</tr>
<tr>
<td>Enter Answer 4</td>
<td><input type="text" style="width:auto" style="height:100px" name="answer4"></input></td>
</tr>
<tr>
<td>True Answer</td>
<td><input type="text" style="width:auto" style="height:100px" name="correctanswer"></input></td>
</tr>
<tr>
<td><input type="submit" name="submit" value="submit"></td>
</tr>
</table>
</form>
</fieldset>
</body>
</html><file_sep>/RegisterRetrieve.php
<?php
function __autoload($classname)
{
include "$classname.php";
}
$obj = new connect();
$st=$obj->con();
//echo "Hello";
if (isset($_POST['sub'])) {
extract($_POST);
$line = implode(",",$_POST['lang']);
if(isset($_FILES['iname']))
{
echo "hello";
$name = $_FILES['iname']['name'];
$type = $_FILES['iname']['type'];
$size = $_FILES['iname']['size'];
$tmp_name = $_FILES['iname']['tmp_name'];
$loc = 'img/';
$ext = substr($name,strpos($name,'.')+1);
if($_FILES['iname']['size']>= '10000' || $_FILES['iname']['size']<="7000000")
{
//echo $size;
}
else{
// echo "size is not supported";
}
$val = $_FILES['iname']['size'];
if($ext == 'jpg' || $ext == 'png')
{
{
move_uploaded_file($tmp_name,$loc.$name);
}
}
}
$qry="update register SET uname='$uname',pwd='<PASSWORD>',emailid='$emailid',gen='$gen',lang='$line' ,mobile='$mobile',10marks='$marks_10',12marks='$marks_12',iname='$name',size='$size' WHERE id=$sid ";
print_r($qry);
//$this->con();
$res=mysqli_query($st,$qry);
print_r($res);
$upd= new update();
$upd->updatedata($_POST);
print_r($_POST);
//exit();
header("location:ShowData.php");
}
?><file_sep>/Examiner.php
<title>Examiner</title>
<?php
function __autoload($classname)
{
include "$classname.php";
}
$obj = new connect();
$st=$obj->con();
?>
<form method="POST" action="Examiner.php">
<select name = "testid">
<option>
Select TEST
</option>
<?php
$rel = "select * from test ";
$res =mysqli_query($st,$rel);
//print_r($run);
//exit;
while($row = mysqli_fetch_assoc($res))
{
?>
<option value="<?php echo $row['test']; ?>"><?php echo $row['test']; ?></option>
<?php
}
?>
</select>
<?php
$qry="select * from register";
$run=mysqli_query($st,$qry);
?>
<?php
while($query2=mysqli_fetch_assoc($run))
{
?>
<input type='checkbox' name='selected' value="<?php echo $query2['uname']; ?>"><?php echo $query2['uname']; ?><br>
<?php
}
?>
<input type="submit" name="submit" value="submit">
</form>
<?php
if (isset($_POST['submit']))
{
$ins= new insert();
$ins->insertexamees();
}
?>
<file_sep>/addsub.php
<!DOCTYPE html>
<html>
<head>
<title>Subject ADD</title>
</head>
<body>
<fieldset>
<form method="POST" action="addsub.php">
<table>
<tr>
<td>
Enter Your Subject:
</td>
<td>
<input type="text" name="subject">
</td>
</tr>
<tr>
<td>
<input type="submit" name="submit" value="Save">
</td>
</tr>
</table>
</form>
</fieldset>
</body>
</html>
<?php
function __autoload($classname)
{
include "$classname.php";
}
$obj = new connect();
$obj->con();
if(isset($_POST['submit']))
{
$ins= new insert();
$ins->insertsub();
}
?>
<file_sep>/ShowData.php
<?php
function __autoload($classname)
{
include "$classname.php";
}
$obj = new connect();
$st=$obj->con();
$start=0;
$limit=2;
$id="";
if(isset($_GET['id']))
{
$id=$_GET['id'];
$start=($id-1)*$limit;
}
$query=mysqli_query($st,"select * from register LIMIT $start,$limit");
//echo "<ul>";
echo '<table width="650px" align="center" border="1px">';
echo '<th>id</th><th>Username</th><th>Password</th><th>emailid</th><th>Gender</th><th>Language</th><th>Mobile</th><th>Marks 10th</th><th>Marks 12th</th><th>Image Name</th><th>Priority</th>';
echo "<form method='GET' action='Register_Update.php'>";
while($query2=mysqli_fetch_assoc($query))
{
?>
<tr><td><?php echo $query2['id']; ?></td>
<td><?php echo $query2['uname']; ?></td>
<td><?php echo $query2['pwd']; ?></td>
<td><?php echo $query2['emailid']; ?></td>
<td><?php echo $query2['gen'];?></td>
<td><?php echo $query2['lang'];?></td>
<td><?php echo $query2['mobile']; ?></td>
<td><?php echo $query2['10marks'];?></td>
<td><?php echo $query2['12marks'];?></td>
<td><?php echo $query2['iname'];?></td>
<td><?php echo $query2['priority']; ?></td>
<td><a href="Register_Update.php?id=<?php echo $query2['id']; ?>">EDIT</a></td>
</tr>
<?php
}
echo "</table>";
$rows=mysqli_num_rows(mysqli_query($st,"select * from register"));
$total=ceil($rows/$limit);
if($id>1)
{
echo "<a href='?id=".($id-1)."' class='button'>PREVIOUS</a>";
}
if($id!=$total)
{
echo "<a href='?id=".($id+1)."' class='button'>NEXT</a>";
}
?><file_sep>/delete.php
<?php
function deleteData($del)
{
extract($del);
$sql = "delete from new where id= $sid" ;
$result = mysqli_query($this->myconn,$sql);
return $result;
}
?><file_sep>/Register_Update.php
<title>Register Update</title>
<?php
//error_reporting(0);
function __autoload($classname)
{
include "$classname.php";
}
$obj = new connect();
$st=$obj->con();
$qry = "select * from register ";
$run = mysqli_query($st,$qry);
$row = mysqli_fetch_assoc($run);
{
$g = $row['gen'];
$l = $row['lang'];
}
$id=$_GET['id'];
$query=mysqli_query($st,"select * from register where id='$id'");
//echo "<ul>";
while($query2=mysqli_fetch_assoc($query))
{
?>
<form method='POST' action='RegisterRetrieve.php' enctype='multipart/form-data'>
<table>
<p><input type="hidden" name="sid" value="<?php echo $query2['id']; ?>"></p>
<tr>
<td>
First Name:
</td>
<td><input type="text" name="uname" value="<?php echo $query2['uname']; ?>"></td>
</tr>
<tr>
<td>Password:</td>
<td><input type="password" name="pwd" value="<?php echo $query2['pwd']; ?>"></td>
</tr>
<tr>
<td>Email Id:</td>
<td><input type="text" name="emailid" value="<?php echo $query2['emailid']; ?>"
</td>
</tr>
<tr>
<td>Radio Button: Are you male or female?</td>
<?php
if ($g == "male"){
echo "<td><input type='radio' name='gen' value='Male' id='gen' checked> Male <input type='radio' name='gen' value='Female' id='gen'> Female </td>";
}
else
{
echo "<td><input type='radio' name='gen' value='Male' id='gen'> Male <input type='radio' name='gen' value='Female' id='gen' checked> Female </td>";
}
?>
</tr>
<tr>
<td>Check Box: Check the languages you know?</td>
<td><?php
$lang=explode(',',$l);
//print_r($lang);
if(in_array('Cricket', $lang))
echo '<input type="checkbox" name="lang[0]" value="Cricket" checked>Cricket';
else
echo '<input type="checkbox" name="lang[0]" value="Cricket">Cricket';
if(in_array('Basketball', $lang))
echo '<input type="checkbox" name="lang[1]" value="Basketball" checked>Basketball';
else
echo '<input type="checkbox" name="lang[1]" value="Basketball">Basketball';
if(in_array('Hockey', $lang))
echo '<input type="checkbox" name="lang[2]" value="Hockey" checked>Hockey';
else
echo '<input type="checkbox" name="lang[2]" value="Hockey">Hockey'."<br>";
?>
</td>
</tr>
<tr>
<td>Mobile No:</td>
<td><input type="text" name="mobile" value="<?php echo $query2['mobile']; ?>"
</td>
</tr>
<tr>
<td>10th Marks:</td>
<td><input type="text" name="marks_10" value="<?php echo $query2['10marks'];?>"
</td>
</tr>
<tr>
<td>
12th Marks:</td>
<td><input type="text" name="marks_12" value="<?php echo $query2['12marks'];?>"</td>
</tr>
<tr>
<td>
Browse Image:</td>
<td><img src='img/<?php echo $query2['iname'];?>' width='150px' height='150px'></td>
<td><input type="file" name="iname" value="<?php echo $query2['iname'];?>"></td>
</tr>
<tr>
<td>
Size:
<input type="text" name="size" value="<?php echo $query2['size'];?>" disabled>
</td>
</tr>
<tr>
<td></td>
<td>
<input type="submit" value="submit" name="sub"><br>
</td>
</tr>
</table>
</form>
<?php
}
?><file_sep>/register.php
<!DOCTYPE html>
<html>
<head>
<title>Register</title>
</head>
<body>
<fieldset>
<LEGEND>Registration</LEGEND>
<form method="post" action="register.php" enctype="multipart/form-data">
<table>
<tr>
<td>Enter Your Username</td>
<td><input type="text" name="uname"></td>
</tr>
<tr>
<td>Enter Your Password</td>
<td><input type="text" name="pwd"></td>
</tr>
<tr>
<td>Enter Your Email Id</td>
<td><input type="emailid" name="emailid"></td>
</tr>
<!-- <tr>
<td>Confirm Your Password</td>
<td><input type="text" name="pwd"></td>
</tr> -->
<tr>
<td>Radio Button: Are you male or female?</td>
<td> <input type="radio" name="gen" value="male">Male
<input type="radio" name="gen" value="female">Female
</td>
</tr>
<tr>
<td>Check You Hobbies:</td>
<td><input type="checkbox" name="lang[]" value="Cricket">Cricket
<input type="checkbox" name="lang[]" value="Basketball">Basketball
<input type="checkbox" name="lang[]" value="Hockey">Hockey</td>
</tr>
<tr>
<td>Enter Your Mobile No:</td>
<td><input type="text" name="mobile"></td>
</tr>
<tr>
<td>Enter Your 10th %ge:</td>
<td><input type="text" name="marks_10"></td>
</tr>
</tr>
<tr>
<td>Enter Your 12th %ge:</td>
<td><input type="text" name="marks_12"></td>
</tr>
<tr>
<td>Browse Image</td>
<td><input type="file" name="iname"></td>
</tr>
<tr>
<td>
<select name="priority">
<option value="admin">
admin
</option>
<option value="guest">
guest
</option>
<option value="superadmin">
superadmin
</option>
</select>
</td>
</tr>
<tr>
<td><input type="submit" value="Register" name="reg"><br></td>
</tr>
</table>
</form>
</fieldset>
</body>
</html>
<?php
function __autoload($classname)
{
include "$classname.php";
}
$obj = new connect();
$obj->con();
if(isset($_POST['reg']))
{
$ins= new insert();
$ins->insertreg();
}
?><file_sep>/insert.php
<?php
class insert extends connect
{
function insertreg()
{
$obj= new connect();
$obj->con();
extract($_POST);
$lang = implode(",",$_POST['lang']);
if(isset($_FILES['iname']))
{
//extract($_POST);
//echo "hello";
$name = $_FILES['iname']['name'];
$type = $_FILES['iname']['type'];
$size = $_FILES['iname']['size'];
$tmp_name = $_FILES['iname']['tmp_name'];
$loc = 'img/';
$ext = substr($name,strpos($name,'.')+1);
if($_FILES['iname']['size']>= '10000' || $_FILES['iname']['size']<="23000000")
{
//echo $size;
}
else{
// echo "size is not supported";
}
$val = $_FILES['iname']['size'];
if($ext == 'jpg' || $ext == 'png')
{
//echo $lang;
//print_r($_POST);
//exit;
$qry = "insert into register(uname,pwd,emailid,gen,lang,mobile,10marks,12marks,iname,size,priority)values('$uname','$pwd','$emailid','$gen','$lang','$mobile','$marks_10','$marks_12','$name','$size','$priority')";
print_r($qry);
$run = mysqli_query($this->con(),$qry);
//print_r($run);
if($run)
{
move_uploaded_file($tmp_name,$loc.$name);
//echo "data saved";
//echo "Data inserted";
}
else
{
//echo "Data Not Inserted";
}
}
}
}
function insertsub()
{
$obj= new connect();
$obj->con();
extract($_POST);
$qry="insert into subject (subname)values('$subject')";
$run=mysqli_query($this->con(),$qry);
//print_r($run);
}
function inserttest()
{
$obj= new connect();
$obj->con();
extract($_POST);
$qry="insert into test(test,subid)values('$test','$subid')";
$run=mysqli_query($this->con(),$qry);
//print_r($run);
}
function insertques()
{
$obj= new connect();
$obj->con();
extract($_POST);
$qry="insert into question(testid,quesname,answer1,answer2,answer3,answer4,correctanswer)values('$testid','$quesname','$answer1','$answer2','$answer3','$answer4','$correctanswer')";
$run=mysqli_query($this->con(),$qry);
}
function insertexamees()
{
$obj= new connect();
$obj->con();
extract($_POST);
$qry="insert into examiner(test,selected)values('$testid','$selected')";
//print_r($qry);
$run=mysqli_query($this->con(),$qry);
}
}
//$ins= new insert();
//$ins->insertdata();
?><file_sep>/connect.php
<?php
class connect
{
var $db_host="localhost";
var $username="root";
var $password="";
var $database="projectexam";
var $myconn;
function con()
{
$con = mysqli_connect($this->db_host,$this->username,$this->password,$this->database);
if ($con) {
//echo "Connection Established";
}else
{
//echo "Connection Aborted";
}
return $this->myconn=$con;
}
}
//$obj= new connect();
//$obj->con();
?> | 19c80c7ed8c4e7e98b44d220d8b356c9f2866b01 | [
"PHP"
] | 11 | PHP | himcoder/examproject | d7c69cd68e296333b486201dd0e87ab45b77ee82 | 353eab70c0c7ad81e79415d01fb95d6822f7c435 |
refs/heads/master | <file_sep>import { Reducer } from 'redux';
import { CombinedActions } from '../../app/AppState';
export enum MoveErrorTypes {
NOT_ENOUGH_TODOS = "NOT_ENOUGH_TODOS",
CURRENT_LESS_THAN_ZERO = "CURRENT_LESS_THAN_ZERO",
CURRENT_OUT_OF_BOUNDS = "CURRENT_OUT_OF_BOUNDS",
TARGET_LESS_THAN_ZERO = "TARGET_LESS_THAN_ZERO",
TARGET_OUT_OF_BOUNDS = "TARGET_OUT_OF_BOUNDS"
};
interface NotEnoughToDos {
errorType: MoveErrorTypes.NOT_ENOUGH_TODOS
};
interface CurrentLessThanZero {
errorType: MoveErrorTypes.CURRENT_LESS_THAN_ZERO
};
interface CurrentOutOfBounds {
errorType: MoveErrorTypes.CURRENT_OUT_OF_BOUNDS
};
interface TargetLessThanZero {
errorType: MoveErrorTypes.TARGET_LESS_THAN_ZERO
};
interface TargetOutOfBounds {
errorType: MoveErrorTypes.TARGET_OUT_OF_BOUNDS
};
export type MoveErrors = NotEnoughToDos
| CurrentLessThanZero
| CurrentOutOfBounds
| TargetLessThanZero
| TargetOutOfBounds;
interface MoveToDo {
errors: MoveErrors[]
};
export interface MoveToDoState {
moveToDo: MoveToDo;
};
export enum MoveActionTypes {
TOO_FEW_TODOS = "TOO_FEW_TODOS",
CURRENT_TOO_SMALL = "CURRENT_TOO_SMALL",
CURRENT_TOO_LARGE = "CURRENT_TOO_LARGE",
TARGET_TOO_SMALL = "TARGET_TOO_SMALL",
TARGET_TOO_LARGE = "TARGET_TOO_LARGE"
};
interface TooFewToDosAction {
type: MoveActionTypes.TOO_FEW_TODOS
};
interface CurrentTooSmallAction {
type: MoveActionTypes.CURRENT_TOO_SMALL
};
interface CurrentTooLargeAction {
type: MoveActionTypes.CURRENT_TOO_LARGE
};
interface TargetTooSmallAction {
type: MoveActionTypes.TARGET_TOO_SMALL
};
interface TargetTooLargeAction {
type: MoveActionTypes.TARGET_TOO_LARGE
}
const tooFewToDosToMove = (): TooFewToDosAction => ({
type: MoveActionTypes.TOO_FEW_TODOS
});
const currentTooSmall = (): CurrentTooSmallAction => ({
type: MoveActionTypes.CURRENT_TOO_SMALL
});
const currentTooLarge = (): CurrentTooLargeAction => ({
type: MoveActionTypes.CURRENT_TOO_LARGE
});
const targetTooSmall = (): TargetTooSmallAction => ({
type: MoveActionTypes.TARGET_TOO_SMALL
});
const targetTooLarge = (): TargetTooLargeAction => ({
type: MoveActionTypes.TARGET_TOO_LARGE
});
const initialMoveToDo: MoveToDo = {
errors: []
}
type MoveToDoActions = CombinedActions<
TooFewToDosAction
| CurrentTooSmallAction
| CurrentTooLargeAction
| TargetTooSmallAction
| TargetTooLargeAction
>
const toDoMove: Reducer<MoveToDo> = (
state: MoveToDo = initialMoveToDo,
action: MoveToDoActions
): MoveToDo => {
if (action.type === MoveActionTypes.TOO_FEW_TODOS) {
return {
errors: [{ errorType: MoveErrorTypes.NOT_ENOUGH_TODOS }]
};
}
if (action.type === MoveActionTypes.CURRENT_TOO_SMALL) {
return {
errors: [{ errorType: MoveErrorTypes.CURRENT_LESS_THAN_ZERO }]
};
}
if (action.type === MoveActionTypes.CURRENT_TOO_LARGE) {
return {
errors: [{ errorType: MoveErrorTypes.CURRENT_OUT_OF_BOUNDS }]
};
}
if (action.type === MoveActionTypes.TARGET_TOO_SMALL) {
return {
errors: [{ errorType: MoveErrorTypes.TARGET_LESS_THAN_ZERO }]
};
}
if (action.type === MoveActionTypes.TARGET_TOO_LARGE) {
return {
errors: [{ errorType: MoveErrorTypes.TARGET_OUT_OF_BOUNDS }]
};
}
return state;
}
export {
tooFewToDosToMove
, currentTooSmall
, currentTooLarge
, targetTooSmall
, targetTooLarge
, toDoMove
};
<file_sep>import {
AnyAction
, Middleware
, MiddlewareAPI
, Dispatch
} from 'redux';
import { MiddlewareFactory } from './AppFactory';
import { AppState, CombinedActions } from './AppState';
import { ID_ACTIONS } from '../todo/add/todoId-state';
import {
AddAction
, DeleteAction
, MoveAction
, addAction
, moveAction
, ToDo
} from '../todo/todo-state';
import { NewToDoCommand, NewToDoCommands } from '../todo/newToDoCommandHandler';
import { MoveCommand, MoveCommands } from '../todo/moveToDoCommandHandler';
import { ADD_TYPES } from '../todo/add/addToDo-state';
import {
tooFewToDosToMove
, currentTooSmall
, currentTooLarge
, targetTooSmall
, targetTooLarge
} from '../todo/move/moveToDo-state';
type AppStateMiddleware = Middleware<any, AppState, Dispatch>;
type MiddlewareStore = MiddlewareAPI<Dispatch, AppState>;
type AllActions = CombinedActions<AddAction | DeleteAction | MoveAction | NewToDoCommand | MoveCommand>;
const middleware: AppStateMiddleware = (store: MiddlewareStore) => (next: Dispatch) => (action: AllActions) => {
if (action.type === NewToDoCommands.NEW_TODO) {
const id = store.getState().todoId.nextId;
const todoContent = store.getState().addToDo;
const actionToAdd: AddAction = addAction({ id, ...todoContent })
next({ type: ID_ACTIONS.INCREMENT_ID });
next({ type: ADD_TYPES.RESET })
return next(actionToAdd);
} else if (action.type === MoveCommands.MOVE) {
const todos = store.getState().todos;
if (todos.length < 2) {
return next(tooFewToDosToMove());
}
if (action.indexes.current < 0) {
return next(currentTooSmall());
}
if (action.indexes.current >= todos.length) {
return next(currentTooLarge());
}
if (action.indexes.target < 0) {
return next(targetTooSmall());
}
if (action.indexes.target >= todos.length) {
return next(targetTooLarge());
}
return next(moveAction(action.indexes));
} else {
return next(action);
}
}
const middlewareFactory: MiddlewareFactory<AppState> = () => middleware;
export {
middlewareFactory
};
<file_sep>export enum MoveCommands {
MOVE = "MOVE"
};
export interface MoveIndexes {
current: number;
target: number;
};
export interface MoveCommand {
type: MoveCommands.MOVE;
indexes: MoveIndexes;
}
const moveCommand = (indexes: MoveIndexes): MoveCommand => ({
type: MoveCommands.MOVE,
indexes
});
const handleMoveCommand = () => { };
export { moveCommand, handleMoveCommand };
<file_sep>import * as R from 'ramda';
import React from 'react';
import ReactDOM from 'react-dom';
import { Store } from 'redux';
import { Provider } from 'react-redux';
import { AppState } from '../app/AppState';
import { ToDo } from './todo-state';
import { moveCommand } from './moveToDoCommandHandler';
import { newToDoCommand } from './newToDoCommandHandler';
import { getTestConnectedComponent } from '../test-tools/TestConnectedComponent';
import { reducerFactory } from '../app/ReducerFactory';
import { middlewareFactory } from '../app/MiddlewareFactory';
import { getTestStore } from '../test-tools/TestStore';
import { updateTitleAction, updateDescriptionAction } from '../todo/add/addToDo-state';
import { MoveErrorTypes } from '../todo/move/moveToDo-state';
describe('[reorder-todo]', () => {
let store: Store<any>;
let div: Element;
let stateHolder: Array<AppState>;
beforeEach(() => {
store = getTestStore(reducerFactory, middlewareFactory);
div = document.createElement('div');
});
afterEach(() => {
ReactDOM.unmountComponentAtNode(div);
});
const renderTestElement = (): Array<AppState> => {
const stateHolder: Array<AppState> = [];
ReactDOM.render(
React.createElement(
Provider,
{ store },
React.createElement(getTestConnectedComponent((props: AppState) => {
stateHolder[0] = props;
return React.createElement("div")
})),
),
div
);
return stateHolder;
}
const createNewTodos = (todoCount: number): void => {
R.forEach(
(v: number) => {
store.dispatch(updateTitleAction(`title_${v}`));
store.dispatch(updateDescriptionAction(`description_${v}`));
store.dispatch(newToDoCommand());
},
R.range(0, todoCount)
);
};
const makeToDo = (index: number): ToDo => ({
id: index
, title: `title_${index}`
, description: `description_${index}`
});
const todosStartInTheRightOrder = (todos: ToDo[]): void => {
const mapIndexed = R.addIndex<ToDo, { value: ToDo; index: number; }>(R.map)
const todosWithIndex: {
value: ToDo;
index: number;
}[] = mapIndexed(<ToDo>(value: ToDo, index: number) => ({ index, value }), todos);
R.forEach(
({ value, index }) => expect(value).toEqual(makeToDo(index))
, todosWithIndex
);
};
const sectionIsInRightOrder = (todos: ToDo[], { start, finish, offset }: {
start: number;
finish: number;
offset: number;
}): void => {
R.forEach(
(v: number) => expect(todos[v]).toEqual(makeToDo(v + offset))
, R.range(start, finish + 1)
);
};
const areInRightOrder = (todos: ToDo[], { start, finish }: {
start: number;
finish: number;
}): void => sectionIsInRightOrder(todos, { start, finish, offset: 0 });
beforeEach(() => {
stateHolder = renderTestElement();
});
describe('[invalid-move-commands]', () => {
it('[initial value]', () => {
expect(stateHolder[0].moveToDo.errors).toEqual([]);
});
describe('sends an error', () => {
it('[reorder of 0 todos]', () => {
store.dispatch(moveCommand({ current: 0, target: 1 }));
expect(stateHolder[0].moveToDo.errors).toEqual([{
errorType: MoveErrorTypes.NOT_ENOUGH_TODOS
}]);
});
it('[reorder of 1 todo]', () => {
createNewTodos(1);
store.dispatch(moveCommand({ current: 0, target: 1 }));
expect(stateHolder[0].moveToDo.errors).toEqual([{
errorType: MoveErrorTypes.NOT_ENOUGH_TODOS
}]);
});
it('[current less than 0]', () => {
createNewTodos(4);
store.dispatch(moveCommand({ current: -1, target: 3 }));
expect(stateHolder[0].moveToDo.errors).toEqual([{
errorType: MoveErrorTypes.CURRENT_LESS_THAN_ZERO
}]);
});
it('[current greater than number of todos]', () => {
createNewTodos(4);
store.dispatch(moveCommand({ current: 5, target: 2 }));
expect(stateHolder[0].moveToDo.errors).toEqual([{
errorType: MoveErrorTypes.CURRENT_OUT_OF_BOUNDS
}]);
});
it('[current equal to the number of todos]', () => {
createNewTodos(4);
store.dispatch(moveCommand({ current: 4, target: 2 }));
expect(stateHolder[0].moveToDo.errors).toEqual([{
errorType: MoveErrorTypes.CURRENT_OUT_OF_BOUNDS
}]);
});
it('[target less than 0]', () => {
createNewTodos(4);
store.dispatch(moveCommand({ current: 2, target: -1 }));
expect(stateHolder[0].moveToDo.errors).toEqual([{
errorType: MoveErrorTypes.TARGET_LESS_THAN_ZERO
}]);
});
it('[target greater than the number of todos]', () => {
createNewTodos(4);
store.dispatch(moveCommand({ current: 2, target: 5 }));
expect(stateHolder[0].moveToDo.errors).toEqual([{
errorType: MoveErrorTypes.TARGET_OUT_OF_BOUNDS
}]);
});
it('[target equal to the number of todos]', () => {
createNewTodos(4);
store.dispatch(moveCommand({ current: 2, target: 4 }));
expect(stateHolder[0].moveToDo.errors).toEqual([{
errorType: MoveErrorTypes.TARGET_OUT_OF_BOUNDS
}]);
});
});
describe('does not send an error', () => {
it('[current is 0]', () => {
createNewTodos(4);
store.dispatch(moveCommand({ current: 0, target: 3 }));
expect(stateHolder[0].moveToDo.errors).toEqual([]);
});
it('[current is equal to last todo index]', () => {
createNewTodos(4);
store.dispatch(moveCommand({ current: 3, target: 1 }));
expect(stateHolder[0].moveToDo.errors).toEqual([]);
});
it('[target is 0]', () => {
createNewTodos(4);
store.dispatch(moveCommand({ current: 3, target: 0 }));
expect(stateHolder[0].moveToDo.errors).toEqual([]);
});
it('[target is equal to last todo index]', () => {
createNewTodos(4);
store.dispatch(moveCommand({ current: 2, target: 3 }));
expect(stateHolder[0].moveToDo.errors).toEqual([]);
});
});
});
describe('[valid-move-commands]', () => {
describe('[moving up]', () => {
it('[can move the last up 1 with 2 todos]', () => {
createNewTodos(2);
todosStartInTheRightOrder(stateHolder[0].todos);
const current = 1;
const target = 0;
store.dispatch(moveCommand({ current, target }));
const finalState: AppState = stateHolder[0];
const finalTodos: ToDo[] = finalState.todos;
expect(finalTodos.length).toEqual(2);
expect(finalTodos[target]).toEqual(makeToDo(current));
expect(finalTodos[current]).toEqual(makeToDo(target));
});
it('[can move the last up 1]', () => {
createNewTodos(7);
todosStartInTheRightOrder(stateHolder[0].todos);
const current = 6;
const target = 5;
store.dispatch(moveCommand({ current, target }));
const finalState: AppState = stateHolder[0];
const finalTodos: ToDo[] = finalState.todos;
expect(finalTodos.length).toEqual(7);
expect(finalTodos[target]).toEqual(makeToDo(current));
expect(finalTodos[current]).toEqual(makeToDo(target));
areInRightOrder(finalTodos, { start: 0, finish: target - 1 })
});
it('[can move the last to the top]', () => {
createNewTodos(10);
todosStartInTheRightOrder(stateHolder[0].todos);
const current = 9;
const target = 0;
store.dispatch(moveCommand({ current, target }));
const finalState: AppState = stateHolder[0];
const finalTodos: ToDo[] = finalState.todos;
expect(finalTodos.length).toEqual(10);
expect(finalTodos[target]).toEqual(makeToDo(current));
sectionIsInRightOrder(finalTodos, { start: 1, finish: 9, offset: -1 });
});
it('[can move the last to the middle]', () => {
createNewTodos(10);
todosStartInTheRightOrder(stateHolder[0].todos);
const current = 9;
const target = 4;
store.dispatch(moveCommand({ current, target }));
const finalState: AppState = stateHolder[0];
const finalTodos: ToDo[] = finalState.todos;
expect(finalTodos.length).toEqual(10);
expect(finalTodos[target]).toEqual(makeToDo(current));
areInRightOrder(finalTodos, { start: 0, finish: target - 1 });
sectionIsInRightOrder(finalTodos, { start: target + 1, finish: current, offset: -1 });
});
it('[can move a middle one to another middle spot]', () => {
createNewTodos(10);
todosStartInTheRightOrder(stateHolder[0].todos);
const current = 7;
const target = 4;
store.dispatch(moveCommand({ current, target }));
const finalState: AppState = stateHolder[0];
const finalTodos: ToDo[] = finalState.todos;
expect(finalTodos.length).toEqual(10);
expect(finalTodos[target]).toEqual(makeToDo(current));
areInRightOrder(finalTodos, { start: 0, finish: target - 1 });
sectionIsInRightOrder(finalTodos, { start: target + 1, finish: current, offset: -1 });
});
});
describe('[moving down]', () => {
it('[can move the first down 1 with 2 todos]', () => {
createNewTodos(2);
todosStartInTheRightOrder(stateHolder[0].todos);
const current = 0;
const target = 1;
store.dispatch(moveCommand({ current, target }));
const finalState: AppState = stateHolder[0];
const finalTodos: ToDo[] = finalState.todos;
expect(finalTodos.length).toEqual(2);
expect(finalTodos[target]).toEqual(makeToDo(current));
expect(finalTodos[current]).toEqual(makeToDo(target));
});
it('[can move the first todo down 1]', () => {
createNewTodos(5);
todosStartInTheRightOrder(stateHolder[0].todos);
const current = 0;
const target = 1;
store.dispatch(moveCommand({ current, target }));
const finalState: AppState = stateHolder[0];
const finalTodos: ToDo[] = finalState.todos;
expect(finalTodos.length).toEqual(5);
expect(finalTodos[target]).toEqual(makeToDo(0));
expect(finalTodos[current]).toEqual(makeToDo(1));
areInRightOrder(finalTodos, { start: 2, finish: 4 })
});
it('[can move the first todo to the end]', () => {
createNewTodos(10);
todosStartInTheRightOrder(stateHolder[0].todos);
expect(stateHolder[0].todos).toHaveLength(10);
const current = 0;
const target = 9;
store.dispatch(moveCommand({ current, target }));
const finalState: AppState = stateHolder[0];
const finalTodos: ToDo[] = finalState.todos;
expect(finalTodos).toHaveLength(10);
expect(finalTodos[target]).toEqual(makeToDo(0));
sectionIsInRightOrder(finalTodos, { start: 0, finish: target - 1, offset: 1 });
});
it('[can move the first todo to the middle]', () => {
createNewTodos(10);
todosStartInTheRightOrder(stateHolder[0].todos);
expect(stateHolder[0].todos).toHaveLength(10);
const current = 0;
const target = 4;
store.dispatch(moveCommand({ current, target }));
const finalState: AppState = stateHolder[0];
const finalTodos: ToDo[] = finalState.todos;
expect(finalTodos).toHaveLength(10);
expect(finalTodos[target]).toEqual(makeToDo(0));
sectionIsInRightOrder(finalTodos, { start: 0, finish: target - 1, offset: 1 });
areInRightOrder(finalTodos, { start: target + 1, finish: 9 });
});
it('[can move middle todo to the bottom]', () => {
createNewTodos(10);
todosStartInTheRightOrder(stateHolder[0].todos);
expect(stateHolder[0].todos).toHaveLength(10);
const current = 4;
const target = 9;
store.dispatch(moveCommand({ current, target }));
const finalState: AppState = stateHolder[0];
const finalTodos: ToDo[] = finalState.todos;
expect(finalTodos).toHaveLength(10);
expect(finalTodos[target]).toEqual(makeToDo(current));
areInRightOrder(finalTodos, { start: 0, finish: current - 1 });
sectionIsInRightOrder(finalTodos, { start: current, finish: target - 1, offset: 1 });
});
it('[can move middle todo to the middle]', () => {
createNewTodos(10);
todosStartInTheRightOrder(stateHolder[0].todos);
expect(stateHolder[0].todos).toHaveLength(10);
const current = 4;
const target = 6;
store.dispatch(moveCommand({ current, target }));
const finalState: AppState = stateHolder[0];
const finalTodos: ToDo[] = finalState.todos;
expect(finalTodos).toHaveLength(10);
expect(finalTodos[target]).toEqual(makeToDo(current));
areInRightOrder(finalTodos, { start: 0, finish: current - 1 });
sectionIsInRightOrder(finalTodos, { start: current, finish: target - 1, offset: 1 });
areInRightOrder(finalTodos, { start: target + 1, finish: 9 });
});
});
describe('[not moving]', () => {
it('[does nothing if current and target are the same]', () => {
createNewTodos(10);
todosStartInTheRightOrder(stateHolder[0].todos);
expect(stateHolder[0].todos).toHaveLength(10);
const current = 5;
const target = 5;
store.dispatch(moveCommand({ current, target }));
const finalState: AppState = stateHolder[0];
const finalTodos: ToDo[] = finalState.todos;
todosStartInTheRightOrder(finalTodos);
});
});
});
});
<file_sep>import {
ToDo
, ToDoListState
} from '../todo/todo-state';
import {
AddToDoState
} from '../todo/add/addToDo-state';
import {
ToDoIdState
} from '../todo/add/todoId-state';
import {
MoveToDoState
} from '../todo/move/moveToDo-state';
export interface UnHandledAction {
type: "UNHANDLED";
}
export type CombinedActions<T> = T | UnHandledAction;
export type Omit<T, K extends keyof T> = Pick<T, Exclude<keyof T, K>>;
export interface AppState extends ToDoListState, AddToDoState, ToDoIdState, MoveToDoState { }
<file_sep>import { Dispatch } from 'redux';
import { connect } from 'react-redux';
type functionComponent<T> = (props: T) => JSX.Element;
const getTestConnectedComponent = <T>(component: functionComponent<T>) => {
const mapStateToProps = (state: T) => state;
const mapDispatchToProps = (dispatch: Dispatch) => ({});
return connect(mapStateToProps, mapDispatchToProps)(component);
};
export { getTestConnectedComponent };
<file_sep>import {
Reducer,
Action
} from 'redux';
import * as R from 'ramda';
import { ToDoContent } from './add/addToDo-state';
import { CombinedActions } from '../app/AppState';
export interface ToDo {
id: number;
title: string;
description: string;
}
export enum TODO_ACTION {
DELETE = 'DELETE',
ADD = 'ADD',
MOVE = 'MOVE',
}
export interface DeleteAction {
type: TODO_ACTION.DELETE;
id: number;
}
export interface AddAction {
type: TODO_ACTION.ADD;
todoContent: ToDo;
}
export interface IndexPair {
current: number;
target: number;
}
export interface MoveAction {
type: TODO_ACTION.MOVE;
move: IndexPair;
}
type ToDoListActions = CombinedActions<DeleteAction | AddAction | MoveAction>;
const deleteAction = (id: number): DeleteAction => ({
type: TODO_ACTION.DELETE,
id
});
const addAction = (todoContent: ToDo): AddAction => ({
type: TODO_ACTION.ADD,
todoContent
});
const moveAction = (pair: IndexPair): MoveAction => ({
type: TODO_ACTION.MOVE,
move: pair,
});
export interface ToDoListState {
todos: ToDo[];
}
const todos: ToDo[] = [];
type range = { start: number; end: number; };
const getSubArrayFun = <T>(list: Array<T>) => ({ start, end }: range): Array<T> => {
const result: Array<T> = [];
let index = 0;
R.forEach(
(pointer: number) => {
result[index] = list[pointer];
index++;
}
, R.range(start, end + 1)
)
return result;
};
const todoList: Reducer<ToDo[]> = (
state: ToDo[] = todos,
action: ToDoListActions
): ToDo[] => {
if (action.type === TODO_ACTION.DELETE) {
return R.filter((todo: ToDo) => todo.id !== action.id, state)
}
if (action.type === TODO_ACTION.ADD) {
return [...state, action.todoContent];
}
if (action.type === TODO_ACTION.MOVE) {
const { current, target } = action.move;
if (current === target) {
return state;
} else if (current > target) {
const value = state[current];
const subArray = getSubArrayFun(state);
const unchangedTop = subArray({ start: 0, end: target - 1 });
const shiftedDown = subArray({ start: target, end: current - 1 });
const unchangedBottom = subArray({ start: current + 1, end: state.length - 1 });
return [...unchangedTop, value, ...shiftedDown, ...unchangedBottom];
} else {
const value = state[current];
const subArray = getSubArrayFun(state);
const unchangedTop = subArray({ start: 0, end: current - 1 });
const shiftedUp = subArray({ start: current + 1, end: target });
const unchangedBottom = subArray({ start: target + 1, end: state.length - 1 });
return [...unchangedTop, ...shiftedUp, value, ...unchangedBottom];
}
}
return state;
}
export {
todoList
, addAction
, deleteAction
, moveAction
};
<file_sep>import * as R from 'ramda';
import React from 'react';
import ReactDOM from 'react-dom';
import { Store } from 'redux';
import { Provider } from 'react-redux';
import { getTestStore } from '../test-tools/TestStore';
import { AppState, Omit } from '../app/AppState';
import { getTestConnectedComponent } from '../test-tools/TestConnectedComponent';
import { reducerFactory } from '../app/ReducerFactory';
import { middlewareFactory } from '../app/MiddlewareFactory';
import { deleteAction, ToDo } from './todo-state';
import {
updateTitleAction
, updateDescriptionAction
} from './add/addToDo-state';
import { newToDoCommand } from './newToDoCommandHandler';
describe('[state] todo', () => {
let store: Store<any>;
let div: Element;
beforeEach(() => {
store = getTestStore(reducerFactory, middlewareFactory);
div = document.createElement('div');
});
afterEach(() => {
ReactDOM.unmountComponentAtNode(div);
});
const renderTestElement = (): Array<AppState> => {
const stateHolder: Array<AppState> = [];
ReactDOM.render(
React.createElement(
Provider,
{ store },
React.createElement(getTestConnectedComponent((props: AppState) => {
stateHolder[0] = props;
return React.createElement("div")
})),
),
div
);
return stateHolder;
}
const withId: (partial: {
title: string;
description: string
},
id: number
) => ({
title: string;
description: string;
id: number;
}) = (partial, id) => ({ ...partial, id })
describe('[todo-state-changes]', () => {
let stateHolder: Array<AppState>;
beforeEach(() => {
stateHolder = renderTestElement();
});
it('initial state', () => {
expect(stateHolder[0].addToDo).toEqual({
title: "",
description: ""
});
expect(stateHolder[0].todos).toHaveLength(0);
expect(stateHolder[0].todoId).toEqual({ nextId: 0 })
});
describe('[addToDo]', () => {
describe('[update values]', () => {
it('can update the title with [updateTitleAction]', () => {
store.dispatch(updateTitleAction("updated title"));
expect(stateHolder[0].addToDo).toEqual({
title: "updated title",
description: ""
});
});
it('can update the description with [updateDescriptionAction]', () => {
store.dispatch(updateDescriptionAction("updated description"));
expect(stateHolder[0].addToDo).toEqual({
title: "",
description: "updated description"
});
});
it('can update both title and description', () => {
store.dispatch(updateTitleAction("updated title"));
store.dispatch(updateDescriptionAction("updated description"));
expect(stateHolder[0].addToDo).toEqual({
title: "updated title",
description: "updated description"
});
});
});
it('updates values for next todo on [addAction]', () => {
store.dispatch(updateTitleAction("updated title"));
store.dispatch(updateDescriptionAction("updated description"));
store.dispatch(newToDoCommand());
expect(stateHolder[0].addToDo).toEqual({
title: "",
description: ""
});
expect(stateHolder[0].todoId).toEqual({ nextId: 1 });
});
});
describe('[todos]', () => {
it('can add a todo with [newToDoCommand]', () => {
store.dispatch(updateTitleAction("this is the new title"));
expect(stateHolder[0].addToDo).toEqual({
title: "this is the new title",
description: "",
})
store.dispatch(updateDescriptionAction("this is the new description"));
expect(stateHolder[0].addToDo).toEqual({
title: "this is the new title",
description: "this is the new description",
})
store.dispatch(newToDoCommand());
expect(stateHolder[0].todos).toHaveLength(1);
expect(stateHolder[0].todos).toEqual([{
id: 0
, title: "this is the new title"
, description: "this is the new description"
}]);
expect(stateHolder[0].addToDo).toEqual({
title: "",
description: ""
});
});
describe('[delete-todo]', () => {
const getToDo1 = () => ({
title: 'title1'
, description: 'description1'
});
const getToDo2 = () => ({
title: 'title2'
, description: 'description2'
});
const getToDo3 = () => ({
title: 'title3'
, description: 'description3'
});
const addAToDo = ({ title, description }: Omit<ToDo, "id">) => {
store.dispatch(updateTitleAction(title));
store.dispatch(updateDescriptionAction(description));
store.dispatch(newToDoCommand());
};
beforeEach(() => {
addAToDo(getToDo1());
addAToDo(getToDo2());
addAToDo(getToDo3());
expect(stateHolder[0].todos).toHaveLength(3);
expect(stateHolder[0].todos).toEqual([
withId(getToDo1(), 0),
withId(getToDo2(), 1),
withId(getToDo3(), 2)
]);
});
it('can delete the first todo', () => {
store.dispatch(deleteAction(0));
expect(stateHolder[0].todos).toHaveLength(2);
expect(stateHolder[0].todos).toEqual([
withId(getToDo2(), 1),
withId(getToDo3(), 2)
]);
});
it('can delete the last todo', () => {
store.dispatch(deleteAction(2));
expect(stateHolder[0].todos).toHaveLength(2);
expect(stateHolder[0].todos).toEqual([
withId(getToDo1(), 0),
withId(getToDo2(), 1)
]);
});
it('can delete the middle todo', () => {
store.dispatch(deleteAction(1));
expect(stateHolder[0].todos).toHaveLength(2);
expect(stateHolder[0].todos).toEqual([
withId(getToDo1(), 0),
withId(getToDo3(), 2)
]);
});
it('can delete all todos', () => {
store.dispatch(deleteAction(0));
store.dispatch(deleteAction(1));
store.dispatch(deleteAction(2));
expect(stateHolder[0].todos).toHaveLength(0);
expect(stateHolder[0].todos).toEqual([]);
});
it('does nothing for invalid id', () => {
store.dispatch(deleteAction(10000));
expect(stateHolder[0].todos).toHaveLength(3);
expect(stateHolder[0].todos).toEqual([
withId(getToDo1(), 0),
withId(getToDo2(), 1),
withId(getToDo3(), 2)
]);
});
});
});
});
});
<file_sep>import {
Store
, createStore
, applyMiddleware
} from 'redux';
import { ReducerFactory, MiddlewareFactory } from './AppFactory';
import { AppState } from './AppState';
const storeFactory = (
reducerFactory: ReducerFactory<AppState>,
middlewareFactory: MiddlewareFactory<AppState>
): Store<AppState> => createStore(
reducerFactory(),
applyMiddleware(middlewareFactory())
);
export { storeFactory };
<file_sep>import {
Reducer
, AnyAction
} from 'redux';
import { CombinedActions } from '../../app/AppState';
interface ToDoId {
nextId: number;
}
export interface ToDoIdState {
todoId: ToDoId;
}
export enum ID_ACTIONS {
INCREMENT_ID = "INCREMENT_ID"
}
interface IncrementAction {
type: ID_ACTIONS.INCREMENT_ID
}
const initialIdState: ToDoId = {
nextId: 0
}
const todoId: Reducer<ToDoId> = (
state: ToDoId = initialIdState,
action: CombinedActions<IncrementAction>
): ToDoId => {
if (action.type === ID_ACTIONS.INCREMENT_ID) {
const nextId = state.nextId + 1;
return { nextId };
}
return state;
}
export {
todoId
}
<file_sep>import {
Store
, AnyAction
} from 'redux';
import { ToDoIdState } from './todoId-state';
const addToDoMiddleware = (store: Store<ToDoIdState>) => (next: any) => (action: AnyAction) => {
return next(action);
}
export { addToDoMiddleware };
<file_sep>import { Dispatch } from 'redux';
import { connect } from 'react-redux';
import {
AddToDo
, AddToDoStateProps
, AddToDoDispatchProps
} from './addToDo';
import {
ToDo
} from '../todo-state';
import {
updateTitleAction
, updateDescriptionAction
, ToDoContent
} from './addToDo-state';
import { newToDoCommand } from '../newToDoCommandHandler';
import { AddToDoState } from './addToDo-state';
const mapStateToProps = ({ addToDo }: AddToDoState): AddToDoStateProps => addToDo;
const mapDispatchToProps = (dispatch: Dispatch): AddToDoDispatchProps => ({
add: (todoContent: ToDoContent) => dispatch(newToDoCommand()),
updateTitle: (title: string) => dispatch(updateTitleAction(title)),
updateDescription: (description: string) => dispatch(updateDescriptionAction(description))
});
const AddToDoComponent = connect(mapStateToProps, mapDispatchToProps)(AddToDo)
export { AddToDoComponent };
<file_sep>import * as R from 'ramda';
import {
createStore
, combineReducers
, Dispatch
, Store
, AnyAction
, Reducer
, MiddlewareAPI
} from 'redux';
import {
ReducerFactory
, MiddlewareFactory
, StoreFactory
} from '../app/AppFactory';
import { AppState } from '../app/AppState';
const d: Dispatch = <T extends AnyAction>(action: T): T => action;
const getTestStore: StoreFactory = <T>(
reducerFactory: ReducerFactory<T>,
middlewareFactory: MiddlewareFactory<T>
): Store<T> => {
const reducer: Reducer = reducerFactory();
const initialState: T = reducer(undefined, { type: "UNDEFINED" });
const storeState: {
currentState: T;
reducer: Reducer;
subscribers: { [key: number]: () => void; };
nextSubscriberId: number;
} = {
currentState: initialState,
reducer,
subscribers: {},
nextSubscriberId: 0
};
const middleware = middlewareFactory();
const dispatcher = <A extends AnyAction>(action: A) => {
const dispatch: Dispatch = <T extends AnyAction>(a: T): T => dispatcher(a);
const middlewareStore: MiddlewareAPI<Dispatch<AnyAction>, T> = {
getState: () => storeState.currentState,
dispatch
};
const reducerDispatch = (a: AnyAction) => {
const getState = () => storeState.currentState;
const updatedState = reducer(getState(), a);
storeState.currentState = updatedState;
return updatedState;
};
const updatedStore = middleware(middlewareStore)(reducerDispatch)(action);
storeState.currentState = updatedStore;
R.forEach((l) => l(), R.values(storeState.subscribers));
return action;
}
return {
dispatch: dispatcher,
getState: (): T => {
return storeState.currentState;
},
subscribe: (listener: () => void) => {
const removalId = storeState.nextSubscriberId;
storeState.subscribers[storeState.nextSubscriberId] = listener;
storeState.nextSubscriberId = storeState.nextSubscriberId + 1;
return () => { delete storeState.subscribers[removalId] };
},
replaceReducer: () => { }
};
};
const findChildWithClass = (element: Element, c: string): Array<Element> => {
const foundChildren: Array<Element> = [];
const children: HTMLCollection = element.children;
const childList: Array<Element> = [];
const length: number = children.length;
let i = 0;
while (i < length) {
childList.push(children[i]);
i++;
}
const match: Element | undefined = R.find((child: Element) => child.className === c, childList);
if (match !== undefined) {
foundChildren.push(match);
}
return foundChildren;
};
export {
getTestStore
, findChildWithClass
};
<file_sep>import React from 'react';
import {
Store
, Reducer
, Middleware
, Dispatch
} from 'redux';
import { app } from '../App';
import { AppState } from './AppState';
export type ReducerFactory<T> = () => Reducer<T>;
export type MiddlewareFactory<T> = () => Middleware<any, T, Dispatch>;
export type StoreFactory = (
reducerFactory: ReducerFactory<AppState>,
middlewareFactory: MiddlewareFactory<AppState>
) => Store;
const AppFactory = (
storeFactory: StoreFactory
, reducerFactory: ReducerFactory<AppState>
, middlewareFactory: MiddlewareFactory<AppState>
): typeof React.Component => app(storeFactory, reducerFactory, middlewareFactory);
export { AppFactory };
<file_sep>import { combineReducers } from 'redux';
import { todoList } from '../todo/todo-state';
import { addToDo } from '../todo/add/addToDo-state';
import { todoId } from '../todo/add/todoId-state';
import { toDoMove } from '../todo/move/moveToDo-state';
import { ReducerFactory } from './AppFactory';
import { AppState } from './AppState';
const reducerFactory: ReducerFactory<AppState> = () => combineReducers({
todos: todoList
, addToDo
, moveToDo: toDoMove
, todoId
});
export { reducerFactory };
<file_sep>import * as R from 'ramda';
import { Reducer } from 'redux';
import { CombinedActions } from '../../app/AppState';
import {
TODO_ACTION
, AddAction
} from '../todo-state';
export interface ToDoContent {
title: string;
description: string;
}
interface AddToDo {
title: string;
description: string;
}
export interface AddToDoState {
addToDo: AddToDo;
}
export enum ADD_TYPES {
UPDATE_TITLE = "UPDATE_TITLE",
UPDATE_DESCRIPTION = "UPDATE_DESCRIPTION",
NEW_TODO = "NEW_TODO",
RESET = "RESET",
}
export interface UpdateTitleAction {
type: ADD_TYPES.UPDATE_TITLE;
title: string;
}
export interface UpdateDescriptionAction {
type: ADD_TYPES.UPDATE_DESCRIPTION;
description: string;
}
export interface ResetAction {
type: ADD_TYPES.RESET;
}
const updateTitleAction = (title: string): UpdateTitleAction => ({
type: ADD_TYPES.UPDATE_TITLE,
title
});
const updateDescriptionAction = (description: string): UpdateDescriptionAction => ({
type: ADD_TYPES.UPDATE_DESCRIPTION,
description
});
const initialState: AddToDo = {
description: "",
title: ""
};
type AddToDoActions = CombinedActions<UpdateTitleAction | UpdateDescriptionAction | ResetAction>;
const addToDo: Reducer<AddToDo> = (state: AddToDo = initialState, action: AddToDoActions) => {
switch (action.type) {
case ADD_TYPES.UPDATE_TITLE: {
return { ...state, title: action.title };
}
case ADD_TYPES.UPDATE_DESCRIPTION: {
return { ...state, description: action.description };
}
case ADD_TYPES.RESET: {
return {
...initialState,
}
}
default: {
return state;
}
}
}
export {
addToDo
, updateTitleAction
, updateDescriptionAction
};
<file_sep>export enum NewToDoCommands {
NEW_TODO = "NEW_TODO"
}
export interface NewToDoCommand {
type: NewToDoCommands.NEW_TODO
};
const newToDoCommand = () => ({
type: NewToDoCommands.NEW_TODO
});
export { newToDoCommand };
<file_sep>import { Dispatch } from 'redux';
import { connect } from 'react-redux';
import {
ToDoList
, ListProps
, ListDispatch
} from './list';
import { ToDo } from '../todo-state'
import { ToDoListState } from '../../todo/todo-state';
import { TODO_ACTION } from '../todo-state';
const mapStateToProps = (state: ToDoListState): ListProps => {
return { todos: state.todos }
};
const mapDispatchToProps = (dispatch: Dispatch): ListDispatch => ({
deleteToDo: (id: number) => {
dispatch({ type: TODO_ACTION.DELETE, id });
}
});
const ListComponent = connect(mapStateToProps, mapDispatchToProps)(ToDoList)
export { ListComponent };
| 9284e1603c34932da945d2ca8607610bcd55822f | [
"TypeScript"
] | 18 | TypeScript | tim-butterworth/todos | 59e17d09988f7568763267951e30dccffa32a9a1 | 0df9781a37846b967c13b29883c3596c627b6013 |
refs/heads/master | <repo_name>VIKASUM13/Movies-redux<file_sep>/src/App.js
import React , { Component } from 'react';
import MovieList from './components/MovieList';
import MovieDetails from './components/MovieDetails';
import './App.css';
class App extends Component {
render() {
return (
<div className="App">
<h1 className="H1">Redux Movies</h1>
<div className="container">
<table className="table1">
<tr>
<td>
<MovieList />
</td>
<td>
<MovieDetails />
</td>
</tr>
</table>
</div>
</div>
)
}
}
export default App ;
<file_sep>/src/reducers/index.js
import { combineReducers } from 'redux';
const moviesReducer = () => {
return [
{title:'KGF' ,releaseDate:'21-12-2019', rating:8.2},
{title:'Aquaman' ,releaseDate:'12-07-2018', rating:7.6},
{title:'Black Panther' ,releaseDate:'13-03-2018', rating:8.6},
{title:'EndGame' ,releaseDate:'21-12-2019', rating:8.2},
{title:'War' ,releaseDate:'21-12-2019', rating:6.2},
]
}
const selectedMovieReducer = (state = null, action) => {
switch(action.type) {
case 'MOVIE_SELECTED' :
return action.payload;
default:
return state;
}
}
export default combineReducers({
movies: moviesReducer,
selectedMovie: selectedMovieReducer
}) | fb8d43b803faccb7d838ddaa08250c9e4a24fb5a | [
"JavaScript"
] | 2 | JavaScript | VIKASUM13/Movies-redux | 1818553d36729f01bd70fc391380915d3f9b0250 | 5a26f21d1aac45bcdb4eb08c9c4719cd80356a6a |
refs/heads/master | <file_sep><section class="littleWindow">
<h4>Single Page Application</h4>
<p>
Una SPA es un sitio web que cabe en una sola página conc el propósito de dar una experiencia más fluida a los usuarios, como si fuera una aplicación de escritorio. En una SPA todos los códigos HTML, CSS y JavaScript se cargan una sola vez y los recursos necesarios se cargan dinámicamente cuando lo requiera la página, en respuesta a acciones propias de la navegación (enviar un formulario, clickar en un enlace, acceder a una sección interna, etc) sin tener que realizar peticiones al servidor para volver a cargar más código HTML.
</p>
</section>
<section class="btnSection">
<button id='btnClick'>
Click Me
</button>
</section>
<file_sep># SPA-JS-Vanilla
## Single Page Application
Una Single Page Application o SPA, es un sitio web que recarga y muestra su contenido en respuesta a acciones propias de la navegación (enviar un formulario, clickar en un enlace, acceder a una sección interna…) sin tener que realizar peticiones al servidor para volver a cargar más código HTML.
La filosofía de SPA es ofrecer una experiencia de usuario similar a la de una aplicación de escritorio, pero desde un navegador, manejando datos, flujos y estructuras que dependen de una conectividad a Internet en menor medida que el resto de aplicaciones web tradicionales, de una manera ágil y grata, ofreciendo una experiencia de usuario muy cómoda, rápida y agradable.
Ejemplos de aplicaciones SPA: Gmail, Netflix, Trello, Github…
###### Instalar modulos:
`Npm html-webpack-plugin –D`
The HtmlWebpackPlugin simplifies creation of HTML files to serve your webpack bundles.
`Npm I webpack –D`
Webpack is a static module bundler for modern JavaScript applications. When webpack processes your application, it internally builds a dependency graph which maps every module your project needs and generates one or more bundles.
`Npm I webpack-dev-server –D`
Can be used to quickly develop an application.
`Npm I css-loader –D`
The css-loader interprets @import and url() like import/require() and will resolve them.
`Npm I style-loader –D`
Inject CSS into the DOM.
`Npm I html-loader –D`
Exports HTML as string. HTML is minimized when the compiler demands.
<file_sep>import './main.css'
import { router } from './router/index.routes'
const init = () => {
router(window.location.hash);
window.addEventListener("hashchange", () => {
router(window.location.hash);
});
};
window.addEventListener("load", init); | 071bb1661d000c98482bcd515b878b4692e46020 | [
"Markdown",
"JavaScript",
"HTML"
] | 3 | HTML | victorsnz/SPA-JS-Vanilla | a4c76a74c8e05491ca16120bdd09ff034ab518c2 | 18aafa52a21d58c40d6419cef1ddfd30977f901b |
refs/heads/main | <file_sep>import Dom from './Dominik.png';
import Jan from './Jannis.png';
import Max from './Max.png';
export const SliderData = [
{
Image : 'https://images.unsplash.com/photo-1635055658722-494d99b8aebd?ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&ixlib=rb-1.2.1&auto=format&fit=crop&w=3774&q=80'
},
{
Image : 'https://images.unsplash.com/photo-1635051802863-bfa3b4ff74ec?ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&ixlib=rb-1.2.1&auto=format&fit=crop&w=1364&q=80'
},
{
Image: 'https://images.unsplash.com/photo-1593642533144-3d62aa4783ec?ixid=MnwxMjA3fDF8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&ixlib=rb-1.2.1&auto=format&fit=crop&w=2369&q=80'
}
]
<file_sep>
import React from 'react';
import './Topbar.scss';
import { Person , Mail } from '@material-ui/icons';
import {Navbar, Container, Nav, NavDropdown} from 'react-bootstrap';
function Topbar({ menuOpen, setMenuOpen}) {
return (
<div className="topbar">
<Navbar collapseOnSelect expand="lg" bg="dark" variant="dark">
<Container>
<Navbar.Brand href="#about">Tinhat.</Navbar.Brand>
<Navbar.Toggle aria-controls="responsive-navbar-nav" />
<Navbar.Collapse id="responsive-navbar-nav">
<Nav className="me-auto">
</Nav>
<Nav>
<Nav.Link href="#about">About</Nav.Link>
<Nav.Link href="#members">Engineers</Nav.Link>
<Nav.Link href="#contact">Contact</Nav.Link>
</Nav>
</Navbar.Collapse>
</Container>
</Navbar>
</div>
)
}
export default Topbar
<file_sep>import React from 'react'
import './About.scss'
import {Container, Button} from 'react-bootstrap';
import tinfoil from "./jannik-selz-uVxhbhuVWqg-unsplash.jpg";
function About() {
return (
<div className="about" id='about'>
<div className="left">
<div className="imgContainer">
<div className="smallerimgContainer">
<img src= {tinfoil} alt="/" />
</div>
</div>
</div>
<div className="right">
<div className="headlines">
<h4>Hi there, we are </h4>
<h1 className="headlineone"> Tinhat Engineering </h1>
<h4 className='Text'>A Group of students and freelancers specialising in Embeddded Systems, and UI Design
</h4>
<a href="#contact"><div className="cta"><Button size ='lg' variant='danger'>let's get in touch</Button>
</div></a>
</div></div>
</div>
)
}
export default About
<file_sep>
import About from './components/About/About.jsx';
import Contact from './components/Contact/Contact.jsx';
import Footer from './components/Footer/Footer.jsx';
import Members from'./components/Members/Members.jsx';
import Topbar from './components/Topbar/Topbar.jsx';
import Background from './resources/background.jsx';
import './App.scss'
import { useState } from 'react';
function App() {
const [ menuOpen, setMenuOpen] =useState(false)
return (
<div className="App">
<Topbar menuOpen= {menuOpen} setMenuOpen={setMenuOpen} />
<div className="sections">
<About/>
<Members/>
<Contact/>
<Footer/>
</div>
</div>
);
}
export default App;
<file_sep>import React from 'react'
import './Contact.scss'
import {Form, Button,Container } from 'react-bootstrap';
function Contact() {
return (
<div className="contact" id='contact'>
<h1 className="headline" >Contact</h1>
<Container>
<div className="input-fields">
<Form>
<Form.Group className="mb-3" controlId="exampleForm.ControlInput1">
<Form.Label>Email address</Form.Label>
<Form.Control type="email" placeholder="<EMAIL>" />
</Form.Group>
<Form.Group className="mb-3" controlId="exampleForm.ControlTextarea1">
<Form.Label>Your Message</Form.Label>
<Form.Control as="textarea" rows={5} />
</Form.Group>
</Form>
</div>
<div className="button">
<Button variant="success">send</Button>{' '}</div>
</Container>
</div>
)
}
export default Contact
<file_sep>
import React, {useState} from 'react';
import {FaArrowAltCircleRight,FaArrowAltCircleLeft } from 'react-icons/fa'
import Businesscard from './BusinessCard/Businesscard.jsx'
import './ImageSlider.scss'
import Dom from './Dominik.png'
const iconlist =[' https://img.shields.io/badge/HTML5-E34F26?style=for-the-badge&logo=html5&logoColor=white',
'https://img.shields.io/badge/CSS3-1572B6?style=for-the-badge&logo=css3&logoColor=white',
'https://img.shields.io/badge/Sass-CC6699?style=for-the-badge&logo=sass&logoColor=white',
'https://img.shields.io/badge/Python-14354C?style=for-the-badge&logo=python&logoColor=white',
' https://img.shields.io/badge/React-20232A?style=for-the-badge&logo=react&logoColor=61DAFB',
'https://img.shields.io/badge/React_Native-20232A?style=for-the-badge&logo=react&logoColor=61DAFB',
'https://img.shields.io/badge/Bootstrap-563D7C?style=for-the-badge&logo=bootstrap&logoColor=white',
'https://img.shields.io/badge/C%2B%2B-00599C?style=for-the-badge&logo=c%2B%2B&logoColor=white'
];
function ImageSlider({slides}) {
const [state, setstate] = useState(0);
const length = slides.length
const nextSlide = () => {
setstate(state === length -1 ? 0 : state + 1)
}
const prevSlide = () => {
setstate(state === 0 ? length -1: state -1)
}
console.log(state);
if (!Array.isArray(slides) || slides.length <= 0){
return null
}
return (
<div className='Imageslider'>
<FaArrowAltCircleRight className="right-arrow" onClick={nextSlide}/>
<FaArrowAltCircleLeft className="left-arrow" onClick={prevSlide}/>
<div className="container">
<Businesscard img_url={Dom} name="<NAME>" specialisation_list="UI for Embedded Systems " text= "Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet."
badges={iconlist} projpage_link_url=" link_prop" />
</div>
</div>
);
}
export default ImageSlider
| 0451bdf92115c3a5a809eaf970461ddf5e21690e | [
"JavaScript"
] | 6 | JavaScript | KF-Engineering/company-website | d2d10d5e46ea71995e2c72b5d8055be88b64f883 | b7eecad6062aed0baca662fea042ccf9afb673ad |
refs/heads/master | <file_sep><?php
namespace App\Policies;
use App\Models\Topic;
use App\Models\User;
use Illuminate\Auth\Access\HandlesAuthorization;
class TopicPolicy
{
use HandlesAuthorization;
public function delete(User $user, Topic $topic){
return $user -> id === $topic -> user_id;
}
}
<file_sep># Laravel application
Enables authenticated users to add/delete topics and posts related to those topics. Users can also like/unlike posts. Unauthorized users can only view the topics and posts.
<file_sep><?php
namespace App\Http\Controllers;
use App\Models\Post;
use App\Models\Topic;
use Illuminate\Http\Request;
class TopicController extends Controller
{
public function index(){
$topics = Topic::latest()->paginate(10);
return view('topics.index', [
'topics' => $topics
]);
}
public function store(Request $request){
$this->validate($request,[
'title' => 'required'
]);
$request -> user() -> topics() -> create([
'title'=> $request-> title
]);
return back();
}
public function destroy(Topic $topic){
$this->authorize('delete', $topic);
$topic->delete();
return back();
}
public function get(Topic $topic){
$posts = Post::where('topic_id', $topic -> id)->latest()->paginate(10);
return view('posts.index', [
'posts' => $posts,
'topic' => $topic
]);
}
}
<file_sep><?php
namespace Database\Seeders;
use Illuminate\Database\Seeder;
class DatabaseSeeder extends Seeder
{
/**
* Seed the application's database.
*
* @return void
*/
public function run()
{
\App\Models\Topic::factory()->times(10)->create(['user_id' => 2]);
\App\Models\Topic::factory()->times(10)->create(['user_id' => 4]);
\App\Models\Post::factory()->times(2)->create(['user_id' => 2, 'topic_id' => 4]);
\App\Models\Post::factory()->times(2)->create(['user_id' => 4, 'topic_id' => 4]);
\App\Models\Post::factory()->times(2)->create(['user_id' => 2, 'topic_id' => 5]);
\App\Models\Post::factory()->times(2)->create(['user_id' => 4, 'topic_id' => 5]);
}
}
| da56f827959e180e3c373f93011fa51e3e906c6e | [
"Markdown",
"PHP"
] | 4 | PHP | nikolaabadic/forum | 5447c89c4625b9c1af28222ccdd70606583f2e85 | a5f44729b416f6cc909e99391aa6ce692273320c |
refs/heads/master | <repo_name>arpit728/evoting<file_sep>/web/materialize/js/signup_script.js
function only_mobile_number() {
inp = document.getElementById("mobile_number").value;
if(isNaN(inp)) {
document.getElementById("mobile_number").value = "";
}
}
function only_letters(x) {
inp = document.getElementById(x).value;
if(!/[a-z]/.test(inp.toLowerCase())) {
document.getElementById(x).value="";
}
}<file_sep>/web/materialize/js/script.js
$( document ).ready(function(){
$(".button-collapse").sideNav();
})
rand_list = []
function grid_gen() {
while (rand_list.length != 4) {
a = Math.floor(Math.random() * (7 - 1 + 1) + 0);
if (!rand_list.includes(a))
rand_list.push(a)
}
document.getElementById("grid_label0").innerHTML = rand_list[0];
document.getElementById("grid_label1").innerHTML = rand_list[1];
document.getElementById("grid_label2").innerHTML = rand_list[2];
document.getElementById("grid_label3").innerHTML = rand_list[3];
}
function compute_grid_string() {
grid_string = new String();
for (i = 0; i < 8; i++) {
if(!rand_list.includes(i))
grid_string += 0;
else
grid_string += document.getElementById(rand_list.indexOf(i)).value;
}
// alert(grid_string);
document.getElementById("hidden_field").value = grid_string;
alert(document.getElementById("hidden_field").value);
}<file_sep>/web/materialize/js/view_results_script.js
function indicate_winner() {
vote_count_cont1 = document.getElementById("votes_cont1").innerHTML;
vote_count_cont2 = document.getElementById("votes_cont2").innerHTML;
vote_count_cont3 = document.getElementById("votes_cont3").innerHTML;
max = Math.max(vote_count_cont1, vote_count_cont2, vote_count_cont3);
if (max == vote_count_cont1) {
document.getElementById("images_cell_cont1").className += "winner_cell_indicator";
document.getElementById("badge_cont1").className += "visible";
} else if (max == vote_count_cont2) {
document.getElementById("images_cell_cont2").className += "winner_cell_indicator";
document.getElementById("badge_cont2").className += "visible";
} else {
document.getElementById("images_cell_cont3").className += "winner_cell_indicator";
document.getElementById("badge_cont3").className += "visible";
}
}<file_sep>/web/materialize/js/vote_script.js
var iterationCount = 1000;
var keySize = 128;
var encryptionKey ="<KEY>";
var iv = "dc0da04af8fee58593442bf834b30739"
var salt = "<KEY>"
var AesUtil = function(keySize, iterationCount) {
this.keySize = keySize / 32;
this.iterationCount = iterationCount;
};
AesUtil.prototype.generateKey = function(salt, passPhrase) {
var key = CryptoJS.PBKDF2(passPhrase, CryptoJS.enc.Hex.parse(salt),{ keySize: this.keySize, iterations: this.iterationCount });
return key;
}
AesUtil.prototype.encrypt = function(salt, iv, passPhrase, plainText) {
var key = this.generateKey(salt, passPhrase);
var encrypted = CryptoJS.AES.encrypt(
plainText,
key,
{ iv: CryptoJS.enc.Hex.parse(iv) });
return encrypted.ciphertext.toString(CryptoJS.enc.Base64);
}
AesUtil.prototype.decrypt = function(salt, iv, passPhrase, cipherText) {
var key = this.generateKey(salt, passPhrase);
var cipherParams = CryptoJS.lib.CipherParams.create({
ciphertext: CryptoJS.enc.Base64.parse(cipherText)
});
}
function encrypt(msg){
var aesUtil = new AesUtil(keySize, iterationCount);
var cipher= aesUtil.encrypt(salt, iv, encryptionKey, msg);
return cipher;
}
function decodeUTF8(s) {
var i, d = unescape(encodeURIComponent(s)), b = new Uint8Array(d.length);
for (i = 0; i < d.length; i++) b[i] = d.charCodeAt(i);
return b;
}
function calculate_digest(msg) {
var h = new BLAKE2s(32);
h.update(decodeUTF8(msg));
h = h.hexDigest();
console.log(h);
return h;
}
function completeForm() {
var msg = document.querySelector('input[name="g1"]:checked').value.replace(/\r\n/g, '\n');
console.log("plain text "+msg);
var encryptedVote=encrypt(msg).toString();
var hashedVote=calculate_digest(msg).toString();
document.getElementById("encryptedVote").value=encryptedVote;
document.getElementById("hashedVote").value=hashedVote;
console.log('encryptedVote'+ document.getElementById("encryptedVote").value);
console.log('hashedVote'+document.getElementById("hashedVote").value);
return true;
}
<file_sep>/web/materialize/js/user_profile_script.js
/**
* Created by hardCode on 3/17/2017.
*/
$( document ).ready(function(){
$(".button-collapse").sideNav();
}) | 4fd6f42d6cb78fe3134a88534edc0985d4f6c0a1 | [
"JavaScript"
] | 5 | JavaScript | arpit728/evoting | 90cb367188297ff0d65a7370e2915a24704e43bc | 5edc488e0d9af62409e3ed7cfc437065dd98b89d |
refs/heads/master | <file_sep>#!/bin/bash
#
# A simple HTTP server that can serve up any directory, built with Dart.
#
dart "/usr/lib/dart/dart-dhttpd/dhttpd.snapshot" "$@"
<file_sep># CHANGELOG
## 0.3.1
* Fixed bug with setting the path from the command line.
* Start the server with `dhttpd`.
## 0.3.0
* New `host` command-line flag, to set
the hostname to listen on. Defaults
to `localhost`
## 0.2.0
* New `allow-origin` command-line flag for CORS headers.
Thanks to @gmosx for the patch.
<file_sep># Maintainer: <NAME> <<EMAIL>>
_pubname=dhttpd
pkgname=dart-$_pubname
pkgver=0.3.1
pkgrel=1
pkgdesc="A simple HTTP server that can serve up any directory, built with Dart."
arch=('any')
url="https://github.com/sethladd/dhttpd"
license=('custom')
depends=('dart')
changelog=CHANGELOG.md
source=("https://storage.googleapis.com/pub.dartlang.org/packages/$_pubname-$pkgver.tar.gz"
"local://$_pubname")
md5sums=('bcf3bf652dda26e76de1f3295e166503'
'32392f34d46b75089b185ac43c3f364a')
build() {
cd $srcdir
pub get
dart --snapshot=$_pubname.snapshot bin/dhttpd.dart
}
package() {
install -Dm755 $srcdir/LICENSE $pkgdir/usr/share/licenses/$pkgname/LICENSE
install -Dm755 $srcdir/README.md $pkgdir/usr/share/doc/$pkgname/README.md
install -Dm755 $srcdir/$_pubname.snapshot $pkgdir/usr/lib/dart/$pkgname/$_pubname.snapshot
install -Dm755 $srcdir/$_pubname $pkgdir/usr/bin/$_pubname
}
| 723c771b6076e9432218dd0439a54888c4b31b16 | [
"Markdown",
"Shell"
] | 3 | Shell | fxleblanc-pkg/dart-dhttpd | 8e4f18999c82eaacb4f2aede562362fcdc1798b1 | 02d1f2a00f91041e05d12b17ef353fb872cfaa09 |
refs/heads/master | <repo_name>ly774508966/GameWork.Core<file_sep>/GameWork.Core.Logging.Tests/MockObjects/LogMessage.cs
using System;
namespace GameWork.Core.Logging.Tests.MockObjects
{
public class LogMessage
{
public LogLevel LogLevel { get; set; }
public string Message { get; set; }
public Exception Exception { get; set; }
}
}
<file_sep>/GameWork.Core.States/Event/EventStateTransition.cs
using System;
namespace GameWork.Core.States.Event
{
public abstract class EventStateTransition
{
internal event Action<string> EnterStateEvent;
internal event Action<string> ExitStateEvent;
protected virtual void OnEnter(string fromStateName)
{
}
protected virtual void OnExit(string toStateName)
{
}
protected virtual void EnterState(string toStateName)
{
EnterStateEvent?.Invoke(toStateName);
}
protected virtual void ExitState(string toStateName)
{
ExitStateEvent?.Invoke(toStateName);
}
internal virtual void Enter(string fromStateName)
{
OnEnter(fromStateName);
}
internal virtual void Exit(string toStateName)
{
OnExit(toStateName);
}
}
}
<file_sep>/GameWork.Core.States.Tests/StateTransitionTests.cs
using GameWork.Core.States.Tests.TestObjects;
using GameWork.Core.States.Tick;
using NUnit.Framework;
using TickStateTransition = GameWork.Core.States.Tests.TestObjects.TickStateTransition;
namespace GameWork.Core.States.Tests
{
[TestFixture]
public class StateTransitionTests
{
private readonly StateTransitionBlackboard _stateTransitionBlackboard;
private readonly TickState[] _states;
private TickStateController _stateController;
public StateTransitionTests()
{
_stateTransitionBlackboard = new StateTransitionBlackboard();
var testStateOne = new TestStateOne();
testStateOne.AddTransitions(new TickStateTransition(TestStateTwo.StateName, _stateTransitionBlackboard));
var testStateTwo = new TestStateTwo();
testStateTwo.AddTransitions(new TickStateTransition(TestStateThree.StateName, _stateTransitionBlackboard));
var testStateThree = new TestStateThree();
testStateThree.AddTransitions(new TickStateTransition(TestStateOne.StateName, _stateTransitionBlackboard));
_states = new TickState[]
{
testStateOne, testStateTwo, testStateThree
};
}
[SetUp]
public void Setup()
{
_stateController = new TickStateController(_states);
}
[TestCase("One", "Two")]
[TestCase("Two", "Three")]
[TestCase("Three", "One")]
public void TickTransition(string fromStateName, string toStateName)
{
// Arrange
_stateController.Initialize();
_stateController.EnterState(fromStateName);
_stateTransitionBlackboard.ToStateName = toStateName;
// Act
_stateController.Tick(0f);
// Assert
Assert.AreEqual(toStateName, _stateController.ActiveStateName);
}
}
}<file_sep>/GameWork.Core.States/State.cs
namespace GameWork.Core.States
{
public abstract class State
{
public abstract string Name { get; }
public bool IsActive { get; private set; }
protected StateControllerBase StateController { get; private set; }
protected virtual void OnInitialize()
{
}
protected virtual void OnTerminate()
{
}
protected virtual void OnEnter()
{
}
protected virtual void OnExit()
{
}
internal void SetStateController(StateControllerBase stateController)
{
StateController = stateController;
}
internal virtual void Initialize()
{
OnInitialize();
}
internal virtual void Terminate()
{
OnTerminate();
}
internal virtual void Enter(string fromStateName)
{
OnEnter();
IsActive = true;
}
internal virtual void Exit(string toStateName)
{
OnExit();
IsActive = false;
}
}
}<file_sep>/GameWork.Core.Audio/Fade/Interfaces/IAudioFade.cs
using GameWork.Core.Audio.Clip;
namespace GameWork.Core.Audio.Fade.Interfaces
{
public interface IAudioFade
{
AudioClipModel Clip { get; }
bool IsComplete { get; }
float Volume { get; }
float TargetVolume { get; }
float Duration { get; }
void AddDeltaTime(float deltaTime);
}
}<file_sep>/GameWork.Core.IO/PlatformAdaptors/ITextFileLoader.cs
namespace GameWork.Core.IO.PlatformAdaptors
{
public interface ITextFileLoader : IFileLoader
{
}
}<file_sep>/GameWork.Core.Audio/Fade/AudioMultiFade.cs
using System;
using GameWork.Core.Audio.Fade.Interfaces;
using GameWork.Core.Math;
using GameWork.Core.Audio.Clip;
namespace GameWork.Core.Audio.Fade
{
public class AudioMultiFade : IAudioFade
{
private readonly AudioFadeModel[] _audioFadeModels;
private AudioFadeModel _currentModel;
private float _completedDurations;
private float _elapsedTime;
public AudioClipModel Clip { get; private set; }
public bool IsComplete
{
get { return _completedDurations + _currentModel.Duration <= _elapsedTime; }
}
public float Volume
{
get
{
return MathF.Lerp(_currentModel.StartVolume,
_currentModel.TargetVolume,
(_elapsedTime - _completedDurations) / _currentModel.Duration);
}
}
public float TargetVolume
{
get { return _currentModel.TargetVolume; }
}
public float Duration
{
get { return _currentModel.Duration; }
}
public AudioMultiFade(AudioClipModel clip, params AudioFadeModel[] audioFadeModels)
{
Clip = clip;
_audioFadeModels = audioFadeModels;
_currentModel = audioFadeModels[0];
}
public void AddDeltaTime(float deltaTime)
{
_elapsedTime += deltaTime;
var nextModelIndex = Array.IndexOf(_audioFadeModels, _currentModel) + 1;
while (_completedDurations + _currentModel.Duration < _elapsedTime)
{
if (nextModelIndex < _audioFadeModels.Length)
{
_completedDurations += _currentModel.Duration;
_currentModel = _audioFadeModels[nextModelIndex];
nextModelIndex++;
}
else
{
break;
}
}
}
}
}<file_sep>/GameWork.Core.States.Tests/TestObjects/TestStateThree.cs
using GameWork.Core.States.Tick;
namespace GameWork.Core.States.Tests.TestObjects
{
public class TestStateThree : TickState
{
public const string StateName = "Three";
public override string Name
{
get { return StateName; }
}
}
}
<file_sep>/GameWork.Core.Components/ComponentContainer.cs
using System;
using System.Collections.Generic;
using System.Linq;
using GameWork.Core.Components.Interfaces;
namespace GameWork.Core.Components
{
public class ComponentContainer
{
private readonly Dictionary<Type, IComponent> Components = new Dictionary<Type, IComponent>();
public bool HasComponent<TComponent>() where TComponent : IComponent
{
var componentType = typeof(TComponent);
return Components.ContainsKey(componentType)
|| Components.Keys.Any(k => k.IsAssignableFrom(componentType));
}
public bool TryGetComponent<TComponent>(out TComponent component) where TComponent : IComponent
{
var didGetComponent = false;
component = default(TComponent);
IComponent baseTypeComponent;
if (Components.TryGetValue(typeof(TComponent), out baseTypeComponent))
{
didGetComponent = true;
component = (TComponent) baseTypeComponent;
}
else
{
Type assignableType;
if (TryGetAssignableType<TComponent>(out assignableType))
{
didGetComponent = true;
component = (TComponent)Components[assignableType];
}
}
return didGetComponent;
}
public bool TryAddComponent(IComponent component)
{
var didAddComponent = false;
var type = component.GetType();
if (!Components.ContainsKey(type))
{
Components[type] = component;
didAddComponent = true;
}
return didAddComponent;
}
public bool TryRemoveComponent(IComponent component)
{
return TryRemoveComponent(component.GetType());
}
public bool TryRemoveComponent<TComponent>() where TComponent : IComponent
{
return TryRemoveComponent(typeof(TComponent));
}
private bool TryRemoveComponent(Type findType)
{
var didRemove = false;
if (Components.Remove(findType))
{
didRemove = true;
}
else
{
Type assignableType;
if(TryGetAssignableType(findType, out assignableType))
{
didRemove = Components.Remove(assignableType);
}
}
return didRemove;
}
private bool TryGetAssignableType<TComponent>(out Type assignableType) where TComponent : IComponent
{
return TryGetAssignableType(typeof(TComponent), out assignableType);
}
private bool TryGetAssignableType(Type findType, out Type assignableType)
{
assignableType = Components.Keys.FirstOrDefault(k => k.IsAssignableFrom(findType));
return assignableType != null;
}
}
}
<file_sep>/GameWork.Core.IO/PlatformAdaptors/IFileLoader.cs
using System.IO;
namespace GameWork.Core.IO.PlatformAdaptors
{
public interface IFileLoader
{
Stream Load(string path);
}
}<file_sep>/GameWork.Core.Localization/LocalizationManager.cs
using System;
using System.Collections.Generic;
using GameWork.Core.Logging.PlatformAdaptors;
namespace GameWork.Core.Localization
{
public class LocalizationManager
{
private readonly ILogger _logger;
private LocalizationModel _model;
private Dictionary<string, string> _currentLocalization;
public event Action SetLocaleEvent;
public LocalizationManager(ILogger logger)
{
_logger = logger;
}
public void SetModel(LocalizationModel model)
{
_model = model;
SetLocale(_model.Default);
}
public void SetLocale(string localeId)
{
_currentLocalization = _model.Localizations[localeId];
if (SetLocaleEvent != null)
{
SetLocaleEvent();
}
}
public string GetLocalization(string id)
{
if (!_currentLocalization.ContainsKey(id))
{
_logger.Error("Localization doesn't contain key for: \"" + id + "\"");
return string.Empty;
}
return _currentLocalization[id];
}
public bool HasLocale(string locale)
{
return _model.Localizations.ContainsKey(locale);
}
public void Reset()
{
SetLocale(_model.Default);
}
}
}
<file_sep>/GameWork.Core.Localization/LocalizationModel.cs
using GameWork.Core.Models.Interfaces;
using System.Collections.Generic;
namespace GameWork.Core.Localization
{
public struct LocalizationModel : IModel
{
public string Default { get; set; }
public Dictionary<string, Dictionary<string, string>> Localizations { get; set; }
}
}<file_sep>/GameWork.Core.Math.Tests/MathFTests.cs
using NUnit.Framework;
namespace GameWork.Core.Math.Tests
{
[TestFixture]
public class MathFTests
{
[TestCase(-11, 9, 0.5f, -1)]
[TestCase(11, -9, 0.5f, 1)]
[TestCase(2000, 1000, 0.2f, 1800)]
[TestCase(1000, 2000, 0.2f, 1200)]
[TestCase(-2000, -1000, 0.2f, -1800)]
[TestCase(-1000, -2000, 0.2f, -1200)]
[TestCase(10, -10, 4, -10)]
[TestCase(10, -10, -5, 10)]
public void Lerp(float start, float end, float weight, float expected)
{
var result = MathF.Lerp(start, end, weight);
Assert.AreEqual(expected, result);
}
[TestCase(2, 0, 1, 1)]
[TestCase(-2, 0, 1, 0)]
[TestCase(0.5f, 0, 1, 0.5f)]
[TestCase(-300, -100, 100, -100)]
[TestCase(300, -100, 100, 100)]
[TestCase(-25, -100, 100, -25)]
public void Clamp(float val, float min, float max, float expected)
{
var result = val.Clamp(min, max);
Assert.AreEqual(expected, result);
}
[TestCase(100, 100)]
[TestCase(-100, 100)]
public void Abs(float val, float expected)
{
var result = MathF.Abs(val);
Assert.AreEqual(expected, result);
}
}
}
<file_sep>/GameWork.Core.Audio/Clip/AudioClipModel.cs
namespace GameWork.Core.Audio.Clip
{
public class AudioClipModel
{
public string Name { get; set; }
public float TargetVolume { get; set; }
public float Duration { get; set; }
}
}<file_sep>/GameWork.Core.Audio/MultiClip/MultiClipModel.cs
using GameWork.Core.Audio.Clip;
using GameWork.Core.Models.Interfaces;
namespace GameWork.Core.Audio.MultiClip
{
public class MultiClipModel : IModel
{
public AudioClipModel[] Clips { get; set; }
}
}<file_sep>/GameWork.Core.Audio/MultiClip/MultiClip.cs
using GameWork.Core.Audio.Clip;
using GameWork.Core.Utilities;
namespace GameWork.Core.Audio.MultiClip
{
public class MultiClip
{
private readonly MultiClipModel _model;
private int _previousIndex = int.MinValue;
public MultiClip(MultiClipModel model)
{
_model = model;
}
public AudioClipModel GetRandom()
{
var randomIndex = RandomUtil.Next(_model.Clips.Length);
return _model.Clips[randomIndex];
}
public AudioClipModel GetDifferentRandom()
{
var randomIndex = RandomUtil.Next(_model.Clips.Length);
if(_previousIndex == randomIndex)
{
randomIndex = (randomIndex + 1) % _model.Clips.Length;
}
_previousIndex = randomIndex;
return _model.Clips[randomIndex];
}
}
}<file_sep>/GameWork.Core.States.Tests/TestObjects/StateTransitionBlackboard.cs
namespace GameWork.Core.States.Tests.TestObjects
{
public class StateTransitionBlackboard
{
public string ToStateName { get; set; }
}
}
<file_sep>/GameWork.Core.States/StateController.cs
using System;
using System.Collections.Generic;
namespace GameWork.Core.States
{
public class StateController : StateController<State>
{
public StateController(params State[] states) : base(states)
{
}
}
public class StateController<TState> : StateControllerBase
where TState : State
{
protected readonly Dictionary<string, TState> States = new Dictionary<string, TState>();
public string ActiveStateName { protected set; get; }
protected bool IsProcessingStateChange { get; set; }
protected string LastActiveStateName { get; set; }
public StateController(params TState[] states)
{
foreach (var state in states)
{
States.Add(state.Name, state);
state.SetStateController(this);
}
}
public void Initialize()
{
foreach (var state in States.Values)
{
state.Initialize();
}
OnInitialize();
}
public void Terminate()
{
OnTerminate();
if (ActiveStateName != null)
{
States[ActiveStateName].Exit(null);
}
foreach (var state in States.Values)
{
state.Terminate();
}
}
protected virtual void OnInitialize()
{
}
protected virtual void OnTerminate()
{
}
public override void ExitState(string toStateName)
{
IsProcessingStateChange = true;
if (ActiveStateName != null)
{
LastActiveStateName = ActiveStateName;
ActiveStateName = null;
States[LastActiveStateName].Exit(toStateName);
}
if (!States.ContainsKey(toStateName))
{
if (ParentController != null)
{
ParentController.ExitState(toStateName);
}
else
{
throw new ArgumentOutOfRangeException($"No state with the name: {toStateName} was found" +
$"There is also no parent {nameof(StateController)} set, which may also resolve the state change.");
}
}
}
public override void EnterState(string toStateName)
{
if (States.ContainsKey(toStateName))
{
States[toStateName].Enter(LastActiveStateName);
ActiveStateName = toStateName;
}
else
{
ParentController.EnterState(toStateName);
}
IsProcessingStateChange = false;
}
}
}<file_sep>/GameWork.Core.Components.Tests/ComponentContainerTests.cs
using GameWork.Core.Components.Tests.MockObjects;
using NUnit.Framework;
namespace GameWork.Core.Components.Tests
{
public class ComponentContainerTests
{
[Test]
public void AddComponent()
{
var component = new MockMesh();
var componentContainer = new ComponentContainer();
Assert.IsTrue(componentContainer.TryAddComponent(component));
}
[Test]
public void AddDuplicateComponent()
{
var component = new MockMesh();
var componentContainer = new ComponentContainer();
Assert.IsTrue(componentContainer.TryAddComponent(component));
Assert.IsFalse(componentContainer.TryAddComponent(component));
}
[Test]
public void HasComponent()
{
var component = new MockMesh();
var componentContainer = new ComponentContainer();
componentContainer.TryAddComponent(component);
Assert.IsTrue(componentContainer.HasComponent<MockMesh>());
}
[Test]
public void DoesntHaveComponent()
{
var component = new MockMesh();
var componentContainer = new ComponentContainer();
Assert.IsFalse(componentContainer.HasComponent<MockMesh>());
componentContainer.TryAddComponent(component);
Assert.IsFalse(componentContainer.HasComponent<MockTransform>());
}
[Test]
public void GetComponent()
{
var component = new MockMesh();
var componentContainer = new ComponentContainer();
componentContainer.TryAddComponent(component);
MockMesh gotComponent;
Assert.IsTrue(componentContainer.TryGetComponent(out gotComponent));
Assert.AreSame(component, gotComponent);
}
[Test]
public void CantGetComponent()
{
var component = new MockMesh();
var componentContainer = new ComponentContainer();
componentContainer.TryAddComponent(component);
MockTransform gotComponent;
Assert.IsFalse(componentContainer.TryGetComponent(out gotComponent));
Assert.AreNotSame(component, gotComponent);
Assert.IsNull(gotComponent);
}
[Test]
public void RemoveComponentInstance()
{
var component = new MockMesh();
var componentContainer = new ComponentContainer();
componentContainer.TryAddComponent(component);
Assert.IsTrue(componentContainer.TryRemoveComponent(component));
Assert.IsFalse(componentContainer.HasComponent<MockMesh>());
}
[Test]
public void RemoveComponentType()
{
var component = new MockMesh();
var componentContainer = new ComponentContainer();
componentContainer.TryAddComponent(component);
Assert.IsTrue(componentContainer.TryRemoveComponent<MockMesh>());
Assert.IsFalse(componentContainer.HasComponent<MockMesh>());
}
}
}
<file_sep>/GameWork.Core.IO/CSV.cs
namespace GameWork.Core.IO
{
public static class CSV
{
private const char Delimiter = ',';
public static string[] ParseRow(string line)
{
return line.Split(Delimiter);
}
}
}<file_sep>/GameWork.Core.States/StateControllerBase.cs
namespace GameWork.Core.States
{
public abstract class StateControllerBase
{
protected StateControllerBase ParentController;
public abstract void ExitState(string toStateName);
public abstract void EnterState(string toStateName);
public void SetParent(StateControllerBase parentController)
{
ParentController = parentController;
}
}
}
<file_sep>/GameWork.Core.Commands.Tests/CommandResolverTests.cs
using System.Collections.Generic;
using GameWork.Core.Commands.Interfaces;
using GameWork.Core.Commands.Tests.TestObjects;
using NUnit.Framework;
namespace GameWork.Core.Commands.Tests
{
[TestFixture]
public class CommandResolverTests
{
[Test]
public void ResolveSingleCommand()
{
// Setup
var values = new List<string>()
{
"Hannah",
"Bob",
"Frank",
"Franchesca",
"Zoltan"
};
var testCollection = new TestCollection<string>();
var testCollectionCommandResolver = new TestCollectionCommandResolver<string>(testCollection);
Assert.AreEqual(0, testCollection.Count);
// Process
foreach (var value in values)
{
testCollectionCommandResolver.ProcessCommand(new AddToTestCollectionCommand<string>(value));
}
// Assert
Assert.AreEqual(values.Count, testCollection.Count);
CollectionAssert.AreEqual(values, testCollection);
}
[Test]
public void ResolveMultipleCommands()
{
// Setup
var values = new List<string>()
{
"Hannah",
"Bob",
"Frank",
"Franchesca",
"Zoltan"
};
var testCollection = new TestCollection<string>();
var testCollectionCommandResolver = new TestCollectionCommandResolver<string>(testCollection);
Assert.AreEqual(0, testCollection.Count);
var commands = new List<ICommand>();
foreach (var value in values)
{
commands.Add(new AddToTestCollectionCommand<string>(value));
}
// Process
testCollectionCommandResolver.ProcessCommands(commands);
// Assert
Assert.AreEqual(values.Count, testCollection.Count);
CollectionAssert.AreEqual(values, testCollection);
}
[Test]
public void ResolveCommandQueue()
{
// Setup
var values = new List<string>()
{
"Hannah",
"Bob",
"Frank",
"Franchesca",
"Zoltan"
};
var commandQueue = new CommandQueue();
// Process
foreach (var value in values)
{
commandQueue.AddCommand(new AddToTestCollectionCommand<string>(value));
}
var testCollection = new TestCollection<string>();
var testCollectionCommandResolver = new TestCollectionCommandResolver<string>(testCollection);
// Assert
Assert.AreEqual(0, testCollection.Count);
testCollectionCommandResolver.ProcessCommandQueue(commandQueue);
Assert.AreEqual(values.Count, testCollection.Count);
CollectionAssert.AreEqual(values, testCollection);
}
}
}
<file_sep>/GameWork.Core.States/Event/EventState.cs
using System.Collections.Generic;
namespace GameWork.Core.States.Event
{
public abstract class EventState : State
{
private readonly List<EventStateTransition> _transitions = new List<EventStateTransition>();
public void AddTransitions(params EventStateTransition[] stateTransitions)
{
_transitions.AddRange(stateTransitions);
}
internal override void Enter(string fromStateName)
{
base.Enter(fromStateName);
_transitions.ForEach(t => t.Enter(fromStateName));
}
internal override void Exit(string toStateName)
{
_transitions.ForEach(t => t.Exit(toStateName));
base.Exit(toStateName);
}
internal void ConnectTransitions(StateControllerBase stateController)
{
foreach (var transition in _transitions)
{
transition.ExitStateEvent += stateController.ExitState;
transition.EnterStateEvent += stateController.EnterState;
}
}
internal void DisconnectTransisions(StateControllerBase stateController)
{
foreach (var transition in _transitions)
{
transition.ExitStateEvent -= stateController.ExitState;
transition.EnterStateEvent -= stateController.EnterState;
}
}
}
}<file_sep>/GameWork.Core.Commands.Tests/TestObjects/TestAccountCommandResolver.cs
using GameWork.Core.Commands.Accounts;
using GameWork.Core.Commands.Interfaces;
namespace GameWork.Core.Commands.Tests.TestObjects
{
public class TestAccountCommandResolver : CommandResolver
{
private readonly TestAccountContoller _accountController;
public TestAccountCommandResolver(TestAccountContoller accountContoller)
{
_accountController = accountContoller;
}
public override void ProcessCommand(ICommand command)
{
var registerCommand = command as RegisterCommand;
if (registerCommand != null)
{
registerCommand.Execute(_accountController);
return;
}
var loginCommand = command as LoginCommand;
if (loginCommand != null)
{
loginCommand.Execute(_accountController);
return;
}
var logoutCommand = command as LogoutCommand;
if (logoutCommand != null)
{
logoutCommand.Execute(_accountController);
return;
}
}
}
}
<file_sep>/GameWork.Core.Audio/PlatformAdaptors/IAudioChannelFactory.cs
namespace GameWork.Core.Audio.PlatformAdaptors
{
public interface IAudioChannelFactory
{
IAudioChannel Create();
}
}
<file_sep>/GameWork.Core.IO/PlatformAdaptors/IJSONReader.cs
using System.IO;
using GameWork.Core.Models.Interfaces;
namespace GameWork.Core.IO.PlatformAdaptors
{
public interface IJsonReader
{
TModel ConstructModel<TModel>(Stream stream) where TModel : IModel;
}
}<file_sep>/GameWork.Core.Logging/PlatformAdaptors/ILogger.cs
using System;
namespace GameWork.Core.Logging.PlatformAdaptors
{
public interface ILogger
{
/// <summary>
/// Information tracking the usage of the system.
/// </summary>
/// <param name="message"></param>
void Info(string message);
/// <summary>
/// Information to help with debugging
/// </summary>
/// <param name="message"></param>
void Debug(string message);
/// <summary>
/// Issues that should be addressed but do not break gameplay/user experience.
/// </summary>
/// <param name="message"></param>
void Warning(string message);
/// <summary>
/// Issues that break gameplay/user experience.
/// </summary>
/// <param name="message"></param>
void Error(string message);
/// <summary>
/// Issues that break gameplay/user experience.
/// </summary>
/// <param name="exception"></param>
void Error(Exception exception);
/// <summary>
/// Issues that would/should crash the game.
/// </summary>
/// <param name="message"></param>
void Fatal(string message);
/// <summary>
/// Issues that would/should crash the game.
/// </summary>
/// <param name="exception"></param>
void Fatal(Exception exception);
}
}<file_sep>/GameWork.Core.States/Event/EventStateController.cs
namespace GameWork.Core.States.Event
{
public class EventStateController : EventStateController<EventState>
{
}
public class EventStateController<TState> : StateController<TState>
where TState : EventState
{
public EventStateController(params TState[] states) : base(states)
{
}
public override void EnterState(string toStateName)
{
if (LastActiveStateName != null)
{
States[LastActiveStateName].DisconnectTransisions(this);
}
if (States.ContainsKey(toStateName))
{
States[toStateName].ConnectTransitions(this);
}
base.EnterState(toStateName);
}
}
}<file_sep>/README.md
GameWork.Core
Engine agnostic C# Framework for building games
Source:
https://github.com/Game-Work/GameWork.Core
Build Tools:
BuildAll: Run .\Tools\BuildAll.ps1<file_sep>/GameWork.Core.Audio/MultiClip/MultiClipFactory.cs
using System.Collections.Generic;
namespace GameWork.Core.Audio.MultiClip
{
public class MultiClipFactory
{
private readonly Dictionary<string, MultiClipModel> _models = new Dictionary<string, MultiClipModel>();
public void AddModel(string id, MultiClipModel model)
{
_models[id] = model;
}
public MultiClip Create(string id)
{
return new MultiClip(_models[id]);
}
}
}<file_sep>/GameWork.Core.Audio/Fade/AudioFade.cs
using GameWork.Core.Audio.Clip;
using GameWork.Core.Audio.Fade.Interfaces;
using GameWork.Core.Math;
namespace GameWork.Core.Audio.Fade
{
public class AudioFade : IAudioFade
{
private readonly AudioFadeModel _model;
private float _elapsedTime;
public AudioClipModel Clip { get; private set; }
public bool IsComplete
{
get { return _model.Duration <= _elapsedTime; }
}
public float Volume
{
get { return MathF.Lerp(_model.StartVolume, _model.TargetVolume, _elapsedTime / _model.Duration); }
}
public float TargetVolume
{
get { return _model.TargetVolume; }
}
public float Duration
{
get { return _model.Duration; }
}
public AudioFade(AudioClipModel clip, float startVolume, float targetVolume, float duration)
{
Clip = clip;
_model = new AudioFadeModel(startVolume, targetVolume, duration);
}
public void AddDeltaTime(float deltaTime)
{
_elapsedTime += deltaTime;
}
}
}<file_sep>/GameWork.Core.Logging.Tests/MockObjects/MockLogger.cs
using System;
using System.Collections.Generic;
using GameWork.Core.Logging.PlatformAdaptors;
namespace GameWork.Core.Logging.Tests.MockObjects
{
public class MockLogger : ILogger
{
public readonly List<LogMessage> Messages = new List<LogMessage>();
public void Debug(string message)
{
Messages.Add(new LogMessage
{
LogLevel = LogLevel.Debug,
Message = message
});
}
public void Error(Exception exception)
{
Messages.Add(new LogMessage
{
LogLevel = LogLevel.Error,
Exception = exception
});
}
public void Error(string message)
{
Messages.Add(new LogMessage
{
LogLevel = LogLevel.Error,
Message = message
});
}
public void Fatal(Exception exception)
{
Messages.Add(new LogMessage
{
LogLevel = LogLevel.Fatal,
Exception = exception
});
}
public void Fatal(string message)
{
Messages.Add(new LogMessage
{
LogLevel = LogLevel.Fatal,
Message = message
});
}
public void Info(string message)
{
Messages.Add(new LogMessage
{
LogLevel = LogLevel.Info,
Message = message
});
}
public void Warning(string message)
{
Messages.Add(new LogMessage
{
LogLevel = LogLevel.Warning,
Message = message
});
}
}
}
<file_sep>/GameWork.Core.Logging/LogUtil.cs
using System;
using GameWork.Core.Logging.PlatformAdaptors;
namespace GameWork.Core.Logging
{
public class LogUtil
{
private static ILogger _logger;
public static LogLevel LogLevel { get; set; }
public static void SetLogger(ILogger logger)
{
_logger = logger;
}
public static void Fatal(Exception exception)
{
if (LogLevel.Fatal <= LogLevel)
{
_logger.Fatal(exception);
}
}
public static void Fatal(string message)
{
if (LogLevel.Fatal <= LogLevel)
{
_logger.Fatal(message);
}
}
public static void Error(Exception exception)
{
if (LogLevel.Error <= LogLevel)
{
_logger.Error(exception);
}
}
public static void Error(string message)
{
if (LogLevel.Error <= LogLevel)
{
_logger.Error(message);
}
}
public static void Warning(string message)
{
if (LogLevel.Warning <= LogLevel)
{
_logger.Warning(message);
}
}
public static void Debug(string message)
{
if (LogLevel.Debug <= LogLevel)
{
_logger.Debug(message);
}
}
public static void Info(string message)
{
if(LogLevel.Info <= LogLevel)
{
_logger.Info(message);
}
}
}
}
<file_sep>/GameWork.Core.States/Event/Input/EventStateInput.cs
using GameWork.Core.States.Input;
namespace GameWork.Core.States.Event.Input
{
public abstract class InputEventState : InputEventState<StateInput>
{
protected InputEventState(StateInput stateInput) : base(stateInput)
{
}
}
public abstract class InputEventState<TStateInput> : EventState
where TStateInput : StateInput
{
internal readonly TStateInput StateInput;
protected InputEventState(TStateInput stateInput)
{
StateInput = stateInput;
}
}
}<file_sep>/GameWork.Core.Logging.Tests/LogUtilTests.cs
using System;
using System.Linq;
using GameWork.Core.Logging.Tests.MockObjects;
using NUnit.Framework;
namespace GameWork.Core.Logging.Tests
{
public class LogUtilTests
{
[Test]
public void LogsInfo()
{
// Arrange
var logger = new MockLogger();
LogUtil.SetLogger(logger);
LogUtil.LogLevel = LogLevel.Info;
// Act
LogAll();
// Assert
Assert.True(logger.Messages.All(m => m.LogLevel <= LogLevel.Info));
}
[Test]
public void LogsDebug()
{
// Arrange
var logger = new MockLogger();
LogUtil.SetLogger(logger);
LogUtil.LogLevel = LogLevel.Debug;
// Act
LogAll();
// Assert
Assert.True(logger.Messages.All(m => m.LogLevel <= LogLevel.Debug));
}
[Test]
public void LogsWarning()
{
// Arrange
var logger = new MockLogger();
LogUtil.SetLogger(logger);
LogUtil.LogLevel = LogLevel.Warning;
// Act
LogAll();
// Assert
Assert.True(logger.Messages.All(m => m.LogLevel <= LogLevel.Warning));
}
[Test]
public void LogsErrorMessage()
{
// Arrange
var logger = new MockLogger();
LogUtil.SetLogger(logger);
LogUtil.LogLevel = LogLevel.Error;
// Act
LogAll();
// Assert
Assert.True(logger.Messages.All(m => m.LogLevel <= LogLevel.Error));
Assert.True(logger.Messages.Any(m => m.Message != null));
}
[Test]
public void LogsErrorException()
{
// Arrange
var logger = new MockLogger();
LogUtil.SetLogger(logger);
LogUtil.LogLevel = LogLevel.Error;
// Act
LogAll();
// Assert
Assert.True(logger.Messages.All(m => m.LogLevel <= LogLevel.Error));
Assert.True(logger.Messages.Any(m => m.Exception != null));
}
[Test]
public void LogsFatalMessage()
{
// Arrange
var logger = new MockLogger();
LogUtil.SetLogger(logger);
LogUtil.LogLevel = LogLevel.Fatal;
// Act
LogAll();
// Assert
Assert.True(logger.Messages.All(m => m.LogLevel <= LogLevel.Fatal));
Assert.True(logger.Messages.Any(m => m.Message != null));
}
[Test]
public void LogsFatalException()
{
// Arrange
var logger = new MockLogger();
LogUtil.SetLogger(logger);
LogUtil.LogLevel = LogLevel.Fatal;
// Act
LogAll();
// Assert
Assert.True(logger.Messages.All(m => m.LogLevel <= LogLevel.Fatal));
Assert.True(logger.Messages.Any(m => m.Exception != null));
}
private void LogAll()
{
LogUtil.Info("info");
LogUtil.Debug("debug");
LogUtil.Warning("warning");
LogUtil.Error("error");
LogUtil.Error(new Exception("error"));
LogUtil.Fatal("fatal");
LogUtil.Fatal(new Exception("fatal"));
}
}
}
<file_sep>/GameWork.Core.Math.Tests/Vector3Tests.cs
using GameWork.Core.Math.Types;
using NUnit.Framework;
namespace GameWork.Core.Math.Tests
{
public class Vector3Tests
{
[Test]
public void Add()
{
var a = new Vector3(1, 2, 3);
var b = new Vector3(4, 5, 6);
var expected = new Vector3(5, 7, 9);
var result = a + b;
Assert.AreEqual(expected, result);
}
[Test]
public void Subtract()
{
var a = new Vector3(1, 2, 3);
var b = new Vector3(4, 5, 6);
var expected = new Vector3(-3, -3, -3);
var result = a - b;
Assert.AreEqual(expected, result);
}
}
}
| a224b1b4a18dca1ab9ada6f5b4d6b9bd0b689ca8 | [
"Markdown",
"C#"
] | 36 | C# | ly774508966/GameWork.Core | a33c59600069489a7b28a12a446295d1180039be | cb054d0230c761107c3922798aac35f60d76734d |
refs/heads/master | <repo_name>Svem1rko/AdventOfCode<file_sep>/Day8_1/Program.cs
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Day8
{
class Program
{
static void Main(string[] args)
{
string projectFolder = Directory.GetParent(Directory.GetCurrentDirectory()).Parent.FullName;
string fileName = Path.Combine(projectFolder, @"input.txt");
string[] lines = File.ReadAllLines(fileName);
HashSet<Register> registers = new HashSet<Register>();
int max = 0;
foreach (string s in lines)
{
string[] line = s.Split(' ');
var registar = new Register(line[0]);
registers.Add(registar);
var a = registers.First(r => r.Name.Equals(line[0]));
if (Condition(registers, line[4], line[5], line[6]))
{
if (line[1].Equals("inc"))
{
a.Value += Int32.Parse(line[2]);
}
else
{
a.Value -= Int32.Parse(line[2]);
}
}
if (a.Value > max)
{
max = a.Value;
}
registers.Remove(a);
registers.Add(a);
}
Console.WriteLine("Part one :" + registers.Max(r => r.Value));
Console.WriteLine("Part two: " + max);
Console.ReadLine();
}
private static bool Condition(HashSet<Register> registers, string register, string condition, string value)
{
var a = registers.FirstOrDefault(r => r.Name.Equals(register));
if (a == null)
{
a = new Register(register);
}
if (condition.Equals(">"))
{
return a.Value > Int32.Parse(value);
}
else if (condition.Equals("<"))
{
return a.Value < Int32.Parse(value);
}
else if (condition.Equals(">="))
{
return a.Value >= Int32.Parse(value);
}
else if (condition.Equals("<="))
{
return a.Value <= Int32.Parse(value);
}
else if (condition.Equals("=="))
{
return a.Value == Int32.Parse(value);
}
else if (condition.Equals("!="))
{
return a.Value != Int32.Parse(value);
}
return false;
}
}
class Register
{
public string Name { get; set; }
public int Value { get; set; }
public Register(string name)
{
Name = name;
Value = 0;
}
public override bool Equals(object obj)
{
if (!(obj is Register register))
{
return false;
}
return register.Name.Equals(Name);
}
public override int GetHashCode()
{
return Name.GetHashCode();
}
}
}
<file_sep>/Day1/Program.cs
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Day1
{
class Program
{
static void Main(string[] args)
{
string projectFolder = Directory.GetParent(Directory.GetCurrentDirectory()).Parent.FullName;
string fileName = Path.Combine(projectFolder, @"input.txt");
var line = File.ReadAllText(fileName).ToCharArray();
int sum = 0;
for (int i = 0; i < line.Length - 1; i++)
{
if (line[i] == line[i + 1])
sum += line[i] - 48;
}
if (line[line.Length - 1] == line[0])
{
sum += line[0] - 48;
}
var jump = line.Length / 2;
var sum2 = 0;
for (int i = 0; i < line.Length; i++)
{
int index = (i + jump) % line.Length;
if (line[i] == line[index])
{
sum2 += line[i] - 48;
}
}
Console.WriteLine("Part one: " + sum);
Console.WriteLine("Part two: " + sum2);
Console.ReadLine();
}
}
}
<file_sep>/Day2_2/Program.cs
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
namespace AdventOfCode
{
class Day2_2
{
static void Main(string[] args)
{
string projectFolder = Directory.GetParent(Directory.GetCurrentDirectory()).Parent.FullName;
string fileName = Path.Combine(projectFolder, @"input.txt");
string[] lines = File.ReadAllLines(fileName);
var suma = 0;
foreach (string line in lines)
{
var sNumbers = line.Split('\t');
var numbers = sNumbers.Select(s => Int32.Parse(s)).ToArray();
var div1 = 0;
var div2 = 0;
for (int i = 0; i < numbers.Length; i++)
{
for (int j = i + 1; j < numbers.Length; j++)
{
if (numbers[i] % numbers[j] == 0 || numbers[j] % numbers[i] == 0)
{
div1 = numbers[i];
div2 = numbers[j];
break;
}
}
}
if (div2 > div1)
{
var temp = div1;
div1 = div2;
div2 = temp;
}
suma += div1 / div2;
}
Console.WriteLine(suma);
Console.ReadLine();
}
}
}
<file_sep>/Day5_1/Program.cs
using System;
using System.Collections;
using System.IO;
namespace Day5_1
{
class Program
{
static void Main(string[] args)
{
string projectFolder = Directory.GetParent(Directory.GetCurrentDirectory()).Parent.FullName;
string fileName = Path.Combine(projectFolder, @"input.txt");
string[] lines = File.ReadAllLines(fileName);
int[] jumps = new int[lines.Length];
for (int i = 0; i < lines.Length; i++)
{
jumps[i] = Int32.Parse(lines[i]);
}
var index = 0;
var count = 0;
while (index < jumps.Length)
{
var temp = index;
index += jumps[index];
if (index > jumps.Length)
break;
jumps[temp]++;
count++;
}
Console.WriteLine(count);
Console.ReadLine();
}
}
}
<file_sep>/Day2_1/Program.cs
using System;
using System.Collections.Generic;
using System.Linq;
namespace AdventOfCode
{
class Day2_1
{
static void Main(string[] args)
{
var sum = 0;
do
{
var input = Console.ReadLine();
if (input.Equals("KRAJ"))
break;
var sNumbers = input.Split(' ');
var numbers = sNumbers.Select(s => Int32.Parse(s)).ToArray();
var min = numbers.Min();
var max = numbers.Max();
sum += max - min;
} while (true);
Console.WriteLine(sum);
Console.ReadLine();
}
}
}
<file_sep>/Day4_2/Program.cs
using System;
using System.Collections.Generic;
using System.IO;
namespace Day4_2
{
class Program
{
static void Main(string[] args)
{
string projectFolder = Directory.GetParent(Directory.GetCurrentDirectory()).Parent.FullName;
string fileName = Path.Combine(projectFolder, @"input.txt");
string[] lines = File.ReadAllLines(fileName);
var valid = 0;
foreach (string line in lines)
{
var words = line.Split(' ');
var notAnagrams = true;
for (int i = 0; i < words.Length - 1 && notAnagrams; i++)
{
for (int j = i + 1; j < words.Length && notAnagrams; j++)
{
if (isAnagram(words[i], words[j]))
notAnagrams = false;
}
}
if (notAnagrams)
valid++;
}
Console.WriteLine(valid);
Console.ReadLine();
}
private static bool isAnagram(string s, string s1)
{
if (s.Length != s1.Length)
return false;
var c1 = s.ToCharArray();
var c2 = s1.ToCharArray();
var index = 0;
do
{
var c = c1[index++];
var count1 = 0;
var count2 = 0;
for (int i = 0; i < c1.Length; i++)
{
if (c1[i] == c)
count1++;
}
for (int j = 0; j < c2.Length; j++)
{
if (c2[j] == c)
count2++;
}
if (count1 != count2)
return false;
} while (index < c1.Length);
return true;
}
}
}
<file_sep>/Day9_1/Program.cs
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Day9
{
class Program
{
static void Main(string[] args)
{
string projectFolder = Directory.GetParent(Directory.GetCurrentDirectory()).Parent.FullName;
string fileName = Path.Combine(projectFolder, @"input.txt");
var line = File.ReadAllText(fileName).ToCharArray();
int level = 1;
bool garbage = false;
bool ignor = false;
int result = 0;
int group = 0;
int garbageSize = 0;
foreach (var character in line)
{
if (ignor)
{
ignor = false;
}
else if (character == '<' && !garbage)
{
garbage = true;
}
else if (character == '>')
{
garbage = false;
}
else if (character == '!' && garbage)
{
ignor = true;
}
else if (character == '{' && !garbage)
{
result += level++;
group++;
}
else if (character == '}' && !garbage)
{
group--;
if (group > 0)
{
level--;
}
}
else if (garbage)
{
garbageSize++;
}
}
Console.WriteLine("Part one : " + result);
Console.WriteLine("Part two: " + garbageSize);
Console.ReadLine();
}
}
}
<file_sep>/Day6_1/Program.cs
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Day6
{
class Program
{
static void Main(string[] args)
{
string projectFolder = Directory.GetParent(Directory.GetCurrentDirectory()).Parent.FullName;
string fileName = Path.Combine(projectFolder, @"input.txt");
string[] lines = File.ReadAllLines(fileName);
var numbers = lines[0].Split('\t').Select(n => Int32.Parse(n)).ToArray();
HashSet<string> set = new HashSet<string>();
set.Add(PretvoriUString(numbers));
string duplic;
while (true)
{
var max = numbers[0];
var maxIndex = 0;
for (int i = 0; i < numbers.Length; i++)
{
if (numbers[i] > max)
{
max = numbers[i];
maxIndex = i;
}
}
var blocks = numbers[maxIndex];
numbers[maxIndex] = 0;
while (blocks > 0)
{
maxIndex = (maxIndex + 1) % numbers.Length;
numbers[maxIndex]++;
blocks--;
}
if (!set.Add(PretvoriUString(numbers)))
{
duplic = PretvoriUString(numbers);
break;
}
}
var count = 0;
int index = 0;
foreach (string s in set)
{
if (s.Equals(duplic))
{
index = count;
break;
}
count++;
}
Console.WriteLine($"1) {set.Count}");
Console.WriteLine($"2) {set.Count - index}");
Console.ReadLine();
}
private static string PretvoriUString(int[] numbers)
{
string result = "";
for (int i = 0; i < numbers.Length; i++)
result += numbers[i].ToString();
return result;
}
}
}
<file_sep>/Day4_1/Program.cs
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.Remoting.Messaging;
using System.Text;
using System.Threading.Tasks;
namespace Day4_1
{
class Program
{
static void Main(string[] args)
{
HashSet<string> set;
string projectFolder = Directory.GetParent(Directory.GetCurrentDirectory()).Parent.FullName;
string fileName = Path.Combine(projectFolder, @"input.txt");
string[] lines = File.ReadAllLines(fileName);
var valid = 0;
foreach (string line in lines )
{
set = new HashSet<string>();
var words = line.Split(' ');
foreach (string word in words)
{
set.Add(word);
}
if (set.Count == words.Length)
valid++;
}
Console.WriteLine(valid);
Console.ReadLine();
}
}
}
| c2494a73e1e3db7fd1fbf72e8ec659500e2e7975 | [
"C#"
] | 9 | C# | Svem1rko/AdventOfCode | 2610d751f097cb93b19190d490d3f52c80798967 | f26d654256e7ff710452d706372a8d9a45694bbc |
refs/heads/master | <file_sep>import React, { Component } from 'react'
import { Container, Header } from 'semantic-ui-react'
export default class Vis3Explanation extends Component {
constructor (props) {
super(props)
}
render () {
return (
<Container fluid>
<center>
<Header as= 'hVis1' className='analysis-title'>VISUALIZATION #3</Header>
<p className='paragraph'>
<br/>
This scatter plot compares the Total Revenue
(Amount of money the school earns prior to taxes and deductions) and
the average scores for the three different sections on the SAT.
This was created to help identify a correlation between a rise in
total score on the SAT, a nation-wide test, with the rise or fall in
total revenue.
</p>
<p className='paragraph'>
Some schools that did not provide the statistics to all three SAT scores
as well as their total revenue amounts were not included within the
data utilized to create the visualization. This condition was implemented in
order to remove any outliers within the database of school profiles.
<br/>
<br/>
</p>
</center>
</Container>
)
}
}
<file_sep>import React, { Component } from 'react'
import { Container, Header } from 'semantic-ui-react'
export default class Vis2Explanation extends Component {
constructor (props) {
super(props)
}
render () {
return (
<Container fluid>
<center>
<Header as= 'hVis1' className='analysis-title'>VISUALIZATION #2</Header>
<p className='paragraph'>
<br/>
This sunburst chart visualizes the PSSA exam performances for each school type.
From this visualization, we hope that one can learn more about how different
school types compare.
</p>
<p className='paragraph'>
The data featured in the graph is calculated by taking the weighted average of the
PSSA scores for a given LEA type. To further visualize the breakdown of the percentages,
feel free to mouseover or click any of the arcs. Once in a zoomed in view,
click the center of the visualization to go back up one level.
<br/>
<br/>
</p>
</center>
</Container>
)
}
}
<file_sep>import { geoMercator, geoPath } from 'd3-geo'
import { browserHistory } from 'react-router'
import React, { Component } from 'react'
export default class PAMap extends Component {
constructor() {
super()
this.state = {
worldData: [],
containerWidth: null,
containerHeight: null,
selectedFeature: null,
selected: null
}
}
projection() {
const center = this.props.county ? geoPath().centroid(this.state.selectedFeature) : [-77.82, 40.91]
const scale = 360*this.state.containerWidth/8
return geoMercator()
.scale([scale])
.translate([ this.state.containerWidth / 2, this.state.containerHeight / 2 ])
.center(center)
}
componentWillMount() {
// Get data for the map
fetch('../data/counties.json')
.then(response => {
if (response.status !== 200) {
return
}
response.json().then(counties => {
const selectedCounty = this.props.county || 'Centre'
const selectedFeature = counties.features.find((el) => {
return el.properties.NAME == selectedCounty
})
this.setState({
worldData: counties.features,
selectedFeature: selectedFeature
})
})
})
}
componentDidMount() {
this.fitParentContainer()
setTimeout(() => this.fitParentContainer(), 100)
window.addEventListener('resize', this.fitParentContainer)
}
componentWillUnmount() {
window.removeEventListener('resize', this.fitParentContainer)
}
fitParentContainer = () => {
const { containerWidth } = this.state
const currentContainerWidth = this.refs.svg.parentNode.clientWidth
const shouldResize = containerWidth !== Math.min(900, currentContainerWidth)
if (shouldResize) {
this.setState({
containerWidth: Math.min(900, currentContainerWidth),
containerHeight: Math.min(900, currentContainerWidth) * (600/960)
})
}
}
render () {
return (
<svg
ref='svg'
width={ this.state.containerWidth }
height={ this.state.containerHeight }
>
<g className='schools'>
{
this.state.worldData.map((d,i) => {
if (d !== this.state.selectedFeature)
return (<g key={ `path-container-${ i }` } />)
const path = geoPath().projection(this.projection())
return (
<g
key={ `path-container-${ i }` }
>
<path
key={ `path-${ i }` }
d={ path(d) }
className='county'
fill={ 'rgb(40,40,40)' }
stroke='#666'
strokeWidth={ 1 }
/>
</g>
)
})
}
{
this.props.schools.map((school) => {
const {school_name, state_school_id, latitude, longitude} = school
if (!latitude || !longitude) return
const cx = this.projection()([longitude, latitude])[0],
cy = this.projection()([longitude, latitude])[1]
if (!cx || !cy) return
return (
<g
key = {`circle-${state_school_id}`}
opacity={
(
this.props.currentSchools.indexOf(school) == -1 ||
(this.props.selected && this.props.selected != school)
) ? '0.1' : '1'}
className='school_marker'
onClick={() => browserHistory.push(`/school/${state_school_id}`)}
onMouseEnter={() => this.setState({selected: school})}
onMouseLeave={() => this.setState({selected: null})}
>
<circle
key = {`biggest-circle-${state_school_id}`}
cx = { cx }
cy = { cy }
fill='rgba(255, 204, 26, 0.04)'
r = '24px'
/>
<circle
key = {`medium-circle-${state_school_id}`}
cx = { cx }
cy = { cy }
fill='rgba(255, 204, 26, 0.09)'
r = '16px'
/>
<circle
key = {`smallest-circle-${state_school_id}`}
cx = { cx }
cy = { cy }
fill='yellow'
r = '4px'
/>
{(this.state.selected == school || this.props.selected == school)
&&
(<text
key={ `school-name-${state_school_id}` }
fill='#CCC'
x={ cx }
y={ cy - 20 }
textAnchor='middle'
fontSize='12'
className={'tooltip'}
>
{ school_name }
</text>)
}
</g>
)
}
)
}
</g>
</svg>
)
}
}
<file_sep>class School < ApplicationRecord
self.table_name = 'school'
self.primary_keys = :state_lea_id, :state_school_id
has_many :Exam, :foreign_key => [:state_lea_id, :state_school_id]
has_one :Fiscal, :foreign_key => [:state_lea_id, :state_school_id]
has_one :Fact, :foreign_key => [:state_lea_id, :state_school_id]
has_one :Performance, :foreign_key => [:state_lea_id, :state_school_id]
end
<file_sep>class ApiController < ApplicationController
def list_counties
@counties = School.select('county').group('county').all().pluck('county')
json_response(@counties)
end
def list_schools
@schools = School.joins(:Fact)
.where(school: {county: params[:county_id]})
.select('data_school_facts.school_add_city,
data_school_facts.school_enrollment,
data_school_facts.grades_offered,
data_school_facts.dropout_rate,
data_school_facts.sat_math,
data_school_facts.sat_reading,
data_school_facts.sat_writing,
data_school_facts.website,
data_school_facts.school_add_city,
school.school_name,
school.latitude,
school.longitude,
school.state_school_id
')
.uniq
# .distinct()
json_response(@schools)
end
def search_schools
@schools = School.where('school_name LIKE UPPER(?) AND county IS NOT NULL', "%#{params[:query]}%").uniq
json_response(@schools)
end
def school_details
@schools = School.joins(:Fact)
.where('school.state_school_id = ?', params[:school_id])
.select('data_school_facts.school_add_city,
data_school_facts.school_enrollment,
data_school_facts.grades_offered,
data_school_facts.male,
data_school_facts.female,
data_school_facts.dropout_rate,
data_school_facts.website,
data_school_facts.school_add_city,
data_school_facts.telephone_no,
data_school_facts.act_english,
data_school_facts.act_math,
data_school_facts.act_reading,
data_school_facts.act_science,
data_school_facts.sat_math,
data_school_facts.sat_reading,
data_school_facts.sat_writing,
data_school_facts.americanindian_alaskan,
data_school_facts.asian,
data_school_facts.black,
data_school_facts.hawaiian_pacific_islander,
data_school_facts.hispanic,
data_school_facts.multiracial,
data_school_facts.white,
school.school_name,
school.county,
school.latitude,
school.longitude,
school.state_school_id,
school.lea_type
')
.first
json_response(@schools)
end
def visualization_1
@pssa_information = School.joins(:Fiscal, :Performance)
.select('
pupil_expenditure_total,
school.state_school_id,
school_name,
math_algebra_percent_proficient,
reading_lit_percent_proficient_pssa,
scibio_percent_proficient_pssa
')
.where.not(data_school_fiscal: { pupil_expenditure_total: nil})
.where.not(data_school_performance_measure: { math_algebra_percent_proficient: nil })
.where.not(data_school_performance_measure: { reading_lit_percent_proficient_pssa: nil })
.where.not(data_school_performance_measure: { scibio_percent_proficient_pssa: nil })
.order('pupil_expenditure_total ASC')
.all()
json_response(@pssa_information)
end
def visualization_1_county
@pssa_information = School.joins(:Fiscal, :Performance)
.select('
pupil_expenditure_total,
school.state_lea_id,
school_name,
math_algebra_percent_proficient,
reading_lit_percent_proficient_pssa,
scibio_percent_proficient_pssa
')
.where.not(data_school_fiscal: { pupil_expenditure_total: nil})
.where.not(data_school_performance_measure: { math_algebra_percent_proficient: nil })
.where.not(data_school_performance_measure: { reading_lit_percent_proficient_pssa: nil })
.where.not(data_school_performance_measure: { scibio_percent_proficient_pssa: nil })
.where(school: {county: params[:county_id]})
.order('pupil_expenditure_total ASC')
.uniq()
json_response(@pssa_information)
end
def visualization_2
@pssa_performance_information = Exam.joins(:School)
.select('
subject,
lea_type,
AVG(pctadvanced) AS avgpctadvanced,
AVG(pctproficient) AS avgpctproficient,
AVG(pctbasic) AS avgpctbasic,
AVG(pctbelowbasic) AS avgpctbelowbasic
')
.where.not(data_exam: { pctadvanced: nil })
.where.not(data_exam: { pctproficient: nil })
.where.not(data_exam: { pctbasic: nil })
.where.not(data_exam: { pctbelowbasic: nil })
.where(data_exam: { student_group: "All Students" })
.where(data_exam: { source: ["pssa"] })
.where(data_exam: { grade: params[:grade] })
.where(data_exam: { academic_year_start: params[:academic_year_start] })
.group("lea_type")
.group("subject")
json_response(@pssa_performance_information)
end
def visualization_2_county
@pssa_performance_information = Exam.joins(:School)
.select('
subject,
lea_type,
AVG(pctadvanced) AS avgpctadvanced,
AVG(pctproficient) AS avgpctproficient,
AVG(pctbasic) AS avgpctbasic,
AVG(pctbelowbasic) AS avgpctbelowbasic
')
.where.not(data_exam: { pctadvanced: nil })
.where.not(data_exam: { pctproficient: nil })
.where.not(data_exam: { pctbasic: nil })
.where.not(data_exam: { pctbelowbasic: nil })
.where(data_exam: { student_group: "All Students" })
.where(data_exam: { source: ["pssa"] })
.where(data_exam: { grade: params[:grade] })
.where(data_exam: { academic_year_start: params[:academic_year_start] })
.where(school: {county: params[:county_id]})
.group("lea_type")
.group("subject")
json_response(@pssa_performance_information)
end
def visualization_3
@fiscal_information = School.joins(:Fiscal, :Fact)
.select('
school_name,
(sat_math + sat_reading + sat_writing) AS sattotal,
(local_revenue + state_revenue + other_revenue + fed_revenue) AS totalrevenue
')
.where.not(data_school_facts: { sat_math: nil })
.where.not(data_school_facts: { sat_reading: nil })
.where.not(data_school_facts: { sat_writing: nil })
.order('totalrevenue ASC')
.all()
json_response(@fiscal_information)
end
def visualization_3_county
@fiscal_information = School.joins(:Fiscal, :Fact)
.select('
school_name,
(sat_math + sat_reading + sat_writing) AS sattotal,
(local_revenue + state_revenue + other_revenue + fed_revenue) AS totalrevenue
')
.where.not(data_school_facts: { sat_math: nil })
.where.not(data_school_facts: { sat_reading: nil })
.where.not(data_school_facts: { sat_writing: nil })
.where(school: {county: params[:county_id]})
.order('totalrevenue ASC')
.all()
json_response(@fiscal_information)
end
end
<file_sep>import React, { Component } from 'react'
import { browserHistory } from 'react-router'
import { Segment, Container, Label, mb, Header, Icon, Statistic, Grid, Breadcrumb } from 'semantic-ui-react'
import { PieChart, BarChart } from 'react-d3-basic'
import _ from 'lodash'
const label_colors = [
'red', 'orange', 'yellow', 'olive', 'green', 'teal',
'blue', 'violet', 'purple', 'pink', 'brown', 'grey', 'black'
]
const school_types = {
CTC: 'Technical Center',
AVTS: 'Technical School',
SPJ: 'Correctional Institution',
STATE: 'State',
REGSCH: 'Regular School',
SD: 'School District',
CS: 'Charter School',
Future: 'Future',
PS: 'Public School',
SJCI: 'Correctional Institution'
}
class County extends Component {
constructor (props) {
super(props)
this.state = {
details: []
}
}
componentWillMount() {
fetch(`http://localhost:3001/api/v1/school/${this.props.params.school}/`)
.then(response => {
if (response.status !== 200) {
return
}
response.json().then(details => {
this.setState({
details: details
}, () => {
this.forceUpdate()
console.log(details)
})
})
})
}
renderStatistic(val, name, icon) {
return val && (
<Statistic>
<Statistic.Label>
{name}
</Statistic.Label>
<Statistic.Value>
{icon && <Icon name={icon} />}
{' ' + val}
</Statistic.Value>
</Statistic>
)
}
formatPhoneNumber(s) {
var s2 = (''+s).replace(/\D/g, '');
var m = s2.match(/^(\d{3})(\d{3})(\d{4})$/);
return (!m) ? null : '(' + m[1] + ') ' + m[2] + '-' + m[3];
}
render () {
const actScores = [
{section: 'English', score: Number(this.state.details.act_english) || 0 },
{section: 'Math', score: Number(this.state.details.act_math) || 0 },
{section: 'Reading', score: Number(this.state.details.act_reading) || 0 },
{section: 'Science', score: Number(this.state.details.act_science) || 0 }
]
const satScores = [
{section: 'Math', score: Number(this.state.details.sat_math) || 0 },
{section: 'Reading', score: Number(this.state.details.sat_reading) || 0 },
{section: 'Writing', score: Number(this.state.details.sat_writing) || 0 }
]
return (
<Container fluid className='school-section'>
<Container>
<Segment>
<Breadcrumb size='large'>
<Breadcrumb.Section link onClick={() => browserHistory.push('/')}>Home</Breadcrumb.Section>
<Breadcrumb.Divider icon='right chevron' />
<Breadcrumb.Section link onClick={() => browserHistory.push(`/county/${this.state.details.county}`)}>
{this.state.details.county} County
</Breadcrumb.Section>
<Breadcrumb.Divider icon='right chevron' />
<Breadcrumb.Section active>{_.startCase(_.toLower(this.state.details.school_name))}</Breadcrumb.Section>
</Breadcrumb>
</Segment>
</Container>
<Container>
<Header as='h2' className='headerText' >{_.lowerCase(this.state.details.school_name)}</Header>
<Header as='h3' className='subHeaderText' >{this.state.details.county} County, PA</Header>
<Statistic.Group>
{this.renderStatistic(this.state.details.dropout_rate, 'Dropout Rate', 'percent')}
{this.renderStatistic(this.state.details.school_enrollment, 'Enrollment', 'student')}
{this.renderStatistic(this.state.details.school_add_city, 'City', 'marker')}
{this.renderStatistic(this.formatPhoneNumber(this.state.details.telephone_no), 'Phone', 'phone')}
{this.renderStatistic(school_types[this.state.details.lea_type], 'Type', 'building')}
{this.renderStatistic(this.state.details.sat_math, 'SAT Math', 'calculator')}
{this.renderStatistic(this.state.details.sat_reading, 'SAT Reading', 'book')}
{this.renderStatistic(this.state.details.sat_writing, 'SAT Writing', 'write')}
</Statistic.Group>
</Container>
<iframe
width='100%'
height='300'
className='schoolMap'
src={`https://www.google.com/maps/embed/v1/place?key=<KEY>&q=${this.state.details.school_name} , PA`}
>
</iframe>
<Container>
<Header as='h2' className='headerText'>Overview</Header>
<Header as='h3' className='subHeaderText top'>Grades offered</Header>
{
this.state.details.grades_offered && this.state.details.grades_offered.map((grade) => (
<Label circular color={label_colors[Number(grade)]} key={grade}>{grade}</Label>
))
}
<Header as='h3' className='subHeaderText top'>Statistics</Header>
<Container
className='school-pies'
style={{display: 'flex', flexDirection: 'row', alignItems: 'center', justifyContent: 'center'}}
fluid>
<div style={{margin: '30px'}}>
<PieChart
data= {[{percent: Number(this.state.details.female), name: 'female'}, {percent: Number(this.state.details.male), name: 'male'}]}
width= {320}
height= {300}
chartSeries= {[{field: 'female', name: 'Females', color: '#e74c3c'}, {field: 'male', name: 'Males', color: '#2980b9'}]}
value = {(d) => d.percent}
name = {(d) => d.name}
showLegend
innerRadius = {40}
/>
</div>
<div style={{margin: '30px'}}>
<PieChart
svgClassName='pie-svg'
legendClassName='pie-title'
style={{flex: .5}}
data= {[
{percent: Number(this.state.details.americanindian_alaskan), name: 'americanindian_alaskan'},
{percent: Number(this.state.details.asian), name: 'asian'},
{percent: Number(this.state.details.black), name: 'black'},
{percent: Number(this.state.details.hawaiian_pacific_islander), name: 'hawaiian_pacific_islander'},
{percent: Number(this.state.details.hispanic), name: 'hispanic'},
{percent: Number(this.state.details.multiracial), name: 'multiracial'},
{percent: Number(this.state.details.white), name: 'white'}
]}
width= {500}
height= {300}
chartSeries= {[
{field: 'americanindian_alaskan', name: 'American Indian/Alaskan', color: '#16a085'},
{field: 'asian', name: 'Asian', color: '#27ae60'},
{field: 'black', name: 'Black', color: '#2980b9'},
{field: 'hawaiian_pacific_islander', name: 'Hawaiian Pacific Islander', color: '#8e44ad'},
{field: 'hispanic', name: 'Hispanic', color: '#c0392b'},
{field: 'multiracial', name: 'Multiracial', color: '#d35400'},
{field: 'white', name: 'White', color: '#f39c12'}
]}
value = {(d) => d.percent}
name = {(d) => d.name}
showLegend
innerRadius = {40}
/>
</div>
</Container>
<Container
className='school-bars'
style={{display: 'flex', flexDirection: 'row', alignItems: 'center', justifyContent: 'center'}}
fluid>
<BarChart
style={{flex: .5}}
title={'ACT Scores'}
data={actScores}
width={600}
height={300}
chartSeries={[{field: 'score',name: 'ACT Scores'}]}
x={d => d.section}
xLabel={'ACT Section'}
xScale={'ordinal'}
yLabel={'Score'}
/>
<BarChart
style={{flex: .5}}
title={'SAT Scores'}
data={satScores}
width={600}
height={300}
chartSeries={[{field: 'score',name: 'SAT Scores'}]}
x={d => d.section}
xLabel={'SAT Section'}
xScale={'ordinal'}
yLabel={'Score'}
/>
</Container>
</Container>
</Container>
)
}
}
export default County
<file_sep>import React from 'react'
import { Router, Route, IndexRoute } from 'react-router'
import App from './pages/App.jsx'
import Landing from './pages/Landing.jsx'
import County from './pages/County.jsx'
import School from './pages/School.jsx'
export default (
<Router>
<Route path='/' component={App}>
<IndexRoute component={Landing} />
<Route path='county/:county' component={County} />
<Route path='school/:school' component={School} />
<Route path='*' component={Landing} />
</Route>
</Router>
)
<file_sep>import React, { Component } from 'react'
import {hierarchy, partition} from 'd3-hierarchy'
import {arc} from 'd3-shape'
import {color} from 'd3-color'
import { Container } from 'semantic-ui-react'
class Visualization2 extends Component {
constructor (props) {
super(props)
this.root = null
this.state = {
hovered: null,
selected: null
}
this.getData = this.getData.bind(this)
}
componentWillMount () {
this.getData()
}
componentWillReceiveProps(nextProps) {
if (JSON.stringify(this.props.url) !== JSON.stringify(nextProps.url)) {
this.getData()
}
}
getData () {
fetch(this.props.url)
.then(response => {
if (response.status !== 200) {
return
}
response.json().then(data => {
if(data.length == 0){
} else {
this.root = hierarchy(this.formatDataFromApi(data))
.sum(function (d) { return d.size })
this.setState({
percentage: null,
testTopic: null,
profLevel: null,
schoolType: null,
hovered: null,
selected: this.root,
selectedReal: this.root,
dataRoot: this.root
})
}
})
})
}
render () {
if(!this.state.selected){
return (<div className='visContainer'></div>);
}
let radius = Math.min(this.props.width, this.props.height) / 2;
const colors = {
'FUTURE': '#38c742',
'CS': '#303ce3',
'SD': '#114183',
'A': '#259ee7',
'P': '#7ab6db',
'B': '#d8d8d8',
'BB': '#db7712',
'Math': '#c35b48',
'English': '#e5c027',
'Science': '#125592'
}
// Data strucure
this.state.selected.sum(function (d) { return d.size });
let partitionGraph = partition().size([2 * Math.PI, radius]);
partitionGraph(this.state.selected)
let arcGenerator = arc()
.startAngle(function (d) { return d.x0 })
.endAngle(function (d) { return d.x1 })
.innerRadius(function (d) { return d.y0 })
.outerRadius(function (d) { return d.y1 });
let sequenceArray = this.state.hovered != null ? this.getAncestors(this.state.hovered) : [];
return (
<div className='visContainer'>
<svg
className='vis2svg'
width={ this.props.width }
height={ this.props.height }
viewBox={`0 0 ${this.props.width} ${this.props.height}`}
>
<g className='vis2'
transform={'translate(' + this.props.width/2 + ',' + this.props.height/2 + ')'}>
{
this.state.selected.descendants().map((d,i) => (
<path
key = { `path-${ i }` }
display = {function (d) { return d.depth ? null : 'none'; }}
d = {arcGenerator(d)}
onMouseOver = {() => {this.mouseover(d)}}
onClick ={() => {this.onClick(d)}}
fill = {color(colors[d.data.name])}
opacity = {
sequenceArray.indexOf(d) >= 0 ? 1.0 : 0.6
}
/>
))
}
</g>
<text textAnchor='middle' x={this.props.width/2} y={this.props.height/2 - 30}>
{this.state.testTopic}
</text>
<text textAnchor='middle' x={this.props.width/2} y={this.props.height/2 -10}>
{this.state.profLevel}
</text>
<text textAnchor='middle' x={this.props.width/2} y={this.props.height/2 + 10}>
{this.state.schoolType}
</text>
<text textAnchor='middle' x={this.props.width/2} y={this.props.height/2 + 30}>
{isNaN(this.state.percentage) ? 0 : Math.round(this.state.percentage * 100)}%
</text>
</svg>
</div>
)
}
getAncestors = (node) => {
let path = [];
let current = node;
while (current.parent) {
path.unshift(current);
current = current.parent;
}
return path;
}
isTopicNode = (d) => {
return d.height == 2;
}
isProficiencyNode = (d) => {
return d.height == 1;
}
isSchoolNode = (d) => {
return d.height == 0;
}
onClick = (d) =>{
let newRoot = null;
if(d === this.state.selected){
// if the node is the same as the selected node, then we go up a layer
if(d.data.name === this.state.dataRoot.data.name){
// if we are at the dataRoot, don't do anything
return;
} else {
//otherwise we have parents
newRoot = this.state.selectedReal.parent
}
} else {
// otherwise the new root becomes the dataNode at d
newRoot = this.findDataNode(d);
}
this.setState({
// the selected node becomes the root of a copied subtree
selected: newRoot.copy(),
// the real selected node is stored
selectedReal: newRoot
})
this.render()
}
// finds the node in the complete data tree
// d can come from the copied tree
findDataNode = (d) => {
// since we know the topic node for sure, the children's names are not
// ambiguous.
let topicNode = this.recursiveFind(this.state.dataRoot, this.state.testTopic)
return this.recursiveFind(topicNode, d.data.name)
}
// pass in the name of the node u want to find
// and the node you want to recursively search
recursiveFind = (d, name) => {
// base case, current node is the node to find
if(d.data.name === name){
return d;
}
let desc = d.descendants();
// remove d from the descendants
desc.shift();
// base case, current node has no children and is not the node to find
if(desc.length == 0){
return null;
}
// recurse for each child
for(var child of desc){
// look for a node with name equal to name in the child
var result = this.recursiveFind(child, name)
// if we found match, stop running and return it
if(result != null){
return result;
}
}
// the node was not found in the tree
return null;
}
mouseover = (d) => {
if(this.state.selectedReal.height >= 2){
if(this.isTopicNode(d)){
this.setState({
testTopic: d.data.name,
percentage: 1,
profLevel: '',
schoolType: ''
})
} else if(this.isProficiencyNode(d)) {
this.setState({
testTopic: d.parent.data.name,
percentage: d.value/d.parent.value,
profLevel: d.data.name,
schoolType: ''
})
} else if(this.isSchoolNode(d)) {
this.setState({
testTopic: d.parent.parent.data.name,
percentage: d.value/d.parent.parent.value,
profLevel: d.parent.data.name,
schoolType: d.data.name
})
}
} else {
if(this.isProficiencyNode(d)) {
this.setState({
percentage: d.value/this.state.selectedReal.value,
profLevel: d.data.name,
schoolType: ''
})
} else if(this.isSchoolNode(d)) {
this.setState({
percentage: d.value/this.state.selectedReal.value,
profLevel: d.parent.data.name,
schoolType: d.data.name
})
}
}
this.setState({
hovered: d
})
this.render()
}
formatDataFromApi = (data) =>{
var profLevels = ['A', 'P', 'B', 'BB']
var result = {}
for(var tuple of data){
var subject = tuple.subject
if(subject == 'English Language Arts'){
subject = 'English'
}
var leaType = tuple.lea_type
if(!result.hasOwnProperty(subject)){
result[subject] = {
'A': {},
'P': {},
'B': {},
'BB': {}
};
}
for(var profLevel of profLevels){
if(!profLevel.hasOwnProperty(leaType)){
result[subject][profLevel][leaType] = {};
}
}
result[subject]['A'][leaType] = tuple.avgpctadvanced
result[subject]['P'][leaType] = tuple.avgpctproficient
result[subject]['B'][leaType] = tuple.avgpctbasic
result[subject]['BB'][leaType] = tuple.avgpctbelowbasic
}
return this.visFormatData(result);
}
visFormatData = (data) => {
var result = {
'name': 'TOPICS',
'children': []
}
for(var subject in data){
if(data.hasOwnProperty(subject)){
var subjectEntry = {
'name': subject,
'children': []
}
for(var profLevel in data[subject]){
if(data[subject].hasOwnProperty(profLevel)){
var profLevelEntry = {
'name': profLevel,
'children': []
}
for(var leaType in data[subject][profLevel]){
if(data[subject][profLevel].hasOwnProperty(leaType)){
var leaTypeEntry = {
'name': leaType,
'size': data[subject][profLevel][leaType]
}
profLevelEntry.children.push(leaTypeEntry)
}
}
subjectEntry.children.push(profLevelEntry)
}
}
result.children.push(subjectEntry)
}
}
return result;
}
}
export default Visualization2
<file_sep># **LafTech**
### Structure
The project is built in [*React*](https://reactjs.org/tutorial/tutorial.html) and [*Ruby on Rails*](http://guides.rubyonrails.org/getting_started.html). There are two main parts of the project - server-side rails application and client-side react application. [Backend is written on Rails while React is used to build front-end](https://www.fullstackreact.com/articles/how-to-get-create-react-app-to-work-with-your-rails-api/)
In addition to React we are using [ES6](http://ccoenraets.github.io/es6-tutorial/), [Sass](http://sass-lang.com/) and [Semantic UI](https://react.semantic-ui.com/), with [Webpack](https://webpack.js.org/) bundler. The structure of the whole project is following:
##### Main directories:
- `src` directory contains all the source files
- `dist` directory keeps production versions
- `test` directory is supposed to store all the unit and integration tests
- `cfg` provides *webpack* configuration for *test, production* and *development* builds
#### React
- `src/actions` contains all the [Redux](https://redux.js.org/) actions
- `src/api` contains the server-side codebase written on Rails
- `src/components` keeps all the [React Components](https://reactjs.org/docs/react-component.html)
- `src/data` contains all the data files used in application (JSON, txt, etc.)
- `src/images` contains all the media files used in the project
- `src/pages` contains main all the pages user can navigate to using LafTech
- `src/styles`directory provides stylesheets written in Sass
#### Rails
To be developed....
### Setup
In order to set up the project on the local machine, at first clone the repo:
- `git clone <EMAIL>:prosperi/LafTech.git`
#### Running the frontend (React)
Navigate to the project directory:
- `cd LafTech`
Install all the packages:
- `npm install`
Start webpack dev-server:
- `npm start`
After this react will be serving on port 3000, hence navigate to localhost:3000 in your browser and view the client-side.
#### Database Setup
Create an SSH tunnel to the Lafayette server using
>> `ssh -fN -L 5432:localhost:5432 yourLafUsername@192.168.3.11`
You may want to save this as an alias in `~/bash_profile` as `alias cs320db='ssh -fN -L 5432:localhost:5432 yourLafUsername@192.168.3.11'`
Once the ssh tunnel is enabled, configure `/config/database.yml` to use the port `5432`, your lafayette username and your LID as a password (copy from previous project). You can now proceed to the next steps.
#### Rails setup
Follow [this tutorial](https://gorails.com/setup/osx/10.13-high-sierra) to set up Ruby and Rails
#### Running the backend (Rails)
To start the rails server, navigate to api directory:
- `cd src/api`
Start rails on port 3001:
- `bin/rails s -p 3001`
<file_sep>Rails.application.routes.draw do
scope '/api' do
scope '/v1' do
scope '/visualizations' do
scope '/1' do
get '/' => 'api#visualization_1'
scope '/:county_id' do
get '/' => 'api#visualization_1_county'
end
end
scope '/2/(:grade)/(:academic_year_start)',
:defaults => {:grade => 'School Total', :academic_year_start => '2014'} do
get '/' => 'api#visualization_2'
scope '/:county_id' do
get '/' => 'api#visualization_2_county'
end
end
scope '/3' do
get '/' => 'api#visualization_3'
scope '/:county_id' do
get '/' => 'api#visualization_3_county'
end
end
end
scope '/map' do
get '/' => 'api#map'
scope '/:county_id' do
get '/' => 'api#map_county'
end
end
scope '/county' do
scope '/list' do
get '/' => 'api#list_counties'
end
scope '/:county_id/schools' do
get '/' => 'api#list_schools'
end
scope '/details' do
scope '/:county_id' do
get '/' => 'api#details_county'
end
end
end
scope '/school' do
scope '/:school_id' do
get '/' => 'api#school_details'
end
scope '/search/:query' do
get '/' => 'api#search_schools'
end
end
end
end
get '/' => 'api#index'
end
<file_sep>const data = [
{
'schoolName': 'Huntington',
'totalRevenue': 100000,
'sat_math': 570.25,
'sat_reading': 640.00,
'sat_writing': 584.10,
},
{
'schoolName': 'Mason',
'totalRevenue': 200000,
'sat_math': 590.20,
'sat_reading': 660.52,
'sat_writing': 543.30,
},
{
'schoolName': 'Carter',
'totalRevenue': 300000,
'sat_math': 600.25,
'sat_reading': 610.00,
'sat_writing': 575.10,
},
{
'schoolName': 'Creekwood',
'totalRevenue': 200000,
'sat_math': 690.20,
'sat_reading': 735.52,
'sat_writing': 750.30,
},
{
'schoolName': 'Ford',
'totalRevenue': 150000,
'sat_math': 367.25,
'sat_reading': 425.00,
'sat_writing': 390.10,
},
{
'schoolName': 'Johnson',
'totalRevenue': 138000,
'sat_math': 596.25,
'sat_reading': 725.00,
'sat_writing': 590.10,
}
]
export default data
<file_sep>import React, { Component } from 'react'
import { Grid, Container, Breadcrumb, Header, Menu, Label, Icon, Table, Dropdown, Button } from 'semantic-ui-react'
import { browserHistory } from 'react-router'
import capitalize from 'capitalize'
import CountyMap from './CountyMap'
import _ from 'lodash'
import VisualizationOne from '../components/VisualizationOne'
import VisualizationTwo from '../components/VisualizationTwo'
import VisualizationThree from '../components/VisualizationThree'
const label_colors = [
'red', 'orange', 'yellow', 'olive', 'green', 'teal',
'blue', 'violet', 'purple', 'pink', 'brown', 'grey', 'black'
]
class County extends Component {
constructor (props) {
super(props)
this.state = {
schools: [],
selected: null,
page: 1,
visWidth: null,
visHeight: null,
url: `http://localhost:3001/api/v1/visualizations/2/School Total/2014/${props.params.county}`,
grade: 12,
year: 2014
}
this._perPage = 5
this._numPages = 0
}
componentDidMount() {
this.fitParentContainer()
window.addEventListener('resize', this.fitParentContainer)
}
fitParentContainer = () => {
const currentContainerWidth = window.innerWidth
this.setState({
visWidth: Math.min(900, currentContainerWidth),
visHeight: Math.min(900, currentContainerWidth) * (600/960)
})
}
componentWillUnmount() {
window.removeEventListener('resize', this.fitParentContainer)
}
componentWillMount() {
fetch(`http://localhost:3001/api/v1/county/${this.props.params.county}/schools`)
.then(response => {
if (response.status !== 200) {
return
}
response.json().then(schools => {
this.setState({
schools: schools
}, () => {
this._numPages = Math.round(this.state.schools.length / this._perPage)
this.forceUpdate()
})
})
})
}
_page = (page) => {
this.setState({
page
})
}
_prevPage = () => {
if (this.state.page < 1)
return
this.setState({
page: --this.state.page
})
}
_nextPage = () => {
if (this.state.page >= this._numPages)
return
this.setState({
page: ++this.state.page
})
}
render () {
const currentSchools = this.state.schools.slice((this.state.page - 1) * this._perPage, this.state.page * this._perPage)
const gradeOptions = [
{ key: '3', value: '3', text: '3' }, { key: '4', value: '4', text: '4' }, { key: '5', value: '5', text: '5' },
{ key: '6', value: '6', text: '6' }, { key: '7', value: '7', text: '7' }, { key: '8', value: '8', text: '8' },
{ key: '9', value: '9', text: '9' }, { key: '10', value: '10', text: '10' }, { key: '11', value: '11', text: '11' },
{ key: '12', value: '12', text: '12' }
]
const yearOptions = [
{ key: '2012', value: '2012', text: '2012' },
{ key: '2013', value: '2013', text: '2013' },
{ key: '2014', value: '2014', text: '2014' }
]
return (
<Container fluid>
<Container className='district-section' fluid>
<Grid stackable>
<Grid.Row columns={2}>
<Grid.Column width={6} verticalAlign={'middle'} className='padded-column'>
<Header as='h2' className='hint' >{this.props.params.county} County</Header>
<CountyMap
county={this.props.params.county}
currentSchools={currentSchools}
schools={this.state.schools}
selected={this.state.selected}
/>
</Grid.Column>
<Grid.Column width={10} className='padded-column'>
<Table unstackable celled padded>
<Table.Header>
<Table.Row>
<Table.HeaderCell>School</Table.HeaderCell>
<Table.HeaderCell className={'mobile-hide'}>Grades</Table.HeaderCell>
<Table.HeaderCell>City</Table.HeaderCell>
<Table.HeaderCell className={'mobile-hide'}>Website</Table.HeaderCell>
</Table.Row>
</Table.Header>
<Table.Body>
{currentSchools.map((school) => {
const {school_name, state_school_id, grades_offered, website, school_add_city} = school
return (
<Table.Row
key={`row-${state_school_id}`}
onMouseEnter={() => this.setState({selected: school})}
onMouseLeave={() => this.setState({selected: null})}
onClick={() => browserHistory.push(`/school/${state_school_id}`)}
className={'school_row'}
>
<Table.Cell>{capitalize.words(school_name.toLowerCase())}</Table.Cell>
<Table.Cell singleLine className={'mobile-hide'}>
{
grades_offered.slice(0, 5).map((grade) => (
<Label circular color={label_colors[Number(grade)]} key={grade}>{grade}</Label>
))
}
{
grades_offered.length > 5 ? ' + ' + (grades_offered.length - 5) + ' more' : ''
}
</Table.Cell>
<Table.Cell>
{ school_add_city }
</Table.Cell>
<Table.Cell className={'mobile-hide'}>
<a href={ website }>{ website }</a>
</Table.Cell>
</Table.Row>
)
})}
</Table.Body>
<Table.Footer>
<Table.Row>
<Table.HeaderCell colSpan='5'>
<Menu floated='right' pagination>
{
this.state.page !== 1 && (
<Menu.Item
onClick={this._prevPage}
as='a'
icon
>
<Icon name='left chevron' />
</Menu.Item>
)
}
{
_.range(1, this._numPages + 1).map((page) => {
if (this._numPages >= 5 && (Math.abs(this.state.page - page) < 4 || page == this._numPages || page == 1)) {
return (
<Menu.Item
className={this.state.page == page ? 'active' : ''}
as='a'
onClick={() => this._page(page)}
>
{page}
</Menu.Item>
)
}
})
}
{
this.state.page !== this._numPages && (
<Menu.Item
onClick={this._nextPage}
as='a'
icon
>
<Icon name='right chevron' />
</Menu.Item>
)
}
</Menu>
</Table.HeaderCell>
</Table.Row>
</Table.Footer>
</Table>
</Grid.Column>
</Grid.Row>
</Grid>
</Container>
<Container className='county-section' fluid>
<Container>
<Header as='h2' className='countyName' >{this.props.params.county} County</Header>
<Header as='h3' className='stateName' >Pennsylvania</Header>
</Container>
<iframe
width='100%'
height='300'
className='countyMap'
src={`https://www.google.com/maps/embed/v1/place?key=<KEY>&q=${this.props.params.county} County,PA`}
>
</iframe>
</Container>
<Container className='analysis-section' fluid>
<VisualizationOne width={this.state.visWidth} height={this.state.visHeight} url={`http://localhost:3001/api/v1/visualizations/1/${this.props.params.county}`} />
</Container>
<Container className='analysis-section' fluid>
<div style={{display: 'flex', flexDirection: 'row'}}>
<Dropdown placeholder='Grade' selection options={gradeOptions} style={{margin: '20px'}} onChange={(e, v) => this.setState({grade: v.value})}/>
<Dropdown placeholder='Academic Year' selection options={yearOptions} style={{margin: '20px'}} onChange={(e, v) => this.setState({year: v.value})}/>
</div>
<Button style={{marginBottom: '20px'}} size='large' primary
onClick={(e) => { this.setState({url: `http://localhost:3001/api/v1/visualizations/2/${Number(this.state.grade)}/${Number(this.state.year)}/${this.props.params.county}`})}}>
Filter
</Button>
<VisualizationTwo width={Number(this.state.visWidth)} height={Number(this.state.visWidth) * 2/5} url={this.state.url} />
</Container>
<Container className='analysis-section' fluid>
<VisualizationThree width={this.state.visWidth} height={this.state.visHeight} url={`http://localhost:3001/api/v1/visualizations/3/${this.props.params.county}`} />
</Container>
</Container>
)
}
}
export default County
<file_sep>import React, { Component } from 'react'
import { ScatterPlot } from 'react-d3-basic'
import { Container, Divider } from 'semantic-ui-react'
export default class Visualization3 extends Component {
constructor (props) {
super(props)
this.state = {
data: null
}
}
componentDidMount() {
fetch(this.props.url).then((res) => {
return res.json()
}).then((data) => {
console.log(data)
this.setState({ data: data })
})
}
render () {
if(!this.state.data){
return(<div></div>)
}
let title = 'Visualization 3'
let width = this.props.width
let height = this.props.height
let margins = {
left: 100,
right: 50,
top: 10,
bottom: 50
}
let chartSeries = [
{
field: 'sattotal',
name: 'Sat Total Score',
color: '#3CC47C',
symbolSize: 5
}
]
const x = d => {
return Number(d.totalrevenue)
},
xLabel = 'Total Revenue ($)',
yLabel = 'Total SAT Score (AVG)',
xScale = 'linear',
yDomain =
[d3.min(this.state.data, function(a) { return Number(a.sattotal);}),
d3.max(this.state.data, function(b) { return Number(b.sattotal);}) ],
xDomain = [0,//d3.min(this.state.data, function(a) { return Number(a.totalrevenue); }),
d3.max(this.state.data, function(b) { return Number(b.totalrevenue); })],
xTicks = [10, '$']
return (
this.state.data.length > 0
? (
<ScatterPlot
showXGrid= {true}
showYGrid= {true}
xLabel= {xLabel}
yLabel= {yLabel}
margins= {margins}
title={title}
width={width}
height={height}
chartSeries={chartSeries}
data={this.state.data}
x={x}
xTicks={xTicks}
xScale = {xScale}
xDomain= {xDomain}
yDomain = {yDomain}
/>
)
: (
<Container className='analysis-section'>
<p className='analysis-title' style={{textAlign: 'center'}}>
NOT ENOUGH DATA TO COMPARE THE TOTAL REVENUE AND THE AVERAGE SCORES FOR THE THREE DIFFERENT SECTIONS ON THE SAT
</p>
<hr style={{width: '70%', borderColor: '#707070'}} />
</Container>
)
)
}
}
<file_sep>const data = [
{
'schoolName': 'Huntington',
'pupil_expenditure_total': 100000,
'math_algebra_percent_proficient': 570.25,
'reading_lit_percent_proficient_pssa': 440.00,
'writing_percent_proficient_pssa': 584.10,
'scibio_percent_proficient_pssa': 490.50,
'index': 0
},
{
'schoolName': 'Mason',
'pupil_expenditure_total': 185000,
'math_algebra_percent_proficient': 590.20,
'reading_lit_percent_proficient_pssa': 660.52,
'writing_percent_proficient_pssa': 443.30,
'scibio_percent_proficient_pssa': 610.25,
'index': 1
},
{
'schoolName': 'Carter',
'pupil_expenditure_total': 263100,
'math_algebra_percent_proficient': 600.25,
'reading_lit_percent_proficient_pssa': 610.00,
'writing_percent_proficient_pssa': 575.10,
'scibio_percent_proficient_pssa': 650.00,
'index': 2
},
{
'schoolName': 'Monahan',
'pupil_expenditure_total': 350000,
'math_algebra_percent_proficient': 200.25,
'reading_lit_percent_proficient_pssa': 310.00,
'writing_percent_proficient_pssa': 475.10,
'scibio_percent_proficient_pssa': 350.00,
'index': 3
},
{
'schoolName': 'Creekwood',
'pupil_expenditure_total': 400000,
'math_algebra_percent_proficient': 690.20,
'reading_lit_percent_proficient_pssa': 735.52,
'writing_percent_proficient_pssa': 750.30,
'scibio_percent_proficient_pssa': 710.00,
'index': 4
}
]
export default data
<file_sep>import React, { Component } from 'react'
import { Container, Header } from 'semantic-ui-react'
export default class Vis1Explanation extends Component {
constructor (props) {
super(props)
}
render () {
return (
<Container fluid>
<center>
<Header as='hVis1' className='analysis-title'>VISUALIZATION #1</Header>
<p className='paragraph'>
<br/>
This grouped bar graph compares the Pupil Expenditure
(Amount spent by the school on each student in the school) and
the average percentage of proficiency for the four different sections on the PSSA.
This was created to help identify a correlation between a rise in average
score with a rise or fall in pupil expenditure.
</p>
<p className='paragraph'>
Some schools that did not provide the statistics to all four PSSA scores
as well as their pupil expenditure amounts were not included within the
data utilized to create the visualization. This condition was implemented in
order to remove any outliers within the database of school profiles.
</p>
<p className='paragraph'>
The size of the data within the LafTech database is too large to be
expressed within a single graph for this visualization. Thus the
data shown here on the main page is utilizing dummy data in order to
express the idea behind the creation of this visualization. To see
this visualization using real data, select a county.
<br/>
</p>
</center>
</Container>
)
}
}
<file_sep>import React, { Component } from 'react'
import { Container } from 'semantic-ui-react'
import HeaderSection from './HeaderSection'
import FooterSection from './FooterSection'
class App extends Component {
constructor (props) {
super(props)
}
componentDidMount () {
}
render () {
return (
<Container fluid >
<HeaderSection />
{this.props.children}
<FooterSection />
</Container>
)
}
}
export default App
<file_sep>class Fiscal < ApplicationRecord
self.table_name = 'data_school_fiscal'
belongs_to :School, :foreign_key => [:state_lea_id, :state_school_id]
end
<file_sep>class Exam < ApplicationRecord
self.table_name = 'data_exam'
belongs_to :School, :foreign_key => [:state_lea_id, :state_school_id]
def school_year
"#{academic_year_start} - #{academic_year_end}"
end
end
| a5c4fea59151773d4a721c7c60a3b4c30bb0eda8 | [
"JavaScript",
"Ruby",
"Markdown"
] | 18 | JavaScript | wassgha/LafTech | 9a529f20fb45ef399d1ea0c50d38afef2c99142c | afd68ae9a182818cae480cec419c903c6fb7a763 |
refs/heads/master | <file_sep>__version__ = "0.5.3"
major_minor_version = "0.5"
<file_sep>################################################################################
#
# Copyright (c) 2019, the Perspective Authors.
#
# This file is part of the Perspective library, distributed under the terms of
# the Apache License 2.0. The full license can be found in the LICENSE file.
#
import json
import random
import pytest
import tornado
from tornado import gen
from tornado.websocket import websocket_connect
from datetime import datetime
from ...table import Table
from ...manager import PerspectiveManager
from ...manager.manager_internal import DateTimeEncoder
from ...tornado_handler import PerspectiveTornadoHandler
data = {
"a": [i for i in range(10)],
"b": [i * 1.5 for i in range(10)],
"c": [str(i) for i in range(10)],
"d": [datetime(2020, 3, i, i, 30, 45) for i in range(1, 11)],
}
MANAGER = PerspectiveManager()
APPLICATION = tornado.web.Application(
[
(
r"/websocket",
PerspectiveTornadoHandler,
{"manager": MANAGER, "check_origin": True},
)
]
)
@pytest.fixture(scope="module")
def app():
return APPLICATION
class TestPerspectiveTornadoHandler(object):
def setup_method(self):
"""Flush manager state before each test method execution."""
MANAGER._tables = {}
MANAGER._views = {}
@gen.coroutine
def websocket_client(self, port):
"""Connect and initialize a websocket client connection to the
Perspective tornado server.
If the initialization response is incorrect, raise an `AssertionError`.
"""
client = yield websocket_connect(
"ws://127.0.0.1:{0}/websocket".format(port)
)
yield client.write_message(json.dumps({"id": -1, "cmd": "init"}))
response = yield client.read_message()
assert json.loads(response) == {"id": -1, "data": None}
# Compatibility with Python < 3.3
raise gen.Return(client)
@pytest.mark.gen_test(run_sync=False)
def test_tornado_handler_init(self, app, http_client, http_port):
"""Using Tornado's websocket client, test the websocket provided by
PerspectiveTornadoHandler.
All test methods must import `app`, `http_client`, and `http_port`,
otherwise a mysterious timeout will occur."""
yield self.websocket_client(http_port)
@pytest.mark.gen_test(run_sync=False)
def test_tornado_handler_table_method(self, app, http_client, http_port):
table_name = str(random.random())
table = Table(data)
MANAGER.host_table(table_name, table)
client = yield self.websocket_client(http_port)
yield client.write_message(
json.dumps(
{
"id": 0,
"name": table_name,
"cmd": "table_method",
"method": "schema",
"args": [],
}
)
)
response = yield client.read_message()
assert json.loads(response) == {
"id": 0,
"data": {
"a": "integer",
"b": "float",
"c": "string",
"d": "datetime",
},
}
@pytest.mark.gen_test(run_sync=False)
def test_tornado_handler_create_view_to_dict(
self, app, http_client, http_port
):
table_name = str(random.random())
table = Table(data)
MANAGER.host_table(table_name, table)
client = yield self.websocket_client(http_port)
yield client.write_message(
json.dumps(
{
"id": 0,
"cmd": "view",
"table_name": table_name,
"view_name": "view1",
}
)
)
yield client.write_message(
json.dumps(
{
"id": 1,
"name": "view1",
"cmd": "view_method",
"method": "to_dict",
"args": [],
}
)
)
response = yield client.read_message()
assert response == json.dumps(
{"id": 1, "data": data}, cls=DateTimeEncoder
)
@pytest.mark.gen_test(run_sync=False)
def test_tornado_handler_create_view_to_dict_one_sided(
self, app, http_client, http_port
):
table_name = str(random.random())
table = Table(data)
MANAGER.host_table(table_name, table)
client = yield self.websocket_client(http_port)
yield client.write_message(
json.dumps(
{
"id": 0,
"cmd": "view",
"table_name": table_name,
"view_name": "view1",
"config": {
"row_pivots": ["c"]
}
}
)
)
yield client.write_message(
json.dumps(
{
"id": 1,
"name": "view1",
"cmd": "view_method",
"method": "to_dict",
"args": [],
}
)
)
response = yield client.read_message()
assert response == json.dumps(
{
"id": 1,
"data": {
"__ROW_PATH__": [[]] + [[item] for item in data["c"]],
"a": [sum(data["a"])] + data["a"],
"b": [sum(data["b"])] + data["b"],
"c": [10] + [1 for i in range(10)],
"d": [10] + [1 for i in range(10)],
}
}, cls=DateTimeEncoder
)
@pytest.mark.gen_test(run_sync=False)
def test_tornado_handler_create_view_to_arrow(
self, app, http_client, http_port
):
table_name = str(random.random())
table = Table(data)
MANAGER.host_table(table_name, table)
client = yield self.websocket_client(http_port)
yield client.write_message(
json.dumps(
{
"id": 0,
"cmd": "view",
"table_name": table_name,
"view_name": "view1",
}
)
)
yield client.write_message(
json.dumps(
{
"id": 1,
"name": "view1",
"cmd": "view_method",
"method": "to_arrow",
"args": [],
}
)
)
response = yield client.read_message()
assert json.loads(response) == {
"id": 1,
"name": "view1",
"cmd": "view_method",
"method": "to_arrow",
"args": [],
"is_transferable": True
}
binary = yield client.read_message()
new_table = Table(binary)
assert new_table.view().to_dict() == data
| 0f321b831f8cb0d68675352914f3f85ad55f30e7 | [
"Python"
] | 2 | Python | rohsua/perspective | c486901e055014c9b80daa8397a35711ee41911b | 74b5825aecdd7788c8fb1e65204ca27d7caf49e0 |
refs/heads/master | <file_sep>
# This module is part of mail_merge_scheduler and is released under
# the MIT License: http://www.opensource.org/licenses/mit-license.php
"""This is the module that the user will import and uses to set up a scheduled
mail merges, with data taken from database types supported by sqlalchemy. It
will write the information to the schedules.ini file and uses the xml template
to schedule the task through Windows Task Scheduler. The user can also use this
module to remove scheduled mail merges from both the schedules.ini file and the
Windows Task Scheduler, provided the name of the task, and the key in the
schedules.ini file have not been altered.
"""
# Standard library imports
import configparser
from datetime import time
from datetime import date
from datetime import datetime
from datetime import timedelta
import os
import sys
import subprocess
# Third-party imports
from lxml import etree
import sqlalchemy
def remove_scheduled_merge(scheduled_merge_key):
"""Removes a scheduled mail merge.
This function takes the key from an entry in the schedules.ini files,
and removes it from the ini file, and deletes the task from the
Windows Task Scheduler.
Args:
scheduled_merge_key: A string of a key from a scheduled merge in the
schedules.ini file.
Returns:
None.
Raises:
KeyError: scheduled_merge_key.
"""
config = configparser.ConfigParser()
config.optionxform = str
config.read("scheduled_merges.ini")
sect = "SCHEDULED_MERGES"
del config[sect][scheduled_merge_key]
with open('scheduled_merges.ini', 'w') as config_file:
config.write(config_file)
config_file.close()
# subprocess batch script to Windows Task Scheduler, to delete the task
# whose name correlates to the key id in the schedules.ini file.
task = "schtasks.exe /delete /tn {} /f".format(scheduled_merge_key)
process = subprocess.Popen(task, shell=False)
process.wait()
return
class ScheduledMerge(object):
"""This is the class that the end-user will use to set up a scheduled mail
merge with data taken from a database.
Should work for all database types that are supported by sqlalchemy.
Usage of this class requires 3 steps.
Here is an example:
from mail_merge_scheduler import ScheduledMerge
new_merge = ScheduledMerge(connection_string, query, template_docx_path)
new_merge.set_scheudle(week_interval, days, hour, minute)
new_merge.generate_scheduled_merge()
Attributes:
db_connection_string: A connection string that can be used to connect
to the desired database. Instructions can be found on sqlalchemy's
website at: http://docs.sqlalchemy.org/en/latest/core/engines.html
db_query: A string of a database query that will be used to take data
from the database that the db_connection_string attribute connects
with.
template_docx_file_path: A string giving the full path to a .docx or
.dotx document that has mail merge fields with names that correlate
to the field names of the table in the db_query attribute.
output_docx_name: OPTIONAL A string of the file name only, and not the
full path, of the the .docx document created from the mail merge.
This is a new document, and does not overwrite the
template_docx_file_path.
start_day: A datetime.date object that specifies the day the user wants
the scheduled mail merge task to begin.
week_int: An integer indicating the week interval/frequency for the
scheduled mail merge task to occur.
sched_days: A list of strings indicating the days of the week that the
user would like the scheduled mail merge task to occur on.
sched_time: A datetime.time object indicating the hour and minute of
the day the user wants the scheduled mail merge task to occur.
"""
# pylint: disable=too-many-instance-attributes
def __init__(
self, db_connection_string, db_query,
template_docx_file_path, output_docx_name=None):
"""Init for ScheduledMerge
Raises:
sqlalchemy.exc.OperationalError: no such table.
FileNotFoundError: template_docx_file_path.
"""
# Check if the given connection string and query are valid.
# If invalid, sqlalchemy will raise an error.
engine = sqlalchemy.create_engine(db_connection_string)
engine = engine.connect()
engine.execute(db_query)
engine.close()
# Check if the docx file path is valid.
if os.path.isfile(template_docx_file_path) is False:
raise FileNotFoundError(template_docx_file_path)
## Database Information
self.db_connection_string = db_connection_string
self.db_query = db_query
## Path Information
self.template_docx_file_path = template_docx_file_path
# Output docx is saved to the same folder as the template docx file.
if output_docx_name is None:
self.output_docx_name = None
else:
self.output_docx_name = output_docx_name
## Scheduling Information.
self.start_day = None
self.week_int = None
self.sched_days = []
self.sched_time = None
# pylint: disable=too-many-arguments
def set_scheudle(self, week_interval, days, hour, minute, start_day=None):
"""Allows the end-user to set the attributes for scheduling.
Args:
week_interval: An integer indicating the week interval/frequency
for the scheduled mail merge task to occur.
days: A list of strings indicating the days of the week that the
user would like the scheduled mail merge task to occur on. Each
day must be in a specific format:
1.) The first letter must be uppercase.
2.) The the following letters must be lowercase.
3.) The full name of the day must be used. No abbreviations.
Example: ['Monday', 'Wednesday', 'Friday']
hour: An integer between 0 and 23 (inclusive), indicating the hour,
in military time, the user wants the scheduled mail merge to
occur.
minute: An integer between 0 and 59 (inclusive), indicating the
minute, in military time, the user wants the scheduled mail
merge to occur.
start_day: OPTIONAL A datetime.date object that specifies the day
the user wants the scheduled mail merge task to begin.
Returns:
None.
Raises:
AssertionError: Scheduling Error: Cannot schedule a mail merge with
an empty list of days.
AssertionError: Scheduling Error: List of days contains duplicates.
AssertionError: Scheduling Error: Incorrect format for a day(s) in
your list of days.
"The required format for a day has:
"1.) The full name of the day.
"2.) The first letter is uppercase.
"3.) The following letters are all lowercase.
"Example: ['Monday', 'Wednesday', 'Friday'].
"""
if start_day is None:
self.start_day = date.today()
else:
self.start_day = start_day
self.week_int = int(week_interval)
self.sched_time = time(hour=int(hour), minute=int(minute))
assert days, \
("\nScheduling Error: "
"Cannot schedule a mail merge with an empty list of days.")
assert len(days) == len(set(days)), \
("\nScheduling Error: "
"List of days contains duplicates.")
# days_format_checker and check_days ensures the days are in the proper
# format for use in the Windows Task Scheduler xml schema.
days_format_checker = set([
"Monday", "Tuesday", "Wednesday", "Thursday",
"Friday", "Saturday", "Sunday"])
check_days = [item for item in days if item in days_format_checker]
assert days == check_days, \
("\nScheduling Error:\n"
"Incorrect format for a day(s) in your list of days.\n"
"The required format for a day has:\n"
"1.) The full name of the day.\n"
"2.) The first letter is uppercase.\n"
"3.) The following letters are all lowercase.\n"
"Example: ['Monday', 'Wednesday', 'Friday'].")
self.sched_days = self.generate_list_of_next_days(days)
# Check for errors in other attributes. This was seperated because it
# is used in other areas, and to maintain readability.
self.error_check_attributes()
return
def error_check_attributes(self):
"""Checks to see if all attributes are filled with correct data.
Returns:
None.
Raises:
AssertionError: Scheduling Error: start_day must be a datetime.date
object.
AssertionError: Scheduling Error: Week interval must be an integer
of 1 or above.
AssertionError: Scheduling Error: There was an error with hour or
minute input. Hour must be between 0 and 23, inclusive. Minute
must be between 0 and 59, inclusive.
"""
assert isinstance(self.start_day, date), \
("\nScheduling Error: "
"start_day must be a datetime.date object.")
assert isinstance(self.week_int, int) and self.week_int >= 1, \
("\nScheduling Error: "
"Week interval must be an integer of 1 or above.")
assert isinstance(self.sched_time, time), \
("\nScheduling Error: "
"There was an error with hour or minute input."
"Hour must be between 0 and 23, inclusive."
"Minute must be between 0 and 59, inclusive.")
# Ensure each day in sched_days is a datetime.datetime object.
sched_days_format_check = True
for day in self.sched_days:
if isinstance(day, datetime) is False:
sched_days_format_check = False
break
assert sched_days_format_check is True, \
("\nScheduling Error: "
"One or more of the items in the list of self.sched_days is not a"
"datetime.datetime object.")
return
def load_data_into_list_of_dicts(self):
"""Takes the instance attributes of the class, and converts them into
an appropriate format for storing in the schedules.ini file.
Returns:
A list of dictionaries of attribute names and thier data. This
format was chosen so the data stays in the same place in the
schedules.ini file, so it is easier to read.
"""
# Create a list of dictionaries instead of a single dictionary, so the
# schedules.ini file has better human readability.
days = [str(d) for d in self.sched_days]
list_of_dicts = [
{"db_connection_string":self.db_connection_string},
{"db_query":self.db_query},
{"template_docx_file_path":self.template_docx_file_path},
{"output_docx_name":self.output_docx_name},
{"week_int":self.week_int},
{"sched_days":days}]
return list_of_dicts
def generate_unique_config_key_id(self):
"""Creates a unique string to use as a key in the schedules.ini file.
Returns:
A unique string that is used as the key in the schedules.ini file,
as well as for the task name in the Windows Task Scheduler.
"""
config = configparser.ConfigParser()
config.optionxform = str
config.read("scheduled_merges.ini")
sect = "SCHEDULED_MERGES"
# Get all keys from the .ini file, so a duplicate key is not made.
config_keys_set = set([i for i in config[sect]])
prefix = "Scheduled_Mail_Merge_for"
docx_name = os.path.basename(self.template_docx_file_path)
id_num = 1
hour = self.sched_time.hour
minute = self.sched_time.minute
week_int = self.week_int
config_key_front = "{}_{}_at_{}_{}_every_{}_week(s)".format(
prefix, docx_name, hour, minute, week_int)
config_key = "{}_{}".format(config_key_front, id_num)
# If the key already exists, keep adding 1 to id_num, until a unique
# key is found.
while True:
if config_key in config_keys_set:
id_num += 1
config_key = "{}_{}".format(config_key_front, id_num)
else:
break
return config_key
# pylint: disable=no-self-use
def import_task_to_win_task_sched(self, xml_name, task_name):
"""Imports an xml into Windows Task Scheduler via a subprocess.
Args:
xml_name: A string of the file name of xml that was generated, to
be imported into Windows Task Scheduler.
task_name: A string to be used as the task name for the task in
Windows Task Scheduler.
Returns:
None.
"""
task = "schtasks.exe /create /XML {} /tn {}".format(xml_name, task_name)
process = subprocess.Popen(task, shell=False)
process.wait()
return
# pylint: disable=too-many-locals
def generate_list_of_next_days(self, days):
"""Given the list of days, this method finds when the next occurance of
those days of the week, and converts them into datetime objects and
returns a list of datetime objects.
Args:
days: A list of strings indicating the days of the week that the
user would like the scheduled mail merge task to occur on.
Returns:
A list of datetime.datetime objects.
"""
# A Dictionary for converting the number that is returned from
# datetime.weekday(), into the string representation of the day's name.
weekday_conv = {
"Monday":0, "Tuesday":1, "Wednesday":2, "Thursday":3,
"Friday":4, "Saturday":5, "Sunday":6}
start_hour = self.sched_time.hour
start_minute = self.sched_time.minute
start_day = self.start_day
start_day_num = self.start_day.weekday()
datetime_days = []
for day in days:
day_num = weekday_conv[day]
if start_day_num > day_num:
next_day_num = 6 - (start_day_num - abs(start_day_num -
day_num))
elif start_day_num < day_num:
next_day_num = 7 - (start_day_num + abs(start_day_num -
day_num))
elif start_day_num == day_num:
now = datetime.today().time()
curr_hour = now.hour
curr_minute = now.minute
if curr_hour <= start_hour and curr_minute < start_minute:
next_day_num = 0
else:
next_day_num = 7
start_day_copy = start_day
start_day_copy += timedelta(days=next_day_num)
start_day_copy = str(start_day_copy)
year, month, day = map(int, start_day_copy.split("-"))
next_day = datetime(
year=year, month=month, day=day,
hour=start_hour, minute=start_minute)
datetime_days.append(next_day)
return datetime_days
# pylint: disable=too-many-locals
# pylint: disable=too-many-branches
# pylint: disable=too-many-statements
# pylint: disable=no-member
# pylint: disable=anomalous-backslash-in-string
def xml_gen(self, task_name):
"""Uses the weekly schedule xml template for Windows Task Scheduler,
and replaces specific data in the xml tree, then writes the xml as
out_xml.xml, imports the xml into Windows Task Scheduler via a
subprocess batch script, then deletes out_xml.xml.
Args:
task_name: A string to be used as the task name for the task in
Windows Task Scheduler.
Returns:
None.
Raises:
If the weekly_xml_schedule_template.xml is edited, it may raise
errors pertaining to the Windows Task Scheduler xml schema. If
you would like to edit this xml, you can find information on
how to do so here:
https://msdn.microsoft.com/en-us/library/windows/desktop/aa38360
9(v=vs.85).aspx .
"""
weekday_conv = {
0:"Monday", 1:"Tuesday", 2:"Wednesday", 3:"Thursday",
4:"Friday", 5:"Saturday", 6:"Sunday"}
next_date = self.start_day
next_time = self.sched_time
week_int = self.week_int
days = self.sched_days
days = [weekday_conv[d.weekday()] for d in days]
xml_template = "weekly_xml_schedule_template.xml"
dom = os.getenv("USERDOMAIN")
user = os.getenv("USERNAME")
dn_un = "{}\{}".format(dom, user)
today = datetime.today().date()
curr_time = datetime.today().time()
creation_datetime = "{}T{}".format(today, curr_time)
next_date = "{}T{}".format(next_date, next_time)
# Tries to find the windowless version of the version of python being
# used to run the script. The search is done using typical naming
# conventions for python, but if it cannot be found, then the normal
# version of python will be used.
pyth_path = '\\'.join(sys.executable.split('\\')[0:-1])
files_in_pyth_path = os.listdir(pyth_path)
python_variations = ["python", "Python", "PYTHON"]
windowless_pyth_path = ""
for file_name in files_in_pyth_path:
for var in python_variations:
if var in file_name:
if "w" in file_name or "W" in file_name:
windowless_pyth_path = "{}\\{}".format(
pyth_path, file_name)
# If the windowless python executable couldnt be found, then use the
# windowed executable that is being used to run the script.
if not windowless_pyth_path:
windowless_pyth_path = sys.executable
# name of the script that Windows Task Scheduler will run.
script_name = "schedules.py"
curr_dir = os.getcwd()
curr_dir = r"{}".format(curr_dir)
tree = etree.parse(xml_template)
for ele in tree.iter():
# The prefix is set to
# http://schemas.microsoft.com/windows/2004/02/mit/task
# This should work on all versions of Windows newer than, and
# including, Windows Vista.
prefix = str(ele.tag)[:55]
tag_name = str(ele.tag)[55:]
if tag_name == "Date":
ele.text = creation_datetime
if tag_name == "Author":
ele.text = dn_un
if tag_name == "Description":
ele.text = "Scheduled Mail Merge"
if tag_name == "StartBoundary":
ele.text = next_date
if tag_name == "WeeksInterval":
ele.text = str(week_int)
if tag_name == "DaysOfWeek":
for day in days:
etree.SubElement(ele, "{}{}".format(prefix, day))
if tag_name == "UserId":
ele.text = dn_un
if tag_name == "Command":
ele.text = r"{}".format(windowless_pyth_path)
if tag_name == "Arguments":
ele.text = script_name
if tag_name == "WorkingDirectory":
ele.text = curr_dir
xml_name = "out_xml.xml"
tree.write(xml_name, xml_declaration=None, encoding='UTF-16')
# Import the generated xml into Windows task Scheduler via a subprocess
# batch script.
self.import_task_to_win_task_sched(xml_name, task_name)
# Remove the generated xml after it has been imported.
os.remove("out_xml.xml")
return
# pylint: disable=too-many-locals
def generate_scheduled_merge(self):
"""Finalizes the scheduled mail merge.
Writes a dictionary of the intance attributes to the schedules.ini
file, and generates an xml from the template xml and imports the xml
into Windows Task Scheduler.
Returns:
None.
Raises:
All errors raised by the method: error_check_attributes(self)
"""
# Do a quick check for errors before generating a scheduled mail merge.
self.error_check_attributes()
# Make a list of dictionaries to be written to the schedules.ini file.
list_of_dicts_of_merge_data = self.load_data_into_list_of_dicts()
config = configparser.ConfigParser()
# optionxform maintains upercase letters in strings for keys.
config.optionxform = str
config.read("scheduled_merges.ini")
sect = "SCHEDULED_MERGES"
# Shorten the config_key_id string if the length exceedes the maximum
# length for a task name in Windows Task Scheduler of 232 characters.
config_key_id = self.generate_unique_config_key_id()
config_key_id = config_key_id[:232]
config[sect][config_key_id] = str(list_of_dicts_of_merge_data)
with open('scheduled_merges.ini', 'w') as config_file:
config.write(config_file)
config_file.close()
# Create an xml, from the template xml, that will be used to import
# into Windows Task Scheduler.
self.xml_gen(str(config_key_id))
return
<file_sep>[SCHEDULED_MERGES]
| e07a51083cf4a103ccb73ff8ae03750082511d51 | [
"Python",
"INI"
] | 2 | Python | verdra/mail_merge_scheduler | 45ec54187151dd27bc732686cc2fa32457897a98 | 92c387ceb2a0e3adc50c8c3c680037779cc43d1f |
refs/heads/master | <file_sep>//
// ViewController.swift
// SmaSmaForMac
//
// Created by ADK114019 on 2016/12/27.
// Copyright © 2016年 ADK114019. All rights reserved.
//
import Cocoa
import BleFormatterForMac
let SERVICE_UUID = "0BF806E9-F1FE-4326-AB21-CEAFDEAFE0E0"
let CHR_UUID_1 = "F5A6373E-B756-4B55-BE51-F8BD9A4A3193"
//let CHR_UUID_2 = "BC24FB53-E185-4C05-8221-FFF92242914F"
class ViewController: NSViewController {
var bleManager:BleManager!;
var dataFormat:[BleDataFormat] = []
override func viewDidLoad() {
super.viewDidLoad()
self.bleManager = BleManager.sharedInstance;
self.bleManager.setUUID(serviceUUID: SERVICE_UUID)
self.dataFormat.append(BleDataFormat(uuid: CHR_UUID_1, dataType: .String))
// self.dataFormat.append(BleDataFormat(uuid: CHR_UUID_2, dataType: .String))
self.bleManager.setReadDataFormat(bleDataFormat: self.dataFormat)
// observer登録
self.bleManager.addObserver(self, withRead: #selector(ViewController.readNotification(_:)))
self.bleManager.addObserver(self, withWrite: #selector(ViewController.writeNotification(_:)))
// Do any additional setup after loading the view.
}
override var representedObject: Any? {
didSet {
// Update the view, if already loaded.
}
}
@IBAction func onClickButton(_ sender: Any) {
bleManager.write(withString: "test", dataFormat: &self.dataFormat[0])
}
@IBAction func onClickSendHTTP(_ sender: Any) {
// sendSmartDeviceData()
}
func sendSmartDeviceData(_ message:String) {
let request: Request = Request()
// no=C93057&user=kenji&used=false
let urlTmp = "http://localhost:8000/insertEnginSpeed.php" + message
let url: URL = URL(string: urlTmp)!
let body: NSMutableDictionary = NSMutableDictionary()
body.setValue("value", forKey: "key")
do {
try request.get(url: url, completionHandler: { data, response, error in
if let dataValue = data {
print("\(dataValue)")
do {
let jsonNode = try JSONSerialization.jsonObject(with: dataValue, options: .allowFragments)
print("\(jsonNode)")
} catch {
}
}
})
// try request.post(url: url, body: body, completionHandler: { data, response, error in
// print("\(data)")
// code
// })
} catch {
}
}
func sendSampleLaravel() {
let request: Request = Request()
let url: URL = URL(string: "http://172.28.36.66:8000/smartdata/3")!
// let url: URL = URL(string: "http://localhost:8000/smartphones")!
let body: NSMutableDictionary = NSMutableDictionary()
body.setValue("value", forKey: "key")
do {
try request.get(url: url, completionHandler: { data, response, error in
print("\(data)")
do {
let jsonNode = try JSONSerialization.jsonObject(with: data!, options: .allowFragments)
print("\(jsonNode)")
} catch {
}
})
// try request.post(url: url, body: body, completionHandler: { data, response, error in
// print("\(data)")
// code
// })
} catch {
}
}
func readNotification(_ notification: Notification) {
// 変数宣言時にアンラップ & キャストする方法
// let userInfo = [BleDataKey.NOTIFY_READ.description():dataFormatList[index].characteristicUUID.description,
// BleDataKey.VALUE.description():dataFormatList[index].value] as [String : Any]
// let value = self.dataFormatList[index].getStringFromValue()
var tmpValue:String?
guard let userInfo = notification.userInfo else {
return
}
let data = userInfo[BleDataKey.NOTIFY_READ.description()] as! BleDataFormat
switch data.dataType {
case .String:
tmpValue = data.getStringFromValue() as String
case .Int:
let i = data.getIntFromValue() as Int
print("read Int value = \(i)")
tmpValue = data.getStringFromValue() as String
case .Double:
let i = data.getDoubleFromValue() as Double
print("read Double value = \(i)")
tmpValue = data.getStringFromValue() as String
case .Data:
let i = data.getDataFromValue() as Data
print("read Data value = \(i)")
tmpValue = data.getStringFromValue() as String
}
guard let value = tmpValue else {
print("can not read Notification message!!")
return
}
print("read Notification message = \(value)")
sendSmartDeviceData(value)
let postName = data.getPostName() as String
// self.myTalkFlg = false
// talkList.insert(value + "," + postName, at: 0)
// let indexPath = IndexPath(row: 0, section: 0)
// self.tableView.insertRows(at: [indexPath], with: .automatic)
}
func writeNotification(_ notification: Notification) {
// 変数宣言時にアンラップ & キャストする方法
// self.msgText.text = ""
return
}
}
| d3f04a49099daece4aaf1e48684b4f0fcae15a83 | [
"Swift"
] | 1 | Swift | kekenzy/SmaSmaForMac | ff46cb12988ab42daddfc7dc5f3445d51bebed6f | 074009125d4ac5dc8298a8859737d965efab5b93 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.