branch_name
stringclasses
149 values
text
stringlengths
23
89.3M
directory_id
stringlengths
40
40
languages
listlengths
1
19
num_files
int64
1
11.8k
repo_language
stringclasses
38 values
repo_name
stringlengths
6
114
revision_id
stringlengths
40
40
snapshot_id
stringlengths
40
40
refs/heads/master
<repo_name>rena987/Find4Rescue<file_sep>/app/src/main/java/com/example/find4rescue/models/Comments.java package com.example.find4rescue.models; import com.parse.ParseClassName; import com.parse.ParseObject; import org.json.JSONArray; @ParseClassName("Comments") public class Comments extends ParseObject { public static final String KEY_COMMENTEDRISK = "CommentedRisk"; public static final String KEY_USERNAMES = "Usernames"; public static final String KEY_MESSAGES = "Messages"; public Comments() { } public ParseObject getRisk() { return getParseObject(KEY_COMMENTEDRISK); } public void setRisk(ParseObject risk) { put(KEY_COMMENTEDRISK, risk); } public JSONArray getUsernames() { return getJSONArray(KEY_USERNAMES); } public void setUsernames(JSONArray usernames) { put(KEY_USERNAMES, usernames); } public JSONArray getMessages() { return getJSONArray(KEY_MESSAGES); } public void setMessages(JSONArray messages) { put(KEY_MESSAGES, messages); } } <file_sep>/settings.gradle rootProject.name = "Find4Rescue" include ':app' <file_sep>/README.md # Find4Rescue ## Wireframes ![Wireframes2](https://user-images.githubusercontent.com/47072485/125831227-3d936594-abdf-4649-b568-93a861e90172.jpg) ## User Stories The following **required** functionality is completed: * [x] Rescuer can **sign in** to his or her account * [x] Rescuer can **sign out** to his or her account * [x] Rescuer can **log out** from his or her account * [x] Rescuer can **view people in need of help** in the Search View * [x] Rescuer can see details of risk (stored on Parse Database) within the main Search View such as: * [x] Primary Rescuer who reported the risk * [x] Address of the Risk * [x] Type of Risk * [x] Description of the Risk * [x] The [relative timestamp](https://gist.github.com/nesquena/f786232f5ef72f6e10a7) when each risk was reported (eg. "8m", "7h") * [x] Rescuer can create a new "risk" on search screen through given: * [x] Coordinates * [x] Address * [x] Type * [x] Description * [x] Image * [x] Rescuer can attach an image from their drive * [x] Rescuer can take picture from their device * [x] Rescuer can filter out risks based on most recent and rescuers needed * [ ] Rescuer can double tap on a risk to address it (gesture) * [x] Rescuer can **view a detailed view** of each risk in the Search View * [x] Rescuer can access the detailed view by: * [x] Tap on individual risk from the search view * [x] Open search detail view using shared element transition (Animation) * [x] Rescuer can view all the details they saw on the search screen plus the number of existing rescuers addressing the risk * [x] Rescuer can "like" or press the heart button to indicate to other rescuers that they are also addressing the risk by incrementing the number of existing rescuers displayed * [x] Rescuer can comment and view other rescuers comments on the risk by pressing the "message" button * [x] Rescuer can **view arcGIS map** by pressing the "map" button * [x] Rescuer can view parcel polygon lines of the county they are in (Orange County) * [x] Rescuer can plot highlighted parcel polygon they have selected to help based on the risk they click on the search view * [x] Rescuer can view details of the highlighted parcel polygon: * [x] Parcel Identification Number * [x] Subdivision * [x] Complete Address * [x] Rescuer can press on camera button in the bottom navigation view to take picture in order to: * [x] Make new risk The following **stretch** features are implemented: * [ ] Rescuer sees an **indeterminate progress indicator** when any background or network task is happening * [x] Rescuer can find the distance between themselves and the risk they are dealing with on arcGIS map * [ ] Rescuer can search for a "risk" based on type * [ ] Rescuer can view more people at risk as they scroll with infinite pagination * [ ] "Person in need" has there own login where they can chat with rescuers * [ ] Replace all icon drawables and other static image assets with vector drawables * [ ] Use the View Binding library to reduce view boilerplate. * [ ] Rescuer can **pull down to refresh search screen** * [ ] Use 2-3 more counties as data for the arcGIS map # Schema ## Risk | Property | Type | Description | | -------------- | ---- | ------------- | | objectId | String | unique id for "risk screen" (default field) | | createdAt | DateTime | date when "risk screen" is created (default field) | | updatedAt | DateTime | date when "risk screen" is last updated (default field) | | Address | String | address of where the risk is ocurring | | Type | String | type of risk | | Rescuer | Pointer to User | author of "risk screen" | | Image | File | image that rescuer attached to risk | | Description | String | description of "risk" | | DealtOrNot | Boolean | whether or not the "risk screen" is being dealt with already | | NumOfRescuers | Number | number of rescuers dealing with the risk | ## Comments | Property | Type | Description | | -------------- | ---- | ------------- | | objectId | String | unique id for "risk screen" (default field) | | createdAt | DateTime | date when "risk screen" is created (default field) | | updatedAt | DateTime | date when "risk screen" is last updated (default field) | | CommentedRisk | Pointer to Risk | Risk on which is being commented on | | Usernames | Array | Array of strings of the usernames within the comments | | Messages | Array | Array of strings of the messages corresponding to the usernames | <file_sep>/app/src/main/java/com/example/find4rescue/fragments/CommentFragment.java package com.example.find4rescue.fragments; import android.os.Bundle; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.fragment.app.Fragment; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import androidx.appcompat.widget.AppCompatImageButton; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; import android.widget.EditText; import android.widget.Toast; import com.example.find4rescue.R; import com.example.find4rescue.adapters.CommentsAdapter; import com.example.find4rescue.models.Risk; import com.parse.FindCallback; import com.parse.GetCallback; import com.parse.ParseException; import com.parse.ParseObject; import com.parse.ParseQuery; import com.parse.ParseUser; import org.json.JSONArray; import org.json.JSONException; import java.util.ArrayList; import java.util.List; /** * A simple {@link Fragment} subclass. */ public class CommentFragment extends Fragment { public static final String TAG = "CommentFragment"; EditText etMessage; AppCompatImageButton ibSend; RecyclerView rvComments; ParseQuery<ParseObject> query; List<String> usernames; List<String> messages; CommentsAdapter adapter; public CommentFragment() { // Required empty public constructor } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment return inflater.inflate(R.layout.fragment_comment, container, false); } @Override public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); etMessage = view.findViewById(R.id.etMessage); ibSend = view.findViewById(R.id.ibSend); rvComments = view.findViewById(R.id.rvComments); usernames = new ArrayList<>(); messages = new ArrayList<>(); Risk risk = getArguments().getParcelable("risk"); query = ParseQuery.getQuery("Comments"); query.whereEqualTo("CommentedRisk", risk); query.getFirstInBackground(new GetCallback<ParseObject>() { @Override public void done(ParseObject object, ParseException e) { JSONArray usernames_arr_ = object.getJSONArray("Usernames"); JSONArray messages_arr_ = object.getJSONArray("Messages"); for (int i = 0; i < usernames_arr_.length(); i++) { try { usernames.add(usernames_arr_.getString(i)); messages.add(messages_arr_.getString(i)); adapter = new CommentsAdapter(getContext(), usernames, messages); rvComments.setAdapter(adapter); rvComments.setLayoutManager(new LinearLayoutManager(getContext())); refreshComments(); } catch (JSONException jsonException) { jsonException.printStackTrace(); } } } }); ibSend.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { String message = etMessage.getText().toString(); String username = ParseUser.getCurrentUser().getUsername(); query.getFirstInBackground(new GetCallback<ParseObject>() { @Override public void done(ParseObject object, ParseException e) { if (e == null) { JSONArray usernames = object.getJSONArray("Usernames"); usernames.put(username); object.put("Usernames", usernames); JSONArray messages = object.getJSONArray("Messages"); messages.put(message); object.put("Messages", messages); object.saveInBackground(); refreshComments(); etMessage.setText(""); } else { // something went wrong Toast.makeText(getContext(), e.getMessage(), Toast.LENGTH_SHORT).show(); } } }); } }); } private void refreshComments() { query.getFirstInBackground(new GetCallback<ParseObject>() { @Override public void done(ParseObject object, ParseException e) { messages.clear(); usernames.clear(); JSONArray usernames_arr_ = object.getJSONArray("Usernames"); JSONArray messages_arr_ = object.getJSONArray("Messages"); for (int i = 0; i < usernames_arr_.length(); i++) { try { usernames.add(usernames_arr_.getString(i)); messages.add(messages_arr_.getString(i)); Log.d(TAG, "Refreshing: " + messages); adapter.notifyDataSetChanged(); } catch (JSONException jsonException) { jsonException.printStackTrace(); } } } }); } }<file_sep>/app/src/main/java/com/example/find4rescue/fragments/CreateSearchFragment.java package com.example.find4rescue.fragments; import android.content.Intent; import android.content.pm.PackageManager; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Color; import android.graphics.ImageDecoder; import android.graphics.drawable.BitmapDrawable; import android.graphics.drawable.ColorDrawable; import android.net.Uri; import android.os.Build; import android.os.Bundle; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.core.app.ActivityCompat; import androidx.core.content.ContextCompat; import androidx.core.content.FileProvider; import androidx.fragment.app.Fragment; import android.os.Environment; import android.provider.MediaStore; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.EditText; import android.widget.ImageView; import android.widget.Toast; import com.example.find4rescue.R; import com.example.find4rescue.models.Comments; import com.example.find4rescue.models.Risk; import com.google.android.material.floatingactionbutton.FloatingActionButton; import com.parse.ParseException; import com.parse.ParseFile; import com.parse.ParseUser; import com.parse.SaveCallback; import org.json.JSONArray; import org.w3c.dom.Comment; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.IOException; import static android.Manifest.permission.ACCESS_COARSE_LOCATION; import static android.Manifest.permission.READ_EXTERNAL_STORAGE; import static android.Manifest.permission.WRITE_EXTERNAL_STORAGE; import static android.app.Activity.RESULT_OK; /** * A simple {@link Fragment} subclass. * create an instance of this fragment. */ public class CreateSearchFragment extends Fragment { private EditText etLatitude; private EditText etLongitude; private EditText etCreateAddress; private EditText etCreateType; private EditText etCreateDescription; private Button btnAttachImage; private Button btnTakePicture; private ImageView ivCreateImage; private Button btnCreateAddRisk; public static final String TAG = "MakeRisk"; public final static int PICK_PHOTO_REQUEST_CODE = 1046; public static final int CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = 37; public File photoFile; public String photoFileName = "photo.jpg"; public CreateSearchFragment() { // Required empty public constructor } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment return inflater.inflate(R.layout.fragment_create_search, container, false); } @Override public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); etLatitude = view.findViewById(R.id.etLatitude); etLongitude = view.findViewById(R.id.etLongitude); etCreateAddress = view.findViewById(R.id.etCreateAddress); etCreateType = view.findViewById(R.id.etCreateType); etCreateDescription = view.findViewById(R.id.etCreateDescription); btnAttachImage = view.findViewById(R.id.btnAttachImage); btnTakePicture = view.findViewById(R.id.btnTakePicture); ivCreateImage = view.findViewById(R.id.ivCreateImage); btnCreateAddRisk = view.findViewById(R.id.btnCreateAddRisk); Bundle bundle = this.getArguments(); if (bundle != null) { Bitmap bitmap = bundle.getParcelable("bitmap"); ivCreateImage.setImageBitmap(bitmap); } btnTakePicture.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { launchCamera(); } }); btnAttachImage.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { onPickPhoto(v); } }); btnCreateAddRisk.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Log.d(TAG, "Attempt to add risk..."); clearBackgroundFields(); if (!checkEmptyFields()) { return; } saveRisk(); } }); } private void saveRisk() { Log.d(TAG, "Attempting to save risk..."); Risk risk = new Risk(); risk.setCoordinates(etLatitude.getText().toString() + "," + etLongitude.getText().toString()); risk.setAddress(etCreateAddress.getText().toString()); risk.setType(etCreateType.getText().toString()); risk.setDescription(etCreateDescription.getText().toString()); risk.setRescuer(ParseUser.getCurrentUser()); Bitmap bitmap = ((BitmapDrawable) ivCreateImage.getDrawable()).getBitmap(); ByteArrayOutputStream stream = new ByteArrayOutputStream(); bitmap.compress(Bitmap.CompressFormat.JPEG, 100, stream); byte[] bitmapBytes = stream.toByteArray(); ParseFile image = new ParseFile(photoFileName, bitmapBytes); risk.setImage(image); Log.d(TAG, "Risk: " + risk.getAddress() + ", " + risk.getRescuer().getUsername()); risk.saveInBackground(new SaveCallback() { @Override public void done(ParseException e) { if (e != null) { Log.e(TAG, "Error while saving: " + e); return; } Log.d(TAG, "Risk was saved successfully!"); clearTextualFields(); } }); Comments comment = new Comments(); comment.setRisk(risk); comment.setUsernames(new JSONArray()); comment.setMessages(new JSONArray()); comment.saveInBackground(new SaveCallback() { @Override public void done(ParseException e) { if (e != null) { Log.e(TAG, "Error while saving: " + e); } } }); getFragmentManager().beginTransaction().replace(R.id.flContainer, new SearchFragment()).commit(); } private void clearTextualFields() { etLatitude.setText(""); etLongitude.setText(""); etCreateAddress.setText(""); etCreateType.setText(""); etCreateDescription.setText(""); ivCreateImage.setImageResource(0); } private void clearBackgroundFields() { etLatitude.setBackground(new ColorDrawable(Color.parseColor("#FFFFFF"))); etLongitude.setBackground(new ColorDrawable(Color.parseColor("#FFFFFF"))); etCreateAddress.setBackground(new ColorDrawable(Color.parseColor("#FFFFFF"))); etCreateType.setBackground(new ColorDrawable(Color.parseColor("#FFFFFF"))); etCreateDescription.setBackground(new ColorDrawable(Color.parseColor("#FFFFFF"))); Log.d(TAG, "Attempting to clear background risk..."); } private Boolean checkEmptyFields() { Boolean checkEmpty = true; if (etLatitude.getText().toString().isEmpty()) { etLatitude.setBackground(new ColorDrawable(Color.parseColor("#F08080"))); checkEmpty = false; } if (etLongitude.getText().toString().isEmpty()) { etLongitude.setBackground(new ColorDrawable(Color.parseColor("#F08080"))); checkEmpty = false; } if (etCreateAddress.getText().toString().isEmpty()) { etCreateAddress.setBackground(new ColorDrawable(Color.parseColor("#F08080"))); checkEmpty = false; } if (etCreateType.getText().toString().isEmpty()) { etCreateType.setBackground(new ColorDrawable(Color.parseColor("#F08080"))); checkEmpty = false; } if (etCreateDescription.getText().toString().isEmpty()) { etCreateDescription.setBackground(new ColorDrawable(Color.parseColor("#F08080"))); checkEmpty = false; } if (ivCreateImage.getDrawable() == null) { Toast.makeText(getContext(), "You haven't attached an iamge!", Toast.LENGTH_SHORT).show(); checkEmpty = false; } Log.d(TAG, "Attempting to clear textual risk..."); return checkEmpty; } private void launchCamera() { Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); photoFile = getPhotoFileUri(photoFileName); Uri fileProvider = FileProvider.getUriForFile(getContext(), "com.codepath.fileprovider", photoFile); intent.putExtra(MediaStore.EXTRA_OUTPUT, fileProvider); if (intent.resolveActivity(getContext().getPackageManager()) != null) { startActivityForResult(intent, CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE); } } public File getPhotoFileUri(String fileName) { File mediaStorageDir = new File(getContext().getExternalFilesDir(Environment.DIRECTORY_PICTURES), TAG); if (!mediaStorageDir.exists() && !mediaStorageDir.mkdirs()){ Log.d(TAG, "failed to create directory"); } return new File(mediaStorageDir.getPath() + File.separator + fileName); } @Override public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) { super.onActivityResult(requestCode, resultCode, data); if (requestCode == CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE) { if (resultCode == RESULT_OK) { Bitmap takenImage = BitmapFactory.decodeFile(photoFile.getAbsolutePath()); ivCreateImage.setImageBitmap(takenImage); } else { Toast.makeText(getContext(), "Picture wasn't taken!", Toast.LENGTH_SHORT).show(); } } else if (requestCode == PICK_PHOTO_REQUEST_CODE) { if (resultCode == RESULT_OK) { Uri photoUri = data.getData(); Bitmap selectedImage = loadFromUri(photoUri); ivCreateImage.setImageBitmap(selectedImage); } else { Toast.makeText(getContext(), "Invalid uploaded picture!", Toast.LENGTH_SHORT).show(); } } } public void onPickPhoto(View view) { Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI); if (intent.resolveActivity(getActivity().getPackageManager()) != null) { startActivityForResult(intent, PICK_PHOTO_REQUEST_CODE); } } public Bitmap loadFromUri(Uri photoUri) { Bitmap image = null; try { if(Build.VERSION.SDK_INT > 27){ ImageDecoder.Source source = ImageDecoder.createSource(getContext().getContentResolver(), photoUri); image = ImageDecoder.decodeBitmap(source); } else { image = MediaStore.Images.Media.getBitmap(getContext().getContentResolver(), photoUri); } } catch (IOException e) { e.printStackTrace(); } return image; } }<file_sep>/app/src/main/java/com/example/find4rescue/fragments/SearchFragment.java package com.example.find4rescue.fragments; import android.os.Bundle; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.appcompat.widget.SearchView; import androidx.core.view.MenuItemCompat; import androidx.core.view.ViewCompat; import androidx.fragment.app.Fragment; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; import androidx.swiperefreshlayout.widget.SwipeRefreshLayout; import android.util.Log; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.widget.CompoundButton; import android.widget.ImageView; import android.widget.Switch; import android.widget.Toast; import com.bumptech.glide.Glide; import com.example.find4rescue.R; import com.example.find4rescue.adapters.RiskAdapter; import com.example.find4rescue.models.Risk; import com.google.android.material.floatingactionbutton.FloatingActionButton; import com.parse.FindCallback; import com.parse.ParseException; import com.parse.ParseObject; import com.parse.ParseQuery; import com.parse.ParseUser; import com.squareup.picasso.Picasso; import java.util.ArrayList; import java.util.List; /** * A simple {@link Fragment} subclass. * create an instance of this fragment. */ public class SearchFragment extends Fragment { public static final String TAG = "SearchFragment"; RecyclerView rvRisks; List<Risk> risks; RiskAdapter riskAdapter; FloatingActionButton fabAddRisk; Switch stSort; public SearchFragment() { // Required empty public constructor } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment return inflater.inflate(R.layout.fragment_search, container, false); } @Override public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); risks = new ArrayList<>(); rvRisks = view.findViewById(R.id.rvRisks); fabAddRisk = view.findViewById(R.id.fabAddRisk); stSort = view.findViewById(R.id.stSort); queryRisks(false); stSort.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { queryRisks(isChecked); } }); riskAdapter = new RiskAdapter(getContext(), risks, onRiskClickListener, onRiskLongClickListener); rvRisks.setAdapter(riskAdapter); rvRisks.setLayoutManager(new LinearLayoutManager(getContext())); fabAddRisk.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { getFragmentManager() .beginTransaction() .replace(R.id.flContainer, new CreateSearchFragment()) .commit(); } }); } RiskAdapter.OnRiskClickListener onRiskClickListener = new RiskAdapter.OnRiskClickListener() { @Override public void onRiskClick(int position, Risk risk, ImageView imageView) { SearchDetailFragment fragment = new SearchDetailFragment(); Bundle bundle = new Bundle(); bundle.putParcelable("risk", risks.get(position)); bundle.putString("transitionName", ViewCompat.getTransitionName(imageView)); fragment.setArguments(bundle); getFragmentManager() .beginTransaction() .addSharedElement(imageView, ViewCompat.getTransitionName(imageView)) .replace(R.id.flContainer, fragment) .commit(); } }; RiskAdapter.OnRiskLongClickListener onRiskLongClickListener = new RiskAdapter.OnRiskLongClickListener() { @Override public boolean onRiskLongClicked(int position, Risk risk) { if (ParseUser.getCurrentUser().getUsername().equals(risk.getRescuer().getUsername())) { Log.d(TAG, "Long clicked: " + position); risks.remove(position); riskAdapter.notifyDataSetChanged(); deleteRisk(risk); return true; } else { Log.d(TAG, "No access to risk!"); return false; } } }; private void deleteRisk(Risk risk) { ParseQuery<ParseObject> query = ParseQuery.getQuery("Risk"); query.getInBackground(risk.getObjectId(), (object, e) -> { if (e == null) { object.deleteInBackground(e2 -> { if(e2==null){ Log.d(TAG,"Delete Successful"); }else{ Log.d(TAG,"Error: "+e2.getMessage()); } }); }else{ Log.d(TAG, "Error: "+e.getMessage()); } }); } private void queryRisks(boolean isChecked) { ParseQuery<Risk> query = ParseQuery.getQuery(Risk.class); query.include(Risk.KEY_RESCUER); query.setLimit(20); if (isChecked) { query.orderByAscending("NumOfRescuers"); } else { query.orderByDescending("createdAt"); } query.findInBackground(new FindCallback<Risk>() { @Override public void done(List<Risk> objects, ParseException e) { riskAdapter.clear(); if (e != null) { Log.e(TAG, "Issue with getting risks: " + e); return; } risks.addAll(objects); riskAdapter.notifyDataSetChanged(); } }); } }<file_sep>/app/src/main/java/com/example/find4rescue/adapters/RiskAdapter.java package com.example.find4rescue.adapters; import android.content.Context; import android.os.Bundle; import android.text.format.DateUtils; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.EditText; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.TextView; import androidx.annotation.NonNull; import androidx.core.view.ViewCompat; import androidx.recyclerview.widget.RecyclerView; import com.bumptech.glide.Glide; import com.example.find4rescue.R; import com.example.find4rescue.databinding.ItemRiskBinding; import com.example.find4rescue.fragments.SearchDetailFragment; import com.example.find4rescue.models.Risk; import com.parse.ParseFile; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; import java.util.List; import java.util.Locale; public class RiskAdapter extends RecyclerView.Adapter<RiskAdapter.ViewHolder> { public interface OnRiskClickListener { void onRiskClick(int position, Risk risk, ImageView imageView); } public interface OnRiskLongClickListener { boolean onRiskLongClicked(int position, Risk risk); } Context context; List<Risk> risks; OnRiskClickListener listener; OnRiskLongClickListener longListener; private static final int SECOND_MILLIS = 1000; private static final int MINUTE_MILLIS = 60 * SECOND_MILLIS; private static final int HOUR_MILLIS = 60 * MINUTE_MILLIS; private static final int DAY_MILLIS = 24 * HOUR_MILLIS; public RiskAdapter(Context context, List<Risk> risks, OnRiskClickListener listener, OnRiskLongClickListener longListener) { this.context = context; this.risks = risks; this.listener = listener; this.longListener = longListener; } @NonNull @Override public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { Log.d("RiskAdapter", "OnCreateViewHolder"); View view = LayoutInflater.from(context).inflate(R.layout.item_risk, parent, false); return new ViewHolder(view, listener); } @Override public void onBindViewHolder(@NonNull RiskAdapter.ViewHolder holder, int position) { Log.d("RiskAdapter", "OnBindViewHolder: " + position); Risk risk = risks.get(position); ViewCompat.setTransitionName(holder.ivDisasterImage, risk.getDescription()); holder.bind(risk); holder.itemView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { listener.onRiskClick(holder.getAdapterPosition(), risk, holder.ivDisasterImage); } }); holder.itemView.setOnLongClickListener(new View.OnLongClickListener() { @Override public boolean onLongClick(View v) { longListener.onRiskLongClicked(holder.getAdapterPosition(), risk); return true; } }); } @Override public int getItemCount() { return risks.size(); } // Clean all elements of the recycler public void clear() { risks.clear(); notifyDataSetChanged(); } // Add a list of items -- change to type used public void addAll(List<Risk> list) { risks.addAll(list); notifyDataSetChanged(); } public class ViewHolder extends RecyclerView.ViewHolder { TextView tvDescription; TextView tvType; TextView tvUsername; TextView tvAddress; ImageView ivDisasterImage; TextView tvTimestamp; OnRiskClickListener onRiskClickListener; public ViewHolder(@NonNull View itemView, OnRiskClickListener listener) { super(itemView); tvDescription = itemView.findViewById(R.id.tvDescription); tvType = itemView.findViewById(R.id.tvType); tvUsername = itemView.findViewById(R.id.tvUsername); tvAddress = itemView.findViewById(R.id.tvAddress); ivDisasterImage = itemView.findViewById(R.id.ivDisasterImage); tvTimestamp = itemView.findViewById(R.id.tvTimestamp); onRiskClickListener = listener; } public void bind(Risk risk) { tvDescription.setText("Description: " + risk.getDescription()); tvType.setText("Type: " + risk.getType()); tvUsername.setText("Rescuer: " + risk.getRescuer().getUsername()); tvAddress.setText("Address: " + risk.getAddress()); ParseFile image = risk.getImage(); if (image != null) { Glide.with(context) .load(image.getUrl()) .into(ivDisasterImage); } Date date = risk.getCreatedAt(); Log.d("RiskAdapter", "date: " + getRelativeTimeAgo(date.toString())); tvTimestamp.setText(getRelativeTimeAgo(date.toString())); SearchDetailFragment fragment = new SearchDetailFragment(); Bundle bundle = new Bundle(); bundle.putParcelable("risk", risk); fragment.setArguments(bundle); } public String getRelativeTimeAgo(String rawJsonDate) { String twitterFormat = "EEE MMM dd HH:mm:ss ZZZZZ yyyy"; SimpleDateFormat sf = new SimpleDateFormat(twitterFormat, Locale.ENGLISH); sf.setLenient(true); try { long time = sf.parse(rawJsonDate).getTime(); long now = System.currentTimeMillis(); final long diff = now - time; if (diff < MINUTE_MILLIS) { return "just now"; } else if (diff < 50 * MINUTE_MILLIS) { return diff / MINUTE_MILLIS + "m"; } else if (diff < 24 * HOUR_MILLIS) { return diff / HOUR_MILLIS + "h"; } else { return diff / DAY_MILLIS + "d"; } } catch (ParseException e) { Log.i("RiskAdapter", "getRelativeTimeAgo failed"); e.printStackTrace(); } return ""; } } }
86329e86b85e6b04f35a055b556dc0f026e09fa7
[ "Markdown", "Java", "Gradle" ]
7
Java
rena987/Find4Rescue
37ec7e58cb77c40e4f65def3fc41bab559b315fb
da1ce52218cba4fe82df7d8e2cf01b387222377b
refs/heads/master
<repo_name>SpardaProgram/KillRush-Game-Projetc<file_sep>/src/com/spardagames/main/Game.java package com.spardagames.main; import java.awt.Canvas; import java.awt.Color; import java.awt.Dimension; import java.awt.Font; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.event.KeyEvent; import java.awt.event.KeyListener; import java.awt.image.BufferStrategy; import java.awt.image.BufferedImage; import java.util.ArrayList; import java.util.List; import java.util.Random; import javax.swing.JFrame; import com.spardagames.entities.GameObjects; import com.spardagames.entities.Monstro; import com.spardagames.entities.Jogador; import com.spardagames.entities.Shoot; import com.spardagames.graficos.SpriteSheet; import com.spardagames.graficos.UI; import com.spardagames.world.World; public class Game extends Canvas implements Runnable,KeyListener{ private static final long serialVersionUID = 1L; public boolean active=false; public static final int altura=240; public static final int largura=240; public static final int escala=3; public Thread thread; public BufferedImage layer = new BufferedImage(largura,altura,BufferedImage.TYPE_INT_RGB); public static List<GameObjects> entities; public static List<Monstro> monstros; public static List<Shoot> shoots; public static SpriteSheet spritesheet; public static Jogador player; public static Random rand; public UI ui; public static String gameState = "MENU"; private int CUR_LEVEL = 1,MAX_LEVEL = 2; private boolean showMessageGameOver = false; private int framesGameOver = 0; private boolean restartGame = false; public Menu menu; public static World world; public Game() { addKeyListener(this); rand = new Random(); active=true; this.setPreferredSize(new Dimension(largura*escala,altura*escala)); ui = new UI(); entities = new ArrayList <GameObjects>(); monstros = new ArrayList <Monstro>(); shoots = new ArrayList <Shoot>(); spritesheet = new SpriteSheet("/GameObjects.png"); player = new Jogador(0,0,16,16,spritesheet.getSprite(32, 0, 16, 16)); entities.add(player); world = new World("/level1.png"); menu = new Menu(); } public static void main(String[] args) { Sound.music.loop(); Game game = new Game(); JFrame frame = new JFrame("Kill Rush"); frame.setResizable(false); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.add(game); frame.pack(); frame.setVisible(true); new Thread(game).start(); } public void tick() { if(gameState == "NORMAL") { this.restartGame=false; for(int i = 0 ; i < entities.size(); i++){ GameObjects e = entities.get(i); e.tick(); } for(int i = 0; i<shoots.size();i++) { shoots.get(i).tick(); } if(monstros.size() == 0) { CUR_LEVEL++; if(CUR_LEVEL>MAX_LEVEL) { CUR_LEVEL=1; } String newWorld = "level"+CUR_LEVEL+".png"; World.restartGame(newWorld); } }else if(gameState == "GAME_OVER") { this.framesGameOver++; if(this.framesGameOver == 30) { this.framesGameOver = 0; if(this.showMessageGameOver) { this.showMessageGameOver = false; }else { this.showMessageGameOver = true; } if(restartGame) { this.restartGame = false; gameState = "NORMAL"; CUR_LEVEL=1; String newWorld = "level"+CUR_LEVEL+".png"; World.restartGame(newWorld); } } }else if(gameState == "MENU") { menu.tick(); } } public void render() { BufferStrategy bs = this.getBufferStrategy(); if(bs == null) { this.createBufferStrategy(3); return; } Graphics g = layer.getGraphics(); g.setColor(new Color(0,0,0)); g.fillRect(0,0,largura,altura); world.render(g); for(int i = 0 ; i < entities.size(); i++){ GameObjects e = entities.get(i); e.render(g); } for(int i = 0; i<shoots.size();i++) { shoots.get(i).render(g); } ui.render(g); g = bs.getDrawGraphics(); g.drawImage(layer, 0, 0, largura*escala, altura*escala,null); g.setFont(new Font("arial",Font.BOLD,20)); g.setColor(Color.yellow); g.drawString("Munição: "+player.ammo, 10, 100); if(gameState == "GAME_OVER") { Graphics2D g2 = (Graphics2D) g; g2.setColor(new Color(0,0,0,200)); g2.fillRect(0, 0, largura*escala, altura*escala); g.setFont(new Font("arial",Font.BOLD,50)); g.setColor(Color.red); g.drawString("Game Over", (largura*escala)/2 - 120, (altura*escala)/2); g.setFont(new Font("arial",Font.BOLD,15)); if(showMessageGameOver) { g.drawString(">PRESSIONE ENTER PARA REINICIAR<", (largura*escala)/2 - 130, (altura*escala)/2 + 30); } }else if(gameState == "MENU") { menu.render(g); } bs.show(); } public void run(){ long lastTime = System.nanoTime(); double fps = 60.0; double ns = 1000000000/fps; double delta=0; requestFocus(); while(active) { long now = System.nanoTime(); delta+= (now - lastTime) / ns; lastTime=now; if(delta>=1) { tick(); render(); delta--; } } } public void keyTyped(KeyEvent e) { } public void keyPressed(KeyEvent e) { if(e.getKeyCode() == KeyEvent.VK_D) { player.direita = true; }else if(e.getKeyCode() == KeyEvent.VK_A) { player.esquerda = true; } if(e.getKeyCode() == KeyEvent.VK_W) { player.cima = true; if(gameState == "MENU") { menu.cima = true; } }else if(e.getKeyCode() == KeyEvent.VK_S) { player.baixo = true; if(gameState == "MENU") { menu.baixo = true; } } if(e.getKeyCode() == KeyEvent.VK_K) { player.bulletShoots = true; } if(e.getKeyCode() == KeyEvent.VK_ENTER) { this.restartGame = true; if(gameState == "MENU"){ menu.enter = true; } } if(e.getKeyCode() == KeyEvent.VK_ESCAPE) { gameState = "MENU"; menu.pause = true; } } public void keyReleased(KeyEvent e) { if(e.getKeyCode() == KeyEvent.VK_D) { player.direita = false; }else if(e.getKeyCode() == KeyEvent.VK_A) { player.esquerda = false; } if(e.getKeyCode() == KeyEvent.VK_W) { player.cima = false; }else if(e.getKeyCode() == KeyEvent.VK_S) { player.baixo = false; } } } <file_sep>/src/com/spardagames/entities/Monstro.java package com.spardagames.entities; import java.awt.Graphics; import java.awt.Rectangle; import java.awt.image.BufferedImage; import com.spardagames.main.Game; import com.spardagames.main.Sound; import com.spardagames.world.Camera; import com.spardagames.world.World; public class Monstro extends GameObjects{ private double speed = 1; private int frames=0, maxFrames = 5, index = 0, maxIndex = 3; private BufferedImage[] paraDireita; private BufferedImage[] paraEsquerda; private int direita_dir=0,esquerda_dir=1; private int dir=direita_dir; private int vida = 10; private boolean damaged = false; private int damageFrames = 2,damageCurrent = 0; public Monstro(int x, int y, int largura, int altura, BufferedImage sprite) { super(x, y, largura, altura, sprite); paraDireita = new BufferedImage[4]; paraEsquerda = new BufferedImage[4]; for(int i=0;i<4;i++) { paraDireita[i] = Game.spritesheet.getSprite(7*16, 16 + (i*16), 16, 16); } for(int i=0;i<4;i++) { paraEsquerda[i] = Game.spritesheet.getSprite(8*16, 16 + (i*16), 16, 16); } } public void tick() { if(collidingWithPlayer() == false) { if((int)x < Game.player.getX() && World.isFree((int)(x+speed), this.getY()) && !isColliding((int)(x+speed), this.getY())) { dir = direita_dir; x+=speed; }else if((int)x > Game.player.getX() && World.isFree((int)(x-speed), this.getY()) && !isColliding((int)(x-speed), this.getY())) { dir = esquerda_dir; x-=speed; }if((int)y < Game.player.getY() && World.isFree(this.getX(), (int)(y+speed)) && !isColliding(this.getX(), (int)(y+speed))) { y+=speed; }else if((int)y > Game.player.getY() && World.isFree(this.getX(), (int)(y-speed)) && !isColliding(this.getX(), (int)(y-speed))) { y-=speed; } frames++; if(frames == maxFrames) { frames=0; index++; if(index > maxIndex) { index = 0; } collidingBullet(); if(vida<=0) { destroySelf(); return; } if(damaged) { this.damageCurrent++; if(this.damageCurrent==this.damageFrames) { this.damageCurrent = 0; this.damaged = false; } } } }else { if(Game.rand.nextInt(100)<10) { Sound.hit.play(); Game.player.vida-=Game.rand.nextInt(3); Game.player.damaged = true; System.out.println("Vida: "+Game.player.vida); } } } public void destroySelf() { Game.monstros.remove(this); Game.entities.remove(this); } public void collidingBullet() { for(int i = 0;i<Game.shoots.size();i++) { GameObjects e = Game.shoots.get(i); if(e instanceof Shoot) { if(GameObjects.Colliding(this, e)) { damaged = true; vida--; Game.shoots.remove(i); return; } } } } public boolean collidingWithPlayer() { Rectangle monstroCurrent = new Rectangle(this.getX(),this.getY(),World.tile_size,World.tile_size); Rectangle player = new Rectangle(Game.player.getX(),Game.player.getY(),16,16); return monstroCurrent.intersects(player); } public boolean isColliding(int xnext, int ynext) { Rectangle monstroCurrent = new Rectangle(xnext,ynext,World.tile_size,World.tile_size); for(int i=0;i<Game.monstros.size(); i++) { Monstro e = Game.monstros.get(i); if(e == this) continue; Rectangle targetMonstro = new Rectangle(e.getX(),e.getY(),World.tile_size,World.tile_size); if(monstroCurrent.intersects(targetMonstro)){ return true; } } return false; } public void render(Graphics g) { if(!damaged) { if(dir == direita_dir) { g.drawImage(paraDireita[index],this.getX() - Camera.x,this.getY() - Camera.y, null); }else if(dir == esquerda_dir) { g.drawImage(paraEsquerda[index],this.getX() - Camera.x,this.getY() - Camera.y, null); } }else { g.drawImage(GameObjects.Monstro_FEEDBACK,this.getX() - Camera.x,this.getY() - Camera.y, null); } } } <file_sep>/src/com/spardagames/world/World.java package com.spardagames.world; import java.awt.Graphics; import java.awt.image.BufferedImage; import java.io.IOException; import java.util.ArrayList; import javax.imageio.ImageIO; import com.spardagames.entities.Monstro; import com.spardagames.entities.Jogador; import com.spardagames.graficos.SpriteSheet; import com.spardagames.entities.Ammo; import com.spardagames.entities.Arma; import com.spardagames.entities.GameObjects; import com.spardagames.entities.Medkit; import com.spardagames.main.Game; public class World { public static Tile[] tiles; public static int largura,altura; public static final int tile_size = 16; public World(String path) { try { BufferedImage map = ImageIO.read(getClass().getResource(path)); int[] pixels = new int[map.getWidth()* map.getHeight()]; largura = map.getWidth(); altura = map.getHeight(); tiles = new Tile[map.getWidth() * map.getHeight()]; map.getRGB(0, 0, map.getWidth(), map.getHeight(), pixels ,0, map.getWidth()); for(int xx=0;xx<map.getWidth();xx++) { for(int yy = 0;yy<map.getHeight();yy++) { int pixelAtual = pixels[xx + (yy*map.getWidth())]; tiles[xx +(yy *largura)] = new FloorTile(xx*16,yy*16,Tile.TILE_FLOOR); if(pixelAtual == 0xFF000000) { //Chão tiles[xx +(yy *largura)] = new FloorTile(xx*16,yy*16,Tile.TILE_FLOOR); }else if(pixelAtual == 0xFFFFFFFF){ //Parede tiles[xx +(yy *largura)] = new WallTile(xx*16,yy*16,Tile.TILE_WALL); }else if(pixelAtual == 0xFF0026FF) { //Player Game.player.setX(xx*16); Game.player.setY(yy*16); } else if(pixelAtual == 0xFFFF0000){ //enemy Monstro en = new Monstro(xx*16,yy*16,16,16,GameObjects.Monstro_EN); Game.entities.add(en); Game.monstros.add(en); }else if(pixelAtual == 0xFF404040) { //arma Game.entities.add(new Arma(xx*16,yy*16,16,16,GameObjects.Arma_EN)); }else if(pixelAtual == 0xFF4CFF00) { //Medkit Medkit kit = new Medkit(xx*16,yy*16,16,16,GameObjects.MedKit_EN); kit.setMask(8, 8, 8, 8); Game.entities.add(kit); }else if(pixelAtual == 0xFFFFF951) { //ammo Game.entities.add(new Ammo(xx*16,yy*16,16,16,GameObjects.Ammo_EN)); } } } } catch (IOException e) { e.printStackTrace(); } } public static boolean isFree(int xnext, int ynext) { int x1 = xnext/tile_size; int y1 = ynext/tile_size; int x2 = (xnext+tile_size-1)/tile_size; int y2 = ynext / tile_size; int x3 = xnext / tile_size; int y3 = (ynext+tile_size-1) / tile_size; int x4 = (xnext+tile_size-1)/tile_size; int y4 = (ynext+tile_size-1) / tile_size; return !((tiles[x1 + (y1 * World.largura)] instanceof WallTile) || (tiles[x2 + (y2 * World.largura)] instanceof WallTile) || (tiles[x3 + (y3 * World.largura)] instanceof WallTile) || (tiles[x4 + (y4 * World.largura)] instanceof WallTile)); } public static void restartGame(String level) { Game.entities.clear(); Game.monstros.clear(); Game.entities = new ArrayList <GameObjects>(); Game.monstros = new ArrayList <Monstro>(); Game.spritesheet = new SpriteSheet("/GameObjects.png"); Game.player = new Jogador(0,0,16,16,Game.spritesheet.getSprite(32, 0, 16, 16)); Game.entities.add(Game.player); Game.world = new World("/"+level); return; } public void render(Graphics g) { int xstart = Camera.x >> 4; int ystart = Camera.y >> 4; int xfinal = xstart + (Game.largura/16); int yfinal = ystart + (Game.altura/16); for(int xx = xstart;xx <= xfinal;xx++) { for(int yy = ystart;yy <= yfinal;yy++) { if(xx<0 || yy<0 || xx>=largura || yy>=altura) { continue; } Tile tile = tiles[xx + (yy*largura)]; tile.render(g); } } } } <file_sep>/src/com/spardagames/main/Menu.java package com.spardagames.main; import java.awt.Color; import java.awt.Font; import java.awt.Graphics; import java.io.BufferedWriter; import java.io.FileWriter; import java.io.IOException; public class Menu { public String[] options = {"New Game", "Load Game", "Quit"}; public int currentOption = 0; public int maxOption = options.length - 1; public boolean cima,baixo,enter,pause = false; public void tick() { if(cima) { cima = false; currentOption--; if(currentOption<0) { currentOption = maxOption; } } if(baixo) { baixo = false; currentOption++; if(currentOption>maxOption) { currentOption = 0; } } if(enter) { enter = false; if(options[currentOption] == "New Game" || options[currentOption] == "Continue") { Game.gameState = "NORMAL"; pause = false; }else if(options[currentOption] == "Quit") { System.exit(1); } } } public static void saveGame(String[] val1, int[] val2, int encode) { BufferedWriter write = null; try { write = new BufferedWriter(new FileWriter("save.txt")); }catch(IOException e) {} for(int i = 0; i<val1.length; i++) { String current = val1[i]; current+=":"; char[] value = Integer.toString(val2[i]).toCharArray(); for(int n = 0; n < value.length; n++) { value[n]+=encode; current+=value[n]; } try { write.write(current); if(i < val1.length - 1) write.newLine(); }catch(IOException e) {} } try { write.flush(); write.close(); }catch(IOException e) {} } public void render(Graphics g) { g.setColor(Color.black); g.fillRect(0, 0, Game.largura*Game.escala, Game.altura*Game.escala); g.setColor(Color.red); g.setFont(new Font("arial", Font.BOLD,36)); g.drawString("Kill Rush", (Game.largura*Game.escala)/2 - 70, (Game.altura*Game.escala)/2-200); g.setColor(Color.white); g.setFont(new Font("arial", Font.BOLD,24)); if(pause == false) g.drawString("New Game", (Game.largura*Game.escala)/2 -60,300); else g.drawString("Continue", (Game.largura*Game.escala)/2 -60,300); g.drawString("Load Game", (Game.largura*Game.escala)/2 -60,340); g.drawString("Quit", (Game.largura*Game.escala)/2 -60,380); if(options[currentOption] == "New Game") { g.drawString(">", (Game.largura*Game.escala)/2 - 90, 300); }else if(options[currentOption] == "Load Game") { g.drawString(">", (Game.largura*Game.escala)/2 - 90, 340); }else if(options[currentOption] == "Quit") { g.drawString(">", (Game.largura*Game.escala)/2 - 90, 380); } } } <file_sep>/src/com/spardagames/entities/Medkit.java package com.spardagames.entities; import java.awt.image.BufferedImage; public class Medkit extends GameObjects { public Medkit(int x, int y, int largura, int altura, BufferedImage sprite) { super(x, y, largura, altura, sprite); } } <file_sep>/src/com/spardagames/entities/Ammo.java package com.spardagames.entities; import java.awt.image.BufferedImage; public class Ammo extends GameObjects{ public Ammo(int x, int y, int largura, int altura, BufferedImage sprite) { super(x, y, largura, altura, sprite); } }
b2f1c01e0af6f3004bae1863ae13c8d80d35a3ba
[ "Java" ]
6
Java
SpardaProgram/KillRush-Game-Projetc
762b49a297c3a76f0edbf0779db9f3a1116f60bf
42d5910d8704725cf8d58a59e1f5ab2484c59f56
refs/heads/master
<repo_name>seanlowjk/duke<file_sep>/src/main/java/duke/parser/DataParser.java package duke.parser; import java.util.Scanner; import duke.command.AddDeadlineTaskCommand; import duke.command.AddEventTaskCommand; import duke.command.AddTagCommand; import duke.command.AddToDoTaskCommand; import duke.command.Command; import duke.command.CompleteTaskCommand; import duke.command.DeleteTaskCommand; import duke.command.EditTaskDateCommand; import duke.command.EditTaskNameCommand; import duke.command.EndCommand; import duke.command.FindTaggedTaskCommand; import duke.command.FindTaskCommand; import duke.command.ListCommandsCommand; import duke.command.ListTaskCommand; import duke.exception.DukeException; import duke.exception.InvalidDeadlineException; import duke.exception.InvalidEditTaskException; import duke.exception.InvalidEventException; import duke.exception.InvalidKeywordException; import duke.exception.InvalidTagException; import duke.exception.InvalidTaskIndexException; import duke.exception.InvalidToDoException; import duke.exception.UnknownCommandException; import duke.task.TaskList; /** * Represents a Data Parser to parse in all user input provided. */ public class DataParser { private Scanner sc; private String input; /** * Constructs a new DataParser to read in the user input. */ public DataParser() { this.sc = new Scanner(System.in); this.input = ""; } /** * To check the user has anymore data left unread. * If there is anymore data left unread, return true. * @return Returns true if there is data left unread. */ public boolean hasAnymoreData() { return sc.hasNextLine(); } /** * Reads the input line. */ public void readInput() { this.input = sc.nextLine(); } /** * Reads the given input line. * @param input The given input line. */ public void readInput(String input) { this.input = input; } /** * Parses the User Input data and returns a Command based on the first word given by the user. * Inputs should start with "bye", "delete", "done" etc. * @return A Command based on the user input. * @throws DukeException If the user input is invalid. */ public Command findTaskCommand() throws DukeException { if (shouldEndParsing()) { return new EndCommand(); } else if (shouldListTasks()) { return new ListTaskCommand(); } else if (shouldCompleteTask()) { return new CompleteTaskCommand(); } else if (shouldDeleteTask()) { return new DeleteTaskCommand(); } else if (shouldAddToDoTask()) { return new AddToDoTaskCommand(); } else if (shouldAddDeadlineTask()) { return new AddDeadlineTaskCommand(); } else if (shouldAddEventTask()) { return new AddEventTaskCommand(); } else if (shouldFindTask()) { return new FindTaskCommand(); } else if (shouldTagTask()) { return new AddTagCommand(); } else if (isNotProperEditCommand()) { throw new UnknownCommandException(); } else if (shouldEditTaskName()) { return new EditTaskNameCommand(); } else if (shouldEditTaskDate()) { return new EditTaskDateCommand(); } else if (shouldFindTaggedTask()) { return new FindTaggedTaskCommand(); } else if (shouldListCommands()) { return new ListCommandsCommand(); } else { throw new UnknownCommandException(); } } /** * Returns the Index of the Task involved from the user input. * @return The Index of the Task. * @throws InvalidTaskIndexException If no index or invalid index is provided. */ public int getTaskIndex() throws InvalidTaskIndexException { String[] parsedData = input.split(" "); if (parsedData.length < 2) { throw new InvalidTaskIndexException(); } else { String index = parsedData[1]; try { Integer.parseInt(index); } catch (Exception e) { throw new InvalidTaskIndexException(); } int taskIndex = Integer.parseInt(index) - 1; return taskIndex; } } /** * Checks if the data given represents a task with no name. * @param data The data provided by the user input. * @return Returns false if the data provided gives a name for the task. */ public boolean isEmptyData(String data) { return data.equals(""); } /** * Checks if the data given does not provide the name to edit the task. * @param data the data provided by the user input. * @return false if the data provided does not give a name to edit the task. */ public boolean isNewNameMissing(String data) { return data.split(" ").length == 1; } /** * Checks if the data given does not provide the date to edit the task. * @param data the data provided by the user input. * @return false if the data provided does not give a date to edit the task. */ public boolean isNewDateMissing(String data) { return data.split(" ").length <= 1; } /** * Checks if the data given does not provide the time to edit the task. * @param data the data provided by the user input. * @return false if the data provided does not give a time to edit the task. */ public boolean isNewTimeMissing(String data) { return data.split(" ").length <= 2; } /** * Checks if the data given represents an empty input or not. * @param data The data provided by the user input. * @return Returns false if the data provided gives a name for the task. */ public boolean isEmptyInput(String data) { return data.equals(""); } /** * Checks if the user has included the "/by" regex to allow parsing of the date for the Deadline Task. * @param data The data provided by the user input. * @return Returns false if the data provided does not contain the "/by" regex. */ public boolean isDeadlineTaskValid(String data) { return data.contains("/by"); } /** * Checks if the user has included the "/att" regex to allow parsing of the date for the Event Task. * @param data The data provided by the user input. * @return Returns false if the data provided does not contain the "/at" regex. */ public boolean isEventTaskValid(String data) { return data.contains("/at"); } /** * Checks if a name is given for the to do task. * @param data the to do data given. * @return if there is a name given. */ private boolean isTodoNameProvided(String[] data) { return data.length >= 2; } private boolean isNotProperEditCommand() { return input.trim().equals("edit"); } /** * Parses the user input to return the name of the ToDo Task. * @return the name of the ToDo Task. * @throws InvalidToDoException If the name of the task is not provided. */ public String[] parseToDoData() throws InvalidToDoException, UnknownCommandException { String[] data = this.input.split(" "); if (!isTodoNameProvided(data)) { throw new InvalidToDoException(); } return data; } /** * Prases the input and returns the index and tag as an array of Strings. * @return an array of Strings providing the index and the tag in this order. * @throws InvalidTagException if no data is provided. */ public String[] parseTagData() throws InvalidTagException { String tagData = input.substring(4).trim(); if (isEmptyData(tagData)) { throw new InvalidTagException("Please provide an index and a tag!"); } return tagData.split(" "); } /** * Parses the edited task data based its name and given index. * @return an array containing the index and the new name of the task. * @throws InvalidEditTaskException if no name or index or invalid index is given. */ public String[] parseEditTaskNameData() throws InvalidEditTaskException { String data = this.input.substring(9).trim(); if (isEmptyInput(data) || isInvalidIndex(data)) { throw new InvalidEditTaskException("Please key in a valid index!"); } else if (isNewNameMissing(data)) { throw new InvalidEditTaskException("Please key in a name!"); } return data.split(" "); } /** * Parses the edited task data based its date and given index. * @return an array containing the index and the new name of the task. * @throws InvalidEditTaskException if no name or index or invalid index is given. */ public String[] parseEditTaskDateData() throws InvalidEditTaskException { String data = this.input.substring(9).trim(); if (isEmptyInput(data) || isInvalidIndex(data)) { throw new InvalidEditTaskException("Please key in a valid index!"); } else if (isNewDateMissing(data)) { throw new InvalidEditTaskException("Please key in a date!"); } else if (isNewTimeMissing(data)) { throw new InvalidEditTaskException("Please key in a time!"); } return data.split(" "); } /** * Checks if the data given is a valid index or not. * @return true if the index is invalid */ private boolean isInvalidIndex(String data) { try { Integer.parseInt(data.split(" ")[0]); } catch (Exception e) { return true; } int index = Integer.parseInt(data.split(" ")[0]); return (index < 1 || index > TaskList.getNumberOfTasks()); } /** * Parses the user input to return the name of the Deadline Task. * @return the name and the date of the Deadline Task in the form of an array. * @throws InvalidDeadlineException If the name or the date of the task is not provided. */ public String[] parseDeadlineData() throws InvalidDeadlineException { String data = this.input.substring(8).trim(); if (isEmptyData(data)) { throw new InvalidDeadlineException("The description of a deadline cannot be empty."); } else if (!isDeadlineTaskValid(data)) { throw new InvalidDeadlineException("Please include the time of a deadline."); } String[] taskData = data.split(" /by "); if (taskData.length == 1) { throw new InvalidDeadlineException("The time of a deadline cannot be empty."); } return taskData; } /** * Parses the user input to return the name of the Event Task. * @return the name and the date of the Event Task in the form of an array. * @throws InvalidEventException If the name or the date of the task is not provided. */ public String[] parseEventDate() throws InvalidEventException { String data = this.input.substring(5).trim(); if (isEmptyData(data)) { throw new InvalidEventException("The description of an event cannot be empty."); } else if (!isEventTaskValid(data)) { throw new InvalidEventException("Please include the time of an event."); } String[] taskData = data.split(" /at "); if (taskData.length == 1) { throw new InvalidEventException("The time of an event cannot be empty."); } return taskData; } /** * Checks if the user has given a keyword to find matching tasks. * @param data the keyword data given. * @return true if there is a keyword given. */ private boolean hasKeyWord(String[] data) { return data.length > 1; } /** * Returns the keyword to start the search of matching tasks. * @return the matching keyword. */ public String findKeyWord() throws InvalidKeywordException { String[] data = this.input.split(" "); if (!hasKeyWord(data)) { throw new InvalidKeywordException(); } if (isEmptyData(data[1])) { throw new InvalidKeywordException(); } return data[1]; } /** * Returns the tag to start the search of matching tasks. * @return the matching tag. */ public String findTag() throws InvalidKeywordException { String[] data = this.input.split(" "); if (!hasKeyWord(data)) { throw new InvalidKeywordException(); } if (isEmptyData(data[1])) { throw new InvalidKeywordException(); } return data[1]; } public boolean shouldEndParsing() { return input.equals("bye"); } /** * Checks if the user input indicates that the tasks should be listed out. * @return Returns true if input is "list". */ public boolean shouldListTasks() { return input.equals("list"); } /** * Checks if the user input wishes to complete a task. * @return Returns true if the input starts with "done". */ public boolean shouldCompleteTask() { return input.split(" ")[0].equals("done"); } /** * Checks if the user wishes to delete a task. * @return True if the input starts with "delete". */ public boolean shouldDeleteTask() { return input.split(" ")[0].equals("delete"); } /** * Checks if the user wishes to add a ToDo Task. * @return True if the input starts with "todo". */ public boolean shouldAddToDoTask() { return input.split(" ")[0].equals("todo"); } /** * Checks if the user wishes to add a Deadline Task. * @return True if the input starts with "deadline". */ public boolean shouldAddDeadlineTask() { return input.split(" ")[0].equals("deadline"); } /** * Checks if the user wishes to add an Event Task. * @return True if the input starts with "event". */ public boolean shouldAddEventTask() { return input.split(" ")[0].equals("event"); } /** * Checks if the user wishes to find a task based on a keyword. * @return True if the input starts with "find". */ public boolean shouldFindTask() { return input.split(" ")[0].equals("find"); } /** * Checks if the user wishes to find a task based on a tag. * @return True if the input starts with "findTag". */ public boolean shouldFindTaggedTask() { return input.split(" ")[0].equals("findTag"); } /** * Checks if the user wishes to tag a task. * @return true if the input starts with "tag". */ public boolean shouldTagTask() { return input.split(" ")[0].equals("tag"); } /** * Checks if the user wishes to edit the task name. * @return true if the input starts with "edit name". */ public boolean shouldEditTaskName() { return input.split(" ")[0].equals("edit") && input.split(" ")[1].equals("name"); } /** * Checks if the user wishes to edit a task date or not. * @return true if the input starts with "edit date". */ public boolean shouldEditTaskDate() { return input.split(" ")[0].equals("edit") && input.split(" ")[1].equals("date"); } /** * Checks if the user wishes to list the commands available. * @return true if the input is "help". */ private boolean shouldListCommands() { return input.equals("help"); } } <file_sep>/src/main/java/duke/exception/UnknownCommandException.java package duke.exception; /** * Represents an Exception that is thrown when the input does not result in the execution of a command. */ public class UnknownCommandException extends DukeException { public String toString() { return "OOPS!!! I'm sorry, but I don't know what that means :-("; } } <file_sep>/gradle.properties # To Fix JAVA_HOME for JDK 11 Compilation for Martin's To Do Helper # org.gradle.java.home=/C:/Program Files/Java/jdk-11.0.4 <file_sep>/src/main/java/duke/exception/DukeException.java package duke.exception; /** * Represents an Exception which is thrown during the running of the Duke Application. */ public class DukeException extends Exception { } <file_sep>/src/main/java/duke/task/ToDoTask.java package duke.task; /** * A Class that represents a Task in which the user wishes to do. */ public class ToDoTask extends Task { /** * Constructs a ToDo Task which sets the default of isCompleted value to false. * @param todo The name of the task. */ public ToDoTask(String todo) { super(todo); } /** * Constructs the name of the todo task. * @param todo the array containing the data for the task name. * @return the task name as a String. */ public static String getName(String[] todo) { String taskName = ""; for (int i = 1; i < todo.length; i++) { if (i > 1) { taskName += " "; } taskName += todo[i]; } return taskName; } /** * Constructs a ToDo Task based on the name and the isComplated value given. * @param todo The name of the task. * @param isCompleted Whether the task is Completed or not. */ public ToDoTask(String todo, boolean isCompleted) { super(todo, isCompleted); } /** * Returns a string representation of the Task. * @return A string representation of the Task. */ public String toString() { if (isCompleted) { return String.format("[T][Y] %s", this.todo); } else { return String.format("[T][N] %s", this.todo); } } } <file_sep>/src/main/java/duke/command/Command.java package duke.command; import java.util.ArrayList; import duke.exception.DukeException; import duke.parser.DataParser; import duke.parser.DateParser; import duke.storage.Storage; import duke.task.TaskList; import duke.ui.Ui; /** * Represents a Command to be executed during the running of the Duke Application. */ public abstract class Command { private boolean isExit; /** * Constructs a new Command where it does not terminate the Duke Application. * @param isExit Represents whether the Application should terminate or not. */ public Command(boolean isExit) { this.isExit = isExit; } /** * Gets all the commands available. * @return a list of all commands available. */ public static ArrayList<Command> getAllCommands() { ArrayList<Command> commands = new ArrayList<>(); commands.add(new AddDeadlineTaskCommand()); commands.add(new AddEventTaskCommand()); commands.add(new AddTagCommand()); commands.add(new AddToDoTaskCommand()); commands.add(new CompleteTaskCommand()); commands.add(new DeleteTaskCommand()); commands.add(new EditTaskDateCommand()); commands.add(new EditTaskNameCommand()); commands.add(new EndCommand()); commands.add(new FindTaggedTaskCommand()); commands.add(new FindTaskCommand()); commands.add(new ListCommandsCommand()); commands.add(new ListTaskCommand()); return commands; } /** * Checks if the command signals the exit of a program or not. * @return whether the exit signal is given or not. */ public boolean checkIfExit() { return this.isExit; } /** * Executes the specific command based on the type of the command. * @param taskList The List of tasks involved. * @param ui The Interface which deals with user input and interaction. * @param storage The storage to load and save task data into the output file. * @param dataParser Parses user and task data. * @param dateParser Parser date data. * @throws DukeException If there is a problem with data processing, loading or saving. */ public abstract void execute(TaskList taskList, Ui ui, Storage storage, DataParser dataParser, DateParser dateParser) throws DukeException; } <file_sep>/src/main/java/duke/parser/TimeChecker.java package duke.parser; /** * Represent a Checker to check the validity of the time provided by the user. */ public class TimeChecker { private int hours; private int minutes; private String timeString; /** * Constructs a Time Checker which parses the hours and minutes , * denoted by the string input. * @param timeData the time input represented as a String. */ public TimeChecker(String timeData) { this.timeString = timeData; this.hours = Integer.parseInt(timeData.substring(0, 2)); this.minutes = Integer.parseInt(timeData.substring(2)); } /** * Main method to check if the time given is valid or not. * @return true if the time given is invalid. */ public boolean containsInvalidTime() { return containsWrongFormat() || containsInvalidHour() || containsInvalidMinutes(); } /** * Checks if the String provided is in the correct format or not. * @return true if the number of characters is less than 4. */ private boolean containsWrongFormat() { return timeString.length() != 4; } /** * Checks if the hour provided is valid or not. * @return true if hour is less than 0 or greater than 24. */ private boolean containsInvalidHour() { return hours < 0 || hours > 24; } /** * Checks if the minute provided is valid or not. * @return true if the minutes are less than 0 or greater than 24. */ private boolean containsInvalidMinutes() { return minutes < 0 || minutes > 59; } } <file_sep>/src/main/java/duke/parser/DateParser.java package duke.parser; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; import duke.exception.InvalidDateInputException; /** * Represents a Date Parser to parse in all String data given into a form readable by the user. */ public class DateParser { private SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yyyy hhmm"); private String input; private Calendar calendar = Calendar.getInstance(); /** * Reads the input and stores it in the parser. * @param input The input provided by the user. */ public void readInput(String input) { this.input = input; } /** * Reads the month (provided an integer) and returns it as a String. * For example, 0 represents January, 1 represents February all the way until 11 represents December. * @param month The integer representation of the month. * @return The String representation of the month. */ public String monthToString(int month) { if (month == 0) { return "January"; } else if (month == 1) { return "February"; } else if (month == 2) { return "March"; } else if (month == 3) { return "April"; } else if (month == 4) { return "May"; } else if (month == 5) { return "June"; } else if (month == 6) { return "July"; } else if (month == 7) { return "August"; } else if (month == 8) { return "September"; } else if (month == 9) { return "October"; } else if (month == 10) { return "November"; } else { return "December"; } } /** * Takes in an array of data which represents the day, month and year of the date. * Following which, checks if the day, month and year are valid. * @param dateData An array of data which contains the day, month and year of the date. * @throws InvalidDateInputException If the day, month or year is invalid. */ private void checkDateData(String[] dateData) throws InvalidDateInputException { InvalidDateInputException error = new InvalidDateInputException("Please key in a valid date in the format:\n " + "dd/MM/yyyy"); DateChecker dateChecker = new DateChecker(dateData); if (dateChecker.containsInvalidDate()) { throw error; } } /** * Takes in a String which represents the hour and the minutes. * Following which, check if the data is valid or not. * @param time A String representation of the time in the format "hhmm". * @throws InvalidDateInputException If the hour or minutes is invalid. */ private void checkTimeData(String time) throws InvalidDateInputException { InvalidDateInputException error = new InvalidDateInputException("Please key in " + "a valid time in the format:\n " + "hhmm"); TimeChecker timeChecker = new TimeChecker(time); if (timeChecker.containsInvalidTime()) { throw error; } } /** * Checks if the Date and Time are valid in general. * This is done by splitting the Date and Time and checking them individually. * @throws InvalidDateInputException IF either the Date of Time is invalid. */ private void checkDateTime() throws InvalidDateInputException { try { String[] dateTime = this.input.split(" "); String[] dateData = dateTime[0].split("/"); checkDateData(dateData); checkTimeData(dateTime[1]); } catch (InvalidDateInputException error) { throw error; } catch (Exception e) { throw new InvalidDateInputException("Please key in the date in this format:\n dd/MM/yyyy hhmm"); } } /** * Converts the time in "hhmm" format into a String. * For example: "1207" is converted to "12:07 pm". * @param hour The hour of the time. * @param minutes The minute of the time. * @param timeInString The String representation of the time in "hhmm" format to determine am or pm. * @return The String representation fot eh time in the format "hh:mm pm" or "hh:mm am". */ private String timeToString(int hour, int minutes, String timeInString) { if (hour > 12) { return String.format("%02d:%02d pm", hour - 12, minutes); } else if (hour > 0 && hour < 12) { return String.format("%02d:%02d am", hour, minutes); } else if (timeInString.substring(0, 2).equals("12")) { return String.format("%02d:%02d pm", hour + 12, minutes); } else { return String.format("%02d:%02d am", hour + 12, minutes); } } /** * Converts the date from "dd/MM/yyyy" into the format "dd of mm yyyy". * @return The date in the format of "dd of mm yyyy". * @throws InvalidDateInputException If the date, month or year is invalid. */ public String convertDateToString() throws InvalidDateInputException { checkDateTime(); try { Date inputParser = formatter.parse(input); calendar.setTime(inputParser); int year = calendar.get(Calendar.YEAR); String month = monthToString(calendar.get(Calendar.MONTH)); int day = calendar.get(Calendar.DAY_OF_MONTH); int hour = calendar.get(Calendar.HOUR_OF_DAY); int minutes = calendar.get(Calendar.MINUTE); return String.format("%02d of %s %d %s", day, month, year, timeToString(hour, minutes, (input.split(" "))[1])); } catch (Exception e) { throw new InvalidDateInputException("Please key in the date in this format:\n dd/MM/yyyy hhmm"); } } } <file_sep>/src/main/java/duke/command/DeleteTaskCommand.java package duke.command; import duke.task.TaskList; import duke.task.Task; import duke.exception.DukeException; import duke.parser.DataParser; import duke.parser.DateParser; import duke.ui.Ui; import duke.storage.Storage; /** * Represents a Command to delete one single task. */ public class DeleteTaskCommand extends Command { /** * Constructs a new Command where it does not terminate the Duke Application. */ public DeleteTaskCommand() { super(false); } /** * Executes the specific command based on the type of the command. * In this case, it deletes a task by retrieving its index and removing it from TaskList. * @param taskList The List of tasks involved. * @param ui The Interface which deals with user input and interaction. * @param storage The storage to load and save task data into the output file. * @param dataParser Parses user and task data. * @param dateParser Parser date data. * @throws DukeException If there is a problem with data processing, loading or saving. */ public void execute(TaskList taskList, Ui ui, Storage storage, DataParser dataParser, DateParser dateParser) throws DukeException { int taskIndex = dataParser.getTaskIndex(); Task deletedTask = taskList.deleteTask(taskIndex); ui.showDeletedTask(deletedTask); storage.save(); } /** * Returns a String representation for user guidance. * @return a String representation for user guidance. */ public String toString() { String helper = "Deletes a task from the list: \n" + "Usage: delete (index)"; return helper; } } <file_sep>/README.md # Duke by [<NAME>](https://github.com/seanlowjk) ![Travis Build](https://travis-ci.org/AY1920S1-CS2103T-F13-2/main.svg?branch=master) [![Codacy Badge](https://api.codacy.com/project/badge/Grade/359a4c25fafb40a08633cec2dcc4074b)](https://www.codacy.com/manual/seanlowjk/duke?utm_source=github.com&amp;utm_medium=referral&amp;utm_content=seanlowjk/duke&amp;utm_campaign=Badge_Grade) Welcome to Duke: Martin's Todo Helper! ![User Interface](docs/Ui.png) ## Prerequisites 1) Have Java installed on your computer. 2) Create a folder called `data` in the same directory in which you save the jar file for the application for data storage and processing. <br/> Do also make sure that there is a `tasks.txt` Text Document file inside the folder! ![Storage Prerequisite](docs/Storage%20Prerequisite.png) ## User Guide To learn more on how to use this application, please head down to our [user guide](https://seanlowjk.github.io/duke/) <file_sep>/src/main/java/duke/exception/InvalidDeadlineException.java package duke.exception; /** * Represents an exception to be thrown when the name or the date of the Deadline Task is not given or valid. */ public class InvalidDeadlineException extends DukeException { public String message; public InvalidDeadlineException(String message) { this.message = message; } public String toString() { return "OOPS!!! " + message; } } <file_sep>/src/main/java/duke/parser/DateChecker.java package duke.parser; /** * Represent a Checker to check the validity of the date provided by the user. */ public class DateChecker { private int year; private int month; private int day; /** * Constructs a new DateChecker based on the date data given. * @param dateData an array containing the year, month and day stores as strings. */ public DateChecker(String[] dateData) { this.day = Integer.parseInt(dateData[0]); this.month = Integer.parseInt(dateData[1]); this.year = Integer.parseInt(dateData[2]); } /** * Main method to check if the date given is invalid or not. * @return true if the date given contains an invalid year, month or day. */ public boolean containsInvalidDate() { return containsInvalidYear() || containsInvalidMonth() || containsInvalidDay() || containsInvalidDayInMonth(); } /** * Checks if the year given is invalid. * @return true if the year given is less than zero. */ private boolean containsInvalidYear() { return year < 0; } /** * Checks if the month given is invalid. * @return true if the month given is less than 0 or greater than 12. */ private boolean containsInvalidMonth() { return month < 0 || month > 12; } /** * Checks if the day given is invalid. * @return true if the day given is less than 0 or greater than 31. */ private boolean containsInvalidDay() { return day < 0 || day > 31; } /** * Checks if the year given is a leap year. * @return true if the year can be divided by 4. */ private boolean isLeapYear() { return year % 4 == 0; } /** * Checks if the day given fits in the month provided. * @return true if the day given is not a part of the month provided. */ private boolean containsInvalidDayInMonth() { if (month == 1 || month == 3 || month == 5 || month == 7 || month == 8 || month == 10 || month == 12) { return day > 31; } else if (month == 2) { if (isLeapYear()) { return day > 29; } else { return day > 28; } } else { return day > 30; } } } <file_sep>/src/main/java/duke/command/AddToDoTaskCommand.java package duke.command; import duke.exception.DukeException; import duke.parser.DataParser; import duke.parser.DateParser; import duke.storage.Storage; import duke.task.TaskList; import duke.ui.Ui; /** * Represents a Command to add a ToDo Task to the list of tasks. */ public class AddToDoTaskCommand extends Command { /** * Constructs a new Command where it does not terminate the Duke Application. */ public AddToDoTaskCommand() { super(false); } /** * Executes the specific command based on the type of the command. * In this case, it adds a new ToDo Task to the TaskList, if there are less than 101 tasks. * @param taskList The List of tasks involved. * @param ui The Interface which deals with user input and interaction. * @param storage The storage to load and save task data into the output file. * @param dataParser Parses user and task data. * @param dateParser Parser date data. * @throws DukeException If there is a problem with data processing, loading or saving. */ public void execute(TaskList taskList, Ui ui, Storage storage, DataParser dataParser, DateParser dateParser) throws DukeException { assert (!TaskList.hasHitTaskLimit()) : "OOPS!!! You can only have up to 100 tasks!"; String[] toDoData = dataParser.parseToDoData(); int taskIndex = taskList.addTodoTask(toDoData); ui.showAddedTask(TaskList.getTask(taskIndex)); storage.save(); } /** * Returns a String representation for user guidance. * @return a String representation for user guidance. */ public String toString() { String helper = "Adds a todo task: \n" + "Usgae: todo (taskname)"; return helper; } } <file_sep>/src/main/java/duke/exception/InvalidEventException.java package duke.exception; /** * Represents an exception to be thrown when the name or the date of the Event Task is not given or valid. */ public class InvalidEventException extends DukeException { public String message; public InvalidEventException(String message) { this.message = message; } public String toString() { return "OOPS!!! " + message; } }<file_sep>/docs/README.md # User Guide Welcome to Duke: Martin's Todo Helper! ![User Interface](Ui.png) To help you understand this application, there a few things you would need to set up before proceeding with usage. ## Contents Page * [Prerequisites](#prerequisites) * [Features](#features) * [Feature 1: Adding of Tasks](#feature-1-adding-of-tasks) * [Feature 2: Editing of Tasks](#feature-2-editing-of-tasks) * [Feature 3: Completion of Tasks](#feature-3-completion-of-tasks) * [Feature 4: Deletion of Tasks](#feature-4-deletion-of-tasks) * [Feature 5: Tagging of Tasks](#feature-5-tagging-of-tasks) * [Feature 6: Searching of Tasks](#feature-6-searching-of-tasks) * [Feature 7: Listing of Tasks](#feature-7-listing-of-tasks) * [Feature 8: Listing of Commands](#feature-8-listing-of-commands) * [Feature 9: Loading and Saving of Tasks](#feature-9-loading-and-saving-of-tasks) * [Commands](#usage) * [bye](#bye---indicate-the-exit-of-the-application) * [deadline](#deadline---creates-a-new-deadline-task) * [delete](#delete---deletes-a-task-from-the-list-of-tasks) * [done](#done---marks-a-task-as-done) * [edit date](#edit-name---edits-the-name-of-the-task) * [edit name](#edit-name---edits-the-name-of-the-task) * [event](#event---creates-a-new-event-task) * [find](#find---finds-tasks-containing-keywords) * [findTag](#findtag---finds-tasks-containing-the-tag) * [help](#help---provides-the-list-of-commands) * [list](#list---provides-the-list-of-tasks) * [tag](#tag---gives-a-tag-to-a-task) * [todo](#todo---creates-a-new-todo-task) ## Prerequisites 1) Have Java installed on your computer. 2) Create a folder called `data` in the same directory in which you save the jar file for the application for data storage and processing. <br/> Do also make sure that there is a `tasks.txt` Text Document file inside the folder! ![Storage Prerequisite](Storage%20Prerequisite.png) ## Features Here are the following features which can aid you in the usage of this to-do list application. ### Feature 1: Adding of Tasks You are allowed to create the following types of tasks. 1) ToDo Tasks with a name. 2) Deadline Tasks with a name and a specified deadline (time). 3) Event Tasks with a name and a specified time. ### Feature 2: Editing of Tasks You are allowed to edit the following: 1) The name of the task 2) The date and time of the task. (Only applies to deadline and event tasks) ### Feature 3: Completion of Tasks You are allowed to mark tasks as done. ### Feature 4: Deletion of Tasks You are allowed to delete tasks. ### Feature 5: Tagging of Tasks You are allowed to tag tasks for easier reference. ### Feature 6: Searching of Tasks You are allowed to search tasks based on either criteria: 1) A keyword which is found within the task name. 2) The tag of the tasks. ### Feature 7: Listing of Tasks You are allowed to list the tasks you have in the application. ### Feature 8: Listing of Commands You are allowed to list the commands available in the application. ### Feature 9: Loading and Saving of Tasks The tasks processed will be saved automatically if you have your `data` folder in the same subdirectory as your jar file. On restarting the application, the file `data/tasks.txt` will be loaded and processed to load the tasks stored in it. ## Usage These are the following commands to aid you through in the usage of this application. ### `bye` - Indicate the exit of the application Once typed in, you will receive a prompt to leave the application. Following which, press enter to exit the application. Example of usage: `bye` Expected outcome: `Receives a prompt to leave the application` ### `deadline` - Creates a new deadline task After providing the task name and deadline date and time, a new deadline task will be created. Date must be in the format of `dd/mm/yyyy`<br/> Time must be in format of `hhmm` Example of usage: `deadline (taskname) /by (date) (time)` Expected outcome: `Creates a new deadline task based on name and deadline` ### `delete` - Deletes a task from the list of tasks After the providing the task number, the specified task will be deleted as such. The task number is `1-indexed`, so the first task has the index of 1. Example of usage: `delete (index)` Expected outcome: `Deletes the task at the specified index` ### `done` - Marks a task as done After providing the index of the task, the task will be marked as done. The task number is `1-indexed`, so the first task has the index of 1. Example of usage: `done (index)` Expected outcome: `Marks the specified task as done` ### `edit date` - Edits the date of the task After providing the index and the new date, the specified task will have its date changed. The task number is `1-indexed`, so the first task has the index of 1. Date must be in the format of `dd/mm/yyyy`<br/> Time must be in format of `hhmm` Example of usage: `edit date (index) (date) (time` Expected outcome: `Edits the date and time of the task at the specified index` ### `edit name` - Edits the name of the task After providing the index and the new name, the specified task will have its name changed. The task number is `1-indexed`, so the first task has the index of 1. Example of usage: `edit name (index) (name)` Expected outcome: `Edits the name of the task at the specified index` ### `event` - Creates a new event task After providing the task name and event date and time, a new event task will be created. Date must be in the format of `dd/mm/yyyy`<br/> Time must be in format of `hhmm` Example of usage: `event (taskname) /at (date) (time)` Expected outcome: `Creates a new event task based on name and date and time` ### `find` - Finds tasks containing keywords After providing the keyword, a list of tasks will be given which contain the specific keywords. Example of usage: `find (keywords)` Expected outcome: `Returns a list of tasks containing the keywords` ### `findTag` - Finds tasks containing the tag After providing the tag, a list of tasks will be given which contain the specific tag. Example of usage: `findTag (tag)` Expected outcome: `Returns a list of tasks containing the tag` ### `help` - Provides the list of commands On this command, a list of commands will be given. Example of usage: `help` Expected outcome: `Returns a list of commands available` ### `list` - Provides the list of tasks On this command, a list of tasks will be given. Example of usage: `list` Expected outcome: `Returns the list of tasks` ### `tag` - Gives a tag to a task On providing the task number and the tag, the tag will be given to that task. The task number is `1-indexed`, so the first task has the index of 1. Example of usage: `tag (index) (tag)` Expected outcome: `Gives a tag to the specified task` ### `todo` - Creates a new todo task After providing the task name, a new todo task will be created. Example of usage: `todo (taskname)` Expected outcome: `Create a new todo task based on the given name` [Back to Top](#user-guide)
a94b5106c315debb2072eb3786bf45fadd1c4d02
[ "Markdown", "Java", "INI" ]
15
Java
seanlowjk/duke
95553ff84e335425ec8585388b47ca6b18093777
856ada426af2ef1e2f14d7120aa7b4963756fc18
refs/heads/master
<file_sep>package com.chess.gui; import java.awt.Dimension; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JFrame; import javax.swing.JMenu; import javax.swing.JMenuBar; import javax.swing.JMenuItem; public class Table { private final JFrame gameFrame; private static Dimension OUTER_FRAME_DIMENSION = new Dimension(600, 600); public Table(){ this.gameFrame = new JFrame("JChess"); final JMenuBar tableMenuBar = new JMenuBar(); populateMenuBar(tableMenuBar); this.gameFrame.setJMenuBar(tableMenuBar); this.gameFrame.setSize(OUTER_FRAME_DIMENSION); this.gameFrame.setVisible(true); } private void populateMenuBar(final JMenuBar tableMenuBar){ tableMenuBar.add(createFileMenu()); } private JMenu createFileMenu() { final JMenu fileMenu = new JMenu("File"); final JMenuItem openPGN = new JMenuItem("Load PGN File"); openPGN.addActionListener(new ActionListener(){ @Override public void actionPerformed(ActionEvent e) { System.out.println("Open that pgn file"); } }); fileMenu.add(openPGN); return fileMenu; } }
1d68920bccf30c4b4c850eee7de95e7b7f66f4f2
[ "Java" ]
1
Java
SmirdenByben/Chess
2c16a7a8ec102d6e2ce10645efeadd02c9968e35
79a3309b0b7809b28ffc72ef77118cdebe7eabd5
refs/heads/master
<repo_name>antoiner77/caddy-ansible<file_sep>/Vagrantfile # -*- mode: ruby -*- # vi: set ft=ruby : Vagrant.configure(2) do |config| config.vm.define "jessie" do |jessie| jessie.vm.box = "debian/jessie64" end config.vm.define "precise" do |precise| precise.vm.box = "bento/ubuntu-12.04" end config.vm.define "trusty" do |trusty| trusty.vm.box = "bento/ubuntu-14.04" end config.vm.define "xenial" do |xenial| xenial.vm.box = "bento/ubuntu-16.04" end config.vm.define "centos7" do |centos7| centos7.vm.box = "bento/centos-7.3" end config.vm.define "fedora22" do |fedora22| fedora22.vm.box = "bento/fedora-22" end config.vm.provision "ansible" do |ansible| ansible.playbook = 'tests/playbook.yml' end $script = <<SCRIPT # curl localhost and get the http response code while ! curl -Is localhost:2020 -o /dev/null; do sleep 1 && echo -n . done http_code=$(curl --silent --head --output /dev/null -w '%{http_code}' localhost:2020) case $http_code in 200|404) echo "$http_code | Server running" ;; 000) echo "$http_code | Server not accessible!" >&2 ;; *) echo "$http_code | Unknown http response code!" >&2 ;; esac SCRIPT # Fix 'stdin: is not a tty' error config.ssh.pty = true config.vm.provision :shell, inline: $script config.vm.synced_folder ".", "/vagrant", disabled: true end <file_sep>/.travis/images.sh #!/bin/bash images=$(cat << 'IMAGES' centos-molecule:7 debian-molecule:8 debian-molecule:9 fedora-molecule:27 ubuntu-molecule:16.04 ubuntu-molecule:18.04 IMAGES ) for i in ${images} ; do docker pull paulfantom/$i & done wait <file_sep>/tests/test_default.py from testinfra.utils.ansible_runner import AnsibleRunner testinfra_hosts = AnsibleRunner('.molecule/ansible_inventory').get_hosts('all') def test_files(host): dirs = [ "/etc/caddy", "/var/log/caddy" ] for dir in dirs: d = host.file(dir) assert d.exists assert d.is_directory def test_packages(host): pkgs = [ "git" ] for p in pkgs: assert host.package(p).is_installed def test_service(host): s = host.service("caddy") assert s.is_enabled assert s.is_running def test_socket(host): sockets = [ "tcp://127.0.0.1:2020" ] for socket in sockets: s = host.socket(socket) assert s.is_listening <file_sep>/README.md [![Build Status](https://travis-ci.org/antoiner77/caddy-ansible.svg?branch=master)](https://travis-ci.org/antoiner77/caddy-ansible) [![Galaxy Role](https://img.shields.io/badge/ansible--galaxy-caddy-blue.svg)](https://galaxy.ansible.com/antoiner77/caddy/) *This project has moved to https://github.com/caddy-ansible/caddy-ansible* Caddy Ansible Role ========= This role installs and configures the caddy web server. The user can specify any http configuration parameters they wish to apply their site. Any number of sites can be added with configurations of your choice. Dependencies ------------ None Role Variables -------------- **The [Caddyfile](https://caddyserver.com/docs/caddyfile)** (notice the pipe)<br> default: ``` caddy_config: | localhost:2020 gzip # tls <EMAIL> root /var/www git github.com/antoiner77/caddy-ansible ``` If you wish to use a template for the config you can do this: ``` caddy_config: "{{ lookup('template', 'templates/Caddyfile.j2') }}" ``` **The type of license to use**<br> default: ``` caddy_license: personal ``` If you set the license type to `commercial` then you should also specify (replacing the dummy values with your real ones): ``` caddy_license_account_id: YOUR_ACCOUNT_ID caddy_license_api_key: YOUR_API_KEY ``` **Auto update Caddy?**<br> default: ``` caddy_update: yes ``` **Features that can be added to core:** http.authz, http.awses, http.awslambda, http.cache, http.cgi, http.cors, http.datadog, http.expires, http.filebrowser, http.filter, http.forwardproxy, http.git, http.gopkg, http.grpc, http.hugo, http.ipfilter, http.jekyll, http.jwt, http.locale, http.login, http.mailout, http.minify, http.nobots, http.prometheus, http.proxyprotocol, http.ratelimit, http.realip, http.reauth, http.restic, http.upload, http.webdav, dns, net, hook.service, tls.dns.azure, tls.dns.cloudflare, tls.dns.digitalocean, tls.dns.dnsimple, tls.dns.dnspod, tls.dns.dyn, tls.dns.exoscale, tls.dns.gandi, tls.dns.googlecloud, tls.dns.linode, tls.dns.namecheap, tls.dns.ovh, tls.dns.rackspace, tls.dns.rfc2136, tls.dns.route53, tls.dns.vultr Changing this variable will reinstall Caddy with the new features if `caddy_update` is enabled<br> default: ``` caddy_features: http.git ``` **Use `setcap` for allowing Caddy to open a low port (e.g. 80, 443)?**<br> default: ``` caddy_setcap: yes ``` **Verify the PGP signature on download?**<br> ``` caddy_pgp_verify_signatures: no ``` **Use systemd capabilities controls**<br> default: ``` caddy_systemd_capabilities_enabled: False caddy_systemd_capabilities: "CAP_NET_BIND_SERVICE" ``` NOTE: This feature requires systemd v229 or newer and might be needed in addition to `caddy_setcap: yes`. Supported: * Debian 9 (stretch) * Fedora 25 * Ubuntu 16.04 (xenial) RHEL/CentOS has no release that supports systemd capability controls at this time. **Add additional environment variables**<br> Add environment variables to the systemd script ``` caddy_environment_variables: FOO: bar SECONDVAR: spam ``` **Use additional cli arguments**<br> default: ``` caddy_additional_args: "" ``` Example for Letsencrypt staging: ``` caddy_additional_args: "-ca https://acme-staging.api.letsencrypt.org/directory" ``` Example Playbooks ---------------- ``` --- - hosts: all roles: - role: caddy-ansible caddy_config: | localhost:2020 gzip tls <EMAIL> root /var/www git github.com/antoiner77/caddy-ansible ``` Example with Cloudflare DNS for TLS ``` --- - hosts: all roles: - role: caddy-ansible caddy_features: tls.dns.cloudflare caddy_environment_variables: CLOUDFLARE_EMAIL: <EMAIL> CLOUDFLARE_API_KEY: 1234567890 caddy_config: | yourcloudflareddomain.com { tls { dns cloudflare } gzip root /var/www git github.com/antoiner77/caddy-ansible } ``` Debugging --------- If the service fails to start you can figure out why by looking at the output of Caddy.<br> ```console systemctl status caddy -l ``` If something doesn't seem right, open an issue! Contributing ------------ Pull requests are welcome. Please test your changes beforehand with vagrant: ``` vagrant up vagrant provision (since it already provisioned there should be no changes here) vagrant destroy ```
14ea3b9ea3b24973eeb66ea8a0382df79cbfb6fc
[ "Markdown", "Python", "Ruby", "Shell" ]
4
Ruby
antoiner77/caddy-ansible
6412a650f08254f1348ea8795febbf2a40998e69
68405b40b73ce429d485b9ccabb0af6a135cb1c3
refs/heads/master
<repo_name>Binett/BudgetCalculator<file_sep>/BudgetCalculatorTests1/Helpers/WriteToFileTests.cs using Microsoft.VisualStudio.TestTools.UnitTesting; using System.IO; namespace BudgetCalculator.Helpers.Tests { [TestClass()] public class WriteToFileTests { [TestMethod()] public void WriteStringToFileTest_CallsWriteTofileWithString_ShouldWriteToFile() { var fileTxt = new WriteToFile(); const string test = "Hello"; fileTxt.WriteStringToFile("error", test); var expected = File.ReadAllLines(fileTxt.PathAndFileName); Assert.AreEqual(expected[0], test); } [TestMethod()] public void WriteStringToFileTest_CallsWriteToFileWithEmptyString_ShouldNotWriteToFile() { var fileTxt = new WriteToFile(); string test = string.Empty; fileTxt.WriteStringToFile(fileTxt.PathAndFileName, test); Assert.AreEqual(false, File.Exists(fileTxt.PathAndFileName)); } [TestMethod()] public void WriteStringToFileTest_CallsWriteToFileWithNullText_ShouldNotWriteToFile() { var fileTxt = new WriteToFile(); string test = null; fileTxt.WriteStringToFile(fileTxt.PathAndFileName, test); Assert.AreEqual(false, File.Exists(fileTxt.PathAndFileName)); } [TestMethod()] public void WriteStringToFileTest_CallsWriteToFileWithNullName_ShouldNotWriteToFile() { var fileTxt = new WriteToFile(); string test = "Error"; fileTxt.WriteStringToFile(null, test); Assert.AreEqual(false, File.Exists(null)); } } }<file_sep>/BudgetCalculator/Controllers/EconomicController.cs using BudgetCalculator.Helpers; using BudgetCalculator.Models; using System; using System.Collections.Generic; using System.Diagnostics; namespace BudgetCalculator.Controllers { /// <summary> /// The controller of EconomicObject objects. /// </summary> public class EconomicController { #region Public Methods /// <summary> /// Constructor for EconomicController /// instanciate a new list of EconomicObject /// </summary> public EconomicController() { GetList = new List<EconomicObject>(); } public List<EconomicObject> GetList { get; } /// <summary> /// Add Economic object to EconomicObjectList /// </summary> /// <param name="name">string name</param> /// <param name="type">Type of object</param> /// <param name="amount">double amount</param> /// <returns>bool true or false</returns> public bool AddEconomicObjectToList(string name, EconomicType type, double amount) { if (IsValidString(name) && IsAmountMoreThanZero(amount)) { if (!DoListContainName(name)) { GetList.Add(new EconomicObject { Name = name, Type = type, Amount = amount, }); return true; } else { string errormsg = $"{this} String name does already exist in economic object list"; Debug.WriteLine(errormsg); ErrorLogger.Add(errormsg); return false; } } return false; } /// <summary> /// Remove an economic object from EconomicObjectList /// </summary> /// <param name="name">string name</param> /// <returns>bool true or false</returns> public bool RemoveEconomicObjectFromList(string name) { if (IsValidString(name)) { if (DoListContainName(name)) { GetList.RemoveAll(x => x.Name == name); return true; } return false; } else { return false; } } /// <summary> /// Updates an economic objects amount /// </summary> /// <param name="name">string name</param> /// <param name="newAmount">double new amount</param> /// <returns>bool true if success</returns> public bool UpdateEconomicObjectAmount(string name, double newAmount) { if (IsValidString(name) && IsAmountMoreThanZero(newAmount) && !IsAmountMoreThanMaxValue(newAmount)) { if (DoListContainName(name)) { foreach (var ecoObj in GetList) { if (ecoObj.Name.Contains(name)) { ecoObj.Amount = newAmount; return true; } } } else { string errormsg = $"{this} Name Does not exist in the list, therefore cannot update."; Debug.WriteLine(errormsg); ErrorLogger.Add(errormsg); return false; } } return false; } /// <summary> /// Updates an economic object name if name /// dosent exist /// </summary> /// <param name="oldName">string old name</param> /// <param name="newName">string new name</param> /// <returns>bool true if success else false</returns> public bool UpdateEconomicObjectName(string oldName, string newName) { if (IsValidString(oldName) && IsValidString(newName)) { foreach (var ecoObj in GetList) { if (ecoObj.Name.Contains(oldName)) { ecoObj.Name = newName; return true; } } string errormsg = $"{this} String name does not exist in economic object list"; Debug.WriteLine(errormsg); ErrorLogger.Add(errormsg); return false; } else { return false; } } #endregion Public Methods #region Private Methods /// <summary> /// Checks if incoming value is more than double.MaxValue /// </summary> /// <param name="amount"></param> /// <returns>True if value is over double.MaxValue</returns> private bool IsAmountMoreThanMaxValue(double amount) { if (amount > double.MaxValue) { return true; } else { string errormsg = $"{this} Amount was more than double.MaxValue"; Debug.WriteLine(errormsg); ErrorLogger.Add(errormsg); return false; } } /// <summary> /// Checks so the string name dosent contain /// null, string empty and string whitespace /// </summary> /// <param name="check">string check</param> /// <returns>bool if success</returns> private bool IsValidString(string check) { string errormsg; if (!IsStringNull(check)) { if (!IsStringEmpty(check)) { if (!IsStringPreWhitespace(check)) { return true; } else { errormsg = $"{this} String name had a whitespace as first character"; Debug.WriteLine(errormsg); ErrorLogger.Add(errormsg); return false; } } else { errormsg = $"{this} String name was empty"; Debug.WriteLine(errormsg); ErrorLogger.Add(errormsg); return false; } } else { errormsg = $"{this} String name was null"; Debug.WriteLine(errormsg); ErrorLogger.Add(errormsg); return false; } } /// <summary> /// Checks if string is null /// </summary> /// <param name="check">string check</param> /// <returns>if string is null return false</returns> private static bool IsStringNull(string check) { return check == null; } /// <summary> /// Checks if string is Empty /// </summary> /// <param name="check">string check</param> /// <returns>if string is empty return false</returns> private static bool IsStringEmpty(string check) { return check.Length == 0; } /// <summary> /// Checks if string is starts with whitespace /// </summary> /// <param name="check">string check</param> /// <returns>if string starts with whitespace return false</returns> private static bool IsStringPreWhitespace(string check) { return check[0] == ' '; } /// <summary> /// Checks if objects amount is greater than 0 /// </summary> /// <param name="amount">double amount</param> /// <returns>If double amount is greater than 0 return true</returns> private bool IsAmountMoreThanZero(double amount) { if (amount > 0) { return true; } else { string errormsg = $"{this} Amount was less than zero"; Debug.WriteLine(errormsg); ErrorLogger.Add(errormsg); return false; } } /// <summary> /// Checks if objects name already exists /// </summary> /// <param name="name">string name</param> /// <returns>bool true if name dosent exists</returns> private bool DoListContainName(string name) { foreach (var ecoObj in GetList) { if (ecoObj.Name.Contains(name)) { return true; } } return false; } #endregion Private Methods } }<file_sep>/BudgetCalculator/Models/EconomicObject.cs namespace BudgetCalculator.Models { /// <summary> /// A DTO of economic objects /// </summary> public class EconomicObject { public EconomicType Type { get; set; } public string Name { get; set; } public double Amount { get; set; } } }<file_sep>/BudgetCalculator/BudgetReport.cs using BudgetCalculator.Controllers; using BudgetCalculator.Models; using BudgetCalculator.Helpers; using System.Collections.Generic; using System.Diagnostics; namespace BudgetCalculator { /// <summary> /// Functions as a POCO, using the calculatorclass in it self. /// </summary> public class BudgetReport { public double TotalIncome { get; } public double TotalExpenses { get; } public double TotalMoneyForSavings { get; } public List<EconomicObject> PaidExpenses { get; } public List<EconomicObject> UnpaidExpenses { get; } public double Balance { get; } private readonly Calculator calc; public EconomicController ecoController; /// <summary> /// Constructor initializes all necessary objects which the class needs. Must have an economic object to function. /// </summary> /// <param name="_ecoController"></param> public BudgetReport(EconomicController _ecoController) { if (_ecoController != null) { ecoController = _ecoController; calc = new Calculator(ecoController); TotalIncome = calc.GetTotalIncome(); TotalExpenses = calc.GetTotalExpenses(); TotalMoneyForSavings = calc.GetTotalMoneyForSaving(); Balance = calc.GetRemainingBalance(out List<EconomicObject> paidExpenses, out List<EconomicObject> unpayedExpenses); PaidExpenses = paidExpenses; UnpaidExpenses = unpayedExpenses; } else { Debug.WriteLine("ecocontroller was null"); ErrorLogger.Add("Ecocontroller was null when instantiating budgetreport object"); } } /// <summary> /// Collect all calculated data from calculator to a string. /// </summary>O /// <param name="ecoController"></param> /// <returns>A string of all calculated data.</returns> public string GetCalculatedDataToString() { List<string> listOfPaidExpenses = new(UnWrapExpenses(PaidExpenses)); List<string> listOfUnpaidExpenses = new(UnWrapExpenses(UnpaidExpenses)); return $"Total Income: {TotalIncome}\n" + $"Total Expenses: {TotalExpenses}\n" + $"Total Saving: {TotalMoneyForSavings}\n" + $"Cash: {Balance}\n\n" + $"Paid expenses:\n{GetStringFromList(listOfPaidExpenses)}\n" + $"Unpaid expenses:\n{GetStringFromList(listOfUnpaidExpenses)}\n"; } /// <summary> /// Converts List of economic objects of certain type to string list /// </summary> /// <param name="list"></param> /// <returns>List of string</returns> private static List<string> UnWrapExpenses(List<EconomicObject> list) { List<string> listToSend = new(); if (list != null) { foreach (var exp in list) { if (exp.Type == EconomicType.Saving) { listToSend.Add($"{exp.Name} Amount: {exp.Amount * 100} Percent\n"); } else { listToSend.Add($"{exp.Name} Amount: {exp.Amount}\n"); } } } return listToSend; } /// <summary> /// Set up one single string from a list of string /// </summary> /// <param name="list"></param> /// <returns></returns> private static string GetStringFromList(List<string> list) { string dataTxt = string.Empty; if (list != null) { foreach (var s in list) { dataTxt += s; } if (dataTxt?.Length == 0) { return "None\n"; } } return dataTxt; } } }<file_sep>/BudgetCalculatorTests1/Seeder/TestSeeder.cs using BudgetCalculator.Controllers; using BudgetCalculator.Models; namespace BudgetCalculatorTests1.Seeder { public class TestSeeder { public EconomicController ecoController; public TestSeeder() { ecoController = new EconomicController(); } public void InitList() { ecoController.AddEconomicObjectToList("Salary", EconomicType.Income, 14000); ecoController.AddEconomicObjectToList("Rent", EconomicType.Expense, 2000); ecoController.AddEconomicObjectToList("Subscription", EconomicType.Expense, 99); ecoController.AddEconomicObjectToList("Food", EconomicType.Expense, 1500); ecoController.AddEconomicObjectToList("Savings", EconomicType.Saving, 0.1); } } }<file_sep>/BudgetCalculatorTests1/Helpers/ErrorLoggerTests.cs using BudgetCalculatorTests1.Seeder; using Microsoft.VisualStudio.TestTools.UnitTesting; using System; namespace BudgetCalculator.Helpers.Tests { [TestClass()] public class ErrorLoggerTests { private TestSeeder seeder; [TestInitialize] public void SetUp() { seeder = new TestSeeder(); } [TestMethod()] public void GetSummarizedLogAsStringTest_NoErrors_ShouldReturnNoLogs() { ErrorLogger.GetLogList().Clear(); seeder.InitList(); const string expected = "No Logs"; var actual = ErrorLogger.GetSummarizedLogAsString(); Assert.AreEqual(expected, actual); } [TestMethod()] public void GetSummarizedLogAsStringTest_UpdateEconomicObjectWithEmptyName_ShouldReturnLogMessageStringWasEmpty() { ErrorLogger.GetLogList().Clear(); seeder.InitList(); seeder.ecoController.UpdateEconomicObjectName("Rent", ""); var expected = "1: " + DateTime.Now + " BudgetCalculator.Controllers.EconomicController String name was empty\n"; var actual = ErrorLogger.GetSummarizedLogAsString(); Assert.AreEqual(expected, actual); } [TestMethod()] public void AddTest_AddEconomicObjectWithDoubleMaxValue_ShouldReturnAnErrorInLogList() { ErrorLogger.GetLogList().Clear(); seeder.InitList(); seeder.ecoController.UpdateEconomicObjectAmount("Rent", double.MaxValue); const string expected = "BudgetCalculator.Controllers.EconomicController Amount was more than double.MaxValue"; var actual = ErrorLogger.GetLogList()[0]; Assert.AreEqual(expected, actual); } } }<file_sep>/BudgetCalculatorTests1/BudgetReportTests.cs using BudgetCalculator.Helpers; using BudgetCalculatorTests1.Seeder; using Microsoft.VisualStudio.TestTools.UnitTesting; using System.IO; namespace BudgetCalculator.Tests { [TestClass()] public class BudgetReportTests { private TestSeeder seeder; [TestInitialize] public void SetUp() { seeder = new TestSeeder(); } [TestMethod()] public void GetCalculatedDataToStringTest_SendInEcoController_ReturnsCollectedDataAsString() { seeder.InitList(); BudgetReport report = new(seeder.ecoController); var actual = report.GetCalculatedDataToString().Trim(); WriteToFile writer = new(); //In case file already exists-- writer.WriteStringToFile("test file", report.GetCalculatedDataToString()); File.Delete(writer.PathAndFileName); //-- writer.WriteStringToFile("test file", report.GetCalculatedDataToString()); string expected = File.ReadAllText(writer.PathAndFileName).Trim(); Assert.AreEqual(expected, actual); } [TestMethod()] public void GetCalculatedDataToStringTest_Null_ReturnsEmptyString() { BudgetReport report = new(null); var actual = report.GetCalculatedDataToString().Trim(); WriteToFile writer = new(); //In case file already exists-- writer.WriteStringToFile("test file", report.GetCalculatedDataToString()); File.Delete(writer.PathAndFileName); //-- writer.WriteStringToFile("test file", report.GetCalculatedDataToString()); string expected = File.ReadAllText(writer.PathAndFileName).Trim(); Assert.AreEqual(expected, actual); } } }<file_sep>/TestConsoleEnviorment/Program.cs using System; using BudgetCalculator; using BudgetCalculatorTests1.Seeder; using BudgetCalculator.Controllers; using BudgetCalculator.Helpers; using BudgetCalculator.Models; using BudgetCalculator.Tests; namespace TestConsoleEnviorment { internal static class Program { private static void Main(string[] args) { if (args is null) { throw new ArgumentNullException(nameof(args)); } //Skapa en ecocontroller. EconomicController ecoController = new EconomicController(); //För in data i ecocontrollern ecoController.AddEconomicObjectToList("Giraffe", EconomicType.Saving, 9999.9); ecoController.AddEconomicObjectToList("Income", EconomicType.Income, 5000); ecoController.AddEconomicObjectToList(" ", EconomicType.Expense, double.MaxValue); ecoController.AddEconomicObjectToList(null, EconomicType.Income, -2222.222); //Skapa en rapport med ecocontrollern BudgetReport report = new BudgetReport(ecoController); //Skapa en writer WriteToFile writer = new WriteToFile(); //Skriv errorloggern till fil writer.WriteStringToFile("the error log", ErrorLogger.GetSummarizedLogAsString()); //Ta bort giraffen, för dyr. ecoController.RemoveEconomicObjectFromList("Giraffe"); //Lägg till lite grejjer ecoController.AddEconomicObjectToList("Salary", EconomicType.Income, 14000); ecoController.AddEconomicObjectToList("Rent", EconomicType.Expense, 2000); ecoController.AddEconomicObjectToList("Subscription", EconomicType.Expense, 99); ecoController.AddEconomicObjectToList("Food", EconomicType.Expense, 1500); ecoController.AddEconomicObjectToList("Savings", EconomicType.Saving, 0.1); //Ny rapport report = new BudgetReport(ecoController); //Skicka till consolen Console.WriteLine(report.GetCalculatedDataToString()); //Skriv rapporten till fil writer.WriteStringToFile("Private economy report", report.GetCalculatedDataToString()); } } } <file_sep>/BudgetCalculator/Models/EconomicType.cs namespace BudgetCalculator.Models { public enum EconomicType { Other, Expense, Income, Saving, } }<file_sep>/BudgetCalculator/Helpers/ErrorLogger.cs using System; using System.Collections.Generic; namespace BudgetCalculator.Helpers { /// <summary> /// Static class that contains a list of errors. /// </summary> public static class ErrorLogger { private static readonly List<string> logList = new(); /// <summary> /// Returns the list of errors. /// </summary> /// <returns>A list of string type</returns> public static List<string> GetLogList() { return logList; } /// <summary> /// Returns a summarize of the LogList as a string. /// </summary> /// <returns>String of summarized log errors</returns> public static string GetSummarizedLogAsString() { int counter = 1; string stringToSend = string.Empty; if (logList == null || logList.Count == 0) { return "No Logs"; } foreach (var s in logList) { stringToSend += $"{counter}: {DateTime.Now} {s}\n"; counter++; } return stringToSend; } /// <summary> /// Adds a error to the LogList /// </summary> /// <param name="text"></param> public static void Add(string text) { if (logList.Contains(text)) { return; } logList.Add(text); } } }<file_sep>/BudgetCalculatorTests1/Controllers/EconomicControllerTests.cs using BudgetCalculator.Models; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace BudgetCalculator.Controllers.Tests { [TestClass()] public class EconomicControllerTests { private EconomicController ecoController; [TestInitialize] public void Setup() { ecoController = new EconomicController(); ecoController.AddEconomicObjectToList("Salary", EconomicType.Income, 2000); } [TestMethod()] [DataRow(null, 200, false)] [DataRow("", 200, false)] [DataRow(" ", 200, false)] [DataRow("Salary", -1200, false)] public void AddEconomicObjectToList_Negative_ShouldReturnFalse( string name, double amount, bool expected) { bool actual = ecoController.AddEconomicObjectToList(name, EconomicType.Income, amount); Assert.AreEqual(expected, actual); } [TestMethod()] public void AddEconomicObjectToList_Pass_ShouldReturnTrue() { var actual = ecoController.AddEconomicObjectToList("Salad", EconomicType.Income, 200); const bool expected = true; Assert.AreEqual(expected, actual); } [TestMethod()] public void AddEconomicObjectToList_PassNameThatExist_ShouldReturnFalse() { var actual = ecoController.AddEconomicObjectToList("Salary", EconomicType.Expense, 200); const bool expected = false; Assert.AreEqual(expected, actual); } [TestMethod()] [DataRow(null, false)] [DataRow("", false)] [DataRow(" ", false)] public void RemoveEconomicObjectFromListTest_NameIsEmptyOrNull_ShouldReturnFalse( string name, bool expected) { var actual = ecoController.RemoveEconomicObjectFromList(name); Assert.AreEqual(expected, actual); } [TestMethod()] public void RemoveEconomicObjectFromListTest_Pass_ShouldReturnTrue() { var actual = ecoController.RemoveEconomicObjectFromList("Salary"); const bool expected = true; Assert.AreEqual(expected, actual); } [TestMethod()] [DataRow(null, 200, false)] [DataRow("", 200, false)] [DataRow(" ", 200, false)] [DataRow("Salary", -200, false)] public void UpdateEconomicObjectAmountTest_Negative_ShouldReturnFalse( string name, double amount, bool expected) { var actual = ecoController.UpdateEconomicObjectAmount(name, amount); Assert.AreEqual(expected, actual); } [TestMethod()] public void UpdateEconomicObjectAmountTest_Pass_ShouldReturnTrue() { var actual = ecoController.UpdateEconomicObjectAmount("Salary", 200); const bool expected = true; Assert.AreEqual(expected, actual); } [TestMethod()] [DataRow(null, "Winnings", false)] [DataRow("", "Winnings", false)] [DataRow(" ", "Winnings", false)] [DataRow("Salary", null, false)] [DataRow("Salary", "", false)] [DataRow("Salary", " ", false)] [DataRow("Winnings", "Salary", false)] public void UpdateEconomicObjectNameTest_Negative_ShouldReturnFalse( string oldName, string newName, bool expected) { var actual = ecoController.UpdateEconomicObjectName(oldName, newName); Assert.AreEqual(expected, actual); } [TestMethod()] public void UpdateEconomicObjectNameTest_Pass_ShouldReturnTrue() { var actual = ecoController.UpdateEconomicObjectName("Salary", "Winnings"); const bool expected = true; Assert.AreEqual(expected, actual); } } }<file_sep>/BudgetCalculatorTests1/CalculatorTests.cs using BudgetCalculator; using BudgetCalculator.Models; using BudgetCalculatorTests1.Seeder; using Microsoft.VisualStudio.TestTools.UnitTesting; using System.Collections.Generic; namespace BudgetCalculator.Tests { [TestClass()] public class CalculatorTests { private Calculator calc; private TestSeeder seeder; [TestInitialize] public void Setup() { seeder = new TestSeeder(); } [TestMethod()] public void GetTotalIncomeTest_Pass_ShouldReturnSum_14000() { seeder.InitList(); calc = new Calculator(seeder.ecoController); const int expected = 14000; var actual = calc.GetTotalIncome(); Assert.AreEqual(expected, actual); } [TestMethod()] public void GetTotalIncomeTest_DoubleMaxValue_ShouldReturnZero() { seeder.InitList(); calc = new Calculator(seeder.ecoController); seeder.ecoController.UpdateEconomicObjectAmount("Salary", double.MaxValue); const int expected = 0; var actual = calc.GetTotalIncome(); Assert.AreEqual(expected, actual); } [TestMethod()] public void GetTotalExpenses_PassValidSum_ShouldReturnSum_3599() { seeder.InitList(); calc = new Calculator(seeder.ecoController); const int expected = 3599; var actual = calc.GetTotalExpenses(); Assert.AreEqual(expected, actual); } [TestMethod()] public void GetTotalExpenses_PassDoubleMaxValue_ShouldReturnZero() { seeder.InitList(); calc = new Calculator(seeder.ecoController); seeder.ecoController.UpdateEconomicObjectAmount("Food", double.MaxValue); const int expected = 0; var actual = calc.GetTotalExpenses(); Assert.AreEqual(expected, actual); } [TestMethod()] public void GetTotalSavingTest_PositiveAmount_ShouldReturnSum() { seeder.InitList(); seeder.ecoController.AddEconomicObjectToList("Buffer", EconomicType.Saving, 0.15); calc = new Calculator(seeder.ecoController); const double expected = 0.25; var actual = calc.GetTotalSaving(); Assert.AreEqual(expected, actual); } [TestMethod()] public void GetTotalSavingTest_NegativeAmount_ShouldReturnZero() { seeder.InitList(); seeder.ecoController.AddEconomicObjectToList("Buffer", EconomicType.Saving, -0.15); calc = new Calculator(seeder.ecoController); const double expected = 0.1d; var actual = calc.GetTotalSaving(); Assert.AreEqual(expected, actual); } [TestMethod()] public void GetTotalSavingTest_MaxValue_ShouldReturnZero() { seeder.InitList(); seeder.ecoController.UpdateEconomicObjectAmount("Saving", double.MaxValue); calc = new Calculator(seeder.ecoController); const int expected = 0; var actual = calc.GetTotalSaving(); Assert.AreEqual(expected, actual); } [TestMethod()] public void GetRemainingBalanceTest_SeederList_ShouldReturnSum() { seeder.InitList(); calc = new Calculator(seeder.ecoController); const int expected = 9001; var actual = calc.GetRemainingBalance(out _, out _); Assert.AreEqual(expected, actual); } [TestMethod()] public void GetRemainingBalanceTest_NegativeHighPercentageSavings_ShouldReturnSum() { seeder.InitList(); seeder.ecoController.AddEconomicObjectToList("Fun stuff", EconomicType.Expense, 1000); seeder.ecoController.AddEconomicObjectToList("Motorcycle", EconomicType.Saving, 0.7); calc = new Calculator(seeder.ecoController); const int expected = 9401; var actual = calc.GetRemainingBalance(out _, out _); Assert.AreEqual(expected, actual); } [TestMethod()] public void GetRemainingBalanceTest_NegativeHighValueExpense_ShouldReturnZero() { seeder.InitList(); seeder.ecoController.UpdateEconomicObjectAmount("Salary", 10000); seeder.ecoController.UpdateEconomicObjectAmount("Food", 8500); calc = new Calculator(seeder.ecoController); const int expected = 0; var actual = calc.GetRemainingBalance(out _, out _); Assert.AreEqual(expected, actual); } [TestMethod()] public void GetRemainingBalanceTest_NegativeList_ShouldContain1Unpaid() { seeder.InitList(); seeder.ecoController.AddEconomicObjectToList("Electric bill", EconomicType.Expense, 9001); seeder.ecoController.AddEconomicObjectToList("Fun stuff", EconomicType.Expense, 1000); calc = new Calculator(seeder.ecoController); calc.GetRemainingBalance(out _, out List<EconomicObject> listOfUnpaidExpenses); Assert.AreEqual(1, listOfUnpaidExpenses.Count); } [TestMethod()] public void GetRemainingBalanceTest_PositiveList_ShouldContain5Paid() { seeder.InitList(); seeder.ecoController.AddEconomicObjectToList("Electric bill", EconomicType.Expense, 500); calc = new Calculator(seeder.ecoController); calc.GetRemainingBalance(out List<EconomicObject> listOfPaidExpenses, out _); Assert.AreEqual(5, listOfPaidExpenses.Count); } [TestMethod()] public void GetRemainingBalanceTest_NegativeListSavings_ShouldContain1Unpaid() { seeder.InitList(); seeder.ecoController.AddEconomicObjectToList("Ima buy me some Solar cells", EconomicType.Saving, 0.70); calc = new Calculator(seeder.ecoController); calc.GetRemainingBalance(out _, out List<EconomicObject> listOfUnpaidExpenses); Assert.AreEqual("Ima buy me some Solar cells", listOfUnpaidExpenses[0].Name); } [TestMethod()] public void GetTotalSavingToMoneyTest_PassValue_ShouldReturn_3500() { seeder.InitList(); seeder.ecoController.AddEconomicObjectToList("Buffer", EconomicType.Saving, 0.15); calc = new Calculator(seeder.ecoController); const int expected = 3500; var actual = calc.GetTotalMoneyForSaving(); Assert.AreEqual(expected, actual); } [TestMethod()] public void GetTotalSavingToMoneyTest_NegativeValue_ShouldReturnZero() { seeder.InitList(); seeder.ecoController.UpdateEconomicObjectAmount("Saving", -0.15); calc = new Calculator(seeder.ecoController); const int expected = 1400; var actual = calc.GetTotalMoneyForSaving(); Assert.AreEqual(expected, actual); } [TestMethod()] public void GetTotalSavingToMoneyTest_MaxValue_ShouldReturnZero() { seeder.InitList(); seeder.ecoController.UpdateEconomicObjectAmount("Saving", double.MaxValue); calc = new Calculator(seeder.ecoController); const int expected = 0; var actual = calc.GetTotalMoneyForSaving(); Assert.AreEqual(expected, actual); } [TestMethod()] public void CalculatorTest_Null_ShouldReturnZero() { seeder.InitList(); calc = new Calculator(null); var actual = calc.GetTotalExpenses(); var expected = 0; Assert.AreEqual(expected,actual); } } }<file_sep>/BudgetCalculator/Helpers/WriteToFile.cs using System; using System.Diagnostics; using System.IO; namespace BudgetCalculator.Helpers { /// <summary> /// Class for writing strings to file. /// </summary> public class WriteToFile { private string fileName = "default"; /// <summary> /// Generates file for todays date and sets path to desktop /// </summary> public string PathAndFileName { get { var desktop = Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory); string temp = fileName + ".txt"; return Path.Combine(desktop, DateTime.Now.ToString("yyyy-MM-dd") + temp); } } /// <summary> /// Recieves string txt and writes to file /// </summary> /// <param name="txt">text that should be added to file</param> public void WriteStringToFile(string name, string txt) { if (!string.IsNullOrEmpty(name) && !string.IsNullOrEmpty(txt)) { if (txt != "") { fileName = name; File.AppendAllText(PathAndFileName, txt + "\n"); } else { Debug.WriteLine("Text is empty"); } } else { Debug.WriteLine("String is null or empty"); ErrorLogger.Add("String is null or empty in write to file call to write to string file"); } } } }<file_sep>/BudgetCalculator/Calculator.cs using BudgetCalculator.Controllers; using BudgetCalculator.Helpers; using BudgetCalculator.Models; using System; using System.Collections.Generic; using System.Diagnostics; namespace BudgetCalculator { /// <summary> /// Class is used to calculate income, expenses and savings in varies ways. /// </summary> public class Calculator { private readonly List<EconomicObject> economicObjectList; public Calculator(EconomicController ecoController) { economicObjectList = new List<EconomicObject>(); if(ecoController != null) { economicObjectList = ecoController.GetList; } else { Debug.WriteLine("ecocontroller was null"); ErrorLogger.Add("Ecocontroller was null in the constructor of calcualtor"); } } /// <summary> /// Method that calculates the total sum of incomes /// </summary> /// <returns>the sum of all incomes</returns> public double GetTotalIncome() { double totalIncomes = 0; foreach (var p in economicObjectList) { if (p.Type == EconomicType.Income) { totalIncomes += p.Amount; } } if (totalIncomes < double.MaxValue) { return totalIncomes; } string errormsg = $"{this} GetTotalIncome got double.maxvalue"; Debug.WriteLine(errormsg); ErrorLogger.Add(errormsg); return 0; } /// <summary> /// Returns all expenses from the economic Object list in this calculator class. /// </summary> /// <returns>double as total expenses</returns> public double GetTotalExpenses() { double totalExpenses = 0; foreach (var p in economicObjectList) { if (p.Type == EconomicType.Expense) { totalExpenses += p.Amount; } } if (totalExpenses < double.MaxValue) { return totalExpenses; } string errormsg = $"{this} GetTotalExpenses got double.maxvalue"; Debug.WriteLine(errormsg); ErrorLogger.Add(errormsg); return 0; } /// <summary> /// Method for calculating the sum of all savings in percentage. /// </summary> /// <returns>The sum of all savings if the total percentage is less than 100%</returns> public double GetTotalSaving() { var totalSavingInPercentage = 0d; string errormsg; if (GetTotalIncome() > GetTotalExpenses()) { foreach (var s in economicObjectList) { if (s.Type == EconomicType.Saving) { if (s.Amount < double.MaxValue) { totalSavingInPercentage += s.Amount; } else { errormsg = $"{this} Saving amount was more than double.MaxValue"; Debug.WriteLine(errormsg); ErrorLogger.Add(errormsg); } if(totalSavingInPercentage >= 1) { errormsg = $"{this} Calculated saving value was over 100% of income"; Debug.WriteLine(errormsg); ErrorLogger.Add(errormsg); return 0; } } } return totalSavingInPercentage; } errormsg = $"{this} Less income than expenses"; Debug.WriteLine(errormsg); ErrorLogger.Add(errormsg); return 0; } /// <summary> /// Calculates the remaining balance when all expenses has been made /// </summary> /// <returns>double, remaining balance</returns> public double GetRemainingBalance(out List<EconomicObject> listOfPaidExpenses, out List<EconomicObject> listOfUnpaidExpenses) { listOfPaidExpenses = new(); listOfUnpaidExpenses = new(); GetExpensesLists(ref listOfPaidExpenses, ref listOfUnpaidExpenses); string errormsg; var income = GetTotalIncome(); var expenses = GetTotalExpenses(); var savings = GetTotalMoneyForSaving(); if (income > expenses) { var remainingBalance = income - expenses; if (remainingBalance >= savings) { remainingBalance -= savings; } else { errormsg = $"{this} Saving is not possible"; Debug.WriteLine(errormsg); ErrorLogger.Add(errormsg); } return remainingBalance; } errormsg = $"{this} Expenses exceed income"; Debug.WriteLine(errormsg); ErrorLogger.Add(errormsg); return 0; } /// <summary> /// Convert the total percentage of saving into money. /// </summary> /// <returns>The sum of Saving value.</returns> public double GetTotalMoneyForSaving() => Math.Round(GetTotalIncome() * GetTotalSaving(), 2); #region Private /// <summary> /// Checks when the total income is exceeded and adds seperate object to list when it does not exceed income /// </summary> /// <returns>list of economic objects</returns> private void GetExpensesLists(ref List<EconomicObject> listOfPaidExpenses, ref List<EconomicObject> listOfUnpaidExpenses) { var income = GetTotalIncome(); var temp = income; foreach(var obj in economicObjectList) { if(obj.Type == EconomicType.Expense) { if(obj.Amount <= income) { income -= obj.Amount; listOfPaidExpenses.Add(obj); } else { listOfUnpaidExpenses.Add(obj); } } else if (obj.Type == EconomicType.Saving) { if(obj.Amount * temp <= income) { income -= obj.Amount * temp; listOfPaidExpenses.Add(obj); } else { listOfUnpaidExpenses.Add(obj); } } } } #endregion Private } }
3f63c3ec15ac6d0430233f23622ca188e8280504
[ "C#" ]
14
C#
Binett/BudgetCalculator
b29ae39301269369cde8dcaf2898512286d7708c
35e8ac385dce98317bdeb8647382a6c77ff38ce1
refs/heads/master
<file_sep># Go go学习笔记 <file_sep>package main import ( "fmt" "testing" ) //单元测试 方法名要大写Test func TestFibonacciCreation(t *testing.T) { //变量声明 自动推断 没有使用的变量会报错 var ( a = 1 b = 1 ) t.Log(a) //for循环 for i := 1; i < 5; i++ { t.Log(b) temp := a a = b b = temp + a } fmt.Println() } func TestChange(t *testing.T) { a := 1 b := 2 t.Log(a, b) //temp:=a //a=b //b=temp a, b = b, a t.Log(a, b) } //快速设置连续的值 func TestConst(t *testing.T) { const ( Monday = iota + 1 TuesDay Wednesday ) t.Log(Monday, TuesDay, Wednesday) } func TestConst1(t *testing.T) { const ( Readable = 1 << iota Writable Executable ) //0111 a := 7 t.Log(a&Readable == Readable, a&Writable == Writable, a&Executable == Executable) } <file_sep>`基础学习` ``` go 不允许隐式类型转换 变量定义方式 常量定义方式 快速数据交换 ```
df005ede91c591ca8243be547f2a3eaef7608fce
[ "Markdown", "Go" ]
3
Markdown
Jasmine-Ya/Go
4788446b1f14c1ae7c7bb49f9e17ee941411d3e6
ecef177cf9713996e54e22f4a5027895ab8dbcc2
refs/heads/master
<file_sep>/* robot-charts is a web application that runs analyses on competitive robotics competitions in real time. The rankings system is based on the Elo rankings system originally designed for rankings competitive chess players. */ package main import ( "fmt" ) // Main entry point for the application. func main() { fmt.Println("Starting server.") } <file_sep># robot-charts Comparative rankings and analysis for robotics competitions. robot-charts is a web application that runs analyses on competitive robotics competitions in real time. The rankings system is based on the Elo rankings system originally designed for rankings competitive chess players. <file_sep>package main import ( "math" "testing" ) const DIFFERENCE float64 = 0.000001 func floatEquals(a, b float64) bool { return math.Abs(a-b) < DIFFERENCE } func TestWinProbability(t *testing.T) { t.Log("Testing probability with two even players") if probability := winProbability(1000, 1000); probability != 0.5 { t.Errorf("Expected 0.5, found %f instead.", probability) } t.Log("Testing probability with players 400 points apart") if probability := winProbability(1400, 1000); !floatEquals(probability, 0.909090909) { t.Errorf("Expected 0.9090909, found %f instead.", probability) } t.Log("Testing probability with players 190 points apart") if probability := winProbability(1190, 1000); !floatEquals(probability, 0.749083) { t.Errorf("Expected 0.749083, found %f instead.", probability) } if probability := winProbability(1000, 1400); !floatEquals(probability, 0.09090909) { t.Errorf("Expected 0.09090909, found %f instead.", probability) } } func TestRatingChange(t *testing.T) { // Test for wins t.Log("Testing change in rating with even players, a win and kMod=1") if change := ratingChange(1000, 1000, 1.0, 1); change != K/2 { t.Errorf("Expected %d, found %d instead.", K/2, change) } t.Log("Testing change in rating with even players, a win and kMod=2") if change := ratingChange(1000, 1000, 1.0, 2); change != K { t.Errorf("Expected %d, found %d instead.", K, change) } t.Log("Testing change in rating with 190 difference between players, a win and kMod=1") if change := ratingChange(1190, 1000, 1.0, 1); change != K/4 { t.Errorf("Expected %d, found %d instead.", K/4, change) } t.Log("Testing change in rating with 190 difference between players, a win and kMod=2") if change := ratingChange(1190, 1000, 1.0, 2); change != K/2 { t.Errorf("Expected %d, found %d instead.", K/2, change) } t.Log("Testing change in rating with even players, a win and kMod=1") if change := ratingChange(1000, 1000, 1.0, 1); change != K/2 { t.Errorf("Expected %d, found %d instead.", K/2, change) } // Test for ties t.Log("Testing change in rating with even players, a tie and kMod=1") if change := ratingChange(1000, 1000, 0.5, 1); change != 0 { t.Errorf("Expected %d, found %d instead.", 0, change) } t.Log("Testing change in rating with even players, a tie and kMod=0") if change := ratingChange(1000, 1000, 0.5, 0); change != 0 { t.Errorf("Expected %d, found %d instead.", 0, change) } t.Log("Testing change in rating with even players, a tie and kMod=2") if change := ratingChange(1000, 1000, 0.5, 2); change != 0 { t.Errorf("Expected %d, found %d instead.", 0, change) } // Test for losses t.Log("Testing change in rating with even players, a loss and kMod=1") if change := ratingChange(1000, 1000, 0.0, 1); change != -K/2 { t.Errorf("Expected %d, found %d instead.", -K/2, change) } t.Log("Testing change in rating with a 191 difference between players, a loss and kMod=1") if change := ratingChange(1191, 1000, 0.0, 1); change != -3*K/4 { t.Errorf("Expected %d, found %d instead.", -3*K/4, change) } } <file_sep>package main import ( "math" ) const ( MIN_MATCHES = 8 DEFAULT_RATING = 1000 K = 12 CARRYOVER = 65 WIN = 1.0 TIE = 0.5 LOSS = 0.0 ) // winProbability calculates the probability of one player winnings // against another player on from a scale running from zero to one. // Two teams with the same rating will have a 50% probablity of // winning for both teams. In such a case, the function will return // 0.5 which is equivalent to 50%. func winProbability(player, opponent int) float64 { return 1 / (1 + math.Pow(10.0, float64(opponent-player)/400)) } // ratingChange calculates the appropriate chnage to the elo scores // after a match. kMod is a modifier for the "K" value, which determines // the magnitude of the change. The modifier is multiplied by the // difference between a float representation of the results // (1.0 for a win, 0.5 for a tie, and 0.0 for a loss) and the player's // win probability for the match. func ratingChange(player, opponent int, win float64, kMod int) int { return int(float64(kMod*K) * (win - winProbability(player, opponent))) }
56e5ed34d204924f21254ee1e45cc69946d1d9b8
[ "Markdown", "Go" ]
4
Go
CarlColglazier/robochart
f1c2ea15bb85cdaf263b892337a6c25748ef876d
9ec8a8d7225bd548f016bb41683d7d3e359b6538
refs/heads/master
<file_sep>host_ip=172.16.17.32 port=6888 password=<PASSWORD>$@% <file_sep>SLEEP_TIME=10 CHECK_INTERVAL_TIMES=12000 NOTIFY_THREAD_NUM=1 <file_sep>package com.ml; 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.List; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; public class SqlHelper { private static final Log log = LogFactory.getLog(SqlHelper.class); private static String url = null; private static String username = null; private static String password = <PASSWORD>; public static final String JDBC_FILE_PATH = "jdbc.properties"; // 用户名 static { try { url = CommonUtil.getProperty(JDBC_FILE_PATH, "url"); username = CommonUtil.getProperty(JDBC_FILE_PATH, "username"); password = CommonUtil.getProperty(JDBC_FILE_PATH, "password"); } catch (Exception e) { log.error("#ERROR# :系统加载jdbc.properties配置文件异常,请检查!", e); } // 注册驱动类 try { Class.forName(CommonUtil.getProperty(JDBC_FILE_PATH, "driverClassName")); } catch (ClassNotFoundException e) { log.error("#ERROR# :加载数据库驱动异常,请检查!", e); } } /** * 创建一个数据库连接 * * @return 一个数据库连接 */ public static Connection getConnection() { Connection conn = null; // 创建数据库连接 try { conn = DriverManager.getConnection(url, username, password); } catch (SQLException e) { log.error("#ERROR# :创建数据库连接发生异常,请检查!", e); } return conn; } /** * 在一个数据库连接上执行一个静态SQL语句查询 * * @param conn * 数据库连接 * @param staticSql * 静态SQL语句字符串 * @return 返回查询结果集ResultSet对象 * @throws SQLException */ public static ResultSet executeQuery(Connection conn, String staticSql) throws SQLException { ResultSet rs = null; // 创建执行SQL的对象 Statement stmt = conn.createStatement(); // 执行SQL,并获取返回结果 rs = stmt.executeQuery(staticSql); return rs; } /** * 在一个数据库连接上执行一带参数的SQL语句查询 * * @param conn * 数据库连接 * @param Sql * SQL语句字符串 * @param params * 参数 * @return 返回查询结果集ResultSet对象 * @throws SQLException */ public static int executeUpdate(Connection conn, String Sql, String[] params) throws SQLException { int iCnt = 1; // 创建执行SQL的对象 PreparedStatement stmt = conn.prepareStatement(Sql); if (params != null && params.length > 0) { int i = 1; for (String param : params) { stmt.setString(i++, param); } } // 执行SQL,并获取返回结果 iCnt = stmt.executeUpdate(); stmt.close(); return iCnt; } /** * 在一个数据库连接上执行一个静态SQL语句查询 * * @param conn * 数据库连接 * @param staticSql * 静态SQL语句字符串 * @return 返回查询结果集ResultSet对象 * @throws SQLException */ public static ResultSet executeQuery(Connection conn, String Sql, String[] params) throws SQLException { ResultSet rs = null; // 创建执行SQL的对象 PreparedStatement stmt = conn.prepareStatement(Sql); if (params != null && params.length > 0) { int i = 1; for (String param : params) { stmt.setString(i++, param); } } // 执行SQL,并获取返回结果 rs = stmt.executeQuery(); return rs; } /** * 在一个数据库连接上执行一个静态SQL语句 * * @param conn * 数据库连接 * @param staticSql * 静态SQL语句字符串 * @throws SQLException */ public static void executeSQL(Connection conn, String staticSql) throws SQLException { // 创建执行SQL的对象 Statement stmt = conn.createStatement(); // 执行SQL,并获取返回结果 stmt.execute(staticSql); } /** * 在一个数据库连接上执行一批静态SQL语句 * * @param conn * 数据库连接 * @param sqlList * 静态SQL语句字符串集合 * @throws SQLException */ public static void executeBatchSQL(Connection conn, List<String> sqlList) throws SQLException { // 创建执行SQL的对象 Statement stmt = conn.createStatement(); for (String sql : sqlList) { stmt.addBatch(sql); } // 执行SQL,并获取返回结果 stmt.executeBatch(); } public static void closeConnection(Connection conn) { if (conn == null) return; try { if (!conn.isClosed()) { // 关闭数据库连接 conn.close(); } } catch (SQLException e) { log.error("#ERROR# :关闭数据库连接发生异常,请检查!", e); } } } <file_sep>package com.ml; import java.util.ArrayList; import java.util.List; import org.apache.commons.beanutils.BeanUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import net.sf.json.JSONObject; public class PayNotifyThread extends Thread { private static final Logger log = (Logger) LoggerFactory.getLogger(PayNotifyThread.class); public void run() { try{ int sleepTime = Integer.parseInt(CommonUtil.getProperty("SLEEP_TIME")); while(true) { try{ int listSize = CheckPayNofify.mchOrderDataList.size(); for(int i=0;i<listSize;i++){ PayNotifyData payNotifyData =new PayNotifyData(); MchOrderData mchOrderStatusData =new MchOrderData(); MchOrderData mchOrderData=CheckPayNofify.mchOrderDataList.get(i); //BeanUtils.copyProperties(mchOrderData,payNotifyData); //BeanUtils.copyProperties(mchOrderData,mchOrderStatusData); //回调数据对象 payNotifyData.setOut_trade_no(mchOrderData.getOut_trade_no()); payNotifyData.setTransaction_id(mchOrderData.getTransaction_id()); payNotifyData.setTotal_fee(mchOrderData.getTotal_fee()); payNotifyData.setBody(mchOrderData.getBody()); payNotifyData.setAttach(mchOrderData.getAttach()); payNotifyData.setTime_end(mchOrderData.getTime_end()); payNotifyData.setStatus(mchOrderData.getStatus()); payNotifyData.setSign(mchOrderData.getSign()); //状态数据对象 mchOrderStatusData.setTransaction_order_id(mchOrderData.getTransaction_order_id()); mchOrderStatusData.setOut_trade_no(mchOrderData.getOut_trade_no()); mchOrderStatusData.setTransaction_id(mchOrderData.getTransaction_id()); mchOrderStatusData.setTotal_fee(mchOrderData.getTotal_fee()); mchOrderStatusData.setBody(mchOrderData.getBody()); mchOrderStatusData.setAttach(mchOrderData.getAttach()); mchOrderStatusData.setTime_end(mchOrderData.getTime_end()); mchOrderStatusData.setStatus(mchOrderData.getStatus()); mchOrderStatusData.setSign(mchOrderData.getSign()); mchOrderStatusData.setNotify_url(mchOrderData.getNotify_url()); mchOrderStatusData.setFail_times(mchOrderData.getFail_times()); //JSONObject getObj = JSONObject.fromObject(payNotifyData); String StrUrl =mchOrderData.getNotify_url(); //没同步的做同步通知 if(StrUrl!=null && !"".equals(StrUrl) && mchOrderData.getSynchronize_status()==CheckPayNofify.STATUS_INIT){ //String ret= CommonUtil.postURL(StrUrl, getObj.toString()); String ret= CommonNotify.doPayNotify(mchOrderData, mchOrderData.getMch_id()); log.info("notify TRANSACTION_ORDER_ID="+mchOrderData.getTransaction_order_id()); if(CheckPayNofify.mchOrderDataList.size()>0){ if("success".equals(ret)){ CheckPayNofify.mchOrderDataList.get(i).setSynchronize_status(CheckPayNofify.STATUS_NO); CheckPayNofify.mchOrderDataList.get(i).setFail_retry_end(CheckPayNofify.STATUS_NO); //更新状态队列 if(CheckPayNofify.mchOrderDataStatusList==null ){ CheckPayNofify.mchOrderDataStatusList =new ArrayList<MchOrderData>(); } mchOrderStatusData.setSynchronize_status(CheckPayNofify.STATUS_NO); CheckPayNofify.mchOrderDataStatusList.add(mchOrderStatusData); } else { CheckPayNofify.mchOrderDataList.get(i).setSynchronize_status(CheckPayNofify.STATUS_FAIL); CheckPayNofify.mchOrderDataList.get(i).setFail_times(CheckPayNofify.mchOrderDataList.get(i).getFail_times()+1); CheckPayNofify.mchOrderDataList.get(i).setStart_fail_time(DateUtil.getTime()); } } } else if((StrUrl==null || "".equals(StrUrl))&& mchOrderData.getSynchronize_status()==CheckPayNofify.STATUS_INIT) { //没有回到地址的 CheckPayNofify.mchOrderDataList.get(i).setSynchronize_status(CheckPayNofify.STATUS_NO_URL); CheckPayNofify.mchOrderDataList.get(i).setFail_times(CheckPayNofify.mchOrderDataList.get(i).getFail_times()+1); CheckPayNofify.mchOrderDataList.get(i).setFail_retry_end(CheckPayNofify.STATUS_NO); //更新状态队列 if(CheckPayNofify.mchOrderDataStatusList==null){ CheckPayNofify.mchOrderDataStatusList =new ArrayList<MchOrderData>(); } mchOrderStatusData.setSynchronize_status(CheckPayNofify.STATUS_NO_URL); CheckPayNofify.mchOrderDataStatusList.add(mchOrderStatusData); } } removeMchOrderDataList(); }catch (Exception e) { log.error("同步消息通知失败:" +e.getMessage()); } //间隔指定时间之后从新检查 Thread.sleep(sleepTime); } } catch (Exception e) { log.error("同步消息通知失败:" +e.getMessage()); } } public synchronized void removeMchOrderDataList() { try{ //在队列中删除已同步数据 for(int i=CheckPayNofify.mchOrderDataList.size()-1;i>=0;i--){ MchOrderData mchOrderData=CheckPayNofify.mchOrderDataList.get(i); if((mchOrderData.getSynchronize_status()==CheckPayNofify.STATUS_NO||mchOrderData.getSynchronize_status()==CheckPayNofify.STATUS_NO_URL)&& mchOrderData.getFail_retry_end()==CheckPayNofify.STATUS_NO){ CheckPayNofify.mchOrderDataList.remove(i); log.info("reomove TRANSACTION_ORDER_ID="+mchOrderData.getTransaction_order_id()); } } } catch (Exception e) { log.error("在队列中删除已同步数据:" +e.getMessage()); } } }
1df3e22376a18175f44d62b2a69bc577ee0e2750
[ "Java", "INI" ]
4
INI
luckyyeah/paynotify
4e60435eecc3a5bcf5dd72c0a0bc3c8b8a882d90
043fe681da782cf03eb17ea6bdebfabf31ad5581
refs/heads/master
<repo_name>hasheddan/plunder<file_sep>/go.mod module github.com/plunder-app/plunder go 1.12 require ( github.com/AlecAivazis/survey/v2 v2.0.2 // indirect github.com/c4milo/gotoolkit v0.0.0-20190525173301-67483a18c17a // indirect github.com/ghodss/yaml v1.0.0 github.com/gorilla/mux v1.7.3 // indirect github.com/hooklift/assert v0.0.0-20170704181755-9d1defd6d214 // indirect github.com/hooklift/iso9660 v1.0.0 // indirect github.com/konsorten/go-windows-terminal-sequences v1.0.2 // indirect github.com/kr/pretty v0.1.0 // indirect github.com/kr/pty v1.1.8 // indirect github.com/krolaw/dhcp4 v0.0.0-20190531080455-7b64900047ae // indirect github.com/pkg/sftp v1.10.1 // indirect github.com/plunder-app/BOOTy v0.0.0-20200506165408-19d2090683fe // indirect github.com/plunder-app/plunder/pkg/apiserver v0.0.0-20191105152536-b5c505aaf830 github.com/plunder-app/plunder/pkg/certs v0.0.0-00010101000000-000000000000 github.com/plunder-app/plunder/pkg/parlay v0.0.0-20191105152536-b5c505aaf830 github.com/plunder-app/plunder/pkg/parlay/parlaytypes v0.0.0-20191105152536-b5c505aaf830 github.com/plunder-app/plunder/pkg/plunderlogging v0.0.0-20191105152536-b5c505aaf830 // indirect github.com/plunder-app/plunder/pkg/services v0.0.0-20191105152536-b5c505aaf830 github.com/plunder-app/plunder/pkg/ssh v0.0.0-00010101000000-000000000000 github.com/plunder-app/plunder/pkg/utils v0.0.0-20191105152536-b5c505aaf830 github.com/sirupsen/logrus v1.4.2 github.com/spf13/cobra v0.0.5 github.com/thebsdbox/go-tftp v0.0.0-20190329154032-a7263f18c49c // indirect github.com/vishvananda/netlink v1.1.0 // indirect github.com/whyrusleeping/go-tftp v0.0.0-20180830013254-3695fa5761ee // indirect golang.org/x/net v0.0.0-20190813141303-74dc4d7220e7 // indirect golang.org/x/sys v0.0.0-20190813064441-fde4db37ae7a // indirect gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127 // indirect ) replace ( github.com/plunder-app/plunder/pkg/apiserver => ./pkg/apiserver github.com/plunder-app/plunder/pkg/certs => ./pkg/certs github.com/plunder-app/plunder/pkg/services => ./pkg/services github.com/plunder-app/plunder/pkg/ssh => ./pkg/ssh github.com/plunder-app/plunder/pkg/utils => ./pkg/utils github.com/plunder-app/BOOTy => ../../../github.com/thebsdbox/BOOTy ) <file_sep>/pkg/services/templateBOOTy.go package services import ( "encoding/json" "net" "github.com/plunder-app/BOOTy/pkg/plunderclient/types" "github.com/vishvananda/netlink" ) //BuildBOOTYconfig - Creates a new presseed configuration using the passed data func (config *HostConfig) BuildBOOTYconfig() string { a := types.BootyConfig{} a.Action = types.WriteImage // Parse the strings subnet := net.ParseIP(config.Subnet) ip := net.ParseIP(config.IPAddress) // Change into a cidr cidr := net.IPNet{ IP: ip, Mask: subnet.DefaultMask(), } addr, _ := netlink.ParseAddr(cidr.String()) // Set configuration if addr != nil { a.Address = addr.String() a.Gateway = config.Gateway } a.DestinationDevice = config.DestinationDevice a.SourceImage = config.SourceImage a.GrowPartition = *config.GrowPartition a.LVMRootName = config.LVMRootName a.DropToShell = *config.ShellOnFail a.NameServer = config.NameServer b, _ := json.Marshal(a) return string(b) }
f661b8c2440e8c9ad36daa9851b24c6947618af8
[ "Go", "Go Module" ]
2
Go Module
hasheddan/plunder
01273007741f0671722d19e4b9d34866363cbd6b
29d859b79019b7937af4578fd1bc5e974260287a
refs/heads/master
<file_sep>VeryLongInt =========== Represents a very long Integer object which holds a theoretical infinite number of numbers. <file_sep>package sysc2100; import java.io.*; public class VeryLongDriverMain { public static void main(String[] args) { PrintWriter writer = null; try { VeryLongDriver driver = new VeryLongDriver(); writer = driver.openFiles(); driver.testVeryLongIntMethods(); } // try finally { writer.close(); } // finally } // method main } // class VeryLongDriverMain
6ed69bae179f1c8aa9206f7762f382b69beb3f9e
[ "Markdown", "Java" ]
2
Markdown
ryanseys/very-long-int
928270fbf2f691e662603b96ea24e12a44fef587
43b21aff55d94e5d59d43da628daf4ee5ee729c4
refs/heads/master
<file_sep>package dictionary.database; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import dictionary.word.Word; public final class Database { private static final String DRIVER_O = "oracle.jdbc.driver.OracleDriver"; private static final String URL_O = "jdbc:oracle:thin:@localhost:1521:XE"; private static final String USER_O = "dictionary"; private static final String PASS_O = "<PASSWORD>"; private static Connection connect; private static Statement stmt; private Database() { /*cannot instantiate this class outside (not required) as all the methods are static*/ } private static void connect() { try { Class.forName(DRIVER_O); //DriverManager.registerDriver( new oracle.jdbc.driver.OracleDriver()); connect = DriverManager.getConnection(URL_O, USER_O, PASS_O); System.out.println("Connected to the database..."); } catch(SQLException e) { e.printStackTrace(); } catch(ClassNotFoundException e) { e.printStackTrace(); } } public static void addWord(Word word) { if(connect==null) connect(); try { if(connect!=null) { String query = "insert into dictionary values ('"+word.getWord()+"','"+word.getPostype()+"')"; stmt = connect.createStatement(); stmt.executeUpdate(query); System.out.println(query); addDefinition(word); addSynonyms(word); addAntonyms(word); connect.commit(); //stmt.close();connect.close(); } } catch(SQLException e) { System.err.println(e.getMessage()); } } public static void addDefinition(Word word) { if(word.getDefinition()==null || word.getDefinition().isEmpty()) return; if(connect==null) connect(); try { if(connect!=null) { String query = "insert into definition values ('"+word.getWord()+"','"+word.getDefinition()+"')"; stmt = connect.createStatement(); stmt.executeUpdate(query); System.out.println(query); connect.commit(); //stmt.close();connect.close(); } } catch(SQLException e) { System.err.println(e.getMessage()); } catch(NullPointerException e) { System.err.println(e.getMessage()); } } public static void addSynonyms(Word word) { if(connect==null) connect(); try { if(connect!=null) { for(String s:word.getSynonyms()) { String query = "insert into synonyms values ('"+word.getWord()+"','"+s+"')"; stmt = connect.createStatement(); stmt.executeUpdate(query); System.out.println(query); } connect.commit(); //stmt.close();connect.close(); } } catch(SQLException e) { System.err.println(e.getMessage()); } catch(NullPointerException e) { System.err.println(e.getMessage()); } } public static void addAntonyms(Word word) { if(connect==null) connect(); try { if(connect!=null) { for(String a:word.getAntonyms()) { String query = "insert into antonym values ('"+word.getWord()+"','"+a+"')"; stmt = connect.createStatement(); stmt.executeUpdate(query); System.out.println(query); } connect.commit(); //stmt.close();connect.close(); } } catch(SQLException e) { System.err.println(e.getMessage()); } catch(NullPointerException e) { System.err.println(e.getMessage()); } } public static Word findWord(String text) { Word word=null; if(connect==null) connect(); try { if(connect!=null) { String query = "select * from dictionary where word ='"+text+"'"; stmt = connect.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_READ_ONLY); ResultSet words = stmt.executeQuery(query); if(words.next()) { word = new Word(text); findPosType(word,words.getString(2)); findDefinition(word); findSynonyms(word); findAntonyms(word); } } } catch(SQLException e) { System.err.println(e.getMessage()); } return word; } private static void findPosType(Word word, String tag) { try { if(connect!=null) { String query = "select description from postype where tag ='"+tag+"'"; stmt = connect.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_READ_ONLY); ResultSet pos = stmt.executeQuery(query); while(pos.next()) word.setPostype(pos.getString(1)); } } catch(SQLException e) { System.err.println(e.getMessage()); } } private static void findDefinition(Word word) { try { if(connect!=null) { String query = "select definition from definition where word ='"+word.getWord()+"'"; stmt = connect.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_READ_ONLY); ResultSet def = stmt.executeQuery(query); if(def.next()) word.setDefinition(def.getString(1)); } } catch(SQLException e) { System.err.println(e.getMessage()); } } private static void findSynonyms(Word word) { try { if(connect!=null) { String query = "select synonyms from synonyms where word ='"+word.getWord()+"'"; stmt = connect.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_READ_ONLY); ResultSet synonyms = stmt.executeQuery(query); while(synonyms.next()) word.addSynonym(synonyms.getString(1)); } } catch(SQLException e) { System.err.println(e.getMessage()); } } private static void findAntonyms(Word word) { try { if(connect!=null) { String query = "select antonym from antonym where word ='"+word.getWord()+"'"; stmt = connect.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_READ_ONLY); ResultSet antonyms = stmt.executeQuery(query); while(antonyms.next()) word.addAntonym(antonyms.getString(1)); } } catch(SQLException e) { System.err.println(e.getMessage()); } } } <file_sep># Custom-Dictionary Using DBMS to create a custom dictionary, with the help of Stanford CoreNLP, to extract POS tags.
0ba411974cd9e4c9cb0b9b279c8d36d68f5f2540
[ "Markdown", "Java" ]
2
Java
arahant/Custom-Dictionary
3ed720abcdf1182e5ba56d3effd61048e7309fb3
fec916413ad11f57f324ac544061f0d4529bb374
refs/heads/master
<file_sep><?php $type = $_GET['type']; $zip_code = $_GET['zip_code']; $sql = "select * from person where zip = '".$zip_code."' order by name asc"; $dblink = mysql_connect("localhost", "naffis_naffis", "naffis04host") or die("ERROR: count not connect"); mysql_select_db("naffis_mapdata", $dblink) or die("ERROR: count not select db"); $result = mysql_query($sql, $dblink) or die("ERROR: query failed<br>sql = ".$sql."<br>"); $num = mysql_numrows($result); $xmlString = ""; if($type == "map") { $xmlString .= "<?xml version=\"1.0\"?>"; $xmlString .= "<page>"; $xmlString .= "<title></title>"; $xmlString .= "<query></query>"; $xmlString .= "<request>"; $xmlString .= "<url></url>"; $xmlString .= "<query></query>"; $xmlString .= "</request>"; if($num > 0) { $centerLat=mysql_result($result,0,"lat"); $centerLon=mysql_result($result,0,"lon"); $xmlString .= "<center lat=\"".$centerLat."\" lng=\"".$centerLon."\"/>"; $xmlString .= "<span lat=\"0.062134\" lng=\"0.104253\"/>"; $xmlString .= "<searchcenter lat=\"".$centerLat."\" lng=\"".$centerLon."\"/>"; $xmlString .= "<searchspan lat=\"0.062134\" lng=\"0.104253\"/>"; } else { $xmlString .= "<center lat=\"37.062500\" lng=\"-95.677068\"/>"; $xmlString .= "<span lat=\"62.625000\" lng=\"105.459315\"/>"; $xmlString .= "<searchcenter lat=\"37.062500\" lng=\"-95.677068\"/>"; $xmlString .= "<searchspan lat=\"62.625000\" lng=\"105.459315\"/>"; } $xmlString .= "<overlay panelStyle=\"http://www.somapper.com/xsl/geocodepanel.xsl\">"; if($num > 0) { $i=0; while ($i < $num) { $person_id=mysql_result($result,$i,"person_id"); $details_link=mysql_result($result,$i,"details_link"); $name=mysql_result($result,$i,"name"); $image=mysql_result($result,$i,"image"); $address_type=mysql_result($result,$i,"address_type"); $address=mysql_result($result,$i,"address"); $state=mysql_result($result,$i,"state"); $lat=mysql_result($result,$i,"lat"); $lon=mysql_result($result,$i,"lon"); $xmlString .= "<location infoStyle=\"http://www.somapper.com/xsl/infostyle_statemap.xsl\" id=\"".$i."\">\n"; $xmlString .= "<point lat=\"".$lat."\" lng=\"".$lon."\"/>\n"; $xmlString .= "<icon image=\"http://www.somapper.com/images/society.png\" class=\"local\"/>\n"; $xmlString .= "<info>\n"; $xmlString .= "<id>".$i."</id>\n"; $xmlString .= "<title xml:space=\"preserve\">Details</title>\n"; $xmlString .= "<url>".str_replace("&", "&amp;", $details_link)."</url>\n"; $xmlString .= "<imgsrc>".str_replace("&", "&amp;", $image)."</imgsrc>\n"; $xmlString .= "<name>".str_replace("&nbsp;", " ", $name)."</name>\n"; if($address_type == "general") $xmlString .= "<type>Address</type>\n"; else if($address_type == "work") $xmlString .= "<type>Work Address</type>\n"; else if($address_type == "school") $xmlString .= "<type>School Address</type>\n"; else if($address_type == "home") $xmlString .= "<type>Home Address</type>\n"; $addresses = array(); $addresses = explode("<br>", $address); $lineCount = count($addresses); if($lineCount == 1) { $addresses[0] = str_replace("\n;", "", $addresses[0]); $addresses[0] = str_replace("&nbsp;", " ", $addresses[0]); $xmlString .= "<address1>".$addresses[0]."</address1>\n"; $xmlString .= "<address2></address2>\n"; } else { $addresses[0] = str_replace("\n;", "", $addresses[0]); $addresses[0] = str_replace("&nbsp;", " ", $addresses[0]); $addresses[1] = str_replace("\n;", "", $addresses[1]); $addresses[1] = str_replace("&nbsp;", " ", $addresses[1]); $xmlString .= "<address1>".$addresses[0]."</address1>\n"; $xmlString .= "<address2>".$addresses[1]."</address2>\n"; } $xmlString .= "</info>\n"; $xmlString .= "</location>\n"; $i++; } } else { $xmlString .= "<location infoStyle=\"http://www.somapper.com/xsl/infostyle_mainmap.xsl\" id=\"0\">"; $xmlString .= "<point lat=\"38.895000\" lng=\"-77.036667\"/>"; $xmlString .= "<icon image=\"http://www.somapper.com/images/society.png\" class=\"local\"/>"; $xmlString .= "<info>"; $xmlString .= "<id>0</id>\n"; $xmlString .= "<title xml:space=\"preserve\">Washington DC</title>"; $xmlString .= "<url>javascript:update(20001);</url>"; $xmlString .= "<city>Washington DC</city>"; $xmlString .= "</info>"; $xmlString .= "</location>"; $xmlString .= "<location infoStyle=\"http://www.somapper.com/xsl/infostyle_mainmap.xsl\" id=\"1\">"; $xmlString .= "<point lat=\"39.286580\" lng=\"-76.607221\"/>"; $xmlString .= "<icon image=\"http://www.somapper.com/images/society.png\" class=\"local\"/>"; $xmlString .= "<info>"; $xmlString .= "<id>1</id>\n"; $xmlString .= "<title xml:space=\"preserve\">Maryland</title>"; $xmlString .= "<url>javascript:update(21202);</url>"; $xmlString .= "<city>Maryland</city>"; $xmlString .= "</info>"; $xmlString .= "</location>"; } $xmlString .= "</overlay>"; $xmlString .= "</page>"; } else if($type == "list") { if($num > 0) { $xmlString = "<people>"; $i=0; while ($i < $num) { $name=mysql_result($result,$i,"name"); $address=mysql_result($result,$i,"address"); $name = str_replace("&nbsp;", " ", $name); $name = str_replace("nbsp;", " ", $name); $name = str_replace("\n", "", $name); $name = trim($name); $address = str_replace("&nbsp;", " ", $address); $address = str_replace("<br>", " ", $address); $address = str_replace("\n", "", $address); $address = str_replace("nbsp;", " ", $address); $address = trim($address); $xmlString .= "<person>\n"; $xmlString .= "<id>".$i."</id>\n"; $xmlString .= "<name>".$name."</name>\n"; $xmlString .= "<address>".$address."</address>\n"; $xmlString .= "</person>\n"; $name = ""; $address = ""; $i++; } $xmlString .= "</people>"; } else { $xmlString .= "<cities>"; $xmlString .= "<city>"; $xmlString .= "<id>0</id>\n"; $xmlString .= "<name><a href=\"javascript:update(20001);\">Washington DC</a></name>"; $xmlString .= "</city>"; $xmlString .= "<city>"; $xmlString .= "<id>1</id>\n"; $xmlString .= "<name><a href=\"javascript:update(21202);\">Maryland</a></name>"; $xmlString .= "</city>"; $xmlString .= "</cities>"; } } // content type is xml header("Content-Type: text/xml"); // print out the xml file we sucked in print($xmlString) ?><file_sep><?php $newline = "<br />"; // connect to the database //$dbcon = mysql_connect("localhost","naffis_naffis","naffis04host") or die ("Can not connect to given host"); //mysql_select_db("eventdata") or die ("Can not connect to database"); $url = "http://www.somapper.com/crawl/dcdata.txt"; // get the number of records found echo "Beginning parsing...<br>"; $content = file_get_contents($url); get_chunks($content); echo "Done parsing...<br>"; echo "Getting coordinates...<br>"; getCoords(); echo "Done getting coordinates...<br>"; echo "deleting empty coordinates...<br>"; deleteNoCoords(); echo "Done deleting empty coordinates...<br>"; // function get_chunks($pageContent) { $marker = "<input type=checkbox name="; $currentPos = 0; $dblink = mysql_connect("localhost", "naffis_naffis", "naffis04host") or die("ERROR: count not connect"); mysql_select_db("naffis_mapdata", $dblink) or die("ERROR: count not select db"); $sql = "DELETE FROM personstage where state = \"DC\""; $result = mysql_query($sql, $dblink) or die("ERROR: delete failed<br>sql = ".$sql."<br>"); while(strpos($pageContent, $marker, $currentPos)) { $indexStart = strpos($pageContent, $marker, $currentPos); echo "indexStart = ".$indexStart."<br>"; if(strpos($pageContent, $marker, $indexStart + strlen($marker))) $indexEnd = strpos($pageContent, $marker, $indexStart + strlen($marker)); else $indexEnd = strlen($pageContent); echo "indexEnd = ".$indexEnd."<br>"; $currentPos = $indexEnd; //echo "currentPos = ".$currentPos."<br>"; $chunk = substr($pageContent, $indexStart, $indexEnd - $indexStart); //echo "chunk =".$chunk."<br>"; // parse and insert the chunk into the database parse($chunk); echo "currentPos = ".$currentPos."<br>"; } } function parse($chunk) { $currentP = 0; $dblink = mysql_connect("localhost", "naffis_naffis", "naffis04host") or die("ERROR: count not connect"); mysql_select_db("naffis_mapdata", $dblink) or die("ERROR: count not select db"); $detailsLink = ""; $name = ""; $image = ""; $homeAddress = ""; $schoolAddress = ""; $workAddress = ""; $state = "DC"; // get the details link if(strpos($chunk, "genDataSheet.asp?id=", $currentP)) { $start = strpos($chunk, "genDataSheet.asp?id=", $currentP); echo "start = ".$start."<br>"; $end = strpos($chunk, "\"", $start); echo "end = ".$end."<br>"; $detailsLink = substr($chunk, $start, $end-$start); $detailsLink = "http://sor.csosa.net/sor/public/".$detailsLink; echo "detailsLink = ".$detailsLink."<br>"; $currentP = $end; } // get the name if(strpos($chunk, ">", $currentP)) { $start = strpos($chunk, ">", $currentP) + strlen(">"); $end = strpos($chunk, "<", $start); $name = substr($chunk, $start, $end - $start); echo "name = ".$name."<br>"; $currentP = $end; } $name = str_replace("\n;", "", $name); $name = str_replace("&nbsp;", "", $name); // get the thumbnail if(strpos($chunk, "ThumbnailsPDID/", $currentP)) { $baseurl = "http://sor.csosa.net/sor/clientPics/ThumbnailsPDID/"; $start = strpos($chunk, "ThumbnailsPDID/", $currentP) + strlen("ThumbnailsPDID/"); $end = strpos($chunk, "\"", $start); $image = $baseurl.substr($chunk, $start, $end-$start); echo "image = ".$image."<br>"; $currentP = $end; } // get the home address if(strpos($chunk, "Home Address", $currentP)) { $start = strpos($chunk, "Home Address", $currentP); $start = strpos($chunk, "<br>", $start) + strlen("<br>"); $end = strpos($chunk, "</td>", $start); $homeAddress = substr($chunk, $start, $end-$start); echo "homeAddress = ".$homeAddress."<br>"; $currentP = $end; } $homeAddress = str_replace("\n;", "", $homeAddress); // get the school address if(strpos($chunk, "School", $currentP)) { $start = strpos($chunk, "School", $currentP); $start = strpos($chunk, "<br>", $start) + strlen("<br>"); $end = strpos($chunk, "</td>", $start); $schoolAddress = substr($chunk, $start, $end-$start); echo "schoolAddress = ".$schoolAddress."<br>"; $currentP = $end; } $schoolAddress = str_replace("\n;", "", $schoolAddress); // get the work address if(strpos($chunk, "Work", $currentP)) { $start = strpos($chunk, "Work", $currentP); $start = strpos($chunk, "<br>", $start) + strlen("<br>"); $end = strpos($chunk, "</td>", $start); $workAddress = substr($chunk, $start, $end-$start); echo "workAddress = ".$workAddress."<br>"; $currentP = $end; } $workAddress = str_replace("\n;", "", $workAddress); $countinsert = 0; while($countinsert < 3) { $sql = ""; $addressType = ""; $address = ""; echo "addressType = ".$addressType."<br>"; echo "address = ".$address."<br>"; if($countinsert == 0 && $workAddress != "") { $addressType = "work"; $address = $workAddress; } else if($countinsert == 1 && $schoolAddress != "") { $addressType = "school"; $address = $schoolAddress; } else if($countinsert == 2 && $homeAddress != "") { $addressType = "home"; $address = $homeAddress; } if($addressType != "") { // now insert into the database; $sql = "INSERT INTO personstage ( person_id, details_link, name, image, address_type, address, state, zip ) VALUES ( '', '$detailsLink', '$name', '$image', '$addressType', '$address', '$state', '$zip' )"; echo $sql."<br>"; $result = mysql_query($sql, $dblink) or die("ERROR: insert failed<br>sql = ".$sql."<br>"); echo "inserted row<br>"; } echo "countinsert=".$countinsert."<br>"; $countinsert++; } } function escape($str) { return addslashes($str); } function getGooglePage($address) { $address = fixAddress($address); $url = "http://maps.google.com/maps?q="; $url = trim($url).trim($address); $url = trim($url)."&output=js"; echo "url = ".$url."<br>"; return file_get_contents($url); } function fixAddress($address) { $address = str_replace("&nbsp;&nbsp;", "+", $address); $address = str_replace("S.E.", "SE", $address); $address = str_replace("S.W.", "SW", $address); $address = str_replace("N.E.", "NE", $address); $address = str_replace("N.W.", "NW", $address); $address = str_replace("<br>", ",+", $address); $address = str_replace("Unit Block of ", "1", $address); $address = str_replace(" Block of ", "", $address); $address = str_replace(" ", "+", $address); echo "address = ".$address."<br>"; return $address; } function getCoords() { $dblink = mysql_connect("localhost", "naffis_naffis", "naffis04host") or die("ERROR: count not connect"); mysql_select_db("naffis_mapdata", $dblink) or die("ERROR: count not select db"); $sql = "select person_id, address from personstage"; $result = mysql_query($sql, $dblink); $numrows = mysql_num_rows($result); if($numrows > 0) { for($i = 0; $i < $numrows; $i++) { $row = mysql_fetch_array($result); $personId = $row["person_id"]; $address = $row["address"]; $content = getGooglePage($address); if(strpos($content, "<refinement><query>", $currentP)) { // the address was not correct so get the suggested one $start = strpos($content, "<refinement><query>", 0) + strlen("<refinement><query>"); echo "start = ".$start."<br>"; $end = strpos($content, "</query>", $start); echo "end = ".$end."<br>"; $address = substr($content, $start, $end-$start); $content = getGooglePage($address); } $coords[2] = array("", ""); $coords = parseCoords($content); $zip = parseZip($content); $sqlInsert = "UPDATE personstage SET lat = '".$coords[0]."', lon = '".$coords[1]."', zip = '".$zip."' WHERE person_id = ".$personId; echo "sqlInsert = ".$sqlInsert."<br>"; $insertresult = mysql_query($sqlInsert, $dblink) or die("ERROR: insert failed<br>sqlInsert = ".$sqlInsert."<br>"); } } } function parseCoords($content) { // <point lat="38.891011" lng="-76.982346"/> $currentP = 0; $coords[2] = array("", ""); // get the lat if(strpos($content, "<point lat=\"", $currentP)) { $start = strpos($content, "<point lat=\"", $currentP) + strlen("<point lat=\""); echo "start = ".$start."<br>"; $end = strpos($content, "\"", $start); echo "end = ".$end."<br>"; $coords[0] = substr($content, $start, $end-$start); echo "lat = ".$coords[0]."<br>"; $currentP = $end; } // get the lon if(strpos($content, "lng=\"", $currentP)) { $start = strpos($content, "lng=\"", $currentP) + strlen("lng=\""); $end = strpos($content, "\"", $start); $coords[1] = substr($content, $start, $end-$start); echo "lon = ".$coords[1]."<br>"; $currentP = $end; } return $coords; } function parseZip($content) { // 21030</query> $currentP = 0; $zip = ""; if(strpos($content, "</query>", $currentP)) { $start = strpos($content, "</query>", $currentP) - 5; echo "dash pos = ".strpos($content, "-", $start) - $start; if(strpos($content, "-", $start)-$start == 0) $start = strpos($content, "</query>", $currentP) - 10; echo "start = ".$start."<br>"; $zip = substr($content, $start, 5); echo "zip = ".$zip."<br>"; } return $zip; } function deleteNoCoords() { $dblink = mysql_connect("localhost", "naffis_naffis", "naffis04host") or die("ERROR: count not connect"); mysql_select_db("naffis_mapdata", $dblink) or die("ERROR: count not select db"); $sql = "delete from personstage where lat = '' OR lon = ''"; $result = mysql_query($sql, $dblink); } ?><file_sep><?php $newline = "<br />"; $url = "http://www.dpscs.state.md.us/sorSearch/search.do?searchType=byName&anchor=false&lastnm=&firstnm="; $numRecs = get_num_records_md($url); // get the number of records found $num_records = get_num_records_md($url); echo "num_records = ".$num_records."<br>"; // get the number of records found echo "Beginning parsing...<br>"; $dblink = mysql_connect("localhost", "naffis", "naffis04host") or die("ERROR: count not connect"); mysql_select_db("peoplestage", $dblink) or die("ERROR: count not select db"); $sql = "DELETE FROM personstage where state = \"MD\""; $result = mysql_query($sql, $dblink) or die("ERROR: delete failed<br>sql = ".$sql."<br>"); // go through each page and parse out the events for ($counter = 1; $counter <= $num_records; $counter += 10) { echo "count = ".$counter."<br>"; $pageurl = $url."&start=".$counter; $content = file_get_contents($pageurl); get_chunks($content); } echo "Done parsing...<br>"; echo "Getting coordinates...<br>"; getCoords(); echo "Done getting coordinates...<br>"; echo "deleting empty coordinates...<br>"; deleteNoCoords(); echo "Done deleting empty coordinates...<br>"; // get the number of records in washington post function get_num_records_md($url) { $pageCont = file_get_contents($url); $tokenBefore = "Total Registrant Found: "; $tokenAfter = "</td>"; $indexBeforeToken = strpos($pageCont, $tokenBefore) + strlen($tokenBefore); $indexAfterToken = strpos($pageCont, $tokenAfter, $indexBeforeToken); $numRecords = trim(substr($pageCont, $indexBeforeToken, $indexAfterToken-$indexBeforeToken)); return (int)$numRecords; } function get_chunks($pageContent) { $marker = "<div class=\"smallPrint\">"; $currentPos = 0; while(strpos($pageContent, $marker, $currentPos)) { $indexStart = strpos($pageContent, $marker, $currentPos); echo "indexStart = ".$indexStart."<br>"; if(strpos($pageContent, $marker, $indexStart + strlen($marker))) $indexEnd = strpos($pageContent, $marker, $indexStart + strlen($marker)); else $indexEnd = strlen($pageContent); echo "indexEnd = ".$indexEnd."<br>"; $currentPos = $indexEnd; //echo "currentPos = ".$currentPos."<br>"; $chunk = substr($pageContent, $indexStart, $indexEnd - $indexStart); //echo "chunk =".$chunk."<br>"; // parse and insert the chunk into the database parse($chunk); echo "currentPos = ".$currentPos."<br>"; } } function parse($chunk) { $currentP = 0; $dblink = mysql_connect("localhost", "naffis", "naffis04host") or die("ERROR: count not connect"); mysql_select_db("peoplestage", $dblink) or die("ERROR: count not select db"); $detailsLink = ""; $name = ""; $image = ""; $address = ""; $homeAddress = ""; $schoolAddress = ""; $workAddress = ""; $state = "MD"; // get the name if(strpos($chunk, "<td class=\"smallPrint\">Name:</td>", $currentP)) { $currentP = strpos($chunk, "<td class=\"smallPrint\">Name:</td>", $currentP) + strlen("<td class=\"smallPrint\">Name:</td>"); $start = strpos($chunk, "<td class=\"smallPrint\">", $currentP) + strlen("<td class=\"smallPrint\">"); echo "start = ".$start."<br>"; $end = strpos($chunk, "</td>", $start); echo "end = ".$end."<br>"; $name = substr($chunk, $start, $end-$start); $name = str_replace("\n;", "", $name); $name = escape($name); echo "name = ".$name."<br>"; $currentP = $end; } if(strpos($chunk, "<td class=\"smallPrint\">Address:</td>", $currentP)) { $currentP = strpos($chunk, "<td class=\"smallPrint\">Address:</td>", $currentP) + strlen("<td class=\"smallPrint\">Address:</td>"); $start = strpos($chunk, "<td class=\"smallPrint\">", $currentP) + strlen("<td class=\"smallPrint\">"); echo "start = ".$start."<br>"; $end = strpos($chunk, "</td>", $start); echo "end = ".$end."<br>"; $address = substr($chunk, $start, $end-$start); $address = str_replace("\n;", "", $address); $address = escape($address); echo "address = ".$address."<br>"; $currentP = $end; } if(strpos($chunk, "/sorSearch/search.do?searchType=detail&anchor=false&id=", $currentP)) { $start = strpos($chunk, "/sorSearch/search.do?searchType=detail&anchor=false&id=", $currentP); echo "start = ".$start."<br>"; $end = strpos($chunk, "\">", $start); echo "end = ".$end."<br>"; $detailsLink = "http://www.dpscs.state.md.us".substr($chunk, $start, $end-$start); $detailsLink = str_replace("\n;", "", $detailsLink); echo "detailsLink = ".$detailsLink."<br>"; $currentP = $end; } if(strpos($chunk, "<img src=\"", $currentP)) { $start = strpos($chunk, "<img src=\"", $currentP) + strlen("<img src=\""); echo "start = ".$start."<br>"; $end = strpos($chunk, "\"", $start); echo "end = ".$end."<br>"; $image = "http://www.dpscs.state.md.us".substr($chunk, $start, $end-$start); $image = str_replace("\n;", "", $image); echo "image = ".$image."<br>"; $currentP = $end; } $addressType = "general"; // now insert into the database; $sql = "INSERT INTO personstage ( person_id, details_link, name, image, address_type, address, state ) VALUES ( '', '$detailsLink', '$name', '$image', '$addressType', '$address', '$state' )"; echo $sql."<br>"; $result = mysql_query($sql, $dblink) or die("ERROR: insert failed<br>sql = ".$sql."<br>"); echo "inserted row<br>"; } function escape($str) { return addslashes($str); } function getGooglePage($address) { $address = fixAddress($address); $url = "http://maps.google.com/maps?q="; $url = trim($url).trim($address); $url = trim($url)."&output=js"; echo "url = ".$url."<br>"; return file_get_contents($url); } function fixAddress($address) { $address = str_replace("&nbsp;&nbsp;", "+", $address); $address = str_replace("S.E.", "SE", $address); $address = str_replace("S.W.", "SW", $address); $address = str_replace("N.E.", "NE", $address); $address = str_replace("N.W.", "NW", $address); $address = str_replace("<br>", ",+", $address); $address = str_replace("Unit Block of ", "1", $address); $address = str_replace(" Block of ", "", $address); $address = str_replace(" ", "+", $address); echo "address = ".$address."<br>"; return $address; } function getCoords() { $dblink = mysql_connect("localhost", "naffis", "naffis04host") or die("ERROR: count not connect"); mysql_select_db("peoplestage", $dblink) or die("ERROR: count not select db"); $sql = "select person_id, address from personstage where state = 'MD'"; $result = mysql_query($sql, $dblink); $numrows = mysql_num_rows($result); if($numrows > 0) { for($i = 0; $i < $numrows; $i++) { echo "getCoords i = ".$i."<br>"; $row = mysql_fetch_array($result); $personId = $row["person_id"]; $address = $row["address"]; $content = getGooglePage($address); if(strpos($content, "<refinement><query>", $currentP)) { // the address was not correct so get the suggested one $start = strpos($content, "<refinement><query>", 0) + strlen("<refinement><query>"); echo "start = ".$start."<br>"; $end = strpos($content, "</query>", $start); echo "end = ".$end."<br>"; $address = substr($content, $start, $end-$start); $content = getGooglePage($address); } $coords[2] = array("", ""); $coords = parseCoords($content); $zip = parseZip($content); $sqlInsert = "UPDATE personstage SET lat = '".$coords[0]."', lon = '".$coords[1]."', zip = '".$zip."' WHERE person_id = ".$personId; echo "sqlInsert = ".$sqlInsert."<br>"; $insertresult = mysql_query($sqlInsert, $dblink) or die("ERROR: insert failed<br>sqlInsert = ".$sqlInsert."<br>"); } } } function parseCoords($content) { // <point lat="38.891011" lng="-76.982346"/> $currentP = 0; $coords[2] = array("", ""); // get the lat if(strpos($content, "<point lat=\"", $currentP)) { $start = strpos($content, "<point lat=\"", $currentP) + strlen("<point lat=\""); echo "start = ".$start."<br>"; $end = strpos($content, "\"", $start); echo "end = ".$end."<br>"; $coords[0] = substr($content, $start, $end-$start); echo "lat = ".$coords[0]."<br>"; $currentP = $end; } // get the lon if(strpos($content, "lng=\"", $currentP)) { $start = strpos($content, "lng=\"", $currentP) + strlen("lng=\""); $end = strpos($content, "\"", $start); $coords[1] = substr($content, $start, $end-$start); echo "lon = ".$coords[1]."<br>"; $currentP = $end; } return $coords; } function parseZip($content) { // 21030</query> $currentP = 0; $zip = ""; if(strpos($content, "</query>", $currentP)) { $start = strpos($content, "</query>", $currentP) - 5; echo "dash pos = ".strpos($content, "-", $start) - $start; if(strpos($content, "-", $start)-$start == 0) $start = strpos($content, "</query>", $currentP) - 10; echo "start = ".$start."<br>"; $zip = substr($content, $start, 5); echo "zip = ".$zip."<br>"; } return $zip; } function deleteNoCoords() { $dblink = mysql_connect("localhost", "naffis", "naffis04host") or die("ERROR: count not connect"); mysql_select_db("peoplestage", $dblink) or die("ERROR: count not select db"); $sql = "delete from personstage where lat = '' OR lon = ''"; $result = mysql_query($sql, $dblink); } ?><file_sep>somapper ======== SOMapper was a Google Maps hack that mapps the location of sex offenders in DC and Maryland. It was created around May 2005. It was slashdotted (http://science.slashdot.org/story/05/06/23/220229/slashback-summer-sail-sex-offenders) and then subsequently taken down after numerous death threats :)<file_sep><?php $zip_code = $_GET['zip_code']; $sql = "select * from person where zip = '".$zip_code."' order by name asc"; $dblink = mysql_connect("localhost", "naffis_naffis", "naffis04host") or die("ERROR: count not connect"); mysql_select_db("naffis_mapdata", $dblink) or die("ERROR: count not select db"); $result = mysql_query($sql, $dblink) or die("ERROR: query failed<br>sql = ".$sql."<br>"); $num = mysql_numrows($result); $xmlString = ""; if($num > 0) $xmlString .= "1"; else $xmlString .= "2"; // content type is xml //header("Content-Type: text/xml"); // print out the xml file we sucked in print($xmlString) ?>
97ee6e6d365aa5ad5d4aada8dfe52e374e7895d0
[ "Markdown", "PHP" ]
5
PHP
naffis/somapper
6ccb1c87de1119ba392519f84e0d93aba80bd016
cf1c322b5e957db7293f64798c98bcc28175eb81
refs/heads/master
<repo_name>indenpendman/TestDemo<file_sep>/Podfile platform :ios,'7.0' target ‘TestDemo' do pod 'AFNetworking','~> 3.0' end <file_sep>/README.md # TestDemo ios自动化测试简单案例 对应博文: http://www.jianshu.com/p/9fafd4354ec5 <file_sep>/TestDemo/Constant.h // // Constant.h // TestDemo // // Created by weixuewu on 2017/4/21. // Copyright © 2017年 weixuewu. All rights reserved. // #define SYSTEM_VERSION ([[UIDevice currentDevice] systemVersion]) #define IOS9_OR_LATER ((SYSTEM_VERSION.floatValue >= 9.0) ? 1:0) //适配字体,ios9及以上系统使用新字体——平方字体 #ifdef __IPHONE_9_0 #define kFontSize15 [UIFont fontWithName:@"PingFangSC-Light" size:15.0] #else #define kFontSize15 [UIFont systemFontOfSize:15.0] #endif #ifdef DEBUG #define kPortURL @"http://192.168.127.12:8089" //端口ip #else #define kPortURL @"http://192.168.1.254:8080" //端口ip #endif #if TEST #define kName @"ios10以前" #else #define kName @"ios10以后" #endif #if 1 //code 1 #elif 2 //code 2 #else //code n #endif #ifndef Constant_h #define Constant_h #endif /* Constant_h */
3dc11016f064f64ecb8acc00d6b36a56f1d216c0
[ "Markdown", "C", "Ruby" ]
3
Ruby
indenpendman/TestDemo
873f26964054bb0cf436f4c658d63c17b0db301a
a0bc985521fa3ee295edb3fdaa8772e87b2ffe47
refs/heads/main
<file_sep>var selected_text = ()=>{return document.getSelection().toString()} var get_body = () => { var selected = selected_text(); if (selected!=""){return selected} var body = document.querySelectorAll('body'); var result = ""; for(var i in body){ result+=body[i].innerText;result+="\n"} window.current_text=result return result } get_body();<file_sep>import { GeneListComponent, GeneFunctionComponent, DiseaseListComponent, CollapseComponent , DrugComponent, DrugListComponent, QAComponent, CollapsePrettyJSONComponent, ClinicalTrialComponent } from "./tools/comp.js"; import { load_config } from "./tools/load_config.js"; import { ActivateSelection } from "./tools/select.js"; import { APIAsync, create_modal, Tabs } from "./tools/hover_tip.js" import { pretty_json, render_list } from "./tools/easy_bs.js" var execute_code = (config) =>{ var {ravenclaw, aws_lambda} = config var rv_url = ravenclaw.endPoint; var json_options = { method:"POST", headers: { "x-api-key":aws_lambda.api_key, 'Content-Type': 'application/json', } } /* ============================= GET DETAILED DATA ============================= */ const get_gene_function = async(dom, data)=>{ var {gene,parent} = data; load_config((config)=>{ var input_data = {gene, "detail-type":"get_gene_functions"} fetch( config.aws_lambda.endPoint, { ...json_options, body: JSON.stringify(input_data) }) .then(res=>res.json()) .then((gfs) => { if(gfs.length>0) { var gene_function_component = new GeneFunctionComponent(); $(dom).append(gene_function_component.render(gfs)) } $(parent).append(dom) }) .catch((e) => { console.log(e.stack) }) }) } const get_disease_detail = async(dom, data) =>{ var { disease, parent } = data; var name_cn = disease load_config(async (config)=>{ var input_data = {name_cn, "detail-type":"ckb_get_disease"} fetch( config.aws_lambda.endPoint, { ...json_options, body: JSON.stringify(input_data) }) .then(res=>res.json()) .then((details) => { if(details.length>0) { var colla_pretty_component = new CollapsePrettyJSONComponent({ title:`${disease} Detail`, dom_id:`desease-detail-${disease}` }); $(dom).append(colla_pretty_component.render(details[0])) } $(parent).append(dom) }) .catch((e) => {console.log(e.stack)}) }) } const get_trial_by = (field) =>{ const get_trial_by_ = async(dom, data) =>{ var { parent } = data; var field_val = data[field] load_config(async (config)=>{ var input_data = { "detail-type":"get_clinic_trial"}; input_data[field] = field_val fetch( config.aws_lambda.endPoint, { ...json_options, body: JSON.stringify(input_data) }) .then(res=>res.json()) .then((details) => { if(details.length>0) var clinical_trial_component = new ClinicalTrialComponent({ button_text:`${field_val} Clinical Trial` }); $(dom).append(clinical_trial_component.render(details)) $(parent).append(dom) }) .catch((e) => {console.log(e.stack)}) }) } return get_trial_by_ } const get_drug_detail = async(dom, data) =>{ var { drug, parent } = data; var input_data = { "detail-type": "ckb_get_drug", "gnameEN":drug } load_config(async (config)=>{ fetch(aws_lambda.endPoint,{ ...json_options, body:JSON.stringify(input_data) }) .then(res=>res.json()) .then((details) => { if(details.length>0) { var colla_pretty_component = new CollapsePrettyJSONComponent({ title:`${drug} Detail`, dom_id:`desease-detail-${drug}` }); $(dom).append(colla_pretty_component.render(details[0])) } $(parent).append(dom) }) .catch((e) => {console.log(e.stack)}) }) } const get_qa_answer = async(dom, data) =>{ var {text,question, answer_dom} = data; var context = text; var input_data = {context, question} load_config( async(config)=>{ fetch( rv_url+"/nlp/bioasq", { ...json_options, body:JSON.stringify(input_data) } ) .then(res=>res.json()) .then( return_data=>{ var {answer, score} = return_data; $(answer_dom).html(answer) } ) .catch( e=>{ $(answer_dom).html(e.stack) } ) } ) } var append_data_on_dom = (dom) =>{ var wrapper = (data) => { console.log("loaded successful", data); $(dom).append(pretty_json(data[0])) } return wrapper } var render_item_list = (data_list, get_specific, slug)=>{ var doms = []; for(var i in data_list){ var name = data_list[i]; doms[i] = document.createElement("div") doms[i].id=`${name}_gc_${slug}_item` $(doms[i]).html(`<h4>${slug}:${name}</h4>`) get_specific( name, append_data_on_dom(doms[i]), (e)=>{$(doms[i]).append(e)}) } return render_list(doms) } // how we manage the selected text in modal var activate_modal=(text) => { var tabs = new Tabs( {target_id:"selected_original_text", content:text, label:"Text", is_active:true}, {target_id:"find_gene_in_text", label:"🧬 Gene"}, {target_id:"find_drug_in_text", label:"💊 Drug",}, {target_id:"find_disease_in_text", label:"🤧 Disease",}, {target_id:"find_mutations_in_text", label:"Mutation"}, {target_id:"translate_en_to_cn", label:"🇨🇳 to_Zh"}, {target_id:"qa_bio", label:"❓ Q&A"} ) create_modal( { title:"Text Helper", dom_id:"selected_text_helper_modal", body:tabs.everything() }) var get_text_f = ()=>{return {text}}; /* =============================== GENE =============================== */ var api_find_gene = new APIAsync("find_gene_in_text"); var genelist_component=new GeneListComponent({callbacks: [get_gene_function,] }); api_find_gene.assign_load( rv_url+"/nlp/find_gene",get_text_f,genelist_component.render, ) /* =============================== MUTATION =============================== */ var api_find_mutation = new APIAsync("find_mutations_in_text"); api_find_mutation.assign_load( rv_url+"/nlp/find_mutations",get_text_f, function(data){ return data.matched_mutations.length?render_list(data.matched_mutations):"No mutation found"} ) /* =============================== DRUG =============================== */ var druglist_component = new DrugListComponent({ callbacks:[ get_drug_detail, get_trial_by("drug") ] }) var api_find_drug = new APIAsync("find_drug_in_text"); api_find_drug.assign_load( rv_url+"/nlp/drug",get_text_f,druglist_component.render ) /* =============================== DISEASE =============================== */ var diseaselist_component = new DiseaseListComponent({ callbacks:[ get_disease_detail, get_trial_by("disease") ] }) var api_find_disease = new APIAsync("find_disease_in_text"); api_find_disease.assign_load( rv_url+"/nlp/find_disease", get_text_f,diseaselist_component.render ) /* =============================== Question & Anwser =============================== */ var qa_component = new QAComponent({ callbacks:[ get_qa_answer ] }); $("#qa_bio").html(qa_component.render({text})) /* =============================== TRANSLATE =============================== */ var api_translate = new APIAsync("translate_en_to_cn"); api_translate.assign_load( rv_url+"/nlp/en_to_cn", get_text_f, (data)=>{ return data.translation?data.translation:"Translation API failed" } ) } var load_material = async() =>{ // load target text material from record var hid = new URLSearchParams(window.location.search).get("hid") $("#text-work-station").html("Loading text material...") await fetch( aws_lambda.endPoint, { ...json_options, body:JSON.stringify({id:hid, "detail-type":"read_doc"}) } ) .then(res=>res.json()) .then((data)=>{ var {doc, gc_user, created_at, id} = data[0] $("#text-work-station").html(doc) $("#doc_created_at").html(created_at) $("#gc_user").html(gc_user) }) } var loud = (text)=>{ console.log(text) } if($("#gc_user").length>0){ load_material() var activate_selection = new ActivateSelection( "#text-work-station",[loud,activate_modal]) } else { $("#analyze").click(function(){ var doc=$("#text-work-station").val(); activate_modal(doc) }) } } $(document).ready(function(){ load_config(execute_code) }) window.CollapseComponent = CollapseComponent<file_sep>console.log("load sa"); var load_config = (callback) =>{ chrome.storage.sync.get( { user_name:false, ds_endpoint:false, query_endpoint:false, api_key:false }, (item)=>{ if((item.user_name==false) || (item.ds_endpoint==false) || (item.query_endpoint==false) || (item.api_key==false) ){ window.location = `chrome-extension://${chrome.runtime.id}/options.html` } else { var config = { gc_user: item.user_name, ravenclaw: {endPoint: item.ds_endpoint}, aws_lambda: {endPoint: item.query_endpoint, api_key: item.api_key} }; callback(config); } } ) } var log_text=(doc)=>{ var load_work_page = async (config) => { var location = window.location.href; var gc_user = config.gc_user; var data = {doc, location, gc_user, "detail-type":"add_doc"}; await fetch( config.aws_lambda.endPoint, { method:"POST", headers: { "x-api-key": config.aws_lambda.api_key, 'Content-Type': 'application/json' }, body:JSON.stringify(data) } ).then(res=>res.json()).then( (data)=>{ console.info(data) var page_id = data.res; // var target_url = `chrome-extension://${chrome.runtime.id}/work.html?hid=${page_id}` var target_url = chrome.runtime.getURL("work.html")+`?hid=${page_id}` // window.open(target_url) chrome.tabs.create({url:target_url}) }).catch(e=>{alert(e.stack)}) } return load_work_page } var select_text_launch = () =>{ chrome.tabs.executeScript(details={file:"tools/collect_tab_text.js"}, (tab)=>{ var text = tab[0]; load_config(log_text(text)) }) } chrome.commands.onCommand.addListener(function(command) { console.log('Command:', command); select_text_launch() });<file_sep># <NAME> > Latin for "Dare to know things", A textual based bioinformatic chrome extension ## It's a Chrome Extension! ### Installation steps * If you are using chrome, go to [this configuration page](chrome://extensions/) * On the upper right corner, turn on "Developer mode" ![developer mode](imgs/install_01.png) * Click "Load unpacked" button ![Load unpacked](imgs/install_02.png) * Select this directory of codes as the root folder ### Hotkey Config * go to [this shortcut setup page](chrome://extensions/shortcuts) * configure the "Study the selected text" hotkey, here I choose "command shift 1" for making example. ![configure hotkey](imgs/install_04.png) ### Server config * Go to options page by click the extension options, fill in every field properly ![server configuration](imgs/install_05.png) ### Enjoy! #### Method A * Go to the interactive draft page, fill in the text yourself ![interactive draft](imgs/install_05.png) #### Method B * Browse any web page, eg pubmed, tcga etc, and select the text you want to analyze * Press the hotkey you've configured (In my example "command shift 1")<file_sep>var load_config = (callback) =>{ chrome.storage.sync.get( { user_name:false, ds_endpoint:false, query_endpoint:false, api_key:false }, (item)=>{ if((item.user_name==false) || (item.ds_endpoint==false) || (item.query_endpoint==false) || (item.api_key==false) ){ window.location = `chrome-extension://${chrome.runtime.id}/options.html` } else { var config = { gc_user: item.user_name, ravenclaw: {endPoint: item.ds_endpoint}, aws_lambda: {endPoint: item.query_endpoint, api_key: item.api_key} }; callback(config) } } ) } export {load_config} <file_sep>import {pretty_json, ce, dom_to_text, abbreviate_long_text} from "./easy_bs.js" const dom_parser = new DOMParser(); const get_rand=()=> String(parseInt(Math.random()*20)) ; class Component{ constructor(properties={}){ Object.assign(this, properties) } render=(data)=>{ this.data=data; this.dom = this.html(data) this.callback(this.dom, data) return this.dom } callback = (dom, data) => { // default no event assigned to dom } run_callbacks = (dom, data) =>{ for(var i in this.callbacks){ var cb = this.callbacks[i]; cb(dom, data); } } } /* +++++++++++++++++++++++++++++++++++++++++ Bootstrap structure +++++++++++++++++++++++++++++++++++++++++ */ class CollapseComponent extends Component{ constructor(properties={}){ super(properties) if(!properties.btn_theme){ this.btn_theme="primary" } } html = (d) => { var {dom_id, body, button_text} = d this.card_body = ce("div",{id:`${dom_id}_body`,className:"card card-body"}); var collapse = ce( "div", {className:"container"},{}, ce("p",{},{}, ce("a",{className:`btn btn-${this.btn_theme}`}, {"data-toggle":"collapse", href:`#${dom_id}`, role:"button", "aria-expanded":false, "aria-controls":dom_id}, button_text) ), ce("div",{className:"collapse",id:dom_id},{}, this.card_body) ) return collapse } callback = ( dom, data ) => { $(dom).find(`#${data.dom_id}_body`).html(data.body) } } class ModalComponent extends Component{ constructor(property={}){ super(property); } html = (data) => { var {title, dom_id, body} = data; this.modal_title = ce("h5",{className:"modal-title"},{},title) this.modal_header = ce( "div",{className:"modal-header"},{}, this.modal_title, ce( "button",{id:`${dom_id}_close`,className:"close"}, {type:"button","data-dismiss":"modal","aria-label":"Close"}, ce("span",{},{"aria-hidden":true},"x")) ) this.modal_body = ce("div",{className:"modal-body",id:"ht_selection_modal_body"},{},body) this.modal_footer = ce("div",{className:"modal-footer"},{}, ce("button",{className:"btn btn-primary"},{type:"button", "data-dismiss":"modal"},"Close") ) this.content = ce( "div", {className:"modal-content"},{}, this.modal_header, this.modal_body, this.modal_footer ) this.document = ce( "div", {className:"modal-dialog modal-lg",role:"document"}, {role:"document"}, this.content ) this.frame = ce("div",{ id:data.dom_id, className:"modal fade", }, {tabindex:"-1",role:"dialog"}, this.document); return this.frame } } class CollapsePrettyJSONComponent extends Component{ constructor(properties={}){ super(properties) if(!this.dom_id){console.error("Has to be a dom_id for CollapsePrettyJSONComponent")} if(!this.title){console.error("Has to be a title for CollapsePrettyJSONComponent")} if(!properties.btn_theme){this.btn_theme="primary"} } html = (d) =>{ return ce("div",{id:`${this.dom_id}-collapse-pretty-json`}) } callback=(dom, data)=>{ var jlist = pretty_json(data); var jcollapse = new CollapseComponent({btn_theme:this.btn_theme}); $(dom).append(jcollapse.render({ button_text: this.title , body: jlist, dom_id:`${this.dom_id}-collapse-component` })) } } /* +++++++++++++++++++++++++++++++++++++++++ GENE +++++++++++++++++++++++++++++++++++++++++ */ class GeneListComponent extends Component{ constructor(properties={}){ super(properties) } html = (d) => { if(d.genes.length==0){ return ce("div",{className:"gene_list_component"},{},"No GENE found") } else{ return ce("div",{className:"gene_list_component"}) } } callback = (dom, d) => { for(var i in d.genes){ var gene = d.genes[i]; var gene_component = new GeneComponent({callbacks:this.callbacks}); gene_component.render({gene, parent:dom}) } } } class GeneComponent extends Component{ constructor(properties={}){ super(properties) } html = (d) => { var {gene} = d return ce( "div", {className:'gene_item_frame',id:`gene_item_${gene}`}, {}, ce("h5",{},{},gene) ) } callback = (dom, data) => { this.run_callbacks(dom, data) } } class GeneFunctionComponent extends Component{ constructor(properties={}){ super(properties) } html = (d) =>{ var data = d[0]; return ce("div",{id:`${data.gene}-gene-function`}) } callback=(dom, d)=>{ var data = d[0]; var jlist = pretty_json(data); var jcollapse = new CollapseComponent({skip_parser:true}); $(dom).append(jcollapse.render({ button_text:`Gene Function ${data.gene}`, body: jlist, dom_id:`gene_function_${data.gene}_collapse` })) } } /* +++++++++++++++++++++++++++++++++++++++++ Disease +++++++++++++++++++++++++++++++++++++++++ */ class DiseaseListComponent extends Component{ constructor(properties={}){ super(properties) } html = (d)=>{ if(d.diseases.length==0){ return ce("div",{className:"disease_list_component"},{},"No Disease Found") } else{ return ce("div",{className:"disease_list_component"}) } } callback = (dom, d) => { for(var i in d.diseases){ var disease = d.diseases[i]; var disease_component = new DiseaseComponent({callbacks:this.callbacks}); disease_component.render({disease, parent:dom}) } } } class DiseaseComponent extends Component{ constructor(properties={}){ super(properties) } html = (d) => { var {disease} = d return ce( "div", {className:'disease_item_frame',id:`disease_item_${disease}`}, {}, ce("h5",{},{},disease) ) } callback = (dom, data) => { this.run_callbacks(dom, data) } } /* +++++++++++++++++++++++++++++++++++++++++ Drug +++++++++++++++++++++++++++++++++++++++++ */ class DrugListComponent extends Component{ constructor(properties={}){ super(properties) } html = (d) =>{ if(d.drugs.length==0){ return ce("div",{className:"drug_list_component"},{},"No drug found") } else{ return ce("div",{className:"drug_list_component"}) } } callback = (dom, d) =>{ for(var i in d.drugs){ var drug = d.drugs[i]; var drug_component = new DrugComponent({callbacks:this.callbacks}); drug_component.render({drug, parent:dom}) } } } class DrugComponent extends Component{ constructor(properties={}){ super(properties) } html = (d) =>{ var {drug} = d; return ce( "div", {className:'drug_item_frame', id:`drug_item_${drug}`}, {}, ce("h5", {}, {}, drug) ) } callback = (dom, data) =>{ this.run_callbacks(dom, data) } } /* +++++++++++++++++++++++++++++++++++++++++ Clinical Trial +++++++++++++++++++++++++++++++++++++++++ */ class ClinicalTrialComponent extends Component{ constructor(properties={}){ super(properties) if(properties.button_text){this.button_text=properties.button_text} else{this.button_text="Clinical Trial"} } html=(data)=>{ var outer_colla = new CollapseComponent(); outer_colla.render({dom_id:`clinical_trial_${get_rand()}`, body:"", button_text:this.button_text}) for(var i in data){ var d=data[i]; var main_title=d.title_cn!=""?d.title_cn:d.title_en; var is_dom = d.dm_or_in=="国内"?"🇨🇳":"🌎" var clinicalal_data = new CollapsePrettyJSONComponent( { btn_theme:"secondary", title:`${ abbreviate_long_text(main_title,30) },${abbreviate_long_text(d.drugs.join(),30)}(${is_dom}${d.code})`, dom_id:`clinical_trial_${d.code}_${i}` }); var {code,disease_text, drugs_text,drugs, phases, dm_or_in, location, gender, age, startdate, url} = d; var original_link = ce( "a", {className:"btn btn-secondary"}, {'href':url, target:"_blank"}, "Open Source Link" ) $(outer_colla.card_body, phases, dm_or_in, url).append( clinicalal_data.render({ code, main_title,disease_text, drugs_text,drugs, phases, gender, age, dm_or_in, location, startdate, original_link }) ) } return outer_colla.dom } } class QAComponent extends Component{ constructor(properties){ super(properties) if(!properties.callbacks){ console.error("has to load callbacks for this component") } } html=(data)=>{ var {text} = data; this.question_input = ce( "input",{className:"form-control"} ) this.btn = ce("button",{className:"btn btn-primary mt-5"},{}, "ask") this.answer = ce("div",{className:"card card-body pt-5"}) var big_card = ce("div",{className:"container"},{}, ce("div",{className:"card card-body pb-5"},{}, ce("label",{className:"label"},{},"Context"),text), ce("label",{className:"label"},{},"Question:"), this.question_input, this.btn, ce("hr"), ce("label",{className:"label"},{},"Answer:"), this.answer ) return big_card } callback=(dom, data)=>{ var qa_comp = this; $(this.btn).click(function () { data["question"] = qa_comp.question_input.value data["answer_dom"] = qa_comp.answer qa_comp.run_callbacks(dom, data) }) } } export {Component, GeneListComponent, GeneFunctionComponent, GeneComponent, CollapseComponent, CollapsePrettyJSONComponent, ModalComponent, DiseaseListComponent, DiseaseComponent, ClinicalTrialComponent, DrugListComponent, DrugComponent, QAComponent }<file_sep>import { load_config } from "./load_config.js"; const utf8_dec = new TextDecoder("utf8"); class Recorder{ constructor(){ } start = (...callbacks) =>{ /* Start recording */ var recorder = this; this.audio_chunks=[]; var audio_chunks = this.audio_chunks; window.is_recording=true window.recorder_now = this navigator.mediaDevices.getUserMedia({audio:true}) .then( (stream)=>{ recorder.mediaRecorder = new MediaRecorder(stream, {audioBitsPerSecond:16000}) recorder.mediaRecorder.start(); recorder.mediaRecorder.addEventListener("dataavailable" , event=>{ audio_chunks.push(event.data); }) recorder.mediaRecorder.addEventListener("stop", ()=>{ const audioBlob = new Blob(audio_chunks, {mimeType:"audio/webm"}); recorder.audioBlob = audioBlob; }) } ) this.run_callbacks(callbacks) } stop = (...callbacks) =>{ this.mediaRecorder.stop() window.is_recording=false this.run_callbacks(callbacks) } play = (...callbacks) =>{ const audio_url = URL.createObjectURL(this.audioBlob); const audio = new Audio(audio_url); audio.play() this.run_callbacks(callbacks) } run_callbacks = (callbacks) =>{ for(var i in callbacks){ var cb =callbacks[i]; cb(this) } } } const to_b64 = (blob, callback)=>{ var reader = new FileReader(); reader.readAsDataURL(blob) reader.onloadend = function() { var base64data = reader.result $("#download-btn").attr("href",base64data) callback(base64data); } } const inputing_text_result = data=>{ if(data.result){ var text = data.result[0] $("#text-work-station").text( $("#text-work-station").text()+String(text) ) } } const dictate = (recorder) =>{ load_config(async(config)=>{ to_b64(recorder.audioBlob,b64data=>{ var byteslen = recorder.audioBlob.size; var format="webm"; var rate=16000; var data = { b64data,byteslen,format, rate } fetch( config.ravenclaw.endPoint+"/nlp/dictate_en", { method:"POST", headers: { 'Content-Type': 'application/json', }, body:JSON.stringify(data) } ).then( res=>res.json() ).then(inputing_text_result) .catch(console.error) }) }) } const record_btn = ()=>{ if(window.is_recording){ var recorder = window.recorder_now; recorder.stop(dictate) }else{ var recorder = new Recorder(); recorder.start() } } $(document).ready( function(){ $("#record-btn").click(record_btn) } )
b273af83faa4379d567346bbc7b1faf91d42cd23
[ "JavaScript", "Markdown" ]
7
JavaScript
raynardj/sapere_aude
8ea47fb1f4989d2ae0a450e039463cee25e287ce
ef33568567bc25d22ff01ecd0e7e6ce7114370bc
refs/heads/master
<repo_name>GuySK/ExData_Plotting1<file_sep>/EDA_PA1.R ## ------------------------------------------------------------------------ uri <- "https://d396qusza40orc.cloudfront.net/exdata%2Fdata%2Fhousehold_power_consumption.zip" zipfn <- "household_power_consumption.zip" unzip(zipfn) fn <- "household_power_consumption.txt" ## ----checkSize, results='hide'------------------------------------------- checkSize <- function(fn) { finfo <- file.info(fn) # get file information fsize <- round(finfo[1,1]/(2**20),0) # file size in MB memsize <- memory.limit() # system memory available for R round(fsize / memsize,2) # report proportion } ## ----check--------------------------------------------------------------- checkSize(fn) hpc <- read.table(fn, sep=";", header=TRUE) head(hpc,2) ## ----dat, results='hide'------------------------------------------------- dat <- function(x) {as.Date(as.character(x), "%d/%m/%Y")} ## ------------------------------------------------------------------------ from.date <- as.Date("01-02-2007", "%d-%m-%Y") to.date <- as.Date("02-02-2007", "%d-%m-%Y") hpc2 <- hpc[((dat(hpc[,1]) == from.date) | (dat(hpc[,1]) == to.date)),] head(hpc2[,1:2],2) tail(hpc2[,1:2],2) rm(hpc) hpc <- hpc2 rm(hpc2) ## ----Plot1, results='hide'----------------------------------------------- fac.as.numeric <- function(x) {as.numeric(as.character(x))} gap <- fac.as.numeric(hpc[,3]) plname <- "plot1.png" png(plname, height=480, width=480) xlab="Global Active Power (kilowatts)" title <- "Global Active Power" color <- "red" hist(gap,col=color, xlab=xlab, main=title) dev.off() ## ----TimeStamp----------------------------------------------------------- hpc.dt <- strptime(paste(hpc[,1], hpc[,2]), format="%d/%m/%Y %H:%M:%S") hpc2 <- cbind(hpc.dt,hpc[,3:9]) colnames(hpc2)[1] <- "TimeStamp" hpc2$Global_active_power <- gap ## ----Plot2,results='hide'------------------------------------------------ plname <- "plot2.png" png(plname, height=480, width=480) ylab <- "Global Active Power (kilowatts)" with(hpc2, plot(TimeStamp, Global_active_power, xlab="", ylab=ylab, type="l")) dev.off() ## ------------------------------------------------------------------------ hpc2$Sub_metering_1 <- fac.as.numeric(hpc2$Sub_metering_1) hpc2$Sub_metering_2 <- fac.as.numeric(hpc2$Sub_metering_2) ## ----Plot3,results='hide'------------------------------------------------ plname <- "plot3.png" png(plname, height=480, width=480) ylabel <- "Energy Sub metering" with(hpc2, plot(TimeStamp, Sub_metering_1, ylab=ylabel, type="n")) with(hpc2, lines(TimeStamp, Sub_metering_1)) with(hpc2, lines(TimeStamp, Sub_metering_2,col="red")) with(hpc2, lines(TimeStamp, Sub_metering_3,col="blue")) legend("topright",lty=1, pt.cex=1, cex=0.5, seg.len=0.5, col=c("black","red","blue"), legend=colnames(hpc2)[6:8]) dev.off() ## ----Plot4.1------------------------------------------------------------- hpc2$Voltage <- fac.as.numeric(hpc2$Voltage) hpc2$Global_reactive_power <- fac.as.numeric(hpc2$Global_reactive_power) ## ----Plot4.2,results='hide'---------------------------------------------- plname <- "plot4.png" png(plname, height=480, width=480) par(mfrow = c(2, 2)) # Global Active Power 1/4 with(hpc2, plot(TimeStamp, Global_active_power, xlab="", ylab=ylab, cex.lab=0.75, type="l")) # Voltage 2/4 with(hpc2, plot(TimeStamp, Voltage, xlab="datetime", cex.lab=0.75, type="l")) # Energy ub metering 3/4 with(hpc2, plot(TimeStamp, Sub_metering_1, xlab="", ylab="", type = "n")) title(ylab="Energy Sub metering", xlab="", cex.lab=0.75) legend("topright", legend=colnames(hpc2)[6:8], col=c("black","blue","red"), lty=1, cex=0.5, seg.len=0.5, bty="n", yjust=1,) with(hpc2, lines(TimeStamp, Sub_metering_1)) with(hpc2, lines(TimeStamp, Sub_metering_2,col="red")) with(hpc2, lines(TimeStamp, Sub_metering_3,col="blue")) # Global Reactive Power 4/4 with(hpc2, plot(TimeStamp, Global_reactive_power, type="l", xlab="datetime", cex.lab=0.75)) dev.off() <file_sep>/README.md ExData_Plotting1 ================ # Exploratory Data Analysis ## Course Project 1 ### Table of contents 1. EDA_PA1.R *R code to generate plots* 2. EDA_PA1.md *Code documentation* 3. EDA_PA1.Rmd *Same as above but in Rmd format* 4. plot1.png *Plot files* 3. plot2.png 4. plot3.png 5. plot4.png <file_sep>/EDA_PA1.Rmd Exploratory Data Analysis ========================= # Course Project 1 ## Loading all data into a data frame The following code is used to download the dataset and unzip it. Before reading it unto a dataframe, we will check if there is enough memory in the system. ``` {r} uri <- "https://d396qusza40orc.cloudfront.net/exdata%2Fdata%2Fhousehold_power_consumption.zip" zipfn <- "household_power_consumption.zip" unzip(zipfn) fn <- "household_power_consumption.txt" ``` The following function is used to check if there is enough memory available. ```{r checkSize, results='hide'} checkSize <- function(fn) { finfo <- file.info(fn) # get file information fsize <- round(finfo[1,1]/(2**20),0) # file size in MB memsize <- memory.limit() # system memory available for R round(fsize / memsize,2) # report proportion } ``` In our case, we have no problems in our system. The file size is just a small proportion of our memory. So, we go on to read it. ``` {r check} checkSize(fn) hpc <- read.table(fn, sep=";", header=TRUE) head(hpc,2) ``` ## Selecting data between required dates The Date variable is stored as factor, so the following function is defined to simplify the selection of data in the required timeframe. ```{r dat, results='hide'} dat <- function(x) {as.Date(as.character(x), "%d/%m/%Y")} ``` Now the appropriate dates are selected and the rest is removed from the environment in order to free memory. The resulting data set is named hpc, for 'household power consumption'. ``` {r} from.date <- as.Date("01-02-2007", "%d-%m-%Y") to.date <- as.Date("02-02-2007", "%d-%m-%Y") hpc2 <- hpc[((dat(hpc[,1]) == from.date) | (dat(hpc[,1]) == to.date)),] head(hpc2[,1:2],2) tail(hpc2[,1:2],2) rm(hpc) hpc <- hpc2 rm(hpc2) ``` ## Plot 1 We convert factors to numerics as needed and proceed to plot. Plots are saved to disc by using the png device and therefore they are not shown in this document, but they are available as separate files. ``` {r Plot1, results='hide'} fac.as.numeric <- function(x) {as.numeric(as.character(x))} gap <- fac.as.numeric(hpc[,3]) plname <- "plot1.png" png(plname, height=480, width=480) xlab="Global Active Power (kilowatts)" title <- "Global Active Power" color <- "red" hist(gap,col=color, xlab=xlab, main=title) dev.off() ``` ## Plot 2 We will now create a new variable TimeStamp to replace Date and Time, since we need to plot all points. We use a new dataframe, just in case we need the old Date and Time variables again. ``` {r TimeStamp} hpc.dt <- strptime(paste(hpc[,1], hpc[,2]), format="%d/%m/%Y %H:%M:%S") hpc2 <- cbind(hpc.dt,hpc[,3:9]) colnames(hpc2)[1] <- "TimeStamp" hpc2$Global_active_power <- gap ``` We are now, ready to plot. ``` {r Plot2,results='hide'} plname <- "plot2.png" png(plname, height=480, width=480) ylab <- "Global Active Power (kilowatts)" with(hpc2, plot(TimeStamp, Global_active_power, xlab="", ylab=ylab, type="l")) dev.off() ``` ## Plot 3 Plot 3 shows all sub meterings together. Before plotting, we convert factors to numeric as usual. ``` {r} hpc2$Sub_metering_1 <- fac.as.numeric(hpc2$Sub_metering_1) hpc2$Sub_metering_2 <- fac.as.numeric(hpc2$Sub_metering_2) ``` ``` {r Plot3,results='hide'} plname <- "plot3.png" png(plname, height=480, width=480) ylabel <- "Energy Sub metering" with(hpc2, plot(TimeStamp, Sub_metering_1, ylab=ylabel, type="n")) with(hpc2, lines(TimeStamp, Sub_metering_1)) with(hpc2, lines(TimeStamp, Sub_metering_2,col="red")) with(hpc2, lines(TimeStamp, Sub_metering_3,col="blue")) legend("topright",lty=1, pt.cex=1, cex=0.5, seg.len=0.5, col=c("black","red","blue"), legend=colnames(hpc2)[6:8]) dev.off() ``` ## Plot 4 Plot 4 is particular because it contains four different graphs. Before plotting, we need to convert factors to numeric, as usual. ``` {r Plot4.1} hpc2$Voltage <- fac.as.numeric(hpc2$Voltage) hpc2$Global_reactive_power <- fac.as.numeric(hpc2$Global_reactive_power) ``` In this case, we use the parameter 'mfrow' and the order in which the graphs are plotted to define the position of each graph in the page. ``` {r Plot4.2,results='hide'} plname <- "plot4.png" png(plname, height=480, width=480) par(mfrow = c(2, 2)) # Global Active Power 1/4 with(hpc2, plot(TimeStamp, Global_active_power, xlab="", ylab=ylab, cex.lab=0.75, type="l")) # Voltage 2/4 with(hpc2, plot(TimeStamp, Voltage, xlab="datetime", cex.lab=0.75, type="l")) # Energy ub metering 3/4 with(hpc2, plot(TimeStamp, Sub_metering_1, xlab="", ylab="", type = "n")) title(ylab="Energy Sub metering", xlab="", cex.lab=0.75) legend("topright", legend=colnames(hpc2)[6:8], col=c("black","blue","red"), lty=1, cex=0.5, seg.len=0.5, bty="n", yjust=1,) with(hpc2, lines(TimeStamp, Sub_metering_1)) with(hpc2, lines(TimeStamp, Sub_metering_2,col="red")) with(hpc2, lines(TimeStamp, Sub_metering_3,col="blue")) # Global Reactive Power 4/4 with(hpc2, plot(TimeStamp, Global_reactive_power, type="l", xlab="datetime", cex.lab=0.75)) dev.off() ```<file_sep>/EDA_PA1.md Exploratory Data Analysis ========================= # Course Project 1 ## Loading all data into a data frame The following code is used to download the dataset and unzip it. Before reading it unto a dataframe, we will check if there is enough memory in the system. ```r uri <- "https://d396qusza40orc.cloudfront.net/exdata%2Fdata%2Fhousehold_power_consumption.zip" zipfn <- "household_power_consumption.zip" unzip(zipfn) fn <- "household_power_consumption.txt" ``` The following function is used to check if there is enough memory available. ```r checkSize <- function(fn) { finfo <- file.info(fn) # get file information fsize <- round(finfo[1,1]/(2**20),0) # file size in MB memsize <- memory.limit() # system memory available for R round(fsize / memsize,2) # report proportion } ``` In our case, we have no problems in our system. The file size is just a small proportion of our memory. So, we go on to read it. ```r checkSize(fn) ``` ``` ## [1] 0.04 ``` ```r hpc <- read.table(fn, sep=";", header=TRUE) head(hpc,2) ``` ``` ## Date Time Global_active_power Global_reactive_power Voltage ## 1 16/12/2006 17:24:00 4.216 0.418 234.840 ## 2 16/12/2006 17:25:00 5.360 0.436 233.630 ## Global_intensity Sub_metering_1 Sub_metering_2 Sub_metering_3 ## 1 18.400 0.000 1.000 17 ## 2 23.000 0.000 1.000 16 ``` ## Selecting data between required dates The Date variable is stored as factor, so the following function is defined to simplify the selection of data in the required timeframe. ```r dat <- function(x) {as.Date(as.character(x), "%d/%m/%Y")} ``` Now the appropriate dates are selected and the rest is removed from the environment in order to free memory. The resulting data set is named hpc, for 'household power consumption'. ```r from.date <- as.Date("01-02-2007", "%d-%m-%Y") to.date <- as.Date("02-02-2007", "%d-%m-%Y") hpc2 <- hpc[((dat(hpc[,1]) == from.date) | (dat(hpc[,1]) == to.date)),] head(hpc2[,1:2],2) ``` ``` ## Date Time ## 66637 1/2/2007 00:00:00 ## 66638 1/2/2007 00:01:00 ``` ```r tail(hpc2[,1:2],2) ``` ``` ## Date Time ## 69515 2/2/2007 23:58:00 ## 69516 2/2/2007 23:59:00 ``` ```r rm(hpc) hpc <- hpc2 rm(hpc2) ``` ## Plot 1 We convert factors to numerics as needed and proceed to plot. Plots are saved to disc by using the png device and therefore they are not shown in this document, but they are available as separate files. ```r fac.as.numeric <- function(x) {as.numeric(as.character(x))} gap <- fac.as.numeric(hpc[,3]) plname <- "plot1.png" png(plname, height=480, width=480) xlab="Global Active Power (kilowatts)" title <- "Global Active Power" color <- "red" hist(gap,col=color, xlab=xlab, main=title) dev.off() ``` ## Plot 2 We will now create a new variable TimeStamp to replace Date and Time, since we need to plot all points. We use a new dataframe, just in case we need the old Date and Time variables again. ```r hpc.dt <- strptime(paste(hpc[,1], hpc[,2]), format="%d/%m/%Y %H:%M:%S") hpc2 <- cbind(hpc.dt,hpc[,3:9]) colnames(hpc2)[1] <- "TimeStamp" hpc2$Global_active_power <- gap ``` We are now, ready to plot. ```r plname <- "plot2.png" png(plname, height=480, width=480) ylab <- "Global Active Power (kilowatts)" with(hpc2, plot(TimeStamp, Global_active_power, xlab="", ylab=ylab, type="l")) dev.off() ``` ## Plot 3 Plot 3 shows all sub meterings together. Before plotting, we convert factors to numeric as usual. ```r hpc2$Sub_metering_1 <- fac.as.numeric(hpc2$Sub_metering_1) hpc2$Sub_metering_2 <- fac.as.numeric(hpc2$Sub_metering_2) ``` ```r plname <- "plot3.png" png(plname, height=480, width=480) ylabel <- "Energy Sub metering" with(hpc2, plot(TimeStamp, Sub_metering_1, ylab=ylabel, type="n")) with(hpc2, lines(TimeStamp, Sub_metering_1)) with(hpc2, lines(TimeStamp, Sub_metering_2,col="red")) with(hpc2, lines(TimeStamp, Sub_metering_3,col="blue")) legend("topright",lty=1, pt.cex=1, cex=0.5, seg.len=0.5, col=c("black","red","blue"), legend=colnames(hpc2)[6:8]) dev.off() ``` ## Plot 4 Plot 4 is particular because it contains four different graphs. Before plotting, we need to convert factors to numeric, as usual. ```r hpc2$Voltage <- fac.as.numeric(hpc2$Voltage) hpc2$Global_reactive_power <- fac.as.numeric(hpc2$Global_reactive_power) ``` In this case, we use the parameter 'mfrow' and the order in which the graphs are plotted to define the position of each graph in the page. ```r plname <- "plot4.png" png(plname, height=480, width=480) par(mfrow = c(2, 2)) # Global Active Power 1/4 with(hpc2, plot(TimeStamp, Global_active_power, xlab="", ylab=ylab, cex.lab=0.75, type="l")) # Voltage 2/4 with(hpc2, plot(TimeStamp, Voltage, xlab="datetime", cex.lab=0.75, type="l")) # Energy ub metering 3/4 with(hpc2, plot(TimeStamp, Sub_metering_1, xlab="", ylab="", type = "n")) title(ylab="Energy Sub metering", xlab="", cex.lab=0.75) legend("topright", legend=colnames(hpc2)[6:8], col=c("black","blue","red"), lty=1, cex=0.5, seg.len=0.5, bty="n", yjust=1,) with(hpc2, lines(TimeStamp, Sub_metering_1)) with(hpc2, lines(TimeStamp, Sub_metering_2,col="red")) with(hpc2, lines(TimeStamp, Sub_metering_3,col="blue")) # Global Reactive Power 4/4 with(hpc2, plot(TimeStamp, Global_reactive_power, type="l", xlab="datetime", cex.lab=0.75)) dev.off() ```
c91ce01f5fb7e6059f3de1d70ae1e88daf1dd2bf
[ "Markdown", "R", "RMarkdown" ]
4
R
GuySK/ExData_Plotting1
184ed5771309585114a9fa5abe78ada8065b180f
84b2bd11bb0efd5c48eb10ccd0582f9804efa46f
refs/heads/master
<repo_name>Nero-Zjf/com.nero.servlet<file_sep>/servlet-upload/src/main/java/servlet/upload/UploadServlet.java package servlet.upload; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; /** * @created zjf * @date 2019/7/22 14:08 */ public class UploadServlet extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { if (req.getContentLength() > 0) { InputStream inputStream = null; FileOutputStream outputStream = null; try { inputStream = req.getInputStream(); // 给新文件拼上时间毫秒,防止重名 long now = System.currentTimeMillis(); String fileSavePath = this.getServletContext().getRealPath("") + "WEB-INF\\upload"; File parentFile = new File(fileSavePath); if (!parentFile.exists() && !parentFile.isDirectory()) { System.out.println("目录或文件不存在!"); if (!parentFile.mkdir()) { System.out.println("添加目录失败!"); return; } } File file = new File(fileSavePath, "file-" + now + ".txt"); if (!file.createNewFile()) { System.out.println("创建上传的文件失败!"); return; } outputStream = new FileOutputStream(file); //计算上传时间 long calTimeStart = System.currentTimeMillis(); byte temp[] = new byte[1024]; int size = -1; while ((size = inputStream.read(temp)) != -1) { // 每次读取1KB,直至读完 outputStream.write(temp, 0, size); } //此种方式上传的文件会比实际文件多出一些请求头信息,需要编写逻辑将多余信息过滤 long calTimeEnd = System.currentTimeMillis(); System.out.println("File load success. time=" + (calTimeEnd - calTimeStart)); } catch (Exception e) { System.out.println("File load fail."); } finally { if (outputStream != null) { outputStream.close(); } if (inputStream != null) { inputStream.close(); } } } } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { doGet(req, resp); } } <file_sep>/README.md # com.nero.servlet java web servlet <file_sep>/servlet-upload/src/main/java/servlet/upload/CommonUploadServlet.java package servlet.upload; import org.apache.commons.fileupload.FileItem; import org.apache.commons.fileupload.disk.DiskFileItemFactory; import org.apache.commons.fileupload.servlet.ServletFileUpload; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.util.List; /** * 使用Common-fileupload组件来实现上传 * * @created zjf * @date 2019/7/22 17:30 */ public class CommonUploadServlet extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { if (req.getContentLength() > 0) { InputStream inputStream = null; try { inputStream = req.getInputStream(); // 给新文件拼上时间毫秒,防止重名 long now = System.currentTimeMillis(); String fileSavePath = this.getServletContext().getRealPath("/WEB-INF/upload"); File parentFile = new File(fileSavePath); if (!parentFile.exists() && !parentFile.isDirectory()) { System.out.println("目录或文件不存在!"); if (!parentFile.mkdir()) { System.out.println("添加目录失败!"); return; } } //使用Apache文件上传组件处理文件上传步骤: //1、创建一个DiskFileItemFactory工厂 DiskFileItemFactory factory = new DiskFileItemFactory(); //2、创建一个文件上传解析器 ServletFileUpload upload = new ServletFileUpload(factory); //解决上传文件名的中文乱码 upload.setHeaderEncoding("UTF-8"); //3、判断提交上来的数据是否是上传表单的数据 if (!ServletFileUpload.isMultipartContent(req)) { //按照传统方式获取数据 return; } //4、使用ServletFileUpload解析器解析上传数据,解析结果返回的是一个List<FileItem>集合,每一个FileItem对应一个Form表单的输入项 List<FileItem> list = upload.parseRequest(req); //计算上传时间 long calTimeStart = System.currentTimeMillis(); for (FileItem item : list) { //如果fileitem中封装的是普通输入项的数据 if (item.isFormField()) { String name = item.getFieldName(); //解决普通输入项的数据的中文乱码问题 String value = item.getString("UTF-8"); //value = new String(value.getBytes("iso8859-1"),"UTF-8"); System.out.println(name + "=" + value); } else {//如果fileitem中封装的是上传文件 //得到上传的文件名称, String filename = item.getName(); System.out.println(filename); if (filename == null || filename.trim().equals("")) { continue; } //注意:不同的浏览器提交的文件名是不一样的,有些浏览器提交上来的文件名是带有路径的,如: c:\a\b\1.txt,而有些只是单纯的文件名,如:1.txt //处理获取到的上传文件的文件名的路径部分,只保留文件名部分 filename = filename.substring(filename.lastIndexOf("\\") + 1); //获取item中的上传文件的输入流 InputStream in = item.getInputStream(); //创建一个文件输出流 FileOutputStream out = new FileOutputStream(fileSavePath + "\\" + filename); //创建一个缓冲区 byte buffer[] = new byte[1024]; //判断输入流中的数据是否已经读完的标识 int len = 0; //循环将输入流读入到缓冲区当中,(len=in.read(buffer))>0就表示in里面还有数据 while ((len = in.read(buffer)) > 0) { //使用FileOutputStream输出流将缓冲区的数据写入到指定的目录(savePath + "\\" + filename)当中 out.write(buffer, 0, len); } //关闭输入流 in.close(); //关闭输出流 out.close(); //删除处理文件上传时生成的临时文件 item.delete(); System.out.println("文件上传成功!"); } } long calTimeEnd = System.currentTimeMillis(); System.out.println("File load success. time=" + (calTimeEnd - calTimeStart)); } catch (Exception e) { System.out.println("File load fail."); } finally { if (inputStream != null) { inputStream.close(); } } } } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { this.doGet(req, resp); } }
a757883f5de6c88964b26e261c8605aeade31537
[ "Markdown", "Java" ]
3
Java
Nero-Zjf/com.nero.servlet
29f5a9b5e69b03f0cb8aca63776509326c39c53d
5029241b9bff81308ddc53d9cff37829431b46a3
refs/heads/master
<file_sep>let icons = ["F", "P", "H"] let i = -50 let myId = "d" let icon = "" let stop = 0 let list = [''] // basic.forever(function () { // let c = input.temperature() // // let f = (c * 18) / 10 + 32 // basic.showNumber(parseInt('32')) // }) function show_flash() { for (let index = 0; index < 3; index++) { basic.showIcon(IconNames.Yes) basic.pause(500) basic.clearScreen() basic.pause(500) } } radio.setGroup(99) // function parse(msg: string) { // return [msg.charAt(0), msg.charAt(1), msg.charAt(2), msg.substr(3, msg.length - 3)]; // } // let icons = parse(st); // [originID, piReceived, originRecieved^2, message] // need to find a way input.onButtonPressed(Button.A, function () { if (i == -50) { i = 0 } else if (i == 0) { i = icons.length - 1 } else { i = i - 1 } basic.showString(icons[i]) }) input.onButtonPressed(Button.B, function () { if (i == -50) { i = 0 } else if (i == icons.length - 1) { i = 0 } else { i = i + 1 } icon = icons[i] basic.showString(icon) }) input.onButtonPressed(Button.AB, function () { stop = 0 if (i == -50) { i = 0 } let c = input.temperature() let st = myId + "00" + icons[i] + c.toString() radio.sendString(st) basic.showString(st) }) radio.onReceivedString(function (receivedString) { let msg = receivedString basic.showString(receivedString) basic.pause(1000) if (myId != "d") { if (stop == 0) { if (msg[0] != myId) { radio.sendString(msg); basic.showIcon(IconNames.LeftTriangle) if (msg[1] == '1' && msg[2] == '1') { show_flash() stop = 1 } } else { if (msg[1] == "1" && msg[0] == myId) { radio.sendString(myId + "1" + "1" + msg.substr(3, msg.length - 3)) stop = 1 show_flash() } } } } else { if (msg[1] == "0" && msg[2] == "0") { if (list.indexOf(msg) == -1) { serial.writeString(msg) radio.sendString(msg[0] + "1" + "0" + msg.substr(3, msg.length - 3)) show_flash() list.push(msg) } } } }) <file_sep>import serial import requests import json import random def getCoords(): return [str(random.uniform(-25, 20)), str(random.uniform(120, 145))] coords = { 'a': [str(random.uniform(-25, 20)), str(random.uniform(130, 135))], 'b': [str(random.uniform(-25, 20)), str(random.uniform(130, 135))], 'c': [str(random.uniform(-25, 20)), str(random.uniform(130, 135))], 'd': [str(random.uniform(-25, 20)), str(random.uniform(130, 135))], } while True: try: ser = serial.Serial("/dev/ttyACM0", 115200, timeout=2) ser.flushInput() ser.flushOutput() data = ser.readline() if data is not b'': data = data.decode("UTF-8") print(data) id = data[0] message = data[3] body = json.dumps({ 'type': message, 'lat': getCoords()[0], 'long': getCoords()[1], 'time': 154345345235, 'origin': id, 'temp': data[4:] }) res = requests.post("https://m9po41o830.execute-api.eu-west-1.amazonaws.com/dev/event", data=body) print(res) except Exception as e: print(str(e)) pass <file_sep>![logo](assets/logo.png) A basic implementation of a mesh network using low-power, low-cost micro:bit devices for disaster reporting. Created for Visa Graduate Hackathon, January 2019. [thekeshavgoel](https://github.com/thekeshavgoel) || [HartBlanc](https://github.com/HartBlanc) || [salmansamie](https://github.com/salmansamie) ### How the network works The mesh is built up of BBC micro:bit devices, each allowing the user to send a message from a selection of emergency services required. Once the message is broadcast from the origin, it is picked up by surrounding devices and passed on until it reaches the internet-connected basestation. Once the basestation receives the message and POSTs it to AWS, it broadcasts an ACK which is propogated back through the network. ### Why * Communication in disaster situations is hard, and traditional GSM is extremely high-overhead and doesn't scale well with high load in close-proximity. * Devices that offer GPS capability are expensive, and have lower market penetration in areas where they'd be most useful. * Mobile phones have high power consumption, and are likely to be more fragile than a more primitive device with a battery life of months, not days. ### GUI To run the GUI, simply load the site at [salmansamie.github.io/microalert](https://salmansamie.github.io/microalert), or open index.html locally. ![GUI](assets/gui.png)
836757581976238db927d5f7df6a6b4fdc72a41e
[ "JavaScript", "Python", "Markdown" ]
3
JavaScript
salmansamie/microalert
c433dc7bab5c56602d611274abdeb4e53ce836f4
c231c6da0fde5a067ed90040aead93c44cd9e228
refs/heads/master
<repo_name>nphilipp/tiny-stage<file_sep>/README.md # tiny-stage An attempt to set up freeipafas, fasjson and noggin so we can test auth without stage. ``` $ sudo dnf install ansible libvirt vagrant-libvirt vagrant-sshfs vagrant-hostmanager $ sudo systemctl enable libvirtd $ sudo systemctl start libvirtd ``` then run vagrant with: ``` $ vagrant up ``` IPA will be at http://ipa.tinystage.test/ and fasjson at http://fasjson.tinystage.test/fasjson ## TODO * add ipsilon * run IPA data gen script on provision (there is a bash alias to run it afterwards, just need to add it to the provisioning) * add another app that uses ipsilon for identity * add noggin itself maybe <file_sep>/ansible/roles/freeipa/files/.bashrc # .bashrc alias tinystage-ipa-resetdb="sudo ipa-restore /var/lib/ipa/backup/backup-clean -p adminPassw0rd!" alias tinystage-ipa-populatedb="poetry run python /vagrant/devel/create-test-data.py" <file_sep>/ansible/roles/freeipa/files/create_dummy_data.py #!/usr/bin/env python3 from faker import Faker import python_freeipa USER_PASSWORD = "<PASSWORD>" fake = Faker() fake.seed_instance(0) ipa = python_freeipa.ClientLegacy( host="ipa.example.test", verify_ssl="/etc/ipa/ca.crt" ) ipa.login("admin", "<PASSWORD>!") # create a developers fasgroup try: ipa.group_add("developers", "A group for developers", fasgroup=True) except python_freeipa.exceptions.FreeIPAError as e: print(e) # create a designers fasgroup try: ipa.group_add("designers", "A group for designers", fasgroup=True) except python_freeipa.exceptions.FreeIPAError as e: print(e) for x in range(50): firstName = fake.first_name() lastName = fake.last_name() username = firstName + lastName fullname = firstName + " " + lastName print(f"adding user {fullname}") try: ipa.user_add( username, firstName, lastName, fullname, fasircnick=[username, username + "_"], faslocale="en-US", fastimezone="Australia/Brisbane", fasstatusnote="active", fasgpgkeyid=[], ) if x % 3 == 0: ipa.group_add_member("developers", username) if x < 10: ipa._request( "group_add_member_manager", "developers", {"user": username}, ) if x % 5 == 0: ipa.group_add_member("designers", username) if x <= 15: ipa._request( "group_add_member_manager", "designers", {"user": username}, ) except python_freeipa.exceptions.FreeIPAError as e: print(e) <file_sep>/Vagrantfile # -*- mode: ruby -*- # vi: set ft=ruby : ENV['VAGRANT_NO_PARALLEL'] = 'yes' Vagrant.configure(2) do |config| config.hostmanager.enabled = true config.hostmanager.manage_host = true config.hostmanager.manage_guest = true config.vm.define "freeipa" do |freeipa| freeipa.vm.box_url = "https://download.fedoraproject.org/pub/fedora/linux/releases/32/Cloud/x86_64/images/Fedora-Cloud-Base-Vagrant-32-1.6.x86_64.vagrant-libvirt.box" freeipa.vm.box = "f32-cloud-libvirt" freeipa.vm.hostname = "ipa.tinystage.test" freeipa.hostmanager.aliases = ("kerberos.tinystage.test") freeipa.vm.synced_folder ".", "/vagrant", disabled: true freeipa.vm.provider :libvirt do |libvirt| libvirt.cpus = 2 libvirt.memory = 2048 end # Vagrant adds '127.0.0.1 ipa.example.test ipa' as the first line in /etc/hosts # and freeipa doesnt like that, so we remove it freeipa.vm.provision "shell", inline: "sudo sed -i '1d' /etc/hosts" freeipa.vm.provision "ansible" do |ansible| ansible.playbook = "ansible/freeipa.yml" end end config.vm.define "fasjson" do |fasjson| fasjson.vm.box_url = "https://download.fedoraproject.org/pub/fedora/linux/releases/32/Cloud/x86_64/images/Fedora-Cloud-Base-Vagrant-32-1.6.x86_64.vagrant-libvirt.box" fasjson.vm.box = "f32-cloud-libvirt" fasjson.vm.hostname = "fasjson.tinystage.test" fasjson.vm.synced_folder ".", "/vagrant", disabled: true fasjson.vm.provider :libvirt do |libvirt| libvirt.cpus = 2 libvirt.memory = 2048 end fasjson.vm.provision "ansible" do |ansible| ansible.playbook = "ansible/fasjson.yml" end end end
645095541524d1d6dd186862747fcc110563a8d6
[ "Markdown", "Python", "Ruby", "Shell" ]
4
Markdown
nphilipp/tiny-stage
8c786a594bbcca9f0fbbcc7e22c691b529f29b94
d6993e966f83382f851ff8410dcdc8a1db861494
refs/heads/master
<file_sep>package net.wtako.WTAKOProfiler; import java.io.File; import java.io.IOException; import java.sql.SQLException; import java.util.logging.Level; import java.util.logging.Logger; import net.milkbowl.vault.economy.Economy; import net.wtako.WTAKOProfiler.Commands.CommandProfile; import net.wtako.WTAKOProfiler.Methods.InfoShower; import net.wtako.WTAKOProfiler.Methods.MemoryDatabase; import net.wtako.WTAKOProfiler.Schedulers.CheckScheduler; import net.wtako.WTAKOProfiler.Schedulers.GlobalCheckScheduler; import net.wtako.WTAKOProfiler.Utils.Config; import net.wtako.WTAKOProfiler.Utils.Lang; import org.bukkit.configuration.file.YamlConfiguration; import org.bukkit.entity.Player; import org.bukkit.plugin.RegisteredServiceProvider; import org.bukkit.plugin.java.JavaPlugin; import org.bukkit.scoreboard.DisplaySlot; public final class Main extends JavaPlugin { private static Main instance; public static String artifactId; public static YamlConfiguration LANG; public static File LANG_FILE; public static Logger log = Logger.getLogger("WTAKOProfiler"); public static Economy economy = null; @Override public void onEnable() { Main.instance = this; Main.artifactId = getProperty("artifactId"); getCommand(getProperty("mainCommand")).setExecutor(new CommandProfile()); Config.saveAll(); loadLang(); if (Config.CHECK_ECON.getBoolean()) { setupEconomy(); } if (MemoryDatabase.getInstance() == null) { try { new MemoryDatabase(); } catch (final SQLException e) { e.printStackTrace(); } } if (Config.INFOBOX_ENABLED.getBoolean() && CheckScheduler.getInstance() == null) { new CheckScheduler(); } if (Config.INFOBOX_ENABLED.getBoolean() && GlobalCheckScheduler.getInstance() == null) { new GlobalCheckScheduler(); } } @Override public void onDisable() { CheckScheduler.reload(); InfoShower.reload(); for (final Player player: getServer().getOnlinePlayers()) { player.getScoreboard().clearSlot(DisplaySlot.SIDEBAR); } } public void loadLang() { final File lang = new File(getDataFolder(), "messages.yml"); if (!lang.exists()) { try { getDataFolder().mkdir(); lang.createNewFile(); final YamlConfiguration defConfig = YamlConfiguration.loadConfiguration(lang); defConfig.save(lang); Lang.setFile(defConfig); return; } catch (final IOException e) { e.printStackTrace(); // So they notice Main.log.severe("[" + Main.getInstance().getName() + "] Couldn't create language file."); Main.log.severe("[" + Main.getInstance().getName() + "] This is a fatal error. Now disabling"); setEnabled(false); // Without it loaded, we can't send them // messages } } final YamlConfiguration conf = YamlConfiguration.loadConfiguration(lang); for (final Lang item: Lang.values()) { if (conf.getString(item.getPath()) == null) { conf.set(item.getPath(), item.getDefault()); } } Lang.setFile(conf); Main.LANG = conf; Main.LANG_FILE = lang; try { conf.save(getLangFile()); } catch (final IOException e) { Main.log.log(Level.WARNING, "[" + Main.getInstance().getName() + "] Failed to save messages.yml."); Main.log.log(Level.WARNING, "[" + Main.getInstance().getName() + "] Report this stack trace to " + getProperty("author") + "."); e.printStackTrace(); } } private boolean setupEconomy() { final RegisteredServiceProvider<Economy> economyProvider = getServer().getServicesManager().getRegistration( net.milkbowl.vault.economy.Economy.class); if (economyProvider != null) { Main.economy = economyProvider.getProvider(); } return (Main.economy != null); } /** * Gets the messages.yml config. * * @return The messages.yml config. */ public YamlConfiguration getLang() { return Main.LANG; } /** * Get the messages.yml file. * * @return The messages.yml file. */ public File getLangFile() { return Main.LANG_FILE; } @SuppressWarnings("deprecation") public String getProperty(String key) { final YamlConfiguration spawnConfig = YamlConfiguration.loadConfiguration(getResource("plugin.yml")); return spawnConfig.getString(key); } public static Main getInstance() { return Main.instance; } } <file_sep>package net.wtako.WTAKOProfiler.Schedulers; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import net.wtako.WTAKOProfiler.Main; import net.wtako.WTAKOProfiler.Methods.InfoShower; import net.wtako.WTAKOProfiler.Methods.MemoryDatabase; import net.wtako.WTAKOProfiler.Utils.Config; import org.bukkit.scheduler.BukkitRunnable; public class GlobalCheckScheduler extends BukkitRunnable { private static GlobalCheckScheduler instance = null; private static final double[] values = new double[] {0, 20}; private static final double[] diffCaches = new double[] {0, 0}; public GlobalCheckScheduler() { GlobalCheckScheduler.instance = this; runTaskTimerAsynchronously(Main.getInstance(), 0L, Config.CHECKER_INTERVAL.getLong()); new BukkitRunnable() { @Override public void run() { checkTPS(); } }.runTaskTimer(Main.getInstance(), 0L, Config.TPS_CHECK_INTERVAL.getLong()); } @Override public void run() { try { if (checkOnlinePlayers()) { CheckScheduler.notify(0); } } catch (final SQLException e) { e.printStackTrace(); } } private boolean checkOnlinePlayers() throws SQLException { boolean hasChange = false; final int playersOnline = Main.getInstance().getServer().getOnlinePlayers().size(); if (playersOnline != GlobalCheckScheduler.values[0]) { final double diff = playersOnline - GlobalCheckScheduler.values[0]; addDiff(0, diff); hasChange = true; } GlobalCheckScheduler.diffCaches[0] = getDiff(0, System.currentTimeMillis() - (InfoShower.diffLastSeconds * 1000L)); GlobalCheckScheduler.values[0] = playersOnline; return hasChange; } private void checkTPS() { final long currentTime = System.currentTimeMillis(); new BukkitRunnable() { @Override public void run() { final long endTime = System.currentTimeMillis(); new BukkitRunnable() { @Override public void run() { double tps = (Config.TPS_CHECK_INTERVAL.getDouble() * 1000D) / (endTime - currentTime); tps = tps > 20 ? 20 : tps; boolean hasChange = false; if (Math.round(GlobalCheckScheduler.values[1] * 10D) / 10D != Math.round(tps * 10D) / 10D) { try { addDiff(1, tps - GlobalCheckScheduler.values[1]); } catch (final SQLException e) { e.printStackTrace(); } hasChange = true; } try { GlobalCheckScheduler.diffCaches[1] = getDiff(1, System.currentTimeMillis() - (InfoShower.diffLastSeconds * 1000L)); } catch (final SQLException e) { e.printStackTrace(); } GlobalCheckScheduler.values[1] = tps; if (hasChange) { CheckScheduler.notify(1); } } }.runTaskAsynchronously(Main.getInstance()); } }.runTaskLater(Main.getInstance(), Config.TPS_CHECK_INTERVAL.getLong()); } private void addDiff(int index, double diff) throws SQLException { final PreparedStatement insStmt = MemoryDatabase.getInstance().getConn() .prepareStatement("INSERT INTO `global_diffs` (`index`, `value`, `timestamp`) VALUES (?, ?, ?)"); insStmt.setInt(1, index); insStmt.setDouble(2, diff); insStmt.setLong(3, System.currentTimeMillis()); insStmt.execute(); insStmt.close(); } private double getDiff(int index, Long last) throws SQLException { double diff = 0; final PreparedStatement selStmt = MemoryDatabase.getInstance().getConn() .prepareStatement("SELECT SUM(value) FROM `global_diffs` WHERE `index` = ? AND `timestamp` >= ?"); selStmt.setInt(1, index); selStmt.setLong(2, last); final ResultSet result = selStmt.executeQuery(); result.next(); diff = result.getDouble(1); result.close(); selStmt.close(); return diff; } public double getValue(int index) { return GlobalCheckScheduler.values[index]; } public double getDiffCache(int index) { return GlobalCheckScheduler.diffCaches[index]; } public static void reload() { GlobalCheckScheduler.instance = null; } public static GlobalCheckScheduler getInstance() { return GlobalCheckScheduler.instance; } } <file_sep>package net.wtako.WTAKOProfiler.Schedulers; import java.sql.SQLException; import java.util.HashMap; import net.wtako.WTAKOProfiler.Main; import net.wtako.WTAKOProfiler.Methods.InfoShower; import net.wtako.WTAKOProfiler.Utils.Config; import net.wtako.WTAKOProfiler.Utils.ExperienceManager; import org.bukkit.entity.Player; import org.bukkit.scheduler.BukkitRunnable; import org.bukkit.scoreboard.DisplaySlot; public class CheckScheduler extends BukkitRunnable { private static CheckScheduler instance = null; private static HashMap<Player, Double> playerHealths = new HashMap<Player, Double>(); private static HashMap<Player, Double> playerFoods = new HashMap<Player, Double>(); private static HashMap<Player, ExperienceManager> playerEXPManagers = new HashMap<Player, ExperienceManager>(); private static HashMap<Player, Double> playerEXPs = new HashMap<Player, Double>(); private static HashMap<Player, Double> playerBalances = new HashMap<Player, Double>(); private static final boolean[] notified = new boolean[] {false, false}; public CheckScheduler() { CheckScheduler.instance = this; runTaskTimerAsynchronously(Main.getInstance(), 0L, Config.CHECKER_INTERVAL.getLong()); new BukkitRunnable() { @Override public void run() { for (final Player player: Main.getInstance().getServer().getOnlinePlayers()) { if (player.getScoreboard().getObjective(DisplaySlot.SIDEBAR) == null) { InfoShower.getInfoShower(player).showInfo(); } } } }.runTaskTimerAsynchronously(Main.getInstance(), 0L, Config.CHECK_PLAYER_INFOBOX_INTERVAL.getLong()); } @Override public void run() { try { boolean hasNotify = false; for (final Player player: Main.getInstance().getServer().getOnlinePlayers()) { boolean hasChange = false; if (checkHealth(player)) { hasChange = true; } if (checkEcon(player)) { hasChange = true; } if (checkFood(player)) { hasChange = true; } if (checkEXP(player)) { hasChange = true; } for (final boolean element: CheckScheduler.notified) { if (element) { hasChange = true; hasNotify = true; break; } } if (hasChange) { InfoShower.getInfoShower(player).showInfo(); } } if (hasNotify) { for (int i = 0; i < CheckScheduler.notified.length; i++) { CheckScheduler.notified[i] = false; } } } catch (final SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } private boolean checkHealth(Player player) throws SQLException { boolean hasChange = false; final double currentHealth = player.getHealth(); if (!CheckScheduler.playerHealths.containsKey(player) || CheckScheduler.playerHealths.get(player) != currentHealth) { final double diff = CheckScheduler.playerHealths.get(player) != null ? currentHealth - CheckScheduler.playerHealths.get(player) : 0; InfoShower.getInfoShower(player).addDiff(0, diff); hasChange = true; } CheckScheduler.playerHealths.put(player, currentHealth); return hasChange; } private boolean checkFood(Player player) throws SQLException { boolean hasChange = false; final double currentFood = player.getFoodLevel(); if (!CheckScheduler.playerFoods.containsKey(player) || CheckScheduler.playerFoods.get(player) != currentFood) { final double diff = CheckScheduler.playerFoods.get(player) != null ? currentFood - CheckScheduler.playerFoods.get(player) : 0; InfoShower.getInfoShower(player).addDiff(1, diff); hasChange = true; } CheckScheduler.playerFoods.put(player, currentFood); return hasChange; } private boolean checkEXP(Player player) throws SQLException { boolean hasChange = false; if (!CheckScheduler.playerEXPManagers.containsKey(player)) { CheckScheduler.playerEXPManagers.put(player, new ExperienceManager(player)); } final double currentEXP = CheckScheduler.playerEXPManagers.get(player).getCurrentExp(); if (!CheckScheduler.playerEXPs.containsKey(player) || CheckScheduler.playerEXPs.get(player) != currentEXP) { final double diff = CheckScheduler.playerEXPs.get(player) != null ? currentEXP - CheckScheduler.playerEXPs.get(player) : 0; InfoShower.getInfoShower(player).addDiff(2, diff); hasChange = true; } CheckScheduler.playerEXPs.put(player, currentEXP); return hasChange; } private boolean checkEcon(Player player) throws SQLException { boolean hasChange = false; if (Main.economy == null) { return false; } final double currentBalance = Main.economy.getBalance(player); if (!CheckScheduler.playerBalances.containsKey(player) || CheckScheduler.playerBalances.get(player) != currentBalance) { final double diff = CheckScheduler.playerBalances.get(player) != null ? currentBalance - CheckScheduler.playerBalances.get(player) : 0; InfoShower.getInfoShower(player).addDiff(3, diff); hasChange = true; } CheckScheduler.playerBalances.put(player, currentBalance); return hasChange; } public static void notify(int index) { CheckScheduler.notified[index] = true; } public static ExperienceManager getEXPManager(Player player) { if (!CheckScheduler.playerEXPManagers.containsKey(player)) { CheckScheduler.playerEXPManagers.put(player, new ExperienceManager(player)); } return CheckScheduler.playerEXPManagers.get(player); } public static void reload() { CheckScheduler.instance = null; } public static CheckScheduler getInstance() { return CheckScheduler.instance; } } <file_sep>package net.wtako.WTAKOProfiler.Utils; import java.text.MessageFormat; import org.bukkit.ChatColor; public class StringUtils { public static String toInvisible(String s) { String hidden = ""; for (final char c: s.toCharArray()) { hidden += ChatColor.COLOR_CHAR + "" + c; } return hidden; } public static String fromInvisible(String s) { return s.replaceAll("§", ""); } public static String getChangeText(Double oldVal, Double newVal) { return StringUtils.getChangeText(newVal - oldVal); } public static String getChangeText(double diff) { if (diff == 0) { return ""; } String symbol = ""; if (diff < 0) { symbol = Lang.MINUS_SYMBOL.toString(); } else { symbol = Lang.ADD_SYMBOL.toString(); } return MessageFormat.format(Lang.DIGIT_CHANGE_FORMAT.toString(), symbol, Math.abs(diff)); } public static ChatColor getTPSColor(double tps) { if (tps >= 19.8) { return ChatColor.AQUA; } else if (tps >= 18) { return ChatColor.GREEN; } else if (tps >= 14) { return ChatColor.YELLOW; } else if (tps >= 10) { return ChatColor.RED; } else { return ChatColor.DARK_RED; } } } <file_sep>package net.wtako.WTAKOProfiler.Utils; import java.util.List; import net.wtako.WTAKOProfiler.Main; import org.bukkit.configuration.file.FileConfiguration; public enum Config { INFOBOX_ENABLED("infobox.enabled", true), CHECK_ECON("infobox.show-econ", true), CHECKER_INTERVAL("infobox.checker-interval-ticks", 2), CHECK_PLAYER_INFOBOX_INTERVAL("infobox.check-player-infobox-interval", 20), TPS_CHECK_INTERVAL("infobox.tps-check-interval-ticks", 40), DANGER_VALUE("infobox.danger-value", 6), DIFF_LAST("infobox.diff-last", 10); private String path; private Object value; Config(String path, Object var) { this.path = path; final FileConfiguration config = Main.getInstance().getConfig(); if (config.contains(path)) { value = config.get(path); } else { value = var; } } public Object getValue() { return value; } public boolean getBoolean() { return (boolean) value; } public String getString() { return (String) value; } public int getInt() { if (value instanceof Double) { return ((Double) value).intValue(); } return (int) value; } public long getLong() { return Integer.valueOf(getInt()).longValue(); } public double getDouble() { if (value instanceof Integer) { return ((Integer) value).doubleValue(); } return (double) value; } public String getPath() { return path; } @SuppressWarnings("unchecked") public List<Object> getValues() { return (List<Object>) value; } @SuppressWarnings("unchecked") public List<String> getStrings() { return (List<String>) value; } public static void saveAll() { final FileConfiguration config = Main.getInstance().getConfig(); for (final Config setting: Config.values()) { if (!config.contains(setting.getPath())) { config.set(setting.getPath(), setting.getValue()); } } Main.getInstance().saveConfig(); } }<file_sep>package net.wtako.WTAKOProfiler.Methods; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.SQLException; import java.sql.Statement; import net.wtako.WTAKOProfiler.Main; import org.bukkit.scheduler.BukkitRunnable; public class MemoryDatabase { private static MemoryDatabase instance; private final Connection conn; public MemoryDatabase() throws SQLException { MemoryDatabase.instance = this; conn = DriverManager.getConnection("jdbc:sqlite::memory:"); createTables(); final BukkitRunnable timer = new BukkitRunnable() { @Override public void run() { try { MemoryDatabase.getInstance().purgeData(); } catch (final SQLException e) { e.printStackTrace(); } } }; timer.runTaskTimerAsynchronously(Main.getInstance(), 30L * 20L, 180L * 20L); } public void createTables() throws SQLException { final Statement cur = conn.createStatement(); cur.execute("CREATE TABLE `player_diffs` (`row_id` INTEGER PRIMARY KEY AUTOINCREMENT, `player` VARCHAR(36) NOT NULL, `index` INT NOT NULL, `value` DOUBLE NOT NULL, `timestamp` INT NOT NULL)"); cur.execute("CREATE TABLE `global_diffs` (`row_id` INTEGER PRIMARY KEY AUTOINCREMENT, `index` INT NOT NULL, `value` DOUBLE NOT NULL, `timestamp` INT NOT NULL)"); cur.close(); } public void purgeData() throws SQLException { final long oldTime = System.currentTimeMillis() - (InfoShower.diffLastSeconds * 1000L); final PreparedStatement delStmt1 = conn.prepareStatement("DELETE FROM `player_diffs` WHERE timestamp < ?"); delStmt1.setLong(1, oldTime); delStmt1.execute(); delStmt1.close(); final PreparedStatement delStmt2 = conn.prepareStatement("DELETE FROM `global_diffs` WHERE timestamp < ?"); delStmt2.setLong(1, oldTime); delStmt2.execute(); delStmt2.close(); } public static MemoryDatabase getInstance() { return MemoryDatabase.instance; } public Connection getConn() { return conn; } }
105cae592d954fdcd6c7a9f455667cf94109ddd6
[ "Java" ]
6
Java
Saren-Arterius/WTAKOProfiler
933aec04fda0f72eaa478a7b22f8e5f07b0ea599
4f49942b6d908bf5e60f30547cb0da729a8173da
refs/heads/master
<repo_name>nshirke007/JdbcTemplete<file_sep>/src/main/java/com/scp/jdbc/jdbcTemplete/EmployeeMapper.java package com.scp.jdbc.jdbcTemplete; import java.sql.ResultSet; import java.sql.SQLException; import org.springframework.jdbc.core.RowMapper; public class EmployeeMapper implements RowMapper<Employee> { public Employee mapRow(ResultSet rs, int rowNum) throws SQLException { Employee e=new Employee(); e.setEmpId(rs.getInt("empId")); e.setEmpName(rs.getString("empName")); return e; } } <file_sep>/src/main/java/com/scp/jdbc/jdbcTemplete/DaoImpli.java package com.scp.jdbc.jdbcTemplete; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.sql.DataSource; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.jdbc.core.namedparam.MapSqlParameterSource; import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate; import org.springframework.jdbc.core.namedparam.SqlParameterSource; import org.springframework.jdbc.core.simple.SimpleJdbcTemplate; public class DaoImpli implements DaoLayer { /* * <--------------------------------------NamedParameterJdbcTemplate---------------------------------------------------> */ /*NamedParameterJdbcTemplate namedparameterjdbctemplate; public NamedParameterJdbcTemplate getNamedparameterjdbctemplate() { return namedparameterjdbctemplate; } public void setNamedparameterjdbctemplate(NamedParameterJdbcTemplate namedparameterjdbctemplate) { this.namedparameterjdbctemplate = namedparameterjdbctemplate; } public int saveEmployee(Employee e) { Map namedParameters = new HashMap(); namedParameters.put("empId", e.empId); namedParameters.put("empName", e.empName); namedparameterjdbctemplate.update("INSERT INTO empployee1 (empId,empName) VALUES (:empId, :empName)", namedParameters); System.out.println("created"); return 0; } public Employee getEmployee(int empId) { String sql = "SELECT empId, empName FROM empployee1 WHERE empId = :empId"; SqlParameterSource namedparam=new MapSqlParameterSource("empId",empId); return getNamedparameterjdbctemplate().queryForObject(sql, namedparam, new EmployeeMapper()); // return Employee; } public int deleteEmployee(int empId) { String sql = "delete From empployee1 WHERE empId =:empId "; SqlParameterSource namedparam=new MapSqlParameterSource("empId",empId); int returnvalue= getNamedparameterjdbctemplate().update(sql, namedparam); return returnvalue; } public int updateEmployee(Employee e) { Map<String, Object> param=new HashMap(); param.put("empId", e.empId); param.put("empName", e.empName); String s="update empployee1 set empName= :empName where empId = :empId "; return getNamedparameterjdbctemplate().update(s, param); } public List<Employee> getAllEmployee() { return namedparameterjdbctemplate.query("select * from empployee1", new EmployeeMapper()); } */ /* * --------------------------<jdbc templete>---------------------------------- */ /* // DataSource dataSource; JdbcTemplate jdbctemplete; public void setJdbctemplete(JdbcTemplate jdbctemplete) { this.jdbctemplete = jdbctemplete; } public int saveEmployee(Employee e) { // JdbcTemplate jdbctemplete = new JdbcTemplate(dataSource); int id = e.empId; String name = e.empName; Object p[] = { id, name }; String query = "insert into empployee2 values(?,?)"; return jdbctemplete.update(query, p); } public Employee getEmployee(int empId) { return jdbctemplete.queryForObject("select * from empployee2 where empId =" + empId, new EmployeeMapper()); } public int deleteEmployee(int empId) { return jdbctemplete.update("delete from empployee2 where empId = ?", empId); } public int updateEmployee(Employee e) { return jdbctemplete.update("update empployee2 set empId=?,empName=?", e.getEmpId(), e.getEmpName()); } public List<Employee> getAllEmployee() { return jdbctemplete.query("select * from empployee2", new EmployeeMapper()); }*/ SimpleJdbcTemplate Simplejdbctemplate; public SimpleJdbcTemplate getSimplejdbctemplate() { return Simplejdbctemplate; } public void setSimplejdbctemplate(SimpleJdbcTemplate simplejdbctemplate) { this.Simplejdbctemplate = simplejdbctemplate; } public int saveEmployee(Employee e) { // JdbcTemplate jdbctemplete = new JdbcTemplate(dataSource); int id = e.empId; String name = e.empName; Object p[] = { id, name }; String query = "insert into empployee2 values(?,?)"; return Simplejdbctemplate.update(query, p); } public Employee getEmployee(int empId) { return Simplejdbctemplate.queryForObject("select * from empployee2 where empId =" + empId, new EmployeeMapper()); } public int deleteEmployee(int empId) { return Simplejdbctemplate.update("delete from empployee2 where empId = ?", empId); } public int updateEmployee(Employee e) { Map<String, Object> param=new HashMap(); param.put("empId", e.empId); param.put("empName", e.empName); String s="update empployee1 set empName= :empName where empId = :empId "; return getSimplejdbctemplate().update(s, param); } public List<Employee> getAllEmployee() { return Simplejdbctemplate.query("select * from empployee2", new EmployeeMapper()); } }
59fefcfc035b0aec8c7615fa7cbf0a967075a5b1
[ "Java" ]
2
Java
nshirke007/JdbcTemplete
0f413f7a7bfcdf0b8067fd7b3ed7a559ab35fa47
d53dae43f30b8c1b26af860988ad9efa91f40708
refs/heads/master
<repo_name>OfferingSolutions/Offering-Solutions-Angular-Course<file_sep>/course/projects/osac111-unittesting/src/app/services/async-service/async.service.ts import { Injectable } from '@angular/core'; import { Observable, Observer } from 'rxjs'; @Injectable() export class AsyncService { constructor() {} getNameASync(): Observable<string> { return Observable.create((observer: Observer<string>) => { setTimeout(() => { observer.next('Fabian'); observer.complete(); }, 2000); }); } } <file_sep>/course/projects/osac112-e2etesting/src/app/core/todo.service.ts import { Injectable } from '@angular/core'; import { Observable, Observer } from 'rxjs'; import { Todo } from '../models/todo.models'; @Injectable() export class TodoService { private existingTodos: Todo[] = []; constructor() { } getAllTodos(): Observable<Todo[]> { return Observable.create((observer: Observer<Todo[]>) => { setTimeout(() => { observer.next(this.existingTodos); observer.complete(); }, 200); }); } getSingleTodo(id: string): Observable<Todo> { return Observable.create((observer: Observer<Todo>) => { setTimeout(() => { observer.next(this.existingTodos.find(x => x.id === id)); observer.complete(); }, 200); }); } addTodo(description: string): Todo { const toAdd: Todo = new Todo(); toAdd.created = new Date(); toAdd.id = this.guid(); toAdd.done = false; toAdd.description = description; this.existingTodos.push(toAdd); return toAdd; } updateTodo(toUpdate: Todo): Todo { this.existingTodos.map(obj => this.existingTodos.find(o => o.id === obj.id)); return toUpdate; } deleteTodo(id: string) { this.existingTodos = this.existingTodos.filter(item => item.id !== id); } private guid() { function s4() { return Math.floor((1 + Math.random()) * 0x10000) .toString(16) .substring(1); } return s4() + s4() + '-' + s4() + '-' + s4() + '-' + s4() + '-' + s4() + s4() + s4(); } } <file_sep>/README.md # [Offering Solutions](https://offering.solutions/) Angular Course (OSAC) <p align="center"> <img src=".github/Academy_logo_black.png" /> </p> This repository contains material for getting started with Angular. It should provide a code base where you can start on learning or teaching Angular. [Twitter](https://twitter.com/FabianGosebrink/) ## Demo Application [Demo](http://foodapiui.azurewebsites.net/) ## Offering Solutions Angular Course If you are attending the course you are ready to dive into the following chapters with us 1. [Angular Start](./chapters/00_AngularStart) 2. [Components Part I](./chapters/01_Components_Part_I) 3. [Directives](./chapters/02_Directives) 4. [Components Part II](./chapters/03_Components_Part_II) 5. [Lifecycle](./chapters/04_Lifecycle) 6. [Observables](./chapters/05_Observables) 7. [Services](./chapters/06_Services) 8. [Dependency Injection](./chapters/07_DependencyInjection) 9. [Pipes](./chapters/08_Pipes) 10. [Forms](./chapters/09_Forms) 11. [Routing](./chapters/10_Routing) 12. [Modules](./chapters/11_Modules) 13. [Testing](./chapters/12_Testing) # Preparation See the instructions to get started ## Things you need to bring to get started with the course 1. Dropbox - Account (not obligatory) 2. PC / Laptop 3. Enthusiasm and the will to learn something new :-) ### If you come with your own laptop please make sure you installed the following pieces of software to your PC: * [Git](#git) * [Node & npm](#node-with-npm) * [Typescript](#typescript) * [Visual Studio Code](#visual-studio-code) * [Angular CLI](#angular-cli) ## Git You can get git on [https://git-scm.com/downloads](https://git-scm.com/downloads) and check if you installed git via typing `git` on your commandline. Something like this should appear: ![git](.github/git.png 'git') ## Node with npm You can get node at [https://nodejs.org/en/download/](https://nodejs.org/en/download/) and install it normally. After doing this make sure you can type `node -v` ![node](.github/nodeversion.png 'node') and `npm -v` ![npm](.github/npmversion.png 'npm') on your console. > The exact versions do not really matter at all but be sure that node version is greater than version 6! ## Typescript You can get Typescript on [https://www.typescriptlang.org/#download-links](https://www.typescriptlang.org/#download-links) or by directly typing `npm install -g typescript` on your commandline. Please make sure that afterwards you are able to type `tsc -v` on your commandline seeing something like this: ![tsc](.github/tsc.png 'tsc') ## Visual Studio Code Generally you can use every text editor you want to implement Angular applications. We will use Visual Studio Code in this course. We will do an introduction to this editor and extend it with useful plugins to make our dev life a little easier. > Please check the checkboxes highlighted here. It makes your life easier: ![VSCodeInstall](.github/VSCodeInstall.png 'VSCodeInstall') You can download Visual Studio Code from [https://code.visualstudio.com/](https://code.visualstudio.com/) ## Angular CLI You can get the Angular CLI at [https://cli.angular.io/](https://cli.angular.io/). After installing it cia `npm` you can check if it is correctly installed by typing `ng version` without getting an error. ![angularcli](.github/angularcli.png 'angularcli')<file_sep>/course/projects/osac042-lifecyclehooks-end/src/app/content/content.component.ts import { AfterContentChecked, AfterContentInit, AfterViewChecked, AfterViewInit, Component, DoCheck, ElementRef, Input, OnChanges, OnDestroy, OnInit, SimpleChanges, ViewChild } from '@angular/core'; @Component({ selector: 'app-content', templateUrl: './content.component.html', styleUrls: ['./content.component.css'] }) export class ContentComponent implements OnChanges, OnInit, DoCheck, AfterContentInit, AfterContentChecked, AfterViewInit, AfterViewChecked, OnDestroy { @ViewChild('scrollMe', { static: true }) private scrollTextArea: ElementRef; @Input() textForOnChanges: string; textAreaValue = ''; constructor() {} // only called for/if there is an @input variable set by parent. ngOnChanges(changes: SimpleChanges) { console.log('ngOnChanges'); console.log(changes); this.addLine(`OnChanges ${JSON.stringify(changes)}`); } ngOnInit() { console.log('OnInit'); this.addLine('OnInit'); } // ACHTUNG!!! ngDoCheck() { console.log('DoCheck'); // this.addLine('DoCheck'); } ngAfterContentInit() { console.log('AfterContentInit'); // this.addLine('AfterContentInit'); } // ACHTUNG!!! ngAfterContentChecked() { console.log('AfterContentChecked'); // this.addLine('AfterContentChecked'); } ngAfterViewInit() { console.log('AfterViewInit'); // this.addLine('AfterViewInit'); } // ACHTUNG!!! ngAfterViewChecked() { console.log('AfterViewChecked'); // this.addLine('AfterViewChecked'); } ngOnDestroy() { console.log('OnDestroy'); this.addLine('OnDestroy'); } clearConsole() { this.textAreaValue = ``; } private addLine(message: string) { setTimeout(() => { this.textAreaValue += `${this.getFormattedDate()} - ${message}\r\n`; }); this.scrollTextArea.nativeElement.scrollTop = this.scrollTextArea.nativeElement.scrollHeight; } private getFormattedDate() { const date = new Date(); return `${date.getHours()}:${date.getMinutes()} ${date.getMinutes()} ${date.getSeconds()} ${date.getMilliseconds()}`; } } <file_sep>/course/projects/osac111-unittesting/src/app/components/inline-template/inline-template.component.spec.ts import { ComponentFixture, TestBed } from '@angular/core/testing'; import { By } from '@angular/platform-browser'; import { InlineTemplateComponent } from './inline-template.component'; describe('InlineTemplateComponent', () => { let component: InlineTemplateComponent; let fixture: ComponentFixture<InlineTemplateComponent>; beforeEach(() => { TestBed.configureTestingModule({ declarations: [InlineTemplateComponent], }); }); beforeEach(() => { fixture = TestBed.createComponent(InlineTemplateComponent); component = fixture.componentInstance; }); it('should create', () => { expect(component).toBeTruthy(); }); it('should set the name', () => { expect(component.name).toBe(undefined); fixture.detectChanges(); expect(component.name).not.toBe(''); }); it('should display the name', () => { expect(component.name).toBe(undefined); fixture.detectChanges(); const div = fixture.debugElement.query(By.css('div')); expect(div.nativeElement.innerHTML).toBe(component.name); }); }); <file_sep>/course/projects/osac092-routing-end/src/app/with-children-recipe/with-children-recipe.component.ts import { Component, OnInit } from '@angular/core'; @Component({ selector: 'app-with-children-recipe', templateUrl: './with-children-recipe.component.html', styleUrls: ['./with-children-recipe.component.css'] }) export class WithChildrenRecipeComponent implements OnInit { constructor() { } ngOnInit() { } } <file_sep>/course/projects/osac082-forms-end-simple/src/app/content/content.component.ts import { Component } from '@angular/core'; @Component({ selector: 'app-content', templateUrl: './content.component.html', styleUrls: ['./content.component.css'], }) export class ContentComponent { firstname = 'Fabian'; lastname = 'Gosebrink'; formSubmit(value: any): void { console.log(value); } } <file_sep>/course/projects/osac112-e2etesting/src/app/models/todo.models.ts export class Todo { public id: string; public created: Date; public description: string; public done: boolean; } <file_sep>/course/projects/osac032-components-II-end/src/app/parent/parent.component.ts import { Component, OnInit } from '@angular/core'; @Component({ selector: 'app-parent', templateUrl: './parent.component.html', styleUrls: ['./parent.component.css'] }) export class ParentComponent implements OnInit { public fruitList: string[] = ['Banana', 'Apples', 'Pineapples']; constructor() {} ngOnInit() {} public parentAddItem($event: any) { this.fruitList.push($event.name); } } <file_sep>/course/projects/osac102-modules-end/src/app/home/home.routing.ts import { ContentComponent } from './content/content.component'; import { Routes } from '@angular/router'; export const HomeRoutes: Routes = [ { path: 'home', component: ContentComponent } ]; <file_sep>/course/projects/osac112-e2etesting/src/app/core/todo.service.spec.ts import { fakeAsync, TestBed, tick } from '@angular/core/testing'; import { Todo } from '../models/todo.models'; import { TodoService } from './todo.service'; describe('TodoService', () => { let service: TodoService; beforeEach(() => { TestBed.configureTestingModule({ providers: [TodoService] }); service = TestBed.get(TodoService); }); it('should be created', () => { expect(service).toBeTruthy(); }); it( 'should get todoitems correctly', fakeAsync(() => { let items; service.getAllTodos().subscribe((result: Todo[]) => { items = result; }); expect(items).not.toBeDefined(); tick(200); expect(items).toBeDefined(); }) ); it( 'should add todoitems correctly', fakeAsync(() => { let items: Todo[]; service.getAllTodos().subscribe((result: Todo[]) => { items = result; }); tick(200); expect(items.length).toBe(0); service.addTodo('description'); service.getAllTodos().subscribe((result: Todo[]) => { items = result; }); tick(200); expect(items.length).toBe(1); }) ); it( 'should update todoitems correctly', fakeAsync(() => { const addedToDo = service.addTodo('description'); addedToDo.description = 'Fabian'; const singleTodo = service.updateTodo(addedToDo); expect(singleTodo.description).toBe('Fabian'); let items: Todo[]; service.getAllTodos().subscribe((result: Todo[]) => { items = result; }); tick(200); expect(items[0].description).toBe('Fabian'); }) ); it( 'should delete todoitems correctly', fakeAsync(() => { const addedToDo = service.addTodo('description'); let items: Todo[]; service.getAllTodos().subscribe((result: Todo[]) => { items = result; }); tick(200); expect(items.length).toBe(1); service.deleteTodo(addedToDo.id); service.getAllTodos().subscribe((result: Todo[]) => { items = result; }); tick(200); expect(items.length).toBe(0); }) ); }); <file_sep>/course/projects/osac111-unittesting/src/helpers/DOM-helpers.ts import { By } from '@angular/platform-browser'; import { ComponentFixture } from '@angular/core/testing'; export function queryDebugElement<T>(fixture: ComponentFixture<T>, searchItem: string) { return fixture.debugElement.query(By.css(searchItem)); } export function getInnerHtml<T>(fixture: ComponentFixture<T>, searchItem: string) { return fixture.debugElement.query(By.css(searchItem)).nativeElement.innerHTML; } <file_sep>/course/projects/osac062-services-and-di-end/src/app/core/calculator/calculator.service.ts import { Injectable } from '@angular/core'; @Injectable() export class CalculatorService { add(x: number, y: number) { return x + y; } substract(x: number, y: number) { return x - y; } } <file_sep>/course/projects/osac102-modules-end/src/app/core/services/calculator.service.ts export class CalculatorService { private random: number; constructor() { this.random = Math.random() * 100; console.log('-----------> constructor'); } add(x: number, y: number) { return x + y; } getRandomNumber() { return this.random; } } <file_sep>/course/projects/osac112-e2etesting/src/app/shell/shell.component.spec.ts import { async, ComponentFixture, fakeAsync, TestBed, tick } from '@angular/core/testing'; import { ReactiveFormsModule } from '@angular/forms'; import { of } from 'rxjs'; import { CoreModule } from '../core/core.module'; import { TodoService } from '../core/todo.service'; import { Todo } from '../models/todo.models'; import { TodoFormComponent } from '../todo-form/todo-form.component'; import { TodoListComponent } from '../todo-list/todo-list.component'; import { ShellComponent } from './shell.component'; describe('ShellComponent', () => { let component: ShellComponent; let fixture: ComponentFixture<ShellComponent>; let service: TodoService; beforeEach(async(() => { TestBed.configureTestingModule({ imports: [CoreModule, ReactiveFormsModule], declarations: [ShellComponent, TodoFormComponent, TodoListComponent] }).compileComponents(); })); beforeEach(() => { fixture = TestBed.createComponent(ShellComponent); component = fixture.componentInstance; service = TestBed.get(TodoService); }); it('should create', () => { expect(component).toBeTruthy(); }); it('should get service injected', () => { expect(component.todoService).toBeTruthy(); }); it('ngOnInit shall call service to get all items', () => { spyOn(service, 'getAllTodos').and.returnValue(of([])); fixture.detectChanges(); expect(service.getAllTodos).toHaveBeenCalled(); }); it('addTodo shall call service to get all items', () => { spyOn(service, 'getAllTodos').and.returnValue(of([])); component.addTodo(''); expect(service.getAllTodos).toHaveBeenCalled(); }); it('addTodo shall call service to add an item', () => { spyOn(service, 'addTodo'); component.addTodo('description'); expect(service.addTodo).toHaveBeenCalled(); }); it( 'addTodo shall add an item to the service', fakeAsync(() => { let todos: Todo[]; service.getAllTodos().subscribe((items: Todo[]) => (todos = items)); tick(200); expect(todos.length).toBe(0); component.addTodo('description'); service.getAllTodos().subscribe((items: Todo[]) => (todos = items)); tick(200); expect(todos.length).toBe(1); expect(todos[0].description).toBe('description'); }) ); it('markAsDone shall call service updateTodo', () => { spyOn(service, 'updateTodo'); const todo = new Todo(); todo.id = 'testId'; component.markAsDone(todo); expect(service.updateTodo).toHaveBeenCalled(); }); it( 'markAsDone shall updateTodo and set done to done', fakeAsync(() => { // const todo = new Todo(); const addedToDo = service.addTodo('todo'); let notDoneTodo: Todo; service.getSingleTodo(addedToDo.id).subscribe((item: Todo) => { notDoneTodo = item; }); tick(200); expect(notDoneTodo.done).toBe(false); component.markAsDone(addedToDo); let doneTodo: Todo; service.getSingleTodo(addedToDo.id).subscribe((item: Todo) => { doneTodo = item; }); tick(200); expect(doneTodo.done).toBe(true); }) ); }); <file_sep>/course/projects/osac092-routing-end/src/app/with-children/with-children.component.ts import { Component, OnInit } from '@angular/core'; import { ActivatedRoute, Params } from '@angular/router'; @Component({ selector: 'app-with-children', templateUrl: './with-children.component.html', styleUrls: ['./with-children.component.css'] }) export class WithChildrenComponent implements OnInit { id: number; constructor(private route: ActivatedRoute) {} ngOnInit() { this.route.params.forEach((params: Params) => { const id = +params['id']; this.id = id; }); } } <file_sep>/course/projects/osac111-unittesting/src/app/components/with-external-service/with-external-service.component.spec.ts import { HttpClientTestingModule } from '@angular/common/http/testing'; import { async, ComponentFixture, TestBed } from '@angular/core/testing'; import { BrowserModule } from '@angular/platform-browser'; import { of } from 'rxjs'; import { delay } from 'rxjs/operators'; import { getInnerHtml, queryDebugElement } from '../../../helpers/DOM-helpers'; import { CustomHttpService } from '../../services/http-service/http.service'; import { WithExternalServiceComponent } from './with-external-service.component'; describe('WithExternalServiceComponent', () => { let component: WithExternalServiceComponent; let fixture: ComponentFixture<WithExternalServiceComponent>; let service: CustomHttpService; const responseObject = { name: '<NAME>', }; beforeEach(async(() => { TestBed.configureTestingModule({ imports: [BrowserModule, HttpClientTestingModule], declarations: [WithExternalServiceComponent], providers: [CustomHttpService], }); })); beforeEach(() => { fixture = TestBed.createComponent(WithExternalServiceComponent); component = fixture.componentInstance; service = TestBed.get(CustomHttpService); }); it('should create', () => { expect(component).toBeTruthy(); }); it('(IntegrationTest) should get data when loaded', async(() => { expect( queryDebugElement<WithExternalServiceComponent>(fixture, 'span') ).toBeFalsy(); const spy = spyOn(service, 'getSingle').and.returnValue( of(responseObject).pipe(delay(500)) ); fixture.detectChanges(); // ngOnInit() fixture.whenStable().then(() => { fixture.detectChanges(); expect(spy.calls.any()).toBe(true, 'getSingle called'); expect( queryDebugElement<WithExternalServiceComponent>(fixture, 'span') ).toBeDefined(); expect( queryDebugElement<WithExternalServiceComponent>(fixture, 'pre') ).toBeDefined(); expect(component.result$).toBeDefined(); expect(getInnerHtml<WithExternalServiceComponent>(fixture, 'pre')).toBe( '<NAME>' ); }); })); }); <file_sep>/course/projects/osac083-forms-end-advanced/src/app/content/content.component.ts import { FoodItem } from '../models/foodItem'; import { Component, OnInit } from '@angular/core'; @Component({ selector: 'app-content', templateUrl: './content.component.html', styleUrls: ['./content.component.css'] }) export class ContentComponent { currentFood = new FoodItem(); addOrUpdateFoodNoValidation(): void { const stringObject = JSON.stringify(this.currentFood); alert(stringObject); } addOrUpdateFoodWithValidation(): void { const stringObject = JSON.stringify(this.currentFood); alert(stringObject); } } <file_sep>/course/projects/osac092-routing-end/src/app/with-children-overview/with-children-overview.component.spec.ts import { async, ComponentFixture, TestBed } from '@angular/core/testing'; import { WithChildrenOverviewComponent } from './with-children-overview.component'; describe('WithChildrenOverviewComponent', () => { let component: WithChildrenOverviewComponent; let fixture: ComponentFixture<WithChildrenOverviewComponent>; beforeEach(async(() => { TestBed.configureTestingModule({ declarations: [ WithChildrenOverviewComponent ] }) .compileComponents(); })); beforeEach(() => { fixture = TestBed.createComponent(WithChildrenOverviewComponent); component = fixture.componentInstance; fixture.detectChanges(); }); it('should create', () => { expect(component).toBeTruthy(); }); }); <file_sep>/course/projects/osac051-observables/src/app/content/content.component.ts import { HttpClient } from '@angular/common/http'; import { Component } from '@angular/core'; import { Observable, Observer } from 'rxjs'; import { finalize } from 'rxjs/operators'; @Component({ selector: 'app-content', templateUrl: './content.component.html', styleUrls: ['./content.component.css'] }) export class ContentComponent { name$: Observable<any>; constructor(private http: HttpClient) { const data$ = new Observable((observer: Observer<number>) => { setTimeout(() => { observer.next(42); }, 1000); setTimeout(() => { // observer.error(new Error()); observer.next(43); }, 2000); setTimeout(() => { observer.complete(); }, 3000); }); const subscription = data$ .pipe( // map(x => <number>x + 1), finalize(() => console.log('finally, if error or not')) ) .subscribe( (value: number) => { console.log(value); }, (error: number) => { console.log(error); }, () => console.log('finished') ); // subscription.unsubscribe(); this.name$ = this.getNameAsync(); } getNameAsync(): Observable<any> { return this.http.get<any>('https://swapi.co/api/people/1/'); } } <file_sep>/course/projects/osac121-angular-elements/src/app/app.component.ts import { Component } from '@angular/core'; @Component({ selector: 'app-root', template: ` <div id="placeholder"></div> <button (click)="addWebComponent()">add web component</button> `, styleUrls: ['./app.component.css'], }) export class AppComponent { title = 'angular-elements'; addWebComponent() { const element = document.getElementById('placeholder'); element.innerHTML = '<web-component></web-component>'; } } <file_sep>/course/projects/osac102-modules-end/src/app/app.routing.ts import { Routes } from '@angular/router'; export const AppRoutes: Routes = [ { path: '', redirectTo: '/home', pathMatch: 'full' }, { path: 'lazy', loadChildren: './+lazy/lazy.module#LazyModule' } ]; <file_sep>/course/projects/osac111-unittesting/src/app/services/async-service/async.service.spec.ts import { Injectable } from '@angular/core'; import { async, fakeAsync, TestBed, tick } from '@angular/core/testing'; import { Observable, Observer, of } from 'rxjs'; import { delay } from 'rxjs/operators'; import { AsyncService } from './async.service'; describe('AsyncService', () => { describe('AsyncService with real service', () => { let service: AsyncService; beforeEach(() => { TestBed.configureTestingModule({ providers: [AsyncService], }); service = TestBed.get(AsyncService); }); it('should be created', () => { expect(service).toBeTruthy(); }); it('should get the name', async(() => { service.getNameASync().subscribe((name: string) => { expect(name).toBe('Fabian'); }); })); it('should get the name (fakeasync)', fakeAsync(() => { let value; service.getNameASync().subscribe((name: string) => { value = name; }); expect(value).not.toBeDefined(); tick(500); expect(value).not.toBeDefined(); tick(1500); expect(value).toBeDefined(); expect(value).toBe('Fabian'); })); }); describe('AsyncService with a spy', () => { let service: AsyncService; beforeEach(() => { TestBed.configureTestingModule({ providers: [AsyncService], }); service = TestBed.get(AsyncService); }); it('should be created', () => { expect(service).toBeTruthy(); }); it('should get the name', async(() => { const spy = spyOn(service, 'getNameASync').and.returnValue(of('SpyFabian').pipe(delay(500))); service.getNameASync().subscribe((name: string) => { expect(name).toBe('SpyFabian'); }); expect(spy.calls.any()).toBe(true, 'getNameASync called'); })); }); describe('AsyncService with fake service', () => { @Injectable() class AsyncFakeService { getNameASync(): Observable<string> { return Observable.create((observer: Observer<string>) => { setTimeout(() => { observer.next('FakeFabian'); observer.complete(); }, 500); }); } } let service: AsyncService; beforeEach(() => { TestBed.configureTestingModule({ providers: [{ provide: AsyncService, useClass: AsyncFakeService }], }); service = TestBed.get(AsyncService); }); it('should be created', () => { expect(service).toBeTruthy(); }); it('should get the name (async)', async(() => { service.getNameASync().subscribe((name: string) => { expect(name).toBe('FakeFabian'); }); })); it('should get the name (fakeasync)', fakeAsync(() => { let value; service.getNameASync().subscribe((name: string) => { value = name; }); expect(value).not.toBeDefined(); tick(250); expect(value).not.toBeDefined(); tick(250); expect(value).toBeDefined(); expect(value).toBe('FakeFabian'); })); }); }); <file_sep>/course/projects/osac112-e2etesting/src/app/todo-list/todo-list.component.spec.ts import { async, ComponentFixture, TestBed } from '@angular/core/testing'; import { By } from '@angular/platform-browser'; import { Todo } from '../models/todo.models'; import { TodoListComponent } from './todo-list.component'; describe('TodoListComponent', () => { let component: TodoListComponent; let fixture: ComponentFixture<TodoListComponent>; beforeEach(async(() => { TestBed.configureTestingModule({ declarations: [TodoListComponent] }) .compileComponents(); })); beforeEach(() => { fixture = TestBed.createComponent(TodoListComponent); component = fixture.componentInstance; fixture.detectChanges(); }); it('should create', () => { expect(component).toBeTruthy(); }); it('method \'markAsDone\' calls eventEmitter', () => { spyOn(component.onMarkAsDone, 'emit'); const item = new Todo(); component.markAsDone(item); expect(component.onMarkAsDone.emit).toHaveBeenCalledWith(item); }); it('should correctly render the passed @Input value', () => { const allListItems = fixture.debugElement.queryAll(By.css('li')); expect(allListItems.length).toBe(0); component.items = [new Todo(), new Todo()]; fixture.detectChanges(); expect(fixture.debugElement.queryAll(By.css('li')).length).toBe(2); }); it('should correctly display the description', () => { const todo = new Todo(); todo.description = 'toShow'; component.items = [todo]; fixture.detectChanges(); const allItems = fixture.debugElement.queryAll(By.css('li')); const renderedText = allItems[0].nativeElement.querySelector('span').innerHTML; expect(renderedText).toBe(todo.description); }); it('eventemitter shall be called when button is clicked', () => { const todo = new Todo(); todo.description = 'toShow'; component.items = [todo]; fixture.detectChanges(); spyOn(component.onMarkAsDone, 'emit'); const button = fixture.nativeElement.querySelector('button'); button.click(); expect(component.onMarkAsDone.emit).toHaveBeenCalledWith(todo); }); it('span is invisble when item is done', () => { const todo = new Todo(); todo.description = 'toShow'; todo.done = true; component.items = [todo]; fixture.detectChanges(); expect(fixture.nativeElement.querySelector('span')).toBeNull(); expect(fixture.nativeElement.querySelector('s')).toBeDefined(); }); it('css class \'inactive\' is applied when item is done', () => { const todo = new Todo(); todo.description = 'toShow'; todo.done = true; component.items = [todo]; fixture.detectChanges(); const classList = fixture.nativeElement.querySelector('s').classList; expect(classList).toContain('inactive'); }); it('s is invisible when item is not done', () => { const todo = new Todo(); todo.description = 'toShow'; component.items = [todo]; fixture.detectChanges(); expect(fixture.nativeElement.querySelector('span')).toBeDefined(); expect(fixture.nativeElement.querySelector('s')).toBeNull(); }); }); <file_sep>/course/projects/osac092-routing-end/src/app/with-children-overview/with-children-overview.component.ts import { Component, OnInit } from '@angular/core'; import { ActivatedRoute, Router } from '@angular/router'; @Component({ selector: 'app-with-children-overview', templateUrl: './with-children-overview.component.html', styleUrls: ['./with-children-overview.component.css'] }) export class WithChildrenOverviewComponent implements OnInit { parentRouteId: number; constructor(private router: Router, private route: ActivatedRoute) {} ngOnInit() { // Get parent ActivatedRoute of this route. this.route.parent.params.forEach(params => { this.parentRouteId = +params['id']; }); } } <file_sep>/course/projects/osac072-pipes-end/src/app/content/content.component.ts import { Component, OnInit } from '@angular/core'; @Component({ selector: 'app-content', templateUrl: './content.component.html', styleUrls: ['./content.component.css'] }) export class ContentComponent { value = 'Hello'; items = [ { name: 'Hans', age: 20 }, { name: 'Franz', age: 30 }, { name: 'Peter', age: 40 }, { name: 'Timo', age: 50 }, { name: 'Hugo', age: 60 } ]; searchString = ''; date = new Date(); } <file_sep>/course/projects/osac022-directives-end/src/app/directives/my-highlight.directive.ts import { Directive, OnInit, Input, ElementRef } from '@angular/core'; @Directive({ selector: '[appMyHighlight]' }) export class MyHighlightDirective implements OnInit { @Input() appMyHighlight: string; constructor(private el: ElementRef) {} ngOnInit() { this.el.nativeElement.style.backgroundColor = this.appMyHighlight || 'cyan'; } } <file_sep>/course/projects/osac111-unittesting/src/app/components/with-input/with-input.component.ts import { Component, Input, OnChanges, SimpleChanges } from '@angular/core'; @Component({ selector: 'app-with-input', templateUrl: './with-input.component.html', styleUrls: ['./with-input.component.css'], }) export class WithInputComponent implements OnChanges { @Input() name: string; public ngOnChanges(changes: SimpleChanges): void { console.log('Not implemented yet.'); } } <file_sep>/course/projects/osac102-modules-end/src/app/+lazy/components/main/main.component.ts import { Component, OnInit } from '@angular/core'; import { CalculatorService } from '../../../core/services/calculator.service'; @Component({ selector: 'app-main', templateUrl: './main.component.html', styleUrls: ['./main.component.css'] }) export class MainComponent { lazyRandomNumber: number; constructor(private myService: CalculatorService) { this.lazyRandomNumber = myService.getRandomNumber(); } } <file_sep>/course/projects/osac062-services-and-di-end/src/app/core/item-data/item-data.service.spec.ts import { TestBed, inject } from '@angular/core/testing'; import { ItemDataService } from './item-data.service'; describe('ItemDataService', () => { beforeEach(() => { TestBed.configureTestingModule({ providers: [ItemDataService] }); }); it('should be created', inject([ItemDataService], (service: ItemDataService) => { expect(service).toBeTruthy(); })); }); <file_sep>/course/projects/osac111-unittesting/src/app/components/inline-template/inline-template.component.ts import { Component, OnInit } from '@angular/core'; @Component({ selector: 'app-inline-template', template: '<div>{{name}}</div>', styleUrls: ['./inline-template.component.css'] }) export class InlineTemplateComponent implements OnInit { name: string; constructor() {} ngOnInit() { this.name = 'Fabian'; } } <file_sep>/course/projects/osac112-e2etesting/src/app/shell/shell.component.ts import { Component, OnInit } from '@angular/core'; import { TodoService } from '../core/todo.service'; import { Todo } from '../models/todo.models'; @Component({ selector: 'app-shell', templateUrl: './shell.component.html', styleUrls: ['./shell.component.css'] }) export class ShellComponent implements OnInit { items: Todo[] = []; constructor(public todoService: TodoService) { } ngOnInit() { this.todoService.getAllTodos().subscribe((items: Todo[]) => this.items = items); } addTodo(description: string) { this.todoService.addTodo(description); this.todoService.getAllTodos().subscribe((items: Todo[]) => this.items = items); } markAsDone(todo: Todo) { todo.done = true; this.todoService.updateTodo(todo); } } <file_sep>/course/projects/osac092-routing-end/src/app/app.module.ts import { RouterModule } from '@angular/router'; import { HttpClientModule } from '@angular/common/http'; import { NgModule } from '@angular/core'; import { FormsModule } from '@angular/forms'; import { BrowserModule } from '@angular/platform-browser'; import { BrowserAnimationsModule } from '@angular/platform-browser/animations'; import { AppComponent } from './app.component'; import { NavigationComponent } from './navigation/navigation.component'; import { ContentComponent } from './content/content.component'; import { AboutComponent } from './about/about.component'; import { ProductComponent } from './product/product.component'; import { ProductDetailsComponent } from './product-details/product-details.component'; import { WithChildrenComponent } from './with-children/with-children.component'; import { WithChildrenOverviewComponent } from './with-children-overview/with-children-overview.component'; import { WithChildrenRecipeComponent } from './with-children-recipe/with-children-recipe.component'; import { AppRoutes } from './app.routing'; @NgModule({ declarations: [ AppComponent, NavigationComponent, ContentComponent, AboutComponent, ProductComponent, ProductDetailsComponent, WithChildrenComponent, WithChildrenOverviewComponent, WithChildrenRecipeComponent ], imports: [ RouterModule.forRoot(AppRoutes), BrowserAnimationsModule, BrowserModule, FormsModule, HttpClientModule ], providers: [], bootstrap: [AppComponent] }) export class AppModule {} <file_sep>/course/projects/osac062-services-and-di-end/src/app/core/item-data/item-data.service.ts import { Observable } from 'rxjs'; import { Injectable } from '@angular/core'; import { HttpClient } from '@angular/common/http'; import { FoodItem } from '../../models/foodItem'; import { Configuration } from '../../app.configuration'; @Injectable() export class ItemDataService { private actionUrl: string; constructor(private http: HttpClient, private configuration: Configuration) { this.actionUrl = configuration.baseUrl + 'api/foods/'; } getAllFood(): Observable<FoodItem[]> { return this.http.get<FoodItem[]>(this.actionUrl); } getSingleFood(id: number): Observable<FoodItem> { return this.http.get<FoodItem>(this.actionUrl + id); } addFood(foodItem: FoodItem): Observable<FoodItem> { const toAdd = { name: foodItem.name, calories: foodItem.calories, created: new Date() }; return this.http.post<FoodItem>(this.actionUrl, toAdd); } updateFood(id: number, foodToUpdate: FoodItem): Observable<FoodItem> { return this.http.put<FoodItem>(this.actionUrl + id, foodToUpdate); } deleteFood(id: number): Observable<Object> { return this.http.delete(this.actionUrl + id); } } <file_sep>/course/projects/osac111-unittesting/src/app/services/basic-Service/basic.service.ts import { Injectable } from '@angular/core'; @Injectable() export class BasicService { constructor() {} add(x: number, y: number) { return x + y; } } <file_sep>/course/projects/osac062-services-and-di-end/src/app/content/content.component.ts import { Component, OnInit, Inject } from '@angular/core'; import { Observable } from 'rxjs'; import { CalculatorService } from '../core/calculator/calculator.service'; import { ItemDataService } from '../core/item-data/item-data.service'; import { FoodItem } from '../models/foodItem'; @Component({ selector: 'app-content', templateUrl: './content.component.html', styleUrls: ['./content.component.css'] }) export class ContentComponent implements OnInit { result: number; randomWithFactoryValue: number; randomWithValue: number; observable$: Observable<FoodItem[]>; constructor( private calculatorService: CalculatorService, @Inject('RandomWithFactory') randomWithFactory: number, @Inject('RandomWithValue') randomWithValue: number, private dataService: ItemDataService ) { this.randomWithFactoryValue = randomWithFactory; this.randomWithValue = randomWithValue; } ngOnInit() { this.result = this.calculatorService.add(1, 3); this.observable$ = this.dataService.getAllFood(); } } <file_sep>/course/projects/osac112-e2etesting/src/app/todo-form/todo-form.component.ts import { Component, EventEmitter, OnInit, Output } from '@angular/core'; import { FormBuilder, FormControl, FormGroup, Validators } from '@angular/forms'; @Component({ selector: 'app-todo-form', templateUrl: './todo-form.component.html', styleUrls: ['./todo-form.component.css'] }) export class TodoFormComponent implements OnInit { @Output() onAddTodo = new EventEmitter(); form: FormGroup; constructor(private formBuilder: FormBuilder) { } ngOnInit() { this.form = new FormGroup({ todoDescription: new FormControl('', Validators.required), }); } addTodo() { const payload = Object.assign({}, this.form.value); // console.log(payload.todoDescription); this.onAddTodo.emit(payload.todoDescription); this.form.reset(); } } <file_sep>/course/projects/osac092-routing-end/src/app/product-details/product-details.component.ts import { Component, OnInit } from '@angular/core'; import { ActivatedRoute } from '@angular/router'; @Component({ selector: 'app-product-details', templateUrl: './product-details.component.html', styleUrls: ['./product-details.component.css'] }) export class ProductDetailsComponent implements OnInit { id: number; constructor(private route: ActivatedRoute) {} ngOnInit() { // this._route.params.forEach((params: Params) => { // let id = +params['id']; // this.id = id; // }); // this.id = this.route // .queryParams // .map(params => +params['id'] || -1); this.id = +this.route.snapshot.paramMap.get('id'); } } <file_sep>/course/projects/osac112-e2etesting/src/app/todo-form/todo-form.component.spec.ts import { async, ComponentFixture, fakeAsync, TestBed, tick } from '@angular/core/testing'; import { ReactiveFormsModule } from '@angular/forms'; import { By } from '@angular/platform-browser'; import { TodoFormComponent } from './todo-form.component'; describe('TodoFormComponent', () => { let component: TodoFormComponent; let fixture: ComponentFixture<TodoFormComponent>; beforeEach(async(() => { TestBed.configureTestingModule({ imports: [ReactiveFormsModule], declarations: [TodoFormComponent] }) .compileComponents(); })); beforeEach(() => { fixture = TestBed.createComponent(TodoFormComponent); component = fixture.componentInstance; // fixture.detectChanges(); }); it('should create', () => { expect(component).toBeTruthy(); }); it('addTodo method should emit the output', () => { component.onAddTodo.subscribe((desc: string) => { expect(desc).toBe('hello'); }); fixture.detectChanges(); component.form.setValue({ todoDescription: 'hello' }); component.addTodo(); }); it('eventemitter should be called when button is clicked', () => { spyOn(component.onAddTodo, 'emit'); fixture.detectChanges(); component.form.setValue({ todoDescription: 'emitted' }); const button = fixture.nativeElement.querySelector('button'); fixture.detectChanges(); button.click(); expect(component.onAddTodo.emit).toHaveBeenCalledWith('emitted'); }); it('button should be disabled when description is empty', async(() => { fixture.detectChanges(); component.form.setValue({ todoDescription: '' }); expect(component.form.valid).toBe(false); const button = fixture.debugElement.query(By.css('button')).nativeElement; expect(button.disabled).toBe(true); })); it('input should have class invalid when description is empty', async(() => { fixture.detectChanges(); component.form.setValue({ todoDescription: '' }); const input = fixture.debugElement.query(By.css('input')); expect(input.classes['ng-valid']).toBe(false); expect(input.classes['ng-invalid']).toBe(true); component.form.setValue({ todoDescription: 'test' }); fixture.detectChanges(); expect(input.classes['ng-valid']).toBe(true); })); it('addTodo() should reset the description', () => { fixture.detectChanges(); component.form.setValue({ todoDescription: 'test' }); component.addTodo(); expect(component.form.value.todoDescription).toBeNull(); }); it('component description property gets reflected on UI', fakeAsync(() => { fixture.detectChanges(); component.form.setValue({ todoDescription: 'test' }); tick(); const input = fixture.nativeElement.querySelector('input'); expect(input.value).toBe('test'); })); }); <file_sep>/course/projects/osac111-unittesting/src/app/services/http-service/http.service.ts import { HttpClient } from '@angular/common/http'; import { Injectable } from '@angular/core'; import { Observable, Observer } from 'rxjs'; @Injectable() export class CustomHttpService { constructor(private httpClient: HttpClient) {} getSingle<T>(id: number) { return this.httpClient.get<T>(`http://replace.with.api/anything/${id}`); } post<T>(item: any) { return this.httpClient.post<T>(`http://replace.with.api/anything`, item); } put<T>(id: number, item: any) { return this.httpClient.put<T>( `http://replace.with.api/anything/${id}`, item ); } delete(id: number) { return this.httpClient.delete(`http://replace.with.api/anything/${id}`); } getlanguages() { return Observable.create((observer: Observer<string>) => { setTimeout(() => { observer.next(`['en', 'de', 'it']`); observer.complete(); }, 1000); }); } } <file_sep>/course/projects/osac112-e2etesting/e2e/src/app.po.ts import { browser, by, element } from 'protractor'; export class AppPage { navigateTo() { return browser.get('/'); } getParagraphText() { return element(by.css('app-root h1')).getText(); } getTextField() { return element(by.css('input')); } getButton() { return element(by.css('button')); } getTodoItemButton() { return element(by.id('doneButton')); } getListCount() { return element.all(by.css('ul li')).count(); } getList() { return element.all(by.css('ul li')); } getInactiveElements() { return element.all(by.css('.inactive')); } } <file_sep>/course/projects/osac092-routing-end/src/app/app.routing.ts import { Routes } from '@angular/router'; import { ContentComponent } from './content/content.component'; import { ProductComponent } from './product/product.component'; import { AboutComponent } from './about/about.component'; import { ProductDetailsComponent } from './product-details/product-details.component'; import { WithChildrenComponent } from './with-children/with-children.component'; import { WithChildrenOverviewComponent } from './with-children-overview/with-children-overview.component'; import { WithChildrenRecipeComponent } from './with-children-recipe/with-children-recipe.component'; export const AppRoutes: Routes = [ { path: '', redirectTo: '/home', pathMatch: 'full' }, { path: 'home', component: ContentComponent }, { path: 'about', component: AboutComponent }, { path: 'products', component: ProductComponent }, { path: 'product/:id', component: ProductDetailsComponent }, { path: 'withChildren/:id', component: WithChildrenComponent, children: [ { path: '', component: WithChildrenOverviewComponent }, { path: 'recipe', component: WithChildrenRecipeComponent } ] } ]; <file_sep>/course/projects/osac112-e2etesting/e2e/src/app.e2e-spec.ts import * as fs from 'fs'; import { browser, by, element } from 'protractor/built'; import { AppPage } from './app.po'; describe('todo-app App', () => { let page: AppPage; beforeEach(() => { page = new AppPage(); }); it('should display welcome message', () => { page.navigateTo(); expect(page.getParagraphText()).toEqual('Welcome to app!'); }); it('should add Todo in List', () => { page.navigateTo(); expect(page.getListCount()).toBe(0); page.getTextField().clear(); page.getTextField().sendKeys('<PASSWORD>'); browser.takeScreenshot().then(png => { const stream = fs.createWriteStream(`screenshot-1.png`); stream.write(new Buffer(png, 'base64')); stream.end(); }); page.getButton().click(); browser.takeScreenshot().then(png => { const stream = fs.createWriteStream('screenshot-2.png'); stream.write(new Buffer(png, 'base64')); stream.end(); }); expect(page.getListCount()).toBe(1); }); it('should add correct css class when marked as done', () => { page.navigateTo(); page.getTextField().clear(); page.getTextField().sendKeys('example<PASSWORD>'); browser.takeScreenshot().then(png => { const stream = fs.createWriteStream('screenshot-3.png'); stream.write(new Buffer(png, 'base64')); stream.end(); }); page.getButton().click(); page.getTodoItemButton().click(); browser.takeScreenshot().then(png => { const stream = fs.createWriteStream('screenshot-4.png'); stream.write(new Buffer(png, 'base64')); stream.end(); }); expect(page.getInactiveElements().count()).toBe(1); }); }); <file_sep>/course/projects/osac092-routing-end/src/app/product/product.component.ts import { Component, OnInit } from '@angular/core'; import { FoodItem } from '../models/foodItem'; import { Router } from '@angular/router'; @Component({ selector: 'app-product', templateUrl: './product.component.html', styleUrls: ['./product.component.css'] }) export class ProductComponent implements OnInit { foodItems: FoodItem[] = []; constructor(private router: Router) { const foodItemToPush = new FoodItem(); foodItemToPush.calories = 999; foodItemToPush.id = 999; foodItemToPush.created = new Date(); foodItemToPush.name = 'Lasagne'; this.foodItems.push(foodItemToPush); } goToDetails(id: number) { this.router.navigate(['/product', id]); } ngOnInit() {} } <file_sep>/course/cypress/integration/todo_tests.js describe('My First Test', () => { beforeEach(function() { cy.visit('http://localhost:4200'); cy.get('#addtodobutton').as('addtodobutton'); cy.get('#todoinput').as('todoinput'); cy.get('#todolist').as('todolist'); cy.get('#addtodoform').as('addtodoform'); }); it('Application has the correct title!', () => { cy.title().should('include', 'Osac112E2etesting'); }); it('Application has the correct h1 tag!', () => { cy.get('h1').contains('Welcome to app!'); }); it('Button has correct naming', () => { cy.get('@addtodobutton').should('contain', 'Add Todo'); }); it('Add Todo button is disabled when input is empty', () => { cy.get('@addtodobutton').should('have.attr', 'disabled'); }); it('Add Todo button is enabled when input is not empty', () => { cy.get('@addtodobutton') .should('have.attr', 'disabled') .get('@todoinput') .type('SomeTodo') .get('@addtodobutton') .should('not.have.attr', 'disabled'); }); it('Submit Form should clear Input', () => { cy.get('@todoinput') .type('SomeTodo') .get('@addtodoform') .submit() .get('@todoinput') .should('have.value', ''); }); it('After submitting form list should contain element', () => { cy.get('@todoinput') .type('SomeTodo') .get('@addtodoform') .submit() .get('#todolist>li') .its('length') .should('be.eq', 1); }); it("After clicking 'done' the item should contain done css class", () => { cy.get('@todoinput') .type('SomeTodo') .get('@addtodoform') .submit() .get('#doneButton') .click() .get('#todolist>li s') .first() .should('have.class', 'inactive'); }); }); <file_sep>/course/projects/osac111-unittesting/src/app/services/http-service/http.service.spec.ts import { HttpClientTestingModule, HttpTestingController, } from '@angular/common/http/testing'; import { async, TestBed } from '@angular/core/testing'; import { CustomHttpService } from './http.service'; describe('CustomHttpService', () => { let service: CustomHttpService; let httpMock: HttpTestingController; beforeEach(() => { TestBed.configureTestingModule({ imports: [HttpClientTestingModule], providers: [CustomHttpService], }); // inject the service service = TestBed.get(CustomHttpService); httpMock = TestBed.get(HttpTestingController); }); it('should be created', () => { expect(service).toBeTruthy(); }); it('should get the correct star wars character', async(() => { service.getSingle(1).subscribe((data: any) => { expect(data.name).toBe('<NAME>'); }); const req = httpMock.expectOne( `http://replace.with.api/anything/1`, 'call to api' ); expect(req.request.method).toBe('GET'); req.flush({ name: '<NAME>', }); httpMock.verify(); })); it('should post the correct data', () => { service.post<any>({ firstname: 'firstname' }).subscribe((data: any) => { expect(data.firstname).toBe('firstname'); }); const req = httpMock.expectOne( `http://replace.with.api/anything`, 'post to api' ); expect(req.request.method).toBe('POST'); req.flush({ firstname: 'firstname', }); httpMock.verify(); }); it('should put the correct data', () => { service.put<any>(3, { firstname: 'firstname' }).subscribe((data: any) => { expect(data.firstname).toBe('firstname'); }); const req = httpMock.expectOne( `http://replace.with.api/anything/3`, 'put to api' ); expect(req.request.method).toBe('PUT'); req.flush({ firstname: 'firstname', }); httpMock.verify(); }); it('should delete the correct data', () => { service.delete(3).subscribe((data: any) => { expect(data).toBe(3); }); const req = httpMock.expectOne( `http://replace.with.api/anything/3`, 'delete to api' ); expect(req.request.method).toBe('DELETE'); req.flush(3); httpMock.verify(); }); it('should return available languages', async(() => { service.getlanguages().subscribe(x => { expect(x).toContain('en'); expect(x).toContain('de'); expect(x).toContain('it'); expect(x).toBeDefined(); }); })); }); <file_sep>/course/projects/osac032-components-II-end/src/app/child/child.component.ts import { Component, EventEmitter, OnInit, Output, Input } from '@angular/core'; @Component({ selector: 'app-child', templateUrl: './child.component.html', styleUrls: ['./child.component.css'] }) export class ChildComponent implements OnInit { @Input() itemList: string[]; @Output() itemAdded = new EventEmitter(); constructor() {} ngOnInit() {} public internalAddItem() { this.itemAdded.emit({ name: Math.random() }); } } <file_sep>/course/projects/osac102-modules-end/src/app/home/content/content.component.ts import { Component, OnInit } from '@angular/core'; import { CalculatorService } from '../../core/services/calculator.service'; @Component({ selector: 'app-content', templateUrl: './content.component.html', styleUrls: ['./content.component.css'] }) export class ContentComponent { lazyRandomNumber: number; constructor(private myService: CalculatorService) { this.lazyRandomNumber = myService.getRandomNumber(); } } <file_sep>/course/projects/osac062-services-and-di-end/src/app/core/core.module.ts import { NgModule } from '@angular/core'; import { CommonModule } from '@angular/common'; import { ItemDataService } from './item-data/item-data.service'; import { CalculatorService } from './calculator/calculator.service'; @NgModule({ imports: [CommonModule], declarations: [], providers: [ItemDataService, CalculatorService] }) export class CoreModule {} <file_sep>/course/projects/osac022-directives-end/src/app/content/content.component.ts import { Component } from '@angular/core'; @Component({ selector: 'app-content', templateUrl: './content.component.html', styleUrls: ['./content.component.css'] }) export class ContentComponent { items: string[] = ['Hamburger', 'Pommes', 'Schnitzel']; private color = 'red'; showItem = true; toggleShowItem() { this.showItem = !this.showItem; } } <file_sep>/course/projects/osac111-unittesting/src/app/services/basic-Service/basic.service.spec.ts import { inject, TestBed } from '@angular/core/testing'; import { BasicService } from './basic.service'; describe('BasicService', () => { describe('Injecting in every single Test', () => { beforeEach(() => { TestBed.configureTestingModule({ providers: [BasicService], }); }); it('should be created', inject([BasicService], (service: BasicService) => { expect(service).toBeTruthy(); })); }); describe('Injecting in a seperate foreach (Suite)', () => { let service: BasicService; beforeEach(() => TestBed.configureTestingModule({ providers: [BasicService], })); beforeEach(inject([BasicService], (s: BasicService) => { service = s; })); it('should have a service instance', () => { expect(service).toBeDefined(); }); }); describe('Injecting via TestBed.get()', () => { let service: BasicService; beforeEach(() => { TestBed.configureTestingModule({ providers: [BasicService], }); service = TestBed.get(BasicService); }); it('should have a service instance', () => { expect(service).toBeDefined(); }); }); describe('Testing service functions', () => { let service: BasicService; beforeEach(() => { TestBed.configureTestingModule({ providers: [BasicService], }); service = TestBed.get(BasicService); }); it('should add properly: injection method 1', () => { expect(service.add(2, 3)).toBe(5); }); it('should add properly: (Spy)', () => { spyOn(service, 'add').and.returnValue(6); expect(service.add(2, 3)).toBe(6); }); }); }); <file_sep>/course/projects/osac121-angular-elements/src/app/web/web.component.ts import { Component, EventEmitter, Input, OnInit, Output } from '@angular/core'; @Component({ template: ` <p>web-component works! {{ name }}</p> <button (click)="buttonClick()">Click me</button> `, styles: [], }) export class WebComponent implements OnInit { @Input() name; @Output() buttonClicked = new EventEmitter(); constructor() {} ngOnInit() {} buttonClick() { this.buttonClicked.emit(); } } <file_sep>/course/projects/osac092-routing-end/src/app/with-children-recipe/with-children-recipe.component.spec.ts import { async, ComponentFixture, TestBed } from '@angular/core/testing'; import { WithChildrenRecipeComponent } from './with-children-recipe.component'; describe('WithChildrenRecipeComponent', () => { let component: WithChildrenRecipeComponent; let fixture: ComponentFixture<WithChildrenRecipeComponent>; beforeEach(async(() => { TestBed.configureTestingModule({ declarations: [ WithChildrenRecipeComponent ] }) .compileComponents(); })); beforeEach(() => { fixture = TestBed.createComponent(WithChildrenRecipeComponent); component = fixture.componentInstance; fixture.detectChanges(); }); it('should create', () => { expect(component).toBeTruthy(); }); });
4ccd7fc34815275ef2157c03c5a6a5dd60be5395
[ "Markdown", "TypeScript", "JavaScript" ]
53
TypeScript
OfferingSolutions/Offering-Solutions-Angular-Course
29d1e31c0bb10aac789d6130768b84296a8fa9d7
335743cc4bbcd1e4570570e8fe60766131dffcfd
refs/heads/particle3d
<repo_name>icicle4/patricle_filter<file_sep>/main.py from tracker import * import pdb from pydarknet import Detector, Image import cv2 from three_dimension import deter_3d_loc WINDOW_TITLE = "Tracking" if __name__ == '__main__': frameNo = 0 camera_number = 2 # # width = cap.get(cv2.CAP_PROP_FRAME_WIDTH) # height = cap.get(cv2.CAP_PROP_FRAME_HEIGHT) # fps = int(cap.get(cv2.CAP_PROP_FPS)) # # res_path = "final_res.mp4" # fourcc = cv2.VideoWriter_fourcc(*'mp4v') # res_video = cv2.VideoWriter(res_path, fourcc, float(fps), (int(width), int(height)), True) video_path = "videos/src/0.mp4" root_dir = "" cap = cv2.VideoCapture(video_path) total_number = cap.get(cv2.CAP_PROP_FRAME_COUNT) caps = [] for i in range(camera_number): video_path = "videos/src/{}.mp4".format(i) caps.append(cv2.VideoCapture(video_path)) hTrack = tracker() net = Detector(bytes("yolo/yolov3_head.cfg", encoding="utf-8"), bytes("yolo/yolov3_head.weights", encoding="utf-8"), 0, bytes("yolo/head.data", encoding="utf-8") ) digits_net = Detector( bytes("yolo/yolov3_digits.cfg", encoding="utf-8"), bytes("yolo/yolov3_digits.weights", encoding="utf-8"), 0, bytes("yolo/digits.data", encoding="utf-8") ) for i in range(int(total_number)): if i == 0: results = [] frames = [] for j, cap in enumerate(caps): ret, frame = cap.read() frames.append(frame) dark_frame = Image(frame) results.append(net.detect(dark_frame)) three_dim_locs = deter_3d_loc(results, root_dir) print("init three dim locs:{}".format(three_dim_locs)) hTrack.initTracker(frames, three_dim_locs, 100, digits_net) else: results = [] frames = [] for j, cap in enumerate(caps): ret, frame = cap.read() frames.append(frame) dark_frame = Image(frame) results.append(net.detect(dark_frame)) print("frame {} yolo_res:{}".format(i, results)) three_dim_locs = deter_3d_loc(results, root_dir) print("frame {} dim locs:{}".format(i, three_dim_locs)) hTrack.next(frames, three_dim_locs) hTrack.addObjects(frames, three_dim_locs, digits_net) displayed = hTrack.showResults(frames, 0, results=results, yolo=True) if displayed is not None: cv2.imshow(WINDOW_TITLE, displayed) cv2.waitKey(100) else: break if cv2.waitKey(21) == 27: break <file_sep>/three_dimension.py from camera_world import transto3d, transto2d from itertools import product def ishead(yolo_res): cat, prob, _ = yolo_res if cat == b"head" and prob > 0.5: return True else: return False def in_court(p_3d): x, y, z = p_3d if z < 0: return False if x > 9000 or x < 0: return False if y > 9000 or y < -9000: return False if z > 4800: return False return True def res_filter(results): results = filter(ishead, results) return [bounds for cat, score, bounds in results] def pixel_dist(p_2d, view_result): x, y, _, _ = view_result x_0, y_0 = p_2d[0] return abs(x - x_0) + abs(y - y_0) def is_projection(p_2d, view_results): for view_result in view_results: if pixel_dist(p_2d, view_result) < 12: return True return False def reproject_deter(p_3ds, view_results, root_dir): p_3ds = list(filter(in_court, p_3ds)) deter = [0] * len(p_3ds) for j in range(len(view_results)): p_2ds = transto2d(p_3ds, j, root_dir) for i, p_2d in enumerate(p_2ds): print(p_2d,view_results[j]) if is_projection(p_2d, view_results[j]): deter[i] += 1 new_p3ds = [] for i, d in enumerate(deter): if d == 2: new_p3ds.append(p_3ds[i]) return new_p3ds # now only support 2 view def deter_3d_loc(results, root_dir): assert len(results) == 2, "now only support 2 view" view_1_results = results[0] view_1_results = res_filter(view_1_results) view_2_results = results[1] view_2_results = res_filter(view_2_results) results = [view_1_results,view_2_results] print("results after filter:{}".format(results)) view_pair_reses = product(view_1_results, view_2_results) p_3ds = [] for i, view_pair_res in enumerate(view_pair_reses): view_1_result, view_2_result = view_pair_res x1, y1, _, _ = view_1_result x2, y2, _, _ = view_2_result p_3d = transto3d([x1, y1], [x2, y2], 0, 1, root_dir) p_3ds.append(p_3d[0]) return reproject_deter(p_3ds,results,root_dir) def corner_points(loc, man_ray, man_height, head_height): x, y, z = loc points = [[x + man_ray, y + man_ray, z - (man_height - head_height/2)], [x + man_ray, y - man_ray, z - (man_height - head_height/2)], [x - man_ray, y + man_ray, z - (man_height - head_height/2)], [x - man_ray, y - man_ray, z - (man_height - head_height/2)], [x + man_ray, y + man_ray, z + (head_height/2)], [x + man_ray, y - man_ray, z + (head_height / 2)], [x - man_ray, y + man_ray, z + (head_height / 2)], [x - man_ray, y - man_ray, z + (head_height / 2)]] return points def cal_rect(loc, camera_id, man_ray=200, man_height=1800,head_height=200,root_dir=""): points = corner_points(loc, man_ray, man_height, head_height) point_projection = transto2d(points, camera_id, root_dir) x_points = [int(p[0][0]) for p in point_projection] x_min, x_max = min(x_points), max(x_points) y_points = [int(p[0][1]) for p in point_projection] y_min, y_max = min(y_points), max(y_points) vec = sorted(y_points)[4:] y_mid = int(sum(vec) / 4) return [x_min, y_min, x_max - x_min, y_mid - y_min]<file_sep>/camera_world.py import json import os from glob import glob import cv2 import numpy as np def rectify(points, camera_id, root_dir): camera_info = load_camera_info(root_dir, camera_id) camera_matrix = np.matrix(camera_info["camera_matrix"], dtype=np.float32) dist_coefs = np.array(camera_info['dist_coefs'], dtype=np.float32) rectified = cv2.undistortPoints(points, camera_matrix, dist_coefs) return rectified def load_camera_info(root_dir, camera_id): camera_info_dir = root_dir + "camera/camera{}.json".format(camera_id) with open(camera_info_dir, "r") as camera_info_file: camera_info = json.load(camera_info_file) return camera_info # different transto2d def transto2d(points, camera_id, root_dir): points = np_wrappy(points) camera_info = load_camera_info(root_dir, camera_id) camera_matrix = np.matrix(camera_info["camera_matrix"], dtype=np.float32) dist_coefs = np.zeros((5,1)) r_vet = np.array(camera_info["r_vet"], dtype=np.float32) t_vet = np.array(camera_info["t_vet"], dtype=np.float32) res = cv2.projectPoints(points, r_vet, t_vet, camera_matrix, dist_coefs)[0] return res def projMat(camera_id, root_dir): camera_info = load_camera_info(root_dir, camera_id) camera_matrix = np.matrix(camera_info["camera_matrix"], dtype=np.float32) r_vet = np.array(camera_info["r_vet"], dtype=np.float32) t_vet = np.array(camera_info["t_vet"], dtype=np.float32) r_mat, _ = cv2.Rodrigues(r_vet) m = np.dot(camera_matrix, r_mat) t = np.dot(camera_matrix, t_vet) rt_mat = np.matrix([ [m[0, 0], m[0, 1], m[0, 2], t[0, 0]], [m[1, 0], m[1, 1], m[1, 2], t[1, 0]], [m[2, 0], m[2, 1], m[2, 2], t[2, 0]] ]) return rt_mat def np_wrappy(points): if not isinstance(points, np.ndarray): points = np.array(points, dtype=np.float32) return points def transto3d(image1_point, image2_point, camera1_id, camera2_id, root_dir): image1_points = np.array(image1_point, dtype=np.float32).reshape((2, 1)) # image1_points = rectify(image1_points,camera1_id,root_dir) image2_points = np.array(image2_point, dtype=np.float32).reshape((2, 1)) # image2_points = rectify(image2_points,camera2_id,root_dir) projMat1 = projMat(camera1_id, root_dir) projMat2 = projMat(camera2_id, root_dir) X = cv2.triangulatePoints(projMat1, projMat2, image1_points, image2_points) X /= X[3] X = X[:3].T.reshape((1, 3)).tolist() return X def load_marker_file(image_marker_dir): with open(image_marker_dir, "r") as image_marker_file: image_makers = json.load(image_marker_file) p1 = image_makers['1'] p2 = image_makers['2'] p3 = image_makers['3'] p4 = image_makers['4'] p1_3d = image_makers['1_3d'] p2_3d = image_makers['2_3d'] p3_3d = image_makers['3_3d'] p4_3d = image_makers['4_3d'] image_floor_points = np.array([ p1, p2, p3, p4 ], dtype=np.float32).reshape((4, 1, 2)) object_floor_points = np.array([ p1_3d, p2_3d, p3_3d, p4_3d ], dtype=np.float32).reshape((4, 1, 3)) return image_floor_points, object_floor_points def load_inter_camera_matrix(camera_info_dir): with open(camera_info_dir) as camera_info_file: camera_info = json.load(camera_info_file) camera_matrix = np.array(camera_info["camera_matrix"], dtype=np.float32) distCoeffs = np.array(camera_info['dist_coefs'], dtype=np.float32) return camera_matrix, distCoeffs def camera_world(root_dir, camera_id, camera_info_dir): image_marker_dir = root_dir + "/marker/marker{}.json".format(camera_id) image_floor_points, object_floor_points = load_marker_file(image_marker_dir) camera_matrix, dist_coefs = load_inter_camera_matrix(camera_info_dir) _, r_vet, t_vet = cv2.solvePnP(object_floor_points, image_floor_points, camera_matrix, dist_coefs) ex_dict = {"r_vet": r_vet.tolist(), "t_vet": t_vet.tolist()} with open(camera_info_dir, "r") as camera_info_file: camera_info = json.load(camera_info_file) camera_info.update(ex_dict) with open(camera_info_dir, "w") as camera_info_file: json.dump(camera_info, camera_info_file) def calibrate(input, out, debug_dir=None, framestep=20, fisheye=False): if '*' in input: source = glob(input) else: source = cv2.VideoCapture(input) pattern_size = (9, 6) pattern_points = np.zeros((np.prod(pattern_size), 3), np.float32) pattern_points[:, :2] = np.indices(pattern_size).T.reshape(-1, 2) # pattern_points *= square_size obj_points = [] img_points = [] h, w = 0, 0 i = -1 while True: i += 1 if isinstance(source, list): if i == len(source): break img = cv2.imread(source[i]) else: retval, img = source.read() if not retval: break if i % framestep != 0: continue print('Searching for chessboard in frame ' + str(i) + '...'), img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) h, w = img.shape[:2] found, corners = cv2.findChessboardCorners(img, pattern_size, cv2.CALIB_CB_FILTER_QUADS) if found: term = (cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_COUNT, 30, 0.1) cv2.cornerSubPix(img, corners, (5, 5), (-1, -1), term) if debug_dir: img_chess = cv2.cvtColor(img, cv2.COLOR_GRAY2BGR) cv2.drawChessboardCorners(img_chess, pattern_size, corners, found) cv2.imwrite(os.path.join(debug_dir, '%04d.png' % i), img_chess) if not found: print('not found') continue img_points.append(corners.reshape(1, -1, 2)) obj_points.append(pattern_points.reshape(1, -1, 3)) print('ok') # if corners!=None: # with open(corners, 'wb') as fw: # pickle.dump(img_points, fw) # pickle.dump(obj_points, fw) # pickle.dump((w, h), fw) print('\nPerforming calibration...') if fisheye: rms, camera_matrix, dist_coefs, rvecs, tvecs = cv2.fisheye.calibrate(obj_points, img_points, (w, h), None, None) else: rms, camera_matrix, dist_coefs, rvecs, tvecs = cv2.calibrateCamera(obj_points, img_points, (w, h), None, None) print("RMS:", rms) print("camera matrix:\n", camera_matrix) print("distortion coefficients: ", dist_coefs.ravel()) calibration = {'rms': rms, 'camera_matrix': camera_matrix.tolist(), 'dist_coefs': dist_coefs.tolist()} with open(out, 'w') as fw: json.dump(calibration, fw) <file_sep>/jersey.py from pydarknet import Image from functools import partial import numpy as np import cv2 from three_dimension import cal_rect def score_jersey(jersus): if jersus is None: score = -1 elif jersus > 20: score = 1e-7 else: score = abs(20 - jersus) return score def loc_jersey(net, frames, locs): different_view_jersus = [] for i, frame in enumerate(frames): rects = [cal_rect(loc, i) for loc in locs] jersuses = [] for removed_occ_frame in remove_occ_frame(rects, frame): dealed_frame, _ = removed_occ_frame _, jersus = search_number(net, dealed_frame) jersuses.append(jersus) different_view_jersus.append(jersuses) return [max(res_jersuses, key=score_jersey) for res_jersuses in zip(*different_view_jersus)] # input rect and frame, which may be occluded def search_number(net, frame, rect=None): if rect is not None: rio = rect_rio(frame, rect) dark_rio = Image(rio) digit_reses = net.detect(dark_rio) found = False if digit_reses: found = True digit_reses = filter_by_area(digit_reses) if len(digit_reses) > 2: return False, None digit_reses = sort_digits(digit_reses) final_res = [cls for cls, _, _ in digit_reses] final_id = trans_res_id(final_res) return found, final_id return found, None else: rio = frame dark_rio = Image(rio) digit_reses = net.detect(dark_rio) found = False if digit_reses: found = True digit_reses = filter_by_area(digit_reses) if len(digit_reses) > 2: return False, None digit_reses = sorted_digits(digit_reses) final_res = [cls for cls, _, _ in digit_reses] final_id = trans_res_id(final_res) return found, final_id return found, None def good_area(main_area, digit_res): _, _, (_, _, w, h) = digit_res if w * h > 0.7 * main_area: return True else: return False def filter_by_area(digit_reses): if len(digit_reses) == 1: return digit_reses main_digit = max(digit_reses, key=lambda x: x[2][2] * x[2][3]) main_area = main_digit[2][2] * main_digit[2][3] suit_main_area = partial(good_area, main_area) digit_reses = filter(suit_main_area, digit_reses) return digit_reses def sorted_digits(digit_reses): digit_reses = sorted(digit_reses, key=lambda x: x[2][0]) return digit_reses def trans_res_id(final_res): final_res = list(map(int, final_res)) if len(final_res) == 1: jersus = final_res else: final_res = final_res[:2] assert final_res[0] < 2, "jersus # shold not be big" jersus = final_res[0] * 10 + final_res[1] return jersus def rect_area(rect): x, y, w, h = rect return w * h def rect_rio(frame, rect): x, y, w, h = rect rio = frame[y:y + h, x:x + w] return rio def IOU(rect1, rect2): x1, y1, w1, h1 = rect1 x2, y2, w2, h2 = rect2 overlap_x = w1 + w2 - (max(x1 + w1, x2 + w2) - min(x1, x2)) overlap_y = h1 + h2 - (max(y1 + h1, y2 + h2) - min(y1, y2)) overlap_area = overlap_x * overlap_y return overlap_area def remove_occ(frame, src_rect, other_rects): src_rectangle = np.zeros(frame.shape[0:2], dtype="uint8") src_x, src_y, src_w, src_h = src_rect cv2.rectangle(src_rectangle, (src_x, src_y), (src_x + src_w, src_y + src_h), 255, -1) occ_rectangle = src_rectangle.copy() for i, rect in enumerate(other_rects): if IOU(rect, src_rect) > 0: x, y, w, h = rect cv2.rectangle(occ_rectangle, (x, y), (x + w, y + h), 0, -1) mask = cv2.bitwise_and(src_rectangle, occ_rectangle) final_frame = cv2.bitwise_and(frame, frame, mask=mask) return final_frame def remove_occ_frame(rects, frame): rects_and_index = [(i, rect) for i, rect in enumerate(rects)] rects_by_dist = sorted(rects_and_index, key=lambda x: rect_area(x[1]), reverse=True) dealed_frames = [] for i, rect_and_index in enumerate(rects_by_dist): rect, index = rect_and_index if i == len(rects_by_dist) - 1: dealed_frame = rect_rio(frame, rect) else: dealed_frame = remove_occ(frame, rect, rects_by_dist[i + 1:]) dealed_frames.append((dealed_frame, index)) dealed_rect_frames = sorted(dealed_frames, key=lambda x: x[1]) return dealed_rect_frames <file_sep>/tracker.py from particleFilter import * import cv2 import math from functools import partial from features import initFeatures from three_dimension import res_filter, cal_rect from jersey import loc_jersey import copy def loc_dis_traj(loc, traj): x1, y1, z1 = loc loc2 = traj.object.getParticleCenter() x2, y2, z2 = loc2 return math.sqrt( (x1 - x2) ** 2 + (y1 - y2) ** 2 + (z1 - z2) ** 2) class trajectory: def __init__(self, object, startFrame, features): self.pf = object self.startFrame = startFrame self.features = features self.locs = {} def update_features(self, new_loc, frames): features = self.features for i, (frame, feature) in enumerate(zip(frames, features)): new_rect = cal_rect(new_loc, i) H, mosse = feature.hog, feature.mosse H.update(frame, new_rect) mosse.update(frame, new_rect) def feature_pred(self, frames): features = self.features for frame, feature in zip(frames, features): mosse = feature.mosse mosse.predict(frame) class tracker: def __init__(self): self.nTrajectories = 0 self.frameNumber = 0 self.trajectories = {} self.totalTrajectories = 0 def initTracker(self, frames, locs, particlePerObject, net): self.nTrajectories = len(locs) self.totalTrajectories = self.nTrajectories self.p_perObject = particlePerObject self.trajectories = {} jerseys = loc_jersey(net, frames, locs) for i, loc in enumerate(locs): pf = particleFilter(loc, particlePerObject) it = trajectory(pf, 0, initFeatures(frames, locs[i])) it.locs[self.frameNumber] = loc if jerseys is None: objectId = 100 + i else: objectId = jerseys it.pf.weight = 1 self.trajectories[objectId] = it def next(self, frames, yolo_locs): for traj in self.trajectories.values(): traj.feature_pred(frames) traj.pf.transition(traj.locs) traj.pf.updateWeight(frames, traj.features, yolo_locs) traj.pf.normalizeWeight() traj.pf.resample() traj.locs[self.frameNumber] = traj.object.getParticleCenter() traj.update_features(traj.object.getParticleCenter(), frames) self.mergeTrack() self.frameNumber += 1 # TODO may should adjust addobjects and next def addObjects(self, frames, locs, net): if len(locs) < 1: return nw = 0 jerseys = loc_jersey(net, frames, locs) all_trajs = list(self.trajectories.keys()) for i, loc in enumerate(locs): jersey = jerseys[i] dist_to_traj = partial(loc_dis_traj, loc) if jersey is not None: if self.trajectories.get(jersey): traj = self.trajectories[jersey] traj.pf.resetParticles(loc) traj.features = traj.update_features(frames, loc) traj.pf.weight = 1 all_trajs.remove(jersey) else: trajs = [self.trajectories.get(ID) for ID in all_trajs] nearest_traj = min(trajs, key=dist_to_traj) if dist_to_traj(nearest_traj)<300: nearest_traj.pf.resetParticles(loc) nearest_traj.features = nearest_traj.update_features(frames, loc) nearest_traj.pf.weight = 1 all_trajs.remove(jersey) self.trajectories[jersey] = copy.copy(nearest_traj) self.trajectories.pop(nearest_traj.pf.objectId) else: pf = particleFilter(loc, self.p_perObject) pf.objectId = nw + self.totalTrajectories pf.weight = 0.5 traj = trajectory(pf, self.frameNumber, initFeatures(frames, locs[i])) self.trajectories[jersey] = traj traj.locs[self.frameNumber] = loc nw += 1 else: trajs = [self.trajectories.get(ID) for ID in all_trajs] nearest_traj = min(trajs, key=dist_to_traj) if dist_to_traj(nearest_traj) < 300: nearest_traj.pf.resetParticles(loc) nearest_traj.features = nearest_traj.update_features(frames, loc) nearest_traj.pf.weight = 1 all_trajs.remove(jersey) else: pf = particleFilter(loc, self.p_perObject) pf.objectId = 100 + nw + self.totalTrajectories pf.weight = 0.5 traj = trajectory(pf, self.frameNumber, initFeatures(frames, locs[i])) self.trajectories[pf.objectId] = traj traj.locs[self.frameNumber] = loc nw += 1 for ID,traj in self.trajectories.items(): if ID in all_trajs: traj.pf.weight -= 0.5 else: if traj.pf.weight < 1: traj.pf.weight += 0.5 self.nTrajectories += nw self.totalTrajectories += nw for j, traj in enumerate(self.trajectories.values()): if traj.pf.weight < -3: self.nTrajectories -= 1 print("remove {}".format(traj.pf.objectId)) self.trajectories.pop(traj.pf.objectId) def showResults(self, frames, camera_id, results=None, yolo=False): if yolo: view1_result, view2_result = results view1_result = res_filter(view1_result) view2_result = res_filter(view2_result) results = [view1_result, view2_result] results = results[camera_id] displayed = frames[camera_id] for id, traj in self.trajectories.items(): print("objectId:{} weight:{}".format(traj.object.objectId, traj.object.weight)) if traj.object.weight >= 1: color = ((12 * id) % 255, (24 * id) % 255, (48 * id) % 255 ) displayed = traj.pf.displayParticles(displayed, (0, 0, 255), color, camera_id) if results: for i, result in enumerate(results): x, y, w, h = result displayed = cv2.rectangle( displayed, (int(x - w / 2), int(y - h / 2)), (int(x + w / 2), int(y + h / 2)), (0, 255, 0) ) return displayed def mergeTrack(self): for id, traj in self.trajectories.items(): x = traj.pf.particles[0].x y = traj.pf.particles[0].y z = traj.pf.particles[0].z for other_id, other_traj in self.trajectories.items(): x1 = other_traj.pf.particles[0].x y1 = other_traj.pf.particles[0].y z1 = other_traj.pf.particles[0].z if id == other_id: continue d = math.sqrt((x1 - x) ** 2 + (y1 - y) ** 2 + (z1 - z) ** 2) if d < 300: if traj.startFrame <= other_traj.startFrame: traj.pf.weight = 1.5 other_traj.pf.weight -= 1 else: other_traj.pf.weight = 1.5 traj.pf.weight -= 1 <file_sep>/requirements.txt numpy scikit-image yolo34py-gpu opencv-python <file_sep>/particleFilter.py import numpy as np import cv2 import copy from filterpy.monte_carlo import residual_resample from three_dimension import cal_rect import math TRANS_X_STD = 0.5 TRANS_Y_STD = 1.0 TRANS_Z_STD = 2.0 A1 = 2.0 A2 = -1.0 B0 = 1.000 # bins of HSV in histogram NH = 10 NS = 10 NV = 10 bins = [NH, NS, NV] # distribution parameter LAMBDA = 20 court_x = 9000 court_y = 9000 court_z = 8000 eps = 1e-5 def generate_loc(h, R): z = np.random.uniform(low=0, high=h, size=(1,))[0] x = np.random.normal(loc=0, scale=R, size=1) y = np.random.normal(loc=0, scale=R, size=1) return np.array([x, y, z]) def R_trans(a, b, c): sqrt_bc = math.sqrt(b ** 2 + c ** 2) sqrt_abc = math.sqrt(a ** 2 + b ** 2 + c ** 2) Rx = np.matrix([ [1, 0, 0, 0], [0, c / sqrt_bc, b / sqrt_bc, 0], [0, -b / sqrt_bc, c / sqrt_bc, 0], [0, 0, 0, 1] ]) Ry = np.matrix([ [sqrt_bc / sqrt_abc, 0, a / sqrt_abc, 0], [0, 1, 0, 0], [-a / sqrt_abc, 0, sqrt_bc / sqrt_abc, 0], [0, 0, 0, 1] ]) return (Rx * Ry).I def T_trans(src): a, b, c = src T = np.matrix([ [1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 1, 0], [a, b, c, 1] ]) return T def latest_fit(locs): x = [point[0] for point in list(locs.values())[-10:]] y = [point[1] for point in list(locs.values())[-10:]] z = [point[2] for point in list(locs.values())[-10:]] index = np.array(list(range(10))) xp = np.polyfit(index, x, 2) new_x = np.poly1d(xp)(10) yp = np.polyfit(index, y, 2) new_y = np.poly1d(yp)(10) zp = np.polyfit(index, z, 2) new_z = np.poly1d(zp)(10) return new_x, new_y, new_z class Particle3d: def __init__(self, x, y, z, xp, yp, zp, x0, y0, z0, w): super(Particle3d, self).__init__() self.x = x # current x coordinate self.y = y # current y coordinate self.z = z # current z coordinate self.xp = xp # previous x coordinate self.yp = yp # previous y coordinate self.zp = zp # previous z coordinate self.x0 = x0 # original x coordinate self.y0 = y0 # original y coordinate self.z0 = z0 # original z coordinat # self.radius = 300 # original width of region described by particle # self.height = 1800 # original height of region described by particle self.w = w # weight def reset(self, loc): x, y, z = loc self.x = x self.y = y self.z = z self.w = 1 / 100 # # def transition(self, locs): # x = A1 * (self.x - self.x0) + A2 * (self.xp - self.x0) + B0 * np.random.normal(0, TRANS_X_STD) + self.x0 # y = A1 * (self.y - self.y0) + A2 * (self.yp - self.y0) + B0 * np.random.normal(0, TRANS_Y_STD) + self.y0 # z = A1 * (self.z - self.z0) + A2 * (self.zp - self.z0) + B0 * np.random.normal(0, TRANS_Z_STD) + self.z0 # # self.x = max(0.0, min(court_x - 1.0, x)) # self.y = max(-8999, min(court_y - 1.0, y)) # self.z = max(0.0, min(court_z - 1.0, z)) # self.xp = self.x # self.yp = self.y # self.zp = self.z # self.w = 0 def transition(self, method=None, last_loc=None, h=None, R_M=None, T_M=None, R=None): if method == "moment": x = A1 * (self.x - self.x0) + A2 * (self.xp - self.x0) + B0 * np.random.normal(0, TRANS_X_STD) + self.x0 y = A1 * (self.y - self.y0) + A2 * (self.yp - self.y0) + B0 * np.random.normal(0, TRANS_Y_STD) + self.y0 z = A1 * (self.z - self.z0) + A2 * (self.zp - self.z0) + B0 * np.random.normal(0, TRANS_Z_STD) + self.z0 elif method == "sphere": x, y, z = last_loc x = x + B0 * np.random.normal(loc=0, scale=200, size=1) y = y + B0 * np.random.normal(loc=0, scale=200, size=1) z = z + B0 * np.random.normal(loc=0, scale=200, size=1) elif method == "pillar": init_loc = generate_loc(h, R) new_loc = init_loc * R_M * T_M x, y, z = new_loc else: x, y, z = 0, 0, 0 self.x = max(0.0, min(court_x - 1.0, x)) self.y = max(-8999.0, min(court_y - 1.0, y)) self.z = max(0.0, min(court_z - 1.0, z)) self.xp = self.x self.yp = self.y self.zp = self.z self.w = 0 def dis_3d(self, loc): x, y, z = loc return math.sqrt((self.x - x) ** 2 + (self.y - y) ** 2 + (self.z - z) ** 2) def displayParticle(self, frame, color, camera_id, ID): loc = (self.x, self.y, self.z) rect = cal_rect(loc, camera_id) x, y, w, h = rect displayed = cv2.rectangle(frame.copy(), (x, y), (x + w, y + h), color) tx, ty = x + 5, y + 5 displayed = cv2.putText(displayed, str(ID), (tx, ty), cv2.FONT_HERSHEY_SIMPLEX, 1, (255, 255, 255)) return displayed class particleFilter: def __init__(self, loc, particlesPerObject): super(particleFilter, self).__init__() self.nParticles = particlesPerObject x, y, z = loc self.objectId = 0 self.weight = 0 self.particles = [Particle3d(x, y, z, x, y, z, x, y, z, 0) for i in range(self.nParticles)] def resetParticles(self, loc): for i in range(self.nParticles): self.particles[i].reset(loc) def displayParticles(self, image, nColor, hColor, camera_id, SHOW_ALL=False): if SHOW_ALL: displayed = image for i in range(self.nParticles - 1, -1, -1): if i == 0: color = hColor else: color = nColor displayed = self.particles[i].displayParticle(displayed.copy(), color, camera_id, self.objectId) else: color = hColor displayed = self.particles[0].displayParticle(image.copy(), color, camera_id, self.objectId) return displayed def getParticleCenter(self): return self.particles[0].x, self.particles[0].y, self.particles[0].z def transition(self, locs): if len(locs) < 10: for i in range(self.nParticles): self.particles[i].transition(method="moment") else: src1 = list(locs.values())[-1] src2 = latest_fit(locs) x1, y1, z1 = src1 x2, y2, z2 = src2 R = 150 a, b, c = x2 - x1, y2 - y1, z2 - z1 h = math.sqrt(a ** 2 + b ** 2 + c ** 2) R_M = R_trans(a, b, c) T_M = T_trans(src1) for i in range(self.nParticles): if i <= self.nParticles // 2: self.particles[i].transition(method="sphere", last_loc=src1) else: self.particles[i].transition(method="pillar", h=h, R=R, R_M=R_M, T_M=T_M) def normalizeWeight(self): sumWeight = sum([p.w for p in self.particles]) for i in range(self.nParticles): self.particles[i].w /= sumWeight def resample(self): weights = [p.w for p in self.particles] resampleIndex = residual_resample(weights) newParticles = [copy.copy(self.particles[i]) for i in resampleIndex] self.particles = newParticles def updateWeight(self, frames, view_features, yolo_locs): for p in self.particles: min_dis_loc = min(yolo_locs, key=p.dis_3d) min_dis = p.dis_3d(min_dis_loc) w = math.exp(-min_dis / 500) view_weight = 1 for i, (frame, feature) in enumerate(zip(frames, view_features)): hog, mosse = feature.hog, feature.mosse rect = cal_rect((p.x, p.y, p.z), i) mosse_weight = mosse.score_by_pre(rect) hog_weight = hog.score_by_dis(rect, frame) view_weight *= (mosse_weight * hog_weight) p.w = w * math.sqrt(view_weight + eps)
b0a245445e54a82d80d7ad270ab09f7b13f1c172
[ "Python", "Text" ]
7
Python
icicle4/patricle_filter
90eef1c6d901689cd65a40ecf124ffb9fbc3a711
b9a4fb69f0bebe93581cf618959fce117fe441c9
refs/heads/master
<repo_name>dstroot/.osx-defaults<file_sep>/defaults/dock.sh #! /bin/sh # ------------------------------------------------------------------------------ # Copyright (c) 2014 <NAME> # All rights reserved. # # 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 THE COPYRIGHT HOLDER OR CONTRIBUTORS 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. # ------------------------------------------------------------------------------ # NAME: dock.sh # PURPOSE: Setup dock # VERSION: 1.0 Initial version # ------------------------------------------------------------------------------ # echo "Enable highlight hover effect for the grid view of a stack (Dock)" # defaults write com.apple.dock mouse-over-hilite-stack -bool true echo "Set the icon size of Dock items to 50 pixels" defaults write com.apple.dock tilesize -int 50 echo "Change minimize/maximize window effect" defaults write com.apple.dock mineffect -string "scale" # # echo "Minimize windows into their application’s icon" # defaults write com.apple.dock minimize-to-application -bool true # # echo "Enable spring loading for all Dock items" # defaults write com.apple.dock enable-spring-load-actions-on-all-items -bool true # # echo "Show indicator lights for open applications in the Dock" # defaults write com.apple.dock show-process-indicators -bool true echo "Don’t animate opening applications from the Dock" defaults write com.apple.dock launchanim -bool false # echo "Disable Dashboard" # defaults write com.apple.dashboard mcx-disabled -bool true # # echo "Don’t show Dashboard as a Space" # defaults write com.apple.dock dashboard-in-overlay -bool true # # echo "Don’t automatically rearrange Spaces based on most recent use" # defaults write com.apple.dock mru-spaces -bool false echo "Remove the auto-hiding Dock delay" defaults write com.apple.dock autohide-delay -float 0 echo "Remove the animation when hiding/showing the Dock" defaults write com.apple.dock autohide-time-modifier -float 0 echo "Automatically hide and show the Dock" defaults write com.apple.dock autohide -bool true # echo "Make Dock icons of hidden applications translucent" # defaults write com.apple.dock showhidden -bool true # # echo "Disable the Launchpad gesture (pinch with thumb and three fingers)" # #defaults write com.apple.dock showLaunchpadGestureEnabled -int 0 # # echo "Reset Launchpad, but keep the desktop wallpaper intact" # find "${HOME}/Library/Application Support/Dock" -name "*-*.db" -maxdepth 1 -delete # echo "Add iOS Simulator to Launchpad" # sudo ln -sf "/Applications/Xcode.app/Contents/Developer/Applications/iOS Simulator.app" "/Applications/iOS Simulator.app" # echo "Add a spacer to the left side of the Dock (where the applications are)" # #defaults write com.apple.dock persistent-apps -array-add '{tile-data={}; tile-type="spacer-tile";}' # # echo "Add a spacer to the right side of the Dock (where the Trash is)" # #defaults write com.apple.dock persistent-others -array-add '{tile-data={}; tile-type="spacer-tile";}' echo "Set hot corners" # Possible values: # 0: no-op # 2: Mission Control # 3: Show application windows # 4: Desktop # 5: Start screen saver # 6: Disable screen saver # 7: Dashboard # 10: Put display to sleep # 11: Launchpad # 12: Notification Center # Top left screen corner → Nothing defaults write com.apple.dock wvous-tl-corner -int 0 defaults write com.apple.dock wvous-tl-modifier -int 0 # Top right screen corner → Nothing defaults write com.apple.dock wvous-tr-corner -int 0 defaults write com.apple.dock wvous-tr-modifier -int 0 # Bottom left screen corner → Start screen saver defaults write com.apple.dock wvous-bl-corner -int 5 defaults write com.apple.dock wvous-bl-modifier -int 0 # Bottom right screen corner → Mission Control defaults write com.apple.dock wvous-br-corner -int 2 defaults write com.apple.dock wvous-br-modifier -int 0 <file_sep>/defaults/general.sh #! /bin/sh # ------------------------------------------------------------------------------ # Copyright (c) 2014 <NAME> # All rights reserved. # # 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 THE COPYRIGHT HOLDER OR CONTRIBUTORS 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. # ------------------------------------------------------------------------------ # NAME: general.sh # PURPOSE: Set general UI # VERSION: 1.0 Initial version # ------------------------------------------------------------------------------ # echo "Restart automatically if the computer freezes" # sudo systemsetup -setrestartfreeze on # # echo "Check for software updates daily, not just once per week" # defaults write com.apple.SoftwareUpdate ScheduleFrequency -int 1 echo "Menu bar: Set date and time format e.g. Sun 11 Aug 16:55" defaults write com.apple.menuextra.clock DateFormat -string "EEE MMM d h:mm:ss a" # echo "Disable the sound effects on boot." # sudo nvram SystemAudioVolume=" " echo "Automatically quit printer app once the print jobs is complete" defaults write com.apple.print.PrintingPrefs "Quit When Finished" -bool true # echo "Save to disk (not to iCloud) by default" # defaults write NSGlobalDomain NSDocumentSaveNewDocumentsToCloud -bool false # # Disable smart quotes as they’re annoying when typing code # defaults write NSGlobalDomain NSAutomaticQuoteSubstitutionEnabled -bool false # # # Disable smart dashes as they’re annoying when typing code # defaults write NSGlobalDomain NSAutomaticDashSubstitutionEnabled -bool false # echo "Set sidebar icon size to medium" # defaults write NSGlobalDomain NSTableViewDefaultSizeMode -int 2 # # echo "Always show scrollbars" # defaults write NSGlobalDomain AppleShowScrollBars -string "Always" # # Possible values: `WhenScrolling`, `Automatic` and `Always` # # echo "Increase window resize speed for Cocoa applications" # defaults write NSGlobalDomain NSWindowResizeTime -float 0.001 # # echo "Expand save panel by default" # defaults write NSGlobalDomain NSNavPanelExpandedStateForSaveMode -bool true # defaults write NSGlobalDomain NSNavPanelExpandedStateForSaveMode2 -bool true # # echo "Expand print panel by default" # defaults write NSGlobalDomain PMPrintingExpandedStateForPrint -bool true # defaults write NSGlobalDomain PMPrintingExpandedStateForPrint2 -bool true # # echo "Disable the “Are you sure you want to open this application?” dialog" # defaults write com.apple.LaunchServices LSQuarantine -bool false # # echo "Remove duplicates in the “Open With” menu (also see `lscleanup` alias)" # /System/Library/Frameworks/CoreServices.framework/Frameworks/LaunchServices.framework/Support/lsregister -kill -r -domain local -domain system -domain user # # echo "Display ASCII control characters using caret notation in standard text views" # echo "Try e.g. `cd /tmp; unidecode "\x{0000}" > cc.txt; open -e cc.txt`" # defaults write NSGlobalDomain NSTextShowsControlCharacters -bool true # # echo "Disable Resume system-wide" # defaults write com.apple.systempreferences NSQuitAlwaysKeepsWindows -bool false # # echo "Disable automatic termination of inactive apps" # defaults write NSGlobalDomain NSDisableAutomaticTermination -bool true # # echo "Set Help Viewer windows to non-floating mode" # defaults write com.apple.helpviewer DevMode -bool true <file_sep>/defaults/screen.sh #! /bin/sh # ------------------------------------------------------------------------------ # Copyright (c) 2014 <NAME> # All rights reserved. # # 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 THE COPYRIGHT HOLDER OR CONTRIBUTORS 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. # ------------------------------------------------------------------------------ # NAME: screen.sh # PURPOSE: Setup screen # VERSION: 1.0 Initial version # ------------------------------------------------------------------------------ # # echo "Require password immediately after sleep or screen saver begins" # defaults write com.apple.screensaver askForPassword -int 1 # defaults write com.apple.screensaver askForPasswordDelay -int 0 # # echo "Save screenshots to the desktop" # defaults write com.apple.screencapture location -string "${HOME}/Desktop" # # echo "Save screenshots in PNG format" # # other options: BMP, GIF, JPG, PDF, TIFF # defaults write com.apple.screencapture type -string "png" # # echo "Disable shadow in screenshots" # defaults write com.apple.screencapture disable-shadow -bool true # # Enable subpixel font rendering on non-Apple LCDs # defaults write NSGlobalDomain AppleFontSmoothing -int 2 # # Enable HiDPI display modes (requires restart) # sudo defaults write /Library/Preferences/com.apple.windowserver DisplayResolutionEnabled -bool true <file_sep>/defaults/finder.sh #! /bin/sh # ------------------------------------------------------------------------------ # Copyright (c) 2014 <NAME> # All rights reserved. # # 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 THE COPYRIGHT HOLDER OR CONTRIBUTORS 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. # ------------------------------------------------------------------------------ # NAME: finder.sh # PURPOSE: Setup trackpad # VERSION: 1.0 Initial version # ------------------------------------------------------------------------------ # # Finder: allow quitting via ⌘ + Q; doing so will also hide desktop icons # defaults write com.apple.finder QuitMenuItem -bool true # echo "Finder: disable window animations and Get Info animations" # defaults write com.apple.finder DisableAllAnimations -bool true # # echo "Set Desktop as the default location for new Finder windows" # defaults write com.apple.finder NewWindowTarget -string "PfDe" # defaults write com.apple.finder NewWindowTargetPath -string "file://${HOME}/Desktop/" # # echo "Show icons for hard drives, servers, and removable media on the desktop" # defaults write com.apple.finder ShowExternalHardDrivesOnDesktop -bool true # defaults write com.apple.finder ShowHardDrivesOnDesktop -bool false # defaults write com.apple.finder ShowMountedServersOnDesktop -bool true # defaults write com.apple.finder ShowRemovableMediaOnDesktop -bool true # echo "Finder: show hidden files by default" # #defaults write com.apple.finder AppleShowAllFiles -bool true # # echo "Finder: show all filename extensions" # defaults write NSGlobalDomain AppleShowAllExtensions -bool true # echo "Finder: show status bar" # defaults write com.apple.finder ShowStatusBar -bool true # # echo "Finder: show path bar" # defaults write com.apple.finder ShowPathbar -bool true # # echo "Finder: allow text selection in Quick Look" # defaults write com.apple.finder QLEnableTextSelection -bool true # echo "Display full POSIX path as Finder window title" # defaults write com.apple.finder _FXShowPosixPathInTitle -bool true # # echo "When performing a search, search the current folder by default" # defaults write com.apple.finder FXDefaultSearchScope -string "SCcf" # echo "Disable the warning when changing a file extension" # defaults write com.apple.finder FXEnableExtensionChangeWarning -bool false # echo "Enable spring loading for directories" # defaults write NSGlobalDomain com.apple.springing.enabled -bool true # # echo "Remove the spring loading delay for directories" # defaults write NSGlobalDomain com.apple.springing.delay -float 0 # echo "Avoid creating .DS_Store files on network volumes" # defaults write com.apple.desktopservices DSDontWriteNetworkStores -bool true # echo "Disable disk image verification" # defaults write com.apple.frameworks.diskimages skip-verify -bool true # defaults write com.apple.frameworks.diskimages skip-verify-locked -bool true # defaults write com.apple.frameworks.diskimages skip-verify-remote -bool true # # echo "Automatically open a new Finder window when a volume is mounted" # defaults write com.apple.frameworks.diskimages auto-open-ro-root -bool true # defaults write com.apple.frameworks.diskimages auto-open-rw-root -bool true # defaults write com.apple.finder OpenWindowForNewRemovableDisk -bool true # echo "Show item info near icons on the desktop and in other icon views" # /usr/libexec/PlistBuddy -c "Set :DesktopViewSettings:IconViewSettings:showItemInfo true" ~/Library/Preferences/com.apple.finder.plist # /usr/libexec/PlistBuddy -c "Set :FK_StandardViewSettings:IconViewSettings:showItemInfo true" ~/Library/Preferences/com.apple.finder.plist # /usr/libexec/PlistBuddy -c "Set :StandardViewSettings:IconViewSettings:showItemInfo true" ~/Library/Preferences/com.apple.finder.plist # # echo "Show item info to the right of the icons on the desktop" # /usr/libexec/PlistBuddy -c "Set DesktopViewSettings:IconViewSettings:labelOnBottom false" ~/Library/Preferences/com.apple.finder.plist # # echo "Enable snap-to-grid for icons on the desktop and in other icon views" # /usr/libexec/PlistBuddy -c "Set :DesktopViewSettings:IconViewSettings:arrangeBy grid" ~/Library/Preferences/com.apple.finder.plist # /usr/libexec/PlistBuddy -c "Set :FK_StandardViewSettings:IconViewSettings:arrangeBy grid" ~/Library/Preferences/com.apple.finder.plist # /usr/libexec/PlistBuddy -c "Set :StandardViewSettings:IconViewSettings:arrangeBy grid" ~/Library/Preferences/com.apple.finder.plist # # echo "Increase grid spacing for icons on the desktop and in other icon views" # /usr/libexec/PlistBuddy -c "Set :DesktopViewSettings:IconViewSettings:gridSpacing 100" ~/Library/Preferences/com.apple.finder.plist # /usr/libexec/PlistBuddy -c "Set :FK_StandardViewSettings:IconViewSettings:gridSpacing 100" ~/Library/Preferences/com.apple.finder.plist # /usr/libexec/PlistBuddy -c "Set :StandardViewSettings:IconViewSettings:gridSpacing 100" ~/Library/Preferences/com.apple.finder.plist # # echo "Increase the size of icons on the desktop and in other icon views" # /usr/libexec/PlistBuddy -c "Set :DesktopViewSettings:IconViewSettings:iconSize 80" ~/Library/Preferences/com.apple.finder.plist # /usr/libexec/PlistBuddy -c "Set :FK_StandardViewSettings:IconViewSettings:iconSize 80" ~/Library/Preferences/com.apple.finder.plist # /usr/libexec/PlistBuddy -c "Set :StandardViewSettings:IconViewSettings:iconSize 80" ~/Library/Preferences/com.apple.finder.plist # # echo "Use list view in all Finder windows by default" # # Four-letter codes for the other view modes: `icnv`, `clmv`, `Flwv` # defaults write com.apple.finder FXPreferredViewStyle -string "Nlsv" echo "Disable the warning before emptying the Trash" defaults write com.apple.finder WarnOnEmptyTrash -bool false # echo "Empty Trash securely by default" # defaults write com.apple.finder EmptyTrashSecurely -bool true # # echo "Enable AirDrop over Ethernet and on unsupported Macs running Lion" # defaults write com.apple.NetworkBrowser BrowseAllInterfaces -bool true # # echo "Enable the MacBook Air SuperDrive on any Mac" # sudo nvram boot-args="mbasd=1" # # echo "Show the ~/Library folder" # chflags nohidden ~/Library # echo "Remove Dropbox’s green checkmark icons in Finder" # file=/Applications/Dropbox.app/Contents/Resources/emblem-dropbox-uptodate.icns # [ -e "${file}" ] && mv -f "${file}" "${file}.bak" # echo "Expand the following File Info panes:" # echo "“General”, “Open with”, and “Sharing & Permissions”" # defaults write com.apple.finder FXInfoPanesExpanded -dict \ # General -bool true \ # OpenWith -bool true \ # Privileges -bool true <file_sep>/defaults/transmission.sh #! /bin/sh # ------------------------------------------------------------------------------ # Copyright (c) 2014 <NAME> # All rights reserved. # # 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 THE COPYRIGHT HOLDER OR CONTRIBUTORS 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. # ------------------------------------------------------------------------------ # NAME: transmission.sh # PURPOSE: Setup Transmission # VERSION: 1.0 Initial version # ------------------------------------------------------------------------------ # echo "Use `~/Downloads/Incomplete` to store incomplete downloads" # mkdir -p ~/Downloads/Incomplete # defaults write org.m0k.transmission UseIncompleteDownloadFolder -bool true # defaults write org.m0k.transmission IncompleteDownloadFolder -string "${HOME}/Downloads/Incomplete" # # echo "Don't prompt for confirmation before downloading" # defaults write org.m0k.transmission DownloadAsk -bool false # # echo "Trash original torrent files" # defaults write org.m0k.transmission DeleteOriginalTorrent -bool true # # echo "Hide the donate message" # defaults write org.m0k.transmission WarningDonate -bool false # # echo "Hide the legal disclaimer" # defaults write org.m0k.transmission WarningLegal -bool false <file_sep>/defaults/trackpad.sh #! /bin/sh # ------------------------------------------------------------------------------ # Copyright (c) 2014 <NAME> # All rights reserved. # # 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 THE COPYRIGHT HOLDER OR CONTRIBUTORS 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. # ------------------------------------------------------------------------------ # NAME: trackpad.sh # PURPOSE: Setup trackpad # VERSION: 1.0 Initial version # ------------------------------------------------------------------------------ echo "Trackpad: enable tap to click for this user and for the login screen" defaults write com.apple.driver.AppleBluetoothMultitouch.trackpad Clicking -bool true defaults -currentHost write NSGlobalDomain com.apple.mouse.tapBehavior -int 1 defaults write NSGlobalDomain com.apple.mouse.tapBehavior -int 1 # echo "Trackpad: map bottom right corner to right-click" # defaults write com.apple.driver.AppleBluetoothMultitouch.trackpad TrackpadCornerSecondaryClick -int 2 # defaults write com.apple.driver.AppleBluetoothMultitouch.trackpad TrackpadRightClick -bool true # defaults -currentHost write NSGlobalDomain com.apple.trackpad.trackpadCornerClickBehavior -int 1 # defaults -currentHost write NSGlobalDomain com.apple.trackpad.enableSecondaryClick -bool true # echo "Trackpad: swipe between pages with three fingers" # defaults write NSGlobalDomain AppleEnableSwipeNavigateWithScrolls -bool true # defaults -currentHost write NSGlobalDomain com.apple.trackpad.threeFingerHorizSwipeGesture -int 1 # defaults write com.apple.driver.AppleBluetoothMultitouch.trackpad TrackpadThreeFingerHorizSwipeGesture -int 1 echo "Disable “natural” (Lion-style) scrolling" defaults write NSGlobalDomain com.apple.swipescrolldirection -bool false # echo "Increase sound quality for Bluetooth headphones/headsets" # defaults write com.apple.BluetoothAudioAgent "Apple Bitpool Min (editable)" -int 40 # # echo "Enable full keyboard access for all controls" # echo "(e.g. enable Tab in modal dialogs)" # defaults write NSGlobalDomain AppleKeyboardUIMode -int 3 # echo "Use scroll gesture with the Ctrl (^) modifier key to zoom" # defaults write com.apple.universalaccess closeViewScrollWheelToggle -bool true # defaults write com.apple.universalaccess HIDScrollZoomModifierMask -int 262144 # echo "Follow the keyboard focus while zoomed in" # defaults write com.apple.universalaccess closeViewZoomFollowsFocus -bool true echo "Disable press-and-hold for keys in favor of key repeat" defaults write NSGlobalDomain ApplePressAndHoldEnabled -bool false echo "Set a blazingly fast keyboard repeat rate" defaults write NSGlobalDomain KeyRepeat -int 0 # echo "Set language and text formats" # defaults write NSGlobalDomain AppleLanguages -array "en" # defaults write NSGlobalDomain AppleLocale -string "en_US@currency=USD" # defaults write NSGlobalDomain AppleMeasurementUnits -string "Inches" # defaults write NSGlobalDomain AppleMetricUnits -bool false # # echo "Set the timezone; see `sudo systemsetup -listtimezones` for other values" # systemsetup -settimezone "America/Los_Angeles" > /dev/null
62e1f7c67d072d0a8ad62850ed341376422d5f89
[ "Shell" ]
6
Shell
dstroot/.osx-defaults
6d73423d1edca62ef94bb1549077c7a8a20bf0f7
bf025de55a85778f91037205fdb154dff7301b9c
refs/heads/main
<file_sep>import React from "react"; import chroma from "chroma-js"; class Calculator extends React.Component { constructor(props) { super(props); this.state = { hex1: "First HEX", hex2: "Second HEX", result: "?", }; this.handleChange = this.handleChange.bind(this); this.handleSubmit = this.handleSubmit.bind(this); } handleChange(event) { const target = event.target; const value = target.value; const name = target.name; this.setState({ [name]: value, }); } handleSubmit(event) { // transform hex's to lch's let lch1 = chroma(this.state.hex1).lch(); let lch2 = chroma(this.state.hex2).lch(); // get differences let result = lch1.map(function (num, i) { return num - lch2[i]; }); console.log(result); // lch(from hex1 -20.095281554789977, -72.33231061331429, 0.19841406746820667) this.setState({ result: result, }); event.preventDefault(); } render() { return ( <div> <form onSubmit={this.handleSubmit}> <label> Primary HEX: <input type="text" name="hex1" value={this.state.hex1} onChange={this.handleChange} /> </label> <label> Secondary HEX: <input type="text" name="hex2" value={this.state.hex2} onChange={this.handleChange} /> </label> <input className="Button" type="submit" value="Submit" /> </form> <p classname="Result">{this.state.result}</p> </div> ); } } export default Calculator; <file_sep>## color-mix I made myself a tool to get the lch difference between 2 hex colors. Because color is hard. `yarn start`
e477cedea5c8843bf25c71e07b264a8d45511221
[ "JavaScript", "Markdown" ]
2
JavaScript
amychurchwell/color-mix
5dceb7d6c7899c2ed4876e8bd6a7c45ae7c9b050
10a5c670ca7b3e26fd03bc56561f3aba17d3c9b4
refs/heads/master
<file_sep>import Vue from 'vue' import VueRouter from 'vue-router' import Home from '../views/Home.vue' Vue.use(VueRouter) const routes = [ { path: '/home', name: 'home', component: Home }, { path: '/about', name: 'about', // route level code-splitting // this generates a separate chunk (about.[hash].js) for this route // which is lazy-loaded when the route is visited. component: () => import(/* webpackChunkName: "about" */ '../views/About.vue') }, { path: '/inicio', name: 'inicio', // route level code-splitting // this generates a separate chunk (about.[hash].js) for this route // which is lazy-loaded when the route is visited. component: () => import(/* webpackChunkName: "about" */ '../views/Inicio.vue') }, { path: '/principal/:id', name: 'principal', // route level code-splitting // this generates a separate chunk (about.[hash].js) for this route // which is lazy-loaded when the route is visited. component: () => import(/* webpackChunkName: "about" */ '../views/Principal.vue') }, { path: '/listarServicios/:id', name: 'listarServicios', // route level code-splitting // this generates a separate chunk (about.[hash].js) for this route // which is lazy-loaded when the route is visited. component: () => import(/* webpackChunkName: "about" */ '../views/ListarServicios.vue') }, { path: '/agregarUsuario', name: 'agregarUsuario', // route level code-splitting // this generates a separate chunk (about.[hash].js) for this route // which is lazy-loaded when the route is visited. component: () => import(/* webpackChunkName: "about" */ '../views/AgregarUsuario.vue') }, { path: '/', name: 'index', // route level code-splitting // this generates a separate chunk (about.[hash].js) for this route // which is lazy-loaded when the route is visited. component: () => import(/* webpackChunkName: "about" */ '../views/Index.vue') }, { path: '/detalle/:id/:id2', name: 'detalle', // route level code-splitting // this generates a separate chunk (about.[hash].js) for this route // which is lazy-loaded when the route is visited. component: () => import(/* webpackChunkName: "about" */ '../views/Detalle.vue') }, { path: '/agregarServicio/:id', name: 'agregarServicio', // route level code-splitting // this generates a separate chunk (about.[hash].js) for this route // which is lazy-loaded when the route is visited. component: () => import(/* webpackChunkName: "about" */ '../views/AgregarServicio.vue') }, { path: '/perfil/:id/:id2', name: 'perfil', // route level code-splitting // this generates a separate chunk (about.[hash].js) for this route // which is lazy-loaded when the route is visited. component: () => import(/* webpackChunkName: "about" */ '../views/Perfil.vue') }, { path: '/buscarPersonas/:id', name: 'buscarPersonas', // route level code-splitting // this generates a separate chunk (about.[hash].js) for this route // which is lazy-loaded when the route is visited. component: () => import(/* webpackChunkName: "about" */ '../views/BuscarPersonas.vue') }, { path: '/miPerfil/:id', name: 'miPerfil', // route level code-splitting // this generates a separate chunk (about.[hash].js) for this route // which is lazy-loaded when the route is visited. component: () => import(/* webpackChunkName: "about" */ '../views/MiPerfil.vue') }, { path: '/subscripcion/:id', name: 'subscripcion', // route level code-splitting // this generates a separate chunk (about.[hash].js) for this route // which is lazy-loaded when the route is visited. component: () => import(/* webpackChunkName: "about" */ '../views/Subscripcion.vue') }, { path: '/agregarReserva/:id/:id2', name: 'agregarReserva', // route level code-splitting // this generates a separate chunk (about.[hash].js) for this route // which is lazy-loaded when the route is visited. component: () => import(/* webpackChunkName: "about" */ '../views/AgregarReserva.vue') }, { path: '/modificarServicio/:id/:id2', name: 'modificarServicio', // route level code-splitting // this generates a separate chunk (about.[hash].js) for this route // which is lazy-loaded when the route is visited. component: () => import(/* webpackChunkName: "about" */ '../views/ModificarServicio.vue') }, { path: '/editarPerfil/:id', name: 'editarPerfil', // route level code-splitting // this generates a separate chunk (about.[hash].js) for this route // which is lazy-loaded when the route is visited. component: () => import(/* webpackChunkName: "about" */ '../views/EditarPerfil.vue') }, { path: '/modificarReserva/:id/:id2', name: 'modificarReserva', // route level code-splitting // this generates a separate chunk (about.[hash].js) for this route // which is lazy-loaded when the route is visited. component: () => import(/* webpackChunkName: "about" */ '../views/ModificarReserva.vue') } ] const router = new VueRouter({ mode: 'history', base: process.env.BASE_URL, routes }) export default router
8f9049bb30d7100fdd4a88e121404bdf4b39daa9
[ "JavaScript" ]
1
JavaScript
Galatenea98/Frontend
1b2590b095d616b359262b33f426c950aa53b806
8b7e84701682bad84b30563366a90153205e451b
refs/heads/master
<repo_name>CitlalliDMG/cdmx-social-network-frameworks<file_sep>/src/firebase/firebase.js // Firebase configuration and initialize file import firebase from 'firebase/app'; // Initialize the auth object import 'firebase/auth'; import 'firebase/database'; const config = { apiKey: "<KEY>", authDomain: "pseudogram-f3149.firebaseapp.com", databaseURL: "https://pseudogram-f3149.firebaseio.com", projectId: "pseudogram-f3149", storageBucket: "pseudogram-f3149.appspot.com", messagingSenderId: "566775694569" }; if (!firebase.apps.length) { firebase.initializeApp(config); } const db = firebase.database(); const auth = firebase.auth(); export { db, auth, firebase, };<file_sep>/src/firebase/auth.js // File to authentication services from Firebae // Interface between Firebase API and the app import { auth, firebase, db } from './firebase'; import * as routes from '../constants/routes'; // Sign Up function export const doCreateUserWithEmailAndPassword = (email, password) => auth.createUserWithEmailAndPassword(email, password); // Sign In function export const doSignInWithEmailAndPassword = (email, password) => auth.signInWithEmailAndPassword(email, password); // Sign Out function export const doSignOut = () => auth.signOut(); // Password Reset export const doPasswordReset = (email) => auth.sendPasswordResetEmail(email); // Password Change export const doPasswordUpdate = (password) => auth.currentUser.updatePassword(password); // Sign in Google export const doSignInWithGoogle = async (history) => { const provider = new firebase.auth.GoogleAuthProvider(); await auth.signInWithPopup(provider); history.push(routes.HOME); }; // State listener export const authStateChangeListener = auth.onAuthStateChanged((user) => { console.log(user); console.log(db); db.ref(`users/${user.uid}`).set({ username: user.displayName, email: user.email, }); // return user; }); <file_sep>/src/firebase/index.js // Entry poin file to the Firebase module // Group and sample the module functionalities // Avoid to react components to access to the configuration and auth files directly import * as auth from './auth'; import * as db from './db'; import * as firebase from './firebase'; export { auth, db, firebase, }
d034d9c31b18e1b32f0741ca5cfa69a813fcde43
[ "JavaScript" ]
3
JavaScript
CitlalliDMG/cdmx-social-network-frameworks
2df3725de8b378a69fd95a56968f19d80ad570eb
62b898e57eb9a4d67b419ea6218200b168a16b1f
refs/heads/main
<file_sep>library(readr) library(ggplot2) setwd("/Users/jackhostetler/Desktop") data <- read_csv('AugmentationData.csv') print(data) plot(data$C, data$`C*`, xlab = "x-axis", ylab = "y-axis", main = "Plot" ) ggplot(data, aes(x=C, y=`C*`)) + geom_point(aes(color=Augmentation)) + labs(title="",x="C (mg/l)", y="C* (mg/g)") + scale_color_manual(values=c('#041e42', '#ba0c2f', '#edae49', '#66a182')) + theme_classic() <file_sep>library(readr) x <- read_csv("FeSO4-iso.csv") for (i in 1:nrow(x)) { x$C[i] <- (x$`C 1`[i] + x$`C 2`[i] + x$`C 3`[i])/3 # averages the three measurements of each trial; assumes mg/l } vol <- 0.05 # l, volume of reactor, 50 ml. m <- vol * x$C # mg, calculates the mass remaining in solution in each reactor control.mass <- m[1] # assumes that the first line is the control sorbed.mass <- array(0, dim = (nrow(x))) for (i in 2:nrow(x)) { sorbed.mass[i] <- control.mass - m[i] } Cstar <- sorbed.mass/x$`FeSO4 (g)` plot(x$C, Cstar, xlab = "C (mg/l)", ylab = "C* (mg/g)")
27aee48712804af2c662cb948516c881c3fdbc1d
[ "R" ]
2
R
hydro-lab/fluoride
36c174876e3e59b17e1d03928e0f6868ac64741a
6ebe2c7c32f5e2a0481e35eb3cb1caab485adbd9
refs/heads/main
<file_sep>const express = require("express"); const router = express.Router(); const feedsController = require("../controllers/feeds"); router.get("/posts", feedsController.getPosts); router.post("/posts", feedsController.createPost); module.exports = router;
ba9aac31ad9f8be5e164258b55a95cc3a96ad8a2
[ "JavaScript" ]
1
JavaScript
ahmedfouad01099/simple-api
323e82890a9b2af0a05df852344905e7686c69ee
91b2e30f05390588d6ae055dabc484512493e347
refs/heads/master
<file_sep>var app = require('http').createServer(handler) , io = require('socket.io').listen(app) , fs = require('fs') var MAX_COLOR_CODE = 9; app.listen(8888); function handler (req, res) { fs.readFile(__dirname + '/index.html', function (err, data) { if (err) { res.writeHead(500); return res.end('Error loading index.html'); } res.writeHead(200); res.end(data); }); } var users = {}; var guestId = 0; var sanitizeRegEx = /\074|\076/g; var messageTypes = { displayMessage: 'displayMsg', refreshUsers: 'refreshusers', userlist: 'userlist' }; io.sockets.on('connection', function (socket) { socket.on('adduser', function (username) { if(username==null) { username='guest'; } // remove special chars username = username.replace(/\074|\076|\s/g, ''); // prevent null users if(username==='') { username = 'guest' + guestId++; } // no dupilcate names for(var usr in users) { if(usr === username) { username = username + guestId++; } } console.log('added user: ' + username); socket.username = username; users[username] = {name: username, color: getColorForName(username), socket: socket}; io.sockets.emit(messageTypes.refreshUsers); }); socket.on('getuserlist', function() { var userlist = []; for(var userName in users) { var user = users[userName]; console.log("foo" + user); userlist.push({ name: user.name, color: user.color }); }; socket.emit(messageTypes.userlist, userlist); }); socket.on('chatmsg', function (data) { console.log("chatmsg - data: data"); var command = parseCommand(data.text); if(command != null && isValidCommand(command)) { doCommand(socket.username, command); } else { var user = users[socket.username]; if (user == null) { user = {name : '-----', color: '#000000'}; } data.text = sanitizeText(data.text); var msg = { text: data.text, user: user.name, color: user.color } io.sockets.emit(messageTypes.displayMessage, msg); } }); socket.on('disconnect', function() { delete users[socket.username]; io.sockets.emit(messageTypes.refreshUsers); }); }); /** * Gets the string hex value for a user's name. This is based on the first three characters * of the name (which are used for the R G and B parts of the returned color code. No * value greater than MAX_COLOR_CODE so the color isn't too tough to read on the background * * @param {string} name The user's name */ function getColorForName(name) { var R = name[0] ? name.charCodeAt(0) % MAX_COLOR_CODE : 0; var G = name[1] ? name.charCodeAt(1) % MAX_COLOR_CODE : 0; var B = name[2] ? name.charCodeAt(2) % MAX_COLOR_CODE : 0; return "#" + R + R + G + G + B + B; } function sanitizeText(text) { return text.replace(sanitizeRegEx, ''); } var commandHandlers = []; // handlers should follow this prototype: // function handler(username, cmdargs){} function registerCommand(cmdName, handler) { console.log('registering command: [' + cmdName + ']'); commandHandlers[cmdName] = handler; } function parseCommand(chatString) { var index = chatString.indexOf('/'); if (index > -1) { return chatString.slice(index+1); } return null; } function isValidCommand(cmdAndArgs) { var command = cmdAndArgs.split(' ',1); for( var cmd in commandHandlers) { if(cmd == command) { return true; } } return false; } function doCommand(username, cmdAndArgs) { var cmd = cmdAndArgs.split(' ',1); var args = ''; console.log('doing command: [' + cmd + ']'); if( cmdAndArgs.indexOf(' ') > -1) { args = cmdAndArgs.slice(cmdAndArgs.indexOf(' ') + 1); } console.log('with args: [' + args + ']'); console.log('with function: ' + commandHandlers[cmd]); if(commandHandlers[cmd] != null) { console.log('found command!'); commandHandlers[cmd](username, args); } } function whisper(username, args) { var index = args.indexOf(' ', 1); // make sure to ignore leading space if there var toUser = args.slice(0,index); var msgText = args.slice(index+1); if(users[toUser] != null) { var msg = { text: sanitizeText(msgText), user: '[' + username + ' -> ' + toUser + ']', color: '#000099' } users[toUser]['socket'].emit(messageTypes.displayMessage, msg); users[username]['socket'].emit(messageTypes.displayMessage, msg); } } function shout(username, args) { if(users[username] != null) { var msg = { text: sanitizeText(args), user: users[username].name, color: users[username].color, style: 'shout' } console.log('shout - ' + msg); io.sockets.emit(messageTypes.displayMessage, msg); } } function displayCommands(username, args) { var helpText = 'These are the available commands:\n'; for( var cmd in commandHandlers ) { helpText += ' /' + cmd + '\n'; } var msg = { text: helpText, user: 'help', color: '#880000' } if(users[username] != null) { users[username]['socket'].emit(messageTypes.displayMessage, msg); } } function renameUser(username, args) { var cleanNewName = sanitizeText(args); var oldUserExists = false; var newNameExists = false; for(var usernamekey in users) { console.log('username: ' + username + '\ncleanNewName: ' + cleanNewName + '\nkey: ' + usernamekey); oldUserExists = oldUserExists || (usernamekey === username); newNameExists = newNameExists || (usernamekey === cleanNewName); } // ignore requests from users that don't exist if(!oldUserExists) { return; } var msg = { text: '', user: 'rename', color: '#008800' } // notify of name taken if(newNameExists) { msg.text = 'a user with the name "' + cleanNewName + '" already exists, please choose a different name.'; users[username]['socket'].emit(messageTypes.displayMessage, msg); return; } // process name change var socket = users[username]['socket']; socket.username = cleanNewName; delete users[username]; users[cleanNewName] = {name: cleanNewName, color: getColorForName(cleanNewName), socket: socket}; msg.text = 'user "' + username + '" has been renamed to "' + cleanNewName + '"'; io.sockets.emit(messageTypes.displayMessage, msg); io.sockets.emit(messageTypes.refreshUsers); } registerCommand('?', displayCommands); registerCommand('help', displayCommands); registerCommand('w', whisper); registerCommand('whisper', whisper); registerCommand('s', shout); registerCommand('shout', shout); registerCommand('rename', renameUser);
46c15d53f10550c3903573d656587ffe78ccbe9a
[ "JavaScript" ]
1
JavaScript
brian-d/NodeChat
7f4acd57e89238d2ca9c571b0e3f82657bdd3ed8
01b84663a0f7cd865aa65d6f1d80378c2eeb0c58
refs/heads/master
<repo_name>dmcwhorter/osf.io<file_sep>/website/static/js/projectSettings.js (function () { window.ProjectSettings = {}; /** * returns a random name from this list to use as a confirmation string */ function randomScientist() { var scientists = [ 'Anning', 'Banneker', 'Cannon', 'Carver', 'Chappelle', 'Curie', 'Divine', 'Emeagwali', 'Fahlberg', 'Forssmann', 'Franklin', 'Herschel', 'Hodgkin', 'Hopper', 'Horowitz', 'Jemison', 'Julian', 'Kovalevsky', 'Lamarr', 'Lavoisier', 'Lovelace', 'Massie', 'McClintock', 'Meitner', 'Mitchell', 'Morgan', 'Nosek', 'Odum', 'Pasteur', 'Pauling', 'Payne', 'Pearce', 'Pollack', 'Rillieux', 'Sanger', 'Somerville', 'Tesla', 'Tyson', 'Turing' ]; return scientists[Math.floor(Math.random() * scientists.length)]; } // Request the first 5 contributors, for display in the deletion modal var contribs = []; var moreContribs = 0; var contribURL = nodeApiUrl + 'get_contributors/?limit=5'; var request = $.ajax({ url: contribURL, type: 'get', dataType: 'json' }); request.done(function(response) { var currentUserName = window.contextVars.currentUser.fullname; contribs = response.contributors.filter(function(contrib) { return contrib.shortname !== currentUserName; }); moreContribs = response.more; }); request.fail(function(xhr, textStatus, err) { Raven.captureMessage('Error requesting contributors', { url: contribURL, textStatus: textStatus, err: err, }); }); /** * Pulls a random name from the scientist list to use as confirmation string * Ignores case and whitespace */ ProjectSettings.getConfirmationCode = function(nodeType) { var key = randomScientist(); function successHandler(response) { // Redirect to either the parent project or the dashboard window.location.href = response.url; } var promptMsg = 'Are you sure you want to delete this ' + nodeType + '?' + '<div class="bootbox-node-deletion-modal"><p>It will no longer be available to other contributors on the project.'; // It's possible that the XHR request for contributors has not finished before getting to this // point; only construct the HTML for the list of contributors if the contribs list is populated var contribsMsg = ''; if (contribs.length) { // Build contributor unordered list var contriblist = ''; $.each(contribs, function(i, b){ contriblist += '<li>' + b.fullname + '</li>'; }); contribsMsg = ' Contributors include:</p>' + '<ol>' + contriblist +'</ol>' + '<p style="font-weight: normal; font-size: medium; line-height: normal;">' + ((moreContribs > 0) ? 'and <strong>' + moreContribs + '</strong> others.</p>' : ''); } var promptMsgEnd = '<p style="font-weight: normal; font-size: medium; line-height: normal;">' + 'If you want to continue, type <strong>' + key + '</strong> and click OK.</p></div>'; var fullMsg = [promptMsg, contribsMsg, promptMsgEnd].join(''); bootbox.prompt( fullMsg, function(result) { if (result != null) { result = result.toLowerCase(); } if ($.trim(result) === key.toLowerCase()) { var request = $.ajax({ type: 'DELETE', dataType: 'json', url: nodeApiUrl }); request.done(successHandler); request.fail($.osf.handleJSONError); } else if (result != null) { $.osf.growl('Incorrect confirmation', 'The confirmation string you provided was incorrect. Please try again.'); } } ); }; $(document).ready(function() { // TODO: Knockout-ify me $('#commentSettings').on('submit', function() { var $commentMsg = $('#configureCommentingMessage'); var $this = $(this); var commentLevel = $this.find('input[name="commentLevel"]:checked').val(); $.osf.postJSON( nodeApiUrl + 'settings/comments/', {commentLevel: commentLevel} ).done(function() { $commentMsg.addClass('text-success'); $commentMsg.text('Successfully updated settings.'); window.location.reload(); }).fail(function() { $.osf.growl('Could not set commenting configuration.', 'Please try again.'); }); return false; }); // Set up submission for addon selection form $('#selectAddonsForm').on('submit', function() { var formData = {}; $('#selectAddonsForm').find('input').each(function(idx, elm) { var $elm = $(elm); formData[$elm.attr('name')] = $elm.is(':checked'); }); var msgElm = $(this).find('.addon-settings-message'); $.ajax({ url: nodeApiUrl + 'settings/addons/', data: JSON.stringify(formData), type: 'POST', contentType: 'application/json', dataType: 'json', success: function() { msgElm.text('Settings updated').fadeIn(); window.location.reload(); } }); return false; }); // Show capabilities modal on selecting an addon; unselect if user // rejects terms $('.addon-select').on('change', function() { var that = this, $that = $(that); if ($that.is(':checked')) { var name = $that.attr('name'); var capabilities = $('#capabilities-' + name).html(); if (capabilities) { bootbox.confirm( capabilities, function(result) { if (!result) { $(that).attr('checked', false); } } ); } } }); }); }()); <file_sep>/website/addons/s3/api.py import os from dateutil.parser import parse from boto.s3.connection import S3Connection, Key from boto.s3.connection import OrdinaryCallingFormat from boto.s3.cors import CORSConfiguration from boto.exception import S3ResponseError from hurry.filesize import size, alternative #Note: (from boto docs) this function is in beta def enable_versioning(user_settings): wrapper = S3Wrapper.from_addon(user_settings) wrapper.bucket.configure_versioning(True) def has_access(access_key, secret_key): try: c = S3Connection(access_key, secret_key) c.get_all_buckets() return True except Exception: return False def get_bucket_list(user_settings): return S3Connection(user_settings.access_key, user_settings.secret_key).get_all_buckets() def create_bucket(user_settings, bucket_name): connect = S3Connection( user_settings.access_key, user_settings.secret_key) return connect.create_bucket(bucket_name) def does_bucket_exist(accessKey, secretKey, bucketName): try: c = S3Connection(accessKey, secretKey) c.get_bucket(bucketName, validate=False) return True except Exception: return False class S3Wrapper(object): @classmethod def from_addon(cls, s3): if s3 is None or s3.user_settings is None: return None if not s3.is_registration: return cls(S3Connection(s3.user_settings.access_key, s3.user_settings.secret_key), s3.bucket) else: return RegistrationWrapper(s3) @classmethod def bucket_exist(cls, s3, bucketName): m = cls.fromAddon(s3) return not m.connection.lookup(bucketName.lower(), validate=False) "S3 Bucket management" def __init__(self, connection, bucket_name): self.connection = connection if bucket_name != bucket_name.lower(): self.connection.calling_format = OrdinaryCallingFormat() self.bucket = self.connection.get_bucket(bucket_name, validate=False) def create_key(self, key): self.bucket.new_key(key) def get_file_list(self, prefix=None): if not prefix: return self.bucket.list() else: return self.bucket.list(prefix=prefix) def create_folder(self, name, pathToFolder=""): if not name.endswith('/'): name.append("/") k = self.bucket.new_key(pathToFolder + name) return k.set_contents_from_string("") def delete_file(self, keyName): return self.bucket.delete_key(keyName) def download_file_URL(self, keyName, vid=None): headers = {'response-content-disposition': 'attachment'} return self.bucket.get_key(keyName, version_id=vid).generate_url(5, response_headers=headers) def get_wrapped_keys(self, prefix=None): return [S3Key(x) for x in self.get_file_list()] def get_wrapped_key(self, key_name, vid=None): """Get S3 key. :param str key_name: Name of S3 key :param str version_id: Optional file version :return: Wrapped S3 key if found, else None """ try: key = self.bucket.get_key(key_name, version_id=vid) if key is not None: return S3Key(key) return None except S3ResponseError: return None def get_wrapped_keys_in_dir(self, directory=None): return [S3Key(x) for x in self.bucket.list(delimiter='/', prefix=directory) if isinstance(x, Key) and x.key != directory] def get_wrapped_directories_in_dir(self, directory=None): return [S3Key(x) for x in self.bucket.list(prefix=directory) if isinstance(x, Key) and x.key.endswith('/') and x.key != directory] @property def bucket_name(self): return self.bucket.name def get_version_data(self): versions = {} versions_list = self.bucket.list_versions() for p in versions_list: if isinstance(p, Key) and str(p.version_id) != 'null' and str(p.key) not in versions: versions[str(p.key)] = [str(k.version_id) for k in versions_list if p.key == k.key] return versions # TODO update this to cache results later def get_file_versions(self, file_name): return [x for x in self.bucket.list_versions(prefix=file_name) if isinstance(x, Key)] def get_cors_rules(self): try: return self.bucket.get_cors() except: return CORSConfiguration() def set_cors_rules(self, rules): return self.bucket.set_cors(rules) def does_key_exist(self, key_name): return self.bucket.get_key(key_name) is not None # TODO Add null checks etc class RegistrationWrapper(S3Wrapper): def __init__(self, node_settings): if node_settings.user_settings: connection = S3Connection( node_settings.user_settings.access_key, node_settings.user_settings.secret_key, ) else: connection = S3Connection() super(RegistrationWrapper, self).__init__(connection, node_settings.bucket) self.registration_data = node_settings.registration_data def get_wrapped_keys_in_dir(self, directory=None): return [ S3Key(x) for x in self.bucket.list_versions(delimiter='/', prefix=directory) if isinstance(x, Key) and x.key != directory and self.is_right_version(x) ] def get_wrapped_directories_in_dir(self, directory=None): return [S3Key(x) for x in self.bucket.list_versions(prefix=directory) if self._directory_check(x, directory)] def _directory_check(self, to_check, against): return isinstance(to_check, Key) and to_check.key.endswith('/') and to_check.key != against and self.is_right_version(to_check) def is_right_version(self, key): return [x for x in self.registration_data['keys'] if x['version_id'] == key.version_id and x['path'] == key.key] def get_file_versions(self, key_name): to_cut = [x for x in self.bucket.list_versions( prefix=key_name) if isinstance(x, Key)] return to_cut[self._get_index_of(self._get_proper_version(key_name), to_cut):] def _get_proper_version(self, key_name): vid = [x['version_id'] for x in self.registration_data['keys'] if x['path'] == key_name][0] return self.bucket.get_key(key_name, version_id=vid) def _get_index_of(self, version, to_cut): return to_cut.index([x for x in to_cut if x.version_id == version.version_id][0]) # TODO Extend me and you bucket.setkeyclass class S3Key(object): def __init__(self, key): self.s3Key = key if self.type == 'file': self.versions = ['current'] else: self.versions = None @property def name(self): d = self.s3Key.key.split('/') if len(d) > 1 and self.type == 'file': return d[-1] elif self.type == 'folder': return d[-2] else: return d[0] @property def type(self): if not self.s3Key.key.endswith('/'): return 'file' else: return 'folder' @property def parentFolder(self): d = self.s3Key.key.split('/') if len(d) > 1 and self.type == 'file': return d[len(d) - 2] elif len(d) > 2 and self.type == 'folder': return d[len(d) - 3] else: return None @property def pathTo(self): return self.s3Key.key[:self.s3Key.key.rfind('/')] + '/' @property def size(self): if self.type == 'folder': return None else: return size(float(self.s3Key.size), system=alternative) @property def lastMod(self): if self.type == 'folder': return None else: return parse(self.s3Key.last_modified) @property def version(self): return self.versions @property def extension(self): if self.type != 'folder': if os.path.splitext(self.s3Key.key)[1] is None: return None else: return os.path.splitext(self.s3Key.key)[1][1:] else: return None @property def md5(self): return self.s3Key.md5 @property def version_id(self): return self.s3Key.version_id if self.s3Key.version_id != 'null' else 'Pre-versioning' def updateVersions(self, manager): if self.type != 'folder': self.versions.extend(manager.get_file_versions(self.s3Key.key)) @property def etag(self): return self.s3Key.etag.replace('"', '') <file_sep>/website/addons/forward/static/forwardWidget.js ;(function (global, factory) { if (typeof define === 'function' && define.amd) { define(['knockout', 'jquery', 'knockoutpunches'], factory); } else if (typeof $script === 'function') { global.ForwardWidget = factory(ko, jQuery, window); $script.done('forwardWidget'); } else { global.ForwardWidget = factory(ko, jQuery, window); } }(this, function(ko, $, window) { 'use strict'; ko.punches.enableAll(); /** * Knockout view model for the Forward node settings widget. */ var ViewModel = function(url) { var self = this; self.url = ko.observable(); self.label = ko.observable(); self.linkDisplay = ko.computed(function() { if (self.label()) { return self.label(); } else { return self.url(); } }); self.redirectBool = ko.observable(); self.redirectSecs = ko.observable(); self.interval = null; self.redirecting = ko.observable(); self.timeLeft = ko.observable(); self.doRedirect = function() { window.location.href = self.url(); }; self.tryRedirect = function() { if (self.timeLeft() > 0) { self.timeLeft(self.timeLeft() - 1); } else { self.doRedirect(); } }; self.queueRedirect = function() { self.redirecting(true); $.blockUI({message: $('#forwardModal')}); self.timeLeft(self.redirectSecs()); self.interval = setInterval( self.tryRedirect, 1000 ); }; self.cancelRedirect = function() { self.redirecting(false); $.unblockUI(); clearInterval(self.interval); }; self.execute = function() { if (self.redirectBool()) { self.queueRedirect(); } }; self.init = function() { $.ajax({ type: 'GET', url: url, dataType: 'json', success: function(response) { self.url(response.url); self.label(response.label); self.redirectBool(response.redirectBool); self.redirectSecs(response.redirectSecs); self.execute(); } }); }; }; // Public API function ForwardWidget(selector, url) { var self = this; self.viewModel = new ViewModel(url); $.osf.applyBindings(self.viewModel, selector); self.viewModel.init(); } return ForwardWidget; })); <file_sep>/website/conferences/views.py # -*- coding: utf-8 -*- import os import re import hmac import json import uuid import hashlib import logging import urlparse import httplib as http import requests from flask import request from nameparser import HumanName from modularodm import Q from modularodm.exceptions import ModularOdmException from framework.forms.utils import sanitize from framework.exceptions import HTTPError from framework.auth import Auth from website import settings, security from website.util import web_url_for from website.models import User, Node, MailRecord from website.project import new_node from website.project.views.file import prepare_file from website.util.sanitize import escape_html from website.mails import send_mail, CONFERENCE_SUBMITTED, CONFERENCE_FAILED from website.conferences.model import Conference logger = logging.getLogger(__name__) def request_to_data(): return { 'headers': dict(request.headers), 'form': request.form.to_dict(), 'args': request.args.to_dict(), } def get_or_create_user(fullname, address, is_spam): """Get or create user by email address. """ user = User.find(Q('username', 'iexact', address)) user = user[0] if user.count() else None user_created = False if user is None: password = str(uuid.uuid4()) user = User.create_confirmed(address, password, fullname) user.verification_key = security.random_string(20) # Flag as potential spam account if Mailgun detected spam if is_spam: user.system_tags.append('is_spam') user.save() user_created = True return user, user_created def add_poster_by_email(conf, recipient, address, fullname, subject, message, attachments, tags=None, system_tags=None, is_spam=False): # Fail if no attachments if not attachments: send_mail( address, CONFERENCE_FAILED, fullname=fullname, ) return # Use address as name if name missing fullname = fullname or address.split('@')[0] created = [] user, user_created = get_or_create_user(fullname, address, is_spam) if user_created: created.append(user) set_password_url = web_url_for( 'reset_password', verification_key=user.verification_key, ) else: set_password_url = None auth = Auth(user=user) # Find or create node node = Node.find(Q('title', 'iexact', subject)) node = node[0] if node.count() else None if node is None or not node.is_contributor(user): node = new_node('project', subject, user) created.append(node) # Add admin to project if conf.admins: for admin in conf.admins: node.add_contributor( contributor=admin, visible=False, log=False, save=True ) # Make public if confident that this is not spam and projects made public if is_spam: logger.warn( 'Possible spam detected in email modification of ' 'user {0} / node {1}'.format( user._id, node._id, ) ) elif conf.public_projects: node.set_privacy('public', auth=auth) # Add body node.update_node_wiki('home', sanitize(message), auth) # Add tags presentation_type = 'talk' if 'talk' in recipient else 'poster' tags = tags or [] tags.append(presentation_type) for tag in tags: node.add_tag(tag, auth=auth) # Add system tags system_tags = system_tags or [] system_tags.append(presentation_type) system_tags.append('emailed') if is_spam: system_tags.append('spam') for tag in system_tags: if tag not in node.system_tags: node.system_tags.append(tag) # Save changes node.save() from website.addons.osfstorage import utils as storage_utils # Add files for attachment in attachments: name, content, content_type, size = prepare_file(attachment) upload_url = storage_utils.get_upload_url(node, user, size, content_type, name) requests.put( upload_url, data=content, headers={'Content-Type': content_type}, ) download_url = node.web_url_for( 'osf_storage_view_file', path=attachments[0].filename, action='download', ) # Add mail record mail_record = MailRecord( data=request_to_data(), records=created, ) mail_record.save() # Send confirmation email send_mail( address, CONFERENCE_SUBMITTED, conf_full_name=conf.name, conf_view_url=urlparse.urljoin( settings.DOMAIN, os.path.join('view', conf.endpoint) ), fullname=fullname, user_created=user_created, set_password_url=set_password_url, profile_url=user.absolute_url, node_url=urlparse.urljoin(settings.DOMAIN, node.url), file_url=urlparse.urljoin(settings.DOMAIN, download_url), presentation_type=presentation_type, is_spam=is_spam, ) def get_mailgun_subject(form): subject = form['subject'] subject = re.sub(r'^re:', '', subject, flags=re.I) subject = re.sub(r'^fwd:', '', subject, flags=re.I) subject = subject.strip() return subject def _parse_email_name(name): name = re.sub(r'<.*?>', '', name).strip() name = name.replace('"', '') name = unicode(HumanName(name)) return name def get_mailgun_from(): """Get name and email address of sender. Note: this uses the `from` field instead of the `sender` field, meaning that envelope headers are ignored. """ name = _parse_email_name(request.form['from']) match = re.search(r'<(.*?)>', request.form['from']) address = match.groups()[0] if match else '' return name, address def get_mailgun_attachments(): attachment_count = request.form.get('attachment-count', 0) attachment_count = int(attachment_count) return [ request.files['attachment-{0}'.format(idx + 1)] for idx in range(attachment_count) ] def check_mailgun_headers(): """Verify that request comes from Mailgun. Based on sample code from http://documentation.mailgun.com/user_manual.html#webhooks """ # TODO: Cap request payload at 25MB signature = hmac.new( key=settings.MAILGUN_API_KEY, msg='{}{}'.format( request.form['timestamp'], request.form['token'], ), digestmod=hashlib.sha256, ).hexdigest() if signature != request.form['signature']: logger.error('Invalid headers on incoming mail') raise HTTPError(http.NOT_ACCEPTABLE) SSCORE_MAX_VALUE = 5 DKIM_PASS_VALUES = ['Pass'] SPF_PASS_VALUES = ['Pass', 'Neutral'] def check_mailgun_spam(): """Check DKIM and SPF verification to determine whether incoming message is spam. Returns `True` if either criterion indicates spam, else False. See http://documentation.mailgun.com/user_manual.html#spam-filter for details. :return: Is message spam """ try: sscore_header = float(request.form.get('X-Mailgun-Sscore')) except (TypeError, ValueError): return True dkim_header = request.form.get('X-Mailgun-Dkim-Check-Result') spf_header = request.form.get('X-Mailgun-Spf') return ( (sscore_header and sscore_header > SSCORE_MAX_VALUE) or (dkim_header and dkim_header not in DKIM_PASS_VALUES) or (spf_header and spf_header not in SPF_PASS_VALUES) ) def parse_mailgun_receiver(form): """Check Mailgun recipient and extract test status, meeting name, and content category. Crash if test status does not match development mode in settings. :returns: Tuple of (meeting, category) """ match = re.search( r'''^ (?P<test>test-)? (?P<meeting>\w*?) - (?P<category>poster|talk) @osf\.io $''', form['recipient'], flags=re.IGNORECASE | re.VERBOSE, ) if not match: logger.error('Invalid recipient: {0}'.format(form['recipient'])) raise HTTPError(http.NOT_ACCEPTABLE) data = match.groupdict() if bool(settings.DEV_MODE) != bool(data['test']): logger.error('Mismatch between `DEV_MODE` and recipient {0}'.format(form['recipient'])) raise HTTPError(http.NOT_ACCEPTABLE) return data['meeting'], data['category'] def meeting_hook(): # Fail if not from Mailgun check_mailgun_headers() form = escape_html(request.form.to_dict()) meeting, category = parse_mailgun_receiver(form) conf = Conference.find(Q('endpoint', 'iexact', meeting)) if conf.count(): conf = conf[0] else: raise HTTPError(http.NOT_FOUND) # Fail if not found or inactive # Note: Throw 406 to disable Mailgun retries try: if not conf.active: logger.error('Conference {0} is not active'.format(conf.endpoint)) raise HTTPError(http.NOT_ACCEPTABLE) except KeyError: # TODO: Can this ever be reached? raise HTTPError(http.NOT_ACCEPTABLE) name, address = get_mailgun_from() # Add poster add_poster_by_email( conf=conf, recipient=form['recipient'], address=address, fullname=name, subject=get_mailgun_subject(form), message=form['stripped-text'], attachments=get_mailgun_attachments(), tags=[meeting], system_tags=[meeting], is_spam=check_mailgun_spam(), ) def _render_conference_node(node, idx): storage_settings = node.get_addon('osfstorage') if storage_settings.file_tree and storage_settings.file_tree.children: record = storage_settings.file_tree.children[0] download_count = record.get_download_count() download_url = node.web_url_for( 'osf_storage_view_file', path=record.path, action='download', ) else: download_url = '' download_count = 0 author = node.visible_contributors[0] return { 'id': idx, 'title': node.title, 'nodeUrl': node.url, 'author': author.family_name, 'authorUrl': node.creator.url, 'category': 'talk' if 'talk' in node.system_tags else 'poster', 'download': download_count, 'downloadUrl': download_url, } def conference_data(meeting): try: Conference.find_one(Q('endpoint', 'iexact', meeting)) except ModularOdmException: raise HTTPError(http.NOT_FOUND) nodes = Node.find( Q('tags', 'eq', meeting) & Q('is_public', 'eq', True) & Q('is_deleted', 'eq', False) ) data = [ _render_conference_node(each, idx) for idx, each in enumerate(nodes) ] return data def conference_results(meeting): """Return the data for the grid view for a conference. :param str meeting: Endpoint name for a conference. """ try: conf = Conference.find_one(Q('endpoint', 'iexact', meeting)) except ModularOdmException: raise HTTPError(http.NOT_FOUND) data = conference_data(meeting) return { 'data': json.dumps(data), 'label': meeting, 'meeting': conf.to_storage(), } # TODO: Test me @jmcarp def conference_view(**kwargs): meetings = [] for conf in Conference.find(): query = ( Q('tags', 'eq', conf.endpoint) & Q('is_public', 'eq', True) & Q('is_deleted', 'eq', False) ) projects = Node.find(query) submissions = projects.count() if submissions < settings.CONFERNCE_MIN_COUNT: continue meetings.append({ 'name': conf.name, 'active': conf.active, 'url': web_url_for('conference_results', meeting=conf.endpoint), 'submissions': submissions, }) meetings.sort(key=lambda meeting: meeting['submissions'], reverse=True) return {'meetings': meetings} <file_sep>/website/addons/twofactor/static/twoFactorUserConfig.js ;(function (global, factory) { if (typeof define === 'function' && define.amd) { define(['knockout', 'jquery', 'osfutils'], factory); } else if (typeof $script === 'function') { global.TwoFactorUserConfig = factory(ko, jQuery); $script.done('dropboxUserConfig'); } else { global.TwoFactorUserConfig = factory(ko, jQuery); } }(this, function(ko, $) { var SETTINGS_URL = '/api/v1/settings/twofactor/'; function ViewModel(qrCodeSelector, otpURL) { var self = this; self.qrCodeSelector = qrCodeSelector; self.tfaCode = ko.observable(''); self.message = ko.observable(''); self.messageClass = ko.observable(''); // Initialize QR Code $(self.qrCodeSelector).qrcode(otpURL); /** Change the flashed message. */ self.changeMessage = function(text, css, timeout) { self.message(text); var cssClass = css || 'text-info'; self.messageClass(cssClass); if (timeout) { // Reset message after timeout period setTimeout(function() { self.message(''); self.messageClass('text-info'); }, timeout); } }; self.submitSettings = function() { $.osf.postJSON( SETTINGS_URL, {code: self.tfaCode()} ).done(function() { $('#TfaVerify').slideUp(function() { $('#TfaDeactivate').slideDown(); }); }).fail(function(e) { if (e.status === 403) { self.changeMessage('Verification failed. Please enter your verification code again.', 'text-danger', 5000); } else { self.changeMessage( 'Unexpected HTTP Error (' + e.status + '/' + e.statusText + ')', 'text-danger', 5000); } }); }; } // Public API function TwoFactorUserConfig(scopeSelector, qrCodeSelector, otpURL) { var self = this; self.viewModel = new ViewModel(qrCodeSelector, otpURL); $.osf.applyBindings(self.viewModel, scopeSelector); } return TwoFactorUserConfig; })); <file_sep>/website/assets.py # -*- coding: utf-8 -*- import logging from webassets import Environment, Bundle from website import settings logger = logging.getLogger(__name__) env = Environment(settings.STATIC_FOLDER, settings.STATIC_URL_PATH) css = Bundle( # Vendorized libraries Bundle( 'vendor/bower_components/jquery.tagsinput/jquery.tagsinput.css', 'vendor/pygments.css', 'vendor/bower_components/x-editable/dist/bootstrap3-editable/css/bootstrap-editable.css', 'vendor/bower_components/bootstrap/dist/css/bootstrap-theme.css', 'vendor/bower_components/hgrid/dist/hgrid.css', filters='cssmin'), # Site-specific CSS Bundle( 'css/site.css', 'css/rubeus.css', 'css/commentpane.css', 'vendor/animate/animate-tasteful.min.css', filters="cssmin"), output="public/css/common.css" ) js = Bundle( # Vendorized libraries that are already minified Bundle( # For unknown reasons, moment must be first "vendor/bower_components/moment/min/moment-with-langs.min.js", "vendor/bower_components/bootstrap/dist/js/bootstrap.min.js", "vendor/bootbox/bootbox.min.js", "vendor/script.min.js", ), 'vendor/knockout-sortable/knockout-sortable.js', 'vendor/bower_components/jquery.cookie/jquery.cookie.js', 'js/site.js', "vendor/bower_components/bootstrap.growl/bootstrap-growl.min.js", 'js/growlBox.js', 'js/koHelpers.js', 'js/language.js', output="public/js/common.js" ) js_bottom = Bundle( # Vendorized libraries loaded at the bottom of the page "vendor/bower_components/x-editable/dist/bootstrap3-editable/js/bootstrap-editable.min.js", "vendor/bower_components/jquery.tagsinput/jquery.tagsinput.min.js", "vendor/jquery-blockui/jquery.blockui.js", # 'vendor/dropzone/dropzone.js', # 'vendor/hgrid/hgrid.js', 'vendor/bower_components/jquery-autosize/jquery.autosize.min.js', # Site-specific JS Bundle( 'js/project.js', 'js/addons.js' # 'js/dropzone-patch.js', # 'js/rubeus.js' ), filters='jsmin', output='public/js/site.js' ) logger.debug('Registering asset bundles') env.register('js', js) env.register('css', css) env.register('js_bottom', js_bottom) # Don't bundle in debug mode env.debug = settings.DEBUG_MODE <file_sep>/tests/test_conferences.py # -*- coding: utf-8 -*- from nose.tools import * # noqa (PEP8 asserts) from modularodm.exceptions import ValidationError from website.conferences.views import _parse_email_name, _render_conference_node from website.conferences.model import Conference from website.util import api_url_for, web_url_for from framework.auth.core import Auth from tests.base import OsfTestCase, fake from tests.factories import ModularOdmFactory, FakerAttribute, ProjectFactory class ConferenceFactory(ModularOdmFactory): FACTORY_FOR = Conference endpoint = FakerAttribute('slug') name = FakerAttribute('catch_phrase') active = True def test_parse_email_name(): assert_equal(_parse_email_name(' Fred'), 'Fred') assert_equal(_parse_email_name(u'Me䬟'), u'Me䬟') assert_equal(_parse_email_name(u'Fred <<EMAIL>>'), u'Fred') assert_equal(_parse_email_name(u'"Fred" <<EMAIL>>'), u'Fred') def create_fake_conference_nodes(n, endpoint): nodes = [] for i in range(n): node = ProjectFactory(is_public=True) node.add_tag(endpoint, Auth(node.creator)) node.save() nodes.append(node) return nodes class TestConferenceEmailViews(OsfTestCase): def test_conference_data(self): conference = ConferenceFactory() # Create conference nodes n_conference_nodes = 3 conf_nodes = create_fake_conference_nodes(n_conference_nodes, conference.endpoint) # Create a non-conference node ProjectFactory() url = api_url_for('conference_data', meeting=conference.endpoint) res = self.app.get(url) assert_equal(res.status_code, 200) json = res.json assert_equal(len(json), n_conference_nodes) def test_conference_results(self): conference = ConferenceFactory() url = web_url_for('conference_results', meeting=conference.endpoint) res = self.app.get(url) assert_equal(res.status_code, 200) class TestConferenceModel(OsfTestCase): def test_endpoint_and_name_are_required(self): with assert_raises(ValidationError): ConferenceFactory(endpoint=None, name=fake.company()).save() with assert_raises(ValidationError): ConferenceFactory(endpoint='spsp2014', name=None).save() <file_sep>/website/static/js/filerenderer.js /* * Refresh rendered file through mfr */ (function (global, factory) { if (typeof define === 'function' && define.amd) { define(['jquery'], factory); } else { global.FileRenderer = factory(jQuery); } }(this, function($) { FileRenderer = { start: function(url, selector){ this.url = url; this.element = $(selector); this.tries = 0; this.refreshContent = window.setInterval(this.getCachedFromServer.bind(this), 1000); }, getCachedFromServer: function() { var self = this; $.get( self.url, function(data) { if (data) { self.element.html(data); clearInterval(self.refreshContent); } else { self.tries += 1; if(self.tries > 10){ clearInterval(self.refreshContent); self.element.html("Timeout occurred while loading, please refresh the page") } } }); } }; return FileRenderer; })); <file_sep>/website/addons/dropbox/static/dropboxRubeusCfg.js ;(function (global, factory) { if (typeof define === 'function' && define.amd) { define(['js/rubeus'], factory); } else if (typeof $script === 'function') { $script.ready('rubeus', function() { factory(Rubeus); }); } else { factory(Rubeus); } }(this, function(Rubeus) { Rubeus.cfg.dropbox = { // Custom error message for when folder contents cannot be fetched FETCH_ERROR: '<span class="text-danger">This Dropbox folder may ' + 'have been renamed or deleted. ' + 'Please select a folder at the settings page.</span>' }; })); <file_sep>/website/conferences/model.py # -*- coding: utf-8 -*- from modularodm import fields from framework.mongo import StoredObject class Conference(StoredObject): #: Determines the email address for submission and the OSF url # Example: If endpoint is spsp2014, then submission email will be # <EMAIL> or <EMAIL> and the OSF url will # be osf.io/view/spsp2014 endpoint = fields.StringField(primary=True, required=True, unique=True) #: Full name, e.g. "SPSP 2014" name = fields.StringField(required=True) info_url = fields.StringField(required=False, default=None) logo_url = fields.StringField(required=False, default=None) active = fields.BooleanField(required=True) admins = fields.ForeignField('user', list=True, required=False, default=None) #: Whether to make submitted projects public public_projects = fields.BooleanField(required=False, default=True)
a31849cd6c9330049770e8d9bffb98ba61a59330
[ "JavaScript", "Python" ]
10
JavaScript
dmcwhorter/osf.io
5825439882e655a2b6010e250b9e0059c386b2a4
e58f4472941a89b741086c98f2e2e0789a60a3e8
refs/heads/master
<file_sep><?php class ModuleTemplate{ protected $_data = array( ); public function __get($key) { return isset($this->_data[$key]) ? $this->_data[$key] : null; } public function __isset($key) { if($this->__isPosition($key)){ App::import('Helper', 'Modules.ModuleLoader'); $ModuleLoader = new ModuleLoaderHelper(); $this->_data[$key] = $ModuleLoader->load($key); return true; } } private function __isPosition($position){ return ClassRegistry::init('Modules.ModulePosition')->isPosition($position); } } final class ModulesEvents extends AppEvents{ public function onSetupConfig(){ } public function onSetupCache(){ return array( 'name' => 'modules', 'config' => array( 'prefix' => 'core.modules.' ) ); } public function onAdminMenu($event){ $menu['main'] = array( 'All' => array('plugin' => 'modules', 'controller' => 'modules', 'action' => 'index'), 'Frontend' => array('plugin' => 'modules', 'controller' => 'modules', 'action' => 'index', 'Module.admin' => 0), 'Backend' => array('plugin' => 'modules', 'controller' => 'modules', 'action' => 'index', 'Module.admin' => 1), 'Module Positions' => array('controller' => 'module_positions', 'action' => 'index') ); return $menu; } public function onRequireHelpersToLoad($event){ return array( 'Modules.ModuleLoader' ); } public function onRequireGlobalTemplates($event){ return array( 'ModuleLoader' => new ModuleTemplate() ); } }<file_sep><?php $map = array( 1 => array( '000008_categories' => 'R4c94edcbe44c421e917478d86318cd70'), ); ?><file_sep><?php /** * Comment Template. * * @todo -c Implement .this needs to be sorted out. * * Copyright (c) 2009 <NAME> ( dogmatic69 ) * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. * * @filesource * @copyright Copyright (c) 2009 <NAME> ( dogmatic69 ) * @link http://infinitas-cms.org * @package sort * @subpackage sort.comments * @license http://www.opensource.org/licenses/mit-license.php The MIT License * @since 0.5a */ class WysiwygHelper extends AppHelper{ var $helpers = array( 'Form', 'Html', 'Javascript' ); function load($editor = null, $field = null, $config = array()){ switch($editor){ case 'text': return $this->text($field); break; } // switch $editor = 'Wysiwyg'.Inflector::Classify($editor); if (!App::import('Helper', $editor.'.'.$editor)) { return $this->input($field, array('style' => 'width:98%; height:500px;', 'value' => sprintf(__('%s was not found', true), $editor))); } $helper = $editor.'Helper'; $this->_Editor = new $helper; $fields = explode('.', $field); $heading = '<h3>'.__(ucfirst(isset($fields[1]) ? $fields[1] : $fields[0])).'</h3>'; return $this->input($field, array('label' => false)).$this->_Editor->editor($field, $config); } function text($id = null){ return $this->input($id, array('type' => 'textarea')); } function input($id, $params = array('style' => 'width:98%; height:500px;')){ return $this->Form->input($id, $params); } } ?><file_sep><?php /* IpAddress Test cases generated on: 2010-03-13 11:03:42 : 1268471142*/ App::import('Model', 'management.IpAddress'); class IpAddressTestCase extends CakeTestCase { function startTest() { $this->IpAddress =& ClassRegistry::init('IpAddress'); } function endTest() { unset($this->IpAddress); ClassRegistry::flush(); } } ?><file_sep><?php class FixtureTask extends Shell { public $connection = 'default'; public function generate($models = null, $plugin = null) { if($models == null) { $models = array( 'Aco', 'Aro', 'ArosAco', 'Session' ); } $fixtures = array(); foreach($models as $model => $options) { if(is_string($options)) { $model = $options; $options = array( 'core' => array( 'where' => '1=1', 'limit' => 0 ) ); } foreach($options as $type => $option) { $modelName = $plugin . '.' . $model; $conditions = $option['where']; if($option['limit'] != 0) { $conditions .= ' LIMIT ' . $option['limit']; } $records = $this->_getRecordsFromTable($modelName, $conditions); if(!empty($records)) { $fixtures[$type][$model] = $records; } } } return $this->_makeRecordString($fixtures); } /** * Interact with the user to get a custom SQL condition and use that to extract data * to build a fixture. * * @param string $modelName name of the model to take records from. * @param string $useTable Name of table to use. * @return array Array of records. * @access protected */ function _getRecordsFromTable($modelName, $condition, $useTable = null) { $modelObject = ClassRegistry::init($modelName); $out = array(); if(is_object($modelObject) && isset($modelObject->useTable) && $modelObject->useTable !== false) { $records = $modelObject->find('all', array( 'conditions' => $condition, 'recursive' => -1 )); $db =& ConnectionManager::getDataSource($modelObject->useDbConfig); $schema = $modelObject->schema(true); if(!empty($records)) { foreach ($records as $record) { $row = array(); foreach ($record[$modelObject->alias] as $field => $value) { if(isset($schema[$field])) { $row[$field] = $db->value($value, $schema[$field]['type']); } } $out[] = $row; } } } return $out; } /** * Convert a $records array into a a string. * * @param array $records Array of records to be converted to string * @return string A string value of the $records array. * @access protected */ function _makeRecordString($records) { $out = ''; foreach($records as $type => $models) { $out .= "\t'$type' => array(\n"; foreach($models as $model => $modelRecords) { $out .= "\t\t'$model' => array(\n"; foreach ($modelRecords as $record) { $values = array(); foreach ($record as $field => $value) { $values[] = "\t\t\t\t'$field' => $value"; } $out .= "\t\t\tarray(\n"; $out .= implode(",\n", $values); $out .= "\n\t\t\t),\n"; } $out .= "\t\t),\n"; } $out .= "\t\t),\n"; } return $out; } }<file_sep><table class="listing" cellpadding="0" cellspacing="0"> <?php echo $this->Core->adminTableHeader( array( __('Username', true), __('Browser', true) => array( 'style' => 'width:75px;' ), __('OS', true) => array( 'style' => 'width:75px;' ), __('Country', true) => array( 'style' => 'width:75px;' ), __('Last Login', true) => array( 'style' => 'width:75px;' ) ) ); foreach ( $users as $user ) { ?> <tr class="<?php echo $this->Core->rowClass(); ?>"> <td> <?php echo $this->Html->link( $user['User']['username'], array('action' => 'edit', $user['User']['id'])); ?>&nbsp; </td> <td> <?php echo $user['User']['browser']; ?>&nbsp; </td> <td> <?php echo $user['User']['operating_system']; ?>&nbsp; </td> <td> <?php echo $user['User']['country']; ?>&nbsp; </td> <td> <?php echo $this->Time->niceShort($user['User']['last_login']); ?>&nbsp; </td> </tr> <?php } ?> </table><file_sep><?php /** * @brief The Contact model handles the CRUD for user details. * * @todo link up the contacts to users in the User table * * @copyright Copyright (c) 2010 <NAME> ( dogmatic69 ) * @link http://www.infinitas-cms.org * @package Infinitas.Contact.models * @license http://www.opensource.org/licenses/mit-license.php The MIT License * @since 0.7a * * @author dogmatic69 * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. */ class Contact extends ContactAppModel{ /** * the models name * @var string */ public $name = 'Contact'; /** * Behaviors that are attached to this model * @var string */ public $actsAs = array( 'MeioUpload.MeioUpload' => array( 'image' => array( 'dir' => 'img{DS}content{DS}contact{DS}{ModelName}', 'create_directory' => true, 'allowed_mime' => array( 'image/jpeg', 'image/pjpeg', 'image/png' ), 'allowed_ext' => array( '.jpg', '.jpeg', '.png' ), ) ), 'Libs.Sequence' => array( 'group_fields' => array( 'branch_id' ) ), 'Libs.Sluggable' => array( 'label' => array( 'first_name', 'last_name' ), 'length' => 255, 'overwrite' => true ) ); /** * Relations for this model * @var array */ public $belongsTo = array( 'Branch' => array( 'className' => 'Contact.Branch', 'counterCache' => 'user_count', 'counterScope' => array('Contact.active' => 1) ) ); /** * The branch model * * @var Branch */ public $Branch; /** * @copydoc AppModel::__construct() */ public function __construct($id = false, $table = null, $ds = null) { parent::__construct($id, $table, $ds); $this->validate = array( 'first_name' => array( 'notEmpty' => array( 'rule' => 'notEmpty', 'message' => __('Please enter the contacts first name', true) ), ), 'last_name' => array( 'notEmpty' => array( 'rule' => 'notEmpty', 'message' => __('Please enter the contacts last name', true) ), ), 'phone' => array( 'phone' => array( 'rule' => array('phone', '/\D?(\d{3})\D?\D?(\d{3})\D?(\d{4})$/'), //Configure::read('Website.phone_regex')), 'message' => __('The number does not seem to be valid', true), 'allowEmpty' => true ) ), 'mobile' => array( 'phone' => array( 'rule' => array('phone', '/\D?(\d{3})\D?\D?(\d{3})\D?(\d{4})$/'), //Configure::read('Website.phone_regex')), 'message' => __('Please enter a valid mobile number', true), 'allowEmpty' => true ) ), 'email' => array( 'notEmpty' => array( 'rule' => 'notEmpty', 'message' => __('Please enter an email address', true) ), 'email' => array( 'rule' => array('email', true), 'message' => __('That email address does not seem valid', true) ) ), 'branch_id' => array( 'rule' => array('comparison', '>', 0), 'message' => __('Please select a branch', true) ) ); } }<file_sep><?php /** * @brief CommentAttribute model is only here for the installer to work properly * * @copyright Copyright (c) 2010 <NAME> ( dogmatic69 ) * @link http://www.infinitas-cms.org * @package Infinitas.Comments.models * @license http://www.opensource.org/licenses/mit-license.php The MIT License * @since 0.8a * * @author dogmatic69 * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. */ class CommentAttribute extends CommentsAppModel { /** * The model name * * @var string * @access public */ public $name = 'CommentAttribute'; }<file_sep><?php class GlobalContent extends ContentsAppModel{ public $name = 'GlobalContent'; public $useTable = 'global_contents'; public $belongsTo = array( 'GlobalLayout' => array( 'className' => 'Contents.GlobalLayout', 'foreignKey' => 'layout_id', 'fields' => array( 'GlobalLayout.id', 'GlobalLayout.name', 'GlobalLayout.model', 'GlobalLayout.css', 'GlobalLayout.html' ) ), 'Group' => array( 'className' => 'Users.Group', 'foreignKey' => 'group_id', 'fields' => array( 'Group.id', 'Group.name' ) ) ); public function __construct($id = false, $table = null, $ds = null) { parent::__construct($id, $table, $ds); $this->validate = array( 'title' => array( 'notEmpty' => array( 'rule' => 'notEmpty', 'message' => __('Please enter a name for this content item', true) ) ), 'layout_id' => array( 'notEmpty' => array( 'rule' => 'notEmpty', 'message' => __('Please select the layout for this content item', true) ) ), 'group_id' => array( 'notEmpty' => array( 'rule' => 'notEmpty', 'message' => __('Please select the lowest group that will have access', true) ) ), 'body' => array( 'notEmpty' => array( 'rule' => 'notEmpty', 'message' => __('Please enter the body of this content item', true) ) ) ); } public function moveContent($model = null, $limit = 500){ if(!$model){ trigger_error(__('No model selected to move', true), E_USER_WARNING); return false; } if(!is_int($limit)){ $limit = 500; } $return = array(); $return['moved'] = 0; $Model = ClassRegistry::init($model); $return['total'] = $Model->find( 'count', array( 'conditions' => array( $Model->alias . '.' . $Model->displayField . ' IS NOT NULL' ) ) ); if($Model->displayField == $Model->primaryKey){ trigger_error(sprintf(__('Display field and primary key are the same for %s, cant move', true), $model), E_USER_WARNING); return false; } $rows = $Model->find( 'all', array( 'conditions' => array( $Model->alias . '.' . $Model->displayField . ' IS NOT NULL' ), 'contain' => false, 'limit' => $limit ) ); foreach($rows as $row){ $newContent = array(); $newContent[$this->alias] = $row[$Model->alias]; $newContent[$this->alias]['foreign_key'] = $row[$Model->alias][$Model->primaryKey]; $newContent[$this->alias]['model'] = $Model->plugin . '.' . $Model->alias; unset($newContent[$this->alias][$Model->primaryKey]); $this->create(); if($this->save($newContent)){ $Model->id = $row[$Model->alias][$Model->primaryKey]; $Model->saveField($Model->displayField, '', false); $return['moved']++; } } return $return; } }<file_sep><?php $categories = ClassRegistry::init('Categories.Category')->generateTreeList(); if(!isset($options)) { $options = array(); } $options = array_merge((array)$options, array('options' => $categories, 'empty' => Configure::read('Website.empty_select'))); unset($categories); echo $this->Form->input('category_id', $options); ?><file_sep><?php /** * Comment Template. * * @todo Implement .this needs to be sorted out. * * Copyright (c) 2009 <NAME> ( dogmatic69 ) * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. * @filesource * @copyright Copyright (c) 2009 <NAME> ( dogmatic69 ) * @link http://infinitas-cms.org * @package sort * @subpackage sort.comments * @license http://www.opensource.org/licenses/mit-license.php The MIT License * @since 0.5a */ class ManagementController extends ManagementAppController { public $name = 'Management'; public $uses = array(); public function beforeFilter(){ parent::beforeFilter(); $this->helpers[] = 'Google.Chart'; } /** * This is the main admin dashboard when visiting admin/ */ public function admin_dashboard() { } /** * This is a few of the smaller items that dont need to be directly on the * main dashboard as they will not be used all that often. */ public function admin_site(){ } }<file_sep><?php /* * Short Description / title. * * Overview of what the file does. About a paragraph or two * * Copyright (c) 2010 <NAME> ( dogmatic69 ) * * @filesource * @copyright Copyright (c) 2010 <NAME> ( dogmatic69 ) * @link http://www.infinitas-cms.org * @package {see_below} * @subpackage {see_below} * @license http://www.opensource.org/licenses/mit-license.php The MIT License * @since {check_current_milestone_in_lighthouse} * * @author {your_name} * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. */ $parts = $this->Event->trigger('userProfile'); ?> <h3><?php echo $user['User']['username']; ?></h3> <?php foreach($parts['userProfile'] as $plugin => $profile){ echo sprintf('<div class="profile %s">%s</div>', $plugin, $this->element($profile['element'], array('plugin' => $plugin))); } ?> <file_sep><?php echo $category['Category']['description']; ?><file_sep><?php /* SVN FILE: $Id$ */ /* Contact schema generated on: 2010-09-18 18:09:20 : 1284828620*/ class ContactSchema extends CakeSchema { var $name = 'Contact'; function before($event = array()) { return true; } function after($event = array()) { } var $branches = array( 'id' => array('type' => 'integer', 'null' => false, 'default' => NULL, 'length' => 10, 'key' => 'primary'), 'name' => array('type' => 'string', 'null' => false, 'default' => NULL, 'length' => 100), 'slug' => array('type' => 'string', 'null' => false, 'default' => NULL), 'map' => array('type' => 'string', 'null' => true, 'default' => NULL), 'image' => array('type' => 'string', 'null' => true, 'default' => NULL, 'length' => 100), 'email' => array('type' => 'string', 'null' => false, 'default' => NULL, 'length' => 100), 'phone' => array('type' => 'string', 'null' => true, 'default' => NULL, 'length' => 20), 'fax' => array('type' => 'string', 'null' => true, 'default' => NULL, 'length' => 20), 'address_id' => array('type' => 'integer', 'null' => false, 'default' => '0'), 'user_count' => array('type' => 'integer', 'null' => false, 'default' => NULL), 'active' => array('type' => 'boolean', 'null' => false, 'default' => '0'), 'ordering' => array('type' => 'integer', 'null' => false, 'default' => NULL), 'time_zone_id' => array('type' => 'integer', 'null' => false, 'default' => NULL), 'created' => array('type' => 'datetime', 'null' => true, 'default' => NULL), 'modified' => array('type' => 'datetime', 'null' => true, 'default' => NULL), 'indexes' => array('PRIMARY' => array('column' => 'id', 'unique' => 1)), 'tableParameters' => array('charset' => 'utf8', 'collate' => 'utf8_general_ci', 'engine' => 'InnoDB') ); var $contacts = array( 'id' => array('type' => 'integer', 'null' => false, 'default' => NULL, 'length' => 10, 'key' => 'primary'), 'user_id' => array('type' => 'integer', 'null' => false, 'default' => NULL), 'image' => array('type' => 'string', 'null' => false, 'default' => NULL), 'first_name' => array('type' => 'string', 'null' => false, 'default' => NULL, 'length' => 50), 'last_name' => array('type' => 'string', 'null' => false, 'default' => NULL, 'length' => 100), 'slug' => array('type' => 'string', 'null' => false, 'default' => NULL), 'position' => array('type' => 'string', 'null' => true, 'default' => NULL, 'length' => 100), 'phone' => array('type' => 'string', 'null' => false, 'default' => NULL, 'length' => 20), 'mobile' => array('type' => 'string', 'null' => false, 'default' => NULL, 'length' => 20), 'email' => array('type' => 'string', 'null' => false, 'default' => NULL, 'length' => 100), 'skype' => array('type' => 'string', 'null' => true, 'default' => NULL, 'length' => 50), 'branch_id' => array('type' => 'integer', 'null' => false, 'default' => NULL), 'ordering' => array('type' => 'integer', 'null' => false, 'default' => NULL), 'configs' => array('type' => 'text', 'null' => false, 'default' => NULL), 'active' => array('type' => 'boolean', 'null' => false, 'default' => NULL), 'created' => array('type' => 'datetime', 'null' => true, 'default' => NULL), 'modified' => array('type' => 'datetime', 'null' => true, 'default' => NULL), 'indexes' => array('PRIMARY' => array('column' => 'id', 'unique' => 1)), 'tableParameters' => array('charset' => 'utf8', 'collate' => 'utf8_general_ci', 'engine' => 'InnoDB') ); } ?><file_sep><?php /** * Comment Template. * * @todo Implement .this needs to be sorted out. * * Copyright (c) 2009 <NAME> ( dogmatic69 ) * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. * @filesource * @copyright Copyright (c) 2009 <NAME> ( dogmatic69 ) * @link http://infinitas-cms.org * @package sort * @subpackage sort.comments * @license http://www.opensource.org/licenses/mit-license.php The MIT License * @since 0.5a */ class NewslettersController extends NewsletterAppController { /** * Class name. * * @access public * @var string */ public $name = 'Newsletters'; public function beforeFilter() { parent::beforeFilter(); // @todo make sure function track is allowed by all $this->Auth->allow('track'); } public function track($id) { Configure::write('debug', 0); $this->autoRender = false; $this->layout = 'ajax'; if (!$id) { $this->log('no id for email tracking', 'newsletter'); exit; } $this->Newsletter->id = $id; $views = $this->Newsletter->read('views'); if (empty($views)) { $this->log('no newsletter found with id: ' . $id); exit; } if (!$this->Newsletter->saveField('views', $views['Newsletter']['views'] + 1)) { $this->log('could not save a view for id: ' . $id); } exit; } public function sendEmail(){ $info = array_merge( array( 'to' => array(), 'cc' => array(), 'bcc' => array(), 'subject' => null, 'html' => null, 'text' => null ), $this->params['named']['email'] ); $this->Emailer->to = $info['to']; $this->Emailer->bcc = $info['bcc']; $this->Emailer->subject = $info['subject']; $this->Emailer->template = 'blank'; $this->set('info', $info); $this->Emailer->delivery = 'smtp'; $this->Emailer->send(); } public function sendNewsletters() { $this->autoRender = false; $this->layout = 'ajax'; Configure::write('debug', 0); $newsletters = $this->Newsletter->find( 'all', array( 'fields' => array( 'Newsletter.id', 'Newsletter.html', 'Newsletter.text', 'Newsletter.sends' ), 'conditions' => array( 'Newsletter.sent' => 0, 'Newsletter.active' => 1, ), 'contain' => array( 'Template' => array( 'fields' => array( 'Template.header', 'Template.footer', ) ), 'User' => array( 'fields' => array( 'User.id', 'User.email', 'User.username' ), 'conditions' => array( 'NewslettersUser.sent' => 0 ) ) ) ) ); foreach($newsletters as $newsletter) { if (empty($newsletter['User'])) { continue; } $html = $newsletter['Template']['header'] . $newsletter['Newsletter']['html'] . $newsletter['Template']['footer']; $search = array( '<br/>', '<br>', '</p><p>' ); $text = strip_tags( str_replace($search, "\n\r", $newsletter['Template']['header'] . $newsletter['Newsletter']['html'] . $newsletter['Template']['footer'] ) ); foreach($newsletter['User'] as $user) { $to = $user['email']; $name = $user['username']; // @todo send the email here if (false) { $this->Newsletter->NewslettersUser->id = $user['NewslettersUser']['id']; if (!$this->Newsletter->NewslettersUser->saveField('sent', 1)) { $this->log('problem sending mail #' . $newsletter['Newsletter']['id'] . ' to user #' . $user['id'], 'newsletter'); } $this->Newsletter->id = $newsletter['Newsletter']['id']; if (!$this->Newsletter->saveField('sends', $newsletter['Newsletter']['sends'] + 1)) { $this->log('problem counting send for mail #' . $newsletter['Newsletter']['id'], 'newsletter'); } } } } } public function admin_dashboard() { } public function admin_report($id) { if (!$id) { $this->Infinitas->noticeInvalidRecord(); } } public function admin_index() { $this->paginate = array( 'fields' => array( 'Newsletter.id', 'Newsletter.campaign_id', 'Newsletter.from', 'Newsletter.reply_to', 'Newsletter.subject', 'Newsletter.active', 'Newsletter.sent', 'Newsletter.created', ), 'limit' => 20, 'contain' => array( 'Campaign' => array( 'fields' => array( 'Campaign.name' ) ) ) ); $newsletters = $this->paginate('Newsletter', $this->Filter->filter); $filterOptions = $this->Filter->filterOptions; $filterOptions['fields'] = array( 'subject', 'html', 'from', 'reply_to' ); $this->set(compact('newsletters','filterOptions')); } public function admin_add(){ parent::admin_add(); $campaigns = $this->Newsletter->Campaign->find('list'); if(empty($campaigns)){ $this->notice( __('Please create a campaign before creating a newsletter', true), array( 'level' => 'notice', 'redirect' => array( 'controller' => 'campaigns' ) ) ); } $this->set(compact('campaigns')); } public function admin_view($id = null) { if (!$id && empty($this->data)) { $this->Infinitas->noticeInvalidRecord(); } $newsletter = $this->Newsletter->read(null, $id); if (!empty($this->data)) { $id = $this->data['Newsletter']['id']; $addresses = explode(',', $this->data['Newsletter']['email_addresses']); if (empty($addresses)) { $this->notice( __('Please input at least one email address for testing', true), array( 'level' => 'warning', 'redirect' => true ) ); } $sent = 0; foreach($addresses as $address) { $this->Email->from = 'Infinitas Test Mail <' . $newsletter['Newsletter']['from'] . '>'; $this->Email->to = 'Test <' . $address . '>'; $this->Email->subject = strip_tags($newsletter['Newsletter']['subject']); $this->set('email', $newsletter['Template']['header'] . $newsletter['Newsletter']['html'] . $newsletter['Template']['footer']); if ($this->Email->send()) { $sent++; } pr($this->Email->smtpError); $this->Email->reset(); } $this->notice(sprintf(__('%s mails were sent', true), $sent)); } if (empty($this->data) && $id) { $this->data = $newsletter; } $this->set('newsletter', $this->Newsletter->read(null, $id)); } public function admin_preview($id = null) { $this->layout = 'ajax'; if (!$id) { $this->set('data', __('The template was not found', true)); }else { $newsletter = $this->Newsletter->find( 'first', array( 'fields' => array( 'Newsletter.id', 'Newsletter.html' ), 'conditions' => array( 'Newsletter.id' => $id ), 'contain' => array( 'Template' => array( 'fields' => array( 'Template.header', 'Template.footer', ) ) ) ) ); $this->set('data', $newsletter['Template']['header'] . $newsletter['Newsletter']['html'] . $newsletter['Template']['footer']); } } public function __massActionDelete($ids){ return $this->MassAction->delete($this->__canDelete($ids)); } private function __canDelete($ids) { $newsletters = $this->Newsletter->find( 'list', array( 'fields' => array( 'Newsletter.id', 'Newsletter.id' ), 'conditions' => array( 'Newsletter.sent' => 0, // only get mails that are not sent 'Newsletter.sends > ' => 0, // get mails that have not sent anything. 'Newsletter.id' => $ids ) ) ); if (empty($newsletters)) { $this->notice( __('There are no newsletters to delete.', true), array( 'level' => 'warning', 'redirect' => 'true' ) ); } return $newsletters; } public function admin_toggleSend($id = null) { if (!$id) { $this->Infinitas->noticeInvalidRecord(); } $this->Newsletter->recursive = - 1; $sent = $this->Newsletter->read(array('id', 'sent', 'active'), $id); if (!isset($sent['Newsletter']['sent'])) { $this->notice( __('The newsletter was not found', true), array( 'level' => 'error', 'redirect' => true ) ); } if ($sent['Newsletter']['sent']) { $this->notice( __('The newsletter has already been sent', true), array( 'level' => 'warning', 'redirect' => true ) ); } if (!$sent['Newsletter']['active']) { $sent['Newsletter']['active'] = 1; if (!$this->Newsletter->save($sent)) { $this->notice( __('Could not activate the newsletter', true), array( 'level' => 'error', 'redirect' => true ) ); } } $this->notice( __('Newsletter is now sending.', true), array( 'redirect' => true ) ); } public function admin_stopAll() { $runningNewsletters = $this->Newsletter->find( 'list', array( 'fields' => array( 'Newsletter.id', 'Newsletter.id' ), 'conditions' => array( 'Newsletter.active' => 1, 'Newsletter.sent' => 0 ), 'contain' => false ) ); foreach($runningNewsletters as $id) { $this->Newsletter->id = $id; $this->Newsletter->saveField('active', 0); } $this->notice( __('All newsletters have been stopped.', true), array( 'redirect' => true ) ); } }<file_sep><?php class ValidationBehavior extends ModelBehavior { /** * @brief This can either be empty or a valid json string. * * @deprecated * * @param array $field the field being validated * @access public * * @return bool is it valid */ public function validateEmptyOrJsonDeprecated($Model, $field){ return strlen(current($field)) == 0 || $Model->validateJson(current($field)); } /** * @brief This can either be empty or a valid json string. * * @deprecated * * @param array $field the field being validated * @access public * * @return bool is it valid */ public function validateJson($Model, $field){ return $Model->getJson($Model->data[$Model->alias][current(array_keys($field))], array(), false); } /** * @brief allow the selection of one field or another or nothing * * @deprecated * * @param array $field not used * @params array $fields list of 2 fields that should be checked * @access public * * @return bool is it valid? */ public function validateNothingEitherOr($Model, $field, $fields = array()){ return // nothing empty($Model->data[$Model->alias][$fields[0]]) && empty($Model->data[$Model->alias][$fields[1]]) || // either or $this->validateEitherOr($Model, $field, $fields); } /** * @brief allow the selection of one field or another * * This is used in times where one thing should be filled out and another * should be left empty. * * @param array $field not used * @params array $fields list of 2 fields that should be checked * @access public * * @return bool is it valid? */ public function validateEitherOr($Model, $field, $fields){ return // either empty($Model->data[$Model->alias][$fields[0]]) && !empty($Model->data[$Model->alias][$fields[1]]) || // or !empty($Model->data[$Model->alias][$fields[0]]) && empty($Model->data[$Model->alias][$fields[1]]); } /** * @brief check for urls either /something/here or full * * this can be a url relative to the site /my/page or full like * http://site.com/my/page it can also be empty for times when the selects * are used to build the url * * @todo remove current($field) == '' || as 'notEmpty' works fine * * @param array $field the field being validated * @access public * * @return bool is it valid */ public function validateUrlOrAbsolute($Model, $field){ return // not in use current($field) == '' || // aboulute url substr(current($field), 0, 1) == '/' || // valid url Validation::url(current($field), true); } /** * @brief compare 2 fields and make sure they are the same * * This method can compare 2 fields, with password having a special meaning * as they will be hashed automatically. * * the order of password fields is important as you could end up hashing * the hashed password again and still having the other one as plain text * which will always fail. * * basic usage * * @code * // random fields * 'rule' => array( * 'validateCompareFields', array('field1', 'field2') * ), * 'message' => 'fields do not match' * * // real world * 'rule' => array( * 'validateCompareFields', array('email', 'compare_email') * ), * 'message' => 'The email addresses you entered do not match' * * 'rule' => array( * 'validateCompareFields', array('compare_password', 'password') * ), * 'message' => 'The email addresses you entered do not match' * @endcode * * @todo move to a validation behavior * * @param array $field not used * @access public * * @param bool $fields the fields to compare */ public function validateCompareFields($Model, $field, $fields){ if($fields[0] == 'password'){ if(!class_exists('Security')){ App::import('Security'); } return Security::hash($Model->data[$Model->alias][$fields[1]], null, true) === $Model->data[$Model->alias][$fields[0]]; } return $Model->data[$Model->alias][$fields[0]] === $Model->data[$Model->alias][$fields[1]]; } }<file_sep><?php /* * Short Description / title. * * Overview of what the file does. About a paragraph or two * * Copyright (c) 2010 <NAME> ( dogmatic69 ) * * @filesource * @copyright Copyright (c) 2010 <NAME> ( dogmatic69 ) * @link http://www.infinitas-cms.org * @package {see_below} * @subpackage {see_below} * @license http://www.opensource.org/licenses/mit-license.php The MIT License * @since {check_current_milestone_in_lighthouse} * * @author {your_name} * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. */ class LockerComponent extends InfinitasComponent{ public function initialize($Controller){ if(!strstr($Controller->action, 'admin') && isset($Controller->{$Controller->modelClass}->Behaviors)){ $Controller->{$Controller->modelClass}->Behaviors->disable('Locks.Lockable'); } } public function beforeRender($Controller){ if(isset($Controller->data['Lock']['user_id']) && $Controller->data['Lock']['user_id'] != $this->Session->read('Auth.User.id')){ $Controller->Session->setFlash(sprintf(__('The %s you requested has been locked by %s', true), $Controller->prettyModelName, $Controller->data['Locker']['username'])); $Controller->redirect(array('plugin' => 'locks', 'controller' => 'locks', 'action' => 'locked')); } } public function beforeRedirect($Controller){ if(isset($Controller->{$Controller->modelClass}->lockable) && $Controller->{$Controller->modelClass}->lockable){ if(isset($Controller->params['form']['action']) && $Controller->params['form']['action'] == 'cancel'){ $Controller->{$Controller->modelClass}->Lock->deleteAll( array( 'Lock.class' => Inflector::camelize($Controller->plugin).'.'.$Controller->modelClass, 'Lock.foreign_key' => $Controller->params['data'][$Controller->modelClass][$Controller->{$Controller->modelClass}->primaryKey] ) ); } } } }<file_sep><div id="menucontainer" class="grid_16 center"> <div id="menunav"> <ul> <?php if(isset($pluginInfo['pluginRollCall'][$this->plugin]['icon'])){ echo '<li class="icon">'.$this->Html->image(DS . $this->plugin . DS . 'img' . DS . 'icon.png').'</li>'; } ?> <li><?php echo implode('</li><li>', $this->Menu->builAdminMenu()); ?></li> </ul> <?php echo $this->Html->image('/users/img/logout.png', array('url' => '/admin/logout', 'class' => 'logout-link')); ?> </div> </div> <div class="clear"></div><file_sep><?php $map = array( 1 => array( '000008_meio_upload' => 'R4c94edcd121c4ec3b04478d86318cd70'), ); ?><file_sep><?php class ResetDataShell extends Shell { var $uses = array('Installer.Release'); function main() { $this->out('Reseting database'); $this->Release->installData(true); $this->out('Done'); } }<file_sep><?php /** * Themes controller for managing the themes in infinitas * * Copyright (c) 2009 <NAME> ( dogmatic69 ) * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. * @filesource * @copyright Copyright (c) 2009 <NAME> ( dogmatic69 ) * @link http://infinitas-cms.org * @package sort * @subpackage sort.comments * @license http://www.opensource.org/licenses/mit-license.php The MIT License * @since 0.5a */ class ThemesController extends ThemesAppController{ public $name = 'Themes'; public function admin_index() { $this->Theme->recursive = 1; $themes = $this->paginate(null, $this->Filter->filter); $filterOptions = $this->Filter->filterOptions; $filterOptions['fields'] = array( 'name' => $this->Theme->find('list'), 'licence', 'author', 'core' => Configure::read('CORE.core_options'), 'active' => Configure::read('CORE.active_options') ); $this->set(compact('themes', 'filterOptions')); } public function admin_add(){ parent::admin_add(); $themes = $this->__listThemes(); if(empty($themes)){ $this->notice( __('You do not have any themes to add', true), array( 'level' => 'warning', 'redirect' => true ) ); } $this->set(compact('themes')); } public function admin_edit($id){ parent::admin_edit($id); $themes = $this->__listThemes(); $themes[$this->data['Theme']['name']] = $this->data['Theme']['name']; $this->set(compact('themes')); } private function __listThemes($return = false){ $Folder = new Folder(APP . 'views' . DS . 'themed'); $folders = $Folder->read(); unset($Folder); $themes = array(); $exsitingThemes = $this->Theme->find('list'); foreach($folders[0] as $theme){ if(in_array($theme, $exsitingThemes)){ continue; } $themes[$theme] = Inflector::humanize($theme); } return $themes; } /** * Mass toggle action. * * This overwrites the default toggle action so that other themes can * be deactivated first as you should only have one active at a time. * * @var array $ids the id of the theme to toggle */ public function __massActionToggle($ids) { if (count($ids) > 1) { $this->notice( __('Please select only one theme to be active', true), array( 'level' => 'warning', 'redirect' => true ) ); } if ($this->Theme->deactivateAll()) { return $this->MassAction->toggle($ids); } $this->notice( __('There was a problem deactivating the other theme', true), array( 'level' => 'error', 'redirect' => true ) ); } }<file_sep><?php final class ServerStatusEvents extends AppEvents{ public function __construct() { parent::__construct(); } public function onAdminMenu($event){ $menu['main']['Dashboard'] = array('controller' => 'server_status', 'action' => 'dashboard'); switch($event->Handler->params['controller']){ case 'php': $menu['main']['Php Info'] = array('controller' => 'php', 'action' => 'info'); $menu['main']['APC'] = array('controller' => 'php', 'action' => 'apc'); break; } return $menu; } }<file_sep><div class="dashboard"> <h1><?php echo $name; ?></h1> <p class="error"> <strong><?php __('Error'); ?>: </strong> <?php printf(__('The requested address <strong>\'%s\'</strong> was not found on this server.', true), htmlspecialchars($message)); ?> </p> </div><file_sep><?php /* * Short Description / title. * * Overview of what the file does. About a paragraph or two * * Copyright (c) 2010 <NAME> ( dogmatic69 ) * * @filesource * @copyright Copyright (c) 2010 <NAME> ( dogmatic69 ) * @link http://www.infinitas-cms.org * @package {see_below} * @subpackage {see_below} * @license http://www.opensource.org/licenses/mit-license.php The MIT License * @since {check_current_milestone_in_lighthouse} * * @author {your_name} * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. */ ?> <div class="table"> <h1 class="no-gap">Local Variables<small>Only what is different</small></h1> <table class="listing no-gap" cellpadding="0" cellspacing="0"> <thead> <tr> <th style="width:200px;">Variable Name</th> <th>Value</th> </tr> </thead> <?php foreach($localVars as $name => $value){ $globalVars[$name] = sprintf('<b style="color:red;">%s</b>', $globalVars[$name]); ?> <tr> <td><?php echo $name; ?></td> <td><?php echo $value; ?></td> </tr> <?php } ?> </table> </div> <div class="table"> <h1 class="no-gap">Global Variables<small>Highlighted Items have been Changed localy</small></h1> <table class="listing no-gap" cellpadding="0" cellspacing="0"> <thead> <tr> <th style="width:200px;">Variable Name</th> <th>Value</th> </tr> </thead> <?php foreach($globalVars as $name => $value){ ?> <tr> <td><?php echo $name; ?></td> <td><?php echo $value; ?></td> </tr> <?php } ?> </table> </div><file_sep><?php $icons = $this->Menu->builDashboardLinks(); ?> <div id="dock" class="plugins"> <div class="panel" style="display: none;"> <div class="dashboard"> <ul class="icons"><li><?php echo implode('</li><li>', $icons['core']); ?></li></ul> </div> <?php if(isset($icons['plugin'])){ ?> <div class="dashboard"> <ul class="icons"><li><?php echo implode('</li><li>', $icons['plugin']); ?></li></ul> </div> <?php } ?> </div> <a href="#" class="trigger"><?php echo __('Plugins', true); ?></a> </div><file_sep><?php class Cron extends CoreAppModel{ /** * @copydoc AppModel::name */ public $name = 'Cron'; /** * @brief The process that is currently running * * @property _currentProcess */ protected $_currentProcess; /** * @copydoc AppModel::__construct() * * Create some virtual fields for easier finds later on */ public function __construct($id = false, $table = null, $ds = null) { parent::__construct($id, $table, $ds); $this->virtualFields['created'] = 'CONCAT('. $this->alias.'.year, "-", '. $this->alias.'.month, "-", `'. $this->alias.'.day, " ", '. $this->alias.'.start_time)'; $this->virtualFields['modified'] = 'CONCAT('. $this->alias.'.year, "-", '. $this->alias.'.month, "-", `'. $this->alias.'.day, " ", '. $this->alias.'.end_time)'; } /** * @brief save the start of a cron run * * This is later used to check if any processes are running, along with * some stats befor the cron starts. This will enable infinitas to show * how much resources the crons are taking up. * * @return bool|void true if everything is cool, null if already running or could not start */ public function start(){ $data = null; $memUsage = memoryUsage(false, false); $serverLoad = serverLoad(false); $data['Cron'] = array( 'process_id' => @getmypid(), 'year' => date('Y'), 'month' => date('m'), 'day' => date('d'), 'start_time' => date('H:i:s'), 'start_mem' => $memUsage['current'], 'start_load' => $serverLoad[0] >= 0 ? $serverLoad[0] : 0 ); unset($memUsage, $serverLoad); $this->create(); $alreadyRunning = $this->_isRunning(); if($this->save($data)){ $this->_currentProcess = $this->id; return $alreadyRunning === false; } } /** * @brief updates the cron row to show the process as complete * * When the cron run is done this method is called to mark the end of the * process, along with recording some stats on the system that can * later be used for analysys. * * @param int $tasksRan the number of events that did something * @param string $memAverage average memory usage for the run * @param string $loadAverage system load average for the run * @access public * * @return AppModel::save() */ public function end($tasksRan = 0, $memAverage = 0, $loadAverage = 0){ if(!$this->_currentProcess){ trigger_error(__('Cron not yet started', true), E_USER_WARNING); return false; } $data = null; $memUsage = memoryUsage(false, false); $serverLoad = serverLoad(false); $data['Cron'] = array( 'id' => $this->_currentProcess, 'end_time' => date('H:i:s'), 'end_mem' => $memUsage['current'], 'end_load' => $serverLoad[0] >= 0 ? $serverLoad[0] : 0, 'mem_ave' => $memAverage, 'load_ave' => $loadAverage, 'tasks_ran' => $tasksRan, 'done' => 1 ); unset($memUsage, $serverLoad); $this->_currentProcess = null; return $this->save($data); } /** * @brief check if a cron is already running * * This does a simple check against the database to see if any jobs are * open (not marked done). If there are there could be something still * running. * * @todo check using the process_id to see if the process is still active * * @return <type> */ protected function _isRunning(){ return (bool)$this->find( 'count', array( 'conditions' => array( $this->alias . '.done' => 0 ) ) ); } /** * @brief check if enough time has elapsed since the last run * * the query checks if there are any jobs between the desired date and the * last run. If there are that means there was a job that ran more recently * than the time span required. * * @param string $date the datetime since the last cron should have run * * @return bool are there jobs recently */ public function countJobsAfter($date){ $data = $this->find( 'count', array( 'conditions' => array( 'Cron.created > ' => $date ) ) ); return $data; } /** * @brief get the last run job * * This gets the last time a cron ran, and can be used for checking if * the crons are setup or if they are running. * * @return string|bool false if not running, or datetime string of last run */ public function getLastRun(){ $last = $this->find( 'first', array( 'fields' => array( $this->alias . '.id', 'created' ), 'order' => array( 'created' => 'desc' ) ) ); return isset($last['Cron']['created']) && !empty($last['Cron']['created']) ? $last['Cron']['created'] : false; } /** * @brief clear out old data * * This method is used to clear out old data, normally it is called via * crons to happen automatically, but could be used in other places. */ public function clearOldLogs($date = null){ if(!$date){ $date = Configure::read('Cron.clear_logs'); } $date = date('Y-m-d H:i:s', strtotime('- ' . $date)); return $this->deleteAll( array( 'Cron.created <= ' => $date ), false ); } }<file_sep><?php class ConfigsEventsTestCase extends CakeTestCase { var $fixturesasd = array( 'plugin.configs.config', 'plugin.themes.theme', 'plugin.routes.route', 'plugin.view_counter.view_count', 'plugin.categories.category', 'plugin.users.group', ); public function startTest() { $this->Event = EventCore::getInstance(); } public function endTest() { unset($this->Event); ClassRegistry::flush(); } public function testGenerateSiteMapData(){ $this->assertIsA($this->Event, 'EventCore'); } }<file_sep><?php class EmailAttachmentsHelper extends AppHelper{ public $helpers = array( 'Text', 'Html', 'Events.Event' ); public function outputBody($mail){ $_url = $this->Event->trigger('emails.slugUrl', array('type' => 'mail', 'data' => $mail)); return '<iframe src="' . Router::url(current($_url['slugUrl'])) . '" height="100%" width="100%"></iframe>'; } /** * generate an attachment icon for emails with an attachment * * @param mixed true to show, mail array to check * @return mixed false or html for attachment icon */ public function hasAttachment($mail = array(), $small = true){ if((isset($mail['attachments']) && $mail['attachments']) || $mail === true){ $size = $small === true ? 16 : 24; return $this->Html->image( '/newsletter/img/attachment.png', array( 'alt' => __('Attachment', true), 'height' => $size.'px', 'width' => $size.'px', 'title' => __('This email has attachments', true) ) ); } return false; } /** * generate an icon for emails that are flagged * * @param mixed true to show, mail array to check * @return mixed false or html for attachment icon */ public function isFlagged($mail = array(), $image = '/newsletter/img/flagged.png', $small = true){ $title = __('Flagged :: This email has been flagged', true); $alt = __('Flagged', true); if((isset($mail['flagged']) && (bool)$mail['flagged'] === false) || $mail === false){ $image = '/newsletter/img/flagged-not.png'; $title = __('Not Flagged :: Flag this email', true); $alt = __('Not Flagged', true); } $size = $small === true ? 16 : 24; return $this->Html->image( $image, array( 'alt' => $alt, 'height' => $size.'px', 'width' => $size.'px', 'title' => $title ) ); } /** * * @param <type> $attachments * @return string html block of attachments */ public function listAttachments($attachments = array()){ if(empty($attachments) || !is_array($attachments)){ return false; } $return = array(); foreach($attachments as $attachment){ switch($attachment['type']){ case 'jpeg': case 'gif': $data = $this->__imageAttachment($attachment); break; case 'msword': case 'pdf': $data = $this->__fileAttachment($attachment); break; default: pr($attachment); exit; break; } $return[] = $this->__addAttachment($attachment, $data); } if(!empty($return)){ return sprintf('<ul class="attachments"><li>%s</li></ul>', implode('</li><li>', $return)); } return false; } private function __addAttachment($attachment, $data){ return sprintf('<h4>%s</h4>%s', $attachment['name'], $data); } /** * Show an image attachment * @param <type> $attachment */ private function __imageAttachment($attachment){ return $this->Html->link( $this->Html->image( $attachment['versions']['thumbnail'], array( 'alt' => $attachment['filename'], 'title' => sprintf('%s (%s)', $attachment['filename'], $attachment['size']) ) ), Router::url($attachment['versions']['large']), array( 'escape' => false, 'class' => 'thickbox' ) ); } /** * Show a file attachment * @param <type> $attachment */ private function __fileAttachment($attachment){ return $this->Html->link( sprintf('%s (%s)', $this->Text->truncate($attachment['filename'], 50), convert($attachment['size'])), $attachment['download_url'] ); } }<file_sep><?php class TrashAppModel extends CoreAppModel{ }<file_sep><?php /** * Custom bake view add / edit * * creates a custom views for infinitas. * * Copyright (c) 2009 <NAME> ( dogmatic69 ) * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. * * @filesource * @copyright Copyright (c) 2009 <NAME> ( dogmatic69 ) * @link http://infinitas-cms.org * @package Shell * @subpackage Shell.templates.views.index * @license http://www.opensource.org/licenses/mit-license.php The MIT License * * availabel vars * =================== [directory] => views [filename] => form [vars] => [themePath] => c:\xampp\htdocs\thinkmoney\vendors\shells\templates\infinitas\ [templateFile] => c:\xampp\htdocs\thinkmoney\vendors\shells\templates\infinitas\views\form.ctp [action] => admin_add [plugin] => compare [modelClass] => Supplier [schema] => Array [primaryKey] => id [displayField] => name [singularVar] => supplier [pluralVar] => suppliers [singularHumanName] => Supplier [pluralHumanName] => Suppliers [fields] => Array [associations] => array */ $ignore = array( $primaryKey, 'locked', 'locked_by', 'locked_since', 'deleted_date', 'created', 'modified', 'updated', 'active', 'deleted' ); $configs = array( 'active' ); echo "<?php\n". "\t/**\n". "\t * $modelClass view/edit\n". "\t *\n". "\t * Add some documentation for $modelClass.\n". "\t *\n". "\t * Copyright (c) {yourName}\n". "\t *\n". "\t * Licensed under The MIT License\n". "\t * Redistributions of files must retain the above copyright notice.\n". "\t *\n". "\t * @filesource\n". "\t * @copyright Copyright (c) 2009 {yourName}\n". "\t * @link http://infinitas-cms.org\n". "\t * @package $modelClass\n". "\t * @subpackage $modelClass.views.$pluralVar.index\n". "\t * @license http://www.opensource.org/licenses/mit-license.php The MIT License\n". "\t */\n\n"; $possibleFileFields = array('file', 'image'); $fileUpload = ''; foreach ($fields as $field) { if (in_array($field, $possibleFileFields)) { $fileUpload = ", array('type' => 'file')"; } } echo "\techo \$this->Form->create('{$modelClass}'{$fileUpload});\n". "\t\techo \$this->Infinitas->adminEditHead(\$this);\n"; echo "\t\t\t<div class=\"data\">\n"; echo "\t\t\t\t<?php\n"; echo "\t\t\t\t\techo \$this->Form->input('$primaryKey');\n"; $end = ''; foreach ($fields as $field) { if (!empty($associations['belongsTo'])) { foreach ($associations['belongsTo'] as $alias => $details) { if ($field === $details['foreignKey']) { if (in_array($field, array('locked_by'))) { continue; } $configs[] = $field; continue; } } } if (!in_array($field, $ignore) && (str_replace('_count', '', $field) == $field)) { switch($schema[$field]['type']){ case 'text': $end .= "\t\t\t\t\techo \$this->".ucfirst($plugin)."->wysiwyg('{$modelClass}.{$field}');\n"; break; case $displayField == $field: echo "\t\t\t\t\techo \$this->Form->input('{$field}', array('class' => 'title'));\n"; break; case in_array($field, $possibleFileFields): echo "\t\t\t\t\techo \$this->Form->input('{$field}'{$fileUpload});\n"; break; default: echo "\t\t\t\t\techo \$this->Form->input('{$field}');\n"; break; } // switch } } echo $end; echo "\t\t\t\t?>\n"; echo "\t\t\t</div>\n\n"; echo "\t\t\t<div class=\"config\">\n"; echo "\t\t\t\t<?php\n"; echo "\t\t\t\t\t\t?><h2><?php __('Configuration'); ?></h2><?php\n"; foreach ($fields as $field) { if (in_array($field, $configs)) { echo "\t\t\t\t\t\techo \$this->Form->input('{$field}');\n"; } } if (!empty($associations['hasAndBelongsToMany'])) { foreach ($associations['hasAndBelongsToMany'] as $assocName => $assocData) { echo "\t\t\t\t\t\techo \$this->Form->input('{$assocName}');\n"; } } echo "\t\t\t\t?>\n"; echo "\t\t\t</div><?php\n"; echo "\techo \$this->Form->end();\n"; echo "?>\n"; ?><file_sep><?php class CronLockTask extends Shell { public $uses = array( 'Crons.Cron' ); /** * @property Cron */ public $Cron; /** * @brief This method checks if there is a cron already running befor starting a new one * * If there is already a cron running this method will prevent the cron * from continuing. If It has been a long time since the cron has run * it will send an email to alert the admin that there is a problem. * * @todo should see if there is a way to kill the process for self maintanence. */ public function start(){ return $this->Cron->start(); } public function end($tasksRan = 0, $memAverage = 0, $loadAverage = 0){ return $this->Cron->end($tasksRan, $memAverage, $loadAverage); } /** * @brief check if its time to do a run * * Make sure that enough time has passed since the last cron before running * the next one. This has nothing to do with if the cron is already * running and is only a tiny request if it fails. * * @return bool true if time has passed, false if time has not passed */ public function checkTimePassed(){ $date = strtotime('-' . Configure::read('Cron.run_every')); return !(bool)$this->Cron->countJobsAfter(date('Y-m-d H:i:s', $date)); } } <file_sep><?php /* User Test cases generated on: 2010-03-11 18:03:16 : 1268325136*/ App::import('Model', 'Users.User'); App::import('Security'); /** * * */ class UserTest extends User{ public $useDbConfig = 'test'; public $belongsTo = array(); public $actsAs = array(); public $data; } class UserTestCase extends CakeTestCase { public $fixtures = array( 'plugin.users.user' ); public function startTest() { $this->User =& new UserTest(); } /** * Test the validation methods */ public function testValidationRules(){ // fake the submision $this->data['User']['password'] = '<PASSWORD>'; $this->data['User']['email'] = '<EMAIL>'; $this->User->set($this->data['User']); // pw should match $field['confirm_password'] = '<PASSWORD>'; $this->assertTrue($this->User->matchPassword($field)); // pw does not match $field['confirm_password'] = '<PASSWORD>'; $this->assertFalse($this->User->matchPassword($field)); // pw regex simple Configure::write('Website.password_regex', '[a-z]'); $field['confirm_password'] = '<PASSWORD>'; $this->assertTrue($this->User->validPassword($field)); $field['confirm_password'] = '�^%&^%*^&�$%�'; $this->assertFalse($this->User->validPassword($field)); // pw regex advanced Configure::write('Website.password_regex', '^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?!.*\s).{4,8}$'); $field['confirm_password'] = '<PASSWORD>'; $this->assertTrue($this->User->validPassword($field)); $field['confirm_password'] = '<PASSWORD>'; $this->assertFalse($this->User->validPassword($field)); // email should match $field['confirm_email'] = $this->data['User']['email']; $this->assertTrue($this->User->matchEmail($field)); // email should fail $field['confirm_email'] = '<EMAIL>'; $this->assertFalse($this->User->matchEmail($field)); } /** * Test the other methods */ public function testMethods(){ $expected['User'] = array( 'ip_address' => '127.0.0.1', 'last_login' => '2010-08-16 10:49:19', 'country' => 'Unknown', 'city' => '', ); $this->assertEqual($expected, $this->User->getLastLogon(1)); } public function endTest() { unset($this->User); ClassRegistry::flush(); } }<file_sep><div class="dashboard"> <h1><?php __('Missing Helper File'); ?></h1> <p class="error"> <strong><?php __('Error'); ?>: </strong> <?php printf(__('The helper file %s can not be found or does not exist.', true), APP_DIR . DS . 'views' . DS . 'helpers' . DS . $file); ?> </p> <p class="error"> <strong><?php __('Error'); ?>: </strong> <?php printf(__('Create the class below in file: %s', true), APP_DIR . DS . 'views' . DS . 'helpers' . DS . $file); ?> </p> <pre> &lt;?php class <?php echo $helperClass;?> extends AppHelper { } ?&gt; </pre> </div><file_sep><?php echo $this->element('modules/admin/current', array('current' => $current, 'plugin' => 'server_status')); echo $this->element('modules/admin/all_time', array('allTime' => $allTime, 'plugin' => 'server_status')); echo $this->element('modules/admin/last_two_weeks', array('lastTwoWeeks' => $lastTwoWeeks, 'plugin' => 'server_status')); echo $this->element('modules/admin/last_six_months', array('lastSixMonths' => $lastSixMonths, 'plugin' => 'server_status')); echo $this->element('modules/admin/by_hour', array('byHour' => $byHour, 'plugin' => 'server_status')); echo $this->element('modules/admin/by_day', array('byDay' => $byDay, 'plugin' => 'server_status'));<file_sep><?php /* SVN FILE: $Id$ */ /* Filter schema generated on: 2010-09-18 18:09:20 : 1284828620*/ class FilterSchema extends CakeSchema { var $name = 'Filter'; function before($event = array()) { return true; } function after($event = array()) { } } ?><file_sep><?php /** * * */ class Relation extends ManagementAppModel{ var $name = 'Relation'; var $tablePrefix = 'relation_'; var $belongsTo = array( //'Management.RelationType' ); function getRelations($bind = true){ $return = $this->find( 'all', array( 'fields' => array( ), 'contain' => array( 'RelationType' ) ) ); pr( $return ); exit; } }<file_sep><?php /* * Short Description / title. * * Overview of what the file does. About a paragraph or two * * Copyright (c) 2010 <NAME> ( dogmatic69 ) * * @filesource * @copyright Copyright (c) 2010 <NAME> ( dogmatic69 ) * @link http://www.infinitas-cms.org * @package {see_below} * @subpackage {see_below} * @license http://www.opensource.org/licenses/mit-license.php The MIT License * @since {check_current_milestone_in_lighthouse} * * @author {your_name} * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. */ $config['Webmaster'] = array( 'last_modified' => '-2 weeks', // default time ago that things were changed 'change_frequency' => 'monthly', // never, yearly, monthly, daily, hourly, always 'priority' => 0.5 // 0 -> 1 );<file_sep><?php /* Commentable Test cases generated on: 2010-12-14 02:12:04 : 1292295484*/ App::import('behavior', 'Comments.Commentable'); class CommentableBehaviorTestCase extends CakeTestCase { function startTest() { $this->Commentable = new CommentableBehavior(); } function endTest() { unset($this->Commentable); ClassRegistry::flush(); } }<file_sep><div class="dashboard"> <h1><?php echo __('Update your site', true); ?></h1> </div><file_sep><?php /* Charts Test cases generated on: 2010-12-14 01:12:17 : 1292291837*/ App::import('helper', 'charts.Charts'); class ChartshelperTestCase extends CakeTestCase { function startTest() { $this->Charts = new ChartsHelper(); } function endTest() { unset($this->Charts); ClassRegistry::flush(); } }<file_sep><?php /** * Users controller * * This is for the management of users. * * Copyright (c) 2010 <NAME> ( dogmatic69 ) * * @filesource * @copyright Copyright (c) 2010 <NAME> ( dogmatic69 ) * @link http://www.infinitas-cms.org * @package management * @subpackage management.controllers.users * @license http://www.opensource.org/licenses/mit-license.php The MIT License * @since 0.7alpha * * @author <NAME> (dogmatic69) * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. */ class UsersController extends UsersAppController{ public $name = 'Users'; public function beforeFilter(){ parent::beforeFilter(); $this->Auth->allow( 'login', 'logout', 'register', 'forgot_password', 'reset_password' ); } public function view(){ if(!$this->Session->read('Auth.User.id')){ $this->Session->setFlash(__('You must be logged in to view your profile', true)); $this->redirect(array('action' => 'login')); } $user = $this->User->find( 'first', array( 'conditions' => array( 'User.id' => $this->Session->read('Auth.User.id') ) ) ); if(empty($user)){ $this->Session->setFlash(__('Please login to view your profile', true)); $this->redirect(array('action' => 'login')); } $this->set(compact('user')); } /** * Login method. * * Cake magic * * @access public */ public function login(){ if (!Configure::read('Website.allow_login')) { $this->Session->setFlash(__('Login is disabled', true)); $this->redirect('/'); } $this->_createCookie(); if(!(empty($this->data)) && $this->Auth->user()){ $this->User->recursive = -1; $lastLogon = $this->User->getLastLogon($this->Auth->user('id')); $data = $this->_getUserData(); if ($this->User->save($data)) { $currentUser = $this->Session->read('Auth.User'); // there is something wrong if ($lastLogon === false) { $this->redirect('/logout'); } $this->Session->write('Auth.User', array_merge($data['User'], $currentUser)); $this->Session->setFlash( sprintf( __('Welcome back %s, your last login was from %s, %s on %s. (%s)', true), $currentUser['username'], $lastLogon['User']['country'], $lastLogon['User']['city'], $lastLogon['User']['last_login'], $lastLogon['User']['ip_address'] ) ); } $this->Event->trigger('userLogin', $currentUser); unset($lastLogon, $data); $this->redirect($this->Auth->redirect()); } if (!(empty($this->data)) && !$this->Auth->user()) { $this->Infinitas->badLoginAttempt($this->data['User']); } } /** * get some info about the user when they log in * * @return array */ public function _getUserData(){ $data['User']['id'] = $this->Auth->user('id'); $data['User']['last_login'] = date('Y-m-d H:i:s'); $data['User']['modified'] = false; $data['User']['browser'] = $this->Infinitas->getBrowser(); $data['User']['operating_system'] = $this->Infinitas->getOperatingSystem(); //$data['User'] = array_merge($data['User'], $this->Session->read('GeoLocation')); $data['User']['is_mobile'] = $this->RequestHandler->isMobile(); $location = $this->Event->trigger('getLocation'); $data['User'] = array_merge($data['User'], current($location['getLocation'])); return $data; } /** * Check if there is a cookie to log the user in with */ public function _checkCookie(){ if (!empty($this->data)) { $cookie = $this->Cookie->read('Auth.User'); if (!is_null($cookie)) { if ($this->Auth->login($cookie)) { $this->Session->del('Message.auth'); } } } } /** * Create a remember me cookie */ public function _createCookie(){ if ($this->Auth->user()) { if (!empty($this->data['User']['remember_me'])) { $cookie = array(); $cookie['username'] = $this->data['User']['username']; $cookie['password'] = $this-><PASSWORD>['<PASSWORD>']['<PASSWORD>']; $this->Cookie->write('Auth.User', $cookie, true, '+2 weeks'); unset($this->data['User']['remember_me']); } } } /** * Logout method. * * Cake magic * * @access public */ public function logout(){ $this->Event->trigger('beforeUserLogout', array('user' => $this->Session->read('Auth.User'))); //@todo if this is false dont logout. $this->Session->destroy(); $this->Event->trigger('afterUserLogout'); $this->redirect($this->Auth->logout()); } /** * register a new user * * Only works when you have allowed registrations. When the email validation * is on the user will be sent an email to confirm the registration */ public function register(){ if (!Configure::read('Website.allow_registration')) { $this->Session->setFlash(__('Registration is disabled', true)); $this->redirect('/'); } if (!empty($this->data)) { $this->data['User']['active'] = 1; if (Configure::read('Website.email_validation') === true) { $this->data['User']['active'] = 0; } $this->data['User']['group_id'] = 2; $this->User->create(); if ($this->User->saveAll($this->data)) { if (!$this->data['User']['active']) { $ticket = $this->User->createTicket($this->User->id); $urlToActivateUser = ClassRegistry::init('ShortUrlsShortUrl')->newUrl( Router::url(array('action' => 'activate', $ticket), true) ); $this->Emailer->sendDirectMail( array( $this->data['User']['email'] ), array( 'subject' => Configure::read('Website.name').' '.__('Confirm your registration', true), 'body' => $urlToActivateUser, 'template' => 'User - Activate' ) ); } else{ $this->Emailer->sendDirectMail( array( $this->data['User']['email'] ), array( 'subject' => __('Welcome to ', true).' '.Configure::read('Website.name'), 'body' => '', 'template' => 'User - Registration' ) ); } if (Configure::read('Website.email_validation') === true) { $this->Session->setFlash(__('Thank you, please check your email to complete your registration', true)); } else{ $this->Session->setFlash(__('Thank you, your registration was completed', true)); } $this->redirect('/'); } } } /** * Activate a registration * * When this was set in registration the user needs to click the link * from an email. the code is then checked and if found it will activate * that user. aims to stop spam * * @param string $hash */ public function activate($hash = null){ if (!$hash){ $this->Session->setFlash(__('Invalid address', true)); $this->redirect('/'); } $this->User->id = $this->User->getTicket($hash); if ($this->User->saveField('active', 1, null, true)){ $user = $this->User->read('email', $this->User->id); $this->Emailer->sendDirectMail( array( $user['User']['email'] ), array( 'subject' => __('Welcome to ', true).' '.Configure::read('Website.name'), 'body' => '', 'template' => 'User - Registration' ) ); $this->Session->setFlash(__('Your account is now active, you may log in', true)); $this->redirect(array('action' => 'login')); } else{ $this->Session->setFlash('There was a problem activating your account, please try again'); $this->redirect('/'); } } /** * If the user has forgotten the pw they can reset it using this form. * An email will be sent if they supply the correct details which they * will need to click the link to be taken to the reset page. */ public function forgot_password(){ if (!empty($this->data)){ $theUser = $this->User->find( 'first', array( 'conditions' => array( 'User.email' => $this->data['User']['email'] ) ) ); if (is_array( $theUser['User']) && ($ticket = $this->User->createTicket($theUser['User']['email']) !== false)){ $urlToRessetPassword = ClassRegistry::init('ShortUrls.ShortUrl')->newUrl( Router::url(array('action' => 'reset_password', $ticket), true) ); // @todo send a email with a link to reset. $this->Session->setFlash(__('An email has been sent to your address with instructions to reset your password', true)); } else{ // no user found for adress $this->Session->setFlash(__('That does not seem to be a valid user', true)); } } } /** * After the forgot pw page and they have entered the correct details * they will recive an email with a link to this page. they can then * enter a new pw and it will be reset. * * @param string $hash the hash of the reset request. */ public function reset_password($hash = null){ if (!$hash){ $this->Session->setFlash(__('Reset request timed out, please try again', true)); $this->redirect('/'); } if (!empty($this->data)){ $this->User->id = $this->data['User']['id']; if ( $this->User->saveField('password', Security::hash($this->data['User']['new_password'], null, true))){ $this->Session->setFlash(__('Your new password was saved. You may now login', true)); $this->redirect(array('action' => 'login')); } else{ $this->Session->setFlash('User could not be saved'); $this->redirect(array('action' => 'forgot_password')); } } $email = $this->User->getTicket($hash); if (!$email){ $this->Session->setFlash(__('Your ticket has expired, please request a new password', true)); $this->redirect(array('action' => 'forgot_password')); } $this->data = $this->User->find( 'first', array( 'conditions' => array( 'User.email' => $email ) ) ); } public function admin_login(){ $this->layout = 'admin_login'; $this->_createCookie(); if(!(empty($this->data)) && $this->Auth->user()){ $lastLogon = $this->User->getLastLogon($this->Auth->user('id')); $data = $this->_getUserData(); if ($this->User->save($data)) { $currentUser = $this->Session->read('Auth.User'); // there is something wrong if ($lastLogon === false) { $this->redirect('/logout'); } $this->Session->write('Auth.User', array_merge($data['User'], $currentUser)); $this->notice( sprintf( __('Welcome back %s, your last login was from %s, %s on %s. (%s)', true), $currentUser['username'], $lastLogon['User']['country'], $lastLogon['User']['city'], $lastLogon['User']['last_login'], $lastLogon['User']['ip_address'] ) ); } $this->redirect($this->Auth->redirect()); } if(!empty($this->data) && !$this->Auth->user()){ unset($this->data['User']['password']); } } public function admin_logout(){ $this->Session->destroy(); $this->redirect($this->Auth->logout()); } public function admin_dashboard(){ } public function admin_index(){ $this->User->recursive = 0; $users = $this->paginate(null, $this->Filter->filter); $filterOptions = $this->Filter->filterOptions; $filterOptions['fields'] = array( 'name', 'email', 'group_id' => $this->User->Group->find('list'), 'active' => Configure::read('CORE.active_options') ); $this->set(compact('users','filterOptions')); } public function admin_logged_in(){ $this->paginate =array( 'conditions' => array( 'User.last_login > ' => date('Y-m-d H:i:s', strtotime('-30 min')) ), 'order' => array( 'User.last_login' => 'desc' ) ); $users = $this->paginate(null, $this->Filter->filter); $filterOptions = $this->Filter->filterOptions; $filterOptions['fields'] = array( 'name', 'email' ); $this->set(compact('users','filterOptions')); $this->render('admin_index'); } public function admin_add(){ parent::admin_add(); $groups = $this->User->Group->find('list'); $this->set(compact('groups')); } public function admin_edit($id = null) { if (!$id) { $this->Infinitas->noticeInvalidRecord(); } if (!empty($this->data)) { if ($this->data['User']['password'] == Security::hash('', null, true)) { unset($this->data['User']['password']); unset($this->data['User']['confirm_password']); } if ($this->User->saveAll($this->data)) { $this->Infinitas->noticeSaved(); } $this->Infinitas->noticeNotSaved(); } if ($id && empty($this->data)) { $this->data = $this->User->read(null, $id); } $groups = $this->User->Group->find('list'); $this->set(compact('groups')); } /** * for acl, should be removed. */ public function admin_initDB() { $group =& $this->User->Group; //Allow admins to everything $group->id = 1; $this->Acl->allow($group, 'controllers'); //allow managers to posts and widgets $group->id = 2; //$this->Acl->deny($group, 'controllers'); } }<file_sep><?php /** * This is core configuration file. * * Used to configure some base settings and load configs from all the plugins in the app. */ if(env('SERVER_ADDR') == '127.0.0.1'){ Configure::write('debug', 2); } else{ Configure::write('debug', 0); } Configure::write('log', true); /** * @brief Error logging level * * Same as the debug level, but will send errors to a file. Good to see * what is going on when the site's debug is off. */ define('LOG_ERROR', 2); if(phpversion() >= 5.3){ date_default_timezone_set(date_default_timezone_get()); } /** * if debug is off check for view file cache */ if(Configure::read('debug') == 0){ Configure::write('Cache.check', true); } /** * Cache configuration. * * Try apc or memcache, default to the namespaceFile cache. */ $cacheEngine = 'File'; switch(true){ case function_exists('apc_cache_info'): $cacheEngine = 'Apc'; break; case function_exists('xcache_info'): $cacheEngine = 'Xcache'; break; case class_exists('Memcache'): $cacheEngine = 'Memcache'; break; default: $cacheEngine = 'Libs.NamespaceFile'; break; } Configure::write('Cache.engine', $cacheEngine); /** * @todo when this is set to $cacheEngine the developer plugin is gone */ Cache::config('_cake_core_', array('engine' => 'File')); Cache::config('default', array('engine' => $cacheEngine, 'prefix' => 'infinitas_')); unset($cacheEngine); App::build(array('plugins' => array(APP . 'core' . DS))); /** * @brief get the configuration values from cache * * If they are available, set them to the Configure object else run the * Event to get the values from all the plugins and cache them */ $cachedConfigs = Cache::read('global_configs'); if($cachedConfigs !== false){ foreach($cachedConfigs as $k => $v){ Configure::write($k, $v); } unset($cachedConfigs); return true; } /** * Load plugin events */ if(!App::import('Libs', 'Events.Events')){ trigger_error('Could not load the Events Class', E_USER_ERROR); } EventCore::getInstance(); EventCore::trigger(new StdClass(), 'setupConfig'); //no home Configure::write('Rating.require_auth', true); Configure::write('Rating.time_limit', '4 weeks'); Configure::write('Reviews.auto_moderate', true); Cache::write('global_configs', Configure::getInstance());<file_sep><?php /** * The helper definition for the Script Combiner helper. * @author <NAME> * @version 0.1 * * @property JavascriptHelper $Javascript */ class CompressHelper extends Helper { /** * Array containing additional helpers to be used in this helper. * * @access public * @var array */ public $helpers = array('Html', 'Javascript'); /** * @property HtmlHelper */ public $Html; /** * The directory to which the combined CSS files will be cached. * * @access private * @var string */ private $cssCachePath; /** * The directory to which the combined Javascript files will be cached. * * @access private * @var string */ private $jsCachePath; /** * Indicates the time of expiry for the combined files. * @access private * @var int */ private $cacheLength; /** * Indicates whether the class is active and is able to begin combining scripts. * @access private * @var bool */ private $enabled = false; /** * Sets up the helper's properties, and determines whether the helper's environment * is set up and ready to be used. * * @access public * * @return void */ public function __construct() { parent::__construct(); $this->cssCachePath = CSS; $this->jsCachePath = JS; $cacheLength = Configure::read('ScriptCombiner.cacheLength'); if (is_string($cacheLength)) { $this->cacheLength = strtotime($cacheLength) - time(); } else { $this->cacheLength = (int)$cacheLength; } if(Configure::read('debug') != 2){ $this->enabled = true; } } /** * Receives numerous CSS files, and combines all the supplied CSS files into one * file, which helps in reducing the number of HTTP requests needed to load numerous * CSS files. * * Files to be combined should be supplied exactly as if they were being used in * the HtmlHelper::css() method, as this method is used to generate the paths * to the files. * * @param mixed [$url1,$url2,...] Either an array of files to combine, or multiple arguments of filenames. * @access public * * @return string The HTML &lt;link /&gt; to either the combined file, or to the multiple CSS files if the combined file could not be cached. */ public function css() { $cssFiles = func_get_args(); if (empty($cssFiles)) { return ''; } // Whoops. No configuration options defined, or something else went wrong // in trying to set up the class. Either way, we can't process the files, // so we'll need to handle this through the parent. if (!$this->enabled) { return $this->Html->css($cssFiles); } // Let's generate the cache hash, and ensure we have all the files that // we are going to use to process. if (is_array($cssFiles[0])) { $cssFiles = $cssFiles[0]; } $cacheKey = md5(serialize($cssFiles)); // Let's generate the path to the cache file. $cacheFile = $this->cssCachePath . 'combined.' . $cacheKey . '.css'; $this->File = new File($cacheFile); // Oh. Look. It appears we already have a cached version of the combined // file. This means we'll have to see when it last modified, and ensure // that the cached version hasn't yet expired. If it has, then we can // just return the URL to it straight away. if ($this->isCacheFileValid($cacheFile)) { $cacheFile = $this->convertToUrl($cacheFile); return $this->Html->css($cacheFile); } // Let's generate the HTML that would normally be returned, and strip // out the URLs. $cssData = $this->_getCssFiles($cssFiles); // If we can cache the file, then we can return the URL to the file. if ($this->File->write($cssData)) { return $this->Html->css($this->convertToUrl($cacheFile)); } // Otherwise, we'll have to trigger an error, and pass the handling of the // CSS files to the HTML Helper. trigger_error("Cannot combine CSS files to {$cacheFile}. Please ensure this directory is writable.", E_USER_WARNING); return $this->Html->css($cssFiles); } protected function _getCssFiles($cssFiles){ $urlMatches = $cssData = array(); $_setting = Configure::read('Asset.timestamp'); Configure::write('Asset.timestamp', false); $links = $this->Html->css($cssFiles, 'import'); Configure::write('Asset.timestamp', $_setting); preg_match_all('#\(([^\)]+)\)#i', $links, $urlMatches); $urlMatches = isset($urlMatches[1]) ? $urlMatches[1] : array(); $cssData = array(); foreach ($urlMatches as $urlMatch) { $cssPath = str_replace(array('/', '\\'), DS, WWW_ROOT . ltrim(Router::normalize($urlMatch), '/')); if (is_file($cssPath)) { $css = file_get_contents($cssPath); if(strstr($css, '../')){ $parts = explode('/', str_replace(APP . 'webroot' . DS, '', $cssPath)); $css = str_replace('../', '/' .$parts[0] . '/', $css); } $cssData[] = $css; unset($parts, $css); } } $cssData = implode(Configure::read('ScriptCombiner.fileSeparator'), $cssData); if (Configure::read('ScriptCombiner.compressCss')) { $cssData = $this->compressCss($cssData); } return $cssData; } public function script() { return call_user_func_array(array($this, 'js'), func_get_args()); } /** * Receives a number of Javascript files, and combines all of them together. * @param mixed [$url1,$url2,...] Either an array of files to combine, or multiple arguments of filenames. * @access public * * @return string The HTML &lt;script /&gt; to either the combined file, or to the multiple Javascript files if the combined file could not be cached. */ public function js() { // Get the javascript files. $jsFiles = func_get_args(); // Whoops. No files! We'll have to return an empty string then. if (empty($jsFiles)) { return ''; } // If the helper hasn't been set up correctly, then there's no point in // combining scripts. We'll pass it off to the parent to handle. if (!$this->enabled) { return $this->Javascript->link($jsFiles); } // Let's make sure we have the array of files correct. And we'll generate // a key for the cache based on the files supplied. if (is_array($jsFiles[0])) { $jsFiles = $jsFiles[0]; } $cacheKey = md5(serialize($jsFiles)); // And we'll generate the absolute path to the cache file. $cacheFile = $this->jsCachePath . 'combined.' . $cacheKey . '.js'; $this->File = new File($cacheFile); // If we can determine that the current cache file is still valid, then // we can just return the URL to that file. if ($this->isCacheFileValid($cacheFile)) { return $this->Javascript->link($this->convertToUrl($cacheFile)); } $jsData = $this->_getJsFiles($jsFiles); // If we can cache the file, then we can return the URL to the file. if ($this->File->write($jsData)) { return $this->Javascript->link($this->convertToUrl($cacheFile)); } // Otherwise, we'll have to trigger an error, and pass the handling of the // CSS files to the HTML Helper. trigger_error("Cannot combine Javascript files to {$cacheFile}. Please ensure this directory is writable.", E_USER_WARNING); return $this->Javascript->link($jsFiles); } protected function _getJsFiles($jsFiles){ $urlMatches = $jsData = array(); $_setting = Configure::read('Asset.timestamp'); Configure::write('Asset.timestamp', false); $jsLinks = $this->Javascript->link($jsFiles); Configure::write('Asset.timestamp', $_setting); preg_match_all('/src="([^"]+)"/i', $jsLinks, $urlMatches); $urlMatches = isset($urlMatches[1]) ? array_unique($urlMatches[1]) : array(); foreach ($urlMatches as $urlMatch) { $jsPath = str_replace(array('/', '\\'), DS, WWW_ROOT . ltrim(Router::normalize($urlMatch), '/')); if (is_file($jsPath)) { $jsData[] = file_get_contents($jsPath); } } $jsData = implode(Configure::read('ScriptCombiner.fileSeparator'), $jsData); if (Configure::read('ScriptCombiner.compressJs')) { $jsData = $this->compressJs($jsData); } $jsData = "/** \r\n * Files included \r\n * " . implode("\r\n * ", $urlMatches) . "\r\n */ \r\n" . $jsData; return $jsData; } /** * Indicates whether the supplied cached file's cache life has expired or not. * Returns a boolean value indicating this. * * @param string $cacheFile The path to the cached file to check. * @access private * * @return bool Flag indicating whether the file has expired or not. */ private function isCacheFileValid($cacheFile) { if (is_file($cacheFile) && $this->cacheLength > 0) { $lastModified = filemtime($cacheFile); $timeNow = time(); if (($timeNow - $lastModified) < $this->cacheLength) { return true; } } return false; } /** * Receives the path to a given file, and strips the webroot off the file, returning * a URL path that is relative to the webroot (WWW_ROOT). * * @param string $filePath The path to the file. * @access private * * @return string The path to the file, relative to WWW_ROOT (webroot). */ private function convertToUrl($filePath) { $___path = Set::filter(explode(DS, $filePath)); $___root = Set::filter(explode(DS, WWW_ROOT)); $webroot = array_diff_assoc($___root, $___path); $webrootPaths = array_diff_assoc($___path, $___root); return ('/' . implode('/', $webrootPaths)); } /** * Receives the CSS data to compress, and compresses it. Doesn't apply any encoding * to it (such as GZIP), but merely strips out unnecessary whitespace. * * @param string $cssData CSS data to be compressed. * @access private * @return string Compressed CSS data. */ private function compressCss($cssData) { // let's remove all the comments from the css code. $cssData = preg_replace('!/\*[^*]*\*+([^/][^*]*\*+)*/!', '', $cssData); // let's remove all tabs and line breaks. $cssData = str_replace(array("\r\n", "\r", "\n", "\t"), '', $cssData); // remove trailing semicolons just before closing brace. $cssData = preg_replace('/;\s*}/i', '}', $cssData); // remove any whitespace between element selector and opening brace. $cssData = preg_replace('/[\t\s]*{[\t\s]*/i', '{', $cssData); // remove whitespace between style declarations and their values. $cssData = preg_replace('/[\t\s]*:[\t\s]*/i', ':', $cssData); // remove whitespace between sizes and their measurements. $cssData = preg_replace('/(\d)[\s\t]+(em|px|%)/i', '$1$2', $cssData); // remove any spaces between background image "url" and the opening "(". $cssData = preg_replace('/url[\s\t]+\(/i', 'url(', $cssData); return $cssData; } /** * Compresses the supplied Javascript data, removing extra whitespaces, as well * as any comments found. * * @todo Implement reliable Javascript compression without use of a 3rd party. * * @param string $jsData The Javascript data to be compressed. * @access private * * @return string The compressed Javascript data. */ private function compressJs($jsData) { if (!class_exists('JSMin')) { App::import('Vendor', 'assets.js_min'); } if (!class_exists('JSMin')) { trigger_error('JavaScript not compressed -- cannot locate JSMin class.', E_USER_WARNING); return $jsData; } return JSMin::minify($jsData); } } <file_sep><?php /** * Show who locked what. * * Copyright (c) 2010 <NAME> ( dogmatic69 ) * * @filesource * @copyright Copyright (c) 2010 <NAME> ( dogmatic69 ) * @link http://www.infinitas-cms.org * @package Infinitas.locks * @subpackage Infinitas.locks.helpers.locked * @license http://www.opensource.org/licenses/mit-license.php The MIT License * @since 0.8a * * @author dogmatic69 * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. */ class LockedHelper extends InfinitasHelper{ public $helpers = array( 'Time', 'Html', 'Libs.Image' ); /** * Create a locked icon. * * takes the data from a find and shows if it is locked and if so who by * and when. * * @param array $row the row of data from the find * * @return sstring some html with the image */ public function display($row = array()){ if(!empty($row) && isset($row['Lock']['id']) && $row['Lock']['id'] > 0){ return $this->Html->image( $this->Image->getRelativePath('status', 'locked'), array( 'alt' => __('Locked', true), 'width' => '16px', 'title' => sprintf( __('Locked :: This record was locked %s by %s', true ), $this->Time->timeAgoInWords($row['Lock']['created']), $row['Lock']['Locker']['username'] ) ) ); } return $this->Html->image( $this->Image->getRelativePath('status', 'not-locked'), array( 'alt' => __('Not Locked', true), 'width' => '16px', 'title' => __('Unlocked :: This record is not locked', true) ) ); } }<file_sep><?php /** * The MenuItem model. * * The MenuItem model handles the items within a menu, these are the indervidual * links that are used to build up the menu required. * * Copyright (c) 2010 <NAME> ( dogmatic69 ) * * @filesource * @copyright Copyright (c) 2010 <NAME> ( dogmatic69 ) * @link http://www.infinitas-cms.org * @package Infinitas.Menus * @subpackage Infinitas.Menus.models.MenuItem * @license http://www.opensource.org/licenses/mit-license.php The MIT License * @since 0.8a * * @author dogmatic69 * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. */ class MenuItem extends MenusAppModel{ /** * The name of the class * * @var string * @access public */ public $name = 'MenuItem'; /** * The relations for menu items * @var array * @access public */ public $belongsTo = array( 'Menu' => array( 'className' => 'Menus.Menu', 'fields' => array( 'Menu.id', 'Menu.name', 'Menu.type', 'Menu.active', ) ), 'Group' => array( 'className' => 'Users.Group', 'fields' => array( 'Group.id', 'Group.name' ) ) ); /** * the default order of the menu items is set to lft as that is the only * way that MPTT records show the hierarchy * * @var array * @access public */ public $order = array( 'MenuItem.menu_id' => 'ASC', 'MenuItem.lft' => 'ASC' ); public function __construct($id = false, $table = null, $ds = null) { parent::__construct($id, $table, $ds); $this->validate = array( 'name' => array( 'notEmpty' => array( 'rule' => 'notEmpty', 'message' => __('Please enter the name of the menu item, this is what users will see', true) ) ), 'link' => array( 'validateEitherOr' => array( 'rule' => array('validateEitherOr', array('link', 'plugin')), 'message' => __('Please only use external link or the route', true) ), 'validUrl' => array( 'rule' => 'validateUrlOrAbsolute', 'message' => __('please use a valid url (absolute or full)', true) ) ), 'plugin' => array( 'validateOnlyOneFilledIn' => array( 'rule' => array('validateEitherOr', array('link', 'plugin')), 'message' => __('Please use the external link or the route', true) ) ), 'force_frontend' => array( 'validateNothingEitherOr' => array( 'rule' => 'validateNothingEitherOr', 'message' => __('You can only force one area of the site', true) ) ), 'force_backend' => array( 'validateNothingEitherOr' => array( 'rule' => 'validateNothingEitherOr', 'message' => __('You can only force one area of the site', true) ) ), 'group_id' => array( 'notEmpty' => array( 'rule' => 'notEmpty', 'message' => __('Please select the group that can see this link', true) ) ), 'params' => array( 'emptyOrJson' => array( 'rule' => 'validateEmptyOrJson', 'message' => __('Please enter some valid json or leave empty', true) ) ), 'class' => array( 'emptyOrValidCssClass' => array( 'rule' => 'validateEmptyOrCssClass', 'message' => __('Please enter valid css classes', true) ) ), 'menu_id' => array( 'notEmpty' => array( 'rule' => 'notEmpty', 'message' => __('Please select the menu this item belongs to', true) ) ), 'parent_id' => array( 'notEmpty' => array( 'rule' => 'notEmpty', 'message' => __('Please select where in the menu this item belongs', true) ) ) ); } /** * Empty string or valid css class * * @param array $field the field being validated * @access public * * @return bool is it valid? */ public function validateEmptyOrCssClass($field){ return strlen(current($field)) == 0 || preg_match('/-?[_a-zA-Z]+[_a-zA-Z0-9-]*/', current($field)); } /** * Set the parent_id for the menu item before saving so that the menu will * be within the correct menu item group. This only applies to the root * level menu items and not the sub items. * * @param bool $cascade not used * @access public * * @return the parent method */ public function beforeSave($cascade){ if($this->data['MenuItem']['parent_id'] == 0) { $menuItem = $this->find( 'first', array( 'fields' => array('id'), 'conditions' => array( 'parent_id' => 0, 'menu_id' => $this->data['MenuItem']['menu_id'] ) ) ); $this->data['MenuItem']['parent_id'] = $menuItem['MenuItem']['id']; } return parent::beforeSave($cascade); } /** * This will get an entire menu based on the type that is selected. The * data will be cached so further requests do not require access to the * database. * * @param string $type the menu that you want to pull * @access public * * @return array the menu items that belong to the type you asked for */ public function getMenu($type = null){ if (!$type) { return false; } $menus = Cache::read($type, 'menus'); if (!empty($menus)) { return $menus; } $menus = $this->find( 'threaded', array( 'fields' => array( 'MenuItem.id', 'MenuItem.name', 'MenuItem.link', 'MenuItem.prefix', 'MenuItem.plugin', 'MenuItem.controller', 'MenuItem.action', 'MenuItem.params', 'MenuItem.force_backend', 'MenuItem.force_frontend', 'MenuItem.class', 'MenuItem.active', 'MenuItem.menu_id', 'MenuItem.parent_id', 'MenuItem.lft', 'MenuItem.rght', 'MenuItem.group_id', ), 'conditions' => array( 'Menu.type' => $type, 'Menu.active' => 1, 'MenuItem.active' => 1, 'MenuItem.parent_id !=' => 0 ), 'contain' => array( 'Menu' ) ) ); Cache::write($type, $menus, 'menus'); return $menus; } /** * check if the menu being created has the menu_itmes container and if * not create one. Keeps the mptt structure together so that all the items * are withing a containing record. * * @param string $id the id of the menu * @param string $name the name of the menu * @access public * * @return bool if there is a container, or sone was created. */ public function hasContainer($id, $name){ $count = $this->find( 'count', array( 'conditions' => array( 'menu_id' => $id, 'parent_id' => 0 ) ) ); if($count > 0){ return true; } $data = array( 'MenuItem' => array( 'name' => $name, 'menu_id' => $this->id, 'parent_id' => 0, 'active' => 0, 'fake_item' => true ) ); $this->create(); return (bool)$this->save($data); } }<file_sep><?php /** * @brief Contact plugin events. * * The events for the Contact plugin for setting up cache and the general * configuration of the plugin. * * @copyright Copyright (c) 2010 <NAME> ( dogmatic69 ) * @link http://www.infinitas-cms.org * @package Infinitas.Contact * @license http://www.opensource.org/licenses/mit-license.php The MIT License * @since 0.7a * * @author dogmatic69 * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. */ final class ContactEvents extends AppEvents{ public function onAdminMenu($event){ $menu['main'] = array( 'Branches' => array('plugin' => 'contact', 'controller' => 'branches', 'action' => 'index'), 'Contacts' => array('plugin' => 'contact', 'controller' => 'contacts', 'action' => 'index') ); return $menu; } public function onRequireCssToLoad($event){ return array( '/contact/css/contact' ); } public function onSetupExtensions(){ return array( 'vcf' ); } public function onSiteMapRebuild($event){ $newest = ClassRegistry::init('Contact.Branch')->getNewestRow(); $frequency = ClassRegistry::init('Contact.Contact')->getChangeFrequency(); $return = array(); $return[] = array( 'url' => Router::url(array('plugin' => 'contact', 'controller' => 'branches', 'action' => 'index', 'admin' => false, 'prefix' => false), true), 'last_modified' => $newest, 'change_frequency' => $frequency ); $branches = ClassRegistry::init('Contact.Branch')->find('list'); foreach($branches as $branch){ $return[] = array( 'url' => Router::url(array('plugin' => 'contact', 'controller' => 'branches', 'action' => 'view', 'slug' => $branch, 'admin' => false, 'prefix' => false), true), 'last_modified' => $newest, 'change_frequency' => $frequency ); } return $return; } }<file_sep><?php /** * @brief Categories plugin events. * * The events for the Categories plugin for setting up cache and the general * configuration of the plugin. * * @copyright Copyright (c) 2010 <NAME> ( dogmatic69 ) * @link http://www.infinitas-cms.org * @package Infinitas.Categories * @license http://www.opensource.org/licenses/mit-license.php The MIT License * @since 0.8a * * @author dogmatic69 * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. */ final class CategoriesEvents extends AppEvents{ public function onAdminMenu($event){ $menu['main'] = array( 'Categories' => array('controller' => false, 'action' => false), 'Active' => array('controller' => 'categories', 'action' => 'index', 'Category.active' => 1), 'Disabled' => array('controller' => 'categories', 'action' => 'index', 'Category.active' => 0) ); return $menu; } public function onAttachBehaviors($event) { if(is_subclass_of($event->Handler, 'Model') && isset($event->Handler->_schema) && is_array($event->Handler->_schema)) { if (array_key_exists('category_id', $event->Handler->_schema) && !$event->Handler->Behaviors->enabled('Categories.Categorisable')) { $event->Handler->Behaviors->attach('Categories.Categorisable'); } } } public function onSiteMapRebuild($event){ $Category = ClassRegistry::init('Categories.Category'); $newest = $Category->getNewestRow(); $frequency = $Category->getChangeFrequency(); $return = array(); $return[] = array( 'url' => Router::url(array('plugin' => 'categories', 'controller' => 'categories', 'action' => 'index', 'admin' => false, 'prefix' => false), true), 'last_modified' => $newest, 'change_frequency' => $frequency ); $categories = $Category->find('list'); foreach($categories as $category){ $return[] = array( 'url' => Router::url(array('plugin' => 'categories', 'controller' => 'categories', 'action' => 'view', 'slug' => $category, 'admin' => false, 'prefix' => false), true), 'last_modified' => $newest, 'change_frequency' => $frequency ); } return $return; } }<file_sep><?php /* * Short Description / title. * * Overview of what the file does. About a paragraph or two * * Copyright (c) 2010 <NAME> ( dogmatic69 ) * * @filesource * @copyright Copyright (c) 2010 <NAME> ( dogmatic69 ) * @link http://www.infinitas-cms.org * @package {see_below} * @subpackage {see_below} * @license http://www.opensource.org/licenses/mit-license.php The MIT License * @since {check_current_milestone_in_lighthouse} * * @author {your_name} * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. */ class ModulePositionsController extends CoreAppController{ public $name = 'ModulePositions'; public function admin_index(){ $modules = $this->paginate(null, $this->Filter->filter); $filterOptions = $this->Filter->filterOptions; $filterOptions['fields'] = array( 'name' ); $modulePositions = $this->paginate(); $this->set(compact('modulePositions', 'filterOptions')); } }<file_sep><?php /* ContactContact Fixture generated on: 2010-08-17 14:08:06 : 1282055106 */ class ContactFixture extends CakeTestFixture { var $name = 'Contact'; var $table = 'contact_contacts'; var $fields = array( 'id' => array('type' => 'integer', 'null' => false, 'default' => NULL, 'length' => 10, 'key' => 'primary'), 'user_id' => array('type' => 'integer', 'null' => false, 'default' => NULL), 'image' => array('type' => 'string', 'null' => false, 'default' => NULL), 'first_name' => array('type' => 'string', 'null' => false, 'default' => NULL, 'length' => 50), 'last_name' => array('type' => 'string', 'null' => false, 'default' => NULL, 'length' => 100), 'slug' => array('type' => 'string', 'null' => false, 'default' => NULL), 'position' => array('type' => 'string', 'null' => true, 'default' => NULL, 'length' => 100), 'phone' => array('type' => 'string', 'null' => false, 'default' => NULL, 'length' => 20), 'mobile' => array('type' => 'string', 'null' => false, 'default' => NULL, 'length' => 20), 'email' => array('type' => 'string', 'null' => false, 'default' => NULL, 'length' => 100), 'skype' => array('type' => 'string', 'null' => true, 'default' => NULL, 'length' => 50), 'branch_id' => array('type' => 'integer', 'null' => false, 'default' => NULL), 'ordering' => array('type' => 'integer', 'null' => false, 'default' => NULL), 'configs' => array('type' => 'text', 'null' => false, 'default' => NULL), 'active' => array('type' => 'boolean', 'null' => false, 'default' => NULL), 'created' => array('type' => 'datetime', 'null' => true, 'default' => NULL), 'modified' => array('type' => 'datetime', 'null' => true, 'default' => NULL), 'indexes' => array('PRIMARY' => array('column' => 'id', 'unique' => 1)), 'tableParameters' => array('charset' => 'utf8', 'collate' => 'utf8_general_ci', 'engine' => 'InnoDB') ); var $records = array( array( 'id' => 1, 'user_id' => 0, 'image' => 'installer_home.png', 'first_name' => 'bob', 'last_name' => 'smith', 'slug' => '', 'position' => 'boss', 'phone' => '3216549875', 'mobile' => '', 'email' => '', 'skype' => 'bobSmith', 'branch_id' => 3, 'ordering' => 1, 'configs' => '', 'active' => 1, 'created' => '2010-02-18 08:21:41', 'modified' => '2010-02-18 08:21:41' ), array( 'id' => 2, 'user_id' => 0, 'image' => 'installer_home-0.png', 'first_name' => 'asdf', 'last_name' => 'asdf', 'slug' => '', 'position' => 'asdf', 'phone' => '3216549875', 'mobile' => '', 'email' => '', 'skype' => 'sdf', 'branch_id' => 3, 'ordering' => 2, 'configs' => '', 'active' => 1, 'created' => '2010-02-18 08:24:13', 'modified' => '2010-02-18 08:24:13' ), ); } ?><file_sep> <?php App::import('Model', 'Cms.Content'); class LockableContent extends CakeTestModel{ public $useDbConfig = 'test'; public $useTable = 'cms_content'; public $belongsTo = array(); public $hasOne = array(); public $actsAs = array( 'Libs.Lockable' ); } class LockableTestCase extends CakeTestCase { //need something to set with var $fixtures = array( 'plugin.categories.global_category', 'plugin.cms.content', 'plugin.management.ticket', 'plugin.management.group' ); function startTest() { $this->LockableContent = new LockableContent(); } function testLocking(){ $content = $this->LockableContent->find('first'); unset($content['LockableContent']['id']); unset($content['LockableContent']['locked']); unset($content['LockableContent']['locked_since']); unset($content['LockableContent']['locked_by']); unset($content['LockableContent']['views']); unset($content['LockableContent']['created']); unset($content['LockableContent']['modified']); $this->LockableContent->create(); $this->LockableContent->save($content); $new = $this->LockableContent->find('first', array('conditions' => array('LockableContent.id' => $this->LockableContent->id))); //$this->assertEqual(0, $new['LockableContent']['locked']); } function endTest() { unset($this->Infinitas); ClassRegistry::flush(); } }<file_sep><?php $map = array( 1 => array( '000008_locks' => 'R4c94edcd4f3c41b3b42b78d86318cd70'), ); ?><file_sep><?php /** * @mainpage Infinitas - CakePHP powered Content Management Framework * * @section infinitas-overview What is it * * Infinitas is a content management framework that allows you to create powerful * application using the CakePHP framework in the fastes way posible. It follows * the same convention over configuration design paradigm. All the coding standards * of CakePHP are followed, and the core libs are used as much as possible to * limit the amount of time that is required to get a hang of what is going on. * * Infinitas aims to take care of all the normal things that most sites require * so that you can spend time building the application instead. Things like * comments, users, auth, geo location, emailing and view counting is built into * the core. * * There is a powerful Event system that makes plugins truly seperate from * the core, so seperate that they can be disabled from the backend and its like * the plugin does not exist. * * The bulk of work that has been done to Infinitas has been to the admin * backend and internal libs. The final product is something that is extreamly * easy to extend, but also very usable. Knowing that one day you will need to * hand the project over to a client that may not be to technical has always been * one of the main considerations. * * Infinitas is here to bridge the gap between usablity and extendability offering * the best of both worlds, something that developers can build upon and end users * can actually use. * * @section categories-usage How to use it * * To get started check out the installation guide, currently there is only * a web based installer but shortly we will have some shell commands for * the people that are not fond of icons. * * You may also want to check the feature list and versions to get an overview * of what the project has to offer. */ /** * @page AppController AppController * * @section app_controller-overview What is it * * AppController is the main controller method that all other countrollers * should normally extend. This gives you a lot of power through inheritance * allowing things like mass deletion, copying, moving and editing with absolutly * no code. * * AppController also does a lot of basic configuration for the application * to run like automatically putting components in to load, compressing output * setting up some security and more. * * @section app_controller-usage How to use it * * Usage is simple, extend your MyPluginAppController from this class and then the * controllers in your plugin just extend MyPluginAppController. Example below: * * @code * // in APP/plugins/my_plugin/my_plugin_app_controller.php create * class MyPluginAppController extends AppModel{ * // do not set the name in this controller class, there be gremlins * } * * // then in APP/plugins/my_plugin/controllers/something.php * class SomethingsController extends MyPluginAppController{ * public $name = 'Somethings'; * //... * } * @endcode * * After that you will be able to directly access the public methods that * are available from this class as if they were in your controller. * * @code * $this->someMethod(); * @endcode * * @section app_controller-see-also Also see * @ref GlobalActions * @ref InfinitasComponent * @ref Event * @ref MassActionComponent * @ref InfinitasView */ /** * @brief AppController is the main controller class that all plugins should extend * * This class offers a lot of methods that should be inherited to other controllers * as it is what allows you to build plugins with minimal code. * * @copyright Copyright (c) 2009 <NAME> ( dogmatic69 ) * @link http://infinitas-cms.org * @package Infinitas * @license http://www.opensource.org/licenses/mit-license.php The MIT License * @since 0.5a * * @author dogmatic69 * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. */ class AppController extends GlobalActions { /** * class name * * @var string * @access public */ public $name = 'AppController'; /** * the View Class that will load by defaul is the Infinitas View to take * advantage which extends the ThemeView and auto loads the Mustache class. * This changes when requests are json etc */ public $view = 'Libs.Infinitas'; /** * not sure if this is still used * * @deprecated * @var array */ public $_helpers = array(); /** * internal cache of css files to load * * @var array * @access private */ private $__addCss = array(); /** * internal cache of javascript files to load * * @var array * @access private */ private $__addJs = array(); /** * @var AuthComponent * @access public */ public $Auth; /** * @var RequestHandlerComponent * @access public */ public $RequestHandler; /** * @var SessionComponent * @access public */ public $Session; /** * @var SecurityComponent * @access public */ public $Security; /** * The InfinitasComponent * * @var InfinitasComponent * @access public */ public $Infinitas; /** * @var MassActionComponent * @access public */ public $MassAction; /** * @brief called before a page is loaded * * before render is called before the page is rendered, but after all the * processing is done. * * @link http://api.cakephp.org/class/controller#method-ControllerbeforeRender * * @todo this could be moved to the InfinitasView class */ public function beforeRender(){ parent::beforeRender(); $this->Infinitas->getPluginAssets(); $this->set('css_for_layout', array_filter($this->__addCss)); $this->set('js_for_layout', array_filter($this->__addJs)); $fields = array( $this->params['plugin'], $this->params['controller'], $this->params['action'] ); $this->set('class_name_for_layout', implode(' ', $fields)); unset($fields); } /** * @brief redirect pages * * Redirect method, will remove the last_page session var that is stored * when adding/editing things in admin. makes redirect() default to /index * if there is no last page. * * @link http://api.cakephp.org/class/controller#method-Controllerredirect * * @param mixed $url string or array url * @param int $status the code for the redirect 301 / 302 etc * @param bool $exit should the script exit after the redirect * @access public * * @return void */ public function redirect($url = null, $status = null, $exit = true){ if(!$url || $url == ''){ $url = $this->Session->read('Infinitas.last_page'); $this->Session->delete('Infinitas.last_page'); if(!$url){ $url = array('action' => 'index'); } } parent::redirect($url, $status, $exit); } /** * @brief normal before filter. * * set up some variables and do a bit of pre processing before handing * over to the controller responsible for the request. * * @link http://api.cakephp.org/class/controller#method-ControllerbeforeFilter * * @access public * * @return void */ public function beforeFilter() { parent::beforeFilter(); // @todo it meio upload is updated. if(isset($this->data['Image']['image']['name']) && empty($this->data['Image']['image']['name'])){ unset($this->data['Image']); } $this->Infinitas->_setupAuth(); $this->Infinitas->_setupSecurity(); $this->Infinitas->_setupJavascript(); if((isset($this->params['admin']) && $this->params['admin']) && $this->params['action'] != 'admin_login' && $this->Session->read('Auth.User.group_id') != 1){ $this->redirect(array('admin' => 1, 'plugin' => 'users', 'controller' => 'users', 'action' => 'login')); } if (isset($this->data['PaginationOptions']['pagination_limit'])) { $this->Infinitas->changePaginationLimit( $this->data['PaginationOptions'], $this->params ); } if (isset($this->params['named']['limit'])) { $this->params['named']['limit'] = $this->Infinitas->paginationHardLimit($this->params['named']['limit']); } if(isset($this->params['form']['action']) && $this->params['form']['action'] == 'cancel'){ if(isset($this->{$this->modelClass}) && $this->{$this->modelClass}->hasField('locked') && isset($this->data[$this->modelClass]['id'])){ $this->{$this->modelClass}->unlock($this->data[$this->modelClass]['id']); } $this->redirect(array('action' => 'index')); } if (sizeof($this->uses) && (isset($this->{$this->modelClass}->Behaviors) && $this->{$this->modelClass}->Behaviors->attached('Logable'))) { $this->{$this->modelClass}->setUserData($this->Session->read('Auth')); } if(isset($this->RequestHandler)){ switch(true){ case $this->RequestHandler->prefers('json'): $this->view = 'Libs.Json'; Configure::write('debug', 0); break; case $this->RequestHandler->prefers('rss'): ; break; case $this->RequestHandler->prefers('vcf'): ; break; } // switch // $this->theme = null; } } /** * @brief add css from other controllers. * * way to inject css from plugins to the layout. call addCss(false) to * clear current stack, call addCss(true) to get a list back of what is there. * * @param mixed $css array of paths like HtmlHelper::css or a string path * @access public * * @return mixed bool for adding/removing or array when requesting data */ public function addCss($css = false){ return $this->__loadAsset($css, __FUNCTION__); } /** * @brief add js from other controllers. * * way to inject js from plugins to the layout. call addJs(false) to * clear current stack, call addJs(true) to get a list back of what is there. * * @param mixed $js array of paths like HtmlHelper::css or a string path * @access public * * @return mixed bool for adding/removing or array when requesting data */ public function addJs($js = false){ return $this->__loadAsset($js, __FUNCTION__); } /** * @brief DRY method for AppController::addCss() and AppController::addJs() * * loads the assets into a var that will be sent to the view, used by * addCss / addJs. if false is passed in the var is reset, if true is passed * in you get back what is currently set. * * @param mixed $data takes bool for reseting, strings and arrays for adding * @param string $method where its going to store / remove * @access private * * @return mixed true on success, arry if you pass true */ private function __loadAsset($data, $method){ $property = '__' . $method; if($data === false){ $this->{$property} = array(); return true; } else if($data === true){ return $this->{$property}; } foreach((array)$data as $_data){ if(is_array($_data)){ $this->{$method}($_data); continue; } if(!in_array($_data, $this->{$property}) && !empty($_data)){ $this->{$property}[] = $_data; } } return true; } /** * @brief render method * * Infinits uses this method to use admin_form.ctp for add and edit views * when there is no admin_add / admin_edit files available. * * @link http://api.cakephp.org/class/controller#method-Controllerrender * * @param string $action Action name to render * @param string $layout Layout to use * @param string $file File to use for rendering * @access public * * @return Full output string of view contents */ public function render($action = null, $layout = null, $file = null) { if(($this->action == 'admin_edit' || $this->action == 'admin_add')) { $viewPath = App::pluginPath($this->params['plugin']) . 'views' . DS . $this->viewPath . DS . $this->action . '.ctp'; if(!file_exists($viewPath)) { $action = 'admin_form'; } } else if(($this->action == 'edit' || $this->action == 'add')) { $viewPath = App::pluginPath($this->params['plugin']) . 'views' . DS . $this->viewPath . DS . $this->action . '.ctp'; if(!file_exists($viewPath)) { $action = 'form'; } } return parent::render($action, $layout, $file); } /** * @brief blackHole callback for security component * * this function is just here to stop wsod confusion. it will become more * usefull one day * * @todo maybe add some emailing in here to notify admin when requests are * being black holed. * * @link http://api.cakephp.org/view_source/security-component/#l-427 * * @param object $Controller the controller object that triggered the blackHole * @param string $error the error message * @access public * * @return it ends the script */ public function blackHole($Controller, $error){ pr('you been blackHoled'); pr($error); exit; } /** * @brief after all processing is done and the page is ready to show * * after filter is called after your html is put together, and just before * it is rendered to the user. here we are removing any white space from * the html before its output. * * @access public * * @link http://api.cakephp.org/class/controller#method-ControllerafterFilter */ public function afterFilter(){ if(Configure::read('debug') === 0){ $this->output = preg_replace( array( '/ {2,}/', '/<!--.*?-->|\t|(?:\r?\n[ \t]*)+/s' ), array( ' ', '' ), $this->output ); } } /** * @brief Create a generic warning to display usefull information to the user * * The code passed can be used for linking to error pages with more information * eg: creating some pages on your site like /errors/<code> and then making it * a clickable link the user can get more detailed information. * * @param string $message the message to show to the user * @param int $code a code that can link to help * @param string $level something like notice/warning/error * @param string $plugin if you would like to use your own elements pass the name of the plugin here * @access public * * @return string the markup for the error */ public function notice($message, $config = array()){ $_default = array( 'level' => 'success', 'code' => 0, 'plugin' => 'assets', 'redirect' => false ); $config = array_merge($_default, (array)$config); $vars = array( 'code' => $config['code'], 'plugin' => $config['plugin'] ); $this->Session->setFlash($message, 'messages/'.$config['level'], $vars); if($config['redirect'] || $config['redirect'] === ''){ if($config['redirect'] === true){ $config['redirect'] = $this->referer(); } $this->redirect($config['redirect']); } unset($_default, $config, $vars); } } /** * @brief keep the core code dry * * CoreAppController is a base clas for most of infinitas Core Controllers. * It makes the code more DRY. * * Externally developed plugins should never inherit from this class. It is * only for Infinitas and could change at any point. Extending this could * break your application in later versions. * * @copyright Copyright (c) 2009 <NAME> ( dogmatic69 ) * @link http://infinitas-cms.org * @package Infinitas * @license http://www.opensource.org/licenses/mit-license.php The MIT License * @since 0.8a * * @author dogmatic69 * * @internal * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. */ class CoreAppController extends AppController{ /** * Some helpers for the core controllers * * @var array * @access public */ public $helpers = array( 'Management.Core', 'Filter.Filter' ); } /** * @brief global methods so the AppController is a bit cleaner. * * basicaly all the methods like _something should be moved to a component * * @todo this needs to be more extendable, something like the ChartsHelper * could work. * * @copyright Copyright (c) 2009 <NAME> ( dogmatic69 ) * @link http://infinitas-cms.org * @package Infinitas * @license http://www.opensource.org/licenses/mit-license.php The MIT License * @since 0.8a * * @author dogmatic69 * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. */ class GlobalActions extends Controller{ /** * components should not be included here * * @var array * @access public */ public $components = array(); /** * reference to the model name of the current controller * * @var string * @access public */ public $modelName; /** * reference to the model name for user output * * @var string * @access public */ public $prettyModelName; /** * @brief Construct the Controller * * Currently getting components that are needed by the application. they * are then loaded into $components making them available to the entire * application. * * @access public * * @return void */ public function __construct(){ $this->__setupConfig(); $event = EventCore::trigger($this, 'requireComponentsToLoad'); if(isset($event['requireComponentsToLoad']['libs'])){ $libs['libs'] = $event['requireComponentsToLoad']['libs']; $event['requireComponentsToLoad'] = $libs + $event['requireComponentsToLoad']; } foreach($event['requireComponentsToLoad'] as $plugin => $components){ if(!empty($components)){ if(!is_array($components)){ $components = array($components); } $this->components = array_merge((array)$this->components, (array)$components); } } unset($event); parent::__construct(); } /** * @brief Set up some general variables that are used around the code. * * @access public * * @return void */ public function beforeFilter(){ parent::beforeFilter(); $this->modelName = $this->modelClass; $this->prettyModelName = prettyName($this->modelName); $this->{$this->modelName}->plugin = $this->plugin; if(!$this->Session->read('ip_address')){ $this->Session->write('ip_address', $this->RequestHandler->getClientIp()); } } /** * @brief Set up system configuration. * * Load the default configuration and check if there are any configs * to load from the current plugin. configurations can be completely rewriten * or just added to. * * @access private * * @return void */ private function __setupConfig(){ $configs = ClassRegistry::init('Configs.Config')->getConfig(); $eventData = EventCore::trigger($this, $this->plugin.'.setupConfigStart', $configs); if (isset($eventData['setupConfigStart'][$this->plugin])){ $configs = (array)$eventData['setupConfigStart'][$this->plugin]; if (!array($configs)) { $this->cakeError('eventError', array('message' => 'Your config is wrong.', 'event' => $eventData)); } } $eventData = EventCore::trigger($this, $this->plugin.'.setupConfigEnd'); if (isset($eventData['setupConfigEnd'][$this->plugin])){ $configs = $configs + (array)$eventData['setupConfigEnd'][$this->plugin]; } if (!$this->__writeConfigs($configs)) { $this->cakeError('configError', array('message' => 'Config was not written')); } unset($configs, $eventData); } /** * Write the configuration. * * Write all the config values that have been called found in InfinitasComponent::setupConfig() * * @access private * * @return bool */ private function __writeConfigs($configs){ foreach($configs as $config) { if (!(isset($config['Config']['key']) || isset($config['Config']['value']))) { $config['Config']['key'] = isset($config['Config']['key']) ? $config['Config']['key'] : 'NOT SET'; $config['Config']['value'] = isset($config['Config']['key']) ? $config['Config']['value'] : 'NOT SET'; $this->log(serialize($config['Config']), 'configuration_error'); continue; } Configure::write($config['Config']['key'], $config['Config']['value']); } unset($configs); return true; } /** * @brief allow posting comments to any controller * * @todo this needs to be moved to the Comments plugin and is part of * the reason this code needs to be more extendable * * @access public * * @return void */ public function comment($id = null) { if (!empty($this->data[$this->modelClass.'Comment'])) { $message = 'Your comment has been saved and will be available after admin moderation.'; if (Configure::read('Comments.auto_moderate') === true) { $message = 'Your comment has been saved and is active.'; } $this->data[$this->modelClass.'Comment']['class'] = Inflector::camelize($this->params['plugin']).'.'.$this->modelClass; if ($this->{$this->modelClass}->createComment($this->data)) { $this->Session->setFlash(__($message, true)); $this->redirect($this->referer()); } else { $this->Session->setFlash(__('Your comment was not saved. Please check for errors and try again', true)); } } $this->render(null, null, App::pluginPath('Comment') . 'views' . DS . 'comments' . DS . 'add.ctp'); } /** * @brief preview pages from admin when they are inactive * * method for admin to preview items without having them active, this * expects a few things from the code being previewed. * * you need a model method called getViewData for the view page that takes a conditions array * you should have a file named view.ctp * only admin can access this page * the page will be passed a variable named with Inflector::variable() * * @param mixed $id id of the record * @access public * * @return void */ public function preview($id = null){ if(!$id || (int)$this->Session->read('Auth.User.group_id') !== 1){ $this->Session->setFlash('That page does not exist', true); $this->redirect($this->referer()); } $varName = Inflector::variable($this->modelClass); $$varName = $this->{$this->modelClass}->getViewData( array( $this->modelClass . '.' . $this->{$this->modelClass}->primaryKey => $id ) ); $this->set($varName, $$varName); $this->render('view'); } /** * @brief Common method for rating. * * This is the default method for a rating, if you would like to change * the way it works for your own plugin just define your own method in the * plugins app_controller or the actual controller. * * By default it will check if users need to be logged in before rating and * redirect if they must and are not. else it will get the ip address and then * save the rating. * * @todo check if the model is a rateable model. * @todo needs to go on a diet, moved to a rating plugin * * @param int $id the id of the itme you are rating. * @access public * * @return null, will redirect. */ public function rate($id = null) { $this->data['Rating']['ip'] = $this->RequestHandler->getClientIP(); $this->data['Rating']['user_id'] = $this->Session->read('Auth.User.id'); $this->data['Rating']['class'] = isset($this->data['Rating']['class']) ? $this->data['Rating']['class']: ucfirst($this->params['plugin']).'.'.$this->modelClass; $this->data['Rating']['foreign_id'] = isset($this->data['Rating']['foreign_id']) ? $this->data['Rating']['foreign_id'] : $id; $this->data['Rating']['rating'] = isset($this->data['Rating']['rating']) ? $this->data['Rating']['rating'] : $this->params['named']['rating']; $this->log(serialize($this->data['Rating'])); if (Configure::read('Rating.require_auth') === true && !$this->data['Rating']['user_id']) { $this->Session->setFlash(__('You need to be logged in to rate this item',true)); $this->redirect('/login'); } if (!empty($this->data['Rating']['rating'])) { if ($this->{$this->modelClass}->rateRecord($this->data)) { $data = $this->{$this->modelClass}->find( 'first', array( 'fields' => array( $this->modelClass.'.rating', $this->modelClass.'.rating_count' ), 'conditions' => array( $this->modelClass.'.id' => $this->data['Rating']['foreign_id'] ) ) ); $message = sprintf(__('Saved! new rating %s (out of %s)', true), $data[$this->modelClass]['rating'], $data[$this->modelClass]['rating_count']); } else { $message = __('It seems you have already voted for this item.', true); } if(!$this->RequestHandler->isAjax()){ $this->Session->setFlash($message); $this->redirect($this->referer()); } else{ Configure::write('debug', 0); $this->set('json', array('message' => $message)); } } } /** * Some global methods for admin */ /** * @brief get a list of all the plugins in the app * * @access public * * @return void */ public function admin_getPlugins(){ $this->set('json', array('' => __('Please select', true)) + $this->{$this->modelClass}->getPlugins()); } /** * @brief get a list of all the controllers for the selected plugin * * @access public * * @return void */ public function admin_getControllers(){ if (!isset($this->params['named']['plugin'])) { $this->set('json', array('error')); return; } $this->set('json', array('' => __('Please select', true)) + $this->{$this->modelClass}->getControllers($this->params['named']['plugin'])); } /** * @brief get a list of all the models for the selected plugin * * @access public * * @return void */ public function admin_getModels(){ if (!isset($this->params['named']['plugin'])) { $this->set('json', array('error')); return; } $this->set('json', array('' => __('Please select', true)) + $this->{$this->modelClass}->getModels($this->params['named']['plugin'])); } /** * @brief get a list of all the actions for the selected plugin + controller * * @access public * * @return void */ public function admin_getActions(){ if (!(isset($this->params['named']['plugin']) && isset($this->params['named']['controller'] ))) { $this->set('json', array('error')); return; } $this->set('json', array('' => __('Please select', true)) + $this->{$this->modelClass}->getActions($this->params['named']['plugin'], $this->params['named']['controller'])); } /** * Create ACO's automaticaly * * http://book.cakephp.org/view/647/An-Automated-tool-for-creating-ACOs * * @deprecated */ public function admin_buildAcl() { if (!Configure::read('debug')) { return $this->_stop(); } $log = array(); $aco =& $this->Acl->Aco; $root = $aco->node('controllers'); if (!$root) { $aco->create(array('parent_id' => null, 'model' => null, 'alias' => 'controllers')); $root = $aco->save(); $root['Aco']['id'] = $aco->id; $log[] = 'Created Aco node for controllers'; } else { $root = $root[0]; } App::import('Core', 'File'); $Controllers = Configure::listObjects('controller'); $appIndex = array_search('App', $Controllers); if ($appIndex !== false ) { unset($Controllers[$appIndex]); } $baseMethods = get_class_methods('Controller'); $baseMethods[] = 'admin_buildAcl'; $baseMethods[] = 'blackHole'; $baseMethods[] = 'comment'; $baseMethods[] = 'rate'; $baseMethods[] = 'blackHole'; $baseMethods[] = 'addCss'; $baseMethods[] = 'addJs'; $baseMethods[] = 'admin_delete'; $Plugins = $this->Infinitas->_getPlugins(); $Controllers = array_merge($Controllers, $Plugins); // look at each controller in app/controllers foreach ($Controllers as $ctrlName) { $methods = $this->Infinitas->_getClassMethods($this->Infinitas->_getPluginControllerPath($ctrlName)); // Do all Plugins First if ($this->Infinitas->_isPlugin($ctrlName)){ $pluginNode = $aco->node('controllers/'.$this->Infinitas->_getPluginName($ctrlName)); if (!$pluginNode) { $aco->create(array('parent_id' => $root['Aco']['id'], 'model' => null, 'alias' => $this->Infinitas->_getPluginName($ctrlName))); $pluginNode = $aco->save(); $pluginNode['Aco']['id'] = $aco->id; $log[] = 'Created Aco node for ' . $this->Infinitas->_getPluginName($ctrlName) . ' Plugin'; } } // find / make controller node $controllerNode = $aco->node('controllers/'.$ctrlName); if (!$controllerNode) { if ($this->Infinitas->_isPlugin($ctrlName)){ $pluginNode = $aco->node('controllers/' . $this->Infinitas->_getPluginName($ctrlName)); $aco->create(array('parent_id' => $pluginNode['0']['Aco']['id'], 'model' => null, 'alias' => $this->Infinitas->_getPluginControllerName($ctrlName))); $controllerNode = $aco->save(); $controllerNode['Aco']['id'] = $aco->id; $log[] = 'Created Aco node for ' . $this->Infinitas->_getPluginControllerName($ctrlName) . ' ' . $this->Infinitas->_getPluginName($ctrlName) . ' Plugin Controller'; } else { $aco->create(array('parent_id' => $root['Aco']['id'], 'model' => null, 'alias' => $ctrlName)); $controllerNode = $aco->save(); $controllerNode['Aco']['id'] = $aco->id; $log[] = 'Created Aco node for ' . $ctrlName; } } else { $controllerNode = $controllerNode[0]; } //clean the methods. to remove those in Controller and private actions. foreach ((array)$methods as $k => $method) { if (strpos($method, '_', 0) === 0 || in_array($method, $baseMethods)) { unset($methods[$k]); continue; } $methodNode = $aco->node('controllers/'.$ctrlName.'/'.$method); if (!$methodNode) { $aco->create(array('parent_id' => $controllerNode['Aco']['id'], 'model' => null, 'alias' => $method)); $methodNode = $aco->save(); $log[] = 'Created Aco node for '. $method; } } } if(count($log)>0) { debug($log); } } /** * Mass actions * * Method to handle mass actions (Such as mass deletions, toggles, etc.) * * @access public * * @return void */ public function admin_mass() { $massAction = $this->MassAction->getAction($this->params['form']); $ids = $this->MassAction->getIds( $massAction, $this->data[isset($this->data['Confirm']['model']) ? $this->data['Confirm']['model'] : $this->modelClass] ); $massActionMethod = '__massAction' . ucfirst($massAction); if(method_exists($this, $massActionMethod)){ return $this->{$massActionMethod}($ids); } elseif(method_exists($this->MassAction, $massAction)) { return $this->MassAction->{$massAction}($ids); } else { return $this->MassAction->generic($massAction, $ids); } } /** * @brief Simple Admin add method. * * If you need simple Add method for your admin just dont create one and * it will fall back to this. It does the basics, saveAll with a * Session::setFlash() message. * * @todo sanitize input * @todo render generic view * * @access public * * @return void */ public function admin_add(){ if (!empty($this->data)) { $this->{$this->modelName}->create(); if ($this->{$this->modelName}->saveAll($this->data)) { $this->Infinitas->noticeSaved(); } $this->Infinitas->noticeNotSaved(); } $lastPage = $this->Session->read('Infinitas.last_page'); if(!$lastPage){ $this->Session->write('Infinitas.last_page', $this->referer()); } } /** * @brief Simple Admin edit method * * If you need simple Edit method for your admin just dont create one and * it will fall back to this. It does the basics, saveAll with a * Session::setFlash() message. * * @todo sanitize input * @todo render generic view * * @param mixed $id int | string (uuid) the id of the record to edit. * @access public * * @return void */ public function admin_edit($id = null, $query = array()){ if(empty($this->data) && !$id){ $this->Infinitas->noticeInvalidRecord(); } if (!empty($this->data)) { if ($this->{$this->modelName}->saveAll($this->data)) { $this->Infinitas->noticeSaved(); } $this->Infinitas->noticeNotSaved(); } if(empty($this->data) && $id){ $query['conditions'][$this->{$this->modelName}->alias . '.' . $this->{$this->modelName}->primaryKey] = $id; $this->data = $this->{$this->modelName}->find('first', $query); if(empty($this->data)){ $this->Infinitas->noticeInvalidRecord(); } } $lastPage = $this->Session->read('Infinitas.last_page'); if(!$lastPage){ $this->Session->write('Infinitas.last_page', $this->referer()); } } /** * reorder records. * * uses named paramiters can use the following: * - position: sets the position for the record for sequenced models * - possition needs the new possition of the record * * - direction: for MPTT and only needs the record id. * * @param int $id the id of the record to move. * * @access public * * @return void */ public function admin_reorder($id = null) { $model = $this->modelClass; if (!$id) { $this->Infinitas->noticeInvalidRecord(); } $this->data[$model]['id'] = $id; if (!isset($this->params['named']['position']) && isset($this->$model->actsAs['Libs.Sequence'])) { $this->notice( __('A problem occured moving the ordered record.', true), array( 'level' => 'error', 'redirect' => true ) ); } if (!isset($this->params['named']['direction']) && isset($this->$model->actsAs['Tree'])) { $this->notice( __('A problem occured moving that MPTT record.', true), array( 'level' => 'error', 'redirect' => true ) ); } if (isset($this->params['named']['position'])) { $this->Infinitas->_orderedMove(); } if (isset($this->params['named']['direction'])) { $this->Infinitas->_treeMove(); } $this->redirect($this->referer()); } } <file_sep><?php /* Contacts Test cases generated on: 2010-12-14 13:12:08 : 1292334968*/ App::import('Helper', 'contact.Contacts'); class ContactsHelperTestCase extends CakeTestCase { function startTest() { $this->Contacts =& new ContactsHelper(); } function endTest() { unset($this->Contacts); ClassRegistry::flush(); } } ?><file_sep><?php $map = array( 1 => array( '000008_data' => 'R4c94edcc2b7c4e1999cf78d86318cd70'), ); ?><file_sep><?php class PhpController extends ServerStatusAppController{ public $name = 'Php'; public $uses = array(); /** * @brief Status pannel for apc */ public function admin_apc(){ // Configure::write('debug', 0); if(!function_exists('apc_cache_info')){ $this->notice( __('APC is not installed, or has been deactivated', true), array( 'level' => 'warning', 'redirect' => true ) ); } $this->layout = 'ajax'; } public function admin_info(){ } }<file_sep><div class="dashboard"> <h1><?php __('Missing Behavior Class'); ?></h1> <p class="error"> <strong><?php __('Error'); ?>: </strong> <?php printf(__('The behavior class <em>%s</em> can not be found or does not exist.', true), $behaviorClass); ?> </p> <p class="error"> <strong><?php __('Error'); ?>: </strong> <?php printf(__('Create the class below in file: %s', true), APP_DIR . DS . 'models' . DS . 'behaviors' . DS . $file); ?> </p> <pre> &lt;?php class <?php echo $behaviorClass;?> extends ModelBehavior { } ?&gt; </pre> </div><file_sep><?php class TagsController extends TagsAppController { /** * Name * * @var string $name * @access public */ public $name = 'Tags'; public function beforeFilter(){ parent::beforeFilter(); $this->helpers[] = 'Filter.Filter'; } /** * Admin Index * * @return void * @access public */ public function admin_index() { $tags = $this->paginate(); $filterOptions = $this->Filter->filterOptions; $filterOptions['fields'] = array( 'name', 'identifier', 'keyname' ); $this->set(compact('tags','filterOptions')); } } <file_sep><?php /** * Comment Template. * * @todo -c Implement .this needs to be sorted out. * * Copyright (c) 2009 <NAME> ( dogmatic69 ) * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. * * @filesource * @copyright Copyright (c) 2009 <NAME> ( dogmatic69 ) * @link http://infinitas-cms.org * @package sort * @subpackage sort.comments * @license http://www.opensource.org/licenses/mit-license.php The MIT License * @since 0.5a */ echo $this->Form->create('Trash', array('url' => array('controller' => 'trash', 'action' => 'mass'))); $massActions = $this->Core->massActionButtons(array('restore', 'delete')); echo $this->Infinitas->adminIndexHead($filterOptions, $massActions); ?> <div class="table"> <table class="listing" cellpadding="0" cellspacing="0"> <?php echo $this->Core->adminTableHeader( array( $this->Form->checkbox('all') => array( 'class' => 'first', 'style' => 'width:25px;' ), $this->Paginator->sort('name'), $this->Paginator->sort('Type', 'model') => array( 'style' => 'width:100px;' ), $this->Paginator->sort('deleted') => array( 'style' => 'width:100px;' ), $this->Paginator->sort( 'Deleted By', 'Deleter.name' ) => array( 'style' => 'width:100px;' ) ) ); foreach ($trashed as $trash) { ?> <tr class="<?php echo $this->Core->rowClass(); ?>"> <td><?php echo $this->Form->checkbox( $trash['Trash']['id'] ); ?>&nbsp;</td> <td> <?php echo Inflector::humanize($trash['Trash']['name']); ?>&nbsp; </td> <td> <?php $type = pluginSplit($trash['Trash']['model']); echo $type[0] . (isset($type[1]) ? ' ' . prettyName($type[1]) : ''); ?>&nbsp; </td> <td> <?php echo $this->Time->timeAgoInWords($trash['Trash']['deleted']); ?>&nbsp; </td> <td> <?php echo $trash['User']['username']; ?>&nbsp; </td> </tr> <?php } ?> </table> <?php echo $this->Form->end(); ?> </div> <?php echo $this->element('pagination/admin/navigation'); ?><file_sep><?php /* Group Test cases generated on: 2010-03-13 11:03:33 : 1268471133*/ App::import('Model', 'management.Group'); class GroupTestCase extends CakeTestCase { function startTest() { $this->Group =& ClassRegistry::init('Group'); } function endTest() { unset($this->Group); ClassRegistry::flush(); } } ?><file_sep><?php /** * @brief CommentsAppModel is the base model that all the models in comments extends * * @copyright Copyright (c) 2010 <NAME> ( dogmatic69 ) * @link http://www.infinitas-cms.org * @package Infinitas.Comments * @license http://www.opensource.org/licenses/mit-license.php The MIT License * @since 0.8a * * @author dogmatic69 * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. */ class CommentsAppModel extends AppModel{ /** * the table prefix used in this plugin * * @var string * @access public */ public $tablePrefix = 'global_'; }<file_sep><?php /** * @brief ConfigsEvents for the Configs plugin to attach into the application * * @copyright Copyright (c) 2010 <NAME> ( dogmatic69 ) * @link http://www.infinitas-cms.org * @package Infinitas.Configs * @license http://www.opensource.org/licenses/mit-license.php The MIT License * @since 0.8a * * @author dogmatic69 * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. */ final class ConfigsEvents extends AppEvents{ public function onSetupConfig(){ } public function onSetupCache(){ return array( 'name' => 'configs', 'config' => array( 'prefix' => 'core.configs.', ) ); } public function onAdminMenu($event){ $menu['main'] = array( 'Configuration' => array('controller' => 'configs', 'action' => 'index'), 'Available' => array('controller' => 'configs', 'action' => 'available') ); return $menu; } }<file_sep><?php /** * Blog pagination view element file. * * this is a custom pagination element for the blog plugin. you can * customize the entire blog pagination look and feel by modyfying this file. * * Copyright (c) 2009 <NAME> ( dogmatic69 ) * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. * * @filesource * @copyright Copyright (c) 2009 <NAME> ( dogmatic69 ) * @link http://infinitas-cms.org * @package blog * @subpackage blog.views.elements.pagination.navigation * @license http://www.opensource.org/licenses/mit-license.php The MIT License */ ?> <div class="clr">&nbsp;</div> <?php // show a message if nothing is found ( count == 0 or its not set ) if ( !isset($this->Paginator->params['paging'][key( $this->Paginator->params['paging'] )]['count']) || $this->Paginator->params['paging'][key( $this->Paginator->params['paging'] )]['count'] == 0 ) { echo '<p class="empty">', __( Configure::read( 'Pagination.nothing_found_message' ), true ), '</p>'; return true; } ?> <div class="wrap"> <div class="button2-left"> <div class="prev"> <?php echo $paginator->prev( __( 'Older', true ), array( 'escape' => false, 'tag' => 'span', 'class' => '' ), null, null ); ?> </div> </div> <div class="button2-right"> <div class="next"> <?php echo $paginator->next( __( 'Newer', true ), array( 'escape' => false, 'tag' => 'span', 'class' => '' ), null, null ); ?> </div> </div> </div><file_sep><div class="user-warning error"> <?php echo $this->Html->image( $this->Image->getRelativePath('notifications', 'stop'), array('alt' => 'error') ); if(isset($code) && $code){ sprintf('<b>%s:</b> %s', $code, $message); } else{ echo $message; } ?> </div><file_sep><?php /** * Admin pagination * * This is the default pagination file for infinitas. You can use your own * by adding one to your_plugin/views/elements/pagination/admin/navigation.ctp * or setting a different pagination element in the view you are using. * * Copyright (c) 2009 <NAME> ( dogmatic69 ) * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. * * @filesource * @copyright Copyright (c) 2009 <NAME> ( dogmatic69 ) * @link http://infinitas-cms.org * @package Infinitas.views * @subpackage Infinitas.views.pagination.admin * @license http://www.opensource.org/licenses/mit-license.php The MIT License */ $numbers = $paginator->numbers( array( 'tag' => 'li', 'before' => null, 'after' => null, 'model' => null, 'modulus' => '8', 'separator' => '', 'first' => null, 'last' => null ) ); // show a message if nothing is found ( count == 0 or its not set ) if ( !isset($this->Paginator->params['paging'][key( $this->Paginator->params['paging'] )]['count']) || $this->Paginator->params['paging'][key( $this->Paginator->params['paging'] )]['count'] == 0 ) { echo '<p class="empty">', __( Configure::read( 'Pagination.nothing_found_message' ), true ), '</p>'; return true; } ?> <ul class="pagination"> <?php echo $paginator->prev('prev page', array('tag' => 'li'), "\n"); echo $paginator->numbers(array('separator' => false, 'tag' => 'li', 'first' => 5, 'last' => 5)); echo $paginator->next('next page', array('tag' => 'li'), "\n"); ?> <li class="form"> <?php $_paginationOptions = explode( ',', Configure::read( 'Global.pagination_select' ) ); $paginationLimmits = array_combine( array_values( $_paginationOptions ), array_values( $_paginationOptions ) ); $_paginationOptionsSelected = (isset($this->params['named']['limit'])) ? $this->params['named']['limit'] : 20; echo $this->Form->create('PaginationOptions', array('url' => str_replace($this->base, '', $this->here), 'id' => 'PaginationOptions')); echo $this->Form->input( 'pagination_limit', array( 'options' => $paginationLimmits, 'div' => false, 'label' => false, 'selected' => $_paginationOptionsSelected ) ); echo $this->Form->end(); ?> </li> <li class="text"><?php echo $this->Design->paginationCounter($paginator); ?></li> </ul><file_sep><?php /* HtmlChartEngine Test cases generated on: 2010-12-14 01:12:23 : 1292291603*/ App::import('helper', 'charts.ChartsHelper'); class HtmlChartEnginehelperTestCase extends CakeTestCase { function startTest() { $this->HtmlChartEngine = new HtmlChartEngineHelper(); } function endTest() { unset($this->HtmlChartEngine); ClassRegistry::flush(); } }<file_sep><?php /* ModulePosition Test cases generated on: 2010-03-13 11:03:53 : 1268471213*/ App::import('Model', 'management.ModulePosition'); class ModulePositionTestCase extends CakeTestCase { function startTest() { $this->ModulePosition =& ClassRegistry::init('ModulePosition'); } function endTest() { unset($this->ModulePosition); ClassRegistry::flush(); } } ?><file_sep><?php class ModulePosition extends CoreAppModel{ public $name = 'ModulePosition'; public function __construct($id = false, $table = null, $ds = null) { parent::__construct($id, $table, $ds); $this->validate = array( 'name' => array( 'validName' => array( 'rule' => '/[a-z0-9_]{1,50}/', 'message' => __('Please enter a valid name, lowercase letters, numbers and underscores only', true) ), 'isUnique' => array( 'rule' => 'isUnique', 'message' => __('There is already a position with that name', true) ) ) ); } public function isPosition($position = null){ if(!$position){ return false; } return (bool)$this->find( 'count', array( 'conditions' => array( 'ModulePosition.name' => $position ) ) ); } }<file_sep><div class="dashboard"> <h1><?php __('Missing Component Class'); ?></h1> <p class="error"> <strong><?php __('Error'); ?>: </strong> <?php printf(__('Component class %1$s in %2$s was not found.', true), '<em>' . $component . 'Component</em>', '<em>' . $controller . 'Controller</em>'); ?> </p> <p class="error"> <strong><?php __('Error'); ?>: </strong> <?php printf(__('Create the class %s in file: %s', true), '<em>' . $component . 'Component</em>', APP_DIR . DS . 'controllers' . DS . 'components' . DS . $file); ?> </p> <pre> &lt;?php class <?php echo $component;?>Component extends Object {<br /> } ?&gt; </pre> </div><file_sep><?php $map = array( 1 => array( '000008_configs' => 'R4ce2a439e60c43688a73133c6318cd70'), ); ?><file_sep><?php $map = array( 1 => array( '000008_contact' => 'R4c94edccf7144d6c8f1778d86318cd70'), ); ?><file_sep><?php /** * AnalogueHelper * Renames, or "maps", helpers prior to rendering * @author <NAME> <<EMAIL>> * * Example * * public $helpers = array( * 'Analogue' => array( * array( * 'helper' => 'MyHtml', * 'rename' => 'Html' * ), * array( * 'helper' => 'MyForm', * 'rename' => 'Form' * ) * ) * ); */ class AnalogueHelper extends AppHelper { /** * Mappings * @var array * @access private */ private $mappings = array(); /** * View * @var View * @access private */ private $view; /** * Executed prior to rendering * @return null * @access public */ public function beforeRender() { // Loop through and call _mapHelper() foreach ($this->mappings as $mapping) { $this->_mapHelper($mapping); } } /** * Construction * @param array $settings * @return null * @access public */ public function __construct($mappings = array()) { // Grab our View object for use later... $this->view = ClassRegistry::getObject('view'); // Merge our mappings together... $this->mappings = am( $this->mappings, $mappings ); } /** * Performs the mapping of a helper object to a new name * @param array $mapping * @return null * @access private */ private function _mapHelper($mapping = array()) { // Helpers are always lowercased in the View object $mapping = array_map('strtolower', $mapping); // Extract our array for use extract($mapping); // Only continue if we have a valid, loaded helper if (isset($helper)) { if (isset($this->view->loaded[$helper]) and isset($rename)) { $this->view->loaded[$rename] = $this->view->loaded[$helper]; } } } } ?><file_sep><?php class DatabasesController extends ServerStatusAppController{ public $name = 'Databases'; public $uses = array(); public function admin_dashboard(){ } public function admin_mysql(){ $User = ClassRegistry::init('Users.User'); $globalVars = $User->query('show global variables'); $globalVars = array_combine( Set::extract('/VARIABLES/Variable_name', $globalVars), Set::extract('/VARIABLES/Value', $globalVars) ); $localVars = $User->query('show variables'); $localVars = array_combine( Set::extract('/VARIABLES/Variable_name', $localVars), Set::extract('/VARIABLES/Value', $localVars) ); $localVars = Set::diff($localVars, $globalVars); $this->set(compact('globalVars', 'localVars')); } }<file_sep><?php class EmailsAppController extends AppController{ public function beforeFilter(){ parent::beforeFilter(); $this->helpers[] = 'Filter.Filter'; } } <file_sep><?php /* Aro Fixture generated on: 2010-08-17 14:08:42 : 1282055082 */ class AroFixture extends CakeTestFixture { var $name = 'Aro'; var $fields = array( 'id' => array('type' => 'integer', 'null' => false, 'default' => NULL, 'length' => 10, 'key' => 'primary'), 'parent_id' => array('type' => 'integer', 'null' => true, 'default' => NULL, 'length' => 10), 'model' => array('type' => 'string', 'null' => true, 'default' => NULL), 'foreign_key' => array('type' => 'integer', 'null' => true, 'default' => NULL, 'length' => 10), 'alias' => array('type' => 'string', 'null' => true, 'default' => NULL), 'lft' => array('type' => 'integer', 'null' => true, 'default' => NULL, 'length' => 10), 'rght' => array('type' => 'integer', 'null' => true, 'default' => NULL, 'length' => 10), 'indexes' => array('PRIMARY' => array('column' => 'id', 'unique' => 1)), 'tableParameters' => array('charset' => 'utf8', 'collate' => 'utf8_general_ci', 'engine' => 'InnoDB') ); var $records = array( array( 'id' => 1, 'parent_id' => 0, 'model' => 'Group', 'foreign_key' => 1, 'alias' => '', 'lft' => 1, 'rght' => 2 ), array( 'id' => 2, 'parent_id' => 0, 'model' => 'User', 'foreign_key' => 1, 'alias' => '', 'lft' => 3, 'rght' => 4 ), array( 'id' => 3, 'parent_id' => 0, 'model' => 'User', 'foreign_key' => 2, 'alias' => '', 'lft' => 5, 'rght' => 6 ), array( 'id' => 4, 'parent_id' => 0, 'model' => 'User', 'foreign_key' => 3, 'alias' => '', 'lft' => 7, 'rght' => 8 ), array( 'id' => 5, 'parent_id' => 0, 'model' => 'User', 'foreign_key' => 4, 'alias' => '', 'lft' => 9, 'rght' => 10 ), array( 'id' => 6, 'parent_id' => 0, 'model' => 'User', 'foreign_key' => 5, 'alias' => '', 'lft' => 11, 'rght' => 12 ), array( 'id' => 7, 'parent_id' => 0, 'model' => 'User', 'foreign_key' => 6, 'alias' => '', 'lft' => 13, 'rght' => 14 ), array( 'id' => 8, 'parent_id' => 0, 'model' => 'User', 'foreign_key' => 7, 'alias' => '', 'lft' => 15, 'rght' => 16 ), array( 'id' => 9, 'parent_id' => 0, 'model' => 'User', 'foreign_key' => 8, 'alias' => '', 'lft' => 17, 'rght' => 18 ), array( 'id' => 10, 'parent_id' => 0, 'model' => 'User', 'foreign_key' => 9, 'alias' => '', 'lft' => 19, 'rght' => 20 ), array( 'id' => 11, 'parent_id' => 0, 'model' => 'User', 'foreign_key' => 10, 'alias' => '', 'lft' => 21, 'rght' => 22 ), array( 'id' => 12, 'parent_id' => 0, 'model' => 'User', 'foreign_key' => 11, 'alias' => '', 'lft' => 23, 'rght' => 24 ), array( 'id' => 13, 'parent_id' => 0, 'model' => 'User', 'foreign_key' => 12, 'alias' => '', 'lft' => 25, 'rght' => 26 ), array( 'id' => 14, 'parent_id' => 0, 'model' => 'User', 'foreign_key' => 13, 'alias' => '', 'lft' => 27, 'rght' => 28 ), array( 'id' => 15, 'parent_id' => 0, 'model' => 'User', 'foreign_key' => 14, 'alias' => '', 'lft' => 29, 'rght' => 30 ), array( 'id' => 16, 'parent_id' => 0, 'model' => 'User', 'foreign_key' => 15, 'alias' => '', 'lft' => 31, 'rght' => 32 ), array( 'id' => 17, 'parent_id' => 0, 'model' => 'User', 'foreign_key' => 16, 'alias' => '', 'lft' => 33, 'rght' => 34 ), array( 'id' => 18, 'parent_id' => 0, 'model' => 'User', 'foreign_key' => 18, 'alias' => '', 'lft' => 35, 'rght' => 36 ), ); } ?><file_sep><?php /* Branch Test cases generated on: 2010-12-14 13:12:22 : 1292334982*/ App::import('Model', 'contact.Branch'); class BranchTestCase extends CakeTestCase { function startTest() { $this->Branch =& ClassRegistry::init('Branch'); } function endTest() { unset($this->Branch); ClassRegistry::flush(); } } ?><file_sep><?php /** * Management Modules admin edit post. * * this page is for admin to manage the modules on the site * * Copyright (c) 2009 <NAME> ( dogmatic69 ) * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. * * @filesource * @copyright Copyright (c) 2009 <NAME> ( dogmatic69 ) * @link http://infinitas-cms.org * @package management * @subpackage management.views.configs.admin_edit * @license http://www.opensource.org/licenses/mit-license.php The MIT License */ echo $this->Form->create('Module'); echo $this->Infinitas->adminEditHead(); ?> <fieldset> <h1><?php echo __('Menu Item', true); ?><a href="#" onlcick="$('.dynamic').toggle(); $('.static').toggle();">Toggle</a></h1><?php echo $this->Form->input('id'); echo $this->Form->input('name'); ?> <div class="dynamic"> <div class="input select smaller"> <label for="ModulePlugin"><?php echo __('Module File', true); ?></label><?php echo $this->Form->input('plugin', array('label' => false, 'div' => false, 'class' => "modulePuluginSelect {url:{action:'getModules'}, target:'ModuleModule'}")); echo $this->Form->input('module', array('label' => false, 'div' => false, 'empty' => __(Configure::read('Website.empty_select'), true))); ?> </div><?php echo $this->Form->input('config', array('class' => 'title')); echo $this->Form->input('active');?> </div> <div class="static"><?php echo $this->Form->input('show_heading'); echo $this->Form->input('content', array('class' => 'title'));?> </div> </fieldset> <fieldset> <h1><?php echo __('Where Module should show', true); ?></h1><?php echo $this->Form->input('group_id', array('empty' => Configure::read('Website.empty_select'))); echo $this->Form->input('theme_id', array('empty' => __('All Themes', true))); echo $this->Form->input('position_id', array('empty' => Configure::read('Website.empty_select'))); $selected = isset($this->data['Route']) ? $this->data['Route'] : 0; echo $this->Form->input('Route', array('type' => 'select', 'multiple' => 'checkbox', 'selected' => $selected)); ?> </fieldset> <fieldset> <h1><?php echo __('Author Details', true); ?></h1><?php echo $this->Form->input('author'); echo $this->Form->input('url'); echo $this->Form->input('update_url'); echo $this->Form->input('licence'); ?> </fieldset><?php echo $this->Form->end(); ?><file_sep><?php /* * Short Description / title. * * Overview of what the file does. About a paragraph or two * * Copyright (c) 2010 <NAME> ( dogmatic69 ) * * @filesource * @copyright Copyright (c) 2010 <NAME> ( dogmatic69 ) * @link http://www.infinitas-cms.org * @package {see_below} * @subpackage {see_below} * @license http://www.opensource.org/licenses/mit-license.php The MIT License * @since {check_current_milestone_in_lighthouse} * * @author {your_name} * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. */ class InstallerEvents extends AppEvents{ public function onSetupRoutes(){ // infinitas is not installed $databaseConfig = APP.'config'.DS.'database.php'; Router::connect('/install/finish/*', array('plugin' => 'installer', 'controller' => 'install', 'action' => 'finish')); Router::connect('/install/:step', array('plugin' => 'installer', 'controller' => 'install', 'action' => 'index'), array('pass' => array('step'))); if(!file_exists($databaseConfig) || filesize($databaseConfig) == 0) { if(!file_exists($databaseConfig)) { $file = fopen($databaseConfig, 'w'); fclose($file); } Configure::write('Session.save', 'php'); Router::connect('/', array('plugin' => 'installer', 'controller' => 'install', 'action' => 'index')); Router::connect('/*', array('plugin' => 'installer', 'controller' => 'install', 'action' => 'index')); } return true; } public function onPluginRollCall(){ return array( 'name' => 'Plugins', 'description' => 'Manage, install and remove plugins', 'icon' => '/installer/img/icon.png', 'author' => 'Infinitas', 'dashboard' => array('plugin' => 'installer', 'controller' => 'plugins', 'action' => 'dashboard'), ); } public function onAdminMenu($event){ $menu['main'] = array( 'Dashboard' => array('plugin' => 'installer', 'controller' => 'plugins', 'action' => 'dashboard'), 'Plugins' => array('plugin' => 'installer', 'controller' => 'plugins', 'action' => 'index'), 'Install' => array('plugin' => 'installer', 'controller' => 'plugins', 'action' => 'install'), 'Update' => array('plugin' => 'installer', 'controller' => 'plugins', 'action' => 'update_infinitas'), ); return $menu; } }<file_sep><?php $dashboardIcons = array( array( 'name' => 'Accounts', 'description' => 'Manage your email accounts', 'dashboard' => array( 'plugin' => 'emails', 'controller' => 'email_accounts', 'action' => 'index' ) ) ); $dashboardIcons = $this->Menu->builDashboardLinks($dashboardIcons, 'email_dashbaord'); $accountIcons = array(); foreach($accounts as $account){ $_url = $this->Event->trigger('emails.slugUrl', array('type' => 'inbox', 'data' => $account)); $accountIcons[] = array( 'name' => $account['EmailAccount']['name'], 'description' => $account['EmailAccount']['email'], 'dashboard' => current($_url['slugUrl']) ); } $accountIcons = $this->Menu->builDashboardLinks($accountIcons, 'accounts_'.$this->Session->read('Auth.User.id')); ?> <div class="dashboard grid_16"> <h1><?php __('Email Manager', true); ?></h1> <ul class="icons"><li><?php echo implode('</li><li>', current((array)$dashboardIcons)); ?></li></ul> <p class="info"><?php echo Configure::read('Email.info.general'); ?></p> </div> <div class="dashboard grid_8 half"> <h1><?php echo __('Your Accounts', true); ?></h1> <?php if(!empty($accountIcons)){ ?><ul class="icons"><li><?php echo implode('</li><li>', current((array)$accountIcons)); ?></li></ul><?php } ?> <p class="info"><?php echo Configure::read('Email.info.accounts'); ?></p> </div> <div class="dashboard grid_8 half"> <h1><?php echo __('New Mails', true); ?></h1> <ul class="icons"><li></li></ul> </div><file_sep><?php class EmailsAppModel extends AppModel{ public $tablePrefix = 'emails_'; public $types = array( 'smtp' => 'smtp', 'php' => 'php', 'pop3' => 'pop3', 'imap' => 'imap' ); } <file_sep><?php /** * @page AppError AppError * * @section app_error-overview What is it * * The error handler for Infinitas * * @section app_controller-usage How to use it * * All error are pushed through this class * * @section app_controller-see-also Also see * @link http://api.cakephp.org/class/error-handler */ /** * @brief App Error class * * Over load cakes default error handeling. * * @copyright Copyright (c) 2010 <NAME> ( dogmatic69 ) * @link http://www.infinitas-cms.org * @package Infinitas * @license http://www.opensource.org/licenses/mit-license.php The MIT License * @since 0.7a * * @author <NAME> ( dogmatic69 ) * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. */ class AppError extends ErrorHandler { /** * @brief Event errors * * Create errors for events that are not configured * properly. * * @see AppEvents * @see EventCore * * @param array $params the array of params to display to the user. */ public function eventError($params){ $this->controller->set('params', $params); $this->_outputMessage('event_error'); } /** * @brief overload to show a stack trace and log some data * * This shows all the error pages like 404 missing files and classes. It * is overloaded to add a bit of logging and dump a stack trace when debug * is on. * * @link http://api.cakephp.org/class/error-handler * * @param string $template the error to show * @access public * * @return mixed void */ public function _outputMessage($template) { $this->log('Where: ' . serialize($this->controller->params['url']), 'page_errors'); $this->log('What: ' . serialize($this->controller->viewVars), 'page_errors'); $this->log('Referer: ' . $this->controller->referer(), 'page_errors'); $this->controller->render($template); $this->controller->afterFilter(); echo $this->controller->output; if(!Configure::read('debug')){ return; } $backtrace = debug_backtrace(false); ?> <table width="80%" style="margin:auto;"> <tr> <th>File</th> <th>Code</th> <th>Line</th> </tr> <?php foreach($backtrace as $_b){ $_b = array_merge( array( 'file' => '?', 'class' => '?', 'type' => '?', 'function' => '?', 'line' => '?' ), $_b ); ?> <tr> <td><?php echo $_b['file']; ?></td> <td><?php echo $_b['class'], $_b['type'], $_b['function']; ?></td> <td><?php echo $_b['line']; ?></td> </tr> <?php } ?> </table> <?php } }<file_sep><?php $map = array( 1 => array( '000008_comments' => 'R4c94edccda44433ebb1e78d86318cd70'), ); ?><file_sep><?php /* Categories Test cases generated on: 2010-12-14 01:12:59 : 1292289659*/ App::import('Controller', 'Categories.Categories'); class TestCategoriesController extends CategoriesController { var $autoRender = false; function redirect($url, $status = null, $exit = true) { $this->redirectUrl = $url; } } class CategoriesControllerTestCase extends CakeTestCase { function startTest() { $this->Categories = new TestCategoriesController(); $this->Categories->constructClasses(); } function endTest() { unset($this->Categories); ClassRegistry::flush(); } }<file_sep><?php /* SVN FILE: $Id$ */ /* Filemanager schema generated on: 2010-09-18 18:09:20 : 1284828620*/ class FilemanagerSchema extends CakeSchema { var $name = 'Filemanager'; function before($event = array()) { return true; } function after($event = array()) { } } ?><file_sep><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <?php echo $this->Html->charset(); ?> <title> <?php echo __( 'Infinitas Admin :: ', true ), $title_for_layout; ?> </title> <?php echo $this->Html->meta('icon'); $css = array( '/assets/css/960gs/960', '/assets/css/admin_nav', '/assets/css/960gs/uncompressed/demo' ); echo $this->Html->css($css); echo $scripts_for_layout; ?> </head> <body> <div id="wrap"> <div class="module admin-menu "> <div class="grid_16 center" id="menucontainer"> <div id="menunav"> <ul><li><?php echo $this->Html->link(__('Login', true), array('action' => 'login'), array('class' => 'current')); ?></li></ul> </div> </div> <div class="clear"></div> </div> <div class="container_16"> <div class="grid_16"> <?php echo $this->Session->flash(); ?> </div> <div class="clear"></div> <div class="grid_16 dashboard"> <h1><?php __('Infinitas Cms'); ?></h1> <?php echo $content_for_layout; ?> </div> <div class="powered-by">Powered By: <?php echo $this->Html->link('Infinitas', 'http://infinitas-cms.org');?></div> </div> </div> </body> </html><file_sep><?php /** * * */ class GlobalLayoutsController extends ContentsAppController{ public $name = 'GlobalLayouts'; /** * Helpers. * * @access public * @var array */ public $helpers = array('Filter.Filter'); /** * Its pointless trying to use a wysiwyg here, so we will just put if off * completely for the layouts. */ public function beforeRender(){ parent::beforeRender(); Configure::write('Wysiwyg.editor', 'text'); } public function admin_index() { $layouts = $this->paginate(null, $this->Filter->filter); $filterOptions = $this->Filter->filterOptions; $filterOptions['fields'] = array( 'name' ); $this->set(compact('layouts','filterOptions')); } public function admin_add(){ parent::admin_add(); $plugins = $this->GlobalLayout->getPlugins(); $this->set(compact('plugins')); } public function admin_edit($id = null, $query = array()) { parent::admin_edit($id, $query); $plugins = $this->GlobalLayout->getPlugins(); $models = $this->GlobalLayout->getModels($this->data['GlobalLayout']['plugin']); $this->set(compact('plugins', 'models')); } }<file_sep><?php /** * Comment Template. * * @todo Implement .this needs to be sorted out. * * Copyright (c) 2009 <NAME> ( dogmatic69 ) * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. * @filesource * @copyright Copyright (c) 2009 <NAME> ( dogmatic69 ) * @link http://infinitas-cms.org * @package sort * @subpackage sort.comments * @license http://www.opensource.org/licenses/mit-license.php The MIT License * @since 0.5a */ class FeedableBehavior extends ModelBehavior { public $_defaults = array(); public $_results = null; public $basicStatement = array( 'order' => array(), 'limit' => array(), 'setup' => array(), 'conditions' => array(), 'joins' => array(), 'group' => array(), 'fields' => array(), ); /** * @param object $Model Model using the behavior * @param array $settings Settings to override for model. * @access public * @return void */ public function setup(&$Model, $config = null) { $Model->_findMethods = array_merge($Model->_findMethods, array('feed'=>true)); if (is_array($config)) { $this->settings[$Model->alias] = array_merge($this->_defaults, $config); } else { $this->settings[$Model->alias] = $this->_defaults; } $Model->Behaviors->__methods = array_merge( $Model->Behaviors->__methods, array('_findFeed' => array('_findFeed', 'Feedable')) ); } protected function _findFeed(&$Model, $state, $query, $results = array()){ if($state == 'before') { if (!isset($query['feed'])){ return $query; } $DboMysql = Connectionmanager::getDataSource($Model->useDbConfig); $sql = ''; foreach((array)$query['feed'] as $key => $feed){ $feed = array_merge($this->basicStatement, $feed); $sql .= ' UNION '; $currentModel = ClassRegistry::init($key); $setup = explode(' AND ', str_replace(array('=', '`'), array('AS', '\''), $DboMysql->conditions(array_flip($feed['setup']), false, false))); $sql .= $DboMysql->renderStatement( 'select', array( 'fields' => implode(', ', array_merge($DboMysql->fields($currentModel, null, (array)$feed['fields']), $setup)), 'table' => $DboMysql->fullTableName($currentModel), 'alias' => ' AS '.$currentModel->alias, 'joins' => '', 'conditions' => $DboMysql->conditions($feed['conditions']), 'group' => '', 'order' => $DboMysql->order($feed['order']), 'limit' => $DboMysql->limit($feed['limit']) ) ); } $query = array_merge($this->basicStatement, $query); $setup = explode(' AND ', str_replace(array('=', '`'), array('AS', '\''), $DboMysql->conditions(array_flip($query['setup']), false, false))); $sql = $DboMysql->renderStatement( 'select', array( 'fields' => implode(', ', array_merge($DboMysql->fields($Model, null, (array)$query['fields']), $setup)), 'table' => $DboMysql->fullTableName($Model), 'alias' => ' AS '.$Model->alias, 'joins' => '', 'conditions' => $DboMysql->conditions($query['conditions']), 'group' => $sql, // @todo slight hack 'order' => $DboMysql->order($query['order']), 'limit' => $DboMysql->limit($query['limit']) ) ); $_results = $Model->query($sql); foreach($_results as $res){ $this->_results[]['Feed'] = $res[0]; } return $query; } elseif ($state == 'after') { return $this->_results; } return false; } }<file_sep><?php /** */ class FilemanagerController extends CoreAppController { public $name = 'Filemanager'; public $uses = array('Filemanager.Files', 'Filemanager.Folders'); public function admin_index() { $path = '/'; if(!empty($this->params['pass'])){ $path = implode('/', $this->params['pass']); } $this->Folders->recursive = 2; $folders = $this->Folders->find( 'all', array( 'fields' => array( ), 'conditions' => array( 'path' => $path ), 'order' => array( 'name' => 'ASC' ) ) ); $this->Files->recursive = 2; $files = $this->Files->find( 'all', array( 'fields' => array( ), 'conditions' => array( 'path' => $path ), 'order' => array( 'name' => 'ASC' ) ) ); $this->set(compact('files', 'folders')); } public function admin_view() { if(!empty($this->params['pass'])){ $path = implode('/', $this->params['pass']); } if (!$path || !is_file(APP.$path)) { $this->notice( __('Please select a file first', true), array( 'level' => 'error', 'redirect' => true ) ); } $this->set('path', APP.$path); } public function admin_download($file = null) { if (!$file) { $this->notice( __('Please select a file first', true), array( 'level' => 'error', 'redirect' => true ) ); } // @todo mediaViews } public function admin_delete($file = null) { if (!$file) { $this->Infinitas->noticeInvalidRecord(); } if ($this->FileManager->delete($file)) { $this->Infinitas->noticeDeleted(); } $this->Infinitas->noticeNotDeleted(); } }<file_sep><?php /* * Short Description / title. * * Overview of what the file does. About a paragraph or two * * Copyright (c) 2010 <NAME> ( dogmatic69 ) * * @filesource * @copyright Copyright (c) 2010 <NAME> ( dogmatic69 ) * @link http://www.infinitas-cms.org * @package {see_below} * @subpackage {see_below} * @license http://www.opensource.org/licenses/mit-license.php The MIT License * @since {check_current_milestone_in_lighthouse} * * @author {your_name} * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. */ echo $this->Html->link( __('logout', true), array( 'plugin' => 'users', 'controller' => 'users', 'action' => 'logout' ), array( 'class' => 'niceLink' ) ); ?> <div id="login-box"> <div class="siteLogout"> <?php echo sprintf(__('Welcome back to %s', true), Configure::read('Website.name')); echo $this->Html->link(__('Logout', true), array('plugin' => 'users', 'controller' => 'users', 'action' => 'logout'), array('class' => 'niceLink')); ?> </div> <div class="login-links"> <?php echo $this->Html->link( __('Manage Your profile', true), array( 'plugin' => 'users', 'controller' => 'users', 'action' => 'view', $this->Session->read('Auth.User.id') ) ), '<br/>', $this->Html->link( __('See whats going on', true), array( 'plugin' => 'feed', 'controller' => 'feeds', 'action' => 'index' ) ); ?> </div> </div> <file_sep><?php /** * Static Page admin edit * * Editing current static pages * * Copyright (c) 2010 <NAME> ( dogmatic69 ) * * @filesource * @copyright Copyright (c) 2010 <NAME> ( dogmatic69 ) * @link http://www.infinitas-cms.org * @package management * @subpackage management.views.admin_edit * @license http://www.opensource.org/licenses/mit-license.php The MIT License * @since 0.7a * * @author dakota * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. */ echo $this->Form->create('Page'); echo $this->Infinitas->adminEditHead(); echo $this->Form->input('Page.file_name'); echo $this->Core->wysiwyg('Page.body'); echo $this->Form->end(); ?><file_sep><?php /* SVN FILE: $Id$ */ /* MeioUpload schema generated on: 2010-09-18 18:09:21 : 1284828621*/ class MeioUploadSchema extends CakeSchema { var $name = 'MeioUpload'; function before($event = array()) { return true; } function after($event = array()) { } } ?><file_sep><?php $map = array( 1 => array( '000008_libs' => 'R4c94edcd4680495f801a78d86318cd70'), ); ?><file_sep><?php /** * lockable behavior. * * This behavior auto binds to any model and will lock a row when it is being * edited by a user. only that user will be able to edit it while it is locked. * This will avoid any issues with many people working on content at the same * time * * Copyright (c) 2010 <NAME> ( dogmatic69 ) * * @filesource * @copyright Copyright (c) 2010 <NAME> ( dogmatic69 ) * @link http://www.infinitas-cms.org * @package Infinitas.locks * @subpackage Infinitas.locks.behaviors.lockable * @license http://www.opensource.org/licenses/mit-license.php The MIT License * @since 0.5a * * @author <NAME> ( dogmatic69 ) * @author Ceeram * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. */ class LockableBehavior extends ModelBehavior { /** * Contain default settings. * * @var array * @access protected */ public $_defaults = array( ); /** * * @param object $Model Model using the behavior * @param array $settings Settings to override for model. * @access public * @return void */ public function setup($Model, $config = null) { if($Model->alias == 'Lock' || !$Model->Behaviors->enabled('Locks.Lockable')){ return; } $Model->bindModel( array( 'hasOne' => array( 'Lock' => array( 'className' => 'Locks.Lock', 'foreignKey' => 'foreign_key', 'conditions' => array( 'Lock.class' => $Model->plugin . '.' . $Model->alias ), 'fields' => array( 'Lock.id', 'Lock.created', 'Lock.user_id' ), 'dependent' => true ) ) ), false ); if(rand(0, 50) == 0){ $this->__gc($Model); } if (is_array($config)) { $this->settings[$Model->alias] = array_merge($this->_defaults, $config); } else { $this->settings[$Model->alias] = $this->_defaults; } } /** * Clear out old locks * * This will delete any locks that have expired (configured in Locks.timeout) * so that things do not remain locked when its not needed. */ private function __gc($Model){ ClassRegistry::init('Locks.Lock')->clearOldLocks(); } /** * Locking rows. * * After a row has been pulled from the database this will record the locked * state with the user that locked it. if a user reads a row that they * locked the date will be updated. if a different user tries to read this * row nothing will be retured and the component will take over displaying * an error message * * @var object $Model the current model * @var array $results the data that was found * @var bool $primary is it the main model doing the find */ public function afterFind($Model, $results, $primary){ if($Model->findQueryType != 'first' || !$primary || empty($results) || !isset($Model->Lock)){ return $results; } $class = Inflector::camelize($Model->plugin).'.'.$Model->alias; if(isset($results[0][$Model->alias][$Model->primaryKey])){ $this->user_id = CakeSession::read('Auth.User.id'); $lock = $Model->Lock->find( 'all', array( 'conditions' => array( 'Lock.foreign_key' => $results[0][$Model->alias][$Model->primaryKey], 'Lock.class' => $class, 'Lock.created > ' => date('Y-m-d H:m:s', strtotime(Configure::read('Locks.timeout'))) ), 'contain' => array( 'Locker' ) ) ); if(isset($lock[0]['Lock']['user_id']) && $this->user_id == $lock[0]['Lock']['user_id']){ $Model->Lock->delete($lock[0]['Lock']['id']); $lock = array(); } if(!empty($lock)){ return $lock; } $lock['Lock'] = array( 'foreign_key' => $results[0][$Model->alias][$Model->primaryKey], 'class' => $class, 'user_id' => $this->user_id ); $Model->Lock->create(); if($Model->Lock->save($lock)){ return $results; } } return $results; } /** * contain the lock * * before a find is made the Lock model is added to contain so that * the lock details are available in the view to show if something is locked * or not. * * @param object $model referenced model * @param array $query the query being done * * @return array the find query data */ public function beforeFind($Model, $query) { if($Model->findQueryType == 'count' || !isset($Model->Lock)){ return $query; } $query['contain'][$Model->Lock->alias] = array('Locker'); if(isset($query['recursive']) && $query['recursive'] == -1){ $query['recursive'] = 0; } call_user_func(array($Model, 'contain'), $query['contain']); return $query; } /** * unlock after the save * * once the row has been saved, the lock can be removed so that other users * may have accesss to the data. * * @param object $model referenced model * @param bool $created if its a new row * * @return bool true on succsess false if not. */ public function afterSave($Model, $created){ if($created || !isset($Model->Lock) || !is_object($Model->Lock)){ return parent::afterSave(&$Model, $created); } $Model->Lock->deleteAll( array( 'Lock.foreign_key' => $Model->data[$Model->alias][$Model->primaryKey], 'Lock.class' => $Model->plugin.'.'.$Model->alias, 'Lock.user_id' => CakeSession::read('Auth.User.id') ) ); parent::afterSave(&$Model, $created); } }<file_sep><?php class LibsEvents extends AppEvents{ public function onSetupConfig(){ return Configure::load('libs.images') && Configure::load('libs.config'); } public function onSetupExtensions(){ return array( 'json' ); } public function onAttachBehaviors($event) { if(is_subclass_of($event->Handler, 'Model') && isset($event->Handler->_schema) && is_array($event->Handler->_schema)) { // attach the expandable (eva) behavior if there is a table for it $attributesTable = Inflector::singularize($event->Handler->tablePrefix.$event->Handler->table).'_attributes'; if(in_array($attributesTable, $event->Handler->getTables($event->Handler->useDbConfig))){ $event->Handler->bindModel( array( 'hasMany' => array( $event->Handler->name.'Attribute' => array( 'className' => Inflector::camelize($attributesTable), 'foreignKey' => Inflector::underscore($event->Handler->name).'_id', 'dependent' => true ) ) ), false ); $event->Handler->Behaviors->attach('Libs.Expandable'); } if ($event->Handler->hasField('slug') && !$event->Handler->Behaviors->enabled('Libs.Sluggable')) { $event->Handler->Behaviors->attach( 'Libs.Sluggable', array( 'label' => array($event->Handler->displayField) ) ); } if ($event->Handler->hasField('ordering') && !$event->Handler->Behaviors->enabled('Libs.Sequence')) { $event->Handler->Behaviors->attach('Libs.Sequence'); } if ($event->Handler->hasField('rating') && !$event->Handler->Behaviors->enabled('Libs.Rateable')) { $event->Handler->Behaviors->attach('Libs.Rateable'); } if ($event->Handler->hasField('lft') && $event->Handler->hasField('rght') && !$event->Handler->Behaviors->enabled('Tree')) { $event->Handler->Behaviors->attach('Tree'); } if(!$event->Handler->Behaviors->enabled('Libs.Validation')){ $event->Handler->Behaviors->attach('Libs.Validation'); } } } public function onRequireComponentsToLoad($event){ return array( 'Libs.Infinitas', 'Session','RequestHandler', 'Auth', 'Acl', 'Security', // core general things from cake 'Libs.MassAction' ); } public function onRequireHelpersToLoad($event){ return array( 'Html', 'Form', 'Javascript', 'Session', 'Time', // core general things from cake 'Libs.Infinitas' => true ); } public function onRequireCssToLoad(){ return '/assets/css/jquery_ui'; } }<file_sep><?php /* SVN FILE: $Id$ */ /* Migrations schema generated on: 2010-09-18 18:09:21 : 1284828621*/ class MigrationsSchema extends CakeSchema { var $name = 'Migrations'; function before($event = array()) { return true; } function after($event = array()) { } } ?><file_sep><?php /* AppHelper Test cases generated on: 2010-12-14 01:12:39 : 1292290119*/ App::import('Helper', 'AppHelper'); class AppHelperHelperTestCase extends CakeTestCase { function startTest() { $this->AppHelper = new AppHelperHelper(); } function endTest() { unset($this->AppHelper); ClassRegistry::flush(); } }<file_sep><?php /** * Core moving records view * * display a page with a list of records that are being moved and the * places they can be moved to. * * Copyright (c) 2010 <NAME> ( dogmatic69 ) * * @filesource * @copyright Copyright (c) 2010 <NAME> ( dogmatic69 ) * @link http://www.infinitas-cms.org * @package libs * @subpackage libs.views.global.move * @license http://www.opensource.org/licenses/mit-license.php The MIT License * @since 0.7a * * @author <NAME> ( dogmatic69 ) * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. */ echo $this->Form->create($model, array('url' => '/'.$this->params['url']['url'])); $massActions = $this->Infinitas->massActionButtons( array( 'move' ) ); echo $this->Infinitas->adminIndexHead(null, $massActions); ?> <div class="table"> <table class="listing" cellpadding="0" cellspacing="0"> <?php $ignore = array( 'Locker' ); $belongs = $habtm = array(); foreach($relations['belongsTo'] as $alias => $belongsTo){ if(in_array($alias, $ignore)){ continue; } $belongs[] = __(prettyName($alias), true); } foreach($relations['hasAndBelongsToMany'] as $alias => $hasAndBelongsToMany){ if(in_array($alias, $ignore)){ continue; } $habtm[] = __(prettyName(Inflector::pluralize($alias)), true); } echo $this->Infinitas->adminTableHeader( array_merge( array( '' => array( 'class' => 'first', 'style' => 'width:25px;' ), __('Record', true) => array( 'style' => 'width:150px;' ) ), $belongs, $habtm ) ); $i = 0; foreach($rows as $row){ ?> <tr class="<?php echo $this->Infinitas->rowClass(); ?>"> <td><?php echo $this->Form->checkbox($model.'.'.$row[$model][$modelSetup['primaryKey']]); ?>&nbsp;</td> <td> <?php echo $row[$model][$modelSetup['displayField']]; ?> </td> <?php foreach($relations['belongsTo'] as $alias => $belongsTo){ if(in_array($alias, $ignore)){ continue; } if(isset(${strtolower(Inflector::pluralize($alias))}[$row[$model][$belongsTo['foreignKey']]])){ echo '<td>'.${strtolower(Inflector::pluralize($alias))}[$row[$model][$belongsTo['foreignKey']]].'</td>'; } else{ echo '<td>'.__('Not set', true).'</td>'; } } foreach($relations['hasAndBelongsToMany'] as $alias => $hasAndBelongsToMany){ echo '<td>'.__('Some tags', true).'</td>'; } $i++; ?> </tr> <?php } ?> </table> </div> <?php echo $this->Form->hidden('Move.model', array('value' => $model)); echo $this->Form->hidden('Move.confirmed', array('value' => 1)); echo $this->Form->hidden('Move.referer', array('value' => $referer)); foreach($relations['belongsTo'] as $alias => $belongsTo){ if(in_array($alias, $ignore)){ continue; } ?><div class="info"> <h3><?php echo __(prettyName($alias), true); ?></h3><?php echo $this->Form->input('Move.'.$belongsTo['foreignKey'], array('label' => false, 'empty' => __(Configure::read('Website.empty_select'), true))); ?></div><?php } foreach($relations['hasAndBelongsToMany'] as $alias => $belongsTo){ ?><div class="info"> <h3><?php echo __(prettyName(Inflector::pluralize($alias)), true); ?></h3><?php echo $this->Form->input('Move.'.$alias, array('label' => false, 'multiple' => 'multiple', 'options' => ${strtolower($alias)})); ?></div><?php } echo $this->Form->end(); ?><file_sep><?php /** * @brief Comment Model class file handles comment CRUD. * * This is the model that handles comment saving and other CRUD actions, the * commentable behavior will auto relate and attach this model to the models * that need it. If your tables do not allow this you can do it yourself using * $hasMany param in your model * * The model has a few methods for getting some data like new comments, pending * and other thigns that may be of use in an application * * @copyright Copyright (c) 2009 <NAME> ( dogmatic69 ) * @link http://infinitas-cms.org * @package Infinitas.Comments.models * @license http://www.opensource.org/licenses/mit-license.php The MIT License * @since 0.8a * * @author dogmatic69 * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. */ class Comment extends CommentsAppModel { /** * the model name * * @var string * @access public */ public $name = 'Comment'; /** * behaviors that are attached to the model. * * @var array * @access public */ public $actsAs = array( 'Libs.Expandable' ); /** * relations for the model * * @var array * @access public */ public $hasMany = array( 'CommentAttribute' => array( 'className' => 'Comments.CommentAttribute' ) ); /** * @copydoc AppModel::__construct() */ public function __construct($id = false, $table = null, $ds = null) { parent::__construct($id, $table, $ds); $this->validate = array( 'email' => array( 'notEmpty' => array( 'rule' => 'notEmpty', 'message' => __('Please enter your email address', true) ), 'email' => array( 'rule' => array('email'), 'message' => __('Please enter a valid email address', true) ) ), 'comment' => array( 'notEmpty' => array( 'rule' => 'notEmpty', 'message' => __('Please enter your comments', true) ) ) ); } /** * @brief hack to get the attributes for comments * * @todo this is a hack to get the atributes in the comment, this should * be handled in the attributes behavior but cake does not do model callbacks * 3 relations deep * * @param array $results the data found * @param bool $primary is this the primary model doing the find * @access public * * @return array the results after bing formatted */ public function afterFind($results, $primary){ if(isset($results[0][0]['count'])){ return $results; } $base = array_merge( array('schema' => $this->schema()), array('with' => 'CommentAttribute', 'foreignKey' => $this->hasMany['CommentAttribute']['foreignKey']) ); if (!Set::matches('/' . $base['with'], $results)) { return $results; } if(isset($results[0]) || $primary){ foreach ($results as $k => $item) { foreach ($item[$base['with']] as $field) { $results[$k][$field['key']] = $field['val']; } unset($results[$k][$base['with']]); } } else{ foreach ($results[$base['with']] as $field) { $results[$field['key']] = $field['val']; } } return $results; } /** * @brief get comments by user * * Find all comments that a particulat user has created with a limit of * $limit * * @param string $user_id the users id * @param int $limit the max number of records to get * @access public * * @return array the comments that were found */ public function getUsersComments($user_id = null, $limit = 5){ $comments = $this->find( 'all', array( 'conditions' => array( 'Comment.user_id' => $user_id ), 'order' => array( 'Comment.created' => 'asc' ) ) ); return $comments; } /** * @brief get some stats for notices in admin * * Find the number of comments that are pending and active so admin will * be able to take action. * * @param string $class the model class that the comments should be in * eg blog.post for blog comments * @access public * * @return array */ public function getCounts($class = null) { if (!$class) { return false; } $counts = Cache::read('comments_count_' . $class); if ($counts !== false) { return $counts; } $counts['active'] = $this->find( 'count', array( 'conditions' => array( 'Comment.active' => 1, 'Comment.class' => $class ), 'contain' => false ) ); $counts['pending'] = $this->find( 'count', array( 'conditions' => array( 'Comment.active' => 0, 'Comment.class' => $class ), 'contain' => false ) ); Cache::write('comments_count_' . $class, $counts, 'blog'); return $counts; } /** * @brief get a list of all the models that have comments * * @todo add cache * * @return array list of model classes */ public function getUniqueClassList(){ $this->displayField = 'class'; $classes = $this->find( 'list', array( 'group' => array( 'Comment.class' ), 'order' => array( 'Comment.class' => 'asc' ) ) ); if(empty($classes)){ return array(); } return array_combine($classes, $classes); } /** * @brief get a list of the latest comments * * used in things like comment wigets etc. will get a list of comments * from the site. * * @param bool $all all or just active * @param int $limit the msx number of comments to get * @access public * * @return array the comments found */ public function latestComments($all = true, $limit = 10){ $cacheName = cacheName('latest_comments_', array($all, $limit)); $comments = Cache::read($cacheName, 'core'); if (!empty($comments)) { return $comments; } $conditions = array(); if (!$all) { $conditions = array('Comment.active' => 1); } $comments = $this->find( 'all', array( 'conditions' => $conditions, 'limit' => (int)$limit, 'order' => array( 'Comment.created' => 'DESC' ) ) ); Cache::write($cacheName, $comments, 'core'); return $comments; } }<file_sep> <?php /* Infinitas Test cases generated on: 2010-03-13 14:03:31 : 1268484451*/ App::import('Behavior', 'libs.Validation'); class ValidationBehaviorTestCase extends CakeTestCase { public $fixtures = array( 'plugin.users.user', ); public function startTest() { $this->User = ClassRegistry::init('Users.User'); } public function endTest() { unset($this->Infinitas); ClassRegistry::flush(); } /** * check validation is attached */ public function testValidationAttached(){ $this->assertTrue($this->User->Behaviors->attached('Validation')); } public function testValidateJson(){ $this->User->validate = array( 'field_1' => array( 'validateJson' => array( 'rule' => 'validateJson', 'message' => 'thats not json' ) ) ); $expected = array('field_1' => 'thats not json'); $data['User']['field_1'] = 'foo'; $this->User->set($data); $this->User->validates(); $this->assertEqual($this->User->validationErrors, $expected); $data['User']['field_1'] = ''; $this->User->set($data); $this->User->validates(); $this->assertEqual($this->User->validationErrors, $expected); $data['User']['field_1'] = json_encode(array('asd' => 'meh')); $this->User->set($data); $this->User->validates(); $this->assertEqual($this->User->validationErrors, array()); } /** * test either or */ public function testValidateEitherOr(){ $this->User->validate = array( 'field_1' => array( 'validateEitherOr' => array( 'rule' => array('validateEitherOr', array('field_1', 'field_2')), 'message' => 'pick one, only one' ) ) ); $expected = array('field_1' => 'pick one, only one'); /** * invalid */ $data['User']['field_1'] = 'foo'; $data['User']['field_2'] = 'bar'; $this->User->set($data); $this->User->validates(); $this->assertEqual($this->User->validationErrors, $expected); /** * valid */ $data['User'] = array(); $this->User->create(); $data['User']['field_1'] = 'foo'; $this->User->set($data); $this->User->validates(); $this->assertEqual($this->User->validationErrors, array()); $data['User'] = array(); $this->User->create(); $data['User']['field_2'] = 'bar'; $this->User->set($data); $this->User->validates(); $this->assertEqual($this->User->validationErrors, array()); $data['User'] = array(); $this->User->create(); $this->User->set($data); $this->User->validates(); $this->assertEqual($this->User->validationErrors, array()); /** * force one to be selected */ $this->User->validate['field_1']['validateEitherOr']['required'] = true; $data['User'] = array(); $this->User->create(); $data['User']['field_1'] = ''; $data['User']['field_2'] = ''; $this->User->set($data); $this->User->validates(); $this->assertEqual($this->User->validationErrors, $expected); $data['User'] = array(); $this->User->create(); $data['User']['field_1'] = ''; $data['User']['field_2'] = 'bar'; $this->User->set($data); $this->User->validates(); $this->assertEqual($this->User->validationErrors, array()); } /** * tests is url or absolute path */ public function testValidateUrlOrAbsolute(){ $this->User->validate = array( 'url' => array( 'validateUrlOrAbsolute' => array( 'rule' => 'validateUrlOrAbsolute', 'message' => 'not url or absolute path' ) ) ); $expected = array('url' => 'not url or absolute path'); /** * invalid */ $data['User']['url'] = 'this/is/not/an/absolute.path'; $this->User->set($data); $this->User->validates(); $this->assertEqual($this->User->validationErrors, $expected); $data['User']['url'] = 'http:/this.is/an/url.ext'; $this->User->set($data); $this->User->validates(); $this->assertEqual($this->User->validationErrors, $expected); /** * valid */ $data['User']['url'] = '/this/is/an/absolute.path'; $this->User->set($data); $this->User->validates(); $this->assertEqual($this->User->validationErrors, array()); $data['User']['url'] = 'http://this.is/an/url.ext'; $this->User->set($data); $this->User->validates(); $this->assertEqual($this->User->validationErrors, array()); $data['User']['url'] = 'ftp://this.is/an/url.ext'; $this->User->set($data); $this->User->validates(); $this->assertEqual($this->User->validationErrors, array()); } /** * tests comparing passwords */ public function testValidateComparePasswords(){ $this->User->validate = array( 'password' => array( 'validateCompareFields' => array( 'rule' => array('validateCompareFields', array('password', 'password_match')), 'message' => 'fields dont match' ) ) ); $data['User']['password'] = 'abc'; $data['User']['password_match'] = 'xyz'; $this->User->set($data); $this->User->validates(); $expected = array('password' => 'fields dont match'); $this->assertEqual($this->User->validationErrors, $expected); $data['User']['password'] = Security::hash('abc', null, true); $this->User->set($data); $this->User->validates(); $this->assertEqual($this->User->validationErrors, $expected); $data['User']['password_match'] = 'abc'; $this->User->set($data); $this->User->validates(); $this->assertEqual($this->User->validationErrors, array()); } /** * test comparing normal fields */ public function testCompareFields(){ $this->User->validate = array( 'field_1' => array( 'validateCompareFields' => array( 'rule' => array('validateCompareFields', array('field_1', 'field_2')), 'message' => 'fields dont match' ) ) ); $data['User']['field_1'] = 'abc'; $data['User']['field_2'] = 'xyz'; $this->User->set($data); $this->User->validates(); $expected = array('field_1' => 'fields dont match'); $this->assertEqual($this->User->validationErrors, $expected); $data['User']['field_2'] = 'abc'; $this->User->set($data); $this->User->validates(); $this->assertEqual($this->User->validationErrors, array()); } }<file_sep><?php /* * Short Description / title. * * Overview of what the file does. About a paragraph or two * * Copyright (c) 2010 <NAME> ( dogmatic69 ) * * @filesource * @copyright Copyright (c) 2010 <NAME> ( dogmatic69 ) * @link http://www.infinitas-cms.org * @package {see_below} * @subpackage {see_below} * @license http://www.opensource.org/licenses/mit-license.php The MIT License * @since {check_current_milestone_in_lighthouse} * * @author {your_name} * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. */ class VisitorComponent extends InfinitasComponent{ public function initialize(&$controller, $settings = array()){ $this->Controller =& $controller; if($this->Controller->Session->read('Auth.User.id')){ $User = ClassRegistry::init('Users.User'); $User->unbindModel( array( 'belongsTo' => array_keys($User->belongsTo), 'hasOne' => array_keys($User->hasOne) ) ); $User->updateAll( array('User.last_click' => '\''.date('Y-m-d H:i:s').'\''), array('User.id' => $this->Controller->Session->read('Auth.User.id')) ); } } }<file_sep><?php class ContentableBehavior extends ModelBehavior{ /** * Settings initialized with the behavior * * @access public * @var array */ public $defaults = array(); /** * Contain settings indexed by model name. * * @var array * @access private */ private $__settings = array(); /** * Initiate behaviour for the model using settings. * * @param object $Model Model using the behaviour * @param array $settings Settings to override for model. * @access public */ public function setup($Model, $settings = array()) { $default = $this->defaults; if (!isset($this->__settings[$Model->alias])) { $this->__settings[$Model->alias] = $default; } $this->__settings[$Model->alias] = array_merge($this->__settings[$Model->alias], (array)$settings); $Model->bindModel( array( 'hasOne' => array( 'GlobalContent' => array( 'className' => 'Contents.GlobalContent', 'foreignKey' => 'foreign_key', 'conditions' => array( 'or' => array( 'GlobalContent.model' => $Model->plugin . '.' . $Model->alias ) ), 'dependent' => true ) ) ), false ); $Model->Group = $Model->GlobalContent->Group; $Model->Layout = $Model->GlobalContent->GlobalLayout; } /** * Auto contain the needed relations to the find * * @param object $Model the model doing the find * @param array $query the conditions of the find * @return array the modified query */ public function beforeFind($Model, $query) { if($Model->findQueryType == 'count'){ return $query; } $query['contain']['GlobalContent'] = array( 'fields' => array( 'GlobalContent.id', 'GlobalContent.model', 'GlobalContent.foreign_key', 'GlobalContent.title', 'GlobalContent.slug', 'GlobalContent.body', 'GlobalContent.meta_keywords', 'GlobalContent.meta_description', 'GlobalContent.group_id', 'GlobalContent.layout_id', 'GlobalContent.created', 'GlobalContent.modified' ), 'GlobalLayout', 'Group' ); if(isset($query['recursive']) && $query['recursive'] == -1){ $query['recursive'] = 0; } call_user_func(array($Model, 'contain'), $query['contain']); return $query; } /** * Format the data after the find to make it look like a normal relation * * @param object $Model the model that did the find * @param array $results the data from the find * @param bool $primary is it this model doing the query * * @return array the modified data from the find */ public function afterFind($Model, $results, $primary = false) { parent::afterFind($Model, $results, $primary); if($Model->findQueryType == 'list' || $Model->findQueryType == 'count' || empty($results)){ return $results; } foreach($results as $k => $result){ if(isset($results[$k]['GlobalContent']['GlobalLayout'])){ $results[$k]['Layout'] = $results[$k]['GlobalContent']['GlobalLayout']; } if(isset($results[$k]['GlobalContent']['Group'])){ $results[$k]['Group'] = $results[$k]['GlobalContent']['Group']; } unset($results[$k]['GlobalContent']['GlobalLayout'], $results[$k]['GlobalContent']['Group']); if(isset($results[$k]['GlobalContent'])){ $results[$k][$Model->alias] = array_merge($results[$k]['GlobalContent'], $results[$k][$Model->alias]); } } return $results; } /** * make sure the model is set for the record to be able to link * * @param object $Model the model that is doing the save * @return bool true to save, false to skip */ public function beforeSave($Model) { if(!isset($Model->data['GlobalContent']['model']) || empty($Model->data['GlobalContent']['model'])){ $Model->data['GlobalContent']['model'] = $this->__getModel($Model); } return isset($Model->data['GlobalContent']['model']) && !empty($Model->data['GlobalContent']['model']); } public function getContentId($Model, $slug){ $id = array(); $id = $Model->GlobalContent->find( 'first', array( 'fields' => array( $Model->GlobalContent->alias . '.foreign_key' ), 'conditions' => array( 'or' => array( $Model->GlobalContent->alias . '.id' => $slug, 'and' => array( $Model->GlobalContent->alias . '.model' => $Model->plugin . '.' . $Model->alias, $Model->GlobalContent->alias . '.slug' => $slug ) ) ) ) ); return current(Set::extract('/' . $Model->GlobalContent->alias . '/foreign_key', $id)); } private function __getModel($Model){ return Inflector::camelize($Model->plugin) . '.' . $Model->alias; } }<file_sep><?php /* * Short Description / title. * * Overview of what the file does. About a paragraph or two * * Copyright (c) 2010 <NAME> ( dogmatic69 ) * * @filesource * @copyright Copyright (c) 2010 <NAME> ( dogmatic69 ) * @link http://www.infinitas-cms.org * @package {see_below} * @subpackage {see_below} * @license http://www.opensource.org/licenses/mit-license.php The MIT License * @since {check_current_milestone_in_lighthouse} * * @author {your_name} * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. */ echo $this->Html->link( __('Login', true), array( 'plugin' => 'users', 'controller' => 'users', 'action' => 'login', 'TB_inline?height=185&width=600&inlineId=login-box' ), array( 'class' => 'niceLink thickbox' ) ); ?> <div id="login-box"> <div class="siteLogin"> <?php echo $this->Form->create('User', array('url' => array('plugin' => 'users', 'controller' => 'users', 'action' => 'login'))); echo sprintf('<b>%s</b>', __('Members Login', true)); echo $this->Form->input('username', array('label' => false, 'value' => __('Username', true))); echo $this->Form->input('password', array('label' => false, 'value' => __('Password', true))); echo $this->Form->submit('Login', array('class' => 'niceLink')); echo $this->Form->end(); $links = array(''); $links[] = $this->Html->link( __('Forgot your password', true), array( 'plugin' => 'users', 'controller' => 'users', 'action' => '<PASSWORD>password' ) ); $links[] = $this->Html->link( __('Create an account', true), array( 'plugin' => 'users', 'controller' => 'users', 'action' => 'register' ) ); echo implode('<br/>', $links); ?> </div> <div class="oAuthLogin"> <?php $providers = $this->Event->trigger('oauthProviders'); foreach($providers['oauthProviders'] as $provider){ if(isset($provider['element']) && isset($provider['config'])){ echo $this->element((string)$provider['element'], (array)$provider['config']); } } ?> <p><?php echo __('You may us the above logins if you would like to become a member, or your account is already linked.', true); ?></p> </div> </div> <file_sep><?php /** * Static Page Manager * * Creating and maintainig static pages * * Copyright (c) 2010 <NAME> ( dogmatic69 ) * * @filesource * @copyright Copyright (c) 2010 <NAME> ( dogmatic69 ) * @link http://www.infinitas-cms.org * @package management * @subpackage management.controllers.pages * @license http://www.opensource.org/licenses/mit-license.php The MIT License * @since 0.7a * * @author dakota * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. */ class PagesController extends ManagementAppController{ var $name = 'Pages'; function admin_index(){ $pages = $this->paginate(null, $this->Filter->filter); $filterOptions = $this->Filter->filterOptions; $filterOptions['fields'] = array( 'name', 'type', 'active' => (array)Configure::read('CORE.active_options') ); $path = APP . str_replace(array('/', '\\'), DS, Configure::read('CORE.page_path')); $writable = is_writable($path); $this->set(compact('pages', 'filterOptions', 'writable', 'path')); } function admin_add(){ if (!empty($this->data)){ $this->data['Page']['file_name'] = low(Inflector::slug($this->data['Page']['name'])); if ($this->Page->save($this->data)){ $this->Infinitas->noticeSaved(); } $this->Infinitas->noticeNotSaved(); } } function admin_edit($filename){ if (!$filename){ $this->Infinitas->noticeInvalidRecord(); } if (!empty($this->data)){ if ($this->Page->save($this->data)){ $this->Infinitas->noticeSaved(); } $this->Infinitas->noticeNotSaved(); } if ($filename && empty($this->data)){ $this->data = $this->Page->read(null, $filename); } } function __massGetIds($data) { if (in_array($this->__massGetAction($this->params['form']), array('add','filter'))) { return null; } $ids = array(); foreach($data as $id => $selected) { if ($selected) { $ids[] = $selected['id']; } } if (empty($ids)) { $this->Infinitas->noticeInvalidRecord(); } return $ids; } function __massActionDelete($ids) { $deleted = true; foreach($ids as $id){ $deleted = $deleted && $this->Page->delete($id); } if ($delete) { $this->Infinitas->noticeDeleted(); } else{ $this->Infinitas->noticeNotDeleted(); } } }<file_sep><?php /* AppHelper Test cases generated on: 2010-12-14 01:12:39 : 1292290119*/ App::import('Controller', 'AppController'); class TestAppControllerController extends AppController { var $autoRender = false; function redirect($url, $status = null, $exit = true) { $this->redirectUrl = $url; } } class AppControllerTestCase extends CakeTestCase { function startTest() { $this->AppController = new AppController(); $this->AppController->constructClasses(); } function endTest() { unset($this->AppController); ClassRegistry::flush(); } }<file_sep><?php /* * Short Description / title. * * Overview of what the file does. About a paragraph or two * * Copyright (c) 2010 <NAME> ( dogmatic69 ) * * @filesource * @copyright Copyright (c) 2010 <NAME> ( dogmatic69 ) * @link http://www.infinitas-cms.org * @package Infinitas.routes * @subpackage Infinitas.routes.events * @license http://www.opensource.org/licenses/mit-license.php The MIT License * @since 0.8a * * @author dogmatic69 * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. */ class InfinitasRouting extends Object{ public function setup(){ InfinitasRouting::__registerExtensions(); InfinitasRouting::__buildRoutes(); } /** * Build routes for the app. * * Allows other plugins to register routes to be used in the app and builds * the routes from the database. */ private function __buildRoutes(){ EventCore::trigger(new StdClass(), 'setupRoutes'); //TODO: Figure out cleaner way of doing this. If infinitas is not installed, this throws a datasource error. $databaseConfig = APP.'config'.DS.'database.php'; if(file_exists($databaseConfig) && filesize($databaseConfig) > 0) { $routes = Classregistry::init('Routes.Route')->getRoutes(); if (!empty($routes)) { foreach($routes as $route ){ if (false) { debugRoute($route); continue; } call_user_func_array(array('Router', 'connect'), $route['Route']); } } } } /** * Register extensions that are used in the app * * Call all plugins and see what extensions are need, this is cached */ private function __registerExtensions(){ $extensions = Cache::read('extensions', 'routes'); if($extensions === false){ $extensions = EventCore::trigger(new StdClass(), 'setupExtensions'); $_extensions = array(); foreach($extensions['setupExtensions'] as $plugin => $ext){ $_extensions = array_merge($_extensions, (array)$ext); } $extensions = array_flip(array_flip($_extensions)); Cache::write('extentions', $extensions, 'routes'); unset($_extensions); } call_user_func_array(array('Router', 'parseExtensions'), $extensions); } }<file_sep><?php /* Vcf Test cases generated on: 2010-12-14 13:12:02 : 1292334962*/ App::import('Helper', 'contact.Vcf'); class VcfHelperTestCase extends CakeTestCase { function startTest() { $this->Vcf =& new VcfHelper(); } function endTest() { unset($this->Vcf); ClassRegistry::flush(); } } ?><file_sep><div class="dashboard"> <h1><?php __('Missing Controller'); ?></h1> <p class="error"> <strong><?php __('Error'); ?>: </strong> <?php printf(__('%s could not be found.', true), '<em>' . $controller . '</em>'); ?> </p> <p class="error"> <strong><?php __('Error'); ?>: </strong> <?php printf(__('Create the class %s below in file: %s', true), '<em>' . $controller . '</em>', APP_DIR . DS . 'controllers' . DS . Inflector::underscore($controller) . '.php'); ?> </p> <pre> &lt;?php class <?php echo $controller;?> extends AppController { var $name = '<?php echo $controllerName;?>'; } ?&gt; </pre> </div><file_sep><?php /* GlobalComment Fixture generated on: 2010-12-13 17:12:34 : 1292259754 */ class CommentFixture extends CakeTestFixture { var $name = 'Comment'; var $table = 'global_comments'; var $fields = array( 'id' => array('type' => 'integer', 'null' => false, 'default' => NULL, 'length' => 10, 'key' => 'primary'), 'class' => array('type' => 'string', 'null' => false, 'default' => NULL, 'length' => 128, 'collate' => 'utf8_general_ci', 'charset' => 'utf8'), 'foreign_id' => array('type' => 'string', 'null' => false, 'default' => NULL, 'length' => 36, 'collate' => 'utf8_general_ci', 'charset' => 'utf8'), 'user_id' => array('type' => 'integer', 'null' => false, 'default' => '0', 'length' => 8), 'email' => array('type' => 'string', 'null' => false, 'default' => NULL, 'length' => 100, 'collate' => 'utf8_general_ci', 'charset' => 'utf8'), 'comment' => array('type' => 'text', 'null' => false, 'default' => NULL, 'collate' => 'utf8_general_ci', 'charset' => 'utf8'), 'active' => array('type' => 'boolean', 'null' => false, 'default' => NULL, 'key' => 'index'), 'rating' => array('type' => 'integer', 'null' => false, 'default' => NULL), 'points' => array('type' => 'integer', 'null' => false, 'default' => NULL), 'status' => array('type' => 'string', 'null' => true, 'default' => NULL, 'length' => 100, 'key' => 'index', 'collate' => 'utf8_general_ci', 'charset' => 'utf8'), 'created' => array('type' => 'datetime', 'null' => false, 'default' => NULL), 'indexes' => array('PRIMARY' => array('column' => 'id', 'unique' => 1), 'active' => array('column' => 'active', 'unique' => 0), 'status' => array('column' => 'status', 'unique' => 0)), 'tableParameters' => array('charset' => 'utf8', 'collate' => 'utf8_general_ci', 'engine' => 'InnoDB') ); var $records = array( array( 'id' => 3, 'class' => 'Blog.TestPost', 'foreign_id' => 1, 'user_id' => 0, 'email' => '<EMAIL>', 'comment' => ' blaa blaa blaa blaa blaa blaa blaa blaa blaa blaa blaa blaa some long comment user1 blaa blaa blaa blaa blaa blaa blaa blaa blaa blaa blaa blaa', 'active' => 1, 'rating' => 0, 'points' => 4, 'status' => 'approved', 'created' => '2010-10-04 01:19:32' ), array( 'id' => 332, 'class' => 'Blog.TestPost', 'foreign_id' => 1, 'user_id' => 0, 'email' => '<EMAIL>', 'comment' => ' blaa blaa blaa blaa blaa blaa blaa blaa blaa blaa blaa blaa another long comment by user2 blaa blaa blaa blaa blaa blaa blaa blaa blaa blaa blaa blaa', 'active' => 1, 'rating' => 0, 'points' => 4, 'status' => 'approved', 'created' => '2010-12-08 16:43:09' ), ); } ?><file_sep><?php class AssetsEventsTestCase extends CakeTestCase { public function startTest() { $this->Event = EventCore::getInstance(); } public function endTest() { unset($this->Event); ClassRegistry::flush(); } public function testStuff(){ $this->assertIsA($this->Event, 'EventCore'); $expected = array('requireHelpersToLoad' => array('assets' => array('Assets.Compress'))); $this->assertEqual($expected, $this->Event->trigger(new Object(), 'assets.requireHelpersToLoad')); } }<file_sep><?php $map = array( 1 => array( '000008_management' => 'R4c94edcd27f04a8d95f078d86318cd70'), ); ?><file_sep><?php /* * Short Description / title. * * Overview of what the file does. About a paragraph or two * * Copyright (c) 2010 <NAME> ( dogmatic69 ) * * @filesource * @copyright Copyright (c) 2010 <NAME> ( dogmatic69 ) * @link http://www.infinitas-cms.org * @package {see_below} * @subpackage {see_below} * @license http://www.opensource.org/licenses/mit-license.php The MIT License * @since {check_current_milestone_in_lighthouse} * * @author {your_name} * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. */ class ModuleLoaderHelper extends InfinitasHelper{ /** * Skip modules. * * Add the names of modules you want to skip to this var and they will not * be loaded. * * @var array */ public $moduleIgnoreOverload = array(); /** * Module Loader. * * This is used to load modules. it generates a wrapper div with the class * set as the module name for easy styleing, and will create a header if set * in the backend. * * @params string $position this is the possition that is to be loaded, can be anything from the database * @params bool $admin if true its a admin module that should be loaded. */ public function load($position = null, $admin = false){ if (!$position) { $this->errors[] = 'No position selected to load modules'; return false; } $modules = ClassRegistry::init('Modules.Module')->getModules($position, $admin); /** * @todo if no modules based on possition, possition is a module -> $this->loadModule($position) */ $currentRoute = Configure::read('CORE.current_route'); $out = '<div class="modules '.$position.'">'; foreach($modules as $module){ if ( ($module['Theme']['name'] != '' && $module['Theme']['name'] != $this->theme) || in_array($module['Module']['module'], $this->moduleIgnoreOverload) ) { //skip modules that are not for the current theme continue; } $params = $this->__getModuleParams($module, $admin); if($params === false){ continue; // from userland and its not active } $moduleOut = $this->loadModule($module['Module']['module'], $params); if (!empty($module['Route']) && is_object($currentRoute)){ foreach($module['Route'] as $route){ if ($route['url'] == $currentRoute->template) { $out .= $moduleOut; } } } else if (empty($module['Route'])) { $out .= $moduleOut; } } $out .= '</div>'; return $out; } /** * Load single modules. * * This is used by the core module loader, and to load single modules. This * can be handy when you just want to load a particular module inside a view. * * @params string $position this is the possition that is to be loaded, can be anything from the database * @params bool $admin if true its a admin module that should be loaded. */ public function loadModule($module = null, $params = array()){ if(!$module){ return false; } if($params == null){ $params = $this->__getModuleParams($module); } $class = isset($params['config']['class']) ? $params['config']['class'] : ''; $id = isset($params['config']['id']) ? $params['config']['id'] : ''; $moduleOut = '<div class="module '.str_replace('/', '-', $module).' '.$class.'">'; if ($params['title']) { $moduleOut .= '<h2><a id="'.$id.'" href="#">'.__($params['title'],true).'</a></h2>'; } if (!empty($module)) { $path = 'modules/'; $this->__getViewClass(); $moduleOut .= $this->View->element( $path.$module, $params, true ); } else if ($params['content']) { $moduleOut .= $params['content']; } $moduleOut .= '</div>'; return $moduleOut; } /** * Get the params for the module being loaded, If loadModule is called * from user land, they will not have the details of the module for it * to load properly, and instead of making them do the db call manualy, * it is done here automaticaly * * @param mixed $module string from userland, array (like find(first)) from core * @param bool $admin affects the path the module is loaded from. * * @return array the params for loading the module. */ private function __getModuleParams($module, $admin = null){ if(!$admin){ $admin = isset($this->params['admin']) ? $this->params['admin'] : false; } if(is_string($module)){ $module = ClassRegistry::init('Modules.Module')->getModule($module, $admin); if(empty($module)){ return false; } } return array( 'plugin' => $module['Module']['plugin'], 'title' => $module['Module']['show_heading'] ? $module['Module']['name'] : false, 'config' => $this->__getModuleConfig($module['Module']), 'content' => !empty($module['Module']['content']) ? $module['Module']['content'] : false, 'admin' => $admin ); } /** * Module Config. * * This method works out params from JSON data in the module. if there is something * wrong with the JSON code that is submitted it will return an empty array(), or it * will return an array with the config. * * @access protected * @params string $config some JSON data to be decoded. */ private function __getModuleConfig($config = ''){ if (empty($config['config'])) { return array(); } $json = json_decode($config['config'], true); if (!$json) { $this->errors[] = 'module ('.$config['name'].'): has no json'; return array(); } return $json; } private function __getViewClass(){ if(!$this->View){ $this->View = ClassRegistry::getObject('view'); } } } class ModuleTemplates{ public $parent = array( 'child' => 'child works', ); public $grandparent = array( 'parent' => array( 'child' => 'grandchild works', ), ); }<file_sep><?php $map = array( 1 => array( '000008_routes' => 'R4c94edce63b447ddb6b178d86318cd70'), ); ?><file_sep><div id="side_bar"> <ul> <li alt="Home"><?php echo $this->Html->image('status_bar/home.png', array('url' => '/')); ?>Home</li> </ul> <span class="jx-separator-left"></span> <ul> <li alt="Profile"><?php echo $this->Html->image('status_bar/profile.png', array('url' => '/me')); ?></li> <li alt="About"><?php echo $this->Html->image('status_bar/information.png', array('url' => '/about')); ?></li> <li alt="Contact"><?php echo $this->Html->image('status_bar/megaphone.png', array('url' => array('plugin' => 'contact', 'controller' => 'branches'))); ?></li> </ul> <span class="jx-separator-left"></span> <ul class="jx-bar-button-left"> <?php $shortUrl = ClassRegistry::init('ShortUrls.ShortUrl')->newUrl($this->here, true, $this->webroot); ?> <li alt="Share with the world" class="addthis_toolbox addthis_default_style"> <a href="http://www.addthis.com/bookmark.php?v=250&amp;username=xa-4c114e15110816c8" class="addthis_button_compact">Share</a> <span class="addthis_separator">|</span> <a class="addthis_button_facebook"></a> <a class="addthis_button_myspace"></a> <a class="addthis_button_google"></a> <a class="addthis_button_twitter"></a> <script type="text/javascript" src="http://s7.addthis.com/js/250/addthis_widget.js#username=xa-4c114e15110816c8"></script> </li> </ul> <span class="jx-separator-left"></span> <div></div> <ul class="jx-bar-button-right"> <li alt="Feed"><?php echo $this->Html->image('status_bar/feed.png', array('url' => str_replace('/thinkmoney', '', $this->here).'.rss')); ?></li> </ul> <span class="jx-separator-right"></span> <ul class="jx-bar-button-right"> <?php $items = $this->Session->read('Compare.Item');?> <li alt="Compare <?php echo count($items) > 0 ? ' ('.count($items).' '.__((count($items) == 1) ? 'items' : 'item', true).')' : ''; ?>"><?php echo $this->Html->image('status_bar/compare.png', array('url' => array('plugin' => 'compare', 'controller' => 'items', 'action' => 'view'))); ?></li> </ul> <span class="jx-separator-right"></span> </div><file_sep><?php /* SVN FILE: $Id$ */ /* Assets schema generated on: 2010-09-18 18:09:19 : 1284828619*/ class AssetsSchema extends CakeSchema { var $name = 'Assets'; function before($event = array()) { return true; } function after($event = array()) { } } ?><file_sep><div class="dashboard"> <h1><?php __('Missing Layout'); ?></h1> <p class="error"> <strong><?php __('Error'); ?>: </strong> <?php printf(__('The layout file %s can not be found or does not exist.', true), '<em>' . $file . '</em>'); ?> </p> <p class="error"> <strong><?php __('Error'); ?>: </strong> <?php printf(__('Confirm you have created the file: %s', true), '<em>' . $file . '</em>'); ?> </p> </div><file_sep><?php if($this->action == 'finish') { $grid = 'grid_12'; $hideSteps = true; } else { $grid = 'grid_8'; $hideSteps = false; } ?> <!DOCTYPE html> <html> <head> <title>Infinitas Installer :: <?php echo $title_for_layout; ?></title> <?php echo $this->Html->css('reset'); echo $this->Html->css('/assets/css/960gs/960'); echo $this->Html->css( '/installer/css/install' ); echo $scripts_for_layout; ?> </head> <body> <?php echo $this->Form->create('Install', array('id' => 'container', 'class' => 'container_12', 'url' => array('controller' => 'install', 'action' => 'index', $this->Wizard->activeStep()))) ?> <?php echo $this->Form->hidden('step', array('value' => $this->Wizard->activeStep())); ?> <h2 class="grid_12" id="header">Infinitas Logo Here</h2> <div class="clear"></div> <div class="<?php echo $grid; ?>" id="inner-container"> <div class="<?php echo $grid; ?> alpha" id="inner-header"> <h3 class="grid_5 alpha"><?php echo $title_for_layout; ?></h3> <div class="buttons grid_3 omega"> <?php if($this->Wizard->stepNumber() > 1 && !isset($hidePrevious)) { echo $this->Form->button('Previous', array('name' => 'Previous', 'value' => 'Previous')); } if(!isset($hideNext)) { echo $this->Form->button('Next', array('name' => 'Next', 'value' => 'Next', 'disabled' => (isset($hasErrors) ? $hasErrors : false))); } ?> </div> </div> <div class="clear"></div> <div class="<?php echo $grid; ?> alpha" id="content"> <?php echo $content_for_layout; ?> </div> <div class="clear"></div> <?php if (!isset($hideNext) || !isset($hidePrevious)) { ?> <div class="<?php echo $grid; ?> alpha buttons" id="inner-footer"> <?php if($this->Wizard->stepNumber() > 1 && !isset($hidePrevious)) { echo $this->Form->button('Previous', array('name' => 'Previous', 'value' => 'Previous')); } if(!isset($hideNext)) { echo $this->Form->button('Next', array('name' => 'Next', 'value' => 'Next', 'disabled' => (isset($hasErrors) ? $hasErrors : false))); } ?> </div> <?php } ?> </div> <?php if(!$hideSteps) { ?> <div class="grid_3" id="steps"> <h3>Installer progress</h3> <ul> <?php echo $this->Wizard->progressMenu($installerProgress, false, array('wrap' => 'li')) ?> </ul> </div> <?php } ?> <div class="clear"></div> </form> </body> </html> <?php /* <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <title>Infinitas Installer :: <?php echo $title_for_layout; ?></title> <?php echo $this->Html->css( '/installer/css/install' ); echo $scripts_for_layout; ?> </head> <body> <div id="wrap"> <div id="header"> <?php echo $this->Html->image('/installer/img/infinitas.png', array('alt' => 'Infinitas Cms', 'style' => 'padding-left:35px;padding-top:10px; width:220px;')); ?> <div id="nav"> <div id="topmenu"> <ul> <li class="active"><?php echo $this->Html->link(__('Installer', true), '/'); ?></li> <li><?php echo $this->Html->link(__('Infinitas', true), 'http://infinitas-cms.org', array('target' => '_blank')); ?></li> <li><?php echo $this->Html->link(__('Code', true), 'http://github.com/infinitas/infinitas', array('target' => '_blank')); ?></li> <li><?php echo $this->Html->link(__('Themes', true), 'http://github.com/infinitas/themes', array('target' => '_blank')); ?></li> <li><?php echo $this->Html->link(__('Issues', true), 'http://infinitas.lighthouseapp.com', array('target' => '_blank')); ?></li> </ul> <h1 id="sitename"><?php echo __('Welcome to Infinitas', true); ?></h1> </div> </div> <div class="clear"></div> <div id="breadcrumb"> Installer &raquo; <?php echo $this->action; ?> </div> </div> <div id="content"> <div id="right"> <div class="<?php echo isset($this->params['plugin'])?$this->params['plugin']:''; ?>"> <div class="<?php echo isset($this->params['controller'])?$this->params['controller']:''; ?>"> <div class="<?php echo isset($this->params['action'])?$this->params['action']:''; ?>"> <?php //echo $this->Session->flash(); echo $content_for_layout; ?> </div> </div> </div> </div> <div id="sidebar"> <div id="sidebartop"></div> <h2><?php echo __('Progress', true); ?></h2> <ul> <?php foreach($installerProgress as $action => $title) { ?> <li class="<?php echo ($this->action == $action) ? 'active' : ''; ?>"><?php echo $this->Html->link($title, array('plugin' => 'installer', 'controller' => 'install', 'action' => $this->action, '#' => 'here' )); ?></li> <?php } ?> </ul> <div id="sidebarbtm"></div> </div> <div class="clear"></div> <div id="bottom"> <p>Copyright &copy; <?php echo date('Y'), ' ', $this->Html->link('Infinitas', 'http://infinitas-cms.org', array('title' => 'Infinitas Cms')); ?> </p> </div> </div> <div id="footer"> <div id="credits"> <a href="http://ramblingsoul.com">CSS Template</a> by RamblingSoul</div> </div> </div> </body> </html> */<file_sep><?php class EmailAccount extends EmailsAppModel{ public $name = 'EmailAccount'; public $belongsTo = array( 'User' => array( 'className' => 'Users.User', 'fields' => array( 'User.id', 'User.usermane', 'User.email' ) ) ); public function __construct($id = false, $table = null, $ds = null) { parent::__construct($id, $table, $ds); $this->validate = array( 'name' => array( 'notEmpty' => array( 'rule' => 'notEmpty', 'message' => __('Please enter the name of the account', true) ), 'isUnique' => array( 'rule' => 'isUnique', 'message' => __('There is already an account with that name', true) ) ), 'server' => array( 'notEmpty' => array( 'rule' => 'notEmpty', 'message' => __('Please enter the server address or ip', true) ), 'validServer' => array( 'rule' => 'validServer', 'message' => __('Please enter a valid server address or ip', true) ) ), 'username' => array( 'notEmpty' => array( 'rule' => 'notEmpty', 'message' => __('Please enter the username for this account', true) ) ), 'password' => array( 'notEmpty' => array( 'rule' => 'notEmpty', 'message' => __('Please enter the password for this account', true) ) ), 'email' => array( 'notEmpty' => array( 'rule' => 'notEmpty', 'message' => __('Please enter the email address of this account', true) ) ), 'type' => array( 'notEmpty' => array( 'rule' => 'notEmpty', 'message' => __('Please select the type of service', true) ) ), 'port' => array( 'notEmpty' => array( 'rule' => 'notEmpty', 'message' => __('Please enter the port number to connect to', true) ), 'validPort' => array( 'rule' => '/[1-9][0-9]{2,5}/', 'message' => __('Please enter a valid port number', true) ) ) ); } /** * check the mail server is valid * * @param array $field the field being validated * @return bool is it valid */ public function validServer($field){ return // server like mail.something.ext preg_match('/^[a-z0-9]*\.[a-z0-9]*\.([a-z]{2,3}|[a-z]{2,3}\.[a-z]{2,3})*$/', current($field)) || // ip address preg_match('/^(([0-2]*[0-9]+[0-9]+)\.([0-2]*[0-9]+[0-9]+)\.([0-2]*[0-9]+[0-9]+)\.([0-2]*[0-9]+[0-9]+))$/', current($field)); } /** * this is used for making sure that the mail server details are correct * before saving them to the database. * * @return bool were we able to connect? */ public function beforeSave(){ return true; //is_int(ClassRegistry::init('Emails.MailSystem')->testConnection($this->data['EmailAccount'])); } /** * Get a list of email accounts that are associated to the user plus the * main account for the system. * * @param <type> $user_id the user requesting * @return <type> array of accounts */ public function getMyAccounts($user_id){ $accounts = $this->find( 'all', array( 'fields' => array( 'EmailAccount.id', 'EmailAccount.name', 'EmailAccount.slug', 'EmailAccount.email', ), 'conditions' => array( 'or' => array( 'EmailAccount.user_id' => $user_id, 'EmailAccount.system' => 1 ) ) ) ); return $accounts; } /** * @brief get a list of mails that are set to download with crons */ public function getCronAccounts(){ return $this->find( 'all', array( 'fields' => array( $this->alias . '.id', $this->alias . '.host', $this->alias . '.username', $this->alias . '.password', $this->alias . '.email', $this->alias . '.ssl', $this->alias . '.port', $this->alias . '.type', $this->alias . '.readonly' ), 'conditions' => array( $this->alias . '.cron' => 1 ) ) ); } public function getConnectionDetails($id){ $account = $this->find( 'first', array( 'conditions' => array( 'EmailAccount.id' => $id ) ) ); if(!empty($account)){ return $account['EmailAccount']; } return false; } }<file_sep><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <?php echo $this->Html->charset(); ?> <title> <?php echo Configure::read('Website.name'), ' :: ', $title_for_layout; ?> </title> <?php echo $this->Html->meta('icon'); echo $html->css(array('front') + $css_for_layout); echo $this->Html->script($js_for_layout); echo $scripts_for_layout; ?> </head> <body> <!-- terrafirma1.0 by nodethirtythree design http://www.nodethirtythree.com --> <div id="outer"> <div id="upbg"></div> <div id="inner"> <div id="header"> <h1><?php echo $this->Html->link(Configure::read('Website.name'), '/'); ?><sup>1.0</sup></h1> </div> <div id="splash"></div> <?php echo $this->ModuleLoader->load('top'); echo $this->Session->flash(); ?> <div id="primarycontent"> <div class="<?php echo isset($this->params['plugin'])?$this->params['plugin']:''; ?>"> <div class="<?php echo isset($this->params['controller'])?$this->params['controller']:''; ?>"> <div class="<?php echo isset($this->params['action'])?$this->params['action']:''; ?>"> <div id="content"> <?php echo $session->flash(), $content_for_layout; ?> </div> </div> </div> </div> </div> <div id="secondarycontent"> <?php echo $this->ModuleLoader->load('right'); ?> </div> <div id="footer"> <?php echo $this->Html->link( 'Infinitas CMS', 'http://infinitas-cms.org' ); echo $this->Html->link( $this->Html->image( 'cake.power.gif', array( 'alt'=> __( 'CakePHP: the rapid development php framework', true), 'border' => '0' ) ), 'http://www.cakephp.org/', array( 'target' => '_blank', 'escape' => false, 'style' => 'float:right;' ) ); ?> </div> </div> </div> </body> </html><file_sep><?php class InfinitasTask extends Shell{ /** * @brief width to wrap text to */ public $wrap = 70; /** * @brief create a heading for infinitas shell stuff */ public function h1($title){ $this->clear(); $this->out(" _____ __ _ _ _"); $this->out(" |_ _| / _(_) (_) |"); $this->out(" | | _ __ | |_ _ _ __ _| |_ __ _ ___"); $this->out(" | | | '_ \| _| | '_ \| | __|/ _` / __|"); $this->out(" _| |_| | | | | | | | | | | |_| (_| \__ \ "); $this->out(" |_____|_| |_|_| |_|_| |_|_|\__|\__,_|___/ " . Configure::read('Infinitas.version')); $this->h2($title); } /** * @brief create a heading for infinitas shell stuff */ public function h2($title){ $this->out(); $this->hr(); $this->center($title, '|'); $this->hr(); } /** * @brief create a heading for infinitas shell stuff */ public function h3($title){ $this->out(); $this->center($title); $this->hr(); } /** * @brief create nice paragraphs */ public function p($text){ $this->out(wordwrap($text, 64)); $this->out(); } /** * @brief center text */ public function center($text, $ends = ''){ $space1 = $space2 = str_repeat(' ', intval(($this->wrap - strlen($text)) / 2) -4); $this->out(sprintf('%s%s%s%s%s', $ends, $space1, $text, $space2, $ends)); } /** * @brief generate a list of options */ public function li($options = array()){ if(!is_array($options)){ $options = array($options); } foreach($options as $option){ $this->out($option); } } /** * @brief do a line break * * create a line break */ public function br(){ $this->out(); } /** * @brief clear the page * * clear the screen */ public function clear(){ $this->Dispatch->clear(); } /** * @brief pause help text when called from running shel * * When the comand is 'cake something help' its ok to just exit, if * its 'cake something' and then the option [h] is used it should pause * or the text is scrolled off the screen. */ public function helpPause(){ if(!isset($this->Dispatch->shellCommand) || $this->Dispatch->shellCommand != 'help'){ $this->br(); $this->in('Press a key to continue'); } } /** * @brief exit the shell * * Clear the screen and exit */ public function quit(){ $this->clear(); exit(0); } } <file_sep><?php if(App::import('Libs', 'Routes.routing')){ InfinitasRouting::setup(); } else{ // some error }<file_sep><?php final class RoutesEvents extends AppEvents{ public function onPluginRollCall(){ return array( 'name' => 'Routes', 'description' => 'Route pretty urls to your code', 'icon' => '/routes/img/icon.png', 'author' => 'Infinitas' ); } public function onSetupConfig(){ } public function onSetupCache(){ return array( 'name' => 'routes', 'config' => array( 'prefix' => 'core.routes.' ) ); } public function onAdminMenu($event){ $menu['main'] = array( 'Routes' => array('controller' => false, 'action' => false), 'Active' => array('controller' => 'routes', 'action' => 'index', 'Route.active' => 1), 'Disabled' => array('controller' => 'routes', 'action' => 'index', 'Route.active' => 0) ); return $menu; } }<file_sep><?php class ShortUrlsController extends ShortUrlsAppController{ public $name = 'ShortUrls'; public function view(){ if(!isset($this->params['pass'][0])){ $this->redirect($this->referer()); } $url = $this->ShortUrl->getUrl($this->params['pass'][0]); if(empty($url)){ $this->Session->setFlash(__('Page not found', true)); $this->redirect($this->referer()); } $this->redirect($url); } public function preview(){ if(!isset($this->params['pass'][0])){ $this->redirect($this->referer()); } $url = $this->ShortUrl->getUrl($this->params['pass'][0]); if(empty($url)){ $this->Session->setFlash(__('Page not found', true)); $this->redirect($this->referer()); } $shortUrl = $this->ShortUrl->find( 'first', array( 'conditions' => array( 'ShortUrl.url' => $url ) ) ); $this->set(compact('shortUrl')); } public function admin_index(){ $shortUrls = $this->paginate(null, $this->Filter->filter); $filterOptions = $this->Filter->filterOptions; $filterOptions['fields'] = array( 'url' ); $this->set(compact('shortUrls', 'filterOptions')); } }<file_sep><?php /** * @brief bootstrap defines a few global methods and triggers plugin integration * * This is the place where infinitas invokes plugins to start acting on the * core, alowing them to set cache configurations, import required lib files. * * Things like the Xhprof profiler needs to be attached as early as possible, * so using AppController::beforeFilter() is not good enough. For this reason * you can attach libs from here using the Events * * @li AppEvents::onRequireLibs() * @li AppEvents::onSetupCache() * * @throws E_USER_ERROR when Events is not available * * @copyright Copyright (c) 2009 <NAME> ( dogmatic69 ) * @link http://infinitas-cms.org * @package Infinitas * @license http://www.opensource.org/licenses/mit-license.php The MIT License * @since 0.5a * * @author dogmatic69 * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. */ /** * @brief the cached plugin paths * * Get the paths out of cache if there are any or get them with Folder::read * They are used with App::build() to make any extra folders in APP be plugin * folders. This can help if you want to keep plugins outside of /plugins */ $paths = Cache::read('plugin_paths'); if(!class_exists('Folder')){ App::import('Folder'); } if($paths === false){ $Folder = new Folder(APP); $folders = $Folder->read(); $folders = array_flip($folders[0]); unset($Folder, $folders['.git'], $folders['config'], $folders['locale'], $folders['nbproject'], $folders['tmp'], $folders['views'], $folders['webroot'], $folders['tests']); $paths = array(); foreach(array_flip($folders) as $folder){ $paths[] = APP . $folder . DS; } Cache::write('plugin_paths', $paths); unset($Folder, $folders); // @todo trigger event to get oter plugin paths } App::build( array( 'plugins' => $paths ) ); unset($paths); /** * Load plugin events */ if(!App::import('Libs', 'Events.Events')){ trigger_error('Could not load the Events Class', E_USER_ERROR); } EventCore::trigger(new StdClass(), 'requireLibs'); configureCache(EventCore::trigger(new StdClass(), 'setupCache')); /** * Make sure the json defines are loaded. */ if(!defined('JSON_ERROR_NONE')){define('JSON_ERROR_NONE', 0);} if(!defined('JSON_ERROR_DEPTH')){define('JSON_ERROR_DEPTH', 1);} if(!defined('JSON_ERROR_CTRL_CHAR')){define('JSON_ERROR_CTRL_CHAR', 3);} if(!defined('JSON_ERROR_SYNTAX')){define('JSON_ERROR_SYNTAX', 4);} function configureCache($cacheDetails) { foreach($cacheDetails['setupCache'] as $plugin => $cache) { $cache['config']['prefix'] = isset($cache['config']['prefix']) ? $cache['config']['prefix'] : ''; $folder = str_replace('.', DS, $cache['config']['prefix']); if(!strstr($folder, 'core' . DS)){ $folder = 'plugins' . DS . $folder; } if(Configure::read('Cache.engine') == 'Libs.NamespaceFile'){ if(!is_dir(CACHE.$folder)){ $Folder = new Folder(CACHE . $folder, true); } } else{ $cache['config']['prefix'] = Inflector::slug(APP_DIR) . '_' . str_replace(DS, '_', $folder); } $cache['config'] = array_merge(array('engine' => Configure::read('Cache.engine')), (array)$cache['config']); // set a default and turn off if debug is on. $cache['config']['duration'] = isset($cache['config']['duration']) ? $cache['config']['duration'] : '+ 999 days'; $cache['config']['duration'] = Configure::read('debug') > 0 ? '+ 10 seconds' : $cache['config']['duration']; if(!empty($cache['name']) && !empty($cache['config'])) { Cache::config($cache['name'], $cache['config']); } } unset($cacheDetails, $cache, $folder, $plugin); } /** * Escape things for preg_match * * will escape a string for goind preg match. * http://www.php.net/manual/en/function.preg-replace.php#92456 * * - Escapes the following * - \ ^ . $ | ( ) [ ] * + ? { } , * * - Example * - regexEscape('http://www.example.com/s?q=php.net+docs') * - http:\/\/www\.example\.com\/s\?q=php\.net\+docs * * @author alammar at gmail dot com * * @param string $str the stuff you want escaped * @return string the escaped string */ function regexEscape($str){ $patterns = array( '/\//', '/\^/', '/\./', '/\$/', '/\|/', '/\(/', '/\)/', '/\[/', '/\]/', '/\*/', '/\+/', '/\?/', '/\{/', '/\}/', '/\,/' ); $replace = array('\/', '\^', '\.', '\$', '\|', '\(', '\)', '\[', '\]', '\*', '\+', '\?', '\{', '\}', '\,'); return preg_replace($patterns,$replace, $str); } /** * @brief generate a unique cache name for a file. * * uses an array of data or a string to generate a hash for the end of the cache * name so that you can cache finds etc * * @param string $prefix the normal name for cache * @param mixed $data your conditions in the find * * @return a nice unique name */ function cacheName($prefix = 'PleaseNameMe', $data = null){ $hash = ''; if ($data) { $hash = '_' . sha1(serialize($data)); } $data = Inflector::underscore($prefix) . $hash; unset($hash); return $data; } /** * @brief return a nice user friendly name. * * Takes a cake class like SomeModel and converts it to Some model * * @code * prettyName(SomeModel); * // Some models * * prettyName(CateogryStuff); * // Category stuffs * @endcode * * @param string $class the name to convert * * @return a nice name */ function prettyName($class = null){ if($class !== null){ if(!class_exists('Inflector')){ App::import('Inflector'); } return ucfirst(low(Inflector::humanize(Inflector::underscore(Inflector::pluralize((string)$class))))); } return false; } /** * @brief having issues with routes * * @todo this should be moved to the routing plugin and a page added to admin * to view what is being generated. * * @param mixed $route * * @return null echo's out the route. */ function debugRoute($route){ echo 'Router::connect(\''.$route['Route']['url'].'\', array('; $parts = array(); foreach($route['Route']['values'] as $k => $v){ $parts[] = "'$k' => '$v'"; } echo implode(', ', $parts); echo '), array('; $parts = array(); foreach($route['Route']['regex'] as $k => $v){ $parts[] = "'$k' => '$v'"; } echo implode(', ', $parts); echo ')); </br>'; } /** * @brief Quick method to conver byte -> anything. * * @code * // output 1 kb * convert(1024); * * // output 5.24 mb * convert(5494237); * @endcode * * @param $size size in bytes * * @return string size in human readable */ function convert($size){ $unit=array('b','kb','mb','gb','tb','pb'); return @round($size/pow(1024,($i=floor(log($size,1024)))),2).' '.$unit[$i]; } /** * @brief get the current memory stats * * @param $print true to pr() false to return * * @code * // both output pr() data; * memoryUsage(); * memoryUsage(true); * * // set var with mem details * $var = memoryUsage(false); * @endcode * * @return mixed true if $print, array if !$print */ function memoryUsage($print = true, $convert = true){ $memory = array( 'current' => memory_get_usage(), 'current_t' => memory_get_usage(true), 'max' => memory_get_peak_usage(), 'max_' => memory_get_peak_usage(true), 'limit' => ini_get('memory_limit') ); if($convert){ $memory['current'] = convert($memory['current']); $memory['current_t'] = convert($memory['current_t']); $memory['max'] = convert($memory['max']); $memory['max_'] = convert($memory['max_']); } if((bool)$print){ pr($memory); unset($memory); return true; } return $memory; } /** * @brief attempt to get the current server load * * This will attempt a few methods to determin the server load, can be used * for reporting or keeping an eye on how things are running. * * @param <type> $print * @return <type> */ function serverLoad($print = true){ // try file method $load = @file_get_contents('/proc/loadavg'); if($load){ $load = explode(' ', $load, 4); unset($load[3]); } // try exec if(!$load){ $load = @exec('uptime'); // try shell_exec if(!$load){ $load = @shell_exec('uptime'); } if($load){ $load = explode(' ', $load); $load[2] = trim(array_pop($load)); $load[1] = str_replace(',', '', array_pop($load)); $load[0] = str_replace(',', '', array_pop($load)); } else{ $load[0] = $load[1] = $load[2] = -1; } } if((bool)$print){ pr($load); unset($load); return true; } return $load; } function systemInfo($extendedInfo = false){ $return = array(); $return['Server'] = array( 'name' => php_uname('n'), 'os' => php_uname('s'), 'type' => php_uname('s'), 'version' => php_uname('v'), 'release' => php_uname('r'), ); $return['Php'] = array( 'version' => phpversion(), 'memory_limit' => ini_get('memory_limit'), 'sapi' => php_sapi_name() ); if(!$extendedInfo){ return $return; } $extentions = get_loaded_extensions(); foreach($extentions as $extention){ $return['Php']['extentions'][] = array( 'name' => $extention, 'version' => phpversion($extention) ); } return $return; } <file_sep><?php /** * CakePHP Tags Plugin * * Copyright 2009 - 2010, Cake Development Corporation * 1785 E. Sahara Avenue, Suite 490-423 * Las Vegas, Nevada 89104 * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. * * @copyright 2009 - 2010, Cake Development Corporation (http://cakedc.com) * @link http://github.com/CakeDC/Tags * @package plugins.tags * @license MIT License (http://www.opensource.org/licenses/mit-license.php) */ /** * Short description for class. * * @package plugins.tags * @subpackage plugins.tags.tests.fixtures */ class ArticleFixture extends CakeTestFixture { /** * name property * * @var string 'AnotherArticle' * @access public */ public $name = 'Article'; /** * fields property * * @var array * @access public */ public $fields = array( 'id' => array('type' => 'integer', 'key' => 'primary'), 'title' => array('type' => 'string', 'null' => false)); /** * records property * * @var array * @access public */ public $records = array( array( 'id' => 1, 'title' => 'First Article'), array( 'id' => 2, 'title' => 'Second Article'), array( 'id' => 3, 'title' => 'Third Article')); } ?><file_sep><fieldset> <h1><?php echo __('Address', true); ?></h1><?php echo $this->Form->hidden('Address.id'); echo $this->Form->hidden('Address.plugin', array('value' => 'Projects')); echo $this->Form->hidden('Address.model', array('value' => 'Company')); echo $this->Form->hidden('Address.foreign_key'); echo $this->Form->input('Address.name'); echo $this->Form->input('Address.street'); echo $this->Form->input('Address.city'); echo $this->Form->input('Address.province'); echo $this->Form->input('Address.postal'); echo $this->Form->input('Address.country_id', array('empty' => Configure::read('Website.empty_select'))); echo $this->Form->input('Address.continent_id', array('empty' => Configure::read('Website.empty_select'))); ?> </fieldset><file_sep><?php /* Page Test cases generated on: 2010-03-13 11:03:01 : 1268471221*/ App::import('Model', 'management.Page'); class PageTestCase extends CakeTestCase { function startTest() { $this->Page =& ClassRegistry::init('Page'); } function endTest() { unset($this->Page); ClassRegistry::flush(); } } ?><file_sep><?php final class ThemesEvents extends AppEvents{ public function onSetupConfig(){ return array(); } public function onSetupCache(){ return array( 'name' => 'themes', 'config' => array( 'prefix' => 'core.themes.', ) ); } public function onAdminMenu($event){ $menu['main'] = array( 'Themes' => array('controller' => false, 'action' => false), 'Default Theme' => array('controller' => 'themes', 'action' => 'index', 'Theme.active' => 1) ); return $menu; } }<file_sep><?php /* NewsletterTemplate Fixture generated on: 2010-08-17 14:08:21 : 1282055181 */ class TemplateFixture extends CakeTestFixture { var $name = 'Template'; var $table = 'newsletter_templates'; var $fields = array( 'id' => array('type' => 'integer', 'null' => false, 'default' => NULL, 'length' => 10, 'key' => 'primary'), 'name' => array('type' => 'string', 'null' => false, 'default' => NULL, 'length' => 50, 'key' => 'unique'), 'header' => array('type' => 'text', 'null' => true, 'default' => NULL), 'footer' => array('type' => 'text', 'null' => true, 'default' => NULL), 'locked' => array('type' => 'boolean', 'null' => false, 'default' => '0'), 'locked_by' => array('type' => 'integer', 'null' => true, 'default' => NULL), 'locked_since' => array('type' => 'datetime', 'null' => true, 'default' => NULL), 'created' => array('type' => 'datetime', 'null' => true, 'default' => NULL), 'modified' => array('type' => 'datetime', 'null' => true, 'default' => NULL), 'delete' => array('type' => 'boolean', 'null' => false, 'default' => NULL), 'deleted_date' => array('type' => 'datetime', 'null' => true, 'default' => NULL), 'indexes' => array('PRIMARY' => array('column' => 'id', 'unique' => 1), 'name' => array('column' => 'name', 'unique' => 1)), 'tableParameters' => array('charset' => 'utf8', 'collate' => 'utf8_general_ci', 'engine' => 'InnoDB') ); var $records = array( array( 'id' => 1, 'name' => '<NAME>', 'header' => '<p style=\"color: red;\">this is the head</p>', 'footer' => '<p>this is the foot</p>', 'locked' => 0, 'locked_by' => 0, 'locked_since' => '0000-00-00 00:00:00', 'created' => '2009-12-12 17:04:07', 'modified' => '2009-12-21 16:26:14', 'delete' => 0, 'deleted_date' => '0000-00-00 00:00:00' ), array( 'id' => 2, 'name' => 'User - Registration', 'header' => '<p>\r\n Thank-you for joining us, your account is active and you may login at www.site.com</p>', 'footer' => '<p>\r\n &nbsp;</p>\r\n<div firebugversion=\"1.5.4\" id=\"_firebugConsole\" style=\"display: none;\">\r\n &nbsp;</div>', 'locked' => 0, 'locked_by' => 0, 'locked_since' => '0000-00-00 00:00:00', 'created' => '2010-05-14 16:32:42', 'modified' => '2010-05-15 13:33:45', 'delete' => 0, 'deleted_date' => '0000-00-00 00:00:00' ), array( 'id' => 3, 'name' => 'User - Activate', 'header' => '<p>\r\n Thank you for registering, please click the link below to activate your account.</p>\r\n<p>\r\n &nbsp;</p>\r\n<div firebugversion=\"1.5.4\" id=\"_firebugConsole\" style=\"display: none;\">\r\n &nbsp;</div>', 'footer' => '<p>\r\n &nbsp;</p>\r\n<p>\r\n Once your account is activated you will be able to login.</p>\r\n<div firebugversion=\"1.5.4\" id=\"_firebugConsole\" style=\"display: none;\">\r\n &nbsp;</div>', 'locked' => 0, 'locked_by' => 0, 'locked_since' => '0000-00-00 00:00:00', 'created' => '2010-05-15 13:30:46', 'modified' => '2010-05-15 13:30:46', 'delete' => 0, 'deleted_date' => '0000-00-00 00:00:00' ), ); } ?><file_sep><?php /** * Comment Template. * * @todo Implement .this needs to be sorted out. * * Copyright (c) 2009 <NAME> ( dogmatic69 ) * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. * @filesource * @copyright Copyright (c) 2009 <NAME> ( dogmatic69 ) * @link http://infinitas-cms.org * @package sort * @subpackage sort.comments * @license http://www.opensource.org/licenses/mit-license.php The MIT License * @since 0.5a */ Configure::write('Session.save', 'php'); class InstallController extends Controller { /** * Controller name * * @var string * @access public */ var $name = 'Install'; /** * No models required * * @var array * @access public */ var $uses = array(); /** * No components required * * @var array * @access public */ var $components = array('Libs.Wizard', 'Session'); public $helpers = array('Html', 'Form', 'Libs.Wizard', 'Text'); private $__phpVersion = '5.0'; private $__supportedDatabases = array( 'mysql' => array( 'name' => 'MySQL', 'version' => '5.0', 'versionQuery' => 'select version();', 'function' => 'mysql_connect', ), 'mysqli' => array( 'name' => 'MySQLi', 'version' => '5.0', 'versionQuery' => 'select version();', 'function' => 'mysqli_connect', ), 'mssql' => array( 'name' => 'Microsoft SQL Server', 'version' => '8.0', 'versionQuery' => 'SELECT CAST(SERVERPROPERTY(\'productversion\') AS VARCHAR)', 'function' => 'mssql_connect', ) ); private $__requiredExtensions = array( 'zlib' => 'Zlib is required for some of the functionality in Infinitas' ); private $__recommendedIniSettings = array ( array ( 'setting' => 'safe_mode', 'recomendation' => 0, 'desc' => 'This function has been DEPRECATED as of PHP 5.3.0 and REMOVED as of PHP 6.0.0' ), array ( 'setting' => 'display_errors', 'recomendation' => 1, 'desc' => 'Infinitas will handle errors througout the app' ), array ( 'setting' => 'file_uploads', 'recomendation' => 1, 'desc' => 'File uploads are needed for the wysiwyg editors and system installers' ), array ( 'setting' => 'magic_quotes_runtime', 'recomendation' => 0, 'desc' => 'This function has been DEPRECATED as of PHP 5.3.0 and REMOVED as of PHP 6.0.0. Relying on this feature is highly discouraged.' ), array ( 'setting' => 'register_globals', 'recomendation' => 0, 'desc' => 'This feature has been DEPRECATED as of PHP 5.3.0 and REMOVED as of PHP 6.0.0. Relying on this feature is highly discouraged.' ), array ( 'setting' => 'output_buffering', 'recomendation' => 0, 'desc' => 'Infinitas will handle output_buffering for you throughout the app' ), array ( 'setting' => 'session.auto_start', 'recomendation' => 0, 'desc' => 'Sessions are completly handled by Infinitas' ), ); private $__paths = array( 'config/database.php' => array( 'type' => 'write', 'message' => 'The database configuration (%s) file should be writable during the installation process. It should be set to be read-only once Infinitas has been installed.' ), 'tmp' => array( 'type' => 'write', 'message' => 'The temporary directory (%s) should be writable by Infinitas. Caching will not work otherwise and Infinitas will perform very poorly.', ) ); var $installerProgress = array(); /** * beforeFilter * * @return void */ function beforeFilter() { parent::beforeFilter(); $this->layout = 'installer'; $this->view = 'View'; $this->helpers[] = 'Html'; $this->sql = array( 'core_data' => APP . 'infinitas' . DS . 'installer' . DS . 'config' . DS . 'schema' . DS . 'infinitas_core_data.sql', 'core_sample_data' => APP . 'infinitas' . DS . 'installer' . DS . 'config' . DS . 'schema' . DS . 'infinitas_sample_data.sql', ); $this->Wizard->wizardAction = 'index'; $this->Wizard->steps = array( 'welcome', 'database', 'install', 'admin_user', ); $this->installerProgress = array( 'welcome' => __('Welcome', true), 'database' => __('Database configuration', true), 'install' => __('Ready to install', true), 'admin_user' => __('Site administrator', true), ); $this->Wizard->completeUrl = array('plugin' => 'installer', 'controller' => 'install', 'action' => 'finish'); $this->set('installerProgress', $this->installerProgress); } function index($step = null) { if(filesize(APP.'config'.DS.'database.php') > 0 && $this->Session->read('installing') == false) { $this->notice( __('Infinitas has already been installed', true), array( 'redirect' => true ) ); } $this->Session->write('installing', true); $this->set('title_for_layout', $this->installerProgress[$step == null ? 'welcome' : $step]); $this->Wizard->process($step); } function finish() { $this->Session->write('installing', false); $this->set('title_for_layout', 'Finished'); $this->set('hidePrevious', true); $this->set('hideNext', true); } /** * Wizard prepare steps methods */ function _prepareWelcome() { $core = $this->__checkCore(); $paths = $this->__checkPaths(); $database = $this->__checkDatabases(true); $recomendations = $this->__checkIniSettings(); $this->set(compact('core', 'database', 'paths', 'recomendations')); $this->set('supportedDb', $this->__supportedDatabases); } function _prepareDatabase() { $this->loadModel('Installer.Install'); $database = $this->__checkDatabases(); $this->set(compact('database')); } function _prepareInstall() { } function _prepareAdminUser() { $this->loadModel('Management.User'); $this->set('hidePrevious', true); } /** * Wizard process step methods */ function _processWelcome() { return true; } function _processDatabase() { App::import('Model', 'Installer.Install'); $install = new Install(false, false, false); $install->set($this->data); if($install->validates() && $this->__testConnection()) { return true; } return false; } function _processInstall() { if($this->__installPlugins() && $this->__writeDbConfig()) { return true; } return false; } function _processAdminUser() { $this->loadModel('Management.User'); $this->data['User']['password'] = Security::hash($this->data['User']['password'], null, true); $this->data['User']['ip_address'] = env('REMOTE_ADDR'); $this->data['User']['browser'] = env('HTTP_USER_AGENT'); $this->data['User']['operating_system'] = ''; $this->data['User']['country'] = ''; $this->data['User']['city'] = ''; $this->data['User']['group_id'] = 1; $this->data['User']['active'] = 1; if($this->User->save($this->data)) { return true; } return false; } /** * Private methods */ /** * * @return array */ private function __checkCore() { $core = array(); if(phpversion() < $this->__phpVersion) { $core[] = sprintf(__('PHP version %s detected, %s needs at least version %s.', true), phpversion(), 'Infinitas', $this->__phpVersion.'.x'); } foreach($this->__requiredExtensions as $extension => $message) { if(!extension_loaded($extension)) { $core[] = __($message); } } return $core; } /** * * @return array */ private function __checkPaths() { $paths = array(); foreach($this->__paths as $path => $options) { switch($options['type']) { case 'write': $function = 'is_writable'; break; default: $function = 'is_readable'; } if(!$function(APP.$path)) { $paths[] = sprintf(__($options['message'], true), APP.$path); } } return $paths; } /** * * @return array */ private function __checkDatabases($databaseSupported = false) { $availableDb = array(); foreach($this->__supportedDatabases as $cakeType => $supportedDatabase) { if(function_exists($supportedDatabase['function'])) { $availableDb[$cakeType] = sprintf(__('%s (Version %s or newer)', true), $supportedDatabase['name'], $supportedDatabase['version']);; } } return $databaseSupported == true ? !empty($availableDb) : $availableDb; } /** * * @return array */ private function __checkIniSettings() { $recomendations = array(); foreach($this->__recommendedIniSettings as $k => $setting) { if((int)ini_get($setting['setting']) !== $setting['recomendation']) { $setting['current'] = (int)ini_get($setting['setting']); $setting['desc'] = __($setting['desc'], true); $recomendations[] = $setting; } } return $recomendations; } function __cleanConnectionDetails($adminUser = false) { $connectionDetails = $this->data['Install']; unset($connectionDetails['step']); if(trim($connectionDetails['port']) == '') { unset($connectionDetails['port']); } if(trim($connectionDetails['prefix']) == '') { unset($connectionDetails['prefix']); } if($adminUser == true) { $connectionDetails['login'] = $this->data['Admin']['username']; $connectionDetails['password'] = $this->data['Admin']['password']; } return $connectionDetails; } function __testConnection() { $connectionDetails = $this->__cleanConnectionDetails(); $adminConnectionDetails = $this->__cleanConnectionDetails(true); if(!@ConnectionManager::create('installer', $connectionDetails)->isConnected()) { $this->set('dbError', true); return false; } else { if(trim($adminConnectionDetails['login']) != '') { if(!@ConnectionManager::create('admin', $adminConnectionDetails)->isConnected()) { $this->set('adminDbError', true); return false; } } $dbOptions = $this->__supportedDatabases[$connectionDetails['driver']]; $version = ConnectionManager::getDataSource('installer')->query($dbOptions['versionQuery']); $version = $version[0][0]['version()']; if(version_compare($version, $dbOptions['version']) >= 0) { return true; } else { $this->set('versionError', $version); $this->set('requiredDb', $dbOptions); return false; } } } private function __writeDbConfig() { $dbConfig = $this->Wizard->read('database.Install'); copy(App::pluginPath('Installer') . 'config' . DS . 'database.install', APP . 'config' . DS . 'database.php'); App::import('Core', 'File'); $file = new File(APP . 'config' . DS . 'database.php', true); $content = $file->read(); $find = array( '{default_driver}', '{default_host}', '{default_login}', '{default_password}', '{default_database}', '{default_prefix}', '{default_port}', ); $replacements = array( $dbConfig['driver'], $dbConfig['host'], $dbConfig['login'], $dbConfig['password'], $dbConfig['database'], $dbConfig['prefix'], $dbConfig['port'], ); $content = str_replace($find, $replacements, $content); if ($file->write($content)) { return true; } return false; } private function __installPlugins() { $this->data = array_merge($this->data, $this->Wizard->read('database')); App::import('Core', 'ConnectionManager'); if($this->data['Admin']['username'] !== '') { $dbConfig = $this->__cleanConnectionDetails(true); } else { $dbConfig = $this->__cleanConnectionDetails(); } $db = ConnectionManager::create('default', $dbConfig); $plugins = App::objects('plugin'); natsort($plugins); App::import('Lib', 'Installer.ReleaseVersion'); $Version = new ReleaseVersion(); //Install app tables first $result = $this->__installPlugin($Version, $dbConfig, 'app'); $result = true; if($result) { //Then install the Installer plugin $result = $result && $this->__installPlugin($Version, $dbConfig, 'Installer'); if($result) { //Then install all other plugins foreach($plugins as $plugin) { if($plugin != 'Installer') { $result = $result && $this->__installPlugin($Version, $dbConfig, $plugin); } } } } return $result; } private function __installPlugin(&$Version, $dbConfig, $plugin = 'app') { if($plugin !== 'app') { $pluginPath = App::pluginPath($plugin); $configPath = $pluginPath . 'config' . DS; $checkFile = $configPath . 'config.json'; } else { $configPath = APP . 'config' . DS; $checkFile = $configPath . 'releases' . DS . 'map.php'; } if(file_exists($checkFile)) { if(file_exists($configPath . 'releases' . DS . 'map.php')) { try { $mapping = $Version->getMapping($plugin); $latest = array_pop($mapping); $versionResult = $Version->run(array( 'type' => $plugin, 'version' => $latest['version'], 'basePrefix' => (isset($dbConfig['prefix']) ? $dbConfig['prefix'] : ''), 'sample' => $this->data['Sample']['sample'] == 1 )); } catch (Exception $e) { return false; } } else { $versionResult = true; } if($versionResult && $plugin !== 'app') { $this->loadModel('Installer.Plugin'); return $this->Plugin->installPlugin($plugin, array('installRelease' => false)); } return $versionResult; } return true; } }<file_sep><?php class ModulesRoute extends ModulesAppModel{ }<file_sep><?php $map = array( 1 => array( '000010_emails' => 'R4cbc4ef355dc49f1b73016836318cd70'), ); ?><file_sep><?php /** * The model for ip address blocking. * * Used to manage ip addresses that are blocked * * Copyright (c) 2010 <NAME> ( dogmatic69 ) * * @filesource * @copyright Copyright (c) 2010 <NAME> ( dogmatic69 ) * @link http://www.infinitas-cms.org * @package management * @subpackage management.models.ip_address * @license http://www.opensource.org/licenses/mit-license.php The MIT License * @since 0.7a * * @author <NAME> ( dogmatic69 ) * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. */ class IpAddress extends ManagementAppModel{ var $name = 'IpAddress'; var $displayField = 'ip_address'; /** * Get the blocked ip addresses / ranges. * * gets a list of ip addresses that are blocked and Caches the data so * there is not so much queries. * * @return array of blocked ip addresses and blocked ranges. */ function getBlockedIpAddresses(){ $ip_addresses = Cache::read('blocked_ips', 'core'); if ($ip_addresses) { return $ip_addresses; } $ip_addresses = $this->find( 'list', array( 'conditions' => array( 'IpAddress.active' => 1 ) ) ); Cache::write('blocked_ips', $ip_addresses, 'core'); return $ip_addresses; } /** * Check for other simmilar failed logins. * * This method will see how many other atempts that failed for that login * exists, so things like "admin" or "administrator" will be more common * as hackers always try them. things like this pose a higher risk so they will * get a higher risk factor. * * The number of sessions is also taken into account so that sites will millions * of users and only a few matches will not be a high risk, basicaly its * proportional to the number of users of the site. * * The risk is later used to work out the amount of time the user will be * blocked for. * * @param mixed $ipAddress the users ip address * @param string $username the user name that was used to try login * * @return int the risk of the failed login. */ function findSimmilarAttempts($ipAddress = null, $username = ''){ if (!$ipAddress) { exit; } $badCount = $this->find( 'count', array( 'conditions' => array( 'IpAddress.description LIKE ' => '%'.$username.'%' ) ) ); $totalCount = $this->find( 'count' ) * 3; $risk = 0; $factor = ClassRegistry::init('Session')->find('count'); // no risk if ($totalCount === $badCount || $totalCount === 0 || $factor == 0) { return $risk; } $risk = (($badCount/$factor) / $totalCount)*100; switch($risk){ case ($risk < .5): return 2; break; case ($risk < 1): return 3; break; case ($risk < 2): return 4; break; case ($risk < 5): return 5; break; case ($risk < 10): return 4; break; case ($risk < 20): return 2; break; case ($risk < 50): return 2; break; default: return 1; break; } // switch } /** * Block an ip address. * * This method is called after a number of failed logins and will create * an entry into the database blocking the ip address from accessing the * site. * * case: * - first time being blocked (1) with no risk (1) on a site that has security on low (5) * - 1 x 1 x 5 x 5 = 25 min blocked * * - first time being blocked (1) with no risk (1) on a site that has security on high (20) * - 1 x 1 x 20 x 5 = 100 min blocked * * - 3rd time being blocked (3) with low risk (2) on a site that has security on low (5) * - 3 x 2 x 5 x 5 = 150 min blocked * * - 3rd time being blocked (3) with high risk (5) on a site that has security on high (20) * - 3 x 5 x 20 x 5 = 1500 min blocked (25 hours) * * @param mixed $ipAddress the users ip address * @param mixed $data the data that was submited for that request. * @param integer $risk the risk determined for that login. * * @return bool true on succes. or exit */ function blockIp($ipAddress = null, $data = null, $risk = 0){ if (!$ipAddress) { exit; } $old = $this->find( 'first', array( 'conditions' => array( 'IpAddress.ip_address' => $ipAddress ), 'contain' => false ) ); $save['IpAddress']['ip_address'] = $ipAddress; $save['IpAddress']['active'] = 1; $save['IpAddress']['description'] = serialize($data); $save['IpAddress']['times_blocked'] = 1; $save['IpAddress']['risk'] = $risk; if (!empty($old)) { $save['IpAddress']['id'] = $old['IpAddress']['id']; $save['IpAddress']['times_blocked'] = $old['IpAddress']['times_blocked'] + 1; } $time = $save['IpAddress']['times_blocked'] * 20; switch(Configure::read('Security.level')){ case 'low': $time = $save['IpAddress']['times_blocked'] * 5; break; case 'medium': $time = $save['IpAddress']['times_blocked'] * 10; break; } // switch $save['IpAddress']['unlock_at'] = $time // blocked times * the security level * 5 // minutes * ($risk + 1); $save['IpAddress']['unlock_at'] = date('Y-m-d H:i:s', mktime(0, date('i') + $save['IpAddress']['unlock_at'], 0, date('m'), date('d'), date('Y'))); if ($this->save($save)) { return true; } exit; } }<file_sep><div class="dashboard"> <h1><?php echo $name; ?></h1> <p class="error"> <strong><?php __('Error'); ?>: </strong> <?php printf(__('An Internal Error Has Occurred.', true), "<strong>'{$message}'</strong>"); ?> </p> </div><file_sep><?php $managementGeneral = array( array( 'name' => 'Dashboard', 'description' => 'Back to the main admin dashboard', 'icon' => '/management/img/icon.png', 'author' => 'Infinitas', 'dashboard' => array('plugin' => 'management', 'controller' => 'management', 'action' => 'dashboard') ), array( 'name' => 'Configs', 'description' => 'Configure Your site', 'icon' => '/configs/img/icon.png', 'author' => 'Infinitas', 'dashboard' => array('plugin' => 'configs', 'controller' => 'configs', 'action' => 'index') ), array( 'name' => 'Locks', 'description' => 'Stop others editing things you are working on', 'icon' => '/locks/img/icon.png', 'author' => 'Infinitas', 'dashboard' => array('plugin' => 'locks', 'controller' => 'locks', 'action' => 'index') ), array( 'name' => 'Menus', 'description' => 'Build menus for your site', 'icon' => '/menus/img/icon.png', 'author' => 'Infinitas', 'dashboard' => array('plugin' => 'menus', 'controller' => 'menus', 'action' => 'index') ), array( 'name' => 'Server', 'description' => 'Track your servers health', 'icon' => '/server_status/img/icon.png', 'author' => 'Infinitas', 'dashboard' => array('plugin' => 'server_status', 'controller' => 'server_status', 'action' => 'dashboard') ), array( 'name' => 'Short Urls', 'description' => 'Manage the short urls pointing to your site', 'icon' => '/short_urls/img/icon.png', 'author' => 'Infinitas', 'dashboard' => array('plugin' => 'short_urls', 'controller' => 'short_urls', 'action' => 'index') ), array( 'name' => 'Themes', 'description' => 'Theme your site', 'icon' => '/themes/img/icon.png', 'author' => 'Infinitas', 'dashboard' => array('plugin' => 'themes', 'controller' => 'themes', 'action' => 'index') ), array( 'name' => 'Trash', 'description' => 'Manage the deleted content', 'icon' => '/trash/img/icon.png', 'author' => 'Infinitas', 'dashboard' => array('plugin' => 'trash', 'controller' => 'trash', 'action' => 'index') ), array( 'name' => 'Webmaster', 'description' => 'Manage your sites robots files and sitemaps', 'icon' => '/webmaster/img/icon.png', 'author' => 'Infinitas', 'dashboard' => array('plugin' => 'webmaster', 'controller' => 'webmaster', 'action' => 'dashboard') ) ); $managementContent = array( array( 'name' => 'Categories', 'description' => 'Categorize your content', 'icon' => '/categories/img/icon.png', 'author' => 'Infinitas', 'dashboard' => array('plugin' => 'categories', 'controller' => 'categories', 'action' => 'index') ), array( 'name' => 'Contact', 'description' => 'Display your contact details and allow users to contact you', 'icon' => '/contact/img/icon.png', 'author' => 'Infinitas', 'dashboard' => array('plugin' => 'contact', 'controller' => 'branches', 'action' => 'index') ), array( 'name' => 'Content', 'description' => 'Mange the way content works inside Infinitas', 'icon' => '/contents/img/icon.png', 'author' => 'Infinitas', 'dashboard' => array('plugin' => 'contents', 'controller' => 'global_contents', 'action' => 'index') ), array( 'name' => 'Modules', 'description' => 'Add sections of output to your site with ease', 'icon' => '/modules/img/icon.png', 'author' => 'Infinitas', 'dashboard' => array('plugin' => 'modules', 'controller' => 'modules', 'action' => 'index', 'Module.admin' => 0) ), array( 'name' => 'Tags', 'description' => 'Attach tags to records', 'icon' => '/tags/img/icon.png', 'author' => 'CakeDC', 'dashboard' => array('plugin' => 'tags', 'controller' => 'tags', 'action' => 'index') ) ); $managementGeneral = $this->Menu->builDashboardLinks($managementGeneral, 'management_general'); $managementContent = $this->Menu->builDashboardLinks($managementContent, 'management_content'); ?> <div class="dashboard grid_16"> <h1><?php echo __('Site Management', true); ?></h1> <ul class="icons"><li><?php echo implode('</li><li>', current((array)$managementGeneral)); ?></li></ul> </div> <div class="dashboard grid_16"> <h1><?php echo __('Content Related', true); ?></h1> <ul class="icons"><li><?php echo implode('</li><li>', current((array)$managementContent)); ?></li></ul> </div><file_sep><?php /** * @brief CommentsEvents for the comments plugin * * @copyright Copyright (c) 2010 <NAME> ( dogmatic69 ) * @link http://www.infinitas-cms.org * @package Infinitas.Comments * @license http://www.opensource.org/licenses/mit-license.php The MIT License * @since 0.8a * * @author dogmatic69 * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. */ final class CommentsEvents extends AppEvents{ public function onPluginRollCall(){ return array( 'name' => 'Comments', 'description' => 'See what your users have to say', 'icon' => '/comments/img/icon.png', 'author' => 'Infinitas' ); } public function onAdminMenu($event){ $menu['main'] = array( 'Comments' => array('controller' => false, 'action' => false), 'Active' => array('controller' => 'comments', 'action' => 'index', 'Comment.active' => 1), 'Pending' => array('controller' => 'comments', 'action' => 'index', 'Comment.active' => 0, 'Comment.status' => 'approved'), 'Spam' => array('controller' => 'comments', 'action' => 'index', 'Comment.status' => 'spam') ); return $menu; } public function onSetupConfig(){ return Configure::load('comments.config'); } public function onAttachBehaviors($event) { if(is_subclass_of($event->Handler, 'Model')) { if ($event->Handler->hasField('comment_count')) { if(!$event->Handler->Behaviors->enabled('Comments.Commentable')){ $event->Handler->Behaviors->attach('Comments.Commentable'); } } } } public function onRequireCssToLoad($event){ return array( '/comments/css/comment' ); } public function onRequireJavascriptToLoad($event){ return array( '/comments/js/comment' ); } public function onSiteMapRebuild($event){ pr(ClassRegistry::init('Comments.Comment')->getNewestRow()); exit; return array( array( 'url' => Router::url(array('plugin' => 'comments', 'controller' => 'comments', 'action' => 'index', 'admin' => false, 'prefix' => false), true), 'last_modified' => ClassRegistry::init('Comments.Comment')->getNewestRow(), 'change_frequency' => ClassRegistry::init('Comments.Comment')->getChangeFrequency(), 'priority' => 0.8 ) ); } public function onUserProfile($event){ return array( 'element' => 'profile' ); } }<file_sep><?php /** * Comment Template. * * @todo -c Implement .this needs to be sorted out. * * Copyright (c) 2009 <NAME> ( dogmatic69 ) * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. * * @filesource * @copyright Copyright (c) 2009 <NAME> ( dogmatic69 ) * @link http://infinitas-cms.org * @package sort * @subpackage sort.comments * @license http://www.opensource.org/licenses/mit-license.php The MIT License * @since 0.5a */ echo $this->Form->create('MenuItem', array('url' => array('controller' => 'menuItems', 'action' => 'mass', 'admin' => 'true'))); $massActions = $this->Core->massActionButtons( array( 'add', 'edit', 'toggle', 'copy', 'move', 'delete' ) ); echo $this->Infinitas->adminIndexHead($filterOptions, $massActions); ?> <div class="table"> <table class="listing" cellpadding="0" cellspacing="0"> <?php echo $this->Core->adminTableHeader( array( $this->Form->checkbox('all') => array( 'class' => 'first', 'style' => 'width:25px;' ), $this->Paginator->sort('name'), $this->Paginator->sort('Menu') => array( 'style' => 'width:100px;' ), $this->Paginator->sort('Access', 'Group.name') => array( 'style' => 'width:90px;' ), __('Order', true) => array( 'style' => 'width:50px;' ), $this->Paginator->sort('Status', 'active') => array( 'style' => 'width:50px;' ), __('Actions', true) => array( 'style' => 'width:50px;' ) ) ); $MenuItem = ClassRegistry::init('Menu.MenuItem'); foreach ($menuItems as $menuItem){ ?> <tr class="<?php echo $this->Core->rowClass(); ?>"> <td><?php echo $this->Form->checkbox($menuItem['MenuItem']['id']); ?>&nbsp;</td> <td> <?php $paths = count($MenuItem->getPath($menuItem['MenuItem']['id']))-1; $links = array(); if ($paths > 1) { echo '<b>', str_repeat('- ', $paths-1), ' |</b> '; } echo $this->Html->link( $menuItem['MenuItem']['name'] == '--' ? __('Seperator' ,true) : Inflector::humanize($menuItem['MenuItem']['name']), array('action' => 'edit', $menuItem['MenuItem']['id']) ); ?>&nbsp; </td> <td> <?php echo Inflector::humanize($menuItem['Menu']['name']); ?>&nbsp; </td> <td> <?php if(isset($menuItem['Group']['name'])){ echo __(Inflector::humanize($menuItem['Group']['name']), true); } else{ echo __('Public', true); } ?>&nbsp; </td> <td> <?php echo $this->Infinitas->treeOrdering($menuItem['MenuItem']); ?>&nbsp; </td> <td> <?php echo $this->Infinitas->status($menuItem['MenuItem']['active']); ?>&nbsp; </td> <td> <?php echo $this->Html->image( $this->Image->getRelativePath('actions', 'add'), array( 'width' => '16px', 'url' => array( 'action' => 'add', 'parent_id' => $menuItem['MenuItem']['id'] ) ) ); ?> </td> </tr> <?php } unset($MenuItem); ?> </table> <?php echo $this->Form->end(); ?> </div> <?php echo $this->element('pagination/admin/navigation'); ?><file_sep><?php /* * Short Description / title. * * Overview of what the file does. About a paragraph or two * * Copyright (c) 2010 <NAME> ( dogmatic69 ) * * @filesource * @copyright Copyright (c) 2010 <NAME> ( dogmatic69 ) * @link http://www.infinitas-cms.org * @package {see_below} * @subpackage {see_below} * @license http://www.opensource.org/licenses/mit-license.php The MIT License * @since {check_current_milestone_in_lighthouse} * * @author {your_name} * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. */ class WebmasterEvents extends AppEvents{ public function onAdminMenu($event){ $menu['main'] = array( 'Edit Robots' => array('plugin' => 'webmaster', 'controller' => 'robots', 'action' => 'edit'), 'View Sitemap' => array('plugin' => 'webmaster', 'controller' => 'site_maps', 'action' => 'view'), 'Rebuild Sitemap' => array('plugin' => 'webmaster', 'controller' => 'site_maps', 'action' => 'rebuild') ); return $menu; } public function onSetupConfig(){ return Configure::load('webmaster.config'); } public function onSetupCache(){ return array( 'name' => 'webmaster', 'config' => array( 'prefix' => 'webmaster.', ) ); } public function onSetupRoutes(){ Router::connect('/sitemap', array('plugin' => 'webmaster', 'controller' => 'site_maps', 'action' => 'index', 'admin' => false, 'prefix' => '')); } public function onSetupExtensions(){ return array( 'xml' ); } }<file_sep><?php class R4c94edceb66c49d38c8678d86318cd70 extends CakeRelease { /** * Migration description * * @var string * @access public */ public $description = 'Migration for Newsletter version 0.8'; /** * Plugin name * * @var string * @access public */ public $plugin = 'Newsletter'; /** * Actions to be performed * * @var array $migration * @access public */ public $migration = array( 'up' => array( 'create_table' => array( 'campaigns' => array( 'id' => array('type' => 'integer', 'null' => false, 'default' => NULL, 'length' => 10, 'key' => 'primary'), 'name' => array('type' => 'string', 'null' => false, 'default' => NULL, 'length' => 50), 'description' => array('type' => 'text', 'null' => false, 'default' => NULL), 'active' => array('type' => 'boolean', 'null' => false, 'default' => '1'), 'newsletter_count' => array('type' => 'integer', 'null' => false, 'default' => '0'), 'template_id' => array('type' => 'integer', 'null' => false, 'default' => NULL), 'deleted' => array('type' => 'integer', 'null' => false, 'default' => NULL, 'length' => 1), 'deleted_date' => array('type' => 'datetime', 'null' => true, 'default' => NULL), 'created' => array('type' => 'datetime', 'null' => true, 'default' => NULL), 'modified' => array('type' => 'datetime', 'null' => true, 'default' => NULL), 'indexes' => array( 'PRIMARY' => array('column' => 'id', 'unique' => 1), ), 'tableParameters' => array('charset' => 'utf8', 'collate' => 'utf8_general_ci', 'engine' => 'InnoDB'), ), 'newsletters' => array( 'id' => array('type' => 'integer', 'null' => false, 'default' => NULL, 'length' => 10, 'key' => 'primary'), 'campaign_id' => array('type' => 'integer', 'null' => true, 'default' => NULL, 'key' => 'index'), 'template_id' => array('type' => 'integer', 'null' => false, 'default' => NULL), 'from' => array('type' => 'string', 'null' => false, 'default' => NULL, 'length' => 150), 'reply_to' => array('type' => 'string', 'null' => false, 'default' => NULL, 'length' => 150), 'subject' => array('type' => 'string', 'null' => false, 'default' => NULL, 'length' => 100), 'html' => array('type' => 'text', 'null' => false, 'default' => NULL), 'text' => array('type' => 'text', 'null' => false, 'default' => NULL), 'active' => array('type' => 'boolean', 'null' => false, 'default' => NULL), 'sent' => array('type' => 'boolean', 'null' => false, 'default' => '0'), 'views' => array('type' => 'integer', 'null' => false, 'default' => '0'), 'sends' => array('type' => 'integer', 'null' => false, 'default' => '0'), 'last_sent' => array('type' => 'datetime', 'null' => true, 'default' => NULL), 'created' => array('type' => 'datetime', 'null' => true, 'default' => NULL), 'modified' => array('type' => 'datetime', 'null' => true, 'default' => NULL), 'created_by' => array('type' => 'integer', 'null' => true, 'default' => NULL), 'modified_by' => array('type' => 'integer', 'null' => true, 'default' => NULL), 'indexes' => array( 'PRIMARY' => array('column' => 'id', 'unique' => 1), 'campaign_id' => array('column' => 'campaign_id', 'unique' => 0), ), 'tableParameters' => array('charset' => 'utf8', 'collate' => 'utf8_general_ci', 'engine' => 'InnoDB'), ), 'newsletters_users' => array( 'id' => array('type' => 'integer', 'null' => false, 'default' => NULL, 'length' => 10, 'key' => 'primary'), 'user_id' => array('type' => 'integer', 'null' => false, 'default' => NULL), 'newsletter_id' => array('type' => 'integer', 'null' => false, 'default' => NULL, 'key' => 'index'), 'sent' => array('type' => 'boolean', 'null' => false, 'default' => '0', 'key' => 'index'), 'created' => array('type' => 'datetime', 'null' => true, 'default' => NULL), 'modified' => array('type' => 'datetime', 'null' => true, 'default' => NULL), 'indexes' => array( 'PRIMARY' => array('column' => 'id', 'unique' => 1), 'newsletter_sent' => array('column' => 'sent', 'unique' => 0), 'newsletter_newsletter_id' => array('column' => 'newsletter_id', 'unique' => 0), ), 'tableParameters' => array('charset' => 'utf8', 'collate' => 'utf8_general_ci', 'engine' => 'InnoDB'), ), 'templates' => array( 'id' => array('type' => 'integer', 'null' => false, 'default' => NULL, 'length' => 10, 'key' => 'primary'), 'name' => array('type' => 'string', 'null' => false, 'default' => NULL, 'length' => 50, 'key' => 'unique'), 'header' => array('type' => 'text', 'null' => true, 'default' => NULL), 'footer' => array('type' => 'text', 'null' => true, 'default' => NULL), 'delete' => array('type' => 'boolean', 'null' => false, 'default' => NULL), 'deleted_date' => array('type' => 'datetime', 'null' => true, 'default' => NULL), 'created' => array('type' => 'datetime', 'null' => true, 'default' => NULL), 'modified' => array('type' => 'datetime', 'null' => true, 'default' => NULL), 'indexes' => array( 'PRIMARY' => array('column' => 'id', 'unique' => 1), 'name' => array('column' => 'name', 'unique' => 1), ), 'tableParameters' => array('charset' => 'utf8', 'collate' => 'utf8_general_ci', 'engine' => 'InnoDB'), ), ), ), 'down' => array( 'drop_table' => array( 'campaigns', 'newsletters', 'newsletters_users', 'templates' ), ), ); /** * Fixtures for data * * @var array $fixtures * @access public */ public $fixtures = array( 'core' => array( 'Template' => array( array( 'id' => 3, 'name' => 'User - Activate', 'header' => '<p>\\r\\n Thank you for registering, please click the link below to activate your account.</p>\\r\\n<p>\\r\\n &nbsp;</p>\\r\\n<div firebugversion=\\\"1.5.4\\\" id=\\\"_firebugConsole\\\" style=\\\"display: none;\\\">\\r\\n &nbsp;</div>', 'footer' => '<p>\\r\\n &nbsp;</p>\\r\\n<p>\\r\\n Once your account is activated you will be able to login.</p>\\r\\n<div firebugversion=\\\"1.5.4\\\" id=\\\"_firebugConsole\\\" style=\\\"display: none;\\\">\\r\\n &nbsp;</div>', 'delete' => 0, 'deleted_date' => '0000-00-00 00:00:00', 'created' => '2010-05-15 13:30:46', 'modified' => '2010-05-15 13:30:46' ), array( 'id' => 2, 'name' => 'User - Registration', 'header' => '<p>\\r\\n Thank-you for joining us, your account is active and you may login at www.site.com</p>', 'footer' => '<p>\\r\\n &nbsp;</p>\\r\\n<div firebugversion=\\\"1.5.4\\\" id=\\\"_firebugConsole\\\" style=\\\"display: none;\\\">\\r\\n &nbsp;</div>', 'delete' => 0, 'deleted_date' => '0000-00-00 00:00:00', 'created' => '2010-05-14 16:32:42', 'modified' => '2010-05-15 13:33:45' ), ), ), ); /** * Before migration callback * * @param string $direction, up or down direction of migration process * @return boolean Should process continue * @access public */ public function before($direction) { return true; } /** * After migration callback * * @param string $direction, up or down direction of migration process * @return boolean Should process continue * @access public */ public function after($direction) { return true; } } ?><file_sep><?php class ShortUrl extends ShortUrlsAppModel{ public $viewable = true; /** * direct delete or to trash * * @access public * @var bool */ public $noTrash = true; /** * skip confirmation * * @access public * @var bool */ public $noConfirm = true; /** * A string of chars used in the encoding / decoding * * @var string */ private $__codeSet = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'; /** * The length of the $__codeSet * * @var int */ private $__base; public function __construct($id = false, $table = null, $ds = null) { parent::__construct($id, $table, $ds); $this->validate = array( 'url' => array( 'isUnique' => array( 'rule' => 'isUnique', 'message' => __('That url has already been shortened', true) ), 'url' => array( 'rule' => 'someTypeOfUrl', 'message' => __('Please enter a valid url (something that does in href)', true) ), 'notEmpty' => array( 'rule' => 'notEmpty', 'message' => __('Please enter the url to shorten', true) ) ) ); $this->__base = strlen($this->__codeSet); } /** * make sure we save only valid urls. * * @param array the field being validated * @return bool if it is valid or not */ public function someTypeOfUrl($field){ // absolute url if(substr(current($field), 0, 1) == '/'){ return true; } // full url else if(preg_match('/^((mailto\:|(news|(ht|f)tp(s?))\:\/\/){1}\S+).*$/', current($field))){ return true; } else if(false){ // validate json so that you can use a cake url that can change with routing. } return false; } /** * Convert a long url to a short one. * * @param string $url the url to shroten * @return string the code of the short url to be used with slugUrl event */ public function shorten($url = null){ if(!$url){ return false; } $data['ShortUrl']['url'] = $url; $this->create(); if(!$this->save($data)){ if(current($this->validationErrors) == $this->validate['url']['isUnique']['message']){ $id = $this->find( 'first', array( 'conditions' => array( 'ShortUrl.url' => $url ) ) ); $this->id = isset($id['ShortUrl']['id']) ?$id['ShortUrl']['id'] : false; if(!$this->id){ return false; } } } return $this->__encode($this->id); } /** * convert a short url to a long one. * * @param string $code the code from the short url * @return mixed false on fail, string url on true */ public function getUrl($code = null){ if(!$code){ return false; } $check = $this->read(null, $this->__decode($code)); if(!empty($check)){ return $check['ShortUrl']['url']; } return false; } /** * encode the id to a few chars * * @param int $id * @return string the code for the short url */ private function __encode($id){ $return = ''; while ($id > 0) { $return = substr($this->__codeSet, ($id % $this->__base), 1) . $return; $id = floor($id / $this->__base); } return $return; } /** * decode a short url to figure out the correct long url that will be * returned. * * @param string $data the code from the short url * @return int the id of the record that has the url */ private function __decode($data){ $return = ''; $i = strlen($data); for ($i; $i; $i--) { $return += strpos($this->__codeSet, substr($data, (-1 * ($i - strlen($data))), 1)) * pow($this->__base,$i-1); } return $return; } }<file_sep><?php class CategoriesEventsTestCase extends CakeTestCase { public $fixtures = array( 'plugin.crons.cron' ); public function startTest() { $this->Event = EventCore::getInstance(); $this->Cron = ClassRegistry::init('Crons.Cron'); } public function endTest() { unset($this->Event, $this->Cron); ClassRegistry::flush(); } /** * test if the checks are working fine */ public function testAreCronsSetup(){ $expected = array('areCronsSetup' => array('crons' => '2010-12-07 14:21:01')); $this->assertEqual($expected, $this->Event->trigger($this, 'crons.areCronsSetup')); $this->Cron->deleteAll(array('Cron.id != 1')); $expected = array('areCronsSetup' => array('crons' => false)); $this->assertEqual($expected, $this->Event->trigger($this, 'crons.areCronsSetup')); } /** * test the todo list stuff is working fine */ public function testRequireTodoList(){ /** * were running but broke/stoped */ $expected = array('requireTodoList' => array('crons' => array( array('name' => '/^The crons are not running, last run was (.*)$/', 'type' => 'error', 'url' => '#') ))); $event = $this->Event->trigger($this, 'crons.requireTodoList'); $this->assertEqual($expected['requireTodoList']['crons'][0]['type'], $event['requireTodoList']['crons'][0]['type']); $this->assertEqual($expected['requireTodoList']['crons'][0]['url'], $event['requireTodoList']['crons'][0]['url']); $this->assertTrue(preg_match($expected['requireTodoList']['crons'][0]['name'], $event['requireTodoList']['crons'][0]['name'])); /** * have never been setup */ $this->Cron->deleteAll(array('Cron.id != 1')); $expected = array('requireTodoList' => array('crons' => array( array('name' => 'Crons are not configured yet', 'type' => 'warning', 'url' => '#') ))); $this->assertEqual($expected, $this->Event->trigger($this, 'crons.requireTodoList')); /** * running fine */ $this->assertTrue($this->Cron->start()); $expected = array('requireTodoList' => array('crons' => true)); $this->assertEqual($expected, $this->Event->trigger($this, 'crons.requireTodoList')); } }<file_sep><?php /** * @brief GlobalLayout handles the CRUD for layouts within infinitas * * @copyright Copyright (c) 2010 <NAME> ( dogmatic69 ) * @link http://www.infinitas-cms.org * @package Infinitas.Contents.models * @license http://www.opensource.org/licenses/mit-license.php The MIT License * @since 0.8a * * @author dogmatic69 * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. */ class GlobalLayout extends ContentsAppModel{ /** * the model name * * @var string * @access public */ public $name = 'GlobalLayout'; /** * enable the row locking for layouts * * @ref LockableBehavior * * @var bool * @access public */ public $lockable = true; /** * The table to use for layouts * * @bug this could be causing the installer to not include the prefix when * installing infinitas * * @var string * @access public */ public $useTable = 'global_layouts'; /** * belongs to relations for the GlobalLayout model * * @var array * @access public */ public $belongsTo = array( 'GlobalContent' => array( 'className' => 'Contents.GlobalContent', 'counterCache' => true ) ); /** * The GlobalContent model * * @var GlobalContent * @access public */ public $GlobalContent; /** * @copydoc AppModel::__construct() */ public function __construct($id = false, $table = null, $ds = null) { parent::__construct($id, $table, $ds); $this->validate = array( 'name' => array( 'notEmpty' => array( 'rule' => 'notEmpty', 'message' => __('Please enter the name of this template', true) ), 'isUnique' => array( 'rule' => 'isUnique', 'message' => __('There is already a template with that name', true) ) ), 'html' => array( 'notEmpty' => array( 'rule' => 'notEmpty', 'message' => __('Please create the html for your template', true) ) ), 'plugin' => array( 'notEmpty' => array( 'rule' => 'notEmpty', 'message' => __('Please select the plugin that this layout is for', true) ) ), 'model' => array( 'notEmpty' => array( 'rule' => 'notEmpty', 'message' => __('Please select the model that this layout is for', true) ) ) ); } /** * @copydoc AppModel::beforeSave() * * Before saving the record make sure that the model is set to the correct * value so that it will be linked up properly to the related rows. */ public function beforeSave($options){ $this->data['GlobalLayout']['model'] = $this->data['GlobalLayout']['plugin'] . '.' . $this->data['GlobalLayout']['model']; return true; } /** * @copydoc AppModel::afterFind() * * after getting the data split the model into its plugin / model parts * for the ajax selects to work properly */ public function afterFind($results, $primary = false) { parent::afterFind($results, $primary); if(isset($results[0][$this->alias]['model'])){ foreach($results as $k => $result){ $parts = pluginSplit($results[$k][$this->alias]['model']); $results[$k][$this->alias]['model_class'] = $results[$k][$this->alias]['model']; $results[$k][$this->alias]['plugin'] = $parts[0]; $results[$k][$this->alias]['model'] = $parts[1]; } } return $results; } }<file_sep><?php /* * Short Description / title. * * Overview of what the file does. About a paragraph or two * * Copyright (c) 2010 <NAME> ( dogmatic69 ) * * @filesource * @copyright Copyright (c) 2010 <NAME> ( dogmatic69 ) * @link http://www.infinitas-cms.org * @package {see_below} * @subpackage {see_below} * @license http://www.opensource.org/licenses/mit-license.php The MIT License * @since {check_current_milestone_in_lighthouse} * * @author {your_name} * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. */ class ThemesComponent extends InfinitasComponent{ public function initialize(&$Controller, $settings = array()){ $event = $Controller->Event->trigger($Controller->plugin.'.setupThemeStart'); if (isset($event['setupThemeStart'][$Controller->plugin])) { if (is_string($event['setupThemeStart'][$Controller->plugin])) { $Controller->theme = $event['setupThemeStart'][$Controller->plugin]; return true; } else if ($event['setupThemeStart'][$Controller->plugin] === false) { return false; } } $Controller->layout = 'front'; if (isset($Controller->params['admin'] ) && $Controller->params['admin']){ $Controller->layout = 'admin'; } $event = $Controller->Event->trigger($Controller->plugin.'.setupThemeLayout', array('layout' => $Controller->layout, 'params' => $Controller->params)); if (isset($event['setupThemeLayout'][$Controller->plugin])) { if (is_string($event['setupThemeLayout'][$Controller->plugin])) { $Controller->layout = $event['setupThemeLayout'][$Controller->plugin]; } } if(!$theme = Cache::read('currentTheme')) { $theme = ClassRegistry::init('Themes.Theme')->getCurrentTheme(); } if (!isset($theme['Theme']['name'])) { $theme['Theme'] = array('name' => null); } else { $event = $Controller->Event->trigger($Controller->plugin.'.setupThemeSelector', array('theme' => $theme['Theme'], 'params' => $Controller->params)); if (isset($event['setupThemeSelector'][$Controller->plugin])) { if (is_array($event['setupThemeSelector'][$Controller->plugin])) { $theme['Theme'] = $event['setupThemeSelector'][$Controller->plugin]; if (!isset($theme['Theme']['name'])) { $this->cakeError('eventError', array('message' => 'The theme is invalid.', 'event' => $event)); } } } } $Controller->theme = $theme['Theme']['name']; Configure::write('Theme', $theme['Theme']); $event = $Controller->Event->trigger($Controller->plugin.'.setupThemeRoutes', array('params' => $Controller->params)); if (isset($event['setupThemeRoutes'][$Controller->plugin]) && !$event['setupThemeRoutes'][$Controller->plugin]) { return false; } $routes = Cache::read('routes', 'core'); if (empty($routes)) { $routes = Classregistry::init('Routes.Route')->getRoutes(); } $currentRoute = Router::currentRoute(Configure::read('CORE.current_route')); if (!empty($routes) && is_object($currentRoute)) { foreach( $routes as $route ){ if ( $route['Route']['url'] == $currentRoute->template && !empty($route['Route']['theme'])) { $Controller->theme = $route['Route']['theme']; } } } $event = $Controller->Event->trigger($Controller->plugin.'.setupThemeEnd', array('theme' => $Controller->theme, 'params' => $Controller->params)); if (isset($event['setupThemeEnd'][$Controller->plugin])) { if (is_string($event['setupThemeEnd'][$Controller->plugin])) { $Controller->theme = $event['setupThemeEnd'][$Controller->plugin]; } } return true; } }<file_sep><?php class Country extends ManagementAppModel { } ?> <file_sep><?php /** * @brief The Branch model. * * CRUD for database of Contact branches * * @copyright Copyright (c) 2010 <NAME> ( dogmatic69 ) * @link http://www.infinitas-cms.org * @package Infinitas.Contact.models * @license http://www.opensource.org/licenses/mit-license.php The MIT License * @since 0.7a * * @author dogmatic69 * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. */ class Branch extends ContactAppModel{ /** * the name of the class * * @var string * @access public */ public $name = 'Branch'; /** * behaviors that are attached to this model * * @var array * @access public */ public $actsAs = array( 'MeioUpload.MeioUpload' => array( 'image' => array( 'dir' => 'img{DS}content{DS}contact{DS}{ModelName}', 'create_directory' => true, 'allowed_mime' => array( 'image/jpeg', 'image/pjpeg', 'image/png' ), 'allowed_ext' => array( '.jpg', '.jpeg', '.png' ), 'validations' => array( 'Empty' => array( ) ), 'Empty' => array( ) ) ), 'Libs.Sluggable' => array( 'label' => array( 'name' ) ) ); /** * hasMany related models * * @var array * @access public */ public $hasMany = array( 'Contact.Contact' ); /** * The Contact model * * @var Contact * @access public */ public $Contact; /** * belongsTo related models * * @var array * @access public */ public $belongsTo = array( 'Contact.Address' ); /** * The Address model * * @var Address * @access public */ public $Address; /** * @copydoc AppModel::__construct() */ public function __construct($id = false, $table = null, $ds = null) { parent::__construct($id, $table, $ds); $this->validate = array( 'name' => array( 'notEmpty' => array( 'rule' => 'notEmpty', 'message' => __('Please enter the name of your branch', true) ), ), 'address' => array( 'notEmpty' => array( 'rule' => 'notEmpty', 'message' => __('Please enter the branches address', true) ) ), 'phone' => array( 'notEmpty' => array( 'rule' => 'notEmpty', 'message' => __('Please enter some text for the body', true) ), 'phone' => array( 'rule' => array('phone', '/\D?(\d{3})\D?\D?(\d{3})\D?(\d{4})$/'), //Configure::read('Website.phone_regex')), 'message' => __('The number does not seem to be valid', true) ) ), 'fax' => array( 'phone' => array( 'rule' => array('phone', '/\D?(\d{3})\D?\D?(\d{3})\D?(\d{4})$/'), //Configure::read('Website.phone_regex')), 'message' => __('Please enter a valid fax number', true), 'allowEmpty' => true ) ), 'time_zone_id' => array( 'comparison' => array( 'rule' => array('comparison', '>', 0), 'message' => __('Please select your time zone', true) ) ) ); } /** * @todo list all the time zones so that the current time can be shown * of different branches. * * @param array $queryData the find data * * @return bool */ public function beforeFind($queryData){ return true; } }<file_sep><?php class AcosController extends ManagementAppController { var $name = 'Acos'; function admin_index() { $acos = $this->Aco->find( 'all', array( 'fields' => array( 'Aco.id', 'Aco.parent_id', 'Aco.model', 'Aco.foreign_key', 'Aco.alias', 'Aco.lft', 'Aco.rght', ), 'conditions' => array( //'Aco.rght = Aco.lft + 1' 'Aco.parent_id > 1' ), 'contain' => array( 'ParentAco' => array( 'fields' => array( 'ParentAco.id', 'ParentAco.alias' ) ) ) ) ); $this->set(compact('acos')); } function admin_view($id = null) { if (!$id) { $this->Session->setFlash(__('Invalid aco', true)); $this->redirect(array('action' => 'index')); } $this->set('aco', $this->Aco->read(null, $id)); } function admin_add() { if (!empty($this->data)) { $this->Aco->create(); if ($this->Aco->save($this->data)) { $this->Session->setFlash(__('The aco has been saved', true)); $this->redirect(array('action' => 'index')); } else { $this->Session->setFlash(__('The aco could not be saved. Please, try again.', true)); } } $parentAcos = $this->Aco->ParentAco->find('list'); $aros = $this->Aco->Aro->find('list'); $this->set(compact('parentAcos', 'aros')); } function admin_edit($id = null) { if (!$id && empty($this->data)) { $this->Session->setFlash(__('Invalid aco', true)); $this->redirect(array('action' => 'index')); } if (!empty($this->data)) { if ($this->Aco->save($this->data)) { $this->Session->setFlash(__('The aco has been saved', true)); $this->redirect(array('action' => 'index')); } else { $this->Session->setFlash(__('The aco could not be saved. Please, try again.', true)); } } if (empty($this->data)) { $this->data = $this->Aco->read(null, $id); } $parentAcos = $this->Aco->ParentAco->find('list'); $aros = $this->Aco->Aro->find('list'); $this->set(compact('parentAcos', 'aros')); } }<file_sep><?php $map = array( 1 => array( '000008_filter' => 'R4c94edcc54904167a8cc78d86318cd70'), ); ?><file_sep><?php class Trash extends TrashAppModel { public $useTable = 'trash'; public $belongsTo = array( 'User' => array( 'className' => 'Users.User', 'foreignKey' => 'deleted_by', 'fields' => array( 'User.id', 'User.username' ) ) ); public function restore($ids) { $trashed = $this->find('all', array('conditions' => array('id' => $ids))); $result = true; foreach($trashed as $trash) { $data = unserialize($trash['Trash']['data']); $model = ClassRegistry::init($trash['Trash']['model']); if($model) { $model->create(); $result = $result && $model->save($data); $this->delete($trash['Trash']['id']); } } return $result; } }<file_sep><div class="dashboard half"> <?php echo sprintf(__('<h1>%s</h1>', true), __('Overall usage statistics', true)); ?> <table class="listing" style="margin: auto; width: 96%; background: none;"> <thead> <tr> <th colspan="3"><?php __('Server Loads'); ?></th> </tr> </thead> <tbody> <tr> <th rowspan="2"><?php __('Memory'); ?>&nbsp</th> <td><?php __('Agerage'); ?>&nbsp</td> <td class="right"><?php echo convert($allTime['average_memory']); ?>&nbsp</td> </tr> <tr> <td><?php echo __('Max'); ?>&nbsp</td> <td class="right"><?php echo convert($allTime['max_memory']); ?>&nbsp</td> </tr> <tr> <th rowspan="2"><?php __('Load'); ?>&nbsp</th> <td><?php __('Agerage'); ?>&nbsp</td> <td class="right"><?php echo $allTime['average_load']; ?>&nbsp</td> </tr> <tr> <td><?php echo __('Max'); ?>&nbsp</td> <td class="right"><?php echo $allTime['max_load']; ?>&nbsp</td> </tr> </tbody> </table> </div><file_sep><?php class CronsEvents extends AppEvents{ public function onSetupConfig($event, $data = null) { Configure::load('crons.config'); } /** * @copydoc AppError::onRequireTodoList() * * Check if the crons are running and if not add a notice to the admin * so that they can take action. If they are setup but something has * gone wrong and they are not running show an error. */ public function onRequireTodoList($event) { $crons = $this->onAreCronsSetup(); if(!$crons){ return array( array( 'name' => __('Crons are not configured yet', true), 'type' => 'warning', 'url' => '#' ) ); } else if(date('Y-m-d H:i:s', strtotime('-' . Configure::read('Cron.run_every'))) > $crons){ App::import('Helper', 'Time'); $Time = new TimeHelper(); return array( array( 'name' => sprintf(__('The crons are not running, last run was %s', true), $Time->timeAgoInWords($crons)), 'type' => 'error', 'url' => '#' ) ); } return true; } /** * @brief check if crons are running * * @return string|bool false if not, or datetime of last run */ public function onAreCronsSetup(){ $date = ClassRegistry::init('Crons.Cron')->getLastRun(); return $date ? date('Y-m-d H:i:s', strtotime($date)) : $date; } /** * @brief housekeeping, clear out old cron logs. * * @param <type> $event * @return <type> */ public function onRunCrons($event) { ClassRegistry::init('Crons.Cron')->clearOldLogs(); return true; } }<file_sep><?php /** * * */ class ModulesController extends ModulesAppController{ public $name = 'Modules'; public function admin_index() { $this->paginate = array( 'contain' => array( 'Position', 'Group' ) ); $modules = $this->paginate(null, $this->Filter->filter); $filterOptions = $this->Filter->filterOptions; $filterOptions['fields'] = array( 'name', 'plugin' => $this->Module->getPlugins(), 'theme_id' => array(null => __('All', true)) + $this->Module->Theme->find('list'), 'position_id' => array(null => __('All', true)) + $this->Module->Position->find('list'), 'author', 'licence', 'group_id' => array(null => __('Public', true)) + $this->Module->Group->find('list'), 'core' => Configure::read('CORE.core_options'), 'active' => Configure::read('CORE.active_options') ); $this->set(compact('modules', 'filterOptions')); } public function admin_add() { parent::admin_add(); $positions = $this->Module->Position->find('list'); $groups = $this->Module->Group->find('list'); $routes = array(0 => __('All Pages', true)) + $this->Module->Route->find('list'); $themes = array(0 => __('All Themes', true)) + $this->Module->Theme->find('list'); $plugins = $this->Module->getPlugins(); $modules = $this->Module->getModuleList(); $this->set(compact('positions', 'groups', 'routes', 'themes', 'plugins', 'modules')); } public function admin_edit($id = null) { parent::admin_edit($id); $positions = $this->Module->Position->find('list'); $groups = $this->Module->Group->find('list'); $routes = array(0 => __('All Pages', true)) + $this->Module->Route->find('list'); $themes = array(0 => __('All Themes', true)) + $this->Module->Theme->find('list'); $plugins = $this->Module->getPlugins(); $modules = $this->Module->getModuleList($this->data['Module']['plugin']); $this->set(compact('positions', 'groups', 'routes', 'themes', 'plugins', 'modules')); } /** * get a list of modules that can be used. * * Gets the plugin name from POST data to find the required modules. */ public function admin_getModules(){ if (!isset($this->params['named']['plugin'])) { $this->set('json', array('error')); return; } $this->set('json', $this->{$this->modelClass}->getModuleList($this->params['named']['plugin'])); } }<file_sep><?php /** * * */ class RobotsController extends WebmasterAppController{ public $name = 'Robots'; public $uses = array(); /** * takes your robots.txt */ public function admin_edit(){ Configure::write('Wysiwyg.editor', 'text'); $File = new File(APP . 'webroot' . DS . 'robots.txt'); if(isset($this->data['Robot']['robots']) && !empty($this->data['Robot']['robots'])){ if($File->write(sprintf('Sitemap: %ssitemap.xml%s%s', Router::url('/', true), "\n", $this->data['Robot']['robots']))){ $this->notice( __('Robots file updated', true), array( 'redirect' => array('controller' => 'webmaster', 'action' => 'dashboard') ) ); } $this->notice( __('There was a problem updating the robots file', true), array( 'level' => 'error' ) ); } if(!isset($this->data['Robot']['robots'])){ $this->data['Robot']['robots'] = $File->read(); } } }<file_sep><?php /** * Comment Template. * * @todo Implement .this needs to be sorted out. * * Copyright (c) 2009 <NAME> ( dogmatic69 ) * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. * @filesource * @copyright Copyright (c) 2009 <NAME> ( dogmatic69 ) * @link http://infinitas-cms.org * @package sort * @subpackage sort.comments * @license http://www.opensource.org/licenses/mit-license.php The MIT License * @since 0.5a */ class Install extends Model { public $name = 'Install'; public $useTable = false; public $useDbConfig = false; public $actsAs = false; public function __construct($id = false, $table = null, $ds = null) { parent::__construct($id, $table, $ds); $this->validate = array( 'driver' => array( 'rule' => 'notempty', 'message' => __('You need to select a database engine', true) ), 'database' => array( 'rule' => 'notempty', 'message' => __('You need to enter a database name', true) ), 'login' => array( 'rule' => 'notempty', 'message' => __('You need to enter the username used to connect to the database', true) ), 'host' => array( 'rule' => 'notempty', 'message' => __('You need to enter the host for your database', true) ), ); } /** * Ucky hacks to make the model work without a datasource */ public $_schema = array(); public function find() { return true; } }<file_sep><?php /* SVN FILE: $Id$ */ /* ServerStatus schema generated on: 2010-12-07 14:12:58 : 1291731058*/ class ServerStatusSchema extends CakeSchema { var $name = 'ServerStatus'; function before($event = array()) { return true; } function after($event = array()) { } } ?><file_sep><?php /** * Install additional plugins and thmese * * Copyright (c) 2009 <NAME> ( dogmatic69 ) * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. * * @filesource * @copyright Copyright (c) 2009 <NAME> ( dogmatic69 ) * @link http://infinitas-cms.org * @package Infinitas.categories * @subpackage Infinitas.categories.admin_form * @license http://www.opensource.org/licenses/mit-license.php The MIT License * @since 0.5a * * @author dogmatic69 */ echo $this->Form->create('Install', array('type' => 'file')); echo $this->Infinitas->adminEditHead(); ?> <fieldset> <h1><?php echo __('Install From disk', true); ?></h1><?php echo $this->Form->input('file', array('type' => 'file')); ?> </fieldset> <fieldset> <h1><?php echo __('Install From the web', true); ?></h1><?php echo $this->Form->input('url'); ?> </fieldset> <fieldset> <h1><?php echo __('Install from Infinitas', true); ?></h1><?php echo __('Coming soon', true); ?> </fieldset><?php echo $this->Form->end(); ?><file_sep><?php class CsvHelper extends AppHelper{ /** * fields to ignore * * @var unknown_type */ var $ignore = array( 'id' ); var $helpers = array( 'Session' ); /** * convert data to csv * * @param array $rows the data from a find * @param $params */ function output($rows = null, $params = array(), $generated = true){ if(!$rows || empty($params)){ return false; } $row = array(); if (!empty($rows)){ foreach($params['needed'][key($params['needed'])] as $head){ if (!in_array($head, $this->ignore)){ if($head == 'id'){ $parts[] = __(Inflector::humanize(key($params['needed'])), true).' #'; continue; } $parts[] = __(Inflector::humanize(str_replace('_id', ' #', $head)), true); } } $row[] = implode(',', $parts); foreach($rows as $k => $array){ $parts = array(); foreach($array[key($params['needed'])] as $field => $value){ if (!in_array($field, $this->ignore)){ if($field == 'id'){ $parts[] = str_pad($value, 5, 0, STR_PAD_LEFT); } else if (strpos($field, '_id') && in_array($field, $params['needed'][key($params['needed'])])){ $parts[] = $array[Inflector::camelize(str_replace('_id', '' , $field))][ClassRegistry::init(Inflector::camelize(str_replace('_id', '' , $field)))->displayField]; } else if (in_array($field, $params['needed'][key($params['needed'])])){ $parts[] = $value; } else{ $parts[] = ''; } } } $row[] = implode(',', $parts); unset($parts); } } if($generated){ $row[] = ''; $row[] = sprintf(__('Generated on the %s at %s by %s', true), date('Y-m-d'), date('H:m:s'), $this->Session->read('Auth.User.username')); } return $csv = implode("\r\n", $row); } }<file_sep><?php class EventBehavior extends ModelBehavior { var $name = 'Events'; /** * Trigger a event * * @param string $eventName Name of the event to trigger * @param array $data Data to pass to event handler * @return array: */ public function triggerEvent($Model, $eventName, $data = array()){ return EventCore::trigger($Model, $eventName, $data); } }<file_sep><?php /** * Events for the Infinitas Short Urls * * Copyright (c) 2010 <NAME> ( dogmatic69 ) * * @filesource * @copyright Copyright (c) 2010 <NAME> ( dogmatic69 ) * @link http://www.infinitas-cms.org * @package Infinitas.short_urls * @subpackage Infinitas.short_urls.events * @license http://www.opensource.org/licenses/mit-license.php The MIT License * @since 0.8a * * @author dogmatic69 * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. */ final class ShortUrlsEvents extends AppEvents{ public function onAdminMenu($event){ $menu['main'] = array( 'Short Urls' => array('plugin' => 'short_urls', 'controller' => 'short_urls', 'action' => 'index') ); return $menu; } public function onSetupRoutes(){ // preview Router::connect( '/s/p/*', array( 'admin' => false, 'prefix' =>false, 'plugin' => 'short_urls', 'controller' => 'short_urls', 'action' => 'preview' ) ); // redirect Router::connect( '/s/*', array( 'admin' => false, 'plugin' => 'short_urls', 'controller' => 'short_urls', 'action' => 'view' ) ); } public function onShortenUrl($event, $url){ } public function onSlugUrl($event, $data){ $data['type'] = isset($data['type']) ? $data['type'] : ''; switch($data['type']){ case 'preview': return array( 'admin' => false, 'plugin' => 'short_urls', 'controller' => 'short_urls', 'action' => 'preview', $data['code'] ); break; default: return array( 'admin' => false, 'plugin' => 'short_urls', 'controller' => 'short_urls', 'action' => 'view', $data['code'] ); break; } } /** * event to create short urls from anywere in the code. show a preview * link by setting type => preview or leave type out type to go direct to * the url * * @param $event the event object * @param $data array of type and url * @return array a cake url array for the short url that was created */ public function onGetShortUrl($event, $data){ $data['code'] = ClassRegistry::init('ShortUrls.ShortUrl')->shorten($data['url']); if(!$data['code']){ $this->cakeError('error404', __('That url seems invalid', true)); } return $this->onSlugUrl($event, $data); } }<file_sep><?php /* Address Test cases generated on: 2010-03-13 11:03:14 : 1268471054*/ App::import('Model', 'Management.Address'); class AddressTestCase extends CakeTestCase { function startTest() { $this->Address =& ClassRegistry::init('Address'); } function endTest() { unset($this->Address); ClassRegistry::flush(); } } ?><file_sep><?php /** * Feed model * * Add some documentation for Feed model. * * Copyright (c) {yourName} * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. * * @filesource * @copyright Copyright (c) 2009 {yourName} * @link http://infinitas-cms.org * @package Management * @subpackage Management.models.Feed * @license http://www.opensource.org/licenses/mit-license.php The MIT License */ class Feed extends FeedAppModel { public $name = 'Feed'; public $actsAs = array( // 'Libs.Commentable', // 'Libs.Rateable ); public $order = array( ); public $hasOne = array( ); public $belongsTo = array( 'Group' => array( 'className' => 'Users.Group', 'fields' => array( 'Group.id', 'Group.name' ) ) ); public $hasMany = array( ); public $hasAndBelongsToMany = array( 'FeedsFeed' => array( 'className' => 'Feed.FeedsFeed', 'joinTable' => 'global_feeds_feeds', 'with' => 'Feed.FeedsFeed', 'foreignKey' => 'main_feed_id', 'associationForeignKey' => 'sub_feed_id', 'unique' => true, 'conditions' => '', 'fields' => '', 'order' => '', 'limit' => '', 'offset' => '', 'finderQuery' => '', 'deleteQuery' => '', 'insertQuery' => '' ) ); public function __construct($id = false, $table = null, $ds = null) { parent::__construct($id, $table, $ds); $this->validate = array( 'name' => array( 'notEmpty' => array( 'rule' => 'notEmpty', 'message' => __('Please enter a name for your feed item', true) ), 'isUnique' => array( 'rule' => 'isUnique', 'message' => __('There is already a feed item with that name', true) ) ), 'fields' => array( 'validateJson' => array( 'rule' => 'validateJson', 'message' => __('Your fields are not valid', true) ) ), 'conditions' => array( 'validateJson' => array( 'rule' => 'validateJson', 'message' => __('Your conditions are not valid', true) ) ), 'order' => array( 'validateJson' => array( 'rule' => 'validateJson', 'message' => __('Your order is not valid', true) ) ), ); } public function listFeeds(){ $feeds = $this->find( 'all', array( 'conditions' => array( 'Feed.active' => 1 ), 'fields' => array( 'Feed.id', 'Feed.name', 'Feed.slug' ) ) ); $return = array(); foreach($feeds as $feed){ $return[] = array( 'name' => $feed['Feed']['name'], 'url' => Router::url(array('plugin' => 'feed', 'controller' => 'feeds', 'action' => 'view', 'slug' => $feed['Feed']['slug']), true) ); } return $return; } public function getFeed($slug = null, $group_id = 999){ if(!$slug){ return array(); } $mainFeed = $this->find( 'first', array( 'conditions' => array( 'Feed.active' => 1, //'Feed.group_id > ' => $group_id, 'Feed.slug' => $slug ) ) ); if(empty($mainFeed)){ return array(); } $items = ClassRegistry::init('Feed.FeedsFeed')->find( 'list', array( 'conditions' => array('FeedsFeed.main_feed_id' => $mainFeed['Feed']['id']), 'fields' => array('FeedsFeed.sub_feed_id', 'FeedsFeed.sub_feed_id') ) ); if(empty($items)){ return array(); } $items = $this->find( 'all', array( 'conditions' => array( 'Feed.id' => $items, 'Feed.active' => 1 ) ) ); if(empty($items)){ return array(); } foreach($items as $item){ $mainFeed['FeedItem'][] = $item['Feed']; } return $this->feedArrayFormat($this->getJsonRecursive($mainFeed)); } public function feedArrayFormat($feed = array()){ if (empty($feed)){ return array(); } $query['fields'] = $feed['Feed']['fields']; //$query['conditions'] = $feed['Feed']['conditions']; //$query['order'] = $feed['Feed']['order']; $query['limit'] = $feed['Feed']['limit']; $query['setup'] = array( 'plugin' => $feed['Feed']['plugin'], 'controller' => $feed['Feed']['controller'], 'action' => $feed['Feed']['action'] ); foreach($feed['FeedItem'] as $item){ $plugin = Inflector::camelize($item['plugin']); $controller = Inflector::camelize(Inflector::singularize($item['controller'])); $query['feed'][$plugin.'.'.$controller] = array( 'setup' => array( 'plugin' => $item['plugin'], 'controller' => $item['controller'], 'action' => $item['action'] ), 'fields' => $item['fields'], //'conditions' => $item['conditions'], //'limit' => $item['limit'] ); } $_Model = ClassRegistry::init($feed['Feed']['plugin'].'.'.Inflector::camelize(Inflector::singularize($feed['Feed']['controller']))); return $_Model->find('feed', $query); } }<file_sep><?php /* Config Test cases generated on: 2010-03-13 11:03:23 : 1268471123*/ App::import('Model', 'Configs.Config'); /** * ConfigTestCase * * @package * @author dogmatic * @copyright Copyright (c) 2010 * @version $Id$ * @access public */ class ConfigTestCase extends CakeTestCase { var $fixtures = array( 'plugin.configs.config' ); function startTest() { $this->Config = ClassRegistry::init('Configs.Config'); } function endTest() { unset($this->Config); ClassRegistry::flush(); } /** * Test custom validation rules * * Check that the correct options use the corect values. */ function testValidationRules(){ $data = array(); $this->assertTrue($this->Config->customOptionCheck(array('options' => 'no type set yet so dont validate'))); /** * test string inputs */ $this->Config->data['Config']['type'] = 'string'; $data['options'] = 'abc'; $this->assertTrue($this->Config->customOptionCheck($data)); $data['options'] = 123; $this->assertTrue($this->Config->customOptionCheck($data)); $data['options'] = null; $this->assertTrue($this->Config->customOptionCheck($data)); /** * test integer inputs */ $this->Config->data['Config']['type'] = 'integer'; $data['options'] = null; $this->assertFalse($this->Config->customOptionCheck($data)); $data['options'] = 'text'; $this->assertFalse($this->Config->customOptionCheck($data)); $data['options'] = 123; $this->assertTrue($this->Config->customOptionCheck($data)); /** * test dropdowns inputs */ $this->Config->data['Config']['type'] = 'dropdown'; $data['options'] = null; $this->assertFalse($this->Config->customOptionCheck($data)); $data['options'] = 'text'; $this->assertTrue($this->Config->customOptionCheck($data)); $data['options'] = 'option1,option2,option3,option4'; $this->assertTrue($this->Config->customOptionCheck($data)); $data['options'] = 'option1, option2, option3, option4'; $this->assertTrue($this->Config->customOptionCheck($data)); $data['options'] = 'option1 ,option2 ,option3 ,option4'; $this->assertTrue($this->Config->customOptionCheck($data)); $data['options'] = 'option1 ,option2, option3 ,option4'; $this->assertTrue($this->Config->customOptionCheck($data)); $data['options'] = 123; $this->assertFalse($this->Config->customOptionCheck($data)); /** * test bool */ $this->Config->data['Config']['type'] = 'bool'; $data['options'] = null; $this->assertFalse($this->Config->customOptionCheck($data)); $data['options'] = true; $this->assertFalse($this->Config->customOptionCheck($data)); $data['options'] = false; $this->assertFalse($this->Config->customOptionCheck($data)); $data['options'] = 'true,false'; $this->assertTrue($this->Config->customOptionCheck($data)); $data['options'] = 'false,true'; $this->assertTrue($this->Config->customOptionCheck($data)); /** * test array */ $this->Config->data['Config']['type'] = 'array'; $data = array(); $this->Config->data['Config']['value'] = null; $this->assertFalse($this->Config->customOptionCheck($data)); $this->Config->data['Config']['value'] = '{}'; $this->assertFalse($this->Config->customOptionCheck($data)); $this->Config->data['Config']['value'] = 'some text'; $this->assertFalse($this->Config->customOptionCheck($data)); // see more tests for checking json in the app model tests $this->Config->data['Config']['value'] = '{"hello":"world"}'; $this->assertTrue($this->Config->customOptionCheck($data)); } /** * Test geting config values. * * Make sure the values put in config is correct * * Need to bypass cache. */ function testGetConfigs(){ // value format $expected = array( array('Config' => array('key' => 'Test.bool_false', 'value' => false, 'type' => 'bool')), array('Config' => array('key' => 'Test.bool_true', 'value' => true, 'type' => 'bool')), array('Config' => array('key' => 'Test.int_normal', 'value' => 123, 'type' => 'integer')), array('Config' => array('key' => 'Test.int_string', 'value' => 987, 'type' => 'integer')), array('Config' => array('key' => 'Test.nested_array', 'value' => array('abc1' => array('abc2' => array( 'abc3' => array('abc4' => array('abc5' => 'xyz'))))), 'type' => 'array')), array('Config' => array('key' => 'Test.simple_array', 'value' => array('abc' => 'xyz'), 'type' => 'array')), array('Config' => array('key' => 'Test.string1', 'value' => 'this is a string', 'type' => 'string')), array('Config' => array('key' => 'Website.description', 'value' => 'Infinitas Cms is a open source content management system that is designed to be fast and user friendly, with all the features you need.', 'type' => 'string')), array('Config' => array('key' => 'Website.name', 'value' => 'Infinitas Cms', 'type' => 'string'))); $this->assertEqual($this->Config->getConfig(), $expected); // getting website configs for installer $expected = array( array( 'Config' => array( 'id' => 9, 'key' => 'Website.description', 'value' => 'Infinitas Cms is a open source content management system that is designed to be fast and user friendly, with all the features you need.', 'type' => 'string', 'options' => null, 'description' => 'This is the main description about the site', 'core' => 0 ) ), array( 'Config' => array( 'id' => 8, 'key' => 'Website.name', 'value' => 'Infinitas Cms', 'type' => 'string', 'options' => null, 'description' => '<p>This is the name of the site that will be used in emails and on the website its self</p>', 'core' => 0 ) ) ); $this->assertEqual($this->Config->getInstallSetupConfigs(), $expected); } public function testCacheRelatedStuff(){ $this->assertTrue(Cache::read('global_configs'), 'Nothing in the cache %s'); $cacheConfigs = $this->Config->getConfig(); $this->Config->afterSave(true); $this->assertFalse(Cache::read('global_configs')); $nonCacheConfigs = $this->Config->getConfig(); $this->assertTrue(Cache::read('global_configs'), 'Still nothing in the cache %s'); $this->assertEqual($cacheConfigs, $nonCacheConfigs); } public function testFormatting(){ $this->Config->afterSave(true); $configs = $this->Config->getConfig(true); $expect = array(); $expect['Test.bool_false'] = false; $expect['Test.bool_true'] = true; $expect['Test.int_normal'] = 123; $expect['Test.int_string'] = 987; $expect['Test.nested_array'] = array('abc1' => array('abc2' => array('abc3' => array('abc4' => array('abc5' => 'xyz'))))); $expect['Test.simple_array'] = array('abc' => 'xyz'); $expect['Test.string1'] = 'this is a string'; $expect['Website.description'] = 'Infinitas Cms is a open source content management system that is designed to be fast and user friendly, with all the features you need.'; $expect['Website.name'] = 'Infinitas Cms'; $this->assertEqual($expect, $configs); $configs = $this->Config->getConfig(true); $this->assertEqual($expect, $configs); } }<file_sep><?php $dashboardIcons = array( array( 'name' => 'Users', 'description' => 'Manage your sites users', 'icon' => '/users/img/icon.png', 'dashboard' => array( 'action' => 'index' ) ), array( 'name' => 'Groups', 'description' => 'Manage the different groups on your site', 'icon' => '/users/img/groups.png', 'dashboard' => array( 'controller' => 'groups', 'action' => 'index' ) ), array( 'name' => 'Access - ACL', 'description' => 'Manage who can view what', 'icon' => '/users/img/groups.png', 'dashboard' => array( 'controller' => 'access', 'action' => 'index' ) ) ); $dashboardIcons = $this->Menu->builDashboardLinks($dashboardIcons, 'user_dashboard'); ?> <div class="dashboard grid_16"> <h1><?php __('Email Manager', true); ?></h1> <ul class="icons"><li><?php echo implode('</li><li>', current((array)$dashboardIcons)); ?></li></ul> </div><file_sep><?php /** * * */ class Ticket extends ManagementAppModel{ var $name = 'Ticket'; }<file_sep><?php class CategoriesEventsTestCase extends CakeTestCase { var $fixtures = array( 'plugin.configs.config', 'plugin.themes.theme', 'plugin.routes.route', 'plugin.view_counter.view_count', 'plugin.categories.category', 'plugin.users.group', ); public function startTest() { $this->Event = EventCore::getInstance(); } public function endTest() { unset($this->Event); ClassRegistry::flush(); } public function testGenerateSiteMapData(){ $this->assertIsA($this->Event, 'EventCore'); $expected = array('siteMapRebuild' => array('categories' => array( array( 'url' => Router::url('/', true) . 'categories/categories', 'last_modified' => '2010-08-16 23:56:50', 'change_frequency' => 'monthly' ), array( 'url' => Router::url('/', true) . 'categories/categories/view/slug:category 1', 'last_modified' => '2010-08-16 23:56:50', 'change_frequency' => 'monthly' ), array( 'url' => Router::url('/', true) . 'categories/categories/view/slug:category 2', 'last_modified' => '2010-08-16 23:56:50', 'change_frequency' => 'monthly' ), array( 'url' => Router::url('/', true) . 'categories/categories/view/slug:category 2a', 'last_modified' => '2010-08-16 23:56:50', 'change_frequency' => 'monthly' ), array( 'url' => Router::url('/', true) . 'categories/categories/view/slug:category 4', 'last_modified' => '2010-08-16 23:56:50', 'change_frequency' => 'monthly' ), ))); $this->assertEqual($expected, $this->Event->trigger(new Object(), 'categories.siteMapRebuild')); } }<file_sep><?php /* * Short Description / title. * * Overview of what the file does. About a paragraph or two * * Copyright (c) 2010 <NAME> ( dogmatic69 ) * * @filesource * @copyright Copyright (c) 2010 <NAME> ( dogmatic69 ) * @link http://www.infinitas-cms.org * @package {see_below} * @subpackage {see_below} * @license http://www.opensource.org/licenses/mit-license.php The MIT License * @since {check_current_milestone_in_lighthouse} * * @author {your_name} * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. */ class Lock extends LocksAppModel{ public $name = 'Lock'; public $belongsTo = array( 'Locker' => array( 'className' => 'Users.User', 'foreignKey' => 'user_id', 'fields' => array( 'Locker.id', 'Locker.email', 'Locker.username' ) ) ); public function beforeDelete($cascade){ $this->Behaviors->detach('Trashable'); return parent::beforeDelete($cascade); } public function clearOldLocks(){ return $this->deleteAll( array( 'Lock.created < ' => date('Y-m-d H:m:s', strtotime(Configure::read('Locks.timeout'))) ) ); } }<file_sep><?php /* * Generic Json data fetcher. * * Copyright (c) 2010 <NAME> ( dogmatic69 ) * * @filesource * @copyright Copyright (c) 2010 <NAME> ( dogmatic69 ) * @link http://www.infinitas-cms.org * @package libs * @subpackage libs.models.datasources.json * @license http://www.opensource.org/licenses/mit-license.php The MIT License * @since 0.8a * * @author dogmatic69 * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. */ App::import('Datasource', 'Libs.ReaderSource'); class JsonSource extends ReaderSource { /** * Process json. * * Takes json and convers it to an array using json_decode * * @param string $response the json that will be converted * * @return array the data from json or empty array if there is nothing passed */ protected function _process($response = null) { if (empty($response)) { return array(); } $_response = json_decode($response); if(!empty($_response)){ $response = $_response; } // @todo app::import modeless AppModel and use the Infinitas->getJson() method. return $response; } }<file_sep><?php /* CoreModule Fixture generated on: 2010-08-17 12:08:19 : 1282046299 */ class ModuleFixture extends CakeTestFixture { var $name = 'Module'; var $table = 'core_modules'; var $fields = array( 'id' => array('type' => 'integer', 'null' => false, 'default' => NULL, 'length' => 10, 'key' => 'primary'), 'name' => array('type' => 'string', 'null' => false, 'default' => NULL, 'length' => 100, 'key' => 'unique'), 'content' => array('type' => 'text', 'null' => false, 'default' => NULL), 'module' => array('type' => 'string', 'null' => false, 'default' => NULL, 'length' => 100), 'config' => array('type' => 'text', 'null' => true, 'default' => NULL), 'theme_id' => array('type' => 'integer', 'null' => false, 'default' => '0', 'length' => 4), 'position_id' => array('type' => 'integer', 'null' => false, 'default' => '0', 'length' => 4), 'group_id' => array('type' => 'integer', 'null' => false, 'default' => '0'), 'ordering' => array('type' => 'integer', 'null' => false, 'default' => NULL, 'key' => 'index'), 'admin' => array('type' => 'boolean', 'null' => false, 'default' => '0', 'key' => 'index'), 'active' => array('type' => 'boolean', 'null' => false, 'default' => '0'), 'locked' => array('type' => 'boolean', 'null' => false, 'default' => NULL), 'locked_by' => array('type' => 'integer', 'null' => true, 'default' => NULL), 'locked_since' => array('type' => 'integer', 'null' => true, 'default' => NULL), 'show_heading' => array('type' => 'boolean', 'null' => false, 'default' => '1'), 'core' => array('type' => 'boolean', 'null' => false, 'default' => '0'), 'author' => array('type' => 'string', 'null' => true, 'default' => NULL, 'length' => 50), 'licence' => array('type' => 'string', 'null' => false, 'default' => NULL, 'length' => 75), 'url' => array('type' => 'string', 'null' => true, 'default' => NULL), 'update_url' => array('type' => 'string', 'null' => true, 'default' => NULL), 'created' => array('type' => 'datetime', 'null' => true, 'default' => NULL), 'modified' => array('type' => 'datetime', 'null' => true, 'default' => NULL), 'plugin' => array('type' => 'string', 'null' => false, 'default' => NULL, 'length' => 50), 'indexes' => array('PRIMARY' => array('column' => 'id', 'unique' => 1), 'name' => array('column' => 'name', 'unique' => 1), 'active' => array('column' => array('admin', 'active'), 'unique' => 0), 'ordering' => array('column' => 'ordering', 'unique' => 0)), 'tableParameters' => array('charset' => 'utf8', 'collate' => 'utf8_general_ci', 'engine' => 'InnoDB') ); var $records = array( array( 'id' => 2, 'name' => 'login', 'content' => '', 'module' => 'login', 'config' => '', 'theme_id' => 0, 'position_id' => 5, 'group_id' => 2, 'ordering' => 1, 'admin' => 0, 'active' => 1, 'locked' => 0, 'locked_by' => NULL, 'locked_since' => NULL, 'show_heading' => 0, 'core' => 0, 'author' => 'Infinitas', 'licence' => 'MIT', 'url' => 'http://infinitas-cms.org', 'update_url' => '', 'created' => '2010-01-19 00:30:53', 'modified' => '2010-06-02 14:53:06', 'plugin' => 'management' ), array( 'id' => 4, 'name' => 'Popular Posts', 'content' => '', 'module' => '', 'config' => '', 'theme_id' => 0, 'position_id' => 4, 'group_id' => 1, 'ordering' => 1, 'admin' => 0, 'active' => 1, 'locked' => 0, 'locked_by' => 0, 'locked_since' => 0, 'show_heading' => 1, 'core' => 0, 'author' => 'Infinitas', 'licence' => 'MIT', 'url' => 'http://www.i-project.co.za', 'update_url' => '', 'created' => '2010-01-19 00:58:20', 'modified' => '2010-05-12 03:40:56', 'plugin' => '' ), array( 'id' => 5, 'name' => 'search', 'content' => '', 'module' => 'search', 'config' => '', 'theme_id' => 0, 'position_id' => 5, 'group_id' => 2, 'ordering' => 2, 'admin' => 0, 'active' => 1, 'locked' => 0, 'locked_by' => NULL, 'locked_since' => NULL, 'show_heading' => 0, 'core' => 1, 'author' => 'Infinitas', 'licence' => '', 'url' => 'http://infinitas-cms.org', 'update_url' => '', 'created' => '2010-01-19 11:22:09', 'modified' => '2010-08-05 00:22:18', 'plugin' => 'news' ), array( 'id' => 7, 'name' => 'ThinkMoney Live', 'content' => '', 'module' => 'news', 'config' => '', 'theme_id' => 0, 'position_id' => 7, 'group_id' => 2, 'ordering' => 4, 'admin' => 0, 'active' => 1, 'locked' => 0, 'locked_by' => NULL, 'locked_since' => NULL, 'show_heading' => 1, 'core' => 0, 'author' => 'Infinitas', 'licence' => 'MIT', 'url' => 'http://www.i-project.co.za', 'update_url' => '', 'created' => '2010-01-19 11:40:45', 'modified' => '2010-08-16 16:49:06', 'plugin' => 'think' ), array( 'id' => 12, 'name' => 'Admin Menu', 'content' => '', 'module' => 'menu', 'config' => '{\"menu\":\"core_admin\"}', 'theme_id' => 0, 'position_id' => 1, 'group_id' => 1, 'ordering' => 1, 'admin' => 1, 'active' => 1, 'locked' => 0, 'locked_by' => 0, 'locked_since' => 0, 'show_heading' => 0, 'core' => 1, 'author' => 'Infinitas', 'licence' => 'MIT', 'url' => 'http://infinitas-cms.org', 'update_url' => '', 'created' => '2010-01-27 18:14:16', 'modified' => '2010-05-07 19:05:29', 'plugin' => 'management' ), array( 'id' => 13, 'name' => 'Frontend Menu', 'content' => '', 'module' => 'main_menu', 'config' => '{\"public\":\"main_menu\",\"registered\":\"registered_users\"}', 'theme_id' => 0, 'position_id' => 1, 'group_id' => 2, 'ordering' => 2, 'admin' => 0, 'active' => 1, 'locked' => 0, 'locked_by' => 0, 'locked_since' => 0, 'show_heading' => 0, 'core' => 1, 'author' => 'Infinitas', 'licence' => 'MIT', 'url' => 'http://infinitas-cms.org', 'update_url' => '', 'created' => '2010-02-01 00:57:01', 'modified' => '2010-05-13 20:29:15', 'plugin' => 'management' ), array( 'id' => 14, 'name' => 'Tag Cloud', 'content' => '', 'module' => 'post_tag_cloud', 'config' => '', 'theme_id' => 0, 'position_id' => 4, 'group_id' => 2, 'ordering' => 4, 'admin' => 0, 'active' => 1, 'locked' => 0, 'locked_by' => 0, 'locked_since' => 0, 'show_heading' => 1, 'core' => 1, 'author' => 'Infinitas', 'licence' => 'MIT', 'url' => 'http://infinitas-cms.org', 'update_url' => '', 'created' => '2010-02-01 16:01:01', 'modified' => '2010-05-07 19:06:29', 'plugin' => 'blog' ), array( 'id' => 15, 'name' => 'Post Dates', 'content' => '', 'module' => 'post_dates', 'config' => '', 'theme_id' => 0, 'position_id' => 4, 'group_id' => 2, 'ordering' => 5, 'admin' => 0, 'active' => 1, 'locked' => 0, 'locked_by' => 0, 'locked_since' => 0, 'show_heading' => 1, 'core' => 1, 'author' => 'Infinitas', 'licence' => 'MIT', 'url' => 'http://infinitas-cms.org', 'update_url' => '', 'created' => '2010-02-01 16:34:00', 'modified' => '2010-05-07 19:06:56', 'plugin' => 'blog' ), array( 'id' => 16, 'name' => 'Google analytics', 'content' => '', 'module' => 'google_analytics', 'config' => '{\"code\":\"UA-xxxxxxxx-x\"}', 'theme_id' => 0, 'position_id' => 13, 'group_id' => 2, 'ordering' => 1, 'admin' => 0, 'active' => 0, 'locked' => 0, 'locked_by' => NULL, 'locked_since' => NULL, 'show_heading' => 0, 'core' => 1, 'author' => 'Infinitas', 'licence' => 'MIT', 'url' => 'http://infinitas-cms.org', 'update_url' => '', 'created' => '2010-02-01 20:45:05', 'modified' => '2010-08-05 01:47:17', 'plugin' => '' ), array( 'id' => 24, 'name' => '<NAME>', 'content' => '', 'module' => 'rate', 'config' => '', 'theme_id' => 0, 'position_id' => 4, 'group_id' => 2, 'ordering' => 1, 'admin' => 0, 'active' => 1, 'locked' => 0, 'locked_by' => 0, 'locked_since' => 0, 'show_heading' => 1, 'core' => 0, 'author' => 'Infinitas', 'licence' => 'MIT', 'url' => 'http://infinitas-cms.org/', 'update_url' => '', 'created' => '2010-05-10 20:06:53', 'modified' => '2010-05-11 12:40:08', 'plugin' => 'management' ), ); } ?><file_sep><?php class BouncedMail extends NewsletterAppModel{ public $name = 'BouncedMail'; /** * database configuration to use * * @var string */ public $useDbConfig = 'imap'; /** * Behaviors to attach * * @var mixed */ public $actsAs = false; /** * database table to use * * @var string */ public $useTable = false; public $server = array(); public function __construct($id = false, $table = null, $ds = null) { parent::__construct($id, $table, $ds); $this->server = array( 'server' => Configure::read('Newsletter.smtp_host'), 'username' => Configure::read('Newsletter.smtp_username'), 'email' => Configure::read('Newsletter.smtp_username'), 'password' => Configure::read('Newsletter.smtp_password'), 'ssl' => Configure::read('Newsletter.ssl'), 'port' => Configure::read('Newsletter.port'), 'type' => Configure::read('Newsletter.type') ); } }<file_sep><?php /** * @brief CommentsController is used for the management of comments * * allowing admins to view, toggle and delete as needed. * * @copyright Copyright (c) 2009 <NAME> ( dogmatic69 ) * @link http://infinitas-cms.org * @package Infinitas.Comments.controllers * @license http://www.opensource.org/licenses/mit-license.php The MIT License * @since 0.6a * * @author dogmatic69 * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. */ class CommentsController extends CommentsAppController { /** * the name of the controller * * @var sting * @access public */ public $name = 'Comments'; public function index(){ $conditions = array( 'Comment.active' => 1 ); if(isset($this->params['named']['Comment.class'])){ $conditions['Comment.class'] = $this->params['named']['Comment.class']; } if(isset($this->params['named']['Comment.foreign_id'])){ $conditions['Comment.foreign_id'] = $this->params['named']['Comment.foreign_id']; } $this->paginate = array( 'conditions' => $conditions, 'contain' => array( 'CommentAttribute' ) ); $this->set('comments', $this->paginate()); } public function admin_index() { $this->paginate = array( 'fields' => array( 'Comment.id', 'Comment.class', 'Comment.email', 'Comment.user_id', 'Comment.comment', 'Comment.active', 'Comment.status', 'Comment.points', 'Comment.foreign_id', 'Comment.created', ), 'contain' => array( 'CommentAttribute' ), 'order' => array( 'Comment.active' => 'asc', 'Comment.created' => 'desc', ), 'limit' => 20 ); $comments = $this->paginate(null, $this->Filter->filter); $filterOptions = $this->Filter->filterOptions; $filterOptions['fields'] = array( 'class' => $this->Comment->getUniqueClassList(), 'email', 'comment', 'active' => Configure::read('CORE.active_options') ); $this->set(compact('comments', 'filterOptions')); } public function admin_reply(){ // @todo reply to the comment. } public function admin_commentPurge($class = null) { if (!$class) { $this->Session->setFlash(__('Nothing chosen to purge', true)); $this->redirect($this->referer()); } if (!Configure::read('Comments.purge')) { $this->Session->setFlash(__('Purge is disabled', true)); $this->redirect($this->referer()); } $ids = ClassRegistry::init('Comment.Comment')->find( 'list', array( 'fields' => array( 'Comment.id', 'Comment.id' ), 'conditions' => array( 'Comment.class' => $class, 'Comment.active' => 0, 'Comment.created < ' => date('Y-m-d H:i:s', strtotime('-' . Configure::read('Comments.purge'))) ) ) ); if (empty($ids)) { $this->Session->setFlash(__('Nothing to purge', true)); $this->redirect($this->referer()); } $counter = 0; foreach($ids as $id) { if (ClassRegistry::init('Comment.Comment')->delete($id)) { $counter++; } } $this->Session->setFlash(sprintf(__('%s comments were purged.', true), $counter)); $this->redirect($this->referer()); } }<file_sep><?php class ServerStatusAppController extends AppController{ }<file_sep>/** * popup alert box * @access public * @return void **/ function pr(data){ alert(data); } /** * write data to console * @access public * @return void **/ function debug(data){ // better test http://benalman.com/projects/javascript-debug-console-log/ if(typeof console.log != 'undefined') { console.log(data); } } if(typeof Infinitas.params.prefix == 'undefined'){ Infinitas.params.prefix = 'frontend'; } switch(Infinitas.params.prefix) { case 'admin': $(document).ready(function(){ $('.tabs').tabs(); $('.accordions').accordion(); $.FormHelper.foucusOnFirst(); setupAjaxDropdowns(); setupRowSelecting(); setupDatePicker(); setupAjaxPagination(); $.FormHelper.checkboxToggleAll(); $(".trigger").click(function(){ $this = $(this); $this.siblings(".panel").toggle("fast"); $(".trigger").removeClass('active').siblings(".panel").hide(); $this.toggleClass("active"); return false; }); $('#PaginationOptionsPaginationLimit').change(function(){ $('#PaginationOptions').submit(); }); if($('.filter-form').length > 0){ $('.massActions').prepend('<button id="searchForm" name="action" value="search" type="submit"><span><img alt="" src="' + Infinitas.base + 'img/core/icons/actions/search.png"><br>Search</span></button>'); $('#searchForm').click(function(){ $('.filter-form').toggle(); return false; }); } $("[title]:not(.textarea *)").tooltip({ track: true, delay: 0, showURL: false, fixPNG: true, showBody: " :: ", left: 5, top: -5 }); $('#' + Infinitas.model + 'ImageId').imageSelect(); $('#ProductImageProductImage').imageSelect(); }); break; default: $(document).ready(function(){ $('.tabs').tabs(); //setupStarRating(); $("#accordion").accordion({ collapsible: true }); }); break; } /** core code */ /** * * @access public * @return void **/ function setupAjaxDropdowns(){ /** * Check for plugin dropdown changes */ $pluginSelect = $('.pluginSelect'); $pluginSelect.change(function(){ var $this = $(this); metaData = $.HtmlHelper.getParams($this); $.FormHelper.emptySelect(metaData); if ($this.val().length != 0) { metaData.params.plugin = $this.val(); $.HtmlHelper.requestAction(metaData, $.FormHelper.input); } }); /** * Check for controller dropdown changes */ $('.controllerSelect').change(function(){ var $this = $(this); metaData = $.HtmlHelper.getParams($this); $.FormHelper.emptySelect(metaData); if ($this.val().length != 0) { metaData.params.plugin = $pluginSelect.val(); metaData.params.controller = $this.val(); $.HtmlHelper.requestAction(metaData, $.FormHelper.input); } }); /** * Check for module changes */ $modulePuluginSelect = $('.modulePuluginSelect'); $modulePuluginSelect.change(function(){ var $this = $(this); metaData = $.HtmlHelper.getParams($this); $.FormHelper.emptySelect(metaData); if ($this.val().length != 0) { metaData.params.plugin = $('.modulePuluginSelect').val(); metaData.params.controller = $this.val(); $.HtmlHelper.requestAction(metaData, $.FormHelper.input); } }); } function setupRowSelecting(){ $("table.listing input:checkbox").change(function() { var $this = $(this); if ($this.attr("checked") == true) { $this .parents('tr') .removeClass('highlightRowRelated') .addClass("highlightRowSelected"); } else { $this.parents('tr').removeClass("highlightRowSelected"); } }); $('td').click(function(){ var $this = $(this) var col = $this.prevAll().length+1; if (col > 1){ var thisClicked = $.trim($this.text()); $('table.listing td:nth-child(' + col + ')' ).each(function() { var $_this = $(this); if (thisClicked == $.trim($_this.text())) { $_this.parent().removeClass('highlightRowSelected'); $_this.parent().addClass('highlightRowRelated'); } else{ $_this.parent().removeClass('highlightRowRelated'); } }); } }); } function setupStarRating() { var $rating = $('.star-rating'); metaData = $.HtmlHelper.getParams($rating); pr(metaData); url = $.HtmlHelper.url(metaData); $('.coreRatingBox').empty(); $rating.rater( url + metaData.url.id, { curvalue: metaData.currentRating } ); } function setupDatePicker() { var currentDate; var now = new Date(); now.setDate(now.getDate()); /** * Start dates */ var date1 = $("#" + Infinitas.model + "StartDate"); if(date1.length){ currentDate = now; if(date1.val() != '') { currentDate = date1.val().split('-'); currentDate = new Date (currentDate[0], currentDate[1]-1, currentDate[2]); } startDate = $("#" + Infinitas.model + "DatePickerStartDate").calendarPicker({ "date": currentDate, callback: function(cal){ date1.val(cal.mysqlDate); } }); } /** * end dates */ var date2 = $("#" + Infinitas.model + "EndDate"); if(date2.length){ currentDate = now; if(date2.val() != ''){ currentDate = date2.val().split('-'); currentDate = new Date (currentDate[0], currentDate[1]-1, currentDate[2]); } endDate = $("#" + Infinitas.model + "DatePickerEndDate").calendarPicker({ "date": currentDate, callback: function(cal){ date2.val(cal.mysqlDate); } }); } /** * general dates */ var date3 = $("#" + Infinitas.model + "Date"); if(date3.length){ currentDate = now; if(date3.val() != '') { currentDate = date3.val().split('-'); currentDate = new Date (currentDate[0], currentDate[1]-1, currentDate[2]); } date = $("#" + Infinitas.model + "DatePickerDate").calendarPicker({ "date": new Date (currentDate[0], currentDate[1]-1, currentDate[2]), callback: function(cal){ date3.val(cal.mysqlDate); } }); } } function setupAjaxPagination() { $link = $('a.ajax'); $.HtmlHelper.loading('showMore'); $link.live('click', function(event){ $('.showMore').remove(); $.ajax({ url: $(this).attr('href'), success: function(data, textStatus, XMLHttpRequest){ data = $('<div>'+data+'</div>').find('.list').children(); $('.list').append(data); data = ''; $.HtmlHelper.loading('', false); } }); return false; }); } ;(function($) { $.fn.imageSelect = function(options){ var opts = $.extend({}, $.fn.imageSelect.defaults, options); return this.each(function() { var $this = $(this); if(this.tagName == 'SELECT'){ $this.wrap('<div class="' + opts.containerClass + '">' ); var html = ''; $this.children('option').each(function(){ if(this.selected == true){ selectClass = 'selected'; } else{ selectClass = ''; } var src; if(opts.imageSrc == 'text'){ src = $(this).text(); } else{ src = this.value; } if ((this.value == '') || (this.value == undefined)) { /*html += '<a class="' + selectClass + ' ' + opts.imageClass + '" href="#select_' + this.value + '"><div style="background-color: #ccc; width: ' + opts.thumbnailWidth + 'px; height: ' + opts.thumbnailWidth + 'px">'+opts.emptyText+'</div></a>';*/ } else { html += '<a class="' + selectClass + ' ' + opts.imageClass + '" href="#select_' + this.value + '"><img src="' + src + '" style="width: ' + opts.thumbnailWidth + 'px" /></a>'; } }); $(this).after(html); $('a.image-select').click($.fn.imageSelect.selectImage); $this.css('display', 'none'); } }); } $.fn.imageSelect.selectImage = function(e){ var $selectBox = $(this).prevAll('select:first'); if($selectBox.attr('multiple') == true){ var $option = $selectBox.children('option[value='+this.href.split('_')[1]+']'); if($option.attr('selected') == true){ $option.attr('selected', false); $(this).removeClass('selected'); } else{ $option.attr('selected', true); $(this).addClass('selected'); } } else{ $selectBox.val(this.href.split('_')[1]); $(this).parent().children('a').removeClass('selected'); $(this).addClass('selected'); } return false; } $.fn.imageSelect.defaults = { containerClass: 'image-select-container', imageClass: 'image-select', imageSrc: 'text', thumbnailWidth: '60', emptyText: 'No image' }; })(jQuery);<file_sep><?php /** * @brief Categories base model * * The model that all the category related models extends from * * @copyright Copyright (c) 2010 <NAME> ( dogmatic69 ) * @link http://www.infinitas-cms.org * @package Infinitas.Categories * @license http://www.opensource.org/licenses/mit-license.php The MIT License * @since 0.8a * * @author dogmatic69 * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. */ class CategoriesAppModel extends AppModel { /** * the table prefix for this plugin * * @var string * @access public */ public $tablePrefix = 'global_'; /** * Customized paginateCount method * * @todo why is this needed * * @param array $conditions the conditions for the find * @param int $recursive the recursive level * @param string $extra * @access public * * @return int the count of records */ public function paginateCount($conditions = array(), $recursive = 0, $extra = array()) { $parameters = compact('conditions'); if ($recursive != $this->recursive) { $parameters['recursive'] = $recursive; } if (isset($extra['type']) && isset($this->_findMethods[$extra['type']])) { $extra['operation'] = 'count'; return $this->find($extra['type'], array_merge($parameters, $extra)); } else { return $this->find('count', array_merge($parameters, $extra)); } } }<file_sep><?php /** * Comment Template. * * @todo -c Implement .this needs to be sorted out. * * Copyright (c) 2009 <NAME> ( dogmatic69 ) * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. * * @filesource * @copyright Copyright (c) 2009 <NAME> ( dogmatic69 ) * @link http://infinitas-cms.org * @package sort * @subpackage sort.comments * @license http://www.opensource.org/licenses/mit-license.php The MIT License * @since 0.5a */ echo $this->Form->create('Newsletter', array('action' => 'mass')); $massActions = $this->Infinitas->massActionButtons( array( 'add', 'view', 'edit', 'copy', 'toggle', 'send', 'delete' ) ); echo $this->Infinitas->adminIndexHead($filterOptions, $massActions); ?> <div class="table"> <table class="listing" cellpadding="0" cellspacing="0"> <?php echo $this->Infinitas->adminTableHeader( array( $this->Form->checkbox('all') => array( 'class' => 'first', 'style' => 'width:25px;' ), $paginator->sort('subject'), $paginator->sort('Campaign', 'Campaign.name') => array( 'style' => 'width:150px;' ), $paginator->sort('from') => array( 'style' => 'width:100px;' ), $paginator->sort('reply_to') => array( 'style' => 'width:100px;' ), $paginator->sort('sent') => array( 'style' => 'width:100px;' ), __('Status', true) => array( 'class' => 'actions', 'width' => '50px' ) ) ); foreach($newsletters as $newsletter){ ?> <tr class="<?php echo $this->Infinitas->rowClass(); ?>"> <td><?php echo $this->Form->checkbox($newsletter['Newsletter']['id']); ?>&nbsp;</td> <td><?php echo $newsletter['Newsletter']['subject']; ?>&nbsp;</td> <td> <?php echo $html->link( $newsletter['Campaign']['name'], array( 'controller' => 'campaign', 'action' => 'view', $newsletter['Newsletter']['campaign_id'] ) ); ?>&nbsp; </td> <td><?php echo $newsletter['Newsletter']['from']; ?>&nbsp;</td> <td><?php echo $newsletter['Newsletter']['reply_to']; ?>&nbsp;</td> <td> <?php if ($newsletter['Newsletter']['active'] && !$newsletter['Newsletter']['sent']){ echo $this->Html->image( 'core/icons/actions/16/update.png', array( 'alt' => __('In Progress', true), 'title' => __('Busy sending', true) ) ); } else{ echo $this->Infinitas->status($newsletter['Newsletter']['sent']); } ?> </td> <td> <?php if ($newsletter['Newsletter']['sent']){ echo $this->Html->link( $this->Html->image( 'core/icons/actions/16/reports.png' ), array( 'action' => 'report', $newsletter['Newsletter']['id'] ), array( 'title' => __('Sending complete. See the report.', true), 'alt' => __('Done', true ), 'escape' => false ) ); } else{ echo $this->Infinitas->status($newsletter['Newsletter']['active']); } ?> </td> </tr> <?php } ?> </table> <?php echo $this->Form->end(); ?> </div> <?php echo $this->element('pagination/admin/navigation'); ?><file_sep><div class="dashboard"> <h1><?php __('Scaffold Error'); ?></h1> <p class="error"> <strong><?php __('Error'); ?>: </strong> <?php __('Method _scaffoldError in was not found in the controller'); ?> </p> <pre> &lt;?php function _scaffoldError() {<br /> } ?&gt; </pre> </div><file_sep><?php /* Branches Test cases generated on: 2010-12-14 13:12:47 : 1292334947*/ App::import('Controller', 'Contact.Branches'); class TestBranchesController extends BranchesController { var $autoRender = false; function redirect($url, $status = null, $exit = true) { $this->redirectUrl = $url; } } class BranchesControllerTestCase extends CakeTestCase { var $fixtures = array( 'plugin.configs.config', 'plugin.themes.theme', 'plugin.routes.route', 'plugin.modules.module', 'plugin.modules.module_position', 'plugin.modules.modules_route', 'plugin.view_counter.view_count', 'plugin.blog.post', 'plugin.contact.branche', 'plugin.contact.contact', 'plugin.contact.address', 'plugin.users.user', 'plugin.users.group', 'plugin.management.ticket', //'plugin.users.group', ); function startTest() { $this->Branches = new TestBranchesController(); $this->Branches->constructClasses(); } function endTest() { unset($this->Branches); ClassRegistry::flush(); } function testStuff(){ //$this->assertIsA($this->Branches, 'BranchesController'); } }<file_sep><?php class AssetsEvents extends AppEvents{ public function onSetupConfig($event, $data = null) { Configure::load('assets.config'); } public function onRequireHelpersToLoad($event = null) { return array( 'Assets.Compress' ); } public function onRequireJavascriptToLoad($event, $data = null) { $return = array( '/assets/js/3rd/jquery', '/assets/js/3rd/jquery_ui', '/assets/js/3rd/metadata', '/assets/js/infinitas', '/assets/js/libs/core', '/assets/js/libs/form', '/assets/js/libs/html', '/assets/js/libs/number' ); if(isset($event->Handler->params['admin']) && $event->Handler->params['admin']){ $return[] = '/assets/js/3rd/date'; $return[] = '/assets/js/3rd/image_drop_down'; } else{ $return[] = '/assets/js/3rd/rater'; $return[] = '/assets/js/3rd/moving_boxes'; } return $return; } }<file_sep><div class="dashboard"> <h1><?php __('Missing View'); ?></h1> <p class="error"> <strong><?php __('Error'); ?>: </strong> <?php printf(__('The view for %1$s%2$s was not found.', true), '<em>' . $controller . 'Controller::</em>', '<em>' . $action . '()</em>'); ?> </p> <p class="error"> <strong><?php __('Error'); ?>: </strong> <?php printf(__('Confirm you have created the file: %s', true), $file); ?> </p> </div><file_sep><?php class FilterHelper extends AppHelper{ public $helpers = array( 'Form', 'Html' ); public $count = 0; public function form($model, $filter = array()){ if (empty($filter) || !isset($filter['fields'])){ $this->errors[] = 'There is no filters'; return false; } $output = '<div class="filter-form"><h1>'.__('Search', true).'</h1>'; foreach($filter['fields'] as $field => $options){ if (is_array($options)){ switch($field){ case 'active': $emptyText = __('status', true); break; default: $emptyText = __($field, true); break; } $emptyText = sprintf(__('Select the %s', true), Inflector::humanize(str_replace('_id', '', $emptyText))); $output .= $this->Form->input( $field, array( 'type' => 'select', 'div' => false, 'options' => $options, 'empty' => $emptyText, 'label' => false ) ); } else if(strstr($options, 'date')){ $output .= $this->Html->datePicker(array($options)); } else{ $output .= $this->Form->input( $options, array( 'type' => 'text', 'div' => false, 'label' => false, 'placeholder' => Inflector::humanize($options) ) ); } } $output .= $this->Form->button( $this->Html->image( $this->Image->getRelativePath(array('actions'), 'filter'), array( 'width' => '16px' ) ), array( 'value' => 'filter', 'name' => 'action', 'title' => $this->niceTitleText('Filter results'), 'div' => false ) ); $output .= '</div>'; return $output; } /** * Comment Template. * * @todo -c Implement .this needs to be sorted out. * * Copyright (c) 2009 <NAME> ( dogmatic69 ) * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. * * @filesource * @copyright Copyright (c) 2009 <NAME> ( dogmatic69 ) * @link http://infinitas-cms.org * @package sort * @subpackage sort.comments * @license http://www.opensource.org/licenses/mit-license.php The MIT License * @since 0.5a */ public function clear($filter, $div = false){ if (!isset($filter['url'][0]) || empty($filter['url'][0]) || $filter['url'][0] == '/'){ $filter['url'][0] = '/'; } $out = ''; if ($div){ $out .= '<div class="filter">'; } $out .= '<div class="wrap">'; $parts = explode( '/', $filter['url'][0] ); $done = array(); foreach($parts as $_f){ if (empty($_f) || in_array($_f, $done)){ continue; } $done[] = $_f; $text = explode(':', $_f); $text = explode('.', $text[0]); $text = count($text ) > 1 ? $text[1] : $text[0]; $out .= '<div class="left">'. '<div class="remove">'. $this->Html->link( Inflector::humanize($text), str_replace($_f, '', '/' . $this->params['url']['url']) ). '</div>'. '</div>'; } $out .= '</div>'; if ($div){ $out .= '</div>'; } return $out; } /** * bulid a list of leters and numbers with filtered links to rows that * start with that letter or number * * @return string ul->li list of things found */ public function alphabetFilter(){ if(empty($this->params['models'])){ return false; } $model = current($this->params['models']); $letters = ClassRegistry::init($model)->getLetterList(); $return = array(); foreach($letters as $key => $value){ $url = $value == true ? $this->__filterLink($key) : $key; if(is_array($url)){ $url = $this->Html->link( $key, Router::url($url), array( 'title' => sprintf(__('Rows starting with "%s"', true), $key) ) ); } $return[] = sprintf('<li>%s</li>', $url); } $return[] = sprintf('<li>%s</li>', $this->Html->link('All', $this->cleanCurrentUrl())); return '<div class="alphabet-filter"><ul>' . implode('', $return) . '</ul></div>'; } /** * create a link for some text against the display field * * @param string $text the text to show/filter with * @return array the url cake style */ private function __filterLink($text = null){ if(!$text){ return false; } $model = current($this->params['models']); $filter = array( ClassRegistry::init($model)->alias . '.' . ClassRegistry::init($model)->displayField => $text ); $params = array_merge(parent::cleanCurrentUrl(), $this->params['named'], $this->params['pass'], $filter); return $params; } }<file_sep><?php final class GeoLocationEvents extends AppEvents{ public function onRequireComponentsToLoad($event = null) { return array( 'GeoLocation.GeoLocation' ); } /** * Get the location, will try for city, but if not available will get the * country. * * @param object $event the event object * @param string $ipAddress the ip address * @return array the details requested */ public function onGetLocation($event, $ipAddress = null){ App::import('GeoIp', 'GeoIp.IpLocation'); $IpLocation = new IpLocation(); $return = $IpLocation->getCityData($ipAddress); if(!$return){ $return = $IpLocation->getCountryData($ipAddress); } unset($IpLocation); return $return; } /** * Get the country data * * @param object $event the event object * @param string $ipAddress the ip address * @return array the details requested */ public function onGetCountry($event, $ipAddress = null){ App::import('GeoIp', 'GeoIp.IpLocation'); $IpLocation = new IpLocation(); $return = $IpLocation->getCountryData($ipAddress); unset($IpLocation); return $return; } /** * Get the city data * * @param object $event the event object * @param string $ipAddress the ip address * @return array the details requested */ public function onGetCity($event, $ipAddress = null){ App::import('GeoIp', 'GeoIp.IpLocation'); $IpLocation = new IpLocation(); $return = $IpLocation->getCityData($ipAddress); unset($IpLocation); return $return; } }<file_sep><?php /** * view and manage short urls for your site * * Copyright (c) 2009 <NAME> ( dogmatic69 ) * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. * * @filesource * @copyright Copyright (c) 2009 <NAME> ( dogmatic69 ) * @link http://infinitas-cms.org * @package sort * @subpackage sort.comments * @license http://www.opensource.org/licenses/mit-license.php The MIT License * @since 0.5a */ echo $this->Form->create('ShortUrl', array('action' => 'mass')); $massActions = $this->Core->massActionButtons( array( 'add', 'edit', 'delete' ) ); echo $this->Infinitas->adminIndexHead($filterOptions, $massActions); ?> <div class="table"> <table class="listing" cellpadding="0" cellspacing="0"> <?php echo $this->Core->adminTableHeader( array( $this->Form->checkbox('all') => array( 'class' => 'first', 'style' => 'width:25px;' ), $this->Paginator->sort('url'), $this->Paginator->sort(__('Short Url', true), 'id'), $this->Paginator->sort('views') => array( 'style' => 'width:75px;' ), $this->Paginator->sort('dead') => array( 'style' => 'width:50px;' ) ) ); foreach ($shortUrls as $shortUrl){ ?> <tr class="<?php echo $this->Core->rowClass(); ?>"> <td><?php echo $this->Form->checkbox($shortUrl['ShortUrl']['id']); ?>&nbsp;</td> <td> <?php echo $this->Html->link($shortUrl['ShortUrl']['url'], array('action' => 'edit', $shortUrl['ShortUrl']['id'])); ?>&nbsp; </td> <td> <?php $short = $this->Event->trigger('shorturls.getShortUrl', array('type' => 'preview', 'url' => $shortUrl['ShortUrl']['url'])); $short = Router::url(current($short['getShortUrl'])); echo $this->Html->link($short, $short, array('target' => '_blank')); ?>&nbsp; </td> <td><?php echo $shortUrl['ShortUrl']['views']; ?></td> <td><?php echo $this->Infinitas->status($shortUrl['ShortUrl']['dead']); ?></td> </tr> <?php } ?> </table> <?php echo $this->Form->end(); ?> </div> <?php echo $this->element('pagination/admin/navigation'); ?><file_sep><?php /** * CategoriesController for the management and display of categories and * related data. * * @filesource * @copyright Copyright (c) 2009 <NAME> ( dogmatic69 ) * @link http://infinitas-cms.org * @package Infinitas.Categories.controllers * @license http://www.opensource.org/licenses/mit-license.php The MIT License * @since 0.7a * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. */ class CategoriesController extends CategoriesAppController { public $name = 'Categories'; public function index() { if(isset($this->params['category'])){ $this->paginate['Category']['conditions']['Category.slug'] = $this->params['category']; } $categories = $this->paginate(); // redirect if there is only one category. if (count($categories) == 1 && Configure::read('Cms.auto_redirect')) { $this->redirect( array( 'controller' => 'categories', 'action' => 'view', $categories[0]['Category']['id'] ) ); } $this->set('categories', $categories); } public function view() { if(isset($this->params['category'])){ $conditions['Category.slug'] = $this->params['category']; } $category = $this->Category->find( 'first', array( 'conditions' => $conditions ) ); // redirect if there is only one content item. if ((isset($category['Content']) && count($category['Content']) == 1) && Configure::read('Cms.auto_redirect')) { $this->redirect( array( 'controller' => 'contents', 'action' => 'view', $category['Content'][0]['id'] ) ); } else if(empty($category)){ $this->Session->setFlash(__('Invalid category', true)); $this->redirect($this->referer()); } $this->set('title_for_layout', $category['Category']['title']); $this->set('category', $category); } public function admin_index() { $categories = $this->paginate(null, $this->Filter->filter); $filterOptions = $this->Filter->filterOptions; $filterOptions['fields'] = array( 'title', 'parent_id' => array(null => __('All', true), 0 => __('Top Level Categories', true)) + $this->Category->generatetreelist(), 'group_id' => array(null => __('Public', true)) + $this->Category->Group->find('list'), 'active' => (array)Configure::read('CORE.active_options') ); $this->set(compact('filterOptions','categories')); } public function admin_view($id = null) { if (!$id) { $this->Infinitas->noticeInvalidRecord(); } $this->set('category', $this->Category->read(null, $id)); } public function admin_add() { parent::admin_add(); $parents = array(__('Top Level Category', true)) + $this->Category->generatetreelist(); $groups = $this->Category->Group->find('list'); $this->set(compact('parents', 'groups')); } public function admin_edit($id = null) { parent::admin_edit($id); $parents = array(__('Top Level Category', true)) + $this->Category->generatetreelist(); $groups = $this->Category->Group->find('list'); $this->set(compact('parents', 'groups')); } public function admin_delete($id = null) { if (!$id) { $this->Infinitas->noticeInvalidRecord(); } $count = $this->Category->find('count', array('conditions' => array('Category.parent_id' => $id))); if ($count > 0) { $this->notice( sprintf(__('That %s has sub-categories', true), $this->prettyModelName), array( 'level' => 'warning', 'redirect' => true ) ); } $category = $this->Category->read(null, $id); if (!empty($category['Content'])) { $this->notice( sprintf(__('That %s has content items, remove them before continuing', true), $this->prettyModelName), array( 'level' => 'warning', 'redirect' => true ) ); } return parent::admin_delete($id); } }<file_sep><div class="dashboard"> <h1><?php __('Missing Model'); ?></h1> <p class="error"> <strong><?php __('Error'); ?>: </strong> <?php printf(__('<em>%s</em> could not be found.', true), $model); ?> </p> <p class="error"> <strong><?php __('Error'); ?>: </strong> <?php printf(__('Create the class %s in file: %s', true), '<em>' . $model . '</em>', APP_DIR . DS . 'models' . DS . Inflector::underscore($model) . '.php'); ?> </p> <pre> &lt;?php class <?php echo $model;?> extends AppModel { var $name = '<?php echo $model;?>'; } ?&gt; </pre> </div><file_sep><?php /** * Short Description / title. @todo * * Overview of what the file does. About a paragraph or two @todo * * Copyright (c) 2010 <NAME> ( dogmatic69 ) * * @filesource * @copyright Copyright (c) 2010 <NAME> ( dogmatic69 ) * @link http://infinitas-cms.org * @package libs * @subpackage libs.helpers.slug * @license http://www.opensource.org/licenses/mit-license.php The MIT License * @since 0.6 * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. * * @author Ceeram */ class SlugHelper extends AppHelper{ var $helpers = array('Html'); function link($title, $data, $model = null, $edit = false, $plugin = null){ $id = $slug = null; $action = ($edit) ? 'edit' : 'view'; if (!$model){ $models = array_keys($data); $model = $models[0]; } $controller = Inflector::tableize($model); $id = (isset($data[$model]['id'])) ? $data[$model]['id'] : null; $slug = (isset($data[$model]['slug'])) ? $data[$model]['slug'] : null; $url = array( 'controller' => $controller, 'action' => $action, 'plugin' => $plugin, $id, $slugged ); return $this->Html->link($title, $url); } } ?><file_sep><?php $map = array( 1 => array( '000008_installer' => 'R4c94edcd61c04d8992e678d86318cd70'), ); ?><file_sep><?php class BouncedMailsController extends NewsletterAppController{ public $name = 'BouncedMails'; } <file_sep><?php /* CommentAttribute Test cases generated on: 2010-12-14 02:12:49 : 1292295409*/ App::import('model', 'Comments.CommentAttribute'); class CommentAttributeTestCase extends CakeTestCase { function startTest() { $this->CommentAttribute = ClassRegistry::init('Comments.CommentAttribute'); } function endTest() { unset($this->CommentAttribute); ClassRegistry::flush(); } function testStuff(){ $this->assertIsA($this->CommentAttribute, 'CommentAttribute'); } }<file_sep><?php /* SVN FILE: $Id$ */ /* Emails schema generated on: 2010-10-18 14:10:15 : 1287409395*/ class EmailsSchema extends CakeSchema { var $name = 'Emails'; function before($event = array()) { return true; } function after($event = array()) { } var $email_accounts = array( 'id' => array('type' => 'string', 'null' => false, 'default' => NULL, 'length' => 36, 'key' => 'primary', 'collate' => 'utf8_general_ci', 'charset' => 'utf8'), 'name' => array('type' => 'string', 'null' => false, 'default' => 'My Account', 'length' => 50, 'collate' => 'utf8_general_ci', 'charset' => 'utf8'), 'slug' => array('type' => 'string', 'null' => false, 'default' => NULL, 'length' => 100, 'collate' => 'utf8_general_ci', 'charset' => 'utf8'), 'server' => array('type' => 'string', 'null' => false, 'default' => NULL, 'length' => 150, 'collate' => 'utf8_general_ci', 'charset' => 'utf8'), 'username' => array('type' => 'string', 'null' => false, 'default' => NULL, 'length' => 150, 'collate' => 'utf8_general_ci', 'charset' => 'utf8'), 'password' => array('type' => 'string', 'null' => false, 'default' => NULL, 'length' => 150, 'collate' => 'utf8_general_ci', 'charset' => 'utf8'), 'email' => array('type' => 'string', 'null' => false, 'default' => NULL, 'length' => 150, 'collate' => 'utf8_general_ci', 'charset' => 'utf8'), 'ssl' => array('type' => 'boolean', 'null' => false, 'default' => NULL), 'port' => array('type' => 'integer', 'null' => false, 'default' => NULL, 'length' => 6), 'type' => array('type' => 'string', 'null' => false, 'default' => NULL, 'length' => 4, 'collate' => 'utf8_general_ci', 'charset' => 'utf8'), 'readonly' => array('type' => 'boolean', 'null' => false, 'default' => NULL), 'user_id' => array('type' => 'string', 'null' => false, 'default' => NULL, 'length' => 36, 'collate' => 'utf8_general_ci', 'charset' => 'utf8'), 'system' => array('type' => 'boolean', 'null' => false, 'default' => NULL), 'outgoing' => array('type' => 'boolean', 'null' => false, 'default' => NULL), 'indexes' => array('PRIMARY' => array('column' => 'id', 'unique' => 1)), 'tableParameters' => array('charset' => 'utf8', 'collate' => 'utf8_general_ci', 'engine' => 'InnoDB') ); } ?><file_sep><?php if(!isset($config['menu'])){ //trow error return false; } $type = isset($config['type']) ? $config['type'] : 'horizontal'; $menus = ClassRegistry::init('Menus.MenuItem')->getMenu($config['menu']); echo $this->Menu->nestedList($menus, $type); ?><file_sep><!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <?php echo $this->Html->charset(); ?> <meta http-equiv="content-type" content="text/html; charset=utf-8" /> <title><?php echo sprintf('Infinitas Admin :: %s', $title_for_layout); ?></title> <?php echo $this->Html->meta('icon'); $css = array( '/assets/css/960gs/reset', '/assets/css/960gs/text', '/assets/css/960gs/960', '/assets/css/admin_nav', '/assets/css/960gs/uncompressed/demo', '/assets/css/3rd/date', ); echo $this->Compress->css(array_merge($css, $css_for_layout)); ?> <script type="text/javascript"> Infinitas = <?php echo json_encode(isset($infinitasJsData) ? $infinitasJsData : ''); ?>; if (Infinitas.base != '/') { Infinitas.base = Infinitas.base + '/'; } </script> </head> <body> <div id="wrap"> <?php echo $this->ModuleLoader->load('top', true); ?> <div class="container_16"> <!-- menus --> <div class="grid_16"> <?php echo $this->Session->flash(); ?> </div> <div class="clear"></div> </div> <div class="container_16 <?php echo $class_name_for_layout; ?>"> <!-- content --> <?php echo $content_for_layout; ?> <div class="clear"></div> <!-- footer --> <div class="grid_16"> <?php echo $this->ModuleLoader->load('bottom', true), $this->ModuleLoader->load('hidden', true), $this->Compress->script($js_for_layout); echo $scripts_for_layout; ?> </div> <div class="clear"></div> </div> <div class="powered-by">Powered By: <?php echo $this->Html->link('Infinitas', 'http://infinitas-cms.org');?></div> </div> </body> </html><file_sep><?php class AddressesController extends ManagementAppController{ var $name = 'Addresses'; function add(){ if($this->Session->read('Auth.User.id') < 1){ $this->Session->setFlash(__('You must be logged in to do that', true)); $this->redirect('/'); } if (!empty($this->data)) { $this->Address->create(); if ($this->Address->saveAll($this->data)) { $this->Session->setFlash('Your address has been saved.'); $this->redirect('/'); } } $this->data['Address']['plugin'] = 'management'; $this->data['Address']['model'] = 'user'; $this->data['Address']['foreign_key'] = $this->Session->read('Auth.User.id'); $countries = $this->Address->Country->find('list'); $continents = array(0 => 'Other', 1 => 'Africa'); $this->set(compact('referer', 'countries', 'continents')); } function edit($id = null){ if (!$id) { $this->Session->setFlash(__('That address could not be found', true), true); $this->redirect($this->referer()); } if (!empty($this->data)) { if ($this->Address->save($this->data)) { $this->Session->setFlash('Your address has been saved.'); $this->redirect(array('action' => 'index')); } } if ($id && empty($this->data)) { $this->data = $this->Address->read(null, $id); } $countries = $this->Address->Country->find('list'); $continents = array(0 => 'Other', 1 => 'Africa'); $this->set(compact('countries', 'continents')); } }<file_sep><?php /** * Newsletter events * * events for the newsletter system * * Copyright (c) 2010 <NAME> ( dogmatic69 ) * * @filesource * @copyright Copyright (c) 2010 <NAME> ( dogmatic69 ) * @link http://www.infinitas-cms.org * @package newsletter * @subpackage infinitas.newsletter.events * @license http://www.opensource.org/licenses/mit-license.php The MIT License * @since 0.8a * * @author dogmatic * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. */ final class NewsletterEvents extends AppEvents{ public function onPluginRollCall(){ return array( 'name' => 'Newsletter', 'description' => 'Keep in contact with your user base', 'author' => 'Infinitas', 'icon' => '/newsletter/img/icon.png', 'dashboard' => array('plugin' => 'newsletter', 'controller' => 'newsletters', 'action' => 'dashboard'), ); } public function onAdminMenu($event){ $menu['main'] = array( 'Campaigns' => array('plugin' => 'newsletter', 'controller' => 'campaigns', 'action' => 'index'), 'Templates' => array('plugin' => 'newsletter', 'controller' => 'templates', 'action' => 'index'), 'Newsletters' => array('plugin' => 'newsletter', 'controller' => 'newsletters', 'action' => 'index') ); return $menu; } public function onSetupConfig(){ return Configure::load('newsletter.config'); } public function onRequireComponentsToLoad(){ return array( 'Email', 'Newsletter.Emailer' ); } } <file_sep><?php /** * View to create and edit global categories * * Copyright (c) 2009 <NAME> ( dogmatic69 ) * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. * * @filesource * @copyright Copyright (c) 2009 <NAME> ( dogmatic69 ) * @link http://infinitas-cms.org * @package Infinitas.categories * @subpackage Infinitas.categories.admin_form * @license http://www.opensource.org/licenses/mit-license.php The MIT License * @since 0.5a * * @author dogmatic69 */ echo $this->Form->create('Category', array('action' => 'edit')); echo $this->Infinitas->adminEditHead(); ?> <fieldset> <h1><?php echo __('Category', true); ?></h1><?php echo $this->Form->input('id'); echo $this->Form->input('title', array('class' => 'title')); echo $this->Infinitas->wysiwyg('Category.description'); ?> </fieldset> <fieldset> <h1><?php echo __('Config', true); ?></h1><?php echo $this->Form->input('parent_id'); echo $this->Form->input('group_id', array('label' => __('Min Group', true), 'empty' => __('Public', true))); echo $this->Form->input('active'); ?> </fieldset> <?php echo $this->Form->end(); ?><file_sep><?php /** * Infinitas Helper. * * Does a lot of stuff like generating ordering buttons, load modules and * other things needed all over infinitas. * * Copyright (c) 2010 <NAME> ( dogmatic69 ) * * @filesource * @copyright Copyright (c) 2010 <NAME> ( dogmatic69 ) * @link http://www.infinitas-cms.org * @package libs * @subpackage libs.views.helpers.infinitas * @license http://www.opensource.org/licenses/mit-license.php The MIT License * @since 0.6a * * @author <NAME> ( dogmatic69 ) * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. */ class InfinitasHelper extends AppHelper{ public $helpers = array( 'Html', 'Form', 'Libs.Design', 'Libs.Image', 'Libs.Wysiwyg' ); /** * JSON errors. * * Set up some errors for json. * @access public */ public $_json_errors = array( JSON_ERROR_NONE => 'No error', JSON_ERROR_DEPTH => 'The maximum stack depth has been exceeded', JSON_ERROR_CTRL_CHAR => 'Control character error, possibly incorrectly encoded', JSON_ERROR_SYNTAX => 'Syntax error', ); var $_menuData = ''; var $_menuLevel = 0; public $external = true; var $View = null; /** * Set to true when the menu has a current marker to avoid duplicates. * @var unknown_type */ var $_currentCssDone = false; /** * Create a status icon. * * Takes a int 0 || 1 and returns a icon with title tags etc to be used * in places like admin to show iff something is on/off etc. * * @param int $status the status tinyint(1) from a db find. * * @return string some html for the generated image. */ public function status($status = null){ $image = false; $params = array(); switch (strtolower($status)){ case 1: case 'yes': case 'on': if ($this->external){ $params['title'] = __( 'Active', true ); } $image = $this->Html->image( $this->Image->getRelativePath('status', 'active'), $params + array( 'width' => '16px', 'alt' => __('On', true) ) ); break; case 0: case 'no': case 'off': if ($this->external){ $params['title'] = __('Disabled', true); } $image = $this->Html->image( $this->Image->getRelativePath('status', 'inactive'), $params + array( 'width' => '16px', 'alt' => __('Off', true) ) ); break; } return $image; } /** * Featured icon. * * Creates a featured icon like the status and locked. * * @param array $record the data from find * @param string $model the model alias * * @return string html of the icon. */ public function featured($record = array(), $model = 'Feature'){ if (empty($record[$model])){ $this->messages[] = 'This has no featured items.'; return $this->Html->image( $this->Image->getRelativePath('status', 'not-featured'), array( 'alt' => __('No', true), 'title' => __('Not a featured item', true), 'width' => '16px' ) ); } return $this->Html->image( $this->Image->getRelativePath('status', 'featured'), array( 'alt' => __('Yes', true), 'title' => __('Featured Item', true), 'width' => '16px' ) ); } public function loggedInUserText($counts){ $allInIsAre = ($counts['all'] > 1) ? __('are', true) : __('is', true); $loggedInIsAre = ($counts['loggedIn'] > 1) ? __('are', true) : __('is', true); $guestsIsAre = ($counts['guests'] > 1) ? __('are', true) : __('is', true); $guests = ($counts['guests'] > 1) ? __('guests', true) : __('a guest', true); return '<p>'. sprintf( __('There %s %s people on the site, %s %s logged in and %s %s %s.', true), $allInIsAre, $counts['all'], $counts['loggedIn'], $loggedInIsAre, $counts['guests'], $guestsIsAre, $guests ). '</p><p>&nbsp;</p>'; } } ?><file_sep><?php $map = array( 1 => array( '000008_assets' => 'R4c94edcbfba44cae9af978d86318cd70'), ); ?><file_sep><?php class JsonView extends View{ function render($action = null, $layout = null, $file = null){ if (strtolower($this->params['url']['ext']) != 'json'){ return parent::render($action, $layout, $file); } $vars = $this->viewVars; unset($vars['debugToolbarPanels']); unset($vars['debugToolbarJavascript']); if (is_array($vars)){ header('Content-type: application/json'); Configure::write('debug', 0); // Omit time in end of view return json_encode($vars); } return 'null'; } }<file_sep><?php /** * Management Modules admin edit post. * * this page is for admin to manage the menu items on the site * * Copyright (c) 2009 <NAME> ( dogmatic69 ) * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. * * @filesource * @copyright Copyright (c) 2009 <NAME> ( dogmatic69 ) * @link http://infinitas-cms.org * @package management * @subpackage management.views.menuItems.admin_add * @license http://www.opensource.org/licenses/mit-license.php The MIT License */ echo $this->Form->create('MenuItem'); echo $this->Infinitas->adminEditHead(); ?> <fieldset> <h1><?php echo __('Menu Item', true); ?></h1><?php echo $this->Form->input('id'); echo $this->Form->input('name'); echo $this->Form->input('link', array('label' => __('External Link', true))); echo $this->Form->input('prefix'); echo $this->element('route_select', array('plugin' => 'routes')); $errorMenu = $this->Form->error('menu_id'); $errorParent = $this->Form->error('parent_id'); $errorMessage = !empty($errorMenu) || !empty($errorParent) ? 'error' : ''; ?> <div class="input select smaller <?php echo $errorMessage; ?>"> <label for=""><?php echo __('Menu / Parent Item', true); ?></label><?php echo $this->Form->input('menu_id', array('error' => false, 'type' => 'select', 'div' => false, 'label' => false, 'class' => "pluginSelect {url:{action:'getParents'}, target:'MenuItemParentId'}", 'empty' => Configure::read('Website.empty_select'))); echo $this->Form->input('parent_id', array('error' => false, 'type' => 'select', 'div' => false, 'label' => false)); echo $errorMenu, $errorParent; ?> </div> </fieldset> <fieldset> <h1><?php echo __('Config', true); ?></h1><?php echo $this->Form->input('active'); echo $this->Form->input('force_backend'); echo $this->Form->input('force_frontend'); echo $this->Form->input('group_id', array('empty' => Configure::read('Website.empty_select'))); echo $this->Form->input('params', array('type' => 'textarea')); echo $this->Form->input('class'); ?> </fieldset> <?php echo $this->Form->end(); ?><file_sep><?php /** * User Model. * * Model for managing users * * Copyright (c) 2010 <NAME> ( dogmatic69 ) * * @filesource * @copyright Copyright (c) 2010 <NAME> ( dogmatic69 ) * @link http://www.infinitas-cms.org * @package management * @subpackage management.models.user * @license http://www.opensource.org/licenses/mit-license.php The MIT License * @since 0.7alpha * * @author <NAME> (dogmatic69) * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. */ class User extends UsersAppModel{ public $name = 'User'; public $displayField = 'username'; public $actsAs = array( 'Acl' => 'requester', 'Libs.Ticketable' ); public $belongsTo = array( 'Users.Group' ); public function __construct($id = false, $table = null, $ds = null) { parent::__construct($id, $table, $ds); $message = Configure::read('Website.password_validation'); $this->validate = array( 'username' => array( 'notEmpty' => array( 'rule' => 'notEmpty', 'message' => __('Please enter your username', true) ), 'isUnique' => array( 'rule' => 'isUnique', 'message' => __('That username is taken, sorry', true) ) ), 'email' => array( 'notEmpty' => array( 'rule' => 'notEmpty', 'message' => __('Please enter your email address', true) ), 'email' => array( 'rule' => array('email', true), 'message' => __('That email address does not seem to be valid', true) ), 'isUnique' => array( 'rule' => 'isUnique', 'message' => __('It seems you are already registered, please use the forgot password option', true) ) ), 'confirm_email' => array( 'validateCompareFields' => array( 'rule' => array('validateCompareFields', array('email', 'confirm_email')), 'message' => __('Your email address does not match', true) ) ), 'password' => array( 'notEmpty' => array( 'rule' => 'notEmpty', 'message' => __('Please enter a password', true) ) ), 'confirm_password' => array( 'notEmpty' => array( 'rule' => 'notEmpty', 'message' => __('Please re-enter your password', true) ), 'validPassword' => array( 'rule' => 'validPassword', 'message' => (!empty($message) ? $message : __('Please enter a stronger password', true)) ), 'validateCompareFields' => array( 'rule' => array('validateCompareFields', array('password', 'confirm_password')), 'message' => __('The passwords entered do not match', true) ) ) ); } /** * Valid password. * * This method uses the regex saved in the config to check that the * password is secure. The user can update this and the message in the * backend by changing the config value "Website.password_regex". * * @params array $field the array $field => $value from the form * @return bool true if password matches the regex and false if not */ public function validPassword($field = null){ return preg_match('/'.Configure::read('Website.password_regex').'/', $field['confirm_password']); } /** * Get last login details. * * Gets the details of the last login of the user so we can show the last * login and ipaddress to them. * * @param int $user_id the users id. * @return array the data from the last login. */ public function getLastLogon($user_id = null){ if (!$user_id) { return false; } return $this->read( array( 'User.ip_address', 'User.last_login', 'User.country', 'User.city' ), (int)$user_id ); } public function loggedInUserCount(){ $Session = ClassRegistry::init('Session'); return $Session->find('count'); } public function latestUsers($limit = 10){ $Session = ClassRegistry::init('Session'); $sessions = $Session->find('all'); foreach($sessions as &$session){ $session['User'] = explode('Auth|', $session['Session']['data']); if(isset($session['User'][1])) { $session['User'] = unserialize($session['User'][1]); if (isset($session['User']['User'])) { $session['User'] = $session['User']['User']; } else { $session['User'] = ''; } } else { $session['User'] = ''; } } $users = Set::extract('/User/id', $sessions); $this->User->recursive = 0; $users = $this->find( 'all', array( 'conditions' => array( 'User.id' => $users ), 'limit' => $limit ) ); return $users; } public function parentNode() { if (!$this->id && empty($this->data)) { return null; } $data = $this->data; if (empty($this->data)) { $data = $this->read(); } if (!isset($data['User']['group_id']) || !$data['User']['group_id']) { return null; } else { return array('Group' => array('id' => $data['User']['group_id'])); } } /** * After save callback * * Update the aro for the user. * * @access public * @return void */ public function afterSave($created) { if (!$created) { $parent = $this->parentNode(); $parent = $this->node($parent); $node = $this->node(); $aro = $node[0]; $aro['Aro']['parent_id'] = $parent[0]['Aro']['id']; $this->Aro->save($aro); } } public function getSiteRelatedList(){ return $this->find( 'list', array( 'conditions' => array( 'User.group_id' => 1 ) ) ); } }<file_sep><?php $map = array( 1 => array( '000008_tags' => 'R4c94edcecc8c46e4bc7078d86318cd70'), ); ?><file_sep><?php /** * CakePHP Tags Plugin * * Copyright 2009 - 2010, Cake Development Corporation * 1785 E. Sahara Avenue, Suite 490-423 * Las Vegas, Nevada 89104 * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. * * @copyright 2009 - 2010, Cake Development Corporation (http://cakedc.com) * @link http://github.com/CakeDC/Tags * @package plugins.tags * @license MIT License (http://www.opensource.org/licenses/mit-license.php) */ /** * Short description for class. * * @package plugins.tags */ class TagsAppModel extends AppModel { public $tablePrefix = 'global_'; /** * Customized paginateCount method * * @param array * @param integer * @param array * @return * @access public */ public function paginateCount($conditions = array(), $recursive = 0, $extra = array()) { $parameters = compact('conditions'); if ($recursive != $this->recursive) { $parameters['recursive'] = $recursive; } if (isset($extra['type']) && isset($this->_findMethods[$extra['type']])) { $extra['operation'] = 'count'; return $this->find($extra['type'], array_merge($parameters, $extra)); } else { return $this->find('count', array_merge($parameters, $extra)); } } }<file_sep><?php /* Contact Test cases generated on: 2010-12-14 13:12:18 : 1292334978*/ App::import('Model', 'contact.Contact'); class ContactTestCase extends CakeTestCase { function startTest() { $this->Contact =& ClassRegistry::init('Contact'); } function endTest() { unset($this->Contact); ClassRegistry::flush(); } } ?><file_sep><div class="feed"> <?php if(!isset($feeds)){ $config['feed'] = isset($config['feed']) ? $config['feed'] : ''; $feeds = ClassRegistry::init('Feed.Feed')->getFeed($config['feed'], $this->Session->read('Auth.User.group_id')); } foreach($feeds as $feed){ $model = Inflector::camelize(Inflector::singularize($feed['Feed']['controller'])); $feed[$model] =& $feed['Feed']; ?><div class="beforeEvent"><?php $eventData = $this->Event->trigger('feedBeforeContentRender', array('_this' => $this, 'feed' => $feed)); foreach((array)$eventData['feedBeforeContentRender'] as $_plugin => $_data){ echo '<div class="'.$_plugin.'">'.$_data.'</div>'; } ?></div> <div class="wrapper"> <div class="introduction <?php echo $this->layout; ?>"> <h2> <?php $eventData = $this->Event->trigger($feed['Feed']['plugin'].'.slugUrl', array('type' => $feed['Feed']['controller'], 'data' => $feed)); $urlArray = current($eventData['slugUrl']); echo $this->Html->link( $feed['Feed']['title'], $urlArray ); ?><small><?php echo $this->Time->niceShort($feed['Feed']['date']); ?></small> </h2> <div class="content <?php echo $this->layout; ?>"> <?php echo $this->Text->truncate($feed['Feed']['body'], 350, array('html' => true)); ?> </div> </div> </div> <div class="afterEvent"> <?php $eventData = $this->Event->trigger('feedAfterContentRender', array('_this' => $this, 'feed' => $feed)); foreach((array)$eventData['feedAfterContentRender'] as $_plugin => $_data){ echo '<div class="'.$_plugin.'">'.$_data.'</div>'; } ?> </div> <?php } ?> </div><file_sep><?php class R4c94edce63b447ddb6b178d86318cd70 extends CakeRelease { /** * Migration description * * @var string * @access public */ public $description = 'Migration for Routes version 0.8'; /** * Plugin name * * @var string * @access public */ public $plugin = 'Routes'; /** * Actions to be performed * * @var array $migration * @access public */ public $migration = array( 'up' => array( 'create_table' => array( 'routes' => array( 'id' => array('type' => 'integer', 'null' => false, 'default' => NULL, 'key' => 'primary'), 'core' => array('type' => 'boolean', 'null' => false, 'default' => NULL), 'name' => array('type' => 'string', 'null' => false, 'default' => NULL, 'length' => 50), 'url' => array('type' => 'string', 'null' => false, 'default' => NULL), 'prefix' => array('type' => 'string', 'null' => true, 'default' => NULL, 'length' => 100), 'plugin' => array('type' => 'string', 'null' => true, 'default' => NULL, 'length' => 50), 'controller' => array('type' => 'string', 'null' => true, 'default' => NULL, 'length' => 50), 'action' => array('type' => 'string', 'null' => true, 'default' => NULL, 'length' => 50), 'values' => array('type' => 'text', 'null' => false, 'default' => NULL), 'pass' => array('type' => 'string', 'null' => true, 'default' => NULL, 'length' => 100), 'rules' => array('type' => 'text', 'null' => false, 'default' => NULL), 'force_backend' => array('type' => 'boolean', 'null' => false, 'default' => '0'), 'force_frontend' => array('type' => 'boolean', 'null' => false, 'default' => '0'), 'order_id' => array('type' => 'integer', 'null' => false, 'default' => '1'), 'ordering' => array('type' => 'integer', 'null' => false, 'default' => NULL, 'key' => 'index'), 'theme_id' => array('type' => 'integer', 'null' => true, 'default' => NULL), 'active' => array('type' => 'boolean', 'null' => false, 'default' => NULL), 'created' => array('type' => 'datetime', 'null' => true, 'default' => NULL), 'modified' => array('type' => 'datetime', 'null' => true, 'default' => NULL), 'indexes' => array( 'PRIMARY' => array('column' => 'id', 'unique' => 1), 'active_routes' => array('column' => array('ordering', 'active', 'theme_id'), 'unique' => 1), ), 'tableParameters' => array('charset' => 'utf8', 'collate' => 'utf8_general_ci', 'engine' => 'InnoDB'), ), ), ), 'down' => array( 'drop_table' => array( 'routes' ), ), ); /** * Fixtures for data * * @var array $fixtures * @access public */ public $fixtures = array( 'core' => array( 'Route' => array( array( 'id' => 25, 'core' => 0, 'name' => 'Default homepage', 'url' => '/', 'prefix' => NULL, 'plugin' => NULL, 'controller' => 'pages', 'action' => 'display', 'values' => '["home"]', 'pass' => NULL, 'rules' => '', 'force_backend' => 0, 'force_frontend' => 0, 'order_id' => 1, 'ordering' => 0, 'theme_id' => NULL, 'active' => 1, 'created' => NULL, 'modified' => NULL ), array( 'id' => 8, 'core' => 0, 'name' => 'Pages', 'url' => '/pages/*', 'prefix' => '', 'plugin' => '0', 'controller' => 'pages', 'action' => 'display', 'values' => '', 'pass' => '', 'rules' => '', 'force_backend' => 0, 'force_frontend' => 0, 'order_id' => 1, 'ordering' => 3, 'theme_id' => 4, 'active' => 1, 'created' => '2010-01-13 18:26:36', 'modified' => '2010-01-14 00:38:53' ), ), ), ); /** * Before migration callback * * @param string $direction, up or down direction of migration process * @return boolean Should process continue * @access public */ public function before($direction) { return true; } /** * After migration callback * * @param string $direction, up or down direction of migration process * @return boolean Should process continue * @access public */ public function after($direction) { return true; } } ?><file_sep><?php /** * Comment Template. * * @todo Implement .this needs to be sorted out. * * Copyright (c) 2009 <NAME> ( dogmatic69 ) * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. * @filesource * @copyright Copyright (c) 2009 <NAME> ( dogmatic69 ) * @link http://infinitas-cms.org * @package sort * @subpackage sort.comments * @license http://www.opensource.org/licenses/mit-license.php The MIT License * @since 0.5a */ class Campaign extends NewsletterAppModel { public $name = 'Campaign'; public $lockable = true; public $order = array( 'Campaign.name' => 'asc' ); public $hasMany = array( 'Newsletter.Newsletter' ); public $belongsTo = array( 'Newsletter.Template' ); public function __construct($id = false, $table = null, $ds = null) { parent::__construct($id, $table, $ds); $this->validate = array( 'name' => array( 'notEmpty' => array( 'rule' => 'notEmpty', 'message' => __('Please enter the name of this campaign', true) ), 'isUnique' => array( 'rule' => 'isUnique', 'message' => __('There is already a campaign with that name', true) ) ), 'template_id' => array( 'notEmpty' => array( 'rule' => 'notEmpty', 'message' => __('Please select the default template for this campaign', true) ) ) ); } }<file_sep>;(function($) { var FormHelper = $.FormHelper = {}; /** * Focus on the first available text field, used in admin to make the * overall usability a bit better. * * @access public * @return void **/ FormHelper.foucusOnFirst = function(){ $("input:text:visible:first").focus(); } /** * generate a form input */ FormHelper.input = function(data, metaData) { $('#' + metaData.target).empty(); if ($.Core.type(data) == 'string') { } $.FormHelper.select(data, metaData); }; /** * generate a select dropdown */ FormHelper.select = function(data, metaData) { var options = '<option value="">' + $.Core.config('Website.empty_select') + '</option>'; $.each(data, function(index, name) { if(($.Core.type(name) == 'plainObject') || ($.Core.type(name) == 'array')) { options += '<optgroup label="' + index + '">'; $.each(name, function(sub_index, sub_name) { options += '<option value="' + sub_index + '">' + sub_name + '</option>'; }); options += '</optgroup>'; } else { options += '<option value="' + index + '">' + name + '</option>'; } }); $('#' + metaData.target).empty().html(options); }; /** * generate a select dropdown */ FormHelper.emptySelect = function(metaData) { $('#' + metaData.target).empty(); }; /** * toggle checkboxes */ FormHelper.checkboxToggleAll = function() { var tog = false; var toggleId = '#' + Infinitas.model + 'All'; $(toggleId).click(function(){ $("input:checkbox[not:"+toggleId+"]").attr("checked",!tog).change(); tog = !tog; }); }; /** * image dropdown */ FormHelper.imageDropdown = function(fieldId) { $("#" + fieldId).msDropDown(); }; })(jQuery);<file_sep><?php /* Route Test cases generated on: 2010-03-13 11:03:13 : 1268471233*/ App::import('Model', 'management.Route'); class RouteTestCase extends CakeTestCase { var $fixtures = array( 'plugin.management.route', 'plugin.management.theme' ); function startTest() { $this->Route =& ClassRegistry::init('Route'); } function testGetRoutes(){ $this->assertFalse($this->Route->_getValues(array())); $this->assertFalse($this->Route->_getValues(null)); $route = array( 'prefix' => 'admin', 'plugin' => 'blog', 'controller' => 'posts', 'action' => '', 'values' => '', 'force_backend' => 1, 'force_frontend' => 0 ); //basic test $this->assertEqual($this->Route->_getValues($route), array('prefix' => 'admin', 'plugin' => 'blog', 'controller' => 'posts', 'admin' => 1)); // no prefix $route['prefix'] = ''; $this->assertEqual($this->Route->_getValues($route), array('plugin' => 'blog', 'controller' => 'posts', 'admin' => 1)); // admin prefix without forcing anything $route['prefix'] = 'admin'; $route['force_backend'] = 0; $route['force_frontend'] = 0; $this->assertEqual($this->Route->_getValues($route), array('prefix' => 'admin', 'plugin' => 'blog', 'controller' => 'posts')); // force frontend (admin => false) $route['prefix'] = ''; $route['force_backend'] = 0; $route['force_frontend'] = 1; $this->assertEqual($this->Route->_getValues($route), array('plugin' => 'blog', 'controller' => 'posts', 'admin' => false)); // forcing both will default to admin $route['prefix'] = ''; $route['force_backend'] = 1; $route['force_frontend'] = 1; $this->assertEqual($this->Route->_getValues($route), array('plugin' => 'blog', 'controller' => 'posts', 'admin' => 1)); // force frontend with a prefix $route['prefix'] = 'something'; $route['force_backend'] = 0; $route['force_frontend'] = 1; $this->assertEqual($this->Route->_getValues($route), array('prefix' => 'something', 'plugin' => 'blog', 'controller' => 'posts', 'admin' => false)); // with an action $route['prefix'] = ''; $route['force_backend'] = 0; $route['force_frontend'] = 1; $route['action'] = 'index'; $this->assertEqual($this->Route->_getValues($route), array('plugin' => 'blog', 'controller' => 'posts', 'action' => 'index', 'admin' => false)); // bad json data $route['values'] = '{}'; $route['action'] = ''; $this->assertEqual($this->Route->_getValues($route), array('plugin' => 'blog', 'controller' => 'posts', 'admin' => false)); // simple $route['values'] = '{"day":null}'; $route['action'] = ''; $this->assertEqual($this->Route->_getValues($route), array('plugin' => 'blog', 'controller' => 'posts', 'admin' => false, 'day' => null)); // completely ignore nested arrays $route['values'] = '{"day":null,"abc":{"test":"bad"}}'; $route['action'] = ''; $this->assertEqual($this->Route->_getValues($route), array('plugin' => 'blog', 'controller' => 'posts', 'admin' => false, 'day' => null)); //reset route and test regex rules and values passing $route = ''; $route['rules'] = ''; $route['pass'] = ''; // wrong usage $this->expectError(); $this->Route->_getRegex(); // test empty $this->assertEqual($this->Route->_getRegex($route['rules']), array()); $this->assertEqual($this->Route->_getRegex($route['rules'], $route['pass']), array()); //basic test $route['rules'] = '{"year":"[12][0-9]{3}","month":"0[1-9]|1[012]","day":"0[1-9]|[12][0-9]|3[01]"}'; $this->assertEqual($this->Route->_getRegex($route['rules']), array('year' => '[12][0-9]{3}', 'month' => '0[1-9]|1[012]', 'day' => '0[1-9]|[12][0-9]|3[01]')); //ignore nested arrays $route['rules'] = '{"year":"[12][0-9]{3}","month":"0[1-9]|1[012]","day":"0[1-9]|[12][0-9]|3[01]","array":{"abc":false}}'; $this->assertEqual($this->Route->_getRegex($route['rules']), array('year' => '[12][0-9]{3}', 'month' => '0[1-9]|1[012]', 'day' => '0[1-9]|[12][0-9]|3[01]')); // basic rules with pass $route['rules'] = '{"year":"[12][0-9]{3}"}'; $route['pass'] = '<PASSWORD>'; $this->assertEqual($this->Route->_getRegex($route['rules'], $route['pass']), array('year' => '[12][0-9]{3}', 0 => 'id', 1 => 'year')); // pass only one field $route['pass'] = 'id'; $this->assertEqual($this->Route->_getRegex($route['rules'], $route['pass']), array('year' => '[12][0-9]{3}', 0 => 'id')); //pass many fields $route['pass'] = 'id,name,slug,date'; $this->assertEqual($this->Route->_getRegex($route['rules'], $route['pass']), array('year' => '[12][0-9]{3}', 0 => 'id', 1 => 'name', 2 => 'slug', 3 => 'date')); // pass wtih no rules $route['rules'] = ''; $route['pass'] = 'id'; $this->assertEqual($this->Route->_getRegex($route['rules'], $route['pass']), array(0 => 'id')); //basic find $routes = $this->Route->getRoutes(); //random checks $this->assertTrue(isset($routes[7])); $this->assertTrue(!empty($routes[5])); // advanced route $expected = array( 'Route' => array( 'url' => '/p/:year/:month/:day', 'values' => array( 'plugin' => 'blog', 'controller' => 'posts', 'admin' => false ), 'regex' => array(), 'theme' => 'default' ) ); $this->assertEqual($routes[9], $expected); // admin route $expected = array( 'Route' => array( 'url' => '/admin', 'values' => array( 'prefix' => 'admin', 'plugin' => 'management', 'controller' => 'management', 'action' => 'dashboard', 'admin' => true ), 'regex' => array(), 'theme' => null ) ); $this->assertEqual($routes[2], $expected); } function endTest() { unset($this->Route); ClassRegistry::flush(); } }<file_sep><?php /** * add / edit routes for the site * * Copyright (c) 2009 <NAME> ( dogmatic69 ) * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. * * @filesource * @copyright Copyright (c) 2009 <NAME> ( dogmatic69 ) * @link http://infinitas-cms.org * @package Infinitas.routes * @subpackage Infinitas.routes.views.admin_form * @license http://www.opensource.org/licenses/mit-license.php The MIT License */ echo $this->Form->create('Route'); echo $this->Infinitas->adminEditHead(); ?> <fieldset> <h1><?php echo __('Route', true); ?></h1><?php echo $this->Form->input('id'); echo $this->Form->input('name'); echo $this->Form->input('url'); ?> <div class="dynamic"><?php $options = Configure::read('Routing.prefixes'); $options = array_combine($options, $options); echo $this->Form->input('prefix', array('options' => $options, 'type' => 'select', 'empty' => __('None', true))); echo $this->element('route_select', array('plugin' => 'routes')); ?> </div><?php echo $this->Form->input('values'); echo $this->Form->input('rules'); ?> </fieldset> <fieldset> <h1><?php echo __('Config', true); ?></h1> <div class="dynamic"><?php echo $this->Form->input('pass'); echo $this->Form->input('force_backend'); echo $this->Form->input('force_frontend'); ?> </div><?php echo $this->Form->input('active'); echo $this->Form->input('theme_id'); echo $this->Form->hidden('order_id', array('value' => 1)); ?> </fieldset> <?php echo $this->Form->end(); ?><file_sep><?php /** * * */ class Module extends ModulesAppModel{ public $name = 'Module'; public $lockable = true; public $virtualFields = array( 'list_name' => "IF(Module.admin = 1, CONCAT('Admin :: ', Module.name), Module.name)", 'save_name' => "IF(Module.admin = 1, CONCAT('admin/', Module.module), Module.module)" ); public $actsAs = array( 'Libs.Sequence' => array( 'group_fields' => array( 'position_id' ) ) ); public $order = array( 'Module.position_id' => 'ASC', 'Module.ordering' => 'ASC' ); public $belongsTo = array( 'Position' => array( 'className' => 'Modules.ModulePosition', 'foreignKey' => 'position_id', 'counterCache' => true, 'counterScope' => array('Module.active' => 1) ), 'Users.Group', 'Theme' => array( 'className' => 'Themes.Theme', 'foreignKey' => 'theme_id' ), ); public $hasAndBelongsToMany = array( 'Route' => array( 'className' => 'Routes.Route', 'with' => 'Modules.ModulesRoute', 'foreignKey' => 'module_id', 'associationForeignKey' => 'route_id', 'unique' => true ) ); private $__contain = array( 'Position' => array( 'fields' => array( 'Position.id', 'Position.name' ) ), 'Group' => array( 'fields' => array( 'Group.id', 'Group.name' ) ), 'Route' => array( 'fields' => array( 'Route.id', 'Route.name', 'Route.url' ) ), 'Theme' => array( 'fields' => array( 'Theme.id', 'Theme.name' ) ) ); public function __construct($id = false, $table = null, $ds = null) { parent::__construct($id, $table, $ds); $this->subPath = 'views'.DS.'elements'.DS.'modules'.DS; $this->validate = array( 'name' => array( 'notEmpty' => array( 'rule' => 'notEmpty', 'message' => __('Please enter a name for this module', true) ) ), 'config' => array( 'validateEmptyOrJson' => array( 'rule' => 'validateEmptyOrJson', 'message' => __('Please enter a valid json config or leave blank', true) ) ), 'group_id' => array( 'notEmpty' => array( 'rule' => 'notEmpty', 'message' => __('Please select the group this module is for', true) ) ), 'position_id' => array( 'notEmpty' => array( 'rule' => 'notEmpty', 'message' => __('Please select the position this module will show in', true) ) ), 'author' => array( 'notEmpty' => array( 'rule' => 'notEmpty', 'message' => __('Please enter the author of this module', true) ) ), 'url' => array( 'notEmpty' => array( 'rule' => array('url', true), 'message' => __('Please enter the url of this module', true) ) ) ); } /** * decide if its an admin module or not. */ public function beforeSave($options = array()){ $this->data['Module']['admin'] = strstr($this->data['Module']['module'], 'admin/') ? 1 : 0; return true; } public function getModules($position = null, $admin = false){ if (!$position) { return array(); } $modules = Cache::read($position . '.' . ($admin ? 'admin' : 'user'), 'modules'); if($modules !== false){ return $modules; } $modules = $this->find( 'all', array( 'fields' => array( 'Module.id', 'Module.name', 'Module.plugin', 'Module.content', 'Module.module', 'Module.config', 'Module.show_heading' ), 'conditions' => array( 'Position.name' => $position, 'Module.admin' => $admin, 'Module.active' => 1 ), 'contain' => $this->__contain ) ); Cache::write($position . '.' . ($admin ? 'admin' : 'user'), $modules, 'modules'); return $modules; } public function getModule($module = null, $admin = false){ if (!$module) { return array(); } $_module = Cache::read('single.' . ($admin ? 'admin' : 'user'), 'modules'); if($_module !== false){ return $_module; } $module = $this->find( 'first', array( 'fields' => array( 'Module.id', 'Module.name', 'Module.plugin', 'Module.content', 'Module.module', 'Module.config', 'Module.show_heading' ), 'conditions' => array( 'Module.name' => $module, 'Module.admin' => $admin, 'Module.active' => 1 ), 'contain' => $this->__contain ) ); Cache::write('single.' . ($admin ? 'admin' : 'user'), $module, 'modules'); return $module; } public function getModuleList($plugin = null){ $admin = $non_admin = array(); $conditions = array(); $path = APP; if ($plugin) { $plugin = strtolower($plugin); $path = App::pluginPath($plugin); $conditions = array('Module.plugin' => $plugin); } App::import('File'); $this->Folder = new Folder($path.$this->subPath); $files = $this->Folder->read(); foreach($files[1] as $file){ $file = str_replace('.ctp', '', $file); $non_admin[$file] = Inflector::humanize($file); } if(!empty($files[0]) && is_dir($path.$this->subPath.'admin')){ $this->Folder->cd($path.$this->subPath.'admin'); $files = $this->Folder->read(); foreach($files[1] as &$file){ $file = str_replace('.ctp', '', $file); $admin['admin/'.$file] = Inflector::humanize($file); } } return array( 'admin' => $admin, 'user' => $non_admin ); } } <file_sep><?php /** * Filter events. * * events for the filter plugin * * Copyright (c) 2010 <NAME> ( dogmatic69 ) * * @filesource * @copyright Copyright (c) 2010 <NAME> ( dogmatic69 ) * @link http://www.infinitas-cms.org * @package infinitas * @subpackage infinitas.filter.events * @license http://www.opensource.org/licenses/mit-license.php The MIT License * @since 0.8a * * @author dogmatic69 * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. */ final class FilterEvents extends AppEvents{ public function onRequireComponentsToLoad($event){ return array( 'Filter.Filter' => array( 'actions' => array('admin_index') ) ); } public function onRequireHelpersToLoad($event){ return array( 'Filter.Filter' ); } public function onRequireCssToLoad($event, $data = null) { return array( '/filter/css/filter' ); } }<file_sep><?php $map = array( 1 => array( '000008_events' => 'R4c94edcc56e8492aa06b78d86318cd70'), ); ?><file_sep><?php class EventComponent extends Object{ /** * Controller Instance * @var object */ public $Controler = null; /** * Startup * * @param object $controller * */ public function initialize($Controller){ $this->Controller = $Controller; } /** * Trigger a event * * @param string $eventName Name of the event to trigger * @param array $data Data to pass to event handler * @return array: */ public function trigger($eventName, $data = array()){ return EventCore::trigger($this->Controller, $eventName, $data); } }<file_sep><?php final class ManagementEvents extends AppEvents{ public function onPluginRollCall(){ return array( 'name' => 'Setup', 'description' => 'Configure Your site', 'icon' => '/management/img/icon.png', 'author' => 'Infinitas', 'dashboard' => array('plugin' => 'management', 'controller' => 'management', 'action' => 'site') ); } public function onSetupConfig(){ return Configure::load('management.config'); } public function onSetupCache(){ return array( 'name' => 'core', 'config' => array( 'prefix' => 'core.', ) ); } public function onAdminMenu($event){ return array(); } public function onSlugUrl($event, $data){ switch($data['type']){ case 'comments': return array( 'plugin' => 'management', 'controller' => 'comments', 'action' => $data['data']['action'], 'id' => $data['data']['id'], 'category' => 'user-feedback' ); break; } // switch } public function onSetupRoutes(){ Router::connect('/admin', array('plugin' => 'management', 'controller' => 'management', 'action' => 'dashboard', 'admin' => true, 'prefix' => 'admin')); } }<file_sep><?php $map = array( 1 => array( '000008_modules' => 'R4c94edcd902444fc83c078d86318cd70'), ); ?><file_sep><?php /** * * */ class RelationType extends ManagementAppModel{ var $name = 'RelationType'; var $tablePrefix = 'relation_'; }<file_sep><?php $map = array( 1 => array( '000008_server_status' => 'R4cfe4072364844ea9a141bbd6318cd70'), ); ?><file_sep><?php echo $form->create('User'); echo $form->input('id'); echo $form->input('email', array('readonly' => 'readonly')); if(Configure::read('Website.login_type') == 'username'){ echo $form->input('username', array('readonly' => 'readonly')); } echo $form->input('new_password', array('type' => '<PASSWORD>')); echo $form->input('confirm_password', array('type' => '<PASSWORD>')); echo $form->end(__('Reset Password', true)); ?><file_sep><?php class NewslettersUser extends NewsletterAppModel { } <file_sep><?php /** * The Menu model. * * This is just a way to store the names of the menu groups that have been * created * * Copyright (c) 2010 <NAME> ( dogmatic69 ) * * @filesource * @copyright Copyright (c) 2010 <NAME> ( dogmatic69 ) * @link http://www.infinitas-cms.org * @package Infinitas.Menus * @subpackage Infinitas.Menus.models.Menu * @license http://www.opensource.org/licenses/mit-license.php The MIT License * @since 0.8a * * @author dogmatic69 * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. */ class Menu extends MenusAppModel{ /** * The model name * * @var string * @access public */ public $name = 'Menu'; /** * The relations for the menu * * @var array * @access public */ public $hasMany = array( 'MenuItem' => array( 'className' => 'Menus.MenuItem', 'foreignKey' => 'menu_id', 'conditions' => array( 'MenuItem.active' => 1 ), 'dependent' => true ) ); public function __construct($id = false, $table = null, $ds = null) { parent::__construct($id, $table, $ds); $this->validate = array( 'name' => array( 'notEmpty' => array( 'rule' => 'notEmpty', 'message' => __('Please enter a name for the menu', true) ), 'validName' => array( 'rule' => '/[a-z_]{1,100}/i', 'message' => __('Please enter a name for the menu lower case letters and under-scores only', true) ), 'isUnique' => array( 'rule' => 'isUnique', 'message' => __('There is already a menu with that name', true) ) ), 'type' => array( 'notEmpty' => array( 'rule' => 'notEmpty', 'message' => __('Please enter the menu type', true) ), 'validName' => array( 'rule' => '/[a-z_]{1,100}/i', 'message' => __('Please enter a valid type for the menu lower case letters and under-scores only', true) ) ) ); } /** * Before saving there needs to be a container item for the menu, hasContainer * will check and create one if needed. If something goes wrong the method will * return false and the save will abort. * * @param array $options the options for the save * @access public * * @return bool true if all is well, false to abort */ public function beforeSave($options){ parent::beforeSave($options); return $this->MenuItem->hasContainer($this->id, $this->data['Menu']['name']); } /** * If the menu is deleted, the menu items should also be deleted. As its a * mptt tree deleting the root node will cause cake to delete everything * within the tree and the whole thing will be gone * * @access public * * @return mixed what ever the parent returns */ public function afterDelete() { $menuItem = $this->MenuItem->find('first', array('conditions' => array('menu_id' => $this->id, 'parent_id' => 0))); $this->MenuItem->Behaviors->disable('Trashable'); $this->MenuItem->delete($menuItem['MenuItem']['id']); $this->MenuItem->Behaviors->enable('Trashable'); return parent::afterDelete(); } }<file_sep><?php final class EventsEvents extends AppEvents { public function onRequireHelpersToLoad(){ return array( 'Events.Event' => true ); } public function onRequireComponentsToLoad(){ return 'Events.Event'; } public function onReturnEventForTest($event){ return $event; } }<file_sep><?php class MailSystemsController extends EmailsAppController{ public $name = 'MailSystems'; public function beforeFilter(){ parent::beforeFilter(); $this->helpers[] = 'Emails.EmailAttachments'; } public function admin_dashboard(){ $accounts = ClassRegistry::init('Emails.EmailAccount')->getMyAccounts($this->Session->read('Auth.User.id')); if(empty($accounts)){ $this->notice('You do not have any accounts set up', 'notice'); } $this->set(compact('accounts')); } public function admin_index(){ if(!$this->params['account']){ $this->notice(__('Please select an account', true), 'notice', 0, null, true); } $this->paginate = array( 'conditions' => array( 'MailSystem.account' => $this->params['account'] ), 'order' => array( 'date' => 'desc' ) ); $mails = $this->paginate(); $filterOptions = $this->Filter->filterOptions; $filterOptions['fields'] = array( 'name', 'description' ); $this->set(compact('mails', 'filterOptions')); } public function admin_view(){ if(!$this->params['email']){ $this->notice(__('Please select an email to view', true), 'error', 0, true); } $mail = $this->MailSystem->find( 'first', array( 'conditions' => array( 'MailSystem.account' => $this->params['account'], 'MailSystem.id' => $this->params['email'] ) ) ); $this->set(compact('mail')); } public function admin_get_mail(){ if(!$this->params['email']){ $this->notice(__('Please select an email to view', true), 'error', 0, true); } $this->layout = 'ajax'; Configure::write('debug', 0); $mail = $this->MailSystem->find( 'first', array( 'conditions' => array( 'MailSystem.account' => $this->params['account'], 'MailSystem.id' => $this->params['email'] ) ) ); $this->set(compact('mail')); } public function admin_mass(){ $massAction = $this->MassAction->getAction($this->params['form']); switch($massAction){ case 'back': $this->redirect(array('action' => 'index')); break; default: parent::admin_mass(); break; } } }<file_sep><?php /** * Infinitas View * * makes the mustache templating class available in the views, and extends * the Theme View to allow the use of themes. * * Copyright (c) 2010 <NAME> ( dogmatic69 ) * * @filesource * @copyright Copyright (c) 2010 <NAME> ( dogmatic69 ) * @link http://www.infinitas-cms.org * @package infinitas * @subpackage infinitas.extentions.views.infinitas * @license http://www.opensource.org/licenses/mit-license.php The MIT License * @since 0.8a * * @author dogmatic69 * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. */ App::import('Lib', 'Libs.Mustache'); App::import('View', 'Theme'); App::import('View', 'Libs.LazyHelper'); class InfinitasView extends LazyHelperView{ /** * place holder for the mustache templating engine. */ public $Mustache = null; /** * internal cache of template parts from the entire system */ private $__mustacheTemplates = array(); /** * internal cache of vars that are used in the mustache template rendering */ private $__vars = array(); /** * get the */ public function __construct($Controller, $register = true) { $this->Mustache = new Mustache(); parent::__construct($Controller, $register); } /** * render views * * Lets cake do its thing, then takes the output and runs it through * mustache, doing all the template rendering things, and then returns * the final output to where ever its going. * * you can pass ?mustache=false in the url to see the raw output skipping * the template rendering. could be handy for debugging. if debug is off * this has no effect. */ public function _render($___viewFn, $___dataForView, $loadHelpers = true, $cached = false) { $out = parent::_render($___viewFn, $___dataForView, $loadHelpers, $cached); // only on for admin or it renders the stuff in the editor which is pointless // could maybe just turn it off for edit or some other work around if(!isset($this->params['admin'])){ $this->params['admin'] = false; } if($this->Mustache !== null && !$this->params['admin']){ if(empty($this->__mustacheTemplates)){ $this->__mustacheTemplates = array_filter(current($this->Event->trigger('requireGlobalTemplates'))); } foreach($this->__mustacheTemplates as $plugin => $template){ $this->__vars['viewVars'][Inflector::classify($plugin) . 'Template'] = $template; } //$this->__vars['viewVars']['templates'] =& $this->__mustacheTemplates['requireGlobalTemplates']; $this->__vars['viewVars'] = $this->viewVars; $this->__vars['params'] = $this->params; if(Configure::read('debug') < 1){ unset($this->params['url']['mustache']); } if(!isset($this->params['url']['mustache']) || $this->params['url']['mustache'] != 'false' && strstr($___viewFn, 'front.ctp')){ $out = $this->Mustache->render($out, $this->__vars['viewVars']); } } return $out; } }<file_sep><?php /* SVN FILE: $Id$ */ /* Webmaster schema generated on: 2010-09-18 18:09:23 : 1284828623*/ class WebmasterSchema extends CakeSchema { var $name = 'Webmaster'; function before($event = array()) { return true; } function after($event = array()) { } } ?><file_sep><?php class PluginsController extends InstallerAppController{ public $name = 'Plugins'; public $helpers = array( 'Filter.Filter' ); public function admin_dashboard(){ } public function admin_index(){ $plugins = $this->paginate(null, $this->Filter->filter); $filterOptions = $this->Filter->filterOptions; $filterOptions['fields'] = array( 'name', 'author', 'version', 'core' => Configure::read('CORE.core_options'), 'active' => Configure::read('CORE.active_options') ); $this->set(compact('plugins','filterOptions')); } public function admin_add(){ $this->notice( __('Nothing to see, move along', true), array( 'level' => 'warning', 'redirect' => true ) ); } public function admin_edit(){ self::admin_add(); } public function admin_install(){ } public function admin_update_infinitas(){ } }<file_sep><?php /* Event Test cases generated on: 2010-12-14 22:12:39 : 1292364399*/ App::import('Helper', 'Events.Event'); class EventHelperTestCase extends CakeTestCase { function startTest() { $this->Event = new EventHelper(); } function endTest() { unset($this->Event); ClassRegistry::flush(); } public function testEvents(){ $expected = array('foo'=> array()); $this->assertEqual($expected, $this->Event->trigger('foo')); $this->assertEqual($expected, $this->Event->trigger('plugin.foo')); $global = $this->Event->trigger('returnEventForTest'); $plugin = $this->Event->trigger('events.returnEventForTest'); /** * test calling the plugin method vs global returns the same format. */ $this->assertIdentical( $global['returnEventForTest']['events']->Handler, $plugin['returnEventForTest']['events']->Handler ); $this->assertIdentical($global['returnEventForTest']['events']->Handler, $this->Event); $this->assertIdentical($plugin['returnEventForTest']['events']->Handler, $this->Event); } }<file_sep><?php /* App Test cases generated on: 2010-12-14 01:12:59 : 1292290679*/ App::import('Model', 'AppModel'); class AppModelTestCase extends CakeTestCase { var $fixtures = array( 'plugin.configs.config', 'plugin.themes.theme', 'plugin.routes.route', 'plugin.view_counter.view_count' ); function startTest() { $this->AppModel = new AppModel(); } function endTest() { unset($this->AppModel); ClassRegistry::flush(); } public function testStuff(){ } }<file_sep><?php /** * @page Configs-Plugin Configs Plugin * * @section configs-overview What is it * * The configs plugin provides a way to overload configuration options from the * admin backend. The configs plugin uses the normal Configure class from * CakePHP. This is done to allow normal usage within the code but have the * ability to overload options in the backend. * * @link http://api.cakephp.org/class/configure * * @section configs-usage How to use it * * You can use all the normal Configure methods within the code including * Configure::load(), Configure::read() and Configure::write(). There are some * Event callbacks that are triggered early on in the request so if you would * like the data to be cached it should be loaded in these calls. See * AppEvents::onSetupConfig() for more information. * * Configs plugin provides a number of things to manage configs, including * adding new ones from the backend, overloading options and seeing what has * changed from the defaults. * * @image html sql_configs_plugin.png "Configs Plugin table structure" * * @section configs-see-also Also see * @ref AppEvents * @ref EventCore */ /** * @brief ConfigsAppController is the main controller class that all other * configuration related controllers extend. * * @copyright Copyright (c) 2010 <NAME> ( dogmatic69 ) * @link http://www.infinitas-cms.org * @package Infinitas.Configs * @license http://www.opensource.org/licenses/mit-license.php The MIT License * @since 0.5a * * @author dogmatic69 * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. */ class ConfigsAppController extends CoreAppController { }<file_sep><?php /* * Short Description / title. * * Overview of what the file does. About a paragraph or two * * Copyright (c) 2010 <NAME> ( dogmatic69 ) * * @filesource * @copyright Copyright (c) 2010 <NAME> ( dogmatic69 ) * @link http://www.infinitas-cms.org * @package {see_below} * @subpackage {see_below} * @license http://www.opensource.org/licenses/mit-license.php The MIT License * @since {check_current_milestone_in_lighthouse} * * @author {your_name} * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. */ final class FilemanagerEvents extends AppEvents{ public function onPluginRollCall(){ return array( 'name' => 'Files', 'description' => 'Allow you to manage files from the backend', 'icon' => '/filemanager/img/icon.png', 'author' => 'Infinitas' ); } public function onAdminMenu($event){ $menu['main'] = array( 'Root Dir' => array('controller' => false, 'action' => false) ); return $menu; } public function onSetupCache(){ return array( 'name' => 'filemanager', 'config' => array( 'prefix' => 'core.filemanager.', ) ); } public function onSetupConfig(){ return Configure::load('filemanager.config'); } }<file_sep><?php /* * Short Description / title. * * Overview of what the file does. About a paragraph or two * * Copyright (c) 2010 <NAME> ( dogmatic69 ) * * @filesource * @copyright Copyright (c) 2010 <NAME> ( dogmatic69 ) * @link http://www.infinitas-cms.org * @package {see_below} * @subpackage {see_below} * @license http://www.opensource.org/licenses/mit-license.php The MIT License * @since {check_current_milestone_in_lighthouse} * * @author {your_name} * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. */ $config['Newsletter'] = array( 'from_email' => '<EMAIL>', 'from_name' => 'dogmatic69 test', 'send_as' => 'both', 'send_count' => 200, 'send_interval' => 600, 'send_method' => 'smtp', 'smtp_username' => '<EMAIL>', 'smtp_password' => '<PASSWORD>', 'smtp_host' => 'mail.dogmatic69.com', 'smtp_out_going_port' => 49, 'smtp_timeout' => 100, 'template' => 'default', 'track_views' => true );<file_sep><?php /** * * */ class GeoLocationComponent extends Object{ /** * components being used here */ public $components = array( 'Session', 'RequestHandler', 'Events.Event', ); /** * default configuration */ public $configs = array(); private $__emptyCountry = array('country' => false, 'country_code' => false); private $__emptyCity = array( 'latitude' => false, 'longitude' => false, 'region' => false, 'city' => false, 'postcode' => false, 'areaCode' => false ); public function initialize(&$controller, $settings = array()) { $this->Controller = &$controller; $settings = array_merge(array(), (array)$settings); $this->countryDataFile = dirname(dirname(dirname(__FILE__))).DS.'libs'.DS.'geoip'.DS.'country.dat'; $this->cityDataFile = dirname(dirname(dirname(__FILE__))).DS.'libs'.DS.'geoip'.DS.'city.dat'; $this->__autoUserLocation(); } private function __autoUserLocation(){ if(!$this->Session->read('GeoLocation')){ $data = $this->Event->trigger('geoip.getLocation'); $this->Session->write('GeoLocation', current($data['getLocation'])); } } /** * Find users country. * * Attempt to get the country the user is from. returns unknown if its not * able to match something. */ public function getCountryData($ipAddress = null, $code = false){ if (!$ipAddress){ $ipAddress = $this->RequestHandler->getClientIP(); if (!$ipAddress) { return $this->__emptyCountry; } } App::import('Lib', 'Libs.Geoip/inc.php'); if (!is_file($this->countryDataFile)) { return $this->__emptyCountry; } $data = geoip_open($this->countryDataFile, GEOIP_STANDARD); $country = geoip_country_name_by_addr($data, $ipAddress); $country = empty($country) ? 'Unknown' : $country; if ($code) { $code = geoip_country_code_by_addr($data, $ip_address); $code = empty($code) ? 'Unknown' : $code; } geoip_close($data); return array('country' => $country, 'country_code' => $code); } /** * Get the city the user is in. */ public function getCityData($ipAddress = null){ if (!$ipAddress){ $ipAddress = $this->RequestHandler->getClientIP(); if (!$ipAddress) { return $this->__emptyCity; } } App::import('Lib', 'Libs.Geoip/inc.php'); App::import('Lib', 'Libs.Geoip/city.php'); App::import('Lib', 'Libs.Geoip/region_vars.php'); if(!is_file($this->cityDataFile)){ return $this->__emptyCity; } $gi = geoip_open($this->cityDataFile ,GEOIP_STANDARD); $data = geoip_record_by_addr($gi, $ipAddress); geoip_close($gi); pr($data); exit; return $this->cityData; } }<file_sep><?php class TimeZone extends ManagementAppModel{ var $name = 'TimeZone'; var $tablePrefix = ''; var $useTable = false; function find($type){ $return = timezone_identifiers_list(); switch($type){ case 'list': return $return; break; case 'all': foreach($return as $key => $value){ $data[] = array( 'TimeZone' => array( 'id' => $key, 'name' => $value ) ); } return $data; break; } // switch } }<file_sep><?php /* BaseChartEngine Test cases generated on: 2010-12-14 02:12:10 : 1292292070*/ App::import('helper', 'charts.Charts'); class BaseChartEnginelibTestCase extends CakeTestCase { function startTest() { $this->BaseEngine =& new ChartsBaseEngineHelper(); } function endTest() { unset($this->BaseEngine); ClassRegistry::flush(); } }<file_sep><?php App::import('Helper', 'Assets.Compress'); class CompressHelperTestCase extends CakeTestCase { public function startTest() { $this->Compress =& new CompressHelper(); } public function endTest() { unset($this->Compress); ClassRegistry::flush(); } public function testStuff(){ $this->assertIsA($this->Compress, 'CompressHelper'); } }<file_sep> <?php /* Infinitas Test cases generated on: 2010-03-13 14:03:31 : 1268484451*/ App::import('Behavior', 'libs.Infinitas'); App::import('Model', 'Routes.Route'); class RouteTest1 extends Route{ public $useDbConfig = 'test'; public function someMethod($conditions = array()){ return $this->find('list', array('conditions' => $conditions)); } } class RouteTest2 extends Route{ public $useDbConfig = 'test'; function _getList($conditions = array()){ return $this->find('list', array('conditions' => $conditions)); } } class InfinitasBehaviorTestCase extends CakeTestCase { //need something to set with var $fixtures = array( 'plugin.routes.route', 'plugin.themes.theme' ); function startTest() { $this->Infinitas =& new InfinitasBehavior(); App::import('AppModel'); $this->expectError('AppModel is using AppModel, please create a model file'); $this->AppModel = new AppModel(array('table' => false)); } function testGetJson(){ // test wrong usage $this->expectError(); $this->assertFalse($this->Infinitas->getJson()); $this->assertFalse($this->Infinitas->getJson($this->AppModel)); // bad json $this->assertFalse($this->Infinitas->getJson($this->AppModel, '')); $this->assertFalse($this->Infinitas->getJson($this->AppModel, 'some text')); $this->assertFalse($this->Infinitas->getJson($this->AppModel, array(123 => 'abc'))); $this->assertFalse($this->Infinitas->getJson($this->AppModel, '{123:"abc"}')); // good json $this->assertEqual($this->Infinitas->getJson($this->AppModel, '{"123":"abc"}'), array(123 => 'abc')); $this->assertEqual($this->Infinitas->getJson($this->AppModel, '{"abc":123}'), array('abc' => 123)); // nested array $this->assertEqual( $this->Infinitas->getJson($this->AppModel, '{"abc":{"abc":{"abc":{"abc":{"abc":{"abc":123}}}}}}'), array('abc' => array('abc' => array('abc' => array('abc' => array('abc' => array('abc' => 123)))))) ); // get object back $expected = new stdClass(); $expected->abc = 123; $this->assertEqual($this->Infinitas->getJson($this->AppModel, '{"abc":123}', array('assoc' => false)), $expected); //validate bad json $this->assertFalse($this->Infinitas->getJson($this->AppModel, 'some text', array(), false)); $this->assertTrue($this->Infinitas->getJson($this->AppModel, '{"abc":123}', array(), false)); $data['Model']= array( 'abc' => json_encode(array('abc' => 123)), 'xyz' => array( 123 => json_encode(array(1,2,3,4,5)), 'xyz' => array( 'abc123' => json_encode(array('a','b','c','d')) ) ) ); // get recursive json $expected = array('Model' => array('abc' => array('abc' => 123),'xyz' => array(123 => array(1,2,3,4,5),'xyz' => array('abc123' => array('a','b','c','d'))))); $this->assertEqual($expected, $this->Infinitas->getJsonRecursive($this->AppModel, $data)); // string passed in $this->assertEqual(array(array('abc')), $this->Infinitas->getJsonRecursive($this->AppModel, json_encode(array('abc')))); } function testSingleDimentionArray(){ //test wrong usage $this->assertEqual($this->Infinitas->singleDimentionArray($this->AppModel, ''), array()); $this->assertEqual($this->Infinitas->singleDimentionArray($this->AppModel, array()), array()); //normal tests $this->assertEqual($this->Infinitas->singleDimentionArray($this->AppModel, array(array('abc' => 123))), array()); $this->assertEqual($this->Infinitas->singleDimentionArray($this->AppModel, array('one' => array('abc' => 123), 'two' => 2)), array('two' => 2)); } function testGetPlugins(){ $_allPlugins = Configure::listObjects('plugin'); $allPlugins = array() + array('' => 'None'); foreach($_allPlugins as $k => $v){ $allPlugins[Inflector::underscore($v)] = $v; } // need to see how to do this //$this->assertEqual(count($this->Infinitas->getPlugins($this->AppModel, true)), count($allPlugins)); } function testGettingTableThings(){ // find all the tables $expected = array( 'core_routes', 'core_themes' ); $this->assertEqual($expected, $this->Infinitas->getTables($this->AppModel, 'test')); $this->expectError('ConnectionManager::getDataSource - Non-existent data source this_is_not_a_connection'); $this->Infinitas->getTables($this->AppModel, 'this_is_not_a_connection'); // find tables with a id field $expected = array( array('plugin' => 'Management', 'model' => 'Route', 'table' => 'core_routes'), array('plugin' => 'Management', 'model' => 'Theme', 'table' => 'core_themes') ); $this->assertEqual($expected, $this->Infinitas->getTablesByField($this->AppModel, 'test', 'id')); // find tables with a pass field $expected = array( array('plugin' => 'Management', 'model' => 'Route', 'table' => 'core_routes') ); $this->assertEqual($expected, $this->Infinitas->getTablesByField($this->AppModel, 'test', 'pass')); // find a table when there is no field. $this->assertEqual(array(), $this->Infinitas->getTablesByField($this->AppModel, 'test', 'no_such_field')); // no field passed $this->assertFalse($this->Infinitas->getTablesByField($this->AppModel, 'test')); } function testGetList(){ $this->assertFalse($this->Infinitas->getList($this->AppModel)); $expected = array( 7 => 'Home Page', 8 => 'Pages', 9 => 'Admin Home', 11 => 'Management Home', 12 => 'Blog Home - Backend', 13 => 'Blog Home - Frontend', 14 => 'Cms Home - Backend', 15 => 'Cms Home - Frontend', 16 => 'Newsletter Home - Backend', 18 => 'Blog Test' ); $this->assertEqual($expected, $this->Infinitas->getList($this->AppModel, 'Management', 'Route')); echo 'this error is normal (and the tests cant catch it)'; $this->assertEqual($expected, $this->Infinitas->getList($this->AppModel, null, 'CoreRoute')); // conditions $this->assertEqual(array(7 => 'Home Page'), $this->Infinitas->getList($this->AppModel, 'Management', 'Route', null, array('Route.id' => 7))); // custom find method $this->assertEqual($expected, $this->Infinitas->getList(new RouteTest1(), null, null, 'someMethod')); $this->assertEqual(array(11 => 'Management Home'), $this->Infinitas->getList($this->AppModel, 'Management', 'Route', 'someMethod', array('Route.id' => 11))); // _getList method tests $this->assertEqual($expected, $this->Infinitas->getList(new RouteTest2())); $this->assertEqual(array(), $this->Infinitas->getList(new RouteTest2(), null, null, null, array('Route.id' => 999))); } function endTest() { unset($this->Infinitas); ClassRegistry::flush(); } }<file_sep><?php App::import('Libs', 'Events.Event'); class EventsTest extends CakeTestCase { public function startTest(){ $this->Events = EventCore::getInstance(); } public function endTest() { unset($this->Events); ClassRegistry::flush(); } public function testGetEventInstance(){ $this->Events->something = 'foo'; $Event = EventCore::getInstance(); $this->assertTrue(isset($Event->something)); $this->assertTrue($Event->something == 'foo'); unset($Event); $this->assertFalse(isset($this->Event)); } public function testPluginsWith(){ $this->assertEqual(array(), $this->Events->pluginsWith('foo')); $this->assertEqual(array('events'), $this->Events->pluginsWith('returnEventForTest')); } public function testEventClass(){ $Event = new Event('someEvent', $this, 'myPlugin'); $this->assertIdentical($this, $Event->Handler); $this->assertEqual('someEvent', $Event->name); $this->assertEqual('myPlugin', $Event->plugin); } public function testEvents(){ $expected = array('foo'=> array()); $this->assertEqual($expected, $this->Events->trigger($this, 'foo')); $this->assertEqual($expected, $this->Events->trigger($this, 'plugin.foo')); $global = $this->Events->trigger($this, 'returnEventForTest'); $plugin = $this->Events->trigger($this, 'events.returnEventForTest'); /** * test calling the plugin method vs global returns the same format. */ $this->assertIdentical( $global['returnEventForTest']['events']->Handler, $plugin['returnEventForTest']['events']->Handler ); $this->assertIdentical($global['returnEventForTest']['events']->Handler, $this); $this->assertIdentical($plugin['returnEventForTest']['events']->Handler, $this); } public function testLoadEventClass(){ } }<file_sep><?php /* Theme Test cases generated on: 2010-03-13 11:03:20 : 1268471240*/ App::import('Model', 'management.Theme'); class ThemeTest extends Theme{ public $useDbConfig = 'test'; public $hasMany = array(); } class ThemeTestCase extends CakeTestCase { public $fixtures = array( 'plugin.management.theme', 'plugin.management.trash' ); function startTest() { $this->Theme = new ThemeTest(); } function testGetting(){ $expected['Theme'] = array( 'id' => 4, 'name' => 'aqueous_light', 'core' => 0 ); $this->assertEqual($expected, $this->Theme->getCurrentTheme()); } function testKeepingOneActiveThemeAtATime(){ // adding a new theme that is active should be the only active one $theme = $this->Theme->find('first', array('conditions' => array('Theme.active' => 0))); unset($theme['Theme']['id']); $theme['Theme']['active'] = 1; $theme['Theme']['name'] = 'some new theme'; $this->Theme->save($theme); $this->assertEqual(1, $this->Theme->find('count', array('conditions' => array('Theme.active' => 1)))); // making a theme active should be the only active one $theme = $this->Theme->find('first', array('conditions' => array('Theme.active' => 0))); $theme['Theme']['active'] = 1; $this->Theme->save($theme); $this->assertEqual(1, $this->Theme->find('count', array('conditions' => array('Theme.active' => 1)))); // deleteing an active theme should set another to active $this->Theme->delete($theme['Theme']['id']); $this->assertEqual(1, $this->Theme->find('count', array('conditions' => array('Theme.active' => 1)))); } function endTest() { unset($this->Theme); ClassRegistry::flush(); } }<file_sep><?php echo $form->create('User'); echo $form->input('email'); echo $form->end(__('Reset Password', true)); ?><file_sep><?php /* CoreModulesRoute Fixture generated on: 2010-08-17 12:08:51 : 1282046151 */ class ModulesRouteFixture extends CakeTestFixture { var $name = 'ModulesRoute'; var $table = 'core_modules_routes'; var $fields = array( 'id' => array('type' => 'integer', 'null' => false, 'default' => NULL, 'length' => 10, 'key' => 'primary'), 'module_id' => array('type' => 'integer', 'null' => false, 'default' => NULL, 'key' => 'index'), 'route_id' => array('type' => 'integer', 'null' => false, 'default' => NULL, 'key' => 'index'), 'indexes' => array('PRIMARY' => array('column' => 'id', 'unique' => 1), 'habtm' => array('column' => array('route_id', 'module_id'), 'unique' => 1), 'route' => array('column' => 'route_id', 'unique' => 0), 'module' => array('column' => 'module_id', 'unique' => 0)), 'tableParameters' => array('charset' => 'utf8', 'collate' => 'utf8_general_ci', 'engine' => 'InnoDB') ); var $records = array( array( 'id' => 65, 'module_id' => 2, 'route_id' => 0 ), array( 'id' => 56, 'module_id' => 4, 'route_id' => 0 ), array( 'id' => 66, 'module_id' => 5, 'route_id' => 0 ), array( 'id' => 39, 'module_id' => 12, 'route_id' => 0 ), array( 'id' => 60, 'module_id' => 13, 'route_id' => 0 ), array( 'id' => 40, 'module_id' => 14, 'route_id' => 0 ), array( 'id' => 41, 'module_id' => 15, 'route_id' => 0 ), array( 'id' => 77, 'module_id' => 16, 'route_id' => 0 ), array( 'id' => 68, 'module_id' => 25, 'route_id' => 0 ), array( 'id' => 95, 'module_id' => 26, 'route_id' => 0 ), ); }<file_sep><?php /* GlobalCommentAttribute Fixture generated on: 2010-12-13 17:12:02 : 1292259722 */ class CommentAttributeFixture extends CakeTestFixture { var $name = 'CommentAttribute'; var $table = 'global_comment_attributes'; var $fields = array( 'id' => array('type' => 'integer', 'null' => false, 'default' => NULL, 'length' => 10, 'key' => 'primary'), 'comment_id' => array('type' => 'integer', 'null' => false, 'default' => NULL, 'length' => 10), 'key' => array('type' => 'string', 'null' => false, 'default' => NULL, 'length' => 50, 'collate' => 'utf8_general_ci', 'charset' => 'utf8'), 'val' => array('type' => 'text', 'null' => false, 'default' => NULL, 'collate' => 'utf8_general_ci', 'charset' => 'utf8'), 'indexes' => array('PRIMARY' => array('column' => 'id', 'unique' => 1)), 'tableParameters' => array('charset' => 'utf8', 'collate' => 'utf8_general_ci', 'engine' => 'InnoDB') ); var $records = array( array( 'id' => 5, 'comment_id' => 3, 'key' => 'username', 'val' => 'user1' ), array( 'id' => 6, 'comment_id' => 3, 'key' => 'website', 'val' => 'http://user1.com' ), array( 'id' => 89, 'comment_id' => 332, 'key' => 'username', 'val' => 'user2' ), array( 'id' => 90, 'comment_id' => 332, 'key' => 'website', 'val' => 'http://user2.com' ), ); } ?><file_sep><?php /** * Comment Template. * * @todo -c Implement .this needs to be sorted out. * * Copyright (c) 2009 <NAME> ( dogmatic69 ) * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. * * @filesource * @copyright Copyright (c) 2009 <NAME> ( dogmatic69 ) * @link http://infinitas-cms.org * @package sort * @subpackage sort.comments * @license http://www.opensource.org/licenses/mit-license.php The MIT License * @since 0.5a */ echo $this->Html->link( __( 'Dashboard', true ), array( 'plugin' => 'management' ), array( 'class' => 'link' ) ); echo $this->Html->link( __( 'Blog', true ), array( 'plugin' => 'blog', 'controller' => 'posts', 'action' => 'dashboard' ), array( 'class' => 'link' ) ); echo $this->Html->link( __( 'Newsletters', true ), array( 'plugin' => 'newsletter', 'controller' => 'newsletters', 'action' => 'dashboard' ), array( 'class' => 'link' ) ); echo $this->Html->link( __( 'Cms', true ), array( 'plugin' => 'cms', 'controller' => 'categories', 'action' => 'dashboard' ), array( 'class' => 'link' ) ); //echo $this->Html->link( __( 'Cart', true ), array( 'plugin' => 'cart' ), array( 'class' => 'link' ) ); echo '</br>'; echo $this->Html->link( __( 'Config Manager', true ), array( 'plugin' => 'management', 'controller' => 'configs' ), array( 'class' => 'link' ) ); echo $this->Html->link( __( 'File Manager', true ), array( 'plugin' => 'filemanager', 'controller' => 'file_manager' ), array( 'class' => 'link' ) ); echo $this->Html->link( __( 'Routing Manager', true ), array( 'plugin' => 'management', 'controller' => 'routes' ), array( 'class' => 'link' ) ); echo $this->Html->link( __( 'Themes Manager', true ), array( 'plugin' => 'management', 'controller' => 'themes' ), array( 'class' => 'link' ) ); echo $this->Html->link( __( 'Modules Manager', true ), array( 'plugin' => 'management', 'controller' => 'modules' ), array( 'class' => 'link' ) ); ?><file_sep><?php /** * @brief Commentable Model Behavior * * Allows you to attach a comment to any model in your application * Moderates/Validates comments to check for spam. * Validates comments based on a point system. High points is an automatic approval, * where as low points is marked as spam or deleted. * * Based on Jonathan Snooks outline. * * @copyright Stoop Dev * @link http://github.com/josegonzalez/cakephp-commentable-behavior * @package Infinitas.Comments.models.behaviors * @license http://www.opensource.org/licenses/mit-license.php The MIT License * @since 0.6a * * @author <NAME> - http://github.com/josegonzalez/cakephp-commentable-behavior * @author dogmatic69 * * @todo this code should be refactored into a spam filter lib that can be used * all over (eg: email contact forms) the comment model can just check in beforeSave * that it is not spam, could even be a validation rule. * * @todo add a rating method for amount of text with no links vs total amount of text * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. */ class CommentableBehavior extends ModelBehavior{ /** * Settings initialized with the behavior * * @var array * @access public */ public $defaults = array( 'plugin' => 'Comment', 'class' => 'Comment', // name of Comment model 'auto_bind' => true, // automatically bind the model to the User model (default true), 'sanitize' => true, // whether to sanitize incoming comments 'column_author' => 'name', // Column name for the authors name 'column_content' => 'comment', // Column name for the comments body 'column_class' => 'class', // Column name for the foreign model 'column_email' => 'email', // Column name for the authors email 'column_website' => 'website', // Column name for the authors website 'column_foreign_id' => 'foreign_id',// Column name of the foreign id that links to the article/entry/etc 'column_status' => 'status', // Column name for automatic rating 'column_points' => 'points', // Column name for accrued points 'deletion' => -10 // How many points till the comment is deleted (negative) ); /** * Contain settings indexed by model name. * * @var array * @access private */ private $__settings = array(); /** * @brief Initiate behaviour for the model using settings. * * @param object $Model Model using the behaviour * @param array $settings Settings to override for model. * @access public * * @return void */ public function setup($Model, $settings = array()) { $default = $this->defaults; $default['blacklist_keywords'] = explode(',', Configure::read('Website.blacklist_keywords')); $default['blacklist_words'] = explode(',', Configure::read('Website.blacklist_words')); $default['conditions'] = array('Comment.class' => $Model->alias); $default['class'] = $Model->name.'Comment'; if (!isset($this->__settings[$Model->alias])) { $this->__settings[$Model->alias] = $default; } $this->__settings[$Model->alias] = array_merge($this->__settings[$Model->alias], (array)$settings); $Model->bindModel( array( 'hasMany' => array( $Model->alias.'Comment' => array( 'className' => 'Comments.Comment', 'foreignKey' => 'foreign_id', 'limit' => 5, 'order' => array( $Model->alias . 'Comment.created' => 'desc' ), 'fields' => array( $Model->alias . 'Comment.id', $Model->alias . 'Comment.class', $Model->alias . 'Comment.foreign_id', $Model->alias . 'Comment.user_id', $Model->alias . 'Comment.email', $Model->alias . 'Comment.comment', $Model->alias . 'Comment.active', $Model->alias . 'Comment.status', $Model->alias . 'Comment.created' ), 'conditions' => array( 'or' => array( $Model->alias . 'Comment.active' => 1 ) ), 'dependent' => true ) ) ), false ); } /** * @brief contain the comments * * before a find is done, add the comments to contain so they are available * in the view. * * @param object $Model referenced model * @param array $query the query being done * @access public * * @return array the find query data */ public function beforeFind($Model, $query) { if($Model->findQueryType == 'count'){ return $query; } $query['contain'][$Model->alias.'Comment'] = array('CommentAttribute'); if(isset($query['recursive']) && $query['recursive'] == -1){ $query['recursive'] = 0; } call_user_func(array($Model, 'contain'), $query['contain']); return $query; } /** * @brief create a new comment calls the methods to do the spam checks * * @param object $Model the model object * @param array $data the comment being saved * @access public * * @return bool true on save, false when not. */ public function createComment($Model, $data = array()) { if (empty($data[$this->__settings[$Model->alias]['class']])) { return false; } unset($data[$Model->alias]); $Model->Comment->validate = array( $this->__settings[$Model->alias]['column_content'] => array( 'notempty' => array( 'rule' => array('notempty') ) ), $this->__settings[$Model->alias]['column_email'] => array( 'notempty' => array( 'rule' => array('notempty') ), 'email' => array( 'rule' => array('email'), 'message' => __('Please enter a valid email address', true) ) ), $this->__settings[$Model->alias]['column_class'] => array( 'notempty' => array( 'rule' => array('notempty') ) ), $this->__settings[$Model->alias]['column_foreign_id'] => array( 'notempty' => array( 'rule' => array('notempty') ) ), $this->__settings[$Model->alias]['column_status'] => array( 'notempty' => array( 'rule' => array('notempty') ) ), $this->__settings[$Model->alias]['column_points'] => array( 'notempty' => array( 'rule' => array('notempty') ), 'numeric' => array( 'rule' => array('numeric'), ) ) ); $data[$this->__settings[$Model->alias]['class']] = $this->__rateComment($Model, $data[$this->__settings[$Model->alias]['class']]); if($data[$this->__settings[$Model->alias]['class']][$this->__settings[$Model->alias]['column_points']] < Configure::read('Comments.spam_threshold')){ return false; } $data[$this->__settings[$Model->alias]['class']]['active'] = 0; if (Configure::read('Comments.auto_moderate') === true && $data[$this->__settings[$Model->alias]['class']]['status'] == 'pending' || $data[$this->__settings[$Model->alias]['class']]['status'] == 'approved' ) { $data[$this->__settings[$Model->alias]['class']]['active'] = 1; } if ($this->__settings[$Model->alias]['sanitize']) { App::import('Sanitize'); $data[$this->__settings[$Model->alias]['class']][$this->__settings[$Model->alias]['column_email']] = Sanitize::clean($data[$this->__settings[$Model->alias]['class']][$this->__settings[$Model->alias]['column_email']]); $data[$this->__settings[$Model->alias]['class']][$this->__settings[$Model->alias]['column_content']] = Sanitize::clean($data[$this->__settings[$Model->alias]['class']][$this->__settings[$Model->alias]['column_content']]); } $Model->{$this->__settings[$Model->alias]['class']}->create(); if ($Model->{$this->__settings[$Model->alias]['class']}->save($data)) { return true; } return false; } /** * @brief gets comments * * @var $Model object the model object * @var $options array the data from the form * @access private * * @return int the amout of points to add/deduct */ public function getComments($Model, $options = array()) { $options = array_merge(array('id' => $Model->id, 'options' => array()), $options); $parameters = array(); if (isset($options['id']) && is_numeric($options['id'])) { $settings = $this->__settings[$Model->alias]; $parameters = array_merge_recursive( array( 'conditions' => array( $settings['class'] . '.' . $settings['column_class'] => $Model->alias, $settings['class'] . '.foreign_id' => $options['id'], $settings['class'] . '.' . $settings['column_status'] => 'approved' ) ), $options['options'] ); } return $Model->Comment->find('all', $parameters); } /** * @brief get the rating of a comment before its saved * * the main method that calls all the comment rating code. after getting * the score it will set a staus for the comment. * * @var $Model object the model object * @var $data array the data from the form * @access private * * @return int the amout of points to add/deduct */ private function __rateComment($Model, $data) { if (empty($data)) { $data[$this->__settings[$Model->alias]['column_points']] = -100; $data[$this->__settings[$Model->alias]['column_status']] = 'delete'; return $data; } $points = $this->__rateLinks($Model, $data); $points += $this->__rateLength($Model, $data); $points += $this->__rateEmail($Model, $data); $points += $this->__rateKeywords($Model, $data); $points += $this->__rateStartingWord($Model, $data); $points += $this->__rateByPreviousComment($Model, $data); $points += $this->__rateBody($Model, $data); $data[$this->__settings[$Model->alias]['column_points']] = $points; if ($points >= 1) { $data[$this->__settings[$Model->alias]['column_status']] = 'approved'; } else if ($points == 0) { $data[$this->__settings[$Model->alias]['column_status']] = 'pending'; } else if ($points <= $this->__settings[$Model->alias]['deletion']) { $data[$this->__settings[$Model->alias]['column_status']] = 'delete'; } else { $data[$this->__settings[$Model->alias]['column_status']] = 'spam'; } return $data; } /** * @brief adds points based on the amount and length of links in the comment * * @var $Model object the model object * @var $data array the data from the form * @access private * * @return int the amout of points to add/deduct */ private function __rateLinks($Model, $data) { $links = preg_match_all( "#(^|[\n ])(?:(?:http|ftp|irc)s?:\/\/|www.)(?:[-A-Za-z0-9]+\.)+[A-Za-z]{2,4}(?:[-a-zA-Z0-9._\/&=+%?;\#]+)#is", $data[$this->__settings[$Model->alias]['column_content']], $matches ); $links = $matches[0]; $this->totalLinks = count($links); $length = mb_strlen($data[$this->__settings[$Model->alias]['column_content']]); // How many links are in the body // -1 per link if over 2, otherwise +2 if less than 2 $maxLinks = Configure::read('Comments.maximum_links'); $maxLinks > 0 ? $maxLinks : 2; $points = $this->totalLinks > $maxLinks ? $this->totalLinks * -1 : 2; // URLs that have certain words or characters in them // -1 per blacklisted word // URL length // -1 if more then 30 chars foreach ($links as $link) { foreach ($this->__settings[$Model->alias]['blacklist_words'] as $word) { $points = stripos($link, $word) !== false ? $points - 1 : $points; } foreach ($this->__settings[$Model->alias]['blacklist_keywords'] as $keyword) { $points = stripos($link, $keyword) !== false ? $points - 1 : $points; } $points = strlen($link) >= 30 ? $points - 1 : $points; } return $points; } /** * @brief rate according to the lenght of the text * * Rate the length of the comment. if the length is greater than the required * and there are no links then 2 points are added. with links only 1 point * is added. if the lenght is too short 1 point is deducted * * @var $Model object the model object * @var $data array the data from the form * @access private * * @return int the amout of points to add/deduct */ private function __rateLength($Model, $data) { // How long is the body // +2 if more then 20 chars and no links, -1 if less then 20 $length = mb_strlen($data[$this->__settings[$Model->alias]['column_content']]); $minLenght = Configure::read('Comments.minimum_length') > 0 ? Configure::read('Comments.minimum_length') : 20; if ($length >= $minLenght && $this->totalLinks <= 0) { return 2; } elseif ($length >= $minLenght && $this->totalLinks == 1) { return 1; } elseif ($length < $minLenght) { return - 1; } } /** * @brief rate according to past history * * Check previous comments by the same user. If they have been marked as * active they get points added, if they are marked as spam points are * deducted. * * on dogmatic69.com 95% of the spam had a number as the email address, * There is hardly any people that have a number as the email address. * * @var $Model object the model object * @var $data array the data from the form * @access private * * @return int the amout of points to deduct */ private function __rateEmail($Model, $data) { $parts = explode('@', $data[$this->__settings[$Model->alias]['column_email']]); if(is_int($parts[0])){ return -15; } $points = 0; $comments = $Model->{$this->__settings[$Model->alias]['class']}->find( 'all', array( 'fields' => array($this->__settings[$Model->alias]['class'].'.id', $this->__settings[$Model->alias]['class'].'.status'), 'conditions' => array( $this->__settings[$Model->alias]['class'].'.' . $this->__settings[$Model->alias]['column_email'] => $data[$this->__settings[$Model->alias]['column_email']], $this->__settings[$Model->alias]['class'].'.active' => 1 ), 'contain' => false ) ); foreach ($comments as $comment) { switch($comment[$this->__settings[$Model->alias]['class']]['status']){ case 'approved': ++$points; break; case 'spam': --$points; break; } } return $points; } /** * @brief check for blacklisted words * * Checks the text to see if it contains any of the blacklisted words. * If there are, 1 point is deducted for each match. * * @var $Model object the model object * @var $data array the data from the form * @access private * * @return int the amout of points to deduct */ private function __rateKeywords($Model, $data) { $points = 0; foreach ($this->__settings[$Model->alias]['blacklist_keywords'] as $keyword) { if (stripos($data[$this->__settings[$Model->alias]['column_content']], $keyword) !== false) { --$points; } } return $points; } /** * @brief rate according to the start of the comment * * Checks the first word against the blacklist keywords. if there is a * match then 10 points are deducted. * * @var $Model object the model object * @var $data array the data from the form * @access private * * @return int the amout of points to deduct */ private function __rateStartingWord($Model, $data) { $firstWord = mb_substr( $data[$this->__settings[$Model->alias]['column_content']], 0, stripos($data[$this->__settings[$Model->alias]['column_content']], ' ') ); return in_array(mb_strtolower($firstWord), $this->__settings[$Model->alias]['blacklist_keywords']) ? - 10 : 0; } /** * @brief Deduct points if it is a copy of any other comments in the database. * * @var $Model object the model object * @var $data array the data from the form * @access private * * @return int the amout of points to deduct */ private function __rateByPreviousComment($Model, $data) { // Body used in previous comment // -1 per exact comment $previousComments = $Model->{$this->__settings[$Model->alias]['class']}->find( 'count', array( 'conditions' => array( $this->__settings[$Model->alias]['class'] . '.' . $this->__settings[$Model->alias]['column_content'] => $data[$this->__settings[$Model->alias]['column_content']] ), 'contain' => false ) ); return 0 - $previousComments; } /** * @brief rate according to the structure of words * * Rate according to the text. Generaly words do not contain more than * a few consecutive consonants. -1 point is given per 5 consecutive * consonants. * * @var $Model object the model object * @var $data array the data from the form * @access private * * @return int the amout of points to deduct */ private function __rateBody($Model, $data) { $consonants = preg_match_all( '/[^aAeEiIoOuU\s]{5,}+/i', $data[$this->__settings[$Model->alias]['column_content']], $matches ); return 0 - count($matches[0]); } }<file_sep><?php $map = array( 1 => array( '000008_migrations' => 'R4c94edcdbdd44dd9a88c78d86318cd70'), ); ?><file_sep><div class="dashboard"> <h1><?php __('Missing Database Table'); ?></h1> <p class="error"> <strong><?php __('Error'); ?>: </strong> <?php printf(__('Database table %1$s for model %2$s was not found.', true), '<em>' . $table . '</em>', '<em>' . $model . '</em>'); ?> </p> </div><file_sep><?php /** * The MenuItemsController * * Used to show and manage the items in a menu group. * * Copyright (c) 2010 <NAME> ( dogmatic69 ) * * @filesource * @copyright Copyright (c) 2010 <NAME> ( dogmatic69 ) * @link http://www.infinitas-cms.org * @package Infinitas.Menus * @subpackage Infinitas.Menus.controllers.MenusItemsController * @license http://www.opensource.org/licenses/mit-license.php The MIT License * @since 0.8a * * @author dogmatic69 * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. */ class MenuItemsController extends MenusAppController{ /** * The controller name * * @var string * @access public */ public $name = 'MenuItems'; public function admin_index(){ $this->paginate = array( 'contain' => array( 'Menu' ) ); $menuItems = $this->paginate( null, array_merge(array('MenuItem.parent_id !=' => 0), $this->Filter->filter) ); $filterOptions = $this->Filter->filterOptions; $filterOptions['fields'] = array( 'name', 'menu_id' => array(null => __('All', true)) + $this->MenuItem->Menu->find('list'), 'group_id' => array(null => __('Public', true)) + $this->MenuItem->Group->find('list'), 'active' => (array)Configure::read('CORE.active_options') ); $this->set(compact('menuItems','filterOptions')); } public function admin_add(){ parent::admin_add(); // auto select parent when the + button is used if (isset($this->params['named']['parent_id'])) { $this->data['MenuItem']['parent_id'] = $this->params['named']['parent_id']; } $menus = $this->MenuItem->Menu->find('list'); if(empty($menus)){ $this->notice( __('Please add a menu before adding items', true), array( 'level' => 'notice', 'redirect' => array( 'controller' => 'menus' ) ) ); } $groups = array(0 => __('Public', true)) + $this->MenuItem->Group->find('list'); $parents = array(0 => __('Root', true)) + $this->MenuItem->generateTreeList(array('MenuItem.parent_id !=' => 0, 'MenuItem.menu_id' => reset(array_keys($menus)))); $plugins = $this->MenuItem->getPlugins(); $this->set(compact('menus', 'groups', 'parents', 'plugins')); } /** * Get parent menus * * Used for the ajax getting of parent menus items to populate the ajax * dropdown menus when building and editing menu items. * * @access public */ public function admin_getParents() { $conditions = array('MenuItem.menu_id' => $this->params['named']['plugin']); $json = array_merge( array(0 => __('Root', true)), $this->MenuItem->generateTreeList($conditions) ); $this->set(compact('json')); } public function admin_edit($id = null){ parent::admin_edit($id); $menus = $this->MenuItem->Menu->find('list'); $groups = array(0 => __('Public', true)) + $this->MenuItem->Group->find('list'); $parents = array(0 => __('Root', true)) + $this->MenuItem->generateTreeList(array('MenuItem.parent_id !=' => 0, 'MenuItem.menu_id' => $this->data['MenuItem']['menu_id'])); $plugins = $this->MenuItem->getPlugins(); $controllers = $this->MenuItem->getControllers($this->data['MenuItem']['plugin']); $actions = $this->MenuItem->getActions($this->data['MenuItem']['plugin'], $this->data['MenuItem']['controller']); $this->set(compact('menus', 'groups', 'parents', 'plugins', 'controllers', 'actions')); } }<file_sep><?php /* Event Test cases generated on: 2010-12-14 22:12:32 : 1292364992*/ class DummyModel extends Model{ public $name = 'DummyModel'; public $useTable = false; } class EventBehaviorTestCase extends CakeTestCase { public function startTest() { $this->DummyModel = new DummyModel(); $this->DummyModel->Behaviors->attach('Events.Event'); } public function endTest() { unset($this->Event); ClassRegistry::flush(); } public function testEvent(){ $expected = array('foo'=> array()); $this->assertEqual($expected, $this->DummyModel->triggerEvent('foo')); $this->assertEqual($expected, $this->DummyModel->triggerEvent('plugin.foo')); $global = $this->DummyModel->triggerEvent('returnEventForTest'); $plugin = $this->DummyModel->triggerEvent('events.returnEventForTest'); /** * test calling the plugin method vs global returns the same format. */ $this->assertIsA($global['returnEventForTest']['events']->Handler, 'DummyModel'); $this->assertIsA($plugin['returnEventForTest']['events']->Handler, 'DummyModel'); } }<file_sep><?php /* SVN FILE: $Id$ */ /* Libs schema generated on: 2010-09-18 18:09:21 : 1284828621*/ class LibsSchema extends CakeSchema { var $name = 'Libs'; function before($event = array()) { return true; } function after($event = array()) { } var $ratings = array( 'id' => array('type' => 'integer', 'null' => false, 'default' => NULL, 'length' => 10, 'key' => 'primary'), 'class' => array('type' => 'string', 'null' => false, 'default' => NULL, 'length' => 100), 'foreign_id' => array('type' => 'integer', 'null' => false, 'default' => NULL), 'rating' => array('type' => 'integer', 'null' => false, 'default' => NULL, 'length' => 3), 'user_id' => array('type' => 'integer', 'null' => true, 'default' => NULL), 'ip' => array('type' => 'string', 'null' => true, 'default' => NULL, 'length' => 100), 'created' => array('type' => 'datetime', 'null' => true, 'default' => NULL), 'indexes' => array('PRIMARY' => array('column' => 'id', 'unique' => 1)), 'tableParameters' => array('charset' => 'utf8', 'collate' => 'utf8_general_ci', 'engine' => 'InnoDB') ); } ?><file_sep><div class="dashboard"> <h1><?php __('Missing Database Connection'); ?></h1> <p class="error"> <strong><?php __('Error'); ?>: </strong> <?php printf(__('%s requires a database connection', true), $model); ?> </p> <p class="error"> <strong><?php __('Error'); ?>: </strong> <?php printf(__('Confirm you have created the file : %s.', true), APP_DIR . DS . 'config' . DS . 'database.php'); ?> </p> </div><file_sep><?php $map = array( 1 => array( '000008_crons' => 'R4cfe4011f4784cd9aef31bbd6318cd70'), ); ?><file_sep><?php class R4c94edcd902444fc83c078d86318cd70 extends CakeRelease { /** * Migration description * * @var string * @access public */ public $description = 'Migration for Modules version 0.8'; /** * Plugin name * * @var string * @access public */ public $plugin = 'Modules'; /** * Actions to be performed * * @var array $migration * @access public */ public $migration = array( 'up' => array( 'create_table' => array( 'module_positions' => array( 'id' => array('type' => 'integer', 'null' => false, 'default' => NULL, 'length' => 10, 'key' => 'primary'), 'name' => array('type' => 'string', 'null' => false, 'default' => NULL, 'length' => 50, 'key' => 'index'), 'created' => array('type' => 'datetime', 'null' => true, 'default' => NULL), 'modified' => array('type' => 'datetime', 'null' => true, 'default' => NULL), 'module_count' => array('type' => 'integer', 'null' => false, 'default' => '0', 'length' => 5), 'indexes' => array( 'PRIMARY' => array('column' => 'id', 'unique' => 1), 'name' => array('column' => 'name', 'unique' => 0), ), 'tableParameters' => array('charset' => 'utf8', 'collate' => 'utf8_general_ci', 'engine' => 'InnoDB'), ), 'modules' => array( 'id' => array('type' => 'integer', 'null' => false, 'default' => NULL, 'length' => 10, 'key' => 'primary'), 'name' => array('type' => 'string', 'null' => false, 'default' => NULL, 'length' => 100), 'content' => array('type' => 'text', 'null' => false, 'default' => NULL), 'plugin' => array('type' => 'string', 'null' => false, 'default' => NULL, 'length' => 50), 'module' => array('type' => 'string', 'null' => false, 'default' => NULL, 'length' => 100), 'config' => array('type' => 'text', 'null' => true, 'default' => NULL), 'theme_id' => array('type' => 'integer', 'null' => false, 'default' => '0'), 'position_id' => array('type' => 'integer', 'null' => false, 'default' => NULL, 'key' => 'index'), 'group_id' => array('type' => 'integer', 'null' => false, 'default' => '0'), 'ordering' => array('type' => 'integer', 'null' => false, 'default' => NULL), 'admin' => array('type' => 'boolean', 'null' => false, 'default' => '0'), 'active' => array('type' => 'boolean', 'null' => false, 'default' => '0'), 'show_heading' => array('type' => 'boolean', 'null' => false, 'default' => '1'), 'core' => array('type' => 'boolean', 'null' => false, 'default' => '0'), 'author' => array('type' => 'string', 'null' => true, 'default' => NULL, 'length' => 50), 'licence' => array('type' => 'string', 'null' => false, 'default' => NULL, 'length' => 75), 'url' => array('type' => 'string', 'null' => true, 'default' => NULL), 'update_url' => array('type' => 'string', 'null' => true, 'default' => NULL), 'created' => array('type' => 'datetime', 'null' => true, 'default' => NULL), 'modified' => array('type' => 'datetime', 'null' => true, 'default' => NULL), 'indexes' => array( 'PRIMARY' => array('column' => 'id', 'unique' => 1), 'module_loader_by_position' => array('column' => array('position_id', 'admin', 'active', 'ordering'), 'unique' => 0), ), 'tableParameters' => array('charset' => 'utf8', 'collate' => 'utf8_general_ci', 'engine' => 'InnoDB'), ), 'modules_routes' => array( 'id' => array('type' => 'integer', 'null' => false, 'default' => NULL, 'length' => 10, 'key' => 'primary'), 'module_id' => array('type' => 'integer', 'null' => false, 'default' => NULL), 'route_id' => array('type' => 'integer', 'null' => false, 'default' => NULL), 'indexes' => array( 'PRIMARY' => array('column' => 'id', 'unique' => 1), ), 'tableParameters' => array('charset' => 'utf8', 'collate' => 'utf8_general_ci', 'engine' => 'InnoDB'), ), ), ), 'down' => array( 'drop_table' => array( 'module_positions', 'modules', 'modules_routes' ), ), ); /** * Fixtures for data * * @var array $fixtures * @access public */ public $fixtures = array( 'core' => array( 'Module' => array( array( 'id' => 25, 'name' => 'Plugin Dock', 'content' => '', 'plugin' => 'menus', 'module' => 'admin/dock', 'config' => '', 'theme_id' => 0, 'position_id' => 1, 'group_id' => 1, 'ordering' => 1, 'admin' => 1, 'active' => 1, 'show_heading' => 0, 'core' => 1, 'author' => 'Infinitas', 'licence' => 'MIT', 'url' => 'http://infinitas-cms.org', 'update_url' => '', 'created' => '2010-09-09 19:47:53', 'modified' => '2010-09-16 14:09:45' ), array( 'id' => 12, 'name' => 'Admin Menu', 'content' => '', 'plugin' => 'menus', 'module' => 'admin/menu', 'config' => '{\\\"menu\\\":\\\"core_admin\\\"}', 'theme_id' => 0, 'position_id' => 1, 'group_id' => 1, 'ordering' => 2, 'admin' => 1, 'active' => 1, 'show_heading' => 0, 'core' => 1, 'author' => 'Infinitas', 'licence' => 'MIT', 'url' => 'http://infinitas-cms.org', 'update_url' => '', 'created' => '2010-01-27 18:14:16', 'modified' => '2010-09-16 14:09:45' ), array( 'id' => 26, 'name' => 'Admin Todo List', 'content' => '', 'plugin' => 'menus', 'module' => 'admin/todo', 'config' => '', 'theme_id' => 0, 'position_id' => 1, 'group_id' => 1, 'ordering' => 3, 'admin' => 1, 'active' => 1, 'show_heading' => 0, 'core' => 1, 'author' => 'Infinitas', 'licence' => 'MIT', 'url' => 'http://infinitas-cms.org', 'update_url' => '', 'created' => '2010-09-10 15:40:06', 'modified' => '2010-09-16 14:09:45' ), array( 'id' => 13, 'name' => 'Frontend Menu', 'content' => '', 'plugin' => 'menus', 'module' => 'main_menu', 'config' => '{\\\"menu\\\":\\\"main_menu\\\"}', 'theme_id' => 0, 'position_id' => 1, 'group_id' => 2, 'ordering' => 4, 'admin' => 0, 'active' => 1, 'show_heading' => 0, 'core' => 1, 'author' => 'Infinitas', 'licence' => 'MIT', 'url' => 'http://infinitas-cms.org', 'update_url' => '', 'created' => '2010-02-01 00:57:01', 'modified' => '2010-09-16 16:03:36' ), array( 'id' => 27, 'name' => 'Admin Dashboard Icons', 'content' => '', 'plugin' => 'menus', 'module' => 'admin/dashboard_icons', 'config' => '', 'theme_id' => 0, 'position_id' => 8, 'group_id' => 1, 'ordering' => 1, 'admin' => 1, 'active' => 1, 'show_heading' => 0, 'core' => 1, 'author' => 'Infinitas', 'licence' => '&copy; MIT', 'url' => 'http://infinitas-cms.org', 'update_url' => '', 'created' => '2010-09-11 17:32:33', 'modified' => '2010-09-16 14:09:45' ), array( 'id' => 29, 'name' => 'Overall Stats', 'content' => '', 'plugin' => 'view_counter', 'module' => 'admin/overall', 'config' => '', 'theme_id' => 0, 'position_id' => 8, 'group_id' => 1, 'ordering' => 2, 'admin' => 1, 'active' => 1, 'show_heading' => 0, 'core' => 1, 'author' => 'Infinitas', 'licence' => '&copy; MIT', 'url' => 'http://infinitas-cms.org', 'update_url' => '', 'created' => '2010-09-12 21:45:32', 'modified' => '2010-09-16 14:09:45' ), array( 'id' => 28, 'name' => 'View Counter Stats', 'content' => '', 'plugin' => 'view_counter', 'module' => 'admin/popular_items', 'config' => '', 'theme_id' => 0, 'position_id' => 8, 'group_id' => 1, 'ordering' => 3, 'admin' => 1, 'active' => 1, 'show_heading' => 0, 'core' => 0, 'author' => 'Infinitas', 'licence' => '&copy; MIT', 'url' => 'http://infinitas-cms.org', 'update_url' => '', 'created' => '2010-09-11 18:00:14', 'modified' => '2010-09-16 14:09:45' ), ), 'ModulesRoute' => array( array( 'id' => 65, 'module_id' => 25, 'route_id' => 0 ), array( 'id' => 66, 'module_id' => 12, 'route_id' => 0 ), array( 'id' => 67, 'module_id' => 26, 'route_id' => 0 ), array( 'id' => 69, 'module_id' => 27, 'route_id' => 9 ), array( 'id' => 71, 'module_id' => 28, 'route_id' => 9 ), array( 'id' => 72, 'module_id' => 29, 'route_id' => 9 ), array( 'id' => 74, 'module_id' => 13, 'route_id' => 0 ), array( 'id' => 76, 'module_id' => 30, 'route_id' => 0 ), ), 'ModulePosition' => array( array( 'id' => 1, 'name' => 'top', 'created' => '2010-01-18 21:45:23', 'modified' => '2010-01-18 21:45:23', 'module_count' => 4 ), array( 'id' => 2, 'name' => 'bottom', 'created' => '2010-01-18 21:45:23', 'modified' => '2010-01-18 21:45:23', 'module_count' => 3 ), array( 'id' => 3, 'name' => 'left', 'created' => '2010-01-18 21:45:23', 'modified' => '2010-01-18 21:45:23', 'module_count' => 0 ), array( 'id' => 4, 'name' => 'right', 'created' => '2010-01-18 21:45:23', 'modified' => '2010-01-18 21:45:23', 'module_count' => 0 ), array( 'id' => 5, 'name' => 'custom1', 'created' => '2010-01-18 21:45:23', 'modified' => '2010-01-18 21:45:23', 'module_count' => 0 ), array( 'id' => 6, 'name' => 'custom2', 'created' => '2010-01-18 21:45:23', 'modified' => '2010-01-18 21:45:23', 'module_count' => 1 ), array( 'id' => 7, 'name' => 'custom3', 'created' => '2010-01-18 21:45:23', 'modified' => '2010-01-18 21:45:23', 'module_count' => 2 ), array( 'id' => 8, 'name' => 'custom4', 'created' => '2010-01-18 21:45:23', 'modified' => '2010-01-18 21:45:23', 'module_count' => 0 ), array( 'id' => 9, 'name' => 'bread_crumbs', 'created' => '2010-01-18 21:45:23', 'modified' => '2010-01-18 21:45:23', 'module_count' => 0 ), array( 'id' => 10, 'name' => 'debug', 'created' => '2010-01-18 21:45:23', 'modified' => '2010-01-18 21:45:23', 'module_count' => 0 ), array( 'id' => 11, 'name' => 'feeds', 'created' => '2010-01-18 21:45:23', 'modified' => '2010-01-18 21:45:23', 'module_count' => 0 ), array( 'id' => 12, 'name' => 'search', 'created' => '2010-01-18 21:45:23', 'modified' => '2010-01-18 21:45:23', 'module_count' => 0 ), array( 'id' => 13, 'name' => 'hidden', 'created' => '2010-03-05 18:33:20', 'modified' => '2010-03-05 18:33:20', 'module_count' => 0 ), ), ), ); /** * Before migration callback * * @param string $direction, up or down direction of migration process * @return boolean Should process continue * @access public */ public function before($direction) { return true; } /** * After migration callback * * @param string $direction, up or down direction of migration process * @return boolean Should process continue * @access public */ public function after($direction) { return true; } } ?><file_sep><?php /** * Comment Template. * * @todo Implement .this needs to be sorted out. * * Copyright (c) 2009 <NAME> ( dogmatic69 ) * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. * @filesource * @copyright Copyright (c) 2009 <NAME> ( dogmatic69 ) * @link http://infinitas-cms.org * @package sort * @subpackage sort.comments * @license http://www.opensource.org/licenses/mit-license.php The MIT License * @since 0.5a */ class Template extends NewsletterAppModel { public $name = 'Template'; public $lockable = true; public $order = array( 'Template.name' => 'asc' ); public $hasMany = array( 'Newsletter.Newsletter', 'Newsletter.Campaign' ); public function __construct($id = false, $table = null, $ds = null) { parent::__construct($id, $table, $ds); $this->validate = array( 'name' => array( 'notEmpty' => array( 'rule' => 'notEmpty', 'message' => 'Please enter the name for this template' ), 'isUnique' => array( 'rule' => 'isUnique', 'message' => 'A template with that name already exists' ) ) ); } function getTemplate($data = null){ if($data){ $template = $this->find( 'first', array( 'conditions' => array( 'or' => array( 'Template.id' => $data, 'Template.name' => $data ) ) ) ); if(!empty($template)){ return $template; } } return $this->find( 'first', array( 'conditions' => array( 'Template.name' => Configure::read('Newsletter.template') ) ) ); } }<file_sep><?php class MailSystem extends EmailsAppModel{ public $name = 'MailSystem'; /** * database configuration to use * * @var string */ public $useDbConfig = 'emails'; /** * Behaviors to attach * * @var mixed */ public $actsAs = false; /** * database table to use * * @var string */ public $useTable = false; /** * The details of the server to connect to * @var array */ public $server = array(); /** * Test a connection * * Validation method before saving an email account. */ public function testConnection($details){ $this->server = $details; return $this->find('count'); } public function checkNewMail($account){ $mails = $this->find( 'all', array( 'conditions' => Set::flatten(array($this->alias => $account)) ) ); // @todo save to the db here // @todo delete messages from server here return $mails; } } <file_sep><?php /** * Management Config admin edit post. * * this page is for admin to manage the setup of the site * * Copyright (c) 2009 <NAME> ( dogmatic69 ) * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. * * @filesource * @copyright Copyright (c) 2009 <NAME> ( dogmatic69 ) * @link http://infinitas-cms.org * @package management * @subpackage management.views.configs.admin_edit * @license http://www.opensource.org/licenses/mit-license.php The MIT License */ echo $this->Form->create('Theme'); echo $this->Infinitas->adminEditHead(); ?> <fieldset> <h1><?php echo __('Theme', true); ?></h1><?php echo $this->Form->input('id'); echo $this->Form->input('name', array('options' => $themes, 'type' => 'select', 'empty' => Configure::read('Website.empty_select'))); echo $this->Form->input('active'); ?> </fieldset> <fieldset> <h1><?php echo __('Author', true); ?></h1><?php echo $this->Form->input('author'); echo $this->Form->input('url'); echo $this->Form->input('update_url'); echo $this->Form->input('licence'); echo $this->Infinitas->wysiwyg('Theme.description'); ?> </fieldset> <?php echo $this->Form->end(); ?><file_sep><?php /* NewsletterCampaign Fixture generated on: 2010-08-17 14:08:11 : 1282055171 */ class CampaignFixture extends CakeTestFixture { var $name = 'Campaign'; var $table = 'newsletter_campaigns'; var $fields = array( 'id' => array('type' => 'integer', 'null' => false, 'default' => NULL, 'length' => 10, 'key' => 'primary'), 'name' => array('type' => 'string', 'null' => false, 'default' => NULL, 'length' => 50), 'description' => array('type' => 'text', 'null' => false, 'default' => NULL), 'active' => array('type' => 'boolean', 'null' => false, 'default' => '1'), 'newsletter_count' => array('type' => 'integer', 'null' => false, 'default' => '0'), 'template_id' => array('type' => 'integer', 'null' => false, 'default' => NULL), 'locked' => array('type' => 'boolean', 'null' => false, 'default' => '0'), 'locked_by' => array('type' => 'integer', 'null' => true, 'default' => NULL), 'locked_since' => array('type' => 'datetime', 'null' => true, 'default' => NULL), 'created' => array('type' => 'datetime', 'null' => true, 'default' => NULL), 'modified' => array('type' => 'datetime', 'null' => true, 'default' => NULL), 'deleted' => array('type' => 'integer', 'null' => false, 'default' => NULL, 'length' => 1), 'deleted_date' => array('type' => 'datetime', 'null' => true, 'default' => NULL), 'indexes' => array('PRIMARY' => array('column' => 'id', 'unique' => 1)), 'tableParameters' => array('charset' => 'utf8', 'collate' => 'utf8_general_ci', 'engine' => 'InnoDB') ); var $records = array( array( 'id' => 3, 'name' => '436', 'description' => '34563456546', 'active' => 0, 'newsletter_count' => 2, 'template_id' => 1, 'locked' => 0, 'locked_by' => 0, 'locked_since' => '0000-00-00 00:00:00', 'created' => '2009-12-12 12:47:53', 'modified' => '2009-12-21 16:28:38', 'deleted' => 0, 'deleted_date' => '0000-00-00 00:00:00' ), array( 'id' => 6, 'name' => '23423', 'description' => '23423', 'active' => 1, 'newsletter_count' => 1, 'template_id' => 1, 'locked' => 0, 'locked_by' => 0, 'locked_since' => '0000-00-00 00:00:00', 'created' => '2010-01-04 09:23:38', 'modified' => '2010-01-04 09:23:57', 'deleted' => 0, 'deleted_date' => '0000-00-00 00:00:00' ), array( 'id' => 7, 'name' => 'asdf', 'description' => '<p>\r\n sadfsdaf</p>\r\n', 'active' => 1, 'newsletter_count' => 0, 'template_id' => 1, 'locked' => 0, 'locked_by' => 0, 'locked_since' => '0000-00-00 00:00:00', 'created' => '2010-05-14 15:39:18', 'modified' => '2010-05-14 15:39:18', 'deleted' => 0, 'deleted_date' => '0000-00-00 00:00:00' ), ); } ?><file_sep><?php /** * @brief ConfigsAppModel is the main model class that all other configuration models * extend. * * The configs extends the CoreAppModel to inherit the prefix core_ so that * it does not need to be defined all around the code. * * @copyright Copyright (c) 2010 <NAME> ( dogmatic69 ) * @link http://www.infinitas-cms.org * @package Infinitas.Configs * @license http://www.opensource.org/licenses/mit-license.php The MIT License * @since 0.5a * * @author dogmatic69 * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. */ class ConfigsAppModel extends CoreAppModel{ }<file_sep><?php Class IpLocation extends Object{ private $__emptyCountry = array('country' => false, 'country_code' => false); private $__emptyCity = array('country' => false, 'country_code' => false); public function __construct(){ $this->countryDataFile = dirname(dirname(__FILE__)).DS.'libs'.DS.'geoip'.DS.'country.dat'; $this->cityDataFile = dirname(dirname(__FILE__)).DS.'libs'.DS.'geoip'.DS.'city.dat'; } private function __loadFile($type = 'country'){ $type = strtolower((string)$type); App::import('Lib', 'GeoLocation.Geoip/inc.php'); switch($type){ case 'country': if(!is_file($this->countryDataFile)){ trigger_error(sprintf(__('%s data file is missing', true), $type), E_USER_WARNING); return false; } return geoip_open($this->countryDataFile, GEOIP_STANDARD); break; case 'city': App::import('Lib', 'GeoLocation.Geoip/city.php'); App::import('Lib', 'GeoLocation.Geoip/region_vars.php'); if(!is_file($this->cityDataFile)){ trigger_error(sprintf(__('%s data file is missing', true), $type), E_USER_WARNING); return false; } return geoip_open($this->cityDataFile, GEOIP_STANDARD); break; default: trigger_error(sprintf(__('%s is not a valid data file', true), $type), E_USER_WARNING); return false; break; } } private function __getIpAddress(){ App::import('Component', 'RequestHandler'); $RequestHandler = new RequestHandlerComponent(); $ipAddress = $RequestHandler->getClientIP(); unset($RequestHandler); return $ipAddress; } /** * Find users country. * * Attempt to get the country the user is from. returns unknown if its not * able to match something. * * @param string $ipAddress the ip address to check against * @param bool $code get the country code or not * * @return array the data requested */ public function getCountryData($ipAddress = null, $code = false){ if (!$ipAddress){ $ipAddress = $this->__getIpAddress(); } $data = $this->__loadFile(); if(!$data){ return $this->__emptyCountry; } $return = array( 'country' => geoip_country_name_by_addr($data, $ipAddress), 'country_code' => geoip_country_code_by_addr($data, $ipAddress), 'country_id' => geoip_country_id_by_addr($data, $ipAddress), 'city' => null, 'ip_address' => $ipAddress ); geoip_close($data); unset($data); return $return; } /** * Find users country. * * Attempt to get the country the user is from. returns unknown if its not * able to match something. * * @param string $ipAddress the ip address to check against * @param bool $code get the country code or not * * @return array the data requested */ public function getCityData($ipAddress = null, $fields = array()){ if (!$ipAddress){ $ipAddress = $this->__getIpAddress(); } $data = $this->__loadFile('city'); if(!$data){ return false; } $city = (array)geoip_record_by_addr($data, $ipAddress); if(!empty($city)){ $city['country'] = $city['country_name']; unset($city['country_name']); $city['ip_address'] = $ipAddress; } geoip_close($data); unset($data); return (array)$city; } }<file_sep><?php /** * Comment Template. * * @todo Implement .this needs to be sorted out. * * Copyright (c) 2009 <NAME> ( dogmatic69 ) * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. * @filesource * @copyright Copyright (c) 2009 <NAME> ( dogmatic69 ) * @link http://infinitas-cms.org * @package sort * @subpackage sort.comments * @license http://www.opensource.org/licenses/mit-license.php The MIT License * @since 0.5a */ class RoutesController extends RoutesAppController{ public $name = 'Routes'; public $listThemes = array(0 => 'Default'); public function beforeFilter() { parent::beforeFilter(); $this->listThemes = array( 0 => __('Default', true) ) + $this->Route->Theme->find('list'); } public function admin_index() { $this->paginate = array( 'contain' => array( 'Theme' ) ); $routes = $this->paginate(null, $this->Filter->filter); $filterOptions = $this->Filter->filterOptions; $filterOptions['fields'] = array( 'name', 'url', 'plugin' => $this->Route->getPlugins(), 'theme_id' => array(null => __('All', true)) + $this->Route->Theme->find('list'), 'active' => Configure::read('CORE.active_options') ); $this->set(compact('routes', 'filterOptions')); } public function admin_add() { parent::admin_add(); $this->set('plugins', $this->Route->getPlugins()); $this->set('themes', $this->listThemes); } public function admin_edit($id = null) { parent::admin_edit($id); $plugins = $this->Route->getPlugins(); $controllers = $this->Route->getControllers($this->data['Route']['plugin']); $actions = $this->Route->getActions($this->data['Route']['plugin'], $this->data['Route']['controller']); $themes = $this->listThemes; $this->set(compact('plugins', 'controllers', 'actions', 'themes')); } }<file_sep><?php /* CoreModulePosition Fixture generated on: 2010-03-13 11:03:31 : 1268472511 */ class ModulePositionFixture extends CakeTestFixture { var $name = 'ModulePosition'; var $table = 'core_module_positions'; var $fields = array( 'id' => array('type' => 'integer', 'null' => false, 'default' => NULL, 'length' => 10, 'key' => 'primary'), 'name' => array('type' => 'string', 'null' => false, 'default' => NULL, 'length' => 50), 'created' => array('type' => 'datetime', 'null' => true, 'default' => NULL), 'modified' => array('type' => 'datetime', 'null' => true, 'default' => NULL), 'indexes' => array('PRIMARY' => array('column' => 'id', 'unique' => 1)), 'tableParameters' => array('charset' => 'utf8', 'collate' => 'utf8_general_ci', 'engine' => 'InnoDB') ); var $records = array( array( 'id' => 1, 'name' => 'top', 'created' => '2010-01-18 21:45:23', 'modified' => '2010-01-18 21:45:23' ), array( 'id' => 2, 'name' => 'bottom', 'created' => '2010-01-18 21:45:23', 'modified' => '2010-01-18 21:45:23' ), array( 'id' => 3, 'name' => 'left', 'created' => '2010-01-18 21:45:23', 'modified' => '2010-01-18 21:45:23' ), array( 'id' => 4, 'name' => 'right', 'created' => '2010-01-18 21:45:23', 'modified' => '2010-01-18 21:45:23' ), array( 'id' => 5, 'name' => 'custom1', 'created' => '2010-01-18 21:45:23', 'modified' => '2010-01-18 21:45:23' ), array( 'id' => 6, 'name' => 'custom2', 'created' => '2010-01-18 21:45:23', 'modified' => '2010-01-18 21:45:23' ), array( 'id' => 7, 'name' => 'custom3', 'created' => '2010-01-18 21:45:23', 'modified' => '2010-01-18 21:45:23' ), array( 'id' => 8, 'name' => 'custom4', 'created' => '2010-01-18 21:45:23', 'modified' => '2010-01-18 21:45:23' ), array( 'id' => 9, 'name' => 'bread_crumbs', 'created' => '2010-01-18 21:45:23', 'modified' => '2010-01-18 21:45:23' ), array( 'id' => 10, 'name' => 'debug', 'created' => '2010-01-18 21:45:23', 'modified' => '2010-01-18 21:45:23' ), array( 'id' => 11, 'name' => 'hidden', 'created' => '2010-01-18 21:45:23', 'modified' => '2010-01-18 21:45:23' ), ); }<file_sep><?php /** * @brief ContentsEvents plugin events. * * The events for the Contents plugin for setting up cache and the general * configuration of the plugin. * * @copyright Copyright (c) 2010 <NAME> ( dogmatic69 ) * @link http://www.infinitas-cms.org * @package Infinitas.Contents * @license http://www.opensource.org/licenses/mit-license.php The MIT License * @since 0.8a * * @author dogmatic69 * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. */ final class ContentsEvents extends AppEvents{ public function onAdminMenu($event){ $menu['main'] = array( 'Contents' => array('plugin' => 'contents', 'controller' => 'global_contents', 'action' => 'index'), 'Layouts' => array('plugin' => 'contents', 'controller' => 'global_layouts', 'action' => 'index'), ); return $menu; } public function onAttachBehaviors($event) { if(is_subclass_of($event->Handler, 'Model') && isset($event->Handler->_schema) && is_array($event->Handler->_schema)) { if (isset($event->Handler->contentable) && $event->Handler->contentable && !$event->Handler->Behaviors->enabled('Contents.Contentable')) { $event->Handler->Behaviors->attach('Contents.Contentable'); } } } }<file_sep><?php /* Comment Test cases generated on: 2010-12-14 02:12:15 : 1292293635*/ App::import('model', 'Comments.Comment'); class CommentTestCase extends CakeTestCase { var $fixtures = array( 'plugin.configs.config', 'plugin.themes.theme', 'plugin.routes.route', 'plugin.view_counter.view_count', 'plugin.comments.comment', 'plugin.comments.comment_attribute' ); function startTest() { $this->Comment = ClassRegistry::init('Comments.Comment'); } function endTest() { unset($this->Comment); ClassRegistry::flush(); } function testStuff(){ $this->assertIsA($this->Comment, 'Comment'); } }<file_sep><?php /* * Short Description / title. * * Overview of what the file does. About a paragraph or two * * Copyright (c) 2010 <NAME> ( dogmatic69 ) * * @filesource * @copyright Copyright (c) 2010 <NAME> ( dogmatic69 ) * @link http://www.infinitas-cms.org * @package {see_below} * @subpackage {see_below} * @license http://www.opensource.org/licenses/mit-license.php The MIT License * @since {check_current_milestone_in_lighthouse} * * @author {your_name} * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. */ final class GoogleEvents extends AppEvents { public function onRequireHelpersToLoad(){ return array( 'Google.Chart' ); } } <file_sep><?php App::import('Behavior', 'Upload.Upload'); class TestUpload extends CakeTestModel { var $useTable = 'uploads'; var $actsAs = array( 'Upload.Upload' => array( 'photo' ) ); } class UploadBehaviorTest extends CakeTestCase { var $fixtures = array('plugin.upload.upload'); var $TestUpload = null; var $data = array(); function startTest() { $this->TestUpload = ClassRegistry::init('TestUpload'); $this->data['test_ok'] = array( 'photo' => array( 'tmp_name' => 'Photo.png', 'dir' => '/tmp/php/file.tmp', 'type' => 'image/png', 'size' => 8192, 'error' => UPLOAD_ERR_OK, ) ); } function endTest() { Classregistry::flush(); unset($this->TestUpload); } function testIsUnderPhpSizeLimit() { $this->TestUpload->validate = array( 'photo' => array( 'isUnderPhpSizeLimit' => array( 'rule' => 'isUnderPhpSizeLimit', 'message' => 'isUnderPhpSizeLimit' ), ) ); $data = array( 'photo' => array( 'tmp_name' => 'Photo.png', 'dir' => '/tmp/php/file.tmp', 'type' => 'image/png', 'size' => 8192, 'error' => UPLOAD_ERR_INI_SIZE, ) ); $this->TestUpload->set($data); $this->assertFalse($this->TestUpload->validates()); $this->assertEqual(1, count($this->TestUpload->validationErrors)); $this->assertEqual('isUnderPhpSizeLimit', current($this->TestUpload->validationErrors)); $this->TestUpload->set($this->data['test_ok']); $this->assertTrue($this->TestUpload->validates()); $this->assertEqual(0, count($this->TestUpload->validationErrors)); } function testIsUnderFormSizeLimit() { $this->TestUpload->validate = array( 'photo' => array( 'isUnderFormSizeLimit' => array( 'rule' => 'isUnderFormSizeLimit', 'message' => 'isUnderFormSizeLimit' ), ) ); $data = array( 'photo' => array( 'tmp_name' => 'Photo.png', 'dir' => '/tmp/php/file.tmp', 'type' => 'image/png', 'size' => 8192, 'error' => UPLOAD_ERR_FORM_SIZE, ) ); $this->TestUpload->set($data); $this->assertFalse($this->TestUpload->validates()); $this->assertEqual(1, count($this->TestUpload->validationErrors)); $this->assertEqual('isUnderFormSizeLimit', current($this->TestUpload->validationErrors)); $this->TestUpload->set($this->data['test_ok']); $this->assertTrue($this->TestUpload->validates()); $this->assertEqual(0, count($this->TestUpload->validationErrors)); } function testIsCompletedUpload() { $this->TestUpload->validate = array( 'photo' => array( 'isCompletedUpload' => array( 'rule' => 'isCompletedUpload', 'message' => 'isCompletedUpload' ), ) ); $data = array( 'photo' => array( 'tmp_name' => 'Photo.png', 'dir' => '/tmp/php/file.tmp', 'type' => 'image/png', 'size' => 8192, 'error' => UPLOAD_ERR_PARTIAL, ) ); $this->TestUpload->set($data); $this->assertFalse($this->TestUpload->validates()); $this->assertEqual(1, count($this->TestUpload->validationErrors)); $this->assertEqual('isCompletedUpload', current($this->TestUpload->validationErrors)); $this->TestUpload->set($this->data['test_ok']); $this->assertTrue($this->TestUpload->validates()); $this->assertEqual(0, count($this->TestUpload->validationErrors)); } function testIsFileUpload() { $this->TestUpload->validate = array( 'photo' => array( 'isFileUpload' => array( 'rule' => 'isFileUpload', 'message' => 'isFileUpload' ), ) ); $data = array( 'photo' => array( 'tmp_name' => 'Photo.png', 'dir' => '/tmp/php/file.tmp', 'type' => 'image/png', 'size' => 8192, 'error' => UPLOAD_ERR_NO_FILE, ) ); $this->TestUpload->set($data); $this->assertFalse($this->TestUpload->validates()); $this->assertEqual(1, count($this->TestUpload->validationErrors)); $this->assertEqual('isFileUpload', current($this->TestUpload->validationErrors)); $this->TestUpload->set($this->data['test_ok']); $this->assertTrue($this->TestUpload->validates()); $this->assertEqual(0, count($this->TestUpload->validationErrors)); } function testTempDirExists() { $this->TestUpload->validate = array( 'photo' => array( 'tempDirExists' => array( 'rule' => 'tempDirExists', 'message' => 'tempDirExists' ), ) ); $data = array( 'photo' => array( 'tmp_name' => 'Photo.png', 'dir' => '/tmp/php/file.tmp', 'type' => 'image/png', 'size' => 8192, 'error' => UPLOAD_ERR_NO_TMP_DIR, ) ); $this->TestUpload->set($data); $this->assertFalse($this->TestUpload->validates()); $this->assertEqual(1, count($this->TestUpload->validationErrors)); $this->assertEqual('tempDirExists', current($this->TestUpload->validationErrors)); $this->TestUpload->set($this->data['test_ok']); $this->assertTrue($this->TestUpload->validates()); $this->assertEqual(0, count($this->TestUpload->validationErrors)); } function testIsSuccessfulWrite() { $this->TestUpload->validate = array( 'photo' => array( 'isSuccessfulWrite' => array( 'rule' => 'isSuccessfulWrite', 'message' => 'isSuccessfulWrite' ), ) ); $data = array( 'photo' => array( 'tmp_name' => 'Photo.png', 'dir' => '/tmp/php/file.tmp', 'type' => 'image/png', 'size' => 8192, 'error' => UPLOAD_ERR_CANT_WRITE, ) ); $this->TestUpload->set($data); $this->assertFalse($this->TestUpload->validates()); $this->assertEqual(1, count($this->TestUpload->validationErrors)); $this->assertEqual('isSuccessfulWrite', current($this->TestUpload->validationErrors)); $this->TestUpload->set($this->data['test_ok']); $this->assertTrue($this->TestUpload->validates()); $this->assertEqual(0, count($this->TestUpload->validationErrors)); } function testNoPhpExtensionErrors() { $this->TestUpload->validate = array( 'photo' => array( 'noPhpExtensionErrors' => array( 'rule' => 'noPhpExtensionErrors', 'message' => 'noPhpExtensionErrors' ), ) ); $data = array( 'photo' => array( 'tmp_name' => 'Photo.png', 'dir' => '/tmp/php/file.tmp', 'type' => 'image/png', 'size' => 8192, 'error' => UPLOAD_ERR_EXTENSION, ) ); $this->TestUpload->set($data); $this->assertFalse($this->TestUpload->validates()); $this->assertEqual(1, count($this->TestUpload->validationErrors)); $this->assertEqual('noPhpExtensionErrors', current($this->TestUpload->validationErrors)); $this->TestUpload->set($this->data['test_ok']); $this->assertTrue($this->TestUpload->validates()); $this->assertEqual(0, count($this->TestUpload->validationErrors)); } function testIsValidMimeType() { $this->TestUpload->Behaviors->detach('Upload.Upload'); $this->TestUpload->Behaviors->attach('Upload.Upload', array( 'photo' => array( 'mimetypes' => array('image/bmp', 'image/jpeg') ) )); $this->TestUpload->validate = array( 'photo' => array( 'isValidMimeType' => array( 'rule' => 'isValidMimeType', 'message' => 'isValidMimeType' ), ) ); $this->TestUpload->set($this->data['test_ok']); $this->assertFalse($this->TestUpload->validates()); $this->assertEqual(1, count($this->TestUpload->validationErrors)); $this->assertEqual('isValidMimeType', current($this->TestUpload->validationErrors)); $this->TestUpload->Behaviors->detach('Upload.Upload'); $this->TestUpload->Behaviors->attach('Upload.Upload', array( 'photo' => array( 'mimetypes' => array('image/png', 'image/jpeg') ) )); $this->TestUpload->set($this->data['test_ok']); $this->assertTrue($this->TestUpload->validates()); $this->assertEqual(0, count($this->TestUpload->validationErrors)); } function testIsValidExtension() { $this->TestUpload->Behaviors->detach('Upload.Upload'); $this->TestUpload->Behaviors->attach('Upload.Upload', array( 'photo' => array( 'extensions' => array('jpeg', 'bmp') ) )); $this->TestUpload->validate = array( 'photo' => array( 'isValidExtension' => array( 'rule' => 'isValidExtension', 'message' => 'isValidExtension' ), ) ); $data = array( 'photo' => array( 'tmp_name' => 'Photo.png', 'dir' => '/tmp/php/file.tmp', 'type' => 'image/png', 'size' => 8192, 'error' => UPLOAD_ERR_OK, ) ); $this->TestUpload->set($data); $this->assertFalse($this->TestUpload->validates()); $this->assertEqual(1, count($this->TestUpload->validationErrors)); $this->assertEqual('isValidExtension', current($this->TestUpload->validationErrors)); $data = array( 'photo' => array( 'tmp_name' => 'Photo.bmp', 'dir' => '/tmp/php/file.tmp', 'type' => 'image/bmp', 'size' => 8192, 'error' => UPLOAD_ERR_OK, ) ); $this->TestUpload->set($data); $this->assertTrue($this->TestUpload->validates()); $this->assertEqual(0, count($this->TestUpload->validationErrors)); } function testIsWritable() { $this->TestUpload->validate = array( 'photo' => array( 'isWritable' => array( 'rule' => 'isWritable', 'message' => 'isWritable' ), ) ); $data = array( 'photo' => array( 'tmp_name' => 'Photo.png', 'dir' => '/tmp/php/file.tmp', 'type' => 'image/png', 'size' => 8192, 'error' => UPLOAD_ERR_OK, ) ); $this->TestUpload->set($data); $this->assertFalse($this->TestUpload->validates()); $this->assertEqual(1, count($this->TestUpload->validationErrors)); $this->assertEqual('isWritable', current($this->TestUpload->validationErrors)); $this->TestUpload->Behaviors->detach('Upload.Upload'); $this->TestUpload->Behaviors->attach('Upload.Upload', array( 'photo' => array( 'path' => TMP ) )); $data = array( 'photo' => array( 'tmp_name' => 'Photo.bmp', 'dir' => '/tmp/php/file.tmp', 'type' => 'image/bmp', 'size' => 8192, 'error' => UPLOAD_ERR_OK, ) ); $this->TestUpload->set($data); $this->assertTrue($this->TestUpload->validates()); $this->assertEqual(0, count($this->TestUpload->validationErrors)); } function testIsValidDir() { $this->TestUpload->validate = array( 'photo' => array( 'isValidDir' => array( 'rule' => 'isValidDir', 'message' => 'isValidDir' ), ) ); $data = array( 'photo' => array( 'tmp_name' => 'Photo.png', 'dir' => '/tmp/php/file.tmp', 'type' => 'image/png', 'size' => 8192, 'error' => UPLOAD_ERR_OK, ) ); $this->TestUpload->set($data); $this->assertFalse($this->TestUpload->validates()); $this->assertEqual(1, count($this->TestUpload->validationErrors)); $this->assertEqual('isValidDir', current($this->TestUpload->validationErrors)); $this->TestUpload->Behaviors->detach('Upload.Upload'); $this->TestUpload->Behaviors->attach('Upload.Upload', array( 'photo' => array( 'path' => TMP ) )); $data = array( 'photo' => array( 'tmp_name' => 'Photo.bmp', 'dir' => '/tmp/php/file.tmp', 'type' => 'image/bmp', 'size' => 8192, 'error' => UPLOAD_ERR_OK, ) ); $this->TestUpload->set($data); $this->assertTrue($this->TestUpload->validates()); $this->assertEqual(0, count($this->TestUpload->validationErrors)); } function testIsImage() { $this->TestUpload->Behaviors->detach('Upload.Upload'); $this->TestUpload->Behaviors->attach('Upload.Upload', array( 'photo' => array( 'mimetypes' => array('image/bmp', 'image/jpeg') ) )); $result = $this->TestUpload->Behaviors->Upload->_isImage($this->TestUpload, 'image/bmp'); $this->assertTrue($result); $result = $this->TestUpload->Behaviors->Upload->_isImage($this->TestUpload, 'image/jpeg'); $this->assertTrue($result); $result = $this->TestUpload->Behaviors->Upload->_isImage($this->TestUpload, 'application/zip'); $this->assertFalse($result); } function testGetPathRandom() { $result = $this->TestUpload->Behaviors->Upload->_getPathRandom('string', TMP); $this->assertIsA($result, 'String'); $this->assertEqual(9, strlen($result)); $this->assertTrue(is_dir(TMP . DIRECTORY_SEPARATOR . $result)); } function testReplacePath() { $result = $this->TestUpload->Behaviors->Upload->_path($this->TestUpload, 'photo', 'webroot{DS}files/{model}\\{field}{DS}'); $this->assertIsA($result, 'String'); $this->assertEqual('webroot/files/test_upload/photo/', $result); } function testPrepareFilesForDeletion() { $this->TestUpload->Behaviors->detach('Upload.Upload'); $this->TestUpload->Behaviors->attach('Upload.Upload', array( 'photo' => array( 'thumbsizes' => array( 'xvga' => '1024x768', 'vga' => '640x480', 'thumb' => '80x80' ), 'fields' => array( 'dir' => 'dir' ) ) )); $result = $this->TestUpload->Behaviors->Upload->_prepareFilesForDeletion( $this->TestUpload, 'photo', array('TestUpload' => array('dir' => '1/', 'photo' => 'Photo.png')), $this->TestUpload->Behaviors->Upload->settings['TestUpload']['photo'] ); $this->assertIsA($result, 'Array'); $this->assertEqual(1,count($result)); $this->assertEqual(4, count($result['TestUpload'])); } }<file_sep><?php class Rating extends CoreAppModel { } ?> <file_sep><?php final class TrashEvents extends AppEvents{ public function onAttachBehaviors($event) { if(is_subclass_of($event->Handler, 'Model') && isset($event->Handler->_schema) && is_array($event->Handler->_schema)) { $noTrashModels = array( 'Session', 'SchemaMigration', 'Config', 'Aco', 'Aro', 'Trash' ); if (!in_array($event->Handler->name, $noTrashModels) && !isset($event->Handler->noTrash) && !$event->Handler->Behaviors->enabled('Trash.Trashable')) { $event->Handler->Behaviors->attach('Trash.Trashable'); } } } public function onAdminMenu($event){ $menu['main'] = array( 'Trash' => array('controller' => 'trash', 'action' => 'index') ); return $menu; } }<file_sep><?php /* * Short Description / title. * * Overview of what the file does. About a paragraph or two * * Copyright (c) 2010 <NAME> ( dogmatic69 ) * * @filesource * @copyright Copyright (c) 2010 <NAME> ( dogmatic69 ) * @link http://www.infinitas-cms.org * @package {see_below} * @subpackage {see_below} * @license http://www.opensource.org/licenses/mit-license.php The MIT License * @since {check_current_milestone_in_lighthouse} * * @author {your_name} * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. */ echo __('Join our mailing list', true); echo $this->Form->create('Newsletter', array('action' => 'subscribe')); echo $this->Form->input('email', array('value' => $this->Session->read('Auth.User.email'), 'label' => false)); echo $this->Form->submit('Go'); echo $this->Form->end(); <file_sep><?php class CronResourceTask extends Shell { public $memoryUsage = array( 'start' => array(), 'end' => array() ); public $verbose = false; protected $_memoryLog = array(); protected $_loadLog = array(); public function __construct(&$dispatch) { parent::__construct($dispatch); $this->lastTime = microtime(true); } /** * @brief overload log to show on the screen when needed and log files * * @see http://api13.cakephp.org/class/object#method-Objectlog * * @param string $message the message to log * * @return boolean Success of log write */ public function log($message){ if($this->verbose){ $this->out($message); } return parent::log($message, 'cron_jobs'); } /** * @brief overload the hr method so the logs are more readable */ public function hr(){ $this->log(''); $this->log('---------------------------------------------------------------'); $this->log(''); } /** * @brief Log the memory usage as we go along to make sure things dont get out of hand * * Eventually if something is hogging to much memory it will (should) be * stopped so that the server is not hogged. * * @access public * * @return float the average memory usage */ public function logMemoryUsage($doing = 'running', $prefix = ''){ $memoryUsage = memoryUsage(false); if(empty($this->memoryUsage['start'])){ $this->log( sprintf( "Memory %s %s %s %s %s %s", str_pad('Current:', 15, ' ', STR_PAD_RIGHT), str_pad('Max:', 15, ' ', STR_PAD_RIGHT), str_pad('Ave:', 15, ' ', STR_PAD_RIGHT), str_pad('Load:', 15, ' ', STR_PAD_RIGHT), str_pad('Taken:', 15, ' ', STR_PAD_RIGHT), str_pad('Doing:', 15, ' ', STR_PAD_RIGHT) ) ); $this->log("---------------------------------------------------------------------------------------------------------------"); $this->memoryUsage['start'] = $memoryUsage; } $this->_memoryLog[] = substr($memoryUsage['current'], 0, -3); $average = $this->averageMemoryUsage(); $load = $this->logServerLoad(); $taken = round(microtime(true) - $this->lastTime, 4); $this->log( sprintf( " %s %s %s %s %s %s", str_pad($memoryUsage['current'], 15, ' ', STR_PAD_RIGHT), str_pad($memoryUsage['max'], 15, ' ', STR_PAD_RIGHT), str_pad($average, 15, ' ', STR_PAD_RIGHT), str_pad($load, 15, ' ', STR_PAD_RIGHT), str_pad($taken, 15, ' ', STR_PAD_RIGHT), str_pad($doing, 15, ' ', STR_PAD_RIGHT) ) ); unset($memoryUsage); $this->lastTime = microtime(true); return array('memory' => $average, 'load' => $load); } /** * @brief Log the server load while crons are running * * @access public * * @return float the 1 min load average if found, -1 if not */ public function logServerLoad(){ $load = serverLoad(false); if(!isset($this->memoryUsage['start']['load'])){ $this->memoryUsage['start']['load'] = $load[0]; } $this->_loadLog[] = $load[0]; return $load[0]; } /** * @brief Get the current average memory usage */ public function averageMemoryUsage(){ return round(array_sum($this->_memoryLog) / count($this->_memoryLog), 3); } /** * @brief Get the current average memory usage */ public function averageLoad(){ return array_sum($this->_loadLog) / count($this->_loadLog); } /** * @brief Get the time elapsed since the start */ public function elapsedTime(){ return round(microtime(true) - $this->start, 3); } /** * @brief output some stats for the cron that just ran */ public function stats(){ if($this->verbose){ $this->log('Below are the stats for the run'); $this->hr(); } $memoryUsage = $totalMemoryUsed = null; $memoryUsage = memoryUsage(false); $totalMemoryUsed = round(substr($memoryUsage['current'], 0, -3) - substr($this->memoryUsage['start']['current'], 0, -3), 3); $this->log(sprintf('Total time taken :: %s sec', $this->elapsedTime())); $this->log(sprintf('Load max :: %s', max($this->_loadLog))); $this->log(sprintf('Load average :: %s', $this->averageLoad())); $this->log(sprintf('Memory max :: %s', $memoryUsage['max'])); $this->log(sprintf('Memory current :: %s', $memoryUsage['current'])); $this->log(sprintf('Memory average :: %s mb', $this->averageMemoryUsage())); $this->log(sprintf('Memory used :: %s mb', $totalMemoryUsed)); } } <file_sep><?php /** * Management Modules admin edit post. * * this page is for admin to manage the menu items on the site * * Copyright (c) 2009 <NAME> ( dogmatic69 ) * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. * * @filesource * @copyright Copyright (c) 2009 <NAME> ( dogmatic69 ) * @link http://infinitas-cms.org * @package management * @subpackage management.views.menuItems.admin_add * @license http://www.opensource.org/licenses/mit-license.php The MIT License */ echo $this->Form->create('EmailAccount'); echo $this->Infinitas->adminEditHead(); ?> <fieldset> <h1><?php echo __('Outgoing', true); ?></h1><?php echo $this->Form->input('id'); echo $this->Form->input('name'); echo $this->Form->input('host'); echo $this->Form->input('user_id', array('empty' => Configure::read('Website.empty_select'))); echo $this->Form->input('username', array('autocomplet' => false)); echo $this->Form->input('password', array('autocomplet' => false)); echo $this->Form->input('email'); ?> </fieldset> <fieldset> <h1><?php echo __('Configuration', true); ?></h1><?php echo $this->Form->input('system'); echo $this->Form->input('outgoing'); echo $this->Form->input('ssl'); echo $this->Form->input('cron');?> <div class="input select smaller"> <label for=""><?php echo __('Connection Type', true); ?></label><?php echo $this->Form->input('type', array('type' => 'select', 'class' => 'required', 'div' => false, 'label' => false, 'options' => $types, 'empty' => Configure::read('Website.empty_select'))); echo $this->Form->input('port'); echo $this->Form->input('readonly', array('options' => array(0 => 'Read and Write', 1 => 'Read only'), 'empty' => Configure::read('Website.empty_select'))); ?> </div> <?php $params = array( 'plugin' => 'assets', 'message' => __('The following is only a guide, please check your server as it may be different', true) ); echo $this->element('messages/warning', $params); ?> <table style="width: 300px; margin: auto;"> <tr><th><?php echo __('Port', true); ?></th><th><?php echo __('Use', true); ?></th></tr> <tr><td>110</td><td><?php echo __('Standard POP3 port / MMP POP3 Proxy', true); ?></td></tr> <tr><td>992</td><td><?php echo __('POP3 over SSL', true); ?></td></tr> <tr><td>143</td><td><?php echo __('Standard IMAP4 port / MMP IMAP Proxy', true); ?></td></tr> <tr><td>993</td><td><?php echo __('IMAP over SSL or MMP IMAP Proxy over SSL', true); ?></td></tr> <tr><td> 25</td><td><?php echo __('Standard SMTP port', true); ?></td></tr> <tr><td>465</td><td><?php echo __('Standard SMTP port', true); ?></td></tr> </table> </fieldset> <?php echo $this->Form->end(); ?><file_sep><?php $map = array( 1 => array( '000008_newsletter' => 'R4c94edceb66c49d38c8678d86318cd70'), ); ?><file_sep><?php $devIcons = array( array( 'name' => 'Status', 'description' => 'Check on the health of your setup', 'icon' => '/server_status/img/icon.png', 'author' => 'Infinitas', 'dashboard' => array('plugin' => 'server_status', 'controller' => 'server_status', 'action' => 'status'), ), array( 'name' => 'Php', 'description' => 'See and manage your Php configuration', 'icon' => '/server_status/img/php.png', 'author' => 'Infinitas', 'dashboard' => array('plugin' => 'server_status', 'controller' => 'php', 'action' => 'info'), ), array( 'name' => 'MySQL', 'description' => 'Information regarding the MySQL server currently running', 'icon' => '/server_status/img/mysql.png', 'author' => 'Infinitas', 'dashboard' => array('plugin' => 'server_status', 'controller' => 'databases', 'action' => 'mysql'), ) ); ?> <div class="dashboard grid_16"> <h1><?php echo __('Manage your server', true); ?></h1> <ul class="icons"><li><?php echo implode('</li><li>', current((array)$this->Menu->builDashboardLinks($devIcons, 'server_status'))); ?></li></ul> </div><file_sep><?php echo $this->Form->create('Config', array('action' => 'mass')); $massActions = $this->Infinitas->massActionButtons(array('add')); echo $this->Infinitas->adminIndexHead(null, $massActions); ?> <div class="table"> <h1 class="no-gap"> <?php echo __('Overloaded Values', true); ?> <small><?php __('Click a link below to edit / delete the overladed value'); ?></small> </h1> <table class="listing no-gap" cellpadding="0" cellspacing="0"> <?php echo $this->Infinitas->adminTableHeader( array( __('Key', true) => array( 'style' => 'width:200px;' ), __('Value', true) => array( 'style' => 'width:200px;' ) ) ); foreach ($overloaded as $key => $value){ unset($configs[$key]); ?> <tr class="<?php echo $this->Infinitas->rowClass(); ?>"> <td> <?php echo $this->Html->link( $key, array( 'action' => 'index', 'Config.key' => $key ) ); ?>&nbsp; </td> <td> <?php echo $value; ?>&nbsp; </td> </tr> <?php } ?> </table> <?php echo $this->Form->end(); ?> </div> <div class="table"> <h1 class="no-gap"> <?php echo __('Default Values', true); ?> <small><?php __('Click a link below to overload the config with new values'); ?></small> </h1> <table class="listing no-gap" cellpadding="0" cellspacing="0"> <?php echo $this->Infinitas->adminTableHeader( array( __('Key', true) => array( 'style' => 'width:200px;' ), __('Value', true) => array( 'style' => 'width:200px;' ) ) ); foreach ($configs as $key => $value){ ?> <tr class="<?php echo $this->Infinitas->rowClass(); ?>"> <td> <?php echo $this->Html->link( $key, array( 'action' => 'add', 'Config.key' => $key ) ); ?>&nbsp; </td> <td> <?php echo $value; ?>&nbsp; </td> </tr> <?php } ?> </table> <?php echo $this->Form->end(); ?> </div><file_sep><div class="dashboard"> <h1><?php printf(__('Private Method in %s', true), $controller); ?></h1> <p class="error"> <strong><?php __('Error'); ?>: </strong> <?php printf(__('%s%s cannot be accessed directly.', true), '<em>' . $controller . '::</em>', '<em>' . $action . '()</em>'); ?> </p> </div><file_sep><?php App::import('Lib', 'Libs.LazyModel'); /** * @page AppModel AppModel * * @section app_model-overview What is it * * AppModel is the main model class that all other models will eventually * extend. AppModel provides some methods through inheritance and also sets up * a few configurations that are used throughout the application. * * A lot of the code that is found here is to help make development simpler * but can easily be overloaded should you requre something a little bit * different. Take the cache clearing for example, the default is that after * a change in the database is detected any related cache will be deleted. Should * you want something else to happen just overload the method in your model * or the MyPluginAppModel. * * @section app_model-usage How to use it * * Usage is simple, extend your MyPluginAppModel from this class and then the * models in your plugin just extend MyPluginAppModel. Example below: * * @code * // in APP/plugins/my_plugin/my_plugin_app_model.php create * class MyPluginAppModel extends AppModel{ * // do not set the name in this model, there be gremlins * } * * // then in APP/plugins/my_plugin/models/something.php * class Something extends MyPluginAppModel{ * public $name = 'Something'; * //... * } * @endcode * * After that you will be able to directly access the public methods that * are available from this class as if they were in your model. * * @code * $this->someMethod(); * @endcode * * @section app_model-see-also Also see * @ref LazyModel * @ref InfinitasBehavior * @ref Event * @ref InfinitasBehavior */ /** * @brief main model class to extend * * AppModel is the base Model that all models should extend, unless you are * doing something completely different. * * @copyright Copyright (c) 2009 <NAME> ( dogmatic69 ) * @link http://infinitas-cms.org * @package Infinitas * @license http://www.opensource.org/licenses/mit-license.php The MIT License * @since 0.5a * * @author dogmatic69 * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. */ class AppModel extends LazyModel { /** * The database configuration to use for the site. * * @var string * @access public */ public $useDbConfig = 'default'; /** * @brief The prefix for the table this model is using * * This Should be the same throughout a plugin, and should be the same * as the plugins name with a trailing _ some my_plugin should have a * prefix of 'my_plugin_' * * @todo make this auto set in the constructor * * @var string * @access public */ public $tablePrefix; /** * Behaviors to attach to the site. * * @var string * @access public */ public $actsAs = array( 'Libs.Infinitas', 'Events.Event' ); /** * recursive level should always be -1 * * @var string * @access public */ public $recursive = -1; /** * error messages in the model * * @todo this should either be named $errors or made protected * * @var string * @access public */ public $_errors = array(); /** * Plugin that the model belongs to. * * @var string * @access public */ public $plugin = null; /** * auto delete cache * * @var bool * @access public */ public $autoCacheClear = true; /** * @brief Constructor for models * * Throughout Infinitas this method is mainly used to define the validation * rules for models. See below if there is any thing else specific to the * model calling this method. * * @link http://api13.cakephp.org/class/model#method-Model__construct * * @throw E_USER_WARNING if the model is using AppModel for a virtual model. * * @param mixed $id Set this ID for this model on startup, can also be an array of options, see Model::__construct(). * @param string $table Name of database table to use. * @param string $ds DataSource connection name. * @access public * * @return void */ public function __construct($id = false, $table = null, $ds = null) { $this->__getPlugin(); if($this->tablePrefix != ''){ $config = $this->getDataSource()->config; if(isset($config['prefix'])) { $this->tablePrefix = $config['prefix'] . $this->tablePrefix; } } parent::__construct($id, $table, $ds); $this->__setupDatabaseConnections(); $thisClass = get_class($this); $ignore = array( 'SchemaMigration', 'Session' ); if(php_sapi_name() != 'cli' && !in_array($this->alias, $ignore) && ($thisClass == 'AppModel' || $thisClass == 'Model')){ trigger_error(sprintf(__('%s is using AppModel, please create a model file', true), $this->alias), E_USER_WARNING); } if (isset($this->_schema) && is_array($this->_schema) && php_sapi_name() != 'cli') { if($this->Behaviors->enabled('Event')) { $this->triggerEvent('attachBehaviors'); $this->Behaviors->attach('Containable'); } } elseif(php_sapi_name() == 'cli') { $this->actsAs = array(); } } /** * @brief Called before each save operation, after validation. Return a non-true result * to halt the save. * * @link http://api13.cakephp.org/class/model#method-ModelbeforeSave * * @param $created True if this save created a new record * @access public * * @return boolean True if the operation should continue, false if it should abort */ public function beforeSave($options = array()) { return parent::beforeSave($options); } /** * @brief called after something is saved * * @link http://api13.cakephp.org/class/model#method-ModelafterSave * * @param $created True if this save created a new record * @access public * * @return void */ public function afterSave($created){ $this->__clearCache(); } /** * @brief called after something is deleted. * * @link http://api13.cakephp.org/class/model#method-ModelafterDelete * * @access public * * @return void */ public function afterDelete(){ $this->__clearCache(); } /** * @brief Delete all cahce for the plugin. * * Will automaticaly delete all the cache for a model that it can detect. * you can overlaod after save/delete to stop this happening if you dont * want all your cache rebuilt after a save/delete. * * @todo should use the clear_cache plugin for this * * @access private * * @return void */ private function __clearCache(){ if(in_array($this->plugin, Cache::configured())){ $_cache = Cache::getInstance()->__config[$this->plugin]; $path = CACHE.str_replace('.', DS, $_cache['prefix']); if(CACHE !== $path && is_dir($path)){ $Folder = new Folder($path); if($Folder->delete()){ $this->log('deleted: '.$path, 'cache_clearing'); } else{ $this->log('failed: '.$path, 'cache_clearing'); } } else{ $this->log('skip: '.$path, 'cache_clearing'); } } } /** * @brief get a unique list of any model field, used in the search * * @param string $displayField the field to search by * @param bool $primaryKey if true will return array(id, field) else array(field, field) * @access public * * @return array the data from the find */ public function uniqueList($displayField = '', $primaryKey = false){ if(empty($displayField) || !is_string($displayField) || !$this->hasField($displayField)){ return false; } $displayField = $displayField; $primaryKey = $primaryKey ? $this->primaryKey : $displayField; return $this->find( 'list', array( 'fields' => array( $this->alias . '.' . $primaryKey, $this->alias . '.' . $displayField ), 'group' => array( $this->alias . '.' . $displayField ), 'order' => array( $this->alias . '.' . $displayField => 'asc' ) ) ); } /** * @brief Get the name of the plugin * * Get a model name with the plugin prepended in the format used in * CR::init() and Usefull for polymorphic relations. * * @return string Name of the model in the form of Plugin.Name. */ public function modelName() { if($this->plugin == null) { $this->__getPlugin(); } return $this->plugin == null ? $this->name : $this->plugin . '.' . $this->name; } /** * @brief Get the current plugin. * * try and get the name of the current plugin from the parent model class * * @access private * * @return void */ private function __getPlugin() { $parentName = get_parent_class($this); if($parentName !== 'AppModel' && $parentName !== 'Model' && strpos($parentName, 'AppModel') !== false) { $this->plugin = str_replace('AppModel', '', $parentName); } } /** * @brief add connection to the connection manager * * allow plugins to use their own db configs. If there is a conflict, * eg: a plugin tries to set a config that alreay exists an error will * be thrown and the connection will not be created. * * default is a reserved connection that can only be set in database.php * and not via the events. * * @code * // for databases * array( * 'my_connection' => array( * 'driver' => 'mysqli', * 'persistent' => true, * 'host' => 'localhost', * 'login' => 'username', * 'password' => 'pw', * 'database' => 'db_name', * 'encoding' => 'utf8' * ) * ) * * // or other datasources * array( * 'my_connection' => array( * 'datasource' => 'Emails.Imap' * ) * ) * @endcode * * @access private * * @return void */ private function __setupDatabaseConnections(){ $connections = array_filter(current(EventCore::trigger($this, 'requireDatabaseConfigs'))); $existingConnections = ConnectionManager::getInstance()->config; foreach($connections as $plugin => $connection){ $key = current(array_keys($connection)); $connection = current($connection); if(strtolower($key) == 'default' || (isset($existingConnections->{$key}) && $existingConnections->{$key} !== $connection)){ trigger_error(sprintf(__('The connection "%s" in the plugin "%s" has already been used. Skipping', true), $key, $plugin), E_USER_WARNING); continue; } ConnectionManager::create($key, $connection); } } } /** * @brief DRY model class to get the prefix in core models. * * CoreAppModel is used by most of Infinitas core models. All this does is * Set the table prefix so it does not need to be set in every {Core}AppModel * * @copyright Copyright (c) 2009 <NAME> ( dogmatic69 ) * @link http://infinitas-cms.org * @package Infinitas * @license http://www.opensource.org/licenses/mit-license.php The MIT License * @since 0.8a * * @author dogmatic69 * * @internal * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. */ class CoreAppModel extends AppModel{ /** * the table prefix for core models * * @var string * @access public */ public $tablePrefix = 'core_'; }<file_sep><?php /* Comments Test cases generated on: 2010-12-14 02:12:13 : 1292293453*/ App::import('Controller', 'Comments.Comments'); class TestCommentsController extends CommentsController { var $autoRender = false; function redirect($url, $status = null, $exit = true) { $this->redirectUrl = $url; } } class CategoriesControllerTestCase extends CakeTestCase { function startTest() { $this->Comments = new TestCommentsController(); $this->Comments->constructClasses(); } function endTest() { unset($this->Comments); ClassRegistry::flush(); } }<file_sep><?php class TrashAppController extends CoreAppController{ }<file_sep>$(document).ready(function(){ $('.comment textarea').focus(function(){ $(this).css('height', '125px'); $(this).siblings('input.submit').show(); }); $('.comment textarea').blur(function(){ if($(this).val() == ''){ $(this).siblings('input.submit').hide(); $(this).css('height', '15px'); } }); });<file_sep><?php /* Categorisable Test cases generated on: 2010-12-14 01:12:28 : 1292289928*/ App::import('behavior', 'Categories.Categorisable'); class CategorisablebehaviorTestCase extends CakeTestCase { function startTest() { $this->Categorisable = new Categorisablebehavior(); } function endTest() { unset($this->Categorisable); ClassRegistry::flush(); } }<file_sep><?php /** * Module positions controller * * Copyright (c) 2010 <NAME> ( dogmatic69 ) * * @filesource * @copyright Copyright (c) 2010 <NAME> ( dogmatic69 ) * @link http://www.infinitas-cms.org * @package Infinitas.modules * @subpackage Infinitas.modules.controllers.module_positions * @license http://www.opensource.org/licenses/mit-license.php The MIT License * @since 0.8a * * @author dogmatic69 * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. */ echo $this->Form->create('ModulePosition', array('url' => array('action' => 'mass'))); $massActions = $this->Infinitas->massActionButtons( array( 'add', 'edit', 'copy', 'delete' ) ); echo $this->Infinitas->adminIndexHead($filterOptions, $massActions); ?> <div class="table"> <table class="listing" cellpadding="0" cellspacing="0"> <?php echo $this->Infinitas->adminTableHeader( array( $this->Form->checkbox('all') => array( 'class' => 'first', 'style' => 'width:25px;' ), $this->Paginator->sort('name'), $this->Paginator->sort('Modules', 'module_count') => array( 'style' => 'width:100px' ), $this->Paginator->sort('modified') => array( 'style' => 'width:100px' ) ) ); $i = 0; foreach ($modulePositions as $modulePosition){ ?> <tr class="<?php echo $this->Core->rowClass(); ?>"> <td><?php echo $this->Form->checkbox($modulePosition['ModulePosition']['id']); ?>&nbsp;</td> <td> <?php echo $this->Html->link(Inflector::humanize($modulePosition['ModulePosition']['name']), array('action' => 'edit', $modulePosition['ModulePosition']['id'])); ?>&nbsp; </td> <td> <?php echo $modulePosition['ModulePosition']['module_count']; ?>&nbsp; </td> <td> <?php echo $this->Time->niceShort($modulePosition['ModulePosition']['modified']); ?>&nbsp; </td> </tr> <?php } ?> </table> <?php echo $this->Form->end(); ?> </div> <?php echo $this->element('pagination/admin/navigation'); ?><file_sep><?php /** * Comment Template. * * @todo -c Implement .this needs to be sorted out. * * Copyright (c) 2009 <NAME> ( dogmatic69 ) * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. * * @filesource * @copyright Copyright (c) 2009 <NAME> ( dogmatic69 ) * @link http://infinitas-cms.org * @package sort * @subpackage sort.comments * @license http://www.opensource.org/licenses/mit-license.php The MIT License * @since 0.5a */ echo $this->Form->create('GlobalLayout'); echo $this->Infinitas->adminEditHead(); ?> <fieldset> <h1><?php echo __('Content', true); ?></h1><?php echo $this->Form->input('id'); $error = $this->Form->error('plugin'); $errorClass = !empty($error) ? 'error' : ''; ?> <div class="input smaller required <?php echo $errorClass; ?>"> <label for="GlobalLayoutPlugin"><?php echo __('Route', true); ?></label><?php echo $this->Form->input('plugin', array('error' => false, 'div' => false, 'type' => 'select', 'label' => false, 'class' => "pluginSelect {url:{action:'getModels'}, target:'GlobalLayoutModel'}")); echo $this->Form->input('model', array('error' => false, 'div' => false, 'type' => 'select', 'label' => false)); echo $error; ?> </div><?php echo $this->Form->input('name', array('class' => 'title')); echo $this->Form->input('css', array('class' => 'title')); echo $this->Infinitas->wysiwyg('GlobalLayout.html'); // echo $this->Form->input('php', array('class' => 'title')); ?> </fieldset><?php echo $this->Form->end(); ?><file_sep><?php class Plugin extends InstallerAppModel { public function __construct($id = false, $table = null, $ds = null) { parent::__construct($id, $table, $ds); $this->validate = array( 'id' => array( 'uuid' => array( 'rule' => 'uuid', 'required' => true, 'message' => __d('installer', 'All plugins are required to have a valid unique identifier based on the RFC4122 definition.', true) ), ), 'internal_name' => array( 'unique' => array( 'rule' => 'isUnique', 'message' => __d('installer', 'You already have a plugin with this name installed', true) ) ) ); } public function installPlugin($pluginName, $options = array()) { $options = array_merge( array( 'sampleData' => false, 'installRelease' => true ), $options ); extract($options); $pluginDetails = $this->__loadPluginDetails($pluginName); if($pluginDetails !== false && isset($pluginDetails['id'])) { $pluginDetails['dependancies'] = json_encode($pluginDetails['dependancies']); $pluginDetails['internal_name'] = $pluginName; $pluginDetails['enabled'] = true; $pluginDetails['core'] = strpos(App::pluginPath($pluginName), APP . 'core' . DS) !== false; if($this->save($pluginDetails)) { if($installRelease === true) { $installed = $this->__processRelease($pluginName, $sampleData); } else { $installed = true; } return $installed; } else { return false; } } } private function __loadPluginDetails($pluginName) { $configFile = App::pluginPath($pluginName) . 'config' . DS . 'config.json'; return file_exists($configFile) ? Set::reverse(json_decode(file_get_contents($configFile))) : false; } private function __processRelease($pluginName, $sampleData = false) { App::import('Lib', 'Installer.ReleaseVersion'); try { $Version = new ReleaseVersion(); $mapping = $Version->getMapping($pluginName); $latest = array_pop($mapping); return $Version->run(array( 'type' => $plugin, 'version' => $latest['version'], 'sample' => $sampleData )); } catch(Exception $e) { return false; } return true; } }<file_sep><?php class TicketableBehavior extends ModelBehavior{ /** * Initiate behavior for the model using specified settings. * Available settings: * * - timeout :: the date/time when the ticket will expire * * @param object $Model Model using the behaviour * @param array $settings Settings to override for model. * @access public */ function setup(&$Model, $settings = array()) { $default = array( 'expires' => date('Y-m-d H:i:s', time() + (24 * 60 * 60)) ); if (!isset($this->__settings[$Model->alias])) { $this->__settings[$Model->alias] = $default; } $this->__settings[$Model->alias] = am($this->__settings[$Model->alias], ife(is_array($settings), $settings, array())); $this->Ticket = ClassRegistry::init('Management.Ticket'); } /** * Create a new ticket. * * Create a new ticket by providing the data to be stored in the ticket. * If no information is passed false is returned, or the ticket id is returned. * * @param string $info the information to save. will be serialized so arrays are fine */ function createTicket(&$Model, $info = null){ $this->cleanup(); if (!$info){ return false; } $data['Ticket']['data'] = serialize($info); $data['Ticket']['expires'] = $this->__settings[$Model->alias]['expires']; $this->Ticket->create(); $return = $this->Ticket->save($data); if ($this->Ticket->id > 0){ return $this->Ticket->id; } return false; } /** * Get a ticket. * * If something is found return the data that was saved or return false * if there is something wrong. * * @param string $ticket the ticket uuid */ function getTicket(&$Model, $ticket = null){ $this->cleanup(); if (!$ticket){ return false; } $data = $this->Ticket->find( 'first', array( 'conditions' => array( 'Ticket.id' => $ticket ) ) ); if (isset($data['Ticket']) && is_array($data['Ticket'])){ if($this->Ticket->delete($ticket)){ return unserialize($data['Ticket']['data']); } } return false; } /** * Remove old tickets * * When things are done, remove old tickets that have expired. */ function cleanup(){ $this->Ticket->deleteAll( array( 'Ticket.expires < ' => date('Y-m-d H:i:s') ) ); } } ?><file_sep><div class="dashboard"> <h1><?php __('Missing Database Connection'); ?></h1> <p class="error"> <strong><?php __('Error'); ?>: </strong> <?php __('Scaffold requires a database connection'); ?> </p> <p class="error"> <strong><?php __('Error'); ?>: </strong> <?php printf(__('Confirm you have created the file: %s', true), APP_DIR . DS . 'config' . DS . 'database.php'); ?> </p> </div><file_sep><?php /** * @brief Config model is for saving and editing site configurations. * * @copyright Copyright (c) 2009 <NAME> ( dogmatic69 ) * @link http://infinitas-cms.org * @package Infinitas.Configs.models * @license http://www.opensource.org/licenses/mit-license.php The MIT License * @since 0.5a * * @author dogmatic69 * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. */ class Config extends ConfigsAppModel { /** * the name of the model * * @var string * @access public */ public $name = 'Config'; /** * the display field * * @var string * @access public */ public $displayField = 'key'; /** * The default ordering for configs * * @var array * @access public */ public $order = array( 'Config.key' => 'ASC' ); /** * @copydoc AppModel::__construct() */ public function __construct($id = false, $table = null, $ds = null) { parent::__construct($id, $table, $ds); $this->_configTypes = array( 0 => __('Please Select', true), 'string' => __('String', true), 'integer' => __('Integer', true), 'dropdown' => __('Dropdown', true), 'bool' => __('Bool', true), 'array' => __('Array', true) ); $ruleCheck = $this->_configTypes; unset($ruleCheck[0]); $this->validate = array( 'key' => array( 'notEmpty' => array( 'rule' => 'notEmpty', 'message' => __('Please enter the name of this config', true) ), 'validKeyName' => array( 'rule' => '/^[A-Z][A-Za-z]*\.[a-z_]+$/', 'message' => __('The key must be in the format "Plugin.config_name"', true), 'on' => 'create' ) ), 'value' => array( 'notEmpty' => array( 'rule' => 'notEmpty', 'message' => __('Please enter the value', true) ) ), 'type' => array( 'allowedChoice' => array( 'rule' => array('inList', array_keys($ruleCheck)), 'message' => __('Please select the type', true) ) ), 'options' => array( 'customOptionCheck' => array( 'rule' => 'customOptionCheck', 'message' => __('Please enter some valid options', true) ) ) ); } /** * @brief delete config cache * * after saving something delete the main core_configs cache so that * the changes will take effect * * @param bool $created is it new or not * @access public * * @return parent method */ public function afterSave($created){ Cache::delete('global_configs'); return parent::afterSave($created); } /** * @brief delete config cache * * after saving something delete the main core_configs cache so that * the changes will take effect * * @param bool $created is it new or not * @access public * * @return parent method */ public function afterDelete($created){ Cache::delete('global_configs'); return parent::afterDelete($created); } /** * @brief validate the options based on what type is set for the row * * @todo this should be renamed to validateCustomOptionCheck * * @param array $data the field being validated * @access public * * @return bool is it valid or not */ public function customOptionCheck($data){ if (!isset($this->data['Config']['type']) || empty($this->data['Config']['type'])) { return true; } switch($this->data['Config']['type']){ case 'string': return true; break; case 'integer': if (!empty($data['options']) && is_int($data['options'])) { return true; } break; case 'dropdown': if (is_int($data['options'])) { return false; } //@todo needs a bit more work return preg_match('/[0-9A-Za-z*\,]+$/', $data['options']); break; case 'bool': if ($data['options'] === 'true,false' || $data['options'] === 'false,true') { return true; } break; case 'array': return $this->getJson($this->data['Config']['value'], array(), false); break; } // switch return false; } /** * @brief Get configuration for the app. * * This gets and formats an array of config values for the app to use. it goes * through the list and formats the values to match the type that was passed. * * @param bool $format should it be formated for configure::write or not. * @access public * * @return array all the config options set to the correct type */ public function getConfig($format = false) { $configs = Cache::read('global_configs'); if ($configs !== false) { if ($format) { return $this->__formatConfigs($configs); } return $configs; } $configs = $this->find( 'all', array( 'fields' => array( 'Config.key', 'Config.value', 'Config.type' ), 'conditions' => array( 'Config.key !=' => -1 ) ) ); foreach($configs as $k => $config) { switch($configs[$k]['Config']['type']) { case 'bool': $configs[$k]['Config']['value'] = ($configs[$k]['Config']['value'] == 'true') ? true : false; break; case 'string': $configs[$k]['Config']['value'] = (string)$configs[$k]['Config']['value']; break; case 'integer': $configs[$k]['Config']['value'] = (int)$configs[$k]['Config']['value']; break; case 'array': $configs[$k]['Config']['value'] = $this->getJson($configs[$k]['Config']['value']); break; } // switch } Cache::write('global_configs', $configs); if ($format) { return $this->__formatConfigs($configs); } return $configs; } /** * @brief format the data into a key value array to be used in Configure::write * * @param array $configs the unformatted configs * @access private * * @return array the data that has been formatted */ private function __formatConfigs($configs = array(), $json = false){ if (empty($configs)) { return false; } $format = array(); foreach($configs as $k => $config) { $format[$configs[$k]['Config']['key']] = $json ? json_encode($configs[$k]['Config']['value']) : $configs[$k]['Config']['value']; } return $format; } /** * @brief Installer setup. * * This gets some config values that are used in the installer for the site * setup. * * @access public * * @return array of all the configs that are needed/able to be done in the installer */ public function getInstallSetupConfigs(){ return $this->find( 'all', array( 'conditions' => array( 'Config.key LIKE ' => 'Website.%' ) ) ); } /** * @brief build up the code to see what is being used or to avoid typing * * Just for generating code for the configs, can be used in the dev installer * plugin stuff to avoid typing out stuff. * * @internal * @access public */ public function generateCode($config){ if(isset($config[0])){ foreach($config as $_config){ $return[] = self::generateCode($_config); } } if(is_bool($config['Config']['value'])){ if($config['Config']['value']){ $_config = 'true'; } else{ $_config = 'false'; } } else if(is_array($config['Config']['value'])){ $_config = 'array('; foreach($config['Config']['value'] as $k => $v){ $_config .= !is_int($k) ? '\''.$k.'\'' : $k; $_config .= '=> \''.$v.'\','; } $_config .= ')'; } else if(is_string($config['Config']['value'])){ $_config = '\''.$config['Config']['value'].'\''; } else{ $_config = $config['Config']['value']; } return 'Configure::write(\''.$config['Config']['key'].'\', '.$_config.');'; } /** * @brief Get a list of config options that can be overloaded by an admin user. * * This gets a list of possible values that can be changed in the backend * unsetting a few options first that should not be fiddled with. * * @return array the config options to be overloaded. */ public function availableConfigs(){ $configs = Configure::getInstance(); unset( $configs->CORE['current_route'] ); $configs = Set::flatten($configs); ksort($configs); return $configs; } }<file_sep><?php /** * @brief Category model handles the CRUD for categories. * * Saving and editing categories are done here. * * @copyright Copyright (c) 2009 <NAME> ( dogmatic69 ) * @link http://infinitas-cms.org * @package Infinitas.Categories.models * @license http://www.opensource.org/licenses/mit-license.php The MIT License * @since 0.7a * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. */ class Category extends CategoriesAppModel { /** * The model name * * @var string * @access public */ public $name = 'Category'; /** * lockable enables the internal row locking while a row is being modified * preventing anyone from accessing that row. * * @var bool * @access public */ public $lockable = true; /** * default order of the model is set to lft as its an mptt table * * @var array * @access public */ public $order = array( 'Category.lft' => 'asc' ); /** * the relations for the category model * * @var array * @access public */ public $belongsTo = array( //'Parent' => array( // 'className' => 'Categories.Category', // 'counterCache' => true //), 'Users.Group' ); /** * @copydoc AppModel::__construct() */ public function __construct($id = false, $table = null, $ds = null) { parent::__construct($id, $table, $ds); $this->validate = array( 'title' => array( 'notEmpty' => array( 'rule' => 'notEmpty', 'message' => __('Please enter a title for this category', true) ), 'isUnique' => array( 'rule' => 'isUnique', 'message' => __('There is already a category with this title', true) ) ) ); } /** * get active ids of the categories for use in other finds where you only * want the active rows according to what categories are active. * * @access public * * @return array list of ids for categories that are active */ public function getActiveIds(){ $ids = $this->find( 'list', array( 'fields' => array( 'Category.id', 'Category.id' ), 'conditions' => array( 'Category.active' => 1 ) ) ); return $ids; } /** * overwrite childern method to allow finding by slug or name * * @param mixed $id the id of the parent * @param bool $direct direct children only or all like grandchildren * @access public * * @todo seems like a bug here with uuid's * * @return TreeBehavior::children */ public function children($id = null, $direct = false){ if(!$id || is_int($id)){ return parent::children($id, $direct); } $id = $this->find( 'first', array( 'conditions' => array( 'or' => array( 'Category.slug' => $id, 'Category.title' => $id ), ) ) ); if(isset($id['Category']['id']) && !empty($id['Category']['id'])){ $id = $id['Category']['id']; } return parent::children($id, $direct); } }<file_sep><div class="dashboard"> <h1><?php printf(__('Missing Method in %s', true), $controller); ?></h1> <p class="error"> <strong><?php __('Error'); ?>: </strong> <?php printf(__('The action %1$s is not defined in controller %2$s', true), '<em>' . $action . '</em>', '<em>' . $controller . '</em>'); ?> </p> <p class="error"> <strong><?php __('Error'); ?>: </strong> <?php printf(__('Create %1$s%2$s in file: %3$s.', true), '<em>' . $controller . '::</em>', '<em>' . $action . '()</em>', APP_DIR . DS . 'controllers' . DS . Inflector::underscore($controller) . '.php'); ?> </p> <pre> &lt;?php class <?php echo $controller;?> extends AppController { var $name = '<?php echo $controllerName;?>'; <strong> function <?php echo $action;?>() { } </strong> } ?&gt; </pre> </div><file_sep><?php /** * * */ class WebmasterAppController extends CoreAppController{ }<file_sep><?php echo $this->Charts->draw( array( 'bar' => array( 'type' => 'vertical', 'bar' => 'vertical' ) ), array( 'data' => array(10, 15, 20, 5, 10, 40), 'axes' => array( 'x' => array('a', 'b', 'c', 'd', 'e', 'f'), 'y' => '' ), 'size' => array( 900, 150 ), 'color' => array( 'background' => 'FFFFFF', 'fill' => 'FFCC33', 'text' => '989898', 'lines' => '989898', ), 'spacing' => array( 'padding' => 6 ), 'tooltip' => 'Something Cool :: figure1: %s<br/>figure1: %s<br/>figure3: %s', 'html' => array( 'class' => 'chart' ) ) );<file_sep><?php /** * Comment Template. * * @todo -c Implement .this needs to be sorted out. * * Copyright (c) 2009 <NAME> ( dogmatic69 ) * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. * * @filesource * @copyright Copyright (c) 2009 <NAME> ( dogmatic69 ) * @link http://infinitas-cms.org * @package sort * @subpackage sort.comments * @license http://www.opensource.org/licenses/mit-license.php The MIT License * @since 0.5a */ echo $this->Form->create( 'Menu', array( 'url' => array( 'controller' => 'menus', 'action' => 'mass', 'admin' => 'true' ) ) ); $massActions = $this->Core->massActionButtons( array( 'add', 'edit', 'toggle', 'copy', 'delete' ) ); echo $this->Infinitas->adminIndexHead($filterOptions, $massActions); ?> <div class="table"> <table class="listing" cellpadding="0" cellspacing="0"> <?php echo $this->Core->adminTableHeader( array( $this->Form->checkbox( 'all' ) => array( 'class' => 'first', 'style' => 'width:25px;' ), $this->Paginator->sort( 'name' ), $this->Paginator->sort( 'type' ) => array( 'style' => 'width:75px;' ), $this->Paginator->sort( 'Active Items', true ) => array( 'style' => 'width:100px;' ), $this->Paginator->sort( 'Inactive Items', true ) => array( 'style' => 'width:100px;' ), $this->Paginator->sort( 'active', true ) => array( 'style' => 'width:50px;' ) ) ); foreach ( $menus as $menu ) { ?> <tr class="<?php echo $this->Core->rowClass(); ?>"> <td><?php echo $this->Form->checkbox( $menu['Menu']['id'] ); ?>&nbsp;</td> <td> <?php echo $this->Html->link( Inflector::humanize($menu['Menu']['name']), array('controller' => 'menuItems', 'action' => 'index', 'menu_id' => $menu['Menu']['id'])); ?>&nbsp; </td> <td> <?php echo $menu['Menu']['type']; ?>&nbsp; </td> <td> <?php echo $menu['Menu']['item_count']; ?>&nbsp; </td> <td> <?php echo $menu['Menu']['item_count']; ?>&nbsp; </td> <td> <?php echo $this->Infinitas->status($menu['Menu']['active']); ?>&nbsp; </td> </tr> <?php } ?> </table> <?php echo $this->Form->end(); ?> </div> <?php echo $this->element('pagination/admin/navigation'); ?><file_sep><?php $map = array( 1 => array( '000008_short_urls' => 'R4cbd67db435c4099a94347b96318cd70'), ); ?><file_sep><?php /* CoreTrash Fixture generated on: 2010-08-17 03:08:19 : 1282012219 */ class TrashFixture extends CakeTestFixture { var $name = 'Trash'; var $table = 'core_trash'; var $fields = array( 'id' => array('type' => 'integer', 'null' => false, 'default' => NULL, 'key' => 'primary'), 'model' => array('type' => 'string', 'null' => false, 'default' => NULL, 'length' => 100), 'foreign_key' => array('type' => 'string', 'null' => false, 'default' => NULL, 'length' => 36), 'name' => array('type' => 'string', 'null' => false, 'default' => NULL), 'data' => array('type' => 'text', 'null' => false, 'default' => NULL), 'deleted' => array('type' => 'datetime', 'null' => false, 'default' => NULL), 'deleted_by' => array('type' => 'integer', 'null' => true, 'default' => NULL), 'indexes' => array('PRIMARY' => array('column' => 'id', 'unique' => 1)), 'tableParameters' => array('charset' => 'utf8', 'collate' => 'utf8_general_ci', 'engine' => 'InnoDB') ); var $records = array( array( 'id' => 1, 'model' => 'Creditcards.Product', 'foreign_key' => '16', 'name' => 'Deleted Credit Card', 'data' => 'a:1:{s:7:\"Product\";a:17:{s:2:\"id\";s:2:\"16\";s:4:\"name\";s:19:\"Deleted Credit Card\";s:4:\"slug\";s:19:\"deleted-credit-card\";s:4:\"info\";s:36:\"Deleted Credit Card user information\";s:11:\"description\";s:37:\"Deleted Credit Card admin information\";s:5:\"image\";s:23:\"deleted_credit_card.png\";s:14:\"minimum_salary\";s:8:\"99999999\";s:16:\"product_color_id\";s:1:\"1\";s:11:\"supplier_id\";s:1:\"1\";s:6:\"active\";s:1:\"1\";s:6:\"locked\";s:1:\"0\";s:9:\"locked_by\";N;s:12:\"locked_since\";N;s:7:\"deleted\";s:1:\"1\";s:12:\"deleted_date\";s:19:\"2010-03-01 00:00:00\";s:7:\"created\";s:19:\"2010-03-01 00:00:00\";s:8:\"modified\";s:19:\"2010-03-02 00:00:00\";}}', 'deleted' => '2010-05-24 17:38:07', 'deleted_by' => NULL ), array( 'id' => 2, 'model' => 'Creditcards.Package', 'foreign_key' => '5', 'name' => 'deleted package', 'data' => 'a:1:{s:7:\"Package\";a:22:{s:2:\"id\";s:1:\"5\";s:4:\"name\";s:15:\"deleted package\";s:4:\"slug\";s:15:\"deleted package\";s:4:\"info\";s:15:\"deleted package\";s:11:\"description\";s:15:\"deleted package\";s:11:\"supplier_id\";s:1:\"5\";s:17:\"debit_interest_id\";s:1:\"5\";s:18:\"credit_interest_id\";s:1:\"1\";s:10:\"product_id\";s:2:\"10\";s:19:\"subscription_fee_id\";s:1:\"1\";s:6:\"active\";s:1:\"1\";s:6:\"locked\";s:1:\"0\";s:12:\"locked_since\";N;s:9:\"locked_by\";N;s:7:\"deleted\";s:1:\"1\";s:12:\"deleted_date\";s:19:\"2010-03-01 00:00:00\";s:7:\"created\";s:19:\"2010-03-01 00:00:00\";s:8:\"modified\";s:19:\"2010-05-25 14:22:29\";s:21:\"subscription_fee_rank\";s:6:\"604.84\";s:6:\"rating\";s:1:\"1\";s:12:\"rating_count\";s:3:\"100\";s:18:\"included_fee_count\";s:1:\"0\";}}', 'deleted' => '2010-05-25 15:39:13', 'deleted_by' => NULL ), array( 'id' => 3, 'model' => 'Management.MenuItem', 'foreign_key' => '68', 'name' => 'Blog', 'data' => 'a:1:{s:8:\"MenuItem\";a:20:{s:2:\"id\";s:2:\"68\";s:4:\"name\";s:4:\"Blog\";s:4:\"slug\";s:0:\"\";s:4:\"link\";s:0:\"\";s:6:\"prefix\";s:0:\"\";s:6:\"plugin\";s:4:\"blog\";s:10:\"controller\";s:5:\"posts\";s:6:\"action\";s:5:\"index\";s:6:\"params\";s:0:\"\";s:13:\"force_backend\";s:1:\"0\";s:14:\"force_frontend\";s:1:\"1\";s:5:\"class\";s:0:\"\";s:6:\"active\";s:1:\"1\";s:7:\"menu_id\";s:1:\"2\";s:8:\"group_id\";s:1:\"0\";s:9:\"parent_id\";s:2:\"97\";s:3:\"lft\";s:1:\"4\";s:4:\"rght\";s:1:\"5\";s:7:\"created\";s:19:\"2010-02-01 00:39:00\";s:8:\"modified\";s:19:\"2010-05-05 02:56:54\";}}', 'deleted' => '2010-06-03 09:36:15', 'deleted_by' => NULL ), array( 'id' => 4, 'model' => 'Management.MenuItem', 'foreign_key' => '69', 'name' => 'Cms', 'data' => 'a:1:{s:8:\"MenuItem\";a:20:{s:2:\"id\";s:2:\"69\";s:4:\"name\";s:3:\"Cms\";s:4:\"slug\";s:0:\"\";s:4:\"link\";s:0:\"\";s:6:\"prefix\";s:0:\"\";s:6:\"plugin\";s:3:\"cms\";s:10:\"controller\";s:10:\"frontpages\";s:6:\"action\";s:5:\"index\";s:6:\"params\";s:0:\"\";s:13:\"force_backend\";s:1:\"0\";s:14:\"force_frontend\";s:1:\"1\";s:5:\"class\";s:0:\"\";s:6:\"active\";s:1:\"1\";s:7:\"menu_id\";s:1:\"2\";s:8:\"group_id\";s:1:\"0\";s:9:\"parent_id\";s:2:\"97\";s:3:\"lft\";s:1:\"4\";s:4:\"rght\";s:1:\"5\";s:7:\"created\";s:19:\"2010-02-01 00:40:00\";s:8:\"modified\";s:19:\"2010-05-05 02:56:49\";}}', 'deleted' => '2010-06-03 09:36:15', 'deleted_by' => NULL ), array( 'id' => 5, 'model' => 'Management.MenuItem', 'foreign_key' => '115', 'name' => 'Shop', 'data' => 'a:1:{s:8:\"MenuItem\";a:20:{s:2:\"id\";s:3:\"115\";s:4:\"name\";s:4:\"Shop\";s:4:\"slug\";s:0:\"\";s:4:\"link\";s:0:\"\";s:6:\"prefix\";s:0:\"\";s:6:\"plugin\";s:4:\"shop\";s:10:\"controller\";s:8:\"products\";s:6:\"action\";s:9:\"dashboard\";s:6:\"params\";s:0:\"\";s:13:\"force_backend\";s:1:\"0\";s:14:\"force_frontend\";s:1:\"1\";s:5:\"class\";s:0:\"\";s:6:\"active\";s:1:\"1\";s:7:\"menu_id\";s:1:\"2\";s:8:\"group_id\";s:1:\"0\";s:9:\"parent_id\";s:2:\"97\";s:3:\"lft\";s:1:\"4\";s:4:\"rght\";s:1:\"5\";s:7:\"created\";s:19:\"2010-05-05 02:51:00\";s:8:\"modified\";s:19:\"2010-05-05 02:53:38\";}}', 'deleted' => '2010-06-03 09:36:15', 'deleted_by' => NULL ), array( 'id' => 6, 'model' => 'Management.MenuItem', 'foreign_key' => '70', 'name' => 'Register', 'data' => 'a:1:{s:8:\"MenuItem\";a:20:{s:2:\"id\";s:2:\"70\";s:4:\"name\";s:8:\"Register\";s:4:\"slug\";s:0:\"\";s:4:\"link\";s:0:\"\";s:6:\"prefix\";s:0:\"\";s:6:\"plugin\";s:10:\"management\";s:10:\"controller\";s:5:\"users\";s:6:\"action\";s:8:\"register\";s:6:\"params\";s:0:\"\";s:13:\"force_backend\";s:1:\"0\";s:14:\"force_frontend\";s:1:\"1\";s:5:\"class\";s:0:\"\";s:6:\"active\";s:1:\"1\";s:7:\"menu_id\";s:1:\"2\";s:8:\"group_id\";s:1:\"0\";s:9:\"parent_id\";s:2:\"97\";s:3:\"lft\";s:1:\"4\";s:4:\"rght\";s:1:\"5\";s:7:\"created\";s:19:\"2010-02-02 22:59:00\";s:8:\"modified\";s:19:\"2010-05-05 02:56:43\";}}', 'deleted' => '2010-06-03 09:36:15', 'deleted_by' => NULL ), array( 'id' => 7, 'model' => 'Management.MenuItem', 'foreign_key' => '72', 'name' => 'Contact', 'data' => 'a:1:{s:8:\"MenuItem\";a:20:{s:2:\"id\";s:2:\"72\";s:4:\"name\";s:7:\"Contact\";s:4:\"slug\";s:0:\"\";s:4:\"link\";s:0:\"\";s:6:\"prefix\";s:0:\"\";s:6:\"plugin\";s:7:\"contact\";s:10:\"controller\";s:8:\"branches\";s:6:\"action\";s:5:\"index\";s:6:\"params\";s:0:\"\";s:13:\"force_backend\";s:1:\"0\";s:14:\"force_frontend\";s:1:\"1\";s:5:\"class\";s:0:\"\";s:6:\"active\";s:1:\"1\";s:7:\"menu_id\";s:1:\"2\";s:8:\"group_id\";s:1:\"0\";s:9:\"parent_id\";s:2:\"97\";s:3:\"lft\";s:1:\"4\";s:4:\"rght\";s:1:\"5\";s:7:\"created\";s:19:\"2010-02-10 18:10:00\";s:8:\"modified\";s:19:\"2010-05-05 02:56:37\";}}', 'deleted' => '2010-06-03 09:36:15', 'deleted_by' => NULL ), array( 'id' => 8, 'model' => 'Management.MenuItem', 'foreign_key' => '119', 'name' => 'Login', 'data' => 'a:1:{s:8:\"MenuItem\";a:20:{s:2:\"id\";s:3:\"119\";s:4:\"name\";s:5:\"Login\";s:4:\"slug\";s:5:\"login\";s:4:\"link\";s:0:\"\";s:6:\"prefix\";s:0:\"\";s:6:\"plugin\";s:10:\"management\";s:10:\"controller\";s:5:\"users\";s:6:\"action\";s:5:\"login\";s:6:\"params\";s:0:\"\";s:13:\"force_backend\";s:1:\"0\";s:14:\"force_frontend\";s:1:\"1\";s:5:\"class\";s:0:\"\";s:6:\"active\";s:1:\"1\";s:7:\"menu_id\";s:1:\"2\";s:8:\"group_id\";s:1:\"0\";s:9:\"parent_id\";s:2:\"97\";s:3:\"lft\";s:1:\"4\";s:4:\"rght\";s:1:\"5\";s:7:\"created\";s:19:\"2010-05-13 20:42:12\";s:8:\"modified\";s:19:\"2010-05-13 20:42:12\";}}', 'deleted' => '2010-06-03 09:36:15', 'deleted_by' => NULL ), array( 'id' => 9, 'model' => 'Think.Supplier', 'foreign_key' => '4', 'name' => '<NAME>', 'data' => 'a:1:{s:8:\"Supplier\";a:18:{s:2:\"id\";s:1:\"4\";s:4:\"name\";s:16:\"Deleted Supplier\";s:4:\"slug\";s:16:\"deleted-supplier\";s:4:\"logo\";s:0:\"\";s:4:\"info\";s:26:\"Deleted Supplier user info\";s:11:\"description\";s:27:\"Deleted Supplier admin info\";s:5:\"phone\";s:9:\"123456789\";s:5:\"email\";s:21:\"<EMAIL>\";s:6:\"active\";s:1:\"0\";s:13:\"package_count\";s:1:\"0\";s:13:\"product_count\";s:1:\"0\";s:6:\"locked\";s:1:\"0\";s:9:\"locked_by\";N;s:12:\"locked_since\";N;s:7:\"deleted\";s:1:\"1\";s:12:\"deleted_date\";s:19:\"2010-03-05 00:00:00\";s:8:\"modified\";s:19:\"2010-03-01 00:00:00\";s:7:\"created\";s:19:\"2010-03-02 00:00:00\";}}', 'deleted' => '2010-06-03 12:18:05', 'deleted_by' => NULL ), array( 'id' => 10, 'model' => 'Management.Module', 'foreign_key' => '20', 'name' => 'Promotion 1', 'data' => 'a:1:{s:6:\"Module\";a:25:{s:2:\"id\";s:2:\"20\";s:4:\"name\";s:11:\"Promotion 1\";s:7:\"content\";s:0:\"\";s:6:\"module\";s:11:\"promotion_1\";s:6:\"config\";s:0:\"\";s:8:\"theme_id\";s:1:\"0\";s:11:\"position_id\";s:1:\"6\";s:8:\"group_id\";s:1:\"2\";s:8:\"ordering\";s:1:\"1\";s:5:\"admin\";s:1:\"0\";s:6:\"active\";s:1:\"0\";s:6:\"locked\";s:1:\"0\";s:9:\"locked_by\";s:1:\"0\";s:12:\"locked_since\";s:1:\"0\";s:12:\"show_heading\";s:1:\"0\";s:4:\"core\";s:1:\"0\";s:6:\"author\";s:9:\"Infinitas\";s:7:\"licence\";s:3:\"MIT\";s:3:\"url\";s:24:\"http://infinitas-cms.org\";s:10:\"update_url\";s:0:\"\";s:7:\"created\";s:19:\"2010-05-07 19:17:15\";s:8:\"modified\";s:19:\"2010-05-07 19:41:57\";s:6:\"plugin\";s:4:\"shop\";s:9:\"list_name\";s:11:\"Promotion 1\";s:9:\"save_name\";s:11:\"promotion_1\";}}', 'deleted' => '2010-08-04 23:30:12', 'deleted_by' => 1 ), ); } ?><file_sep><?php /** * @brief ContactsHelper is a collection of methods to help build up contact related * pages * * Currently can output a business card type markup for contacts. * * @todo contact forms. pass in a contact row and a form will be made using the * supplied email address etc. * * @copyright Copyright (c) 2010 <NAME> ( dogmatic69 ) * @link http://www.infinitas-cms.org * @package Infinitas.Contact.helpers * @license http://www.opensource.org/licenses/mit-license.php The MIT License * @since 0.8a * * @author dogmatic69 * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. */ class ContactsHelper extends AppHelper{ public $helpers = array( 'Text', 'Html' ); public function drawCard($details){ if(is_array(current($details))){ $this->drawCards($details); } $out = '<div class="contact-card">'; $out .= $this->__output($details); $out .= '</div>'; return $out; } private function __output($details){ $default = array( 'checkbox' => '', 'avitar' => '', 'user' => '', 'company' => '', 'mobile' => '', 'landline' => '', 'email' => '', 'address' ); $return = array(); $details = array_merge($default, $details); if(!empty($details['avitar'])){ $return[] = $this->Html->image( $details['avitar'], array( 'style' => 'width: 75; height: 75', 'title' => sprintf('%s - %s', $details['user'], $details['company']) ) ); } if(!empty($details['mobile'])){ $return[] = sprintf('<li class="mobile">%s</li>', $details['mobile']); } if(!empty($details['landline'])){ $return[] = sprintf('<li class="landline">%s</li>', $details['landline']); } if(!empty($details['email'])){ $return[] = sprintf('<li class="email">%s</li>', $this->Text->autoLinkEmails($details['email'])); } if(!empty($details['address'])){ $return[] = sprintf('<li class="address">%s</li>', $details['address']); } if(!empty($details['extra'])){ $return[] = sprintf('<li class="extra">%s</li>', $details['extra']); } if(empty($details['user']) && !empty($details['company'])){ $name = $details['company']; } else if(!empty($details['company'])){ $name = sprintf('%s - %s', $details['company'], $details['user']); } else{ $name = $details['user']; } return sprintf('<h2>%s%s</h2>', $details['checkbox'], $name) . '<ul class="details">' . implode('', $return) . '</ul>'; } }<file_sep><?php /** * @page Categoires-Plugin Categories plugin * * @section categories-overview What is it * * The categories plugin provides an easy way for developers to make data * categorizable. This is done by adding a category_id to the table inquestion. * When a category_id field is present the CategorisableBehavior is automatically * attached through the Event system. * * @todo this fits in with the Contents plugin, could possibly be moved there * together with the Content and Layout stuff * * @section categories-usage How to use it * * When you need to add categories to a row, after having added the category_id * to the table you will need to include a dropdown for the user to select which * category the row will belong to. The easy way to do this is to add the following * snip of code to your view. That will take care of everything for you regarding * the selection of a category. * * @code * echo $this->element('category_list', array('plugin' => 'Categories')); * @endcode * * @section categories-code How it works * * With every request when models are being started up, an event is triggered * by the Infinitas core. This event is a call to all plugins that need to * attach behaviors to the models for the current request. At this point the * CategoriesEvents will establish if the model being loaded has the category_id * field and if so attach the CategorisableBehavior to the model. Once the * behavior has been attached the startup method is called and the behavior will * create the relations necessary for the model to be categorized. * * Before any finds the CategorisableBehavior will automatically contain * the Category model so that the data will be available in the views. * * @image html sql_categories_plugin.png "Categories Plugin table structure" * * @section categories-see-also Also see * @ref EventCore */ /** * @brief Categorize your appliaction * * The categories plugin makes categorising records in your application easy * by automatically attaching and joing the related category information * to models that require it. * * CategoriesAppController is the base controller class that other controllers * extend from inside the categories plugin * * @copyright Copyright (c) 2010 <NAME> ( dogmatic69 ) * @link http://www.infinitas-cms.org * @package Infinitas.Categories * @license http://www.opensource.org/licenses/mit-license.php The MIT License * @since 0.8a * * @author dogmatic69 * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. */ class CategoriesAppController extends AppController { /** * before anything starts processing this fires to include the filter * helper * * @access public */ public function beforeFilter(){ parent::beforeFilter(); $this->helpers[] = 'Filter.Filter'; } }<file_sep><?php /** * Controller to manage reckord locking. * * This controller will unlock records that are locked. * * Copyright (c) 2010 <NAME> ( dogmatic69 ) * * @filesource * @copyright Copyright (c) 2010 <NAME> ( dogmatic69 ) * @link http://www.infinitas-cms.org * @package management * @subpackage management.controllers.locks * @license http://www.opensource.org/licenses/mit-license.php The MIT License * @since 0.7a * * @author <NAME> ( dogmatic69 ) * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. */ class LocksController extends LocksAppController{ public $name = 'Locks'; public function beforeFilter(){ parent::beforeFilter(); $this->helpers[] = 'Filter.Filter'; } public function admin_index(){ $this->paginate = array( 'contain' => array( 'Locker' ) ); $locks = $this->paginate(); $this->set(compact('locks')); } /** * unlock the rows by deleting them. */ protected function __massActionUnlock($ids = array()){ return $this->MassAction->__handleDeletes($ids); } /** * Action to show when attemptying to edit a record that is locked. */ public function admin_locked(){ $this->set('title_for_layout', __('This content is currently locked', true)); } }<file_sep><?php /* Module Test cases generated on: 2010-03-13 11:03:28 : 1268471188*/ App::import('Model', 'management.Module'); /** * * */ class ModuleTest extends Module{ public $useDbConfig = 'test'; } class ModuleTestCase extends CakeTestCase { public $fixtures = array( 'plugin.management.module_position', 'plugin.management.module', 'plugin.management.theme', 'plugin.management.group', 'plugin.management.route', 'plugin.management.modules_route', ); public function startTest() { $this->Module = new ModuleTest(); } public function testGet(){ $this->assertEqual(array(), $this->Module->getModules()); $result = $this->Module->getModules('top'); //pr($result); } public function endTest() { unset($this->Module); ClassRegistry::flush(); } }<file_sep><?php /** * Static Page Admin index * * Creating and maintainig static pages * * Copyright (c) 2010 <NAME> ( dogmatic69 ) * * @filesource * @copyright Copyright (c) 2010 <NAME> ( dogmatic69 ) * @link http://www.infinitas-cms.org * @package management * @subpackage management.views.admin_index * @license http://www.opensource.org/licenses/mit-license.php The MIT License * @since 0.7a * * @author dakota * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. */ echo $this->Form->create( 'Page', array( 'url' => array( 'controller' => 'pages', 'action' => 'mass', 'admin' => 'true' ) ) ); $massActions = $this->Core->massActionButtons( array( 'add', 'edit', 'copy', 'delete' ) ); echo $this->Infinitas->adminIndexHead($filterOptions, $massActions); if(!$writable){ ?> <div class="error-message"> <?php sprintf(__('Please ensure that %s is writable by the web server.', true), $path); ?> </div><?php } ?> <div class="table"> <table class="listing" cellpadding="0" cellspacing="0"> <?php echo $this->Core->adminTableHeader( array( $this->Form->checkbox( 'all' ) => array( 'class' => 'first', 'style' => 'width:25px;' ), $this->Paginator->sort( 'name' ), $this->Paginator->sort( 'file_name' ) ) ); $id = 0; foreach ( $pages as $page ){ ?> <tr class="<?php echo $this->Core->rowClass(); ?>"> <td><?php echo $this->Form->checkbox( 'Page.'.$id.'.id', array('value' => $page['Page']['file_name']) ); ?>&nbsp;</td> <td> <?php echo $this->Html->link( Inflector::humanize($page['Page']['name']), array('controller' => 'pages', 'action' => 'edit', $page['Page']['file_name'])); ?>&nbsp; </td> <td> <?php echo $page['Page']['file_name']; ?>&nbsp; </td> </tr><?php $id++; } ?> </table> <?php echo $this->Form->end(); ?> </div> <?php echo $this->element('pagination/admin/navigation'); ?><file_sep><?php $this->Session->flash('auth'); echo $this->Form->create('User'); if(Configure::read('Website.login_type') == 'email'){ echo $this->Form->input('email'); } else{ echo $this->Form->input('username'); } echo $this->Form->input('password'); echo $this->Form->end('Login'); ?><file_sep><?php /* * Short Description / title. * * Overview of what the file does. About a paragraph or two * * Copyright (c) 2010 <NAME> ( dogmatic69 ) * * @filesource * @copyright Copyright (c) 2010 <NAME> ( dogmatic69 ) * @link http://www.infinitas-cms.org * @package {see_below} * @subpackage {see_below} * @license http://www.opensource.org/licenses/mit-license.php The MIT License * @since {check_current_milestone_in_lighthouse} * * @author {your_name} * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. */ if(!isset($comment)){ return false; } $comment = isset($comment['Comment']) ? $comment['Comment'] : $comment; $comment['comment'] = str_replace('\\n', '', strip_tags($comment['comment'])); if($this->plugin != 'comments'){ $comment['comment'] = $this->Text->truncate($comment['comment'], 350); } ?> <div class="comment"> <h4> <?php if(isset($comment['website']) && isset($comment['username'])){ echo $this->Html->link( $comment['username'], $comment['website'], array('rel' => 'nofollow') ); } else if(isset($comment['username'])){ echo $comment['username']; } ?> <small><?php echo $this->Time->timeAgoInWords($comment['created']); ?></small> </h4> <?php echo $this->Gravatar->image($comment['email'], array('size' => '50')); ?> <p><?php echo $comment['comment']; ?></p> </div><file_sep><?php /** * @brief Contact plugin Branches controller. * * controller to manage branches in the company. * * @copyright Copyright (c) 2010 <NAME> ( dogmatic69 ) * @link http://www.infinitas-cms.org * @package Infinitas.Contact.controllers * @license http://www.opensource.org/licenses/mit-license.php The MIT License * @since 0.7a * * @author dogmatic69 * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. */ class BranchesController extends ContactAppController{ /** * The name of the class * * @var string * @access public */ public $name = 'Branches'; /** * The Branch model * * @var Branch * @access public */ public $Branch; /** * @todo remove recursive 0 */ public function index(){ $this->Branch->recursive = 0; $branches = $this->paginate( null, $this->Filter->filter ); if (empty($branches)) { $this->Session->setFlash(__('There are no contact details available', true)); $this->redirect($this->referer()); } if (count($branches) == 1) { $this->redirect(array('action' => 'view', 'slug' => $branches[0]['Branch']['slug'], 'id' => $branches[0]['Branch']['id'])); } $filterOptions = $this->Filter->filterOptions; $filterOptions['fields'] = array( 'name' ); $this->set(compact('branches','filterOptions')); } public function view(){ if (!isset($this->params['slug'])) { $this->Session->setFlash( __('A problem occured', true) ); $this->redirect($this->referer()); } $branch = $this->Branch->find( 'first', array( 'conditions' => array( 'Branch.slug' => $this->params['slug'], 'Branch.active' => 1 ), 'contain' => array( 'Address' => array( 'fields' => array( 'Address.address' ), 'Country' => array( 'fields' => array( 'Country.name' ) ) ), 'Contact' ) ) ); if (empty($branch)) { $this->Session->setFlash( __('The branch does not exsit', true) ); $this->redirect($this->referer()); } $title_for_layout = sprintf(__('Contact us at %s', true), $branch['Branch']['name']); $this->set(compact('branch', 'title_for_layout')); } public function admin_index(){ $branches = $this->paginate( null, $this->Filter->filter ); $filterOptions = $this->Filter->filterOptions; $filterOptions['fields'] = array( 'name', 'active' => (array)Configure::read('CORE.active_options') ); $this->set(compact('branches','filterOptions')); } public function admin_add(){ parent::admin_add(); //$timeZones = $this->Branch->TimeZone->find('list'); $this->set(compact('timeZones')); } public function admin_edit($id = null){ parent::admin_edit(); //$timeZones = $this->Branch->TimeZone->find('list'); $this->set(compact('timeZones')); } }<file_sep><?php $class = implode('.', array($plugin, $name)); $schema = ClassRegistry::init($class)->_schema; $validationIgnore = array( 'slug', 'views', 'ordering', 'active', 'locked', 'locked_by', 'locked_since', 'deleted', 'deleted_date', 'created_by', 'modified_by' ); $_order = $_belongsTo = null; $possibleFileFields = array('file', 'image'); echo "<?php\n". "\t/**\n". "\t * $name model\n". "\t *\n". "\t * Add some documentation for $name model.\n". "\t *\n". "\t * Copyright (c) {yourName}\n". "\t *\n". "\t * Licensed under The MIT License\n". "\t * Redistributions of files must retain the above copyright notice.\n". "\t *\n". "\t * @filesource\n". "\t * @copyright Copyright (c) 2009 {yourName}\n". "\t * @link http://infinitas-cms.org\n". "\t * @package $plugin\n". "\t * @subpackage $plugin.models.$name\n". "\t * @license http://www.opensource.org/licenses/mit-license.php The MIT License\n". "\t */\n\n". "\tclass $name extends {$plugin}AppModel {\n". "\t\tvar \$name = '$name';\n"; if ($useDbConfig != 'default'){ echo "\t\tvar \$useDbConfig = '$useDbConfig';\n"; } if ($useTable && $useTable !== Inflector::tableize($name)){ echo "\t\tvar \$useTable = '$useTable';\n"; } if ($primaryKey !== 'id'){ echo "\t\tvar \$primaryKey = '$primaryKey';\n"; } if ($displayField){ echo "\t\tvar \$displayField = '$displayField';\n"; } echo "\t\tvar \$actsAs = array(\n"; foreach ($schema as $field => $data){ switch($field){ case 'ordering': echo "\t\t\t'Libs.Sequence' => array(\n". "\t\t\t\t'group_fields' => array(\n". "\t\t\t\t\t/* Add parent field here */\n". "\t\t\t\t)\n". "\t\t\t),\n"; break; case 'slug': echo "\t\t\t'Libs.Sluggable' => array(\n"; if ($displayField) { echo "\t\t\t\t'label' => array('$displayField')\n"; } echo "\t\t\t),\n"; break; case 'deleted': echo "\t\t\t'Libs.SoftDeletable',\n"; break; case 'views': echo "\t\t\t'Libs.Viewable',\n"; break; case 'lft': echo "\t\t\t'Tree',\n"; $_order = "\t\t'{$name}.lft' => 'ASC'\n"; break; case 'image': echo "\t\t\t'MeioUpload.MeioUpload' => array(\n". "\t\t\t\t'image' => array(\n". "\t\t\t\t\t'dir' => 'img{DS}content{DS}thinkmoney{DS}creditcards{DS}{ModelName}',\n". "\t\t\t\t\t'create_directory' => true,\n". "\t\t\t\t\t'allowed_mime' => array(\n". "\t\t\t\t\t\t'image/jpeg',\n". "\t\t\t\t\t\t'image/pjpeg',\n". "\t\t\t\t\t\t'image/png'\n". "\t\t\t\t\t),\n". "\t\t\t\t\t'allowed_ext' => array(\n". "\t\t\t\t\t\t'.jpg',\n". "\t\t\t\t\t\t'.jpeg',\n". "\t\t\t\t\t\t'.png'\n". "\t\t\t\t\t)\n". "\t\t\t\t)\n". "\t\t\t),\n"; break; case 'file': echo "\t\t\t'MeioUpload.MeioUpload' => array(\n". "\t\t\t\t'image' => array(\n". "\t\t\t\t\t'dir' => 'img{DS}content{DS}thinkmoney{DS}creditcards{DS}{ModelName}',\n". "\t\t\t\t\t'create_directory' => true,\n". "\t\t\t\t\t'allowed_mime' => array(\n". "\t\t\t\t\t\t/** add mime types */\n". "\t\t\t\t\t),\n". "\t\t\t\t\t'allowed_ext' => array(\n". "\t\t\t\t\t\t/** add extentions */\n". "\t\t\t\t\t)\n". "\t\t\t\t)\n". "\t\t\t),\n"; break; } // switch } // end foreach echo "\t\t\t// 'Libs.Feedable',\n". "\t\t\t// 'Libs.Commentable',\n". "\t\t\t// 'Libs.Rateable\n"; echo "\t\t);\n\n"; //end actsAs echo "\t\tvar \$order = array(\n". $_order. "\t\t);\n\n"; foreach (array('hasOne', 'belongsTo') as $assocType){ echo "\t\tvar \$$assocType = array(\n"; if ($assocType == 'belongsTo') { echo $_belongsTo; } if (!empty($associations[$assocType])){ $typeCount = count($associations[$assocType]); foreach ($associations[$assocType] as $i => $relation){ $out = "\t\t\t'{$relation['alias']}' => array(\n"; $out .= "\t\t\t\t'className' => '{$relation['className']}',\n"; $out .= "\t\t\t\t'foreignKey' => '{$relation['foreignKey']}',\n"; $out .= "\t\t\t\t'conditions' => '',\n"; $out .= "\t\t\t\t'fields' => '',\n"; $out .= "\t\t\t\t'order' => '',\n"; if ($assocType == 'belongsTo') { $relatedSchema = ClassRegistry::init($relation['className'])->_schema; $relatedCounterCache = false; $relatedActive = false; $relatedDeleted = false; foreach($relatedSchema as $field => $data){ if (strstr($field, '_count')) { $relatedCounterCache = true; } if ($field == 'active') { $relatedActive = true; } else if ($field == 'active') { $relatedDeleted = true; } } if ($relatedCounterCache) { $out .= "\t\t\t\t'counterCache' => true,\n"; } if ($relatedActive || $relatedDeleted) { $out .= "\t\t\t\t'counterScope' => array(\n"; if ($relatedActive) { $out .= "\t\t\t\t\t'{$name}.active' => 1\n"; } if ($relatedDeleted) { $out .= "\t\t\t\t\t'{$name}.deleted' => 1\n"; } $out .= "\t\t\t\t),\n"; } } $out .= "\t\t\t)"; if ($i + 1 < $typeCount) { $out .= ",\n"; } else{ $out .= "\n"; } echo $out; } } echo "\t\t);\n\n"; } echo "\t\tvar \$hasMany = array(\n"; if (!empty($associations['hasMany'])){ $belongsToCount = count($associations['hasMany']); foreach ($associations['hasMany'] as $i => $relation){ $out = "\t\t\t'{$relation['alias']}' => array(\n"; $out .= "\t\t\t\t'className' => '{$relation['className']}',\n"; $out .= "\t\t\t\t'foreignKey' => '{$relation['foreignKey']}',\n"; $out .= "\t\t\t\t'dependent' => false,\n"; $out .= "\t\t\t\t'conditions' => '',\n"; $out .= "\t\t\t\t'fields' => '',\n"; $out .= "\t\t\t\t'order' => '',\n"; $out .= "\t\t\t\t'limit' => '',\n"; $out .= "\t\t\t\t'offset' => '',\n"; $out .= "\t\t\t\t'exclusive' => '',\n"; $out .= "\t\t\t\t'finderQuery' => '',\n"; $out .= "\t\t\t\t'counterQuery' => ''\n"; $out .= "\t\t\t)"; if ($i + 1 < $belongsToCount) { $out .= ",\n"; } else{ $out .= "\n"; } echo $out; } } echo "\t\t);\n\n"; echo "\t\tvar \$hasAndBelongsToMany = array(\n"; if (!empty($associations['hasAndBelongsToMany'])){ $habtmCount = count($associations['hasAndBelongsToMany']); foreach ($associations['hasAndBelongsToMany'] as $i => $relation){ $out = "\t\t\t'{$relation['alias']}' => array(\n"; $out .= "\t\t\t\t'className' => '{$relation['className']}',\n"; $out .= "\t\t\t\t'joinTable' => '{$relation['joinTable']}',\n"; $out .= "\t\t\t\t'foreignKey' => '{$relation['foreignKey']}',\n"; $out .= "\t\t\t\t'associationForeignKey' => '{$relation['associationForeignKey']}',\n"; $out .= "\t\t\t\t'unique' => true,\n"; $out .= "\t\t\t\t'conditions' => '',\n"; $out .= "\t\t\t\t'fields' => '',\n"; $out .= "\t\t\t\t'order' => '',\n"; $out .= "\t\t\t\t'limit' => '',\n"; $out .= "\t\t\t\t'offset' => '',\n"; $out .= "\t\t\t\t'finderQuery' => '',\n"; $out .= "\t\t\t\t'deleteQuery' => '',\n"; $out .= "\t\t\t\t'insertQuery' => ''\n"; $out .= "\t\t\t)"; if ($i + 1 < $habtmCount) { $out .= ",\n"; } else{ $out .= "\n"; } echo $out; } } echo "\t\t);\n\n"; echo "\t\tfunction __construct(\$id = false, \$table = null, \$ds = null) {\n"; echo "\t\t\tparent::__construct(\$id, \$table, \$ds);\n\n"; echo "\t\t\t\$this->validate = array(\n"; if (!empty($validate)){ foreach ($validate as $field => $validations){ if (in_array($field, $validationIgnore) || preg_match('/[a-z_]+_count/i', $field)) { continue; } echo "\t\t\t\t'$field' => array(\n"; foreach ($validations as $key => $validator){ echo "\t\t\t\t\t'$key' => array(\n"; echo "\t\t\t\t\t\t'rule' => array('$validator'),\n"; echo "\t\t\t\t\t\t//'message' => 'Your custom message here',\n"; echo "\t\t\t\t\t\t//'allowEmpty' => false,\n"; echo "\t\t\t\t\t\t//'required' => false,\n"; echo "\t\t\t\t\t\t//'last' => false, // Stop validation after this rule\n"; echo "\t\t\t\t\t\t//'on' => 'create', // Limit validation to 'create' or 'update' operations\n"; echo "\t\t\t\t\t),\n"; } echo "\t\t\t\t),\n"; } } echo "\t\t\t);\n"; echo "\t\t}\n"; echo "\t}\n"; echo '?>'; ?><file_sep><?php class TrashController extends TrashAppController { var $name = 'Trash'; function beforeFilter(){ parent::beforeFilter(); if(isset($this->params['form']['action']) && $this->params['form']['action'] == 'cancel'){ unset($this->params['form']['action']); $this->redirect(array_merge(array('action' => 'list_items'), $this->params['named'])); } } /** * List all table with deleted in the schema */ function admin_index(){ $this->paginate = array( 'contain' => array( 'User' ) ); $trashed = $this->paginate(null, $this->Filter->filter); $filterOptions = $this->Filter->filterOptions; $filterOptions['fields'] = array( 'name', 'type', 'deleted_by' => $this->Trash->User->find('list') ); $this->set(compact('trashed', 'filterOptions')); } function __massActionRestore($ids) { if($this->Trash->restore($ids)) { $this->notice( __('The items have been restored', true), array( 'redirect' => true ) ); } else { $this->notice( __('The items could not be restored', true), array( 'level' => 'error', 'redirect' => true ) ); } } }<file_sep><?php /** * manage the plugins on the site * * Copyright (c) 2009 <NAME> ( dogmatic69 ) * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. * * @filesource * @copyright Copyright (c) 2009 <NAME> ( dogmatic69 ) * @link http://infinitas-cms.org * @package sort * @subpackage sort.comments * @license http://www.opensource.org/licenses/mit-license.php The MIT License * @since 0.5a */ echo $this->Form->create('Plugin', array('action' => 'mass')); $massActions = $this->Infinitas->massActionButtons( array( 'install', 'uninstall', 'toggle', 'delete' ) ); echo $this->Infinitas->adminIndexHead($filterOptions, $massActions); ?> <div class="table"> <table class="listing" cellpadding="0" cellspacing="0"> <?php echo $this->Infinitas->adminTableHeader( array( $this->Form->checkbox('all') => array( 'class' => 'first', 'style' => 'width:25px;' ), $this->Paginator->sort('name'), $this->Paginator->sort('author'), $this->Paginator->sort('license'), $this->Paginator->sort('dependancies'), $this->Paginator->sort('version'), $this->Paginator->sort('enabled'), $this->Paginator->sort('core'), $this->Paginator->sort('Installed', 'created'), $this->Paginator->sort('Updated', 'modified'), ) ); foreach ($plugins as $plugin){ ?> <tr class="<?php echo $this->Infinitas->rowClass(); ?>"> <td><?php echo $this->Form->checkbox( $plugin['Plugin']['id'] ); ?>&nbsp;</td> <td><?php echo $plugin['Plugin']['name']; ?>&nbsp;</td> <td><?php echo $this->Html->link($plugin['Plugin']['author'], $plugin['Plugin']['website']); ?>&nbsp;</td> <td><?php echo $plugin['Plugin']['license']; ?>&nbsp;</td> <td><?php echo $plugin['Plugin']['dependancies']; ?>&nbsp;</td> <td><?php echo $plugin['Plugin']['version']; ?>&nbsp;</td> <td><?php echo $this->Infinitas->status($plugin['Plugin']['enabled']); ?>&nbsp;</td> <td><?php echo $this->Infinitas->status($plugin['Plugin']['core']); ?>&nbsp;</td> <td><?php echo $this->Time->timeAgoInWords($plugin['Plugin']['created']); ?>&nbsp;</td> <td> <?php if($plugin['Plugin']['created'] == $plugin['Plugin']['modified']){ echo __('Never', true); } else{ echo $this->Time->timeAgoInWords($plugin['Plugin']['created']); } ?>&nbsp; </td> </tr> <?php } ?> </table> <?php echo $this->Form->end(); ?> </div> <?php echo $this->element('pagination/admin/navigation'); ?><file_sep><?php /* SchemaMigration Fixture generated on: 2010-08-17 14:08:37 : 1282055197 */ class SchemaMigrationFixture extends CakeTestFixture { var $name = 'SchemaMigration'; var $fields = array( 'id' => array('type' => 'integer', 'null' => false, 'default' => NULL, 'key' => 'primary'), 'version' => array('type' => 'integer', 'null' => false, 'default' => NULL), 'type' => array('type' => 'string', 'null' => false, 'default' => NULL, 'length' => 50), 'created' => array('type' => 'datetime', 'null' => false, 'default' => NULL), 'indexes' => array('PRIMARY' => array('column' => 'id', 'unique' => 1)), 'tableParameters' => array('charset' => 'utf8', 'collate' => 'utf8_general_ci', 'engine' => 'InnoDB') ); var $records = array( array( 'id' => 1, 'version' => 1, 'type' => 'migrations', 'created' => '2010-08-17 09:55:00' ), array( 'id' => 2, 'version' => 1, 'type' => 'app', 'created' => '2010-08-17 09:57:01' ), array( 'id' => 3, 'version' => 2, 'type' => 'app', 'created' => '2010-08-17 09:57:46' ), array( 'id' => 4, 'version' => 1, 'type' => 'blog', 'created' => '2010-08-17 09:58:32' ), array( 'id' => 5, 'version' => 1, 'type' => 'cms', 'created' => '2010-08-17 09:59:26' ), array( 'id' => 6, 'version' => 1, 'type' => 'contact', 'created' => '2010-08-17 09:59:38' ), array( 'id' => 7, 'version' => 1, 'type' => 'feed', 'created' => '2010-08-17 09:59:51' ), array( 'id' => 8, 'version' => 2, 'type' => 'blog', 'created' => '2010-08-17 10:06:51' ), array( 'id' => 9, 'version' => 1, 'type' => 'management', 'created' => '2010-08-17 10:08:49' ), array( 'id' => 10, 'version' => 1, 'type' => 'newsletter', 'created' => '2010-08-17 10:33:10' ), array( 'id' => 11, 'version' => 1, 'type' => 'shop', 'created' => '2010-08-17 10:33:33' ), array( 'id' => 12, 'version' => 1, 'type' => 'blog', 'created' => '2010-08-17 13:47:17' ), array( 'id' => 13, 'version' => 1, 'type' => 'cms', 'created' => '2010-08-17 13:48:14' ), array( 'id' => 14, 'version' => 1, 'type' => 'contact', 'created' => '2010-08-17 13:48:28' ), array( 'id' => 15, 'version' => 1, 'type' => 'feed', 'created' => '2010-08-17 13:49:34' ), array( 'id' => 16, 'version' => 1, 'type' => 'management', 'created' => '2010-08-17 13:49:46' ), array( 'id' => 17, 'version' => 1, 'type' => 'newsletter', 'created' => '2010-08-17 13:49:58' ), array( 'id' => 18, 'version' => 1, 'type' => 'shop', 'created' => '2010-08-17 13:50:09' ), array( 'id' => 19, 'version' => 1, 'type' => 'categories', 'created' => '2010-08-17 13:51:26' ), array( 'id' => 20, 'version' => 2, 'type' => 'app', 'created' => '2010-08-17 13:52:43' ), array( 'id' => 21, 'version' => 1, 'type' => 'order', 'created' => '2010-08-17 14:09:03' ), ); } ?><file_sep><?php echo $this->element('modules/login');<file_sep><?php /* Category Test cases generated on: 2010-08-16 23:08:27 : 1281999567*/ App::import('Model', 'Categories.Category'); class CategoryTestCase extends CakeTestCase { var $fixtures = array( 'plugin.configs.config', 'plugin.view_counter.view_count', 'plugin.categories.category', 'plugin.users.group', ); function startTest() { $this->Category = ClassRegistry::init('Categories.Category'); } function endTest() { unset($this->Category); ClassRegistry::flush(); } function testFindActive(){ $this->assertEqual(4, $this->Category->find('count')); $expected = array(1 => 1, 2 => 2, 3 => 3); $this->assertEqual($expected, $this->Category->getActiveIds()); } }<file_sep><?php /** * Model for themes * * handles the themes for infinitas finding and making sure only one can be * active at a time. * * Copyright (c) 2009 <NAME> ( dogmatic69 ) * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. * @filesource * @copyright Copyright (c) 2009 <NAME> ( dogmatic69 ) * @link http://infinitas-cms.org * @package management * @subpackage management.models.theme * @license http://www.opensource.org/licenses/mit-license.php The MIT License * @since 0.5a */ class Theme extends ThemesAppModel { public $name = 'Theme'; public $hasMay = array( 'Routes.Route' ); public function __construct($id = false, $table = null, $ds = null) { parent::__construct($id, $table, $ds); $this->validate = array( 'name' => array( 'notEmpty' => array( 'rule' => 'notEmpty', 'message' => __('Please enter the name of the them', true) ), 'isUnique' => array( 'rule' => 'isUnique', 'message' => __('There is already a them with this name', true) ) ), 'author' => array( 'notEmpty' => array( 'rule' => 'notEmpty', 'message' => __('Please enter the name of the author', true) ) ), 'url' => array( 'notEmpty' => array( 'rule' => 'notEmpty', 'message' => __('Please enter the url for this theme', true) ), 'url' => array( 'rule' => array('url', true), 'message' => __('Please enter a valid url', true) ) ) ); } /** * Get the current Theme * * @param array $conditions * @return array $theme the current theme. */ public function getCurrentTheme(){ $theme = Cache::read('current_theme', 'core'); if ($theme !== false) { return $theme; } $theme = $this->find( 'first', array( 'fields' => array( 'Theme.id', 'Theme.name', 'Theme.core' ), 'conditions' => array( 'Theme.active' => 1 ) ) ); Cache::write('current_theme', $theme, 'core'); return $theme; } /** * before saving * * if the new / edited theme is active deactivte everything. * * @return bool */ public function beforeSave(){ if(isset($this->data['Theme']['active']) && $this->data['Theme']['active']){ return $this->deactivateAll(); } return parent::beforeSave(); } /** * before deleteing * * If the theme is active do not let it be deleted. * * @param $cascade bool * @return bool true to delete, false to stop */ public function beforeDelete($cascade){ $active = $this->read('active'); return isset($active['Theme']['active']) && !$active['Theme']['active']; } /** * deactivate all themes. * * This is used before activating a theme to make sure that there is only * ever one theme active. * * @return bool true on sucsess false if not. */ public function deactivateAll(){ return $this->updateAll( array( 'Theme.active' => '0' ) ); } }<file_sep><?php final class TagsEvents extends AppEvents{ public function onAdminMenu($event){ $menu['main'] = array( 'Tags' => array('plugin' => 'tags', 'controller' => 'tags', 'action' => 'index') ); return $menu; } public function onAttachBehaviors($event) { if(is_subclass_of($event->Handler, 'Model') && isset($event->Handler->_schema) && is_array($event->Handler->_schema)) { $Model = $event->Handler; if (array_key_exists('tags', $Model->_schema)) { $Model->Behaviors->attach('Tags.Taggable'); } } } public function onRequireHelpersToLoad(){ return 'Tags.TagCloud'; } public function onRequireJavascriptToLoad($event){ return array( '/tags/js/jq-tags', '/tags/js/tags' ); } public function onRequireCssToLoad($event){ return array( '/tags/css/tags' ); } }<file_sep><?php $core = array( array( 'name' => 'Plugins', 'description' => 'View core plugins', 'icon' => '/installer/img/icon.png', 'author' => 'Infinitas', 'dashboard' => array('plugin' => 'installer', 'controller' => 'plugins', 'action' => 'index', 'Plugin.core' => 1) ), array( 'name' => 'Update', 'description' => 'Update your site', 'icon' => '/installer/img/update.png', 'author' => 'Infinitas', 'dashboard' => array('plugin' => 'installer', 'controller' => 'plugins', 'action' => 'update_infinitas') ), ); $nonCore = array( array( 'name' => 'Plugins', 'description' => 'View, install and manage your plugins', 'icon' => '/installer/img/icon.png', 'author' => 'Infinitas', 'dashboard' => array('plugin' => 'installer', 'controller' => 'plugins', 'action' => 'index', 'Plugin.core' => 0) ), array( 'name' => 'Install', 'description' => 'Install additional plugins and themes', 'icon' => '/installer/img/install.png', 'author' => 'Infinitas', 'dashboard' => array('plugin' => 'installer', 'controller' => 'plugins', 'action' => 'install') ), ); $core = $this->Menu->builDashboardLinks($core, 'plugins_core'); $nonCore = $this->Menu->builDashboardLinks($nonCore, 'plugins_non_core'); ?> <div class="dashboard grid_16"> <h1><?php echo __('Infinitas Core', true); ?></h1> <ul class="icons"><li><?php echo implode('</li><li>', current((array)$core)); ?></li></ul> </div> <div class="dashboard grid_16"> <h1><?php echo __('Plugins', true); ?></h1> <ul class="icons"><li><?php echo implode('</li><li>', current((array)$nonCore)); ?></li></ul> </div><file_sep><?php final class LocksEvents extends AppEvents{ public function onSetupCache(){ return array( 'name' => 'locks', 'config' => array( 'prefix' => 'locks.' ) ); } public function onSetupConfig(){ return Configure::load('locks.config'); } public function onAdminMenu($event){ $menu['main'] = array( 'Locks' => array('plugin' => 'locks', 'controller' => 'locks', 'action' => 'index') ); return $menu; } public function onRequireComponentsToLoad($event){ return array( 'Locks.Locker' ); } public function onRequireHelpersToLoad($event){ return array( 'Locks.Locked' ); } public function onAttachBehaviors($event = null) { if(is_subclass_of($event->Handler, 'Model') && isset($event->Handler->_schema) && is_array($event->Handler->_schema)) { if (isset($event->Handler->lockable) && $event->Handler->lockable && !$event->Handler->Behaviors->enabled('Locks.Lockable')) { $event->Handler->Behaviors->attach('Locks.Lockable'); } } } public function onSetupRoutes(){ Router::connect('/admin/content-locked', array('plugin' => 'locks', 'controller' => 'locks', 'action' => 'locked', 'admin' => true, 'prefix' => 'admin')); } }<file_sep><?php /** * Configuration file for the Script Combiner helper. This file is used to determine * the behaviour of the helper. * * @author <NAME> * @version 0.1 */ Configure::write('Asset.timestamp', true); /** * Indicates whether CSS files should be combined. Set to false to disable * CSS combination. */ $config['ScriptCombiner']['combineCss'] = true; /** * Indicates whether Javascript files should be combined. Set to false to disable * Javascript combination. */ $config['ScriptCombiner']['combineJs'] = true; /** * Indicates whether CSS files should be compressed. Set to false to disable CSS * compression. */ $config['ScriptCombiner']['compressCss'] = true; /** * Indicates whether Javascript files should be compressed. Set to false to disable * Javascript compression. * * jsmin.php is very slow, adding 6 seconds to a page load (xhprof) and breaks debugkit */ $config['ScriptCombiner']['compressJs'] = true; /** * Indicates how long the combined cache files should exist for. If an integer is * supplied] = then it is supplied as the number of seconds the file should be cached * for. Otherwise] = it is assumed a valid strtotime() value is supplied. Set to * -1 to disable caching. */ $config['ScriptCombiner']['cacheLength'] = '1 year'; /** * Sets the path to the cached CSS combined file. Must be a directory] = and must * be a valid directory on the local machine. */ $config['ScriptCombiner']['cssCachePath'] = CSS . 'combined' . DS; /** * Sets the path to the cached Javascript combined file. Must be a directory, * and must be a valid directory on the local machine. */ $config['ScriptCombiner']['jsCachePath'] = JS . 'combined' . DS; /** * The string to use when combining multiple to separator file contents. This is * mainly used when files are not compressed] = and you're looking to see where * the file joins are. */ $config['ScriptCombiner']['fileSeparator'] = "\n\n/** FILE SEPARATOR **/\n\n"; <file_sep><?php class GoogleAppHelper extends AppHelper{ public function __construct($options = array()){ $default = array( 'cachePath' => dirname(dirname(dirname(__FILE__))).DS.'webroot'.DS.'img'.DS.get_class($this).DS, 'cacheImagePath' => '/google/img/'.get_class($this).'/' ); $options = array_merge($default, $options); $this->cachePath = $options['cachePath']; $this->cacheImagePath = $options['cacheImagePath']; } protected function _checkCache($data){ $file = sha1(serialize($data)).'.png'; if (is_file($this->cachePath.$file)){ return $this->Html->image($this->cacheImagePath.$file ); } return false; } protected function _writeCache($data, $url){ $file = sha1(serialize($data)).'.png'; if(is_writable($this->cachePath)){ $contents = file_get_contents($url); $fp = fopen($this->cachePath.$file, 'w'); fwrite($fp, $contents); fclose($fp); if (!is_file($this->cachePath.$file)){ $this->__errors[] = __('Could not create the cache file', true); } } } } <file_sep><?php /** * */ class Address extends ManagementAppModel{ var $name = 'Address'; var $virtualFields = array( 'address' => 'CONCAT(Address.street, ", ", Address.city, ", ", Address.province)' ); var $belongsTo = array( 'Management.Country', //'Management.Continent' ); function getAddressByUser($user_id = null, $type = 'list'){ if(!$user_id){ return false; } $contain = array(); if($type === 'all'){ $contain = array( 'Country' ); } $address = $this->find( $type, array( 'conditions' => array( 'Address.foreign_key' => $user_id, 'Address.plugin' => 'management', 'Address.model' => 'user' ), 'contain' => $contain ) ); return $address; } }<file_sep><?php $model = isset($model) ? $model : $this->params['models'][0]; $model = ClassRegistry::init($model)->plugin . '.' . ClassRegistry::init($model)->alias; $layouts = ClassRegistry::init($model)->GlobalContent->GlobalLayout->find( 'list', array( 'conditions' => array( 'model' => $model ) ) ); $groups = array(0 => __('Public', true)) + ClassRegistry::init($model)->GlobalContent->Group->find('list'); ?> <fieldset> <h1><?php echo __('Content', true); ?></h1><?php echo $this->Form->input('GlobalContent.id'); echo $this->Form->hidden('GlobalContent.model', array('value' => $model)); echo $this->Form->input('GlobalContent.title'); echo $this->Form->input('GlobalContent.layout_id', array('options' => $layouts, 'empty' => Configure::read('Website.empty_select'))); echo $this->Form->input('GlobalContent.group_id', array('options' => $groups, 'label' => __('Min Group', true))); echo $this->Infinitas->wysiwyg('GlobalContent.body'); ?> </fieldset> <fieldset> <h1><?php echo __('Meta Data', true); ?></h1><?php echo $this->Form->input('GlobalContent.meta_keywords'); echo $this->Form->input('GlobalContent.meta_description'); ?> </fieldset><file_sep><div class="dashboard"> <h1>Problem with your event.</h1> <p><b>Message:</b> <?php echo $params['message']; ?></p> <p><b>Event:</b> <?php echo 'on', ucfirst(key($params['event'])); ?></p> <p>Check your config and try again.</p> </div>
a5ccddf5d4cec21efede792d924cecb4a652b7e6
[ "JavaScript", "PHP" ]
307
PHP
jellehenkens/infinitas
40ca743f9e896f75ac06f820f0b9c5bac642f6e3
0a6b396801301685e0b152a9440d3e8acfe40a04
refs/heads/master
<repo_name>clockworkbits/SectionedListView<file_sep>/src/com/clockworkbits/sectionedlistview/MainFragment.java package com.clockworkbits.sectionedlistview; import java.util.LinkedList; import java.util.List; import android.app.Fragment; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ListView; public class MainFragment extends Fragment { @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_main, container, false); ListView listView = (ListView) view.findViewById(R.id.list); listView.setAdapter(new SectionedAdapter(getActivity(), getDataList())); return view; } private List<Object> getDataList() { List<Object> list = new LinkedList<Object>(); list.add(new Country("Australia")); list.add(new City("Melbourne")); list.add(new City("Perth")); list.add(new City("Sydney")); list.add(new Country("Germany")); list.add(new City("Aachen")); list.add(new City("Berlin")); list.add(new City("Munich")); list.add(new Country("Spain")); list.add(new City("Barcelona")); list.add(new City("Madrit")); list.add(new Country("Italy")); list.add(new City("Rome")); list.add(new City("Milan")); list.add(new City("Naples")); list.add(new City("Turin")); list.add(new City("Palermo")); list.add(new Country("Switzerland")); list.add(new City("Zčrich")); list.add(new City("Geneva")); list.add(new City("Basel")); list.add(new City("Lausanne")); list.add(new City("Bern")); list.add(new Country("Poland")); list.add(new City("Warsaw")); list.add(new City("Cracow")); list.add(new City("Lodz")); list.add(new City("Wroclaw")); list.add(new City("Poznan")); return list; } } <file_sep>/src/com/clockworkbits/sectionedlistview/City.java package com.clockworkbits.sectionedlistview; public class City { private final String mName; public City(String name) { mName = name; } public String getName() { return mName; } } <file_sep>/src/com/clockworkbits/sectionedlistview/SectionedAdapter.java package com.clockworkbits.sectionedlistview; import java.util.List; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.TextView; public class SectionedAdapter extends ArrayAdapter<Object> { private static final int TYPE_SECTION = 0; private static final int TYPE_ITEM = 1; public SectionedAdapter(Context context, List<Object> items) { super(context, 0, items); } @Override public View getView(int position, View convertView, ViewGroup parent) { if (getItemViewType(position) == TYPE_SECTION) { if (convertView == null) { convertView = LayoutInflater.from(getContext()).inflate(R.layout.list_section, null); } Country country = (Country) getItem(position); TextView section = (TextView) convertView.findViewById(R.id.section_text); section.setText(country.getName()); } else { if (convertView == null) { convertView = LayoutInflater.from(getContext()).inflate(R.layout.list_item, null); } City city = (City) getItem(position); TextView item = (TextView) convertView.findViewById(R.id.item_text); item.setText(city.getName()); } return convertView; } @Override public int getItemViewType(int position) { Object object = getItem(position); if (object instanceof Country) { return TYPE_SECTION; } else { return TYPE_ITEM; } } @Override public int getViewTypeCount() { return 2; // Section type & item type } @Override public boolean areAllItemsEnabled() { return false; } @Override public boolean isEnabled(int position) { return getItemViewType(position) == TYPE_ITEM ? true : false; // Only the items are clickable } } <file_sep>/src/com/clockworkbits/sectionedlistview/Country.java package com.clockworkbits.sectionedlistview; public class Country { private final String mName; public Country(String name) { mName = name; } public String getName() { return mName; } }
4e3444fb97f5397dcc7ab7797429f15f251422c4
[ "Java" ]
4
Java
clockworkbits/SectionedListView
85f8b1f00dbc99c025dd4d54a57afc72a2825673
d2c4adc7d26b93316d934216839451fbc2324dbf
refs/heads/master
<file_sep>#!/usr/bin/python3.6 # -*- coding: utf-8 -*- __author__ = '<NAME>' __version__ = "0.1.0" import censys.certificates from ipaddress import ip_network, ip_address import geoip2.database import censys.ipv4 import yaml from functools import reduce import censys import socket import time import requests from datetime import datetime, timedelta, date import json import os import csv import logging import argparse import base64 import sqlite3 import collections import urllib.request class DataBase: def __init__(self, database_path=None, database_name=None, ): self.logger = logging.getLogger('Database') self.logger.info('Checking Database.') self.database_path = database_path self.database_name = database_name if not os.path.exists('{path}/{filename}'.format(path=self.database_path, filename=self.database_name)): conn = sqlite3.connect('{path}/{filename}'.format(path=self.database_path, filename=self.database_name)) cursor = conn.cursor() cursor.execute('CREATE TABLE IF NOT EXISTS DOMAINNAMES ( id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT UNIQUE,' 'domain TEXT, type TEXT, subdomain TEXT, local TEXT, status_code TEXT, ipv4 TEXT, autonomous_system_number TEXT, autonomous_system_organization TEXT, iso_code TEXT, country_name TEXT, most_specific TEXT, city_name TEXT, latitude TEXT, longitude TEXT);') conn.commit() conn.close() else: conn = sqlite3.connect('{path}/{filename}'.format(path=self.database_path, filename=self.database_name)) cursor = conn.cursor() cursor.execute('CREATE TABLE IF NOT EXISTS DOMAINNAMES ( id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT UNIQUE,' 'domain TEXT, type TEXT, subdomain TEXT, local TEXT, status_code TEXT, ipv4 TEXT, autonomous_system_number TEXT, autonomous_system_organization TEXT, iso_code TEXT, country_name TEXT, most_specific TEXT, city_name TEXT, latitude TEXT, longitude TEXT);') conn.commit() conn.close() def compare(self, subdomain=None): """ In order not to generate unnecessary requests anymore, a comparison is made in a sqllite database, preventing it from making requests, in subdomains that we already have information. """ self.logger.debug('Comparing SCAN with what you already have in the database.') conn = sqlite3.connect('{path}/{filename}'.format(path=self.database_path, filename=self.database_name)) cursor = conn.cursor() r = cursor.execute("SELECT * FROM DOMAINNAMES WHERE subdomain='{subdomain}';".format(subdomain=subdomain)) return r.fetchall() def save(self, domain=None, type=None, subdomain=None, local=None, status_code=None, ipv4=None, autonomous_system_number=None, autonomous_system_organization=None, iso_code=None, country_name=None, most_specific=None, city_name=None, latitude=None, longitude=None): """ If the subdomain does not exist in the database, it is saved. """ self.logger.debug('Saving the SUBDOMAINS in the database..') conn = sqlite3.connect('{path}/{filename}'.format(path=self.database_path, filename=self.database_name)) cursor = conn.cursor() cursor.execute(""" INSERT INTO DOMAINNAMES (domain, type, subdomain, local, status_code, ipv4, autonomous_system_number, autonomous_system_organization, iso_code, country_name, most_specific, city_name, latitude, longitude) VALUES ('%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s') """ % (domain, type, subdomain, local, status_code, ipv4, autonomous_system_number, autonomous_system_organization, iso_code, country_name, most_specific, city_name, latitude, longitude)) conn.commit() conn.close() class GetDomains: def __init__(self, apid=None, secret=None, database_path=None, database_name=None, splunk_dir=None, debug=None, checkcidr=None, CIDR=None, target=None): self.apid = apid self.secret = secret self.database_path = database_path self.database_name = database_name self.splunk_dir = splunk_dir self.debug = debug self.checkcidr = checkcidr self.CIDR = CIDR self.target = target self.database = DataBase(database_path=self.database_path, database_name=self.database_name ,) if debug: logging.basicConfig( level=logging.INFO, format='%(asctime)s.%(msecs)03d %(levelname)s %(module)s - %(funcName)s: %(message)s', datefmt='%Y-%m-%d %H:%M:%S', ) else: logging.basicConfig( level=logging.DEBUG, format='%(asctime)s.%(msecs)03d %(levelname)s %(module)s - %(funcName)s: %(message)s', datefmt='%Y-%m-%d %H:%M:%S', ) self.logger = logging.getLogger('XP Domains name') self.censys_certificates = censys.certificates.CensysCertificates(api_id=self.apid, api_secret=self.secret) self.session = requests.session() def subs(self, domain=None): """ Obtains all subdomains from the censys.io site through the SSL certificate and WildCard used by the company. To get subdomains the free API version, which has a daily limit, is used. For more information go to https://censys.io/demo-request """ if domain is not None: try: certificate_query = 'parsed.names: %s' % domain certificates_search_results = self.censys_certificates.search(certificate_query, fields=['parsed.subject.common_name']) subdomains = [] for search_result in certificates_search_results: subdomains.extend(search_result['parsed.subject.common_name']) return subdomains except: self.logger.error('You have reached Censys daily limit, renew your Token, as some subdomains may not be found.') pass def getlocal(self, ip=None): """ Some names are resolved internally, and to know where you are, a hint is made, pointing to CIDR and the name of the location where it is located. This also serves for public addresses.. """ if ip is not None: for cidr in self.CIDR: for ranges in cidr['group']['id'].split(','): if ip_address(ip) in ip_network(ranges): return cidr['group']['name'] def replaces_text(self, raw=None): """ In order not to generate line breaks or information that harm the database, some replaces are done. """ if raw is not None: repls = ( ('\n', r''), ('\r', r''), ('\t', r''), ('\s', r''), ) data = reduce(lambda a, kv: a.replace(*kv), repls, raw) return data @property def start(self): self.logger.info('Getting the domain target.') with open(self.target, 'r') as stream: for line in stream: self.logger.info('Searching for subdomains of {}'.format(self.replaces_text(raw=line))) templist = [] self.logger.debug('Clearing variables.') type = None sub = None local = None status_code = None ipv4 = None autonomous_system_number = None autonomous_system_organization = None iso_code = None country_name = None most_specific = None city_name = None latitude = None longitude = None name = self.replaces_text(raw=line) self.logger.info('Getting subdomains in censys.') list = self.subs(domain=name) self.logger.debug('Clearing information and removing duplicates.') if list is not None: mylist = self.clearlist( list=list, domain=name) templist.extend(mylist) # Resolve os nomes, para obter os endereços IPS self.logger.info('Getting subdomains from VirusTotal.') virustotallist = self.virustotal(domain=name) templist.extend(self.removeDuplicate(list=virustotallist)) self.logger.info('Getting information from all subdomains found. WAIT...') for sub in templist: if self.database.compare(subdomain=sub): self.logger.debug('The domain {} is already in the database.'.format(sub)) else: if 'Not Found' in self.getmyIP(domain=sub): status_code = "404" else: try: type = "Public" local = self.getlocal(ip=self.getmyIP(domain=sub)) try: status_code = urllib.request.urlopen("http://"+sub).getcode() except (ConnectionResetError,urllib.error.URLError) as e: status_code = "404" reader = geoip2.database.Reader('utils/GeoLite2-ASN.mmdb') response = reader.asn(self.getmyIP(domain=sub)) autonomous_system_number = response.autonomous_system_number autonomous_system_organization = response.autonomous_system_organization reader = geoip2.database.Reader('utils/GeoLite2-City.mmdb') response = reader.city(self.getmyIP(domain=sub)) iso_code = response.country.iso_code country_name = response.country.name most_specific = response.subdivisions.most_specific.name city_name = response.city.name latitude = response.location.latitude longitude = response.location.longitude except (geoip2.errors.AddressNotFoundError) as e: local = self.getlocal(ip=str(self.getmyIP(domain=sub))) type = "Private" try: status_code = urllib.request.urlopen("http://"+sub).getcode() except (ConnectionResetError,urllib.error.URLError) as e: status_code = "404" type = type if type is not None else "Null" sub = sub if sub is not None else "Null" local = local if local is not None else "Null" status_code = status_code if status_code is not None else "Null" ipv4 = self.getmyIP(domain=sub) if self.getmyIP(domain=sub) is not None else "Null" ASN = "ASN{}".format(autonomous_system_number) if autonomous_system_number is not None else "Null" autonomous_system_organization = autonomous_system_organization if autonomous_system_organization is not None else "Null" iso_code = iso_code if iso_code is not None else "Null" country_name = country_name if country_name is not None else "Null" most_specific = most_specific if most_specific is not None else "Null" city_name = city_name if city_name is not None else "Null" latitude = latitude if latitude is not None else "Null" longitude = longitude if longitude is not None else "Null" data ={ "domain": name, "type": type, "subdomain": sub, "local": local, "status_code": status_code, "ipv4": ipv4, "autonomous_system_number": ASN, "autonomous_system_organization": autonomous_system_organization, "iso_code": iso_code, "country_name": country_name, "most_specific": most_specific, "city_name":city_name, "latitude": latitude, "longitude": longitude, } self.logger.debug('Saving the domain {} in the database.'.format(sub)) self.database.save( domain=name, type=type, subdomain=sub, local=local, status_code=status_code, ipv4= ipv4, autonomous_system_number=ASN, autonomous_system_organization=autonomous_system_organization, iso_code=iso_code, country_name=country_name, most_specific=most_specific, city_name=city_name, latitude=latitude, longitude=longitude) self.logs_save_splunk = '{0}/finish-splunk-domainsnames-{1}.json'.format(self.splunk_dir, datetime.now().strftime("%Y-%m-%d-%H-%M-%S-%f")) self.logger.info('Saving file to {}.'.format(self.logs_save_splunk)) if not os.path.exists(self.logs_save_splunk): arquivo = open(self.logs_save_splunk, 'w', encoding="utf-8") arquivo.close() arquivo = open(self.logs_save_splunk, 'r', encoding="utf-8") conteudo = arquivo.readlines() conteudo.append(json.dumps(data, ensure_ascii=False)+'\n') arquivo = open(self.logs_save_splunk, 'w', encoding="utf-8") arquivo.writelines(conteudo) arquivo.close() def getmyIP(self,domain=None): """ To get additional information about the subdomain, you need to convert it to IPV4. """ if domain is not None: try: self.logger.debug('Getting IPV4 Address from Domain {}'.format(domain)) return socket.gethostbyname(domain) except (socket.gaierror) as e: self.logger.debug('Could not get domain IPV4 address {}'.format(domain)) return 'Not Found' def virustotal(self, domain=None): """ The virustotal API is used, for more subdomains, this is not the paid way to get information. So it is somewhat limited, if you misuse it, you'll need to go through a recap, but don't worry, I'll have warn you when that happens. There is also a daily limit, which I am not sure how much it is, because I use the same requests that the site makes. """ if domain is not None: self.logger.debug('Getting VirusTotal Information') request = self.session.get('https://www.virustotal.com/ui/domains/{}/subdomains?relationships=resolutions'.format(domain)) datajson = json.loads(request.content) names = [] try: try: myerror = datajson['message'] self.logger.error('Something went wrong with the VirusTotal API. I believe it may be the capcha or we have exceeded the daily limit.\nError: {}'.format(myerror)) exit(0) except: myerror = datajson['error'] self.logger.error('Something went wrong with the VirusTotal API. I believe it may be the capcha or we have exceeded the daily limit.\nError: {}'.format(myerror)) exit(0) except (KeyError) as e: try: for subs in datajson['data']: names.append(subs['id']) count = 0 while count <= 90: try: count = count+10 decode = "I%s\n." % (count) url = 'https://www.virustotal.com/ui/domains/{domain}/subdomains?relationships=resolutions&cursor={cursor}%3D&limit=40'.format( cursor=base64.b64encode(decode.encode('utf-8')).decode('UTF-8').replace('=',''), domain=domain) request = self.session.get(url) datajson = json.loads(request.content) for subs in datajson['data']: names.append(subs['id']) except (KeyError) as e: pass except (KeyError) as e: pass return names def removeDuplicate(self,list=None): """ Before getting information on subdomains I make a list of everything I already have, to avoid making too many requests in the APIs and eventually reach my limit, I clean up duplicate items. """ self.logger.debug('Remove Duplicate Names from List.') if list is not None: return [el for i, el in enumerate(list) if el not in list[:i]] def clearlist(self, list=None, domain=None): """ Some more information may come together, and sometimes some domains that are not our scope, so they should be removed here. """ self.logger.debug('Performing cleanup of information that is not required.') if list is not None: itens = [ 'incapsula.com', '*.{}'.format(domain), '.pantheonsite.io' ] listOfitens = [ elem for elem in list if elem not in itens ] return listOfitens class GetConfigs: def __init__(self): logging.basicConfig( level=logging.INFO, format='%(asctime)s.%(msecs)03d %(levelname)s %(module)s - %(funcName)s: %(message)s', datefmt='%Y-%m-%d %H:%M:%S', ) self.logger = logging.getLogger('Get Configs') parser = argparse.ArgumentParser() parser.add_argument('-c', '--config', help='The directory of the settings file, in Yaml format.', action='store', dest = 'config') parser.add_argument('-t', '--target', help='Enter the file location, where you have all the domains you want to verify.', action='store', dest = 'target') args = parser.parse_args() self.config = args.config self.target = args.target @property def start(self): if os.path.exists(self.config): if '.yml' in self.config: with open(self.config, 'r') as stream: data = yaml.load(stream, Loader=yaml.FullLoader) self.apid = data.get('apid', '') self.secret = data.get('secret', '') self.database_path = data.get('database_path', '') self.database_name = data.get('database_name', '') self.splunk_dir = data.get('splunk_dir', '') self.debug = data.get('debug', '') self.checkcidr = data.get('checkcidr', '') self.CIDR = data.get('CIDR', '') if self.debug: logging.basicConfig( level=logging.DEBUG, format='%(asctime)s.%(msecs)03d %(levelname)s %(module)s - %(funcName)s: %(message)s', datefmt='%Y-%m-%d %H:%M:%S', ) else: logging.basicConfig( level=logging.INFO, format='%(asctime)s.%(msecs)03d %(levelname)s %(module)s - %(funcName)s: %(message)s', datefmt='%Y-%m-%d %H:%M:%S', ) get = GetDomains(apid=self.apid, secret=self.secret, database_path=self.database_path, database_name=self.database_name, splunk_dir=self.splunk_dir, debug=self.debug, checkcidr=self.checkcidr, CIDR=self.CIDR, target=self.target) get.start else: self.logger.error('Entered file type is not valid, must be of format yml.\n') sys.exit(1) else: self.logger.error('File does not exist or path is incorrect.\n') sys.exit(1) GetConfigs().start <file_sep># SearchSubdomains Search for all available subdomains using the certificate used or even using [virustotal](https://www.virustotal.com/gui/home/upload). ## Settings This script relies on [censys.io](https://censys.io/) to work, so create a free account and get the API information. To create an account you can use a temporary email. ``` apid: 'APPID' secret: 'SECRETID' ``` If you know your public IP CIDR and would like to know which subdomains are within your network, mark `checkcidr` as` True`, and provide your CIDR as the example below: ``` CIDR: - group: name: 'MyCIDR' id: '10.1.0.0/24,10.0.0.0/24' ``` For location, ANS, and ISP information I used the [geoip2](https://dev.maxmind.com/geoip/geoip2/geolite2/) offiline as it does not have to use any API and is not dependent on daily limits. These files should be downloaded and placed in the `utils\*` folder, such as `GeoLite2-ASN.mmdb`,` GeoLite2-City.mmdb` and `GeoLite2-Country.mmdb`. ## Usage To use the script create a file with all the domains you want to discover, one below the other, like the following example: ``` google.com.br terra.com.br ``` After creating your file, use the following command to get started. ``` python SplunkSubDomains.py --config utils\config\config.yml --target target.txt ``` ## Output ``` { "domain":"petrobras.com.br", "type":"Public", "subdomain":"medusa.petrobras.com.br", "local":"Null", "status_code":"404", "ipv4":"192.168.3.11", "autonomous_system_number":"ASN23074", "autonomous_system_organization":"Petróleo Brasileiro S/A - Petrobras", "iso_code":"BR", "country_name":"Brazil", "most_specific":"Null", "city_name":"Null", "latitude":-22.8305, "longitude":-43.2192 } ```
ea7ed46427657bad3bd467ba4db1b1c311006040
[ "Markdown", "Python" ]
2
Python
andreyglauzer/SearchSubdomains
04784c5c212427c6f1493d068fc0d12580df860b
ac4250b7f4f41d5e5b2b510efcec9c340298d569
refs/heads/master
<repo_name>yana-davydenko/python<file_sep>/python2.py def function(sentence, letter): i=0 for x in sentence: if x == letter: i +=1 print('letter', i) function('never never never', 'e')
c5bfb7134df901461c32ea34abe17b4239b9f218
[ "Python" ]
1
Python
yana-davydenko/python
9822981b3985c798b55a5408919ad2a4032287bb
8ef123643b5a85af478301518cebdd0a5d341fea
refs/heads/master
<file_sep>using System; using System.IO; using System.Windows.Forms; namespace CSharpDictionaryWords { public partial class Form1 : Form { Operations operations = new Operations(); public Form1() { InitializeComponent(); operations.LoadDictionaryFile(); } private void BtnLoadWords_Click(object sender, EventArgs e) { operations.LoadDictionary(); this.Text = operations.DictionaryWords.Count.ToString(); btnSearch.Enabled = true; pbxDict.Image = Resource1.randomDudeOnZoom; } #region Old Load words code OK to delete private void LoadDictionary() { //make a counter to show how many words we have int count = 0; //'C:\Dropbox\C# Lessons 2020\CSharpDictionaryWords\Resource1\dict1.txt'.' //C:\Dropbox\C# Lessons 2020\CSharpDictionaryWords\Resources string RunningPath = AppDomain.CurrentDomain.BaseDirectory; string FileName = string.Format("{0}Resources\\dict1.txt", Path.GetFullPath(Path.Combine(RunningPath, @"..\..\"))); foreach (var word in File.ReadLines(FileName)) { count++; this.Text = count.ToString(); //if the word is not in the dictionary then add it if (operations.DictionaryWords.ContainsKey(word) == false) { operations.DictionaryWords.Add(word, word); } } } private string RunSearch() { if (operations.DictionaryWords.ContainsKey(operations.SearchWord)) { return " is found"; } else { return " is not found"; } } #endregion private void btnSearch_Click(object sender, EventArgs e) { operations.SearchWord = txtEnterWord.Text; string answer = operations.RunSearch(operations.DictionaryWords, operations.SearchWord); lbxAnswer.Items.Add(operations.SearchWord + answer); } } } <file_sep>using System; using System.Collections.Generic; using System.IO; namespace CSharpDictionaryWords { public class Operations { //fields public Dictionary<string, string> DictionaryWords = new Dictionary<string, string>(); //properties // public Dictionary<string, string> DictionaryWords { get; set; } public string SearchWord { get; set; } // public string DictionaryName { get; set; } = "dict1.txt"; public string LoadDictionaryFile() { string RunningPath = AppDomain.CurrentDomain.BaseDirectory; string FileName = string.Format("{0}Resources\\dict1.txt", Path.GetFullPath(Path.Combine(RunningPath, @"..\..\"))); if (File.Exists(FileName)) { return FileName; } else { return null; } } //methods public void LoadDictionary() { //make a counter to show how many words we have //'C:\Dropbox\C# Lessons 2020\CSharpDictionaryWords\Resource1\dict1.txt'.' //C:\Dropbox\C# Lessons 2020\CSharpDictionaryWords\Resources // string RunningPath = AppDomain.CurrentDomain.BaseDirectory; // string FileName = string.Format("{0}Resources\\dict1.txt", Path.GetFullPath(Path.Combine(RunningPath, @"..\..\"))); string Filename = LoadDictionaryFile(); if (!String.IsNullOrEmpty(Filename)) { foreach (var word in File.ReadLines(Filename)) { //if the word is not in the dictionary then add it if (DictionaryWords.ContainsKey(word) == false) { DictionaryWords.Add(word, word); } } } } //pure method for UNit Test public string RunSearch(Dictionary<string, string> Dict, string Search) { if (Dict.ContainsKey(Search.ToLower())) { return " is found"; } else { return " is not found"; } } } } <file_sep>using CSharpDictionaryWords; using Microsoft.VisualStudio.TestTools.UnitTesting; using System.Collections.Generic; namespace CSharpDictionaryWordUnitTest { [TestClass] public class OperationsTest { Operations operations = new Operations(); [TestMethod] public void RunSearchRunningTest() { Dictionary<string, string> MockData = new Dictionary<string, string>(); MockData.Add("cat", "cat"); MockData.Add("dog", "dog"); MockData.Add("fish", "fish"); MockData.Add("kiwi", "kiwi"); string SearchTerm = "cat"; string result = " is found"; // MockData.ContainsKey(SearchTerm); Assert.AreEqual(operations.RunSearch(MockData, SearchTerm), result); } [TestMethod] public void RunSearchCaseSensitivityTest() { Dictionary<string, string> MockData = new Dictionary<string, string>(); MockData.Add("cat", "cat"); MockData.Add("dog", "dog"); MockData.Add("fish", "fish"); MockData.Add("kiwi", "kiwi"); string SearchTerm = "Cat"; string result = " is found"; Assert.AreEqual(operations.RunSearch(MockData, SearchTerm), result); } [TestMethod] public void LoadDictionaryFileTest() { //C:\\Dropbox\\C# Lessons 2020\\CSharpDictionaryWords\\CSharpDictionaryWordUnitTest\\Resources\\dict1.txt // string expected = @"C:\\Dropbox\\C# Lessons 2020\\CSharpDictionaryWords\\CSharpDictionaryWordUnitTest\\Resources\\dict1.txt"; string actual = operations.LoadDictionaryFile(); // string actual2 = actual.Replace("CSharpDictionaryWords", "CSharpDictionaryWords\\CSharpDictionaryWordUnitTest"); Assert.IsNotNull(actual); } } }
1487cce3101b50817ee9247ba656528ee44232d0
[ "C#" ]
3
C#
Netchicken/CSharpDictionaryWords
4596e2b69a713a5d9f10d6af74c87344946a2a01
adbff0fc2121a74d72e7f5ab61842761595a84e0
refs/heads/master
<repo_name>wongaj/test1<file_sep>/hello.cpp #include <iostream> #include <string> using namespace std; void space_out(string& word); int main(){ string hello; cout << "Enter a word: "; cin >> hello; space_out(hello); cout << "hello world\n"; return 0; } //puts spaces between all the letters in the word void space_out(string& word){ for(unsigned int q = 0; q < word.size(); ++q){ cout << word[q] << ' '; } cout << "\n"; } <file_sep>/README.md # test1 trying to learn how to use github. posted some throwaway c++ code
2b468bf0fb914fd324ef271feaefff73636937e2
[ "Markdown", "C++" ]
2
C++
wongaj/test1
c1f93d6f7b701814affc4e00e2547db00757d767
ede21086d839d6ae919ecf120c5f02bce03c6e7f
refs/heads/master
<repo_name>isoundy000/h-react-library<file_sep>/layouts/ShopLayout/Layout.jsx import React, { Component } from 'react'; import { Toast } from 'antd-mobile'; import { Splitter, SplitterSide, SplitterContent, Page, List, ListItem, Icon, } from 'react-onsenui'; import './Layout.scss'; import Auth from './../../common/Auth'; import Api from '../../common/Api'; import I18n from "../../common/I18n"; const leftMenu = [ { label: '商城', icon: 'md-home', url: '/shop' }, { label: '我的', icon: 'md-tab', url: '/user' }, ]; export default class AppLayout extends Component { static propTypes = {}; static defaultProps = {}; constructor(props) { super(props); this.state = { allow: false, leftMenuIsOpen: false, userInfo: {}, }; const shopCode = location.hash.split('/')[1]; Auth.setShopCode(shopCode); Auth.setLoginPath('/' + shopCode + '/sign/sign?prev_url=' + encodeURIComponent(location.href)); if (Auth.isOnline() === false) { Toast.fail(I18n.translate('loginOffline'), 3.00); if (window.location.hostname.indexOf('127.0.0.1') === 0 || window.location.hostname.indexOf('localhost') === 0) { this.props.history.replace('/' + shopCode + '/sign/testIn'); } else { this.props.history.replace(Auth.getLoginPath()); } this.state.allow = false; } else { this.state.allow = true; } } componentDidMount() { if (this.state.allow === true) { Api.cache('User.Info.getInfo', { uid: Auth.getUid(), withThis: true }, (resUser) => { if (resUser.code === 200) { this.setState({ userInfo: resUser.data, }); } else { Toast.fail(resUser.response); } }); } } to = (url) => { this.props.history.push(url); }; leftMenuToggle = (status) => { this.setState({ leftMenuIsOpen: status }); }; render() { return ( <Splitter> <SplitterSide style={styles.leftMenuIsOpen} side="left" width="auto" collapse={true} swipeable={true} animation="push" isOpen={this.state.leftMenuIsOpen} onClose={this.leftMenuToggle.bind(this, false)} onOpen={this.leftMenuToggle.bind(this, true)} > <Page> <List> { leftMenu.map((lm, idx) => { return ( <ListItem key={idx} tappable={true} onClick={this.to.bind(this, lm.url)}> <div className="left"> <Icon icon={lm.icon} /> </div> <div className="center"> {lm.label} </div> </ListItem> ); }) } </List> </Page> </SplitterSide> <SplitterContent> {this.state.allow === true && this.props.children} </SplitterContent> </Splitter> ); } } const styles = { leftMenuIsOpen: { borderRight: '1px solid #ccc', }, }; <file_sep>/README.md ## h-react-library <a href="https://github.com/hunzsig/h-react-library" target="_blank">GitHub</a> ### 依赖antd,antv,iceDesign等组件库 #### 在基础上更进一步的常用react组件库 <file_sep>/common/Api/Api.js import Http from './Http'; import Ws from './Ws'; import Auth from './../Auth'; import I18n from "../I18n"; /** * api 请求 * @param scope * @param params * @param then * @param refresh * @constructor */ const Api = { type: null, host: null, crypto: null, setType: (t) => { Api.type = t.toUpperCase(); }, setHost: (h) => { Api.host = h; }, setCrypto: (c) => { Api.crypto = c; }, // TODO CACHE cache: (scope, params, then) => { switch (Api.type) { case 'HTTP': Http.PathLogin = Auth.getLoginPath(); Http.cache({ host: Api.host, scope: scope, params: params, then: then, crypto: Api.crypto, }); break; case 'HTTP.SHARP': Http.PathLogin = '/#' + Auth.getLoginPath(); Http.cache({ host: Api.host, scope: scope, params: params, then: then, crypto: Api.crypto, }); break; case 'HTTP.REST': Http.PathLogin = Auth.getLoginPath(); Http.cache({ host: Api.host + scope, scope: '', params: params, then: then, crypto: Api.crypto, }); break; case 'WS': Ws.PathLogin = Auth.getLoginPath(); Ws.cache({ host: Api.host, scope: scope, params: params, then: then, crypto: Api.crypto, }); break; case 'WS.SHARP': Ws.PathLogin = '/#' + Auth.getLoginPath(); Ws.cache({ host: Api.host, scope: scope, params: params, then: then, crypto: Api.crypto, }); break; default: console.error(I18n.translate('apiTypeError')); break; } }, // TODO REAL real: (scope, params, then) => { switch (Api.type) { case 'HTTP': Http.PathLogin = Auth.getLoginPath(); Http.real({ host: Api.host, scope: scope, params: params, then: then, crypto: Api.crypto, }); break; case 'HTTP.SHARP': Http.PathLogin = '/#' + Auth.getLoginPath(); Http.real({ host: Api.host, scope: scope, params: params, then: then, crypto: Api.crypto, }); break; case 'HTTP.REST': Http.PathLogin = Auth.getLoginPath(); Http.real({ host: Api.host + scope, scope: '', params: params, then: then, crypto: Api.crypto, }); break; case 'WS': Ws.PathLogin = Auth.getLoginPath(); Ws.real({ host: Api.host, scope: scope, params: params, then: then, crypto: Api.crypto, }); break; case 'WS.SHARP': Ws.PathLogin = '/#' + Auth.getLoginPath(); Ws.real({ host: Api.host, scope: scope, params: params, then: then, crypto: Api.crypto, }); break; default: console.error(I18n.translate('apiTypeError')); break; } }, }; export default Api; <file_sep>/common/I18n/lang.js /* 默认的i18n 会被外置的覆盖 主要处理组件内文本 */ import * as ZH_CN from "./zh_cn.json"; import * as ZH_HK from "./zh_hk.json"; import * as ZH_TW from "./zh_tw.json"; import * as EN_US from "./en_us.json"; import * as JA_JP from "./ja_jp.json"; import * as KO_KR from "./ko_kr.json"; const lang = { zh_cn: ZH_CN.default, zh_hk: ZH_HK.default, zh_tw: ZH_TW.default, en_us: EN_US.default, ja_jp: JA_JP.default, ko_kr: KO_KR.default, }; export default lang; <file_sep>/layouts/EmptyLayout/Layout.jsx import React, { Component } from 'react'; import { Layout, Button, message } from 'antd'; import { withRouter } from 'react-router-dom'; import Auth from './../../common/Auth'; import Api from '../../common/Api'; import './Layout.scss'; import I18n from "../../common/I18n"; const { Content } = Layout; class hLayout extends Component { static propTypes = {}; static defaultProps = {}; constructor(props) { super(props); if (Auth.isOnline() === false) { message.error(I18n.translate('loginOffline'), 3.00); this.props.history.replace(Auth.getLoginPath()); } this.state = {}; } componentDidMount() {} render() { return ( <Layout style={style.FullHV}> <Content style={style.Content} id="layout"> {this.props.children} </Content> <Button className="loginOut" type="primary" shape="round" icon="logout" onClick={ () => { Api.real('User.Online.logout', { uid: Auth.getUid() }, (res) => { if (res.code === 200) { message.success(I18n.translate('logoutSuccess')); Auth.clearUid(); this.props.history.replace(Auth.getLoginPath()); } else { message.error(res.response); } }); } } > 退出 </Button> </Layout> ); } } const style = { loading: { width: '100%', marginTop: '100px' }, FullHV: { minHeight: '100hv' }, Layout: { height: '100hv', display: 'flex', flexDirection: 'column' }, Header: { margin: 0, padding: 0 }, HeaderMenu: { lineHeight: '50px' }, Content: { margin: 0, background: '#ffffff' }, }; export default withRouter(hLayout);
559eb09892d950fb9229359c45ff21eefed24ceb
[ "JavaScript", "Markdown" ]
5
JavaScript
isoundy000/h-react-library
426fe408ad557e170a7556b87433cb6cd751ed19
025e9270daa950c24e8ee89b46a20834b6496dfe
refs/heads/master
<repo_name>dkbhadeshiya/WorkSpace<file_sep>/BmiCalculator/src/server/PersonDetails.java /** * */ package server; import java.io.Serializable; /** * @author dkbhadeshiya * */ public class PersonDetails implements Serializable { /** * */ /** * A Bean Class to store the Data about person */ String name; int age; double weight,height,bmi; //Getter and Setter methods public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public double getWeight() { return weight; } public void setWeight(double weight) { this.weight = weight; } public double getHeight() { return height; } public void setHeight(double height) { this.height = height; } public double getBmi() { return bmi; } public void setBmi(double bmi) { this.bmi = bmi; } } <file_sep>/README.md # Advanced Java -------------------------------------------------- This repository contains the Advanced Java lab works and some other practising projects that I've done for learning various concepts of Advanced Java. Mostly J2EE and Core Java projects. -------------------------------------------------- # Current Projects |No| Name | Faculty | Description | |---|---------------------------|---------|----------------------------------------------------------------------------------| |1.| Basic Database Connection | JBT | Initial Database Connection to Oracle Database using OJDBC Drivers | |2.| BMI Calculator | NJG | BMI (Body Mass Index) calculator for demonstrating the use of include and forward | |3.| Practice Project | NJG | A Practice Project to demonstrate the use of Java Beans classes & jsp useBean tag |
ddd30ebe7317de4ca8ee993d5922821e6a37cebc
[ "Markdown", "Java" ]
2
Java
dkbhadeshiya/WorkSpace
a2dd288ba71d990e610b017575935334e2437254
f766696ad56a5bc99325e50c5045a1f0ec0e9c5b
refs/heads/master
<repo_name>rodrigosantana/ProgrammingAssignment2<file_sep>/cachematrix.R ## Put comments here that give an overall description of what your ## functions do ## Write a short comment describing this function ## This first function sets the steps to construct and apply the ## resolution desired to the respective matrix passed by the user... makeCacheMatrix <- function(x = matrix()) { # Set a null variable to receive tha inverse matrix... m <- NULL set <- function(y) { x <<- y m <<- NULL } # Get the matrix passed by the user in the argument of this # function... get <- function() x # Set the function that will be used on the matrix passed in the # argument of this function... Here the exercise are aimed in solve # the inverse of any matrix... setmatrix <- function(solve) m <<- solve # Get the inverse matrix m... getmatrix <- function() m list(set = set, get = get, setmatrix = setmatrix, getmatrix = getmatrix) } ## Write a short comment describing this function ## This function take the matrix passed by user and apply the resolution ## desired. In this case it was conducted a invertion of a matrix. cacheSolve <- function(x, ...) { ## Return a matrix that is the inverse of 'x' m <- x$getmatrix() if(!is.null(m)) { message("getting cached data") return(m) } # Set the matrix passed by the argument in the makeCacheMatrix... data <- x$get() # Invert the matrix... m <- solve(data) # Set the inverted matrix to m object x$setmatrix(m) # Return m m }
44b8c4c5cf6f2d82be0eb7bb90f7b5403052668f
[ "R" ]
1
R
rodrigosantana/ProgrammingAssignment2
c27ee9bdc53f42d14355b5ddd6862b08bb16115e
77c7c83a4e8a3ebf0b5123f3c5fcc5d711b83466
refs/heads/master
<repo_name>ASEDOS999/CognitiveAssistant<file_sep>/CognitiveAssistent/CA_Examples/trivial/trivial.py import pickle import sys sys.path.append('../../Creating') from CA_create import CognitiveAssistant, ScriptGraphVert from CA_create import ScriptGraphVert as SCV dict_vert = {} vert = SCV(name = "start", texts = ["Здравствуйте. Приступим к выбору автомобиля."], is_start = True) dict_vert["start"] = vert name = "Выбор" vert = SCV(name = name, texts = ["Выберите автомобиль.", "Определитесь с суммой покупки", "Обратите внимание на кузов, трансмиссию, производителя."]) dict_vert[name] = vert name = "Осмотр" vert = SCV(name = name, texts = []) dict_vert[name] = vert name = "Осмотр_бу" vert = SCV(name = name, texts = ["Осмотрите деффекты лакокрсочного покрытия.", "Оцените возраст автомобиля по изношенности салона и уплотнителей.", "Прокатитесь на автомобиле."]) dict_vert[name] = vert name = "Осмотр_новая" vert = SCV(name = name, texts = ["Осмотрите представленные в салоне автомобиле. Оцените комфорт и соответствие желаниям", "Побеседуйте с консультантом. Распросите про возможные варианты, скидки и бонусы.", "Воспользуйтесь тест-драйвом при возможности.", "Проверьте условия договора. Убедитесь в соответствии всех пунктов в документации."]) dict_vert[name] = vert name = "Юридическая_Проверка_бу" vert = SCV(name = name, texts = ["Спросите у продавца ВИН номер автомоболи и проверьте данные автомобиля на сайте ГИБДД."]) dict_vert[name] = vert name = "Оформление_покупки" vert = SCV(name = name, texts = []) dict_vert[name] = vert name = "Оформление_бу_частник" vert = SCV(name = name, texts = ["Подпишите договор купли-продажи.", "Внесите изменения в ПТС.", "Получите ключи от Авто.", "Оформите ОСАГО.", "Зарегестируйте авто в ГИБДД."]) dict_vert[name] = vert name = "Оформление_новая_БезКредита" vert = SCV(name = name, texts = ["Автомобиль, как правило, приходится подождать. В таком случае нужно будет сделать заказ выбранной модели и, возможно, внести задаток.", "При доставке автомобиля проведите осмотр вновь.", "Подпишите договор купли-продажи. Перепрочтите его перед подписанием.", "Внесите полную стоимость авто и получите его.", "Оформите ОСАГО. Подумайте над КАСКО. ...Советы, различия...", "Зарегистрируйте авто в ГИБДД"]) dict_vert[name] = vert name = "Оформление_новая_кредит" vert = SCV(name = name, texts = ["Выберете кредитную организацию, подайте документы и ждите одобрения.", "Выполните условия кредитного договора (напр., покупка КАСКО и внесение первого взноса)", "Подписание договора.", "Получите авто.", "Зарегистрируйте авто в ГИБДД", "Передайте ПТС банку, выдавшему кредит"]) dict_vert[name] = vert dict_vert["end"] = SCV(name = "end", texts = ["Поздравляю с покупкой автомобиля."], is_terminal = True) dict_vert["start"].add_edge(child = dict_vert["Выбор"], cond = "") dict_vert['start'].add_edge(child = dict_vert["Осмотр"], cond = "Осмотр") dict_vert["start"].add_edge(child = dict_vert["Оформление_покупки"], cond = "Оформление") dict_vert['Выбор'].add_edge(child = dict_vert["Осмотр"], cond = "") dict_vert["Осмотр"].add_edge(child = dict_vert["Осмотр_бу"], cond = "бу") dict_vert["Осмотр"].add_edge(child = dict_vert["Осмотр_новая"], cond = "новая") dict_vert["Осмотр_бу"].add_edge(child = dict_vert["Оформление_покупки"], cond = "") dict_vert["Осмотр_новая"].add_edge(child = dict_vert["Оформление_покупки"], cond = "") dict_vert["Оформление_покупки"].add_edge(child = dict_vert["Оформление_бу_частник"], cond = "бу_частник") dict_vert["Оформление_покупки"].add_edge(child = dict_vert["Оформление_новая_БезКредита"], cond = "новая без кредита") dict_vert["Оформление_покупки"].add_edge(child = dict_vert["Оформление_новая_кредит"], cond = "новая с кредитом") dict_vert["Оформление_бу_частник"].add_edge(child = dict_vert["end"], cond = "") dict_vert["Оформление_новая_БезКредита"].add_edge(child = dict_vert["end"], cond = "") dict_vert["Оформление_новая_кредит"].add_edge(child = dict_vert["end"], cond = "") CA = CognitiveAssistant("trivial", dict_vert["start"]) CA.dialogue_start() with open("CA_trivial.pickle", "wb") as f: pickle.dump(CA, f) f.close() <file_sep>/README.md # CognitiveAssistant It is a new dialogue system that should help users to solve their problems. There are theortical results, motivation and example of such dialogue system. <file_sep>/CognitiveAssistent/Creating/CA_create.py import numpy as np class CognitiveAssistant: def __init__(self, name = None, ScriptGraph = None): self.name = name self.ScriptGraph = ScriptGraph def dialogue_start(self): vert = self.ScriptGraph self.user_state = None while not vert is None: vert, self.user_state = vert.dialogue(self.user_state) class ScriptGraphVert: def __init__(self, name = None, texts = None, is_terminal = False, is_start = True): self.name = name if texts is None: texts = [] self.texts = texts self.next_states = [] self.is_terminal = is_terminal self.is_start = is_start def dialogue(self, user_state): if user_state is None: if self.is_start: user_state = np.zeros((300,)) else: return None self.text_generator() return self.make_a_choice(), user_state def text_generator(self): for text in self.texts: print(text) def add_edge(self, new_edge = None, child = None, cond = None): if self.is_terminal: print("You can not to add children into terminal vertices") return None if new_edge is None: new_edge = edge(child, cond) self.next_states.append(new_edge) def make_a_choice(self): def dist(s1, s2): return int(s1==s2) if len(self.next_states) == 0: return None if len(self.next_states) == 1: return self.next_states[0].next_vert s = input() ind = np.argmax(np.array([dist(i.cond, s) for i in self.next_states])) return self.next_states[ind].next_vert class edge: def __init__(self, next_vert, cond): self.next_vert = next_vert self.cond = cond
0762011584ff63552d96fa41c4139d202eaf8363
[ "Markdown", "Python" ]
3
Python
ASEDOS999/CognitiveAssistant
d0f4b813051c9387a14ac350bbd72a78423a88e4
08aa0e9148f25e3911673a96f99588d507d43603
refs/heads/master
<file_sep>using System; using System.Diagnostics; using System.Drawing; using System.IO; using System.Linq; using System.Runtime.InteropServices; using System.Text; using System.Windows.Forms; using LibGit2Sharp; using SharpShell.Attributes; using SharpShell.SharpContextMenu; namespace GitInfoExplorerExtension { [ComVisible(true)] [COMServerAssociation(AssociationType.AllFiles)] [COMServerAssociation(AssociationType.Directory)] public class GitInfoContextMenu : SharpContextMenu { private const string GitDirectoryName = ".git"; private const string GitInfoMenuName = "GitInfo"; private ContextMenuStrip _menu = new ContextMenuStrip(); protected override bool CanShowMenu() { if (SelectedItemPaths.Count() == 1 && IsGitDirectory(SelectedItemPaths.First()))//选中一个目录时构建菜单并显示 { this.UpdateMenu(); return true; } else { return false; } } private static void Log(string msg) => Debug.WriteLine(msg); public static bool IsGitDirectory(string path) { if (string.IsNullOrEmpty(path)) return false; if (!IsDirectory(path)) path = Path.GetDirectoryName(path); if (string.IsNullOrEmpty(path)) return false; return !string.IsNullOrEmpty(GetGitDirectory(path)); } private static string GetGitDirectory(string path) { if (!IsDirectory(path)) path = Path.GetDirectoryName(path); if (string.IsNullOrEmpty(path)) return String.Empty; var directoryInfo = new DirectoryInfo(path); if (directoryInfo.GetDirectories(GitDirectoryName, SearchOption.TopDirectoryOnly).Length == 1) return directoryInfo.FullName; return GetGitDirectory(directoryInfo.Parent?.FullName); } protected override ContextMenuStrip CreateMenu() { BuildGitInfoContextMenus(); return _menu; } private void UpdateMenu() { _menu.Dispose(); _menu = CreateMenu(); } private static bool IsDirectory(string path) { if (string.IsNullOrEmpty(path)) return false; var attr = File.GetAttributes(path); return attr.HasFlag(FileAttributes.Directory); } protected void BuildGitInfoContextMenus() { _menu.Items.Clear(); var gitDir = GetGitDirectory(SelectedItemPaths.First()); if (string.IsNullOrEmpty(gitDir) || !Directory.Exists(gitDir)) return; var repo = new Repository(gitDir); var lastCommit = repo.Head.Tip; var mainMenu = new ToolStripMenuItem { Text = GitInfoMenuName, Image = Properties.Resources.Git }; mainMenu.DropDownItems.Add(new ToolStripMenuItem { Text = $@"Branch Name: {repo.Head.FriendlyName} <->{repo.Head.TrackedBranch?.FriendlyName}" }); mainMenu.DropDownItems.Add(new ToolStripMenuItem { Text = @"Branches Count: " + repo.Branches.Count().ToString() }); mainMenu.DropDownItems.Add(new ToolStripMenuItem { Text = @"Tags Count: " + repo.Tags.Count().ToString() }); mainMenu.DropDownItems.Add(new ToolStripSeparator()); mainMenu.DropDownItems.Add(new ToolStripMenuItem { Text = $@"Last Commit : {lastCommit.Message} {lastCommit.Author} {lastCommit.Author.When.ToString()}" }); _menu.Items.Clear(); _menu.Items.Add(mainMenu); repo.Dispose(); } } }<file_sep>using System.IO; namespace GitInfoExplorerExtension { internal class Program { public static void Main(string[] args) { var result= GitInfoContextMenu.IsGitDirectory(@"E:\RNSS\dashboard\entrypoint.sh"); } } }<file_sep># GitInfoExplorerExtension 在资源管理器中,利用右键上下文菜单展示git信息 Q:TortoiseGit在属性界面中增加了Git栏展示Git信息,为什么不用这个? A:简单说,为了这么一个小功能,太重了。其次,懒人不想多次点击。 Q:为什么是在右键菜单中? A:最开始想加到任务管理器的Title中,(如[RepoZ](https://github.com/awaescher/RepoZ)),或者也可以直接鼠标指向时显示提示信息,取决于个人。同时当不在一个Git目录下时,不会出现此菜单项,避免干扰。
768c18e30ad5c6f9e02b1807a270de7c8979a5ed
[ "Markdown", "C#" ]
3
C#
lockcp/GitInfoExplorerExtension
91e8e7cb8a8d69480781daaaa2fe9a144f8a6f46
5a0f4e6b9c6dee5dc9615a1ea44e812761a207d0
refs/heads/master
<file_sep>package me.jbuelow.trashbot.command.io; import java.util.regex.Pattern; import lombok.Getter; import org.javacord.api.event.message.MessageCreateEvent; public class ParsedCommand { @Getter private MessageCreateEvent event; @Getter private String callableString; @Getter private String contentWithoutCommand; @Getter private String[] arguments; public ParsedCommand(MessageCreateEvent event, String callableString) { this.event = event; this.callableString = callableString; contentWithoutCommand = event.getMessageContent().split(Pattern.quote(callableString), 2)[1]; try { arguments = contentWithoutCommand.split(" ", 2)[1].split(" "); } catch (ArrayIndexOutOfBoundsException e) { arguments = new String[0]; } } } <file_sep>package me.jbuelow.trashbot.service.impl; import java.net.MalformedURLException; import java.net.URL; import javax.annotation.PostConstruct; import lombok.Getter; import lombok.extern.slf4j.Slf4j; import me.jbuelow.trashbot.Config; import me.jbuelow.trashbot.service.ExecuteOnStartService; import org.javacord.api.DiscordApi; import org.springframework.stereotype.Component; import org.springframework.stereotype.Service; @Component @Slf4j public class AvatarUpdaterService implements ExecuteOnStartService { private final Config config; private final DiscordApi discordApi; @Getter Boolean done = false; public AvatarUpdaterService(Config config, DiscordApi discordApi) { this.config = config; this.discordApi = discordApi; log.info("Loaded Service: " + this.getClass().getCanonicalName()); } @Override @PostConstruct public void executeService() { try { discordApi.createAccountUpdater().setAvatar(new URL(config.getAvatarURL())).update(); } catch (MalformedURLException e) { log.error("Exception was thrown while setting avatar: ", e); } done = true; log.debug("AvatarUpdaterService has set the bot avatar successfully."); } } <file_sep>package me.jbuelow.trashbot.command.io; import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.CoreMatchers.instanceOf; import static org.junit.Assert.*; import java.time.Instant; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.concurrent.CompletableFuture; import me.jbuelow.trashbot.Config; import org.javacord.api.DiscordApi; import org.javacord.api.entity.channel.TextChannel; import org.javacord.api.entity.emoji.CustomEmoji; import org.javacord.api.entity.emoji.Emoji; import org.javacord.api.entity.message.Message; import org.javacord.api.entity.message.MessageActivity; import org.javacord.api.entity.message.MessageAttachment; import org.javacord.api.entity.message.MessageAuthor; import org.javacord.api.entity.message.MessageType; import org.javacord.api.entity.message.Reaction; import org.javacord.api.entity.message.embed.Embed; import org.javacord.api.entity.message.embed.EmbedBuilder; import org.javacord.api.entity.permission.Role; import org.javacord.api.entity.server.Server; import org.javacord.api.entity.user.User; import org.javacord.api.event.message.MessageCreateEvent; import org.javacord.api.listener.ObjectAttachableListener; import org.javacord.api.listener.message.CachedMessagePinListener; import org.javacord.api.listener.message.CachedMessageUnpinListener; import org.javacord.api.listener.message.MessageAttachableListener; import org.javacord.api.listener.message.MessageDeleteListener; import org.javacord.api.listener.message.MessageEditListener; import org.javacord.api.listener.message.reaction.ReactionAddListener; import org.javacord.api.listener.message.reaction.ReactionRemoveAllListener; import org.javacord.api.listener.message.reaction.ReactionRemoveListener; import org.javacord.api.util.event.ListenerManager; import org.junit.Test; public class ParsedCommandTest { Config config = new Config(){ @Override public List<String> getPrefixes() { return new ArrayList<String>(){{ add(","); }}; } }; @Test public void testCommandParsesArguments() { MessageCreateEvent testMessage = new MessageCreateEvent(){ @Override public DiscordApi getApi() { return null; } @Override public TextChannel getChannel() { return null; } @Override public long getMessageId() { return 0; } @Override public Optional<Server> getServer() { return Optional.empty(); } @Override public CompletableFuture<Void> deleteMessage() { return null; } @Override public CompletableFuture<Void> deleteMessage(String reason) { return null; } @Override public CompletableFuture<Void> editMessage(String content) { return null; } @Override public CompletableFuture<Void> editMessage(EmbedBuilder embed) { return null; } @Override public CompletableFuture<Void> editMessage(String content, EmbedBuilder embed) { return null; } @Override public CompletableFuture<Void> addReactionToMessage(String unicodeEmoji) { return null; } @Override public CompletableFuture<Void> addReactionToMessage(Emoji emoji) { return null; } @Override public CompletableFuture<Void> addReactionsToMessage(Emoji... emojis) { return null; } @Override public CompletableFuture<Void> addReactionsToMessage(String... unicodeEmojis) { return null; } @Override public CompletableFuture<Void> removeAllReactionsFromMessage() { return null; } @Override public CompletableFuture<Void> removeReactionByEmojiFromMessage(User user, Emoji emoji) { return null; } @Override public CompletableFuture<Void> removeReactionByEmojiFromMessage(User user, String unicodeEmoji) { return null; } @Override public CompletableFuture<Void> removeReactionByEmojiFromMessage(Emoji emoji) { return null; } @Override public CompletableFuture<Void> removeReactionByEmojiFromMessage(String unicodeEmoji) { return null; } @Override public CompletableFuture<Void> removeReactionsByEmojiFromMessage(User user, Emoji... emojis) { return null; } @Override public CompletableFuture<Void> removeReactionsByEmojiFromMessage(User user, String... unicodeEmojis) { return null; } @Override public CompletableFuture<Void> removeReactionsByEmojiFromMessage(Emoji... emojis) { return null; } @Override public CompletableFuture<Void> removeReactionsByEmojiFromMessage(String... unicodeEmojis) { return null; } @Override public CompletableFuture<Void> removeOwnReactionByEmojiFromMessage(Emoji emoji) { return null; } @Override public CompletableFuture<Void> removeOwnReactionByEmojiFromMessage(String unicodeEmoji) { return null; } @Override public CompletableFuture<Void> removeOwnReactionsByEmojiFromMessage(Emoji... emojis) { return null; } @Override public CompletableFuture<Void> removeOwnReactionsByEmojiFromMessage(String... unicodeEmojis) { return null; } @Override public CompletableFuture<Void> pinMessage() { return null; } @Override public CompletableFuture<Void> unpinMessage() { return null; } @Override public Message getMessage() { return new Message() { @Override public String getContent() { return config.getPrefixes().get(0) + "test this is a command with many arguments"; } @Override public Optional<Instant> getLastEditTimestamp() { return Optional.empty(); } @Override public List<MessageAttachment> getAttachments() { return null; } @Override public List<CustomEmoji> getCustomEmojis() { return null; } @Override public MessageType getType() { return null; } @Override public TextChannel getChannel() { return null; } @Override public Optional<MessageActivity> getActivity() { return Optional.empty(); } @Override public boolean isPinned() { return false; } @Override public boolean isTts() { return false; } @Override public boolean mentionsEveryone() { return false; } @Override public List<Embed> getEmbeds() { return null; } @Override public Optional<User> getUserAuthor() { return Optional.empty(); } @Override public MessageAuthor getAuthor() { return null; } @Override public boolean isCachedForever() { return false; } @Override public void setCachedForever(boolean cachedForever) { } @Override public List<Reaction> getReactions() { return null; } @Override public List<User> getMentionedUsers() { return null; } @Override public List<Role> getMentionedRoles() { return null; } @Override public CompletableFuture<Void> addReactions(String... unicodeEmojis) { return null; } @Override public CompletableFuture<Void> removeReactionByEmoji(User user, String unicodeEmoji) { return null; } @Override public CompletableFuture<Void> removeReactionByEmoji(String unicodeEmoji) { return null; } @Override public CompletableFuture<Void> removeReactionsByEmoji(User user, String... unicodeEmojis) { return null; } @Override public CompletableFuture<Void> removeReactionsByEmoji(String... unicodeEmojis) { return null; } @Override public CompletableFuture<Void> removeOwnReactionByEmoji(String unicodeEmoji) { return null; } @Override public CompletableFuture<Void> removeOwnReactionsByEmoji(String... unicodeEmojis) { return null; } @Override public int compareTo(Message o) { return 0; } @Override public DiscordApi getApi() { return null; } @Override public long getId() { return 0; } @Override public ListenerManager<ReactionRemoveAllListener> addReactionRemoveAllListener( ReactionRemoveAllListener listener) { return null; } @Override public List<ReactionRemoveAllListener> getReactionRemoveAllListeners() { return null; } @Override public ListenerManager<ReactionAddListener> addReactionAddListener( ReactionAddListener listener) { return null; } @Override public List<ReactionAddListener> getReactionAddListeners() { return null; } @Override public ListenerManager<ReactionRemoveListener> addReactionRemoveListener( ReactionRemoveListener listener) { return null; } @Override public List<ReactionRemoveListener> getReactionRemoveListeners() { return null; } @Override public ListenerManager<MessageEditListener> addMessageEditListener( MessageEditListener listener) { return null; } @Override public List<MessageEditListener> getMessageEditListeners() { return null; } @Override public ListenerManager<CachedMessageUnpinListener> addCachedMessageUnpinListener( CachedMessageUnpinListener listener) { return null; } @Override public List<CachedMessageUnpinListener> getCachedMessageUnpinListeners() { return null; } @Override public ListenerManager<MessageDeleteListener> addMessageDeleteListener( MessageDeleteListener listener) { return null; } @Override public List<MessageDeleteListener> getMessageDeleteListeners() { return null; } @Override public ListenerManager<CachedMessagePinListener> addCachedMessagePinListener( CachedMessagePinListener listener) { return null; } @Override public List<CachedMessagePinListener> getCachedMessagePinListeners() { return null; } @Override public <T extends MessageAttachableListener & ObjectAttachableListener> Collection<ListenerManager<T>> addMessageAttachableListener( T listener) { return null; } @Override public <T extends MessageAttachableListener & ObjectAttachableListener> void removeMessageAttachableListener( T listener) { } @Override public <T extends MessageAttachableListener & ObjectAttachableListener> Map<T, List<Class<T>>> getMessageAttachableListeners() { return null; } @Override public <T extends MessageAttachableListener & ObjectAttachableListener> void removeListener( Class<T> listenerClass, T listener) { } }; } }; Object testObject = new ParsedCommand(testMessage, "test"); assertThat(testObject, instanceOf(ParsedCommand.class)); ParsedCommand testParsedCommand = (ParsedCommand) testObject; assertThat(testParsedCommand.getArguments(), instanceOf(String[].class)); String[] expected = { "this", "is", "a", "command", "with", "many", "arguments" }; assertArrayEquals(expected, testParsedCommand.getArguments()); assertThat(testParsedCommand.getCallableString(), equalTo("test")); assertThat(testParsedCommand.getEvent(), equalTo(testMessage)); } @Test public void testNoArgumentsDoesntThrowException() { MessageCreateEvent testMessage = new MessageCreateEvent(){ @Override public DiscordApi getApi() { return null; } @Override public TextChannel getChannel() { return null; } @Override public long getMessageId() { return 0; } @Override public Optional<Server> getServer() { return Optional.empty(); } @Override public CompletableFuture<Void> deleteMessage() { return null; } @Override public CompletableFuture<Void> deleteMessage(String reason) { return null; } @Override public CompletableFuture<Void> editMessage(String content) { return null; } @Override public CompletableFuture<Void> editMessage(EmbedBuilder embed) { return null; } @Override public CompletableFuture<Void> editMessage(String content, EmbedBuilder embed) { return null; } @Override public CompletableFuture<Void> addReactionToMessage(String unicodeEmoji) { return null; } @Override public CompletableFuture<Void> addReactionToMessage(Emoji emoji) { return null; } @Override public CompletableFuture<Void> addReactionsToMessage(Emoji... emojis) { return null; } @Override public CompletableFuture<Void> addReactionsToMessage(String... unicodeEmojis) { return null; } @Override public CompletableFuture<Void> removeAllReactionsFromMessage() { return null; } @Override public CompletableFuture<Void> removeReactionByEmojiFromMessage(User user, Emoji emoji) { return null; } @Override public CompletableFuture<Void> removeReactionByEmojiFromMessage(User user, String unicodeEmoji) { return null; } @Override public CompletableFuture<Void> removeReactionByEmojiFromMessage(Emoji emoji) { return null; } @Override public CompletableFuture<Void> removeReactionByEmojiFromMessage(String unicodeEmoji) { return null; } @Override public CompletableFuture<Void> removeReactionsByEmojiFromMessage(User user, Emoji... emojis) { return null; } @Override public CompletableFuture<Void> removeReactionsByEmojiFromMessage(User user, String... unicodeEmojis) { return null; } @Override public CompletableFuture<Void> removeReactionsByEmojiFromMessage(Emoji... emojis) { return null; } @Override public CompletableFuture<Void> removeReactionsByEmojiFromMessage(String... unicodeEmojis) { return null; } @Override public CompletableFuture<Void> removeOwnReactionByEmojiFromMessage(Emoji emoji) { return null; } @Override public CompletableFuture<Void> removeOwnReactionByEmojiFromMessage(String unicodeEmoji) { return null; } @Override public CompletableFuture<Void> removeOwnReactionsByEmojiFromMessage(Emoji... emojis) { return null; } @Override public CompletableFuture<Void> removeOwnReactionsByEmojiFromMessage(String... unicodeEmojis) { return null; } @Override public CompletableFuture<Void> pinMessage() { return null; } @Override public CompletableFuture<Void> unpinMessage() { return null; } @Override public Message getMessage() { return new Message() { @Override public String getContent() { return config.getPrefixes().get(0) + "test"; } @Override public Optional<Instant> getLastEditTimestamp() { return Optional.empty(); } @Override public List<MessageAttachment> getAttachments() { return null; } @Override public List<CustomEmoji> getCustomEmojis() { return null; } @Override public MessageType getType() { return null; } @Override public TextChannel getChannel() { return null; } @Override public Optional<MessageActivity> getActivity() { return Optional.empty(); } @Override public boolean isPinned() { return false; } @Override public boolean isTts() { return false; } @Override public boolean mentionsEveryone() { return false; } @Override public List<Embed> getEmbeds() { return null; } @Override public Optional<User> getUserAuthor() { return Optional.empty(); } @Override public MessageAuthor getAuthor() { return null; } @Override public boolean isCachedForever() { return false; } @Override public void setCachedForever(boolean cachedForever) { } @Override public List<Reaction> getReactions() { return null; } @Override public List<User> getMentionedUsers() { return null; } @Override public List<Role> getMentionedRoles() { return null; } @Override public CompletableFuture<Void> addReactions(String... unicodeEmojis) { return null; } @Override public CompletableFuture<Void> removeReactionByEmoji(User user, String unicodeEmoji) { return null; } @Override public CompletableFuture<Void> removeReactionByEmoji(String unicodeEmoji) { return null; } @Override public CompletableFuture<Void> removeReactionsByEmoji(User user, String... unicodeEmojis) { return null; } @Override public CompletableFuture<Void> removeReactionsByEmoji(String... unicodeEmojis) { return null; } @Override public CompletableFuture<Void> removeOwnReactionByEmoji(String unicodeEmoji) { return null; } @Override public CompletableFuture<Void> removeOwnReactionsByEmoji(String... unicodeEmojis) { return null; } @Override public int compareTo(Message o) { return 0; } @Override public DiscordApi getApi() { return null; } @Override public long getId() { return 0; } @Override public ListenerManager<ReactionRemoveAllListener> addReactionRemoveAllListener( ReactionRemoveAllListener listener) { return null; } @Override public List<ReactionRemoveAllListener> getReactionRemoveAllListeners() { return null; } @Override public ListenerManager<ReactionAddListener> addReactionAddListener( ReactionAddListener listener) { return null; } @Override public List<ReactionAddListener> getReactionAddListeners() { return null; } @Override public ListenerManager<ReactionRemoveListener> addReactionRemoveListener( ReactionRemoveListener listener) { return null; } @Override public List<ReactionRemoveListener> getReactionRemoveListeners() { return null; } @Override public ListenerManager<MessageEditListener> addMessageEditListener( MessageEditListener listener) { return null; } @Override public List<MessageEditListener> getMessageEditListeners() { return null; } @Override public ListenerManager<CachedMessageUnpinListener> addCachedMessageUnpinListener( CachedMessageUnpinListener listener) { return null; } @Override public List<CachedMessageUnpinListener> getCachedMessageUnpinListeners() { return null; } @Override public ListenerManager<MessageDeleteListener> addMessageDeleteListener( MessageDeleteListener listener) { return null; } @Override public List<MessageDeleteListener> getMessageDeleteListeners() { return null; } @Override public ListenerManager<CachedMessagePinListener> addCachedMessagePinListener( CachedMessagePinListener listener) { return null; } @Override public List<CachedMessagePinListener> getCachedMessagePinListeners() { return null; } @Override public <T extends MessageAttachableListener & ObjectAttachableListener> Collection<ListenerManager<T>> addMessageAttachableListener( T listener) { return null; } @Override public <T extends MessageAttachableListener & ObjectAttachableListener> void removeMessageAttachableListener( T listener) { } @Override public <T extends MessageAttachableListener & ObjectAttachableListener> Map<T, List<Class<T>>> getMessageAttachableListeners() { return null; } @Override public <T extends MessageAttachableListener & ObjectAttachableListener> void removeListener( Class<T> listenerClass, T listener) { } }; } }; Object testObject = new ParsedCommand(testMessage, "test"); assertThat(testObject, instanceOf(ParsedCommand.class)); ParsedCommand testParsedCommand = (ParsedCommand) testObject; assertThat(testParsedCommand.getArguments(), instanceOf(String[].class)); String[] expected = {}; assertArrayEquals(expected, testParsedCommand.getArguments()); assertThat(testParsedCommand.getCallableString(), equalTo("test")); assertThat(testParsedCommand.getEvent(), equalTo(testMessage)); } }<file_sep>package me.jbuelow.trashbot.listener.impl; import java.awt.Color; import java.util.concurrent.ExecutionException; import lombok.extern.slf4j.Slf4j; import me.jbuelow.trashbot.listener.Listener; import org.javacord.api.entity.message.MessageBuilder; import org.javacord.api.entity.message.embed.EmbedBuilder; import org.javacord.api.entity.server.Server; import org.javacord.api.event.server.ServerJoinEvent; import org.javacord.api.listener.server.ServerJoinListener; import org.springframework.stereotype.Service; @Service @Slf4j public class OwnerJoinAlertListener implements Listener, ServerJoinListener { @Override public void onServerJoin(ServerJoinEvent event) { Server server = event.getServer(); try { new MessageBuilder() .append(":confetti_ball: Server joined! :confetti_ball:") .setEmbed(new EmbedBuilder() .setAuthor(server.getName()) .addInlineField("Owner", server.getOwner().getDiscriminatedName()) .addInlineField("Members", String.valueOf(server.getMemberCount())) .addInlineField("Channels", String.valueOf(server.getChannels().size())) .addInlineField("Date Created", server.getCreationTimestamp().toString()+" UTC") .setColor(Color.green) .setImage(server.getIcon().orElse(null)) .setThumbnail(server.getOwner().getAvatar())) .send(event.getApi().getOwner().get()); } catch (InterruptedException | ExecutionException e) { log.error("An exception occurred: ", e); } } } <file_sep>package me.jbuelow.trashbot.service.io; import lombok.Getter; import org.javacord.api.entity.activity.ActivityType; public class Activity { @Getter private ActivityType type = ActivityType.PLAYING; @Getter private String text = "a game"; public Activity(ActivityType type, String text) { this.type = type; this.text = text; } public ActivityType getType() { return type; } } <file_sep>package me.jbuelow.trashbot.listener.impl; import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.CoreMatchers.instanceOf; import static org.junit.Assert.*; import java.time.Instant; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Optional; import java.util.concurrent.CompletableFuture; import me.jbuelow.trashbot.Config; import org.javacord.api.DiscordApi; import org.javacord.api.entity.channel.TextChannel; import org.javacord.api.entity.emoji.CustomEmoji; import org.javacord.api.entity.message.Message; import org.javacord.api.entity.message.MessageActivity; import org.javacord.api.entity.message.MessageAttachment; import org.javacord.api.entity.message.MessageAuthor; import org.javacord.api.entity.message.MessageType; import org.javacord.api.entity.message.Reaction; import org.javacord.api.entity.message.embed.Embed; import org.javacord.api.entity.permission.Role; import org.javacord.api.entity.user.User; import org.javacord.api.listener.ObjectAttachableListener; import org.javacord.api.listener.message.CachedMessagePinListener; import org.javacord.api.listener.message.CachedMessageUnpinListener; import org.javacord.api.listener.message.MessageAttachableListener; import org.javacord.api.listener.message.MessageDeleteListener; import org.javacord.api.listener.message.MessageEditListener; import org.javacord.api.listener.message.reaction.ReactionAddListener; import org.javacord.api.listener.message.reaction.ReactionRemoveAllListener; import org.javacord.api.listener.message.reaction.ReactionRemoveListener; import org.javacord.api.util.event.ListenerManager; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringRunner; @RunWith(SpringRunner.class) @SpringBootTest public class CommandListenerTest { @Autowired CommandListener commandListener; @Autowired Config config; @Test public void testMessageHasPrefixNoTriggerConversation() { runTestWithStringAndExpectedBoolean("this is a normal conversation message. the bot should not trigger, even though it contains the bot prefix.", false); } @Test public void testMessageHasPrefixNoTriggerWrongPrefix() { config.setPrefixes(new ArrayList<String>(){{add(",");}}); //Ensures that a configuration file change will not break this test runTestWithStringAndExpectedBoolean("#test", false); } @Test public void testMessageHasPrefixNoTriggerWithStockEmoji() { runTestWithStringAndExpectedBoolean(":eggplant:", false); } @Test public void testMessageHasPrefixNoTriggerServerEmoji() { runTestWithStringAndExpectedBoolean("<:thonkang:219069250692841473>", false); } @Test public void testMessageHasPrefixNoTriggerEveryoneMention() { runTestWithStringAndExpectedBoolean("@everyone", false); } @Test public void testMessageHasPrefixNoTriggerUserMention() { runTestWithStringAndExpectedBoolean("<@439838454203591019>", false); } @Test public void testMessageHasPrefixNoTriggerRoleMention() { runTestWithStringAndExpectedBoolean("<@&576393517247274123>", false); } @Test public void testMessageHasPrefixTrigger() { config.setPrefixes(new ArrayList<String>(){{add(",");}}); //Ensures that a configuration file change will not break this test runTestWithStringAndExpectedBoolean(",test", true); } private void runTestWithStringAndExpectedBoolean(String messageContent, boolean expectedOutcome) { Message testMessage = new TestMessage(messageContent); Object result = commandListener.messageHasPrefix(testMessage); assertThat(result, instanceOf(Boolean.class)); boolean resultBool = (boolean) result; assertThat(resultBool, equalTo(expectedOutcome)); } private class TestMessage implements Message { String content; public TestMessage(String content) { this.content = content; } @Override public String getContent() { return content; } @Override public Optional<Instant> getLastEditTimestamp() { return Optional.empty(); } @Override public List<MessageAttachment> getAttachments() { return null; } @Override public List<CustomEmoji> getCustomEmojis() { return null; } @Override public MessageType getType() { return null; } @Override public TextChannel getChannel() { return null; } @Override public Optional<MessageActivity> getActivity() { return Optional.empty(); } @Override public boolean isPinned() { return false; } @Override public boolean isTts() { return false; } @Override public boolean mentionsEveryone() { return false; } @Override public List<Embed> getEmbeds() { return null; } @Override public Optional<User> getUserAuthor() { return Optional.empty(); } @Override public MessageAuthor getAuthor() { return null; } @Override public boolean isCachedForever() { return false; } @Override public void setCachedForever(boolean cachedForever) { } @Override public List<Reaction> getReactions() { return null; } @Override public List<User> getMentionedUsers() { return null; } @Override public List<Role> getMentionedRoles() { return null; } @Override public CompletableFuture<Void> addReactions(String... unicodeEmojis) { return null; } @Override public CompletableFuture<Void> removeReactionByEmoji(User user, String unicodeEmoji) { return null; } @Override public CompletableFuture<Void> removeReactionByEmoji(String unicodeEmoji) { return null; } @Override public CompletableFuture<Void> removeReactionsByEmoji(User user, String... unicodeEmojis) { return null; } @Override public CompletableFuture<Void> removeReactionsByEmoji(String... unicodeEmojis) { return null; } @Override public CompletableFuture<Void> removeOwnReactionByEmoji(String unicodeEmoji) { return null; } @Override public CompletableFuture<Void> removeOwnReactionsByEmoji(String... unicodeEmojis) { return null; } @Override public int compareTo(Message o) { return 0; } @Override public DiscordApi getApi() { return null; } @Override public long getId() { return 0; } @Override public ListenerManager<ReactionRemoveAllListener> addReactionRemoveAllListener( ReactionRemoveAllListener listener) { return null; } @Override public List<ReactionRemoveAllListener> getReactionRemoveAllListeners() { return null; } @Override public ListenerManager<ReactionAddListener> addReactionAddListener( ReactionAddListener listener) { return null; } @Override public List<ReactionAddListener> getReactionAddListeners() { return null; } @Override public ListenerManager<ReactionRemoveListener> addReactionRemoveListener( ReactionRemoveListener listener) { return null; } @Override public List<ReactionRemoveListener> getReactionRemoveListeners() { return null; } @Override public ListenerManager<MessageEditListener> addMessageEditListener( MessageEditListener listener) { return null; } @Override public List<MessageEditListener> getMessageEditListeners() { return null; } @Override public ListenerManager<CachedMessageUnpinListener> addCachedMessageUnpinListener( CachedMessageUnpinListener listener) { return null; } @Override public List<CachedMessageUnpinListener> getCachedMessageUnpinListeners() { return null; } @Override public ListenerManager<MessageDeleteListener> addMessageDeleteListener( MessageDeleteListener listener) { return null; } @Override public List<MessageDeleteListener> getMessageDeleteListeners() { return null; } @Override public ListenerManager<CachedMessagePinListener> addCachedMessagePinListener( CachedMessagePinListener listener) { return null; } @Override public List<CachedMessagePinListener> getCachedMessagePinListeners() { return null; } @Override public <T extends MessageAttachableListener & ObjectAttachableListener> Collection<ListenerManager<T>> addMessageAttachableListener( T listener) { return null; } @Override public <T extends MessageAttachableListener & ObjectAttachableListener> void removeMessageAttachableListener( T listener) { } @Override public <T extends MessageAttachableListener & ObjectAttachableListener> Map<T, List<Class<T>>> getMessageAttachableListeners() { return null; } @Override public <T extends MessageAttachableListener & ObjectAttachableListener> void removeListener( Class<T> listenerClass, T listener) { } } }<file_sep>package me.jbuelow.trashbot.listener; import org.javacord.api.listener.GloballyAttachableListener; public interface Listener extends GloballyAttachableListener { } <file_sep>package me.jbuelow.trashbot.service.impl; import java.util.List; import java.util.Random; import lombok.extern.slf4j.Slf4j; import me.jbuelow.trashbot.Config; import me.jbuelow.trashbot.service.PeriodicBackgroundService; import me.jbuelow.trashbot.service.io.Activity; import org.javacord.api.DiscordApi; import org.springframework.scheduling.annotation.Scheduled; import org.springframework.stereotype.Component; @Component @Slf4j public class StatusChangerService implements PeriodicBackgroundService { private final Config config; private final DiscordApi discordApi; private Random random = new Random(); private List<Activity> activityList; public StatusChangerService(Config config, DiscordApi discordApi) { this.config = config; this.discordApi = discordApi; this.activityList = config.getActivities(); log.info("Loaded Service: " + this.getClass().getCanonicalName()); } @Override @Scheduled(fixedRate = 30000) public void executeService() { Activity activity = activityList.get(random.nextInt(activityList.size())); discordApi.updateActivity(activity.getType(), activity.getText()); log.debug("Set bot activity"); } } <file_sep>package me.jbuelow.trashbot; import java.util.ArrayList; 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 lombok.Getter; import lombok.Setter; import me.jbuelow.trashbot.service.io.Activity; import org.javacord.api.DiscordApi; import org.javacord.api.DiscordApiBuilder; import org.javacord.api.entity.activity.ActivityType; import org.javacord.api.entity.permission.Permissions; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.boot.context.properties.EnableConfigurationProperties; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @Configuration @EnableConfigurationProperties @ConfigurationProperties public class Config { @Getter @Setter private String token; @Getter @Setter private List<String> prefixes = new ArrayList<>(); @Getter @Setter private String botUsername; @Getter @Setter private String avatarURL; @Getter @Setter private List<String> eightBallLines; @Getter private List<Activity> activities = new ArrayList<>(); @Getter private Permissions defaultPermissions = Permissions.fromBitmask(8); public void setActivityConfig(List<Map<String, String>> data) { for (Map<String, String> map : data) { activities.add(new Activity(ActivityType.valueOf(map.get("type")), map.get("text"))); } } public void setDefaultPermissions(int bitmask) { defaultPermissions = Permissions.fromBitmask(bitmask); } @Bean public DiscordApi discordApi() { if(System.getenv("DISCORD_TOKEN") != null) { token = System.getenv("DISCORD_TOKEN"); } return new DiscordApiBuilder().setToken(token).login().join(); } } <file_sep>package me.jbuelow.trashbot.command.processor; import java.util.List; import java.util.Map; import me.jbuelow.trashbot.command.handler.CommandHandler; import me.jbuelow.trashbot.command.io.ParsedCommand; public interface CommandProcessorService { void handleCommand(ParsedCommand parsedCommand); Map<String, CommandHandler> getCommandHandlerMap(); List<CommandHandler> getCommandHandlerList(); } <file_sep>package me.jbuelow.trashbot.service; public interface ExecuteOnStartService extends BackgroundService { Boolean getDone(); }
0580677079069379c84469f51286562b2982f454
[ "Java" ]
11
Java
jbuelow1/shitcord
df9e290cb921a2f6aa3af18d93710f9c8091bd52
1e2079191204f6b4e407b5e82271c44e38158b58
refs/heads/master
<repo_name>smtion/laravel-practice<file_sep>/app/Api/v1/Controllers/SimpleController.php <?php namespace App\Api\v1\Controllers; use Illuminate\Http\Request; use App\User; class SimpleController extends Controller { public function index(Request $request) { return 'This is simple index'; } public function show($id = 'Default') { return 'Echo : ' . $id; } public function sample() { return 'This is a sample'; } }
ce22441ad674fffd4153e6a1dd6d430a7da8d539
[ "PHP" ]
1
PHP
smtion/laravel-practice
f9d34a93ff75fab2804a35976d03cb1deaa6c407
93465b95ded7ae943d44edd6d27b634eb28a9387
refs/heads/main
<repo_name>doriandres/webdroid<file_sep>/js/viewmodels/index.js import { Observable } from "./../utils/observable.js"; export class IndexViewModel{ static create(){ return new IndexViewModel(); } constructor(){ this._datos = Observable.create([]); } eliminarDato(dato){ this._datos.setValue(this._datos.getValue().filter(v => v!== dato)); } agregarDato(dato){ this._datos.setValue([ ...this._datos.getValue(), dato ]); } getDatos(){ return this._datos; } }<file_sep>/js/utils/adapter.js export class ViewHolder{ constructor(view){ this._view = view; } getView(){ return this._view; } } export class ViewAdapter { constructor(parent){ this._parent = parent; setTimeout(()=> this.update()); } update(){ window.requestAnimationFrame(() => { const fragment = document.createDocumentFragment(); for(let i = 0; i < this.getItemCount(); i++){ const viewHolder = this.onCreateViewHolder(this._parent); this.onBindViewHolder(viewHolder, i); fragment.appendChild(viewHolder.getView()); } this._parent.innerHTML = ""; this._parent.appendChild(fragment); }); } onCreateViewHolder(parent){ // Override } onBindViewHolder(viewHolder, position){ // Override } getItemCount(){ // Override return 1; } }<file_sep>/README.md # webdroid This is just an Android like way to make an Web SPA in JS <file_sep>/js/views/index.js import { ListAdapter } from "../adapters/list.js"; import { Layout } from "../utils/layout.js"; import { IndexViewModel } from "./../viewmodels/index.js"; import index_layout from './../layouts/index.js'; export class IndexView{ create(){ const view = Layout.build(index_layout); this._lista = view.querySelector(".lista"); this._formulario = view.querySelector(".formulario"); this._texto = view.querySelector(".texto"); this._indexViewModel = IndexViewModel.create(); this._listAdapter = new ListAdapter(this._lista); this._listAdapter.setOnItemClicked(item => this._indexViewModel.eliminarDato(item)); this._indexViewModel.getDatos().observe(items => this._listAdapter.setItems(items)); this._formulario.addEventListener('submit', event => { event.preventDefault(); if(!this._texto.value) return; this.agregar(); this.limpiar(); }); return view; } agregar(){ const dato = this._texto.value; this._indexViewModel.agregarDato({ dato }); } limpiar(){ this._formulario.reset(); } }<file_sep>/js/layouts/list_item.js export default ` <li> <span class="texto_item"></span> </li> `;<file_sep>/js/adapters/list.js import { ViewAdapter, ViewHolder } from "./../utils/adapter.js"; import { Layout } from "./../utils/layout.js"; import list_item_layout from "./../layouts/list_item.js"; class ListViewHolder extends ViewHolder{ constructor(view){ super(view); this.text = view.querySelector('.texto_item'); } } export class ListAdapter extends ViewAdapter{ constructor(parent, items = []){ super(parent); this._items = items; } setOnItemClicked(handler){ this._onItemClicked = handler; } setItems(items){ if(items !== this._items){ this._items = items; this.update(); } } onCreateViewHolder(){ const view = Layout.build(list_item_layout); return new ListViewHolder(view); } onBindViewHolder(viewHolder, position){ const item = this._items[position]; viewHolder.text.textContent = item.dato; viewHolder.getView().addEventListener('click', () => { if(this._onItemClicked) this._onItemClicked(item); }); } getItemCount(){ return this._items.length; } } <file_sep>/js/index.js import { IndexViewModel } from './viewmodels/index.js'; import { IndexView } from './views/index.js'; const view = new IndexView(); document.getElementById("root").appendChild(view.create());
b0a40befdeff05b93d1898212adfbda39fbe71b9
[ "JavaScript", "Markdown" ]
7
JavaScript
doriandres/webdroid
0165f33116676798692d578074ea53d2967021a6
1e18a47040ad8eb4f9e2f1929d941f4d70c45a7b
refs/heads/master
<file_sep>print(__doc__) # Code source: <NAME> # Modified for documentation by <NAME> # License: BSD 3 clause from sklearn import manifold import numpy as np import pickle import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D from fuzzywuzzy import fuzz from sklearn.cluster import KMeans from sklearn import datasets dis_mat = pickle.load(open("matrixbin","rb")) label = pickle.load(open("malwareclass","rb")) aff_mat = np.exp(-1*dis_mat**2) se = manifold.SpectralEmbedding( affinity='precomputed', n_components=2, n_neighbors=100) pos2 = se.fit_transform(aff_mat) for i in range(0,499): if pos2[i,0] < -0.22 and pos2[i,0] > -0.28 and pos2[i,1] > 0.10 and pos2[i,1] < 0.16: print i ''' seed = np.random.RandomState(seed=3) mds = manifold.MDS(n_components=2, max_iter=3000, eps=1e-9, random_state=seed, dissimilarity="precomputed", n_jobs=1) pos = mds.fit(dis_mat).embedding_ plt.figure() ''' plt.figure().add_subplot(111, axisbg="grey") color = [str(float(item)) for item in label] plt.scatter(pos2[:, 0], pos2[:, 1], s=20, c=color) print "D" plt.show() ''' centers = [[1, 1], [-1, -1], [1, -1]] iris = datasets.load_iris() X = iris.data y = iris.target estimators = {'k_means_iris_3': KMeans(n_clusters=2), 'k_means_iris_8': KMeans(n_clusters=8), } fignum = 1 for name, est in estimators.items(): fig = plt.figure(fignum, figsize=(4, 3)) plt.clf() ax = Axes3D(fig, rect=[0, 0, .95, 1], elev=48, azim=134) plt.cla() est.fit(X) labels = est.labels_ ax.scatter(X[:, 3], X[:, 0], X[:, 2], c=labels.astype(np.float)) ax.w_xaxis.set_ticklabels([]) ax.w_yaxis.set_ticklabels([]) ax.w_zaxis.set_ticklabels([]) ax.set_xlabel('Petal width') ax.set_ylabel('Sepal length') ax.set_zlabel('Petal length') fignum = fignum + 1 # Plot the ground truth fig = plt.figure(fignum, figsize=(4, 3)) plt.clf() ax = Axes3D(fig, rect=[0, 0, .95, 1], elev=48, azim=134) plt.cla() for name, label in [('Setosa', 0), ('Versicolour', 1), ('Virginica', 2)]: ax.text3D(X[y == label, 3].mean(), X[y == label, 0].mean() + 1.5, X[y == label, 2].mean(), name, horizontalalignment='center', bbox=dict(alpha=.5, edgecolor='w', facecolor='w')) # Reorder the labels to have colors matching the cluster results y = np.choose(y, [1, 2, 0]).astype(np.float) ax.scatter(X[:, 3], X[:, 0], X[:, 2], c=y) ax.w_xaxis.set_ticklabels([]) ax.w_yaxis.set_ticklabels([]) ax.w_zaxis.set_ticklabels([]) ax.set_xlabel('Petal width') ax.set_ylabel('Sepal length') ax.set_zlabel('Petal length') plt.show() '''<file_sep>import os,cPickle as pickle,sys from scrape import Resource from collections import Counter import time import numpy as np File_Count = {} Reg_Count = {} Mux_Count = {} Res_Count = [File_Count, Reg_Count, Mux_Count] malware_files = [] malware_class = [] malware_names = [] for k in range(1,500): file = "Data/file"+str(k) resources = pickle.load(open(file,"rb")) for i in range(0,3): if i == 0: malware_files.append(resources.resources[i]) malware_names.append(resources.name) if resources.avr <0: malware_class.append(0) else: malware_class.append(resources.avr) #r = len(files) r = 499 x = 0 y = 0 dis_mat = np.zeros((r, r)) # Substring Sieve for i in range(0,r): malware_files[i].sort(key = lambda s: -len(s)) out = [] for s in malware_files[i]: if not any([s in o for o in out]): out.append(s) malware_files[i] = out for x in range(0, r): for y in range(0, r): try: dis_mat[x,y] = len(list(set(malware_files[x])^(set(malware_files[y]))))*1.0/len(malware_files[x]+malware_files[y]) except: dis_mat[x,y] = 0 pickle.dump( dis_mat, open( "matrixbin", "wb" ) ) pickle.dump( malware_class, open( "malwareclass", "wb" ) ) print "https://malwr.com"+pickle.load(open("links","rb"))[195] print "https://mal<EMAIL>"+pickle.load(open("links","rb"))[313] <file_sep>import urllib3 from bs4 import BeautifulSoup import re, pickle, urllib3 from fractions import Fraction import threading, sys from timeit import default_timer as timer ##################################################################################################################### ##################################################################################################################### ############################## Definitions ################################# ##################################################################################################################### ##################################################################################################################### # Define Resource class which will store 3 maps, a name, and 2 anti virus ratings class Resource(): def __init__(self): self.resources = [] self.name = str self.link = str self.trojan = 0 self.avl = 0 # label depending on threshold self.avr = 0.0 # Ratio of malware labels positive class myThread (threading.Thread): def __init__(self, threadID, counter,r,select): threading.Thread.__init__(self) self.threadID = threadID self.counter = counter*r+1 self.r = r self.select = select def run(self): if self.select == 0: Scrape_Name(self.name, self.counter, self.r) if self.select == 1: Scrape_Resc(self.name, self.counter, self.r) malware_dict = {} # Dictionary of link to malware using md5 hash links = [] # List of every link # Set Arguments to command line or default try: test = int(sys.argv[1]) # command line argument setting whether program executes except: test = 0 try: pages = int(sys.argv[2]) # otherwise use commandline arguement 2 except: pages = 1 # Disable Unverified HTTPS Request urllib3.disable_warnings() ##################################################################################################################### ##################################################################################################################### ############################## Functions ################################# ##################################################################################################################### ##################################################################################################################### # Scrape links of resources def Scrape_Name(threadName, counter, r): for w in range (counter,counter+r): if w > pages: sys.exit(0) http = urllib3.PoolManager() index_url = "https://malwr.com/analysis/?page="+str(w) # change to whatever your url is index_page = http.urlopen('GET',index_url,preload_content=False).read() index_soup = BeautifulSoup(index_page,'lxml') href_table = index_soup.find('table', attrs={'class':'table table-striped'}) try: href_rows = href_table.find_all('tr') except: print "https://malwr.com/analysis/?page="+str(w) print "Request timed out." continue print len(href_rows) for row in href_rows: md5 = "" cols = row.find_all('td') mal = Resource() for ele in cols: a = re.search(r'(?<=href=\").*(?=\"><)',str(ele)) if a is not None: links.append(a.group()) if cols.index(ele) == 1: md5 = ele.text if cols.index(ele) == 4: try: mal.avr = Fraction(ele.text) mal.avl = int(ele.text.split("/")[0]) except: mal.avr = -1 mal.avl = -1 malware_dict[md5] = mal # Scrape name of resources def Scrape_Resc(threadName, counter, r): for q in range(counter,counter+r): if q > (len(links)-1): sys.exit(0) http = urllib3.PoolManager() url = "https://malwr.com"+links[q] # change to whatever your url is page = http.urlopen('GET',url,preload_content=False).read() soup = BeautifulSoup(page,'lxml') table = soup.find_all('table', attrs={'class':'table table-striped'}) table = table[1] rows = table.find_all('tr') for row in rows: cols = row.find_all("td") '''if rows.index(row)== 2: print row.find('td')''' if rows.index(row)== 3: md5 = row.find('td').text break malware = malware_dict[md5] malware.link = "https://malwr.com"+links[q] table = soup.findAll('div', {"class":"well mono"}) files = [] regs = [] mutex = [] resources = [files,regs,mutex] k = 0 for i in table: for j in i: try: resources[k].append(j.lstrip()) except: pass k+=1 table = soup.find_all('table', attrs={'class':'table table-striped table-bordered'}) av_pres = 0 for i in table: title = i.find('tr').find('th') if title.text == "Antivirus": av_pres = 1 t_rows = i.find_all('tr') virus_strings = [] vendor = "temp" for row in t_rows: cols = row.find_all('td') if len(cols)>0: it = iter(cols) vendor = next(it).text virus_name = next(it).text if ( virus_name == "\nClean\n"): pass else: virus_strings.append(virus_name) g = open("Virus_Label/"+md5,"w") for j in virus_strings: if "troj" in j.lower(): malware.trojan = 1 f = open("Virus_Label/Trojan.txt","a").write(md5+"\n") break g.write(j.lower()+"\n") try: f.close() g.close() except: pass break if av_pres == 0: g = open("Virus_Label/"+md5,"w") g.write("NO AV") g.close() try: malware.resources = resources malware.name = md5 pickle.dump( malware, open( "Data/file"+str(q), "wb" ) ) except: pass ##################################################################################################################### ##################################################################################################################### ############################## Main Execution ################################# ##################################################################################################################### ##################################################################################################################### if test == 1: ###################################################################################################### # Multithread scraping links for resources threadLock = threading.Lock() threads = [] if pages < 11: a = pages b = 1 else: a = 10 b = pages/11 + 1 for i in range (1,a+1): threads.append(myThread(i,(i-1),b,0)) threads[i-1].start() for t in threads: t.join() print len(links) ################################################################################################### # Multithread scraping name of resources entries = pages * 50 threadLock = threading.Lock() threads = [] if entries < 11: a = entries b = 1 else: a = 10 b = entries/10+1 for i in range (1,a+1): threads.append(myThread(i,(i-1),b,1)) threads[i-1].start() for t in threads: t.join() pickle.dump( malware_dict, open( "malware_dict", "wb" ) ) pickle.dump( links, open( "links", "wb" ) )
afe970f1661460a5fc7712cb9b5d21c8eb110465
[ "Python" ]
3
Python
ReversingWithMe/Malware-Resource-Clustering
81ab361777175a913441822cb5816da5eeaf2c32
e161cdf4ab5b7372c76cbb7f1dd1566db558ebea
refs/heads/master
<repo_name>miguel-depaz/blockchain-wallet<file_sep>/migrations/2_moolahcoin_migration.js let MoolahCoin = artifacts.require("MoolahCoin.sol"); module.exports = function (deployer) { deployer.deploy(MoolahCoin); }; <file_sep>/README.md # blockchain-wallet Blockchain Wallet to Manage Digital Assets (Fungible & Non Fungible Tokens) - React JS - Solidity Contracts (using ERC20, ERC721 standards) - Truffle Framework
6129b2abdd2fe455bbe5888385c08f13ca3a1153
[ "JavaScript", "Markdown" ]
2
JavaScript
miguel-depaz/blockchain-wallet
fb299a369e94d530ea22d1177a9f91e98fa320ef
1aa0defb7a9b6c07b1ed7bff51e2cb0d4b03f767
refs/heads/master
<repo_name>APuck003/CLI-app<file_sep>/models/user.rb class User < ActiveRecord::Base belongs_to :messages belongs_to :contacts end <file_sep>/bin/run.rb require_relative '../config/environment' require_relative '../send_text' puts "Message Sent" # Write the methods that see data # Either send text or see data or view calendar # Make the video <file_sep>/send_text.rb $all_names = [] $message = "" def get_name puts "Enter full name of contact: " name = gets.chomp $all_names << name puts "Do you want to send this message to another person?" choice = gets.chomp unless choice.downcase == "no" get_name end end def get_message puts "Enter message you want to send: " $message = gets.chomp.gsub("'", "`") end def execute_text message1 = Message.create(content: $message) $all_names.each do |name| contact = Contact.find_or_create_by(name: name) user = User.create(contact_id: contact.id, message_id: message1.id) contact.save message1.save user.save %x(osascript -e 'tell application "Messages" to send "#{$message}" to buddy "#{name}"') end end def title system("artii 'Texter' --font banner3-D | lolcat --animate --speed 40") end def send_text title get_name get_message execute_text end send_text
bf46ea08a384f695ca66da82022a3a53c043b967
[ "Ruby" ]
3
Ruby
APuck003/CLI-app
32d05e2374fa1dae1e42654ff9ded3ddcdb3df16
1f86cec74acb4bcfa4319b3703dbc0a38944dc58
refs/heads/master
<repo_name>pixinixi/pixinixi.github.io<file_sep>/web-crawler.html <!DOCTYPE html> <html lang="en-US"> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta name="author" content="angelika" /> <meta name="copyright" content="angelika" /> <meta property="og:type" content="article" /> <meta name="twitter:card" content="summary"> <meta name="keywords" content="python, dane, otodom, mieszkania, web scraping, " /> <meta property="og:title" content="Web crawler - piszemy robota - pajączka "/> <meta property="og:url" content="./web-crawler.html" /> <meta property="og:description" content="Web scraping to technika służąca do wydobywania informacji z sieci za pomocą programów komputerowych. W tym poście napiszemy robota - pajączka, który pobierze nam informacje o ofertach mieszkaniowych z serwisu otodom.pl. Do zbudowania pajączka potrzebować będziemy biblioteki requests oraz BeautifulSoup. Requests posłuży nam do obsługi protokołu HTTP czyli wysyłania żądań i odbierania odpowiedzi, natomiast BeautifulSoup do wydobycia danych z surowego htmla." /> <meta property="og:site_name" content="<NAME>" /> <meta property="og:article:author" content="angelika" /> <meta property="og:article:published_time" content="2017-11-20T20:18:00+01:00" /> <meta name="twitter:title" content="Web crawler - piszemy robota - pajączka "> <meta name="twitter:description" content="Web scraping to technika służąca do wydobywania informacji z sieci za pomocą programów komputerowych. W tym poście napiszemy robota - pajączka, który pobierze nam informacje o ofertach mieszkaniowych z serwisu otodom.pl. Do zbudowania pajączka potrzebować będziemy biblioteki requests oraz BeautifulSoup. Requests posłuży nam do obsługi protokołu HTTP czyli wysyłania żądań i odbierania odpowiedzi, natomiast BeautifulSoup do wydobycia danych z surowego htmla."> <title>Web crawler - piszemy robota - pajączka · <NAME> </title> <link href="//netdna.bootstrapcdn.com/twitter-bootstrap/2.3.2/css/bootstrap-combined.min.css" rel="stylesheet"> <link href="//netdna.bootstrapcdn.com/font-awesome/4.0.1/css/font-awesome.css" rel="stylesheet"> <link rel="stylesheet" type="text/css" href="./theme/css/pygments.css" media="screen"> <link rel="stylesheet" type="text/css" href="./theme/tipuesearch/tipuesearch.css" media="screen"> <link rel="stylesheet" type="text/css" href="./theme/css/elegant.css" media="screen"> <link rel="stylesheet" type="text/css" href="./theme/css/custom.css" media="screen"> <link rel="shortcut icon" href="./theme/images/favicon.ico" type="image/x-icon" type="image/png" /> <link rel="icon" href="./theme/images/apple-touch-icon-152x152.png" type="image/png" /> <link rel="apple-touch-icon" href="./theme/images/apple-touch-icon.png" type="image/png" /> <link rel="apple-touch-icon" sizes="57x57" href="./theme/images/apple-touch-icon-57x57.png" type="image/png" /> <link rel="apple-touch-icon" sizes="72x72" href="./theme/images/apple-touch-icon-72x72.png" type="image/png" /> <link rel="apple-touch-icon" sizes="76x76" href="./theme/images/apple-touch-icon-76x76.png" type="image/png" /> <link rel="apple-touch-icon" sizes="114x114" href="./theme/images/apple-touch-icon-114x114.png" type="image/png" /> <link rel="apple-touch-icon" sizes="120x120" href="./theme/images/apple-touch-icon-120x120.png" type="image/png" /> <link rel="apple-touch-icon" sizes="144x144" href="./theme/images/apple-touch-icon-144x144.png" type="image/png" /> <link rel="apple-touch-icon" sizes="152x152" href="./theme/images/apple-touch-icon-152x152.png" type="image/png" /> </head> <body> <div id="content-sans-footer"> <div class="navbar navbar-static-top"> <div class="navbar-inner"> <div class="container-fluid"> <a class="btn btn-navbar" data-toggle="collapse" data-target=".nav-collapse"> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </a> <a class="brand" href="./"><span class=site-name><NAME></span></a> <div class="nav-collapse collapse"> <ul class="nav pull-right top-menu"> <li ><a href=".">Home</a></li> <li ><a href="./categories.html">Categories</a></li> <li ><a href="./tags.html">Tags</a></li> <li ><a href="./archives.html">Archives</a></li> <li><form class="navbar-search" action="./search.html" onsubmit="return validateForm(this.elements['q'].value);"> <input type="text" class="search-query" placeholder="Search" name="q" id="tipue_search_input"></form></li> </ul> </div> </div> </div> </div> <div class="container-fluid"> <div class="row-fluid"> <div class="span1"></div> <div class="span10"> <article> <div class="row-fluid"> <header class="page-header span10 offset2"> <h1><a href="./web-crawler.html"> Web crawler <small> piszemy robota - pajączka </small> </a></h1> </header> </div> <div class="row-fluid"> <div class="span8 offset2 article-content"> <div class="cell border-box-sizing text_cell rendered"><div class="prompt input_prompt"> </div> <div class="inner_cell"> <div class="text_cell_render border-box-sizing rendered_html"> <p>Web scraping to technika służąca do wydobywania informacji z sieci za pomocą programów komputerowych. W tym poście napiszemy robota - pajączka, który pobierze nam informacje o ofertach mieszkaniowych z serwisu otodom.pl.</p> </div> </div> </div> <div class="cell border-box-sizing text_cell rendered"><div class="prompt input_prompt"> </div> <div class="inner_cell"> <div class="text_cell_render border-box-sizing rendered_html"> <p><img alt="alt text" src="/theme/images/spider.png" title="Logo Title Text 1" /></p> </div> </div> </div> <div class="cell border-box-sizing text_cell rendered"><div class="prompt input_prompt"> </div> <div class="inner_cell"> <div class="text_cell_render border-box-sizing rendered_html"> <p>Do zbudowania pajączka potrzebować będziemy biblioteki requests oraz BeautifulSoup. Requests posłuży nam do obsługi protokołu HTTP czyli wysyłania żądań i odbierania odpowiedzi, natomiast BeautifulSoup do wydobycia danych z surowego htmla.</p> </div> </div> </div> <div class="cell border-box-sizing code_cell rendered"> <div class="input"> <div class="prompt input_prompt">In [1]:</div> <div class="inner_cell"> <div class="input_area"> <div class=" highlight hl-ipython3"><pre><span></span><span class="kn">import</span> <span class="nn">requests</span> <span class="kn">from</span> <span class="nn">bs4</span> <span class="k">import</span> <span class="n">BeautifulSoup</span> </pre></div> </div> </div> </div> </div> <div class="cell border-box-sizing text_cell rendered"><div class="prompt input_prompt"> </div> <div class="inner_cell"> <div class="text_cell_render border-box-sizing rendered_html"> <p>Otworzmy plik, w którym zapisywane będą informacje o ofertach.</p> </div> </div> </div> <div class="cell border-box-sizing code_cell rendered"> <div class="input"> <div class="prompt input_prompt">In [2]:</div> <div class="inner_cell"> <div class="input_area"> <div class=" highlight hl-ipython3"><pre><span></span><span class="n">file</span> <span class="o">=</span> <span class="nb">open</span><span class="p">(</span><span class="s2">"ustka.txt"</span><span class="p">,</span> <span class="s2">"w"</span><span class="p">)</span> </pre></div> </div> </div> </div> </div> <div class="cell border-box-sizing text_cell rendered"><div class="prompt input_prompt"> </div> <div class="inner_cell"> <div class="text_cell_render border-box-sizing rendered_html"> <p>Zdefiniujmy pierwszą funkcję, która odpowiedzalna będzie za znalezienie linków do indywidualnych ofert.</p> </div> </div> </div> <div class="cell border-box-sizing code_cell rendered"> <div class="input"> <div class="prompt input_prompt">In [3]:</div> <div class="inner_cell"> <div class="input_area"> <div class=" highlight hl-ipython3"><pre><span></span><span class="k">def</span> <span class="nf">spider</span><span class="p">(</span><span class="n">max_page</span><span class="p">):</span> <span class="sd">""" znajduje linki do ofert """</span> <span class="c1"># większe miasta będą miały wiele ofert, które znajdować się będą na kolejnych stronach,</span> <span class="c1"># stworzymy pętle, która odwiedzi wszystkie strony do zmiennej max_page</span> <span class="n">page</span> <span class="o">=</span> <span class="mi">1</span> <span class="k">while</span> <span class="n">page</span> <span class="o"><=</span> <span class="n">max_page</span><span class="p">:</span> <span class="c1"># link do strony, dla każdego miasta będzie wyglądał inaczej</span> <span class="n">url</span> <span class="o">=</span> <span class="s2">"https://www.otodom.pl/sprzedaz/mieszkanie/ustka/?page="</span> <span class="o">+</span> <span class="nb">str</span><span class="p">(</span><span class="n">page</span><span class="p">)</span> <span class="n">source</span> <span class="o">=</span> <span class="n">requests</span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="n">url</span><span class="p">)</span> <span class="c1"># plain - surowy html strony</span> <span class="n">plain</span> <span class="o">=</span> <span class="n">source</span><span class="o">.</span><span class="n">text</span> <span class="n">soup</span> <span class="o">=</span> <span class="n">BeautifulSoup</span><span class="p">(</span><span class="n">plain</span><span class="p">,</span> <span class="s2">"html.parser"</span><span class="p">)</span> <span class="c1"># dla każdej strony z listami ofert odwiedzimy linki prowadzące do szczegółowych </span> <span class="c1"># informacji o ofercie</span> <span class="k">for</span> <span class="n">link</span> <span class="ow">in</span> <span class="n">soup</span><span class="o">.</span><span class="n">findAll</span><span class="p">(</span><span class="s2">"header"</span><span class="p">,</span> <span class="p">{</span><span class="s2">"class"</span><span class="p">:</span> <span class="s2">"offer-item-header"</span><span class="p">}):</span> <span class="n">find_href</span> <span class="o">=</span> <span class="n">link</span><span class="o">.</span><span class="n">a</span> <span class="n">href</span> <span class="o">=</span> <span class="n">find_href</span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="s2">"href"</span><span class="p">)</span> <span class="c1"># funkcja, która pobierze interesujące nas dane</span> <span class="n">get_data</span><span class="p">(</span><span class="n">href</span><span class="p">)</span> <span class="n">page</span> <span class="o">+=</span> <span class="mi">1</span> </pre></div> </div> </div> </div> </div> <div class="cell border-box-sizing text_cell rendered"><div class="prompt input_prompt"> </div> <div class="inner_cell"> <div class="text_cell_render border-box-sizing rendered_html"> <p>Mając funkcję, która znajdzie nam strony ze szczegółowymi informacjami o ofertach, możemy dane z tej strony pobrać.</p> </div> </div> </div> <div class="cell border-box-sizing code_cell rendered"> <div class="input"> <div class="prompt input_prompt">In [4]:</div> <div class="inner_cell"> <div class="input_area"> <div class=" highlight hl-ipython3"><pre><span></span><span class="k">def</span> <span class="nf">get_data</span><span class="p">(</span><span class="n">url</span><span class="p">):</span> <span class="sd">""" pobiera dane o ofertach """</span> <span class="n">source</span> <span class="o">=</span> <span class="n">requests</span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="n">url</span><span class="p">)</span> <span class="c1"># ponownie pobieramy surowy html strony, tym razem, ten zawierający szczegółowe informacje</span> <span class="n">plain</span> <span class="o">=</span> <span class="n">source</span><span class="o">.</span><span class="n">text</span> <span class="n">soup</span> <span class="o">=</span> <span class="n">BeautifulSoup</span><span class="p">(</span><span class="n">plain</span><span class="p">,</span> <span class="s2">"html.parser"</span><span class="p">)</span> <span class="c1"># łopatologia do oddzielenia ofert ;)</span> <span class="n">file</span><span class="o">.</span><span class="n">write</span><span class="p">(</span><span class="s2">"_!_!_"</span><span class="p">)</span> <span class="c1"># wreszcie możemy wyszukać to co nas interesuje, a następnie zapisać do pliku .txt</span> <span class="k">for</span> <span class="n">title</span> <span class="ow">in</span> <span class="n">soup</span><span class="o">.</span><span class="n">findAll</span><span class="p">(</span><span class="s1">'h1'</span><span class="p">,</span> <span class="p">{</span><span class="s1">'itemprop'</span><span class="p">:</span> <span class="s1">'name'</span><span class="p">}):</span> <span class="n">title_text</span> <span class="o">=</span> <span class="n">title</span><span class="o">.</span><span class="n">text</span> <span class="n">file</span><span class="o">.</span><span class="n">write</span><span class="p">(</span><span class="n">title_text</span><span class="p">)</span> <span class="k">for</span> <span class="n">adres</span> <span class="ow">in</span> <span class="n">soup</span><span class="o">.</span><span class="n">findAll</span><span class="p">(</span><span class="s1">'p'</span><span class="p">,</span> <span class="p">{</span><span class="s1">'class'</span><span class="p">:</span> <span class="s1">'address-links'</span><span class="p">}):</span> <span class="n">adres</span> <span class="o">=</span> <span class="n">adres</span><span class="o">.</span><span class="n">text</span> <span class="n">file</span><span class="o">.</span><span class="n">write</span><span class="p">(</span><span class="s2">"dzielnicaadres:"</span> <span class="o">+</span> <span class="n">adres</span><span class="p">)</span> <span class="n">file</span><span class="o">.</span><span class="n">write</span><span class="p">(</span><span class="s2">"k_ad"</span><span class="p">)</span> <span class="k">for</span> <span class="n">main</span> <span class="ow">in</span> <span class="n">soup</span><span class="o">.</span><span class="n">findAll</span><span class="p">(</span><span class="s1">'ul'</span><span class="p">,</span> <span class="p">{</span><span class="s1">'class'</span><span class="p">:</span> <span class="s1">'main-list'</span><span class="p">}):</span> <span class="n">main_text</span> <span class="o">=</span> <span class="n">main</span><span class="o">.</span><span class="n">text</span> <span class="n">file</span><span class="o">.</span><span class="n">write</span><span class="p">(</span><span class="n">main_text</span><span class="p">)</span> <span class="k">for</span> <span class="n">sub</span> <span class="ow">in</span> <span class="n">soup</span><span class="o">.</span><span class="n">findAll</span><span class="p">(</span><span class="s1">'ul'</span><span class="p">,</span> <span class="p">{</span><span class="s1">'class'</span><span class="p">:</span> <span class="s1">'sub-list'</span><span class="p">}):</span> <span class="n">sub_text</span> <span class="o">=</span> <span class="n">sub</span><span class="o">.</span><span class="n">text</span> <span class="n">file</span><span class="o">.</span><span class="n">write</span><span class="p">(</span><span class="n">sub_text</span><span class="p">)</span> <span class="k">for</span> <span class="n">add</span> <span class="ow">in</span> <span class="n">soup</span><span class="o">.</span><span class="n">findAll</span><span class="p">(</span><span class="s1">'ul'</span><span class="p">,</span> <span class="p">{</span><span class="s1">'class'</span><span class="p">:</span> <span class="s1">'dotted-list'</span><span class="p">}):</span> <span class="n">add_text</span> <span class="o">=</span> <span class="n">add</span><span class="o">.</span><span class="n">text</span> <span class="n">file</span><span class="o">.</span><span class="n">write</span><span class="p">(</span><span class="n">add_text</span><span class="p">)</span> <span class="k">for</span> <span class="nb">id</span> <span class="ow">in</span> <span class="n">soup</span><span class="o">.</span><span class="n">findAll</span><span class="p">(</span><span class="s1">'section'</span><span class="p">,</span> <span class="p">{</span><span class="s1">'class'</span><span class="p">:</span> <span class="s1">'section-offer-text updated'</span><span class="p">}):</span> <span class="n">id_text</span> <span class="o">=</span> <span class="nb">id</span><span class="o">.</span><span class="n">text</span> <span class="n">file</span><span class="o">.</span><span class="n">write</span><span class="p">(</span><span class="n">id_text</span><span class="p">)</span> <span class="k">for</span> <span class="n">j</span> <span class="ow">in</span> <span class="n">soup</span><span class="o">.</span><span class="n">select</span><span class="p">(</span><span class="s1">'#adDetailInlineMap'</span><span class="p">):</span> <span class="n">file</span><span class="o">.</span><span class="n">write</span><span class="p">(</span><span class="nb">str</span><span class="p">(</span><span class="n">j</span><span class="p">)</span> <span class="o">+</span> <span class="s2">"</span><span class="se">\n</span><span class="s2">"</span><span class="p">)</span> <span class="c1"># wywołując funkcję, do katalogu roboczego zostanie zapisany plik tekstowy z danymi o ofertach</span> <span class="n">spider</span><span class="p">(</span><span class="mi">1</span><span class="p">)</span> <span class="n">file</span><span class="o">.</span><span class="n">close</span><span class="p">()</span> </pre></div> </div> </div> </div> </div> <div class="cell border-box-sizing text_cell rendered"><div class="prompt input_prompt"> </div> <div class="inner_cell"> <div class="text_cell_render border-box-sizing rendered_html"> <p>Sprawdźmy pobrany plik.</p> </div> </div> </div> <div class="cell border-box-sizing code_cell rendered"> <div class="input"> <div class="prompt input_prompt">In [5]:</div> <div class="inner_cell"> <div class="input_area"> <div class=" highlight hl-ipython3"><pre><span></span><span class="n">ustka</span> <span class="o">=</span> <span class="nb">open</span><span class="p">(</span><span class="s2">"ustka.txt"</span><span class="p">,</span><span class="s2">"r"</span><span class="p">)</span> <span class="nb">print</span><span class="p">(</span><span class="n">ustka</span><span class="o">.</span><span class="n">read</span><span class="p">()[:</span><span class="mi">550</span><span class="p">])</span> </pre></div> </div> </div> </div> <div class="output_wrapper"> <div class="output"> <div class="output_area"> <div class="prompt"></div> <div class="output_subarea output_stream output_stdout output_text"> <pre>_!_!_Bezpośrednio 2 pokoje w Ustce tel. 517.060.524dzielnicaadres:Mieszkanie na sprzedaż, Ustka, pomorskie, XX-lecia PRL - Zobacz na mapiek_addzielnicaadres:Mieszkanie na sprzedaż, Ustka, pomorskie, XX-lecia PRLk_ad Cena 145 000 zł 4 315 zł/m² Powierzchnia 33,60 m² Liczba pokoi 2 Piętro 3 (z 4) Rynek: wtórny Rodzaj zabudowy: blok Materiał budynku: cegła Okna: plastikowe Ogrzewanie: miejskie Forma własności: spółdzielcze wł. z KW telewizja kablowa telefon domofon / wideofon balkon piwnica oddzielna kuchnia Nr oferty w Otodom: 5366 </pre> </div> </div> </div> </div> </div> <div class="cell border-box-sizing text_cell rendered"><div class="prompt input_prompt"> </div> <div class="inner_cell"> <div class="text_cell_render border-box-sizing rendered_html"> <p>Ok, mamy dane o ofertach, jednak znajdują się one w pliku tekstowym. Sformatuję go do formatu, który ułatwiłby analizę takich danych.</p> </div> </div> </div> <div class="cell border-box-sizing text_cell rendered"><div class="prompt input_prompt"> </div> <div class="inner_cell"> <div class="text_cell_render border-box-sizing rendered_html"> <p>Zaimportuję w tym celu dwa moduły, re do wyrażeń regularnych oraz csv do zapisania danych w formacie wartości rozdzielonych przecinkiem.</p> </div> </div> </div> <div class="cell border-box-sizing code_cell rendered"> <div class="input"> <div class="prompt input_prompt">In [6]:</div> <div class="inner_cell"> <div class="input_area"> <div class=" highlight hl-ipython3"><pre><span></span><span class="kn">import</span> <span class="nn">re</span> <span class="kn">import</span> <span class="nn">csv</span> </pre></div> </div> </div> </div> </div> <div class="cell border-box-sizing code_cell rendered"> <div class="input"> <div class="prompt input_prompt">In [7]:</div> <div class="inner_cell"> <div class="input_area"> <div class=" highlight hl-ipython3"><pre><span></span><span class="c1"># otwiera plik txt z ofertami</span> <span class="n">file</span> <span class="o">=</span> <span class="nb">open</span><span class="p">(</span><span class="s1">'ustka.txt'</span><span class="p">,</span> <span class="s1">'r'</span><span class="p">)</span> <span class="c1"># kilka zmiennych, które przydadzą się do rodzielenia mieszkań, a następnie ich charakterystyk</span> <span class="n">read_file</span> <span class="o">=</span> <span class="n">file</span><span class="o">.</span><span class="n">read</span><span class="p">()</span> <span class="n">lista_mieszkania_zmienne</span> <span class="o">=</span> <span class="p">[]</span> <span class="n">lista_mieszkan</span> <span class="o">=</span> <span class="n">read_file</span><span class="o">.</span><span class="n">split</span><span class="p">(</span><span class="s2">"_!_!_"</span><span class="p">)</span> <span class="n">podzielona_lista_mieszkan</span> <span class="o">=</span> <span class="p">[]</span> </pre></div> </div> </div> </div> </div> <div class="cell border-box-sizing code_cell rendered"> <div class="input"> <div class="prompt input_prompt">In [8]:</div> <div class="inner_cell"> <div class="input_area"> <div class=" highlight hl-ipython3"><pre><span></span><span class="c1"># pętla rozdzielająca mieszkania</span> <span class="k">for</span> <span class="n">mieszkanie</span> <span class="ow">in</span> <span class="n">lista_mieszkan</span><span class="p">:</span> <span class="n">koniec_tytulu</span> <span class="o">=</span> <span class="n">mieszkanie</span><span class="o">.</span><span class="n">find</span><span class="p">(</span><span class="s2">"dzielnicaadres:"</span><span class="p">,</span> <span class="mi">1</span><span class="p">)</span> <span class="n">mieszkanie</span> <span class="o">=</span> <span class="n">mieszkanie</span><span class="p">[</span><span class="n">koniec_tytulu</span><span class="p">:]</span> <span class="n">podzielona_lista_mieszkan</span><span class="o">.</span><span class="n">append</span><span class="p">(</span><span class="n">mieszkanie</span><span class="p">)</span> </pre></div> </div> </div> </div> </div> <div class="cell border-box-sizing code_cell rendered"> <div class="input"> <div class="prompt input_prompt">In [9]:</div> <div class="inner_cell"> <div class="input_area"> <div class=" highlight hl-ipython3"><pre><span></span><span class="c1"># pętla do wyszukiwania informacji, cena, powierzchnia, liczba pokoi i inne</span> <span class="k">for</span> <span class="n">mieszkanie</span> <span class="ow">in</span> <span class="n">podzielona_lista_mieszkan</span><span class="p">:</span> <span class="c1"># zmienne, które pojawiają się w każdej ofercie</span> <span class="nb">id</span> <span class="o">=</span> <span class="n">mieszkanie</span><span class="o">.</span><span class="n">find</span><span class="p">(</span><span class="s1">'Nr oferty w Otodom:'</span><span class="p">)</span> <span class="o">+</span> <span class="mi">20</span> <span class="n">id_koniec</span> <span class="o">=</span> <span class="nb">id</span> <span class="o">+</span> <span class="mi">8</span> <span class="n">id_oferty</span> <span class="o">=</span> <span class="n">mieszkanie</span><span class="p">[</span><span class="nb">id</span><span class="p">:</span><span class="n">id_koniec</span><span class="p">]</span> <span class="n">cena</span> <span class="o">=</span> <span class="n">mieszkanie</span><span class="o">.</span><span class="n">find</span><span class="p">(</span><span class="s1">'Cena'</span><span class="p">)</span> <span class="o">+</span> <span class="mi">5</span> <span class="n">cena_koniec</span> <span class="o">=</span> <span class="n">mieszkanie</span><span class="o">.</span><span class="n">find</span><span class="p">(</span><span class="s1">'zł'</span><span class="p">)</span> <span class="o">-</span> <span class="mi">1</span> <span class="n">powierzchnia</span> <span class="o">=</span> <span class="n">mieszkanie</span><span class="o">.</span><span class="n">find</span><span class="p">(</span><span class="s1">'Powierzchnia'</span><span class="p">)</span> <span class="o">+</span> <span class="mi">13</span> <span class="n">powierzchnia_koniec</span> <span class="o">=</span> <span class="n">mieszkanie</span><span class="o">.</span><span class="n">find</span><span class="p">(</span><span class="s1">'Liczba pokoi'</span><span class="p">)</span> <span class="o">-</span> <span class="mi">4</span> <span class="n">liczba_pokoi</span> <span class="o">=</span> <span class="n">mieszkanie</span><span class="o">.</span><span class="n">find</span><span class="p">(</span><span class="s1">'Liczba pokoi'</span><span class="p">)</span> <span class="o">+</span> <span class="mi">13</span> <span class="n">liczba_pokoi_koniec</span> <span class="o">=</span> <span class="n">liczba_pokoi</span> <span class="o">+</span> <span class="mi">1</span> <span class="n">adres1</span> <span class="o">=</span> <span class="n">mieszkanie</span><span class="o">.</span><span class="n">find</span><span class="p">(</span><span class="s1">'dzielnicaadres:'</span><span class="p">)</span> <span class="o">+</span> <span class="mi">39</span> <span class="n">adres1_koniec</span> <span class="o">=</span> <span class="n">mieszkanie</span><span class="o">.</span><span class="n">find</span><span class="p">(</span><span class="s1">'- Zobacz na mapie'</span><span class="p">)</span> <span class="n">lista_mieszkania_zmienne</span><span class="o">.</span><span class="n">append</span><span class="p">(</span><span class="n">id_oferty</span><span class="p">)</span> <span class="n">price</span> <span class="o">=</span> <span class="n">mieszkanie</span><span class="p">[</span><span class="n">cena</span><span class="p">:</span><span class="n">cena_koniec</span><span class="p">]</span> <span class="n">lista_mieszkania_zmienne</span><span class="o">.</span><span class="n">append</span><span class="p">(</span><span class="n">price</span><span class="p">)</span> <span class="n">size</span> <span class="o">=</span> <span class="n">mieszkanie</span><span class="p">[</span><span class="n">powierzchnia</span><span class="p">:</span><span class="n">powierzchnia_koniec</span><span class="p">]</span> <span class="n">lista_mieszkania_zmienne</span><span class="o">.</span><span class="n">append</span><span class="p">(</span><span class="n">size</span><span class="p">)</span> <span class="n">rooms</span> <span class="o">=</span> <span class="n">mieszkanie</span><span class="p">[</span><span class="n">liczba_pokoi</span><span class="p">:</span><span class="n">liczba_pokoi_koniec</span><span class="p">]</span> <span class="n">lista_mieszkania_zmienne</span><span class="o">.</span><span class="n">append</span><span class="p">(</span><span class="n">rooms</span><span class="p">)</span> <span class="c1"># informacji o piętrze może brakować w takim wypadku wpisze "NA"</span> <span class="n">pi</span> <span class="o">=</span> <span class="s2">"Piętro"</span> <span class="k">if</span> <span class="n">pi</span> <span class="ow">in</span> <span class="n">mieszkanie</span><span class="p">:</span> <span class="n">pietro</span> <span class="o">=</span> <span class="n">mieszkanie</span><span class="o">.</span><span class="n">find</span><span class="p">(</span><span class="s1">'Piętro'</span><span class="p">)</span> <span class="o">+</span> <span class="mi">7</span> <span class="n">pietro_koniec</span> <span class="o">=</span> <span class="n">pietro</span> <span class="o">+</span> <span class="mi">1</span> <span class="n">pietra</span> <span class="o">=</span> <span class="n">mieszkanie</span><span class="p">[</span><span class="n">pietro</span><span class="p">:</span><span class="n">pietro_koniec</span><span class="p">]</span> <span class="n">lista_mieszkania_zmienne</span><span class="o">.</span><span class="n">append</span><span class="p">(</span><span class="n">pietra</span><span class="p">)</span> <span class="k">else</span><span class="p">:</span> <span class="n">lista_mieszkania_zmienne</span><span class="o">.</span><span class="n">append</span><span class="p">(</span><span class="s2">"NA"</span><span class="p">)</span> <span class="n">adres</span> <span class="o">=</span> <span class="n">mieszkanie</span><span class="p">[</span><span class="n">adres1</span><span class="p">:</span><span class="n">adres1_koniec</span><span class="p">]</span> <span class="n">lista_mieszkania_zmienne</span><span class="o">.</span><span class="n">append</span><span class="p">(</span><span class="n">adres</span><span class="p">)</span> <span class="n">longitude</span> <span class="o">=</span> <span class="n">mieszkanie</span><span class="o">.</span><span class="n">find</span><span class="p">(</span><span class="s1">'data-lat='</span><span class="p">)</span> <span class="o">+</span> <span class="mi">10</span> <span class="n">latitude</span> <span class="o">=</span> <span class="n">mieszkanie</span><span class="o">.</span><span class="n">find</span><span class="p">(</span><span class="s1">'data-lon='</span><span class="p">)</span> <span class="o">+</span> <span class="mi">10</span> <span class="n">longitude_koniec</span> <span class="o">=</span> <span class="n">latitude</span> <span class="o">-</span> <span class="mi">12</span> <span class="n">latitude_koniec</span> <span class="o">=</span> <span class="n">mieszkanie</span><span class="o">.</span><span class="n">find</span><span class="p">(</span><span class="s1">'data-poi-lat='</span><span class="p">)</span> <span class="o">-</span> <span class="mi">2</span> <span class="n">dlugosc</span> <span class="o">=</span> <span class="n">mieszkanie</span><span class="p">[</span><span class="n">longitude</span><span class="p">:</span><span class="n">longitude_koniec</span><span class="p">]</span> <span class="n">lista_mieszkania_zmienne</span><span class="o">.</span><span class="n">append</span><span class="p">(</span><span class="n">dlugosc</span><span class="p">)</span> <span class="n">szerokosc</span> <span class="o">=</span> <span class="n">mieszkanie</span><span class="p">[</span><span class="n">latitude</span><span class="p">:</span><span class="n">latitude_koniec</span><span class="p">]</span> <span class="n">lista_mieszkania_zmienne</span><span class="o">.</span><span class="n">append</span><span class="p">(</span><span class="n">szerokosc</span><span class="p">)</span> <span class="c1"># zmienne kategoryczne</span> <span class="n">cat_var</span> <span class="o">=</span> <span class="p">(</span><span class="s2">"Rynek:"</span><span class="p">,</span> <span class="s2">"Rodzaj zabudowy:"</span><span class="p">,</span> <span class="s2">"Materiał budynku:"</span><span class="p">,</span> <span class="s2">"Okna:"</span><span class="p">,</span> <span class="s2">"Ogrzewanie:"</span><span class="p">,</span> <span class="s2">"Rok budowy:"</span><span class="p">,</span> <span class="s2">"Stan wykończenia: do"</span><span class="p">,</span> <span class="s2">"Czynsz:"</span><span class="p">,</span> <span class="s2">"Forma własności:"</span><span class="p">)</span> <span class="k">for</span> <span class="n">var</span> <span class="ow">in</span> <span class="n">cat_var</span><span class="p">:</span> <span class="c1"># wyszukuje wsytępujące po zmiennych z kat_var słowo czyli ich kategorie</span> <span class="n">regex</span> <span class="o">=</span> <span class="n">var</span> <span class="o">+</span> <span class="sa">r</span><span class="s2">" (\w+)"</span> <span class="n">match</span> <span class="o">=</span> <span class="n">re</span><span class="o">.</span><span class="n">search</span><span class="p">(</span><span class="n">regex</span><span class="p">,</span> <span class="n">mieszkanie</span><span class="p">)</span> <span class="k">if</span> <span class="n">match</span><span class="p">:</span> <span class="n">lista_mieszkania_zmienne</span><span class="o">.</span><span class="n">append</span><span class="p">(</span><span class="n">match</span><span class="o">.</span><span class="n">group</span><span class="p">(</span><span class="mi">1</span><span class="p">))</span> <span class="c1"># informacji mogło brakować, w takim wypadku wpisuje "0"</span> <span class="k">else</span><span class="p">:</span> <span class="n">lista_mieszkania_zmienne</span><span class="o">.</span><span class="n">append</span><span class="p">(</span><span class="s2">"0"</span><span class="p">)</span> <span class="c1"># poniższe zmienne są opcjonalne, jeśli wystąpiły w opisie mieszkania przypisujemy 1, jeśli nie 0</span> <span class="n">var01</span> <span class="o">=</span> <span class="p">(</span><span class="s2">"internet"</span><span class="p">,</span> <span class="s2">"telewizja kablowa"</span><span class="p">,</span> <span class="s2">"telefon"</span><span class="p">,</span> <span class="s2">"rolety antywłamaniowe"</span><span class="p">,</span> <span class="s2">"drzwi / okna antywłamaniowe"</span><span class="p">,</span> <span class="s2">"domofon / wideofon"</span><span class="p">,</span><span class="s2">"monitoring / ochrona"</span><span class="p">,</span> <span class="s2">"system alarmowy"</span><span class="p">,</span> <span class="s2">"teren zamknięty"</span><span class="p">,</span> <span class="s2">"meble"</span><span class="p">,</span> <span class="s2">"pralka"</span><span class="p">,</span> <span class="s2">"zmywarka"</span><span class="p">,</span> <span class="s2">"lodówka"</span><span class="p">,</span> <span class="s2">"kuchenka"</span><span class="p">,</span> <span class="s2">"piekarnik"</span><span class="p">,</span> <span class="s2">"telewizor"</span><span class="p">,</span> <span class="s2">"balkon"</span><span class="p">,</span> <span class="s2">"pom. użytkowe"</span><span class="p">,</span> <span class="s2">"garaż/miejsce parkingowe"</span><span class="p">,</span> <span class="s2">"piwnica"</span><span class="p">,</span> <span class="s2">"ogródek"</span><span class="p">,</span> <span class="s2">"taras"</span><span class="p">,</span> <span class="s2">"winda"</span><span class="p">,</span> <span class="s2">"dwupoziomowe"</span><span class="p">,</span> <span class="s2">"oddzielna kuchnia"</span><span class="p">,</span> <span class="s2">"klimatyzacja"</span><span class="p">)</span> <span class="k">for</span> <span class="n">var</span> <span class="ow">in</span> <span class="n">var01</span><span class="p">:</span> <span class="k">if</span> <span class="n">var</span> <span class="ow">in</span> <span class="n">mieszkanie</span><span class="p">:</span> <span class="n">lista_mieszkania_zmienne</span><span class="o">.</span><span class="n">append</span><span class="p">(</span><span class="s2">"1"</span><span class="p">)</span> <span class="k">else</span><span class="p">:</span> <span class="n">lista_mieszkania_zmienne</span><span class="o">.</span><span class="n">append</span><span class="p">(</span><span class="s2">"0"</span><span class="p">)</span> </pre></div> </div> </div> </div> </div> <div class="cell border-box-sizing code_cell rendered"> <div class="input"> <div class="prompt input_prompt">In [10]:</div> <div class="inner_cell"> <div class="input_area"> <div class=" highlight hl-ipython3"><pre><span></span><span class="c1"># lista ze wszystkimi wyszukanymi iformacjami</span> <span class="n">lista_do_csv</span> <span class="o">=</span> <span class="p">[</span><span class="n">lista_mieszkania_zmienne</span><span class="p">[</span><span class="n">x</span><span class="p">:</span><span class="n">x</span> <span class="o">+</span> <span class="mi">43</span><span class="p">]</span> <span class="k">for</span> <span class="n">x</span> <span class="ow">in</span> <span class="nb">range</span><span class="p">(</span><span class="mi">0</span><span class="p">,</span> <span class="nb">len</span><span class="p">(</span><span class="n">lista_mieszkania_zmienne</span><span class="p">),</span> <span class="mi">43</span><span class="p">)]</span> <span class="c1"># usuwa duplikaty (oferty wyróżnione zapisują się kilkukrotnie)</span> <span class="kn">import</span> <span class="nn">itertools</span> <span class="n">lista_do_csv</span><span class="o">.</span><span class="n">sort</span><span class="p">()</span> <span class="n">lista_do_csv</span> <span class="o">=</span> <span class="nb">list</span><span class="p">(</span><span class="n">lista_do_csv</span> <span class="k">for</span> <span class="n">lista_do_csv</span><span class="p">,</span><span class="n">_</span> <span class="ow">in</span> <span class="n">itertools</span><span class="o">.</span><span class="n">groupby</span><span class="p">(</span><span class="n">lista_do_csv</span><span class="p">))</span> <span class="n">header</span> <span class="o">=</span> <span class="p">([</span><span class="s1">'id oferty'</span><span class="p">,</span><span class="s1">'cena (zł)'</span><span class="p">,</span> <span class="s1">'powierzchnia'</span><span class="p">,</span> <span class="s1">'liczba pokoi'</span><span class="p">,</span> <span class="s1">'piętro'</span><span class="p">,</span> <span class="s1">'adres'</span><span class="p">,</span> <span class="s2">"dlugosc"</span><span class="p">,</span> <span class="s2">"szerokosc"</span><span class="p">,</span> <span class="s2">"rynek"</span><span class="p">,</span> <span class="s2">"rodzaj zabudowy"</span><span class="p">,</span> <span class="s2">"materiał budynku"</span><span class="p">,</span> <span class="s2">"okna"</span><span class="p">,</span> <span class="s2">"ogrzewanie"</span><span class="p">,</span> <span class="s2">"rok budowy"</span><span class="p">,</span> <span class="s2">"stan wykończenia (do)"</span><span class="p">,</span> <span class="s2">"czynsz"</span><span class="p">,</span> <span class="s2">"forma własności"</span><span class="p">,</span> <span class="s2">"internet"</span><span class="p">,</span> <span class="s2">"telewizja kablowa"</span><span class="p">,</span> <span class="s2">"telefon"</span><span class="p">,</span> <span class="s2">"rolety antywłamaniowe"</span><span class="p">,</span> <span class="s2">"drzwi/okna antywłamaniowe"</span><span class="p">,</span> <span class="s2">"domofon/wideofon"</span><span class="p">,</span> <span class="s2">"monitoring/ochrona"</span><span class="p">,</span> <span class="s2">"system alarmowy"</span><span class="p">,</span> <span class="s2">"teren zamknięty"</span><span class="p">,</span> <span class="s2">"meble"</span><span class="p">,</span> <span class="s2">"pralka"</span><span class="p">,</span> <span class="s2">"zmywarka"</span><span class="p">,</span> <span class="s2">"lodówka"</span><span class="p">,</span> <span class="s2">"kuchenka"</span><span class="p">,</span> <span class="s2">"piekarnik"</span><span class="p">,</span> <span class="s2">"telewizor"</span><span class="p">,</span> <span class="s2">"balkon"</span><span class="p">,</span> <span class="s2">"pom. użytkowe"</span><span class="p">,</span> <span class="s2">"garaż/miejsce parkingowe"</span><span class="p">,</span> <span class="s2">"piwnica"</span><span class="p">,</span> <span class="s2">"ogródek"</span><span class="p">,</span> <span class="s2">"taras"</span><span class="p">,</span> <span class="s2">"winda"</span><span class="p">,</span> <span class="s2">"dwupoziomowe"</span><span class="p">,</span> <span class="s2">"oddzielna kuchnia"</span><span class="p">,</span> <span class="s2">"klimatyzacja"</span> <span class="p">])</span> <span class="c1"># zapisuje do csv</span> <span class="k">with</span> <span class="nb">open</span><span class="p">(</span><span class="s1">'ustka.csv'</span><span class="p">,</span> <span class="s1">'w'</span><span class="p">)</span> <span class="k">as</span> <span class="n">myfile</span><span class="p">:</span> <span class="n">wr</span> <span class="o">=</span> <span class="n">csv</span><span class="o">.</span><span class="n">writer</span><span class="p">(</span><span class="n">myfile</span><span class="p">,</span> <span class="n">quoting</span><span class="o">=</span><span class="n">csv</span><span class="o">.</span><span class="n">QUOTE_ALL</span><span class="p">)</span> <span class="n">wr</span><span class="o">.</span><span class="n">writerow</span><span class="p">(</span><span class="n">header</span><span class="p">)</span> <span class="k">for</span> <span class="n">row</span> <span class="ow">in</span> <span class="n">lista_do_csv</span><span class="p">:</span> <span class="n">wr</span><span class="o">.</span><span class="n">writerow</span><span class="p">(</span><span class="n">row</span><span class="p">)</span> <span class="n">file</span><span class="o">.</span><span class="n">close</span><span class="p">()</span> </pre></div> </div> </div> </div> </div> <div class="cell border-box-sizing text_cell rendered"><div class="prompt input_prompt"> </div> <div class="inner_cell"> <div class="text_cell_render border-box-sizing rendered_html"> <p>Sprawdźmy jak prezentuje się zapisany plik.</p> </div> </div> </div> <div class="cell border-box-sizing code_cell rendered"> <div class="input"> <div class="prompt input_prompt">In [11]:</div> <div class="inner_cell"> <div class="input_area"> <div class=" highlight hl-ipython3"><pre><span></span><span class="kn">import</span> <span class="nn">pandas</span> <span class="k">as</span> <span class="nn">pd</span> <span class="n">df</span> <span class="o">=</span> <span class="n">pd</span><span class="o">.</span><span class="n">read_csv</span><span class="p">(</span><span class="s2">"ustka.csv"</span><span class="p">)</span> <span class="n">df</span><span class="o">.</span><span class="n">iloc</span><span class="p">[</span><span class="mi">1</span><span class="p">:</span><span class="mi">5</span><span class="p">,:</span><span class="mi">9</span><span class="p">]</span> </pre></div> </div> </div> </div> <div class="output_wrapper"> <div class="output"> <div class="output_area"> <div class="prompt output_prompt">Out[11]:</div> <div class="output_html rendered_html output_subarea output_execute_result"> <div> <style> .dataframe thead tr:only-child th { text-align: right; } .dataframe thead th { text-align: left; } .dataframe tbody tr th { vertical-align: top; } </style> <table border="1" class="dataframe"> <thead> <tr style="text-align: right;"> <th></th> <th>id oferty</th> <th>cena (zł)</th> <th>powierzchnia</th> <th>liczba pokoi</th> <th>piętro</th> <th>adres</th> <th>dlugosc</th> <th>szerokosc</th> <th>rynek</th> </tr> </thead> <tbody> <tr> <th>1</th> <td>45747214.0</td> <td>169 000</td> <td>36,65</td> <td>2.0</td> <td>4</td> <td>Ustka, pomorskie, Legionów</td> <td>54.579717</td> <td>16.870866</td> <td>wtórny</td> </tr> <tr> <th>2</th> <td>45786782.0</td> <td>420 000</td> <td>64,70</td> <td>3.0</td> <td>p</td> <td>Ustka, pomorskie, Słowiańska</td> <td>54.585518</td> <td>16.859341</td> <td>wtórny</td> </tr> <tr> <th>3</th> <td>49267140.0</td> <td>269 000</td> <td>74</td> <td>2.0</td> <td>NaN</td> <td>Ustka, pomorskie</td> <td>54.576294</td> <td>16.855700</td> <td>wtórny</td> </tr> <tr> <th>4</th> <td>49421054.0</td> <td>259 000</td> <td>53,93</td> <td>2.0</td> <td>1</td> <td>Ustka, pomorskie, <NAME>iej</td> <td>54.583126</td> <td>16.857657</td> <td>wtórny</td> </tr> </tbody> </table> </div> </div> </div> </div> </div> </div> <div class="cell border-box-sizing text_cell rendered"><div class="prompt input_prompt"> </div> <div class="inner_cell"> <div class="text_cell_render border-box-sizing rendered_html"> <p>Wygląda na gotowy do analizy! :)</p> <p>Cały kod dostępny jest na <a href="https://github.com/pixinixi/otodom-crawler">repozytorium</a>.</p> </div> </div> </div> <script type="text/javascript">if (!document.getElementById('mathjaxscript_pelican_#%@#$@#')) { var mathjaxscript = document.createElement('script'); mathjaxscript.id = 'mathjaxscript_pelican_#%@#$@#'; mathjaxscript.type = 'text/javascript'; mathjaxscript.src = '//cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.1/MathJax.js?config=TeX-AMS-MML_HTMLorMML'; mathjaxscript[(window.opera ? "innerHTML" : "text")] = "MathJax.Hub.Config({" + " config: ['MMLorHTML.js']," + " TeX: { extensions: ['AMSmath.js','AMSsymbols.js','noErrors.js','noUndefined.js'], equationNumbers: { autoNumber: 'AMS' } }," + " jax: ['input/TeX','input/MathML','output/HTML-CSS']," + " extensions: ['tex2jax.js','mml2jax.js','MathMenu.js','MathZoom.js']," + " displayAlign: 'center'," + " displayIndent: '0em'," + " showMathMenu: true," + " tex2jax: { " + " inlineMath: [ ['$','$'] ], " + " displayMath: [ ['$$','$$'] ]," + " processEscapes: true," + " preview: 'TeX'," + " }, " + " 'HTML-CSS': { " + " linebreaks: { automatic: true, width: '95% container' }, " + " styles: { '.MathJax_Display, .MathJax .mo, .MathJax .mi, .MathJax .mn': {color: 'black ! important'} }" + " } " + "}); "; (document.body || document.getElementsByTagName('head')[0]).appendChild(mathjaxscript); } </script> <hr/> </div> <section> <div class="span2" style="float:right;font-size:0.9em;"> <h4>Published</h4> <time pubdate="pubdate" datetime="2017-11-20T20:18:00+01:00">lis 20, 2017</time> <h4>Category</h4> <a class="category-link" href="./categories.html#web-scraping-ref">web scraping</a> <h4>Tags</h4> <ul class="list-of-tags tags-in-article"> <li><a href="./tags.html#dane-ref">dane <span>1</span> </a></li> <li><a href="./tags.html#mieszkania-ref">mieszkania <span>1</span> </a></li> <li><a href="./tags.html#otodom-ref">otodom <span>1</span> </a></li> <li><a href="./tags.html#python-ref">python <span>4</span> </a></li> </ul> </div> </section> </div> </article> </div> <div class="span1"></div> </div> </div> <div id="push"></div> </div> <footer> <div id="footer"> <ul class="footer-content"> <li class="elegant-power">Powered by <a href="http://getpelican.com/" title="Pelican Home Page">Pelican</a>. Theme: <a href="http://oncrashreboot.com/pelican-elegant" title="Theme Elegant Home Page">Elegant</a> by <a href="http://oncrashreboot.com" title="Talha Mansoor Home Page">Talha Mansoor</a></li> </ul> </div> </footer> <script src="http://code.jquery.com/jquery.min.js"></script> <script src="//netdna.bootstrapcdn.com/twitter-bootstrap/2.3.2/js/bootstrap.min.js"></script> <script> function validateForm(query) { return (query.length > 0); } </script> </body> <!-- Theme: Elegant built for Pelican License : http://oncrashreboot.com/pelican-elegant --> </html><file_sep>/theme/quotes/quoteArray.js var quotes=new Array(); quotes[0]="<q>Quote 1</q>"; quotes[0]="<q>so fucking sweet</q>"; quotes[1]="<q>Sure do...slide those panties to the side</q>"; quotes[2]="<q>let me hit it</q>"; quotes[3]="<q>nice ass</q>"; quotes[4]="<q>I'LL EAT UR PUSSY</q>"; quotes[5]="<q>yes i do.</q>"; quotes[6]="<q>I want it with my mouth, tongue, hands and cock</q>"; quotes[7]="<q>PRETTY FACE,NICE BIG ASS,ROUND TITTIES=VERY SEXY</q>"; quotes[8]="<q>nice titties wit a matchin ass...i'm loving it </q>"; quotes[9]="<q>I can't be the only one that has seen this picture in an advertisement about ebonyteengfs or something on this site</q>"; quotes[10]="<q>so sexy</q>"; quotes[11]="<q>Slutfuckerrrrr?! What the fuck?! Photoshop? No hun! All my girls are 100% Real. No need for that!</q>"; quotes[12]="<q>she got a baby face and a phat ass</q>"; quotes[13]="<q>sexy</q>"; quotes[14]="<q>round tits with a round ass. hell yeah i like</q>"; quotes[15]="<q>You're the most beautiful woman in the world I need you and your hot body</q>"; quotes[16]="<q>VERY LICKABLE!!!</q>"; quotes[17]="<q>just wanna slap that fatty</q>"; quotes[18]="<q>thats a true sexy! juicy! black ass mmmmmmmmmmm x</q>"; quotes[19]="<q>I wanna bite it.....</q>"; quotes[20]="<q>My fuck cushions so I don't hurt myself as I slam fuck your tiny tight asshole pumping sperm deep up into your guts ! xoxo's </q>"; quotes[21]="<q>i love that big black bootys</q>"; quotes[22]="<q>Super ass</q>"; quotes[23]="<q>perfection</q>"; quotes[24]="<q>i love it </q>"; quotes[25]="<q>sexy ass</q>"; quotes[26]="<q>the only thing better would be a close up of my face in that ass</q>"; quotes[27]="<q>nicki minaj type ass</q>"; quotes[28]="<q>That aint no onion...thas more like some christmas hams in those pants...& i love ham </q>"; quotes[29]="<q>1 LOVE</q>"; quotes[30]="<q>Bend ova, Let mi Lick that azz, till ur pussy squirt.</q>"; quotes[31]="<q>Lovely Phaat booty !!:)</q>"; quotes[32]="<q>lol @ WellHung232 & MrCee83! Y'll crazy!</q>"; quotes[33]="<q>lol @ WellHung232!</q>"; quotes[34]="<q>i would love to wake up to her every morning</q>"; quotes[35]="<q>I want to fuck that ass</q>"; quotes[36]="<q>what a fantastic ass </q>"; quotes[37]="<q>u got an onion on you</q>"; quotes[38]="<q>god damn!!!!!!!</q>"; quotes[39]="<q>what a great ass</q>"; quotes[40]="<q>That is too sexy...love to get it in wit u in that position </q>"; quotes[41]="<q>damm u sexy</q>"; quotes[42]="<q>sexxxxxxxxxxy</q>"; quotes[43]="<q>very sexy</q>"; quotes[44]="<q>Love it!</q>"; quotes[45]="<q>love this one</q>"; quotes[46]="<q>Like never before :)</q>"; quotes[47]="<q>Always...but can u hang?</q>"; quotes[48]="<q>yeah baby turn of the lights</q>"; quotes[49]="<q>When are u ready? That's the question</q>"; quotes[50]="<q>sure am!!!</q>"; quotes[51]="<q>your tits are fucking amazing, I would love to cum all over them.</q>"; quotes[52]="<q>hummmm que tu es d\u00e9licieuse</q>"; quotes[53]="<q>wow...you're stunning</q>"; quotes[54]="<q>a ce niveau c'est de l'art ^^</q>"; quotes[55]="<q>pas une grosse poitrine mais ton corps reste un d\u00e9lice a regarder</q>"; quotes[56]="<q>tu est super sexi !!</q>"; quotes[57]="<q>un corp parfait !</q>"; quotes[58]="<q>Superbe</q>"; quotes[59]="<q>Tu as un corps superbe </q>"; quotes[60]="<q>hummm le reste aussi *_*</q>"; quotes[61]="<q>joli corps, rien \u00e0 jeter</q>"; quotes[62]="<q>Pardon me while I bust a nut to you!</q>"; quotes[63]="<q>You are PERFECT!! Stunning face, perfect body and your tits are awesome!!!</q>"; quotes[64]="<q>royale !</q>"; quotes[65]="<q>j'aimerais etre l\u00e0 a tes pieds</q>"; quotes[66]="<q>vraiment excitante</q>"; quotes[67]="<q>Tr\u00e8s jolie</q>"; quotes[68]="<q>super sexy cette partie *_*</q>"; quotes[69]="<q>Joli petit coeur, entre autres...</q>"; quotes[70]="<q>nice</q>"; quotes[71]="<q>app\u00e9tissant</q>"; quotes[72]="<q>c'est splendide</q>"; quotes[73]="<q>miam</q>"; quotes[74]="<q>bien \u00e9pil\u00e9 comme il faut et bient\u00f4t pr\u00eat a se faire p\u00e9n\u00e9trer !</q>"; quotes[75]="<q>Tr\u00e8s sexy , tu donnes envie </q>"; quotes[76]="<q>hot</q>"; quotes[77]="<q>tr\u00e8s tr\u00e8s jolie </q>"; quotes[78]="<q>On en redemande</q>"; quotes[79]="<q>Tease ;-)</q>"; quotes[80]="<q>trop belle !</q>"; quotes[81]="<q>ce serait pas de refus que tu viennes me le mettre dans le cul</q>"; quotes[82]="<q>rebelle !! et le mien de doigt tu en veux ?!?</q>"; quotes[83]="<q>Je mettrai ce doigt dans ta chatte, et ma queue dans ta bouche... </q>"; quotes[84]="<q>Superbe !!</q>"; quotes[85]="<q>ce doigt en dit long sur ce qu il peut faire ^^</q>"; quotes[86]="<q>vachement sexy, j'adore !</q>"; quotes[87]="<q>Love the attitude! visions of angry sex ;-)</q>"; quotes[88]="<q>tigth ass hole,,, and cute peanut,,, lick,,, lick,,, till,,, wet,,,</q>"; quotes[89]="<q>j'ai envie d'y mettre la langue</q>"; quotes[90]="<q>id\u00e9al pour y mettre sa langue</q>"; quotes[91]="<q>Un tout petit cul et une toute petite chatte... c'est ce qu'il y a de meilleur \u00e0 d\u00e9foncer.</q>"; quotes[92]="<q>App\u00e9tissant</q>"; quotes[93]="<q>sa me parrait fort humide ... </q>"; quotes[94]="<q>moi ma langue!</q>"; quotes[95]="<q>absolutly GREAT baby! Lick your sweet lips up....</q>"; quotes[96]="<q>incredible xx</q>"; quotes[97]="<q>hmmmm</q>"; quotes[98]="<q>Jolie petite chatte et trou du cul \u00e0 l\u00e9cher et \u00e0 p\u00e9n\u00e9trer avec passion... Tr\u00e8s jolie vue que tu offres </q>"; quotes[99]="<q>Mmmm je voudrais y glisser ma langue </q>"; quotes[100]="<q>mmmmmmmmmmmmmmmmm</q>"; quotes[101]="<q>\u00e7a donne envie de tout l\u00e9cher </q>"; quotes[102]="<q>Miam !</q>"; quotes[103]="<q>j'aimerai y plonger ma queue !</q>"; quotes[104]="<q>j'aimerai bien me glisser dedans!</q>"; quotes[105]="<q>Perfect. Both.</q>"; quotes[106]="<q>Trop hot</q>"; quotes[107]="<q>j'aimerais y \u00eatre...</q>"; quotes[108]="<q>Jviendrais bien me r\u00e9chauffer un peu </q>"; quotes[109]="<q>Tu me plais.</q>"; quotes[110]="<q>sexy </q>"; quotes[111]="<q>Ready for my cum?</q>"; quotes[112]="<q>tr\u00e8s jolie</q>"; quotes[113]="<q>your ass so much won't get my cookc in deep into your aas and stock hard</q>"; quotes[114]="<q>Superbe</q>"; quotes[115]="<q>wow quelle beaut\u00e9 </q>"; quotes[116]="<q>Sublime !</q>"; quotes[117]="<q>tu est super belle bisous</q>"; quotes[118]="<q>damn sexy</q>"; quotes[119]="<q>J'aime te nene ;-)</q>"; quotes[120]="<q>Magnifique, \u00e7a donne vraiment envie </q>"; quotes[121]="<q>je ne serai me retenir</q>"; quotes[122]="<q>Bouge pas, j'arrive</q>"; quotes[123]="<q>jolie pose coquine</q>"; quotes[124]="<q>waou tu me rend fou</q>"; quotes[125]="<q>hummm</q>"; quotes[126]="<q>Tu es d\u00e9licieuse, coquine et sensuelle... ca donne tr\u00e8s envie !</q>"; quotes[127]="<q>miam</q>"; quotes[128]="<q>id\u00e9ale</q>"; quotes[129]="<q>yes, a real sweety</q>"; quotes[130]="<q>Tu es \u00e0 croquer!!!!</q>"; quotes[131]="<q>du 5 \u00e9toiles </q>"; quotes[132]="<q>Un petit cot\u00e9 prude tr\u00e8s excitant</q>"; quotes[133]="<q>magnifique</q>"; quotes[134]="<q>You're amazingly cute! love that nipple just peaking out ;-)</q>"; quotes[135]="<q>Vraiment tu es superbe</q>"; quotes[136]="<q>beautiful \u2764</q>"; quotes[137]="<q>awesome pussy girl!</q>"; quotes[138]="<q>from <NAME> in Amature Allure</q>"; quotes[139]="<q>What Video is this from?</q>"; quotes[140]="<q>my hubby is going to plug is dick into your sweet hole darling !!</q>"; quotes[141]="<q>think of the possibilities- im just imagining all the fun things we can use and experiment with to replace that buttplug</q>"; quotes[142]="<q>yoou need a cock in your sweet pussy.</q>"; quotes[143]="<q>hummm</q>"; quotes[144]="<q>this is my favourite one so far </q>"; quotes[145]="<q>lickable and fuckable..both ..a lot!!</q>"; quotes[146]="<q>nice ass to rim or fuck:P</q>"; quotes[147]="<q>buddy is good but the real thing its better </q>"; quotes[148]="<q>looks so tasty</q>"; quotes[149]="<q>Beautiful ass!</q>"; quotes[150]="<q>Let me take turns punishing those little fuck holes!</q>"; quotes[151]="<q>I want to slide all of my cock deep into your ass.</q>"; quotes[152]="<q>I would love to lick your asshole ... </q>"; quotes[153]="<q>Girls are fun but only a real man can satisfy that girl! She's a knockout</q>"; quotes[154]="<q>Nice butt!I would lick it then fuck it!Mmmmmmmmm</q>"; quotes[155]="<q>perfect </q>"; quotes[156]="<q>I want to tongue fuck</q>"; quotes[157]="<q>great view!!my husband cock would fill your nice pussy right now!!</q>"; quotes[158]="<q>Dam I'd lick those holes then ram my 9 inch cock deep in that ass</q>"; quotes[159]="<q>u just keep getn better and better- so many sexy girls who rnt afraid to show themselves off are so hesitant wen it comes to anal- such a waste of a good ass wen some1 is 2shy or insecure to try experimenting a lil- GOLD STAR FOR U HEHE</q>"; quotes[160]="<q>perfect ass</q>"; quotes[161]="<q>fuck yeah babe!!!you've got an amazing ass!!love how you spread it!!</q>"; quotes[162]="<q>thats so yummy and hot!! i would love to play with you ;-)</q>"; quotes[163]="<q>I'd love to lick that hole nice and deep</q>"; quotes[164]="<q>Oooh, I'm very wet</q>"; quotes[165]="<q>I wanna lick that buttplug</q>"; quotes[166]="<q>nice asshole </q>"; quotes[167]="<q>damn.. and i love your hair..</q>"; quotes[168]="<q>Stockings look Amazing on you x</q>"; quotes[169]="<q>very sexy!</q>"; quotes[170]="<q>Your hott, love the hair.\u00a0 Perhaps my cock can take the place of the buttplug.</q>"; quotes[171]="<q>Stay put and let me slide my hard cock up your pussy</q>"; quotes[172]="<q>I want to stick my tongue so deep in your pretty little tight hole then suck that butt plug after its been in your tight ass.</q>"; quotes[173]="<q>great pic!!we've got the same toy!!check out in my pics!!i love it too!!</q>"; quotes[174]="<q>beautiful ass</q>"; quotes[175]="<q>love it</q>"; quotes[176]="<q>I can help with that!!!</q>"; quotes[177]="<q>and after the plug i will fuck your asshole</q>"; quotes[178]="<q>i love girls with butt plugs</q>"; quotes[179]="<q>Would love to take the place of your plug.</q>"; quotes[180]="<q>perfect body.</q>"; quotes[181]="<q>\u0131 want you</q>"; quotes[182]="<q>I love this pic</q>"; quotes[183]="<q>Those panties get my pussy so wet!</q>"; quotes[184]="<q>Love this view!</q>"; quotes[185]="<q>What a perfect shot at a perfect ass and tight little pussy! Would love to eat both holes from behind making you cum and squirt and getting to taste and drink you and your sweet cum and squirting pussy!</q>"; quotes[186]="<q>Can I fuck tjwt ass</q>"; quotes[187]="<q>ass ready for my cock!!!!</q>"; quotes[188]="<q>Perfect tight little pussy i love the view u make my bbc going hard ur very in shape</q>"; quotes[189]="<q>love that view</q>"; quotes[190]="<q>This view too!</q>"; quotes[191]="<q>that pussy slammin</q>"; quotes[192]="<q>Yumm anal slut let me fuck that ass</q>"; quotes[193]="<q>ur doin aus proud- album after album u just keep getting more and more fuckable-</q>"; quotes[194]="<q>2 are not enought for you ass..take more!!</q>"; quotes[195]="<q>mmmm your bubble butt is so great id love to have you sit on my face before slowly penetrating your asshole and your sweet wet pussy </q>"; quotes[196]="<q>I'd love to spank it</q>"; quotes[197]="<q>incredible *_*\u00a0</q>"; quotes[198]="<q>just PERFECT!!!!!</q>"; quotes[199]="<q>nice pose, nice ass, nice feet!</q>"; quotes[200]="<q>I enjoy this view </q>"; quotes[201]="<q>Beautiful!!!!</q>"; quotes[202]="<q>wowwwwww!!!!</q>"; quotes[203]="<q>yesssssssssssssssss</q>"; quotes[204]="<q>You made my wall of Fame (favorite photo's) ! ! ! !</q>"; quotes[205]="<q>I love watching my husband stroke his big black cock to your picture</q>"; quotes[206]="<q>i just wanna grab dat ass lick it and pound him !</q>"; quotes[207]="<q>MmM please do.</q>"; quotes[208]="<q>would love to play with that kitty</q>"; quotes[209]="<q>Make sure that those caps are on tight!</q>"; quotes[210]="<q>Very Alluring!</q>"; quotes[211]="<q>You're making me picture you pushing you into a utility closet at a Christmas party because I just can't keep away any longer. </q>"; quotes[212]="<q>fucking gorgeous!!! (I'd love to \</q>"; quotes[213]="<q>You are beautiful!!!</q>"; quotes[214]="<q>i'd pay for those moist panties fresh off your wet pussy!</q>"; quotes[215]="<q>I do love panties with a moist camel toe</q>"; quotes[216]="<q>this is one of my favorite pictures ever... thank you so much...</q>"; quotes[217]="<q>soooo tasty </q>"; quotes[218]="<q>yes</q>"; quotes[219]="<q>Mmmmm!</q>"; quotes[220]="<q>wauw, just wauw</q>"; quotes[221]="<q>so sexy</q>"; quotes[222]="<q>perfect!</q>"; quotes[223]="<q>Mmmfuck -- legs like Li-Lo. I'd lick you from toe to top, then back, for hours and hours, and never lose a bit of my erection!</q>"; quotes[224]="<q>Great LEGS!</q>"; quotes[225]="<q>I absolutely love this picture *licks his lips*</q>"; quotes[226]="<q>a cheeky flash- recon i got time b4 we get cought?..</q>"; quotes[227]="<q>I want to slide in, you can keep those on :-)</q>"; quotes[228]="<q>I'm so hard seeing your perfect body!!</q>"; quotes[229]="<q>Perfect! Looks good with a little hair on your puss </q>"; quotes[230]="<q>lickable, suckable, edible....so FUCKABLE!! </q>"; quotes[231]="<q>your pics are amazing!</q>"; quotes[232]="<q>You have a beautiful body!</q>"; quotes[233]="<q>yum yum yum</q>"; quotes[234]="<q>Very cool pics.</q>"; quotes[235]="<q>dam that ass looks amazing and your pussy looks so tight and moist i love it </q>"; quotes[236]="<q>licks lips- sorry to b the bearer of bad news, but when ur ass is as much fun to look at as urs is then i can tell u now that dildo aint gona last long- cant just stand back and let the tous hav all the fun</q>"; quotes[237]="<q>now see if my cock can fit up there</q>"; quotes[238]="<q>Another memorable Sharpy moment!</q>"; quotes[239]="<q>Like your hot ass</q>"; quotes[240]="<q>instant favorite</q>"; quotes[241]="<q>your pussy wants out</q>"; quotes[242]="<q>Your feet are just beautiful</q>"; quotes[243]="<q>I think you'd enjoy my dick a lot better</q>"; quotes[244]="<q>Good girl.</q>"; quotes[245]="<q>mmm, this makes me think \</q>"; quotes[246]="<q>Would love to make you gape</q>"; quotes[247]="<q>Looks sooo delicious. And I'll never be able to look at a sharpie again without picturing this!</q>"; quotes[248]="<q>i want to slide my cock between them and fuck u like that dear\u00a0:*\u00a0:*\u00a0:*\u00a0</q>"; quotes[249]="<q>fuck i want to eat your ass!</q>"; quotes[250]="<q>Perfect wet amazing pussy that tastes like it looks, amazing!</q>"; quotes[251]="<q>you're making me so wet</q>"; quotes[252]="<q>mmm this makes me so very hungry... I want to feast on that juicy horny pussy and asshole for hours</q>"; quotes[253]="<q>id die a happy man if i ever got to fill this sweet pussy with a hot load</q>"; quotes[254]="<q>I wanna like lick that wetness all off!</q>"; quotes[255]="<q>Mmmh so perfectly wet... Looks so tasty! Just wanna spit on your pussy and let my tounge whirl around your clit while im fingering you both in the pussy and your tight little asshole, lick your wet pussy all the way from your clit down to your asshole</q>"; quotes[256]="<q>mmm so wet dam that's hot</q>"; quotes[257]="<q>LoVe to fuck your beautiful WET pussy!</q>"; quotes[258]="<q>I love it wet </q>"; quotes[259]="<q>I want to fuck that pussy hard and fill it with my cum.</q>"; quotes[260]="<q>I want to be inside you so bad, and feel you squeeze while you cum</q>"; quotes[261]="<q>Love your sweet tight wet little pussy! So beautiful and so sexy!</q>"; quotes[262]="<q>this is sooo inviting </q>"; quotes[263]="<q>humm, i love you</q>"; quotes[264]="<q>ur pussy looks great so wet</q>"; quotes[265]="<q>such a wet pussy</q>"; quotes[266]="<q>Wow !!! Soooo fuckable!</q>"; quotes[267]="<q>omg u're sooo wet</q>"; quotes[268]="<q>lick lick liiick </q>"; quotes[269]="<q>Such a beautiful pussy</q>"; quotes[270]="<q>we would have so much fun with your hot pussy</q>"; quotes[271]="<q>your pussy lips get so red when you're horny</q>"; quotes[272]="<q>WOWWWWWWWWWWWWWWWWW!</q>"; quotes[273]="<q>seems you love to fill your ass babe..isnt it??</q>"; quotes[274]="<q>i dont know who in the right mind wouldnt love this pic, i love all ur pics with something in ur ass :X :X :X</q>"; quotes[275]="<q>Can I borrow a Sharpy?</q>"; quotes[276]="<q>thanks, how would you fuck me?</q>"; quotes[277]="<q>so hot babe</q>"; quotes[278]="<q>hey gorgeous like your pics</q>"; quotes[279]="<q>so hot</q>"; quotes[280]="<q>I'd love to cum on your delicious tits!!!!</q>"; quotes[281]="<q>Love all your photos - incredibly sexy, more, more more x</q>"; quotes[282]="<q>you are Amazing!</q>"; quotes[283]="<q>Incredible -- not ONE picture has a thumbs-down! Not easy to get, though I agree 1000% !! </q>"; quotes[284]="<q>omg you have the perfect fuck body and amazing tits!! 10/10</q>"; quotes[285]="<q>thank you baby. What would you do to me?</q>"; quotes[286]="<q>sexy body</q>"; quotes[287]="<q>now now, how r u supposed 2 fend off all the devious lil boys when u hav ur hands full... hehehei guess this is the perfect opatunity 2 take advantage ;o)</q>"; quotes[288]="<q>I want u to take that double headed dildo out of ur mouth and fuck my ass with it</q>"; quotes[289]="<q>So perfect!!! I'm about to bust a nut!!!</q>"; quotes[290]="<q>PERFECT 10, my gawd i'd fuck you all day and night!!!!!</q>"; quotes[291]="<q>Dam your kinky come to New York</q>"; quotes[292]="<q>like pussy</q>"; quotes[293]="<q>WOW!! That's HOT!!!!!!!!!!</q>"; quotes[294]="<q>Too sexy</q>"; quotes[295]="<q>Can u put the other end in my butt?</q>"; quotes[296]="<q>you r so hot .....\u00a0</q>"; quotes[297]="<q>Very sexy! Love your feet and toes!</q>"; quotes[298]="<q>wow, that's the pose...!</q>"; quotes[299]="<q>I love ur feet. So damn beautiful</q>"; quotes[300]="<q>I'd love to play with you when you fuck yourself.</q>"; quotes[301]="<q>I wish I was that dildo!</q>"; quotes[302]="<q>That's the way i like my drinks</q>"; quotes[303]="<q>absolutely perfect!</q>"; quotes[304]="<q>Drinking the wodka straight from your beatiful pussy would be the best vodka experience!!</q>"; quotes[305]="<q>Chilling your nipples is so HOT!!! Maybe do your clit too!!!</q>"; quotes[306]="<q>I wanna lick ur cute lil asshole</q>"; quotes[307]="<q>and a good fucking too!</q>"; quotes[308]="<q>Great body</q>"; quotes[309]="<q>WoW, what a hot body!!</q>"; quotes[310]="<q>Amazing body babe - you're exquisite !!!</q>"; quotes[311]="<q>they just don't CUM any more delicious than this!</q>"; quotes[312]="<q>Get those holes ready, make the most of it as I won't be gentle</q>"; quotes[313]="<q>mmmmh,beautiful,,,,,,,,,,,,,,</q>"; quotes[314]="<q>Your just perfect</q>"; quotes[315]="<q>I LOVE upskirt pics!</q>"; quotes[316]="<q>Mmm wish that was my cock I your ass</q>"; quotes[317]="<q>oh damn that is hot wish it was my big thick cock deep in your tight ass</q>"; quotes[318]="<q>you give much pleasure to the Pleasurist, and many others too! Keep up the beautiful work.</q>"; quotes[319]="<q>i would like licking yours tits mmm , there so beutiful !!</q>"; quotes[320]="<q>wow what a body</q>"; quotes[321]="<q>u found my weakness.. i love water and that goes for oil 2 and especially soap suds... the touch of a female body dripping wet, the look and taste as soon as theyve come out of the shower or bath... il never pass up an opatunity 2 go play in the bath room...i hav a thing for showers, baths, spas, saunas and expecially pools... hav u ever cum while feeling the weightless in a pool?? best feeling ever</q>"; quotes[322]="<q>Love this pic!</q>"; quotes[323]="<q>Your body is perfection</q>"; quotes[324]="<q>Your tight young body is so sexy! What a perfect pair of tits! Love your little red patch! </q>"; quotes[325]="<q>wow !</q>"; quotes[326]="<q>you're making me mad! you're so perfect!</q>"; quotes[327]="<q>mmmm\u00a0I would want to know the taste which she has *_*\u00a0</q>"; quotes[328]="<q>Love your went cunt!</q>"; quotes[329]="<q>I would fuck you so hard!!!!</q>"; quotes[330]="<q>lovely lips</q>"; quotes[331]="<q>I wish your lips were wrapped around my HARD COCK!</q>"; quotes[332]="<q>You look delicious</q>"; quotes[333]="<q>Ice cubes? YES!</q>"; quotes[334]="<q>let me taste ur juice!</q>"; quotes[335]="<q>Dam girl you make me so horny! I just want to slide my hard dick in that wet pussy and fuck you till were both sore then fuck you some more</q>"; quotes[336]="<q>looks great</q>"; quotes[337]="<q>com'on..let's dp your nice holes!!!</q>"; quotes[338]="<q>Perfect the only question is which one stays in and which get replaced with a dick?</q>"; quotes[339]="<q>This is such a beautiful thing</q>"; quotes[340]="<q>VERY NICE!!</q>"; quotes[341]="<q>I will pay money just to watch u masturbate infront of me</q>"; quotes[342]="<q>very hot</q>"; quotes[343]="<q>Perfect presentation</q>"; quotes[344]="<q>perrrrfect 4a good deep plowing</q>"; quotes[345]="<q>Id push them together and make you scream </q>"; quotes[346]="<q>mmmmm</q>"; quotes[347]="<q>mmmm would love to take the other end of that with you </q>"; quotes[348]="<q>how deep can you take it babe?</q>"; quotes[349]="<q>the best size</q>"; quotes[350]="<q>deaptroath me</q>"; quotes[351]="<q>I love a lady who knows how to get herself off. Well done. xoxo</q>"; quotes[352]="<q>I adore this one. xoxo</q>"; quotes[353]="<q>Wow love seeing your body like this sexy </q>"; quotes[354]="<q>I love hoe plump your pussy gets when you've got something in your ass.</q>"; quotes[355]="<q>ur piks hav me hangin off the edge of my seat- please tell me u like to chat- id love to find out more about what makes a fellow aussie tick- especially one whos as open and willing to take it anywhere</q>"; quotes[356]="<q>wau </q>"; quotes[357]="<q>delicious</q>"; quotes[358]="<q>You have PERFECT tits!</q>"; quotes[359]="<q>They are stunning, sexy pink nipples,mmmmmmmmmmm</q>"; quotes[360]="<q>Great ! hummmmmm\u00a0</q>"; quotes[361]="<q>2 birds with 1 stone?</q>"; quotes[362]="<q>yuuuuumm . So hot i cant believe it Would love to be locked in a room with you </q>"; quotes[363]="<q>love it, damn hot</q>"; quotes[364]="<q>How long were you going for? </q>"; quotes[365]="<q>very hot just need to see those hard nipples too</q>"; quotes[366]="<q>"": "Me Masturbating", "segment": "Solo Female"}</q>"; quotes[367]="<q>UR fucking sexy body this have good </q>"; quotes[368]="<q>perfect woman ass mmmmmm haven</q>"; quotes[369]="<q>oh baby you have a smoken hot body but i wanna see your pretty litlle face to pleeeeese!</q>"; quotes[370]="<q>wow very hot body!</q>"; quotes[371]="<q>MMMMMM.... i just shot a HUGE load of CUMMMMMMMMMM all over my screen....</q>"; quotes[372]="<q>sweet and sexy...</q>"; quotes[373]="<q>So HOT ! Take that towel down a little more </q>"; quotes[374]="<q>So Hot !</q>"; quotes[375]="<q>you have beautiful body</q>"; quotes[376]="<q>Very sexy xxx</q>"; quotes[377]="<q>really hot body</q>"; quotes[378]="<q>What a nice titties!?Kisses</q>"; quotes[379]="<q>Your body is absolutely perfect sweety! Stunning! I think i'm in love with it!</q>"; quotes[380]="<q>loving those breasts</q>"; quotes[381]="<q>thank you God </q>"; quotes[382]="<q>Damn! nice hair & hottest body babe;)</q>"; quotes[383]="<q>Fuck....very tasty, can i lick u up and down?</q>"; quotes[384]="<q>Nice!!</q>"; quotes[385]="<q>hey sexy wats up?;)</q>"; quotes[386]="<q>mmmmm wot a sweet sexy body, id love 2 nibble on ur titties</q>"; quotes[387]="<q>my fav pic cutie</q>"; quotes[388]="<q>nice body</q>"; quotes[389]="<q>oh I need to suck that perfect yummy nipples while I fisting your smelly gorgeous pussy and tight asshole, after I want to cover your perfec tits with my hot CUM babe</q>"; quotes[390]="<q>omg, you have an awesome body!</q>"; quotes[391]="<q>perfect body babe, your so sexy </q>"; quotes[392]="<q>so hot...</q>"; quotes[393]="<q>you are a very sexual girl!!!</q>"; quotes[394]="<q>you are perfect and cute...</q>"; quotes[395]="<q>sexy!</q>"; quotes[396]="<q>awesome</q>"; quotes[397]="<q>mmmm thats one amazing body!</q>"; quotes[398]="<q>You have a beautiful body... When can we see some of your hot sweet pussy and ass?</q>"; quotes[399]="<q>SOOO FUCKN SEXY</q>"; quotes[400]="<q>nice nips show me the kitty..</q>"; quotes[401]="<q>beautiful</q>"; quotes[402]="<q>your body is so fine x</q>"; quotes[403]="<q>perfect!</q>"; quotes[404]="<q>wow very nice body</q>"; quotes[405]="<q>stunning body, you are gorgeous</q>"; quotes[406]="<q>pic lov!!!!yumm yumm!!!</q>"; quotes[407]="<q>nice</q>"; quotes[408]="<q>Absolutely my favorite! </q>"; quotes[409]="<q>PERFECT!</q>"; quotes[410]="<q>beautiful...</q>"; quotes[411]="<q>i wanna cum on your tits!</q>"; quotes[412]="<q>nice pic! sexy body</q>"; quotes[413]="<q>humm love your tits</q>"; quotes[414]="<q>you are so beaoutifull i realy like your long black hair so sexy</q>"; quotes[415]="<q>oh my!!! You look just perfect!;)</q>"; quotes[416]="<q>wet is best </q>"; quotes[417]="<q>OMG MMMMM so dam fuckin hot</q>"; quotes[418]="<q>i want to take a shower with you!</q>"; quotes[419]="<q>Nice body baby. Let's have a shower together </q>"; quotes[420]="<q>So pretty, sweet </q>"; quotes[421]="<q>sweet babe</q>"; quotes[422]="<q>We would say in poland about you :Jeste? zajebist? dziuni? , zajebistymi cycami ))Pozdro :****</q>"; quotes[423]="<q>Nice tits!</q>"; quotes[424]="<q>hhhmmmmm...</q>"; quotes[425]="<q>can't wait to see the rest of you who knows maybe one day tastes you</q>"; quotes[426]="<q>Tasty</q>"; quotes[427]="<q>i want to touch taste and suck them too sweetie;)</q>"; quotes[428]="<q>i wish i was wraped around ur waist like that towl</q>"; quotes[429]="<q>so cute...</q>"; quotes[430]="<q>thanks for the tease</q>"; quotes[431]="<q>you look amazing babe, wish you would show your face though</q>"; quotes[432]="<q>Fresh out of the shower,,,Lovley</q>"; quotes[433]="<q>wooooow very nice</q>"; quotes[434]="<q>sexy, but would be even greater without towel </q>"; quotes[435]="<q>i want kiss your tits</q>"; quotes[436]="<q>wow, ur so cute...</q>"; quotes[437]="<q>i want to try your breast</q>"; quotes[438]="<q>ooooh the tease hehehe</q>"; quotes[439]="<q>Do you need a hand???ahaha</q>"; quotes[440]="<q>OMG! let me take a shower with u cutie!:)</q>"; quotes[441]="<q>a nice tit an a cute lil chin...x</q>"; quotes[442]="<q>i want that nipple in my mouth</q>"; quotes[443]="<q>love to help u with that soap...</q>"; quotes[444]="<q>mmmmmm tit wank, im thinkin</q>"; quotes[445]="<q>i would love to suck that nipple</q>"; quotes[446]="<q>cool 6 sexy pic</q>"; quotes[447]="<q>please upload pics of your feet!! I like U'r pics!!;)</q>"; quotes[448]="<q>I want to lick the foam from your breast</q>"; quotes[449]="<q>MARRY ME!!!!!!</q>"; quotes[450]="<q>amazing</q>"; quotes[451]="<q>Gorgeous</q>"; quotes[452]="<q>god I wish I knew qho you was lol</q>"; quotes[453]="<q>Can i cum wash ur back?</q>"; quotes[454]="<q>I LIKE TO GIVE U A HAND WASHING</q>"; quotes[455]="<q>W:OW! i want to suck these nice nipples while ur riding my harder dick! lol!</q>"; quotes[456]="<q>let me help give you a bath</q>"; quotes[457]="<q>perfect! to be kissed for days...</q>"; quotes[458]="<q>wish i could shower with you, you look so sexy in your pics</q>"; quotes[459]="<q>wow, can i cum shower with u? ill wash ur back....front...well...every bit of u</q>"; quotes[460]="<q>you are so sexy. I'd love to suck your breasts</q>"; quotes[461]="<q>mmmmm nice </q>"; quotes[462]="<q>wot an amazing pic.... such a perfect set of tits xXx</q>"; quotes[463]="<q>mmmm.....may i help you?</q>"; quotes[464]="<q>oh so nice</q>"; quotes[465]="<q>nice</q>"; quotes[466]="<q>saucey!! x</q>"; quotes[467]="<q>wow</q>"; quotes[468]="<q>babe let me est those tits</q>"; quotes[469]="<q>Beautiful!</q>"; quotes[470]="<q>oohh i want to see your face</q>"; quotes[471]="<q>dream breasts!</q>"; quotes[472]="<q>mmmm slippery and slidery room for 2 in that shower?</q>"; quotes[473]="<q>Lovely tits. So pretty</q>"; quotes[474]="<q>awesome</q>"; quotes[475]="<q>those are the tits of perfection.. love those nipples.</q>"; quotes[476]="<q>wwwwwwwwwwwwwwwwooooooooooooooowwww</q>"; quotes[477]="<q>i would like to meet you...Kisses</q>"; quotes[478]="<q>Id rather think of my substance over those hot beautiful tits</q>"; quotes[479]="<q>Great tits</q>"; quotes[480]="<q>I want to lick all your sexual body!!!</q>"; quotes[481]="<q>SOME FIRM LIL A CUPS, R, B CUPS WHO CARES THEIR FIRM</q>"; quotes[482]="<q>can i cum on ur sexual tits babe?</q>"; quotes[483]="<q>mmmmh can i join you and make sure you stay wet long after rubbing your hot body?</q>"; quotes[484]="<q>you are so hot I just want to cum all over you</q>"; quotes[485]="<q>you let me with no word...</q>"; quotes[486]="<q>Very nice boobs, let me fuck you under the shower</q>"; quotes[487]="<q>sexy body </q>"; quotes[488]="<q>wish that was my cum!</q>"; quotes[489]="<q>mmmmmmmm I luv big soapy titties..Wow</q>"; quotes[490]="<q>wow</q>"; quotes[491]="<q>I love you boobies~!</q>"; quotes[492]="<q>let me suck on your tits</q>"; quotes[493]="<q>I would love to share a shower with you...</q>"; quotes[494]="<q>veri nice tits</q>"; quotes[495]="<q>SOOOOOOOOO INCREDIBLY SEXY.... I need ashower now>>></q>"; quotes[496]="<q>look so beutiful ur erec nipples bb !! well the hot whater make hot... horn. nice really nice mami !</q>"; quotes[497]="<q>only one word fits WOW</q>"; quotes[498]="<q>You re tits are amazing</q>"; quotes[499]="<q>great fucking body!</q>"; quotes[500]="<q>thats hot</q>"; quotes[501]="<q>they are PERFECTTT!!!</q>"; quotes[502]="<q>Oh god! there r hot lips here!!! i want to taste and suck them too sweetie! xxx</q>"; quotes[503]="<q>love your hidden lips...</q>"; quotes[504]="<q>instant boner </q>"; quotes[505]="<q>holy fuck! you have an amazing body! hit me up sometime</q>"; quotes[506]="<q>stunning...</q>"; quotes[507]="<q>you have great tits hun </q>"; quotes[508]="<q>ALL FOR ME...X</q>"; quotes[509]="<q>Damn! you look so horny in this nice pic babe!:)</q>"; quotes[510]="<q>love it three pic in one</q>"; quotes[511]="<q>mmm, a very sexy set of pics. you're making me, um, light-headed... </q>"; quotes[512]="<q>so pretty and sexy!</q>"; quotes[513]="<q>mmm what a beautiful pair of breasts</q>"; quotes[514]="<q>too hot!!!!!</q>"; quotes[515]="<q>How sweet u sexxxy girl lick u from hole 2 hole till u begged me to stab u wiff the gut wrench </q>"; quotes[516]="<q>wow</q>"; quotes[517]="<q>ooops you droped your towel hehehe</q>"; quotes[518]="<q>Face SWEET !;****</q>"; quotes[519]="<q>can i suck?</q>"; quotes[520]="<q>love it!</q>"; quotes[521]="<q>Fantastic!</q>"; quotes[522]="<q>i want that cock</q>"; quotes[523]="<q>damn i'll suck dat bitch</q>"; quotes[524]="<q>i need that</q>"; quotes[525]="<q>mmm</q>"; quotes[526]="<q>deep n my pussy</q>"; quotes[527]="<q>mmm</q>"; quotes[528]="<q>fuck me with that</q>"; quotes[529]="<q>Beautiful...love how it hangs.</q>"; quotes[530]="<q>how i wish...</q>"; quotes[531]="<q>mmm</q>"; quotes[532]="<q>priceless</q>"; quotes[533]="<q>Wow</q>"; quotes[534]="<q>can u fuck me with that dick</q>"; quotes[535]="<q>fuckin sexy</q>"; quotes[536]="<q>luv to suck on that amazingly huge cock</q>"; quotes[537]="<q>thats really sexy!</q>"; quotes[538]="<q>hot love black cock</q>"; quotes[539]="<q>sexy</q>"; quotes[540]="<q>i could...</q>"; quotes[541]="<q>wow, what a nice cock u have!!!! LOve to suck it and find other safe places for it - will you let me, love</q>"; quotes[542]="<q>fuckin hot</q>"; quotes[543]="<q>can i fuck u pa</q>"; quotes[544]="<q>the definition of hung</q>"; quotes[545]="<q>wow, to big for my ass</q>"; quotes[546]="<q>thats fucking hot</q>"; quotes[547]="<q>Nice n THICK Pa.</q>"; quotes[548]="<q>I would let you fuck the shit out of me. Dick's huge and it's not even hard!</q>"; quotes[549]="<q>that big</q>"; quotes[550]="<q>I want that dick in my ass</q>"; quotes[551]="<q>love your sexy body omg </q>"; quotes[552]="<q>I love it!</q>"; quotes[553]="<q>give that great...</q>"; quotes[554]="<q>Wen cani getthe D</q>"; quotes[555]="<q>big dick</q>"; quotes[556]="<q>damn is so long n yummy</q>"; quotes[557]="<q>i like that bbc </q>"; quotes[558]="<q>Let me ride you all day?</q>"; quotes[559]="<q>Awesome stiffy and fantastic calls.</q>"; quotes[560]="<q>U should make a jerking off video</q>"; quotes[561]="<q>luv it</q>"; quotes[562]="<q>nice</q>"; quotes[563]="<q>u got 2 let me suck ur balls</q>"; quotes[564]="<q>Nice !!!</q>"; quotes[565]="<q>fuck me with it please</q>"; quotes[566]="<q>.. great cock a deep...</q>"; quotes[567]="<q>Share what you think</q>"; quotes[568]="<q>Now THAT is what I call a joystick.....</q>"; quotes[569]="<q>hey sexy can i sit on that</q>"; quotes[570]="<q>long dick</q>"; quotes[571]="<q>shiiitt i wanna fuck that so hard!! deep in my asshole</q>"; quotes[572]="<q>this pic made me cum. would love to be on my knees with that down my throat</q>"; quotes[573]="<q>Crazy shot. Luv it! This monster is lying in wait.</q>"; quotes[574]="<q>thats a great cock you have</q>"; quotes[575]="<q>that cock looks sooo good</q>"; quotes[576]="<q>..a deep tissue</q>"; quotes[577]="<q>like that dick</q>"; quotes[578]="<q>honestly that is fuckin amazing</q>"; quotes[579]="<q>hell yes</q>"; quotes[580]="<q>When you going to let me ride this dick ?</q>"; quotes[581]="<q>wow i love that</q>"; quotes[582]="<q>Luv to suck that dry!</q>"; quotes[583]="<q>massage with my...</q>"; quotes[584]="<q>i like</q>"; quotes[585]="<q>How I would love wrap my wet lips around that sometime!</q>"; quotes[586]="<q>i want to swallow your cock and take your cum all over my face</q>"; quotes[587]="<q>ohhhhhhh boy, soooo hot</q>"; quotes[588]="<q>nice, huge cock man !!!</q>"; quotes[589]="<q>good morning .|.</q>"; quotes[590]="<q>pleas fuck me with it</q>"; quotes[591]="<q>i wanna wrap my warm mouth around that monster of yours big boy!!</q>"; quotes[592]="<q>wow, wow you need some help</q>"; quotes[593]="<q>can i sit on it</q>"; quotes[594]="<q>i would definately ride that!!!</q>"; quotes[595]="<q>can i have some?</q>"; quotes[596]="<q>..with my warm, wet and...</q>"; quotes[597]="<q>OMG, i want that huge rod in my tight ass hole and keep it as long as u want, love</q>"; quotes[598]="<q>me and a male friend would love to take turns sucking you </q>"; quotes[599]="<q>looks like it needs a hand !!</q>"; quotes[600]="<q>mmmm</q>"; quotes[601]="<q>what a monster</q>"; quotes[602]="<q>I like how you have a different angle on each pose. Im going to make gif movie out of them</q>"; quotes[603]="<q>mmmmmm..perfect!!</q>"; quotes[604]="<q>let me suck</q>"; quotes[605]="<q>Wow!</q>"; quotes[606]="<q>let me suck</q>"; quotes[607]="<q>it wants to be in my ass</q>"; quotes[608]="<q>can i suck that cock and balls ?</q>"; quotes[609]="<q>can i ride it?</q>"; quotes[610]="<q>beatiful.</q>"; quotes[611]="<q>well trained tongue and expert mouth!!!!!!</q>"; quotes[612]="<q>i want that dick in my ass and puss</q>"; quotes[613]="<q>Wish I were there... Unbuttoning those pants with my tongue...</q>"; quotes[614]="<q>hahaha! this is great</q>"; quotes[615]="<q>MMMMMM..... i just shot 2 HUGE loads of CUMMMMMMMMMMMMM all over my screen.....</q>"; quotes[616]="<q>You wanna play with me!!? LOVLEY!</q>"; quotes[617]="<q>love it cutie..</q>"; quotes[618]="<q>a like call of duty,but i like more that thing under package </q>"; quotes[619]="<q>fuck you are sexy!</q>"; quotes[620]="<q>very nice!!!</q>"; quotes[621]="<q>wooooooow</q>"; quotes[622]="<q>you have a sexy body baby</q>"; quotes[623]="<q>I think I've just been called to duty.</q>"; quotes[624]="<q>Oh my god this might be one of the sexiest pictures I've ever seen! There are so many things I wanna do to you here </q>"; quotes[625]="<q>i dont have words describe what im seing. mabey one word: hot hot hot hot</q>"; quotes[626]="<q>you are so sexy</q>"; quotes[627]="<q>wow hahaha...quirky pic sexy lady,didnt rec you there for a sec haha xoxox</q>"; quotes[628]="<q>WHAT A SEXXY PIC,I WOULD LOVE TO PLAY GAMES WITH YOU ALL NIGHT </q>"; quotes[629]="<q>I will like to play with you......</q>"; quotes[630]="<q>Will you marry me!!! This is so sexy!I would cod the shit out of you!!</q>"; quotes[631]="<q>wow i never thought i would love video games this much</q>"; quotes[632]="<q>shows the pussy and boobs too</q>"; quotes[633]="<q>I like playing on the xbox but more with you!</q>"; quotes[634]="<q>very cute pic.</q>"; quotes[635]="<q>love your smile, so sunny, not to mention ur hardrocking body</q>"; quotes[636]="<q>super pic xoxox</q>"; quotes[637]="<q>great great body sexy shape.........</q>"; quotes[638]="<q>I love your pics Amy, very sexy x</q>"; quotes[639]="<q>quite possibly the hottest woman on PH</q>"; quotes[640]="<q>nice body....</q>"; quotes[641]="<q>dammmmmmmmmmm love thatttttt so sexy so beautifulllll</q>"; quotes[642]="<q>VERY VERY HOT!!!!mmmm</q>"; quotes[643]="<q>MMMMMMMM.... i just shot a HUGE load of CUMMMMMMMMMMMMM all over my screen....</q>"; quotes[644]="<q>very sexy</q>"; quotes[645]="<q>wow, love that body</q>"; quotes[646]="<q>verry sexy</q>"; quotes[647]="<q>god u r absolutly amazing...</q>"; quotes[648]="<q>luv ur panties, would like to be behind you </q>"; quotes[649]="<q>bellissima </q>"; quotes[650]="<q>I must drop a load on this one</q>"; quotes[651]="<q>SIMPLY A PIC OF PERFECTION AND BEAUTY!!!</q>"; quotes[652]="<q>amazing babe honestly your just a boys dream girl x</q>"; quotes[653]="<q>ya ur really hot</q>"; quotes[654]="<q>pureee beauty</q>"; quotes[655]="<q>damn your sexy</q>"; quotes[656]="<q>great body...</q>"; quotes[657]="<q>mmmm i wanna ride</q>"; quotes[658]="<q>\u042f,\u0445\u043e\u0447\u0443 \u0442\u0435\u0431\u044f \u043c\u043e\u044f \u043f\u0440\u0435\u043b\u043e\u0441\u0442\u044c</q>"; quotes[659]="<q>lovely cleavage</q>"; quotes[660]="<q>Perfect!</q>"; quotes[661]="<q>mmm their perfect ;]</q>"; quotes[662]="<q>R U GOING TO SPANK ME</q>"; quotes[663]="<q>ace ventura!!! but hot. </q>"; quotes[664]="<q>LOVE THAT PIC...;P</q>"; quotes[665]="<q>Your eyes, neckless, hair, you're the essence of beauty.</q>"; quotes[666]="<q>Wow pretty !</q>"; quotes[667]="<q>WOW WILL U B MY GIRLFRIEND</q>"; quotes[668]="<q>omg i love your eyes</q>"; quotes[669]="<q>You are hot.</q>"; quotes[670]="<q>VERY PRETTY...</q>"; quotes[671]="<q>Un visage ang\u00e9lique</q>"; quotes[672]="<q>are u real?</q>"; quotes[673]="<q>You are so cute</q>"; quotes[674]="<q>sooooooo cute</q>"; quotes[675]="<q>you are sooo pretty </q>"; quotes[676]="<q>you look so hot yet innocent i like it </q>"; quotes[677]="<q>absolutely beautiful</q>"; quotes[678]="<q>soo hot & cute</q>"; quotes[679]="<q>nice</q>"; quotes[680]="<q>The look of your eye is amazing</q>"; quotes[681]="<q>I like this one</q>"; quotes[682]="<q>VERY COOL PIC</q>"; quotes[683]="<q>Q tan hermosa!</q>"; quotes[684]="<q>Awesome pic! And wonderful looking eyes! thank you!</q>"; quotes[685]="<q>wow i want to lick your entire body.</q>"; quotes[686]="<q>wow your hot, love to be friends</q>"; quotes[687]="<q>sexy</q>"; quotes[688]="<q>wow :]</q>"; quotes[689]="<q>lovely, i always woundered what it's like to fuck in a bath tub.</q>"; quotes[690]="<q>wow</q>"; quotes[691]="<q>so sexy! x</q>"; quotes[692]="<q>Heather is the most beautiful and sexiest woman in porn. I would like to see Heather and <NAME> do a hot lesbian scene together (at least 30 minutes long). . .</q>"; quotes[693]="<q>mmm ... nice, very nice</q>"; quotes[694]="<q>Hmmm si sex </q>"; quotes[695]="<q>Hmmmmm So sex </q>"; quotes[696]="<q>so sexy</q>"; quotes[697]="<q>what is her rate</q>"; quotes[698]="<q>Fuck yeah!</q>"; quotes[699]="<q>would love yo lick and suck your nipples</q>"; quotes[700]="<q>10000 rs</q>"; quotes[701]="<q>Nice pose</q>"; quotes[702]="<q>Wow 2 for 2 Nice</q>"; quotes[703]="<q>mmm lemmmieee bitee on those nippless =]</q>"; quotes[704]="<q>lick this tits babe!!!</q>"; quotes[705]="<q>Genial!!</q>"; quotes[706]="<q>Did this every night for 6 months with too roommates on my dorm floor.</q>"; quotes[707]="<q>TODO TAPADO</q>"; quotes[708]="<q>dream</q>"; quotes[709]="<q>nice pics ..</q>"; quotes[710]="<q>those are the same girls you can see it on the necklace and bracelet on her </q>"; quotes[711]="<q>wow, stunning</q>"; quotes[712]="<q>sexy</q>"; quotes[713]="<q>Amazing looking bodies</q>"; quotes[714]="<q>Wish it was my dick in there</q>"; quotes[715]="<q>damn looks good</q>"; quotes[716]="<q>Panties drenched pulled to the side - hard cock in tight wet pussy... YES</q>"; quotes[717]="<q>lucky boy, she is amazing</q>"; quotes[718]="<q>omg im nuttin in my pants</q>"; quotes[719]="<q>lucky guy, I'm jealous</q>"; quotes[720]="<q>Sweet as pussy</q>"; quotes[721]="<q>Mmmm, pretty wet pussy!</q>"; quotes[722]="<q>I love</q>"; quotes[723]="<q>Can I make a mess? I promise to clean it up!!!</q>"; quotes[724]="<q>That pussy looks like it would be great to eat and to fuck</q>"; quotes[725]="<q>DAMN</q>"; quotes[726]="<q>so hot</q>"; quotes[727]="<q>soooo hot..........</q>"; quotes[728]="<q>lovee to do you just made my dick hard as fuck</q>"; quotes[729]="<q>Oh my christ.. Santa got my letter!</q>"; quotes[730]="<q>will you marry me lol you are beautiful mommE</q>"; quotes[731]="<q>hi lisa will u b my xmass present as i'd lov 2 unrap u</q>"; quotes[732]="<q>damn u look like u need some cock in that mouth....think u can handle it?</q>"; quotes[733]="<q>Your smoking hot sexy</q>"; quotes[734]="<q>looks great (:</q>"; quotes[735]="<q>beatiful girl whatdo you the messenger please ?</q>"; quotes[736]="<q>lovely photo!!!!!!!!!</q>"; quotes[737]="<q>Muy sexy, me excitas</q>"; quotes[738]="<q>Hun you very beautifull </q>"; quotes[739]="<q>Man, that is such a pretty pink hole.\u00a0</q>"; quotes[740]="<q>a penis?</q>"; quotes[741]="<q>sweet hole! love it!</q>"; quotes[742]="<q>that sexy tight pink hole is begging for my throbbing cock!</q>"; quotes[743]="<q>yummy!</q>"; quotes[744]="<q>that hole wawnts to be filled</q>"; quotes[745]="<q>super hooottttttttt!!!!</q>"; quotes[746]="<q>WOW !!! GOOD enough to eat</q>"; quotes[747]="<q>i love having my ass played with!!!</q>"; quotes[748]="<q>thanks for all the comments! You all really turn me on!</q>"; quotes[749]="<q>wow..nice tight juicy pussy ass hole..jsut perfect to take my cock all deep inside it..:-))</q>"; quotes[750]="<q>wow i want to like that so bad</q>"; quotes[751]="<q>Do you mind very much if I stick my tongue inside that sweet looking hole of yours?</q>"; quotes[752]="<q>I want to lick it all around and stick my tongue as deep in your asshole as I can. Yum, yum.</q>"; quotes[753]="<q>WAPAAAAAAA..........!!!!</q>"; quotes[754]="<q>OMG.....Nice Penis.....I like it!!!!I want suck it!!!!</q>"; quotes[755]="<q>looks tasty !!</q>"; quotes[756]="<q>MMMMMMMMM SEXY,TONED MUSCULAR BODY DUDE,WOULD LOVE TO HOOKUP FOR SOME FUN</q>"; quotes[757]="<q>nice very nice</q>"; quotes[758]="<q>What a great dick. Love that big head.\u00a0</q>"; quotes[759]="<q>Hot hot!</q>"; quotes[760]="<q>love those balls - yummy!</q>"; quotes[761]="<q>Wow, nice dick, I like it</q>"; quotes[762]="<q>fuckin hot!</q>"; quotes[763]="<q>nice dick </q>"; quotes[764]="<q>nice, hot body too</q>"; quotes[765]="<q>wow nice hard cock lickable balls and ass</q>"; quotes[766]="<q>Mmmm hot!</q>"; quotes[767]="<q>nice dick....</q>"; quotes[768]="<q>Love that big thick head! </q>"; quotes[769]="<q>ooooo lets def shoot spunk!</q>"; quotes[770]="<q>Sweet </q>"; quotes[771]="<q>mmmmmm, I like your hard cock,</q>"; quotes[772]="<q>Thanks everyone for the comments! I want to fuck you all!</q>"; quotes[773]="<q>its all yours babe!</q>"; quotes[774]="<q>Thanks! you can suck it anytime! or fuck it </q>"; quotes[775]="<q>I like it !!</q>"; quotes[776]="<q>Omg I want to suck your cock so bad!!!</q>"; quotes[777]="<q>nice cock..:P</q>"; quotes[778]="<q>very nice cock.</q>"; quotes[779]="<q>nice cock</q>"; quotes[780]="<q>omg beautiful piece</q>"; quotes[781]="<q>yummy2</q>"; quotes[782]="<q>i want you to give it to me hard</q>"; quotes[783]="<q>great cock !!</q>"; quotes[784]="<q>nice DICK!</q>"; quotes[785]="<q>beautiful cock. would love to suck you dry</q>"; quotes[786]="<q>can i suck it??</q>"; quotes[787]="<q>nice dick</q>"; quotes[788]="<q>Cute!! xx</q>"; quotes[789]="<q>I'd like to bounce up and down on that until you fill my hole with your hot cum!</q>"; quotes[790]="<q>nice cock</q>"; quotes[791]="<q>Nice!</q>"; quotes[792]="<q>A very impressive dick for a white guy. I could have fun with that. And you could have fun with me.</q>"; quotes[793]="<q>thats a beautiful cock</q>"; quotes[794]="<q>yummy pussy</q>"; quotes[795]="<q>u and karen?</q>"; quotes[796]="<q>Id lick that feet , and then lick that ass and pussy and in the end put my hard cock in there and fuck her for hours...she is great !</q>"; quotes[797]="<q>mmmm, GOD yr lovelly...XX</q>"; quotes[798]="<q>PERFECT, SUCH A BEAUTY.</q>"; quotes[799]="<q>is your ass as nice as your tits?</q>"; quotes[800]="<q>Wow, hammer body und geile titten </q>"; quotes[801]="<q>stunning body\u00a0</q>"; quotes[802]="<q>Wow momma!</q>"; quotes[803]="<q>hmmm diese Titten</q>"; quotes[804]="<q>Hot as fuck!</q>"; quotes[805]="<q>Fuck, those r fantastic lookin tits and you r Hott</q>"; quotes[806]="<q>Fucking hell those tits are awesome.</q>"; quotes[807]="<q>Perfect body and breasts </q>"; quotes[808]="<q>fuck......u do have a very sexy body and i sooooooooo want 2 suck ur sweet tits</q>"; quotes[809]="<q>looking awesome</q>"; quotes[810]="<q>nice hair sexy face and hot boobs with sweet nipples;)can i taste ur hot lips and suck these nice nipples babe?;)</q>"; quotes[811]="<q>i love your tits</q>"; quotes[812]="<q>amazing body baby can u add me so amazing hi</q>"; quotes[813]="<q>perfect! so sweet so beauty!</q>"; quotes[814]="<q>I LOVE it! Hot!</q>"; quotes[815]="<q>wow those tits </q>"; quotes[816]="<q>Mmmm my mouth is watering so sexy</q>"; quotes[817]="<q>sweet and sexy lovely sexy body and boobs yummy</q>"; quotes[818]="<q>Fantastically fit,what a babe</q>"; quotes[819]="<q>I didnt know 3 abbreviated words belonged to a practicular gender going by your name JacktheLad your a butch lesbian?</q>"; quotes[820]="<q>OMG</q>"; quotes[821]="<q>I want to suck on those nipples</q>"; quotes[822]="<q>very hot!</q>"; quotes[823]="<q>Wow, so sexy, a perfect pair of tits too</q>"; quotes[824]="<q>Gorgeous and a perfectly tight body with amazing boobs</q>"; quotes[825]="<q>this pic just made me cum </q>"; quotes[826]="<q>very sexy pic, I love it</q>"; quotes[827]="<q>very strokeable\u00a0</q>"; quotes[828]="<q>too sexy pic!would u hide ur hot boobs if i want to tatse them babe?:)</q>"; quotes[829]="<q>Very sexy indeed.. makes me want to fuck you really hard while pulling your head back that lovely long hair</q>"; quotes[830]="<q>amazing honey I like</q>"; quotes[831]="<q>too sweet to be 29, maybe 19 :X</q>"; quotes[832]="<q>Love your body mmm look at your hips</q>"; quotes[833]="<q>hottie</q>"; quotes[834]="<q>damn, you are sexy!</q>"; quotes[835]="<q>Tease </q>"; quotes[836]="<q>Love the tease of such a sexy, hot body</q>"; quotes[837]="<q>So fucking sexy!</q>"; quotes[838]="<q>du bist so h\u00fcbsch</q>"; quotes[839]="<q>h\u00fcbsches Gesicht und und ein scharfer sexy K\u00f6rper</q>"; quotes[840]="<q>OMG! i really want to lick this great body all morn sweetie...</q>"; quotes[841]="<q>I'd hold that for you;)</q>"; quotes[842]="<q>sweet and sexy love to lick your lovely boobs ann make your nipples all hard</q>"; quotes[843]="<q>Body to die for</q>"; quotes[844]="<q>Perfect!</q>"; quotes[845]="<q>See and I was instantly drawn to her left eye. The photographer staged her perfectly, especially with the slight downward angle, sort of giving her the evil pixie look.</q>"; quotes[846]="<q>Love this shot. The angle of view has an interesting created an interesting look to her ear. Hope the class she's now running isn't one on religion! Keeping with the theme, most likely biology....</q>"; quotes[847]="<q>I guess that discussion went well for someone.......</q>"; quotes[848]="<q>ass looks good enough to eat omg... *smacks your ass and jiggles it with my cock* </q>"; quotes[849]="<q>OMG EYES LOVE IT</q>"; quotes[850]="<q>wow what an ASS beautiful more please take some more pictures I want to see it all.</q>"; quotes[851]="<q>Phat ass.. Love it</q>"; quotes[852]="<q>\</q>"; quotes[853]="<q>Nice shot! She's on the wrong side of the road too! Might explain a few things!</q>"; quotes[854]="<q>DAMN that's hot!!</q>"; quotes[855]="<q>Fuckin killer bod baby.</q>"; quotes[856]="<q>luv her toned bodeyh</q>"; quotes[857]="<q>so fucking hot</q>"; quotes[858]="<q>i bet you love squats </q>"; quotes[859]="<q>sexy legs you have </q>"; quotes[860]="<q>perfect body hotie</q>"; quotes[861]="<q>Im gay and you are absolutely beautiful. Prob the prettiest model period</q>"; quotes[862]="<q>nice picture</q>"; quotes[863]="<q>i want to lick you</q>"; quotes[864]="<q>like this </q>"; quotes[865]="<q>you r sexy and you know it </q>"; quotes[866]="<q>babe you are a sex doll look like pornstar i give you a 10</q>"; quotes[867]="<q>definite10</q>"; quotes[868]="<q>Thats not sexy, its not for gurls, ugly! U looks like a man</q>"; quotes[869]="<q>U just make me hard...</q>"; quotes[870]="<q>mmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmm</q>"; quotes[871]="<q>Your abs are so fucking sexy I'd lick your mans cum off of em!</q>"; quotes[872]="<q>your eyes look so sexy here </q>"; quotes[873]="<q>may i shoot my load between them? </q>"; quotes[874]="<q>so hot i want to lick every inch of your body</q>"; quotes[875]="<q>i'd like to test this statement on yours </q>"; quotes[876]="<q>i want to cover that tongue with my cum</q>"; quotes[877]="<q>your body is so damn hot </q>"; quotes[878]="<q>OMG ...</q>"; quotes[879]="<q>well done good girl</q>"; quotes[880]="<q>lucky one...</q>"; quotes[881]="<q>don't use plastic... use me !</q>"; quotes[882]="<q>amazing Body!!!</q>"; quotes[883]="<q>wow what a fitt body love it!</q>"; quotes[884]="<q>do you have a good body and fierce competitor of you...!;*</q>"; quotes[885]="<q>Yes and yes!! Lol. Prettiest pink little pussy every! God I would love to taste you!</q>"; quotes[886]="<q>great work </q>"; quotes[887]="<q>perfect body! wow!</q>"; quotes[888]="<q>want to feed that sexy ass with some cum </q>"; quotes[889]="<q>I LOVE them!!!</q>"; quotes[890]="<q>Abs on girl is amazing sexy make me want of suck he pussy really</q>"; quotes[891]="<q>stunning ...</q>"; quotes[892]="<q>awesome </q>"; quotes[893]="<q>a sexy magician who make things disappear and reappear </q>"; quotes[894]="<q>Fabulous</q>"; quotes[895]="<q>what a women ...</q>"; quotes[896]="<q>Now that is one lucky guy </q>"; quotes[897]="<q>wonderful </q>"; quotes[898]="<q>Mmmm</q>"; quotes[899]="<q>gorgeous!</q>"; quotes[900]="<q>hi heels </q>"; quotes[901]="<q>if i could be behind you..</q>"; quotes[902]="<q>Beautiful...</q>"; quotes[903]="<q>You have the most incredible body I have ever seen. Cant get enough of your pics </q>"; quotes[904]="<q>i like stockings </q>"; quotes[905]="<q>Picture Perfect!</q>"; quotes[906]="<q>amazing Body!!!</q>"; quotes[907]="<q>I wanna lick it </q>"; quotes[908]="<q>HOTTTTTTTT</q>"; quotes[909]="<q>this is hot!</q>"; quotes[910]="<q>wanna eat your ass out so hard </q>"; quotes[911]="<q>hummm!!!</q>"; quotes[912]="<q>wish to lick them both first until they became so wet and ready..and than if you like and love i could fuck you real deep and hard in both holes all day and nights long..in real life..at my place..RIGHT NOW!! :-)</q>"; quotes[913]="<q>You can do with me as you wish baby!</q>"; quotes[914]="<q>so fuckin hot!!</q>"; quotes[915]="<q>it's worth even more </q>"; quotes[916]="<q>nice skin </q>"; quotes[917]="<q>i love it!</q>"; quotes[918]="<q>my darling</q>"; quotes[919]="<q>your nipples make me crazy !!</q>"; quotes[920]="<q>Oh my god!i've got a weakness for pretty girls with glasses...love youre content Brianna xxx</q>"; quotes[921]="<q>lucky guy</q>"; quotes[922]="<q>take mine</q>"; quotes[923]="<q>He's got a nice pipe</q>"; quotes[924]="<q>I would love to be that lucky guy!</q>"; quotes[925]="<q>you are soo good darling </q>"; quotes[926]="<q>yum yum here licking goodxoxo</q>"; quotes[927]="<q>SEXY Were you from?</q>"; quotes[928]="<q>Fuck.....Gorgeous</q>"; quotes[929]="<q>PHHWOAAAAAR sexy lil minx</q>"; quotes[930]="<q>i want to bend you over</q>"; quotes[931]="<q>licks lips... u just keep gettin better and better... sexy with style</q>"; quotes[932]="<q>You have Awesome Taste in clothes. So damn hot. Earings match the panties. love it.</q>"; quotes[933]="<q>*Beauty*</q>"; quotes[934]="<q>great view</q>"; quotes[935]="<q>so so hot!!</q>"; quotes[936]="<q>You are soo sexy!</q>"; quotes[937]="<q>Damn your hot!</q>"; quotes[938]="<q>I love the pic!!</q>"; quotes[939]="<q>Can a person be any hotter then you? no! you make me sooo horny girl!</q>"; quotes[940]="<q>so fucking hot</q>"; quotes[941]="<q>i wanna suck your pussy and them titties so bad!!</q>"; quotes[942]="<q>what ababe! this is ur sexiest pic...damn hot!</q>"; quotes[943]="<q>can i fuck you after?</q>"; quotes[944]="<q>dam that is a hot pic</q>"; quotes[945]="<q>u look so hot in here !!!!!!!!!</q>"; quotes[946]="<q>So Fucking SEXY..</q>"; quotes[947]="<q>Thats the only realy sexy Picture in this Set. </q>"; quotes[948]="<q>I'd crawl right across the floor to get to you! :-)</q>"; quotes[949]="<q>beautiful</q>"; quotes[950]="<q>you are so hot!!! </q>"; quotes[951]="<q>you are faaaaantastic! gorgeous! so sexy! be my girl;)</q>"; quotes[952]="<q>MAMI RICA</q>"; quotes[953]="<q>nice hair x</q>"; quotes[954]="<q>baby, u r just so fuckin hot!!</q>"; quotes[955]="<q>id fuck you soo hard ;]</q>"; quotes[956]="<q>PERFECT TITS!</q>"; quotes[957]="<q>wow!!! nice body!!!</q>"; quotes[958]="<q>amazing body</q>"; quotes[959]="<q>you look like you love to get fucked</q>"; quotes[960]="<q>No you look like you love lookin' good, and getting your pussy licked.</q>"; quotes[961]="<q>You look soooo hot!</q>"; quotes[962]="<q>your body is perfect. makes my dick so hard.</q>"; quotes[963]="<q>lol u so luckii u av an amazing figure lol</q>"; quotes[964]="<q>gr8 body babe</q>"; quotes[965]="<q>I would bet hers is a mess, sorry hunni </q>"; quotes[966]="<q>I bet you have a tight little pussy </q>"; quotes[967]="<q>OMFG!!!! mmmmmmmmm so hot!</q>"; quotes[968]="<q>dam i want take my tongue up those thighs to that pussy</q>"; quotes[969]="<q>IM SO WET!</q>"; quotes[970]="<q>so fuckin hot</q>"; quotes[971]="<q>thats really hot baby xxx</q>"; quotes[972]="<q>mmm soooo sexy!lovin it</q>"; quotes[973]="<q>gaaad mmmm best</q>"; quotes[974]="<q>Emo ALL the fucking way.</q>"; quotes[975]="<q>WOW!!!</q>"; quotes[976]="<q>i want to feel your tits so bad </q>"; quotes[977]="<q>i wanna lick your tits honey</q>"; quotes[978]="<q>Nice Hot Tits..Like To Slide My BBC Between Them Girls </q>"; quotes[979]="<q>look swedish! </q>"; quotes[980]="<q>Yeah, your fuckin hotter than hell, that's for sure baby.I wanna fuckin nut on every one of your fucking photos, mmmmmm .....</q>"; quotes[981]="<q>HOT!!!</q>"; quotes[982]="<q>mmmm i want to tittyfuck you!</q>"; quotes[983]="<q>you have the most amazing boobs</q>"; quotes[984]="<q>wow como quisiera ser tu fotografo privado... que linda mi vida te cojeria hasta decir basta. nice tits te las chuparia hasta cansarme, y te comeria tu ass and pussy.</q>"; quotes[985]="<q>fuck yeah</q>"; quotes[986]="<q>dobre si tiiii</q>"; quotes[987]="<q>Dam your fucking sexy:)</q>"; quotes[988]="<q>You are So Sexy!!</q>"; quotes[989]="<q>your the baddest bitch ive seen!!!</q>"; quotes[990]="<q>you are so fucking sexy ;]</q>"; quotes[991]="<q>whe want to fuck whit you</q>"; quotes[992]="<q>Nice Spanking Hot Sexy Ass</q>"; quotes[993]="<q>DAYUM girl fine as fuck...hit me up</q>"; quotes[994]="<q>I'd love to bend you over right here slide that thong to the side and Fuck you deep and hard </q>"; quotes[995]="<q>this is a fav</q>"; quotes[996]="<q>FUCK!</q>"; quotes[997]="<q>dammm</q>"; quotes[998]="<q>amazing!</q>"; quotes[999]="<q>I just want to grab you sweetie....Muuaahh</q>"; quotes[1000]="<q>I'd like to fuck you from behind!</q>"; quotes[1001]="<q>WHAT A PIC UR AMAZING</q>"; quotes[1002]="<q>i'd love to get a nice handful of that cushy ass omg </q>"; quotes[1003]="<q>love ur ASS!</q>"; quotes[1004]="<q>mmm beautiful !!</q>"; quotes[1005]="<q>you are HOT!! do you speak greek?</q>"; quotes[1006]="<q>I love that ass!</q>"; quotes[1007]="<q>love THAT ASS! MMMM CUMERE!!</q>"; quotes[1008]="<q>Baby i am soo horny.... )))</q>"; quotes[1009]="<q>going Greek?</q>"; quotes[1010]="<q>nice</q>"; quotes[1011]="<q>Slovak or Czech?</q>"; quotes[1012]="<q>god dam girl lovin that sexy ass</q>"; quotes[1013]="<q>you are divine baby!!</q>"; quotes[1014]="<q>you are the sexiest girl i have ever seen! sooo hot!</q>"; quotes[1015]="<q>Gorgeous with Sexy Hot Stunning Body!!;)</q>"; quotes[1016]="<q>Fuck ME!!!! you are so hot!!xx</q>"; quotes[1017]="<q>perfect!!!</q>"; quotes[1018]="<q>my fav</q>"; quotes[1019]="<q>I'd fuck you my body breaks.. Cum over you again and again!</q>"; quotes[1020]="<q>Favorite!!</q>"; quotes[1021]="<q>I would lick your sweet pussy!</q>"; quotes[1022]="<q>mamacita hotttttttttttttttt</q>"; quotes[1023]="<q>sexies body ever</q>"; quotes[1024]="<q>would love to have that body riding me</q>"; quotes[1025]="<q>such a tonned sexy body... drop dead gorgeous... u hav a body most girls dream about and sum guys would kill 2 b with even just for 5min</q>"; quotes[1026]="<q>Ooo..! Baby</q>"; quotes[1027]="<q>Too fucking cute:)</q>"; quotes[1028]="<q>wow, soo sexy </q>"; quotes[1029]="<q>perfect girl</q>"; quotes[1030]="<q>wow</q>"; quotes[1031]="<q>girl you are tasty</q>"; quotes[1032]="<q>hi baby..you are sexy!</q>"; quotes[1033]="<q>baby you're amazing</q>"; quotes[1034]="<q>fav!</q>"; quotes[1035]="<q>WoW babe you are a dirty Little sexbomb!! </q>"; quotes[1036]="<q>SO sexy!</q>"; quotes[1037]="<q>You're have a Hot & Sexy Body</q>"; quotes[1038]="<q>PERFECT</q>"; quotes[1039]="<q>i would love you to have a threesome with me and my GF xxx</q>"; quotes[1040]="<q>very hot!</q>"; quotes[1041]="<q>wow sexy..</q>"; quotes[1042]="<q>u re FUCKING HOT!!!!</q>"; quotes[1043]="<q>you're hot as hell!!!!</q>"; quotes[1044]="<q>fantastically stunning xx</q>"; quotes[1045]="<q>very hot body!!!</q>"; quotes[1046]="<q>i love this one!</q>"; quotes[1047]="<q>VERY HOT , LOVE TO HAVE YOU THREESOME</q>"; quotes[1048]="<q>You are so HOOOTTT !!!</q>"; quotes[1049]="<q>amazing body</q>"; quotes[1050]="<q>love your boobs so fucking much!!</q>"; quotes[1051]="<q>thats a perfect picture right there</q>"; quotes[1052]="<q>damm</q>"; quotes[1053]="<q>AMAZING BODY</q>"; quotes[1054]="<q>Very sexy picture thank you for sharing</q>"; quotes[1055]="<q>amazing!</q>"; quotes[1056]="<q>thats soo hott! love the pink!</q>"; quotes[1057]="<q>yes</q>"; quotes[1058]="<q>i would love to suck your pussy</q>"; quotes[1059]="<q>Awesome tits and pussy.</q>"; quotes[1060]="<q>my dick it get hard</q>"; quotes[1061]="<q>you're too sexy!!!!</q>"; quotes[1062]="<q>I want You!! The Camera loves you</q>"; quotes[1063]="<q>stunningly hot! xx</q>"; quotes[1064]="<q>your body is banging!</q>"; quotes[1065]="<q>Sexy hun </q>"; quotes[1066]="<q>Now thats what i want</q>"; quotes[1067]="<q>i would destroy you!</q>"; quotes[1068]="<q>Fantastic!!!</q>"; quotes[1069]="<q>simply stunning and cute xx</q>"; quotes[1070]="<q>Nice picture, breathtaking figure.</q>"; quotes[1071]="<q>thnx but i lost it actually:(</q>"; quotes[1072]="<q>hi sex</q>"; quotes[1073]="<q>Well cutie, isnt that a perfect start to an album, cant wait 2c more</q>"; quotes[1074]="<q>girl </q>"; quotes[1075]="<q>thnx doing my best </q>"; quotes[1076]="<q>I guess you fucked the guy, that took that picture? Really nice body btw </q>"; quotes[1077]="<q>what a body ...</q>"; quotes[1078]="<q>This picture is fantastic! Wonderful body, picture is well taken!</q>"; quotes[1079]="<q>glad u like what u see </q>"; quotes[1080]="<q>You are welcome gorgeous. The pleasure is all mine </q>"; quotes[1081]="<q>As I said, I like the results </q>"; quotes[1082]="<q>hhmm horny</q>"; quotes[1083]="<q>Very Nice GEIL</q>"; quotes[1084]="<q>Would love to rub against my kitty!!</q>"; quotes[1085]="<q>wow,great back!</q>"; quotes[1086]="<q>so great</q>"; quotes[1087]="<q>nice ass.</q>"; quotes[1088]="<q>damn, dit is echt mn favo!wat een geweldig lichaam</q>"; quotes[1089]="<q>love those panties</q>"; quotes[1090]="<q>very sexy x</q>"; quotes[1091]="<q>Beautiful back</q>"; quotes[1092]="<q>wow</q>"; quotes[1093]="<q>Die gaat naar mijn favorites</q>"; quotes[1094]="<q>just pefect!</q>"; quotes[1095]="<q>priceless</q>"; quotes[1096]="<q>Wat een prachtig lichaam en lief koppie pffff</q>"; quotes[1097]="<q>Heerlijk. x</q>"; quotes[1098]="<q>MMMMM.... i just shot a HUGE load of CUMMMMMMMMMMMMM all over my screen....</q>"; quotes[1099]="<q>amazing girl</q>"; quotes[1100]="<q>Wow je bent inderdaad hot Geil koppie heb je </q>"; quotes[1101]="<q>lekker hoor!</q>"; quotes[1102]="<q>you make me wanna rejoice!</q>"; quotes[1103]="<q>Yes baby very hot pics</q>"; quotes[1104]="<q>Perfect gorgeous breasts.</q>"; quotes[1105]="<q>damn....very hott</q>"; quotes[1106]="<q>heerlijke foto xx</q>"; quotes[1107]="<q>i love this pic</q>"; quotes[1108]="<q>you're beautiful baby\u00a1\u00a1\u00a1\u00a1\u00a1\u00a1\u00a1\u00a1\u00a1\u00a1\u00a1\u00a1\u00a1</q>"; quotes[1109]="<q>can i cum on your tits =]?</q>"; quotes[1110]="<q>ooohhhh shit,wat een lekker lijf heb je</q>"; quotes[1111]="<q>wauuuuuuuuuuuuuuuuuuuuuuuu</q>"; quotes[1112]="<q>Thank you!</q>"; quotes[1113]="<q>nice boobs! they look so soft n censittive! dont mind the spelling! LMAO!</q>"; quotes[1114]="<q>wow are you hot!</q>"; quotes[1115]="<q>fucking hot</q>"; quotes[1116]="<q>Damn wat ben jij mooi</q>"; quotes[1117]="<q>Very Sexy!</q>"; quotes[1118]="<q>What a sensual woman</q>"; quotes[1119]="<q>so so sexy x</q>"; quotes[1120]="<q>So hot and sexy.</q>"; quotes[1121]="<q>So beautiful !! bye, nice girl !!</q>"; quotes[1122]="<q>Thats hot gurl</q>"; quotes[1123]="<q>damn!</q>"; quotes[1124]="<q>wish my cock was there</q>"; quotes[1125]="<q>Cutie </q>"; quotes[1126]="<q>Heerlijk! Hoe zou je het vinden om die dildo even weg te leggen, of in je kutje te 'stallen' terwijl mijn pik tussen die heerlijke borsten van je ligt? Kuzz</q>"; quotes[1127]="<q>very hot hon.....would love to see that as my hubbys cock!</q>"; quotes[1128]="<q>let me be your dildo and cum on your tits</q>"; quotes[1129]="<q>Pure seduction.</q>"; quotes[1130]="<q>zat mijn stijve er maar tussen, heerlijk!</q>"; quotes[1131]="<q>ckkr geile blik!!</q>"; quotes[1132]="<q>geile blik rrr</q>"; quotes[1133]="<q>Vraiment adorable!!!</q>"; quotes[1134]="<q>wow, you're a sexy girl baby!</q>"; quotes[1135]="<q>Zum ersten Male bedauere ich ein mann zu sein - da w\u00c3\u00a4r ich doch lieber eine lesbe und w\u00c3\u00bcrde dich kennen Mit l\u00c3\u00a4chelnJOjo</q>"; quotes[1136]="<q>nice picture, so cute ;-)</q>"; quotes[1137]="<q>dont tease me, awsume pic</q>"; quotes[1138]="<q>Waiting for me???</q>"; quotes[1139]="<q>very cute , hello kitty </q>"; quotes[1140]="<q>Sweet, sexy! Like a Kitty. I dream with you now;) Kisses;)</q>"; quotes[1141]="<q>You're so sexy and cute!</q>"; quotes[1142]="<q>nice shot.. gorgeous..</q>"; quotes[1143]="<q>do you wanna play with me:)</q>"; quotes[1144]="<q>damn, you are HOOOTTT!</q>"; quotes[1145]="<q>beautiful =]</q>"; quotes[1146]="<q>very very sexy </q>"; quotes[1147]="<q>you're so hot</q>"; quotes[1148]="<q>WOW love ur eyes... Look so hungry for sex...</q>"; quotes[1149]="<q>very nice! x</q>"; quotes[1150]="<q>very attractive lady! i kiss you even if you don t want! </q>"; quotes[1151]="<q>i would like 2 say u just 2 words (very cute)</q>"; quotes[1152]="<q>Traumhaft sch\u00c3\u00b6ne augen.</q>"; quotes[1153]="<q>i love that belly</q>"; quotes[1154]="<q>You have that \</q>"; quotes[1155]="<q>Gorgeous</q>"; quotes[1156]="<q>wow h\u00c3\u00bcbsche frau</q>"; quotes[1157]="<q>sooo hot</q>"; quotes[1158]="<q>SEXY</q>"; quotes[1159]="<q>princces</q>"; quotes[1160]="<q>sexy</q>"; quotes[1161]="<q>kiss babe,i love ur sexy body..i want to squirt on you as my sexy video when i squirt a lot!i wait ur comments in my photos and videos!kiss from ur sexy french blonde</q>"; quotes[1162]="<q>hot</q>"; quotes[1163]="<q>your really sexy and beautiful!!!</q>"; quotes[1164]="<q>beautiful</q>"; quotes[1165]="<q>Echt scharf</q>"; quotes[1166]="<q>schlicht und einfach ein tolles Bild</q>"; quotes[1167]="<q>damn you r so hot</q>"; quotes[1168]="<q>Mmmm so sexy, love the boots. leave them on when we seduce you.xo</q>"; quotes[1169]="<q>you re lookin great babe.</q>"; quotes[1170]="<q>wwooowww!!!will you merry me???</q>"; quotes[1171]="<q>fucking gorgeous x</q>"; quotes[1172]="<q>very nice</q>"; quotes[1173]="<q>da sag ich nur schade das so eine h\u00c3\u00bcbsche frau eine lesbe ist!</q>"; quotes[1174]="<q>Mmmmmmm very nice...</q>"; quotes[1175]="<q>Mmmmmmmmmmmmm very beautiful and sexy...</q>"; quotes[1176]="<q>siehst du geil auss mmmm</q>"; quotes[1177]="<q>sweet,hot,sexy and very fucking beautiful</q>"; quotes[1178]="<q>wow so sexy so what u into</q>"; quotes[1179]="<q>omg you are so pretty and the sexiest legs ever xxxxx</q>"; quotes[1180]="<q>Beutiful body mmmmmmmmm</q>"; quotes[1181]="<q>Sexy legs!!</q>"; quotes[1182]="<q>very sexy pic... makes me want to go and explore under that skirt</q>"; quotes[1183]="<q>Sexy long legs huni ? luv the skirt too ;-) xxxx</q>"; quotes[1184]="<q>very hot outfit, got me thinking about what i would be doing to you while you wore it </q>"; quotes[1185]="<q>yum, love the panties pulled down!</q>"; quotes[1186]="<q>Luv the panties around your thighs!!</q>"; quotes[1187]="<q>May I look underneath :3</q>"; quotes[1188]="<q>every mens dream!</q>"; quotes[1189]="<q>wow, what a perfect body, love it</q>"; quotes[1190]="<q>So nice. Has my cock throbin, Cum slide that lil pussy on my face huni, ;-) xxxx</q>"; quotes[1191]="<q>cute skirt ... beautiful pussy </q>"; quotes[1192]="<q>Now that's the way to say: Fuck me now</q>"; quotes[1193]="<q>Oh God, thats perfect!</q>"; quotes[1194]="<q>Such a turn on! </q>"; quotes[1195]="<q>love your pics; your album is great</q>"; quotes[1196]="<q>Sooo hot, love you're legs</q>"; quotes[1197]="<q>so cute, that it could be a Christmas postcard!) and so sexy) Fuck, i like you!)</q>"; quotes[1198]="<q>looking very hot like that </q>"; quotes[1199]="<q>yes lift it up</q>"; quotes[1200]="<q>stunning x</q>"; quotes[1201]="<q>I could sit and please them feet all day if you let me. Fuck they would look good dripping with cum and spit.</q>"; quotes[1202]="<q>So innocent looking </q>"; quotes[1203]="<q>Oh my god, those legs! </q>"; quotes[1204]="<q>Nice view</q>"; quotes[1205]="<q>holy fuck yes!</q>"; quotes[1206]="<q>More like this</q>"; quotes[1207]="<q>Mmmmm dam, That is one sexy ass there babe. ;-) xxx</q>"; quotes[1208]="<q>Nothing hotter than a short skirt..hmmm..except it being lifted to get at an even hotter ass </q>"; quotes[1209]="<q>this is nice</q>"; quotes[1210]="<q>nice skirt wow</q>"; quotes[1211]="<q>mm hot ass.</q>"; quotes[1212]="<q>Awesome!!!!!!!!</q>"; quotes[1213]="<q>whts her name???she is damn hottt..</q>"; quotes[1214]="<q>My cock ready to cum for you</q>"; quotes[1215]="<q>you are hot </q>"; quotes[1216]="<q>te gustan las polla negras no, mmm ya lo creo ya que son muy grandes</q>"; quotes[1217]="<q>my cock</q>"; quotes[1218]="<q>you can if you play nice </q>"; quotes[1219]="<q>where do i sign up.....</q>"; quotes[1220]="<q>33 w/f, niceeeeeee</q>"; quotes[1221]="<q>why i am not the black guy!!!</q>"; quotes[1222]="<q>I can fill you also I can feel your juices on my cock</q>"; quotes[1223]="<q>looks like a good meal !</q>"; quotes[1224]="<q>mmmmmmmmmmm, sexy!</q>"; quotes[1225]="<q>33 w/f, ny, I LIKE!</q>"; quotes[1226]="<q>Do you like to licked? You have such inviting lips.</q>"; quotes[1227]="<q>Mmmmmm... Doesn't that look yummy! \u00a0Mind if I go in for a long slow lick?</q>"; quotes[1228]="<q>a real man is always ready;)</q>"; quotes[1229]="<q>Ma queue est d\u00e9j\u00e0 pr\u00eate \u00e0 s'y glisser </q>"; quotes[1230]="<q>and you are not the only one who's ready </q>"; quotes[1231]="<q>Sexy sexy!</q>"; quotes[1232]="<q>perfect view!</q>"; quotes[1233]="<q>perfect pussy</q>"; quotes[1234]="<q>hmm fuck that ass and pussy would look perfect with my thick hard white cock deep in them hmm id love to fill both your holes with my cum \u00a0</q>"; quotes[1235]="<q>what you got is all I want </q>"; quotes[1236]="<q>oh wow.. this is so hot</q>"; quotes[1237]="<q>my god its nice</q>"; quotes[1238]="<q>Hot baby 4my dick!;):P</q>"; quotes[1239]="<q>so is a real woman...are you ready for a good ass fuckin?</q>"; quotes[1240]="<q>very nice pic i'm ready to fuck your ass.</q>"; quotes[1241]="<q>makes me horny</q>"; quotes[1242]="<q>hott ass, love the boots!</q>"; quotes[1243]="<q>nice ass!</q>"; quotes[1244]="<q>i could do terrible things with u !!!!!1</q>"; quotes[1245]="<q>Please can I fuck u hard over and over and over</q>"; quotes[1246]="<q>Very sexy, hot legs</q>"; quotes[1247]="<q>y love position,very nice ass.</q>"; quotes[1248]="<q>Bad, can I just slide in behind you?? Smacka dat ASS!!</q>"; quotes[1249]="<q>kiss...kiss!!!! MMMMmmmmmHHHHhhhh!!!!!!</q>"; quotes[1250]="<q>nice view, i love that position</q>"; quotes[1251]="<q>great pic and your ass is perfect ciaoooo bella</q>"; quotes[1252]="<q>mmmmmmmmmmmmmmmmmmmmmmmmm.................</q>"; quotes[1253]="<q>damn you look goooood;)</q>"; quotes[1254]="<q>ate me deu vontade de foder</q>"; quotes[1255]="<q>Nice undercarriage...brace yourself girl!Hehe,nice slit!</q>"; quotes[1256]="<q>I have a dream width you.</q>"; quotes[1257]="<q>nice..</q>"; quotes[1258]="<q>could i get a closer look??</q>"; quotes[1259]="<q>sexy woman,good;););).</q>"; quotes[1260]="<q>you are so sexy</q>"; quotes[1261]="<q>can i clean it up?</q>"; quotes[1262]="<q>i wanna fill your cunt too </q>"; quotes[1263]="<q>mmmm look at those lovely ridges inside which will caress my cock into heaven mmmm so good</q>"; quotes[1264]="<q>just beautiful.</q>"; quotes[1265]="<q>omg thats a sweet looking pussy hun</q>"; quotes[1266]="<q>Huge fan of big pussy lips. Love to have those suck the cum out of me!</q>"; quotes[1267]="<q>i would like to put me cock in that pussy. contact me at <EMAIL></q>"; quotes[1268]="<q>Someone should lick that creampie...</q>"; quotes[1269]="<q>just what i was thinking!!</q>"; quotes[1270]="<q>all i wanna do is fuck that cream filled pussy</q>"; quotes[1271]="<q>i like yor photos....</q>"; quotes[1272]="<q>oh i love this pussy</q>"; quotes[1273]="<q>sweetest oiled pussy</q>"; quotes[1274]="<q>IZ THAT CUNT STILL *CUMMING*? </q>"; quotes[1275]="<q>love this picture.</q>"; quotes[1276]="<q>hot close up</q>"; quotes[1277]="<q>go i just want to dive on in</q>"; quotes[1278]="<q>what a hot cumfilled pussy!! i just wanna lick it clean!</q>"; quotes[1279]="<q>Hum... elle bave encore !</q>"; quotes[1280]="<q>Sexy.</q>"; quotes[1281]="<q>I'd lick this clean and slide my tongue inside of you and lick you so well you'll squirt again </q>"; quotes[1282]="<q>I bet that tastes great</q>"; quotes[1283]="<q>mmmmmmmm</q>"; quotes[1284]="<q>When that guy stuck his cock in your wet pussy, how long did it take for you to squeeeze the load out?</q>"; quotes[1285]="<q>AWW ur KIDDING ME?:P *RHETORICAL?*</q>"; quotes[1286]="<q>oh we defo want more gaping crempies like this mmm</q>"; quotes[1287]="<q>id lick that up!</q>"; quotes[1288]="<q>lick mmmmmmmmmmmmmmm</q>"; quotes[1289]="<q>Very yummy!</q>"; quotes[1290]="<q>i love it:)</q>"; quotes[1291]="<q>mmm tongue was out</q>"; quotes[1292]="<q>i want this pussy to be mine</q>"; quotes[1293]="<q>mmm, can i lick it clean?</q>"; quotes[1294]="<q>mmmm</q>"; quotes[1295]="<q>That is fuckin horny, I want to lick your cum covered cunt</q>"; quotes[1296]="<q>what could i do with that ass.... </q>"; quotes[1297]="<q>best ass ever!</q>"; quotes[1298]="<q>beutyful ass and nice peanut(clit),,, lick,,,</q>"; quotes[1299]="<q>That is a tight white cunt. I would make your holes stretch out with this black meatpole and you will fucking love it you nasty bitch</q>"; quotes[1300]="<q>such a tight little pussy. wont be like that when im done with it</q>"; quotes[1301]="<q>can you take all my fat thick cock in your awesome ass hole and pussy mmmmmmmmmmmmm</q>"; quotes[1302]="<q>i would love to deep drill your awsome sweet ass bb mmmmmmmmmmm</q>"; quotes[1303]="<q>OMFG! \u00a0I'm SO drooling right now!</q>"; quotes[1304]="<q>:D</q>"; quotes[1305]="<q>for big black cock? you bet! </q>"; quotes[1306]="<q>maybe i'm too easy sometimes x</q>"; quotes[1307]="<q>ohhh yesss love it when a big black cock is smashing my pussy with no bit of respect</q>"; quotes[1308]="<q>thats good to hear:p</q>"; quotes[1309]="<q>your cock won't be either </q>"; quotes[1310]="<q>always ready for doggystyle </q>"; quotes[1311]="<q>shoot wherever you want on me </q>"; quotes[1312]="<q>not only to the eyes honey;)</q>"; quotes[1313]="<q>my ass has been good for a lot of dicks;D</q>"; quotes[1314]="<q>thats good to hear because i love to get fucked hard and deep from behind</q>"; quotes[1315]="<q>I'd make u cum like crazy</q>"; quotes[1316]="<q>Yummm</q>"; quotes[1317]="<q>and have You ever have Polish sausage in your naughty bum ?......because I have one.....and i'm sure it would be perfect for you</q>"; quotes[1318]="<q>hummmmmmmm</q>"; quotes[1319]="<q>Wow perfect ass</q>"; quotes[1320]="<q>Always room for one more though right?</q>"; quotes[1321]="<q>you're my kind of girl honey</q>"; quotes[1322]="<q>You have a beautiful pussy! I would put you his cock balls deep!!!</q>"; quotes[1323]="<q>I wanna tongue fuck that asshole before I force my BBC in it</q>"; quotes[1324]="<q>that pussy ready to be fuck, and that ass also need a dick in it too</q>"; quotes[1325]="<q>hmm how id love to slap that ass as i hold your hips while teasing your clit as i entered you nice and slowly ;0xx</q>"; quotes[1326]="<q>perfect!</q>"; quotes[1327]="<q>\u0131 want to fuck this ass and pussy</q>"; quotes[1328]="<q>You look ready for doggystyle, I'll volunteer</q>"; quotes[1329]="<q>I wanna grab your hair and put my cock in your asshole!</q>"; quotes[1330]="<q>\</q>"; quotes[1331]="<q>wat would u hav us do if we walked in on u like this and granted u 1 wish, 1 desire, anything u like...wat would it be??their isnt an inch of ur body i wouldnt want 2 explore... tickle, touch, kiss or lick... watever u desired... PURE XTC</q>"; quotes[1332]="<q>Yummmmmy!</q>"; quotes[1333]="<q>I go the worked hand to hand:p</q>"; quotes[1334]="<q>haha yes I go the worked hand to hand:p</q>"; quotes[1335]="<q>haha yes i go the worked hand to hand:p</q>"; quotes[1336]="<q>ooooh Let me return of in hummm</q>"; quotes[1337]="<q>Ready and waiting</q>"; quotes[1338]="<q>i just wanna dive right in ! ;p</q>"; quotes[1339]="<q>perfect, my favorite position for fucking hard both your horny holes!</q>"; quotes[1340]="<q>Id love to stick my dick in that ass</q>"; quotes[1341]="<q>so fucking sexy.... your hips are so nice, perfect to hold on to while slamming you from behind n fuck u deep Inside;),)!!!</q>"; quotes[1342]="<q>I want to shoot my load all over that ass</q>"; quotes[1343]="<q>I would love to stretch that tiny pussy right now!</q>"; quotes[1344]="<q>I wanna eat your pussy,and ass all night long;)</q>"; quotes[1345]="<q>this pussy is so pleasing to the eye's</q>"; quotes[1346]="<q>it would be very hard not to drill this fine asshole every day.</q>"; quotes[1347]="<q>Perfect ass hot pussy! :P:P</q>"; quotes[1348]="<q>wooooooooow perfect sexy ass baby, I would love to lick and fuck both your holes.</q>"; quotes[1349]="<q>stay just like that, i will be right there.</q>"; quotes[1350]="<q>I'll bet he shoots like a water pistol... RV</q>"; quotes[1351]="<q>Christian or not, I'd still want to get him naked and hard and cumming.</q>"; quotes[1352]="<q>All American Boy. \u00a0Nice.</q>"; quotes[1353]="<q>Now there's a guy I'd really enjoy having me \</q>"; quotes[1354]="<q>That's no way to talk about my boyfriend! \u00a0RV</q>"; quotes[1355]="<q>Grrrrrowwwl -- I wouldn't care if this guy topped me or wanted me to top him -- I just wanna fuck with him.\u00a0 Run my tongue all over that body, taste every square inch of him, make him cum so hard he'd be back for seconds!</q>"; quotes[1356]="<q>YOUR boyfriend????\u00a0 I thought he was working towards being MINE!\u00a0 Oh well -- take one look at him and you can see he's a \</q>"; quotes[1357]="<q>id fill your ass to. lovely</q>"; quotes[1358]="<q>wonderfull</q>"; quotes[1359]="<q>I want to stretch out that gape with my tongue!</q>"; quotes[1360]="<q>love to fuck that ass hard</q>"; quotes[1361]="<q>What a sight !</q>"; quotes[1362]="<q>i wanna cum in all your holes</q>"; quotes[1363]="<q>oh yeah im really stroking my cock now x</q>"; quotes[1364]="<q>Amazing pussy and HOT ass!!! Would love to slide my hard cock into both and make you cum!!!</q>"; quotes[1365]="<q>such a warm welcoming asshole you have</q>"; quotes[1366]="<q>ust want put my tonge inside that buthole !!!</q>"; quotes[1367]="<q>id luv to switch off between the two </q>"; quotes[1368]="<q>Mmmm just needs more cum</q>"; quotes[1369]="<q>i want to suck your pussy lips and tongue that asshole</q>"; quotes[1370]="<q>a real good position for a..fucking</q>"; quotes[1371]="<q>sexy pic</q>"; quotes[1372]="<q>Che culoooooooooooooooooooooo</q>"; quotes[1373]="<q>ass fuck too, shit you are my girl.</q>"; quotes[1374]="<q>Love that gaping ass</q>"; quotes[1375]="<q>i wanna stick my fingers, tongue, and cock in both holes!!!</q>"; quotes[1376]="<q>DAMN I JUST LOVE UR OPEN HOLES,I WISH I HAD MY COCK IN BOTH!</q>"; quotes[1377]="<q>can i stretch that asshole a little more baby?</q>"; quotes[1378]="<q>fuck, i was already jacking off then i clicked on this pic and nutted</q>"; quotes[1379]="<q>mmm i love pics like this so tastey xx</q>"; quotes[1380]="<q>mmmmmmmmmmmmmmmmmmmmmmmmm</q>"; quotes[1381]="<q>yummie yumme looks good</q>"; quotes[1382]="<q>what a nice creamy steaky cunt!</q>"; quotes[1383]="<q>I'd luv to cum in your pee hole!</q>"; quotes[1384]="<q>Fuck!!!! sit on my face</q>"; quotes[1385]="<q>Yum, tasty looking!</q>"; quotes[1386]="<q>niceeeeee</q>"; quotes[1387]="<q>shit id love to put my tongue in that</q>"; quotes[1388]="<q>damn that is so beautiful....</q>"; quotes[1389]="<q>I like what I see.</q>"; quotes[1390]="<q>Kinda reminds me of the Czech guys who will do ANYTHING for $200 bucks... \u00a0RV</q>"; quotes[1391]="<q>Damn -- where's a secluded men's room when you need one!!\u00a0 I'd follow that into one and suck him off real good.\u00a0 Kinda thinking he'd go for sucking some cock himself, actually.</q>"; quotes[1392]="<q>Might as well take your pants off. \u00a0It's not hiding anything. \u00a0LOL</q>"; quotes[1393]="<q>A man and his toy!!</q>"; quotes[1394]="<q>I used to LOVE PE class... You could look and not get in trouble. There were always guys who knew they had something good, and wanted to show it off. \u00a0RV</q>"; quotes[1395]="<q>I'd look too. \u00a0Nice buns.</q>"; quotes[1396]="<q>Can't blame the coach for getting a good look. \u00a0It's a beaut.</q>"; quotes[1397]="<q>wow really hot</q>"; quotes[1398]="<q>Luv it cum on ladies grind it out</q>"; quotes[1399]="<q>Girls just wana have fun</q>"; quotes[1400]="<q>very hot!</q>"; quotes[1401]="<q>SEXY</q>"; quotes[1402]="<q>oh yes!</q>"; quotes[1403]="<q>thats hot</q>"; quotes[1404]="<q>SHE LOOKS LIKE MY COUSIN</q>"; quotes[1405]="<q>wow</q>"; quotes[1406]="<q>damn come do my girl like that both of you</q>"; quotes[1407]="<q>Turn me on</q>"; quotes[1408]="<q>wow</q>"; quotes[1409]="<q>Nice pic, and nice piercing too!</q>"; quotes[1410]="<q>beautiful puss</q>"; quotes[1411]="<q>I want to lick that pussy</q>"; quotes[1412]="<q>Pretty nice babes!!</q>"; quotes[1413]="<q>enjoy!</q>"; quotes[1414]="<q>Wanna fuck her perfect tits and cum in her pretty face! Cute smile :-)</q>"; quotes[1415]="<q>hot.</q>"; quotes[1416]="<q>So sexy!</q>"; quotes[1417]="<q>Belle!</q>"; quotes[1418]="<q>So sexy</q>"; quotes[1419]="<q>Very very very hot!</q>"; quotes[1420]="<q>sexy...xxx</q>"; quotes[1421]="<q>Tettona cattiva! Ti voglio!</q>"; quotes[1422]="<q>i love this who is she</q>"; quotes[1423]="<q>Make us a Video girl!!!!!!!!!!!!</q>"; quotes[1424]="<q>She is yummy!</q>"; quotes[1425]="<q>She is yummy!</q>"; quotes[1426]="<q>White lace panties. You're such a tease.......lol</q>"; quotes[1427]="<q>thank you hun im glad you like it . Im not an attention girl but it always turns me on to see what guys think of me</q>"; quotes[1428]="<q>damn i like that booty hangin out of those pants</q>"; quotes[1429]="<q>Well hi , i am the girl in the photo. Me and my boyfriend do this for fun and are new to it . Im glad you like me That was sexy \</q>"; quotes[1430]="<q>Omg i would surely fuck you baby .All that ass mmm baby over the side of the bed just like that</q>"; quotes[1431]="<q>Spread them for me baby</q>"; quotes[1432]="<q>Sexy ass</q>"; quotes[1433]="<q>oooh . hmmm why don't you just squeeze yourself while looking at this </q>"; quotes[1434]="<q>I love it ! I want to squeeze</q>"; quotes[1435]="<q>Suck me like that, please</q>"; quotes[1436]="<q>Yummmm, nice cock, too!</q>"; quotes[1437]="<q>I'd love to give you my white dick </q>"; quotes[1438]="<q>every time i see this pic my cock gets rock hard.......LOVE IT</q>"; quotes[1439]="<q>Nice</q>"; quotes[1440]="<q>you really like that white dick dont you </q>"; quotes[1441]="<q>You know what I like</q>"; quotes[1442]="<q>ok ,aww i guess i have a fan feel free to talk</q>"; quotes[1443]="<q>ooooh accept my friend request !</q>"; quotes[1444]="<q>I want to skeet all over those cheeks</q>"; quotes[1445]="<q>Amazing</q>"; quotes[1446]="<q>How many licks does it take to make you cum</q>"; quotes[1447]="<q>One of the best photos on here</q>"; quotes[1448]="<q>damn! .. beautiful</q>"; quotes[1449]="<q>Yummy, nice and thick!</q>"; quotes[1450]="<q>looks like me!</q>"; quotes[1451]="<q>I like it a nice face what looks at you and spoils your cock, besides, with the mouth!</q>"; quotes[1452]="<q>Do you have more of these girls?</q>"; quotes[1453]="<q>My Boy Lollipop!!</q>"; quotes[1454]="<q>hate that shape</q>"; quotes[1455]="<q>Kissing a cock is nice, but actually sucking it is better.</q>"; quotes[1456]="<q>she s like an angel.</q>"; quotes[1457]="<q>Beautiful. Who doesn't love Raven?</q>"; quotes[1458]="<q>Mmmm like to share that cock</q>"; quotes[1459]="<q>she's look even better with a hot load on her face!</q>"; quotes[1460]="<q>Wow! Very sexy!!!! I wish that was my cock in between those soft titties!</q>"; quotes[1461]="<q>Yeah bitch, it's a REAL cock</q>"; quotes[1462]="<q>Cute</q>"; quotes[1463]="<q>You can tell by the look on her face how bad she really wants it!</q>"; quotes[1464]="<q>Those really are the greatest eyes</q>"; quotes[1465]="<q>very sexy eyes</q>"; quotes[1466]="<q>Pretty girl. Looks like she knows she worked out a big load. Confidence?</q>"; quotes[1467]="<q>Great facial, gorgeous eyes!</q>"; quotes[1468]="<q>She is lovely. Who is she?</q>"; quotes[1469]="<q>Pretty face</q>"; quotes[1470]="<q>nice picture, cum facial is so cool </q>"; quotes[1471]="<q>Wow, I want a woman like you</q>"; quotes[1472]="<q>....looking great ,babe...!!!</q>"; quotes[1473]="<q>Perfect shot on glasses.</q>"; quotes[1474]="<q>She wants the whole world to see how gooed - erh I mean, \</q>"; quotes[1475]="<q>Great Shot!</q>"; quotes[1476]="<q>always a fav pic</q>"; quotes[1477]="<q><NAME> !</q>"; quotes[1478]="<q>who\u00b4s that chick?</q>"; quotes[1479]="<q>Lots of cream here </q>"; quotes[1480]="<q>we LOVE tobi pacific!!!</q>"; quotes[1481]="<q>pretty whore</q>"; quotes[1482]="<q>you like your present</q>"; quotes[1483]="<q>Cream delight </q>"; quotes[1484]="<q>She looks wonderful with that cum on her face! </q>"; quotes[1485]="<q>who is that girl?</q>"; quotes[1486]="<q>Hott Tat!</q>"; quotes[1487]="<q>Lovely!</q>"; quotes[1488]="<q>The cream dessert </q>"; quotes[1489]="<q>WOW i want a facial like that!</q>"; quotes[1490]="<q>is there a video that shows how this face got blasted?</q>"; quotes[1491]="<q>now thats an awesome thick facial</q>"; quotes[1492]="<q>beautiful mess</q>"; quotes[1493]="<q>She looks happy </q>"; quotes[1494]="<q>who\u00b4s that girl? I think I know her ... :-)</q>"; quotes[1495]="<q>nice picture </q>"; quotes[1496]="<q>Damn, aren't you caring that somebody that you know will find this picture? I can't understand it.</q>"; quotes[1497]="<q>Cute face !nice tits !</q>"; quotes[1498]="<q>Gorgeous</q>"; quotes[1499]="<q>Real cum queen.</q>"; quotes[1500]="<q>So cute and so free. I love it !</q>"; quotes[1501]="<q>tra le pi\u00f9 belle pornostar al mondo secondo me</q>"; quotes[1502]="<q>Caprice. So hot, so sexy... beautiful photos.</q>"; quotes[1503]="<q>Fucking get lost eating her wee tight cunt for sure</q>"; quotes[1504]="<q>She is totally beautiful</q>"; quotes[1505]="<q>Call me I'd lick the dildo clean of your cum for sure</q>"; quotes[1506]="<q>mamasita!!!!!!!!!!!!!!!!!!</q>"; quotes[1507]="<q>Beautiful, just beautiful.</q>"; quotes[1508]="<q>Pinky has major skills!!!</q>"; quotes[1509]="<q>this was a great scene she did</q>"; quotes[1510]="<q>Man, if only</q>"; quotes[1511]="<q>i would fuck that ass.....her hair turns me on</q>"; quotes[1512]="<q>i could bust a nut all over Pinky</q>"; quotes[1513]="<q>I have this video Full! </q>"; quotes[1514]="<q>that was my favorite one she ever did was the one for roundandbrown</q>"; quotes[1515]="<q>wow that's what i call yummy</q>"; quotes[1516]="<q>Wish that was my \</q>"; quotes[1517]="<q>nice perfect porny</q>"; quotes[1518]="<q>just awesome!!!!!</q>"; quotes[1519]="<q>thats right take that cock deep</q>"; quotes[1520]="<q>fucking hot!!</q>"; quotes[1521]="<q>honey so hot XXX</q>"; quotes[1522]="<q>ohhhhh that mmust hurt this is making me horny and cumkeep it going</q>"; quotes[1523]="<q>Your the cream in a BBC oreo</q>"; quotes[1524]="<q>omg - lucky girl!</q>"; quotes[1525]="<q>mmmmmm I want so hot baby</q>"; quotes[1526]="<q>ohhhhhh 2 cocks one in the pusy and in the ass</q>"; quotes[1527]="<q>i bet you could making wearing a burlap bag sexy....</q>"; quotes[1528]="<q>sexy hips love that cock stretching your pussy!</q>"; quotes[1529]="<q>thts beautiful hunni.. we need more pix of u.. ur even more beautiful</q>"; quotes[1530]="<q>nice.</q>"; quotes[1531]="<q>I want that nice cock in my pussy too!</q>"; quotes[1532]="<q>Very sexy. This is my favorite pic in this album. I would love to watch my wife with a big black dick but she won't do it. Any tips to get her to do it?</q>"; quotes[1533]="<q>Thats lovely and tight, bet it hurts just a little bit, but I bet you like it that way.</q>"; quotes[1534]="<q>Brava Sam!</q>"; quotes[1535]="<q>DAMN THAT IS PICTURE PERFECT</q>"; quotes[1536]="<q>shame you had to ware</q>"; quotes[1537]="<q>very sexy girl.</q>"; quotes[1538]="<q>lindo interior quitartelo con mis dientes</q>"; quotes[1539]="<q>Beautiful!</q>"; quotes[1540]="<q>So sexiest smile, with eyes full of erotism and sensual lips...</q>"; quotes[1541]="<q>Beautiful</q>"; quotes[1542]="<q>One good looking Babe for sure!</q>"; quotes[1543]="<q>So HOT and sexy, great smile!!!</q>"; quotes[1544]="<q>oh yeah that smile turns me on big time. mmm so nice!</q>"; quotes[1545]="<q>i want to fuck you...</q>"; quotes[1546]="<q>Very pretty!</q>"; quotes[1547]="<q>lucky tinkerbell</q>"; quotes[1548]="<q>you very pretty</q>"; quotes[1549]="<q>sexy women</q>"; quotes[1550]="<q>Oh how I want to pound your twat!</q>"; quotes[1551]="<q>you'r pretty</q>"; quotes[1552]="<q>You're Gorgeous with Your Lovely Smile,Hot Soft Lips & Sexy Intermate Eyes</q>"; quotes[1553]="<q>Hottie! </q>"; quotes[1554]="<q>You are quite sexy! I would love to get to know you better!</q>"; quotes[1555]="<q>I love it when a girl gets comfortable in my car.</q>"; quotes[1556]="<q>When can I see you naked?</q>"; quotes[1557]="<q>oh god baby. open ur mouth wide and do what u do best!</q>"; quotes[1558]="<q>you are really beautiful xxx</q>"; quotes[1559]="<q>very hot</q>"; quotes[1560]="<q>wow..que mujeron !!!</q>"; quotes[1561]="<q>Aren't you just beatiful!</q>"; quotes[1562]="<q>SEXXXY & BEAUTIFUL!</q>"; quotes[1563]="<q>love to fuck you</q>"; quotes[1564]="<q>hi fantastic lady</q>"; quotes[1565]="<q>wow !!!! beutyful lady ;-))</q>"; quotes[1566]="<q>hummm.....</q>"; quotes[1567]="<q>how sexy! x mmmm 5 stars babey. I'll shag u hard to be honest!</q>"; quotes[1568]="<q>HI, YOU ARE SUPER BEAUTY AND SEXY, KISS BI-CHARLI</q>"; quotes[1569]="<q>love this pic</q>"; quotes[1570]="<q>hummm very sexy </q>"; quotes[1571]="<q>You would never guess from such a normal look that you would be a complete cock sucking cum loving slut.. Just the way most men love their women to be..</q>"; quotes[1572]="<q>ohhh ... very sexy and elegant ... mmmm cute baby</q>"; quotes[1573]="<q>ahhh ouiii trop mimi !!!</q>"; quotes[1574]="<q>sexy en diable!!</q>"; quotes[1575]="<q>Pas mal</q>"; quotes[1576]="<q>Wow ...</q>"; quotes[1577]="<q>Belle!!!</q>"; quotes[1578]="<q>tre belle</q>"; quotes[1579]="<q>tres atirante jolie femme!!!</q>"; quotes[1580]="<q>nice begining!</q>"; quotes[1581]="<q>Tr\u00e8s belle fille. J'habite en r\u00e9gion parisienne et j'aimerai vous rencontrer. N'h\u00e9sitez pas \u00e0 me contacter via mon adresse mail : <EMAIL></q>"; quotes[1582]="<q>Hum ce petit anus est tres allechant </q>"; quotes[1583]="<q>si c'est une invitation, je suis dj debout dans mon pantalon!</q>"; quotes[1584]="<q>Tr\u00e8s jolie</q>"; quotes[1585]="<q>mmmmh i want to fuck you so hard!!!</q>"; quotes[1586]="<q>Wow, sexy ...Kissesxxx Annette </q>"; quotes[1587]="<q>I want to eat your hot pussy and lick your ass before fucking them. You make me so hungry and horny</q>"; quotes[1588]="<q>your hot and sexy too.</q>"; quotes[1589]="<q>I want to spit on your asshole and then slide my hard dick inside! Make me blow my load baby!</q>"; quotes[1590]="<q>Quel beau cul</q>"; quotes[1591]="<q>je te demonte</q>"; quotes[1592]="<q>ouaaaa un superbe cul </q>"; quotes[1593]="<q>que c est beau tout ca</q>"; quotes[1594]="<q>Trs jolie tout a,j'ai trs envie de caresser, de toucher et de gouter...</q>"; quotes[1595]="<q>c'est un appel a la sodomie? tres attirant ca ne se refuse pas...</q>"; quotes[1596]="<q>spread wide open... and all just for me? WOW</q>"; quotes[1597]="<q>Quelle magnifique invitation \u00e0 la sodomie!!!</q>"; quotes[1598]="<q>Can I have a taste???</q>"; quotes[1599]="<q>Permets moi de mettre mon gros pnis a l'intrieur de a</q>"; quotes[1600]="<q>hot pussy and ass. so edible and fuckable</q>"; quotes[1601]="<q>Bonne chatte</q>"; quotes[1602]="<q>ca a l air bien acceuillant tout ca</q>"; quotes[1603]="<q>hummm tres joli tous ca j y mettrai bien ma langue;)</q>"; quotes[1604]="<q>that pussy needs my cock in it</q>"; quotes[1605]="<q>c'est qd mme meilleurs une vraie!</q>"; quotes[1606]="<q>j'ai une grosse envie de remplir cette jolie bouche!</q>"; quotes[1607]="<q>EN plus en camouflage</q>"; quotes[1608]="<q>Alors la ... je fond !!!</q>"; quotes[1609]="<q>tu as des yeux bleu magnifique tr\u00e8s exitan</q>"; quotes[1610]="<q>envie de me masturber en voyant a.... hmmm</q>"; quotes[1611]="<q>you like dick in your mouth?</q>"; quotes[1612]="<q>j'adore cette photo</q>"; quotes[1613]="<q>hmmm... ca laisse reveur...</q>"; quotes[1614]="<q>I need you on my cock like that!</q>"; quotes[1615]="<q>mmmh j'aimerai les mordiller</q>"; quotes[1616]="<q>I want to suck on those tits!</q>"; quotes[1617]="<q>Ca donne vraiment envie !!!</q>"; quotes[1618]="<q>HAAAAAAhahaahhaahhahaah lolll trop marrant !!!</q>"; quotes[1619]="<q>oh la gourmande !!!!!!!</q>"; quotes[1620]="<q>wich one u prefer?</q>"; quotes[1621]="<q>il te les faut tous ;-)</q>"; quotes[1622]="<q>alot of toys bbe</q>"; quotes[1623]="<q>belle panoplie tu dois bien t'amuser des fois ^^</q>"; quotes[1624]="<q>y pa une place pour moi</q>"; quotes[1625]="<q>Wow ...</q>"; quotes[1626]="<q>you got ur hands full baby lol ... we definitely gotta cum and help u out </q>"; quotes[1627]="<q>t'en as de beaux jouets ...</q>"; quotes[1628]="<q>it looks like you like it in the ass as well... hmmmmHow many have you had inside you at one time?</q>"; quotes[1629]="<q>Tr\u00e8s belle avec ses bas et ses hauts talons ! J'adore aussi.</q>"; quotes[1630]="<q>MOI AUSSI J ADORE LA LINGERIE</q>"; quotes[1631]="<q>Jolie tenue, j'adore</q>"; quotes[1632]="<q>how about some pics of you getting ass fucked, or maybe some with your dildos in you... that would be hot!</q>"; quotes[1633]="<q>wow.</q>"; quotes[1634]="<q>Una diosa</q>"; quotes[1635]="<q>here!</q>"; quotes[1636]="<q>My sentiments exactly</q>"; quotes[1637]="<q>I was made for it</q>"; quotes[1638]="<q>here i cum</q>"; quotes[1639]="<q>true whore</q>"; quotes[1640]="<q>Don't they all</q>"; quotes[1641]="<q>total trash</q>"; quotes[1642]="<q>whats about my cock?</q>"; quotes[1643]="<q>i agree hun!</q>"; quotes[1644]="<q>where and when let me know</q>"; quotes[1645]="<q>idc bwc will do</q>"; quotes[1646]="<q>but i want to fuc you real hard bb</q>"; quotes[1647]="<q>I'm here for you.</q>"; quotes[1648]="<q>How about a big white cock</q>"; quotes[1649]="<q>I agree what a fucking waste.</q>"; quotes[1650]="<q>i want it too</q>"; quotes[1651]="<q>Lol I google searched trying to find the source of this girl, and unfortunately it's a photoshop, real pic says \</q>"; quotes[1652]="<q>cougar for shure</q>"; quotes[1653]="<q>damn sexy.</q>"; quotes[1654]="<q>they look nicethanks</q>"; quotes[1655]="<q>Spectacular!</q>"; quotes[1656]="<q>Like and Fav!</q>"; quotes[1657]="<q>whoa nice</q>"; quotes[1658]="<q>.. lovely .. </q>"; quotes[1659]="<q>licks 4 uvery hot</q>"; quotes[1660]="<q>Lovely photo,very nice</q>"; quotes[1661]="<q>Damn</q>"; quotes[1662]="<q>I bet it still looks beautiful now!</q>"; quotes[1663]="<q>mmm... looks tasty</q>"; quotes[1664]="<q>nice</q>"; quotes[1665]="<q>Yummy!</q>"; quotes[1666]="<q>Be still my heart</q>"; quotes[1667]="<q>very horny..:)</q>"; quotes[1668]="<q>Fucking fit. So sexy looking at all that cum pouring back out...</q>"; quotes[1669]="<q>beautiful</q>"; quotes[1670]="<q>Her ass is just perfect </q>"; quotes[1671]="<q>I love your ass when you spread that pussy wide open beautiful</q>"; quotes[1672]="<q>love the guys huge balls</q>"; quotes[1673]="<q>Cum here baby, I got a nice BIG cock for ya then you can give me a nice sloppy kiss</q>"; quotes[1674]="<q>make that dick sucking nice and nasty and wet</q>"; quotes[1675]="<q>The way life should be for a big cocked white manpick me!</q>"; quotes[1676]="<q>a gorgeous woman you are I like</q>"; quotes[1677]="<q>Me too!!!!!!!!!!!!!!!!!!</q>"; quotes[1678]="<q>lol, looks like he's kinda carefully backing onto it like parking a car</q>"; quotes[1679]="<q>Mmmmmm, black dick!!!!!</q>"; quotes[1680]="<q>Fuck, I would in a heart beat!!!!</q>"; quotes[1681]="<q>j aime ta chatte</q>"; quotes[1682]="<q>gorgeus</q>"; quotes[1683]="<q>very sexy pic ! thank you !</q>"; quotes[1684]="<q>dam were was I</q>"; quotes[1685]="<q>i wish i was there!!</q>"; quotes[1686]="<q>what a slut!!! good girl </q>"; quotes[1687]="<q>You are one down fuck toy aren't you?</q>"; quotes[1688]="<q>very nice!!</q>"; quotes[1689]="<q>mmmmm one of those lucky guys should be me...</q>"; quotes[1690]="<q>I call next on a bj !!!</q>"; quotes[1691]="<q>My kind of party. Can you guess what part I'd be playing in a scene like this? I can, and I'd be doing it on my knees. I love the taste of cum.</q>"; quotes[1692]="<q>damn what sexy tight little pussy I would love to fill it up with my big dick</q>"; quotes[1693]="<q>Yum yum</q>"; quotes[1694]="<q>my dick between all of those tits... nice</q>"; quotes[1695]="<q>damn, hottie!</q>"; quotes[1696]="<q>Nice hair ^_^</q>"; quotes[1697]="<q>really hot </q>"; quotes[1698]="<q>Very sexy and mysterious.</q>"; quotes[1699]="<q>DAMN!! you re so gorgeous!!! absolutely beautiful!! And a very sexy body.</q>"; quotes[1700]="<q>Du er for kinky i bildene. Du br ta en tur til Danmark.</q>"; quotes[1701]="<q>Wowww.... you are sexy and gorgeous! Great pic</q>"; quotes[1702]="<q>awesome pic mate! cum with me! </q>"; quotes[1703]="<q>damn, you're incredible!</q>"; quotes[1704]="<q>wow, u r Hott, go on, lift it up just a lil more</q>"; quotes[1705]="<q>damm i must admit.. there isnt many things sexier than a tiny lil top just showing the bottom of a perfect looking pair of tits... i cant wait 2 c more</q>"; quotes[1706]="<q>well if this is wat we hav 2 look 4ward 2 in ur albums i cant wait - reow - i love just the look of ur top being just 2 short and ur amazing tits just about 2 fall out...now that is SEXY</q>"; quotes[1707]="<q>Nothing like a good Flash... x E x</q>"; quotes[1708]="<q>stunnin pic pretty face n nice tits</q>"; quotes[1709]="<q>du er utrolig nydelig. utrolig bra og sexy kropp </q>"; quotes[1710]="<q>omg thats hot</q>"; quotes[1711]="<q>wow now thats a good tease</q>"; quotes[1712]="<q>your hair and eyes are so fucking sexxxy</q>"; quotes[1713]="<q>mmmmmmm Very nice</q>"; quotes[1714]="<q>hmmmm the bathroom... one of my fav places in the house... its where the shower/bath is and there is always mirrors</q>"; quotes[1715]="<q>NICE PIC >>> love to be their in the tub;)</q>"; quotes[1716]="<q>so gorgeous, and sexy, you've got it all ;D</q>"; quotes[1717]="<q>would lovee to take you from behind</q>"; quotes[1718]="<q>let me suck those juicy tits!!!</q>"; quotes[1719]="<q>sexy </q>"; quotes[1720]="<q>very very sexy.</q>"; quotes[1721]="<q>Gorgeous.</q>"; quotes[1722]="<q>nydelig!</q>"; quotes[1723]="<q>Mmm, so yummy!</q>"; quotes[1724]="<q>fuck, you're amazingly hot!</q>"; quotes[1725]="<q>hey good lookin </q>"; quotes[1726]="<q>mmmmm id nibble on those all night</q>"; quotes[1727]="<q>wow you are hot</q>"; quotes[1728]="<q>you are drop dead sexy!!!</q>"; quotes[1729]="<q>you have amazing tits </q>"; quotes[1730]="<q>Beauty at its finest!</q>"; quotes[1731]="<q>very nice tits</q>"; quotes[1732]="<q>perfect lil nipples just like my gf... small and always erect - so much better 2 lick, more desirable 2 pinch, and so perfect 2 suck...</q>"; quotes[1733]="<q>Cute, Sweet good enough to treat.. x E x</q>"; quotes[1734]="<q>beautiful.</q>"; quotes[1735]="<q>damn girl you are so hot and sexy!!</q>"; quotes[1736]="<q>wow!!!!! ..nice .xxxx</q>"; quotes[1737]="<q>very sexy !</q>"; quotes[1738]="<q>nice tits </q>"; quotes[1739]="<q>omg so cute</q>"; quotes[1740]="<q>Gorgeous pic, super playful looking. Very nice.</q>"; quotes[1741]="<q>Sexy!</q>"; quotes[1742]="<q>you are really cute, your tits are so perfect;)</q>"; quotes[1743]="<q>Cute & sexy at the same time... thats the best</q>"; quotes[1744]="<q>ke linda nena</q>"; quotes[1745]="<q>utrolig flott jente:)</q>"; quotes[1746]="<q>you are so hot baby! kisses to those titties xxx</q>"; quotes[1747]="<q>wow!!! du er sykt deilig!!</q>"; quotes[1748]="<q>wow, those nipples are perfect!!!!!!!!!!!!!!!!</q>"; quotes[1749]="<q>Girl, you are BEAUTIFUL!</q>"; quotes[1750]="<q>Nice hair ! Nice Eyes ! What else would a man want ! </q>"; quotes[1751]="<q>S\u00fcss</q>"; quotes[1752]="<q>Nydelig! </q>"; quotes[1753]="<q>You have sooo amazing eyes...! i like them!!!</q>"; quotes[1754]="<q>You are so beautiful !!!!</q>"; quotes[1755]="<q>your soo cute:)</q>"; quotes[1756]="<q>WOW gorgeous and amazing eyes ;-) x</q>"; quotes[1757]="<q>amazzzing!</q>"; quotes[1758]="<q>gorgeous picture, love those eyes</q>"; quotes[1759]="<q>you're absolutely gorgeous babe!</q>"; quotes[1760]="<q>Stunning beauty and I Love your eyes.</q>"; quotes[1761]="<q>So sexy and gorgeous!!!</q>"; quotes[1762]="<q>such an amazing rack u hav.. so perfect and perky... so petite and a cleavage that i would get lost in and wouldnt care if i were never found again...</q>"; quotes[1763]="<q>Beautiful eyes</q>"; quotes[1764]="<q>Soooo loving this one</q>"; quotes[1765]="<q>so amazing</q>"; quotes[1766]="<q>sexi pic</q>"; quotes[1767]="<q>I want you </q>"; quotes[1768]="<q>absolute beauty</q>"; quotes[1769]="<q>you are beautiful, love your underwear:)</q>"; quotes[1770]="<q>wow you are so hot babe love this pic</q>"; quotes[1771]="<q>sooo cute</q>"; quotes[1772]="<q>awesome hair, and phenomenal complexion</q>"; quotes[1773]="<q>damn... sykt pen!</q>"; quotes[1774]="<q>you look so cute....the first word that came to mind</q>"; quotes[1775]="<q>such a pretty face.. im not normally into blondes, im more of a brunnett sorta person (as u can c from sarah hehe) but u my dear r gorgeous... something about u makes it hard 2 look away... dunno wat though - very intreguing</q>"; quotes[1776]="<q>Definaltey a Fave</q>"; quotes[1777]="<q>very purty : 3</q>"; quotes[1778]="<q>your features are stellar! i'm with that dude below, favs</q>"; quotes[1779]="<q>Love this pic, you're just so cute!</q>"; quotes[1780]="<q>...smelt...</q>"; quotes[1781]="<q>love it!!</q>"; quotes[1782]="<q>such an amazing body!!! like perfect hour glass, stunning hips.</q>"; quotes[1783]="<q>gorgeous!</q>"; quotes[1784]="<q>super hot pic. You've got an amazing body</q>"; quotes[1785]="<q>yeah we can do it reindeer style </q>"; quotes[1786]="<q>very cute</q>"; quotes[1787]="<q>we think you look hot hun x</q>"; quotes[1788]="<q>such a cutie.. ur gorgeous... so much fun 2 look at... just a fun cheeky dimena and i bet u would b lots of fun in person both in and out of the bedroom hehe</q>"; quotes[1789]="<q>So perfect</q>"; quotes[1790]="<q>You look amazing sexy!Your lips are so hot;)</q>"; quotes[1791]="<q>really nice love it</q>"; quotes[1792]="<q>very hard to beat Phoenix!!</q>"; quotes[1793]="<q>this pic deserve pulicer award! xD</q>"; quotes[1794]="<q>Perfection!</q>"; quotes[1795]="<q>Beautiful Picture</q>"; quotes[1796]="<q>you know he does</q>"; quotes[1797]="<q>THAT FAT PUSSY TAKES IT WELL!!</q>"; quotes[1798]="<q>Stretched wide, about to be pounded deep and hard</q>"; quotes[1799]="<q>he must feel so good inside her</q>"; quotes[1800]="<q>fuck yes that things beautiful!!</q>"; quotes[1801]="<q>whats her name?</q>"; quotes[1802]="<q>name?? pm me it?</q>"; quotes[1803]="<q>monster cock and monster boobs, nice!</q>"; quotes[1804]="<q>Cum to me Baby</q>"; quotes[1805]="<q>my fucking dream girl!</q>"; quotes[1806]="<q>Her curves just look dangerous!</q>"; quotes[1807]="<q>i love fishnets and big tits i love to cum all over them.</q>"; quotes[1808]="<q>i wanna kiss her</q>"; quotes[1809]="<q>favorite place to be</q>"; quotes[1810]="<q>of course they do</q>"; quotes[1811]="<q>lucky girl hihi</q>"; quotes[1812]="<q>Every slut looks better when she's covered in cum. No exceptions.</q>"; quotes[1813]="<q>damn she needs a kiss i'll do it</q>"; quotes[1814]="<q>She must be thinking mm just that moment before he enters me I feel so special to have him want me</q>"; quotes[1815]="<q>Awesome pic!</q>"; quotes[1816]="<q>Sexy Pic!!</q>"; quotes[1817]="<q>Tori's blowjob technique, full lips, working slowly up and down, is one I remember from her performances years ago. Still great to watch.</q>"; quotes[1818]="<q>A recent photo of <NAME>. A classic beauty. She remains employed in the industry as a saleswoman for a web company. A hard worker. Loves her two sons. I wish the best for her. She deserves it.</q>"; quotes[1819]="<q>Most white girls Do!</q>"; quotes[1820]="<q>damn who is she, love her breast</q>"; quotes[1821]="<q>lisa ann</q>"; quotes[1822]="<q>Room for 1 more?</q>"; quotes[1823]="<q>Ooooooh, what a lucky girl, she needs her mouth fucked and her tits slapped, and these Cocks can do that for her!</q>"; quotes[1824]="<q>dayum! she's got a juicy ass and a fat pussy. nice </q>"; quotes[1825]="<q>I Love DPs</q>"; quotes[1826]="<q>Very hot!</q>"; quotes[1827]="<q>You know it</q>"; quotes[1828]="<q>truth</q>"; quotes[1829]="<q>I know that's why.</q>"; quotes[1830]="<q>wow</q>"; quotes[1831]="<q>i love shanes girth... he's amazing</q>"; quotes[1832]="<q>Great cock</q>"; quotes[1833]="<q>If anyone can swallow that monster, it's Sasha!</q>"; quotes[1834]="<q>push your gorgeous cock right down her throat!</q>"; quotes[1835]="<q>wow like my ex</q>"; quotes[1836]="<q>I wanna lick it too</q>"; quotes[1837]="<q>Id lick her asshole till my tounge , fell off</q>"; quotes[1838]="<q>wow love it!!</q>"; quotes[1839]="<q>nice girls can you make the same with my pussy..</q>"; quotes[1840]="<q>please !!!! need a hot girl to get on top of me like this</q>"; quotes[1841]="<q>oh yeah my pussy is weet..ohhh</q>"; quotes[1842]="<q>Nikki...how did I know you would comment on this guy's manhood! lol</q>"; quotes[1843]="<q>mm yes I love seeing him like this</q>"; quotes[1844]="<q>omg baby i need that cock in all of my holes i wanna lick on that asshole master will u pizzzz allow me to at least touch it ?????</q>"; quotes[1845]="<q>I am 'either one' of these horny gals!annie</q>"; quotes[1846]="<q>pi\u0119kna cipka liza\u0142a bym ;D</q>"; quotes[1847]="<q>humm !! j'adore \u2665</q>"; quotes[1848]="<q>My\u015bla\u0142em, \u017ce w moim mie\u015bcie nikt si\u0119 nie umie bawi\u0107 </q>"; quotes[1849]="<q>I wish that you would slide that cock deep inside my asshole and pussy!!!!!</q>"; quotes[1850]="<q>Simply awesome, fuck man, so much ... cheers</q>"; quotes[1851]="<q>how bad do you want it? beg me for this big monster black cock, i want to see your pussy throbbingly juice while you pull this meat out my pants</q>"; quotes[1852]="<q>idk if i can take that monster but i would love to try,,but i know i could prob take it all down my throat,,pretty good at swallowing dick</q>"; quotes[1853]="<q>that is one big ass dick mastr ,,i love it and im gonna do whatever u tell me to do,,can u please give me another demand that u want for me to do for u,im ur black cock slut</q>"; quotes[1854]="<q>I have added you to my favorites.</q>"; quotes[1855]="<q>Tie her up and give her a good fucking</q>"; quotes[1856]="<q>Luv this sexy white bitch! Luv Lisa! Thanks!</q>"; quotes[1857]="<q>You are amazing um I would love to eat your pussy til you couldn't take it then give you this fat dick and suck your man's dick while you watch.</q>"; quotes[1858]="<q>Like</q>"; quotes[1859]="<q>I want one</q>"; quotes[1860]="<q>Wow this slut likes to be owned by master who has hard cock, i can do like her, gag on dick open my legs, be assfucked, suck lick the bulls\u2026.Where his master? I want it if hard cock</q>"; quotes[1861]="<q>she's fucking sexy</q>"; quotes[1862]="<q>wow thats hot</q>"; quotes[1863]="<q>Love it! She has that look like I'm your slave but I'm going to blow your mind. The Chain is sweet too.</q>"; quotes[1864]="<q>nice</q>"; quotes[1865]="<q>wow those tits are hot</q>"; quotes[1866]="<q>perfect boobs...</q>"; quotes[1867]="<q>wow wat a hot slave!!</q>"; quotes[1868]="<q>sexy love it</q>"; quotes[1869]="<q>super sexy</q>"; quotes[1870]="<q>Damn, that's hot</q>"; quotes[1871]="<q>very nice love those tits</q>"; quotes[1872]="<q>OMG...this is the reason why I love big blk cock.</q>"; quotes[1873]="<q>Long and thick...I've seen a dick that thick. Gonna need lots lube.</q>"; quotes[1874]="<q>Want you balls deep in my ass, cumming deep inside it. Katexxx</q>"; quotes[1875]="<q>can you explode on my face i want to taste your cum</q>"; quotes[1876]="<q>miam</q>"; quotes[1877]="<q>would love to be fucked by that</q>"; quotes[1878]="<q>wow.. i want itcome here;)</q>"; quotes[1879]="<q>its so Thick!</q>"; quotes[1880]="<q>mmmmmmmmmmmm nice bbc,</q>"; quotes[1881]="<q>this look good.</q>"; quotes[1882]="<q>that would hurt</q>"; quotes[1883]="<q>Wow! That would be a tough one to swallow, or even up my ass, but I'd sure love to suck on it anyway.</q>"; quotes[1884]="<q>gotta love a big black cock</q>"; quotes[1885]="<q>I would love to take this in the ass</q>"; quotes[1886]="<q>Holy fuck...I'm such a white whore for big blk cock like this...Wish I was riding it</q>"; quotes[1887]="<q>god i'd love to see that cock with cum all over it</q>"; quotes[1888]="<q>mm.... let me fuck that </q>"; quotes[1889]="<q>the things I would let u do to me with BBC....mmmmmm</q>"; quotes[1890]="<q>I'm with Kristina on this... love to see it covered in cum and just pulled out of my ass!!! Katexxx</q>"; quotes[1891]="<q>would love stuffing this in my pussi!</q>"; quotes[1892]="<q>i think all us girls would love to have this cock!</q>"; quotes[1893]="<q>OMG, your bbc makes me so wet and horny</q>"; quotes[1894]="<q>i want that dick </q>"; quotes[1895]="<q>god damn </q>"; quotes[1896]="<q>I can almost taste it!</q>"; quotes[1897]="<q>My goodness, you would have me in blk cock heaven with that sweet blk cock</q>"; quotes[1898]="<q>wow thats thick</q>"; quotes[1899]="<q>So horny for that mamba babe... Katexxx</q>"; quotes[1900]="<q>nice !!</q>"; quotes[1901]="<q>i dont think ive ever seen such a thick cock! and also it still heaps long ahhh!! love it!</q>"; quotes[1902]="<q>mmmmmmmmmmmmmmm I'm licking my pc screen, love ur bbc</q>"; quotes[1903]="<q>To be inside that pussy ... omg</q>"; quotes[1904]="<q>SHE HAS A SWEET ASS</q>"; quotes[1905]="<q>jolie cul</q>"; quotes[1906]="<q>lovely body</q>"; quotes[1907]="<q>nice boobs and pussy i wanna fuck you</q>"; quotes[1908]="<q>Beautiful</q>"; quotes[1909]="<q>nice</q>"; quotes[1910]="<q>very nice</q>"; quotes[1911]="<q>beautiful with big boobs i love it</q>"; quotes[1912]="<q>I like your curves...</q>"; quotes[1913]="<q>You are too sexy, I wish you were close so I could kiss you</q>"; quotes[1914]="<q>OMG!!!! You're soooo sexy! Wonderful foto set!!!</q>"; quotes[1915]="<q>Yes Please! </q>"; quotes[1916]="<q>beautiful body, gorgeous eyes, amazing curves... honey you're absolutely stunning!! </q>"; quotes[1917]="<q>Not fat,just sexy...</q>"; quotes[1918]="<q>You have a so hot body baby!!!</q>"; quotes[1919]="<q>Ur not fat babe Ur fit!!! X</q>"; quotes[1920]="<q>damn i love those big huge natural boobs</q>"; quotes[1921]="<q>so hot * </q>"; quotes[1922]="<q>Mmm your body is perfect</q>"; quotes[1923]="<q>You have a wonderful body. Very sexy.</q>"; quotes[1924]="<q>you look great dont let anyone tell you anything else </q>"; quotes[1925]="<q>:)</q>"; quotes[1926]="<q>the look on your face... so seductive and mysterious... you look like you're ready to go. So sexy </q>"; quotes[1927]="<q>Nice boobs,more pics !</q>"; quotes[1928]="<q>super HOT</q>"; quotes[1929]="<q>wow so sexy</q>"; quotes[1930]="<q>Amazing woman wow!!! Soooooo pretty!!! X</q>"; quotes[1931]="<q>gorgeous</q>"; quotes[1932]="<q>cute and sexy</q>"; quotes[1933]="<q>omfg your eyes and your smile... your stunning.. there is no words for your beauty</q>"; quotes[1934]="<q>amazing eyes!!!</q>"; quotes[1935]="<q>ouaaa very cute, sexy</q>"; quotes[1936]="<q>Thank you! </q>"; quotes[1937]="<q>You have a gorgeous smile on that pretty face dear</q>"; quotes[1938]="<q>Beautiful and hot i like it</q>"; quotes[1939]="<q>so cute!</q>"; quotes[1940]="<q>Your sorta gorgeous babe!!! X</q>"; quotes[1941]="<q>sorta?! you are cute as hell </q>"; quotes[1942]="<q>WOW SO SEXY</q>"; quotes[1943]="<q>I love stockings....especially on you....such a sexy photo ;-)</q>"; quotes[1944]="<q>Sexy + beautiful</q>"; quotes[1945]="<q>Beauty!</q>"; quotes[1946]="<q>really sensual, really sexy, i love</q>"; quotes[1947]="<q>Very nice pics you're so sexy </q>"; quotes[1948]="<q>Oh nice babe</q>"; quotes[1949]="<q>very gorgeous, love the stockings</q>"; quotes[1950]="<q>You are so sexy baby!</q>"; quotes[1951]="<q>Beautiful babe</q>"; quotes[1952]="<q>sexy as fuck</q>"; quotes[1953]="<q>Wow beautiful woman x</q>"; quotes[1954]="<q>What a sexy thing you are! Love the way you tease!</q>"; quotes[1955]="<q>i wish i was behind you....grabbing those perfect tits in my hands!!!</q>"; quotes[1956]="<q>so sexy and hot!</q>"; quotes[1957]="<q>looking amazing babe</q>"; quotes[1958]="<q>a hot swiss roll please miss</q>"; quotes[1959]="<q>You are Very Very Beautiful;)</q>"; quotes[1960]="<q>my my, such an amazing ass. love the seductive look </q>"; quotes[1961]="<q>*_* Amazing :$</q>"; quotes[1962]="<q>can i please eat your pussy</q>"; quotes[1963]="<q>let's talk about spanking </q>"; quotes[1964]="<q>I'll eat ur pussy from behind</q>"; quotes[1965]="<q>SPANK!</q>"; quotes[1966]="<q>"": "r/Me!", "segment": "Solo Female"}</q>"; quotes[1967]="<q>oh lala</q>"; quotes[1968]="<q>looks tasty!</q>"; quotes[1969]="<q>looks like trouble </q>"; quotes[1970]="<q>Wow....you are hot!!</q>"; quotes[1971]="<q>Wow, you have one fantastic arse. Would love to peel those pretty little knickers off you revealing your beautiful little pussy. Slowly stroking my bellend up and down your wet slit before sliding my stiff shaft deep into you. Gripping your hips firmly as I fuck you with long deep thrusts from the tip of my cock right down to my balls banging off your arse x</q>"; quotes[1972]="<q>love fuckin from behind with the panties just to the side... i would love to give you my big throbbing cock</q>"; quotes[1973]="<q>nice pose babe love fucking u this way</q>"; quotes[1974]="<q>dat ass needs a good spankin</q>"; quotes[1975]="<q>lovely lips :$</q>"; quotes[1976]="<q>This one is a favorite..so sexy...and cute at the same time...whew! Hot!</q>"; quotes[1977]="<q>Your soooo fucking hot when you do that w/ your lip...</q>"; quotes[1978]="<q>Just when I thought you could not get any sexier ...lip biting... </q>"; quotes[1979]="<q>Gorgeous picture from a gorgeous girl </q>"; quotes[1980]="<q>\u0421\u0430\u043c\u0430\u044f \u043a\u043b\u0430\u0441\u0441\u043d\u0430\u044f \u0444\u043e\u0442\u043a\u0430</q>"; quotes[1981]="<q>Sexy pic I'd have you biting those beautiful lips soooooo hard</q>"; quotes[1982]="<q>sexy</q>"; quotes[1983]="<q>so perfect</q>"; quotes[1984]="<q>why u bitting em babyy,?? what u want?? ur so freaking delicious !</q>"; quotes[1985]="<q>you can stop trying, you really are a cutie </q>"; quotes[1986]="<q>Yes you are. Sweet and lovely face!!!! Beautiful eyes.... I wanna to eat your kissable lips...</q>"; quotes[1987]="<q>Real Beauty</q>"; quotes[1988]="<q>You dont have to try babe x</q>"; quotes[1989]="<q>nice friends</q>"; quotes[1990]="<q>Wow sweety, you really are beautifull! xoxoxo</q>"; quotes[1991]="<q>astonishing girl, love that smile</q>"; quotes[1992]="<q>I wish u can suck my cock ur so sexxy</q>"; quotes[1993]="<q>dreamy</q>"; quotes[1994]="<q>Let me say it for you stunning woman x</q>"; quotes[1995]="<q>i love ur smile ,eyes & lips</q>"; quotes[1996]="<q>wow, you are simply remarkable.</q>"; quotes[1997]="<q>message me xXxXx</q>"; quotes[1998]="<q>:p</q>"; quotes[1999]="<q>Holy shit, they found the perfect way to make a \</q>"; quotes[2000]="<q>beautiful face and perfect tits..think im in love.</q>"; quotes[2001]="<q>nice</q>"; quotes[2002]="<q>sexy!</q>"; quotes[2003]="<q>.....when i noticed your clevage, i can't stop staring lol you look sooo cuute and sexy</q>"; quotes[2004]="<q>Babe, u r very pretty and i love ur cleavage, lovely tits</q>"; quotes[2005]="<q>I want you all to myself </q>"; quotes[2006]="<q>Nice pic </q>"; quotes[2007]="<q>Very sexy!</q>"; quotes[2008]="<q>cute</q>"; quotes[2009]="<q>really nice girl you are charming!</q>"; quotes[2010]="<q>wow very cute bb</q>"; quotes[2011]="<q>Oh baby you gots a dirty mouth.....I love your dirty mouth.....</q>"; quotes[2012]="<q>I can find no flaw with this photo... perfection!</q>"; quotes[2013]="<q>BEAUTIFUL!!!......You have a perfect body but your face is the better.....Youre so pretty honey, very pretty!!!...</q>"; quotes[2014]="<q>such beauty and so sexy</q>"; quotes[2015]="<q>you have awesome breasts!</q>"; quotes[2016]="<q>dangerous cleavage but provocative!</q>"; quotes[2017]="<q>Bellissima. ti leccherei tutta</q>"; quotes[2018]="<q>BEAUTIFUL!Favorited!!! </q>"; quotes[2019]="<q>haha.. nice..</q>"; quotes[2020]="<q>angel</q>"; quotes[2021]="<q>your a 11/10</q>"; Err:511 quotes[2023]="<q>Would love to go down with her in the elevator, or would it better to go \</q>"; quotes[2024]="<q>Would love to eat that pussy!!!!!!!</q>"; quotes[2025]="<q>Let me suck that out!!!!</q>"; quotes[2026]="<q>mmmm so pretty</q>"; quotes[2027]="<q>Kiss me..sweetheart!!!</q>"; quotes[2028]="<q>mmm give us kiss</q>"; quotes[2029]="<q>nice</q>"; quotes[2030]="<q>I will glady take that cum in my mouth....</q>"; quotes[2031]="<q>Now thats a load mmmmm</q>"; quotes[2032]="<q>Shit thats hot wish i were there mmmm</q>"; quotes[2033]="<q>got a clean shot off lol</q>"; quotes[2034]="<q>I love Deauxma!!! One of my favorite scenes is in the title \</q>"; quotes[2035]="<q>wonderfulll : )-</q>"; quotes[2036]="<q>Nice fuckin wife!</q>"; quotes[2037]="<q>great cock and pussy and ass mmm looks so good</q>"; quotes[2038]="<q>perfect ass</q>"; quotes[2039]="<q>beautifuzl cock... so suckable;)</q>"; quotes[2040]="<q>good wife and you</q>"; quotes[2041]="<q>wow, your one lucky guy. She looks like she's wetter than a rainstorm</q>"; quotes[2042]="<q>your both good looking, sexy and he's well-hung</q>"; quotes[2043]="<q>Prachtschwanz fickt geile Fotze!</q>"; quotes[2044]="<q>mmm hot!</q>"; quotes[2045]="<q>in her ass!</q>"; quotes[2046]="<q>tight fit?</q>"; quotes[2047]="<q>Hast du anal schon mal versucht!?</q>"; quotes[2048]="<q>Badass</q>"; quotes[2049]="<q>love his glans...</q>"; quotes[2050]="<q>In her pussy.Yeeeees</q>"; quotes[2051]="<q>like to join u</q>"; quotes[2052]="<q>Immer wieder ein geiler fick</q>"; quotes[2053]="<q>nice view</q>"; quotes[2054]="<q>Mhh geiler fick, steck ihn tief rein</q>"; quotes[2055]="<q>soo ein tight pussy!!!Sehr sch\u00f6n</q>"; quotes[2056]="<q>good job</q>"; quotes[2057]="<q>Yummy</q>"; quotes[2058]="<q>shes got a nice hole </q>"; quotes[2059]="<q>would love to suck that cock of your pussy</q>"; quotes[2060]="<q>ich mag es auch gern h\u00e4rter... Gru\u00df Conny</q>"; quotes[2061]="<q><NAME> - man erahnt wie geil er Dich von hinten ran nimmt!</q>"; quotes[2062]="<q>That's fantastic.</q>"; quotes[2063]="<q>i like that </q>"; quotes[2064]="<q>nice</q>"; quotes[2065]="<q>I love this pic, is so exciting even if you do not see anything explicit!</q>"; quotes[2066]="<q>Looks like some raw sex! Very nice!</q>"; quotes[2067]="<q>ist das geil</q>"; quotes[2068]="<q>soft pussy!</q>"; quotes[2069]="<q>nice balls and great shot</q>"; quotes[2070]="<q>Sch\u00f6\u00f6\u00f6\u00f6n !all inn</q>"; quotes[2071]="<q>She have a Nice Tasty Fuckable Pussy!!How Wet do she get?:)</q>"; quotes[2072]="<q>Diesen Arsch w\u00fcrd ich liebend gerne auch einmal durchnageln!</q>"; quotes[2073]="<q>my cock begins to swellSlowly he becomes stifflets play together</q>"; quotes[2074]="<q>She is so sexy . Also I love her sexy booty </q>"; quotes[2075]="<q>sch\u00f6ne ansicht</q>"; quotes[2076]="<q>omg what a fuckn awesome ass</q>"; quotes[2077]="<q>shes real nice would love to dump a load in there</q>"; quotes[2078]="<q>Geile blick</q>"; quotes[2079]="<q>w\u00fcrde ich zu gern vollspritzen</q>"; quotes[2080]="<q>very hot!!!!!!!!!</q>"; quotes[2081]="<q>all to lick</q>"; quotes[2082]="<q>oh my gosh, your wife is so sexy. amazing back door!</q>"; quotes[2083]="<q>wow nice pussy,bet she taste good!</q>"; quotes[2084]="<q>she is beautiful</q>"; quotes[2085]="<q>nothin's better then wide open pussy baby it's like it's inviting my dick in</q>"; quotes[2086]="<q>wow perfekt </q>"; quotes[2087]="<q>sch\u00f6ne ansicht</q>"; quotes[2088]="<q>would love to lick your pussy</q>"; quotes[2089]="<q>your pussy Looks delicious</q>"; quotes[2090]="<q>Perfect ass hot pussy 4myhard cock!;)</q>"; quotes[2091]="<q>puedo chuparle el culo!!</q>"; quotes[2092]="<q>perfect</q>"; quotes[2093]="<q>a shame not to be able to play together . kissies</q>"; quotes[2094]="<q>look like you could suck the skin off my shit with them lips</q>"; quotes[2095]="<q>U got da sexiest lips, and a pretty face</q>"; quotes[2096]="<q>waooo tienes unos labios expectaculares</q>"; quotes[2097]="<q>love your lips</q>"; quotes[2098]="<q>Sos tan hermosa!!!</q>"; quotes[2099]="<q>If you ever come to Buenos Aires, drop by La Plata, i cant wait to fuck you!!</q>"; quotes[2100]="<q>Wow!!! I would love to suck your pussy for a very long time!!\u00a0</q>"; quotes[2101]="<q>love this pic</q>"; quotes[2102]="<q>thanks for the info and btw send me an inbox sometime would love to get to chat with you</q>"; quotes[2103]="<q>where did you find this pic at</q>"; quotes[2104]="<q>Shadbase.com, the guy that does this is updating the website every week and it's free</q>"; quotes[2105]="<q>So hot!!!\u00a0</q>"; quotes[2106]="<q>buena</q>"; quotes[2107]="<q>GOOD</q>"; quotes[2108]="<q>I'd love to see you on the side of the road!</q>"; quotes[2109]="<q>what a wonderful arse, favorite of course</q>"; quotes[2110]="<q>p\u00e1\u00e1\u00e1\u00e1ni jsi kr\u00e1sn\u00e1</q>"; quotes[2111]="<q>you are one drop dead gorgeous woman,</q>"; quotes[2112]="<q>Nature offers such beautiful things.</q>"; quotes[2113]="<q>oh I like your smile so much, your body and your kinky hairy pussy make me hard babe</q>"; quotes[2114]="<q>guauuuuuuuuuuuuuu</q>"; quotes[2115]="<q>Pretty... and your smile says a lot of you. Nice</q>"; quotes[2116]="<q>nice body!</q>"; quotes[2117]="<q>You have the perfect body.</q>"; quotes[2118]="<q>Stuuning body and great smile</q>"; quotes[2119]="<q>I love your natural style.</q>"; quotes[2120]="<q>This is such a cute pic. The smile so enticing! </q>"; quotes[2121]="<q>You have a nice smile.</q>"; quotes[2122]="<q>Ok now THAT, is one amazing asssss...</q>"; quotes[2123]="<q>AH! A swallower! </q>"; quotes[2124]="<q>you are my favorite babe</q>"; quotes[2125]="<q>When in doubt, \</q>"; quotes[2126]="<q>flexibility, a must!</q>"; quotes[2127]="<q>this pussy is the perfect PINK</q>"; quotes[2128]="<q>I think she likes to fuck!</q>"; quotes[2129]="<q>love this angle -- bottoms' UP!</q>"; quotes[2130]="<q>Big fake tits, but they still look good with that sticky cumshot on them......</q>"; quotes[2131]="<q>Pretty face, hot cummy lips, mmmm </q>"; quotes[2132]="<q>good suck! the girl know use her tongue!</q>"; quotes[2133]="<q>Professional bj</q>"; quotes[2134]="<q>These sluts know how to treat big cock.</q>"; quotes[2135]="<q>hou , cock in eruption!</q>"; quotes[2136]="<q>Please x</q>"; quotes[2137]="<q>mmmn stunning so hot and sexy</q>"; quotes[2138]="<q>wow, you are so hotttt</q>"; quotes[2139]="<q>Magnifique!!!!</q>"; quotes[2140]="<q>oh my god</q>"; quotes[2141]="<q>damn would love to be at the beach with my arm wrapped around you would have the hottest lady there that's for sure</q>"; quotes[2142]="<q>Fuck you 18! I'm pornhub!</q>"; quotes[2143]="<q>Hard instantly.... add me!</q>"; quotes[2144]="<q>Mmmmmm I want you so hard!</q>"; quotes[2145]="<q>very nice</q>"; quotes[2146]="<q>love that body</q>"; quotes[2147]="<q>i want to suck your body</q>"; quotes[2148]="<q>Nice!</q>"; quotes[2149]="<q>Sweet, would love to see the star in private </q>"; quotes[2150]="<q>Your bf is one lucky guy</q>"; quotes[2151]="<q>Amazing body and smile 3};D</q>"; quotes[2152]="<q>you is very beautiful</q>"; quotes[2153]="<q>fucking hot!</q>"; quotes[2154]="<q>Damn ,thats hot. Love the bush!!</q>"; quotes[2155]="<q>very sexy!</q>"; quotes[2156]="<q>my kinda girl...</q>"; quotes[2157]="<q>Super Hot</q>"; quotes[2158]="<q>Hello You are very beautiful</q>"; quotes[2159]="<q>I actually have this issue somewhere. excellent spread.</q>"; quotes[2160]="<q>APPLAUSE!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!</q>"; quotes[2161]="<q>wonderful magazine because of you.</q>"; quotes[2162]="<q>You're so cute</q>"; quotes[2163]="<q>Alright! Good start!</q>"; quotes[2164]="<q>yup you can get right on top this big dick </q>"; quotes[2165]="<q>very sexy!</q>"; quotes[2166]="<q>wow... my new fantasy for tonight</q>"; quotes[2167]="<q>making the scene as a beauty queen on the cover of a magazine</q>"; quotes[2168]="<q>Sexy smile and gorgeous lips</q>"; quotes[2169]="<q>you are goregous xoxo</q>"; quotes[2170]="<q>U have gorgeous lips. Bi as well?</q>"; quotes[2171]="<q>ahh I want to be in your next porno</q>"; quotes[2172]="<q>i miss datin az girls they all looked like models such as u an were all nice. and i always had the knack of turnin them kinky</q>"; quotes[2173]="<q>Sweet</q>"; quotes[2174]="<q>WOW!! You are stunning Ashley.</q>"; quotes[2175]="<q>Perfect </q>"; quotes[2176]="<q>Thank-you xx</q>"; quotes[2177]="<q>Hey cutie </q>"; quotes[2178]="<q>wow totally gorgeous</q>"; quotes[2179]="<q>Wow cutie! x</q>"; quotes[2180]="<q>YOur eyes entrance me.</q>"; quotes[2181]="<q>Making my heart race...Wow... Stunning girl..xoxo</q>"; quotes[2182]="<q>absolutely beautiful.</q>"; quotes[2183]="<q>this is the perfection!!!</q>"; quotes[2184]="<q>stunningly beautiful,sexy body and my god do I want to play with you!</q>"; quotes[2185]="<q>la pensativa...</q>"; quotes[2186]="<q>beautiful</q>"; quotes[2187]="<q>Stunning</q>"; quotes[2188]="<q>You have some of the most beautiful eyes</q>"; quotes[2189]="<q>wow, seriously wow! perfect</q>"; quotes[2190]="<q>Very beautiful</q>"; quotes[2191]="<q>Can I take you on a date to red lobster, I would never judge you for getting deserts</q>"; quotes[2192]="<q>ooo i wana join </q>"; quotes[2193]="<q>Fantastic moment......</q>"; quotes[2194]="<q>wish i was there</q>"; quotes[2195]="<q>Hey beastmaster. Do You made this pictures.If so, Youre a lucky boy.Greets Pis&Mike</q>"; quotes[2196]="<q>OMG.</q>"; quotes[2197]="<q>wow. loving the clip x</q>"; quotes[2198]="<q>may i cum in your mouth? </q>"; quotes[2199]="<q>waw</q>"; quotes[2200]="<q>go deeper</q>"; quotes[2201]="<q>nice.</q>"; quotes[2202]="<q>one lucky guy</q>"; quotes[2203]="<q>i want to come to ur bed</q>"; quotes[2204]="<q>hottie! x</q>"; quotes[2205]="<q>don't need to ask twice </q>"; quotes[2206]="<q>!!!!!beautiful!!!!</q>"; quotes[2207]="<q>wet dreams love...</q>"; quotes[2208]="<q>nice body</q>"; quotes[2209]="<q>i would love to get in bed with that hotness </q>"; quotes[2210]="<q>Very nice! Would love to chat sometime! Rob</q>"; quotes[2211]="<q>God you have gorgeous legs!! I want them wrapped around me!</q>"; quotes[2212]="<q>great body x</q>"; quotes[2213]="<q>Incredible body girl!!</q>"; quotes[2214]="<q>Stunning!! Mmmmm</q>"; quotes[2215]="<q>sexy</q>"; quotes[2216]="<q>Wow,hot shot,love your hair!</q>"; quotes[2217]="<q>Dammnn!!! Where is this bar??!!!</q>"; quotes[2218]="<q>i'd pour some drink on your naked body, then suck it up or drink from your pussy </q>"; quotes[2219]="<q>Hot body</q>"; quotes[2220]="<q>i love girls that fuck with this shoes!!!!! i wanna impaled your ass and fuck still your wet pussy squirt</q>"; quotes[2221]="<q>you're beautiful you have a beautiful naked body the venglo with you as well I stripped completely naked with huge cock straight then you slam him to ddosso to your naked body</q>"; quotes[2222]="<q>very sexy body hun.</q>"; quotes[2223]="<q>h</q>"; quotes[2224]="<q>Your smile is killer</q>"; quotes[2225]="<q>sexy body</q>"; quotes[2226]="<q>perfect body very beautiful</q>"; quotes[2227]="<q>you're stunning.</q>"; quotes[2228]="<q>Perfect Body</q>"; quotes[2229]="<q>Beautiful!</q>"; quotes[2230]="<q>we'd love to fuck w/U!</q>"; quotes[2231]="<q>yeah babe..my hard cock is ready behind you..</q>"; quotes[2232]="<q>mmmm... i want to bust out my strap-on. such a sexy ass!</q>"; quotes[2233]="<q>Ahhhhhh, just want to play with that hair, and that ass/</q>"; quotes[2234]="<q><EMAIL>.... Add me for casual clit squirting cams or jus fantasy ways n positions</q>"; quotes[2235]="<q>Oh I love to lick that pussy in this position! xoxoxo</q>"; quotes[2236]="<q>wow!!!! i'm sure it's not your best profile, but it's a really good pic. it's makes me bigger!!</q>"; quotes[2237]="<q>Oh baby! I would love to have your ass for one night!</q>"; quotes[2238]="<q>The invitation to fuck that pretty lil ass ...that's the look</q>"; quotes[2239]="<q>hosetwitching pic! great body!</q>"; quotes[2240]="<q>Lovely eyes and that ass ready to be licked hmm</q>"; quotes[2241]="<q>How pretty and very sexy you are !!! Perfect body !!!</q>"; quotes[2242]="<q>You are wonderful baby!</q>"; quotes[2243]="<q>\u0418\u0434\u0435\u0430\u043b\u044c\u043d\u0430\u044f \u043f\u043e\u043f\u043e\u0447\u043a\u0430</q>"; quotes[2244]="<q>grrrr, gonna have wet dreams tonight</q>"; quotes[2245]="<q>ufff I love it, you are so fucking sexy. and natural blonde I think. I love it babe.\u00a0</q>"; quotes[2246]="<q>Great shot!</q>"; quotes[2247]="<q>nice ass would eat and finger it until you start squirting </q>"; quotes[2248]="<q>amazing attitude. lovely sexy eyes and what an perfect ass;)</q>"; quotes[2249]="<q>that's a perfect ass</q>"; quotes[2250]="<q>voila une bite pour ta chatte mon skyp = rida nasiri</q>"; quotes[2251]="<q>you're beautiful and you're all to fuck you infilerei all my huge cock into her ass and inside the pussy</q>"; quotes[2252]="<q>SMACKADATASS! Love to spank you as we fuck hard!</q>"; quotes[2253]="<q>Sexy booty;!</q>"; quotes[2254]="<q>damn</q>"; quotes[2255]="<q>Awwww... Thanks boys!</q>"; quotes[2256]="<q>you look ready to fuck, really stunning babe keeps me up!!!:)</q>"; quotes[2257]="<q>i want u soooo bad</q>"; quotes[2258]="<q>waaaaaw !!!</q>"; quotes[2259]="<q>Very Nice !!!! I would love to toss your salad :-)</q>"; quotes[2260]="<q>LOve that hot little ASS</q>"; quotes[2261]="<q>lm ready for you!!!</q>"; quotes[2262]="<q>I love this position. Grabbing your waist tight and slamming my hard dick deep inside of you in each of your holes would be perfect !!:)!!</q>"; quotes[2263]="<q>wow, I just came to this pic Alexis</q>"; quotes[2264]="<q>Wow beautiful. a pussy as I like it </q>"; quotes[2265]="<q>FANTASTIC body! GORGEOUS face, and your eyes just POP! WOW! :*</q>"; quotes[2266]="<q>yummmmmmmmy u look prefect in that position</q>"; quotes[2267]="<q>quien pillara ese hermoso culito.........</q>"; quotes[2268]="<q>very sexy.</q>"; quotes[2269]="<q>Amazing ass 4my dick baby? ;);)</q>"; quotes[2270]="<q>such a sexy view!! damn!!</q>"; quotes[2271]="<q>awesome love to take you for a ride</q>"; quotes[2272]="<q>Sweet position to mount you..</q>"; quotes[2273]="<q>Wish I was there!</q>"; quotes[2274]="<q>I wanna explode on your face!!!!</q>"; quotes[2275]="<q>I'd love to play very naughty games with you !!!</q>"; quotes[2276]="<q>wawe</q>"; quotes[2277]="<q>we could have some fun, i love doggy too:)</q>"; quotes[2278]="<q>wanna pull ur hair and rape u doggy style, wanna make u scream.......for more</q>"; quotes[2279]="<q>i'll just get behind you and slide it in deep then </q>"; quotes[2280]="<q>i want to fuck youuuuu and cover your face with my cum!!!!!!u r the perfect whore!!!!</q>"; quotes[2281]="<q>would fuck you so hard</q>"; quotes[2282]="<q>Wow!! You are so cute and sexy.</q>"; quotes[2283]="<q>You are a cutie and have a lot of charm !!!</q>"; quotes[2284]="<q>wow. you're so sexy holy shit </q>"; quotes[2285]="<q>natural beauty:)</q>"; quotes[2286]="<q>waiting for you to start sucking mine babe </q>"; quotes[2287]="<q>we both want some of you yum</q>"; quotes[2288]="<q>Pretty picture!!!</q>"; quotes[2289]="<q>ready to get covered in cum</q>"; quotes[2290]="<q>Hey!, she jerks off too. Wonder if she's watching herself:)</q>"; quotes[2291]="<q>She's banging hot.</q>"; quotes[2292]="<q>If only I'd a chosen porndick when they asked me what I wanted to do in life.</q>"; quotes[2293]="<q>Cracking body!!</q>"; quotes[2294]="<q>cute one - I like it !</q>"; quotes[2295]="<q>Mmmm, such a wonderfully sexy little body</q>"; quotes[2296]="<q>wow ein Traum </q>"; quotes[2297]="<q>phuuhhuuu...</q>"; quotes[2298]="<q>Wow! Who is this? Tell her to get on here!!!!!! x</q>"; quotes[2299]="<q>you look amazing x</q>"; quotes[2300]="<q>oh jes</q>"; quotes[2301]="<q>s\u00fcsse strand Maus</q>"; quotes[2302]="<q>Wow, verdammt sexy! Zum vernaschen</q>"; quotes[2303]="<q>Hi cutie ... Beautiful sexy bikini clad woman ! ... _: :_</q>"; quotes[2304]="<q>Hornysandy, ur sooo hot</q>"; quotes[2305]="<q>einfach nur unbeschreiblich hei\u00df!! wow...</q>"; quotes[2306]="<q>wow... sie ist unfassbar hei\u00df!! unglaublich *_*</q>"; quotes[2307]="<q>tooo cute</q>"; quotes[2308]="<q>wow baby great body</q>"; quotes[2309]="<q>du bist ein perfektes st\u00fcck </q>"; quotes[2310]="<q>Gorgeous</q>"; quotes[2311]="<q>perfectt !</q>"; quotes[2312]="<q>boner material</q>"; quotes[2313]="<q>Sexy as hell.</q>"; quotes[2314]="<q>omg you are so beautiful sweetie</q>"; quotes[2315]="<q>wauuuuuuuuuuu......menudo cuerpo.....your body is ok..fuchsia bikini and feel like death</q>"; quotes[2316]="<q>Du bist din geile moese</q>"; quotes[2317]="<q>ein sch\u00f6ner k\u00f6rper honey</q>"; quotes[2318]="<q>geiler body... und heisser bikini</q>"; quotes[2319]="<q>OMFG!!!!!! </q>"; quotes[2320]="<q>oh my good............anal fucking with her..............ahhahahahahahahahah........</q>"; quotes[2321]="<q>Love the hair!</q>"; quotes[2322]="<q>Interesting looking travelogue!</q>"; quotes[2323]="<q>peace, yeah baby..</q>"; quotes[2324]="<q>nice hair </q>"; quotes[2325]="<q>Interesting photograph. Touched or retouched it is rather pretty!</q>"; quotes[2326]="<q>#4 from left</q>"; quotes[2327]="<q>dann komm mal sch\u00f6n vorbei gibts gleich paar mehr f\u00fcr dich </q>"; quotes[2328]="<q>kannst ja mal raten welche davon ich bin </q>"; quotes[2329]="<q>great view</q>"; quotes[2330]="<q>geile \u00e4rsche, geile m\u00e4dels... was will man mehr?!</q>"; quotes[2331]="<q>schwer... sehen halt alle hei\u00df aus :*</q>"; quotes[2332]="<q>lauter granaten </q>"; quotes[2333]="<q>This is not the involvement of a scene that I would expect from you! I guess it shows how big of an asshole I can be! Sorry. I find this exciting. You befriended me and I took the situation as curious. I did not give you the credit that you deserved! I will make it my business to pay more attention to a woman that is more than what she appears. I love that you appear to be exactly as you advertise! Cute, sexy, And while I would make a poor cop, I would guess you are the lady with the</q>"; quotes[2334]="<q>lay with the sash! Thanks, that was fun!</q>"; quotes[2335]="<q>could have some fun with them girls xxx</q>"; quotes[2336]="<q>ich tippe mal auf rosa...zumindest ist das der geilste von allen </q>"; quotes[2337]="<q>Ich vermute auch rosa, aber der Hintern in blau ist auch verdammt hei\u00df! </q>"; quotes[2338]="<q>I am going to go with you are the one either wearing the pink bottoms or the blue bottoms</q>"; quotes[2339]="<q>I am thinking the pink bottoms that have black on them am I right?</q>"; quotes[2340]="<q>blau? :></q>"; quotes[2341]="<q>einen nach dem anderen versohlen und dann verw\u00f6hnen </q>"; quotes[2342]="<q>ass ass ass ass ass </q>"; quotes[2343]="<q>oh my--lovely</q>"; quotes[2344]="<q>you are not in this picture... your body is better than theres, you are a full bodied women these are girls.</q>"; quotes[2345]="<q>Lovely ladies! I, being a numb American, do not trust females in that kind of proximity! Butt, that IS some fine femininity!</q>"; quotes[2346]="<q>Sexy sirens ;-)</q>"; quotes[2347]="<q>u and ur girls are so damn sexy</q>"; quotes[2348]="<q>geiles Foto.. wo ist das?</q>"; quotes[2349]="<q>Beutyul girl,,,, and you have amzing face,,, cute,,, i want kiss your sexy lips,,</q>"; quotes[2350]="<q>Ich will dich S\u00fc\u00dfe </q>"; quotes[2351]="<q>Kussi \u00fcberall S\u00fc\u00dfe, hoffe, wir sehen uns bald, Bussi , HDL </q>"; quotes[2352]="<q>ich tr\u00e4ume schon von unserer ersten Begegnung, hmmmmmmmmmm </q>"; quotes[2353]="<q>Mmmmm, breathtaking!!</q>"; quotes[2354]="<q>Hast echt ein sehr sch\u00f6nes Gesicht....sehr s\u00fc\u00df </q>"; quotes[2355]="<q>und du erst du geiles St\u00fcck </q>"; quotes[2356]="<q>dann hol und nimm mich </q>"; quotes[2357]="<q>Bestes Bild aus dem Album </q>"; quotes[2358]="<q>I find you very attractive.</q>"; quotes[2359]="<q>Du siehst so gut aus du bist so eine sch\u00f6ne Frau</q>"; quotes[2360]="<q>Wow du bist heiss und s\u00fcss</q>"; quotes[2361]="<q>wow ... zum ... Anbei\u00dfen hei\u00df </q>"; quotes[2362]="<q>Damn girl you ARE sexy and so beautiful! I\u00b4d love to tear that t-shirt off you and kiss you every where!!</q>"; quotes[2363]="<q>Sehr sexy !!!</q>"; quotes[2364]="<q>beautiful!!!</q>"; quotes[2365]="<q>you are soon sex mmmmm</q>"; quotes[2366]="<q>I want to kiss ur mouth and ur eyes cause u look so lovely</q>"; quotes[2367]="<q>du bist echt hei\u00df!! wow...</q>"; quotes[2368]="<q>Hrrh!Ich werde dir soo hart meine Ramme geben.!</q>"; quotes[2369]="<q>absolutely stunning</q>"; quotes[2370]="<q>Holy Moly, siehst du gut aus :o</q>"; quotes[2371]="<q>HornySandy92, while I do have asshole tendencies, you have to admit that there is some suspicions that come up then you publish 9 photographs and every one that has you are a part of the group is good photography, yet, when you are exclusive the pictures are haphazard. Curiouser and curiouser!</q>"; quotes[2372]="<q>do you fart during the butt fuck ? \u00a0:)</q>"; quotes[2373]="<q>do you like anal fuck ????????????</q>"; quotes[2374]="<q>wow hammer;)</q>"; quotes[2375]="<q>du bist so sch\u00f6n BITTE nimm MICH!!!wahnsinn</q>"; quotes[2376]="<q>ich glaub dir muss mal richtig dein loch aufgerissen und verw\u00f6hnt werden </q>"; quotes[2377]="<q>Very pretty lady yum yum baby</q>"; quotes[2378]="<q>nice pic</q>"; quotes[2379]="<q>face of a angel ;;) body for sinning </q>"; quotes[2380]="<q>Stunning</q>"; quotes[2381]="<q>love it</q>"; quotes[2382]="<q>wow!!!</q>"; quotes[2383]="<q>sexy..... </q>"; quotes[2384]="<q>nice......</q>"; quotes[2385]="<q>Not the first sayind that but.. Damn your hot!!!</q>"; quotes[2386]="<q>hello beautiful</q>"; quotes[2387]="<q>YOU'RE SO CUTE </q>"; quotes[2388]="<q>mmmm yuor soow sweet :* :* :*</q>"; quotes[2389]="<q>s\u00fc\u00df</q>"; quotes[2390]="<q>beautiful and natural ... i love it!!! </q>"; quotes[2391]="<q>du hast sch\u00f6ne lippen</q>"; quotes[2392]="<q>your all hot! I wish I could hang with you....</q>"; quotes[2393]="<q>du bist einfach ne geile sau </q>"; quotes[2394]="<q>wow!du siehst einfach supergeil aus!!!</q>"; quotes[2395]="<q>untouchable</q>"; quotes[2396]="<q>I love you like thaaaaat!!!</q>"; quotes[2397]="<q>your so dam sexy I love to look at all pictures sexy</q>"; quotes[2398]="<q>Baby, I want you as soon as possible, am hot on you...wow </q>"; quotes[2399]="<q>Einfach nur h\u00fcbsch und Sexy</q>"; quotes[2400]="<q>wow da m\u00f6cht ich jetzt auch gerne sein ^^</q>"; quotes[2401]="<q>Really beautiful picture babe. You look simply gorgeous brunette although you do whatever colour your hair is. Please post more pics you are so hot!!! x</q>"; quotes[2402]="<q>as beautiful and gorgeous as ever princess</q>"; quotes[2403]="<q>Hrrr zu dir w\u00fcrde ich doch auch gerne mal in Whirpool steigen - nackt versteht sich </q>"; quotes[2404]="<q>Your albums are stunning..</q>"; quotes[2405]="<q>knaller weibchen! lecker lecker </q>"; quotes[2406]="<q>i could eat you out underwater </q>"; quotes[2407]="<q>Du bist eine absulut SCH\u00d6NHEIT!!!hab mich in deine augen verliebt</q>"; quotes[2408]="<q>Would love to join you in there.</q>"; quotes[2409]="<q>Boingg!** mmmm..... you make my cock hard...</q>"; quotes[2410]="<q>Please post more pics you are so hot</q>"; quotes[2411]="<q>sweet ...xxx</q>"; quotes[2412]="<q>Sublime. xoxo</q>"; quotes[2413]="<q>w\u00e4re jetzt gerne mit dir in dem pool.. h\u00e4tte lust..;)</q>"; quotes[2414]="<q>your eyes says that u r dam crazy in bed mmmmmmmmmmmmmm</q>"; quotes[2415]="<q>du bist echt \u00b4ne traumfrau!!!</q>"; quotes[2416]="<q>oh mann!s\u00fcsse, du bist echt \u00b4ne traumfrau...</q>"; quotes[2417]="<q>I wanna make some face shots again... </q>"; quotes[2418]="<q>One in bikini and I give you my cum...</q>"; quotes[2419]="<q>stunning</q>"; quotes[2420]="<q>ur cute</q>"; quotes[2421]="<q>you have a nice smile</q>"; quotes[2422]="<q>que linda</q>"; quotes[2423]="<q>You're beautiful! Thanks for the post!</q>"; quotes[2424]="<q>snoochie boochies, fucking snoogans on that cunt</q>"; quotes[2425]="<q>too bad that isnt really you... notice : watermark at the bottom left of the pic...</q>"; quotes[2426]="<q>Can you say perfect ? I can</q>"; quotes[2427]="<q>10</q>"; quotes[2428]="<q>wonderfuly tight!</q>"; quotes[2429]="<q>If this picture is really you, I just have to say WOW. You so yummy.</q>"; quotes[2430]="<q>10</q>"; quotes[2431]="<q>mmmmmmmmmmmmmmmmmm yummmmie thanXXX</q>"; quotes[2432]="<q>Smochie Booches</q>"; quotes[2433]="<q>you have my attention and my mouth watering !</q>"; quotes[2434]="<q>nice ass</q>"; quotes[2435]="<q>hmmmmm im glad u like 2 show off ur bum... theirs nothing i find more attractive than a nice lil petite bubble bum that just looks like it needs 2 hav a bite taken out of it</q>"; quotes[2436]="<q>that looks so very delicious... ao smooth</q>"; quotes[2437]="<q>Hmm...hot....would love to lick both holes..:-)</q>"; quotes[2438]="<q>i like you !! kiss you baby !!!</q>"; quotes[2439]="<q>i want lick your asshole ciaooo bella</q>"; quotes[2440]="<q>now honestly thats a beautifulll amazing pic that i ever sawwwwwwwwwwwwwwwww</q>"; quotes[2441]="<q>que bonito trasero</q>"; quotes[2442]="<q>thats so hot i have to lick my monitor lol</q>"; quotes[2443]="<q>i would love to lick that ass</q>"; quotes[2444]="<q>HOTHOTHOT!!!!</q>"; quotes[2445]="<q>hai un culetto fantastico. ciao</q>"; quotes[2446]="<q>sweet!!!!!!!!!</q>"; quotes[2447]="<q>Perfect</q>"; quotes[2448]="<q>Great ass great pussy would give you 10 stars if I could!mmmm </q>"; quotes[2449]="<q>Perfec, sweet, pink great ass/pussy</q>"; quotes[2450]="<q>nice ass</q>"; quotes[2451]="<q>You have such a beautiful smile.</q>"; quotes[2452]="<q>Gorgeous Smile babe : )</q>"; quotes[2453]="<q>yup, you're so pretty alright ;DComment my pics too XD</q>"; quotes[2454]="<q>Lovely</q>"; quotes[2455]="<q>You're so beautiful.. </q>"; quotes[2456]="<q>Great Smile Hun</q>"; quotes[2457]="<q>nice pic</q>"; quotes[2458]="<q>love that gorgeous and sexiest smile XD</q>"; quotes[2459]="<q>A women that like Patron as much as I do is rockin`.</q>"; quotes[2460]="<q>looks tasty</q>"; quotes[2461]="<q>yes please... atleast im confident that u know how 2 party and hav fun... sign me in</q>"; quotes[2462]="<q>maddd cute..let me put my mouth where that money is lol</q>"; quotes[2463]="<q>let me have some of that</q>"; quotes[2464]="<q>Oh Yeah!!! It's time to party</q>"; quotes[2465]="<q>Hell yeah!! This picture says: \</q>"; quotes[2466]="<q>Ok still looking tasty but Sloppy tasty</q>"; quotes[2467]="<q>Too Hot</q>"; quotes[2468]="<q>lol thats funni as... drunk??</q>"; quotes[2469]="<q>this picture is maddd sexy</q>"; quotes[2470]="<q>whow!! how'd it happen? XD</q>"; quotes[2471]="<q>Looks like fun! </q>"; quotes[2472]="<q>looks like u were having fun</q>"; quotes[2473]="<q>hi baby you have a great body , i soooooo love mmmmmm ciaoooo</q>"; quotes[2474]="<q>she is hot.</q>"; quotes[2475]="<q>See, now I like the cosplay..... Pika!!!</q>"; quotes[2476]="<q>Looking Snowtight !</q>"; quotes[2477]="<q>linda blancanieves</q>"; quotes[2478]="<q>Ohhhh Yeah!</q>"; quotes[2479]="<q>damn hot milf would love to bang her</q>"; quotes[2480]="<q>omg!!! can we be friends?! uh u r so hooooooooot!!!</q>"; quotes[2481]="<q>now we just need to lower that top and check what's under the hood huh? *kisses*</q>"; quotes[2482]="<q>great!!!</q>"; quotes[2483]="<q>perfection at it's best</q>"; quotes[2484]="<q>Ummm Yeah Nice ....very nice</q>"; quotes[2485]="<q>wow everyone who's commented on this pic is fucking retarted.... nice rack haha</q>"; quotes[2486]="<q>yummy!</q>"; quotes[2487]="<q>yellow looks amazing on ur complection... and such an awesome rack... licks lips</q>"; quotes[2488]="<q>OH MY GOD!!!!! THOSE ARE REALLY BEAUTIFUL!!!! WOLD YOU LET ME HAVE A TASTE OF THOSE????</q>"; quotes[2489]="<q>can i suck them?</q>"; quotes[2490]="<q>love those tits, nice.</q>"; quotes[2491]="<q>i love'em ;D</q>"; quotes[2492]="<q>Stunning!</q>"; quotes[2493]="<q>Baby got Boobs :-)</q>"; quotes[2494]="<q>i love it</q>"; quotes[2495]="<q>Freaking fine</q>"; quotes[2496]="<q>Hot as Hell Girl.....great fucking legs and again luv that smile</q>"; quotes[2497]="<q>Very Sexy Girl ....Luv your legs hun</q>"; quotes[2498]="<q>Great photo,you look lovely</q>"; quotes[2499]="<q>YOU ARE REALLY A PRETTY WOMAN!!</q>"; quotes[2500]="<q>this one is nice, i like it so much XD</q>"; quotes[2501]="<q>damn sexy,great body nice smile and beautiful eyes.you have the whole package</q>"; quotes[2502]="<q>sexy</q>"; quotes[2503]="<q>very cute in this pic</q>"; quotes[2504]="<q>Very beautiful</q>"; quotes[2505]="<q>can i beat??</q>"; quotes[2506]="<q>I love this one :-)</q>"; quotes[2507]="<q>nice</q>"; quotes[2508]="<q>How come I never saw you in my bathroom?.. </q>"; quotes[2509]="<q>asnul6 - you lucky bastard !</q>"; quotes[2510]="<q>nice</q>"; quotes[2511]="<q>do you need some body to take pictures for you</q>"; quotes[2512]="<q>Hello there, hottie.</q>"; quotes[2513]="<q>looks good</q>"; quotes[2514]="<q>cute</q>"; quotes[2515]="<q>My favorite dreamgirl i love you kim</q>"; quotes[2516]="<q>Come show me daddy</q>"; quotes[2517]="<q>Think you can handle it?</q>"; quotes[2518]="<q>idk if she could bro ... LOL</q>"; quotes[2519]="<q>Only one way to find out.. I need that big black dick to fill my tight lil pussy</q>"; quotes[2520]="<q>I want u to beat my pussy up jus like that!!</q>"; quotes[2521]="<q>fuck me like this plizz</q>"; quotes[2522]="<q>so hot</q>"; quotes[2523]="<q>Mmmm hit my spot from the back</q>"; quotes[2524]="<q>THEY ARE AWESOME</q>"; quotes[2525]="<q>Oohhhh I love sucking a big black dick mmm lemme prove it to you daddy</q>"; quotes[2526]="<q>I want all that cum in my mouth!!</q>"; quotes[2527]="<q>She looks so fine with her glasses on. Love those pics/scenes.</q>"; quotes[2528]="<q>fuck yeah</q>"; quotes[2529]="<q>Now I feel much better doctor.</q>"; quotes[2530]="<q>Stain these glasses with huge load</q>"; quotes[2531]="<q>Lovely big ass</q>"; quotes[2532]="<q>I love redheads</q>"; quotes[2533]="<q>Some of them make great love!</q>"; quotes[2534]="<q>says who?</q>"; quotes[2535]="<q>girls with dicks are not attractive.</q>"; quotes[2536]="<q>I love black chicks with dicks</q>"; quotes[2537]="<q>Mmmmm....they are so sexy.....I love chicks with dicks...xxxx</q>"; quotes[2538]="<q>I'd like to join in!</q>"; quotes[2539]="<q>Good girl</q>"; quotes[2540]="<q>That's a hardcore bitch</q>"; quotes[2541]="<q>Some girls is given everything</q>"; quotes[2542]="<q>six great looking cocks on one hot babe!</q>"; quotes[2543]="<q>Six loads on that pretty face</q>"; quotes[2544]="<q>looks like she doesn't have a choice</q>"; quotes[2545]="<q>looks like more fun than im havn atm</q>"; quotes[2546]="<q>LIKE!</q>"; quotes[2547]="<q>Nicely fucked big ass slut</q>"; quotes[2548]="<q>Jerk those cocks in your hands</q>"; quotes[2549]="<q>That's a nice cupful of cum!! I can't believe it so so full!</q>"; quotes[2550]="<q>I want to suck her mouth....</q>"; quotes[2551]="<q>Don't waist it sweety</q>"; quotes[2552]="<q>Good girl</q>"; quotes[2553]="<q>Dylan is handjob master</q>"; quotes[2554]="<q>Awesome fun</q>"; quotes[2555]="<q>Very cute</q>"; quotes[2556]="<q>Kool Kitty</q>"; quotes[2557]="<q>very naughty</q>"; quotes[2558]="<q>uuuuuuuu</q>"; quotes[2559]="<q>SeXy Sirens..XxX</q>"; quotes[2560]="<q>two is better than one </q>"; quotes[2561]="<q>sexy and hot, love to folow you</q>"; quotes[2562]="<q>very sexy</q>"; quotes[2563]="<q>toutes ces photos sont belles avec de bien jolies filles sexy et de jolies lesbiennes que j'aime et respecte le souhait , bisous \u2665these photos are beautiful with very pretty girls sexy and pretty lesbians that I love and respect the wishes, kisses \u2665</q>"; quotes[2564]="<q>hey ....so hot darling...a big kiss from italy.</q>"; quotes[2565]="<q>can i eat that pussy</q>"; quotes[2566]="<q>HomeLand Security..USA</q>"; quotes[2567]="<q>luv it</q>"; quotes[2568]="<q>I wanna see more</q>"; quotes[2569]="<q>Sweet-Tight Firm-SeXy</q>"; quotes[2570]="<q>Sexy!!</q>"; quotes[2571]="<q>OMG... u r my type...let me see u bb...</q>"; quotes[2572]="<q>Sweet Again..XxX</q>"; quotes[2573]="<q>sexy</q>"; quotes[2574]="<q>very sexy</q>"; quotes[2575]="<q>o mio dio!!! che figa!!!</q>"; quotes[2576]="<q>damn girl you fine!</q>"; quotes[2577]="<q>suk my nob u sexy fuker xxxxxxxxxx</q>"; quotes[2578]="<q>I love it</q>"; quotes[2579]="<q>Picasso had to see this!</q>"; quotes[2580]="<q>Beautiful!</q>"; quotes[2581]="<q>nice lookin ass</q>"; quotes[2582]="<q>Ti voglio</q>"; quotes[2583]="<q>mmmmm, i love to explore your sexy body</q>"; quotes[2584]="<q>Love those sexy curves baby</q>"; quotes[2585]="<q>I love a girl with real curves.</q>"; quotes[2586]="<q>OMG I am in heaven thinking of jumping on your fine fat ass and spread those fantastic buns pushing my hard cock deep into your fat pink pussy and ride you hard pulling hair and slapping that great ass as I pump your pussy full of cock and my huge hot creamy cum load ! xoxo :):):)</q>"; quotes[2587]="<q>you are a nice looking chubby lady!</q>"; quotes[2588]="<q>beatifull picture!! peace of art</q>"; quotes[2589]="<q>very nice position. i wanna lick your ass this position baby</q>"; quotes[2590]="<q>Love to lie on top and ride your sweet ass.</q>"; quotes[2591]="<q>This picture looks like art - Rembrandt's painting ! http://en.wikipedia.org/wiki/Dana%C3%AB_%28Rembrandt_painting%29</q>"; quotes[2592]="<q>nice ass</q>"; quotes[2593]="<q>GREAT ASS TO HOLD WHILE YOU SIT ON MY FACE</q>"; quotes[2594]="<q>GREAT ASS!</q>"; quotes[2595]="<q>i would like to meet u</q>"; quotes[2596]="<q>Lovley curves..... Welll Helloooooooo x E x</q>"; quotes[2597]="<q>So beautiful! You look like a Botero paint. I want to follow each and everyone of your curves until I reach the paradise between your legs</q>"; quotes[2598]="<q>Great arse,would love to run my tongue over it.</q>"; quotes[2599]="<q>mmmmmmmmmmmmmmmm, you make my man's cock hard</q>"; quotes[2600]="<q>You have nice Sexy Curves,Legs and Butt!!:O;)</q>"; quotes[2601]="<q>That's the position i like fuck you sweetie</q>"; quotes[2602]="<q>god hello sexy</q>"; quotes[2603]="<q>Perfect!!! Love that ass and those thighs</q>"; quotes[2604]="<q>mmmmm, i'd love to exxxplore your curve-a-licious bod!</q>"; quotes[2605]="<q>nice ass</q>"; quotes[2606]="<q>mmmmmmmmm love that pic and btw fine ass babes</q>"; quotes[2607]="<q>your so sexxy ... id love to fuck you !!!</q>"; quotes[2608]="<q>si j'etais un artiste peintre je t'aurais fait un magnifique croquil adorable femme</q>"; quotes[2609]="<q>i like!!</q>"; quotes[2610]="<q>such a sweet ass</q>"; quotes[2611]="<q>Damn, that\u00b4s hot</q>"; quotes[2612]="<q>nice and tight</q>"; quotes[2613]="<q>Nice penetration</q>"; quotes[2614]="<q>Delicious</q>"; quotes[2615]="<q>great.</q>"; quotes[2616]="<q>Fantastic</q>"; quotes[2617]="<q>Favorite</q>"; quotes[2618]="<q>Great</q>"; quotes[2619]="<q>Gorgeous</q>"; quotes[2620]="<q>Hottie</q>"; quotes[2621]="<q>She is soooooo fuckin Hott</q>"; quotes[2622]="<q>hmmmm</q>"; quotes[2623]="<q>this is hot as fuck</q>"; quotes[2624]="<q>Horny</q>"; quotes[2625]="<q>Hot</q>"; quotes[2626]="<q>Hot</q>"; quotes[2627]="<q>Nice</q>"; quotes[2628]="<q>that is one nice pussy</q>"; quotes[2629]="<q>Pretty</q>"; quotes[2630]="<q>Wonderful</q>"; quotes[2631]="<q>suk on my dik xx</q>"; quotes[2632]="<q>cute</q>"; quotes[2633]="<q>Fantastic ass!!</q>"; quotes[2634]="<q>great ass!!</q>"; quotes[2635]="<q>very nice ass</q>"; quotes[2636]="<q>WHAT A P.H.A.T. ass u have love it hun!!! your so damn fine!!</q>"; quotes[2637]="<q>Perfect!</q>"; quotes[2638]="<q>u r so hot</q>"; quotes[2639]="<q>COOL</q>"; quotes[2640]="<q>Cute and sexy, very nice </q>"; quotes[2641]="<q>FIT! Your pussy looks gorgeous here, and your body is so well proportioned, sooo sexy</q>"; quotes[2642]="<q>I really like you</q>"; quotes[2643]="<q>hm i would like to fuck u !</q>"; quotes[2644]="<q>miss hottness!</q>"; quotes[2645]="<q>you are amazing..</q>"; quotes[2646]="<q>you have beautiful tits i would luv to suck on while im rubbin your clit an slidin a finger or two in till your nice and wet to ride my cock</q>"; quotes[2647]="<q>So hot</q>"; quotes[2648]="<q>LOOK AT THAT BODY..WOW</q>"; quotes[2649]="<q>MMMMMMMMMMMMMM CUMERE !!!!!!!!!!!!!!!!!!!</q>"; quotes[2650]="<q>lekker</q>"; quotes[2651]="<q>Mmmm. I want to make your thighs melt babe.</q>"; quotes[2652]="<q>such a tonned sexy body... drop dead gorgeous... u hav a body most girls dream about and sum guys would kill 2 b with even just for 5min</q>"; quotes[2653]="<q>nice body ..OxoxXOox</q>"; quotes[2654]="<q>mooi figuurtje...xxx</q>"; quotes[2655]="<q>i'd love to fuck the hell out of you...</q>"; quotes[2656]="<q>love your juicy pussy lol</q>"; quotes[2657]="<q>very nice</q>"; quotes[2658]="<q>perfect body!!!</q>"; quotes[2659]="<q>Yummy!</q>"; quotes[2660]="<q>fuckyeah. You look good, baby.</q>"; quotes[2661]="<q>great body</q>"; quotes[2662]="<q>i'd love to have you as a girlfriend here **kisses**</q>"; quotes[2663]="<q>would love to suck that</q>"; quotes[2664]="<q>let me lick your pussy now,please</q>"; quotes[2665]="<q>Mmm I love it, I could spend all day inside you</q>"; quotes[2666]="<q>Nice honey</q>"; quotes[2667]="<q>damn, you're amazingly hot!</q>"; quotes[2668]="<q>humm yummy!!! can i try??</q>"; quotes[2669]="<q>i wanna lick u all over</q>"; quotes[2670]="<q>luv to have your sweet lips wrapped around my cock while im lickin and teasing your sweet pussy and i would luv to cum all over your sexy face</q>"; quotes[2671]="<q>nice pusse</q>"; quotes[2672]="<q>youed look so nice on my face LOL</q>"; quotes[2673]="<q>wat would u hav us do if we walked in on u like this and granted u 1 wish, 1 desire, anything u like...wat would it be??their isnt an inch of ur body i wouldnt want 2 explore... tickle, touch, kiss or lick... watever u desired... PURE XTC</q>"; quotes[2674]="<q>yum</q>"; quotes[2675]="<q>Youuu are gorgeous, babe!</q>"; quotes[2676]="<q>what i wouldnt give damn your sexy</q>"; quotes[2677]="<q>Beautiful, you are stunning</q>"; quotes[2678]="<q>love it. Getting that pussy right out there. So sexy.</q>"; quotes[2679]="<q>mysterious and sexy hmm!</q>"; quotes[2680]="<q>yummy pussy</q>"; quotes[2681]="<q>i want to slam ur holes....</q>"; quotes[2682]="<q>Your ass is incredible! My tongue could do a lot in there. </q>"; quotes[2683]="<q>I now have a raging hard on from this pic of your fine self </q>"; quotes[2684]="<q>Looks ass licking good</q>"; quotes[2685]="<q>WHAT A HARD LIL ASS</q>"; quotes[2686]="<q>my fav doggie!!!</q>"; quotes[2687]="<q>too nice =]my favorite</q>"; quotes[2688]="<q>wow that is a perfect ass this is my favorite pic of them all luv to fuck you doggie style and fil your ass and pussy with my throbbin cock</q>"; quotes[2689]="<q>Beautiful</q>"; quotes[2690]="<q>Ready for action! Love that ass!</q>"; quotes[2691]="<q>Wanna fuck you hard...</q>"; quotes[2692]="<q>thats my fav babe</q>"; quotes[2693]="<q>u are so sexy</q>"; quotes[2694]="<q>i wana go DEEP n them holes with this BBC till u cant take it anymore n SCREAM </q>"; quotes[2695]="<q>hmmmmm im glad u like 2 show off ur bum... YUMM YUMM.. SUCH A PERFECT LIL BUBBLE BUTT... SO VERY BITEABLE... AN ASS THAT PERFECT SHOULDNT B FLAUNTED LIKE THAT.. U GIV US NAUGHTY LIL BOYS IDEAS</q>"; quotes[2696]="<q>ok my 22cm are fully erected now babe! ready to fuck your little snatch</q>"; quotes[2697]="<q>great ass</q>"; quotes[2698]="<q>Wonderful</q>"; quotes[2699]="<q>jou wil ik wel een keer klaar likken en hard op zun hondjes nemen mmm</q>"; quotes[2700]="<q>beautiful stance!</q>"; #NAME? quotes[2702]="<q>that looks yummy</q>"; quotes[2703]="<q>Id love to give you a hard pounding from behind</q>"; quotes[2704]="<q>Perfect position, \u00a0my cock want into your horny pussy\u00a0</q>"; quotes[2705]="<q>wonderful</q>"; quotes[2706]="<q>I would lick every bit</q>"; quotes[2707]="<q>WELL HELLO SANDY THIS PIC IS FUCKING HOT HOT HOT...XXX</q>"; quotes[2708]="<q>Want to ravage your gorgeous snatch and beautiful arse</q>"; quotes[2709]="<q>i would luv to fuck you like that and fill you with my cock</q>"; quotes[2710]="<q>mmmmm can i eat ur sweet pussy?</q>"; quotes[2711]="<q>mmmur tea's getting creamy, my i taste</q>"; quotes[2712]="<q>Hey Sandy, dat is wel een heel lekker nat kutje. Zit nu al lekker met een harde paal in mijn hand. Wil best wel eens weten wat jou handen ermee kunnen. Dat zal ik dat natte kutje ook even onder handen nemen.-x-</q>"; quotes[2713]="<q>hmmmm lovely sexy ass </q>"; quotes[2714]="<q>NOW THATS A PINK PUSSY</q>"; quotes[2715]="<q>not bad, id slap that</q>"; quotes[2716]="<q>i wanna fuck this pussy!!!! is perfect...</q>"; quotes[2717]="<q>hmmm, langzaam erin</q>"; quotes[2718]="<q>THATS WAT I LOVE 2 C.. IM DEFINITELY AN ASS MAN AND MY DEAR U HAV AN ASS THAT JUST BEGS 2 B SLAPPED... WAT I WOULD GIVE 2 PUT ONE NICE RED HAND PRINT DEAD CENTRE ON EITHER ONE OF THOSE PERFECT LIL CHEEKS</q>"; quotes[2719]="<q>lekker schatje</q>"; quotes[2720]="<q>fucking beautiful</q>"; quotes[2721]="<q>mmmmmmm so hot!</q>"; quotes[2722]="<q>I have to creampie you, babe!</q>"; quotes[2723]="<q>Would love to fuck you ..Rough</q>"; quotes[2724]="<q>woww uv gt a sexy bum!!!!</q>"; quotes[2725]="<q>I want to bury my face in it.</q>"; quotes[2726]="<q>like too taste it mmmm</q>"; quotes[2727]="<q>Hmm want to lick it</q>"; quotes[2728]="<q>Pretty holes.</q>"; quotes[2729]="<q>would love to lick u </q>"; quotes[2730]="<q>Quite the sexy body you have!</q>"; quotes[2731]="<q>ohh yes you are very sexy...I want you:)</q>"; quotes[2732]="<q>Amazing body, you're really hot </q>"; quotes[2733]="<q>Wow! Sexy hips</q>"; quotes[2734]="<q>great body you\u00b4re really hot</q>"; quotes[2735]="<q>sexy!!! but can i get a smile???</q>"; quotes[2736]="<q>so sexy</q>"; quotes[2737]="<q>this one to to my faves...love it..</q>"; quotes[2738]="<q>your fuckin uber sexy</q>"; quotes[2739]="<q>hmm jij bent lekker!</q>"; quotes[2740]="<q>gaaaaaaaawd ur so cute and sexy baby!!</q>"; quotes[2741]="<q>Tu es trs belle !!!</q>"; quotes[2742]="<q>wow perfect body very beautiful tits</q>"; quotes[2743]="<q>je bent erg knap, als je eens model wil staan voor me, laat dan gerust iets weten</q>"; quotes[2744]="<q>beautiful and whery sexy too </q>"; quotes[2745]="<q>i would love t make a video with her...omfg...</q>"; quotes[2746]="<q>yah she is</q>"; quotes[2747]="<q>Flipping Gorgeous girl!</q>"; quotes[2748]="<q>I wish that was my dick!</q>"; quotes[2749]="<q>i love him!!!!!</q>"; quotes[2750]="<q>What a lovely pink circumcised cock! Nicely trimmed too</q>"; quotes[2751]="<q>Mouthwatering cock.</q>"; quotes[2752]="<q>inbox me sexy! would love to chat asap!</q>"; quotes[2753]="<q>very nice cock.</q>"; quotes[2754]="<q>beautiful cock</q>"; quotes[2755]="<q>Amazing legs</q>"; quotes[2756]="<q>yes so hot!</q>"; quotes[2757]="<q>Fuck dude I'm working overtime been workin a lot lately and I still find myself logging onto this site &amp; checking out your pics!!! Fucking awesome man!</q>"; quotes[2758]="<q>def my favorite out of this album</q>"; quotes[2759]="<q>Fucking excellent!!!!!</q>"; quotes[2760]="<q>Hot body</q>"; quotes[2761]="<q>wowwwwwwwwwwwwwwwwww</q>"; quotes[2762]="<q>funyyyyyyyyyyyyyyyyyyyyyyyyy</q>"; quotes[2763]="<q>\u0432\u043e\u0442 \u044d\u0442\u043e \u043a\u0440\u0443\u0442\u043e</q>"; quotes[2764]="<q>now thats a hairy beaver</q>"; quotes[2765]="<q>\u043a\u043b\u0430\u0441</q>"; quotes[2766]="<q>Bleib sooo - ich geb Dir einen kleinen Klaps auf Deinen sexy Po!</q>"; quotes[2767]="<q>Insane! Yum.</q>"; quotes[2768]="<q>omg! das ist ein mega arsch!! den wuerde ich so gern aufspiessen</q>"; quotes[2769]="<q>I would tribute this photo if the resolution was a bit higher :/</q>"; quotes[2770]="<q>mmm I want that little sexy ass of yours so damn bad</q>"; quotes[2771]="<q>NICE ASS!!!!!</q>"; quotes[2772]="<q>WOW>>NOW THAT'S AN ASS BABY:):);)</q>"; quotes[2773]="<q>very nice ... i like it !!! </q>"; quotes[2774]="<q>If you was looking at me I could....^^</q>"; quotes[2775]="<q>MMmmmm^^ I wanna cover this of pleasure!!!</q>"; quotes[2776]="<q>THIS is a good one!</q>"; quotes[2777]="<q>That's hot</q>"; quotes[2778]="<q>good doggy</q>"; quotes[2779]="<q>yes hun.</q>"; quotes[2780]="<q>did you get it in the ass dear</q>"; quotes[2781]="<q>i ll blast your ass!!! just as a good whore loves it!!!</q>"; quotes[2782]="<q>U&I can suck cock together!annie</q>"; quotes[2783]="<q>dirty slut, sexy oral</q>"; quotes[2784]="<q>Awesome! x</q>"; quotes[2785]="<q>Work it girl...</q>"; quotes[2786]="<q>nice</q>"; quotes[2787]="<q>the best pornstar..............waooooooooooo</q>"; quotes[2788]="<q>nice</q>"; quotes[2789]="<q>like.....waooo</q>"; quotes[2790]="<q>love u</q>"; quotes[2791]="<q>oofffffffffff</q>"; quotes[2792]="<q>20</q>"; quotes[2793]="<q>Grate</q>"; quotes[2794]="<q>mmmm i loove baby! xoxo</q>"; quotes[2795]="<q>sit on my face any day sexy</q>"; quotes[2796]="<q>hei\u00c3\u0178</q>"; quotes[2797]="<q>I want to lick you front to back</q>"; quotes[2798]="<q>GORGEOUS!</q>"; quotes[2799]="<q>lekker kontje toch.</q>"; quotes[2800]="<q>oh wow, I love this photo of you</q>"; quotes[2801]="<q>Yummy</q>"; quotes[2802]="<q>I LOVE this pic! SO HOT! I wish i was the one who took it...</q>"; quotes[2803]="<q>You are so beautiful</q>"; quotes[2804]="<q>oh my i love whatt i am seeing </q>"; quotes[2805]="<q>Nice</q>"; quotes[2806]="<q>you have a very nice body</q>"; quotes[2807]="<q>Can I hit it from the back</q>"; quotes[2808]="<q>fucken sexy</q>"; quotes[2809]="<q>Kiss xxx Annette</q>"; quotes[2810]="<q>you are so sexy</q>"; quotes[2811]="<q>"": "r/Me!", "segment": "Solo Female"}</q>"; quotes[2812]="<q>il fo une bite pour sex</q>"; quotes[2813]="<q>mmmmmmmmmmmmmm hot kiss</q>"; quotes[2814]="<q>such a tease of a pic!you are sexy!!</q>"; quotes[2815]="<q>sexy</q>"; quotes[2816]="<q>damn hot!</q>"; quotes[2817]="<q>Very pretty.</q>"; quotes[2818]="<q>Yes.</q>"; quotes[2819]="<q>nice view M</q>"; quotes[2820]="<q>amaazing</q>"; quotes[2821]="<q>Great blowjob, can I join in?</q>"; quotes[2822]="<q>Both holes looking tight.</q>"; quotes[2823]="<q>horny slut^^</q>"; quotes[2824]="<q>Beautiful cocksucker, grear tongue technique</q>"; quotes[2825]="<q>Hingabe!!</q>"; quotes[2826]="<q>da w\u00c3\u00bcrde ich gern mal mitmachen</q>"; quotes[2827]="<q>sehr heiss!!! lass mich dein hengst sein</q>"; quotes[2828]="<q>oh yes!</q>"; quotes[2829]="<q>is that you ?</q>"; quotes[2830]="<q>She is so hot!</q>"; quotes[2831]="<q>It my favorite !!!</q>"; quotes[2832]="<q>meine herrn, ist das ne hei\u00c3\u0178e braut!</q>"; quotes[2833]="<q>uuoooouuu</q>"; quotes[2834]="<q>hot</q>"; quotes[2835]="<q>this pic is so hot please let me clean that all off you with my tongue I will share it with you this has me sooooo thirsty for some warm tasty cum yummmm</q>"; quotes[2836]="<q>lick lick...</q>"; quotes[2837]="<q>I want to fuck her asshole with my tongue</q>"; quotes[2838]="<q>wow, perfect!</q>"; quotes[2839]="<q>id love to squirt that fine ass!</q>"; quotes[2840]="<q>very exciting</q>"; quotes[2841]="<q>sexy ass only made better with cum</q>"; quotes[2842]="<q>full penatration</q>"; quotes[2843]="<q>Look at her silky hair - she does this regularly!</q>"; quotes[2844]="<q>COHF Gabrielle, the best COHF girl and the greatest bukkake facial and cunt eating scene of all time....love how dirty she is what she does with cum....</q>"; quotes[2845]="<q>Modesty? \u00a0You know you want me to squeeze and fondle you and suck your nipples hard.</q>"; quotes[2846]="<q>WHO IS THIS AMAZINGLY BEAUTIFUL GIRL ? SHE LOOKS A LOT LIKE ANNE HATHAWAY ! IS SHE ON PORNHUB ?</q>"; quotes[2847]="<q>I will sound stupid BUT she looks like a classmate of mine, her name was Kylee (or something like that)</q>"; quotes[2848]="<q>She is damn hot, someone find out her name, some more pics would kick ass!</q>"; quotes[2849]="<q>She is without a doubt one of the hottest girls on PH!</q>"; quotes[2850]="<q>gotta love scene chicks.. i would tear that shit up.. for days...</q>"; quotes[2851]="<q>This is my favorite part of the day</q>"; quotes[2852]="<q>mmmm sexy i like</q>"; quotes[2853]="<q>Nice fuckable tits!\u00a0 YUM!</q>"; quotes[2854]="<q>Damn</q>"; quotes[2855]="<q>nice everything</q>"; quotes[2856]="<q>I'm jealous</q>"; quotes[2857]="<q>yes xxxxx</q>"; quotes[2858]="<q>amazing</q>"; quotes[2859]="<q>Beautiful, she got a name?</q>"; quotes[2860]="<q>Omg</q>"; quotes[2861]="<q>just what I need!</q>"; quotes[2862]="<q>I think i'm sick, please help me</q>"; quotes[2863]="<q>Nice cleavage, Faith! YUM!</q>"; quotes[2864]="<q>lucky guy</q>"; quotes[2865]="<q>just lovin these two pieces of meat to fuck!sry but when im seein these bitches i just can talk of pieces and not of human beings xD</q>"; quotes[2866]="<q>good xxxxx</q>"; quotes[2867]="<q>double the fun</q>"; quotes[2868]="<q>so cute face </q>"; quotes[2869]="<q>Beautiful Insertion Wish it was me though</q>"; quotes[2870]="<q>Wow wish that was me, You are literally perfect!!! x</q>"; quotes[2871]="<q>oh my!!</q>"; quotes[2872]="<q>All the way in ball Deep he missing playing with u\u00b4r Beautiful Clitt</q>"; quotes[2873]="<q>so hot</q>"; quotes[2874]="<q>that is great pic. this should be the PH Pic of the Week. APPLAUSE!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!</q>"; quotes[2875]="<q>Luv doing this</q>"; quotes[2876]="<q>I bet that is nice and tight</q>"; quotes[2877]="<q>Love this pic... Nice ass fuck</q>"; quotes[2878]="<q>Niiiiice... i love this pic.</q>"; quotes[2879]="<q>What a beautiful hole</q>"; quotes[2880]="<q>Come here so I can fuck that ass balls deep.</q>"; quotes[2881]="<q>nice creampie</q>"; quotes[2882]="<q>now thats nice x</q>"; quotes[2883]="<q>hmmmmmmmm let me try it baby!!</q>"; quotes[2884]="<q>Super cum!!</q>"; quotes[2885]="<q>mmmhhhh excellent</q>"; quotes[2886]="<q>that is a nice cumshot very sexy pic and that pussy looks amazing covered in hot cum</q>"; quotes[2887]="<q>mmmh,i wanna open more that asshole!!!!!!</q>"; quotes[2888]="<q>that is a fucking load n a half</q>"; quotes[2889]="<q>nice load</q>"; quotes[2890]="<q>I can beat that up for you let me know baby</q>"; quotes[2891]="<q>very delicious,I want to lick .</q>"; quotes[2892]="<q>yammi</q>"; quotes[2893]="<q>splendid view</q>"; quotes[2894]="<q>Oh wow, I would love to lick your ass clean babe!</q>"; quotes[2895]="<q>Nice</q>"; quotes[2896]="<q>if you ever need some younger cock, im here</q>"; quotes[2897]="<q>so hot double pleasure. Kisses from lauren</q>"; quotes[2898]="<q>lovely :-P</q>"; quotes[2899]="<q>dude on left is thick</q>"; quotes[2900]="<q>love u face snd body</q>"; quotes[2901]="<q>Girl, you are absolutely lovely!</q>"; quotes[2902]="<q>U my favourite</q>"; quotes[2903]="<q>Nice body!very sexy</q>"; quotes[2904]="<q>You have the most penetrating eyes. Very nice.</q>"; quotes[2905]="<q>you make that collar look so hot</q>"; quotes[2906]="<q>lindo lunar</q>"; quotes[2907]="<q>Mmmm..very Beautiful Hot Suckable Tits!!:)</q>"; quotes[2908]="<q>absoluly gogus vey nice</q>"; quotes[2909]="<q>nice!</q>"; quotes[2910]="<q>wow very sexy i love your boobs</q>"; quotes[2911]="<q>that is fucking sexy baby</q>"; quotes[2912]="<q>mhm@those nipples</q>"; quotes[2913]="<q>Gorgeous eyes, hot body</q>"; quotes[2914]="<q>You are beautifull Cassandra! Great tits very sexy pic </q>"; quotes[2915]="<q>You look even hotter!</q>"; quotes[2916]="<q>sexy eyes!;)</q>"; quotes[2917]="<q>This photo makes me want you. Your always so hot</q>"; quotes[2918]="<q>hmmmmmmmmmmmmmmmmmmmmmmm...</q>"; quotes[2919]="<q>THis is one ur best pics....seductive</q>"; quotes[2920]="<q>They just keep getting better:)</q>"; quotes[2921]="<q>Now this is HOT!!!!!!!!!!!!!! Damn...........</q>"; quotes[2922]="<q>beautiful photo!</q>"; quotes[2923]="<q>MMM you make that jumpsuit look so good. looks liek it was designed just 4 uuuuuuu</q>"; quotes[2924]="<q>I love what you wear! is so hot!! And it fits you so well!!</q>"; quotes[2925]="<q>hot</q>"; quotes[2926]="<q>lookin' good, baby. Does that zip any further?</q>"; quotes[2927]="<q>you're totally hot cassie</q>"; quotes[2928]="<q>very hot</q>"; quotes[2929]="<q>Too sexy :-)</q>"; quotes[2930]="<q>*Grins* This looks like a \</q>"; quotes[2931]="<q>i like the idea of you been in that position infront of me whilst i'm wankining, waitiong for me to shoot my man juice all over you.....\</q>"; quotes[2932]="<q>mmm! nice tits! nice POV!</q>"; quotes[2933]="<q>what are you waiting for, girl? Get started.</q>"; quotes[2934]="<q>Gorgeous Face,Soft Passionate Lips & Sexy Eyes..Cover Them All wth My Big Hot Load </q>"; quotes[2935]="<q>just the way i like</q>"; quotes[2936]="<q>great pic hun. your eyes are gorgeous</q>"; quotes[2937]="<q>I'll Pick This One, I Seen You Use It As An Avatar Before, So You Must Like It. </q>"; quotes[2938]="<q>open up and take my dick in your mouth gorgeous</q>"; quotes[2939]="<q>cute girl</q>"; quotes[2940]="<q>Beautifull pic stunning absolutly stunning!!</q>"; quotes[2941]="<q>Yes, this is probably the sexiest picture of you. The look in your eyes, the perfect tits, the smooth cunt and taht sexy collar! You are just beautiful girl!</q>"; quotes[2942]="<q>Hypenotising!i looked at for long moments,if you're alive in front of me how I'll react!!</q>"; quotes[2943]="<q>You are driving me crazy...</q>"; quotes[2944]="<q>great pic </q>"; quotes[2945]="<q>i wish you where sitting on my face</q>"; quotes[2946]="<q>I wabt you babe!:)very hot</q>"; quotes[2947]="<q>Hot</q>"; quotes[2948]="<q>Wow babe your Stunning,,,,So Sexy</q>"; quotes[2949]="<q>love this pose i would love to straddle you with my nutsack swinging on your face!!</q>"; quotes[2950]="<q>thank you for sharing that hot body! great tits</q>"; quotes[2951]="<q>simply hot as hell!</q>"; quotes[2952]="<q>love this pic, awesome shot</q>"; quotes[2953]="<q>Gorgeous Hot and Sexy..I can just cum all over you;)</q>"; quotes[2954]="<q>wow wat a body</q>"; quotes[2955]="<q>looking hottt</q>"; quotes[2956]="<q>INCREDIBLE such a yearning in your eyes mmmmmm</q>"; quotes[2957]="<q>i want sex with you.you looks so hot bunny!!!!</q>"; quotes[2958]="<q>Yeah! I'm ready too girl!!</q>"; quotes[2959]="<q>you look ready for action</q>"; quotes[2960]="<q>hottt</q>"; quotes[2961]="<q>nice i wish its for me</q>"; quotes[2962]="<q>something about a little choker that makes a girl look so sexy. makes my dick hard.</q>"; quotes[2963]="<q>Hot very hot love this pic </q>"; quotes[2964]="<q>i like u</q>"; quotes[2965]="<q>i want to rape your mouth !</q>"; quotes[2966]="<q>You are sexy!</q>"; quotes[2967]="<q>Like the collar, very hot!</q>"; quotes[2968]="<q>I like your hairstyle! sexy!! And I still want to lick those beautiful tits! </q>"; quotes[2969]="<q>What beautiful Tits thank you</q>"; quotes[2970]="<q>Can i hold the leash?</q>"; quotes[2971]="<q>HELLO SEXY!!</q>"; quotes[2972]="<q>beautiful</q>"; quotes[2973]="<q>You look very Sexy in that Black Out Fit:)</q>"; quotes[2974]="<q>you are so hot!</q>"; quotes[2975]="<q>a very nice Hairstyle......</q>"; quotes[2976]="<q>love to lick your pussy</q>"; quotes[2977]="<q>wat a cute pussy, its screeming for a good lickin</q>"; quotes[2978]="<q>lick lick lick lick lick</q>"; quotes[2979]="<q>nice pussy ! i want to lick it !! :X</q>"; quotes[2980]="<q>yummy</q>"; quotes[2981]="<q>I just want to cum all over that</q>"; quotes[2982]="<q>I want a taste</q>"; quotes[2983]="<q>i would fuck that</q>"; quotes[2984]="<q>No forks or knives, please.</q>"; quotes[2985]="<q>mmmm sweet pussy</q>"; quotes[2986]="<q>i hope you got fucked real good by the camera person.....hope he crawled up and licked you good first...</q>"; quotes[2987]="<q>nice pussy</q>"; quotes[2988]="<q>estas como para sexxx</q>"; quotes[2989]="<q>Yummy!!I Lick and Suck your Pussy's Lips then Suck your Clit,stick my Tongue deep your Pussy and then Slide my Hard Cock all the way deep in Your Pussy!!:)</q>"; quotes[2990]="<q>this pic made me cum! so sexy!</q>"; quotes[2991]="<q>lick lick that</q>"; quotes[2992]="<q>WOW, this is 1 FANTASTIC pic of you! It's also one of my FAVS here!</q>"; quotes[2993]="<q>looks good from here</q>"; quotes[2994]="<q>:)</q>"; quotes[2995]="<q>Sexy! Very pretty pussy too!</q>"; quotes[2996]="<q>yum yum</q>"; quotes[2997]="<q>fuckin hot</q>"; quotes[2998]="<q>i'd fuck the puusy n the ass!</q>"; quotes[2999]="<q>Yum yum</q>"; quotes[3000]="<q>it looks so hot....i would like to lick your pussy first and later your ass hole...really hot..!!!</q>"; quotes[3001]="<q>WOW very sexy shot absolutly georgeous want to lick it </q>"; quotes[3002]="<q>i envy the person taking this photo. would love to have you spread eagled on my floor ur pussy looks soooo sweet and perfectly shaved massive turn on!</q>"; quotes[3003]="<q>hehe, nice idea!</q>"; quotes[3004]="<q>what's the title of the fuck scene from this gif?</q>"; quotes[3005]="<q>;)</q>"; quotes[3006]="<q>From 4chan, so dunno,sorry</q>"; quotes[3007]="<q>I knew the official video was cut ;-)</q>"; quotes[3008]="<q>que rico</q>"; quotes[3009]="<q>I forgot the name of this one... =0\u00a0 What was it again?</q>"; quotes[3010]="<q>Oo god sexy</q>"; quotes[3011]="<q>Too bad it is photo-shopped. Look how small his wrist is (with the watch) compared to the forearm above it. Jeez.</q>"; quotes[3012]="<q>good lord</q>"; quotes[3013]="<q>amazinggg</q>"; quotes[3014]="<q>ummmmm</q>"; quotes[3015]="<q>Nice and hard!</q>"; quotes[3016]="<q>NOW THAT'S A COCK!!!!!!!</q>"; quotes[3017]="<q>YO, BRIAN4MTV!!! DON'T B SO READY TO JUDGE BRO. IT IS IN-FACT A \</q>"; quotes[3018]="<q>nice</q>"; quotes[3019]="<q>Nice</q>"; quotes[3020]="<q>How long and how thick?I'm not even gay, and I'm still tempted to suck you off.</q>"; quotes[3021]="<q>Tremendous horsecock! I'd drink up the cum out of that huge condom!</q>"; quotes[3022]="<q>his cock is amazing!</q>"; quotes[3023]="<q>Now that's what I call a Friday night!</q>"; quotes[3024]="<q>\</q>"; quotes[3025]="<q>\</q>"; quotes[3026]="<q>WOW........i mean wow. absolutley gorgeous</q>"; quotes[3027]="<q>Yes mi Queen</q>"; quotes[3028]="<q>Gorgeous</q>"; quotes[3029]="<q>Erotic</q>"; quotes[3030]="<q>Sexy Photo, Love the Voyeur feel about it</q>"; quotes[3031]="<q>that's art!</q>"; quotes[3032]="<q>I would def. do this!!</q>"; quotes[3033]="<q>very nice</q>"; quotes[3034]="<q>This is the hottest picture in the album!</q>"; quotes[3035]="<q>Excellent party bitches!</q>"; quotes[3036]="<q>Intense scissor! My favorite position </q>"; quotes[3037]="<q>What scene is this</q>"; quotes[3038]="<q>HUMMMMM</q>"; quotes[3039]="<q>mmmmm you naughty naughty i like it i love it when a girl is a freak all the way</q>"; quotes[3040]="<q>i've got some cum for you over here </q>"; quotes[3041]="<q>cum in face is so delicious mmmm</q>"; quotes[3042]="<q>woww you are so hot.</q>"; quotes[3043]="<q>So nice.I would love to add some more to it</q>"; quotes[3044]="<q>great pic</q>"; quotes[3045]="<q>nice pic.. more?</q>"; quotes[3046]="<q>hummm yess</q>"; quotes[3047]="<q>Wanna make out?</q>"; quotes[3048]="<q>Cutie,I want to cum in your pretty mouth</q>"; quotes[3049]="<q>I bet I could make you smile too.</q>"; quotes[3050]="<q>Now that 's HOT pretty face covered in cum Hot!</q>"; quotes[3051]="<q>so perfect!</q>"; quotes[3052]="<q>You're Gorgeous with hot smile but.. next time it's going to my cum all over your pretty face..haha</q>"; quotes[3053]="<q>Now I can give you a REALLY good facial. See my cum video. That was the second take because I missed the first one!</q>"; quotes[3054]="<q>nice facial baby, you ready to take my load?</q>"; quotes[3055]="<q>OH YAEH Babe!!</q>"; quotes[3056]="<q>mmmm sexy i want to stick my tongue in your delicious pussy and lick your sweet ass before i fuck them both</q>"; quotes[3057]="<q>i want to lick it...</q>"; quotes[3058]="<q>damnnnn baby this pic is so fuckin sexy</q>"; quotes[3059]="<q>My dick would fit real nice in there! </q>"; quotes[3060]="<q>hmmm perfect holes</q>"; quotes[3061]="<q>sexy ass and pussy, needs my dick</q>"; quotes[3062]="<q>mouth watering!</q>"; quotes[3063]="<q>ready for cum beybe</q>"; quotes[3064]="<q>Nice wide Perfect!!Let me it wider with my cock!!</q>"; quotes[3065]="<q>Damn, Can I put my dick in it?</q>"; quotes[3066]="<q>All I can say is WOW.</q>"; quotes[3067]="<q>I could get to that!</q>"; quotes[3068]="<q>That's close but a little too blurry...</q>"; quotes[3069]="<q>:P</q>"; quotes[3070]="<q>i want to rub my cock along those pussy hairs</q>"; quotes[3071]="<q>sweet pussy babe</q>"; quotes[3072]="<q>very nice!</q>"; quotes[3073]="<q>yummy</q>"; quotes[3074]="<q>damn girl, your tight pussy got stretched wide there</q>"; quotes[3075]="<q>I would like to Slide my Big Black Cock Deep In Your Pussy!!</q>"; quotes[3076]="<q>nice pussy</q>"; quotes[3077]="<q>Delicious.</q>"; quotes[3078]="<q>nice oriental cunt. offer it to occidental cock!</q>"; quotes[3079]="<q>cute and petite baby i surely want to fuck you</q>"; quotes[3080]="<q>Dame!!I would like to suck your Tits,Eat your Pussy out in till you get nice and wet and Fuck you Hard;)</q>"; quotes[3081]="<q>very nice body you are nice</q>"; quotes[3082]="<q>How adorable.</q>"; quotes[3083]="<q><NAME>!!! Lovely!!! Remember back in the day she used to only do girls, glad she changed her ways tho. Gotta love her'forcedplay' vids!</q>"; quotes[3084]="<q>Ah Janine, one of my all time favorites..Finger in her ass, beautiful shaved pussy..I do love her!</q>"; quotes[3085]="<q>this picture is so hott. love it!</q>"; quotes[3086]="<q>Oooh, I can just feel this one..Looks like fun Vivi!</q>"; quotes[3087]="<q>Would love to let my balls explode all over that sexy face and watch her swallow the rest as I shove my big thick cock deep down her throat!</q>"; quotes[3088]="<q>She looks like <NAME>...</q>"; quotes[3089]="<q>fucking hell i would do her for hours.</q>"; quotes[3090]="<q>Those breasts are absolutely the most perfect set I think I have ever seen! Id love to have a pair like that or maybe just her to play with me and my man </q>"; quotes[3091]="<q>so well-hung</q>"; quotes[3092]="<q>I wanna see you cum.. do a vid? </q>"; quotes[3093]="<q>wow so hot, i wanna ride you for hours</q>"; quotes[3094]="<q>can i suck you cock and swalow or share your cum with you?:-)</q>"; quotes[3095]="<q>I would like that!</q>"; quotes[3096]="<q>Thanks </q>"; quotes[3097]="<q>Would u like that? </q>"; quotes[3098]="<q>I am just plain in love with you.......all my fantasies have always been you .... just never thought the real man existed!!!!</q>"; quotes[3099]="<q>Please daddy ......I want your DNA inside me</q>"; quotes[3100]="<q>When you gonna fuck this ass and marry me? I NEED your babies inside this cunt</q>"; quotes[3101]="<q>Oh fuck yes I wanna sit on that big dick daddy</q>"; quotes[3102]="<q>i love sexy big black cock yumm!!</q>"; quotes[3103]="<q>i am now:)</q>"; quotes[3104]="<q>id love to just sit my ass down on your bbc and ride it balls deep;)</q>"; quotes[3105]="<q>mmm need some of that</q>"; quotes[3106]="<q>dayumn i want ur cum</q>"; quotes[3107]="<q>mmmm want some?</q>"; quotes[3108]="<q>Want to feel that big dick deep inside me !!</q>"; quotes[3109]="<q>Damn daddy you sexy</q>"; quotes[3110]="<q>fantastic</q>"; quotes[3111]="<q>I Wondring if i had learn more if the school had look like this.Coz i was worthless in school.</q>"; quotes[3112]="<q>I just love this image, have to try this 1 day.</q>"; quotes[3113]="<q>I love it too nothing like a girl tied up having a diddo plugging her up</q>"; quotes[3114]="<q>Yea I could play with you</q>"; quotes[3115]="<q>I'd love to suck on your nipples then make love to you nice and slow so I can feel all your pussy juice running down my cock</q>"; quotes[3116]="<q>Very nice</q>"; quotes[3117]="<q>mmmmmmmm i love that pussy sunshine</q>"; quotes[3118]="<q>MMMMMMMMMMMMM</q>"; quotes[3119]="<q>I'd love to lick that pussy and suck on those nipples</q>"; quotes[3120]="<q>wish you were here</q>"; quotes[3121]="<q>get in touch</q>"; quotes[3122]="<q>i want to lick you hard...</q>"; quotes[3123]="<q>still love this</q>"; quotes[3124]="<q>wanking</q>"; quotes[3125]="<q>want u to pic me doin it</q>"; quotes[3126]="<q>love it mmmmm</q>"; quotes[3127]="<q>check my album hun, i bet u would prefer what u see there </q>"; quotes[3128]="<q>damn hot, nice pov!</q>"; quotes[3129]="<q>love the view wish we could see it better</q>"; quotes[3130]="<q>hmmm</q>"; quotes[3131]="<q>yummy!! i want to play</q>"; quotes[3132]="<q>mm woww id loveee to helpp u out theree =]</q>"; quotes[3133]="<q>i can see play button and others.;)</q>"; quotes[3134]="<q>I like that ass.</q>"; quotes[3135]="<q>what a hot fat hairy pussy and ass to eat and fuck!</q>"; quotes[3136]="<q>Fantastic!</q>"; quotes[3137]="<q>Sexy</q>"; quotes[3138]="<q>I'm hungry for ass and pussy. I'll eat them both, them fuck'em both</q>"; quotes[3139]="<q>Fantastic!</q>"; quotes[3140]="<q>Damn bby that looks good !!</q>"; quotes[3141]="<q>I'd love to be deep inside you </q>"; quotes[3142]="<q>beautyful!</q>"; quotes[3143]="<q>I love eating hairy pussy and ass, then fucking them both</q>"; quotes[3144]="<q>love that bent over ass, want to eat that hairy pussy</q>"; quotes[3145]="<q>i like</q>"; quotes[3146]="<q>oh yeah! feed me some hairy pussy baby</q>"; quotes[3147]="<q>\u6211\u9001\u989d\u5916\u7684100\u7684\u7c73\u5229\u5347\u6765\u4f60\u4eca\u5929</q>"; quotes[3148]="<q>holy shit that's pretty!</q>"; quotes[3149]="<q>Yes please .... Let me pamper you on the beach .... Then fuck all night like animals !!! </q>"; quotes[3150]="<q>I would love to join you at the beach. ;-) What beach can I find you ? ;-D</q>"; quotes[3151]="<q>what a way to relax...waves, sand, and a beautiful girl. life is good </q>"; quotes[3152]="<q>WOW! i could look at that view all day </q>"; quotes[3153]="<q>i will the place on your towel..:)</q>"; quotes[3154]="<q>i can\u00b4t say anything different than just perfect! I love it!</q>"; quotes[3155]="<q>WAUW! I love your wonderful smile. ;-) I wish I could KISS that sweat lips of yours. ;-D</q>"; quotes[3156]="<q>guapaaaaaa!!</q>"; quotes[3157]="<q>is it possible that you get better with each photo...i think so</q>"; quotes[3158]="<q>Absolutely stunning!!!</q>"; quotes[3159]="<q>MMmm you know what I want^^</q>"; quotes[3160]="<q>Your boobs already look great and the shirts still on</q>"; quotes[3161]="<q>Whats up, lookin damn sexy</q>"; quotes[3162]="<q>Them hips aint ugly. Nice lil suckable apples on top</q>"; quotes[3163]="<q>My god, you're sexy!</q>"; quotes[3164]="<q>But do you have pretty feet</q>"; quotes[3165]="<q>Just let me know when i can see</q>"; quotes[3166]="<q>wow you are stunning babes xx</q>"; quotes[3167]="<q>Sexy you have a great body:)</q>"; quotes[3168]="<q>SEXY AS HELL</q>"; quotes[3169]="<q>perfect baby i like ur style</q>"; quotes[3170]="<q>good stufffff </q>"; quotes[3171]="<q>hot slim goody mama</q>"; quotes[3172]="<q>\</q>"; quotes[3173]="<q>Damn...that's one HOT tight little bodyLookin good baby</q>"; quotes[3174]="<q>id fuk u so good baby</q>"; quotes[3175]="<q>You're mad beautiful</q>"; quotes[3176]="<q>that one lucky nigga</q>"; quotes[3177]="<q>Well baby girl you can get on them other guys and act mean if you want to but I love Black women and you are very fine....now can I please see him do something to That or just smoke beautiful</q>"; quotes[3178]="<q>Eh..they're okay. But I will let you be the judge.;P</q>"; quotes[3179]="<q>mmm that cock looks like fun!</q>"; quotes[3180]="<q>Nice cock....</q>"; quotes[3181]="<q>Now this is a realllll fucking cock!!!! mmmm I'd love to suck that head until you came all over me and then for you to ram that fucking sexy cock deeeeep inside my wet pussy! Mmmmmmm</q>"; quotes[3182]="<q>Mmm well thank you gorgeous! I can say the same about you With that perfect ass of yours and my cock I think we could have a lot of fun!</q>"; quotes[3183]="<q>what a hot head to suck!</q>"; quotes[3184]="<q>Mmmmm I would ride that hard long cock.</q>"; quotes[3185]="<q>Mmmmmm hey baby! Be sure to cum check out all my pics and comment...mmmmmmm!</q>"; quotes[3186]="<q>Purple head is gorgeous. Love to deepthroat your cock</q>"; quotes[3187]="<q>Stroke that cock!</q>"; quotes[3188]="<q>Mm-mm-mm. </q>"; quotes[3189]="<q>You have a lovely cock! What's your snapchat?!</q>"; quotes[3190]="<q>Mind it? My god baby it's what I've been dreaming about!!!</q>"; quotes[3191]="<q>Mmm sounds perfect to me </q>"; quotes[3192]="<q>that's HOT!!!</q>"; quotes[3193]="<q>Mmm damn! That cock is amazing. I wanna just sit on it. I want every inch in me right now </q>"; quotes[3194]="<q>Oh mhm boy oh boy, holding that dick nicely. Mind if I replace your hands?</q>"; quotes[3195]="<q>Mm-mm-mm, I want to stroke and suck that beautiful cock!!!!! ;P</q>"; quotes[3196]="<q>Put Your Hot Lips Around Mines;)</q>"; quotes[3197]="<q>Vraiment pas mal!</q>"; quotes[3198]="<q>I wanna try your hot mouth... mmm</q>"; quotes[3199]="<q>WOW!! NOW THAT WHAT I CALL A HAPPY MEAL!!</q>"; quotes[3200]="<q>L'heure de se mettre \u00e0 table pour cette suculente chatte </q>"; quotes[3201]="<q>noce smile, great shot, just need a couple real cocks in your holes and mouth now while a few hard cocks wait for there turn and its just perfect</q>"; quotes[3202]="<q>nos voisins toulousains je les pens\u00e9 pas aussi nature </q>"; quotes[3203]="<q>mmm... juicy pussy!</q>"; quotes[3204]="<q>Very nice pussy, let my dick in you</q>"; quotes[3205]="<q>I would love to put my cock in your pussy!</q>"; quotes[3206]="<q>hey baby nice smile you ve got here</q>"; quotes[3207]="<q>quel belle chatte a remplir de mon sperme !</q>"; quotes[3208]="<q>jolie chatte avec un petit cul sympas </q>"; quotes[3209]="<q>yummy</q>"; quotes[3210]="<q>hummmm\u00a0 superbe chatte\u00a0</q>"; quotes[3211]="<q>very hot</q>"; quotes[3212]="<q>mmmm</q>"; quotes[3213]="<q>amazing!!! I wanna lick and suck your titts while you're doing this...</q>"; quotes[3214]="<q>Good for vitamin A</q>"; quotes[3215]="<q>what's up doc?</q>"; quotes[3216]="<q>wouaw tu as de beau gros sein</q>"; quotes[3217]="<q>love uu r so sexy</q>"; quotes[3218]="<q>hummm quel chance elle a cette carotte</q>"; quotes[3219]="<q>Une personne respectable qui aime prendre 5 fruits et legumes par jour. </q>"; quotes[3220]="<q>mmm... let me lick your clit...</q>"; quotes[3221]="<q>you are amazing.</q>"; quotes[3222]="<q>Can My BBC Be Next In Line To Slide Deep In Your Pussy?</q>"; quotes[3223]="<q>I want to be a vegetable</q>"; quotes[3224]="<q>Mmmm...I'd suck on that carrot for a week after it's been in that sexy ass of yours.</q>"; quotes[3225]="<q>Trs excitante</q>"; quotes[3226]="<q>nice... love the anal action</q>"; quotes[3227]="<q>Now thats hot.</q>"; quotes[3228]="<q>You're hot baby!!! I wanna taste your body...</q>"; quotes[3229]="<q>Wow, superbe, j'adore</q>"; quotes[3230]="<q>yeah i like that plays</q>"; quotes[3231]="<q>i would like to fuck you hard baby nice arrrrrr</q>"; quotes[3232]="<q>Quelle carotte! Je marche.</q>"; quotes[3233]="<q>hmmmm nice</q>"; quotes[3234]="<q>Mmm so gorgeous!</q>"; quotes[3235]="<q>carrots in the ass, I love it, WOW.</q>"; quotes[3236]="<q>mmmm..... ;9 kissess</q>"; quotes[3237]="<q>good idea i really like your pics</q>"; quotes[3238]="<q>Lucky Carrot</q>"; quotes[3239]="<q>i wanna put mij dick in your pussy right now</q>"; quotes[3240]="<q>hummmm\u00a0 super avec la carotte</q>"; quotes[3241]="<q>having carrot in pussy is nice. I do that almost every day </q>"; quotes[3242]="<q>OMG!!! I wanna be those carrot...</q>"; quotes[3243]="<q>C'est plein....</q>"; quotes[3244]="<q>great photo!!! love it</q>"; quotes[3245]="<q>Now I want eat the carrot with your personal sauce</q>"; quotes[3246]="<q>deeper please :-)</q>"; quotes[3247]="<q>MMMMMMMM you are making me sooo Hard;)</q>"; quotes[3248]="<q>great photo!!! love it </q>"; quotes[3249]="<q>double!!! nice picture.</q>"; quotes[3250]="<q>wow!! I like so much!!</q>"; quotes[3251]="<q>mmm very hot</q>"; quotes[3252]="<q>mmmm ur hot</q>"; quotes[3253]="<q>You're Fucking Hot & Amazing!!</q>"; quotes[3254]="<q>fruits and vegetables are good for your health. I always use fruit and vegetables this way and I love them</q>"; quotes[3255]="<q>*_____*</q>"; quotes[3256]="<q>This pix is awesome!! I wanna enjoy your cum baby</q>"; quotes[3257]="<q>Une belle grosse salope :-)</q>"; quotes[3258]="<q>can i eat the veg when you've finished?lol.xxxxxx</q>"; quotes[3259]="<q>Very capable </q>"; quotes[3260]="<q>I wich i was there..you would love it;)</q>"; quotes[3261]="<q>Dam that looks like it fits nice! Would love more of it, very sexy!</q>"; quotes[3262]="<q>il y a des jours on voudrait etre un concombre, une banane, une carotte !!!</q>"; quotes[3263]="<q>Perfect... I would like to get my cock deep in you babe</q>"; quotes[3264]="<q>Oui c'est bon pour la sant hihi</q>"; quotes[3265]="<q>yeah baby, can u take my huge cock.</q>"; quotes[3266]="<q>hummmmm j aimerais etre a la place du concombre</q>"; quotes[3267]="<q>tu es top excitente stafina</q>"; quotes[3268]="<q>mmm anal mush banana</q>"; quotes[3269]="<q>I wanna eat your cream Hun xoxxx</q>"; quotes[3270]="<q>yeah!!! tight hole... mmm</q>"; quotes[3271]="<q>i wont this banana!</q>"; quotes[3272]="<q>wow i think your ass so tight oh i love your ass for anal sex</q>"; quotes[3273]="<q>the hottest pics on hubthanks for sharing</q>"; quotes[3274]="<q>Fruits are healthy </q>"; quotes[3275]="<q>super photo, <NAME>.</q>"; quotes[3276]="<q><NAME> </q>"; quotes[3277]="<q>fucking hot</q>"; quotes[3278]="<q>getting your 5 a day wish i was one of them</q>"; quotes[3279]="<q>you should be a very healthy persson if you like vegetables and fruits so much</q>"; quotes[3280]="<q>tu me donnes la banane</q>"; quotes[3281]="<q>Very Sexy Hot Very!! Wanna Do You From Behind!!</q>"; quotes[3282]="<q>2 thumbs up plus my cock</q>"; quotes[3283]="<q>and now... please try my cock</q>"; quotes[3284]="<q>I fuck you from behind baby.</q>"; quotes[3285]="<q>laisse moi m'occuper de ton beau petit cul</q>"; quotes[3286]="<q>hummm ji planterai bien ma queue</q>"; quotes[3287]="<q>mmmmmmmmmmmmmmmmmmm wow</q>"; quotes[3288]="<q>your ass hole is waiting for my cock... kisses</q>"; quotes[3289]="<q>What a view, the way I like it.</q>"; quotes[3290]="<q>very hot ass i would love to stick my large cock up there and make you scream</q>"; quotes[3291]="<q>sexy ass</q>"; quotes[3292]="<q>Thats nice....</q>"; quotes[3293]="<q>I'm drinking one of those right now! Too fuckin' cool.</q>"; quotes[3294]="<q>What a spread! Fucking AWESOME!!!!!!!!!</q>"; quotes[3295]="<q>So sexy.... damn</q>"; quotes[3296]="<q>Thats one sexy bitch right there!</q>"; quotes[3297]="<q>Look at that lil pink asshole!</q>"; quotes[3298]="<q>Fafa pussy</q>"; quotes[3299]="<q>want u..</q>"; quotes[3300]="<q>Lots of G strings to wear.</q>"; quotes[3301]="<q>Nice edit background gas</q>"; quotes[3302]="<q>Love to be right there!</q>"; quotes[3303]="<q>FUCKING AWESOME!</q>"; quotes[3304]="<q>very sexy</q>"; quotes[3305]="<q>i would fuck the shit out of her</q>"; quotes[3306]="<q>she took more than she could handle, they will rip her apart</q>"; quotes[3307]="<q>I've been looking for stuff like this for a long time...</q>"; quotes[3308]="<q>sensual eyes!!!!</q>"; quotes[3309]="<q>well hello</q>"; quotes[3310]="<q>sexy girl</q>"; quotes[3311]="<q>Yup *TASH* u have a beautiful look Yummy ?;) U betya </q>"; quotes[3312]="<q>u r very beauitful</q>"; quotes[3313]="<q>very nice </q>"; quotes[3314]="<q>wow babey amazing</q>"; quotes[3315]="<q>damn girl </q>"; quotes[3316]="<q>sexy</q>"; quotes[3317]="<q>Do they taste as good as they look like they do</q>"; quotes[3318]="<q>great rack! my BBC should be between those beauties...</q>"; quotes[3319]="<q>super sexy</q>"; quotes[3320]="<q>Stunning... Literally. You could knock someone out with those. Beautiful picture.</q>"; quotes[3321]="<q>got me soo hard... my cock is ringing looking through this album</q>"; quotes[3322]="<q>nice</q>"; quotes[3323]="<q>sexy</q>"; quotes[3324]="<q>u r fucking gorgeous!</q>"; quotes[3325]="<q>i love your hair babe and your so pretty xxx</q>"; quotes[3326]="<q>mmm...yummy so sexy </q>"; quotes[3327]="<q>Its hard to say what I like best - the hair or the smilenice boobs by the way</q>"; quotes[3328]="<q>Your on fire!!! And you kno it</q>"; quotes[3329]="<q>Hot !</q>"; quotes[3330]="<q>sexy xxx</q>"; quotes[3331]="<q>just amazing thats all I can say about that</q>"; quotes[3332]="<q>you are pure perfection no doubt about it loving the pics you look stunning</q>"; quotes[3333]="<q>so sexy x</q>"; quotes[3334]="<q>mmm damn</q>"; quotes[3335]="<q>Sexy red head</q>"; quotes[3336]="<q>de\u00b7lec\u00b7ta\u00b7ble</q>"; quotes[3337]="<q>yummy is right!!!</q>"; quotes[3338]="<q>I love you, i mean your tits are awesome and your lovely face </q>"; quotes[3339]="<q>your hot.</q>"; quotes[3340]="<q>veryyummy!!</q>"; quotes[3341]="<q>so freaking cute!!!</q>"; quotes[3342]="<q>gorgeous</q>"; quotes[3343]="<q>nice red hair and big beautiful tits are a great combo</q>"; quotes[3344]="<q>sexy as fuck</q>"; quotes[3345]="<q>Gorgeous tits. Need to be soaked in cum tho </q>"; quotes[3346]="<q>I want to soak you with my cum from head to toe. my huge cock is ready to fuck your georgous tits.</q>"; quotes[3347]="<q>beautiful and sexy </q>"; quotes[3348]="<q>fit babes xxxx</q>"; quotes[3349]="<q>love to buy a shot of that lol</q>"; quotes[3350]="<q>i think you need a cock up your ass right away</q>"; quotes[3351]="<q>very nice shorts!!!! would love those laying next to my bed.:)</q>"; quotes[3352]="<q>i love partys!!</q>"; quotes[3353]="<q>very sexy regards</q>"; quotes[3354]="<q>can i take you in doggy</q>"; quotes[3355]="<q>those are sexy panties</q>"; quotes[3356]="<q>this sexy hot ass need my hard dick</q>"; quotes[3357]="<q>You're Both Gorgeous Sexy Hot Babes</q>"; quotes[3358]="<q>how bout a 3 sum????</q>"; quotes[3359]="<q>ooooofffftt two sexy redheads,my fella would spunk his load lol;-)</q>"; quotes[3360]="<q>do you wan't to teach you how to fuck little girl?:)</q>"; quotes[3361]="<q>O fuck yessss!</q>"; quotes[3362]="<q>horny schoolgirls mmm so hott...</q>"; quotes[3363]="<q>topshagger91</q>"; quotes[3364]="<q>i love naughty school girls </q>"; quotes[3365]="<q>mmmmmmmmmmmmmmmm</q>"; quotes[3366]="<q>Very Sexy Hot Body & Legs!! I Wish I Was That Pole </q>"; quotes[3367]="<q>Hope you know how to handle a pole </q>"; quotes[3368]="<q>LOVE IT!</q>"; quotes[3369]="<q>Love the retro/vintage look of this. Almost like an old school pinup girl really! Very good!</q>"; quotes[3370]="<q>gr8 pic babe</q>"; quotes[3371]="<q>i cummed 4 times over this pic and i love the handcufs maybe you could use them on me sometimee xxx</q>"; quotes[3372]="<q>This is a hot pic!!!! Xx</q>"; quotes[3373]="<q>LOVE!!</q>"; quotes[3374]="<q>This is one of the sexest picture's I seen on here love it !!!!</q>"; quotes[3375]="<q>i cumed just to look this</q>"; quotes[3376]="<q>you are so hot bich!!</q>"; quotes[3377]="<q>sexy!</q>"; quotes[3378]="<q>hot you look like a model</q>"; quotes[3379]="<q>amazing x</q>"; quotes[3380]="<q>wow stunner xxx</q>"; quotes[3381]="<q>hot!</q>"; quotes[3382]="<q>I Love spinning Fire, im more Staff then Poi...</q>"; quotes[3383]="<q>yo poi spinner i got some snake pois at home looking good </q>"; quotes[3384]="<q>hot and spicy</q>"; quotes[3385]="<q>i spin fire too, maybe u'd like to work my stick?</q>"; quotes[3386]="<q>would love to slide my cock in</q>"; quotes[3387]="<q>i want that ass</q>"; quotes[3388]="<q>damn!!!</q>"; quotes[3389]="<q>STAY RIGHT THERE BABE WHILE I ENJOY YOUR SWEET BOTTOM</q>"; quotes[3390]="<q>Best View ever!!!</q>"; quotes[3391]="<q>OMG!!!! beautiful ass!!!</q>"; quotes[3392]="<q>Do you like having your pussy ate from behind?I'm ready if you are...</q>"; quotes[3393]="<q>I'd like to climb up between your thighs and eat whatever you want me too</q>"; quotes[3394]="<q>WOW, what a body.</q>"; quotes[3395]="<q>perfect body hot legs</q>"; quotes[3396]="<q>thats sweet kiss</q>"; quotes[3397]="<q>Very sexy ass!</q>"; quotes[3398]="<q>Nice Fucking ass!!!! Would you like me to oil your body then maybe cream ur pussy</q>"; quotes[3399]="<q>look at that arse the thing i could do to you babe x x</q>"; quotes[3400]="<q>i'm ready 4 sum desert! </q>"; quotes[3401]="<q>what a sexy ass</q>"; quotes[3402]="<q>its fucking sexy!!!</q>"; quotes[3403]="<q>WOOOOOW is it really your ass?</q>"; quotes[3404]="<q>Mmmm Would just bury my face n' that *ARSE* </q>"; quotes[3405]="<q>ohhhhh so gooooooooood so perfect love that poseeeeeeeeeeeeeeeeeeeee really nice and very very hotttt</q>"; quotes[3406]="<q>i would love to fuck that ass</q>"; quotes[3407]="<q>WELL I WOULD'NT KICK YOU OUTTA BED FOR EATIN PRETZELS..</q>"; quotes[3408]="<q>yum x</q>"; quotes[3409]="<q>Looking sexy</q>"; quotes[3410]="<q>nice fuck ass</q>"; quotes[3411]="<q>sexy little scouse minx</q>"; quotes[3412]="<q>omg this ass makes me so harddd</q>"; quotes[3413]="<q>huuu</q>"; quotes[3414]="<q>i wanna to fuck u this like that</q>"; quotes[3415]="<q>there aint nothing i can say that hasnt already been said.. oh yeah... u wanna fuck? lol</q>"; quotes[3416]="<q>beautiful.. love the pic</q>"; quotes[3417]="<q>fantastik bodyhmmmm i love it !</q>"; quotes[3418]="<q>My my my what i would love to do to you!!! Beautiful xx</q>"; quotes[3419]="<q>love it</q>"; quotes[3420]="<q>is this you on the pic</q>"; quotes[3421]="<q>beautifullll so sexy and amazingggg loooking so great</q>"; quotes[3422]="<q>very sensual</q>"; quotes[3423]="<q>You're Gorgeous with Them Sexy Eyes & Smile</q>"; quotes[3424]="<q>mmm u r proud of those titties arent u </q>"; quotes[3425]="<q>"": "yummy", "segment": "Solo Female"}</q>"; quotes[3426]="<q>this is a face i want to fuck :*</q>"; quotes[3427]="<q>Your eyes say exactly what's on your mind honey x</q>"; quotes[3428]="<q>mezmorizing. oops something else is rizing</q>"; quotes[3429]="<q>I want you to cum breasts</q>"; quotes[3430]="<q>ohh yeah love the loooks you have on your faceeee</q>"; quotes[3431]="<q>gorgeous !</q>"; quotes[3432]="<q>id like to service u daddy</q>"; quotes[3433]="<q>Those lucky Honolulu men who get to service you! Day-um!</q>"; quotes[3434]="<q>I want to suck that cock hard!</q>"; quotes[3435]="<q>sexy and I love the hairy chest</q>"; quotes[3436]="<q>Sexy!!!</q>"; quotes[3437]="<q>SMOKIN HOT</q>"; quotes[3438]="<q>wow so sexy !!</q>"; quotes[3439]="<q>wouldn't mind climbin' yer frame mate - rip</q>"; quotes[3440]="<q>What a Sexy Guy You are = </q>"; quotes[3441]="<q>Boy would I love to throw those legs over my shoulders...</q>"; quotes[3442]="<q>Yes PLEASE!!</q>"; quotes[3443]="<q>damn yeah need a ride yeah</q>"; quotes[3444]="<q>wow!!!</q>"; quotes[3445]="<q>hottt as it is.......You are.</q>"; quotes[3446]="<q>mmm, hot!</q>"; quotes[3447]="<q>Sexy as fuck</q>"; quotes[3448]="<q>you can fuck my mouth and ass anytime.</q>"; quotes[3449]="<q>very nice man</q>"; quotes[3450]="<q>great body</q>"; quotes[3451]="<q>Sexy man...hmmm! </q>"; quotes[3452]="<q>sexy</q>"; quotes[3453]="<q>very sexy... </q>"; quotes[3454]="<q>wonderful photo, sooo hottt</q>"; quotes[3455]="<q>Your men is one of the lukiest on the world</q>"; quotes[3456]="<q>such a great body, I love it!</q>"; quotes[3457]="<q>lets fuck</q>"; quotes[3458]="<q>beautiful</q>"; quotes[3459]="<q>Perfect tits</q>"; quotes[3460]="<q>Would you let them ride you?</q>"; quotes[3461]="<q>They can test out my suspension, and try all of the gears, the gas mileage is outstanding too! Dipstick may need to be checked a few times though....</q>"; quotes[3462]="<q>you are beautiful !!</q>"; quotes[3463]="<q>We get you bigger camera lol.</q>"; quotes[3464]="<q>You are such a beautiful woman - love the profile shot</q>"; quotes[3465]="<q>Now that is a beautiful woman.</q>"; quotes[3466]="<q>beauteful baby! kisssss</q>"; quotes[3467]="<q>you are beautiful !!</q>"; quotes[3468]="<q>I would love to come behind you just like this..peel away your scarf..kiss your neck..cup your breasts and make your turn and kiss me ...hard... the rest can play out naturally... You are Beautiful..xoxo</q>"; quotes[3469]="<q>You`re very pretty, Sylvia.</q>"; quotes[3470]="<q>yummy..nice fingering you pussy..</q>"; quotes[3471]="<q>damn u stunning and sexy</q>"; quotes[3472]="<q>she is sexiest porn gal in this world...</q>"; quotes[3473]="<q>so hot</q>"; quotes[3474]="<q>that looks just right. a perfect fit for my ass.</q>"; quotes[3475]="<q>I really dig it when a girl fucks me from behind with a big thick strap-on just like in this picture. It feel so good. Im always looking for girls that are interested in using a strap-on and fuck me good. Hit me up.</q>"; quotes[3476]="<q>i want you to fuck me with your big strap-on, i need it now.</q>"; quotes[3477]="<q>10/10 would get banged</q>"; quotes[3478]="<q>I would love too be her sex slave for a year.</q>"; quotes[3479]="<q>very fucking HOT....</q>"; quotes[3480]="<q>nina tenha paciencia comigo pq ta tudo corrido pra mim tenha paciencia comigo pq quando de tempo a gente faz sexo ok eu qero qe vc fa\u00e7a os meus gosto ok miguxa quando eu chamo vc morena ok</q>"; quotes[3481]="<q>two on one thats hot.</q>"; quotes[3482]="<q>that looks so hot, i want that big strap-on in me</q>"; quotes[3483]="<q>extremely \u00a0sexy</q>"; quotes[3484]="<q>thats the big strap-on i want you to fuck me with.</q>"; quotes[3485]="<q>She is so damn hot!!</q>"; quotes[3486]="<q>as perfect as you can anonymously get -- 5 Star Amateur EASY</q>"; quotes[3487]="<q>make me suck it and then stuff it in my ass.</q>"; quotes[3488]="<q>I love her little smile. So sexy. She's enjoying making him suck her big cock.</q>"; quotes[3489]="<q>surprised theirs not cum all over the fingers of her left hand... very surprised\u00a0</q>"; quotes[3490]="<q>yum.....</q>"; quotes[3491]="<q>I love getting fuck by my girlfriend</q>"; quotes[3492]="<q>I could lick these legs & ass 4 hrs.. just warming up... 5 STARS</q>"; quotes[3493]="<q>wow that is such a nice cock and she is beautiful, i want you to fuck me with that big cock.</q>"; quotes[3494]="<q>Same</q>"; quotes[3495]="<q>I like to be watched by strangers when im getting fucked by a guy or a girl with a strap-on.</q>"; quotes[3496]="<q>GREAT OUTFIT SEXY U WEAR IT WELL</q>"; quotes[3497]="<q>wow!</q>"; quotes[3498]="<q>que delicia mamita</q>"; quotes[3499]="<q>damn baby you are thick I love thick women girl I would lick your ass if you asked me to</q>"; quotes[3500]="<q>this shit is so sexy and u so thick</q>"; quotes[3501]="<q>VERY SEXY LADY I WOULD LICK U FROM HEAD TO TOE</q>"; quotes[3502]="<q>A GODDESS!</q>"; quotes[3503]="<q>you are so please-ing to the eyes</q>"; quotes[3504]="<q>awesome picture</q>"; quotes[3505]="<q>Damn you make me so horny sexy!</q>"; quotes[3506]="<q>hot realy hot!</q>"; quotes[3507]="<q>hot realy hot!</q>"; quotes[3508]="<q>beautiful and whery sexy too </q>"; quotes[3509]="<q>That looks tasty</q>"; quotes[3510]="<q>I would lick and suck that sweet pussy real well</q>"; quotes[3511]="<q>Looks like ur ready for some dick!</q>"; quotes[3512]="<q>MMM YUMMY GREAT VEIW FROM HERE</q>"; quotes[3513]="<q>Can i dry it for you?</q>"; quotes[3514]="<q>fantastic :-)</q>"; quotes[3515]="<q>I'm going in head 1st!</q>"; quotes[3516]="<q>Want to smash my face in that pussy and make a mess!</q>"; quotes[3517]="<q>damn you sexyid love to fuck u</q>"; quotes[3518]="<q>Very sexy</q>"; quotes[3519]="<q>look like some good pussy</q>"; quotes[3520]="<q>your so fine dammmm</q>"; quotes[3521]="<q>beautiful and whery sexy too </q>"; quotes[3522]="<q>With a body like this, my cock would love to make you wet every day</q>"; quotes[3523]="<q>u r fucking hot! i would stretch that pussy!</q>"; quotes[3524]="<q>too fuckin sexy</q>"; quotes[3525]="<q>Damn baby...</q>"; quotes[3526]="<q>dam</q>"; quotes[3527]="<q>WOW SEXY</q>"; quotes[3528]="<q>i want to fuck u like now!</q>"; quotes[3529]="<q>wow................nice nice.......</q>"; quotes[3530]="<q>Ooooooo yess baby stay here like this....look my big cock is ready to fuck this beautiful pussy until your squirt!!!!!! i wanna lick your tits when i fuck and put two fingers in your ass to hear you scream a lot!!!!</q>"; quotes[3531]="<q>I....Just...Came...ahhh.</q>"; quotes[3532]="<q>mmmmm, i'd love to savor your flavor while licking and tongue-teasing your pussy and clit as i finger-fuck you in that position until i can't resist my horny urge to slide my hard cock deep into you and feel you squeeze and massage my stiff shaft while fucking you like that!</q>"; quotes[3533]="<q>:-p</q>"; quotes[3534]="<q>damn sexy,wish i could lick your pussy!</q>"; quotes[3535]="<q>ohhhh that is hot!</q>"; quotes[3536]="<q>so fine</q>"; quotes[3537]="<q>wow love your body. Great pussy</q>"; quotes[3538]="<q>Fuck you ALL</q>"; quotes[3539]="<q>wooow, that's very nice !!</q>"; quotes[3540]="<q>amazing ass</q>"; quotes[3541]="<q>i will deep fuck your sweet tight pussy my dirty whore and come on your sweet ass hole mmmmmmmmmmmmm</q>"; quotes[3542]="<q>hummmm tasty</q>"; quotes[3543]="<q>mmm you are so hot</q>"; quotes[3544]="<q>your lips look so smooth baby</q>"; quotes[3545]="<q>i need to breed you like the cock whore you are</q>"; quotes[3546]="<q>damn im in love</q>"; quotes[3547]="<q>Love how those beautiful lips bust out of your thong. Tasty</q>"; quotes[3548]="<q>Mmmm it was amazing shooting my warm thick load of black cum deep inside that white pussy last night baby My white slut was so good in bed!</q>"; quotes[3549]="<q>Your pussy peaking out is such a tease, I want to fill it with my hard cock and thick cum for u</q>"; quotes[3550]="<q>So tight and fuckable </q>"; quotes[3551]="<q>So fucking hot !!</q>"; quotes[3552]="<q>Holy shit! The things I would do.</q>"; quotes[3553]="<q>wow that ass is no joke</q>"; quotes[3554]="<q>hmmm.... I wanna be there</q>"; quotes[3555]="<q>I love you</q>"; quotes[3556]="<q>mmm i like what i see</q>"; quotes[3557]="<q>so hot!!!!!!!!!!!</q>"; quotes[3558]="<q>mmmmm let me suck you!</q>"; quotes[3559]="<q>You kill me with this position........ fantastic.....amazing......</q>"; quotes[3560]="<q>damn, you're gonna be my lifetime cumdumpster!!</q>"; quotes[3561]="<q>wanna feed thus with my cum!!</q>"; quotes[3562]="<q>damn sexy ass and lovely pussy would love to grab you by your hips and thrust my rock hard cock deep in to you giving you a good hard pounding making you scream and shake as you have an amazing orgasm</q>"; quotes[3563]="<q>great ass...</q>"; quotes[3564]="<q>Verrry nice ass</q>"; quotes[3565]="<q>i love that fat pussy lips ...mmmmmm ass made for me</q>"; quotes[3566]="<q>i would love to see you spred them bunds for me like this</q>"; quotes[3567]="<q>I love how your panties are pulled to the side exposing your hot pussan just waiting for me to lick it real well</q>"; quotes[3568]="<q>hummm love your pussy</q>"; quotes[3569]="<q>je veut me glisser dedans !!!!!!</q>"; quotes[3570]="<q>like what? </q>"; quotes[3571]="<q>luv u </q>"; quotes[3572]="<q>just slide it in... use my hole and go balls deep hun... pump your thick seed in me.....</q>"; quotes[3573]="<q>nicesty.........</q>"; quotes[3574]="<q>My favorite position to fuck.....Don't move baby.....wanna slide with my lemon head cock inside your honey hole baby;)</q>"; quotes[3575]="<q>Perfect 3</q>"; quotes[3576]="<q>Perfect !!</q>"; quotes[3577]="<q>I love how your panties are pulled to the side exposing your hot mound....it's begging for my thick lips to be all up in there</q>"; quotes[3578]="<q>amazing view</q>"; quotes[3579]="<q>I'd like to fill u with my load</q>"; quotes[3580]="<q>that ass is to die for!</q>"; quotes[3581]="<q>Damn girl would like to oil that ass and then...</q>"; quotes[3582]="<q>i would rip them off and start fucking you hard</q>"; quotes[3583]="<q>My property....only good for one thing! Taking my big hung black cock deep </q>"; quotes[3584]="<q>sexy</q>"; quotes[3585]="<q>super hot...</q>"; quotes[3586]="<q>Perfection!</q>"; quotes[3587]="<q>omg baby, let me slide in slowly and then start pounding my little cumslut hard!!</q>"; quotes[3588]="<q>I would love to pull that G string down and taste that ass and pussy...</q>"; quotes[3589]="<q>sexy boos&d</q>"; quotes[3590]="<q>This is what you need: The string pulled aside, me grabbing you by the hips and thrusting my cock in you</q>"; quotes[3591]="<q>Mm \u00a0I love this perfect sexy ass</q>"; quotes[3592]="<q>I'd like to slip down that thong! And ram my cock in your pussy! You have a really nice ass</q>"; quotes[3593]="<q>"": "Bending Over for U", "segment": "Solo Female"}</q>"; quotes[3594]="<q>your ass is amazing</q>"; quotes[3595]="<q>I'd tap dat</q>"; quotes[3596]="<q>perfect ass !</q>"; quotes[3597]="<q>White women must be breeded by black cock</q>"; quotes[3598]="<q>let me feed that monster cock with that ass baby..</q>"; quotes[3599]="<q>loving it !</q>"; quotes[3600]="<q>mmmh, lovely ass</q>"; quotes[3601]="<q>very sexy</q>"; quotes[3602]="<q>Damn I love that one!!</q>"; quotes[3603]="<q>love taste</q>"; quotes[3604]="<q>Very nice!</q>"; quotes[3605]="<q>id impregnate the fuck out of you</q>"; quotes[3606]="<q>love u mmmmmmmmmmmmmmmmmmm</q>"; quotes[3607]="<q>you are a gorgeous woman</q>"; quotes[3608]="<q>you perfect little whore...my cock is so wet for you right now</q>"; quotes[3609]="<q>juicy white ass and bent over. just how i like my women</q>"; quotes[3610]="<q>I have shot three massive loads of hot cum over this picture honey </q>"; quotes[3611]="<q>If you had even the slightest bit of grammar skills that could have been a potentially erotic comment. However as it is, it is not even close.</q>"; quotes[3612]="<q>You have a perfect body honey </q>"; quotes[3613]="<q>sexi asss, mmmm que rico</q>"; quotes[3614]="<q>You are ready for my cock aren't you?</q>"; quotes[3615]="<q>very sexy</q>"; quotes[3616]="<q>Perfect body:)</q>"; quotes[3617]="<q>What a Sexy Ass!! Yummy!!</q>"; quotes[3618]="<q>i fucking love your ass...</q>"; quotes[3619]="<q>Insert cock here! mmmm!</q>"; quotes[3620]="<q>wanna stuff you so good baby</q>"; quotes[3621]="<q>how could i resist that ass </q>"; quotes[3622]="<q>Mmmmmmmmmmmmmm\u00a0\u00a0 ...............\u00a0\u00a0 so sexy shapes who make wanna hard evil fuckin '\u00a0 you so baaaaaaaaaaaaaaaaDDDDDDDddd\u00a0 ......\u00a0\u00a0 < 3\u00a0\u00a0 ^p</q>"; quotes[3623]="<q>Damn that's a nice bubble butt </q>"; quotes[3624]="<q>bend ove hun to take my big dick ... all in that lovely .... pussy i cant wait wanna ... go so deep</q>"; quotes[3625]="<q>ohh i will lay on u and grab ur silky hair and kiss ur neck whily my dick fucking ur wet pussy non stop</q>"; quotes[3626]="<q>I wanna fuck that sexy ass so hard pumping my warm cum inside your cunt</q>"; quotes[3627]="<q>hmmmmmmmmmm</q>"; quotes[3628]="<q>i luv that feeling... getting filled</q>"; quotes[3629]="<q>mmm ram that veiny thick cockmeat in my wet pussy... wow</q>"; quotes[3630]="<q>I'd smash your breast to the bed and ram that monster deep inside your cunt and fill your pussy with peace of my hard Bulging muscles meat all over& pumping my warm cum inside your cunt until my cum flows out from your mouth baby.....xoxoxo</q>"; quotes[3631]="<q>i want to rape your pussy hard</q>"; quotes[3632]="<q>YEAHHHH</q>"; quotes[3633]="<q>mmm i wanna be there and fuck you :></q>"; quotes[3634]="<q>very sexy ass !</q>"; quotes[3635]="<q>this is the perfect position for me and you;)</q>"; quotes[3636]="<q>cute bikini </q>"; quotes[3637]="<q>:)</q>"; quotes[3638]="<q>wow thats one pretty amazing cleavage^^ sexy!</q>"; quotes[3639]="<q>beautiful!!!</q>"; quotes[3640]="<q>amazing body</q>"; quotes[3641]="<q>hooooooooooot!!!!!!!!</q>"; quotes[3642]="<q>amazing....</q>"; quotes[3643]="<q>you're cute!</q>"; quotes[3644]="<q>amazing!love that dress girl!</q>"; quotes[3645]="<q>wowww yuo are beautiful girl :-))</q>"; quotes[3646]="<q>steaming hot</q>"; quotes[3647]="<q>your boobs are PERFECT! i wish mine were so big </q>"; quotes[3648]="<q>gorgeous, u deserve to be fucked good only</q>"; quotes[3649]="<q>simply stunning A x</q>"; quotes[3650]="<q>This is extremely sexy</q>"; quotes[3651]="<q>i can't believe people are not commenting on these pics like crazy, you are soooo hot. i don't want to sound wierd but i will probably fantasize about you later. thank you for the pics and have a nice day.</q>"; quotes[3652]="<q>Wow ... very sexy </q>"; quotes[3653]="<q>lovely!!that's one hot outfit!! </q>"; quotes[3654]="<q>fantastic !!!</q>"; quotes[3655]="<q>Sexy as hell!!!</q>"; quotes[3656]="<q>Too cute!</q>"; quotes[3657]="<q>Sweet Jesus!!</q>"; quotes[3658]="<q>Babe, u r soooooooooo sexy, wot a fantastic lil body u have</q>"; quotes[3659]="<q>super sexy tight panties!</q>"; quotes[3660]="<q>are you kidding me...you are absolutely beautiful. you need to do modeling or something. no joke but one of the prettiest girls i have ever seen.</q>"; quotes[3661]="<q>perfection </q>"; quotes[3662]="<q>You have such a fucking hot body, Jes!!</q>"; quotes[3663]="<q>HoTT!</q>"; quotes[3664]="<q>thats so sexy!</q>"; quotes[3665]="<q>look at this beautiful eyes. not this eyes, the other two:DD</q>"; quotes[3666]="<q>Please tell that I'm not dreaming? </q>"; quotes[3667]="<q>Oh wow I'd fuck that thing for hours!</q>"; quotes[3668]="<q>holly peers i think</q>"; quotes[3669]="<q>omg so hot!! whats her name?</q>"; quotes[3670]="<q>Beautiful woman.</q>"; quotes[3671]="<q>she is so beautiful I could spend all my life in bed with her</q>"; quotes[3672]="<q><NAME></q>"; quotes[3673]="<q>Ready an willing in both openings !</q>"; quotes[3674]="<q>Dear diary \</q>"; quotes[3675]="<q>It looks like a real girl!</q>"; quotes[3676]="<q>You suck her balls and ill suck on that cock, ill feed you that cum you greedy cum sucking whore, but only if you beg for it and promise to drain all the cum from my balls too.</q>"; quotes[3677]="<q>I would love to hammer that pretty little asshole</q>"; quotes[3678]="<q>so sexy</q>"; quotes[3679]="<q>Deal.</q>"; quotes[3680]="<q>I'm just drooling over the thought of attacking her balls with my tongue and lips.</q>"; quotes[3681]="<q>shes fucking hot</q>"; quotes[3682]="<q>It's a shame that there is a dick instead a pussy. Asshole looks pretty delicious to lick.</q>"; quotes[3683]="<q>bitch is on fire.</q>"; quotes[3684]="<q>Gorgeous face, beautiful hair and beautiful cock.</q>"; quotes[3685]="<q>such a beautiful TR xx stunning xx</q>"; quotes[3686]="<q>gorgeous!</q>"; quotes[3687]="<q>unbelievable hot i want to brush my teeth</q>"; quotes[3688]="<q>trop bandante</q>"; quotes[3689]="<q>wish that was my cum xxxx mmmm youre sexy girl </q>"; quotes[3690]="<q>Beautiful! I wanna lick those tits clean!</q>"; quotes[3691]="<q>I think the guys could imagine something else being there! haha love it!</q>"; quotes[3692]="<q>Is that Titpaste??x</q>"; quotes[3693]="<q>aw baby ur gettin messy let me lick u clean</q>"; quotes[3694]="<q>daaaam gurl</q>"; quotes[3695]="<q>mmmmm id be happy 2 cum over ur pretty face and tits</q>"; quotes[3696]="<q>ohh u messy girl i love it</q>"; quotes[3697]="<q>sexy......hot hot hot</q>"; quotes[3698]="<q>id dribble like that too. if thats what i saw eveytime i looked in a mirror</q>"; quotes[3699]="<q>sexy</q>"; quotes[3700]="<q>yeah, u know what i like</q>"; quotes[3701]="<q>love it!</q>"; quotes[3702]="<q>fuckin great pic baby!!!</q>"; quotes[3703]="<q>you know how to BRUSH..! llol</q>"; quotes[3704]="<q>hmmmmmm naughty brushhhhh!!! </q>"; quotes[3705]="<q>you are beautiful!</q>"; quotes[3706]="<q>cutieee</q>"; quotes[3707]="<q>Guter Dog Fuck</q>"; quotes[3708]="<q>goooddd</q>"; quotes[3709]="<q>Daddy don't waste that shit .....nut all up inside me like you need to....</q>"; quotes[3710]="<q>Waaaw i love your dick!</q>"; quotes[3711]="<q>Id suck you any time any day sexyy!!</q>"; quotes[3712]="<q>Wow</q>"; quotes[3713]="<q>I would love to take it up the ass, but is obviously not gonna fit :/</q>"; quotes[3714]="<q>Today is good for me, come get a mouth full</q>"; quotes[3715]="<q>wher is dat glory hole?thats a dream come true Dayum..........</q>"; quotes[3716]="<q>Good-Lookin' Body & Great, Big,Long,Thick Dick! </q>"; quotes[3717]="<q>FUCK ME YOUR HOT</q>"; quotes[3718]="<q>I could suck that allllllllll night long and start over in the morning</q>"; quotes[3719]="<q>Damn you are hot!</q>"; quotes[3720]="<q>MY LADY SAY THAT SHE WOULD LOVE TO SEE ME SUCK THAT MONSTER,,,MAN IT BEAUTIFUL,,I HAVE TO JACK OFF JUST LOOKING AT YOUR PICS</q>"; quotes[3721]="<q>very nice</q>"; quotes[3722]="<q>mmmmmmmmmmm</q>"; quotes[3723]="<q>You are a star. WOW!! I would serve you so well just as you deserve.</q>"; quotes[3724]="<q>very hot video -- toooo bad you have to do that</q>"; quotes[3725]="<q>I know where you can put it.... Right now</q>"; quotes[3726]="<q>Oh man - I'd love to suck that down my throat, then have you fuck your load up inside my gut.</q>"; quotes[3727]="<q>Would eat every part for days!</q>"; quotes[3728]="<q>this is what i am talking about</q>"; quotes[3729]="<q>Little Red Ridin Hood Cum Sit In Daddies Lap</q>"; quotes[3730]="<q>U like that? Cum get a taste!</q>"; quotes[3731]="<q>What the fuck u waiting on, come get it</q>"; quotes[3732]="<q>;)\</q>"; quotes[3733]="<q>Hot man... Can't wait to hop on it</q>"; quotes[3734]="<q>one of the sexiest guys in the industry. body, face, and dick.</q>"; quotes[3735]="<q>Todo maravilhoso</q>"; quotes[3736]="<q>perfection</q>"; quotes[3737]="<q>Fuck yeah!</q>"; quotes[3738]="<q>I love her expression!</q>"; quotes[3739]="<q>love to eat that.</q>"; quotes[3740]="<q>Yeah, and way better than anything you'll ever get, colt45x.</q>"; quotes[3741]="<q>mmmm Your body is very sexy and yummy!</q>"; quotes[3742]="<q>Damn girl, what a body!!!</q>"; quotes[3743]="<q>nice......</q>"; quotes[3744]="<q>sexc</q>"; quotes[3745]="<q>sexy..</q>"; quotes[3746]="<q>you got a body i wanna worship and taste</q>"; quotes[3747]="<q>i'll fuck</q>"; quotes[3748]="<q>Nice tits for a cottonpicker</q>"; quotes[3749]="<q>Corps de r\u00eave</q>"; quotes[3750]="<q>hey babeyouve got the most amazing tits;)i hope you get more pics soon</q>"; quotes[3751]="<q>love 2 suck your chocolate tits</q>"; quotes[3752]="<q>Sexy body, I want a taste!</q>"; quotes[3753]="<q>beautiful and whery sexy too </q>"; quotes[3754]="<q>Damn, she's cute.</q>"; quotes[3755]="<q>nice</q>"; quotes[3756]="<q>damb you are sexy.mmmmmmm</q>"; quotes[3757]="<q>sexy</q>"; quotes[3758]="<q>Fuckin sexy as shit</q>"; quotes[3759]="<q>so hot!!</q>"; quotes[3760]="<q>WANT TO TRY SOME VANILLA I'LL MAKE IT WORTH YOUR TIME SEXY</q>"; quotes[3761]="<q>Woaaaw! Splendid!</q>"; quotes[3762]="<q>Want to lick my way down your tight belly!</q>"; quotes[3763]="<q>Mmmm wow, perfect body</q>"; quotes[3764]="<q>my fav</q>"; quotes[3765]="<q>sexc was good</q>"; quotes[3766]="<q>You are so hot Bambi</q>"; quotes[3767]="<q>How about showing us that pussy nigger?</q>"; quotes[3768]="<q>let me tast some of ur chocolate pussy</q>"; quotes[3769]="<q>Looks so good!</q>"; quotes[3770]="<q>I'd love to fuck you like that!!!</q>"; quotes[3771]="<q>love 2 hit that booty</q>"; quotes[3772]="<q>Whaouuuuuuuuuuu superbe</q>"; quotes[3773]="<q>you have a great ass</q>"; quotes[3774]="<q>let me eat ur asshole then shove my dick in there</q>"; quotes[3775]="<q>DAMN!!!! YOU A BAD BLEEP BLEEP BLEEP .....</q>"; quotes[3776]="<q>We want more</q>"; quotes[3777]="<q>yes! perfection 5 stars</q>"; quotes[3778]="<q>CUTE !!!</q>"; quotes[3779]="<q>Great breasts, in my opinion, butt, this is a pure voyeurist portrait.</q>"; quotes[3780]="<q>So sweet.</q>"; quotes[3781]="<q>anyone know who this is?</q>"; quotes[3782]="<q>Girl those breast is calling me and i will answer</q>"; quotes[3783]="<q>The nights can be cold There's a chill to ev'ry evenin' when you're all alone Don't talk anymore 'cause you know that I'll be here to keep you warm (Oh, darling keep me warm) Baby, come to me, let me put my arms around you This was meant to be and I'm oh so glad I found you Need you ev'ry day, gotta have your love around me Baby, always stay 'cause I can't go back to livin' without you Good photography that she kicks up a couple of notches!</q>"; quotes[3784]="<q>possibly dillion harper? prob not tho</q>"; quotes[3785]="<q>similar to cinti dicker</q>"; quotes[3786]="<q>Anybody know who this is?</q>"; quotes[3787]="<q>And she graduated with a 3.5 GPA and graduated with her virginity intact. One year later she was in the national enquirer as octomom2!</q>"; quotes[3788]="<q>missalice MFc</q>"; quotes[3789]="<q>who is she?</q>"; quotes[3790]="<q>I never thought of a woman disrobing as cascading until this scene! Talk about refreshing!</q>"; quotes[3791]="<q>Nice</q>"; quotes[3792]="<q>My milkshake brings all the boys to the yard, And they're like It's better than yours, Damn right it's better than yours, I can teach you, But I have to chargeI know you want it, The thing that makes me, What the guys go crazy for. They lose their minds, The way I wind, I think its time</q>"; quotes[3793]="<q>Poor photography, butt, I can see her pride! Talk about globes!</q>"; quotes[3794]="<q>similar to suzysmartz?</q>"; quotes[3795]="<q>She is very, very good at this! She doesn;t flash she perform!</q>"; quotes[3796]="<q>To me this is beautiful! She obviously loves colors and while she burned them into her skin and they are turning out superb, the fact that she purposely or subconsciously matches her art with her dressed can not be over looked and she made sure of that! As a short video it's outstanding. Just as much art and artistry as ppPORN! Maybe MORE artistic! Perfect skin for art, perfect breast for admiration! My only flaw is I can not read her facial features.</q>"; quotes[3797]="<q>Hmm, selfie or slurpy? Fair photography, butt, superb breasts!</q>"; quotes[3798]="<q>Nice breasts, butt, other than a greeting to a lover or possible lover or bitchy tease I am missing the story. Strange composition.</q>"; quotes[3799]="<q>I see this and hear <NAME> singing: 'Looking in your eyes Kind of heaven eyes Closing both my eyes Waiting for surprise To see the heaven in your eyes is not so far Cause I'm not afraid to try and go it To know the love and the beauty never known before I'll leave it up to you to show it'</q>"; quotes[3800]="<q>Nubile, chocolate, cute and fantastic body that has this distinctive essence that can be tasted, seen, heard, felt and smelling the wonders of her emerging sciences! Is tempting a equivalent sense?</q>"; quotes[3801]="<q>phukin beautiful</q>"; quotes[3802]="<q>real</q>"; quotes[3803]="<q>wow, very beautiful body and the boots make it all kinky</q>"; quotes[3804]="<q>What an awesome body Jenny!</q>"; quotes[3805]="<q>Great bum!</q>"; quotes[3806]="<q>Very sexy xxx</q>"; quotes[3807]="<q>Would love to bend you over the counter in those sexy boots!</q>"; quotes[3808]="<q>Awesome bod hun </q>"; quotes[3809]="<q>delicious body..</q>"; quotes[3810]="<q>mi ecciti ti voglio my pussy in hot for you</q>"; quotes[3811]="<q>sexy lady</q>"; quotes[3812]="<q>Super sexy bod hun </q>"; quotes[3813]="<q>very sexy</q>"; quotes[3814]="<q>nice ass!! and lovely long legs!</q>"; quotes[3815]="<q>beautiful as and body!!!!</q>"; quotes[3816]="<q>awesome bb</q>"; quotes[3817]="<q>i will suck u till u cry</q>"; quotes[3818]="<q>Thats one cute ass!!</q>"; quotes[3819]="<q>great tight body love those legs</q>"; quotes[3820]="<q>mmmmmmmm that women are very beautiful</q>"; quotes[3821]="<q>ohh babe..i want to squirt on ur sexy body!i wait ur comments in my photos and videos!kiss from ur sexy french blonde</q>"; quotes[3822]="<q>Beautiful.....</q>"; quotes[3823]="<q>You are so beautiful.</q>"; quotes[3824]="<q>sweet kisses on your lovely tiny tits and nipples</q>"; quotes[3825]="<q>awesome!</q>"; quotes[3826]="<q>Yummy, Tits are bomb!</q>"; quotes[3827]="<q>I love your tits...looks so perfect.</q>"; quotes[3828]="<q>Yummi chica </q>"; quotes[3829]="<q>perky tits lovin them</q>"; quotes[3830]="<q>mmmmmmm Your soooooo beauitful a 10 out of 10 and alot more</q>"; quotes[3831]="<q>so sexy ;]</q>"; quotes[3832]="<q>You have a amazing body</q>"; quotes[3833]="<q>Bei diesen Anblick bekomme ich einen St\u00e4nder...</q>"; quotes[3834]="<q>great ass!</q>"; quotes[3835]="<q>mmmmmmmmmm</q>"; quotes[3836]="<q>delicious !</q>"; quotes[3837]="<q>ohhh my love your ass</q>"; quotes[3838]="<q>Mmmmm, yummy!</q>"; quotes[3839]="<q>perfect</q>"; quotes[3840]="<q>knackiger hintern...</q>"; quotes[3841]="<q>That pic is awesome, love it!</q>"; quotes[3842]="<q>You have a sweet ass and those tanlines turn me on! </q>"; quotes[3843]="<q>hoooooooooooo..nasty hot ass!</q>"; quotes[3844]="<q>soooooooooooooo fucking hot</q>"; quotes[3845]="<q>The ladies of the world are lucky.</q>"; quotes[3846]="<q>love those tanlines!!:D</q>"; quotes[3847]="<q>WOW, great!</q>"; quotes[3848]="<q>You could do that split with me under it </q>"; quotes[3849]="<q>And flexible too!!</q>"; quotes[3850]="<q>dayuuuum thats a sexy ass</q>"; quotes[3851]="<q>WOW the things i would do with that!</q>"; quotes[3852]="<q>Wow-would love to get an upclose and personal look at your splits!</q>"; quotes[3853]="<q>I want you to do that while I eat you out</q>"; quotes[3854]="<q>I need to lick your sexy white ass</q>"; quotes[3855]="<q>Love the tanlines and the splits </q>"; quotes[3856]="<q>tiny ass I'd love to kiss & fuck !</q>"; quotes[3857]="<q>nice tan babe, love that ass!</q>"; quotes[3858]="<q>super sexy !!! my girl woeld love to fk you hehehe drop us a line anytime .. or comment </q>"; quotes[3859]="<q>nice flexibility, but ya gotta get a tan on that butt</q>"; quotes[3860]="<q>can you make this over my face, pls !! so hot</q>"; quotes[3861]="<q>Soo sexy!!! mmm</q>"; quotes[3862]="<q>grate!</q>"; quotes[3863]="<q>what a prefect ass</q>"; quotes[3864]="<q>wow nice ass reallt like the tan lines so sexy</q>"; quotes[3865]="<q>fuck me thats hot ;D</q>"; quotes[3866]="<q>You have a beautiful body!</q>"; quotes[3867]="<q>very sexy ass, I would love for my face to be under you..</q>"; quotes[3868]="<q>sweet ass</q>"; quotes[3869]="<q>Mmm fuck yeah</q>"; quotes[3870]="<q>Mwahhh </q>"; quotes[3871]="<q>yumm</q>"; quotes[3872]="<q>eine wundersch\u00f6ne muschi, w\u00fcrde sie gerne von hinten lecken...</q>"; quotes[3873]="<q>they are look close for me</q>"; quotes[3874]="<q>you are so sexy.... can i lick?</q>"; quotes[3875]="<q>Yummy </q>"; quotes[3876]="<q>Looks tight!</q>"; quotes[3877]="<q>mmmmmm beautiful </q>"; quotes[3878]="<q>awesome beybe.... mmmmm</q>"; quotes[3879]="<q>ooh yah i like</q>"; quotes[3880]="<q>SO HOT!!</q>"; quotes[3881]="<q>wow simply amazing. would love to lick those holes</q>"; quotes[3882]="<q>i want kiss your pussy</q>"; quotes[3883]="<q>Pussy looks delicious!!</q>"; quotes[3884]="<q>extrem hot!</q>"; quotes[3885]="<q>mmmmmmmm that women are very beautiful</q>"; quotes[3886]="<q>We thinks you have avery nice pussy.</q>"; quotes[3887]="<q>mmmm i would lick you for hours....</q>"; quotes[3888]="<q>cute pic !</q>"; quotes[3889]="<q>amazing ! i want some </q>"; quotes[3890]="<q>u said i have a nice cock well u have an amazing body and nice boobs</q>"; quotes[3891]="<q>u look wonderfull</q>"; quotes[3892]="<q>you have a great body sweetie! Would love to see more of it!!! </q>"; quotes[3893]="<q>great body</q>"; quotes[3894]="<q>Stunnin' absolutely STUNNIN'</q>"; quotes[3895]="<q>You Are amazing!!!!!!!</q>"; quotes[3896]="<q>Mmmmmmm u are very beautiful and super sexy...</q>"; quotes[3897]="<q>Hi Dione, I took your great picture to my favorites, thanks :-)Kissesxx Annette</q>"; quotes[3898]="<q>gorgeous</q>"; quotes[3899]="<q>Dam your sexy love those tits.</q>"; quotes[3900]="<q>beautiful titts!!!</q>"; quotes[3901]="<q>ummm yummy</q>"; quotes[3902]="<q>luv 'em</q>"; quotes[3903]="<q>wow nice tits... i love hairy pussies</q>"; quotes[3904]="<q>what a hot WOMEN </q>"; quotes[3905]="<q>I wanna taste those tits and pie so fuckin bad</q>"; quotes[3906]="<q>Absolutely stunning body.</q>"; quotes[3907]="<q>very sexy</q>"; quotes[3908]="<q>Nice one gorgeous!!! </q>"; quotes[3909]="<q>simply irresistible</q>"; quotes[3910]="<q>Very hot!</q>"; quotes[3911]="<q>very sexy</q>"; quotes[3912]="<q>Im luven it!!!</q>"; quotes[3913]="<q>Your beauty has silenced me</q>"; quotes[3914]="<q>OMG what horny eyes...Love ur tittis...</q>"; quotes[3915]="<q>Wonderful tits! Please let me be your friend :-) Kisses xx Annette</q>"; quotes[3916]="<q>Very beautiful tits !</q>"; quotes[3917]="<q>beautiful ;).</q>"; quotes[3918]="<q>wonderful</q>"; quotes[3919]="<q>che sguardo e che gran belle tette ciaoooo</q>"; quotes[3920]="<q>gorgeous blue eyes.</q>"; quotes[3921]="<q>Wow you have great tits !! x</q>"; quotes[3922]="<q>Sexy </q>"; quotes[3923]="<q>sexy</q>"; quotes[3924]="<q>very sexy lips, i love it.</q>"; quotes[3925]="<q>Nice eys</q>"; quotes[3926]="<q>beauty</q>"; quotes[3927]="<q>Oh yeah, you're Hot!</q>"; quotes[3928]="<q>What i can say???</q>"; quotes[3929]="<q>MAY I SUCK ON YOUR BOOBS AND LICK ON YOUR PUSSY???</q>"; quotes[3930]="<q>i love this pic its lovely</q>"; quotes[3931]="<q>Great smile, sexy body</q>"; quotes[3932]="<q>Please let me be your friend :-)Kissesxx Annette</q>"; quotes[3933]="<q>What a smile!!!!</q>"; quotes[3934]="<q>woooooooooooooowwwwww me derrito!!!!</q>"; quotes[3935]="<q>Lo que me gusta mas aparte de tu cuerpo esplendido, es tu mirada con esos ojos que creo adivinar verdes.</q>"; quotes[3936]="<q>nice smile you are very beatiful...... ciaooooooo</q>"; quotes[3937]="<q>enfin du poil ouf extra cool</q>"; quotes[3938]="<q>i love ur smile...and ur sexy body for sure!!</q>"; quotes[3939]="<q>mare de deu senyor que esta noche he de tocarme... guapissssima</q>"; quotes[3940]="<q>voc\u00e9 \u00e9 linda, e tein um lindo soriso, beijokas desde barcelona..</q>"; quotes[3941]="<q>I love your smile :-)</q>"; quotes[3942]="<q>I got a big black dick for you</q>"; quotes[3943]="<q>nice ass let me full it up with my cock and my juiices</q>"; quotes[3944]="<q>mmmm...\u00e7a donne envie de te prendre direct sans m\u00eame enlever ton jean.\u00a0 </q>"; quotes[3945]="<q>yeah</q>"; quotes[3946]="<q>let me pull baby with my teeth</q>"; quotes[3947]="<q>nice</q>"; quotes[3948]="<q>Hmm, hmm, good. Hmm, hmm, good. This is why Polita's butt is hmm, hmm good! She deserved better photography, butt, a picture of this ass under water in the dark on a moonlit night.</q>"; quotes[3949]="<q>MMMMMMMMMMMM</q>"; quotes[3950]="<q>Nice ass!!! (; come and sit on my face</q>"; quotes[3951]="<q>any cock that gets to have that ass clapping on it when you fuck it deep and hard is going to be in heaven \u00a0\u00a0\u00a0\u00a0 then fuck it slow and deep grinding deep in her with every thick inch as my hands run gently up and down between her ass teasing her</q>"; quotes[3952]="<q>sublime</q>"; quotes[3953]="<q>I love ver boobs!</q>"; quotes[3954]="<q>I'd kiss that ass baby</q>"; quotes[3955]="<q>;)</q>"; quotes[3956]="<q>Just like, that's the way I want it</q>"; quotes[3957]="<q>I want that ass!!!!</q>"; quotes[3958]="<q>5 out of 5 :-D</q>"; quotes[3959]="<q>mmm , i bet</q>"; quotes[3960]="<q>You have such a fabulous booty......I want to slide my dick between those lovely cheeks</q>"; quotes[3961]="<q>boy friends a lucky man</q>"; quotes[3962]="<q>Id love to grab you by the hips and take that ass for a ride</q>"; quotes[3963]="<q>It looks like you are sucking me while looking at that sweet ass of yours</q>"; quotes[3964]="<q>I like to be teased</q>"; quotes[3965]="<q>me to</q>"; quotes[3966]="<q>is that your brother? if it is tell him he has a grest cock</q>"; quotes[3967]="<q>yes,he is my brother. Okay...I will tell him. Do u want to feel his nice cock???</q>"; quotes[3968]="<q>ho yessssssssssssss</q>"; quotes[3969]="<q>so big wow </q>"; quotes[3970]="<q>would love to have sex with you..to suck that dick and destroy your little tight asshole</q>"; quotes[3971]="<q>wow</q>"; quotes[3972]="<q>id love to suck on that.</q>"; quotes[3973]="<q>bigerrr then my hgaaaa</q>"; quotes[3974]="<q>BIG ONE </q>"; quotes[3975]="<q>how old r u</q>"; quotes[3976]="<q>inches?</q>"; quotes[3977]="<q>DAMN!</q>"; quotes[3978]="<q>oh Daddy will. After Daddy beats your ass, you wont be able to sit for days. Your ass will be covered in welts and bruises, and every time you try to sit, you scream and remember the terrible things Daddy has done to you</q>"; quotes[3979]="<q>this is only a fraction of what Daddy can do to your ass, cum slut</q>"; quotes[3980]="<q>Do your worst </q>"; quotes[3981]="<q>Of ciourse little one, come to my lap...</q>"; quotes[3982]="<q>Someone got a punishing </q>"; quotes[3983]="<q>Fuck I'll leave my handprint on your ass cheek you naughty girl;)</q>"; quotes[3984]="<q>I would love to play with them</q>"; quotes[3985]="<q>Great pair of tits. Want to motorboat them!!!...;)</q>"; quotes[3986]="<q>nice tits</q>"; quotes[3987]="<q>Woow what a amazing tit. I would like to suck then cum all over it...</q>"; quotes[3988]="<q>Fabulous tits.</q>"; quotes[3989]="<q>I wanna massage your tits and suck on your nipples;)</q>"; quotes[3990]="<q>how much would you like my big cock between that pair of beauties </q>"; quotes[3991]="<q>great titties and nipples!</q>"; quotes[3992]="<q>hot suckable boobs</q>"; quotes[3993]="<q>Yummy babe, very sexy tits!!!</q>"; quotes[3994]="<q>nice anal play... love it</q>"; quotes[3995]="<q>tasty..ill make u squirts as many time u can take it..and than..</q>"; quotes[3996]="<q>How about you take the finger out your asshole so I can suck on it and taste your ass;)</q>"; quotes[3997]="<q>May i lick that hole???</q>"; quotes[3998]="<q>want in NOW:.</q>"; quotes[3999]="<q>My tongue so wants to tease, please and pleasure both the strawberry and the chocolate, ummm.</q>"; quotes[4000]="<q>Dreier? (:</q>"; quotes[4001]="<q>would love to be with you two sexy ladies</q>"; quotes[4002]="<q>du hast wunder sch\u00f6ne br\u00fcste :*</q>"; quotes[4003]="<q>Sehr sch\u00f6n!</q>"; quotes[4004]="<q>Very Beautiful nipple!</q>"; quotes[4005]="<q>ohhhh .... nice tits ..... I could taste them?</q>"; quotes[4006]="<q>wow sexy</q>"; quotes[4007]="<q>sexy tits I would love to suck on them then blow a huge load all over you</q>"; quotes[4008]="<q>Dich wuerde ich auch gerne mal verwoehnen. </q>"; quotes[4009]="<q>Adorable</q>"; quotes[4010]="<q>wow gorgeous!</q>"; quotes[4011]="<q>you are so beautiful, I'd like to fuck</q>"; quotes[4012]="<q>Hell Yeah baby...making me rock hard Hottie..xoxox</q>"; quotes[4013]="<q>fucking hot body</q>"; quotes[4014]="<q>echt hei\u00df! w\u00fcrde ich gerne mal meinen schwanz zwischen stecken </q>"; quotes[4015]="<q>super sexy..</q>"; quotes[4016]="<q>sehr sexy</q>"; quotes[4017]="<q>mmm so sweet i love it</q>"; quotes[4018]="<q>Hot ihr zwei S\u00fc\u00dfen geile Bodys !</q>"; quotes[4019]="<q>ihr beiden seht aber echt hei\u00df aus! </q>"; quotes[4020]="<q>beautiful fire .... mmmm</q>"; quotes[4021]="<q>Two cute latina lady's. Love it.</q>"; quotes[4022]="<q>both of you are looking very hot in yalls bra and panties would love to be there with yall</q>"; quotes[4023]="<q>great smile </q>"; quotes[4024]="<q>I know your from Germany. But i can tell your a sexy latina</q>"; quotes[4025]="<q>cute smile looking very beautiful</q>"; quotes[4026]="<q>hammer l\u00e4cheln </q>"; quotes[4027]="<q>Sehr geil</q>"; quotes[4028]="<q>sexy flittchen </q>"; quotes[4029]="<q>Best ass EVER need to bend you over and pound that ass xx</q>"; quotes[4030]="<q>..hei\u00df!</q>"; quotes[4031]="<q>perfect ass</q>"; quotes[4032]="<q>hmm... hast aber einen echt geilen po </q>"; quotes[4033]="<q>hot tight ass mmm love it baby</q>"; quotes[4034]="<q>einfach perfekt der hintern</q>"; quotes[4035]="<q>wooow </q>"; quotes[4036]="<q>mmmmmmm xxxxxx</q>"; quotes[4037]="<q>mmmm ..... very sweet</q>"; quotes[4038]="<q>i want your tongue on my hard cock baby</q>"; quotes[4039]="<q>love to fuck that hot body</q>"; quotes[4040]="<q>please arrest me... i've been a bad bad boy...</q>"; quotes[4041]="<q>kinky xx</q>"; quotes[4042]="<q>super hot ... i'm sure those cuffs could come in handy i'd like to get roughed up by you </q>"; quotes[4043]="<q>arrest me any day!</q>"; quotes[4044]="<q>there aren't words to describe you....</q>"; quotes[4045]="<q>Whoow, you look so cute! Just love your hips and flat belly! So sexy!</q>"; quotes[4046]="<q>too much for me xx</q>"; quotes[4047]="<q>Your very pretty! Good pic!</q>"; quotes[4048]="<q>Wow you look sexy</q>"; quotes[4049]="<q>i would fuck you so hard. gorgeous.</q>"; quotes[4050]="<q>wow!</q>"; quotes[4051]="<q>and the heavens send us an angel... YOU</q>"; quotes[4052]="<q>Stunning!</q>"; quotes[4053]="<q>You just look so cute and sexy... I wish I was there with you on the carpet!</q>"; quotes[4054]="<q>so sexy </q>"; quotes[4055]="<q>very sexy outfit you ok great xx</q>"; quotes[4056]="<q>so hot ... i think i have a vest that i could wear to match that </q>"; quotes[4057]="<q>PERFECT BODY!!</q>"; quotes[4058]="<q>Definitely the sexiest pic on your page!! Straight to my favourites</q>"; quotes[4059]="<q>if a sin was to be hot, beautiful and sexy, dam girl would be the devil</q>"; quotes[4060]="<q>like your legs!</q>"; quotes[4061]="<q>love this pic,,, you look sooo sexy</q>"; quotes[4062]="<q>yum x</q>"; quotes[4063]="<q>hey do you mind sending me a friend request? and you are super pretty</q>"; quotes[4064]="<q>amazzz'n</q>"; quotes[4065]="<q>mmm damn;)</q>"; quotes[4066]="<q>very hot pic hun love the attitude makes me want to fuck you right then and there in that car let me know if you ever want to chat it might be fun</q>"; quotes[4067]="<q>sexy outfitt! sexy legs!</q>"; quotes[4068]="<q>amazing, so sexy x</q>"; quotes[4069]="<q>mmm so sexy!</q>"; quotes[4070]="<q>perfect!</q>"; quotes[4071]="<q>nice pics but this is the hottest and best one</q>"; quotes[4072]="<q>so hot and sexy</q>"; quotes[4073]="<q>just made me cum</q>"; quotes[4074]="<q>You don't understand how hard this pic has just made me! I'm going to strok it lookign at you until I cum.</q>"; quotes[4075]="<q>I wish I seen you in my kitchen!!</q>"; quotes[4076]="<q>Waauaw ..</q>"; quotes[4077]="<q>This picture is so hot!</q>"; quotes[4078]="<q>we like this photo alot add it our favorites x</q>"; quotes[4079]="<q>just wow.</q>"; quotes[4080]="<q>this is your best photo!</q>"; quotes[4081]="<q>hmmm </q>"; quotes[4082]="<q>fantastic! superb!</q>"; quotes[4083]="<q>\u041e\u041d\u0410 \u041f\u0420\u0415\u041a\u0420\u0410\u0421\u041d\u0410!!!!!</q>"; quotes[4084]="<q>fantastic! superb! excellent!</q>"; quotes[4085]="<q>Nice round boobs</q>"; quotes[4086]="<q>beautiful girl and beautiful breasts...</q>"; quotes[4087]="<q>nice to be your GF </q>"; quotes[4088]="<q>Hi sexy lady!</q>"; quotes[4089]="<q>so hot and\u00a0beautiful</q>"; quotes[4090]="<q>You're so hot cutie. Come to france</q>"; quotes[4091]="<q>Uncommon real image, where a most beautiful face matches perfectly with an amazing bossom.Great, just great.</q>"; quotes[4092]="<q>YOU are so AMAZING...!! Yours LIPS look more BEAUTIFUL then your TITs.!! :* </q>"; quotes[4093]="<q>Gorgeous!</q>"; quotes[4094]="<q>Wow, you look beautiful! Gorgeous body and a cute teasing smile! xx</q>"; quotes[4095]="<q>Charming </q>"; quotes[4096]="<q>come here! I need to feel them in my hands and under my tongue!</q>"; quotes[4097]="<q>WOW! Beautiful tits! I wanna take care of them so much!</q>"; quotes[4098]="<q>amazing!!!</q>"; quotes[4099]="<q>Leka lite </q>"; quotes[4100]="<q>Absolutely stunning! I knew I loved swedish cars, but now I see yet an other reason to love Sweden! You! You look absolutely stunning, love your boobs and you have such a cute face! Gorgeous!</q>"; quotes[4101]="<q>SEXY SEXY</q>"; quotes[4102]="<q>Sjuuuukt s\u00f6t ju </q>"; quotes[4103]="<q>nice</q>"; quotes[4104]="<q>grymma br\u00f6st </q>"; quotes[4105]="<q>Do it please! 3</q>"; quotes[4106]="<q>Thank you bae! 3</q>"; quotes[4107]="<q>Thanks hun! </q>"; quotes[4108]="<q>You are! Kissings</q>"; quotes[4109]="<q>Fuck me Alicia 3</q>"; quotes[4110]="<q>Oh thank you! Kissings</q>"; quotes[4111]="<q>sexy;)</q>"; quotes[4112]="<q>Absolutely beautiful !!!</q>"; quotes[4113]="<q>Titty perfect</q>"; quotes[4114]="<q>Beauty Sweet body Honey :*</q>"; quotes[4115]="<q>love it want it you are so damn sexy</q>"; quotes[4116]="<q>Great tits,and more grat niples </q>"; quotes[4117]="<q>cute</q>"; quotes[4118]="<q>really nice body</q>"; quotes[4119]="<q>so sexy!!!</q>"; quotes[4120]="<q>angel....</q>"; quotes[4121]="<q>nice pic...</q>"; quotes[4122]="<q>Beautiful beautiful beautiful breast</q>"; quotes[4123]="<q>Very nice x</q>"; quotes[4124]="<q>nice tits</q>"; quotes[4125]="<q>perfection</q>"; quotes[4126]="<q>gorgeous, would love to ravish you </q>"; quotes[4127]="<q>fantastic breast..... kiss..</q>"; quotes[4128]="<q>hi beautyfull ladykiss from switzerland </q>"; quotes[4129]="<q>Sooo fucking nice! Would love to play with them! And lick you </q>"; quotes[4130]="<q>I Love this Pic .</q>"; quotes[4131]="<q>so cute and sexy!! love this pic </q>"; quotes[4132]="<q>So beautiful tits and a lovely smile :-)</q>"; quotes[4133]="<q>Sublime poitrine!</q>"; quotes[4134]="<q>love to feel you hot body on mine. our hard nipples pressed together as we kiss. i am soo wet for you now.</q>"; quotes[4135]="<q>very sexy hun.you make me wet</q>"; quotes[4136]="<q>this one is real.</q>"; quotes[4137]="<q>mmmm can I taste?</q>"; quotes[4138]="<q>NICE PHAT AND JUICY...I CAN MAKE THAT CLIT MAGICALLY APPEAR LOL</q>"; quotes[4139]="<q>tasty;)</q>"; quotes[4140]="<q>I'm loving this pic babygirl are there anymore ?</q>"; quotes[4141]="<q>IM HUNGRY!!!</q>"; quotes[4142]="<q>UhUmmmmmm..that l00ks g00d!!</q>"; quotes[4143]="<q>nice and wet i love 2 lick it</q>"; quotes[4144]="<q>looking real good</q>"; quotes[4145]="<q>im hungry baby</q>"; quotes[4146]="<q>I would drop this Dick in that little white pussy and make you scream for more.</q>"; quotes[4147]="<q>Wooow.. awesome!! Nice! </q>"; quotes[4148]="<q>holly crap</q>"; quotes[4149]="<q>i would stick it</q>"; quotes[4150]="<q>damn let me eat that pussy </q>"; quotes[4151]="<q>let me lick that beauty...:-)</q>"; quotes[4152]="<q>nice view!</q>"; quotes[4153]="<q>I should help clean you up~</q>"; quotes[4154]="<q>That's a wet and juicy pussy !! I'd love to help !</q>"; quotes[4155]="<q>fuck me thats so hooootttt</q>"; quotes[4156]="<q>Damn you have a sexy little pussy </q>"; quotes[4157]="<q>hmm sch\u00f6n nass das loch lecker</q>"; quotes[4158]="<q>Fuckable ass and pussy!</q>"; quotes[4159]="<q>Really nice and sexy!</q>"; quotes[4160]="<q>nice pussy</q>"; quotes[4161]="<q>ARE VERY PLEASE-ING TO THE EYE'S</q>"; quotes[4162]="<q>This had to be a lot of fun to do.</q>"; quotes[4163]="<q>so hot.</q>"; quotes[4164]="<q>You are gorgeous.</q>"; quotes[4165]="<q>haha</q>"; quotes[4166]="<q>mmm would love to do u on the edge of the bed sometime X</q>"; quotes[4167]="<q>Nice</q>"; quotes[4168]="<q>you have the most apitizing body i've seen in awhile.</q>"; quotes[4169]="<q>Perfect body! Really hot!</q>"; quotes[4170]="<q>OMG... Hot!</q>"; quotes[4171]="<q>wow</q>"; quotes[4172]="<q>DAAAM girlgotta say ur probably the most gorgeou girl i eva seen what u about link me</q>"; quotes[4173]="<q>instant fav!!!</q>"; quotes[4174]="<q>ill fuck u like that</q>"; quotes[4175]="<q>wanna eat that pussy..after u can ride on my cock</q>"; quotes[4176]="<q>let me lay down next to u</q>"; quotes[4177]="<q>love the run way!</q>"; quotes[4178]="<q>yum</q>"; quotes[4179]="<q>I want you to fuck my black dick</q>"; quotes[4180]="<q>Hahaaaaa</q>"; quotes[4181]="<q>Oh my gosh that's a perfect ass right there mmmm so hot xxx</q>"; quotes[4182]="<q>yummmm how I would eat that ass out</q>"; quotes[4183]="<q>all waiting to try some black dick so to teach those white pussies what they are meant for BBC</q>"; quotes[4184]="<q>i would fuck all 3 of yall</q>"; quotes[4185]="<q>Fuckable asss and pussys!</q>"; quotes[4186]="<q>Hot!</q>"; quotes[4187]="<q>Nice ass.I would fuck it deep Anal.</q>"; quotes[4188]="<q>lecker mall rhein wigsen</q>"; quotes[4189]="<q>Fuckable ass and pussy!</q>"; quotes[4190]="<q>my fav possiton to fuk a gurl</q>"; quotes[4191]="<q>Or licking a pussy.</q>"; quotes[4192]="<q>nice pussy...</q>"; quotes[4193]="<q>yep</q>"; quotes[4194]="<q>damn hot.</q>"; quotes[4195]="<q>Great body!!!</q>"; quotes[4196]="<q>Wonderful skin I like this persone ..Xooxo</q>"; quotes[4197]="<q>sexy</q>"; quotes[4198]="<q>rico, yo quiero comerme esa vulvita...</q>"; quotes[4199]="<q>Wonderful pose. Great looking legs.</q>"; quotes[4200]="<q>nice tits</q>"; quotes[4201]="<q>perfect body</q>"; quotes[4202]="<q>Favorite! Thx!</q>"; quotes[4203]="<q>so hot! wow...</q>"; quotes[4204]="<q>sweet</q>"; quotes[4205]="<q>Nice skinny babe</q>"; quotes[4206]="<q>omg thats beautiful would love to stroke my cock in that sweet pussy</q>"; quotes[4207]="<q>hot...i love natural pussy...and she looks like she can ride all night long...is she asian</q>"; quotes[4208]="<q>i love that pussy</q>"; quotes[4209]="<q>so sexy!</q>"; quotes[4210]="<q>Ass licked ! </q>"; quotes[4211]="<q>ca donne envi ca . . .</q>"; quotes[4212]="<q>hum sexy</q>"; quotes[4213]="<q>tre chaaaaaaaaaaaud</q>"; quotes[4214]="<q>Love it !</q>"; quotes[4215]="<q>nice pussy</q>"; quotes[4216]="<q>hum, je passerai bien ma langue par la </q>"; quotes[4217]="<q>mmmh plein d'id\u00e9e ^^</q>"; quotes[4218]="<q>fuckable ass and pussy!</q>"; quotes[4219]="<q>this pussy gets fucked by black dicks for sure</q>"; quotes[4220]="<q>nice ass and pussy girl sexy</q>"; quotes[4221]="<q>boy i'd kneel down there and dangle my cock in her mouth while it feast on pussy</q>"; quotes[4222]="<q>Perfect fuckable this position ass and pussy yeahh!</q>"; quotes[4223]="<q>Ready to be tapped 'n slapped!</q>"; quotes[4224]="<q>I love to see little white pussies like this stretched around My Black Cock teaching them to worship Black Dick</q>"; quotes[4225]="<q>beautiful view...:-)</q>"; quotes[4226]="<q>Fuckable ass and pussy!</q>"; quotes[4227]="<q>great.</q>"; quotes[4228]="<q>fantasstic</q>"; quotes[4229]="<q>mmmmmm love to put my dick in your ass</q>"; quotes[4230]="<q>Family Guy!</q>"; quotes[4231]="<q>Pretty much want to slowly slide my long thick cock into this girl while watching an episode of Family Guy and share a joint. I'd paint her arched back with a big hot load when the credits roll.</q>"; quotes[4232]="<q>pretty hot</q>"; quotes[4233]="<q>Nice!</q>"; quotes[4234]="<q>blaze it</q>"; quotes[4235]="<q>Puff Puff Pass Lick</q>"; quotes[4236]="<q>Love those boots and pussy perfect match</q>"; quotes[4237]="<q>a beautiful naked girl and weed? it dont get much better than that</q>"; quotes[4238]="<q>fucking sexy</q>"; quotes[4239]="<q>wow xxx gorgeous bod</q>"; quotes[4240]="<q>I love women</q>"; quotes[4241]="<q>That is one hot arse. I wonder if she'll fuck a shemale...</q>"; quotes[4242]="<q>Fuck me she is stunning love those lips</q>"; quotes[4243]="<q>Fuckable ass and pussy!</q>"; quotes[4244]="<q>id fuck that nice and hard</q>"; quotes[4245]="<q>damn i wanna be next to you can i lets party naked</q>"; quotes[4246]="<q>Fuckable ass and pussy!</q>"; quotes[4247]="<q>o ya o ya Hot</q>"; quotes[4248]="<q>Fuckable ass and pussy!</q>"; quotes[4249]="<q>The photography is flawed thus poor, butt, her gifts sure make up for ANY and all flaws. !</q>"; quotes[4250]="<q>AMAZING!</q>"; quotes[4251]="<q>The photography is slightly dark, butt, the revelation is this woman's name must be adrenaline And damn she's smooth! I know, I know she's had years of practice. !</q>"; quotes[4252]="<q>She's such a hot!</q>"; quotes[4253]="<q>love your Wife:)</q>"; quotes[4254]="<q>You should be a model! Just an absolutely perfect body!</q>"; quotes[4255]="<q>name?</q>"; quotes[4256]="<q>How do you keep it the road with that in the mirror?</q>"; quotes[4257]="<q>beatyful girl</q>"; quotes[4258]="<q>fantastic woman</q>"; quotes[4259]="<q>OMG!</q>"; quotes[4260]="<q>nice feet</q>"; quotes[4261]="<q>Very sexy, in a moving vehicle on a highway with another car behind you. So naughty.</q>"; quotes[4262]="<q>BEAUTIFUL!! THE THINGS I WOULD DO TO YOU!! MMMM</q>"; quotes[4263]="<q>I want to lick your hot pussy</q>"; quotes[4264]="<q>mmmmmm extra</q>"; quotes[4265]="<q>Nice</q>"; quotes[4266]="<q>woooooow beautiful pussy</q>"; quotes[4267]="<q>Gorgeous...xoxo</q>"; quotes[4268]="<q>I want to lick your hot pussy</q>"; quotes[4269]="<q>perfect for mi cock!</q>"; quotes[4270]="<q>I bet thats sum good puddy!</q>"; quotes[4271]="<q>She is so hot!</q>"; quotes[4272]="<q>gorgeous</q>"; quotes[4273]="<q>lil bubble butt</q>"; quotes[4274]="<q>nice view..</q>"; quotes[4275]="<q>you are really hot baby !!</q>"; quotes[4276]="<q>sweet little shape you have xx</q>"; quotes[4277]="<q>i can feel u::::!:)</q>"; quotes[4278]="<q>favorite</q>"; quotes[4279]="<q>YUM</q>"; quotes[4280]="<q>sexy lil thing u r...x</q>"; quotes[4281]="<q>wow, amazing eyes, i love them.</q>"; quotes[4282]="<q>damn</q>"; quotes[4283]="<q>So pretty!!</q>"; quotes[4284]="<q>Absolutely gorgeous.</q>"; quotes[4285]="<q>soo sexy face </q>"; quotes[4286]="<q>ohh add me babe!i want to squirt on ur young and sexy face!and give me sexy comments,i love it!kiss from ur sexy french blonde</q>"; quotes[4287]="<q>sei una stella caduta dal cielo...</q>"; quotes[4288]="<q>bellissima</q>"; quotes[4289]="<q>q hermosa eres me encantan tus ojos</q>"; quotes[4290]="<q>bella e porca...... sei fantastica</q>"; quotes[4291]="<q>Very sexy!! </q>"; quotes[4292]="<q>thats hot!</q>"; quotes[4293]="<q>Hi</q>"; quotes[4294]="<q>Sei proprio una bambola..vorrei vedere le tue foto private...\u00e8 un peccato ti piacciano solo le ragazze baci dalla Sicilia </q>"; quotes[4295]="<q>damm is that all for me</q>"; quotes[4296]="<q>really hot, perfect.</q>"; quotes[4297]="<q>very pretty</q>"; quotes[4298]="<q>perfect..</q>"; quotes[4299]="<q>tutta da scopare</q>"; quotes[4300]="<q>lovely</q>"; quotes[4301]="<q>verry nice</q>"; quotes[4302]="<q>yeahhh! FRENCH FAN!!! i dream... bisous! kiss from france!</q>"; quotes[4303]="<q>kiss babe,i love ur sexy body..i want to squirt on you as my sexy video when i squirt a lot!i wait ur comments in my photos and videos!kiss from ur sexy french blonde</q>"; quotes[4304]="<q>gorgeous!!!</q>"; quotes[4305]="<q>You are fucking HOT!!! </q>"; quotes[4306]="<q>thats a real WOMAN...luv this pic it's really hot :-*</q>"; quotes[4307]="<q>so sexyh *_* i love :$</q>"; quotes[4308]="<q>YUMMMMMMY....</q>"; quotes[4309]="<q>i know what u likyessss u are soo sexy girl!:)</q>"; quotes[4310]="<q>love itkiss</q>"; quotes[4311]="<q>sexy!</q>"; quotes[4312]="<q>You are totally hot in pink.My favoutite colour</q>"; quotes[4313]="<q>damn!</q>"; quotes[4314]="<q>damn... perfect body.</q>"; quotes[4315]="<q>sexy ma belle</q>"; quotes[4316]="<q>wow your cute,love to bed you with my fella filming.</q>"; quotes[4317]="<q>omg your sexy</q>"; quotes[4318]="<q>soo hot</q>"; quotes[4319]="<q>:)</q>"; quotes[4320]="<q>i want to lick and hard fuck...</q>"; quotes[4321]="<q>You are sexy!!!!</q>"; quotes[4322]="<q>mmhm beautiful body, i love everything about it!</q>"; quotes[4323]="<q>pretty hot!</q>"; quotes[4324]="<q>pretty hot body baby!</q>"; quotes[4325]="<q>Very fuckable!!!</q>"; quotes[4326]="<q>wow baby you are perfect!!!i waaant you !!</q>"; quotes[4327]="<q>bellaa )</q>"; quotes[4328]="<q>OMG!!!!!!u r sooooo f n hot,marry me!lol</q>"; quotes[4329]="<q>yummy</q>"; quotes[4330]="<q>wow super sexy bod</q>"; quotes[4331]="<q>your absolutely gorgeous!</q>"; quotes[4332]="<q>waw sexy how are you</q>"; quotes[4333]="<q>cutee</q>"; quotes[4334]="<q>mamma mia che ficona</q>"; quotes[4335]="<q>mmmm mi piacciono le bionde e tu sei proprio da scopare in modo violento. Contattami se ti va ;*</q>"; quotes[4336]="<q>u are actully perfect</q>"; quotes[4337]="<q>You are a hot!</q>"; quotes[4338]="<q>i can only say the same. i love ur face.</q>"; quotes[4339]="<q>stunning:-)</q>"; quotes[4340]="<q>you look like an angel</q>"; quotes[4341]="<q>mmm nice</q>"; quotes[4342]="<q>hot boobs !!!</q>"; quotes[4343]="<q>\</q>"; quotes[4344]="<q>beautiful soft pussy</q>"; quotes[4345]="<q>Gorgeous</q>"; quotes[4346]="<q>Licking good</q>"; quotes[4347]="<q>sexy ass! so hard just thinking of what I would do to that ass!!!</q>"; quotes[4348]="<q>mmmmmmmmm..............yummy</q>"; quotes[4349]="<q>wow that is a very tight sexy pussy mmm I would love to munch on it and slide my hard cock into it yummy oh that would feel so amazing</q>"; quotes[4350]="<q>super yummy</q>"; quotes[4351]="<q>thats a nice ass</q>"; quotes[4352]="<q>she is INTENT on draining those balls!</q>"; quotes[4353]="<q>wow!</q>"; quotes[4354]="<q>PAWG</q>"; quotes[4355]="<q>PAWG</q>"; quotes[4356]="<q>this is all kinds of sexy, bad ass face body and def ass..... wish I knew who this was damn</q>"; quotes[4357]="<q>Now that's a azz!!!!</q>"; quotes[4358]="<q>hot ass</q>"; quotes[4359]="<q>damn</q>"; quotes[4360]="<q>dame</q>"; quotes[4361]="<q>She looks like such a white trash slut!</q>"; quotes[4362]="<q>10/10 so beautiful</q>"; quotes[4363]="<q>I give her a 10 a fucking 10</q>"; quotes[4364]="<q>nice ass!!! :-*</q>"; quotes[4365]="<q>killer ass and face...</q>"; quotes[4366]="<q>nice ass lick</q>"; quotes[4367]="<q>Let me tag in with that bloke there, he might be onto something good.</q>"; quotes[4368]="<q>damn sexy i wanna give it to u badly</q>"; quotes[4369]="<q>lucky man!!!!</q>"; quotes[4370]="<q>wow your hot as fuck!! i would eat that pussy so quick ! </q>"; quotes[4371]="<q>NICE TWATT LOKKS PHAT N JUICY</q>"; quotes[4372]="<q>love it</q>"; quotes[4373]="<q>IM IN LOVE</q>"; quotes[4374]="<q>u have a nice look</q>"; quotes[4375]="<q>Sorry ,but: Looks like 'Emo'... not Goth...</q>"; quotes[4376]="<q>why hello there </q>"; quotes[4377]="<q>it doesn't matter wheter it looks emo or goth... the point is she looks really cute..</q>"; quotes[4378]="<q>love the gloves babe!</q>"; quotes[4379]="<q>nice pic!</q>"; quotes[4380]="<q>i agree love the gloves!</q>"; quotes[4381]="<q>i agree more like an emo hot topic girl than a gothic girl but tomato, toe-mauto whatever floats you boat</q>"; quotes[4382]="<q>Perfect-Ass (stay right there)</q>"; quotes[4383]="<q>fuck me baby xoxoxoxo</q>"; quotes[4384]="<q>lovely</q>"; quotes[4385]="<q>good looking women highly advanced very beautiful gift</q>"; quotes[4386]="<q>grrr hot baby</q>"; quotes[4387]="<q>Very pretty!</q>"; quotes[4388]="<q>love to lick that pussy </q>"; quotes[4389]="<q>both of those holes are screaming for my throbbing cock </q>"; quotes[4390]="<q>Let me lick both those holes...</q>"; quotes[4391]="<q>suck it</q>"; quotes[4392]="<q>spread that big ass so we can lick it and fuck it</q>"; quotes[4393]="<q>I wanna lick your wet pussy</q>"; quotes[4394]="<q>These pink holes are so tempting !</q>"; quotes[4395]="<q>awesome ass hole to deep penetrate</q>"; quotes[4396]="<q>perfection</q>"; quotes[4397]="<q>era uma noite bemm passada.</q>"; quotes[4398]="<q>Mmmmmm I want both yummy holes I'd love to pound that pussy</q>"; quotes[4399]="<q>stay right there!</q>"; quotes[4400]="<q>Now that is a work of art\u00a0</q>"; quotes[4401]="<q>you've got holes to die for baby</q>"; quotes[4402]="<q>Where abouts in SAI'm from there too</q>"; quotes[4403]="<q>Would love to fuck both your tight holes..</q>"; quotes[4404]="<q>wow! to invite cock inside :-P</q>"; quotes[4405]="<q>woooww !! the helll</q>"; quotes[4406]="<q>your holes are absolutely perfect. i would love to be inside those</q>"; quotes[4407]="<q>Look so nice making me so hard</q>"; quotes[4408]="<q>fuck here is a very nice well worked pussy and arse hole, babe you just fucking love it , fill you up both holes wanting to have hot hard cock , over and over till you drip cum</q>"; quotes[4409]="<q>horny asshole...;)</q>"; quotes[4410]="<q>va bene dentro</q>"; quotes[4411]="<q>Wow, it's just what I wanted.</q>"; quotes[4412]="<q>The perfect slut.</q>"; quotes[4413]="<q>I'm jealous!</q>"; quotes[4414]="<q>Are you watching</q>"; quotes[4415]="<q>QA Inspections.</q>"; quotes[4416]="<q>Week ends can be slow.</q>"; quotes[4417]="<q>Pretty girl looking good...</q>"; quotes[4418]="<q>Wow, what is her name?</q>"; quotes[4419]="<q>No idea..</q>"; quotes[4420]="<q>A very good girl. ..omg I'm horny for her..</q>"; quotes[4421]="<q>good pic</q>"; quotes[4422]="<q>Mistress knows how to handle cocks.</q>"; quotes[4423]="<q>Tight and hot grip.</q>"; quotes[4424]="<q>Nice shoot</q>"; quotes[4425]="<q>Nicely dropped load.</q>"; quotes[4426]="<q>Amazing titfuck.</q>"; quotes[4427]="<q>Big load</q>"; quotes[4428]="<q>Love that cum shot into a gaping asshole</q>"; quotes[4429]="<q>Purple cock!</q>"; quotes[4430]="<q>thats bad ass shootin there</q>"; quotes[4431]="<q>Bent over and ready to take it sexy slut</q>"; quotes[4432]="<q>So so sexy</q>"; quotes[4433]="<q>Sexy pussy</q>"; quotes[4434]="<q>wwhat a tease... sooooo sexy!!</q>"; quotes[4435]="<q>i would like to be that pillow!! u look very sexy!!!</q>"; quotes[4436]="<q>I gotta start w/ those gorgeous blue eyes...titties look great from here too</q>"; quotes[4437]="<q>wow yes please,great pic.</q>"; quotes[4438]="<q>such pretty eyes</q>"; quotes[4439]="<q>your eyes are incredibly blue!</q>"; quotes[4440]="<q>what a nice pic for a tribute...</q>"; quotes[4441]="<q>Good to see a different angle : ).. you are stunning.</q>"; quotes[4442]="<q>super hawt!!!</q>"; quotes[4443]="<q>new fav pic </q>"; quotes[4444]="<q>sexy</q>"; quotes[4445]="<q>nice shoes </q>"; quotes[4446]="<q>you are fucking stunning... i want you</q>"; quotes[4447]="<q>lovely view</q>"; quotes[4448]="<q>Wow, speechless.Your eyes and lips are amazing!</q>"; quotes[4449]="<q>Kissxxx Annette :*</q>"; quotes[4450]="<q>wow stunning</q>"; quotes[4451]="<q>I'm going to print this out and cum all over her</q>"; quotes[4452]="<q>lol at the comment below but god dam girl you are sexy and this pic has just made me fuckin horny </q>"; quotes[4453]="<q>this pic makes me want to pounce on you</q>"; quotes[4454]="<q>love it all:those lipsthose eyesso dimple (lower back)the under-boob</q>"; quotes[4455]="<q>wow, sexy or what!</q>"; quotes[4456]="<q>i just cummed babe</q>"; quotes[4457]="<q>wow even have the fit dimple in your back! very nice huni </q>"; quotes[4458]="<q>i want you</q>"; quotes[4459]="<q>Wow. just, wow!</q>"; quotes[4460]="<q>Thats fucking HOT!!!!</q>"; quotes[4461]="<q>Wonderful</q>"; quotes[4462]="<q>it's Captain Sav A Bro....</q>"; quotes[4463]="<q>very sexy! love the innocent yet devilish look in your eyes</q>"; quotes[4464]="<q>sexy sexy</q>"; quotes[4465]="<q>wow..mayu..i luv japanese girls.... i really wannna go usa to see u...lol...`</q>"; quotes[4466]="<q>Nice pic cute legs.</q>"; quotes[4467]="<q>Oh babe i wanna lay next to you.</q>"; quotes[4468]="<q>beautiful and your body is to die for</q>"; quotes[4469]="<q>nice pic and u looks amazing honey</q>"; quotes[4470]="<q>sexy babe all alone in american samoa</q>"; quotes[4471]="<q>Sexy legs and great pose...Id love to feel those legs</q>"; quotes[4472]="<q>CUTIE!!!!!!!!!</q>"; quotes[4473]="<q>Champion!!!!!!!!!!!!!!!</q>"; quotes[4474]="<q>Very cute ready for your fish kiss? lol</q>"; quotes[4475]="<q>beautiful and sexy</q>"; quotes[4476]="<q>kisses hun</q>"; quotes[4477]="<q>Nice body.</q>"; quotes[4478]="<q>Hmmm, very pretty in pink.</q>"; quotes[4479]="<q>fit</q>"; quotes[4480]="<q>Smoking body</q>"; quotes[4481]="<q>love the cheeky nipple very sexy!</q>"; quotes[4482]="<q>I'd suck on that ;p</q>"; quotes[4483]="<q>Very nice tits! </q>"; quotes[4484]="<q>wow..nice tits !!!</q>"; quotes[4485]="<q>so hot ;-)</q>"; quotes[4486]="<q>beautiful cleavage...I'd love to let my tongue flicker over your sweet little nipple, to circle around it with my fingers</q>"; quotes[4487]="<q>very sexy</q>"; quotes[4488]="<q>such a beauty with sweet tits</q>"; quotes[4489]="<q>love 2 lick that nipple.</q>"; quotes[4490]="<q>Ohh I love the nipple slip</q>"; quotes[4491]="<q>wow again .. very nice</q>"; quotes[4492]="<q>wonderful</q>"; quotes[4493]="<q>very sensual and seductive, wow </q>"; quotes[4494]="<q>lovely boobs</q>"; quotes[4495]="<q>i want to sperm your tits</q>"; quotes[4496]="<q>very hot !!!</q>"; quotes[4497]="<q>Beautiful tits, can I get my teeth on that nipple baby?</q>"; quotes[4498]="<q>I would love to see more of that beautiful body.</q>"; quotes[4499]="<q>that picture is awesome its goint to my favorites allready lol</q>"; quotes[4500]="<q>dass will ich auch</q>"; quotes[4501]="<q>omg i love it</q>"; quotes[4502]="<q>l gro .. tro ...</q>"; quotes[4503]="<q>auf kopftuch wichsen</q>"; quotes[4504]="<q>das ist god</q>"; quotes[4505]="<q>hat grosse bite</q>"; quotes[4506]="<q>Joli petit cul </q>"; quotes[4507]="<q>Une fess\u00e9 </q>"; quotes[4508]="<q>joli cul salope</q>"; quotes[4509]="<q>Quel cul ! \u00c7a donne envie ..</q>"; quotes[4510]="<q>skayp= rida nasiri</q>"; quotes[4511]="<q>i love tris dick mmmmm</q>"; quotes[4512]="<q>yummy</q>"; quotes[4513]="<q>i hope i can fuck his cock...anytime n anywhere....</q>"; quotes[4514]="<q>his face is very similar with my classmates in junior high school</q>"; quotes[4515]="<q>I like this pic because he looks very submissive and hot...</q>"; quotes[4516]="<q>nice body</q>"; quotes[4517]="<q>Nice cute juicy pussy! Want to lick it.</q>"; quotes[4518]="<q>killer pic!</q>"; quotes[4519]="<q>Superstar!</q>"; quotes[4520]="<q>She's beautiful!</q>"; quotes[4521]="<q>Love it</q>"; quotes[4522]="<q>Nearly Perfect</q>"; quotes[4523]="<q>great stuff!</q>"; quotes[4524]="<q>Very nice</q>"; quotes[4525]="<q>Stunning pic!</q>"; quotes[4526]="<q>great body</q>"; quotes[4527]="<q>Cute little pussy</q>"; quotes[4528]="<q>tight body!</q>"; quotes[4529]="<q>i like</q>"; quotes[4530]="<q>cute!</q>"; quotes[4531]="<q>OMG, what a load of cum, next time spray your cum into my face</q>"; quotes[4532]="<q>man whats up there :-)</q>"; quotes[4533]="<q>Sweet...</q>"; quotes[4534]="<q>let ME help clean UP!</q>"; quotes[4535]="<q>Fuuucckk! that makes mr really horny!</q>"; quotes[4536]="<q>U MAKE ME WET</q>"; quotes[4537]="<q>mmm i wanna lick it off</q>"; quotes[4538]="<q>lol..excessive..lol</q>"; quotes[4539]="<q>damn thats beautiful</q>"; quotes[4540]="<q>lots and lots of cum</q>"; quotes[4541]="<q>i would feast on that thick nut. simply beatiful</q>"; quotes[4542]="<q>that looks good</q>"; quotes[4543]="<q>wow, so many cum, i like that!</q>"; quotes[4544]="<q>holly shit!! thats an amazing pic ::giggles:: I LOVE IT!!!</q>"; quotes[4545]="<q>awesome pic 5 stars (L)</q>"; quotes[4546]="<q>uuuuu i would love to ride that</q>"; quotes[4547]="<q>NICE DICK.LET ME SUCK IT</q>"; quotes[4548]="<q>I'd luv to put that in my mouth!!</q>"; quotes[4549]="<q>now that scarey</q>"; quotes[4550]="<q>uwwwwwwwwwwww i wouldnt mind sitin on that</q>"; quotes[4551]="<q>fuck me papi</q>"; quotes[4552]="<q>who wouldnt like that?</q>"; quotes[4553]="<q>hello!</q>"; quotes[4554]="<q>yes yes yes</q>"; quotes[4555]="<q>wow</q>"; quotes[4556]="<q>You are sexy :></q>"; quotes[4557]="<q>you can read minds too?</q>"; quotes[4558]="<q>i'd just make love to you </q>"; quotes[4559]="<q>very damn sexy</q>"; quotes[4560]="<q>great tits</q>"; quotes[4561]="<q>mmm love ur breasts hun, ur nipples n areolas, ur eyes ur lips.........mmmmmmmm</q>"; quotes[4562]="<q>yes I do</q>"; quotes[4563]="<q>that's the \</q>"; quotes[4564]="<q>U Sexy Lil Hottie</q>"; quotes[4565]="<q>leave the light on for me</q>"; quotes[4566]="<q>AMAZING BODY.....YOU LOOK LIKE AN ANGEL!!!! I CAN GROW UP YOUR BODY AND PUT MY COCK IN YOUR PUSSY UNTIL YOU ARE SO COMPLETE WET!!!!</q>"; quotes[4567]="<q>You guys are funny! No Tibe!It's not me, lol just another lady friend. I'm in the profile pic.</q>"; quotes[4568]="<q>im on my way</q>"; quotes[4569]="<q>irresistably hot!</q>"; quotes[4570]="<q>wow, i hope this is you, this is breathtaking</q>"; quotes[4571]="<q>let me know where and I will get you</q>"; quotes[4572]="<q>deserve a good pounding and i'll rather u cum all over the room first</q>"; quotes[4573]="<q>added your pic to my favourites babe </q>"; quotes[4574]="<q>anytime u ready</q>"; quotes[4575]="<q>Nice tits</q>"; quotes[4576]="<q>ok i will hehe i will send to later</q>"; quotes[4577]="<q>I would fuck the shit out of that.</q>"; quotes[4578]="<q>tr\u00e9s belle !!</q>"; quotes[4579]="<q>yes maam</q>"; quotes[4580]="<q>suck on ur lips n lick our way down.......</q>"; quotes[4581]="<q>damn, just fucking gorgeous</q>"; quotes[4582]="<q>que ricas tentaciones mami</q>"; quotes[4583]="<q>what perfect tits and huge nipples... would make sure to cum on her everyday</q>"; quotes[4584]="<q>mmm would love to shood a massive load all over your hot tits </q>"; quotes[4585]="<q>nice!!!</q>"; quotes[4586]="<q>8==========================B</q>"; quotes[4587]="<q>sexy</q>"; quotes[4588]="<q>so damn sexy</q>"; quotes[4589]="<q>you are sexy </q>"; quotes[4590]="<q>Perfect beautiful ass !!! Work !!</q>"; quotes[4591]="<q>damn girl...beautiful pic</q>"; quotes[4592]="<q>So Sexy All About That Azz</q>"; quotes[4593]="<q>While you hold that chair tight I will drive my cock in an out of that fine Phatt ass going deep in your rectum filling your rectum with my cock pumping my hot cum up your asshole ! xoxo's ;0</q>"; quotes[4594]="<q>i want to lick and hard fuck...</q>"; quotes[4595]="<q>MMMMMM that looks good. I want to bite your ass.</q>"; quotes[4596]="<q>yes momma yes</q>"; quotes[4597]="<q>YOU CAN SIT ON MY FACE JUST LIKE THAT</q>"; quotes[4598]="<q>Smoking Hot\</q>"; quotes[4599]="<q>all u need to do now is replace the chair with me</q>"; quotes[4600]="<q>let me get behind ya</q>"; quotes[4601]="<q>so sexy doesnt come close to you babe</q>"; quotes[4602]="<q>stay just like that....i got u </q>"; quotes[4603]="<q>im up</q>"; quotes[4604]="<q>Bounce on the bed an bounce some cock in your ass ! xoxo's </q>"; quotes[4605]="<q>i'd cum on your booty ass </q>"; quotes[4606]="<q>wow!</q>"; quotes[4607]="<q>damn girl.. that shits fuckin sexy</q>"; quotes[4608]="<q>thats just the way i like it</q>"; quotes[4609]="<q>With No problem!!!</q>"; quotes[4610]="<q>DAYUM...</q>"; quotes[4611]="<q>Hold on as I shove my cock up between those fine tight buns into your tight butthole driving for your stomach balls slapping your pussy ! xoxo's </q>"; quotes[4612]="<q>mmmmmmmm</q>"; quotes[4613]="<q>I WANNA CUM IN THAT NICE BLACK ASS</q>"; quotes[4614]="<q>real nice</q>"; quotes[4615]="<q>mmmm that's the way i love it </q>"; quotes[4616]="<q>Love the art on top of art!</q>"; quotes[4617]="<q>que deliciosa cola tienes mamita darte unas palmadas</q>"; quotes[4618]="<q></q>"; quotes[4619]="<q></q>"; quotes[4620]="<q></q>"; quotes[4621]="<q></q>"; quotes[4622]="<q></q>"; quotes[4623]="<q></q>"; quotes[4624]="<q></q>"; quotes[4625]="<q></q>"; quotes[4626]="<q></q>"; quotes[4627]="<q></q>"; quotes[4628]="<q></q>"; quotes[4629]="<q></q>"; quotes[4630]="<q></q>"; quotes[4631]="<q></q>"; quotes[4632]="<q></q>"; quotes[4633]="<q></q>"; quotes[4634]="<q></q>"; quotes[4635]="<q></q>"; quotes[4636]="<q></q>"; quotes[4637]="<q></q>"; quotes[4638]="<q></q>"; quotes[4639]="<q></q>"; quotes[4640]="<q></q>"; quotes[4641]="<q></q>"; quotes[4642]="<q></q>"; quotes[4643]="<q></q>"; quotes[4644]="<q></q>"; quotes[4645]="<q></q>"; quotes[4646]="<q></q>"; quotes[4647]="<q></q>"; quotes[4648]="<q></q>"; quotes[4649]="<q></q>"; quotes[4650]="<q></q>"; quotes[4651]="<q></q>"; quotes[4652]="<q></q>"; quotes[4653]="<q></q>"; quotes[4654]="<q></q>"; quotes[4655]="<q></q>"; quotes[4656]="<q></q>"; quotes[4657]="<q></q>"; quotes[4658]="<q></q>"; quotes[4659]="<q></q>"; quotes[4660]="<q></q>"; quotes[4661]="<q></q>"; quotes[4662]="<q></q>"; quotes[4663]="<q></q>"; quotes[4664]="<q></q>"; quotes[4665]="<q></q>"; quotes[4666]="<q></q>"; quotes[4667]="<q></q>"; quotes[4668]="<q></q>"; quotes[4669]="<q></q>"; quotes[4670]="<q></q>"; quotes[4671]="<q></q>"; quotes[4672]="<q></q>"; quotes[4673]="<q></q>"; quotes[4674]="<q></q>"; quotes[4675]="<q></q>"; quotes[4676]="<q></q>"; quotes[4677]="<q></q>"; quotes[4678]="<q></q>"; quotes[4679]="<q></q>"; quotes[4680]="<q></q>"; quotes[4681]="<q></q>"; quotes[4682]="<q></q>"; quotes[4683]="<q></q>"; quotes[4684]="<q></q>"; quotes[4685]="<q></q>"; quotes[4686]="<q></q>"; quotes[4687]="<q></q>"; quotes[4688]="<q></q>"; quotes[4689]="<q></q>"; quotes[4690]="<q></q>"; quotes[4691]="<q></q>"; quotes[4692]="<q></q>"; quotes[4693]="<q></q>"; quotes[4694]="<q></q>"; quotes[4695]="<q></q>"; quotes[4696]="<q></q>"; quotes[4697]="<q></q>"; quotes[4698]="<q></q>"; quotes[4699]="<q></q>"; quotes[4700]="<q></q>"; quotes[4701]="<q></q>"; quotes[4702]="<q></q>"; quotes[4703]="<q></q>"; quotes[4704]="<q></q>"; quotes[4705]="<q></q>"; quotes[4706]="<q></q>"; quotes[4707]="<q></q>"; quotes[4708]="<q></q>"; quotes[4709]="<q></q>"; quotes[4710]="<q></q>"; quotes[4711]="<q></q>"; quotes[4712]="<q></q>"; quotes[4713]="<q></q>"; quotes[4714]="<q></q>"; quotes[4715]="<q></q>"; quotes[4716]="<q></q>"; quotes[4717]="<q></q>"; quotes[4718]="<q></q>"; quotes[4719]="<q></q>"; quotes[4720]="<q></q>"; quotes[4721]="<q></q>"; quotes[4722]="<q></q>"; quotes[4723]="<q></q>"; quotes[4724]="<q></q>"; quotes[4725]="<q></q>"; quotes[4726]="<q></q>"; quotes[4727]="<q></q>"; quotes[4728]="<q></q>"; quotes[4729]="<q></q>"; quotes[4730]="<q></q>"; quotes[4731]="<q></q>"; quotes[4732]="<q></q>"; quotes[4733]="<q></q>"; quotes[4734]="<q></q>"; quotes[4735]="<q></q>"; quotes[4736]="<q></q>"; quotes[4737]="<q></q>"; quotes[4738]="<q></q>"; quotes[4739]="<q></q>"; quotes[4740]="<q></q>"; quotes[4741]="<q></q>"; quotes[4742]="<q></q>"; quotes[4743]="<q></q>"; quotes[4744]="<q></q>"; quotes[4745]="<q></q>"; quotes[4746]="<q></q>"; quotes[4747]="<q></q>"; quotes[4748]="<q></q>"; quotes[4749]="<q></q>"; quotes[4750]="<q></q>"; quotes[4751]="<q></q>"; quotes[4752]="<q></q>"; quotes[4753]="<q></q>"; quotes[4754]="<q></q>"; quotes[4755]="<q></q>"; quotes[4756]="<q></q>"; quotes[4757]="<q></q>"; quotes[4758]="<q></q>"; quotes[4759]="<q></q>"; quotes[4760]="<q></q>"; quotes[4761]="<q></q>"; quotes[4762]="<q></q>"; quotes[4763]="<q></q>"; quotes[4764]="<q></q>"; quotes[4765]="<q></q>"; quotes[4766]="<q></q>"; quotes[4767]="<q></q>"; quotes[4768]="<q></q>"; quotes[4769]="<q></q>"; quotes[4770]="<q></q>"; quotes[4771]="<q></q>"; quotes[4772]="<q></q>"; quotes[4773]="<q></q>"; quotes[4774]="<q></q>"; quotes[4775]="<q></q>"; quotes[4776]="<q></q>"; quotes[4777]="<q></q>"; quotes[4778]="<q></q>"; quotes[4779]="<q></q>"; quotes[4780]="<q></q>"; quotes[4781]="<q></q>"; quotes[4782]="<q></q>"; quotes[4783]="<q></q>"; quotes[4784]="<q></q>"; quotes[4785]="<q></q>"; quotes[4786]="<q></q>"; quotes[4787]="<q></q>"; quotes[4788]="<q></q>"; quotes[4789]="<q></q>"; quotes[4790]="<q></q>"; quotes[4791]="<q></q>"; quotes[4792]="<q></q>"; quotes[4793]="<q></q>"; quotes[4794]="<q></q>"; quotes[4795]="<q></q>"; quotes[4796]="<q></q>"; quotes[4797]="<q></q>"; quotes[4798]="<q></q>"; quotes[4799]="<q></q>"; quotes[4800]="<q></q>"; quotes[4801]="<q></q>"; quotes[4802]="<q></q>"; quotes[4803]="<q></q>"; quotes[4804]="<q></q>"; quotes[4805]="<q></q>"; quotes[4806]="<q></q>"; quotes[4807]="<q></q>"; quotes[4808]="<q></q>"; quotes[4809]="<q></q>"; quotes[4810]="<q></q>"; quotes[4811]="<q></q>"; quotes[4812]="<q></q>"; quotes[4813]="<q></q>"; quotes[4814]="<q></q>"; quotes[4815]="<q></q>"; quotes[4816]="<q></q>"; quotes[4817]="<q></q>"; quotes[4818]="<q></q>"; quotes[4819]="<q></q>"; quotes[4820]="<q></q>"; quotes[4821]="<q></q>"; quotes[4822]="<q></q>"; quotes[4823]="<q></q>"; quotes[4824]="<q></q>"; quotes[4825]="<q></q>"; quotes[4826]="<q></q>"; quotes[4827]="<q></q>"; quotes[4828]="<q></q>"; quotes[4829]="<q></q>"; quotes[4830]="<q></q>"; quotes[4831]="<q></q>"; quotes[4832]="<q></q>"; quotes[4833]="<q></q>"; quotes[4834]="<q></q>"; quotes[4835]="<q></q>";
56c4a48e162876c57a7e26f4c9dcdb6549f3b6b2
[ "JavaScript", "HTML" ]
2
HTML
pixinixi/pixinixi.github.io
b0fc17eab5b1a64189fe28391554d2267c2a6039
d9610765c251a4b14fd6d107ce44ca27deb0d959
refs/heads/master
<file_sep>package main import ( "io" "log" "net/http" ) func handleHello(w http.ResponseWriter, r *http.Request) { io.WriteString(w, "Hello Friend!") io.WriteString(w, " URL: "+r.URL.Path) } func handleQuote(w http.ResponseWriter, r *http.Request) { io.WriteString(w, "Quotes Yet to implement! Please work with below joke, W@rning: PUN intended - \n") switch r.Method { case "GET": io.WriteString(w, "GET set go!") case "POST": io.WriteString(w, "POST the HOST!") case "PUT": io.WriteString(w, "This is writer's Block! You 'PUT' it on top of your desk and then you can't write there any more!\n ---------------- \n ---------------- \n ---------------- \n ---------------- \n ---------------- \n ---------------- \n ---------------- \n ---------------- \n ---------------- \n ---------------- \n") case "DELETE": io.WriteString(w, "DELETE Cookies?!") default: w.WriteHeader(http.StatusBadRequest) } } func handleQuotes(w http.ResponseWriter, r *http.Request) { if r.Method == "GET" { io.WriteString(w, "Congrats! you are here early. You should GET somthing here in some days(like 365ish)") } else { io.WriteString(w, " I was supposed to send 404 or any other code, but couldn't. Hold on!") w.WriteHeader(http.StatusBadRequest) } } func main() { const PREFIX string = "/api/v1/" http.HandleFunc("/", handleHello) http.HandleFunc(PREFIX+"quote", handleQuote) http.HandleFunc(PREFIX+"quotes", handleQuotes) err := http.ListenAndServe("localhost:8080", nil) if err != nil { log.Fatalln("ListenAndServe Failed:", err) } } <file_sep>package main import ( "appliedgo/intqueue" "appliedgo/queue" "fmt" ) func main() { fmt.Println("This is queue program") q := queue.Queue{} q.PutAny(1) q.PutAny(2) q.PutAny(3) q.PutAny(4) elem, err := q.GetAny() if err == nil { fmt.Println(elem) } elem1, err1 := q.GetAny() if err1 == nil { fmt.Println(elem1) } elem2, err2 := q.GetAny() if err2 == nil { fmt.Println(elem2) } elem3, err3 := q.GetAny() if err3 == nil { fmt.Println(elem3) } elem4, err4 := q.GetAny() if err4 == nil { fmt.Println(elem4) } forInt() } func forInt() { fmt.Println("This is queue program For int") q := intqueue.IntegerQueue{} q.PutAny(1) q.PutAny(2) q.PutAny(3) q.PutAny(4) elem, err := q.GetAny() if err == nil { fmt.Println(elem) } elem1, err1 := q.GetAny() if err1 == nil { fmt.Println(elem1) } elem2, err2 := q.GetAny() if err2 == nil { fmt.Println(elem2) } elem3, err3 := q.GetAny() if err3 == nil { fmt.Println(elem3) } elem4, err4 := q.GetAny() if err4 == nil { fmt.Println(elem4) } } <file_sep>package main import ( "fmt" "os" "strconv" ) func main() { var n int if len(os.Args) > 1 { input, err := strconv.Atoi(os.Args[1]) if err != nil { fmt.Println("Error:", err) return } n = input } else { fmt.Println("Plese enter a number grater than 1:") _, err := fmt.Scanf("%d", &n) if err != nil { fmt.Println("Error:", err) return } } playfizzbuzz(n) } func playfizzbuzz(num int) { for idx := 1; idx <= num; idx++ { switch { case idx%15 == 0: fmt.Println("FizzBuzz") case idx%3 == 0: fmt.Println("Fizz") case idx%5 == 0: fmt.Println("Buzz") default: fmt.Println(idx) } } } <file_sep>package main import ( "fmt" "io" "net/http" ) func hello(w http.ResponseWriter, r *http.Request) { io.WriteString(w, "<H1><c>Hello</c></H1>") io.WriteString(w, fmt.Sprintf("From URL: %s", r.URL.Path)) } func main() { http.HandleFunc("/", hello) err := http.ListenAndServe("localhost:8080", nil) if err != nil { fmt.Println(err) } } <file_sep>package main import "fmt" type s1 struct { n int b bool } type s2 struct { r []rune } type s3 struct { r [3]rune } func main() { // try0 s11 := s1{n: 4, b: true} s12 := s1{n: 4, b: true} fmt.Println(s11 == s12) // try1 s21 := s2{r: []rune{'a', 'b', '🎵'}} s22 := s2{r: []rune{'a', 'b', '🎶'}} fmt.Println(s21.r[1] == s22.r[1]) // try2 s31 := s3{r: [3]rune{'a', 'b', '🎵'}} s32 := s3{r: [3]rune{'a', 'b', '🎶'}} fmt.Println(s31 == s32) } <file_sep>package queue import "errors" // Queue jo sab ke liye kam kare type Queue []interface{} // PutAny adds an element to the queue. func (c *Queue) PutAny(elem interface{}) { *c = append(*c, elem) } // GetAny removes an element from the queue. // If the queue is empty, GetAny returns an error. func (c *Queue) GetAny() (interface{}, error) { //TODO: fetch the first element's value, and then remove the first element from the queue. //If the queue is already empty, return the zero value of interface{} and an error. if len(*c) > 0 { elem := (*c)[0] *c = (*c)[1:] return elem, nil } return 0, errors.New("POP failed") } <file_sep>package main import ( "fmt" "os" "strconv" "github.com/appliedgocourses/bank" ) func main() { if len(os.Args) < 2 { usage() return } // Restore the bank data. // Call bank.Load() here and handle any error. bank.Load() // Save the bank data. // Use a deferred function for calling bank.Save(). // (See the lecture on function behavior.) // If Save() returns an error, print it. defer bank.Save() // Perform the action. // os.Args[0] is the path to the executable. // os.Args[1] is the first parameter - the action we want to perform: // create, list, update, transfer, or history. switch os.Args[1] { case "list": s := bank.ListAccounts() fmt.Println(s) // TODO: more cases case "create": newAccName := os.Args[2] acc := bank.NewAccount(newAccName) fmt.Println("Account", acc.Name, "created successfully") case "update": i, _ := strconv.ParseInt(os.Args[3], 0, 32) newbal, err := update(os.Args[2], int(i)) if err == nil { fmt.Println("Update successful new balnce is", newbal) } else { fmt.Errorf(err.Error()) } case "transfer": i, _ := strconv.ParseInt(os.Args[4], 0, 32) newBal1, newBal2, err := transfer(os.Args[2], os.Args[3], int(i)) if err == nil { fmt.Println("Transfer successful, new balance of", os.Args[2], "is", newBal1, "and", os.Args[3], "is", newBal2) } else { fmt.Errorf(err.Error()) } case "history": hist, err := history(os.Args[2]) if err == nil { fmt.Println(hist) } else { fmt.Errorf(err.Error()) } default: fmt.Println("Please choose proper option") usage() } } func usage() { fmt.Println(`Usage: bank create <name> Create an account. bank list List all accounts. bank update <name> <amount> Deposit or withdraw money. bank transfer <name> <name> <amount> Transfer money between two accounts. bank history <name> Show an account's transaction history. `) } // update takes a name and an amount, deposits the amount if it // is greater than zero, or withdraws it if it is less than zero, // and returns the new balance and any error that occurred. func update(name string, amount int) (int, error) { acc, err := bank.GetAccount(name) if err == nil { if amount > 0 { return bank.Deposit(acc, amount) } return bank.Withdraw(acc, amount*-1) } return 0, err } // transfer takes two names and an amount, transfers the amount from // the account belonging to name #1 to the account belonging to name #2, // and returns the new balances of both accounts and any error that occurred. func transfer(name, name2 string, amount int) (int, int, error) { acc, err := bank.GetAccount(name) acc2, err := bank.GetAccount(name2) if err == nil { return bank.Transfer(acc, acc2, amount) } return 0, 0, err } // history takes an account name, retrieves the account, and calls bank.History() // to get the history closure function. Then it calls the closure in a loop, // formatting the return values and appending the result to the output string, until the boolean return parameter of the closure is `false`. func history(name string) (string, error) { var result string acc, err := bank.GetAccount(name) if err == nil { hisFunc := bank.History(acc) for { trasctionAmount, resultingBalance, more := hisFunc() if !more { break } result = result + fmt.Sprint(trasctionAmount) + " " + fmt.Sprint(resultingBalance) + "\n" } } return result, err } <file_sep>package main import ( "fmt" ) func main() { str := "<NAME>" fmt.Println(str) runeArray := []rune(str) copied := make([]rune, len(runeArray)) copy(copied, runeArray) fmt.Println(runeArray) fmt.Println(copied) } <file_sep>package main import ( "fmt" "os" "strings" "unicode" ) func acronym(s string) (acr string) { flag := true for _, ch := range s { if flag && unicode.IsLetter(ch) { acr = acr + string(unicode.ToUpper(ch)) flag = false } if unicode.IsSpace(ch) { flag = true } } return acr } func main() { s := "Pan Galactic Gargle Blaster" if len(os.Args) > 1 { s = strings.Join(os.Args, " ") } fmt.Println(acronym(s)) } <file_sep>// this is the main package package main import ( "fmt" ) // Common interface type Common interface { } // Parent is interfce type Parent interface { A() } //Child struct type Child struct{} // A is part of Child func (c Child) A() { fmt.Println("In Child A") } // B is here func (c *Child) B() { fmt.Println("In Child B") } func main() { var p Parent p = Child{} callA(p) } func callA(p Parent) { p.A() } <file_sep>package main import ( "fmt" ) // IntegerTree is structure to carry tree of integer type IntegerTree struct { Number int Left, Right *IntegerTree } func populateTree(integerSlice []int) IntegerTree { var tree IntegerTree tree.Number = integerSlice[0] newslice := integerSlice[1:] for _, integer := range newslice { insert(&tree, integer) } return tree } func insert(tree *IntegerTree, val int) *IntegerTree { if tree == nil { newNode := IntegerTree{Number: val} return &newNode } if val < tree.Number { tree.Left = insert(tree.Left, val) } else if val > tree.Number { tree.Right = insert(tree.Right, val) } return tree } func main() { intSlice := []int{11, 6, 8, 19, 4, 10, 5, 17, 43, 49, 31} tree := populateTree(intSlice) printTree(tree) } func printTree(tree IntegerTree) { fmt.Print(tree.Number, ",") if tree.Left != nil { printTree(*tree.Left) } if tree.Right != nil { printTree(*tree.Right) } } <file_sep>package main import "fmt" func main() { s, d := getMessage() fmt.Println(s, d) } func getMessage() (s int, d string) { d = "mandar" return 0, d } <file_sep>package main import ( "flag" "fmt" "os" "strconv" ) func main() { var val float64 var from, to string //setting flags flag.StringVar(&from, "from", "meters", "Unit to convert from - 'meters','feet' or 'inches' ") flag.StringVar(&to, "to", "feet", "Unit to convert to - 'meters','feet' or 'inches'") //reading flags flag.Parse() //read passed value if len(os.Args) == 4 { input, _ := strconv.ParseFloat(os.Args[3], 64) val = input } else { fmt.Println("Parmeterss missing plese refer help") return } // validate flag if !isFlagValid(from) { fmt.Println("'from' flag is invalid. Allowed flag are 'meters','feet' or 'inches'") return } if !isFlagValid(to) { fmt.Println("'to' flag is invalid. Allowed flag are 'meters','feet' or 'inches'") return } //calling convert result := converter(from, to, val) fmt.Println("Length", val, from, "is equivalent to", result, to) } func isFlagValid(flag string) (b bool) { switch flag { case "meters", "feet", "inches": return true } return false } func converter(from string, to string, val float64) (result float64) { switch { case from == "meters" && to == "inches": return val * 39.3701 case from == "meters" && to == "feet": return val * 3.2808 case from == "inches" && to == "meters": return val * 0.0254 case from == "inches" && to == "feet": return val * 0.0833 case from == "feet" && to == "inches": return val * 12.0 case from == "feet" && to == "meters": return val * 0.3048 } return 0 } <file_sep>package main import ( "fmt" "time" ) func main() { //num := 941 start := time.Now() count := 0 for idx := 1; idx <= 941; idx++ { if isPrime(idx) { fmt.Println(idx) count++ } } elapsed := time.Since(start) fmt.Println("Time Taken:", elapsed) fmt.Println("Total count:", count) } func isPrime(num int) bool { if num <= 0 || num == 1 { return false } for idx := 2; idx < num/2; idx++ { if num%idx == 0 { return false } } return true } <file_sep>package main import ( "fmt" "strings" "time" ) func main() { str1 := "aaaataArmy" str2 := "Maryasaaaa" start := time.Now() if isAnagram(str1, str2) { fmt.Println("these are anagrams") } else { fmt.Println("these are not anagrams") } elapsed := time.Since(start) fmt.Println("Time Taken:", elapsed) start = time.Now() isAnagramOldWay(str1, str2) elapsed = time.Since(start) fmt.Println("Time Taken:", elapsed) } func isAnagram(str1 string, str2 string) bool { charMap1 := getCharCount(strings.ToLower(str1)) charMap2 := getCharCount(strings.ToLower(str2)) return compareCharMaps(charMap1, charMap2) } func compareCharMaps(map1 map[rune]int, map2 map[rune]int) bool { for k, v := range map1 { if map2[k] == 0 || map2[k] != v { return false } } return true } func getCharCount(str string) map[rune]int { charMap := make(map[rune]int) for _, char := range str { charMap[char]++ } return charMap } func isAnagramOldWay(str1 string, str2 string) { lowerStr1 := strings.ToLower(str1) lowerStr2 := strings.ToLower(str2) runeArrayStr1 := []rune(lowerStr1) runeArrayStr2 := []rune(lowerStr2) for idx, char := range lowerStr1 { index := strings.IndexRune(lowerStr2, char) if index != -1 { runeArrayStr2 = removeFromArray(runeArrayStr2, index) lowerStr2 = string(runeArrayStr2) runeArrayStr1 = removeFromArray(runeArrayStr1, idx) //lowerStr1 = string(runeArrayStr1) } } fmt.Println("Anagarms :", len(runeArrayStr2) == 0) } func removeFromArray(s []rune, i int) []rune { s[len(s)-1], s[i] = s[i], s[len(s)-1] return s[:len(s)-1] } <file_sep>package main import ( "encoding/json" "io" "io/ioutil" "log" "net/http" mgo "gopkg.in/mgo.v2" "gopkg.in/mgo.v2/bson" ) // Quote ghune ja re marbat type Quote struct { Author string `json:"author"` Text string `json:"text"` Source string `json:"source,omitempty"` } // QuoteApp quotes ka khajana type QuoteApp struct { Storage map[string]*Quote } func (qa *QuoteApp) handleHello(w http.ResponseWriter, r *http.Request) { io.WriteString(w, "Hello Friend!") io.WriteString(w, " URL: "+r.URL.Path) } func (qa *QuoteApp) handleQuote(w http.ResponseWriter, r *http.Request) { w.Header().Set("Content-Type", "application/json") switch r.Method { case "GET": var q Quote val := r.URL.Query() author := val["author"][0] if len(author) > 0 { db := getDatabase() if err := db.DB("lessons").C("quote").Find(bson.M{"author": author}).One(&q); err != nil { log.Fatalln(err) } db.Close() jsonVal, err := json.Marshal(q) if err != nil { w.WriteHeader(http.StatusBadRequest) return } io.WriteString(w, string(jsonVal)) } case "POST", "PUT": var q Quote body, _ := ioutil.ReadAll(r.Body) json.Unmarshal(body, &q) db := getDatabase() if err := db.DB("lessons").C("quote").Insert(&q); err != nil { log.Fatalln(err) } db.Close() io.WriteString(w, string(body)) case "DELETE": val := r.URL.Query() author := val["author"][0] if len(author) > 0 { jsonVal, err := json.Marshal(qa.Storage[author]) delete(qa.Storage, author) if err != nil { w.WriteHeader(http.StatusBadRequest) return } io.WriteString(w, "Deleted:"+string(jsonVal)) } default: w.WriteHeader(http.StatusBadRequest) } } func (qa *QuoteApp) handleQuotes(w http.ResponseWriter, r *http.Request) { w.Header().Set("Content-Type", "application/json") if r.Method == "GET" { var quotes []Quote db := getDatabase() if err := db.DB("lessons").C("quote").Find(nil).All(&quotes); err != nil { log.Fatalln(err) } db.Close() jsonVal, _ := json.Marshal(quotes) io.WriteString(w, string(jsonVal)) } else { w.WriteHeader(http.StatusBadRequest) } } func main() { qa := QuoteApp{ Storage: map[string]*Quote{}, } const PREFIX string = "/api/v1/" http.HandleFunc("/", qa.handleHello) http.HandleFunc(PREFIX+"quote", qa.handleQuote) http.HandleFunc(PREFIX+"quotes", qa.handleQuotes) err := http.ListenAndServe("localhost:8080", nil) if err != nil { log.Fatalln("ListenAndServe Failed:", err) } } func getDatabase() *mgo.Session { db, err := mgo.Dial("localhost") if err != nil { return nil } return db } <file_sep>package main import ( "fmt" "os" ) // TerminalWriter writes to a terminal, breaking the lines // at the given width. type TerminalWriter struct { width int } // Write writes slice p to stdout, in chunks of tw.width bytes, // separated by newline. // It returns the number of successfully written bytes, and // any error that occurred. // If the complete slice is written, Write returns error io.EOF func (tw *TerminalWriter) Write(p []byte) (n int, err error) { length := len(p) newLineByte := []byte("\n") idx := 1 for ; idx*tw.width < length; idx++ { os.Stdout.Write(p[(idx-1)*tw.width : idx*tw.width]) os.Stdout.Write(newLineByte) } os.Stdout.Write(p[(idx-1)*tw.width : length]) // for idx := 0; idx < tw.width; idx++ { // fmt.Printf("%s", string(p[n])) // n++ // } n = tw.width fmt.Printf("\n") return n, err } // NewTerminalWriter creates a new TerminalWriter. width is // the terminal's width. func NewTerminalWriter(width int) *TerminalWriter { return &TerminalWriter{width: width} } func main() { s := []byte("This is a long string converted into a byte slice for testing the TerminalWriter.") tw := NewTerminalWriter(31) n, err := tw.Write(s) fmt.Println(n, "bytes written. Error:", err) } <file_sep>package main import ( "fmt" "strings" ) func main() { mapVar := getWordCount("my name is mandar, And my full name is <NAME>") printMap(mapVar) } func getWordCount(str string) map[string]int { wordCountmap := make(map[string]int) stringSlice := strings.Split(str, " ") for _, word := range stringSlice { trimmedWord := strings.Trim(word, " '.,:;?!()-[]<>{}\t\n\"") lowerWord := strings.ToLower(trimmedWord) wordCountmap[lowerWord]++ } return wordCountmap } func printMap(mapArg map[string]int) { for k, v := range mapArg { if v > 1 { fmt.Printf("Key:%10s Value: %2d\n", k, v) } } } <file_sep>package main import ( "fmt" "unicode" ) func main() { s := longest("mandar", "anand", "joshi") fmt.Println(s) magicOfScopes() } func longest(s ...string) (result string) { for _, str := range s { if len(str) > len(result) { result = str } } return result } func magicOfScopes() { s := "abcde" for _, s := range s { s := unicode.ToUpper(s) fmt.Print(string(s)) } fmt.Println("\n" + s) } <file_sep>package main import ( "fmt" ) // Car is for use type Car struct { Name string Model string } func main() { print() print1() scan() } func print() { intVar := 1234 stringVar := "Mandar" boolVar := true floatVar := 22.0 / 7.0 car := Car{"i10", "Grand"} fmt.Printf("intVar = %d\n", intVar) fmt.Printf("stringVar = %s\n", stringVar) fmt.Printf("boolVar = %t\n", boolVar) fmt.Printf("floatVar = %f\n", floatVar) fmt.Printf("Anything = %v\n", car) fmt.Printf("Anything = %#v\n", car) fmt.Printf("Anything = %T\n", car) fmt.Printf("%[2]f %[1]X\n", intVar, floatVar) } func scan() { // var a float64 // fmt.Println("Please enter a float value") // fmt.Scanf("%f", &a) // fmt.Println("The float you entered is :", a) var n1, n2, n3, n4 int var f1 float64 // Scan the card number. str1 := "Card number: 1234 5678 0123 4567" _, err := fmt.Sscanf(str1, "Card number: %d %d %d %d", &n1, &n2, &n3, &n4) if err != nil { fmt.Println(err) } fmt.Printf("%04d %04d %04d %04d\n", n1, n2, n3, n4) // Scan the numeric values into a floating-point variable, and an integer. str2 := "Brightness is 50.0% (hex #7ffff)" _, err = fmt.Sscanf(str2, "Brightness is %f%% (hex #%x)", &f1, &n1) if err != nil { fmt.Println(err) } fmt.Println(f1, n1) } func print1() { // Print RGB values... r, g, b := 124, 87, 3 // ...as #7c5703 (specifying hex format, fixed width, and leading zeroes) // Hint: don't forget to add a newline at the end of the format string. fmt.Printf("#%#X #%#X #%#X \n", r, g, b) // ...as rgb(124, 87, 3) fmt.Printf("rgb(%d, %d, %d)\n", r, g, b) // ...as rgb(124, 087, 003) (specifying fixed width and leading zeroes) fmt.Printf("rgb(%03d, %03d, %03d)\n", r, g, b) // ...as rgb(48%, 34%, 1%) (specifying a literal percent sign) fmt.Printf("rgb(%d%%, %d%%, %d%%)\n", r*100/255, g*100/255, b*100/255) // Print the type of r. fmt.Printf("%T\n", r) } <file_sep>package main import ( "fmt" "math" ) func main() { n := 0.0 fmt.Println(1 / n) // +Inf fmt.Println(-1 / n) // -Inf fmt.Println(n / n) // NaN fmt.Println(math.Sqrt(-1)) // NaN if math.IsInf((1 / n), 1) { // we have to pass the expected sign fmt.Println("This is positive infinity") } if math.IsInf((-1 / n), -1) { // we have to pass the expected sign fmt.Println("This is nigative infinity") } if math.IsNaN(n / n) { fmt.Println("This is not a number") } } <file_sep>package intqueue import "appliedgo/queue" // IntegerQueue bla bla bla type IntegerQueue struct { queue.Queue } // Get get E func (i *IntegerQueue) Get() (int, error) { elem, err := i.GetAny() if err != nil { return 0, err } intelem := elem.(int) return intelem, err } // Put bla bla bla func (i *IntegerQueue) Put(elem int) { i.PutAny(elem) }
99f168a9020618fe1c2c6eeab118aa389dc1a266
[ "Go" ]
22
Go
mandarjoshi941/mastergo
35576c0c6070a25bf44881bfc66fdedf59e92691
20dbb47491d5a6c77688b83b85ec16f9cd78d170
refs/heads/master
<file_sep>'use strict'; var util = require('util'); var EventEmitter = require('events').EventEmitter; var timers = require('timers'); var whatsapi = require('whatsapi'); var Dispatcher = require('./lib/dispatcher'); var Errors = require('./lib/errors'); var createDelay = require('./lib/type-delay'); /** * Create an instance of a Bot * @param {Object} options * @param {Object} options.adapter whatsapi adapter options * @param {String} options.adapter.msisdn msisdn number * @param {String} options.adapter.password password * @param {String} options.adapter.ccode country code * @param {String} [options.adapter.username] Whatsapp username * @constructor */ function Bot(options) { var self = this; options = options || {}; options.adapter = options.adapter || {}; if (!options.adapter.msisdn) { throw Errors.InvalidArgumentError({ argument: 'adapter.msisdn', given: options.adapter.msisdn, expected: 'String' }); } if (!options.adapter.password) { throw Errors.InvalidArgumentError({ argument: 'adapter.password', given: options.adapterpassword, expected: 'String' }); } if (!options.adapter.ccode) { throw Errors.InvalidArgumentError({ argument: 'adapter.ccode', given: options.adapter.ccode, expected: 'String' }); } this.adapter = whatsapi.createAdapter(options.adapter); this.adapter.on('error', function reportError(err) { self.emit('error', err); }); // Setup bot state this.contacts = []; this.serverProperties = {}; // Add listeners this.dispatcher = options.dispatcher || new Dispatcher(); this._events = [ 'receivedMessage', 'receivedLocation', 'receivedImage', 'receivedVideo', 'receivedAudio', 'receivedVcard' ]; var dispatch = this.dispatcher.dispatchEvent.bind(this.dispatcher); this._events.forEach(function register(event) { self.adapter.on(event, dispatch); }); } util.inherits(Bot, EventEmitter); /** * Connect the bot to whatsapp servers * This function will connect, login, get server properties and set the online status * This attempts to mimic the official clients as closely as possible * @param {Function} callback function which is called when connected */ Bot.prototype.connect = function connect(callback) { var self = this; function onLogin(err) { if (err) { callback(Errors.ConnectionError(err)); return; } // Simulate official clients by requesting properties self.adapter.requestServerProperties(function onProps(props) { self.serverProperties = props; }); self.adapter.sendIsOnline(); callback(null); } this.adapter.connect(function onConnect(err) { if (err) { callback(Errors.ConnectionError(err)); return; } self.adapter.login(onLogin); }); }; /** * Register an action for the bot * @param {Trigger} trigger The trigger to listen for * @param {Function} handler The function to run when the trigger matches * @param {Object} context Context to call the action with */ Bot.prototype.registerTrigger = function registerTrigger(trigger, handler, context) { this.dispatcher.registerTrigger(trigger, handler, context); }; /** * Send a message with a delay. * Also set the typing state to imitate a real client * @param {String} recipient The recipient's id * @param {String} text The text to send * @param {Function} callback called when sent. */ Bot.prototype.sendMessage = function sendMessage(recipient, text, callback) { var self = this; this.adapter.sendComposingState(recipient); timers.setTimeout(function send() { self.adapter.sendPausedState(recipient); self.adapter.sendMessage(recipient, text, callback); }, createDelay(text)); }; /** * Destroy and cleanup the bot */ Bot.prototype.destroy = function destroy() { this._events.forEach(this.adapter.removeAllListeners); this.adapter.sendIsOffline(); this.adapter.disconnect(); }; module.exports = Bot; <file_sep>'use strict'; var TypedError = require('error/typed'); var WrappedError = require('error/wrapped'); var InvalidArgumentError = TypedError({ type: 'argument.invalid', message: 'Invalid argument for `{argument}`. Given {given} expected {expected}', argument: null, given: null, expected: null }); var ConnectionError = WrappedError({ type: 'connection', message: 'Connection error: {origMessage}' }); module.exports = { InvalidArgumentError: InvalidArgumentError, ConnectionError: ConnectionError }; <file_sep>'use strict'; var Buffertools = require('buffertools'); var extend = require('xtend'); module.exports = { /** * Create a trigger which matches some text * @param {String} text Text to match * @param {Object} options options * @param {Boolean} [options.caseSensitive=false] Match case sensitive, default false * @returns {Trigger} this object for chaining * @constructor */ withText: function matchingText(text, options) { options = options || {}; options = extend({ caseSensitive: false }, options); return function matcher(event) { if (!event.body) { return false; } if (!options.caseSensitive) { return event.body.toLowerCase().indexOf(text.toLowerCase()) !== -1; } return event.body.indexOf(text) !== -1; }; }, withRegex: function withRegex(regex) { return function matcher(event) { if (!event.body) { return false; } return regex.test(event.body); }; }, withEmoji: function containingEmoji(emoji) { return function matcher(event) { if (!event.body) { return false; } var bodyBuffer = new Buffer(event.body); return Boolean(Buffertools.indexOf(bodyBuffer, emoji) !== -1); }; } }; <file_sep>'use strict'; var WORDS_PER_SECOND = 0.7; /** * Get an artificial delay based on length of the text. * @param {String} text The text to send * @returns {Number} A delay */ module.exports = function getTypeDelay(text) { var words = text.split(' '); return (words.length * WORDS_PER_SECOND * 1000) + getNoise(3); }; /** * Get +- N seconds of noise, randomly * @param {Number} seconds number of seconds * @returns {Number} some noise, in ms */ function getNoise(seconds) { var noise = Math.random() * seconds * 1000; if (noise % 2 === 0) { return noise; } return -noise; } <file_sep>'use strict'; var Buffer = require('buffer').Buffer; var _ = require('lodash'); var extend = require('xtend'); var Errors = require('./lib/errors'); var Location = require('./predicates/location'); var Message = require('./predicates/message'); var JOIN_MODES = { ALL: 'all', ANY: 'any' }; /** * Create a trigger for a given matching predicate * @param {Object} options * @constructor */ function Trigger(options) { options = options || {}; this.options = extend({ mode: JOIN_MODES.ALL }, options); if (!_.contains(_.values(JOIN_MODES), this.options.mode)) { throw Errors.InvalidArgumentError({ argument: 'options.mode', given: options.mode, expected: 'One of: ' + _.values(JOIN_MODES) }); } this.conditions = []; } /** * Check whether the trigger matches this event by invoking the predecate * @param {Object} event Event from whatsapp * @returns {Boolean} true if match, false otherwise */ Trigger.prototype.matches = function matches(event) { function isMatch(predicate) { return predicate(event); } if (this.options.mode === JOIN_MODES.ALL) { return _.all(this.conditions, isMatch); } return _.any(this.conditions, isMatch); }; // Predicate constructors below /** * Create a trigger which always matches an event * Useful if you want to capture everything */ Trigger.prototype.always = function always() { var predicate = function matcher() { return true; }; this.conditions.push(predicate); return this; }; /** * Create a trigger which matches some text * @param {String} text Text to match * @param {Object} options options * @param {Boolean} [options.caseSensitive=false] Match case sensitive, default false * @returns {Trigger} this object for chaining */ Trigger.prototype.withText = function matchingText(text, options) { this.conditions.push(Message.withText(text, options)); return this; }; /** * Create a trigger which matches a regex * @param {RegExp} regex Regex to apply to message * @returns {Trigger} this object for chaining */ Trigger.prototype.withRegex = function withRegex(regex) { if (!(regex instanceof RegExp)) { throw Errors.InvalidArgumentError({ argument: 'regex', given: regex, expected: 'RegExp' }); } this.conditions.push(Message.withRegex(regex)); return this; }; /** * Create a trigger which matches emoji * @param {Buffer} emoji Emoji as a buffer * @returns {Trigger} this object for chaining */ Trigger.prototype.withEmoji = function containingEmoji(emoji) { if (!Buffer.isBuffer(emoji)) { throw Errors.InvalidArgumentError({ argument: 'emoji', given: emoji, expected: 'buffer' }); } this.conditions.push(Message.withEmoji(emoji)); return this; }; /** * Create a trigger which matches some author * @param {String} author the author * @returns {Trigger} this object for chaining */ Trigger.prototype.from = function from(author) { var predicate = function matcher(event) { if (event.author) { return event.author === author; } return event.from === author; }; this.conditions.push(predicate); return this; }; /** * Create a trigger which matches a group * @param {Object} options options * @param {String} [options.groupId] options * @param {String} [options.author] options * @returns {Trigger} this object for chaining */ Trigger.prototype.inGroup = function inGroup(options) { options = options || {}; var predicate = function matcher(event) { if (!event.isGroup) { return false; } if (options.groupId && options.groupId !== event.from) { return false; } if (options.author && options.author !== event.author) { return false; } return true; }; this.conditions.push(predicate); return this; }; /** * Register a custom predicate * @param {Function} predicate the predicate * @returns {Trigger} this object for chaining */ Trigger.prototype.custom = function custom(predicate) { this.conditions.push(predicate); return this; }; /** * Check that a message is a location * @returns {Trigger} this object for chaining */ Trigger.prototype.isLocation = function isLocation() { this.conditions.push(Location.isLocation); return this; }; /** * Check that a location message is within a distance of * @param {{latitude: number, longitude: number}} point Point to check * @param {Number} distanceLimit limit * @param {String} [unit] distance unit, 'km' (default) or 'mile' * @returns {Trigger} this object for chaining */ Trigger.prototype.withinDistanceOf = function withinDistanceOf(point, distanceLimit, unit) { this.conditions.push(Location.withinDistance(point, distanceLimit, unit)); return this; }; module.exports = Trigger; <file_sep>'use strict'; var util = require('util'); var Dispatcher = require('./dispatcher'); function DrainDispatcher(date) { Dispatcher.call(this); this.drained = false; this.dispatchAfter = date || Date.now(); } util.inherits(DrainDispatcher, Dispatcher); /** * Drop all old messages up until we instantiated this disptacher * Dispatch anything that comes afterwards * @param {Object} event The event */ Dispatcher.prototype.dispatchEvent = function dispatchEvent(event) { var self = this; if (!this.drained) { var eventDate = new Date(event.date); if (eventDate >= this.dispatchAfter) { this.drained = true; dispatch(); } return; } dispatch(); function dispatch() { var matchingActions = self.triggers.filter(function findMatch(pair) { var trigger = pair.trigger; return Boolean(trigger.matches(event)); }); matchingActions.forEach(function callAction(pair) { var action = pair.action; if (pair.context) { action.call(pair.context, event); return; } action(event); }); } }; module.exports = DrainDispatcher; <file_sep># botsapp A WhatsApp bot framework in Node Botsapp is simple framework for creating WhatsApp bots (using the awesome [whatsapi](https://github.com/hidespb/node-whatsapi) project). ## whatapi As of May 2015 the whatsapi library which is a dependecy of botsapp has been removed due to legal threats.. I belive there are other forks possibly still available. I'm no longer actively using this library, but I'm happy to accept pull requests for anyone who wishes to test one of these libraries and change the dependency. ## Disclaimer I know. I'm sorry. I really hope this doesn't end up powering lots of annoying WhatsApp bots, but I needed this for a personal project. Be warned that there are plenty of reports of people getting their number banned from WhatsApp when using anything other than the official clients. *Using this code may result in your account being banned*. The bot will attempt to follow the protocol as closely as possible to avoid that, but this is based on annecdotal evidence rather than watching network traffic (as that is against the WhatsApp terms and conditions). ## Install `npm install --save botsapp` ## Usage ```js 'use strict'; var Botsapp = require('botsapp'); var process = require('process'); var yourBot = new Botsapp.Bot({ adapter: { msisdn: '123456789', // phone number with country code username: 'YourBot', // your name on WhatsApp password: '<PASSWORD>', // WhatsApp password ccode: '44' // country code } }); // Register a handler which logs every message var anyMessage = new Botsapp.Trigger().always(); yourBot.registerTrigger(anyMessage, function onTrigger(event) { console.log(event); }); // Get a thumbsup, give a thumbsup var thumbsupEmoji = new Buffer([240, 159, 145, 141]); var thumbsUp = new Botsapp.Trigger().withEmoji(thumbsupEmoji); yourBot.registerTrigger(thumbsUp, function onTrigger(event) { var emoji = thumbsupEmoji.toString('utf8'); yourBot.sendMessage(event.from, emoji, function onSend() { console.log('Sent emoji to', event.from); }); }); // Get hello from a specific user var author = '<EMAIL>'; var helloFromMe = new Botsapp.Trigger() .from(author) .withText('hello'); yourBot.registerTrigger(helloFromMe, function onTrigger(event) { console.log('Got hello from', author, event.body); }); // Connect to the server yourBot.connect(function() { console.log("I'm alive!"); }); yourBot.on('error', function gracefulShutdown() { yourBot.destroy(); process.exit(1); }); ``` ## API There are a few exports: - `Bot` - `Trigger` - `Dispatcher` - `DrainDisptacher` #### Bot Make an instance of Bot to establish a connection. The bot provides methods to register actions and to interact with WhatsApp. Currently, only sending a message (to a user or group) is supported. #### Trigger Triggers are sets of conditions which trigger functions when all (default) or any of those conditions are met. Triggers can be arbitrarily constructed with a chain. Matching any conditions: ```js var someWords = new Trigger({ mode: 'any', }).withText('foo').withText('bar') ``` Matching all conditions: ```js var helloInGroup = new Trigger() .withText('hello') .inGroup() ``` #### Dispatcher (+ DrainDispatcher) The `Dispatcher` is used to dispatch events from WhatsApp, check if they match triggers and invoke actions. By default the `Dispatcher` class will dispatch every event from the server to the triggers. When the bot logs in, you will automatically be dispatched any events which happened when the bot was offline. If you'd like to ignore all those events and only process going forwards, you should use the `DrainDispatcher`: ```js var beanBot = new Botsapp.Bot({ dispatcher: new Botsapp.DrainDispatcher(), adapter: { ... } }); ``` #### TODO - [ ] Groups (join, leave, edit, invite, promote, demote, info) - [ ] Send pictures, videos, vcards, locations - [ ] Sync contacts (to avoid bans) - [ ] Capture group notifications (joins/leaves/edits) - [ ] Unit tests! Note: Many of these thigs can be done directly with `whatsapi` on `bot.adapter`. Full API description: ```ocaml Bot(options: Object) => { connect: (callback: Function) => void, destroy: () => void, registerTrigger: (trigger: Trigger, handler: Function, callback: Function) => void, sendMessage: (recipient: String, text: String, callback: Function) => void, } Trigger(options: Object) => { matches: (event: Object) => Boolean, always: () => Trigger, withText: (text: String, options: Object) => Trigger, withEmoji: (emoji: Buffer) => Trigger, from: (author: String) => Trigger, inGroup: (options: Object) => Trigger, custom: (predicate: (event: Object) => Boolean) => Trigger } ``` <file_sep>'use strict'; var _ = require('lodash'); var haversine = require('haversine'); module.exports = { /** * Check that the event has a location * @returns {Function} predicate */ isLocation: function() { return function(event) { return _.isNumber(event.latitude) && _.isNumber(event.longitude); } }, /** * Use haversine distance to check if location is within a limit * @param {{latitude: number, longitude: number}} point Point to check * @param {Number} distanceLimit limit * @param {String} [unit] distance unit, 'km' (default) or 'mile' * @returns {Function} predicate */ withinDistance: function(point, distanceLimit, unit) { unit = unit || 'km'; return function(event) { if (!event.latitude) { return false; } var sentLocation = _.pick(event, 'latitude', 'longitude'); var distance = haversine(point, sentLocation, unit); return distance <= distanceLimit; } } };
d81a6a45d06755db0e53c89ac20769e124f63143
[ "JavaScript", "Markdown" ]
8
JavaScript
kauegimenes/botsapp
00cd23f629ab938baf40c5f0b732c6ad4f2b7693
ade7984c531ce47a215c1846e734d890ab4a6069
refs/heads/master
<file_sep><?php session_start(); if(!isset($_SESSION['seas_admin'])) { header("location:/nitesh/modified/admin_login.html"); } else { ?> <!DOCTYPE html> <html> <head> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="/nitesh/modified/style.css"> </head> <title>login</title> <body> <nav> <div class="container"> <ul class="nav"> <li><a href="/nitesh/modified/admin_logout.php">Logout</a></li> </ul> </div> </nav> <center><h2>Scores by students</h2></center> <div class="log1"> <form action="#" method="post"> <fieldset> <legend> Select Subject</legend> <?php include'database.php'; $sql = "SELECT * FROM test_status "; ?> <table > <thead> <tr> <th>UserId</th> <th>TotalQuestions</th> <th>Correct</th> <th>Wrong</th> <th>Percentage</th> <th>Status</th> <th>UpdateTyme</th> </tr> </thead> <tbody> <?php $result = $con->query($sql); if ($result->num_rows > 0) { while($row = $result->fetch_assoc()) { echo "<tr> <td>{$row['user_id']}</td> <td>{$row['total_question']}</td> <td>{$row['correct_ans']}</td> <td>{$row['wrong_ans']}</td> <td>{$row['percentage']}</td> <td>{$row['status']}</td> <td>{$row['created_on']}</td> </tr>"."\n"; } } ?> </tbody> </table> <input type="hidden" value="Login"> </fieldset> </form> </div> </body> </html> <?php mysqli_close($con); } ?> <file_sep><?php session_start(); ?> <?php require'database.php'; $userid = $_POST['userid']; $userpass = $_POST['<PASSWORD>pass']; $sql="SELECT * FROM user_registration WHERE user_userid='$userid' and user_passid='$userpass'"; $result=mysqli_query($con,$sql); $count=mysqli_num_rows($result); if ($result->num_rows > 0) { while($row = $result->fetch_assoc()) { if($count==1) { $_SESSION['seas_user']=$userid; $_SESSION['seas_user_id']=$row['user_id']; $_SESSION['values']=0; $_SESSION['q_id'][]=0; $_SESSION['count']=0; header('Location:subject_type.php'); } } } else { echo "<center><h2>Wrong Username or Password</br> Please check your </b> Id OR Password </h2></center>"; } ?> <file_sep><?php session_start(); if(!isset($_SESSION['seas_user'])) { header("location:/nitesh/modified/login.html"); } else { require 'database.php'; if(isset($_GET['type'])) { $_SESSION['values']=$_GET['type']; } $userid=$_SESSION['seas_user_id']; $subject_type=$_SESSION['values']; $sql="SELECT * FROM subject_status WHERE user_id='".$userid."' AND subject_type='".$subject_type."' AND status in (0,1)"; $query = mysqli_query($con, $sql); if(mysqli_num_rows($query) > 0) { header("location:/nitesh/modified/question.php/?type=$subject_type"); } else { $sql="INSERT INTO `nitesh`.`subject_status` ( `user_id`,`status`, `subject_type`, `created_on`, `updated_on`) VALUES ('$userid' ,'0', '$subject_type', now(), now())"; if ($con->query($sql) === TRUE) { header("location:/nitesh/modified/question.php/?type=$subject_type"); } else { echo "Error: " . $sql . "<br>" . $con->error; } mysqli_close($con); } } ?> <file_sep><?php session_start(); if(!isset($_SESSION['seas_user'])) { header("location:/nitesh/modified/login.html"); } else { ?> <html> <head> <title> Question page </title> <link rel="stylesheet" href="/nitesh/modified/style.css"> </head> <body> <nav> <div class="container"> <ul class="nav"> <li><a href="/nitesh/modified/logout.php">Logout</a></li> </ul> </div> </nav> <body> <center><h2>Result of&nbsp&nbsp<?php echo $_SESSION['seas_user'];?></h2></center> <div class="log1"> <fieldset> <legend> Score page</legend> <form action="#" method="post" id="quiz"> <?php $correct=0; $wrong=0; include'database.php'; $userid=$_SESSION['seas_user_id']; $subject_type =$_SESSION['values']; $sql = "SELECT * FROM questions ql,user_response us WHERE us.user_id=$userid AND us.question_id=ql.id AND us.subject_id=$subject_type"; ?> <?php $result = $con->query($sql); if ($result->num_rows > 0) { while($row = $result->fetch_assoc()) { ?> <?php if($row["option_id"]==$row["answer"]) { $correct++; } else { $wrong++; } ?> <?php } } $total_questions=$wrong+$correct; echo "<center><h3 >Total no of questions:$total_questions</h3></center></br>"; echo "<center><h3 >Correct answer: $correct</h3></center></br>"; echo "<center><h3 >wrong answer: $wrong</h3></center></br>"; $percentage=$correct/$total_questions*100; echo "<center><h3>percentage: $percentage</h3></center></br>"; if($percentage>=60) { $p="PASS"; echo "<center><h3>PASS</h3></center></br>"; } else { $p="FAIL"; echo "<center><h3>FAIL</h3></center></br>"; } $subject_type =$_SESSION['values']; $sql1= "SELECT * FROM test_status WHERE user_id='$userid' AND subject_type='$subject_type' AND $total_questions='10' "; $query = mysqli_query($con, $sql1); if(mysqli_num_rows($query) > 0) { echo "<br/><br/><span><center><h2>User id aleredy exist...!!<br/> Try with different :)</h2></center></span>"; } else{ $sql1= "INSERT INTO test_status (user_id,subject_type,total_question,correct_ans, wrong_ans,percentage,status,created_on,updated_on) values ('$userid','$subject_type','$total_questions', '$correct','$wrong','$percentage','$p', now(),now())"; if ($con->query($sql1) === TRUE) { } else { echo "Error: " . $sql . "<br>" . $con->error; } $con->close(); } } ?> </fieldset> </div> </body> </html><file_sep>/* SQLyog Community v12.2.2 (64 bit) MySQL - 5.6.30-0ubuntu0.14.04.1 : Database - nitesh ********************************************************************* */ /*!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*/`nitesh` /*!40100 DEFAULT CHARACTER SET latin1 */; USE `nitesh`; /*Table structure for table `admin_login` */ DROP TABLE IF EXISTS `admin_login`; CREATE TABLE `admin_login` ( `id` int(50) NOT NULL AUTO_INCREMENT, `admin_id` varchar(50) NOT NULL, `admin_pass` varchar(50) NOT NULL, `created_on` datetime(5) NOT NULL, `updated_on` datetime(5) NOT NULL, KEY `id` (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=latin1; /*Data for the table `admin_login` */ LOCK TABLES `admin_login` WRITE; insert into `admin_login`(`id`,`admin_id`,`admin_pass`,`created_on`,`updated_on`) values (1,'admin','<PASSWORD>','2016-06-28 17:31:01.00000','2016-06-28 17:31:01.00000'); UNLOCK TABLES; /*Table structure for table `questions` */ DROP TABLE IF EXISTS `questions`; CREATE TABLE `questions` ( `id` int(255) NOT NULL AUTO_INCREMENT, `q_type` int(25) NOT NULL, `img_url` varchar(40) NOT NULL, `question` tinytext NOT NULL, `answer1` varchar(255) NOT NULL, `answer2` varchar(255) NOT NULL, `answer3` varchar(255) NOT NULL, `answer4` varchar(255) NOT NULL, `answer` varchar(255) NOT NULL, `created_on` datetime(6) NOT NULL, `updated_on` datetime(6) NOT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=44 DEFAULT CHARSET=latin1; /*Data for the table `questions` */ LOCK TABLES `questions` WRITE; insert into `questions`(`id`,`q_type`,`img_url`,`question`,`answer1`,`answer2`,`answer3`,`answer4`,`answer`,`created_on`,`updated_on`) values (1,1,'','What Default Data Type ?','String','Variant','Integer','Boolear','2','2016-07-01 13:12:48.000000','2016-07-01 13:12:48.000000'), (2,1,'','What is Default Form Border Style ?','Fixed','Single','None','Sizeable','3','2016-07-01 13:16:24.000000','2016-07-01 13:16:24.000000'), (3,1,'','Which is not type of Control ?','text','lable','checkbox','option button','1','2016-07-01 13:17:18.000000','2016-07-01 13:17:18.000000'), (4,1,'','Which city is known as The City of Palaces','Kolkatta','Jerusalem','Mumbai','Udaipur','1','2016-07-01 13:18:07.000000','2016-07-01 13:18:07.000000'), (5,1,'','The Gateway of India is ?','Delhi','Kolkatta','Mumbai','Udaipur','3','2016-07-01 13:19:04.000000','2016-07-01 13:19:04.000000'), (6,1,'','Which city is known as Pink City?','Hyderabad','Jaipur','Mumbai','Udaipur','2','2016-07-01 13:20:00.000000','2016-07-01 13:20:00.000000'), (7,1,'','Which is the city of Golden Temple?','Amritsar','Banaras','Mumbai','Udaipur','1','2016-07-01 13:20:47.000000','2016-07-01 13:20:47.000000'), (8,1,'','The Land of Lilies ?','Finland','Banaras','Mumbai','Canada','4','2016-07-01 13:21:32.000000','2016-07-01 13:21:32.000000'), (9,1,'','The symbol dove signifies ?','Strength','Dignity','Peace','Distress','3','2016-07-01 13:22:29.000000','2016-07-01 13:22:29.000000'), (10,1,'','how year u old?','20','25','26','22','1','2016-07-01 14:11:05.000000','2016-07-01 14:11:05.000000'), (11,2,'','PC Stands for','pocket computer','personal computer','phisycal computer','personal','2','2016-07-01 16:19:03.000000','2016-07-01 16:19:03.000000'), (12,2,'','RAM Stands for','Random Access Memory','Random accelerated Memory','Random Access Machenism','Random Accurace Mantan','1','2016-07-01 16:20:06.000000','2016-07-01 16:20:06.000000'), (13,2,'','mouse is the type of device','input','pointing','scanning','none of the above','2','2016-07-01 16:21:28.000000','2016-07-01 16:21:28.000000'), (14,2,'','keybord is the type of device','input','pointing','scanning','none of the above','1','2016-07-01 16:22:02.000000','2016-07-01 16:22:02.000000'), (15,2,'','scanner is the type of device','input','pointing','scanning','none of the above','3','2016-07-01 16:22:38.000000','2016-07-01 16:22:38.000000'), (16,2,'','the touchable part of computer is called as','hardware','software','none','none of the above','1','2016-07-01 16:23:30.000000','2016-07-01 16:23:30.000000'), (17,2,'','to deleter the character towards left side is','backspace','del','inst','none of the above','1','2016-07-01 16:24:23.000000','2016-07-01 16:24:23.000000'), (18,2,'','to move the cursor beginning of the which key is used','end','home','pgup','pgdn','1','2016-07-01 16:25:37.000000','2016-07-01 16:25:37.000000'), (19,2,'','to move the cursor beginning of the which key is used','end','home','pgup','pgdn','2','2016-07-01 16:26:28.000000','2016-07-01 16:26:28.000000'), (20,2,'','f caps lock key is on then','small letters are printed','none','capital letters print','pgdn','3','2016-07-01 16:27:21.000000','2016-07-01 16:27:21.000000'), (21,3,'','business is?','money','strategy','mind','game','1','2016-07-02 22:52:43.000000','2016-07-02 22:52:43.000000'), (22,3,'','play business like?','money','strategy','mind','game','4','2016-07-02 22:54:42.000000','2016-07-02 22:54:42.000000'), (23,3,'Screenshot from 2016-06-15 16:11:44.png','what u see in image?','logic ','none','game ','picture','none','2016-07-04 00:00:32.000000','2016-07-04 00:00:32.000000'), (24,1,'','mumbai lies inside?','india','pakistan','us','uk','1','2016-07-08 16:09:01.000000','2016-07-08 16:09:01.000000'), (25,1,'','delhi lies inside?','india','pakistan','us','uk','1','2016-07-08 16:09:13.000000','2016-07-08 16:09:13.000000'), (26,1,'','panjab lies inside?','india','pakistan','us','uk','1','2016-07-08 16:09:27.000000','2016-07-08 16:09:27.000000'), (27,1,'','us','united state','use system','uk','us','1','2016-07-08 16:10:05.000000','2016-07-08 16:10:05.000000'), (28,2,'','linux is?','os','kernel','platform','os','2','2016-07-08 16:18:34.000000','2016-07-08 16:18:34.000000'), (29,2,'','windows is?','os','kernel','platform','as','1','2016-07-08 16:18:56.000000','2016-07-08 16:18:56.000000'), (30,2,'','pantos is?','os','kernel','platform','as','2','2016-07-08 16:19:17.000000','2016-07-08 16:19:17.000000'), (31,2,'','cmos battery present on ?','motherbord ','display','hdd','ram','1','2016-07-08 16:20:00.000000','2016-07-08 16:20:00.000000'), (32,2,'','processer present on ?','motherbord ','display','hdd','ram','1','2016-07-08 16:20:27.000000','2016-07-08 16:20:27.000000'), (33,2,'','click nois error is due to present on ?','motherbord ','display','hdd','ram','3','2016-07-08 16:20:55.000000','2016-07-08 16:20:55.000000'), (34,3,'9ba25796112cad616be27e473ae1e149.jpg','character identification?','tom','jerry','banna','bheem','1','2016-07-08 23:42:06.000000','2016-07-08 23:42:06.000000'), (35,3,'images (2).jpg','character identification?','tom','jerry','banna','bheem','2','2016-07-08 23:42:36.000000','2016-07-08 23:42:36.000000'), (36,3,'images (1).jpg','character identification?','tom','jerry','banna','minnions','4','2016-07-08 23:43:03.000000','2016-07-08 23:43:03.000000'), (37,3,'images (3).jpg','character identification?','tom','jerry','novita','minnions','3','2016-07-08 23:43:22.000000','2016-07-08 23:43:22.000000'), (38,3,'images (4).jpg','character identification?','tom','scooby','novita','minnions','2','2016-07-08 23:43:47.000000','2016-07-08 23:43:47.000000'), (39,3,'images.jpg','character identification?','hero','scooby','novita','minnions','1','2016-07-08 23:44:13.000000','2016-07-08 23:44:13.000000'), (40,3,'sql.png','what u see in pic?','database','game','only table','none','1','2016-07-09 13:14:44.000000','2016-07-09 13:14:44.000000'), (41,3,'','hey?','a','b','c','d','1','2016-07-14 15:26:04.000000','2016-07-14 15:26:04.000000'), (42,3,'','pic?','1','2','3','5','3','2016-07-14 16:44:12.000000','2016-07-14 16:44:12.000000'), (43,3,'multiple_series.jpg','pic?','1','2','3','5','3','2016-07-14 16:44:50.000000','2016-07-14 16:44:50.000000'); UNLOCK TABLES; /*Table structure for table `subject_status` */ DROP TABLE IF EXISTS `subject_status`; CREATE TABLE `subject_status` ( `id` int(40) NOT NULL AUTO_INCREMENT, `user_id` varchar(10) NOT NULL, `status` varchar(10) NOT NULL, `subject_type` int(10) NOT NULL, `created_on` datetime(5) DEFAULT NULL, `updated_on` datetime(5) DEFAULT NULL, KEY `id` (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=10 DEFAULT CHARSET=latin1; /*Data for the table `subject_status` */ LOCK TABLES `subject_status` WRITE; insert into `subject_status`(`id`,`user_id`,`status`,`subject_type`,`created_on`,`updated_on`) values (1,'1','1',1,'2016-07-14 13:48:36.00000','2016-07-14 13:48:36.00000'), (2,'1','0',2,'2016-07-14 13:42:28.00000','2016-07-14 13:42:28.00000'), (3,'1','0',3,'2016-07-14 13:42:31.00000','2016-07-14 13:42:31.00000'), (4,'2','1',1,'2016-07-14 16:27:08.00000','2016-07-14 16:27:08.00000'), (5,'2','1',2,'2016-07-14 16:30:30.00000','2016-07-14 16:30:30.00000'), (6,'2','1',3,'2016-07-14 16:42:24.00000','2016-07-14 16:42:24.00000'), (7,'3','1',1,'2016-07-14 17:07:23.00000','2016-07-14 17:07:23.00000'), (8,'3','0',2,'2016-07-14 17:06:48.00000','2016-07-14 17:06:48.00000'), (9,'3','0',3,'2016-07-14 17:06:50.00000','2016-07-14 17:06:50.00000'); UNLOCK TABLES; /*Table structure for table `test_status` */ DROP TABLE IF EXISTS `test_status`; CREATE TABLE `test_status` ( `id` int(255) NOT NULL AUTO_INCREMENT, `user_id` varchar(255) NOT NULL, `total_question` int(255) NOT NULL, `correct_ans` int(255) NOT NULL, `wrong_ans` int(255) NOT NULL, `percentage` float NOT NULL, `status` varchar(255) NOT NULL, `created_on` datetime(5) NOT NULL, `updated_on` datetime(5) NOT NULL, KEY `id` (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=8 DEFAULT CHARSET=latin1; /*Data for the table `test_status` */ LOCK TABLES `test_status` WRITE; insert into `test_status`(`id`,`user_id`,`total_question`,`correct_ans`,`wrong_ans`,`percentage`,`status`,`created_on`,`updated_on`) values (1,'2',10,1,9,10,'FAIL','2016-07-14 16:27:12.00000','2016-07-14 16:27:12.00000'), (2,'2',10,1,9,10,'FAIL','2016-07-14 16:27:30.00000','2016-07-14 16:27:30.00000'), (3,'2',10,2,8,20,'FAIL','2016-07-14 16:30:36.00000','2016-07-14 16:30:36.00000'), (4,'2',10,2,8,20,'FAIL','2016-07-14 16:30:52.00000','2016-07-14 16:30:52.00000'), (5,'1',0,0,0,0,'FAIL','2016-07-14 16:32:27.00000','2016-07-14 16:32:27.00000'), (6,'2',10,2,8,20,'FAIL','2016-07-14 16:42:27.00000','2016-07-14 16:42:27.00000'), (7,'3',10,3,7,30,'FAIL','2016-07-14 17:07:27.00000','2016-07-14 17:07:27.00000'); UNLOCK TABLES; /*Table structure for table `user_registration` */ DROP TABLE IF EXISTS `user_registration`; CREATE TABLE `user_registration` ( `user_id` int(10) NOT NULL AUTO_INCREMENT, `user_name` varchar(200) NOT NULL, `user_email` varchar(200) NOT NULL, `user_userid` varchar(200) NOT NULL, `user_passid` varchar(200) NOT NULL, `user_country` varchar(200) NOT NULL, `created_on` datetime(5) NOT NULL, `updated_on` datetime(5) NOT NULL, KEY `student_id` (`user_id`) ) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=latin1; /*Data for the table `user_registration` */ LOCK TABLES `user_registration` WRITE; insert into `user_registration`(`user_id`,`user_name`,`user_email`,`user_userid`,`user_passid`,`user_country`,`created_on`,`updated_on`) values (1,'nitesh','<EMAIL>','nitesh','12345','male','2016-07-14 13:41:38.00000','2016-07-14 13:41:38.00000'), (2,'vikas','<EMAIL>','vikas','12345','male','2016-07-14 16:26:19.00000','2016-07-14 16:26:19.00000'), (3,'gaurav','<EMAIL>','gaurav','12345','male','2016-07-14 17:03:20.00000','2016-07-14 17:03:20.00000'); UNLOCK TABLES; /*Table structure for table `user_response` */ DROP TABLE IF EXISTS `user_response`; CREATE TABLE `user_response` ( `subject_id` varchar(10) NOT NULL, `user_id` int(10) NOT NULL, `question_id` int(10) NOT NULL, `option_id` int(255) NOT NULL, `created_on` datetime(6) NOT NULL, `updated_on` datetime(6) NOT NULL, KEY `user_id` (`user_id`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1; /*Data for the table `user_response` */ LOCK TABLES `user_response` WRITE; insert into `user_response`(`subject_id`,`user_id`,`question_id`,`option_id`,`created_on`,`updated_on`) values ('1',1,8,1,'2016-07-14 13:43:58.000000','2016-07-14 13:43:58.000000'), ('1',1,5,1,'2016-07-14 13:44:04.000000','2016-07-14 13:44:04.000000'), ('1',1,6,2,'2016-07-14 13:44:07.000000','2016-07-14 13:44:07.000000'), ('1',1,25,1,'2016-07-14 13:44:09.000000','2016-07-14 13:44:09.000000'), ('1',1,10,1,'2016-07-14 13:44:11.000000','2016-07-14 13:44:11.000000'), ('1',1,26,1,'2016-07-14 13:44:12.000000','2016-07-14 13:44:12.000000'), ('1',1,27,1,'2016-07-14 13:44:15.000000','2016-07-14 13:44:15.000000'), ('1',1,3,2,'2016-07-14 13:44:19.000000','2016-07-14 13:44:19.000000'), ('1',1,1,3,'2016-07-14 13:44:22.000000','2016-07-14 13:44:22.000000'), ('1',1,9,2,'2016-07-14 13:44:26.000000','2016-07-14 13:44:26.000000'), ('1',2,3,3,'2016-07-14 16:26:55.000000','2016-07-14 16:26:55.000000'), ('1',2,7,4,'2016-07-14 16:26:57.000000','2016-07-14 16:26:57.000000'), ('1',2,1,4,'2016-07-14 16:26:59.000000','2016-07-14 16:26:59.000000'), ('1',2,5,4,'2016-07-14 16:27:00.000000','2016-07-14 16:27:00.000000'), ('1',2,10,4,'2016-07-14 16:27:02.000000','2016-07-14 16:27:02.000000'), ('1',2,25,4,'2016-07-14 16:27:03.000000','2016-07-14 16:27:03.000000'), ('1',2,6,3,'2016-07-14 16:27:04.000000','2016-07-14 16:27:04.000000'), ('1',2,27,4,'2016-07-14 16:27:06.000000','2016-07-14 16:27:06.000000'), ('1',2,8,3,'2016-07-14 16:27:07.000000','2016-07-14 16:27:07.000000'), ('1',2,2,3,'2016-07-14 16:27:08.000000','2016-07-14 16:27:08.000000'), ('2',2,14,1,'2016-07-14 16:30:18.000000','2016-07-14 16:30:18.000000'), ('2',2,11,3,'2016-07-14 16:30:19.000000','2016-07-14 16:30:19.000000'), ('2',2,29,3,'2016-07-14 16:30:20.000000','2016-07-14 16:30:20.000000'), ('2',2,30,3,'2016-07-14 16:30:25.000000','2016-07-14 16:30:25.000000'), ('2',2,20,3,'2016-07-14 16:30:26.000000','2016-07-14 16:30:26.000000'), ('2',2,28,4,'2016-07-14 16:30:27.000000','2016-07-14 16:30:27.000000'), ('2',2,16,4,'2016-07-14 16:30:28.000000','2016-07-14 16:30:28.000000'), ('2',2,19,4,'2016-07-14 16:30:29.000000','2016-07-14 16:30:29.000000'), ('2',2,18,4,'2016-07-14 16:30:30.000000','2016-07-14 16:30:30.000000'), ('2',2,12,4,'2016-07-14 16:30:30.000000','2016-07-14 16:30:30.000000'), ('2',1,12,1,'2016-07-14 16:32:37.000000','2016-07-14 16:32:37.000000'), ('3',2,23,3,'2016-07-14 16:42:09.000000','2016-07-14 16:42:09.000000'), ('3',2,39,4,'2016-07-14 16:42:10.000000','2016-07-14 16:42:10.000000'), ('3',2,37,2,'2016-07-14 16:42:11.000000','2016-07-14 16:42:11.000000'), ('3',2,38,3,'2016-07-14 16:42:13.000000','2016-07-14 16:42:13.000000'), ('3',2,35,3,'2016-07-14 16:42:14.000000','2016-07-14 16:42:14.000000'), ('3',2,36,3,'2016-07-14 16:42:15.000000','2016-07-14 16:42:15.000000'), ('3',2,22,4,'2016-07-14 16:42:17.000000','2016-07-14 16:42:17.000000'), ('3',2,34,3,'2016-07-14 16:42:20.000000','2016-07-14 16:42:20.000000'), ('3',2,21,2,'2016-07-14 16:42:22.000000','2016-07-14 16:42:22.000000'), ('3',2,40,1,'2016-07-14 16:42:24.000000','2016-07-14 16:42:24.000000'), ('1',3,25,1,'2016-07-14 17:06:57.000000','2016-07-14 17:06:57.000000'), ('1',3,24,1,'2016-07-14 17:06:59.000000','2016-07-14 17:06:59.000000'), ('1',3,1,3,'2016-07-14 17:07:02.000000','2016-07-14 17:07:02.000000'), ('1',3,5,1,'2016-07-14 17:07:06.000000','2016-07-14 17:07:06.000000'), ('1',3,27,2,'2016-07-14 17:07:08.000000','2016-07-14 17:07:08.000000'), ('1',3,6,3,'2016-07-14 17:07:11.000000','2016-07-14 17:07:11.000000'), ('1',3,7,4,'2016-07-14 17:07:14.000000','2016-07-14 17:07:14.000000'), ('1',3,2,2,'2016-07-14 17:07:18.000000','2016-07-14 17:07:18.000000'), ('1',3,3,1,'2016-07-14 17:07:21.000000','2016-07-14 17:07:21.000000'), ('1',3,8,1,'2016-07-14 17:07:23.000000','2016-07-14 17:07:23.000000'); UNLOCK TABLES; /*!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 session_start(); if(!isset($_SESSION['seas_user'])) { header("location:/nitesh/modified/login.html"); } else { ?> <html> <head> <title> Question page </title> <link rel="stylesheet" href="/nitesh/modified/style.css"> </head> <body> <nav> <div class="container"> <ul class="nav"> <li><a href="logout.php">Logout</a></li> </ul> </div> </nav> <body> <center><h2>Result of&nbsp&nbsp<?php echo $_SESSION['seas_user'];?></h2></center> <div class="log1"> <fieldset> <legend> User Results</legend> <form action="user_response.php" method="post" id="quiz"> <?php require'database.php'; $userid=$_SESSION['seas_user_id']; $subject_type =$_SESSION['values']; $sql = "SELECT * FROM questions ql,user_response us WHERE us.user_id=$userid AND us.question_id=ql.id AND us.subject_id=$subject_type"; ?> <?php $result = $con->query($sql); if ($result->num_rows > 0) { while($row = $result->fetch_assoc()) { ?> <h3><?php echo $row["question"]; ?></h3> <input type="hidden" id="question_id" name="question_id" value="<?php echo $row["id"]; ?>" /> <div> <input id="1" type="hidden" name="answer" value="<?php echo $row["option_id"]; ?> " /> option: <?php echo $row["option_id"]; ?> &nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp correct:<?php echo $row["answer"]; ?> </div> <?php } } } ?> <center><a href="/nitesh/modified/score.php"/>result</center> </fieldset> </div> </body> </html><file_sep><?php session_start(); if(!isset($_SESSION['seas_user'])) { header("location:/nitesh/modified/login.html"); } else { include'database.php'; $userid=$_SESSION['seas_user_id']; $subject_type=$_SESSION['values']; $sql="UPDATE `nitesh`.`subject_status` SET `status` = '1' , `created_on` = now() ,`updated_on` = now() WHERE `user_id` = '$userid' AND `status` = '0' AND `subject_type` = '$subject_type'"; if ($con->query($sql) === TRUE) { header("location:/nitesh/modified/result.php"); } else { echo "Error: " . $sql . "<br>" . $con->error; } mysqli_close($con); } ?> <file_sep>function formValidation() { var userid = document.registration.userid; var userpass = document.registration.userpass; var username = document.registration.username; var gender = document.registration.gender; var useremail = document.registration.useremail; if(userid_validation(userid,5,20)) { if(passid_validation(userpass,5,20)) { if(allLetter(username)) { if(countryselect(gender)) { if(ValidateEmail(useremail)) { return true; } } } } } return false; }; function userid_validation(userid,mx,my) { var uidlen = userid.value.length; if (uidlen == 0 || uidlen >= my || uidlen < mx) { alert("User Id should not be empty / length be between "+mx+" to "+my); userid.focus(); return false; } return true; } function passid_validation(userpass,mx,my) { var passid_len = userpass.value.length; if (passid_len == 0 ||passid_len >= my || passid_len < mx) { alert("Password should not be empty / length be between "+mx+" to "+my); userpass.focus(); return false; } return true; } function allLetter(username) { var letters = /^[A-Za-z]+$/; if(username.value.match(letters)) { return true; } else { alert('Username must have alphabet characters only'); username.focus(); return false; } } function countryselect(gender) { if(gender.value == "Default") { alert('Select your Gender from the list'); gender.focus(); return false; } else { return true; } } function ValidateEmail(useremail) { var mailformat = /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/; if(useremail.value.match(mailformat)) { return true; } else { alert("You have entered an invalid email address!"); useremail.focus(); return false; } } <file_sep><?php require 'database.php'; if(isset($_POST['submit'])) { $username = $_POST['username']; $useremail = $_POST['useremail']; $userid = $_POST['userid']; $userpass = $_POST['userpass']; $gender = $_POST['gender']; $sql= "SELECT * FROM user_registration WHERE user_userid='$userid' "; $query = mysqli_query($con, $sql); if(mysqli_num_rows($query) > 0) { echo "<br/><br/><span><center><h2>User id aleredy exist...!!<br/> Try with different :)</h2></center></span>"; } else { if($username !=''&&$useremail !=''&&$userid !=''&&$userpass !=''&&$gender !='') { $sql = "INSERT INTO user_registration(user_name, user_email, user_userid, user_passid, user_country,created_on,updated_on) values ('$username', '$useremail', '$userid', '$userpass','$gender',now(),now())"; if($con->query($sql) === TRUE) { header('Location:login.html'); } else { echo "Error: " . $sql . "<br>" . $con->error; } } } } $con->close(); ?> <file_sep><?php session_start(); if(!isset($_SESSION['seas_user'])) { header("location:/nitesh/modified/login.html"); } else { if(isset($_SESSION['QuestionCount']) && $_SESSION['QuestionCount']==10) { header("location:/nitesh/modified/subject_status_update.php"); } ?> <html> <head> <title> Question page </title> <script LANGUAGE="JavaScript"> function ValidateForm(form) { ErrorText= ""; if ( ( form.answer[0].checked == false ) && ( form.answer[1].checked == false ) && ( form.answer[2].checked == false )&& ( form.answer[3].checked == false )) { alert ( "Please choose Option" ); return false; } if (ErrorText= "") { form.submit() } } </script> <link rel="stylesheet" href="/nitesh/modified/style.css"> </head> <body> <nav> <div class="container"> <ul class="nav"> <li><a href="/nitesh/modified/logout.php">Logout</a></li> </ul> </div> </nav> <center><h2>Welcome&nbsp&nbsp<?=$_SESSION['seas_user'];?></h2></center> <div class="log1"> <fieldset> <legend> Question page</legend> <form action="/nitesh/modified/user_response.php" method="post" id="quiz"> <?php if(!isset($_SESSION['QuestionCount'])||$_SESSION['QuestionCount']==null) { $_SESSION['QuestionCount']=0; } if(isset($_GET['type'])) { $_SESSION['values']=$_GET['type']; $subject_type=$_SESSION['values']; } include'database.php'; $userid=$_SESSION['seas_user_id']; $sql="SELECT * FROM subject_status WHERE user_id='".$userid."' AND subject_type='".$subject_type."' AND status='1' "; $query = mysqli_query($con,$sql ); if(mysqli_num_rows($query) > 0) { echo "<br/><br/><span><center><h2>User aleredy made test...!!<br/> If u want give another subject test :)</h2></center></span>"; } else { $qid_arr = implode(',',$_SESSION['q_id']); echo $_SESSION['count']; if($_SESSION['count']==0) { // echo hey; //exit(); $sql= "SELECT us.subject_id,us.user_id,question_id FROM subject_status ss JOIN user_response us ON us.user_id=ss.user_id AND us.subject_id = ss.subject_type WHERE us.user_id='$userid' AND us.subject_id='$subject_type' AND ss.status='0'"; //print_r($sql); //exit(); $result = mysqli_query($con,$sql ); //$cnt=1; //result = $con->query($sql1); if ($result->num_rows > 0 && $result->num_rows >$_SESSION['count']) { while($row = $result->fetch_assoc()) { $_SESSION['count']++; //exit(); //$questions_in_db= $row['question_id']; //$_SESSION['q_id']=$row['question_id']; //print_r($_SESSION['q_id']); //$qid_arr = implode(',',$_SESSION['q_id']); array_push($_SESSION['q_id'],$row['question_id']); //exit(); //$cnt++; } $_SESSION['QuestionCount']=$_SESSION['count']; } } //echo $_SESSION['QuestionCount']; print_r($_SESSION['q_id']); print_r($qid_arr); //exit(); $sql = "SELECT id,img_url, question, answer1, answer2, answer3, answer4, answer FROM questions where q_type='$subject_type' AND id NOT IN ($qid_arr) ORDER BY RAND() LIMIT 1"; ?> <?php $result = $con->query($sql); if ($result->num_rows > 0) { while($row = $result->fetch_assoc()) { ?> <?php array_push($_SESSION['q_id'], $row["id"]); ?> <h3>Q:<?php echo $_SESSION['QuestionCount']; ?>)&nbsp&nbsp<?php echo $row["question"]; ?></h3></br> &nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp <?php if($row["img_url"]!='') { ?> <img src="/nitesh/final_project_of_quix/images/<?php echo $row["img_url"]; ?>" width="250px" height="150px"/> <?php } ?> <input type="hidden" id="question_id" name="question_id" value="<?php echo $row["id"]; ?>" /> <div> <input id="1" type="radio" name="answer" value="1" /> <label for="1">1)&nbsp; <?php echo $row["answer1"]; ?> </label> </div> <div> <input id="2" type="radio" name="answer" value="2" /> <label for="2">2)&nbsp; <?php echo $row["answer2"]; ?> </label> </div> <div> <input id="3" type="radio" name="answer" value="3" /> <label for="3">3)&nbsp; <?php echo $row["answer3"]; ?> </label> </div> <div> <input id="4" type="radio" name="answer" value="4" /> <label for="4">4)&nbsp; <?php echo $row["answer4"]; ?> </label> </div> <?php } } ?> <input type="submit" class="hvr-grow" name="submit" value="Next" onClick="return ValidateForm(this.form)" /> </form> </fieldset> </div> </body> </html> <?php echo $_SESSION['QuestionCount']; } } ?> <file_sep><?php session_start(); if(!isset($_SESSION['seas_user'])) { header("location:/nitesh/modified/login.html"); } else { include'database.php'; if(isset($_POST['submit'])) { $_SESSION['QuestionCount'] = $_SESSION['QuestionCount']+1; } $userid=$_SESSION['seas_user_id'];/////////////////// $q_id=$_POST['question_id'];////////// $answer=$_POST['answer'];/////////////// $subject_type=$_SESSION['values']; $sql= "INSERT INTO user_response(subject_id,user_id, question_id, option_id,created_on,updated_on) values ($subject_type,$userid, $q_id, $answer, now(),now())"; // header("location:question.php"); if ($con->query($sql) === TRUE) { echo "New record created successfully"; } else { echo "Error: " . $sql . "<br>" . $con->error; } header("location:/nitesh/modified/question.php/?type=$subject_type"); $conn->close(); } ?> <file_sep><?php session_start(); ?> <?php if($_FILES['image']['name'] != ''||$_FILES['image']['name'] == '') { $errors= array(); $file_name = $_FILES['image']['name']; $file_size = $_FILES['image']['size']; $file_tmp = $_FILES['image']['tmp_name']; $file_type = $_FILES['image']['type']; $a=explode('.',$_FILES['image']['name']); $file_ext=strtolower(end($a)); $expensions= array("jpeg","jpg","png"); if(in_array($file_ext,$expensions)=== false) { $errors[]="extension not allowed, please choose a JPEG or PNG file."; } if($file_size > 2097152) { $errors[]='File size must be excately 2 MB'; } if(empty($errors)==true) { move_uploaded_file($file_tmp,dirname(__DIR__)."/final_project_of_quix/images/".$file_name); $fileupload = $file_name; } else { $fileupload = ''; } include'database.php'; $q_type = $_POST['type']; $question = $_POST['question']; $q_option1 = $_POST['option1']; $q_option2 = $_POST['option2']; $q_option3 = $_POST['option3']; $q_option4 = $_POST['option4']; $q_answer = $_POST['correct']; if($q_type !=''&&$question !=''&&$q_option1 !=''&&$q_option2 !=''&&$q_option3 !=''&&$q_option4 !=''&&$q_answer !='') { $sql= "INSERT INTO questions (q_type,img_url,question, answer1,answer2,answer3,answer4, answer,created_on,updated_on) values ('$q_type','$fileupload', '$question', '$q_option1','$q_option2','$q_option3','$q_option4','$q_answer', now(),now())"; if ($con->query($sql) === TRUE) { echo "<center><h2>Data inserted Successfully</h2></center>"; } else { echo "Error: " . $sql . "<br>" . $con->error; } } $con->close(); } ?> <file_sep><?php define('DB_HOST', 'localhost'); define('DB_NAME', 'nitesh'); define('DB_USER','Nitesh'); define('DB_PASSWORD','<PASSWORD>'); $con=mysqli_connect(DB_HOST,DB_USER,DB_PASSWORD) or die("Failed to connect to MySQL: " . mysqli_connect_error()); $db=mysqli_select_db($con, DB_NAME) or die("Failed to connect to MySQL: " . mysqli_connect_error()); ?><file_sep><?php session_start(); ?> <?php include 'database.php'; $adminid = $_POST['adminid']; $adminpass = $_POST['<PASSWORD>']; $sql="SELECT * FROM admin_login WHERE admin_id='".$adminid."' and admin_pass='".$adminpass."' "; $result=mysqli_query($con,$sql); $count=mysqli_num_rows($result); if ($result->num_rows > 0) { while($row = $result->fetch_assoc()) { if($count==1) { $_SESSION['seas_admin']=$adminid; header('Location:/nitesh/modified/admin_options.php'); } } } else { echo "<center><h2>Wrong Username or Password</br> Please check your </b> Id and Password </h2></center>"; } ?>
b2ee7abb2004e45ffb373c532582defdeb99b7a1
[ "JavaScript", "SQL", "PHP" ]
14
PHP
jhanitesh10/online_test
d50e364ec2ab07d67c7998df778a6d2af3952161
2acf43b44f086f17ffd5d24efcc7ded6a10698b8
refs/heads/master
<file_sep>import asyncpg import logging import os __all__ = ("pg_engine", "get_db", "asyncpg") __db: asyncpg.pool.Pool = None async def pg_engine(app): global __db logging.info("Подключаемся к базе данных") if os.getenv("IS_CONTAINER", False): from time import sleep for _ in range(10): try: __db = await asyncpg.create_pool(host="db", user="postgres", database="postgres", password="123") del sleep break except ConnectionRefusedError: sleep(0.2) else: raise ConnectionError("Нет доступа к базе данных!") else: __db = await asyncpg.create_pool(host="localhost", user="postgres", database="postgres", password="123") yield await __db.close() def get_db() -> asyncpg.pool.Pool: assert __db return __db <file_sep>from aiohttp.web import Application from .database import pg_engine, get_db from .routers import routers, init as init_r import logging import os logging.basicConfig( format="%(asctime)s [%(levelname)s] module:'%(module)s' line:%(lineno)s - %(message)s", datefmt='%m.%d.%Y %H:%M:%S', level=logging.ERROR if os.getenv("IS_CONTAINER", False) else logging.INFO ) def init(app: Application): app.cleanup_ctx.append(pg_engine) app.on_startup.append(init_r) <file_sep>from random import randint from asyncio import gather from time import perf_counter from .util import * from .name_generator import NameGenerator def test_many_requests(loop): async def _test(): ng = NameGenerator() async with aiohttp.ClientSession() as session: await delete_all(session) # Очищаем все данные перед тестом tasks = [] for _ in range(1000): tasks.append(loop.create_task(check(session.post, "companies", {'name': next(ng)}, 200, empty_schema))) if randint(0, 10) == 1: tasks.append(loop.create_task(check(session.get, "companies", {}, 200, content_schema))) begin = perf_counter() await gather(*tasks) t = perf_counter() - begin print() print(len(tasks), "requests") print(f"{t:.3F}s ({t/len(tasks):.6F} s/request)") loop.run_until_complete(_test()) <file_sep>from asyncio import gather from functools import partial from typing import Callable, Awaitable from .util import * def test_company(loop): company_schema = { "type": "object", "properties": { "name": {"type": "string"} }, "required": ["name"], "additionalProperties": False } async def _test(): err_params = [ {"name": "A"}, {"name": "A12"}, {"name": "123456"}, {"name": "New", "id": 17}, {} ] tasks = [] async with aiohttp.ClientSession() as session: await delete_all(session) check_add: Callable[[dict, int, dict], Awaitable[dict]] = partial(check, session.post, "companies") check_list: Callable[[dict, int, dict], Awaitable[dict]] = partial(check, session.get, "companies", {}, 200, content_schema) for p in err_params: tasks.append(loop.create_task(check_add(p, 422, error_schema))) await gather(*tasks) del tasks await check_add({"name": "Company"}, 200, empty_schema) await check_add({"name": "Company"}, 208, error_schema) await check_add({"name": "NewCompany"}, 200, empty_schema) companies = [] for i in (await check_list())["content"]: jsonschema.validate(i, company_schema) companies.append(i['name']) assert companies == ["Company", "NewCompany"] loop.run_until_complete(_test()) <file_sep>from asyncio import gather from functools import partial from .util import * def test_staff(loop): person_schema = { "type": "object", "properties": { "name": { "type": "string", "pattern": "^[A-Z][a-z]+$" }, "companies": { "type": "array" }, "id": { "type": "integer" } }, "required": ["name", "companies", "id"], "additionalProperties": False } async def setup(): """ Очищаем все таблицы и создаем компании, к которым будем назначать сотрудников """ async with aiohttp.ClientSession() as session: await delete_all(session) await check(session.post, "companies", {"name": "Google"}, 200, empty_schema) await check(session.post, "companies", {"name": "Apple"}, 200, empty_schema) await check(session.post, "companies", {"name": "JetBrains"}, 200, empty_schema) async def _test(): err_params_and_code = [ ({"name": "Tim1", "company": "Apple"}, 422), ({"name": "Tim", "company": "Russia"}, 400), ({"name": "A12"}, 422), ({"name": "Tim"}, 422), ({"nam": "Tim", "company": "Apple"}, 422), ({"company": "Apple"}, 422), ({"name": "New", "id": 17}, 422), ({}, 422) ] tasks = [] async with aiohttp.ClientSession() as session: check_addtoc = partial(check, session.put, "staff") check_add = partial(check, session.post, "staff") check_list = partial(check, session.get, "staff", {}, 200, content_schema) for p, c in err_params_and_code: tasks.append(loop.create_task(check_add(p, c, error_schema))) await gather(*tasks) del tasks await check_add({"name": "Tim", "company": "Apple"}, 200, empty_schema) await check_add({"name": "Tim", "company": "Apple"}, 200, empty_schema) # У Apple не один Тим await check_add({"name": "Sundar", "company": "Google"}, 200, empty_schema) await check_add({"name": "Oleg", "company": "JetBrains"}, 200, empty_schema) staff = set() oleg_id = None for i in (await check_list())["content"]: jsonschema.validate(i, person_schema) staff.add((i["name"], frozenset(i["companies"]))) if i["name"] == "Oleg": assert not oleg_id oleg_id = i["id"] assert staff == {("Tim", frozenset(("Apple", ))), ("Tim", frozenset(("Apple", ))), ("Sundar", frozenset(("Google", ))), ("Oleg", frozenset(("JetBrains", )))} staff = set() await check_addtoc({"id": oleg_id, "company": "Google"}, 200, empty_schema) await check_addtoc({"id": oleg_id, "company": "Gogle"}, 400, error_schema) await check_addtoc({"id": 1000, "company": "Google"}, 400, error_schema) del oleg_id for i in (await check_list())["content"]: jsonschema.validate(i, person_schema) staff.add((i["name"], frozenset(i["companies"]))) assert staff == {("Tim", frozenset(("Apple",))), ("Tim", frozenset(("Apple",))), ("Sundar", frozenset(("Google",))), ("Oleg", frozenset(("JetBrains", "Google",)))} loop.run_until_complete(setup()) loop.run_until_complete(_test()) <file_sep>API ------- ------- #### post /company Добавляет компанию Обязательные параметры: - name - название компании ----- #### get /company Возвращает список всех компаний ----- #### post /staff Добавляет работника Обязательные параметры: - name - имя работника - company - название компании(она должна уже существовать) ----- #### put /staff Добавляет работника к компании Обязательные параметры: - id - id работника(он должен уже существовать) - company - название компании(она должна уже существовать) ----- #### get /staff Возвращает список персонала ----- ### post /products Добавляет продукт Обязательные параметры: - name - название продукта Дополнительные параметры: - employee_id - id ответственного сотрудника ------ ### put /products Назначает продукту отвецственного сотрудника Обязательные параметры: - name - название продукта - employee_id - id ответственного сотрудника ------ ### get /products Возвращает список продуктов ------ ### delete / Удаляет все данные ------ <file_sep>FROM python:3.7 WORKDIR /usr/src/app COPY container_requirements.txt main.py ./ COPY ./server ./server RUN pip install --no-cache-dir -r container_requirements.txt CMD ["python", "-OO", "main.py"] <file_sep>from aiohttp import web from server import init as server_init import logging app = web.Application() server_init(app) logging.info("Сервер запущен") web.run_app(app) logging.error("Сервер остановлен") <file_sep>import pytest import asyncio @pytest.fixture() def loop(): res = asyncio.new_event_loop() yield res res.close() <file_sep>import aiohttp import jsonschema from typing import Callable error_schema = { "type": "object", "properties": { "error": {"type": "string"} }, "required": ["error"], "additionalProperties": False } empty_schema = { "type": "object", "maxProperties": 0 } content_schema = { "type": "object", "properties": { "content": { "type": "array", "items": { "type": "object" } } }, "required": ["content"], "additionalProperties": False } async def delete_all(session: aiohttp.ClientSession): async with session.delete('http://0.0.0.0:8080/') as resp: assert resp.status == 200 async def check(method: Callable, src: str, params: dict, expect_status: int, expect_json_schema: dict) -> dict: async with method(f'http://0.0.0.0:8080/{src}', params=params) as resp: assert resp.status == expect_status json: dict = await resp.json() jsonschema.validate(json, expect_json_schema) return json <file_sep>from asyncio import gather from functools import partial from typing import Callable, Awaitable import dataclasses import random from .util import * @dataclasses.dataclass(frozen=True) class Product: name: str employee_id: int = None product_schema = { "type": "object", "properties": { "name": { "type": "string" }, "employee_id": { "type": "integer" } }, "required": ["name"], "additionalProperties": False } def test_products(loop): async def setup(): """ Очищаем все таблицы. создаем компании и сотрудников """ async with aiohttp.ClientSession() as session: await delete_all(session) # очистка таблиц get = partial(check, session.get) post = partial(check, session.post) # добавляем компании await post("companies", {"name": "Google"}, 200, empty_schema) await post("companies", {"name": "Apple"}, 200, empty_schema) await post("companies", {"name": "JetBrains"}, 200, empty_schema) # добавляем людей await post("staff", {"name": "Sundar", "company": "Google"}, 200, empty_schema) await post("staff", {"name": "Tim", "company": "Apple"}, 200, empty_schema) await post("staff", {"name": "Oleg", "company": "JetBrains"}, 200, empty_schema) # получаем id добавленных людей for i in (await get("staff", {}, 200, content_schema))["content"]: available_staff_ids.add(i["id"]) assert len(available_staff_ids) == 3 async def _test(): err_params_and_code = [ ({"name": "product", "employee_id": max(available_staff_ids) + 1}, 400), ({"name": "product", "employee_id": "hello!"}, 422), ({"name": "Tim", "employee_id": random.choice(available_staff_ids), "add": ""}, 422), ({"employee_id": random.choice(available_staff_ids)}, 422), ({}, 422) ] tasks = [] async with aiohttp.ClientSession() as session: check_add: Callable[[dict, int, dict], Awaitable[dict]] = partial(check, session.post, "products") check_set: Callable[[dict, int, dict], Awaitable[dict]] = partial(check, session.put, "products") check_list: Callable[[dict, int, dict], Awaitable[dict]] = partial(check, session.get, "products", {}, 200, content_schema) for p, c in err_params_and_code: tasks.append(loop.create_task(check_add(p, c, error_schema))) await gather(*tasks) del tasks await check_add({"name": "p1"}, 200, empty_schema) await check_add({"name": "p1"}, 208, error_schema) await check_add({"name": "p2"}, 200, empty_schema) await check_add({"name": "p3"}, 200, empty_schema) await check_add({"name": "p2", "employee_id": 1}, 400, error_schema) p4_emp = random.choice(available_staff_ids) p2_emp = random.choice(available_staff_ids) await check_add({"name": "p4", "employee_id": p4_emp}, 200, empty_schema) await check_set({"name": "p2", "employee_id": p2_emp}, 200, empty_schema) products = set() for i in (await check_list())["content"]: jsonschema.validate(i, product_schema) products.add(Product(**i)) assert products == {Product("p1"), Product("p2", p2_emp), Product("p3"), Product("p4", p4_emp)} available_staff_ids = set() loop.run_until_complete(setup()) available_staff_ids = list(available_staff_ids) # там должны быть уникальные элементы loop.run_until_complete(_test()) <file_sep>from aiohttp.web import RouteTableDef, Request import jsonschema import logging from .database import get_db, asyncpg from .resp_validation import validated_json_response db_pool: asyncpg.pool.Pool routers = RouteTableDef() @routers.delete('/') async def drop_all_handler(request: Request): """ Удаляет все данные """ async with db_pool.acquire() as conn: await conn.execute("DELETE FROM products") await conn.execute("DELETE FROM CSLinks") await conn.execute("DELETE FROM staff") await conn.execute("DELETE FROM companies") return validated_json_response({}) @routers.post('/companies') async def company_add_handler(request: Request): """ Добавляет компанию Обязательные параметры: - name - название компании """ schema = { "type": "object", "properties": { "name": { "type": "string", "pattern": "^[A-Za-z]{2,}$" } }, "required": ["name"], "additionalProperties": False } try: jsonschema.validate(dict(request.query), schema) except jsonschema.ValidationError as e: return validated_json_response({"error": e.message}, status=422) name = request.query.get("name") try: async with db_pool.acquire() as conn: await conn.execute(f"INSERT INTO companies (name) VALUES ('{name}')") return validated_json_response({}) except asyncpg.UniqueViolationError: return validated_json_response({"error": "company already created"}, status=208) @routers.get('/companies') async def company_list_handler(request: Request): """ Возвращает список всех компаний """ async with db_pool.acquire() as conn: companies = await conn.fetch("SELECT name FROM companies") return validated_json_response({ "content": [{"name": i.get('name')} for i in companies] }) @routers.post('/staff') async def staff_add_handler(request: Request): """ Добавляет работника Обязательные параметры: - name - имя работника - company - название компании(Компания должна уже существовать) """ schema = { "type": "object", "properties": { "name": { "type": "string", "pattern": "^[A-Z][a-z]+$" }, "company": { "type": "string", "pattern": "^[A-Za-z]{2,}$" } }, "additionalProperties": False, "minProperties": 2 } try: jsonschema.validate(dict(request.query), schema) except jsonschema.ValidationError as e: return validated_json_response({"error": e.message}, status=422) name = request.query.get("name") company = request.query.get("company") try: async with db_pool.acquire() as conn: async with conn.transaction(): # добавляем работника и получаем его id emp_id = (await conn.fetch(f"INSERT INTO staff (name) VALUES ('{name}') RETURNING id"))[0].get('id') # получаем id компании comp_id = (await conn.fetch(f"SELECT id FROM companies WHERE name='{company}'")) if len(comp_id) != 1: assert len(comp_id) == 0 raise ValueError comp_id = comp_id[0].get('id') # добавляем связь работника с компанией await conn.execute(f"INSERT INTO CSLinks (com_id, emp_id) VALUES ({comp_id}, {emp_id})") return validated_json_response({}) except ValueError: return validated_json_response({"error": f"company '{company}' is not exists"}, status=400) @routers.put('/staff') async def add_to_company_handler(request: Request): """ Добавляет работника к компании Обязательные параметры: - id - id работника(он должен уже существовать) - company - название компании(она должна уже существовать) """ schema = { "type": "object", "properties": { "id": { "type": "string", "pattern": "^[0-9]+$" }, "company": { "type": "string", "pattern": "^[A-Za-z]{2,}$" } }, "additionalProperties": False, "minProperties": 2 } try: jsonschema.validate(dict(request.query), schema) except jsonschema.ValidationError as e: return validated_json_response({"error": e.message}, status=422) emp_id = int(request.query.get("id")) company = request.query.get("company") try: async with db_pool.acquire() as conn: # получаем id компании comp_id = (await conn.fetch(f"SELECT id FROM companies WHERE name='{company}'")) if len(comp_id) != 1: assert len(comp_id) == 0 raise ValueError comp_id = comp_id[0].get('id') # добавляем связь работника с компанией await conn.execute(f"INSERT INTO CSLinks (com_id, emp_id) VALUES ({comp_id}, {emp_id})") return validated_json_response({}) except ValueError: return validated_json_response({"error": f"company '{company}' is not exists"}, status=400) except asyncpg.ForeignKeyViolationError: return validated_json_response({"error": f"employee with id '{emp_id}' is not exists"}, status=400) @routers.get('/staff') async def staff_list_handler(request: Request): """ Возвращает список персонала """ async with db_pool.acquire() as conn: # получаем список всего персонала staff = await conn.fetch("SELECT * FROM staff") return validated_json_response({ "content": [ { "id": i.get('id'), "name": i.get('name'), "companies": [c.get('name') for c in (await conn.fetch( f"SELECT name FROM companies " f"JOIN CSLinks ON emp_id={i.get('id')} AND CSLinks.com_id=companies.id" ))] } for i in staff ] }) @routers.post('/products') async def products_add_handler(request: Request): """ Добавляет продукт Обязательные параметры: - name - название продукта Дополнительные параметры: - employee_id - id ответственного сотрудника """ schema = { "type": "object", "properties": { "name": { "type": "string" }, "employee_id": { "type": "string", "pattern": "^[0-9]+$" } }, "required": ["name"], "additionalProperties": False } try: jsonschema.validate(dict(request.query), schema) except jsonschema.ValidationError as e: return validated_json_response({"error": e.message}, status=422) name = request.query.get("name") employee_id = request.query.get("employee_id") async with db_pool.acquire() as conn: if employee_id: # проверяем, что сотрудник с указанным id существует tmp = await conn.fetch(f"SELECT count(*) FROM staff WHERE id={employee_id}") if tmp[0].get("count") == 0: return validated_json_response({"error": f"employee with id '{employee_id}' is not exists"}, status=400) try: # добавляем продукт await conn.execute(f"INSERT INTO products (name, employee_id) VALUES ('{name}', {employee_id})") except asyncpg.UniqueViolationError: return validated_json_response({"error": f"product '{name}' already exists. Use /products/set_employee " f"to set employee"}, status=400) else: # добавляем продукт без указания отвецственного сотрудника try: await conn.execute(f"INSERT INTO products (name) VALUES ('{name}')") except asyncpg.UniqueViolationError: return validated_json_response({"error": f"product '{name}' already exists"}, status=208) return validated_json_response({}) @routers.put('/products') async def products_set_employee_handler(request: Request): """ Назначает продукту отвецственного сотрудника Обязательные параметры: - name - название продукта - employee_id - id ответственного сотрудника """ schema = { "type": "object", "properties": { "name": { "type": "string" }, "employee_id": { "type": "string", "pattern": "^[0-9]+$" } }, "required": ["name", "employee_id"], "additionalProperties": False } try: jsonschema.validate(dict(request.query), schema) except jsonschema.ValidationError as e: return validated_json_response({"error": e.message}, status=422) name = request.query.get("name") employee_id = request.query.get("employee_id") async with db_pool.acquire() as conn: # проверяем, что сотрудник с указанным id существует if (await conn.fetch(f"SELECT count(*) FROM staff WHERE id={employee_id}"))[0].get("count") == 0: return validated_json_response({"error": f"employee with id '{employee_id}' is not exists"}, status=400) # проверяем, что продукт с указанным названием существует if (await conn.fetch(f"SELECT count(*) FROM products WHERE name='{name}'"))[0].get("count") == 0: return validated_json_response({"error": f"product with name '{name}' is not exists"}, status=400) # Обновляем запись await conn.execute(f"UPDATE products SET employee_id={employee_id} WHERE name='{name}'") return validated_json_response({}) @routers.get('/products') async def products_list_handler(request: Request): """ Возвращает список продуктов """ def delete_none(d: dict): to_del = [] for k, v in d.items(): if v is None: to_del.append(k) for i in to_del: del d[i] return d async with db_pool.acquire() as conn: products = await conn.fetch("SELECT * FROM products") return validated_json_response({ "content": [ delete_none({ "name": i.get('name'), "employee_id": i.get('employee_id') }) for i in products ] }) async def init(app): global db_pool db_pool = get_db() logging.info("Добавляем роутеры") app.add_routes(routers) <file_sep> CREATE TABLE companies ( id serial primary key, name text unique ); CREATE TABLE staff ( id serial primary key, name varchar(50) not null ); -- так как каждый работник может работать в разных компаниях(связь многие ко многим) создаем вспомогательную таблицу CREATE TABLE CSLinks ( id serial primary key, com_id integer references companies(id), emp_id integer references staff(id) ); CREATE TABLE products ( id serial primary key, employee_id integer, -- ответственный сотрудник name text not null unique -- название товара ); <file_sep>import jsonschema from aiohttp.web import json_response def validated_json_response(data, *, status=200, **kwargs): if status == 200: schema = { "type": "object", "properties": { "content": { "type": "array", "items": { "type": "object" } } }, "additionalProperties": False } elif status//100 == 2: schema = { "type": "object", "properties": { "error": {"type": "string"}, "content": { "type": "array", "items": { "type": "object" } } }, "required": ["error"], "additionalProperties": False } else: schema = { "type": "object", "properties": { "error": {"type": "string"} }, "required": ["error"], "additionalProperties": False } jsonschema.validate(data, schema) return json_response(data, status=status, **kwargs) <file_sep>aiohttp asyncpg pytest jsonschema <file_sep> class NameGenerator: __slots__ = ("last_name", ) def __init__(self): self.last_name = 'a'*6 # последнее сгенерированное имя def generated(self, name: str) -> bool: for i in name: if ord('a') > ord(i) or ord(i) > ord('z'): return False if len(name) < 6: return False elif len(name) < len(self.last_name): return True elif len(name) > len(self.last_name): return False # длинна как у последнего сгенерированного элемента for a, b in zip(name, self.last_name): if ord(a) > ord(b): return False return True def __next__(self) -> str: for i in range(len(self.last_name)): if self.last_name[i] != 'z': self.last_name = self.last_name[:i] + chr(ord(self.last_name[i]) + 1) + self.last_name[i + 1:] break else: self.last_name = 'a' * (len(self.last_name) + 1) return self.last_name
e229006625b21f0f2e99af7ec3c8e4729feadf06
[ "SQL", "Markdown", "Python", "Text", "Dockerfile" ]
16
Python
MAndrey99/api4biz-task
aa43a6ec25fe971e7a79b6132aa57edddf1ad615
a9cdd38e9835d24415f90400aeebfeaa52565b77
refs/heads/master
<repo_name>lmontigny/Cuda<file_sep>/pinnedMemory_bis.cpp int main(void) { int * host_p; /*< Host data allocated as pinned memory */ int * dev_ptr_p; /*< this pointer resides on the host */ int ns = 32; int data_size = ns * sizeof(int); checkCudaErrors( cudaHostAlloc((void**) &host_p, data_size, cudaHostAllocMapped)); /* host_p = {1, 2, 3, ..., ns}*/ for (int i = 0; i < ns; i++) host_p[i] = i + 1; /* * we can pass the address of `host_p`, * namely `dev_ptr_p` to the kernel. This address * is retrieved using cudaHostGetDevicePointer: * */ checkCudaErrors(cudaHostGetDevicePointer(&dev_ptr_p, host_p, 0)); kernel<<<1, ns>>>(dev_ptr_p); /* * The following line is necessary for the host * to be able to "see" the changes that have been done * on `host_p` */ checkCudaErrors(cudaDeviceSynchronize()); for (int i = 0; i < ns; i++) printf("host_p[%d] = %d\n", i, host_p[i]); /* Free the page-locked memory */ checkCudaErrors(cudaFreeHost(host_p)); return 0; } <file_sep>/pinnedMemory.cpp #include <stdio.h> #include <cuda_runtime.h> #include "helper_cuda.h" /* A very simple kernel function */ __global__ void kernel(int *d_var) { d_var[threadIdx.x] += 10; } int * host_p; int * host_result; int * dev_p; int main(void) { int ns = 4; int data_size = ns * sizeof(int); /* Allocate host_p as pinned memory */ checkCudaErrors( cudaHostAlloc((void**)&host_p, data_size, cudaHostAllocDefault) ); /* Allocate host_result as pinned memory */ checkCudaErrors( cudaHostAlloc((void**)&host_result, data_size, cudaHostAllocDefault) ); /* Allocate dev_p on the device global memory */ checkCudaErrors( cudaMalloc((void**)&dev_p, data_size) ); /* Initialise host_p*/ for (int i=0; i<ns; i++){ host_p[i] = i + 1; } /* Transfer data to the device host_p .. dev_p */ checkCudaErrors( cudaMemcpy(dev_p, host_p, data_size, cudaMemcpyHostToDevice) ); /* Now launch the kernel... */ kernel<<<1, ns>>>(dev_p); getLastCudaError("Kernel error"); /* Copy the result from the device back to the host */ checkCudaErrors( cudaMemcpy(host_result, dev_p, data_size, cudaMemcpyDeviceToHost) ); /* and print the result */ for (int i=0; i<ns; i++){ printf("result[%d] = %d\n", i, host_result[i]); } /* * Now free the memory! */ checkCudaErrors( cudaFree(dev_p) ); checkCudaErrors( cudaFreeHost(host_p) ); checkCudaErrors( cudaFreeHost(host_result) ); return 0; } <file_sep>/README.md # Cuda Tutorials and examples using Cuda <file_sep>/thrust_sum.cpp // Example from https://github.com/thrust/thrust/ #include <thrust/host_vector.h> #include <thrust/device_vector.h> #include <thrust/generate.h> #include <thrust/reduce.h> #include <thrust/functional.h> #include <thrust/random.h> int my_rand(void) { static thrust::default_random_engine rng; static thrust::uniform_int_distribution<int> dist(0, 9999); return dist(rng); } int main(void) { // generate random data on the host thrust::host_vector<int> h_vec(100); thrust::generate(h_vec.begin(), h_vec.end(), my_rand); // transfer to device and compute sum thrust::device_vector<int> d_vec = h_vec; // initial value of the reduction int init = 0; // binary operation used to reduce values thrust::plus<int> binary_op; // compute sum on the device int sum = thrust::reduce(d_vec.begin(), d_vec.end(), init, binary_op); // print the sum std::cout << "sum is " << sum << std::endl; return 0; } <file_sep>/CUDA_aware_MPI.cpp /* However, if you are combining MPI and CUDA, you often need to send GPU buffers instead of host buffers. Without CUDA-aware MPI, you need to stage GPU buffers through host memory, using cudaMemcpy as shown in the following code excerpt. */ //MPI rank 0 cudaMemcpy(s_buf_h,s_buf_d,size,cudaMemcpyDeviceToHost); MPI_Send(s_buf_h,size,MPI_CHAR,1,100,MPI_COMM_WORLD); //MPI rank 1 MPI_Recv(r_buf_h,size,MPI_CHAR,0,100,MPI_COMM_WORLD, &status); cudaMemcpy(r_buf_d,r_buf_h,size,cudaMemcpyHostToDevice); // With a CUDA-aware MPI library this is not necessary; the GPU buffers can be directly passed to MPI as in the following excerpt. //MPI rank 0 MPI_Send(s_buf_d,size,MPI_CHAR,1,100,MPI_COMM_WORLD); //MPI rank n-1 MPI_Recv(r_buf_d,size,MPI_CHAR,0,100,MPI_COMM_WORLD, &status);
d9b3e5718d3ccbaa81b3550405e8ea3c2fcd28c7
[ "Markdown", "C++" ]
5
C++
lmontigny/Cuda
9ad9393d4e7302f11a4af8998d08be3e0a9db64d
38325180164db622733faa9be6955db237de6279
refs/heads/main
<repo_name>winea/RESTfulWebServicesNodeExpress<file_sep>/routes/bookRouter.js /*eslint-disable no-param-reassign */ const express = require('express'); function routes(Book) { const booksRouter = express.Router(); //REST booksRouter.route('/books') .post((req, res) => { const book = new Book(req.body); //console.log(book); //salvar book database book.save(); return res.status(201).json(book); }) .get((req, res) => { //const response = {hello: 'This is my API'}; //inserir busca genero //{query} exemplo de destructuring makes it possible to unpack values from arrays, or properties from objects, into distinct variables. //const {query} = req; const query = {}; //http://localhost:4000/api/books?genre=Fantasy if(req.query.genre) { query.genre = req.query.genre; } //mostrar lista livros Book.find(query, (err, books) => { if (err) { return res.send(err); } //else { return res.json(books); //} }); //res.json(response); }) //middleware, fica entre cliente e servidor, next aponta //para a proxima fç que pode ser qualquer uma a seguir (get, put, delete, patch) booksRouter.use('/books/:bookId', (req, res, next) => { //http://localhost:4000/api/books/5f74e8a3970f8356615c4eb3 Book.findById(req.params.bookId, (err, book) => { if (err) { return res.send(err); } if(book) { req.book = book; return next(); } return res.sendStatus(404); }); }); //rota id booksRouter.route('/books/:bookId') .get((req, res) => { res.json(book); //tratado pelo middleware acima // Book.findById(req.params.bookId, (err, book) => { // if (err) { // return res.send(err); // } // return res.json(book); // }); }) //PUT atualizar .put((req, res) => { //tratado pelo middleware acima // Book.findById(req.params.bookId, (err, book) => { // if (err) { // return res.send(err); // } const { book } = req; book.title = req.body.title; book.author = req.body.author; book.genre = req.body.genre; book.read = req.body.read; //book.save(); //return res.json(book); req.body.save((err) => { if(err) { return res.send(err); } return res.json(book); }) }) //faz o update de um unico parametro, ex mudar read: true .path((req, res) => { const { book } = req; if (req.body._id) { delete req.body._id; } Object.entries(req.body).forEach((item) => { const key = item[0]; const value = item[1]; book[key] = value; }); req.body.save((err) => { if(err) { return res.send(err); } return res.json(book); }) }) .delete ((req, res) => { req.book.remove((err) => { if(err) { return res.send(err); } return res.sendStatus(204); }) }) return booksRouter; } module.exports = routes;<file_sep>/README.md # RESTfulWebServicesNodeExpress https://app.pluralsight.com/library/courses/node-js-express-rest-web-services-update/table-of-contents ## REST cliente envia request para server e server responde ao cliente #### npm init #### npm install express@4.16.4 adicinar tooling como eslint para garantir qualidade do codigo nodemon para controlar alteraçoes automatico #### npm i eslint@5.16.0 -D inserir script para lint #### npm run lint -- --init ``` How would you like to configure ESLint? Use a popular style guide Which style guide do you want to follow? Airbnb (https://github.com/airbnb/javascript) Do you use React? No What format do you want your config file to be in? JavaScript ``` validar codigo #### npm run lint faz sumir erros bobos de tab espaço etc #### ./node_modules/.bin/eslint app.js --fix controlar alteraçoes codigo #### npm install nodemon@1.18.5 adicinar script no package.json ``` scripts": { "lint": "eslint .", "start": "nodemon app.js", "test": "mocha tests/**/*Test.js" }, ..., "nodemonConfig": { "restartable": "rs", "ignore": [ "node_modules/**/node_modules" ], "delay": "2500", "env": { "NODE_ENV": "development", "PORT": 4000 } ``` //run #### npm start instalar mongodb, adicionar bin no path variavel de ambiente no cmd adicionar o caminho db e log #### mongod –dbpath=C:\MongoDB\Server\4.4\data\db –logpath=C:\MongoDB\Server\4.4\data\db\log.txt –install usar git bash na pasta do projeto importar dados livros no mongoDB, criar a lista de objetos json rodar o comando abaixo ira importar as tabelas automatico no mongodb #### mongo bookAPI < booksJson.js #### npm install mongoose@5.3.10 ## POST data wth body-parser #### npm install body-parser@1.18.3 ## teste com POSTMAN ### GET insira a url: http://localhost:4000/api/books ### POST insira a url: http://localhost:4000/api/books seleciona aba Body, raw, mude text para json, cole exemplo de livro sem id ``` { "read": false, "title": "Jon's Book", "genre": "Fiction", "author": "<NAME>" } ``` clique Send ### PUT insira url com id http://localhost:4000/api/books/5f760f23edf375095c95f200 selecione aba body, marque opcao raw, mude text para json ``` { "read": false, "title": "Jon's New Book", "genre": "Fiction", "author": "<NAME>", "__v": 0 } ``` ### PATCH (atualiza somente o que informar no id) nao deixa fazer update no id insira url com id http://localhost:4000/api/books/5f760f23edf375095c95f200 selecione aba body, marque opcao raw, mude text para json ```{"read":true}``` ## TESTE UNITARIO #### npm install -D mocha@5.2.0 should@13.2.3 sinon@7.2.2 adicionar no .eslintrc.js para sumir erros ``` "env": {"node": true, "mocha": true}``` para rodar testes criados inserir package.json #### "test": "mocha tests/**/*Test.js" #### npm test ## TESTE de INTEGRAÇAO #### npm install supertest@3.3.0 -D
476e10b7d6b3488352772f3d4d5faad8fa0e01e1
[ "JavaScript", "Markdown" ]
2
JavaScript
winea/RESTfulWebServicesNodeExpress
61819c562370e6d507a4c335805661e603d32ec8
6e9ba59a4aecc0bd28ce1e8a9b15794682b6a8bc
refs/heads/master
<repo_name>EyesSoft/DropwizardAPI<file_sep>/pom.xml <?xml version="1.0" encoding="UTF-8"?> <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/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>DropWizard</groupId> <artifactId>DropWizard.org</artifactId> <version>1.0-SNAPSHOT</version> <properties> <lombok.version>1.16.18</lombok.version> </properties> <build> <plugins> <plugin> <artifactId>maven-assembly-plugin</artifactId> <configuration> <finalName>ServiceCreate</finalName> <appendAssemblyId>false</appendAssemblyId> <archive> <manifest> <mainClass>DropWizard.org.HelloMain</mainClass> </manifest> </archive> <descriptorRefs> <descriptorRef>jar-with-dependencies</descriptorRef> </descriptorRefs> </configuration> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <configuration> <source>1.8</source> <target>1.8</target> </configuration> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <configuration> <compilerArgs> <arg>-parameters</arg> </compilerArgs> </configuration> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-shade-plugin</artifactId> <version>2.3</version> <configuration> <createDependencyReducedPom>true</createDependencyReducedPom> <filters> <filter> <artifact>*:*</artifact> <excludes> <exclude>META-INF/*.SF</exclude> <exclude>META-INF/*.DSA</exclude> <exclude>META-INF/*.RSA</exclude> </excludes> </filter> </filters> </configuration> <executions> <execution> <phase>package</phase> <goals> <goal>shade</goal> </goals> <configuration> <transformers> <transformer implementation="org.apache.maven.plugins.shade.resource.ServicesResourceTransformer"/> <transformer implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer"> <mainClass>DropWizard.org.HelloMain</mainClass> </transformer> </transformers> </configuration> </execution> </executions> </plugin> </plugins> </build> <dependencies> <!--<dependency>--> <!--<groupId>org.hibernate</groupId>--> <!--<artifactId>hibernate-entitymanager</artifactId>--> <!--<version>4.3.6.Final</version>--> <!--</dependency>--> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-entitymanager</artifactId> <version>5.0.1.Final</version> <exclusions> <exclusion> <groupId>org.jboss.logging</groupId> <artifactId>jboss-logging</artifactId> </exclusion> </exclusions> </dependency> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-core</artifactId> <version>5.0.7.Final</version> </dependency> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-annotations</artifactId> <version>3.5.5-Final</version> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-api</artifactId> <version>1.7.7</version> </dependency> <dependency> <groupId>com.google.inject</groupId> <artifactId>guice</artifactId> <version>4.1.0</version> </dependency> <dependency> <groupId>io.dropwizard</groupId> <artifactId>dropwizard-core</artifactId> <version>1.3.7</version> </dependency> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <version>${lombok.version}</version> <scope>provided</scope> </dependency> <dependency> <groupId>io.dropwizard</groupId> <artifactId>dropwizard-db</artifactId> <version>1.3.0</version> </dependency> <dependency> <groupId>org.postgresql</groupId> <artifactId>postgresql</artifactId> <version>42.2.5</version> </dependency> <dependency> <groupId>io.dropwizard</groupId> <artifactId>dropwizard-client</artifactId> <version>1.0.6</version> </dependency> <dependency> <groupId>io.dropwizard</groupId> <artifactId>dropwizard-client</artifactId> <version>1.0.6</version> </dependency> <dependency> <groupId>io.dropwizard</groupId> <artifactId>dropwizard-hibernate</artifactId> <version>1.0.6</version> </dependency> <dependency> <groupId>io.dropwizard</groupId> <artifactId>dropwizard-auth</artifactId> <version>1.0.6</version> </dependency> </dependencies> </project><file_sep>/src/main/java/com/siseth/newapp/TworzenieTabel.java package com.siseth.newapp; import java.io.Serializable; public interface TworzenieTabel extends Serializable { public void saySomething(); } <file_sep>/src/main/java/GuiceInject/Communicator.java package GuiceInject; import com.google.inject.Inject; import com.google.inject.name.Named; public class Communicator { @Inject @Named("Friends") private Messanger friends; @Inject @Named("OtherPeople") private Messanger otherPeople; public Communicator( @Named("Friends") Messanger friends, @Named("OtherPeople") Messanger otherPeople ) { this.friends = friends; this.otherPeople = otherPeople; } public Communicator() { } public String zwrocWiadomoscOdOsoby(){ return friends.pisz(); } public String zwrocWiadomoscOdZnajomego(){ return otherPeople.pisz(); } } <file_sep>/src/main/java/GuiceInject/Bindowanie.java package GuiceInject; import com.google.inject.AbstractModule; import com.google.inject.name.Names; public class Bindowanie extends AbstractModule { @Override protected void configure() { bind(Messanger.class).annotatedWith(Names.named("Friends")).to(FriendsMsg.class); bind(Messanger.class).annotatedWith(Names.named("OtherPeople")).to(OtherPeople.class); } // @Provides // public Messanger provideFriendsMsg(){ // String name="something"; // Messanger friendsMessages=new FriendsMsg(name); // return friendsMessages; // } }
37ff138557fc4eb09b1f78645a1e341658104a8f
[ "Java", "Maven POM" ]
4
Maven POM
EyesSoft/DropwizardAPI
18601619b8c83d6abab32f8310dd3f49024dbc6c
ec5f3fe7069277bf941f9de7ac227589e5064231
refs/heads/main
<file_sep>package main.java.artglorin.generic.refactoring; class FileResource implements Resource {} <file_sep>package main.java.artglorin.typeinference; class FileResource implements Resource {} <file_sep>package main.java.artglorin.generic.solution.useclasses; import java.util.ArrayList; import java.util.stream.Collectors; @SuppressWarnings("all") class ReportService { String createReport(ArrayList<? extends Resource> resources) { return resources.stream() .map(it -> it.getClass() .getSimpleName()) .collect(Collectors.joining(",")); } } <file_sep>package main.java.artglorin.generic.solution.sealedinterfaces; interface Resource permits FileResource {} <file_sep>package main.java.artglorin.generic.solution.container; class FileResource implements Resource {} <file_sep>package main.java.artglorin.generic.statusquo; import java.net.URI; import java.util.List; public class UsageExample { public static void main(String[] args) { var uri = URI.create("file://test.txt"); var factory = new ResourceFactory(); FileResource fileResource = factory.createResource(uri); // do something with fileResource var resources = List.<Resource>of(fileResource); var report = new ReportService().createReport(resources); System.out.printf("%n=========%nReport%n%s%n=========%n", report); } } <file_sep>package main.java.artglorin.generic.solution.useclasses; abstract class Resource {} <file_sep>package main.java.artglorin.generic.refactoring; import java.net.URI; public class UsageExample { public static void main(String[] args) { System.out.printf( "%n=========%nReport%n%s%n=========%n", new ReportService().createReport(new ResourceFactory().createResource( URI.create("file://test.txt"))) ); } } <file_sep>package main.java.artglorin.generic.solution.sealedclasses; class Resource permits FileResource {} <file_sep>package main.java.artglorin.generic.statusquo; class FileResource implements Resource {} <file_sep>package main.java.artglorin.typeinference; interface Resource {} <file_sep>package main.java.artglorin.generic.solution.useclasses; import java.net.URI; import java.util.ArrayList; import java.util.List; public class ValidationExample { private static final ResourceFactory factory = new ResourceFactory(); private static final ReportService reportService = new ReportService(); private static final URI uri = URI.create("file://text.txt"); private static void validate() { // should be compile time error String assignToString = factory.createResource(uri); // should be compile time error String castToString = (String) factory.createResource(uri); // should be OK FileResource assignToCorrectClass = factory.createResource(uri); // should be OK var castToCorrectClass = (FileResource) factory.createResource(uri); // should be compile time warning Exception assignToIncorrectClass = factory.createResource(uri); // should be compile time warning var castToIncorrectClass = (Exception) factory.createResource(uri); // should be compile time error reportService.createReport(factory.createResource(uri)); // should be OK reportService.createReport(List.of(factory.createResource(uri))); // fix reportService.createReport(new ArrayList<>(List.of(factory.createResource( uri)))); } } <file_sep>package main.java.artglorin.generic.solution.container; import java.util.Objects; public final class Container<T> { private final T value; public Container(T value) {this.value = value;} @Override public String toString() { return "Container{" + "value=" + value + '}'; } @Override public boolean equals(Object o) { if (this == o) return true; if (!(o instanceof Container)) return false; Container<?> container = (Container<?>) o; return Objects.equals(value, container.value); } @Override public int hashCode() { return value != null ? value.hashCode() : 0; } public T get() { return value; } }
efb6e3e04b3bbea4ddf3766d44bf6493b18dc4a5
[ "Java" ]
13
Java
artglorin/article-how-generic-inference-work-in-Java
88445dfe081862c00955b41a9b8629125eea240a
8a5e004a2354a8994eaeab03051c3748a3a1d9c2
refs/heads/master
<file_sep>#include "paq.h" <file_sep>#include <stdio.h> #include <stdlib.h> #include <errno.h> #include <pcap.h> #include <sys/socket.h> #include <net/ethernet.h> #include <stdint.h> void printWelcome() { fprintf(stdout, "=======Sample IPS=======\n"); } void printRunningInfo(char *args[]) { fprintf(stdout, "Device: %s\n", args[1]); fprintf(stdout, "acq_mode: %s\n", args[2]); fprintf(stdout, "run_mode: %s\n", args[3]); } int initialize() { int success = 1; return success; } int main (int argc, char *argv[]) { char *dev = argv[1]; char *acq_mode = argv[2]; char *run_mode = argv[3]; char buffer[2048]; uint32_t rcv_len; printWelcome(); printRunningInfo(argv); if (!initialize()) { fprintf(stderr, "Failed to initialize\n"); exit(0); } // make n PacketAnalyzers int fd = socket (AF_PACKET, SOCK_RAW, htons(ETH_P_ALL)); if (fd == -1) { fprintf(stderr, "Error no: %d\n", errno); exit(0); } while ((rcv_len = recv(fd, buffer, sizeof(buffer), MSG_OOB)) > 0) { fprintf(stdout, "Received: %s\n", buffer); } return 0; } <file_sep>#ifndef JAM_IPS_SAMP_PAQ #define JAM_IPS_SAMP_PAQ #include <sys/socket.h> struct Jam_Packet { } Packet; #endif
fab8ad09c493d418ee04147cf3061336495faee7
[ "C" ]
3
C
jammingyu9/IPS_sample
7149ac3310826bbf7fad91ed66c4cdb2d4d73fae
2fb9a16249501eb9089d9345b58ebd87ee6cc924
refs/heads/master
<file_sep>Cinnajist ========= Toy cinnamon applet to get a list of gists from git hub. Installation ------------- * Copy the folder `<EMAIL>` to `~/.local/share/cinnamon/applets/` * Enable the applet in "Cinnamon Settings" This was developed with cinnamon 1.6.7 on Ubuntu 12.04.1 <file_sep>/* * Copyright 2013 <NAME> * * 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. */ // Imports: const Lang = imports.lang; const Applet = imports.ui.applet; const PopupMenu = imports.ui.popupMenu; const Json = imports.gi.Json; const Soup = imports.gi.Soup; const GLib = imports.gi.GLib; const UUID = '<EMAIL>'; // Logging - make more convenient // Both functions taken from cinnamon-weather function log(message) { global.log(UUID + "::" + log.caller.name + message); } function logError(error) { global.logError(UUID + "::" + logError.caller.name + ":" + error); } const GIST_LIST_URL = 'https://api.github.com/gists'; // All applets are recommended to be called MyApplet.. function MyApplet(metadata, orientation) { this._init(metadata, orientation); } MyApplet.prototype = { __proto__:Applet.TextApplet.prototype, _init: function(metadata, orientation) { Applet.TextApplet.prototype._init.call(this, orientation); this.set_applet_label("Gists"); // Setup basic menu this._menuManager = new PopupMenu.PopupMenuManager(this); this._menu = new Applet.AppletPopupMenu(this, orientation); this._menu.addMenuItem(new PopupMenu.PopupMenuItem("Loading...")); this._menuManager.addMenu(this._menu); // Setup soup for HTTP requests this._httpSession = new Soup.SessionAsync(); Soup.Session.prototype.add_feature.call( this._httpSession, new Soup.ProxyResolverDefault()); // Kick off an async request this.refresh_gists(); }, on_applet_clicked: function(event) { this._menu.toggle(); this.refresh_gists(); }, refresh_gists: function () { this._get_request(GIST_LIST_URL, function(gists) { log("removing all from menu"); this._menu.removeAll(); gists.foreach_element(Lang.bind(this, function(arr, index, node) { log("Iterating results"); var description, url, user, menuText; description = node.get_object().get_string_member('description'); url = node.get_object().get_string_member('url'); user = node.get_object().get_object_member('user').get_string_member('login'); // Stuff login and description into a menu button and on click open up a web browser menuText = user + ": " + description.substr(0, 30); this._addBrowserButton(menuText, url); })); }); }, /** * Adds a button to the menu that opens up a web browser with the url * menuText: String - The button text * url: String - The URL that the browser should go to */ _addBrowserButton: function(menuText, url) { var menuItem, _onClick = function (event) { GLib.spawn_command_line_async("xdg-open " + url); }; menuItem = new PopupMenu.PopupMenuItem(menuText); menuItem.connect('activate', _onClick); log("adding button to menu " + menuText); this._menu.addMenuItem(menuItem); }, /** * Performs a GET request on the specified URL * url: URL to request * fn: Function to run if successful, passed response as JSON */ _get_request: function (url, fn) { log(url); let message = Soup.Message.new('GET', url); var closure = Lang.bind(this, function(session, message) { let jp = new Json.Parser(); jp.load_from_data(message.response_body.data, -1); fn.call(this, jp.get_root().get_array()); }); this._httpSession.queue_message(message, closure); } }; function main(metadata, orientation) { let myApplet = new MyApplet(metadata, orientation); return myApplet; }
789b69dc75e2b39a4b6d9ee4f46540b7f72b5ba0
[ "Markdown", "JavaScript" ]
2
Markdown
dsas/cinnajist
5f0e311af4f893eab733b240b1beb389b9c88b7a
2cf4fcfe32e978c98bb68da395d4efc6765da61a
refs/heads/master
<file_sep>#pragma once #include <stdlib.h> #include <iomanip> #include <fstream> #include <math.h> #include <stdio.h> #include <iostream> #include <vector> #include "imageOpen.h" using namespace std; void increaseBrightness(bmpBITMAP_FILE &image, int brightness); void decreaseBrightness(bmpBITMAP_FILE &image, int brightness); void increaseContrast(bmpBITMAP_FILE &image, double contrast); void decreaseContrast(bmpBITMAP_FILE &image, double contrast); void insertionSort(int window[]); void medianSmooth(bmpBITMAP_FILE &image); void histogramEqualization(bmpBITMAP_FILE &image); //www.programming-techniques.com/2013/03/sobel-and-prewitt-edge-detector-in-c.html void sobelEdgeDetection(bmpBITMAP_FILE &image); //convert to black and white void grayToBlackWhite(bmpBITMAP_FILE &image); void grayToBinary(bmpBITMAP_FILE &image); void binaryToGray(bmpBITMAP_FILE &image); //these dont work yet void thinningAlg(bmpBITMAP_FILE &image); void thinning(bmpBITMAP_FILE &image); void doZhangSuenThinning(bmpBITMAP_FILE &image); class Point { private: int x; int y; public: Point::Point(); Point(int xx, int yy); int getX(); void setX(int xx); int getY(); void setY(int yy); }; <file_sep>#include "preprocessor.h" ////////////////////////////////////////// Point::Point() {} Point::Point(int xx, int yy) {x = xx; y = yy;} int Point::getX() {return x;} void Point::setX(int xx) {x = xx;} int Point::getY() {return y;} void Point::setY(int yy) {y = yy;} /////////////////////////////////////////// void increaseBrightness(bmpBITMAP_FILE &image, int brightness) { int width; int height; height = Assemble_Integer(image.infoheader.biHeight); width = Assemble_Integer(image.infoheader.biWidth); for (int i = 0; i<height; i++) { for (int j = 0; j < width; j++) { if (image.image_ptr[i][j] + brightness > 255) { image.image_ptr[i][j] = image.image_ptr[i][j] + (255 - image.image_ptr[i][j]); } else { image.image_ptr[i][j] = image.image_ptr[i][j] + brightness; } } } } void decreaseBrightness(bmpBITMAP_FILE &image, int brightness) { int width; int height; height = Assemble_Integer(image.infoheader.biHeight); width = Assemble_Integer(image.infoheader.biWidth); for (int i = 0; i<height; i++) { for (int j = 0; j < width; j++) { if (image.image_ptr[i][j] - brightness < 0) { image.image_ptr[i][j] = image.image_ptr[i][j] - image.image_ptr[i][j]; } else { image.image_ptr[i][j] = image.image_ptr[i][j] - brightness; } } } } //contrast > 1 void increaseContrast(bmpBITMAP_FILE &image, double contrast) { int width; int height; height = Assemble_Integer(image.infoheader.biHeight); width = Assemble_Integer(image.infoheader.biWidth); for (int i = 0; i<height; i++) { for (int j = 0; j < width; j++) { if (127 + (contrast * (image.image_ptr[i][j] - 127)) > 255) { image.image_ptr[i][j] = 255; } else if(127 + (contrast * (image.image_ptr[i][j] - 127)) < 0) { image.image_ptr[i][j] = 0; } else { image.image_ptr[i][j] = 127 + (contrast * (image.image_ptr[i][j] - 127)); } } } } //contrast < 1 void decreaseContrast(bmpBITMAP_FILE &image, double contrast) { int width; int height; height = Assemble_Integer(image.infoheader.biHeight); width = Assemble_Integer(image.infoheader.biWidth); for (int i = 0; i<height; i++) { for (int j = 0; j < width; j++) { if (127 + (contrast * (image.image_ptr[i][j] - 127)) > 255) { image.image_ptr[i][j] = 255; } else if (127 + (contrast * (image.image_ptr[i][j] - 127)) < 0) { image.image_ptr[i][j] = 0; } else { image.image_ptr[i][j] = 127 + (contrast * (image.image_ptr[i][j] - 127)); } } } } void insertionSort(int window[]) { int temp, i, j; for (i = 0; i < 9; i++) { temp = window[i]; for (j = i - 1; j >= 0 && temp < window[j]; j--) { window[j + 1] = window[j]; } window[j + 1] = temp; } } void medianSmooth(bmpBITMAP_FILE &image) { bmpBITMAP_FILE imageCopy; int width; int height; height = Assemble_Integer(image.infoheader.biHeight); width = Assemble_Integer(image.infoheader.biWidth); //create a sliding window of size 9 int window[9]; Copy_Image(image, imageCopy); for (int i = 1; i < height-1; i++) { for (int j = 1; j < width-1; j++) { // Pick up window elements window[0] = image.image_ptr[i - 1][j - 1]; window[1] = image.image_ptr[i][j - 1]; window[2] = image.image_ptr[i + 1][j - 1]; window[3] = image.image_ptr[i - 1][j]; window[4] = image.image_ptr[i][j]; window[5] = image.image_ptr[i + 1][j]; window[6] = image.image_ptr[i - 1][j + 1]; window[7] = image.image_ptr[i][j + 1]; window[8] = image.image_ptr[i + 1][j + 1]; // sort the window to find median insertionSort(window); // assign the median to centered element of the matrix imageCopy.image_ptr[i][j] = window[4]; } } Copy_Image(imageCopy, image); } void histogramEqualization(bmpBITMAP_FILE &image) { int width; int height; height = Assemble_Integer(image.infoheader.biHeight); width = Assemble_Integer(image.infoheader.biWidth); int hist[256]; //initialize histogram for (int i = 0; i < 256; i++) { hist[i] = 0; } //compute the histogram for (int i = 0; i < height; i++) { for (int j = 0; j < width; j++) { hist[image.image_ptr[i][j]] += 1; } } //compute the cummulative histogram for (int i = 1; i < 256; i++) { hist[i] = hist[i - 1] + hist[i]; } //normalize the cummulative histogram for (int i = 0; i < 256; i++) { hist[i] = hist[i] * 255 / (height * width); } //write the equalized values into the image for (int i = 0; i < height; i++) { for (int j = 0; j < width; j++) { image.image_ptr[i][j] = hist[image.image_ptr[i][j]]; } } } // Computes the x component of the gradient vector // at a given point in a image. // returns gradient in the x direction int xGradient(bmpBITMAP_FILE &image, int x, int y) { return image.image_ptr[y - 1][x - 1] + 2 * image.image_ptr[y][x - 1] + image.image_ptr[y + 1][x - 1] - image.image_ptr[y - 1][x + 1] - 2 * image.image_ptr[y][x + 1] - image.image_ptr[y + 1][x + 1]; } // Computes the y component of the gradient vector // at a given point in a image // returns gradient in the y direction int yGradient(bmpBITMAP_FILE &image, int x, int y) { return image.image_ptr[y - 1][x - 1] + 2 * image.image_ptr[y - 1][x] + image.image_ptr[y - 1][x + 1] - image.image_ptr[y + 1][x - 1] - 2 * image.image_ptr[y + 1][x] - image.image_ptr[y + 1][x + 1]; } //uses the aove two functions as helper functions void sobelEdgeDetection(bmpBITMAP_FILE &image) { bmpBITMAP_FILE imageCopy; Copy_Image(image, imageCopy); int width; int height; int gx, gy, sum; height = Assemble_Integer(image.infoheader.biHeight); width = Assemble_Integer(image.infoheader.biWidth); for (int y = 0; y < height; y++) for (int x = 0; x < width; x++) imageCopy.image_ptr[y][x] = 0; for (int y = 1; y < height - 1; y++) { for (int x = 1; x < width - 1; x++) { gx = xGradient(image, x, y); gy = yGradient(image, x, y); sum = abs(gx) + abs(gy); sum = sum > 255 ? 255 : sum; sum = sum < 0 ? 0 : sum; imageCopy.image_ptr[y][x] = sum; } } Copy_Image(imageCopy, image); } void grayToBlackWhite(bmpBITMAP_FILE &image) { int width; int height; height = Assemble_Integer(image.infoheader.biHeight); width = Assemble_Integer(image.infoheader.biWidth); for (int i = 0; i < height; i++) { for (int j = 0; j < width; j++) { if (image.image_ptr[i][j] > 127) //change threshold for dif conversions { image.image_ptr[i][j] = 255; } else { image.image_ptr[i][j] = 0; } } } } //backwards gray to binary converter for thinning algorithm void grayToBinary(bmpBITMAP_FILE &image) { int width; int height; height = Assemble_Integer(image.infoheader.biHeight); width = Assemble_Integer(image.infoheader.biWidth); for (int i = 0; i < height; i++) { for (int j = 0; j < width; j++) { if (image.image_ptr[i][j] == 0) //change threshold for dif conversions { image.image_ptr[i][j] = 1; } else { image.image_ptr[i][j] = 0; } } } } //backwards gray to binary converter for thinning algorithm void binaryToGray(bmpBITMAP_FILE &image) { int width; int height; height = Assemble_Integer(image.infoheader.biHeight); width = Assemble_Integer(image.infoheader.biWidth); for (int i = 0; i < height; i++) { for (int j = 0; j < width; j++) { if (image.image_ptr[i][j] == 1) //change threshold for dif conversions { image.image_ptr[i][j] = 0; } else { image.image_ptr[i][j] = 255; } } } } //everything below here doesnt work yet //placeholder code, doesnt do shit yet void thinningAlg(bmpBITMAP_FILE &image) { bmpBITMAP_FILE imageCopy; Copy_Image(image, imageCopy); int width; int height; height = Assemble_Integer(image.infoheader.biHeight); width = Assemble_Integer(image.infoheader.biWidth); for (int i = 0; i < height; i++) { for (int j = 0; j < width; j++) { image.image_ptr[i][j] = 1; } } Copy_Image(imageCopy, image); } /** * @param givenImage * @param changeGivenImage decides whether the givenArray should be modified or a clone should be used * @return a 2D array of binary image after thinning using zhang-suen thinning algo. */ int getA(bmpBITMAP_FILE binaryImage, int y, int x) { int width; int height; height = Assemble_Integer(binaryImage.infoheader.biHeight); width = Assemble_Integer(binaryImage.infoheader.biWidth); int count = 0; //p2 p3 if (y - 1 >= 0 && x + 1 < width && binaryImage.image_ptr[y - 1][x] == 0 && binaryImage.image_ptr[y - 1][x + 1] == 1) { count++; } //p3 p4 if (y - 1 >= 0 && x + 1 < width && binaryImage.image_ptr[y - 1][x + 1] == 0 && binaryImage.image_ptr[y][x + 1] == 1) { count++; } //p4 p5 if (y + 1 < height && x + 1 < width && binaryImage.image_ptr[y][x + 1] == 0 && binaryImage.image_ptr[y + 1][x + 1] == 1) { count++; } //p5 p6 if (y + 1 < height && x + 1 < width && binaryImage.image_ptr[y + 1][x + 1] == 0 && binaryImage.image_ptr[y + 1][x] == 1) { count++; } //p6 p7 if (y + 1 < height && x - 1 >= 0 && binaryImage.image_ptr[y + 1][x] == 0 && binaryImage.image_ptr[y + 1][x - 1] == 1) { count++; } //p7 p8 if (y + 1 < height && x - 1 >= 0 && binaryImage.image_ptr[y + 1][x - 1] == 0 && binaryImage.image_ptr[y][x - 1] == 1) { count++; } //p8 p9 if (y - 1 >= 0 && x - 1 >= 0 && binaryImage.image_ptr[y][x - 1] == 0 && binaryImage.image_ptr[y - 1][x - 1] == 1) { count++; } //p9 p2 if (y - 1 >= 0 && x - 1 >= 0 && binaryImage.image_ptr[y - 1][x - 1] == 0 && binaryImage.image_ptr[y - 1][x] == 1) { count++; } return count; } int getB(bmpBITMAP_FILE binaryImage, int y, int x) { return binaryImage.image_ptr[y - 1][x] + binaryImage.image_ptr[y - 1][x + 1] + binaryImage.image_ptr[y][x + 1] + binaryImage.image_ptr[y + 1][x + 1] + binaryImage.image_ptr[y + 1][x] + binaryImage.image_ptr[y + 1][x - 1] + binaryImage.image_ptr[y][x - 1] + binaryImage.image_ptr[y - 1][x - 1]; } void doZhangSuenThinning(bmpBITMAP_FILE &binaryImage) { int width; int height; height = Assemble_Integer(binaryImage.infoheader.biHeight); width = Assemble_Integer(binaryImage.infoheader.biWidth); vector<Point> pointsToChange; int a, b; grayToBlackWhite(binaryImage); grayToBinary(binaryImage); //List<Point> pointsToChange = new LinkedList(); bool hasChange; do { hasChange = false; for (int y = 1; y + 1 < height; y++) { for (int x = 1; x + 1 < width; x++) { a = getA(binaryImage, y, x); b = getB(binaryImage, y, x); if (binaryImage.image_ptr[y][x] == 1 && 2 <= b && b <= 6 && a == 1 && (binaryImage.image_ptr[y - 1][x] * binaryImage.image_ptr[y][x + 1] * binaryImage.image_ptr[y + 1][x] == 0) && (binaryImage.image_ptr[y][x + 1] * binaryImage.image_ptr[y + 1][x] * binaryImage.image_ptr[y][x - 1] == 0)) { Point pt; pt.setX(x); pt.setY(y); pointsToChange.push_back(pt); //binaryImage[y][x] = 0; hasChange = true; } } } for (Point point : pointsToChange) { binaryImage.image_ptr[point.getY()][point.getX()] = 0; } pointsToChange.clear(); for (int y = 1; y + 1 < height; y++) { for (int x = 1; x + 1 < width; x++) { a = getA(binaryImage, y, x); b = getB(binaryImage, y, x); if (binaryImage.image_ptr[y][x] == 1 && 2 <= b && b <= 6 && a == 1 && (binaryImage.image_ptr[y - 1][x] * binaryImage.image_ptr[y][x + 1] * binaryImage.image_ptr[y][x - 1] == 0) && (binaryImage.image_ptr[y - 1][x] * binaryImage.image_ptr[y + 1][x] * binaryImage.image_ptr[y][x - 1] == 0)) { Point pt; pt.setX(x); pt.setY(y); pointsToChange.push_back(pt); hasChange = true; } } } for (Point point : pointsToChange) { binaryImage.image_ptr[point.getY()][point.getX()] = 0; } pointsToChange.clear(); } while (hasChange); binaryToGray(binaryImage); } <file_sep>#pragma once ///////////////////////////////// // // Program Bitmap_Parser // // CSCI 540 // // Author: <NAME> <EMAIL> // // Instructor: Dr. <NAME> // // I am sharing this code in the spirit of collaboration. I // have found that it serves my purposes, and I hope it // improves your learning experience. Please feel free to // modify it for your own use. I would appreciate any // comments, questions or bug reports. // I may be reached at: <EMAIL> // // This program will read a binary file containing a bitmap // and load it into a structure. Each pixel is assumed to be // represented by 8 bits. The binary data are maintained in // the structure as bytes. This makes reading and writing // the files easy. However, when integer values need to be // extracted, the bytes need to be assembled into integers, // using the Assemble_Integer() function. // // This code was written with the notion in mind that it // could be scaled to deal with bitmaps other than the ones // with 256 greys. However, this version will only work // with 256 greys. Additonally, extra work will need to be // done to support bitmaps with bits-per-row not evenly // divisible by 4. (This is the "padding" issue) // // If you change the size of the image, there are three // variables in the header which will need to be // considered for updating. They are: // bfSize // biWidth // biHeight // // Additionally, if the width of your new image is not // evenly divisible by four bytes, you will have to add // "padding" bytes to make it so. This will change // the size of the file (bfSize), so you should update // that parameter to reflect padding. However, I do not // think that biWidth is to be updated to reflect // padding. That is a question I have not had to // answer yet. // //////////////////// #include <stdlib.h> #include <iomanip> #include <fstream> #include <math.h> #include <stdio.h> #include <iostream> using namespace std; typedef unsigned char byte_t; // The following two structures were adapted from // http://users.ece.gatech.edu/~slabaugh/personal/c/bmpwrite.html struct bmpFILEHEADER { byte_t bfType[2]; //Bitmap identifier, Must be "BM" byte_t bfSize[4]; byte_t bfReserved[4]; byte_t bfOffbits[4]; //specifies the location //(in bytes) in the file of the // image data. Should be equal to // sizeof(bmpFileHeader + sizeof(bmpInfoHeader) // + sizeof(Palette) }; struct bmpINFOHEADER { byte_t biSize[4]; // Size of the bmpInfoHeader, i.e. sizeof(bmpInfoheader) byte_t biWidth[4]; // Width of bitmap, in pixels change this if you change // the size of the image. see ***** note below byte_t biHeight[4]; // Height of bitmap, in pixels change this if you change // the size of the image. see ***** note below byte_t biPlanes[2]; // Should/must be 1. byte_t biBitCount[2]; // The bit depth of the bitmap. // For 8 bit bitmaps, this is 8 byte_t biCompression[4]; // Should be 0 for uncompressed bitmaps byte_t biSizeImage[4]; //The size of the padded image, in bytes byte_t biXPelsPerMeter[4]; //Horizontal resolution, in pixels per meter. Not signif. byte_t biYPelsPermeter[4]; //Vertical resolution, as above. byte_t biClrUsed[4]; //Indicates the number of colors in the palette. byte_t biClrImportant[4]; //Indicates number of colors to display the bitmap. // Set to zero to indicate all colors should be used. }; // *****Note (from above) you will have to write a function to do this. I have not yet. struct bmpPALETTE { byte_t palPalette[1024]; // this will need to beimproved if the program is to scale. // unless we change the palette, this will do. }; struct bmpBITMAP_FILE // note: this structure may not be // written to file all at once. // the two headers may be written // normally, but the image requires // a write for each line followed // by a possible 1 - 3 padding bytes. { bmpFILEHEADER fileheader; bmpINFOHEADER infoheader; bmpPALETTE palette; //this implementation // will not generalize. Fixed at 256 shades of grey. byte_t **image_ptr; //this points to the // image. Allows the allocation of a two dimensional // array dynamically }; //================= Open_input_file ======================= // // Gets the name of the input file from the user and opens // it for input // void open_input_file ( ifstream &in_file //Pre: none //Post: File name supplied by user ); //================ Assemble_Integer ======================== // // Accepts a pointer to an array of unsigned characters // (there should be 4 bytes) // Assembles them into a signed integer and returns the // result int Assemble_Integer ( unsigned char bytes[] // Pre: 4 little-endian bytes // (least significant byte first) ); //============= Display_FileHeader ========================== // void Display_FileHeader(bmpFILEHEADER &fileheader); //============= Display_InfoHeader ========================== // void Display_InfoHeader(bmpINFOHEADER &infoheader); //=============== Calc_Padding ============================== // // Returns the number of bytes of padding for an image // (either 0,1,2,3). // Each scan line must end on a 4 byte boundry. // Threfore, if the pixel_width is not evenly divisible // by 4, extra bytes are added (either 1, 2 or 3 extra // bytes) when writing each line. Likewise, when reading // a bitmap file it may be helpful to remove the padding // prior to any manipulations. // This is not needed unless the number of bytes in a row // are not evenly divisible by 4. See implementation // section for details. int Calc_Padding(int pixel_width); //pre: the width of the // image in pixels //================= load_Bitmap_File ======================= // void Load_Bitmap_File(bmpBITMAP_FILE &image); //Post: structure is filled with data from a .bmp file //============== Display_Bitmap_File ======================= // void Display_Bitmap_File(bmpBITMAP_FILE &image); //================== Copy_Image ============================ // // Pre: image_orig.byte_t points to a 2 dim array // image_copy does not have an array associated with byte_t** // Post: image_copy receives a copy of the structurs in image_orig void Copy_Image(bmpBITMAP_FILE &image_orig, bmpBITMAP_FILE &image_copy); //================== Remove_Image ========================== // // Pre: image.byte-t contains pointers to a 2-dim array // Post: memory that **byte_t points to is freed with the // delete operator image.bfType[] is set to "XX" // void Remove_Image(bmpBITMAP_FILE &image); //================= Save_Bitmap_File ======================= // void Save_Bitmap_File(bmpBITMAP_FILE &image); //=================== Open_Output_File ===================== // void Open_Output_File(ofstream &out_file);<file_sep>#define _CRT_SECURE_NO_DEPRECATE #include <fstream> #include <stdlib.h> #include <iomanip> #include <stdio.h> #include <malloc.h> #include <memory.h> #include <iostream> /*int main() { unsigned char buffer[787512]; ifstream myFile("im7-c.bmp", ios::in | ios::binary); myFile.read(buffer, 787512); ofstream hFile("test.bmp", ios::out | ios::binary); hFile.write(buffer, 787512); } */ /* fileName[in] : the name of the bitmap file (with .bmp extension) to open header[out] : an unallocated pointer to store the header's data into data[out] : an unallocated unsigned char pointer to store the integer data in returns : 0 for failure, 1 for success */ int openBitmapAndGetInts(char fileName[], char **header, unsigned char **data); void main(void) { char *header; unsigned char *data; int ret = 0; //open the bitmap file... ret = openBitmapAndGetInts("im4-c.bmp", &header, &data); if (ret != 0) { /* This is where you do all your processing since everything went fine */ // Make certain to free our data...after all, we're not Microsoft...we // can't afford memory leaks free(header); free(data); } } int openBitmapAndGetInts(char fileName[], char **header, unsigned char **data) { int headerSize = 14 + 40 + 1026; FILE *file = fopen(fileName, "rb"); int num = 0; //problem opening the file if (file == 0) return 0; //make the room for the header (*header) = (char *)malloc(headerSize); memset(*header, 0, headerSize); //make the room for the data (*data) = (unsigned char *)malloc(1024 * 768); memset(*data, 0, 1024 * 768); //problem getting the space for the header if ((*header) == 0) return 0; if ((*data) == 0) return 0; //read in the header for the bitmap num = fread((*header), 1, headerSize, file); //error reading in header if (num != headerSize) return 0; //read in the integer data num = fread((*data), 1, 1024 * 768, file); //error reading in data if (num != 1024 * 768) return 0; //close the file fclose(file); return 1; } <file_sep>#include "imageOpen.h" //============== open_input_file =========================== // void open_input_file ( ifstream &in_file ) { char in_file_name[80]; cout << "Enter the name of the file" << endl << "which contains the bitmap: "; cin >> in_file_name; //cout << "You entered: " << in_file_name << endl; in_file.open(in_file_name, ios::in | ios::binary); if (!in_file) cerr << "Error opening file\a\a\n", exit(101); return; } //================ Assemble_Integer ======================== // int Assemble_Integer(unsigned char bytes[]) { int an_integer; an_integer = int(bytes[0]) + int(bytes[1]) * 256 + int(bytes[2]) * 256 * 256 + int(bytes[3]) * 256 * 256 * 256; return an_integer; } //============= Display_FileHeader ======================= // void Display_FileHeader(bmpFILEHEADER &fileheader) { cout << "bfType: " << fileheader.bfType[0] << fileheader.bfType[1] << "\n"; cout << "bfSize: " << Assemble_Integer(fileheader.bfSize) << "\n"; cout << "bfReserved: " << Assemble_Integer(fileheader.bfReserved) << "\n"; cout << "bfOffbits: " << Assemble_Integer(fileheader.bfOffbits) << "\n"; } //================ Display_InfoHeader ====================== // void Display_InfoHeader(bmpINFOHEADER &infoheader) { cout << "\nThe bmpInfoHeader contains the following:\n"; cout << "biSize: " << Assemble_Integer(infoheader.biSize) << "\n"; cout << "biWidth: " << Assemble_Integer(infoheader.biWidth) << "\n"; cout << "biHeight: " << Assemble_Integer(infoheader.biHeight) << "\n"; cout << "biPlanes: " << int(infoheader.biPlanes[0]) + int(infoheader.biPlanes[1]) * 256 << "\n"; cout << "biBitCount: " << int(infoheader.biBitCount[0]) + int(infoheader.biBitCount[1]) * 256 << "\n"; cout << "biCompression: " << Assemble_Integer(infoheader.biCompression) << "\n"; cout << "biSizeImage: " << Assemble_Integer(infoheader.biSizeImage) << "\n"; cout << "biClrUsed: " << Assemble_Integer(infoheader.biClrUsed) << "\n"; cout << "biClrImportant: " << Assemble_Integer(infoheader.biClrImportant) << "\n"; } //==================== Calc_Padding ======================== // int Calc_Padding(int pixel_width) { // Each scan line must end on a 4 byte boundry. // Threfore, if the pixel_width is not evenly divisible // by 4, extra bytes are added (either 1 - 3 extra bytes) int remainder; int padding = 0; remainder = pixel_width % 4; //cout << "\nPixel width: " << pixel_width << "\n"; //cout << "Remainder: " << remainder << "\n"; switch (remainder) { case 0: padding = 0; break; case 1: padding = 3; break; case 2: padding = 2; break; case 3: padding = 1; break; default: cerr << "Error: Padding was set to " << padding << "\n"; exit(101); } //cout << "Padding determined: " << padding << "\n"; return padding; } //================== load_Bitmap_File ====================== // void Load_Bitmap_File(bmpBITMAP_FILE &image) { ifstream fs_data; int bitmap_width; int bitmap_height; int padding; long int cursor1; // used to navigate through the // bitfiles open_input_file(fs_data); fs_data.read((char *)&image.fileheader, sizeof(bmpFILEHEADER)); //fs_data.seekg(14L); fs_data.read((char *)&image.infoheader, sizeof(bmpINFOHEADER)); fs_data.read((char *)&image.palette, sizeof(bmpPALETTE)); // this will need to // be dynamic, once // the size of the palette can vary bitmap_height = Assemble_Integer(image.infoheader.biHeight); bitmap_width = Assemble_Integer(image.infoheader.biWidth); padding = Calc_Padding(bitmap_width); // allocate a 2 dim array image.image_ptr = new byte_t*[bitmap_height]; for (int i = 0; i < bitmap_height; i++) image.image_ptr[i] = new byte_t[bitmap_width]; cursor1 = Assemble_Integer(image.fileheader.bfOffbits); fs_data.seekg(cursor1); //move the cursor to the // beginning of the image data //load the bytes into the new array one line at a time for (int i = 0; i<bitmap_height; i++) { fs_data.read((char *)image.image_ptr[i], bitmap_width); // insert code here to read the padding, // if there is any } fs_data.close(); //close the file // (consider replacing with a function w/error checking) } //============== Display_Bitmap_File ======================= // void Display_Bitmap_File(bmpBITMAP_FILE &image) { int bitmap_width; int bitmap_height; Display_FileHeader(image.fileheader); Display_InfoHeader(image.infoheader); //display the palatte here too, perhaps. bitmap_height = Assemble_Integer(image.infoheader.biHeight); bitmap_width = Assemble_Integer(image.infoheader.biWidth); for (int i = 0; i < 1; i++) { for (int j = 0; j < bitmap_width; j++) cout << setw(4) << int(image.image_ptr[i][j]); cout << "\n\nNew Line\n\n"; } } //=============== Copy_Image =============================== // void Copy_Image(bmpBITMAP_FILE &image_orig, bmpBITMAP_FILE &image_copy) { int height, width; image_copy.fileheader = image_orig.fileheader; image_copy.infoheader = image_orig.infoheader; image_copy.palette = image_orig.palette; height = Assemble_Integer(image_copy.infoheader.biHeight); width = Assemble_Integer(image_copy.infoheader.biWidth); image_copy.image_ptr = new byte_t*[height]; for (int i = 0; i < height; i++) image_copy.image_ptr[i] = new byte_t[width]; //load the bytes into the new array one byte at a time for (int i = 0; i<height; i++) { for (int j = 0; j < width; j++) image_copy.image_ptr[i][j] = image_orig.image_ptr[i][j]; } } //================== Remove_Image ========================== // void Remove_Image(bmpBITMAP_FILE &image) { int height, width; height = Assemble_Integer(image.infoheader.biHeight); width = Assemble_Integer(image.infoheader.biWidth); //once the palette is dynamic, must delete the memory // allocated for the palatte here too // delete the dynamic memory for (int i = 0; i < height; i++) delete[] image.image_ptr[i]; delete[] image.image_ptr; image.fileheader.bfType[0] = 'X'; // just to mark it as image.fileheader.bfType[1] = 'X'; // unused. // Also, we may wish to initialize all the header // info to zero. } //================== Save_Bitmap_File ====================== // void Save_Bitmap_File(bmpBITMAP_FILE &image) { ofstream fs_data; int width; int height; int padding; long int cursor1; // used to navigate through the // bitfiles height = Assemble_Integer(image.infoheader.biHeight); width = Assemble_Integer(image.infoheader.biWidth); Open_Output_File(fs_data); fs_data.write((char *)&image.fileheader, sizeof(bmpFILEHEADER)); if (!fs_data.good()) { cout << "\aError 101 writing bitmapfileheader"; cout << " to file.\n"; exit(101); } fs_data.write((char *)&image.infoheader, sizeof(bmpINFOHEADER)); if (!fs_data.good()) { cout << "\aError 102 writing bitmap"; cout << " infoheader to file.\n"; exit(102); } fs_data.write((char *)&image.palette, sizeof(bmpPALETTE)); if (!fs_data.good()) { cout << "\aError 103 writing bitmap palette to"; cout << "file.\n"; exit(103); } //this loop writes the image data for (int i = 0; i< height; i++) { for (int j = 0; j<width; j++) { fs_data.write((char *)&image.image_ptr[i][j], sizeof(byte_t)); if (!fs_data.good()) { cout << "\aError 104 writing bitmap data"; cout << "to file.\n"; exit(104); } } } fs_data.close(); } //================== Open_Output_File =================== // void Open_Output_File(ofstream &out_file) { char out_file_name[80]; cout << "Save file as: "; cin >> out_file_name; out_file.open(out_file_name, ios::out | ios::binary); if (!out_file) { cout << "\nCannot open " << out_file_name << endl; exit(101); } return; }<file_sep># 440-Box-Finder ~~~~code and stuff~~~~give me free private repositories :(~~~~ hear ye hear ye, ye listless souls who have come to this far-flung code island. Abandon all hope of absolution, for this be code of the stranger sort. naught but patches and remnants scrounged up from far away. why are you here anyway? <file_sep>#include "imageOpen.h" #include "preprocessor.h" int main() { int exitflag = 0; bmpBITMAP_FILE orig_image; bmpBITMAP_FILE copy1,copy2; Load_Bitmap_File(orig_image); Display_FileHeader(orig_image.fileheader); Display_InfoHeader(orig_image.infoheader); Copy_Image(orig_image, copy2); cout << endl << "A second copy of the file has been " << "made to process."; //Free memory of image //Remove_Image(orig_image); // frees dynamic memory too //cout << endl << "The original image has been " << //"removed from main memory." << endl; //select image processing choice for copy2 while (exitflag == 0) { cout << endl << "Choose a processing option." << endl; cout << "0: display array, 1: increase brightness, 2: decrease brightness" << endl; cout << "3: increase contrast, 4: decrease contrast, 5: median smooth" << endl; cout << "6: equalize, 7: edge detect, 8: thin, 9: convert to black and white" << endl; cout << "b: convert to binary(test), g: convert to gray scale" << endl; cout << "s: save current image, r: reset image, e: exit" << endl; char option; cin >> option; switch (option) { case '0': cout << "Display bitmap file." << endl; Display_Bitmap_File(copy2); break; case '1': cout << "enter amount to increase brightness by." << endl; int brightness1; cin >> brightness1; increaseBrightness(copy2, brightness1); break; case '2': cout << "enter amount to decrease brightness by." << endl; int brightness2; cin >> brightness2; decreaseBrightness(copy2, brightness2); break; case '3': cout << "enter amount greater than 1 to increase contrast by." << endl; double contrast1; cin >> contrast1; increaseContrast(copy2, contrast1); break; case '4': cout << "enter amount less than 1 to decrease contrast by." << endl; double contrast2; cin >> contrast2; decreaseContrast(copy2, contrast2); break; case '5': cout << "median smoothing" << endl; medianSmooth(copy2); break; case '6': cout << "equalizing" << endl; histogramEqualization(copy2); break; case '7': cout << "sobel edge detect" << endl; sobelEdgeDetection(copy2); break; case '8': cout << "crappy thin" << endl; //thinning(copy2); doZhangSuenThinning(copy2); break; case '9': cout << "converting grayscale to black and white" << endl; grayToBlackWhite(copy2); break; case 'b': cout << "converting grayscale to binary" << endl; grayToBinary(copy2); break; case 'g': cout << "converting binary to grayscale" << endl; binaryToGray(copy2); break; case 's': cout << endl << "To show the edited copy's changes " << endl; cout << "Save the copy as a bitmap." << endl; Save_Bitmap_File(copy2); break; case 'r': cout << endl << "Resetting changes to image" << endl; Copy_Image(orig_image, copy2); break; case 'e': cout << "Finished" << endl; exitflag = 1; break; default: cout << "Invalid input" << endl; break; } } //save copy2 to a output bitmap to show the changes //cout << endl << "To show the edited copy's changes " << endl; //cout << "Save the copy as a bitmap." << endl; Remove_Image(orig_image); Remove_Image(copy2); return 0; }
3e020cc7d5aeaf213d92797ea0849854e1f4bce2
[ "Markdown", "C++" ]
7
C++
raptor0dev/440-Box-Finder
02bdf41ab03ca466014439f5db5e90d75ca83439
72a79afbe582b271b07c4964406b82a2c4807c94
refs/heads/master
<file_sep><?php namespace Avkdev\YmParserBundle\Entity; use Doctrine\Common\Collections\Criteria; use Doctrine\ORM\EntityRepository; /** * ProductRepository * * This class was generated by the Doctrine ORM. Add your own custom * repository methods below. */ class ProductRepository extends EntityRepository { public function findByYandexModelId(array $ids) { $criteria = Criteria::create() ->where(Criteria::expr()->in('yandexModelId', $ids)); return $this->matching($criteria); } } <file_sep><?php namespace Avkdev\YmParserBundle\Entity; use Doctrine\ORM\Mapping as ORM; /** * Product */ class Product { /** * @var integer */ private $id; /** * @var integer */ private $categoryId; /** * @var integer */ private $yandexModelId; /** * @var string */ private $name; /** * @var string */ private $retail; /** * @var string */ private $currency; /** * @var string */ private $descr; /** * @var string */ private $urlOriginal; /** * @var string */ private $urlPhoto; /** * @var \Avkdev\YmParserBundle\Entity\Category */ private $category; /** * Get id * * @return integer */ public function getId() { return $this->id; } /** * Set categoryId * * @param integer $categoryId * @return Product */ public function setCategoryId($categoryId) { $this->categoryId = $categoryId; return $this; } /** * Get categoryId * * @return integer */ public function getCategoryId() { return $this->categoryId; } /** * Set yandexModelId * * @param integer $yandexModelId * @return Product */ public function setYandexModelId($yandexModelId) { $this->yandexModelId = $yandexModelId; return $this; } /** * Get yandexModelId * * @return integer */ public function getYandexModelId() { return $this->yandexModelId; } /** * Set name * * @param string $name * @return Product */ public function setName($name) { $this->name = $name; return $this; } /** * Get name * * @return string */ public function getName() { return $this->name; } /** * Set retail * * @param string $retail * @return Product */ public function setRetail($retail) { $this->retail = $retail; return $this; } /** * Get retail * * @return string */ public function getRetail() { return $this->retail; } /** * Set currency * * @param string $currency * @return Product */ public function setCurrency($currency) { $this->currency = $currency; return $this; } /** * Get currency * * @return string */ public function getCurrency() { return $this->currency; } /** * Set descr * * @param string $descr * @return Product */ public function setDescr($descr) { $this->descr = $descr; return $this; } /** * Get descr * * @return string */ public function getDescr() { return $this->descr; } /** * Set urlOriginal * * @param string $urlOriginal * @return Product */ public function setUrlOriginal($urlOriginal) { $this->urlOriginal = $urlOriginal; return $this; } /** * Get urlOriginal * * @return string */ public function getUrlOriginal() { return $this->urlOriginal; } /** * Set urlPhoto * * @param string $urlPhoto * @return Product */ public function setUrlPhoto($urlPhoto) { $this->urlPhoto = $urlPhoto; return $this; } /** * Get urlPhoto * * @return string */ public function getUrlPhoto() { return $this->urlPhoto; } /** * Set category * * @param \Avkdev\YmParserBundle\Entity\Category $category * @return Product */ public function setCategory(\Avkdev\YmParserBundle\Entity\Category $category = null) { $this->category = $category; return $this; } /** * Get category * * @return \Avkdev\YmParserBundle\Entity\Category */ public function getCategory() { return $this->category; } public function __toString() { return $this->getYandexModelId() . ' | ' . $this->getName(); } } <file_sep><?php namespace Avkdev\YmParserBundle; use Symfony\Component\HttpKernel\Bundle\Bundle; class AvkdevYmParserBundle extends Bundle { } <file_sep><?php /** * Created by PhpStorm. * User: alex * Date: 29.08.14 * Time: 20:52 */ namespace Avkdev\YmParserBundle\Parser; use Avkdev\YmParserBundle\Entity\Product; class YandexMarket extends AbstractParser { const BASE_URL = 'http://market.yandex.ua'; /** * {@inheritdoc} */ protected function makeOutHtml($response) { $xpath = new \DOMXPath($response->toDomDocument()); $nodes = $xpath->query("//div[@id]"); $entities = []; $i = 0; /** @var $node \DOMElement */ foreach ($nodes as $node) { $product = new Product(); $product->setCategory($this->task->getCategory()); // yandex_model_id $product->setYandexModelId($node->getAttribute('id')); // parse <a> tag /** @var $item \DOMElement */ foreach ($node->getElementsByTagName('a') as $item) { if ($item->getAttribute('class') != 'b-offers__name') { continue; } $product->setUrlOriginal(self::BASE_URL . $item->attributes->getNamedItem('href')->nodeValue); $product->setName($item->nodeValue); break; } // parse <img> tag $product->setUrlPhoto( $node->getElementsByTagName('img')->item(0)->attributes->getNamedItem('src')->nodeValue ); // parse <p> tag $product->setDescr(trim($node->getElementsByTagName('p')->item(0)->nodeValue)); $entities[$i++] = $product; } // parse retail and currency $nodes = $xpath->query('//span[starts-with(@class,"b-prices ")]'); $i = -1; /** @var $node \DOMElement */ foreach ($nodes as $node) { $i++; $childs = $node->getElementsByTagName('span'); if ($childs->length == 0) { continue; } $retail = (double)trim($childs->item(0)->nodeValue); $currency = trim($childs->item(1)->nodeValue); //$this->output->writeln("$i. $retail $currency"); $entities[$i]->setRetail($retail); $entities[$i]->setCurrency($currency); } return $entities; } /** * {@inheritdoc} */ protected function buildUrl() { $yandexCatId = $this->task->getCategory()->getYandexCatId(); $pattern = "CMD=-RR=0,0,0,0-VIS=8470-CAT_ID=%d-BPOS=%d"; return self::BASE_URL . "/guru.xml?" . sprintf($pattern, $yandexCatId, $this->buildPageOffset($this->getNumPage())); } /** * {@inheritdoc} */ protected function buildPageOffset($numPage) { return $numPage * 10 - 10; } /** * {@inheritdoc} */ protected function getHeaders() { return array( 'User-Agent' => 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/37.0.2062.94 Safari/537.36', 'Accept' => 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8', 'Accept-Language' => 'ru,uk;q=0.8,en-US;q=0.6,en;q=0.4', 'Accept-Encoding' => 'gzip,deflate,sdch', 'Connection' => 'keep-alive', 'Cookie' => 'fuid01=533555a26a8f3b82.2L4g2_Nbsh7iUYY7k6mBMJevRvcTw7O1tAFPw5aWQTqGF1uLkWlv9vlDZymS9n16J2PO7is5FEQsQe-ajbKnHoAD-6TBDJjDptRjYB7Ed_iAw9f-XhNocNd2IdiaBFBc; yandexuid=106970761394314933; ys=wprid.1403073436079795-480307191671301785517789-8-047-PPS; yabs-frequency=/4/0000000000000000/jSznS7GPH_RFSN1q6Lm0/; Session_id=noauth:1406622004; M=1409147239420; ps_gch=1863671348593794048; uid=CmZNWlP94WcYr20AByV0Ag==; TOP10=9281948,10406906,8226328,10413823,10505954,9367527,10711495,10848877,10481279,10692975; markethistory=<h><cm>686672-10404684</cm><cm>160043-10495456</cm><cm>971072-8512100</cm><m>160043-10495456</m><m>686672-10404684</m><m>106388-6211881</m><m>971072-8512100</m><c>686672</c><c>160043</c><c>115828</c></h>; ps_bch=3467907325981784064; yandexmarket=10,UAH,1,,,,2,0,0; cuts=0; _ym_visorc_160656=w', ); } /** * {@inheritdoc} */ protected function persistProducts(array $entities) { // check existense into DB $ids = array_flip(array_map(function ($e) { return $e->getYandexModelId();}, $entities)); /** @var $repo ProductRepository */ $res = $this->container->get('avkdev_ym_parser.product_repository')->findByYandexModelId(array_keys($ids)); foreach ($res as $i) { unset($ids[$i->getYandexModelId()]); } /** @var $entity Product */ foreach ($entities as $entity) { if (!array_key_exists($entity->getYandexModelId(), $ids)) { continue; } $this->em->persist($entity); } $this->em->flush(); } } <file_sep><?php /** * Created by PhpStorm. * User: alex * Date: 29.08.14 * Time: 20:11 */ namespace Avkdev\YmParserBundle\Parser; use Avkdev\YmParserBundle\Entity\Task; use Doctrine\ORM\EntityManager; use Symfony\Component\DependencyInjection\ContainerAware; use Symfony\Component\Security\Acl\Exception\Exception; use Symfony\Component\Console\Output\OutputInterface; abstract class AbstractParser extends ContainerAware { /** * @var Task */ protected $task; /** * @var EntityManager */ protected $em; /** * @var array */ protected $progressStatus = array( 'numPage' => 1 ); /** * @var OutputInterface */ protected $output; /** * Run parser */ public function run() { $this->em = $this->container->get('doctrine.orm.entity_manager'); /** @var $tasks \Doctrine\Common\Collections\ArrayCollection */ $tasks = $this->container->get('avkdev_ym_parser.task_repository')->getUnresolvedTasks(); $this->output->writeln("Num tasks: " . $tasks->count()); /** @var $task \Avkdev\YmParserBundle\Entity\Task */ foreach ($tasks as $task) { $this->task = $task; $this->persistStatus(Task::STATUS_PROCESSING); try { $this->loadProgressStatus(); $this->parse(); $this->persistStatus(Task::STATUS_DONE); } catch (Exception $e) { $this->persistStatus(Task::STATUS_ERROR); } } return $this; } /** * Save task status * @param $status * @return $this */ public function persistStatus($status) { $this->task->setStatus($status); $this->em->persist($this->task); $this->em->flush(); return $this; } /** * Load progress status for task * @return $this */ protected function loadProgressStatus() { $this->progressStatus = $this->task->getProgressStatus(); if (empty($this->progressStatus)) { $this->progressStatus = array( 'numPage' => 1 ); } return $this; } /** * main parser method * @return $this */ protected function parse() { $maxNumPages = $this->container->getParameter('ymparser_num_pages'); $sleepTime = $this->container->getParameter('ymparser_sleep_time'); // start parsing for ($i = $this->getNumPage(); $i <= $maxNumPages; $i++) { $this->setNumPage($i); $this->parsePage(); sleep($sleepTime); } return $this; } /** * @return int */ protected function getNumPage() { return $this->progressStatus['numPage']; } /** * @param $num integer * @return $this */ protected function setNumPage($num) { $this->progressStatus['numPage'] = $num; return $this; } /** * Parse current page * @return $this */ protected function parsePage() { $this->saveProgressStatus(); $url = $this->buildUrl(); $this->output->writeln("Parsing page {$this->getNumPage()}: $url"); $browser = $this->container->get('buzz.browser'); $entities = $this->makeOutHtml($browser->get($url, $this->getHeaders())); $this->persistProducts($entities); return $this; } /** * Save current task state * @return $this */ protected function saveProgressStatus() { $this->task->setProgressStatus($this->progressStatus); $this->em->persist($this->task); $this->em->flush(); return $this; } /** * @return array */ protected function getHeaders() { return array(); } /** * @param OutputInterface $output * @return $this */ public function setOutput(OutputInterface $output) { $this->output = $output; return $this; } /** * Calculate page offset for load a specified page * @param $numPage * @return int */ protected function buildPageOffset($numPage) { return $numPage; } /** * Build url for creating request * @return string */ abstract protected function buildUrl(); /** * Parse HTML and fetch data to entities array * @param $response \Buzz\Message\Response * @return mixed */ abstract protected function makeOutHtml($response); /** * @param array $entities */ abstract protected function persistProducts(array $entities); } <file_sep><?php /** * Created by PhpStorm. * User: alex * Date: 27.08.14 * Time: 18:55 */ namespace Avkdev\YmParserBundle\DataFixtures\ORM; use Doctrine\Common\DataFixtures\Doctrine; use Doctrine\Common\DataFixtures\OrderedFixtureInterface; use Doctrine\Common\DataFixtures\AbstractFixture; use Doctrine\Common\Persistence\ObjectManager; use Avkdev\YmParserBundle\Entity\Category; class LoadCategoryData extends AbstractFixture implements OrderedFixtureInterface { public function load(ObjectManager $manager) { // categories $cat1 = new Category(); $cat1 ->setYandexCatId('117929') ->setName("Вытяжки"); $manager->persist($cat1); $cat2 = new Category(); $cat2 ->setYandexCatId(106388) ->setName("Посудомоечные машины"); $manager->persist($cat2); $manager->flush(); $this->addReference('cat1', $cat1); $this->addReference('cat2', $cat2); } /** * Get the order of this fixture * * @return integer */ public function getOrder() { return 1; } } <file_sep><?php namespace Avkdev\YmParserBundle\Form; use Symfony\Component\Form\AbstractType; use Symfony\Component\Form\FormBuilderInterface; use Symfony\Component\OptionsResolver\OptionsResolverInterface; use Avkdev\YmParserBundle\Entity\CategoryRepository; class TaskType extends AbstractType { /** * @param FormBuilderInterface $builder * @param array $options */ public function buildForm(FormBuilderInterface $builder, array $options) { $builder ->add( 'category', 'entity', array( 'class' => 'Avkdev\YmParserBundle\Entity\Category', 'query_builder' => function (CategoryRepository $r) { return $r->createQueryBuilder('c'); }, 'required' => true, ) ); $builder->add('runDate', null, array('data' => new \DateTime())); // $builder->add('isRepeat', 'checkbox', array( // 'required' => false // )); // $builder->add('status'); // $builder->add('progressStatus'); } /** * @param OptionsResolverInterface $resolver */ public function setDefaultOptions(OptionsResolverInterface $resolver) { $resolver->setDefaults(array( 'data_class' => 'Avkdev\YmParserBundle\Entity\Task' )); } /** * @return string */ public function getName() { return 'avkdev_ymparserbundle_task'; } } <file_sep><?php /** * Created by PhpStorm. * User: alex * Date: 27.08.14 * Time: 18:55 */ namespace Avkdev\YmParserBundle\DataFixtures\ORM; use Doctrine\Common\DataFixtures\Doctrine; use Doctrine\Common\DataFixtures\OrderedFixtureInterface; use Doctrine\Common\DataFixtures\AbstractFixture; use Doctrine\Common\Persistence\ObjectManager; use Avkdev\YmParserBundle\Entity\Product; class LoadProductData extends AbstractFixture implements OrderedFixtureInterface { public function load(ObjectManager $manager) { // products for ($i = 0; $i < 10; $i++) { $product = new Product(); $product ->setCurrency("грн") ->setDescr("стационарный, автомобильный, ПО: Garmin, дисплей 5 дюйм., 480x272 пикс., USB, слот MicroSD, голосовые сообщения") ->setName("Garmin nuvi 150LMT") ->setRetail(2560 + $i * 10) ->setCategory($manager->merge($this->getReference('cat1'))) ->setYandexModelId(45435435 + $i) ->setUrlOriginal("http://market.yandex.ua/model.xml?modelid=8512100&hid=294661") ->setUrlPhoto("http://mdata.yandex.net/i?path=b0922125700_img_id336785696886444143.jpeg"); $manager->persist($product); } $manager->flush(); } /** * Get the order of this fixture * * @return integer */ public function getOrder() { return 2; } } <file_sep><?php /** * Created by PhpStorm. * User: alex * Date: 29.08.14 * Time: 20:04 */ namespace Avkdev\YmParserBundle\Command; use Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand; use Symfony\Component\Console\Input\InputArgument; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Input\InputOption; use Symfony\Component\Console\Output\OutputInterface; class ParseCommand extends ContainerAwareCommand { protected function configure() { $this ->setName('ymparser:run') ->setDescription('Yandex Market Parser'); } protected function execute(InputInterface $input, OutputInterface $output) { $parser = $this->getContainer()->get('avkdev_ym_parser.ymparser'); $parser->setOutput($output); $parser->run(); } } <file_sep>$(function() { $(".products").tablesorter(); }) <file_sep><?php namespace Avkdev\YmParserBundle\Entity; use Doctrine\ORM\Mapping as ORM; /** * Task */ class Task { const STATUS_PENDING = 0; const STATUS_PROCESSING = 1; const STATUS_DONE = 2; const STATUS_ERROR = 3; /** * @var integer */ private $id; /** * @var integer */ private $yandexCatId; /** * @var \DateTime */ private $createDate; /** * @var integer */ private $status; /** * @var array */ private $progressStatus; /** * Get id * * @return integer */ public function getId() { return $this->id; } /** * Set yandexCatId * * @param integer $yandexCatId * @return Task */ public function setYandexCatId($yandexCatId) { $this->yandexCatId = $yandexCatId; return $this; } /** * Get yandexCatId * * @return integer */ public function getYandexCatId() { return $this->yandexCatId; } /** * Set createDate * * @param \DateTime $createDate * @return Task */ public function setCreateDate($createDate) { $this->createDate = $createDate; return $this; } /** * Get createDate * * @return \DateTime */ public function getCreateDate() { return $this->createDate; } /** * Set status * * @param integer $status * @return Task */ public function setStatus($status) { $this->status = $status; return $this; } /** * Get status * * @return integer */ public function getStatus() { return $this->status; } /** * Set progressStatus * * @param array $progressStatus * @return Task */ public function setProgressStatus($progressStatus) { $this->progressStatus = $progressStatus; return $this; } /** * Get progressStatus * * @return array */ public function getProgressStatus() { return $this->progressStatus; } public function getProgressStatusStr() { return print_r($this->getProgressStatus(), true); } /** * @var \DateTime */ private $runDate; /** * @var boolean */ private $isRepeat; /** * Set runDate * * @param \DateTime $runDate * @return Task */ public function setRunDate($runDate) { $this->runDate = $runDate; return $this; } /** * Get runDate * * @return \DateTime */ public function getRunDate() { return $this->runDate; } /** * Set isRepeat * * @param boolean $isRepeat * @return Task */ public function setIsRepeat($isRepeat) { $this->isRepeat = $isRepeat; return $this; } /** * Get isRepeat * * @return boolean */ public function getIsRepeat() { return $this->isRepeat; } /** * @ORM\PrePersist */ public function setCreateDateValue() { $this->setCreateDate(new \DateTime()); return $this; } /** * @ORM\PrePersist */ public function setStatusValue() { $this->setStatus(0); return $this; } /** * @var integer */ private $categoryId; /** * Set categoryId * * @param integer $categoryId * @return Task */ public function setCategoryId($categoryId) { $this->categoryId = $categoryId; return $this; } /** * Get categoryId * * @return integer */ public function getCategoryId() { return $this->categoryId; } /** * @var \Avkdev\YmParserBundle\Entity\Category */ private $category; /** * Set category * * @param \Avkdev\YmParserBundle\Entity\Category $category * @return Task */ public function setCategory(\Avkdev\YmParserBundle\Entity\Category $category = null) { $this->category = $category; return $this; } /** * Get category * * @return \Avkdev\YmParserBundle\Entity\Category */ public function getCategory() { return $this->category; } /** * @return array */ public static function getStatusList() { return array ( self::STATUS_DONE => 'Выполнено', self::STATUS_ERROR => 'Ошибка', self::STATUS_PENDING => 'Ожидает выполнения', self::STATUS_PROCESSING => 'В процессе', ); } public function getStatusString() { return self::getStatusList()[$this->getStatus()]; } public function __toString() { return '#' . $this->getId() . ' | ' . $this->getCategory()->getName(); } /** * @ORM\PrePersist */ public function setIsRepeatValue() { $this->setIsRepeat(0); return $this; } } <file_sep><?php /** * Created by PhpStorm. * User: alex * Date: 27.08.14 * Time: 18:55 */ namespace Avkdev\YmParserBundle\DataFixtures\ORM; use Doctrine\Common\DataFixtures\Doctrine; use Doctrine\Common\DataFixtures\OrderedFixtureInterface; use Doctrine\Common\DataFixtures\AbstractFixture; use Doctrine\Common\Persistence\ObjectManager; use Avkdev\YmParserBundle\Entity\Task; class LoadTaskData extends AbstractFixture implements OrderedFixtureInterface { public function load(ObjectManager $manager) { // tasks $task = new Task(); $task ->setCategory($manager->merge($this->getReference('cat1'))) ->setStatus(0) ->setIsRepeat(false) ->setRunDate(new \DateTime()); $manager->persist($task); $manager->flush(); } /** * Get the order of this fixture * * @return integer */ public function getOrder() { return 3; } } <file_sep><?php namespace Avkdev\YmParserBundle\Entity; use Doctrine\ORM\EntityRepository; use Doctrine\Common\Collections\Criteria; use Avkdev\YmParserBundle\Entity\Task; /** * TaskRepository * * This class was generated by the Doctrine ORM. Add your own custom * repository methods below. */ class TaskRepository extends EntityRepository { public function getUnresolvedTasks() { $criteria = Criteria::create() ->where(Criteria::expr()->lt('runDate', new \DateTime())) ->andWhere(Criteria::expr()->in('status', array(Task::STATUS_PENDING,Task::STATUS_ERROR))) ->orderBy(array('runDate' => Criteria::ASC)); return $this->matching($criteria); } } <file_sep><?php namespace Avkdev\YmParserBundle\Entity; use Doctrine\ORM\EntityRepository; /** * CategoryRepository * * This class was generated by the Doctrine ORM. Add your own custom * repository methods below. */ class CategoryRepository extends EntityRepository { public function getList() { return $this ->createQueryBuilder('c') ->add('orderBy', 'c.name ASC'); } }
8e0e1ddc147f27bff53d7104507493a49f89c6d5
[ "JavaScript", "PHP" ]
14
PHP
alexeyst14/ymp
60ed9a8f9888fc9cf8be9358a25f75971ce2b93f
a47540adb6be6efd7c912ab3dd783404a4a7a708
refs/heads/master
<repo_name>pacargile/charm<file_sep>/charm/fitting.py import sys import dynesty from datetime import datetime import numpy as np from .model import clustermodel from .priors import priors class charmfit(object): """docstring for charmfit""" def __init__(self,inarr,*args,**kwargs): super(charmfit, self).__init__() # input array self.inarr = inarr # other input args and keywords self.args = args self.kwargs = kwargs # set ndim self.ndim = 6 # set verbose self.verbose = self.kwargs.get('verbose',True) # make sure inarr has correct parameters try: assert('RA' in self.inarr.keys()) assert('Dec' in self.inarr.keys()) assert('Parallax' in self.inarr.keys()) except AssertionError: print('-- Could not find RA/Dec/Parallax keys in input dictionary') raise IOError # initialize the model class self.clustermodel = clustermodel( self.inarr, self.kwargs.get('Nsamples',1000.0), modeltype=self.kwargs.get('ModelType','gaussian')) # initialize the prior class priordict = self.kwargs.get('priordict',{}) self.priors = priors self.priorobj = self.priors(priordict) # initialize the output file self._initoutput() # bulid sampler self._buildsampler() def _initoutput(self): # determine if user defined output filename output_fn = self.kwargs.get('output','test.out') # init output file self.outff = open(output_fn,'w') self.outff.write('Iter ') self.outff.write('X sig_X Y sig_Y Z sig_Z ') self.outff.write('log(lk) log(vol) log(wt) h nc log(z) delta(log(z))') self.outff.write('\n') def _buildsampler(self): # pull out user defined sampler variables samplerdict = self.kwargs.get('samplerdict',{}) self.npoints = samplerdict.get('npoints',200) self.samplertype = samplerdict.get('samplertype','multi') self.samplemethod = samplerdict.get('samplemethod','unif') self.bootstrap = samplerdict.get('bootstrap',0) self.update_interval = samplerdict.get('update_interval',0.6) self.delta_logz_final = samplerdict.get('delta_logz_final',1.0) self.flushnum = samplerdict.get('flushnum',100) self.maxiter = samplerdict.get('maxiter',sys.maxsize) self.walks = samplerdict.get('walks',25) # initialize sampler object self.dy_sampler = dynesty.NestedSampler( self.likefn, self.priorobj.priortrans, self.ndim, # logl_args=[self.likeobj,self.priorobj], nlive=self.npoints, bound=self.samplertype, sample=self.samplemethod, update_interval=self.update_interval, bootstrap=self.bootstrap, walks=self.walks, ) def likefn(self,args): likeprob = self.clustermodel.likefn(args) # likeprob += -0.5*(((args[1]-20.0)/5.0)**2.0) return likeprob def runsampler(self): # set start time starttime = datetime.now() if self.verbose: print( ('Start Dynesty w/ {0} number of samples, Ndim = {1}, ' 'and w/ stopping criteria of dlog(z) = {2}: {3}').format( self.npoints,self.ndim,self.delta_logz_final,starttime)) sys.stdout.flush() ncall = 0 nit = 0 iter_starttime = datetime.now() deltaitertime_arr = [] # start sampling for it, results in enumerate(self.dy_sampler.sample(dlogz=self.delta_logz_final)): (worst, ustar, vstar, loglstar, logvol, logwt, logz, logzvar, h, nc, worst_it, propidx, propiter, eff, delta_logz) = results self.outff.write('{0} '.format(it)) self.outff.write(' '.join([str(q) for q in vstar])) self.outff.write(' {0} {1} {2} {3} {4} {5} {6} '.format( loglstar,logvol,logwt,h,nc,logz,delta_logz)) self.outff.write('\n') ncall += nc nit = it deltaitertime_arr.append((datetime.now()-iter_starttime).total_seconds()/float(nc)) iter_starttime = datetime.now() if ((it%self.flushnum) == 0) or (it == self.maxiter): self.outff.flush() if self.verbose: # format/output results if logz < -1e6: logz = -np.inf if delta_logz > 1e6: delta_logz = np.inf if logzvar >= 0.: logzerr = np.sqrt(logzvar) else: logzerr = np.nan if logzerr > 1e6: logzerr = np.inf sys.stdout.write("\riter: {0:d} | nc: {1:d} | ncall: {2:d} | eff(%): {3:6.3f} | " "logz: {4:6.3f} +/- {5:6.3f} | dlogz: {6:6.3f} > {7:6.3f} | mean(time): {8} " .format(nit, nc, ncall, eff, logz, logzerr, delta_logz, self.delta_logz_final,np.mean(deltaitertime_arr))) sys.stdout.flush() deltaitertime_arr = [] if (it == self.maxiter): break # add live points to sampler object for it2, results in enumerate(self.dy_sampler.add_live_points()): # split up results (worst, ustar, vstar, loglstar, logvol, logwt, logz, logzvar, h, nc, worst_it, boundidx, bounditer, eff, delta_logz) = results self.outff.write('{0} '.format(nit+it2)) self.outff.write(' '.join([str(q) for q in vstar])) self.outff.write(' {0} {1} {2} {3} {4} {5} {6} '.format( loglstar,logvol,logwt,h,nc,logz,delta_logz)) self.outff.write('\n') ncall += nc if self.verbose: # format/output results if logz < -1e6: logz = -np.inf if delta_logz > 1e6: delta_logz = np.inf if logzvar >= 0.: logzerr = np.sqrt(logzvar) else: logzerr = np.nan if logzerr > 1e6: logzerr = np.inf sys.stdout.write("\riter: {:d} | nc: {:d} | ncall: {:d} | eff(%): {:6.3f} | " "logz: {:6.3f} +/- {:6.3f} | dlogz: {:6.3f} > {:6.3f} " .format(nit + it2, nc, ncall, eff, logz, logzerr, delta_logz, self.delta_logz_final)) sys.stdout.flush() # close the output file self.outff.close() sys.stdout.write('\n') finishtime = datetime.now() if self.verbose: print('RUN TIME: {0}'.format(finishtime-starttime)) sys.stdout.flush() <file_sep>/charm/priors.py import numpy as np class priors(object): """docstring for priors""" def __init__(self, inpriordict): super(priors, self).__init__() # find uniform priors and put them into a # dictionary used for the prior transformation self.priordict = {} # put any additional priors into a dictionary so that # they can be applied in the lnprior_* functions self.additionalpriors = {} for kk in inpriordict.keys(): for ii in inpriordict[kk].keys(): if ii == 'uniform': self.priordict[kk] = inpriordict[kk]['uniform'] else: try: self.additionalpriors[kk][ii] = inpriordict[kk][ii] except KeyError: self.additionalpriors[kk] = {ii:inpriordict[kk][ii]} def priortrans(self,upars): # split upars ux,usig_x,uy,usig_y,uz,usig_z = upars outarr = [] if 'X' in self.priordict.keys(): x = ( (max(self.priordict['X'])-min(self.priordict['X']))*ux + min(self.priordict['X']) ) else: x = (1e+5 - -1e+5)*ux - 1e+5 if 'sig_X' in self.priordict.keys(): sig_x = ( (max(self.priordict['sig_X'])-min(self.priordict['sig_X']))*usig_x + min(self.priordict['sig_X']) ) else: sig_x = (10000.0 - 0.0)*usig_x + 0.0 if 'Y' in self.priordict.keys(): y = ( (max(self.priordict['Y'])-min(self.priordict['Y']))*uy + min(self.priordict['Y']) ) else: y = (1e+5 - -1e+5)*uy - 1e+5 if 'sig_Y' in self.priordict.keys(): sig_y = ( (max(self.priordict['sig_Y'])-min(self.priordict['sig_Y']))*usig_y + min(self.priordict['sig_Y']) ) else: sig_y = (10000.0 - 0.0)*usig_y + 0.0 if 'Z' in self.priordict.keys(): z = ( (max(self.priordict['Z'])-min(self.priordict['Z']))*uz + min(self.priordict['Z']) ) else: z = (1e+5 - -1e+5)*uz - 1e+5 if 'sig_Z' in self.priordict.keys(): sig_z = ( (max(self.priordict['sig_Z'])-min(self.priordict['sig_Z']))*usig_z + min(self.priordict['sig_Z']) ) else: sig_z = (10000.0 - 0.0)*usig_z + 0.0 pars = [x,sig_x,y,sig_y,z,sig_z] return pars <file_sep>/charm/model.py import numpy as np from scipy.stats import norm as gaussian from astropy import units as u from astropy.coordinates import SkyCoord def gauss(args): x,mu,sigma = args return 1/(sigma*np.sqrt(2*np.pi))*np.exp(-(x - mu)**2 / (2*sigma**2)) class clustermodel(object): """docstring for clustermodel""" def __init__(self, inarr, Nsamp, modeltype='gaussian'): super(clustermodel, self).__init__() self.inarr = inarr self.Nstars = len(self.inarr) self.starid = range(self.Nstars) self.Nsamp = Nsamp self.modeltype = modeltype # generate grid of samples for each star # self.starsamples = np.empty( (self.Nstars, self.Nsamp) ) # for idx in self.starid: # self.starsamples[idx,:] = gaussian( # loc=self.inarr['Parallax'][idx], # scale=self.inarr['Parallax_Error'][idx]).rvs(size=self.Nsamp) """ self.starsamples = np.array([{} for _ in range(self.Nstars)]) for idx in self.starid: RAdist = gaussian( loc=self.inarr['RA'][idx], scale=self.inarr['RA_Error'][idx]).rvs(size=self.Nsamp) Decdist = gaussian( loc=self.inarr['Dec'][idx], scale=self.inarr['Dec_Error'][idx]).rvs(size=self.Nsamp) Distdist = 1000.0/gaussian( loc=self.inarr['Parallax'][idx], scale=self.inarr['Parallax_Error'][idx]).rvs(size=self.Nsamp) Xarr = [] Yarr = [] Zarr = [] for ra_i,dec_i,dist_i in zip(RAdist,Decdist,Distdist): c = SkyCoord(ra=ra_i*u.deg,dec=dec_i*u.deg,distance=dist_i*u.pc) Xarr.append(float(c.galactocentric.x.value)) Yarr.append(float(c.galactocentric.y.value)) Zarr.append(float(c.galactocentric.z.value)) self.starsamples[idx] = ({ 'X':np.array(Xarr), 'Y':np.array(Yarr), 'Z':np.array(Zarr), }) """ self.starsamples = np.empty((3,self.Nstars,self.Nsamp)) for idx in range(self.Nstars): RAdist = gaussian( loc=self.inarr['RA'][idx], scale=self.inarr['RA_Error'][idx]).rvs(size=self.Nsamp) Decdist = gaussian( loc=self.inarr['Dec'][idx], scale=self.inarr['Dec_Error'][idx]).rvs(size=self.Nsamp) Distdist = 1000.0/gaussian( loc=self.inarr['Parallax'][idx], scale=self.inarr['Parallax_Error'][idx]).rvs(size=self.Nsamp) for idd,dim in enumerate(['x','y','z']): c = SkyCoord(ra=RAdist*u.deg,dec=Decdist*u.deg,distance=Distdist*u.pc) if dim == 'x': self.starsamples[idd,idx,:] = np.array(c.galactocentric.x.value) elif dim == 'y': self.starsamples[idd,idx,:] = np.array(c.galactocentric.y.value) elif dim == 'z': self.starsamples[idd,idx,:] = np.array(c.galactocentric.z.value) else: raise IOError def likefn(self,arg): # dist,sigma_dist = arg x,sigma_x,y,sigma_y,z,sigma_z = arg # calculate like for all stars if self.modeltype == 'gaussian': # Gaussian model like = ( ((1.0/(np.sqrt(2.0*np.pi)*sigma_x)) * np.exp( -0.5 * ((self.starsamples[0,...] -x)**2.0)*(sigma_x**-2.0) )) + ((1.0/(np.sqrt(2.0*np.pi)*sigma_y)) * np.exp( -0.5 * ((self.starsamples[1,...]-y)**2.0)*(sigma_y**-2.0) )) + ((1.0/(np.sqrt(2.0*np.pi)*sigma_z)) * np.exp( -0.5 * ((self.starsamples[2,...]-z)**2.0)*(sigma_z**-2.0) )) ) elif self.modeltype == 'cauchy': # Cauchy model like = ( ((1.0/(np.pi*sigma_x)) * (sigma_x**2.0)/( ((self.starsamples[0,...]-x)**2.0) + (sigma_x**2.0) )) + ((1.0/(np.pi*sigma_y)) * (sigma_y**2.0)/( ((self.starsamples[1,...]-y)**2.0) + (sigma_y**2.0) )) + ((1.0/(np.pi*sigma_z)) * (sigma_z**2.0)/( ((self.starsamples[2,...]-z)**2.0) + (sigma_z**2.0) )) ) elif self.modeltype == 'plummer': # Plummer model like = ( ( (1.0/(sigma_x**3.0)) * ((1.0 + (((self.starsamples[0,...]-x)/sigma_x)**2.0))**(-5.0/2.0)) ) + ( (1.0/(sigma_y**3.0)) * ((1.0 + (((self.starsamples[1,...]-y)/sigma_y)**2.0))**(-5.0/2.0)) ) + ( (1.0/(sigma_z**3.0)) * ((1.0 + (((self.starsamples[2,...]-z)/sigma_z)**2.0))**(-5.0/2.0)) ) ) else: print('Did not understand model type') raise IOError if np.min(like) <= np.finfo(np.float).eps: return -np.inf like = (like.T*self.inarr['Prob']).T lnp = np.sum(np.log(like)) return lnp<file_sep>/setup.py #!/usr/bin/env python # -*- coding: utf-8 -*- import os import sys import re try: from setuptools import setup setup except ImportError: from distutils.core import setup setup setup( name="charm", version='0.1', author="<NAME>", author_email="<EMAIL>", packages=["charm"], url="", #license="LICENSE", description="Cluster Heirarchical Astrometric Modeling", long_description=open("README.md").read() + "\n\n", #install_requires=["numpy", "scipy"], )
318e20135bf5c87ecfea1301bc94edbbfed9630a
[ "Python" ]
4
Python
pacargile/charm
b579442c672afaa7bc39ffb4cfee77ebd473d2b6
f9cca2ed256c4e48772162803e3b2856074a4855
refs/heads/master
<file_sep>package io.swagger.api; import io.swagger.api.*; import io.swagger.model.*; import org.glassfish.jersey.media.multipart.FormDataContentDisposition; import io.swagger.model.MementoItem; import io.swagger.model.ModelApiResponse; import java.util.Map; import java.util.List; import io.swagger.api.NotFoundException; import java.io.InputStream; import javax.ws.rs.core.Response; import javax.ws.rs.core.SecurityContext; import javax.validation.constraints.*; @javax.annotation.Generated(value = "io.swagger.codegen.languages.java.JavaJerseyServerCodegen", date = "2018-11-23T14:41:06.005Z[GMT]") public abstract class MementoApiService { public abstract Response addmemento(MementoItem body,SecurityContext securityContext) throws NotFoundException; public abstract Response deleteMemento(Long mementoId,String apiKey,SecurityContext securityContext) throws NotFoundException; public abstract Response getMementoById(Long mementoId,SecurityContext securityContext) throws NotFoundException; public abstract Response getallmementos(SecurityContext securityContext) throws NotFoundException; public abstract Response updateMemento(MementoItem body,SecurityContext securityContext) throws NotFoundException; public abstract Response uploadRecordedVoice(Long mementoId,Object body,SecurityContext securityContext) throws NotFoundException; } <file_sep>package io.swagger.api.impl; import io.swagger.api.*; import io.swagger.model.*; import java.util.ArrayList; import java.util.Map; import java.util.List; import io.swagger.api.NotFoundException; import java.io.InputStream; import org.glassfish.jersey.media.multipart.FormDataContentDisposition; import javax.ws.rs.core.Response; import javax.ws.rs.core.SecurityContext; import javax.validation.constraints.*; @javax.annotation.Generated(value = "io.swagger.codegen.languages.java.JavaJerseyServerCodegen", date = "2018-11-23T14:41:06.005Z[GMT]") public class MementoApiServiceImpl extends MementoApiService { List<MementoItem> lm= new ArrayList<MementoItem>(); @Override public Response addmemento(MementoItem body, SecurityContext securityContext) throws NotFoundException { MementoItem mi= new MementoItem(); mi.setIdMemento(body.getIdMemento()); mi.setTitle(body.getTitle()); mi.setUrlRecordedVoice(body.getUrlRecordedVoice()); mi.setXCoordinate(body.getXCoordinate()); mi.setYCoordinate(body.getYCoordinate()); lm.add(mi); return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "Memento Added!")).build(); } @Override public Response deleteMemento(Long mementoId, String apiKey, SecurityContext securityContext) throws NotFoundException { // do some magic! for (int i = 0; i < lm.size(); i++) { if(lm.get(i).getIdMemento()==mementoId) lm.remove(lm.get(i)); } return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "All Mementos Deleted!")).build(); } @Override public Response getMementoById(Long mementoId, SecurityContext securityContext) throws NotFoundException { // do some magic! MementoItem mi= new MementoItem(); for (int i = 0; i < lm.size(); i++) { if(lm.get(i).getIdMemento()==mementoId) mi=lm.get(i); } return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, mi.toString())).build(); } @Override public Response getallmementos(SecurityContext securityContext) throws NotFoundException { return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, lm.toString())).build(); } @Override public Response updateMemento(MementoItem body, SecurityContext securityContext) throws NotFoundException { MementoItem mi= new MementoItem(); for (int i = 0; i < lm.size(); i++) { if(lm.get(i).getIdMemento()==body.getIdMemento()){ mi= lm.get(i); mi.setIdMemento(body.getIdMemento()); mi.setTitle(body.getTitle()); mi.setUrlRecordedVoice(body.getUrlRecordedVoice()); mi.setXCoordinate(body.getXCoordinate()); mi.setYCoordinate(body.getYCoordinate()); } } return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "Memento Updated!")).build(); } @Override public Response uploadRecordedVoice(Long mementoId, Object body, SecurityContext securityContext) throws NotFoundException { MementoItem mi= new MementoItem(); for (int i = 0; i < lm.size(); i++) { if(lm.get(i).getIdMemento()==mementoId){ mi= lm.get(i); mi.setUrlRecordedVoice(body.toString()); } } return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "RecordedVoice!")).build(); } }
bcea6a41042ba0198928057ad2ab3464977f2a8f
[ "Java" ]
2
Java
ManuJazz/Memento_API
129afbf0ddd8aa5393c2201a1214467f93bf7e67
bd11baa6feacdd87ea332c3c4cbb4262090547b1
refs/heads/master
<file_sep>var $container = {}; var $control = {}; var $slideshow = { domain: location.protocol+'//'+location.hostname+(location.port ? ':'+location.port: ''), open_help: true, position: { current: null, pprev: null, prev: null, next: null, nnext: null, }, direction: null, animation: null, popup: { width: 800, height: 600, autoSize: false, href: false, content: false, scrolling: 'no', iframe: { preload: false } }, garbage: [] }; function init(){ // check current entry $slideshow.position.current = jQuery('.entry.current'); // update browser informations update_page_meta(); // load prev/next entries var _next_source = $slideshow.position.current.attr('data-next_permalink'); var _prev_source = $slideshow.position.current.attr('data-prev_permalink'); var _nnext_source = $slideshow.position.current.attr('data-nnext_permalink'); var _pprev_source = $slideshow.position.current.attr('data-pprev_permalink'); if(_next_source){ load(_next_source,'next'); } if(_prev_source){ load(_prev_source,'prev'); } if(_nnext_source){ load(_nnext_source,'nnext'); } if(_pprev_source){ load(_pprev_source,'pprev'); } } function init_flag($trigger){ var $target = jQuery($trigger.attr('href')); $trigger.flag = $trigger.attr('data-flag'); console.log($trigger.attr('id')+' => '+$target.attr('id')+' ('+$trigger.flag+')'); if($trigger.flag=='true'){ $target.removeClass($trigger.attr('data-flag-false-class')).addClass($trigger.attr('data-flag-true-class')); }else{ $target.removeClass($trigger.attr('data-flag-true-class')).addClass($trigger.attr('data-flag-false-class')); } } function init_flags(){ jQuery('[data-flag]').each(function(index){ init_flag(jQuery(this)); }); } function toggle_flag($trigger,flag){ flag = flag || null; if(flag==null){ flag = $trigger.attr('data-flag')!='true'?true:false; } if(flag){ $trigger.attr('data-flag','true'); }else{ $trigger.attr('data-flag','false'); } init_flag($trigger); return flag; } function resize(position,context){ position = position || ''; position = '#body section.entry'+(position!=''?'.'+position:''); context = context || ''; var flag = '['+position+']'; var padding = $smallgallery.padding; var padnum = $smallgallery.padding.replace(/(\%|px)$/,''); console.log('RESIZE: redrawing '+flag+(context?' ('+context+')':'')); jQuery(position).each(function(index){ var $resolution = jQuery(document).width()+'x'+jQuery(document).height(); var $entry = jQuery(this); var $box = $entry.children('.wrap'); var $feature = $box.find('.feature'); var $img = $feature.find('img'); // get default size $entry.availableWidth = $entry.width(); $entry.availableHeight = $entry.height(); $box.availableWidth = $entry.availableWidth; $box.availableHeight = $entry.availableHeight; console.log('RESIZE: '+flag+' is in the box => '+$box.availableWidth+'x'+$box.availableHeight); // adjust size with given padding value if(padding.search(/\%$/)>0){ $box.availableWidth = $box.availableWidth-(($entry.width()/padnum)*2); $box.availableHeight = $box.availableHeight-(($entry.height()/padnum)*2); } if(padding.search(/px$/)>0){ $box.availableWidth = $box.availableWidth-(padnum*2); $box.availableHeight = $box.availableHeight-(padnum*2); } // consider feature image size if($img.length){ // check natural size of image $feature.givenWidth = $feature.width(); $feature.givenHeight = $feature.height(); console.log('RESIZE: '+flag+' has a featured image => '+$feature.givenWidth+'x'+$feature.givenHeight); // check aspect ratios of image and container $feature.ratio = $feature.givenWidth/$feature.givenHeight; $box.ratio = $box.availableWidth/$box.availableHeight; if($feature.ratio>$box.ratio){ // if image is wider, limit it's width $feature.availableWidth = $box.availableWidth; $feature.availableHeight = $feature.givenHeight*$feature.availableWidth/$feature.givenWidth; }else{ // if container is wider, limit image's height $feature.availableHeight = $box.availableHeight; $feature.availableWidth = $feature.givenWidth*$feature.availableHeight/$feature.givenHeight; } $box.availableWidth = $feature.availableWidth; $box.availableHeight = $feature.availableHeight; } console.log('RESIZE: '+flag+' => available resolution is '+$box.availableWidth+'x'+$box.availableHeight); // calculate size $box.actualWidth = $box.availableWidth; $box.actualHeight = $box.availableHeight; console.log('RESIZE: '+flag+' => actual resolution is '+$box.actualWidth+'x'+$box.actualHeight); // apply size $box.cssWidth = Math.floor($box.actualWidth); $box.cssHeight = Math.floor($img.length?$entry.availableHeight:$box.actualHeight); $box.css({ width: $box.cssWidth, height: 'auto', maxHeight: $box.cssHeight }); /* // update perfect-scrollbar if($entry.is('.page')||$entry.is('.archive')){ $entry.perfectScrollbar(); } if($entry.is('.post')){ $entry.children('.wrap').perfectScrollbar(); } */ console.log('RESIZE: '+flag+' => content resolution is '+$box.width()+'x'+$box.height()); }); fullscreenchange(); // over do for MSIE } function build_url(url,attributes){ attributes = attributes || {}; var filtered = url; var index = 0; var glue = ''; for(key in attributes){ index ++; glue = index>1&&url.search(/\?/)?'&':'?'; value = attributes[key]; filtered = filtered+glue+key+'='+value; } return filtered; } function load(source,position){ var flag = '['+position+']'; console.log('BEGIN: load '+flag+' item -- '+source); if(!jQuery('[data-permalink="'+source+'"]').length){ source_filtered = build_url(source,{format:'json'}); console.log('_SOURCE FILTERED: '+flag+' using '+source+' => '+source_filtered); var _markup; jQuery.getJSON(source_filtered) .done(function(data){ console.log('_DATA LOADED: '+flag+' using '+source_filtered+' => #'+data.ID); _markup = jQuery(data.filtered_post).removeClass('current').addClass('fresh '+position); switch(position){ case 'pprev': case 'prev': $container.prepend(_markup); break; case 'nnext': case 'next': $container.append(_markup); break; } bind_entry_events(_markup.attr('id')); }) .error(function(data){ console.log('_ERROR: '+flag+' using '+source+' => '+data); }) .always(function(data){ console.log('END: load '+flag+' item -- '+source); update_control(); resize(position); }); }else{ console.log('ABORT: '+flag+' item already exists'); } } function bind_entry_events(id){ id = id || jQuery('section.entry.current').attr('id'); var $entry = jQuery('#'+id); $entry.imagesLoaded(function(e){ resize($entry.attr('data-position'),'imagesLoaded'); }); $entry.find('.popup_link a').on('click',function(e){ e.preventDefault(); var $trigger = jQuery(this); var $content = jQuery($trigger.attr('href')).clone(); var $popup; var $options; if(!$content.length){ return; } $content.attr('id',$content.attr('id')+'-content'); $popup = jQuery('<div></div>').append($content).html(); $options = jQuery.extend({},$slideshow.popup,{ type: 'html', wrapCSS: 'content-popup', content: $popup, afterLoad:function(){ jQuery('.fancybox-inner').scrollTop($content.offset().top); } }); jQuery.fancybox.open($options); }); $entry.find('.comment_link a').on('click',function(e){ e.preventDefault(); e.stopPropagation(); var $trigger = jQuery(this); var $options; $options = jQuery.extend({},$slideshow.popup,{ type: 'iframe', wrapCSS: 'comment-popup', href: $trigger.attr('href'), afterClose: function(){ location.reload(); } }); jQuery.fancybox.open($options); }); $entry.find('.social a').on('click',function(e){ e.preventDefault(); e.stopPropagation(); var $trigger = jQuery(this); open_social_link($trigger.attr('href')); }); /* if($entry.is('.page')||$entry.is('.archive')){ $entry.perfectScrollbar(); } if($entry.is('.post')){ $entry.children('.wrap').perfectScrollbar(); } */ } function update_control(){ var _pprev_permalink = $slideshow.position.current.attr('data-pprev_permalink'); var _prev_permalink = $slideshow.position.current.attr('data-prev_permalink'); var _next_permalink = $slideshow.position.current.attr('data-next_permalink'); var _nnext_permalink = $slideshow.position.current.attr('data-nnext_permalink'); // update control buttons if($control.prev.find('a').attr('href')!=_prev_permalink){ $control.prev.find('a').attr('href',_prev_permalink); console.log('CONTROL: [prev] button updated => '+_prev_permalink); } if($control.next.find('a').attr('href')!=_next_permalink){ $control.next.find('a').attr('href',_next_permalink); console.log('CONTROL: [next] button updated => '+_next_permalink); } // check prev/next entries and enable control buttons $slideshow.position.next = jQuery('[data-permalink="'+_next_permalink+'"]'); if($slideshow.position.next.length){ console.log('ENTRY: new [next] => #'+$slideshow.position.next.attr('data-ID')); $control.next.removeClass('disabled'); console.log('CONTROL: [next] button enabled'); } $slideshow.position.prev = jQuery('[data-permalink="'+_prev_permalink+'"]'); if($slideshow.position.prev.length){ console.log('ENTRY: new [prev] => #'+$slideshow.position.prev.attr('data-ID')); $control.prev.removeClass('disabled'); console.log('CONTROL: [prev] button enabled'); } $slideshow.position.nnext = jQuery('[data-permalink="'+_nnext_permalink+'"]'); if($slideshow.position.nnext.length){ console.log('ENTRY: new [nnext] => #'+$slideshow.position.nnext.attr('data-ID')); } $slideshow.position.pprev = jQuery('[data-permalink="'+_pprev_permalink+'"]'); if($slideshow.position.pprev.length){ console.log('ENTRY: new [pprev] => #'+$slideshow.position.pprev.attr('data-ID')); } } function update_page_meta(){ if(!$slideshow.position.current.attr('data-permalink')){ return; } // update browser history var current = { url: document.location.href }; var history = { title: $slideshow.position.current.attr('data-title')+$smallgallery.title.separator+$smallgallery.title.text, html: '<!DOCTYPE html><html>'+jQuery('html').html()+'</html>', url: $slideshow.position.current.attr('data-permalink') }; console.log('HISTORY: check '+current.url+' (current) => '+history.url+' (update)'); if(current.url!=history.url){ window.history.pushState( { 'html': history.html, 'pageTitle': history.title }, history.title, history.url ); document.title = history.title; // fallback console.log('HISTORY: (updated) '+history.title+' -- '+current.url+' => '+history.url); }else{ console.log('HISTORY: (unchanged) '+history.title+' -- '+current.url+' => '+history.url); } // update social metatags var social = { og: {}, twitter: {}, format: $slideshow.position.current.attr('data-format'), title: history.title, url: encodeURI(history.url), description: $slideshow.position.current.attr('data-description'), image: $slideshow.position.current.find('.feature img').length?encodeURI($slideshow.position.current.find('.feature img').attr('src')):'', time: { published: $slideshow.position.current.attr('data-time-published'), modified: $slideshow.position.current.attr('data-time-modified') }, author: { url: $slideshow.position.current.attr('data-author-url') } }; switch(social.format){ case 'image': social.og.type = 'article'; social.twitter.card = 'photo'; social.twitter.imagetag = 'image'; break; default: social.og.type = 'article'; social.twitter.card = 'summary'; social.twitter.imagetag = 'image:src'; break; } // facebook open graph jQuery('meta[property="og:type"]').attr('content',social.og.type); jQuery('meta[property="og:title"]').attr('content',social.title); jQuery('meta[property="og:url"]').attr('content',social.url); jQuery('meta[property="og:description"]').attr('content',social.description); jQuery('meta[property="og:image"]').attr('content',social.image); jQuery('meta[property="article:published_time"]').attr('content',social.time.published); jQuery('meta[property="article:modified_time"]').attr('content',social.time.modified); jQuery('meta[property="article:author"]').attr('content',social.author.url); // twitter cards jQuery('meta[name="twitter:card"]').attr('content',social.twitter.card); jQuery('meta[name="twitter:description"]').attr('content',social.description); jQuery('meta[name="twitter:image"]').remove(); jQuery('meta[name="twitter:image:src"]').remove(); jQuery('<meta name="twitter:'+social.twitter.imagetag+'" content="'+social.image+'">').appendTo('head'); } function cleanup(){ console.log('CLEANUP: que => '+$slideshow.garbage); if($slideshow.garbage.length){ for(index in $slideshow.garbage){ var $ID = $slideshow.garbage[index]; jQuery('.entry[data-ID="'+$ID+'"]').remove(); console.log('CLEANUP: #'+$ID+' removed'); } $slideshow.garbage = []; } } function fullscreen(flag){ var element = document.documentElement; flag = flag || !is_fullscreen(); if(flag){ if(element.requestFullscreen) { element.requestFullscreen(); } else if(element.mozRequestFullScreen) { element.mozRequestFullScreen(); } else if(element.webkitRequestFullscreen) { element.webkitRequestFullscreen(); } else if(element.msRequestFullscreen) { element.msRequestFullscreen(); } }else{ if(document.exitFullscreen) { document.exitFullscreen(); } else if(document.mozCancelFullScreen) { document.mozCancelFullScreen(); } else if(document.webkitExitFullscreen) { document.webkitExitFullscreen(); } else if(document.msExitFullscreen){ document.msExitFullscreen(); } } } function fullscreenchange(){ var $trigger = jQuery('#toggle-fullscreen'); var flag = is_fullscreen(); toggle_flag($trigger,flag); } function is_fullscreen(){ var is_fullscreen; if(typeof document.fullscreen!='undefined'){ is_fullscreen = document.fullscreen; }else if(typeof document.mozFullScreen!='undefined'){ is_fullscreen = document.mozFullScreen; }else if(typeof document.webkitIsFullScreen!='undefined'){ is_fullscreen = document.webkitIsFullScreen; }else{ is_fullscreen = Math.abs(screen.width-window.innerWidth)<10?true:false; } return is_fullscreen; } function open_help(flag){ var $options; if(typeof flag=='undefined'){ flag = jQuery.cookie('open_help'); if(typeof flag == 'undefined'){ jQuery.cookie('open_help','0',{expires:30,path:'/'}); flag = $slideshow.open_help; } } if(typeof flag=='string'){ flag = parseInt(flag)?true:false; } if(flag){ $options = jQuery.extend({},$options,{ type: 'html', wrapCSS: 'help-popup', content: jQuery('#help-container').html(), }); jQuery.fancybox.open($options); } //jQuery.removeCookie('open_help',{path:'/'}); } function open_social_link(url){ var name = '_blank'; var options = 'width='+$slideshow.popup.width+',height='+$slideshow.popup.height+',menubar=no,resizable=yes,scrollable=no,status=no,titlebar=yes,toolbar=no'; window.open(url,name,options); } jQuery(document).ready(function(e){ $container = jQuery('#container'); $control = jQuery('#control'); $control.prev = $control.find('li.prev'); $control.next = $control.find('li.next'); jQuery('#control a').on('click',function(e){ e.preventDefault(); var $trigger = jQuery(this); var $box = $trigger.closest('li'); var position = $box.attr('data-position'); var _current; var _next; var _prev; var _nnext; var _pprev; var _garbage; if($box.hasClass('disabled')){ return; }else{ // disable controls to prevent overhead $control.prev.addClass('disabled'); console.log('CONTROL: [prev] button disabled'); $control.next.addClass('disabled'); console.log('CONTROL: [prev] button disabled'); // redefine positions and determine things to do $slideshow.direction = position; _current = $slideshow.position[position]; switch(position){ case 'prev': $slideshow.animation = $smallgallery.animation.name[$slideshow.position.current.attr('data-animation')]; _prev = $slideshow.position.pprev; _nnext = $slideshow.position.next; _next = $slideshow.position.current; _garbage = $slideshow.position.nnext.addClass('expired').attr('data-ID'); break; case 'next': $slideshow.animation = $smallgallery.animation.name[$slideshow.position.next.attr('data-animation')]; _next = $slideshow.position.nnext; _pprev = $slideshow.position.prev; _prev = $slideshow.position.current; _garbage = $slideshow.position.pprev.addClass('expired').attr('data-ID'); break; default: _garbage = null; break; } for(pos in $slideshow.position){ $slideshow.position[pos].attr('data-position',pos); } // do animation $container.attr('data-animation',$slideshow.animation); // garbage collection if(_garbage){ $slideshow.garbage.push(_garbage); console.log('CLEANUP QUE: #'+_garbage+' will be deleted'); setTimeout(function(){cleanup();},$smallgallery.animation.duration); } // reset classes var classes_to_remove = 'pprev prev current next nnext'; $slideshow.position.current = _current.removeClass(classes_to_remove+' fresh').addClass('current'); if(_next){ $slideshow.position.next = _next.removeClass(classes_to_remove).addClass('next'); } if(_prev){ $slideshow.position.prev = _prev.removeClass(classes_to_remove).addClass('prev'); } if(_nnext){ $slideshow.position.nnext = _nnext.removeClass(classes_to_remove).addClass('nnext'); } if(_pprev){ $slideshow.position.pprev = _pprev.removeClass(classes_to_remove).addClass('pprev'); } // init init(); } // endif }); jQuery(window).on('resize',function(e){ resize(); }); /* messed up with MSIE jQuery(document).on('fullscreenchange webkitfullscreenchange mozfullscreenchange MSFullscreenChange',function(e){ fullscreenchange(); }); */ jQuery('.toggler').on('click',function(e){ e.preventDefault(); var $trigger = jQuery(this); switch($trigger.attr('id')){ case 'toggle-navigation': toggle_flag($trigger); break; case 'toggle-help': open_help(true); break; case 'toggle-fullscreen': fullscreen(); break; } }); jQuery('#container').swipe({ swipe:function(e,direction,distance,duration,fingerCount,fingerData){ switch(direction){ case 'right': jQuery('#control .prev a').click(); break; case 'left': jQuery('#control .next a').click(); break; default: return; break; } }, allowPageScroll: 'vertical', threadhold: 75 }); jQuery(document).keydown(function(e){ if(jQuery('#comments-body').length){ return; } var context = e.target; var pressed = e.charCode || e.keyCode || e.which; var is_popup = jQuery('.fancybox-overlay').length?true:false; if(context=='input'||context=='textarea'){ return; } console.log('KEY PRESSED: #'+pressed); switch(pressed){ case 37: // left if(!is_popup){ jQuery('#control .prev a').click(); } break; case 39: // right if(!is_popup){ jQuery('#control .next a').click(); } break; case 38: // up break; case 40: // down break; /* case 70: // f fullscreen(); break; */ case 67: // c if(!is_popup){ jQuery('section.entry.current .comment_link a').click(); } break; case 80: // p if(!is_popup){ jQuery('section.entry.current .popup_link a').click(); } break; case 72: // h if(!is_popup){ open_help(true); } break; case 27: // esc return false; break; } }); /* jQuery('a').on('click',function(e){ var $trigger = jQuery(this); var $href = $trigger.attr('href'); if( !$trigger.attr('class')&&!$trigger.attr('id') && !$trigger.parent().attr('class')&&!$trigger.parent().attr('id') && ($href.search(/^\//)||$href.search($slideshow.domain)) ($href.search(/^\//)||$href.search($slideshow.domain)) ){ e.preventDefault(); alert('ajax'); window.location = $trigger.attr('href'); } }); */ if(is_fullscreen()){ jQuery('#toggle-fullscreen').attr('data-flag','true'); }else{ jQuery('#toggle-fullscreen').attr('data-flag','false'); } resize(); bind_entry_events(); init_flags(); init(); if($slideshow.open_help){ open_help(); } }); <file_sep><?php define('CONTROL',false); get_header(); if(have_posts()): while(have_posts()): the_post(); $post = rebuild_post($post); echo <<<EOT <section id="entry-{$post->ID}" class="current format-standard {$post->class}"> <div class="wrap"> {$post->div_feature} <div class="caption"> {$post->div_edit_link} {$post->div_title} {$post->div_content} {$post->div_author} {$post->div_date} </div> </div> </section><!--/#entry-{$post->ID}--> EOT; endwhile; endif; get_footer(); ?> <file_sep><?php global $post; setup_postdata($post); $post = rebuild_post($post); the_post(); ?><!DOCTYPE html> <html> <head> <meta charset="<?php echo get_option('blog_charset'); ?>"> <base target="_top"> <?php smallgallery_head(); wp_head(); ?> <script> jQuery(document).ready(function(e){ jQuery('a.comment-date').on('click',function(e){ e.preventDefault(); }); }); </script> </head> <body id="comments-body"> <div id="entry-<?php echo $post->ID; ?>-comments" class="comments-container"> <h1 class="site-title"><?php echo get_option('blogname'); ?></h1> <h1 class="entry-title"><?php printf(__('Reply on <strong>%s</strong>',TEXTDOMAIN),$post->filtered_title); ?></h1> <?php define('CONTROL',false); //echo build_post($post); comments_template(); ?> </div><!--.comments--> <?php wp_footer(); ?> </body> </html> <file_sep><?php function __field($options=array()){ extract($options); $heading = $heading?$heading:'h4'; $type = esc_attr($type); $name = esc_attr($name); $label = make_label(($label?$label:$name)); $value = $type=='textarea'?htmlspecialchars($value):esc_attr($value); $disabled = $disabled?" disabled='{$disabled}'":''; $checked = $checked?" checked='{$checked}'":''; $selected = $selected?" selected='{$selected}'":''; if(!empty($children)){ $children_markup = ''; foreach($children as $child){ $children_markup .= __field($child); } } switch($type){ case 'text': case 'password': case 'hidden': $markup = <<<EOT <p> <{$heading}><label for="{$name}">{$label}</label></{$heading}> <input type="{$type}" name="{$name}" value="{$value}"{$disabled}{$checked}{$selected}/> </p> EOT; break; case 'checkbox': $markup = <<<EOT <div> <label>{$label} <input type="{$type}" name="{$name}[]" value="{$value}"{$disabled}{$checked}{$selected}/> </label> </div> EOT; break; case 'radio': $markup = <<<EOT <div> <label>{$label} <input type="{$type}" name="{$name}" value="{$value}"{$disabled}{$checked}{$selected}/> </label> </div> EOT; break; case 'select': $markup = <<<EOT <p> <{$heading}><label for="{$name}">{$label}</label></{$heading}> <select name="{$name}"> {$children_markup} </select> </p> EOT; break; case 'checkboxes': case 'radios': $markup = <<<EOT <p> <{$heading}><label>{$label}</label></{$heading}> {$children_markup} </p> EOT; break; } return $markup; } function _field($options=array()){ echo __field($options); } function __metabox($post,$options=array()){ $properties = get_properties($post); $options['args']['fields']['slide_weight']['children'][$properties['slide_weight']]['checked']='checked'; $options['args']['fields']['slide_animation']['children'][$properties['slide_animation']]['checked']='checked'; $options['args']['fields']['slide_title']['children'][$properties['slide_title']]['checked']='checked'; $options['args']['fields']['slide_content']['children'][$properties['slide_content']]['checked']='checked'; $options['args']['fields']['slide_author']['children'][$properties['slide_author']]['checked']='checked'; $options['args']['fields']['slide_date']['children'][$properties['slide_date']]['checked']='checked'; $options['args']['fields']['slide_category']['children'][$properties['slide_category']]['checked']='checked'; $options['args']['fields']['slide_tag']['children'][$properties['slide_tag']]['checked']='checked'; wp_nonce_field($options['id'],$options['id'].'_nonce'); foreach($options['args']['fields'] as $field){ _field($field); } } function _metabox($post=array(),$options=array()){ echo __metabox($post,$options); } function __heading_label($post){ $default = strtoupper('heading'); $in_format = strtoupper($default.'_'.$post->format); $in_weight = strtoupper($in_format.'_'.$post->slide_weight); if(defined($in_weight)){ $label = $in_weight; }else if(defined($in_format)){ $label = $in_format; }else if(defined($default)){ $label = $default; } return $label; } function _heading_label($post){ echo __heading_label($post); } function __heading($post){ $heading = isset($post->heading_label)?constant($post->heading_label):constant(__heading_label($post)); return $heading; } function _heading($post){ echo __heading($post); } ?> <file_sep><?php define('DEFAULT_MENU_FLAG_STRING',DEFAULT_MENU_FLAG?'true':'false'); define('DEFAULT_CAPTION_FLAG_STRING',DEFAULT_CAPTION_FLAG?'true':'false'); ?><!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width,initial-scale=1,user-scalable=0"> <title><?php wp_title(''); ?></title> <?php ob_start(); smallgallery_head(); wp_head(); $head = ob_get_contents(); ob_end_clean(); echo "\t".str_replace("\n","\n\t",$head); if(has_nav_menu('navigation')){ $navigation_options = array( 'theme_location' => 'navigation', 'container' => false, 'echo' => false, 'fallback_cb' => 'wp_page_menu', 'link_before' => '<span>', 'link_after' => '</span>', 'items_wrap' => '<ul id="menu" class="menu items disabled">%3$s</ul><!--/#menu-->', 'depth' => 0, ); $navigation = '<nav id="navigation">'.PHP_EOL . '<h2 class="title a11y">'.__('Navigation',TEXTDOMAIN).'</h2>'.PHP_EOL . '<ul class="console items">'.PHP_EOL . '<li class="toggle-navigation-container toggle-container item"><a id="toggle-navigation" class="toggler" href="#menu" data-flag="'.DEFAULT_MENU_FLAG_STRING.'" data-flag-true-class="enabled" data-flag-false-class="disabled"><span>'.__('Toggle navigation',TEXTDOMAIN).'</span></a></li>'.PHP_EOL . '<li class="toggle-help-container toggle-container item"><a id="toggle-help" class="toggler" href="#help" data-flag="'.DEFAULT_HELP_FLAG_STRING.'" data-flag-true-class="help-enabled" data-flag-false-class="help-disabled"><span>'.__('Help',TEXTDOMAIN).'</span></a></li>'.PHP_EOL //. '<li class="toggle-fullscreen-container toggle-container item"><a id="toggle-fullscreen" class="toggler" href="#body" data-flag="'.DEFAULT_FULLSCREEN_FLAG_STRING.'" data-flag-true-class="fullscreen-enabled" data-flag-false-class="fullscreen-disabled"><span>'.__('Fullscreen',TEXTDOMAIN).'</span></a></li>'.PHP_EOL . '</ul><!--/.console-->'.PHP_EOL . wp_nav_menu($navigation_options).PHP_EOL . '</nav><!--/#navigation-->'.PHP_EOL; }else{ $navigation = ''; } ?> </head> <body id="body" <?php body_class(); ?>> <div id="smallgallery"> <div id="header-and-navigation" class="autofade" data-autofade-default-opacity="0"> <header id="header"> <h1 class="site-title"><a href="<?php bloginfo('siteurl'); ?>"><span><?php bloginfo('title'); ?></span></a></h1> <div class="site-description"><?php bloginfo('description'); ?></div><!--/.site-description--> </header><!--/#header--> <?php echo $navigation; ?> </div><!--/#header-and-navigation--> <article id="article"> <div id="container" class="entries wrap"> <file_sep><?php require_once dirname(__FILE__).'/contrib/lessphp/lessc.inc.php'; require_once TEMPLATEPATH.'/_config.php'; require_once TEMPLATEPATH.'/_functions.apis.php'; require_once TEMPLATEPATH.'/_functions.hooks.php'; require_once TEMPLATEPATH.'/_functions.tags.php'; ?> <file_sep><?php global $query_string; query_posts($query_string.'&posts_per_page=1&order=ASC'); ?> <file_sep><?php function check_stylesheet(){ $less = new lessc; try{ $less->setVariables(array( 'slide-padding' => SLIDE_PADDING, 'slide-animation-duration' => SLIDE_ANIMATION_DURATION.'ms', 'slide-animation-timing' => SLIDE_ANIMATION_TIMING, 'ui-animation-duration' => UI_ANIMATION_DURATION.'ms', 'ui-animation-timing' => UI_ANIMATION_TIMING, 'ui-portrait-size' => UI_PORTRAIT_SIZE, 'text-padding' => TEXT_PADDING, )); $less->setPreserveComments(true); $less->checkedCompile(CSS_SOURCE,CSS_OUTPUT); $result = true; }catch(exception $e){ $result = $e->getMessage(); } return $result; } function make_label($string=''){ $result = ''; $pattern = array( '-' => ' ', '_' => ' ', ); $string = str_replace(array_keys($pattern),array_values($pattern),$string); $string = ucfirst($string); $string = __($string,TEXTDOMAIN); $result = $string; return $result; } function get_properties($post){ $post = (object) $post; $slide_format = get_post_format($post->ID); $slide_format = $slide_format?$slide_format:'standard'; $slide_properties = array(); $slide_property_names = explode(':',SLIDE_PROPERTY_NAMES); foreach($slide_property_names as $slide_property_name){ $slide_property_name = "slide_{$slide_property_name}"; $slide_property_value = get_post_meta($post->ID,$slide_property_name); if(empty($slide_property_value)){ $slide_constant_name = strtoupper("default_{$slide_format}_{$slide_property_name}"); $slide_property_value = array(constant($slide_constant_name)); update_post_meta($post->ID,$slide_property_name,$slide_property_value[0]); } $slide_properties[$slide_property_name] = $slide_property_value[0]; } return $slide_properties; } function rebuild_post($post){ global $wpdb; $post->permalink = get_permalink($post->ID); $post->author_url = get_author_posts_url($post->post_author); $post->comments_number = get_comments_number($post->ID); $post->has_comment = $post->comments_number>0||$post->comment_status=='open'||$post->ping_status=='open'?true:false; if($post->post_type=='post'){ $post->pprev_ID = $wpdb->get_var("SELECT ID FROM {$wpdb->posts} WHERE post_type = 'post' AND post_status = 'publish' AND post_date < '{$post->post_date}' ORDER BY post_date DESC LIMIT 1,1"); $post->prev_ID = $wpdb->get_var("SELECT ID FROM {$wpdb->posts} WHERE post_type = 'post' AND post_status = 'publish' AND post_date < '{$post->post_date}' ORDER BY post_date DESC LIMIT 1"); if(!$post->pprev_ID&&$post->prev_ID){ $post->pprev_ID = $wpdb->get_var("SELECT ID FROM {$wpdb->posts} WHERE post_type = 'post' AND post_status = 'publish' ORDER BY post_date DESC LIMIT 1"); }else if(!$post->pprev_ID&&!$post->prev_ID){ $post->pprev_ID = $wpdb->get_var("SELECT ID FROM {$wpdb->posts} WHERE post_type = 'post' AND post_status = 'publish' ORDER BY post_date DESC LIMIT 1,1"); $post->prev_ID = $wpdb->get_var("SELECT ID FROM {$wpdb->posts} WHERE post_type = 'post' AND post_status = 'publish' ORDER BY post_date DESC LIMIT 1"); } $post->next_ID = $wpdb->get_var("SELECT ID FROM {$wpdb->posts} WHERE post_type = 'post' AND post_status = 'publish' AND post_date > '{$post->post_date}' ORDER BY post_date ASC LIMIT 1"); $post->nnext_ID = $wpdb->get_var("SELECT ID FROM {$wpdb->posts} WHERE post_type = 'post' AND post_status = 'publish' AND post_date > '{$post->post_date}' ORDER BY post_date ASC LIMIT 1,1"); if($post->next_ID&&!$post->nnext_ID){ $post->nnext_ID = $wpdb->get_var("SELECT ID FROM {$wpdb->posts} WHERE post_type = 'post' AND post_status = 'publish' ORDER BY post_date ASC LIMIT 1"); }else if(!$post->next_ID&&!$post->nnext_ID){ $post->next_ID = $wpdb->get_var("SELECT ID FROM {$wpdb->posts} WHERE post_type = 'post' AND post_status = 'publish' ORDER BY post_date ASC LIMIT 1"); $post->nnext_ID = $wpdb->get_var("SELECT ID FROM {$wpdb->posts} WHERE post_type = 'post' AND post_status = 'publish' ORDER BY post_date ASC LIMIT 1,1"); } } if($post->pprev_ID){ $post->pprev_permalink = get_permalink($post->pprev_ID); } if($post->prev_ID){ $post->prev_permalink = get_permalink($post->prev_ID); } if($post->next_ID){ $post->next_permalink = get_permalink($post->next_ID); } if($post->nnext_ID){ $post->nnext_permalink = get_permalink($post->nnext_ID); } $post->categories = get_the_category($post->ID); $post->tags = get_the_tags($post->ID); $post->format = get_post_format($post->ID); if(!$post->format){ $post->format = 'standard'; } $post->post_type_label = $post->post_type=='post'?'slide':$post->post_type; $post->edit_link = current_user_can('edit_'.$post->post_type,$post->ID)?get_edit_post_link($post->ID):''; $post->comment_link = get_comments_popup_link($post); $properties = get_properties($post); $post->slide_weight = $properties['slide_weight']; $post->slide_animation = $properties['slide_animation']; $post->slide_feature = has_post_thumbnail($post->ID); $post->slide_title = $properties['slide_title']; $post->slide_content = $properties['slide_content']; $post->slide_author = $properties['slide_author']; $post->slide_date = $properties['slide_date']; $post->slide_category = $properties['slide_category']; $post->slide_tag = $properties['slide_tag']; $post->heading_label = __heading_label($post); $post->heading = __heading($post); $post->classes = get_post_class('',$post->ID); $post->classes[] = 'entry'; $post->classes[] = 'slide-heading-label-'.strtolower($post->heading_label); $post->classes[] = 'slide-heading-'.$post->heading; $post->classes[] = 'slide-weight-'.$post->slide_weight; $post->classes[] = 'slide-animation-'.$post->slide_animation; $post->classes[] = 'slide-title-'.$post->slide_title; $post->classes[] = 'slide-content-'.$post->slide_content; $post->classes[] = 'slide-author-'.$post->slide_author; $post->classes[] = 'slide-date-'.$post->slide_date; $post->classes[] = 'slide-category-'.$post->slide_category; $post->classes[] = 'slide-tag-'.$post->slide_tag; if($post->categories){ foreach($post->categories as $category){ $post->classes[] = 'category-id-'.$category->term_id; } } if($post->tags){ foreach($post->tags as $tag){ $post->classes[] = 'tag-id-'.$tag->term_id; } } $post->class = implode(' ',$post->classes); $post->filtered_feature = get_the_post_thumbnail($post->ID,'medium'); $post->filtered_title = apply_filters('the_title',$post->post_title); $post->filtered_content = apply_filters('the_content',$post->post_content); $post->filtered_excerpt = apply_filters('get_the_excerpt',$post->post_excerpt); ob_start(); the_post_thumbnail('medium'); $post->filtered_feature_medium = ob_get_contents(); ob_clean(); the_category(); $post->filtered_category = ob_get_contents(); ob_clean(); the_tags(); $post->filtered_tag = ob_get_contents(); ob_clean(); the_author_posts_link(); $post->filtered_author = ob_get_contents(); ob_clean(); ob_end_clean(); $post->alt_title = esc_attr(strip_tags($post->filtered_title)); $post->alt_content = esc_attr(strip_tags($post->filtered_content)); $post->alt_excerpt = esc_attr(strip_tags($post->filtered_excerpt)); $post->div_feature = ($post->slide_feature?"<div class='feature'>{$post->filtered_feature}</div>":'').'<!--/.feature-->'; $post->div_title = ($post->slide_title?"<{$post->heading} class='title'>{$post->filtered_title}</{$post->heading}>":'').'<!--/.title-->'; $post->div_content = ($post->slide_content?"<div class='content'>{$post->filtered_content}</div>":'').'<!--/.content-->'; $post->div_author = ($post->slide_author?"<div class='author'>{$post->filtered_author}</div>":'').'<!--/.author-->'; $post->div_date = ($post->slide_date?"<div class='date'>{$post->filtered_date}</div>":'').'<!--/.date-->'; $post->div_category = ($post->slide_category?"<div class='category'>{$post->filtered_category}</div>":'').'<!--/.category-->'; $post->div_tag = ($post->slide_tag?"<div class='tag'>{$post->filtered_tag}</div>":'').'<!--/.tag-->'; $post->caption_title = $post->slide_title==1?$post->div_title:''; $post->caption_content = $post->slide_content==1?$post->div_content:''; $post->caption_author = $post->slide_author==1?$post->div_author:''; $post->caption_date = $post->slide_date==1?$post->div_date:''; $post->caption_category = $post->slide_category==1?$post->div_category:''; $post->caption_tag = $post->slide_tag==1?$post->div_tag:''; $post->popup_title = $post->slide_title==2?$post->div_title:''; $post->popup_content = $post->slide_content==2?$post->div_content:''; $post->popup_author = $post->slide_author==2?$post->div_author:''; $post->popup_date = $post->slide_date==2?$post->div_date:''; $post->popup_category = $post->slide_category==2?$post->div_category:''; $post->popup_tag = $post->slide_tag==2?$post->div_tag:''; $post->div_caption = build_caption($post); $post->div_popup = build_popup($post); $post->div_edit_link = ($post->edit_link?"<div class='edit_link'><a href='{$post->edit_link}'><span>".__("Edit this {$post->post_type_label}",TEXTDOMAIN)."</span></a></div><!--/.edit_link-->":''); $post->div_popup_link = $post->div_popup?"<div class='popup_link'><a href='#entry-{$post->ID}-popup'><span>".__("Open popup",TEXTDOMAIN)."</span></a></div>":''; $post->div_comment_link = $post->has_comment?"<div class='comment_link'><a href='{$post->comment_link}'><span>{$post->comments_number}</span></a></div>":''; $post->div_social_links = build_social($post); return $post; } function build_post($post){ $markup = ''; switch($post->format){ case 'standard': $post->div_popup_link = ''; break; } ob_start(); echo <<<EOT <section id="entry-{$post->ID}" class="current {$post->class}" data-ID="{$post->ID}" data-format="{$post->format}" data-animation="{$post->slide_animation}" data-pprev_permalink="{$post->pprev_permalink}" data-prev_permalink="{$post->prev_permalink}" data-next_permalink="{$post->next_permalink}" data-nnext_permalink="{$post->nnext_permalink}" data-title="{$post->alt_title}" data-permalink="{$post->permalink}" data-description="{$post->alt_excerpt}" data-time-published="" data-time-modified="" data-author-url="{$post->author_url}" > <div class="wrap"> {$post->div_edit_link} {$post->div_social_links} {$post->div_feature} <div class="wrap-inner"> {$post->div_popup_link} {$post->div_comment_link} {$post->div_caption} {$post->div_popup} </div> </div> <!--/#entry-{$post->ID}--> </section> EOT; $markup = ob_get_contents(); ob_end_clean(); return $markup; } function build_popup($post){ $markup; if($post->popup_title||$post->popup_content||$post->popup_author||$post->popup_date||$post->popup_category||$post->popup_tag){ ob_start(); echo <<<EOT <div id="entry-{$post->ID}-popup" class="popup"> {$post->popup_title} {$post->popup_author} {$post->popup_date} {$post->popup_content} {$post->popup_category} {$post->popup_tag} </div><!--/#entry-{$post->ID}-popup--> EOT; $markup = ob_get_contents(); ob_end_clean(); } return $markup; } function get_comments_popup_link($post){ $link = ''; $link = home_url().'/'.$wpcommentspopupfile.'?comments_popup='.$post->ID; $link = apply_filters('comments_popup_link_attributes',$link); return $link; } function build_caption($post){ $markup; if($post->caption_title||$post->caption_content||$post->caption_author||$post->caption_date||$post->caption_category||$post->caption_tag){ ob_start(); echo <<<EOT <div id="entry-{$post->ID}-caption" class="caption"> {$post->caption_title} {$post->caption_author} {$post->caption_date} {$post->caption_content} {$post->caption_category} {$post->caption_tag} </div><!--/#entry-{$post->ID}-caption--> EOT; $markup = ob_get_contents(); ob_end_clean(); } return $markup; } function build_social($post){ $markup; if(USE_SOCIAL_SHARING){ $twitter = __('Share with Twitter',TEXTDOMAIN); $facebook = __('Share with Facebook',TEXTDOMAIN); $googleplus = __('Share with Google+',TEXTDOMAIN); $kakaotalk = __('Share with Kakaotalk',TEXTDOMAIN); ob_start(); echo <<<EOT <div class="social"> <ul class="items"> <li class="item twitter"><a href="https://twitter.com/share?u={$post->permalink}"><span>{$twitter}</span></a></li> <li class="item facebook"><a href="https://facebook.com/sharer.php?u={$post->permalink}"><span>{$facebook}</span></a></li> <li class="item googleplus"><a href="https://plus.google.com/share?url={$post->permalink}"><span>{$googleplus}</span></a></li> <li class="item kakaotalk"><a href="{$post->permalink}"><span>{$kakaotalk}</span></a></li> </ul> </div> EOT; $markup = ob_get_contents(); ob_end_clean(); } return $markup; } function build_control($post){ $control = ''; if(defined('CONTROL')){ return $control; } $prev_label = __('Previous slide',TEXTDOMAIN); $next_label = __('Next slide',TEXTDOMAIN); ob_start(); echo <<<EOT <nav id="control" class="autofade" data-autofade-default-opacity="0"> <ul class="items"> <li class="item prev disabled" data-position="prev"><a href="{$post->prev_permalink}"><span>{$prev_label}</span></a></li> <li class="item next disabled" data-position="next"><a href="{$post->next_permalink}"><span>{$next_label}</span></a></li> </ul> </nav><!--/#control--> EOT; $control = ob_get_contents(); ob_end_clean(); define('CONTROL',$control); return $control; } function build_archives($entries){ $markup = ''; $items = array(); foreach($entries as $entry): $entry = rebuild_post($entry); $entry->feature = has_post_thumbnail($entry->ID)?get_the_post_thumbnail($entry->ID,'thumbnail',array('alt'=>$entry->alt_title)):"<img src='".DEFAULT_POST_THUMBNAIL."' alt='{$entry->alt_title}'>"; $items[] = "<li id='thumbnail-{$entry->ID}' class='item'><a href='{$entry->permalink}'>{$entry->feature}</a></li>".PHP_EOL; endforeach; $markup = implode(PHP_EOL,$items); $markup = "<ul class='thumbnail-archives items'>{$markup}</ul>".PHP_EOL; return $markup; } function rebuild_user($user){ $user->filtered_email = $user->user_email?str_replace('@',' at ',$user->user_email):''; $user->filtered_url = strpos($user->user_url,'http')==0?$user->user_url:'http://'.$user->user_url; $user->filtered_description = $user->description?wptexturize($user->description):''; $user->div_email = $user->filtered_email?"<div class='email'>{$user->filtered_email}</div>":''; $user->div_url = $user->filtered_url?"<div class='url'>{$user->filtered_url}</div>":''; $user->div_description = $user->filtered_description?"<div class='description'>{$user->filtered_description}</div>":''; return $user; } function build_feedback($message){ $markup = ''; define('CONTROL',false); ob_start(); echo <<<EOT <section class="{$message->context} {$message->type} entry format-standard current"> <div class="wrap"> <h1 class="title">{$message->title}</h1> <div class="description">{$message->description}</div> {$message->links} </div> </section> EOT; $markup = ob_get_contents(); ob_end_clean(); return $markup; } function get_feedback($message){ echo build_feedback($message); } ?> <file_sep>smallgallery ============ 슬라이드 쇼 형식의 소규모 갤러리를 위한 [워드프레스](http://wordpress.org) 테마입니다. 개요 ---- 1. 게시물을 슬라이드로 취급합니다. * 슬라이드들은 날짜 순으로 정렬됩니다. (가장 최근 게시물이 마지막 슬라이드가 됨) * 포스트 포맷을 `image`로 설정하면 이미지 슬라이드로 간주하고 피쳐 이미지를 출력합니다. * 포스트 포맷을 `standard`로 설정하면 텍스트 슬라이드로 간주하고 피쳐 이미지를 감춥니다. (썸네일 아카이브에서만 피쳐 이미지를 사용) 2. 워드프레스 메뉴 기능을 지원합니다. 3. 카테고리/태그/저자 정보는 갤러리 구성에 관여하지 않습니다. * 카테고리/태그/저자 및 날짜 아카이브는 썸네일 갤러리로 출력됩니다. 4. 슬라이드 디자인을 위한 추가 설정을 제공합니다. (기본값은 `_config.php` 파일에서 설정) * 제목, 본문, 날짜, 카테고리, 태그, 저자 정보를 게시물 단위로 보여주거나 감출 수 있습니다. * 슬라이드 무게(중요도)를 설정할 수 있습니다. 5. (미구현) `thumbnailarchives` 숏코드로 썸네일 갤러리 형식의 아카이브를 출력할 수 있습니다. 지정할 수 있는 옵션은 다음과 같습니다. * `size` -- 썸네일 사이즈를 지정합니다. (기본값: thumbnail) * `category` -- 특정 카테고리에 속한 게시물로 아카이브를 구성합니다. [기본값: 없음/현재 카테고리(카테고리 아카이브일 때)] * `tag` -- 특정 태그에 속한 게시물로 아카이브를 구성합니다. [기본값: 없음/현재 태그(태그 아카이브일 때)] * `author` -- 특정 저자의 게시물로 아카이브를 구성합니다. [기본값: 없음/현재 저자(저자 아카이브일 때)] * `date` -- 특정 날짜에 속한 게시물로 아카이브를 구성합니다. [기본값: 없음/현재 날짜(날짜 아카이브일 때)] * `ids` -- 지정된 게시물로 아카이브를 구성합니다. *이 값이 지정되면 category, tag, author, date 옵션을 무시합니다.* (기본값: 없음) 할일 ---- 1. 카카오톡 공유 링크 -- 새 API 발표 후에 작업하기로 함 https://developers.kakao.com/ 1. 전체화면 전환 기능 -- 크로스 브라우징 문제로 구현 중지 2. 내부 링크 AJAX 처리 3. 코너링 애니메이션 <file_sep><?php if(is_home()): require_once TEMPLATEPATH.'/query.php'; if(have_posts()): the_post(); header('location:'.get_permalink(get_the_ID())); else: $message = (object) array( 'context' => 'error', 'type' => '', 'title' => __('Gallery is empty.',TEXTDOMAIN), 'description' => '', 'guide' => '', ); get_header(); get_feedback($message); get_footer(); endif; else: if(have_posts()): the_post(); $message = (object) array( 'context' => 'archive ', 'type' => '', 'title' => '', 'description' => '', 'links' => '', ); global $wp_query; $object = $wp_query->get_queried_object(); if(is_author()): $object = rebuild_user($object); $message->type = 'author'; $message->title = $object->display_name; $message->description = "<ul class='profile'>".PHP_EOL . ($object->user_email?"<li class='email'><dl><dt>".__('Email',TEXTDOMAIN)."</dt><dd>{$object->div_email}</dd></dl></li>".PHP_EOL:'') . ($object->user_url?"<li class='url'><dl><dt>".__('Homepage',TEXTDOMAIN)."</dt><dd>{$object->div_url}</dd></dl></li>".PHP_EOL:'') . ($object->description?"<li class='bio'><dl><dt>".__('About',TEXTDOMAIN)."</dt><dd>{$object->div_description}</dd></dl></li>".PHP_EOL:'') . "</ul>"; elseif(is_date()): $message->type = 'date'; elseif(is_category()): $message->type = 'category'; $message->title = $object->name; $message->description = $object->description; elseif(is_tag()): $message->type = 'tag'; $message->title = $object->name; $message->description = $object->description; endif; get_header(); rewind_posts(); $entries = array(); while(have_posts()): the_post(); $entry = get_post(); $entries[] = $entry; endwhile; $message->links = build_archives($entries); get_feedback($message); get_footer(); else: $message = (object) array( 'context' => 'error', 'type' => '', 'title' => __('Archive is empty.',TEXTDOMAIN), 'description' => '', 'guide' => '', ); print_r($message); get_header(); get_feedback($message); get_footer(); endif; endif; ?> <file_sep> </div><!--/#container--> </article><!--/#article--> <?php echo CONTROL; ?> <footer id="footer"> <div class="powered"><?php _e('Powered by <a href=\'http://jinbo.net\'><span>Jinbo.net</span></a>',TEXTDOMAIN); ?></div><!--/.powered--> <footer><!--/#footer--> </div><!--/#smallgallery--> <div id="help-container"><div id="help"><!--/splash--></div></div> <?php wp_footer(); ?> </body> </html> <file_sep><?php // Development define('TEXTDOMAIN','smallgallery'); define('DEBUG_CSS',false); define('DEBUG_SCRIPT',false); define('CSS_SOURCE',TEMPLATEPATH.'/style.less'); define('CSS_OUTPUT',TEMPLATEPATH.'/style.css'); // Sitewide define('TITLE_TEXT',esc_attr(get_option('blogname'))); define('TITLE_SEPARATOR',' | '); define('USE_SOCIAL_SHARING',true); // LESS variables define('SLIDE_PADDING','10%'); define('SLIDE_ANIMATION_DURATION','600'); define('SLIDE_ANIMATION_TIMING','linear'); define('UI_ANIMATION_DURATION','300'); define('UI_ANIMATION_TIMING','linear'); define('UI_PORTRAIT_SIZE',64); define('TEXT_PADDING','20px'); // Editing options define('SLIDE_ANIMATION_NAMES','horizontal:corner_in:corner_out'); define('HEADING','h1'); define('HEADING_STANDARD','h2'); define('HEADING_STANDARD_0','h2'); define('HEADING_STANDARD_1','h1'); define('HEADING_IMAGE','h3'); define('HEADING_IMAGE_0','h3'); define('HEADING_IMAGE_1','h1'); define('DEFAULT_POST_FORMAT','image'); // set false to make configurable define('DEFAULT_POST_THUMBNAIL',get_stylesheet_directory_uri().'/images/default-post-thumbnail.png'); define('SLIDE_PROPERTY_NAMES','weight:title:content:author:date:category:tag:animation'); define('DEFAULT_IMAGE_SLIDE_WEIGHT',0); define('DEFAULT_IMAGE_SLIDE_TITLE',0); define('DEFAULT_IMAGE_SLIDE_CONTENT',0); define('DEFAULT_IMAGE_SLIDE_AUTHOR',1); define('DEFAULT_IMAGE_SLIDE_DATE',0); define('DEFAULT_IMAGE_SLIDE_CATEGORY',0); define('DEFAULT_IMAGE_SLIDE_TAG',0); define('DEFAULT_IMAGE_SLIDE_ANIMATION',0); // array index from SLIDE_ANIMATION_NAMES define('DEFAULT_STANDARD_SLIDE_WEIGHT',0); define('DEFAULT_STANDARD_SLIDE_TITLE',1); define('DEFAULT_STANDARD_SLIDE_CONTENT',1); define('DEFAULT_STANDARD_SLIDE_AUTHOR',0); define('DEFAULT_STANDARD_SLIDE_DATE',0); define('DEFAULT_STANDARD_SLIDE_CATEGORY',0); define('DEFAULT_STANDARD_SLIDE_TAG',0); define('DEFAULT_STANDARD_SLIDE_ANIMATION',0); // array index from SLIDE_ANIMATION_NAMES // Other settings define('DEFAULT_MENU_FLAG',false); define('DEFAULT_MENU_FLAG_STRING',DEFAULT_MENU_FLAG?'true':'false'); define('DEFAULT_HELP_FLAG',true); define('DEFAULT_HELP_FLAG_STRING',DEFAULT_HELP_FLAG?'true':'false'); define('DEFAULT_FULLSCREEN_FLAG',false); define('DEFAULT_FULLSCREEN_FLAG_STRING',DEFAULT_FULLSCREEN_FLAG?'true':'false'); ?> <file_sep><?php if(have_posts()): while(have_posts()): the_post(); $post = rebuild_post($post); switch($_GET['format']): case 'json': $post->filtered_post = build_post($post); header('Content-type:application/json;charset='.get_option('blog_charset')); echo json_encode($post); break; default: get_header(); echo build_post($post); build_control($post); get_footer(); break; endswitch; endwhile; endif; ?> <file_sep><?php if(post_password_required()){ return; } global $post; if(have_comments()): global $comments; require_once TEMPLATEPATH.'/class.walker.comment.php'; $comments_walk_arguments = array( 'walker' => new Smallgallery_Walker_Comment, 'style' => 'ol', 'short_ping' => true, 'avatar_size' => UI_PORTRAIT_SIZE*2, // doubling for retina display ); if(get_option('page_comments')){ $pagination = (object) array(); $pagination->comments_per_page = get_option('comments_per_page'); $pagination->total_comments = $post->comments_number; $pagination->total_pages = ceil($pagination->total_comments/$pagination->comments_per_page); $pagination->page = max(1,get_query_var('page')); $pagination->offset = $pagination->comments_per_page*($pagination->page-1); $pagination_arguments = array( 'base' => $post->comment_link.'%_%', 'format' => '&page=%#%', 'total' => $pagination->total_pages, 'current' => $pagination->page, 'type' => 'list', 'echo' => false, ); $pagination->markup = str_replace('<a ','<a target="_self" ',paginate_links($pagination_arguments)); $default_comments_page = get_option('default_comments_page'); $comment_order = get_option('comment_order'); $comments_arguments = array( 'status' => 'approve', 'orderby' => 'comment_date_gmt', 'order' => ($default_comments_page=='newest'?'DESC':'ASC'), 'number' => $pagination->comments_per_page, //'count' => $pagination->comments_per_page, 'offset' => $pagination->comments_per_page*($pagination->page-1), 'post_id' => $post->ID, ); $comments = get_comments($comments_arguments); $comments_walk_arguments['reverse_top_level'] = ($default_comments_page=='newest'&&$comment_order=='asc'||$default_comments_page=='oldest'&&$comment_order=='desc')?1:0; }else{ $pagination->markup = ''; } $pagination->markup = $pagination->markup?"<div class='pagination'>{$pagination->markup}</div><!--/.pagination-->":''; echo $pagination->markup; wp_list_comments($comments_walk_arguments,$comments); echo $pagination->markup; else: echo "<p class='there-are-no-comments'>".__('There are no comments.',TEXTDOMAIN)."</p>".PHP_EOL; endif; if(comments_open()&&post_type_supports(get_post_type(),'comments')): ob_start(); comment_form(array( 'fields' => array( 'author' => '<p class="comment-form-author"><label for="author">'.__('Name',TEXTDOMAIN).($req?'<span class="required">*</span>':'').'</label><input id="author" name="author" type="text" value="'.esc_attr($commenter['comment_author']).'" size="30"'.$aria_req.' placeholder="'.__('Your name here',TEXTDOMAIN).'"></p>', 'email' => '<p class="comment-form-email"><label for="email">'.__('Email',TEXTDOMAIN ).($req?'<span class="required">*</span>':'').'</label><input id="email" name="email" type="text" value="'.esc_attr($commenter['comment_author_email']).'" size="30"'.$aria_req.' placeholder="'.__('<EMAIL>',TEXTDOMAIN ).'"></p>', 'url' => '<p class="comment-form-url"><label for="url">'.__('Homepage',TEXTDOMAIN).'</label><input id="url" name="url" type="text" value="'.esc_attr($commenter['comment_author_url']).'" size="30" placeholder="'.__('http://homepage.domain.com',TEXTDOMAIN).'"></p>', ), 'comment_field' => '<p class="comment-form-comment"><label for="comment">'.__('Comment',TEXTDOMAIN).'</label><textarea id="comment" name="comment" cols="45" rows="8" aria-required="true" placeholder="'.__('Your comment here',TEXTDOMAIN).'"></textarea><input type="hidden" name="redirect_to" value="'.$post->comment_link.'">', 'must_log_in' => '<p class="must-log-in">'.sprintf(__('You must be <a href=\'%s\' target=\'_self\'>logged in</a> to post a comment.',TEXTDOMAIN),wp_login_url($post->comment_link)).'</p>', 'logged_in_as' => '<p class="logged-in-as">'.sprintf(__('Logged in as <a href=\'%1$s\'>%2$s</a>. <a href=\'%3$s\' title=\'Log out of this account\' target=\'_self\'>Log out?</a>',TEXTDOMAIN),admin_url('profile.php'),$user_identity,wp_logout_url($post->comment_link)).'</p>', 'comment_notes_before' => '<p class="comment-notes">'.__('Your email address will not be published.',TEXTDOMAIN).($req?$required_text:'').'</p>', 'comment_notes_after' => '<p class="form-allowed-tags">'.sprintf(__('You may use these <abbr title=\'HyperText Markup Language\'>HTML</abbr> tags and attributes: %s',TEXTDOMAIN),' <code>'.allowed_tags().'</code>').'</p>', )); $comment_form = ob_get_contents(); ob_end_clean(); echo str_replace('<form ','<form target="_self" ',$comment_form); else: echo "<p class='comments-are-closed'>".__('Comments are closed.',TEXTDOMAIN)."</p>".PHP_EOL; endif; ?> <file_sep><?php add_filter('show_admin_bar', '__return_false'); function on_init(){ add_theme_support('post-thumbnails'); add_theme_support('post-formats',array('standard','image')); if(DEFAULT_POST_FORMAT){ update_option('default_post_format',DEFAULT_POST_FORMAT); } register_nav_menu('navigation',__('Navigation',TEXTDOMAIN)); } add_action('init','on_init'); function on_after_theme_setup(){ load_theme_textdomain(TEXTDOMAIN,get_template_directory().'/languages'); } add_action('after_setup_theme', 'on_after_theme_setup'); function on_wp_enqueue_scripts(){ global $withcomments; $withcomments = 1; if(get_option('thread_comments')){ wp_enqueue_script('comment-reply'); } wp_enqueue_script('jquery-cookie',get_template_directory_uri().'/contrib/jquery-cookie/src/jquery.cookie.js',array('jquery')); wp_enqueue_script('imagesloaded',get_template_directory_uri().'/contrib/imagesloaded/imagesloaded.pkgd.min.js',array('jquery')); wp_enqueue_script('touchswipe',get_template_directory_uri().'/contrib/touchswipe/jquery.touchSwipe.min.js',array('jquery')); wp_enqueue_style('font-awesome',get_template_directory_uri().'/contrib/font-awesome/css/font-awesome.min.css'); //wp_enqueue_style('perfect-scrollbar',get_template_directory_uri().'/contrib/perfect-scrollbar/min/perfect-scrollbar.min.css'); //wp_enqueue_script('perfect-scrollbar',get_template_directory_uri().'/contrib/perfect-scrollbar/min/perfect-scrollbar.min.js',array('jquery')); wp_enqueue_style('fancybox',get_template_directory_uri().'/contrib/fancybox/source/jquery.fancybox.css'); wp_enqueue_script('fancybox',get_template_directory_uri().'/contrib/fancybox/source/jquery.fancybox.pack.js',array('jquery')); if(check_stylesheet()){ wp_enqueue_style('smallgallery',get_template_directory_uri().'/style.css',array('font-awesome')); } //wp_enqueue_script('smallgallery',get_template_directory_uri().'/script.js',array('jquery','jquery-cookie','imagesloaded','perfect-scrollbar','fancybox','touchswipe')); wp_enqueue_script('smallgallery',get_template_directory_uri().'/script.js',array('jquery','jquery-cookie','imagesloaded','fancybox','touchswipe')); } add_action('wp_enqueue_scripts','on_wp_enqueue_scripts'); add_action('wp_head','comments_popup_script'); function smallgallery_head(){ do_action('smallgallery_head'); } function on_smallgallery_head(){ $purge_console = !DEBUG_SCRIPT?'console.log = function(){};'.PHP_EOL:''; $title_text = TITLE_TEXT; $title_separator = TITLE_SEPARATOR; $slide_padding = SLIDE_PADDING; $slide_animation_names = "'".implode("','",explode(':',SLIDE_ANIMATION_NAMES))."'"; $slide_animation_duration = SLIDE_ANIMATION_DURATION; echo <<<HEAD <script> {$purge_console} var \$smallgallery = { title: { text: '{$title_text}', separator: '{$title_separator}' }, padding: '{$slide_padding}', animation: { name: [{$slide_animation_names}], duration: '{$slide_animation_duration}' } }; </script> HEAD; } add_action('smallgallery_head','on_smallgallery_head'); function shortcode_thumbnail_archives($options=array()){ $markup = ''; $defaults = array( 'posts_per_page' => -1, 'size' => 'thumbnail', 'category' => false, 'tag' => false, 'author' => false, 'ids' => false, ); $options = shortcode_atts($defaults,$options); $entries = get_posts($options); $markup = !empty($entries)?build_archives($entries):''; return $markup; } add_shortcode('thumbnail_archives','shortcode_thumbnail_archives'); function on_add_meta_boxes($post){ $boxes = array( 'slide_properties' => array( 'label' => make_label('slide_properties'), 'callback' => '_metabox', 'post_type' => 'post', 'context' => 'side', 'priority' => 'core', 'fields' => array( 'slide_weight' => array( 'name' => 'slide_weight', 'type' => 'radios', 'children' => array( array( 'name' => 'slide_weight', 'type' => 'radio', 'label' => 'default slide', 'value' => 0, ), array( 'name' => 'slide_weight', 'type' => 'radio', 'label' => 'cover slide', 'value' => 1, ), ), ), 'slide_animation' => array( 'name' => 'slide_animation', 'type' => 'radios', 'children' => array( ), ), 'slide_title' => array( 'name' => 'slide_title', 'type' => 'radios', 'children' => array( array( 'name' => 'slide_title', 'type' => 'radio', 'label' => 'hidden', 'value' => 0, ), array( 'name' => 'slide_title', 'type' => 'radio', 'label' => 'caption', 'value' => 1, ), array( 'name' => 'slide_title', 'type' => 'radio', 'label' => 'popup', 'value' => 2, ), ), ), 'slide_content' => array( 'name' => 'slide_content', 'type' => 'radios', 'children' => array( array( 'name' => 'slide_content', 'type' => 'radio', 'label' => 'hidden', 'value' => 0, ), array( 'name' => 'slide_content', 'type' => 'radio', 'label' => 'caption', 'value' => 1, ), array( 'name' => 'slide_content', 'type' => 'radio', 'label' => 'popup', 'value' => 2, ), ), ), 'slide_author' => array( 'name' => 'slide_author', 'type' => 'radios', 'children' => array( array( 'name' => 'slide_author', 'type' => 'radio', 'label' => 'hidden', 'value' => 0, ), array( 'name' => 'slide_author', 'type' => 'radio', 'label' => 'caption', 'value' => 1, ), array( 'name' => 'slide_author', 'type' => 'radio', 'label' => 'popup', 'value' => 2, ), ), ), 'slide_date' => array( 'name' => 'slide_date', 'type' => 'radios', 'children' => array( array( 'name' => 'slide_date', 'type' => 'radio', 'label' => 'hidden', 'value' => 0, ), array( 'name' => 'slide_date', 'type' => 'radio', 'label' => 'caption', 'value' => 1, ), array( 'name' => 'slide_date', 'type' => 'radio', 'label' => 'popup', 'value' => 2, ), ), ), 'slide_category' => array( 'name' => 'slide_category', 'type' => 'radios', 'children' => array( array( 'name' => 'slide_category', 'type' => 'radio', 'label' => 'hidden', 'value' => 0, ), array( 'name' => 'slide_category', 'type' => 'radio', 'label' => 'caption', 'value' => 1, ), array( 'name' => 'slide_category', 'type' => 'radio', 'label' => 'popup', 'value' => 2, ), ), ), 'slide_tag' => array( 'name' => 'slide_tag', 'type' => 'radios', 'children' => array( array( 'name' => 'slide_tag', 'type' => 'radio', 'label' => 'hidden', 'value' => 0, ), array( 'name' => 'slide_tag', 'type' => 'radio', 'label' => 'caption', 'value' => 1, ), array( 'name' => 'slide_tag', 'type' => 'radio', 'label' => 'popup', 'value' => 2, ), ), ), ), ), ); $slide_animation_names = explode(':',SLIDE_ANIMATION_NAMES); foreach($slide_animation_names as $index => $name){ $boxes['slide_properties']['fields']['slide_animation']['children'][] = array( 'name' => 'slide_animation', 'type' => 'radio', 'label' => $name, 'value' => $index, ); } foreach($boxes as $id => $options){ add_meta_box($id,$options['label'],$options['callback'],$options['post_type'],$options['context'],$options['priority'],$options); // $id, $title, $callback, $post_type, $context, $priority, $callback_args } } add_action('add_meta_boxes','on_add_meta_boxes'); function on_save_post($post_id){ if(defined('SMALLGALLERY_ON_SAVE_POST')){ return; }else{ define('SMALLGALLERY_ON_SAVE_POST',true); } if($_POST['post_type']!='post'){ return; } if(defined('DOING_AUTOSAVE')&&DOING_AUTOSAVE){ return; } if(!isset($_POST['slide_properties_nonce'])||!wp_verify_nonce($_POST['slide_properties_nonce'],'slide_properties')){ return; } $slide_format = $_POST['post_format']; $slide_format = $slide_format?$slide_format:'standard'; $slide_property_names = explode(':',SLIDE_PROPERTY_NAMES); foreach($slide_property_names as $slide_property_name){ $slide_property_name = "slide_{$slide_property_name}"; $slide_constant_name = strtoupper("default_{$post->post_format}_{$slide_property_name}"); $slide_property_value = 0; if(isset($_POST[$slide_property_name])){ $slide_property_value = $_POST[$slide_property_name]; }else if(defined($slide_constant_name)){ $slide_property_value = constant($slide_constant_name); } update_post_meta($post_id,$slide_property_name,$slide_property_value); } return; } add_action('save_post','on_save_post'); ?> <file_sep><?php class Smallgallery_Walker_Comment extends Walker_Comment { var $tree_type = 'comment'; var $db_fields = array( 'parent' => 'comment_parent', 'id' => 'comment_ID' ); function __construct() { global $post; $comments_title = sprintf(__('Comments on <strong>%s</strong>',TEXTDOMAIN),$post->filtered_title); echo <<<CONSTRUCT <h3 id="comments-title">{$comments_title}</h3> <ol id="comments" class="comments"> CONSTRUCT; } function start_lvl(&$output,$depth=0,$args=array()){ $GLOBALS['comment_depth'] = $depth + 1; echo <<<START_LVL <ol class="children"> START_LVL; } function end_lvl(&$output,$depth=0,$args=array()){ $GLOBALS['comment_depth'] = $depth + 1; echo <<<END_LVL </ul><!-- /.children --> END_LVL; } function start_el(&$output,$comment,$depth,$args,$id=0){ global $post; $depth++; $GLOBALS['comment_depth'] = $depth; $GLOBALS['comment'] = $comment; $parent_class = (empty($args['has_children'])?'':'parent'); if(get_option('thread_comments')){ $replyOptions = array_merge($args,array( 'add_below' => 'comment-body', 'depth' => $depth, 'max_depth' => $args['max_depth'] )); ob_start(); comment_reply_link($replyOptions,$comment,$post); $comment->reply_link = ob_get_contents(); ob_end_clean(); }else{ $comment->reply_link = ''; } ob_start(); edit_comment_link(__('Edit',TEXTDOMAIN)); $comment->edit_link = ob_get_contents(); ob_end_clean(); $comment->says = __(' says,',TEXTDOMAIN); $comment->at = __(' at ',TEXTDOMAIN); $comment->permalink = htmlspecialchars(get_comment_link()); $comment->class = comment_class($parent_class,null,null,false); $comment->portrait = $args['avatar_size']!=0?get_avatar($comment,$args['avatar_size']):''; $comment->filtered_author = get_comment_author_link(); $comment->filtered_date = get_comment_time(get_option('date_format'))."<span class='at'>{$comment->at}</span>".get_comment_time(get_option('time_format')); if(!$comment->comment_approved){ $comment->filtered_text = __('Your comment is awaiting moderation.',TEXTDOMAIN); }else{ $comment->filtered_text = get_comment_text(); } $comment->filtered_text = apply_filters('comment_text',$comment->filtered_text); echo <<<START_EL <li id="comment-{$comment->comment_ID}" {$comment->class}> <div id="comment-body-{$comment->comment_ID}" class="comment-body"> <div class="comment-author vcard author"> {$comment->portrait} <cite class="fn n author-name">{$comment->filtered_author}<span class="says">{$comment->says}</span></cite> </div><!--/.comment-author--> <div id="comment-content-{$comment->comment_ID}" class="comment-content"> {$comment->filtered_text} </div><!--/.comment-content--> <div class="comment-meta comment-meta-data"> <span class="comment-date">{$comment->filtered_date}</span> {$comment->reply_link} {$comment->edit_link} </div><!--/.comment-meta--> </div><!--/.comment-body--> START_EL; } function end_el(&$output,$comment,$depth=0,$args=array()){ echo <<<END_EL </li><!-- /#comment-{$comment->comment_ID}--> END_EL; } function __destruct() { echo <<<DESTRUCT </ul><!-- /#comment-list --> DESTRUCT; } } ?>
ad8f169c2dfab727c3f8a4214ab11dd8f8f316c1
[ "JavaScript", "Markdown", "PHP" ]
16
JavaScript
jinbonetwork/smallgallery
424dd6e9acb11e256074dfcbae5e60a9c6e37805
7707b22ad167c8028daacf989e1e5c7290a7bc36
refs/heads/main
<repo_name>IANDE-X/Trial-code<file_sep>/first.py from array import * import datetime print("Hello welcome to the programming world \n") phrase: str = "the world where code speaks, codes run and bugs suck!!! \n " my_country = input("Enter your country [----]:") print(phrase.replace("world", my_country).upper()) print("Lets code,lets learn languages,lets play with keyboard \n") def greetings(name, age): print("Good morning fuck u ", name.upper() + " " "you are ", str(age) + " years old You should be fucking working by this age, this is a disgrace to ", my_country) name = input("Enter your name:") Date = int(input("Enter your year of birth: \n")) age = int(2020 - Date) greetings(name, age) print("But okay, tell me a word and i will tell you 10 time:\n") i = input("Enter a word :\n") x = int(input("Enter any number:")) while x <= 10: if i == "bored": print("Hey ", name, " go out to play or read a book") break elif i == "love": print("wow,", name + " i love you:))\n") break elif i == "fuck" and age >= 18: print("haha,", name + " you're stupid stop simping\n") break elif i == "sad": print("awww,", name + " youre making me sad also , what acn we do\n") break else: print(" Huh", name, " that was a ", i, " right, whats wrong ", name + " is everything fine ?") break print("okay hey", name, "you are ", age, " years old now" "enter the password now:") secret = "ian" password = " " pass_count = 0 pass_limit = 3 out_of_guesses = False while password != secret and not (out_of_guesses): if pass_count < pass_limit: password = input("Enter a password:") pass_count += 1 else: out_of_guesses = True if out_of_guesses: print("You cannot guess any more, try after 30 seconds") else: print("Welcome ") class friend: def __init__(self, name, address, major, hobbie, partier): self.name = name self.address = address self.major = major self.hobbie = hobbie self.partier = partier friend1 = friend("john", "kandia", "engineering", "fucking", "yes") print("Name:", (friend1.name), "\n", "Adress:", (friend1.address), "\n", "Major:", (friend1.major), "\n", "Hobbie:", (friend1.hobbie)) x = input("Enter your new friend:\n") y: str = input("Enter your best friend:\n") z = input("Enter your closest friend:\n") friends = [x, y, z] friends2 = ["John", "Eliakim", "God", "jesus"] friends.extend(friends2) for friend in range(len(friends)): print("You're family is: ", (friends[friend])) print("\n") def translate(phrase): translation = "" for letter in phrase: if letter in "AEIOUaeiou": translation = translation + "g" else: translation = translation + letter return translation print(translate(input("ENTER A WORD TO BE TRANSLATED:[-------]:"))) class student: def __init__(self, name, address, major, gpa, probation): self.name = name self.address = address self.major = major self.gpa = gpa self.probation = probation def honor(self): if self.gpa >= 3: print((student1.name), "is on honor role\n") else: print((student1.name), " a failure \n ") student1 = student("john", "kandia", "engineering", 2, "yes") print("Name:", (student1.name), "\n", "Adress:", (student1.address), "\n", "Major:", (student1.major)) # question # here i used an array to store the different question that i willa sk the user questions_ask = [ "What COLOR are apples??\n 1.RED \n 2.BLUE \n 3.BLACK \n\n", "What is your favourite FRUIT??\n 1.APPLE \n 2.GUAVA \n 3.MANGO \n\n", "What CITIES have you been to?\n 1.NAI \n 2.NKU \n 3.KSM\n\n", ] # here i created a class called Question that i will pass the argumants prompt and aansew class Maswali: def __init__(self, ask, answer): self.ask = ask self.answer = answer # here is another array tha contains answers to the asked aquestions q ojects questions_object = [ Maswali(questions_ask[0], "1"), Maswali(questions_ask[1], "2"), Maswali(questions_ask[2], "1"), # qes ojcets ] # here is a function called run that i use to run it def run_questions(questions_object): # functio score = 0 # counter for question in questions_object: student_answer = input(question.ask) # variable jibu if student_answer == question.answer: score += 1 print("you got ", str(score), "/", str(len(questions_object)), " corre \n") run_questions(questions_object) print(student1.honor()) student_x = array('i', [1, 2, 3, 4, 5, 6, 67, ]) for x in range(4, 67): print(x) command = " " started = False while True: command = input(" press commands to start engine ----->>").lower() if command == "start": if started: print("car already starteed BITCH \n") else: started = True print("car started...\n") elif command == "stop": if not started: print("car already stopped\n") else: started = False print("car stopped.\n") elif command == "help": print(""" start- to start stop- to stop quit- to quit """) elif command == "quit": break else: print("I dont understand your command\n") Phone = input("PHONE:\n") digits_converter = { "1": "one", "2": "two", "3": "three", "4": "for", } output = "" for x in Phone: output += digits_converter.get(x, "!") + " " print(output) # emoji message = input("Enter some text with emotions like phrases like 💌💢❤:\n") words = message.split(' ') emojis = { ":)": "🧡", ":(": "🤣🤣🤣🤣🤣🤣🤣🤣", "_": "😣", "++": "😎😍😍" } out = "" z = 0 while z <= 10: for word in words: out += emojis.get(word, word) + " " z += 1 print("\n", (out)) now = datetime.datetime.now() print("Current date and time : \n") print("\nFinished on\n:", (now.strftime("%Y-%m-%d %H:%M:%S"))) print("\n") print("THE END\n")<file_sep>/Clock_timer.py ##import library from tkinter import * import time from playsound import playsound ## display window root = Tk() root.geometry('400x300') root.resizable(0, 0) root.config(bg='blanched almond') root.title('TechVidvan - Countdown Clock And Timer') Label(root, text='Countdown Clock and Timer', font='arial 20 bold', bg='papaya whip').pack() # display current time####################### Label(root, font='arial 15 bold', text='current time :', bg='papaya whip').place(x=40, y=70) ####fun to display current time def clock(): clock_time = time.strftime('%H:%M:%S %p') curr_time.config(text=clock_time) curr_time.after(1000, clock) curr_time = Label(root, font='arial 15 bold', text='', fg='gray25', bg='papaya whip') curr_time.place(x=190, y=70) clock() #######################timer countdown########## # storing seconds sec = StringVar() Entry(root, textvariable=sec, width=2, font='arial 12').place(x=250, y=155) sec.set('00') # storing minutes mins = StringVar() Entry(root, textvariable=mins, width=2, font='arial 12').place(x=225, y=155) mins.set('00') # storing hours hrs = StringVar() Entry(root, textvariable=hrs, width=2, font='arial 12').place(x=200, y=155) hrs.set('00') ##########fun to start countdown def countdown(): times = int(hrs.get()) * 3600 + int(mins.get()) * 60 + int(sec.get()) while times > -1: minute, second = (times // 60, times % 60) hour = 0 if minute > 60: hour, minute = (minute // 60, minute % 60) sec.set(second) mins.set(minute) hrs.set(hour) root.update() time.sleep(1) if (times == 0): playsound('Loud_Alarm_Clock_Buzzer.mp3') sec.set('00') mins.set('00') hrs.set('00') times -= 1 Label(root, font='arial 15 bold', text='set the time', bg='papaya whip').place(x=40, y=150) Button(root, text='START', bd='5', command=countdown, bg='antique white', font='arial 10 bold').place(x=150, y=210) root.mainloop() <file_sep>/README.md # Trial-code project one some working some not <file_sep>/ALARMCLI.py # alarm_clock.py # Description: A simple Python program to make the computer act # like an alarm clock. Start it running from the command line # with a command line argument specifying the duration in minutes # after which to sound the alarm. It will sleep for that long, # and then beep a few times. Use a duration of 0 to test the # alarm immediately, e.g. for checking that the volume is okay. # Author: <NAME> - http://www.dancingbison.com import datetime import time import winsound # sa = sys.argv # lsa = len(sys.argv) lsa = input("\n ENTER THE DURATION:") # Importing all the necessary libraries to form the alarm clock: set_alarm_timer =input("\n Enter the alarm:") def alarm(set_alarm_timer): while True: time.sleep(1) current_time = datetime.datetime.now() now = current_time.strftime("%H:%M:%S") date = current_time.strftime("%d/%m/%Y") print("The Set Date is:", date) print(now) if now == set_alarm_timer: print("Time to Wake up") winsound.PlaySound("sound.mp3", winsound.SND_ASYNC) break def actual_time(): set_alarm_timer = f"{hour.get()}:{min.get()}:{sec.get()}" alarm(set_alarm_timer) <file_sep>/trial.py import datetime class color: PURPLE = '\033[95m' CYAN = '\033[96m' DARKCYAN = '\033[36m' BLUE = '\033[94m' GREEN = '\033[92m' YELLOW = '\033[93m' RED = '\033[91m' BOLD = '\033[1m' UNDERLINE = '\033[4m' END = '\033[0m' print(color.BLUE, color.BOLD, '''Hello welcome Doctor Online , im here to help you with diagnosis whenever you ae sick always feel free to ask me any question , im your assitant, welcome, \n ''', color.END) # prevention phrase prevention = '''Hey,Protect yourself and others around you by knowing the facts and taking appropriate precautions. Follow advice provided by your local health authority. To prevent the spread of COVID-19: Clean your hands often. Use soap and water, or an alcohol-based hand rub. Maintain a safe distance from anyone who is coughing or sneezing. Wear a mask when physical distancing is not possible. Don’t touch your eyes, nose or mouth. Cover your nose and mouth with your bent elbow or a tissue when you cough or sneeze. Stay home if you feel unwell. If you have a fever, cough and difficulty breathing, seek medical attention. Calling in advance allows your healthcare provider to quickly direct you to the right health facility. This protects you, and prevents the spread of viruses and other infections. Masks Masks can help prevent the spread of the virus from the person wearing the mask to others. Masks alone do not protect against COVID-19, and should be combined with physical distancing and hand hygiene. Follow the advice provided by your local health authority. ''' print(color.BOLD + 'Hello World !' + color.END) questions_ask = [ "Have you travelled to a red covid zone before?\n 1.YES \n 2.NO \n 3.IM NOT SURE\n\n", "Do you feel fatigue?\n 1.YES\n 2.NO \n 3.A LITTLE \n\n", "Do you feel a cough, a dry throat or headache?\n 1.YES \n 2.NO\n 3.I FEEL A LITTLE DIZZY\n\n", "Do you have a difficulty in breathing?\n 1.YES\n 2.NO \n 3.A LITTLE \n\n", ] class Maswali: def __init__(self, ask, answer): self.ask = ask self.answer = answer questions_object = [ Maswali(questions_ask[0], "1"), Maswali(questions_ask[1], "2"), Maswali(questions_ask[2], "1"), Maswali(questions_ask[3], "2"), # qes ojcets ] # here is a function called run that i use to run it def run_questions(questions_object): # functio score = 0 # counter for question in questions_object: student_answer = input(question.ask) # variable jibu if student_answer == question.answer: score += 1 if score >= 3: print("you got ", str(score), "/", str(len(questions_object)), "covid 19 symptoms\n hence we " "\n recomend that you qurantine yourself" " for 14 days") elif score < 2: print("You are safe from covid !") run_questions(questions_object) print(color.RED + color.BOLD + "Bold red string" + color.END) questions_ask = [ color.RED, color.BOLD, "Have you travelled to a red covid zone before?\n 1.YES \n 2.NO \n 3.IM NOT SURE\n\n", "Do you feel fatigue?\n 1.YES\n 2.NO \n 3.A LITTLE \n\n", "Do you feel a cough, a dry throat or headache?\n 1.YES \n 2.NO\n 3.I FEEL A LITTLE DIZZY\n\n", "Do you have a difficulty in breathing?\n 1.YES\n 2.NO \n 3.A LITTLE \n\n", color.END ] class Maswali: def __init__(self, ask, answer): self.ask = ask self.answer = answer questions_object = [ Maswali(questions_ask[0], "1"), Maswali(questions_ask[1], "2"), Maswali(questions_ask[2], "1"), Maswali(questions_ask[3], "2"), # qes ojcets ] # here is a function called run that i use to run it def run_questions(questions_object): # functio score = 0 # counter for question in questions_object: student_answer = input(question.ask) # variable jibu if student_answer == question.answer: score += 1 if score >= 3: print(color.RED, color.BOLD, "you got ", str(score), "/", str(len(questions_object)), '''Self care If you feel sick you should rest, drink plenty of fluid, and eat nutritious food. Stay in a separate room from other family members, and use a dedicated bathroom if possible. Clean and disinfect frequently touched surfaces. Everyone should keep a healthy lifestyle at home. Maintain a healthy diet, sleep, stay active, and make social contact with loved ones through the phone or internet. Children need extra love and attention from adults during difficult times. Keep to regular routines and schedules as much as possible. It is normal to feel sad, stressed, or confused during a crisis. Talking to people you trust, such as friends and family, can help. If you feel overwhelmed, talk to a health worker or counsellor. Learn more on who.int For informational purposes only. Consult your local medical authority for advice. Medical treatments If you have mild symptoms and are otherwise healthy, self-isolate and contact your medical provider or a COVID-19 information line for advice. Seek medical care if you have a fever, cough, and difficulty breathing. Call in advance.''', color.END) else: print(color.GREEN, prevention, color.END) run_questions(questions_object) now = datetime.datetime.now() print("\nDiagnosed on\n:", (now.strftime("%Y-%m-%d %H:%M:%S"))) <file_sep>/2nd timeer.py class RepeatedTimer(object): def __init__(self, interval, function, *args, **kwargs): self._timer = None self.interval = interval self.function = function self.args = args self.kwargs = kwargs self.is_running = False self.next_call = time.time() self.start() def _run(self): self.is_running = False self.start() self.function(*self.args, **self.kwargs) def start(self): if not self.is_running: self.next_call += self.interval self._timer = threading.Timer(self.next_call - time.time(), self._run) self._timer.start() self.is_running = True def stop(self): self._timer.cancel() self.is_running = False def save_datetime(file='date.txt', user=getpass.getuser()): with open(file, 'a+') as f: f.write('register: ' + user + '\t' + str(datetime.datetime.now().time()) + '\n') if __name__ == '__main__': RepeatedTimer(1, save_datetime)<file_sep>/2nd jan.py from datetime import datetime import time import datetime class color: """Colors class: reset all colors with colors.reset two subclasses fg for foreground and bg for background. use as colors.subclass.colorname. i.e. colors.fg.red or colors.bg.green also, the generic bold, disable, underline, reverse, strikethrough, and invisible work with the main class i.e. colors.bold """ END = '\033[0m' BOLD = '\033[01m' RESET = '\033[02m' UNDERLINE = '\033[04m' REVERSE = '\033[07m' STRIKETHROUGH = '\033[09m' INVISIBLE = '\033[08m' class fg: BLACK = '\033[30m' RED = '\033[31m' GREEN = '\033[32m' ORANGE = '\033[33m' BLUE = '\033[34m' PURPLE = '\033[35m' CYAN = '\033[36m' LIGHTGREY = '\033[37m' DARKGREY = '\033[90m' LIGHTRED = '\033[91m' LIGHTGREEN = '\033[92m' YELLOW = '\033[93m' LIGHTBLUE = '\033[94m' PINK = '\033[95m' LIGHTCYAN = '\033[96m' class bg: BLACK = '\033[40m' RED = '\033[41m' GREEN = '\033[42m' ORANGE = '\033[43m' BLUE = '\033[44m' PURPLE = '\033[45m' CYAN = '\033[46m' LIGHTGREY = '\033[47m' start_time = datetime.datetime.now() while True: if (datetime.datetime.now() - start_time).seconds == 1: start_time = datetime.datetime.now() print(color.fg.BLUE, color.BOLD,"\n", (start_time),"\n", color.END) #former code ya time #while True: #now = datetime.now() # z = "\r%s/%s/%s %s:%s:%s" % (now.month, now.day, now.year, now.hour, now.minute, now.second) #q = end = ' ' #print(color.fg.BLUE, color.BOLD, z, q, color.END) #time.sleep(1) #print('')
3bdfe407e330235f2f847ed0fccba7beb15f66f8
[ "Markdown", "Python" ]
7
Python
IANDE-X/Trial-code
f12bc703a4e019213339a8644612b79606c530e7
74e6357cd63397682234aa7adf76de7f4d082425
refs/heads/master
<file_sep>package com.datamata.market.coin.bot; /** * This Bot's objective is to safely show/test order submission cancellation within trading station. * Actual trading is not its purpose. */ public class BotTest implements Api.Bot, Api{ Position positionBtcUsd; int orderCount = 0; public String getParameterDescription() { return "Specify account name to run test against"; } public void onStart(Control c, Setup s, String param){ c.out.println(c.getTime()+" BotTest.onStartEvent"); positionBtcUsd = c.getAccount(param).getPosition(Currency.BTC, Currency.USD); // Will automatically round order prices to 2 decimal points positionBtcUsd.setPricePrecision(2); // Will automatically round order quantities to 2 decimal points positionBtcUsd.setQuantityPrecision(2); // Subscribing for Quote.Ticker updates s.subscribeForQuoteTicker(positionBtcUsd); // Subscribing for Quote.Depth updates s.subscribeForQuoteDepth(positionBtcUsd); // Subscribing for Trade.List updates s.subscribeForTradeList(positionBtcUsd); // Subscribing for Timer calls every 5 seconds s.subscribeForTimer(5); } public void onStop(Control c) { c.out.println(c.getTime()+" BotTest.onStopEvent"); } public void onQuoteTicker(Control c, Quote.Ticker t) { c.out.println(c.getTime()+" BotTest.onQuoteTickerEvent: "+t); if(positionBtcUsd.getAllOrders().size()==0){ // If there are no orders, issue buy and sell 2% safely away from current price. positionBtcUsd.submitOrder( 0.02, t.getBid() * 0.98); positionBtcUsd.submitOrder(-0.02, t.getAsk() * 1.02); // Will add a message log about new orders. It will be with timestamp and Bot name. c.showInfoMessage("2 Orders submitted"); // Show order counter in status line. c.showStatus("Total Orders: "+(orderCount+=2)); } } public void onQuoteDepth(Control c, Quote.Depth d) { c.out.println(c.getTime()+" BotTest.onDepthEvent: "+d); } public void onTradeList(Control c, Api.Trade.List l) { c.out.println(c.getTime()+" ***BotTest.onTradeListEvent: "+l); } public void onTimer(Control c, Time time) { c.out.println(c.getTime()+" BotTest.onTimerEvent."); // If orders are out there for 12 seconds or more, cancel them. for(Order o : positionBtcUsd.getAllOrders()){ if(o.getTime().getAgeSeconds()>12 && o.getStatus().isSubmitted()){ o.cancel(); c.showInfoMessage("Cancelled "+o); } } // Clean station old orders, with 4 latest left int i = positionBtcUsd.cleanStationOldOrders(4); if(i>0) c.showInfoMessage("Cleared "+i+" old orders."); } }
24f3646490369937689cf7e4484faccd4b62b008
[ "Java" ]
1
Java
datamata/Bitcoin-Trading-Station
e890ad0033da8e04ad099e0708a4762e3b1ec61d
0923a3c2eded304c5ad43023f479a3c5db4e7dd2
refs/heads/master
<repo_name>anants277/TodoList<file_sep>/Todo-List-master/ToDoList/ViewControllers/AddTodoViewController.swift // // AddTodoViewController.swift // ToDoList // // Created by Creo Server on 24/06/20. // Copyright © 2020 Anant Server. All rights reserved. // import UIKit import RealmSwift class AddTodoViewController: UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate{ private var realm = try! Realm() var completionHandler : (()-> Void)? var todoImage = UIImage() var todoTitle = "" var todoDescription = "" var todoImageName = "" var errormsg = "" var bottomView : BottomView! var bottomViewConstraint : NSLayoutConstraint! var tableView : UITableView = { let tableView = UITableView() tableView.translatesAutoresizingMaskIntoConstraints = false tableView.keyboardDismissMode = .onDrag return tableView }() override func viewDidLoad() { super.viewDidLoad() subscribeToShowKeyboardNotifications() // Do any additional setup after loading the view. } override func loadView() { super.loadView() setup() } func setup() { view.backgroundColor = #colorLiteral(red: 1, green: 0.9274827249, blue: 0.6415239935, alpha: 1) title = "New Todo Item" view.addSubview(tableView) tableView.edges([.left,.right,.top,.bottom], to: view.safeAreaLayoutGuide, offset: UIEdgeInsets(top: 30, left: 20, bottom: -80, right: -20)) tableView.dataSource = self tableView.delegate = self tableView.register(TextFieldTableViewCell.self, forCellReuseIdentifier: "TextFieldCell") tableView.register(TextViewTableViewCell.self, forCellReuseIdentifier: "TextViewCell") tableView.register(ButtonTableViewCell.self, forCellReuseIdentifier: "ButtonCell") tableView.register(LabelTableViewCell.self, forCellReuseIdentifier: "LabelCell") tableView.tableFooterView = UIView() tableView.backgroundColor = #colorLiteral(red: 1, green: 0.9274827249, blue: 0.6415239935, alpha: 1) bottomView = BottomView(frame: CGRect(x: view.frame.size.width/2, y: 0, width: view.frame.size.width, height: 80)) bottomView.translatesAutoresizingMaskIntoConstraints = false bottomView.backgroundColor = #colorLiteral(red: 1, green: 0.9274827249, blue: 0.6415239935, alpha: 1) view.addSubview(bottomView) bottomView.edges([.left,.right], to: view, offset: UIEdgeInsets(top: 0, left: 30, bottom: 0, right: -30)) bottomViewConstraint = bottomView.bottomAnchor.constraint(equalTo: view.safeAreaLayoutGuide.bottomAnchor, constant: 0) bottomViewConstraint.isActive = true bottomView.cancelButton.addTarget(self, action: #selector(cancelButtonAction), for: .touchUpInside) bottomView.doneButton.addTarget(self, action: #selector(doneButtonAction), for: .touchUpInside) } @objc func cancelButtonAction() { self.dismiss(animated: true, completion: nil) } @objc func doneButtonAction() { if(todoTitle != "") { realm.beginWrite() let newItem = ListItem() newItem.title = todoTitle newItem.todoDescription = todoDescription newItem.imageName = todoImageName newItem.toDoisChecked = false realm.add(newItem) try! realm.commitWrite() completionHandler?() self.dismiss(animated: true, completion: nil) } else { errormsg = "Please give a title.." tableView.beginUpdates() tableView.reloadRows(at: [IndexPath(row: 1, section: 1)], with: .automatic) tableView.endUpdates() } } @objc func showAlertForPhoto(_ sender : UIButton) { let imagePickerController = UIImagePickerController() imagePickerController.delegate = self let actionSheet = UIAlertController(title: "Photo Source", message: "Choose a source", preferredStyle: .actionSheet) actionSheet.addAction(UIAlertAction(title: "Camera", style: .default, handler: { (action: UIAlertAction) in if UIImagePickerController.isSourceTypeAvailable(.camera) { imagePickerController.sourceType = .camera self.present(imagePickerController, animated: true, completion: nil) } else { print("no camera available") } })) actionSheet.addAction(UIAlertAction(title: "Photo Library", style: .default, handler: { (action: UIAlertAction) in imagePickerController.sourceType = .photoLibrary self.present(imagePickerController, animated: true, completion: nil) })) actionSheet.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: { (action: UIAlertAction) in })) self.present(actionSheet, animated: true, completion: nil) } func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) { let pickedImage = info[UIImagePickerController.InfoKey.originalImage] as! UIImage todoImage = pickedImage tableView.reloadData() dismiss(animated: true, completion: nil) DispatchQueue.global().async { self.todoImageName = UUID().uuidString let fileManager = FileManager.default let imagePath = (NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0] as NSString).appendingPathComponent(self.todoImageName) let image = pickedImage let data = image.pngData() fileManager.createFile(atPath: imagePath as String, contents: data, attributes: nil) } } func imagePickerControllerDidCancel(_ picker: UIImagePickerController) { dismiss(animated: true, completion: nil) } @objc func keyboardWillShow(_ notification: Notification) { let userInfo = notification.userInfo let keyboardSize = userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as! NSValue let keyboardHeight = keyboardSize.cgRectValue.height var extraHeight:CGFloat = 0 if UIDevice.current.hasNotch { extraHeight = 20 } bottomViewConstraint.constant = -keyboardHeight + extraHeight let animationDuration = userInfo?[UIResponder.keyboardAnimationDurationUserInfoKey] as! Double UIView.animate(withDuration: animationDuration) { self.view.layoutIfNeeded() } } @objc func keyboardWillHide(_ notification: Notification) { bottomViewConstraint.constant = 0 let userInfo = notification.userInfo let animationDuration = userInfo?[UIResponder.keyboardAnimationDurationUserInfoKey] as! Double UIView.animate(withDuration: animationDuration) { self.view.layoutIfNeeded() } } func subscribeToShowKeyboardNotifications() { NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow(_:)), name: UIResponder.keyboardWillShowNotification, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillHide(_:)), name: UIResponder.keyboardWillHideNotification, object: nil) } @objc func textFieldDidChange(textField : UITextField) { if textField.text!.count > 0 { todoTitle = textField.text! } } } extension AddTodoViewController: UITableViewDataSource { func numberOfSections(in tableView: UITableView) -> Int { 3 } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { if section == 1 { return 2 } return 1 } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { if indexPath.section == 0 { let cell = tableView.dequeueReusableCell(withIdentifier: "TextFieldCell", for: indexPath) as! TextFieldTableViewCell cell.titleTextField.addTarget(self, action: #selector(textFieldDidChange(textField:)), for: UIControl.Event.editingChanged) return cell } else if indexPath.section == 1 { if indexPath.row == 0 { let cell = tableView.dequeueReusableCell(withIdentifier: "TextViewCell", for: indexPath) as! TextViewTableViewCell cell.titleTextView.delegate = self return cell }else { let cell = tableView.dequeueReusableCell(withIdentifier: "LabelCell", for: indexPath) as! LabelTableViewCell cell.label.text = errormsg cell.label.textColor = .red cell.label.textAlignment = .center return cell } } else { let cell = tableView.dequeueReusableCell(withIdentifier: "ButtonCell", for: indexPath) as! ButtonTableViewCell cell.label.text = "Image to remember" cell.label.textColor = .black cell.button.backgroundColor = #colorLiteral(red: 0.8039215803, green: 0.8039215803, blue: 0.8039215803, alpha: 1) cell.button.setImage(UIImage(named: "add"), for: .normal) cell.button.setBackgroundImage(todoImage, for: .normal) cell.button.addTarget(self, action: #selector(showAlertForPhoto(_:)), for: .touchUpInside) return cell } } } extension AddTodoViewController: UITableViewDelegate { func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { if indexPath == IndexPath(row: 0, section: 1) { return view.frame.size.height/3 } return UITableView.automaticDimension } func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? { return UIView() } func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat { return 50 } } extension AddTodoViewController: UITextViewDelegate { func textViewDidChange(_ textView: UITextView) { if textView.text.count > 0 { todoDescription = textView.text } } } <file_sep>/Todo-List-master/ToDoList/TableViewCells/TextViewTableViewCell.swift // // TextViewTableViewCell.swift // ToDoList // // Created by Creo Server on 24/06/20. // Copyright © 2020 Anant Server. All rights reserved. // import UIKit import KMPlaceholderTextView class TextViewTableViewCell: UITableViewCell { var titleTextView : KMPlaceholderTextView = { let titleTextView = KMPlaceholderTextView() titleTextView.translatesAutoresizingMaskIntoConstraints = false return titleTextView }() override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) if reuseIdentifier == "TextViewCell" { setup() } } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } func setup() { contentView.addSubview(titleTextView) titleTextView.edges(.all, to: contentView, offset: UIEdgeInsets.zero) titleTextView.placeholder = "Description" // titleTextView.heightAnchor.constraint(equalToConstant: 250).isActive = true titleTextView.font = UIFont.systemFont(ofSize: 20) titleTextView.sizeToFit() titleTextView.isScrollEnabled = true } override func awakeFromNib() { super.awakeFromNib() // Initialization code } override func setSelected(_ selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) // Configure the view for the selected state } } <file_sep>/Todo-List-master/ToDoList/ViewControllers/ToDoListViewController.swift // // ViewController.swift // ToDoList // // Created by Creo Server on 24/06/20. // Copyright © 2020 Anant Server. All rights reserved. // import UIKit import RealmSwift class ToDoListViewController: UIViewController { var realm = try! Realm() var toDoList = [ListItem]() var searchTodoList = [ListItem]() var searching = false var searchBar : UISearchBar = { let searchBar = UISearchBar() searchBar.translatesAutoresizingMaskIntoConstraints = false searchBar.searchBarStyle = .minimal return searchBar }() var tableView : UITableView = { let tableView = UITableView() tableView.translatesAutoresizingMaskIntoConstraints = false tableView.keyboardDismissMode = .onDrag return tableView }() var activityIndicatorView : UIActivityIndicatorView = { let activityIndicatorView = UIActivityIndicatorView() activityIndicatorView.translatesAutoresizingMaskIntoConstraints = false return activityIndicatorView }() override func viewDidLoad() { super.viewDidLoad() toDoList = arrangeList() } override func loadView() { super.loadView() setup() } func setup() { view.backgroundColor = #colorLiteral(red: 1, green: 0.9274827249, blue: 0.6415239935, alpha: 1) title = "Todo List" self.navigationController?.navigationBar.barTintColor = #colorLiteral(red: 1, green: 0.9274827249, blue: 0.6415239935, alpha: 1) self.navigationController?.navigationBar.tintColor = #colorLiteral(red: 0, green: 0, blue: 0, alpha: 1) let button = UIButton(type: .system) button.setImage(UIImage(named: "add"), for: .normal) button.setTitle("Add", for: .normal) button.sizeToFit() self.navigationItem.rightBarButtonItem = UIBarButtonItem(customView: button) button.addTarget(self, action: #selector(addButtonAction(sender:)), for: .touchUpInside) view.addSubview(activityIndicatorView) activityIndicatorView.style = .large activityIndicatorView.size(width: 50, height: 50) activityIndicatorView.center = view.center view.addSubview(searchBar) searchBar.edges([.left,.right,.top], to: view.safeAreaLayoutGuide, offset: UIEdgeInsets(top: 10, left: 10, bottom: 0, right: -10)) searchBar.layer.masksToBounds = false searchBar.barTintColor = .yellow searchBar.backgroundColor = #colorLiteral(red: 1, green: 0.9274827249, blue: 0.6415239935, alpha: 1) searchBar.tintColor = .blue searchBar.showsCancelButton = true searchBar.placeholder = " " searchBar.delegate = self view.addSubview(tableView) tableView.topAnchor.constraint(equalTo: searchBar.bottomAnchor, constant: 10).isActive = true tableView.edges([.left,.right,.bottom], to: view, offset: UIEdgeInsets(top: 0, left: 10, bottom: 10, right: -10)) tableView.dataSource = self tableView.delegate = self tableView.register(ToDoTableViewCell.self, forCellReuseIdentifier: "ToDoCell") tableView.tableFooterView = UIView() tableView.backgroundColor = #colorLiteral(red: 1, green: 0.9274827249, blue: 0.6415239935, alpha: 1) } @objc func addButtonAction(sender: UIButton) { let addVC = AddTodoViewController() addVC.completionHandler = { self.refresh() } let navAddVC = UINavigationController(rootViewController: addVC) navAddVC.modalPresentationStyle = .fullScreen self.present(navAddVC, animated: true, completion: nil) } func refresh() { var uncheckedList = [ListItem]() var checkedList = [ListItem]() let allList = realm.objects(ListItem.self).map({$0}) for item in allList { if item.toDoisChecked == false{ uncheckedList.append(item) } else { checkedList.append(item) } } toDoList = uncheckedList + checkedList tableView.reloadData() } func arrangeList()-> [ListItem] { var uncheckedList = [ListItem]() var checkedList = [ListItem]() let allList = realm.objects(ListItem.self).map({$0}) for item in allList { if item.toDoisChecked == false{ uncheckedList.append(item) } else { checkedList.append(item) } } return uncheckedList + checkedList } @objc func checkTheBox(_ sender: UIButton) { if !searching { let index = sender.tag let duplicateItem = ListItem() duplicateItem.title = toDoList[index].title duplicateItem.todoDescription = toDoList[index].todoDescription duplicateItem.imageName = toDoList[index].imageName duplicateItem.toDoisChecked = !toDoList[index].toDoisChecked realm.beginWrite() realm.delete(toDoList[index]) realm.add(duplicateItem) try! realm.commitWrite() self.refresh() } else { let alert = UIAlertController(title: "ALERT!", message: "Can't edit while searching!!", preferredStyle: .alert) alert.addAction(UIAlertAction(title: "OK", style: .cancel, handler: nil)) self.present(alert, animated: true,completion: nil) } } } extension ToDoListViewController: UITableViewDataSource { func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return searching ? searchTodoList.count : toDoList.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "ToDoCell", for: indexPath) as! ToDoTableViewCell var imageName = "" var checkImage = UIImage() cell.tag = indexPath.row if searching { cell.titleLabel.text = searchTodoList[indexPath.row].title cell.descriptionLabel.text = searchTodoList[indexPath.row].todoDescription imageName = searchTodoList[indexPath.row].imageName checkImage = (searchTodoList[indexPath.row].toDoisChecked ? UIImage(systemName: "checkmark.circle.fill") : UIImage(systemName: "circle"))! } else { cell.titleLabel.text = toDoList[indexPath.row].title cell.descriptionLabel.text = toDoList[indexPath.row].todoDescription imageName = toDoList[indexPath.row].imageName checkImage = (toDoList[indexPath.row].toDoisChecked ? UIImage(systemName: "checkmark.circle.fill") : UIImage(systemName: "circle"))! cell.checkButton.tag = indexPath.row cell.checkButton.addTarget(self, action: #selector(checkTheBox(_:)), for: .touchUpInside) } cell.checkButton.setBackgroundImage(checkImage, for: .normal) let fileManager = FileManager.default let imagePath = (NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0] as NSString).appendingPathComponent(imageName) if fileManager.fileExists(atPath: imagePath){ cell.myImageView.image = UIImage(contentsOfFile: imagePath) }else{ print("No Image!") } return cell } } extension ToDoListViewController: UITableViewDelegate { func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return UITableView.automaticDimension } } extension ToDoListViewController: UISearchBarDelegate { func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) { searchTodoList = toDoList.filter({$0.title.lowercased().prefix(searchText.count) == searchText.lowercased()}) searching = true tableView.reloadData() } func searchBarCancelButtonClicked(_ searchBar: UISearchBar) { searching = false searchBar.text = "" tableView.reloadData() searchBar.resignFirstResponder() } } <file_sep>/Todo-List-master/ToDoList/TableViewCells/ToDoTableViewCell.swift // // ToDoTableViewCell.swift // ToDoList // // Created by Creo Server on 24/06/20. // Copyright © 2020 Anant Server. All rights reserved. // import UIKit class ToDoTableViewCell: UITableViewCell { var titleLabel : UILabel = { let titleLabel = UILabel() titleLabel.translatesAutoresizingMaskIntoConstraints = false return titleLabel }() var descriptionLabel : UILabel = { let descriptionLabel = UILabel() descriptionLabel.translatesAutoresizingMaskIntoConstraints = false return descriptionLabel }() var checkButton : UIButton = { let checkButton = UIButton() checkButton.translatesAutoresizingMaskIntoConstraints = false checkButton.tintColor = .black return checkButton }() var myImageView : UIImageView = { let myImageView = UIImageView() myImageView.translatesAutoresizingMaskIntoConstraints = false return myImageView }() override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) if reuseIdentifier == "ToDoCell" { setup() } } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } func setup() { contentView.backgroundColor = #colorLiteral(red: 1, green: 0.9274827249, blue: 0.6415239935, alpha: 1) contentView.addSubview(checkButton) checkButton.size(width: 30, height: 30) checkButton.centerYAnchor.constraint(equalTo: contentView.centerYAnchor).isActive = true checkButton.edges([.right, ], to: contentView, offset: UIEdgeInsets(top: 10, left: 0, bottom: 0, right: -10)) checkButton.layer.cornerRadius = 15 checkButton.layer.masksToBounds = false checkButton.clipsToBounds = true checkButton.setBackgroundImage(UIImage(systemName: "checkmark.circle.fill"), for: .normal) contentView.addSubview(myImageView) myImageView.size(width: 60, height: 60) // myImageView.centerYAnchor.constraint(equalTo: contentView.centerYAnchor).isActive = true myImageView.edges([.left, .top, .bottom], to: contentView, offset: UIEdgeInsets(top: 10, left: 10, bottom: -10, right: 0)) myImageView.layer.cornerRadius = 30 myImageView.layer.masksToBounds = false myImageView.clipsToBounds = true myImageView.image = UIImage(systemName: "circle") contentView.addSubview(titleLabel) titleLabel.trailingAnchor.constraint(equalTo: checkButton.leadingAnchor, constant: -10).isActive = true titleLabel.leadingAnchor.constraint(equalTo: myImageView.trailingAnchor, constant: 5).isActive = true titleLabel.edges([.top], to: contentView, offset: UIEdgeInsets(top: 15, left: 0, bottom: 0, right: 0)) titleLabel.text = " " titleLabel.textAlignment = .left titleLabel.textColor = .black titleLabel.font = UIFont.boldSystemFont(ofSize: 18.0) contentView.addSubview(descriptionLabel) descriptionLabel.leadingAnchor.constraint(equalTo: myImageView.trailingAnchor, constant: 5).isActive = true descriptionLabel.topAnchor.constraint(equalTo: titleLabel.bottomAnchor, constant: 10).isActive = true descriptionLabel.trailingAnchor.constraint(equalTo: checkButton.leadingAnchor, constant: -10).isActive = true descriptionLabel.text = " " descriptionLabel.textAlignment = .left descriptionLabel.textColor = .black descriptionLabel.numberOfLines = 2 descriptionLabel.font = UIFont.systemFont(ofSize: 14.0) } } <file_sep>/Todo-List-master/ToDoList/AppDelegate.swift // // AppDelegate.swift // ToDoList // // Created by Creo Server on 24/06/20. // Copyright © 2020 Anant Server. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { // Override point for customization after application launch. //setting up window window = UIWindow(frame: UIScreen.main.bounds) //to show the current window and position it in front of all other windows at the same level or lower window?.makeKeyAndVisible() let vc = ToDoListViewController() window?.rootViewController = UINavigationController(rootViewController: vc) return true } } <file_sep>/Todo-List-master/ToDoList/TableViewCells/LabelTableViewCell.swift // // LabelTableViewCell.swift // ToDoList // // Created by Creo Server on 25/06/20. // Copyright © 2020 Anant Server. All rights reserved. // import UIKit class LabelTableViewCell: UITableViewCell { var label : UILabel = { let label = UILabel() label.translatesAutoresizingMaskIntoConstraints = false return label }() override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) if reuseIdentifier == "LabelCell" { setup() } } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } func setup() { contentView.backgroundColor = #colorLiteral(red: 1, green: 0.9274827249, blue: 0.6415239935, alpha: 1) contentView.addSubview(label) label.edges(.all, to: contentView, offset: UIEdgeInsets(top: 15, left: 0, bottom: 0, right: 0)) label.font = UIFont.systemFont(ofSize: 15) } override func awakeFromNib() { super.awakeFromNib() // Initialization code } override func setSelected(_ selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) // Configure the view for the selected state } } <file_sep>/Todo-List-master/ToDoList/Extension.swift // // Extension.swift // ToDoList // // Created by Creo Server on 24/06/20. // Copyright © 2020 Anant Server. All rights reserved. // import Foundation import UIKit extension UIView { func edges(_ edges: UIRectEdge, to view: UIView, offset: UIEdgeInsets) { if edges.contains(.top) || edges.contains(.all) { self.topAnchor.constraint(equalTo: view.topAnchor, constant: offset.top).isActive = true } if edges.contains(.bottom) || edges.contains(.all) { self.bottomAnchor.constraint(equalTo: view.bottomAnchor, constant: offset.bottom).isActive = true } if edges.contains(.left) || edges.contains(.all) { self.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: offset.left).isActive = true } if edges.contains(.right) || edges.contains(.all) { self.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: offset.right).isActive = true } } func edges(_ edges: UIRectEdge, to layoutGuide: UILayoutGuide, offset: UIEdgeInsets) { if edges.contains(.top) || edges.contains(.all) { self.topAnchor.constraint(equalTo: layoutGuide.topAnchor, constant: offset.top).isActive = true } if edges.contains(.bottom) || edges.contains(.all) { self.bottomAnchor.constraint(equalTo: layoutGuide.bottomAnchor, constant: offset.bottom).isActive = true } if edges.contains(.left) || edges.contains(.all) { self.leadingAnchor.constraint(equalTo: layoutGuide.leadingAnchor, constant: offset.left).isActive = true } if edges.contains(.right) || edges.contains(.all) { self.trailingAnchor.constraint(equalTo: layoutGuide.trailingAnchor, constant: offset.right).isActive = true } } func size(width: CGFloat, height: CGFloat) { NSLayoutConstraint.activate([self.widthAnchor.constraint(equalToConstant: width),self.heightAnchor.constraint(equalToConstant: height)]) } } extension UIDevice { var hasNotch: Bool { let bottom = UIApplication.shared.keyWindow?.safeAreaInsets.bottom ?? 0 return bottom > 0 } } <file_sep>/Todo-List-master/ToDoList/TableViewCells/ButtonTableViewCell.swift // // ButtonTableViewCell.swift // ToDoList // // Created by Creo Server on 25/06/20. // Copyright © 2020 Anant Server. All rights reserved. // import UIKit import UIKit class ButtonTableViewCell: UITableViewCell { var label : UILabel = { let label = UILabel() label.translatesAutoresizingMaskIntoConstraints = false label.textAlignment = .left return label }() var button : UIButton = { let button = UIButton() button.translatesAutoresizingMaskIntoConstraints = false return button }() required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func awakeFromNib() { super.awakeFromNib() // Initialization code } override func setSelected(_ selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) // Configure the view for the selected state } override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) self.selectionStyle = .none if reuseIdentifier == "ButtonCell" { setupButtonWithLabel() } } func setupButtonWithLabel() { contentView.backgroundColor = #colorLiteral(red: 1, green: 0.9274827249, blue: 0.6415239935, alpha: 1) self.contentView.addSubview(label) label.edges([.top, .left, . right], to: self.contentView, offset: UIEdgeInsets(top: 0, left: 20, bottom: 0, right: -20)) self.contentView.addSubview(button) button.leadingAnchor.constraint(equalTo: contentView.leadingAnchor, constant: 20).isActive = true button.topAnchor.constraint(equalTo: label.bottomAnchor, constant: 20).isActive = true button.size(width: 60, height: 60) button.bottomAnchor.constraint(equalTo: contentView.bottomAnchor, constant: -10).isActive = true } } <file_sep>/Todo-List-master/ToDoList/DataModels/ListItem.swift // // ListItem.swift // ToDoList // // Created by Creo Server on 24/06/20. // Copyright © 2020 Anant Server. All rights reserved. // import Foundation import UIKit import RealmSwift class ListItem: Object { @objc dynamic var title : String = "" @objc dynamic var todoDescription: String = "" @objc dynamic var imageName: String = "" @objc dynamic var toDoisChecked: Bool = false } <file_sep>/Todo-List-master/ToDoList/CustomViews/BottomView.swift // // BottomView.swift // ToDoList // // Created by Creo Server on 24/06/20. // Copyright © 2020 Anant Server. All rights reserved. // import UIKit class BottomView: UIView { func createButton() -> UIButton { let button = UIButton() button.translatesAutoresizingMaskIntoConstraints = false button.layer.borderWidth = 2 button.layer.cornerRadius = 10 button.setTitleColor(.black, for: .normal) return button } var cancelButton : UIButton! var doneButton: UIButton! override init(frame: CGRect) { super.init(frame: frame) // self.backgroundColor = .white cancelButton = createButton() doneButton = createButton() self.addSubview(cancelButton) cancelButton.edges([.left,.bottom,.top], to: self, offset: UIEdgeInsets(top: 5, left: 5, bottom: -5, right: 0)) cancelButton.size(width: self.frame.size.width/3, height: 50) cancelButton.setTitle("CANCEL", for: .normal) self.addSubview(doneButton) doneButton.edges([.right,.bottom,.top], to: self, offset: UIEdgeInsets(top: 5, left: 0, bottom: -5, right: -5)) doneButton.size(width: self.frame.size.width/3, height: 50) doneButton.setTitle("DONE", for: .normal) } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } } <file_sep>/Todo-List-master/ToDoList/TableViewCells/TextFieldTableViewCell.swift // // TextFieldTableViewCell.swift // ToDoList // // Created by Creo Server on 24/06/20. // Copyright © 2020 Anant Server. All rights reserved. // import UIKit class TextFieldTableViewCell: UITableViewCell { var titleTextField : UITextField = { let titleTextField = UITextField() titleTextField.translatesAutoresizingMaskIntoConstraints = false return titleTextField }() override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) if reuseIdentifier == "TextFieldCell" { setup() } } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } func setup() { contentView.addSubview(titleTextField) titleTextField.edges(.all, to: contentView, offset: UIEdgeInsets(top: 0, left: 5, bottom: 0, right: 0)) titleTextField.placeholder = "Title*" titleTextField.heightAnchor.constraint(equalToConstant: 50).isActive = true titleTextField.font = UIFont.systemFont(ofSize: 20) } override func awakeFromNib() { super.awakeFromNib() // Initialization code } override func setSelected(_ selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) // Configure the view for the selected state } }
8948a005322bd586cacf4bf72eccbaaa40d09bfc
[ "Swift" ]
11
Swift
anants277/TodoList
26a93439822fcb836dc2f674d9631e037cde9773
0c60ee5a09017bea0eb853e456c1044199c32e9d
refs/heads/master
<file_sep># hospital-api ## Overview: Sample API for the doctors to manage COVID-19 patients. ## Routes: #### Doctors: - /doctors/register --> Registration of doctor. - /doctors/login --> Login of doctor #### Patients: - /patients/register ---> Registration of patient - /patients/:id/create_report ---> Create a testing report of patient - /patients/:id/all_reports ---> Generate all reports of a particular patient. #### Other: - /reports/:status --> Generate all the report based on a particular status. ### Tech Stack : - Node, Express, MongoDB. - Passport is used for Authentication (JWT) ## Project Structure: ``` ├── config │   ├── mongoose.js │   └── passport-jwt-strategy.js ├── controllers │   ├── doctor_controller.js │   ├── patient_controller.js │   └── report_controller.js ├── index.js ├── models │   ├── doctor.js │   └── patient.js ├── package-lock.json ├── package.json └── routes ├── doctors.js ├── index.js └── patients.js ``` <file_sep>const express = require("express"); const router = express.Router(); const reportController = require("../controllers/report_controller"); console.log("router loaded"); router.get("/", (req, res) => { return res.status(200).json({ msg: "hello", }); }); router.use("/doctors", require("./doctors.js")); router.use("/patients", require("./patients.js")); router.get("/reports/:status", reportController.getReportBystatus); module.exports = router; <file_sep>const mongoose = require("mongoose"); const reports = mongoose.Schema({}); const patient = new mongoose.Schema( { phone: { type: String, required: true, unique: true, }, name: { type: String, required: true, }, reports: [ { _id: false, createdBy: { type: mongoose.Schema.Types.ObjectId, ref: "Doctor", }, status: { type: String, required: true, }, date: { type: String, required: true, }, }, ], }, { timestamps: true, } ); const Patient = mongoose.model("Patient", patient); module.exports = Patient; <file_sep>const Doctor = require("../models/doctor"); const jwt = require("jsonwebtoken"); const bcrypt = require("bcrypt"); const saltRounds = 10; module.exports.register = async function (req, res) { try { let hash = await bcrypt.hash(req.body.password, saltRounds); // console.log(req.body); await Doctor.create({ name: req.body.name, username: req.body.username, password: <PASSWORD>, }); return res.status(200).json({ response: "success", msg: "successfully created", }); } catch (error) { // console.log(__filename, error); if (error.code === 11000) { return res.status(200).json({ msg: "doctor already exists", data: error, }); } } }; module.exports.logIn = async function (req, res) { try { let doctor = await Doctor.findOne({ username: req.body.username }); if (!doctor) { return res .status(422) .json({ response: "failed", msg: "Inavlid username or password" }); } console.log(req.body); const match = await bcrypt.compare(req.body.password, doctor.password); // console.log("match", match); if (match) return res.status(200).json({ response: "success", message: "Sign in successful, here is your token, please keep it safe!", data: { token: jwt.sign(doctor.toJSON(), process.env.JWT_KEY, { expiresIn: "36000000", }), }, }); else { return res .status(422) .json({ response: "failed", msg: "Inavlid username or password" }); } } catch (error) { console.log("********", error); return res.status(500).json({ response: "failed", err: error }); } }; <file_sep>const Patient = require("../models/patient"); module.exports.register = async function (req, res) { try { await Patient.create({ phone: req.body.phone, name: req.body.name }); return res.status(200).json({ response: "success", msg: "patient successfully added", }); } catch (error) { // console.log( err); if (error.code === 11000) { const patient = await Patient.findOne({ phone: req.body.phone }).select([ "phone", "name", "-_id", ]); return res.status(200).json({ msg: "patient already exists", patient, }); } else return res.status(500).json({ response: "failed", err: error }); } }; module.exports.createReport = async function (req, res) { try { // console.log("create report"); const id = req.params.id; // console.log(id); const report = { createdBy: req.user._id, status: req.body.status, date: new Date().toISOString(), }; // console.log(report); const patient = await Patient.findById(id); patient.reports.push(report); patient.save(); return res.status(200).json({ response: "success", msg: "successfully created report", }); } catch (error) { // console.log( err); return res.status(500).json({ response: "failed", err: error }); } }; function compare(a, b) { if (a.date < b.date) return -1; if (a.date > b.date) return 1; return 0; } module.exports.getAllReports = async function (req, res) { try { const id = req.params.id; const patient = await Patient.findById(id).populate({ path: "reports", populate: { path: "createdBy", select: "name -_id", }, }); const reports = patient.reports; reports.sort(compare); return res.status(200).json({ response: "success", name: patient.name, reports, }); // console.log(reports); } catch (error) { // console.log( err); return res.status(500).json({ response: "failed", err: error }); } };
fa60a6c05b80276712e4974d4ac6a58003ef0a7d
[ "Markdown", "JavaScript" ]
5
Markdown
shvm61/hospital-api
526fd1f41469aa8f7098edd17c507f6ff707510e
0655308a691a7b329aeb53a88c878093d42f56d2
refs/heads/master
<file_sep># BottomAppBar An example project demonstrating the usage of [Bottom App Bar](https://material.io/components/app-bars-bottom) which is a Material Component. ![bottomappbar](https://user-images.githubusercontent.com/34041050/175141748-79cb0a89-794d-4f68-92f4-10f2c233c6a5.gif) <file_sep>package com.example.bottomappbar import android.content.Context import android.widget.Toast interface IFragmentMethods { fun showToastMessage(text: String?, context: Context) { Toast.makeText(context, text, Toast.LENGTH_SHORT).show() } fun createNavItemArray(navItemList: ArrayList<Int>): ArrayList<Int> { navItemList.apply { add(R.id.nav1) add(R.id.nav2) add(R.id.nav3) add(R.id.nav4) add(R.id.nav5) add(R.id.nav6) add(R.id.nav7) add(R.id.nav8) add(R.id.nav9) add(R.id.nav10) add(R.id.nav11) add(R.id.nav12) add(R.id.nav13) add(R.id.nav14) add(R.id.nav15) } return navItemList } fun createToastTextItemArray(context: Context, toastTextItemList: ArrayList<String>): ArrayList<String> { toastTextItemList.apply { add(context.resources?.getString(R.string.holiday_click)!!) add(context.resources?.getString(R.string.furniture_click)!!) add(context.resources?.getString(R.string.work_click)!!) add(context.resources?.getString(R.string.moon_click)!!) add(context.resources?.getString(R.string.call_click)!!) add(context.resources?.getString(R.string.cloud_click)!!) add(context.resources?.getString(R.string.cut_click)!!) add(context.resources?.getString(R.string.detail_click)!!) add(context.resources?.getString(R.string.walk_click)!!) add(context.resources?.getString(R.string.drive_click)!!) add(context.resources?.getString(R.string.download_click)!!) add(context.resources?.getString(R.string.fingerprint_click)!!) add(context.resources?.getString(R.string.flight_click)!!) add(context.resources?.getString(R.string.ideas_click)!!) add(context.resources?.getString(R.string.sun_click)!!) } return toastTextItemList } }<file_sep>package com.example.bottomappbar import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import com.google.android.material.bottomsheet.BottomSheetDialogFragment import kotlinx.android.synthetic.main.fragment_bottomsheet.* class BottomNavigationDrawerFragment : BottomSheetDialogFragment(), IFragmentMethods { private var navItemList = ArrayList<Int>() private var toastTextItemList = ArrayList<String>() companion object { fun getInstance(): BottomNavigationDrawerFragment { var instance: BottomNavigationDrawerFragment? = null return if (instance == null) { instance = BottomNavigationDrawerFragment() instance } else { instance } } } override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { return inflater.inflate(R.layout.fragment_bottomsheet, container, false) } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { navItemList = createNavItemArray(navItemList) toastTextItemList = createToastTextItemArray(context!!, toastTextItemList) navigation_view.setNavigationItemSelectedListener { for (i in 0 until navItemList.size) { when (it.itemId) { navItemList[i] -> showToastMessage(toastTextItemList[i], context!!) } } return@setNavigationItemSelectedListener true } } }<file_sep>package com.example.bottomappbar import android.os.Bundle import android.view.Menu import android.view.MenuInflater import android.view.animation.AnimationUtils import androidx.appcompat.app.AppCompatActivity import com.google.android.material.bottomappbar.BottomAppBar import com.google.android.material.snackbar.Snackbar import kotlinx.android.synthetic.main.activity_main.* class MainActivity : AppCompatActivity(), IActivityMethods { private var navItemList = ArrayList<Int>() private var toastTextItemList = ArrayList<String>() override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) createNavItemArray(navItemList) createToastTextItemArray(this, toastTextItemList) //region Set menu (primary) to Bottom App Bar at first (App theme must be NoActionBar type of theme!) bottom_app_bar.replaceMenu(R.menu.bottom_app_bar_menu_primary) //endregion //region When items on Bottom App Bar menu are clicked on (both primary menu and secondary menu): bottom_app_bar.setOnMenuItemClickListener { for (i in 0 until navItemList.size) { when (it.itemId) { navItemList[i] -> showToastMessage(toastTextItemList[i], this) } } return@setOnMenuItemClickListener true } //endregion //region When 3 straight line menu item at the left is clicked on: bottom_app_bar.setNavigationOnClickListener { openNavigationDrawer(supportFragmentManager) } //endregion //region When fab is clicked on: fab.setOnClickListener { //Change background color: coordinatorLayout.changeBackgroundColor() //Show a snack bar: Snackbar.make(fab, getString(R.string.snack_bar_shown), Snackbar.LENGTH_SHORT) .setAction(getString(R.string.ok)) { //Do what you want as snackBar action. }.show() } //endregion //region When toggle button is clicked, a slide animation on Bottom App Bar is run between primary menu and secondary menu: toggleButton.setOnCheckedChangeListener { _, isChecked -> val slideRtl = AnimationUtils.loadAnimation(applicationContext, R.anim.slide_rtl) if (isChecked) { slideAction( this, fab, bottom_app_bar, null, slideRtl, BottomAppBar.FAB_ALIGNMENT_MODE_END, R.menu.bottom_app_bar_menu_secondary, R.drawable.ic_reply_white_24dp ) } else { slideAction( this, fab, bottom_app_bar, R.drawable.ic_menu_white_24dp, slideRtl, BottomAppBar.FAB_ALIGNMENT_MODE_CENTER, R.menu.bottom_app_bar_menu_primary, R.drawable.ic_add_white_24dp ) } } //endregion } override fun onCreateOptionsMenu(menu: Menu?): Boolean { val inflater = MenuInflater(this) inflater.inflate(R.menu.bottom_app_bar_menu_primary, menu) /*** ** If you want to add an icon in front of your menu items: }***/ /*if (menu is MenuBuilder) { menu.setOptionalIconsVisible(true) }*/ return true } //endregion } <file_sep>package com.example.bottomappbar import android.content.Context import android.graphics.Color import android.view.View import android.view.animation.Animation import android.widget.Toast import androidx.core.content.ContextCompat import androidx.fragment.app.FragmentManager import com.google.android.material.bottomappbar.BottomAppBar import com.google.android.material.floatingactionbutton.FloatingActionButton import java.util.* interface IActivityMethods { fun showToastMessage(text: String?, context: Context) { Toast.makeText(context, text, Toast.LENGTH_SHORT).show() } fun createNavItemArray(navItemList: ArrayList<Int>): ArrayList<Int> { navItemList.apply { add(R.id.app_bar_fav) add(R.id.app_bar_search) add(R.id.app_bar_settings) add(R.id.app_bar_mail) add(R.id.app_bar_delete) add(R.id.app_bar_archive) } return navItemList } fun createToastTextItemArray(context: Context, toastTextItemList: ArrayList<String>): ArrayList<String> { toastTextItemList.apply { add(context.resources?.getString(R.string.favorites_click)!!) add(context.resources?.getString(R.string.search_click)!!) add(context.resources?.getString(R.string.settings_click)!!) add(context.resources?.getString(R.string.mail_click)!!) add(context.resources?.getString(R.string.delete_click)!!) add(context.resources?.getString(R.string.archive_click)!!) } return toastTextItemList } fun openNavigationDrawer(fm: FragmentManager) { //Create a Singleton object of BottomNavigationDrawerFragment: val bottomNavigationDrawerFragment = BottomNavigationDrawerFragment.getInstance() bottomNavigationDrawerFragment.show(fm, bottomNavigationDrawerFragment.tag) } fun View.changeBackgroundColor() { val rnd = Random() val color: Int = Color.argb(255, rnd.nextInt(256), rnd.nextInt(256), rnd.nextInt(256)) this.setBackgroundColor(color) } //region Slide animation method for Bottom App Bar fun slideAction( context: Context, fab: FloatingActionButton, bottomAppBar: BottomAppBar, navigationIcon: Int?, anim: Animation, alignmentMode: Int, menu: Int, fabDrawable: Int ) { fab.startAnimation(anim) if (navigationIcon == null) { // If you do not want to show navigation drawer icon (3 straight line at the left), hide it: bottomAppBar.navigationIcon = null } else { bottomAppBar.navigationIcon = ContextCompat.getDrawable(context, navigationIcon) } bottomAppBar.fabAlignmentMode = alignmentMode // Replace the action menu bottomAppBar.replaceMenu(menu) // Change FAB icon fab.setImageDrawable(ContextCompat.getDrawable(context, fabDrawable)) } //endregion }
74711e66dd3077dea3c9ea356c95538910d40b31
[ "Markdown", "Kotlin" ]
5
Markdown
cyeksan/BottomAppBar
e9566c3a8fe39115ee4e02587cd5b21c5bad9b9c
404a39a216c5c05e0a4c57a07f37894376edf835
refs/heads/master
<repo_name>MarlonMazzine/controle-das-rotinas-do-pre-natal<file_sep>/ControleRotinasDoPreNatal/src/br/com/marlonenathan/telas/TelaCadastraPaciente.java /* * 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 br.com.marlonenathan.telas; import java.awt.Color; import javax.swing.GroupLayout; import javax.swing.GroupLayout.Alignment; import javax.swing.JOptionPane; import javax.swing.LayoutStyle.ComponentPlacement; import br.com.marlonenathan.model.bean.Paciente; import br.com.marlonenathan.model.dao.PessoaDAO; /** * * @author marlonmazzine */ public class TelaCadastraPaciente extends javax.swing.JFrame { /** * */ private static final long serialVersionUID = 1L; /** * Creates new form TelaCadastraFuncionario */ public TelaCadastraPaciente() { 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. */ // <editor-fold defaultstate="collapsed" desc="Generated // Code">//GEN-BEGIN:initComponents private void initComponents() { jPanel1 = new javax.swing.JPanel(); jLabel5 = new javax.swing.JLabel(); jPanel2 = new javax.swing.JPanel(); txtNome = new javax.swing.JTextField(); jLabel1 = new javax.swing.JLabel(); jLabel2 = new javax.swing.JLabel(); jLabel3 = new javax.swing.JLabel(); jLabel4 = new javax.swing.JLabel(); btnSalvar = new javax.swing.JButton(); btnSair = new javax.swing.JButton(); txtSUS = new javax.swing.JFormattedTextField(); txtTelefone = new javax.swing.JFormattedTextField(); txtNascimento = new javax.swing.JFormattedTextField(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); setTitle("Novo cadastro"); setBackground(new java.awt.Color(8, 77, 110)); setMaximumSize(new java.awt.Dimension(600, 680)); setMinimumSize(new java.awt.Dimension(600, 680)); setPreferredSize(new java.awt.Dimension(600, 680)); getContentPane().setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout()); jPanel1.setBackground(new java.awt.Color(0, 102, 204)); jPanel1.setPreferredSize(new java.awt.Dimension(342, 161)); jLabel5.setFont(new java.awt.Font("FreeMono", 1, 36)); // NOI18N jLabel5.setForeground(new java.awt.Color(255, 255, 255)); jLabel5.setText("Novo cadastro"); javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1); jPanel1.setLayout(jPanel1Layout); jPanel1Layout.setHorizontalGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup().addGap(45, 45, 45).addComponent(jLabel5) .addContainerGap(269, Short.MAX_VALUE))); jPanel1Layout.setVerticalGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup().addGap(59, 59, 59).addComponent(jLabel5) .addContainerGap(65, Short.MAX_VALUE))); getContentPane().add(jPanel1, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 0, 600, -1)); jPanel2.setBackground(new java.awt.Color(8, 77, 110)); jPanel2.setMaximumSize(new java.awt.Dimension(600, 530)); jPanel2.setMinimumSize(new java.awt.Dimension(600, 530)); jPanel2.setName(""); // NOI18N txtNome.setBackground(new java.awt.Color(204, 204, 204)); txtNome.setFont(new java.awt.Font("Dialog", 1, 16)); // NOI18N txtNome.setForeground(new java.awt.Color(51, 51, 51)); jLabel1.setFont(new java.awt.Font("Dialog", 1, 16)); // NOI18N jLabel1.setForeground(new java.awt.Color(255, 255, 255)); jLabel1.setText("Nome:"); jLabel2.setFont(new java.awt.Font("Dialog", 1, 16)); // NOI18N jLabel2.setForeground(new java.awt.Color(255, 255, 255)); jLabel2.setText("SUS:"); jLabel3.setFont(new java.awt.Font("Dialog", 1, 16)); // NOI18N jLabel3.setForeground(new java.awt.Color(255, 255, 255)); jLabel3.setText("Telefone:"); jLabel4.setFont(new java.awt.Font("Dialog", 1, 16)); // NOI18N jLabel4.setForeground(new java.awt.Color(255, 255, 255)); jLabel4.setText("Nascimento:"); btnSalvar.setBackground(new java.awt.Color(35, 142, 35)); btnSalvar.setIcon( new javax.swing.ImageIcon(getClass().getResource("/br/com/marlonenathan/imagens/checkmark.png"))); // NOI18N btnSalvar.setBorderPainted(false); btnSalvar.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR)); btnSalvar.setFocusPainted(false); btnSalvar.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnSalvarActionPerformed(evt); } }); btnSair.setBackground(new java.awt.Color(204, 0, 51)); btnSair.setIcon(new javax.swing.ImageIcon(getClass().getResource("/br/com/marlonenathan/imagens/delete.png"))); // NOI18N btnSair.setBorderPainted(false); btnSair.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR)); btnSair.setFocusPainted(false); btnSair.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnSairActionPerformed(evt); } }); txtSUS.setBackground(new java.awt.Color(204, 204, 204)); txtSUS.setForeground(new java.awt.Color(51, 51, 51)); try { txtSUS.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory( new javax.swing.text.MaskFormatter("### #### #### ####"))); } catch (java.text.ParseException ex) { ex.printStackTrace(); } txtSUS.setCaretColor(new java.awt.Color(51, 51, 51)); txtSUS.setFont(new java.awt.Font("Dialog", 1, 16)); // NOI18N txtTelefone.setBackground(new java.awt.Color(204, 204, 204)); txtTelefone.setForeground(new java.awt.Color(51, 51, 51)); try { txtTelefone.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory( new javax.swing.text.MaskFormatter("(##) # ####-####"))); } catch (java.text.ParseException ex) { ex.printStackTrace(); } txtTelefone.setFont(new java.awt.Font("Dialog", 1, 16)); // NOI18N txtNascimento.setBackground(new java.awt.Color(204, 204, 204)); txtNascimento.setForeground(new java.awt.Color(51, 51, 51)); try { txtNascimento.setFormatterFactory( new javax.swing.text.DefaultFormatterFactory(new javax.swing.text.MaskFormatter("##/##/####"))); } catch (java.text.ParseException ex) { ex.printStackTrace(); } txtNascimento.setFont(new java.awt.Font("Dialog", 1, 16)); // NOI18N javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2); jPanel2Layout.setHorizontalGroup(jPanel2Layout.createParallelGroup(Alignment.LEADING).addGroup(jPanel2Layout .createSequentialGroup().addGap(0, 36, Short.MAX_VALUE) .addGroup(jPanel2Layout.createParallelGroup(Alignment.LEADING) .addGroup(jPanel2Layout.createSequentialGroup().addGap(53).addComponent(jLabel1) .addPreferredGap(ComponentPlacement.UNRELATED) .addComponent(txtNome, GroupLayout.PREFERRED_SIZE, 400, GroupLayout.PREFERRED_SIZE)) .addGroup(jPanel2Layout.createSequentialGroup().addComponent(jLabel4).addGap(18).addComponent( txtNascimento, GroupLayout.PREFERRED_SIZE, 400, GroupLayout.PREFERRED_SIZE)) .addGroup(jPanel2Layout.createSequentialGroup().addGap(386) .addComponent(btnSalvar, GroupLayout.PREFERRED_SIZE, 62, GroupLayout.PREFERRED_SIZE) .addGap(18) .addComponent(btnSair, GroupLayout.PREFERRED_SIZE, 62, GroupLayout.PREFERRED_SIZE)) .addGroup(jPanel2Layout.createSequentialGroup() .addGroup(jPanel2Layout.createParallelGroup(Alignment.LEADING) .addGroup( jPanel2Layout.createSequentialGroup().addGap(27).addComponent(jLabel3)) .addGroup( jPanel2Layout.createSequentialGroup().addGap(64).addComponent(jLabel2))) .addGap(18) .addGroup(jPanel2Layout.createParallelGroup(Alignment.LEADING) .addComponent(txtSUS, GroupLayout.PREFERRED_SIZE, 400, GroupLayout.PREFERRED_SIZE) .addComponent(txtTelefone, GroupLayout.PREFERRED_SIZE, 400, GroupLayout.PREFERRED_SIZE)))) .addGap(0, 36, Short.MAX_VALUE))); jPanel2Layout .setVerticalGroup(jPanel2Layout.createParallelGroup(Alignment.LEADING) .addGroup(jPanel2Layout.createSequentialGroup().addContainerGap(47, Short.MAX_VALUE) .addGroup(jPanel2Layout.createParallelGroup(Alignment.BASELINE) .addComponent(txtNome, GroupLayout.PREFERRED_SIZE, 50, GroupLayout.PREFERRED_SIZE) .addComponent(jLabel1)) .addGap(18) .addGroup(jPanel2Layout .createParallelGroup(Alignment.BASELINE).addComponent(jLabel2).addComponent( txtSUS, GroupLayout.PREFERRED_SIZE, 50, GroupLayout.PREFERRED_SIZE)) .addGap(18) .addGroup(jPanel2Layout.createParallelGroup(Alignment.LEADING) .addGroup( jPanel2Layout.createSequentialGroup().addGap(15).addComponent(jLabel3)) .addComponent(txtTelefone, GroupLayout.PREFERRED_SIZE, 50, GroupLayout.PREFERRED_SIZE)) .addGap(18) .addGroup(jPanel2Layout.createParallelGroup(Alignment.LEADING) .addGroup( jPanel2Layout.createSequentialGroup().addGap(15).addComponent(jLabel4)) .addComponent(txtNascimento, GroupLayout.PREFERRED_SIZE, 50, GroupLayout.PREFERRED_SIZE)) .addGap(154) .addGroup(jPanel2Layout.createParallelGroup(Alignment.LEADING) .addComponent(btnSalvar, GroupLayout.PREFERRED_SIZE, 48, GroupLayout.PREFERRED_SIZE) .addComponent(btnSair, GroupLayout.PREFERRED_SIZE, 48, GroupLayout.PREFERRED_SIZE)) .addGap(0, 32, Short.MAX_VALUE))); jPanel2.setLayout(jPanel2Layout); txtNascimento.getAccessibleContext().setAccessibleDescription(""); getContentPane().add(jPanel2, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 160, 600, 520)); pack(); setLocationRelativeTo(null); }// </editor-fold>//GEN-END:initComponents private void btnSalvarActionPerformed(java.awt.event.ActionEvent evt) {// GEN-FIRST:event_btnSalvarActionPerformed Paciente p = new Paciente(); PessoaDAO dao = new PessoaDAO(); p.setNome(txtNome.getText()); p.setDocumento(txtSUS.getText()); p.setTelefone(txtTelefone.getText()); p.setNascimento(txtNascimento.getText()); if (p.getNome().length() == 0 || p.getDocumento().replaceAll("[^0-9]", "").length() == 0 || p.getTelefone().replaceAll("[^0-9]", "").length() == 0 || p.getNascimento().replaceAll("[^0-9]", "").length() == 0) { JOptionPane.showMessageDialog(null, "Todos os campos são de preencheimento obrigatório"); } else { dao.createPaciente(p); new TelaCadastroDePacientes().setVisible(true); this.dispose(); } }// GEN-LAST:event_btnSalvarActionPerformed private void btnSairActionPerformed(java.awt.event.ActionEvent evt) {// GEN-FIRST:event_btnSairActionPerformed new TelaCadastroDePacientes().setVisible(true); this.dispose(); }// GEN-LAST:event_btnSairActionPerformed /** * @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 ("".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(TelaCadastraPaciente.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(TelaCadastraPaciente.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(TelaCadastraPaciente.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(TelaCadastraPaciente.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } // </editor-fold> /* Create and display the form */ java.awt.EventQueue.invokeLater(() -> { TelaCadastraPaciente telaCadastraFuncionario = new TelaCadastraPaciente(); telaCadastraFuncionario.setVisible(true); telaCadastraFuncionario.getContentPane().setBackground(new Color(8, 77, 110)); }); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton btnSair; private javax.swing.JButton btnSalvar; private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel2; private javax.swing.JLabel jLabel3; private javax.swing.JLabel jLabel4; private javax.swing.JLabel jLabel5; private javax.swing.JPanel jPanel1; private javax.swing.JPanel jPanel2; private javax.swing.JFormattedTextField txtSUS; private javax.swing.JFormattedTextField txtNascimento; private javax.swing.JTextField txtNome; private javax.swing.JFormattedTextField txtTelefone; // End of variables declaration//GEN-END:variables } <file_sep>/ControleRotinasDoPreNatal/src/br/com/marlonenathan/telas/TelaCadastroDeFuncionarios.java /* * 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 br.com.marlonenathan.telas; import java.awt.Color; import javax.swing.JFrame; import javax.swing.JOptionPane; import javax.swing.table.DefaultTableModel; import javax.swing.table.TableModel; import javax.swing.table.TableRowSorter; import br.com.marlonenathan.model.bean.Funcionario; import br.com.marlonenathan.model.dao.PessoaDAO; /** * * @author marlonmazzine */ public final class TelaCadastroDeFuncionarios extends javax.swing.JFrame { /** * */ private static final long serialVersionUID = 1L; /** * Creates new form TelaCadastroDeFuncionarios */ public TelaCadastroDeFuncionarios() { initComponents(); DefaultTableModel modelo = (DefaultTableModel) tbFuncionario.getModel(); tbFuncionario.setRowSorter(new TableRowSorter<DefaultTableModel>(modelo)); readTable(); } TelaEditarFuncionario telaEditFunc = new TelaEditarFuncionario(); Funcionario f = new Funcionario(); /** * 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. */ // <editor-fold defaultstate="collapsed" desc="Generated // Code">//GEN-BEGIN:initComponents private void initComponents() { jPanel2 = new javax.swing.JPanel(); txtPesquisaPeloNome = new javax.swing.JTextField(); btnPesquisar = new javax.swing.JButton(); jScrollPane1 = new javax.swing.JScrollPane(); tbFuncionario = new javax.swing.JTable(); btnIncluir = new javax.swing.JButton(); btnEditar = new javax.swing.JButton(); btnExcluir = new javax.swing.JButton(); btnVoltar = new javax.swing.JButton(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); setTitle("Cadastros de funcionários"); setBackground(new java.awt.Color(8, 77, 110)); setMinimumSize(new java.awt.Dimension(1280, 720)); setResizable(false); jPanel2.setBackground(new java.awt.Color(8, 77, 110)); jPanel2.setMaximumSize(new java.awt.Dimension(1280, 720)); jPanel2.setMinimumSize(new java.awt.Dimension(1280, 720)); jPanel2.setPreferredSize(new java.awt.Dimension(1280, 720)); txtPesquisaPeloNome.setFont(new java.awt.Font("Dialog", 0, 16)); // NOI18N txtPesquisaPeloNome.setText("Nome do funcionário"); txtPesquisaPeloNome.addFocusListener(new java.awt.event.FocusAdapter() { public void focusGained(java.awt.event.FocusEvent evt) { txtPesquisaPeloNomeFocusGained(evt); } public void focusLost(java.awt.event.FocusEvent evt) { txtPesquisaPeloNomeFocusLost(evt); } }); btnPesquisar.setBackground(new java.awt.Color(153, 153, 153)); btnPesquisar.setFont(new java.awt.Font("Dialog", 1, 16)); // NOI18N btnPesquisar.setIcon( new javax.swing.ImageIcon(getClass().getResource("/br/com/marlonenathan/imagens/pesquisar.png"))); // NOI18N btnPesquisar.setBorderPainted(false); btnPesquisar.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR)); btnPesquisar.setFocusPainted(false); btnPesquisar.setMaximumSize(new java.awt.Dimension(79, 40)); btnPesquisar.setMinimumSize(new java.awt.Dimension(79, 40)); btnPesquisar.setPreferredSize(new java.awt.Dimension(79, 40)); btnPesquisar.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnPesquisarActionPerformed(evt); } }); tbFuncionario.setAutoCreateRowSorter(true); tbFuncionario.setFont(new java.awt.Font("Dialog", 0, 18)); // NOI18N tbFuncionario.setModel( new javax.swing.table.DefaultTableModel(new Object[][] { { null, null, null, null, null, null } }, new String[] { "Nome", "CRM", "Telefone", "Nascimento", "usuario", "senha" }) { /** * */ private static final long serialVersionUID = 1L; boolean[] canEdit = new boolean[] { false, false, false, false, false, false }; public boolean isCellEditable(int rowIndex, int columnIndex) { return canEdit[columnIndex]; } }); tbFuncionario.setRowHeight(30); jScrollPane1.setViewportView(tbFuncionario); tbFuncionario.getColumnModel().getSelectionModel() .setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION); if (tbFuncionario.getColumnModel().getColumnCount() > 0) { tbFuncionario.getColumnModel().getColumn(1).setMinWidth(150); tbFuncionario.getColumnModel().getColumn(1).setPreferredWidth(150); tbFuncionario.getColumnModel().getColumn(1).setMaxWidth(150); tbFuncionario.getColumnModel().getColumn(2).setMinWidth(170); tbFuncionario.getColumnModel().getColumn(2).setPreferredWidth(170); tbFuncionario.getColumnModel().getColumn(2).setMaxWidth(170); tbFuncionario.getColumnModel().getColumn(3).setMinWidth(150); tbFuncionario.getColumnModel().getColumn(3).setPreferredWidth(150); tbFuncionario.getColumnModel().getColumn(3).setMaxWidth(150); tbFuncionario.getColumnModel().getColumn(4).setMinWidth(1); tbFuncionario.getColumnModel().getColumn(4).setPreferredWidth(1); tbFuncionario.getColumnModel().getColumn(4).setMaxWidth(1); tbFuncionario.getColumnModel().getColumn(5).setMinWidth(1); tbFuncionario.getColumnModel().getColumn(5).setPreferredWidth(1); tbFuncionario.getColumnModel().getColumn(5).setMaxWidth(1); } btnIncluir.setBackground(new java.awt.Color(0, 153, 102)); btnIncluir.setFont(new java.awt.Font("Dialog", 1, 18)); // NOI18N btnIncluir.setForeground(new java.awt.Color(255, 255, 255)); btnIncluir.setIcon( new javax.swing.ImageIcon(getClass().getResource("/br/com/marlonenathan/imagens/adicionarPessoa.png"))); // NOI18N btnIncluir.setText(" Incluir"); btnIncluir.setToolTipText(""); btnIncluir.setBorderPainted(false); btnIncluir.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR)); btnIncluir.setFocusCycleRoot(true); btnIncluir.setFocusPainted(false); btnIncluir.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnIncluirActionPerformed(evt); } }); btnEditar.setBackground(new java.awt.Color(204, 204, 0)); btnEditar.setFont(new java.awt.Font("Dialog", 1, 18)); // NOI18N btnEditar.setForeground(new java.awt.Color(255, 255, 255)); btnEditar .setIcon(new javax.swing.ImageIcon(getClass().getResource("/br/com/marlonenathan/imagens/editar.png"))); // NOI18N btnEditar.setText(" Editar"); btnEditar.setToolTipText(""); btnEditar.setBorderPainted(false); btnEditar.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR)); btnEditar.setFocusCycleRoot(true); btnEditar.setFocusPainted(false); btnEditar.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { btnEditarMouseClicked(evt); } }); btnExcluir.setBackground(new java.awt.Color(204, 51, 0)); btnExcluir.setFont(new java.awt.Font("Dialog", 1, 18)); // NOI18N btnExcluir.setForeground(new java.awt.Color(255, 255, 255)); btnExcluir .setIcon(new javax.swing.ImageIcon(getClass().getResource("/br/com/marlonenathan/imagens/romver.png"))); // NOI18N btnExcluir.setText(" Excluir"); btnExcluir.setToolTipText(""); btnExcluir.setBorderPainted(false); btnExcluir.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR)); btnExcluir.setFocusCycleRoot(true); btnExcluir.setFocusPainted(false); btnExcluir.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnExcluirActionPerformed(evt); } }); btnVoltar.setBackground(new java.awt.Color(255, 153, 0)); btnVoltar.setFont(new java.awt.Font("Dialog", 1, 18)); // NOI18N btnVoltar.setForeground(new java.awt.Color(255, 255, 255)); btnVoltar .setIcon(new javax.swing.ImageIcon(getClass().getResource("/br/com/marlonenathan/imagens/voltar.png"))); // NOI18N btnVoltar.setText(" Voltar"); btnVoltar.setToolTipText(""); btnVoltar.setBorderPainted(false); btnVoltar.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR)); btnVoltar.setFocusCycleRoot(true); btnVoltar.setFocusPainted(false); btnVoltar.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnVoltarActionPerformed(evt); } }); javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2); jPanel2.setLayout(jPanel2Layout); jPanel2Layout.setHorizontalGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel2Layout.createSequentialGroup() .addContainerGap(38, Short.MAX_VALUE) .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addGroup(jPanel2Layout.createSequentialGroup() .addComponent(txtPesquisaPeloNome, javax.swing.GroupLayout.PREFERRED_SIZE, 468, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(18, 18, 18).addComponent(btnPesquisar, javax.swing.GroupLayout.PREFERRED_SIZE, 79, javax.swing.GroupLayout.PREFERRED_SIZE)) .addComponent(jScrollPane1) .addGroup(jPanel2Layout.createSequentialGroup() .addComponent(btnVoltar, javax.swing.GroupLayout.PREFERRED_SIZE, 145, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 597, Short.MAX_VALUE) .addComponent(btnIncluir, javax.swing.GroupLayout.PREFERRED_SIZE, 145, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(18, 18, 18) .addComponent(btnEditar, javax.swing.GroupLayout.PREFERRED_SIZE, 145, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(18, 18, 18).addComponent(btnExcluir, javax.swing.GroupLayout.PREFERRED_SIZE, 145, javax.swing.GroupLayout.PREFERRED_SIZE))) .addGap(29, 29, 29))); jPanel2Layout.setVerticalGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel2Layout.createSequentialGroup().addGap(36, 36, 36) .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(txtPesquisaPeloNome, javax.swing.GroupLayout.PREFERRED_SIZE, 40, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(btnPesquisar, javax.swing.GroupLayout.PREFERRED_SIZE, 40, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(18, 18, 18).addComponent(jScrollPane1).addGap(18, 18, 18) .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(btnVoltar, javax.swing.GroupLayout.PREFERRED_SIZE, 70, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(btnIncluir, javax.swing.GroupLayout.PREFERRED_SIZE, 70, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(btnEditar, javax.swing.GroupLayout.PREFERRED_SIZE, 70, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(btnExcluir, javax.swing.GroupLayout.PREFERRED_SIZE, 70, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(46, 46, 46))); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(0, 0, Short.MAX_VALUE))); layout.setVerticalGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING).addComponent( jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)); pack(); setLocationRelativeTo(null); }// </editor-fold>//GEN-END:initComponents String pesquisaPeloNome; private void txtPesquisaPeloNomeFocusGained(java.awt.event.FocusEvent evt) {// GEN-FIRST:event_txtPesquisaPeloNomeFocusGained pesquisaPeloNome = txtPesquisaPeloNome.getText(); if (pesquisaPeloNome.length() > 0 && !txtPesquisaPeloNome.getText().contains("Nome do funcionário")) { pesquisaPeloNome = txtPesquisaPeloNome.getText(); txtPesquisaPeloNome.setText(pesquisaPeloNome); } else { txtPesquisaPeloNome.setText(""); } }// GEN-LAST:event_txtPesquisaPeloNomeFocusGained private void txtPesquisaPeloNomeFocusLost(java.awt.event.FocusEvent evt) {// GEN-FIRST:event_txtPesquisaPeloNomeFocusLost pesquisaPeloNome = txtPesquisaPeloNome.getText(); if (pesquisaPeloNome.length() == 0 || txtPesquisaPeloNome.getText().contains("Nome do funcionário")) { txtPesquisaPeloNome.setText("Nome do funcionário"); } }// GEN-LAST:event_txtPesquisaPeloNomeFocusLost private void btnIncluirActionPerformed(java.awt.event.ActionEvent evt) {// GEN-FIRST:event_jButton2ActionPerformed new TelaCadastraFuncionario().setVisible(true); this.dispose(); }// GEN-LAST:event_jButton2ActionPerformed private void btnPesquisarActionPerformed(java.awt.event.ActionEvent evt) {// GEN-FIRST:event_btnPesquisarActionPerformed readTablePeloNome(txtPesquisaPeloNome.getText()); }// GEN-LAST:event_btnPesquisarActionPerformed private void btnVoltarActionPerformed(java.awt.event.ActionEvent evt) {// GEN-FIRST:event_btnVoltarActionPerformed new TelaEscolhaChefe().setVisible(true); this.dispose(); }// GEN-LAST:event_btnVoltarActionPerformed private void btnExcluirActionPerformed(java.awt.event.ActionEvent evt) {// GEN-FIRST:event_btnExcluirActionPerformed int resposta = JOptionPane.showConfirmDialog(null, "Tem certeza de que deseja excluir?", "Confirmar exlusão", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE); if (resposta == JOptionPane.YES_OPTION) { if (tbFuncionario.getSelectedRow() != -1) { Funcionario f = new Funcionario(); PessoaDAO pdao = new PessoaDAO(); f.setDocumento(tbFuncionario.getValueAt(tbFuncionario.getSelectedRow(), 1).toString()); pdao.deleteFuncionario(f); readTable(); } else { JOptionPane.showMessageDialog(null, "Selecione um produto para excluir"); } } }// GEN-LAST:event_btnExcluirActionPerformed private void btnEditarMouseClicked(java.awt.event.MouseEvent evt) {// GEN-FIRST:event_btnEditarMouseClicked if (tbFuncionario.getSelectedRow() != -1) { int index = tbFuncionario.getSelectedRow(); TableModel tabela = tbFuncionario.getModel(); telaEditFunc.setVisible(true); telaEditFunc.pack(); telaEditFunc.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); telaEditFunc.txtNome.setText(tabela.getValueAt(index, 0).toString()); telaEditFunc.txtCRM.setText(tabela.getValueAt(index, 1).toString()); telaEditFunc.txtTelefone.setText(tabela.getValueAt(index, 2).toString()); telaEditFunc.txtNascimento.setText(tabela.getValueAt(index, 3).toString()); readTable(); this.dispose(); } else { JOptionPane.showMessageDialog(null, "Selecione um funcionário para editar"); } }// GEN-LAST:event_btnEditarMouseClicked public void readTable() { DefaultTableModel modelo = (DefaultTableModel) tbFuncionario.getModel(); modelo.setNumRows(0); PessoaDAO pDao = new PessoaDAO(); for (Funcionario f : pDao.readFuncionario()) { modelo.addRow(new Object[] { f.getNome(), f.getDocumento(), f.getTelefone(), f.getNascimento(), f.getUsuario(), f.getSenha() }); } } public void readTablePeloNome(String nome) { DefaultTableModel modelo = (DefaultTableModel) tbFuncionario.getModel(); modelo.setNumRows(0); PessoaDAO pDao = new PessoaDAO(); for (Funcionario f : pDao.buscarFuncionario(nome)) { modelo.addRow(new Object[] { f.getNome(), f.getDocumento(), f.getTelefone(), f.getNascimento(), f.getUsuario(), f.getSenha() }); } } /** * @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 ("".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(TelaCadastroDeFuncionarios.class.getName()) .log(java.util.logging.Level.SEVERE, null, ex); } // </editor-fold> // </editor-fold> /* Create and display the form */ java.awt.EventQueue.invokeLater(() -> { TelaCadastroDeFuncionarios telaCadastroDeFuncionarios = new TelaCadastroDeFuncionarios(); telaCadastroDeFuncionarios.setVisible(true); telaCadastroDeFuncionarios.getContentPane().setBackground(new Color(8, 77, 110)); }); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton btnEditar; private javax.swing.JButton btnExcluir; private javax.swing.JButton btnPesquisar; private javax.swing.JButton btnVoltar; private javax.swing.JButton btnIncluir; private javax.swing.JPanel jPanel2; private javax.swing.JScrollPane jScrollPane1; private javax.swing.JTable tbFuncionario; private javax.swing.JTextField txtPesquisaPeloNome; // End of variables declaration//GEN-END:variables } <file_sep>/ControleRotinasDoPreNatal/src/br/com/marlonenathan/telas/TelaListaDeAtendimentos.java package br.com.marlonenathan.telas; import java.awt.Color; import java.awt.Cursor; import java.awt.Font; import java.awt.Rectangle; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.time.LocalDate; import java.time.format.DateTimeFormatter; import javax.swing.GroupLayout; import javax.swing.GroupLayout.Alignment; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JOptionPane; import javax.swing.JScrollPane; import javax.swing.JTable; import javax.swing.LayoutStyle.ComponentPlacement; import javax.swing.table.DefaultTableModel; import javax.swing.table.TableModel; import javax.swing.table.TableRowSorter; import br.com.marlonenathan.model.bean.Atendimento; import br.com.marlonenathan.model.dao.AtendimentoDAO; /** * @author marlonmazzine */ public final class TelaListaDeAtendimentos extends javax.swing.JFrame { DefaultTableModel modelo; private static final long serialVersionUID = 1L; public TelaListaDeAtendimentos() { initComponents(); modelo = (DefaultTableModel) tbAtendimentos.getModel(); tbAtendimentos.setRowSorter(new TableRowSorter<DefaultTableModel>(modelo)); readTable(); } TelaAtendimento telaAtendimento = new TelaAtendimento(); Atendimento a = new Atendimento(); public void initComponents() { jPanel2 = new javax.swing.JPanel(); txtPesquisaPeloNome = new javax.swing.JTextField(); btnPesquisar = new javax.swing.JButton(); tbAtendimentos = new javax.swing.JTable(); JScrollPane jScrollPane1 = new JScrollPane(tbAtendimentos, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS); tbAtendimentos.setAutoResizeMode(JTable.AUTO_RESIZE_OFF); btnVoltar = new javax.swing.JButton(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); setTitle("Lista de atendimentos"); setBackground(new java.awt.Color(8, 77, 110)); setMinimumSize(new java.awt.Dimension(1280, 720)); setResizable(false); jPanel2.setBackground(new java.awt.Color(8, 77, 110)); jPanel2.setMaximumSize(new java.awt.Dimension(1280, 720)); jPanel2.setMinimumSize(new java.awt.Dimension(1280, 720)); jPanel2.setPreferredSize(new java.awt.Dimension(1280, 720)); txtPesquisaPeloNome.setFont(new java.awt.Font("Dialog", 0, 16)); txtPesquisaPeloNome.setText("Nome do paciente"); txtPesquisaPeloNome.addFocusListener(new java.awt.event.FocusAdapter() { public void focusGained(java.awt.event.FocusEvent evt) { txtPesquisaPeloNomeFocusGained(evt); } public void focusLost(java.awt.event.FocusEvent evt) { txtPesquisaPeloNomeFocusLost(evt); } }); btnPesquisar.setBackground(new java.awt.Color(153, 153, 153)); btnPesquisar.setFont(new java.awt.Font("Dialog", 1, 16)); btnPesquisar.setIcon( new javax.swing.ImageIcon(getClass().getResource("/br/com/marlonenathan/imagens/pesquisar.png"))); btnPesquisar.setBorderPainted(false); btnPesquisar.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR)); btnPesquisar.setFocusPainted(false); btnPesquisar.setMaximumSize(new java.awt.Dimension(79, 40)); btnPesquisar.setMinimumSize(new java.awt.Dimension(79, 40)); btnPesquisar.setPreferredSize(new java.awt.Dimension(79, 40)); btnPesquisar.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnPesquisarActionPerformed(evt); } }); tbAtendimentos.setAutoCreateRowSorter(true); tbAtendimentos.setFont(new java.awt.Font("Dialog", 0, 18)); // NOI18N tbAtendimentos.setModel(new DefaultTableModel( new Object[][] { { null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null }, }, new String[] { "Nome", "SUS", "Data", "Atendimento", "Filhos", "Gravidez", "Partos", "Abortos", "Doença prévia", "Ult. preventivo", "BHCG", "USG dias", "USG semanas", "Ult. USG", "Ult. menstruação", "Obs." })); tbAtendimentos.setColumnSelectionAllowed(true); tbAtendimentos.setRowHeight(30); if (tbAtendimentos.getColumnModel().getColumnCount() >= 0) { // nome tbAtendimentos.getColumnModel().getColumn(0).setMinWidth(300); tbAtendimentos.getColumnModel().getColumn(0).setPreferredWidth(300); tbAtendimentos.getColumnModel().getColumn(0).setMaxWidth(300); // SUS tbAtendimentos.getColumnModel().getColumn(1).setMinWidth(200); tbAtendimentos.getColumnModel().getColumn(1).setPreferredWidth(200); tbAtendimentos.getColumnModel().getColumn(1).setMaxWidth(200); // data tbAtendimentos.getColumnModel().getColumn(2).setMinWidth(110); tbAtendimentos.getColumnModel().getColumn(2).setPreferredWidth(110); tbAtendimentos.getColumnModel().getColumn(2).setMaxWidth(110); // atendimentos tbAtendimentos.getColumnModel().getColumn(3).setMinWidth(90); tbAtendimentos.getColumnModel().getColumn(3).setPreferredWidth(90); tbAtendimentos.getColumnModel().getColumn(3).setMaxWidth(90); // filhos tbAtendimentos.getColumnModel().getColumn(4).setMinWidth(50); tbAtendimentos.getColumnModel().getColumn(4).setPreferredWidth(50); tbAtendimentos.getColumnModel().getColumn(4).setMaxWidth(50); // gravidez tbAtendimentos.getColumnModel().getColumn(5).setMinWidth(60); tbAtendimentos.getColumnModel().getColumn(5).setPreferredWidth(60); tbAtendimentos.getColumnModel().getColumn(5).setMaxWidth(60); // partos tbAtendimentos.getColumnModel().getColumn(6).setMinWidth(50); tbAtendimentos.getColumnModel().getColumn(6).setPreferredWidth(50); tbAtendimentos.getColumnModel().getColumn(6).setMaxWidth(50); // abortos tbAtendimentos.getColumnModel().getColumn(7).setMinWidth(60); tbAtendimentos.getColumnModel().getColumn(7).setPreferredWidth(60); tbAtendimentos.getColumnModel().getColumn(7).setMaxWidth(60); // doença prévia tbAtendimentos.getColumnModel().getColumn(8).setMinWidth(100); tbAtendimentos.getColumnModel().getColumn(8).setPreferredWidth(100); tbAtendimentos.getColumnModel().getColumn(8).setMaxWidth(100); // ultimo prevetivo tbAtendimentos.getColumnModel().getColumn(9).setMinWidth(110); tbAtendimentos.getColumnModel().getColumn(9).setPreferredWidth(110); tbAtendimentos.getColumnModel().getColumn(9).setMaxWidth(110); // BHCG tbAtendimentos.getColumnModel().getColumn(10).setMinWidth(110); tbAtendimentos.getColumnModel().getColumn(10).setPreferredWidth(110); tbAtendimentos.getColumnModel().getColumn(10).setMaxWidth(110); // USG dias tbAtendimentos.getColumnModel().getColumn(11).setMinWidth(70); tbAtendimentos.getColumnModel().getColumn(11).setPreferredWidth(70); tbAtendimentos.getColumnModel().getColumn(11).setMaxWidth(70); // USG semanas tbAtendimentos.getColumnModel().getColumn(12).setMinWidth(100); tbAtendimentos.getColumnModel().getColumn(12).setPreferredWidth(100); tbAtendimentos.getColumnModel().getColumn(12).setMaxWidth(100); // ultima USG tbAtendimentos.getColumnModel().getColumn(13).setMinWidth(110); tbAtendimentos.getColumnModel().getColumn(13).setPreferredWidth(110); tbAtendimentos.getColumnModel().getColumn(13).setMaxWidth(110); // ultima menstruacao tbAtendimentos.getColumnModel().getColumn(14).setMinWidth(120); tbAtendimentos.getColumnModel().getColumn(14).setPreferredWidth(120); tbAtendimentos.getColumnModel().getColumn(14).setMaxWidth(120); // obs tbAtendimentos.getColumnModel().getColumn(15).setMinWidth(200); tbAtendimentos.getColumnModel().getColumn(15).setPreferredWidth(200); tbAtendimentos.getColumnModel().getColumn(15).setMaxWidth(200); } btnVoltar.setBackground(new java.awt.Color(255, 153, 0)); btnVoltar.setFont(new java.awt.Font("Dialog", 1, 18)); btnVoltar.setForeground(new java.awt.Color(255, 255, 255)); btnVoltar .setIcon(new javax.swing.ImageIcon(getClass().getResource("/br/com/marlonenathan/imagens/voltar.png"))); btnVoltar.setText(" Voltar"); btnVoltar.setToolTipText(""); btnVoltar.setBorderPainted(false); btnVoltar.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR)); btnVoltar.setFocusCycleRoot(true); btnVoltar.setFocusPainted(false); btnVoltar.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnVoltarActionPerformed(evt); } }); JButton btnVerAtendimento = new JButton(); btnVerAtendimento.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { verAtendimento(e); } }); btnVerAtendimento.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR)); btnVerAtendimento.setBounds(new Rectangle(0, 0, 100, 40)); btnVerAtendimento.setToolTipText(""); btnVerAtendimento.setText("Ver atendimento >>"); btnVerAtendimento.setForeground(Color.WHITE); btnVerAtendimento.setFont(new Font("Dialog", Font.BOLD, 18)); btnVerAtendimento.setFocusPainted(false); btnVerAtendimento.setFocusCycleRoot(true); btnVerAtendimento.setBorderPainted(false); btnVerAtendimento.setBackground(new Color(0, 204, 255)); javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2); jPanel2Layout.setHorizontalGroup(jPanel2Layout.createParallelGroup(Alignment.TRAILING).addGroup(jPanel2Layout .createSequentialGroup().addContainerGap(38, Short.MAX_VALUE) .addGroup(jPanel2Layout.createParallelGroup(Alignment.LEADING) .addGroup(jPanel2Layout.createSequentialGroup() .addComponent(txtPesquisaPeloNome, GroupLayout.PREFERRED_SIZE, 468, GroupLayout.PREFERRED_SIZE) .addGap(18) .addComponent(btnPesquisar, GroupLayout.PREFERRED_SIZE, 79, GroupLayout.PREFERRED_SIZE)) .addGroup(jPanel2Layout.createParallelGroup(Alignment.TRAILING, false) .addGroup(Alignment.LEADING, jPanel2Layout.createSequentialGroup() .addComponent(btnVoltar, GroupLayout.PREFERRED_SIZE, 145, GroupLayout.PREFERRED_SIZE) .addPreferredGap(ComponentPlacement.RELATED, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(btnVerAtendimento, GroupLayout.PREFERRED_SIZE, 386, GroupLayout.PREFERRED_SIZE)) .addComponent(jScrollPane1, Alignment.LEADING, GroupLayout.PREFERRED_SIZE, 1215, GroupLayout.PREFERRED_SIZE))) .addContainerGap(27, Short.MAX_VALUE))); jPanel2Layout.setVerticalGroup(jPanel2Layout.createParallelGroup(Alignment.LEADING).addGroup(jPanel2Layout .createSequentialGroup().addGap(36) .addGroup(jPanel2Layout.createParallelGroup(Alignment.TRAILING) .addComponent(txtPesquisaPeloNome, GroupLayout.PREFERRED_SIZE, 40, GroupLayout.PREFERRED_SIZE) .addComponent(btnPesquisar, GroupLayout.PREFERRED_SIZE, 40, GroupLayout.PREFERRED_SIZE)) .addGap(18).addComponent(jScrollPane1, GroupLayout.PREFERRED_SIZE, 505, GroupLayout.PREFERRED_SIZE) .addGap(18) .addGroup(jPanel2Layout.createParallelGroup(Alignment.LEADING) .addComponent(btnVoltar, GroupLayout.PREFERRED_SIZE, 70, GroupLayout.PREFERRED_SIZE) .addComponent(btnVerAtendimento, GroupLayout.PREFERRED_SIZE, 70, GroupLayout.PREFERRED_SIZE)) .addGap(33))); jPanel2.setLayout(jPanel2Layout); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(0, 0, Short.MAX_VALUE))); layout.setVerticalGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING).addComponent( jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)); pack(); setLocationRelativeTo(null); } String pesquisaPeloNome; private static final DateTimeFormatter FBR = DateTimeFormatter.ofPattern("dd/MM/yyyy"); private static final LocalDate HOJE = LocalDate.now(); private static final String DATA_ATENDIMENTO = HOJE.format(FBR); private void txtPesquisaPeloNomeFocusGained(java.awt.event.FocusEvent evt) { pesquisaPeloNome = txtPesquisaPeloNome.getText(); if (pesquisaPeloNome.length() > 0 && !txtPesquisaPeloNome.getText().contains("Nome do paciente")) { pesquisaPeloNome = txtPesquisaPeloNome.getText(); txtPesquisaPeloNome.setText(pesquisaPeloNome); } else { txtPesquisaPeloNome.setText(""); } } private void txtPesquisaPeloNomeFocusLost(java.awt.event.FocusEvent evt) { pesquisaPeloNome = txtPesquisaPeloNome.getText(); if (pesquisaPeloNome.length() == 0 || txtPesquisaPeloNome.getText().contains("Nome do paciente")) { txtPesquisaPeloNome.setText("Nome do paciente"); } } private void btnPesquisarActionPerformed(java.awt.event.ActionEvent evt) { readTablePeloNome(txtPesquisaPeloNome.getText()); } private void btnVoltarActionPerformed(java.awt.event.ActionEvent evt) { new TelaEscolhaFuncionario().setVisible(true); this.dispose(); } private void verAtendimento(ActionEvent e) { if (tbAtendimentos.getSelectedRow() != -1) { int index = tbAtendimentos.getSelectedRow(); TableModel tabela = tbAtendimentos.getModel(); telaAtendimento.setVisible(true); telaAtendimento.pack(); telaAtendimento.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); telaAtendimento.txtNomePaciente.setText(tabela.getValueAt(index, 0).toString()); telaAtendimento.txtSUS.setText(tabela.getValueAt(index, 1).toString()); telaAtendimento.qtdFilhos.setValue(tabela.getValueAt(index, 4)); telaAtendimento.qtdGravidez.setValue(tabela.getValueAt(index, 5)); telaAtendimento.qtdPartos.setValue(tabela.getValueAt(index, 6)); telaAtendimento.qtdAbortos.setValue(tabela.getValueAt(index, 7)); if (tabela.getValueAt(index, 8).equals(true)) { telaAtendimento.rdbtnSim.setSelected(true); } else { telaAtendimento.rdbtnNo.setSelected(true); } telaAtendimento.dtUltimoPreventivo.setText(tabela.getValueAt(index, 9).toString()); telaAtendimento.exameBHCG.setSelectedItem(tabela.getValueAt(index, 10)); telaAtendimento.igUSGDias.setValue(tabela.getValueAt(index, 11)); telaAtendimento.igUSGSemanas.setValue(tabela.getValueAt(index, 12)); telaAtendimento.ultimaUSG.setText(tabela.getValueAt(index, 13).toString()); telaAtendimento.ultimaMenstruacao.setText(tabela.getValueAt(index, 14).toString()); telaAtendimento.observacoes.setText(tabela.getValueAt(index, 15).toString()); readTable(); this.dispose(); telaAtendimento.setLocationRelativeTo(null); } else { JOptionPane.showMessageDialog(null, "Selecione um paciente para editar"); } } public void readTable() { DefaultTableModel modelo = (DefaultTableModel) tbAtendimentos.getModel(); modelo.setNumRows(0); AtendimentoDAO aDao = new AtendimentoDAO(); for (Atendimento a : aDao.readAtendimentos()) { modelo.addRow(new Object[] { a.getNome(), a.getDocumento(), DATA_ATENDIMENTO, a.getNumDeConsultas(), a.getQtdFilhos(), a.getQtdGravidez(), a.getQtdPartos(), a.getQtdAbortos(), a.getDoencaPrevia(), a.getDtUltimoPreventivo(), a.getExameBHCG(), a.getIgUSGDias(), a.getIgUSGSemanas(), a.getUltimaUSG(), a.getUltimaMenstruacao(), a.getObservacoes() }); } } public void readTablePeloNome(String nome) { DefaultTableModel modelo = (DefaultTableModel) tbAtendimentos.getModel(); modelo.setNumRows(0); AtendimentoDAO aDao = new AtendimentoDAO(); for (Atendimento a : aDao.buscarAtendimento(nome)) { modelo.addRow(new Object[] { a.getNome(), a.getDocumento(), DATA_ATENDIMENTO, a.getNumDeConsultas(), a.getQtdFilhos(), a.getQtdGravidez(), a.getQtdPartos(), a.getQtdAbortos(), a.getDoencaPrevia(), a.getDtUltimoPreventivo(), a.getExameBHCG(), a.getIgUSGDias(), a.getIgUSGSemanas(), a.getUltimaUSG(), a.getUltimaMenstruacao(), a.getObservacoes() }); } } public static void main(String args[]) { try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(TelaListaDeAtendimentos.class.getName()) .log(java.util.logging.Level.SEVERE, null, ex); } java.awt.EventQueue.invokeLater(() -> { TelaListaDeAtendimentos telaCadastroDeFuncionarios = new TelaListaDeAtendimentos(); telaCadastroDeFuncionarios.setVisible(true); telaCadastroDeFuncionarios.getContentPane().setBackground(new Color(8, 77, 110)); }); } private javax.swing.JButton btnPesquisar; private javax.swing.JButton btnVoltar; private javax.swing.JPanel jPanel2; private javax.swing.JTable tbAtendimentos; private javax.swing.JTextField txtPesquisaPeloNome; } <file_sep>/ControleRotinasDoPreNatal/src/br/com/marlonenathan/model/dao/PessoaDAO.java /* * 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 br.com.marlonenathan.model.dao; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; import javax.swing.JOptionPane; import br.com.marlonenathan.connection.ConnectionFactory; import br.com.marlonenathan.model.bean.Funcionario; import br.com.marlonenathan.model.bean.Paciente; /** * * @author marlonmazzine */ public class PessoaDAO { public void createFuncionario(Funcionario f) { Connection con = ConnectionFactory.getConnection(); PreparedStatement stmt = null; try { stmt = con.prepareStatement( "INSERT INTO funcionario (nome, documento, telefone, nascimento, usuario, senha)VALUES(?, ?, ?, ?, ?, ?)"); stmt.setString(1, f.getNome()); stmt.setString(2, f.getDocumento()); stmt.setString(3, f.getTelefone()); stmt.setString(4, f.getNascimento()); stmt.setString(5, f.getUsuario()); stmt.setString(6, f.getSenha()); stmt.executeUpdate(); JOptionPane.showMessageDialog(null, "Salvo com sucesso"); } catch (SQLException ex) { if(ex.getMessage().contains("Duplicate entry")) { JOptionPane.showMessageDialog(null, "Erro ao salvar: código do CRM já existe.", "Documento duplicado", JOptionPane.ERROR_MESSAGE); } } finally { ConnectionFactory.closeConnection(con, stmt); } } public List<Funcionario> readFuncionario() { Connection con = ConnectionFactory.getConnection(); PreparedStatement stmt = null; ResultSet rs = null; List<Funcionario> funcionarios = new ArrayList<>(); try { stmt = con.prepareStatement("SELECT * FROM cadastro.funcionario"); rs = stmt.executeQuery(); while (rs.next()) { Funcionario funcionario = new Funcionario(); funcionario.setNome(rs.getString("nome")); funcionario.setDocumento(rs.getString("documento")); funcionario.setTelefone(rs.getString("telefone")); funcionario.setNascimento(rs.getString("nascimento")); funcionarios.add(funcionario); } } catch (SQLException ex) { Logger.getLogger(PessoaDAO.class.getName()).log(Level.SEVERE, null, ex); } finally { ConnectionFactory.closeConnection(con, stmt, rs); } return funcionarios; } public void updateFuncionario(Funcionario f) { Connection con = ConnectionFactory.getConnection(); PreparedStatement stmt = null; try { stmt = con.prepareStatement( "UPDATE cadastro.funcionario SET nome = ?, documento = ?, telefone = ?, nascimento = ?, usuario = ?, senha = ? WHERE documento = ?"); stmt.setString(1, f.getNome()); stmt.setString(2, f.getDocumento()); stmt.setString(3, f.getTelefone()); stmt.setString(4, f.getNascimento()); stmt.setString(5, f.getUsuario()); stmt.setString(6, f.getSenha()); stmt.setString(7, f.getDocumento()); stmt.executeUpdate(); JOptionPane.showMessageDialog(null, "Atualizado com sucesso"); } catch (SQLException ex) { JOptionPane.showMessageDialog(null, "Erro ao atualizar: " + ex); } finally { ConnectionFactory.closeConnection(con, stmt); } } public void deleteFuncionario(Funcionario f) { Connection con = ConnectionFactory.getConnection(); PreparedStatement stmt = null; try { stmt = con.prepareStatement("DELETE FROM cadastro.funcionario WHERE documento = ?"); stmt.setString(1, f.getDocumento()); stmt.executeUpdate(); JOptionPane.showMessageDialog(null, "Excluído com sucesso"); } catch (SQLException ex) { JOptionPane.showMessageDialog(null, "Erro ao excluir: " + ex); } finally { ConnectionFactory.closeConnection(con, stmt); } } public List<Funcionario> buscarFuncionario(String nome) { Connection con = ConnectionFactory.getConnection(); PreparedStatement stmt = null; ResultSet rs = null; List<Funcionario> funcionarios = new ArrayList<>(); try { stmt = con.prepareStatement("SELECT * FROM cadastro.funcionario WHERE nome LIKE ?"); stmt.setString(1, "%" + nome + "%"); rs = stmt.executeQuery(); while (rs.next()) { Funcionario funcionario = new Funcionario(); funcionario.setNome(rs.getString("nome")); funcionario.setDocumento(rs.getString("documento")); funcionario.setTelefone(rs.getString("telefone")); funcionario.setNascimento(rs.getString("nascimento")); funcionarios.add(funcionario); } } catch (SQLException ex) { Logger.getLogger(PessoaDAO.class.getName()).log(Level.SEVERE, null, ex); } finally { ConnectionFactory.closeConnection(con, stmt, rs); } return funcionarios; } // termina o funcionario // começa o paciente public void createPaciente(Paciente p) { Connection con = ConnectionFactory.getConnection(); PreparedStatement stmt = null; try { stmt = con.prepareStatement( "INSERT INTO cadastro.paciente (nome, documento, telefone, nascimento) VALUES (?, ?, ?, ?)"); stmt.setString(1, p.getNome()); stmt.setString(2, p.getDocumento()); stmt.setString(3, p.getTelefone()); stmt.setString(4, p.getNascimento()); stmt.executeUpdate(); JOptionPane.showMessageDialog(null, "Salvo com sucesso"); } catch (SQLException ex) { if(ex.getMessage().contains("Duplicate entry")) { JOptionPane.showMessageDialog(null, "Erro ao salvar: código do SUS já existe.", "Documento duplicado", JOptionPane.ERROR_MESSAGE); } } finally { ConnectionFactory.closeConnection(con, stmt); } } public List<Paciente> readPaciente() { Connection con = ConnectionFactory.getConnection(); PreparedStatement stmt = null; ResultSet rs = null; List<Paciente> pacientes = new ArrayList<>(); try { stmt = con.prepareStatement("SELECT * FROM cadastro.paciente"); rs = stmt.executeQuery(); while (rs.next()) { Paciente paciente = new Paciente(); paciente.setNome(rs.getString("nome")); paciente.setDocumento(rs.getString("documento")); paciente.setTelefone(rs.getString("telefone")); paciente.setNascimento(rs.getString("nascimento")); pacientes.add(paciente); } } catch (SQLException ex) { Logger.getLogger(PessoaDAO.class.getName()).log(Level.SEVERE, null, ex); } finally { ConnectionFactory.closeConnection(con, stmt, rs); } return pacientes; } public void updatePaciente(Paciente p) { Connection con = ConnectionFactory.getConnection(); PreparedStatement stmt = null; try { stmt = con.prepareStatement( "UPDATE cadastro.paciente SET nome = ?, documento = ?, telefone = ?, nascimento = ? WHERE documento = ?"); stmt.setString(1, p.getNome()); stmt.setString(2, p.getDocumento()); stmt.setString(3, p.getTelefone()); stmt.setString(4, p.getNascimento()); stmt.setString(5, p.getDocumento()); stmt.executeUpdate(); JOptionPane.showMessageDialog(null, "Atualizado com sucesso"); } catch (SQLException ex) { JOptionPane.showMessageDialog(null, "Erro ao atualizar: " + ex); } finally { ConnectionFactory.closeConnection(con, stmt); } } public void deletePaciente(Paciente p) { Connection con = ConnectionFactory.getConnection(); PreparedStatement stmt = null; try { stmt = con.prepareStatement("DELETE FROM cadastro.paciente WHERE documento = ?"); stmt.setString(1, p.getDocumento()); stmt.executeUpdate(); JOptionPane.showMessageDialog(null, "Excluído com sucesso"); } catch (SQLException ex) { JOptionPane.showMessageDialog(null, "Erro ao excluir: " + ex); } finally { ConnectionFactory.closeConnection(con, stmt); } } public List<Paciente> buscarPaciente(String nome) { Connection con = ConnectionFactory.getConnection(); PreparedStatement stmt = null; ResultSet rs = null; List<Paciente> pacientes = new ArrayList<>(); try { stmt = con.prepareStatement("SELECT * FROM cadastro.paciente WHERE nome LIKE ?"); stmt.setString(1, "%" + nome + "%"); rs = stmt.executeQuery(); while (rs.next()) { Paciente paciente = new Paciente(); paciente.setNome(rs.getString("nome")); paciente.setDocumento(rs.getString("documento")); paciente.setTelefone(rs.getString("telefone")); paciente.setNascimento(rs.getString("nascimento")); pacientes.add(paciente); } } catch (SQLException ex) { Logger.getLogger(PessoaDAO.class.getName()).log(Level.SEVERE, null, ex); } finally { ConnectionFactory.closeConnection(con, stmt, rs); } return pacientes; } } <file_sep>/ControleRotinasDoPreNatal/src/br/com/marlonenathan/model/dao/AtendimentoDAO.java package br.com.marlonenathan.model.dao; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; import javax.swing.JOptionPane; import br.com.marlonenathan.connection.ConnectionFactory; import br.com.marlonenathan.model.bean.Atendimento; public class AtendimentoDAO { public void createAtendimento(Atendimento a) { Connection con = ConnectionFactory.getConnection(); PreparedStatement stmt = null; try { stmt = con.prepareStatement( "INSERT INTO cadastro.atendimento (nome, documento, qtdFilhos, qtdGravidez, qtdPartos, qtdAbortos, doencaPrevia, dtUltimoPreventivo," + " exameBHCG, igUSGDias, igUSGSemanas, ultimaUSG, ultimaMenstruacao, numDeConsultas, observacoes)" + "VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"); stmt.setString(1, a.getNome()); stmt.setString(2, a.getDocumento()); stmt.setInt(3, a.getQtdFilhos()); stmt.setInt(4, a.getQtdGravidez()); stmt.setInt(5, a.getQtdPartos()); stmt.setInt(6, a.getQtdAbortos()); stmt.setBoolean(7, a.getDoencaPrevia()); stmt.setString(8, a.getDtUltimoPreventivo()); stmt.setString(9, a.getExameBHCG()); stmt.setInt(10, a.getIgUSGDias()); stmt.setInt(11, a.getIgUSGSemanas()); stmt.setString(12, a.getUltimaUSG()); stmt.setString(13, a.getUltimaMenstruacao()); stmt.setInt(14, a.getNumDeConsultas()); stmt.setString(15, a.getObservacoes()); stmt.executeUpdate(); JOptionPane.showMessageDialog(null, "Salvo com sucesso"); } catch (SQLException ex) { JOptionPane.showMessageDialog(null, "Erro ao salvar: " + ex); } finally { ConnectionFactory.closeConnection(con, stmt); } } public List<Atendimento> readAtendimentos() { Connection con = ConnectionFactory.getConnection(); PreparedStatement stmt = null; ResultSet rs = null; List<Atendimento> atendimentos = new ArrayList<>(); try { stmt = con.prepareStatement("SELECT * FROM cadastro.atendimento"); rs = stmt.executeQuery(); while (rs.next()) { Atendimento atendimento = new Atendimento(); atendimento.setNome(rs.getString("nome")); atendimento.setDocumento(rs.getString("documento")); atendimento.setNumDeConsultas(rs.getInt("numDeConsultas")); atendimento.setQtdFilhos(rs.getInt("qtdFilhos")); atendimento.setQtdGravidez(rs.getInt("qtdGravidez")); atendimento.setQtdPartos(rs.getInt("qtdPartos")); atendimento.setQtdAbortos(rs.getInt("qtdAbortos")); atendimento.setDoencaPrevia(rs.getBoolean("doencaPrevia")); atendimento.setDtUltimoPreventivo(rs.getString("dtUltimoPreventivo")); atendimento.setExameBHCG(rs.getString("exameBHCG")); atendimento.setIgUSGDias(rs.getInt("igUSGDias")); atendimento.setIgUSGSemanas(rs.getInt("igUSGSemanas")); atendimento.setUltimaUSG(rs.getString("ultimaUSG")); atendimento.setUltimaMenstruacao(rs.getString("ultimaMenstruacao")); atendimento.setObservacoes(rs.getString("observacoes")); atendimentos.add(atendimento); } } catch (SQLException ex) { Logger.getLogger(AtendimentoDAO.class.getName()).log(Level.SEVERE, null, ex); } finally { ConnectionFactory.closeConnection(con, stmt, rs); } return atendimentos; } public List<Atendimento> buscarAtendimento(String nome) { Connection con = ConnectionFactory.getConnection(); PreparedStatement stmt = null; ResultSet rs = null; List<Atendimento> atendimentos = new ArrayList<>(); try { stmt = con.prepareStatement("SELECT * FROM cadastro.atendimento WHERE nome LIKE ?"); stmt.setString(1, "%" + nome + "%"); rs = stmt.executeQuery(); while (rs.next()) { Atendimento atendimento = new Atendimento(); atendimento.setNome(rs.getString("nome")); atendimento.setDocumento(rs.getString("documento")); atendimento.setNumDeConsultas(rs.getInt("numDeConsultas")); atendimento.setQtdFilhos(rs.getInt("qtdFilhos")); atendimento.setQtdGravidez(rs.getInt("qtdGravidez")); atendimento.setQtdPartos(rs.getInt("qtdPartos")); atendimento.setQtdAbortos(rs.getInt("qtdAbortos")); atendimento.setDoencaPrevia(rs.getBoolean("doencaPrevia")); atendimento.setDtUltimoPreventivo(rs.getString("dtUltimoPreventivo")); atendimento.setExameBHCG(rs.getString("exameBHCG")); atendimento.setIgUSGDias(rs.getInt("igUSGDias")); atendimento.setIgUSGSemanas(rs.getInt("igUSGSemanas")); atendimento.setUltimaUSG(rs.getString("ultimaUSG")); atendimento.setUltimaMenstruacao(rs.getString("ultimaMenstruacao")); atendimento.setObservacoes(rs.getString("observacoes")); atendimentos.add(atendimento); } } catch (SQLException ex) { Logger.getLogger(AtendimentoDAO.class.getName()).log(Level.SEVERE, null, ex); } finally { ConnectionFactory.closeConnection(con, stmt, rs); } return atendimentos; } } <file_sep>/README.md # controle-das-rotinas-do-pre-natal
be36451083c6fb9a0f21076fc2c9b816b70a04f1
[ "Markdown", "Java" ]
6
Java
MarlonMazzine/controle-das-rotinas-do-pre-natal
8e9adf16d9e00ecfb835731b0022d67fd11a3d6b
434a591a4157e6738100b373fb3cb5295b0dc112
refs/heads/master
<file_sep>module.exports = function(app) { const testing = require('../controller/testing.controller'); const upload = require('../config/multer.config'); // Create a new AdminUser app.post('/api/addTesting',upload.single('uploadfile'), testing.create); }<file_sep>module.exports = (sequelize, Sequelize) => { const RegisterUser = sequelize.define('tbl_registeruser', { registerName: { type: Sequelize.STRING }, registerEmail: { type: Sequelize.STRING }, registerPhone: { type: Sequelize.STRING }, registerPassword: { type: Sequelize.STRING }, registerUserPoint:{ type:Sequelize.DOUBLE }, updatedUser:{ type: Sequelize.STRING }, active:{ type: Sequelize.BOOLEAN }, }, { freezeTableName:true, tableName:'tbl_registeruser' }); return RegisterUser; }<file_sep>module.exports = function(app) { const upload = require('../config/yourConfidence.multer.config'); const ycgallery = require('../controller/yourConfidence.controller.js'); // Create a new category app.post('/api/addNewModel', upload.single('uploadfile'), ycgallery.create); // Show Category Photo Path app.get('/api/getYcGalleryPhotoPath/:fileName', ycgallery.getPhotoPath); // Update a category with Id app.put('/api/updateycgallery/:ycgalleryId', upload.single('uploadfile'), ycgallery.update); //Retrieve all Category by active app.get('/api/getycgallery', ycgallery.getAll); }<file_sep>const db = require('../config/db.config.js'); //db.tbl_subscriber = require('../model/subscriber.model.js'); const Subscriber = db.tbl_subscriber; exports.create = (req, res) => { // Save to MySQL database console.log(req.body.email_id); // Subscriber.create({ // email_id: req.body.email_id, // }).then(subscriber => { // res.send(subscriber); // }); }; exports.findAll = (req, res) => { Subscriber.findAll({}).then(list => { res.send(list); }) .catch((error) => { console.log(error.toString()); res.status(400).send(error) }); }; <file_sep>module.exports = function(app) { const discount = require('../controller/discountCoupon.controller'); // Retrieve all Price app.get('/api/getCouponType', discount.getCouponType); app.get('/api/getDiscountCoupon', discount.getDiscountCoupon); app.post('/api/addNewDiscountCoupon',discount.addNewDiscountCoupon); app.put('/api/updateDiscountCoupon/:id',discount.updateDiscountCoupon); app.get('/api/checkCouponCode/:code',discount.checkCouponCode); }<file_sep>module.exports = (sequelize, Sequelize) => { const VarientOne = sequelize.define('tbl_varientone', { item: { type: Sequelize.INTEGER }, varientOneImage: { type: Sequelize.STRING }, varientGroupNameOne:{ type: Sequelize.STRING }, varientNameOne:{ type:Sequelize.STRING }, updatedUser:{ type: Sequelize.STRING }, creationUser:{ type: Sequelize.STRING }, }, { freezeTableName:true, tableName:'tbl_varientone' }); return VarientOne; }<file_sep>module.exports = function(app) { const upload = require('../config/ocassion.multer.config'); const ocassion = require('../controller/ocassion.controller.js'); // Create a new ocassion app.post('/api/addNewOcassion', upload.single('uploadfile'), ocassion.create); // Show Ocassion Photo Path app.get('/api/getOcassionPhotoPath/:fileName', ocassion.getPhotoPath); // Retrieve all ocassion app.get('/api/getAllOcassion', ocassion.findAll); app.get('/api/findAllOcassion', ocassion.findAllOcassion); // Update a ocassion with Id app.put('/api/updateOcassion/:ocassionId', upload.single('uploadfile'), ocassion.update); //Retrieve all Ocassion by active app.get('/api/getOcassionByActive', ocassion.findAllByActive); }<file_sep>module.exports = (sequelize, Sequelize) => { const Varient = sequelize.define('tbl_varient', { item: { type: Sequelize.INTEGER }, varientOneImage: { type: Sequelize.STRING }, quantity: { type: Sequelize.INTEGER }, price: { type: Sequelize.DOUBLE }, discountPrice:{ type: Sequelize.DOUBLE }, varientGroupNameOne:{ type: Sequelize.STRING }, varientNameOne:{ type:Sequelize.STRING }, varientGroupNameTwo:{ type:Sequelize.STRING }, varientNameTwo:{ type:Sequelize.STRING }, description:{ type:Sequelize.STRING }, updatedUser:{ type: Sequelize.STRING }, }, { freezeTableName:true, tableName:'tbl_varient' }); return Varient; }<file_sep>module.exports = function (app) { const item = require('../controller/item.controller.js'); // Create a new Item app.post('/api/addNewItem', item.create); // Retrieve all Item app.get('/api/getAllItem', item.findAll); //get Item for Home Page Default is New Arrival app.get('/api/getMatchItemByCategoryId/:id',item.getMatchItemByCategoryId) app.get('/api/findByOcassion/:id',item.findByOcassion) app.get('/api/getMatchItemByMainCategoryId/:id',item.getMatchItemByMainCategoryId) //get Item for Home Page app.get('/api/getBestSellingItem',item.getBestSellingItem) app.get('/api/getNewArrivalItem',item.getNewArrivalItem) app.get('/api/getItemHome',item.getItemHome) //get Item for Home Page app.get('/api/getPromotionItem',item.getPromotionItem) // Update a Item with Id app.put('/api/updateItem/:itemId', item.update); //Retrieve all Item by active app.get('/api/getItemByActive', item.findAllByActive); // Retrieve a single Item by Id app.get('/api/getItemById/:itemId', item.findById); app.get('/api/getItemViewById/:itemId', item.getItemViewById); //Retrieve Item Photo By Id app.get('/api/getItemPhotoById/:itemId', item.findPhotoById); // Show Item Photo Path app.get('/api/getItemPhotoPath/:fileName', item.getPhotoPath); //Retrieve a single item photo by Id app.get('/api/getOneItemPhoto/:itemId', item.findOnePhotoByItemId); //retrieve related item depend on subcategory app.get('/api/getRelatedItem/:categoryId/:itemId', item.getRelatedItem); // get Item list by Category Id app.get('/api/getItemListByCategory/:category', item.getItemListByCategory); //get Item List by Campaign Id app.get('/api/getItemListByCampaign/:campaign', item.getItemListByCampaign); //get Item with Price by active app.get('/api/item/getItemWithPriceByActive', item.getItemWithPriceByActive); //get lowest price item app.get('/api/item/getLowestPriceItem', item.getLowestPriceItem); //get highest price item app.get('/api/item/getHighestPriceItem', item.getHighestPriceItem); //get popular item app.get('/api/item/getPopularItem', item.getPopularItem); //get Check Out Item Data app.post('/api/getCheckOutItem', item.getCheckOutItem); //get Item for multiple select app.get('/api/item/getItemSelect', item.getItemSelect); app.get('/api/item/getItemSelectNotIncluded/:itemId', item.getItemSelectNotIncluded); app.get('/api/getMatchItem/:id',item.getMatchItem) app.get('/api/getMachItemById/:id',item.getMatchItemById) }<file_sep>module.exports = (sequelize, Sequelize) => { const City = sequelize.define('tbl_city', { cityName: { type: Sequelize.STRING }, creationUser:{ type: Sequelize.STRING }, updatedUser:{ type: Sequelize.STRING } }, { freezeTableName:true, tableName:'tbl_city' }); return City; }<file_sep>module.exports = (sequelize, Sequelize) => { const Item = sequelize.define('tbl_item', { itemName: { type: Sequelize.STRING }, ocassionId:{ type:Sequelize.INTEGER }, shortName: { type: Sequelize.STRING }, shortNote: { type: Sequelize.STRING }, description: { type: Sequelize.STRING }, categoryId: { type: Sequelize.INTEGER }, creationUser:{ type: Sequelize.STRING }, active:{ type: Sequelize.BOOLEAN }, isHomeDisplay:{ type:Sequelize.BOOLEAN }, isPromotion:{ type:Sequelize.BOOLEAN }, isNewArrival:{type:Sequelize.BOOLEAN}, isBestSelling:{type:Sequelize.BOOLEAN}, updatedUser:{ type: Sequelize.STRING }, // itemPhoto:{ // type:DataTypes.ARRAY(Sequelize.STRING) // } }, { freezeTableName:true, tableName:'tbl_item' }); return Item; }<file_sep>const db = require('../config/db.config.js'); const fs = require('fs'); const path = require('../config/Global'); var crypto = require('crypto'); const AdminUser = db.tbl_adminuser; exports.create = (req, res) => { var hash = crypto.createHash('md5').update(req.body.password).digest('hex'); if (req.file == undefined) { AdminUser.create({ userName: req.body.userName, email: req.body.email, phone: req.body.phone, address: req.body.address, password: <PASSWORD>, gender: req.body.gender, active: req.body.active, creationUser: req.body.creationUser, profileImage: 'default-image.jpg', }).then(user => { res.send(user); }); } else { AdminUser.create({ userName: req.body.userName, email: req.body.email, phone: req.body.phone, address: req.body.address, password: <PASSWORD>, gender: req.body.gender, active: req.body.active, creationUser: req.body.creationUser, profileImage: req.file.filename, }).then(user => { res.send(user); }); } }; // show photo path exports.getPhotoPath = (req, res) => { const fileName = req.params.fileName; const mimeType = fileName.split('.')[1]; var staticResource = path.adminPhotoPath + fileName; console.log(staticResource) fs.readFile(staticResource, (err, data) => { if (err) { console.log("Can't read file"); } console.log(data) res.writeHead(200, { 'Content-Type': mimeType }); res.end(data) }); }; //check Account exports.check = (req, res) => { const userName = req.params.userName; var hash = crypto.createHash('md5').update(req.params.password).digest('hex'); AdminUser.find( { where: { userName: userName, password: <PASSWORD> } } ).then(acc => { if (acc != null) { res.send(acc.userName); } else { res.send('wrong'); } }); }; // FETCH all Admin Users exports.findAll = (req, res) => { AdminUser.findAll().then(admin => { res.send(admin); }); }; //Update Admin User With Image exports.updateAdmin = (req, res) => { const id = req.params.adminId; if (req.file == undefined) { var hash = crypto.createHash('md5').update(req.body.password).digest('hex'); AdminUser.update({ userName: req.body.userName, email: req.body.email, phone: req.body.email, address: req.body.address, password: <PASSWORD>, phone: req.body.phone, gender: req.body.gender, active: req.body.active, updatedUser: req.body.updatedUser }, { where: { id: req.params.adminId } } ).then(() => { res.status(200).send("updated successfully a admin with id = " + id); }); } else { var hash = crypto.createHash('md5').update(req.body.password).digest('hex'); AdminUser.update({ userName: req.body.userName, email: req.body.email, phone: req.body.email, address: req.body.address, password: <PASSWORD>, gender: req.body.gender, active: req.body.active, profileImage: req.file.filename, updatedUser: req.body.updatedUser }, { where: { id: req.params.adminId } } ).then(() => { res.status(200).send("updated successfully a admin with id = " + id); }); } }; <file_sep>const main = require('os').homedir + "/Rene/"; const path = { adminPhotoPath: main + "adminuser_upload/", itemPhotoPath:main+"item_upload/", categoryPhotoPath:main+"category_upload/", yourConfidencePhotoPath:main+"yourConfidence_upload/", upload:main+"upload/" } module.exports = path <file_sep>module.exports = (sequelize, Sequelize) => { const Supplier = sequelize.define('tbl_supplier', { supplierName: { type: Sequelize.STRING }, phone: { type: Sequelize.STRING }, email: { type: Sequelize.STRING }, address: { type: Sequelize.STRING }, description: { type: Sequelize.STRING }, creationUser:{ type: Sequelize.STRING }, active:{ type:Sequelize.BOOLEAN }, updatedUser:{ type: Sequelize.STRING }, }, { freezeTableName:true, tableName:'tbl_supplier' }); return Supplier; }<file_sep>module.exports = (sequelize, Sequelize) => { const Classs = sequelize.define('tbl_classs', { classsName: { type: Sequelize.STRING }, description: { type: Sequelize.STRING }, creationUser:{ type: Sequelize.STRING }, active:{ type: Sequelize.BOOLEAN }, updatedUser:{ type: Sequelize.STRING }, }, { freezeTableName:true, tableName:'tbl_classs' }); return Classs; }<file_sep>module.exports = function(app) { const campaign = require('../controller/campaign.controller.js'); const upload = require('../config/multer.config'); // Create a new Campaign app.post('/api/addNewCampaign',upload.single('uploadfile'), campaign.create); // Show Profile Photo Path app.get('/api/getCampaignPhotoPath/:fileName',campaign.getPhotoPath); // Retrieve all Campaign app.get('/api/getAllCampaign', campaign.findAll); //Retrieve campaign for select app.get('/api/getCampaignSelect',campaign.findCampaignSelect); // Update a Campaign with Id app.put('/api/updateCampaign/:campaignId',upload.single('uploadfile'), campaign.update); //Retrieve all Campaign by active app.get('/api/getCampaignByActive',campaign.findAllByActive); }<file_sep>const db = require('../config/db.config.js'); const Testing = db.tbl_testing; // Post a Category exports.create = (req, res) => { console.log(req.body) console.log(req.file); // Save to MySQL database Testing.create({ fileName:req.body.filename, userName:req.body.username, }).then(testing => { res.send(testing); }); };<file_sep>const db = require('../config/db.config.js'); const Category = db.tbl_category; const SubCategory = db.tbl_subcategory; const sequelize = db.sequelize; const path = require('../config/Global'); const fs = require('fs'); // Post a Category exports.create = (req, res) => { if (req.file == undefined) { Category.create({ categoryName: req.body.categoryName, description: req.body.description, active: req.body.active, classId: req.body.classId, isHomeDisplay:req.body.isHomeDisplay, creationUser:req.body.creationUser, categoryImage: 'default-image.jpg', }).then(category => { res.send(category); }); } else { Category.create({ categoryName: req.body.categoryName, description: req.body.description, creationUser:req.body.creationUser, active: req.body.active, classId: req.body.classId, isHomeDisplay:req.body.isHomeDisplay, categoryImage: req.file.filename, }).then(category => { res.send(category); }); } }; exports.findAllByActive = (req, res) => { let query = `SELECT id as value, categoryName as label FROM tbl_category where active = true `; sequelize.query(query, { type: sequelize.QueryTypes.SELECT }) .then(list => { res.send(list) }) } // show photo path exports.getPhotoPath = (req, res) => { const fileName = req.params.fileName; const mimeType = fileName.split('.')[1]; var staticResource = path.categoryPhotoPath + fileName; console.log(fileName) console.log(mimeType) console.log(staticResource) fs.readFile(staticResource, (err, data) => { if (err) { console.log("Can't read file"); } res.writeHead(200, { 'Content-Type': mimeType }); res.end(data) }); }; // FETCH all Category exports.findAll = (req, res) => { let query = `SELECT a.id, a.categoryName, a.classsId, a.description, a.categoryImage, a.creationUser, a.updatedUser, a.createdAt, a.updatedAt, a.isHomeDisplay,a.active, b.classsName FROM tbl_category as a inner join tbl_classs as b on a.classsId = b.id`; sequelize.query(query, { type: sequelize.QueryTypes.SELECT }) .then(list => { res.send(list) }) }; // Update a Category exports.update = (req, res) => { const id = req.params.categoryId; if (req.file == undefined) { Category.update({ categoryName: req.body.categoryName,classId: req.body.classId, description: req.body.description, active: req.body.active,isHomeDisplay:req.body.isHomeDisplay, updatedUser:req.body.updatedUser }, { where: { id: req.params.categoryId } } ).then(() => { res.status(200).send("updated successfully a category with id = " + id); }); } else { Category.update({ categoryName: req.body.categoryName,classId: req.body.classId,categoryImage: req.file.filename, description: req.body.description,isHomeDisplay:req.body.isHomeDisplay, active: req.body.active,updatedUser:req.body.updatedUser }, { where: { id: req.params.categoryId } } ).then(() => { res.status(200).send("updated successfully a category with id = " + id); }); } }; exports.createSubCategory = (req, res) => { SubCategory.create({ subCategoryName: req.body.subCategoryName, description: req.body.description, creationUser:req.body.creationUser, active: req.body.active, isHomeDisplay:req.body.isHomeDisplay, mainCategoryId: req.body.mainCategoryId }).then(category => { res.send(category); }); }; // FETCH all Category exports.findSubCategory = (req, res) => { let query = `SELECT id as value , subCategoryName as label FROM tbl_subcategory where active = true `; sequelize.query(query, { type: sequelize.QueryTypes.SELECT }) .then(list => { res.send(list) }) }; exports.findTop3MainCategory = async (req, res) => { let subCategory = ''; let mainCategory = [] let mCategoryQuery = `Select id, categoryName,categoryImage from tbl_category where isHomeDisplay = true`; mainCategory = await sequelize.query(mCategoryQuery, { type: sequelize.QueryTypes.SELECT }); for (var i = 0; i < mainCategory.length; i++) { let subCategoryQuery = `Select id,subCategoryName from tbl_subcategory where isHomeDisplay= true and mainCategoryId=` + mainCategory[i].id ; subCategory = await sequelize.query(subCategoryQuery, { type: sequelize.QueryTypes.SELECT }); mainCategory[i].detail = subCategory } res.send(mainCategory) }; exports.findSubCategoryByActive = (req, res) => { let query = `SELECT a.id, a.mainCategoryId,a.subCategoryName,a.description,a.isHomeDisplay,a.active, b.categoryName FROM tbl_subcategory as a inner join tbl_category as b on a.mainCategoryId = b.id`; sequelize.query(query, { type: sequelize.QueryTypes.SELECT }) .then(list => { res.send(list) }) } // Update a sub Category exports.updateSubCategory = (req, res) => { const id = req.params.subCategoryId; SubCategory.update({ subCategoryName: req.body.subCategoryName, mainCategoryId:req.body.mainCategoryId, description: req.body.description,isHomeDisplay:req.body.isHomeDisplay, active: req.body.active, updatedUser:req.body.updatedUser }, { where: { id: id } } ).then(() => { res.status(200).send("updated successfully a category with id = " + id); }); }; <file_sep>module.exports = (sequelize, Sequelize) => { const Ocassion = sequelize.define('tbl_ocassion', { ocassionName: { type: Sequelize.STRING }, description: { type: Sequelize.STRING }, ocassionImage:{ type: Sequelize.STRING }, creationUser:{ type: Sequelize.STRING }, active:{ type: Sequelize.BOOLEAN }, isHomeDisplay:{ type:Sequelize.BOOLEAN }, updatedUser:{ type: Sequelize.STRING }, }, { freezeTableName:true, tableName:'tbl_ocassion' }); return Ocassion; }<file_sep>const db = require('../config/db.config.js'); const City = db.tbl_city; // Post a City exports.create = (req, res) => { // Save to MySQL database City.create({ cityName: req.body.cityName, }).then(city => { res.send(city); }); }; // FETCH all Cities exports.findAll = (req, res) => { City.findAll().then(city => { res.send(city); }); }; exports.findCityByActive = (req,res) => { City.findAll({ where: { active: true } } ).then(city => { res.send(city); }); } // // Find a Customer by Id // exports.findById = (req, res) => { // Customer.findById(req.params.customerId).then(customer => { // res.send(customer); // }) // }; // Update a City exports.update = (req, res) => { const id = req.params.cityId; City.update( { cityName: req.body.cityName}, { where: {id: req.params.cityId} } ).then(() => { res.status(200).send("updated successfully a city with id = " + id); }); }; // // Delete a Customer by Id // exports.delete = (req, res) => { // const id = req.params.customerId; // Customer.destroy({ // where: { id: id } // }).then(() => { // res.status(200).send('deleted successfully a customer with id = ' + id); // }); // };<file_sep>module.exports = (sequelize, Sequelize) => { const orderUser = sequelize.define('tbl_orderuser', { userId: { type: Sequelize.INTEGER }, address: { type: Sequelize.STRING }, billingAddress:{ type: Sequelize.STRING }, description: { type: Sequelize.STRING }, grandTotal:{ type:Sequelize.DOUBLE }, }, { freezeTableName: true, tableName: 'tbl_orderuser' }); return orderUser; }<file_sep>const db = require('../config/db.config.js'); const sequelize = db.sequelize; const path = require('../config/Global'); const couponType = db.tbl_coupontype; const coupon = db.tbl_discountcoupon; exports.getCouponType = (req, res) => { let query = `SELECT id as value, couponTypeName as label FROM tbl_coupontype `; sequelize.query(query, { type: sequelize.QueryTypes.SELECT }) .then(list => { res.send(list) }) } exports.getDiscountCoupon = (req, res) => { let query = `SELECT a.*, b.couponTypeName from tbl_discountcoupon as a inner join tbl_coupontype as b on a.couponTypeId = b.id where active = true `; sequelize.query(query, { type: sequelize.QueryTypes.SELECT }) .then(list => { res.send(list) }) } exports.addNewDiscountCoupon = (req, res) => { coupon.create({ couponName: req.body.couponName, couponCode: req.body.couponCode, couponTypeId:req.body.couponTypeId, amount: req.body.amount, active: true }).then(coupon => { res.send(coupon); }); }; exports.updateDiscountCoupon = (req, res) => { const id = req.params.id; coupon.update({ couponName: req.body.couponName, couponCode:req.body.couponCode, couponTypeId: req.body.couponType,amount:req.body.amount, active: req.body.active, updatedUser:req.body.updatedUser }, { where: { id: id } } ).then((coupon) => { res.status(200).send("updated successfully a coupon with id = " + id); }); } exports.checkCouponCode = (req, res) => { const code = req.params.code; let query = `SELECT amount,couponTypeId FROM tbl_discountcoupon where couponCode = '`+code + `' and active = true `; sequelize.query(query, { type: sequelize.QueryTypes.SELECT }) .then(list => { res.send(list) }) } <file_sep>module.exports = function(app) { const upload = require('../config/multer.config'); const brand = require('../controller/brand.controller.js'); // Create a new Supplier app.post('/api/addNewBrand',upload.single('uploadfile'), brand.create); // Show Category Photo Path app.get('/api/getBrandPhotoPath/:fileName',brand.getPhotoPath); // Retrieve all Supplier app.get('/api/getAllBrand', brand.findAll); // Update a Supplier with Id app.put('/api/updateBrand/:brandId',upload.single('uploadfile'), brand.update); //Retrieve all Category by active app.get('/api/getBrandByActive',brand.findAllByActive); }<file_sep>module.exports = (sequelize, Sequelize) => { const Campaign = sequelize.define('tbl_campaign', { campaignName: { type: Sequelize.STRING }, headerLine1: { type: Sequelize.STRING }, bannerImage:{ type:Sequelize.STRING }, headerLine2: { type: Sequelize.STRING }, startDate: { type: Sequelize.DATE }, endDate: { type: Sequelize.DATE }, creationUser:{ type:Sequelize.STRING }, updatedUser:{ type: Sequelize.STRING }, active:{ type: Sequelize.BOOLEAN }, description:{ type: Sequelize.STRING } }, { freezeTableName:true, tableName:'tbl_campaign' }); return Campaign; }<file_sep>const db = require('../config/db.config.js'); const Ocassion = db.tbl_ocassion; const sequelize = db.sequelize; const path = require('../config/Global'); const fs = require('fs'); // Post a Ocassion exports.create = (req, res) => { if (req.file == undefined) { Ocassion.create({ ocassionName: req.body.ocassionName, description: req.body.description, active: req.body.active, isHomeDisplay:req.body.isHomeDisplay, creationUser:req.body.creationUser, ocassionImage: 'default-image.jpg', }).then(ocassion => { res.send(ocassion); }); } else { Ocassion.create({ ocassionName: req.body.ocassionName, description: req.body.description, creationUser:req.body.creationUser, active: req.body.active, isHomeDisplay:req.body.isHomeDisplay, ocassionImage: req.file.filename, }).then(ocassion => { res.send(ocassion); }); } }; exports.findAllByActive = (req, res) => { let query = `SELECT id as value, ocassionName as label ,ocassionImage as banner FROM tbl_ocassion where active = true `; sequelize.query(query, { type: sequelize.QueryTypes.SELECT }) .then(list => { res.send(list) }) } // show photo path exports.getPhotoPath = (req, res) => { const fileName = req.params.fileName; const mimeType = fileName.split('.')[1]; var staticResource = path.ocassionPhotoPath + fileName; fs.readFile(staticResource, (err, data) => { if (err) { console.log("Can't read file"); } res.writeHead(200, { 'Content-Type': mimeType }); res.end(data) }); }; // FETCH all Ocassion exports.findAll = (req, res) =>{ let query = `SELECT * FROM tbl_ocassion`; sequelize.query(query, { type: sequelize.QueryTypes.SELECT }) .then(list => { res.send(list) }) }; // Update a Ocassion exports.update = (req, res) => { const id = req.params.ocassionId; if (req.file == undefined) { Ocassion.update({ ocassionName: req.body.ocassionName, description: req.body.description, active: req.body.active,isHomeDisplay:req.body.isHomeDisplay, updatedUser:req.body.updatedUser }, { where: { id: req.params.ocassionId } } ).then(() => { res.status(200).send("updated successfully a ocassion with id = " + id); }); } else { Ocassion.update({ ocassionName: req.body.ocassionName,ocassionImage: req.file.filename, description: req.body.description,isHomeDisplay:req.body.isHomeDisplay, active: req.body.active,updatedUser:req.body.updatedUser }, { where: { id: req.params.ocassionId } } ).then(() => { res.status(200).send("updated successfully a ocassion with id = " + id); }); } }; exports.findAllOcassion = (req, res) => { let query = `SELECT id as value , ocassionName as label FROM tbl_ocassion where active = true `; sequelize.query(query, { type: sequelize.QueryTypes.SELECT }) .then(list => { res.send(list) console.log(list) }) }; <file_sep>const db = require('../config/db.config.js'); const RegisterUser = db.tbl_registeruser; var nodemailer = require('nodemailer'); var path = require('path'); var Promise= require('bluebird') const Email = require('email-templates'); var crypto =require('crypto'); //fetch register user exports.getAllRegisterUser = (req, res) => { RegisterUser.findAll().then(user => { res.send(user); }); }; // Check Phone Have or Not exports.checkPhone = (req, res) => { RegisterUser.findOne( { where: {registerPhone:req.body.phone} } ).then(user => { console.log(user) res.send(user); }); }; exports.checkUser = (req, res) => { var hash = crypto.createHash('md5').update(req.body.password).digest('hex'); RegisterUser.findOne( { where: {registerEmail:req.body.email,registerPassword:<PASSWORD>} } ).then(user => { if(user === null){ let data ={ id:null, } res.send(data); } else{ let data ={ id:user.id, name:user.registerName } res.send(data); } }); }; // var mailOptions = { // from: '<EMAIL>', // to: req.body.email, // subject: 'Happy to see you as a Shal Zay Member', // // text: 'Hello !' // }; // transporter.sendMail(mailOptions, function(error, info){ // if (error) { // console.log(error); // } else { // console.log('Email sent: ' + info.response); // } // }); //Add New Register User exports.AddNewRegisterUser = (req, res) => { console.log("newww") console.log(req.body.firstName) // var hash = crypto.createHash('md5').update(req.body.password).digest('hex'); // var transporter = nodemailer.createTransport({ // service: 'gmail', // auth: { // user: '<EMAIL>', // pass: '<PASSWORD>' // } // }); // var mailOptions = { // from: '<EMAIL>', // to: req.body.email, // subject: 'Happy to see you as a Shal Zay Member', // // text: 'Hello !' // }; // transporter.sendMail(mailOptions, function(error, info){ // if (error) { // console.log(error); // } else { // console.log('Email sent: ' + info.response); // } // }); // var templateDir = path.join(__dirname ,"../",'templates','testMailTemplate') // console.log('Hello'+templateDir) // const testMailTemplate = new Email ({ // views: { root: templateDir} // }) // var locals={ // userName:req.body.userName // } // testMailTemplate.render(locals, function(err,temp){ // console.log(temp) // if(err){ // console.log('error',err); // } // else{ // transporter.sendMail({ // form:'<EMAIL>', // to:req.body.email, // text:temp.text, // html:temp.html // },function(error, info){ // if(error){ // console.log(error); // } // console.log('message sent'+ info.response) // }) // } // }) // RegisterUser.create({ // registerName: req.body.userName, // registerEmail: req.body.email, // registerPhone: req.body.phone, // registerPassword: <PASSWORD>, // registerUserPoint:10, // creationUser:req.body.creationUser, // }).then(user => { // res.send(user); // }); }; exports.addNewUser = (req, res) => { var hash = crypto.createHash('md5').update(req.body.password).digest('hex'); RegisterUser.create({ registerName: req.body.firstName +" "+ req.body.lastName, registerEmail: req.body.email, registerPhone: req.body.phone, registerPassword: <PASSWORD>, registerUserPoint:10, active:true }).then(user => { let data ={ id:user.id, name:user.registerName } res.send(data); }); }; <file_sep>module.exports = (sequelize, Sequelize) => { const AdminUser = sequelize.define('tbl_adminuser', { userName: { type: Sequelize.STRING }, email: { type: Sequelize.STRING }, phone: { type: Sequelize.STRING }, gender: { type: Sequelize.STRING }, address: { type: Sequelize.STRING }, password: { type: Sequelize.STRING }, creationUser:{ type:Sequelize.STRING }, updatedUser:{ type: Sequelize.STRING }, active:{ type: Sequelize.BOOLEAN }, profileImage:{ type: Sequelize.STRING } }, { freezeTableName:true, tableName:'tbl_adminuser' }); return AdminUser; }<file_sep>const env = require('./env.js'); const Sequelize = require('sequelize'); const sequelize = new Sequelize(env.database, env.username, env.password, { host: env.host, dialect: env.dialect, operatorsAliases: false, pool: { max: env.max, min: env.pool.min, acquire: env.pool.acquire, idle: env.pool.idle } }); const db = {}; db.Sequelize = Sequelize; db.sequelize = sequelize; //Models/tables db.tbl_city = require('../model/city.model.js')(sequelize, Sequelize); db.tbl_adminuser = require('../model/adminUser.model.js')(sequelize, Sequelize); db.tbl_supplier = require('../model/supplier.model.js')(sequelize, Sequelize); db.tbl_campaign = require('../model/campaign.model.js')(sequelize, Sequelize); db.tbl_classs = require('../model/classs.modal.js')(sequelize, Sequelize); db.tbl_classs = require('../model/ocassion.model.js')(sequelize, Sequelize); db.tbl_category = require('../model/category.model.js')(sequelize, Sequelize); db.tbl_item = require('../model/item.model.js')(sequelize, Sequelize); db.tbl_subcategory =require('../model/subCategory.model.js')(sequelize, Sequelize); db.tbl_varientone = require('../model/varientOne.model.js')(sequelize, Sequelize); db.tbl_varienttwo = require('../model/varientTwo.model.js')(sequelize, Sequelize); db.tbl_itemprice= require('../model/itemPrice.model.js') (sequelize, Sequelize); db.tbl_itemphoto = require('../model/itemPhoto.model.js')(sequelize, Sequelize); db.tbl_registeruser = require('../model/registerUser.model')(sequelize, Sequelize); db.tbl_orderuser = require('../model/orderUser.model') (sequelize , Sequelize); db.tbl_orderitem = require('../model/orderItem.model.js')(sequelize, Sequelize); db.tbl_brand = require('../model/brand.model.js')(sequelize,Sequelize); db.tbl_shippingFee =require('../model/shippingFees.model.js')(sequelize,Sequelize); db.tbl_matchoutfititem = require('../model/matchOutfitItem.model') (sequelize, Sequelize); db.tbl_coupontype = require('../model/couponType.model') (sequelize, Sequelize); db.tbl_discountcoupon = require('../model/discountCoupon.model') (sequelize, Sequelize); db.tbl_your_confidence = require('../model/yourConfidence.model') (sequelize, Sequelize); //Relations // db.tbl_item.hasMany(db.tbl_itemprice, { foreignKey: 'item' }); // db.tbl_item.hasMany(db.tbl_varientone, { foreignKey: 'item' }); // db.tbl_varienttwo.belongsTo(db.tbl_item, { foreignKey: 'item',targetKey: 'id' }); // db.tbl_varientone.hasMany(db.tbl_itemprice, { foreignKey: 'varientOne' }); // db.tbl_itemprice.belongsTo(db.tbl_varienttwo, { foreignKey: 'varientTwo', targetKey: 'id' }); module.exports = db;<file_sep>const db = require('../config/db.config.js'); const Price = db.tbl_itemprice; const VarientOne = db.tbl_varientone; const VarientTwo = db.tbl_varienttwo; // Post a Price exports.create = (req, res) => { Price.findAll({ where: { item: req.body.item, varientOne: req.body.varientOne, varientTwo: req.body.varientTwo } }).then(price => { if (price.length === 0) { //Save to MySQL database Price.create({ item: req.body.item, price: req.body.price, quantity: req.body.quantity, itemCode: req.body.itemCode, varientOne: req.body.varientOne, varientTwo: req.body.varientTwo, creationUser: req.body.creationUser }).then(price => { res.send("success"); }); } else { res.status(401).send("fail"); } }) }; exports.findAll = (req, res) => { Price.findAll().then(price => { res.send(price); }); }; // exports.find = (req, res) => { // Price.findAll ({ // include:[{ // model:VarientOne, // through:{ // } // }], // // // include:[{ // // // model:VarientTwo // // // }], // // include:[{ // // model:Item // // }] // }).then (item => { // res.send(item) // }); // }; //Update Price exports.update = (req, res) => { const id = req.params.priceId; Price.update({ item: req.body.item, price: req.body.price, quantity: req.body.quantity, itemCode: req.body.itemCode, varientOne: req.body.varientOne, updatedUser: req.body.updatedUser, varientTwo: req.body.varientTwo }, { where: { id: req.params.priceId } } ).then(() => { res.status(200).send("updated successfully a price with id = " + id); }); }; exports.getPriceByItemId = (req, res) => { Price.findAll({ where: { item: req.params.itemId } }).then(price => { res.send(price); }) } exports.getPriceById = (req, res) => { Price.findOne({ where: { id: req.params.id } }).then(price => { res.send(price); }) } exports.getItemPrice = (req, res) => { Price.findAll({ where: { item: req.params.itemId } }).then(item => { res.send(item) }) } exports.getItemStock = (req, res) => { console.log(req.body) Price.find({ where: { id: req.body.priceId } }).then(price => { res.send(price) }) } // exports.getItemStockInCart= (req, res) => { // var newitemlist=[]; // var itemlist = req.body; // for(var i=0; i< itemlist.length; i++){ // Price.find({ // where: { id:itemlist[i].priceId } // }).then(price => { // var nodedata = price.quantity; // console.log(nodedata) // // console.log(price.quantity) // // newitemlist.push(price.quantity) // }) // } // } exports.getItemStockInCart = async (req, res) => { var itemlist = req.body; let price = [] for (var i = 0; i < itemlist.length; i++) { price[i] = await Price.find({ where: { id: itemlist[i].priceId } }) // console.log(price.quantity) } res.send(price) } exports.getItemStockWithVarient = (req, res) => { VarientOne.findAll({ where: { item: req.params.itemId }, attributes: ['id', 'varientNameOne', 'varientGroupNameOne', 'varientOneImage'], include: [{ model: Price, attributes: ['id', 'discountPrice', 'price', 'varientTwo', 'quantity', 'itemCode'], // this may not be needed include: [{ model: VarientTwo, attributes: ['varientNameTwo', 'varientGroupNameTwo'] }] }] }).then(item => { res.status(200).json(item) }) } // get price for varient by one item id exports.getPriceForVarientByItemId = (req, res) => { var query = "select p.discountPrice as discount, p.price as price," + " vone.varientNameOne, vone.varientGroupNameOne, vone.varientOneImage," + " vtwo.varientNameTwo, vtwo.varientGroupNameTwo" + " from shal_zay.tbl_itemPrices as p" + " left join shal_zay.tbl_varientOnes as vone" + " on (p.varientOne = vone.id and p.varientOne > 0)" + " left join shal_zay.tbl_varientTwos as vtwo" + " on (p.varientTwo = vtwo.id and p.varientTwo >0)" + " where p.item = " + req.params.itemId; sequalize.query(query, { type: sequalize.QueryTypes.SELECT }).then(price => { res.send(price); }) } <file_sep>module.exports = (sequelize, Sequelize) => { const orderItem = sequelize.define('tbl_orderitem', { priceId: { type: Sequelize.INTEGER }, orderItemId: { type: Sequelize.INTEGER }, orderUserId: { type: Sequelize.INTEGER }, itemQty: { type: Sequelize.INTEGER }, totalPrice: { type: Sequelize.DOUBLE }, varientOneId: { type: Sequelize.INTEGER }, varientTwoId:{ type:Sequelize.INTEGER } }, { freezeTableName: true, tableName: 'tbl_orderitem'// to fix table }); return orderItem; } <file_sep>module.exports = function(app) { const adminUser = require('../controller/adminUser.controller'); const upload = require('../config/adminuser.multer.config'); // Create a new AdminUser app.post('/api/addAdminUser',upload.single('uploadfile'), adminUser.create); // Retrieve all AdminUser app.get('/api/getAllAdminUser', adminUser.findAll); // Show Profile Photo Path app.get('/api/getAdminPhotoPath/:fileName',adminUser.getPhotoPath); //Update a AdminUser with Id app.put('/api/updateAdminUser/:adminId',upload.single('uploadfile'), adminUser.updateAdmin); //Check username and password app.get('/api/checkAccount/:userName/:password',adminUser.check); }<file_sep>module.exports = function(app) { const price = require('../controller/itemPrice.controller'); // Retrieve all Price app.get('/api/getAllPrice', price.findAll); // Create a new price app.post('/api/addNewPrice', price.create); //Update price app.put('/api/updatePrice/:priceId', price.update); //get item and price app.get('/api/getItemPrice/:itemId', price.getItemPrice); //Retrieve Price By Item Id app.get('/api/getPriceByItemId/:itemId', price.getPriceByItemId); //Retrieve price for varient by item id app.get('/api/price/getPriceForVarientByItemId/:itemId', price.getPriceForVarientByItemId); //Retrieve Price By price Id app.get('/api/getPriceById/:id', price.getPriceById); //Retrieve Item Stock By price Id app.post('/api/getItemStock', price.getItemStock); //Retrieve Item Stock in whole cart app.post('/api/getItemStockInCart', price.getItemStockInCart); }<file_sep>module.exports = (sequelize, Sequelize) => { const itemPhoto = sequelize.define('tbl_itemphoto', { itemId:{ type:Sequelize.INTEGER }, photoName: { type: Sequelize.STRING }, }, { freezeTableName:true, tableName:'tbl_itemphoto' }); return itemPhoto; }<file_sep>module.exports = function(app) { const classs = require('../controller/classs.controller.js'); // Create a new classs app.post('/api/addNewClasss', classs.create); // Retrieve all classs app.get('/api/getAllClasss', classs.findAll); // Update a classs with Id app.put('/api/updateClasss/:classsId', classs.update); //Retrieve all Classs by active app.get('/api/getClasssByActive', classs.findAllByActive); } <file_sep>const db = require('../config/db.config.js'); const Supplier = db.tbl_supplier; const sequelize = db.sequelize; // Post a Supplier exports.create = (req, res) => { console.log(req.body) // Save to MySQL database Supplier.create({ supplierName: req.body.supplierName, email:req.body.email, address:req.body.address, phone:req.body.phone, description: req.body.description, active:req.body.active, creationUser:req.body.creationUser }).then(supplier => { res.send(supplier); }); }; //testing exports.selectTesting = (req,res) => { sequelize.query('SELECT * FROM tbl_suppliers', { replacements: ['active'], type: sequelize.QueryTypes.SELECT } ).then(supplier => { res.send(supplier) }) } // FETCH all Supplier exports.findAll = (req, res) => { Supplier.findAll().then(supplier => { res.send(supplier); }); }; exports.findAllByActive = ( req,res) => { Supplier.findAll({ where:{ active:true }} ).then(supplier =>{ res.send(supplier); }); } // Update a Supplier exports.update = (req, res) => { const id = req.params.supplierId; Supplier.update( { supplierName: req.body.supplierName, email:req.body.email, address:req.body.address, phone:req.body.phone, description:req.body.description, active:req.body.active, updatedUser:req.body.updatedUser }, { where: {id: req.params.supplierId} } ).then(() => { res.status(200).send("updated successfully a supplier with id = " + id); }); }; <file_sep>module.exports = (sequelize, Sequelize) => { const YourConfidence = sequelize.define('tbl_your_confidence', { modelImage:{ type: Sequelize.STRING }, modelName:{ type: Sequelize.STRING }, }, { freezeTableName:true, tableName:'tbl_your_confidence' }); return YourConfidence; }<file_sep>const db = require('../config/db.config'); const OrderItem = db.tbl_orderitem; const OrderUser = db.tbl_orderuser; const sequelize = db.sequelize; const {photoPath,itemPhotoPath} = require('../config/Global'); const Price = db.tbl_itemprice; const fs = require('fs'); exports.setOrderItem = (req, res) => { var user = req.body.user; var item = req.body.item; OrderUser.create({ userId: user.id, address: req.body.address, billingAddress:req.body.billingAddress, description: req.body.description, grandTotal:req.body.grandTotal }).then(u => { for ( var i = 0 ; i< item.length; i++) { OrderItem.create({ priceId: item[i].priceId, orderItemId: item[i].itemId, orderUserId: u.id, itemQty: item[i].itemCount, totalPrice:item[i].amount, varientOneId:item[i].varientOneId, varientTwoId:item[i].varientTwoId } ).then(order => { res.send("success"); }); } }) } exports.getOrderUser = (req, res) => { var query = "SELECT u.id, u.userId,r.registerName, u.description,u.address,u.billingAddress FROM tbl_orderuser as u"+ " inner join tbl_registeruser as r on r.id = u.userId"; sequelize.query(query, { type: sequelize.QueryTypes.SELECT }).then(orderUser => { res.send(orderUser); }) } exports.getItemPhoto = (req, res) => { var query ="SELECT ordItem.id ,photo.photoName,'item' as Status FROM tbl_orderitem as ordItem inner join"+ " tbl_item as item on ordItem.orderItemId = item.id inner join"+ " tbl_itemphoto as photo on photo.itemId = item.id where orderItemId="+req.body.itemId +" group by itemId" sequelize.query(query,{ type:sequelize.QueryTypes.SELECT }).then(photo => { res.send(photo) }) } exports.getOrderPhoto = (req, res) => { if(req.body.voneId == null || req.body.vtwoId == null) { var query ="SELECT ordItem.id ,photo.photoName,'item' as Status FROM tbl_orderitem as ordItem inner join"+ " tbl_item as item on ordItem.orderItemId = item.id inner join"+ " tbl_itemphoto as photo on photo.itemId = item.id where orderItemId="+req.body.itemId +" group by itemId" sequelize.query(query,{ type:sequelize.QueryTypes.SELECT }).then(photo => { res.send(photo) }) } else{ var query ="SELECT ordItem.id , vone.varientOneImage,'varient' as Status FROM tbl_orderitem as ordItem inner join"+ " tbl_item as item on ordItem.orderItemId = item.id inner join"+ " tbl_varientone as vone on item.id = vone.item inner join"+ " tbl_varienttwo as vtwo on item.id = vtwo.item group by id" sequelize.query(query,{ type:sequelize.QueryTypes.SELECT }).then(photo => { res.send(photo) }) } } exports.getOrderItem = (req, res) => { const id = req.params.id; var query = "SELECT ordItem.id,ordItem.orderUserId,item.itemName,item.id as itemId, vone.id as voneId, vtwo.id as vtwoId,price.price,ordItem.totalPrice,ordItem.itemQty,vone.varientNameOne, vtwo.varientNameTwo"+ " FROM tbl_orderitem as ordItem inner join"+ " tbl_item as item on ordItem.orderItemId=item.id inner join"+ " tbl_itemprice as price on ordItem.priceId = price.id left join"+ " tbl_varientone as vone on vone.item = item.id left join" + " tbl_varienttwo as vtwo on vtwo.item = item.id where ordItem.orderUserId="+ id +" group by ordItem.id" sequelize.query(query,{ type:sequelize.QueryTypes.SELECT }).then(orderItem => { res.send(orderItem) }) // OrderItem.findAll( // { where: {orderUserId:id} } // ).then(item => { // res.send(item) // }); } exports.getOrderPhotoURL = (req, res) => { const fileName = req.params.fileName; const mimeType = fileName.split('.')[1]; var staticResource=itemPhotoPath+fileName; fs.readFile(staticResource,(err, data)=> { if(err){ console.log("Can't read file"); } res.writeHead(200, {'Content-Type': mimeType}); res.end(data) }); }; exports.getOrderPhotoURLHasNoVarient = (req, res) => { const fileName = req.params.fileName; const mimeType = fileName.split('.')[1]; var staticResource= itemPhotoPath +fileName; fs.readFile(staticResource,(err, data)=> { if(err){ console.log("Can't read file"); } res.writeHead(200, {'Content-Type': mimeType}); res.end(data) }); };<file_sep>const db = require('../config/db.config.js'); const Brand = db.tbl_brand; const { photoPath } = require('../config/Global'); const fs = require('fs'); // Post a Category exports.create = (req, res) => { if (req.file == undefined) { Brand.create({ brandNameMM: req.body.brandNameMM, brandNameEg: req.body.brandNameEg, description: req.body.description, active: req.body.active, creationUser:req.body.creationUser, brandImage: 'default-image.jpg', }).then(brand => { res.send(brand); }); } else { Brand.create({ brandNameMM: req.body.brandNameMM, brandNameEg: req.body.brandNameEg, description: req.body.description, creationUser:req.body.creationUser, active: req.body.active, brandImage: req.file.filename, }).then(brand => { res.send(brand); }); } }; exports.findAllByActive = (req, res) => { Brand.findAll({ where: { active: true } } ).then(brand => { res.send(brand); }); } // show photo path exports.getPhotoPath = (req, res) => { const fileName = req.params.fileName; console.log(fileName) const mimeType = fileName.split('.')[1]; console.log(fileName); var staticResource = photoPath + fileName; fs.readFile(staticResource, (err, data) => { if (err) { console.log("Can't read file"); } res.writeHead(200, { 'Content-Type': mimeType }); res.end(data) }); }; // FETCH all Category exports.findAll = (req, res) => { Brand.findAll().then(brand => { res.send(brand); }); }; // Update a Category exports.update = (req, res) => { const id = req.params.brandId; if (req.file == undefined) { Brand.update({ brandNameMM: req.body.brandNameMM, brandNameEg: req.body.brandNameEg, description: req.body.description, active: req.body.active, updatedUser:req.body.updatedUser }, { where: { id: id} } ).then(() => { res.status(200).send("updated successfully a brand with id = " + id); }); } else { Brand.update({ brandNameMM: req.body.brandNameMM, brandNameEg: req.body.brandNameEg, brandImage: req.file.filename, description: req.body.description, active: req.body.active,updatedUser:req.body.updatedUser }, { where: { id: id } } ).then(() => { res.status(200).send("updated successfully a brand with id = " + id); }); } }; <file_sep>module.exports = (sequelize, Sequelize) => { const discountCoupon = sequelize.define('tbl_discountcoupon', { id: { type: Sequelize.INTEGER, primaryKey: true, autoIncrement: true }, couponName: { type: Sequelize.STRING }, couponCode:{ type: Sequelize.STRING }, couponTypeId:{ type: Sequelize.INTEGER }, amount:{ type:Sequelize.DOUBLE }, active:{ type:Sequelize.BOOLEAN } }, { freezeTableName:true, tableName:'tbl_discountcoupon' }); return discountCoupon; }<file_sep>const db = require('../config/db.config.js'); const varientOne = db.tbl_varientOne; module.exports = (sequelize, Sequelize) => { const itemPrice = sequelize.define('tbl_itemprice', { item: { type: Sequelize.INTEGER }, price:{ type: Sequelize.DOUBLE }, quantity:{ type:Sequelize.INTEGER }, itemCode:{ type:Sequelize.INTEGER }, varientOne:{ type:Sequelize.INTEGER }, varientTwo:{ type:Sequelize.INTEGER }, creationUser:{ type:Sequelize.STRING }, updatedUser:{ type: Sequelize.STRING }, }, { freezeTableName:true, tableName:'tbl_itemprice' }); return itemPrice; }<file_sep>module.exports = function(app) { const subscriber = require('../controller/subscriber.controller'); }<file_sep> const db = require('../config/db.config.js'); const Sequelize = require('sequelize'); const Op = Sequelize.Op; const Price = db.tbl_itemprice; const VarientOne = db.tbl_varientone; const VarientTwo = db.tbl_varienttwo; const fs = require('fs'); const { upload } = require('../config/Global'); // FETCH all Varient One exports.varientOneFindAll = (req, res) => { VarientOne.findAll().then(varient => { res.send(varient); }); }; // FETCH all Varient One exports.varientTwoFindAll = (req, res) => { VarientTwo.findAll().then(varient => { res.send(varient); }); }; // FETCH all Varient One exports.getVarientOneByItem = (req, res) => { VarientOne.findAll({ where: { item: req.params.itemId } }).then(varient => { res.send(varient); }); }; // FETCH all Varient One exports.getVarientTwoByItem = (req, res) => { VarientTwo.findAll( { where: { item: req.params.itemId } }).then(varient => { res.send(varient); }); }; //Post a Varient One exports.createVarientOne = (req, res) => { //Save to MySQL database if (req.file == undefined) { VarientOne.findAll({ where: { varientNameOne: req.body.varientNameOne, item:req.body.item } }).then(list => { if (list.length > 0) res.status(500).send("fail"); else { VarientOne.create({ item: req.body.item, varientOneImage: 'default-image.jpg', varientGroupNameOne: req.body.varientGroupNameOne, varientNameOne: req.body.varientNameOne, creationUser: req.body.creationUser }).then(varient => { res.send("success"); }); } }) } else { VarientOne.findAll({ where: { varientNameOne: req.body.varientNameOne, item:req.body.item } }).then(list => { if (list.length > 0) res.status(500).send("fail"); else { VarientOne.create({ item: req.body.item, varientOneImage: req.file.filename, varientGroupNameOne: req.body.varientGroupNameOne, varientNameOne: req.body.varientNameOne, creationUser: req.body.creationUser }).then(varient => { res.status(200).send("success"); }); } }) } } //Post a Varient Two exports.createVarientTwo = (req, res) => { // Save to MySQL database VarientTwo.findAll({ where: { varientNameTwo: req.body.varientNameTwo, item:req.body.item } }).then(list => { if (list.length > 0) res.status(500).send("fail"); else { VarientTwo.create({ item: req.body.item, varientGroupNameTwo: req.body.varientGroupNameTwo, varientNameTwo: req.body.varientNameTwo, creationUser: req.body.creationUser }).then(varient => { res.send("success"); }); } }) } // show photo path exports.getPhotoPath = (req, res) => { const fileName = req.params.fileName; const mimeType = fileName.split('.')[1]; var staticResource = item_upload + fileName; fs.readFile(staticResource, (err, data) => { if (err) { console.log("Can't read file"); } res.writeHead(200, { 'Content-Type': mimeType }); res.end(data) }); }; // Update Varient One2 exports.updateVarientOne = (req, res) => { const id = req.params.varientId; if (req.file == undefined) { VarientOne.update({ item: req.body.item, varientNameOne: req.body.varientNameOne, varientGroupNameOne: req.body.varientGroupNameOne, updatedUser: req.body.updatedUser }, { where: { id: req.params.varientId } } ).then(() => { res.status(200).send("updated successfully a varientOne with id = " + id); }); } else { VarientOne.update({ item: req.body.item, varientNameOne: req.body.varientNameOne, varientGroupNameOne: req.body.varientGroupNameOne, varientOneImage: req.file.filename, updatedUser: req.body.updatedUser }, { where: { id: req.params.varientId } } ).then(() => { res.status(200).send("updated successfully a varientOne with id = " + id); }); } }; exports.updateVarientTwo = (req, res) => { const id = req.params.varientId; VarientTwo.update({ item: req.body.item, varientNameTwo: req.body.varientNameTwo, varientGroupNameTwo: req.body.varientGroupNameTwo, updatedUser: req.body.updatedUser }, { where: { id: req.params.varientId } } ).then(() => { res.status(200).send("updated successfully a varientTwo with id = " + id); }); }; exports.getVarientWithPrice = (req, res) => { VarientOne.findAll({ where: { item: req.params.itemId }, attributes: ['id', 'varientNameOne', 'varientGroupNameOne', 'varientOneImage'], include: [{ model: Price, attributes: ['id', 'discountPrice', 'price', 'varientTwo', 'quantity'], // this may not be needed include: [{ model: VarientTwo, attributes: ['varientNameTwo', 'varientGroupNameTwo'] }] }] }).then(item => { res.status(200).json(item) }) } // }; // // Post a Varient // exports.create = (req, res) => { // var vG2=null; // if(req.body.varientGroupNameTwo == undefined) // { // vG2 = vG2 // } // else{ // vG2= req.body.varientGroupNameTwo // } // // Save to MySQL database // if(req.file ==undefined) // { // Varient.create({ // item: req.body.item, // quantity:req.body.quantity, // price:req.body.price, // varientOneImage:'default-image.jpg', // discountPrice:req.body.discountPrice, // varientGroupNameOne:req.body.varientGroupNameOne, // varientNameOne: req.body.varientNameOne, // varientGroupNameTwo:vG2, // varientNameTwo:req.body.varientNameTwo, // description:req.body.description // }).then(varient => { // res.send(varient); // }); // } // else{ // Varient.create({ // item: req.body.item, // quantity:req.body.quantity, // price:req.body.price, // varientOneImage:req.file.filename, // discountPrice:req.body.discountPrice, // varientGroupNameOne:req.body.varientGroupNameOne, // varientNameOne: req.body.varientNameOne, // varientGroupNameTwo:req.body.varientGroupNameTwo, // varientNameTwo:req.body.varientNameTwo, // description:req.body.description // }).then(varient => { // res.send(varient); // }); // } // }; // exports.getVareintByGroup = ( req,res) => { // const varientName=req.params.varientName; // Varient.findAll({ // where:{ // [Op.and]: // [{varientNameOne:varientName}, // {varientGroupNameTwo: // {[Op.ne]:'null'} // } // ] // }} // ).then(varient =>{ // res.send(varient); // }); // } // exports.update = (req, res) => { // const id = req.params.varientId; // console.log(req.file) // if( req.file == undefined){ // Varient.update( { item: req.body.item,quantity:req.body.quantity,price:req.body.price,discountPrice:req.body.discountPrice, // varientNameOne:req.body.varientNameOne,varientGroupNameOne:req.body.varientGroupNameOne,description:req.body.description, // varientGroupNameTwo:req.body.varientGroupNameTwo,varientNameTwo:req.body.varientNameTwo}, // { where: {id: req.params.varientId} } // ).then(() => { // res.status(200).send("updated successfully a varient with id = " + id); // }); // } // else{ // Varient.update( { item: req.body.item,quantity:req.body.quantity,price:req.body.price,discountPrice:req.body.discountPrice, // varientNameOne:req.body.varientNameOne,varientGroupNameOne:req.body.varientGroupNameOne,varientGroupNameTwo:req.body.varientGroupNameTwo, // varientOneImage:req.file.filename,varientNameTwo:req.body.varientNameTwo,description:req.body.description}, // { where: {id: req.params.varientId} } // ).then(() => { // res.status(200).send("updated successfully a varient with id = " + id); // }); // } // }; // exports.getVarientByItemId = (req, res) => { // Varient.findAll({ // where: { item: req.params.itemId } // }) // .then(varient => { // res.send(varient); // }); // }
8fd07b1bb48115ff6985143b85f0eb8ef9f7cae5
[ "JavaScript" ]
42
JavaScript
pawanjaiswal18/rene_api_2020
f370910e1b6877c57f8d787a5efac0e68e078df3
36fe5d0d36b917c3f9d5de57c2b21a703449b0a4
refs/heads/master
<file_sep>import "reflect-metadata"; import { Query, Resolver, buildSchema } from "type-graphql"; import express, { Application } from "express"; import { ApolloServer } from "apollo-server-express"; import { GraphQLSchema } from "graphql"; @Resolver() class HelloResolver { @Query(() => String) async helloWorld(): Promise<string> { return "Hello world!"; } } export const createApolloServer = async (): Promise<ApolloServer> => { const schema: GraphQLSchema = await buildSchema({ resolvers: [HelloResolver] }); const apolloServer: ApolloServer = new ApolloServer({ schema, playground: true, }); return apolloServer; }; export const createExpressServer = async (path = "/graphql"): Promise<Application> => { const app: Application = express(); const apolloServer = await createApolloServer(); apolloServer.applyMiddleware({ app, path }); return app; }; <file_sep><h1 align="center">🌐 Opinionated Sapper project base</h1> ## ❓ What is this? The site that builds from this repository can be found [here](https://fir-sapper-tailwindcss.web.app/). This is an extremely opinionated Sapper project base intended for my own use. That being said, there is quite a bit of work put into it to make it generalized and adaptable to your own setup, given that you want to use *most* of these things. The lower something is on this list, the easier it is to reconfigure or remove: * [Sapper for Svelte](https://sapper.svelte.dev/) * [Firebase](https://firebase.google.com/) * [Functions](https://firebase.google.com/docs/functions/) for Server Side Rendering (SSR) * [Hosting](https://firebase.google.com/docs/hosting) * Thanks to [`sapper-firebase-starter`](https://github.com/Eckhardt-D/sapper-firebase-starter) * [TypeScript](https://www.typescriptlang.org/) * [TypeGraphQL](https://typegraphql.ml/) * Inside Svelte components, thanks to [`svelte-preprocess`](https://github.com/kaisermann/svelte-preprocess) * [PostCSS](https://postcss.org/) * [Tailwind CSS](https://tailwindcss.com/) * [PurgeCSS](https://www.purgecss.com/) * [CSSNano](https://cssnano.co/) * Inside Svelte components, thanks to [`svelte-preprocess`](https://github.com/kaisermann/svelte-preprocess) * [GitHub Actions](https://github.com/features/actions) * Automatic building and deployment (to Firebase), triggered on commits to master * [ESLint](https://eslint.org/) * [VS Code Plugin](https://marketplace.visualstudio.com/items?itemName=dbaeumer.vscode-eslint) ## 📋 Copy Choose either to clone or fork depending on your preference. ### 🐑 Clone ```sh git clone https://github.com/babichjacob/sapper-firebase-typescript-graphql-tailwindcss-actions-template ``` ### 🍴 Fork Click the `Use this template` button on [this project's GitHub page](https://github.com/babichjacob/sapper-firebase-typescript-graphql-tailwindcss-actions-template). ## 🛠 Usage ### 🔄 Development ```sh npm run dev ``` ### 🔥 Deployment to Firebase This will create a production build for you before deploying. ```sh npm run deploy ``` ## ⚙ Configuration ### 🔥 Firebase and 🐙 GitHub Actions The least you should need to do to get started is to edit `.firebaserc`, changing the project ID to *your* project (initialized in the [Firebase console](https://console.firebase.google.com/)) ID. For automatic building and deployment to work, you need to generate [a CI login token from Firebase](https://firebase.google.com/docs/cli#cli-ci-systems): ```sh firebase login:ci # If this doesn't work, try node_modules/.bin/firebase login:ci ``` Then, go to your repository's Settings > Secrets. Copy the result of the command above and save it as a Secret named `FIREBASE_TOKEN`. You can test if it's working by making a commit to `master` and checking the Actions tab of your repository to see if your project successfully builds and deploys to Firebase. ### 🕸️ TypeGraphQL Edit the `namedExports` in `rollup.config.js` for `"type-graphql"` [when you need to import something from the library](https://github.com/MichalLytek/type-graphql/issues/378). ## 😵 Help! I have a question [Create an issue](https://github.com/babichjacob/sapper-firebase-typescript-graphql-tailwindcss-actions-template/issues/new) and I'll try to help. ## 😡 Fix! There is something that needs improvement [Create an issue](https://github.com/babichjacob/sapper-firebase-typescript-graphql-tailwindcss-actions-template/issues/new) or [pull request](https://github.com/babichjacob/sapper-firebase-typescript-graphql-tailwindcss-actions-template/pulls) and I'll try to fix. I'm sorry, because of my skill level and the fragility of (the combination of) some of these tools, there are likely to be problems in this project. Thank you for bringing them to my attention or fixing them for me. ## 📄 License MIT *** _This README was generated with ❤️ by [readme-md-generator](https://github.com/kefranabg/readme-md-generator)_ <file_sep>// This is ONLY used for VS Code IntelliSense const preprocess = require("svelte-preprocess"); module.exports = { preprocess: preprocess() }; <file_sep>import { Request as ExpressRequest, Response as ExpressResponse } from "express"; // eslint-disable-next-line max-len export const get = async (req: ExpressRequest, res: ExpressResponse): Promise<void> => { res.end("you made a get request"); }; // eslint-disable-next-line max-len export const post = async (req: ExpressRequest, res: ExpressResponse): Promise<void> => { res.end("you made a post request"); }; <file_sep>import * as sapper from "@sapper/server"; import compression from "compression"; import sirv from "sirv"; import { createExpressServer } from "./graphql/index.ts"; const { PORT, NODE_ENV } = process.env; const dev = NODE_ENV === "development"; const createSapperAndApolloServer = async (dev_) => { const app = await createExpressServer(); if (dev_) app.use(compression({ threshold: 0 }), sirv("static", { dev: true })); app.use(sapper.middleware()); return app; }; if (dev) { createSapperAndApolloServer(true).then((app) => { app.listen(PORT, (err) => { if (err) console.log("error", err); }); }); } export { createSapperAndApolloServer, sapper }; <file_sep>/* Tailwind - The Utility-First CSS Framework A project by <NAME> (@adamwathan), <NAME> (@reinink), <NAME> (@davidhemphill) and <NAME> (@steveschoger). View the full documentation at https://tailwindcss.com. */ /* eslint-disable global-require */ module.exports = { theme: { extend: { spacing: { 72: "18rem", 96: "24rem", 128: "32rem", }, }, }, corePlugins: { placeholderColor: false, }, variants: {}, plugins: [ require("@tailwindcss/ui"), ], }; <file_sep>{ "compilerOptions": { "target": "es2016", "lib": [ "es2016", "esnext.asynciterable" ], "typeRoots": [ "node_modules/@types", ], "types": [ "@pyoner/svelte-types", ], "allowSyntheticDefaultImports": true, "alwaysStrict": true, "experimentalDecorators": true, "emitDecoratorMetadata": true, "esModuleInterop": true, "moduleResolution": "node", "noImplicitAny": true, "noImplicitThis": true, "noImplicitReturns": true, "noUnusedLocals": true, "strictBindCallApply": true, "strictNullChecks": true, "strictFunctionTypes": true, "strictPropertyInitialization": true } }
577e85bb49812615b2c56b3dda1f1ed8be23c63c
[ "Markdown", "TypeScript", "JavaScript", "JSON with Comments" ]
7
TypeScript
lgs/sapper-firebase-typescript-graphql-tailwindcss-actions-template
0bbdd4872906c143afeb42575089acbb386dfc0b
25be0bcd4c97edbad17c6be9722755690a04a9c0
refs/heads/master
<file_sep>package com.mogujie.coverflowsample; import android.app.Activity; import android.content.Context; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.widget.TextView; import com.dolphinwang.imagecoverflow.CoverFlowAdapter; import com.dolphinwang.imagecoverflow.CoverFlowView; public class MyActivity extends Activity { protected static final String VIEW_LOG_TAG = "CoverFlowDemo"; private TextView bottomtitle; int index=0; private Handler handler = new Handler() { @Override public void handleMessage(Message msg) { super.handleMessage(msg); } }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); View v = LayoutInflater.from(this).inflate(R.layout.activity_main, null, false); setContentView(v); final CoverFlowView<MyCoverFlowAdapter> mCoverFlowView = (CoverFlowView<MyCoverFlowAdapter>) findViewById(R.id.coverflow); bottomtitle= (TextView) findViewById(R.id.bottomtitle); MyCoverFlowAdapter adapter = new MyCoverFlowAdapter(this); mCoverFlowView.setAdapter(adapter); mCoverFlowView.setSelection(0); handler.postDelayed(new Runnable() { @Override public void run() { if (index < 3) { mCoverFlowView.setSelection(index); } index++; if(index<3) handler.postDelayed(this,500); } }, 500); mCoverFlowView.setCoverFlowListener(new CoverFlowView.CoverFlowListener<MyCoverFlowAdapter>() { @Override public void imageOnTop(CoverFlowView<MyCoverFlowAdapter> view, int position, float left, float top, float right, float bottom) { Log.e(VIEW_LOG_TAG, position + " on top!"); } @Override public void topImageClicked(CoverFlowView<MyCoverFlowAdapter> view, int position) { Log.e(VIEW_LOG_TAG, position + " clicked!"); } @Override public void invalidationCompleted() { } }); mCoverFlowView.setTopImageLongClickListener(new CoverFlowView.TopImageLongClickListener() { @Override public void onLongClick(int position) { Log.e(VIEW_LOG_TAG, "top image long clicked == >" + position); } }); } class MyCoverFlowAdapter extends CoverFlowAdapter { public MyCoverFlowAdapter(Context context) { image1 = BitmapFactory.decodeResource(context.getResources(), R.drawable.icon1_youxi_da); image2 = BitmapFactory.decodeResource(context.getResources(), R.drawable.icon1_shipin_da); image3 = BitmapFactory.decodeResource(context.getResources(), R.drawable.icon1_zhaopian_da); } private Bitmap image1 = null; private Bitmap image2 = null; private Bitmap image3 = null; @Override public int getCount() { return 3; } @Override public Bitmap getImage(final int position) { if(position == 0){ bottomtitle.setText("你不曾感受的空间"); return image1; }else if(position == 1){ bottomtitle.setText("你从未见过的画面"); return image2; } bottomtitle.setText("另一个世界,就在眼前"); return image3; } } } <file_sep>include ':app', ':coverflowsample' <file_sep># ImageCoverFlow #### To show Cover Flow effect on Android ImageCoverFlow is an open source Android library that allows developers to easily create applications with a cover flow effect to show images. This library does not extend Gallery. Feel free to use it all you want in your Android apps provided that you cite this project and include the license in your app. **Note**: looping mode is currently supported, non-looping mode will be supported later. ![Oops! The screenshot is missing!](https://github.com/dolphinwang/ImageCoverFlow/raw/master/imagecoverflow_screenshot.png) #### ImageCoverFlow is currently used in some published Android apps: 1. [ICardEnglish](https://play.google.com/store/apps/details?id=com.cn.icardenglish&hl=zh_CN) --- # How to Use: #### Step One: Add `CoverFlowView` to your project 1. Via XML: ```xml <com.dolphinwang.imagecoverflow.CoverFlowView xmlns:imageCoverFlow="http://schemas.android.com/apk/res-auto" android:id="@+id/coverflow" android:layout_width="match_parent" android:layout_height="match_parent" android:paddingLeft="20dp" android:paddingRight="20dp" imageCoverFlow:coverflowGravity="center_vertical" imageCoverFlow:coverflowLayoutMode="wrap_content" imageCoverFlow:enableReflection="true" imageCoverFlow:reflectionGap="10dp" imageCoverFlow:reflectionHeight="30%" imageCoverFlow:reflectionShaderEnable="true" imageCoverFlow:visibleImage="5" /> ``` 2. Programatically (via Java): ```java CoverFlowView<MyCoverFlowAdapter> mCoverFlowView = (CoverFlowView<MyCoverFlowAdapter>) findViewById(R.id.coverflow); mCoverFlowView.setCoverFlowGravity(CoverFlowGravity.CENTER_VERTICAL); mCoverFlowView.setCoverFlowLayoutMode(CoverFlowLayoutMode.WRAP_CONTENT); mCoverFlowView.enableReflection(true); mCoverFlowView.setReflectionHeight(30); mCoverFlowView.setReflectionGap(20); mCoverFlowView.enableReflectionShader(true); mCoverFlowView.setVisibleImage(5); ``` **TIP**: If you want to support different movement speeds on different screen densities, you can use method `setScreenDensity()`. Otherwise CoverFlow will have a unified movement speed. --- #### Step Two: Set an adapter, which extends `CoverFlowAdapter`: ```java MyCoverFlowAdapter adapter = new MyCoverFlowAdapter(this); mCoverFlowView.setAdapter(adapter); ``` **TIPS**: * Method `setAdapter()` should be called after all properties of CoverFlow are settled. * If you want to load image dynamically, you can call method `notifyDataSetChanged()` when bitmaps are loaded. #### Step Three: if you want to listen for the click event of the top image, you can set a `CoverFlowListener` to it: ```java mCoverFlowView.setCoverFlowListener(new CoverFlowListener<MyCoverFlowAdapter>() { @Override public void imageOnTop(CoverFlowView<MyCoverFlowAdapter> view, int position, float left, float top, float right,float bottom) { // TODO } @Override public void topImageClicked(CoverFlowView<MyCoverFlowAdapter> view, int position) { // TODO } }); ``` If you want to listen for long click events of the top image, you can set a `TopImageLongClickListener` to it: ```java mCoverFlowView .setTopImageLongClickListener(new CoverFlowView.TopImageLongClickListener() { @Override public void onLongClick(int position) { Log.e(VIEW_LOG_TAG, "top image long clicked ==> " + position); } }); ``` Users can use method `setSelection()` to show a specific position at the top. --- #### If you want to subclass `CoverFlowView` 1. You can override method `getCustomTransformMatrix()` to make more transformations for images (there is some annotated code which shows how to make image y-axis rotation). 2. You should never override method `onLayout()` to layout any of `CoverFlowView`’s children, because all of image will draw on the canvas directly. --- #### Developed By: <NAME> (<EMAIL>) If you use this library, please let me know. --- #### License: Copyright 2013 <NAME> 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.
d0b4942fc8339f2b87c9bc1808bf75e28d260daf
[ "Markdown", "Java", "Gradle" ]
3
Java
Maliola/ImageCoverFlow-master
d29ebb437106b5c61b28c6e98d273714fcb63718
142f9ca806727b1139a1e9fb24ced4a9cf921a4e
refs/heads/master
<file_sep>package calculator_momentum; import javax.el.ELContext; import javax.faces.bean.ManagedBean; import javax.faces.bean.ManagedProperty; import javax.faces.bean.SessionScoped; import javax.faces.context.FacesContext; import javax.script.ScriptEngine; import javax.script.ScriptEngineManager; import calculator.calculations.calculations; import calculator.entities.User; @ManagedBean @SessionScoped public class basicBean { private double first_value; private double second_value; private String operator; private double result; private String message; public double getFirst_value() { return first_value; } public void setFirst_value(double first_value) { this.first_value = first_value; } public double getSecond_value() { return second_value; } public void setSecond_value(double second_value) { this.second_value = second_value; } public String getOperator() { return operator; } public void setOperator(String operator) { this.operator = operator; } public double getResult() { return result; } public void setResult(double result) { this.result = result; } public String getMessage() { return message; } public void setMessage(String message) { this.message = message; } public void calculate() { try { //concatenate equation string String equation = getFirst_value() + getOperator() + getSecond_value(); //get actual value of string using js ScriptEngineManager manager = new ScriptEngineManager(); ScriptEngine se = manager.getEngineByName("JavaScript"); Object actualvalue = se.eval(equation); setResult(Double.parseDouble(actualvalue.toString())); ELContext elContext = FacesContext.getCurrentInstance().getELContext(); loginBean lb = (loginBean) FacesContext.getCurrentInstance().getApplication().getELResolver().getValue(elContext, null, "loginBean"); //save calculation to db calculations calc = new calculations(); User user = new User(); user.setUserId(lb.getUserId()); calc.saveCalculations(user, equation, actualvalue.toString()); setMessage(""); } catch (Exception e) { setMessage("Error"); e.printStackTrace(); } } } <file_sep>package calculator.calculations; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import javax.ejb.LocalBean; import javax.ejb.Stateless; import calculator.database.Database; import calculator.entities.User; /** * Session Bean implementation class calculations */ @Stateless(mappedName = "calculations") @LocalBean public class calculations implements calculationsLocal { @Override public void saveCalculations(User user, String equation, String result) { PreparedStatement ps = null; int resultRows = 0; try { Class.forName(Database.driver).newInstance(); Connection connection = DriverManager.getConnection(Database.url, Database.username, Database.password); ps = connection.prepareStatement(Database.saveCalculation); ps.setString(1,equation); ps.setString(2,result); ps.setLong(3,user.getUserId()); resultRows = ps.executeUpdate(); if (resultRows > 0) { } } catch(Exception ex) { ex.printStackTrace(); } } } <file_sep>package calculator.users; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import javax.ejb.LocalBean; import calculator.database.Database; import calculator.entities.User; import javax.ejb.Stateless; /** * Session Bean implementation class UsersBean */ @Stateless(mappedName = "UsersBean") @LocalBean public class UsersBean implements UsersBeanLocal { public UsersBean() {} @Override public User getUser(User attempting_user) { User foundUser = new User(); PreparedStatement ps = null; ResultSet result = null; try { Class.forName(Database.driver).newInstance(); Connection connection = DriverManager.getConnection(Database.url, Database.username, Database.password); ps = connection.prepareStatement(Database.fetchUser); ps.setString(1,attempting_user.getUsername()); ps.setString(2, attempting_user.getPassword()); result = ps.executeQuery(); if (result.next()) { foundUser.setUserId(result.getLong("id")); foundUser.setUsername(result.getString("user_name")); foundUser.setName(result.getString("name")); foundUser.setSurname(result.getString("surname")); foundUser.setAdmin(result.getBoolean("is_admin")); } } catch (Exception e) { e.printStackTrace(); } return foundUser; } @Override public User getUserbyUserName(String userName) { User foundUser = new User(); PreparedStatement ps = null; ResultSet result = null; try { Class.forName(Database.driver).newInstance(); Connection connection = DriverManager.getConnection(Database.url, Database.username, Database.password); ps = connection.prepareStatement(Database.fetchUserByUserName); ps.setString(1,userName); result = ps.executeQuery(); if (result.next()) { foundUser.setUserId(result.getLong("id")); foundUser.setUsername(result.getString("user_name")); foundUser.setName(result.getString("name")); foundUser.setSurname(result.getString("surname")); foundUser.setAdmin(result.getBoolean("is_admin")); } } catch (Exception e) { e.printStackTrace(); } return foundUser; } } <file_sep>package calculator_momentum; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.List; import javax.faces.bean.ManagedBean; import javax.faces.bean.SessionScoped; import calculator.admin.AdminBean; import calculator.entities.Calculation; import calculator.entities.User; import calculator.users.UsersBean; @ManagedBean @SessionScoped public class adminPageBean { private String username; private Date dateFrom; private Date dateTo; private List<Calculation> calculations; private String searchMessage; public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public Date getDateFrom() { return dateFrom; } public void setDateFrom(Date dateFrom) { this.dateFrom = dateFrom; } public Date getDateTo() { return dateTo; } public void setDateTo(Date dateTo) { this.dateTo = dateTo; } public List<Calculation> getCalculations() { return calculations; } public void setCalculations(List<Calculation> calculations) { this.calculations = calculations; } public String getSearchMessage() { return searchMessage; } public void setSearchMessage(String searchMessage) { this.searchMessage = searchMessage; } public void search() { try { Long userId = null; if (getUsername() != null && !getUsername().equalsIgnoreCase("")) { //get user UsersBean userBean = new UsersBean(); User resultUser = userBean.getUserbyUserName(getUsername()); userId = resultUser.getUserId(); } //at least one of the fields must not be null if (userId != null || getDateFrom() != null || getDateTo() != null) { //get calculations according to criteria AdminBean adminBean = new AdminBean(); List<Calculation> resultCalculations = adminBean.searchCalculationsByCriteria(userId, getDateFrom(), getDateTo()); //setList of calculations setCalculations(resultCalculations); //clear error message setSearchMessage("success"); } else { setSearchMessage("Failed"); List<Calculation> resultCalculations = new ArrayList(); setCalculations(resultCalculations); } } catch (Exception e) { List<Calculation> resultCalculations = new ArrayList(); setCalculations(resultCalculations); setSearchMessage("Failed"); e.printStackTrace(); } } } <file_sep>package calculator.entities; import java.util.Date; public class Calculation { private Long calcId; private String calcRequested; private String calcAnswer; private Long userId; private String userName; private String calcDate; public Calculation(){} public Long getCalcId() { return calcId; } public void setCalcId(Long calcId) { this.calcId = calcId; } public String getCalcRequested() { return calcRequested; } public void setCalcRequested(String calcRequested) { this.calcRequested = calcRequested; } public String getCalcAnswer() { return calcAnswer; } public void setCalcAnswer(String calcAnswer) { this.calcAnswer = calcAnswer; } public Long getUserId() { return userId; } public void setUserId(Long userId) { this.userId = userId; } public String getCalcDate() { return calcDate; } public void setCalcDate(String calcDate) { this.calcDate = calcDate; } public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } } <file_sep>package calculator.database; public class Database { //for db connection public static final String url = "jdbc:mariadb://calculatordb.coho3ghuvsx5.eu-west-3.rds.amazonaws.com/momentum_calculatordb"; public static final String driver = "org.mariadb.jdbc.Driver"; public static final String username = "ottilia"; public static final String password = "<PASSWORD>"; //users public static final String fetchUser = "SELECT * FROM users WHERE user_name = ? AND password = ?;"; public static final String fetchUserByUserName = "SELECT * FROM users WHERE user_name = ?;"; //calculations public static final String saveCalculation = "INSERT INTO calculation (calculation_requested, calculation_answer, user_id, calculation_date) VALUES (?, ?, ?, NOW());"; //admin public static final String searchCalculations = "SELECT cl.*, us.user_name FROM calculation cl left join users us on cl.user_id = us.id WHERE user_id is not null"; public static final String searchCalculationsbyUserId = "SELECT * FROM calculation WHERE user_id = ?;"; } <file_sep>package etrxasas; //package calculator_momentum; // //import java.io.Serializable; //import javax.persistence.*; //import javax.validation.constraints.NotNull; //import javax.validation.constraints.Size; //import javax.persistence.Entity; ///** // * Entity implementation class for Entity: users // * // */ //@Entity //@Table(name = "users") //public class usersEntity implements Serializable { // // private static final long serialVersionUID = 1L; // // @Id // @Basic(optional = false) // @NotNull // @Size(min = 1, max = 11) // @Column(name = "id", nullable = false) // private Long id; // // @Basic(optional = false) // @NotNull // @Size(min = 1, max = 50) // @Column(name = "user_name", nullable = false, length = 50) // private String user_name; // // @Basic(optional = false) // @NotNull // @Size(min = 1, max = 50) // @Column(name = "name", nullable = false, length = 50) // private String name; // // @Basic(optional = false) // @NotNull // @Size(min = 1, max = 50) // @Column(name = "surname", nullable = false, length = 50) // private String surname; // // @Basic(optional = false) // @NotNull // @Size(min = 1, max = 50) // @Column(name = "password", nullable = false, length = 50) // private String password; // // @Basic(optional = false) // @NotNull // @Size(min = 1, max = 1) // @Column(name = "is_admin", nullable = false, length = 1) // private int is_admin; // // public usersEntity() { // super(); // } // // public Long getId() { // return id; // } // // public void setId(Long id) { // this.id = id; // } // // public String getUser_name() { // return user_name; // } // // public void setUser_name(String user_name) { // this.user_name = user_name; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public String getSurname() { // return surname; // } // // public void setSurname(String surname) { // this.surname = surname; // } // // public String getPassword() { // return password; // } // // public void setPassword(String password) { // this.password = <PASSWORD>; // } // // public int getIs_admin() { // return is_admin; // } // // public void setIs_admin(int is_admin) { // this.is_admin = is_admin; // } // //}
0a84567683990b9a805f8922127f0ceb3cf267fe
[ "Java" ]
7
Java
Ottilia/calculator
565d3ecd618b3e8619f32341974a2c8037b604d2
111ab940755f9fdef0401bab4c8a86923c942329
refs/heads/master
<file_sep>* <tt>cp amazon_api_keys.rb.sample amazon_api_keys.rb</tt> * rewrite amazon_api_keys.rb * <tt>ruby tropicana.rb</tt> <file_sep>require 'amazon/ecs' require './amazon_api_keys' print 'Input ASIN : ' asin = gets.chomp res = Amazon::Ecs.item_lookup(asin, response_group: 'ItemAttributes, Images', country: 'jp') if res.has_error? puts 'ERROR! Input corrent ASIN' else res.items.each do |item| puts "ASIN : #{item.get('ASIN')}" puts "price : #{item.get('ItemAttributes/ListPrice/Amount')}" puts "image_url : #{item.get('SmallImage/URL')}" end end
b740f05619ad20d87c163ca3d4167959084467ac
[ "Markdown", "Ruby" ]
2
Markdown
to0526/tropicana_cui
1ec3681afc8609a2bdfcdad103308ac535c18fb5
e1bb9f7fdfa316583fd49ac9a86db2c4f6b9a4ff
refs/heads/main
<file_sep># User_CRUD To run app and open SwaggerAPI: 1. cd back & npm install 2. npm run start:dev 3. Go to http://localhost:3000/api<file_sep>import { Body, Controller, Delete, Get, Param, Post, Put } from '@nestjs/common'; import { ApiParam, ApiTags } from '@nestjs/swagger'; import { CreateUserDto } from './dto/create-user.dto'; import { EditUserDto } from './dto/edit-user.dto'; import { UserDto } from './dto/user.dto'; import { UsersService } from './users.service'; @Controller('users') @ApiTags('Users') export class UsersController { constructor( private readonly usersService: UsersService, ) {} @Post() public async createUser(@Body() createUser: CreateUserDto): Promise<any> { return this.usersService.createUser(createUser); } @Put(':id') @ApiParam({ name: 'id', type: 'string' }) public async editUser(@Param('id') id: string, @Body() editUser: EditUserDto): Promise<any> { return this.usersService.editUser(id, editUser); } @Delete(':id') @ApiParam({ name: 'id', type: 'string' }) public async deleteUser(@Param('id') id: string): Promise<string> { return this.usersService.deleteUser(id); } @Get(':id') @ApiParam({ name: 'id', type: 'string' }) public async getOneUser(@Param('id') id: string): Promise<UserDto> { return this.usersService.findOne(id); } @Get() public async getAll(): Promise<UserDto[]> { return this.usersService.findAll(); } } <file_sep>import { BadRequestException, Injectable, NotFoundException } from '@nestjs/common'; import { SESSenderService } from 'src/mail-sender/ses-sender.service'; import { CreateUserDto } from './dto/create-user.dto'; import { EditUserDto } from './dto/edit-user.dto'; import { UserDto } from './dto/user.dto'; const crypto = require("crypto"); const users = [ ]; @Injectable() export class UsersService { constructor( private readonly sESSenderService: SESSenderService, ) {} public async createUser(createUserDto: CreateUserDto): Promise<UserDto> { const check = users.find((u) => u.email === createUserDto.email); if (check) { throw new BadRequestException('User already exists'); } const newUser = { ...createUserDto, id: crypto.randomBytes(16).toString("hex") }; users.push(newUser); // await this.sESSenderService.sendMail(createUserDto.email, 'CreateUserTemplate', { firstName: createUserDto.firstName }); return newUser; } public async editUser(id: string, editUserDto: EditUserDto): Promise<UserDto> { const userIndex = users.find((u) => u.id === id) if (userIndex !== -1) { users[userIndex] = { ...editUserDto, id: users[userIndex].id }; } throw new NotFoundException('User not found'); } public async deleteUser(id: string): Promise<string> { const userIndex = users.find((u) => u.id === id) if (userIndex !== -1) { users.splice(userIndex, 1); } else { throw new NotFoundException('User not found'); } return id; } public async findOne(id: string): Promise<UserDto> { const user = users.find((u) => u.id === id); if (!user) { throw new NotFoundException('User not found'); } return user; } public async findAll(): Promise<UserDto[]> { return users; } } <file_sep>import { Injectable, BadRequestException, NotFoundException } from '@nestjs/common'; import * as aws from 'aws-sdk'; aws.config.update({ region: process.env.AWS_SES_REGION }); @Injectable() export class SESSenderService { constructor( ) {} mailName = '<EMAIL>'; public adjustTemplateData(templateData: any): string { const props = Object.entries(templateData).map(([key, value]) => `\"${key}\":\"${value}\"`); return `{ ${props.join(',')} }`; } public async sendMail(email: string, mailTemplate: string, templateData: any): Promise<any> { const params = { Destination: { ToAddresses: [email] }, Source: this.mailName, Template: mailTemplate, TemplateData: this.adjustTemplateData(templateData), ReplyToAddresses: [this.mailName], } const sendPromise = new aws.SES({ apiVersion: '2010-12-01', region: 'region', credentials: { accessKeyId: 'key', secretAccessKey: 'secret' } }).sendTemplatedEmail(params).promise(); return sendPromise.then((data) => { return data; }).catch((err) => { return err; }); } public async sendMails(mailTemplate: string, emailsData: any[]): Promise<any> { const params = { Source: this.mailName, Template: mailTemplate, Destinations: emailsData.map((item) => { const { email, ...rest } = item; return { Destination: { ToAddresses: [email] }, ReplacementTemplateData: this.adjustTemplateData(rest) }; }), DefaultTemplateData: this.adjustTemplateData({ name: 'user' }), } const sendPromise = new aws.SES({ apiVersion: '2010-12-01', region: 'region', credentials: { accessKeyId: 'key', secretAccessKey: 'secret' } }).sendBulkTemplatedEmail(params).promise(); sendPromise.then((data) => { console.log(data); }).catch((err) => { console.error(err, err.stack); }); } }<file_sep>import { Module } from '@nestjs/common'; import { SESSenderService } from './ses-sender.service'; @Module({ providers: [SESSenderService], exports: [SESSenderService], }) export class MailSenderModule {} <file_sep>import { ApiProperty } from "@nestjs/swagger"; export class CreateUserDto { @ApiProperty({ example: '<EMAIL>' }) email: string; @ApiProperty({ example: '<PASSWORD>' }) password: string; @ApiProperty({ example: 'firstName' }) firstName: string; }
94078560a1347fa20f1e5b4712e45d9ff7e372e1
[ "Markdown", "TypeScript" ]
6
Markdown
viktarkhaliava/User_CRUD
a73d3e95f5440729360512f2f954686f4ed04451
aeb8bc77782754f239745b76478eaedea72715a4
refs/heads/master
<repo_name>sarupbanskota/cexperiments<file_sep>/A Tutorial Introduction/wordoutperline.c #include <stdio.h> /* Prints the input out to standard output, one word per line (quite rough). */ # define IN 1 # define OUT 0 main(){ char c; int STATE=OUT; c = getchar(); while (c != EOF){ if (c == ' ' || c == '\n' || c == '\t') STATE=OUT; else if (STATE == OUT) { STATE=IN; printf("\n"); } if (STATE == IN) putchar(c); c = getchar(); } } <file_sep>/A Tutorial Introduction/ftoc_function.c #include <stdio.h> /* converts from fahr to celcius using a function */ float convert(float fahr){ return (fahr-32) * 5/9; } main(){ float c, f; int lower, step, upper; lower = 0; step = 20; upper = 300; printf("Program that prints a list of fahr to celcius converts!\n"); while ( f <= upper ){ c = convert(f); printf("%3.0f \t %6.1f \n", f, c); f = f + step; } } <file_sep>/A Tutorial Introduction/findeof.c /* This program prints the value of EOF. We take an int input and putchar. */ #include <stdio.h> main(){ int input; while ((input = getchar()) != EOF){ ; } printf("%d", input); } <file_sep>/Notes.md Overall notes from K&R. <file_sep>/A Tutorial Introduction/equateEOF.c #include <stdio.h> /* confirms that getchar() != EOF is either 0 or 1 */ main(){ printf("%d", (getchar() != EOF)); } <file_sep>/A Tutorial Introduction/histogram_horizontal.c #include <stdio.h> /* Prints histograms of lengths of words in input */ int main(){ int count; char c; c=getchar(); while(c!=EOF){ if(c==' ' || c== '\n'){ while(count--){ printf("*"); } printf("\n"); } else count+=1; c=getchar(); } return 0; } <file_sep>/A Tutorial Introduction/blanktabsnewlines.c #include <stdio.h> /* Program that counts blanks, tabs and newlines, and reports the number to standard output */ main(){ int character, bc, tc, nc; bc=tc=nc = 0; character = getchar(); while (character != EOF){ if (character == ' ') ++bc; if (character == '\t') ++tc; if (character == '\n') ++nc; character = getchar(); } printf("%3d blanks \n%3d tabs \n%3d newlines \n", bc, tc, nc); } <file_sep>/A Tutorial Introduction/stripblanks.c #include <stdio.h> /* Program that prints output to standard output after stripping off extra blank spaces */ #define INBLANK 1 #define OUTBLANK 0 main(){ char c; int STATE=OUTBLANK; c = getchar(); while (c != EOF){ if (STATE == INBLANK && c == ' ') ; /* one space to another - do nothing */ else if (STATE == INBLANK && c != ' ') { /* moving from space to word */ STATE=OUTBLANK; putchar(c); } else if (STATE == OUTBLANK && c == ' ') { /* first space after word */ STATE=INBLANK; putchar(c); } else putchar(c); /* inside a word */ c = getchar(); } } <file_sep>/A Tutorial Introduction/remove_trailing_white.c #include <stdio.h> /* program that removes all trailing blankspaces and tabs off standard input, line by line */ #define MAXLENGTH 1000 void remove_trailing_whitespaces(char line[], int length){ int i; for(i=length-1;i>=0;i--){ if(line[i]== ' ' && line[i]== '\t' ) --length; else if(line[i]!='\0' ) break; } line[length]='\0'; for(i=0;i<length;i++){ printf("%c",line[i]); } } int getnextline(char line[]){ int i; char c; for(i=0;(i<MAXLENGTH-1) && ((c=getchar())!=EOF) && (c!='\n');i++){ line[i]=c; } line[i]='\0'; return i; } int main(){ int i,len; char nextline[MAXLENGTH]; while( (len = getnextline(nextline)) > 0){ remove_trailing_whitespaces(nextline,len); printf("\n"); } return 0; } <file_sep>/A Tutorial Introduction/ftoc.c #include <stdio.h> main(){ float c, f; int lower, step, upper; lower = 0; step = 20; upper = 300; printf("Program that prints a list of fahr to celcius converts!\n"); while ( f <= upper ){ c = (f - 32) * 5/9; printf("%3.0f \t %6.1f \n", f, c); f = f + step; } } <file_sep>/A Tutorial Introduction/vertical_histogram.c #include <stdio.h> /* Prints a vertical histogram of the lengths of words in standard input */ #define MAXLENGTH 10 char HISTOGRAM[MAXLENGTH][MAXLENGTH]; int main(){ char c; int i=MAXLENGTH-1; int k; int j=0; for(k=0;k<MAXLENGTH && (c=getchar())!=EOF;k++){ if(c!='\n' && c!=' '){ HISTOGRAM[i][j]='*'; i--; } else{ j++; i=MAXLENGTH-1; } } printf("\n"); for(i=0;i<MAXLENGTH;i++){ for(j=0;j<MAXLENGTH;j++){ printf("%c ", HISTOGRAM[i][j]); } printf("\n"); } return 0; } <file_sep>/A Tutorial Introduction/ftocreversefor.c /* This program prints fahr to celcius, but in reverse. Using a for loop this time. */ #include <stdio.h> #define LOWER 0 #define UPPER 300 #define STEP 20 main(){ int fahr; for(fahr = UPPER; fahr >= LOWER; fahr = fahr - STEP){ printf("%3d \t %6.1f \n", fahr, (5.0/9.0)*(fahr-32)); } } <file_sep>/A Tutorial Introduction/ChapterNotes.c Notes for this chapter. <file_sep>/A Tutorial Introduction/reverse_string.c #include <stdio.h> /* program that reverses strings line by line, taken from standard input */ #define MAXLENGTH 1000 void reverse_print(char line[], int len){ char temp; int i; for(i=0;i<len/2;i++){ temp=line[i]; line[i]=line[len-i-1]; line[len-i-1]=temp; } for(i=0;i<=len;i++){ printf("%c", line[i]);} printf("\n"); } int getnextline(char line[]){ int i; char c; for(i=0;(i<MAXLENGTH-1) && ((c=getchar())!=EOF) && (c!='\n');i++){ line[i]=c; } line[i]='\0'; return i; } int main(){ int i,len; char nextline[MAXLENGTH]; while( (len = getnextline(nextline)) > 0 ){ reverse_print(nextline,len); printf("\n"); } return 0; } <file_sep>/A Tutorial Introduction/character_frequency.c #include <stdio.h> /* Prints a histogram of frequencies of characters */ int main(){ int frequency[26]={0}; char c; int num; c=getchar(); while(c!=EOF){ num = c-'a'; if(num >=0 && num < 26){ frequency[num]+=1; } c=getchar(); } for(num=0;num<26;num++){ printf("%c ", num+'a'); while(frequency[num]--){ printf("*"); } printf("\n"); } return 0; } <file_sep>/README.md cexperiments ============ This repository contains some solutions to questions from [the book on C by Kerninghan and Ritchie](http://bit.ly/1xDYXcc) (While I was playing around with some C). Similar to my [SPOJ repository](https://github.com/sarupbanskota/SPOJ), I mainly started this repository to pick up some version control skills, so you'll probably find it to be inactive now. <file_sep>/A Tutorial Introduction/printgt80.c #include <stdio.h> /* program that prints all input lines greater than 80 characters while(there's another line) get next line if it is over 80 chars, print it. */ #define MAXLENGTH 1000 int getnextline(char line[]){ int i; char c; for(i=0;(i<MAXLENGTH-1) && ((c=getchar())!=EOF) && (c!='\n');i++){ line[i]=c; } line[i]='\0'; return i; } int main(){ int i,len; char nextline[MAXLENGTH]; while( (len = getnextline(nextline)) > 80 ){ for(i=0;i<len;i++){ printf("%c", nextline[i]); } printf("\n"); } return 0; } <file_sep>/A Tutorial Introduction/printescapes.c #include <stdio.h> /* Prints input to standard output, indicating escape characters wherever they occur. */ main(){ char c; c = getchar(); while (c != EOF){ if (c == '\t') printf("\\t"); else if (c == '\b') printf("\\b"); else if (c == '\\') printf("\\"); else putchar(c); c = getchar(); } }
c316323cbae3a3818eae0e7aefe12fe832c31956
[ "Markdown", "C" ]
18
C
sarupbanskota/cexperiments
95f545752facad49fdfc045f2c820dc1742b32d4
d4cc15c1bc98e07d25d33bbc50f0386e4d5854af
refs/heads/master
<file_sep># Snake-CPP Terminal Based Graphic less snake game Movement = Arrow keys Game Over case = touch your own body or leave the area <file_sep>#include <iostream> #include<conio.h> #include<windows.h> #include<ctime> #define KEY_UP 72 #define KEY_DOWN 80 #define KEY_LEFT 75 #define KEY_RIGHT 77 using namespace std; COORD coord = {0,0}; void gotoxy(int x, int y){ coord.X = x; coord.Y = y; SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), coord); } struct snake{ int x; int y; snake* next; }*head; void add_snake(int x, int y){ snake* node = new snake; snake* last = head; while(last->next != NULL) last = last->next; last->next = node; node->x = x; node->y = y; node->next = NULL; } int* remove_snake(){ snake *temp = head; int xy[] = {head->x, head->y}; head = head->next; delete temp; return xy; } int snake_size(){ int counter = 0; snake *temp = head; while(temp->next != NULL){ temp = temp->next; counter ++; } return counter; } bool snake_collision(int x, int y){ snake* temp = head; while(temp->next != NULL){ if(temp->x == x && temp->y == y) return true; temp = temp->next; } return false; } int x = 20; int dx = 1; int y = 10; int dy = 0; int apple_x; int apple_y; bool apple_eaten = true; int snake_length = 5; int score = 0; char c; char direction = 'r'; bool running = true; int main(){ head = new snake; head->x = x; head->y = y; head->next = NULL; long timer = GetTickCount(); int frames = 0; while(running){ if(apple_eaten){ srand(time(NULL)); apple_x = rand()%79 + 1; apple_y = rand()%23 + 2; gotoxy(apple_x, apple_y); cout << "#"; apple_eaten = false; } gotoxy(1,1); cout << "SCORE : " << score; gotoxy(x, y); cout << "*"; gotoxy(500, 500); if(kbhit()) c = getch(); switch(c){ case KEY_UP: if(direction != 'd'){ dx = 0; dy = -1; direction = 'u'; } break; case KEY_DOWN: if(direction != 'u'){ dx = 0; dy = 1; direction = 'd'; } break; case KEY_LEFT: if(direction != 'r'){ dx = -1; dy = 0; direction = 'l'; } break; case KEY_RIGHT: if(direction != 'l'){ dx = 1; dy = 0; direction = 'r'; } break; } x += dx; y += dy; add_snake(x, y); if(snake_size() > snake_length){ int* xy = remove_snake(); gotoxy(*xy, *(xy + 1)); cout << " "; } if(snake_collision(x, y)) running = false; if(x == apple_x && y == apple_y){ apple_eaten = true; snake_length++; score += 10; } if(x > 80 || x < 0 || y > 24 || y < 0) running = false; Sleep(30); frames++; if(GetTickCount() - timer >= 1000){ timer += 1000; gotoxy(35, 1); cout << "fps : " << frames; frames = 0; } } system("cls"); gotoxy(30,12); cout << "Game Over !!!"; gotoxy(30,13); cout << "Your score : " << score; getch(); Sleep(2000); return 0; }
99e92c81bbffe0f0151e60a11a1090866d239a0a
[ "Markdown", "C++" ]
2
Markdown
nikunjarora12345/Snake-CPP
79421c80b601a30c947e4a3d21a98527004d3f86
cc9246d4b6095fb1ab80c7fc74e3d2a754191365
refs/heads/main
<repo_name>YevheniiVolosiuk/new-slider<file_sep>/js/main.js const downButton = document.querySelector('.down-button'); const upButton = document.querySelector('.up-button'); const sideabar = document.querySelector('.sidebar'); const container = document.querySelector('.container'); const mainSlide = document.querySelector('.main-slide'); const slidersCount = mainSlide.querySelectorAll('div').length; sideabar.style.top = `-${(slidersCount - 1) * 100}vh` upButton.addEventListener('click', () => { changeSlide('up') }); downButton.addEventListener('click', () => { changeSlide('down') }); document.addEventListener('keydown', (event) => { if (event.key == 'ArrowUp') { changeSlide('up') } else if (event.key == 'ArrowDown') { changeSlide('down') } }) let activeSlideIndex = 0; function changeSlide(direction) { if (direction === 'up') { activeSlideIndex++ if (activeSlideIndex === slidersCount) { activeSlideIndex = 0 } } else if (direction === 'down') { activeSlideIndex-- if (activeSlideIndex < 0) { activeSlideIndex = slidersCount - 1 } } const height = container.clientHeight mainSlide.style.transform = `translateY(-${activeSlideIndex * height}px)` sideabar.style.transform = `translateY(${activeSlideIndex * height}px)` }
0c00ab7c4482450859f82e2fceb2302083f4699c
[ "JavaScript" ]
1
JavaScript
YevheniiVolosiuk/new-slider
0cdad8a0b05dcf7e8f76bb225ab11d04a5291074
c570e25b54bf2d80180c0685addcba68795824c5
refs/heads/master
<file_sep>var data = { COMMA: { name: '<NAME>', food: ['comida saludable', 'comida vegetariana', 'café', 'ensaladas'], address: 'Av. <NAME> Belaúnde 276, San Isidro 15073', price: 'S/.20 a S/.30', image: '../assets/images/comma.jpg' }, KFC: { name: 'KFC', food: ['nuggets', 'pollo frito', 'twister', 'hot wings'], address: 'Av. Alfredo Benavides 5240, Santiago de Surco 15039', price: 'S/.10 a S/.60', image: '../assets/images/kfc.jpg' }, PUNTOAZUL: { name: '<NAME>', food: ['ceviche', 'comida criolla', 'arroz con mariscos'], address: 'Av. Alfredo Benavides 2711, Miraflores 15048', price: 'S/.25 a S/.40', image: '../assets/images/puntoazul.jpg' }, DONBEL: { name: '<NAME>', food: ['pollo a la brasa', 'anticuchos', 'parrillas'], address: 'Av. Paseo de la Republica 6147, Miraflores 15047', price: 'S/.16 a S/.35', image: '../assets/images/donbel.jpg' }, CHILIS: { name: 'Chilis', food: ['comida mexicana', 'tortillas', 'hamburguesa', 'fajitas', 'costillas'], address: 'Av. Alfredo Benavides 1780, Miraflores 15048', price: 'S/.16 a S/.45', image: '../assets/images/chilis.jpg' }, DONVITO: { name: '<NAME>', food: ['comida italiana', 'pastas', 'pizza', 'lasagna', 'pesto'], address: 'Martin Dulanto Street, Martin Dulanto 111, Miraflores Lima 18', price: 'S/.20 a S/.30', image: '../assets/images/donvito.jpg' }, MANTRA: { name: 'Mantra Indian Cuisine', food: ['comida india', 'kebab', 'vegetariano', 'pollo', 'cordero'], address: 'Avenida Alfredo Benavides, 1761, Miraflores 15048', price: 'S/.18 a S/.34', image: '../assets/images/mantra.jpg' }, TANTA: { name: 'Tanta', food: ['comida criolla', 'comida peruana', 'comida fusión', 'arroz con pollo', 'lomo saltado', 'salchipapa'], address: 'Av Vasco Núñez de Balboa 660, Miraflores 15074', price: 'S/.20 a S/.45', image: '../assets/images/tanta.jpg' }, WASABI: { name: '<NAME>', food: ['sushi', 'comida japonesa', 'makis', 'rolls'], address: '18, Av Mariscal La Mar 1292, Miraflores 15074', price: 'S/.45 All You Can Eat', image: '../assets/images/wasabi.jpg' }, DELICASS: { name: 'Delicass', food: ['postres', 'sandwich', 'café', 'tartas'], address: 'Malecón Balta, Miraflores 15074', price: 'S/.8 a S/.25', image: '../assets/images/delicass.jpg' } };<file_sep># Foodmap Foodmap es un aplicativo que localiza los restaurantes cercanos y los muestra en Google Maps. Además cuenta con una data local de restaurantes con información relevante como dirección, precios y comida que ofrece. ![Foodmap](https://fotos.subefotos.com/ffc18bf90f1a60202d2e70ddfc969423o.png) ## Desarrollado para [Laboratoria](http://laboratoria.la) El objetivo de este reto es desarrollar una web-app que contenga un filtro para restaurantes. La aplicación fue desarrollada utilizando una data para la información de los restaurantes, Bootstrap 3 y jQuery. ## Flujo de aplicación La pantalla principal de la aplicación muestra un filtro de búsqueda y las opciones de restaurantes. Las palabras que se ingresen el filtro de búsqueda serán comparadas con la comida que se ofrece en cada restaurante o con el nombre de este, según la data local de la que se dispone. ![](assets/docs/vista2.png) Al hacer click en las miniaturas, aparece un modal que muestra la información de cada restaurante, así como su ubicación en el mapa. ![](assets/docs/vista3.png) <file_sep>$(document).ready(function() { setTimeout(function() { $('body').fadeOut(1000, function() { $(location).attr('href', 'views/home.html'); }); }, 2000); });
c087c104c9f5d28c83132b4a20d4b76b2a8a2b07
[ "JavaScript", "Markdown" ]
3
JavaScript
AndreaChumioque/foodmap
eed679ea6b7d73bc9512187dc2057d25ebb9d7e6
96fd61e7fb62eb5f43b259e290fda0da81ea0497
refs/heads/main
<repo_name>victorakpokiro/Splice-Site-Prediction<file_sep>/utils/plot.py from matplotlib import pyplot as plt class Plot(object): """docstring for plot""" tableau20 = [(31, 119, 180), (174, 199, 232), (255, 127, 14), (255, 187, 120), (44, 160, 44), (152, 223, 138), (214, 39, 40), (255, 152, 150), (148, 103, 189), (197, 176, 213), (140, 86, 75), (196, 156, 148), (227, 119, 194), (247, 182, 210), (127, 127, 127), (199, 199, 199), (188, 189, 34), (219, 219, 141), (23, 190, 207), (158, 218, 229)] @staticmethod def setup_graph(x_width=12, y_width=9, font_size=16): plt.figure(figsize=(x_width, y_width)) ax = plt.subplot(111) ax.spines["top"].set_visible(False) ax.spines["bottom"].set_visible(True) ax.spines["right"].set_visible(False) ax.spines["left"].set_visible(True) ax.get_xaxis().tick_bottom() ax.get_yaxis().tick_left() plt.yticks(fontsize=font_size) plt.xticks(fontsize=font_size) #plt.tick_params(axis="both", which="both", bottom="on", top="off", #labelbottom="on", left="on", right="off", labelleft="on") return plt @staticmethod def plot_time_series(x_data, y_data, fig_path_name, x_title, y_title, title, tags='b-',color_index=0): Plot.setup_graph() t = Plot.tableau20[color_index%len(Plot.tableau20)] t2 = tuple(ti/255 for ti in t) plt.plot(x_data, y_data,tags,color=t2) #plt.plot(x_data, y_data,tags,color=t2) plt.suptitle(title) plt.xlabel(x_title) plt.ylabel(y_title) #plt.legend(bbox_to_anchor=(0,1),loc="upper left") plt.savefig(fig_path_name, bbox_inches='tight') plt.show()<file_sep>/utils/file_types.py from enum import Enum class File_type(Enum): ZIP = 1 TAR = 2<file_sep>/model.py import numpy as np import torch import torch.nn as nn import torch.nn.functional as F from torch.utils.data import DataLoader from torch.utils import data # from torchvision import datasets # from torchvision.transforms import ToTensor, Lambda from sklearn.model_selection import train_test_split class Net(nn.Module): def __init__(self): super(Net, self).__init__() self.conv1 = nn.Conv2d(400, 4, 9) self.conv2 = nn.Conv2d(4, 1, 1) self.conv3 = nn.Conv2d(1, 128, 3, padding=1, bias=False) self.conv4R = nn.Conv2d(128, 128, 3, padding=1, bias=False) self.conv5 = nn.Conv2d(128, 1, 3, padding=1, bias=False) self.relu = nn.ReLU(inplace=True) # He initialization for m in self.modules(): if isinstance(m, nn.Conv2d): nn.init.kaiming_normal_(m.weight, mode='fan_out', nonlinearity='relu') def forward(self, x): x = self.relu(self.conv1(x)) x = self.relu(self.conv2(x)) residual = x x2 = self.conv3(x) out = x2 for _ in range(25): out = self.conv4R(self.relu(self.conv4R(self.relu(out)))) out = torch.add(out, x2) out = self.conv5(self.relu(out)) out = torch.add(out, residual) return out def load_data(): labels = np.loadtxt('label.txt') encoded_seq = np.loadtxt('encoded_seq.txt') x_train,x_test,y_train,y_test = train_test_split(encoded_seq,labels,test_size=0.1) # xnp_array = np.array(x_train) # xtrain_np = torch.from_numpy(xnp_array) # ynp_array = np.array(y_train) # ytrain_np = torch.from_numpy(ynp_array) # xtxnp_array = np.array(x_test) # xtest_np = torch.from_numpy(xtxnp_array) # ytxnp_array = np.array(y_test) # ytest_np = torch.from_numpy(ytxnp_array) return np.array(x_train),np.array(y_train),np.array(x_test),np.array(y_test) # return xtrain_np, ytrain_np, xtest_np, ytest_np learning_rate = 1e-3 batch_size = 50 epochs = 5 x_train,y_train,x_test,y_test = load_data() train_dataloader = DataLoader(x_train, batch_size=batch_size, shuffle=True) x_train = torch.from_numpy(x_train) # torch.reshape(x_train, (-1, 400)) x_train = x_train.numpy() x_train = np.expand_dims(x_train, 1) x_train = np.expand_dims(x_train, 1) train_loader = torch.utils.data.DataLoader(data.TensorDataset(torch.from_numpy(x_train), torch.from_numpy(y_train)), batch_size=batch_size, shuffle=True) # train_features, train_labels = next(iter(train_dataloader)) # test_dataloader = DataLoader(test_data, batch_size=64) def train(dataloader, model, loss_fn, optimizer): size = len(dataloader.dataset) for batch, (X, y) in enumerate(dataloader): # Compute prediction and loss pred = model(X) loss = loss_fn(pred, y) # Backpropagation optimizer.zero_grad() loss.backward() optimizer.step() if batch % 100 == 0: loss, current = loss.item(), batch * len(X) print(f"loss: {loss:>7f} [{current:>5d}/{size:>5d}]") def main(): device = 'cuda' if torch.cuda.is_available() else 'cpu' model = Net().to(device) loss_fn = nn.CrossEntropyLoss() optimizer = torch.optim.SGD(model.parameters(), lr=learning_rate) epochs = 10 for t in range(epochs): print(f"Epoch {t+1}\n-------------------------------") train(train_loader, model, loss_fn, optimizer) # test_loop(test_dataloader, model, loss_fn) print("Done!") if __name__ == '__main__': main() <file_sep>/utils/constants/data_url.py POWER_PLANT_DATASET_URL = "https://archive.ics.uci.edu/ml/machine-learning-databases/00294/CCPP.zip" POWER_PLANT_DATASET_LOCAL_PATH = "CCPP/CCPP/Folds5x2_pp.xlsx" AIR_QUALITY_DATASET_URL = "https://archive.ics.uci.edu/ml/machine-learning-databases/00360/AirQualityUCI.zip" AIR_QUALITY_DATASET_URL_LOCAL_PATH = "AirQualityUCI/AirQualityUCI.xlsx"<file_sep>/utils/download.py import os import tarfile import zipfile from urllib.request import urlretrieve from multiprocessing import Lock from functools import wraps from .file_types import File_type from .constants import data_url class SingletonType(type): def __new__(mcs, name, bases, attrs): # Assume the target class is created (i.e. this method to be called) in the main thread. cls = super(SingletonType, mcs).__new__(mcs, name, bases, attrs) cls.__shared_instance_lock__ = Lock() return cls def __call__(cls, *args, **kwargs): with cls.__shared_instance_lock__: try: return cls.__shared_instance__ except AttributeError: cls.__shared_instance__ = super(SingletonType, cls).__call__(*args, **kwargs) return cls.__shared_instance__ class DownloardAndExtractFile(metaclass=SingletonType): """ A singleton class to download and extract file from the internet """ def download_and_extract_file(self, url, file_type=File_type.ZIP): base_name = os.path.basename(url) file_name = os.path.splitext(base_name)[0] if file_type == File_type.TAR: file_name = os.path.splitext(file_name)[0] if os.path.isdir(file_name): print(f'{file_name} folder already exit') else: print(f" About to Download {base_name} ...") try: file_tmp = urlretrieve(url,filename=None)[0] except IOError: print(f"Can't retrieve url {url}") return print(f"File downlaoded to a temporary file {file_tmp}") if file_type == File_type.ZIP: self.extract_zip_file(file_tmp, file_name) elif file_type == File_type.TAR: self.extract_tar_file(file_tmp,file_name) else: print("Unknown File type") def extract_zip_file(self,file_tmp, file_name): print(f"Extracting file: {file_name}") with zipfile.ZipFile(file_tmp, 'r') as zip_ref: zip_ref.extractall(file_name) def extract_tar_file(self,file_tmp,file_name): print(f"Extracting file: {file_name}") try: tar = tarfile.open(file_tmp) tar.extractall(file_name) except: print(f"Can't tar the {file_name}") return print(f"Successfully extracted to folder {file_name}") def main(): DownloardAndExtractFile().download_and_extract_file(data_url.POWER_PLANT_DATASET_URL) if __name__ == '__main__': main() <file_sep>/utils/misc.py import numpy as np class Normalization(object): @staticmethod def min_std_norm(df): for col in df.columns: c = df[col] df[col] = (c-c.mean())/c.std() return df class Metrics(object): @staticmethod def mse(y_true, y_predicted): return np.mean((y_true - y_predicted)**2) <file_sep>/README.md # DeepSplicer: An Improved Method of Splice Sites Prediction using Deep Learning **University of Colorado, Colorado Springs** ---------------------------------------------------------------------- **Developers:** <br /> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<NAME><br /> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Department of Computer Science <br /> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;University of Colorado, Colorado Springs <br /> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Email: <EMAIL> <br /><br /> **Contact:** <br /> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<NAME>, PhD <br /> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Department of Computer Science <br /> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;University of Colorado, Colorado Springs <br /> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Email: <EMAIL> -------------------------------------------------------------------- **1. Content of folders:** ----------------------------------------------------------- * src: DeepSplicer source code. deepsplicer.py <br /> * src: Hyper-parameter tuning source code. <br /> * src: DeepSplicer cross-validation source code. deepsplicer_cross_val.py <br /> * Models file for deepsplicer models <br /> * Log file for utilization results logs <br /> * Plots file for utilization results plots <br /> **2. Hi-C Data used in this study:** ----------------------------------------------------------- In our study, we constructed genomic dataset from [Adhikari, et al](https://pubmed.ncbi.nlm.nih.gov/32550561/). To demonstrate our model’s generality, we utilized five carefully selected datasets from organisms, namely: Homo sapiens, Oryza sativa japonica, Arabidopsis thaliana, Drosophila melanogaster, and Caenorhabditis elegans. We downloaded these reference genomic sequence datasets (FASTA file format) from [Albaradei, S. et al](https://pubmed.ncbi.nlm.nih.gov/32550561/) and its corresponding annotation sequence (GTF file format) from [Ensembl](https://uswest.ensembl.org/index.html). Our data for constructed to permit a **Sequence Length of 400** of **3. One-Hot encoding:** ----------------------------------------------------------- We used One-hot encoding to transforms our Genomic sequence data and labels into vectors of 0 and 1. In other words, each element in the vector will be 0, except the element that corresponds to the nucleotide base of the sequence data input is 1. Adenine (A) is [1 0 0 0], Cytosine (C) is [0 1 0 0], Guanine (G) is [0 0 1 0], Thymine (T) is [0 0 0 1]. **4. Usage:** ----------------------------------------------------------- Usage: To use, type in the terminal python deepsplicer.py -n model_name -s sequence(acceptor or donor) -o organism_name -e encoded_sequnce_file -l encoded_label_file <br /> * **Arguments**: <br /> * name: A string for the name of the model <br /> * sequence: A string to specify acceptor or donor input dataset<br /> * organism: A string to specify organism name i.e ["hs", "at", "oriza", "d_mel", "c_elegans"] <br /> * encoded sequence file: A file containing the encoded sequence data <br /> * encoded label file: A file containing the encoded label data <br /> **6. Output:** ----------------------------------------------------------- Deepsplicer outputs three files: 1. .h5: The deepslicer model and weight file. 2. .txt: A log file that contains the accuracy and evaluation metrics results. 3. png: contains the plotting of the prediction accuracy **7. Note:** ----------------------------------------------------------- * Dataset sequence length is 400. * Deepsplice folders [log, models, plots] is essential for code functionality. * Genomic sequence input data should should transfomed using one-hot encoding. <file_sep>/CNN_model.py # Test different window length from __future__ import print_function import numpy as np import time import keras from tensorflow.keras.layers import Conv2D, MaxPooling2D from keras.utils import np_utils from keras.models import Sequential from keras.layers import Flatten from keras.layers.core import Dense, Dropout, Activation from keras.optimizers import Adam from keras.optimizers import RMSprop from keras.callbacks import ModelCheckpoint from keras.applications import * from sklearn.model_selection import train_test_split from sklearn import tree, metrics from sklearn.metrics import precision_score, recall_score, classification_report from utils.plot import Plot from matplotlib import pyplot as plt from tensorflow.keras.applications.resnet50 import ResNet50 import tensorflow as tf from contextlib import redirect_stdout from keras.utils.vis_utils import plot_model from sklearn.metrics import precision_recall_fscore_support as score Length = 400 # length of window def load_data(): labels = np.loadtxt('label.txt') encoded_seq = np.loadtxt('encoded_seq.txt') x_train,x_test,y_train,y_test = train_test_split(encoded_seq,labels,test_size=0.1) return np.array(x_train),np.array(y_train),np.array(x_test),np.array(y_test) def resnet_model(): resnet50_imagenet_model = ResNet50(include_top=False, weights='imagenet', batch_input_shape=(None, Length, 4)) #Flatten output layer of Resnet flattened = tf.keras.layers.Flatten()(resnet50_imagenet_model.output) #Fully connected layer 1 fc1 = tf.keras.layers.Dense(128, activation='relu', name="AddedDense1")(flattened) #Fully connected layer, output layer fc2 = tf.keras.layers.Dense(12, activation='softmax', name="AddedDense2")(fc1) model = tf.keras.models.Model(inputs=resnet50_imagenet_model.input, outputs=fc2) adam = Adam(lr=1e-4) model.compile(optimizer=adam, loss='categorical_crossentropy', metrics=['accuracy']) return model def load_model(): from keras.models import Model from keras.layers import Input, Dense, Dropout, Flatten, Conv2D, MaxPooling2D tensor_in = Input((60, 200, 3)) out = tensor_in out = Conv2D(filters=32, kernel_size=(3, 3), padding='same', activation='relu')(out) out = Conv2D(filters=32, kernel_size=(3, 3), activation='relu')(out) out = MaxPooling2D(pool_size=(2, 2))(out) out = Conv2D(filters=64, kernel_size=(3, 3), padding='same', activation='relu')(out) out = Conv2D(filters=64, kernel_size=(3, 3), activation='relu')(out) out = MaxPooling2D(pool_size=(2, 2))(out) out = Conv2D(filters=128, kernel_size=(3, 3), padding='same', activation='relu')(out) out = Conv2D(filters=128, kernel_size=(3, 3), activation='relu')(out) out = MaxPooling2D(pool_size=(2, 2))(out) out = Conv2D(filters=256, kernel_size=(3, 3), activation='relu')(out) out = MaxPooling2D(pool_size=(2, 2))(out) out = Flatten()(out) out = Dropout(0.5)(out) out = [Dense(37, name='digit1', activation='softmax')(out),\ Dense(37, name='digit2', activation='softmax')(out),\ Dense(37, name='digit3', activation='softmax')(out),\ Dense(37, name='digit4', activation='softmax')(out),\ Dense(37, name='digit5', activation='softmax')(out),\ Dense(37, name='digit6', activation='softmax')(out)] model = Model(inputs=tensor_in, outputs=out) # Define the optimizer model.compile(loss='categorical_crossentropy', optimizer='Adamax', metrics=['accuracy']) if 'Windows' in platform.platform(): model.load_weights('{}\\cnn_weight\\verificatioin_code.h5'.format(PATH)) else: model.load_weights('{}/cnn_weight/verificatioin_code.h5'.format(PATH)) return model def deep_model(): # build the model model = Sequential() model.add(keras.layers.Conv1D(filters=50, kernel_size=9, strides=1, padding='same', batch_input_shape=(None, Length, 4), activation='relu')) model.add(keras.layers.Conv2D(32, kernel_size =(9, 9), strides =(1, 1), padding='same', data_format="channels_last", activation ='relu')) model.add(MaxPooling2D(pool_size =(2, 2), strides =(2, 2))) model.add(keras.layers.Conv2D(64, (9, 9), activation ='relu')) model.add(MaxPooling2D(pool_size =(2, 2))) model.add(Flatten()) model.add(Dense(100, activation ='relu')) model.add(Dropout(0.3)) model.add(Dense(3, activation ='softmax')) # training the model model.compile(loss = keras.losses.categorical_crossentropy, optimizer = keras.optimizers.SGD(lr = 0.01), metrics =['accuracy']) return model def deep_cnn_classifier(): model = Sequential() model.add(keras.layers.Conv1D(filters=50, kernel_size=9, strides=1, padding='same', batch_input_shape=(None, Length, 4), activation='relu')) model.add(Flatten()) model.add(Dense(100,activation='relu')) model.add(Dropout(0.3)) model.add(Dense(3,activation='softmax')) adam = Adam(lr=1e-4) model.compile(optimizer=adam, loss='categorical_crossentropy', metrics=['accuracy']) # plot_model(model, to_file='model_plot.png', show_shapes=True, show_layer_names=True) return model def cnn_classifier(): model = Sequential() model.add(keras.layers.Conv1D(filters=50, kernel_size=9, strides=1, padding='same', batch_input_shape=(None, Length, 4), activation='relu')) model.add(keras.layers.Conv1D(filters=50, kernel_size=7, strides=1, padding='same', batch_input_shape=(None, Length, 4), activation='relu')) model.add(keras.layers.Conv1D(filters=50, kernel_size=5, strides=1, padding='same', batch_input_shape=(None, Length, 4), activation='relu')) model.add(Flatten()) model.add(Dense(100,activation='relu')) model.add(Dropout(0.3)) model.add(Dense(3,activation='softmax')) adam = Adam(lr=1e-4) model.compile(optimizer=adam, loss='categorical_crossentropy', metrics=['accuracy']) # plot_model(model, to_file='model_plot.png', show_shapes=True, show_layer_names=True) return model def training_process(x_train,y_train,x_test,y_test): # x_train = x_train.reshape(-1, Length, Length, 4) x_train = x_train.reshape(-1, Length, 4) y_train = np_utils.to_categorical(y_train, num_classes=3) x_test = x_test.reshape(-1, Length, 4) y_test = np_utils.to_categorical(y_test, num_classes=3) print(x_train.shape, y_train.shape) epoch = 3 print("======================") print('Convolution Neural Network') x_plot = list(range(1,epoch+1)) start_time = time.time() model = deep_model() history = model.fit(x_train, y_train, epochs=epoch, batch_size=50) model.save('CNN.h5') loss,accuracy = model.evaluate(x_test,y_test) print(model.summary()) with open('modelsummary.txt', 'w') as f: with redirect_stdout(f): model.summary() print('testing accuracy: {}'.format(accuracy)) print('testing loss: {}'.format(loss)) print('training took %fs'%(time.time()-start_time)) prob = model.predict(x_test) predict = model.predict(x_test) predict = np_utils.to_categorical(predict, num_classes=3) y_true = y_test # pred = model.predict(x_test, batch_size=32, verbose=1) predicted = np.argmax(prob, axis=1) report = classification_report(np.argmax(y_true, axis=1), predicted, output_dict=True ) print(report) macro_precision = report['macro avg']['precision'] macro_recall = report['macro avg']['recall'] macro_f1 = report['macro avg']['f1-score'] class_accuracy = report['accuracy'] print("precision: ", macro_precision, "recall: ", macro_recall, "f1: ", macro_f1, "accuracy: ", class_accuracy) true_0 = y_true[:,0] prob_0 = prob[:,0] predict_0 = predict[:,0] predicted = np.argmax(prob_0) # report = classification_report(np.argmax(true_0), predict_0) # print("/n/n This is report for acceptor site :", report) # auc = metrics.roc_auc_score(true_0,prob_0) # precision = metrics.precision_score(true_0,predict_0) # recall = metrics.recall_score(true_0,predict_0) # f1 = metrics.f1_score(true_0,predict_0) # print('acceptor AUC of :%f'%auc) # print('acceptor precision of :%f'%precision) # print('acceptor recall of :%f'%recall) # print('acceptor f1 of :%f'%f1) # true_1 = y_true[:,1] # prob_1 = prob[:,1] # predict_1 = predict[:,1] # predicted = np.argmax(prob_1, axis=1) # report = classification_report(np.argmax(true_1, axis=1), predict_1, **output_dict=True**) # print("/n/n This is report for donor site :", report) # auc = metrics.roc_auc_score(true_1,prob_1) # precision = metrics.precision_score(true_1,predict_1) # recall = metrics.recall_score(true_1,predict_1) # f1 = metrics.f1_score(true_1,predict_1) # print('donor AUC of :%f'%auc) # print('donor precision of :%f'%precision) # print('donor recall of :%f'%recall) # print('donor f1 of :%f'%f1) plt.plot(history.history['accuracy']) # plt.plot(history.history['val_accuracy']) plt.title('model accuracy for CNN model') plt.ylabel('accuracy') plt.xlabel('epoch') plt.legend(['train', 'test'], loc='upper left') plt.show() return def main(): x_train,y_train,x_test,y_test = load_data() training_process(x_train,y_train,x_test,y_test) if __name__ == '__main__': main()
abe5738c7684907a6db9c402b997c50a9d71f167
[ "Markdown", "Python" ]
8
Python
victorakpokiro/Splice-Site-Prediction
dbc08ddd6d2fd1e0645d6456b1eea6c8ed561ba6
e7836347836a1c385922324ce43a8f615174ac6f
refs/heads/main
<file_sep>from tkinter import * import random win = Tk() class game: def __init__(self,win): self.countC = 0 self.countU = 0 self.btnclick = 0 self.win = win win.title("Rock Paper Scissors") win.geometry("500x300") label1 = Label(win,text="Rock Paper Scissors",fg="gray",font=(25)).pack(side=TOP) self.entryval2 = StringVar(win,value='Lets play Game') self.entry2 = Entry(win,textvariable=self.entryval2,fg="green",state='readonly',borderwidth=0,font=(20)) self.entry2.place(x=200,y=30) label3 = Label(win,text="Your Options:-",fg="gray",font=(18)).place(x=10,y=60) Rockbtn = Button(win,text="Rock",bg="magenta",fg="#15f4ee",width=15) Rockbtn.place(x=50,y=90) Rockbtn.bind('<Button-1>',self.rock) Paperbtn = Button(win,text="Paper",bg="gray",fg="#15f4ee",width=15) Paperbtn.place(x=200,y=90) Paperbtn.bind('<Button-1>',self.paper) Scissorbtn = Button(win,text="Scissors",bg="yellow",fg="#15f4ee",width=15) Scissorbtn.place(x=350,y=90) Scissorbtn.bind('<Button-1>',self.scissor) label4 = Label(win,text="Score",fg="gray",font=(18)).place(x=10,y=130) label5 = Label(win,text="Your Selected:-",fg="gray",font=(16)).place(x=50,y=160) self.entryval3 = IntVar(win,value='None') self.entry3 = Entry(win,textvariable=self.entryval3,borderwidth=0,state='readonly',fg="gray",font=(8)) self.entry3.place(x=170,y=160) label6 = Label(win,text="Computer Selection:-",fg="gray",font=(16)).place(x=50,y=190) self.entryval4 = IntVar(win,value='None') self.entry4 = Entry(win,textvariable=self.entryval4,borderwidth=0,state='readonly',fg="gray",font=(8)) self.entry4.place(x=210,y=190) label7 = Label(win,text="Your Score:-",fg="gray",font=(16)).place(x=300,y=160) self.entryval5 = IntVar(win,value=0) self.entry5 = Entry(win,textvariable=self.entryval5,borderwidth=0,state='readonly',fg="gray",font=(8)) self.entry5.place(x=400,y=160) label8 = Label(win,text="Computer Score:-",fg="gray",font=(16)).place(x=300,y=190) self.entryval6 = IntVar(win,value=0) self.entry6 = Entry(win,textvariable=self.entryval6,borderwidth=0,state='readonly',fg="gray",font=(8)) self.entry6.place(x=440,y=190) def reset(self,event=None): top = Toplevel() top.title("Match Winner...!") top.geometry("300x300") if self.countC > self.countU: winnerlabel = Label(top,text="Computer Winner..!",fg="green",font=(15)).pack(side=TOP) winnerscore = Label(top,text="Score:-",fg="gray",font=(12)).pack(side=TOP) correct = Label(top,text="Correct",fg="green",font=(10)).place(x=80,y=50) incorrect = Label(top,text="Incorrect",fg="red",font=(10)).place(x=160,y=50) match = Label(top,text="Match",fg="orange",font=(10)).place(x=240,y=50) winnerComputer = Label(top,text="Coputer",fg="blue",font=(12)).place(x=15,y=70) result = 10-(self.countC+self.countU) correctPC = Label(top,text=self.countC,fg="green",font=(10)).place(x=80,y=70) incorrectPC = Label(top,text=self.countU,fg="red",font=(10)).place(x=160,y=70) matchPC = Label(top,text=result,fg="orange",font=(10)).place(x=240,y=70) else: winnerlabel = Label(top,text="You Winner..!",fg="green",font=(12)).pack(side=TOP) winnerscore = Label(top,text="Score:-",fg="gray",font=(12)).pack(side=TOP) correct = Label(top,text="Correct",fg="green",font=(10)).place(x=80,y=50) incorrect = Label(top,text="Incorrect",fg="red",font=(10)).place(x=160,y=50) match = Label(top,text="Match",fg="orange",font=(10)).place(x=240,y=50) winnerComputer = Label(top,text="Your",fg="blue",font=(12)).place(x=15,y=70) result = 10-(self.countC+self.countU) correctPC = Label(top,text=self.countU,fg="green",font=(10)).place(x=80,y=70) incorrectPC = Label(top,text=self.countC,fg="red",font=(10)).place(x=160,y=70) matchPC = Label(top,text=result,fg="orange",font=(10)).place(x=240,y=70) # reset all count value and labels self.countC = 0 self.countU = 0 self.btnclick = 0 self.entryval6.set(self.countC) self.entryval5.set(self.countU) self.entryval4.set("None") self.entryval3.set("None") self.entryval2.set("Lets play Game") def rock(self,event=None): if self.btnclick > 9: self.reset() else: pc=random.choice(['rock','paper','scissor']) self.entryval3.set("rock") self.entryval4.set(pc) if pc == 'rock': self.entryval2.set("match Tie") elif pc == 'paper': self.entryval2.set("Computer Win...!") self.countC = self.countC+1 self.entryval6.set(self.countC) else: self.entryval2.set("You Win...!") self.countU = self.countU+1 self.entryval5.set(self.countU) self.btnclick = self.btnclick+1 def paper(self,event=None): if self.btnclick > 9: self.reset() else: pc=random.choice(['rock','paper','scissor']) self.entryval3.set("paper") self.entryval4.set(pc) if pc == 'paper': self.entryval2.set("Match Tie") elif pc == 'scissor': self.entryval2.set("Computer Win...!") self.countC = self.countC+1 self.entryval6.set(self.countC) else: self.entryval2.set("You Win...!") self.countU = self.countU+1 self.entryval5.set(self.countU) self.btnclick = self.btnclick+1 def scissor(self,event=None): if self.btnclick > 9: self.reset() else: pc=random.choice(['rock','paper','scissor']) self.entryval3.set("scissor") self.entryval4.set(pc) if pc == 'scissor': self.entryval2.set("Match Tie") elif pc == 'rock': self.entryval2.set("Computer Win...!") self.countC = self.countC+1 self.entryval6.set(self.countC) else: self.entryval2.set("You Win") self.countU = self.countU+1 self.entryval5.set(self.countU) self.btnclick = self.btnclick+1 obj = game(win) win.mainloop()
b5ac472fec5326317d7b28c366aea003f8086356
[ "Python" ]
1
Python
niteshasale/rock_paper_scissors-tkinter
8ca480a292af3f165c46863ff307bbbbd88a63bb
6f1b7d8580ac73e3ecea0b2dbef099de973e8e51
refs/heads/master
<repo_name>baydarn/beginning_JS<file_sep>/app.js alert("javascripte hoş geldiniz!"); var a=10; alert(a); console.log(23213); console.log(["Ahmet,Mehmet"]); console.log(typeof a); console.warn("bu bir uyarıdır"); console.error("bu bir hatadır"); var a=20; var b=10; var c=40; console.log(a,b,c); //primitive var a=10; var b=3.14; console.log(typeof a); console.log(typeof b); var name="neslin"; console.log(name); console.log(typeof name); var numbers=["1,2,3,4,5"]; console.log(numbers); console.log(typeof numbers); console.log(numbers[0]); var person = { name = "neslin", age = 24 } console.log(person); console.log(typeof person); var date=new Date(); console.log(date); console.log(typeof date); var merhaba = function(){ console.log("merhaba"); } console.log(merhaba); console.log(typeof merhaba); var a=10; var b=a; console.log(a,b); a=20; console.log(a,b); var a=[1,2,3]; var b=a; a.push(4); console.log(b); console.log(Math.max(1, 3, 2)); // expected output: 3 console.log(Math.max(-1, -3, -2)); // expected output: -1 var array1 = [1, 3, 2]; console.log(Math.max(...array1)); // expected output: 3
7ed2c9f3cc8491ee8fcb3404231d234a40c5305c
[ "JavaScript" ]
1
JavaScript
baydarn/beginning_JS
e6418f63b0f55b92e30bb37533eb3775b136be71
16fb444ebbf5dd4e307b2fe42c625606013a1d2b
refs/heads/master
<file_sep><?php $dbhost = "localhost"; $dbuser = "testdb"; $dbpass = "<PASSWORD>"; $dbname = "testdb"; $con = mysqli_connect($dbhost,'testdb','testdb',$dbname,'8001'); if(!$con) { die("Connection failed: " .mysqli_connect_error()); } $firstname = $_POST['fname']; $lastname = $_POST['lname']; $age = $_POST['age']; $query1= "Insert into users (firstname,lastname,age) values ('$firstname','$lastname',$age)"; //build select query $query = "SELECT firstname,lastname,age,createddatetimestamp FROM users"; if(mysqli_query($con,$query1)) { echo "New record created <br /> <br />"; } else { echo "Error: " .$query1."<br>".mysqli_error($con); } //Execute query $qry_result = mysqli_query($con,$query) or die(mysqli_error()); //Build Result String $display_string = "<table>"; $display_string .= "<tr>"; $display_string .= "<th>FirstName</th>"; $display_string .= "<th>LastName</th>"; $display_string .= "<th>Age</th>"; $display_string .= "<th>CreatedDateTimeStamp</th>"; $display_string .= "</tr>"; // Insert a new row in the table for each person returned while($row = mysqli_fetch_array($qry_result)) { $display_string .= "<tr>"; $display_string .= "<td>$row[firstname]</td>"; $display_string .= "<td>$row[lastname]</td>"; $display_string .= "<td>$row[age]</td>"; $display_string .= "<td>$row[createddatetimestamp]</td>"; $display_string .= "</tr>"; } $display_string .= "</table>"; echo $display_string; mysqli_close($con); ?> <file_sep>Vagrant.configure("2") do |config| config.vm.provider :virtualbox do |vb| vb.memory = 2048 end config.vm.box = "ubuntu/trusty64" end
ff99c52404207a64d0e17252cab0311b695026a4
[ "Ruby", "PHP" ]
2
PHP
ashu02aug/devops-project
b22cf67d5aa9fcce7c29767349bc2e4e21ae38b3
8c35d2ba7ee8509e4a17259e70fca17cf2a5eb2d
refs/heads/master
<repo_name>tachycline/fits2sqlite<file_sep>/fits2sqlite.py #! /usr/bin/env python ''' A Python module for inserting FITS header data in a SQLite database. Command line help available by running: > python fits2sqlite -h <NAME> <EMAIL> ''' import argparse import glob import os import pyfits import sqlite3 # ----------------------------------------------------------------------------- # Functions (alphabetical) # ----------------------------------------------------------------------------- def get_id(database,filename): ''' Return the id of the that matches that filename. Return [] if there is no match. Raise AssertionError if there is more than one match. ''' conn = sqlite3.connect(database) c = conn.cursor() command = 'SELECT id FROM headers WHERE filename = "' command += os.path.basename(filename) + '"' c.execute(command) id = c.fetchall() conn.close() assert len(id) in [0,1], 'Multiple rows match filename.' return id # ----------------------------------------------------------------------------- def get_file_list(search_string): ''' Get the file list based on the seach string. ''' search_string = os.path.abspath(search_string) print search_string file_list = glob.glob(search_string) assert file_list != [], 'No files found.' return file_list # ----------------------------------------------------------------------------- def get_header(filename): ''' Get the header information. ''' f = pyfits.open(filename) header = f[0].header f.close() header.update('filename', os.path.basename(filename)) return header # ----------------------------------------------------------------------------- def ingest_header(args,filename): ''' Ingest the header information with an UPDATE or INSERT. ''' if args.verbose == True: print filename header = get_header(filename) id = get_id(args.database, filename) if id == []: insert_header(args.database, header) else: update_header(args.database, header, id) # ----------------------------------------------------------------------------- def insert_header(database,header): ''' Insert the header information into the database. ''' conn = sqlite3.connect(database) c = conn.cursor() command = 'INSERT INTO headers (' for key in header: command += '"' + key +'",' command = command[:-1] command += ') VALUES (' for key in header: command += '"' + str(header[key]) + '",' command = command[:-1] command += ')' c.execute(command) conn.commit() conn.close() # ----------------------------------------------------------------------------- def make_header_set(file_list): ''' Returns all the header keywords as a set object. ''' header_set = set() for filename in file_list: header = get_header(filename) for key in header.iterkeys(): header_set.add(key) return header_set # ------------------------------------------------------------------------------ def make_table(database): ''' Run the schema. ''' conn = sqlite3.connect(database) c = conn.cursor() sql = open('makefitsdb.sql').read() c.executescript(sql) conn.commit() conn.close() # ------------------------------------------------------------------------------ def prase_args(): ''' Prase the command line arguemnts. ''' parser = argparse.ArgumentParser( description = 'Inserts FITS header information in a SQLite database.' ) parser.add_argument( '--files', required = True, help = 'Search string for the fits files you want to ingest.\ e.g. "dir/*.fits"') parser.add_argument( '--database', required = True, help = 'Path to the SQLite database.') parser.add_argument( '--verbose', required = False, type = bool, default = False, help = 'Print steps') args = parser.parse_args() return args # ----------------------------------------------------------------------------- def update_header(database,header,id): ''' Update the header information for an already existing row. ''' conn = sqlite3.connect(database) c = conn.cursor() command = 'UPDATE OR ROLLBACK headers SET ' for key in header: command += '"' + key + '" = "' + str(header[key]) + '",' command = command[:-1] command += ' WHERE id = "' + str(id[0][0]) + '"' c.execute(command) conn.commit() conn.close() # ------------------------------------------------------------------------------ def write_table_schema(header_set): ''' Create the SQLite schema for the table. ''' f = open('makefitsdb.sql','w') f.write('BEGIN;\n') f.write('CREATE TABLE IF NOT EXISTS headers (\n') f.write('\tid INTEGER PRIMARY KEY,\n') #f.write('\tfilename TEXT UNIQUE ON CONFLICT REPLACE,\n') while len(header_set) > 1: f.write('\t "' + header_set.pop() + '" TEXT,\n') else: f.write('\t "' + header_set.pop() + '" TEXT\n') f.write(');\n') f.write('COMMIT;\n') f.close() # ----------------------------------------------------------------------------- # The main controller. # ----------------------------------------------------------------------------- def main(args): ''' The mail controller. ''' file_list = get_file_list(args.files) database_test = os.access(args.database,os.F_OK) if database_test == False: header_set = make_header_set(file_list) write_table_schema(header_set) make_table(args.database) for filename in file_list: ingest_header(args,filename) # ----------------------------------------------------------------------------- # For command line execution. # ----------------------------------------------------------------------------- if __name__ == '__main__': args = prase_args() main(args) <file_sep>/README.md fits2sqlite =========== A tool for exporting header data from astronomy FITS images in a SQLIte database. Description ----------- fits2sqlite is a lightweight python command line tool that exports header information from FITS files into a SQLite database. Astronomy images in the FITS format contain image metadata (data about the data) in the header of each extension. However, this information is tied up in each individual image making it difficult to sort and query images from large datasets. fits2sqlite solves this problem by consolidates header information in a SQLite database. SQLite is a self-contained serverless relational database that offers many advantages over flat-files. Features -------- - If the SQLite database specified does not exist it will be created. - Each header keyword will be a separate field in a table called headers. - A unique integer id is created for each file name. - Each field (except for the id field) will be a text type. - The file name field has a uniqueness contraint. - If a file is ingested that already exists in the database the header information is updated. Usage ----- For help: `> python fits2sqlite.py -h` To Run: `> python fits2sqlite.py --files 'data/*.fits' --database 'headers.db' [--verbose]` Dependencies ------------ SQLite [http://www.sqlite.org/] Python (all part of the python standard library): - argparse - glob - os - pyfits - sqlite3
093d8cd75ba7a1a633d2a2f21a2c2ff71935b05f
[ "Markdown", "Python" ]
2
Python
tachycline/fits2sqlite
b05e4a616cf5e5ade02aed9830d38d9b83b23f8e
2f1a50419993e6d401acd752e1eddc1e1924ecb8
refs/heads/master
<file_sep>iMagickFx - Effects for iMagick library (PHP module) # Examples ```php $im = new iMagickFx('example.jpg'); $im->fxCropResize(100, 100)->fxReflection('white', 0.9); $im = new iMagickFx('example.jpg'); $im->fxCropResize(100, 100)->fxRoundCorners()->fxDropShadow(); ``` See also doc/example.php <file_sep><?php /** * http://github.com/raspi/iMagickFx */ /** * Base for exceptions */ class iMagickEffectException extends Exception { } /** * Base for effects */ abstract class iMagickEffect { /** * * @var iMagick */ protected $im = null; public function __construct(IMagick $im) { if (false === ($im instanceOf IMagick)) { throw new iMagickEffectException('not valid instance'); } $this->im = $im; } public function getIM() { return $this->im; } /** * All effects call this method */ public function fx() { throw new iMagickEffectException('Effect not implemented'); } } /** * * * <code> * $im = new iMagickFx('example.jpg'); * $im->fxCropResize(100, 100)->fxReflection('white', 0.9); * </code> */ class iMagickFx { /** * * @var IMagick */ public $im = null; /** * Throw exception on missing effects? * @var boolean */ public $throwExceptionOnMissingFx = true; public function __construct($params = null) { if (false === class_exists('iMagick')) { throw new iMagickEffectException('IMagick class not found. Module missing or not loaded?'); } $this->im = new iMagick($params); } public function __toString() { return $this->im->__toString(); } public function __call($name, array $arguments) { if (substr($name, 0, 2) === 'fx') { $fxName = basename(substr($name, 2)); $className = 'iMagickEffect' . $fxName; $fxFile = dirname(__FILE__) . '/fx/' . strtolower($fxName) . '.php'; if (false === class_exists($className) && true === file_exists($fxFile)) { require_once $fxFile; } if (class_exists($className)) { // Call effect $fx = new $className($this->im); $this->im = call_user_func_array(array($fx, 'fx'), $arguments); } else { if ($this->throwExceptionOnMissingFx) { // Effect of given name was not found throw new Exception("Unknown effect: '$name'"); } } } else { // Call iMagick's own method return call_user_func_array(array($this->im, $name), $arguments); } return $this; } } <file_sep><?php /** * */ class iMagickEffectRoundCorners extends iMagickEffect { public function fx($width = 5, $height = null) { if (null === $height) {$height = $width;} $this->im->setImageFormat('png'); $this->im->roundCorners($width, $height); return $this->im; } }<file_sep><?php /** * */ class iMagickEffectGreyScale extends iMagickEffect { public function fx() { $this->im->modulateImage(100, 0, 100); return $this->im; } }<file_sep><?php /** * */ class iMagickEffectDropShadow extends iMagickEffect { public function fx() { $this->im->setImageFormat('png'); $shadow = $this->im->clone(); $shadow->setImageBackgroundColor(new ImagickPixel('black')); $shadow->shadowImage(80, 3, 5, 5); $shadow->compositeImage($this->im, Imagick::COMPOSITE_OVER, 0, 0 ); return $shadow; } }<file_sep><?php /** * */ class iMagickEffectCropResize extends iMagickEffect { public function fx() { $args = func_get_args(); call_user_func_array(array($this->im, 'cropThumbnailImage'), $args); return $this->im; } }<file_sep><?php require_once realpath(dirname(__FILE__) . '/../lib/imagickfx.php'); switch($_GET['example']) { default: break; case 'original': $im = new iMagickFx('apple.jpg'); header('Content-Type: ' . strtolower($im->getImageType())); echo $im; break; case 'grey': $im = new iMagickFx('apple.jpg'); $im->fxGreyScale(); header('Content-Type: ' . strtolower($im->getImageType())); echo $im; break; case 'crop-round-shadows': $im = new iMagickFx('apple.jpg'); $im->fxCropResize(120, 120)->fxRoundCorners()->fxDropShadow(); header('Content-Type: ' . strtolower($im->getImageType())); echo $im; break; case 'crop-reflection': $im = new iMagickFx('apple.jpg'); $im->fxCropResize(200, 200)->fxReflection('white', 0.9); header('Content-Type: ' . strtolower($im->getImageType())); echo $im; break; } // /switch ?> <html> <head> <title>iMagickFx - Examples</title> </head> <body> Original image:<br /> <img src="?example=original" alt="" /><br /> Greyscale:<br /> <img src="?example=grey" alt="" /><br /> Crop resize to 120x120 + add rounded corners + drop shadow:<br /> <img src="?example=crop-round-shadows" alt="" /><br /> Crop resize to 200x200 + add reflection:<br /> <img src="?example=crop-reflection" alt="" /><br /> </body> </html><file_sep><?php /** * */ class iMagickEffectReflection extends iMagickEffect { /** * * @param mixed color * @param float opacity */ public function fx($color = 'black', $opacity = 0.3) { $this->im->setImageFormat('png'); $reflection = $this->im->clone(); $reflection->flipImage(); $gradient = new Imagick(); $gradient->newPseudoImage($reflection->getImageWidth(), $reflection->getImageHeight(), "gradient:transparent-$color"); $reflection->compositeImage($gradient, imagick::COMPOSITE_OVER, 0, 0); $reflection->setImageOpacity($opacity); $canvas = new Imagick(); $canvas->newImage($this->im->getImageWidth(), $this->im->getImageHeight() * 2, $color, "png"); $canvas->compositeImage($this->im, imagick::COMPOSITE_OVER, 0, 0); $canvas->compositeImage($reflection, imagick::COMPOSITE_OVER, 0, $this->im->getImageHeight()); return $canvas; } }
c9cb5b15666fb114a079791f4aafc3f38df574ac
[ "Markdown", "PHP" ]
8
Markdown
raspi/iMagickFx
4ae60904e8e45b1bfd2a7bc13636d953f9c24513
88bb14ea01457f4bca3e7c65f6cb2d93742eef9b
refs/heads/master
<repo_name>meganlee18/surveyor<file_sep>/lib/surveyor/survey.rb module Surveyor class Survey # your code goes here end end <file_sep>/lib/surveyor/answer.rb module Surveyor class Answer # your code goes here end end
4be419cea3684c3cc98f429b9b0310c61a2790f6
[ "Ruby" ]
2
Ruby
meganlee18/surveyor
1bfa80ec449fa9dd01191536e42d721d35ed5107
681830f700fc64f368a11d81446de41ab635a0bb
refs/heads/master
<repo_name>Hassan-Khalid-folio3/github-actions<file_sep>/src/components/Input/index.js import React from 'react' import PropTypes from 'prop-types' import './style.css'; export default function Input(props) { const { value, onChange, addTodo, } = props; const handleKeyPress = (e) => { if (e.key === 'Enter') { addTodo(value); } }; return ( <> <input className="input" value={ value } onChange={ onChange } onKeyPress={ handleKeyPress } /> <button onClick={addTodo}>Add</button> </> ); } Input.propTypes = { onChange: PropTypes.func.isRequired, value: PropTypes.string.isRequired, } <file_sep>/src/components/TodoList/index.js import React, { useState } from 'react' import PropTypes from 'prop-types' import Input from '../Input'; export default function TodoList() { const [input, onInputChange] = useState(''); const [todos, onTodosChange] = useState([]); const addTodo = () => { if (input) { onTodosChange([...todos, input]); onInputChange(''); } }; const removeTodo = (todo) => () => { if (todos.includes(todo)) { onTodosChange(todos.filter(t => t !== todo)); } }; const list = ( <div> { todos.map(todo => <div className="list-row"> { todo } <button className="remove-button" onClick={ removeTodo(todo) }>Remove</button> </div> ) } </div> ); return ( <> <div className="todolist-container"> <Input value={ input } onChange={ (e) => onInputChange(e.target.value) } addTodo={ addTodo } /> { list } </div> </> ); } TodoList.propTypes = { }
57ad07e8ab457af648e67ccfeee34d4f1c305e72
[ "JavaScript" ]
2
JavaScript
Hassan-Khalid-folio3/github-actions
c47542139c84b7bcad9123814cbe7120034827fa
2212c409e13fab07a8e28db56631aa16552efce8
refs/heads/master
<file_sep>var app = angular.module('prc_app', []); app.controller('ctrl', function(){ this.peoples = [ {name: "hoge1", tel_number: 1234}, {name: "hoge2", tel_number: 2345}, {name: "hoge3", tel_number: 3456}, {name: "hoge4", tel_number: 4567}, {name: "hoge5", tel_number: 5678}, ]; });
51ced9934142c3ce0bd159f01595099605cdebcd
[ "JavaScript" ]
1
JavaScript
tab15/AngularJS_practice
a7940ac9e590dad02b4fe1c7543b41d0744fc023
c800fb42931131f398b750399e34cdfa02cf7192
refs/heads/master
<repo_name>laura-kolcavova/SeaBattle<file_sep>/js/imageManager.js function ImageManager() { var self = this; this.numImages = 3; this.loadedImages = 0; this.fire = new Image(); this.blop = new Image(); this.cursor = new Image(); this.fire.onload = function() { self.loadImage() }; this.blop.onload = function() { self.loadImage() }; this.cursor.onload = function() { self.loadImage() }; this.fire.src = "res/fire.png"; this.blop.src = "res/blop.png"; this.cursor.src = "res/cursor.png"; } ImageManager.prototype.loadImage = function() { this.loadedImages ++; if(this.loadedImages === this.numImages) { main(); } } ImageManager.prototype.initSprites = function() { this.s_fire = new Sprite(this.fire, cg.cw, cg.ch); this.s_blop = new Sprite(this.blop, cg.cw, cg.ch); this.s_cursor = new Sprite(this.cursor, cg.cw, cg.ch); } function Sprite(img, w, h) { this.img = img; this.w = w; this.h = h; } Sprite.prototype.draw = function(x, y, ctx) { ctx.drawImage(this.img, x, y, this.w, this.h); } <file_sep>/js/helpers.js //Functions /////////////////////////////////////// function AABBIntersect(ax, ay, aw, ah, bx, by, bw, bh) { return ax < bx+bw && ay < by+bh && bx < ax+aw && by < ay+ah; } function getRandom(min, max) { var r = Math.floor(Math.random() * (max - min + 1) + min); return r; } Array.prototype.contains = function(obj) { var i = 0; while(i < this.length) { if(this[i] === obj) return true; i++; } return false; } //Helpers /////////////////////////////////////// function Screen(width, height, id) { this.canvas = document.createElement("canvas"); this.canvas.width = this.w = width; this.canvas.height = this.h = height; this.canvas.id = id; this.ctx = this.canvas.getContext("2d"); document.body.appendChild(this.canvas); } function MouseHandler() { this.x = null; this.y = null; this.down = false; this.pushed = false; //for onClick var self = this; game.mCanvas.canvas.addEventListener("mousemove", function(e){ self.x = e.clientX - this.offsetLeft; self.y = e.clientY - this.offsetTop; }); game.mCanvas.canvas.addEventListener("mousedown", function(e){ self.down = true; }); game.mCanvas.canvas.addEventListener("mouseup", function(e){ self.down = false; }); } MouseHandler.prototype.clicked = function() { if(this.down) this.pushed = true; if(this.pushed && !this.down) { this.pushed = false; return true; } else return false; } MouseHandler.prototype.draw = function(ctx) { imageManager.s_cursor.draw(this.x - (Math.round(cg.cw / 2)), this.y - (Math.round(cg.ch / 2)), ctx); } function Button(text, font, color, method, args) { this.text = text; this.font = font; this.color = color; this.method = method; this.args = args; this.hoover = false; this.pushed = false; this.init = function(x, y, w, h) { this.x = x; this.y = y; this.w = w; this.h = h; } this.update = function() { if(AABBIntersect(Mouse.x, Mouse.y, 0, 0, this.x, this.y, this.w, this.h)) { this.hoover = true; if(Mouse.down && !this.pushed) { this.pushed = true; } if(!Mouse.down && this.pushed) { this.pushed = false; this.method.apply(this, this.args); } } else { this.hoover = false; this.pushed = false; } }; this.draw = function(ctx) { ctx.fillStyle = this.color; ctx.fillRect(this.x, this.y, this.w, this.h); if(this.pushed) { ctx.fillStyle = "rgba(0, 0, 0, 0.5)"; ctx.fillRect(this.x, this.y, this.w, this.h); } ctx.font = this.font; ctx.textAlign = "center"; ctx.textBaseline = "middle"; ctx.fillStyle = "black"; ctx.fillText(this.text, this.x + this.w/2, this.y + this.h/2); }; } //Functions for buttons //////////////////////////////////// function b_setRandomlyShips() { game.currentPlayer.setRandomlyShips(); game.selectedShip = null; game.currentPlayer.map.collisionShips = []; } function b_turnShip() { if(game.selectedShip !== null) { game.selectedShip.turn(); game.currentPlayer.map.checkCollisionOfShips(); } } function b_finishInit() { if(game.state === game.states.InitPlayer) { game.selectedShip = null; } game.finishInit(); } function b_startGame(arg) { game.startGame(arg); }<file_sep>/js/seabattle2.js var game, imageManager, soundManager, Mouse; window.requestAnimFrame = (function() { return window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || function( callback ){ window.setTimeout(callback, 1000 / 60); }; })(); var cg = { "w": 1200, "h": 550, "cols": 10, "rows": 10, "cw": 40, "ch": 40, "ships": { "0": { "id": 0, "name": 'clun', "length": 1 }, "1": { "id": 1, "name": 'ponorka', "length": 2 }, "2": { "id": 2, "name": 'kriznik', "length": 3 }, "3": { "id": 3, "name": 'letadlova', "length": 4 } }, "dires": { "Horizontal" : 0, "Vertical": 1 }, "dock": { "x": 540, "y": 50 }, "map1": { "x": 40, "y": 50, "id": 0 }, "map2": { "x": 680, "y": 50, "id": 1 }, "map": { "Watter": 0, "Ship": 1, "ShotOnWatter": 2, "ShotOnShip": 3 }, poradiLodi: new Array(3, 2, 2, 1, 1, 1, 0, 0, 0, 0), canvasBgr: "#99DAF0", //canvasBgr: "#C4F5E9", lineColor: "#003D52", mapColor: "white", shipColor: "#2F738A", shipStroke: "#00394D", alfabeta: "abcdefghij" } window.onload = function() { imageManager = new ImageManager(); soundManager = new SoundManager(); } function main() { imageManager.initSprites(); game = new Game(); Mouse = new MouseHandler(); document.getElementById("mCanvas").style.cursor = 'none'; game.init(); loop(); } function loop() { game.update(); game.draw(); window.requestAnimFrame(loop); } //Classes /////////////////////////////////////// function Game() { this.states = { Menu: 0, InitPlayer: 1, InitComputer: 2, GameFtComputer: 3, GameFtPlayer: 4, End: 5, }; this.state = null; this.gameTypes = { VsComputer: 0, VsPlayer: 1 }; this.gameType = null; this.mCanvas = mCanvas = new Screen(cg.w, cg.h, "mCanvas"); this.ctx = mCanvas.ctx; this.init = function() { this.setState(this.states.Menu); }; this.setState = function(state) { this.state = state; this.initState(state); }; this.initState = function(state) { if(state === this.states.Menu) { this.buttons = []; var font = "30px Arial"; var color = "rgba(255, 255, 255, 0.7)"; this.buttons[0] = new Button("Computer", font, color, b_startGame, [this.gameTypes.VsComputer]); this.buttons[0].init(450, 200, 150, 50); this.buttons[1] = new Button("Two players", font, color, b_startGame, [this.gameTypes.VsPlayer]); this.buttons[1].init(425, 280, 200, 50); } else if(state === this.states.InitPlayer) { this.selectedShip = null; this.dragAction = false; this.buttons = []; var font = "20px Arial"; var color = "white"; this.buttons[0] = new Button("Auto", font, color, b_setRandomlyShips, null); this.buttons[0].init(540, 330, 50, 50); this.buttons[1] = new Button("Turn", font, color, b_turnShip, null); this.buttons[1].init(620, 330, 50, 50); this.buttons[2] = new Button("Play", font, color, b_finishInit, null); this.buttons[2].init(565, 400, 80, 50); } else if(state === this.states.InitComputer) { this.buttons = []; } }; this.update = function() { this.updateState(this.state); }; this.updateState = function(state) { if(state === this.states.Menu) { for(var i = 0; i < this.buttons.length; i++) this.buttons[i].update(); } else if(state === this.states.InitPlayer) { this.currentPlayer.initUpdate(); for(var i = 0; i < this.buttons.length; i++) this.buttons[i].update(); } else if(state === this.states.InitComputer) { this.currentPlayer.initUpdate(); } else if(state === this.states.GameFtPlayer || state === this.states.GameFtComputer) { this.currentPlayer.shotUpdate(); if(!(this.currentPlayer instanceof Computer)) this.secondPlayer.map.shotUpdate(); } else if(state === this.states.End) { } }; this.draw = function() { this.ctx.clearRect(0, 0, mCanvas.w, mCanvas.h); //mCanvas.ctx.fillStyle = "#99DAF0"; this.ctx.fillStyle = cg.canvasBgr; this.ctx.fillRect(0, 0, mCanvas.w, mCanvas.h); this.drawState(this.state); Mouse.draw(this.ctx); }; this.drawState = function(state) { if(this.state === this.states.Menu) { for(var i = 0; i < this.buttons.length; i++) this.buttons[i].draw(this.ctx); } else if(this.state === this.states.InitPlayer) { this.currentPlayer.map.draw(this.ctx); this.currentPlayer.map.drawCrosshair(this.ctx); //draw ships without selected the one for(var i = 0; i < this.currentPlayer.ships.length; i++) { if(this.currentPlayer.ships[i] !== this.selectedShip) { this.currentPlayer.ships[i].draw(this.ctx); } } //draw the selected - hovering if(this.selectedShip !== null) this.selectedShip.draw(this.ctx); for(var i = 0; i < this.buttons.length; i++) this.buttons[i].draw(this.ctx); } else if(this.state === this.states.InitComputer) { //... } else if(this.state === this.states.GameFtComputer) { this.player1.map.draw(this.ctx); this.player1.drawShips(this.ctx); this.player2.map.draw(this.ctx); if(this.currentPlayer === this.player1 && !this.player1.firing) { this.player2.map.drawCrosshair(this.ctx); } this.player1.drawDestroyedShips(this.ctx); this.player2.drawDestroyedShips(this.ctx); this.player1.map.drawShots(this.ctx); this.player2.map.drawShots(this.ctx); } else if(this.state === this.states.GameFtPlayer) { this.player1.map.draw(this.ctx); this.player2.map.draw(this.ctx); if(!this.currentPlayer.firing) { this.secondPlayer.map.drawCrosshair(this.ctx); } this.player1.drawDestroyedShips(this.ctx); this.player2.drawDestroyedShips(this.ctx); this.player1.map.drawShots(this.ctx); this.player2.map.drawShots(this.ctx); } else if(this.state === this.states.End) { } }; /////////////////////////////////////////// ////////////////////////////////////////// this.startGame = function(gameType) { this.setState(this.states.InitPlayer); this.gameType = gameType; this.player1 = new Player(0); this.player2; if(gameType === this.gameTypes.VsComputer) this.player2 = new Computer(1); else this.player2 = new Player(1); this.player1.init(); this.player2.init(); this.player1.map.init(cg.map1.x, cg.map1.y); this.player2.map.init(cg.map2.x, cg.map2.y); this.currentPlayer = this.player1 this.secondPlayer = this.player2; }; this.finishInit = function() { if(this.currentPlayer.map.shipCollision) return; var shipsOnMap = 0; for(var i = 0; i < this.currentPlayer.ships.length; i++) { if(this.currentPlayer.ships[i].onMap) shipsOnMap++; } if(shipsOnMap === this.currentPlayer.ships.length) { this.currentPlayer.setShipsIntoMap(); this.currentPlayer.readyForBattle = true; if(this.currentPlayer === this.player1) { if(!this.currentPlayer instanceof Computer) { game.currentPlayer.map.collisionShips = []; } this.currentPlayer = this.player2; this.secondPlayer = this.player1; if(this.currentPlayer instanceof Computer) { this.setState(this.states.InitComputer); } else { this.setState(this.states.InitPlayer); } } } if(this.player1.readyForBattle && this.player2.readyForBattle) { if(this.gameType === this.gameTypes.VsComputer) { this.setState(this.states.GameFtComputer); } else this.setState(this.states.GameFtPlayer); if(getRandom(0, 1) === 1) { this.currentPlayer = this.player1; this.secondPlayer = this.player2; } return; } }; } function Map(cols, rows, id) { this.cols = cols; this.rows = rows; this.w = cols*cg.cw; this.h = cols*cg.ch; this.id = id; this.init = function(x, y) { this.x = x; this.y = y; this.grid = []; var x, y; for(y = 0; y < this.rows; y++) { this.grid.push(new Array()); for(x = 0; x < this.cols; x++) { this.grid[y].push(cg.map.Watter); } } this.shipCollision = false; this.collisionShips = []; this.coordField = { x: [], y: [] }; }; this.get = function(x, y) { if(x >= 0 && x < this.cols && y >= 0 && y < this.rows) { return this.grid[y][x]; } else return null; }; this.set = function(x, y, value) { this.grid[y][x] = value; }; this.initUpdate = function() { this.coordField.x = []; this.coordField.y = []; var selectedShip = game.selectedShip; if(!(selectedShip === null) && selectedShip.selected) { if(selectedShip.x >= this.x && selectedShip.x + selectedShip.w <= this.x + this.w && selectedShip.y >= this.y && selectedShip.y + selectedShip.h <= this.y + this.h) { if(selectedShip.dir === cg.dires.Horizontal) { for(var i = 0; i < selectedShip.type.length; i++) { this.coordField.x.push(Math.round((selectedShip.x - this.x) / cg.cw) + i); } this.coordField.y.push(Math.round((selectedShip.y - this.y) / cg.ch)); } else if(selectedShip.dir === cg.dires.Vertical) { for(var i = 0; i < selectedShip.type.length; i++) { this.coordField.y.push(Math.round((selectedShip.y - this.y) / cg.ch) + i); } this.coordField.x.push(Math.round((selectedShip.x - this.x) / cg.cw)); } this.checkCollisionOfShips(); } } } this.shotUpdate = function() { this.coordField.x = []; this.coordField.y = []; if(AABBIntersect(Mouse.x, Mouse.y, 0, 0, this.x, this.y, this.w, this.h)) { this.coordField.x.push(Math.floor((Mouse.x - this.x) / cg.cw)); this.coordField.y.push(Math.floor((Mouse.y - this.y) / cg.ch)); } } this.draw = function(ctx) { ctx.beginPath(); ctx.fillStyle = "white"; ctx.fillRect(this.x, this.y, this.w, this.h); ctx.fill(); ctx.lineWidth = "1"; ctx.strokeStyle = cg.lineColor; ctx.font = "20px Arial"; ctx.textAlign = "center"; ctx.textBaseline = "middle"; ctx.fillStyle = "black"; //Draw lines var x, y; //y lines var xOffset; if(this.id === cg.map1.id) xOffset = this.x - cg.cw / 2; else xOffset = this.x + this.w + cg.cw / 2; for(y = 1; y <= this.rows; y++) { //line if(y < this.rows) { ctx.beginPath(); ctx.moveTo(this.x, y*cg.ch + this.y); ctx.lineTo(this.w + this.x, y*cg.ch + this.y); ctx.stroke(); } //letter ctx.fillText(cg.alfabeta[y-1], xOffset, this.y + cg.ch * y - cg.ch / 2); } //x lines for(x = 1; x <= this.cols; x++) { //line if(x < this.cols) { ctx.beginPath(); ctx.moveTo(x*cg.cw+this.x, this.y); ctx.lineTo(x*cg.cw+this.x, this.h+this.y); ctx.stroke(); } //letter ctx.fillText(x, this.x + cg.cw * x - cg.cw / 2, this.y - cg.ch/2); } ctx.lineWidth = "3"; ctx.strokeRect(this.x - 1, this.y - 1, this.w + 2, this.h + 2); } this.drawCrosshair = function(ctx) { ctx.fillStyle = "rgba(20, 255, 0, 0.5)"; if(game.selectedShip !== null && game.selectedShip.selected) { if(this.collisionShips.contains(game.selectedShip)) { ctx.fillStyle = "rgba(255, 0, 0, 0.5)"; } } //draw colums for(var i = 0; i < this.coordField.x.length; i++) { var tx = this.coordField.x[i] * cg.cw; for(var y = 0; y < this.rows; y++) { ctx.fillRect(tx + this.x + 1, y*cg.ch + this.y + 1, cg.cw - 2, cg.ch - 2); } } //draw rows for(var i = 0; i < this.coordField.y.length; i++) { var ty = this.coordField.y[i] * cg.ch; for(var x = 0; x < this.cols; x++) { ctx.fillRect(x*cg.cw + this.x + 1, ty + this.y + 1, cg.cw - 2, cg.ch - 2); } } }; this.drawShots = function(ctx) { for(var y = 0; y < this.rows; y++) { for(var x = 0; x < this.cols; x++) { var xy = this.get(x, y); if(xy === cg.map.ShotOnWatter) { imageManager.s_blop.draw(this.x + x*cg.cw, this.y + y*cg.ch, ctx); } else if(xy === cg.map.ShotOnShip) { imageManager.s_fire.draw(this.x + x*cg.cw, this.y + y*cg.ch, ctx); } } } } this.checkCollisionOfShips = function() { this.shipCollision = false; this.collisionShips = []; var collision = false; for(var i = 0; i < game.currentPlayer.ships.length; i++) { var lodA = game.currentPlayer.ships[i]; for(var j = 0; j < game.currentPlayer.ships.length; j++) { var lodB = game.currentPlayer.ships[j]; if(this.collisionShips.contains(lodA) && this.collisionShips.contains(lodB)) break; if(lodA !== lodB && lodB.onMap && (lodA.onMap || game.selectedShip === lodA)) { collision = AABBIntersect(lodA.mx - 1, lodA.my - 1, lodA.mw + 2, lodA.mh + 2, lodB.mx, lodB.my, lodB.mw, lodB.mh); if(collision) { if(!this.collisionShips.contains(lodA)) this.collisionShips.push(lodA); if(!this.collisionShips.contains(lodB)) this.collisionShips.push(lodB); } } } } this.shipCollision = this.collisionShips.length > 0; }; } function Player(id) { this.id = id; this.map = new Map(cg.cols, cg.rows, id); this.ships = []; for(var i = 0; i < cg.poradiLodi.length; i++) { var id = cg.poradiLodi[i]; this.ships.push(new Ship(cg.ships[id], this)); } this.init = function() { var i; for(i = 0; i < this.ships.length; i++) { this.ships[i].init(cg.dock.x, cg.dock.y, cg.dires.Horizontal, false); } this.readyForBattle = false; this.destroyedShips = []; this.firing = false; }; this.initUpdate = function() { if(game.selectedShip !== null) { game.selectedShip.update(); } if(!game.dragAction) { var i; for(i = 0; i < this.ships.length; i++) this.ships[i].update(); } this.map.initUpdate(); }; this.shotUpdate = function() { if(this.firing) return; var enemyMap = game.secondPlayer.map; var mx = enemyMap.coordField.x[0]; var my = enemyMap.coordField.y[0]; if(mx !== undefined && my !== undefined && Mouse.clicked()) { if(enemyMap.get(mx, my) !== cg.map.ShotOnShip && enemyMap.get(mx, my) !== cg.map.ShotOnWatter) { this.fire(mx, my, enemyMap); } } }; this.fire = function(mx, my, map) { this.firing = true; var self = this; var sound = new Audio("sounds/fire.mp3"); sound.play() window.setTimeout(function(){ self.shot(mx, my, map); }, 1000); }; this.drawShips = function(ctx) { var i; for(i = 0; i < this.ships.length; i++) this.ships[i].draw(ctx); }; this.drawDestroyedShips = function(ctx) { var i; for(i = 0; i < this.destroyedShips.length; i++) { this.destroyedShips[i].draw(ctx); } }; //////////////////////////////////////// //////////////////////////////////////// this.setRandomlyShips = function() { var setAreas = []; for(var i = 0; i < this.ships.length; i++) { var lod = this.ships[i]; var volneSouradniceH = []; var volneSouradniceV = []; for(var x = 0; x < this.map.cols; x++) { for(var y = 0; y < this.map.rows; y++) { var souradnice = {x:x, y:y}; var kolizeV = false; var kolizeH = false; for(var j = 0; j < setAreas.length; j++) { var oblast = setAreas[j]; if(AABBIntersect(x, y, lod.type.length, 1, oblast.x, oblast.y, oblast.w, oblast.h)) kolizeH = true; if(AABBIntersect(x, y, 1, lod.type.length, oblast.x, oblast.y, oblast.w, oblast.h)) kolizeV = true; } if(x <= this.map.cols - lod.type.length && !kolizeH) volneSouradniceH.push(souradnice); if(y <= this.map.rows - lod.type.length && !kolizeV) volneSouradniceV.push(souradnice); } } var dir, rIndex, souradnice; if((volneSouradniceV.length > 0 && getRandom(0, 1) === 1) || (volneSouradniceV.length > 0 && volneSouradniceH == 0)) { dir = cg.dires.Vertical; rIndex = getRandom(0, volneSouradniceV.length - 1); souradnice = volneSouradniceV[rIndex]; } else { dir = cg.dires.Horizontal; rIndex = getRandom(0, volneSouradniceH.length - 1); souradnice = volneSouradniceH[rIndex]; } lod.init(souradnice.x*cg.cw + this.map.x, souradnice.y*cg.ch + this.map.y, dir, true); setAreas.push({ x: lod.mx - 1, //souradnice.x y: lod.my - 1, //souradnice.y w: lod.mw + 2, h: lod.mh + 2 }); } }; this.setShipsIntoMap = function() { for(var i = 0; i < this.ships.length; i++) { this.ships[i].setIntoMap(this.map); } }; this.getShipAt = function(mx, my) { var ship; for(var i = 0; i < this.ships.length; i++) { ship = this.ships[i]; if(mx >= ship.mx && mx <= ship.mx + ship.mw - 1 && my >= ship.my && my <= ship.my + ship.mh - 1) { return ship; } } return null; }; } Player.prototype.shot = function(mx, my, map) { var hit = false; var self = this; if(map.get(mx, my) === cg.map.Ship) hit = true; if(hit) { map.set(mx, my, cg.map.ShotOnShip); var hitedShip = game.secondPlayer.getShipAt(mx, my); hitedShip.takeDamage(); var sound = new Audio("sounds/explosion.wav"); sound.play(); window.setTimeout(function(){ self.firing = false; }, 1000); } else { map.set(mx, my, cg.map.ShotOnWatter); var sound = new Audio("sounds/splash.wav"); sound.play(); window.setTimeout(function(){ self.firing = false; game.currentPlayer = game.secondPlayer; game.secondPlayer = self; }, 1000); } } function Computer(id) { this.id = id; this.map = new Map(cg.cols, cg.rows, id); this.ships = []; this.hitedShip = { ship: null, shots: [], dir: null }; for(var i = 0; i < cg.poradiLodi.length; i++) { var id = cg.poradiLodi[i]; this.ships.push(new Ship(cg.ships[id], this)); } this.initUpdate = function() { this.setRandomlyShips(); game.finishInit(); }; this.shotUpdate = function() { //if(Mouse.down) return; if(this.firing) return; var enemyMap = game.secondPlayer.map; var possibleShots = []; if(this.hitedShip.ship !== null) { //select shotCoord arround hited ship var nshots = []; if(this.hitedShip.dir === null) { //dir is unknown var shot = this.hitedShip.shots[0]; nshots.push({mx: shot.mx - 1, my: shot.my}); nshots.push({mx: shot.mx + 1, my: shot.my}); nshots.push({mx: shot.mx, my: shot.my - 1}); nshots.push({mx: shot.mx, my: shot.my + 1}); } else if (this.hitedShip.dir === cg.dires.Horizontal) { //dir is horizontal var highestShot = this.getHighestShot(); var lowestShot = this.getLowestShot(); nshots.push({mx: highestShot.mx + 1, my: highestShot.my}); nshots.push({mx: lowestShot.mx - 1, my: lowestShot.my}); } else if(this.hitedShip.dir === cg.dires.Vertical) { //dir is vertical var highestShot = this.getHighestShot(); var lowestShot = this.getLowestShot(); nshots.push({mx: highestShot.mx, my: highestShot.my + 1}); nshots.push({mx: lowestShot.mx, my: lowestShot.my - 1}); } for(var i = 0; i < nshots.length; i++) { var nshot = nshots[i]; var hit = enemyMap.get(nshot.mx, nshot.my); if(hit === cg.map.Watter || hit === cg.map.Ship) //uprav { possibleShots.push(nshot); } } } else { //select shotCoord randomly from all map for(var i = 0; i < enemyMap.rows; i++) { for(var j = 0; j < enemyMap.cols; j++) { var coord = { mx: j, my: i}; if(enemyMap.get(coord.mx, coord.my) !== cg.map.ShotOnShip && enemyMap.get(coord.mx, coord.my) !== cg.map.ShotOnWatter) { possibleShots.push(coord); } } } } var randomIndex = getRandom(0, possibleShots.length -1); var shotCoord = possibleShots[randomIndex]; this.fire(shotCoord.mx, shotCoord.my, enemyMap); }; //get highest coord of shots at enemy ship this.getHighestShot = function() { var highestShot = this.hitedShip.shots[0]; for(var i = 1; i < this.hitedShip.shots.length; i++) { var shot = this.hitedShip.shots[i] if(shot.mx > highestShot.mx || shot.my > highestShot.my) highestShot = shot; } return highestShot; }; //get lowest coord of shots at enemy ship this.getLowestShot = function() { var lowestShot = this.hitedShip.shots[0]; for(var i = 1; i < this.hitedShip.shots.length; i++) { var shot = this.hitedShip.shots[i] if(shot.mx < lowestShot.mx || shot.my < lowestShot.my) lowestShot = shot; } return lowestShot; }; } Computer.prototype = new Player(); Computer.prototype.constructor = Player; Computer.prototype.shot = function(mx, my, map) { Player.prototype.shot.call(this, mx, my, map); //if was hited some ship if(map.get(mx, my) === cg.map.ShotOnShip) { if(this.hitedShip.ship === null) { var hitedShip = game.secondPlayer.getShipAt(mx, my); this.hitedShip.ship = hitedShip; } if(this.hitedShip.ship.alive) { this.hitedShip.shots.push({mx:mx, my:my}); if(this.hitedShip.shots.length === 2) { this.hitedShip.dir = this.hitedShip.ship.dir; } } else // ship is destroyed { this.hitedShip.ship = null; this.hitedShip.shots = []; this.hitedShip.dir = null; } } } function Ship(type, owner) { this.type = type; this.owner = owner; this.x; //real x this.y; //real y this.mx; //map x this.my; //map y this.w; //real w this.h; //real h this.mw; //map w this.mh; //map h this.dir; this.alive; this.init = function(x, y, dir, onMap) { this.setPosition(x, y); this.setDir(dir); this.alive = true; this.selected = false; this.onMap = onMap; this.lives = this.type.length; }; this.setDir = function(dir) { this.dir = dir; if(dir === cg.dires.Horizontal) { this.mw = this.type.length; this.mh = 1; } else if(dir === cg.dires.Vertical) { this.mw = 1; this.mh = this.type.length; } this.w = this.mw * cg.cw; this.h = this.mh * cg.ch; }; this.setPosition = function(x, y) { this.x = x; this.y = y; this.mx = Math.round((x - this.owner.map.x) / cg.cw); this.my = Math.round((y - this.owner.map.y) / cg.ch); }; this.offsetX = 0; this.offsetY = 0; this.update = function() { //Drag if(AABBIntersect(Mouse.x, Mouse.y, 0, 0, this.x, this.y, this.w, this.h) && Mouse.down && !game.dragAction) { this.offsetX = Mouse.x - this.x; this.offsetY = Mouse.y - this.y; game.selectedShip = this; game.dragAction = true; this.selected = true; this.onMap = false; } if(Mouse.down === false && this.selected) { this.selected = false; game.dragAction = false; this.setOnMap(this.owner.map); } if(this.selected) this.drag(this.offsetX, this.offsetY); }; this.draw = function(ctx) { ctx.fillStyle = cg.shipColor; ctx.fillRect(this.x, this.y, this.w, this.h); if(this.owner.map.collisionShips.contains(this)) { ctx.fillStyle = "rgba(255, 0, 0, 0.6)"; ctx.fillRect(this.x, this.y, this.w, this.h); } if(game.selectedShip === this) { ctx.fillStyle = "rgba(255, 255, 255, 0.4)"; ctx.fillRect(this.x, this.y, this.w, this.h); } ctx.strokeStyle = cg.shipStroke; ctx.lineWidth = "1"; ctx.strokeRect(this.x, this.y, this.w, this.h); }; this.drag = function(offsetX, offsetY) { this.setPosition(Mouse.x - offsetX, Mouse.y - offsetY); }; this.setOnMap = function(map) { if(this.x >= map.x && this.x + this.w <= map.x + map.w && this.y >= map.y && this.y + this.h <= map.y + map.h) { var nx = Math.round((this.x - map.x) / cg.cw) * cg.cw + map.x; var ny = Math.round((this.y - map.y) / cg.ch) * cg.ch + map.y; this.setPosition(nx , ny); this.onMap = true; } else { this.init(cg.dock.x, cg.dock.y, cg.dires.Horizontal, false); game.selectedShip = null; } }; this.setIntoMap = function(map) { if(!this.onMap) return; if(this.dir === cg.dires.Horizontal) { for(var i = 0; i < this.type.length; i++) { map.set(this.mx + i, this.my, cg.map.Ship); } } else if(this.dir === cg.dires.Vertical) { for(var i = 0; i < this.type.length; i++) { map.set(this.mx, this.my + i, cg.map.Ship); } } }; this.turn = function() { if(this.onMap) { if(this.dir === cg.dires.Horizontal) { this.setDir(cg.dires.Vertical); if(this.my + this.mh > this.owner.map.rows) this.setPosition(this.x, this.y - (this.h - cg.ch)); } else if (this.dir === cg.dires.Vertical) { this.setDir(cg.dires.Horizontal); if(this.mx + this.mw > this.owner.map.cols) this.setPosition(this.x - (this.w - cg.cw), this.y); } } }; this.takeDamage = function() { this.lives --; if(this.lives === 0) { this.alive = false; this.destroy(); } }; this.destroy = function() { var cx = this.mx - 1; var cy = this.my - 1; for(var i = 0; i < (this.type.length - 1) * 2 + 8; i++) { if(this.owner.map.get(cx, cy) === cg.map.Watter) { this.owner.map.set(cx, cy, cg.map.ShotOnWatter); } //jump to next row if(cx === this.mx + this.mw) { cx = this.mx - 1; cy++; } else { cx++; } //across ship body if(cy > this.my - 1 && cy < this.my + this.mh) { if(cx === this.mx) cx = this.mx + this.mw; } } this.owner.destroyedShips.push(this); }; }<file_sep>/README.md # SeaBattle JS canvas - simple sea battle game (my first project in JS canvas)
9f6d811621f6c82fe64b005147fe614dafeed69e
[ "JavaScript", "Markdown" ]
4
JavaScript
laura-kolcavova/SeaBattle
f76f0706319528b9527e23c93f50b118435b981c
61b97873b7f947dacd0f0230647f5b77e68e67a7
refs/heads/master
<repo_name>MarinaGoto/react_youtube_api<file_sep>/README.md "# react_youtube_api" Following the React-Redux tutorial by <NAME>, I have built a Youtube Player in ReactJS. The document "Step by step - Youtube Player in ReactJS" provides a step-by-step explanation of how to create the App. To follow through the instruction easily, code snips and snips of localhost UI are provided. You will also find some theory, for example: Difference between functional and class based component Use of an arrow function Definition and use of State Definition and use of Controlled Field Use of Downwards data flow Use of Props Definition and use of Key Handling Null Process Use of callback <file_sep>/src/components/header/navigation.js import React from 'react'; class Navigation extends React.Component { render() { return( <div id="navigator" className="navigation" > <nav> <ul> <li> Browse </li> <li> My List </li> <li> Recent </li> </ul> </nav> </div> ) } } export default Navigation;<file_sep>/src/components/header/profile.js import React from 'react'; class Profile extends React.Component { render(){ return( <div className="user_profile"> <div className="user"> <div className="name">Marina</div> <div className="image"> <img src="https://scontent.fosl1-1.fna.fbcdn.net/v/t1.0-9/22310554_2056505667905881_6274626765414205678_n.jpg?_nc_cat=0&oh=f2ee3a31daaa741a9383d951e0521900&oe=5BE72BB7" alt="profile"/> </div> </div> </div> ) } } export default Profile;<file_sep>/src/components/animate_load.js import React from 'react'; const AnimateLoad = ({show}) => { const componentClasses = ['example-component']; if (show) { componentClasses.push('show'); } return ( <div className={componentClasses.join(' ')}> </div> ); }; AnimateLoad.propTypes = { show: React.PropTypes.bool.isRequired }; export default AnimateLoad;
6aecf142adf47ff13a4857332ae028e104062642
[ "Markdown", "JavaScript" ]
4
Markdown
MarinaGoto/react_youtube_api
b86c2325fb67d9af5285e8688f94018f2066cda9
306cb6bb66ff51c7e5bd90a231033a1ffb2aa183
refs/heads/master
<repo_name>SourcingDenis/dasper<file_sep>/_plugins/htmlCompressor.rb module Jekyll module HtmlCompressor def htmlCompressor(data) #data.gsub("\n", "").gsub("\t", "").gsub(/<!--(?!<!)[^\[>].*?-->/, "") data.gsub(/<!--(?!<!)[^\[>].*?-->/, "") end end end Liquid::Template.register_filter(Jekyll::HtmlCompressor) <file_sep>/_posts/2016/07/2016-07-02-first-post.md --- layout: article title: First Post date: 2016-07-02 15:33:00+0200 coverPhoto: https://ozgrozer.github.io/dasper/contents/images/2016/07/jekyll.jpg --- Cupcake ipsum dolor sit amet cake. Cotton candy candy canes jujubes. Powder toffee I love sugar plum sweet roll candy cookie powder wafer. Tiramisu tootsie roll I love sweet chocolate cake cookie. Fruitcake I love gummies cheesecake sugar plum. Candy candy candy jelly jelly-o. ![](https://ozgrozer.github.io/dasper/contents/images/2016/07/jekyll.jpg) Carrot cake brownie jujubes gingerbread liquorice pastry I love croissant. I love bonbon powder chocolate cake apple pie dragée. Apple pie donut I love topping chocolate bar liquorice cotton candy liquorice. Marzipan apple pie sweet roll halvah oat cake I love pastry chocolate bar. Apple pie I love cookie brownie powder. Fruitcake chocolate bar I love jelly jelly carrot cake. Jelly beans toffee tart halvah icing macaroon gingerbread croissant. Jelly beans dragée cupcake cotton candy jelly dessert liquorice carrot cake. Sugar plum liquorice sugar plum jujubes marzipan bear claw donut cheesecake tart. I love muffin jujubes dragée pudding powder biscuit. Marshmallow halvah I love gummies I love cake dessert. Dragée marzipan dessert candy I love oat cake chocolate. Cotton candy cake icing cookie lollipop. Sweet candy halvah jelly beans toffee sesame snaps oat cake pastry. Pudding jelly beans ice cream candy canes sugar plum candy canes chocolate bar cookie. Chocolate toffee I love gummies gummies. I love sesame snaps croissant brownie I love. Candy canes I love I love sesame snaps fruitcake. Tart ice cream I love tootsie roll sweet roll brownie sweet roll. Marshmallow chocolate cake danish I love caramels candy canes gummi bears bonbon dragée. Biscuit tootsie roll oat cake gingerbread powder pudding. Jujubes dragée donut carrot cake muffin icing. Carrot cake wafer caramels pie apple pie sweet candy canes I love. Danish danish chocolate bar cake. Chocolate cake jujubes gummi bears lollipop topping. Sesame snaps marshmallow candy macaroon lemon drops pudding jujubes brownie. Croissant liquorice sugar plum I love sesame snaps lollipop I love bonbon. Tiramisu macaroon tootsie roll. I love jujubes caramels cheesecake. I love chupa chups carrot cake bonbon biscuit chocolate cake oat cake cake jujubes. Jelly danish pastry tart. Powder powder pie dessert marshmallow chocolate. <file_sep>/readme.md # Dasper Dasper is a [Jekyll](https://jekyllrb.com/) theme inspired by [Ghost](https://ghost.org/)'s default theme [Casper](https://demo.ghost.io/) and also [Jasper](https://biomadeira.github.io/jasper/) & [Kasper](http://rosario.io/). ## Live Demo - [ozgrozer.github.io/dasper](https://ozgrozer.github.io/dasper) ## Includes - Pagination - 404 page - Fastclick ([@ftlabs](https://github.com/ftlabs/fastclick)) - Syntax highlighting ([@PrismJS](https://github.com/PrismJS/prism)) - Sitemap generator ([@kinnetica](https://github.com/kinnetica/jekyll-plugins)) - RSS generator ([@agelber](https://github.com/agelber/jekyll-rss)) - Addthis sharing buttons - Disqus comments - Google Analytics tracking ## Usage 1. Fork the repo. 2. Change repo name from "dasper" to "username.github.io". 3. Update your informations in the `_config.yml` file. 4. You're ready to go on https://username.github.io/. ## Copyright & License Copyright (c) 2016 - Released under the MIT License.
91d552d712991ba66939d10897dabb16eabb22e4
[ "Markdown", "Ruby" ]
3
Ruby
SourcingDenis/dasper
18589ae12ed1552eadb659b3ddf827344358e8f6
63c122dd8292fa7dd83daaca51f7393f0db02c39
refs/heads/master
<repo_name>humpangle/gatsby-with-apollo<file_sep>/src/pages/index.js import React from 'react'; import { graphql } from 'gatsby'; import { Query } from 'react-apollo'; import gql from 'graphql-tag'; import { graphql as apolloGraphql } from 'react-apollo'; // This query is executed at build time by Gatsby. export const GatsbyQuery = graphql` query { rickAndMorty { character(id: 1) { name image } } } `; // This query is executed at run time by Apollo. const APOLLO_QUERY = gql` query { character(id: 1) { id name image } } `; export const Comp = ({ data: { rickAndMorty: { character }, }, apolloQuery: { character: characterFromApollo, loading, error }, }) => ( <div style={{ textAlign: 'center', width: '600px', margin: '50px auto' }}> <h1>{character.name} With His Pupper</h1> <p> Rick & Morty API data loads at build time. Dog API data loads at run time. </p> <div> <img src={character.image} alt={character.name} style={{ width: 300 }} /> {(function() { if (loading) return <p>Loading pupper...</p>; if (error) return <p>Error: ${error.message}</p>; const { image: src, name } = characterFromApollo; return <img src={src} alt={name} style={{ maxWidth: 300 }} />; })()} </div> </div> ); export default apolloGraphql(APOLLO_QUERY, { props: props => ({ apolloQuery: props.data }), })(Comp);
f3d4f36bb1bb74222c263eb9f49f793698ff8cbf
[ "JavaScript" ]
1
JavaScript
humpangle/gatsby-with-apollo
2d9980dd7a22ae8bf20ef139f0a9e56c0528ff5a
bc17baea12c92bba7430d5cbcef41cd05fe5bf68
refs/heads/master
<repo_name>DiMarioJulieta/Programacionbasica2<file_sep>/README.md # ProgramacionBasica2 Trabajos Practicos y demás. <file_sep>/.metadata/version.ini #Tue Apr 19 04:31:20 ART 2016 org.eclipse.core.runtime=2 org.eclipse.platform=4.5.2.v20160212-1500 <file_sep>/TrabajoPractico1/src/ar/edu/unlam/trabajo/practico1/Circulo.java package ar.edu.unlam.trabajo.practico1; import java.math.RoundingMode; import java.text.DecimalFormat; public class Circulo { private Double perimetro; private Double area; private Double radio; private DecimalFormat formato = new DecimalFormat("#0.00"); //Construcor con Radio public Circulo(Double radio) { formato.setRoundingMode(RoundingMode.DOWN); this.radio = radio; calcularPerimetro(); calcularArea(); } private void calcularArea() { area = radio * radio * Math.PI; } private void calcularPerimetro() { perimetro = 2 * Math.PI * radio; } public String getPerimetroTruncado() { return formato.format(perimetro); } public String getAreaTruncada() { return formato.format(area); } public Double getPerimetro() { return perimetro; } public void setPerimetro(Double perimetro) { this.perimetro = perimetro; } public Double getArea() { return area; } public void setArea(Double area) { this.area = area; } public Double getRadio() { return radio; } public void setRadio(Double radio) { this.radio = radio; } }
ea4aab21e2cc225b68d83cfcda91ceb05d07cfb7
[ "Markdown", "Java", "INI" ]
3
Markdown
DiMarioJulieta/Programacionbasica2
d51e3797afbf8f11014b9d646d62fb8df0b0455f
da2119ba08a6ae1843e4b187afcc6eb40e4942ba
refs/heads/master
<repo_name>gapgag55/Simple-Script<file_sep>/1.Location-Formidable-Thailand.php <?php //connect to mysql db $servername = "some servername"; $username = "some username"; $password = "<PASSWORD>"; $dbname = "some database"; // Create connection $conn = new mysqli($servername, $username, $password, $dbname); // Check connection if ($conn->connect_error) { die("Connection failed: " . $conn->connect_error); } echo "Connected successfully"; mysqli_set_charset($conn,"utf8"); //read the json file contents $changwats = file_get_contents('https://raw.githubusercontent.com/ignitry/thai-tambons/master/changwats/json/th.json'); $amphoes = file_get_contents('https://raw.githubusercontent.com/ignitry/thai-tambons/master/amphoes/json/th.json'); $tambons = file_get_contents('https://raw.githubusercontent.com/ignitry/thai-tambons/master/tambons/json/th.json'); //convert json object to php associative array $data = json_decode($changwats, true); $changwats = $data['th']['changwats']; $data = json_decode($amphoes, true); $amphoes = $data['th']['amphoes']; $data = json_decode($tambons, true); $tambons = $data['th']['tambons']; $frm_id = 12160; $itemID = 60426; $desc = "Some description"; foreach ($changwats as $changwat): // Array(pid, name) - $changwat foreach ($amphoes as $amphoe): // Array(pid, name, changwat_pid) if ($changwat['pid'] == $amphoe['changwat_pid']) { foreach ($tambons as $tambon): // Array(pid, name, latitude, longtitude, amphoe_pid, changwat_pid) if ($amphoe['pid'] == $tambon['amphoe_pid']) { $changwat_name = $changwat['name']; $amphoe_name = $amphoe['name']; $tambon_name = $tambon['name']; $frm_id++; // wp_frm_items $entry = "INSERT INTO wp_frm_items (id, item_key, name, description, ip, form_id, post_id, user_id, parent_item_id, is_draft, updated_by, created_at, updated_at) VALUES('$frm_id', '$frm_id', '$amphoe_name', '$desc', '172.17.0.1', 20, 0, 1, 0, 0, '2018-07-02 16:52:21', '2018-07-02 16:52:21', '2018-07-02 16:52:21')"; if ($conn->query($entry) === TRUE) { // echo "New entry created successfully"; } else { echo $conn->error; } $item_one = $itemID++; $item_two = $itemID++; $item_three = $itemID++; // //insert item meta $addItem = "INSERT INTO wp_frm_item_metas (id, meta_value, field_id, item_id, created_at) VALUES ('$item_one', '$changwat_name', '420', '$frm_id', '2018-07-02 16:52:21'), ('$item_two', '$amphoe_name', '419', '$frm_id', '2018-07-02 16:52:21'), ('$item_three', '$tambon_name', '418', '$frm_id', '2018-07-02 16:52:21')"; if ($conn->query($addItem) === TRUE) { // echo "New addItem created successfully"; } else { echo $conn->error; } } endforeach; } endforeach; endforeach; ?>
79c8ee89026cb836d5b79f01bc618ef19dc01c04
[ "PHP" ]
1
PHP
gapgag55/Simple-Script
dbbd19abbede9ab24eba9151e5700f133241e3c3
ae7e3129a146cbd02d6e7b7e2638b0b398b2076b
refs/heads/master
<repo_name>fancycheung/nlp-tutorial<file_sep>/1-2.Word2Vec/word2vector.py #!/usr/bin/env python2 # -*- coding: utf-8 -*- """ @author:nali @file: word2vector.py @time: 2019/3/13/下午3:47 @software: PyCharm """ """ comment here """ import sys import tensorflow as tf import numpy as np reload(sys) sys.setdefaultencoding("utf8") tf.reset_default_graph() # 3 Words Sentence sentences = [ "i like dog", "i like cat", "i like animal", "dog cat animal", "apple cat dog like", "dog fish milk like", "dog cat eyes like", "i like apple", "apple i hate", "apple i movie book music like", "cat dog hate", "cat dog like"] word_sequence = " ".join(sentences).split() word_list = " ".join(sentences).split() word_list = list(set(word_list)) word_list.sort() word_dict = {w: i for i, w in enumerate(word_list)} # Word2Vec Parameter batch_size = 20 embedding_size = 2# To show 2 dim embedding graph voc_size = len(word_list) def random_batch(data, size): random_inputs = [] random_labels = [] random_index = np.random.choice(range(len(data)), size, replace=False) for i in random_index: random_inputs.append(np.eye(voc_size)[data[i][0]]) # target random_labels.append(np.eye(voc_size)[data[i][1]]) # context word return random_inputs, random_labels skip_gram = [] for i in range(1, len(word_sequence) - 1): target = word_dict[word_sequence[i]] context = [word_dict[word_sequence[i-1]], word_dict[word_sequence[i+1]]] #上下文 for w in context: skip_gram.append([target, w]) #Model inputs = tf.placeholder(tf.float32, shape=[None, voc_size]) labels = tf.placeholder(tf.float32, shape=[None, voc_size]) #variable W = tf.Variable(tf.random_uniform([voc_size, embedding_size], -1.0, 1.0)) WT = tf.Variable(tf.random_uniform([embedding_size, voc_size], -1.0, 1.0)) hidden = tf.matmul(inputs, W) output = tf.matmul(hidden, WT) cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits_v2(logits=output, labels=labels)) optimizer = tf.train.AdamOptimizer(0.001).minimize(cost) # runner with tf.Session() as sess: init = tf.global_variables_initializer() sess.run(init) for epoch in range(5000): batch_inputs, batch_labels = random_batch(skip_gram, batch_size) _, loss = sess.run([optimizer, cost], feed_dict={inputs: batch_inputs, labels: batch_labels}) if (epoch + 1) % 1000 == 0: print('Epoch:', '%04d' % (epoch + 1), 'cost =', '{:.6f}'.format(loss)) trained_embeddings = W.eval() if __name__ == "__main__": pass<file_sep>/6.BaseAlgorithms/6-1.Rank/__init__.py #!/usr/bin/env python2 # -*- coding: utf-8 -*- """ @author:nali @file: __init__.py.py @time: 2019/3/14/上午11:20 @software: PyCharm """ """ 排序算法 """ import sys reload(sys) sys.setdefaultencoding("utf8") if __name__ == "__main__": pass<file_sep>/6.BaseAlgorithms/6-1.Rank/Rank.py #!/usr/bin/env python2 # -*- coding: utf-8 -*- """ @author:nali @file: Rank.py @time: 2019/3/14/上午11:23 @software: PyCharm """ """ 排序页面 """ import sys reload(sys) sys.setdefaultencoding("utf8") def bubbleRank(data): """ 冒泡排序是一种简单的排序算法。它重复地走访过要排序的数列,一次比较两个元素,如果它们的顺序错误就把它们交换过来。 走访数列的工作是重复地进行直到没有再需要交换,也就是说该数列已经排序完成。这个算法的名字由来是因为越小的元素会经由交换慢慢“浮”到数列的顶端。 比较相邻的元素。如果第一个比第二个大,就交换它们两个; 对每一对相邻元素作同样的工作,从开始第一对到结尾的最后一对,这样在最后的元素应该会是最大的数; 针对所有的元素重复以上的步骤,除了最后一个; 重复步骤1~3,直到排序完成。 冒泡排序 时间复杂度 O(n**2), 空间复杂度 O(1), 稳定排序 :param data: :return: """ length = data.__len__() for j in range(length - 1): for i in range(length - 1 - j): if data[i] > data[i+1]: data[i], data[i+1] = data[i+1], data[i] return data def selectorRank(data): """ 选择排序(Selection-sort)是一种简单直观的排序算法。它的工作原理:首先在未排序序列中找到最小(大)元素,存放到排序序列的起始位置, 然后,再从剩余未排序元素中继续寻找最小(大)元素,然后放到已排序序列的末尾。以此类推,直到所有元素均排序完毕。 初始状态:无序区为R[1..n],有序区为空; 第i趟排序(i=1,2,3…n-1)开始时,当前有序区和无序区分别为R[1..i-1]和R(i..n)。 该趟排序从当前无序区中-选出关键字最小的记录 R[k],将它与无序区的第1个记录R交换, 使R[1..i]和R[i+1..n)分别变为记录个数增加1个的新有序区和记录个数减少1个的新无序区; n-1趟结束,数组有序化了。 选择排序 时间复杂度 O(n**2), 空间复杂度 O(1), 不稳定排序 :param data: :return: """ length = data.__len__() for i in range(length - 1): index = i for j in range(i, length): if data[j] < data[index]: index = j data[i], data[index] = data[index], data[i] return data def insertRank(data): """ 插入排序(Insertion-Sort)的算法描述是一种简单直观的排序算法。 它的工作原理是通过构建有序序列,对于未排序数据,在已排序序列中从后向前扫描,找到相应位置并插入。 从第一个元素开始,该元素可以认为已经被排序; 取出下一个元素,在已经排序的元素序列中从后向前扫描; 如果该元素(已排序)大于新元素,将该元素移到下一位置; 重复步骤3,直到找到已排序的元素小于或者等于新元素的位置; 将新元素插入到该位置后; 重复步骤2~5。 插入排序 时间复杂度 O(n**2), 空间复杂度 O(1), 稳定排序 :param data: :return: """ length = data.__len__() for i in range(1, length): index = i - 1 current = data[i] while index >= 0 and current < data[index]: data[index + 1] = data[index] index -= 1 data[index + 1] = current return data def shellRank(data): """ 第一个突破O(n2)的排序算法,是简单插入排序的改进版。它与插入排序的不同之处在于, 它会优先比较距离较远的元素。希尔排序又叫缩小增量排序。 选择一个增量序列t1,t2,…,tk,其中ti>tj,tk=1; 按增量序列个数k,对序列进行k 趟排序; 每趟排序,根据对应的增量ti,将待排序列分割成若干长度为m 的子序列, 分别对各子表进行直接插入排序。仅增量因子为1 时,整个序列作为一个表来处理,表长度即为整个序列的长度。 希尔排序 时间复杂度 O(n**1.3), 空间复杂度 O(1), 不稳定排序 :param data: :return: """ length = data.__len__() gap = length/2 while gap > 0: for i in range(gap, length): j = i current = data[i] while j - gap > 0 and current < data[j - gap]: data[j] = data[j - gap] j -= gap data[j] = current gap = gap/2 return data def mergeSort(data): """ 归并排序是建立在归并操作上的一种有效的排序算法。该算法是采用分治法(Divide and Conquer)的一个非常典型的应用。将已有序的子序列合并, 得到完全有序的序列;即先使每个子序列有序,再使子序列段间有序。若将两个有序表合并成一个有序表,称为2-路归并。 把长度为n的输入序列分成两个长度为n/2的子序列; 对这两个子序列分别采用归并排序; 将两个排序好的子序列合并成一个最终的排序序列。 归并排序 时间复杂度 O(n*log(n)), 空间复杂度 O(n), 不稳定排序 :param data: :return: """ length = data.__len__() if length < 2: return data middle = length/2 return merge(mergeSort(data[0:middle]), mergeSort((data[middle:]))) def merge(left, right): """ 两个有序数组合并 :param left: :param right: :return: """ res = [] l_len = left.__len__() r_len = right.__len__() i, j = 0, 0 while i < l_len and j < r_len: if left[i] < right[j]: res.append(left[i]) i += 1 else: res.append(right[j]) j += 1 while i < l_len: res.append(left[i]) i += 1 while j < r_len: res.append(right[j]) j += 1 return res def quickSort(data, left, right): """ 快速排序的基本思想:通过一趟排序将待排记录分隔成独立的两部分, 其中一部分记录的关键字均比另一部分的关键字小,则可分别对这两部分记录继续进行排序,以达到整个序列有序。 从数列中挑出一个元素,称为 “基准”(pivot); 重新排序数列,所有元素比基准值小的摆放在基准前面,所有元素比基准值大的摆在基准的后面(相同的数可以到任一边)。在这个分区退出之后,该基准就处于数列的中间位置。这个称为分区(partition)操作; 递归地(recursive)把小于基准值元素的子数列和大于基准值元素的子数列排序 快速排序 时间复杂度 O(n*log(n)), 空间复杂度 O(n*log(n)), 不稳定排序 :param data: :return: """ if left < right: data, pivot = partition(data, left, right) quickSort(data, left, pivot-1) quickSort(data, pivot+1, right) return data def partition(data, left, right): """ 列表 :param data: :param left: :param right: :return: """ pivot = left index = left + 1 for i in range(left + 1, right): if data[i] < data[pivot]: data[i], data[index] = data[index], data[i] index += 1 data[pivot], data[index - 1] = data[index - 1], data[pivot] return data, index - 1 def heapSort(data): """ 堆排序(Heapsort)是指利用堆这种数据结构所设计的一种排序算法。堆积是一个近似完全二叉树的结构, 并同时满足堆积的性质:即子结点的键值或索引总是小于(或者大于)它的父节点。 将初始待排序关键字序列(R1,R2….Rn)构建成大顶堆,此堆为初始的无序区; 将堆顶元素R[1]与最后一个元素R[n]交换,此时得到新的无序区(R1,R2,……Rn-1)和新的有序区(Rn),且满足R[1,2…n-1]<=R[n]; 由于交换后新的堆顶R[1]可能违反堆的性质,因此需要对当前无序区(R1,R2,……Rn-1)调整为新堆,然后再次将R[1]与无序区最后一个元素交换, 得到新的无序区(R1,R2….Rn-2)和新的有序区(Rn-1,Rn)。不断重复此过程直到有序区的元素个数为n-1,则整个排序过程完成。 堆排序 时间复杂度 O(n*log(n)), 空间复杂度 O(1), 不稳定排序 :param data: :return: """ first = len(data)//2 - 1 for i in range(first, -1, -1): sift_down(data, i, len(data)-1) for ix in range(len(data)-1, 0, -1): data[ix], data[0] = data[0], data[ix] sift_down(data, i, ix - 1) return data def sift_down(data, start, end): while True: left = 2 * start + 1 if left > end: break if left + 1 < end and data[left+1] > data[left]: left += 1 if data[left] > data[start]: data[left], data[start] = data[start], data[left] start = left else: break if __name__ == "__main__": data = [1,3,4,2,8,6,5,3] # print bubbleRank(data) # print selectorRank(data) # print insertRank(data) # print shellRank(data) # print mergeSort(data) # print quickSort(data, 0, data.__len__()) print heapSort(data) pass
c0b5f90ffa71cf953d086a12d08d2cfaa34befef
[ "Python" ]
3
Python
fancycheung/nlp-tutorial
5fd27761a9c6c046533d6215e0bbb6ff99e22949
e958731efac4fdb9d3f054c36434919e1b8a4e75
refs/heads/master
<repo_name>Thorleye/Giphy-Project<file_sep>/README.md # Giphy-Project This is a webpage utilizing Giphy's API to create a dynamically generated page of Gifs. The Gifs will stop and start on a click. Click a button to load some gifs or search to _create a button on your own!_ Powered by Giphy©. Hosted on Github Pages. [Try the site for youself here](https://thorleye.github.io/Giphy-Project/) <file_sep>/assets/script.js //vars// var APIKey = "&api_key=<KEY>" var limit ="&limit=10" var rating = "&rating=g" //Initial array// var gifArray = ["NBA-block", "NBA-windmill", "NBA-tomahawk" ,"NBA-half-court", "NFL-celebration", "NFL-sack", "NFL-touchdown", "NHL-breakaway", "Fifa-bicycle-kick", "NHL-save", "NHL-hit", ] //creating the buttons based on the array// var makeButtons = function(){ // Delete the content inside the movies-view div prior to adding new movies $("#gif-button-area").empty() //loop to make it work for (i=0; i < gifArray.length; i++){ var gifButton = $("<button>") gifButton.text(gifArray[i]); gifButton.addClass("btn btn-primary"); //bootstrap formatting// gifButton.addClass("gifCreate") gifButton.attr("data-name", gifArray[i]); $("#gif-button-area").append(gifButton); } } // add the button based on the array on the search // var searchGif = function(){ $("#searchButton").on("click", function(event){ event.preventDefault() var newGif = $("#gif-search").val().trim() gifArray.push(newGif) makeButtons() gifCall() $("#gif-search").val("") }) } //function to make ajax call// function gifCall(){ $(".gifCreate").on("click", function(){ var keyword = $(this).attr("data-name"); var queryURL = "https:/" + "/api.giphy.com/v1/gifs/search?q=" + keyword + APIKey + limit + rating $.ajax({ url: queryURL, method: "GET" }).then(function(response){ //put results into divs to go into gif-area// var results = response.data; console.log(results) for (var i=0; i < results.length; i++){ var gifDiv = $("<div class='item'>"); var rating = results[i].rating; var p = $("<p>").text("Rating: " + rating); var gifImage = $("<img>") //url for the static image// gifImage.attr("src", results[i].images.fixed_height_still.url) //setting data for still images gifImage.attr("data-still", results[i].images.fixed_height_still.url) gifImage.attr("data-state", "static") // url for the moving gif// gifImage.attr("data-animate", results[i].images.fixed_height.url) gifDiv.prepend(p); gifDiv.append(gifImage); $("#gif-display-area").prepend(gifDiv) } //fun instructions to change from still to moving and back again// $("img").on("click", function(){ var state = $(this).attr("data-state") console.log(state) if (state ==="static"){ $(this).attr("src", $(this).attr("data-animate")) $(this).attr("data-state", "animated") } if (state === "animated"){ $(this).attr("src", $(this).attr("data-still")) $(this).attr("data-state", "static") } }) }) }) } function startup(){ makeButtons() searchGif() gifCall() } startup()
cda2fd02809281b64325b0a078b1ad5cd29459a1
[ "Markdown", "JavaScript" ]
2
Markdown
Thorleye/Giphy-Project
bcb0bbd239d5572dbdd450e53be4d9f8a6bc0eb6
99170ae8638a10d4efa75376ba3d944c4fb34e44
refs/heads/master
<file_sep># pygameproject2 # ontsnapperdam project 2 groep 2 <file_sep>import pygame import Game as dm pygame.init() def Players(): pygame.mixer.music.load("music.mp3") pygame.mixer.music.play(loops=0, start=0.0) size = width, height = 340,240 screen = pygame.display.set_mode(size) redSquare = pygame.image.load('achtergrondopties.png').convert() white = (255,255,255) w = 700 h = 420 screen = pygame.display.set_mode((w, h)) screen.fill((white)) x = 0 y = 0 screen.blit(redSquare, (x, y)) pygame.display.flip() black = (0,0,0) pygame.mixer.music.play(loops=0, start=0.0) choose = dm.dumbmenu(screen,[ '- 3 spelers', '- 4 spelers', '- 5 spelers', '- 6 spelers', '- speel met de computer', '- terug naar het menu'] , 200,150,None,35,1.4,black ,black) if choose == 0: print ("Je hebt gekozen voor 3 spelers.") elif choose == 1: print ("Je hebt gekozen voor 4 spelers'.") elif choose == 2: print( "Je hebt gekozen voor 5 spelers'.") elif choose == 3: print ("Je hebt gekozen voor 6 spelers'.") elif choose == 4: print ("Je hebt gekozen voor spelen met computer.") elif choose == 5: print('Je hebt gekozen voor terug naar menu ') <file_sep>import pygame import Manual as M import Game as dm import sys pygame.init() def music(): if True: pygame.mixer.music.load("music.mp3") pygame.mixer.music.play(loops = 999, start = 0.0) pygame.mixer.music.set_volume(0.2) def Hoofdmenu(): redSquare = pygame.image.load('MENU.png') white = (255,255,255) w = 700 h = 420 screen = pygame.display.set_mode((w, h)) screen.fill((white)) x = 0 y = 0 black = (0,0,0) screen.blit(redSquare, (x, y)) pygame.display.flip() choose = dm.dumbmenu(screen, ['Start Game', 'Options', 'Manual', 'Show Highscore'], 200,150,None,35,1.4,black ,black) if choose == 0: Players() print ("You choose 'Start Game'.") elif choose == 1: opties() print ("You choose 'Options'.") elif choose == 2: story() print( "You choose 'Manual'.") elif choose == 3: Hoofdmenu() print ("You choose 'Show Highscore'.") elif choose == 4: print ("You choose 'Quit Game'.") pygame.init() def Players(): redSquare = pygame.image.load('achtergrondopties.png').convert() white = (255,255,255) w = 700 h = 420 screen = pygame.display.set_mode((w, h)) screen.fill((white)) x = 0 y = 0 screen.blit(redSquare, (x, y)) pygame.display.flip() black = (0,0,0) choose = dm.dumbmenu(screen,[ '- 3 spelers', '- 4 spelers', '- 5 spelers', '- 6 spelers', '- speel met de computer', '- terug naar het menu'] , 200,150,None,35,1.4,black ,black) if choose == 0: M.program() Hoofdmenu() print ("Je hebt gekozen voor 3 spelers.") elif choose == 1: Hoofdmenu() print ("Je hebt gekozen voor 4 spelers'.") elif choose == 2: Hoofdmenu() print( "Je hebt gekozen voor 5 spelers'.") elif choose == 3: Hoofdmenu() print ("Je hebt gekozen voor 6 spelers'.") elif choose == 4: Hoofdmenu() print ("Je hebt gekozen voor spelen met computer.") elif choose == 5: Hoofdmenu() print('Je hebt gekozen voor terug naar menu ') def opties(): redSquare = pygame.image.load('achtergrondSpelers.png').convert() white = (255,255,255) w = 700 h = 420 screen = pygame.display.set_mode((w, h)) screen.fill((white)) x = 0 y = 0 screen.blit(redSquare, (x, y)) pygame.display.flip() black = (0,0,0) choose = dm.dumbmenu(screen,[ 'Geluid uit', 'Taal wijzigen -> Engels', 'Terug naar het menu'] , 180,150,None,35,1.4,black ,black) if choose == 0: musicAan = False Hoofdmenu() print ("Je hebt gekozen voor Geluid uit'.") elif choose == 1: print ("Je hebt gekozen voor Taal wijzigen naar het engels''.") elif choose == 2: Hoofdmenu() print( "Je hebt gekozen voor Terug naar het menu'.") def story(): redSquare = pygame.image.load('Story.png').convert() white = (255, 64, 64) w = 810 h = 420 screen = pygame.display.set_mode((w, h)) screen.fill((white)) screen.fill((white)) x = 0 y = 0 screen.blit(redSquare, (x, y)) pygame.display.flip() running = True while (running): for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() sys.exit() if event.type == pygame.MOUSEBUTTONDOWN: x, y = event.pos if redSquare.get_rect().collidepoint(x, y): regels() def regels(): redSquare = pygame.image.load('Naamloos.png').convert() clock = pygame.time.Clock() white = (255, 64, 64) w = 810 h = 420 screen = pygame.display.set_mode((w, h)) screen.fill((white)) screen.fill((white)) x = 0 y = 0 screen.blit(redSquare, (x, y)) pygame.display.flip() running = True while (running): for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() sys.exit() if event.type == pygame.MOUSEBUTTONDOWN: x, y = event.pos if redSquare.get_rect().collidepoint(x, y): regels2() def regels2(): redSquare = pygame.image.load('Regels2.png').convert() clock = pygame.time.Clock() white = (255, 64, 64) w = 810 h = 420 screen = pygame.display.set_mode((w, h)) screen.fill((white)) screen.fill((white)) x = 0 y = 0 screen.blit(redSquare, (x, y)) pygame.display.flip() running = True while (running): for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() sys.exit() if event.type == pygame.MOUSEBUTTONDOWN: x, y = event.pos if redSquare.get_rect().collidepoint(x, y): regels3() def regels3(): redSquare = pygame.image.load('Regels3.png').convert() clock = pygame.time.Clock() white = (255, 64, 64) w = 810 h = 420 screen = pygame.display.set_mode((w, h)) screen.fill((white)) screen.fill((white)) x = 0 y = 0 screen.blit(redSquare, (x, y)) pygame.display.flip() running = True while (running): for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() sys.exit() if event.type == pygame.MOUSEBUTTONDOWN: x, y = event.pos if redSquare.get_rect().collidepoint(x, y): regels4() def regels4(): redSquare = pygame.image.load('surprisekaart.png').convert() clock = pygame.time.Clock() white = (255, 64, 64) w = 810 h = 420 screen = pygame.display.set_mode((w, h)) screen.fill((white)) screen.fill((white)) x = 0 y = 0 screen.blit(redSquare, (x, y)) pygame.display.flip() running = True while (running): for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() sys.exit() if event.type == pygame.MOUSEBUTTONDOWN: x, y = event.pos if redSquare.get_rect().collidepoint(x, y): regels5() def regels5(): redSquare = pygame.image.load('Questregels2.png').convert() clock = pygame.time.Clock() white = (255, 64, 64) w = 810 h = 420 screen = pygame.display.set_mode((w, h)) screen.fill((white)) screen.fill((white)) x = 0 y = 0 screen.blit(redSquare, (x, y)) pygame.display.flip() running = True while (running): for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() sys.exit() if event.type == pygame.MOUSEBUTTONDOWN: x, y = event.pos if redSquare.get_rect().collidepoint(x, y): regels6() def regels6(): redSquare = pygame.image.load('Powerupregels.png').convert() clock = pygame.time.Clock() white = (255, 64, 64) w = 810 h = 420 screen = pygame.display.set_mode((w, h)) screen.fill((white)) screen.fill((white)) x = 0 y = 0 screen.blit(redSquare, (x, y)) pygame.display.flip() running = True while (running): for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() sys.exit() if event.type == pygame.MOUSEBUTTONDOWN: x, y = event.pos if redSquare.get_rect().collidepoint(x, y): regels7() def regels7(): redSquare = pygame.image.load('Powerupregels2.png').convert() clock = pygame.time.Clock() white = (255, 64, 64) w = 810 h = 420 screen = pygame.display.set_mode((w, h)) screen.fill((white)) screen.fill((white)) x = 0 y = 0 screen.blit(redSquare, (x, y)) pygame.display.flip() running = True while (running): for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() sys.exit() if event.type == pygame.MOUSEBUTTONDOWN: x, y = event.pos if redSquare.get_rect().collidepoint(x, y): regels8() def regels8(): redSquare = pygame.image.load('Battleregels.png').convert() clock = pygame.time.Clock() white = (255, 64, 64) w = 810 h = 420 screen = pygame.display.set_mode((w, h)) screen.fill((white)) screen.fill((white)) x = 0 y = 0 screen.blit(redSquare, (x, y)) pygame.display.flip() running = True while (running): for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() sys.exit() if event.type == pygame.MOUSEBUTTONDOWN: x, y = event.pos if redSquare.get_rect().collidepoint(x, y): regels9() def regels9(): redSquare = pygame.image.load('Battleregels2.png').convert() clock = pygame.time.Clock() white = (255, 64, 64) w = 810 h = 420 screen = pygame.display.set_mode((w, h)) screen.fill((white)) screen.fill((white)) x = 0 y = 0 screen.blit(redSquare, (x, y)) pygame.display.flip() running = True while (running): for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() sys.exit() if event.type == pygame.MOUSEBUTTONDOWN: x, y = event.pos if redSquare.get_rect().collidepoint(x, y): regels10() def regels10(): redSquare = pygame.image.load('Battleregels3.png').convert() clock = pygame.time.Clock() white = (255, 64, 64) w = 810 h = 420 screen = pygame.display.set_mode((w, h)) screen.fill((white)) screen.fill((white)) x = 0 y = 0 screen.blit(redSquare, (x, y)) pygame.display.flip() running = True while (running): for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() sys.exit() if event.type == pygame.MOUSEBUTTONDOWN: x, y = event.pos if redSquare.get_rect().collidepoint(x, y): Hoofdmenu() print('Einde terug naar menu') def regels11(): redSquare = pygame.image.load('Howtoplay.png').convert() clock = pygame.time.Clock() white = (255, 64, 64) w = 810 h = 420 screen = pygame.display.set_mode((w, h)) screen.fill((white)) screen.fill((white)) x = 0 y = 0 screen.blit(redSquare, (x, y)) pygame.display.flip() running = True while (running): for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() sys.exit() if event.type == pygame.MOUSEBUTTONDOWN: x, y = event.pos if redSquare.get_rect().collidepoint(x, y): regels12() def regels12(): redSquare = pygame.image.load('Howtoplay2.png').convert() clock = pygame.time.Clock() white = (255, 64, 64) w = 810 h = 420 screen = pygame.display.set_mode((w, h)) screen.fill((white)) screen.fill((white)) x = 0 y = 0 screen.blit(redSquare, (x, y)) pygame.display.flip() running = True while (running): for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() sys.exit() if event.type == pygame.MOUSEBUTTONDOWN: x, y = event.pos if redSquare.get_rect().collidepoint(x, y): regels13() def regels13(): redSquare = pygame.image.load('Howtoplay3.png').convert() clock = pygame.time.Clock() white = (255, 64, 64) w = 810 h = 420 screen = pygame.display.set_mode((w, h)) screen.fill((white)) screen.fill((white)) x = 0 y = 0 screen.blit(redSquare, (x, y)) pygame.display.flip() running = True while (running): for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() sys.exit() if event.type == pygame.MOUSEBUTTONDOWN: x, y = event.pos if redSquare.get_rect().collidepoint(x, y): regels14() def regels14(): redSquare = pygame.image.load('Howtoplay4.png').convert() clock = pygame.time.Clock() white = (255, 64, 64) w = 810 h = 420 screen = pygame.display.set_mode((w, h)) screen.fill((white)) screen.fill((white)) x = 0 y = 0 screen.blit(redSquare, (x, y)) pygame.display.flip() running = True while (running): for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() sys.exit() if event.type == pygame.MOUSEBUTTONDOWN: x, y = event.pos if redSquare.get_rect().collidepoint(x, y): regels15() def regels15(): redSquare = pygame.image.load('Howtoplay5.png').convert() clock = pygame.time.Clock() white = (255, 64, 64) w = 810 h = 420 screen = pygame.display.set_mode((w, h)) screen.fill((white)) screen.fill((white)) x = 0 y = 0 screen.blit(redSquare, (x, y)) pygame.display.flip() running = True while (running): for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() sys.exit() if event.type == pygame.MOUSEBUTTONDOWN: x, y = event.pos if redSquare.get_rect().collidepoint(x, y): story() ################################################################################################################################# # # # ################################################################################################################################# def story(): redSquare = pygame.image.load('Story.png').convert() clock = pygame.time.Clock() white = (255, 64, 64) w = 810 h = 420 screen = pygame.display.set_mode((w, h)) screen.fill((white)) screen.fill((white)) x = 0 y = 0 screen.blit(redSquare, (x, y)) pygame.display.flip() running = True while (running): for event in pygame.event.get(): if event.type == pygame.QUIT: running = False if event.type == pygame.MOUSEBUTTONDOWN: x, y = event.pos if redSquare.get_rect().collidepoint(x, y): regels() Hoofdmenu() <file_sep>#### dit staat in de player class def winner(self): if (self.pos.x, self.pos.y) == (16, 30) and self.moves == 0 and self.turn and self.alive and dubbel(self.namet) == False: # upload winner screen self.score += 10 insert_naam(self.namet, self.score) update_score(self.namet, self.score) elif (self.pos.x, self.pos.y) == (16, 30) and self.moves == 0 and self.turn and self.alive : self.score += 10 update_score(self.namet, self.score) ######################################## ### vergeet niet aanteroepen voor elke speler### <file_sep>def chance(self): global chance_vakjes for i in chance_vakjes: if (self.pos.y, self.pos.x) == i and self.moves == 0 and self.turn and self.alive: supr = random.randrange(1,12) if supr == 1: if self.verder : self.skip = False self.verder = False screen.blit(sp1,(150,200)) pygame.display.flip() time.sleep(0) print("ga verder") else: self.skip = True self.verder = True screen.blit(sp1, (150,200)) pygame.display.flip() time.sleep(0) print("beurt wachten") # upload image sp1 elif supr == 2: if self.verder : self.skip = False self.verder = False screen.blit(sp2,(150,200)) pygame.display.flip() time.sleep(0) print("ga verder") else: self.skip = True self.verder = True screen.blit(sp2, (150,200)) pygame.display.flip() time.sleep(1) print("beurt wachten") # upload image sp2 elif supr == 3: screen.blit(sp25, (150,200)) pygame.display.flip() time.sleep(8) self.moves += 5 print("5stappen") # upload image sp25 elif supr == 4: if self.verder : self.skip = False self.verder = False screen.blit(sp13,(150,200)) pygame.display.flip() time.sleep(0) print("ga verder") else: self.skip = True self.verder = True screen.blit(sp3, (150,200)) pygame.display.flip() time.sleep(1) print("beurt wachten") elif supr == 5: screen.blit(sp18, (150,200)) pygame.display.flip() time.sleep(8) self.moves += 1 # upload image sp7 elif supr == 6: self.turn = False screen.blit(sp20, (150,200)) pygame.display.flip() time.sleep(8) print("gooi nog een keer") # gooi nog een keer # upload image sp20 elif supr == 7: self.turn = False screen.blit(sp12, (150,200)) pygame.display.flip() time.sleep(8) print("gooi nog een keer") # gooi nog een keer # upload image sp12 elif supr == 8: screen.blit(sp16, (150,200)) pygame.display.flip() time.sleep(8) pass # gebeurt niks # upload image sp16 elif supr == 9: screen.blit(sp19, (150,200)) pygame.display.flip() time.sleep(8) self.moves += 1 print("dobbel + 1") # next worp + 1 # upload image sp18 elif supr == 10: screen.blit(sp32, (150,200)) pygame.display.flip() time.sleep(8) pass # niks # upload image sp32 elif supr == 11: self.dobbel = True screen.blit(sp19, (150,200)) pygame.display.flip() time.sleep(8) self.moves += 1 print("dobbel + 1") # next worp + 1 # upload image sp19 #################################### # vergeet niet om hem aanteroepen # ####################################### <file_sep>import psycopg2 ##################### def interact_with_database(command): connection = psycopg2.connect(" host = localhost dbname= project2 user= postgres password = <PASSWORD>") cursor = connection.cursor() # Execute the command cursor.execute(command) connection.commit() # Save results results = None try: results = cursor.fetchall() except psycopg2.ProgrammingError: # Nothing to fetch pass # Close connection cursor.close() connection.close() return results def update_score(name, score): upload_score(name, score) def dubbel(name): if interact_with_database("SELECT name FROM player WHERE name != ('{}')".format(name)): return True else: return False print("database") def upload_score(name, score): interact_with_database("UPDATE player SET score = {} WHERE name = '{}'" .format(score, name)) def insert_naam(name, score): interact_with_database("INSERT INTO player VALUES ('{}',{})".format(name, score)) update_score(name,score) print("database") def download_top_score(): result = interact_with_database("SELECT name,score FROM player ORDER BY score DESC")[0][0] return result def download_top_name(): result = interact_with_database("SELECT * FROM player ORDER BY score DESC")[0][1] return str(result) def download_top_score2(): result = interact_with_database("SELECT name,score FROM player ORDER BY score DESC")[1][0] return result def download_top_name2(): result = interact_with_database("SELECT * FROM player ORDER BY score DESC")[1][1] return str(result) def download_top_score3(): result = interact_with_database("SELECT name,score FROM player ORDER BY score DESC")[2][0] return result def download_top_name3(): result = interact_with_database("SELECT * FROM player" " ORDER BY score DESC")[2][1] return str(result) def scherm(): score = str(download_top_score()) naam = str(download_top_name()) score2 = str(download_top_score2()) naam2 = str(download_top_name2()) score3 = str(download_top_score3()) naam3 = str(download_top_name3()) screen = pygame.display.set_mode((1700, 1000)) screen.fill((255,255,255)) pygame.display.set_caption("ontsnapperdam") myfont = pygame.font.SysFont("Comic Sans MS", 30) highscore = pygame.image.load("highscore.png") eerste = myfont.render("1.", 200, (0, 0, 0)) tweede = myfont.render("2.", 200, (0, 0, 0)) derde = myfont.render("3. ", 200, (0, 0, 0)) label = myfont.render((score), 200, (0,0,0)) label1 = myfont.render((naam), 200, (0, 0, 0)) label2 = myfont.render((score2), 200, (0, 0, 0)) label3 = myfont.render((naam2), 200, (0, 0, 0)) label4 = myfont.render((score3), 200, (0, 0, 0)) label5 = myfont.render((naam3), 200, (0, 0, 0)) screen.blit(highscore, (0, 0)) screen.blit(eerste, (460, 190)) screen.blit(label, (480, 190)) screen.blit(label1, (700, 190)) screen.blit(tweede, (460, 220)) screen.blit(label2, (480, 220)) screen.blit(label3, (700, 220)) screen.blit(derde, (460, 250)) screen.blit(label4, (480, 250)) screen.blit(label5, (700, 250)) pygame.display.flip() # event loop while True: for event in pygame.event.get(): if event.type == pygame.QUIT: raise SystemExit if event.type == pygame.MOUSEBUTTONDOWN: x, y = event.pos if highscore.get_rect().collidepoint(x, y): HoofdmenuNL() ############################################################################################################# <file_sep> # Foto's van de kaartjes sp1 = pygame.image.load('suprisekaart1.png') sp2 = pygame.image.load('suprisekaart2.png') sp3 = pygame.image.load('suprisekaart3.png') sp6 = pygame.image.load('suprisekaart6.png') sp7 = pygame.image.load('suprisekaart7.png') sp8 = pygame.image.load('suprisekaart8.png') sp10 = pygame.image.load('suprisekaart10.png') sp12 = pygame.image.load('surprisekaarten12.png') sp16 = pygame.image.load('surprisekaarten16.png') sp32 = pygame.image.load('surprisekaarten32.png') spr4 = pygame.image.load('suprisekaart4.png') spr31 = pygame.image.load('surprisekaarten31.png') sp18 = pygame.image.load('surprisekaarten18.png') sp19 = pygame.image.load('surprisekaarten19.png') sp20 = pygame.image.load('surprisekaarten20.png') # Methode moet in de class Player def chance(self): global chance_vakjes for i in chance_vakjes: if (self.pos.y, self.pos.x) == i and self.moves == 0 and self.turn and self.alive: supr = random.randrange(1,12) # niet alle kaartjen worden nu random gekozen if supr == 1: if self.moves == 0: pass else: self.skip = True # upload image sp1 elif supr == 2: self.skip = True print("beurt over slaan") # upload image sp2 elif supr == 3: self.moves += 5 print("5stappen") # upload image sp6 elif supr == 4: self.skip = True print("beurt over slaan") # upload image sp3 elif supr == 5: self.moves += 1 # upload image sp7 elif supr == 6: self.turn = False print("gooi nog een keer") # gooi nog een keer # upload image sp20 elif supr == 7: self.turn = False print("gooi nog een keer") # gooi nog een keer # upload image sp12 elif supr == 8: pass # gebeurt niks # upload image sp16 elif supr == 9: self.dobbel = True print("dobbel + 1") # next worp + 1 # upload image sp18 elif supr == 10: pass # niks # upload image sp32 elif supr == 11: self.dobbel = True print("dobbel + 1") # next worp + 1 # upload image sp19 elif supr == 12: pass # Ga terug naar je meest recente landmark # upload image sp10 elif supr == 13: pass # 1 van je Quest is volbracht # upload image sp7 <file_sep>import random uitkomst = random.randrange(1, 6) if uitkomst == 1: print("gegooide cijfer is 1") if uitkomst == 2: print("gegooide cijfer is 2") if uitkomst == 3: print("gegooide cijfer is 3") if uitkomst == 4: print("gegooide cijfer is 4") if uitkomst == 5: print("gegooide cijfer is 5") if uitkomst == 6: print("gegooide cijfer is 6") <file_sep># foto powerup pw1 = pygame.image.load('pw1.png') pw2 = pygame.image.load('pw2.png') pw3 = pygame.image.load('pw3.png') pw4 = pygame.image.load('pw4.png') pw5 = pygame.image.load('pw5.png') pw6 = pygame.image.load('pw6.png') pw7 = pygame.image.load('pw7.png') pw8 = pygame.image.load('pw8.png') pw9 = pygame.image.load('pw9.png') pw10 = pygame.image.load('pw10.png') helepowerup = [(1,16),(3,10),(6,17),(8,31),(10,22),(11,10),(13,27),(18,17),(19,9)] # power up def def powerupvak(self): global helepowerup if self.powerup == '': for i in helepowerup: if (self.pos.y,self.pos.x) == i and self.moves >= 0 and self.turn and self.alive and beurt == self.name: if i == (1,16): self.powerup = 'sniper' elif i == (3,10): self.powerup = 'wildfire' screen.blit(pw9,(150,200)) pygame.display.flip() time.sleep(8) self.moves += 5 print("ja") elif i == (6,17): self.powerup = 'ufo' screen.blit(pw4,(150,200)) pygame.display.flip() time.sleep(8) self.turn = False elif i == (8,31): self.powerup = 'plusultra' screen.blit(pw6,(150,200)) pygame.display.flip() time.sleep(8) self.turn = False print("ja") # upload image pw6 elif i == (10,22): self.powerup = 'taxi' screen.blit(pw2,(150,200)) pygame.display.flip() time.sleep(8) self.moves += 5 print("ja") elif i == (11,10): self.powerup = 'fiets' screen.blit(pw1,(150,200)) pygame.display.flip() time.sleep(8) self.turn = False print("ja") elif i == (13,27): self.powerup = 'slowdown' screen.blit(pw7,(150,200)) pygame.display.flip() time.sleep(8) self.moves += 5 print("ja") elif i == (18,17): self.powerup = 'camouflage' screen.blit(pw5,(150,200)) pygame.display.flip() time.sleep(8) self.moves += 5 print("ja") elif i == (19,9): self.powerup = 'fusrodah' screen.blit(pw8,(150,200)) pygame.display.flip() time.sleep(8) self.turn = False # roepen in program p1.powerupvak() p2.powerupvak() p3.powerupvak() p4.powerupvak() p5.powerupvak() p6.powerupvak() ################################################################## #1e try def power(self): global fusro global fietss global wild global cam global tax global klok global box while True: if (self.pos.y, self.pos.x) == fusro and self.moves >= 0 and self.turn and self.alive: screen.blit(pw8,(150,200)) pygame.display.flip() time.sleep(8) self.turn = False print("ja") # upload image pw8 elif (self.pos.y, self.pos.x) == fietss and self.moves >= 0 and self.turn and self.alive: screen.blit(pw1,(150,200)) pygame.display.flip() time.sleep(8) self.turn = False print("ja") # upload image pw1 elif (self.pos.y, self.pos.x) == wild and self.moves >= 0 and self.turn and self.alive: screen.blit(pw9,(150,200)) pygame.display.flip() time.sleep(8) self.moves += 5 print("ja") # upload image pw9 elif (self.pos.y, self.pos.x) == cam and self.moves >= 0 and self.turn and self.alive: screen.blit(pw5,(150,200)) pygame.display.flip() time.sleep(8) self.moves += 5 print("ja") # upload image pw5 elif (self.pos.y, self.pos.x) == tax and self.moves >= 0 and self.turn and self.alive: screen.blit(pw2,(150,200)) pygame.display.flip() time.sleep(8) self.moves += 5 print("ja") # upload image pw2 elif (self.pos.y, self.pos.x) == klok and self.moves >= 0 and self.turn and self.alive: screen.blit(pw7,(150,200)) pygame.display.flip() time.sleep(8) self.moves += 5 print("ja") # upload image pw7 elif (self.pos.y, self.pos.x) == box and self.moves >= 0 and self.turn and self.alive: screen.blit(pw6,(150,200)) pygame.display.flip() time.sleep(8) self.turn = False print("ja") # upload image pw6 <file_sep>import pygame import sys def story(): redSquare = pygame.image.load('Story.png').convert() clock = pygame.time.Clock() white = (255, 64, 64) w = 810 h = 420 screen = pygame.display.set_mode((w, h)) screen.fill((white)) screen.fill((white)) x = 0 y = 0 screen.blit(redSquare, (x, y)) pygame.display.flip() running = True while (running): for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() sys.exit() if event.type == pygame.MOUSEBUTTONDOWN: x, y = event.pos if redSquare.get_rect().collidepoint(x, y): regels() def regels(): redSquare = pygame.image.load('Naamloos.png').convert() clock = pygame.time.Clock() white = (255, 64, 64) w = 810 h = 420 screen = pygame.display.set_mode((w, h)) screen.fill((white)) screen.fill((white)) x = 0 y = 0 screen.blit(redSquare, (x, y)) pygame.display.flip() running = True while (running): for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() sys.exit() if event.type == pygame.MOUSEBUTTONDOWN: x, y = event.pos if redSquare.get_rect().collidepoint(x, y): regels2() def regels2(): redSquare = pygame.image.load('Regels2.png').convert() clock = pygame.time.Clock() white = (255, 64, 64) w = 810 h = 420 screen = pygame.display.set_mode((w, h)) screen.fill((white)) screen.fill((white)) x = 0 y = 0 screen.blit(redSquare, (x, y)) pygame.display.flip() running = True while (running): for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() sys.exit() if event.type == pygame.MOUSEBUTTONDOWN: x, y = event.pos if redSquare.get_rect().collidepoint(x, y): regels3() def regels3(): redSquare = pygame.image.load('Regels3.png').convert() clock = pygame.time.Clock() white = (255, 64, 64) w = 810 h = 420 screen = pygame.display.set_mode((w, h)) screen.fill((white)) screen.fill((white)) x = 0 y = 0 screen.blit(redSquare, (x, y)) pygame.display.flip() running = True while (running): for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() sys.exit() if event.type == pygame.MOUSEBUTTONDOWN: x, y = event.pos if redSquare.get_rect().collidepoint(x, y): regels4() def regels4(): redSquare = pygame.image.load('surprisekaart.png').convert() clock = pygame.time.Clock() white = (255, 64, 64) w = 810 h = 420 screen = pygame.display.set_mode((w, h)) screen.fill((white)) screen.fill((white)) x = 0 y = 0 screen.blit(redSquare, (x, y)) pygame.display.flip() running = True while (running): for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() sys.exit() if event.type == pygame.MOUSEBUTTONDOWN: x, y = event.pos if redSquare.get_rect().collidepoint(x, y): regels5() def regels5(): redSquare = pygame.image.load('Questregels2.png').convert() clock = pygame.time.Clock() white = (255, 64, 64) w = 810 h = 420 screen = pygame.display.set_mode((w, h)) screen.fill((white)) screen.fill((white)) x = 0 y = 0 screen.blit(redSquare, (x, y)) pygame.display.flip() running = True while (running): for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() sys.exit() if event.type == pygame.MOUSEBUTTONDOWN: x, y = event.pos if redSquare.get_rect().collidepoint(x, y): regels6() def regels6(): redSquare = pygame.image.load('Powerupregels.png').convert() clock = pygame.time.Clock() white = (255, 64, 64) w = 810 h = 420 screen = pygame.display.set_mode((w, h)) screen.fill((white)) screen.fill((white)) x = 0 y = 0 screen.blit(redSquare, (x, y)) pygame.display.flip() running = True while (running): for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() sys.exit() if event.type == pygame.MOUSEBUTTONDOWN: x, y = event.pos if redSquare.get_rect().collidepoint(x, y): regels7() def regels7(): redSquare = pygame.image.load('Powerupregels2.png').convert() clock = pygame.time.Clock() white = (255, 64, 64) w = 810 h = 420 screen = pygame.display.set_mode((w, h)) screen.fill((white)) screen.fill((white)) x = 0 y = 0 screen.blit(redSquare, (x, y)) pygame.display.flip() running = True while (running): for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() sys.exit() if event.type == pygame.MOUSEBUTTONDOWN: x, y = event.pos if redSquare.get_rect().collidepoint(x, y): regels8() def regels8(): redSquare = pygame.image.load('Battleregels.png').convert() clock = pygame.time.Clock() white = (255, 64, 64) w = 810 h = 420 screen = pygame.display.set_mode((w, h)) screen.fill((white)) screen.fill((white)) x = 0 y = 0 screen.blit(redSquare, (x, y)) pygame.display.flip() running = True while (running): for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() sys.exit() if event.type == pygame.MOUSEBUTTONDOWN: x, y = event.pos if redSquare.get_rect().collidepoint(x, y): regels9() def regels9(): redSquare = pygame.image.load('Battleregels2.png').convert() clock = pygame.time.Clock() white = (255, 64, 64) w = 810 h = 420 screen = pygame.display.set_mode((w, h)) screen.fill((white)) screen.fill((white)) x = 0 y = 0 screen.blit(redSquare, (x, y)) pygame.display.flip() running = True while (running): for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() sys.exit() if event.type == pygame.MOUSEBUTTONDOWN: x, y = event.pos if redSquare.get_rect().collidepoint(x, y): regels10() def regels10(): redSquare = pygame.image.load('Battleregels3.png').convert() clock = pygame.time.Clock() white = (255, 64, 64) w = 810 h = 420 screen = pygame.display.set_mode((w, h)) screen.fill((white)) screen.fill((white)) x = 0 y = 0 screen.blit(redSquare, (x, y)) pygame.display.flip() running = True while (running): for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() sys.exit() if event.type == pygame.MOUSEBUTTONDOWN: x, y = event.pos if redSquare.get_rect().collidepoint(x, y): print("hi") def regels11(): redSquare = pygame.image.load('Howtoplay.png').convert() clock = pygame.time.Clock() white = (255, 64, 64) w = 810 h = 420 screen = pygame.display.set_mode((w, h)) screen.fill((white)) screen.fill((white)) x = 0 y = 0 screen.blit(redSquare, (x, y)) pygame.display.flip() running = True while (running): for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() sys.exit() if event.type == pygame.MOUSEBUTTONDOWN: x, y = event.pos if redSquare.get_rect().collidepoint(x, y): regels12() def regels12(): redSquare = pygame.image.load('Howtoplay2.png').convert() clock = pygame.time.Clock() white = (255, 64, 64) w = 810 h = 420 screen = pygame.display.set_mode((w, h)) screen.fill((white)) screen.fill((white)) x = 0 y = 0 screen.blit(redSquare, (x, y)) pygame.display.flip() running = True while (running): for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() sys.exit() if event.type == pygame.MOUSEBUTTONDOWN: x, y = event.pos if redSquare.get_rect().collidepoint(x, y): regels13() def regels13(): redSquare = pygame.image.load('Howtoplay3.png').convert() clock = pygame.time.Clock() white = (255, 64, 64) w = 810 h = 420 screen = pygame.display.set_mode((w, h)) screen.fill((white)) screen.fill((white)) x = 0 y = 0 screen.blit(redSquare, (x, y)) pygame.display.flip() running = True while (running): for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() sys.exit() if event.type == pygame.MOUSEBUTTONDOWN: x, y = event.pos if redSquare.get_rect().collidepoint(x, y): regels14() def regels14(): redSquare = pygame.image.load('Howtoplay4.png').convert() clock = pygame.time.Clock() white = (255, 64, 64) w = 810 h = 420 screen = pygame.display.set_mode((w, h)) screen.fill((white)) screen.fill((white)) x = 0 y = 0 screen.blit(redSquare, (x, y)) pygame.display.flip() running = True while (running): for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() sys.exit() if event.type == pygame.MOUSEBUTTONDOWN: x, y = event.pos if redSquare.get_rect().collidepoint(x, y): regels15() def regels15(): redSquare = pygame.image.load('Howtoplay5.png').convert() clock = pygame.time.Clock() white = (255, 64, 64) w = 810 h = 420 screen = pygame.display.set_mode((w, h)) screen.fill((white)) screen.fill((white)) x = 0 y = 0 screen.blit(redSquare, (x, y)) pygame.display.flip() running = True while (running): for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() sys.exit() if event.type == pygame.MOUSEBUTTONDOWN: x, y = event.pos if redSquare.get_rect().collidepoint(x, y): story() <file_sep>import math import pygame import random attack = pygame.image.load('Attack.png') chance = pygame.image.load('Chance1.png') normale = pygame.image.load('Normale.png') politie = pygame.image.load('Politielijn.png') politiec = pygame.image.load('PolitielijnChance.png') landmark = pygame.image.load('Powerup.png') badge = pygame.image.load('Badge.png') chanceattack = pygame.image.load('ChanceAttack.png') politielijnmark = pygame.image.load('PolitielijnPowerup.png') politielijnattack = pygame.image.load('PolitielijnAttack.png') politielijnbadge = pygame.image.load('Politielijnbadge.png') plusultra = pygame.image.load('Plusultra.png') fusrodah = pygame.image.load('Fusrodah.png') slowdowntime = pygame.image.load('Slowdowntime.png') taxi = pygame.image.load('Taxi.png') ufo = pygame.image.load('Ufo.png') wildfire = pygame.image.load('Wildfire.png') fiets = pygame.image.load('Fiets.png') camo = pygame.image.load('Camo.png') end = pygame.image.load('End.png') begin1 = pygame.image.load('begin1.png') begin2 = pygame.image.load('begin2.png') begin3 = pygame.image.load('begin3.png') sniper = pygame.image.load('Sniper.png') dice_one = pygame.image.load("dice_one.png") dice_two = pygame.image.load("dice_two.png") dice_three = pygame.image.load("dice_three.png") dice_four = pygame.image.load("dice_four.png") dice_five = pygame.image.load("dice_five.png") dice_six = pygame.image.load("dice_six.png") obama = pygame.image.load("obamaspeler.png") kim = pygame.image.load("kimkspeler.png") black = 0, 0, 0 white = 255, 255, 255 red = 255, 0, 0 green = 0, 255, 0 blue = 0, 0, 255 normale_vakjes = [(0,2),(0,3),(0,5),(0,6),(0,7),(0,8),(0,9),(0,10),(0,10),(0,11),(0,13),(0,14),(0,17),(0,18),(0,19),(0,20),(0,22),(0,23),(0,24),(0,25),(0,27),(0,28),(0,29),(0,30),(0,31),(1,2),(1,8),(1,12),(2,2) ,(2,12),(2,31),(3,2,),(3,12),(3,13),(3,18),(3,19),(4,2),(4,14),(4,24),(4,26),(4,27),(4,31),(5,12),(5,24),(5,26),(5,28),(5,31),(19,2),(19,3),(19,4),(19,10),(19,11),(19,12),(19,13),(19,15),(19,17),(19,18),(19,19),(19,21),(19,22),(19,23),(19,24),(19,25),(19,26),(18,2),(18,27),(17,2),(17,8),(17,17),(17,21),(17,22),(17,23),(17,27),(16,9),(16,17),(16,18),(16,19),(16,20),(16,23),(15,2),(15,7),(15,8),(15,9),(15,11),(15,12),(15,20),(15,31),(14,2),(14,7),(14,20),(14,23),(14,31),(13,2),(13,13),(13,14),(13,17),(13,19),(13,20),(13,24),(13,25),(13,26),(13,31),(12,2),(12,7),(12,19),(12,26),(12,31),(11,7),(11,8),(11,9),(11,27),(11,28),(11,30),(11,31),(10,3),(10,4),(10,7),(10,20),(10,21),(10,26),(10,31),(9,5),(9,6),(9,7),(9,22),(9,26),(8,7),(8,10),(8,12),(7,2),(7,10),(7,13),(7,22),(7,26),(6,2),(6,8),(6,12),(6,13),(6,20),(6,21),(6,22),(6,24)] chanceattack_vakjes = [(2,10),(6,10),(6,19),(16,15),(16,27),(19,7)] badge_vakjes = [(4,28),(6,7),(10,19),(15,10),(17,20)] landmark_vakjes = [(0,4),(0,21),(2,8),(3,14),(3,31),(4,19),(4,25),(8,11),(8,26),(11,19),(11,29),(14,12),(15,23),(16,29),(17,7),(19,14),(19,27)] politie_vakjes = [(2,16),(3,16),(7,16),(9,16),(10,16),(12,16),(19,16)] attack_vakjes = [(2,9),(4,10),(5,10),(5,14),(5,19),(6,9),(6,14),(6,15),(6,18),(6,28),(6,29),(6,30),(6,31),(7,31),(11,11),(11,12),(12,12),(13,15),(14,15),(14,27),(15,15),(15,27),(16,28),(18,7),(19,5),(19,6),(19,8)] chance_vakjes = [(0,12),(0,15),(0,26),(1,31),(3,17),(4,12),(5,2),(6,23),(6,26),(7,7),(8,13),(8,22),(9,4),(9,31),(11,26),(13,7),(13,12),(13,18),(13,23),(16,2),(16,31),(17,9),(19,20)] normale_vakjes_links = [(0,2),(0,3),(0,5),(0,6),(0,7),(0,8),(0,9),(0,10),(0,11),(0,13),(0,14),(0,17),(0,18),(0,19),(0,20),(0,22),(0,23),(0,24),(0,25),(0,27),(0,28),(0,29),(0,30),(3,12),(3,13),(3,15),(3,18),(3,19),(4,24),(4,26),(4,27),(6,8),(6,12),(6,13),(6,20),(6,21),(6,22),(8,10),(8,12),(9,5),(9,6),(10,2),(10,3),(10,20),(10,21),(11,7),(11,9),(11,9),(11,27),(11,28),(11,30),(13,13),(13,14),(13,17),(13,19),(13,24),(13,25),(13,26),(15,7),(15,8),(15,9),(15,11),(16,17),(16,18),(16,19),(17,8),(17,21),(17,22),(19,2),(19,3),(19,4),(19,10),(19,11),(19,12),(19,13),(19,15),(19,17),(19,18),(19,19),(19,21),(19,22),(19,23),(10,24),(19,25)] normale_vakjes_omhoog = [(19,2),(18,2),(17,2),(15,2),(14,2),(13,2),(12,2),(11,2),(10,2),(9,2),(8,2),(7,2),(6,2),(4,2),(3,2),(2,0),(1,0),(10,4),(9,7),(8,7),(16,9),(15,12),(4,14),(19,17),(17,17),(13,19),(12,19),(9,22),(7,22),(17,23),(16,23),(14,23),(6,24),(5,24),(13,26),(12,26),(10,26),(9,26),(7,26),(5,26),(18,27),(17,27)] width = 1700 height = 1000 size = (width, height) screen = pygame.display.set_mode(size) droll = 1 class Vector: def __init__(self, x, y): self.x = x self.y = y class Player: def __init__(self, x, y, image): self.pos = Vector(x, y) self.image = image def update(self): if (self.pos.y, self.pos.x) in normale_vakjes_links: keys = pygame.key.get_pressed() if keys[pygame.K_LEFT]: self.pos.x -= 1 elif keys[pygame.K_RIGHT]: self.pos.x += 1 if keys[pygame.K_UP]: self.pos.y -= 1 elif keys[pygame.K_DOWN]: self.pos.y += 1 def draw(self, screen): screen.blit(self.image, (48 * self.pos.x + 5, 48 * self.pos.y + 5, 43, 43)) Margin = 5 # Handle pygame events def process_events(): for event in pygame.event.get(): if event.type == pygame.QUIT: # Give the signal to quit return True return False '''class Vakjes: def __init__(self,position,row,column): self.Pos = position self.x = row self.y = column def draw(self,screen): pygame.draw.rect(screen, (255,255,255), (self.x,self.y,50,50), 0)''' # Main program logic def program(): # Start PyGame pygame.init() # Set the resolution # Set up the default font font = pygame.font.Font(None, 30) pygame.display.set_caption("Ontsnapperdam") Player1 = Player(2,3, obama) Player2 = Player(2,0, kim) while not process_events(): Player.update(Player1) Player.update(Player2) # Clear the screen screen.fill((255,255,255)) #draw board for row in range(0,20): for column in range(0,32): for i in normale_vakjes: if (row,column) == i : #pygame.draw.rect(screen, (255,255,255), (48 * column + 5 ,48 * row + 5,43,43), 0) screen.blit(normale,(48 * column + 5,48 * row + 5)) elif row == 7 and column == 0: pygame.draw.rect(screen, (0,0,0), (48 * column + 5 ,48 * row + 5,43,43), 0) elif row == 8 and column == 0: pygame.draw.rect(screen, (255,0,0), (48 * column + 5 ,48 * row + 5,43,43), 0) elif row == 9 and column == 0: pygame.draw.rect(screen, (255,0,255), (48 * column + 5 ,48 * row + 5,43,43), 0) elif row == 10 and column == 0: pygame.draw.rect(screen, (0,255,255), (48 * column + 5 ,48 * row + 5,43,43), 0) elif row == 11 and column == 0: pygame.draw.rect(screen, (255,255,0), (48 * column + 5 ,48 * row + 5,43,43), 0) elif row == 12 and column == 0: pygame.draw.rect(screen, (0,255,0), (48 * column + 5 ,48 * row + 5,43,43), 0) elif row == 9 and column == 1: pygame.draw.rect(screen, (255,255,255), (48 * column + 5 ,(48 * row + 5)+24,43,43), 0) screen.blit(normale,(48 * column + 5,(48 * row + 5)+24)) elif row == 8 and column == 2: pygame.draw.rect(screen, (255,255,255), ((48 * column + 5 ),48 * row + 5,43,187), 0) for a in attack_vakjes: if (row,column) == a: screen.blit(attack,(48 * column + 5,48 * row + 5)) for c in chance_vakjes: if (row,column) == c: screen.blit(chance,(48 * column + 5,48 * row + 5)) for ca in chanceattack_vakjes: if (row,column) == ca: screen.blit(chanceattack,(48 * column + 5,48 * row + 5)) for p in politie_vakjes: if (row,column) == p: screen.blit(politie,(48 * column + 5,48 * row + 5)) elif row == 13 and column == 16 or row == 16 and column == 16 or row == 6 and column == 16: screen.blit(politielijnattack,(48 * column + 5,48 * row + 5)) elif row == 8 and column == 16: screen.blit(politiec,(48 * column + 5,48 * row + 5)) elif row == 11 and column == 16: screen.blit(politielijnmark,(48 * column + 5,48 * row + 5)) elif row == 0 and column == 16: screen.blit(politielijnbadge,(48 * column + 5,48 * row + 5)) for u in landmark_vakjes: if (row,column) == u: screen.blit(landmark,(48 * column + 5,48 * row + 5)) for b in badge_vakjes: if (row,column) == b: screen.blit(badge,(48 * column + 5,48 * row + 5)) if row == 3 and column == 10: screen.blit(wildfire,(48 * column + 5,48 * row + 5)) elif row == 6 and column == 17: screen.blit(ufo,(48 * column + 5,48 * row + 5)) elif row == 8 and column == 31: screen.blit(plusultra,(48 * column + 5,48 * row + 5)) elif row == 10 and column == 22: screen.blit(taxi,(48 * column + 5,48 * row + 5)) elif row == 11 and column == 10: screen.blit(fiets,(48 * column + 5,48 * row + 5)) elif row == 13 and column == 27: screen.blit(slowdowntime,(48 * column + 5,48 * row + 5)) elif row == 18 and column == 17: screen.blit(camo,(48 * column + 5,48 * row + 5)) elif row == 19 and column == 9: screen.blit(fusrodah,(48 * column + 5,48 * row + 5)) elif row == 16 and column == 30: screen.blit(end,(48 * column + 5,48 * row + 5)) elif row == 8 and column == 2: screen.blit(begin2,(48 * column + 5,48 * row + 5)) elif row == 9 and column == 2 or row == 10 and column == 2: screen.blit(begin1,(48 * column + 5,48 * row + 5)) elif row == 11 and column == 2: screen.blit(begin3,(48 * column + 5,48 * row + 5)) elif row == 1 and column == 16: screen.blit(sniper,(48 * column + 5,48 * row + 5)) Player1.draw(screen) Player2.draw(screen) # Draw the score text #score_text = font.draw("Score: 100", 1, (255, 0, 0)) #8screen.blit(score_text, (16, 16)) pygame.display.update() clock = pygame.time.Clock() clock.tick(60) pygame.display.flip() program() <file_sep>import pygame import Game as dm def opties(): pygame.mixer.music.load("music.mp3") pygame.mixer.music.play(loops=0, start=0.0) size = width, height = 340,240 screen = pygame.display.set_mode(size) redSquare = pygame.image.load('achtergrondSpelers.png').convert() white = (255,255,255) w = 700 h = 420 screen = pygame.display.set_mode((w, h)) screen.fill((white)) x = 0 y = 0 screen.blit(redSquare, (x, y)) pygame.display.flip() black = (0,0,0) pygame.mixer.music.load("music.mp3") pygame.mixer.music.play(loops=0, start=0.0) choose = dm.dumbmenu(screen,[ 'Geluid uit', 'Taal wijzigen -> Engels', 'Terug naar het menu'] , 180,150,None,35,1.4,black ,black) if choose == 0: print ("Je hebt gekozen voor Geluid uit'.") elif choose == 1: print ("Je hebt gekozen voor Taal wijzigen naar het engels''.") elif choose == 2: print( "Je hebt gekozen voor Terug naar het men'.") <file_sep>def music(): pygame.mixer.music.load("geluid/jaws.mp3") pygame.mixer.music.play(loops = 0, start = .55) pygame.mixer.music.set_volume(0.5) def HoofdmenuNL(): redSquare = pygame.image.load('MENU.png') white = (255,255,255) w = 1700 h = 1000 screen = pygame.display.set_mode((w, h)) screen.fill((white)) x = 0 y = 0 black = (0,0,0) screen.blit(redSquare, (x, y)) # Draw the score t pygame.display.flip() choose = dm.dumbmenu(screen, ['Start Game', 'Opties', 'Handleiding', 'Highscore', 'Stop Game'], 200,150,None,35,1.4,black ,black) if choose == 0: Players() print ("Je hebt gekozen voor 'Start Game'.") elif choose == 1: opties() print ("Je hebt gekozen voor 'Opties'.") elif choose == 2: story() print( "Je hebt gekozen voor 'Handleiding'.") elif choose == 3: scherm() print ("Je hebt gekozen voor 'Highscore'.") elif choose == 4: print ("Je hebt gekozen voor 'Het stoppen van de Game'.") pygame.init() def Players(): redSquare = pygame.image.load('achtergrondSpelers.png') white = (255,255,255) w = 1700 h = 1000 screen = pygame.display.set_mode((w, h)) screen.fill((white)) x = 0 y = 0 screen.blit(redSquare, (x, y)) pygame.display.flip() black = (0,0,0) choose = dm.dumbmenu(screen,[ '- 3 spelers', '- 4 spelers', '- 5 spelers', '- 6 spelers', '- terug naar het menu'] , 200,150,None,35,1.4,black ,black) if choose == 0: program() print ("Je hebt gekozen voor 3 spelers.") elif choose == 1: A.program2() print ("Je hebt gekozen voor 4 spelers'.") elif choose == 2: V.program3() print( "Je hebt gekozen voor 5 spelers'.") elif choose == 3: program4() print ("Je hebt gekozen voor 6 spelers'.") elif choose == 5: HoofdmenuNL() print('Je hebt gekozen voor terug naar menu ') def opties(): redSquare = pygame.image.load('achtergrondopties.png') white = (255,255,255) w = 1700 h = 1000 screen = pygame.display.set_mode((w, h)) screen.fill((white)) x = 0 y = 0 screen.blit(redSquare, (x, y)) pygame.display.flip() black = (0,0,0) choose = dm.dumbmenu(screen,[ 'Geluid uit', 'Taal wijzigen -> Engels', 'Terug naar het menu'] , 180,150,None,35,1.4,black ,black) if choose == 0: HoofdmenuNL() pygame.mixer.music.stop print ("Je hebt gekozen voor Geluid uit'.") elif choose == 1: menuENG() print ("Je hebt gekozen voor Taal wijzigen naar het engels''.") elif choose == 2: HoofdmenuNL() print( "Je hebt gekozen voor Terug naar het menu'.") def story(): redSquare = pygame.image.load('Story.png') white = (255, 64, 64) w = 810 h = 420 screen = pygame.display.set_mode((w, h)) screen.fill((white)) screen.fill((white)) x = 0 y = 0 screen.blit(redSquare, (x, y)) pygame.display.flip() running = True while (running): for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() sys.exit() if event.type == pygame.MOUSEBUTTONDOWN: x, y = event.pos if redSquare.get_rect().collidepoint(x, y): regels() def regels(): redSquare = pygame.image.load('Naamloos.png') clock = pygame.time.Clock() white = (255, 64, 64) w = 810 h = 420 screen = pygame.display.set_mode((w, h)) screen.fill((white)) screen.fill((white)) x = 0 y = 0 screen.blit(redSquare, (x, y)) pygame.display.flip() running = True while (running): for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() sys.exit() if event.type == pygame.MOUSEBUTTONDOWN: x, y = event.pos if redSquare.get_rect().collidepoint(x, y): regels2() def regels2(): redSquare = pygame.image.load('Regels2.png') clock = pygame.time.Clock() white = (255, 64, 64) w = 810 h = 420 screen = pygame.display.set_mode((w, h)) screen.fill((white)) screen.fill((white)) x = 0 y = 0 screen.blit(redSquare, (x, y)) pygame.display.flip() running = True while (running): for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() sys.exit() if event.type == pygame.MOUSEBUTTONDOWN: x, y = event.pos if redSquare.get_rect().collidepoint(x, y): regels3() def regels3(): redSquare = pygame.image.load('Regels3.png') clock = pygame.time.Clock() white = (255, 64, 64) w = 810 h = 420 screen = pygame.display.set_mode((w, h)) screen.fill((white)) screen.fill((white)) x = 0 y = 0 screen.blit(redSquare, (x, y)) pygame.display.flip() running = True while (running): for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() sys.exit() if event.type == pygame.MOUSEBUTTONDOWN: x, y = event.pos if redSquare.get_rect().collidepoint(x, y): regels4() def regels4(): redSquare = pygame.image.load('surprisekaart.png') clock = pygame.time.Clock() white = (255, 64, 64) w = 810 h = 420 screen = pygame.display.set_mode((w, h)) screen.fill((white)) screen.fill((white)) x = 0 y = 0 screen.blit(redSquare, (x, y)) pygame.display.flip() running = True while (running): for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() sys.exit() if event.type == pygame.MOUSEBUTTONDOWN: x, y = event.pos if redSquare.get_rect().collidepoint(x, y): regels5() def regels5(): redSquare = pygame.image.load('Questregels2.png') clock = pygame.time.Clock() white = (255, 64, 64) w = 810 h = 420 screen = pygame.display.set_mode((w, h)) screen.fill((white)) screen.fill((white)) x = 0 y = 0 screen.blit(redSquare, (x, y)) pygame.display.flip() running = True while (running): for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() sys.exit() if event.type == pygame.MOUSEBUTTONDOWN: x, y = event.pos if redSquare.get_rect().collidepoint(x, y): regels6() def regels6(): redSquare = pygame.image.load('Powerupregels.png') clock = pygame.time.Clock() white = (255, 64, 64) w = 810 h = 420 screen = pygame.display.set_mode((w, h)) screen.fill((white)) screen.fill((white)) x = 0 y = 0 screen.blit(redSquare, (x, y)) pygame.display.flip() running = True while (running): for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() sys.exit() if event.type == pygame.MOUSEBUTTONDOWN: x, y = event.pos if redSquare.get_rect().collidepoint(x, y): regels7() def regels7(): redSquare = pygame.image.load('Powerupregels2.png') clock = pygame.time.Clock() white = (255, 64, 64) w = 810 h = 420 screen = pygame.display.set_mode((w, h)) screen.fill((white)) screen.fill((white)) x = 0 y = 0 screen.blit(redSquare, (x, y)) pygame.display.flip() running = True while (running): for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() sys.exit() if event.type == pygame.MOUSEBUTTONDOWN: x, y = event.pos if redSquare.get_rect().collidepoint(x, y): regels8() def regels8(): redSquare = pygame.image.load('Battleregels.png') clock = pygame.time.Clock() white = (255, 64, 64) w = 810 h = 420 screen = pygame.display.set_mode((w, h)) screen.fill((white)) screen.fill((white)) x = 0 y = 0 screen.blit(redSquare, (x, y)) pygame.display.flip() running = True while (running): for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() sys.exit() if event.type == pygame.MOUSEBUTTONDOWN: x, y = event.pos if redSquare.get_rect().collidepoint(x, y): regels9() def regels9(): redSquare = pygame.image.load('Battleregels2.png') clock = pygame.time.Clock() white = (255, 64, 64) w = 810 h = 420 screen = pygame.display.set_mode((w, h)) screen.fill((white)) screen.fill((white)) x = 0 y = 0 screen.blit(redSquare, (x, y)) pygame.display.flip() running = True while (running): for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() sys.exit() if event.type == pygame.MOUSEBUTTONDOWN: x, y = event.pos if redSquare.get_rect().collidepoint(x, y): regels10() def regels10(): redSquare = pygame.image.load('Battleregels3.png') clock = pygame.time.Clock() white = (255, 64, 64) w = 810 h = 420 screen = pygame.display.set_mode((w, h)) screen.fill((white)) screen.fill((white)) x = 0 y = 0 screen.blit(redSquare, (x, y)) pygame.display.flip() running = True while (running): for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() sys.exit() if event.type == pygame.MOUSEBUTTONDOWN: x, y = event.pos if redSquare.get_rect().collidepoint(x, y): HoofdmenuNL() print('Einde terug naar menu') def regels11(): redSquare = pygame.image.load('Howtoplay.png') clock = pygame.time.Clock() white = (255, 64, 64) w = 810 h = 420 screen = pygame.display.set_mode((w, h)) screen.fill((white)) screen.fill((white)) x = 0 y = 0 screen.blit(redSquare, (x, y)) pygame.display.flip() running = True while (running): for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() sys.exit() if event.type == pygame.MOUSEBUTTONDOWN: x, y = event.pos if redSquare.get_rect().collidepoint(x, y): regels12() def regels12(): redSquare = pygame.image.load('Howtoplay2.png') clock = pygame.time.Clock() white = (255, 64, 64) w = 810 h = 420 screen = pygame.display.set_mode((w, h)) screen.fill((white)) screen.fill((white)) x = 0 y = 0 screen.blit(redSquare, (x, y)) pygame.display.flip() running = True while (running): for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() sys.exit() if event.type == pygame.MOUSEBUTTONDOWN: x, y = event.pos if redSquare.get_rect().collidepoint(x, y): regels13() def regels13(): redSquare = pygame.image.load('Howtoplay3.png') clock = pygame.time.Clock() white = (255, 64, 64) w = 810 h = 420 screen = pygame.display.set_mode((w, h)) screen.fill((white)) screen.fill((white)) x = 0 y = 0 screen.blit(redSquare, (x, y)) pygame.display.flip() running = True while (running): for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() sys.exit() if event.type == pygame.MOUSEBUTTONDOWN: x, y = event.pos if redSquare.get_rect().collidepoint(x, y): regels14() def regels14(): redSquare = pygame.image.load('Howtoplay4.png') clock = pygame.time.Clock() white = (255, 64, 64) w = 810 h = 420 screen = pygame.display.set_mode((w, h)) screen.fill((white)) screen.fill((white)) x = 0 y = 0 screen.blit(redSquare, (x, y)) pygame.display.flip() running = True while (running): for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() sys.exit() if event.type == pygame.MOUSEBUTTONDOWN: x, y = event.pos if redSquare.get_rect().collidepoint(x, y): regels15() def regels15(): redSquare = pygame.image.load('Howtoplay5.png') clock = pygame.time.Clock() white = (255, 64, 64) w = 810 h = 420 screen = pygame.display.set_mode((w, h)) screen.fill((white)) screen.fill((white)) x = 0 y = 0 screen.blit(redSquare, (x, y)) pygame.display.flip() running = True while (running): for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() sys.exit() if event.type == pygame.MOUSEBUTTONDOWN: x, y = event.pos if redSquare.get_rect().collidepoint(x, y): story() def story(): redSquare = pygame.image.load('Story.png') clock = pygame.time.Clock() white = (255, 64, 64) w = 810 h = 420 screen = pygame.display.set_mode((w, h)) screen.fill((white)) screen.fill((white)) x = 0 y = 0 screen.blit(redSquare, (x, y)) pygame.display.flip() running = True while (running): for event in pygame.event.get(): if event.type == pygame.QUIT: running = False if event.type == pygame.MOUSEBUTTONDOWN: x, y = event.pos if redSquare.get_rect().collidepoint(x, y): regels() pygame.init() ######################################################## ########################################################### def menuENG(): redSquare = pygame.image.load('MENU.png') white = (255,255,255) w = 1700 h = 1000 screen = pygame.display.set_mode((w, h)) screen.fill((white)) x = 0 y = 0 black = (0,0,0) screen.blit(redSquare, (x, y)) # Draw the score t pygame.display.flip() choose = dm.dumbmenu(screen, ['Start Game', 'Options', 'Manual', 'Show Highscore', 'Quit Game'], 200,150,None,35,1.4,black ,black) if choose == 0: Playerseng() print ("You choose 'Start Game'.") elif choose == 1: optieseng() print ("You choose 'Options'.") elif choose == 2: storyeng() print( "You choose 'Manual'.") elif choose == 3: scherm() print ("You choose 'Show Highscore'.") elif choose == 4: print ("You choose 'Quit Game'.") pygame.init() def foto (name): redSquare = pygame.image.load('winnerscreen.png') white = (255,255,255) w = 1700 h = 1000 screen = pygame.display.set_mode((w, h)) screen.fill((white)) x = 0 y = 0 screen.blit(redSquare, (x, y)) font = pygame.font.Font(None, 80) score_text = font.render(name, 1, (0, 0, 0)) screen.blit(score_text, (460,300)) pygame.display.flip() running = True while (running): for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() sys.exit() elif event.type == pygame.K_KP_ENTER: HoofdmenuNL() def Playerseng(): redSquare = pygame.image.load('achtergrondopties.png') white = (255,255,255) w = 1700 h = 1000 screen = pygame.display.set_mode((w, h)) screen.fill((white)) x = 0 y = 0 screen.blit(redSquare, (x, y)) pygame.display.flip() black = (0,0,0) choose = dm.dumbmenu(screen,[ '- 3 players', '- 4 players', '- 5 players', '- 6 players', '- Back to Menu'] , 200,150,None,35,1.4,black ,black) if choose == 0: program() print ("You choose '3 players'.") elif choose == 1: A.program2() print ("You choose '4 players'.") elif choose == 2: V.program3() print("You choose '5 players'.") elif choose == 3: program4() print ("You choose '6 players'.") elif choose == 5: menuENG() print("You choose 'Back to Menu'.") def optieseng(): redSquare = pygame.image.load('achtergrondopties.png') white = (255,255,255) w = 1700 h = 1000 screen = pygame.display.set_mode((w, h)) screen.fill((white)) x = 0 y = 0 screen.blit(redSquare, (x, y)) pygame.display.flip() black = (0,0,0) choose = dm.dumbmenu(screen,[ 'Sound off/on', 'Change -> Engels/Dutch', 'Back to Menu'] , 180,150,None,35,1.4,black ,black) if choose == 0: menuENG() pygame.mixer.music.stop print ("You choose 'Sound off/on'.") elif choose == 1: HoofdmenuNL() print ("You choose 'Change -> Engels/Dutch'.") elif choose == 2: menuENG() print( "You choose 'Back to Menu'.") def regelseng(): redSquare = pygame.image.load('regels1ENG.png') clock = pygame.time.Clock() white = (255, 64, 64) w = 810 h = 420 screen = pygame.display.set_mode((w, h)) screen.fill((white)) screen.fill((white)) x = 0 y = 0 screen.blit(redSquare, (x, y)) pygame.display.flip() running = True while (running): for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() sys.exit() if event.type == pygame.MOUSEBUTTONDOWN: x, y = event.pos if redSquare.get_rect().collidepoint(x, y): regels2eng() def regels2eng(): redSquare = pygame.image.load('regels2ENG.png') clock = pygame.time.Clock() white = (255, 64, 64) w = 810 h = 420 screen = pygame.display.set_mode((w, h)) screen.fill((white)) screen.fill((white)) x = 0 y = 0 screen.blit(redSquare, (x, y)) pygame.display.flip() running = True while (running): for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() sys.exit() if event.type == pygame.MOUSEBUTTONDOWN: x, y = event.pos if redSquare.get_rect().collidepoint(x, y): regels3eng() def regels3eng(): redSquare = pygame.image.load('regels3ENG.png') clock = pygame.time.Clock() white = (255, 64, 64) w = 810 h = 420 screen = pygame.display.set_mode((w, h)) screen.fill((white)) screen.fill((white)) x = 0 y = 0 screen.blit(redSquare, (x, y)) pygame.display.flip() running = True while (running): for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() sys.exit() if event.type == pygame.MOUSEBUTTONDOWN: x, y = event.pos if redSquare.get_rect().collidepoint(x, y): regels4eng() def regels4eng(): redSquare = pygame.image.load('rules.png') clock = pygame.time.Clock() white = (255, 64, 64) w = 810 h = 420 screen = pygame.display.set_mode((w, h)) screen.fill((white)) screen.fill((white)) x = 0 y = 0 screen.blit(redSquare, (x, y)) pygame.display.flip() running = True while (running): for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() sys.exit() if event.type == pygame.MOUSEBUTTONDOWN: x, y = event.pos if redSquare.get_rect().collidepoint(x, y): regels5eng() def regels5eng(): redSquare = pygame.image.load('surprise.png') clock = pygame.time.Clock() white = (255, 64, 64) w = 810 h = 420 screen = pygame.display.set_mode((w, h)) screen.fill((white)) screen.fill((white)) x = 0 y = 0 screen.blit(redSquare, (x, y)) pygame.display.flip() running = True while (running): for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() sys.exit() if event.type == pygame.MOUSEBUTTONDOWN: x, y = event.pos if redSquare.get_rect().collidepoint(x, y): regels6eng() def regels6eng(): redSquare = pygame.image.load('quest.png') clock = pygame.time.Clock() white = (255, 64, 64) w = 810 h = 420 screen = pygame.display.set_mode((w, h)) screen.fill((white)) screen.fill((white)) x = 0 y = 0 screen.blit(redSquare, (x, y)) pygame.display.flip() running = True while (running): for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() sys.exit() if event.type == pygame.MOUSEBUTTONDOWN: x, y = event.pos if redSquare.get_rect().collidepoint(x, y): regels7eng() def regels7eng(): redSquare = pygame.image.load('power.png') clock = pygame.time.Clock() white = (255, 64, 64) w = 810 h = 420 screen = pygame.display.set_mode((w, h)) screen.fill((white)) screen.fill((white)) x = 0 y = 0 screen.blit(redSquare, (x, y)) pygame.display.flip() running = True while (running): for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() sys.exit() if event.type == pygame.MOUSEBUTTONDOWN: x, y = event.pos if redSquare.get_rect().collidepoint(x, y): regels8eng() def regels8eng(): redSquare = pygame.image.load('battle.png') clock = pygame.time.Clock() white = (255, 64, 64) w = 810 h = 420 screen = pygame.display.set_mode((w, h)) screen.fill((white)) screen.fill((white)) x = 0 y = 0 screen.blit(redSquare, (x, y)) pygame.display.flip() running = True while (running): for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() sys.exit() if event.type == pygame.MOUSEBUTTONDOWN: x, y = event.pos if redSquare.get_rect().collidepoint(x, y): menuENG() print('Einde terug naar menu') def storyeng(): redSquare = pygame.image.load('storyENG.png') clock = pygame.time.Clock() white = (255, 64, 64) w = 810 h = 420 screen = pygame.display.set_mode((w, h)) screen.fill((white)) screen.fill((white)) x = 0 y = 0 screen.blit(redSquare, (x, y)) pygame.display.flip() running = True while (running): for event in pygame.event.get(): if event.type == pygame.QUIT: running = False if event.type == pygame.MOUSEBUTTONDOWN: x, y = event.pos if redSquare.get_rect().collidepoint(x, y): regelseng() music() HoofdmenuNL() <file_sep># Moet in de player class aan het einde def winnerscreen(self): global beurt if (self.pos.x,self.pos.y) == (16,30) and self.moves == 0 and self.turn and self.alive: foto(self.namet) #### # deze moet boven de player class def foto (name): redSquare = pygame.image.load('winnerscreen.png') white = (255,255,255) w = 1700 h = 1000 screen = pygame.display.set_mode((w, h)) screen.fill((white)) x = 0 y = 0 screen.blit(redSquare, (x, y)) font = pygame.font.Font(None, 80) score_text = font.render(name, 1, (0, 0, 0)) screen.blit(score_text, (460,300)) pygame.display.flip() <file_sep>import pygame #Define the lists normale_vakjes = [(2,0),(3,0),(5,0),(6,0),(7,0),(8,0),(9,0),(10,0),(11,0),(13,0),(14,0),(17,0),(18,0),(19,0),(20,0),(22,0),(23,0),(24,0),(25,0),(27,0),(28,0),(29,0),(30,0),(31,0),(1,2),(1,8),(1,12),(2,2),(2,12),(2,31),(3,2),(3,12,),(3,13),(3,15),(3,18),(3,19),(4,2),(4,14),(4,24),(4,26),(4,27),(4,31),(5,12)] #class position class Vakjes: def __init__(self,position,row,column): self.Pos = position self.x = row self.y = column def draw(self,screen): pygame.draw.rect(screen, color, (self.x,self.y,WIDTH,HEIGHT), 0) class Vector: def __init__(self,x,y): self.PosX = x self.PosY = y # Define some colors BLACK = (0, 0, 0) WHITE = (255, 255, 255) GREEN = (0, 255, 0) RED = (255, 0, 0) # This sets the WIDTH and HEIGHT of each grid location WIDTH = 43 HEIGHT = 43 # This sets the margin between each cell MARGIN = 5 # Create a 2 dimensional array. A two dimensional # array is simply a list of lists. grid = [] for row in range(20): # Add an empty array that will hold each cell # in this row grid.append([]) for column in range(40): grid[row].append(0) # Append a cell # Initialize pygame pygame.init() # Set the HEIGHT and WIDTH of the screen WINDOW_SIZE = [1700 , 1000] screen = pygame.display.set_mode(WINDOW_SIZE) # Set title of screen pygame.display.set_caption("Ontsnapperdam") # Loop until the user clicks the close button. done = False # Used to manage how fast the screen updates clock = pygame.time.Clock() # -------- Main Program Loop ----------- while not done: for event in pygame.event.get(): # User did something if event.type == pygame.QUIT: # If user clicked close done = True # Flag that we are done so we exit this loop elif event.type == pygame.MOUSEBUTTONDOWN: # User clicks the mouse. Get the position pos = pygame.mouse.get_pos() # Change the x/y screen coordinates to grid coordinates column = pos[0] // (WIDTH + MARGIN) row = pos[1] // (HEIGHT + MARGIN) # Set that location to one grid[row][column] = 1 print("Click ", pos, "Grid coordinates: ", row, column) # Set the screen background screen.fill(BLACK) # Draw the grid for row in range(0,20): for column in range(0,35): for i in normale_vakjes: Vakjes(i,row,column) if (column,row) == i : Vakjes(i,row,column) pygame.draw.rect(screen, GREEN, [(MARGIN + WIDTH) * column + MARGIN, (MARGIN + HEIGHT) * row + MARGIN, WIDTH, HEIGHT]) else: pygame.draw.rect(screen, WHITE, [(MARGIN + WIDTH) * column + MARGIN, (MARGIN + HEIGHT) * row + MARGIN, WIDTH, HEIGHT]) clock.tick(60) pygame.display.flip() pygame.quit() <file_sep>def roll_a_dice(): dice = random.randrange(1, 6); return dice def display_dice(first): display_first(first) def display_first(first): if (first == 1): gameDisplay.blit(dice_one, (width / 4, 0)) elif (first == 2): gameDisplay.blit(dice_two, (width / 4, 0)) elif (first == 3): gameDisplay.blit(dice_three, (width / 4, 0)) elif (first == 4): gameDisplay.blit(dice_four, (width / 4, 0)) elif (first == 5): gameDisplay.blit(dice_five, (width / 4, 0)) elif (first == 6): gameDisplay.blit(dice_six, (width / 4, 0)) def produce_button_message(text): our_font = pygame.font.SysFont("monospace", 15) # render the text now produce_text = our_font.render(text, 1, red) screen.blit(produce_text, (width / 8, height / 5)) #our roll will display message with our roll converted to text form, alongside def before_roll(): produce_button_message("Please hit space to roll your dice") def roll(): text = "You've completed your roll " + str(dice) + "." print(text) produce_roll_message(text) def worp(): # We don't want our roll value output before the first roll occurs. already_rolled = False roll_occur = False while already_rolled == False: for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() already_rolled = True if event.type == pygame.KEYDOWN: if event.key == pygame.K_SPACE: droll = roll_a_dice() roll_occur = True before_roll() display_dice(droll) if roll_occur: roll() <file_sep>import uitproberen as F import Game as dm import Opties as N import spelers as S pygame.init() pygame.mixer.music.load("music.mp3") red = (255, 0, 0) green = ( 0,255, 0) blue = ( 0, 0,255) black = (0,0,0) white = (255,255,255) pygame.mixer.music.play(loops=0, start=0.0) size = width, height = 340,240 screen = pygame.display.set_mode(size) redSquare = pygame.image.load('background menu.png').convert() white = (255,255,255) w = 700 h = 420 screen = pygame.display.set_mode((w, h)) screen.fill((white)) x = 0 y = 0 screen.blit(redSquare, (x, y)) pygame.display.flip() choose = dm.dumbmenu(screen, [ 'Start Game', 'Options', 'Manual', 'Show Highscore', 'Quit Game'], 200,150,None,45,1.4,black ,black) def menu(choose): if choose == 0: S.Players() print ("You choose 'Start Game'.") elif choose == 1: N.opties() print ("You choose 'Options'.") elif choose == 2: F.story() print( "You choose 'Manual'.") elif choose == 3: print ("You choose 'Show Highscore'.") elif choose == 4: print ("You choose 'Quit Game'.") menu(choose) <file_sep>import pygame import sys pygame.init() class Input: def __init__(self): self.shift = False self.white = (255,255,255) self.red = (255,10,10) self.black = (0,0,0) def get_key(self): while True: event = pygame.event.poll() if event.type == pygame.QUIT: pygame.quit() sys.exit() elif event.type == pygame.KEYDOWN: #print(event.key) if event.key in [pygame.K_LSHIFT, pygame.K_RSHIFT]: self.shift = True continue if self.shift: #return ascii code if event.key >= 97 and event.key <= 122: return event.key - 32 elif event.key == 50: return 64 #return @ elif event.key == 32: return 32 #return space even if shifted elif not self.shift: return event.key elif event.type == pygame.KEYUP: if event.key in [pygame.K_LSHIFT, pygame.K_RSHIFT]: self.shift = False else: pass def display_box(self, screen, message): fontobject = pygame.font.Font(None, 40) pygame.draw.rect(screen, self.white, ((screen.get_width()) - 0, (screen.get_height() / 2) - 0, 0,0)) #if border add 1 for transp if len(message) != 0: screen.blit(fontobject.render(message, 1 , self.black), ((screen.get_width() / 4) - 100, (screen.get_height() / 4) - 10)) pygame.display.update() def ask(self, screen, question): current_string = [] self.display_box(screen, question + ': ' + ''.join(current_string)) while True: inkey = self.get_key() if inkey == pygame.K_BACKSPACE: current_string = current_string[0:-1] elif inkey == pygame.K_RETURN: break else: current_string.append(chr(inkey)) self.display_box(screen, question + ': ' + ''.join(current_string)) return ''.join(current_string) def name(player: int): input_box = Input() white = (255,255,255) screen = pygame.display.set_mode((1700,1000)) x = 0 y = 0 if player == 1: redSquare = pygame.image.load('foto/player1.png') elif player == 2: redSquare = pygame.image.load('foto/player2.png') elif player == 3: redSquare = pygame.image.load('foto/player3.png') elif player == 4: redSquare = pygame.image.load('foto/player4.png') elif player == 5: redSquare = pygame.image.load('foto/player5.png') elif player == 6: redSquare = pygame.image.load('foto/player6.png') screen.blit(redSquare, (x, y)) pygame.display.flip() var = input_box.ask(screen, 'Name') print(var + ' was entered') return var
c14bf4f227949a4dbee25faed5470ef8e4f9dcd8
[ "Markdown", "Python" ]
18
Markdown
fapable/pygameproject2
3581f63c13fe092c57c4bc1967ccad7ad34c46f9
10a50aa37b40992d6050f2e9044d60da0bac1089
refs/heads/master
<repo_name>Derek-meng/codehacking<file_sep>/routes/web.php <?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! | */ Auth::routes(); Route::get('/logout', 'Auth\LoginController@logout'); //Route::post('/api/search','AdminUsersController@search'); Route::post('/blog','AdminPostController@home_search'); Route::get('/','AdminPostController@homeIndex')->name('home.Index'); Route::get('/about', 'AboutMeController@aboutme')->name('home.aboutme'); Route::resource('/contact','ContactController',['names'=>[ 'index'=>'Contact.Controller.index', 'store'=>'Contact.Controller.store', ]]); Route::get('/post/{id}', ['as' => 'home.post', 'uses' => 'AdminPostController@post']); Route::group(['middleware' => 'admin'], function () { Route::get('/admin', function () { return view('admin.index'); }); Route::resource('admin/aboutme', 'AboutMeController', ['names' => [ 'index' => 'admin.aboutme.index', 'create' => 'admin.aboutme.create', 'store' => 'admin.aboutme.store', 'edit' => 'admin.aboutme.edit' ]]); Route::resource('admin/users', 'AdminUsersController', ['names' => [ 'index' => 'admin.users.index', 'create' => 'admin.users.create', 'store' => 'admin.users.store', 'edit' => 'admin.users.edit' ]]); Route::get('/api/search','AdminUsersController@search'); Route::resource('admin/posts', 'AdminPostController', ['names' => [ 'index' => 'admin.posts.index', 'create' => 'admin.posts.create', 'store' => 'admin.posts.store', 'edit' => 'admin.posts.edit', ]]); Route::post('admin/posts/search','AdminPostController@search'); Route::resource('admin/categories', 'AdminCategoriesController', ['names' => [ 'index' => 'admin.catergories.index', 'create' => 'admin.catergories.create', 'store' => 'admin.catergories.store', 'edit' => 'admin.catergories.edit' ]]); Route::resource('admin/media', 'AdminMediasController', ['names' => [ 'index' => 'admin.media.index', 'create' => 'admin.media.create', 'store' => 'admin.media.store', 'edit' => 'admin.media.edit' ]]); Route::resource('admin/message', 'AdminContactController', ['names' => [ 'index' => 'admin.contact.index', 'show'=>'admin.contact.show', 'update'=>'admin.contact.update', ]]); Route::post('admin/message/search','AdminContactController@search'); Route::resource('admin/replyMessage', 'ReplyMessageController', ['names' => [ 'index' => 'admin.replymessage.index', 'show'=>'admin.replymessage.show', // 'update'=>'admin.replymessage.update', ]]); Route::post('admin/replyMessage','ReplyMessageController@search'); Route::resource('admin/comments', 'PostCommentsController', ['names' => [ 'index' => 'admin.comments.index', 'create' => 'admin.comments.create', 'store' => 'admin.comments.store', 'edit' => 'admin.comments.edit', 'show' => 'admin.comments.show' ]]); Route::resource('admin/comment/replies', 'CommentRepliesController', ['names' => [ 'index' => 'admin.replies.index', 'create' => 'admin.replies.create', 'store' => 'admin.replies.store', 'edit' => 'admin.replies.edit' ]]); }); <file_sep>/app/Http/Controllers/AdminContactController.php <?php namespace App\Http\Controllers; use App\Contact; use App\MessageReply; use Illuminate\Http\Request; use Illuminate\Support\Facades\Mail; class AdminContactController extends Controller { /** * Display a listing of the resource. * * @return \Illuminate\Http\Response */ public function index() { // $posts=Contact::orderBy('is_active','ASC')->orderBy('created_at','desc')->paginate(10); return view('admin.message.index',compact('posts')); } /** * Show the form for creating a new resource. * * @return \Illuminate\Http\Response */ public function create() { // } /** * 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) { // $posts=Contact::findOrFail($id); return view('admin.message.show',compact('posts')); } /** * Show the form for editing the specified resource. * * @param int $id * @return \Illuminate\Http\Response */ public function edit($id) { // } /** * Update the specified resource in storage. * * @param \Illuminate\Http\Request $request * @param int $id * @return \Illuminate\Http\Response */ public function update(Request $request, $id) { // $user=Contact::findOrFail($id); MessageReply::create(['contact_id'=>$id,'body'=>$request->body]); $user->update(['is_active' => 1]); $date=$request->body; $user['request']=$date; Mail::send('emails.mail_reply', ['user' => $user], function ($m) use ($user) { $m->from('<EMAIL>', 'Derek blog'); $m->to($user->email, $user->name)->subject('回復:'.$user->title); }); return redirect()->route('admin.contact.index'); } /** * Remove the specified resource from storage. * * @param int $id * @return \Illuminate\Http\Response */ public function destroy($id) { // } public function search(Request $request) { $request = $request->search; $posts = Contact::orderBy('created_at', 'desc')->where('title', 'LIKE', '%' . $request . '%')->orWhere('body', 'LIKE', '%' . $request . '%')->paginate(10); return view('admin.message.index', compact('posts')); } } <file_sep>/database/seeds/AdminsTableSeeder.php <?php use Illuminate\Database\Seeder; use App\User; class AdminsTableSeeder extends Seeder { /** * Run the database seeds. * * @return void */ public function run() { // User::create([ 'role_id'=>'1', 'is_active'=>1, 'name'=>'Derek', 'email'=>'<EMAIL>', 'password'=>bcrypt('<PASSWORD>'), 'remember_token' => str_random(10) ]); factory(App\User::class,50)->create(); } } <file_sep>/app/Http/Controllers/AdminUsersController.php <?php namespace App\Http\Controllers; use App\Http\Requests\UserEditRequest; use App\Http\Requests\UsersRequest; use App\Photo; use App\Role; use App\User; use Illuminate\Http\Request; use App\Http\Requests; use Illuminate\Support\Facades\Cache; use Illuminate\Support\Facades\Log; use Illuminate\Support\Facades\Session; class AdminUsersController extends Controller { /** * Display a listing of the resource. * * @return \Illuminate\Http\Response */ public function index() { // $users = User::orderBy('updated_at', 'desc')->paginate(10); return view('admin.users.index', compact('users')); } /** * Show the form for creating a new resource. * * @return \Illuminate\Http\Response */ public function create() { // $roles = Role::pluck('name', 'id')->all(); return view('admin.users.create', compact('roles')); } /** * Store a newly created resource in storage. * * @param \Illuminate\Http\Request $request * @return \Illuminate\Http\Response */ public function store(UsersRequest $request) { // if(trim($request->password)==""){ // $input=$request->except('password'); // }else{ // $input=$request->all(); // $input['password']=<PASSWORD>($request->password); // } $input = $request->all(); if ($file = $request->file('photo_id')) { $name = time() . $file->getClientOriginalName(); $file->move('images', $name); $photo = Photo::create(['file' => $name]); $input['photo_id'] = $photo->id; } $input['password'] = <PASSWORD>($request->password); User::create($input); return redirect('/admin/users'); } /** * Display the specified resource. * * @param int $id * @return \Illuminate\Http\Response */ public function show($id) { // return view('adnin.user.show'); } /** * Show the form for editing the specified resource. * * @param int $id * @return \Illuminate\Http\Response */ public function edit($id) { // $user = User::find($id); $roles = Role::pluck('name', 'id')->all(); return view('admin.users.edit', compact('user', 'roles')); } /** * Update the specified resource in storage. * * @param \Illuminate\Http\Request $request * @param int $id * @return \Illuminate\Http\Response */ public function update(UserEditRequest $request, $id) { // if (trim($request->password) == "") { $input = $request->except('password'); } else { $input = $request->all(); $input['password'] = <PASSWORD>($request->password); } $user = User::findOrFail($id); if ($file = $request->file('photo_id')) { $name = time() . $file->getClientOriginalName(); $file->move('images', $name); if ($user->photo) { $photo = Photo::find($user->photo->id); $input['photo_id'] = $photo->id; $photo->file = $name; $photo->save(); } else { $photo = Photo::create(['file' => $name]); $input['photo_id'] = $photo->id; } } $user->update($input); return redirect('/admin/users'); } /** * Remove the specified resource from storage. * * @param int $id * @return \Illuminate\Http\Response */ public function destroy($id) { // $user = User::findOrFail($id); if ($user->photo) { unlink(public_path() . $user->photo->file); } $user->delete(); Session::flash('deleted_user', '帳號已經刪除'); return redirect('/admin/users'); } public function search() { $requeset = request('data'); if ($requeset) { Cache::put('requeset', $requeset, 10); } if (Cache::has('requeset')) { $get = Cache::get('requeset'); $respone = User::where('name', 'LIKE', '%' . $get . '%')->orWhere('email', 'LIKE', '%' . $get . '%')->paginate(10); return $respone; } } } <file_sep>/database/factories/ModelFactory.php <?php use App\User; use App\Category; /* |-------------------------------------------------------------------------- | Model Factories |-------------------------------------------------------------------------- | | Here you may define all of your model factories. Model factories give | you a convenient way to create models for testing and seeding your | database. Just tell the factory how a default model should look. | */ $factory->define(App\User::class, function (Faker\Generator $faker) { return [ 'name' => $faker->name, 'role_id'=>mt_rand(1,3), 'is_active'=>$faker->boolean(), 'email' => $faker->safeEmail, 'password' => bcrypt(str_random(10)), 'remember_token' => str_random(10), ]; }); $factory->define(App\Post::class, function ($faker) use($factory) { $category_id=count(Category::all()); return [ 'user_id' => $factory->create(App\User::class)->id, 'category_id'=>mt_rand(1,$category_id), 'title' => $faker->sentence, 'body' => $faker->paragraph, ]; }); <file_sep>/app/Http/Controllers/AboutMeController.php <?php namespace App\Http\Controllers; use App\AboutMe; use App\Category; use App\Http\Requests\AboutMeRequest; use App\Photo; use App\Post; use Illuminate\Http\Request; use Illuminate\Support\Facades\Session; use NumberFormatter; class AboutMeController extends Controller { /** * Display a listing of the resource. * * @return \Illuminate\Http\Response */ public function index() { // $posts = AboutMe::orderBy('updated_at', 'desc')->paginate(10); return view('admin.aboutme.index', compact('posts')); } /** * Show the form for creating a new resource. * * @return \Illuminate\Http\Response */ public function create() { // return view('admin.aboutme.create'); } /** * Store a newly created resource in storage. * * @param \Illuminate\Http\Request $request * @return \Illuminate\Http\Response */ public function store(AboutMeRequest $request) { // $input = $request->all(); if ($file = $request->file('photo_id')) { $name = time() . $file->getClientOriginalName(); $file->move('images', $name); $photo = Photo::create(['file' => $name]); $input['photo_id'] = $photo->id; } AboutMe::Create($input); return redirect('/admin/aboutme'); } /** * Display the specified resource. * * @param int $id * @return \Illuminate\Http\Response */ public function show($id) { // } /** * Show the form for editing the specified resource. * * @param int $id * @return \Illuminate\Http\Response */ public function edit($id) { // $post = AboutMe::findOrFail($id); return view('admin.aboutme.edit', compact('post')); } /** * Update the specified resource in storage. * * @param \Illuminate\Http\Request $request * @param int $id * @return \Illuminate\Http\Response */ public function update(Request $request, $id) { // $post = AboutMe::findOrFail($id); $input = $request->all(); if ($file = $request->file('photo_id')) { $name = time() . $file->getClientOriginalName(); $file->move('images', $name); if ($post->photo) { $photo = Photo::find($post->photo->id); $input['photo_id'] = $photo->id; $photo->file = $name; $files = $post->photo->file; unlink(public_path() . $files); $photo->save(); } else { $photo = Photo::create(['file' => $name]); $input['photo_id'] = $photo->id; } } $post->update($input); return redirect('/admin/aboutme'); } /** * Remove the specified resource from storage. * * @param int $id * @return \Illuminate\Http\Response */ public function destroy($id) { // $sussece = AboutMe::destroy($id); if (!$sussece) return redirect('/admin/aboutme'); else { Session::flash('error', '刪除失敗'); return redirect()->back(); } } public function aboutme() { $post_acount = count(Post::all()); $post = AboutMe::where('is_active', '=', 1)->orderBy('updated_at', 'desc')->get()->first(); $post->body = str_replace("\r\n", "<br>", $post->body); $categorys = Category::pluck('name', 'id'); $categorys_all_count = []; foreach ($categorys as $key => $value) { $count = count(Category::find($key)->post); array_push($categorys_all_count, $count); } $categorys = Category::pluck('name'); for ($i = 0; $i < sizeof($categorys_all_count); $i++) { $categorys_all_count[$i] = $categorys_all_count[$i] / $post_acount; $formatter = new NumberFormatter('en_US', NumberFormatter::PERCENT); $categorys_all_count[$i] = ($formatter->format($categorys_all_count[$i])); } $categorys->categorys_all_count = $categorys_all_count; return view('post.post-about', compact('post', 'categorys')); } } <file_sep>/app/Http/Controllers/ContactController.php <?php namespace App\Http\Controllers; use App\Http\Requests\ContactBlog; use Illuminate\Http\Request; use App\Contact; use Illuminate\Support\Facades\Mail; use Illuminate\Support\Facades\Session; class ContactController extends Controller { /** * Display a listing of the resource. * * @return \Illuminate\Http\Response */ public function index() { // return view('post.contact'); } /** * Show the form for creating a new resource. * * @return \Illuminate\Http\Response */ public function create() { // } /** * Store a newly created resource in storage. * * @param \Illuminate\Http\Request $request * @return \Illuminate\Http\Response */ public function store(ContactBlog $request) { // $data = [ 'name' => $request->name, 'email' => $request->email, 'title' => $request->title, 'body' => $request->body, ]; Contact::create($request->all()); Session::flash('sent_masseage', '已經成功寄出'); $mail=mail::send('emails.mail', $data, function ($message) { $message->to('<EMAIL>','Derek_blog')->subject('Contact Me'); }); return redirect()->back(); } /** * Display the specified resource. * * @param int $id * @return \Illuminate\Http\Response */ public function show($id) { // $posts=Contact::findOrFail($id); return view('admin.message.show',compact('posts')); } /** * Show the form for editing the specified resource. * * @param int $id * @return \Illuminate\Http\Response */ public function edit($id) { // } /** * Update the specified resource in storage. * * @param \Illuminate\Http\Request $request * @param int $id * @return \Illuminate\Http\Response */ public function update(Request $request, $id) { // } /** * Remove the specified resource from storage. * * @param int $id * @return \Illuminate\Http\Response */ public function destroy($id) { // } public function admin_index() { // $posts=Contact::orderBy('is_active','desc')->orderBy('created_at','desc')->paginate(10); return view('admin.message.index',compact('posts')); } } <file_sep>/app/Contact.php <?php namespace App; use Illuminate\Database\Eloquent\Model; class Contact extends Model { // protected $fillable=[ 'name', 'email', 'body', 'is_active', 'title', ]; public function reply_message() { return $this->hasOne('App\MessageReply'); } } <file_sep>/database/seeds/AboutMeTableSeeder.php <?php use Illuminate\Database\Seeder; use App\AboutMe; class AboutMeTableSeeder extends Seeder { /** * Run the database seeds. * * @return void */ public function run() { // AboutMe::create([ 'title'=>'About Derek', 'body'=>'Hi This is Derek blog about Laravel', 'is_active'=>1, ]); } }
cf21d5f83427cda4b57427718d7225043348e2b1
[ "PHP" ]
9
PHP
Derek-meng/codehacking
57365f1def9f5d90f15167536b2a7ea0fa9285cd
c67cc3a30827d0476c69282d97b4790d2b169ca7
refs/heads/master
<repo_name>stIncMale/pies<file_sep>/pies-base/pies-base-main/src/main/java/com/gl/vn/me/ko/pies/base/main/Std.java package com.gl.vn.me.ko.pies.base.main; import static com.google.common.base.Preconditions.checkNotNull; import com.gl.vn.me.ko.pies.base.constant.Constant; import com.gl.vn.me.ko.pies.base.constant.Message; import com.gl.vn.me.ko.pies.base.main.JavaOption.JavaOptionName; import com.gl.vn.me.ko.pies.base.main.JavaOption.JavaOptionUnspecifiedException; import com.gl.vn.me.ko.pies.base.throwable.ApplicationError; import com.gl.vn.me.ko.pies.base.throwable.ApplicationException; import java.io.PrintStream; import java.io.UnsupportedEncodingException; import java.nio.charset.Charset; import java.time.ZonedDateTime; import java.time.format.DateTimeFormatter; import javax.annotation.Nullable; /** * Provides methods for printing to {@link System#out} and {@link System#err} that append some useful information to * printed strings. * <p> * In case of using {@link Std}{@code .outPrintln(...)} and {@link Std}{@code .errPrintln(...)} methods a {@code PREFIX} * is prepended that contains information on the stream and date. Format of the {@code PREFIX} is * {@code "[STREAM] [DATE] [THREAD_NAME] - "}, where * <ul> * <li>{@code STREAM} is {@link StreamType#STDOUT}{@code .}{@link StreamType#toString() toString()} for * {@link System#out} and {@link StreamType#STDERR} {@code .}{@link StreamType#toString() toString()} for * {@link System#err}</li> * <li>{@code DATE} represents date formatted with {@link DateTimeFormatter} constructed with pattern * {@code "yyyy-MM-dd'T'HH:mm:ss.SSSZ"} and {@link Constant#LOCALE}</li> * <li>{@code THREAD_NAME} represents {@linkplain Thread#getName() name} of the {@link Thread} that prints to standard * stream</li> * </ul> * <p> * This class also substitutes {@link System#out} and {@link System#err} streams during initialization, which is * initiated from the {@link Main} class initialization. Streams are substituted with streams that use a special * {@link Charset} specific to the Application (specified by the {@code -Dpies.consoleCharset} Java option, don't * confuse it with {@link Constant#CHARSET}). * <p> * One SHOULD use {@link Std} to print to standard streams * and SHOULD NOT use {@link System#out} and {@link System#err} directly. */ public final class Std { /** * Represents type of a standard stream. */ public static enum StreamType { /** * Designates {@link System#out} stream. */ STDOUT, /** * Designates {@link System#err} stream. */ STDERR; private final PrintStream getStream() { final PrintStream result; switch (this) { case STDOUT: { final PrintStream stream = System.out; result = stream; break; } case STDERR: { final PrintStream stream = System.err; result = stream; break; } default: { throw new ApplicationError(Message.CAN_NEVER_HAPPEN); } } return result; } } private static final DateTimeFormatter DATE_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSSZ", Constant.LOCALE); static { configureOutStreams(); } /** * Substitutes {@link System#out} and {@link System#err} streams with streams that use {@link Charset} specified by * the {@link JavaOptionName#CONSOLE_CHARSET}. */ private static final void configureOutStreams() { final String consoleCharset; try { consoleCharset = JavaOption.getValue(JavaOptionName.CONSOLE_CHARSET); final PrintStream out = new PrintStream(System.out, true, consoleCharset); final PrintStream err = new PrintStream(System.err, true, consoleCharset); System.setOut(out); System.setErr(err); } catch (final JavaOptionUnspecifiedException | UnsupportedEncodingException e) { throw new ApplicationException("Failed to configure standard output and error streams", e); } Std.outPrintln(Message.format("Standard output streams was configured to use %s charset", consoleCharset)); } /** * Acts as {@code java.lang.System.err.println()}. */ public static final void errPrintln() { System.out.println(); } /** * Acts as {@link System#err}{@code .}{@link PrintStream#println println}{@code (PREFIX + x)}. * See documentation of the class {@link Std} for the description of {@code PREFIX}. * * @param x * The {@link String} to be printed. */ public static final void errPrintln(@Nullable final String x) { println(x, StreamType.STDERR); } private static final StringBuilder getPrefix(final StreamType type) { final StringBuilder result = new StringBuilder(); result.append("[").append(type.toString()).append("] [") .append(DATE_FORMATTER.format(ZonedDateTime.now())).append("] [") .append(Thread.currentThread().getName()).append("] - "); return result; } /** * Initiates {@link Std} class initialization. */ static final void initialize() { // empty body is enough } /** * Acts as {@code java.lang.System.out.println()}. */ public static final void outPrintln() { System.out.println(); } /** * Acts as {@link System#out}{@code .}{@link PrintStream#println println}{@code (PREFIX + x)}. * See documentation of the class {@link Std} for the description of {@code PREFIX}. * * @param x * The {@link String} to be printed. */ public static final void outPrintln(@Nullable final String x) { println(x, StreamType.STDOUT); } private static final void println(@Nullable final String x, final StreamType type) { println(x, type, type.getStream()); } /** * Acts as {@link #outPrintln(String)} or {@link #errPrintln(String)} but constructs {@code PREFIX} according to the * specified {@code type} and prints to the provided {@code stream}. This method is useless for most cases. * * @param x * The {@link String} to be printed. * @param type * Type of the {@code stream}. * @param stream * {@link PrintStream} to use for printing {@code x}. */ public static final void println(@Nullable final String x, final StreamType type, final PrintStream stream) { checkNotNull(type, Message.ARGUMENT_NULL, "second", "type"); checkNotNull(type, Message.ARGUMENT_NULL, "third", "stream"); stream.println(getPrefix(type) .append(x) .toString()); } private Std() { throw new UnsupportedOperationException(Message.INSTANTIATION_NOT_SUPPORTED); } } <file_sep>/pies-platform/pies-platform-server/src/main/java/com/gl/vn/me/ko/pies/platform/server/rest/JsonRestServer.java package com.gl.vn.me.ko.pies.platform.server.rest; import static com.google.common.base.Preconditions.checkNotNull; import com.gl.vn.me.ko.pies.base.constant.Constant; import com.gl.vn.me.ko.pies.base.constant.Message; import io.netty.channel.ChannelInitializer; import io.netty.channel.socket.ServerSocketChannel; import io.netty.handler.codec.http.DefaultFullHttpResponse; import io.netty.handler.codec.http.FullHttpResponse; import io.netty.handler.codec.http.HttpHeaders; import io.netty.handler.codec.http.HttpResponseStatus; import io.netty.handler.codec.http.HttpVersion; import java.net.InetSocketAddress; import java.util.Collection; import java.util.concurrent.ThreadFactory; import javax.annotation.Nullable; import javax.annotation.concurrent.ThreadSafe; import javax.inject.Inject; import javax.json.JsonBuilderFactory; import javax.json.JsonObject; import javax.json.JsonObjectBuilder; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * A {@link RestServer} that responds by using JSON only. * <p> * HTTP responses MAY specify * <a href="http://tools.ietf.org/html/rfc2616#section-6.1.1">HTTP reason phrase</a> in the following format * (see {@link #JSON_RESPONSE_REASON_PHRASE_NVNAME}): * <pre><code> * { * "httpReasonPhrase": "a reason phrase" * } * </code></pre> */ @ThreadSafe public final class JsonRestServer extends RestServer<JsonRestRequestHandlerResult> { private static final Logger LOGGER = LoggerFactory.getLogger(JsonRestServer.class); /** * Name of a name-value JSON pair that specifies an * <a href="http://tools.ietf.org/html/rfc2616#section-6.1.1">HTTP reason phrase</a>. * <p> * Value of this constant is {@value}. */ public static final String JSON_RESPONSE_REASON_PHRASE_NVNAME = "httpReasonPhrase"; private final JsonBuilderFactory jsonBuilderFactory; /** * Constructs a new instance of {@link JsonRestServer}. * See {@link RestServer#RestServer( * InetSocketAddress, String, Integer, Integer, Integer, ThreadFactory, ChannelInitializer, Collection)} * for details. * * @param address * See {@link RestServer#RestServer( * InetSocketAddress, String, Integer, Integer, Integer, ThreadFactory, ChannelInitializer, Collection)}. * @param name * {@link RestServer#RestServer( * InetSocketAddress, String, Integer, Integer, Integer, ThreadFactory, ChannelInitializer, Collection)}. * @param maxBossThreads * {@link RestServer#RestServer( * InetSocketAddress, String, Integer, Integer, Integer, ThreadFactory, ChannelInitializer, Collection)}. * @param maxWorkerThreads * {@link RestServer#RestServer( * InetSocketAddress, String, Integer, Integer, Integer, ThreadFactory, ChannelInitializer, Collection)}. * @param maxPostResponseWorkerThreads * {@link RestServer#RestServer( * InetSocketAddress, String, Integer, Integer, Integer, ThreadFactory, ChannelInitializer, Collection)}. * @param threadFactory * {@link RestServer#RestServer( * InetSocketAddress, String, Integer, Integer, Integer, ThreadFactory, ChannelInitializer, Collection)}. * @param serverSocketChannelInitializer * {@link RestServer#RestServer( * InetSocketAddress, String, Integer, Integer, Integer, ThreadFactory, ChannelInitializer, Collection)}. * @param restHandlers * {@link RestServer#RestServer( * InetSocketAddress, String, Integer, Integer, Integer, ThreadFactory, ChannelInitializer, Collection)}. * @param jsonBuilderFactory * An implementation of {@link JsonBuilderFactory}. */ @Inject public JsonRestServer( @RestServerAddress final InetSocketAddress address, @RestServerName final String name, @RestServerBoss final Integer maxBossThreads, @RestServerWorker final Integer maxWorkerThreads, @RestServerRequestHandling final Integer maxPostResponseWorkerThreads, @RestServerThreadFactory final ThreadFactory threadFactory, @RestServerBoss @Nullable final ChannelInitializer<ServerSocketChannel> serverSocketChannelInitializer, @RestServerRequestHandling @Nullable final Collection<? extends RestRequestHandler<? extends JsonRestRequestHandlerResult>> restHandlers, final JsonBuilderFactory jsonBuilderFactory) { super( address, name, maxBossThreads, maxWorkerThreads, maxPostResponseWorkerThreads, threadFactory, serverSocketChannelInitializer, restHandlers ); checkNotNull(jsonBuilderFactory, Message.ARGUMENT_NULL, "tenth", "jsonBuilderFactory"); this.jsonBuilderFactory = jsonBuilderFactory; } @Override protected final FullHttpResponse createServiceHttpResponse( final HttpResponseStatus httpResponseStatus, @Nullable final String httpReasonPhrase) { final FullHttpResponse result = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, httpResponseStatus); if (httpReasonPhrase != null) { final JsonObjectBuilder jsonBuilder = jsonBuilderFactory.createObjectBuilder(); jsonBuilder.add(JSON_RESPONSE_REASON_PHRASE_NVNAME, httpReasonPhrase); final JsonObject httpResponseContent = jsonBuilder.build(); result.content().writeBytes(httpResponseContent.toString().getBytes(Constant.CHARSET)); } final HttpHeaders responseHeaders = result.headers(); responseHeaders.set(HttpHeaders.Names.CONTENT_TYPE, "application/json; charset=" + Constant.CHARSET.name()); return result; } } <file_sep>/misc/manual test/initiatorApplicationLog.sh #!/bin/bash #Set environment readonly MANUAL_TEST_LOCATION="/Users/male/Documents/programming/projects/pies/misc/manual test" readonly PIES_INITIATOR_APP_HOME_DIR_NAME="pies-app-initiator" less "${MANUAL_TEST_LOCATION}/${PIES_INITIATOR_APP_HOME_DIR_NAME}/log/application.log" <file_sep>/pies-base/pies-base-main/pom.xml <?xml version="1.0" encoding="UTF-8"?> <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"> <description> Contains an entry point of the Application as well as some other prime classes that is unreasonable to place to separate projects. Also contains Harness that simplifies Application startup and shutdown. </description> <modelVersion>4.0.0</modelVersion> <artifactId>pies-base-main</artifactId> <packaging>jar</packaging> <name>pies-base-main</name> <url>${pies.project.url}</url> <licenses> <license> <name>${pies.project.license.name}</name> <url>${pies.project.license.url}</url> </license> </licenses> <inceptionYear>${pies.project.inceptionYear}</inceptionYear> <organization> <name>${pies.project.organization.name}</name> <url>${pies.project.organization.url}</url> </organization> <parent> <groupId>com.gl.vn.me.ko.pies</groupId> <artifactId>pies-base-parent</artifactId> <version>0.0.0-SNAPSHOT</version> <relativePath>../pies-base-parent/pom.xml</relativePath> </parent> <dependencies> <dependency> <groupId>com.google.code.findbugs</groupId> <artifactId>jsr305</artifactId> </dependency> <dependency> <groupId>com.google.inject</groupId> <artifactId>guice</artifactId> </dependency> <dependency> <groupId>io.netty</groupId> <artifactId>netty-all</artifactId> </dependency> <dependency> <groupId>javax.inject</groupId> <artifactId>javax.inject</artifactId> </dependency> <dependency> <groupId>com.google.code.findbugs</groupId> <artifactId>annotations</artifactId> </dependency> <dependency> <groupId>com.gl.vn.me.ko.pies</groupId> <artifactId>pies-base-doc</artifactId> </dependency> <dependency> <groupId>com.gl.vn.me.ko.pies</groupId> <artifactId>pies-base-config</artifactId> </dependency> <dependency> <groupId>com.gl.vn.me.ko.pies</groupId> <artifactId>pies-base-constant</artifactId> </dependency> <dependency> <groupId>com.gl.vn.me.ko.pies</groupId> <artifactId>pies-base-throwable</artifactId> </dependency> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <scope>test</scope> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-api</artifactId> </dependency> <dependency><!-- implementation of org.slf4j:slf4j-api --> <groupId>org.apache.logging.log4j</groupId> <artifactId>log4j-slf4j-impl</artifactId> <scope>runtime</scope> </dependency> <dependency><!-- is used by org.apache.logging.log4j:log4j-slf4j-impl --> <groupId>org.apache.logging.log4j</groupId> <artifactId>log4j-core</artifactId> <scope>runtime</scope> </dependency> <dependency><!-- is used by org.apache.logging.log4j:log4j-core --> <groupId>com.lmax</groupId> <artifactId>disruptor</artifactId> <scope>runtime</scope> </dependency> </dependencies> <build> <resources> <resource> <directory>src/main/resources/services</directory> <targetPath>META-INF/services</targetPath> </resource> </resources> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-antrun-plugin</artifactId> <executions> <execution> <id>prepare-harness-artifact</id> <phase>package</phase> <configuration> <target> <zip destfile="${pies.attachedArtifactFile.harness}"> <fileset dir="src/harness"/> </zip> <zip destfile="${pies.attachedArtifactFile.config}"> <fileset dir="src/config"/> </zip> </target> </configuration> <goals> <goal>run</goal> </goals> </execution> </executions> </plugin> <plugin> <groupId>org.codehaus.mojo</groupId> <artifactId>build-helper-maven-plugin</artifactId> <executions> <execution> <id>attach-harness-artifact</id> <phase>package</phase> <goals> <goal>attach-artifact</goal> </goals> <configuration> <artifacts> <artifact> <file>${pies.attachedArtifactFile.harness}</file> <type>zip</type> <classifier>${pies.classifier.harness}</classifier> </artifact> <artifact> <file>${pies.attachedArtifactFile.config}</file> <type>zip</type> <classifier>${pies.classifier.config}</classifier> </artifact> </artifacts> </configuration> </execution> </executions> </plugin> </plugins> </build> </project><file_sep>/pies-platform/pies-platform-server/src/main/java/com/gl/vn/me/ko/pies/platform/server/rest/RestRequestHandler.java package com.gl.vn.me.ko.pies.platform.server.rest; import static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.base.Preconditions.checkState; import com.gl.vn.me.ko.pies.base.constant.Message; import com.gl.vn.me.ko.pies.platform.server.Server; import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.concurrent.CompletableFuture; import java.util.concurrent.CompletionStage; import java.util.concurrent.ExecutorService; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicReference; import javax.annotation.Nullable; import javax.annotation.concurrent.ThreadSafe; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Represents object that is able handleRequest a {@link RestRequest}. * * @param <T> * Represents type of a result of the {@link #handleRequest(RestRequest, ExecutorService)} method. */ @ThreadSafe public abstract class RestRequestHandler<T> { private static final Logger LOGGER = LoggerFactory.getLogger(RestRequestHandler.class); private final RestRequest binding; /** * {@link RestRequestHandler} MUST access {@link RestRequestDispatcher} very carefully: * any new access MUST be analyzed on thread-safety. See code of * {@link RestRequestDispatcher#RestRequestDispatcher(Server, ExecutorService, Collection)} * for details. */ private final AtomicReference<RestRequestDispatcher<?>> dispatcher; private final AtomicBoolean active; /** * Constructor of {@link RestRequestHandler}. * * @param binding * {@link RestRequest} that represents a family of {@link RestRequest}s * this {@link RestRequestHandler} is able to handleRequest (see {@link #getBinding()} for details). */ protected RestRequestHandler(final RestRequest binding) { checkNotNull(binding, Message.ARGUMENT_NULL_SINGLE, "binding"); this.binding = binding; dispatcher = new AtomicReference<>(null); active = new AtomicBoolean(true); } /** * Associates a {@link RestRequestHandler} with the provided {@code dispatcher}. * This method is called from constructors of {@link RestRequestDispatcher}. * * @param dispatcher * A {@link RestRequestDispatcher} with which to associate the {@link RestRequestHandler}. * @throws IllegalStateException * If {@link RestRequestHandler} is already associated with some {@link RestRequestDispatcher}. */ final void associate(final RestRequestDispatcher<?> dispatcher) { checkNotNull(dispatcher, Message.ARGUMENT_NULL_SINGLE, "dispatcher"); checkState(active.get(), "%s isn't active", this); if (!this.dispatcher.compareAndSet(null, dispatcher)) { throw new IllegalStateException( Message.format("Handler %s is already associated with %s", this, dispatcher)); } } /** * Returns {@code true} if and only if {@code object} is an instance of {@link RestRequestHandler} and * {@linkplain #getBinding() is bound} to the same family of {@link RestRequest}s * as this {@link RestRequestHandler}. * * @param object * An {@link Object} with which to compare. * @return * {@code true} if this {@link RestRequestHandler} is equal to {@code object} and {@code false} otherwise. */ @SuppressFBWarnings( value = "NP_METHOD_PARAMETER_TIGHTENS_ANNOTATION", justification = "Object.equals(...) allows null arguments") @Override public final boolean equals(@Nullable final Object object) { final boolean result; if (object instanceof RestRequestHandler) { final RestRequestHandler<?> handler = (RestRequestHandler<?>)object; result = binding.equals(handler.binding); } else { result = false; } return result; } /** * Returns arguments of the provided {@code request}. E.g. if the {@code request} is {@code "POST /b1/a1/a2/"} and * {@linkplain #getBinding() binding} is {@code "POST /b1/"} then arguments are {@code "a1"} and {@code "a2"}. * * @param request * {@link RestRequest} dispatched to this {@link RestRequestHandler}. * @return * {@link List} that contains {@link String} arguments of the provided {@code request}. * The returned {@link List} is {@linkplain List#isEmpty() empty} if there are no arguments. */ public final List<String> getArguments(final RestRequest request) { final List<String> requestUriNodes = request.getUriNodes(); final List<String> bindingUriNodes = binding.getUriNodes(); final int resultSize = requestUriNodes.size() - bindingUriNodes.size(); final List<String> result; if (resultSize > 0) { result = new ArrayList<>(resultSize); for (int i = bindingUriNodes.size(); i < requestUriNodes.size(); i++) { result.add(requestUriNodes.get(i)); } } else { final List<String> empty = Collections.<String>emptyList(); result = empty; } return result; } /** * Returns {@linkplain RestRequest#toString() string representation} of the family of {@link RestRequest}s * this {@link RestRequestHandler} is able to handleRequest. Such a family of {@link RestRequest}s is also a * {@link RestRequest} and is called a binding. * More strictly binding is a {@link RestRequest} that represents the * biggest common part of all {@link RestRequest}s this {@link RestRequestHandler} is able to handleRequest. * E.g. if the {@link RestRequestHandler} is able to handleRequest requests {@code "POST /elements/by_date/2014/01/30/"} * and {@code "POST /elements/by_date/1985/"} then binding is {@code "POST /elements/by_date/"}. * * @return * Returns {@linkplain RestRequest#toString() string representation} of the binding. */ public final RestRequest getBinding() { return binding; } /** * Returns a {@link Server} this {@link RestRequestHandler} belongs to. * * @return * A {@link Server} this {@link RestRequestHandler} belongs to. * @throws IllegalStateException * If {@link RestRequestHandler} doesn't belong to any {@link Server}. */ protected final Server getServer() { @Nullable final RestRequestDispatcher<?> dispatcher = this.dispatcher.get(); final Server result; if (dispatcher != null) { result = dispatcher.getServer(); } else { throw new IllegalStateException( Message.format("Handler %s isn't associated with any REST request dispatcher", this)); } return result; } /** * This method invokes {@link #handleRequest(RestRequest, ExecutorService)}. * It's guaranteed that this method doesn't throw any {@link Exception} except {@link IllegalStateException}. * * @param request * {@link RestRequest} to handleRequest. * @param executorService * {@link ExecutorService} to use to handleRequest the {@code request}. * @return * Result of the {@link #handleRequest(RestRequest, ExecutorService)} method. * @throws IllegalStateException * If {@link #shutdown()} was invoked at least once. */ final CompletionStage<T> handle(RestRequest request, ExecutorService executorService) throws IllegalStateException { checkNotNull(request, Message.ARGUMENT_NULL, "first", "request"); checkNotNull(executorService, Message.ARGUMENT_NULL, "second", "executorService"); checkState(active.get(), "%s isn't active", this); CompletionStage<T> result; try { result = handleRequest(request, executorService); } catch (final Exception e) { final CompletableFuture<T> exceptionallyCompleted = new CompletableFuture<>(); exceptionallyCompleted.completeExceptionally(e); result = exceptionallyCompleted; } return result; } /** * Handles the specified {@code request}. * This method MUST NOT perform blocking operations. * * @param request * {@link RestRequest} to handleRequest. * @param executorService * {@link ExecutorService} to use to handleRequest the {@code request}. * Implementation MUST NOT {@link ExecutorService#shutdown() shut down} this {@link ExecutorService}. * @return * {@link CompletionStage} that represents result of request handling. * The returned {@link CompletionStage} MUST be completed exceptionally as follows: * <ul> * <li>with {@link RestRequestHandlingException} if handling of the {@code request} has failed</li> * <li>with {@link BadRestRequestException} if the {@code request} is incorrect</li> * </ul> */ protected abstract CompletionStage<T> handleRequest(RestRequest request, ExecutorService executorService); /** * Returns if the {@link RestRequestHandler} active or was {@linkplain #shutdown() shut down}. * * @return * {@code true} if the {@link RestRequestHandler} active, {@code false} otherwise. */ protected final boolean getState() { return active.get(); } @Override public final int hashCode() { return binding.hashCode(); } /** * Returns a description of the {@link RestRequestHandler}. * * @return * A description of the {@link RestRequestHandler}. */ @Override public String toString() { final StringBuilder sb = new StringBuilder(this.getClass().getName()) .append("(binding=").append(getBinding()) .append(", active=").append(active.get()).append(')'); final String result = sb.toString(); return result; } /** * This method invokes {@link #shutdownHook()}. * Once this method is invoked {@link RestRequestHandler} can't * {@linkplain #handle(RestRequest, ExecutorService) handle} requests * and can't be {@linkplain #associate(RestRequestDispatcher) associated} with a {@link RestRequestDispatcher}. * The method is idempotent and is called from {@link RestRequestDispatcher#shutdown()}. */ final void shutdown() { if (active.compareAndSet(true, false)) { shutdownHook(); LOGGER.info("{} was shut down", this); } } /** * Subclasses MAY implement this method in order to perform shutdown actions; this implementation does nothing. * This method is called from the {@link #shutdown()} method and MAY be not idempotent. */ protected void shutdownHook() { } } <file_sep>/pies-platform/pies-platform-client/src/main/java/com/gl/vn/me/ko/pies/platform/client/tcp/TcpSequentialHandler.java package com.gl.vn.me.ko.pies.platform.client.tcp; import static com.gl.vn.me.ko.pies.base.constant.Message.format; import static java.util.concurrent.TimeUnit.MILLISECONDS; import com.gl.vn.me.ko.pies.base.throwable.ApplicationError; import com.gl.vn.me.ko.pies.base.throwable.TimeoutException; import io.netty.channel.Channel; import io.netty.channel.ChannelHandlerAdapter; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.ChannelPromise; import java.util.LinkedList; import java.util.Optional; import java.util.Queue; import java.util.concurrent.ScheduledExecutorService; import javax.annotation.Nullable; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Handles {@link TcpMessage} and {@link TcpResponse} * and MUST be the last in the {@link ChannelPipeline} for each {@link SocketChannel} created by {@link TcpSequentialClient}. * * @param <Message> * A type of message contained by {@link TcpMessage}. * @param <Response> * A type of response contained by {@link TcpResponse}. */ final class TcpSequentialHandler<Message, Response> extends ChannelHandlerAdapter { private static final class WaitingMessageCancellator implements Runnable { private static final Logger LOGGER = LoggerFactory.getLogger(WaitingMessageCancellator.class); private final TcpMessage<?, ?> message; private WaitingMessageCancellator(final TcpMessage<?, ?> message) { this.message = message; } @Override public final void run() { boolean closeConnection = false; try { closeConnection = message.getResponse().completeExceptionally( new TimeoutException((format("Can't get response to %s due to timeout", message)), "TCP response timeout")); } finally { if (closeConnection) { final TcpConnection<?, ?> connection = message.getConnection(); connection.close(); LOGGER.debug("{} was closed due to {}", connection, TimeoutException.class.getName()); } } } } private static final Logger LOGGER = LoggerFactory.getLogger(TcpSequentialHandler.class); private final Queue<TcpMessage<Message, Response>> messagesWaitingForResponse; private final ScheduledExecutorService scheduledExecutorService; /** * Constructs a new instance of {@link TcpSequentialHandler}. * * @param scheduledExecutorService * {@link ScheduledExecutorService} that will be used to enforce * {@linkplain TcpMessage#getResponseTimeoutMillis() response timeout}. */ TcpSequentialHandler(final ScheduledExecutorService scheduledExecutorService) { messagesWaitingForResponse = new LinkedList<>(); this.scheduledExecutorService = scheduledExecutorService; } @Override public final void write(final ChannelHandlerContext ctx, final Object msg, final ChannelPromise promise) { LOGGER.debug("Writing {} to {}", msg, ctx.channel()); @SuppressWarnings("unchecked") final TcpMessage<Message, Response> message = (TcpMessage<Message, Response>)msg; scheduleCompletionByTimeout(message); ctx.write(message.get(), promise); if (message.isResponseExpected()) { messagesWaitingForResponse.add(message); } } /* * This isn't the best implementation because it produced a new completion task for each message. * While such approach is the most accurate in terms of compliance with timeout value, * a better implementation would consider a coarsely quantized time * and aggregate completion tasks that should be completed within the same time quantum (e.g. within the same 100ms). */ private final void scheduleCompletionByTimeout(final TcpMessage<?, ?> message) { if (message.isResponseExpected()) { scheduledExecutorService.schedule( new WaitingMessageCancellator(message), message.getResponseTimeoutMillis(), MILLISECONDS); } } @Override public final void channelRead(final ChannelHandlerContext ctx, final Object msg) { LOGGER.debug("Reading {} from {}", msg, ctx.channel()); @SuppressWarnings("unchecked") final Response response = (Response)msg; @Nullable final TcpMessage<Message, Response> message = messagesWaitingForResponse.poll(); if (message != null) { message.getResponse().complete(Optional.of(new TcpResponse<>(response, message.getConnection()))); } else { /* * This exception can only occur if the decoder supplied to TcpSequentialClient has error in its logic. */ exceptionCaught(ctx, new ApplicationError( "Message is null. This exception is likely occur if the decoder above this handler has error in its logic")); } } @Override public final void exceptionCaught(final ChannelHandlerContext ctx, final Throwable cause) { try { LOGGER.error("Exception caught", cause); } finally { try { final Channel channel = ctx.channel(); channel.close(); } finally { messagesWaitingForResponse.stream().forEach(message -> message.getResponse().completeExceptionally(cause)); } } } @Override public final void channelInactive(final ChannelHandlerContext ctx) { final Channel channel = ctx.channel(); try { ctx.fireChannelInactive(); LOGGER.debug("{} is inactive", channel); } finally { cancelAllMessagesWaitingForResponse(); } } @Override public final void disconnect(final ChannelHandlerContext ctx, final ChannelPromise promise) { final Channel channel = ctx.channel(); try { ctx.disconnect(); LOGGER.debug("{} was disconnected", channel); } finally { cancelAllMessagesWaitingForResponse(); channel.close(); } } @Override public final void close(final ChannelHandlerContext ctx, final ChannelPromise promise) { try { final Channel channel = ctx.channel(); ctx.close(); LOGGER.debug("{} was closed", channel); } finally { cancelAllMessagesWaitingForResponse(); } } private final void cancelAllMessagesWaitingForResponse() { messagesWaitingForResponse.stream().forEach(message -> message.getResponse().cancel(true)); } } <file_sep>/pies-platform/pies-platform-client/src/main/java/com/gl/vn/me/ko/pies/platform/client/package-info.java /** * Contains {@link com.gl.vn.me.ko.pies.platform.client.Client} interface. */ @com.gl.vn.me.ko.pies.base.doc.Defaults @javax.annotation.ParametersAreNonnullByDefault package com.gl.vn.me.ko.pies.platform.client; <file_sep>/pies-app/pies-app-initiator/pies-app-initiator-logic/src/main/java/com/gl/vn/me/ko/pies/app/initiator/package-info.java /** * Contains {@link com.gl.vn.me.ko.pies.base.main.App} logic for PIES Initiator Application. */ @com.gl.vn.me.ko.pies.base.doc.Defaults @javax.annotation.ParametersAreNonnullByDefault package com.gl.vn.me.ko.pies.app.initiator; <file_sep>/pies-base/pies-base-main/src/main/java/com/gl/vn/me/ko/pies/base/di/GuiceModule.java package com.gl.vn.me.ko.pies.base.di; import com.gl.vn.me.ko.pies.base.constant.Message; import com.gl.vn.me.ko.pies.base.main.GuiceLocator; import com.gl.vn.me.ko.pies.base.throwable.ApplicationError; import com.google.inject.AbstractModule; import com.google.inject.Injector; import java.util.ServiceLoader; /** * Represents {@link AbstractModule} that is provided as part of API. * <p> * Published instances of {@link GuiceModule} are accessed via {@link ServiceLoader}, and therefore implementation of * the {@link GuiceModule} MUST be public, MUST have a public constructor without parameters, and a * provider-configuration file MUST be available as specified in the {@link ServiceLoader} documentation. The described * constructor MUST NOT be called directly by any Application code. * <p> * It's expected that each project will locate only the required published instances of {@link GuiceModule} via * {@link GuiceLocator} and create an {@link Injector} that MUST only be available for that project. Instances of * {@link GuiceModule} MUST be accessed only via {@link GuiceLocator} even from project that publish the * {@link GuiceModule}. * <p> * {@link GuiceModule} SHOULD be documented to specify everything that can be requested from the {@link Injector} that * is based on the {@link GuiceModule}, and to specify {@linkplain #getName() names} of {@link GuiceModule}s it depends on. * * @see GuiceLocator */ public abstract class GuiceModule extends AbstractModule { /** * Constructor of {@link GuiceModule}. */ protected GuiceModule() { } /** * Returns name of the {@link GuiceModule}. Name is equal to name of the Java package that provides * {@link GuiceModule}, so any Java package MAY only publish a single {@link GuiceModule}, because name MUST be unique. * * @return * Name of the {@link GuiceModule}. */ public final String getName() { final Class<? extends GuiceModule> klass = this.getClass(); final Package pckg = klass.getPackage(); final String result; if (pckg == null) { throw new ApplicationError(Message.format("Unable to return name of the guice module %s", klass)); } else { final String pckgName = pckg.getName(); result = pckgName; } return result; } /** * Returns a description of the {@link GuiceModule}. * * @return * A description of the {@link GuiceModule}. */ @Override public final String toString() { final StringBuilder sb = new StringBuilder(this.getClass().getName()) .append("(name=").append(getName()).append(')'); final String result = sb.toString(); return result; } } <file_sep>/pies-base/pies-base-main/src/harness/start.sh #!/bin/bash #This script is a RECOMMENDED way to start the Application. #This script MAY return -1 in if execution of function from functions.sh failed. #Directory that contains this script. readonly THIS_SCRIPT_DIRNAME=`cd "$(dirname "${0}")"; pwd` #Application Home directory. APP_HOME=`dirname "${THIS_SCRIPT_DIRNAME}"` source "${THIS_SCRIPT_DIRNAME}/functions.sh" source "${THIS_SCRIPT_DIRNAME}/environment.sh" #A file where to write standard output and error streams of the Java process. readonly JAVA_CONSOLE_LOG_FILE="${APP_LOGS_LOCATION}/${JAVA_CONSOLE_LOG}" #PID File - a file where to write PID of the Java process. readonly APP_PID_FILE="${APP_RUNTIME_LOCATION}/application.pid" #Lock File - a file used to prevent repeated start of the same instance of Application. readonly APP_LOCK_FILE="${APP_RUNTIME_LOCATION}/application.lock" #Class that contains entry point to Java application. readonly APP_MAIN_CLASS="com.gl.vn.me.ko.pies.base.main.Main" #Transform paths according to execution environment. if [ "${OPERATING_SYSTEM_TYPE}" == "Windows-Cygwin" ] then JAVA_CLASSPATH=`cygwinToWindowsPath "${JAVA_CLASSPATH}"` APP_HOME=`cygwinToWindowsPath "${APP_HOME}"` APP_LOGS_LOCATION=`cygwinToWindowsPath "${APP_LOGS_LOCATION}"` APP_CONFIGS_LOCATION=`cygwinToWindowsPath "${APP_CONFIGS_LOCATION}"` APP_RUNTIME_LOCATION=`cygwinToWindowsPath "${APP_RUNTIME_LOCATION}"` fi #Append Application-specific -D Java options to JAVA_OPTIONS. JAVA_OPTIONS="${JAVA_OPTIONS} -Dpies.appHome=\"${APP_HOME}\"" JAVA_OPTIONS="${JAVA_OPTIONS} -Dpies.logsLocation=\"${APP_LOGS_LOCATION}\"" JAVA_OPTIONS="${JAVA_OPTIONS} -Dpies.configsLocation=\"${APP_CONFIGS_LOCATION}\"" JAVA_OPTIONS="${JAVA_OPTIONS} -Dpies.runtimeLocation=\"${APP_RUNTIME_LOCATION}\"" JAVA_OPTIONS="${JAVA_OPTIONS} -Dpies.consoleCharset=\"${JAVA_CONSOLE_CHARSET}\"" #Output environment variables. log "Environment:" log " OPERATING_SYSTEM_TYPE = ${OPERATING_SYSTEM_TYPE}" log " FILE_PATH_SEPARATOR = ${FILE_PATH_SEPARATOR}" log " JAVA_EXECUTABLE = ${JAVA_EXECUTABLE}" log " JAVA_OPTIONS = ${JAVA_OPTIONS}" log " JAVA_CLASSPATH = ${JAVA_CLASSPATH}" log " JAVA_CONSOLE_CHARSET = ${JAVA_CONSOLE_CHARSET}" log " JAVA_CONSOLE_LOG_HISTORY = ${JAVA_CONSOLE_LOG_HISTORY}" log " JAVA_CONSOLE_LOG = ${JAVA_CONSOLE_LOG}" log " APP_HOME = ${APP_HOME}" log " APP_LOGS_LOCATION = ${APP_LOGS_LOCATION}" log " APP_CONFIGS_LOCATION = ${APP_CONFIGS_LOCATION}" log " APP_RUNTIME_LOCATION = ${APP_RUNTIME_LOCATION}" log " APP_MAIN_CLASS = ${APP_MAIN_CLASS}" log "" #Check that APP_LOCK_FILE doesn't exist. #This is just a auxiliary check, because Application performs the same check. if [ -e "${APP_LOCK_FILE}" ] then echoError "Application can't be started because Lock File ${APP_LOCK_FILE} exists" exitError fi #Deal with JAVA_CONSOLE_LOG_FILE. log "Log files:" if [ -e "${JAVA_CONSOLE_LOG_FILE}" ] then #Backup log file if necessary. if [ "${JAVA_CONSOLE_LOG_HISTORY}" == "true" ] then JAVA_CONSOLE_LOG_FILE_BACKUP=`backupFile "${JAVA_CONSOLE_LOG_FILE}"` log " File ${JAVA_CONSOLE_LOG_FILE} is moved to ${JAVA_CONSOLE_LOG_FILE_BACKUP}" createFile "${JAVA_CONSOLE_LOG_FILE}" log " File ${JAVA_CONSOLE_LOG_FILE} is created" else log " Console log history is disabled" fi else createFile "${JAVA_CONSOLE_LOG_FILE}" log " File ${JAVA_CONSOLE_LOG_FILE} is created" fi log "" #Start the application. log \ "Starting the Application by executing the following command:" START_COMMAND="nohup \ \"${JAVA_EXECUTABLE}\" \ ${JAVA_OPTIONS} \ -cp \"${JAVA_CLASSPATH}\" \ ${APP_MAIN_CLASS} \ &>\"${JAVA_CONSOLE_LOG_FILE}\" &" log " ${START_COMMAND}" eval "${START_COMMAND}" readonly JAVA_PID="${!}" log "" #Write APP_PID_FILE createFile "${APP_PID_FILE}" echo "${JAVA_PID}" > "${APP_PID_FILE}" log "PID of the Java process is ${JAVA_PID}"<file_sep>/pies-base/pies-base-constant/src/main/java/com/gl/vn/me/ko/pies/base/constant/Constant.java package com.gl.vn.me.ko.pies.base.constant; import java.nio.charset.Charset; import java.nio.charset.StandardCharsets; import java.util.Locale; /** * Provides Application-wide constants such as {@link java.nio.charset.Charset}, {@link java.util.Locale} and so on. */ public final class Constant { /** * {@link Locale} that SHOULD be used to represent all not user-specific data. * <p> * Value of this constant is {@link Locale#ROOT}. */ public static final Locale LOCALE = Locale.ROOT; /** * {@link Charset} that should be used unless some external things enforce usage of other {@link Charset}. * <p> * Value of this constant is {@link StandardCharsets#UTF_8}. */ public static final Charset CHARSET = StandardCharsets.UTF_8; /** * Represents Java process exit status (aka return code) that corresponds to successful execution. * <p> * Value of this constant is {@value}. */ public static final int EXIT_STATUS_SUCCESS = 0; /** * Represents Java process exit status (aka return code) that corresponds to unsuccessful execution. * <p> * Value of this constant is {@value}. */ public static final int EXIT_STATUS_ERROR = 1; private Constant() { throw new UnsupportedOperationException(Message.INSTANTIATION_NOT_SUPPORTED); } } <file_sep>/misc/manual test/shutdown.sh curl http://localhost:5201/shutdown/ -XPUT -s -S --connect-timeout 1 --max-time 5 echo "" curl http://localhost:5202/shutdown/ -XPUT -s -S --connect-timeout 1 --max-time 5 echo "" curl http://localhost:5203/shutdown/ -XPUT -s -S --connect-timeout 1 --max-time 5 echo "" <file_sep>/pies-base/pies-base-main/src/main/java/com/gl/vn/me/ko/pies/base/di/GuiceModuleNotFoundException.java package com.gl.vn.me.ko.pies.base.di; import com.gl.vn.me.ko.pies.base.throwable.ApplicationException; import javax.annotation.Nullable; /** * Indicates that lookup of a {@link GuiceModule} is failed. */ public final class GuiceModuleNotFoundException extends ApplicationException { private static final long serialVersionUID = 0; /** * Creates an instance of {@link GuiceModuleNotFoundException}. */ public GuiceModuleNotFoundException() { } /** * Creates an instance of {@link GuiceModuleNotFoundException}. * * @param message * The detail message which is saved for later retrieval by the {@link #getMessage()} method. */ public GuiceModuleNotFoundException(@Nullable final String message) { super(message); } /** * Creates an instance of {@link GuiceModuleNotFoundException}. * * @param message * The detail message which is saved for later retrieval by the {@link #getMessage()} method. * @param cause * The cause which is saved for later retrieval by the {@link #getCause()} method. */ public GuiceModuleNotFoundException(@Nullable final String message, @Nullable final Throwable cause) { super(message, cause); } /** * Creates an instance of {@link GuiceModuleNotFoundException}. * * @param cause * The cause which is saved for later retrieval by the {@link #getCause()} method. */ public GuiceModuleNotFoundException(@Nullable final Throwable cause) { super(cause); } } <file_sep>/pies-base/pies-base-config/src/main/java/com/gl/vn/me/ko/pies/base/config/package-info.java /** * Contains general API to work with configurations. */ @com.gl.vn.me.ko.pies.base.doc.Defaults @javax.annotation.ParametersAreNonnullByDefault package com.gl.vn.me.ko.pies.base.config; <file_sep>/pies-base/pies-base-main/src/harness/environment.sh #!/bin/bash #This file aggregates variables and constants that MAY be useful for the Administrator. # #One MAY use variable APP_HOME in order to refer to Application Home. #One SHOULD use getOperatingSystemType() function to obtain value of OPERATING_SYSTEM_TYPE. #One SHOULD use getFilePathSeparator() function to obtain value of FILE_PATH_SEPARATOR. # #Due to the fact that Harness scripts can be executed not only in UN*X shell, but also in Windows Cygwin shell, #we need to distinguish shell-specific path and OS-specific path. Shell-specific path is always a UN*X path, #but OS-specific path is UN*X for UN*X shell and Windows for Windows Cygwin shell. #You are allowed to always specify OS-specific path variables in UN*X style, #and Harness will convert the path to OS-specific value for you. #OS-specific variables that are processed by Harness are marked with "#Auto-OS-specific" comment. #If you use a value of OS-specific variable X in some other shell-specific variable Y, #then Harness will not harm Y and it's value will be shell-specific. #Application Home #By default in this script APP_HOME is a parent of the directory which contains Harness start.sh script, #but you MAY specify any path you need. #Auto-OS-specific APP_HOME="${APP_HOME}" #Specifies if logging is enabled in Harness scripts that use environment.sh. #Possible values: # "true" # "false" readonly VERBOSE="true" #Operating system type that includes knowledge about OS and shell. #If by some reason function getOperatingSystemType() fails to correctly determine execution environment the value #MAY be set manually. #Possible values: # "Windows-Cygwin" # "UN*X" readonly OPERATING_SYSTEM_TYPE=`getOperatingSystemType` #A character that separates elements in a list of file paths. #Value is based on the value of OPERATING_SYSTEM_TYPE variable. #If by some reason function getFilePathSeparator() fails to correctly determine execution environment the value #MAY be set manually. readonly FILE_PATH_SEPARATOR=`getFilePathSeparator` #A path to Java executable file. readonly JAVA_EXECUTABLE="java" #Java options. Note that PIES Application-specific -D Java options are configured in separate variables. JAVA_OPTIONS="${JAVA_OPTIONS} -server" JAVA_OPTIONS="${JAVA_OPTIONS} -d64" ##EOL marker that will be used by JRE. This is a standard Java option. ##Particularly this EOL marker will be used for standard output and error streams and for Application logs. ##You MAY comment out this option in order to use OS-specific EOL marker. For example: ## \r\n (Unicode code points U+000DU+000A) for Windows ## \n (Unicode code point U+000A) for UN*X JAVA_OPTIONS="${JAVA_OPTIONS} -Dline.separator=$'\n'" ##Oracle HotSpot JVM: memory options. #JAVA_OPTIONS="${JAVA_OPTIONS} -Xms64M" #JAVA_OPTIONS="${JAVA_OPTIONS} -Xmx64M" ##Oracle HotSpot JVM: debugging options. #JAVA_OPTIONS="${JAVA_OPTIONS} -Xdebug -Xrunjdwp:server=y,transport=dt_socket,address=4000,suspend=n" ##Oracle HotSpot JVM: JMX server options. #JAVA_OPTIONS="${JAVA_OPTIONS} -Dcom.sun.management.jmxremote.port=3000" #JAVA_OPTIONS="${JAVA_OPTIONS} -Dcom.sun.management.jmxremote.ssl=false" #JAVA_OPTIONS="${JAVA_OPTIONS} -Dcom.sun.management.jmxremote.authenticate=false" ##Oracle HotSpot JVM: allow Java Mission Control profiling. #JAVA_OPTIONS="${JAVA_OPTIONS} -XX:+UnlockCommercialFeatures -XX:+FlightRecorder" #Class path for Java executable. #Note that Java require this to be an OS-specific path, and Harness do the job for you. #Auto-OS-specific JAVA_CLASSPATH="" JAVA_CLASSPATH="${JAVA_CLASSPATH}${FILE_PATH_SEPARATOR}${APP_HOME}/lib-pies/*" JAVA_CLASSPATH="${JAVA_CLASSPATH}${FILE_PATH_SEPARATOR}${APP_HOME}/lib-3rdparty/*" #Name of the file where to write standard output and error streams of the Java process. #Only name without path parts MUST be specified. readonly JAVA_CONSOLE_LOG="console.log" #Name of a charset to use for the standard output and error streams (that is for JAVA_CONSOLE_LOG file). #Refer to IANA Charset Registry (http://www.iana.org/assignments/character-sets/character-sets.xhtml) #for all theoretically possible values. #Java option -Dfile.encoding is not used because it doesn't seem to be a standard property #according to specification of the method java.lang.System.getProperties() readonly JAVA_CONSOLE_CHARSET="UTF-8" #Specifies if file specified by variable JAVA_CONSOLE_LOG need to be renamed at Application startup #so that it will remain for history. #The renamed file contains current date in the format year-month-day_hour-minute-second_timeZone. #Possible values are: # "true" # "false" readonly JAVA_CONSOLE_LOG_HISTORY="true" #Logs Location - directory that by default contains all Application's log files, #such as JAVA_CONSOLE_LOG_NAME (location of other logs MAY be changed via log4j2.xml located in APP_CONFIGS_LOCATION). #Auto-OS-specific APP_LOGS_LOCATION="${APP_HOME}/log" #Configs Location - directory that contains all Application's configuration files. #Auto-OS-specific APP_CONFIGS_LOCATION="${APP_HOME}/config" #Runtime Files Location - directory that contains all Application's files that are relevant to running Application, #such as APP_PID_FILE_NAME and APP_LOCK_FILE_NAME files. #Auto-OS-specific APP_RUNTIME_LOCATION="${APP_HOME}/runtime"<file_sep>/pies-app/pies-app-echo/pies-app-echo-logic/pom.xml <?xml version="1.0" encoding="UTF-8"?> <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"> <description> Contains Application logic for PIES Echo Application. </description> <modelVersion>4.0.0</modelVersion> <artifactId>pies-app-echo-logic</artifactId> <packaging>jar</packaging> <name>pies-app-echo-logic</name> <url>${pies.project.url}</url> <licenses> <license> <name>${pies.project.license.name}</name> <url>${pies.project.license.url}</url> </license> </licenses> <inceptionYear>${pies.project.inceptionYear}</inceptionYear> <organization> <name>${pies.project.organization.name}</name> <url>${pies.project.organization.url}</url> </organization> <parent> <groupId>com.gl.vn.me.ko.pies</groupId> <artifactId>pies-app-echo-parent</artifactId> <version>0.0.0-SNAPSHOT</version> <relativePath>../pies-app-echo-parent/pom.xml</relativePath> </parent> <dependencies> <dependency> <groupId>com.google.code.findbugs</groupId> <artifactId>jsr305</artifactId> </dependency> <dependency> <groupId>io.netty</groupId> <artifactId>netty-all</artifactId> </dependency> <dependency> <groupId>com.google.inject</groupId> <artifactId>guice</artifactId> </dependency> <dependency> <groupId>javax.inject</groupId> <artifactId>javax.inject</artifactId> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-api</artifactId> </dependency> <dependency> <groupId>javax.json</groupId> <artifactId>javax.json-api</artifactId> </dependency> <dependency> <groupId>com.google.code.findbugs</groupId> <artifactId>annotations</artifactId> </dependency> <dependency> <groupId>com.gl.vn.me.ko.pies</groupId> <artifactId>pies-base-main</artifactId> </dependency> <dependency> <groupId>com.gl.vn.me.ko.pies</groupId> <artifactId>pies-base-doc</artifactId> </dependency> <dependency> <groupId>com.gl.vn.me.ko.pies</groupId> <artifactId>pies-platform-app</artifactId> </dependency> <dependency> <groupId>com.gl.vn.me.ko.pies</groupId> <artifactId>pies-platform-server</artifactId> </dependency> <dependency><!-- implementation of javax.json:javax.json-api --> <groupId>org.glassfish</groupId> <artifactId>javax.json</artifactId> <scope>runtime</scope> </dependency> <dependency><!-- is used by io.netty:netty-all --> <groupId>org.javassist</groupId> <artifactId>javassist</artifactId> <scope>runtime</scope> </dependency> </dependencies> <build> <resources> <resource> <directory>src/main/resources/services</directory> <targetPath>META-INF/services</targetPath> </resource> </resources> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-antrun-plugin</artifactId> <executions> <execution> <id>prepare-harness-artifact</id> <phase>package</phase> <configuration> <target> <zip destfile="${pies.attachedArtifactFile.config}"> <fileset dir="src/config"/> </zip> </target> </configuration> <goals> <goal>run</goal> </goals> </execution> </executions> </plugin> <plugin> <groupId>org.codehaus.mojo</groupId> <artifactId>build-helper-maven-plugin</artifactId> <executions> <execution> <id>attach-harness-artifact</id> <phase>package</phase> <goals> <goal>attach-artifact</goal> </goals> <configuration> <artifacts> <artifact> <file>${pies.attachedArtifactFile.config}</file> <type>zip</type> <classifier>${pies.classifier.config}</classifier> </artifact> </artifacts> </configuration> </execution> </executions> </plugin> </plugins> </build> </project><file_sep>/pies-platform/pies-platform-app/src/harness/shutdown.sh #!/bin/bash #This script MAY be used to shutdown the Application. #This script MAY return -1 in if execution of function from functions.sh failed. #Directory that contains this script. readonly THIS_SCRIPT_DIRNAME=`cd "$(dirname "${0}")"; pwd` #Application Home directory. APP_HOME=`dirname "${THIS_SCRIPT_DIRNAME}"` source "${THIS_SCRIPT_DIRNAME}/functions.sh" source "${THIS_SCRIPT_DIRNAME}/environment.sh" #Lock File - a file used to prevent repeated start of the same instance of Application. readonly APP_LOCK_FILE="${APP_RUNTIME_LOCATION}/application.lock" readonly APP_LOCK_FILE_LAST_MODIFICATION_DATE=`getLastModifyTime "${APP_LOCK_FILE}"` #Check that APP_LOCK_FILE exists. if ! [ -e "${APP_LOCK_FILE}" ] then echoError "Can't shutdown Application because it's not working: Lock File ${APP_LOCK_FILE} doesn't exist" exitError fi #Control Server address. CONTROL_SERVER_ADDRESS=`cat "${APP_LOCK_FILE}"` #Shutdown the application. log \ "Shutting down the Application by executing the following command:" SHUTDOWN_COMMAND="curl \ http://${CONTROL_SERVER_ADDRESS}/shutdown/ -XPUT \ -s -S --connect-timeout 1 --max-time 5" log " ${SHUTDOWN_COMMAND}" SHUTDOWN_RESPONSE=`eval "${SHUTDOWN_COMMAND}"` SHUTDOWN_STATUS="${?}" log "" if [ "${SHUTDOWN_STATUS}" == "0" ] #last process is completed successfully, i.e. with exit status 0 then log "Control Server response:" log " ${SHUTDOWN_RESPONSE}" log "" fi #Wait till Lock File will be deleted. while : ; do #Break is Lock File doesn't exist. ! [[ -f ${APP_LOCK_FILE} ]] && break #Break if Lock File was modified. We assume, that in this case Lock File was removed and recreated #because Application has stopped and was started again. if ! [ "${APP_LOCK_FILE_LAST_MODIFICATION_DATE}" == `getLastModifyTime "${APP_LOCK_FILE}"` ] then break fi log "Waiting for shutdown completion..." sleep 1 done<file_sep>/pies-platform/pies-platform-app/src/main/java/com/gl/vn/me/ko/pies/platform/app/CommonApp.java package com.gl.vn.me.ko.pies.platform.app; import com.gl.vn.me.ko.pies.base.config.app.ApplicationConfig; import com.gl.vn.me.ko.pies.base.constant.Message; import com.gl.vn.me.ko.pies.base.main.App; import com.gl.vn.me.ko.pies.base.main.LockFileWriter; import com.gl.vn.me.ko.pies.base.throwable.ApplicationError; import com.gl.vn.me.ko.pies.platform.server.rest.RestServerAddress; import com.google.inject.Injector; import com.google.inject.Key; import io.netty.util.ResourceLeakDetector; import io.netty.util.internal.logging.InternalLoggerFactory; import io.netty.util.internal.logging.Slf4JLoggerFactory; import java.net.InetSocketAddress; /** * Provides a common {@link App} logic for all Applications. * * @see App */ public abstract class CommonApp implements App { private static final String PROPERTY_NAME_NETTY_LEAK_DETECTION_LEVEL = "io.netty.leakDetectionLevel"; static { InternalLoggerFactory.setDefaultFactory(new Slf4JLoggerFactory()); } private final Injector injector; /** * Constructor of {@link CommonApp}. * * @param injector * An {@link Injector} that MUST be aware of the following: * <ul> * <li>{@literal @}{@link InetSocketAddress} {@link RestServerAddress} of a Control Server. * This Control Server MUST accept {@code "PUT /shutdown/"} HTTP requests and MUST react on such request * by shutting down the Application which it controls. * </ul> */ protected CommonApp(final Injector injector) { this.injector = injector; {//write Control Server address to the Lock File in the form of host:port final InetSocketAddress controlServerAddress = injector.getInstance(Key.get(InetSocketAddress.class, RestServerAddress.class)); final LockFileWriter lockFileWriter = injector.getInstance(LockFileWriter.class); lockFileWriter.write(controlServerAddress.getHostName() + ":" + controlServerAddress.getPort()); } {//process Application stage final ResourceLeakDetector.Level nettyLeakDetectionLevel; switch (getConfig().getStage()) { case DEVELOPMENT: { nettyLeakDetectionLevel = ResourceLeakDetector.Level.PARANOID; break; } case PRODUCTION: { nettyLeakDetectionLevel = ResourceLeakDetector.Level.SIMPLE; break; } default: { throw new ApplicationError(Message.CAN_NEVER_HAPPEN); } } /* * ResourceLeakDetector.setLevel(nettyLeakDetectionLevel) isn't used * because in this case Netty logs incorrect leak detection level. */ System.setProperty(PROPERTY_NAME_NETTY_LEAK_DETECTION_LEVEL, nettyLeakDetectionLevel.toString()); } } /** * Returns the {@link Injector} specified to construct this {@link CommonApp}. * * @return * The {@link Injector} specified to construct this {@link CommonApp}. */ protected final Injector getInjector() { return injector; } /** * Returns the {@link ApplicationConfig}. * * @return * The {@link ApplicationConfig}. */ protected final ApplicationConfig getConfig() { final ApplicationConfig cfg = injector.getInstance(ApplicationConfig.class); return cfg; } } <file_sep>/pies-base/pies-base-main/src/main/java/com/gl/vn/me/ko/pies/base/main/GuiceLocator.java package com.gl.vn.me.ko.pies.base.main; import static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.base.Preconditions.checkState; import com.gl.vn.me.ko.pies.base.config.app.ApplicationConfig; import com.gl.vn.me.ko.pies.base.constant.Message; import com.gl.vn.me.ko.pies.base.di.GuiceModule; import com.gl.vn.me.ko.pies.base.di.GuiceModuleNotFoundException; import com.gl.vn.me.ko.pies.base.throwable.ApplicationError; import com.google.inject.AbstractModule; import com.google.inject.Guice; import com.google.inject.Injector; import com.google.inject.Stage; import java.util.Arrays; import java.util.HashSet; import java.util.ServiceConfigurationError; import java.util.ServiceLoader; import java.util.Set; import javax.annotation.Nullable; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Allows to conveniently locate published instances of {@link GuiceModule}. * <p> * {@link GuiceModule} respects {@link ApplicationConfig#getStage()} when creates instances of {@link Injector}. */ public final class GuiceLocator { private static final Logger LOGGER = LoggerFactory.getLogger(GuiceLocator.class); @Nullable private static volatile Stage stage = null; private static final class GuiceModuleLoaderInitializer { private static final Object GUICE_MODULE_LOCK = new Object(); private static final ServiceLoader<GuiceModule> GUICE_MODULE_LOADER = ServiceLoader.load(GuiceModule.class); } /** * Creates a new {@link Injector} by using the provided {@code modules}. * * @param modules * Required modules. * @return * {@link Injector} created by using the provided {@code modules}. */ public static final Injector createInjector(final AbstractModule... modules) { checkNotNull(modules); checkState(stage != null); final Injector result = Guice.createInjector(stage, modules); return result; } /** * Creates a new {@link Injector} by using modules specified via {@code names}. * * @param names * Names of the required modules. * @return * {@link Injector} created by using the requested instances of {@link GuiceModule}. * @throws GuiceModuleNotFoundException * If lookup of at least one requested {@link GuiceModule} is failed. */ public static final Injector createInjector(final String... names) throws GuiceModuleNotFoundException { checkNotNull(names); checkState(stage != null); final Injector result = Guice.createInjector(stage, getModules(names)); return result; } /** * Returns published instances of {@link GuiceModule} according to the requested {@code names}. * Multiple invocations of the method with the same modules requested will result to the same objects returned, i.e. * each {@link GuiceModule} is instantiated only once. * <p> * It's important that instances of {@link GuiceModule} are requested by name and not by class, because otherwise if * there are API and implementation JAR's, {@link GuiceModule} can only be published by code in implementation JAR * and requesting it by class would create a compile-time dependency on the implementation JAR. * * @param names * Names of the required modules. * @return * Requested modules. * @throws GuiceModuleNotFoundException * If lookup of at least one requested {@link GuiceModule} is failed. */ public static final Set<GuiceModule> getModules(final String... names) throws GuiceModuleNotFoundException { final Set<GuiceModule> result = new HashSet<>(); final Set<String> moduleNames = new HashSet<>(Arrays.asList(names)); final Set<GuiceModule> modules = new HashSet<>(); try { synchronized (GuiceModuleLoaderInitializer.GUICE_MODULE_LOCK) { for (final GuiceModule module : GuiceModuleLoaderInitializer.GUICE_MODULE_LOADER) { if (!moduleNames.isEmpty()) { modules.add(module); final String moduleName = module.getName(); if (moduleNames.contains(moduleName)) { result.add(module); moduleNames.remove(moduleName); } } else { break; } } } } catch (final ServiceConfigurationError e) { throw new GuiceModuleNotFoundException( Message.format("Can't load at least one module of: %s", moduleNames), e); } finally { if (LOGGER.isDebugEnabled()) { LOGGER.debug("The following Guice modules were requested by name: {}. " + "The following Guice modules were loaded: {}", Arrays.toString(names), modules); } } if (moduleNames.size() > 0) { throw new GuiceModuleNotFoundException( Message.format("The following modules wasn't found: %s", moduleNames)); } return result; } /** * Initializes {@link GuiceLocator}. * This method MUST be called by {@link Main} class * before the first invocation of {@link #createInjector(String...)}. * This method MUST be called only once. * * @param appStage * {@link Stage} that will be used by method {@link #createInjector(String...)}. */ static final void initialize(final com.gl.vn.me.ko.pies.base.config.app.Stage appStage) { checkNotNull(appStage); checkState(stage == null, "GuiceLocator was already initialized"); final Stage guiceStage; switch (appStage) { case DEVELOPMENT: { guiceStage = Stage.DEVELOPMENT; break; } case PRODUCTION: { guiceStage = Stage.PRODUCTION; break; } default: { throw new ApplicationError(Message.CAN_NEVER_HAPPEN); } } stage = guiceStage; if (stage == Stage.PRODUCTION) {//eager load guice modules synchronized (GuiceModuleLoaderInitializer.GUICE_MODULE_LOADER) { GuiceModuleLoaderInitializer.GUICE_MODULE_LOADER.forEach((guiceModule) -> { }); } } LOGGER.info("GuiceLocator initialized with stage {}", appStage); } private GuiceLocator() { throw new UnsupportedOperationException(Message.INSTANTIATION_NOT_SUPPORTED); } } <file_sep>/pies-platform/pies-platform-client/src/test/java/com/gl/vn/me/ko/pies/platform/client/tcp/TestTcpSequentialClient.java package com.gl.vn.me.ko.pies.platform.client.tcp; import static org.junit.Assert.assertEquals; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; import io.netty.channel.nio.NioEventLoopGroup; import io.netty.util.concurrent.Future; import java.net.InetSocketAddress; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.atomic.AtomicBoolean; import org.apache.commons.pool2.ObjectPool; import org.junit.Before; import org.junit.Test; import org.mockito.internal.util.reflection.Whitebox; public final class TestTcpSequentialClient { private NioEventLoopGroup workerEventLoopGroup; private ScheduledExecutorService scheduledExecutorService; @SuppressFBWarnings( value = "UWF_FIELD_NOT_INITIALIZED_IN_CONSTRUCTOR", justification = "The field is initialized in setUp() method") private TcpSequentialClient<byte[], byte[]> client; public TestTcpSequentialClient() { } @Before @SuppressWarnings("unchecked") public final void setUp() { final InetSocketAddress address = InetSocketAddress.createUnresolved("", 0); final Future<?> shutdownFuture = mock(Future.class); workerEventLoopGroup = mock(NioEventLoopGroup.class); when(workerEventLoopGroup.shutdownGracefully()).thenAnswer((invocation) -> { return (Future)shutdownFuture; }); scheduledExecutorService = mock(ScheduledExecutorService.class); final ObjectPool<TcpConnection<byte[], byte[]>> connectionPool = mock(ObjectPool.class); client = new TcpSequentialClient<>( address, workerEventLoopGroup, scheduledExecutorService, connectionPool); } @Test public final void shutdown() { client.shutdown(); verify(workerEventLoopGroup, times(1)).shutdownGracefully(); verify(scheduledExecutorService, times(1)).shutdown(); } @Test public final void shutdownIdempotence() { client.shutdown(); final boolean clientState1 = ((AtomicBoolean)Whitebox.getInternalState(client, "active")).get(); client.shutdown(); final boolean clientState2 = ((AtomicBoolean)Whitebox.getInternalState(client, "active")).get(); assertEquals("Assert that client states are equal", clientState1, clientState2); } @Test(expected = IllegalStateException.class) public final void sendAfterShutdown() { client.shutdown(); client.send(new TcpMessage<>(new byte[] {})); } } <file_sep>/pies-base/pies-base-feijoa/src/main/java/com/gl/vn/me/ko/pies/base/feijoa/StringableConverter.java package com.gl.vn.me.ko.pies.base.feijoa; /** * Implementation of this interface provides ability to restore object of type {@code T} from {@link String} that was * obtained via the method {@link Stringable#toString()}. * * @param <T> * Type which instances can be restored from {@link String} by this {@link StringableConverter}. * @see Stringable */ public interface StringableConverter<T extends Stringable> { /** * Restores object of type {@code T} from the provided {@code stringValue}. * * @param stringValue * A {@link String} returned from {@code T.}{@link Stringable#toString() toString()} method. * @return * Object of type {@code T} such that the following assertion succeeds: * <pre>{@code * MyClass originalObject = ...;// implements Stringable * MyConverter c = ...;// implements StringableConverter<MyClass> * MyClass restoredObject = c.valueOf(originalObject.toString()); * assert originalObject.equals(restoredObject); * }</pre> * * @throws StringableConvertationException * If conversion failed. */ T valueOf(String stringValue) throws StringableConvertationException; } <file_sep>/pies-base/pies-base-main/src/main/java/com/gl/vn/me/ko/pies/base/main/App.java package com.gl.vn.me.ko.pies.base.main; import java.util.ServiceLoader; import javax.inject.Singleton; /** * Represents refined Application logic, that is logic without processing of command-line arguments and some other routines that * need to be done before the pure Application logic can be executed. * <p> * Implementation of this interface is located by the {@link Main} class via {@link ServiceLoader}, and therefore implementation * of the {@link App} MUST be public, MUST have a public constructor without parameters, and a provider-configuration file MUST be * available as specified in the {@link ServiceLoader} documentation. There MUST be exactly one published implementation of * {@link App}. The described constructor MUST NOT be called directly by any Application code. * <p> * The {@link Main} class will invoke method {@link App#run()} on the object constructed via the mentioned constructor. * Note that there is a guarantee that only one instance of the class that implements {@link App} will be created * and the {@link App#run()} method will be called only once. * <p> * Implementation example: * <pre><code> * public final class HelloWorld implements App { * private static final Logger LOGGER = LoggerFactory.getLogger(HelloWorld.class); * * private final ApplicationConfig applicationConfig; * * public HelloWorld() { * final Injector injector = GuiceLocator.createInjector("com.gl.vn.me.ko.pies.base.main"); * applicationConfig = injector.getInstance(ApplicationConfig.class); * } * * {@literal @}Override * public final void run() { * LOGGER.info("Hello World! I'm running in the {} stage", applicationConfig.getStage()); * } * } * </code></pre> * * @see Main#main(String[]) */ @Singleton public interface App extends Runnable { /** * Method that contains Application logic. This method is invoked by the {@link Main} class. After return from this method JVM * will be shut down by using {@link System#exit(int)} method, so if there are any threads started by the method (including * those started indirectly) that require graceful shutdown, the method SHOULD take care of them. */ @Override void run(); } <file_sep>/pies-base/pies-base-main/src/main/java/com/gl/vn/me/ko/pies/base/main/JavaOption.java package com.gl.vn.me.ko.pies.base.main; import static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.base.Preconditions.checkState; import com.gl.vn.me.ko.pies.base.config.PropertyName; import com.gl.vn.me.ko.pies.base.constant.Message; import com.gl.vn.me.ko.pies.base.throwable.ApplicationException; import java.nio.charset.Charset; import javax.annotation.Nullable; import javax.annotation.concurrent.Immutable; /** * Provides a convenient way to access {@code -D} Java options that are needed by {@link Main} class. * <p> * Option MUST be considered mandatory unless otherwise is specified. */ final class JavaOption { /** * Represents names of {@code -D} Java options that are presented as system properties at runtime. * * @see System#getProperty(String) */ @Immutable static enum JavaOptionName implements PropertyName { /** * Specifies Configs Location. * <p> * Denotes option {@code -Dpies.configsLocation}, which name is {@code "pies.configsLocation"}. */ CONFIGS_LOCATION("pies.configsLocation"), /** * Specifies Runtime Location. * <p> * Denotes option {@code -Dpies.runtimeLocation}, which name is {@code "pies.runtimeLocation"}. */ RUNTIME_LOCATION("pies.runtimeLocation"), /** * Name of a {@link Charset} to use for the {@link System#out} and {@link System#err} streams. * <p> * Denotes option {@code -Dpies.consoleCharset}, which name is {@code "pies.consoleCharset"}. */ CONSOLE_CHARSET("pies.consoleCharset"); private final String name; private JavaOptionName(final String name) { this.name = name; } @Override public final String toString() { return name; } } /** * Indicates that the {@code -D} Java option isn't specified. */ static final class JavaOptionUnspecifiedException extends ApplicationException { private static final long serialVersionUID = 0; /** * Creates an instance of {@link JavaOptionUnspecifiedException}. */ private JavaOptionUnspecifiedException() { } /** * Creates an instance of {@link JavaOptionUnspecifiedException}. * * @param message * The detail message which is saved for later retrieval by the {@link #getMessage()} method. */ private JavaOptionUnspecifiedException(@Nullable final String message) { super(message); } /** * Creates an instance of {@link JavaOptionUnspecifiedException}. * * @param message * The detail message which is saved for later retrieval by the {@link #getMessage()} method. * @param cause * The cause which is saved for later retrieval by the {@link #getCause()} method. */ private JavaOptionUnspecifiedException(@Nullable final String message, @Nullable final Throwable cause) { super(message, cause); } /** * Creates an instance of {@link JavaOptionUnspecifiedException}. * * @param cause * The cause which is saved for later retrieval by the {@link #getCause()} method. */ private JavaOptionUnspecifiedException(@Nullable final Throwable cause) { super(cause); } } private static boolean cleared = false; private static final Object MUTEX = new Object(); /** * Clears Java system properties that represent {@code -D} Java options specified by {@link JavaOptionName}. * This method MUST be called by {@link Main} class once these properties become useless. */ static final void clear() { synchronized (MUTEX) { cleared = true; for (final JavaOptionName javaOptionName : JavaOptionName.values()) { System.setProperty(javaOptionName.toString(), ""); } } } /** * Reads value of the Java option specified by {@code optionName} and checks that the value is not {@code null}, * that is the option is set. * * @param optionName * Name of {@code -D} Java option to read. * @return * Value of the Java option specified by {@code optionName} if the option is set. * @throws JavaOptionUnspecifiedException * If the Java option specified by {@code optionName} isn't set. */ static final String getValue(final JavaOptionName optionName) throws JavaOptionUnspecifiedException { checkNotNull(optionName, Message.ARGUMENT_NULL_SINGLE, "optionName"); final String result; synchronized (MUTEX) { checkState(!cleared, "Can't get value because options were cleared"); @Nullable final String optionValue = System.getProperty(optionName.toString()); if (optionValue == null) { throw new JavaOptionUnspecifiedException(Message.format( "-D Java option %s is not specified", optionName)); } else { result = optionValue; } } return result; } private JavaOption() { throw new UnsupportedOperationException(Message.OPERATION_NOT_SUPPORTED); } } <file_sep>/pies-app/pies-app-proxy/pies-app-proxy-logic/src/main/java/com/gl/vn/me/ko/pies/app/proxy/ProxyApplication.java package com.gl.vn.me.ko.pies.app.proxy; import com.gl.vn.me.ko.pies.base.main.App; import com.gl.vn.me.ko.pies.base.main.GuiceLocator; import com.gl.vn.me.ko.pies.platform.app.CommonApp; import com.gl.vn.me.ko.pies.platform.server.Server; import com.gl.vn.me.ko.pies.platform.server.rest.JsonRestServer; import com.gl.vn.me.ko.pies.platform.server.tcp.TcpReverseProxyServer; import com.google.inject.Injector; import io.netty.util.concurrent.Future; import javax.inject.Singleton; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Implementation of PIES Proxy Application. */ @Singleton public final class ProxyApplication extends CommonApp { private static final Logger LOGGER = LoggerFactory.getLogger(ProxyApplication.class); /** * Constructor required according to the specification of {@link App}. * This constructor MUST NOT be called directly by any Application code. */ public ProxyApplication() { super(GuiceLocator.createInjector(ProxyModule.getInstance())); } /** * Creates and starts Proxy and Control Servers. */ @Override public final void run() { final Injector injector = getInjector(); final Server proxyServer = injector.getInstance(TcpReverseProxyServer.class); try { final Future<?> proxyServerCompletion = proxyServer.start(); final Server controlServer = injector.getInstance(JsonRestServer.class); try { final Future<?> controlServerCompletion = controlServer.start(); controlServerCompletion.await(); } catch (final InterruptedException e) { LOGGER.info("Interrupt was detected. {} will shut down", controlServer); Thread.currentThread().interrupt(); } finally { controlServer.shutdown(); Thread.currentThread().interrupt(); } proxyServerCompletion.await(); } catch (final InterruptedException e) { LOGGER.info("Interrupt was detected. {} will shut down", proxyServer); Thread.currentThread().interrupt(); } finally { proxyServer.shutdown(); } } } <file_sep>/pies-base/pies-base-throwable/src/main/java/com/gl/vn/me/ko/pies/base/throwable/TimeoutException.java package com.gl.vn.me.ko.pies.base.throwable; import javax.annotation.Nullable; /** * Indicates that some action wasn't completed due to timeout. */ public final class TimeoutException extends ExternallyVisibleException { private static final long serialVersionUID = 0; /** * Creates an instance of {@link TimeoutException}. * * @param externalMessage * Message that MAY be made visible to a client of an Application. */ public TimeoutException(final String externalMessage) { super(externalMessage); } /** * Creates an instance of {@link TimeoutException}. * * @param message * The detail message which is saved for later retrieval by the {@link #getMessage()} method. * @param externalMessage * Message that MAY be made visible to a client of an Application. */ public TimeoutException(@Nullable final String message, final String externalMessage) { super(message, externalMessage); } /** * Creates an instance of {@link TimeoutException}. * * @param message * The detail message which is saved for later retrieval by the {@link #getMessage()} method. * @param cause * The cause which is saved for later retrieval by the {@link #getCause()} method. * @param externalMessage * Message that MAY be made visible to a client of an Application. */ public TimeoutException( @Nullable final String message, @Nullable final Throwable cause, final String externalMessage) { super(message, cause, externalMessage); } /** * Creates an instance of {@link TimeoutException}. * * @param externalMessage * Message that MAY be made visible to a client of an Application. * @param cause * The cause which is saved for later retrieval by the {@link #getCause()} method. */ public TimeoutException(final String externalMessage, @Nullable final Throwable cause) { super(externalMessage, cause); } } <file_sep>/pies-app/pies-app-initiator/pies-app-initiator-logic/src/main/java/com/gl/vn/me/ko/pies/app/initiator/InitiatorModule.java package com.gl.vn.me.ko.pies.app.initiator; import static com.gl.vn.me.ko.pies.base.constant.Message.GUICE_POTENTIALLY_SWALLOWED; import static java.net.InetAddress.getByName; import com.gl.vn.me.ko.pies.base.config.PropsConfig; import com.gl.vn.me.ko.pies.base.config.app.ConfigLocator; import com.gl.vn.me.ko.pies.base.main.GuiceLocator; import com.gl.vn.me.ko.pies.base.throwable.ApplicationException; import com.gl.vn.me.ko.pies.platform.client.tcp.TcpChannelInitializer; import com.gl.vn.me.ko.pies.platform.client.tcp.TcpSequentialClient; import com.gl.vn.me.ko.pies.platform.client.tcp.TcpSequentialClientAddress; import com.gl.vn.me.ko.pies.platform.client.tcp.TcpSequentialClientConnectTimeout; import com.gl.vn.me.ko.pies.platform.client.tcp.TcpSequentialClientName; import com.gl.vn.me.ko.pies.platform.client.tcp.TcpSequentialClientThreadFactory; import com.gl.vn.me.ko.pies.platform.client.tcp.TcpSequentialClientWorker; import com.gl.vn.me.ko.pies.platform.server.rest.JsonRestRequestHandlerResult; import com.gl.vn.me.ko.pies.platform.server.rest.JsonRestServer; import com.gl.vn.me.ko.pies.platform.server.rest.RestRequestHandler; import com.gl.vn.me.ko.pies.platform.server.rest.RestServerAddress; import com.gl.vn.me.ko.pies.platform.server.rest.RestServerBoss; import com.gl.vn.me.ko.pies.platform.server.rest.RestServerName; import com.gl.vn.me.ko.pies.platform.server.rest.RestServerRequestHandling; import com.gl.vn.me.ko.pies.platform.server.rest.RestServerThreadFactory; import com.gl.vn.me.ko.pies.platform.server.rest.RestServerWorker; import com.google.common.collect.ImmutableList; import com.google.inject.AbstractModule; import com.google.inject.Provider; import com.google.inject.Provides; import com.google.inject.TypeLiteral; import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; import io.netty.channel.ChannelHandler; import io.netty.channel.ChannelInitializer; import io.netty.channel.ChannelPipeline; import io.netty.channel.socket.ServerSocketChannel; import io.netty.handler.logging.LogLevel; import io.netty.handler.logging.LoggingHandler; import java.net.InetAddress; import java.net.InetSocketAddress; import java.net.UnknownHostException; import java.util.Collection; import java.util.Optional; import java.util.concurrent.ThreadFactory; import javax.annotation.Nullable; import javax.inject.Singleton; import javax.json.Json; import javax.json.JsonBuilderFactory; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * {@link AbstractModule} that SHOULD be used throughout PIES Initiator Application. */ final class InitiatorModule extends AbstractModule { private static final Logger LOGGER = LoggerFactory.getLogger(InitiatorModule.class); private static final InitiatorModule INSTANCE = new InitiatorModule(); private static final String[] DEPENDENCIES = new String[] { "com.gl.vn.me.ko.pies.base.main", "com.gl.vn.me.ko.pies.base.thread"}; /** * Name of the file that specifies Initiator Config. */ private static final String CONFIG_FILE_NAME = "initiatorConfig.xml"; final static InitiatorModule getInstance() { return INSTANCE; } @SuppressFBWarnings(value = "UPM_UNCALLED_PRIVATE_METHOD", justification = "The method is called from configure() method, FindBugs just don't understand lambdas") private static final ChannelInitializer<ServerSocketChannel> createServerChannelInitializer() { final ChannelInitializer<ServerSocketChannel> result; try { result = new ChannelInitializer<ServerSocketChannel>() { @Override protected final void initChannel(final ServerSocketChannel channel) throws Exception { final ChannelPipeline pipeline = channel.pipeline(); final ChannelHandler channelHandler; if (LoggerFactory.getLogger(InitiatorApplication.class).isDebugEnabled()) { channelHandler = new LoggingHandler(LogLevel.DEBUG); } else { channelHandler = new LoggingHandler(LogLevel.INFO); } pipeline.addLast(channelHandler); } }; } catch (final RuntimeException e) { LOGGER.error(GUICE_POTENTIALLY_SWALLOWED, e); throw e; } return result; } private InitiatorModule() { } @SuppressFBWarnings(value = "SIC_INNER_SHOULD_BE_STATIC_ANON", justification = "It's more readable to use anonimous class for binding instead of a static one") @Override protected final void configure() { try { for (final AbstractModule module : GuiceLocator.getModules(DEPENDENCIES)) { install(module); } bind(JsonBuilderFactory.class).toInstance(Json.createBuilderFactory(null)); bind(String.class).annotatedWith(RestServerName.class).toInstance("Control Server"); bind(JsonRestServer.class).in(Singleton.class); bind(new TypeLiteral<ChannelInitializer<ServerSocketChannel>>() { }) .annotatedWith(RestServerBoss.class) .toProvider( (Provider<ChannelInitializer<ServerSocketChannel>>)InitiatorModule::createServerChannelInitializer) .in(Singleton.class); bind(new TypeLiteral<TcpSequentialClient<byte[], byte[]>>() { }). in(Singleton.class); bind(String.class).annotatedWith(TcpSequentialClientName.class).toInstance("Initiator Client"); bind(TcpChannelInitializer.class).annotatedWith(TcpSequentialClientWorker.class) .toInstance((channel) -> channel.pipeline().addFirst(new EchoCodec())); } catch (final RuntimeException e) { LOGGER.error(GUICE_POTENTIALLY_SWALLOWED, e); throw e; } } @Provides @Singleton @SuppressFBWarnings(value = "UPM_UNCALLED_PRIVATE_METHOD", justification = "This method is called by Guice framework") private final PropsConfig provideConfig(final ConfigLocator configLocator) { final PropsConfig result; try { result = configLocator.getXmlPropsConfig(CONFIG_FILE_NAME); InitiatorConfigPropertyName.validate(result, CONFIG_FILE_NAME); } catch (final RuntimeException e) { LOGGER.error(GUICE_POTENTIALLY_SWALLOWED, e); throw e; } return result; } @Provides @Singleton @RestServerAddress @SuppressFBWarnings(value = "UPM_UNCALLED_PRIVATE_METHOD", justification = "This method is called by Guice framework") private final InetSocketAddress provideControlSrvAddress(final PropsConfig cfg) { final InetSocketAddress result; try { final int port = cfg.getInteger(InitiatorConfigPropertyName.CONTROL_PORT).intValue(); final Optional<String> optHostPropertyValue = cfg.getString(InitiatorConfigPropertyName.CONTROL_HOST, null); final InetAddress host; try { host = optHostPropertyValue.isPresent() ? InetAddress.getByName(optHostPropertyValue.get()) : InetAddress.getLocalHost(); } catch (final UnknownHostException e) { throw new ApplicationException(e); } result = new InetSocketAddress(host, port); } catch (final RuntimeException e) { LOGGER.error(GUICE_POTENTIALLY_SWALLOWED, e); throw e; } return result; } @Provides @Singleton @RestServerBoss @SuppressFBWarnings(value = "UPM_UNCALLED_PRIVATE_METHOD", justification = "This method is called by Guice framework") private final Integer provideControlSrvMaxBossThreads(final PropsConfig cfg) { final Integer result; try { result = cfg.getInteger(InitiatorConfigPropertyName.CONTROL_ACCEPTORS); } catch (final RuntimeException e) { LOGGER.error(GUICE_POTENTIALLY_SWALLOWED, e); throw e; } return result; } @Provides @Singleton @RestServerRequestHandling @SuppressFBWarnings(value = "UPM_UNCALLED_PRIVATE_METHOD", justification = "This method is called by Guice framework") private final Integer provideControlSrvMaxDispatcherThreads(final PropsConfig cfg) { final Integer result; try { result = cfg.getInteger(InitiatorConfigPropertyName.CONTROL_POST_RESPONSE_WORKERS); } catch (final RuntimeException e) { LOGGER.error(GUICE_POTENTIALLY_SWALLOWED, e); throw e; } return result; } @Provides @Singleton @RestServerWorker @SuppressFBWarnings(value = "UPM_UNCALLED_PRIVATE_METHOD", justification = "This method is called by Guice framework") private final Integer provideControlSrvMaxWorkerThreads(final PropsConfig cfg) { final Integer result; try { result = cfg.getInteger(InitiatorConfigPropertyName.CONTROL_WORKERS); } catch (final RuntimeException e) { LOGGER.error(GUICE_POTENTIALLY_SWALLOWED, e); throw e; } return result; } @Provides @RestServerRequestHandling @Nullable @SuppressFBWarnings(value = "UPM_UNCALLED_PRIVATE_METHOD", justification = "This method is called by Guice framework") private final Collection<? extends RestRequestHandler<? extends JsonRestRequestHandlerResult>> provideControlSrvRestRequestHandlers(final PropsConfig cfg, final TcpSequentialClient<byte[], byte[]> echoClient, final JsonBuilderFactory jsonBuilderFactory) { final Collection<? extends RestRequestHandler<? extends JsonRestRequestHandlerResult>> result; try { final ImmutableList.Builder<RestRequestHandler<JsonRestRequestHandlerResult>> resultBuilder = ImmutableList.builder(); resultBuilder .add(new InitiatorShutdownRestRequestHandler(echoClient, jsonBuilderFactory)) .add(new EchoUtf8StringRestRequestHandler( echoClient, cfg.getBoolean(InitiatorConfigPropertyName.INITIATOR_CLIENT_VALIDATE_RESPONSE).booleanValue(), cfg.getLong(InitiatorConfigPropertyName.INITIATOR_CLIENT_IO_TIMEOUT_MILLIS).longValue(), jsonBuilderFactory)); result = resultBuilder.build(); } catch (final RuntimeException e) { LOGGER.error(GUICE_POTENTIALLY_SWALLOWED, e); throw e; } return result; } @Provides @RestServerThreadFactory @SuppressFBWarnings(value = "UPM_UNCALLED_PRIVATE_METHOD", justification = "This method is called by Guice framework") private final ThreadFactory provideControlSrvThreadFactory(final ThreadFactory threadFactory) { final ThreadFactory result; try { result = threadFactory; } catch (final RuntimeException e) { LOGGER.error(GUICE_POTENTIALLY_SWALLOWED, e); throw e; } return result; } @Provides @TcpSequentialClientAddress @Singleton @SuppressFBWarnings(value = "UPM_UNCALLED_PRIVATE_METHOD", justification = "This method is called by Guice framework") private final InetSocketAddress providEchoClientAddress(final PropsConfig cfg) { final InetSocketAddress result; try { final InetAddress host; try { host = getByName(cfg.getString(InitiatorConfigPropertyName.INITIATOR_CLIENT_HOST)); } catch (final UnknownHostException e) { throw new ApplicationException(e); } final int port = cfg.getInteger(InitiatorConfigPropertyName.INITIATOR_CLIENT_PORT).intValue(); result = new InetSocketAddress(host, port); } catch (final RuntimeException e) { LOGGER.error(GUICE_POTENTIALLY_SWALLOWED, e); throw e; } return result; } @Provides @TcpSequentialClientWorker @Singleton @SuppressFBWarnings(value = "UPM_UNCALLED_PRIVATE_METHOD", justification = "This method is called by Guice framework") private final Integer providEchoClientMaxWorkerThreads(final PropsConfig cfg) { final Integer result; try { result = cfg.getInteger(InitiatorConfigPropertyName.INITIATOR_CLIENT_WORKERS); } catch (final RuntimeException e) { LOGGER.error(GUICE_POTENTIALLY_SWALLOWED, e); throw e; } return result; } @Provides @TcpSequentialClientThreadFactory @SuppressFBWarnings(value = "UPM_UNCALLED_PRIVATE_METHOD", justification = "This method is called by Guice framework") private final ThreadFactory providEchoClientThreadFactory(final ThreadFactory threadFactory) { final ThreadFactory result; try { result = threadFactory; } catch (final RuntimeException e) { LOGGER.error(GUICE_POTENTIALLY_SWALLOWED, e); throw e; } return result; } @Provides @TcpSequentialClientConnectTimeout @Singleton @SuppressFBWarnings(value = "UPM_UNCALLED_PRIVATE_METHOD", justification = "This method is called by Guice framework") private final Integer providEchoClientConnectTimeoutMillis(final PropsConfig cfg) { final Integer result; try { result = cfg.getInteger(InitiatorConfigPropertyName.INITIATOR_CLIENT_IO_TIMEOUT_MILLIS); } catch (final RuntimeException e) { LOGGER.error(GUICE_POTENTIALLY_SWALLOWED, e); throw e; } return result; } } <file_sep>/pies-platform/pies-platform-parent/pom.xml <?xml version="1.0" encoding="UTF-8"?> <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"> <description></description> <modelVersion>4.0.0</modelVersion> <artifactId>pies-platform-parent</artifactId> <packaging>pom</packaging> <name>pies-platform-parent</name> <url>${pies.project.url}</url> <licenses> <license> <name>${pies.project.license.name}</name> <url>${pies.project.license.url}</url> </license> </licenses> <inceptionYear>${pies.project.inceptionYear}</inceptionYear> <organization> <name>${pies.project.organization.name}</name> <url>${pies.project.organization.url}</url> </organization> <parent> <groupId>com.gl.vn.me.ko.pies</groupId> <artifactId>pies-parent</artifactId> <version>0.0.0-SNAPSHOT</version> <relativePath>../../pies-parent/pom.xml</relativePath> </parent> </project><file_sep>/pies-platform/pies-platform-server/src/test/java/com/gl/vn/me/ko/pies/platform/server/rest/TestRestRequestDispatcher.java package com.gl.vn.me.ko.pies.platform.server.rest; import static org.junit.Assert.assertEquals; import static org.mockito.Mockito.mock; import com.gl.vn.me.ko.pies.platform.server.Server; import com.google.common.collect.ImmutableSet; import java.util.concurrent.CompletableFuture; import java.util.concurrent.CompletionStage; import java.util.concurrent.ExecutorService; import java.util.concurrent.atomic.AtomicBoolean; import org.junit.Test; import org.mockito.internal.util.reflection.Whitebox; public final class TestRestRequestDispatcher { private static final class Handler1 extends RestRequestHandler<Object> { private static final RestRequest BINDING = RestRequest.valueOf("GET /one/two/"); private static final Object VALUE = "header1Value_"; private Handler1() { super(BINDING); } @Override public final CompletionStage<Object> handleRequest(final RestRequest request, final ExecutorService executorService) { return CompletableFuture.completedFuture(VALUE.toString() + request.toRawString()); } } private static final class Handler2 extends RestRequestHandler<Object> { private static final RestRequest BINDING = RestRequest.valueOf("GET /one/two/thr%20ee/"); private static final Object VALUE = "header2Value_"; private Handler2() { super(BINDING); } @Override public final CompletionStage<Object> handleRequest(final RestRequest request, final ExecutorService executorService) { return CompletableFuture.completedFuture(VALUE.toString() + request.toRawString()); } } private static final class Handler3 extends RestRequestHandler<Object> { private static final RestRequest BINDING = RestRequest.valueOf("PUT /one/two/"); private static final Object VALUE = "header3Value_"; private Handler3() { super(BINDING); } @Override public final CompletionStage<Object> handleRequest(final RestRequest request, final ExecutorService executorService) { return CompletableFuture.completedFuture(VALUE.toString() + request.toRawString()); } } private static final class Handler4 extends RestRequestHandler<Object> { private static final RestRequest BINDING = RestRequest.valueOf("GET /one/two/thr/"); private static final Object VALUE = "header4Value_"; private Handler4() { super(BINDING); } @Override public final CompletionStage<Object> handleRequest(final RestRequest request, final ExecutorService executorService) { return CompletableFuture.completedFuture(VALUE.toString() + request.toRawString()); } } private static final class ShutdownHandler extends RestRequestHandler<Object> { private static final RestRequest BINDING = RestRequest.valueOf("GET /"); private int shutdownHookInvocationCount = 0; private ShutdownHandler() { super(BINDING); } @Override public final CompletionStage<Object> handleRequest(final RestRequest request, final ExecutorService executorService) { return CompletableFuture.completedFuture(""); } @Override protected final void shutdownHook() { shutdownHookInvocationCount++; } } public TestRestRequestDispatcher() { } private final RestRequestDispatcher<Object> newDispatcher() { return new RestRequestDispatcher<>( mock(Server.class), mock(ExecutorService.class), ImmutableSet.of( new Handler1(), new Handler2(), new Handler3(), new Handler4()) ); } @Test public final void dispatch1() throws Exception { final String strRequest = Handler2.BINDING.toRawString() + "/va%20lue/another_value/"; final RestRequest request = RestRequest.valueOf(strRequest); final Object value = newDispatcher().dispatch(request).toCompletableFuture().get(); assertEquals("Assert correct handling result", Handler2.VALUE + strRequest, value); } @Test public final void dispatch2() throws Exception { final RestRequest request = Handler3.BINDING; final Object value = newDispatcher().dispatch(request).toCompletableFuture().get(); assertEquals("Assert correct handling result", Handler3.VALUE + request.toRawString(), value); } @Test public final void dispatch3() throws Exception { final String strRequest = Handler4.BINDING.toRawString() + "/a/b/c/"; final RestRequest request = RestRequest.valueOf(strRequest); final Object value = newDispatcher().dispatch(request).toCompletableFuture().get(); assertEquals("Assert correct handling result", Handler4.VALUE + strRequest, value); } @Test(expected = BindingNotFoundException.class) public final void dispatchFailed() throws Exception { final String strRequest = "GET /one/t/"; final RestRequest request = RestRequest.valueOf(strRequest); newDispatcher().dispatch(request).toCompletableFuture().get(); } @Test public final void shutdown() { final ShutdownHandler handler = new ShutdownHandler(); final RestRequestDispatcher<Object> dispatcher = new RestRequestDispatcher<>( mock(Server.class), mock(ExecutorService.class), ImmutableSet.of(handler) ); dispatcher.shutdown(); assertEquals("", false, ((AtomicBoolean)Whitebox.getInternalState(dispatcher, "active")).get()); } @Test public final void shutdownIdempotence() { final ShutdownHandler handler = new ShutdownHandler(); final RestRequestDispatcher<Object> dispatcher = new RestRequestDispatcher<>( mock(Server.class), mock(ExecutorService.class), ImmutableSet.of(handler) ); dispatcher.shutdown(); dispatcher.shutdown(); assertEquals("Assert shutdownHook was invoked exactly once", 1, handler.shutdownHookInvocationCount); } @Test(expected = IllegalStateException.class) public final void dispatchAfterShutdown() { final RestRequestDispatcher<Object> dispatcher = newDispatcher(); dispatcher.shutdown(); dispatcher.dispatch(RestRequest.valueOf("GET /")); } } <file_sep>/readme.md ![PIES logo](https://7fc64c31-a-62cb3a1a-s-sites.googlegroups.com/site/projectpies/config/customLogo.gif) # PIES (Proxy, Initiator and Echo Servers) <p align="right"> <a href="https://sites.google.com/site/projectpies"><img src="https://img.shields.io/badge/documentation-current-blue.svg" alt="Documentation"></a> </p> --- Licensed under [WTFPL](http://www.wtfpl.net/), except where another license is explicitly specified. <file_sep>/pies-app/pies-app-echo/pies-app-echo-logic/src/main/java/com/gl/vn/me/ko/pies/app/echo/EchoModule.java package com.gl.vn.me.ko.pies.app.echo; import static com.gl.vn.me.ko.pies.base.constant.Message.GUICE_POTENTIALLY_SWALLOWED; import com.gl.vn.me.ko.pies.base.config.PropsConfig; import com.gl.vn.me.ko.pies.base.config.app.ConfigLocator; import com.gl.vn.me.ko.pies.base.main.GuiceLocator; import com.gl.vn.me.ko.pies.base.throwable.ApplicationException; import com.gl.vn.me.ko.pies.platform.server.rest.JsonRestRequestHandlerResult; import com.gl.vn.me.ko.pies.platform.server.rest.JsonRestServer; import com.gl.vn.me.ko.pies.platform.server.rest.RestRequestHandler; import com.gl.vn.me.ko.pies.platform.server.rest.RestServerAddress; import com.gl.vn.me.ko.pies.platform.server.rest.RestServerBoss; import com.gl.vn.me.ko.pies.platform.server.rest.RestServerName; import com.gl.vn.me.ko.pies.platform.server.rest.RestServerRequestHandling; import com.gl.vn.me.ko.pies.platform.server.rest.RestServerThreadFactory; import com.gl.vn.me.ko.pies.platform.server.rest.RestServerWorker; import com.gl.vn.me.ko.pies.platform.server.tcp.TcpServer; import com.gl.vn.me.ko.pies.platform.server.tcp.TcpServerAddress; import com.gl.vn.me.ko.pies.platform.server.tcp.TcpServerBoss; import com.gl.vn.me.ko.pies.platform.server.tcp.TcpServerName; import com.gl.vn.me.ko.pies.platform.server.tcp.TcpServerThreadFactory; import com.gl.vn.me.ko.pies.platform.server.tcp.TcpServerWorker; import com.google.common.collect.ImmutableList; import com.google.inject.AbstractModule; import com.google.inject.Provider; import com.google.inject.Provides; import com.google.inject.TypeLiteral; import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; import io.netty.channel.ChannelHandler; import io.netty.channel.ChannelInitializer; import io.netty.channel.ChannelPipeline; import io.netty.channel.socket.ServerSocketChannel; import io.netty.channel.socket.SocketChannel; import io.netty.handler.logging.LogLevel; import io.netty.handler.logging.LoggingHandler; import java.net.InetAddress; import java.net.InetSocketAddress; import java.net.UnknownHostException; import java.util.Collection; import java.util.Optional; import java.util.concurrent.ThreadFactory; import javax.annotation.Nullable; import javax.inject.Singleton; import javax.json.Json; import javax.json.JsonBuilderFactory; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * {@link AbstractModule} that SHOULD be used throughout PIES Echo Application. */ final class EchoModule extends AbstractModule { private static final Logger LOGGER = LoggerFactory.getLogger(EchoModule.class); private static final EchoModule INSTANCE = new EchoModule(); private static final String[] DEPENDENCIES = new String[] { "com.gl.vn.me.ko.pies.base.main", "com.gl.vn.me.ko.pies.base.thread"}; /** * Name of the file that specifies Echo Config. */ private static final String CONFIG_FILE_NAME = "echoConfig.xml"; final static EchoModule getInstance() { return INSTANCE; } @SuppressFBWarnings(value = "UPM_UNCALLED_PRIVATE_METHOD", justification = "The method is called from configure() method, FindBugs just don't understand lambdas") private static final ChannelInitializer<ServerSocketChannel> createServerChannelInitializer() { final ChannelInitializer<ServerSocketChannel> result; try { result = new ChannelInitializer<ServerSocketChannel>() { @Override protected final void initChannel(final ServerSocketChannel channel) throws Exception { final ChannelPipeline pipeline = channel.pipeline(); final ChannelHandler channelHandler; if (LoggerFactory.getLogger(EchoApplication.class).isDebugEnabled()) { channelHandler = new LoggingHandler(LogLevel.DEBUG); } else { channelHandler = new LoggingHandler(LogLevel.INFO); } pipeline.addLast(channelHandler); } }; } catch (final RuntimeException e) { LOGGER.error(GUICE_POTENTIALLY_SWALLOWED, e); throw e; } return result; } private EchoModule() { } @SuppressFBWarnings(value = "SIC_INNER_SHOULD_BE_STATIC_ANON", justification = "It's more readable to use anonimous class for binding instead of a static one") @Override protected final void configure() { try { for (final AbstractModule module : GuiceLocator.getModules(DEPENDENCIES)) { install(module); } bind(JsonBuilderFactory.class).toInstance(Json.createBuilderFactory(null)); bind(String.class).annotatedWith(TcpServerName.class).toInstance("Echo Server"); bind(String.class).annotatedWith(RestServerName.class).toInstance("Control Server"); bind(TcpServer.class).in(Singleton.class); bind(JsonRestServer.class).in(Singleton.class); bind(EchoChannelHandler.class).in(Singleton.class); bind(new TypeLiteral<ChannelInitializer<ServerSocketChannel>>() { }) .annotatedWith(RestServerBoss.class) .toProvider((Provider<ChannelInitializer<ServerSocketChannel>>)EchoModule::createServerChannelInitializer) .in(Singleton.class); bind(new TypeLiteral<ChannelInitializer<ServerSocketChannel>>() { }) .annotatedWith(TcpServerBoss.class) .toProvider((Provider<ChannelInitializer<ServerSocketChannel>>)EchoModule::createServerChannelInitializer) .in(Singleton.class); } catch (final RuntimeException e) { LOGGER.error(GUICE_POTENTIALLY_SWALLOWED, e); throw e; } } @Provides @Singleton @SuppressFBWarnings(value = "UPM_UNCALLED_PRIVATE_METHOD", justification = "This method is called by Guice framework") private final PropsConfig provideConfig(final ConfigLocator configLocator) { final PropsConfig result; try { result = configLocator.getXmlPropsConfig(CONFIG_FILE_NAME); EchoConfigPropertyName.validate(result, CONFIG_FILE_NAME); } catch (final RuntimeException e) { LOGGER.error(GUICE_POTENTIALLY_SWALLOWED, e); throw e; } return result; } @Provides @Singleton @RestServerAddress @SuppressFBWarnings(value = "UPM_UNCALLED_PRIVATE_METHOD", justification = "This method is called by Guice framework") private final InetSocketAddress provideControlSrvAddress(final PropsConfig cfg) { final InetSocketAddress result; try { final int port = cfg.getInteger(EchoConfigPropertyName.CONTROL_PORT).intValue(); final Optional<String> optHostPropertyValue = cfg.getString(EchoConfigPropertyName.CONTROL_HOST, null); final InetAddress host; try { host = optHostPropertyValue.isPresent() ? InetAddress.getByName(optHostPropertyValue.get()) : InetAddress.getLocalHost(); } catch (final UnknownHostException e) { throw new ApplicationException(e); } result = new InetSocketAddress(host, port); } catch (final RuntimeException e) { LOGGER.error(GUICE_POTENTIALLY_SWALLOWED, e); throw e; } return result; } @Provides @Singleton @RestServerBoss @SuppressFBWarnings(value = "UPM_UNCALLED_PRIVATE_METHOD", justification = "This method is called by Guice framework") private final Integer provideControlSrvMaxBossThreads(final PropsConfig cfg) { final Integer result; try { result = cfg.getInteger(EchoConfigPropertyName.CONTROL_ACCEPTORS); } catch (final RuntimeException e) { LOGGER.error(GUICE_POTENTIALLY_SWALLOWED, e); throw e; } return result; } @Provides @Singleton @RestServerRequestHandling @SuppressFBWarnings(value = "UPM_UNCALLED_PRIVATE_METHOD", justification = "This method is called by Guice framework") private final Integer provideControlSrvMaxDispatcherThreads(final PropsConfig cfg) { final Integer result; try { result = cfg.getInteger(EchoConfigPropertyName.CONTROL_POST_RESPONSE_WORKERS); } catch (final RuntimeException e) { LOGGER.error(GUICE_POTENTIALLY_SWALLOWED, e); throw e; } return result; } @Provides @Singleton @RestServerWorker @SuppressFBWarnings(value = "UPM_UNCALLED_PRIVATE_METHOD", justification = "This method is called by Guice framework") private final Integer provideControlSrvMaxWorkerThreads(final PropsConfig cfg) { final Integer result; try { result = cfg.getInteger(EchoConfigPropertyName.CONTROL_WORKERS); } catch (final RuntimeException e) { LOGGER.error(GUICE_POTENTIALLY_SWALLOWED, e); throw e; } return result; } @Provides @RestServerRequestHandling @Nullable @SuppressFBWarnings(value = "UPM_UNCALLED_PRIVATE_METHOD", justification = "This method is called by Guice framework") private final Collection<? extends RestRequestHandler<? extends JsonRestRequestHandlerResult>> provideControlSrvRestRequestHandlers(final TcpServer echoServer, final JsonBuilderFactory jsonBuilderFactory) { final Collection<? extends RestRequestHandler<? extends JsonRestRequestHandlerResult>> result; try { final ImmutableList.Builder<RestRequestHandler<JsonRestRequestHandlerResult>> resultBuilder = ImmutableList.builder(); resultBuilder.add(new EchoShutdownRestRequestHandler(echoServer, jsonBuilderFactory)); result = resultBuilder.build(); } catch (final RuntimeException e) { LOGGER.error(GUICE_POTENTIALLY_SWALLOWED, e); throw e; } return result; } @Provides @RestServerThreadFactory @SuppressFBWarnings(value = "UPM_UNCALLED_PRIVATE_METHOD", justification = "This method is called by Guice framework") private final ThreadFactory provideControlSrvThreadFactory(final ThreadFactory threadFactory) { final ThreadFactory result; try { result = threadFactory; } catch (final RuntimeException e) { LOGGER.error(GUICE_POTENTIALLY_SWALLOWED, e); throw e; } return result; } @Provides @Singleton @TcpServerAddress @SuppressFBWarnings(value = "UPM_UNCALLED_PRIVATE_METHOD", justification = "This method is called by Guice framework") private final InetSocketAddress provideEchoSrvAddress(final PropsConfig cfg) { final InetSocketAddress result; try { final int port = cfg.getInteger(EchoConfigPropertyName.ECHO_PORT).intValue(); final Optional<String> optHostPropertyValue = cfg.getString(EchoConfigPropertyName.ECHO_HOST, null); final InetAddress host; try { host = optHostPropertyValue.isPresent() ? InetAddress.getByName(optHostPropertyValue.get()) : InetAddress.getLocalHost(); } catch (final UnknownHostException e) { throw new ApplicationException(e); } result = new InetSocketAddress(host, port); } catch (final RuntimeException e) { LOGGER.error(GUICE_POTENTIALLY_SWALLOWED, e); throw e; } return result; } @Provides @TcpServerWorker @Nullable @SuppressFBWarnings(value = "UPM_UNCALLED_PRIVATE_METHOD", justification = "This method is called by Guice framework") private final ChannelInitializer<SocketChannel> provideEchoSrvChannelInitializer( final EchoChannelHandler echoChannelHandler) { final ChannelInitializer<SocketChannel> result; try { result = new ChannelInitializer<SocketChannel>() { @Override protected final void initChannel(final SocketChannel channel) throws Exception { final ChannelPipeline pipeline = channel.pipeline(); if (LoggerFactory.getLogger(EchoApplication.class).isDebugEnabled()) { pipeline.addFirst(new LoggingHandler(LogLevel.DEBUG)); } pipeline.addLast(echoChannelHandler); } }; } catch (final RuntimeException e) { LOGGER.error(GUICE_POTENTIALLY_SWALLOWED, e); throw e; } return result; } @Provides @Singleton @TcpServerBoss @SuppressFBWarnings(value = "UPM_UNCALLED_PRIVATE_METHOD", justification = "This method is called by Guice framework") private final Integer provideEchoSrvMaxBossThreads(final PropsConfig cfg) { final Integer result; try { result = cfg.getInteger(EchoConfigPropertyName.ECHO_ACCEPTORS); } catch (final RuntimeException e) { LOGGER.error(GUICE_POTENTIALLY_SWALLOWED, e); throw e; } return result; } @Provides @Singleton @TcpServerWorker @SuppressFBWarnings(value = "UPM_UNCALLED_PRIVATE_METHOD", justification = "This method is called by Guice framework") private final Integer provideEchoSrvMaxWorkerThreads(final PropsConfig cfg) { final Integer result; try { result = cfg.getInteger(EchoConfigPropertyName.ECHO_WORKERS); } catch (final RuntimeException e) { LOGGER.error(GUICE_POTENTIALLY_SWALLOWED, e); throw e; } return result; } @Provides @TcpServerThreadFactory @SuppressFBWarnings(value = "UPM_UNCALLED_PRIVATE_METHOD", justification = "This method is called by Guice framework") private final ThreadFactory provideEchoSrvThreadFactory(final ThreadFactory threadFactory) { final ThreadFactory result; try { result = threadFactory; } catch (final RuntimeException e) { LOGGER.error(GUICE_POTENTIALLY_SWALLOWED, e); throw e; } return result; } } <file_sep>/pies-base/pies-base-main/src/test/java/com/gl/vn/me/ko/pies/base/thread/TestApplicationUncaughtExceptionHandler.java package com.gl.vn.me.ko.pies.base.thread; import static org.junit.Assert.assertTrue; import java.io.ByteArrayOutputStream; import java.io.PrintStream; import java.io.UnsupportedEncodingException; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Test; public final class TestApplicationUncaughtExceptionHandler { private static final String SYS_PROPERTY_CONSOLE_CHARSET = "pies.consoleCharset"; private static final String CHARSET_NAME = "UTF-8"; @BeforeClass public static final void setUp() { /* * Std class will not be successfully initialized without this property. */ System.setProperty(SYS_PROPERTY_CONSOLE_CHARSET, CHARSET_NAME); } @AfterClass public static final void tearDown() { System.setProperty(SYS_PROPERTY_CONSOLE_CHARSET, ""); } public TestApplicationUncaughtExceptionHandler() { } @Test public final void uncaughtException() throws UnsupportedEncodingException { final ApplicationUncaughtExceptionHandler handler = ApplicationUncaughtExceptionHandler.getInstance(); final ByteArrayOutputStream data = new ByteArrayOutputStream(); final PrintStream out = new PrintStream(data, false, CHARSET_NAME); final String exceptionMessage = "Test uncaught exception"; final Thread t = new ApplicationThreadFactory().newThread(null); final String threadDescription = t.toString(); final String escapedThreadDescription = threadDescription.replace("(", "\\(").replace(")", "\\)"); try { throw new RuntimeException(exceptionMessage); } catch (final Throwable e) { handler.processUncaughtException(t, e, out); } final String handlerMessage = data.toString(CHARSET_NAME); final Pattern regex = Pattern.compile("^" + ".*" + escapedThreadDescription + ".*" + exceptionMessage + ".*TestApplicationUncaughtExceptionHandler\\.uncaughtException.*$", Pattern.DOTALL); final Matcher regexMatcher = regex.matcher(handlerMessage); assertTrue("Assert that handler message is correct", regexMatcher.matches()); } } <file_sep>/pies-platform/pies-platform-server/src/main/java/com/gl/vn/me/ko/pies/platform/server/tcp/TcpReverseProxyFrontEndChannelHandler.java package com.gl.vn.me.ko.pies.platform.server.tcp; import static com.gl.vn.me.ko.pies.base.constant.Message.ARGUMENT_ILLEGAL; import static com.gl.vn.me.ko.pies.base.constant.Message.ARGUMENT_NULL; import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkNotNull; import com.gl.vn.me.ko.pies.base.constant.Message; import com.gl.vn.me.ko.pies.base.throwable.ApplicationException; import com.gl.vn.me.ko.pies.base.throwable.TimeoutException; import io.netty.bootstrap.Bootstrap; import io.netty.buffer.Unpooled; import io.netty.channel.Channel; import io.netty.channel.ChannelFuture; import io.netty.channel.ChannelHandlerAdapter; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.ChannelOption; import io.netty.channel.ChannelPromise; import io.netty.channel.ConnectTimeoutException; import io.netty.channel.EventLoopGroup; import io.netty.channel.socket.nio.NioSocketChannel; import java.net.InetSocketAddress; import javax.annotation.Nullable; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Handles events on front-end {@link Channel}s. */ final class TcpReverseProxyFrontEndChannelHandler extends ChannelHandlerAdapter { private static final Logger LOGGER = LoggerFactory.getLogger(TcpReverseProxyFrontEndChannelHandler.class); private final InetSocketAddress beAddress; private final int connectTimeoutMillis; private final EventLoopGroup workerEventLoopGroup; @Nullable private Channel beChannel; /** * Constructs a new instance of {@link TcpReverseProxyFrontEndChannelHandler}. * * @param beAddress * Back-end {@link InetSocketAddress}. * @param connectTimeoutMillis * Amount of time in milliseconds to wait for connecting to the {@code beAddress}. * This argument MUST be positive. * @param workerEventLoopGroup * {@Link EventLoopGroup} to use to process events on back-end {@link Channel}s. */ TcpReverseProxyFrontEndChannelHandler( final InetSocketAddress beAddress, final int connectTimeoutMillis, final EventLoopGroup workerEventLoopGroup) { checkNotNull(beAddress, ARGUMENT_NULL, "first", "beAddress"); checkArgument(connectTimeoutMillis > 0, ARGUMENT_ILLEGAL, connectTimeoutMillis, "second", "connectTimeoutMillis", "Expected value must be positive"); checkNotNull(workerEventLoopGroup, ARGUMENT_NULL, "third", "workerEventLoopGroup"); this.beAddress = beAddress; this.connectTimeoutMillis = connectTimeoutMillis; this.workerEventLoopGroup = workerEventLoopGroup; } @Override public final void channelActive(final ChannelHandlerContext ctx) { final Channel feChannel = ctx.channel(); final Bootstrap beBootstrap = new Bootstrap().group(workerEventLoopGroup) .channel(NioSocketChannel.class) .option(ChannelOption.SO_KEEPALIVE, true) .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, connectTimeoutMillis) .handler(new TcpReverseProxyBackEndChannelHandler(feChannel)); final ChannelFuture beConnectFuture = beBootstrap.connect(beAddress); beChannel = beConnectFuture.channel(); LOGGER.debug("A new back-end channel {} was created and was associated with front-end {}", beChannel, feChannel); beConnectFuture.addListener((final ChannelFuture future) -> { if (future.isSuccess()) { LOGGER.debug("Back-end {} was connected", beChannel); feChannel.read(); } else { feChannel.close(); final Throwable cause = future.cause(); final String internalMsg = Message.format("Can't connect to back-end %s", beAddress); if (cause instanceof ConnectTimeoutException) { throw new TimeoutException(internalMsg, cause, "TCP connect timeout"); } else { throw new ApplicationException(internalMsg, cause); } } }); } @Override public final void channelRead(final ChannelHandlerContext ctx, final Object msg) { final Channel feChannel = ctx.channel(); if (beChannel.isActive()) {//can't be null because feChannel.read() is only called if beChannel successfully initialized LOGGER.debug("Writing {} from front-end {} to back-end {}", msg, feChannel, beChannel); beChannel.writeAndFlush(msg).addListener((final ChannelFuture future) -> { if (future.isSuccess()) { feChannel.read(); } else { beChannel.close(); throw new ApplicationException( Message.format("Can't write and flush to back-end %s", beChannel), future.cause()); } }); } else { LOGGER.debug("Data {} from front-end {} was ignored because back-end {} isn't active", msg, feChannel, beChannel); } } @Override public final void channelInactive(final ChannelHandlerContext ctx) { if (beChannel != null && beChannel.isActive()) {//flush beChannel and close beChannel.writeAndFlush(Unpooled.EMPTY_BUFFER).addListener((final ChannelFuture future) -> beChannel.close()); } ctx.fireChannelInactive(); } @Override public final void exceptionCaught(final ChannelHandlerContext ctx, final Throwable e) { try { LOGGER.error("Exception caught", e); } finally { final Channel channel = ctx.channel(); channel.close(); } } @Override public final void close(final ChannelHandlerContext ctx, final ChannelPromise promise) { final Channel channel = ctx.channel(); ctx.close(); LOGGER.debug("{} was closed", channel); } } <file_sep>/pies-platform/pies-platform-server/src/main/java/com/gl/vn/me/ko/pies/platform/server/rest/BindingNotFoundException.java package com.gl.vn.me.ko.pies.platform.server.rest; import com.gl.vn.me.ko.pies.base.throwable.ApplicationException; import javax.annotation.Nullable; /** * Indicates that no suitable {@link RestRequestHandler} was found to handle a {@link RestRequest}. */ public final class BindingNotFoundException extends ApplicationException { private static final long serialVersionUID = 0; /** * Creates an instance of {@link BindingNotFoundException}. */ BindingNotFoundException() { } /** * Creates an instance of {@link BindingNotFoundException}. * * @param message * The detail message which is saved for later retrieval by the {@link #getMessage()} method. */ BindingNotFoundException(@Nullable final String message) { super(message); } /** * Creates an instance of {@link BindingNotFoundException}. * * @param message * The detail message which is saved for later retrieval by the {@link #getMessage()} method. * @param cause * The cause which is saved for later retrieval by the {@link #getCause()} method. */ BindingNotFoundException(@Nullable final String message, @Nullable final Throwable cause) { super(message, cause); } /** * Creates an instance of {@link BindingNotFoundException}. * * @param cause * The cause which is saved for later retrieval by the {@link #getCause()} method. */ BindingNotFoundException(@Nullable final Throwable cause) { super(cause); } } <file_sep>/pies-platform/pies-platform-server/src/main/java/com/gl/vn/me/ko/pies/platform/server/rest/RestDecoder.java package com.gl.vn.me.ko.pies.platform.server.rest; import static com.google.common.base.Preconditions.checkState; import com.gl.vn.me.ko.pies.base.constant.Message; import com.gl.vn.me.ko.pies.base.throwable.ApplicationError; import io.netty.channel.Channel; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.ChannelPromise; import io.netty.channel.SimpleChannelInboundHandler; import io.netty.handler.codec.http.FullHttpResponse; import io.netty.handler.codec.http.HttpContent; import io.netty.handler.codec.http.HttpHeaders; import io.netty.handler.codec.http.HttpRequest; import io.netty.handler.codec.http.HttpResponseStatus; import io.netty.handler.codec.http.LastHttpContent; import javax.annotation.Nullable; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Decodes {@link HttpRequest} and {@link HttpContent} objects and constructs corresponding {@link RestRequest}s, * and {@linkplain ChannelHandlerContext#fireChannelRead(Object) fires channel read} event * with {@link RestHttpRequestsAlloy} object. * In some situations {@link RestDecoder} doesn't * {@linkplain ChannelHandlerContext#fireChannelRead(Object) fires channel read} event * and {@linkplain ChannelHandlerContext#writeAndFlush(Object) responds} with HTTP responses * constructed by using the {@link RestServer.ServiceHttpResponseConstructor#create(HttpResponseStatus, String)} method. * <p> * {@link RestDecoder} MUST be preceeded by the {@link HttpServerCodec} in the {@link ChannelPipeline}. */ final class RestDecoder extends SimpleChannelInboundHandler<Object> { private static final class State { @Nullable HttpRequest httpRequest; @Nullable RestRequest restRequest; private State() { clear(); } private final void clear() { httpRequest = null; restRequest = null; } private final boolean isClear() { return (httpRequest == null) && (restRequest == null); } private final RestHttpRequestsAlloy getAlloy() throws IllegalStateException { checkState(httpRequest != null, "% is null", "httpRequest"); checkState(restRequest != null, "% is null", "restRequest"); return new RestHttpRequestsAlloy(restRequest, httpRequest); } @Override public final String toString() { final StringBuilder sb = new StringBuilder(getClass().getName()) .append("(httpRequest=").append(httpRequest) .append(", restRequest=").append(restRequest).append(')'); final String result = sb.toString(); return result; } } private static final Logger LOGGER = LoggerFactory.getLogger(RestDecoder.class); private final RestServer.ServiceHttpResponseConstructor serviceHttpResponseConstructor; private final RestServer.ExceptionHandler exceptionHandler; private final State state; /** * Constructs a new instance of {@link RestDecoder}. * * @param serviceHttpResponseConstructor * An instance of the {@link RestServer.ServiceHttpResponseConstructor}. * @param keepAliveHandler * An instance of the {@link RestServer.ExceptionHandler}. * */ RestDecoder( final RestServer.ServiceHttpResponseConstructor serviceHttpResponseConstructor, final RestServer.ExceptionHandler exceptionHandler) { this.serviceHttpResponseConstructor = serviceHttpResponseConstructor; this.exceptionHandler = exceptionHandler; state = new State(); } @Override public final void channelInactive(final ChannelHandlerContext ctx) { state.clear(); ctx.fireChannelInactive(); } @Override public final void exceptionCaught(final ChannelHandlerContext ctx, final Throwable cause) { exceptionCaught(ctx, cause, null); } private final void exceptionCaught( final ChannelHandlerContext ctx, final Throwable cause, @Nullable final HttpRequest httpRequest) { final FullHttpResponse httpResponse = exceptionHandler.handle(cause, httpRequest); respond(ctx, httpResponse, true); } @Override protected final void messageReceived(final ChannelHandlerContext ctx, final Object msg) { if (msg instanceof HttpRequest) { if (!state.isClear()) { exceptionCaught(ctx, new ApplicationError(Message.format("State %s isn't clean", state)), state.httpRequest); } else { final HttpRequest localHttpRequest = state.httpRequest = (HttpRequest)msg; if (HttpHeaders.is100ContinueExpected(localHttpRequest)) { respond(ctx, RestServer.HTTP_RESPONSE_STATUS_CONTINUE, null, false); } else { final String restMethod = localHttpRequest.getMethod().toString(); String restUri = localHttpRequest.getUri(); try { state.restRequest = RestRequest.valueOf(restMethod, restUri); } catch (final RestRequestSyntaxException e) { LOGGER.debug("Unable to construct a REST request", e); respond(ctx, RestServer.HTTP_RESPONSE_STATUS_BAD_REQUEST, "Incorrect REST request syntax", true); } } } } else if (msg instanceof HttpContent) { if (msg instanceof LastHttpContent) { final LastHttpContent lastHttpContent = (LastHttpContent)msg; if (lastHttpContent.getDecoderResult().isSuccess()) { try { final RestHttpRequestsAlloy restHttpAlloy = state.getAlloy(); ctx.fireChannelRead(restHttpAlloy); state.clear(); } catch (final IllegalStateException e) { exceptionCaught(ctx, new ApplicationError(e), state.httpRequest); } } else { LOGGER.debug("Unable to decode content {} of a request", lastHttpContent); respond(ctx, RestServer.HTTP_RESPONSE_STATUS_BAD_REQUEST, "Unable to decode request content", true); } } } } private final void respond( final ChannelHandlerContext ctx, final FullHttpResponse finalHttpResponse, final boolean resetState) { try { ctx.writeAndFlush(finalHttpResponse); } finally { if (resetState) { state.clear(); } } } private final void respond( final ChannelHandlerContext ctx, final HttpResponseStatus httpResponseStatus, @Nullable final String httpReasonPhrase, final boolean resetState) { final FullHttpResponse httpResponse = serviceHttpResponseConstructor.create(httpResponseStatus, httpReasonPhrase); RestServer.handleKeepAlive(state.httpRequest, httpResponse); respond(ctx, httpResponse, resetState); } @Override public final void close(final ChannelHandlerContext ctx, final ChannelPromise promise) { final Channel channel = ctx.channel(); ctx.close(); LOGGER.debug("{} was closed", channel); } } <file_sep>/pies-base/pies-base-main/src/main/java/com/gl/vn/me/ko/pies/base/thread/ApplicationThreadFactory.java package com.gl.vn.me.ko.pies.base.thread; import com.gl.vn.me.ko.pies.base.constant.Message; import java.util.concurrent.ThreadFactory; import java.util.concurrent.atomic.AtomicLong; import javax.annotation.Nullable; import javax.annotation.concurrent.ThreadSafe; import javax.inject.Inject; import javax.inject.Singleton; /** * This factory SHOULD be used by the Application whenever it needs a {@link ThreadFactory} or needs to create * a new {@link Thread} unless a {@link java.util.concurrent.ForkJoinWorkerThread} is required. * <p> * If you need a factory that creates threads with other name convention for example, consider using * {@link com.google.common.util.concurrent.ThreadFactoryBuilder}. */ @Singleton @ThreadSafe public final class ApplicationThreadFactory implements ThreadFactory { private static final AtomicLong INDEX = new AtomicLong(); @Inject ApplicationThreadFactory() { } /** * Creates a new instance of {@link ApplicationThread}. * The created {@link ApplicationThread} is not a daemon, has a {@link Thread#NORM_PRIORITY} priority, * {@link ApplicationUncaughtExceptionHandler} as uncaught exception handler and {@code "pies-thread-%d"} as a name, * where {@code %d} is replaced with an index (starting from 1) of this method invocation among all objects of type * {@link ApplicationThreadFactory}. * * @param target * Object which {@link Runnable#run()} method is invoked when the {@link ApplicationThread} is * started. If {@code target} is {@code null} then the {@link ApplicationThread#run()} method of the * constructed {@link ApplicationThread} does nothing. * @return * Constructed {@link ApplicationThread}. */ @Override public final ApplicationThread newThread(@Nullable final Runnable target) { final ApplicationThread result = new ApplicationThread(target); result.setDaemon(false); result.setPriority(Thread.NORM_PRIORITY); result.setUncaughtExceptionHandler(ApplicationUncaughtExceptionHandler.getInstance()); result.setName(Message.format("pies-thread-%d", Long.valueOf(INDEX.incrementAndGet()))); return result; } } <file_sep>/pom.xml <?xml version="1.0" encoding="UTF-8"?> <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"> <description> PIES - simple Proxy, Initiator and Echo Servers that can work with each other. The top module project. This project recursively aggregates all other projects with groupId 'com.gl.vn.me.ko.pies'. </description> <modelVersion>4.0.0</modelVersion> <artifactId>pies</artifactId> <packaging>pom</packaging> <name>pies (PIES)</name> <url>${pies.project.url}</url> <licenses> <license> <name>${pies.project.license.name}</name> <url>${pies.project.license.url}</url> </license> </licenses> <inceptionYear>${pies.project.inceptionYear}</inceptionYear> <organization> <name>${pies.project.organization.name}</name> <url>${pies.project.organization.url}</url> </organization> <parent> <groupId>com.gl.vn.me.ko.pies</groupId> <artifactId>pies-parent</artifactId> <version>0.0.0-SNAPSHOT</version> <relativePath>pies-parent/pom.xml</relativePath> </parent> <modules> <module>pies-parent</module> <module>pies-base</module> <module>pies-platform</module> <module>pies-app</module> </modules> <profiles> <profile> <id>assembly</id> <dependencies> <dependency> <groupId>com.gl.vn.me.ko.pies</groupId> <artifactId>pies-app-echo</artifactId> <classifier>${pies.classifier.assembly}</classifier> <type>zip</type> </dependency> <dependency> <groupId>com.gl.vn.me.ko.pies</groupId> <artifactId>pies-app-initiator</artifactId> <classifier>${pies.classifier.assembly}</classifier> <type>zip</type> </dependency> <dependency> <groupId>com.gl.vn.me.ko.pies</groupId> <artifactId>pies-app-proxy</artifactId> <classifier>${pies.classifier.assembly}</classifier> <type>zip</type> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-assembly-plugin</artifactId> </plugin> </plugins> </build> </profile> <profile> <id>doc</id> <build> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-javadoc-plugin</artifactId> <executions> <execution> <id>attach-aggregated-javadocs</id> <phase>package</phase> <goals> <goal>aggregate-jar</goal> </goals> </execution> </executions> </plugin> </plugins> </build> </profile> </profiles> </project><file_sep>/pies-base/pies-base-config/src/main/java/com/gl/vn/me/ko/pies/base/config/XmlPropsConfig.java package com.gl.vn.me.ko.pies.base.config; import static com.gl.vn.me.ko.pies.base.config.PropertyType.BIG_DECIMAL; import static com.gl.vn.me.ko.pies.base.config.PropertyType.BIG_INTEGER; import static com.gl.vn.me.ko.pies.base.config.PropertyType.BOOLEAN; import static com.gl.vn.me.ko.pies.base.config.PropertyType.DOUBLE; import static com.gl.vn.me.ko.pies.base.config.PropertyType.INTEGER; import static com.gl.vn.me.ko.pies.base.config.PropertyType.LIST_OF_STRINGS; import static com.gl.vn.me.ko.pies.base.config.PropertyType.LONG; import static com.gl.vn.me.ko.pies.base.config.PropertyType.SET_OF_STRINGS; import static com.gl.vn.me.ko.pies.base.config.PropertyType.STRING; import static com.google.common.base.Preconditions.checkNotNull; import com.gl.vn.me.ko.pies.base.constant.Constant; import com.gl.vn.me.ko.pies.base.constant.Message; import com.gl.vn.me.ko.pies.base.feijoa.Stringable; import com.gl.vn.me.ko.pies.base.feijoa.StringableConverter; import com.gl.vn.me.ko.pies.base.throwable.ApplicationError; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableSet; import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; import java.io.IOException; import java.math.BigDecimal; import java.math.BigInteger; import java.net.MalformedURLException; import java.nio.file.FileSystems; import java.nio.file.Path; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import javax.annotation.Nullable; import javax.annotation.concurrent.ThreadSafe; import javax.xml.XMLConstants; import javax.xml.transform.Source; import javax.xml.transform.stream.StreamSource; import javax.xml.validation.Schema; import javax.xml.validation.SchemaFactory; import javax.xml.validation.Validator; import org.apache.commons.configuration.ConfigurationException; import org.apache.commons.configuration.XMLConfiguration; import org.apache.commons.lang.StringUtils; import org.xml.sax.SAXException; /** * Represents configuration that is specified via XML document. * This implementation uses {@link XMLConfiguration} in order to read cachedProps from XML. * See * <a href="http://commons.apache.org/proper/commons-configuration/">Apache Commons Configuration</a> * for details; e.g. <a href= * "http://commons.apache.org/proper/commons-configuration/userguide/howto_basicfeatures.html#Variable_Interpolation" * >Variable Interpolation (aka Property Substitution)</a> is a very useful functionality. * However note also that Apache Commons Configuration seem to violate its specification sometimes, * e.g. you can't preserve spaces by using {@code xml:space="preserve"} as specified in {@link XMLConfiguration}. * <p> * Semicolon {@code ';'} (Unicode code point {@code U+003B}) is used as delimiter in multiple properties (see * {@link XMLConfiguration#setListDelimiter(char)}). One can escape the semicolon character in the multiple value by * using backslash {@code '\'} (Unicode code point {@code U+005C}). */ @ThreadSafe public final class XmlPropsConfig implements PropsConfig { @SuppressFBWarnings(value = {"DM_BOOLEAN_CTOR", "DM_FP_NUMBER_CTOR", "DM_NUMBER_CTOR", "DM_STRING_VOID_CTOR"}, justification = "See comment on Props.EMPTY_VALUES field") private static final class Props { /* * Values in EMPTY_VALUES MUST be new objects, i.e. instead of Boolean.FALSE one MUST use new Boolean(false). */ private static final Map<PropertyType<?>, Object> EMPTY_VALUES = ImmutableMap.<PropertyType<?>, Object>builder() .put(BIG_DECIMAL, new BigDecimal(0)) .put(BIG_INTEGER, new BigInteger("0")) .put(BOOLEAN, new Boolean(false)) .put(DOUBLE, new Double(0)) .put(INTEGER, new Integer(0)) .put(LONG, new Long(0)) .put(STRING, new String()) .put(LIST_OF_STRINGS, new ArrayList<>(0)) .put(SET_OF_STRINGS, new HashSet<>(0)) .build(); private static final <T> T empty(final PropertyType<T> type) { @SuppressWarnings("unchecked") final T result = (T)EMPTY_VALUES.get(type); return result; } private final Map<PropertyType<?>, ConcurrentMap<PropertyName, Object>> byType; private Props() { byType = new HashMap<>(9); for (final PropertyType<?> type : PropertyType.types()) { byType.put(type, new ConcurrentHashMap<>()); } } private final <T> ConcurrentMap<PropertyName, T> byType(final PropertyType<T> type) { @SuppressWarnings("unchecked") final ConcurrentMap<PropertyName, T> result = (ConcurrentMap<PropertyName, T>)byType.get(type); return result; } /** * Returns a description of the {@link Props}. * * @return * A description of the {@link Props}. */ @Override public final String toString() { final StringBuilder sb = new StringBuilder(this.getClass().getName()) .append("(byType=").append(byType).append(')'); final String result = sb.toString(); return result; } } /** * This {@code char} is used as delimiter in multiple properties * (see {@link XMLConfiguration#setListDelimiter(char)}). */ private static final char MULTIPLE_PROPERTY_DELIMETER = ';'; /** * Returns object that is used by {@link XmlPropsConfig} to read configuration. * * @param path * Location of the XML file that contains configuration. UTF-8 encoding MUST be used in the file. * @param validate * Specifies whether XSD schema validation should be performed when loading XML documents. * The XSD schema MUST be specified in the XML document if this argument is {@code true}. * @return Object that is used by {@link XmlPropsConfig} to read configuration. * @throws ConfigurationException * If an error occurs during the config load operation. * @throws SAXException * If {@code validate} is {@code true} and XML is not valid or doesn't specify the schema it expects to * be validated against. */ private static final XMLConfiguration createConfigReader(final Path path, final boolean validate) throws ConfigurationException, SAXException { /* * Seems like Apache Configuration can only validate XML via DTD, but not XSD. * So we need to perform validation by ourselves. */ if (validate) { validate(path); } final XMLConfiguration result = new XMLConfiguration(); result.setValidating(false); result.setEncoding(Constant.CHARSET.name()); result.setThrowExceptionOnMissing(false); result.setListDelimiter(MULTIPLE_PROPERTY_DELIMETER); try { result.load(path.toUri().toURL()); } catch (final MalformedURLException e) { throw new RuntimeException(e); } return result; } /** * Checks if the specified file contains valid XML or not. * The XSD schema MUST be specified in the XML document. * * @param path * A Path to file that contains XML that need to be validated. * @throws SAXException * If XML is not valid or doesn't specify the schema it expects to be validated against. */ private static final void validate(final Path path) throws SAXException { final SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); final Validator validator; try { final Schema schema = schemaFactory.newSchema(); validator = schema.newValidator(); } catch (final SAXException e) { throw new RuntimeException(e); } final Source source = new StreamSource(path.toFile()); try { validator.validate(source); } catch (final IOException e) { throw new RuntimeException(e); } } private final XMLConfiguration configReader; private final Props cachedProps; /** * Constructs a new instance of {@link XmlPropsConfig}. * * @param config * Location of the configuration file. UTF-8 encoding MUST be used in the file. * @param validate * Specifies whether XSD schema validation need to be performed when loading XML document. * @throws ConfigCreationException * If creation of configuration is failed. */ public XmlPropsConfig(final Path config, final boolean validate) throws ConfigCreationException { checkNotNull(config, Message.ARGUMENT_NULL_SINGLE, "config"); try { configReader = createConfigReader(config, validate); cachedProps = new Props(); } catch (final Exception e) { throw new ConfigCreationException(e); } } /** * Constructs a new instance of {@link XmlPropsConfig}. * Acts like {@link #XmlPropsConfig(Path, boolean)} by creating a {@link Path} as following: * <pre>{@code * FileSystems.getDefault().getPath(config) * }</pre> * * @param config * Location of the configuration file. UTF-8 encoding MUST be used in the file. * @param validate * Specifies whether XSD schema validation need to be performed when loading XML document. * @throws ConfigCreationException * If creation of configuration is failed. */ public XmlPropsConfig(final String config, final boolean validate) { checkNotNull(config, Message.ARGUMENT_NULL_SINGLE, "config"); try { final Path path = FileSystems.getDefault().getPath(config); configReader = createConfigReader(path, validate); cachedProps = new Props(); } catch (final RuntimeException | ConfigurationException | SAXException e) { throw new ConfigCreationException(e); } } private final <T> void cachePropertyIfNeeded(final PropertyName name, final PropertyType<T> type) { final ConcurrentMap<PropertyName, T> cachedProperties = cachedProps.byType(type); @Nullable final T readValue = readValue(name, type, null); if (readValue == null) { cachedProperties.putIfAbsent(name, Props.empty(type)); } else { cachedProperties.putIfAbsent(name, readValue); } } @Override public final <T> T get(final PropertyName name, final PropertyType<T> type) throws NoSuchPropertyException { checkNotNull(name, Message.ARGUMENT_NULL, "first", "name"); checkNotNull(type, Message.ARGUMENT_NULL, "second", "type"); return getValue(name, type); } @Override public final <T> Optional<T> get(final PropertyName name, final T defaultValue, final PropertyType<T> type) { checkNotNull(name, Message.ARGUMENT_NULL, "first", "name"); checkNotNull(type, Message.ARGUMENT_NULL, "third", "type"); return Optional.ofNullable(getValue(name, type, defaultValue)); } @Override public final BigDecimal getBigDecimal(final PropertyName name) throws NoSuchPropertyException { checkNotNull(name, Message.ARGUMENT_NULL_SINGLE, "name"); return getValue(name, PropertyType.BIG_DECIMAL); } @Override public final Optional<BigDecimal> getBigDecimal(final PropertyName name, @Nullable final BigDecimal defaultValue) { checkNotNull(name, Message.ARGUMENT_NULL_SINGLE, "name"); return Optional.ofNullable(getValue(name, PropertyType.BIG_DECIMAL, defaultValue)); } @Override public final BigInteger getBigInteger(final PropertyName name) throws NoSuchPropertyException { checkNotNull(name, Message.ARGUMENT_NULL_SINGLE, "name"); return getValue(name, PropertyType.BIG_INTEGER); } @Override public final Optional<BigInteger> getBigInteger(final PropertyName name, @Nullable final BigInteger defaultValue) { checkNotNull(name, Message.ARGUMENT_NULL_SINGLE, "name"); return Optional.ofNullable(getValue(name, PropertyType.BIG_INTEGER, defaultValue)); } @Override public final Boolean getBoolean(final PropertyName name) throws NoSuchPropertyException { checkNotNull(name, Message.ARGUMENT_NULL_SINGLE, "name"); return getValue(name, PropertyType.BOOLEAN); } @Override public final Optional<Boolean> getBoolean(final PropertyName name, @Nullable final Boolean defaultValue) { checkNotNull(name, Message.ARGUMENT_NULL_SINGLE, "name"); return Optional.ofNullable(getValue(name, PropertyType.BOOLEAN, defaultValue)); } @Override public final Double getDouble(final PropertyName name) throws NoSuchPropertyException { checkNotNull(name, Message.ARGUMENT_NULL_SINGLE, "name"); return getValue(name, PropertyType.DOUBLE); } @Override public final Optional<Double> getDouble(final PropertyName name, @Nullable final Double defaultValue) { checkNotNull(name, Message.ARGUMENT_NULL_SINGLE, "name"); return Optional.ofNullable(getValue(name, PropertyType.DOUBLE, defaultValue)); } @Override public final Integer getInteger(final PropertyName name) throws NoSuchPropertyException { checkNotNull(name, Message.ARGUMENT_NULL_SINGLE, "name"); return getValue(name, PropertyType.INTEGER); } @Override public final Optional<Integer> getInteger(final PropertyName name, @Nullable final Integer defaultValue) { checkNotNull(name, Message.ARGUMENT_NULL_SINGLE, "name"); return Optional.ofNullable(getValue(name, PropertyType.INTEGER, defaultValue)); } @Override public final List<String> getListOfStrings(final PropertyName name) throws NoSuchPropertyException { checkNotNull(name, Message.ARGUMENT_NULL_SINGLE, "name"); @SuppressWarnings("unchecked") final List<String> result = getValue(name, PropertyType.LIST_OF_STRINGS); return result; } @Override public final Optional<List<String>> getListOfStrings(final PropertyName name, @Nullable final List<String> defaultValue) { checkNotNull(name, Message.ARGUMENT_NULL_SINGLE, "name"); @SuppressWarnings("unchecked") final List<String> result = getValue(name, PropertyType.LIST_OF_STRINGS, defaultValue); return Optional.ofNullable(result); } @Override public final Long getLong(final PropertyName name) throws NoSuchPropertyException { checkNotNull(name, Message.ARGUMENT_NULL_SINGLE, "name"); return getValue(name, PropertyType.LONG); } @Override public final Optional<Long> getLong(final PropertyName name, @Nullable final Long defaultValue) { checkNotNull(name, Message.ARGUMENT_NULL_SINGLE, "name"); return Optional.ofNullable(getValue(name, PropertyType.LONG, defaultValue)); } @Override public final Set<String> getSetOfStrings(final PropertyName name) throws NoSuchPropertyException { checkNotNull(name, Message.ARGUMENT_NULL_SINGLE, "name"); @SuppressWarnings("unchecked") final Set<String> result = getValue(name, PropertyType.SET_OF_STRINGS); return result; } @Override public final Optional<Set<String>> getSetOfStrings(final PropertyName name, @Nullable final Set<String> defaultValue) { checkNotNull(name, Message.ARGUMENT_NULL_SINGLE, "name"); @SuppressWarnings("unchecked") final Set<String> result = getValue(name, PropertyType.SET_OF_STRINGS, defaultValue); return Optional.ofNullable(result); } @Override public final String getString(final PropertyName name) throws NoSuchPropertyException { checkNotNull(name, Message.ARGUMENT_NULL_SINGLE, "name"); return getValue(name, PropertyType.STRING); } @Override public final Optional<String> getString(final PropertyName name, @Nullable final String defaultValue) { checkNotNull(name, Message.ARGUMENT_NULL_SINGLE, "name"); return Optional.ofNullable(getValue(name, PropertyType.STRING, defaultValue)); } @Override public <T extends Stringable> T getStringable(final PropertyName name, final StringableConverter<T> converter) throws NoSuchPropertyException { checkNotNull(name, Message.ARGUMENT_NULL, "first", "name"); checkNotNull(converter, Message.ARGUMENT_NULL, "second", "converter"); return converter.valueOf(getValue(name, PropertyType.STRING)); } @Override public <T extends Stringable> Optional<T> getStringable(final PropertyName name, @Nullable final T defaultValue, final StringableConverter<T> converter) { checkNotNull(name, Message.ARGUMENT_NULL, "first", "name"); checkNotNull(converter, Message.ARGUMENT_NULL, "third", "converter"); @Nullable final String stringValue = getValue(name, PropertyType.STRING, null); return Optional.ofNullable(stringValue == null ? defaultValue : converter.valueOf(stringValue)); } private final <T> T getValue(final PropertyName name, final PropertyType<T> type) throws NoSuchPropertyException { @Nullable final T result = getValue(name, type, null);// returns null if and only only if the property is undefined if (result == null) { throw new NoSuchPropertyException(Message.format("Configuration doesn't contain property %s", name)); } return result; } @Nullable private final <T> T getValue(final PropertyName name, final PropertyType<T> type, @Nullable final T defaultValue) { final ConcurrentMap<PropertyName, T> cachedProperties = cachedProps.byType(type); @Nullable T cachedValue = cachedProperties.get(name); if (cachedValue == null) {// value isn't cached cachePropertyIfNeeded(name, type); cachedValue = cachedProperties.get(name);// read cached value } return (cachedValue == Props.empty(type)) ? defaultValue : cachedValue; } @Nullable private final List<String> readMultiple(final PropertyName name) { @Nullable final List<String> result; final List<Object> readMultipleValues = configReader.getList(name.toString(), null); if (readMultipleValues != null) { @SuppressWarnings({"unchecked", "rawtypes"}) final List<String> multipleValues = (List)readMultipleValues; final ImmutableList.Builder<String> listBuilder = ImmutableList.<String>builder(); for (@Nullable final String value : multipleValues) { if ((value != null) && StringUtils.isNotBlank(value)) { final String trimmedValue = value.trim(); listBuilder.add(trimmedValue); } } result = listBuilder.build(); } else { result = null; } return result; } @Nullable private final List<String> readListOfStrings(final PropertyName name, @Nullable final List<String> defaultValue) { @Nullable final List<String> readMultiple = readMultiple(name); @Nullable final List<String> result = readMultiple == null ? defaultValue : readMultiple; return result; } @Nullable private final Set<String> readSetOfStrings(final PropertyName name, @Nullable final Set<String> defaultValue) { @Nullable final List<String> readMultiple = readMultiple(name); @Nullable final Set<String> result = readMultiple == null ? defaultValue : ImmutableSet.copyOf(readMultiple); return result; } @Nullable private final <T> T readValue(final PropertyName name, final PropertyType<T> type, @Nullable final Object defaultValue) { @Nullable final T result; if (BIG_DECIMAL.equals(type)) { result = type.cast(configReader.getBigDecimal(name.toString(), BIG_DECIMAL.cast(defaultValue))); } else if (BIG_INTEGER.equals(type)) { result = type.cast(configReader.getBigInteger(name.toString(), BIG_INTEGER.cast(defaultValue))); } else if (BOOLEAN.equals(type)) { result = type.cast(configReader.getBoolean(name.toString(), BOOLEAN.cast(defaultValue))); } else if (DOUBLE.equals(type)) { result = type.cast(configReader.getDouble(name.toString(), DOUBLE.cast(defaultValue))); } else if (INTEGER.equals(type)) { result = type.cast(configReader.getInteger(name.toString(), INTEGER.cast(defaultValue))); } else if (LONG.equals(type)) { result = type.cast(configReader.getLong(name.toString(), LONG.cast(defaultValue))); } else if (STRING.equals(type)) { result = type.cast(configReader.getString(name.toString(), STRING.cast(defaultValue))); } else if (LIST_OF_STRINGS.equals(type)) { result = type.cast(readListOfStrings(name, LIST_OF_STRINGS.cast(defaultValue))); } else if (SET_OF_STRINGS.equals(type)) { result = type.cast(readSetOfStrings(name, SET_OF_STRINGS.cast(defaultValue))); } else { throw new ApplicationError(Message.CAN_NEVER_HAPPEN); } return result; } /** * Returns a description of the {@link XmlPropsConfig}. * * @return * A description of the {@link XmlPropsConfig}. */ @Override public final String toString() { final StringBuilder sb = new StringBuilder(this.getClass().getName()) .append("(cachedProps=").append(cachedProps).append(')'); final String result = sb.toString(); return result; } } <file_sep>/pies-base/pies-base-throwable/src/main/java/com/gl/vn/me/ko/pies/base/throwable/package-info.java /** * Contains base Application exception classes. */ @com.gl.vn.me.ko.pies.base.doc.Defaults @javax.annotation.ParametersAreNonnullByDefault package com.gl.vn.me.ko.pies.base.throwable; <file_sep>/pies-base/pies-base-main/src/main/java/com/gl/vn/me/ko/pies/base/main/package-info.java /** * Contains an entry point of the Application. */ @com.gl.vn.me.ko.pies.base.doc.Defaults @javax.annotation.ParametersAreNonnullByDefault package com.gl.vn.me.ko.pies.base.main; <file_sep>/pies-platform/pies-platform-app/src/main/java/com/gl/vn/me/ko/pies/platform/app/package-info.java /** * Contains common platform functionality that is needed to implement {@link com.gl.vn.me.ko.pies.base.main.App}. */ @com.gl.vn.me.ko.pies.base.doc.Defaults @javax.annotation.ParametersAreNonnullByDefault package com.gl.vn.me.ko.pies.platform.app; <file_sep>/pies-platform/pies-platform-client/src/main/java/com/gl/vn/me/ko/pies/platform/client/tcp/TcpResponse.java package com.gl.vn.me.ko.pies.platform.client.tcp; import static com.google.common.base.Preconditions.checkNotNull; import com.gl.vn.me.ko.pies.base.constant.Message; import javax.annotation.concurrent.ThreadSafe; /** * Represents response that {@link TcpSequentialClient} returns. * * @param <Response> * A type of response contained by {@link TcpResponse}. */ @ThreadSafe public final class TcpResponse<Response> { private final Response response; private final TcpConnection<?, ?> connection; /** * Constructs a new instance of {@link TcpResponse}. * * @param response * Response contained by {@link TcpResponse}. * @param connection * {@link TcpConnection} that was used to send {@link TcpMessage} that has provoked this {@link TcpResponse} * and in which the supplied {@code response} was received. */ TcpResponse(final Response response, final TcpConnection<?, ?> connection) { checkNotNull(response, Message.ARGUMENT_NULL, "first", "response"); checkNotNull(connection, Message.ARGUMENT_NULL, "second", "connection"); this.response = response; this.connection = connection; } /** * Returns a response contained by this {@link TcpResponse}. * * @return * A response contained by this {@link TcpResponse}. */ public final Response get() { return response; } /** * Aborts a TCP connection that was used to get this {@link TcpResponse}. * This method is idempotent. */ public final void abort() { connection.close(); } /** * Returns a description of the {@link TcpResponse}. * * @return * A description of the {@link TcpResponse}. */ @Override public final String toString() { final StringBuilder sb = new StringBuilder(this.getClass().getName()) .append("(response=").append(response).append(", ") .append("(connection=").append(connection).append(')'); final String result = sb.toString(); return result; } } <file_sep>/pies-app/pies-app-proxy/pom.xml <?xml version="1.0" encoding="UTF-8"?> <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"> <description> This project aggregates PIES Proxy Application. </description> <modelVersion>4.0.0</modelVersion> <artifactId>pies-app-proxy</artifactId> <packaging>pom</packaging> <name>pies-app-proxy (PIES Proxy Application)</name> <url>${pies.project.url}</url> <licenses> <license> <name>${pies.project.license.name}</name> <url>${pies.project.license.url}</url> </license> </licenses> <inceptionYear>${pies.project.inceptionYear}</inceptionYear> <organization> <name>${pies.project.organization.name}</name> <url>${pies.project.organization.url}</url> </organization> <parent> <groupId>com.gl.vn.me.ko.pies</groupId> <artifactId>pies-app-parent</artifactId> <version>0.0.0-SNAPSHOT</version> <relativePath>../pies-app-parent/pom.xml</relativePath> </parent> <modules> <module>pies-app-proxy-parent</module> <module>pies-app-proxy-logic</module> </modules> <profiles> <profile> <id>assembly</id> <dependencies> <dependency> <groupId>com.gl.vn.me.ko.pies</groupId> <artifactId>pies-base-main</artifactId> <classifier>${pies.classifier.harness}</classifier> <type>zip</type> </dependency> <dependency> <groupId>com.gl.vn.me.ko.pies</groupId> <artifactId>pies-base-main</artifactId> <classifier>${pies.classifier.config}</classifier> <type>zip</type> </dependency> <dependency> <groupId>com.gl.vn.me.ko.pies</groupId> <artifactId>pies-platform-app</artifactId> <classifier>${pies.classifier.harness}</classifier> <type>zip</type> </dependency> <dependency> <groupId>com.gl.vn.me.ko.pies</groupId> <artifactId>pies-app-proxy-logic</artifactId> <classifier>${pies.classifier.config}</classifier> <type>zip</type> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-assembly-plugin</artifactId> </plugin> </plugins> </build> </profile> </profiles> </project><file_sep>/pies-base/pies-base-feijoa/src/main/java/com/gl/vn/me/ko/pies/base/feijoa/ExecutorUtil.java package com.gl.vn.me.ko.pies.base.feijoa; import static com.gl.vn.me.ko.pies.base.constant.Message.ARGUMENT_ILLEGAL; import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkNotNull; import com.gl.vn.me.ko.pies.base.constant.Message; import java.util.List; import java.util.concurrent.Executor; import java.util.concurrent.ExecutorService; import java.util.concurrent.TimeUnit; /** * This class provides various utility methods related to {@link Executor}s. */ public final class ExecutorUtil { /** * Performs a graceful shutdown of the supplied {@code executorService}. * * @param executorService * An {@link ExecutorService} to shutdown. * @param quietTime * During this amount of time {@code executorService} will continue to execute previously submitted tasks * but no new tasks will be accepted (see {@link ExecutorService#shutdown()}). * If {@code quietTime} has elapsed and {@code executorService} isn't {@linkplain ExecutorService#isTerminated() terminated} * then {@link ExecutorService#shutdownNow()} is invoked followed by the * {@link ExecutorService#awaitTermination(long, TimeUnit) awaitTermination(timeout - quietTime, timeUnit)} method. * <p> * This argument MUST NOT be greater than {@code timeout}. * @param timeout * The total amount of time this method is allowed to spend till return. * @param timeUnit * The time unit of the time arguments. * @return * {@link List} of tasks that never commenced execution (see {@link ExecutorService#shutdownNow()}). * */ public static final List<Runnable> shutdownGracefully( final ExecutorService executorService, final long quietTime, final long timeout, final TimeUnit timeUnit) { checkNotNull(executorService, Message.ARGUMENT_NULL, "first", "executorService"); checkArgument(quietTime >= 0, ARGUMENT_ILLEGAL, quietTime, "second", "quietTime", "Expected value must be nonnegative"); checkArgument(timeout >= 0, ARGUMENT_ILLEGAL, timeout, "third", "timeout", "Expected value must be nonnegative"); checkArgument(quietTime <= timeout, ARGUMENT_ILLEGAL, quietTime, "second", "quietTime", "Expected value must not be greater than the third argument (timeout)"); checkNotNull(timeUnit, Message.ARGUMENT_NULL, "fourth", "timeUnit"); final List<Runnable> result; boolean interrupted = false; executorService.shutdown(); try { executorService.awaitTermination(quietTime, timeUnit); } catch (final InterruptedException e) { interrupted = true; Thread.currentThread().interrupt(); executorService.shutdownNow(); } result = executorService.shutdownNow(); if (!interrupted) { try { executorService.awaitTermination(timeout - quietTime, timeUnit); } catch (final InterruptedException e) { Thread.currentThread().interrupt(); } } return result; } /** * Shortcut method for {@link #shutdownGracefully(ExecutorService, long, long, TimeUnit)} with sensible default values. * * @param executorService * An {@link ExecutorService} to shutdown. * @return * {@link List} of tasks that never commenced execution (see {@link ExecutorService#shutdownNow()}). */ public static final List<Runnable> shutdownGracefully(final ExecutorService executorService) { return shutdownGracefully(executorService, 1, 2, TimeUnit.SECONDS); } /** * Returns an unshutdownable view of the specified {@code executorService}. * Unshutdownable means that methods {@link ExecutorService#shutdown()} and {@link ExecutorService#shutdownNow()} always * throw an unchecked {@link Exception}. * * @param executorService * An {@link ExecutorService} for which an unshutdownable view is to be returned. * @return * An unshutdownable view of the specified {@code executorService}. */ public static final ExecutorService unshutdownable(final ExecutorService executorService) { checkNotNull(executorService, Message.ARGUMENT_NULL_SINGLE, "executorService"); return new UnshutdownableExecutorService(executorService); } private ExecutorUtil() { throw new UnsupportedOperationException(Message.INSTANTIATION_NOT_SUPPORTED); } } <file_sep>/misc/manual test/echoApplicationLog.sh #!/bin/bash #Set environment readonly MANUAL_TEST_LOCATION="/Users/male/Documents/programming/projects/pies/misc/manual test" readonly PIES_ECHO_APP_HOME_DIR_NAME="pies-app-echo" less "${MANUAL_TEST_LOCATION}/${PIES_ECHO_APP_HOME_DIR_NAME}/log/application.log" <file_sep>/pies-base/pies-base-main/src/main/java/com/gl/vn/me/ko/pies/base/thread/ApplicationUncaughtExceptionHandler.java package com.gl.vn.me.ko.pies.base.thread; import com.gl.vn.me.ko.pies.base.constant.Message; import com.gl.vn.me.ko.pies.base.main.Std; import com.google.common.annotations.VisibleForTesting; import com.google.common.base.Throwables; import java.io.PrintStream; import java.lang.Thread.UncaughtExceptionHandler; import javax.annotation.concurrent.Immutable; /** * This {@link UncaughtExceptionHandler} SHOULD be used for all threads where it possible besides the "main" thread. */ @Immutable public final class ApplicationUncaughtExceptionHandler implements UncaughtExceptionHandler { private static final ApplicationUncaughtExceptionHandler INSTANCE = new ApplicationUncaughtExceptionHandler(); static final ApplicationUncaughtExceptionHandler getInstance() { return INSTANCE; } private ApplicationUncaughtExceptionHandler() { } /** * This method is called from {@link #uncaughtException(Thread, Throwable)} and is required only for testing. * The method MAY be used in tests and MUST NOT be used elsewhere. * * @param t * The thread that is going to be terminated because of the uncaught {@link Throwable} {@code e}. * @param e * The uncaught {@link Throwable}. * @param printStream * {@link PrintStream} to use for printing information about {@code t} and {@code e}. * Information is printed by using {@link Std#println(String, Std.StreamType, PrintStream)} method. */ @VisibleForTesting final void processUncaughtException(final Thread t, final Throwable e, final PrintStream printStream) { final String msgFormat = "%s is going to be terminated because of the %s"; Std.println(Message.format(msgFormat, t, Throwables.getStackTraceAsString(e)), Std.StreamType.STDERR, printStream); } /** * Prints information about the thread that is going to be terminated and the cause to {@link System#err}. * * @param t * The thread that is going to be terminated because of the uncaught {@link Throwable} {@code e}. * @param e * The uncaught {@link Throwable}. */ /* * This method MUST delegate all work to the processUncaughtException(...) method for the sake of testability. */ @Override public final void uncaughtException(final Thread t, final Throwable e) { /* * There is no sense in checking preconditions * because any exception thrown by this method will be ignored by JVM. */ final PrintStream errStream = System.err; processUncaughtException(t, e, errStream); } } <file_sep>/misc/findClass.sh #!/bin/bash #This script performs search for compiled Java classes. #TODO check why it doesn't work #Outputs how to use the script. printHelp() { echo "The script performs search for compiled Java classes." echo "Parameters:" echo " lookFor" echo " Name of Java class to search for." echo " This parameter is case insensitive." echo " One MAY specify class name without package name, with package name," echo " or with ending of package name." echo " Alphanumerics, \"_\", \"$\" MAY be used as part of package name or a class name." echo " \".\" or \"/\" MAY be used as part of a package name." echo " One SHOULD specify value of this parameter within single quotes '...'." echo " searchRoot" echo " Search will be performed in this directory and all subdirectories." echo " If value of this parameter is not specified then 'thisScriptLocation/../' is used." echo "Examples:" echo " ./findClass.sh 'MyClass' - class name" echo " ./findClass.sh 'some/package/MyClass' - search for package name and class name" echo " ./findClass.sh 'ckage.MyClass' - search for part of package name (ending) and class name" echo " ./findClass.sh 'some.package.MyClass\$MyNestedClass' - search for nested class" echo " ./findClass.sh 'some/package/MyClass' /my/projects - search for class in '/my/projects' directory" echo " ./my/scripts/findClass.sh 'package.MyClass' . - search for class in current directory" echo "Notes:" echo " Execution of this script isn't fully pipelined," echo " for example at first it collects a list of all archive files under 'searchRoot' directory" echo " and then performs search in each file from the list." echo " Because of this drawback it MAY take quite a time before you'll start to see results" echo " if there are many files under the 'searchRoot' directory." } #Checks if a string contains the specified substring. #Outputs "true" if a string contains the specified substring and "false" otherwise. # #${1} - A string to test. #${2} - A substring to test. contains() { local STRING="${1}" local SUBSTRING="${2}" case "${STRING}" in *"${SUBSTRING}"* ) echo "true";; * ) echo "false";; esac } #Suppress errors output, e.g. "access denied" messages. #exec 2>/dev/null #Print help if no arguments are specified if [ -z "${1}" ] || [ ${1} == "-h" ] || [ ${1} == "-help" ] || [ ${1} == "--help" ] then printHelp exit 0 fi #Directory that contains this script. readonly THIS_SCRIPT_DIRNAME=`cd "$(dirname "${0}")"; pwd` readonly INPUT_LOOK_FOR="${1}" readonly INPUT_SEARCH_ROOT="${2}" #This action will help us if only class name (without a package) is specified if [ `contains "${INPUT_LOOK_FOR}" "."` == "true" ] || [ `contains "${INPUT_LOOK_FOR}" "/"` == "true" ] then readonly LOOK_FOR="${INPUT_LOOK_FOR}" else readonly LOOK_FOR=".${INPUT_LOOK_FOR}" fi #Name of the class without package readonly SHORT_CLASS_NAME=`echo "${LOOK_FOR}" | sed -e "s/^.*\(\.\|\/\)\([^\.^\/\]*\)$/\2/"` #Name of the class package. "/" is used for separation of package name elements, "$" are escaped. readonly PACKAGE_NAME_ESCAPED_FOR_GREP=`echo "${LOOK_FOR}" | sed -e "s/^\(.*\(\.\|\/\)\)[^\.^\/\]*$/\1/" \ -e "s/\./\//g" -e "s/\\\\$/\\\\\\\\$/g"` readonly CLASS_FILE_ENDING_FOR_GREP="\.class$" readonly JAR_FILE_ENDING_FOR_GREP=".*\.jar$" readonly ZIP_FILE_ENDING_FOR_GREP=".*\.zip$" #Search will be performed in SEARCH_ROOT directory and all subdirectories. if [ -z "${INPUT_SEARCH_ROOT}" ] then readonly SEARCH_ROOT=`dirname "${THIS_SCRIPT_DIRNAME}"` else readonly SEARCH_ROOT="${INPUT_SEARCH_ROOT}" fi #TODO use `readlink --canonicalize \"${SEARCH_ROOT}\"` instead of \"${SEARCH_ROOT}\" when it will be fixed in Mac OS X echo "Search for ${INPUT_LOOK_FOR} in \"${SEARCH_ROOT}\"" #Looking for LOOK_FOR_IN_ARCHIVE pattern in archive file contents by using grep #Replace all periods "." with slashes "/", escape dollars "$" and add CLASS_FILE_ENDING_FOR_GREP readonly LOOK_FOR_IN_ARCHIVE=`echo "${LOOK_FOR}" | \ sed -e "s/\./\//g" -e "s/\\\\$/\\\\\\\\$/g"`"${CLASS_FILE_ENDING_FOR_GREP}" echo " Search inside archive files (JAR and ZIP)" echo " Results:" readonly ARCHIVE_FILES=`find "${SEARCH_ROOT}" -type f | \ grep -i "${JAR_FILE_ENDING_FOR_GREP}\|${ZIP_FILE_ENDING_FOR_GREP}"` FOUND="false" #Read ARCHIVE_FILES line by line in ARCHIVE_FILE while read ARCHIVE_FILE do if ! [ -z "${ARCHIVE_FILE}" ] then unzip -v "${ARCHIVE_FILE}" | grep -i "${LOOK_FOR_IN_ARCHIVE}" > /dev/null #${?} is the return status of the last command; grep in our case if [ "${?}" == 0 ] then FOUND="true" echo " ${ARCHIVE_FILE}" fi fi done <<<"${ARCHIVE_FILES}" if [ "${FOUND}" == "false" ] then echo " no results" fi echo "" #Looking for LOOK_FOR_CLASS_FILE pattern in class file names by using grep (search of files that aren't packed) readonly SHORT_CLASS_NAME_ESCAPED_FOR_GREP=`echo "${SHORT_CLASS_NAME}" | sed -e "s/\\\\$/\\\\\\\\$/g"` readonly LOOK_FOR_CLASS_FILE="/${SHORT_CLASS_NAME_ESCAPED_FOR_GREP}${CLASS_FILE_ENDING_FOR_GREP}" echo " Search outside archive files" echo " Results:" readonly CLASS_FILES=`find "${SEARCH_ROOT}" -type f | grep -i "${LOOK_FOR_CLASS_FILE}"` FOUND="false" #Read CLASS_FILES line by line in CLASS_FILE while read CLASS_FILE do if ! [ -z "${CLASS_FILE}" ] then less -f "${CLASS_FILE}" | grep -i "${PACKAGE_NAME_ESCAPED_FOR_GREP}${SHORT_CLASS_NAME_ESCAPED_FOR_GREP}" \ > /dev/null #${?} is the return status of the last command; grep in our case if [ "${?}" == 0 ] then FOUND="true" echo " ${CLASS_FILE}" fi fi done <<<"${CLASS_FILES}" if [ "${FOUND}" == "false" ] then echo " no results" fi<file_sep>/pies-base/pies-base-doc/src/main/java/com/gl/vn/me/ko/pies/base/doc/Defaults.java package com.gl.vn.me.ko.pies.base.doc; import java.lang.annotation.Documented; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import java.util.Collection; import java.util.Collections; import java.util.Enumeration; import java.util.List; import java.util.stream.Stream; import javax.annotation.Nonnull; import javax.annotation.Nullable; import javax.annotation.ParametersAreNonnullByDefault; import javax.annotation.concurrent.Immutable; import javax.annotation.concurrent.ThreadSafe; /** * Specifies rules that are applied to a package. * <p> * The key words "MUST", "MUST NOT", "REQUIRED", "SHALL", "SHALL NOT", "SHOULD", "SHOULD NOT", "RECOMMENDED", "MAY", and * "OPTIONAL" here and in all packages annotated with this annotations are to be interpreted as described in * <a href="http://tools.ietf.org/html/rfc2119">RFC 2119</a>. * <p> * Default properties of all classes, interfaces, methods and constructors in the package: * <ol> * <li>Classes SHOULD be treated mutable and not thread-safe unless otherwise is explicitly specified ({@link Immutable} * and {@link ThreadSafe} annotation SHOULD be used for this purpose).</li> * <li>Arguments and return values of methods MUST be non-{@code null} unless otherwise is explicitly specified. It * SHOULD be specified by the {@link ParametersAreNonnullByDefault} annotation on package/class and/or by {@link Nullable}/ * {@link Nonnull} annotations on fields/local variables/methods.</li> * <li>Methods and constructors MUST NOT modify modifiable<b><sup>*</sup></b> objects passed as arguments unless * otherwise is explicitly specified.</li> * <li>Modifications of modifiable objects returned from methods MUST NOT affect the state of the object on which the * method is invoked unless otherwise is explicitly specified. E.g. modification of contents of a {@link List} returned * from {@code someObject.getList()} method MUST NOT affect state of the {@code someObject}.</li> * <li>If a method returns an object that is supposed to be modifiable the object MUST be modifiable unless otherwise is * explicitly specified.</li> * <li>{@link Enumeration}, {@link Iterable}, {@link Stream}, array arguments and return values MUST NOT contain {@code null} * elements unless otherwise is explicitly specified.</li> * <li>{@link Enumeration}, {@link Iterable}, {@link Stream}, array arguments and return values SHOULD NOT contain duplicate * elements (see {@link Object#equals(Object)}) unless otherwise is explicitly specified. In some obvious cases an explicit * specification MAY be omitted (for example in case of a {@code byte[]}).</li> * <li>Any timeouts MUST be interpreted as approximate periods of real time. * See {@link Object#wait(long)} for that "more or less" phrase.</li> * <li>One SHOULD remember that format of {@link String}s returned by any method that overrides {@link Object#toString()} * MAY be changed at any time unless the format is explicitly specified in the method specification.</li> * </ol> * <p> * <b><sup>*</sup></b> Here and in any package annotated with {@link Defaults} we distinguish immutable and unmodifiable * Java objects. <i>Unmodifiable object</i> (aka <i>read-only object</i>) is an object that is not intended to be * modified via its API (<i>modifiable object</i> is the opposite), but it still MAY change its observable state. E.g. * object returned by {@link Collections#unmodifiableCollection(java.util.Collection)} can't be modified via it's API, * but because such an object is just a view of an actual {@link Collection}, its observable state MAY be modified. * <i>Immutable object</i> is an object which observable state can't be changed once you have a reference to the object. * Observable state of an immutable object can't even be changed because of publication via data race), and because of * this immutable objects are inherently thread-safe just as specified by {@link Immutable} annotation. */ @Documented @Retention(RetentionPolicy.CLASS) @Target({ElementType.PACKAGE}) public @interface Defaults { } <file_sep>/pies-platform/pies-platform-server/pom.xml <?xml version="1.0" encoding="UTF-8"?> <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"> <description> Aggregates functionality that is needed to construct an I/O server. </description> <modelVersion>4.0.0</modelVersion> <artifactId>pies-platform-server</artifactId> <packaging>jar</packaging> <name>pies-platform-server</name> <url>${pies.project.url}</url> <licenses> <license> <name>${pies.project.license.name}</name> <url>${pies.project.license.url}</url> </license> </licenses> <inceptionYear>${pies.project.inceptionYear}</inceptionYear> <organization> <name>${pies.project.organization.name}</name> <url>${pies.project.organization.url}</url> </organization> <parent> <groupId>com.gl.vn.me.ko.pies</groupId> <artifactId>pies-platform-parent</artifactId> <version>0.0.0-SNAPSHOT</version> <relativePath>../pies-platform-parent/pom.xml</relativePath> </parent> <dependencies> <dependency> <groupId>com.google.code.findbugs</groupId> <artifactId>jsr305</artifactId> </dependency> <dependency> <groupId>io.netty</groupId> <artifactId>netty-all</artifactId> </dependency> <dependency> <groupId>com.google.inject</groupId> <artifactId>guice</artifactId> </dependency> <dependency> <groupId>javax.inject</groupId> <artifactId>javax.inject</artifactId> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-api</artifactId> </dependency> <dependency> <groupId>javax.json</groupId> <artifactId>javax.json-api</artifactId> </dependency> <dependency> <groupId>com.google.code.findbugs</groupId> <artifactId>annotations</artifactId> </dependency> <dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-pool2</artifactId> </dependency> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <scope>test</scope> </dependency> <dependency> <groupId>org.mockito</groupId> <artifactId>mockito-all</artifactId> <scope>test</scope> </dependency> <dependency><!-- implementation of javax.json:javax.json-api --> <groupId>org.glassfish</groupId> <artifactId>javax.json</artifactId> <scope>test</scope> </dependency> <dependency> <groupId>com.gl.vn.me.ko.pies</groupId> <artifactId>pies-base-doc</artifactId> </dependency> <dependency> <groupId>com.gl.vn.me.ko.pies</groupId> <artifactId>pies-base-constant</artifactId> </dependency> <dependency> <groupId>com.gl.vn.me.ko.pies</groupId> <artifactId>pies-base-throwable</artifactId> </dependency> <dependency> <groupId>com.gl.vn.me.ko.pies</groupId> <artifactId>pies-base-feijoa</artifactId> </dependency> <dependency><!-- SLF4J implementation for tests --> <groupId>org.slf4j</groupId> <artifactId>slf4j-nop</artifactId> <scope>test</scope> </dependency> </dependencies> </project><file_sep>/pies-base/pies-base-main/src/main/java/com/gl/vn/me/ko/pies/base/thread/ApplicationThread.java package com.gl.vn.me.ko.pies.base.thread; import io.netty.util.internal.ThreadLocalRandom; import javax.annotation.Nullable; import javax.annotation.concurrent.ThreadSafe; /** * All Application threads SHOULD be instances of this class unless a {@link java.util.concurrent.ForkJoinWorkerThread} * is * required. {@link ApplicationThreadFactory} MUST be used to obtain instance of this class. */ @ThreadSafe public class ApplicationThread extends Thread { /** * Constructs an instance of {@link ApplicationThread}. * * @param target * Object which {@link Runnable#run()} method is invoked when this thread is started. * If {@code target} is {@code null} then the {@link ApplicationThread#run()} method of the constructed * {@link ApplicationThread} does nothing. */ ApplicationThread(@Nullable final Runnable target) { super(target); } /** * Acts like {@link Thread#run()} method, but executes WA for * <a href="https://github.com/netty/netty/issues/2170">Netty ThreadLocalRandom bug</a> before invocation of the * {@link Thread#run()} method. */ @Override public final void run() { /* * This is a WA for Netty ThreadLocalRandom bug https://github.com/netty/netty/issues/2170. * TODO remove this WA when bug will be fixed * (changes are in master and most likely will be published in the 5.0.0.Alpha2). */ ThreadLocalRandom.current(); super.run(); } /** * Returns a description of the {@link ApplicationThread}. * This description is prefixed with {@code "ApplicationThread"} and contains thread name, thread priority, * and thread group name, e.g. {@code "ApplicationThread[pies-thread-main, 5, main]"}. * * @return * A description of the {@link ApplicationThread}. */ @Override public final String toString() { final ThreadGroup group = getThreadGroup(); final String groupName = group != null ? group.getName() : null; final StringBuilder sb = new StringBuilder(getClass().getName()) .append("(name=").append(getName()) .append(", priority=").append(getPriority()) .append(", group=").append(groupName).append(')'); final String result = sb.toString(); return result; } } <file_sep>/pies-base/pies-base-config/src/main/java/com/gl/vn/me/ko/pies/base/config/PropsConfig.java package com.gl.vn.me.ko.pies.base.config; import com.gl.vn.me.ko.pies.base.feijoa.Stringable; import com.gl.vn.me.ko.pies.base.feijoa.StringableConverter; import java.math.BigDecimal; import java.math.BigInteger; import java.util.List; import java.util.Optional; import java.util.Set; import javax.annotation.Nullable; import javax.annotation.concurrent.ThreadSafe; /** * Represents a configuration that consists of properties. * <p> * A property is an entity that is identified by {@link PropertyName} and MAY have a value. Value of a property MUST be * consistent with the {@link PropertyType}. A value of a property MAY be treated as some other {@link PropertyType} * if it's possible to convert the value to that type. * A property can either be single or multiple. Single properties MAY only have a single value * and multiple properties MAY have multiple values. * <p> * A property is undefined if it is not specified in the configuration or its value is {@code null}. */ @ThreadSafe public interface PropsConfig { /** * Returns value of a property of the type {@code type}. * * @param name * Identifier of a property. * @param type * {@link PropertyType} of a property. * @param <T> * A Java type of value of a property. * @return * Value of a property. * @throws NoSuchPropertyException * If the property identified by the {@code name} is undefined. */ <T> T get(PropertyName name, PropertyType<T> type) throws NoSuchPropertyException; /** * Returns value of a property of the type {@link PropertyType#BIG_DECIMAL}. * * @param name * Identifier of a property. * @param defaultValue * Value to use if the property identified by the {@code name} is undefined. * @param type * {@link PropertyType} of a property. * @param <T> * A Java type of value of a property. * @return * Value of a property or {@code defaultValue} if the property is undefined. * The returned {@link Optional} isn't {@link Optional#isPresent() present} if and only if the property is undefined and * {@code defaultValue} is {@code null}. */ <T> Optional<T> get(PropertyName name, @Nullable T defaultValue, PropertyType<T> type); /** * Returns value of a property of the type {@link PropertyType#BIG_DECIMAL}. * * @param name * Identifier of a property. * @return * Value of a property. * @throws NoSuchPropertyException * If the property identified by the {@code name} is undefined. */ BigDecimal getBigDecimal(PropertyName name) throws NoSuchPropertyException; /** * Returns value of a property of the type {@link PropertyType#BIG_DECIMAL}. * * @param name * Identifier of a property. * @param defaultValue * Value to use if the property identified by the {@code name} is undefined. * @return * Value of a property or {@code defaultValue} if the property is undefined. * The returned {@link Optional} isn't {@link Optional#isPresent() present} if and only if the property is undefined and * {@code defaultValue} is {@code null}. */ Optional<BigDecimal> getBigDecimal(PropertyName name, @Nullable BigDecimal defaultValue); /** * Returns value of a property of the type {@link PropertyType#BIG_INTEGER}. * * @param name * Identifier of a property. * @return * Value of a property. * @throws NoSuchPropertyException * If the property identified by the {@code name} is undefined. */ BigInteger getBigInteger(PropertyName name) throws NoSuchPropertyException; /** * Returns value of a property of the type {@link PropertyType#BIG_INTEGER}. * * @param name * Identifier of a property. * @param defaultValue * Value to use if the property identified by the {@code name} is undefined. * @return * Value of a property or {@code defaultValue} if the property is undefined. * The returned {@link Optional} isn't {@link Optional#isPresent() present} if and only if the property is undefined and * {@code defaultValue} is {@code null}. */ Optional<BigInteger> getBigInteger(PropertyName name, @Nullable BigInteger defaultValue); /** * Returns value of a property of the type {@link PropertyType#BOOLEAN}. * * @param name * Identifier of a property. * @return * Value of a property. * @throws NoSuchPropertyException * If the property identified by the {@code name} is undefined. */ Boolean getBoolean(PropertyName name) throws NoSuchPropertyException; /** * Returns value of a property of the type {@link PropertyType#BOOLEAN}. * * @param name * Identifier of a property. * @param defaultValue * Value to use if the property identified by the {@code name} is undefined. * @return * Value of a property or {@code defaultValue} if the property is undefined. * The returned {@link Optional} isn't {@link Optional#isPresent() present} if and only if the property is undefined and * {@code defaultValue} is {@code null}. */ Optional<Boolean> getBoolean(PropertyName name, @Nullable Boolean defaultValue); /** * Returns value of a property of the type {@link PropertyType#DOUBLE}. * * @param name * Identifier of a property. * @return * Value of a property. * @throws NoSuchPropertyException * If the property identified by the {@code name} is undefined. */ Double getDouble(PropertyName name) throws NoSuchPropertyException; /** * Returns value of a property of the type {@link PropertyType#DOUBLE}. * * @param name * Identifier of a property. * @param defaultValue * Value to use if the property identified by the {@code name} is undefined. * @return * Value of a property or {@code defaultValue} if the property is undefined. * The returned {@link Optional} isn't {@link Optional#isPresent() present} if and only if the property is undefined and * {@code defaultValue} is {@code null}. */ Optional<Double> getDouble(PropertyName name, @Nullable Double defaultValue); /** * Returns value of a property of the type {@link PropertyType#INTEGER}. * * @param name * Identifier of a property. * @return * Value of a property. * @throws NoSuchPropertyException * If the property identified by the {@code name} is undefined. */ Integer getInteger(PropertyName name) throws NoSuchPropertyException; /** * Returns value of a property of the type {@link PropertyType#INTEGER}. * * @param name * Identifier of a property. * @param defaultValue * Value to use if the property identified by the {@code name} is undefined. * @return * Value of a property or {@code defaultValue} if the property is undefined. * The returned {@link Optional} isn't {@link Optional#isPresent() present} if and only if the property is undefined and * {@code defaultValue} is {@code null}. */ Optional<Integer> getInteger(PropertyName name, @Nullable Integer defaultValue); /** * Returns value of a property of the type {@link PropertyType#LIST_OF_STRINGS}. * * @param name * Identifier of a property. * @return * Value of a property. The returned {@link List} is unmodifiable and MAY contain duplicate elements. * @throws NoSuchPropertyException * If the property identified by the {@code name} is undefined. */ List<String> getListOfStrings(PropertyName name) throws NoSuchPropertyException; /** * Returns value of a property of the type {@link PropertyType#LIST_OF_STRINGS}. * * @param name * Identifier of a property. * @param defaultValue * Value to use if the property identified by the {@code name} is undefined. * @return * Value of a property or {@code defaultValue} if the property is undefined. * The returned {@link List} is unmodifiable unless this {@link List} is the {@code defaultValue}, * and MAY contain duplicate elements. The {@code defaultValue} is returned as is. * The returned {@link Optional} isn't {@link Optional#isPresent() present} if and only if the property is undefined and * {@code defaultValue} is {@code null}. */ Optional<List<String>> getListOfStrings(PropertyName name, @Nullable List<String> defaultValue); /** * Returns value of a property of the type {@link PropertyType#LONG}. * * @param name * Identifier of a property. * @return * Value of a property. * @throws NoSuchPropertyException * If the property identified by the {@code name} is undefined. */ Long getLong(PropertyName name) throws NoSuchPropertyException; /** * Returns value of a property of the type {@link PropertyType#LONG}. * * @param name * Identifier of a property. * @param defaultValue * Value to use if the property identified by the {@code name} is undefined. * @return * Value of a property or {@code defaultValue} if the property is undefined. * The returned {@link Optional} isn't {@link Optional#isPresent() present} if and only if the property is undefined and * {@code defaultValue} is {@code null}. */ Optional<Long> getLong(PropertyName name, @Nullable Long defaultValue); /** * Returns value of a property of the type {@link PropertyType#SET_OF_STRINGS}. * * @param name * Identifier of a property. * @return * Value of a property. The returned {@link Set} is unmodifiable and is ordered. * @throws NoSuchPropertyException * If the property identified by the {@code name} is undefined. */ Set<String> getSetOfStrings(PropertyName name) throws NoSuchPropertyException; /** * Returns value of a property of the type {@link PropertyType#SET_OF_STRINGS}. * * @param name * Identifier of a property. * @param defaultValue * Value to use if the property identified by the {@code name} is undefined. * @return * Value of a property or {@code defaultValue} if the property is undefined. * The returned {@link Set} is unmodifiable unless this {@link Set} is the {@code defaultValue}, and is ordered. * The {@code defaultValue} is returned as is. * The returned {@link Optional} isn't {@link Optional#isPresent() present} if and only if the property is undefined and * {@code defaultValue} is {@code null}. */ Optional<Set<String>> getSetOfStrings(PropertyName name, @Nullable Set<String> defaultValue); /** * Returns value of a property of the type {@link PropertyType#STRING}. * * @param name * Identifier of a property. * @return * Value of a property. * @throws NoSuchPropertyException * If the property identified by the {@code name} is undefined. */ String getString(PropertyName name) throws NoSuchPropertyException; /** * Returns value of a property of the type {@link PropertyType#STRING}. * * @param name * Identifier of a property. * @param defaultValue * Value to use if the property identified by the {@code name} is undefined. * @return * Value of a property or {@code defaultValue} if the property is undefined. * The returned {@link Optional} isn't {@link Optional#isPresent() present} if and only if the property is undefined and * {@code defaultValue} is {@code null}. */ Optional<String> getString(PropertyName name, @Nullable String defaultValue); /** * Returns value of a property of the type {@code T}. * * @param <T> * Type of a property. * @param name * Identifier of a property. * @param converter * {@link StringableConverter} that knows how to restore object of type {@code T} from {@link String} * value of the property. * @return * Value of a property. * @throws NoSuchPropertyException * If the property identified by the {@code name} is undefined. */ <T extends Stringable> T getStringable(PropertyName name, StringableConverter<T> converter) throws NoSuchPropertyException; /** * Returns value of a property of the type {@code T}. * * @param <T> * Type of a property. * @param name * Identifier of a property. * @param defaultValue * Value to use if the property identified by the {@code name} is undefined. * @param converter * {@link StringableConverter} that knows how to restore object of type {@code T} from {@link String} * value of the property. * @return * Value of a property or {@code defaultValue} if the property is undefined. * The returned {@link Optional} isn't {@link Optional#isPresent() present} if and only if the property is undefined and * {@code defaultValue} is {@code null}. */ <T extends Stringable> Optional<T> getStringable(PropertyName name, @Nullable T defaultValue, StringableConverter<T> converter); } <file_sep>/pies-base/pies-base-main/src/harness/functions.sh #!/bin/bash #This file provides functions that MAY be used by other shell scripts. #Please note that if execution of a shell script is terminated because of the function provided here, #then exit status is -1. #TERM signal is used to designate failure. trap "exit -1" TERM #Stops execution of a script in case of failure. exitError() { kill -s TERM $$ } #Outputs error message with "Error: " prefix to the stderr. # #${1} - Error message. echoError() { echo "Error: ${1}" 1>&2 } #Outputs error message to the stderr. #Also specifies name of the function that calls echoFuncError() function. # #${1} - Error message. echoFuncError() { echo "Error in function ${FUNCNAME[1]}: ${1}" 1>&2 } #Outputs the provided string by using echo command. #This function only do output if there is a VERBOSE variable that is set to "true". #Possible values of VERBOSE: # "true" # "false" # #${1} - String for output. log() { if [ -z "${VERBOSE}" ] then echoFuncError "VERBOSE variable is not set" exitError fi if [ "${VERBOSE}" == "true" ] then echo "${1}" fi } #Checks if a string contains the specified substring. #Outputs "true" if a string contains the specified substring and "false" otherwise. # #${1} - A string to test. #${2} - A substring to test. contains() { local STRING="${1}" local SUBSTRING="${2}" case "${STRING}" in *"${SUBSTRING}"* ) echo "true";; * ) echo "false";; esac } #Outputs the type of operating system. #Possible output values: # "Windows-Cygwin" # "UN*X" getOperatingSystemType() { UNAME=`uname -s` RESULT="" if [ `contains "${UNAME}" "CYGWIN"` == "true" ] then RESULT="Windows-Cygwin" else RESULT="UN*X" fi echo "${RESULT}" } #Outputs character that separates elements in a list of file paths. #Result is based on the value of OPERATING_SYSTEM_TYPE variable. #Possible values of OPERATING_SYSTEM_TYPE: # "Windows-Cygwin" # "UN*X" getFilePathSeparator() { if [ -z "${OPERATING_SYSTEM_TYPE}" ] then echoFuncError "OPERATING_SYSTEM_TYPE variable is not set" exitError fi local RESULT="" if [ "${OPERATING_SYSTEM_TYPE}" == "Windows-Cygwin" ] then RESULT=";" elif [ "${OPERATING_SYSTEM_TYPE}" == "UN*X" ] then RESULT=":" fi echo "${RESULT}" } #Creates a file and all necessary directories if file not exists. # #${1} - Name of the file to create. createFile() { if ! [ -e "${1}" ] then local DIRECTORY=`dirname "${1}"` mkdir -p "${DIRECTORY}" #create a file with the name "${1}" > "${1}" fi } #Renames the specified file by adding current date and time. #For example file ./someFile will be renamed to ./someFile__Y-m-d_H-M-S_z, #where Y, m, ... represent current date and time. # #${1} - Name of the file to rename. backupFile() { local RESULT="" if [ -e "${1}" ] then RESULT="${1}__`date +%Y-%m-%d_%H-%M-%S_%z`" mv "${1}" "${RESULT}" fi echo "${RESULT}" } #Transforms list of paths that MAY be in the Windows-Cygwin format to Windows format. #This method uses FILE_PATH_SEPARATOR variable. # #${1} - List of paths that are separated by character specified in the FILE_PATH_SEPARATOR variable. cygwinToWindowsPath() { if [ -z "${FILE_PATH_SEPARATOR}" ] then echoFuncError "FILE_PATH_SEPARATOR variable is not set" exitError fi local readonly CYGWIN_PREFIX="cygdrive" ORIGINAL_IFS="${IFS}" IFS="${FILE_PATH_SEPARATOR}" read -a PATHS <<< "${1}" IFS="${ORIGINAL_IFS}" for PATH_WINDOWS_CYGWIN in "${PATHS[@]}" do #The following operations are performed here by using sed: # remove CYGWIN_PREFIX from the path; by some reason this also removes all backslashes "\" # append ":" to Windows volume label # replace each slash "/" with backslash "\" local PATH_WINDOWS=`echo "${PATH_WINDOWS_CYGWIN}" | \ sed -e "s/^\/${CYGWIN_PREFIX}\/\(.*\)$/\1/" \ -e "s/^\([^\/]*\)\(\/.*\)$/\1:\2/" \ -e "s/\//\\\\\/g"` if [ -z "${RESULT}" ] then RESULT="${PATH_WINDOWS}" else RESULT="${RESULT}${FILE_PATH_SEPARATOR}${PATH_WINDOWS}" fi done echo "${RESULT}" } #Replaces all spaces " " with escaped spaces "\ ". # #${1} - String where to escape spaces. escapeSpacesInPath() { echo `echo "${1}" | sed -e "s/[[:space:]]/\\\\\ /g"` } #Outputs Epoch time the file was last modified. # #${1} - Name of the file. getLastModifyTime() { if stat -f %m "${1}" >/dev/null 2>&1 then #BDS syntax echo `stat -f %m "${1}"` else #GNU/Linux syntax echo `stat -c %Y "${1}"` fi }<file_sep>/pies-app/pies-app-initiator/pies-app-initiator-logic/src/harness/say.sh #!/bin/bash #This script MAY be used to initiate interaction (dialog) between PIES Initiator application and other PIES Applications. #This script MAY return -1 in if execution of function from functions.sh failed. #Directory that contains this script. readonly THIS_SCRIPT_DIRNAME=`cd "$(dirname "${0}")"; pwd` #Application Home directory. APP_HOME=`dirname "${THIS_SCRIPT_DIRNAME}"` source "${THIS_SCRIPT_DIRNAME}/functions.sh" source "${THIS_SCRIPT_DIRNAME}/environment.sh" #A phrase to say. readonly PHRASE="${1}" #Lock File - a file used to prevent repeated start of the same instance of Application. readonly APP_LOCK_FILE="${APP_RUNTIME_LOCATION}/application.lock" readonly APP_LOCK_FILE_LAST_MODIFICATION_DATE=`getLastModifyTime "${APP_LOCK_FILE}"` #Check that APP_LOCK_FILE exists. if ! [ -e "${APP_LOCK_FILE}" ] then echoError "Can't initiate dialog because Initiator isn't working: Lock File ${APP_LOCK_FILE} doesn't exist" exitError fi #Control Server address. CONTROL_SERVER_ADDRESS=`cat "${APP_LOCK_FILE}"` #Initiate dialog. log \ "Initiating dialog by executing the following command:" SAY_COMMAND="curl \ http://${CONTROL_SERVER_ADDRESS}/utf8string/${PHRASE} -XPOST \ -s -S --connect-timeout 1 --max-time 5" log " ${SAY_COMMAND}" SAY_RESPONSE=`eval "${SAY_COMMAND}"` SAY_STATUS="${?}" log "" if [ "${SAY_STATUS}" == "0" ] #last process is completed successfully, i.e. with exit status 0 then log "Control Server response:" log " ${SAY_RESPONSE}" log "" fi<file_sep>/pies-platform/pies-platform-server/src/main/java/com/gl/vn/me/ko/pies/platform/server/rest/RestRequestHandlingException.java package com.gl.vn.me.ko.pies.platform.server.rest; import com.gl.vn.me.ko.pies.base.throwable.ApplicationException; import javax.annotation.Nullable; /** * Indicates that handling of a {@link RestRequest} has failed. */ public final class RestRequestHandlingException extends ApplicationException { private static final long serialVersionUID = 0; /** * Creates an instance of {@link RestRequestHandlingException}. */ public RestRequestHandlingException() { } /** * Creates an instance of {@link RestRequestHandlingException}. * * @param message * The detail message which is saved for later retrieval by the {@link #getMessage()} method. */ public RestRequestHandlingException(@Nullable final String message) { super(message); } /** * Creates an instance of {@link RestRequestHandlingException}. * * @param message * The detail message which is saved for later retrieval by the {@link #getMessage()} method. * @param cause * The cause which is saved for later retrieval by the {@link #getCause()} method. */ public RestRequestHandlingException(@Nullable final String message, @Nullable final Throwable cause) { super(message, cause); } /** * Creates an instance of {@link RestRequestHandlingException}. * * @param cause * The cause which is saved for later retrieval by the {@link #getCause()} method. */ public RestRequestHandlingException(@Nullable final Throwable cause) { super(cause); } } <file_sep>/pies-base/pies-base-config/src/main/java/com/gl/vn/me/ko/pies/base/config/app/package-info.java /** * Contains Application-specific API to work with configurations. */ @com.gl.vn.me.ko.pies.base.doc.Defaults @javax.annotation.ParametersAreNonnullByDefault package com.gl.vn.me.ko.pies.base.config.app; <file_sep>/pies-platform/pies-platform-server/src/test/java/com/gl/vn/me/ko/pies/platform/server/tcp/TestTcpServer.java package com.gl.vn.me.ko.pies.platform.server.tcp; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; import io.netty.bootstrap.ServerBootstrap; import io.netty.channel.nio.NioEventLoopGroup; import io.netty.util.concurrent.Future; import java.net.InetSocketAddress; import org.junit.After; import org.junit.Before; import org.junit.Test; public final class TestTcpServer { private static final class TcpServerExtended extends TcpServer { @SuppressWarnings("unchecked") private static final TcpServerExtended newInstance() { final Future<?> shutdownFuture = mock(Future.class); final NioEventLoopGroup bossEventLoopGroup = mock(NioEventLoopGroup.class); when(bossEventLoopGroup.shutdownGracefully()).thenReturn((Future)shutdownFuture); final NioEventLoopGroup workerEventLoopGroup = mock(NioEventLoopGroup.class); when(workerEventLoopGroup.shutdownGracefully()).thenReturn((Future)shutdownFuture); return new TcpServerExtended( new ServerBootstrap(), mock(InetSocketAddress.class), bossEventLoopGroup, workerEventLoopGroup); } private int shutdownHookInvocationCount = 0; private TcpServerExtended( final ServerBootstrap serverBootstrap, final InetSocketAddress address, final NioEventLoopGroup bossEventLoopGroup, final NioEventLoopGroup workerEventLoopGroup ) { super(serverBootstrap, address, bossEventLoopGroup, workerEventLoopGroup); } @Override protected void shutdownHook() { shutdownHookInvocationCount++; } } private NioEventLoopGroup bossEventLoopGroup; private NioEventLoopGroup workerEventLoopGroup; @SuppressFBWarnings( value = "UWF_FIELD_NOT_INITIALIZED_IN_CONSTRUCTOR", justification = "The field is initialized in setUp() method") private TcpServer server; public TestTcpServer() { } @Before @SuppressWarnings("unchecked") public final void setUp() { final Future<?> shutdownFuture = mock(Future.class); bossEventLoopGroup = mock(NioEventLoopGroup.class); when(bossEventLoopGroup.shutdownGracefully()).thenReturn((Future)shutdownFuture); workerEventLoopGroup = mock(NioEventLoopGroup.class); when(workerEventLoopGroup.shutdownGracefully()).thenReturn((Future)shutdownFuture); server = new TcpServer(new ServerBootstrap(), mock(InetSocketAddress.class), bossEventLoopGroup, workerEventLoopGroup); } @After public final void teadDown() { server.shutdown(); } @Test public final void shutdown() { server.activate(); server.shutdown(); assertFalse("Assert that server isn't active", server.getState()); verify(bossEventLoopGroup, times(1)).shutdownGracefully(); verify(workerEventLoopGroup, times(1)).shutdownGracefully(); } @Test public final void shutdownIdempotence() { final TcpServerExtended server = TcpServerExtended.newInstance(); server.activate(); server.shutdown(); server.shutdown(); assertEquals("Assert that shutdownHook was invoked exactly once", 1, server.shutdownHookInvocationCount); } } <file_sep>/pies-base/pies-base-main/src/main/java/com/gl/vn/me/ko/pies/base/di/package-info.java /** * Contains API that together with {@link com.gl.vn.me.ko.pies.base.main.GuiceLocator} simplifies usage of dependency injection * (DI) pattern. This API is based on Guice framework. */ @com.gl.vn.me.ko.pies.base.doc.Defaults @javax.annotation.ParametersAreNonnullByDefault package com.gl.vn.me.ko.pies.base.di; <file_sep>/pies-parent/pom.xml <?xml version="1.0" encoding="UTF-8"?> <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"> <description> The top parent project. This project is an ancestor of any other project with groupId 'com.gl.vn.me.ko.pies'. </description> <modelVersion>4.0.0</modelVersion> <groupId>com.gl.vn.me.ko.pies</groupId> <artifactId>pies-parent</artifactId> <version>0.0.0-SNAPSHOT</version> <packaging>pom</packaging> <name>pies-parent</name> <url>${pies.project.url}</url> <licenses> <license> <name>${pies.project.license.name}</name> <url>${pies.project.license.url}</url> </license> </licenses> <inceptionYear>${pies.project.inceptionYear}</inceptionYear> <organization> <name>${pies.project.organization.name}</name> <url>${pies.project.organization.url}</url> </organization> <properties> <pies.charset>UTF-8</pies.charset> <project.build.sourceEncoding>${pies.charset}</project.build.sourceEncoding> <project.reporting.outputEncoding>${pies.charset}</project.reporting.outputEncoding> <pies.project.url>https://github.com/stIncMale/pies</pies.project.url> <pies.project.license.name>WTFPL</pies.project.license.name> <pies.project.license.url>http://www.wtfpl.net/</pies.project.license.url> <pies.project.inceptionYear>2013</pies.project.inceptionYear> <pies.project.organization.name><NAME></pies.project.organization.name> <pies.project.organization.url>https://sites.google.com/site/aboutmale/</pies.project.organization.url> <!-- classifier that MUST be used for assemblies (<id> in the assembly.xml) --> <pies.classifier.assembly>pies.assembly</pies.classifier.assembly> <!-- classifier that MUST be used for Harness stuff like shell scripts and so on --> <pies.classifier.harness>pies.harness</pies.classifier.harness> <!-- classifier that MUST be used for configurations --> <pies.classifier.config>pies.config</pies.classifier.config> <!-- line ending of the files that MUST be used for example by maven-assembly-plugin --> <pies.lineEnding>unix</pies.lineEnding> <!-- pattern for harness artifact ZIP file --> <pies.attachedArtifactFile.harness> ${project.build.directory}/${project.name}-${project.version}-${pies.classifier.harness}.zip </pies.attachedArtifactFile.harness> <!-- pattern for config artifact ZIP file --> <pies.attachedArtifactFile.config> ${project.build.directory}/${project.name}-${project.version}-${pies.classifier.config}.zip </pies.attachedArtifactFile.config> </properties> <dependencyManagement> <dependencies> <dependency> <groupId>javax.inject</groupId> <artifactId>javax.inject</artifactId> <version>1</version> </dependency> <dependency> <groupId>com.google.inject</groupId> <artifactId>guice</artifactId> <version>3.0</version> </dependency> <dependency> <groupId>com.google.code.findbugs</groupId> <artifactId>jsr305</artifactId> <version>3.0.0</version> </dependency> <dependency> <groupId>com.google.guava</groupId> <artifactId>guava</artifactId> <version>18.0</version> </dependency> <dependency> <groupId>commons-configuration</groupId> <artifactId>commons-configuration</artifactId> <version>1.10</version> </dependency> <dependency> <groupId>commons-collections</groupId> <artifactId>commons-collections</artifactId> <version>3.2.1</version> </dependency> <dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-lang3</artifactId> <version>3.3.2</version> </dependency> <dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-pool2</artifactId> <version>2.2</version> </dependency> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.11</version> </dependency> <dependency> <groupId>org.mockito</groupId> <artifactId>mockito-all</artifactId> <version>1.10.8</version> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-api</artifactId> <version>1.7.7</version> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-nop</artifactId> <version>1.7.7</version> </dependency> <dependency> <groupId>org.apache.logging.log4j</groupId> <artifactId>log4j-slf4j-impl</artifactId> <version>2.1</version> </dependency> <dependency> <groupId>org.apache.logging.log4j</groupId> <artifactId>log4j-core</artifactId> <version>2.1</version> </dependency> <dependency> <groupId>com.lmax</groupId> <artifactId>disruptor</artifactId> <version>3.3.0</version> </dependency> <dependency> <groupId>io.netty</groupId> <artifactId>netty-all</artifactId> <version>5.0.0.Alpha1</version> </dependency> <dependency> <groupId>org.javassist</groupId> <artifactId>javassist</artifactId> <version>3.18.2-GA</version> </dependency> <dependency> <groupId>javax.json</groupId> <artifactId>javax.json-api</artifactId> <version>1.0</version> </dependency> <dependency> <groupId>org.glassfish</groupId> <artifactId>javax.json</artifactId> <version>1.0.4</version> </dependency> <dependency> <groupId>com.google.code.findbugs</groupId> <artifactId>annotations</artifactId> <version>3.0.0</version> </dependency> <dependency> <groupId>com.gl.vn.me.ko.pies</groupId> <artifactId>pies-base-doc</artifactId> <version>0.0.0-SNAPSHOT</version> </dependency> <dependency> <groupId>com.gl.vn.me.ko.pies</groupId> <artifactId>pies-base-config</artifactId> <version>0.0.0-SNAPSHOT</version> </dependency> <dependency> <groupId>com.gl.vn.me.ko.pies</groupId> <artifactId>pies-base-main</artifactId> <version>0.0.0-SNAPSHOT</version> </dependency> <dependency> <groupId>com.gl.vn.me.ko.pies</groupId> <artifactId>pies-base-constant</artifactId> <version>0.0.0-SNAPSHOT</version> </dependency> <dependency> <groupId>com.gl.vn.me.ko.pies</groupId> <artifactId>pies-base-throwable</artifactId> <version>0.0.0-SNAPSHOT</version> </dependency> <dependency> <groupId>com.gl.vn.me.ko.pies</groupId> <artifactId>pies-base-feijoa</artifactId> <version>0.0.0-SNAPSHOT</version> </dependency> <dependency> <groupId>com.gl.vn.me.ko.pies</groupId> <artifactId>pies-platform-server</artifactId> <version>0.0.0-SNAPSHOT</version> </dependency> <dependency> <groupId>com.gl.vn.me.ko.pies</groupId> <artifactId>pies-platform-client</artifactId> <version>0.0.0-SNAPSHOT</version> </dependency> <dependency> <groupId>com.gl.vn.me.ko.pies</groupId> <artifactId>pies-platform-app</artifactId> <version>0.0.0-SNAPSHOT</version> </dependency> <dependency> <groupId>com.gl.vn.me.ko.pies</groupId> <artifactId>pies-base-main</artifactId> <classifier>${pies.classifier.harness}</classifier> <type>zip</type> <version>0.0.0-SNAPSHOT</version> </dependency> <dependency> <groupId>com.gl.vn.me.ko.pies</groupId> <artifactId>pies-base-main</artifactId> <classifier>${pies.classifier.config}</classifier> <type>zip</type> <version>0.0.0-SNAPSHOT</version> </dependency> <dependency> <groupId>com.gl.vn.me.ko.pies</groupId> <artifactId>pies-platform-app</artifactId> <classifier>${pies.classifier.harness}</classifier> <type>zip</type> <version>0.0.0-SNAPSHOT</version> </dependency> <dependency> <groupId>com.gl.vn.me.ko.pies</groupId> <artifactId>pies-app-echo-logic</artifactId> <version>0.0.0-SNAPSHOT</version> </dependency> <dependency> <groupId>com.gl.vn.me.ko.pies</groupId> <artifactId>pies-app-echo</artifactId> <classifier>${pies.classifier.assembly}</classifier> <type>zip</type> <version>0.0.0-SNAPSHOT</version> </dependency> <dependency> <groupId>com.gl.vn.me.ko.pies</groupId> <artifactId>pies-app-echo-logic</artifactId> <classifier>${pies.classifier.config}</classifier> <type>zip</type> <version>0.0.0-SNAPSHOT</version> </dependency> <dependency> <groupId>com.gl.vn.me.ko.pies</groupId> <artifactId>pies-app-initiator-logic</artifactId> <version>0.0.0-SNAPSHOT</version> </dependency> <dependency> <groupId>com.gl.vn.me.ko.pies</groupId> <artifactId>pies-app-initiator</artifactId> <classifier>${pies.classifier.assembly}</classifier> <type>zip</type> <version>0.0.0-SNAPSHOT</version> </dependency> <dependency> <groupId>com.gl.vn.me.ko.pies</groupId> <artifactId>pies-app-initiator-logic</artifactId> <classifier>${pies.classifier.config}</classifier> <type>zip</type> <version>0.0.0-SNAPSHOT</version> </dependency> <dependency> <groupId>com.gl.vn.me.ko.pies</groupId> <artifactId>pies-app-initiator-logic</artifactId> <classifier>${pies.classifier.harness}</classifier> <type>zip</type> <version>0.0.0-SNAPSHOT</version> </dependency> <dependency> <groupId>com.gl.vn.me.ko.pies</groupId> <artifactId>pies-app-proxy-logic</artifactId> <version>0.0.0-SNAPSHOT</version> </dependency> <dependency> <groupId>com.gl.vn.me.ko.pies</groupId> <artifactId>pies-app-proxy</artifactId> <classifier>${pies.classifier.assembly}</classifier> <type>zip</type> <version>0.0.0-SNAPSHOT</version> </dependency> <dependency> <groupId>com.gl.vn.me.ko.pies</groupId> <artifactId>pies-app-proxy-logic</artifactId> <classifier>${pies.classifier.config}</classifier> <type>zip</type> <version>0.0.0-SNAPSHOT</version> </dependency> </dependencies> </dependencyManagement> <build> <defaultGoal>install</defaultGoal> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-source-plugin</artifactId> </plugin> </plugins> <pluginManagement> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <version>3.2</version> <configuration> <source>8</source> <target>8</target> <encoding>UTF-8</encoding> <debug>true</debug> <debuglevel>lines,vars,source</debuglevel> <showWarnings>true</showWarnings> <showDeprecation>true</showDeprecation> <compilerArguments> <parameters/> <Xlint:all/> <!-- Annotation processing causes a warning "No processor claimed any of these annotations: org.junit.Test,org.junit.AfterClass,org.junit.BeforeClass" while compiling source files to .../pies-base/pies-base-main/target/test-classes So disable it... --> <Xlint:-processing/> <Werror/> </compilerArguments> </configuration> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-jar-plugin</artifactId> <version>2.5</version> <configuration> <archive> <addMavenDescriptor>false</addMavenDescriptor> <manifest> <addDefaultImplementationEntries>false</addDefaultImplementationEntries> <addDefaultSpecificationEntries>false</addDefaultSpecificationEntries> <addClasspath>false</addClasspath> </manifest> </archive> </configuration> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-assembly-plugin</artifactId> <version>2.5.2</version> <configuration> <descriptors> <descriptor>assembly.xml</descriptor> </descriptors> </configuration> <executions> <execution> <id>make-assembly</id> <phase>package</phase> <goals> <goal>single</goal> </goals> </execution> </executions> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-antrun-plugin</artifactId> <version>1.7</version> </plugin> <plugin> <groupId>org.codehaus.mojo</groupId> <artifactId>build-helper-maven-plugin</artifactId> <version>1.9.1</version> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-javadoc-plugin</artifactId> <version>2.10.1</version> <configuration> <detectJavaApiLink>false</detectJavaApiLink> <doctitle>PIES ${project.version} Java Source Code Documentation</doctitle> <author>false</author> <show>protected</show> <linksource>false</linksource> <bottom><![CDATA[<p>]]></bottom> <charset>${pies.charset}</charset> <docencoding>${pies.charset}</docencoding> <encoding>${pies.charset}</encoding> <header> <![CDATA[ <a href="${pies.project.url}">PIES</a> <br></br> Java Source Code Documentation ]]> </header> <footer> <![CDATA[Licensed under <a href="http://www.wtfpl.net/">WTFPL</a>]]> </footer> <locale>en</locale> <windowtitle>PIES Java Source Code Documentation</windowtitle> <groups> <group> <title>Base</title> <packages> com.gl.vn.me.ko.pies.base:com.gl.vn.me.ko.pies.base.* </packages> </group> <group> <title>Platform</title> <packages> com.gl.vn.me.ko.pies.platform:com.gl.vn.me.ko.pies.platform.* </packages> </group> <group> <title>App</title> <packages> com.gl.vn.me.ko.pies.app:com.gl.vn.me.ko.pies.app.* </packages> </group> </groups> <links> <link>http://docs.oracle.com/javase/8/docs/api/</link> <link>http://docs.oracle.com/javaee/7/api/</link> <link>http://stincmale.github.io/jsr-305/javadoc/</link> <link>http://google-guice.googlecode.com/git/javadoc/</link> <link>http://docs.guava-libraries.googlecode.com/git-history/release/javadoc/</link> <link>http://commons.apache.org/proper/commons-configuration/apidocs/</link> <link>http://netty.io/5.0/api/</link> </links> <validateLinks>true</validateLinks> <includeDependencySources>false</includeDependencySources> <includeTransitiveDependencySources>false</includeTransitiveDependencySources> </configuration> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-source-plugin</artifactId> <version>2.4</version> <executions> <execution> <id>attach-sources</id> <phase>verify</phase> <goals> <goal>jar-no-fork</goal> </goals> </execution> </executions> </plugin> </plugins> </pluginManagement> </build> <profiles> <profile> <id>doc</id> <build> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-javadoc-plugin</artifactId> <executions> <execution> <id>attach-javadocs</id> <phase>package</phase> <goals> <goal>jar</goal> </goals> </execution> </executions> </plugin> </plugins> </build> </profile> </profiles> </project><file_sep>/pies-base/pies-base-main/src/main/java/com/gl/vn/me/ko/pies/base/thread/ThreadGuiceModule.java package com.gl.vn.me.ko.pies.base.thread; import static com.gl.vn.me.ko.pies.base.constant.Message.GUICE_POTENTIALLY_SWALLOWED; import com.gl.vn.me.ko.pies.base.di.GuiceModule; import java.util.concurrent.ThreadFactory; import javax.inject.Singleton; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * This {@link GuiceModule} is aware of the following: * <ul> * <li>{@link Singleton @Singleton} {@link ThreadFactory}</li> * </ul> */ public final class ThreadGuiceModule extends GuiceModule { private static final Logger LOGGER = LoggerFactory.getLogger(ThreadGuiceModule.class); /** * Constructor required according to the specification of {@link GuiceModule}. * This constructor MUST NOT be called directly by any Application code. */ public ThreadGuiceModule() { } @Override protected final void configure() { try { bind(ThreadFactory.class).to(ApplicationThreadFactory.class); } catch (final RuntimeException e) { LOGGER.error(GUICE_POTENTIALLY_SWALLOWED, e); throw e; } } } <file_sep>/pies-base/pies-base-config/src/main/java/com/gl/vn/me/ko/pies/base/config/ConfigCreationException.java package com.gl.vn.me.ko.pies.base.config; import com.gl.vn.me.ko.pies.base.throwable.ApplicationException; import javax.annotation.Nullable; /** * Indicates that creation of configuration is failed. */ public final class ConfigCreationException extends ApplicationException { private static final long serialVersionUID = 0; /** * Creates an instance of {@link ConfigCreationException}. */ ConfigCreationException() { } /** * Creates an instance of {@link ConfigCreationException}. * * @param message * The detail message which is saved for later retrieval by the {@link #getMessage()} method. */ ConfigCreationException(@Nullable final String message) { super(message); } /** * Creates an instance of {@link ConfigCreationException}. * * @param message * The detail message which is saved for later retrieval by the {@link #getMessage()} method. * @param cause * The cause which is saved for later retrieval by the {@link #getCause()} method. */ ConfigCreationException(@Nullable final String message, @Nullable final Throwable cause) { super(message, cause); } /** * Creates an instance of {@link ConfigCreationException}. * * @param cause * The cause which is saved for later retrieval by the {@link #getCause()} method. */ ConfigCreationException(@Nullable final Throwable cause) { super(cause); } } <file_sep>/misc/manual test/test.sh #!/bin/bash log() { echo "" echo "Test: ${1} ------------------------------------------------------------------------" echo "" } #Execution levels readonly EXEC_LEVEL_BUILD="0" readonly EXEC_LEVEL_REPLACE="1" readonly EXEC_LEVEL_START="2" readonly EXEC_LEVEL_SHUTDOWN="3" #Set environment readonly MANUAL_TEST_LOCATION="/Users/male/Documents/programming/projects/pies/misc/manual test" readonly PROJECT_LOCATION="/Users/male/Documents/programming/projects/pies" readonly PROJECT_POM="${PROJECT_LOCATION}/pom.xml" readonly ASSEMBLY_LOCATION="${PROJECT_LOCATION}/target" readonly ASSEMBLY_NAME="pies-0.0.0-SNAPSHOT-pies.assembly.zip" readonly PIES_ECHO_APP_HOME_DIR_NAME="pies-app-echo" readonly PIES_INITIATOR_APP_HOME_DIR_NAME="pies-app-initiator" readonly PIES_PROXY_APP_HOME_DIR_NAME="pies-app-proxy" #Process command-line arguments EXEC_LEVEL="${EXEC_LEVEL_BUILD}" if [ "${1}" = "build" ] then EXEC_LEVEL="${EXEC_LEVEL_BUILD}" fi if [ "${1}" = "replace" ] then EXEC_LEVEL="${EXEC_LEVEL_REPLACE}" fi if [ "${1}" = "start" ] then EXEC_LEVEL="${EXEC_LEVEL_START}" fi if [ "${1}" = "stop" ] then EXEC_LEVEL="${EXEC_LEVEL_SHUTDOWN}" fi MVN_CLEAN="${2}" #Build project if [ "${EXEC_LEVEL_BUILD}" -ge "${EXEC_LEVEL}" ] then log "Build project" mvn -f ${PROJECT_POM} ${MVN_CLEAN} package -P assembly echo "" fi #Replace assemblies if [ "${EXEC_LEVEL_REPLACE}" -ge "${EXEC_LEVEL}" ] then log "Replace assemblies" rm -R "${MANUAL_TEST_LOCATION}/${PIES_ECHO_APP_HOME_DIR_NAME}" rm -R "${MANUAL_TEST_LOCATION}/${PIES_INITIATOR_APP_HOME_DIR_NAME}" rm -R "${MANUAL_TEST_LOCATION}/${PIES_PROXY_APP_HOME_DIR_NAME}" cp "${ASSEMBLY_LOCATION}/${ASSEMBLY_NAME}" "${MANUAL_TEST_LOCATION}/${ASSEMBLY_NAME}" unzip "${MANUAL_TEST_LOCATION}/${ASSEMBLY_NAME}" -d "${MANUAL_TEST_LOCATION}" rm "${MANUAL_TEST_LOCATION}/${ASSEMBLY_NAME}" chmod u+x "${MANUAL_TEST_LOCATION}/${PIES_ECHO_APP_HOME_DIR_NAME}/harness/"*.sh chmod u+x "${MANUAL_TEST_LOCATION}/${PIES_INITIATOR_APP_HOME_DIR_NAME}/harness/"*.sh chmod u+x "${MANUAL_TEST_LOCATION}/${PIES_PROXY_APP_HOME_DIR_NAME}/harness/"*.sh echo "" fi #Start Applications if [ "${EXEC_LEVEL_START}" -ge "${EXEC_LEVEL}" ] then log "Start Applications" "${MANUAL_TEST_LOCATION}/${PIES_ECHO_APP_HOME_DIR_NAME}/harness/start.sh" log "" "${MANUAL_TEST_LOCATION}/${PIES_INITIATOR_APP_HOME_DIR_NAME}/harness/start.sh" log "" "${MANUAL_TEST_LOCATION}/${PIES_PROXY_APP_HOME_DIR_NAME}/harness/start.sh" exit fi #Shutdown Applications if [ "${EXEC_LEVEL_SHUTDOWN}" -ge "${EXEC_LEVEL}" ] then log "Shutdown Applications" "${MANUAL_TEST_LOCATION}/${PIES_ECHO_APP_HOME_DIR_NAME}/harness/shutdown.sh" log "" "${MANUAL_TEST_LOCATION}/${PIES_INITIATOR_APP_HOME_DIR_NAME}/harness/shutdown.sh" log "" "${MANUAL_TEST_LOCATION}/${PIES_PROXY_APP_HOME_DIR_NAME}/harness/shutdown.sh" fi <file_sep>/pies-base/pies-base-config/src/main/java/com/gl/vn/me/ko/pies/base/config/app/Stage.java package com.gl.vn.me.ko.pies.base.config.app; import static com.google.common.base.Preconditions.checkNotNull; import com.gl.vn.me.ko.pies.base.constant.Message; import com.gl.vn.me.ko.pies.base.feijoa.Stringable; import com.gl.vn.me.ko.pies.base.feijoa.StringableConvertationException; import com.gl.vn.me.ko.pies.base.feijoa.StringableConverter; import javax.annotation.concurrent.Immutable; /** * Represents a stage the Application is running in. Some parts of the Application MAY decide to change internal * behavior depending on the {@link Stage}, but functionality MUST NOT be affected. * Note that logging SHOULD NOT be affected by {@link Stage}. * * @see ApplicationConfig */ @Immutable public enum Stage implements Stringable { /** * At this stage startup time is more important than runtime performance. * <p> * Name of this {@link Stage} is {@code "development"}. */ DEVELOPMENT("development"), /** * At this stage performance and delays is more important than startup time. * <p> * Name of this {@link Stage} is {@code "production"}. */ PRODUCTION("production"); private static final class StageConverter implements StringableConverter<Stage> { private static final StageConverter INSTANCE = new StageConverter(); private StageConverter() { } @Override public final Stage valueOf(final String name) throws StringableConvertationException { checkNotNull(name, Message.ARGUMENT_NULL_SINGLE, "name"); final Stage result; switch (name) { case "development": { result = DEVELOPMENT; break; } case "production": { result = PRODUCTION; break; } default: throw new StringableConvertationException(Message.format(Message.ARGUMENT_ILLEGAL_SINGLE, name, "name", "Value must be one of \"development\", \"production\"")); } return result; } } /** * Returns {@link StringableConverter} that can restore {@link Stage} from a {@link String} returned from * {@link Stage#toString()}. * * @return * {@link StringableConverter} for {@link Stage}. */ public static final StringableConverter<Stage> converter() { return StageConverter.INSTANCE; } private final String name; private Stage(final String name) { this.name = name; } /** * Returns name of the {@link Stage}. * The returned value can be used as argument for the method {@link StringableConverter#valueOf(String)} of the * {@link StringableConverter} returned by {@link #converter()}. * * @return * Name of the {@link Stage}. * @see #converter() */ @Override public final String toString() { return name; } } <file_sep>/pies-base/pies-base-config/src/main/java/com/gl/vn/me/ko/pies/base/config/PropertyType.java package com.gl.vn.me.ko.pies.base.config; import com.google.common.collect.ImmutableSet; import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; import java.math.BigDecimal; import java.math.BigInteger; import java.util.List; import java.util.Set; import javax.annotation.Nullable; import javax.annotation.concurrent.Immutable; /** * Represents type of a property. * * @param T * A Java type of value of a property. */ @Immutable public final class PropertyType<T> { /** * Corresponds to {@link BigDecimal}. */ public static final PropertyType<BigDecimal> BIG_DECIMAL = new PropertyType<>("BigDecimal", 1); /** * Corresponds to {@link BigInteger}. */ public static final PropertyType<BigInteger> BIG_INTEGER = new PropertyType<>("BigInteger", 2); /** * Corresponds to {@link Boolean}. */ public static final PropertyType<Boolean> BOOLEAN = new PropertyType<>("Boolean", 3); /** * Corresponds to {@link Double}. */ public static final PropertyType<Double> DOUBLE = new PropertyType<>("Double", 4); /** * Corresponds to {@link Integer}. */ public static final PropertyType<Integer> INTEGER = new PropertyType<>("Integer", 5); /** * Corresponds to {@link Long}. */ public static final PropertyType<Long> LONG = new PropertyType<>("Long", 6); /** * Corresponds to {@link String}. */ public static final PropertyType<String> STRING = new PropertyType<>("String", 7); /** * Corresponds to {@link List}{@code <}{@link String}{@code >}. * A type of a multiple property. */ public static final PropertyType<List<String>> LIST_OF_STRINGS = new PropertyType<>("List<String>", 8); /** * Corresponds to {@link Set}{@code <}{@link String}{@code >}. * A type of a multiple property. */ public static final PropertyType<Set<String>> SET_OF_STRINGS = new PropertyType<>("Set<String>", 9); private static final Set<PropertyType<?>> TYPES = ImmutableSet.of( BIG_DECIMAL, BIG_INTEGER, BOOLEAN, DOUBLE, INTEGER, LONG, STRING, LIST_OF_STRINGS, SET_OF_STRINGS); /** * Returns a {@link Set} of all possible {@link PropertyType}s. * * @return * An unmodifiable {@link Set} of all possible {@link PropertyType}s. */ static final Set<PropertyType<?>> types() { return TYPES; } private final String name; private final int id; private PropertyType(final String name, final int id) { this.name = name; this.id = id; } /** * Casts the specified {@code object} the Java type that corresponds to the {@link PropertyType}. * * @param object * An {@link Object} to cast. * @return * {@code object} that was cast. */ @SuppressWarnings("unchecked") @Nullable final T cast(final @Nullable Object object) { return (T)object; } /** * Returns a description of the {@link PropertyType}. * * @return * A description of the {@link PropertyType}. */ @Override public final String toString() { final StringBuilder sb = new StringBuilder(this.getClass().getName()) .append("(name=").append(name) .append(", id=").append(id).append(')'); final String result = sb.toString(); return result; } /** * Tests if the specified {@code object} represents the same {@link PropertyType} as this {@link PropertyType}. * * @param object * {@code Object} to test. * @return * {@code true} if the specified {@code object} is equal to this {@link PropertyType} and {@code false} otherwise. */ @SuppressFBWarnings( value = "NP_METHOD_PARAMETER_TIGHTENS_ANNOTATION", justification = "Object.equals(...) allows null arguments") @Override public final boolean equals(@Nullable final Object object) { final boolean result; if (this == object) { result = true; } else { if (object instanceof PropertyType) { final PropertyType<?> propertyType = (PropertyType<?>)object; result = this.id == propertyType.id; } else { result = false; } } return result; } @Override public final int hashCode() { return id; } } <file_sep>/pies-platform/pies-platform-server/src/main/java/com/gl/vn/me/ko/pies/platform/server/rest/BadRestRequestException.java package com.gl.vn.me.ko.pies.platform.server.rest; import com.gl.vn.me.ko.pies.base.throwable.ExternallyVisibleException; import javax.annotation.Nullable; /** * Indicates that a {@link RestRequest} is incorrect. */ public final class BadRestRequestException extends ExternallyVisibleException { private static final long serialVersionUID = 0; /** * Creates an instance of {@link BadRestRequestException}. * * @param externalMessage * Message that MAY be made visible to a client of an Application. */ public BadRestRequestException(final String externalMessage) { super(externalMessage); } /** * Creates an instance of {@link BadRestRequestException}. * * @param message * The detail message which is saved for later retrieval by the {@link #getMessage()} method. * @param externalMessage * Message that MAY be made visible to a client of an Application. */ public BadRestRequestException(@Nullable final String message, final String externalMessage) { super(message, externalMessage); } /** * Creates an instance of {@link BadRestRequestException}. * * @param message * The detail message which is saved for later retrieval by the {@link #getMessage()} method. * @param cause * The cause which is saved for later retrieval by the {@link #getCause()} method. * @param externalMessage * Message that MAY be made visible to a client of an Application. */ public BadRestRequestException( @Nullable final String message, @Nullable final Throwable cause, final String externalMessage) { super(message, cause, externalMessage); } /** * Creates an instance of {@link BadRestRequestException}. * * @param externalMessage * Message that MAY be made visible to a client of an Application. * @param cause * The cause which is saved for later retrieval by the {@link #getCause()} method. */ public BadRestRequestException(final String externalMessage, @Nullable final Throwable cause) { super(externalMessage, cause); } } <file_sep>/misc/manual test/proxyApplicationLog.sh #!/bin/bash #Set environment readonly MANUAL_TEST_LOCATION="/Users/male/Documents/programming/projects/pies/misc/manual test" readonly PIES_PROXY_APP_HOME_DIR_NAME="pies-app-proxy" less "${MANUAL_TEST_LOCATION}/${PIES_PROXY_APP_HOME_DIR_NAME}/log/application.log" <file_sep>/pies-platform/pies-platform-app/pom.xml <?xml version="1.0" encoding="UTF-8"?> <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"> <description> Aggregates common platform functionality that is needed to construct an Application. </description> <modelVersion>4.0.0</modelVersion> <artifactId>pies-platform-app</artifactId> <packaging>jar</packaging> <name>pies-platform-app</name> <url>${pies.project.url}</url> <licenses> <license> <name>${pies.project.license.name}</name> <url>${pies.project.license.url}</url> </license> </licenses> <inceptionYear>${pies.project.inceptionYear}</inceptionYear> <organization> <name>${pies.project.organization.name}</name> <url>${pies.project.organization.url}</url> </organization> <parent> <groupId>com.gl.vn.me.ko.pies</groupId> <artifactId>pies-platform-parent</artifactId> <version>0.0.0-SNAPSHOT</version> <relativePath>../pies-platform-parent/pom.xml</relativePath> </parent> <dependencies> <dependency> <groupId>com.google.code.findbugs</groupId> <artifactId>jsr305</artifactId> </dependency> <dependency> <groupId>io.netty</groupId> <artifactId>netty-all</artifactId> </dependency> <dependency> <groupId>com.google.inject</groupId> <artifactId>guice</artifactId> </dependency> <dependency> <groupId>javax.inject</groupId> <artifactId>javax.inject</artifactId> </dependency> <dependency> <groupId>com.gl.vn.me.ko.pies</groupId> <artifactId>pies-base-doc</artifactId> </dependency> <dependency> <groupId>com.gl.vn.me.ko.pies</groupId> <artifactId>pies-platform-server</artifactId> </dependency> <dependency> <groupId>com.gl.vn.me.ko.pies</groupId> <artifactId>pies-base-main</artifactId> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-antrun-plugin</artifactId> <executions> <execution> <id>prepare-harness-artifact</id> <phase>package</phase> <configuration> <target> <zip destfile="${pies.attachedArtifactFile.harness}"> <fileset dir="src/harness"/> </zip> </target> </configuration> <goals> <goal>run</goal> </goals> </execution> </executions> </plugin> <plugin> <groupId>org.codehaus.mojo</groupId> <artifactId>build-helper-maven-plugin</artifactId> <executions> <execution> <id>attach-harness-artifact</id> <phase>package</phase> <goals> <goal>attach-artifact</goal> </goals> <configuration> <artifacts> <artifact> <file>${pies.attachedArtifactFile.harness}</file> <type>zip</type> <classifier>${pies.classifier.harness}</classifier> </artifact> </artifacts> </configuration> </execution> </executions> </plugin> </plugins> </build> </project><file_sep>/pies-platform/pies-platform-server/src/main/java/com/gl/vn/me/ko/pies/platform/server/rest/RestChannelHandler.java package com.gl.vn.me.ko.pies.platform.server.rest; import com.gl.vn.me.ko.pies.base.constant.Message; import com.gl.vn.me.ko.pies.base.throwable.ApplicationError; import com.gl.vn.me.ko.pies.base.throwable.ApplicationException; import io.netty.channel.ChannelHandler.Sharable; import io.netty.channel.ChannelHandlerAdapter; import io.netty.channel.ChannelHandlerContext; import io.netty.handler.codec.http.FullHttpResponse; import io.netty.handler.codec.http.HttpRequest; import io.netty.handler.codec.http.HttpResponseStatus; import java.util.concurrent.CompletionStage; import java.util.concurrent.ExecutorService; import javax.annotation.Nullable; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Handles {@link RestRequest}s and {@linkplain ChannelHandlerContext#writeAndFlush(Object) responds} * with HTTP responses constructed by corresponding {@link RestRequestHandler}s. * In some situations {@link RestChannelHandler} * {@linkplain ChannelHandlerContext#writeAndFlush(Object) responds} with HTTP responses * constructed by using the {@link RestServer.ServiceHttpResponseConstructor#create(HttpResponseStatus, String)} method. * <p> * {@link RestChannelHandler} MUST be preceeded by the {@link RestDecoder} in the {@link ChannelPipeline}. */ @Sharable final class RestChannelHandler extends ChannelHandlerAdapter { private static final Logger LOGGER = LoggerFactory.getLogger(RestChannelHandler.class); private final RestRequestDispatcher<? extends RestRequestHandlerResult> restDispatcher; private final ExecutorService postResponseBlockingExecutorService; private final RestServer.ServiceHttpResponseConstructor serviceHttpResponseConstructor; private final RestServer.ExceptionHandler exceptionHandler; RestChannelHandler( final RestRequestDispatcher<? extends RestRequestHandlerResult> restDispatcher, final ExecutorService postResponseBlockingExecutorService, final RestServer.ServiceHttpResponseConstructor serviceHttpResponseConstructor, final RestServer.ExceptionHandler exceptionHandler) { this.restDispatcher = restDispatcher; this.postResponseBlockingExecutorService = postResponseBlockingExecutorService; this.serviceHttpResponseConstructor = serviceHttpResponseConstructor; this.exceptionHandler = exceptionHandler; } @Override public final void exceptionCaught(final ChannelHandlerContext ctx, final Throwable cause) { exceptionCaught(ctx, cause, null); } private final void exceptionCaught( final ChannelHandlerContext ctx, final Throwable cause, @Nullable final HttpRequest httpRequest) { final FullHttpResponse httpResponse = exceptionHandler.handle(cause, httpRequest); respond(ctx, httpRequest, httpResponse); } @Override public final void channelRead(final ChannelHandlerContext ctx, final Object msg) { final RestHttpRequestsAlloy restHttpAlloy = (RestHttpRequestsAlloy)msg; final CompletionStage<? extends RestRequestHandlerResult> restResultCompletionStage; try { restResultCompletionStage = restDispatcher.dispatch(restHttpAlloy.getRestRequest()); restResultCompletionStage.handleAsync((restResult, restException) -> restRequestHandled( ctx, restResult, restException, restHttpAlloy.getHttpRequest()), ctx.executor()); } catch (final BindingNotFoundException e) { LOGGER.debug("Unable to dispatch a REST request", e); respond(ctx, restHttpAlloy.getHttpRequest(), RestServer.HTTP_RESPONSE_STATUS_BAD_REQUEST, "Unknown REST request"); } } private final Void restRequestHandled( final ChannelHandlerContext ctx, @Nullable final RestRequestHandlerResult restResult, @Nullable final Throwable restException, @Nullable final HttpRequest httpRequest) { if (restResult != null) { final FullHttpResponse httpResponse = restResult.getHttpResponse(); try { respond(ctx, httpRequest, httpResponse); } finally { restResult.getPostResponseAction() .ifPresent((postResponseAction) -> postResponseBlockingExecutorService.execute(postResponseAction)); } } else if (restException != null) { exceptionCaught(ctx, new ApplicationException(restException)); } else { exceptionCaught(ctx, new ApplicationError(Message.CAN_NEVER_HAPPEN)); } return null; } private final void respond( final ChannelHandlerContext ctx, @Nullable final HttpRequest httpRequest, final FullHttpResponse httpResponse) { RestServer.handleKeepAlive(httpRequest, httpResponse); ctx.writeAndFlush(httpResponse); } private final void respond( final ChannelHandlerContext ctx, final HttpRequest httpRequest, final HttpResponseStatus httpResponseStatus, @Nullable final String httpReasonPhrase) { final FullHttpResponse httpResponse = serviceHttpResponseConstructor.create(httpResponseStatus, httpReasonPhrase); respond(ctx, httpRequest, httpResponse); } } <file_sep>/pies-base/pies-base-feijoa/src/main/java/com/gl/vn/me/ko/pies/base/feijoa/Stringable.java package com.gl.vn.me.ko.pies.base.feijoa; /** * Objects of this type can be losslessly represented by a {@link String} via the {@link #toString()} method. And can be * restored from a {@link String} via the {@link StringableConverter#valueOf(String)} method. * <p> * It MAY be useful to implement this interface by descendants of {@link Enum}. * * @see StringableConverter */ public interface Stringable { /** * Returns {@link String} value of the {@link Stringable}. * The returned value can be used as argument for the method {@link StringableConverter#valueOf(String)}. * * @return * Value of the {@link Stringable}. */ @Override String toString(); } <file_sep>/pies-platform/pies-platform-server/src/main/java/com/gl/vn/me/ko/pies/platform/server/Server.java package com.gl.vn.me.ko.pies.platform.server; import io.netty.util.concurrent.Future; import javax.annotation.concurrent.ThreadSafe; /** * Represents an I/O server. */ @ThreadSafe public interface Server { /** * Performs a shutdown procedure. * After completion of this method {@link Server} doesn't perform I/O and any other operations anymore. * This method MUST be idempotent. * * @see #start() */ void shutdown(); /** * Performs a start procedure. * After completion of this method {@link Server} is able to perform I/O operations until {@link #shutdown()} is * invoked. * <p> * Once the {@link #start()} method is called the {@link #shutdown()} method MUST be called later. A suggested * approach to start, wait and shutdown a {@link Server} is following: * <pre><code> * final Server server = ... * try { * final Future&lt;?&gt; completion = server.start(); * ... // do something else if you need to * completion.await(); * } catch (final InterruptedException e) { * // shutdown() called in finally block is our reaction on interruption * Thread.currentThread().interrupt(); * } finally { * server.shutdown(); * } * </code></pre> * Two invocations of the {@link #start()} method on the same {@link Server} MUST be separated with * {@link #shutdown()} method invocation. {@link Server} implementation MUST explicitly specify if it supports * multiple {@link #start()} {@literal &} {@link #shutdown()} procedures, otherwise one MUST NOT invoke {@link #start()} * method more than one time for a given {@link Server} instance. * * @return * {@link Future} that MAY be used to {@link Future#await() wait} till the {@link Server} operates. * After completion of this {@link Future} the method {@link #shutdown()} MUST be called in order * to correctly shutdown the {@link Server}. * @throws InterruptedException * If the current {@link Thread} is interrupted. * @see #shutdown() */ Future<?> start() throws InterruptedException; } <file_sep>/pies-app/pies-app-echo/pies-app-echo-logic/src/main/java/com/gl/vn/me/ko/pies/app/echo/EchoApplication.java package com.gl.vn.me.ko.pies.app.echo; import com.gl.vn.me.ko.pies.base.main.App; import com.gl.vn.me.ko.pies.base.main.GuiceLocator; import com.gl.vn.me.ko.pies.platform.app.CommonApp; import com.gl.vn.me.ko.pies.platform.server.Server; import com.gl.vn.me.ko.pies.platform.server.rest.JsonRestServer; import com.gl.vn.me.ko.pies.platform.server.tcp.TcpServer; import com.google.inject.Injector; import io.netty.util.concurrent.Future; import javax.inject.Singleton; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Implementation of PIES Echo Application. */ @Singleton public final class EchoApplication extends CommonApp { private static final Logger LOGGER = LoggerFactory.getLogger(EchoApplication.class); /** * Constructor required according to the specification of {@link App}. * This constructor MUST NOT be called directly by any Application code. */ public EchoApplication() { super(GuiceLocator.createInjector(EchoModule.getInstance())); } /** * Creates and starts Echo and Control Servers. */ @Override public final void run() { final Injector injector = getInjector(); final Server echoServer = injector.getInstance(TcpServer.class); try { final Future<?> echoServerCompletion = echoServer.start(); final Server controlServer = injector.getInstance(JsonRestServer.class); try { final Future<?> controlServerCompletion = controlServer.start(); controlServerCompletion.await(); } catch (final InterruptedException e) { LOGGER.info("Interrupt was detected. {} will shut down", controlServer); Thread.currentThread().interrupt(); } finally { controlServer.shutdown(); Thread.currentThread().interrupt(); } echoServerCompletion.await(); } catch (final InterruptedException e) { LOGGER.info("Interrupt was detected. {} will shut down", echoServer); Thread.currentThread().interrupt(); } finally { echoServer.shutdown(); } } } <file_sep>/pies-base/pies-base-feijoa/src/test/java/com/gl/vn/me/ko/pies/base/feijoa/TestExecutorUtil.java package com.gl.vn.me.ko.pies.base.feijoa; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; import java.util.concurrent.CountDownLatch; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import org.junit.Test; public final class TestExecutorUtil { public TestExecutorUtil() { } @Test(expected = RuntimeException.class) public final void unshutdownableShutdown() { final ExecutorService unshutdownableExecutorService = ExecutorUtil.unshutdownable(Executors.newSingleThreadExecutor()); unshutdownableExecutorService.shutdown(); } @Test(expected = RuntimeException.class) public final void unshutdownableShutdownNow() { final ExecutorService unshutdownableExecutorService = ExecutorUtil.unshutdownable(Executors.newSingleThreadExecutor()); unshutdownableExecutorService.shutdownNow(); } @Test @SuppressWarnings("SleepWhileInLoop") @SuppressFBWarnings( value = {"RV_RETURN_VALUE_IGNORED_BAD_PRACTICE", "DLS_DEAD_LOCAL_STORE"}, justification = "This is just a test") public final void shutdownGracefullyWithUninterruptibleTask() { final ExecutorService executorService = Executors.newFixedThreadPool(2); final AtomicBoolean stopUninterruptible = new AtomicBoolean(false); {//submit tasks final CountDownLatch interruptibleTasksSubmitLatch = new CountDownLatch(1); {//submit uninterruptible task that will consume one thread forever executorService.submit(() -> { interruptibleTasksSubmitLatch.countDown(); while (!stopUninterruptible.get()) { try { Thread.sleep(10); } catch (final InterruptedException e) { //swallow } } }); } {//submit interruptible tasks try { interruptibleTasksSubmitLatch.await();//wait till the uninterruptible task will be started } catch (final InterruptedException e) { Thread.currentThread().interrupt(); fail("Unexpected interruption"); } for (int i = 1; i < 10; i++) { final int sleepTime = i * 1000;//sleep varies from 1 second to 10 seconds executorService.submit(() -> { try { Thread.sleep(sleepTime); } catch (final InterruptedException e) { Thread.currentThread().interrupt(); } }); } } } ExecutorUtil.shutdownGracefully(executorService, 100, 900, TimeUnit.MILLISECONDS); assertFalse("Assert that executor service wasn't terminated", executorService.isTerminated());//because of uninterruptible task stopUninterruptible.set(true); ExecutorUtil.shutdownGracefully(executorService, 0, 100, TimeUnit.MILLISECONDS); assertTrue("Assert that executor service was terminated", executorService.isTerminated()); } @Test @SuppressFBWarnings(value = "RV_RETURN_VALUE_IGNORED_BAD_PRACTICE", justification = "This is just a test") public final void shutdownGracefullyWithoutUninterruptibleTasks() { final ExecutorService executorService = Executors.newFixedThreadPool(2); {//submit task executorService.submit(() -> { try { Thread.sleep(10_000); } catch (final InterruptedException e) { Thread.currentThread().interrupt(); } }); } ExecutorUtil.shutdownGracefully(executorService, 100, 900, TimeUnit.MILLISECONDS); assertTrue("Assert that executor service was terminated", executorService.isTerminated()); } } <file_sep>/pies-base/pies-base-throwable/src/main/java/com/gl/vn/me/ko/pies/base/throwable/ApplicationError.java package com.gl.vn.me.ko.pies.base.throwable; import javax.annotation.Nullable; /** * Indicates a error in the Application logic and the only way to handle it is to fix the Application. */ public final class ApplicationError extends RuntimeException { private static final long serialVersionUID = 0; /** * Creates an instance of {@link ApplicationError}. */ public ApplicationError() { } /** * Creates an instance of {@link ApplicationError}. * * @param message * The detail message which is saved for later retrieval by the {@link #getMessage()} method. */ public ApplicationError(@Nullable final String message) { super(message); } /** * Creates an instance of {@link ApplicationError}. * * @param message * The detail message which is saved for later retrieval by the {@link #getMessage()} method. * @param cause * The cause which is saved for later retrieval by the {@link #getCause()} method. */ public ApplicationError(@Nullable final String message, @Nullable final Throwable cause) { super(message, cause); } /** * Creates an instance of {@link ApplicationError}. * * @param cause * The cause which is saved for later retrieval by the {@link #getCause()} method. */ public ApplicationError(@Nullable final Throwable cause) { super(cause); } }
ba2edc2c29aaba3e1cbc9565635b0eabf80fb99f
[ "Markdown", "Java", "Maven POM", "Shell" ]
71
Java
stIncMale/pies
abc001a7f0ee223d2391b160f3b402d41fc01ebd
f63a631bb83eecc52e08100b8743c9da864e4165