language stringclasses 15
values | src_encoding stringclasses 34
values | length_bytes int64 6 7.85M | score float64 1.5 5.69 | int_score int64 2 5 | detected_licenses listlengths 0 160 | license_type stringclasses 2
values | text stringlengths 9 7.85M |
|---|---|---|---|---|---|---|---|
Java | UTF-8 | 2,558 | 2.015625 | 2 | [] | no_license | package com.example.watertracker;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import com.example.watertracker.R;
import com.example.watertracker.domain.Cup;
import java.util.List;
public class SaveCupName extends AppCompatActivity {
Button btn;
EditText cupNameInput;
public String cupName;
private List<Cup> cupList;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_save_cup_name);
btn = (Button)findViewById(R.id.button5);
cupNameInput = (EditText) findViewById(R.id.cupName);
cupNameInput.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
@Override
public void afterTextChanged(Editable s) {
cupName = s.toString();
}
});
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
cupList = ((MainActivity)MainActivity.mContext).account.getCupList();
((MainActivity)MainActivity.mContext).cup.setUid((long)1);
((MainActivity)MainActivity.mContext).cup.setCupName(cupName);
((MainActivity)MainActivity.mContext).cup.setCupWeight(1111);
((MainActivity)MainActivity.mContext).saveCup();
Log.d("Cup Create Method : ", ((MainActivity)MainActivity.mContext).cup.toString());
//long savedCid = ((MainActivity)MainActivity.mContext).account.getCupList().get(0).getCid();
//((MainActivity)MainActivity.mContext).cup.setCid(savedCid);
//((MainActivity)MainActivity.mContext).chanceCup();
Toast.makeText(SaveCupName.this, "새로운 컵을 사용합니다.", Toast.LENGTH_SHORT).show();
//cupList.add(cup);
Intent intent = new Intent(SaveCupName.this, Change_information.class);
startActivity(intent);
}
});
}
}
|
Java | UTF-8 | 2,356 | 2.125 | 2 | [] | no_license | /*
* Copyright 2010 International Institute for Social History, The Netherlands.
*
* 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.
*/
package org.iish.visualmets.datamodels;
import java.util.ArrayList;
import java.util.List;
public class TocFolderItem
{
private static final long serialVersionUID = 7526471155622776147L;
private String title;
private String index;
private String haschildren;
public String getHaschildren() {
return haschildren;
}
public void setHaschildren(Object haschildren) {
this.haschildren = (haschildren == null)
? "false"
: String.valueOf(haschildren);
}
private List<TocFolderItem> breadcrumbs;
private List<TocMetsItem> metsitems;
private List<TocMetsItem> docs;
public TocFolderItem()
{
this.breadcrumbs = new ArrayList<TocFolderItem>();
this.metsitems = new ArrayList<TocMetsItem>();
this.docs = new ArrayList<TocMetsItem>();
}
public List<TocFolderItem> getBreadcrumbs() {
return breadcrumbs;
}
public List<TocMetsItem> getMetsitems() {
return metsitems;
}
public List<TocMetsItem> getDocs() {
return docs;
}
public void setBreadcrumbs(List<TocFolderItem> breadcrumbs) {
this.breadcrumbs = breadcrumbs;
}
public String getIndex() {
return index;
}
public void setIndex(String index) {
this.index = index;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public void add(TocMetsItem item)
{
metsitems.add(item);
}
public void add(TocFolderItem item)
{
breadcrumbs.add(item);
}
public void addDocs(TocMetsItem item)
{
docs.add(item);
}
}
|
Python | UTF-8 | 728 | 3.109375 | 3 | [] | no_license | import broom
import numpy as np
sw = broom.Sweeper()
def get_sub_array(A, which):
"""extract subarray from A determined by information in the list which
"""
if not A.ndim == len(which):
raise ValueError('A.ndim == len(which) not true')
A_shape = A.shape
slice_list = []
for n, dim in enumerate(which):
if dim == 'all':
slice_list.append(slice(0, A_shape[n]))
elif isinstance(dim, int) and dim - 1 <= A_shape[n]:
slice_list.append(dim)
else:
raise ValueError('invalid value in which list...')
return A[slice_list]
A = np.random.random((5, 3, 4))
which_list = [0, 'all', 2]
B = get_sub_array(A, which_list)
print A
print B |
C++ | UTF-8 | 4,118 | 2.53125 | 3 | [] | no_license | #pragma once
#include <optional>
#include "Vertex.h"
#include "IndexedTriangleList.h"
#include <DirectXMath.h>
#include "ChiliMath.h"
#include <array>
class Cube
{
public:
static IndexedTriangleList MakeIndependent( Dvtx::VertexLayout layout )
{
using namespace Dvtx;
using Type = Dvtx::VertexLayout::ElementType;
constexpr float side = 1.0f / 2.0f;
VertexBuffer vertices( std::move( layout ), 24u );
vertices[ 0 ].Attr<Type::Position3D>() = { -side,-side,-side };// 0 near side
vertices[ 1 ].Attr<Type::Position3D>() = { side,-side,-side };// 1
vertices[ 2 ].Attr<Type::Position3D>() = { -side,side,-side };// 2
vertices[ 3 ].Attr<Type::Position3D>() = { side,side,-side };// 3
vertices[ 4 ].Attr<Type::Position3D>() = { -side,-side,side };// 4 far side
vertices[ 5 ].Attr<Type::Position3D>() = { side,-side,side };// 5
vertices[ 6 ].Attr<Type::Position3D>() = { -side,side,side };// 6
vertices[ 7 ].Attr<Type::Position3D>() = { side,side,side };// 7
vertices[ 8 ].Attr<Type::Position3D>() = { -side,-side,-side };// 8 left side
vertices[ 9 ].Attr<Type::Position3D>() = { -side,side,-side };// 9
vertices[ 10 ].Attr<Type::Position3D>() = { -side,-side,side };// 10
vertices[ 11 ].Attr<Type::Position3D>() = { -side,side,side };// 11
vertices[ 12 ].Attr<Type::Position3D>() = { side,-side,-side };// 12 right side
vertices[ 13 ].Attr<Type::Position3D>() = { side,side,-side };// 13
vertices[ 14 ].Attr<Type::Position3D>() = { side,-side,side };// 14
vertices[ 15 ].Attr<Type::Position3D>() = { side,side,side };// 15
vertices[ 16 ].Attr<Type::Position3D>() = { -side,-side,-side };// 16 bottom side
vertices[ 17 ].Attr<Type::Position3D>() = { side,-side,-side };// 17
vertices[ 18 ].Attr<Type::Position3D>() = { -side,-side,side };// 18
vertices[ 19 ].Attr<Type::Position3D>() = { side,-side,side };// 19
vertices[ 20 ].Attr<Type::Position3D>() = { -side,side,-side };// 20 top side
vertices[ 21 ].Attr<Type::Position3D>() = { side,side,-side };// 21
vertices[ 22 ].Attr<Type::Position3D>() = { -side,side,side };// 22
vertices[ 23 ].Attr<Type::Position3D>() = { side,side,side };// 23
return{
std::move( vertices ),{
0,2, 1, 2,3,1,
4,5, 7, 4,7,6,
8,10, 9, 10,11,9,
12,13,15, 12,15,14,
16,17,18, 18,17,19,
20,23,21, 20,22,23
}
};
}
static IndexedTriangleList MakeIndependentTextured()
{
using namespace Dvtx;
using Type = Dvtx::VertexLayout::ElementType;
auto itl = MakeIndependent( std::move( VertexLayout{}
.Append( Type::Position3D )
.Append( Type::Normal )
.Append( Type::Texture2D )
) );
itl.vertices[ 0 ].Attr<Type::Texture2D>() = { 0.0f,0.0f };
itl.vertices[ 1 ].Attr<Type::Texture2D>() = { 1.0f,0.0f };
itl.vertices[ 2 ].Attr<Type::Texture2D>() = { 0.0f,1.0f };
itl.vertices[ 3 ].Attr<Type::Texture2D>() = { 1.0f,1.0f };
itl.vertices[ 4 ].Attr<Type::Texture2D>() = { 0.0f,0.0f };
itl.vertices[ 5 ].Attr<Type::Texture2D>() = { 1.0f,0.0f };
itl.vertices[ 6 ].Attr<Type::Texture2D>() = { 0.0f,1.0f };
itl.vertices[ 7 ].Attr<Type::Texture2D>() = { 1.0f,1.0f };
itl.vertices[ 8 ].Attr<Type::Texture2D>() = { 0.0f,0.0f };
itl.vertices[ 9 ].Attr<Type::Texture2D>() = { 1.0f,0.0f };
itl.vertices[ 10 ].Attr<Type::Texture2D>() = { 0.0f,1.0f };
itl.vertices[ 11 ].Attr<Type::Texture2D>() = { 1.0f,1.0f };
itl.vertices[ 12 ].Attr<Type::Texture2D>() = { 0.0f,0.0f };
itl.vertices[ 13 ].Attr<Type::Texture2D>() = { 1.0f,0.0f };
itl.vertices[ 14 ].Attr<Type::Texture2D>() = { 0.0f,1.0f };
itl.vertices[ 15 ].Attr<Type::Texture2D>() = { 1.0f,1.0f };
itl.vertices[ 16 ].Attr<Type::Texture2D>() = { 0.0f,0.0f };
itl.vertices[ 17 ].Attr<Type::Texture2D>() = { 1.0f,0.0f };
itl.vertices[ 18 ].Attr<Type::Texture2D>() = { 0.0f,1.0f };
itl.vertices[ 19 ].Attr<Type::Texture2D>() = { 1.0f,1.0f };
itl.vertices[ 20 ].Attr<Type::Texture2D>() = { 0.0f,0.0f };
itl.vertices[ 21 ].Attr<Type::Texture2D>() = { 1.0f,0.0f };
itl.vertices[ 22 ].Attr<Type::Texture2D>() = { 0.0f,1.0f };
itl.vertices[ 23 ].Attr<Type::Texture2D>() = { 1.0f,1.0f };
return itl;
}
}; |
Markdown | UTF-8 | 5,917 | 3.265625 | 3 | [] | no_license | ---
layout: post
title: "My First React Project"
date: 2017-03-23
---
React Doc Builder
======
A Form Wizard React App
------
This project was built using:
* React
* React-Redux
* React-Router
* React-Form
* React-Local-State
The goal of this project was to create a single page app form wizard. The user would select a document and sub document type (if necessary) for the form they wanted to fill out. The user would then fill out that form, which when reviewed and submitted, a PDF copy of the form would be returned.
## Running The App
```
npm install
npm start
```
The project will run on localhost:3000
## How It Works
### Overview
The project starts with React. React is what is use to render the App to the DOM. Redux is used to manage the App's state; Local-State backs up the Redux state to memory in case of page refresh. Router allows the app to use the URL to render different components. Redux Form builds the form, and handles validation.
#### React
The project begins with index.js and index.html. Index.js is used to render the app on index.html. Additionally in index.js, the redux store is created using the imported RootReducer from ```RootReducer.js```. Lastly, the App that is being rendered is the Redux's Provider.
#### React-Redux
React-Redux, stores the state of the Application in a single store. Redux uses actions and reducers to maintain state by dispatching actions to trigger reducers. All the app's reducers are stored in the Reducers folder. Each reducer is responsible for a single object in the state. For example, DocumentTypes.js is responsible DocumentTypes.
RootReducer uses the Redux API's ```combineReducers()``` to combine all the reducers into single map of reducers. Throughout the project, the store is passed around to different components through and as props.
A common React-Redux implementation practice throughout the project is the use of ```mapStateToProps``` and ```mapDispatchToProps```. Both are functions that returns a object containing functions that will dispatch and/or a mapping of store objects. ```mapStateToProps``` allows the component to subscribe to the store updates. Therefore, whenever the store updates, ```mapStateToProps``` is called. The results of ```mapStateToProps``` must be a plain object, which will be merged into the component’s props. ```mapDispatchToProps``` returns an object with the same function names, but with every action creator wrapped into a dispatch call so they may be invoked directly, will be merged into the component’s props. Example:
```javascript
import { nextFormSection, updateBackupForm } from '../../actions'
const mapStateToProps = (state) => {
return {
form: state.form,
formNavigator: state.formNavigator,
documentTypes: state.documentTypes,
backUpForm: state.backUpForm
}
}
const mapDispatchToProps = (dispatch) => {
return {
returnHomeFromFlow: _ => {
dispatch(nextFormSection(-1))
},
backOneFlowStep: index => {
dispatch(nextFormSection(index - 1))
},
nextFlowStep: index => {
dispatch(nextFormSection(index + 1))
},
saveFormDraft: values => {
dispatch(updateBackupForm(values))
}
}
}
```
#### React-Router
React-Router handles the routing of the app. Router app starts at App/index.js, where the ```BrowserRouter``` component is used to store various browser related metadata such as history. In the same directory, layout.js, handles the routing of the Home and Form routes. The Form Route uses two path params which contain the document and sub document type. Those two params determine which document was selected and retrieves the fields selected. In ```Form/layout.js```, ```createFormStepRoutes ``` creates routes for each section in the document. A form component is rendered when the route is activated. The App uses the json to determine which form component gets rendered by mapping the json value to one of ```FormMap```'s keys.
#### React-Local-State
#### React-Form
Next Steps
=======
This app has evolved and grown over time to be what it is, ugly but working. There are a number of clean up tasks that need to be taken care of to improve the look and functionality.
* Form
* Validation
While the form works, it's missing form validation. It's been attempted once, try again.
* Improved Form
The current state of the form is pretty bad. It's only input fields. Radio Buttons and Dropdowns need to be added.
* Document Type Selector Drawer
The Document Type Seletor Drawer (DTSD) would exist on the right side of the page. There would be a some kind of interactable that would trigger the drawer to open. There, the user could chose a different document to generate. After confiming decision to discard the current document, the user will navigate back to the Form Wizard Document Page.
* Document Image Preview
A Nice-To-Have would be a component that contains a preview image of the document. The component would be in the Form Wizard Document Page. This way the user can see the finished product before proceeding.
* Style
The ```style-refactor``` branch cleaned a lot of the mess, but it's very rough. The Form Review page needs to be fixed up. The Form Review page should have collapsable section to free up some page real estate.
* Code Quality
There a number of code issues that need to be fixed.
* Remove loops from ```DocumentTypeParser.js```. Use ```jsonQuery``` instead.
* Remove unused package dependencies from code and ```package.json```
* Create shared exported functions for Form Components. Remove redundant code from each.
Final Vision
=======
It would be really nice to integrate this app with a backend API that can use libraries such as PDFReactor and Mustache to generate document, send a copy to RestHeart, and return a copy to the user.
|
Java | UTF-8 | 697 | 1.9375 | 2 | [] | no_license | package th.co.imake.missconsult.assessment.form;
import java.io.Serializable;
public class McResultPKForm extends CommonForm implements Serializable {
//default serial version id, required for serializable classes.
private static final long serialVersionUID = 1L;
private Integer mcustAssessmentId;
private String mdaHotlink;
public McResultPKForm() {
}
public Integer getMcustAssessmentId() {
return this.mcustAssessmentId;
}
public void setMcustAssessmentId(Integer mcustAssessmentId) {
this.mcustAssessmentId = mcustAssessmentId;
}
public String getMdaHotlink() {
return this.mdaHotlink;
}
public void setMdaHotlink(String mdaHotlink) {
this.mdaHotlink = mdaHotlink;
}
} |
Java | UTF-8 | 374 | 1.820313 | 2 | [] | no_license | package org.igov.model.relation;
import org.igov.model.core.GenericEntityDao;
import org.springframework.stereotype.Repository;
/**
*
* @author Kovilin
*/
@Repository
public class ObjectItemDaoImpl extends GenericEntityDao<Long, ObjectItem> implements ObjectItemDao {
public ObjectItemDaoImpl() {
super(ObjectItem.class);
}
}
|
C# | UTF-8 | 4,320 | 2.96875 | 3 | [] | no_license | using System;
using System.Reflection;
using System.Windows.Forms;
namespace FuzzySelector.Client
{
public partial class WSDLConnectorForm : Form
{
/// <summary>
/// Abstractizarea proprietatilor unei metode a unui serviciu web (ce poate fi invocata).
/// </summary>
private class Properties
{
/// <summary>
/// Tipurile parametrilor metodei.
/// </summary>
private Type[] myTypes;
/// <summary>
/// Valorile date parametrilor metodei.
/// </summary>
private String[] myValues;
/// <summary>
/// Numele parametrilor metodei.
/// </summary>
private String[] myNames;
/// <summary>
/// Pozitie in cadrul parametrilor metodei.
/// </summary>
private int index;
public Properties(int capacity)
{
myTypes = new Type[capacity];
myValues = new String[capacity];
myNames = new String[capacity];
}
[System.ComponentModel.Category("Parameter"),
System.ComponentModel.ReadOnly(true),
System.ComponentModel.Description("Name of parameter")]
public String Name
{
get { return myNames[index]; }
set { myNames[index] = value; }
}
[System.ComponentModel.Category("Parameter"),
System.ComponentModel.ReadOnly(true),
System.ComponentModel.Description("Type of parameter")]
public Type Type
{
get { return myTypes[index]; }
set { myTypes[index] = value; }
}
[System.ComponentModel.Category("Parameter"),
System.ComponentModel.Description("Enter value but with great attention to Type of parameter")]
public String Value
{
get { return myValues[index]; }
set { myValues[index] = value; }
}
[System.ComponentModel.Browsable(false)]
public int Index
{
set { index = value; }
}
[System.ComponentModel.Browsable(false)]
public Type[] MyTypes
{
get { return myTypes; }
}
/// <summary>
/// Are loc o conversia valorilor specificate pentru parametrii la tipurile declarate.
/// </summary>
[System.ComponentModel.Browsable(false)]
public Object[] MyParameters
{
get
{
int capacity = myNames.Length;
if (capacity > 0)
{
Object[] myParameters = new Object[capacity];
string message = string.Empty;
for (int i = 0; i < capacity; ++i)
{
if (myValues[i] != null)
{
try
{
myParameters[i] = Convert.ChangeType(myValues[i], myTypes[i]);
}
catch (Exception e)
{
Value = null;
message += myNames[i] + " " + e.Message + "\r\n";
}
}
else
{
message += myNames[i] + " Value must be set" + "\r\n";
}
}
if (message != String.Empty)
{
throw new Exception(message);
}
else
{
return myParameters;
}
}
else
{
return null;
}
}
}
}
}
}
|
Python | UTF-8 | 2,150 | 3.3125 | 3 | [] | no_license | import pandas as pd
import numpy as np
import nltk
from nltk.corpus import stopwords
from nltk.tokenize import word_tokenize
from nltk.stem import PorterStemmer
from string import punctuation
# nltk.download()
# nltk.download('punkt')
# if you have not downloaded the nltk corpus, then uncomment the lines above
def parseJoke(filename):
data = pd.read_csv(filename)
return data
def CreateMyStopWords ():
stopword = stopwords.words("english")
stopword.remove(u't')
stopword.remove(u's')
stopword.append(u"'s")
stopword.append(u"'t")
stopword.append(u"n't")
stopword.append(u"'d")
stopword.append(u"'re")
stopword.append(u"cannot")
stopword.append(u"'ll")
stopword.append(u"'ve")
stopword.append(u"'m")
stopword.append(u"q")
stopword.append(u"could")
stopword.append(u"would")
return stopword
def is_valid_hyphen_word(str):
flag = False
if str[0].isalpha() and str[len(str) - 1].isalpha():
for chr in str:
if chr.isalpha():
flag = False
elif chr == "-":
if flag:
return False
else:
flag = True
else:
return False
return True
return False
def DataCleaningForKaggleSA(data):
stopword = CreateMyStopWords()
porterStemmer = PorterStemmer()
for i in range(len(data)):
row = data.iloc[i]
sentence = row["Joke"].replace("’", "'").lower()
for chr in sentence:
if (ord(chr) >= 128):
sentence = sentence.replace(chr, '')
words = word_tokenize(sentence)
cleanData = []
for w in words:
if w not in stopword:
if all(chr not in punctuation for chr in w) or is_valid_hyphen_word(w):
cleanData.append(porterStemmer.stem(w))
cleanSentence = ' '.join(cleanData)
data.set_value(i, "Joke", cleanSentence)
return data
data = parseJoke("jokes.csv")
DataCleaningForKaggleSA(data).to_csv("cleanedJokes.csv")
|
Ruby | UTF-8 | 517 | 4.1875 | 4 | [] | no_license | # Merging: That is, given two sorted arrays like the following we must merge them into one sorted array.
# iterative
def merge(array1, array2)
result = []
index_one = 0
index_two = 0
while index_one < array1.length
ele_one = array1[index_one]
ele_two = array2[index_two]
while index_two < array2.length && ele_one > ele_two
result.push(ele_two)
index_two += 1
ele_two = array2[index_two]
end
result.push(ele_one)
index_one += 1
end
result
end
# recursive TODO! |
Markdown | UTF-8 | 1,340 | 3.15625 | 3 | [] | no_license | # Cleaning and Getting Data course project
An analysis of accelerometer data generated from an experiment with Samsung Galaxy S smartphones.
# Script
1. Merges the training and the test sets to create one data set.
2. Extracts only the measurements on the mean and standard deviation for each measurement.
3. Uses descriptive activity names to name the activities in the data set
4. Appropriately labels the data set with descriptive variable names.
5. From the data set in step 4, creates a second, independent tidy data set with the average of each variable for each activity and each subject.
# code book
Group.1 means activity labels,
- 1 WALKING
- 2 WALKING_UPSTAIRS
- 3 WALKING_DOWNSTAIRS
- 4 SITTING
- 5 STANDING
- 6 LAYING
Group.2 means subject, from 1 to 30.
These signals were used to estimate variables of the feature vector for each pattern:
'-XYZ' is used to denote 3-axial signals in the X, Y and Z directions.
- tBodyAcc-XYZ
- tGravityAcc-XYZ
- tBodyAccJerk-XYZ
- tBodyGyro-XYZ
- tBodyGyroJerk-XYZ
- tBodyAccMag
- tGravityAccMag
- tBodyAccJerkMag
- tBodyGyroMag
- tBodyGyroJerkMag
- fBodyAcc-XYZ
- fBodyAccJerk-XYZ
- fBodyGyro-XYZ
- fBodyAccMag
- fBodyAccJerkMag
- fBodyGyroMag
- fBodyGyroJerkMag
The set of variables that were estimated from these signals are:
- mean: Mean value
- std: Standard deviation
|
Java | UTF-8 | 343 | 2.296875 | 2 | [] | no_license | package com.leketo.lolilo.entity;
import java.time.LocalDate;
/**
* Interface to be implemented by entities that contain information about who created them and when.
*/
public interface Creatable {
LocalDate getCreateTs();
void setCreateTs(LocalDate date);
String getCreatedBy();
void setCreatedBy(String createdBy);
}
|
Java | UTF-8 | 9,855 | 1.9375 | 2 | [] | no_license | package com.example.user.ordersystem;
import android.app.DatePickerDialog;
import android.app.TimePickerDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.TextView;
import android.widget.TimePicker;
import org.json.JSONArray;
import org.json.JSONObject;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.LinkedList;
import java.util.List;
public class SeatPage extends AppCompatActivity {
Button[] btns = new Button[10];
private Button doSetDate;
private Button doSetTime;
private TextView textDate;
private TextView textTime;
private DatePickerDialog datePickerDialog;
private TimePickerDialog timePickerDialog;
private TextView tableNmb;
private String tableNumber;
//----------------------------------
private int count;
private UIHandler uiHandler;
private String SeatState1 , SeatState2 , SeatState3 , SeatState4 , SeatState5 , SeatState6,
SeatState7 , SeatState8 , SeatState9 , SeatState0;
private String loginId;
private MyReceiver myReceiver;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_seat_page);
doFindView();
GregorianCalendar calendar = new GregorianCalendar();
datePickerDialog = new DatePickerDialog(this, new DatePickerDialog.OnDateSetListener() {
@Override
public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
int month = monthOfYear+1;
textDate.setText((year+"/"+month+"/"+dayOfMonth));
}
},calendar.get(Calendar.YEAR),calendar.get(Calendar.MONTH),calendar.get(Calendar.DAY_OF_MONTH));
timePickerDialog = new TimePickerDialog(this, new TimePickerDialog.OnTimeSetListener(){
@Override
public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
textTime.setText((hourOfDay>12?hourOfDay-12:hourOfDay)
+":"+minute+" "+(hourOfDay>12?"PM":"AM"));
}
},calendar.get(Calendar.HOUR_OF_DAY),calendar.get(Calendar.MINUTE),false);
Button button = (Button)findViewById(R.id.goSuccessPage);
button.setOnClickListener(clickListenerGo);
for (int i = 0; i < 10; i++) {
btns[i].setOnClickListener(clickListener);}
//---------DATA BASE-----------
pullData();
uiHandler = new UIHandler();
//---------從Service提取資料---------
myReceiver = new MyReceiver();
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction("test");
registerReceiver(myReceiver,intentFilter);
}
@Override
protected void onRestart() {
super.onRestart();
Intent it = new Intent(SeatPage.this,MyService.class);
startService(it);
}
//找View By ID
public void doFindView(){
btns[0] = (Button)findViewById(R.id.b0);
btns[1] = (Button)findViewById(R.id.b1);
btns[2] = (Button)findViewById(R.id.b2);
btns[3] = (Button)findViewById(R.id.b3);
btns[4] = (Button)findViewById(R.id.b4);
btns[5] = (Button)findViewById(R.id.b5);
btns[6] = (Button)findViewById(R.id.b6);
btns[7] = (Button)findViewById(R.id.b7);
btns[8] = (Button)findViewById(R.id.b8);
btns[9] = (Button)findViewById(R.id.b9);
doSetDate = (Button)findViewById(R.id.buttonDate);
doSetTime = (Button)findViewById(R.id.buttonTime);
textDate = (TextView)findViewById(R.id.datetext);
textTime = (TextView)findViewById(R.id.timetext);
tableNmb = (TextView)findViewById(R.id.tableNmb);
}
//日期視窗
public void setDate(View v){
datePickerDialog.show();
}
//日期視窗
public void setTime(View v){
timePickerDialog.show();
}
//位置按鈕
View.OnClickListener clickListener = new View.OnClickListener() {
public void onClick(View v) {
for(int i = 0;i<10;i++) {
btns[i].setBackgroundColor(getResources().getColor(R.color.colorWhite));
}
v.setBackgroundColor(getResources().getColor(R.color.colorOrange));
//顯示桌號 tableNmb
Button b = (Button) v;
tableNumber = b.getText().toString();
tableNmb.setText("你選擇了 " + tableNumber + "號桌");
}
};
//移動按鈕&上傳資料
View.OnClickListener clickListenerGo = new View.OnClickListener(){
public void onClick(View v){
Intent it = new Intent();
it.setClass(SeatPage.this,SuccessPage.class);
pushData();
startActivity(it);
finish();
//上傳資料
}
};
//
//桌號資料變數> tableNumber
//---------------------DATA BASE-----------------------
//提取資料
public void pullData(){
new Thread(){
@Override
public void run() {
try {
MultipartUtility mu = new MultipartUtility("https://android-test-db-ppking2897.c9users.io/DataBase/SeatQuery02.php", "UTF-8");
List<String> ret = mu.finish();
parseJSON(ret.toString());
} catch (Exception e) {
Log.v("ppking", "DB Error:" + e.toString());
}
}
}.start();
}
public void pushData(){
new Thread() {
@Override
public void run() {
try {
count++;
MultipartUtility mu = new MultipartUtility("https://android-test-db-ppking2897.c9users.io/DataBase/AccountUpload02.php", "UTF-8");
if(count<2) {
mu.addFormField("accountid", loginId);
mu.addFormField("resdate", textDate.getText().toString());
mu.addFormField("restime", textTime.getText().toString());
mu.addFormField("seatidnumber",tableNumber);
List<String> ret = mu.finish();
Log.v("ppking", "ret update:: " + ret);
}
} catch (Exception e) {
Log.v("ppking", "DB Error:" + e.toString());
}
}
}.start();
}
//接收JSON格式並且找特定字串
private void parseJSON(String json){
LinkedList accountInfo = new LinkedList<>();
try{
// JSONObject jsonObject = new JSONArray(json).getJSONObject(0);
JSONArray jsonArray = new JSONArray(json).getJSONArray(0);
for(int i = 0 ; i <=9 ; i++ ) {
String stringNo = jsonArray.getString(i);
accountInfo.add(stringNo);
// String stringNo1 = jsonArray.getString(1);
// accountInfo.add(stringNo1);
}
Message mesg = new Message();
Bundle data = new Bundle();
for (int i = 0 ; i<=9 ; i++) {
data.putCharSequence("data"+i, accountInfo.get(i).toString());
// data.putCharSequence("data1", accountInfo.get(1).toString());
// data.putCharSequence("data2",accountInfo.get(2).toString());
}
mesg.setData(data);
mesg.what=0;
uiHandler.sendMessage(mesg);
}catch (Exception e){
Log.v("ppking", "Error : " + e.toString());
}
}
//由handler這邊將資料丟到前景UI
private class UIHandler extends android.os.Handler{
@Override
public void handleMessage(Message msg) {
switch (msg.what){
case 0 :
// textView.setText("Accound : "+msg.getData().getCharSequence("data0")+"\n");
// textView.append("SeatIdNumber : "+msg.getData().getCharSequence("data1")+"\n");
// textView.append("Checkout : $"+msg.getData().getCharSequence("data2")+"\n");
//TODO:各座位的狀態,去判斷座位
SeatState0 = msg.getData().getCharSequence("data0").toString();
SeatState1 = msg.getData().getCharSequence("data1").toString();
SeatState2 = msg.getData().getCharSequence("data2").toString();
SeatState3 = msg.getData().getCharSequence("data3").toString();
SeatState4 = msg.getData().getCharSequence("data4").toString();
SeatState5 = msg.getData().getCharSequence("data5").toString();
SeatState6 = msg.getData().getCharSequence("data6").toString();
SeatState7 = msg.getData().getCharSequence("data7").toString();
SeatState8 = msg.getData().getCharSequence("data8").toString();
SeatState9 = msg.getData().getCharSequence("data9").toString();
break;
}
}
}
private class MyReceiver extends BroadcastReceiver{
@Override
public void onReceive(Context context, Intent intent) {
//-----------從Service提取資料
loginId = intent.getStringExtra("ppking");
Log.v("ppking" , "loginId" + loginId);
}
}
//------------------------------END----------------------------------------------------------
}
|
Java | UTF-8 | 526 | 2.09375 | 2 | [] | no_license | package com.enji_iot.mqtt.Service;
import java.util.Map;
/**
* 邮件服务
*
*/
public interface MailService_MQTT {
/**
*
* 把模板换算成字符串
*
* @return
*/
public String mergeTemplateIntoString(String tpl, Map<String, Object> param);
/**
*
* 发送邮件
*
* @param mailTo
* @param mailSubject
* @param templateLocation
* @param param
*/
public void send(String mailTo, String mailSubject, String templateLocation, Map<String, Object> param);
}
|
Ruby | UTF-8 | 3,467 | 2.609375 | 3 | [] | no_license |
#Framework
require 'sinatra'
require 'sinatra/reloader'
#database configuration
require 'pg'
require_relative 'db_config'
#model classes
require_relative 'models/dish'
require_relative 'models/user'
require_relative 'models/comment'
#test console
require 'pry'
#activate session control
enable :sessions
#methods inside 'helpers' are global
helpers do
#Session check
def logged_in?
if User.find_by(id: session[:user_id]) == nil
return false
else
return true
end
end
#user profile accessor
def current_user
User.find(session[:user_id])
end
end
#mainpage display all dishes
get '/' do
@dishes = Dish.all
erb :index
end
#direction route to add dish form
get '/dishes/new' do
if !logged_in?
redirect to "/session/new"
else
erb :new
end
end
#action route: add the new dish via post method
post '/dishes' do
if !logged_in?
redirect to "/session/new"
else
dish_new = Dish.new()
dish_new.name = params[:name]
dish_new.img_url = params[:img_url]
dish_new.user_id = current_user.id
#if use plain SQL query:
#run_sql("insert into dishes(name, img_url) values ('#{params[:name]}', '#{params[:img_url]}');")
#@dishes = db.exec('select * from dishes;')
dish_new.save
redirect to '/'
end
end
#Show detailed dish info (get)
get '/dishes/:id' do
@dish = Dish.find(params[:id])
@comments = Comment.where(dish_id: params[:id])
#@dish = run_sql("select * from dishes where id = '#{params[:id]}';")
erb :dish
end
#direction route: get the selected dish, and direct to the edit form page
get '/dishes/:id/edit' do
@dish = Dish.find(params[:id])
#@dish = run_sql("select * from dishes where id = '#{params[:id]}';")
erb :edit
end
#action route: find the dish and update
put '/dishes/:id' do
if !logged_in?
redirect to "/session/new"
else
dish = Dish.find(params[:id])
dish.name = params[:name]
dish.img_url = params[:img_url]
dish.save
redirect to '/'
end
end
#deletion using delete method
delete '/dishes/:id' do
if !logged_in?
redirect to "/session/new"
else
dish = Dish.find(params[:id])
dish.destroy
# sql = "delete from dishes where id = '#{params[:id]}';"
# run_sql(sql)
redirect to '/'
end
end
#direction route: get the dishes of the current user and direction to myDish.erb
get '/show_my_dish' do
@my_dishes = current_user.dishes
erb :myDish
end
#receive the dish_id param passed by hidden field
post '/comment' do
cmt = Comment.new
cmt.user_id = current_user.id
cmt.dish_id = params[:dish_id]
cmt.comment = params[:comment]
cmt.save
@dish = Dish.find(cmt.dish_id)
@comments = Comment.where(dish_id: params[:dish_id])
erb :dish
end
# direction to the login form page
get '/session/new' do
# login form
erb :login
end
#action route: validate the user
post '/session' do
# logging in..
user = User.find_by(email: params[:email])
if user && user.authenticate(params[:pw])
session[:user_id] = user.id
redirect to '/'
else
erb :login
end
end
#log off
delete '/session' do
session.delete(:user_id)
erb :login
end
#direction route to the signup page
get '/signup' do
erb :signup
end
#action route: add the new user
post '/signup/post' do
new_user = User.new()
new_user.email = params[:uname]
new_user.password = params[:pw]
new_user.save
@user = User.find_by(email: params[:uname])
session[:user_id] = @user.id
erb :congras_new
end
|
Java | UTF-8 | 845 | 2.65625 | 3 | [] | no_license | package assignments.assignment2;
import org.grouplens.lenskit.data.event.Rating;
import org.grouplens.lenskit.vectors.MutableSparseVector;
public interface IUserProfileType {
/**
* This method updates the User profile vector given the data model and the
* rating that is supposed to affect the User vector.
*
* @param userProfile Current vector of the User's profile which should be updated.
* @param model Data model to be able to retrieve the vector of the Item that the User rated.
* @param rating Rating object the User, represented here by the profile vector, gave to a certain Item.
* @param userRatingsMean The average mean of all the ratings of the user.
*/
public void updateUserProfile(MutableSparseVector userProfile,
ContentBasedDataModel model, Rating rating, double userRatingsMean);
}
|
Markdown | UTF-8 | 3,601 | 2.703125 | 3 | [] | no_license | ---
title: "680 - Two Of A Kind"
url: /2008/08/680-two-of-kind.html
publishDate: Sun, 24 Aug 2008 04:28:00 +0000
date: 2008-08-24 04:28:00
categories:
- "nikon-851-8"
tags:
- "austria"
- "bicycle"
- "newspaper"
- "nikon-d300"
- "vienna"
- "wien"
---
<a href="https://d25zfm9zpd7gm5.cloudfront.net/1200x1200/2008/20080823_191625_ps.jpg" target="_blank"><img src="https://d25zfm9zpd7gm5.cloudfront.net/0600x0600/2008/20080823_191625_ps.jpg"/></a><br/><br/>What's that you ask? Well, that is one way how newspapers are sold in Austria on weekends. Pouches with newspapers are mounted at signposts, with an attached receptacle for money, and people who take a paper are expected to insert the appropriate number of coins. By and large this even seems to work. <br/><br/>I have seen some more mechanic solutions where you would not get the paper without inserting money, but those vending machines seem to not have survived the currency change that happened in 2002, when Austria gave up on its Schilling and embraced the Euro. In fact it was the same with most vending machines in low profit businesses. The cost of adapting the machines to accept the new coins was prohibitive and caused many goods to not be sold this way any more, or in the case of newspapers, it brought a revival of trust. What a nice effect 🙂<br/><br/>The title? Well, those two newspapers "<a href="http://diepresse.com/" target="_blank">Die Presse</a>" and "<a href="http://derstandard.at/" target="_blank">Der Standard</a>", hanging there in concord, are two of the best newspapers in Austria, one strictly conservative, one liberal, and they both compete for the same small market of highly educated people who don't submit to the yellow press. Of course they try to be different, just look at the colors of the money boxes 🙂<br/><br/>And there is more irony to it. The red sticker in between, reading "Krone Hit Radio", advertises for a radio station owned by the biggest and one of the worst of Austria's newspapers, "<a href="http://www.krone.at/" target="_blank">Kronen Zeitung</a>". What a rare display of unity.<br/><br/><a href="https://d25zfm9zpd7gm5.cloudfront.net/1200x1200/2008/20080823_192455_ps.jpg" target="_blank"><img alt="" border="0" src="https://d25zfm9zpd7gm5.cloudfront.net/0150x0150/2008/20080823_192455_ps.jpg" style="margin: 0pt 10px 0pt 0px; float: left;"/></a> Let me close with one more bicycle, one more <a href="/search/label/Puch" target="_blank">Puch</a>. Both of these images were shot with the Nikon 85/1.8, both wide open. When I left work yesterday (yes, it's morning again) at 7pm, it was so dark that I decided to change from the slow 70-300 to something real fast, and I feel that the 85 is underused. I'll be off for work in about an hour, and I'll keep this lens mounted for now. Weather has not improved anyway.<br/><br/>Some time passes ... nope, I will not. I just come from the bathroom, and while I was indulging extensively in the joys of hot water, weather has considerably improved. The sun is shining again, it's got to be back to the 70-300 🙂 <br/><br/>The Song of the Day is "<a href="http://www.lyricstime.com/memphis-slim-two-of-a-kind-lyrics.html" target="_blank">Two Of A Kind</a>" by Memphis Slim. I have it on disc 53 of "<a href="http://www.amazon.com/Ultimate-Jazz-Archive-Various-Artists/dp/B000B7I3W4" target="_blank">The Ultimate Jazz Archive</a>", but if you look for something more ... well ... slim, I'd suggest the 1961 album "<a href="http://www.amazon.com/All-Kinds-Blues-Memphis-Slim/dp/B000000XWX" target="_blank">All Kinds of Blues</a>".
|
C# | UTF-8 | 24,136 | 2.78125 | 3 | [] | no_license | using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Dinamica
{
public class Memoria : IEnumerable
{
//Lista enlazada doble
public Particion Primera;
public Particion Ultima;
public int Count = 0;
public double MemoriaDisponible = 0, MemoriaTotal = 0;
public string modo = "particiones";
public List<string> nombresUsados = new List<string>();
/// <summary>
/// Altura total
/// </summary>
public int Height;
/// <summary>
/// Tamaño dado de KB
/// </summary>
public double Size = 0;
/// <summary>
/// Sistema operativo
/// </summary>
public Particion SO = null;
/// <summary>
/// Particiones
/// </summary>
public BindingList<Particion> StandBy = new BindingList<Particion>();
/// <summary>
/// Constructor para inicializar valores de la memoria
/// </summary>
/// <param name="_size">Tamaño en KB de la memoria</param>
/// <param name="_height"> Altura </param>
public Memoria(double _size, int _height)
{
Size = _size;
Height = _height;
MemoriaTotal = Size;
MemoriaDisponible = Size;
}
public void MostrarMemoriaDisponible()
{
modo = "libres";
MemoriaDisponible = 0;
foreach (Particion e in this)
{
MemoriaDisponible += e.Size;
}
}
public Particion CrearParticion(double _size, bool _estado)
{
double value = (_size * 100) / Size;
value = Nucleo.Truncate(value, 0);
double porcentaje = 0;
if (value.ToString().Length == 1)
{
porcentaje = double.Parse(".0" + value.ToString());
}
else
{
porcentaje = double.Parse("." + value.ToString());
}
double height = porcentaje * Height;
int heightInt = (int)height;
Particion P = new Particion(_size, heightInt, _estado);
return P;
}
public Particion CrearParticion(double _size, bool _estado, string _titulo)
{
double value = (_size * 100) / Size;
value = Nucleo.Truncate(value, 0);
double porcentaje = 0;
if (value.ToString().Length == 1)
{
porcentaje = double.Parse(".0" + value.ToString());
}
else
{
porcentaje = double.Parse("." + value.ToString());
}
double height = porcentaje * Height;
int heightInt = (int)height;
Particion P = new Particion(_size, heightInt, _estado, _titulo);
return P;
}
public Particion TraerUltimo()
{
Particion actual = Primera;
while (actual.Siguiente != null)
{
actual = actual.Siguiente;
}
return actual;
}
public bool EsLaCantidadMenor(double _cant)
{
double? cantidadMenor = null;
Particion actual = Primera;
while (actual != null)
{
if (!actual.Ocupada)
{
if (cantidadMenor == null && actual.Size >= _cant)
{
cantidadMenor = actual.Size;
}
else
{
if (actual.Size <= cantidadMenor && actual.Size >= _cant)
{
cantidadMenor = actual.Size;
}
}
}
actual = actual.Siguiente;
}
if (_cant <= cantidadMenor)
{
return true;
}
else
{
return false;
}
}
public bool AgregarParticion(double _size, bool _estado, string _titulo)
{
bool encontradoTitulo = false;
Particion actual = Primera;
while (actual != null && !encontradoTitulo)
{
if (actual.id == _titulo)
{
encontradoTitulo = true;
MessageBox.Show("El nombre de la tarea ya existe");
}
actual = actual.Siguiente;
}
if (!encontradoTitulo)
{
foreach (string x in nombresUsados)
{
if (x == _titulo)
{
encontradoTitulo = true;
MessageBox.Show("El nombre de la tarea ya ha sido utilizado con anterioridad");
}
}
}
if (!encontradoTitulo)
{
//En caso de no existir ninguna particion
if (Primera == null)
{
if (_size <= MemoriaDisponible)
{
Particion P = CrearParticion(_size, _estado, _titulo);
Primera = P;
Ultima = TraerUltimo();
nombresUsados.Add(_titulo);
return true;
}
else
{
MessageBox.Show("No hay memoria disponible");
return false;
}
}
else
{
bool insertado = false;
actual = Primera;
//En caso de tener solo 1 particion
if (actual.Siguiente == null)
{
if (!actual.Ocupada)
{
if (_size <= actual.Size)
{
insertado = true;
if ((actual.Size - _size) != 0)
{
Particion P = CrearParticion(_size, _estado, _titulo);
nombresUsados.Add(_titulo);
Particion next = CrearParticion((actual.Size - _size), false);
next.Anterior = P;
P.Siguiente = next;
Primera = P;
Ultima = TraerUltimo();
}
else
{
Particion P = CrearParticion(_size, _estado, _titulo);
nombresUsados.Add(_titulo);
Primera = P;
Ultima = TraerUltimo();
}
}
}
}
while (actual != null && !insertado)
{
if (actual.Ocupada)
{
actual = actual.Siguiente;
}
else
{
if (_size <= actual.Size)
{
if (EsLaCantidadMenor(actual.Size))
{
//Tiene un anterior
if (actual.Anterior != null)
{
//Particion con la tarea
Particion P = CrearParticion(_size, _estado, _titulo);
nombresUsados.Add(_titulo);
Particion anterior = actual.Anterior;
if ((actual.Size - _size) != 0)
{
//Particion con el espacio libre
Particion aux = CrearParticion((actual.Size - _size), false);
aux.Siguiente = actual.Siguiente;
aux.Anterior = P;
P.Siguiente = aux;
P.Anterior = anterior;
if (actual.Siguiente != null)
{
actual.Siguiente.Anterior = aux;
}
anterior.Siguiente = P;
Ultima = TraerUltimo();
insertado = true;
}
else
{
//Solo la particion completa
P.Siguiente = actual.Siguiente;
P.Anterior = anterior;
if(actual.Siguiente != null)
{
actual.Siguiente.Anterior = P;
}
anterior.Siguiente = P;
Ultima = TraerUltimo();
insertado = true;
}
}
else
{
if ((actual.Size - _size) != 0)
{
MessageBox.Show("x1");
Particion P = CrearParticion(_size, _estado, _titulo);
nombresUsados.Add(_titulo);
P.Siguiente = CrearParticion((actual.Size - _size), false).Siguiente = actual.Siguiente;
Primera = P;
Ultima = TraerUltimo();
}
else
{
MessageBox.Show("x2");
Particion P = CrearParticion(_size, _estado, _titulo);
P.Siguiente = actual.Siguiente;
if(actual.Siguiente != null)
{
actual.Siguiente.Anterior = P;
}
nombresUsados.Add(_titulo);
actual = P;
Primera = P;
Ultima = TraerUltimo();
}
}
}
else
{
actual = actual.Siguiente;
}
}
else
{
actual = actual.Siguiente;
}
}
}
if (!insertado)
{
//Agregar al StandBy
if(_size <= (MemoriaTotal - SO.Size))
{
Particion P = CrearParticion(_size, _estado, _titulo);
nombresUsados.Add(_titulo);
StandBy.Add(P);
}
else
{
MessageBox.Show("No hay espacio disponible");
}
}
return insertado;
}
}
else
{
MessageBox.Show("Titulo utilizado");
return false;
}
}
public bool Librear(int _cont)
{
bool liberado = false;
bool encontrado = false;
Particion actual = Primera;
int count = -1;
while (actual != null && !encontrado)
{
if (actual.Ocupada)
{
count++;
}
//MessageBox.Show($"-->({count}) id: {actual.id} ");
if (count == _cont)
{
encontrado = true;
//en caso de que tenga los dos espacios libres
if (actual.Anterior != null && !actual.Anterior.Ocupada && actual.Siguiente != null && !actual.Siguiente.Ocupada)
{
//MessageBox.Show("Dos espacios libres para combinar");
double SizeTotal = actual.Anterior.Size + actual.Size + actual.Siguiente.Size;
Particion p = CrearParticion(SizeTotal, false);
p.Siguiente = actual.Siguiente.Siguiente;
if (actual.Siguiente.Siguiente != null)
{
actual.Siguiente.Siguiente.Anterior = p;
}
else
{
Ultima = p;
}
p.Anterior = actual.Anterior.Anterior;
if (actual.Anterior.Anterior != null)
{
actual.Anterior.Anterior.Siguiente = p;
}
else
{
Primera = p;
}
}
else if ((actual.Anterior != null && !actual.Anterior.Ocupada) || (actual.Siguiente != null && !actual.Siguiente.Ocupada))
{
//En caso de que tenga un espacio liberado anterior
if (actual.Anterior != null && !actual.Anterior.Ocupada)
{
// MessageBox.Show($"Espacio libre a anterior de {actual.id} detectado");
//En caso de que se trate del primer elemento
if (actual.Anterior.Anterior == null)
{
double SizeTotal = actual.Anterior.Size + actual.Size;
Particion p = CrearParticion(SizeTotal, false);
p.Siguiente = actual.Siguiente;
if (actual.Siguiente != null)
{
actual.Siguiente.Anterior = p;
}
actual.Anterior = p;
Primera = p;
encontrado = true;
}
else
{
double SizeTotal = actual.Anterior.Size + actual.Size;
Particion p = CrearParticion(SizeTotal, false);
p.Siguiente = actual.Siguiente;
if (actual.Siguiente != null)
{
actual.Siguiente.Anterior = p;
}
else
{
Ultima = p;
}
p.Anterior = actual.Anterior.Anterior;
actual.Anterior.Anterior.Siguiente = p;
encontrado = true;
}
}
//En caso de que tenga un espacio liberado siguiente
if (actual.Siguiente != null && !actual.Siguiente.Ocupada)
{
// MessageBox.Show("Espacio libre al siguiente detectado"); //En caso de que se trate del primer elemento
if (actual.Anterior == null)
{
double SizeTotal = actual.Size + actual.Siguiente.Size;
Particion p = CrearParticion(SizeTotal, false);
p.Siguiente = actual.Siguiente.Siguiente;
if (actual.Siguiente.Siguiente != null)
{
actual.Siguiente.Siguiente.Anterior = p;
}
else
{
Ultima = p;
}
Primera = p;
liberado = true;
encontrado = true;
}
else
{
double SizeTotal = actual.Size + actual.Siguiente.Size;
Particion p = CrearParticion(SizeTotal, false);
p.Siguiente = actual.Siguiente.Siguiente;
if (actual.Siguiente.Siguiente != null)
{
actual.Siguiente.Siguiente.Anterior = p;
}
else
{
Ultima = p;
}
p.Anterior = actual.Anterior;
actual.Anterior.Siguiente = p;
liberado = true;
encontrado = true;
}
}
}
//No tiene espaciso libres a los lados
else
{
//MessageBox.Show("Aqui entra");
Particion na = new Particion(actual.Size, actual.Height);
na.Ocupada = false;
na.Siguiente = actual.Siguiente;
na.Anterior = actual.Anterior;
if (actual.Siguiente != null || actual.Anterior != null)
{
if (actual.Anterior != null)
{
actual.Anterior.Siguiente = na;
}
else
{
Primera = na;
}
if (actual.Siguiente != null)
{
actual.Siguiente.Anterior = na;
}
else
{
Ultima = na;
}
}
liberado = true;
}
}
else
{
actual = actual.Siguiente;
}
}
//Agregar los del StandBy
if(encontrado)
{
bool bandera = false;
Particion pAux = null;
foreach(Particion p in StandBy)
{
actual = Primera;
while(actual != null)
{
if(!actual.Ocupada)
{
if(p.Size <= actual.Size && !bandera)
{
p.Siguiente = actual.Siguiente;
p.Anterior = actual.Anterior;
pAux = p;
bandera = true;
}
}
actual = actual.Siguiente;
}
if (pAux != null)
break;
}
//Verifica si uno de los del StandBy puede entrar
if(bandera)
{
nombresUsados.Remove(pAux.id);
AgregarParticion(pAux.Size, pAux.Ocupada, pAux.id);
StandBy.Remove(pAux);
}
}
return liberado;
}
public IEnumerator GetEnumerator()
{
if (modo == "particiones")
{
Particion actual = Ultima;
while (actual != null)
{
yield return actual;
actual = actual.Anterior;
}
}
else if (modo == "tareas")
{
Particion actual = Primera;
while (actual != null)
{
if (actual.Ocupada)
{
yield return actual;
}
actual = actual.Siguiente;
}
}
else if (modo == "libres")
{
Particion actual = Ultima;
while (actual != null)
{
if (!actual.Ocupada)
{
yield return actual;
}
actual = actual.Anterior;
}
}
}
/// <summary>
/// Agrega el sistema operativo
/// </summary>
/// <param name="_size">Tamaño dado en KB</param>
/// <returns></returns>
public bool AgregarSO(double _size)
{
if (_size <= (Size * .3))
{
double value = (_size * 100) / Size;
value = Dinamica.Nucleo.Truncate(value, 0);
double porcentaje = 0;
if (value.ToString().Length == 1)
{
porcentaje = double.Parse(".0" + value.ToString());
}
else
{
porcentaje = double.Parse("." + value.ToString());
}
double height = porcentaje * Height;
int heightInt = (int)height;
if (_size <= (Size * .3))
{
SO = new Particion(_size, heightInt);
SO.SO = true;
MemoriaDisponible -= SO.Size;
AgregarParticion(MemoriaDisponible, false, "Sistema operativo");
return true;
}
else
{
return false;
}
}
else
{
return false;
}
}
}
}
|
Java | UTF-8 | 639 | 2.171875 | 2 | [] | no_license | package ua.goit.offline.chat.security;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.User;
import java.util.Collection;
/**
* Created by andreymi on 2/7/2017.
*/
public class UserEntity extends User {
private ua.goit.offline.chat.entity.User user;
public UserEntity(String username, String password, Collection<? extends GrantedAuthority> authorities, ua.goit.offline.chat.entity.User user) {
super(username, password, authorities);
this.user = user;
}
public ua.goit.offline.chat.entity.User getUser() {
return user;
}
}
|
C++ | UTF-8 | 2,523 | 2.53125 | 3 | [] | no_license | ///************************************************************************
/// <copyrigth>Voice AI Technology Of ShenZhen</copyrigth>
/// <author>tangyingzhong</author>
/// <contact>yingzhong@voiceaitech.com</contact>
/// <version>v1.0.0</version>
/// <describe>
/// You can operate the sqlite by this class
///</describe>
/// <date>2019/8/6</date>
///***********************************************************************
#ifndef SQLITEDB_H
#define SQLITEDB_H
#include "Model/Fundation/IDatabase.h"
#include "sqlite3.h"
using namespace std;
class SqliteDB:public PluginBase<IDatabase>
{
public:
typedef sqlite3* SqliteDataBase;
typedef vector<vector<std::string> > RecordTable;
public:
// Construct the SqliteDB
SqliteDB();
// Detructe the SqliteDB
~SqliteDB();
private:
// Forbid the Copy
SqliteDB(const SqliteDB& other) { }
// Forbid the assigment of
SqliteDB& operator=(const SqliteDB& other) { return *this; }
public:
// Open the database
virtual Boolean Open(String strDbFilePath);
// Close the database
virtual None Close();
// Is opened or not
virtual Boolean IsOpen();
// Is existed table
virtual Boolean IsExistedTable(String strTableName);
// Excute the sql(serach sql)
virtual Boolean ExecuteNonQuery(String strSql, Int32& iRetCode);
// Excute the sql(serach sql)
virtual Boolean ExecuteNonQuery(String strSql, RecordTable& Table);
// Get the ErrorMessage
virtual String GetErrorMsg();
private:
// Initialize the sqlite
None Initialize();
// Destory the sqlite
None Destory();
// Excute the command
Boolean Excute(String strSql, Int32& iRetCode);
private:
// Get the DB
inline SqliteDataBase& GetDB()
{
return m_pDB;
}
// Set the DB
inline void SetDB(SqliteDataBase pDB)
{
m_pDB = pDB;
}
// Get the ErrorText
inline String GetErrorText() const
{
return m_strErrorText;
}
// Set the ErrorText
inline void SetErrorText(String strErrorText)
{
m_strErrorText = strErrorText;
}
// Get disposed status
inline Boolean GetDisposed() const
{
return this->m_Disposed;
}
// Set the disposed status
inline void SetDisposed(Boolean bDisposed)
{
this->m_Disposed = bDisposed;
}
// Get the IsOpen
inline Boolean GetIsOpen() const
{
return m_bIsOpen;
}
// Set the IsOpen
inline None SetIsOpen(Boolean bIsOpen)
{
m_bIsOpen = bIsOpen;
}
private:
// Sqlite db
SqliteDataBase m_pDB;
// Db is opened or not
Boolean m_bIsOpen;
// Error Message
String m_strErrorText;
// Disposed status
Boolean m_Disposed;
};
#endif //SQLITEDB_H |
PHP | UTF-8 | 1,189 | 2.59375 | 3 | [
"MIT"
] | permissive | <?php
namespace App\Ogniter\Model\Website;
use Illuminate\Database\Eloquent\Model;
use DB;
class Search extends Model {
protected $table = 'searches';
function register($text, $add=FALSE, $universe_id=0){
$text = trim($text);
if(empty($text)){
return;
}
$text = substr($text, 0, 80);
$universe_id = (int) $universe_id;
$filter = str_slug($text);
$r = DB::selectOne("SELECT id FROM searches WHERE universe_id=$universe_id AND slug=?", [$filter]);
$last_update = time();
if(!isset($r->id) ){
$sql = "INSERT INTO searches (universe_id, `text`, slug, repeated, last_update)
VALUES (?,?,?,1,?)";
DB::statement($sql, [$universe_id,$text,$filter, $last_update]);
} elseif($add){
DB::statement("UPDATE searches SET repeated=repeated+1,last_update=$last_update WHERE id=".$r->id);
}
}
function mostPopular($universe_id=0){
$universe_id = (int) $universe_id;
return DB::select(
"SELECT `text`, repeated FROM searches WHERE universe_id=".$universe_id." order BY repeated DESC LIMIT 10");
}
} |
JavaScript | UTF-8 | 1,473 | 2.515625 | 3 | [] | no_license | import {useState, useEffect} from 'react';
import {renameFileWithPrefix} from './../../helper';
const useStorage = (file, firebaseStorage, addAsset, currentUsername, assetCategory) => {
const [progress,
setProgress] = useState(0);
const [error,
setError] = useState(null);
const [url,
setUrl] = useState(null);
useEffect(() => {
// get a new filename
const newFileName = renameFileWithPrefix(file.name);
// references
const storageRef = firebaseStorage.ref(newFileName);
storageRef
.put(file)
.on('state_changed', snap => {
let precentage = (snap.bytesTransferred / snap.totalBytes) * 100;
setProgress(precentage);
}, err => {
setError(err);
}, async() => {
const url = await storageRef.getDownloadURL();
// upload file url to mongo database
const newAsset = {
name: newFileName,
url,
size: file.size,
file_type: file.type,
author_username: currentUsername,
category: assetCategory
};
addAsset(newAsset);
setUrl(url);
})
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [file])
return {progress, url, error};
}
export default useStorage; |
Python | UTF-8 | 449 | 3.90625 | 4 | [] | no_license | # Definition for singly-linked list.
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
def listToListNode(list):
head = ListNode(list[0])
p = head
for i in range(1, len(list)):
p.next = ListNode(list[i])
p = p.next
return head
def printListNode(ListNode):
p = ListNode
while p != None:
print(p.val, '->', end=' ')
p = p.next
print('NULL')
|
C++ | UTF-8 | 1,658 | 3.140625 | 3 | [] | no_license | #include <iostream>
using namespace std;
int main()
{
int aa,bb,hh=0;
int vv[50][50];
int gg[50][50];
int cc[50][50];
cout<<"Enter the number of rows";
cin >> aa;
cout<<"Enter the number of columns";
cin >> bb;
cout << endl;
cout <<"Enter the numbers:";
cout << endl;
for(int i=0;i<aa;i++)
{for(int j=0;j<bb;j++)
{cin >> cc[i][j];
if(cc[i][j]!=0)
{hh++;}}}
cout << endl;
cout <<"The matrix is:";
cout << endl;
for(int i=0;i<aa;i++)
{for(int j=0;j<bb;j++)
{cout << cc[i][j] <<"\t";} cout<<"\n";}
cout<<"\n";
cout << "Rows" << "\t" <<"Columns" <<"\t" <<"\t" <<"Non Zero";
cout<<"\n";
cout << aa << "\t" << bb << "\t" <<"\t" << hh ;
cout<< "\n";
for(int i=0;i<aa;i++)
{for(int j=0;j<bb;j++)
{if(cc[i][j]!=0)
{ gg[i][j]=cc[i][j];
cout<< i <<"\t"<< j <<"\t" <<"\t" << cc[i][j]<<endl;;}}}
cout << endl;
cout <<"The transpose of the matrix is:";
cout << endl;
for(int i=0;i<bb;i++)
{for(int j=0;j<aa;j++)
{cout << gg[j][i] <<"\t";
vv[i][j]=gg[j][i];} cout<<"\n";}
cout<<"\n";
cout << "Rows" << "\t" <<"Columns" <<"\t" <<"\t" <<"Non Zero";
cout<<"\n";
cout << aa << "\t" << bb << "\t" <<"\t" << hh ;
cout<< "\n";
for(int i=0;i<bb;i++)
{for(int j=0;j<aa;j++)
{if(vv[i][j]!=0)
{cout<< i <<"\t"<< j <<"\t" <<"\t" << vv[i][j]<<endl;;}}}
return 0;
}
|
Python | UTF-8 | 370 | 2.53125 | 3 | [] | no_license | import gspread_pandas
def push_to_docs(df, email, book_name, sheet_name):
print("Pushing to docs .... ")
spread = gspread_pandas.Spread(email, book_name, sheet_name)
spread_df = spread.sheet_to_df()
spread_df = spread_df.append(df)
spread.df_to_sheet(spread_df)
#tab = workbook.fetch_tab(sheet_name)
#tab.insert_data(df)
return None |
JavaScript | UTF-8 | 555 | 3.671875 | 4 | [] | no_license | function getBudgets(box) {
let sum = 0;
for (const key of box) {
sum += key.budget;
}
return sum;
}
let x = getBudgets([
{
name: "John",
age: 21,
budget: 23000,
},
{
name: "Steve",
age: 32,
budget: 40000,
},
{
name: "Martin",
age: 16,
budget: 2700,
},
]);
let y = getBudgets([
{
name: "John",
age: 21,
budget: 29000,
},
{
name: "Steve",
age: 32,
budget: 32000,
},
{
name: "Martin",
age: 16,
budget: 1600,
},
]);
console.log(x);
console.log(y);
|
JavaScript | UTF-8 | 3,001 | 2.578125 | 3 | [] | no_license | var http = require("http"),
fs = require('fs');
qs = require('querystring');
books = require('./public/books');
function serveStaticFile(res, path, contentType, responseCode) {
if(!responseCode) responseCode = 200;
fs.readFile(__dirname + path, function(err, data) {
if(err) {
res.writeHead(500, {'Content-Type': 'text/plain'});
res.end('Internal Server Error');
} else {
res.writeHead(responseCode, {'Content-Type': contentType});
res.end(data);
}
});
}
http.createServer(function(req, res) {
var url = req.url.split("?");
var params = qs.parse(url[1]);
/*console.log(params);*/
var path = url[0].toLowerCase();
switch(path) {
case '/':
serveStaticFile(res, '/public/home.html', 'text/html');
break;
case '/wind.png':
serveStaticFile(res, '/public/wind.png', 'image/png');
break;
case '/about':
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end('About page');
break;
case '/search':
console.log(books.get(params.title));
res.writeHead(200, {'Content-Type': 'text/plain'});
if (books.get(params.title) == undefined) {
res.end("Search for " + params.title + ": No records found");
} else {
res.end('Search for ' + params.title + ': ' + JSON.stringify(books.get(params.title)));
/*res.end('Search page');*/
}
break;
case '/delete':
console.log(books.counter() + " books left");
res.writeHead(200, {'Content-Type': 'text/plain'});
if (books.get(params.title) == undefined) {
res.end("Cannot delete " + params.title + ", file cannot be found")
} else {
books.cut(params.title);
res.end(params.title + " deleted. " + books.counter() + " books remaining.")
}
break;
case '/add':
res.writeHead(200, {'Content-Type': 'text/plain'});
if (params.title == undefined) {
res.end('Please enter a title to add');
} else {
books.add(params.title);
console.log(books.get(params.title));
res.end(params.title + ' was added to the booklist. List now contains ' + books.counter() + " books.");
}
break;
default:
res.writeHead(404, {'Content-Type': 'text/plain'});
res.end('Not found');
break;
/*
case '/about':
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end('About page');
break;
default:
res.writeHead(404, {'Content-Type': 'text/plain'});
res.end('Not found');
break;*/
}
}).listen(process.env.PORT || 3000); |
Markdown | UTF-8 | 1,800 | 2.640625 | 3 | [] | no_license | # GPFSWorld
[简体中文](README_CN.md)
GPFSWorld is developed based on the [fyne](https://github.com/fyne-io/fyne) framework. It is the GUI node of the GPFS network and an integral part of the GPFS ecosystem. Everyone can use it to share their files freely. It is not only a file management tool, it is also a resource search engine based on the P2P protocol.

## Function list
| Function | Statuts |
| -------------- | ---------- |
| File import | OK |
| File export | OK |
| Mining | OK |
| Resource search |TODO |
## Q&A
- Why can't I open the link from the browser after importing the file?
Answer: File synchronization takes time, and GFPS (IFPS) gateways are basically abroad. If you can’t open it for a long time, you can choose a suitable gateway here https://ipfs.github.io/public-gateway-checker/ and replace the gateway access in the default link.
For example, in the following, the same file can use different gateways, as long as the file CID is the same:
https://infura-ipfs.io/ipfs/QmVjgobGV2vL12Jv2d5KeJKVu1obVycEN8Sk1GLXPFMfLv?filename=gpfs.jpg
https://astyanax.io/ipfs/QmVjgobGV2vL12Jv2d5KeJKVu1obVycEN8Sk1GLXPFMfLv?filename=gpfs.jpg
https://dweb.link/ipfs/QmVjgobGV2vL12Jv2d5KeJKVu1obVycEN8Sk1GLXPFMfLv?filename=gpfs.jpg
- Can the software be closed when not in use?
Answer: Try not to close the file during sharing.
- Can others still access my files after the software is closed?
Answer: If your files have been synchronized to other nodes, others can still access them even if you shut down or delete the files. However, the GPFS network does not guarantee permanent storage of data, so in order to allow others to access your files continuously, please do not close the software.
|
TypeScript | UTF-8 | 1,304 | 2.890625 | 3 | [] | no_license | import { Command } from "discord-akairo";
import { Message, TextChannel, MessageEmbed } from "discord.js";
export default class Say extends Command {
public constructor() {
super("say", {
aliases: ["say", "echo"],
channel: "guild",
category: "Utilities",
userPermissions: ["MANAGE_CHANNELS"],
ratelimit: 2,
description: {
content: "Echos a certain phrase or word!",
usage: "say [string]",
examples: ["say Luca sucks!"],
},
args: [
{
id: "string",
type: "string",
match: "rest",
prompt: {
start: (msg: Message) =>
`${msg.author}, please provide a string...`,
retry: (msg: Message) =>
`${msg.author}, please provide a valid string...`,
},
},
],
});
}
public async exec(
message: Message,
{ string }: { string: string }
): Promise<Message> {
await message.delete();
const embed = new MessageEmbed().setColor(0x1abc9c);
if (string.length >= 1024) {
embed.setDescription(
"Phrase is over **1024** characters. Please try again."
);
return message.util.send(embed);
}
await message.channel.send(string, { disableMentions: "everyone" });
}
}
|
Python | UTF-8 | 3,647 | 2.890625 | 3 | [] | no_license | import json
from django.http import HttpResponse
from General_modules.module_DB import sqlExecute
from General_modules import global_settings
TABLENAME = global_settings.APA_TABLE_NAME
DB_NAME = global_settings.DB_NAME_EMEP_APA
db_user = global_settings.POSTGRESQL_USERNAME
db_password = global_settings.POSTGRESQL_PASSWORD
db_host = global_settings.POSTGRESQL_HOST
db_port = global_settings.POSTGRESQL_PORT
def get_ListGas(id_estacao):
"""
Return all the gas that the station has information
"""
table_gas_info = global_settings.GAS_INFORMATION_TABLE
sql = '''SELECT DISTINCT id_gas, "Nome" FROM "{0}" inner join "{1}" on id_gas = "ID_APA" WHERE id_estacao = {2}'''.format(TABLENAME, table_gas_info, id_estacao)
resp = sqlExecute(DB_NAME, db_user, db_password, db_host, db_port, sql, True)
listGas = []
if resp['success']:
for id_gas in resp['data']:
listGas.append({
'Name': id_gas[1],
'Id': id_gas[0]
})
return HttpResponse(content_type='text/json', content=json.dumps({
"listGas": listGas,
}))
def get_gasValues(id_estacao, id_gas, resolution, date):
"""
Return a html table that contains all the values for a specific station with a specific gas at a specific temporal resolution, using date as reference
"""
sql = sql_GasValues(id_estacao, id_gas, resolution, date)
html = ""
resp = sqlExecute(DB_NAME, db_user, db_password, db_host, db_port, sql, True)
if resp['success']:
html, data_array = makeHtmlTable(resp['data'])
return HttpResponse(content_type='text/json', content=json.dumps({
"htmlTable": html,
"data_array": data_array,
}))
def decompose_date(date):
"""
Retrieve year, month, day, hour, minute, second from the date
"""
split_date = date.split('-')
year = split_date[0]
month = split_date[1]
split_date = split_date[2].split('T')
day = split_date[0]
split_date = split_date[1].split(':')
hour = split_date[0]
minute = split_date[1]
second = split_date[2].split('.')[0]
return [year, month, day, hour, minute, second]
def sql_GasValues(id_estacao, id_gas, resolution, date):
"""
Create the sql sentence to get the values from the database.\n
This values corresponds to a specific station with a specific gas at a specific temporal resolution, using date as reference
"""
year, month, day, hour, minute, second = decompose_date(date)
sql = """SELECT date, value from "{}" where id_estacao = {} and id_gas = '{}'""".format(TABLENAME, id_estacao, id_gas)
_sql = " and EXTRACT(year from date) = {}".format(year)
if resolution != 'year':
_sql += " and EXTRACT(month from date) = {}".format(month)
if resolution != 'month':
_sql += " and EXTRACT(day from date) = {}".format(day)
if resolution != 'day':
_sql += " and EXTRACT(hour from date) = {}".format(hour)
return sql + _sql
def makeHtmlTable(data):
"""
To make the content more user friendly, transforms the data from the database to a html table
"""
if len(data) > 0:
data_array = []
html = """<table class="tableApa"><tr><td>Date</td><td>Value</td></tr>"""
for values in data:
html += "<tr><td>{}</td><td>{}</td></tr>".format(values[0], values[1])
data_array.append({
'date': values[0],
'value': values [1]
})
return [html + "</table>", data_array]
else:
return ["<h5>Empty Table</h5>", []] |
C++ | UTF-8 | 2,419 | 2.625 | 3 | [] | no_license | #include <FastLED.h>
// How many leds in your strip?
#define NUM_LEDS 150
// For led chips like Neopixels, which have a data line, ground, and power, you just
// need to define DATA_PIN. For led chipsets that are SPI based (four wires - data, clock,
// ground, and power), like the LPD8806, define both DATA_PIN and CLOCK_PIN
#define DATA_PIN 5
#define CLOCK_PIN 13
CRGB leds[NUM_LEDS];
int delayMs = 1000;
int loops = 0;
static uint8_t hue = 160;
static uint8_t hueIncrement = 20;
int iL, iLPrev = 9999, iLSkip = 1;
int brightness = 30;
char z;
void setup() {
Serial.begin(57600);
Serial.println("resetting");
LEDS.addLeds<WS2812, DATA_PIN, RGB>(leds, NUM_LEDS);
LEDS.setBrightness(brightness);
}
void Dim(int dimBy)
{
if (brightness > dimBy)
{
brightness -= dimBy;
LEDS.setBrightness(brightness);
}
}
void Brighten(int newBrightness)
{
brightness = newBrightness;
LEDS.setBrightness(brightness);
}
void ExecuteSkip()
{
if (iL + iLSkip < NUM_LEDS && iL + iLSkip > 0)
{
iL += iLSkip;
}
}
void ClearSerialBuffer()
{
while (Serial.available() > 0) z = Serial.read();
}
void CheckForInput()
{
z = '0';
if (Serial.available() > 0)
{
z = Serial.read();
}
}
void ProcessInput()
{
switch (z)
{
case '0':
if (loops > 0) loops--;
else
{
delayMs += 25;
Dim(10);
}
break;
case 'b':
ExecuteSkip(); //Skip ahead.
Brighten(180);
hue += hueIncrement;
delayMs = 5;
loops = 1;
break;
case 'm':
Brighten(240);
while (true) //Stop moving.
{
FastLED.show();
Dim(3);
if (Serial.available() > 0)z = Serial.read();
if (z == 'b')
{
ProcessInput();
return;
}
if (z == 'm')Brighten(180);
z = '0';
}
break;
default:
break;
}
ClearSerialBuffer();
}
void loop() {
iLPrev = 9999;
for (iL = 0; iL < NUM_LEDS; iL++ ) {
CheckForInput();
ProcessInput();
leds[iL] = CHSV(hue, 255, 255);
leds[iLPrev].fadeToBlackBy(255);
iLPrev = iL;
FastLED.show();
FastLED.delay(delayMs);
}
for (iL = (NUM_LEDS) - 1; iL >= 0; iL--) {
CheckForInput();
ProcessInput();
leds[iL] = CHSV(hue, 255, 255);
leds[iLPrev].fadeToBlackBy(255);
iLPrev = iL;
FastLED.show();
FastLED.delay(delayMs);
}
}
|
Java | UTF-8 | 1,569 | 2.265625 | 2 | [] | no_license | package net.polyv.live.service.impl;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import net.polyv.live.bean.client.WrappedResponse;
import net.polyv.live.bean.model.ChannelAccount;
import net.polyv.live.bean.request.account.PLChannelAccountsGetRequest;
import net.polyv.live.bean.result.PLCommonListResult;
import net.polyv.live.constant.PolyvLiveConstants;
import net.polyv.live.service.PLAbstractService;
import net.polyv.live.service.PLChannelAccountService;
/**
* <pre>
* 直播频道的子频道接口请求实现类
* </pre>
*
* @author HuangYF
*/
public class PLChannelAccountServiceImpl extends PLAbstractService implements PLChannelAccountService {
/**
* <pre>
* 获取频道下所有子频道
* </pre>
*
* @param channelId 频道号
* @param request 获取频道的子频道列表的参数对象。
* @return 子账号列表对象
*/
public PLCommonListResult<ChannelAccount> getAccounts(int channelId, PLChannelAccountsGetRequest request) {
String url = PolyvLiveConstants.getRealUrl(PolyvLiveConstants.CHANNEL_ACCOUNTS_GET_URL, channelId);
WrappedResponse response = request(url, request.getParams(), GET_METHOD);
PLCommonListResult<ChannelAccount> result = new PLCommonListResult<ChannelAccount>();
if (response.isRequestOk()) {
String json = JSON.toJSONString(response.getData());
result.setT(JSONObject.parseArray(json, ChannelAccount.class));
}
return getResult(response, result);
}
}
|
JavaScript | UTF-8 | 681 | 2.84375 | 3 | [
"MIT"
] | permissive | /* eslint no-underscore-dangle:0, no-restricted-syntax: 0 */
class BaseEntity {
/**
* @param {*} rawData
*/
constructor(rawData) {
this.$rawData = this.constructor.transform(rawData);
this._assign();
}
/**
* Transform raw data
* @param {*} data
*/
static transform(data) {
return data;
}
/**
* Assign as instance props
*/
_assign() {
Object.assign(this, this.$rawData);
}
/**
* JSON representation object
*/
toJSON() {
const keys = Object.keys(this.$rawData);
const result = {};
for (const key of keys) {
result[key] = this[key];
}
return result;
}
}
module.exports = BaseEntity;
|
Java | UTF-8 | 3,271 | 3.265625 | 3 | [] | no_license | public class DLL<T>{
private DLLNode<T> head, tail;
public String toString(){
DLLNode<T> p;
String s = "";
for(p = head; p != null; p = p.next)
s = s + p.info.toString() + " ";
return s;
}
public void addToHead(T el){
if(isEmpty()){
head = new DLLNode<T>(el,null,null);
tail = head;
}
else{
head = new DLLNode<T>(el,null,head);
head.next.prev = head;
}
}
public void addToTail(T el){
if(isEmpty()){
head = new DLLNode<T>(el,null,null);
tail = head;
}
else{
tail.next = new DLLNode<T>(el,tail,null);
tail = tail.next;
tail.prev.next = tail;
}
}
public T deleteFromHead(){
if(isEmpty())
return null;
T el = head.info;
if(head == tail)
head = tail = null;
else{
head = head.next;
head.prev = null;
}
return el;
}
public T deleteFromTail(){
if(isEmpty())
return null;
T el = tail.info;
if(head == tail)
head = tail = null;
else{
tail = tail.prev;
tail.next = null;
}
return el;
}
public boolean isEmpty(){
return (head == null);
}
public String toStringReverse(){
DLLNode<T> p;
String s = "";
for(p = tail; p != null; p = p.prev)
s = s + p.info.toString() + " ";
return s;
}
public void addBefore(T el, T add){
if(isEmpty()){
head = new DLLNode<T>(el,null,null);
tail = head;
}
else{
DLLNode<T> p;
for(p = head; p.next != null; p = p.next){
if(p.next.info.equals(el)){
p.next = new DLLNode<T>(add,p,p.next);
p.next.next.prev = p.next;
break;
}
}
}
}
public T delete(T el){
if(isEmpty())
return null;
if(el.equals(head.info)){
return deleteFromHead();
}
if(el.equals(tail.info)){
return deleteFromTail();
}
DLLNode<T> pred = head;
DLLNode<T> t = head.next;
while(t != null && !t.info.equals(el)){
pred = pred.next;
t = t.next;
}
if(t == null) return null;
else{
pred.next = t.next;
pred.next.prev = pred;
}
return el;
}
public void InsertSort(T el){
if(isEmpty()){
head = new DLLNode<T>(el,null,null);
tail = head;
}
else{
DLLNode<T> p;
for(p = head; p.next != null; p = p.next){
if(Integer.parseInt(el+"") < Integer.parseInt(p.next.info+"")){
p.next = new DLLNode<T>(el,p,p.next);
p.next.next.prev = p.next;
break;
}
}
}
}
}
|
Shell | UTF-8 | 235 | 2.859375 | 3 | [] | no_license | #!/bin/bash
echo -e "\e[1;31m math demo of 'let' \e[0m"
x=1999
let "x = $x + 1"
echo $x
let "x = $x + 100"
echo $x
let "x +=1"
echo $x
let "x -=1"
echo $x
let x-=1
echo $x
let x+=1
echo $x
let x=x+99
echo $x
x="olympic'"$x
echo $x |
Markdown | UTF-8 | 1,171 | 3.515625 | 4 | [] | no_license | ---
title: Slides of my talk SVG and React ( ReactJS Tokyo December 2017 )
layout: post
category : software
tags : [software,react,frontend,svg]
published: true
---
A few weeks ago I gave a talk in the ReactJS Tokyo meetup. When I arrived to Japan a few months ago one of my goals was to contribute in some way to the local JavaScript community, so I searched for conferences and meetups and found ReactJS Tokyo. After contacting the organizers and meeting with one of them, things were arranged and I was one of the speakers.
The topic I chose was SVG and React. There's different approaches to loading and manipulating SVG within React, so my goal was to present a series of tools and techniques to use depending on the use case. I've been working a lot with SVG and React and to solve some of the challenges presented, I maintain a tool called react-samy-svg that makes it easy to load and manipulate external SVG files. [Github repository](https://github.com/hugozap/react-samy-svg)
After the presentations ended, I had the opportunity to meet some cool people. The feedback I received was positive.
[Check the slides here](http://slides.com/hugozapata/deck)
|
Java | UTF-8 | 1,446 | 2.703125 | 3 | [
"MIT"
] | permissive | package io.github.eetchyza.springauth;
import java.time.LocalDateTime;
import java.util.Collection;
import io.github.eetchyza.springauth.api.GrantedAuthority;
/**
* Holds authentication details
*
* @author Dan Williams
* @version 1.0.0
* @since 2019-04-06
*/
public class Authentication {
private String authenticationToken;
private String refreshToken;
private LocalDateTime expire;
private Collection<? extends GrantedAuthority> roles;
private String username;
private long id;
Authentication(String authenticationToken, String refreshToken, LocalDateTime expire, Collection<? extends GrantedAuthority> roles, String username, long id) {
this.authenticationToken = authenticationToken;
this.refreshToken = refreshToken;
this.expire = expire;
this.roles = roles;
this.username = username;
this.id = id;
}
boolean isRefreshToken(String refreshToken) {
return refreshToken.equals(this.refreshToken);
}
Collection<? extends GrantedAuthority> getRoles() {
return roles;
}
String getAuthenticationToken() {
return authenticationToken;
}
boolean isExpired() {
return expire.isBefore(LocalDateTime.now());
}
boolean hasRoles(String[] values) {
for (GrantedAuthority authority : roles) {
for (String value : values) {
if (value.equals(authority.getAuthority())) {
return true;
}
}
}
return false;
}
@Override
public String toString() {
return authenticationToken;
}
}
|
C# | UTF-8 | 1,251 | 2.59375 | 3 | [] | no_license | using UnityEngine;
public class Bullet : MonoBehaviour {
private Transform target;
public float speed = 70f;
public GameObject bulletExplosionEffect;
private float damage;
public void Seek(Transform _target, float dmg)
{
target = _target;
damage = dmg;
}
// Update is called once per frame
void Update () {
if (target == null)
{
Destroy(gameObject);
return;
}
Vector3 direction = target.position - transform.position;
float distanceThisFrame = speed * Time.deltaTime;
//Hit the target if this is true
if (direction.magnitude <= distanceThisFrame)
{
MobInteraction mb = target.GetComponent<MobInteraction>();
Debug.Log(damage);
mb.TakeDamage(damage);
HitTarget();
return;
}
//Haven't hit target yet, so move towards it
transform.Translate(direction.normalized * distanceThisFrame, Space.World);
}
void HitTarget()
{
GameObject bulletExplosion = (GameObject) Instantiate(bulletExplosionEffect, transform.position, transform.rotation);
Destroy(bulletExplosion, 2f);
Destroy(gameObject);
}
}
|
TypeScript | UTF-8 | 251 | 2.828125 | 3 | [] | no_license | export class Usuario{
public nome: string;
public endereco: string;
public telefone: string;
constructor(nome: string, endereco:string, telefone:string){
this.nome = nome;
this.endereco = endereco;
this.telefone = telefone;
}
} |
Python | UTF-8 | 1,619 | 4.09375 | 4 | [] | no_license | def get_length(dna):
""" (str) -> int
Return the length of the DNA sequence dna.
>>> get_length('ATCGAT')
6
>>> get_length('ATCG')
4
"""
return len(dna)
def is_longer(dna1, dna2):
""" (str, str) -> bool
Return True if and only if DNA sequence dna1 is longer than DNA sequence
dna2.
>>> is_longer('ATCG', 'AT')
True
>>> is_longer('ATCG', 'ATCGGA')
False
"""
len1 = len(dna1)
len2 = len(dna2)
return len1 > len2
def count_nucleotides(dna, nucleotide):
""" (str, str) -> int
Return the number of occurrences of nucleotide in the DNA sequence dna.
>>> count_nucleotides('ATCGGC', 'G')
2
>>> count_nucleotides('ATCTA', 'G')
0
"""
return dna.count(nucleotide)
def contains_sequence(dna1, dna2):
""" (str, str) -> bool
Return True if and only if DNA sequence dna2 occurs in the DNA sequence
dna1.
>>> contains_sequence('ATCGGC', 'GG')
True
>>> contains_sequence('ATCGGC', 'GT')
False
"""
return dna2 in dna1
def is_valid_sequence(dna):
lst= ('A', 'T', 'C', 'G')
for m in range (0,len(dna)):
if dna[m] not in lst:
return False
return True
def insert_sequence(a,b,n):
lsta=list(a)
lsta.insert(n-1,b)
return ''.join(lsta)
def get_complement(nucleotide):
pair= {'T':'A','A':'T','C':'G','G':'C'}
return pair.get(nucleotide)
def get_complementary_sequence(dna):
pair= {'T':'A','A':'T','C':'G','G':'C'}
dna=list(dna)
lst=[]
for n in dna:
lst.append(pair.get(n))
return ''.join(lst)
|
Java | UTF-8 | 557 | 1.578125 | 2 | [] | no_license | package com.tyh.bankcrawper;
import com.tyh.bankcrawper.client.OrderClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableScheduling;
import java.util.List;
import java.util.Map;
@SpringBootApplication
public class BankcrawperApplication {
public static void main(String[] args) {
SpringApplication.run(BankcrawperApplication.class, args);
}
}
|
C++ | UTF-8 | 7,061 | 3.0625 | 3 | [] | no_license | #include <components/program.h>
#include "print_visitor.h"
PrintVisitor::PrintVisitor(const std::string& filename) :
stream_(filename)
{}
void PrintVisitor::Visit(Program* program) {
stream_ << "Program:" << std::endl;
auto addTab = AddTab(this);
program->main_->Accept(this);
for (const auto& classObj : program->classes_) {
classObj->Accept(this);
}
}
void PrintVisitor::Visit(MainClass* mainClass) {
PrintTabs_();
stream_ << "Main class <" << mainClass->id_ << ">:" << std::endl;
auto addTab = AddTab(this);
for (const auto& statement : mainClass->statements_) {
statement->Accept(this);
}
}
void PrintVisitor::Visit(Class* classObj) {
PrintTabs_();
stream_ << "Class <" << classObj->id_ << ">:" << std::endl;
auto addTab = AddTab(this);
if (!classObj->extension_.empty()) {
PrintTabs_();
stream_ << "Extension <" << classObj->extension_ << ">:" << std::endl;
}
for (const auto& declaration : classObj->declarations_) {
declaration->Accept(this);
}
}
void PrintVisitor::Visit(Formal* formal) {
PrintTabs_();
stream_ << formal->type_ << " " << formal->id_ << std::endl;
}
void PrintVisitor::Visit(MethodInvocation* methodInvocation) {
PrintTabs_();
stream_ << "Method invocation <" << methodInvocation->id_ << ">:" << std::endl;
auto addTab = AddTab(this);
}
void PrintVisitor::Visit(VariableDeclaration* variableDeclaration) {
PrintTabs_();
stream_ << "Variable declaration <" << variableDeclaration->type_ << " "
<< variableDeclaration->id_ << ">:" << std::endl;
}
void PrintVisitor::Visit(MethodDeclaration* methodDeclaration) {
PrintTabs_();
stream_ << "Method declaration <" << methodDeclaration->type_ << " "
<< methodDeclaration->id_ << ">:" << std::endl;;
{
PrintTabs_();
stream_ << "Method formals:" << std::endl;
auto addTab = AddTab(this);
for (const auto &formal : methodDeclaration->formals_) {
formal->Accept(this);
}
}
{
PrintTabs_();
stream_ << "Method statements:" << std::endl;
auto addTab = AddTab(this);
for (const auto &statement : methodDeclaration->statements_) {
statement->Accept(this);
}
}
}
void PrintVisitor::Visit(ArrayMakeExpression* arrayMakeExpression) {
PrintTabs_();
stream_ << "Array make expression <" << arrayMakeExpression->simpleType_ << ">:" << std::endl;
auto addTab = AddTab(this);
arrayMakeExpression->sizeExpr_->Accept(this);
}
void PrintVisitor::Visit(BinaryExpression* binaryExpression) {
PrintTabs_();
stream_ << "Binary expression <" << binaryExpression->binaryOperator_ << ">:" << std::endl;
auto addTab = AddTab(this);
binaryExpression->leftExpr_->Accept(this);
binaryExpression->rightExpr_->Accept(this);
}
void PrintVisitor::Visit(InverseExpression* inverseExpression) {
PrintTabs_();
stream_ << "Inverse expression:" << std::endl;
auto addTab = AddTab(this);
inverseExpression->expr_->Accept(this);
}
void PrintVisitor::Visit(MethodInvocationExpression* methodInvocationExpression) {
PrintTabs_();
stream_ << "Method invocation expression:" << std::endl;
auto addTab = AddTab(this);
methodInvocationExpression->methodInvocation_->Accept(this);
}
void PrintVisitor::Visit(ObjectMakeExpression* objectMakeExpression) {
PrintTabs_();
stream_ << "Object make expression<" << objectMakeExpression->typeIdentifier_ << ">:" << std::endl;
}
void PrintVisitor::Visit(SimpleExpression* simpleExpression) {
PrintTabs_();
stream_ << "Simple expression<" << simpleExpression->value_ << ">:" << std::endl;
}
void PrintVisitor::Visit(NumberExpression *expression) {
PrintTabs_();
stream_ << "Number expression<" << expression->value_ << ">:" << std::endl;
}
void PrintVisitor::Visit(LengthExpression* lengthExpression) {
PrintTabs_();
stream_ << "Length expression:" << std::endl;
auto addTab = AddTab(this);
lengthExpression->expr_->Accept(this);
}
void PrintVisitor::Visit(AssertStatement* statement) {
PrintTabs_();
stream_ << "Assert statement:" << std::endl;
auto addTab = AddTab(this);
statement->expr_->Accept(this);
}
void PrintVisitor::Visit(IfElseStatement* statement) {
PrintTabs_();
stream_ << "If expression:" << std::endl;
{
auto addTab = AddTab(this);
statement->expr_->Accept(this);
}
PrintTabs_();
stream_ << "If statement:" << std::endl;
{
auto addTab = AddTab(this);
statement->if_statement_->Accept(this);
}
PrintTabs_();
stream_ << "Else statement:" << std::endl;
{
auto addTab = AddTab(this);
statement->else_statement_->Accept(this);
}
}
void PrintVisitor::Visit(IfStatement* statement) {
PrintTabs_();
stream_ << "If expression:" << std::endl;
{
auto addTab = AddTab(this);
statement->expr_->Accept(this);
}
PrintTabs_();
stream_ << "If statement:" << std::endl;
{
auto addTab = AddTab(this);
statement->statement_->Accept(this);
}
}
void PrintVisitor::Visit(LocalVariableDeclarationStatement* statement) {
PrintTabs_();
stream_ << "Local variable declaration statement:" << std::endl;
auto addTab = AddTab(this);
statement->variableDeclaration_->Accept(this);
}
void PrintVisitor::Visit(MethodInvocationStatement* statement) {
PrintTabs_();
stream_ << "Method invocation statement:" << std::endl;
auto addTab = AddTab(this);
statement->methodInvocation_->Accept(this);
}
void PrintVisitor::Visit(PrintlnStatement* statement) {
PrintTabs_();
stream_ << "Println statement:" << std::endl;
auto addTab = AddTab(this);
statement->expr_->Accept(this);
}
void PrintVisitor::Visit(ReturnStatement* statement) {
PrintTabs_();
stream_ << "Return statement:" << std::endl;
auto addTab = AddTab(this);
statement->expr_->Accept(this);
}
void PrintVisitor::Visit(ScopeStatements* statement) {
PrintTabs_();
stream_ << "Scope statements:" << std::endl;
auto addTab = AddTab(this);
for (const auto& subStatement : statement->statements_) {
subStatement->Accept(this);
}
}
void PrintVisitor::Visit(SetLvalueStatement* statement) {
PrintTabs_();
stream_ << "Set lvalue statement<" << statement->lvalue_ << ">:" << std::endl;
auto addTab = AddTab(this);
statement->expr_->Accept(this);
}
void PrintVisitor::Visit(WhileStatement* statement) {
PrintTabs_();
stream_ << "While expression:" << std::endl;
{
auto addTab = AddTab(this);
statement->expr_->Accept(this);
}
PrintTabs_();
stream_ << "While statement:" << std::endl;
{
auto addTab = AddTab(this);
statement->statement_->Accept(this);
}
}
void PrintVisitor::PrintTabs_() {
for (size_t i = 0; i < num_tabs_; ++i) {
stream_ << '\t';
}
} |
Python | UTF-8 | 460 | 3.0625 | 3 | [] | no_license | import re
import requests
from bs4 import BeautifulSoup
url = 'https://www.nytimes.com/'
source_code = requests.get(url)
plain_text = source_code.text
soup = BeautifulSoup(plain_text)
string1 = ["sports","trump","tech"]
for i in range(len(string1)):
count = 0
for link in soup.findAll('a',href=re.compile(string1[i])):
if count < 5:
count = count + 1
# print(count)
x = link.get('href')
print(x)
|
Python | UTF-8 | 1,800 | 3.34375 | 3 | [] | no_license | from typing import List
import queue
import collections
def top(i, j, m, n):
'''
:param i:
:param j:
:param m: 行
:param n: 列
:return:
'''
if i == 0 and 0 <= j < n:
return True
def bottom(i, j, m, n):
'''
:param i:
:param j:
:param m: 行
:param n: 列
:return:
'''
if i == (n - 1) and 0 <= j < n:
return True
def left(i, j, m, n):
'''
:param i:
:param j:
:param m: 行
:param n: 列
:return:
'''
if 0 < i < m and j == 0:
return True
def right(i, j, m, n):
'''
:param i:
:param j:
:param m: 行
:param n: 列
:return:
'''
if 0 < i < m and j == (n - 1):
return True
class Solution:
def solve(self, board: List[List[str]]) -> None:
"""
Do not return anything, modify board in-place instead.
"""
m, n = len(board), len(board[0])
def dfs(x, y):
if (not 0 <= x < m) or (not 0 <= y < n):
return
if board[x][y] != 'O':
return
board[x][y] = 'A'
dfs(x + 1, y)
dfs(x - 1, y)
dfs(x, y - 1)
dfs(x, y + 1)
for i in range(m):
dfs(i, 0)
dfs(i, n - 1)
for j in range(n):
dfs(0, j)
dfs(m - 1, j)
for i in range(m):
for j in range(n):
e = board[i][j]
if board[i][j] == 'A':
board[i][j] = 'O'
elif board[i][j] == 'O':
board[i][j] = 'X'
if __name__ == '__main__':
b = [["X","X","X","X"],["X","O","O","X"],["X","X","O","X"],["X","O","X","X"]]
print(b[1][2])
Solution().solve(b)
print(b)
|
C++ | UTF-8 | 781 | 3.375 | 3 | [] | no_license | https://practice.geeksforgeeks.org/problems/zigzag-tree-traversal/1
void zigZagTraversal(Node* root)
{
if (root == NULL) return ;
stack <Node *> s1;
stack <Node *> s2;
s1.push(root);
while(s1.empty() == false || s2.empty() == false){
while(s1.empty() == false){
Node * root_s1 = s1.top();
s1.pop();
cout << root_s1->data<< " ";
if(root_s1->left) s2.push(root_s1->left);
if(root_s1->right) s2.push(root_s1->right); }
while(s2.empty() == false){
Node * root_s2 = s2.top();
s2.pop();
cout << root_s2->data<< " ";
if(root_s2->right) s1.push(root_s2->right);
if(root_s2->left) s1.push(root_s2->left); }
}
}
|
C++ | UTF-8 | 644 | 3.71875 | 4 | [] | no_license | // C++11 thread basics
/*
C++11 threas VS pthreads:
1. pthreads is a C lib, not supporting some of the C++ features like exception and object lifetimes.
2. C++11 threads is in a RAII(Resource Allocation Is Initialization) manner.
3. some of the pthreads functionalities not supported in C++11 and vise versa.
*/
#include <thread>
#include <cstdio>
void func(int a) {
printf("this is %d\n", std::this_thread::get_id());
}
void func2(int a, int b) {
printf("result of %d is : %d\n", std::this_thread::get_id(), a + b);
}
int main() {
std::thread t1(func2, 1, 2);
std::thread t2(func2, -1, -2);
t1.join();
t2.join();
return 0;
} |
Python | UTF-8 | 576 | 4.3125 | 4 | [] | no_license | # Write a Python program to find the smallest multiple of the first n numbers.
# Also, display the factors.
# Test Data:
# If n = (13)
# Expected Output :
# [13, 12, 11, 10, 9, 8, 7]
# 360360
def smallest_multiple(n):
i = n * 2
factors = [number for number in range(n, 1, -1) if number * 2 > n]
print(factors)
while True:
for a in factors:
if i % a != 0:
i += n
break
if (a == factors[-1] and i % a == 0):
return i
print(smallest_multiple(13))
print(smallest_multiple(11))
|
Markdown | UTF-8 | 3,160 | 2.734375 | 3 | [] | no_license | ---
layout: post
status: publish
published: true
title: "소통에 어려움을 겪는 이유"
author:
display_name: Kay
login: Kay
email: iam@hannal.net
url: ''
author_login: Kay
author_email: iam@hannal.net
wordpress_id: 1041
wordpress_url: http://blog.hannal.com/communication_skill_01_for_who_for_what/
date: '2007-07-17 00:58:37 +0900'
date_gmt: '2007-07-16 15:58:37 +0900'
categories:
- "essay"
tags:
- "소통"
permalink: "/2007/7/communication_skill_01_for_who_for_what/"
---
<p>가정을 하나 먼저 내리는 것으로 이야기를 시작하자.</p>
<p>여기 실존하지 않지만 이 이야기 속에는 존재하는 여성, 즉 가상인 여자 갑순이가 있다. 남자인 나는 이 여자와 컴퓨터 메신저로 평소에 많은 얘기를 나눈다. 얘기를 나누느라 둘 다 할 일에 지장을 받기 일쑤.</p>
<p>그러던 어느 날, 둘은 실제로 만나 차 한 잔 마시며 얘기를 나눴다. 그때 나는 갑순이에게 이런 말을 한다.</p>
<p>“나 실은 메신저 되게 싫어해. 그래서 사무실에선 할 말 있으면 직접 가서 말을 하고, 메신저는 파일 주고 받을 때나 써”</p>
<p>갑순이 얼굴을 쳐다보니 혼란에 빠져 있다.</p>
<p>1. 나 메신저 되게 싫어한다. 하지만, 당신이기에 메신저를 켜고 얘기를 나누는 것이다.<br />
2. 나 메신저 되게 싫어하다. 그러니 이제 그만 당신과 얘기하고 싶다.<br />
3. 나 메신저 되게 싫어한다. 이젠 메신저로 얘기 나누지 말고 이렇게 직접 당신을 만나 얘기하고 싶다.</p>
<p>대체 무슨 말이지? 뭐지? 뭘까???</p>
<p>그렇다면 난 무슨 생각으로 저런 말을 한 것일까. 난 단지</p>
<p>“나 메신저 되게 싫어해. 그래도 메신저는 파일 주고 받을 때는 편해서 쓰긴 써”</p>
<p>라고 말을 하고픈 것일지 모른다.</p>
<p>왜 나와 갑순이는 소통에 이런 틈을 겪는걸까? 나는 싫은 이유를 말하지 않았고, 갑순이는 얘기 대상을 “자신”에게 맞췄기 때문이다. 내가 원래 하려던 말은 “쓰임새”에 초점을 맞췄지 누군가를 대상으로 하지 않았고, 갑순이는 쓰임새를 “누군가”라는 대상에(정확히는 자기 자신) 맞췄다.</p>
<p>살짝 한 발자국 떨어져 상황을 보면 참 어리석게 보이지만, 주위를 조금만 둘러보면, 혹은 자기 자신을 조금만 뒤돌아보면 저렇게 개떡 같이 말하는 모습이나 엉뚱하게 받아들이고 혼란에 빠지는 모습을 볼 수 있다. 자신의 머리 속에선 이미 그 말에 대한 충분한 생각이 들어있고(그렇지 않은 경우도 많아서 생각없이 말을 하는 사람도 많다), 그래서 이리 저리 말을 잘라내어 줄여서 내 보낸 말이 저런 개떡 같은 말이다. 물론, 원래 말하려던 내용 대부분은 들어가있다. 하지만, 정리가 되질 않아 무엇에 초점을 맞춘 말인지 알 수 없어 갑순이는 저런 혼란 속에서 아직도 헤어나오지 못하는 것이다.</p>
<p>이것이 소통에 어려움을 겪는 이유 중 하나이다.</p>
|
C# | UTF-8 | 4,681 | 2.515625 | 3 | [] | no_license | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using application.Strategy;
using commonTypes;
using commonClass;
namespace Strategy
{
public class HybridKeltner_Helper : baseHelper
{
public HybridKeltner_Helper()
: base(typeof(HybridKeltnerEMA))
{
}
}
public class BollingerKeltnerEMARule : Rule
{
Indicators.BBANDS bolliger;
Indicators.KELTNER keltner;
TwoEMARule emaRule;
public BollingerKeltnerEMARule(DataBars db,double BolligerPeriod,double kUp,double kDn,double EmaPeriod,double AtrMult,double AtrPeriod,double emaShortPeriod,double emaLongPeriod)
{
bolliger=Indicators.BBANDS.Series(db.Close,BolligerPeriod,kUp,kDn,"bolliger");
keltner=Indicators.KELTNER.Series(db,EmaPeriod,AtrMult,AtrPeriod,"keltner");
emaRule = new TwoEMARule(db.Close, emaShortPeriod, emaLongPeriod);
}
public override bool DownTrend(int index)
{
if (index < emaRule.long_indicator.FirstValidValue)
return false;
if (emaRule.DownTrend(index))
return true;
return false;
}
public override bool UpTrend(int index)
{
if (index < emaRule.long_indicator.FirstValidValue)
return false;
return (emaRule.UpTrend(index));
}
public bool isBolligerInsideKeltner(int index)
{
if (index < Math.Max(bolliger.UpperSeries.FirstValidValue,keltner.UpperSeries.FirstValidValue))
return false;
if ((bolliger.UpperSeries[index]<keltner.UpperSeries[index])
&&(bolliger.LowerSeries[index]>keltner.LowerSeries[index]))
return true;
return false;
}
public override bool isValid_forBuy(int index)
{
if (isBolligerInsideKeltner(index-1)&&(!isBolligerInsideKeltner(index))&&emaRule.UpTrend(index))
return true;
return false;
}
public override bool isValid_forSell(int index)
{
//if ((isBolligerInsideKeltner(index)&&(!isBolligerInsideKeltner(index-1)))
// ||(emaRule.isValid_forSell(index)))
if (isBolligerInsideKeltner(index - 1) && (!isBolligerInsideKeltner(index)) && emaRule.DownTrend(index))
return true;
return false;
}
}
public class HybridKeltnerEMA : GenericStrategy
{
override protected void StrategyExecute()
{
BollingerKeltnerEMARule rule = new BollingerKeltnerEMARule(data.Bars, parameters[0], parameters[1], parameters[2], parameters[3],parameters[4],parameters[5],parameters[6],parameters[7]);
int cutlosslevel = (int)parameters[8];
int trailingstoplevel = (int)parameters[9];
int takeprofitlevel = (int)parameters[10];
Indicators.MIN min = Indicators.MIN.Series(data.Close, parameters[7], "min");
Indicators.MAX max = Indicators.MAX.Series(data.Close, parameters[7], "max");
for (int idx = 0; idx < data.Close.Count; idx++)
{
if (rule.isValid_forBuy(idx))
{
BusinessInfo info = new BusinessInfo();
info.SetTrend(AppTypes.MarketTrend.Upward, AppTypes.MarketTrend.Unspecified, AppTypes.MarketTrend.Unspecified);
info.Short_Target = max[idx];
info.Stop_Loss = min[idx];
BuyAtClose(idx, info);
}
else
if (rule.isValid_forSell(idx))
{
BusinessInfo info = new BusinessInfo();
info.SetTrend(AppTypes.MarketTrend.Downward, AppTypes.MarketTrend.Unspecified, AppTypes.MarketTrend.Unspecified);
info.Short_Target = min[idx];
info.Stop_Loss = max[idx];
SellAtClose(idx, info);
}
if (is_bought && CutLossCondition(data.Close[idx], buy_price, cutlosslevel))
SellCutLoss(idx);
if (is_bought && TakeProfitCondition(data.Close[idx], buy_price, takeprofitlevel))
SellTakeProfit(idx);
if (trailingstoplevel > 0)
TrailingStopWithBuyBack(rule, data.Close[idx], trailingstoplevel, idx);
}
}
}
}
|
Markdown | UTF-8 | 5,877 | 2.796875 | 3 | [] | no_license | # EXMiniHoga
> **Extends**: [`AGrid`](./../afc/AGrid.md)
호가와 거래량을 2열로 표시하는 호가그리드. 형태는 아래와 같다.
1열 | 2열
:--- | ---:
매수호가N | 거래량
... | ...
매수호가1 | 거래량
매도호가1 | 거래량
... | ... | ...
매도호가N | 거래량
<br/>
## Properties
### frwName
* `Default` "stock"
<br/>
### quoteCount \<Number>
호가 단계(5호가, 10호가)
<br/>
### rowLen \<Number>
호가가 적용된 로우의 개수
<br/>
### colLen \<Number>
호가를 표현할 컬럼의 개수
<br/>
### btmRowCnt \<Number>
하단 데이터 영역의 로우 개수
<br/>
### basePrice \<Number>
호가의 색상을 구분하기 위한 기준가
<br/>
### basePriceKey \<String>
수신데이터에서 기준가를 가져오기 위한 키값
<br/>
### curPriceKey \<String>
수신데이터에서 현재가를 가져오기 위한 키값
<br/>
### currentCell \<jQuery Object>
jQuery 현재가셀을 저장하는 변수
<br/>
### currentPrice \<Number>
현재가
<br/>
### curPriceStyleArr \<Array>
현재가를 선택하는 스타일 배열[상승색, 보합색, 하락색]
<br/>
### upColor \<String>
기본 상승색(기본값 StockColor.UP_COLOR)
<br/>
### downColor \<String>
기본 하락색(기본값 DOWN_COLOR.UP_COLOR)
<br/>
### steadyColor \<String>
기본 보합색(기본값 STEADY_COLOR.UP_COLOR)
<br/>
### barSize \<String>
매도, 매수 잔량을 표시하는 바 높이(기본값 70%)
<br/>
### valArr \<Array>
호가그리드의 데이터 값들을 저장하고 있는 2차원 배열. 그리드 형태와 동일
<br/>
<br/>
## Method
### init()
<br/>
### clearContents()
<br/>
### resetGrid()
<br/>
### setBasePrice( basePrice )
기준가를 설정한다.
* `basePrice` \<Number>
<br/>
### setBasePriceKey( basePriceKey )
수신데이터에서 기준가를 뽑아올 키값을 설정한다.
* `basePriceKey` \<String>
<br/>
### setCurrentPrice( currentPrice )
현재가를 설정한다.
* `currentPrice` \<Number>
<br/>
### setCurPriceKey( keyName )
수신데이터에서 현재가를 뽑아올 키값을 설정한다.
* `keyName` \<String>
<br/>
### setUpColor( color )
호가 상승색을 설정한다.
* `color` \<String> #ff0000
<br/>
### setDownColor( color )
호가 하락색을 설정한다.
* `color` \<String> #0000ff
<br/>
### setSteadyColor( color )
호가 보합색을 설정한다.
* `color` \<String> #000000
<br/>
### getUpColor()
호가 상승색을 리턴한다.
* **Returns** \<String> #ff0000
<br/>
### getDownColor()
호가 하락색을 리턴한다.
* **Returns** \<String> #0000ff
<br/>
### getSteadyColor()
호가 보합색을 리턴한다.
* **Returns** \<String> #000000
<br/>
### selectCurrentCell( mapCell )
파라미터로 전달받은 셀을 현재가의 상승, 하락, 보합에 따라 셀에 클래스를 지정해준다.</br>
(호가가 현재가와 일치한 셀)
* `mapCell` \<HTMLTableCellElement> 호가와 현재가가 일치하는 셀 엘리먼트
<br/>
<!-- ### calcCtrtRate() -->
<!-- <br/> -->
### setCurrentPriceStyleArr( styleArr )
현재가에 해당하는 셀에 추가할 상승, 하락, 보합의 클래스 목록을 지정한다.
* `styleArr` \<Array> [상승클래스, 하락클래스, 보합클래스]
<br/>
### initBar()
호가 잔량을 표현하는 바를 초기화한다.
<br/>
### setBarSize( barSize )
호가 잔량을 표현하는 바의 높이를 지정한다.
* `barSize` \<String> 바 높이
<br/>
### getBarSize()
호가 잔량을 표현하는 바의 높이를 리턴한다.
* **Returns** \<String> 바 높이
<br/>
### setAskBarBgImg( bgImage )
매도 잔량바의 Background-image를 지정한다.
* `bgImage` \<String>
<br/>
### getAskBarBgImg()
매도 잔량바의 Background-image를 리턴한다.
* **Returns** \<String>
<br/>
### setBidBarBgImg( bgImage )
매수 잔량바의 Background-image를 지정한다.
* `bgImage` \<String>
<br/>
### getBidBarBgImg()
매수 잔량바의 Background-image를 리턴한다.
* **Returns** \<String>
<br/>
###
### setAskBarPositionX( pos )
매도 잔량바의 시작 위치 x 값을 지정한다.
* `pos` \<String> background-position-x
<br/>
### getAskBarPositionX()
매도 잔량바의 시작 위치 x 값을 리턴한다.
* **Returns** \<String> background-position-x
<br/>
### setAskBarPositionY( pos )
매도 잔량바의 시작 위치 y 값을 지정한다.
* `pos` \<String> background-position-y
<br/>
### getAskBarPositionY()
매도 잔량바의 시작 위치 y 값을 리턴한다.
* **Returns** \<String> background-position-y
<br/>
### setBidBarPositionX( pos )
매수 잔량바의 시작 위치 x 값을 지정한다.
* `pos` \<String> background-position-x
<br/>
### getAskBarPositionX()
매수 잔량바의 시작 위치 x 값을 리턴한다.
* **Returns** \<String> background-position-x
<br/>
### setAskBarPositionY( pos )
매수 잔량바의 시작 위치 y 값을 지정한다.
* `pos` \<String> background-position-y
<br/>
### getAskBarPositionY()
매수 잔량바의 시작 위치 y 값을 리턴한다.
* **Returns** \<String> background-position-y
<br/>
### setBottomRowCount( btmRowCnt )
호가를 하단에 표현될 로우의 개수를 지정한다.
* `btmRowCnt` \<Number>
<br/>
### getBottomRowCount()
호가를 하단에 표현된 로우의 개수를 리턴한다.
* **Returns** \<Number>
<br/>
### setQuoteCount( cnt )
호가의 단계를 지정한다. 5호가, 10호가 등
* `cnt` \<Number>
<br/>
### getQuoteCount()
호가의 단계를 리턴한다. 5호가, 10호가 등
* **Returns** \<Number>
<br/>
### setDelegator( delegator )
델리게이터를 지정한다. quoteCount, bottomRowCount가 변경될 때 델리게이터의 change 이벤트를 호출한다.
* `delegator` \<Object>
<br/> |
Shell | UTF-8 | 872 | 3.3125 | 3 | [] | no_license | #!/bin/sh
#cd /home/dsandler/dsandler.org/tools/shirtdb/preview
SITEDIR=/home/dsandler/web/shirts
cd $SITEDIR/preview
if [ "$1" = "" ]; then
wget --recursive --level=1 --accept=jpg --no-parent http://keepernotes.com/shirts/
cd keepernotes.com/shirts
# fixup
test -f 2010.wiess-front.jpg \
&& mv 2010.wiess-front.jpg 2010-wiess-front.jpg
test -f 1998-back-front.jpg \
&& mv 1998-back-front.jpg 1998-baker-front.jpg
for x in *.jpg; do
convert -geometry 200x200 -quality 80 $x $SITEDIR/preview/$x
convert -geometry 1024x1024 -quality 75 $x $SITEDIR/big/$x
echo $x
done
python $SITEDIR/scaletrim.py 96x96 *.jpg
rename -f 's/\.trim//' *.trim.jpg
mv *.jpg $SITEDIR/thumb/
cd $SITEDIR/preview
rm -r keepernotes.com
else
# just a few
for URL in "$@"; do
curl -O "$URL"
fn=`basename "$URL"`
mogrify -geometry 96x96 "$fn"
echo "$fn"
done
fi
|
Java | UTF-8 | 1,242 | 2.34375 | 2 | [] | no_license | package com.example.tutorial_9;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class call extends AppCompatActivity {
EditText cnum;
Button call;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_call);
cnum = findViewById(R.id.txtcphone);
call = findViewById(R.id.btncall);
call.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String phone = cnum.getText().toString();
if(phone.isEmpty()){
Toast.makeText(getApplicationContext(),"Enter number...!",Toast.LENGTH_SHORT).show();
}
else{
String s = "tel:"+phone;
Intent intent = new Intent(Intent.ACTION_CALL);
intent.setData(Uri.parse(s));
startActivity(intent);
}
}
});
}
} |
Java | UTF-8 | 2,120 | 2.65625 | 3 | [] | no_license | package com.rotemarbiv.tin;
import android.app.Activity;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import java.util.ArrayList;
/**
* Created by laurescemama on 21/08/2017.
*/
public class EventAdapter extends ArrayAdapter<Event> {
Context context;
int layoutResourceId;
ArrayList<Event> events;
public EventAdapter(Context context, int layoutResourceId, ArrayList<Event> data) {
super(context, layoutResourceId, data);
this.layoutResourceId = layoutResourceId;
this.context = context;
this.events = data;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View row = convertView;
EventHolder holder = null;
if(row == null)
{
LayoutInflater inflater = ((Activity)context).getLayoutInflater();
row = inflater.inflate(layoutResourceId, parent, false);
holder = new EventHolder();
holder.imageIcon = (ImageView)row.findViewById(R.id.imageIconList);
holder.nameTitle = (TextView)row.findViewById(R.id.nameTitleList);
holder.timeTitle = (TextView)row.findViewById(R.id.timeTitleList);
holder.dateTitle = (TextView)row.findViewById(R.id.dateTitleList);
row.setTag(holder);
}
else
{
holder = (EventHolder)row.getTag();
}
Event event = events.get(position);
System.out.println(event.getEventTitle() + " " + event.isItMe + " " + position);
holder.imageIcon.setImageResource(event.getIcon());
holder.nameTitle.setText(event.getEventTitle());
holder.timeTitle.setText(event.getTimeStr());
holder.dateTitle.setText(event.getDateStr());
return row;
}
static class EventHolder
{
ImageView imageIcon;
TextView nameTitle;
TextView timeTitle;
TextView dateTitle;
}
} |
Markdown | UTF-8 | 1,046 | 2.671875 | 3 | [
"MIT",
"ISC",
"BSD-2-Clause"
] | permissive | ---
title: Web workers
category: JavaScript
updated: 2017-10-30
layout: 2017/sheet
weight: -1
---
## Web workers
#### Client
```js
var worker = new Worker('worker.js')
worker.onmessage = function (message) {
alert(JSON.stringify(message.data))
})
worker.postMessage('hello!')
```
Messages can be anything that can be serialized into JSON (objects, arrays, strings, numbers, booleans). See: [structured clone](https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API/Structured_clone_algorithm)
#### Worker
```js
self.onmessage = function (message) {
···
}
self.postMessage({ msg: 'hello' })
```
### Message data
#### [MessageEvent]
```js
bubbles: false
cancelBubble: false
cancelable: false
clipboardData: undefined
currentTarget: Worker
data: "Hello" ← the data
defaultPrevented: false
eventPhase: 0
lastEventId: ""
origin: ""
ports: Array[0]
returnValue: true
source: null
srcElement: Worker
target: Worker
timeStamp: 1344821022383
type: "message"
```
These are the contents of `message` on onmessage.
|
C++ | UTF-8 | 4,053 | 2.90625 | 3 | [] | no_license | #include "mbed.h"
#include <math.h>
#include <cstdio>
#include <cmath>
#include <complex>
#include <iostream>
#include <valarray>
void initLCD();
void write_command(char c);
void write_data(char c);
void print_LCD_char(char c);
void print_LCD_String(char *s);
void initLED();
void configLED(char b, char g, char r, char a);
void print_LCD_int(int en);
AnalogIn micro(A0);
I2C i2c(I2C_SDA , I2C_SCL );
Serial pc(USBTX, USBRX);
int LCD_addr = 0x7C;
int LED_addr = 0xC4;
int i = 0;
char*str;
char ch[36];
void initLED(){
char cmd[3];
wait(0.04);
cmd[0] = 0x80;
cmd[1] = 0x00;
cmd[2] = 0x00;
i2c.write(LED_addr, cmd, 3, false);
cmd[0] = 0x08;
cmd[1] = 0xAA;
i2c.write(LED_addr, cmd, 2, false);
}
void configLED(char b, char g, char r, char a){
char cmd[5];
cmd[0] = 0xA2;
cmd[1] = b;
cmd[2] = g;
cmd[3] = r;
cmd[4] = a;
i2c.write(LED_addr, cmd, 5, false);
}
void initLCD(){
wait(0.04);
write_command(0x3C);//4 pour mode 1 ligne(Celle du haut), C pour 2
write_command(0x0C);
write_command(0x01);
wait(0.0016);
write_command(0x06);
}
void write_command(char c){
char cmd[2];
cmd[0] = 0x80;
cmd[1] = c;
i2c.write(LCD_addr, cmd, 2, false);//false car répété
}
void write_data(char c){
char cmd[2];
cmd[0] = 0x40;
cmd[1] = c;
i2c.write(LCD_addr, cmd, 2, false);
}
void print_LCD_char(char c){
char cmd[2];
cmd[0] = 0x40;
cmd[1] = c;
i2c.write(LCD_addr, cmd, 2, false);
}
void print_LCD_String(char *s){
char cmd[36];
cmd[0] = 0x40;
for(int n = 1; n < strlen(s)+1; n++){
cmd[n] = s[n-1];
}
i2c.write(LCD_addr, cmd, strlen(s)+1, false);
}
void affichage(char n, char* b){
wait(0.4);
write_command(0x01);
wait(0.00153);
sprintf(b, "%d", n);
print_LCD_String(b);
}
const double PI = 3.141592653589793238460;
typedef std::complex<double> Complex;
typedef std::valarray<Complex> CArray;
// Cooley–Tukey FFT (in-place, divide-and-conquer)
// Higher memory requirements and redundancy although more intuitive
void fft(CArray& x)
{
const size_t N = x.size();
if (N <= 1) return;
// divide
CArray even = x[std::slice(0, N/2, 2)];
CArray odd = x[std::slice(1, N/2, 2)];
// conquer
fft(even);
fft(odd);
// combine
for (size_t k = 0; k < N/2; ++k)
{
Complex t = std::polar(1.0, -2 * PI * k / N) * odd[k];
x[k ] = even[k] + t;
x[k+N/2] = even[k] - t;
}
}
int main() {
initLED();
configLED(0xFF, 0xFF, 0xFF, 0xFF);
initLCD();
const int nbEch = 128; //nombre d'échantillons
int frqEch = 44000;
Complex echantillons[nbEch];
int continuer = 1;
while(continuer){
//wait (0.1);
continuer = 1;
Complex test[nbEch];
for (int nb = 0; nb <nbEch ; nb++){
wait (1.0/(float)frqEch);
test[nb] = micro.read();
}
/*for (int nb = 0; nb <nbEch ; nb++){
//test[nb] = 100.0*cos(2.0*PI*nb*20000.0*rand()/(float)frqEch)+100.0*cos(2.0*PI*nb*20000.0*rand()/(float)frqEch);
if (nb < nbEch/2)
test[nb] = 100.0;
else test[nb] = -100.0;
}*/
CArray data(test, nbEch);
float VectFreq[nbEch/2];
// forward fft
fft(data);
float max = 0.0;
float maxFreq = 0.0;
for (int nb = 0; nb <nbEch/2 ; nb++){
data[nb] = (norm(data[nb]));
VectFreq[nb] =((float)nb) * (float)frqEch/((float)(nbEch)) ;
//pc.printf("\r\n%.f Hz --> %f",VectFreq[nb],data[nb].real());
if (data[nb].real() > max){
max = data[nb].real();
maxFreq = VectFreq[nb];
}
}
pc.printf("\rFrequence dominante = %f Hz avec A = %f ", maxFreq, max);
}
}
|
C++ | UTF-8 | 741 | 2.515625 | 3 | [] | no_license | //
// TextureCache.cpp
// flyweight, proxy pattern
//
// Created by mac on 2016. 9. 3..
// Copyright © 2016년 남준현. All rights reserved.
//
#include "TextureCache.hpp"
#include "Texture2D.hpp"
TextureCache& TextureCache::getInstance()
{
static TextureCache instance;
return instance;
}
TextureCache::TextureCache()
{
}
TextureCache::~TextureCache()
{
}
Texture2D* TextureCache::addImage(const std::string& fileName)
{
Texture2D* texture = nullptr;
auto iter = _textures.find(fileName);
if ( iter != std::end(_textures) )
texture = iter->second;
else
{
texture = new Texture2D(fileName);
_textures.insert( {fileName, texture} );
}
return texture;
}
|
Java | UTF-8 | 405 | 1.820313 | 2 | [] | no_license | package ch.bergturbenthal.raoa.importer.domain.model;
import java.nio.file.Path;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.lang.NonNull;
import org.springframework.validation.annotation.Validated;
@ConfigurationProperties(prefix = "raoa.import")
@Data
@Validated
public class Properties {
@NonNull private Path media;
}
|
Java | UTF-8 | 584 | 2.25 | 2 | [] | no_license | package ru.pp.xaos.server.manage.response.errors;
import java.io.IOException;
import javax.servlet.http.HttpServletResponse;
import ru.pp.xaos.server.config.Strings;
import ru.pp.xaos.server.format.TemplateLoader;
public class FileIsTooLarge {
private static TemplateLoader templateLoader = new TemplateLoader();
public void send(Integer maxSize, HttpServletResponse resp) throws IOException {
String tpl = templateLoader.load(Strings.SIZE_HTML);
tpl = tpl.replace(Strings.SIZE_HTML_MAX, maxSize.toString());
resp.getOutputStream().write(tpl.getBytes());
}
}
|
JavaScript | UTF-8 | 619 | 2.71875 | 3 | [] | no_license | import { useState, useEffect } from 'react';
import axios from 'axios'
function CurrentLocation() {
const [locationData, setLocationData] = useState('');
useEffect(() => {
let result =
setInterval(() => {
axios.get('https://freegeoip.app/json/').then(function (response) {
result = response.data;
setLocationData(result);
})
}, 5000)
}, []);
return(
<div className="mb-auto">
<p className=" font-medium tracking-widest text-white text-3xl md:text-4xl uppercase">IN {locationData.city}, {locationData.country_name}</p>
</div>
)
}
export default CurrentLocation |
Java | UTF-8 | 987 | 1.640625 | 2 | [] | no_license | package com.google.android.gms.internal.p001firebaseauthapi;
/* renamed from: com.google.android.gms.internal.firebase-auth-api.zzhz reason: invalid package */
/* compiled from: com.google.firebase:firebase-auth@@20.0.2 */
public final class zzhz extends zzzz<zzic, zzhz> implements zzabh {
private zzhz() {
super(zzic.zzg);
}
/* synthetic */ zzhz(zzhy zzhy) {
super(zzic.zzg);
}
public final zzhz zza(String str) {
if (this.zzb) {
zzi();
this.zzb = false;
}
((zzic) this.zza).zzb = str;
return this;
}
public final zzhz zzb(zzzb zzzb) {
if (this.zzb) {
zzi();
this.zzb = false;
}
((zzic) this.zza).zze = zzzb;
return this;
}
public final zzhz zzc(zzib zzib) {
if (this.zzb) {
zzi();
this.zzb = false;
}
((zzic) this.zza).zzf = zzib.zza();
return this;
}
}
|
Markdown | UTF-8 | 8,030 | 3.171875 | 3 | [
"BSD-3-Clause"
] | permissive | ## 2.7 Шаблонизатор Slim
Slim - язык шаблонов, чья задача — сократить объем кода, при этом не делая его страшным и непонятным.
Вот так выгядит шаблон с использованием Slim:
```
doctype html
html
head
title Slim Examples
meta name="keywords" content="template language"
body
h1 Markup examples
#content.example1
p Nest by indentation
= yield
- unless items.empty?
table
- for item in items do
tr
td = item.name
td = item.price
- else
p No items found
#footer
| Copyright © 2010 Andrew Stone
= render 'tracking_code'
script
| $(content).do_something();
```
### Список всех операторов:
```
| Вертикальная черта сообщает шаблонизатору, что нужно просто откопировать линию. При этом все "опасные" символы фильтруется.
' Одиночная скобка работает как и предыдущий оператор, но добавляет в конце пробел.
- Дефис работает как и в Haml, используется для циклов, условий и прочего, в чем вы раньше использовали <% ... %>
= Знак равенства работает как <%= ... %>, выводя содержимое в html
=' Работает как и предыдущий оператор, при этом добавляя в конец пробел.
== Работает как и знак равенства, но выводит текст "как есть", без обработки методом escape_html
==' Тоже самое, что и выше, но добавляет в конце пробел.
/ Знак комментария. Код не будет выполнен и не попадет в html вообще.
/! Знак для html комментариев (<!-- -->), которые попадут в вывод.
```
### Атрибуты и комментарии
Обозначать id и class можно вот так:
```
blockquote id="quote-#{@quote.id}" class="quote"
p class="title" = @quote.title
p style="padding:1em;" = @quote.body
```
Кроме того, Slim допускает несколько вариантов синтаксиса::
/ Эти две линии идентичны.
#nav.top
div id="nav" class="top"
/ Допускается писать любой из этих вариантов
h1 class=page_header_class = page_header
h1{class=page_header_class} = page_header
h1[class=page_header_class] = page_header
h1(class=page_header_class) = page_header
Еще одна приятная штука — если в атрибуте не указаны кавычки, будет использована переменная. Из примера парой строчек выше можно увидеть, что используется переменная page_header_class.
# Можно писать и так, и так.
a href="#{url_for @user}" = @user.name
# Во втором случае не надо писать конструкцию "#{...}"
a href=url_for(@user) = @user.name
Если функция возвращает false, атрибут вообще не будет выведен в html:
option value="Slim" selected=option_selected?("Slim") # -> <option value="Slim"></option>
Можно использовать интерполяцию как в строках Ruby:
body
h1 Приветствуем, #{current_user.name}
| С помощью двойных скобок #{{content}} выводится как есть, без фильтрации методом escape_html.
Мне очень нравится, как работают комментарии. Если у нас имеется блок кода, который надо закомментить, достаточно добавить всего одну строку, которая повлияет на весь блок.
# весь этот блок ниже закомментирован и не будет выведен
/.comments
- @comments.each do |comment|
== render comment
Стоит учесть, что метод render по-умолчанию фильтрует вывод, поэтому перед ним надо ставить двойной знак равенства, чтобы escape_html не сработал дважды.
### Производительность
Шаблоны в Rails кешируются, поэтому по скорости они будут отставать от стандартного Erb лишь при первом обращении к ним. Вот сравнительная таблица, которая показывает, что Slim уж точно не будет узким местом:
# Linux + Ruby 1.9.2, 1000 iterations
user system total real
(1) erb 0.680000 0.000000 0.680000 ( 0.810375)
(1) erubis 0.510000 0.000000 0.510000 ( 0.547548)
(1) fast erubis 0.530000 0.000000 0.530000 ( 0.583134)
(1) slim 4.330000 0.020000 4.350000 ( 4.495633)
(1) haml 4.680000 0.020000 4.700000 ( 4.747019)
(1) haml ugly 4.530000 0.020000 4.550000 ( 4.592425)
(2) erb 0.240000 0.000000 0.240000 ( 0.235896)
(2) erubis 0.180000 0.000000 0.180000 ( 0.185349)
(2) fast erubis 0.150000 0.000000 0.150000 ( 0.154970)
(2) slim 0.050000 0.000000 0.050000 ( 0.046685)
(2) haml 0.490000 0.000000 0.490000 ( 0.497864)
(2) haml ugly 0.420000 0.000000 0.420000 ( 0.428596)
(3) erb 0.030000 0.000000 0.030000 ( 0.033979)
(3) erubis 0.030000 0.000000 0.030000 ( 0.030705)
(3) fast erubis 0.040000 0.000000 0.040000 ( 0.035229)
(3) slim 0.040000 0.000000 0.040000 ( 0.036249)
(3) haml 0.160000 0.000000 0.160000 ( 0.165024)
(3) haml ugly 0.150000 0.000000 0.150000 ( 0.146130)
(4) erb 0.060000 0.000000 0.060000 ( 0.059847)
(4) erubis 0.040000 0.000000 0.040000 ( 0.040770)
(4) slim 0.040000 0.000000 0.040000 ( 0.047389)
(4) haml 0.190000 0.000000 0.190000 ( 0.188837)
(4) haml ugly 0.170000 0.000000 0.170000 ( 0.175378)
1. Рендер некешированной страницы при первом обращении.
Его можно активировать, используя параметр slow=1.
2. Кешированный тест. Шаблон предварительно парсится.
Код Ruby не компилируется и может быть выполнен в любое время.
Этот бенчмарк испольует стандартное API шаблонов.
3. Компилированный тест. Шаблон также предварительно парсится,
но кроме того, код Ruby компилируется в отдельный метод.
Это самый быстрый тест, потому что в нем тестируется лишь
скорость выполнения самого кода.
4. Компилированный Tilt-бенчмарк. Шаблон компилируется с помощью Tilt,
что даёт более точные результаты производительности в режиме Продакшена
в таких фреймворках как Sinatra, Ramaze and Camping. |
C++ | UTF-8 | 730 | 3.515625 | 4 | [
"MIT"
] | permissive | class Solution {
public:
bool checkOverlap(int radius, int x_center, int y_center, int x1, int y1,
int x2, int y2) {
auto clamp = [&](int center, int mini, int maxi) {
return max(mini, min(maxi, center));
};
// The closest point to the circle within the rectangle
int closestX = clamp(x_center, x1, x2);
int closestY = clamp(y_center, y1, y2);
// The distance between the circle's center and this closest point
int distanceX = x_center - closestX;
int distanceY = y_center - closestY;
// If the distance is less than the circle's radius, an intersection occurs
return (distanceX * distanceX) + (distanceY * distanceY) <=
(radius * radius);
}
};
|
Python | UTF-8 | 924 | 3.96875 | 4 | [] | no_license | #!/usr/bin/env python
# encoding: utf-8
"""
nrc.py
Created by Yamato Matsuoka on 2012-07-16.
Description:
Write a program to find the first non repeated character in a string.
Input sample:
The first argument will be a text file containing strings. e.g.
yellow
tooth
Output sample:
Print to stdout, the first non repeating character, one per line.
e.g.
y
h
"""
import sys
import operator
def tally(lis):
d = {}
for i in lis:
if d.has_key(i):
d[i] += 1
else:
d[i] = 1
out = d.items()
out.sort(key=operator.itemgetter(-1))
return out
def nonrepeated_character(s):
singles = [i for (i,j) in tally(s) if j==1]
for c in s:
if c in singles:
return c
if __name__ == '__main__':
with open(sys.argv[1], "r") as f:
data = [s.rstrip() for s in f]
out = (nonrepeated_character(s) for s in data)
print "\n".join(out)
|
PHP | UTF-8 | 2,082 | 2.59375 | 3 | [] | no_license | <?php
namespace App\Repository;
use League\OAuth2\Server\Entities\AuthCodeEntityInterface;
use League\OAuth2\Server\Repositories\AuthCodeRepositoryInterface;
use Psr\Log\LoggerInterface;
use GraphAware\Neo4j\Client\Client;
use GraphAware\Neo4j\Client\ClientBuilder;
use GraphAware\Neo4j\OGM\EntityManager;
use App\Models\AuthCodeEntity;
include __DIR__.'/../Models/AuthCodeEntity.php';
class AuthCodeRepository implements AuthCodeRepositoryInterface
{
private $logger;
private $dbclient;
private $dbentity;
private $mapper;
private $settings;
private $connection;
private $connalias;
public function __construct(LoggerInterface $logger, \Slim\Collection $settings){
$this->logger = $logger;
$this->settings = $settings;
$this->connection = $this->settings['dbclient']['type']. '://'.$this->settings['dbclient']['username'].':'.$this->settings['dbclient']['password'].'@'. $this->settings['dbclient']['host'].':'.$this->settings['dbclient']['port'];
$this->connalias = $this->settings['dbclient']['name'];
$this->dbclient = ClientBuilder::create()->addConnection($this->connalias, $this->connection)->build();
$this->dbentity = EntityManager::create($this->connection);
$this->mapper = new \JsonMapper();
$this->mapper->setLogger($this->logger);
$this->mapper->bStrictNullTypes = FALSE;
} //put your code here
/**
* {@inheritdoc}
*/
public function persistNewAuthCode(AuthCodeEntityInterface $authCodeEntity)
{
// Some logic to persist the auth code to a database
}
/**
* {@inheritdoc}
*/
public function revokeAuthCode($codeId)
{
// Some logic to revoke the auth code in a database
}
/**
* {@inheritdoc}
*/
public function isAuthCodeRevoked($codeId)
{
return false; // The auth code has not been revoked
}
/**
* {@inheritdoc}
*/
public function getNewAuthCode()
{
return new AuthCodeEntity();
}
}
|
Python | UTF-8 | 243 | 2.65625 | 3 | [] | no_license |
with open("/Users/keshavkummari/6am_python_nit_3rdJuly2019/file-and-dir/test.txt","r+a") as file:
#print(file.read())
print(file.tell())
print(file.seek(0))
#print(file.write("Our Next Topic is RegEx"))
print(file.read())
|
C++ | GB18030 | 1,203 | 3.234375 | 3 | [] | no_license | /************************************************************************
* ǩ : shared_ptrweak_ptr
* :
* :
* : v1.0
* ˵ :
* : dragonfive
* ʱ :
* ʱ :
************************************************************************
* Copyright @dragonfive 2016 . All rights reserved.
************************************************************************/
#include <memory>
#include <iostream>
using namespace std;
int main()
{
//shared_ptr<string> sp1(make_shared<string>("Hello"));//make_sharedһ(ָŶ)һsharedָڴ;
//shared_ptr<string> sp1(make_shared<string>(string("Hello")));
shared_ptr<string> sp1(new string("Hello"));
shared_ptr<string> sp2 = sp1;
cout << "*sp1:" << *sp1 << endl;
cout << "*sp2:" << *sp2 << endl;
sp1.reset();
cout << "*sp2:" << *sp2 << endl;
weak_ptr<string> wp = sp2;
cout << "*wp.lock():" << *wp.lock() << endl;
sp2.reset();
//cout << "*wp.lock():" << *wp.lock() << endl; //! ʱ
return 0;
}
|
JavaScript | UTF-8 | 2,500 | 3.15625 | 3 | [
"MIT"
] | permissive | const runBatches = require('./runBatches');
const taskFactorySample = (delay, resolve, val) => () =>
new Promise((res, rej) => setTimeout(resolve ? res : rej, delay, val));
describe('runBatches', () => {
describe('* called with no arguments', () => {
test('returns a rejected promise', async () => {
expect.assertions(1);
await expect(runBatches()).rejects.toThrow('invalid arguments');
});
});
describe('* called with wrong arguments', () => {
test('returns a rejected promise', async () => {
expect.assertions(1);
await expect(runBatches([() => {}])).rejects.toThrow();
});
});
describe('* given a list of 6 mixed tasks', () => {
const tasks = [
taskFactorySample(100, true, 1),
taskFactorySample(200, true, 2),
taskFactorySample(100, false, 'error3'),
taskFactorySample(300, true, 4),
taskFactorySample(100, false, 'error5'),
taskFactorySample(200, false, 'error6'),
];
let batch_size = 2;
test('the result is an array equal to tasks.length', async () => {
expect.assertions(1);
const data = await runBatches(tasks, batch_size);
expect(data.length).toBe(6);
});
test('a fulfilled task returns a value', async () => {
expect.assertions(3);
const data = await runBatches(tasks, batch_size);
expect(data[0]).toStrictEqual({ value: 1 });
expect(data[1]).toStrictEqual({ value: 2 });
expect(data[3]).toStrictEqual({ value: 4 });
});
test('a rejected task returns an error', async () => {
expect.assertions(1);
const data = await runBatches(tasks, batch_size);
expect(data[2]).toStrictEqual({ error: 'error3' });
});
test('with batch_size = 2, execution time is ~500 ms', async () => {
expect.assertions(1);
const expectedTime = 500;
const start = performance.now();
await runBatches(tasks, batch_size);
const end = performance.now();
const time = end - start;
const error = 1 - expectedTime / time;
expect(error).toBeLessThan(0.06);
});
test('with batch_size = 3, execution time is ~400 ms', async () => {
expect.assertions(1);
const expectedTime = 400;
batch_size = 3;
const start = performance.now();
await runBatches(tasks, batch_size);
const end = performance.now();
const time = end - start;
const error = 1 - expectedTime / time;
expect(error).toBeLessThan(0.06);
});
});
});
|
Java | UTF-8 | 357 | 1.828125 | 2 | [] | no_license | package io.lvcore.model.feedback;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import java.time.Instant;
@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
public class Review {
String text;
Instant dateWritten;
String status;
String volunteerId;
String hostId;
}
|
C | UTF-8 | 480 | 3.71875 | 4 | [] | no_license |
/*
Show how each of the following numbers will look if displayed by printf with
%#012.5g as the conversion specification:
a) 83.7361
*0000083.736
00000083.736
b) 29748.6607
*00000029748
00000029749.
c) 1054932234.0
*1.054900000
001.0549e+09
d) 0.0000235218
002.3522e-05
002.3522e-05
*/
#include <stdio.h>
int main()
{
printf("a)%#012.5g\n", 83.7361);
printf("b)%#012.5g\n", 29748.6607);
printf("c)%#012.5g\n", 1054932234.0);
printf("d)%#012.5g\n", 0.0000235218);
}
|
C++ | UTF-8 | 3,535 | 2.84375 | 3 | [
"MIT"
] | permissive | #include <ros/ros.h>
#include <i2c_comm/I2CIn.h>
#include <i2c_comm/I2COut.h>
#include <std_msgs/String.h>
#include <vector>
#include <iostream>
#include <map>
extern "C"
{
#include <picom/i2c.h>
#include <alib-c/alib_error.h>
}
/* Map of file descriptors to I2C devices.
* First value is I2C addr, second is the file descriptor. */
std::map<uint8_t, int> fds;
int reconnectSlave(uint8_t addr)
{
/* Close the old socket if it was open. */
int fd = fds[addr];
if(fd > 0)
close(fd);
fd = connectToSlave(addr);
if(fd <= 0)
ROS_INFO("Could not connect to slave %d.", addr);
else
{
fds[addr] = fd;
ROS_INFO("Connected to slave %d.", addr);
}
return(fd);
}
int getSlave(uint8_t addr)
{
int fd = fds[addr];
if(fd <= 0)
fd = reconnectSlave(addr);
return(fd);
}
//bool i2c_out(uint8_t addr, std_msgs::String& data)
bool i2c_out(uint8_t addr, std::vector<uint8_t>& data)
{
/* Get the file descriptor. */
int fd = getSlave(addr);
if(fd <= 0)
return(false);
/* Write the data. */
int err = write(fd, &data[0], data.size());
if(err < 0)
{
ROS_INFO("Write failed, attempting to reconnect to slave %d.", addr);
fd = reconnectSlave(addr);
if(fd <= 0)
return(false);
err = write(fd, &data[0], data.size());
if(err < 0)
{
ROS_INFO("Second write attempt to %d failed!", addr);
return(false);
}
}
else if(err != data.size())
ROS_INFO("Wrote %d bytes to slave %d, should have written %d bytes.",
err, addr, data.size());
return(true);
}
int32_t i2c_in(uint8_t addr, std::vector<uint8_t>& data, uint32_t dataLen)
{
if(data.size() < dataLen)
data.resize(dataLen);
int fd = getSlave(addr);
if(fd <= 0)
return ALIB_BAD_ARG;
int32_t err = read(fd, &data[0], dataLen);
if(err < 0)
{
fd = reconnectSlave(addr);
if(fd <= 0 || read(fd, &data[0], dataLen) < 0)
{
ROS_INFO("Error reading data from %d. Errno: %d", addr, errno);
err = ALIB_UNKNOWN_ERR;
}
}
return(err);
}
/* Writes a message to a specific I2C device.
*
* Arguments:
* Request:
* uint8_t addr - I2C device address.
* std::vector<uint8_t> data - Data to transmit to slave.
*
* Returns:
* true: Message successfully sent.
* false: Message could not be successfully sent. The
* file descriptor was probably not open or could not be opened. */
bool i2c_out_cb(i2c_comm::I2COut::Request& req, i2c_comm::I2COut::Response& res)
{
return(i2c_out(req.addr, req.data));
}
/* Reads a message from a specific I2C device.
*
* Arguments:
* Requests:
* uint8_t addr - I2C device address.
* uint32_t dataLen - Number of bytes to read.
* Response:
* std::vector<uint8_t> data - The data received from the slave.
* uint32_t dataLen - The number of bytes read.
*
* Returns:
* true: Message successfully sent.
* false: Message could not be successfully sent. The
* file descriptor was probably not open or could not be opened. */
bool i2c_in_cb(i2c_comm::I2CIn::Request& req,
i2c_comm::I2CIn::Response& res)
{
int32_t result = i2c_in(req.addr, res.data, req.dataLen);
if(result < 0)
{
res.dataLen = 0;
return(false);
}
else
{
res.dataLen = result;
return(true);
}
}
int main(int argc, char** argv)
{
/* Init ros. */
ros::init(argc, argv, "i2c_srv");
/* Init node. */
ros::NodeHandle nh;
ros::ServiceServer outService = nh.advertiseService("i2c_out", i2c_out_cb);
ros::ServiceServer inService = nh.advertiseService("i2c_in", i2c_in_cb);
ROS_INFO("Services started!");
ros::spin();
return(0);
} |
PHP | UTF-8 | 481 | 2.59375 | 3 | [
"MIT"
] | permissive | <?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Cart extends Model
{
protected $fillable = [
'products_id', 'users_id', 'qty', 'total',
];
protected $hidden = [
];
public function product(){
return $this->hasOne( Product::class, 'id', 'products_id' );//Relasi dengan tabel product
}
public function user(){
return $this->belongsTo( User::class, 'users_id', 'id');//relasi dengan tabel user
}
}
|
JavaScript | UTF-8 | 3,038 | 3.015625 | 3 | [] | no_license | (function () {
function showError(err) {
let quote = document.getElementById("quotes").getElementsByTagName("p")[0];
let author = document.getElementById("quotes").getElementsByTagName("cite")[0];
quote.textContent = "Sorry, quotes are not currently available. Please check back later.";
author.textContent = "Sad Malfunction Bear";
console.log(err);
}
function showQuote(response) {
let quote = document.getElementById("quotes").getElementsByTagName("p")[0];
let author = document.getElementById("quotes").getElementsByTagName("cite")[0];
let quoteText = response.quoteText.trim();
let authorText = response.quoteAuthor.trim();
quote.textContent = quoteText;
author.textContent = (authorText) ? authorText : "Unknown";
}
function jsonP(url, callbackName, callbackFn) {
let script = document.createElement("script");
script.src = `${url}&jsonp=${callbackName}`;
window[callbackName] = function (response) {
try {
if (!response) throw "New exception";
if (typeof callbackFn === "function") callbackFn(response);
} catch (err) {
showError(err);
}
};
script.onerror = function (err) {
showError(err);
};
document.getElementsByTagName("head")[0].appendChild(script);
script.remove();
}
function makeTweet() {
let tweetBtn = document.getElementById("tweetBtn");
let quote = document.getElementById("quotes").getElementsByTagName("p")[0].textContent;
quote = quote.replace(/;/g, ",");
let author = document.getElementById("quotes").getElementsByTagName("cite")[0].textContent;
tweetBtn.href = `https://twitter.com/intent/tweet?text="${quote}" -${author}`;
}
function fadeOut() {
document.getElementsByTagName("blockquote")[0].style.opacity = "0";
}
function fadeIn() {
setTimeout(function () {
document.getElementsByTagName("blockquote")[0].style.opacity = "1";
}, 2000);
}
function getSetHeight() {
let qCont = document.getElementById("quotes");
let qBlock = document.getElementsByTagName("blockquote")[0];
let ht = qBlock.scrollHeight;
qCont.style.height = ht + "px";
}
function hTweet(time) {
setTimeout(function () {
getSetHeight();
makeTweet();
}, time);
}
(function () {
let url = "https://api.forismatic.com/api/1.0/?method=getQuote&lang=en&format=jsonp";
getSetHeight();
jsonP(url, "handleRes", showQuote);
fadeIn();
hTweet(1000);
document.getElementById("getNewQuote").onclick = function () {
getSetHeight();
fadeOut();
setTimeout(function () {
jsonP(url, "handleRes", showQuote);
}, 1000);
fadeIn();
hTweet(2100);
};
})();
})(); |
C++ | UTF-8 | 5,853 | 2.640625 | 3 | [] | no_license | #include "body.h"
body::body(GLfloat shininess, GLfloat ambient)
{
this-> colour = glm::vec3(0.33, 0.368, 0.192);
this->numberOfVerticies = 40;
this->light = new lighting(shininess, ambient);
this->transform = new transformation();
this->base_cylider = new cylinder(0.2, 70.0, this->colour);
this->gun_transformation = new transformation();
defineVeritices();
}
body::~body()
{
}
void body::defineVeritices()
{
GLfloat width = 1.5;
GLfloat depth = 1.5;
GLfloat hight = 1.0;
glm::vec3 normals[40];
glm::vec3 pColours[40];
GLfloat x = width;
GLfloat y = hight / 5;
GLfloat z = depth / 2;
GLfloat inset = depth / 6;
GLfloat incline = width / 3;
int numberOfSquares = 10;
// Define vertices as glm:vec3
glm::vec3 vertices[] = {
//bottom
/*0*/ glm::vec3(x, y, -z), glm::vec3(x, y, z), glm::vec3(x, y - 0.1, -z), glm::vec3(x, y - 0.1, z),
/*4*/ glm::vec3(x, y - 0.1, -z), glm::vec3(x, y - 0.1, z), glm::vec3(x - incline, -y, -z + inset), glm::vec3(x - incline, -y, z - inset),
/*8*/ glm::vec3(x - incline, -y, -z + inset), glm::vec3(x - incline, -y, z - inset), glm::vec3(-x + incline, -y, -z + inset), glm::vec3(-x + incline, -y, z - inset),
/*12*/ glm::vec3(-x + incline, -y, -z + inset), glm::vec3(-x + incline, -y, z - inset), glm::vec3(-x, y - 0.1, -z), glm::vec3(-x, y - 0.1, z),
/*16*/ glm::vec3(-x, y - 0.1, -z), glm::vec3(-x, y - 0.1, z), glm::vec3(-x, y, -z), glm::vec3(-x, y, z),
//side long strips
/*20*/ glm::vec3(-x, y, -z), glm::vec3(x, y, -z), glm::vec3(-x, y - 0.1, -z), glm::vec3(x, y - 0.1, -z),
/*24*/ glm::vec3(x, y, z), glm::vec3(-x, y, z), glm::vec3(x, y - 0.1, z), glm::vec3(-x, y - 0.1, z),
//side squares
/*28*/ glm::vec3(-x + incline, y - 0.1, -z), glm::vec3(x - incline, y - 0.1, -z), glm::vec3(-x + incline, -y, -z + inset), glm::vec3(x - incline, -y, -z + inset),
/*32*/ glm::vec3(x - incline, y - 0.1, z), glm::vec3(-x + incline, y - 0.1, z), glm::vec3(x - incline, -y, z - inset), glm::vec3(-x + incline, -y, z - inset),
/*36*/ glm::vec3(-x, y, -z), glm::vec3(-x, y, z), glm::vec3(x, y, -z), glm::vec3(x, y, z),
};
glGenBuffers(1, &this->bodyBufferObject);
glBindBuffer(GL_ARRAY_BUFFER, bodyBufferObject);
glBufferData(GL_ARRAY_BUFFER, numberOfVerticies * sizeof(glm::vec3), &vertices[0], GL_STATIC_DRAW);
glBindBuffer(GL_ARRAY_BUFFER, 0);
//define normals
int step = 0;
for (int j = 0; j < numberOfSquares; j++)
{
glm::vec3 V = glm::vec3(vertices[step + 1] - vertices[step]);
glm::vec3 W = glm::vec3(vertices[step + 2] - vertices[step]);
glm::vec3 xProduct = glm::normalize(glm::cross(V, W));
for (int i = step; i < step + 4; i++)
{
normals[i] = xProduct;
}
step += 4;
}
glGenBuffers(1, &this->normalsBufferObject);
glBindBuffer(GL_ARRAY_BUFFER, normalsBufferObject);
glBufferData(GL_ARRAY_BUFFER, numberOfVerticies * sizeof(glm::vec3), &normals[0], GL_STATIC_DRAW);
glBindBuffer(GL_ARRAY_BUFFER, 0);
GLuint pindices[] = { 0, 1, 2,
2, 3, 1,
4, 5, 6,
6, 7, 5,
8, 9, 10,
10, 11, 9,
12, 13, 14,
14, 15, 13,
16, 17, 18,
18, 19, 17,
20, 21, 22,
22, 23, 21,
24, 25, 26,
26, 27, 25,
28, 29, 30,
30, 31, 29,
32, 33, 34,
34, 35, 33,
36, 37, 38,
38, 39, 37,
22, 28, 30,
26, 32, 34,
29, 23, 31,
33, 27, 35};
this->isize = (sizeof(pindices) / sizeof(*pindices));
glGenBuffers(1, &elementbuffer);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, elementbuffer);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, isize * sizeof(GLuint), pindices, GL_STATIC_DRAW);
glBindBuffer(GL_ARRAY_BUFFER, 0);
/* Define colours as the x,y,z components of the sphere vertices */
for (int i = 0; i < this->numberOfVerticies; i++)
{
pColours[i] = this->colour;
}
/* Store the colours in a buffer object */
glGenBuffers(1, &this->colourBuffer);
glBindBuffer(GL_ARRAY_BUFFER, colourBuffer);
glBufferData(GL_ARRAY_BUFFER, sizeof(glm::vec3)* this->numberOfVerticies, pColours, GL_STATIC_DRAW);
glBindBuffer(GL_ARRAY_BUFFER, 0);
}
void body::drawBody()
{
glEnableVertexAttribArray(0);
glBindBuffer(GL_ARRAY_BUFFER, bodyBufferObject);
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, (void*)0);
/* Bind the normals */
glEnableVertexAttribArray(1);
glBindBuffer(GL_ARRAY_BUFFER, normalsBufferObject);
glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 0, (void*)0);
glEnableVertexAttribArray(2);
glBindBuffer(GL_ARRAY_BUFFER, this->colourBuffer);
glVertexAttribPointer(2, 3, GL_FLOAT, GL_FALSE, 0, 0);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, elementbuffer);
glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
glDrawElements(GL_TRIANGLES, this->isize, GL_UNSIGNED_INT, (GLvoid*)0);
}
glm::vec3 body::getColour()
{
return this->colour;
}
std::vector<transformation*> body::getGunTransformations()
{
std::vector<transformation*> gun_transformation(3);
transformation* turret = new transformation();
transformation* barrel = new transformation();
transformation* muzzel = new transformation();
turret->scale(-0.7, 'y');
turret->scale(-0.35, 'x');
turret->scale(-0.35, 'z');
turret->translate(0.3, 'y');
gun_transformation[0] = turret;
barrel->scaleUniform(-0.95);
barrel->scale(1.5, 'x');
barrel->rotate(-90, 'z');
barrel->translate(-1.3, 'x');
barrel->translate(0.34, 'y');
gun_transformation[1] = barrel;
muzzel->scaleUniform(-0.92);
muzzel->scale(0.1, 'x');
muzzel->rotate(-90, 'z');
muzzel->translate(-2.1, 'x');
muzzel->translate(0.34, 'y');
gun_transformation[2] = muzzel;
return gun_transformation;
}
cylinder* body::getBaseCylider()
{
return this->base_cylider;
}
glm::mat4 body::spinTurret(float amount)
{
glm::mat4 turretModel = glm::mat4(1.0f);
turretModel = glm::rotate(turretModel, -amount, glm::vec3(0, 1, 0));
return turretModel;
} |
PHP | UTF-8 | 2,785 | 3.109375 | 3 | [] | no_license | <?php
require_once 'autoload.php';
include 'templates/functions.php';
//New items are not created yet, have to use POST
$db = db_connect();
$faker = Faker\Factory::create();
for( $i=0;$i < 20; $i++ ) {
$blog_title = $faker->sentence($nbWords = 4, $variableNbWords = true) ;
$blog_author = $faker->name;
$blog_text = $faker->paragraph($nbSentences = 5, $variableNbSentences = true);
$date_posted = $faker->date($format = 'Y-m-d', $max = 'now');
$sql = "INSERT INTO `blogs` (`id`, `blog_title`, `blog_author`, `blog_text`, `date_posted`) VALUES (NULL, $blog_title, $blog_author, $blog_text, $date_posted)";
echo "SQL: $sql <br />";
$result = $db->query($sql);
}
/*
for( $i;$i < 20; $i++ ) {
$title = $faker->sentence($nbWords = 4, $variableNbWords = true) ;
$author = $faker->name;
$article_text = $faker->paragraph($nbSentences = 5, $variableNbSentences = true);
$published_date = $faker->date($format = 'Y-m-d', $max = 'now');
$sql = "INSERT INTO `articles` (`article_id`, `title`, `author`, `article_text`, `published_date`, `modified_at`, `created_at`) VALUES (NULL,'$title', '$author', '$article_text', '$published_date', CURRENT_TIMESTAMP, CURRENT_TIMESTAMP)";
echo "SQL: $sql <br />";
$result = $db->query($sql);
}
for( $i;$i < 80; $i++ ) {
$name = $faker->name;
$location = $faker->address;
$priceRangeLow = rand(1, 10);
$priceRangeHigh = rand(11, 100);
$tags = $faker->bs;
$sql = "INSERT INTO `restaurants` (`id`, `name`, `location`, `priceRangeLow`, `priceRangeHigh`, `tags`, `modifiedAt`, `createdAt`) VALUES (NULL,'$name', '$location', '$priceRangeLow', '$priceRangeHigh', '$tags', CURRENT_TIMESTAMP, CURRENT_TIMESTAMP)";
echo "SQL: $sql <br />";
$result = $db->query($sql);
$number_reviews = rand(0,10);
for( $j; $j < $number_reviews; $j++){
$restaurantIDFK = $db->insert_id;
$author = $faker->name;
$reviewText = $faker->bs;
$rating = rand(1,5);
$sql = "INSERT INTO reviews (id, author, review, rating, created_at, restaurantIDFK)
VALUES (null, '$author', '$reviewText', '$rating', NOW(), $restaurantIDFK)";
}
}
/*
for( $i;$i < 20; $i++ ) {
$title = $faker->company;
$author = $faker->name;
$article_text = $faker->text(1000);
$published_date = $faker->dateTime;
$pubDateStr = $published_date->format("Y-m-d H:i:s");
echo $title . "<br />";
echo $author . "<br />";
echo $article_text . "<br />";
echo $pubDateStr . "<br />";
}
*/ |
Python | UTF-8 | 765 | 2.625 | 3 | [] | no_license | import pandas as pd
import folium, os
result = pd.read_csv('datasets/processed/final.csv')
wb_map = folium.Map(location=[22.9964948,87.6855882], zoom_start=6.5, width='100%', height=800,)
for idx, row in result.iterrows():
print('Percentage loaded {0:.3f}\r'.format(idx*100.0/result.shape[0]), end='')
folium.Circle(
radius=50,
location=[row['latitude'], row['longitude']],
popup='<i>{}</i>'.format(row['name']),
color='crimson',
fill=True,
).add_to(wb_map)
# folium.Marker([row['latitude'], row['longitude']], popup='<i>{}</i>'.format(row['name'])).add_to(wb_map)
folium.GeoJson(
os.path.join('./', 'datasets/ac-shapes/wb-ac-shapes.json'),
name='geojson'
).add_to(wb_map)
wb_map.save('index.html')
|
Python | UTF-8 | 414 | 2.921875 | 3 | [
"MIT"
] | permissive | import board
def get_initial_arrangement_from_user() -> board.Board:
"""
the function handles user input to get the initial arrangement from the user
:return: a list of ships objects. according to the games rules.
"""
board.Board()
def get_guess_from_user() -> list:
"""
the function handles user input for each turn
:return: a coordinate - the players guess.
"""
pass
|
Java | UTF-8 | 1,086 | 2.21875 | 2 | [] | no_license | package com.autodisk.ObjectRepository;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.PageFactory;
import com.autodisk.genericutility.FileLib;
public class Loginpage { //Rule_1
WebDriver driver;
@FindBy(name = "user_name") //Rule--2
private WebElement Un;
@FindBy(name = "user_password")
private WebElement Ps;
@FindBy(id = "submitButton")
private WebElement lnBtn;
public WebElement getUn() { //Rile---3
return Un;
}
public WebElement getPs() {
return Ps;
}
public WebElement getLnBtn() {
return lnBtn;
}
public void loginToaApp(String username, String password)
{
Un.sendKeys(username);
Ps.sendKeys(password);
lnBtn.click();
}
public void loginToaApp() throws Throwable
{
FileLib fis = new FileLib();
Un.sendKeys(fis.getPropertieFileData("username"));
Ps.sendKeys(fis.getPropertieFileData("password"));
lnBtn.click();
}
public Loginpage(WebDriver driver)
{
PageFactory.initElements(driver, this);
}
}
|
PHP | UTF-8 | 3,645 | 2.65625 | 3 | [
"MIT"
] | permissive | <?php
$servername = "localhost";
$user = "root";
$passwd = "mysql123";
$db = "car";
$conn = mysqli_connect($servername, $user, $passwd, $db) or die(mysqli_connect_error());
session_start();
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$uname = $_POST['userName'];
$_SESSION["uname"] = $uname;
$pas = $_POST['password'];
$query = mysqli_query($conn, "SELECT * FROM customer WHERE uname='$uname' and password='$pas' ");
$query = mysqli_num_rows($query);
if ($query != 1) {
echo "<script>alert('Username or Password is incorrect');window.location.replace('customer.html');</script>";
exit(0);
}
}
mysqli_close($conn);
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>CUSTOMER LOGGED IN</title>
<link rel="stylesheet" href="customer.css">
<style>
ul {
list-style-type: none;
margin: 0px;
padding: 0;
overflow: hidden;
background-color: #333;
}
li {
float: left;
}
li a {
display: inline-block;
color: white;
text-align: center;
padding: 14px 16px;
text-decoration: none;
}
li a:hover {
background-color: #111;
}
</style>
</head>
<body>
<ul>
<li><a href="/dbPro/home.html">Home</a></li>
<li><a href="customer.html">Logout</a></li>
<li><a href="ccp.html">ChangePassword</a></li>
<li><a href="cra.html">RemoveAccount</a></li>
</ul>
<div class="heading" id="heading">
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$uname = $_POST['userName'];
echo "HELLO $uname,";
}
?>
</div>
<div>
<?php
$servername = "localhost";
$user = "root";
$passwd = "";
$db = "car";
$conn = mysqli_connect($servername, $user, $passwd, $db) or die(mysqli_connect_error());
$id = mysqli_query($conn, "SELECT * FROM car_list");
$num = mysqli_query($conn, "SELECT * FROM car_list");
$num = mysqli_num_rows($num);
$a = mysqli_fetch_assoc($id);
$b = $a['id'];
$c = 0;
$l = $num;
$count = 0;
echo "<table>";
while ($l != 0) {
if ($c != 0) {
$a = mysqli_query($conn, "SELECT * FROM car_list WHERE id=$b");
}
if ($c != 0) {
$a = mysqli_fetch_assoc($a);
$b = $a['id'];
}
$car_id = $a['car_id'];
$fuel = $a['fuel'];
$fare = $a['fare'];
$availability = $a['booked'];
if ($count % 2 == 0) {
echo "<tr>";
}
if ($b != 0) {
echo "<td>";
echo "<img src=get.php?id=$b height='100' width='200'/>";
echo "</td>";
echo "<td></td>";
echo "<td>$car_id<br>$fuel<br>$fare rs/km<br>BOOKED=$availability<br>";
echo "<form action='next.php' method='post'><input type='submit' value='RENT'> <input type='hidden' name='access' value='$car_id'></form></td>";
echo "<td></td>";
echo "<td></td>";
echo "<td></td>";
echo "<td></td>";
echo "<td></td>";
echo "<td></td>";
echo "<td></td>";
echo "<td></td>";
echo "<td></td>";
echo "<td></td>";
echo "<td></td>";
echo "<td></td>";
echo "<td></td>";
echo "<td></td>";
echo "<td></td>";
echo "<td></td>";
echo "<td></td>";
echo "<td></td>";
echo "<td></td>";
echo "<td></td>";
echo "<td></td>";
echo "<td></td>";
echo "<td></td>";
echo "<td></td>";
echo "<td></td>";
echo "<td></td>";
echo "<td></td>";
echo "<td></td>";
echo "<td></td>";
echo "<td></td>";
echo "<td></td>";
echo "<td></td>";
echo "<td></td>";
echo "<td></td>";
echo "<td></td>";
echo "<td></td>";
echo "<td></td>";
echo "<td></td>";
//$ll=0;
$l = $l - 1;
$count++;
}
if ($count % 2 == 0) {
echo "</tr>";
}
$c = $c + 1;
$b = $b + 1;
}
echo "</table>";
?>
</div>
</body>
</html> |
Markdown | UTF-8 | 578 | 2.78125 | 3 | [] | no_license | # short-url
Link to the application: http://1aa.xyz
node.js application with a connected MongoDB to shorten your URL
# How to run locally
- Create MongoDB database, for example on cloud via https://mongodb.com or locally
- Create .env file
- Add ```MONGODB_URI=url_to_your_database``` to .env file
- Run below:
```sh
$ npm run dev
```
<img alt="GitHub Workflow Status" src="https://img.shields.io/github/workflow/status/mhocio/short-url/Node.js%20CI?style=flat-square"> <img alt="Website" src="https://img.shields.io/website?style=flat-square&url=http%3A%2F%2F1aa.xyz">
|
Markdown | UTF-8 | 21,343 | 2.796875 | 3 | [
"MIT",
"CC-BY-4.0"
] | permissive | ---
title: Azure Cosmos DB Provider - EF Core
description: Documentation for the database provider that allows Entity Framework Core to be used with Azure Cosmos DB.
author: AndriySvyryd
ms.date: 02/12/2023
uid: core/providers/cosmos/index
---
# EF Core Azure Cosmos DB Provider
This database provider allows Entity Framework Core to be used with Azure Cosmos DB. The provider is maintained as part of the [Entity Framework Core Project](https://github.com/dotnet/efcore).
It is strongly recommended to familiarize yourself with the [Azure Cosmos DB documentation](/azure/cosmos-db/introduction) before reading this section.
> [!NOTE]
> This provider only works with Azure Cosmos DB for NoSQL.
## Install
Install the [Microsoft.EntityFrameworkCore.Cosmos NuGet package](https://www.nuget.org/packages/Microsoft.EntityFrameworkCore.Cosmos/).
### [.NET Core CLI](#tab/dotnet-core-cli)
```dotnetcli
dotnet add package Microsoft.EntityFrameworkCore.Cosmos
```
### [Visual Studio](#tab/vs)
```powershell
Install-Package Microsoft.EntityFrameworkCore.Cosmos
```
***
## Get started
> [!TIP]
> You can view this article's [sample on GitHub](https://github.com/dotnet/EntityFramework.Docs/tree/main/samples/core/Cosmos).
As for other providers the first step is to call [UseCosmos](/dotnet/api/Microsoft.EntityFrameworkCore.CosmosDbContextOptionsExtensions.UseCosmos):
[!code-csharp[Configuration](../../../../samples/core/Cosmos/ModelBuilding/OrderContext.cs?name=Configuration)]
> [!WARNING]
> The endpoint and key are hardcoded here for simplicity, but in a production app these should be [stored securely](/aspnet/core/security/app-secrets#secret-manager). See [Connecting and authenticating](xref:core/providers/cosmos/index#connecting-and-authenticating) for different ways to connect to Azure Cosmos DB.
In this example `Order` is a simple entity with a reference to the [owned type](xref:core/modeling/owned-entities) `StreetAddress`.
[!code-csharp[Order](../../../../samples/core/Cosmos/ModelBuilding/Order.cs?name=Order)]
[!code-csharp[StreetAddress](../../../../samples/core/Cosmos/ModelBuilding/StreetAddress.cs?name=StreetAddress)]
Saving and querying data follows the normal EF pattern:
[!code-csharp[HelloCosmos](../../../../samples/core/Cosmos/ModelBuilding/Sample.cs?name=HelloCosmos)]
> [!IMPORTANT]
> Calling [EnsureCreatedAsync](/dotnet/api/Microsoft.EntityFrameworkCore.Storage.IDatabaseCreator.EnsureCreatedAsync) is necessary to create the required containers and insert the [seed data](xref:core/modeling/data-seeding) if present in the model. However `EnsureCreatedAsync` should only be called during deployment, not normal operation, as it may cause performance issues.
## Connecting and authenticating
The Azure Cosmos DB provider for EF Core has multiple overloads of the [UseCosmos](/dotnet/api/Microsoft.EntityFrameworkCore.CosmosDbContextOptionsExtensions.UseCosmos) method. These overloads support the different ways that a connection can be made to the database, and the different ways of ensuring that the connection is secure.
> [!IMPORTANT]
> Make sure to understand [_Secure access to data in Azure Cosmos DB_](/azure/cosmos-db/secure-access-to-data) to understand the security implications and best practices for using each overload of the `UseCosmos` method.
| Connection Mechanism | UseCosmos Overload | More information |
|----------------------------|------------------------------------------------------------------------|-------------------------------------------------------------------------------------------|
| Account endpoint and key | `UseCosmos<DbContext>(accountEndpoint, accountKey, databaseName)` | [Primary/secondary keys](/azure/cosmos-db/secure-access-to-data#primary-keys) |
| Account endpoint and token | `UseCosmos<DbContext>(accountEndpoint, tokenCredential, databaseName)` | [Resource tokens](/azure/cosmos-db/secure-access-to-data#primary-keys) |
| Connection string | `UseCosmos<DbContext>(connectionString, databaseName)` | [Work with account keys and connection strings](/azure/cosmos-db/scripts/cli/common/keys) |
## Queries
### LINQ queries
[EF Core LINQ queries](xref:core/querying/index) can be executed against Azure Cosmos DB in the same way as for other database providers. For example:
<!--
var stringResults = await context.Triangles.Where(
e => e.Name.Length > 4
&& e.Name.Trim().ToLower() != "obtuse"
&& e.Name.TrimStart().Substring(2, 2).Equals("uT", StringComparison.OrdinalIgnoreCase))
.ToListAsync();
-->
[!code-csharp[StringTranslations](../../../../samples/core/Miscellaneous/NewInEFCore6.Cosmos/CosmosQueriesSample.cs?name=StringTranslations)]
> [!NOTE]
> The Azure Cosmos DB provider does not translate the same set of LINQ queries as other providers. See [_Limitations_](xref:core/providers/cosmos/limitations) for more information.
### SQL queries
Queries can also be written [directly in SQL](xref:core/querying/sql-queries). For example:
<!--
var maxAngle = 60;
var results = await context.Triangles.FromSqlRaw(
@"SELECT * FROM root c WHERE c[""Angle1""] <= {0} OR c[""Angle2""] <= {0}", maxAngle)
.ToListAsync();
-->
[!code-csharp[FromSql](../../../../samples/core/Miscellaneous/NewInEFCore6.Cosmos/CosmosQueriesSample.cs?name=FromSql)]
This query results in the following query execution:
```sql
SELECT c
FROM (
SELECT * FROM root c WHERE c["Angle1"] <= @p0 OR c["Angle2"] <= @p0
) c
```
Just like for relational `FromSql` queries, the hand written SQL can be further composed using LINQ operators. For example:
<!--
var maxAngle = 60;
var results = await context.Triangles.FromSqlRaw(
@"SELECT * FROM root c WHERE c[""Angle1""] <= {0} OR c[""Angle2""] <= {0}", maxAngle)
.Where(e => e.InsertedOn <= DateTime.UtcNow)
.Select(e => e.Angle1).Distinct()
.ToListAsync();
-->
[!code-csharp[FromSqlComposed](../../../../samples/core/Miscellaneous/NewInEFCore6.Cosmos/CosmosQueriesSample.cs?name=FromSqlComposed)]
This combination of SQL and LINQ is translated to:
```sql
SELECT DISTINCT c["Angle1"]
FROM (
SELECT * FROM root c WHERE c["Angle1"] <= @p0 OR c["Angle2"] <= @p0
) c
WHERE (c["InsertedOn"] <= GetCurrentDateTime())
```
## Azure Cosmos DB options
It is also possible to configure the Azure Cosmos DB provider with a single connection string and to specify other options to customize the connection:
[!code-csharp[Configuration](../../../../samples/core/Cosmos/ModelBuilding/OptionsContext.cs?name=Configuration)]
> [!TIP]
> The code above shows possible options. It is not intended that these will all be used at the same time! See the [Azure Cosmos DB Options documentation](/dotnet/api/microsoft.azure.cosmos.cosmosclientoptions) for a detailed description of the effect of each option mentioned above.
## Cosmos-specific model customization
By default all entity types are mapped to the same container, named after the derived context (`"OrderContext"` in this case). To change the default container name use [HasDefaultContainer](/dotnet/api/Microsoft.EntityFrameworkCore.CosmosModelBuilderExtensions.HasDefaultContainer):
[!code-csharp[DefaultContainer](../../../../samples/core/Cosmos/ModelBuilding/OrderContext.cs?name=DefaultContainer)]
To map an entity type to a different container use [ToContainer](/dotnet/api/Microsoft.EntityFrameworkCore.CosmosEntityTypeBuilderExtensions.ToContainer):
[!code-csharp[Container](../../../../samples/core/Cosmos/ModelBuilding/OrderContext.cs?name=Container)]
To identify the entity type that a given item represent EF Core adds a discriminator value even if there are no derived entity types. The name and value of the discriminator [can be changed](xref:core/modeling/inheritance).
If no other entity type will ever be stored in the same container the discriminator can be removed by calling [HasNoDiscriminator](/dotnet/api/Microsoft.EntityFrameworkCore.Metadata.Builders.EntityTypeBuilder.HasNoDiscriminator):
[!code-csharp[NoDiscriminator](../../../../samples/core/Cosmos/ModelBuilding/OrderContext.cs?name=NoDiscriminator)]
### Partition keys
By default, EF Core will create containers with the partition key set to `"__partitionKey"` without supplying any value for it when inserting items. But to fully leverage the performance capabilities of Azure Cosmos DB, a [carefully selected partition key](/azure/cosmos-db/partition-data) should be used. It can be configured by calling [HasPartitionKey](/dotnet/api/Microsoft.EntityFrameworkCore.CosmosEntityTypeBuilderExtensions.HasPartitionKey):
[!code-csharp[PartitionKey](../../../../samples/core/Cosmos/ModelBuilding/OrderContext.cs?name=PartitionKey)]
> [!NOTE]
>The partition key property can be of any type as long as it is [converted to string](xref:core/modeling/value-conversions).
Once configured the partition key property should always have a non-null value. A query can be made single-partition by adding a <xref:Microsoft.EntityFrameworkCore.CosmosQueryableExtensions.WithPartitionKey%2A> call.
[!code-csharp[PartitionKey](../../../../samples/core/Cosmos/ModelBuilding/Sample.cs?name=PartitionKey&highlight=14)]
It is generally recommended to add the partition key to the primary key as that best reflects the server semantics and allows some optimizations, for example in `FindAsync`.
### Provisioned throughput
If you use EF Core to create the Azure Cosmos DB database or containers you can configure [provisioned throughput](/azure/cosmos-db/set-throughput) for the database by calling <xref:Microsoft.EntityFrameworkCore.CosmosModelBuilderExtensions.HasAutoscaleThroughput%2A?displayProperty=nameWithType> or <xref:Microsoft.EntityFrameworkCore.CosmosModelBuilderExtensions.HasManualThroughput%2A?displayProperty=nameWithType>. For example:
<!--
modelBuilder.HasManualThroughput(2000);
modelBuilder.HasAutoscaleThroughput(4000);
-->
[!code-csharp[ModelThroughput](../../../../samples/core/Miscellaneous/NewInEFCore6.Cosmos/CosmosModelConfigurationSample.cs?name=ModelThroughput)]
To configure provisioned throughput for a container call <xref:Microsoft.EntityFrameworkCore.CosmosEntityTypeBuilderExtensions.HasAutoscaleThroughput%2A?displayProperty=nameWithType> or <xref:Microsoft.EntityFrameworkCore.CosmosEntityTypeBuilderExtensions.HasManualThroughput%2A?displayProperty=nameWithType>. For example:
<!--
modelBuilder.Entity<Family>(
entityTypeBuilder =>
{
entityTypeBuilder.HasManualThroughput(5000);
entityTypeBuilder.HasAutoscaleThroughput(3000);
});
-->
[!code-csharp[EntityTypeThroughput](../../../../samples/core/Miscellaneous/NewInEFCore6.Cosmos/CosmosModelConfigurationSample.cs?name=EntityTypeThroughput)]
### Time-to-live
Entity types in the Azure Cosmos DB model can now be configured with a default time-to-live. For example:
```csharp
modelBuilder.Entity<Hamlet>().HasDefaultTimeToLive(3600);
```
Or, for the analytical store:
```csharp
modelBuilder.Entity<Hamlet>().HasAnalyticalStoreTimeToLive(3600);
```
Time-to-live for individual entities can be set using a property mapped to "ttl" in the JSON document. For example:
<!--
modelBuilder.Entity<Village>()
.HasDefaultTimeToLive(3600)
.Property(e => e.TimeToLive)
.ToJsonProperty("ttl");
-->
[!code-csharp[TimeToLiveProperty](../../../../samples/core/Miscellaneous/NewInEFCore6.Cosmos/CosmosModelConfigurationSample.cs?name=TimeToLiveProperty)]
> [!NOTE]
> A default time-to-live must configured on the entity type for the "ttl" to have any effect. See [_Time to Live (TTL) in Azure Cosmos DB_](/azure/cosmos-db/nosql/time-to-live) for more information.
The time-to-live property is then set before the entity is saved. For example:
<!--
var village = new Village { Id = "DN41", Name = "Healing", TimeToLive = 60 };
context.Add(village);
await context.SaveChangesAsync();
-->
[!code-csharp[SetTtl](../../../../samples/core/Miscellaneous/NewInEFCore6.Cosmos/CosmosModelConfigurationSample.cs?name=SetTtl)]
The time-to-live property can be a [shadow property](xref:core/modeling/shadow-properties) to avoid polluting the domain entity with database concerns. For example:
<!--
modelBuilder.Entity<Hamlet>()
.HasDefaultTimeToLive(3600)
.Property<int>("TimeToLive")
.ToJsonProperty("ttl");
-->
[!code-csharp[TimeToLiveShadowProperty](../../../../samples/core/Miscellaneous/NewInEFCore6.Cosmos/CosmosModelConfigurationSample.cs?name=TimeToLiveShadowProperty)]
The shadow time-to-live property is then set by [accessing the tracked entity](xref:core/change-tracking/entity-entries). For example:
<!--
var hamlet = new Hamlet { Id = "DN37", Name = "Irby" };
context.Add(hamlet);
context.Entry(hamlet).Property("TimeToLive").CurrentValue = 60;
await context.SaveChangesAsync();
-->
[!code-csharp[SetTtlShadow](../../../../samples/core/Miscellaneous/NewInEFCore6.Cosmos/CosmosModelConfigurationSample.cs?name=SetTtlShadow)]
## Embedded entities
> [!NOTE]
> Related entity types are configured as owned by default. To prevent this for a specific entity type call <xref:Microsoft.EntityFrameworkCore.ModelBuilder.Entity%2A?displayProperty=nameWithType>.
For Azure Cosmos DB, owned entities are embedded in the same item as the owner. To change a property name use [ToJsonProperty](/dotnet/api/Microsoft.EntityFrameworkCore.CosmosEntityTypeBuilderExtensions.ToJsonProperty):
[!code-csharp[PropertyNames](../../../../samples/core/Cosmos/ModelBuilding/OrderContext.cs?name=PropertyNames)]
With this configuration the order from the example above is stored like this:
```json
{
"Id": 1,
"PartitionKey": "1",
"TrackingNumber": null,
"id": "1",
"Address": {
"ShipsToCity": "London",
"ShipsToStreet": "221 B Baker St"
},
"_rid": "6QEKAM+BOOABAAAAAAAAAA==",
"_self": "dbs/6QEKAA==/colls/6QEKAM+BOOA=/docs/6QEKAM+BOOABAAAAAAAAAA==/",
"_etag": "\"00000000-0000-0000-683c-692e763901d5\"",
"_attachments": "attachments/",
"_ts": 1568163674
}
```
Collections of owned entities are embedded as well. For the next example we'll use the `Distributor` class with a collection of `StreetAddress`:
[!code-csharp[Distributor](../../../../samples/core/Cosmos/ModelBuilding/Distributor.cs?name=Distributor)]
The owned entities don't need to provide explicit key values to be stored:
[!code-csharp[OwnedCollection](../../../../samples/core/Cosmos/ModelBuilding/Sample.cs?name=OwnedCollection)]
They will be persisted in this way:
```json
{
"Id": 1,
"Discriminator": "Distributor",
"id": "Distributor|1",
"ShippingCenters": [
{
"City": "Phoenix",
"Street": "500 S 48th Street"
},
{
"City": "Anaheim",
"Street": "5650 Dolly Ave"
}
],
"_rid": "6QEKANzISj0BAAAAAAAAAA==",
"_self": "dbs/6QEKAA==/colls/6QEKANzISj0=/docs/6QEKANzISj0BAAAAAAAAAA==/",
"_etag": "\"00000000-0000-0000-683c-7b2b439701d5\"",
"_attachments": "attachments/",
"_ts": 1568163705
}
```
Internally EF Core always needs to have unique key values for all tracked entities. The primary key created by default for collections of owned types consists of the foreign key properties pointing to the owner and an `int` property corresponding to the index in the JSON array. To retrieve these values entry API could be used:
[!code-csharp[ImpliedProperties](../../../../samples/core/Cosmos/ModelBuilding/Sample.cs?name=ImpliedProperties)]
> [!TIP]
> When necessary the default primary key for the owned entity types can be changed, but then key values should be provided explicitly.
### Collections of primitive types
Collections of supported primitive types, such as `string` and `int`, are discovered and mapped automatically. Supported collections are all types that implement <xref:System.Collections.Generic.IReadOnlyList%601> or <xref:System.Collections.Generic.IReadOnlyDictionary%602>. For example, consider this entity type:
<!--
public class Book
{
public Guid Id { get; set; }
public string Title { get; set; }
public IList<string> Quotes { get; set; }
public IDictionary<string, string> Notes { get; set; }
}
-->
[!code-csharp[BookEntity](../../../../samples/core/Miscellaneous/NewInEFCore6.Cosmos/CosmosPrimitiveTypesSample.cs?name=BookEntity)]
Both the list and the dictionary can be populated and inserted into the database in the normal way:
<!--
using var context = new BooksContext();
var book = new Book
{
Title = "How It Works: Incredible History",
Quotes = new List<string>
{
"Thomas (Tommy) Flowers was the British engineer behind the design of the Colossus computer.",
"Invented originally for Guinness, plastic widgets are nitrogen-filled spheres.",
"For 20 years after its introduction in 1979, the Walkman dominated the personal stereo market."
},
Notes = new Dictionary<string, string>
{
{ "121", "Fridges" },
{ "144", "Peter Higgs" },
{ "48", "Saint Mark's Basilica" },
{ "36", "The Terracotta Army" }
}
};
context.Add(book);
context.SaveChanges();
-->
[!code-csharp[Insert](../../../../samples/core/Miscellaneous/NewInEFCore6.Cosmos/CosmosPrimitiveTypesSample.cs?name=Insert)]
This results in the following JSON document:
```json
{
"Id": "0b32283e-22a8-4103-bb4f-6052604868bd",
"Discriminator": "Book",
"Notes": {
"36": "The Terracotta Army",
"48": "Saint Mark's Basilica",
"121": "Fridges",
"144": "Peter Higgs"
},
"Quotes": [
"Thomas (Tommy) Flowers was the British engineer behind the design of the Colossus computer.",
"Invented originally for Guinness, plastic widgets are nitrogen-filled spheres.",
"For 20 years after its introduction in 1979, the Walkman dominated the personal stereo market."
],
"Title": "How It Works: Incredible History",
"id": "Book|0b32283e-22a8-4103-bb4f-6052604868bd",
"_rid": "t-E3AIxaencBAAAAAAAAAA==",
"_self": "dbs/t-E3AA==/colls/t-E3AIxaenc=/docs/t-E3AIxaencBAAAAAAAAAA==/",
"_etag": "\"00000000-0000-0000-9b50-fc769dc901d7\"",
"_attachments": "attachments/",
"_ts": 1630075016
}
```
These collections can then be updated, again in the normal way:
<!--
book.Quotes.Add("Pressing the emergency button lowered the rods again.");
book.Notes["48"] = "Chiesa d'Oro";
context.SaveChanges();
-->
[!code-csharp[Updates](../../../../samples/core/Miscellaneous/NewInEFCore6.Cosmos/CosmosPrimitiveTypesSample.cs?name=Updates)]
Limitations:
* Only dictionaries with string keys are supported
* Querying into the contents of primitive collections is not currently supported. Vote for [#16926](https://github.com/dotnet/efcore/issues/16926), [#25700](https://github.com/dotnet/efcore/issues/25700), and [#25701](https://github.com/dotnet/efcore/issues/25701) if these features are important to you.
## Working with disconnected entities
Every item needs to have an `id` value that is unique for the given partition key. By default EF Core generates the value by concatenating the discriminator and the primary key values, using '|' as a delimiter. The key values are only generated when an entity enters the `Added` state. This might pose a problem when [attaching entities](xref:core/saving/disconnected-entities) if they don't have an `id` property on the .NET type to store the value.
To work around this limitation one could create and set the `id` value manually or mark the entity as added first, then changing it to the desired state:
[!code-csharp[Attach](../../../../samples/core/Cosmos/ModelBuilding/Sample.cs?highlight=4&name=Attach)]
This is the resulting JSON:
```json
{
"Id": 1,
"Discriminator": "Distributor",
"id": "Distributor|1",
"ShippingCenters": [
{
"City": "Phoenix",
"Street": "500 S 48th Street"
}
],
"_rid": "JBwtAN8oNYEBAAAAAAAAAA==",
"_self": "dbs/JBwtAA==/colls/JBwtAN8oNYE=/docs/JBwtAN8oNYEBAAAAAAAAAA==/",
"_etag": "\"00000000-0000-0000-9377-d7a1ae7c01d5\"",
"_attachments": "attachments/",
"_ts": 1572917100
}
```
## Optimistic concurrency with eTags
To configure an entity type to use [optimistic concurrency](xref:core/saving/concurrency) call <xref:Microsoft.EntityFrameworkCore.CosmosEntityTypeBuilderExtensions.UseETagConcurrency%2A>. This call will create an `_etag` property in [shadow state](xref:core/modeling/shadow-properties) and set it as the concurrency token.
[!code-csharp[Main](../../../../samples/core/Cosmos/ModelBuilding/OrderContext.cs?name=ETag)]
To make it easier to resolve concurrency errors you can map the eTag to a CLR property using <xref:Microsoft.EntityFrameworkCore.CosmosPropertyBuilderExtensions.IsETagConcurrency%2A>.
[!code-csharp[Main](../../../../samples/core/Cosmos/ModelBuilding/OrderContext.cs?name=ETagProperty)]
|
Java | UTF-8 | 9,094 | 2.328125 | 2 | [
"LicenseRef-scancode-free-unknown",
"Apache-2.0",
"LicenseRef-scancode-public-domain"
] | permissive | package io.opensphere.filterbuilder2.editor.common;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import javax.swing.BorderFactory;
import javax.swing.Box;
import javax.swing.DefaultListCellRenderer;
import javax.swing.JComboBox;
import javax.swing.JComponent;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JTextField;
import io.opensphere.core.util.ChangeListener;
import io.opensphere.core.util.ObservableValue;
import io.opensphere.core.util.swing.GridBagPanel;
import io.opensphere.core.util.swing.input.controller.AbstractController;
import io.opensphere.core.util.swing.input.controller.ControllerFactory;
import io.opensphere.core.util.swing.input.model.PropertyChangeEvent;
import io.opensphere.core.util.swing.input.model.PropertyChangeEvent.Property;
import io.opensphere.core.util.swing.input.model.PropertyChangeListener;
import io.opensphere.core.util.swing.input.model.ViewModel;
import io.opensphere.filterbuilder2.common.Constants;
import io.opensphere.filterbuilder2.editor.model.CriterionModel;
import io.opensphere.mantle.data.impl.specialkey.TimeKey;
/**
* The panel for editing a single criterion.
*/
public class CriterionEditorPanel extends GridBagPanel
{
/** The serialVersionUID. */
private static final long serialVersionUID = 1L;
/** The height used for all components so that they match. */
private static int ourComponentHeight;
/** The model. */
private final CriterionModel myModel;
/** The number of columns for text fields. */
private final int myTextColumns;
/** The key listener. */
private KeyListener myKeyListener;
/** The field controller. */
private AbstractController<?, ? extends ViewModel<?>, ? extends JComponent> myFieldController;
/** The operator controller. */
private AbstractController<?, ? extends ViewModel<?>, ? extends JComponent> myOperatorController;
/** The value controller. */
private AbstractController<?, ? extends ViewModel<?>, ? extends JComponent> myValueController;
/** The max value controller. */
private AbstractController<?, ? extends ViewModel<?>, ? extends JComponent> myMaxValueController;
/** Whether the current field is a time field. */
private boolean myIsTimeField;
/**
* Sets up the combo box.
*
* @param component the component
* @param maxWidth the maximum width
* @param hasScrollbar if the component should get a scrollbar
* @return the modified component
*/
private static JComponent setupComboBox(JComponent component, int maxWidth, boolean hasScrollbar)
{
if (component instanceof JComboBox)
{
JComboBox<?> comboBox = (JComboBox<?>)component;
if (hasScrollbar)
{
comboBox.setMaximumRowCount(10);
}
else
{
comboBox.setMaximumRowCount(comboBox.getItemCount());
}
comboBox.setRenderer(setupPaddingRenderer(3, 0, 3, 0));
ourComponentHeight = comboBox.getPreferredSize().height;
}
Dimension size = component.getPreferredSize();
if (size.width > maxWidth)
{
size.width = maxWidth;
component.setPreferredSize(size);
}
return component;
}
/**
* Set up the padding renderer for extra space between list items.
*
* @param top the top padding in pixels
* @param left the left padding in pixels
* @param bottom the bottom padding in pixels
* @param right the right padding in pixels
* @return the padding renderer
*/
private static DefaultListCellRenderer setupPaddingRenderer(int top, int left, int bottom, int right)
{
return new DefaultListCellRenderer()
{
private static final long serialVersionUID = 1L;
@Override
public Component getListCellRendererComponent(JList<?> list, Object value, int index, boolean isSelected,
boolean cellHasFocus)
{
JLabel label = (JLabel)super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus);
label.setBorder(BorderFactory.createEmptyBorder(top, left, bottom, right));
return label;
}
};
}
/**
* Constructor.
*
* @param model the model
* @param textColumns the number of columns for text fields
*/
public CriterionEditorPanel(CriterionModel model, int textColumns)
{
super();
myModel = model;
myTextColumns = textColumns;
buildPanel();
myIsTimeField = model.getSpecialType() instanceof TimeKey;
model.getField().addListener(new ChangeListener<String>()
{
@Override
public void changed(ObservableValue<? extends String> observable, String oldValue, String newValue)
{
boolean isTimeField = myModel.getSpecialType() instanceof TimeKey;
if (myIsTimeField != isTimeField)
{
myIsTimeField = isTimeField;
rebuild();
}
}
});
model.getCriterionMaxValue().addPropertyChangeListener(new PropertyChangeListener()
{
@Override
public void stateChanged(PropertyChangeEvent e)
{
if (e.getProperty() == Property.VISIBLE)
{
revalidate();
}
}
});
}
@Override
public void addNotify()
{
super.addNotify();
myValueController.getView().requestFocusInWindow();
}
/**
* Closes the controllers in the panel.
*/
public void close()
{
if (myFieldController != null)
{
myFieldController.close();
}
if (myOperatorController != null)
{
myOperatorController.close();
}
if (myValueController != null)
{
myValueController.close();
}
if (myMaxValueController != null)
{
myMaxValueController.close();
}
}
/**
* Rebuilds the panel.
*/
public void rebuild()
{
close();
removeAll();
buildPanel();
revalidate();
}
/**
* Sets the key listener.
*
* @param keyListener the new key listener
*/
public void setKeyListener(KeyListener keyListener)
{
myKeyListener = keyListener;
}
/**
* Builds the panel.
*/
private void buildPanel()
{
myFieldController = ControllerFactory.createController(myModel.getField(), null, null);
if (myFieldController != null)
{
fillNone();
setInsets(Constants.INSET, Constants.INSET, Constants.INSET, Constants.INSET);
add(setupComboBox(myFieldController.getView(), 180, true));
}
myOperatorController = ControllerFactory.createController(myModel.getOperator(), null, null);
if (myOperatorController != null)
{
setInsets(Constants.INSET, 0, Constants.INSET, Constants.INSET);
add(setupComboBox(myOperatorController.getView(), 180, false));
}
myValueController = ControllerFactory.createController(myModel.getCriterionValue(), null, null);
if (myValueController != null)
{
fillHorizontal();
add(setupTextField(myValueController.getView(), myTextColumns));
}
myMaxValueController = ControllerFactory.createController(myModel.getCriterionMaxValue(), null, null);
if (myMaxValueController != null)
{
fillHorizontal();
add(setupTextField(myMaxValueController.getView(), myTextColumns));
}
fillHorizontal();
setWeightx(.00001);
add(Box.createHorizontalGlue(), getGBC());
}
/**
* Sets up the text field.
*
* @param component the component
* @param textColumns the number of columns for the text field
* @return the modified component
*/
private JComponent setupTextField(JComponent component, int textColumns)
{
if (component instanceof JTextField)
{
((JTextField)component).setColumns(textColumns);
}
component.addKeyListener(new KeyAdapter()
{
@Override
public void keyPressed(KeyEvent e)
{
if (e.getKeyCode() == KeyEvent.VK_ENTER)
{
if (myKeyListener != null)
{
myKeyListener.keyPressed(e);
}
e.consume();
}
}
});
component.setPreferredSize(new Dimension(component.getPreferredSize().width, ourComponentHeight));
return component;
}
}
|
PHP | UTF-8 | 5,055 | 2.5625 | 3 | [] | no_license | <?php
lmb_require('src/service/social_photo_source/BaseSocialPhotoSource.class.php');
class InstagramPhotoSource extends BaseSocialPhotoSource
{
protected $uid;
protected $token;
function __construct(User $user)
{
parent::__construct($user);
$this->uid = $user->instagram_uid;
$this->token = $user->instagram_token;
}
function getLoginUrl($redirect_url)
{
return "https://api.instagram.com/oauth/authorize/?client_id={$this->app_key}&redirect_uri=$redirect_url&response_type=code";
}
function login($code, $redirect_url)
{
$request = new HttpRequest('https://api.instagram.com/oauth/access_token', HTTP_METH_POST);
$request->setPostFields([
'client_id' => $this->app_key,
'client_secret' => $this->app_secret,
'grant_type' => 'authorization_code',
'redirect_uri' => $redirect_url,
'code' => $code
]);
$answer = $request->send();
if($answer->getResponseCode() != 200)
{
$body = json_decode($answer->getBody());
$message = (property_exists($body, 'meta')) ? $body->meta->error_message : $body->error_message;
lmbToolkit::instance()->getLog()->error('Instagram API answer: '.$message);
return null;
}
$info = json_decode($answer->getBody());
$this->user->instagram_uid = $info->user->id;
$this->user->instagram_token = $info->access_token;
return $this->user->save();
}
function getUserInfo()
{
if(!$this->user->instagram_uid)
throw new lmbException("Instagram info not found for user #".$this->user->id);
$url = "https://api.instagram.com/v1/users/{$this->uid}/?access_token={$this->token}";
$answer = (new HttpRequest($url))->send();
if($answer->getResponseCode() != 200)
throw new lmbException('Instagram API answer: '.json_decode($answer->getBody())->meta->error_message);
$raw_info = json_decode($answer->getBody())->data;
return [
'id' => $raw_info->id,
'image' => $raw_info->profile_picture,
'image_width' => 150,
'image_height' => 150,
'name' => $raw_info->username,
'photos_count' => $raw_info->counts->media
];
}
function getPhotos($from_stamp = null, $to_stamp = null)
{
if(!$this->user->instagram_uid)
throw new lmbException("Instagram info not found for user #".$this->user->id);
$url = "https://api.instagram.com/v1/users/{$this->uid}/media/recent/?access_token={$this->token}";
$url .= '&count='.self::LIMIT;
$url .= "&max_timestamp=".$from_stamp;
if($to_stamp)
$url .= "&min_timestamp=".($to_stamp + 1);
$answer = (new HttpRequest($url))->send();
if($answer->getResponseCode() != 200)
{
lmbToolkit::instance()->getLog()->warn('Instagram API answer: '.$answer->getBody());
return [];
}
$raw_info = json_decode($answer->getBody());
$url = $raw_info->pagination && property_exists($raw_info, 'next_url') ? $raw_info->pagination->next_url : null;
$result = [];
foreach($raw_info->data as $raw_photo)
{
$latitude = $raw_photo->location && property_exists($raw_photo->location, 'latitude')
? $raw_photo->location->latitude : null;
$longitude = $raw_photo->location && property_exists($raw_photo->location, 'longitude')
? $raw_photo->location->longitude : null;
$location = $raw_photo->location && property_exists($raw_photo->location, 'name')
? $raw_photo->location->name : null;
$one_result = [
'id' => $raw_photo->id,
'title' => $raw_photo->caption ? $raw_photo->caption->text : '',
'description' => '',
'location_latitude' => $latitude,
'location_longitude' => $longitude,
'location_name' => $location,
'tags' => $raw_photo->tags,
'time' => (int) $raw_photo->created_time,
];
// instagram bug https://groups.google.com/forum/?fromgroups=#!topic/instagram-api-developers/ncB18unjqyg
if(property_exists($raw_photo->images->standard_resolution, 'url'))
{
$one_result['image'] = $raw_photo->images->standard_resolution->url;
$one_result['image_width'] = $raw_photo->images->standard_resolution->width;
$one_result['image_height'] = $raw_photo->images->standard_resolution->height;
}
else
{
$one_result['image'] = $raw_photo->images->standard_resolution;
$one_result['image_width'] = null;
$one_result['image_height'] = null;
}
if(property_exists($raw_photo->images->thumbnail, 'url'))
{
$one_result['thumb'] = $raw_photo->images->thumbnail->url;
$one_result['thumb_width'] = $raw_photo->images->thumbnail->width;
$one_result['thumb_height'] = $raw_photo->images->thumbnail->height;
}
else
{
$one_result['thumb'] = $raw_photo->images->standard_resolution;
$one_result['thumb_width'] = null;
$one_result['thumb_height'] = null;
}
$result[] = $one_result;
}
return $result;
}
function logout()
{
if(!$this->user->instagram_uid)
throw new lmbException("Instagram info not found for user #".$this->user->id);
$this->user->instagram_uid = '';
$this->user->instagram_token = '';
return $this->user->save();
}
protected function getConfig()
{
return lmbToolkit::instance()->getConf('common')->instagram;
}
}
|
Markdown | UTF-8 | 3,811 | 2.796875 | 3 | [] | no_license | # UserProfile.UserApi
All URIs are relative to *http://userprofile.qantas.io/v1*
Method | HTTP request | Description
------------- | ------------- | -------------
[**addUser**](UserApi.md#addUser) | **POST** /user | Add a new user
[**getUser**](UserApi.md#getUser) | **GET** /user | Get an existing user profile
[**updateUser**](UserApi.md#updateUser) | **PUT** /user | Update an existing user
<a name="addUser"></a>
# **addUser**
> SuccessResponse addUser(body)
Add a new user
Add a new user
### Example
```javascript
var UserProfile = require('user_profile');
var defaultClient = UserProfile.ApiClient.instance;
// Configure OAuth2 access token for authorization: user_auth
var user_auth = defaultClient.authentications['user_auth'];
user_auth.accessToken = 'YOUR ACCESS TOKEN';
var apiInstance = new UserProfile.UserApi();
var body = new UserProfile.User(); // User | User object that needs to be added
var callback = function(error, data, response) {
if (error) {
console.error(error);
} else {
console.log('API called successfully. Returned data: ' + data);
}
};
apiInstance.addUser(body, callback);
```
### Parameters
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**body** | [**User**](User.md)| User object that needs to be added |
### Return type
[**SuccessResponse**](SuccessResponse.md)
### Authorization
[user_auth](../README.md#user_auth)
### HTTP request headers
- **Content-Type**: application/json
- **Accept**: application/json
<a name="getUser"></a>
# **getUser**
> User getUser(body)
Get an existing user profile
### Example
```javascript
var UserProfile = require('user_profile');
var defaultClient = UserProfile.ApiClient.instance;
// Configure OAuth2 access token for authorization: user_auth
var user_auth = defaultClient.authentications['user_auth'];
user_auth.accessToken = 'YOUR ACCESS TOKEN';
var apiInstance = new UserProfile.UserApi();
var body = new UserProfile.User(); // User | User object that needs to be updated
var callback = function(error, data, response) {
if (error) {
console.error(error);
} else {
console.log('API called successfully. Returned data: ' + data);
}
};
apiInstance.getUser(body, callback);
```
### Parameters
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**body** | [**User**](User.md)| User object that needs to be updated |
### Return type
[**User**](User.md)
### Authorization
[user_auth](../README.md#user_auth)
### HTTP request headers
- **Content-Type**: application/json
- **Accept**: application/json
<a name="updateUser"></a>
# **updateUser**
> SuccessResponse updateUser(body)
Update an existing user
Update an existing user
### Example
```javascript
var UserProfile = require('user_profile');
var defaultClient = UserProfile.ApiClient.instance;
// Configure OAuth2 access token for authorization: user_auth
var user_auth = defaultClient.authentications['user_auth'];
user_auth.accessToken = 'YOUR ACCESS TOKEN';
var apiInstance = new UserProfile.UserApi();
var body = new UserProfile.User(); // User | User object that needs to be updated
var callback = function(error, data, response) {
if (error) {
console.error(error);
} else {
console.log('API called successfully. Returned data: ' + data);
}
};
apiInstance.updateUser(body, callback);
```
### Parameters
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**body** | [**User**](User.md)| User object that needs to be updated |
### Return type
[**SuccessResponse**](SuccessResponse.md)
### Authorization
[user_auth](../README.md#user_auth)
### HTTP request headers
- **Content-Type**: application/json
- **Accept**: application/json
|
C | UTF-8 | 2,377 | 2.984375 | 3 | [] | no_license | /* ************************************************************************** */
/* */
/* ::: :::::::: */
/* print_arg.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: lmallado <marvin@42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2020/07/13 12:58:15 by lmallado #+# #+# */
/* Updated: 2020/07/13 12:58:20 by lmallado ### ########.fr */
/* */
/* ************************************************************************** */
#include "../includes/printf.h"
static void print_sym(char *format, t_counter *counter)
{
while (format[counter->iterator] != '%' &&
format[counter->iterator] != '\0')
{
if (format[counter->iterator] != ' ')
ft_putchar_fd(format[counter->iterator], 1);
counter->iterator++;
counter->size++;
}
}
static int pass_arg(char *format, int i)
{
while (is_right_arg(format[i]) != 1 &&
format[i] != '\0')
i++;
if (format[i] != '\0')
i++;
return (i);
}
static int print(t_flags flag, va_list ap)
{
int size;
if (flag.arg_type == 'c')
size = print_char(va_arg(ap, int), flag);
if (flag.arg_type == 's')
size = print_string(va_arg(ap, char *), flag);
if (flag.arg_type == '%')
size = print_percent(flag);
if (flag.arg_type == 'd' || flag.arg_type == 'i')
size = print_digit(va_arg(ap, int), flag);
if (flag.arg_type == 'u')
size = print_unsigned_dec(va_arg(ap, unsigned int), flag);
if (flag.arg_type == 'p')
size = print_p(va_arg(ap, unsigned long long), flag);
if (flag.arg_type == 'x' || flag.arg_type == 'X')
size = print_x(va_arg(ap, unsigned int), flag);
return (size);
}
t_counter print_arg(t_flags flag, va_list ap,
char *format, t_counter counter)
{
int size;
size = 0;
counter.iterator++;
if (flag.arg_type == 0)
print_sym(format, &counter);
else
{
size = print(flag, ap);
if (size == -1)
counter.size = -1;
else
counter.size += size;
counter.iterator = pass_arg(format, counter.iterator);
}
return (counter);
}
|
C++ | UTF-8 | 986 | 2.84375 | 3 | [] | no_license | #include "navcontext.h"
NavContext::NavContext(QObject *parent) : QObject(parent), m_history()
{
m_history.push(PageContext());
}
const PageContext &NavContext::currentPage() const
{
return m_history.top();
}
void NavContext::replacePage(const QString& newCurrent)
{
return replacePage(PageContext(newCurrent));
}
void NavContext::gotoPage(const QString& next)
{
return gotoPage(PageContext(next));
}
void NavContext::replacePage(const PageContext& newCurrent)
{
if(currentPage() != newCurrent)
emit routeChanged(newCurrent);
m_history.pop();
m_history.push(newCurrent);
}
void NavContext::gotoPage(const PageContext& next)
{
if(currentPage() == next) { return; }
m_history.push(next);
emit routeChanged(next);
}
void NavContext::backPage()
{
if(history().length() <= 1) { return; }
m_history.pop();
emit routeChanged(currentPage());
}
const QStack<PageContext> &NavContext::history() const
{
return m_history;
}
|
Java | UTF-8 | 1,062 | 2.21875 | 2 | [] | no_license | package com.zr.action.ems;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.zr.service.ExamService;
import com.zr.service.impl.ExamServiceImpl;
import net.sf.json.JSONObject;
public class IssueExamAction extends HttpServlet{
ExamService es = new ExamServiceImpl();
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
this.doPost(req, resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
req.setCharacterEncoding("utf-8");
resp.setCharacterEncoding("utf-8");
int currentExamId = (int)req.getSession().getAttribute("currentExamId");
boolean result = es.issueExam(currentExamId);
JSONObject json = new JSONObject();
json.put("result", result);
resp.getWriter().write(json.toString());
}
}
|
C++ | UTF-8 | 5,736 | 3.53125 | 4 | [] | no_license |
#include <iostream>
#include <string>
using namespace std;
class Package{
public:
Package(){
// cout << "Package is created at " << this << endl;
}
Package(string desc, int wt):description(desc){
// cout << "Package is created at " << this << endl;
setWeight(wt);
}
~Package(){
// cout << "Package is destroyed at " << this << endl;
}
void setDescription(string desc){
this->description = desc;
}
string getDescription() const{
return this->description;
}
void setWeight(int wt){
if(wt < 0)
cout << "Weight can not be negative" << endl;
if(wt > 1000)
cout << "This is too heavy for drones to deliver!!" << endl;
this->weight = wt;
}
int getWeight() const{
return this->weight;
}
bool operator>(const Package& pkg) const{
if(this->weight > pkg.getWeight())
return true;
else
return false;
}
bool operator<(const Package& pkg) const{
if(this->weight > pkg.getWeight())
return false;
else
return true;
}
private:
int weight = 0;
string description = "";
};
class Node{
public:
Node(Package& pkg):next(nullptr){
this->data = pkg;
cout << "Node Constr Data contains package of " << &this->data << endl;
}
Node* getNext() const{
return this->next;
}
void setNext(Node* next){
this->next = next;
}
Package getData() const{
return this->data;
}
void setData(Package& pkg){
this->data = pkg;
}
private:
Node* next;
Package data;
};
class DeliveryManager{
public:
DeliveryManager(){}
DeliveryManager(Package& pkg){
add(pkg);
}
~DeliveryManager(){
Node* cur = head;
while(cur != nullptr){
Node* nodeToRemove = cur;
cur = cur->getNext();
delete nodeToRemove;
}
};
void add(Package& pkg){
Node* newNode = new Node(pkg);
if(head == nullptr){
head = newNode;
}
else{
newNode->setNext(head);
head = newNode;
}
updateDroneCounts(pkg);
numOfPackages++;
};
void sort(){
// if(numOfPackages >= 2)
// sort(numOfPackages-1);
bool swapped = false;
do{
swapped = false;
sort_InClassMethod(head, swapped);
}while(swapped);
}
Package search(Package& pkg);
void print(){
Node* cur = head;
while(cur != nullptr){
Package p = cur->getData();
cout << p.getDescription() << ": " << p.getWeight() << endl;
p.setDescription("Fake Package");
cur = cur->getNext();
}
}
private:
Node* head = nullptr;
int numOfPackages = 0;
int numOfDronesNeeded = 0;
int totalPounds = 0;
void updateDroneCounts(Package& pkg){
totalPounds += pkg.getWeight();
numOfDronesNeeded = totalPounds / 10 + 1;
}
void sort(int cnt){
if(cnt == 0)
return;
Node* cur = head;
Node* prev = nullptr;
Node* next = cur->getNext();
for(int i = 0; i < cnt; i++){
if(cur->getData().getWeight() < next->getData().getWeight()){
swap(prev,cur,next);
}
prev = cur;
cur = next;
next = next->getNext();
}
sort(cnt-1);
}
void sort_InClassMethod(Node* cur, bool& swapped){
if(cur->getNext() == nullptr){
return;
}
sort_InClassMethod(cur->getNext(),swapped);
if(cur->getData() > cur->getNext()->getData()){
Package tmp = cur->getNext()->getData();
Package curPkg = cur->getData();
cur->getNext()->setData(curPkg);
cur->setData(tmp);
swapped = true;
}
}
void swap(Node* &prev, Node* &cur, Node* &next){
if(prev != nullptr){
prev->setNext(next);
}else{
head = next;
}
cur->setNext(next->getNext());
next->setNext(cur);
Node* tmp = next;
next = cur;
cur = tmp;
}
};
bool isEvenNumber(int num)
{
for (int i = 0; i < num; i++)
{
num += i;
}
return true;
}
class base{
public:
virtual void method1(){
cout << "Base Class" << endl;
}
};
class derived: public base{
public:
void method1 () {
cout << "derived class" << endl;
}
};
int main(){
base* b = new derived();
b->method1();
// isEvenNumber(5);
Package pkg1("Package 1", 5);
Package pkg2("Package 2", 7);
Package pkg3("Package 3", 15);
Package pkg4("Package 4", 3);
Package pkg5("Package 5", 12);
// bool pkg1_heavier = pkg1 > pkg2;
DeliveryManager dm;
dm.add(pkg5);
dm.add(pkg4);
dm.add(pkg3);
dm.add(pkg2);
dm.add(pkg1);
dm.print();
dm.sort();
dm.print();
} |
Rust | UTF-8 | 6,072 | 2.6875 | 3 | [
"BSD-3-Clause"
] | permissive |
#[macro_use]
extern crate clap;
use std::io::BufReader;
use arcstar::sae_types::*;
use eventcam_tracker::tracker::FeatureTracker;
use eventcam_converter::conversion;
use std::fs::create_dir_all;
use std::path::Path;
/// process an event file into a set of corners
/// # Arguments
///
/// * `src_path` - Path to the input data file, eg `./data/events.dat`
/// * `img_w` - Width of the camera input, in pixels
/// * `img_h` - Height of the camera input, in pixels
/// * `timebase` - A start time for the event file processing (seconds from some absolute zero)
/// * `timescale` - Seconds per SaeTime tick
/// * `max_events` - A limit to the number of events to process, or 0 if no limit
/// * `render_events` - Should we render input events to an image file?
/// * `render_sae` - Should we render the Surface of Active Events to an image file?
/// * `render_corners` - Should we render detected corners (features) to an image file?
/// * `render_tracks` - Should we render feature tracks to an image file?
///
pub fn process_event_file(src_path: &Path,
img_w: u32, img_h: u32,
timebase: f64,
timescale: f64,
max_events: usize,
render_events: bool,
render_sae: bool,
render_corners: bool,
render_tracks: bool) {
let event_file_res = std::fs::File::open(src_path);
if event_file_res.is_err() {
println!("No event file...skipping");
return;
}
let event_file = event_file_res.unwrap();
let mut event_reader = BufReader::new(event_file);
let time_window = (0.1 / timescale) as SaeTime; //0.1 second
//TODO get reference time filter threshold from command line option?
let ref_time_filter = (50E-3 / timescale) as SaeTime; //50ms
let mut tracker = Box::new(FeatureTracker::new(img_w, img_h, time_window, ref_time_filter));
//ensure that output directory exists
create_dir_all(Path::new("./out/")).expect("Couldn't create output dir");
let mut chunk_count = 0;
let mut event_count = 0;
loop {
chunk_count += 1;
let event_list_opt = conversion::read_next_chunk_sae_events(&mut event_reader, timebase, timescale);
if event_list_opt.is_none() {
break;
}
let event_list:Vec<SaeEvent> = event_list_opt.unwrap();
if event_list.len() > 0 {
event_count += event_list.len();
let corners:Vec<SaeEvent> = tracker.process_events(&event_list);
println!("chunk: {} events: {} corners: {} ", chunk_count, event_list.len(), corners.len() );
//TODO configure horizon based on command line options
let timestamp = event_list.first().unwrap().timestamp;
let horizon = timestamp.max(time_window) - time_window;
if render_events {
let out_path = format!("./out/sae_events_{:04}.png", chunk_count);
tracker.render_events_to_file( &event_list, &FeatureTracker::RED_PIXEL, &FeatureTracker::BLUE_PIXEL, &out_path );
}
if render_sae {
let out_path = format!("./out/sae_surf_{:04}.png", chunk_count);
tracker.render_sae_frame_to_file(horizon, &out_path);
}
if render_corners {
let out_path = format!("./out/sae_corners_{:04}.png", chunk_count);
tracker.render_corners_to_file( &corners, &FeatureTracker::YELLOW_PIXEL, &FeatureTracker::GREEN_PIXEL, &out_path );
}
if render_tracks {
let out_path= format!("./out/sae_tracks_{:04}.png", chunk_count);
tracker.render_tracks_to_file(horizon, &out_path);
}
}
else {
println!("no more events after {} chunks {} events", chunk_count, event_count);
break;
}
if max_events > 0 && event_count > max_events {
println!("Stopping on limit of {} events",event_count);
break;
}
}
}
fn main() {
let matches = clap_app!(blink_cam =>
(version: "0.1.0")
(author: "Todd Stellanova")
(about: "Process event camera pixel change event stream into tracked features.")
(@arg INPUT: -i --input +takes_value "Sets the input file to use: default is ./data/events.dat")
(@arg WIDTH: --width +takes_value "Sets the input width to use: default is 240 pixels")
(@arg HEIGHT: --height +takes_value "Sets the input height to use: default is 180 pixels")
(@arg TIMEBASE: --timebase +takes_value "Base time, default is 0.0 seconds")
(@arg TIMESCALE: --timescale +takes_value "Seconds per clock tick, default is 1E-6")
(@arg MAX_EVENTS: --max_events +takes_value "Maximum number of events to process")
(@arg RNDR_EVENTS: --rend_events "Render events as they occur")
(@arg RNDR_SAE: --rend_sae "Render the Surface of Active Events (SAE)")
(@arg RNDR_CORNERS: --rend_corners "Render corners as they're detected")
(@arg RNDR_TRACKS: --rend_tracks "Render feature matches as tracks:")
).get_matches();
//println!("clap matches: {:?}", matches);
let infile = matches.value_of("INPUT").unwrap_or("./data/events.dat");
let img_w = matches.value_of("WIDTH").unwrap_or("240").parse::<u32>().unwrap();
let img_h = matches.value_of("HEIGHT").unwrap_or("180").parse::<u32>().unwrap();
let timebase = matches.value_of("TIMEBASE").unwrap_or("0.0").parse::<f64>().unwrap();
let timescale = matches.value_of("TIMESCALE").unwrap_or("1E-6").parse::<f64>().unwrap();
let max_events = matches.value_of("MAX_EVENTS").unwrap_or("0").parse::<usize>().unwrap();
let render_events = matches.is_present("RNDR_EVENTS");
let render_sae = matches.is_present("RNDR_SAE");
let render_corners = matches.is_present("RNDR_CORNERS");
let render_tracks = matches.is_present("RNDR_TRACKS");
let in_path = Path::new(infile);
if !in_path.exists() {
eprintln!("Input file doesn't exist: {}", infile);
}
else {
println!("Reading from {}", infile);
}
process_event_file(&in_path, img_w, img_h, timebase, timescale, max_events, render_events, render_sae, render_corners, render_tracks);
}
|
Markdown | UTF-8 | 4,010 | 2.859375 | 3 | [] | no_license | ---
date: 2023-06-21
imdb_id: tt0090917
grade: F
slug: deadly-friend-1986
---
Paul, a teenage prodigy in robotics and artificial intelligence, reanimates his teenage neighbor Sam by implanting his pet robot’s processor into her brain after she’s rendered brain dead by her abusive alcoholic father. It works, but she’s an effective zombie, incapable of speech and exhibiting a robot’s herky-jerky movement. Things escalate when Sam uses her newfound robot strength to extract gruesome vengeance on her father and other neighbors.
<!-- end -->
In a 2021 interview, screenwriter Bruce Joel Rubin revealed he intended to pass on adapting Diana Henstell’s novel _Friend_ because he hated the book. He changed his mind after meditating and hearing his yoga mentor’s voice say, "There’s more integrity in providing for your family than in turning down jobs." His original draft (also titled _Friend_) played as a macabre love story[^1].
But the initial test screening convinced the studio the film needed more violence. Something he and director Wes Craven were happy to contribute. Reshoots added scenes of escalating brutality. Rubin remembers audiences hooting and cheering during a follow-up screening, but now studio execs felt it was _too_ violent and demanded cuts. "For every second we lose," Rubin remembers Craven saying, "that’s a million at the box office."[^1]
Craven proved prescient. The resulting film underwhelms. The first half plays like a PG-rated teen romance. Paul, with his robot sidekick BB, displays an advanced maturity befitting a gifted intellect. But upon encountering Sam, he’s flustered, stammers, and feels every bit a fifteen-year-old boy.
This proves a departure for Craven, known for his edgy independent horror, but he surprises, coaxing charismatic performances from his young leads. The inserted scenes of violence, including BB choking a would-be car-thief and Sam dreaming of stabbing her father and having him spurt gallons of blood over her, feel pulled from one of these earlier Craven entries.
Though the film bears some superficial resemblance to the _Frankenstein_ story, it’s not equipped to tackle the issue of playing God. Paul’s adolescent love for Sam renders him a child, not wanting to play God, just wanting his friend back.
The tone smooths out once Sam begins her killing spree, but at the cost of any emotional or narrative stakes. Sam’s a mindless zombie, ending her effective romantic chemistry with Paul, who’s never in any danger. There’s a visceral glee in watching Sam take revenge on the awful neighbors—including a memorable exploding head sequence—but the story’s focus has been on Paul, so the revenge feels less personal.
Also—short of Elm Street—is this the worst block on the planet? Next door, an abusive alcoholic. Across the street, a shotgun-happy paranoid shut-in. And prowling the streets, a gang of would-be bikers riding sport motorcycles instead of Harleys and picking on kids half their age.
But I digress. Things build to a crescendo when Paul’s friend Tom--aghast at the horror that Sam’s become--storms out of Paul’s house, threatening to go to the police. As Tom mounts his bike, he glances up, and Sam crashes out of a second-floor window in a swan dive yelling “Ahhhhh!”
This scene had me laughing aloud. I rewound it twice, laughing harder each time. Anyway, she lands on Tom and begins attacking him. Paul pulls her off and slaps her, causing her to flee, leading to a standoff with the police. The closing scene makes no sense, but the script has dug such a deep hole of ridiculousness, doubling down was the only viable option.
A shame. Matthew Labyorteaux and Kristy Swanson charm as Paul and Sam. They have great chemistry, and their early scenes together play cute. The original PG-rated macabre love story might not have appealed to Wes Craven’s core demographic, but it would have been a better movie. Granted, that’s not saying much.
[^1]: _Written in Blood_, _Deadly Friend_, Shout Factory, 2021.
|
Java | UTF-8 | 379 | 1.625 | 2 | [] | no_license | package android.support.p010c.p011a;
import android.annotation.TargetApi;
import android.app.Fragment;
@TargetApi(15)
/* renamed from: android.support.c.a.d */
class C0038d {
/* renamed from: a */
public static void m115a(Fragment fragment, boolean z) {
if (fragment.getFragmentManager() != null) {
fragment.setUserVisibleHint(z);
}
}
}
|
Java | UTF-8 | 5,124 | 1.867188 | 2 | [] | no_license | package org.myapp.dev.api.security;
import org.myapp.dev.config.AppConfig;
import org.myapp.dev.config.JwtConfig;
import org.myapp.dev.core.user.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.web.authentication.HttpStatusEntryPoint;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.CorsConfigurationSource;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import javax.crypto.SecretKey;
import static java.util.Arrays.asList;
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
private final UserService userService;
private final BCryptPasswordEncoder bCryptPasswordEncoder;
private final AppConfig appConfig;
private final JwtConfig jwtConfig;
private final SecretKey secretKey;
@Autowired
public WebSecurityConfig(UserService userService, BCryptPasswordEncoder bCryptPasswordEncoder, AppConfig appConfig, JwtConfig jwtConfig, SecretKey secretKey) {
this.userService = userService;
this.bCryptPasswordEncoder = bCryptPasswordEncoder;
this.appConfig = appConfig;
this.jwtConfig = jwtConfig;
this.secretKey = secretKey;
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable();
http.headers().frameOptions().disable();
http.cors()
.and()
.exceptionHandling().authenticationEntryPoint(new HttpStatusEntryPoint(HttpStatus.UNAUTHORIZED))
.and()
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS).and()
.addFilter(authenticationFilter())
.addFilter(authorizationFilter())
.authorizeRequests()
.antMatchers(HttpMethod.POST, appConfig.getSignUpUrl()).permitAll()
.antMatchers(appConfig.getSignUpUrl()).permitAll()
.antMatchers("/users/{userId}/**")
.access("hasRole('ROLE_ADMINISTRATOR') or @userSecurityConfig.hasAccess(authentication, #userId)")
.antMatchers(appConfig.getH2consoleUrl()).permitAll()
.anyRequest().authenticated();
}
@Override
public void configure(WebSecurity web) throws Exception {
web.ignoring().antMatchers("/v2/api-docs",
"/configuration/ui",
"/swagger-resources/**",
"/configuration/security",
"/swagger-ui.html",
"/swagger-ui/**",
"/webjars/**");
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userService).passwordEncoder(bCryptPasswordEncoder);
}
private AuthenticationFilter authenticationFilter() throws Exception{
final AuthenticationFilter filter = new AuthenticationFilter(authenticationManager(), appConfig, jwtConfig, secretKey);
filter.setFilterProcessesUrl(appConfig.getLoginUrl());
return filter;
}
private AuthorizationFilter authorizationFilter() throws Exception{
final AuthorizationFilter filter = new AuthorizationFilter(authenticationManager(), jwtConfig, secretKey);
return filter;
}
@Bean
public CorsConfigurationSource corsConfigurationSource() {
final CorsConfiguration configuration = new CorsConfiguration();
configuration.setAllowedOrigins(asList("*"));
configuration.setAllowedMethods(asList("HEAD", "GET", "POST", "PUT", "DELETE", "PATCH"));
// setAllowCredentials(true) is important, otherwise:
// The value of the 'Access-Control-Allow-Origin' header in the response must not be the
// wildcard '*' when the request's credentials mode is 'include'.
configuration.setAllowCredentials(true);
// setAllowedHeaders is important! Without it, OPTIONS preflight request
// will fail with 403 Invalid CORS request
configuration.setAllowedHeaders(asList("Authorization", "Cache-Control", "Content-Type", "UserId"));
final UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", configuration);
return source;
}
}
|
PHP | UTF-8 | 1,150 | 2.625 | 3 | [
"MIT"
] | permissive | <?php
$home = "/var/www/html/term.js-master";
$current_dir = isset($_POST['id']) ? $_POST['id'] : $home;
$root = array();
if( !strcmp( $current_dir, $home) ){
$root['id'] = $home;
$root['text'] = "Project Home";
$root['type'] = "D";
$root['state'] = 'open';
$root['children'] = listFolders( $current_dir );
echo "[". json_encode($root) . "]";
}else{
$root = listFolders( $current_dir );
echo json_encode($root);
}
function listFolders($dir)
{
$dh = scandir($dir);
$tree = array();
$node = array();
foreach ($dh as $folder) {
$node = array();
if ($folder != '.' && $folder != '..') {
if (is_dir($dir . '/' . $folder)) {
$node['id'] = $dir . '/' . $folder;
$node['text'] = $folder;
$node['state'] = 'closed';
$node['type'] = "D";
} else {
$node['id'] = $dir . '/' . $folder;
$node['text'] = $folder;
$node['state'] = 'open';
$node['type'] = "F";
}
array_push($tree, $node);
}
}
return $tree;
}
?>
|
JavaScript | UTF-8 | 1,306 | 2.6875 | 3 | [] | no_license | var React = require("react");
var _ = require("underscore");
var connect = require("react-redux").connect;
function getSummary(items) {
var result = 0;
_.each(items, function (item) {
result += item.count * item.price;
});
return result;
}
var Bucket = React.createClass({
propTypes: {
items: React.PropTypes.array.isRequired
},
createBucketItem: function (item) {
return (
<div key={item.id}>{item.count} {item.name}</div>
);
},
getBucketItems: function () {
if (this.props.items.length === 0) {
return <div>No items in bucket :(</div>
} else {
return this.props.items.map(this.createBucketItem);
}
},
getSummaryPrice: function () {
if (this.props.items.length <= 0) {
return;
}
return <div className="summary">Summary: {getSummary(this.props.items)}</div>
},
render: function () {
return (
<div className="bucket">
{this.getBucketItems()}
{this.getSummaryPrice()}
</div>
);
}
});
var mapStateToProps = function (state) {
return {
items: state.bucket
};
};
Bucket = connect(mapStateToProps)(Bucket);
module.exports = Bucket; |
Python | UTF-8 | 550 | 3.046875 | 3 | [] | no_license | import socket
def udp_main():
# 1.新建套接字
udp_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
# 绑定端口
udp_socket.bind(('',10001))
# 2.收发数据
udp_data = input("please enter the messege: ")
udp_addr = ('192.168.110.1',8001)
udp_socket.sendto(udp_data.encode('utf-8'), udp_addr)
udp_recv_data = udp_socket.recvfrom(1024)
print(udp_recv_data[0].decode('gbk'))
print(udp_recv_data[1])
# 3.关闭套接字
udp_socket.close()
if __name__ == "__main__":
udp_main() |
Go | UTF-8 | 188 | 3.109375 | 3 | [
"MIT"
] | permissive | package problem50
func myPow(x float64, n int) float64 {
res := 1.0
if n < 0 {
n = -n
x = 1 / x
}
for ; n > 0; n >>= 1 {
if n&1 == 1 {
res *= x
}
x *= x
}
return res
}
|
JavaScript | UTF-8 | 1,067 | 2.65625 | 3 | [] | no_license | const HCCrawler = require('headless-chrome-crawler');
(async () =>
{
const crawler = await HCCrawler.launch(
{
// Function to be evaluated in browsers
evaluatePage: (() => ({
title: $('title').text(),
})),
// Function to be called with evaluated results from browsers
onSuccess: (result => {
console.log(result);
}),
});
// Queue a request
await crawler.queue('https://example.com/');
// Queue multiple requests
await crawler.queue(['https://example.net/', 'https://example.org/']);
// Queue a request with custom options
await crawler.queue(
{
url: 'https://example.com/',
// Emulate a tablet device
device: 'Nexus 7',
// Enable screenshot by passing options
screenshot: {
path: './tmp/example-com.png'
},
});
await crawler.onIdle(); // Resolved when no queue is left
await crawler.close(); // Close the crawler
})(); |
Python | UTF-8 | 4,651 | 4.09375 | 4 | [] | no_license | # Name: Denis Savenkov
# hw3.py
##### Template for Homework 3, exercises 3.1 - ######
import math
# ********** Exercise 3.1 **********
# Define your function here
def list_intersection(list1, list2):
#create an empty list to store common elements
inter_list = []
#iterate the list and if the element is also in second list
#and not in inter_list, append the inter_list
for x in list1:
if x not in inter_list and x in list2:
inter_list.append(x)
return inter_list
print "Test Cases for Exercise 3.1"
print list_intersection([1, 3, 5], [5, 3, 1])
print list_intersection([1, 3, 6, 9], [10, 14, 3, 72, 9])
print list_intersection([2, 3], [3, 3, 3, 2, 10])
print list_intersection([2, 4, 6], [1, 3, 5])
print list_intersection([], [])
print list_intersection([], [1, 3])
print list_intersection([1, 3], [])
print list_intersection([3, 3, 3, 2, 10], [2, 3])
# ********** Exercise 3.2 **********
# Define your function here
def ball_collide(ball1, ball2):
#calculate the distance between balls, and the sum of their radiuses
distance = math.sqrt((ball2[0] - ball1[0])**2 + (ball2[1] - ball1[1])**2)
sumr = ball1[2] + ball2[2]
#compare the distance and sum of radiuses
return distance <= sumr
print "Test Cases for Exercise 3.2"
print ball_collide((0, 0, 1), (3, 3, 1)) # Should be False
print ball_collide((5, 5, 2), (2, 8, 3)) # Should be True
print ball_collide((7, 8, 2), (4, 4, 3)) # Should be True
# ********** Exercise 3.3 **********
# Define your dictionary here - populate with classes from last term
my_classes = {"6.1":"math","6.2":"literature","6.3":"history",\
"6.4":"physics","6.5":"chemistry"}
def add_class(class_num, desc):
#add a class number and the name of the class to dictionary
my_classes[class_num] = desc
# Here, use add_class to add the classes you're taking next term
add_class('6.189', 'Introduction to Python')
def print_classes(course):
#condition if class listed
class_listed = False
for class_num in my_classes.keys():
#check if class number is in course
if class_num[0] == course:
#print out the appropriate class
print str(class_num) + " - " + my_classes[class_num]
class_listed = True
#if class is not listed, print out the response
if class_listed == False:
print "No Course " + course + " classes taken"
print "Test Cases for Exercise 3.3"
print_classes("6")
print_classes("9")
# ********** Exercise 3.4 **********
NAMES = ['Alice', 'Bob', 'Cathy', 'Dan', 'Ed', 'Frank',
'Gary', 'Helen', 'Irene', 'Jack', 'Kelly', 'Larry']
AGES = [20, 21, 18, 18, 19, 20, 20, 19, 19, 19, 22, 19]
# Define your functions here
def combine_lists(l1, l2):
comb_dict = {}
#concatenate two lists, key to value by order
for n in range(0, len(l1)):
comb_dict[l1[n]] = l2[n]
return comb_dict
combined_dict = combine_lists(NAMES, AGES)
def people(age):
#create empty list to store the suitable names
name_list = []
#iterate through dict and add names of appropriate age
for n in combined_dict:
if combined_dict[n] == age:
name_list.append(n)
return name_list
print "Test Cases for Exercise 3.4 (all should be True)"
print 'Dan' in people(18) and 'Cathy' in people(18)
print 'Ed' in people(19) and 'Helen' in people(19) and\
'Irene' in people(19) and 'Jack' in people(19) and 'Larry'in people(19)
print 'Alice' in people(20) and 'Frank' in people(20) and 'Gary' in people(20)
print people(21) == ['Bob']
print people(22) == ['Kelly']
print people(23) == []
# ********** Exercise 3.5 **********
def zellers(month, day, year):
#create dictionary for monthes and days of week
m = {"March":1, "April":2, "May":3, "June":4, "July":5, "August":6, "September":7,\
"October":8, "November":9, "December":10, "January":11, "February":12}
week = {0:"Sunday", 1:"Monday", 2:"Tuesday", 3:"Wednesday", 4:"Thursday",\
5:"Friday", 6:"Saturday"}
#create zellers algorithm
a = m[month]
if a == 11 or a == 12:
c = c - 1
b = day
c = year % 100
d = year / 100
w = (13*a-1) / 5
x = c / 4
y = d / 4
z = w + x + y + b + c - 2*d
r = z % 7
if r < 0:
r += 7
#return day of week using dictionary
return week[r]
print "Test Cases for Exercise 3.5"
print zellers("March", 10, 1940) == "Sunday" # This should be True
print zellers("December", 20, 1992) == "Sunday" # True
|
Python | UTF-8 | 4,178 | 3.578125 | 4 | [] | no_license |
"""
This is homework #1 for A.I. spring class CSCI561
Simple checker game by adopting Minimax, Alphabeta Algorithm
- __main file__ -> class: starCircleWar
- methods:
* parseInputFile
* run_minimax
* run_alphabeta
input : input.txt
output : output.txt
- nextMove
- myopic utility value
- farsighted utility value
- total node expansion count
"""
__version__ = '0.8'
__author__ = 'Chanshin Peter Park'
import logging
from Minimax import Minimax
from Board import Board
from AlphaBeta import AlphaBeta
class starCircleWar(object):
def __init__(self):
logging.basicConfig(level=logging.DEBUG, format='%(asctime)s - %(levelname)s - %(message)s')
input_file = "input.txt"
param = self.parseInputFile(input_file)
self.initialBoardState = param["CURRENT_BOARD_STATE"]
self.maxplayer = param["PLAYER"]
self.depth = param["DEPTH_LIMIT"]
self.row_values = param["ROW_VALUES"]
self.algorithm = {"MINIMAX": 0, "ALPHABETA": 1}[param["ALGORITHM"]]
#Initialize Gaming Board
self.Board = Board(self.initialBoardState, self.row_values, self.maxplayer, None, 0, 0, 0, 0, self.maxplayer)
# Play Game
if self.algorithm == 0:
self.run_minimax()
elif self.algorithm == 1:
self.run_alphabeta()
@staticmethod
def parseInputFile(input_file):
param = {}
rfile = open(input_file)
param["PLAYER"] = rfile.readline().strip()
param["ALGORITHM"] = rfile.readline().strip()
param["DEPTH_LIMIT"] = rfile.readline().strip()
# boardState : state of starting board
boardState = [[0]*8 for i in range(8)]
for i in range(8):
boardState[i] = list(rfile.readline().rstrip().split(','))
param["CURRENT_BOARD_STATE"] = boardState
# row_values : weight of each row
row_values = list(rfile.readline().rstrip().split(','))
param["ROW_VALUES"] = row_values
return param
def run_minimax(self):
game = Minimax(self.Board, self.maxplayer, self.depth)
bestscore = game.minimax(game.Board,0)
#print bestscore
if bestscore.PrevX == bestscore.X and bestscore.PrevX == bestscore.Y:
game.nextMove = "pass"
else:
game.nextMove = bestscore.interpret_xy(bestscore.PrevX, bestscore.PrevY) + "-" + bestscore.interpret_xy(bestscore.X, bestscore.Y)
game.util_myopic = bestscore.get_eval(bestscore.boardState)
# print "nextMove:" + game.nextMove
# print "myopic:" + str(game.util_myopic)
# print "farsighted : " + str(game.util_farsighted)
# print "nodeCount:" + str(game.node_count)
game.print_nextState(game.nextMove,game.util_myopic,game.util_farsighted,game.node_count)
def run_alphabeta(self):
game = AlphaBeta(self.Board, self.maxplayer, self.depth)
# print game.path
# for i in range(len(game.path)):
# print game.path[i]
first = game.path.pop(len(game.path)-1)
if isinstance(first,Board) != 1:
game.nextMove = first[0]
game.util_myopic = first[1]
else:
if first.PrevX == first.X and first.PrevX == first.Y:
game.nextMove = "pass"
else:
game.nextMove = first.interpret_xy(first.PrevX, first.PrevY) + "-" + first.interpret_xy(
first.X, first.Y)
game.util_myopic = first.get_eval(first.boardState)
if self.maxplayer == 'Star':
game.util_farsighted = game.alpha
else:
game.util_farsighted = game.beta
# print "nextMove:" + game.nextMove
# print "myopic:" + str(game.util_myopic)
# print "farsighted : " + str(game.util_farsighted)
# print "nodeCount:" + str(game.node_count)
game.print_nextState(game.nextMove,game.util_myopic,game.util_farsighted,game.node_count)
if __name__ == '__main__':
starCircleWar()
#game.parseInputFile('input.txt') |
C++ | UTF-8 | 457 | 2.796875 | 3 | [
"BSD-3-Clause"
] | permissive | #pragma once
#include <sstream>
#include <string>
namespace global_check {
// Goal: Try to recreate issue of duplicate objects when linking with Python
// code.
struct Impl {
static double global;
};
template <typename T>
std::pair<std::string, T> Producer(const T& value) {
T& global = Impl::global;
global += value;
std::ostringstream os;
os << "Ptr: " << &global;
return std::make_pair(os.str(), global);
}
} // namespace global_check
|
Python | UTF-8 | 13,095 | 2.90625 | 3 | [
"MIT"
] | permissive | from gym_electric_motor.core import ElectricMotorVisualization
from .motor_dashboard_plots import StatePlot, ActionPlot, RewardPlot, TimePlot, EpisodePlot, StepPlot
import matplotlib.pyplot as plt
import gymnasium
class MotorDashboard(ElectricMotorVisualization):
"""A dashboard to plot the GEM states into graphs.
Every MotorDashboard consists of multiple MotorDashboardPlots that are each responsible for the plots in a single
matplotlib axis.
It handles three different types of plots: The TimePlot, EpisodePlot and StepPlot which especially differ in
their x-Axis. The time plots plot every step and have got the time on the x-Axis. The EpisodicPlots plot statistics
over the episodes (e.g. mean reward per step in each episode). The episode number is on their x-Axis. The
StepPlots plot statistics over the last taken steps (e.g. mean reward over the last 1000 steps) and their x-Axis
are the cumulative number of steps.
The StepPlots, EpisodicPlots and TimePlots each are plotted into three separate figures.
The most common TimePlots (i.e to plot the states, actions and rewards) can be plotted by just passing the
corresponding arguments in the constructor. Additional plots (e.g. the MeanEpisodeRewardPlot) have to be
initialized manually and passed to the constructor.
Furthermore, completely custom plots can be defined. They have to derive from the TimePlot, EpisodePlot or
StepPlot base classes.
"""
@property
def update_interval(self):
"""Number of steps until the visualization is updated"""
return self._update_interval
def __init__(
self, state_plots=(), action_plots=(), reward_plot=False, additional_plots=(),
update_interval=1000, time_plot_width=10000, style=None, scale_plots = None
):
"""
Args:
state_plots('all'/iterable(str)): An iterable of state names to be shown. If 'all' all states will be shown.
Default: () (no plotted states)
action_plots('all'/iterable(int)): If action_plots='all', all actions will be plotted. If more than one
action can be applied on the environment it can be selected by its index.
Default: () (no plotted actions).
reward_plot(boolean): Select if the current reward is to be plotted. Default: False
additional_plots(iterable((TimePlot/EpisodePlot/StepPlot))): Additional already instantiated plots
to be shown on the dashboard
update_interval(int > 0): Amount of steps after which the plots are updated. Updating each step reduces the
performance drastically. Default: 1000
time_plot_width(int > 0): Width of the step plots in steps. Default: 10000 steps
(1 second for continuously controlled environments / 0.1 second for discretely controlled environments)
style(string): Select one of the matplotlib-styles. e.g. "dark-background".
Default: None (the already selected style)
"""
# Basic assertions
assert type(reward_plot) is bool
assert all(isinstance(ap, (TimePlot, EpisodePlot, StepPlot)) for ap in additional_plots)
assert type(update_interval) in [int, float]
assert update_interval > 0
assert type(time_plot_width) in [int, float]
assert time_plot_width > 0
assert style in plt.style.available or style is None
super().__init__()
# Select the matplotlib style
if style is not None:
plt.style.use(style)
# List of the opened figures
self._figures = []
# The figures to be opened for the step plots, episodic plots and step plots
self._time_plot_figure = None
self._episodic_plot_figure = None
self._step_plot_figure = None
# Store the input data
self._state_plots = state_plots
self._action_plots = action_plots
self._reward_plot = reward_plot
# Separate the additional plots into StepPlots, EpisodicPlots and StepPlots
self._custom_time_plots = [p for p in additional_plots if isinstance(p, TimePlot)]
self._episodic_plots = [p for p in additional_plots if isinstance(p, EpisodePlot)]
self._step_plots = [p for p in additional_plots if isinstance(p, StepPlot)]
self._time_plots = []
self._update_interval = int(update_interval)
self._time_plot_width = int(time_plot_width)
self._plots = []
self._k = 0
self._update_render = False
#self._scale_plots = scale_plots
def on_reset_begin(self):
"""Called before the environment is reset. All subplots are reset."""
for plot in self._plots:
plot.on_reset_begin()
def on_reset_end(self, state, reference):
"""Called after the environment is reset. The initial data is passed.
Args:
state(array(float)): The initial state :math:`s_0`.
reference(array(float)): The initial reference for the first time step :math:`s^*_0`.
"""
for plot in self._plots:
plot.on_reset_end(state, reference)
def on_step_begin(self, k, action):
"""The information about the last environmental step is passed.
Args:
k(int): The current episode step.
action(ndarray(float) / int): The taken action :math:`a_k`.
"""
for plot in self._plots:
plot.on_step_begin(k, action)
def on_step_end(self, k, state, reference, reward, terminated):
"""The information after the step is passed
Args:
k(int): The current episode step
state(array(float)): The state of the env after the step :math:`s_k`.
reference(array(float)): The reference corresponding to the state :math:`s^*_k`.
reward(float): The reward that has been received for the last action that lead to the current state
:math:`r_{k}`.
terminated(bool): Flag, that indicates, if the last action lead to a terminal state :math:`t_{k}`.
"""
for plot in self._plots:
plot.on_step_end(k, state, reference, reward, terminated)
self._k += 1
if self._k % self._update_interval == 0:
self._update_render = True
def render(self):
"""Updates the plots every *update cycle* calls of this method."""
if not (self._time_plot_figure or self._episodic_plot_figure or self._step_plot_figure) \
and len(self._plots) > 0:
self.initialize()
if self._update_render:
self._update()
self._update_render = False
def set_env(self, env):
"""Called during initialization of the environment to interconnect all modules. State names, references,...
might be saved here for later processing
Args:
env(ElectricMotorEnvironment): The environment.
"""
state_names = env.physical_system.state_names
if self._state_plots == 'all':
self._state_plots = state_names
if self._action_plots == 'all':
if type(env.action_space) is gymnasium.spaces.Discrete:
self._action_plots = [0]
elif type(env.action_space) in (gymnasium.spaces.Box, gymnasium.spaces.MultiDiscrete):
self._action_plots = list(range(env.action_space.shape[0]))
self._time_plots = []
if len(self._state_plots) > 0:
assert all(state in state_names for state in self._state_plots)
for state in self._state_plots:
self._time_plots.append(StatePlot(state))
if len(self._action_plots) > 0:
assert type(env.action_space) in (gymnasium.spaces.Box, gymnasium.spaces.Discrete, gymnasium.spaces.MultiDiscrete), \
f'Action space of type {type(env.action_space)} not supported for plotting.'
for action in self._action_plots:
ap = ActionPlot(action)
self._time_plots.append(ap)
if self._reward_plot:
self._reward_plot = RewardPlot()
self._time_plots.append(self._reward_plot)
self._time_plots += self._custom_time_plots
self._plots = self._time_plots + self._episodic_plots + self._step_plots
for time_plot in self._time_plots:
time_plot.set_width(self._time_plot_width)
for plot in self._plots:
plot.set_env(env)
def reset_figures(self):
"""Method to reset the figures to the initial state.
This method can be called, when the plots shall be reset after the training and before the test, for example.
Another use case, that requires the call of this method by the user, is when the dashboard is executed within
a jupyter notebook and the figures shall be plotted below a new cell."""
for plot in self._plots:
plot.reset_data()
self._episodic_plot_figure = self._time_plot_figure = self._step_plot_figure = None
self._figures = []
def initialize(self):
"""Called with first render() call to setup the figures and plots."""
plt.close()
self._figures = []
if plt.get_backend() in ['nbAgg', 'module://ipympl.backend_nbagg']:
self._initialize_figures_notebook()
else:
self._initialize_figures_window()
plt.pause(0.1)
def _initialize_figures_notebook(self):
# Create all plots below each other: First Time then Episode then Step Plots
no_of_plots = len(self._episodic_plots) + len(self._step_plots) + len(self._time_plots)
if no_of_plots == 0:
return
fig, axes = plt.subplots(no_of_plots, figsize=(8, 2*no_of_plots))
self._figures = [fig]
axes = [axes] if no_of_plots == 1 else axes
time_axes = axes[:len(self._time_plots)]
axes = axes[len(self._time_plots):]
if len(self._time_plots) > 0:
time_axes[-1].set_xlabel('t/s')
self._time_plot_figure = fig
for plot, axis in zip(self._time_plots, time_axes):
plot.initialize(axis)
episode_axes = axes[:len(self._episodic_plots)]
axes = axes[len(self._episodic_plots):]
if len(self._episodic_plots) > 0:
episode_axes[-1].set_xlabel('Episode No')
self._episodic_plot_figure = fig
for plot, axis in zip(self._episodic_plots, episode_axes):
plot.initialize(axis)
step_axes = axes
if len(self._step_plots) > 0:
step_axes[-1].set_xlabel('Cumulative Steps')
self._step_plot_figure = fig
for plot, axis in zip(self._step_plots, step_axes):
plot.initialize(axis)
def _initialize_figures_window(self):
# create separate figures for time based, step and episode based plots
if len(self._episodic_plots) > 0:
self._episodic_plot_figure, axes_ep = plt.subplots(len(self._episodic_plots), sharex=True)
axes_ep = [axes_ep] if len(self._episodic_plots) == 1 else axes_ep
self._episodic_plot_figure.subplots_adjust(wspace=0.0, hspace=0.02)
self._episodic_plot_figure.canvas.manager.set_window_title('Episodic Plots')
axes_ep[-1].set_xlabel('Episode No')
self._figures.append(self._episodic_plot_figure)
for plot, axis in zip(self._episodic_plots, axes_ep):
plot.initialize(axis)
if len(self._step_plots) > 0:
self._step_plot_figure, axes_int = plt.subplots(len(self._step_plots), sharex=True)
axes_int = [axes_int] if len(self._step_plots) == 1 else axes_int
self._step_plot_figure.canvas.manager.set_window_title('Step Plots')
self._step_plot_figure.subplots_adjust(wspace=0.0, hspace=0.02)
axes_int[-1].set_xlabel('Cumulative Steps')
self._figures.append(self._step_plot_figure)
for plot, axis in zip(self._step_plots, axes_int):
plot.initialize(axis)
if len(self._time_plots) > 0:
self._time_plot_figure, axes_step = plt.subplots(len(self._time_plots), sharex=True)
self._time_plot_figure.canvas.manager.set_window_title('Time Plots')
axes_step = [axes_step] if len(self._time_plots) == 1 else axes_step
self._time_plot_figure.subplots_adjust(wspace=0.0, hspace=0.2)
axes_step[-1].set_xlabel('$t$/s')
self._figures.append(self._time_plot_figure)
for plot, axis in zip(self._time_plots, axes_step):
plot.initialize(axis)
self._figures[0].align_ylabels()
def _update(self):
"""Called every *update cycle* steps to refresh the figure."""
for plot in self._plots:
plot.render()
for fig in self._figures:
#fig.align_ylabels()
fig.canvas.draw()
fig.canvas.flush_events()
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.