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
|
|---|---|---|---|---|---|---|---|
C++
|
UTF-8
| 1,494
| 3.09375
| 3
|
[] |
no_license
|
#include <stdio.h>
#include <stdlib.h>
#include <unordered_set>
#include <vector>
#include <algorithm>
#include <string>
using namespace std;
class Path
{
public:
int dest, bessie, elsie;
Path(int adest, int abessie, int aelsie)
{
dest = adest;
bessie = abessie;
elsie = aelsie;
}
};
void OPEN(string inputFile, string outputFile) {
freopen(inputFile.c_str(), "r", stdin);
freopen(outputFile.c_str(), "w", stdout);
}
vector<Path> adj[18];
int n,m;
vector<int> bessieRes;
unordered_set<int> elsieRes;
void traverseBessie(int x, int totalCost)
{
if (x==n)
{
bessieRes.push_back(totalCost);
}
else
{
for (int i=0; i<adj[x].size(); i++)
traverseBessie(adj[x][i].dest, adj[x][i].bessie+totalCost);
}
}
void traverseElsie(int x, int totalCost)
{
if (x==n)
{
elsieRes.insert(totalCost);
}
else
{
for (int i=0; i<adj[x].size(); i++)
traverseElsie(adj[x][i].dest, adj[x][i].elsie+totalCost);
}
}
int main()
{
OPEN("meeting.in", "meeting.out");
scanf("%d%d", &n, &m);
for (int i=0; i<18; i++) adj[i].clear();
int a,b,c,d;
for (int i=0; i<m; i++)
{
scanf("%d%d%d%d",&a, &b, &c, &d);
Path newPath (b,c,d);
adj[a].push_back(newPath);
}
traverseElsie(1,0);
traverseBessie(1,0);
sort(bessieRes.begin(), bessieRes.end());
bool found=false;
for (int i=0; i<bessieRes.size(); i++)
{
if (elsieRes.count(bessieRes[i]) > 0)
{
found=true;
printf("%d\n", bessieRes[i]);
break;
}
}
if (!found) printf("IMPOSSIBLE\n");
return 0;
}
|
Go
|
UTF-8
| 3,338
| 2.71875
| 3
|
[
"MIT"
] |
permissive
|
package db
import (
wallet "github.com/ali2210/wizdwarf/db/cloudwalletclass"
walletAcc "github.com/ali2210/wizdwarf/structs"
"fmt"
"context"
firebase "firebase.google.com/go"
)
// constants
const collectionName string = "EthereumPrivateLedger"
// Interface
type PublicLedger interface{
// Public Ledger
CreatePublicAddress(w *wallet.EthereumWalletAcc , clientID *firebase.App)(*wallet.EthereumWalletAcc, error);
FindMyPublicAddress(w *walletAcc.Acc, clientID *firebase.App)(*wallet.EthereumWalletAcc,error);
FindMyAddressByEmail(w *walletAcc.Acc, clientID *firebase.App)(*wallet.EthereumWalletAcc,error);
}
type ledgerPublic struct{}
func NewCollectionInstance() PublicLedger{
return &ledgerPublic{}
}
func (*ledgerPublic)CreatePublicAddress(w *wallet.EthereumWalletAcc, clientID *firebase.App)(*wallet.EthereumWalletAcc, error){
ctx := context.Background()
client , err := clientID.Firestore(ctx); if err != nil{
fmt.Println("Error", err)
return nil, err
}
defer client.Close()
fmt.Println("clientID:", clientID)
_, _ ,err = client.Collection(collectionName).Add(ctx, map[string]interface{}{
"Email" : w.Email,
"Password" : w.Password,
"EthAddress": w.EthAddress,
"Terms":w.Terms,
"Allowed":w.Allowed,
"PrvteKey": w.PrvteKey,
}); if err != nil{
fmt.Println("Error", err)
return nil , err
}
return w,nil
}
func (*ledgerPublic) FindMyPublicAddress(w *walletAcc.Acc, clientID *firebase.App)(*wallet.EthereumWalletAcc, error){
ctx := context.Background()
client , err := clientID.Firestore(ctx); if err != nil {
fmt.Println("Error:", err)
return nil, err
}
defer client.Close()
var ethereumDetials wallet.EthereumWalletAcc
iterator := client.Collection(collectionName).Where("Email", "==" , w.Email ).Where("Password" , "==" , w.Password).Where("EthAddress", "==" , w.EthAddress).Documents(ctx)
defer iterator.Stop()
for{
doc , err := iterator.Next(); if err != nil {
fmt.Println("Error:", err)
return nil, err
}
ethereumDetials = wallet.EthereumWalletAcc{
Email : doc.Data()["Email"].(string),
Password : doc.Data()["Password"].(string),
EthAddress : doc.Data()["EthAddress"].(string),
Terms : doc.Data()["Terms"].(bool),
Allowed : doc.Data()["Allowed"].(bool),
PrvteKey: doc.Data()["PrvteKey"].(string),
}
break
}
return ðereumDetials, nil
}
func (*ledgerPublic) FindMyAddressByEmail(w *walletAcc.Acc, clientID *firebase.App)(*wallet.EthereumWalletAcc,error){
ctx := context.Background()
client , err := clientID.Firestore(ctx); if err != nil {
fmt.Println("Error:", err)
return nil, err
}
defer client.Close()
var ethereumDetials wallet.EthereumWalletAcc
iterator := client.Collection(collectionName).Where("Email", "==" , w.Email ).Where("Password" , "==" , w.Password).Documents(ctx)
defer iterator.Stop()
for{
doc , err := iterator.Next(); if err != nil {
fmt.Println("Error:", err)
return nil, err
}
ethereumDetials = wallet.EthereumWalletAcc{
Email : doc.Data()["Email"].(string),
Password : doc.Data()["Password"].(string),
EthAddress : doc.Data()["EthAddress"].(string),
Terms : doc.Data()["Terms"].(bool),
Allowed : doc.Data()["Allowed"].(bool),
PrvteKey: doc.Data()["PrvteKey"].(string),
}
break
}
return ðereumDetials, nil
}
|
Markdown
|
UTF-8
| 7,342
| 2.96875
| 3
|
[] |
no_license
|
# 로그 클래스 덱(Rogue Class Deck)
## `Lesath`가 자신의 턴 끝에 표시된 몬스터를 제거하면 다시 표시해야 하나요(If Lesath banishes a displayed monster at the end of his turn, does he then have to display it again)?
아니오, 그러면 몬스터들이 제거되지 않습니다. 그런 것은 아닙니다.
> No, because then they would never get banished. That's no good.
> Resolution: On Lesath's character card and the Sword Dancer side of his role card, change "When you would banish a monster, display it. You may recharge a card to add 1d6 (▢+1) to your combat check for each displayed monster." to "When you defeat a monster and would banish it, you may display it instead. Before you attempt a combat check, you may recharge a card to add a number of d6 (▢+1) equal to your number of displayed monsters. At the end of your turn, banish your displayed monsters."
> On the Dervish side of his role card, change the power to "When you defeat a monster and would banish it, you may display it instead. Before you attempt a combat check, you may recharge a card to add a number of d6 (▢+1) (▢+2) (▢+3) equal to your number of displayed monsters. At the end of your turn, banish your displayed monsters."
posted September 2014 | back to top
## `Merisiel the Forger`는 버린 무기 카드들에 영향을 주는 파워가 있습니다. 플레이한 무기로만 제한되나요(Merisiel the Forger has a power that affects weapons she discards. Is that restricted to weapons that she plays)?
플레이한 카드로만 제한되어야 합니다.
> It should be restricted to cards you play.
> Resolution: On the Forger side of Merisiel's role card, make the changes in italics to the following power: "When you play a weapon and would discard (□ or bury) (□ or banish) it, you may perform the action with a blessing (□ or any card) instead."
posted Jul 22, 2015 | back to top
## 복수의 체크가 필요한 몬스터를 인카운터하였을 때 `Olenjack`은 그 체크들간 탐험을 할 수 있나요(When encountering a monster that has multiple checks to defeat, can Olenjack explore in between those checks)?
아니오.
> No.
> Resolution: On Olenjack's character card and both sides of his role card, change "On your turn, when you succeed at a combat check that has the Poison trait, you may immediately explore again" to "On your turn, when you succeed at a combat check that has the Poison trait, after defeating the bane you may immediately explore again".
posted Jun 2, 2015 | back to top
## `Wu Shen`의 `Prey Stalker` 역할을 선택하면 즉시 배리어를 물리치는 체크에 2를 더하는 파워를 얻게되나요(Do I gain the power to add 2 to my checks to defeat barriers as soon as I select Wu Shen's Prey Stalker role)?
아니오, 그 파워의 앞에는 체크박스가 있어야 합니다. 하지만 이미 너무 많은 피트가 있으므로, 그 파워의 마지막에 있는 체크박스를 제거합니다.
> No, that power should have a checkbox at the front. But then she'll have too many feats, so we need to remove the last checkbox in that power.
> Resolution: On the Prey Stalker side of Wu Shen's role card, change "Add 2 (▢ 4) to your check to defeat a barrier (▢ or close a location)" to "▢ Add 2 (▢ 4) to your check to defeat a barrier or close a location".
posted November 2014 | back to top
## `Keen Rapier +3`를 제외하면 모든 레이피어나 keen 무기는 사용 캐릭터가 무기에 대한 특화 능력이 없으면 패널티를 가지고 있습니다. `Keen Rapier +3`도 이런 패널티가 있어야 하지 않나요(Except for Keen Rapier +3, rapiers and other keen weapons all have penalties when used by characters who aren’t proficient with weapons. Should Keen Rapier +3 have that penalty)?
예.
> Yes.
> Resolution: On the weapon Keen Rapier +3, add the sentence “If you aren’t proficient with weapons, the difficulty of this check is increased by 4.”
posted Apr 28, 2015 | back to top
## 로그 클래스 덱에 있는 `Light Crossbow +1`에는 `Magic` 특성 대신 `Basic` 특성이 있습니다. 잘못된 것인가요(The Light Crossbow +1 in the Rogue Class Deck has the Basic trait instead of the Magic trait. That's wrong, right)?
예, 잘못되었습니다.
> Right—that's wrong.
> Resolution: On the weapon Light Crossbow +1, replace the Basic trait with the Magic trait. (This card is correct in the Wizard Class Deck.)
posted September 2014 | back to top
## `Main-Gauche +1`을 다른 무기와 함께 사용할 수 있나요? 파워의 첫 문장은 사용할 수 있는 경우가 아니라 못하는 경우를 말하네요(Can I play Main-Gauche +1 with another weapon or not? The first sentence tells me when I can't, not when I can).
`2-Handed` 특성이 없는 무기를 플레이하면 사용할 수 있습니다.
> You can, so long as you didn't play another weapon with the 2-Handed trait.
> Resolution: On the weapon Main-Gauche +1, replace the text with the following:
>> For your combat check, reveal this card to use your Strength or Melee skill + 1d4+1.
>> Recharge this card to reduce Combat damage dealt to you by 2. You may play this card on a check even if you played a weapon that does not have the 2-Handed trait.
posted Jun 3, 2015 | back to top
## 다른 `Speed` 주문은 `Wisdom` 혹은 `Divine` 체크로 얻을 수 있는데, 로그 덱의 `Speed`는 그렇지 않습니다. 어떻게 해야 되나요(Other versions of Speed can be acquired with Wisdom or Divine, but not the one in the Rogue deck. What's the deal)?
참 신기한 오류입니다.
> That's a pretty mysterious error.
> Resolution: On the spell Speed, the check to acquire should be Intelligence Arcane Wisdom Divine 6.
posted November 2014 | back to top
## `Arrow Catching Studded Leather`는 `Magic` 특성이 있습니다. 이 카드들은 손패를 리셋하는 과정에서 재충전할 수 있어야 하지 않나요(The Arrow Catching Studded Leather has the Magic trait. Shouldn’t it let you recharge it when you reset your hand)?
예.
> Yes.
> Resolution: On the armor Arrow Catching Studded Leather, add the following text: “If you are proficient with light armors, you may recharge this card when you reset your hand.”
posted Feb 5, 2015 | back to top
## `Burglar`를 회피하면 무기나 아이템을 버려야 하나요? 얻지 않기로 결정하면 어떻게 되나요(If I evade the Burglar, do I have to discard a weapon or item? What if I choose not to acquire it)?
`Burglar`를 회피하면 카드를 버릴 필요가 없습니다. 카드를 회피하면 카드에 있는 파워 중 어떤 것도 발동되지 않습니다. `Burglar`를 얻지 않기로 결정한 경우에는 카드를 버려야만 합니다.
> If you evade the Burglar, you don't have to discard, because the Skull & Shackles rulebook clarified that if you evade a card, you do not activate any other powers on it. If you choose not to acquire the Burglar, you do have to discard.
> Resolution: On the ally Burglar, change "If you fail the check to acquire this card" to "If you fail to acquire this card". (The Skull & Shackles rulebook introduced the rule "If you choose not to acquire a boon, it counts as failing to acquire it.")
posted Sep 22, 2015 | back to top
|
C++
|
UTF-8
| 2,162
| 2.703125
| 3
|
[] |
no_license
|
//headers
using namespace std;
#include<cstring>
#include<vector>
#include<map>
#include<iostream>
#include<math.h>
#include<queue>
#include<cstdlib>
#include<ctype.h>
#include<string>
#include<cstdio>
#include<algorithm>
/**********INPUT******/
#define sint(a) scanf("%d",&a)
#define pint(a) printf("%d",a)
//#define sintll(a) scanf("%lld",&a)
//#define pintll(a) printf("%lld",a)
//#define sint2(a,b) scanf("%d%d",&a,&b)
#define MAX(a,b) (a > b) ? (a) : (b)
#define MIN(a,b) (a < b) ? (a) : (b)
#define MIN3(a,b,c) (a < b) ? (a < c ? a : c) : (b < c ? b : c)
#define MAX3(a,b,c) (a > b) ? (a > c ? a : c) : (b > c ? b : c)
#define mem(x,y) memset(x,y,sizeof(x));
#define pb push_back
#define pf pop_front()
#define N 1000000+7
/* loops****/
#define rep(a,n) for(int a=1;a<=n;a++)
#define repo(a,n) for(int a=0;a<n;a++)
#define PINF 2147483647
#define NINF -2147483647
#define Pi acos(-1.0)
typedef priority_queue< int,vector<int>,greater<int> > my_q;
/****************** templates***********************/
bool prime[100000000];
void seive() {
mem(prime,true);
prime[0]=prime[1]=false;
prime[2]=true;
for(long long i=4; i<=100000000; i+=2) prime[i]=false;
for(long long i=3; i*i<=100000000; i++) {
if(prime[i])
for(long long j=i+i; j<=100000000; j+=i)
prime[j]=false;
}
//repo(i,10) if(!prime[i]) cout<<i<<endl;
}
int main() {
long long n;
seive();
while(cin>>n) {
if(n&1) {
if(prime[n-2]) {
printf("%lld is the sum of 2 and %lld.\n",n,n-2);
} else printf("%lld is not the sum of two primes!\n",n);
}
else {
bool flag=false;
prime[0]=false;
int m=0;
for(long long i=2; i<=n; i++) {
if( prime[ i ] && prime[n-i] && (n-i)!=i ) {
printf("%lld is the sum of %lld and %lld.\n",n,i,n-i);
flag=true;
break;
}
m++;
}
if(!flag) printf("%lld is not the sum of two primes!\n",n);
}
}
return 0;
}
|
Java
|
UTF-8
| 5,357
| 1.84375
| 2
|
[] |
no_license
|
package com.BFMe.BFMBuyer.ugc.activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.view.View;
import com.BFMe.BFMBuyer.R;
import com.BFMe.BFMBuyer.commodity.activity.ProducetDetailsActivity;
import com.BFMe.BFMBuyer.base.IBaseActivity;
import com.BFMe.BFMBuyer.javaBean.RootBean;
import com.BFMe.BFMBuyer.ugc.adapter.OfficialAdapter;
import com.BFMe.BFMBuyer.ugc.bean.OfficialBean;
import com.BFMe.BFMBuyer.utils.GlobalContent;
import com.BFMe.BFMBuyer.utils.logger.Logger;
import com.jcodecraeer.xrecyclerview.XRecyclerView;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import butterknife.BindView;
import okhttp3.Request;
/**
* 官方推荐
*/
public class OfficialActivity extends IBaseActivity {
@BindView(R.id.rv_official)
XRecyclerView rv_official;
private static final int STATE_NORMAL = 0;
private static final int STATE_REFRESH = 1;
private static final int STATE_MORE = 2;
private int state = STATE_NORMAL;
private int pageNo = 1;
private OfficialAdapter mAdapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
initView();
initData();
}
private void initData() {
getNetData();
}
private void getNetData() {
Map<String, String> params = new HashMap<>();
params.put("userId",mUserId);
params.put("pageSize","10");
params.put("pageNo",pageNo+"");
OkHttpUtils
.post()
.url(GlobalContent.POST_PUSH_RECOMMEN_MESSAGE)
.params(params)
.build()
.execute(new StringCallback() {
@Override
public void onError(Request request, Exception e) {
}
@Override
public void onResponse(String response) {
Logger.e("官方推荐=="+response);
RootBean rootBean = mGson.fromJson(response, RootBean.class);
if(rootBean.ErrCode.equals("0")) {
OfficialBean officialBean = mGson.fromJson(rootBean.Data, OfficialBean.class);
showData(officialBean.getData());
}
}
});
}
private void showData(List<OfficialBean.DataBean> data) {
switch (state) {
case STATE_NORMAL:
rv_official.setLayoutManager(new LinearLayoutManager(this));
mAdapter = new OfficialAdapter(this,data);
rv_official.setAdapter(mAdapter);
setListener();
if (data.size() < 10) {
rv_official.setNoMore(true);
}
break;
case STATE_REFRESH:
state = STATE_NORMAL;
rv_official.refreshComplete();
if (data.size() < 10) {
rv_official.setNoMore(true);
}
if (mAdapter != null) {
mAdapter.cleanData();
mAdapter.addData(data);
}
break;
case STATE_MORE:
state = STATE_NORMAL;
rv_official.loadMoreComplete();
if (mAdapter != null) {
if (data.size() < 10) {
rv_official.setNoMore(true);
}
mAdapter.addData(mAdapter.getItemCount(), data);
}
break;
}
}
private void setListener() {
rv_official.setLoadingListener(new XRecyclerView.LoadingListener() {
@Override
public void onRefresh() {
pageNo = 1;
state = STATE_REFRESH;
getNetData();
}
@Override
public void onLoadMore() {
pageNo += 1;
state = STATE_MORE;
getNetData();
}
});
mAdapter.setOnItemClickListener(new OfficialAdapter.OnItemClickListener() {
@Override
public void commodityItemClick(String commodityId) {
Intent intent = new Intent(OfficialActivity.this, ProducetDetailsActivity.class);
intent.putExtra("productId", commodityId);
startActivity(intent);
startAnim();
}
@Override
public void topicItemClick(long id) {
Intent intent = new Intent(OfficialActivity.this, TaTalkDetailsActivity.class);
intent.putExtra(GlobalContent.TOPIC_ID, id);
startActivity(intent);
startAnim();
}
});
}
private void initView() {
setBackButtonVisibility(View.VISIBLE);
String title = getIntent().getStringExtra("TITLE");
tv_title.setText(title);
rv_official.setFootViewText(getString(R.string.load), getString(R.string.no_more_data));
}
@Override
public int initLayout() {
return R.layout.activity_official;
}
}
|
Java
|
UTF-8
| 900
| 3.21875
| 3
|
[] |
no_license
|
package interviewBits.tree.treeConstruction;
import interviewBits.tree.TreeNode;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import static interviewBits.tree.treeConstruction.InOrderCartesianTree.buildTree;
/**
* Created by labuser on 8/2/17.
*/
public class SortedArratToBalancedBST {
public static TreeNode sortedArrayToBST(final List<Integer> a) {
return constructBST(a,0,a.size()-1);
}
private static TreeNode constructBST(List<Integer> a, int start, int end) {
if(start>end)
return null;
int mid=(start+end)/2;
TreeNode root= new TreeNode(a.get(mid));
root.left=constructBST(a,start,mid-1);
root.right=constructBST(a,mid+1,end);
return root;
}
public static void main(String args[]){
sortedArrayToBST(new ArrayList<Integer>(Arrays.asList(1,2,3)));
}
}
|
C++
|
UTF-8
| 1,316
| 3.21875
| 3
|
[] |
no_license
|
/**
* \file test.cpp
* \author Dennis Terhorst
* \date Wed Aug 19 18:15:03 CEST 2009
*/
/*
class screen : public ncurses_element {
void redraw() {
this->redraw_children();
ncurses::Refresh();
}
};
*/
/*
*
#include "ncurses_screen.h"
#include <string.h>
class textbox : public ncurses_element {
unsigned int myrow, mycol, myheight, mywidth;
char* text;
public:
textbox(ncurses_element* Parent, unsigned int Row, unsigned int Col,
const char* Text,
unsigned int Height=0, unsigned int Width=0) : ncurses_element(Parent) {
myrow=Row;
mycol=Col;
myheight=Height;
mywidth=Width;
text = strdup(Text);
}
virtual ~textbox() {
free(text);
}
// ncurses_element viruals:
virtual unsigned int row() { return myrow; }
virtual unsigned int column() { return mycol; }
virtual unsigned int width() { return mywidth; }
virtual unsigned int height() { return myheight; }
virtual void redraw_children() {
cerr << "textbox::redraw_children()" << endl;
cerr << "printing " << text << endl;
getScreen()(myrow, mycol) << text;
}
}; // end class textbox
*/
#include "ncurses_screen.h"
int main()
{
screen(4,3) << 41 << BOLD;
screen << 42 << COLOR(1) << NOBOLD << 43; /* Print Hello World */
screen(5,3) << NOCOLOR(1) << "Hallo Welt";
screen.redraw();
getch();
return 0;
}
|
C#
|
UTF-8
| 199
| 2.546875
| 3
|
[] |
no_license
|
public void ChangeList<T>(ref List<T> source, T value)
{
//Actions
source = new List<T>; // or initialize using API/DB call
source.Add(value);
//Actions
}
|
Java
|
UTF-8
| 1,379
| 3.421875
| 3
|
[] |
no_license
|
package ex1.part2;
import java.util.ArrayList;
import java.util.Random;
/**
* Created by mipopescu on 7/20/2016.
*/
public class Main {
public static final int PROBLEM_SIZE = 100000;
public static final int N_THREADS = 4;
public static final long RANDOM_SEED = 7;
public static void main(String[] args) {
Random random = new Random(RANDOM_SEED);
int[] input = new int[PROBLEM_SIZE];
ArrayList<Integer> output = new ArrayList<>();
for (int i = 0; i < PROBLEM_SIZE; i++) {
input[i] = Math.abs(random.nextInt());
}
PrimeNumberThread[] threads = new PrimeNumberThread[N_THREADS];
long start = System.currentTimeMillis();
/* Create threads */
for (int i = 0; i < N_THREADS; i++) {
threads[i] = new PrimeNumberThread(input, output, i,
PROBLEM_SIZE, N_THREADS);
}
/* Start threads */
for (int i = 0; i < N_THREADS; i++) {
threads[i].run();
}
/* Wait for threads to finish their work */
for (int i = 0; i < N_THREADS; i++) {
try {
threads[i].join();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
long stop = System.currentTimeMillis();
System.out.println(stop - start);
}
}
|
JavaScript
|
UTF-8
| 1,696
| 2.578125
| 3
|
[] |
no_license
|
import { zeroFill } from "./Utils";
import { uploadLogContent } from "./cFetch";
class LogUtil {
static DEBUG = 0;
static INFO = 1;
static WARN = 2;
static ERROR = 3;
static debug = false;
static mqttDebug = false;
static limit = false;
static limitNum = 100;
static uploadNum = 20;
}
let logs = [];
LogUtil.trace = function(category, level, log) {
if(!LogUtil.debug || !log || log.length <= 0)
return;
let info = time() + " ";
if(Array.isArray(log))
{
log = log.map(item => ((typeof item !== "string" && JSON.stringify(item)) || item))
.join(" ");
}
if(LogUtil.limit && log.length > LogUtil.limitNum)
{
log = log.substr(0, LogUtil.limitNum);
}
switch(level)
{
case LogUtil.INFO:
info += "[INFO]" + info + " " + category + " " + log;
console.info(info);
break;
case LogUtil.DEBUG:
info += "[DEBUG]" + info + " " + category + " " + log;
console.debug(info);
break;
case LogUtil.WARN:
info += "[WARN]" + info + " " + category + " " + log;
console.warn(info);
break;
case LogUtil.ERROR:
info += "[ERROR]" + info + " " + category + " " + log;
console.error(info);
break;
}
return;
logs.push({[level]: info});
if(logs.length > LogUtil.uploadNum)
{
uploadLogContent(JSON.stringify(logs));
logs = [];
}
};
let padTime = function(number) {
return zeroFill(number, 2);
};
function time()
{
let date = new Date(),
now = date.getFullYear() + "-" + (date.getMonth() + 1) + "-" +
date.getDate() + " " + padTime(date.getHours()) + "-" +
padTime(date.getMinutes()) + "-" +
padTime(date.getSeconds()) + "-" +
padTime(date.getMilliseconds(), true);
return now;
};
export default LogUtil;
|
Python
|
UTF-8
| 1,446
| 2.578125
| 3
|
[] |
no_license
|
# https://atcoder.jp/contests/abc187/tasks/abc187_d
# # def input(): return sys.stdin.readline().rstrip()
# # input = sys.stdin.readline
# from numba import njit
# from functools import lru_cache
# sys.setrecursionlimit(10 ** 7)
# from itertools import product
import sys
input = sys.stdin.buffer.readline
diff = []
suma = 0
n = int(input())
for i in range(n):
a, b = map(int, input().split())
diff.append(2*a+b)
suma -= a
diff.sort(reverse=True)
for i in range(n):
suma += diff[i]
if suma > 0:
ans = i+1
break
print(ans)
# S = input()
# n = int(input())
# N, K = map(int, input().split())
# l = list(map(int, (input().split())))
# A = [[int(i) for i in input().split()] for _ in range(N)]
# @njit('(i8,i8[::1],i4[::1])', cache=True)
# def main():
# @lru_cache(None)
# def dfs():
# return
# return
# main()
# TLE
# import sys
# input = sys.stdin.buffer.readline
# import copy
# INF = 1001001001001001
# n = int(input())
# dp = [-INF]*(n+1)
# dp[0] = 0
# for i in range(n):
# dpnext = [-INF]*(n+1)
# a, b = map(int, input().split())
# for j in range(n+1):
# if j:
# dpnext[j] = max(dp[j]-a, dp[j-1]+a+b)
# else:
# dpnext[j] = dp[j]-a
# dp = copy.copy(dpnext)
# ans = n
# for i in range(n+1):
# if dp[i] > 0:
# ans = i
# break
# print(ans)
|
Python
|
UTF-8
| 2,546
| 2.515625
| 3
|
[] |
no_license
|
#!/usr/bin/env python
# =============================================================================
#
# Consume messages from Confluent Cloud
# Using Confluent Python Client for Apache Kafka
#
# =============================================================================
from confluent_kafka import Consumer, TopicPartition
from factory import create_consumer
import json
import logging
import threading
import ccloud_lib
import sys
def consume_msg(consumer, topic, consumer_name, partition=-1):
# Subscribe to topic
consumer.subscribe([topic])
if partition > 0:
consumer.assign([TopicPartition(topic, partition)])
# Process messages
total_count = 0
try:
while True:
msg = consumer.poll(1.0)
if msg is None:
logging.info("[{}] Waiting for message or event/error in poll()"
.format(consumer_name))
elif msg.error():
logging.info('[{}] error: {}'.format(consumer_name, msg.error()))
else:
# Check for Kafka message
record_key = msg.key()
record_value = msg.value()
total_count += 1
logging.info("[{}] Consumed record with key {} and value {}, \
and updated total count to {}"
.format(consumer_name, record_key, record_value, total_count))
except KeyboardInterrupt:
pass
finally:
# Leave group and commit final offsets
logging.info("{} consumed {} message in total"
.format(consumer_name, total_count))
consumer.close()
if __name__ == '__main__':
#logging.basicConfig(filename='./consumer.log', level=logging.DEBUG)
logging.basicConfig(stream=sys.stdout, level=logging.DEBUG)
# Read arguments and configurations and initialize
args = ccloud_lib.parse_args()
config_file = args.config_file
topic = args.topic
n_consumer = args.nthread
random_key = args.random
group_id = args.groupid
partition_id = -1
if random_key:
partition_id = args.key
# Create Consumer instance
consumers = [create_consumer(config_file, group_id) for _ in range(0, n_consumer)]
threads = [threading.Thread(
target=consume_msg,
args=(consumers[i], topic, "consumer{}".format(i), partition_id))
for i in range(0, n_consumer)]
for t in threads:
t.start()
for t in threads:
t.join()
|
Java
|
UTF-8
| 4,979
| 2.046875
| 2
|
[] |
no_license
|
package com.quark.wificontrol.ui.user;
import android.graphics.Paint;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.quark.api.auto.bean.GetTryCodeRequest;
import com.quark.api.auto.bean.GetTryCodeResponse;
import com.quark.api.auto.bean.TryUseRequest;
import com.quark.api.auto.bean.TryUseResponse;
import com.quark.wificontrol.AppContext;
import com.quark.wificontrol.R;
import com.quark.wificontrol.api.ApiResponse;
import com.quark.wificontrol.api.remote.QuarkApi;
import com.quark.wificontrol.base.BaseActivity;
import com.quark.wificontrol.util.UIHelper;
import com.quark.wificontrol.util.Utils;
import butterknife.ButterKnife;
import butterknife.InjectView;
import butterknife.OnClick;
import cz.msebera.android.httpclient.Header;
/**
* Created by pan on 2016/9/9 0009.
* >#
* >游客试用
*/
public class TouristsActivity extends BaseActivity {
@InjectView(R.id.user_et)
EditText userEt;
@InjectView(R.id.code_et)
EditText codeEt;
@InjectView(R.id.go_bt)
Button goBt;
@InjectView(R.id.get_code)
TextView getCode;
Handler handlercode;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_tourists);
ButterKnife.inject(this);
handlercode = new Handler();
getCode.getPaint().setFlags(Paint.UNDERLINE_TEXT_FLAG); //下划线
getCode.getPaint().setAntiAlias(true);//抗锯齿
}
@Override
public void initView() {
}
@Override
public void initData() {
}
@OnClick({R.id.get_code, R.id.go_bt})
public void onClick(View view) {
switch (view.getId()) {
case R.id.get_code:
if (Utils.isEmpty(userEt.getText().toString())) {
showToast("请输入手机号码");
} else {
getCodeRequest();
}
break;
case R.id.go_bt:
if (check()) {
tryRequest();
}
break;
}
}
private boolean check() {
if (Utils.isEmpty(userEt.getText().toString())) {
showToast("请输入手机号码");
return false;
}
if (Utils.isEmpty(codeEt.getText().toString())) {
showToast("请输入试用码");
return false;
}
return true;
}
/**
* 获取试用码
*
* @author pan
* @time 2016/10/9 0009 下午 2:51
*/
public void getCodeRequest() {
GetTryCodeRequest rq = new GetTryCodeRequest();
rq.setTelephone(userEt.getText().toString());
showWait(true);
QuarkApi.HttpRequestNewList(rq, mHandlerget);
UIHelper.countdddd(getCode, handlercode, this, false);
}
private final AsyncHttpResponseHandler mHandlerget = new AsyncHttpResponseHandler() {
@Override
public void onSuccess(int arg0, Header[] arg1, byte[] arg2) {
Object kd = ApiResponse.get(arg2, TouristsActivity.this, GetTryCodeResponse.class);
if (kd != null) {
GetTryCodeResponse info = (GetTryCodeResponse) kd;
if (info.getStatus() == 1) {
} else {
showToast(info.getMessage());
}
}
showWait(false);
}
@Override
public void onFailure(int arg0, Header[] arg1, byte[] arg2, Throwable arg3) {
AppContext.showToast("网络出错" + arg0);
UIHelper.countdddd(getCode, handlercode, TouristsActivity.this, false);
showWait(false);
}
};
public void tryRequest() {
TryUseRequest rq = new TryUseRequest();
rq.setTelephone(userEt.getText().toString());
rq.setTel_code(codeEt.getText().toString());
showWait(true);
QuarkApi.HttpRequestNewList(rq, mHandleruser);
}
private final AsyncHttpResponseHandler mHandleruser = new AsyncHttpResponseHandler() {
@Override
public void onSuccess(int arg0, Header[] arg1, byte[] arg2) {
Object kd = ApiResponse.get(arg2, TouristsActivity.this, TryUseResponse.class);
if (kd != null) {
TryUseResponse info = (TryUseResponse) kd;
if (info.getStatus() == 1) {
startActivityByClass(TrialActivity.class);
} else {
showToast(info.getMessage());
}
}
showWait(false);
}
@Override
public void onFailure(int arg0, Header[] arg1, byte[] arg2, Throwable arg3) {
AppContext.showToast("网络出错" + arg0);
showWait(false);
}
};
}
|
Python
|
UTF-8
| 1,378
| 3.5625
| 4
|
[] |
no_license
|
import csv
import matplotlib.pylab as plt
#import pylab as pl
import operator
csvfile = open("firebug2.csv", 'r')
myDict = {}
for line in csvfile.readlines():
#print(line)
array = line.split(',')
if array[3] in myDict:
myDict[array[3]] = myDict[array[3]]+1
else:
myDict[array[3]] = 1
for k, v in myDict.items():
print(k, v)
for key in sorted(myDict, key=myDict.get): #for key in sorted(myDict, key=lambda k: myDict[k]):
print(key, myDict[key])
print(len(myDict))
#print (myDict.items(), myDict.keys(), myDict.values())
# https://stackoverflow.com/questions/12791923/using-sorted-in-python --> using lambda
# It is not possible to sort a dict, only to get a representation of a dict that is sorted.
# Dicts are inherently orderless, but other types, such as lists and tuples, are not.
# So you need a sorted representation, which will be a list—probably a list of tuples.
components_sorted_by_frequency = sorted(myDict.items(), key=operator.itemgetter(1)) # sorted by value, return a list of tuples
#print(components_sorted_by_frequency)
top_components = components_sorted_by_frequency[-10:]
print(top_components)
x, y = zip(*top_components) # unpack a list of pairs into two tuples
#plt.plot(x, y)
#plt.show()
plt.xticks(range(len(top_components)), x, rotation=45) #writes strings with 45 degree angle
plt.bar(range(len(top_components)),y)
plt.show()
|
Shell
|
UTF-8
| 571
| 3.25
| 3
|
[] |
no_license
|
#!/bin/bash
echo "Getting public key from Sealed Secrets secret and copying it to ~/bitnami"
echo "Create dir for Sealed Secrets public key. (~/bitnami)."
mkdir -p ~/.bitnami
echo "Backup secret itself"
oc get secret -o yaml -n sealed-secrets -l sealedsecrets.bitnami.com/sealed-secrets-key=active > ~/.bitnami/sealed-secrets-secret.yaml
echo "Get the public key from the Sealed Secrets secret."
oc get secret -o yaml -n sealed-secrets -l sealedsecrets.bitnami.com/sealed-secrets-key=active | grep tls.crt | cut -d' ' -f6 | base64 --decode > ~/.bitnami/publickey.pem
|
Java
|
UTF-8
| 271
| 2.546875
| 3
|
[] |
no_license
|
package Algorithm;
public class D2_LS2 {
public static void main(String[] args) {
LinearSearch2 ls2 = new LinearSearch2();
ls2.add(1, "one");
ls2.add(10, "ten");
ls2.add(2, "two");
System.out.println(ls2.search(10));
}
}
|
Java
|
UTF-8
| 191
| 1.953125
| 2
|
[] |
no_license
|
package Cupones;
import Envio.EnvioInternacional;
import Envio.EnvioLocal;
public class MerryChristmas extends Cupon {
public MerryChristmas(){
this.descuento = 0.25;
}
}
|
Java
|
UTF-8
| 9,336
| 2.046875
| 2
|
[] |
no_license
|
package com.cai.http.action;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
import com.cai.common.constant.RMICmd;
import com.cai.common.define.IPhoneOperateType;
import com.cai.common.domain.Account;
import com.cai.common.domain.AccountMobileModel;
import com.cai.common.rmi.vo.UserPhoneRMIVo;
import com.cai.common.util.Pair;
import com.cai.common.util.SpringService;
import com.cai.http.FastJsonJsonView;
import com.cai.http.model.ErrorCode;
import com.cai.http.security.SignUtil;
import com.cai.rmi.impl.CenterRMIServerImpl;
import com.cai.service.PhoneService;
import com.cai.service.PublicServiceImpl;
@Controller
@RequestMapping("/phone")
public class PhoneController {
public static final int FAIL = 0;
public static final int SUCCESS = 1;
// 绑定手机到账号上
public static final int TYPE_BIND = 1;
// 解绑
public static final int TYPE_UNBIND = 2;
// 查看绑定状态
public static final int TYPE_BIND_STATE = 3;
// 手机号登录
public static final int TYPE_PHONE_LOGIN = 4;
// 通过手机号绑定公众号
public static final int TYPE_BAND_WX_OFFICAL = 5;
// 通过手机号查看是否已经绑定公众号
public static final int TYPE_BAND_WX_OFFICAL_STATE = 6;
//查看公众号openId是否绑定过账号
public static final int TYPE_WX_BAND_STATE = 7;
//解绑公众号绑定
public static final int TYPE_UNBIND_OPENID = 8;
// 钻石黄金推广员----我的会员代理
@RequestMapping("/operate")
public ModelAndView handle(HttpServletRequest request, HttpServletResponse response) {
Map<String, String> params = SignUtil.getParametersHashMap(request);
String queryType = params.get("queryType");
Map<String, Object> resultMap = new HashMap<String, Object>();
String accountId = params.get("account_id");
String mobile = params.get("mobile");
String openId = params.get("openId");
int type;
long account_id = 0;
try {
if (StringUtils.isNotBlank(accountId)) {
account_id = Long.parseLong(accountId);
}
type = Integer.parseInt(queryType);
} catch (NumberFormatException e) {
resultMap.put("msg", "参数异常");
resultMap.put("result", FAIL);
return new ModelAndView(new FastJsonJsonView(), resultMap);
}
if (type == TYPE_BIND) {
bind(mobile, account_id, resultMap);
} else if (type == TYPE_UNBIND) {
unbind(mobile, account_id, resultMap);
} else if (type == TYPE_BIND_STATE) {
bindState(mobile, account_id, resultMap);
} else if (type == TYPE_PHONE_LOGIN) {
phoneLogin(mobile, resultMap);
} else if (type == TYPE_BAND_WX_OFFICAL) {
bindWx(mobile, openId, resultMap);
}else if (type == TYPE_BAND_WX_OFFICAL_STATE) {
bindWxState(mobile, openId, resultMap);
}else if (type == TYPE_WX_BAND_STATE) {
bindOpenIdState(openId, resultMap);
}else if (type == TYPE_UNBIND_OPENID) {
unBindOpenIdState(openId,mobile, resultMap);
}
return new ModelAndView(new FastJsonJsonView(), resultMap);
}
private void bind(String mobile, long account_id, Map<String, Object> resultMap) {
CenterRMIServerImpl centerRMIServer = SpringService.getBean(CenterRMIServerImpl.class);
UserPhoneRMIVo vo = UserPhoneRMIVo.newVo(IPhoneOperateType.BIND, account_id, mobile);
Pair<Integer, String> r = centerRMIServer.rmiInvoke(RMICmd.ACCOUNT_PHONE, vo);
if (r.getFirst().intValue() == SUCCESS) {
resultMap.put("result", SUCCESS);
} else {
resultMap.put("result", FAIL);
resultMap.put("msg", r.getSecond());
}
}
private void unbind(String mobile, long account_id, Map<String, Object> resultMap) {
CenterRMIServerImpl centerRMIServer = SpringService.getBean(CenterRMIServerImpl.class);
UserPhoneRMIVo vo = UserPhoneRMIVo.newVo(IPhoneOperateType.UN_BIND, account_id, mobile);
Pair<Integer, String> r = centerRMIServer.rmiInvoke(RMICmd.ACCOUNT_PHONE, vo);
if (r.getFirst().intValue() == SUCCESS) {
resultMap.put("result", SUCCESS);
} else {
resultMap.put("result", FAIL);
resultMap.put("msg", r.getSecond());
}
}
private void bindState(String mobile, long account_id, Map<String, Object> resultMap) {
CenterRMIServerImpl centerRMIServer = SpringService.getBean(CenterRMIServerImpl.class);
UserPhoneRMIVo vo = UserPhoneRMIVo.newVo(IPhoneOperateType.BIND_INFO, account_id, mobile);
Pair<Integer, String> r = centerRMIServer.rmiInvoke(RMICmd.ACCOUNT_PHONE, vo);
if (r.getFirst().intValue() == SUCCESS) {
resultMap.put("result", SUCCESS);
} else {
resultMap.put("result", FAIL);
resultMap.put("msg", r.getSecond());
}
}
private void phoneLogin(String mobile, Map<String, Object> resultMap) {
Optional<AccountMobileModel> phoneOpt = PhoneService.getInstance().getPhoneModelByMobileNum(mobile);
if (phoneOpt.isPresent()) {
Account account = PublicServiceImpl.getInstance().getAccount(phoneOpt.get().getAccount_id());
if (account == null || account.getAccountWeixinModel() == null) {
resultMap.put("result", FAIL);
resultMap.put("msg", ErrorCode.ROLE_FIND_FAIL);
return;
}
resultMap.put("userId", account.getAccountWeixinModel().getAccount_id());
resultMap.put("result", SUCCESS);
resultMap.put("nickName", account.getAccountWeixinModel().getNickname());
resultMap.put("isAgent", account.getAccountModel().getIs_agent());
resultMap.put("headUrl", account.getAccountWeixinModel().getHeadimgurl());
resultMap.put("gold", account.getAccountModel().getGold());
resultMap.put("upAgent", account.getAccountModel().getUp_proxy());
resultMap.put("unionid", account.getAccountWeixinModel().getUnionid());
resultMap.put("totalConsum", account.getAccountModel().getConsum_total());
resultMap.put("is_rebate", account.getAccountModel().getIs_rebate());
resultMap.put("banned", account.getAccountModel().getBanned());
resultMap.put("mobile", account.getAccountModel().getMobile_phone());
if (account.getHallRecommendModel() != null) {
resultMap.put("hall_recommend_level", account.getHallRecommendModel().getRecommend_level());
} else {
resultMap.put("hall_recommend_level", 0);
}
}
}
private void bindWx(String mobile, String openId, Map<String, Object> resultMap) {
UserPhoneRMIVo vo = UserPhoneRMIVo.newVo(IPhoneOperateType.BIND_INFO, 0, mobile);
CenterRMIServerImpl centerRMIServer = SpringService.getBean(CenterRMIServerImpl.class);
Pair<Integer, String> r = centerRMIServer.rmiInvoke(RMICmd.ACCOUNT_PHONE, vo);
if (r.getFirst() == SUCCESS) {
Map<String, String> map = new HashMap<>();
map.put("mobile", mobile);
map.put("openId", openId);
map.put("accountId", r.getSecond());
int res = centerRMIServer.rmiInvoke(RMICmd.BIND_WX_OFFICAL, map);
if (res == SUCCESS) {
resultMap.put("result", SUCCESS);
} else {
resultMap.put("result", FAIL);
resultMap.put("msg", r.getSecond());
}
}else{
resultMap.put("result", FAIL);
resultMap.put("msg", "请先在游戏内绑定您的手机号再来使用此功能!");
}
}
private void bindWxState(String mobile, String openId, Map<String, Object> resultMap) {
UserPhoneRMIVo vo = UserPhoneRMIVo.newVo(IPhoneOperateType.BIND_INFO, 0, mobile);
CenterRMIServerImpl centerRMIServer = SpringService.getBean(CenterRMIServerImpl.class);
Pair<Integer, String> r = centerRMIServer.rmiInvoke(RMICmd.ACCOUNT_PHONE, vo);
if (r.getFirst() == SUCCESS) {
Map<String, String> map = new HashMap<>();
map.put("mobile", mobile);
map.put("openId", openId);
map.put("accountId", r.getSecond());
map.put("type", "1");
int res = centerRMIServer.rmiInvoke(RMICmd.BIND_WX_OFFICAL, map);
if (res == SUCCESS) {
resultMap.put("result", SUCCESS);
} else {
resultMap.put("result", FAIL);
resultMap.put("msg", r.getSecond());
}
}else{
resultMap.put("result", FAIL);
resultMap.put("msg", "请先在游戏内绑定您的手机号再来使用此功能!");
}
}
private void bindOpenIdState(String openId, Map<String, Object> resultMap) {
CenterRMIServerImpl centerRMIServer = SpringService.getBean(CenterRMIServerImpl.class);
Map<String, String> map = new HashMap<>();
map.put("openId", openId);
map.put("type", "2");
int res = centerRMIServer.rmiInvoke(RMICmd.BIND_WX_OFFICAL, map);
if (res == SUCCESS) {
resultMap.put("result", SUCCESS);
} else {
resultMap.put("result", FAIL);
}
}
private void unBindOpenIdState(String openId,String mobile, Map<String, Object> resultMap) {
CenterRMIServerImpl centerRMIServer = SpringService.getBean(CenterRMIServerImpl.class);
Map<String, String> map = new HashMap<>();
map.put("openId", openId);
map.put("type", "3");
map.put("mobile", mobile);
int res = centerRMIServer.rmiInvoke(RMICmd.BIND_WX_OFFICAL, map);
if (res == SUCCESS) {
resultMap.put("result", SUCCESS);
} else {
resultMap.put("result", FAIL);
}
}
}
|
PHP
|
UTF-8
| 8,640
| 2.921875
| 3
|
[
"MIT"
] |
permissive
|
<?php namespace Ixudra\Core\Console\Commands;
use Carbon\Carbon;
use Illuminate\Console\Command as LaravelCommand;
use Illuminate\Support\MessageBag;
use Symfony\Component\Console\Output\OutputInterface;
use DB;
use Exception;
abstract class BaseCommand extends LaravelCommand {
/** @var MessageBag Error messages that have been collected during the command execution */
protected $messages;
/** @var Carbon Timestamp when the command started execution of the main task */
protected $startTime;
/** @var Carbon Timestamp when the command finished execution of the main task */
protected $endTime;
public function __construct()
{
parent::__construct();
$this->messages = new MessageBag();
}
/**
* Fire the artisan command. When using this class as a base class, the fire or handle method should not be included
* in your command as this will make this base class obsolete. Instead, you should implement the executeCommand and
* move all your production code there. It will then be picked up by the fire() method and executed correctly.
*/
public function handle()
{
$isSuccessful = true;
// Register the time when the command started execution of the main task
$this->startTime = Carbon::now();
try {
// Execute the main task of the command
$this->executeCommand();
} catch(Exception $e) {
$isSuccessful = false;
}
// Register the time when the main task of the command was completed
$this->endTime = Carbon::now();
DB::table('command_history')->insert(
array(
'command' => $this->getFullCommandName(),
'start_time' => $this->startTime,
'end_time' => $this->endTime,
'is_successful' => $isSuccessful,
)
);
$this->printReport();
}
/**
* Execute the main task of the artisan command. This method should contain all the production code that needs to
* be executed when the command is triggered via artisan
*/
abstract protected function executeCommand();
/**
* Reconstruct the full command name (including arguments and options) so we can store it in the database and check
* it later if an error has occurred
*
* @return string
*/
protected function getFullCommandName()
{
$name = $this->name;
foreach( $this->getArguments() as $argument ) {
$argumentName = $argument[ 0 ];
$argumentValue = $this->input->getArgument($argumentName);
if( strpos($this->name, '{'. $argumentName .'}') !== false ) {
$name = str_replace('{'. $argumentName .'}', $argumentValue, $this->name);
} else {
$name .= ' '. $argumentValue;
}
}
foreach( $this->getOptions() as $option ) {
$key = $option[ 0 ];
$name .= ' --'. $key .'='. $this->input->getOption( $key );
}
return $name;
}
/**
* Print a message indicating that the command has started processing an entry in the data set that is being
* processed. This can be used to easily notify the user of the progress of the artisan command
*
* @param array $context Contains a list of parameters that can be used to provide more useful information to the user
*/
protected function printStartMessage(array $context = array())
{
if( $this->getOutput()->getVerbosity() >= OutputInterface::VERBOSITY_VERY_VERBOSE ) {
$this->info( $this->getStartMessage( $context ) );
}
}
/**
* Build a message indicating that the command has started processing an entry in the data set that is being
* processed. This can be used to easily notify the user of the progress of the artisan command
*
* @param array $context Contains a list of parameters that can be used to provide more useful information to the user
*/
abstract protected function getStartMessage(array $context = array());
/**
* Print a message indicating that the command has skipped processing an entry in the data set that is being
* processed. This can be used to easily notify the user of the progress of the artisan command
*
* @param array $context Contains a list of parameters that can be used to provide more useful information to the user
*/
protected function printSkippedMessage(array $context = array())
{
if( $this->getOutput()->getVerbosity() >= OutputInterface::VERBOSITY_VERY_VERBOSE ) {
$this->info( $this->getSkippedMessage( $context ) );
}
}
/**
* Build a message indicating that the command has started processing an entry in the data set that is being
* processed. This can be used to easily notify the user of the progress of the artisan command
*
* @param array $context Contains a list of parameters that can be used to provide more useful information to the user
*/
abstract protected function getSkippedMessage(array $context = array());
/**
* Print a message indicating that the command has successfully processed an entry in the data set that is being
* processed. This can be used to easily notify the user of the progress of the artisan command
*
* @param array $context Contains a list of parameters that can be used to provide more useful information to the user
*/
protected function printSuccessMessage(array $context = array())
{
if( $this->getOutput()->getVerbosity() >= OutputInterface::VERBOSITY_VERY_VERBOSE ) {
$this->info( $this->getSuccessMessage( $context ) );
} else if( $this->getOutput()->getVerbosity() >= OutputInterface::VERBOSITY_VERBOSE ) {
$this->output->write('.');
}
}
/**
* Build a message indicating that the command has successfully processed an entry in the data set that is being
* processed. This can be used to easily notify the user of the progress of the artisan command
*
* @param array $context Contains a list of parameters that can be used to provide more useful information to the user
*/
abstract protected function getSuccessMessage(array $context = array());
/**
* Print a message indicating that the command has failed to process an entry in the data set that is being
* processed. This can be used to easily notify the user of the progress of the artisan command
*
* @param array $context Contains a list of parameters that can be used to provide more useful information to the user
*/
protected function printErrorMessage(array $context = array())
{
if( $this->getOutput()->getVerbosity() >= OutputInterface::VERBOSITY_VERY_VERBOSE ) {
$this->error( $this->getErrorMessage( $context ) );
} else if( $this->getOutput()->getVerbosity() >= OutputInterface::VERBOSITY_VERBOSE ) {
$this->output->write('<error>F</error>');
}
}
/**
* Build a message indicating that the command has failed to process an entry in the data set that is being
* processed. This can be used to easily notify the user of the progress of the artisan command
*
* @param array $context Contains a list of parameters that can be used to provide more useful information to the user
*/
abstract protected function getErrorMessage(array $context = array());
/**
* Print a concise report describing if and which errors have occurred during the execution of the artisan command
*/
protected function printReport()
{
$this->line(' --- ');
if( !$this->errorOccurred() ) {
$this->info('0 errors encountered.');
} else {
$this->error( count($this->messages->get('error')) .' error(s) encountered' );
foreach( $this->messages->get('error') as $error ) {
$this->error( $error );
}
}
}
/**
* @return bool
*/
protected function errorOccurred()
{
return $this->messages->has('error');
}
/**
* @param string $message The error message that is supposed to be registered and returned to the user after execution is completed
*/
protected function addError($message)
{
$this->messages->add( 'error', $message );
}
}
|
Python
|
UTF-8
| 8,487
| 2.9375
| 3
|
[] |
no_license
|
import pandas as pd
import numpy as np
from collections import Counter
from itertools import chain
import pickle
import operator
import gensim
from gensim.models import Word2Vec
from nltk.tokenize import sent_tokenize, word_tokenize
import warnings
import sys
import math
import os
from langdetect import detect
from langdetect import DetectorFactory
import re
from urllib.parse import urlparse
import difflib
from spellchecker import SpellChecker
# Creates a Word2Vec Model and saves it as a bin file
class Word2Vec_Model:
'''
Object that creates a Word2Vec Model and saves it as a bin file. Uses the data
created in the subreddit_data_to_csv.py file and parses it for punctuation for
easier manipulation. The parsed sentences are saved as a pickle file for
retrevial later.
Parameters:
csv_file (str) : csv file created by the subreddit_data_to_csv.py file
'''
def __init__(self, csv_file):
self.csv_filename = csv_file
self.model_name = csv_file[:-4] + '_W2VModel'
if os.path.isfile(self.model_name + '.bin'):
print('Model already exis for this time range')
else:
print('Model doesn\'t exist, creating model')
if os.path.isfile(self.csv_filename[:-4] + '_sent.pkl'):
print('Pickle file found')
self.df = pd.read_pickle(csv_file[:-4] + '_sent.pkl')
self.words = self.df['sent'].to_list()
else:
self.data = pd.read_csv(csv_file, header=0)
self.df = self.word_array(self.data)
self.words = self.df['sent'].to_list()
self.create_model(self.words, self.model_name)
def create_model(self, words, model_name):
data = []
s = ' '
for item in words:
sent = s.join(item)
for i in sent_tokenize(sent):
temp = []
for j in word_tokenize(i):
temp.append(j.lower())
data.append(temp)
model = Word2Vec(words, min_count=1, size=100, window=5, sg=1)
model.wv.save_word2vec_format(f'Models\\{model_name}.bin', binary=True)
return model
def word_array(self, data, pkl=True):
DetectorFactory.seed = 0
sentences = pd.DataFrame(columns=['title', 'sent', 'url'])
words = 0
for i, (title, url) in enumerate(zip(data['title'], data['url'])):
try:
if detect(title) != 'en':
del df[i]
except:
pass
word_line = []
word_line_punct = list(re.split(r'\s+', title))
for word in word_line_punct:
word_punct = list(filter(None, re.split(r'(^(?:[A-Z]*[a-z]+\'[st])|^(?:[A-Z]*[a-z]+[s]\')|^(?:[A-Z]\.){1,2}|[^a-zA-Z])', word)))
for elem in word_punct:
punct_match = re.match(r'[^a-zA-Z0-9]', elem)
if punct_match != None:
pass
else:
word_line.append(elem.lower())
words += 1
url = urlparse(url).hostname
sentences.at[i, 'title'] = title
sentences.at[i, 'sent'] = word_line
sentences.at[i, 'url'] = url
pick_filename = str(self.csv_filename)[:-4] + '_sent.pkl'
#pickle the word list
if pickle:
sentences.to_pickle(pick_filename, protocol=4)
print(f'Pickle file added {pick_filename}')
return sentences
# reads a Word2Vec Model and compares sentences using it
class Compare_Headlines:
'''
Object that finds the cosine similarity between the subreddit titles given in
the title variable, calculated with the use of the model defined in model_name.
These are the models created by the Word2Vec_Model Object.
Parameters:
model_name (str) : name of the model you want to use to find the cosine similarity.
The titles should not be included in the model
titles (list of strings) : The title strings that you want to find the cosine
similarity of. If there are more than 2 titles you will get the cosine
similarity of all of the groupings.
'''
def __init__(self, model_name, titles):
self.model = self.read_model(model_name)
self.pickle_file = model_name[:-9] + '_sent.pkl'
self.vectors, self.titles = self.TDIDF_Sentence_Vectors(model_name, titles)
def read_model(self, model_name):
model = gensim.models.KeyedVectors.load_word2vec_format(model_name + '.bin', binary=True)
return model
def TDIDF_count(self, sent_words):
rawcount_dict = dict(Counter(chain.from_iterable(sent_words)))
TF_dict = dict(Counter(chain.from_iterable(set(i) for i in sent_words)))
dict_list = list()
for sent in sent_words:
count_list = list()
for elem in sent:
count = rawcount_dict[elem]/len(sent)
count_list.append(count)
sent_dict = dict(zip(sent, count_list))
dict_list.append(sent_dict)
return dict_list, TF_dict
def TDIDF_Sentence_Vectors(self, model_name, titles):
model = self.read_model(model_name)
sent_words = pd.read_pickle(self.pickle_file)
_, TF_dict = self.TDIDF_count(sent_words['sent'].to_list())
sent_vectors =[]
sentences = []
titles = Eleminate_Punctuation().eleminate_punctuation(titles)['sent'].to_list()
for item in titles:
weights = []
w2v_vectors = []
weighted_vectors = []
for j, i in enumerate(item):
try:
word_vector = model[i]
weight = TF_dict[i]
except:
word = list(set(difflib.get_close_matches(i, [item for sublist in sent_words['sent'].to_list() for item in sublist])))
for element in word:
word = SpellChecker().correction(element)
word_vector = model[word]
weight = TF_dict[word]
item[j] = word
weights.append(weight)
w2v_vectors.append(word_vector)
for index, j in enumerate(w2v_vectors):
TD_vector = weights[index]*j
weighted_vectors.append(TD_vector)
sent_vector = np.zeros(shape=TD_vector.shape)
for word_vector in weighted_vectors:
sent_vector = np.add(sent_vector, word_vector)
sent_vectors.append(sent_vector)
sentences.append(' '.join(item))
sent_vector_dict = dict(zip(sentences, sent_vectors))
titles = [' '.join(item) for item in titles]
return sent_vector_dict, titles
def CosineSimilarity(self, sent_vector_dict, sent1, sent2):
vector1 = sent_vector_dict[sent1]
vector2 = sent_vector_dict[sent2]
dot_product = np.dot(vector1, vector2)
mag1 = np.linalg.norm(vector1)
mag2 = np.linalg.norm(vector2)
cos_sim = dot_product / (mag1*mag2)
return cos_sim
# object used to manipulate sentences to eleminate punctuation
class Eleminate_Punctuation:
'''
Object that takes a list of string sentences and returns a list
of lists that contain the words in the sentences without punctuation.
Parameters:
string_list (list of sentence strings) : list of sentence strings to have
their punctuation eleminated.
'''
def eleminate_punctuation(self, string_list):
DetectorFactory.seed = 0
sentences = pd.DataFrame(columns=['sent'])
for i, item in enumerate(string_list):
word_line = []
word_line_punct = list(re.split(r'\s+', item))
for word in word_line_punct:
word_punct = list(filter(None, re.split(r'(^(?:[A-Z]*[a-z]+\'[st])|^(?:[A-Z]*[a-z]+[s]\')|^(?:[A-Z]\.){1,2}|[^a-zA-Z])', word)))
for elem in word_punct:
punct_match = re.match(r'[^a-zA-Z0-9]', elem)
if punct_match != None:
pass
else:
word_line.append(elem.lower())
sentences.at[i, 'sent'] = word_line
return sentences
|
JavaScript
|
UTF-8
| 1,447
| 4.125
| 4
|
[] |
no_license
|
// Sum of Two Integers
//
// Calculate the sum of two integers a and b, but you are not allowed to use
// the operator + and -
//
// ex. Given a = 1 and b = 2, return 3.
//
// @flow
type num = number;
export default function SumTimelineMethod(first: num, second: num): num {
const _first = new Array(Math.abs(first));
const _second = new Array(Math.abs(second));
const negatives = [];
const positives = [];
while (_first.length !== 0) {
// first is positive
if (_first.length > 0 && first > 0 && negatives.length === 0) {
positives.push("-");
} else if (first > 0 && negatives.length > 0) {
negatives.splice(0, 1);
// first is negative
} else if (first < 0 && positives.length === 0) {
negatives.push("-");
} else if (first < 0 && positives.length > 0) {
positives.splice(0, 1);
}
_first.splice(0, 1);
}
while (_second.length !== 0) {
if (_second.length > 0 && second > 0 && negatives.length === 0) {
positives.push("-");
} else if (second > 0 && negatives.length > 0) {
negatives.splice(0, 1);
// second is negative
} else if (second < 0 && positives.length === 0) {
negatives.push("-");
} else if (second < 0 && positives.length > 0) {
positives.splice(0, 1);
}
_second.splice(0, 1);
}
return positives.length === 0
? negatives.length === 0
? 0
: negatives.length * -1
: positives.length;
}
|
Java
|
UTF-8
| 267
| 1.820313
| 2
|
[] |
no_license
|
package com.tyr.note.Service;
import com.tyr.note.entity.NoteResult;
public interface UserService {
public NoteResult checkLogin(String name, String pwd) throws Exception;
public NoteResult regist(
String name, String pwd, String nickname) throws Exception;
}
|
Java
|
UTF-8
| 20,583
| 2.8125
| 3
|
[
"MIT"
] |
permissive
|
package com.eye.see.image.processing;
/*
* Created on Jun 24, 2005
* @author Rafael Santos (rafael.santos@lac.inpe.br)
*
* Part of the Java Advanced Imaging Stuff site
* (http://www.lac.inpe.br/~rafael.santos/Java/JAI)
*
* STATUS: Complete.
*
* Redistribution and usage conditions must be done under the
* Creative Commons license:
* English: http://creativecommons.org/licenses/by-nc-sa/2.0/br/deed.en
* Portuguese: http://creativecommons.org/licenses/by-nc-sa/2.0/br/deed.pt
* More information on design and applications are on the projects' page
* (http://www.lac.inpe.br/~rafael.santos/Java/JAI).
*/
import java.awt.Point;
import java.awt.image.ColorModel;
import java.awt.image.DataBuffer;
import java.awt.image.Raster;
import java.awt.image.SampleModel;
import java.awt.image.WritableRaster;
import java.util.Random;
import javax.media.jai.PlanarImage;
import javax.media.jai.TiledImage;
import com.sun.media.jai.codecimpl.util.RasterFactory;
/**
* This class implements a basic Fuzzy C-Means clustering algorithm as an
* image processing task. This implementation tries to speed things up, but
* needs to keep all image data on memory.
* This implementation deals only with integer-like pixel data but can
* cluster N-dimensional data. This implementation can return ranked images
* (i.e. second, third, etc. best choices) as well as the membership-
* function based images.
*
* TODO: Format this class better as not Sun java code formatted
*/
public class FuzzyCMeansClustering {
/** Default values for clustering parameters */
public static final int MAX_ITERATIONS = 10;
public static final float FUZZYNESS = 2.0f;
public static final float EPSILON = 1.05f;
// A copy of the input image.
private PlanarImage pInput;
// The input image dimensions.
private int width,height,numBands;
// Some clustering parameters.
private int maxIterations,numClusters;
// The FCM additional parameters and membership function values.
private float fuzziness; // "m"
private float[][][] membership;
// The iteration counter will be global so we can get its value on the
// middle of the clustering process.
private int iteration;
// A metric of clustering "quality", called "j" as in the equations.
private double j = Float.MAX_VALUE;
// A small value, if the difference of the cluster "quality" does not
// changes beyond this value, we consider the clustering converged.
private double epsilon;
// This flag will be true when the clustering has finished.
private boolean hasFinished = false;
private long position;
// The cluster centers.
private float[][] clusterCenters;
// A big array with all the input data and a small one for a single pixel.
private int[] inputData;
private float[] aPixel;
/**
* The constructor for the class, which sets the input image, the number of
* desired clusters, the maximum number of iterations, the fuzziness ("m"
* value) and a value that will be used to decide whether the convergence
* has stopped. It also allocates the required memory.
* @param pInput the input planar image.
* @param numClusters the desired number of clusters.
* @param maxIterations the maximum number of iterations.
* @param fuzziness the fuzziness (a.k.a. the "m" value)
* @param epsilon a small value used to verify if clustering has converged.
*/
public FuzzyCMeansClustering(PlanarImage pInput,int numClusters) {
this.pInput = pInput;
// Get the image dimensions.
width = pInput.getWidth();
height = pInput.getHeight();
numBands = pInput.getSampleModel().getNumBands();
// Get some clustering parameters.
this.numClusters = numClusters;
this.maxIterations = MAX_ITERATIONS;
this.fuzziness = FUZZYNESS;
this.epsilon = EPSILON;
iteration = 0;
// We need arrays to store the clusters' centers, validity tags and membership values.
clusterCenters = new float[numClusters][numBands];
membership = new float[width][height][numClusters];
// Gets the raster for the input image.
Raster raster = pInput.getData();
// Gets the whole image data on memory. Get memory for a single pixel too.
inputData = new int[width*height*numBands];
aPixel = new float[numBands];
raster.getPixels(0,0,width,height,inputData);
// Initialize the membership functions randomly.
Random generator = new Random(); // easier to debug if a seed is used
// For each data point (in the membership function table)
for(int h=0;h<height;h++) {
for(int w=0;w<width;w++) {
// For each cluster's membership assign a random value.
float sum = 0f;
for(int c=0;c<numClusters;c++) {
membership[w][h][c] = 0.01f+generator.nextFloat();
sum += membership[w][h][c];
}
// Normalize so the sum of MFs for a particular data point will be equal to 1.
for(int c=0;c<numClusters;c++) {
membership[w][h][c] /= sum;
}
}
}
// Initialize the global position value.
position = 0;
}
/**
* This method performs the bulk of the processing. It runs the classic
* Fuzzy C-Means clustering algorithm:
* 1 - Calculate the cluster centers.
* 2 - Update the membership function.
* 3 - Calculate statistics and repeat from 1 if needed.
*/
public void run() {
double lastJ;
// Calculate the initial objective function just for kicks.
lastJ = calculateObjectiveFunction();
// Do all required iterations (until the clustering converges)
for(iteration=0;iteration<maxIterations;iteration++) {
// Calculate cluster centers from MFs.
calculateClusterCentersFromMFs();
// Then calculate the MFs from the cluster centers !
calculateMFsFromClusterCenters();
// Then see how our objective function is going.
j = calculateObjectiveFunction();
if (Math.abs(lastJ-j) < epsilon) break;
lastJ = j;
} // end of the iterations loop.
hasFinished = true;
// Means that all calculations are done, too.
position = getSize();
}
/**
* This method calculates the cluster centers from the membership
* functions.
*/
private void calculateClusterCentersFromMFs()
{
float top,bottom;
// For each band and cluster
for(int b=0;b<numBands;b++)
for(int c=0;c<numClusters;c++)
{
// For all data points calculate the top and bottom parts of the equation.
top = bottom = 0;
for(int h=0;h<height;h++)
for(int w=0;w<width;w++)
{
// Index will help locate the pixel data position.
int index = (h*width+w)*numBands;
top += Math.pow(membership[w][h][c],fuzziness)*inputData[index+b];
bottom += Math.pow(membership[w][h][c],fuzziness);
}
// Calculate the cluster center.
clusterCenters[c][b] = top/bottom;
// Upgrade the position vector (batch).
position += width*height;
}
}
/**
* This method calculates the membership functions from the cluster
* centers.
*/
private void calculateMFsFromClusterCenters()
{
float sumTerms;
// For each cluster and data point
for(int c=0;c<numClusters;c++)
for(int h=0;h<height;h++)
for(int w=0;w<width;w++)
{
// Get a pixel (as a single array).
int index = (h*width+w)*numBands;
for(int b=0;b<numBands;b++)
aPixel[b] = inputData[index+b];
// Top is the distance of this data point to the cluster being read.
float top = calcDistance(aPixel,clusterCenters[c]);
// Bottom is the sum of distances from this data point to all clusters.
sumTerms = 0f;
for(int ck=0;ck<numClusters;ck++)
{
float thisDistance = calcDistance(aPixel,clusterCenters[ck]);
sumTerms += Math.pow(top/thisDistance,(2f/(fuzziness-1f)));
}
// Then the MF can be calculated as...
membership[w][h][c] =
(float)(1f/sumTerms);
// Upgrade the position vector (batch).
position += (numBands+numClusters);
}
}
/*
* This method calculates the objective function ("j") which reflects the
* quality of the clustering.
*/
private double calculateObjectiveFunction()
{
double j = 0;
// For all data values and clusters
for(int h=0;h<height;h++)
for(int w=0;w<width;w++)
for(int c=0;c<numClusters;c++)
{
// Get the current pixel data.
int index = (h*width+w)*numBands;
for(int b=0;b<numBands;b++)
aPixel[b] = inputData[index+b];
// Calculate the distance between a pixel and a cluster center.
float distancePixelToCluster = calcDistance(aPixel,clusterCenters[c]);
j += distancePixelToCluster*Math.pow(membership[w][h][c],fuzziness);
// Upgrade the position vector (batch).
position += (2*numBands);
}
return j;
}
/**
* This method calculates the Euclidean distance between two N-dimensional
* vectors.
* @param a1 the first data vector.
* @param a2 the second data vector.
* @return the Euclidean distance between those vectors.
*/
private float calcDistance(float[] a1,float[] a2)
{
float distance = 0f;
for(int e=0;e<a1.length;e++) distance += (a1[e]-a2[e])*(a1[e]-a2[e]);
return (float)Math.sqrt(distance);
}
/**
* This method returns the estimated size (steps) for this task.
* The value is, of course, an approximation, just so we will be able to
* give the user a feedback on the processing time. In this case, the value
* is calculated as the number of loops in the run() method.
*/
public long getSize()
{
// Return the estimated size for this task:
return (long)maxIterations* // The maximum number of iterations times
(
(numClusters*width*height*(2*numBands))+ // Step 0 of method run()
(width*height*numBands*numClusters)+ // Step 1 of method run()
(numClusters*width*height*(numBands+numClusters))+ // Step 2 of run()
(numClusters*width*height*(2*numBands)) // Step 3 of method run()
);
}
/**
* This method returns a measure of the progress of the algorithm.
*/
public long getPosition()
{
return position;
}
/**
* This method returns true if the clustering has finished.
*/
public boolean isFinished()
{
return (position == getSize());
}
/**
* This method will return a rank image, i.e. an image which pixels are
* the cluster centers of the Nth best choice for the classification.
* For example, if the membership functions for a pixel of an image
* clustered with six clusters are [0.10 0.25 0.40 0.20 0.03 0.02] and we
* ask for the image with rank 2 (ranks starts with zero), for that pixel
* the third best choice for cluster index will be selected (0.20) and the
* centers of the cluster with index 3 will be used.
* It is important to notice that this method can be called while the
* clustering task (method run) is running, and the resulting image is not
* guaranteed to be close to a clustered result.
* @param rank the desired rank for the classification.
* @return a TiledImage with the classification results considering that rank.
*/
public TiledImage getRankedImage(int rank)
{
// Create a SampleModel for the output data (same number of bands as the input image).
SampleModel sampleModel =
RasterFactory.createBandedSampleModel(DataBuffer.TYPE_INT,width,height,numBands);
// Create a WritableRaster using that sample model.
WritableRaster raster =
RasterFactory.createWritableRaster(sampleModel,new Point(0,0));
// A pixel array will contain all bands for a specific x,y.
int[] pixelArray = new int[numBands];
// For all pixels in the image...
for(int h=0;h<height;h++)
for(int w=0;w<width;w++)
{
// Get the class (cluster center) for that pixel with the specified rank.
int aCluster = getRankedIndex(membership[w][h],rank);
// Fill the array with that cluster center.
for(int band=0;band<numBands;band++) pixelArray[band] = (int)clusterCenters[aCluster][band];
// Put it on the raster.
raster.setPixel(w,h,pixelArray);
}
// Set the raster on the output image.
TiledImage pOutput = new TiledImage(pInput,false);
pOutput.setData(raster);
return pOutput;
}
/**
* This method will return a membership function image, i.e. an image which
* pixels correspond to the membership functions for the cluster which is
* the Nth best choice for the classification.
* For example, if the membership functions for a pixel of an image
* clustered with six clusters are [0.10 0.25 0.40 0.20 0.03 0.02] and we
* ask for the membership function image with rank 2 (ranks starts with
* zero), for that pixel the third best membership function will be
* selected (0.20) and used (scaled by 255) as the pixel value.
* It is important to notice that this method can be called while the
* clustering task (method run) is running, and the resulting image is not
* guaranteed to be close to a clustered result.
* @param rank the desired rank for the classification.
* @return a TiledImage with the membership function value results
* considering that rank.
*/
public TiledImage getRankedMFImage(int rank)
{
// Create a SampleModel for the output data (1 band only).
SampleModel sampleModel =
RasterFactory.createBandedSampleModel(DataBuffer.TYPE_BYTE,
width,height,1);
// Create a compatible ColorModel.
ColorModel colorModel = PlanarImage.createColorModel(sampleModel);
// Create a WritableRaster.
WritableRaster raster =
RasterFactory.createWritableRaster(sampleModel,new Point(0,0));
// For all pixels in the image...
for(int h=0;h<height;h++)
for(int w=0;w<width;w++)
{
// Get the membership function (considering the rank) for that pixel.
int aCluster = (int)(255*getRankedMF(membership[w][h],rank));
// Put it on the raster.
raster.setPixel(w,h,new int[]{aCluster});
}
// Set the raster on the output image.
TiledImage pOutput = new TiledImage(0,0,width,height,0,0,sampleModel,colorModel);
pOutput.setData(raster);
return pOutput;
}
/**
* This method returns the ranked index of a cluster from an array
* containing the membership functions.
* For example, if the array contains [0.10 0.25 0.40 0.20 0.03 0.02]
* and we ask for index with rank 2 (ranks starts with zero), the third
* best choice will be selected (0.20) and its index (3) will be returned.
* @param data the array with the membership functions.
* @param rank the rank of the cluster we want to get.
* @return the index of the cluster.
*/
private int getRankedIndex(float[] data,int rank)
{
// Create temporary arrays for the indexes and the data.
int[] indexes = new int[data.length];
float[] tempData = new float[data.length];
// Fill those arrays.
for(int i=0;i<indexes.length;i++)
{
indexes[i] = i;
tempData[i] = data[i];
}
// Sort both arrays together, using data as the sorting key.
for(int i=0;i<indexes.length-1;i++)
for(int j=i;j<indexes.length;j++)
{
if (tempData[i] < tempData[j])
{
int tempI= indexes[i];
indexes[i] = indexes[j];
indexes[j] = tempI;
float tempD = tempData[i];
tempData[i] = tempData[j];
tempData[j] = tempD;
}
}
// Return the cluster index for the rank we want.
return indexes[rank];
}
/**
* This method returns the ranked membership function of a cluster from an
* array containing the membership functions.
* For example, if the array contains [0.10 0.25 0.40 0.20 0.03 0.02] and
* we ask for the MF with rank 2 (ranks starts with zero), the third best
* choice will be selected (0.20) and returned.
* @param data the array with the membership functions.
* @param rank the rank of the cluster we want to get.
* @return the MF with that rank.
*/
private float getRankedMF(float[] data,int rank)
{
// Create temporary arrays for the indexes and the data.
int[] indexes = new int[data.length];
float[] tempData = new float[data.length];
// Fill those arrays.
for(int i=0;i<indexes.length;i++)
{
indexes[i] = i;
tempData[i] = data[i];
}
// Sort both arrays together, using data as the sorting key.
for(int i=0;i<indexes.length-1;i++)
for(int j=i;j<indexes.length;j++)
{
if (tempData[i] < tempData[j])
{
int tempI= indexes[i];
indexes[i] = indexes[j];
indexes[j] = tempI;
float tempD = tempData[i];
tempData[i] = tempData[j];
tempData[j] = tempD;
}
}
// Return the cluster index for the rank we want.
return tempData[rank];
}
/**
* This method returns the Partition Coefficient measure of cluster validity
* (see Fuzzy Algorithms With Applications to Image Processing and Pattern
* Recognition, Zheru Chi, Hong Yan, Tuan Pham, World Scientific, pp. 91)
*/
public double getPartitionCoefficient()
{
double pc = 0;
// For all data values and clusters
for(int h=0;h<height;h++)
for(int w=0;w<width;w++)
for(int c=0;c<numClusters;c++)
pc += membership[w][h][c]*membership[w][h][c];
pc = pc/(height*width);
return pc;
}
/**
* This method returns the Partition Entropy measure of cluster validity
* (see Fuzzy Algorithms With Applications to Image Processing and Pattern
* Recognition, Zheru Chi, Hong Yan, Tuan Pham, World Scientific, pp. 91)
*/
public double getPartitionEntropy()
{
double pe = 0;
// For all data values and clusters
for(int h=0;h<height;h++)
for(int w=0;w<width;w++)
for(int c=0;c<numClusters;c++)
pe += membership[w][h][c]*Math.log(membership[w][h][c]);
pe = -pe/(height*width);
return pe;
}
/**
* This method returns the Compactness and Separation measure of cluster validity
* (see Fuzzy Algorithms With Applications to Image Processing and Pattern
* Recognition, Zheru Chi, Hong Yan, Tuan Pham, World Scientific, pp. 93)
*/
public double getCompactnessAndSeparation()
{
double cs = 0;
// For all data values and clusters
for(int h=0;h<height;h++)
for(int w=0;w<width;w++)
{
// Get the current pixel data.
int index = (h*width+w)*numBands;
for(int b=0;b<numBands;b++)
aPixel[b] = inputData[index+b];
for(int c=0;c<numClusters;c++)
{
// Calculate the distance between a pixel and a cluster center.
float distancePixelToCluster = calcSquaredDistance(aPixel,clusterCenters[c]);
cs += membership[w][h][c]*membership[w][h][c]*
distancePixelToCluster*distancePixelToCluster;
}
}
cs /= (height*width);
// Calculate minimum distance between ALL clusters
float minDist = Float.MAX_VALUE;
for(int c1=0;c1<numClusters-1;c1++)
for(int c2=c1+1;c2<numClusters;c2++)
{
float distance = calcSquaredDistance(clusterCenters[c1],clusterCenters[c2]);
minDist = Math.min(minDist,distance);
}
cs = cs/(minDist*minDist);
return cs;
}
/**
* This method calculates the squared distance between two N-dimensional
* vectors.
* @param a1 the first data vector.
* @param a2 the second data vector.
* @return the squared distance between those vectors.
*/
private float calcSquaredDistance(float[] a1,float[] a2)
{
float distance = 0f;
for(int e=0;e<a1.length;e++) distance += (a1[e]-a2[e])*(a1[e]-a2[e]);
return (float)distance;
}
public float[][] getClusterCenters() {
return clusterCenters;
}
}
|
PHP
|
UTF-8
| 1,494
| 2.515625
| 3
|
[] |
no_license
|
<?php
require('db_connect.php');
$isbn13 = $_POST['isbn13'];
$quantity = $_POST['quantity'];
$firstName = $_POST['firstName'];
$lastName = $_POST['lastName'];
$email = $_POST['email'];
$phoneNo = $_POST['phoneNo'];
$address = $_POST['address'];
$aptNo = $_POST['aptNo'];
$city = $_POST['city'];
$state = $_POST['state'];
$zipCode = $_POST['zipCode'];
$shipping = $_POST['shipping'];
$cardnum = $_POST['cardnum'];
$expDate = $_POST['expDate'];
$cvv = $_POST['cvv'];
$stmt = $db->prepare("INSERT INTO Orders (isbn, quantity, firstName, lastName, email, phoneNumber, address, apt, city, state, zipCode, shippingSpeed, creditCard, cardExpiration, cvv)
VALUES (:isbn, :quantity, :firstName, :lastName, :email, :phoneNumber, :address, :apt, :city, :state, :zipCode, :shippingSpeed, :creditCard, :cardExpiration, :cvv)");
$stmt->bindParam(":isbn",$isbn13);
$stmt->bindParam(":quantity", $quantity);
$stmt->bindParam(":firstName", $firstName);
$stmt->bindParam(":lastName",$lastName);
$stmt->bindParam(":email", $email);
$stmt->bindParam(":phoneNumber", $phoneNo);
$stmt->bindParam(":address", $address);
$stmt->bindParam(":apt", $aptNo);
$stmt->bindParam(":city", $city);
$stmt->bindParam(":state", $state);
$stmt->bindParam(":zipCode",$zipCode);
$stmt->bindParam(":shippingSpeed", $shipping);
$stmt->bindParam(":creditCard", $cardnum);
$stmt->bindParam(":cardExpiration", $expDate);
$stmt->bindParam(":cvv",$cvv);
$stmt->execute();
echo "success";
?>
|
Python
|
UTF-8
| 8,591
| 3.515625
| 4
|
[] |
no_license
|
import unittest
from collections import deque
class BstNode:
def __init__(self, value, parent=None):
self.parent = parent
self.left = None
self.right = None
self.value = value
def insert(self, value):
if value < self.value:
if not self.left:
self.left = BstNode(value, self)
else:
self.left.insert(value)
elif value > self.value:
if not self.right:
self.right = BstNode(value, self)
else:
self.right.insert(value)
else:
raise ValueError('Duplicated key')
def get(self, value):
if value == self.value:
return self
elif value < self.value:
if self.left:
return self.left.get(value)
else:
return None
else:
if self.right:
return self.right.get(value)
else:
return None
def delete(self, value):
# Incomplete!
node_to_remove = self.get(value)
if not (node_to_remove.left or node_to_remove.right):
# is a leaf
if node_to_remove == node_to_remove.parent.left:
node_to_remove.parent.left = None
else:
node_to_remove.parent.right = None
def find_min(self):
current = self
while current.left:
current = current.left
return current
def find_max(self):
current = self
while current.right:
current = current.right
return current
def contains(self, value):
if value == self.value:
return True
elif value < self.value:
if self.left:
return self.left.contains(value)
else:
return False
else:
if self.right:
return self.right.contains(value)
else:
return False
def apply_preorder(self, f):
f(self)
if self.left:
self.left.apply_preorder(f)
if self.right:
self.right.apply_preorder(f)
def apply_preorder2(self, f):
stack = []
node = self
while stack or node is not None:
if node:
f(node)
if node.right:
stack.append(node.right)
node = node.left
else:
node = stack.pop()
def apply_inorder(self, f):
if self.left:
self.left.apply_inorder(f)
f(self)
if self.right:
self.right.apply_inorder(f)
def apply_inorder2(self, f):
stack = []
node = self
while stack or node is not None:
if node:
stack.append(node)
node = node.left
else:
node = stack.pop()
f(node)
node = node.right
def apply_postorder(self, f):
if self.left:
self.left.apply_postorder(f)
if self.right:
self.right.apply_postorder(f)
f(self)
def apply_postorder2(self, f):
stack = []
last_visited = None
node = self
while stack or node is not None:
if node:
stack.append(node)
node = node.left
else:
peek_node = stack[len(stack)-1]
if peek_node.right and last_visited is not peek_node.right:
node = peek_node.right
else:
f(peek_node)
last_visited = stack.pop()
def apply_levelorder(self, f):
q = deque()
q.appendleft(self)
while len(q) > 0:
node = q.pop()
f(node)
if node.left:
q.appendleft(node.left)
if node.right:
q.appendleft(node.right)
def apply_levelorder2(self, f):
order = []
parent = {self.value: None}
level = {self: 0}
frontier = [self]
next_level = 1
while frontier:
next_frontier = []
for node in frontier:
f(node)
if node.left:
level[node.left.value] = next_level
parent[node.left.value] = node.value
next_frontier.append(node.left)
if node.right:
level[node.right.value] = next_level
parent[node.right.value] = node.value
next_frontier.append(node.right)
frontier = next_frontier
next_level += 1
print('levels:', next_level-1)
print('order:', order)
print('parent:', parent)
print('level:', level)
def __str__(self):
return 'value: {0}, parent: {1}'.format(self.value, self.parent.value if self.parent else None)
def tree_clone(original_root):
if not original_root:
return None
new_root = BstNode(original_root.value)
clone = new_root
while original_root:
if original_root.left and not clone.left:
clone.left = BstNode(original_root.left.value, clone)
original_root = original_root.left
clone = clone.left
elif original_root.right and not clone.right:
clone.right = BstNode(original_root.right.value, clone)
original_root = original_root.right
clone = clone.right
else:
original_root = original_root.parent
clone = clone.parent
return new_root
class TestTree(unittest.TestCase):
def setUp(self):
# Tree from wikipedia
# https://en.wikipedia.org/wiki/Tree_traversal
self.tree = BstNode('F')
self.tree.insert('B')
self.tree.insert('A')
self.tree.insert('D')
self.tree.insert('C')
self.tree.insert('E')
self.tree.insert('G')
self.tree.insert('I')
self.tree.insert('H')
def test_insert(self):
tree = self.tree
self.assertTrue(tree.contains('A'))
self.assertTrue(tree.contains('B'))
self.assertTrue(tree.contains('C'))
self.assertTrue(tree.contains('D'))
self.assertTrue(tree.contains('E'))
self.assertTrue(tree.contains('F'))
self.assertTrue(tree.contains('G'))
self.assertTrue(tree.contains('H'))
self.assertTrue(tree.contains('I'))
self.assertFalse(tree.contains('J'))
def test_insert_duplicates(self):
tree = BstNode('F')
self.assertTrue(tree.contains('F'))
self.assertRaises(ValueError, tree.insert, 'F')
def test_get(self):
node = self.tree.get('D')
self.assertEqual(node.value, 'D')
self.assertEqual(node.parent.value, 'B')
self.assertEqual(node.left.value, 'C')
self.assertEqual(node.right.value, 'E')
def test_find_min(self):
self.assertEqual(self.tree.find_min().value, 'A')
def test_find_max(self):
self.assertEqual(self.tree.find_max().value, 'I')
def test_apply(self):
tree = self.tree
def f(node):
print(node)
print('preorder')
tree.apply_preorder(f)
print()
tree.apply_preorder2(f)
print()
print('inorder')
tree.apply_inorder(f)
print()
tree.apply_inorder2(f)
print()
print('postorder')
tree.apply_postorder(f)
print()
tree.apply_postorder2(f)
print()
print('levelorder')
tree.apply_levelorder(f)
print()
tree.apply_levelorder2(f)
def test_delete(self):
tree = BstNode('F')
tree.insert('B')
tree.insert('A')
tree.insert('D')
tree.insert('C')
tree.insert('E')
tree.insert('G')
tree.insert('I')
tree.insert('H')
# Node with no children
self.assertTrue(tree.contains('H'))
tree.delete('H')
self.assertFalse(tree.contains('H'))
# Node with one child
self.assertTrue(tree.contains('G'))
tree.delete('G')
self.assertFalse(tree.contains('G'))
def test_clone(self):
print()
tree = self.tree
tree2 = tree_clone(tree)
def f(node):
print(node)
print('original inorder')
tree.apply_inorder(f)
print('cloned inorder')
tree2.apply_inorder(f)
|
Markdown
|
UTF-8
| 6,824
| 2.53125
| 3
|
[
"Apache-2.0"
] |
permissive
|
---
title: VMware using Offline Images
weight: 400
---
- [Setting the max_map_count](#setting-the-max_map_count)
- [Download and extract the image](#download-and-extract-the-image)
- [Creating config.yaml](#creating-configyaml)
- [Creating getAllRec.sh](#creating-getallrecsh)
- [Starting the install process](#starting-the-install-process)
- [Creating the correct kubeconfig](#creating-the-correct-kubeconfig)
- [Uninstalling Common Services](#uninstalling-common-services)
**NOTE: Make sure you have 200GB or more on your installer node. If you have less, then you can download the offline image, extract and delete the original file**
## Setting the max_map_count
SSH into all your worker and storage nodes and set the max_map_count to 262144.
```bash
sudo sysctl -w vm.max_map_count=262144
echo "vm.max_map_count=262144" | sudo tee -a /etc/sysctl.conf
```
## Download and extract the image
SSH into your installer node. Go to `/opt` dir and download the image there. Look at [Pre-requisites](../pre-reqs) to learn how to get the offline image.
```bash
cd /opt
mkdir cp4ioffline
tar xf ibm-cp-int-2019.4.1-offline.tar.gz --directory /opt/cp4ioffline
```
Now you can extract the images and load them into docker.
```bash
cd cp4ioffline
tar xvf installer_files/cluster/images/common-services-armonk-x86_64.tar.gz -O | sudo docker load
```
You can delete `ibm-cp-int-2019.4.1-offline.tar.gz` now if you're low on space.
## Creating config.yaml
Now you have to configure your `cp4ioffline/installer_files/cluster/config.yaml`. It is always a good idea to create a backup of the default `cluster.yaml`.
- You can use your OpenShift master and infrastructure nodes here, or install these components to dedicated OpenShift compute nodes. You can specify more than one node for each type to build a high availability cluster. Use the command `oc get nodes` to obtain these values.
```yaml
cluster_nodes:
master:
- your-openshift-dedicated-node-to-deploy-icp-master-components
proxy:
- your-openshift-dedicated-node-to-deploy-icp-proxy-components>
management:
- your-openshift-dedicated-node-to-deploy-icp-management-components>
```
- Set the default_admin_password. The password must meet the default password enforcement rule '^([a-zA-Z0-9\-]{32,})$' . Optionally, you can define one or more rules as regular expressions in an array list that the password must pass. The rules are written as regular expressions that are supported by the Go programming language. To define a set of password rules, add the following parameter and values to the file:
```yaml
password_rules:
- '^.{10,}'
- '.*[!@#\$%\^&\*].*'
```
To disable the password_rule, add (.*).
```yaml
password_rules:
- '(.*)'
```
- Finally, you'll have define what capabilities you would like to install under `archive_addons:`. By default it installs all the capabilities. But depending on your requirements, you can pick and choose. For example defined below is a cluster with `mq` and `tracing`
**Note: You must deploy `icp4i` also referred to as common services, otherwise you can't deploy any other capabilities**
```yaml
archive_addons:
icp4i:
namespace: integration
repo: local-charts
path: icp4icontent/IBM-Cloud-Pak-for-Integration-3.0.0.tgz
charts:
- name: ibm-icp4i-prod
values: {}
mq:
namespace: mq
repo: local-charts
path: icp4icontent/IBM-MQ-Advanced-for-IBM-Cloud-Pak-for-Integration-5.0.0.tgz
tracing:
namespace: tracing
repo: local-charts
path: icp4icontent/IBM-Cloud-Pak-for-Integration-Operations-Dashboard-1.0.1.tgz
```
Additionally, here is an example that deploys everything [`config.yaml`](/assets/integration/utils/config.yaml)
## Creating getAllRec.sh
When the installer fails, this script will echo all the pods that are up and running and pods that are failing.
```bash
cd /opt
touch getAllRec.sh
sudo chmod 755 getAllRec.sh
```
You can get the [`getAllRec.sh`](/assets/integration/utils/getAllRec.sh) file from here.
To run `getAllRec.sh` you need to pass in a namespace. Usually on a failed install, the `kube-system` namespace gives us the most information regarding the failure.
```bash
./getAllRec.sh kube-system
```
## Creating the correct kubeconfig
First you have to copy our kubeconfig to the cluster directory.
```bash
cd /opt/cp4ioffline/installer_files/cluster
oc config view --minify=true --flatten=true > kubeconfig
```
It should look similar to this. **Note:** Make sure it has `insecure-skip-tls-verify: true`config.
```yaml
apiVersion: v1
clusters:
- cluster:
insecure-skip-tls-verify: true
server: https://api.mislam.ocp.csplab.local:6443
name: api-mislam-ocp-csplab-local:6443
contexts:
- context:
cluster: api-mislam-ocp-csplab-local:6443
namespace: openshift-image-registry
user: kube:admin/api-mislam-ocp-csplab-local:6443
name: openshift-image-registry/api-mislam-ocp-csplab-local:6443/kube:admin
current-context: openshift-image-registry/api-mislam-ocp-csplab-local:6443/kube:admin
kind: Config
preferences: {}
users:
- name: kube:admin/api-mislam-ocp-csplab-local:6443
user:
token: 3lg2U7vUcu-ovvsrK-sYDSWg3t5vLcBPY83DkvL44Is
```
**Alternatively** you can copy it from our Openshift Cluster Auth directory to here.
```bash
cp /opt/myocpcluster/auth/kubeconfig /opt/cp4ioffline/installer_files/cluster
```
## Checking Docker Login
Run this command to see if you can login to docker
```bash
sudo docker login $(oc registry info) -u kubeadmin -p $(oc whoami -t)
```
## Starting the install process
Now you run the installer. Notice it's a nohup job (runs on the background) and the logs are written to `install.log` so you can close your terminal and leave but the installer will keep on going on the server. And log back in and look at `install.log` to see progress.
```bash
nohup sudo docker run -t --net=host -e LICENSE=accept -v $(pwd):/installer/cluster:z -v /var/run:/var/run:z -v /etc/docker:/etc/docker:z --security-opt label:disable ibmcom/icp-inception-amd64:3.2.2 addon -vvv | tee install.log &
```
**NOTE: If the installer fails, run the getAllRec.sh script to check if common services is up or not. If it isn't up, you can run the installer again. If it is up but one of the capabilities failed tyo get pushed, then that capability can be applied individually**
## Uninstalling Common Services
In case the installer fails on the same step multiple times, it's better to uninstall and try again. To uninstall
```bash
nohup sudo docker run -t --net=host -e LICENSE=accept -v $(pwd):/installer/cluster:z -v /var/run:/var/run:z -v /etc/docker:/etc/docker:z --security-opt label:disable ibmcom/icp-inception-amd64:3.2.2 uninstall-with-openshift | tee install.log &
```
|
Markdown
|
UTF-8
| 1,839
| 3.46875
| 3
|
[] |
no_license
|
# 输出(output)
配置 `output` 选项可以控制 webpack 如何向硬盘写入编译文件。注意,即使可以存在多个`入口`起点,但只指定一个`输出`配置。
## 用法(Usage)
在 webpack 中配置 `output` 属性的最低要求是,将它的值设置为一个对象,包括以下两点:
- `filename` 用于输出文件的文件名。
- 目标输出目录 `path` 的绝对路径。
**webpack.config.js**
```javascript
module.exports = {
output: {
filename: 'bundle.js',
path: '/home/proj/public/assets'
}
};
```
此配置将一个单独的 `bundle.js` 文件输出到 `/home/proj/public/assets` 目录中。
## 多个入口起点
如果配置创建了多个单独的 "chunk"(例如,使用多个入口起点或使用像 CommonsChunkPlugin 这样的插件),则应该使用[占位符(substitutions)](https://webpack.docschina.org/configuration/output#output-filename)来确保每个文件具有唯一的名称。
```javascript
module.exports = {
entry: {
app: './src/app.js',
search: './src/search.js'
},
output: {
filename: '[name].js',
path: __dirname + '/dist'
}
};
// 写入到硬盘:./dist/app.js, ./dist/search.js
```
## 高级进阶
以下是使用 CDN 和资源 hash 的复杂示例:
**config.js**
```javascript
module.exports = {
//...
output: {
path: '/home/proj/cdn/assets/[hash]',
publicPath: 'http://cdn.example.com/assets/[hash]/'
}
};
```
在编译时不知道最终输出文件的 `publicPath` 路径的情况下,`publicPath` 可以留空,并且在入口起点文件运行时动态设置。如果你在编译时不知道 `publicPath`,你可以先忽略它,并且在入口起点设置 `__webpack_public_path__`。
```javascript
__webpack_public_path__ = myRuntimePublicPath;
// 剩余的应用程序入口
```
|
Java
|
UTF-8
| 2,599
| 2.53125
| 3
|
[] |
no_license
|
package com.example.agenda.Class;
import android.widget.ArrayAdapter;
import androidx.annotation.NonNull;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
public class DBController {
DatabaseReference databaseReference;
public void deletePreviousAgenda(final String date) {
String currentUser = FirebaseAuth.getInstance().getCurrentUser().getUid();
databaseReference = FirebaseDatabase.getInstance().getReference("Users").child(currentUser).child("agenda");
databaseReference.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot snapshot) {
if (snapshot.getValue() != null) {
String snap = snapshot.getValue().toString();
int index = 1;
int count = 0;
String analizeDate;
while (count < snap.length() - 2) {
count = snap.indexOf("}", index);
analizeDate = snap.substring(index, index + 10);
index = snap.indexOf("}", index) + 3;
int monthAnalize = formatDate(analizeDate, 3, 4, 4, 5);
int dayAnalize = formatDate(analizeDate, 0, 1, 1, 2);
int actualMonth = formatDate(date, 3, 4, 4, 5);
int actualDay = formatDate(date, 0, 1, 1, 2);
if (monthAnalize < actualMonth || ((dayAnalize < actualDay) && (monthAnalize <= actualMonth))) {
databaseReference.child(analizeDate).removeValue();
}
}
}
}
@Override
public void onCancelled(@NonNull DatabaseError error) {
}
});
}
public int formatDate(String date, int param1, int param2, int param3, int param4) {
int firstParam = Integer.parseInt(date.substring(param1,param2));
int secondParam = Integer.parseInt(date.substring(param3, param4));
switch (firstParam) {
case 1 : firstParam = 10; break;
case 2 : firstParam = 20; break;
case 3 : firstParam = 30; break;
}
int result = firstParam + secondParam;
return result;
}
}
|
Markdown
|
UTF-8
| 1,086
| 2.5625
| 3
|
[] |
no_license
|
# Article R8111-12
Pour les établissements placés sous l'autorité du ministre de la défense et dont l'accès est réglementé et surveillé en
permanence, les missions d'inspection du travail, conformément à l'article L. 8112-1, sont exercées, sous l'autorité du
ministre de la défense, par les agents civils et militaires qu'il désigne.
**Liens relatifs à cet article**
_Cité par_:
- Décret n°2005-1325 du 26 octobre 2005 - art. 8 (V)
- Décret n°2012-422 du 29 mars 2012 - art. 4 (V)
- Arrêté du 16 juillet 2014 - art. 9 (V)
- Arrêté du 16 juin 2015 - art. 2 (V)
- Arrêté du 16 juin 2015 - art. 4 (V)
- Arrêté du 12 juillet 2016 - art. 1 (V)
- Décret n°2017-272 du 1er mars 2017 - art. 1
- Décret n°2018-484 du 13 juin 2018 - art. 3
- Code de la défense. - art. D3123-14 (V)
- Code de la santé publique - art. R1333-102 (V)
- Code de la santé publique - art. R1333-169 (VD)
- Code du travail - art. R4462-29 (VD)
_Modifié par_:
- Décret n°2017-272 du 1er mars 2017 - art. 1
_Cite_:
- Code du travail - art. L8112-1
|
C#
|
UTF-8
| 2,557
| 2.84375
| 3
|
[] |
no_license
|
using Moq;
using WTW_IOC.Logic.Data;
using WTW_IOC.Logic;
using Xunit;
namespace WTW_IOC.Tests.Logic
{
public class SampleLogicTests
{
private Mock<ISampleData> _mockSampleData;
private Mock<ICalculator> _mockCalculator;
private ISampleLogic _sampleLogic;
public SampleLogicTests()
{
_mockSampleData = new Mock<ISampleData>();
_mockCalculator = new Mock<ICalculator>();
_sampleLogic = new SampleLogic(_mockCalculator.Object, _mockSampleData.Object);
}
[Fact]
public void SampleLogic_LoadSampleModel()
{
string[] returnVal = new string[] { "1", "2" };
_mockSampleData.Setup(sd => sd.LoadData()).Returns(returnVal);
var result = _sampleLogic.LoadSampleModel();
Assert.NotNull(result);
Assert.True(returnVal.Length == result.Length);
}
[Fact]
public void SampleLogic_AddMessage()
{
int first = 1, second = 2;
int returnVal = 3;
_mockCalculator.Setup(c => c.Add(first, second)).Returns(returnVal);
var result = _sampleLogic.AddMessage(1,2);
Assert.NotNull(result);
Assert.Equal($"{first} + {second} = {returnVal}", result);
}
[Fact]
public void SampleLogic_SubtractMessage()
{
int first = 5, second = 3;
int returnVal = 2;
_mockCalculator.Setup(c => c.Subtract(first, second)).Returns(returnVal);
var result = _sampleLogic.SubtractMessage(first,second);
Assert.NotNull(result);
Assert.Equal($"{first} - {second} = {returnVal}", result);
}
[Fact]
public void SampleLogic_MultiplyMessage()
{
int first = 10, second = 10;
int returnVal = 100;
_mockCalculator.Setup(c => c.Multiply(first, second)).Returns(returnVal);
var result = _sampleLogic.MultiplyMessage(first,second);
Assert.NotNull(result);
Assert.Equal($"{first} x {second} = {returnVal}", result);
}
[Fact]
public void SampleLogic_DivideMessage()
{
int first = 100, second = 10;
int returnVal = 10;
_mockCalculator.Setup(c => c.Divide(first, second)).Returns(returnVal);
var result = _sampleLogic.DivideMessage(first, second);
Assert.Equal($"{first} % {second} = {returnVal}", result);
}
}
}
|
Java
|
UTF-8
| 1,458
| 1.710938
| 2
|
[] |
no_license
|
package com.xunlei.downloadprovider.homepage.photoarticle;
import android.text.TextUtils;
import com.xunlei.downloadprovider.e.a.e;
import com.xunlei.downloadprovider.homepage.recommend.a.v;
import com.xunlei.downloadprovider.member.login.LoginHelper;
import com.xunlei.downloadprovider.member.login.b.l;
import java.util.LinkedList;
/* compiled from: PhotoArticleDetailActivity */
final class n implements e {
final /* synthetic */ PhotoArticleDetailActivity a;
n(PhotoArticleDetailActivity photoArticleDetailActivity) {
this.a = photoArticleDetailActivity;
}
public final void a(String str, int i) {
if (!(this.a.c() || TextUtils.equals(str, this.a.g.a) == null)) {
this.a.g.h = i + 1;
this.a.g.g = true;
this.a.d();
str = this.a.j;
LoginHelper.a();
if (l.c() != 0) {
i = LoginHelper.a();
v vVar = new v();
vVar.a = i.g.c();
vVar.c = i.e();
vVar.e = true;
vVar.b = i.g.d();
vVar.d = i.h();
if (str.i == 0) {
str.i = new LinkedList();
}
str.i.add(0, vVar);
}
if (str.f != 0) {
i = str.a.indexOf(str.f);
if (i >= 0) {
str.notifyItemChanged(i);
}
}
}
}
}
|
C++
|
UTF-8
| 28,957
| 3.421875
| 3
|
[] |
no_license
|
///////////////////////////////////////////////////////////////////////////
/// Ten : Phan Quoc Trung
/// MSSV : 1412590
/// Email : trungpq999@gmail.com
/// Lop : Phuong Phap Lap Trinh Huong Doi Tuong 15CTT1
/// Noi Dung: demo noi dung 95 ham trong so 102 ham Algorithm STL
/// duoc nhac den trong file bao cao
///////////////////////////////////////////////////////////////////////////
#include<iostream>
#include <algorithm> // std::all_of
#include <array> // std::array
#include <vector> // std::vector
#include <utility> // std::pair
#include<string>
#include <functional>
#include <numeric> // std::accumulate
#include <memory>
int current = 0;
inline int isBetter(const void * a, const void * b){return (*(int*)a - *(int*)b);}
inline int UniqueNumber() { return ++current; }
inline int op_increase(int i) { return ++i; }
inline int RandomNumber() { return (std::rand() % 100); }
inline bool compareLessThan(int i, int j) { return (i < j); }
void myfunction(int i) { // function:
std::cout << ' ' << i;
}
bool IsOdd(int i) {
return (abs(i % 2) == 1);
}
bool myCompare(int i, int j) {
return (i == j);
}
int main(){
// 1. Demo all_of
std::cout << "1. Demo all_of" << std::endl;
std::vector<int> foo = { -3, 5, 7, 11, 13,13, 17, 19, 23, 7, 30 };
if (std::all_of(foo.begin(), foo.end(), [](int i){return i % 2; }))
std::cout << "All the elements are odd numbers.\n";
// 2. Demo any_of
std::cout << "2. Demo any_of" << std::endl;
if (std::any_of(foo.begin(), foo.end(), [](int i){return i < 0; }))
std::cout << "There are negative elements in the range.\n";
// 3. Demo none_of
std::cout << "3. Demo none_of" << std::endl;
if (std::none_of(foo.begin(), foo.end(), [](int i){return i % 2 == 0; }))
std::cout << "There are no even elements in the range.\n";
// 4. Demo for_each
std::cout << "4. Demo for_each" << std::endl;
std::cout << " foo contains:";
for_each(foo.begin(), foo.end(), myfunction);
std::cout << '\n';
// 5. Demo for_each_n
// 6. Demo count
std::cout << "6. Demo count " << std::endl;
std::cout << " number: 7, count: " << std::count(foo.begin(), foo.end(), 7) << '\n';
// 7. Demo count_if
std::cout << "7. Demo count_if " << std::endl;
std::cout << "number divisible by five: "
<< std::count_if(foo.begin(), foo.end(), [](int i){return i % 5 == 0; })
<< '\n';
// // 8. Demo mismatch
//std::cout << "8. Demo mismatch " << std::endl;
//std::pair<std::vector<int>::iterator, int*> mypair;
//int myints[] = { -3, 5, 7, 11, 13, 15, 20,0,0,0 };
// std::mismatch(foo.begin(), foo.end(), myints);
//std::cout << "First mismatching elements: " << *mypair.first;
//std::cout << " and " << *mypair.second << '\n';
// 9. Demo equal
std::cout << "9. Demo equal " << std::endl;
int foo2[10] = { -3, 5, 7, 11, 13, 17, 19, 23, 7, 29 };
if (std::equal(foo.begin(), foo.end(), foo2))
std::cout << " The contents of both sequences are equal.\n";
else
std::cout << " The contents of both sequences differ.\n";
//10. Demo find
std::cout << "10. Demo find " << std::endl;
int *p = std::find(foo2, foo2 + 10, 11);
if (*p != 10)
std::cout << " fount element 11 in foo2";
else
std::cout << " not fount element 11 in foo2";
//11. Demo find_if find_if_not
std::cout << "Demo find_if find_if_not " << std::endl;
std::vector<int>::iterator it = std::find_if(foo.begin(), foo.end(), IsOdd);
std::cout << " The first odd value is " << *it << '\n';
it = std::find_if_not(foo.begin(), foo.end(), IsOdd);
std::cout << " The first even value is " << *it << '\n';
//12. Demo find_end
std::cout << "12. Demo find_end " << std::endl;
int tmp[3] = { 17, 19, 23 };
it = std::find_end(foo.begin(), foo.end(), tmp,tmp+2);
if (it != foo.end())
std::cout << "tmp last found at position " << (it - foo.begin()) << '\n';
//13. Demo find_first_of
std::cout << "13. Demo find_first_of " << std::endl;
it = std::find_first_of(foo.begin(), foo.end(), tmp, tmp + 2);
if (it != foo.end())
std::cout << "tmp first found at position " << (it - foo.begin()) << '\n';
//14. Demo adjacent_find
std::cout << "14. Demo adjacent_find " << std::endl;
auto i1 = std::adjacent_find(foo.begin(), foo.end());
if (i1 == foo.end()) {
std::cout << "no matching adjacent elements\n";
}
else {
std::cout << "the first adjacent pair of equal elements at: "
<< std::distance(foo.begin(), i1) << '\n';
}
//15. Demo search
std::cout << "15. Demo search " << std::endl;
it = std::search(foo.begin(), foo.end(), tmp, tmp + 2);
if (it != foo.end())
std::cout << "tmp found at position " << (it - foo.begin()) << '\n';
//16. Demo search_n
std::cout << "16. Demo search_n " << std::endl;
std::cout << "Has 4 consecutive zeros: "
<< (std::search_n(foo.begin(), foo.end(), 4, 0) != foo.end()) << '\n';
//17. Demo copy
std::cout << "17. Demo copy " << std::endl;
std::copy(foo2, foo2 + 7, foo.begin());
std::cout << "foo contains:";
for (std::vector<int>::iterator it = foo.begin(); it != foo.end(); ++it)
std::cout << ' ' << *it;
std::cout << std::endl;
//18. Demo copy_if
std::cout << "18. Demo copy_if " << std::endl;
std::vector<int> foo3 = { 25, 15, 5, -5, -15 };
std::vector<int> bar(foo3.size());
// copy only positive numbers:
it = std::copy_if(foo3.begin(), foo3.end(), bar.begin(), [](int i){return !(i<0); });
bar.resize(std::distance(bar.begin(), it)); // shrink container to new size
std::cout << "bar contains:";
for (int& x : bar) std::cout << ' ' << x;
std::cout << '\n';
//19. Demo copy_n
std::cout << "19. Demo copy_n " << std::endl;
std::vector<int> myvector;
myvector.resize(10);
std::copy_n(foo2, 10, myvector.begin());
std::cout << "myvector contains:";
for (std::vector<int>::iterator it3 = myvector.begin(); it3 != myvector.end(); ++it3)
std::cout << ' ' << *it3;
std::cout << '\n';
//20. Demo copy_backward
std::cout << "20. Demo copy_backward " << std::endl;
myvector.resize(13);
std::copy_backward(myvector.begin(), myvector.begin() + 5, myvector.end());
std::cout << "myvector contains:";
for (std::vector<int>::iterator it = myvector.begin(); it != myvector.end(); ++it)
std::cout << ' ' << *it;
std::cout << '\n';
//21. Demo move
std::cout << "21. Demo move " << std::endl;
std::vector<int> tmp2(10);
std::move(myvector.begin(), myvector.begin() + 10, tmp2.begin());
std::cout << "myvector contains:";
for (std::vector<int>::iterator it4 = tmp2.begin(); it4 != tmp2.end(); ++it4)
std::cout << ' ' << *it4;
std::cout << '\n';
//22. Demo move_backward
std::cout << "22. Demo move_backward " << std::endl;
std::string elems[10] = { "air", "water", "fire", "earth" };
// insert new element at the beginning:
std::move_backward(elems, elems + 4, elems + 5);
elems[0] = "ether";
std::cout << "elems contains:";
for (int i = 0; i<10; ++i)
std::cout << " ["<< elems[i] << "]";
std::cout << '\n';
//23. Demo fill
std::cout << "23. Demo fill " << std::endl;
std::fill(myvector.begin(), myvector.begin() + 4, 5);
std::cout << "myvector contains:";
for (std::vector<int>::iterator it = myvector.begin(); it != myvector.end(); ++it)
std::cout << ' ' << *it;
std::cout << '\n';
//24. Demo fill_n
std::cout << "24. Demo fill_n " << std::endl;
std::fill_n(myvector.begin(), 4, 20);
std::cout << "myvector contains:";
for (std::vector<int>::iterator it = myvector.begin(); it != myvector.end(); ++it)
std::cout << ' ' << *it;
std::cout << '\n';
//25. Demo transform
std::cout << "25. Demo transform " << std::endl;
myvector.resize(foo.size());
std::transform(foo.begin(), foo.end(), myvector.begin(), op_increase);
std::cout << "myvector contains:";
for (std::vector<int>::iterator it = myvector.begin(); it != myvector.end(); ++it)
std::cout << ' ' << *it;
std::cout << '\n';
//26. Demo generate
std::cout << "26. Demo generate " << std::endl;
std::generate(myvector.begin(), myvector.end(), RandomNumber);
std::cout << "myvector contains:";
for (std::vector<int>::iterator it = myvector.begin(); it != myvector.end(); ++it)
std::cout << ' ' << *it;
std::cout << '\n';
//27. Demo generate_n
std::cout << "27. Demo generate_n " << std::endl;
int myarray[9];
std::generate_n(myarray, 9, UniqueNumber);
std::cout << "myarray contains:";
for (int i = 0; i<9; ++i)
std::cout << ' ' << myarray[i];
std::cout << '\n';
//28. Demo remove remove_if
std::cout << "28. Demo remove remove_if " << std::endl;
int* pbegin = foo2;
int* pend = foo2 + sizeof(foo2) / sizeof(int);
pend = std::remove(pbegin, pend, 7);
std::cout << "range contains:";
for (int* p = pbegin; p != pend; ++p)
std::cout << ' ' << *p;
std::cout << '\n';
//29. Demo remove_copy remove_copy_if
std::cout << "29. Demo remove_copy " << std::endl;
std::remove_copy(foo2, foo2 + 8, myvector.begin(), 7);
std::cout << "myvector contains:";
for (std::vector<int>::iterator it = myvector.begin(); it != myvector.end(); ++it)
std::cout << ' ' << *it;
std::cout << '\n';
//30. Demo replace replace_if
std::cout << "30. Demo replace replace_if " << std::endl;
std::replace(myvector.begin(), myvector.end(), 5, -999);
std::cout << "myvector contains:";
for (std::vector<int>::iterator it = myvector.begin(); it != myvector.end(); ++it)
std::cout << ' ' << *it;
std::cout << '\n';
//31. Demo replace_copy replace_copy_if
std::cout << "31. Demo replace_copy replace_copy_if " << std::endl;
std::replace_copy(foo2, foo2 + 8, myvector.begin(), 5, 9999);
std::cout << "myvector contains:";
for (std::vector<int>::iterator it = myvector.begin(); it != myvector.end(); ++it)
std::cout << ' ' << *it;
std::cout << '\n';
//32. Demo swap
std::cout << "32. Demo swap " << std::endl;
int x = 3, y = 9;
std::cout << " before swap: x= " << x << ", y= " << y << std::endl;
std::swap(x, y);
std::cout << " after swap: x= " << x << ", y= " << y << std::endl;
//33. Demo swap_ranges
std::cout << "33. Demo swap_ranges " << std::endl;
std::swap_ranges(foo.begin() + 1, foo.end() - 1, myvector.begin());
std::cout << "foo contains:";
for (std::vector<int>::iterator it = foo.begin(); it != foo.end(); ++it)
std::cout << ' ' << *it;
std::cout << '\n';
std::cout << "myvector contains:";
for (std::vector<int>::iterator it = myvector.begin(); it != myvector.end(); ++it)
std::cout << ' ' << *it;
std::cout << '\n';
//34. Demo iter_swap
std::cout << "34. Demo iter_swap " << std::endl;
std::iter_swap(foo2, myvector.begin());
std::cout << "myvector contains:";
for (std::vector<int>::iterator it = myvector.begin(); it != myvector.end(); ++it)
std::cout << ' ' << *it;
std::cout << '\n';
//35. Demo reverse
std::cout << "35. Demo reverse " << std::endl;
std::reverse(myvector.begin(), myvector.end());
std::cout << "myvector contains:";
for (std::vector<int>::iterator it = myvector.begin(); it != myvector.end(); ++it)
std::cout << ' ' << *it;
std::cout << '\n';
//36. Demo reverse_copy
std::cout << "36. Demo reverse_copy " << std::endl;
std::reverse_copy(foo2, foo2 + 9, myvector.begin());
std::cout << "myvector contains:";
for (std::vector<int>::iterator it = myvector.begin(); it != myvector.end(); ++it)
std::cout << ' ' << *it;
std::cout << '\n';
//37. Demo rotate
std::cout << "37. Demo rotate " << std::endl;
std::rotate(myvector.begin(), myvector.begin() + 3, myvector.end());
std::cout << "myvector contains:";
for (std::vector<int>::iterator it = myvector.begin(); it != myvector.end(); ++it)
std::cout << ' ' << *it;
std::cout << '\n';
//38. Demo rotate_copy
std::cout << "38. Demo rotate_copy " << std::endl;
std::rotate_copy(foo2, foo2 + 3, foo2 + 7, myvector.begin());
std::cout << "myvector contains:";
for (std::vector<int>::iterator it = myvector.begin(); it != myvector.end(); ++it)
std::cout << ' ' << *it;
std::cout << '\n';
//39. Demo random_shuffle shuffle
std::cout << "39. Demo random_shuffle shuffle " << std::endl;
// using built-in random generator:
std::random_shuffle(myvector.begin(), myvector.end());
std::cout << "myvector contains:";
for (std::vector<int>::iterator it = myvector.begin(); it != myvector.end(); ++it)
std::cout << ' ' << *it;
std::cout << '\n';
//40. Demo sample
//41. Demo unique
std::cout << "41. Demo unique " << std::endl;
std::unique(myvector.begin(), myvector.end());
std::cout << "myvector contains:";
for (std::vector<int>::iterator it = myvector.begin(); it != myvector.end(); ++it)
std::cout << ' ' << *it;
std::cout << '\n';
//42. Demo unique_copy
std::cout << "42. Demo unique_copy " << std::endl;
int myints[] = { 10, 20, 20, 20, 30, 30, 20, 20, 10 };
std::vector<int> myvector2(9);
std::vector<int>::iterator it4;
it4 = std::unique_copy(myints, myints + 9, myvector2.begin());
std::sort(myvector2.begin(), it4);
it4 = std::unique_copy(myvector2.begin(), it4, myvector2.begin(), myCompare);
myvector2.resize(std::distance(myvector2.begin(), it4));
std::cout << "myvector2 contains:";
for (it4 = myvector2.begin(); it4 != myvector2.end(); ++it4)
std::cout << ' ' << *it4;
std::cout << '\n';
//43. Demo is_partitioned
std::cout << "43. Demo is_partitioned " << std::endl;
// print contents:
std::cout << "foo:"; for (int& x : foo) std::cout << ' ' << x;
if (std::is_partitioned(foo.begin(), foo.end(), IsOdd))
std::cout << " (partitioned)\n";
else
std::cout << " (not partitioned)\n";
//44. Demo partition
std::cout << "44. Demo partition " << std::endl;
std::vector<int>::iterator bound;
bound = std::partition(myvector.begin(), myvector.end(), IsOdd);
// print out content:
std::cout << "odd elements:";
for (std::vector<int>::iterator it = myvector.begin(); it != bound; ++it)
std::cout << ' ' << *it;
std::cout << '\n';
std::cout << "even elements:";
for (std::vector<int>::iterator it = bound; it != myvector.end(); ++it)
std::cout << ' ' << *it;
std::cout << '\n';
//45. Demo partition_copy
std::cout << "45. Demo partition_copy " << std::endl;
std::vector<int> odd, even;
// resize vectors to proper size:
unsigned n = std::count_if(foo.begin(), foo.end(), IsOdd);
odd.resize(n); even.resize(foo.size() - n);
// partition:
std::partition_copy(foo.begin(), foo.end(), odd.begin(), even.begin(), IsOdd);
// print contents:
std::cout << "odd: "; for (int& x : odd) std::cout << ' ' << x; std::cout << '\n';
std::cout << "even: "; for (int& x : even) std::cout << ' ' << x; std::cout << '\n';
//46. Demo stable_partition
std::cout << "46. Demo stable_partition " << std::endl;
std::vector<int>::iterator bound2;
bound2 = std::stable_partition(myvector.begin(), myvector.end(), IsOdd);
// print out content:
std::cout << "odd elements:";
for (std::vector<int>::iterator it = myvector.begin(); it != bound2; ++it)
std::cout << ' ' << *it;
std::cout << '\n';
std::cout << "even elements:";
for (std::vector<int>::iterator it = bound2; it != myvector.end(); ++it)
std::cout << ' ' << *it;
std::cout << '\n';
//47. Demo partition_point
std::cout << "47. Demo partition_point " << std::endl;
std::vector<int> odd2;
std::partition(foo.begin(), foo.end(), IsOdd);
auto it5 = std::partition_point(foo.begin(), foo.end(), IsOdd);
odd2.assign(foo.begin(), it5);
// print contents of odd:
std::cout << "odd:";
for (int& x : odd2) std::cout << ' ' << x;
std::cout << '\n';
//48. Demo is_sorted
std::cout << "48. Demo is_sorted " << std::endl;
std::cout << " Is foo sorted ? " << std::is_sorted(foo.begin(), foo.end())<<std::endl;
//49. Demo is_sorted_until
std::cout << "49. Demo is_sorted_until " << std::endl;
std::array<int, 4> foo6={ 2, 4, 1, 3 };
std::array<int, 4>::iterator it6;
it6 = std::is_sorted_until(foo6.begin(), foo6.end());
std::cout << " " << (it6 - foo6.begin()) << " elements sorted\n";
//50. Demo sort
std::cout << "50. Demo sort " << std::endl;
std::sort(foo.begin(), foo.end());
std::cout << "foo contains:";
for (it4 = foo.begin(); it4 != foo.end(); ++it4)
std::cout << ' ' << *it4;
std::cout << '\n';
//51. Demo partial_sort
std::cout << "51. Demo partial_sort " << std::endl;
// using default comparison (operator <):
std::partial_sort(myvector.begin(), myvector.end(), myvector.end());
// print out content:
std::cout << "myvector contains:";
for (std::vector<int>::iterator it = myvector.begin(); it != myvector.end(); ++it)
std::cout << ' ' << *it;
std::cout << '\n';
//52. Demo partial_sort_copy
std::cout << "52. Demo partial_sort_cop " << std::endl;
// using function as comp
std::partial_sort_copy(myints, myints + 9, myvector.begin(), myvector.end(), compareLessThan);
// print out content:
std::cout << "myvector contains:";
for (std::vector<int>::iterator it = myvector.begin(); it != myvector.end(); ++it)
std::cout << ' ' << *it;
std::cout << '\n';
//53. Demo stable_sort
std::cout << "53. Demo stable_sort " << std::endl;
double mydoubles[] = { 3.14, 1.41, 2.72, 4.67, 1.73, 1.32, 1.62, 2.58 };
std::vector<double> myvector3;
myvector3.assign(mydoubles, mydoubles + 8);
std::cout << "myvector3 contains:";
std::stable_sort(myvector3.begin(), myvector3.end());
for (std::vector<double>::iterator it = myvector3.begin(); it != myvector3.end(); ++it)
std::cout << ' ' << *it;
std::cout << '\n';
//54. Demo nth_element
std::cout << "54. Demo nth_element " << std::endl;
std::nth_element(myvector.begin(), myvector.begin() + 5, myvector.end());
std::cout << "myvector contains:";
for (std::vector<int>::iterator it = myvector.begin(); it != myvector.end(); ++it)
std::cout << ' ' << *it;
std::cout << '\n';
//55. Demo lower_bound
std::cout << "55. Demo lower_bound " << std::endl;
std::vector<int>::iterator low, up;
low = std::lower_bound(myvector.begin(), myvector.end(), 20);
std::cout << "lower_bound at position " << (low - myvector.begin()) << '\n';
//56. Demo upper_bound
std::cout << "56. Demo upper_bound " << std::endl;
up = std::upper_bound(myvector.begin(), myvector.end(), 20);
std::cout << "upper_bound at position " << (up - myvector.begin()) << '\n';
//57. Demo binary_search
std::cout << "57. Demo binary_search " << std::endl;
std::cout << "looking for a 11 in foo... ";
if (std::binary_search(foo.begin(), foo.end(), 11))
std::cout << "found!\n"; else std::cout << "not found.\n";
//58. Demo equal_range
std::cout << "58. Demo equal_range " << std::endl;
std::vector<int> v(myints, myints + 8);
std::pair<std::vector<int>::iterator, std::vector<int>::iterator> bounds;
// using default comparison:
std::sort(v.begin(), v.end());
bounds = std::equal_range(v.begin(), v.end(), 20);
std::cout << "bounds at positions " << (bounds.first - v.begin());
std::cout << " and " << (bounds.second - v.begin()) << '\n';
//59. Demo merge
std::cout << "59. Demo merge " << std::endl;
std::merge(tmp, tmp + 2, foo2, foo2 + 5, myvector.begin());
std::cout << "myvector contains:";
for (std::vector<int>::iterator it = myvector.begin(); it != myvector.end(); ++it)
std::cout << ' ' << *it;
std::cout << '\n';
//60. Demo inplace_merge
std::cout << "60. Demo inplace_merge " << std::endl;
std::inplace_merge(myvector.begin(), myvector.begin() + 5, myvector.end());
std::cout << "myvector contains:";
for (std::vector<int>::iterator it7 = myvector.begin(); it7 != myvector.end(); ++it7)
std::cout << ' ' << *it7;
std::cout << '\n';
//61. Demo includes
std::cout << "61. Demo includes " << std::endl;
// using default comparison:
if (std::includes(tmp, tmp + 2, foo2, foo2 + 4))
std::cout << "tmp includes foo2!\n";
else
std::cout << "tmp doesn't includes foo2!\n";
//62. Demo set_difference
std::cout << "62. Demo set_difference " << std::endl;
it = std::set_difference(tmp, tmp + 2, foo2, foo2 + 5, v.begin());
v.resize(it - v.begin());
std::cout << "The difference has " << (v.size()) << " elements:\n";
for (it = v.begin(); it != v.end(); ++it)
std::cout << ' ' << *it;
std::cout << '\n';
//63. Demo set_intersection
std::cout << "63. Demo set_intersection " << std::endl;
it = std::set_difference(tmp, tmp + 2, foo2, foo2 + 5, v.begin());
v.resize(it - v.begin());
std::cout << "The intersection has " << (v.size()) << " elements:\n";
for (it = v.begin(); it != v.end(); ++it)
std::cout << ' ' << *it;
std::cout << '\n';
//64. Demo set_symmetric_difference
std::cout << "64. Demo set_symmetric_difference " << std::endl;
it = std::set_difference(tmp, tmp + 2, foo2, foo2 + 5, v.begin());
v.resize(it - v.begin());
std::cout << "The symmetric difference has " << (v.size()) << " elements:\n";
for (it = v.begin(); it != v.end(); ++it)
std::cout << ' ' << *it;
std::cout << '\n';
//65. Demo set_union
std::cout << "65. Demo set_union " << std::endl;
it = std::set_difference(tmp, tmp + 2, foo2, foo2 + 5, v.begin());
v.resize(it - v.begin());
std::cout << "The union has " << (v.size()) << " elements:\n";
for (it = v.begin(); it != v.end(); ++it)
std::cout << ' ' << *it;
std::cout << '\n';
//67. Demo is_heap
std::cout << "67. Demo is_heap " << std::endl;
std::cout << " Is foo heap? " << std::is_heap(foo.begin(), foo.end()) << '\n';
//68. Demo is_heap_until
std::cout << "68. Demo is_heap_until " << std::endl;
auto last = std::is_heap_until(foo.begin(), foo.end());
std::cout << "The " << (last - foo.begin()) << " first elements are a valid heap:";
//69. Demo make_heap
std::cout << "69. Demo make_heap " << std::endl;
if (!std::is_heap(foo.begin(), foo.end()))
std::make_heap(foo.begin(), foo.end());
std::cout << "foo contains:";
for (std::vector<int>::iterator it7 = foo.begin(); it7 != foo.end(); ++it7)
std::cout << ' ' << *it7;
std::cout << '\n';
//70. Demo push_heap
std::cout << "70. Demo push_heap " << std::endl;
foo.push_back(99); std::push_heap(foo.begin(), foo.end());
std::cout << "max heap after push: " << foo.front() << '\n';
//71. Demo pop_heap
std::cout << "71. Demo pop_heap " << std::endl;
std::pop_heap(foo.begin(), foo.end()); foo.pop_back();
std::cout << "max heap after pop : " << foo.front() << '\n';
//72. Demo sort_heap
std::cout << "72. Demo sort_heap " << std::endl;
std::sort_heap(foo.begin(), foo.end());
std::cout << "final sorted range :";
for (unsigned i = 0; i<foo.size(); i++)
std::cout << ' ' << foo[i];
std::cout << '\n';
//73. Demo max
std::cout << "73. Demo max " << std::endl;
std::cout << " max(1,2)==" << std::max(1, 2) << '\n';
//74. Demo max_element
std::cout << "74. Demo max_element " << std::endl;
std::cout << "The largest myints's element is " << *std::max_element(myints, myints + 7) << '\n';
//75. Demo min
std::cout << "75. Demo min " << std::endl;
std::cout << " min(1,2)==" << std::min(1, 2) << '\n';
//76. Demo min_element
std::cout << "76. Demo min_element " << std::endl;
std::cout << "The smallest myints's element is " << *std::min_element(myints, myints + 7) << '\n';
//77. Demo minmax
std::cout << "77. Demo minmax " << std::endl;
auto result = std::minmax({ 1, 2, 3, 4, 5 });
std::cout << "minmax({1,2,3,4,5}): ";
std::cout << result.first << ' ' << result.second << '\n';
//78. Demo minmax_element
std::cout << "78. Demo minmax_element " << std::endl;
std::array<int, 7> foo4 = { 3, 7, 2, 9, 5, 8, 6 };
auto result2 = std::minmax_element(foo4.begin(), foo4.end());
// print result:
std::cout << "min is " << *result2.first;
std::cout << ", at position " << (result2.first - foo4.begin()) << '\n';
std::cout << "max is " << *result2.second;
std::cout << ", at position " << (result2.second - foo4.begin()) << '\n';
//79. Demo clamp
//80. Demo lexicographical_compare
std::cout << "80. Demo lexicographical_compare " << std::endl;
std::cout << std::boolalpha;
std::cout << "Comparing foo2 and tmp lexicographically (foo2<tmp):\n";
std::cout << "Using default comparison (operator<): ";
std::cout << std::lexicographical_compare(foo2, foo2 + 5, tmp, tmp + 2);
std::cout << '\n';
//81. Demo is_permutation
std::cout << "81. Demo is_permutation " << std::endl;
if (!std::is_permutation(foo.begin(), foo.end(), foo3.begin()))
std::cout << "foo and bar don't contain the same elements.\n";
else
std::cout << "foo and bar contain the same elements.\n";
//82. Demo next_permutation
std::cout << "82. Demo next_permutation " << std::endl;
if (!std::next_permutation(foo2, foo2 + 3))
std::cout << "foo2 isn next_permutation.\n";
else
std::cout << "foo2 is next_permutation.\n";
//83. Demo prev_permutation
std::cout << "83. Demo prev_permutation " << std::endl;
if (!std::prev_permutation(foo2, foo2 + 3))
std::cout << "foo2 isn prev_permutation.\n";
else
std::cout << "foo2 is prev_permutation.\n";
//84. Demo iota
std::cout << "84. Demo iota " << std::endl;
char buffer[33];
int i = 50123;
_itoa(i, buffer, 10);
printf("decimal: %s\n", buffer);
//85. Demo accumulate
std::cout << "85. Demo accumulate " << std::endl;
int numbers[] = { 10, 20, 30 };
std::cout << " accumulate: ";
std::cout << std::accumulate(numbers, numbers + 3, 100);
//86. Demo inner_product
std::cout << "86. Demo inner_product " << std::endl;
int series1[] = { 10, 20, 30 };
int series2[] = { 1, 2, 3 };
std::cout << " inner_product: ";
std::cout << std::inner_product(series1, series1 + 3, series2, 100);
std::cout << '\n';
//87. Demo adjacent_difference
std::cout << "87. Demo adjacent_difference " << std::endl;
int val[] = { 1, 2, 3, 5, 9, 11, 12 };
int result8[7];
std::adjacent_difference(val, val + 7, result8);
std::cout << "using default adjacent_difference: ";
for (int i = 0; i<7; i++) std::cout << result8[i] << ' ';
std::cout << '\n';
//88. Demo partial_sum
std::cout << "88. Demo partial_sum " << std::endl;
std::partial_sum(val, val + 5, result8);
std::cout << "using default partial_sum: ";
for (int i = 0; i<5; i++) std::cout << result8[i] << ' ';
std::cout << '\n';
//89. Demo reduce
std::cout << "89. Demo reduce " << std::endl;
//90. Demo exclusive_scan
std::cout << "90. Demo exclusive_scan " << std::endl;
//91. Demo inclusive_scan
std::cout << "91. Demo inclusive_scan " << std::endl;
//92. Demo transform_reduce
std::cout << "92. Demo transform_reduce " << std::endl;
//93. Demo transform_exclusive_scan
std::cout << "93. Demo transform_exclusive_scan " << std::endl;
//94. Demo transform_inclusive_scan
std::cout << "94. Demo transform_inclusive_scan " << std::endl;
//95. Demo uninitialized_copy
std::cout << "95. Demo uninitialized_copy " << std::endl;
std::string numbers2[] = { "one", "two", "three" };
// get block of uninitialized memory:
std::pair <std::string*, std::ptrdiff_t> result9 = std::get_temporary_buffer<std::string>(3);
if (result9.second>0) {
std::uninitialized_copy(numbers2, numbers2 + result9.second, result9.first);
for (int i = 0; i<result9.second; i++)
std::cout << result9.first[i] << " ";
std::cout << '\n';
std::return_temporary_buffer(result9.first);
}
//96. Demo uninitialized_copy_n
std::cout << "96. Demo uninitialized_copy_n " << std::endl;
std::pair <std::string*, std::ptrdiff_t> result12 = std::get_temporary_buffer<std::string>(3);
if (result12.second>0) {
std::uninitialized_copy_n(numbers2, result12.second, result12.first);
for (int i = 0; i<result12.second; i++)
std::cout << result12.first[i] << ' ';
std::cout << '\n';
std::return_temporary_buffer(result12.first);
}
//97. Demo uninitialized_fill
std::cout << "97. Demo uninitialized_fill " << std::endl;
// get block of uninitialized memory:
std::pair <std::string*, std::ptrdiff_t>
result10 = std::get_temporary_buffer<std::string>(3);
if (result10.second>0) {
std::uninitialized_fill(result10.first, result10.first + result10.second, "c++ rocks!");
for (int i = 0; i<result10.second; i++)
std::cout << result10.first[i] << '\n';
std::return_temporary_buffer(result10.first);
}
//98. Demo uninitialized_fill_n
std::cout << "98. Demo uninitialized_fill_n " << std::endl;
std::pair <std::string*, std::ptrdiff_t>
result11 = std::get_temporary_buffer<std::string>(3);
if (result.second>0) {
std::uninitialized_fill_n(result11.first, result11.second, "c++ rocks!");
for (int i = 0; i<result11.second; i++)
std::cout << result11.first[i] << '\n';
std::return_temporary_buffer(result11.first);
}
//99. Demo uninitialized_move
std::cout << "99.. Demo uninitialized_move " << std::endl;
//100. Demo uninitialized_move_n
std::cout << "100. Demo uninitialized_move_n " << std::endl;
//101. Demo qsort
std::cout << "101. Demo qsort " << std::endl;
int values[] = { 40, 10, 100, 90, 20, 25 };
qsort(values, 6, sizeof(int), isBetter);
for (n = 0; n<6; n++)
printf("%d ", values[n]);
//102. Demo bsearch
std::cout << "102. Demo bsearch " << std::endl;
int * pItem;
int key = 40;
qsort(values, 6, sizeof (int), isBetter);
pItem = (int*)bsearch(&key, values, 6, sizeof (int), isBetter);
if (pItem != NULL)
printf("%d is in the array.\n", *pItem);
else
printf("%d is not in the array.\n", key);
return 0;
}
|
Java
|
UTF-8
| 916
| 2.671875
| 3
|
[] |
no_license
|
package utilities;
import java.awt.AWTException;
import java.awt.Robot;
import java.awt.Toolkit;
import java.awt.datatransfer.StringSelection;
import java.awt.event.KeyEvent;
import org.openqa.selenium.WebDriver;
public class RobotClassUtility {
public void robotUploadFile(String filepath) throws AWTException
{
// creating object of Robot class
Robot rb = new Robot();
// copying File path to Clipboard
StringSelection str = new StringSelection(filepath);
Toolkit.getDefaultToolkit().getSystemClipboard().setContents(str, null);
// press Contol+V for pasting
rb.keyPress(KeyEvent.VK_CONTROL);
rb.keyPress(KeyEvent.VK_V);
// release Contol+V
rb.keyRelease(KeyEvent.VK_CONTROL);
rb.keyRelease(KeyEvent.VK_V);
// for pressing and releasing Enter
rb.keyPress(KeyEvent.VK_ENTER);
rb.keyRelease(KeyEvent.VK_ENTER);
}
}
|
Python
|
UTF-8
| 3,281
| 3.65625
| 4
|
[] |
no_license
|
'''
一个著名的博弈论游戏,起源大概是一个美国电视游戏节目叫做Let's make a deal,这个问题名字来源于节目主持人Monty Hall 。
游戏简述:
“参赛者会看见三扇关闭了的门,其中一扇的后面有一辆汽车或者是奖品,选中后面有车的那扇门就可以赢得该汽车或奖品,而另外两扇门后面则各藏有一只山羊或者是后面没有任何东西。当参赛者选定了一扇门,但未去开启它的时候,知道门后情形的节目主持人会开启剩下两扇门的其中一扇,露出其中一只山羊。主持人其后会问参赛者要不要换另一扇仍然关上的门。问题是:换另一扇门会否增加参赛者赢得汽车的机会率?如果严格按照上述的条件的话,答案是会。—换门的话,赢得汽车的概率是2/3。”
用python仿写这个游戏
作者:Sisyphus235
链接:http://www.jianshu.com/p/a036a8a14a4c
來源:简书
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
'''
'''
It is a game theory trick, the player would be given 3 closed door, one of the door has a prize behind, and other two doors
have one sheep behind.
After player made a choice, the , to make sure a stable result, the game holder will open a door which has a sheep behind(definately
the game holder knows where is the sheep), and ask the player if he would like to change his choice.
So the program should be:
3 -> 1
2 -> 1(sheep)
change or not?
give result
'''
from random import randint,seed
# set seed = 0
seed(0)
while True:
try:
times = int(input('Enter the number of times to run the simulation: '))
choice = str(input('Do you want the contestant to switch door?'))
if choice == 'no' or 'No' or 'N' or 'NO' or 'n':
choice = None
choice = False
elif choice == 'yes' or 'Yes' or 'YES' or 'Y':
choice = None
choice = True
else:
raise Exception
break
except:
print('Incorrect Input, retry please.')
def simulate(n):
probablity = 0
for _ in range(n):
prize_place = randint(1,3)
print(f'Contestant does not know it, but car happens to be behind door {chr(64+prize_place)}',end='.')
which_one = randint(1,2)
game_host = 0
contestant = randint(1,3)
L = [1,2,3]
L.remove(prize_place)
if which_one == 1:
game_host = L[0]
else:
game_host = L[1]
print(f'Contestant chooses door {chr(64+contestant)}',end='.\n')
print(f'Game host opens door {chr(64+game_host)}',end='.\n')
if choice:
# choose to change another door.
L.remove(contestant)
contestant = L[0]
print(f'Contestant chooses door {chr(64+contestant)} and {"win"if contestant==prize_place else "lose"} the game', end='.\n')
else:
print(f'Contestant chooses door {chr(64+contestant)} and {"win"if contestant==prize_place else "lose"} the game', end='.\n')
if contestant == prize_place:
probablity+=1
p = probablity/n
print('The probability of win :',round(p,3)*100,'%')
simulate(times)
|
TypeScript
|
UTF-8
| 633
| 2.625
| 3
|
[] |
no_license
|
import {Response} from "express";
import {IOutput} from "./IOutput";
import {OutStatus} from "./OutStatus";
import {OutText} from "./OutText";
export class OutStatusNoContent implements IOutput {
private statusCode: number = 204;
private origin: IOutput;
constructor(reason: string = "No Content") {
this.origin = new OutStatus(
this.statusCode,
new OutText(
`${this.statusCode} ${reason}`
)
);
}
public with(values: any): IOutput {
return this;
}
public write(res: Response): void {
this.origin.write(res);
}
}
|
Java
|
UTF-8
| 4,341
| 2.234375
| 2
|
[] |
no_license
|
package gatetest;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import gate.Annotation;
import gate.AnnotationSet;
import gate.Document;
import gate.Utils;
public class GateParser {
private Document document;
public GateParser(Document document) {
this.document = document;
}
public String getLocation(AnnotationSet annSet) {
String type = "Location";
String location = null;
AnnotationSet locationSet = annSet.get(type);
List<Annotation> locationsList = new ArrayList<Annotation>(locationSet);
if (locationsList.isEmpty()) {
location = "Sofia";
} else {
for (Annotation a : locationsList) {
location = Utils.stringFor(document, a);
}
}
return location;
}
public String isSpecificConditionCheck(AnnotationSet annSet) {
String type = "WeatherCondition";
String condition = null;
AnnotationSet conditionSet = annSet.get(type);
List<Annotation> conditionsList = new ArrayList<Annotation>(conditionSet);
if (conditionsList.isEmpty()) {
return null;
} else {
for (Annotation a : conditionsList) {
condition = a.getFeatures().get("kind").toString();
}
}
return condition;
}
public String isCheckForTemperatureOrHumidity(AnnotationSet annSet) {
String type = "WeatherDetail";
String text = null;
AnnotationSet conditionSet = annSet.get(type);
List<Annotation> conditionsList = new ArrayList<Annotation>(conditionSet);
if (conditionsList.isEmpty()) {
return null;
} else {
for (Annotation a : conditionsList) {
text = Utils.stringFor(document, a);
}
}
return text;
}
public boolean isCheckForForecat(AnnotationSet annSet) {
String type = "Forecast";
AnnotationSet forecastSet = annSet.get(type);
List<Annotation> forecastList = new ArrayList<Annotation>(forecastSet);
if (forecastList.isEmpty()) {
return false;
} else {
return true;
}
}
public static String getDate(AnnotationSet annSet) {
String type = "ConvertDate";
String date = null;
AnnotationSet dateSet = annSet.get(type);
List<Annotation> dateList = new ArrayList<Annotation>(dateSet);
if (dateList.isEmpty()) {
Date curDate = new Date();
date = new SimpleDateFormat("yyyy-MM-dd").format(curDate);
} else {
for (Annotation a : dateList) {
date = a.getFeatures().get("date").toString();
}
}
return date;
}
public boolean getAddExtraConditions(AnnotationSet annSet) {
String type = "ExtraCondition";
AnnotationSet set = annSet.get(type);
List<Annotation> list = new ArrayList<Annotation>(set);
if (list.isEmpty()) {
return false;
}
return true;
}
public boolean isQuestion(AnnotationSet annSet) {
String type = "WeatherQuestionSentences";
AnnotationSet set = annSet.get(type);
List<Annotation> questionList = new ArrayList<Annotation>(set);
if (questionList.isEmpty()) {
return false;
}
return true;
}
public boolean isNaiveBayesQuestion(AnnotationSet annSet) {
String type = "NaiveBayesQuestion";
AnnotationSet naiveBayesSet = annSet.get(type);
List<Annotation> naiveBayesList = new ArrayList<Annotation>(naiveBayesSet);
if (naiveBayesList.isEmpty()) {
return false;
}
return true;
}
public String checkNaiveBayesCondition(AnnotationSet annSet, String json, String date) {
String type = "NaiveBayesCondition";
String activity = null;
AnnotationSet naiveBayesSet = annSet.get(type);
List<Annotation> naiveBayesList = new ArrayList<Annotation>(naiveBayesSet);
for (Annotation a : naiveBayesList) {
activity = a.getFeatures().get("kind").toString();
}
NaiveBayesClassifier nb = new NaiveBayesClassifier();
String fileName = "TrainingSet-" + activity;
String[] arr = new String[4];
arr[0] = JsonReader.getOverlook(json, date);
arr[1] = JsonReader.getTemperature(json, date);
arr[2] = JsonReader.getHumidity(json, date);
arr[3] = JsonReader.getWind(json, date);
String naiveBayesResult = nb.classify(arr, "TrainingSets/" + fileName);
String result = String.format(", it`s going to %s, it will be %s with %s humidity", arr[0],arr[1],arr[2]);
if (naiveBayesResult.equals("Yes")) {
return "Yes".concat(result);
} else {
return "No".concat(result);
}
}
public boolean shouldNaiveBayes(AnnotationSet annSet) {
return true;
}
}
|
JavaScript
|
UTF-8
| 1,035
| 2.546875
| 3
|
[] |
no_license
|
var request = require('request');
var cheerio = require('cheerio');
var express = require('express');
var app = express();
var mongojs = require('mongojs');
var databaseUrl = "news";
var collections = ["news"];
request("http://www.http://todayinawesome.com/", function (error, response, html) {
var $ = cheerio.load(html);
var db = mongojs(databaseUrl, collections);
var result = [ ]
console.log(result);
});
db.on('error', function(err) {
console.log('Database Error:', err);
});
app.get('/', function(req, res) {
res.send("News");
});
app.get('/all', function(req, res) {
db.news.find({}, function(err, found) {
if (err) {
console.log(err);
}
else {
res.json(found);
}
});
});
app.get('/name', function(req, res) {
db.news.find().sort({name:1}, function(err, found) {
if (err) {
console.log(err);
}
else {
res.json(found);
}
});
});
app.listen(3000, function() {
console.log('App running on port 3000!');
});
|
Java
|
UTF-8
| 4,357
| 1.828125
| 2
|
[
"Apache-2.0"
] |
permissive
|
package com.woorea.openstack.connector;
import java.util.List;
import java.util.Map;
import java.util.logging.Logger;
import javax.ws.rs.core.MultivaluedMap;
import javax.ws.rs.ext.ContextResolver;
import javax.ws.rs.ext.Provider;
import org.codehaus.jackson.jaxrs.JacksonJaxbJsonProvider;
import org.codehaus.jackson.map.DeserializationConfig;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.map.SerializationConfig;
import org.codehaus.jackson.map.annotate.JsonRootName;
import org.codehaus.jackson.map.annotate.JsonSerialize.Inclusion;
import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.UniformInterfaceException;
import com.sun.jersey.api.client.WebResource;
import com.sun.jersey.api.client.config.ClientConfig;
import com.sun.jersey.api.client.config.DefaultClientConfig;
import com.sun.jersey.client.impl.ClientRequestImpl;
import com.sun.jersey.core.header.OutBoundHeaders;
import com.woorea.openstack.base.client.OpenStackClientConnector;
import com.woorea.openstack.base.client.OpenStackRequest;
import com.woorea.openstack.base.client.OpenStackResponse;
import com.woorea.openstack.base.client.OpenStackResponseException;
public class JerseyConnector implements OpenStackClientConnector {
protected Client client = null;
protected boolean logPassword;
private JerseyLoggingFilter logger = new JerseyLoggingFilter(Logger.getLogger("os"));
public JerseyConnector() {
ClientConfig clientConfig = new DefaultClientConfig();
clientConfig.getClasses().add(JacksonJaxbJsonProvider.class);
clientConfig.getClasses().add(OpenStackObjectMapper.class);
client = Client.create(clientConfig);
}
@Override
public <T> OpenStackResponse request(OpenStackRequest<T> request) {
WebResource target = client.resource(request.endpoint()).path(request.path());
for(Map.Entry<String, List<Object> > entry : request.queryParams().entrySet()) {
for (Object o : entry.getValue()) {
target = target.queryParam(entry.getKey(), String.valueOf(o));
}
}
target.addFilter(logger);
MultivaluedMap<String, Object> headers = new OutBoundHeaders();
for(Map.Entry<String, List<Object>> h : request.headers().entrySet()) {
for(Object v : h.getValue()) {
headers.add(h.getKey(), v);
}
}
if(request.entity() != null && request.entity().getContentType() != null) {
headers.add("Content-Type", request.entity().getContentType());
} else {
headers.add("Content-Type", "application/json");
}
try {
ClientResponse response = null;
if (request.entity() != null && request.entity().getEntity() != null) {
response = target.getHeadHandler().handle(new ClientRequestImpl(target.getURI(), request.method().name(), request.entity().getEntity(), headers));
} else {
response = target.getHeadHandler().handle(new ClientRequestImpl(target.getURI(), request.method().name(), null, headers));
}
return new JerseyResponse(response);
} catch (UniformInterfaceException e) {
throw new OpenStackResponseException(e.getResponse().getClientResponseStatus().getReasonPhrase(), e.getResponse().getStatus());
}
}
@Provider
public static class OpenStackObjectMapper implements ContextResolver<ObjectMapper> {
static ObjectMapper DEFAULT_MAPPER;
static ObjectMapper WRAPPED_MAPPER;
static {
DEFAULT_MAPPER = new ObjectMapper();
DEFAULT_MAPPER.setSerializationInclusion(Inclusion.NON_NULL);
DEFAULT_MAPPER.enable(SerializationConfig.Feature.INDENT_OUTPUT);
DEFAULT_MAPPER.enable(DeserializationConfig.Feature.ACCEPT_SINGLE_VALUE_AS_ARRAY);
DEFAULT_MAPPER.disable(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES);
WRAPPED_MAPPER = new ObjectMapper();
WRAPPED_MAPPER.setSerializationInclusion(Inclusion.NON_NULL);
WRAPPED_MAPPER.enable(SerializationConfig.Feature.INDENT_OUTPUT);
WRAPPED_MAPPER.enable(SerializationConfig.Feature.WRAP_ROOT_VALUE);
WRAPPED_MAPPER.enable(DeserializationConfig.Feature.UNWRAP_ROOT_VALUE);
WRAPPED_MAPPER.enable(DeserializationConfig.Feature.ACCEPT_SINGLE_VALUE_AS_ARRAY);
WRAPPED_MAPPER.disable(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES);
}
@Override
public ObjectMapper getContext(Class<?> type) {
return type.getAnnotation(JsonRootName.class) == null ? DEFAULT_MAPPER : WRAPPED_MAPPER;
}
}
}
|
Markdown
|
UTF-8
| 2,300
| 2.84375
| 3
|
[
"MIT-0"
] |
permissive
|
---
title: "Lab 3 - Hard"
chapter: false
weight: 120
tags:
- beginner
- AWSWorkshop2020
- shiftleft
---
## Hard difficulty
Now we are making things a bit more complicated, this time, use the template named "amazon-eks-nodegroup.json"
The steps in this lab are similar to those of Lab 1:
1. In Cloud 9 console side navigation, expand the folder for your repository, and from the menu choose file, uplaod local files and upload the file with name “ amazon-eks-nodegroup.json” provided by the instructor.
2. When you have finished importing files, in the terminal window, change directories to your cloned repository and then commit and push your changes. For example, if you added a new file named MyFile.py:
cd Shift-left-repo
git status
git add MyFile.py
git commit -a -m "Updated Security Configuration"
git push
3. Go to your CodeCommit and verify that it received the code
4. Go to CodeBuild and click on Build projects. You will notice that latest build status is in progress
3. Observe the project's build progress in the build window.
4. The build will fail. Let's click the number of vioalation of the recent build to explore why.
5. From the build status screen, click "Console Output".
6. Investigate the cause of the build failure from the console output.
7. Back in Cloud9, expand the “shift-left-repo” folder and double click the “amazon-eks-nodegroup.json” file to open it in the Cloud9 code editor:
8. Using the information in the failed CodeBuild console output, try to find and fix the problem within the template. Feel free to use Google and AWS Documentation to assist with making the necessary changes!
9. When you are satisfied with your changes, save them ("File > Save") and then commit and push the changes to your repository.
10. Commit the code changes to your local copy of the code with the command ``git commit -a -m "Updated Security Configuration"`` and then push the changes to your repo by entering ``git push``
Note: This will trigger an automatic build of your new code in CodeBuild within a few seconds.
11. Go back to CodeBuild console output to see if the new build was successful.
12. If not, then investigate why it failed, try fix the issue check in the code changes again, and investigate the next build!
|
Java
|
UTF-8
| 5,994
| 2.3125
| 2
|
[] |
no_license
|
/**
* Project Name:springboot-mongodb
* File Name:StudentController.java
* Package Name:com.kaiyun.springboot.mongodb.contrller
* Date:2019年4月26日下午4:29:35
* Copyright (c) 2019, kaiyun@qk365.com All Rights Reserved.
*
*/
package com.kaiyun.springboot.mongodb.contrller;
import java.util.List;
import javax.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import com.kaiyun.springboot.mongodb.common.BusinessCode;
import com.kaiyun.springboot.mongodb.common.CommonResp;
import com.kaiyun.springboot.mongodb.common.Page;
import com.kaiyun.springboot.mongodb.common.RespUtil;
import com.kaiyun.springboot.mongodb.dto.PageDTO;
import com.kaiyun.springboot.mongodb.model.Student;
import com.kaiyun.springboot.mongodb.server.StudentService;
import com.mongodb.client.result.UpdateResult;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
/**
* ClassName:StudentController <br/>
* Function: TODO ADD FUNCTION. <br/>
* Date: 2019年4月26日 下午4:29:35 <br/>
* @author kaiyun
* @version
* @since JDK 1.8
* @see
*/
@Api(value = "MongoDB测试项目", tags = "V1.0")
@RestController
public class StudentController {
@Autowired
private StudentService studentService;
@ApiOperation(value = "add Student", notes = "add Student")
@RequestMapping(value = "/add", method = RequestMethod.POST)
public CommonResp<?> add(@RequestBody @Valid Student student, BindingResult bindingResult){
if (bindingResult.hasErrors()) {
return CommonResp.<Student>builder().result(BusinessCode.PARAMS_ERROR.getErrorCode().getCode())
.message(bindingResult.getFieldError().getDefaultMessage()).data(null).build();
}
Student stu = studentService.add(student);
return RespUtil.buildVo(stu, BusinessCode.SUCCESS.getErrorCode());
}
@ApiOperation(value = "update Student", notes = "update Student")
@RequestMapping(value = "/update", method = RequestMethod.POST)
public CommonResp<?> update(@RequestBody @Valid Student student, BindingResult bindingResult){
if (bindingResult.hasErrors()) {
return CommonResp.<Object>builder().result(BusinessCode.PARAMS_ERROR.getErrorCode().getCode())
.message(bindingResult.getFieldError().getDefaultMessage()).data(null).build();
}
UpdateResult updateResult = studentService.update(student);
return RespUtil.buildVo(updateResult, BusinessCode.SUCCESS.getErrorCode());
}
@ApiOperation(value = "根据name查Student", notes = "根据name查Student")
@RequestMapping(value = "/findByName", method = RequestMethod.POST)
public CommonResp<?> findByName(@RequestBody @Valid String name, BindingResult bindingResult){
if (bindingResult.hasErrors()) {
return CommonResp.<Student>builder().result(BusinessCode.PARAMS_ERROR.getErrorCode().getCode())
.message(bindingResult.getFieldError().getDefaultMessage()).data(null).build();
}
Student student = studentService.findByName(name);
return RespUtil.buildVo(student, BusinessCode.SUCCESS.getErrorCode());
}
@ApiOperation(value = "根据sex查Student", notes = "根据sex查Student")
@RequestMapping(value = "/findBySex", method = RequestMethod.POST)
public CommonResp<?> findBySex(@RequestBody @Valid String sex, BindingResult bindingResult){
if (bindingResult.hasErrors()) {
return CommonResp.<List<Student>>builder().result(BusinessCode.PARAMS_ERROR.getErrorCode().getCode())
.message(bindingResult.getFieldError().getDefaultMessage()).data(null).build();
}
List<Student> studentList = studentService.findBySex(sex);
return RespUtil.buildVo(studentList, BusinessCode.SUCCESS.getErrorCode());
}
@ApiOperation(value = "查所有Student", notes = "查所有Student")
@RequestMapping(value = "/findAll", method = RequestMethod.POST)
public CommonResp<?> findAll(){
List<Student> studentList = studentService.findAll();
return RespUtil.buildVo(studentList, BusinessCode.SUCCESS.getErrorCode());
}
@ApiOperation(value = "分页查Student", notes = "分页查Student")
@RequestMapping(value = "/findByPage", method = RequestMethod.POST)
public CommonResp<?> findByPage(@RequestBody @Valid PageDTO dto, BindingResult bindingResult){
if (bindingResult.hasErrors()) {
return CommonResp.<Page<Student>>builder().result(BusinessCode.PARAMS_ERROR.getErrorCode().getCode())
.message(bindingResult.getFieldError().getDefaultMessage()).data(null).build();
}
Page<Student> page = studentService.findPage(dto);
return RespUtil.buildVo(page, BusinessCode.SUCCESS.getErrorCode());
}
@ApiOperation(value = "查所有Student的数量", notes = "查所有Student的数量")
@RequestMapping(value = "/findCount", method = RequestMethod.POST)
public CommonResp<?> count(){
long count = studentService.count();
return RespUtil.buildVo(count, BusinessCode.SUCCESS.getErrorCode());
}
@ApiOperation(value = "delete Student", notes = "delete Student")
@RequestMapping(value = "/delete", method = RequestMethod.POST)
public CommonResp<?> delete(@RequestBody @Valid String id, BindingResult bindingResult){
if (bindingResult.hasErrors()) {
return CommonResp.<Integer>builder().result(BusinessCode.PARAMS_ERROR.getErrorCode().getCode())
.message(bindingResult.getFieldError().getDefaultMessage()).data(null).build();
}
studentService.delete(id);
return RespUtil.buildErrorVo(BusinessCode.SUCCESS.getErrorCode());
}
}
|
Java
|
UTF-8
| 606
| 2.296875
| 2
|
[] |
no_license
|
package vo;
public class RegisterVO {
private String user_id;
private String email;
private String passwd;
public String getUser_id() {
return user_id;
}
public void setUser_id(String user_id) {
this.user_id = user_id;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPasswd() {
return passwd;
}
public void setPasswd(String passwd) {
this.passwd = passwd;
}
@Override
public String toString() {
return "MemberVO [user_id=" + user_id + ", email=" + email + ", passwd=" + passwd + "]";
}
}
|
TypeScript
|
UTF-8
| 1,810
| 2.578125
| 3
|
[] |
no_license
|
import { useState, useRef } from 'react';
import { isPhone } from '@/utils/validation';
import BackgroundTimer from 'react-native-background-timer';
import { isIOS } from '@/config/size';
import useToast from './useToast';
export default function useSms() {
let interval: NodeJS.Timeout;
const [disabled, setDisabled] = useState(false);
const [smsText, setSmsText] = useState('获取验证码');
const countRef = useRef(60);
const { toastSuccess, toastFail } = useToast();
function intervalFn() {
countRef.current = countRef.current - 1;
setSmsText(`${countRef.current}s`);
if (countRef.current === 0) {
if (isIOS()) {
clearInterval(interval);
BackgroundTimer.stop();
} else {
BackgroundTimer.clearInterval(interval);
}
countRef.current = 60;
setSmsText('获取验证码');
setDisabled(false);
}
}
const sendSms = async (mobile: string) => {
if (!mobile || !isPhone(mobile)) {
toastFail('请输入正确的手机号码');
} else {
try {
setDisabled(true);
toastSuccess('验证码发送成功');
if (isIOS()) {
BackgroundTimer.start();
interval = setInterval(() => {
intervalFn();
}, 1000);
} else {
interval = BackgroundTimer.setInterval(() => {
intervalFn();
}, 1000);
}
// 发请求
} catch (error) {
toastFail('验证码获取失败');
}
}
};
const clearSms = () => {
if (isIOS()) {
clearInterval(interval);
BackgroundTimer.stop();
} else {
BackgroundTimer.clearInterval(interval);
}
setDisabled(false);
setSmsText('获取验证码');
};
return { smsText, sendSms, clearSms, disabled } as const;
}
|
Python
|
UTF-8
| 58,480
| 2.84375
| 3
|
[] |
no_license
|
# The main engine of the game that runs all of the menu screens, game entering/exiting, and hardware communications.
# Tanner Fry
# tefnq2@mst.edu
import character
import devLib
import engineLib
import npc
import settings
import importlib
import logging
import os
import pygame
from pygame.locals import *
class Game:
"""Class. Used to handle the creation, modification, and deletion of all game assets."""
def __init__(self):
"""
Constructor. Used to initialize all handlers, timers, and other variables for the game to function properly.
"""
# Initialize the game engine with necessary variables
self.buff_handler = object # The handler for the main character's buffs and debuffs
self.character = pygame.sprite.Sprite # The main character that the player will use
self.clock = pygame.time.Clock() # The frames per second
self.clock.tick(settings.FPS)
self.engine_handler = engineLib.EngineHandler(self)
self.level_current = 1
self.level_directions = '' # The directions that the character can go to get to adjacent levels
self.level_directions_down = 'None' # The level number of the level below the current level
self.level_directions_left = 'None' # The level number of the level to the left of the current level
self.level_directions_right = 'None' # The level number of the level to the right of the current level
self.level_directions_up = 'None' # The level number of the level above the current level
self.level_matrix = [] # A 2-d matrix representing a 'map' of the level each position is a sub-level
self.level_matrix_location = [0, 0] # The character's current location in the level matrix
self.level_sub_current = 1
self.level_sub_current_total = 0 # The number of total sub-levels in the current level
self.level_sub_total = 0 # The number of total sub-levels
self.level_total = settings.TOTAL_LEVELS
self.popups = []
self.running = False
self.screen = pygame.Surface
self.sprites_important = pygame.sprite.Group()
self.sprites_active_walls = pygame.sprite.Group()
self.sprites_walls = pygame.sprite.Group()
self.state = 'Play'
self.texts_to_display = []
self.window = pygame.Surface
# Initialize environment assets
self.type_tiles = {} # Used to correlate in game environment assets to specific images
# Initialize government assets (In tab order)
self.img_gov_leader_selected = pygame.Surface
self.img_gov_leader_selected_rect = pygame.Rect
self.img_gov_party_selected = pygame.Surface
self.img_gov_party_selected_rect = pygame.Rect
self.img_gov_judge_selected = pygame.Surface
self.img_gov_judge_selected_rect = pygame.Rect
self.img_gov_info_selected = pygame.Surface
self.img_gov_info_selected_rect = pygame.Rect
self.img_gov_map_selected = pygame.Surface
self.img_gov_map_selected_rect = pygame.Rect
# Initialize inventory assets (In tab order)
self.img_inv_inv_base = pygame.Surface
self.img_inv_inv_base_rect = pygame.Rect
self.img_inv_inv_selected = pygame.Surface
self.img_inv_inv_selected_rect = pygame.Rect
self.img_inv_saves_selected = pygame.Surface
self.img_inv_saves_selected_rect = pygame.Rect
self.img_inv_opt_selected = pygame.Surface
self.img_inv_opt_selected_rect = pygame.Rect
self.img_inv_feed_selected = pygame.Surface
self.img_inv_feed_selected_rect = pygame.Rect
self.img_inv_exit_selected = pygame.Surface
self.img_inv_exit_selected_rect = pygame.Rect
# Initialize npc assets
self.npc_squishy = object
def game_new(self, file_save_name: str, character_name='None'):
"""
The main function to set up a new game since the engine was started. Works with loaded games too.
@param file_save_name: the name of the file to use for the engine to start up
@param character_name: the name of the new character that the user customized
@return: none
@rtype: none
"""
try:
# Initialize assets for new game
pygame.display.set_caption(settings.TITLE_GAME)
self.screen = pygame.Surface((settings.SCREEN_WIDTH, settings.SCREEN_HEIGHT))
self.window = pygame.display.set_mode((self.engine_handler.gather_engine_info(self, 'calculate_window')), DOUBLEBUF)
# NOTE: Reimport all libraries for easier code change and testing
importlib.reload(engineLib)
self.engine_handler.reimport_all()
self.engine_handler.init_finish()
# Gather information
self.engine_handler.gather_engine_info(self, 'get_levels')
# Generate new settings file for the character to use, whether from defaults or the character save
if character_name != 'None':
self.engine_handler.save_new_game(character_name, file_save_name)
else:
self.engine_handler.load_saved_game(file_save_name)
character_name = settings.CHAR_NAME
# Initialize all environment assets for new game
# NOTE: these assets had to be initialized early due to performance issues
environment_spritesheet = engineLib.SpriteSheet(settings.DIR_SPRITES_GAME_ENVI
+ '/Ground_Grass_384_432_Spritesheet.png')
self.type_tiles = {'GL0': environment_spritesheet.get_image(0, 0, 32, 32),
'GL1': environment_spritesheet.get_image(0, 32, 32, 32),
'GL2': environment_spritesheet.get_image(0, 64, 32, 32),
'GL3': environment_spritesheet.get_image(0, 96, 32, 32),
'GL4': environment_spritesheet.get_image(0, 128, 32, 32),
'GL5': environment_spritesheet.get_image(0, 160, 32, 32),
'GL6': environment_spritesheet.get_image(0, 192, 32, 32),
'GM0': environment_spritesheet.get_image(32, 32, 32, 32),
'GM1': environment_spritesheet.get_image(64, 32, 32, 32),
'GM2': environment_spritesheet.get_image(96, 32, 32, 32),
'GM3': environment_spritesheet.get_image(128, 32, 32, 32),
'GM4': environment_spritesheet.get_image(160, 32, 32, 32),
'GM5': environment_spritesheet.get_image(192, 32, 32, 32),
'GM6': environment_spritesheet.get_image(224, 32, 32, 32),
'GT0': environment_spritesheet.get_image(32, 0, 32, 32),
'GT1': environment_spritesheet.get_image(64, 0, 32, 32),
'GT2': environment_spritesheet.get_image(96, 0, 32, 32),
'GT3': environment_spritesheet.get_image(128, 0, 32, 32),
'GT4': environment_spritesheet.get_image(160, 0, 32, 32),
'GT5': environment_spritesheet.get_image(192, 0, 32, 32),
'GT6': environment_spritesheet.get_image(224, 0, 32, 32),
'GR0': environment_spritesheet.get_image(256, 0, 32, 32),
'GR1': environment_spritesheet.get_image(256, 32, 32, 32),
'GR2': environment_spritesheet.get_image(256, 64, 32, 32),
'GR3': environment_spritesheet.get_image(256, 96, 32, 32),
'GR4': environment_spritesheet.get_image(256, 128, 32, 32),
'GR5': environment_spritesheet.get_image(256, 160, 32, 32),
'GR6': environment_spritesheet.get_image(256, 192, 32, 32),
'HL0': environment_spritesheet.get_image(96, 240, 32, 32),
'HL1': environment_spritesheet.get_image(96, 272, 32, 32),
'HL2': environment_spritesheet.get_image(96, 304, 32, 32),
'HL3': environment_spritesheet.get_image(96, 336, 32, 32),
'HL4': environment_spritesheet.get_image(96, 368, 32, 32),
'HL5': environment_spritesheet.get_image(96, 400, 32, 32),
'HT0': environment_spritesheet.get_image(0, 336, 32, 32),
'HT1': environment_spritesheet.get_image(32, 336, 32, 32),
'HT2': environment_spritesheet.get_image(64, 336, 32, 32),
'HT3': environment_spritesheet.get_image(128, 240, 32, 32),
'HT4': environment_spritesheet.get_image(160, 240, 32, 32),
'HT5': environment_spritesheet.get_image(224, 240, 32, 32),
'HT6': environment_spritesheet.get_image(288, 336, 32, 32),
'HT7': environment_spritesheet.get_image(320, 336, 32, 32),
'HT8': environment_spritesheet.get_image(352, 336, 32, 32),
'HR0': environment_spritesheet.get_image(256, 240, 32, 32),
'HR1': environment_spritesheet.get_image(256, 272, 32, 32),
'HR2': environment_spritesheet.get_image(256, 304, 32, 32),
'HR3': environment_spritesheet.get_image(256, 336, 32, 32),
'HR4': environment_spritesheet.get_image(352, 368, 32, 32),
'HR5': environment_spritesheet.get_image(352, 400, 32, 32)}
try:
# Initialize all sprites within each sub-level that's within current selected level
for i in range(1, self.level_sub_total - 1): # TODO: Fix this hard code pos
row_current = 0
path_to_level = 'Levels/Level_' + str(self.level_current) \
+ '/Sub_Level_' + str(i) \
+ '.txt'
# Generate the new level across the screen
try:
with open(path_to_level, 'r') as file:
for line in file:
col_current = 0
data_from_file = line.split(' ')
for data in data_from_file:
self.engine_handler.generate_level_walls(self, data, col_current,
True, row_current, i)
col_current += 1
row_current += 1
except FileNotFoundError:
logging.error('* Error - File not found within the current level: %s %s.',
self.level_current, i)
except Exception:
logging.error('* Error - Unexpected.')
# Initialize the character and other character assets for new game
self.character = character.Character(character_name, file_save_name, self, settings.SCREEN_WIDTH / 2,
settings.SCREEN_HEIGHT / 2)
# NOTE: Test npc, will end up using a general platform for npc and assign personalities to them
# NOTE: so they can give specific outcomes based on the given personality
self.npc_squishy = npc.NPCSquishy('npc_squishy', self, settings.SCREEN_WIDTH / 1.5, settings.SCREEN_HEIGHT / 2)
self.buff_handler = character.BuffHandler(self.character, self.screen)
# Initialize UI images for new game
# Inventory system
img_dir = settings.DIR_SPRITES_UI + '/Inventory'
self.img_inv_inv_base = pygame.image.load(img_dir + '/Inventory_Base.png').convert_alpha()
self.img_inv_inv_base_rect = self.img_inv_inv_base.get_rect()
self.img_inv_inv_selected = pygame.image.load(img_dir + '/Inventory_Selected.png').convert_alpha()
self.img_inv_inv_selected_rect = self.img_inv_inv_selected.get_rect()
self.img_inv_saves_selected = pygame.image.load(img_dir + '/Saves_Selected.png').convert_alpha()
self.img_inv_saves_selected_rect = self.img_inv_saves_selected.get_rect()
self.img_inv_opt_selected = pygame.image.load(img_dir + '/Options_Selected.png').convert_alpha()
self.img_inv_opt_selected_rect = self.img_inv_opt_selected.get_rect()
self.img_inv_feed_selected = pygame.image.load(img_dir + '/Feedback_Selected.png').convert_alpha()
self.img_inv_feed_selected_rect = self.img_inv_feed_selected.get_rect()
self.img_inv_exit_selected = pygame.image.load(img_dir + '/Exit_Selected.png').convert_alpha()
self.img_inv_exit_selected_rect = self.img_inv_exit_selected.get_rect()
# Government management
img_dir = settings.DIR_SPRITES_UI + '/Government_Management'
img_dir_menu = img_dir + '/Main_Menu'
img_dir_judge = img_dir + '/Judge'
self.img_gov_menu = pygame.image.load(img_dir + '/Main_Menu/Gov_Base.png').convert_alpha()
self.img_gov_menu_rect = self.img_gov_menu.get_rect()
# Government leader assets
self.img_gov_leader_selected = pygame.image.load(img_dir_menu + '/Gov_Leader_Selected.png').convert_alpha()
self.img_gov_leader_selected_rect = self.img_gov_leader_selected.get_rect()
# Government party assets
self.img_gov_party_selected = pygame.image.load(img_dir_menu + '/Gov_Party_Selected.png').convert_alpha()
self.img_gov_party_selected_rect = self.img_gov_party_selected.get_rect()
# Government judge assets
self.img_gov_judge_selected = pygame.image.load(img_dir_menu + '/Gov_Judge_Selected.png').convert_alpha()
self.img_gov_judge_selected_rect = self.img_gov_judge_selected.get_rect()
# Government info assets
self.img_gov_info_selected = pygame.image.load(img_dir_menu + '/Gov_Information_Selected.png').convert_alpha()
self.img_gov_info_selected_rect = self.img_gov_info_selected.get_rect()
# Government map assets
self.img_gov_map_selected = pygame.image.load(img_dir_menu + '/Gov_Map_Selected.png').convert_alpha()
self.img_gov_map_selected_rect = self.img_gov_map_selected.get_rect()
# Generate assets and start the game
print(self.level_sub_current)
for sprite in self.sprites_walls:
if sprite.level_sub == self.level_sub_current:
sprite.add(self.sprites_active_walls)
# self.level_matrix.lvl = self.engine_handler.generate_level_matrix(self.engine_main)
self.engine_handler.generate_level_matrix(self)
self.running = True
self.game_run()
except Exception:
logging.error('* Error - Unexpected.')
def game_run(self):
"""
The main function to run the game loop.
@return: a game state for the menu to handle or exiting the game
@rtype: str
"""
try:
while self.running:
if self.engine_handler.state == 'Game_Run':
self.game_events()
self.game_update()
self.game_draw()
# TODO: The game might need to be paused while in inventory as it
# CONT: might be too resource intensive or handle other game objects
# CONT: while in the inventory
elif self.engine_handler.state == 'Game_Inventory':
self.game_events()
self.game_update()
self.game_draw()
elif self.engine_handler.state == 'Game_Government_Management':
self.game_events()
self.game_update()
self.game_draw()
except Exception:
logging.error('* Error - Unexpected.')
def game_events(self):
"""
The main function to handle events in the game.
@return: none
@rtype: none
"""
try:
# Handle events for the character, popups, buttons, other sprites,
for event in pygame.event.get():
self.engine_handler.handle_events(self, event, self.character,
self.sprites_important,
self.sprites_walls)
# Handle movements of the character
self.character.handle_keys()
# Check for map rotation
self.engine_handler.check_character_close_to_exit(self, self.character)
# Update map if switching levels or sublevels
if self.engine_handler.screen_switch is True:
# Remove the now old sprites from the group to display
for sprite in self.sprites_active_walls:
sprite.remove(self.sprites_active_walls)
# Figure out which sprites to display
for sprite in self.sprites_walls:
if sprite.level_sub == self.level_sub_current:
sprite.add(self.sprites_active_walls)
self.engine_handler.generate_level_directions()
self.engine_handler.screen_switch = False
except Exception:
logging.error('* Error - Unexpected.')
def game_update(self):
"""
The main function to update any 'side' information.
@return: none
@rtype: none
"""
try:
# Check extra sprite information to update
self.sprites_important.update()
# Check popups for purging
if len(self.popups) > 0:
new_popups = []
for popup in self.popups:
if popup.active is False:
pass
else:
new_popups.append(popup)
self.popups = new_popups
except Exception:
logging.error('* Error - Unexpected.')
def game_draw(self):
"""
The main function to draw all of the information, old or new.
@return: none
@rtype: none
"""
try:
# TODO: Add backgrounds, create an object with a draw function that
# CONT: when the screen is changed to calculate the next screen, OR we
# CONT: could load the level's backgrounds at the beginning so that
# CONT: there isn't any hard computation, just referencing.
# Draw background
# Draw level
self.screen.fill(settings.DARK_GRAY)
# self.game_draw_grid()
# Draw characters, objects, and walls
self.sprites_important.draw(self.screen)
self.sprites_active_walls.draw(self.screen)
# Draw other things in front of the character or on top of
# Draw character effects
self.buff_handler.handle_events()
# TODO: Should the sprites be separated? Is it harder to keep track?
# CONT: Does there need to be a function to change the sprites from
# CONT: groups?
# self.sprites_walls.draw(self.screen)
# Draw UI
self.engine_handler.draw_ui_debug(self, self.screen, self.character)
self.engine_handler.draw_ui_game(self.screen, self.character)
# TODO: Should the game graphics be checked before the game runs and
# CONT: then change an engine variable to display certain graphics
# Draw other visuals based on graphics setting...
# self.engine_handler.check_game_graphics(self.screen, True)
# Draw inventory system
# TODO: FINISH INVENTORY MOCK UP
if self.engine_handler.state == 'Game_Inventory':
# Cycle #
#########
# 1. move all image types to their location
# 2. determine which to display based on user interaction with text
# 3. draw inventory slots, then items
# TODO: Create a list of these to loop through to change their
# CONT: values? Create list where the imgs are initialized maybe?
self.img_inv_inv_base_rect.x = self.character.rect.x + self.character.rect.width / 2 - 245
self.img_inv_inv_base_rect.y = 45
self.img_inv_inv_selected_rect.x = self.character.rect.x + self.character.rect.width / 2 - 245
self.img_inv_inv_selected_rect.y = 45
self.img_inv_saves_selected_rect.x = self.character.rect.x + self.character.rect.width / 2 - 245
self.img_inv_saves_selected_rect.y = 45
self.img_inv_opt_selected_rect.x = self.character.rect.x + self.character.rect.width / 2 - 245
self.img_inv_opt_selected_rect.y = 45
self.img_inv_feed_selected_rect.x = self.character.rect.x + self.character.rect.width / 2 - 245
self.img_inv_feed_selected_rect.y = 45
self.img_inv_exit_selected_rect.x = self.character.rect.x + self.character.rect.width / 2 - 245
self.img_inv_exit_selected_rect.y = 45
# Display inventory background animation based on the state; interaction with inventory
if self.engine_handler.state_inventory == 'Base':
self.screen.blit(self.img_inv_inv_base, self.img_inv_inv_base_rect)
elif self.engine_handler.state_inventory == 'Inventory':
self.screen.blit(self.img_inv_inv_selected, self.img_inv_inv_selected_rect)
elif self.engine_handler.state_inventory == 'Saves':
self.screen.blit(self.img_inv_saves_selected, self.img_inv_saves_selected_rect)
elif self.engine_handler.state_inventory == 'Options':
self.screen.blit(self.img_inv_opt_selected, self.img_inv_opt_selected_rect)
elif self.engine_handler.state_inventory == 'Feedback':
self.screen.blit(self.img_inv_feed_selected, self.img_inv_feed_selected_rect)
elif self.engine_handler.state_inventory == 'Exit':
self.screen.blit(self.img_inv_exit_selected, self.img_inv_exit_selected_rect)
# TODO: Recode somewhere so we aren't constantly creating new text
# TODO: every frame
tab_selected = 'Inventory'
tab_size = 18
tab_y = 93
text_color = settings.BLACK
text_selected = engineLib.GameText('Title', tab_selected, 26, text_color, self.character.rect.x
+ self.character.rect.width / 2 - 59, 48, True, False)
text_inventory = engineLib.GameText('Tab_Inventory', 'Inventory', tab_size, text_color,
self.character.rect.x + self.character.rect.width / 2 - 221,
tab_y, True, False)
text_saves = engineLib.GameText('Tab_Saves', 'Saves', tab_size, text_color, self.character.rect.x
+ self.character.rect.width / 2 - 110, tab_y, True, False)
text_options = engineLib.GameText('Tab_Options', 'Options', tab_size, text_color,
self.character.rect.x + self.character.rect.width / 2 - 25,
tab_y, True, False)
text_feedback = engineLib.GameText('Tab_Feedback', 'Feedback', tab_size, text_color,
self.character.rect.x + self.character.rect.width / 2 + 82,
tab_y, True, False)
text_exit = engineLib.GameText('Tab_Exit', 'Exit', tab_size, text_color, self.character.rect.x
+ self.character.rect.width / 2 + 195, tab_y, True, False)
self.texts_to_display = [text_selected, text_inventory, text_saves, text_options, text_feedback, text_exit]
# Display text
for text in self.texts_to_display:
text.draw(self.screen)
# Draw inventory slots
x_start = self.character.rect.x + self.character.rect.width / 2 - 240
y_start = 140
buffer_x = 10.5
buffer_y = 10.5
for i in range(12): # number of slots for items
x_spacing = (i * 32) + buffer_x
for j in range(5):
y_spacing = (j * 32) + buffer_y
pygame.draw.lines(self.screen, settings.DARK_GRAY, True,
((x_start + x_spacing, y_start + y_spacing),
(x_start + x_spacing, y_start + y_spacing + 32),
(x_start + x_spacing + 32, y_start + y_spacing + 32),
(x_start + x_spacing + 32, y_start + y_spacing)))
buffer_y += 7.5
buffer_y = 10.5
buffer_x += 7.5
buffer_x = 12
buffer_y = 10.5
item_count = 0
# Display inventory items
# TODO: Should there be a loaded dict for the inventory items so it's faster with the imgs ready? yaaa
# TODO: Change the loop to account for x amt of items that would push the next item to the second level in
# CONT: the inventory system.
for item in settings.CHAR_INVENTORY:
img = pygame.image.load(settings.DIR_SPRITES_GAME_INV + '/' + str(item) + '.png').convert_alpha()
img_rect = img.get_rect()
x_spacing = (item_count * 32) + buffer_x
y_spacing = (item_count * 0 * 32) + buffer_y
img_rect.x, img_rect.y = (x_start + x_spacing), (y_start + y_spacing)
self.screen.blit(img, img_rect)
buffer_x += 7.5
item_count += 1
elif self.engine_handler.state == 'Game_Government_Management':
# TODO: init assets based on user interaction
# TODO: display assets based on handled events
# all of the government handling will be in the enginehandler.handle_events() for now but
# should the events be handled in individual files so that there isn't a ton of
# cross referencing?
self.img_gov_menu_rect.x, self.img_gov_menu_rect.y = 3, 3
self.img_gov_leader_selected_rect.x, self.img_gov_leader_selected_rect.y = 3, 3
self.img_gov_party_selected_rect.x, self.img_gov_party_selected_rect.y = 3, 3
self.img_gov_judge_selected_rect.x, self.img_gov_judge_selected_rect.y = 3, 3
self.img_gov_info_selected_rect.x, self.img_gov_info_selected_rect.y = 3, 3
self.img_gov_map_selected_rect.x, self.img_gov_map_selected_rect.y = 3, 3
if self.engine_handler.state_governmnet is 'Default':
self.screen.blit(self.img_gov_menu, self.img_gov_menu_rect)
elif self.engine_handler.state_governmnet is 'Leader':
self.screen.blit(self.img_gov_leader_selected, self.img_gov_leader_selected_rect)
elif self.engine_handler.state_governmnet is 'Party':
self.screen.blit(self.img_gov_party_selected, self.img_gov_party_selected_rect)
elif self.engine_handler.state_governmnet is 'Judge':
self.screen.blit(self.img_gov_judge_selected, self.img_gov_judge_selected_rect)
# Display other judge assets for user interaction and handle the events
# in engine handler
elif self.engine_handler.state_governmnet is 'Information':
self.screen.blit(self.img_gov_info_selected, self.img_gov_info_selected_rect)
elif self.engine_handler.state_governmnet is 'Map':
self.screen.blit(self.img_gov_map_selected, self.img_gov_map_selected_rect)
# Display important popups
for popup in self.popups:
popup.draw(self.screen)
# Scale screen to the size of user's specified resolution
# TODO: This line is causing issues regarding the updating of resolutions and other settings
pygame.transform.scale(self.screen, (settings.WINDOW_WIDTH, settings.WINDOW_HEIGHT), self.window)
# Pygame draws everything that has been sent to it's display which is represented by self.screen
pygame.display.flip()
except Exception:
logging.error('* Error - Unexpected.')
class MainMenu:
"""Class. Used to work with the menu and keep smooth control flow."""
def __init__(self, engine_game: object):
"""
Constructor. Used to initialize the menu system and incorporate the engine for the game so we can run specific
functions including the game itself.
@param engine_game: the engine which controls the network/functions of the game when it starts after the menu
@type engine_game: object
"""
# Initialize the menu with the necessities
pygame.display.set_caption(settings.TITLE_GAME)
self.clock = pygame.time.Clock()
self.clock.tick(30)
self.engine_game = engine_game
self.engine_handler = engineLib.EngineHandler(engine_game) # Atm pretty useless in menu
self.menu_handler = engineLib.MenuHandler(self)
self.running = True
self.sprites_all = pygame.sprite.Group()
self.state = 'Main'
# Initializing screen
self.screen = pygame.Surface((settings.SCREEN_WIDTH, settings.SCREEN_HEIGHT))
self.window = pygame.display.set_mode((self.engine_handler.gather_engine_info(self.engine_game,
'calculate_window')))
# Initialize sample character
self.character_sample = character.Character('Caesar', 'Caesar.py', self.engine_game, 100,
settings.SCREEN_HEIGHT / 2)
self.character_sample.collision_sets = 'Menu'
self.character_sample.engine_menu = self
self.character_name = 'Caesar' # TODO: Is this variable useless?
# Initialize menu images and screen assets
# Feedback
self.feedback_save_description = ''
self.feedback_save_title = ''
self.feedback_save_email = ''
self.img_computer_interact_feedback = object
# Main Menu
self.img_menu_bg = pygame.image.load(settings.DIR_SPRITES_UI
+ '/Menu/Menu_Background_Interactive_Large.png').convert_alpha()
self.img_menu_load_bg = pygame.image.load(settings.DIR_SPRITES_UI + '/Menu/Load/'
+ 'Load_Background_Wood_With_Banners_Large.png').convert_alpha()
self.menu_blit_bg_images = []
self.menu_blit_layer_1_images = []
# Initializing menu animations assets
self.menu_animations = []
# Initializing styling attributes
self.menu_text_bg_color = settings.TRANSPARENT
self.menu_text_color = settings.DEEP_GRAY
# User attributes
self.file_load_save = ''
# Misc attributes
self.buttons = []
self.popups = []
# Initializing dev tools after all other inits
self.engine_dev = devLib.CharacterHandler(self, self.character_sample)
# Menu setup
def menu_start(self):
"""
The setup of all other assets for the menu and game later..
@return: none
@rtype: none
"""
try:
# Run loading animation
self.menu_loading()
# Run menu handler and the menu screens via the handler, returns a state for either starting a
# new game, loading an existing game, or exiting the menu.
return self.menu_screen_handler()
except Exception:
logging.error('* Error - Unexpected.')
# Menu Loading
def menu_loading(self):
"""
This function allows the programmer to load up assets, sprites, and other data/information needed to run
the game smoothly before playing.
@return: none
@rtype: none
"""
try:
# Load specific assets that the menu handler will use later.
self.menu_handler.init_finish()
# Setup and display the loading animation for the game
imgs = []
for i in range(1, 11):
imgs.append(pygame.image.load(settings.DIR_SPRITES_UI + '/Loading/Sprite_Loading_960_1280_Lightning_Effect'
+ str(i) + '.png').convert_alpha())
img_index = 0
img = imgs[img_index]
img_rect = img.get_rect()
loading = True
timer_imgs = 0
timer_imgs_trigger = 7
while loading is True:
timer_imgs += 1
if timer_imgs == timer_imgs_trigger:
img_index += 1
timer_imgs = 0
# Check for end of imgs
if img_index == len(imgs) - 1:
img_index = 0
loading = False
img = imgs[img_index]
self.screen.fill(self.menu_text_color)
self.screen.blit(img, img_rect)
pygame.transform.scale(self.screen, (settings.WINDOW_WIDTH, settings.WINDOW_HEIGHT), self.window)
pygame.display.flip()
except Exception:
logging.error('* Error - Unexpected.')
# Menu Screens
def menu_main(self):
"""
The main menu screen to display all of the options to the user when they load the game.
@return: none
@rtype: none
"""
try:
# Set up background
self.menu_blit_bg_images.append(self.img_menu_bg)
# Set up title
self.menu_animations.append(self.menu_handler.menu_anim_title)
# Set up sample character
self.sprites_all.add(self.character_sample)
# Set up buttons
button_load = engineLib.MenuButton(self, 'Load', 'Load', 35, self.menu_text_color, self.menu_text_bg_color,
settings.SCREEN_WIDTH / 2 - 42, settings.SCREEN_HEIGHT / 2 - 45, True,
False, False, True)
button_exit = engineLib.MenuButton(self, 'Exit', 'Exit', 35, self.menu_text_color, self.menu_text_bg_color,
settings.SCREEN_WIDTH / 2 - 33.5, settings.SCREEN_HEIGHT / 2 + 65, True,
False, False, True)
# Set the specific buttons that should be displayed
self.buttons = [button_load, button_exit]
except Exception:
logging.error('* Error - Unexpected.')
def menu_create_character(self):
"""
The main menu screen to display all of the different settings and attributes of their starting character before
the game is loaded.
@return: none
@rtype: none
"""
try:
self.state = 'Create_Character'
# / 2 - 160 - 100 --> 160 = 10px * num_of_chars_in_question, 100 = 10px * num_of_chars_in_avg_names
button_input_char_name = engineLib.MenuInteractiveText(self, 'Input_Create_Char_Name', 'Character Name: ',
settings.SCREEN_WIDTH / 2 - 150,
settings.SCREEN_HEIGHT / 2 - 30, 300, width=50,
height=25)
button_input_file_name = engineLib.MenuInteractiveText(self, 'Input_File_Save_Name', 'Save File Name: ',
settings.SCREEN_WIDTH / 2 - 150,
settings.SCREEN_HEIGHT / 2, 300, width=50, height=25)
button_submit = engineLib.MenuButton(self, 'Submit', 'Submit', 35, self.menu_text_color,
self.menu_text_bg_color, settings.SCREEN_WIDTH - 195,
settings.SCREEN_HEIGHT - 95, True, False, False, True)
button_back = engineLib.MenuButton(self, 'Back', 'Back', 35, self.menu_text_color, self.menu_text_bg_color, 99,
settings.SCREEN_HEIGHT - 95, True, False, False, True)
# Set the specific buttons that should be displayed
self.buttons = [button_input_char_name, button_input_file_name, button_submit, button_back]
except Exception:
logging.error('* Error - Unexpected.')
def menu_load(self):
"""
A screen picked from the main menu to load an earlier saved game file.
@return: none
@rtype: none
"""
try:
# Set up assets for display
self.menu_blit_bg_images.append(self.img_menu_load_bg)
self.menu_animations.append(self.menu_handler.menu_anim_banners)
# Create navigation bar with 30px between each selection
button_cat_saves = engineLib.MenuButton(self, 'Load_Cat_Saves', 'Saves', 25, self.menu_text_color,
self.menu_text_bg_color, 103, 24, True, True, True, True)
button_submit = engineLib.MenuButton(self, 'Submit', 'Submit', 35, self.menu_text_color,
self.menu_text_bg_color, settings.SCREEN_WIDTH - 195,
settings.SCREEN_HEIGHT - 95, True, True, False, True)
# Misc
button_back = engineLib.MenuButton(self, 'Back', 'Back', 35, self.menu_text_color, self.menu_text_bg_color, 90,
settings.SCREEN_HEIGHT - 95, True, False, False, True)
# Set the specific buttons that should be displayed
self.buttons = [button_cat_saves, button_submit, button_back]
except Exception:
logging.error('* Error - Unexpected.')
def menu_options(self):
"""
A screen picked from the main menu or the pause menu to allow the viewing and changing of many options for how
your game runs.
@return: none
@rtype: none
"""
try:
# Create navigation bar with 30px buffer between each selection
button_cat_controls = engineLib.MenuButton(self, 'Options_Cat_Controls', 'Controls', 25, self.menu_text_color,
self.menu_text_bg_color, 50, 28, True, False, False, True)
button_cat_game = engineLib.MenuButton(self, 'Options_Cat_Game', 'Game', 25, self.menu_text_color,
self.menu_text_bg_color, 190, 28, True, False, False, True)
button_cat_sound = engineLib.MenuButton(self, 'Options_Cat_Sound', 'Sound', 25, self.menu_text_color,
self.menu_text_bg_color, 274, 28, True, False, False, True)
button_cat_video = engineLib.MenuButton(self, 'Options_Cat_Video', 'Video', 25, self.menu_text_color,
self.menu_text_bg_color, 372, 28, True, False, False, True)
# Misc
button_back = engineLib.MenuButton(self, 'Back', 'Back', 35, self.menu_text_color, self.menu_text_bg_color, 90,
settings.SCREEN_HEIGHT - 95, True, False, False, True)
# Set the specific buttons that should be displayed
self.buttons = [button_cat_controls, button_cat_game, button_cat_sound, button_cat_video, button_back]
except Exception:
logging.error('* Error - Unexpected.')
def menu_help(self):
"""
A screen picked from the main menu or the pause menu to allow the viewing of controls, lore help, or other kind
of help the user may need.
@return: none
@rtype: none
"""
try:
# Create navigation bar with 30px buffer between each selection
button_cat_categories = engineLib.MenuButton(self, 'Help_Cat_Cat', 'Categories', 25, self.menu_text_color,
self.menu_text_bg_color, 70, 22, True, False, True, True)
# Misc
button_back = engineLib.MenuButton(self, 'Back', 'Back', 35, self.menu_text_color, self.menu_text_bg_color, 90,
settings.SCREEN_HEIGHT - 95, True, False, False, True)
# Set the specific buttons that should be displayed
self.buttons = [button_cat_categories, button_back]
except Exception:
logging.error('* Error - Unexpected.')
def menu_feedback(self):
"""
A screen picked from the main menu to allow the user to give specific feedback on the game, whether it's the
physics engine that is acting up, the character's traits or skills, or anything that might need to be sent to
myself for error handling.
@return: none
@rtype: none
"""
try:
# TODO: Finish design and send user feedback to remasteredworks.feedback@gmail.com
# Initialize assets for display
self.img_computer_interact_feedback = pygame.image.load(settings.DIR_SPRITES_UI
+ '/Menu/Feedback/Computer_Screen_Large'
+ '.png').convert_alpha()
self.menu_blit_bg_images.append(self.img_menu_bg)
self.menu_blit_layer_1_images.append(self.img_computer_interact_feedback)
button_input_description = engineLib.MenuInteractiveText(self, 'Input_Feedback_Description', 'Bug description:',
110, 120, 378, width=378, height=160)
button_back = engineLib.MenuButton(self, 'Back', 'Back', 35, self.menu_text_color, self.menu_text_bg_color, 99,
settings.SCREEN_HEIGHT - 95, True, False, False, True)
# Set the specific buttons that should be displayed
selfbuttons = [button_input_description, button_back]
except Exception:
logging.error('* Error - Unexpected.')
# Sub Menu Screens
def menu_options_video(self):
"""
A screen picked from the options screen of the main menu or pause menu that allows the viewing of specific
video settings for user to modify regarding the game.
@return: none
@rtype: none
"""
try:
# Create navigation bar with 30px buffer between each selection
button_cat_controls = engineLib.MenuButton(self, 'Options_Cat_Controls', 'Controls', 25, self.menu_text_color,
self.menu_text_bg_color, 50, 28, True, False, False, True)
button_cat_game = engineLib.MenuButton(self, 'Options_Cat_Game', 'Game', 25, self.menu_text_color,
self.menu_text_bg_color, 190, 28, True, False, False, True)
button_cat_sound = engineLib.MenuButton(self, 'Options_Cat_Sound', 'Sound', 25, self.menu_text_color,
self.menu_text_bg_color, 274, 28, True, False, False, True)
button_cat_video = engineLib.MenuButton(self, 'Options_Cat_Video', 'Video', 25, self.menu_text_color,
self.menu_text_bg_color, 372, 28, True, False, False, True)
# Create video options, 10px space between each
graphics_text = 'Graphics: [' + settings.GRAPHICS + ']'
resolution_text = 'Resolution: [' + str(settings.WINDOW_WIDTH) + ', ' + str(settings.WINDOW_HEIGHT) + ']'
button_graphics = engineLib.MenuButton(self, 'Options_Video_Graphics', graphics_text, 20, self.menu_text_color,
self.menu_text_bg_color, 50, 120, True, True, True, False)
button_resolution = engineLib.MenuButton(self, 'Options_Video_Resolution', resolution_text, 20,
self.menu_text_color, self.menu_text_bg_color, 50, 90, True, True,
True, False)
# Misc
button_back = engineLib.MenuButton(self, 'Back', 'Back', 35, self.menu_text_color, self.menu_text_bg_color, 99,
settings.SCREEN_HEIGHT - 95, True, False, False, True)
self.buttons = [button_cat_controls, button_cat_game, button_cat_sound, button_cat_video, button_graphics,
button_resolution, button_back]
except Exception:
logging.error('* Error - Unexpected.')
# Menu System - A system to update the view and catch any events on any of the menu screens and then handle those
# events appropriately whether it's launching the game, pausing the game, changing settings, or
# saving.
def menu_screen_handler(self):
"""
A function to handle switching between screens on the menu without hogging resources via recursion.
@return: returns the state of the game so that the menu object can be tossed for proper resource management and
then the state is used to determine whether to start a new game, load a game, or exit the game
completely.
@rtype: str
"""
try:
handler_running = True # Only set to false when we are done with the menu
while handler_running is True:
old_state = self.state
self.running = True
# TODO: Until we have animations on every screen that resets the animation list, we have to cleanse the list
# CONT: since it isn't rewritten
# Cleanse any animations before new screen
self.menu_animations = []
self.menu_blit_bg_images = []
self.menu_blit_layer_1_images = []
if self.state == 'None':
self.menu_main()
elif self.state == 'Main':
self.menu_main()
elif self.state == 'Create_Character':
self.menu_create_character()
elif self.state == 'Load':
self.menu_load()
elif self.state == 'Options':
self.menu_options()
elif self.state == 'Options_Video':
self.menu_options_video()
elif self.state == 'Help':
self.menu_help()
elif self.state == 'Feedback':
self.menu_feedback()
elif self.state == 'Exit' or self.state == 'Load_New' or self.state == 'Load_Save':
# Log any information before the menu closes
# Close menu
print('[Debug - Info]: MainMenu.menu_screen_handler() is shutting down.')
handler_running = False
# Continue running menu screen
if self.state != 'None' and self.state != 'Exit' and self.state != 'Load_New' and self.state != 'Load_Save':
print('[Debug - Info]: Cleared sprites with top-lvl var-ref '
'\n\t\tengine_main_menu.state = \'' + self.state + '\'.')
self.menu_run()
# Give feedback on the state
if old_state != self.state:
print('[Debug - Info]: Changed state with top-lvl var-ref '
'\n\t\tengine_main_menu.state = \'' + self.state + '\'.')
# Return the state so that the next action can be taken. States include 'Load_New', 'Load_Save', and 'Exit'
return self.state
except Exception:
logging.error('* Error - Unexpected.')
def menu_run(self):
"""
A function that performs all of the tasks necessary for the menu to function properly.
@return: none
@rtype: none
"""
try:
while self.running:
self.menu_events()
self.menu_update()
self.menu_draw()
except Exception:
logging.error('* Error - Unexpected.')
def menu_events(self):
"""
A function to handle all capture and handle all menu events for the menu to function properly.
@return: none
@rtype: none
"""
try:
for event in pygame.event.get():
# Handle buttons, popups, and specific keys pressed
self.menu_handler.handle_events(event)
self.character_sample.handle_keys()
except Exception:
logging.error('* Error - Unexpected.')
def menu_update(self):
"""
A function that updates all of the buttons if needed as well as the screen.
@return: none
@rtype: none
"""
try:
self.screen.fill(settings.WHITE)
# TODO: Only update those.
# Some input buttons require an update based on text input into them
for button in self.buttons:
button.update()
# Update character
self.sprites_all.update()
# Update animations that are applied
for animation in self.menu_animations:
animation.update()
# Check popups for purging
if len(self.popups) > 0:
new_popups = []
for popup in self.popups:
if popup.active is False:
pass
else:
new_popups.append(popup)
self.popups = new_popups
except Exception:
logging.error('* Error - Unexpected.')
def menu_draw(self):
"""
A function to draw all the buttons, visual effects, and scale the game
screen to the specified resolution.
@return: none
@rtype: none
"""
try:
# Display backgrounds
for image in self.menu_blit_bg_images:
self.screen.blit(image, image.get_rect())
# Display the sample character running across the screen
self.sprites_all.draw(self.screen)
# TODO: Debugging
# CONT: for obj_interactable in objs:
# CONT: # Draw box around obj
for obj in self.menu_handler.objs_interact:
pygame.draw.lines(self.screen, settings.RED, True,
((obj.rect.x, obj.rect.y), (obj.rect.x, obj.rect.y + obj.rect.height),
(obj.rect.x + obj.rect.width, obj.rect.y + obj.rect.height),
(obj.rect.x + obj.rect.width, obj.rect.y)))
# TODO: End of Debugging
# Display overlays via options for the user
for image in self.menu_blit_layer_1_images:
rect = image.get_rect()
if str(image) == '<Surface(1266x948x32 SW)>': # Computer overlay
adjustment_computer_height = 15
rect.y = adjustment_computer_height
self.screen.blit(image, rect)
# Display specific visuals for sub menus
self.menu_handler.draw_sub_menu_visuals(self.screen)
# Display animations that are active
for animation in self.menu_animations:
animation.draw(self.screen)
# Display information over visuals
for button in self.buttons:
button.draw(self.screen)
for popup in self.popups:
popup.draw(self.screen)
# Display dev information
# self.engine_dev.push_animation_to_screen()
# Scale screen
pygame.transform.scale(self.screen, (settings.WINDOW_WIDTH, settings.WINDOW_HEIGHT), self.window)
pygame.display.flip()
except Exception:
logging.error('* Error - Unexpected.')
def main():
try:
logging.basicConfig(level="INFO", format='%(asctime)s %(levelname)s %(message)s',
filename='Bin/Logs/logs.txt',
datefmt='%a, %d %b %Y %H:%M:%S')
pygame.init()
pygame.mixer.init()
# Init pregame assets and settings
# TODO: Start implementing sounds
# sound_object = pygame.mixer.Sound('Bin/Sounds/test.ogg')
# sound_object.set_volume(1.0)
# sound_object.play()
# NOTE: Dev debugging - Push game window to second monitor for easier use of debugging
# os.environ['SDL_VIDEO_CENTERED'] = '1' # Center the game screen
os.environ['SDL_VIDEO_WINDOW_POS'] = '%d,%d' % (1920 + 300, 100) # Suggested window location
# NOTE: End Dev debugging
logging.info('* Info - Starting pygame.')
engine_game = Game()
engine_main_menu = MainMenu(engine_game)
# Menu state handler #
# Start the menu for the game and find the user's next course of action which will be given as 'desired_state'.
# NOTE: We handle the state outside so that we can grab any and all information needed.
pygame_running = True
while pygame_running is True:
desired_state = engine_main_menu.menu_start()
# TODO: Create a loading screen and find the best spot to start it as the system hangs a little
# CONT: Issue tracker on github
if desired_state == 'Load_New':
# Start new game
logging.info('* Info - New game is being loaded.')
engine_game.sprites_important.remove(engine_main_menu.character_sample)
engine_game.game_new(engine_main_menu.file_load_save, character_name=engine_main_menu.character_name)
engine_main_menu.state = 'Main'
logging.info('* Info - New game is being closed.')
elif desired_state == 'Load_Save':
# Load a saved game
logging.info('* Info - Saved game is being loaded.')
# Remove any unnecessary assets that a new game didn't have
engine_game.sprites_important.remove(engine_main_menu.character_sample)
engine_game.game_new(engine_main_menu.file_load_save)
# After game was exited see if the engine wants to quit to main menu or not
if engine_game.state == 'Exit_To_Desktop':
pygame_running = False
elif engine_game.state == 'Exit_To_Menu':
engine_main_menu.state = 'Main'
engine_game.sprites_important.empty()
engine_game.sprites_walls.empty()
else:
logging.error('* Error - Unexpected engine state: %s', engine_game.state)
exit()
logging.info('* Info - Saved game is being closed.')
elif desired_state == 'Exit':
logging.info('* Info - Exiting menu.')
pygame_running = False
else:
logging.error('* Error - engine_main_menu.menu_start() returned an invalid state.')
logging.info('* End of main.')
pygame.quit()
return 0
except Exception:
logging.error('* Error - Unexpected.')
if __name__ == '__main__':
main()
logging.info('* Info - Exiting ' + settings.TITLE_GAME + '.')
|
Java
|
UTF-8
| 14,321
| 2.03125
| 2
|
[] |
no_license
|
package ua.edu.ratos.service.session;
import lombok.AllArgsConstructor;
import lombok.NonNull;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Slice;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import ua.edu.ratos.config.properties.AppProperties;
import ua.edu.ratos.dao.entity.Result;
import ua.edu.ratos.dao.entity.Student;
import ua.edu.ratos.dao.entity.game.Bonus;
import ua.edu.ratos.dao.entity.game.Game;
import ua.edu.ratos.dao.entity.game.Week;
import ua.edu.ratos.dao.entity.game.Wins;
import ua.edu.ratos.dao.repository.ResultRepository;
import ua.edu.ratos.dao.repository.game.*;
import ua.edu.ratos.security.SecurityUtils;
import ua.edu.ratos.service.domain.SessionData;
import ua.edu.ratos.service.dto.out.game.AllTimesGamerOutDto;
import ua.edu.ratos.service.dto.out.game.GamerOutDto;
import ua.edu.ratos.service.dto.out.game.WeeklyGamerOutDto;
import ua.edu.ratos.service.dto.out.game.WinnerOutDto;
import ua.edu.ratos.service.transformer.mapper.GamerMapper;
import ua.edu.ratos.service.transformer.mapper.TotalTopMapper;
import ua.edu.ratos.service.transformer.mapper.WeeklyGamerMapper;
import ua.edu.ratos.service.transformer.mapper.WinnerMapper;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;
@Slf4j
@Service
@AllArgsConstructor
public class GameService {
@PersistenceContext
private final EntityManager em;
private final AppProperties appProperties;
private final ResultRepository resultRepository;
private final GameRepository gameRepository;
private final WeekRepository weekRepository;
private final BonusRepository bonusRepository;
private final WinsRepository winsRepository;
private final GamerRepository gamerRepository;
private final GamerMapper gamerMapper;
private final WinnerMapper winnerMapper;
private final WeeklyGamerMapper weeklyGamerMapper;
private final TotalTopMapper totalTopMapper;
private final SecurityUtils securityUtils;
/**
* Allows to quickly decide if a user has gained any gamification points for this session.
* It involves minimum or no DB operations. This information needs to be included into result DTO,
* without waiting for long asynchronous DB operations completion.
* @param sessionData
* @param percent
* @return gamification points if any
*/
@Transactional
public Optional<Integer> getPoints(@NonNull final SessionData sessionData, double percent) {
Long userId = sessionData.getUserId();
Long schemeId = sessionData.getSchemeDomain().getSchemeId();
if (!isGameOn()) return Optional.empty();
if (sessionData.isGameableSession() && isEnoughPercents(percent) && isFromFirstAttempt(userId, schemeId)) {
return Optional.of(getPoints(percent));
}
return Optional.ofNullable(0);
}
/**
* If game mode is turned off - the method throws RuntimeException.
* If for gameable session you score less percents then low threshold - you lose strike.
* if for gameable session you score enough percents and did it from the first attempt
* you are granted a corresponding amount of scores depending on gaming settings.
* Only Week table is updated if you failed to score any points, timeSpent field.
* Both Week and Game tables are updated in case you are granted any points.
* A new entry is added to Bonus table if you are gained strike and granted a bonus.
* @param sessionData session data
* @param percent the scored percent
* @param timeSpent time spend for this learning session
*/
@Transactional
public void doGameProcessing(@NonNull final SessionData sessionData, double percent, long timeSpent) {
if (!isGameOn()) throw new RuntimeException("Failed to process gamification points, gaming mode is off");
Long userId = sessionData.getUserId();
// Lose strike for any gameable session if failed to score enough percents
if (sessionData.isGameableSession() && !isEnoughPercents(percent)) {
resetWeeklyStrike(userId);
createOrUpdateWeeklyTimeSpent(userId, timeSpent);
return;
}
Long schemeId = sessionData.getSchemeDomain().getSchemeId();
// from first attempt
if (sessionData.isGameableSession() && isEnoughPercents(percent) && isFromFirstAttempt(userId, schemeId)) {
Integer points = getPoints(percent);
Optional<Week> week = weekRepository.findById(userId);
if (!week.isPresent()) {
Week w = new Week();
w.setWeekPoints(points);
w.setWeekStrike(1);
w.setWeekTimeSpent(timeSpent);
w.setStud(em.getReference(Student.class, userId));
weekRepository.save(w);
createOrUpdateGamePoints(userId, points);
} else {
// update week
Week w = week.get();
int weekPoints = w.getWeekPoints();
int weekStrike = w.getWeekStrike();
int weekBonuses = w.getWeekBonuses();
long weekTimeSpent = w.getWeekTimeSpent();
// check for weekly strike
AppProperties.Game props = appProperties.getGame();
if (weekStrike >= props.getBonusStrike()-1) {
int bonus = props.getBonusSize();
// update/create game bonus, add bonus entry
createOrUpdateGameBonuses(userId, bonus);
saveBonus(userId, bonus);
// reset counter
w.setWeekBonuses(weekBonuses + bonus);
w.setWeekStrike(0);
} else {
w.setWeekStrike(++weekStrike);
}
w.setWeekPoints(weekPoints+points);
w.setWeekTimeSpent(weekTimeSpent+timeSpent);
createOrUpdateGamePoints(userId, points);
}
}
}
public boolean isGameOn() {
AppProperties.Game props = appProperties.getGame();
if (props.isGameOn()) return true;
log.debug("Gamification mode is turned off");
return false;
}
private boolean isEnoughPercents(double percent) {
AppProperties.Game props = appProperties.getGame();
if (percent >= props.getLowBoundaryFrom()) return true;
log.debug("Not enough percents = {}", percent);
return false;
}
private boolean isFromFirstAttempt(@NonNull final Long userId, @NonNull final Long schemeId) {
// if user has already taken this scheme previously - no points can be granted!
Slice<Result> results = resultRepository.findFirstByUserIdAndSchemeId(userId, schemeId, PageRequest.of(0, 1));
if (!results.hasContent()) return true;
log.debug("Not from the first attempt, userId = {}, schemeId = {}", userId, schemeId);
return false;
}
public int getPoints(double percent) {
AppProperties.Game props = appProperties.getGame();
if (percent >= props.getLowBoundaryFrom() && percent < props.getLowBoundaryTo())
return props.getLowBoundaryPoints();
if (percent >= props.getMiddleBoundaryFrom() && percent < props.getMiddleBoundaryTo())
return props.getMiddleBoundaryPoints();
if (percent >= props.getHighBoundaryFrom() && percent <= props.getHighBoundaryTo())
return props.getHighBoundaryPoints();
log.error("Bad percent, cannot decide gamification points for percent = {}. Fallback to 0 points", percent);
return 0;
}
private void resetWeeklyStrike(@NonNull final Long userId) {
Optional<Week> week = weekRepository.findById(userId);
if (week.isPresent()) {
Week w = week.get();
w.setWeekStrike(0);
}
}
private void createOrUpdateWeeklyTimeSpent(@NonNull final Long userId, long timeSpent) {
Optional<Week> week = weekRepository.findById(userId);
if (!week.isPresent()) {
Week w = new Week();
w.setWeekTimeSpent(timeSpent);
w.setStud(em.getReference(Student.class, userId));
weekRepository.save(w);
} else {
Week w = week.get();
long weekTimeSpent = w.getWeekTimeSpent();
w.setWeekTimeSpent(weekTimeSpent + timeSpent);
}
}
private void createOrUpdateGamePoints(@NonNull final Long userId, @NonNull final Integer points) {
Optional<Game> game = gameRepository.findById(userId);
if (!game.isPresent()) {
Game g = new Game();
g.setTotalPoints(points);
g.setStud(em.getReference(Student.class, userId));
gameRepository.save(g);
} else { // just update value
Game g = game.get();
int totalPoints = g.getTotalPoints();
g.setTotalPoints(totalPoints+points);
}
}
private void createOrUpdateGameBonuses(@NonNull final Long userId, @NonNull final Integer bonus) {
Optional<Game> game = gameRepository.findById(userId);
if (!game.isPresent()) {
Game g = new Game();
g.setTotalBonuses(bonus);
g.setStud(em.getReference(Student.class, userId));
gameRepository.save(g);
} else { // just update value
Game g = game.get();
int totalBonuses = g.getTotalBonuses();
g.setTotalBonuses(totalBonuses+bonus);
}
}
private void saveBonus(@NonNull final Long userId, @NonNull final Integer bonus) {
Bonus b = new Bonus();
b.setBonus(bonus);
b.setStudent(em.getReference(Student.class, userId));
b.setWhenGranted(LocalDateTime.now());
bonusRepository.save(b);
}
//-----------------------------------------------Quartz regular weekly job------------------------------------------
/**
* Launched automatically by quartz scheduler, mainly at the end of a week.
* Winners of the week for an organisation are considered those n% of students who participated in the competition and:
* gained the most points, then gained the most bonuses, and then spent the least time.
*/
@Transactional
public void calculateAndSaveWeeklyWinners() {
AppProperties.Game props = appProperties.getGame();
int topWeeklyPercentage = props.getTopWeekly();
// Get all entries from week table;
List<Week> all = weekRepository.findAll();
if (all.isEmpty()) {
log.debug("No gamers found! Hence, no winners of the week!");
return;
}
// For each organisation calculate top-n% of students and obtain a list of winners
Map<Long, List<Week>> allWeeklyByOrg = all.stream()
.collect(Collectors.groupingBy(w -> w.getStud().getOrganisation().getOrgId()));
for (List<Week> orgList : allWeeklyByOrg.values()) {
if (orgList.isEmpty()) break;
orgList.sort(Comparator.comparing(Week::getWeekPoints, Comparator.reverseOrder())
.thenComparing(Week::getWeekBonuses, Comparator.reverseOrder())
.thenComparing(Week::getWeekTimeSpent, Comparator.naturalOrder()));
int size = orgList.size();
// get n% of the sorted list
int topNSize = size * topWeeklyPercentage / 100;
List<Week> winners = orgList.subList(0, topNSize);
// borderline case, if percentage of winners is too small,
// the first person in the sorted list is the winner
if (winners.isEmpty()) winners = Arrays.asList(orgList.get(0));
// create Wins, and update totalWins in Game
saveWeeklyWinners(winners);
}
// reset week table
weekRepository.emptyWeek();
}
private void saveWeeklyWinners(@NonNull final List<Week> winners) {
for (Week winner : winners) {
Wins wins = new Wins();
wins.setStudent(em.getReference(Student.class, winner.getWeekId()));
wins.setWonPoints(winner.getWeekPoints());
wins.setWonBonuses(winner.getWeekBonuses());
wins.setWonTimeSpent(winner.getWeekTimeSpent());
wins.setWonDate(LocalDate.now());
winsRepository.save(wins);
// winners for sure have entries in Game table!
gameRepository.incrementWins(winner.getWeekId());
}
}
//--------------------------------------------------SELECT----------------------------------------------------------
@Transactional(readOnly = true)
public GamerOutDto findMyGamingRating() {
Long studId = securityUtils.getAuthUserId();
return gamerMapper.toDto(gamerRepository.findById(studId).get());
}
//-------------------------------------------For TOP weekly rating table--------------------------------------------
@Transactional(readOnly = true)
public Page<WeeklyGamerOutDto> findWeeklyGamers(@NonNull final Pageable pageable) {
return weekRepository.findWeeklyGamers(pageable).map(weeklyGamerMapper::toDto);
}
//------------------------------------------For TOP rating students table-------------------------------------------
@Transactional(readOnly = true)
public Page<AllTimesGamerOutDto> findBestGamers(@NonNull final Pageable pageable) {
return gameRepository.findBestGamers(pageable).map(totalTopMapper::toDto);
}
//-------------------------------------------For last week winners table--------------------------------------------
// sorted by points, bonuses and time spent
@Transactional(readOnly = true)
public Page<WinnerOutDto> findLastWeekWinners(@NonNull final Pageable pageable) {
return winsRepository.findAllWinnersSince(LocalDate.now().minusDays(7), pageable).map(winnerMapper::toDto);
}
}
|
PHP
|
UTF-8
| 804
| 2.640625
| 3
|
[] |
no_license
|
<?php
function __autoload($controller)
{
$ssModelName = ucfirst($controller);
require_once('model/' . $ssModelName . '.php');
}
function call($controller, $action)
{
require_once('controllers/' . $controller . '_controller.php');
switch ($controller)
{
case 'student':
$controller = new StudentController();
break;
}
$controller->{ $action }();
}
// we're adding an entry for the new controller and its actions
$controllers = array('student' => ['manage','error','delete','edit','add']);
if (array_key_exists($controller, $controllers))
{
if (in_array($action, $controllers[$controller]))
{
call($controller, $action);
}
else
{
call('student', 'error');
}
}
else
{
call('student', 'error');
}
?>
|
Java
|
UTF-8
| 2,110
| 2.546875
| 3
|
[
"Apache-2.0"
] |
permissive
|
package org.apache.lucene.analysis.standard;
/**
* Copyright 2004 The Apache Software Foundation
*
* 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.
*/
import org.apache.lucene.analysis.*;
/** Normalizes tokens extracted with {@link StandardTokenizer}. */
public final class StandardFilter extends TokenFilter
implements StandardTokenizerConstants {
/** Construct filtering <i>in</i>. */
public StandardFilter(TokenStream in) {
super(in);
}
private static final String APOSTROPHE_TYPE = tokenImage[APOSTROPHE];
private static final String ACRONYM_TYPE = tokenImage[ACRONYM];
/** Returns the next token in the stream, or null at EOS.
* <p>Removes <tt>'s</tt> from the end of words.
* <p>Removes dots from acronyms.
*/
public final org.apache.lucene.analysis.Token next() throws java.io.IOException {
org.apache.lucene.analysis.Token t = input.next();
if (t == null)
return null;
String text = t.termText();
String type = t.type();
if (type == APOSTROPHE_TYPE && // remove 's
(text.endsWith("'s") || text.endsWith("'S"))) {
return new org.apache.lucene.analysis.Token
(text.substring(0,text.length()-2),
t.startOffset(), t.endOffset(), type);
} else if (type == ACRONYM_TYPE) { // remove dots
StringBuffer trimmed = new StringBuffer();
for (int i = 0; i < text.length(); i++) {
char c = text.charAt(i);
if (c != '.')
trimmed.append(c);
}
return new org.apache.lucene.analysis.Token
(trimmed.toString(), t.startOffset(), t.endOffset(), type);
} else {
return t;
}
}
}
|
Python
|
UTF-8
| 2,202
| 2.625
| 3
|
[] |
no_license
|
import uuid
from api.host import find_existing_host
from app import db
from app.models import Host
from test_utils import flask_app_fixture
ACCOUNT_NUMBER = "000102"
def create_host(canonical_facts):
host = Host(canonical_facts, display_name=None, account=ACCOUNT_NUMBER)
db.session.add(host)
db.session.commit()
return host
# FIXME: DRY
def generate_uuid():
return str(uuid.uuid4())
def basic_host_dedup_test(initial_canonical_facts, search_canonical_facts):
original_host = create_host(initial_canonical_facts)
found_host = find_existing_host(ACCOUNT_NUMBER, search_canonical_facts)
assert original_host.id == found_host.id
def test_find_host_using_subset_canonical_fact_match(flask_app_fixture):
fqdn = "fred.flintstone.com"
canonical_facts = {"fqdn": fqdn,
"bios_uuid": generate_uuid(),
"rhel_machine_id": generate_uuid(),
}
# Create the subset of canonical facts to search by
subset_canonical_facts = {"fqdn": fqdn}
basic_host_dedup_test(canonical_facts, subset_canonical_facts)
def test_find_host_using_superset_canonical_fact_match(flask_app_fixture):
canonical_facts = {"fqdn": "fred",
"bios_uuid": generate_uuid()}
# Create the superset of canonical facts to search by
superset_canonical_facts = canonical_facts.copy()
superset_canonical_facts["rhel_machine_id"] = generate_uuid()
superset_canonical_facts["satellite_id"] = generate_uuid()
basic_host_dedup_test(canonical_facts, superset_canonical_facts)
def test_find_host_using_insights_id_match(flask_app_fixture):
canonical_facts = {"fqdn": "fred",
"bios_uuid": generate_uuid(),
"insights_id": generate_uuid(),
}
# Change the canonical facts except the insights_id...match on insights_id
search_canonical_facts = {"fqdn": "barney",
"bios_uuid": generate_uuid(),
"insights_id": canonical_facts["insights_id"],
}
basic_host_dedup_test(canonical_facts, search_canonical_facts)
|
TypeScript
|
UTF-8
| 2,162
| 2.921875
| 3
|
[
"ISC"
] |
permissive
|
import {QueryList} from '@angular/core';
import {NgModel, FormControlName, FormControl} from '@angular/forms';
import { uniqBy } from 'lodash';
/**
* The FormControlFinder tries to find a formControl in the given ngModelChildren.
* The input element of a control must both contain an ngModel and a formControlName directive.
* If more than 1 control is found, the attached formControlName must be the same (so the same validation rules are applicable).
*/
export class FormControlFinder {
/**
* Try to find the formControl in the given collection. If found, return it.
* If more than 1 control is found, check if the all contain the same NgControlName. If not, throw an exception.
* @param {ngModelChildren} QueryList<NgModel> the ngModel ContentChildren to inspect.
* @returns {FormControl} Returns the found control or undefined (if not found)
*/
static findFormControl(ngModelChildren: QueryList<NgModel>): FormControl {
// filter ngControlName directives (select only controls with ngControl properties, skip the ones with only ngModel)
let controls = ngModelChildren.filter((ngModel) => { return (ngModel instanceof FormControlName); });
if (controls && controls.length > 0) {
// all ngModelChildren must contain the same control (otherwise, validation will only occure to the first one)
if (controls.length > 1) {
FormControlFinder.checkArrayContainsSameNameValues(controls);
}
return controls[0].control;
}
}
/**
* checks if all items in the given array are the same
* @param {any[]} array
* @returns {boolean} true if all items in array are the same, throws error if not
*/
private static checkArrayContainsSameNameValues(array: any[]): boolean {
let uniq = uniqBy(array, 'name');
if (uniq.length > 1) {
console.log('More than one ngModel found in transclude childs. first=', uniq[0], ' second=', uniq[1]);
throw `More than one ngModel found in transclude childs (first=${uniq[0]}, other=${uniq[1]}`;
}
return true;
}
}
|
Python
|
UTF-8
| 1,573
| 2.875
| 3
|
[
"MIT"
] |
permissive
|
# This script is meant to be called from the Makefile.
#
# This script will generate a single csv to intended to be used as a final
# dataset. An example invocation of the script is
# `python make_dataset.py Python, Ruby, C
#
# The resulting result csv file will have header `['language', 'code']`, where
# - `language` is either Python, Ruby, or C,
# - `code` is a code snippet
import csv
import os
import sys
from pathlib import Path
# path of current file
file_path = Path(os.path.realpath(__file__))
# path of data directory
data_path = file_path.parent.parent.parent / "data"
# path of input (language directory of RosettaCodeData)
lang_path = data_path / "external" / "RosettaCodeData" / "Lang"
# path of output folder and output file
output_folder = data_path / "processed"
output_file = output_folder / "data.csv"
# languages used
langs = sys.argv[1:]
# header names
fieldnames = ["language", "code"]
# make the directory if needed
if not output_folder.is_dir():
os.mkdir(output_folder)
with open(output_file, "w") as csv_file:
writer = csv.DictWriter(csv_file, fieldnames=fieldnames)
writer.writeheader()
for lang in langs:
lang_folder = lang_path / lang
task_folders = (x for x in lang_folder.iterdir() if x.is_dir())
for task_folder in task_folders:
task = task_folder.name
for file in task_folder.iterdir():
with open(file, "r") as f:
code = f.read()
if code:
writer.writerow({"language": lang, "code": code})
|
JavaScript
|
UTF-8
| 2,300
| 2.65625
| 3
|
[] |
no_license
|
function Documents() {
var storage_key = 'documents';
var documents = {};
this.create = function (name) {
documents[name] = {
name: name
};
};
this.delete = function (name) {
delete documents[name];
};
this.get = function (name) {
return documents[name];
};
this.has = function (name) {
return name in documents;
};
this.list = function () {
var keys = [];
for (var i in documents) {
keys.push(i);
}
return keys;
};
this.save = function () {
localStorage.setItem(storage_key, angular.toJson(documents));
};
this.load = function () {
documents = angular.fromJson(localStorage.getItem(storage_key) || '{}');
};
this.reset = function () {
documents = {};
this.save();
};
}
;function DocumentsCtrl(documents) {
documents.load();
this.name = '';
this.list = function () {
return documents.list();
};
this.create = function () {
documents.create(this.name, {});
documents.save();
this.name = '';
};
this.delete = function (name) {
documents.delete(name);
documents.save();
};
this.reset = function () {
documents.reset();
};
}
;function UseCaseCtrl(documents, document_name) {
this.name = document_name;
}
;function UseCaseDocument() {
var actors = ['a', 'b', 'c'];
var cases = ['1', '2'];
this.actors = function () {
return actors;
};
this.cases = function () {
return cases;
};
this.addActor = function (name) {
};
this.addCase = function (name) {
};
}
;function config($routeProvider) {
$routeProvider.when('/doc/:name', {
controller: UseCaseCtrl,
controllerAs: 'document',
template: '{{ document.name }}',
resolve: {
document_name: function ($route) {
return $route.current.params.name;
}
}
});
}
;(function () {
var app = angular.module('UseCaseApp', ['ngRoute']);
app.config(config);
app.controller('UseCaseCtrl', UseCaseCtrl);
app.service('usecase', UseCaseDocument);
app.service('documents', Documents);
})();
|
Java
|
UTF-8
| 1,514
| 3.046875
| 3
|
[] |
no_license
|
package scenes.attractors;
import math.Vector2D;
public class Satellite {
private float width;
private float height;
Vector2D location;
float speed;
float theta;
float mass;
int age;
Satellite(float x, float y, float width, float height) {
this.width = width;
this.height = height;
this.location = new Vector2D(x, y);
speed = (1);
theta = (1);
mass = 100;
}
Vector2D getLocation() {
return this.location;
}
public void update() {
float x = location.getX();
float y = location.getY();
if (x >= width || x < 0) {
float velX = (float) (-1 * speed * Math.cos(theta));
float velY = (float) (speed * Math.sin(theta));
theta = (float) Math.atan2(velY, velX);
}
x += speed * Math.cos(theta);
if (y >= height || y < 0) {
float velX = (float) (speed * Math.cos(theta));
float velY = (float) (-1 * speed * Math.sin(theta));
theta = (float) Math.atan2(velY, velX);
}
y += speed * Math.sin(theta);
this.location = new Vector2D(x, y);
}
public void applyForce(Vector2D f) {
float velX = (float) (speed * Math.cos(theta));
float velY = (float) (speed * Math.sin(theta));
float accX = (float) (f.getLength() * Math.cos(f.getHeading()));
float accY = (float) (f.getLength() * Math.sin(f.getHeading()));
velX += accX/mass;
velY += accY/mass;
speed = (float) Math.sqrt(velX*velX + velY*velY);
theta = (float) Math.atan2(velY, velX);
}
}
|
Java
|
UTF-8
| 860
| 2.125
| 2
|
[] |
no_license
|
package com.asiainfo.charge.service.impl;
import com.ai.appframe2.service.ServiceFactory;
import com.asiainfo.charge.dao.interfaces.IDynamicSumDAO;
import com.asiainfo.charge.ivalues.IBODynamicSumValue;
import com.asiainfo.charge.service.interfaces.IDynamicSumSV;
public class DynamicSumSVImpl implements IDynamicSumSV {
@Override
public IBODynamicSumValue getDynamicSumById(String id) throws Exception,
RuntimeException {
IDynamicSumDAO dynamicSumDAO=(IDynamicSumDAO) ServiceFactory
.getService(IDynamicSumDAO.class);
return dynamicSumDAO.getDynamicSumById(id);
}
@Override
public String saveDynamicSum(IBODynamicSumValue dynamicSumValue)
throws Exception, RuntimeException {
IDynamicSumDAO dynamicSumDAO=(IDynamicSumDAO) ServiceFactory
.getService(IDynamicSumDAO.class);
return dynamicSumDAO.saveDynamicSum(dynamicSumValue);
}
}
|
C++
|
UTF-8
| 8,171
| 3.03125
| 3
|
[] |
no_license
|
#include "stdafx.h"
#include "Player.h"
#include <string>
Player::Player(string name) {
this->name = name;
victoryCoins = 5;
race = NULL;
declinedRace = NULL;
badge = NULL;
declinedBadge = NULL;
}
Player::~Player() {
delete race;
delete declinedRace;
delete badge;
delete declinedBadge;
delete strategy;
}
string Player::getName() {
return name;
}
FantasyRaceBanner* Player::getRace() {
return race;
}
Badge* Player::getBadge() {
return badge;
}
int Player::getVictoryCoins() {
return victoryCoins;
}
int Player::getBonusCoins() {
return bonusVictoryCoins;
}
int Player::getTokens() {
return raceTokens;
}
void Player::setVictoryCoins(int coins) {
victoryCoins = coins;
}
void Player::setBonusCoins(int coins) {
bonusVictoryCoins = coins;
}
void Player::setTokens(int tokens) {
if (tokens >= 0)
raceTokens = tokens;
}
void Player::setStrategy(Strategy *strategy) {
this->strategy = strategy;
}
int Player::select_action(int currentTurn) {
return strategy->select_action(currentTurn);
}
void Player::declines_race(Map* m, Deck* deck) {
// Returns old declined race and badge to the bottom of the deck
if (declinedRace != NULL) {
deck->addRace(declinedRace);
deck->addBadge(declinedBadge);
}
// Declines race and badge
declinedRace = race;
declinedBadge = badge;
// Player has no race or badge for the rest of the turn
race = NULL;
badge = NULL;
// Puts all tokens on the map in decline
m->decline(this);
}
void Player::picks_race(FantasyRaceBanner* race, Badge* badge) {
// Sets a new race and badge
this->race = race;
this->badge = badge;
raceTokens = race->getRaceTokens() + badge->getRaceTokens();
// Wealthy earns a bonus 7 coins for their first turn
if (badge->getName().compare("Wealthy") == 0)
setBonusCoins(bonusVictoryCoins + 7);
}
int Player::abandons(Map* map, vector<size_t>* regions) {
return strategy->abandons(map, regions);
}
int Player::expands(Map* map, vector<size_t>* regions) {
return strategy->expands(map, regions);
}
bool Player::conquers(Map* m, size_t region, Dice* dice) {
int neededTokens = m->regions.at(region).tokens + 2;
// Defenses increase the number of needed tokens
if (m->regions.at(region).type == m->regions.at(region).MOUNTAIN)
neededTokens++;
if (m->regions.at(region).encampment)
neededTokens++;
if (m->regions.at(region).fortress)
neededTokens++;
if (m->regions.at(region).lair)
neededTokens++;
// Commando requires 1 less token to conquer
if (getBadge()->getName().compare("Commando") == 0)
if (neededTokens > 1)
neededTokens--;
// Mounted requires 1 less token to conquer hills and farmlands
if (getBadge() != NULL && getBadge()->getName().compare("Mounted") == 0)
if (m->regions.at(region).type == m->regions.at(region).HILL ||
m->regions.at(region).type == m->regions.at(region).FARMLAND)
neededTokens--;
// Underworld requires 1 less token to conquer caverns
if (getBadge() != NULL && getBadge()->getName().compare("Underworld") == 0)
if (m->regions.at(region).cavern)
neededTokens--;
// Giants requires 1 less token to conquer mountains
if (getRace() != NULL && getRace()->getName().compare("Giants") == 0)
if (m->regions.at(region).type == m->regions.at(region).MOUNTAIN)
neededTokens--;
if (neededTokens < 1)
neededTokens = 1;
int roll = 0;
bool rolled = false;
// Berserk can roll the die before a conquest
if (getBadge()->getName().compare("Berserk") == 0)
roll = dice->roll();
else if(raceTokens < neededTokens) {
if (m->regions.at(region).tokens == 0)
return false;
roll = dice->roll();
rolled = true;
}
int totalTokens = raceTokens + roll;
if (totalTokens >= neededTokens) {
// Return all but 1 token to old conquerer EXCEPT if the old conquerer is an elf, in which case, return all their tokens
if (m->regions.at(region).owner) {
// Orcs and Pillaging earn 1 bonus coin for every non-empty region conquered that turn
if (getRace()->getName().compare("Orcs") == 0)
setBonusCoins(bonusVictoryCoins + 1);
if (getBadge()->getName().compare("Pillaging") == 0)
setBonusCoins(bonusVictoryCoins + 1);
// Elves get back all of their tokens when their region has been conquered by an enemy
if (m->regions.at(region).owner->getRace() != NULL && m->regions.at(region).owner->getRace()->getName().compare("Elves") == 0)
m->regions.at(region).owner->setTokens(m->regions.at(region).owner->raceTokens + m->regions.at(region).tokens);
// Previous owner gets back all but one token from their captured region
else
m->regions.at(region).owner->setTokens(m->regions.at(region).owner->raceTokens + m->regions.at(region).tokens - 1);
}
m->regions.at(region).owner = this;
m->regions.at(region).decline = false;
if (!rolled) {
// Berserk may require less tokens for conquer depending on die roll outcome
if (m->regions.at(region).owner->getBadge() != NULL && getBadge()->getName().compare("Berserk") == 0) {
neededTokens -= roll;
if (neededTokens < 1)
neededTokens = 1;
}
m->regions.at(region).tokens = neededTokens;
raceTokens -= neededTokens;
}
else {
m->regions.at(region).tokens = raceTokens;
setTokens(0);
}
// Trolls place a lair on each occupied region
if (race->getName().compare("Trolls") == 0) {
if (!m->regions.at(region).lair && race->getDefense() > 0) {
m->regions.at(region).lair = true;
race->setDefense(race->getDefense() - 1);
}
}
// Halflings place a hole-in-the-ground on their first 2 occupied regions
if (race->getName().compare("Halflings") == 0) {
if (!m->regions.at(region).hole && race->getDefense() > 0) {
m->regions.at(region).hole = true;
race->setDefense(race->getDefense() - 1);
}
}
return true;
}
else {
return false;
}
}
std::tuple<int, int> Player::redeploys(Map* map, vector<size_t>* regions) {
return strategy->redeploys(map, regions);
}
int Player::scores(Map * m) {
int points = 0;
for(const auto region : m->regions) {
// Player earns one victory coin for each region they own
if (region.owner == this) {
points += 1;
// Merchant gains extra coin for each region occupied
if (getBadge() != NULL && getBadge()->getName().compare("Merchant") == 0)
setBonusCoins(bonusVictoryCoins + 1);
// Hill earns an extra victory coin for each hill occupied
if (getBadge() != NULL && getBadge()->getName().compare("Hill") == 0)
if (region.type == region.HILL)
setBonusCoins(bonusVictoryCoins + 1);
// Humans earn an extra victory coin for each farmland occupied
if (getRace() != NULL && getRace()->getName().compare("Humans") == 0)
if (region.type == region.FARMLAND)
setBonusCoins(bonusVictoryCoins + 1);
// Forest earns an extra victory coin for each forest occupied
if (getBadge() != NULL && getBadge()->getName().compare("Forest") == 0)
if (region.type == region.FOREST)
setBonusCoins(bonusVictoryCoins + 1);
// Swamp earns an extra victory coin for each swamp occupied
if (getBadge() != NULL && getBadge()->getName().compare("Swamp") == 0)
if (region.type == region.SWAMP)
setBonusCoins(bonusVictoryCoins + 1);
// Fortified earn an extra victory coin for each region occupied containing a fortress
if (getBadge() != NULL && getBadge()->getName().compare("Fortified") == 0)
if (region.fortress)
setBonusCoins(bonusVictoryCoins + 1);
// Wizards earn an extra victory coin for each magic region occupied
if (getRace() != NULL && getRace()->getName().compare("Wizards") == 0)
if (region.magic)
setBonusCoins(bonusVictoryCoins + 1);
// Dwarves earn an extra victory coin for each mine region occupied
if (getRace() != NULL && getRace()->getName().compare("Dwarves") == 0)
if (region.mine)
setBonusCoins(bonusVictoryCoins + 1);
}
}
victoryCoins += points;
victoryCoins += bonusVictoryCoins;
return points;
}
|
Java
|
UTF-8
| 196
| 2.171875
| 2
|
[] |
no_license
|
package factoryparttern.SimpleFactory;
public class SimpleFactoryClient{
public static void main(String[] args)
{
Electricity haier = SimpleFactory.createObject("Haier");
}
}
|
C++
|
UTF-8
| 714
| 2.71875
| 3
|
[] |
no_license
|
#include "JN_FPSLock.h"
#include <SDL.h>
#include <iostream>
#include <cmath>
JN_FPSLock::JN_FPSLock(int targetFPS, int& refFPS): returnFPS(refFPS)
{
this->targetFPS = targetFPS;
timeAtCreation = std::chrono::system_clock::now();
}
JN_FPSLock::~JN_FPSLock()
{
float deltaTimeBeforeWait = CalculateDeltaTime();
float targetDeltaTime = 1000.0f / targetFPS;
SDL_Delay(std::fmax(targetDeltaTime - deltaTimeBeforeWait, 0));
float deltaTimeAfterWait = CalculateDeltaTime();
returnFPS = 1000.0f / deltaTimeAfterWait;
}
float JN_FPSLock::CalculateDeltaTime()
{
auto now = std::chrono::system_clock::now();
std::chrono::duration<float, std::milli> span = now - timeAtCreation;
return span.count();
}
|
Java
|
UTF-8
| 17,381
| 2.28125
| 2
|
[
"Apache-2.0"
] |
permissive
|
// Copyright 1998--2010 Michael Bruce-Lockhart and Theodore S. Norvell
//
// 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 tm.clc.analysis;
import java.util.*;
import tm.utilities.Assert;
/**
* Generally, a representation of an <em>id</em> with possible qualification.
* <ul><code>ScopedName</code>s are used in several contexts:
* <li> to represent an id or operator with any qualifications as encountered
* in the source code </li>
* <li> to represent the <em>fully qualified name</em> (fqn) corresponding to
* a declared entity </li>
* <li> as keys in the runtime symbol table </li>
* </ul>
* <p>The "encountered representations" if ids are used by the lookup logic
* (compile-time symbol table) to find the matching <code>Declaration</code>(s).
* The fqn of a <code>Declaration</code> is then used to uniquely identify
* objects and other entities at runtime (important exceptions in C++ are
* non-static class attributes, which necessarily use a different naming scheme
* in order to support multiple inheritance).
* <p>A <code>ScopedName</code> has two distinct and enforced states. The
* first is <em>modifiable</em>, wherein the name can be built, extended, and
* revised. The second is <em>readonly</em>, in which the components of the name
* may be traversed, but not modified. State transition is one-way
* (irreversable), from modifiable to readonly, via the <code>completed</code>
* method.
* <p>An internal traversal index is provided for each <code>ScopedName</code>.
* This index is shared among all objects with references to the name,
* and must be treated as such.
*/
public abstract class ScopedName {
/**
* Error message provided when modification is attempted on a
* <code>ScopedName</code in <em>readonly</em> state.
*/
protected static final String READONLY =
"Attempt to modify readonly ScopedName {0}";
/**
* Error message provided when traversal (using internal iterator) is
* attempted on a <code>ScopedName</code in <em>modifiable</em> state.
*/
protected static final String MODIFIABLE =
"Attempt to traverse modifiable ScopedName {0}";
protected static final String INVALID =
"Attempt to traverse modified ScopedName {0}";
/** Constructor flag for unique id */
public static final int UNIQUE = 0;
/** Constructor flag for anonymous id */
public static final int ANON = 1;
/** Constructor flag for builtin copy ref argument */
public static final int COPY_REF = 2;
private static final String UNIQUE_PREFIX = "_TMUniqueId";
private static final String ANON_ID = "_TMAnonId";
public static final String COPY_REF_ID = "_TMCopyRef";
private static int unique_id = 0; // used to assign unique names
private boolean absolute = false; // starting from global scope?
// Invariant: qualifiedName.getElement(i) instanceof String, for all i
private Vector qualifiedName = new Vector ();
/**
* An internal index/iterator over the elements of this
* <code>ScopedName</code>. This is shared among all entities with
* references to this object, so care must be taken when using it to
* traverse over the elements of the name.
*/
public ScopedNameIndex index = new ScopedNameIndex ();
// are we readonly or modifiable ?
private boolean readonly = false;
/**
* Creates a new <code>ScopedName</code> instance.
*/
public ScopedName () { }
/**
* Creates a new <code>ScopedName</code> instance.
*
* @param rawName either an initial terminal id, a simple name, or
* a string representation of a qualified name.
*/
protected ScopedName (String rawName) {
// is the purpose of this constructor to break down a
// String representation into parts ?
if (rawName == null) return;
String scopeOp = getScopeOp();
int from = 0;
int to = rawName.indexOf(scopeOp);
while (to != -1){
qualifiedName.addElement(rawName.substring(from,to));
from = to + scopeOp.length();
to = rawName.indexOf(scopeOp, from);
}
qualifiedName.addElement(rawName.substring(from,rawName.length()));
}
/**
* Creates a new <code>ScopedName</code> instance.
*
* @param elements the components of the name.
*/
protected ScopedName (String elements[]){
for (int e = 0; e < elements.length; e++)
qualifiedName.addElement(elements[e]);
}
/**
* Copy constructor.
* @param orig a <code>ScopedName</code> value
*/
public ScopedName (ScopedName orig) {
absolute = orig.absolute;
// deep copy Vector
qualifiedName = (Vector) orig.qualifiedName.clone ();
}
public abstract Object clone () ;
/**
* Creates a new <code>ScopedName</code> initialized according to
* the flag passed in.
* @param flag controls initialization. Valid values defined in class.
*/
public ScopedName (int flag) {
String id = null;
switch (flag) {
case UNIQUE:
id = UNIQUE_PREFIX + Integer.toString (unique_id++);
break;
case ANON:
id = ANON_ID; // would this ever need to be a unique instance ?
break;
case COPY_REF:
id = COPY_REF_ID;
break;
}
qualifiedName.addElement (id);
}
/**
* Gives the number of parts in this name
* @return the number of parts
*/
public int length () { return qualifiedName.size (); }
/** Return the language specific scope operator. C++'s "::" is the default.
* Over-ride for other languages
* @return the default C++ scope operator
*/
public abstract String getScopeOp() ;
/**
* Indicate that this id is <em>absolutely qualified</em>, i.e. identifies
* an entity by its placement in relation to the outermost scope.
*/
public void set_absolute () { absolute = true; }
/**
* Is this id <em>absolutely qualified</em> or not ?
* @return a <code>boolean</code> indication of this
*/
public boolean is_absolute () { return absolute; }
/**
* Is the name prefixed by any scope qualifiers (global scope included)?
* @return a <code>boolean</code> indication of this
*/
public boolean is_qualified () { return (absolute || qualifiedName.size () > 1); }
/**
* Implementation of <code>equals (Object)</code>. Tries a few short cuts
* before resorting to element-by-element comparison of this
* <code>ScopedName</code> with that provided as an argument.<br>
* <b>Note:</b> states (modifiable or readonly) are not compared.
* @param other an <code>Object</code> value to compare
* @return <code>true</code> if the <code>ScopedName</code>s consist of
* <code>String</code> elements for which <code>equals</code> returns true
* when comparing each in sequence. Otherwise <code>false</code>.
*/
public boolean equals( Object other ) {
if( other == null ) return false ;
if( ! (other instanceof ScopedName) ) return false ;
ScopedName other_scoped_name = (ScopedName) other ;
if( this.absolute != other_scoped_name.absolute )
return false ;
int sz = this.qualifiedName.size() ;
if( sz != other_scoped_name.qualifiedName.size() )
return false ;
Enumeration e0 = this.qualifiedName.elements();
Enumeration e1 = other_scoped_name.qualifiedName.elements();
while (e0.hasMoreElements ()) {
if( ! e0.nextElement().equals( e1.nextElement() ) ) {
return false ; } }
return true ;
}
/**
* Is other name contained at end of this name?
* Added by mpbl April, 2003
* <b>Note:</b> states (modifiable or readonly) are not compared.
* @param other a <code>ScopedName</code> value to compare
* @return <code>true</code> if this <code>ScopedName</code>s ends
* in other ScopedName. Otherwise <code>false</code>.
*/
public boolean contains( ScopedName other ) {
if( this.qualifiedName.size() < other.qualifiedName.size() )
return false ;
Enumeration e0 = this.qualifiedName.elements();
Enumeration e1 = other.qualifiedName.elements();
while (e1.hasMoreElements ()) {
if( ! e0.nextElement().equals( e1.nextElement() ) ) {
return false ; } }
return true ;
}
/**
* Provides a <code>String</code> representation of this
* <code>ScopedName</code> suitable for presentation, including
* <em>separators</em>. Default separator is <em>scope operator</em>.
* <p>For example, in C++, for a name marked as <code>absolute</code> with
* elements "nsA", "clB", "memC", this method would evaluate to
* "::nsA::clB::memC".
*
* @return a presentable <code>String</code> representation
*/
public String getName (String separator) {
StringBuffer name = new StringBuffer ();
if (absolute) name.append (separator);
for (Enumeration parts = qualifiedName.elements ();
parts.hasMoreElements (); ) {
name.append ((String) parts.nextElement ());
if (parts.hasMoreElements ()) name.append (separator);
}
return name.toString ();
}
public String getName () {
return getName(getScopeOp());
}
/** put here for debugging purposes, may be safely removed */
public String toString () { return this.getName (); }
/**
* Provides an <code>Enumeration</code> over the elements of this
* <code>ScopedName</code>. Useful when the internal shared iterator
* cannot be relied upon.
*
* @return an <code>Enumeration</code> over the parts of this name
*/
public Enumeration getParts () { return qualifiedName.elements (); }
/**
* Returns a <code>String</code> representation of this name without
* its qualifiers.
* @return the name stripped of any qualifiers
*/
public String getUnqualifiedName () {
return (String) qualifiedName.lastElement ();
}
/**
* Returns the <code>String</code> representing the terminal id of this
* name. Identical behaviour to <code>getUnqualifiedName</code>.
* @return the terminal id
*/
public String getTerminalId () {
return getUnqualifiedName ();
}
/**
* Replaces the current terminal id with the supplied value.
* @param tid the new terminal id of this <code>ScopedName</code>
*/
public void setTerminalId (String tid) {
if (readonly) Assert.apology (READONLY, getName ());
qualifiedName.removeElementAt (qualifiedName.size () - 1);
qualifiedName.addElement (tid);
index.invalidate();
}
/**
* Removes the current terminal id. The qualifier preceding the
* terminal id (if any) becomes the new terminal id. Does nothing if
* the size of this <code>ScopedName</code> is 0.
*/
public void removeTerminalId () {
if (readonly) Assert.apology (READONLY, getName ());
int qsize = qualifiedName.size ();
if (qsize > 0) {
qualifiedName.removeElementAt (qsize - 1);
index.invalidate();
}
}
/**
* Appends the elements in the provided <code>ScopedName</code> to this
* <code>ScopedName</code>. Elements are appended in the order encountered.
* @param toAppend a <code>ScopedName</code> containing elements to
* append.
*/
public void append (ScopedName toAppend) {
if (readonly) Assert.apology (READONLY, getName ());
Enumeration e = toAppend.qualifiedName.elements();
while (e.hasMoreElements ())
qualifiedName.addElement (e.nextElement ());
index.invalidate();
}
/**
* Appends the <code>String</code> provided to this <code>ScopedName</code>.
* The provided element becomes the new terminal id for the name.
* @param toAppend the <code>String</code> to append
*/
public void append (String toAppend) {
if (readonly) Assert.apology (READONLY, getName ());
qualifiedName.addElement (toAppend);
index.invalidate();
}
/**
* Inserts the elements in the provided <code>ScopedName</code> at the front of this
* <code>ScopedName</code>. Order of the inserted elements is preserved.
* added April, 2003 by mpbl
* @param toAppend a <code>ScopedName</code> containing elements to
* append.
*/
public void insert (ScopedName toInsert) {
if (readonly) Assert.apology (READONLY, getName ());
Enumeration e = toInsert.qualifiedName.elements();
int where = 0;
while (e.hasMoreElements ())
qualifiedName.insertElementAt(e.nextElement (),where++);
index.invalidate();
}
/**
* Inserts the <code>String</code> provided in front of this <code>ScopedName</code>.
* The provided element becomes the new element 0 for the name.
* added April, 2003 by mpbl
* @param toAppend the <code>String</code> to append
*/
public void insert (String toInsert) {
if (readonly) Assert.apology (READONLY, getName ());
qualifiedName.insertElementAt (toInsert, 0);
index.invalidate();
}
/**
* Moves this <code>ScopedName</code>'s state from <em>modifiable</em>
* to <em>readonly</em>, allowing traversal via the internal iterator.
*/
public void completed () { readonly = true; index.reset(); }
/**
* Provides access to the part of this <code>ScopedName</code> currently
* indexed by the internal iterator.
* @return the currently selected part
*/
public String selectedPart () {
if (!index.isValid())
Assert.check (INVALID, this.getName ());
return (String) qualifiedName.elementAt (index.value ());
}
/**
* Provides a reference to the elements of a <code>ScopedName</code>.
* Intended for use when a <code>ScopedName</code> has been built and set
* to <em>readonly</em> via the <code>completed</code> method.
* Operation undefined otherwise.
* <p>As this provides a single shared internal traversal, an
* <code>Enumeration</code> ( via <code>ScopedName.getParts ()</code> )
* is preferred where exclusive traversal is required.
*/
public class ScopedNameIndex {
private int index = 0;
private boolean valid = false;
public void invalidate(){valid = false;}
public boolean isValid(){return valid;}
/**
* Advances the index by one.
*
* @return <code>true</code> if the advance was successful,
* <code>false</code> if it wasn't possible
*/
public boolean advance () {
if (index < qualifiedName.size () - 1) {
index++;
return true;
}
return false;
}
/**
* Resets the index to the first element in the <code>ScopedName</code>.
*/
public void reset () { index = 0; valid = true; }
/**
* Reverses the index by one.
*
* @return <code>true</code> if the reverse was successful,
* <code>false</code> if it wasn't possible
*/
public boolean reverse () {
if (index > 0) {
index--;
return true;
}
return false;
}
/**
* Provides the position of the currently selected element in the
* <code>ScopedName</code>
*
* @return the position
*/
public int value () { return index; }
/**
* Indicates whether or not the index currently references the
* <code>ScopedName</code>'s terminal id.
*
* @return <code>true</code> if the terminal id is the currently
* selected element, <code>false</code> otherwise
*/
public boolean terminal () {
return (index + 1 == qualifiedName.size ());
}
}
}
|
PHP
|
UTF-8
| 4,028
| 2.546875
| 3
|
[
"MIT"
] |
permissive
|
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Jar;
use Ticket;
use Auth;
class TicketController extends Controller
{
public function create(Jar $jar)
{
if(!Auth::check()){
return redirect('home')
->with('warning', 'You must be logged in to do that.');
};
$jarId = $jar->id;
if(!Auth::user()->isOwner($jarId)){
return redirect('home')
->with('warning', 'You do not own that jar.');
// TODO:Log this event.
}
return view('jars.overview')
->with('jar', $jar);
// }
}
public function store(Request $request, Jar $jar){
if(!Auth::check()){
return redirect('home')
->with('warning', 'You must be logged in to do that.');
};
$jarId = $jar->id;
if(!Auth::user()->isOwner($jarId)){
return redirect('home')
->with('warning', 'You do not own that jar.');
}
$request->validate([
'name' => 'required|max:255',
'phoneNumber' => 'required',
'email' => 'email',
]);
for ($i=0; $i < $request->quantity; $i++) {
$ticket = new Ticket;
$ticket->user_id = Auth::user()->id;
$ticket->jar_id = $jar->id;
$ticket->name = $request->name;
$ticket->phone = $request->phoneNumber;
$ticket->email = $request->email;
$ticket->save();
}
return redirect(route('jar.view', $jar))
->with('success', 'Your ticket(s) have been entered into the raffle!');
}
public function update(Request $request, Ticket $ticket){
if(!Auth::check()){
return redirect('home')
->with('warning', 'You must be logged in to do that.');
};
$jarId = $ticket->jar_id;
if(!Auth::user()->isOwner($jarId)){
return redirect('home')
->with('warning', 'You do not own that jar.');
}
if(!$ticket->user_id == Auth::user()->id){
return redirect('home')
->with('warning', 'That ticket is unavailable.');
}
// $request->validate([
// 'name' => 'required|max:255',
// 'phoneNumber' => 'required',
// 'email' => 'email',
// 'statusID' => 'integer'
// ]);
// $ticket->user_id = Auth::user()->id;
// $ticket->jar_id = $jar->id;
// $ticket->name = $request->name;
// $ticket->phone = $request->phoneNumber;
// $ticket->email = $request->email;
// $ticket->save();
}
public function updateStatus(Request $request, Ticket $ticket){
if(!Auth::check()){
return redirect('home')
->with('warning', 'You must be logged in to do that.');
};
$jarId = $ticket->jar_id;
if(!Auth::user()->isOwner($jarId)){
return redirect('home')
->with('warning', 'You do not own that jar.');
}
if(!$ticket->user_id == Auth::user()->id){
return redirect('home')
->with('warning', 'That ticket is unavailable.');
}
$request->validate([
'statusID' => 'integer|required'
]);
$ticket->status_id = $request->statusID;
$ticket->save();
$winnersOtherTickets = Ticket::where('name', '=', $ticket->name)
->where('winner', '=', 1)
->get();
foreach($winnersOtherTickets as $otherTicket)
{
$otherTicket->status_id = $request->statusID;
$otherTicket->save();
}
$jar = $ticket->jar;
return redirect(route('jar.view', $jar))
->with('success', 'The status of that ticket has been updated.');
}
}
|
Java
|
UTF-8
| 1,570
| 2.234375
| 2
|
[] |
no_license
|
package com.example.manishchoudhary.formbuilder.CustomForm;
import android.content.Context;
import android.os.Build;
import android.support.annotation.Nullable;
import android.support.annotation.RequiresApi;
import android.support.v7.widget.ThemedSpinnerAdapter;
import android.util.AttributeSet;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import com.example.manishchoudhary.formbuilder.Helper.Utiles;
/**
* Created by manish.choudhary on 2/11/17.
*/
public class MyLinearLayout extends LinearLayout {
private int padding;
public MyLinearLayout(Context context) {
super(context);
setDefaultLayoutParmas();
}
public void setDefaultLayoutPadding(int padding) {
this.setPadding(padding, padding, padding, padding);
}
private void setDefaultLayoutParmas() {
LayoutParams params = new LayoutParams(Utiles.getScreenWidth(), ViewGroup.LayoutParams.WRAP_CONTENT);
this.setLayoutParams(params);
}
public MyLinearLayout(Context context, @Nullable AttributeSet attrs) {
super(context, attrs);
setDefaultLayoutParmas();
}
public MyLinearLayout(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
setDefaultLayoutParmas();
}
@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
public MyLinearLayout(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
super(context, attrs, defStyleAttr, defStyleRes);
setDefaultLayoutParmas();
}
}
|
Java
|
UTF-8
| 224
| 2.140625
| 2
|
[] |
no_license
|
package org.businessmanager.service;
public interface InvoiceNumberGenerator {
/**
* Retrieves the next unique invoice number.
*
* @return the next unique invoice number
*/
public Long getNextInvoiceNumber();
}
|
JavaScript
|
UTF-8
| 380
| 2.6875
| 3
|
[] |
no_license
|
'use strict'
const text = document.querySelector('.text');
function addText(){
text.innerHTML += '<p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Eius ipsum quo facere harum, facilis reiciendis ab. Natus, omnis necessitatibus! Quis quas incidunt hic consectetur illum commodi corrupti ipsa ratione assumenda.</p>'
}
text.addEventListener('mouseover', addText);
|
C
|
UTF-8
| 192
| 2.625
| 3
|
[] |
no_license
|
//哈弗曼树结点结构
typedef struct{
int weight;//结点权重
int parent,left,right;//父节点、左孩子、右孩子在数组中的位置下标
}HTNode,*HuffmanTree;
|
Markdown
|
UTF-8
| 8,964
| 3.59375
| 4
|
[] |
no_license
|
# Python API Homework - What's the Weather Like?
## Background
Whether financial, political, or social -- data's true power lies in its ability to answer questions definitively. So let's take what you've learned about Python requests, APIs, and JSON traversals to answer a fundamental question: "What's the weather like as we approach the equator?"
Now, we know what you may be thinking: _"Duh. It gets hotter..."_
But, if pressed, how would you **prove** it?

## Part I - WeatherPy
### Observations
### Strongest negative correlation
#### Northern Hemisphere - Temperature (F) vs. Latitude
The max temperatures (F) (y-axis) are highest closest to the equator (latitue 0). As you get farther away from the equator (higher latitude value, x-axis), the max temperatures (F) decrease.

### Strongest positive correlation
#### Southern Hemisphere - Temperature (F) vs. Latitude
The temperatures (F) (y-axis) are lowest farther away from the equator (latitue 0). As you get closer to the equator (higher latitude value, x-axis), the max temperature (F) increases.

Use WeatherPy python script to visualize the weather of 500+ cities across the world of varying distance from the equator. [CityPy library](https://pypi.python.org/pypi/citipy) and [OpenWeatherMap API](https://openweathermap.org/api) were utilized to generate retrieve random list of cites, associated weather data and create a representative model of weather across world cities.
Series of scatter plots are created to showcase the following relationships:
* Temperature (F) vs. Latitude

Latitude vs. Temerature (F) scatter plot shows temperatures rising as you get closer to zero degrees latitude (equator), then as the latitude values increase greater than zero (increasing further from the equator), the temperature decreases steadily.
* Humidity (%) vs. Latitude

Latitude vs. Humidity (%) scatter plot does not appear to show a strong correlation.
* Cloudiness (%) vs. Latitude

Latitude vs. Cloudiness (%) scatter plot does not appear to show a strong correlation.
* Wind Speed (mph) vs. Latitude

Latitude vs. Wind Speed scatter plot does not appear to show a strong correlation.
After each plot, explaination of what the code is analyzing is included.
Next, city weather data is separated into northern hemisphere (greater than or equal to 0 degrees latitude) and southern hemisphere (less than 0 degrees latitude). Linear regressions were run on each relationship. After each plot, explaination of linear regression modeling is included.
* Northern Hemisphere - Temperature (F) vs. Latitude

Strong negative correlation coefficient (r value). In the northern hemisphere, the farther you are in degrees latitude from the equator, the temperature decreases steadily.
* Southern Hemisphere - Temperature (F) vs. Latitude

Moderate positive correlation coefficient (r value). In the southern hemisphere, the closer you are in degrees latitude to the equator, the temperature increases moderately.
* Northern Hemisphere - Humidity (%) vs. Latitude

Moderate positive correlation coefficient (r value). In the northern hemisphere, the farther you are in degrees latitude from the equator, the percent humidity increases moderately.
* Southern Hemisphere - Humidity (%) vs. Latitude

Moderate positive correlation coefficient (r value). In the southern hemisphere, the closer you are in degrees latitude to the equator, the percent humidity increases moderately.
* Northern Hemisphere - Cloudiness (%) vs. Latitude

Weak positive correlation coefficient (r value). In the northern hemisphere, the farther you are in degrees latitude from the equator, the percent cloudiness increases slightly.
* Southern Hemisphere - Cloudiness (%) vs. Latitude

Weak positive correlation coefficient (r value). In the southern hemisphere, the closer you are in degrees latitude to the equator, the percent cloudiness increases slightly.
* Northern Hemisphere - Wind Speed (mph) vs. Latitude

Very weak positive correlation coefficient (r value). In the northern hemisphere, the farther you are in degrees latitude from the equator, the wind speed (mph) increases very slightly.
* Southern Hemisphere - Wind Speed (mph) vs. Latitude

Weak negative correlation coefficient (r value). In the southern hemisphere, the closer you are in degrees latitude to the equator, the wind speed (mph) decreases slightly.
Final notebook includes:
* Randomly select **at least** 500 unique (non-repeat) cities based on latitude and longitude. Use get_cities(mincitycount) to retrive cities where mincitycount is the (int) minimum city count get_cities will retrieve.
* Perform a weather check on each of the cities using a series of successive API calls.
* Include a print log of each city as it's being processed with the city number and city name.
* Save a CSV of all retrieved data and a PNG image for each scatter plot.
### Part II - VacationPy
Now let's use our weather data to plan future vacations. Google Places API and jupyter-gmaps were used for this part the project.
VacationPy includes:
* A heat map that displays the humidity for every city from Part I - WeatherPy.

* Dataframe narrowed down to ideal weather conditions:
* A max temperature lower than 80 degrees but higher than 70.
* Wind speed less than 10 mph.
* Less than or equal to 15% cloudiness.
* Google Places API was used to find the first hotel for each city located within 5000 meters of the cities with ideal weather conditions.
* Hotels layer plot on top of the humidity heatmap with each hotel containing the **Hotel Name**, **City**, and **Country**.

As final considerations:
* Analysis completed using a Jupyter notebook.
* Matplotlib plotting libraries.
* For Part I, written description of three observable trends based on the data.
* For Part II, screenshots of the heatmap and hotels gmaps layers.
* Plot labels including: Plot Titles (with date of analysis) and Axes Labels.
### Other Notes and Considerations
* The city data generated is based on random coordinates as well as different query times. As such, outputs will not be an exact match.
* Geographic coordinate system, [this site](http://desktop.arcgis.com/en/arcmap/10.3/guide-books/map-projections/about-geographic-coordinate-systems.htm) is a great reference.
* Open Weather
* Where do you request the API key? [Signup for OpenWeather](https://home.openweathermap.org/users/sign_up)
* Which Weather API in particular will you need?
API call: api.openweathermap.org/data/2.5/weather?
* What URL endpoints does it expect? q={city name}&appid={API key}
* What JSON structure does it respond with?
```Index 0 fetching weather for San Diego
[{'base': 'stations',
'clouds': {'all': 75},
'cod': 200,
'coord': {'lat': 32.72, 'lon': -117.16},
'dt': 1609811275,
'id': 5391811,
'main': {'feels_like': 52.43,
'humidity': 72,
'pressure': 1022,
'temp': 55.8,
'temp_max': 60.01,
'temp_min': 53.6},
'name': 'San Diego',
'sys': {'country': 'US',
'id': 5771,
'sunrise': 1609771885,
'sunset': 1609808147,
'type': 1},
'timezone': -28800,
'visibility': 10000,
'weather': [{'description': 'broken clouds',
'icon': '04n',
'id': 803,
'main': 'Clouds'}],
'wind': {'deg': 10, 'speed': 4.7}}]
```
* Citipy was utilized to generate list of random cities [citipy Python library](https://pypi.python.org/pypi/citipy).
* Thorough README.md file.
|
C++
|
UTF-8
| 895
| 2.5625
| 3
|
[
"Apache-2.0"
] |
permissive
|
#pragma once
namespace cppgui {
// Inherit_with_aspects
template<class Class, template<class> class ...Aspects> class Inherit_with_aspects;
template<class Class, template<class> class Aspect>
class Inherit_with_aspects<Class, Aspect>: public Aspect< Class > {};
template<class Class, template<class> class FirstAspect, template<class> class ...OtherAspects>
class Inherit_with_aspects<Class, FirstAspect, OtherAspects...>: public FirstAspect< Inherit_with_aspects<Class, OtherAspects...> > {};
/* template<template<class Config, bool With_layout, class Parent> class Aspect_, class Config, bool With_layout>
struct Aspect_specializer {
template<class Parent> using Aspect = Aspect_<Config, With_layout, Parent>;
}; */
//#define ASPECT(Name, Config, With_layout) typename Aspect_specializer<Name, Config, With_layout>::Aspect
} // ns cppgui
|
Java
|
UTF-8
| 614
| 3.1875
| 3
|
[] |
no_license
|
package leetcode;
public class P507 {
//Time Limit Exceeded
/*
public static boolean checkPerfectNumber(int num) {
int total = 1;
for(int i = 2; i < num; i++)
total += num%i==0?i:0;
return total == num;
}
*/
public static boolean checkPerfectNumber(int num) {
int total = 1;
for(int i = 2; i < Math.sqrt(num); i++) {
if(num % i == 0) {
total += i + num / i;
}
}
if((int)Math.sqrt(num) * (int)Math.sqrt(num) == num)
total += (int)Math.sqrt(num);
return total == num;
}
}
|
Python
|
UTF-8
| 492
| 2.96875
| 3
|
[] |
no_license
|
a=int(input())
x=input().split(' ')
y=input().split(' ')
z=input().split(' ')
if(z[0]=='5' and z[1]=='3'):
print(1)
print(1)
print(0)
elif(z[0]=='5' and z[1]=='1' and y[0]=='6' and y[1]=='3'):
print(1)
print(1)
print(1)
elif(z[0]=='5' and z[1]=='1' and y[0]=='6' and y[1]=='4'):
print(1)
print(0)
print(1)
elif(z[0]=='5' and z[1]=='1' and y[0]=='6' and y[1]=='2'):
print(1)
print(1)
print(1)
else:
print(z[0],z[1])
print(y[0],y[1])
|
JavaScript
|
UTF-8
| 3,773
| 2.671875
| 3
|
[] |
no_license
|
function TopEntropy(controller, data, svg, limits){
this.description = 'TopEntropy Class. Displayed on top of DataViews. Has to be aligned with dataviews';
this.controller = controller;
this.tooltip = controller.tooltip;
this.data = data;
this.svg = svg;
this.group = this.svg.append("g").attr("class", "topEntropy");
this.limits = limits;
this.ymargin = 0.5;
this.minWidth = 50;
}
TopEntropy.prototype.reorderDimensions = function(newOrder){
var self = this;
var x0 = this.x.domain(newOrder);
var transition = this.group.transition().duration(750);
var delay = function(d, i) { return i * 50; };
transition.selectAll(".histRect")
.delay(delay)
.attr("x", function(d,i) { return (x0(i) +self.xposInc); });
var transitionText = this.group.transition().duration(750);
transitionText.selectAll(".histLabel")
.delay(delay)
.attr("transform", function(d,i){return "translate("+
(x0(i) + self.xposInc + self.width/2) + "," +
(self.limits.y + self.limits.height - 5) + ")"})
};
TopEntropy.prototype.draw = function(averageEntropies){
this.averageEntropies = averageEntropies;
this.x = d3.scale.ordinal()
.domain(d3.range(averageEntropies.length))
.rangeRoundBands([this.limits.x, this.limits.x + this.limits.width], 0.1, 0.1);
this.y = d3.scale.linear()
.domain([0,1])
.range([this.limits.y + this.limits.height - this.ymargin, this.limits.y + this.ymargin]);
this.xposInc = 0;
this.width = this.x.rangeBand() - 5;
if (this.x.rangeBand() > this.minWidth) {
this.xposInc += (this.x.rangeBand() - this.minWidth) / 2;
this.width = this.minWidth;
}
this.group.remove();
this.group = this.svg.append("g").attr("class", "topEntropy");
this.group.append("rect").attr("x", this.limits.x).attr("y", this.limits.y).attr("width",this.limits.width).attr("height",this.limits.height).attr("class","invisibleBox");
var guidelines = [this.limits.y +.25*this.limits.height,
this.limits.y +.5*this.limits.height,
this.limits.y +.75*this.limits.height];
this.group.selectAll("line")
.data(guidelines)
.enter().append("line")
.attr("class","boxline")
.attr("x1", this.limits.x)
.attr("x2", this.limits.x + this.limits.width)
.attr("y1", function(d){return d;})
.attr("y2", function(d){return d;})
.style("stroke", '#bbb');
var histogram = this.group.selectAll("histRect").data(averageEntropies);
var _this = this;
histogram.enter().append("rect")
.attr("x", function(d,i){return _this.x(i) + _this.xposInc})
.attr("y", function(d,i){return _this.y(d)})
.attr("width", _this.width)
.attr("height", function(d,i){return Math.max(_this.limits.y+_this.limits.height - _this.y(d),0)})
.attr("class","histRect");
var labels = this.group.selectAll("histLabel").data(d3.range(_this.data.length));
labels.enter().append("g")
.attr("transform", function(d,i){return "translate("+
(_this.x(i) + _this.xposInc + _this.width/2) + "," +
(_this.limits.y + _this.limits.height - 5) + ")"})
.attr("class","histLabel")
.append("text")
.text(function(d){return _this.data[d].dimension})
.attr("transform", "rotate(-45)");
this.group.append("text").attr("x",this.limits.x).attr("y",this.limits.y+20).text("Average Entropy").attr("class","borderText");
this.group.on("click", function(){
_this.controller.reorderDimensions(d3.range(_this.averageEntropies.length).sort(function (a, b) {
return (_this.averageEntropies[b] - _this.averageEntropies[a])
}));
});
};
|
C#
|
UTF-8
| 1,335
| 3.171875
| 3
|
[] |
no_license
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace MyLinq
{
class ProjectionComparer<TElement, TKey> : IComparer<TElement>
{
private readonly Func<TElement, TKey> _keySelector;
private readonly IComparer<TKey> _keyComparer;
public ProjectionComparer(Func<TElement, TKey> keySelector, IComparer<TKey> keyComparer)
{
_keySelector = Memoize(keySelector);
_keyComparer = keyComparer ?? Comparer<TKey>.Default;
}
public int Compare(TElement x, TElement y)
{
return _keyComparer.Compare(_keySelector(x), _keySelector(y));
}
private static Func<TElement, TKey> Memoize(Func<TElement, TKey> keySelector)
{
var cache = new Dictionary<TElement, TKey>();
return element =>
{
TKey comparisonKey;
if (!cache.TryGetValue(element, out comparisonKey))
{
comparisonKey = keySelector(element);
cache[element] = comparisonKey;
}
return comparisonKey;
};
}
}
}
|
Java
|
UTF-8
| 3,122
| 2.265625
| 2
|
[] |
no_license
|
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package articuloProductoClases;
import java.util.List;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;
import HiberanteUtil.HibernateUtil;
import tablas.KardexSerieNumero;
/**
*
* @author Henrri
*/
public class cKardexSerieNumero {
Session sesion = null;
public String error;
public String getError() {
return error;
}
public void setError(String error) {
this.error = error;
}
public cKardexSerieNumero() {
this.sesion = HibernateUtil.getSessionFactory().getCurrentSession();
}
public int crear(KardexSerieNumero objKardexSerieNumero) {
int cod = 0;
Transaction trns = null;
sesion = HibernateUtil.getSessionFactory().openSession();
try {
trns = sesion.beginTransaction();
cod = (Integer) sesion.save(objKardexSerieNumero);
sesion.getTransaction().commit();
} catch (Exception e) {
if (trns != null) {
trns.rollback();
}
e.printStackTrace();
setError(e.getMessage());
} finally {
sesion.flush();
sesion.close();
}
return cod;
}
public List leer() {
return null;
}
public KardexSerieNumero leer_codKardexSerieNumero(int codKardexSerieNumero) {
sesion = HibernateUtil.getSessionFactory().openSession();
return (KardexSerieNumero) sesion.get(KardexSerieNumero.class, codKardexSerieNumero);
}
/**
*
* @param codKardexArticuloProducto
* @return
*/
public List leer_por_codKardexArticuloProducto(int codKardexArticuloProducto) {
List l = null;
Transaction trns = null;
sesion = HibernateUtil.getSessionFactory().openSession();
try {
sesion = HibernateUtil.getSessionFactory().openSession();
Query q = sesion.createQuery("from KardexSerieNumero ksn "
+ "where ksn.kardexArticuloProducto.codKardexArticuloProducto = :cod "
+ "and substring(ksn.registro,1,1) = 1")
.setParameter("cod", codKardexArticuloProducto);
l = (List) q.list();
} catch (Exception e) {
e.printStackTrace();
} finally {
sesion.flush();
}
return l;
}
public boolean actualizar(KardexSerieNumero objKardexSerieNumero) {
sesion = HibernateUtil.getSessionFactory().openSession();
sesion.getTransaction().begin();
try {
sesion.update(objKardexSerieNumero);
sesion.getTransaction().commit();
return true;
} catch (Exception e) {
sesion.getTransaction().rollback();
e.printStackTrace();
setError("KardexSerieNumero_actualizar: " + e.getMessage());
}
return false;
}
}
|
Java
|
UTF-8
| 4,210
| 2.046875
| 2
|
[] |
no_license
|
package com.example.w4pity.retropacman;
import android.app.Application;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
import android.media.MediaPlayer;
import android.provider.MediaStore;
import android.util.Log;
import android.widget.TextView;
/**
* Created by W4pity on 25/04/2016.
*/
public class Pacman extends Perso{
//aint color = new Paint(Paint.ANTI_ALIAS_FLAG);
private int nbOfPoints = 0;
private boolean boosted = false;
private long oldTimeBoost;
private long oldTimeView = 0;
private boolean openMouth = true;
private int anticipationMvt = 0;
private MediaPlayer mdB;
int songBonus = R.raw.hiha;
// Paint white = new Paint(Paint.ANTI_ALIAS_FLAG);
public Pacman()
{
mdB = MediaPlayer.create(MainActivity.cont, songBonus);
size = CustomView.sizeCell;
color.setColor(Color.YELLOW);
direction = 1;
//size =15;// width/15-(2*padding);
x = 0;
y = 0;
padding = 12*MainActivity.width/540;
}
/*
w---15
y
*/
public void update(Cell[][] cells)
{
super.update(cells);
if(!cells[(y+size/2)/size][(x+size/2)/size].isTaken()) {
cells[(y + size / 2) / size][(x + size / 2) / size].setTaken(true);
nbOfPoints++;
}
if(cells[(y+size/2)/size][(x+size/2)/size].isContainBonus()) {
cells[(y+size/2)/size][(x+size/2)/size].setContainBonus(false);
CustomView.timeBonusold = System.currentTimeMillis();
CustomView.bonusPresent = false;
boosted = true;
mdB.start();
oldTimeBoost = System.currentTimeMillis();
speed+=2;
}
if(boosted && System.currentTimeMillis()-oldTimeBoost>5000)
{
boosted =false;
speed=speedSave ;
}
}
@Override
public void draw(Canvas canvas)
{
Rect r = new Rect(x + padding-4, y + padding-4, x + size - padding+4, y + size - padding+4);
if(direction ==1&&!CustomView.isLoose && !CustomView.isWin) {
if(openMouth)
canvas.drawBitmap(MainActivity.pacmanRight, null,r, null);
else
canvas.drawBitmap(MainActivity.pacmanRightClose, null, r, null);
}
if(direction ==2&&!CustomView.isLoose&& !CustomView.isWin) {
if (openMouth)
canvas.drawBitmap(MainActivity.pacmanBottom, null, r, null);
else
canvas.drawBitmap(MainActivity.pacmanBottomClose, null, r, null);
}
if(direction ==3&&!CustomView.isLoose&& !CustomView.isWin) {
if (openMouth)
canvas.drawBitmap(MainActivity.pacmanLeft, null, r, null);
else
canvas.drawBitmap(MainActivity.pacmanLeftClose, null, r, null);
}
if(direction ==4&&!CustomView.isLoose&& !CustomView.isWin) {
if (openMouth)
canvas.drawBitmap(MainActivity.pacmanTop, null, r, null);
else
canvas.drawBitmap(MainActivity.pacmanTopClose, null, r, null);
}
if(CustomView.isLoose)
canvas.drawBitmap(MainActivity.pacmanDepth, null, r, null);
if(CustomView.isWin)
canvas.drawBitmap(MainActivity.pacmanWin, null, r, null);
if(1000000000/2/speed<System.nanoTime()-oldTimeView)
{
openMouth = !openMouth;
oldTimeView = System.nanoTime();
}
}
public int getNbOfPoints() {
return nbOfPoints;
}
public boolean isBoosted() {
return boosted;
}
public void setBoosted(boolean boosted) {
this.boosted = boosted;
}
public int getAnticipationMvt() {
return anticipationMvt;
}
public void setAnticipationMvt(int anticipationMvt) {
this.anticipationMvt = anticipationMvt;
}
}
|
JavaScript
|
UTF-8
| 2,002
| 2.921875
| 3
|
[] |
no_license
|
let barPlot = d3.select("#body");
d3.json("./birds.json")
.then(showData);
function showData(birds){
let maxMemb = d3.max(birds.birds, d => d.members.length);
let widthScale = d3.scaleLinear()
.domain([0, maxMemb])
.range([0, 300]);
let positionScale = d3.scaleBand()
.domain(birds.birds.map(d => d.family))
.range([0, 300])
.padding(0.1);
// Line:
let line = d3.select('#barPlot')
.append('g')
.attr('transform', 'translate(500, 0)');
line.append('line')
.attr('x1', 0)
.attr('y1', 0)
.attr('x2', 0)
.attr('y2', 400)
.attr('stroke', 'red')
.attr('stroke-width', '2px');
d3.select('#barPlot')
.on('mousemove', function () {
// all the info about the event
let x = d3.event.x;
// relative to the tag in which the event is happening:
let x0 = d3.mouse(this);
line.attr('transform', `translate(${x}, 0)`);
})
// Axes:
let xAxis = d3.axisBottom(widthScale);
let yAxis = d3.axisLeft(positionScale);
d3.select('#xAxis')
.call(xAxis)
.attr('transform', 'translate(150, 300)');
d3.select('#yAxis')
.call(yAxis)
.attr('transform', 'translate(140, 0)');
let joinPlot = barPlot
.selectAll('rect')
.data(birds.birds);
joinPlot.enter()
.append('rect')
.attr('fill', 'grey')
.attr('width', d => widthScale(d.members.length))
.attr('height', positionScale.bandwidth)
.attr('y', d => positionScale(d.family))
.on('click', d => {
d3.select('#moreInfo')
.text(d.members);
})
.on('mouseover', function (){
this.style.fill = 'black';
})
.on('mouseout', function (){
this.style.fill = 'grey';
});
}
|
JavaScript
|
UTF-8
| 652
| 2.671875
| 3
|
[] |
no_license
|
const controlSignUpCheckBoxes = () => {
const establishmentCb = document.querySelector('.establishment-checkbox')
const consumerCb = document.querySelector('.consumer-checkbox')
// if click on establishmentCb, make sure that consumerCb is 0
establishmentCb.addEventListener('click', event => {
if (establishmentCb.checked) {
consumerCb.checked = false;
} else {
consumerCb.checked = true;
}
});
consumerCb.addEventListener('click', event => {
if (consumerCb.checked) {
establishmentCb.checked = false;
} else {
establishmentCb.checked = true;
}
});
}
export { controlSignUpCheckBoxes }
|
Shell
|
UTF-8
| 319
| 2.640625
| 3
|
[
"MIT"
] |
permissive
|
# With `path_to_md5sum` a file with records:
# c4f9d24f1052da9e224247d527a61c98 WTCHG_310996_249_1.fastq.gz
# Extract full list of *.fastq.gz files
grep \.fastq\.gz$ "$inputfile" | cut -d' ' -f3
# Extract the list of unique basenames
grep \.fastq\.gz$ "$inputfile" | cut -d' ' -f3 | sed 's/_..fastq.gz//g' | uniq
|
JavaScript
|
UTF-8
| 1,600
| 3.421875
| 3
|
[] |
no_license
|
var canvas = document.getElementById("game-stage");
var ctx = canvas.getContext("2d");
var x = canvas.width / 2;
var y = canvas.height - 30;
var dx = 2;
var dy = -2;
var paddleX = (canvas.width - 100) / 2;
var rightPressed = false;
var leftPressed = false;
function drawPaddle() {
ctx.beginPath()
ctx.rect(paddleX - 100, canvas.height - 20, 200, 20);
ctx.fillStyle = "#0095D0";
ctx.fill();
ctx.closePath();
if (rightPressed && paddleX < canvas.width - 100) {
paddleX += 7;
} else if (leftPressed && paddleX > 100) {
paddleX -= 7;
}
}
function draw() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
var ball = new Ball();
ball.draw(ctx);
if (x + dx > canvas.width-ball.radius() || x + dx < ball.radius()) {
dx = -dx;
}
if(y + dy < ball.radius()) {
dy = -dy;
} else if(y + dy > canvas.height - ball.radius()) {
if (x > paddleX && x < paddleX + 200) {
dy = -dy;
} else {
console.log("GAME OVER");
document.location.reload();
}
}
drawPaddle();
x += dx;
y += dy;
}
document.addEventListener("keydown", onKeyDown, false);
document.addEventListener("keyup", onKeyUp, false);
function onKeyDown(event) {
if (event.keyCode == 39) {
rightPressed = true;
} else if (event.keyCode == 37) {
leftPressed = true;
}
}
function onKeyUp(event) {
if (event.keyCode == 39) {
rightPressed = false;
} else if (event.keyCode == 37) {
leftPressed = false;
}
}
setInterval(draw, 10);
|
Python
|
WINDOWS-1253
| 660
| 3.84375
| 4
|
[] |
no_license
|
'''
name : Sung Joon Park
student number : 01514170
'''
random = int(input())
total = random
whisper = 0
while random !=0:
salary = str(input())
if salary == 'stop': #must show the average
average = (total-random) / (whisper) #first person substracts his random salary
average = format(average,'.2f') #formatting as a floating point rounded up by 2 demical digits
print('average salary: '+average)
if salary != 'stop':
salary = int(salary)
whisper += 1 #counting how many whispers.
total += int(salary) # the summing up the salary
print('worker #'+format(whisper),'whispers '+format(total))
|
Python
|
UTF-8
| 472
| 4.375
| 4
|
[] |
no_license
|
'''
Created on 26 mar 2018
Write a Python program to calculate number of days between two dates.
Sample dates : (2014, 7, 2), (2014, 7, 11)
Expected output : 9 days
'''
from datetime import date
y = int(input("Input the year : "))
m = int(input("Input the month : "))
d1 = int(input("Input the first day: "))
d2 = int(input("Input the last day: "))
f_date = date(y, m, d1)
l_date = date(y, m, d2)
delta = l_date - f_date
print("The difference is "+str(delta.days)+" days")
|
C++
|
UTF-8
| 3,786
| 2.8125
| 3
|
[] |
no_license
|
#include "energies.h"
// Constructor
energies::energies(basis set_basis) : basis_(set_basis) {
Init();
}
energies::energies(basis set_basis, double set_aInvMin, double set_aInvMax) : aMin_(1.0/set_aInvMin),aMax_(1.0/set_aInvMax),basis_(set_basis) {
Init();
}
// Destructor
energies::~energies() {
}
void energies::Init() {
// Initialize the matrices G0 and T12 to the identity
G0_.resize( basis_.basisDim(), 1 );
G0_=MatrixXd::Identity( basis_.basisDim(),basis_.basisDim() );
T12_.resize( basis_.basisDim(), 1 );
}
// Calculates the HO Green's function matrix at energy E
void energies::setG0(double E) {
for(unsigned int i=0; i<basis_.basisDim(); i++) G0_(i,i)/= 1/(E - 2*basis_.getBasisState(i).n() - basis_.getBasisState(i).l() - 2*basis_.getBasisState(i).N()- basis_.getBasisState(i).L() - 3 );
}
// Calculates the two body t-matrix for a regulated two-body contact interaction at energy E and interaction strength a
void energies::setT12(double E, double a) {
HOstate state,primeState;
double temp;
for(unsigned int i=0; i<basis_.basisDim(); i++) {
if(basis_.getBasisState(i).l()==0 ) {
primeState=basis_.getBasisState(i);
for (unsigned int j=0; j<basis_.basisDim(); j++ ) {
state=basis_.getBasisState(j);
// If N=N',L=L',l=l'=0 use 2-body t-matrix
if( state.N()==primeState.N() && state.L()==primeState.L() && state.l()==0 ) {
temp=( LogGamma(primeState.n()+1.5)+LogGamma(state.n()+1.5)-LogGamma(primeState.n()+1.0)-LogGamma(state.n()+1) )/2.0;
temp=exp( temp );
temp*=2*ROOT2/PI;
temp*=C0( E, a,state.N(),state.L() );
}
// Otherwise the entries are zero
else temp=0;
T12_(i,j)= temp;
T12_(j,i)= temp;
} // End j loop
} // End if (l'==0)
// Inserts zeros when l'!=0
else for (unsigned int j=0; j<basis_.basisDim(); j++ ) {
T12_(i,j)=0;
T12_(j,i)=0;
} // End else for
} // End i loop
}
// Required by setT12, defined as in Tom's notes
double energies::C0(double E, double a, int N, int L) {
double c0=0.0;
int imax= (basis_.nmax()-2.0*N-L )/2.0;
// Return zero for special case a=0
if(a==0) return 0;
// Otherwise calculate according to Tom's notes
for(int i=0; i<imax; i++ ) {
c0+=exp( LogGamma(i+1.5) - LogGamma(i+1) )/( 2.0*i+1.5-(E-2*N-L-1.5) ) ;
}
c0*= -2*ROOT2/PI;
c0-= ROOT2*exp( LogGamma( .75-(E-2*N-L-1.5)/2.0 ) - LogGamma( .25-(E-2*N-L-1.5)/2.0 ) );
c0+=1/a;
return 1.0/c0;
}
void energies::calcPair(double a,double e, Vector2d * pair) {
MatrixXd mm(basis_.statesDim(),basis_.statesDim());
VectorXd vec(basis_.basisDim());
VectorXd primeVec(basis_.basisDim());
double best=123456789; // Start with an absurd number
// Generate the matrix
for(unsigned int i=0; i<basis_.statesDim(); i++) {
primeVec=basis_.getState(i);
for(unsigned int j=0; j<basis_.statesDim(); j++) {
vec=basis_.getState(j);
mm(i,j)=primeVec.transpose()*G0_*T12_*vec;
}
}
// Calculate the eigenvalues
SelfAdjointEigenSolver<MatrixXd> eigensolver(mm);
// Find eigenvalue closes to 1
for(unsigned int i=0; i<basis_.statesDim(); i++ ) {
if( fabs(eigensolver.eigenvalues()(i)-1) < best ) best=eigensolver.eigenvalues()(i);
}
if(best==123456789) cout<<"Error, no good eigenvalues";
(*pair)(0)=e;
(*pair)(1)=best;
}
void energies::calcAllPairs(double aInvMin, double aInvMax, double aInvStep, double eMin, double eMax, double eStep) {
numPairs_=0;
for( double e=eMin; e<eMax; e+=eStep) {
setG0(e);
for( double aInv=aInvMin; aInv<aInvMax; aInv+=aInvStep) {
setT12(e,a);
numPairs++;
eLambdaPairs_.conservativeResize(numPairs_);
calcPair(a,e,&(eLambdaPairs_.row(numPairs_-1)));
}
}
}
|
Java
|
UTF-8
| 6,173
| 2.09375
| 2
|
[
"MIT"
] |
permissive
|
package com.zkp.androidwan.module.main.activity.weather;
import android.annotation.SuppressLint;
import android.content.Context;
import android.util.Log;
import com.google.gson.Gson;
import com.zkp.androidwan.R;
import com.zkp.androidwan.app.App;
import com.zkp.androidwan.base.presenter.BasePresenter;
import com.zkp.androidwan.bean.AddressItem;
import com.zkp.androidwan.bean.JsonBean;
import com.zkp.androidwan.db.DbHelper;
import com.zkp.androidwan.db.DbHelperImpl;
import com.zkp.androidwan.db.entity.Address;
import com.zkp.androidwan.utils.GetJsonDataUtil;
import com.zkp.androidwan.utils.RxUtils;
import org.json.JSONArray;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import javax.inject.Inject;
import io.reactivex.Observable;
import io.reactivex.ObservableOnSubscribe;
/**
* @author: zkp
* @project: Gank
* @package: com.zkp.gank.module.main.activity.weather
* @time: 2019/5/9 11:14
* @description:
*/
public class WeatherPresenter extends BasePresenter<WeatherActivityContract.View> implements WeatherActivityContract.Presenter {
private DbHelper dbHelper;
@Inject
public WeatherPresenter() {
dbHelper = new DbHelperImpl();
}
@Override
public void loadAddressData(Context context) {
addSubscribe(Observable.create((ObservableOnSubscribe<AddressItem>) e -> {
AddressItem addressItem = loadJson(context);
e.onNext(addressItem);
}).compose(RxUtils.schedulerTransformer())
.filter(addressItem -> mView != null)
.subscribe(addressItem -> {
mView.loadAddressDataSuccess(addressItem);
}
));
}
@Override
public void addAddress(Address address) {
addSubscribe(Observable.create((ObservableOnSubscribe<Address>) e -> {
Address result = dbHelper.addAddress(address);
e.onNext(result);
}).compose(RxUtils.schedulerTransformer())
.filter(result -> mView != null)
.subscribe(result -> {
mView.addAddressSuccess(result);
}
));
}
@Override
public void getAddressByID(Long id) {
addSubscribe(Observable.create((ObservableOnSubscribe<Address>) e -> {
Address result = dbHelper.getAddressByID(id);
e.onNext(result);
}).compose(RxUtils.schedulerTransformer())
.filter(result -> mView != null)
.subscribe(result -> {
mView.getAddressByIDSuccess(result);
}
));
}
@Override
public void getAllAddress() {
addSubscribe(Observable.create((ObservableOnSubscribe<List<Address>>) e -> {
List<Address> result = dbHelper.getAllAddress();
Log.d("qwe", result.toString());
e.onNext(result);
}).compose(RxUtils.schedulerTransformer())
.filter(result -> mView != null)
.subscribe(result -> {
mView.getAllAddressSuccess(result);
}
));
}
private AddressItem loadJson(Context context) {
AddressItem result = new AddressItem();
String jsondata = new GetJsonDataUtil().getJson(context, "province.json");
ArrayList<JsonBean> jsonBean = parseData(jsondata);
result.setOptions1Items(jsonBean);
for (int i = 0; i < jsonBean.size(); i++) {//遍历省份
ArrayList<String> cityList = new ArrayList<>();//该省的城市列表(第二级)
ArrayList<ArrayList<String>> provinceArealist = new ArrayList<>();//该省的所有地区列表(第三极)
for (int c = 0; c < jsonBean.get(i).getCityList().size(); c++) {//遍历该省份的所有城市
String cityName = jsonBean.get(i).getCityList().get(c).getName();
//添加城市
cityList.add(cityName);
//如果无地区数据,建议添加空字符串,防止数据为null 导致三个选项长度不匹配造成崩溃
//该城市的所有地区列表
ArrayList<String> cityArealist = new ArrayList<>(jsonBean.get(i).getCityList().get(c).getArea());
provinceArealist.add(cityArealist);//添加该省所有地区数据
}
result.getOptions2Items().add(cityList);
result.getOptions3Items().add(provinceArealist);
}
return result;
}
/**
* Gson 解析
*
* @param result
* @return
*/
private ArrayList<JsonBean> parseData(String result) {
ArrayList<JsonBean> detail = new ArrayList<>();
try {
JSONArray data = new JSONArray(result);
Gson gson = new Gson();
for (int i = 0; i < data.length(); i++) {
JsonBean entity = gson.fromJson(data.optJSONObject(i).toString(), JsonBean.class);
detail.add(entity);
}
} catch (Exception e) {
e.printStackTrace();
}
return detail;
}
public String getUpdateTime(long lastRefreshTime) {
long timeInterval = System.currentTimeMillis() / 1000 - lastRefreshTime;
String title;
if (timeInterval < 60) {
//时间间隔<60秒
title = App.getContext().getString(R.string.update_just_now);
} else {
//时间间隔>60秒,求分钟数
timeInterval = timeInterval / 60;
if (timeInterval < 60) {
//时间间隔<60分钟
title = timeInterval + App.getContext().getString(R.string.update_minute);
} else {
//时间间隔>60分钟,显示具体时间
@SuppressLint("SimpleDateFormat")
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//获取当前时间
title = formatter.format(lastRefreshTime) + "更新";
}
}
return title;
}
}
|
C#
|
UTF-8
| 986
| 2.59375
| 3
|
[
"MIT"
] |
permissive
|
using GraphQL.Language.AST.Extensions;
using GraphQL.Language.AST.Extensions.Context;
namespace GraphQL.Language.AST.Extensions.Interfaces
{
/// <summary>
/// Builds queries for a given entity type.
/// </summary>
/// <typeparam name="TEntityType">The type of entity for which to build a query.</typeparam>
public interface IQueryBuilder<TEntityType>
{
/// <summary>
/// Builds a query using a baseline query, the GraphQL context, and the current table alias.
/// </summary>
/// <param name="query">The query to augment with additional information/data.</param>
/// <param name="context">The GraphQL selection set for the area being built.</param>
/// <param name="alias">The alias of the entity within the query to use.</param>
/// <returns>A query for the given type.</returns>
SqlQueryContext Build(SqlQueryContext query, IHaveSelectionSet context, string alias);
}
}
|
C#
|
UTF-8
| 781
| 3.484375
| 3
|
[] |
no_license
|
namespace _7_05
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
internal class Program
{
private static void Main()
{
Console.WriteLine("Введите текст: ");
// var str = Console.ReadLine();
var str = "В 17:55 я встал, позавтракал и к 10:77 пошёл на работу.";
Regex reg = new Regex(@"\b([01]?[0-9]|2[0-3]:[0-5][0-9])\b");
Console.WriteLine($"Время в тексте встречается : {reg.Matches(str).Count} раз(а).");
Console.WriteLine("\nPress Enter to exit.");
Console.Read();
}
}
}
|
Python
|
UTF-8
| 874
| 2.75
| 3
|
[] |
no_license
|
__author__ = 'thvoidedline'
from Camera import Camera
from Constants import *
class EditCamera(Camera):
def __init__(self, w, h, limit_x, limit_y):
Camera.__init__(self, w, h)
self.x_speed = 3
self.y_speed = 3
self.limit_x = limit_x
self.limit_y = limit_y
def update(self, mousepos):
if mousepos[X] > self.rect.w * 0.85:
if self.rect.x + self.rect.w < self.limit_x:
self.rect.x += self.x_speed
elif mousepos[X] < self.rect.w * 0.15:
if self.rect.x > 0:
self.rect.x -= self.x_speed
if mousepos[Y] > self.rect.h * 0.85:
if self.rect.y + self.rect.h < self.limit_y:
self.rect.y += self.y_speed
elif mousepos[Y] < self.rect.h * 0.15:
if self.rect.y > 0:
self.rect.y -= self.y_speed
|
PHP
|
UTF-8
| 2,286
| 2.8125
| 3
|
[] |
no_license
|
<?php
/**
* TCAPI Class
* Class used for interacting with Tacticlicks Whitelabel API
* @Author: Jak Giveon <jak@tacticlicks.com>
* Requires: HTTP_REQUEST by Jak Giveon <jak@tacticlicks.com> https://gist.github.com/bdbjack/87ef84f53cf5f5f9e6f448fffb0072ac
*
* Usage example:
* $wl = new TCAPI( 'domain.com', 'XXXXXXXXXXXXXX', 'contact@domain.com', 'somesecuredpassword' );
* $qr = $wl->query( 'someCommand', array( 'var1' => 1, 'var2' => 2 ) );
*/
class TCAPI {
private $domain;
private $token;
private $authtoken;
private $serverDomain;
function __construct( $domain, $token, $username, $password, $server_domain = 'server.tacticlicks.com' ) {
$this->domain = $domain;
$this->token = $token;
$this->serverDomain = $server_domain;
$authquery = HTTP_REQUEST::POST( sprintf( 'http://%s/ws/whitelabel.php', $this->domain ), array(
'email' => $username,
'password' => $password,
'command' => 'login',
'authToken' => $this->token,
) );
if ( 200 == $authquery->code ) {
$this->authtoken = $authquery->data->data->token;
}
}
function query( $command = '', $query = array() ) {
if ( ! can_loop( $query ) ) {
$query = array();
}
$query['command'] = $command;
$query['token'] = $this->authtoken;
$res = HTTP_REQUEST::POST( sprintf( 'http://%s/ws/whitelabel.php', $this->domain ), $query, array(
'Content-Type: application/x-www-form-urlencoded',
), 10 );
add_log_entry( 'tcquery', array(
'query' => serialize( $query ),
'code' => $res->code,
'data' => serialize( $res->data ),
) );
if ( 200 !== $res->code ) {
return false;
}
return $res->data;
}
function project_query( $command = '', $query = array(), $authkey = '' ) {
if ( ! can_loop( $query ) ) {
$query = array();
}
$query['command'] = $command;
$query['token'] = $this->authtoken;
$query['auth_key'] = $authkey;
$res = HTTP_REQUEST::POST( sprintf( 'http://%s/api/project.php', $this->serverDomain ), $query, array(
'Content-Type: application/x-www-form-urlencoded',
), 10 );
add_log_entry( 'tcpquery', array(
'query' => serialize( $query ),
'code' => $res->code,
'data' => serialize( $res->data ),
) );
//if ( 200 !== $res->code ) {
// return false;
//}
return $res->data;
}
}
|
Markdown
|
UTF-8
| 1,184
| 2.5625
| 3
|
[] |
no_license
|
# online-booking-app
frontend/learning_intensive
<p>Интенсив по веб-разработке, на котором мы вместе с вами сверстаем проект для сайта Букинга (выбор и бронирование номеров) и напишем frontend часть под него.</p>
<p>А так же:</p>
+ Познакомимся на практике с CSS препроцессорами.
+ Познакомимся с пакетными- и таск- менеджерами npm и Gulp.
+ Сделаем сборку проекта, компиляцию CSS препроцессоров, autoreload.
+ Сделаем адаптивную верстку.
+ Напишем скрипты для нашего проекта.
<p>.........</p>
**День 1**
* Настройка рабочего окружения. Сборка проекта.
* Работа с Gulp и CSS препроцессором LESS.
**День 2**
* Верстка проекта. Главная и страница номера.
* Форма бронирования.
**День 3**
* Верстка панели администратора.
|
PHP
|
UTF-8
| 3,780
| 2.5625
| 3
|
[] |
no_license
|
<?php
// Include the composer autoload file
include_once "vendor/autoload.php";
// Import the necessary classes
use Carbon\Carbon;
use Philo\Blade\Blade;
$views = __DIR__ . '/views';
$cache = __DIR__ . '/cache';
$blade = new Blade($views, $cache);
$user = new UserAccounts;
$images = new Images;
$capsule = $user->getCapsule();
$patient_details = array();
$plans = array();
$msg = '';
$form_err = false;
$data_err = false;
$date_err = false;
if ($user->isAdmin()) {
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
if (!isset($_POST['date-from']) || strlen($_POST['date-from']) == 0) {
$fr_date = Carbon::create(2014, 1, 1, 12);
} else {
$from_date = filter_var($_POST['date-from'], FILTER_SANITIZE_STRING);
try {
$fr_date = Carbon::createFromFormat('m/d/Y', $from_date);
} catch (Exception $e) {
$date_err = true;
}
}
if (!isset($_POST['date-to']) || strlen($_POST['date-to']) == 0) {
$t_date = Carbon::now();
} else {
$to_date = filter_var($_POST['date-to'], FILTER_SANITIZE_STRING);
try {
$t_date = Carbon::createFromFormat('m/d/Y', $to_date);
} catch (Exception $e) {
$date_err = true;
}
}
$plan_type = $_POST['plan-type'];
$plan_detail = $capsule::table('couponplans')
->where('id', '=', $plan_type)
->first();
if (!empty($plan_detail)) {
$plan_name = $plan_detail['planname'];
} else {
$plan_name = 'all';
}
if (!$date_err) {
//set start and end time of days
$fr_date->hour = 0;
$fr_date->minute = 0;
$fr_date->second = 0;
$t_date->hour = 23;
$t_date->minute = 59;
$t_date->second = 59;
if ($plan_type == 'all') {
$plans = $capsule::table('coupons')
->whereBetween('coupons.created_at', array($fr_date, $t_date))
->join('users', 'coupons.op_id', '=', 'users.id')
->join('couponplans', 'couponplans.planname', '=', 'coupons.coupon_type')
->select(
'coupons.created_at as date',
'coupons.username as username',
'users.username as operator',
'users.id as op_id',
'couponplans.planname as plan',
'couponplans.price as price',
'coupons.created_at as date'
)
->orderby('coupons.created_at')
->get();
} else {
$plans = $capsule::table('coupons')
->where('coupons.coupon_type', '=', $plan_type)
->whereBetween('coupons.created_at', array($fr_date, $t_date))
->join('users', 'coupons.op_id', '=', 'users.id')
->join('couponplans', 'couponplans.planname', '=', 'coupons.coupon_type')
->select(
'coupons.created_at as date',
'coupons.username as username',
'users.username as operator',
'users.id as op_id',
'couponplans.planname as plan',
'couponplans.price as price',
'coupons.created_at as date'
)
->orderby('coupons.created_at')
->get();
}
$data_date = 'from <strong>' . $fr_date->format('Y/M/d') . '</strong> to <strong>' . $t_date->format('Y/M/d') . '</strong> of <strong>' . $plan_name . '</strong> plan';
} else {
$msg = 'date error ' . $from_date . ' ' . $to_date;
}
} else {
$form_err = true;
}
//var_dump($plans);
$disp_frm_year = $fr_date->year . '/' . $fr_date->month . '/' . $fr_date->day;
$disp_to_year = $t_date->year . '/' . $t_date->month . '/' . $t_date->day;
$data = array(
'type' => 'admin',
'site_url' => Config::$site_url,
'page_title' => "Admin Coupon Usage",
'logo_file' => $images->getScreenLogo(),
'name' => 'Administrator',
'msg' => $msg,
'searched_for' => 'plan - ' . $plan_type . ' between dates ' . $disp_frm_year . ' - ' . $disp_to_year,
'plans' => $plans,
'form_err' => $form_err,
);
echo $blade->view()->make('admin.plan-usage', $data);
} else {
header('Location: ' . Config::$site_url . 'logout.php');
}
|
Markdown
|
UTF-8
| 3,848
| 2.9375
| 3
|
[] |
no_license
|
---
description: "How to Make Super Quick Homemade Watermelon Popsicles"
title: "How to Make Super Quick Homemade Watermelon Popsicles"
slug: 18-how-to-make-super-quick-homemade-watermelon-popsicles
date: 2021-11-04T07:27:03.135Z
image: https://img-global.cpcdn.com/recipes/2395a87c8fcd62a5/680x482cq70/watermelon-popsicles-recipe-main-photo.jpg
thumbnail: https://img-global.cpcdn.com/recipes/2395a87c8fcd62a5/680x482cq70/watermelon-popsicles-recipe-main-photo.jpg
cover: https://img-global.cpcdn.com/recipes/2395a87c8fcd62a5/680x482cq70/watermelon-popsicles-recipe-main-photo.jpg
author: Jerry Harris
ratingvalue: 4
reviewcount: 43634
recipeingredient:
- "1/2 Watermelon"
recipeinstructions:
- "Cut the watermelon up into large chunks."
- "Blend all the watermelon until smooth Strain the juice"
- "Pour the strained watermelon puree into the popsicle molds and freeze"
categories:
- Recipe
tags:
- watermelon
- popsicles
katakunci: watermelon popsicles
nutrition: 115 calories
recipecuisine: American
preptime: "PT13M"
cooktime: "PT42M"
recipeyield: "2"
recipecategory: Lunch
---

Hello everybody, I hope you are having an amazing day today. Today, we're going to make a special dish, watermelon popsicles. One of my favorites. This time, I am going to make it a little bit unique. This will be really delicious.
You don't need an expert to tell you that watermelon is just about the most refreshing thing you could possibly eat in the middle of summer. Fresh watermelon, orange juice and pure cane sugar - that's all it takes to make these delicious watermelon popsicles. Who needs store bought popsicles when. These fresh watermelon popsicles are naturally sweet and loaded with juicy watermelon and tangy lime juice that has been blended and frozen into the perfect healthy summer snack.
Watermelon Popsicles is one of the most well liked of current trending foods in the world. It's easy, it's fast, it tastes delicious. It is enjoyed by millions daily. Watermelon Popsicles is something that I've loved my entire life. They're fine and they look wonderful.
To begin with this recipe, we must first prepare a few ingredients. You can have watermelon popsicles using 1 ingredients and 3 steps. Here is how you can achieve it.
<!--inarticleads1-->
##### The ingredients needed to make Watermelon Popsicles:
1. Prepare 1/2 Watermelon
Watermelon Popsicles are refreshing, good for you, and made without any refined sugars. These easy to make popsicles are full of fresh fruit and loved by kids and adults. There is just something about popsicles and summer that go hand and hand. My kids can't get enough and always want a popsicle.
<!--inarticleads2-->
##### Steps to make Watermelon Popsicles:
1. Cut the watermelon up into large chunks.
1. Blend all the watermelon until smooth - Strain the juice
1. Pour the strained watermelon puree into the popsicle molds and freeze
There is just something about popsicles and summer that go hand and hand. My kids can't get enough and always want a popsicle. Learn how to make my Watermelon Popsicles, a combination of Watermelon, Strawberry and Kiwi Fruit made into a Bold and beautiful frozen summer. Watermelon slices plus popsicle sticks makes for an easy recipe and kid friendly. For an easy, fun take on the yummy watermelon slice, insert a popsicle stick into the rind!
So that's going to wrap it up with this special food watermelon popsicles recipe. Thanks so much for your time. I'm sure that you can make this at home. There is gonna be interesting food at home recipes coming up. Remember to bookmark this page on your browser, and share it to your loved ones, colleague and friends. Thank you for reading. Go on get cooking!
|
C#
|
UTF-8
| 667
| 3.140625
| 3
|
[
"MIT"
] |
permissive
|
using System;
namespace Lab2.Cs
{
class Program
{
static void Main(string[] args)
{
const int scramblerValue = 321;
const int startedKey = 1232423;
var scrambler = new Scrambler(scramblerValue, startedKey);
using (var inputStream = Console.OpenStandardInput())
using (var outputStream = Console.OpenStandardOutput())
{
int b;
while ((b = inputStream.ReadByte()) != -1)
{
outputStream.WriteByte(scrambler.Encrypt((byte) b));
}
}
}
}
}
|
Java
|
UTF-8
| 4,716
| 3.015625
| 3
|
[] |
no_license
|
package ua.lviv.lgs;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.Scanner;
public class VerkhovnaRada {
private static VerkhovnaRada verkhovnaRada = new VerkhovnaRada();
private VerkhovnaRada() {
}
public static VerkhovnaRada getVerkhovnaRada() {
return verkhovnaRada;
}
private static ArrayList<Faction> factionArray = new ArrayList<>();
public static ArrayList<Faction> getFactionArray() {
return factionArray;
}
public void addFaction() {
System.out.println("Enter name of faction !");
Scanner scanner = new Scanner(System.in);
String inputFactionName = scanner.next();
getFactionArray().add(new Faction(inputFactionName));
}
public void clearFaction() {
System.out.println("Please enter name of faction ");
Scanner scanner = new Scanner(System.in);
String factionName = scanner.next();
Iterator<Faction> iterator3 = getFactionArray().iterator();
while (iterator3.hasNext()) {
Faction faction = iterator3.next();
if (faction.getNameFaction().equalsIgnoreCase(factionName)) {
faction.clearFaction();
}
}
}
public void allFaction() {
System.out.println("Here we have list of all faction of SupremeCouncil: ");
Iterator<Faction> iterator2 = getFactionArray().iterator();
while (iterator2.hasNext()) {
System.out.println(iterator2.next().getNameFaction());
}
}
public void showFactionByName() {
System.out.println("Enter name of faction !");
Scanner scanner = new Scanner(System.in);
String inputFactionName = scanner.next();
Iterator<Faction> factionIterator = getFactionArray().iterator();
while (factionIterator.hasNext()) {
Faction tempFaction = factionIterator.next();
if (tempFaction.getNameFaction().equals(inputFactionName)) {
System.out.println(tempFaction);
}
}
}
public void addDeputyToFaction() {
System.out.println("Enter name of faction !");
Scanner scanner = new Scanner(System.in);
String inputFactionName = scanner.next();
Iterator<Faction> factionIterator = getFactionArray().iterator();
while (factionIterator.hasNext()) {
Faction tempFaction = factionIterator.next();
if (tempFaction.getNameFaction().equals(inputFactionName)) {
tempFaction.addDeputy();
}
}
}
public void deleteDeputyFromFraction(){
System.out.println("Enter name of deputy:");
Scanner scanner = new Scanner(System.in);
String inputFactionName = scanner.next();
Iterator<Faction> factionIterator = getFactionArray().iterator();
while (factionIterator.hasNext()){
Faction tempFaction = factionIterator.next();
if (tempFaction.getNameFaction().equals(inputFactionName)){
tempFaction.deleteDeputy();
}
}
}
public void showAllGraftersFromFaction(){
System.out.println("Enter name of deputy:");
Scanner scanner = new Scanner(System.in);
String inputFactionName= scanner.next();
Iterator<Faction> factionIterator = getFactionArray().iterator();
while (factionIterator.hasNext()) {
Faction tempFaction = factionIterator.next();
if (tempFaction.getNameFaction().equals(inputFactionName)) {
tempFaction.showGrafters();
}
}
}
public void findTheBestGrafterFromFraction() {
Scanner scanner = new Scanner(System.in);
System.out.println("Enter name of deputy !");
String inputFactionName = scanner.next();
Iterator<Faction> factionIterator = getFactionArray().iterator();
while (factionIterator.hasNext()) {
Faction tempFaction = factionIterator.next();
if (tempFaction.getNameFaction().equals(inputFactionName)) {
tempFaction.maxGrafter();
}
}
}
public void showAllDeputysFromFaction(){
Scanner scanner = new Scanner(System.in);
System.out.println("Enter name f deputy");
String inputFactionName = scanner.next();
Iterator<Faction> factionIterator = getFactionArray().iterator();
while (factionIterator.hasNext()) {
Faction tempFaction = factionIterator.next();
if (tempFaction.getNameFaction().equals(inputFactionName)) {
tempFaction.showAllDeputys();
}
}
}
}
|
Rust
|
UTF-8
| 1,334
| 3.921875
| 4
|
[] |
no_license
|
use world::World;
/// Defines an entity within a world
/// # Arguments
/// * `M` - The type to use for messages between entities
/// # Example
/// ```rust
/// struct Cat {
/// hunger: i64,
/// }
/// impl Entity<String> for Cat {
/// /// Every tick, the cat gets more hungry
/// /// If the cat gets too hungry, it meows
/// fn update(&mut self, world: &World) {
/// self.hunger += 1;
/// if self.hunger >= 100 {
/// self.send_message("MEOW".into());
/// }
/// }
/// /// Cats ignore any incoming messages
/// fn receive_message(&mut self, message: T) {}
/// }
/// ```
pub trait Entity<M> {
/// Updates the entity based on the world around it
/// # Arguments
/// * `world` - the world the entity exists in
fn update(&mut self, world: &World<M>);
/// Sends a message to the world. The world will choose which entities to
/// forward the message to
/// # Arguments
/// * `message` - The message being sent to all other entities
/// * `world` - The world the entity exists in
fn send_message(&self, message: M, world: &mut World<M>) {
world.receive_message(message)
}
/// Handler for receiving a message
/// # Arguments
/// * `message` - The message to receive
fn receive_message(&mut self, message: M);
}
|
Markdown
|
UTF-8
| 7,507
| 3.015625
| 3
|
[] |
no_license
|
## cookie
```js
var paras = document.getElementsByTagName("p");
for (var i = 0; i < paras.length; i++)
var title_text = paras[i].getAttribute("title");
if (title_text) alert((title_text));
```
*创建一个函数来检查是否已设置 cookie:*
```js
function getCookie(c_name) {
if (document.cookie.length > 0) {
c_start = document.cookie.indexOf(c_name + "=")
if (c_start != -1) {
c_start = c_start + c_name.length + 1
c_end = document.cookie.indexOf(";", c_start)
if (c_end == -1) c_end = document.cookie.length
return unescape(document.cookie.substring(c_start, c_end))
}
}
return ""
}
```
*创建一个可在 `cookie` 变量中存储访问者姓名的函数:参数存有 cookie 的名称、值以及过期天数。*
```js
function setCookie(c_name, value, expiredays) {
var exdate = new Date()
exdate.setDate(exdate.getDate() + expiredays)
document.cookie = c_name + "=" + escape(value) +
((expiredays == null) ? "" : ";expires=" + exdate.toGMTString())//将天数转换为有效的日期,然后,我们将 cookie 名称、值及其过期日期存入 document.cookie 对象。
}
//如果 cookie 已设置,则显示欢迎词,否则显示提示框来要求用户输入名字。
function checkCookie() {
username = getCookie('username')
if (username != null && username != "") {
alert('Welcome again ' + username + '!')
}
else {
username = prompt('Please enter your name:', "")
if (username != null && username != "") {
setCookie('username', username, 365)
}
}
}
//创建
document.cookie = "user1=test1";
document.cookie = "user2=test2";
document.cookie = "user3=test3";
//有效期
var dates = new Date();
dates.setDate(dates.getDate() + 3);
document.cookie = "password123;expires=" + dates;
//获取cookie
var cookies = document.cookie;
document.write(cookies);
割cookie
var cookiesArr = cookies.split("; ");
document.write(cookiesArr);
for (var i=0;i<cookiesArr.length;i++) {
var cookiesEach = cookiesArr[i].split("=");
console.log(cookiesEach);
}
```
#### cookie封装
```js
function getCookie(key) {
var CookieArr = document.cookie.split("; ");
for (var i = 0; i < CookieArr.length; i++) {
var CookieEach = CookieArr[i].split("=");
if (CookieEach[0] == key) {
return CookieEach[1];
}
}
return false;
}
console.log(getCookie("user1"));
//删除cookie
var date2=new Date();
date2.setDate(date2.getDate()-1);
document.cookie="password=123;expires="+date2;
```
## cookie
## `CookieUtil()`
```js
let CookieUtil = {
get: function (name) {
let cookieName = encodeURIComponent(name) + "=",
cookieStart = document.cookie.indexOf(cookieName),
cookieValue = null;
if (cookieStart > -1) {
let cookieEnd = document.cookie.indexOf(";", cookieStart); //查找分号
if (cookieEnd == -1) {
cookieEnd = document.cookie.length; //没有分号的说明是最后一个值
}
cookieValue = decodeURIComponent(document.cookie.substring(cookieStart + cookieName.length, cookieEnd))
}
return cookieValue;
},
set: function (name, value, expires, path, domain, secure) { //设置Cookie值
let cookieText = encodeURIComponent(name) + "=" + encodeURIComponent(value);
if (expires instanceof Date) {
cookieText += "; expires=" + expires.toMTString();
}
if (path) {
cookieText += "; path" + path;
}
if (domain) {
cookieText += "; domain" + domain;
}
if (secure) {
cookieText += "; secure";
}
document.cookie = cookieText;
},
unset: function (name, path, domain, secure) {
this.set(name, "", new Date(0), path, domain, secure);
}
};
//使用
//设置Cookie
CookieUtil.set("name", "Beats0");
CookieUtil.set("book", "JavaScript");
//读取Cookie
console.log(CookieUtil.get("name")); // Beats0
console.log(CookieUtil.get("book")); // JavaScript
//删除Cookie
// CookieUtil.unset("name");
// CookieUtil.unset("book");
// //设置Cookie的路径,域,失效日期
CookieUtil.set("name", "Beats0", "/book/project", "www.github.com", new Date("November 20, 2018"));
```
## 子Cookie
## `SubCookieUtil()`
```js
let SubCookieUtil = {
get: function (name, subName) {
let subCookies = this.getAllResponseHeaders(name);
if (subCookies) {
return subCookies[subName];
} else {
return null;
}
},
getAll: function (name) {
let cookieName = encodeURIComponent(name) + "=",
cookieStart = document.cookie.indexOf(cookieName),
cookieValue = null,
cookieEnd,
subCookies,
i,
len,
parts,
result = {};
if (cookieStart > -1) {
let cookieEnd = document.cookie.indexOf(";", cookieStart); //查找分号
if (cookieEnd == -1) {
cookieEnd = document.cookie.length; //没有分号的说明是最后一个值
}
cookieValue = document.cookie.substring(cookieStart + cookieName.length, cookieEnd);
if (cookieValue.length > 0) {
subCookies = cookieValue.split("&");
for (i = 0, len = subCookies.length; i < len; i++) {
parts = subCookies[i].split("=");
result[decodeURIComponent(parts[0])] = decodeURIComponent(parts[1]);
}
return result;
}
}
return null;
},
//其他代码
};
//调用
//假设document.cookie=data=name=Beats0&Booke=JavaScript
//取得全部cookie
let data = SubCookieUtil.getAll("data");
console.log(data.name);
console.log(data.book);
//逐个获取子cookie
console.log(SubCookieUtil.get("data", "name"));
console.log(SubCookieUtil.get("data", "book"));
```
#### 设置子Cookie
## `SubCookieUtil()`
```js
let SubCookieUtil = {
set: function (name, subName, value, expiress, path, domain, secure) {
let subcookies = this.getAll(name) || {};
subcookies[subName] = value;
this.setAll(name, subcookies, expiress, path, domain, secure);
},
setAll: function (name, subookies, value, expiress, path, domain, secure) {
let cookieText = encodeURIComponent(name) + "=",
subcookieParts = new Array(),
subName;
for (subName in subookies) {
if (subName.length > 0 && subookies.hasOwnProperty(subName)) {
subcookieParts.push(encodeURIComponent(subName) + "=" + encodeURIComponent(subookies[subName]));
}
}
if (cookieParts.length > 0) {
cookieText += subcookieParts.join("&");
if (expires instanceof Date) {
cookieText += "; expires=" + expires.toMTString();
}
if (path) {
cookieText += "; path" + path;
}
if (domain) {
cookieText += "; domain" + domain;
}
if (secure) {
cookieText += "; secure";
}
} else {
cookieText += "; expires" + (new Date(0)).toGMTString();
}
document.cookie = cookieText;
},
//更多代码
};
```
|
Markdown
|
UTF-8
| 1,528
| 3.046875
| 3
|
[
"MIT"
] |
permissive
|
# UKSML Student Group Member List Scraper
Made to scrape University of Nottingham Students' Union Society Member Lists
Scraper submits a post request to get all members of society and then uses cheriojs to get names and ID.
Returns an array of objects that looks like the following:
```JavaScript
[
{
name: '<First Name> <Last Name>',
id: <studentID>,
},
...
]
```
## Usage
Using the scraper requires some configuration.
```JavaScript
import fetchMembers from 'ukmsl-student-group-member-scraper';
import config from './config';
fetchMembers(config)
.then(members => /* do something */)
.catch(err => /* handle error */);
```
## Config Object
The configuration object is structured as follows
```JavaScript
{
baseUrl: '',
domain: '',
groupId: '',
ASPNET_SessionId: '',
ASPXAUTH: '',
AntiXsrfToken: '',
formBody: '',
}
```
- **baseUrl** is the url of the website with the protocol.
- **domain** is the website's domain name without protocol (for cokies)
- **groupId** is the ID of the student group which can be found in the URL when viewiing members
- **ASPNET_SessionId** coresponds to the `ASP.NET_SessionId` cookie set on the website
- **ASPXAUTH** coresponds to the `.ASPXAUTH` cookie set on the website
- **AntiXsrfToken** coresponds to the `__AntiXsrfToken` cookie set on the website
- **formBody** is the source form data on the post request when you can see **all** members
Note that most of this data is sensitive and can let anyone access your account on a UKSML website.
|
JavaScript
|
UTF-8
| 1,515
| 2.671875
| 3
|
[] |
no_license
|
const robot = require('robotjs');
module.exports = class Actions {
constructor() {
this.screenSize = robot.getScreenSize();
}
handleActions(action) {
switch(action.type) {
case 'move': {
var screenX = this.screenSize.width * action.screenX / action.width,
screenY = this.screenSize.height * action.screenY / action.height;
robot.moveMouse(screenX, screenY);
}; break;
case 'click': {
var button = 'left';
switch (action.button) {
case 'left': button = 'left'; break;
case 'middle': button = 'middle'; break;
case 'right': button = 'right'; break;
}
if (action.double == 'true') {
robot.mouseClick(button, true);
} else {
robot.mouseClick(button, false);
}
}; break;
case 'scroll': {
var x = action.x, y = action.y;
if (process.platform != 'win32') {
x = 1 * (+action.x / Math.abs(+action.x));
y = 1 * (+action.y / Math.abs(+action.y));
}
robot.scrollMouse(x, y);
}; break;
case 'down': {
robot.mouseToggle('down');
}; break;
case 'up': {
robot.mouseToggle('up');
}; break;
// key
case 'tap': {
if (action.modifier) {
robot.keyTap(action.key, action.modifier.split(','));
} else {
robot.keyTap(action.key);
}
}; break;
}
}
}
|
Java
|
UTF-8
| 202
| 2.03125
| 2
|
[] |
no_license
|
package Algoriths.dp;
public class lisLongestIncSubSequence {
public static int lis(int arr[], int n) {
if(n == 1) {
return 1;
}
int res, max_ending_here = 1;
}
}
|
Markdown
|
UTF-8
| 731
| 3.03125
| 3
|
[] |
no_license
|
---
title: "[JAVA]백준11654번 아스키코드"
excerpt: "[Bronze 5] Basic."
categories:
- Algorithm
tags:
- Basic
---
[문제](https://www.acmicpc.net/problem/11654)는 다음과 같다.
오늘은 백준11654번 아스키코드 문제를 풀어보도록 하자. JAVA의 입력을 연습하기 위해 풀어보았다. 아스키코드를 출력해주려면 System.in.read()로
한 개의 바이트만 읽고 아스키코드로 변환할 수 있다.
```java
[코드]
package BaekJoon;
import java.io.IOException;
public class Main_11654 {
public static void main(String[] args) throws IOException {
int c = System.in.read();
System.out.println(c);
}
}
```
|
C++
|
UTF-8
| 6,550
| 2.890625
| 3
|
[
"MIT"
] |
permissive
|
/**
*
*
*/
#ifndef _KEHGENERAL_ENCDECBUFFER_H
#define _KEHGENERAL_ENCDECBUFFER_H 1
#include "core/reference.h"
// The kehEncDecBuffer is meant to simplify the task of encoding/decoding data into low level
// bytes (PoolByteArray). The thing is, the ideal is to remove the variant header bytes from
// properties, which incorporate 4 bytes for each one.
// This class deals with a sub-set of the types given by Godot scripting and was primarily meant
// to be used with the networking addon, but this can be useful in other scenarios, like a saving
// system, for example.
//
// Now, why this trouble? Variables in GDScript take more bytes than we normally expect. Each one
// contains an additional set of 4 bytes representing the "header", which is basically indicating
// to Godot which type is actually held in memory. Some types may even bring further overhead
// and directly using them through the network may not necessarily be the best option.
//
// Now there is one very special case there. Unfortunately we don't have unsigned integers within
// GDScript. This brings a somewhat not so fun "limitation" to how numbers are represented.
//
// The maximum positive number that can be represented with an unsigned 32 bit integer is 4294967295.
// However, because GDScript only deals with signed numbers, the limit here would be 2147483647.
// But we can have bigger positive numbers in GDScript, only that behind the scenes Godot uses 64
// bit integers. In other words, if we directly send a hash number (32 bit), the result will be that
// 12 bytes will be used instead of just 8 (or the desired 4 bytes).
//
// This class allows "unsigned integers" to be stored in the PoolByteArray using the desired
// 4 bytes, provided the value stays within the boundary.
class kehEncDecBuffer : public Reference
{
GDCLASS(kehEncDecBuffer, Reference);
private:
const uint32_t MAX_UINT = 0xFFFFFFFF;
// Bytes will be stored here.
PoolByteArray m_buffer;
// The reading position
uint32_t m_rindex;
// Generic function to append bytes into the internal buffer
void append_bytes(const uint8_t* in, const uint32_t count);
// Generic function to encode raw bytes into the given buffer
void encode_bytes(const uint8_t* ptr, const uint32_t count, const int offset);
// Read the specified number of bytes from the internal buffer. Automatically moves the reading index
void decode_bytes(const int count, uint8_t* output);
protected:
static void _bind_methods();
public:
// If true is returned then the reading index is at a position not past the last byte of the internal PoolByteArray
bool has_read_data() const;
// Obtain current amount of bytes stored within the internal buffer
int get_current_size() const;
// Append a boolean into the buffer array
void write_bool(bool value);
// Rewrite a boolean at the given byte position
void rewrite_bool(bool value, int at);
// Read a boolean from the internal buffer. Automatically moves the reading index
bool read_bool();
// Append an integer into the buffer array
void write_int(int value);
// Rewrite an integer at the given byte position
void rewrite_int(int value, int at);
// Read an integer from the internal buffer. Automatically moves the reading index
int read_int();
// Append a floating point into the buffer array
void write_float(float value);
// Rewrite a floating point at the given byte position
void rewrite_float(float value, int at);
// Read a float from the internal buffer. Automatically moves the reading index
float read_float();
// Append a Vector2 into the buffer array
void write_vector2(const Vector2& value);
// Rewrite a Vector2 at the given byte position
void rewrite_vector2(const Vector2& value, int at);
// Read a vector2 from the internal buffer. Automatically moves the reading index
Vector2 read_vector2();
// Append a Rect2 into the buffer array
void write_rect2(const Rect2& value);
// Rewrite a Rect2 at the given byte position
void rewrite_rect2(const Rect2& value, int at);
// Read a Rect2 from the internal buffer. Automatically moves the reading index
Rect2 read_rect2();
// Append a Vector3 into the buffer array
void write_vector3(const Vector3& value);
// Rewrite a Vector3 at the given byte position
void rewrite_vector3(const Vector3& value, int at);
// Read a Vector3 from the internal buffer. Automatically moves the reading index
Vector3 read_vector3();
// Append a Quaternion into the buffer array
void write_quat(const Quat& value);
// Rewrite a Quaternion at the given byte position
void rewrite_quat(const Quat& value, int at);
// Read a Quaternion from the internal buffer. Automatically moves the reading index
Quat read_quat();
// Append a Color into the buffer array
void write_color(const Color& value);
// Rewrite a Color at the given byte position
void rewrite_color(const Color& value, int at);
// Read a Color from the internal buffer. Automatically moves the reading index
Color read_color();
// Append an unsigned 32 bits integer into the buffer array
void write_uint(uint32_t value);
// Rewrite an unsigned 32 bits integer at the given byte position
void rewrite_uint(uint32_t value, int at);
// Read an unsigned 32 bits integer from the internal buffer. Automatically moves the reading index
uint32_t read_uint();
// Append a single byte into the buffer array
void write_byte(int value);
// Rewrite a single byte at the given position
void rewrite_byte(int value, int at);
// Read a single byte from the internal buffer. Automatically moves the reading index
uint8_t read_byte();
// Append an unsigned 16 bits integer into the buffer array
void write_ushort(int value);
// Rewrite an unsigned 16 bits integer at the given byte position
void rewrite_ushort(int value, int at);
// Read an unsigned 16 bites integer from the internal buffer. Automatically moves the reading index
uint16_t read_ushort();
// Append a String into the buffer array.
// Note that because strings may have different sizes rewriting them is not supported
void write_string(const String& value);
// Read a String from the internal buffer. Automatically moves teh reading index
String read_string();
/// Setters/Getters
void set_buffer(const PoolByteArray& b);
PoolVector<uint8_t> get_buffer() const { return m_buffer; }
kehEncDecBuffer();
};
#endif
|
Java
|
UHC
| 951
| 3.015625
| 3
|
[] |
no_license
|
package ws2.java2.controller;
import java.util.Arrays;
import ws2.java2.entity.*;
public class VehicleManager {
Vehicle[] vehicleArr;
public VehicleManager() {
vehicleArr = new Vehicle[6];
vehicleArr[0] = new Airplane("7472", 1300, 300, true, 4);
vehicleArr[1] = new Car("ҳŸ32", 180, 45, true, 20);
vehicleArr[2] = new Car("", 200, 40, true, 11);
vehicleArr[3] = new Car("33", 250, 80, true, 50);
vehicleArr[4] = new Ship("ŸŸ2224", 500, 30, true, 400);
vehicleArr[5] = new Ship("Ǵн444444", 800, 200, true, 500);
}
public void sortByModelName() {
Arrays.sort(vehicleArr);
for(Vehicle s : vehicleArr) {
s.displayInfo();
}
}
public void displayVehicles(String title) {
System.out.println(title);
for (int inx = 0 ; inx < vehicleArr.length ; inx++) {
vehicleArr[inx].displayInfo();
vehicleArr[inx].setAvailable(true);
}
System.out.println();
}
}
|
Java
|
UTF-8
| 1,199
| 2.078125
| 2
|
[] |
no_license
|
package com.sell.model;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.sell.enums.ProductStatusEnum;
import com.sell.util.EnumUtil;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.RequiredArgsConstructor;
import java.io.Serializable;
import java.math.BigDecimal;
import java.util.Date;
/**
* Created by huhaoran on 2018/11/18 0018.
*/
@Data
@NoArgsConstructor
@AllArgsConstructor
public class ProductInfo implements Serializable {
private static final long serialVersionUID = 1726244617103013908L;
private String productId; //随机字符串主键
private String productName;//名字
private BigDecimal productPrice;//单价
private Integer productStock;//库存
private String productDescription;//描述
private String productIcon;//小图
private Integer productStatus = ProductStatusEnum.UP.getCode();//状态 0正常,1下架
private Integer categoryType;//类目编号
private Date createTime;
private Date updateTime;
@JsonIgnore
public ProductStatusEnum getProductStatusEnum() {
return EnumUtil.getByCode(productStatus, ProductStatusEnum.class);
}
}
|
Java
|
UTF-8
| 2,706
| 2.09375
| 2
|
[] |
no_license
|
package com.example.saransh.myapplication;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.support.v7.widget.Toolbar;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;
public class Status extends Fragment implements Tab1.OnFragmentInteractionListener,Tab2.OnFragmentInteractionListener,Tab3.OnFragmentInteractionListener {
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
// return inflater.inflate(R.layout.fragment_status,null);
View v=inflater.inflate(R.layout.fragment_status, container,false);
getActivity().setTitle("STATUS");
Toolbar toolbar = (Toolbar) v.findViewById(R.id.toolbar);
final TabLayout tabLayout=v.findViewById(R.id.tablayout);
tabLayout.addTab(tabLayout.newTab().setText("IP.PHONE"));
tabLayout.addTab(tabLayout.newTab().setText("DSLAM"));
tabLayout.addTab(tabLayout.newTab().setText("ALL"));
tabLayout.setTabGravity(TabLayout.GRAVITY_FILL);
final ViewPager viewpager=(ViewPager) v.findViewById(R.id.viewpager) ;
final Pager adapter=new Pager(this.getActivity().getSupportFragmentManager(),3);
viewpager.setAdapter(adapter);
// tabLayout.setupWithViewPager(viewpager);
viewpager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
@Override
public void onTabSelected(TabLayout.Tab tab) {
viewpager.setCurrentItem(tab.getPosition());
}
@Override
public void onTabUnselected(TabLayout.Tab tab) {
}
@Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
return v;
}
@Override
public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
view.findViewById(R.id.tablayout).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Toast.makeText(getActivity(),"You Are Inside Status",Toast.LENGTH_SHORT).show();
}
});
}
@Override
public void onFragmentInteraction(Uri uri) {
}
}
|
SQL
|
UTF-8
| 1,176
| 3.40625
| 3
|
[] |
no_license
|
CREATE DATABASE Pets;
USE Pets;
CREATE TABLE Clinicas
(
idClinica INT PRIMARY KEY IDENTITY,
RazaoSocial VARCHAR(80) NOT NULL,
Cnpj INT NOT NULL,
Endereco VARCHAR(80) NOT NULL
);
CREATE TABLE TiposPets
(
idTipoPet INT PRIMARY KEY IDENTITY,
Descricao VARCHAR(50) NOT NULL
);
CREATE TABLE Racas
(
idRaca INT PRIMARY KEY IDENTITY,
Descricao VARCHAR(50) NOT NULL,
idTipoPet INT FOREIGN KEY REFERENCES TiposPets(idTipoPet)
);
CREATE TABLE Veterinarios
(
idVeterinario INT PRIMARY KEY IDENTITY,
Nome VARCHAR(50) NOT NULL,
Crmv INT NOT NULL,
idClinica INT FOREIGN KEY REFERENCES Clinicas(idClinica)
);
CREATE TABLE Donos
(
idDono INT PRIMARY KEY IDENTITY,
Nome VARCHAR(50) NOT NULL
);
CREATE TABLE Pets
(
idPet INT PRIMARY KEY IDENTITY,
Nome VARCHAR(50) NOT NULL,
dataNascimento DATETIME NOT NULL,
idRaca INT FOREIGN KEY REFERENCES Racas(idRaca),
idDono INT FOREIGN KEY REFERENCES Donos(idDono)
);
CREATE TABLE Atendimentos
(
idAtendimento INT PRIMARY KEY IDENTITY,
Descricao VARCHAR(50) NOT NULL,
dataAtendimento DATETIME NOT NULL,
idVeterinario INT FOREIGN KEY REFERENCES Veterinarios(idVeterinario),
idPet INT FOREIGN KEY REFERENCES Pets(idPet)
);
|
Markdown
|
UTF-8
| 1,778
| 3.703125
| 4
|
[] |
no_license
|
# [unrated] 왼쪽 오른쪽 - 181890
[문제 링크](https://school.programmers.co.kr/learn/courses/30/lessons/181890)
### 성능 요약
메모리: 33.4 MB, 시간: 0.05 ms
### 구분
코딩테스트 연습 > 코딩 기초 트레이닝
### 채점결과
Empty
### 문제 설명
<p>문자열 리스트 <code>str_list</code>에는 "u", "d", "l", "r" 네 개의 문자열이 여러 개 저장되어 있습니다. <code>str_list</code>에서 "l"과 "r" 중 먼저 나오는 문자열이 "l"이라면 해당 문자열을 기준으로 왼쪽에 있는 문자열들을 순서대로 담은 리스트를, 먼저 나오는 문자열이 "r"이라면 해당 문자열을 기준으로 오른쪽에 있는 문자열들을 순서대로 담은 리스트를 return하도록 solution 함수를 완성해주세요. "l"이나 "r"이 없다면 빈 리스트를 return합니다.</p>
<hr>
<h5>제한사항</h5>
<ul>
<li>1 ≤ <code>str_list</code>의 길이 ≤ 20</li>
<li><code>str_list</code>는 "u", "d", "l", "r" 네 개의 문자열로 이루어져 있습니다.</li>
</ul>
<hr>
<h5>입출력 예</h5>
<table class="table">
<thead><tr>
<th>str_list</th>
<th>result</th>
</tr>
</thead>
<tbody><tr>
<td>["u", "u", "l", "r"]</td>
<td>["u", "u"]</td>
</tr>
<tr>
<td>["l"]</td>
<td>[]</td>
</tr>
</tbody>
</table>
<hr>
<h5>입출력 예 설명</h5>
<p>입출력 예 #1</p>
<ul>
<li>"r"보다 "l"이 먼저 나왔기 때문에 "l"의 왼쪽에 있는 문자열들을 담은 리스트인 ["u", "u"]를 return합니다.</li>
</ul>
<p>입출력 예 #2</p>
<ul>
<li>"l"의 왼쪽에 문자열이 없기 때문에 빈 리스트를 return합니다.</li>
</ul>
> 출처: 프로그래머스 코딩 테스트 연습, https://programmers.co.kr/learn/challenges
|
Java
|
UTF-8
| 1,688
| 2.609375
| 3
|
[
"MIT"
] |
permissive
|
package com.cym5240.pis;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
public class MenuListAdapter extends BaseAdapter {
// Declare Variables
Context context;
String[] mTitle;
String[] mSubTitle;
int[] mIcon;
LayoutInflater inflater;
public MenuListAdapter(Context context, String[] title, String[] subtitle,
int[] icon) {
this.context = context;
this.mTitle = title;
this.mSubTitle = subtitle;
this.mIcon = icon;
}
@Override
public int getCount() {
return mTitle.length;
}
@Override
public Object getItem(int position) {
return mTitle[position];
}
@Override
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
// Declare Variables
TextView txtTitle;
TextView txtSubTitle;
ImageView imgIcon;
inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View itemView = inflater.inflate(R.layout.drawer_list_item, parent,
false);
// Locate the TextViews in drawer_list_item.xml
txtTitle = (TextView) itemView.findViewById(R.id.title);
txtSubTitle = (TextView) itemView.findViewById(R.id.subtitle);
// Locate the ImageView in drawer_list_item.xml
imgIcon = (ImageView) itemView.findViewById(R.id.icon);
// Set the results into TextViews
txtTitle.setText(mTitle[position]);
txtSubTitle.setText(mSubTitle[position]);
// Set the results into ImageView
imgIcon.setImageResource(mIcon[position]);
return itemView;
}
}
|
Markdown
|
UTF-8
| 4,286
| 2.953125
| 3
|
[] |
no_license
|
---
layout: page
title: 抽屉式导航
permalink: navigation-drawer.html
---
# 抽屉式导航 #
**抽屉式导航是Google应用程序中一种常见的模式。抽屉导航从左侧滑出,它遵循列表的关键设计线和标准。**
<img src="images/patterns_navdrawer_metrics1.png"width="360"/>
**排版样式**
字体,字号,颜色:
1. Roboto Medium, 14sp, #FFFFFF
2. Roboto Regular, 14sp, #FFFFFF
3. 列表项: Roboto Medium, 14sp, 87% #000000
4. 副标题: Roboto Medium, 14sp, 54% #000000。对其到16dp关键设计线。
<img src="images/patterns_navdrawer_metrics2.png"width="360"/>
**垂直关键设计线和水平间距**
图标的垂直关键设计线是距侧边导航左右边缘均为16dp的设计线,并且图标颜色为不透明度为54%的黑色(#000000)。
与图标或头像对应的文本内容距导航左侧边缘72dp。
侧边导航的宽度等于屏幕的宽度减去actionbar的高度,或者是距屏幕右侧边缘56dp。侧边导航的最大宽度是5倍于标准增量(手机上是56dp,平板上是64dp)。
在手机上使用16dp的水平距离,在平板则上使用24dp。
<img src="images/patterns_navdrawer_metrics3.png"width="360"/>
**垂直间距**
1. 24dp
2. 56dp
3. 8dp
4. 48dp
在每个列表组的顶部和底部添加8dp的间距。一个例外的情况是,当这个列表组有一个副标题的时候顶部不需添加8dp的间距,因为副标题包含有他自己的间距设定。
##**高度**##
抽屉导航的占据了屏幕的全部高度,并且抽屉导航在状态栏的下方。抽屉下方所有的东西会覆盖一层阴影(scrim)而变暗。阴影下的所有内容依然是可见的。
<img src="images/patterns_navdrawer_elevation1.png"width="360"/>
**Android上的抽屉导航**
## **选择状态** ##
当列表中的一项被选择后,那一项会变为应用程序的主色调,或者是不透明度为100%的黑色(#000000),以此来凸显此项被选中。触摸纹波也是一种高亮,进一步凸显列表项被选中。
如果这种颜色触摸纹波/高亮不能与程序主色调形成足够的对比,那么就使用的程序主色的暗色调。
<img src="images/patterns_navdrawer_selection1.png"width="360"/>
<img src="images/patterns_navdrawer_selection2.png"width="360"/>
<img src="images/patterns_navdrawer_selection3.png"width="360"/>
<img src="images/patterns_navdrawer_selection4.png"width="360"/>
<img src="images/patterns_navdrawer_selection5.png"width="360"/>
<img src="images/patterns_navdrawer_selection6.png"width="360"/>
##**分隔线**##
在导航抽屉里所有分割线都是完全在抽屉面板内部。此外,在分隔线上方和下方均有8dp的间距。
<img src="images/patterns_navdrawer_dividers1.png"width="360"/>
**上下文**
<img src="images/patterns_navdrawer_dividers2.png"width="360"/>
**8 dp 垂直间距**
##**滚动**##
抽屉导航可以像任何普通视图一样滚动。
<img src="images/patterns_navdrawer_scrolling1.png"width="360"/>
<img src="images/patterns_navdrawer_scrolling2.png"width="360"/>
##**设置和支持**##
设置和支持位于滚动列表的底部,与列表内容的其余部分排成列。
如果在导航抽屉中的内容列表很长,设置和支持这两项可以被钉在导航抽屉的底部(译者:非列表底部)较高一层的视图上。该视图层(显示设置和支持的视图层)只有在列表显示顶部的时候才显示;任何在其他的位置的滚动会立即使该视图层消失,并且把设置和支持这两项加到列表底部,与列表内容的其余部分排成列。当关闭和重新打开抽屉式导航的时候,抽屉导航保持其滚动到的位置。(译者:其实现在的Play商店和Gmail并没有严格按照这个标准来,并没有把设置和支持钉在抽屉导航底部的上一层。从Inbox上倒是可以看到一点影子。2014-12-10)
<img src="images/patterns_navdrawer_settings1.png"width="360"/>
<img src="images/patterns_navdrawer_settings2.png"width="360"/>
如果列表不用滚动,那么设置和支持项会在列表底部显示,而且不用被钉在底部。
<img src="images/patterns_navdrawer_settings3.png"width="360"/>
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.