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 |
|---|---|---|---|---|---|---|---|
Python | UTF-8 | 401 | 2.828125 | 3 | [] | no_license |
def special_reverse_string(txt):
rev=[]
temp=[]
result=""
for char in txt:
temp.append(char)
for i in temp:
if i!=" ":
rev.insert(0,i.lower())
for j in range(len(temp)):
if temp[j].isupper():
rev[j]=rev[j].upper()
if temp[j]==" ":
rev.insert(j," ")
for i in rev:
result+=i
return result
|
Java | UTF-8 | 18,551 | 1.554688 | 2 | [] | no_license | package com.creativeshare.agriculturalstockexchange.activities_fragments.home_activity.fragments.fragments_more;
import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.location.Location;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Looper;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.Fragment;
import com.creativeshare.agriculturalstockexchange.R;
import com.creativeshare.agriculturalstockexchange.activities_fragments.home_activity.activity.HomeActivity;
import com.creativeshare.agriculturalstockexchange.models.PlaceGeocodeData;
import com.creativeshare.agriculturalstockexchange.models.UserModel;
import com.creativeshare.agriculturalstockexchange.preferences.Preferences;
import com.creativeshare.agriculturalstockexchange.remote.Api;
import com.creativeshare.agriculturalstockexchange.share.Common;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.common.api.PendingResult;
import com.google.android.gms.common.api.ResultCallback;
import com.google.android.gms.common.api.Status;
import com.google.android.gms.location.*;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.*;
import com.google.maps.android.ui.IconGenerator;
import com.squareup.picasso.Picasso;
import java.io.File;
import java.io.IOException;
import java.util.Locale;
import io.paperdb.Paper;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
public class Fragment_Upgrade extends Fragment implements GoogleApiClient.OnConnectionFailedListener, GoogleApiClient.ConnectionCallbacks, LocationListener, OnMapReadyCallback {
private HomeActivity homeActivity;
private final String gps_perm = Manifest.permission.ACCESS_FINE_LOCATION;
private final int gps_req = 22;
private final int loc_req = 1225;
private double lat = 0.0, lng = 0.0;
private float zoom = 15.6f;
private GoogleApiClient googleApiClient;
private LocationRequest locationRequest;
private LocationCallback locationCallback;
private Location location;
private boolean stop = false;
private Marker marker;
private GoogleMap mMap;
private Preferences preferences;
private UserModel userModel;
private String cuurent_language, formatedaddress;
private ImageView back_arrow;
private FrameLayout fl1;
private ImageView icon1, image1;
private final int IMG1 = 1;
private Uri uri = null;
private ImageView back;
private final String read_permission = Manifest.permission.READ_EXTERNAL_STORAGE;
private EditText edt_name;
private Button bt_upgrde;
public static Fragment_Upgrade newInstance() {
return new Fragment_Upgrade();
}
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_upgrade, container, false);
updateUI();
initView(view);
CheckPermission();
return view;
}
private void updateUI() {
SupportMapFragment fragment = (SupportMapFragment) getChildFragmentManager().findFragmentById(R.id.fragment_map);
fragment.getMapAsync(this);
}
private void AddMarker(double lat, double lng) {
this.lat = lat;
this.lng = lng;
if (marker == null) {
IconGenerator iconGenerator = new IconGenerator(homeActivity);
iconGenerator.setBackground(null);
View view = LayoutInflater.from(homeActivity).inflate(R.layout.search_map_icon, null);
iconGenerator.setContentView(view);
marker = mMap.addMarker(new MarkerOptions().position(new LatLng(lat, lng)).icon(BitmapDescriptorFactory.fromBitmap(iconGenerator.makeIcon())).anchor(iconGenerator.getAnchorU(), iconGenerator.getAnchorV()).draggable(true));
mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(lat, lng), zoom));
} else {
marker.setPosition(new LatLng(lat, lng));
mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(lat, lng), zoom));
}
}
private void initView(View view) {
homeActivity = (HomeActivity) getActivity();
preferences = Preferences.getInstance();
userModel = preferences.getUserData(homeActivity);
Paper.init(homeActivity);
cuurent_language = Paper.book().read("lang", Locale.getDefault().getLanguage());
back_arrow = view.findViewById(R.id.arrow_back);
fl1 = view.findViewById(R.id.fl1);
icon1 = view.findViewById(R.id.image_icon_upload);
image1 = view.findViewById(R.id.image);
edt_name = view.findViewById(R.id.edt_name);
bt_upgrde = view.findViewById(R.id.bt_upgrade);
if (cuurent_language.equals("en")) {
back_arrow.setRotation(180);
}
back_arrow.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
homeActivity.Back();
}
});
fl1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Check_ReadPermission(IMG1);
}
});
bt_upgrde.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
checkdata();
}
});
}
private void checkdata() {
Common.CloseKeyBoard(homeActivity,edt_name);
String name = edt_name.getText().toString();
if (TextUtils.isEmpty(name) || (lat == 0.0 || lng == 0.0) || uri == null || formatedaddress == null) {
if (TextUtils.isEmpty(name)) {
edt_name.setError(getResources().getString(R.string.field_req));
}
if (lat == 0.0 || lng == 0.0 || uri == null) {
Toast.makeText(homeActivity, getResources().getString(R.string.field_req), Toast.LENGTH_LONG).show();
}
// Log.e("kklkkl",formatedaddress);
} else {
if (formatedaddress == null) {
getGeoData(lat, lng);
}
// Log.e("kklkkl", formatedaddress);
upgrade(name, uri, lat, lng, formatedaddress);
}
}
private void upgrade(String name, Uri uri, double lat, double lng, String formatedaddress) {
// Log.e("kkkl", formatedaddress);
final Dialog dialog = Common.createProgressDialog(homeActivity, getString(R.string.wait));
dialog.show();
RequestBody user_part = Common.getRequestBodyText(userModel.getUser_id());
RequestBody lat_part = Common.getRequestBodyText(lat + "");
RequestBody long_part = Common.getRequestBodyText(lng + "");
RequestBody address_part = Common.getRequestBodyText(formatedaddress);
RequestBody name_part = Common.getRequestBodyText(name);
MultipartBody.Part image_part = Common.getMultiPart(homeActivity, uri, "commercial_register");
// Log.e("Error", lat + " " + lng + " " + userModel.getUser_id() + " " + name + " " + formatedaddress + " " + uri);
Api.getService().upgrademarket(user_part, lat_part, long_part, name_part, address_part, image_part).enqueue(new Callback<UserModel>() {
@Override
public void onResponse(Call<UserModel> call, Response<UserModel> response) {
dialog.dismiss();
// dialog.dismiss();
if (response.isSuccessful()) {
// Common.CreateSignAlertDialog(adsActivity,getResources().getString(R.string.suc));
// preferences = Preferences.getInstance();
// Log.e("ss", response.body().getUser_type());
preferences.create_update_userdata(homeActivity, response.body());
// Common.CreateSignAlertDialog(homeActivity, getResources().getString(R.string.suc));
homeActivity.RefreshActivity(cuurent_language);
} else {
try {
Common.CreateSignAlertDialog(homeActivity, getResources().getString(R.string.failed));
Log.e("Error", response.code() + response.message().toString() + "" + response.errorBody() + response.raw() + response.body() + response.headers() + response.errorBody().contentType().toString());
}
catch (Exception e){
}
}
}
@Override
public void onFailure(Call<UserModel> call, Throwable t) {
dialog.dismiss();
try {
Toast.makeText(homeActivity, getString(R.string.something), Toast.LENGTH_SHORT).show();
Log.e("Error", t.getMessage());
}
catch (Exception e){
}
}
});
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 1255) {
if (resultCode == Activity.RESULT_OK) {
startLocationUpdate();
}
}
if (requestCode == IMG1 && resultCode == Activity.RESULT_OK && data != null) {
uri = data.getData();
icon1.setVisibility(View.GONE);
File file = new File(Common.getImagePath(homeActivity, uri));
Picasso.with(homeActivity).load(file).fit().into(image1);
// UpdateImage(uri);
}
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode == gps_req && grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
initGoogleApiClient();
}
if (requestCode == IMG1) {
if (grantResults.length > 0) {
if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
select_photo(IMG1);
} else {
Toast.makeText(homeActivity, getString(R.string.perm_image_denied), Toast.LENGTH_SHORT).show();
}
}
}
}
private void CheckPermission() {
if (ActivityCompat.checkSelfPermission(homeActivity, gps_perm) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(homeActivity, new String[]{gps_perm}, gps_req);
} else {
initGoogleApiClient();
}
}
private void initGoogleApiClient() {
googleApiClient = new GoogleApiClient.Builder(homeActivity)
.addOnConnectionFailedListener(this)
.addConnectionCallbacks(this)
.addApi(LocationServices.API)
.build();
googleApiClient.connect();
}
private void intLocationRequest() {
locationRequest = new LocationRequest();
locationRequest.setFastestInterval(1000 * 60 * 2);
locationRequest.setInterval(1000 * 60 * 2);
LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder()
.addLocationRequest(locationRequest);
PendingResult<LocationSettingsResult> result = LocationServices.SettingsApi.checkLocationSettings(googleApiClient, builder.build());
result.setResultCallback(new ResultCallback<LocationSettingsResult>() {
@Override
public void onResult(@NonNull LocationSettingsResult result) {
Status status = result.getStatus();
switch (status.getStatusCode()) {
case LocationSettingsStatusCodes.SUCCESS:
startLocationUpdate();
break;
case LocationSettingsStatusCodes.RESOLUTION_REQUIRED:
try {
status.startResolutionForResult(homeActivity, 1255);
} catch (Exception e) {
}
break;
case LocationSettingsStatusCodes.SETTINGS_CHANGE_UNAVAILABLE:
Log.e("not available", "not available");
break;
}
}
});
}
@Override
public void onConnected(@Nullable Bundle bundle) {
intLocationRequest();
}
@Override
public void onConnectionSuspended(int i) {
if (googleApiClient != null) {
googleApiClient.connect();
}
}
@Override
public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {
}
@Override
public void onLocationChanged(Location location) {
this.location = location;
lng = location.getLongitude();
lat = location.getLatitude();
getGeoData(lat, lng);
AddMarker(lat, lng);
if (googleApiClient != null) {
googleApiClient.disconnect();
}
if (locationCallback != null) {
LocationServices.getFusedLocationProviderClient(homeActivity).removeLocationUpdates(locationCallback);
}
}
@SuppressLint("MissingPermission")
private void startLocationUpdate() {
locationCallback = new LocationCallback() {
@Override
public void onLocationResult(LocationResult locationResult) {
onLocationChanged(locationResult.getLastLocation());
}
};
LocationServices.getFusedLocationProviderClient(homeActivity)
.requestLocationUpdates(locationRequest, locationCallback, Looper.myLooper());
}
@Override
public void onMapReady(GoogleMap googleMap) {
if (googleMap != null) {
mMap = googleMap;
mMap.setMapStyle(MapStyleOptions.loadRawResourceStyle(homeActivity, R.raw.maps));
mMap.setTrafficEnabled(false);
mMap.setBuildingsEnabled(false);
mMap.setIndoorEnabled(true);
mMap.setOnMapClickListener(new GoogleMap.OnMapClickListener() {
@Override
public void onMapClick(LatLng latLng) {
lat = latLng.latitude;
lng = latLng.longitude;
getGeoData(lat, lng);
AddMarker(lat, lng);
}
});
}
}
private void getGeoData(final double lat, final double lng) {
String location = lat + "," + lng;
Api.getService("https://maps.googleapis.com/maps/api/")
.getGeoData(location, cuurent_language, getString(R.string.map_api_key))
.enqueue(new Callback<PlaceGeocodeData>() {
@Override
public void onResponse(Call<PlaceGeocodeData> call, Response<PlaceGeocodeData> response) {
if (response.isSuccessful() && response.body() != null) {
if (response.body().getResults().size() > 0) {
formatedaddress = response.body().getResults().get(0).getFormatted_address().replace("Unnamed Road,", "");
// address.setText(formatedaddress);
//AddMarker(lat, lng);
//place_id = response.body().getCandidates().get(0).getPlace_id();
// Log.e("kkk", formatedaddress);
}
} else {
Log.e("error_code", response.errorBody() + " " + response.code());
try {
Log.e("error_code", response.errorBody().string());
} catch (IOException e) {
e.printStackTrace();
}
}
}
@Override
public void onFailure(Call<PlaceGeocodeData> call, Throwable t) {
try {
// Toast.makeText(activity, getString(R.string.something), Toast.LENGTH_LONG).show();
} catch (Exception e) {
}
}
});
}
private void Check_ReadPermission(int img_req) {
if (ContextCompat.checkSelfPermission(homeActivity, read_permission) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(homeActivity, new String[]{read_permission}, img_req);
} else {
select_photo(img_req);
}
}
private void select_photo(int img1) {
Intent intent;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
intent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
intent.addFlags(Intent.FLAG_GRANT_PERSISTABLE_URI_PERMISSION);
if (img1 == 2) {
intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);
}
} else {
intent = new Intent(Intent.ACTION_GET_CONTENT);
if (img1 == 2) {
intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);
}
}
intent.putExtra(Intent.EXTRA_LOCAL_ONLY, true);
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
intent.setType("image/*");
startActivityForResult(intent, img1);
}
} |
C# | GB18030 | 4,479 | 2.890625 | 3 | [] | no_license | using System;
using System.Collections.Generic;
using System.Text;
using System.Data;
using System.Collections;
namespace ϵͳ
{
/// <summary>
/// SQL װ
/// </summary>
public class ClsSQLFactory
{
ϵͳ.ClsDataBase clsSQL = ϵͳ.ClsDataBaseFactory.Instance();
private static volatile ClsSQLFactory clsSQLFactory = null;
private static object lockHelper = new object();
public static ClsSQLFactory Instance()
{
if (clsSQLFactory == null)
{
lock (lockHelper)
{
if (clsSQLFactory == null)
{
clsSQLFactory = new ClsSQLFactory();
}
}
}
return clsSQLFactory;
}
/// <summary>
/// װSQL
/// </summary>
/// <param name="sTableName"></param>
/// <param name="dt2">ֵ</param>
/// <returns></returns>
public ArrayList sExecInsertSQL(string sTableName, DataTable dt2)
{
ArrayList aList = new ArrayList();
try
{
string sSQL = "select * from information_schema.columns where table_name = '" + sTableName + "'";
DataTable dt1 = clsSQL.ExecQuery(sSQL);
if (dt1.Rows.Count < 1)
{
throw new Exception("δҵݿṹϢ");
}
for (int i = 0; i < dt2.Rows.Count; i++)
{
bool bFisrt = true;
string sSQL1 = "insert into " + dt1.Rows[0]["dtName"].ToString().Trim() + "(";
string sSQL2 = "values(";
for (int j = 0; j < dt1.Rows.Count; j++)
{
string sColName = dt1.Rows[i]["column_name"].ToString().Trim();
int iValueType = iAddCol(dt1.Rows[i]["data_type"].ToString().ToLower().Trim());
object oValue = dt2.Rows[j][sColName];
if (oValue == null || iValueType == 0)
{
continue;
}
if (bFisrt)
{
sSQL1 = sSQL1 + oValue;
if (iValueType == 2)
{
sSQL2 = sSQL2 + "'" + oValue.ToString().Trim() + "'";
}
if (iValueType == 1)
{
sSQL2 = sSQL2 + oValue.ToString().Trim();
}
bFisrt = false;
}
else
{
sSQL1 = sSQL1 + "," + oValue;
if (iValueType == 2)
{
sSQL2 = sSQL2 + ",'" + oValue.ToString().Trim() + "'";
}
if (iValueType == 1)
{
sSQL2 = sSQL2 + "," + oValue.ToString().Trim();
}
}
}
sSQL1 = sSQL1 + ")";
sSQL2 = sSQL2 + ")";
aList.Add(sSQL1 + sSQL2);
}
}
catch(Exception ee)
{
throw new Exception("װSQLʧܣԭ£\n " + ee.Message);
}
return aList;
}
/// <summary>
/// жǷֶΣ0 ֶΣ1 ֶΣ2 ֶַ
/// </summary>
/// <returns></returns>
private int iAddCol(string sDataType)
{
int i = 0;
switch (sDataType)
{
case "int":
case "bit":
case "float":
case "decimal":
case "smallint":
case "numeric":
case "money":
i = 1;
break;
default:
i = 2;
break;
}
return i;
}
}
}
|
PHP | UTF-8 | 1,981 | 2.515625 | 3 | [
"MIT"
] | permissive | <?php
declare(strict_types=1);
namespace Tests;
use Kwai\Core\Infrastructure\Database\Connection;
use Kwai\Core\Infrastructure\Dependencies\DatabaseDependency;
use Kwai\Modules\Users\Domain\User;
use Kwai\Modules\Users\Domain\UserEntity;
use Kwai\Modules\Users\Infrastructure\Repositories\UserDatabaseRepository;
use Phinx\Config\Config;
use Phinx\Migration\Manager;
use Symfony\Component\Console\Input\StringInput;
use Symfony\Component\Console\Output\NullOutput;
trait DatabaseTrait
{
protected ?Connection $db = null;
public function hasDatabase(): bool
{
return $this->db !== null;
}
public function isDatabaseDriver(string $driver): bool
{
if ($this->db === null) {
return false;
}
return $this->db->getDriver() === $driver;
}
public function withDatabase(): self
{
static $migrated = false;
$this->db = depends('kwai.db', DatabaseDependency::class);
if (!$migrated) {
// Migrate the database, if needed.
$configArray = require(__DIR__ . '/../src/phinx.php');
$configArray['environments']['test']['connection'] = $this->db->getPDO();
$configArray['environments']['test']['name'] = 'kwai';
$manager = new Manager(
new Config($configArray),
new StringInput(' '),
new NullOutput()
);
$manager->migrate('test');
$migrated = true;
}
return $this;
}
public function withUser(): UserEntity
{
$this->withDatabase();
$repo = new UserDatabaseRepository($this->db);
$user = $repo->getById(1);
return new UserEntity(
$user->id(),
new User(
uuid: $user->getUuid(),
emailAddress: $user->getEmailAddress(),
username: $user->getUsername(),
admin: true
)
);
}
}
|
Python | UTF-8 | 3,246 | 2.84375 | 3 | [] | no_license | ## Can be used for Front End
from flask import Flask, request
import pandas as pd
import numpy as np
import pickle
import flasgger
from flasgger import Swagger
app = Flask(__name__)
Swagger(app)
pickle_in = open('model.pkl','rb')
classifier = pickle.load(pickle_in)
@app.route('/')
def Welcome():
return "Welcome to the Magesh's Prediction"
@app.route('/predict')
def predict_():
"""Let's predict Using Values
This is using docstrings for specifications.
---
parameters:
- name: vect_30
in: query
type: number
required: true
- name: vect_1
in: query
type: number
required: true
- name: vect_25
in: query
type: number
required: true
- name: vect_2
in: query
type: number
required: true
- name: duration
in: query
type: number
required: true
- name: vect_5
in: query
type: number
required: true
- name: vect_6
in: query
type: number
required: true
- name: vect_10
in: query
type: number
required: true
- name: vect_27
in: query
type: number
required: true
- name: vect_123
in: query
type: number
required: true
- name: vect_19
in: query
type: number
required: true
- name: vect_61
in: query
type: number
required: true
- name: vect_29
in: query
type: number
required: true
- name: vect_16
in: query
type: number
required: true
- name: vect_24
in: query
type: number
required: true
responses:
200:
description: The output values
"""
vect_30 = request.args.get('vect_30')
vect_1 = request.args.get('vect_1')
vect_25 = request.args.get('vect_25')
vect_2 = request.args.get('vect_2')
duration = request.args.get('duration')
vect_5 = request.args.get('vect_5')
vect_6 = request.args.get('vect_6')
vect_10 = request.args.get('vect_10')
vect_27 = request.args.get('vect_27')
vect_123 = request.args.get('vect_123')
vect_19 = request.args.get('vect_19')
vect_61 = request.args.get('vect_61')
vect_29 = request.args.get('vect_29')
vect_16 = request.args.get('vect_16')
vect_24 = request.args.get('vect_24')
prediction = classin.predict([[vect_30, vect_1, vect_25, vect_2, duration, vect_5, vect_6, vect_10, vect_27,
vect_123, vect_19, vect_61, vect_29, vect_16, vect_24]])
return str(prediction)
@app.route('/predict_file',methods = ["POST"])
def predict_test_file():
"""Let's Predict using Files
This is using docstrings for specifications.
---
parameters:
- name: file
in: formData
type: file
required: true
responses:
200:
description: The output values
"""
test = pd.read_csv(request.files.get('file'))
prediction = classifier.predict(test)
return 'The prediction for the test FIle is' + str(list(prediction))
if __name__=='__main__':
app.run() |
Java | UTF-8 | 1,392 | 2.28125 | 2 | [] | no_license | package f4.web.entity;
import javax.persistence.*;
import java.io.Serializable;
import java.util.Date;
@Table(name = "score")
public class Score implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
@Column
private Integer studentId;
@Column
private String lessonName;
@Column
private Double score;
@Column
private Date time;
@Column
private String content;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public Integer getStudentId() {
return studentId;
}
public void setStudentId(Integer studentId) {
this.studentId = studentId;
}
public String getLessonName() {
return lessonName;
}
public void setLessonName(String lessonName) {
this.lessonName = lessonName == null ? null : lessonName.trim();
}
public Double getScore() {
return score;
}
public void setScore(Double score) {
this.score = score;
}
public Date getTime() {
return time;
}
public void setTime(Date time) {
this.time = time;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content == null ? null : content.trim();
}
} |
C++ | UTF-8 | 2,709 | 2.71875 | 3 | [] | no_license | #pragma once
#include "RendererManager.h"
#include "CameraPositionComponent.h"
#include "InputComponent.h"
#include "WindowHandle.h"
#define CELL_SIZE_FLOAT 16.f
#define CELL_SIZE int(16)
enum CellStance
{
EMPTY = 0,
MINE = 1
};
enum CellStance2
{
NONE = 0,
FLAG = 1,
QUESTION_MARK = 2,
EXPLODE = 3,
REVEALED = 4
};
struct CellS
{
bool hover;
CellStance stance;
CellStance2 stance2;
int8_t mines{};
void reveal(CellS matrix[CELL_SIZE][CELL_SIZE], int x, int y)
{
if (stance2 == CellStance2::NONE)
{
if (stance == CellStance::MINE)
{
stance2 = CellStance2::EXPLODE;
}
else
{
stance2 = CellStance2::REVEALED;
if (mines == 0)
{
{
if (x > 0)
{
if (y > 0)
{
matrix[x - 1][y - 1].reveal(matrix, x - 1, y - 1);
matrix[x][y - 1].reveal(matrix, x, y - 1);
matrix[x - 1][y].reveal(matrix, x - 1, y);
if (y < (CELL_SIZE - 1))
{
matrix[x - 1][y + 1].reveal(matrix, x - 1, y + 1);
matrix[x][y + 1].reveal(matrix, x, y + 1);
}
if (x < (CELL_SIZE - 1))
{
matrix[x + 1][y - 1].reveal(matrix, x + 1, y - 1);
matrix[x + 1][y].reveal(matrix, x + 1, y);
if (y < (CELL_SIZE - 1))
matrix[x + 1][y + 1].reveal(matrix, x + 1, y + 1);
}
}
else
{
matrix[x - 1][y].reveal(matrix, x - 1, y);
matrix[x - 1][y + 1].reveal(matrix, x - 1, y + 1);
matrix[x][y + 1].reveal(matrix, x, y + 1);
if (x < (CELL_SIZE - 1))
{
matrix[x + 1][y + 1].reveal(matrix, x + 1, y + 1);
matrix[x + 1][y].reveal(matrix, x + 1, y);
}
}
}
else
{
if (y > 0)
{
matrix[x][y - 1].reveal(matrix, x, y - 1);
matrix[x + 1][y - 1].reveal(matrix, x + 1, y - 1);
matrix[x + 1][y].reveal(matrix, x + 1, y);
if (y < (CELL_SIZE - 1))
{
matrix[x + 1][y + 1].reveal(matrix, x + 1, y + 1);
matrix[x][y + 1].reveal(matrix, x, y + 1);
}
}
else
{
matrix[x][y + 1].reveal(matrix, x, y + 1);
matrix[x + 1][y + 1].reveal(matrix, x + 1, y + 1);
matrix[x + 1][y].reveal(matrix, x + 1, y);
}
}
}
}
}
}
}
void flag()
{
if (stance2 == CellStance2::NONE)
stance2 = CellStance2::FLAG;
else if (stance2 == CellStance2::FLAG)
stance2 = CellStance2::NONE;
}
};
class GameRenderer : RendererManager,RenderTargetSize,InputComponent, WindowHandle
{
public:
GameRenderer();
~GameRenderer();
void Update();
void Render();
private:
CellS matrix[CELL_SIZE][CELL_SIZE];
};
|
Markdown | UTF-8 | 2,742 | 3.015625 | 3 | [] | no_license | # How Crypto Is Taxed in the US: A Taxpayer’s Dilemma ...
###### 2019-04-01 19:04
## A taxpayer’s dilemma
Let's imagine a potential 2019 taxpayer sitting in front of his tax advisor and feeling embarrassed to tell him that he had lost 90 percent of a 100K investment in cryptocurrencies when the cryptocurrency markets experienced a downturn during 2018, with leading cryptocurrencies like Bitcoin (BTC) and Ethereum (ETH) down 80 percent or more.
The tax advisor assured the taxpayer that this would give rise to a taxable event only if he sold, exchanged or donated his cryptocurrency during 2018, and that these things would need to be reported on his U.S. tax return — noting, however, that holding cryptocurrencies would not give rise to a taxable event but may give rise to tax-reporting requirements if the cryptocurrencies were held in a foreign financial account.
Tax-reporting requirements would arise if the taxpayer held these cryptocurrencies in a foreign financial account and if mandatory financial thresholds were met under Foreign Bank Account Report (FBAR) and Foreign Account Tax Compliance Act (FATCA) reporting requirements, according to a letter from the American Institute of Certified Public Accountants (AICPA) to the Internal Revenue Service (IRS).
Specific information should be given in Part V. Noncompliance with FATCA could subject a taxpayer to taxes, severe penalties in excess of the unreported foreign assets, and exclusion from access to U.S. markets, which could include a regulated cryptocurrency derivatives clearing market.
The donation will be tax deductible for the U.S. individual donor as follows:
- If the donor held the cryptocurrency as a capital asset for more than a year, the donor will be able to deduct the fair market value of the gift up to 30 percent of their adjusted gross income (AGI).
A taxpayer can use his cryptocurrency investment capital losses to offset gains and deduct the difference on his tax return, up to $3,000 per year.
However, taxpayers who have neglected to pay their cryptocurrency-related U.S. taxes and who file their applicable U.S. tax returns should do so by April 15, 2019 to avoid interest, penalties, and even jail time for tax evasion or, worse, for tax fraud, since “cryptocurrencies are a key part of the Joint Chiefs of Global Tax Enforcement’s work,” Don Fort, chief of the Criminal Investigation Department at the IRS said at a Joint Chiefs of Global Tax Enforcement meeting in Amsterdam, citing the risk that such coins are used in the U.S. to avoid paying taxes.
[Original source](https://cointelegraph.com/news/how-crypto-is-taxed-in-the-us-a-taxpayers-dilemma)
 |
Python | UTF-8 | 16,163 | 2.828125 | 3 | [
"BSD-3-Clause",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | """
Functions for ground state generation for star geometries via imaginary time evolution
"""
import mpnum as mp
from tmps.star.itime.factory import from_hi as propagator_from_hi, from_hamiltonian as propagator_from_hamiltonian
from tmps.utils.random import get_random_mpa
def _propagation(propagator, nof_steps, verbose):
"""
Performs imaginary time evolution of the passed propagator.
"""
if verbose:
print('Starting propagtion')
for step in range(nof_steps):
propagator.evolve()
if verbose:
print('Step {:d}:'.format(step+1))
print(propagator.psi_t.ranks)
if verbose:
print('Propagation finished')
return propagator.psi_t, propagator.info()
def _convergence(propagator, start, step, stop, err, verbose):
"""
Performs imaginary time evolution of the passed propagator until a convergence condition is met
(absolute l2-norm difference between the states from successive timesteps is small enough)
"""
nof_steps = stop
if verbose:
print('Starting propagtion')
for i in range(start):
propagator.evolve()
if verbose:
print('Step {:d}:'.format(i+1))
print(propagator.psi_t.ranks)
last_psi_t = propagator.psi_t.copy()
check = None
for i in range(1, (stop - start)+1):
propagator.evolve()
if i % step == 0:
check = mp.normdist(last_psi_t, propagator.psi_t)
if check < err:
if verbose:
print('Step {:d}:'.format(i+start))
print(propagator.psi_t.ranks)
nof_steps = i+start
break
else:
last_psi_t = propagator.psi_t.copy()
if verbose:
print('Step {:d}:'.format(i+start))
print(propagator.psi_t.ranks)
if nof_steps == stop:
print('Did not reach convergence in ' + str(nof_steps) + ' steps!')
info = propagator.info()
info['nof_steps'] = nof_steps
info['error'] = check
if verbose:
print('Propagation finished')
return propagator.psi_t, info
def get_propagator(beta, mpa_type, system_index, h_site, h_bond, rank=1, state_compression_kwargs=None,
op_compression_kwargs=None, psi_0_compression_kwargs=None, second_order_trotter=False,
seed=102):
"""
Returns the propagator object for imaginary time evolution ground state generation
:param beta: Decay coefficient
:param mpa_type: Type of mpa to evolve (allowed are 'mps', 'pmps' and 'mpo')
:param system_index: Index of the system site in the chain (place of the system site operator in h_site)
:param h_site: local operators of hamiltonian as list or tuple
:param h_bond: iterator over bond (coupling) operators of the Hamiltonian
:param rank: Rank of the random initial state (default is 1)
:param state_compression_kwargs: Arguments for mps compression after each second order trotter step U(tau_i).
(see real time evolution factory function for details)
:param op_compression_kwargs: Arguments for trotter step operator precompression (see real time evolution
factory function for details)
:param second_order_trotter: Uses second order trotter steps for the propagation
:param seed: Seed for the initial random state
:param psi_0_compression_kwargs: Optional compression kwargs for the initial state (see real time evolution
factory function for details)
"""
tau = -beta
axis_0 = []
for index, site in enumerate(h_site):
assert site.shape[0] == site.shape[1]
axis_0.append(site.shape[0])
psi_0 = get_random_mpa(mpa_type, axis_0, seed=seed, rank=rank)
return propagator_from_hamiltonian(psi_0, mpa_type, system_index, h_site, h_bond, tau=tau,
state_compression_kwargs=state_compression_kwargs,
op_compression_kwargs=op_compression_kwargs,
psi_0_compression_kwargs=psi_0_compression_kwargs,
second_order_trotter=second_order_trotter, t0=0,
track_trace=False)
def get_propagator_from_hi(beta, mpa_type, system_index, dims, hi_list, rank=1, state_compression_kwargs=None,
op_compression_kwargs=None, second_order_trotter=False, seed=102,
psi_0_compression_kwargs=None):
"""
Returns the propagator object for imaginary time evolution ground state generation
:param beta: Decay coefficient
:param mpa_type: Type of mpa to evolve (allowed are 'mps', 'pmps' and 'mpo')
:param system_index: Index of the system site in the chain (place of the system site operator in the hi_list)
:param dims: Physical dimensions in the chain
:param hi_list: List/Tuple of all terms in the Hamiltonian H = sum_i hi, where hi is local to one bond
:param rank: Rank of the random initial state (default is 1)
:param state_compression_kwargs: Arguments for mps compression after each second order trotter step U(tau_i).
(see real time evolution factory function for details)
:param op_compression_kwargs: Arguments for trotter step operator precompression (see real time evolution
factory function for details)
:param second_order_trotter: Uses second order trotter steps for the propagation
:param seed: Seed for the initial random state
:param psi_0_compression_kwargs: Optional compression kwargs for the initial state (see real time evolution
factory function for details)
"""
tau = -beta
psi_0 = get_random_mpa(mpa_type, dims, seed=seed, rank=rank)
return propagator_from_hi(psi_0, mpa_type, system_index, hi_list, tau=tau,
state_compression_kwargs=state_compression_kwargs,
op_compression_kwargs=op_compression_kwargs,
psi_0_compression_kwargs=psi_0_compression_kwargs,
second_order_trotter=second_order_trotter, t0=0,
track_trace=False)
def from_hamiltonian(beta, nof_steps, mpa_type, system_index, h_site, h_bond, rank=1, state_compression_kwargs=None,
op_compression_kwargs=None, psi_0_compression_kwargs=None, second_order_trotter=False, seed=102,
verbose=False):
"""
Generates a ground state of a given Hamiltonian.
:param beta: Decay coefficient
:param nof_steps: number of steps for the imaginary time evolution
:param mpa_type: Type of mpa to evolve (allowed are 'mps', 'pmps' and 'mpo')
:param system_index: Index of the system site in the chain (place of the system site operator in h_site)
:param h_site: local operators of hamiltonian as list or tuple
:param h_bond: iterator over bond (coupling) operators of the Hamiltonian
:param nof_steps: number of steps for the imaginary time evolution
:param rank: Rank of the random initial state (default is 1)
:param state_compression_kwargs: Arguments for mps compression after each second order trotter step U(tau_i).
(see real time evolution factory function for details)
:param op_compression_kwargs: Arguments for trotter step operator precompression (see real time evolution
factory function for details)
:param second_order_trotter: Uses second order trotter steps for the propagation
:param seed: Seed for the initial random state
:param psi_0_compression_kwargs: Optional compression kwargs for the initial state (see real time evolution
factory function for details)
:param verbose: If updates on the time evolution should be given via stdout
:return: ground state from the imaginary time evolution,
info dict from the propagation
"""
ground = get_propagator(beta, mpa_type, system_index, h_site, h_bond, rank=rank,
state_compression_kwargs=state_compression_kwargs,
op_compression_kwargs=op_compression_kwargs,
psi_0_compression_kwargs=psi_0_compression_kwargs,
second_order_trotter=second_order_trotter, seed=seed)
return _propagation(ground, nof_steps, verbose)
def from_convergence(beta, mpa_type, system_index, h_site, h_bond, rank=1, state_compression_kwargs=None,
op_compression_kwargs=None, psi_0_compression_kwargs=None, second_order_trotter=False, seed=102,
start=10, step=1, eps=1e-7, stop=1000, verbose=False):
"""
Generates a ground state for a given Hamiltonian using |psi_t - psi_(t+dt)|_2 as convergence measure.
:param beta: Decay coefficient
:param mpa_type: Type of mpa to evolve (allowed are 'mps', 'pmps' and 'mpo')
:param system_index: Index of the system site in the chain (place of the system site operator in h_site)
:param h_site: local operators of hamiltonian as list or tuple
:param h_bond: iterator over bond (coupling) operators of the Hamiltonian
:param rank: Rank of the random initial state (default is 1)
:param state_compression_kwargs: Arguments for mps compression after each second order trotter step U(tau_i).
(see real time evolution factory function for details)
:param op_compression_kwargs: Arguments for trotter step operator precompression (see real time evolution
factory function for details)
:param second_order_trotter: Uses second order trotter steps for the propagation
:param seed: Seed for the initial random state
:param psi_0_compression_kwargs: Optional compression kwargs for the initial state (see real time evolution
factory function for details)
:param verbose: If updates on the time evolution should be given via stdout
:param start: Number of steps before any convergence measure is checked
:param step: Number of steps between convergence measure is checked
:param stop: Maximum number of steps before convergence is aborted
:param eps: Maximum absolute (and relative) allowed value for the convergence measure
:return: ground state from the imaginary time evolution as mps,
info dict from the propagation
"""
assert stop > start
ground = get_propagator(beta, mpa_type, system_index, h_site, h_bond, rank=rank,
state_compression_kwargs=state_compression_kwargs,
op_compression_kwargs=op_compression_kwargs,
psi_0_compression_kwargs=psi_0_compression_kwargs,
second_order_trotter=second_order_trotter, seed=seed)
return _convergence(ground, start, step, stop, eps, verbose)
def from_hi(beta, nof_steps, mpa_type, system_index, dims, hi_list, rank=1, state_compression_kwargs=None,
op_compression_kwargs=None, psi_0_compression_kwargs=None, second_order_trotter=False, seed=102,
verbose=False):
"""
Generates a ground state of a given Hamiltonian.
:param beta: Decay coefficient
:param nof_steps: number of steps for the imaginary time evolution
:param mpa_type: Type of mpa to evolve (allowed are 'mps', 'pmps' and 'mpo')
:param system_index: Index of the system site in the chain (place of the system site operator in the hi_list)
:param dims: Physical dimensions in the chain
:param hi_list: List/Tuple of all terms in the Hamiltonian H = sum_i hi, where hi is local to one bond
:param rank: Rank of the random initial state (default is 1)
:param nof_steps: number of steps for the imaginary time evolution
:param rank: Rank of the random initial state (default is 1)
:param state_compression_kwargs: Arguments for mps compression after each second order trotter step U(tau_i).
(see real time evolution factory function for details)
:param op_compression_kwargs: Arguments for trotter step operator precompression (see real time evolution
factory function for details)
:param second_order_trotter: Uses second order trotter steps for the propagation
:param seed: Seed for the initial random state
:param psi_0_compression_kwargs: Optional compression kwargs for the initial state (see real time evolution
factory function for details)
:param verbose: If updates on the time evolution should be given via stdout
:return: ground state from the imaginary time evolution,
info dict from the propagation
"""
ground = get_propagator_from_hi(beta, mpa_type, system_index, dims, hi_list, rank=rank,
state_compression_kwargs=state_compression_kwargs,
op_compression_kwargs=op_compression_kwargs,
psi_0_compression_kwargs=psi_0_compression_kwargs,
second_order_trotter=second_order_trotter, seed=seed)
return _propagation(ground, nof_steps, verbose)
def from_hi_convergence(beta, mpa_type, system_index, dims, hi_list, rank=1, state_compression_kwargs=None,
op_compression_kwargs=None, psi_0_compression_kwargs=None, second_order_trotter=False, seed=102,
start=10, step=1, eps=1e-7, stop=1000, verbose=False):
"""
Generates a ground state for a given Hamiltonian using |psi_t - psi_(t+dt)|_2 as convergence measure.
:param beta: Decay coefficient
:param mpa_type: Type of mpa to evolve (allowed are 'mps', 'pmps' and 'mpo')
:param system_index: Index of the system site in the chain (place of the system site operator in the hi_list)
:param dims: Physical dimensions in the chain
:param hi_list: List/Tuple of all terms in the Hamiltonian H = sum_i hi, where hi is local to one bond
:param rank: Rank of the random initial state (default is 1)
:param state_compression_kwargs: Arguments for mps compression after each second order trotter step U(tau_i).
(see real time evolution factory function for details)
:param op_compression_kwargs: Arguments for trotter step operator precompression (see real time evolution
factory function for details)
:param second_order_trotter: Uses second order trotter steps for the propagation
:param seed: Seed for the initial random state
:param psi_0_compression_kwargs: Optional compression kwargs for the initial state (see real time evolution
factory function for details)
:param verbose: If updates on the time evolution should be given via stdout
:param start: Number of steps before any convergence measure is checked
:param step: Number of steps between convergence measure is checked
:param stop: Maximum number of steps before convergence is aborted
:param eps: Maximum absolute (and relative) allowed value for the convergence measure
:return: ground state from the imaginary time evolution as mps,
info dict from the propagation
"""
assert stop > start
ground = get_propagator_from_hi(beta, mpa_type, system_index, dims, hi_list, rank=rank,
state_compression_kwargs=state_compression_kwargs,
op_compression_kwargs=op_compression_kwargs,
psi_0_compression_kwargs=psi_0_compression_kwargs,
second_order_trotter=second_order_trotter, seed=seed)
return _convergence(ground, start, step, stop, eps, verbose)
|
C++ | UTF-8 | 404 | 2.6875 | 3 | [] | no_license | #include<iostream>
using namespace std;
main(){
static int C[3] = {1000, 500, 100}, ans[3];
int a, b;
while(1){
cin >> a >> b;
if ( a== 0 && b == 0 ) break;
b -= a;
for ( int i = 0; i < 3; i++ ){
ans[3-i-1] = b/C[i];
b = b%C[i];
}
for ( int i = 0; i < 3; i++ ){
if (i) cout << " ";
cout << ans[i];
}
cout << endl;
}
}
|
C | UTF-8 | 294 | 3.546875 | 4 | [] | no_license | /*
* chapter_2_04.c
*
* Created on: Mar 29, 2019
* Author: Shane
*/
#include <stdio.h>
#include <string.h>
void chapter_2_04(char *a, char *c) {
int i, j;
for (i = j = 0; a[i] != '\0'; i++) {
if (a[i] != c[i]) {
a[j++] = a[i];
}
}
a[j++] = '\0';
printf("%s\n", a);
}
|
JavaScript | UTF-8 | 842 | 2.578125 | 3 | [] | no_license | const express = require('express')
const path = require('path')
const app = express()
const members = require('./data/members')
app.use(express.static(path.join(__dirname, 'public')))
app.use(express.static(path.join(__dirname, 'data')))
var artist = members.artist
console.log(artist[1].name)
app.get('/api/artist', (req, res)=>{
const artist = members.artist
let data = " "
for(let i = 0; i< artist.length; i++){
data += `<h4>${artist[i].name}</h4>`
}
res.send(data)
})
app.get('/api/justin/', (req, res)=>{
const offMyFace = members.offMyFace[0].tracks
let arr = ""
for(let i = 0; i < offMyFace.length; i++){
arr += `<h4>${offMyFace[i]}<h4/>`
}
res.send(arr);
})
const PORT = 5000
app.listen(PORT, ()=>{
console.log(`running in port http://localhost:${PORT}/`);
}) |
C++ | UTF-8 | 1,952 | 2.9375 | 3 | [] | no_license | #include<iostream>
using namespace std;
#include<vector>
int n, m, d, s;
int basket[50][100];
int dx[] = {0,-1,-1,-1,0,1,1,1};
int dy[] = {-1,-1,0,1,1,1,0,-1}; // ←, ↖, ↑, ↗, →, ↘, ↓, ↙
vector<pair<int, int> > cloud;
bool visit[50][100];
void cloudMove() {
//d 방향으로 s칸이동
d = d - 1; //0부터쓸꺼니까 하나 줄여주고 시작
int x, y;
for (int i = 0; i < cloud.size(); i++) {
x = cloud[i].first + (dx[d] * s);
y = cloud[i].second + (dy[d] * s);
while (x <0) {
x += n;
}
while (y < 0) {
y += n;
}
x = x % n;
y = y % n;
cloud[i] = { x,y };
basket[x][y]++;
}
}
void waterPlus() {
//대각선은 idx 1 3 5 7
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
visit[i][j] = false;
}
}
int xx, yy;
int cnt;
for (int i = 0; i < cloud.size(); i++) {
cnt = 0;
for (int j = 1; j < 8; j += 2) {
xx = cloud[i].first + dx[j];
yy = cloud[i].second + dy[j];
//범위체크
if (xx < 0 || yy < 0 || xx >= n || yy >= n) continue;
if (basket[xx][yy] > 0) cnt++;
}
if (cnt > 0) {
basket[cloud[i].first][cloud[i].second] += cnt;
}
visit[cloud[i].first][cloud[i].second] = true;
}
}
void makeCloud() {
cloud.clear();
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
if (basket[i][j] < 2)continue;
if (visit[i][j])continue;
cloud.push_back({ i,j });
basket[i][j] -= 2;
}
}
}
int main() {
//0,0 ~ n-1,n-1까지
cin >> n >> m;
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
cin >> basket[i][j];
}
}
//초기 구름 4개 넣고 시작~
cloud.push_back({ n - 2,0 });
cloud.push_back({ n - 2,1 });
cloud.push_back({ n - 1,0 });
cloud.push_back({ n - 1,1 });
for (int i = 0; i < m; i++) {
cin >> d >> s;
cloudMove();
waterPlus();
makeCloud();
}
int answer = 0;
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
answer += basket[i][j];
}
}
cout << answer;
}
|
C++ | UTF-8 | 2,526 | 3.65625 | 4 | [] | no_license | /**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
// O(n) space
class Solution {
public:
void replaceVal(TreeNode* root, int a, int b) {
if (!root) return;
if (root->val == a) {
root->val = b;
} else if (root->val == b) {
root->val = a;
}
if (root->left) replaceVal(root->left, a, b);
if (root->right) replaceVal(root->right, a, b);
}
void buildTree(TreeNode* root, vector<int>& bst) {
if (!root) return;
if (root->left) buildTree(root->left, bst);
bst.push_back(root->val);
if (root->right) buildTree(root->right, bst);
}
void recoverTree(TreeNode* root) {
vector<int> bst;
buildTree(root, bst);
vector<int> swap;
for (int i = 0; i < bst.size()-1; i++) {
// bst[i] = bst[i+1] - bst[i];
if (bst[i+1] - bst[i] < 0) {
if (swap.empty()) {
swap.push_back(i);
} else {
swap.push_back(i+1);
}
}
}
if (swap.size()==1) swap.push_back(swap[0]+1);
cout << bst[swap[0]] << " " << bst[swap[1]] << endl;
replaceVal(root, bst[swap[0]], bst[swap[1]]);
}
};
// O(1) space
class Solution {
public:
TreeNode* first = NULL;
TreeNode* second = NULL;
TreeNode* prev = NULL;
void traversal(TreeNode* root) {
if (!root) return;
if (root->left) traversal(root->left);
// `prev` denotes the former and needs special initialization.
if (prev == NULL) {
prev = root;
} else {
// the first must be the one who is bigger than its latter.
if (first == NULL && !(prev->val < root->val)) {
first = prev;
}
// the second must be the one who is smaller than its former.
if (first != NULL && !(prev->val < root->val)) {
second = root;
}
}
prev = root;
if (root->right) traversal(root->right);
}
void recoverTree(TreeNode* root) {
traversal(root);
int tmp = first->val;
first->val = second->val;
second->val = tmp;
}
};
// Pay attention !
// 1. !(prev->val < root->val) needs the bracket! `!` is more prior.
|
Java | UTF-8 | 7,282 | 2.421875 | 2 | [] | no_license | package com.example.iti.sidemenumodule.helperclasses;
import android.app.Activity;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
import com.example.iti.sidemenumodule.R;
import com.example.iti.sidemenumodule.model.Project;
import com.example.iti.sidemenumodule.model.ProjectData;
import com.github.mikephil.charting.charts.PieChart;
import com.github.mikephil.charting.data.Entry;
import com.github.mikephil.charting.data.PieData;
import com.github.mikephil.charting.data.PieDataSet;
import com.github.mikephil.charting.utils.ColorTemplate;
import com.norbsoft.typefacehelper.TypefaceHelper;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Locale;
/**
* Created by ITI on 01/06/2016.
*/
public class MyProjectCustomerAdapter extends ArrayAdapter {
//to Cash my layout element
private static class ViewHolderItem {
PieChart pieChart;
TextView myProjectName;
TextView myProjectStartDate;
TextView myProjectEndDate;
TextView myProjectSalary;
TextView myProjectSate;
}
private final Activity context;
ArrayList<Project> myDate;
public MyProjectCustomerAdapter(Activity context, ArrayList<Project> data) {
super(context, R.layout.my_project_row);
this.context = context;
myDate=data;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolderItem viewHolder;
if(convertView==null){
// inflate the layout
LayoutInflater inflater = context.getLayoutInflater();
convertView = inflater.inflate(R.layout.my_project_row, parent, false);
TypefaceHelper.typeface(convertView);
// well set up the ViewHolder
viewHolder = new ViewHolderItem();
viewHolder.pieChart = (PieChart) convertView.findViewById(R.id.pie_chart);
viewHolder.myProjectName = (TextView) convertView.findViewById(R.id.my_project_name);
viewHolder.myProjectSalary = (TextView) convertView.findViewById(R.id.my_project_price);
viewHolder.myProjectSate = (TextView) convertView.findViewById(R.id.my_project_state);
viewHolder.myProjectEndDate = (TextView) convertView.findViewById(R.id.my_project_end_date);
viewHolder.myProjectStartDate = (TextView) convertView.findViewById(R.id.my_project_start_date);
// store the holder with the view.
convertView.setTag(viewHolder);
}else{
// we've just avoided calling findViewById() on resource everytime
// just use the viewHolder
viewHolder = (ViewHolderItem) convertView.getTag();
}
// object item based on the position
Project objectItem =myDate.get(position);
Log.e("length of data adaptour", myDate.size() + "");
// assign values if the object is not null
if(objectItem != null) {
SimpleDateFormat dateFormat = new SimpleDateFormat("MMM dd, yyyy", Locale.getDefault());
Date todayWithZeroTime=null;
int persent=0;
try
{
int all=get_count_of_days(objectItem.getStartDate(),objectItem.getProjectDeadLine());
Date today = new Date();
todayWithZeroTime =dateFormat.parse(dateFormat.format(today));
int remain=get_count_of_days(todayWithZeroTime,objectItem.getProjectDeadLine());
persent=(remain/all)*100;
} catch (ParseException e)
{
e.printStackTrace();
}
PieData data =DrawMyPieCart(persent);
// get the pieChart from the ViewHolder and then set data into chart
viewHolder.pieChart.setData(data);
viewHolder.pieChart.setCenterText(persent+" %"); // set the description
viewHolder.pieChart.setUsePercentValues(true);
viewHolder.pieChart.setDrawSliceText(true);
viewHolder.pieChart.setTransparentCircleRadius(9f);
viewHolder.pieChart.setDescription(""); // set the description
viewHolder.pieChart.setClickable(false);
viewHolder.myProjectName.setText(objectItem.getProjectName());
SimpleDateFormat sdf = new SimpleDateFormat("MMM dd, yyyy", Locale.ENGLISH);
String timeFormat=sdf.format(objectItem.getStartDate());
viewHolder.myProjectStartDate.setText(timeFormat);
timeFormat=sdf.format(objectItem.getProjectDeadLine());
viewHolder.myProjectEndDate.setText(timeFormat);
viewHolder.myProjectSate.setText(objectItem.getStatusOfProject());
// viewHolder.myProjectSalary.setText(objectItem.getBudget());
}
return convertView;
}
private PieData DrawMyPieCart(float progress)
{
//data of chart see if you move it to outer function
ArrayList<Entry> entries = new ArrayList<>();
entries.add(new Entry(progress, 0));
entries.add(new Entry(100-progress, 1));
//pass argument to pie dara set
PieDataSet dataSet = new PieDataSet(entries,null);
// // creating labels
ArrayList<String> labels = new ArrayList<>();
labels.add("");
labels.add("");
dataSet.setColors(ColorTemplate.COLORFUL_COLORS); // set the color
dataSet.setSliceSpace(3f);
// initialize Piedata
PieData data = new PieData(labels,dataSet);
data.removeXValue(0);
data.removeXValue(0);
return data;
}
@Override
public int getCount() {
return myDate.size();
}
public int get_count_of_days(Date Created_convertedDate,Date Expire_CovertedDate)
{
int c_year=0,c_month=0,c_day=0;
Calendar c_cal = Calendar.getInstance();
c_cal.setTime(Created_convertedDate);
c_year = c_cal.get(Calendar.YEAR);
c_month = c_cal.get(Calendar.MONTH);
c_day = c_cal.get(Calendar.DAY_OF_MONTH);
/*Calendar today_cal = Calendar.getInstance();
int today_year = today_cal.get(Calendar.YEAR);
int today = today_cal.get(Calendar.MONTH);
int today_day = today_cal.get(Calendar.DAY_OF_MONTH);
*/
Calendar e_cal = Calendar.getInstance();
e_cal.setTime(Expire_CovertedDate);
int e_year = e_cal.get(Calendar.YEAR);
int e_month = e_cal.get(Calendar.MONTH);
int e_day = e_cal.get(Calendar.DAY_OF_MONTH);
Calendar date1 = Calendar.getInstance();
Calendar date2 = Calendar.getInstance();
date1.clear();
date1.set(c_year, c_month, c_day);
date2.clear();
date2.set(e_year, e_month, e_day);
long diff = date2.getTimeInMillis() - date1.getTimeInMillis();
float dayCount = (float) diff / (24 * 60 * 60 * 1000);
return (int) dayCount;
}
public List<Project> getData() {
return myDate;
}
}
|
Python | UTF-8 | 223 | 2.8125 | 3 | [] | no_license | """
entity network session
"""
import uuid
class Session(object):
""" Network session
"""
def __init__(self, player, sid=None):
self.player = player
self.sid = sid if sid else str(uuid.uuid4())
|
Java | UTF-8 | 6,175 | 2.203125 | 2 | [] | no_license | package com.android.baselib.image;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.drawable.Drawable;
import android.support.annotation.DrawableRes;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.view.View;
import android.widget.ImageView;
import com.android.baselib.R;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.request.RequestOptions;
import com.bumptech.glide.request.target.ImageViewTarget;
import com.bumptech.glide.request.target.Target;
import java.io.File;
import java.lang.ref.WeakReference;
/**
* 图片加载维护(待完善)
*
* @author PF-NAN
* @date 2018/11/9
*/
public class UImage {
private static UImage mInstance = null;
private WeakReference<Context> mWeakContext;
private UImage() {
}
public static UImage getInstance() {
if (null == mInstance) {
synchronized (UImage.class) {
if (null == mInstance) {
mInstance = new UImage();
}
}
}
return mInstance;
}
/**
* 静态图加载
*
* @param context 上下文
* @param url url
* @param defIcon 加载中、加载失败显示图片资源
* @param imageView 图片控件
*/
public void load(Context context, @NonNull String url, @DrawableRes int defIcon, ImageView imageView) {
try {
if (null != context && null != imageView) {
mWeakContext = new WeakReference<>(context);
RequestOptions options = new RequestOptions()
.placeholder(defIcon)
.error(defIcon)
.diskCacheStrategy(DiskCacheStrategy.AUTOMATIC);
Glide.with(mWeakContext.get()).asBitmap().apply(options).load(url).into(imageView);
}
} catch (Exception e) {
e.printStackTrace();
imageView.setImageResource(defIcon);
}
}
/**
* 静态图加载
*
* @param context 上下文
* @param url url
* @param imageView 图片控件
*/
public void load(Context context, @NonNull String url, ImageView imageView) {
load(context,url,R.drawable.icon_defult_img,imageView);
}
/**
* 加载本地图片
*
* @param context
* @param filePath
* @param defIcon
* @param imageView
*/
public void loadFile(Context context, @NonNull String filePath, @DrawableRes int defIcon, ImageView imageView) {
try {
if (null != context && null != imageView) {
File file = new File(filePath);
if (file.exists()) {
mWeakContext = new WeakReference<>(context);
RequestOptions options = new RequestOptions()
.placeholder(defIcon)
.error(defIcon)
.diskCacheStrategy(DiskCacheStrategy.NONE);
Glide.with(mWeakContext.get()).load(file)
.apply(options)
.into(imageView);
} else {
imageView.setImageResource(defIcon);
}
}
} catch (Exception e) {
e.printStackTrace();
imageView.setImageResource(defIcon);
}
}
/**
* Gif图加载
*
* @param context 上下文
* @param url url
* @param defIcon 加载中、加载失败显示图片资源
* @param imageView 图片控件
*/
public void loadGif(@NonNull Context context, @NonNull String url, @DrawableRes int defIcon, @NonNull ImageView imageView) {
try {
mWeakContext = new WeakReference<>(context);
RequestOptions options = new RequestOptions()
.override(Target.SIZE_ORIGINAL)
.placeholder(defIcon)
.error(defIcon)
.diskCacheStrategy(DiskCacheStrategy.AUTOMATIC);
Glide.with(mWeakContext.get()).asGif().apply(options).load(url).into(imageView);
} catch (Exception e) {
e.printStackTrace();
imageView.setImageResource(defIcon);
}
}
/**
* @param context 上下文
* @param url url
* @param startView 开始加载前显示控件
* @param failedView 加载失败显示控件
* @param imageView 图片控件
*/
public void loading(@NonNull Context context, @NonNull String url, @NonNull final View startView, @NonNull final View failedView, @NonNull final ImageView imageView) {
try {
mWeakContext = new WeakReference<>(context);
Glide.with(mWeakContext.get()).asBitmap().load(url).into(new ImageViewTarget<Bitmap>(imageView) {
@Override
public void onStart() {
super.onStart();
startView.setVisibility(View.VISIBLE);
failedView.setVisibility(View.INVISIBLE);
}
@Override
protected void setResource(@Nullable Bitmap resource) {
startView.setVisibility(View.INVISIBLE);
if (null != resource) {
imageView.setImageBitmap(resource);
failedView.setVisibility(View.INVISIBLE);
} else {
failedView.setVisibility(View.VISIBLE);
}
}
@Override
public void onLoadFailed(@Nullable Drawable errorDrawable) {
super.onLoadFailed(errorDrawable);
failedView.setVisibility(View.VISIBLE);
startView.setVisibility(View.INVISIBLE);
}
});
} catch (Exception e) {
e.printStackTrace();
startView.setVisibility(View.INVISIBLE);
failedView.setVisibility(View.VISIBLE);
}
}
}
|
Java | UTF-8 | 1,376 | 3.234375 | 3 | [] | no_license | package com.xyz.design_pattern.chapter9;
/**
* Created with IntelliJ IDEA.
* User: vuclip123
* Date: 6/4/14
* Time: 10:39 AM
* To change this template use File | Settings | File Templates.
*/
public class Resume {
private String name;
private String sex;
private String age;
private String timeArea;
private String company;
public Resume(String name) {
this.name = name;
}
public void setPersonalInfo(String sex, String age) {
this.sex = sex;
this.age = age;
}
public void setWorkExperience(String timeArea, String company) {
this.timeArea = timeArea;
this.company = company;
}
public void display() {
System.out.printf("个人信息 %s %s %s%n",name,sex,age);
System.out.printf("工作经历 %s %s%n", timeArea, company);
}
public static final void main(String[] args) {
Resume a = new Resume("大鸟");
a.setPersonalInfo("男","29");
a.setWorkExperience("1998-2000","XX 公司");
Resume b = new Resume("大鸟");
b.setPersonalInfo("男","29");
b.setWorkExperience("1998-2000","XX 公司");
Resume c = new Resume("大鸟");
c.setPersonalInfo("男","29");
c.setWorkExperience("1998-2000","XX 公司");
a.display();
b.display();
c.display();
}
}
|
Python | UTF-8 | 202 | 3.03125 | 3 | [] | no_license | def now(text):
f=open(text)
wrds=0
fi=f.readlines()
for lines in fi:
words=lines.split()
wrds=wrds+len(words)
print(wrds)
now(input("enter text file here"))
|
Rust | UTF-8 | 4,340 | 2.84375 | 3 | [
"BSD-3-Clause",
"0BSD",
"LicenseRef-scancode-free-unknown",
"GPL-1.0-or-later",
"MIT",
"Apache-2.0"
] | permissive | use ruff_python_ast::{Expr, Ranged};
use ruff_diagnostics::{Diagnostic, Violation};
use ruff_macros::{derive_message_formats, violation};
use crate::checkers::ast::Checker;
/// ## What it does
/// Checks for the use of legacy `np.random` function calls.
///
/// ## Why is this bad?
/// According to the NumPy documentation's [Legacy Random Generation]:
///
/// > The `RandomState` provides access to legacy generators... This class
/// > should only be used if it is essential to have randoms that are
/// > identical to what would have been produced by previous versions of
/// > NumPy.
///
/// The members exposed directly on the `random` module are convenience
/// functions that alias to methods on a global singleton `RandomState`
/// instance. NumPy recommends using a dedicated `Generator` instance
/// rather than the random variate generation methods exposed directly on
/// the `random` module, as the new `Generator` is both faster and has
/// better statistical properties.
///
/// See the documentation on [Random Sampling] and [NEP 19] for further
/// details.
///
/// ## Examples
/// ```python
/// import numpy as np
///
/// np.random.seed(1337)
/// np.random.normal()
/// ```
///
/// Use instead:
/// ```python
/// rng = np.random.default_rng(1337)
/// rng.normal()
/// ```
///
/// [Legacy Random Generation]: https://numpy.org/doc/stable/reference/random/legacy.html#legacy
/// [Random Sampling]: https://numpy.org/doc/stable/reference/random/index.html#random-quick-start
/// [NEP 19]: https://numpy.org/neps/nep-0019-rng-policy.html
#[violation]
pub struct NumpyLegacyRandom {
method_name: String,
}
impl Violation for NumpyLegacyRandom {
#[derive_message_formats]
fn message(&self) -> String {
let NumpyLegacyRandom { method_name } = self;
format!("Replace legacy `np.random.{method_name}` call with `np.random.Generator`")
}
}
/// NPY002
pub(crate) fn legacy_random(checker: &mut Checker, expr: &Expr) {
if let Some(method_name) = checker
.semantic()
.resolve_call_path(expr)
.and_then(|call_path| {
// seeding state
if matches!(
call_path.as_slice(),
[
"numpy",
"random",
// Seeds
"seed" |
"get_state" |
"set_state" |
// Simple random data
"rand" |
"randn" |
"randint" |
"random_integers" |
"random_sample" |
"choice" |
"bytes" |
// Permutations
"shuffle" |
"permutation" |
// Distributions
"beta" |
"binomial" |
"chisquare" |
"dirichlet" |
"exponential" |
"f" |
"gamma" |
"geometric" |
"gumbel" |
"hypergeometric" |
"laplace" |
"logistic" |
"lognormal" |
"logseries" |
"multinomial" |
"multivariate_normal" |
"negative_binomial" |
"noncentral_chisquare" |
"noncentral_f" |
"normal" |
"pareto" |
"poisson" |
"power" |
"rayleigh" |
"standard_cauchy" |
"standard_exponential" |
"standard_gamma" |
"standard_normal" |
"standard_t" |
"triangular" |
"uniform" |
"vonmises" |
"wald" |
"weibull" |
"zipf"
]
) {
Some(call_path[2])
} else {
None
}
})
{
checker.diagnostics.push(Diagnostic::new(
NumpyLegacyRandom {
method_name: method_name.to_string(),
},
expr.range(),
));
}
}
|
C++ | UTF-8 | 2,082 | 2.625 | 3 | [] | no_license | #include "ShopScreen.h"
ShopScreen::ShopScreen(RenderWindow* w, Player* p) {
window = w;
player = p;
spaceTex.loadFromFile("Textures/general/space.png");
space.setTexture(spaceTex);
space.setPosition(0, 0);
for (int i = 0; i < ChargeChoices; i++) {
ShoptionCharge* shopt = new ShoptionCharge();
shopt->SetPosition(40 + i * 120, 100);
shopt->getCharge()->icon.setScale(2, 2);
chargesSold.push_back(shopt);
}
exit = new ExitShopButton();
}
ShopScreen::~ShopScreen() {
}
void ShopScreen::Draw() {
window->draw(space);
window->draw(exit->icon);
for (Shoption* s : chargesSold) {
s->Draw(window);
}
for (Shoption* s : chargesSold) {
s->DrawOver(window);
}
}
void ShopScreen::ExitShop() {
phase = PICKED;
}
void ShopScreen::MouseDown(Vector2f m) {
selectedShopt = NULL;
for (Shoption* s : chargesSold) {
FloatRect bounds = s->icon->getGlobalBounds();
if (bounds.contains(m)) {
selectedShopt = s;
}
}
}
void ShopScreen::MouseUp(Vector2f m) {
Shoption* bought = NULL;
if (selectedShopt != NULL) {
for (Shoption* s : chargesSold) {
if (s == selectedShopt) {
FloatRect bounds = s->icon->getGlobalBounds();
if (bounds.contains(m)) {
Buy((ShoptionCharge*)s);
bought = s;
}
}
}
if (bought != NULL) {
chargesSold.erase(remove(chargesSold.begin(),chargesSold.end(),bought),chargesSold.end());
}
}
else {
FloatRect bounds = exit->icon.getGlobalBounds();
if (bounds.contains(m)) {
exit->OnClick(this);
}
}
}
void ShopScreen::MoveMouse(Vector2f m) {
mousePos = m;
for (Shoption* s : chargesSold) {
ShoptionCharge* c = (ShoptionCharge*)s;
FloatRect bounds = c->icon->getGlobalBounds();
if (bounds.contains(m)) {
c->getCharge()->setHover(true);
}
else {
c->getCharge()->setHover(false);
}
}
}
void ShopScreen::Buy(ShoptionCharge* s) {
if (player->getMoney() >= s->getCost()) {
player->addMoney(-s->getCost());
player->AddCharge(s->getCharge());
}
}
void ShopScreen::Update(Time t) {
player->Update(t);
for (Shoption* s : chargesSold) {
s->Update(t);
}
} |
Java | UTF-8 | 1,329 | 2.875 | 3 | [] | no_license | package dad.javafx.bindings.window;
import javafx.application.Application;
import javafx.beans.binding.Bindings;
import javafx.beans.binding.DoubleExpression;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
public class WindowProperty extends Application {
private Label ancho;
private Label alto;
private Label area;
@Override
public void start(Stage primaryStage) throws Exception {
ancho = new Label();
DoubleExpression anchoVentana = primaryStage.widthProperty();
ancho.textProperty().bind(Bindings.concat("Ancho: " , primaryStage.widthProperty()));
alto = new Label();
DoubleExpression altoVentana = primaryStage.heightProperty();
alto.textProperty().bind(Bindings.concat("Alto: " , primaryStage.heightProperty()));
area = new Label();
DoubleExpression areaVentana = anchoVentana.multiply(altoVentana);
area.textProperty().bind(Bindings.concat("Area: " ,areaVentana));
VBox root = new VBox(ancho, alto, area);
root.setAlignment(Pos.CENTER);
root.setFillWidth(false);
Scene scene = new Scene(root, 320, 200);
primaryStage.setTitle("Window Propety: ");
primaryStage.setScene(scene);
primaryStage.show();
}
public static void main(String[] args) {
launch(args);
}
}
|
Java | UTF-8 | 1,361 | 1.820313 | 2 | [] | no_license | package top.leeti.controller;
import com.alibaba.fastjson.JSON;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import top.leeti.entity.PublishedInfo;
import top.leeti.service.PublishedInfoService;
import javax.annotation.Resource;
@Slf4j
@Controller
public class PublishedInfoController {
@Resource
private PublishedInfoService publishedInfoService;
@GetMapping("/admin/publishedInfo")
public String findMixedList(@RequestParam(name = "pageNum", defaultValue = "1") Integer pageNum,
Model model) {
PageInfo<PublishedInfo> pageInfo = publishedInfoService.listReportedPublishedInfo(pageNum);
model.addAttribute("pageInfo", pageInfo);
return "published-info/published-info";
}
@ResponseBody
@GetMapping("/admin/publishedInfo/passAjax")
public String dealWithPassAjax(@RequestParam String id, @RequestParam Integer mark, @RequestParam String reportId) {
String msg = publishedInfoService.dealWithPass(id, mark, reportId);
return JSON.toJSONString(msg);
}
} |
Python | UTF-8 | 2,223 | 2.59375 | 3 | [
"MIT"
] | permissive | import sklearn
from sklearn.utils import shuffle
from sklearn.neighbors import KNeighborsClassifier
import pandas as pd
import numpy as np
from sklearn import linear_model, preprocessing
data = pd.read_csv("car.data")
enc = preprocessing.LabelEncoder()
buying = enc.fit_transform(list(data["buying"]))
maint = enc.fit_transform(list(data["maint"]))
door = enc.fit_transform(list(data["door"]))
persons = enc.fit_transform(list(data["persons"]))
lug_boot = enc.fit_transform(list(data["lug_boot"]))
safety = enc.fit_transform(list(data["safety"]))
cls = enc.fit_transform(list(data["class"]))
X = list(zip(buying,maint,door,persons,lug_boot,safety))
Y = list(cls)
X_train, X_test, Y_train, Y_test = sklearn.model_selection.train_test_split(X, Y, test_size = 0.1)
model = KNeighborsClassifier(n_neighbors=9)
model.fit(X_train, Y_train)
acc = model.score(X_test, Y_test)
print(acc)
predicted = model.predict(X_test)
names = ["unacc", "acc", "good", "vgood"]
buying = ["vhigh", "high", "med", "low"]
maint = ["vhigh", "high", "med", "low"]
door = ["2", "3", "4", "5","more"]
persons = ["2", "4", "more"]
lug_boot = ["small", "med", "big"]
safety = ["low", "med", "high"]
names2 = np.array([buying,maint,door,persons,lug_boot,safety])
for x in range(len(predicted)):
"""names3 = "Price: " + buying[X_test[x][0]], " Maintenence: " + maint[X_test[x][1]], " Door: " + door[X_test[x][2]],\
" Persons: " + persons[X_test[x][3]], " Lug Boot: " + lug_boot[X_test[x][4]], \
" Safety: " + safety[X_test[x][5]]"""
print ("Data:"+ str(names3), " Predicted: ", names[predicted[x]], " Actual: ", names[Y_test[x]])
"""print(X_test)
print(X_test[0][0])
print(names3)
names3 = "Price: "+ buying[X_test[0][0]], " Maintenence: "+ maint[X_test[0][1]], " Door: "+ door[X_test[0][2]],
" Persons: "+ persons[X_test[0][3]], " Lug Boot: "+ lug_boot[X_test[0][4]], " Safety: "+ safety[X_test[0][4]]"""
"""names2 = np.array([["vhigh", "high", "med", "low"],["vhigh", "high", "med", "low"],["2", "3", "4", "5more"],
["2", "4", "more"],["small", "med", "big"],["low", "med", "high"]])"""
"""names2 = np.array([buying,maint,door,persons,lug_boot,safety])""" |
C# | UTF-8 | 3,561 | 2.6875 | 3 | [] | no_license | // 2020-12-24, Bruce
//string sql = "SELECT * FROM Person WHERE LastName = '" + lastName + "' OR '1' = '1'"; // SQL注入
//string sql = string.Format("SELECT * FROM Person WHERE LastName = '{0}'", lastName); // 格式化
//string sql = $"SELECT * FROM Person WHERE LastName = '{lastName}'"; // C#6语法
//string sql = $"SELECT * FROM Person WHERE LastName=@LastName"; // @作为参数, 防止SQL注入
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data.SqlClient;
using System.Data;
using Dapper;
namespace ComFram
{
public class PersonDao : IDao
{
public List<IModel> FindListByName(string lastName)
{
using (IDbConnection db = new SqlConnection(DBHelper.ConnStrng))
{
string sql = $"SELECT * FROM Person WHERE 1=1";
if (!string.IsNullOrWhiteSpace(lastName))
{
sql += $" AND LastName LIKE CONCAT('%',@LastName,'%')";
}
IEnumerable<PersonModel> lst = db.Query<PersonModel>(sql, new { LastName = lastName });
return lst.ToList<IModel>();
}
}
public IModel FindByID(int id)
{
using (IDbConnection db = new SqlConnection(DBHelper.ConnStrng))
{
string sql = $"SELECT * FROM Person WHERE ID=@ID";
IEnumerable<PersonModel> lst = db.Query<PersonModel>(sql, new { ID = id });
return lst.FirstOrDefault();
}
}
public List<IModel> FindListByPage(int nPageIndex, int nPageSize)
{
using (IDbConnection db = new SqlConnection(DBHelper.ConnStrng))
{
string sql = $"SELECT * FROM Person";
IEnumerable<PersonModel> lst = db.Query<PersonModel>(sql);
lst = lst.OrderBy(x => x.ID).Skip((nPageIndex - 1) * nPageSize).Take(nPageSize).ToList();
return lst.ToList<IModel>();
}
}
public bool InsertData(IModel model)
{
using (IDbConnection db = new SqlConnection(DBHelper.ConnStrng))
{
PersonModel person = (PersonModel)model;
person.CreatedDate = DateTime.Now;
person.LastModifiedDate = DateTime.Now;
string sql = "INSERT INTO Person(FirstName,LastName,Email,CreatedDate,LastModifiedDate) VALUES(@FirstName,@LastName,@Email,@CreatedDate,@LastModifiedDate)";
int ret = db.Execute(sql, person);
return ret > 0;
}
}
public bool UpdateData(IModel model)
{
using (IDbConnection db = new SqlConnection(DBHelper.ConnStrng))
{
PersonModel person = (PersonModel)model;
person.LastModifiedDate = DateTime.Now;
string sql = "UPDATE Person SET FirstName=@FirstName,LastName=@LastName,Email=@Email,LastModifiedDate=@LastModifiedDate WHERE ID=@ID";
int ret = db.Execute(sql, person);
return ret > 0;
}
}
public bool DeleteData(IModel model)
{
using (IDbConnection db = new SqlConnection(DBHelper.ConnStrng))
{
PersonModel person = (PersonModel)model;
string sql = "DELETE FROM Person WHERE ID=@ID";
int ret = db.Execute(sql, person);
return ret > 0;
}
}
}
}
|
Python | UTF-8 | 249 | 3.703125 | 4 | [] | no_license | w = input("가로를 입력하세요")
h = input("세로를 입력하세요")
try:
area = float(w*h)
preimeter = float(2*(w+h))
except ValueError:
pass
print("사각형의 넓이 : ", area)
print("사각형의 둘레 : ", preimeter)
|
C++ | UTF-8 | 899 | 3 | 3 | [] | no_license | #pragma once
#include "../../core/all.h"
#include "TextBox.h"
///////////////////////////////////////////////////////////////////////////////
/*
Text_Manager class
-class for handling texture data for fonts and rendering
-This class holds ont the texture data for each font and a pointer needs to be passed to every texture box that uses it.
*/
///////////////////////////////////////////////////////////////////////////////
class Text_Manager
{
public:
Text_Manager( std::string fonttexture );
~Text_Manager();
void Render( TextBox &textbox );
bool IsActive(){ return m_initialized; }
private:
//!Renders a specific character at a position x/y with dimensions width and height
void RenderLetter( float x, float y, float width, float height, char c );
GLuint m_textureID; //texture id that holds the font in opengl
bool m_initialized; //wether or not the font has been initialized
}; |
C# | UTF-8 | 412 | 2.984375 | 3 | [] | no_license | using System.Globalization;
private void Convert_From_Hijri_To_Gregorian(System.Object sender, System.EventArgs e)
{
CultureInfo arCI = new CultureInfo("ar-SA");
string hijri = TextBox1.Text;
DateTime tempDate = DateTime.ParseExact(hijri, "dd/MM/yyyy", arCI.DateTimeFormat, DateTimeStyles.AllowInnerWhite);
TextBox2.Text = tempDate.ToString("dd/MM/yyyy");
}
|
Ruby | UTF-8 | 4,322 | 2.609375 | 3 | [
"MIT"
] | permissive | module FathomAnalytics
class Api
LIMIT = 50
attr_reader :url, :email, :password
def initialize(url:, email:, password:)
@url = url
@email = email
@password = password
@auth_token = nil
end
def add_site(name:)
post_request(path: "/api/sites", params: { name: name })
end
def remove_site(id:)
delete_request(path: "/api/sites/#{id}")
end
def sites
get_request(path: "/api/sites")
end
def site_realtime_stats(id:)
get_request(path: "/api/sites/#{id}/stats/site/realtime")
end
def site_stats(id:, from:, to:, limit: LIMIT, offset: 0)
path = "/api/sites/#{id}/stats/site"
get_request(path: path, before: to, after: from, limit: limit, offset: offset)
end
def site_agg_stats(id:, from:, to:, limit: LIMIT, offset: 0)
path = "/api/sites/#{id}/stats/site/agg"
get_request(path: path, before: to, after: from, limit: limit, offset: offset)
end
def page_agg_stats(id:, from:, to:, limit: LIMIT, offset: 0)
path = "/api/sites/#{id}/stats/pages/agg"
get_request(path: path, before: to, after: from, limit: limit, offset: offset)
end
def page_agg_page_views_stats(id:, from:, to:, limit: LIMIT, offset: 0)
path = "/api/sites/#{id}/stats/pages/agg/pageviews"
get_request(path: path, before: to, after: from, limit: limit, offset: offset)
end
def referrer_agg_stats(id:, from:, to:, limit: LIMIT, offset: 0)
path = "/api/sites/#{id}/stats/referrers/agg"
get_request(path: path, before: to, after: from, limit: limit, offset: offset)
end
def referrer_agg_page_views_stats(id:, from:, to:, limit: LIMIT, offset: 0)
path = "/api/sites/#{id}/stats/referrers/agg/pageviews"
get_request(path: path, before: to, after: from, limit: limit, offset: offset)
end
def authenticate
params = {
"Email": email,
"Password": password
}
response = post_request(path: "/api/session", params: params, authenticated: false) do |raw_response|
set_auth_token(raw_response)
end
response
end
private
def get_request(path:, before: nil, after: nil, limit: nil, offset: nil, authenticated: true)
ensure_auth_token if authenticated
params = {}
params['before'] = before if before
params['after'] = after if after
params['limit'] = limit if limit
params['offset'] = offset if offset
response = connection.get(
path: path,
auth_token: @auth_token,
params: params
)
if response.status == 200
api_response(response.body)
else
raise FathomAnalytics::Error.new(response.status)
end
end
def post_request(path:, params:, authenticated: true, &block)
ensure_auth_token if authenticated
response = connection.post(
path: path,
params: params,
auth_token: @auth_token
)
if response.status == 200
yield response if block_given?
api_response(response.body)
else
raise FathomAnalytics::Error.new(response.status)
end
end
def delete_request(path:, authenticated: true)
ensure_auth_token if authenticated
response = connection.delete(
path: path,
auth_token: @auth_token
)
if response.status == 200
yield response if block_given?
api_response(response.body)
else
raise FathomAnalytics::Error.new(response.status)
end
end
def api_response(response_body)
parsed = JSON.parse(response_body)
parsed["Data"] || {}
rescue JSON::ParserError
{}
end
def ensure_auth_token
return unless @auth_token.nil?
authenticate
end
def set_auth_token(response)
set_cookie_header = response.headers['set-cookie']
@auth_token = parse_auth_header(set_cookie_header)
raise FathomAnalytics::Error.new("Failed to retrieve auth key") unless @auth_token
end
def parse_auth_header(header)
return nil if header.nil?
matches = header.match(/auth=([a-zA-Z0-9\-_]+);/)
matches[1] if matches
end
def connection
@connection ||= FathomAnalytics::Connection.new(base_url: url)
end
end
end
|
Python | UTF-8 | 359 | 2.609375 | 3 | [] | no_license | import urllib.request, urllib.response, urllib.error
fhand = urllib.request.urlopen('http://data.pr4e.org/romeo.txt') #Like open command
counts=dict()
for line in fhand:
#print(line.decode().strip()) #it skipps header, only showing body
words=line.decode().split()
for word in words:
counts[word]=counts.get('word',0)+1
print(counts)
|
JavaScript | UTF-8 | 1,724 | 2.625 | 3 | [] | no_license | const commando = require("discord.js-commando");
const req = require("request");
const fs = require("fs");
class Weather extends commando.Command {
constructor(client) {
super(client, {
name : "weather",
memberName : "weather",
description : "Shows you the weather of a given location.",
examples : ["£weather uk lincoln"],
group : "apis",
args : [
{
key : "country",
prompt : "You need to enter the abbreviation of your Country, or State if you live in the USA.",
type : "string"
},
{
key : "city",
prompt : "You need to enter the full name of your City.",
type : "string"
}
]
})
}
async run(message, args) {
var countryL = args["country"];
var cityL = args["city"];
var url = "http://api.wunderground.com/api/85754ff3511af2d7/conditions/q/" + countryL + "/" + cityL + ".json";
req(url, function(error, response, body) {
body = JSON.parse(body);
if(body["current_observation"] != undefined) {
var uwLocation = body["current_observation"]["display_location"]["full"];
var temp = body["current_observation"]["temp_c"];
var cond = body["current_observation"]["weather"];
message.reply(uwLocation + "\nWeather: " + cond + "\nTemperature: " + temp + "C", {
file : body["current_observation"]["icon_url"]
});
}
});
}
}
module.exports = Weather; |
JavaScript | UTF-8 | 6,601 | 4.21875 | 4 | [] | no_license | //Ejercicio 1
//Determina el resultado de un número x elevado a una potencia n.
function elevar(x, y) {
return Math.pow(x, y);
}
console.log("---------------------------------------------------");
console.log("Potencia de 2^4 es:");
console.log(elevar(2, 4))
//Ejercicio 2
//Determina si un número n se encuentra en un rango determinado.
console.log("---------------------------------------------------");
let number = 10;
if (number >= 10 && number <= 100) {
console.log("El numero " + number + " esta en el rango de 10 a 100");
} else {
console.log("El numero " + number + " no esta en el rango de 10 a 100");
}
//Ejercicio 3
//Dado un número entero en segundos, determinar la cantidad de horas, minutos y segundos que contiene.
function reloj(seconds) {
var hour = Math.floor(seconds / 3600);
hour = (hour < 10) ? '0' + hour : hour;
var minute = Math.floor((seconds / 60) % 60);
minute = (minute < 10) ? '0' + minute : minute;
var second = seconds % 60;
second = (second < 10) ? '0' + second : second;
return hour + ':' + minute + ':' + second;
}
var segundos = 9690;
console.log("---------------------------------------------------");
console.log("La conversion del numero: " + segundos + " a hrs, min y seg es: " + reloj(segundos));
//Ejercicio 4
//Determine el mayor de 4 enteros.
function mayor(num1, num2, num3, num4) {
return Math.max(num1, num2, num3, num4);
}
console.log("---------------------------------------------------");
console.log("Arreglo [9,35,5,7]");
console.log("El número mayor del arreglos es: " + mayor(9, 35, 5, 7));
//Ejercicio 5
//Calcula la suma de una lista (arreglo) de elementos.
var num = [1, 2, 3, 4, 5], lista = 0;
num.forEach(function (num) {
lista += num;
});
console.log("---------------------------------------------------");
console.log("Arreglo: " + num);
console.log("La suma del arreglo es:" + lista);
//Otro ejemplo de suma de una lista (arreglo)
let numeros = [1, 2, 3, 4, 5, 100, 20, 80];
let total = numeros.reduce((a, b) => a + b, 0);
console.log("---------------------------------------------------");
console.log("Arreglo: " + numeros);
console.log("La suma del arreglo es:");
console.log(total);
//Ejercicio 6
//Determina si un elemento dado está contenido en una lista. Devuelve verdadero o falso.
const arreglo = [8, 6, 3, 0, 7];
console.log("---------------------------------------------------");
console.log(arreglo);
console.log(arreglo.includes(0));
console.log(arreglo.includes(9));
//Ejercicio 7
//Determina si dada una lista, ésta se encuentra ordenada. Se debe devolver verdadero o falso.
const ordenar = () => {
//var arreglo1 = [32,65,24,87,65,34,33,74,47];
var arreglo1 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
console.log("El arreglo es: ")
console.log(arreglo1);
var numb = 0;
for (let i = 0; i < arreglo1.length; i++) {
if (numb < arreglo1[i]) {
numb = arreglo1[i];
var arregloo = true;
} else {
var arregloo = false;
}
}
return arregloo;
}
console.log("---------------------------------------------------");
console.log("¿El arreglo está ordenado? " + ordenar());
//Ejercicio 8
//Dadas dos listas, determine si son iguales. Devolver verdadeo o falso.
console.log("---------------------------------------------------");
var arreglox = [5, 4, 3, 2, 1];
var arregloy = [1, 2, 0, 4, 0];
//var arreglox = [1,2,3,4,5];
//var arregloy = [1,2,3,4,5];
console.log(arreglox);
console.log(arregloy);
if (arreglox.sort().join(',') === arregloy.sort().join(',')) {
console.log('True, Los valores son iguales');
}
else console.log('False, Los valores no son iguales');
//Ejercicio 9
//Realizar una función recursiva que retorne como salida el resultado de la suma 1 + 3 + 5 + 7 + 9 + N.
const suma = numeros => {
if (numeros.length === 0) {
return 0;
} else {
let [first, ...rest] = numeros;
return first + suma(rest);
}
}
console.log("---------------------------------------------------");
console.log("Arreglo: [1,3,5,7,9,10] la suma es: ");
console.log(suma([1 + 3 + 5 + 7 + 9 + 10]));
//Ejercicio 10
//Realizar una función que reciba una lista y devuelva empleando recursividad otra lista de los elementos pares.
let numw = [1,2,3,4,5,6,7,8];
const parlist = ls => {
let result = [];
if(ls.length === 0){
return result;
}
if (ls[0] % 2 === 0){
result.push(ls[0]);
}
return result.concat(parlist(ls.slice(1)));
};
console.log("---------------------------------------------------");
console.log("Arrelgo");
console.log(numw);
console.log("Los números pares del arreglo son:");
console.log(parlist(numw));
//Ejercicio 11
//Realiza una función que permita cargar calcular la unión, intersección y diferencia de dos conjuntos dados.
const conjunto = () => {
let listax = new Set([31, 42, 62, 54, 35, 70, 56, 90, 80]);
let listay = new Set([42, 89, 70, 76, 26, 45, 44, 82, 21]);
console.log("Los Arreglos son: ");
console.log(listax);
console.log(listay);
console.log("***********************************************************************");
let union = new Set([...listax, ...listay]);
let interseccion = new Set([...listax].filter(a => listay.has(a)));
let diferencia = new Set([...listay].filter(a => !listax.has(a)));
console.log("Union de los numeros");
console.log(union);
console.log("Interseccion de los numeros");
console.log(interseccion);
console.log("Diferencia de los numeros");
console.log(diferencia);
}
console.log("---------------------------------------------------");
console.log(conjunto());
//Ejercicio 12
//Realiza una función que permita definir un mapa de datos y permita encontrar un valor a partir de su clave.
const mapadedatos = x => {
var miMapa = new Map();
miMapa.set("clave1", new Array("ALEX", "CANO", 23));
miMapa.set("clave2", new Array("JOSE", "CANO", 12));
miMapa.set("clave3", new Array("ALEJANDRO", "CANO", 21));
var resul = "";
resul += "Nombre: " + miMapa.get(x)[0] + "\n";
resul += "Apellido: " + miMapa.get(x)[1] + "\n";
resul += "Edad: " + miMapa.get(x)[2] + "\n";
return resul;
}
console.log("---------------------------------------------------");
console.log(mapadedatos("clave3"));
console.log("---------------------------------------------------"); |
Markdown | UTF-8 | 2,022 | 3.21875 | 3 | [] | no_license | ---
title: No Student Left Behind! A session for true beginners who want to learn Python/Django
layout: talk
body_class: talk
permalink: talks/no-student-left-behind-a-session-for-true-beginners-who-want-to-learn-pythondjango
about: We are a mother and daughter coding team and we're new at it! Deanna (mom) just graduated from Nashville Software School and Justina (daughter) is a current student. We're both really energized by the welcoming community of tech in Nashville and want to make 'giving back' a part of our journey from the very beginning. Throughout our short time of learning so far, we have noticed many tutorials and books that are aimed at beginners go right above the heads of most beginners. We are highly empathetic, super friendly and very motivated to help others. Our goal is to encourage and support all beginners and keep people from quitting before they even get going. There's no better time for us to identify what qualifies as "beginner" then right now while we are learning it for the first time. When we're not studying together, we are planning outdoor adventures, listening to music and doing arts and crafts.
abstract: Newbie mother and daughter coders will walk you through how to create your first Django web app. You'll learn how to set up an environment in the terminal and start building a small application as a code-along exercise. We'll discuss the history and uses of Python/Django too.
type: tutorial
expected_length: 1hr
intended_audience: Beginner
speakers: Deanna Vickers and Justina Vickers
---
## Talk Description
Do you want to learn Python but find most "beginner" books and talks too advanced? We are making no assumptions about your knowledge and plan to provide as much background and detail from a true beginner's perspective, because we are beginners ourselves. Bring your laptop so you can code right along with us. We'll start with an introduction to what Python is and why it was created and then show you how to install Python and Django and build a simple web application.
|
JavaScript | UTF-8 | 823 | 3.671875 | 4 | [] | no_license | /////// Ingresar dato semana
let dia = prompt("ingrege el dia de la semana");
// if(dia == null){
// console.log("dato nulo, ingrese un dato valido");
// } else{
// console.log("dato valido");
// dia = dia.toLowerCase();
// if (dia == "sabado" || dia == "domingo") {
// console.log("fin de semana");
// } else if ( dia == "lunes" ||
// dia == "martes" ||
// dia == "miercoles" ||
// dia == "jueves" ||
// dia == "viernes"){
// console.log("dia entre semana");
// } else {
// console.log("Ingresa un dia a la semana valido");
// }
// }
////////////// switch
switch (dia) {
case null:
console.log("dato nulo, ingrese un dato valido");
break;
default:
break;
} |
Markdown | UTF-8 | 28,960 | 2.59375 | 3 | [] | no_license | # 2018年 西邮Linux兴趣小组 纳新免试题揭秘 - Pangda NoSilly - CSDN博客
2018年05月07日 23:14:59[hepangda](https://me.csdn.net/hepangda)阅读数:765
# 前言
小组2018年的免试题的五位出题人是:小组16级成员刘付杰、李猛、时宇辰、王良、娄泽豪。(此处应有掌声若干秒)
本人虽然参与了出题,但是我对其他关卡知之甚少,于是好奇的我在免试题上线了之后,与大家一起开始了破关之旅。以下以我作为第一视角所写而成的“免试题攻略”,若有错漏,还请多多包涵,与我在评论区进行交流。
# 第一关
目前微信推送中第一关的入口已经下线,想要挑战的同学可以点击[这里的入口](http://m.fujie.bid)进行挑战。
打开本关的入口链接,首先我们看到了一大段英文,根据我们在线翻译级别的英语技术,大约意思是我们要不要继续下去:

第一直觉我们肯定选择【Yes!】,不过这一页还有别的信息吗?经过一番尝试,无论是叛逆的选择【No..】或者做其他操作,都没有其他有用的信息。于是我们选择【Yes!】进入第二个页面:

首先最引人瞩目的显然就是中间的看不清楚的字,还有下面“FUJIE”五个字母构成的目前看来意义不明的动画。中间看不清楚的字可以通过选择的方式选中复制出来看:
```
晓伴君王犹未起,
阻避钧衡过十年。
纳降归拟尽公卿,
欣然向我话佳境。
诚知杀身愿如此,
恭谈祖德朵颐开。
```
我的文学水平不怎么高,但是显然这首诗的文学水平实在是一言难尽。不过既然刻意隐藏起来,其中必有玄机,仔细读读之后,发现似乎是一个藏头诗啊——“晓阻纳欣诚恭”,不正是“小组纳新成功”的意思吗?
在刚刚复制字的时候,左右拖动一下,还可以发现网页的动画下边隐藏了这样一些文字:
```
然后,如你所见
Fujie被一股神秘力量肢解了!!!
这实在是太恐怖了!小组的小伙伴们都吓得不知所措了!
希望你能帮我们复原一下Fujie!
```
这里说了“肢解”,可能是一个很重要的信息。不过我们现在手头还没有与之相关的内容,怎么办呢?还是前几年的老方法,按F12在审查元素里面找找吧!

这里有一个隐藏起来的链接,我们点击进去看看:

这里有以26个字母开头的单词为名的文件各一个。随意的下载几个来看,没什么联系,看来是我们已有的信息派上用场的时候了。联想到“FUJIE”被分开的动画以及提示的“肢解”、“藏头诗”的信息,想到了:有可能是f,u,j,i,e五个字母打头的文件被拆分了。于是下载这五个文件,使用以下命令将他们连接起来:
```matlab
cat understand >> freedom
cat jealousy >> freedom
cat independence >> freedom
cat enjoy >> freedom
```
组合起来之后,根据文件图标和文件头来看,是一个zip的压缩包。打开之后,发现里面有两个文件:

尝试解压这个压缩包,果然是需要密码的。不过压缩文件里既然说“请给我们一句祝福的话(UTF-8)”,那么密码就呼之欲出了,藏头诗的内容“小组纳新成功”即是密码。解压之后,仔细听压缩包中的另一个mp3,在音乐的末尾有机读出下一关的IP地址。那么这一关就算完成了。
# 第二关
从上一关中我们得到了[本关的入口](http://47.100.19.186/),打开入口界面,我们看到了以下的界面:

使用Ctrl+A选择页面内的所有元素,没有发现什么有价值的东西。还是老方法,审查元素:

在注释里面说要让我们认真听音乐,然后下面还有一系列文件,在网页上分析太不方便了,干脆统统下载下来好了。下载之后,按照网页上所说的,先听听音乐吧!听了一阵子之后发现有些时候左耳会声音变小,有的时候右耳声音会变小,摘掉另一个耳机,发现有滴滴声。那么我们用频谱分析软件看一看发生了什么吧!这里用的软件是`audacity`。打开之后,发现听的时候三段的声音变小的频谱是这样的:



单独播放声音变小的声道的声音,似乎像发电报的声音,搜索摩尔斯电码对照着看,得到了三个单词:`OPEN FREE SHARE`,是小组的文化精神,应该是一个重要的信息。分析完了音乐,再看看其他的东西吧,打开`XiyouLinux.zip`这个压缩包,果然是需要密码,不过刚才我们刚刚得到了三个单词,进行排列组合尝试一下,发现密码就是`openfreeshare`。压缩包中有两个文件:

解压缩之后,运行`a.out`提示`need parameter`,尝试再次输入`openfreeshare`,这次并不能通过。看来还需要别的信息,打开`.pri.key`这个文件:
```
-----BEGIN PRIVATE KEY-----
MIICdwIBADANBgkqhkiG9w0BAQEFAASCAmEwggJdAgEAAoGBAL4YTFlbLUlGHoW4
bS92RUL0rOn8BnFzNp95FTpeKqUP4gDDTbwflFSZ+1jdhrTsmXHTzTl0rQZ+wNbk
iSX3k8obXFmlO21cj1uvEjmWWtxlR6A375A7iQGH10x3h2Bh9o7dnPXoUvd2wH9x
2p7tD6dPm5GR+dpXiOhByPiuHpahAgMBAAECgYEAnLQZFDw2S8YS2TbcQxjjJbvf
Yw+QHCvW5oWBO1lvHBzIuMpHJYJ+23MIIQyUxEaag5wO/IMzMzyAKWXBrVu3JqGe
Xtu4EGEPxnLG5JNbOeUfo8c25a3Kjm4pAYhEE0cfq0I0QnWKyGfwxuQghT9Fb4xZ
qNd2DIIgOpjhilLj6zUCQQD2HqWesti5VgaqBUk2XZpH0jyFW43ACk5YSuSPhkDp
hnAYFdesNpyJK5M11e/Y3imD1UB8t9s0dpAIp3PwhnpzAkEAxbnjiKUYwwwcF8ts
EZ1ahsLAXYNoBX6YOr+Rxlf2tWKqaF7JAhwb6VNdpH3oi1Jn/Eg99mHHOKgwMjZF
uugBmwJBAIAUOMoadlAUpYkrEQt6sIP5s0cO+vhaJKUr7D+IdRVRwdm23DKhhNqZ
U5VrjNKF4oLZoiKFJ0zo+lGWmu4rfWMCQD7BALYdr/43mbLznRj6GAEtTmBflGQq
CaabpmiNAoAPEIaPjrxcr38eNlo+m8+cF+S6CPBpmBEjUCifkQIBIIECQARkXiTZ
oU7fXHlOW49e1V3ExMah874+XxaZ5BmWoWZASgQ+M+cybPYsQpBKuxwFJMTZdEFo
NY+19KxfsKoFQ2k=
-----END PRIVATE KEY-----
a part of address:(please use public key to deal with)
VkqyowF5O60JThF3tHxgnXlGHDCHHWQG7y8KhlnN9xLOC3eThFPDA/NH9lQIwyiRQQV7XINxOcugiF0xdhKQpzZ9CHdyByUvyvOGyDeA77X3voIF6YivPIOhxEU9vXLLlpFp/2MFbU2D7XX9p4DNCTbn92P8zwx9vcE1FDQkYGE=
```
看到了一个RSA加密算法中所需要的私钥,还有一串让我们使用公钥处理的密文,看来本关与RSA算法有关联,不过我们已经没有更多信息了。思考之后,感觉首页的小组Logo很大(?),而且并没有从外部链接,可能有玄机,使用`vim`打开,跳转到最后,果然别有洞天!

先提示了`#391`,去第391行看看,发现了一个PNG头,删除掉前面内容,得到了一张新的图片:

图片里直截了当的就是一个某网盘的地址,下载对应文件之后是一个TXT文件,内容是:
```
后半部分:(使用公钥加密)
RWpjbKKOKAyi62rw6F5xVfCWUtDSnzaW1zJVmz2p9we3zWszsbuP1OLgz3bzqGYMHYPFenxx+0eX+qgJk3f5Hb6LmBG4huQp2AH7Mmi8pCTjdS3QX60x4zIObWOzh7ya+eelvQu6UcX0VGI7gGpUVTPoNbxEglb4wCE6XV9Mzhw=
```
看来我们又得到了一部分的内容,先暂且记下,接着分析之前的图片,之前的图片下面又出现了`The parameter`,后面是一堆`&#`开头后面跟着数字的东西,应该是HTML转义字符,对应的字符是`I love Linux && I want to challenge`,将这一串信息输入到刚才的`a.out`中,得到信息:
```
-----BEGIN PUBLIC KEY-----
MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQC+GExZWy1JRh6FuG0vdkVC9Kzp
/AZxczafeRU6XiqlD+IAw028H5RUmftY3Ya07Jlx0805dK0GfsDW5Ikl95PKG1xZ
pTttXI9brxI5llrcZUegN++QO4kBh9dMd4dgYfaO3Zz16FL3dsB/cdqe7Q+nT5uR
kfnaV4joQcj4rh6WoQIDAQAB
-----END PUBLIC KEY-----
You need to find the ciphertext to get some information !!!
```
看来是获得了公钥,不过实际上之前已经给了我们私钥,即使我们不获得这个信息,也可以通过私钥计算出公钥,这一步理论上可以跳过。
这样我们知道了RSA的公钥和私钥,以及相应的密文,通过在线RSA解密工具,我们得到了下一关的入口:`http://xyl2018.xuejietech.cn/`
# 第三关
进入[第三关](http://xyl2018.xuejietech.cn/),首先看到的就是一个倒计时:

仔细阅读之后,看来是一个迷宫游戏。下面应该是这个迷宫的构造,迷宫很大,岔路很多,而且每次的迷宫在刷新后都不同,应该是随机的。既然是随机的,人品足够应该也能走出来吧!多次尝试之后发现——运气并不能好到这种程度。那么就写一个程序帮助我计算一下路线吧!上网搜索一下迷宫问题的相关算法,有很多种解法,例如DFS、BFS等等,以下给出一个方案:
```
#include <stdio.h>
const int W = 101, H = 101, M = 4;
const char SPACE = '.',WALL = '#', ROUTE = '$';
char board[H][W];
typedef struct pos_t {
int x, y;
} pos_t;
pos_t movements[] = { {1, 0}, {0, 1}, {-1, 0}, {0, -1} };
void print_board()
{
for (int i = 0; i < H; i++) {
for (int j = 0; j < W; j++) {
putchar(board[i][j]);
}
putchar('\n');
}
}
int main(int argc, char *argv[])
{
for (int i = 0; i < H; i++) {
for (int j = 0; j < W; j++) {
scanf(" %c", &board[i][j]);
}
}
int steps[W * H];
steps[0] = 0;
for (int x = 0, y = 1, top = 0;;) {
pos_t *m = &movements[steps[top]];
x += m->x; y += m->y;
if (x == W - 2 && y == H - 1) {
board[y][x] = ROUTE;
break;
} else if (board[y][x] == SPACE && x >= 0 && y >= 0 && x < W && y < H) {
board[y][x] = ROUTE;
steps[++top] = 0;
} else {
x -= m->x; y -= m->y;
steps[top]++;
while (steps[top] >= M) {
board[y][x] = SPACE;
if (--top < 0) break;
m = &movements[steps[top]];
x -= m->x; y -= m->y;
steps[top]++;
}
}
}
print_board();
return 0;
}
```
按照程序所提示的通关迷宫之后,直接跳转到了[第四关](http://140.143.239.164/)。
# 第四关
从上一关跳转到[本关](http://140.143.239.164/)之后,看到了以下界面:

一如既往的简洁啊,还是打开审查元素看看都有什么吧!

还是一如既往的注释剧透系列,这里有一个命令,还有一个压缩包。先运行一下这个命令吧~

得到了字符串`kcabpool`,根据剧本应该是上面那个压缩包的密码了吧!下载压缩包,使用`kcabpool`作为密码解压,压缩包中只有一个音乐:

这个音乐的名字说“不仅仅是一个音乐”,看来可能还有别的信息?研究之后~~发现~~猜测是一个`zip`格式的压缩文件。直接使用`unzip`命令解压缩,得到一个文件`hint.txt`,内容如下:

`゚ω゚ノ= /`m´)ノ ~┻━┻ //*´∇`*/ ['_']; o=(゚ー゚) =_=3; c=(゚Θ゚) =(゚ー゚)-(゚ー゚); (゚Д゚) =(゚Θ゚)= (o^_^o)/ (o^_^o);(゚Д゚)={゚Θ゚: '_' ,゚ω゚ノ : ((゚ω゚ノ==3) +'_') [゚Θ゚] ,゚ー゚ノ :(゚ω゚ノ+ '_')[o^_^o -(゚Θ゚)] ,゚Д゚ノ:((゚ー゚==3) +'_')[゚ー゚] }; (゚Д゚) [゚Θ゚] =((゚ω゚ノ==3) +'_') [c^_^o];(゚Д゚) ['c'] = ((゚Д゚)+'_') [ (゚ー゚)+(゚ー゚)-(゚Θ゚) ];(゚Д゚) ['o'] = ((゚Д゚)+'_') [゚Θ゚];(゚o゚)=(゚Д゚) ['c']+(゚Д゚) ['o']+(゚ω゚ノ +'_')[゚Θ゚]+ ((゚ω゚ノ==3) +'_') [゚ー゚] + ((゚Д゚) +'_') [(゚ー゚)+(゚ー゚)]+ ((゚ー゚==3) +'_') [゚Θ゚]+((゚ー゚==3) +'_') [(゚ー゚) - (゚Θ゚)]+(゚Д゚) ['c']+((゚Д゚)+'_') [(゚ー゚)+(゚ー゚)]+ (゚Д゚) ['o']+((゚ー゚==3) +'_') [゚Θ゚];(゚Д゚) ['_'] =(o^_^o) [゚o゚] [゚o゚];(゚ε゚)=((゚ー゚==3) +'_') [゚Θ゚]+ (゚Д゚) .゚Д゚ノ+((゚Д゚)+'_') [(゚ー゚) + (゚ー゚)]+((゚ー゚==3) +'_') [o^_^o -゚Θ゚]+((゚ー゚==3) +'_') [゚Θ゚]+ (゚ω゚ノ +'_') [゚Θ゚]; (゚ー゚)+=(゚Θ゚); (゚Д゚)[゚ε゚]='\\'; (゚Д゚).゚Θ゚ノ=(゚Д゚+ ゚ー゚)[o^_^o -(゚Θ゚)];(o゚ー゚o)=(゚ω゚ノ +'_')[c^_^o];(゚Д゚) [゚o゚]='\"';(゚Д゚) ['_'] ( (゚Д゚) ['_'] (゚ε゚+(゚Д゚)[゚o゚]+ (゚Д゚)[゚ε゚]+(゚Θ゚)+ (゚ー゚)+ (゚Θ゚)+ (゚Д゚)[゚ε゚]+(゚Θ゚)+ ((゚ー゚) + (゚Θ゚))+ (゚ー゚)+ (゚Д゚)[゚ε゚]+(゚Θ゚)+ (゚ー゚)+ ((゚ー゚) + (゚Θ゚))+ (゚Д゚)[゚ε゚]+(゚Θ゚)+ ((o^_^o) +(o^_^o))+ ((o^_^o) - (゚Θ゚))+ (゚Д゚)[゚ε゚]+(゚Θ゚)+ ((o^_^o) +(o^_^o))+ (゚ー゚)+ (゚Д゚)[゚ε゚]+((゚ー゚) + (゚Θ゚))+ (c^_^o)+ (゚Д゚)[゚ε゚]+(゚ー゚)+ ((o^_^o) - (゚Θ゚))+ (゚Д゚)[゚ε゚]+(゚Θ゚)+ (o^_^o)+ (゚Θ゚)+ (゚Д゚)[゚ε゚]+(゚Θ゚)+ ((゚ー゚) + (゚Θ゚))+ ((゚ー゚) + (o^_^o))+ (゚Д゚)[゚ε゚]+(゚Θ゚)+ ((o^_^o) +(o^_^o))+ ((゚ー゚) + (゚Θ゚))+ (゚Д゚)[゚ε゚]+(゚Θ゚)+ ((o^_^o) +(o^_^o))+ ((o^_^o) - (゚Θ゚))+ (゚Д゚)[゚ε゚]+(゚ー゚)+ (c^_^o)+ (゚Д゚)[゚ε゚]+(゚Θ゚)+ (゚ー゚)+ (゚Θ゚)+ (゚Д゚)[゚ε゚]+(゚Θ゚)+ ((゚ー゚) + (゚Θ゚))+ ((o^_^o) +(o^_^o))+ (゚Д゚)[゚ε゚]+(゚Θ゚)+ ((o^_^o) +(o^_^o))+ (o^_^o)+ (゚Д゚)[゚ε゚]+(゚Θ゚)+ ((o^_^o) +(o^_^o))+ ((゚ー゚) + (o^_^o))+ (゚Д゚)[゚ε゚]+(゚Θ゚)+ (゚ー゚)+ ((゚ー゚) + (゚Θ゚))+ (゚Д゚)[゚ε゚]+(゚Θ゚)+ ((o^_^o) +(o^_^o))+ ((o^_^o) - (゚Θ゚))+ (゚Д゚)[゚ε゚]+(゚ー゚)+ (c^_^o)+ (゚Д゚)[゚ε゚]+(゚Θ゚)+ ((゚ー゚) + (゚Θ゚))+ ((゚ー゚) + (゚Θ゚))+ (゚Д゚)[゚ε゚]+(゚Θ゚)+ (゚ー゚)+ (゚Θ゚)+ (゚Д゚)[゚ε゚]+(゚Θ゚)+ ((゚ー゚) + (o^_^o))+ (゚Θ゚)+ (゚Д゚)[゚ε゚]+(゚ー゚)+ (c^_^o)+ (゚Д゚)[゚ε゚]+(゚Θ゚)+ ((゚ー゚) + (゚Θ゚))+ (c^_^o)+ (゚Д゚)[゚ε゚]+(゚Θ゚)+ (゚ー゚)+ (゚Θ゚)+ (゚Д゚)[゚ε゚]+(゚Θ゚)+ ((o^_^o) +(o^_^o))+ ((o^_^o) +(o^_^o))+ (゚Д゚)[゚ε゚]+(゚Θ゚)+ (゚ー゚)+ ((゚ー゚) + (゚Θ゚))+ (゚Д゚)[゚ε゚]+(゚ー゚)+ (c^_^o)+ (゚Д゚)[゚ε゚]+(゚Θ゚)+ ((o^_^o) +(o^_^o))+ ((o^_^o) - (゚Θ゚))+ (゚Д゚)[゚ε゚]+(゚Θ゚)+ (゚ー゚)+ ((゚ー゚) + (゚Θ゚))+ (゚Д゚)[゚ε゚]+(゚Θ゚)+ ((゚ー゚) + (゚Θ゚))+ (゚ー゚)+ (゚Д゚)[゚ε゚]+(゚Θ゚)+ (゚ー゚)+ (゚Θ゚)+ (゚Д゚)[゚ε゚]+(゚Θ゚)+ ((o^_^o) +(o^_^o))+ (゚ー゚)+ (゚Д゚)[゚ε゚]+(゚Θ゚)+ ((゚ー゚) + (゚Θ゚))+ (゚Θ゚)+ (゚Д゚)[゚ε゚]+(゚Θ゚)+ ((゚ー゚) + (゚Θ゚))+ ((゚ー゚) + (o^_^o))+ (゚Д゚)[゚ε゚]+(゚Θ゚)+ ((゚ー゚) + (゚Θ゚))+ ((o^_^o) +(o^_^o))+ (゚Д゚)[゚ε゚]+(゚Θ゚)+ ((o^_^o) +(o^_^o))+ (o^_^o)+ (゚Д゚)[゚ε゚]+(゚Θ゚)+ ((゚ー゚) + (゚Θ゚))+ (c^_^o)+ (゚Д゚)[゚ε゚]+(゚Θ゚)+ ((゚ー゚) + (゚Θ゚))+ (゚Θ゚)+ (゚Д゚)[゚ε゚]+(゚Θ゚)+ ((o^_^o) +(o^_^o))+ (c^_^o)+ (゚Д゚)[゚ε゚]+(゚ー゚)+ (c^_^o)+ (゚Д゚)[゚ε゚]+(゚Θ゚)+ ((o^_^o) +(o^_^o))+ ((゚ー゚) + (o^_^o))+ (゚Д゚)[゚ε゚]+(゚Θ゚)+ ((゚ー゚) + (゚Θ゚))+ (゚Θ゚)+ (゚Д゚)[゚ε゚]+(゚Θ゚)+ ((o^_^o) +(o^_^o))+ (゚ー゚)+ (゚Д゚)[゚ε゚]+(゚Θ゚)+ ((゚ー゚) + (゚Θ゚))+ (c^_^o)+ (゚Д゚)[゚ε゚]+(゚ー゚)+ (c^_^o)+ (゚Д゚)[゚ε゚]+(゚Θ゚)+ ((o^_^o) - (゚Θ゚))+ ((o^_^o) - (゚Θ゚))+ (゚Д゚)[゚ε゚]+(゚Θ゚)+ ((゚ー゚) + (゚Θ゚))+ ((゚ー゚) + (o^_^o))+ (゚Д゚)[゚ε゚]+(゚Θ゚)+ (゚ー゚)+ ((o^_^o) - (゚Θ゚))+ (゚Д゚)[゚ε゚]+(゚Θ゚)+ ((゚ー゚) + (゚Θ゚))+ ((゚ー゚) + (o^_^o))+ (゚Д゚)[゚ε゚]+(゚Θ゚)+ ((o^_^o) +(o^_^o))+ (゚ー゚)+ (゚Д゚)[゚ε゚]+(゚Θ゚)+ ((o^_^o) +(o^_^o))+ (o^_^o)+ (゚Д゚)[゚ε゚]+(゚ー゚)+ (c^_^o)+ (゚Д゚)[゚ε゚]+(゚Θ゚)+ (c^_^o)+ ((゚ー゚) + (゚Θ゚))+ (゚Д゚)[゚ε゚]+(゚Θ゚)+ ((゚ー゚) + (o^_^o))+ (c^_^o)+ (゚Д゚)[゚ε゚]+(゚Θ゚)+ (゚ー゚)+ (o^_^o)+ (゚Д゚)[゚ε゚]+(゚Θ゚)+ ((゚ー゚) + (゚Θ゚))+ (゚ー゚)+ (゚Д゚)[゚ε゚]+(゚Θ゚)+ ((o^_^o) +(o^_^o))+ ((゚ー゚) + (゚Θ゚))+ (゚Д゚)[゚ε゚]+(゚Θ゚)+ ((o^_^o) +(o^_^o))+ (o^_^o)+ (゚Д゚)[゚ε゚]+(゚Θ゚)+ ((゚ー゚) + (゚Θ゚))+ (゚Θ゚)+ (゚Д゚)[゚ε゚]+(゚Θ゚)+ ((゚ー゚) + (゚Θ゚))+ ((゚ー゚) + (o^_^o))+ (゚Д゚)[゚ε゚]+(゚Θ゚)+ ((゚ー゚) + (゚Θ゚))+ ((o^_^o) +(o^_^o))+ (゚Д゚)[゚ε゚]+(゚ー゚)+ (c^_^o)+ (゚Д゚)[゚ε゚]+(゚Θ゚)+ ((o^_^o) - (゚Θ゚))+ (c^_^o)+ (゚Д゚)[゚ε゚]+(゚Θ゚)+ ((o^_^o) +(o^_^o))+ ((o^_^o) - (゚Θ゚))+ (゚Д゚)[゚ε゚]+(゚Θ゚)+ ((゚ー゚) + (゚Θ゚))+ ((゚ー゚) + (o^_^o))+ (゚Д゚)[゚ε゚]+(゚Θ゚)+ ((o^_^o) +(o^_^o))+ (゚ー゚)+ (゚Д゚)[゚ε゚]+(゚Θ゚)+ ((゚ー゚) + (゚Θ゚))+ ((゚ー゚) + (o^_^o))+ (゚Д゚)[゚ε゚]+(゚Θ゚)+ (゚ー゚)+ (o^_^o)+ (゚Д゚)[゚ε゚]+(゚Θ゚)+ ((゚ー゚) + (゚Θ゚))+ ((゚ー゚) + (o^_^o))+ (゚Д゚)[゚ε゚]+(゚Θ゚)+ ((゚ー゚) + (゚Θ゚))+ (゚ー゚)+ (゚Д゚)[゚ε゚]+(゚ー゚)+ ((o^_^o) - (゚Θ゚))+ (゚Д゚)[゚ε゚]+((゚ー゚) + (゚Θ゚))+ (゚Θ゚)+ (゚Д゚)[゚o゚]) (゚Θ゚)) ('_');`
哇,好多的颜文字!不过我曾经看到说`Javascript`可以加密为颜文字,这一段是不是一段`Javascript`代码呢?在`Chrome`浏览器自带的`Console`中输入这些内容,得到:

其实如果你不知道这一点,也可以上网找到[“颜文字加密”的解密网站](http://utf-8.jp/public/aaencode.html),也能得到这一串信息。这一串信息是说答案可能与“Robots Exclusion Protocol”相关,那么这是什么呢?搜索一下并仔细阅读阅读:

仔细看完,感觉只有“根目录下的robots.txt”可能是有效信息,其他的都是一些科普知识。那么我们试着在这个网站下找找`robots.txt`吧!在地址栏中输入本关的网址,后面跟上`/robots.txt`:

COOL!我们得到了下一关的地址!
# 第五关
输入网址进入[第五关](http://182.254.130.94:8080),首先看到的是:

不同于其他几关,本关的页面中显示的信息量比其他关卡大了很多。不过我们还是尝试尝试老套路吧,按F12打开`Chrome`浏览器的审查元素功能:

这里的注释居然说以下没有需要查看源码才能得到的信息?!不过我是这关的出题人,我可以向你保证,这里说的真的是真的。尝试在页面中随意点点,发现:点击“官方网站”一项,就真的可以访问小组的官方网站;点击“微信平台”一项,出现的二维码就真的可以关注我们的微信平台;点击“新浪微博”一项,就真的可以跳转到小组的微博;点击“我们在哪”一项,emmm,就真的可以在腾讯地图上找到我们小组的位置。那么关键的信息点在哪里呢?
你可能看到了,页面下面的灰色字体会提示你通过什么系统访问,甚至于通过手机访问的时候:

不过灰色字体是以逗号结束的,选中之后发现后面还有别的信息,这取决于你使用什么系统来访问的这个页面。如果你和我一样使用`Linux`访问,那么会提示你使用`Windows`访问网页看看;如果你使用`Windows`,那么便提示你使用`Linux`访问尝试一下。对比之后,发现在任务目标一节中,如果你使用`Windows`,那么你看到的就是:

如果你使用`Linux`访问,那么你看到的则是:

两者之间的区别就是“链接”状图标的位置不同。分别下载这两组文件,`Windows`下,下载的文件是一个压缩包,按照剧本来说应该有密码,不过——这次并没有。解压之后,可执行文件,里面有一个数独游戏。不过即使你解出来也没有用,因为并不能以任何形式输入结果。反复查看之后,发现在文件属性中就得到Key2了:

在`Linux`下,下载的文件也是一个压缩包,也照例没有密码。解压之后:

压缩包东西很多,其中图片说:

使用`vim`打开图片,里面没有任何其他信息。而文本文件的内容是一串base64编码的内容,内容为补充解释图片的意思。两者结合起来大约是要求我们去求`Key1_2018bytes`这个文件中有多少个二进制1,并将这个数字作为结果提交给`pangda`这个程序。那么我们这里可以写一个程序帮我们做这个事情:
```
#include<stdio.h>
int main(int argc, char *argv[])
{
FILE *fp = fopen("Key1_2018bytes", "rb");
int res = 0;
char t;
fread(&t, sizeof(char), 1, fp);
while (!feof(fp)) {
if (t & 0b10000000) res++;
if (t & 0b01000000) res++;
if (t & 0b00100000) res++;
if (t & 0b00010000) res++;
if (t & 0b00001000) res++;
if (t & 0b00000100) res++;
if (t & 0b00000010) res++;
if (t & 0b00000001) res++;
fread(&t, sizeof(char), 1, fp);
}
printf("result = %d\n", res);
fclose(fp);
return 0;
}
```
不过,等等!这些文件名又是什么意思呢?仔细看一下:一字节有八位,2018×8=16144,Key1是2018字节。那么,既然Key1只有2018字节,最终答案必然也在1~16144之内!所以我们还可以通过暴力解答这个问题:
```bash
for ((i=1;i<=16144;i++));
do
echo $i > ./temp
./pangda < ./temp >> ./out
done
awk '!a[$0]++' out
```
最终结果是8063,提交给程序,得到了`Key1`。

还有一个标签没有访问过,点击进去,有一个智力问答游戏。答案是随机的,尝试几次之后点击新出现的提示链接。进入这个页面:

打开网页源码,发现代码很少,也没有常见的注释提醒。不过,在其中一个`<p>`标签中,有一个名为`tips`即`提示`的属性:

提示内容是`User-Agent`,结合网页上的内容,难道是说让我将`User-Agent`改为`XiyouLinux Group`?在网上查询修改`User-Agent`的方法,重新访问:

只有一个链接,点击后下载一个压缩包。解压之后只有一个名为`Key4.elf`的可执行文件,执行一下只提示`See .rodata`。看来我们的另一个Key就藏在`.rodata`段了!使用命令`readelf -p .rodata Key4.elf`,便得到了`Key 4`!

至此,我们已经拿到了Key1、Key2、Key4。离成功只差一步之遥,即——将Key直接填写进文本框中!虽然我们并没有拿到Key3,不过网页提示的任务目标中并不要求我们提交Key3。

提交之后,弹出提示框了一个网页,当我们进入这个网页之后,便进入了这个页面:

呼~~经过好长时间,看来小组2018的免试题终于全部通关了,那么,2018年西邮Linux兴趣小组免试题的揭秘便到此结束!顺便一说,截止今天,小组2018年的免试题仍然在线,大家若有兴趣也可以继续尝试哟~
>
通关只是目的之一,免试题并不是难住所有做题的人才高兴,希望你能在免试题的旅途上见到很多全新的东西,也许可以引发你的思考,也许能让你兴致盎然。愿你在技术的道路上越走越远~~
参考链接:
[2017 Linux兴趣小组免试题解析](https://blog.csdn.net/tanswer_/article/details/70881447)
[2016 Linux兴趣小组免试题解析](http://blog.csdn.net/yangbodong22011/article/details/51286850)
[2015 Linux兴趣小组免试题解析](http://www.s0nnet.com/archives/xiyoulinux2015)
[2014 Linux兴趣小组免试题解析](http://blog.csdn.net/tutulove1234/article/details/24781255)
[2013 Linux兴趣小组免试题解析](http://www.cnblogs.com/ma6174/archive/2013/05/04/3058889.html)
|
JavaScript | UTF-8 | 1,119 | 2.546875 | 3 | [] | no_license | /*global define*/
define(['events', 'jquery'], function (events, $) {
'use strict';
var self = {};
self.add = function add() {
var operands = Array.prototype.slice.call(arguments),
total = 0;
operands.forEach(function (value) {
if (typeof value === 'string') {
value = parseInt(value, 10) || 0;
}
total += value;
});
$.get('http://numbersapi.com/' + total + '/trivia', function (fact) {
events.publish('added', {
operands: operands,
result: total,
triviaFact: fact
});
});
return total;
};
self.addAfterDelay = function addAfterDelay(delay, callback) {
var timeoutDelay = Array.prototype.shift.call(arguments),
callback = Array.prototype.shift.call(arguments),
operands = arguments;
window.setTimeout(function () {
callback(self.add.apply(this, operands));
}, timeoutDelay);
}
return self;
});
|
Python | UTF-8 | 1,234 | 3.1875 | 3 | [] | no_license | from matplotlib import pyplot as plt
import numpy as np
# plt.xkcd() # Cartoonic Style
plt.style.use("fivethirtyeight")
###########################################################################################################################################
# Median Developer Salaries by Age
age_x = [25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35]
x=np.arange(len(age_x)) # Here's our x Axis
width = 0.25
labels=["Developer salary","Python Developer salary",'JavaScript Developer salary']
# Developer salary
dev_y = [38496, 42000, 46752, 49320, 53200,
56000, 62316, 64928, 67317, 68748, 73752]
# Median Python Developer Salaries by Age
py_dev_y = [45372, 48876, 53850, 57287, 63016,
65998, 70003, 70000, 71496, 75370, 83640]
# Median JavaScript Developer Salaries by Age
js_dev_y = [37810, 43515, 46823, 49293, 53437,
56373, 62375, 66674, 68745, 68746, 74583]
plt.bar(x-width,dev_y,label=labels,width=width)
plt.bar(x,py_dev_y,label=labels,width=width)
plt.bar(x+width,js_dev_y,label=labels,width=width)
plt.title("Salary vs Age")
plt.xlabel("Age")
plt.ylabel("Salary")
plt.show()
plt.tight_layout()
plt.legend()
|
Python | UTF-8 | 660 | 4.03125 | 4 | [] | no_license | pet = input("what pet do you have? ")
age = int(input("how old is your pet? "))
human_age = 0
if pet == "cat":
if age == 1:
human_age = 15
elif age == 2:
human_age = 24
if age > 2:
calc_age = age - 2
for i in range(0,calc_age+1):
yrs = i * 4
human_age = 24 + yrs
if pet == "dog":
if age == 1:
human_age = 12
elif age == 2:
human_age = 24
if age > 2:
calc_age = age - 2
for i in range(0,calc_age+1):
yrs = i * 4
human_age = 24 + yrs
print(f"your {pet}'s human age is {human_age}")
|
Markdown | UTF-8 | 3,083 | 2.5625 | 3 | [
"MIT"
] | permissive | # Autopilot-TensorFlow
A TensorFlow implementation of this [Nvidia paper](https://arxiv.org/pdf/1604.07316.pdf) with some changes. For a summary of the design process and FAQs, see [this medium article I wrote](https://medium.com/@sullyfchen/how-a-high-school-junior-made-a-self-driving-car-705fa9b6e860).
# IMPORTANT
Absolutely, under NO circumstance, should one ever pilot a car using computer vision software trained with this code (or any home made software for that matter). It is extremely dangerous to use your own self-driving software in a car, even if you think you know what you're doing, not to mention it is quite illegal in most places and any accidents will land you in huge lawsuits.
This code is purely for research and statistics, absolutley NOT for application or testing of any sort.
<img src="https://github.com/17011813/Autopilot-TensorFlow/blob/master/2020-04-21%20(15).png" width="90%"></img>
# How to Use
Download the [dataset](https://github.com/SullyChen/driving-datasets) and extract into the repository folder
Use `python train.py` to train the model
Use `python run.py` to run the model on a live webcam feed
Use `python run_dataset.py` to run the model on the dataset
[dataset](https://github.com/SullyChen/driving-datasets) 07/01/2018 Dataset 최신 데이터로 돌릴때 data.txt의 데이터 형식이 달라서 47727.jpg 3.530000,2018-07-01 17:51:57:21 이렇게 되어있어서 line.split()[0] 하면 3.530000,2018-07-01 이렇게 되기때문에 line.split()[0][0:8]로 써줘서 angle 부분만 입력되어 append 되도록 수정하였습니다.
`python driving_data.py`코드 에서 14번째 줄에 line.split()[0] ----> line.split()[0][0:8]
[dataset](https://github.com/SullyChen/driving-datasets)에서 Dataset 1을 쓴다면 코드 수정없이 그대로 해도 됩니다.
To visualize training using Tensorboard use `tensorboard --logdir=./logs`, then open http://0.0.0.0:6006/ into your web browser.
# Acknowledged/Cited in
D. Qian et al., "End-to-End Learning Driver Policy using Moments Deep Neural Network," 2018 IEEE International Conference on Robotics and Biomimetics (ROBIO), Kuala Lumpur, Malaysia, 2018, pp. 1533-1538.
O’Kelly, M., Sinha, A., Namkoong, H., Duchi, J., & Tedrake, R. (2018). Scalable End-to-End Autonomous Vehicle Testing via Rare-event Simulation.
Pan, X., You, Y., Wang, Z., & Lu, C. (2017). Virtual to Real Reinforcement Learning for Autonomous Driving. [https://arxiv.org/abs/1704.03952](https://arxiv.org/pdf/1704.03952.pdf)
Xu, N., Tan, B., & Kong, B. (2018). Autonomous Driving in Reality with Reinforcement Learning and Image Translation.
https://medium.com/@maxdeutsch/how-to-build-a-self-driving-car-in-one-month-d52df48f5b07
https://mc.ai/self-driving-car-on-indian-roads/
http://on-demand.gputechconf.com/gtc/2018/presentation/s8748-simulate-and-validate-your-dnn-inference-with-catia-before-adas-industrial-deployment.pdf
https://www.ctolib.com/amp/cyanamous-Self-Driving-Car-.html
<img src="https://github.com/17011813/Autopilot-TensorFlow/blob/master/2020-04-21%20(14).png" width="90%"></img>
|
Shell | UTF-8 | 1,548 | 2.75 | 3 | [] | no_license | # Contributor: William Rea <sillywilly@gmail.com>
# Contributor: Eduard Warkentin <eduard.warkentin@gmail.com>
# Contributor: neuromante <lorenzo.nizzi.grifi@gmail.com>
# Contributor: Eduardo Robles Elvira <edulix@gmail.com>
pkgname=opensc-svn
pkgver=4619
pkgrel=1
pkgdesc="Access smart cards that support cryptographic operations"
arch=('i686' 'x86_64')
url="http://www.opensc-project.org/opensc"
license=("LGPL")
options=('!libtool')
backup=(etc/opensc.conf)
depends=('zlib' 'openssl' 'pcsclite')
makedepends=('autoconf' 'automake' 'nasm' 'subversion')
provides=('opensc')
conflicts=('opensc')
source=()
md5sums=()
_svntrunk=http://www.opensc-project.org/svn/opensc/trunk/
_svnmod=opensc
build() {
cd $startdir/src
msg "Updating SVN entries for $_svnmod..."
svn co $_svntrunk $_svnmod -r $pkgver
cp -r $_svnmod $_svnmod-build
cd $_svnmod-build
msg "SVN checkout done or server timeout"
msg "Starting make..."
./bootstrap
./configure --prefix=/usr --sysconfdir=/etc --enable-pcsc --disable-man
make || return 1
make DESTDIR=${pkgdir} install || return 1
install -Dm644 ${srcdir}/$_svnmod-build/etc/opensc.conf ${pkgdir}/etc/opensc.conf || return 1
mkdir -p ${pkgdir}/usr/include/libopensc || return 1
install -Dm644 ${srcdir}/$_svnmod-build/src/libopensc/*.h ${pkgdir}/usr/include/libopensc || return 1
mkdir -p ${pkgdir}/usr/include/scconf || return 1
install -Dm644 ${srcdir}/$_svnmod-build/src/scconf/*.h ${pkgdir}/usr/include/scconf || return 1
mkdir -p ${pkgdir}/usr/include/common || return 1
install -Dm644 ${srcdir}/$_svnmod-build/src/common/*.h ${pkgdir}/usr/include/common || return 1
}
|
Python | UTF-8 | 472 | 3.609375 | 4 | [] | no_license | #encoding:utf-8
# num_list = (x for x in range(1,10000))
# print(type(num_list))
# 自己写生成器
# def my_gen():
# yield 1
# yield 2
# yield 3
#
# ret=my_gen()
# print(next(ret))
# print(next(ret))
# print(next(ret))
#send 方法
# def my_gen(start):
# while start<10:
# temp = yield start
# print(temp)
# start+=1
#
#
# ret=my_gen(1)
# for x in ret:
# print(x)
# # print(next(ret))
# #
# # print(ret.send('hello world'))
|
Python | UTF-8 | 1,483 | 2.734375 | 3 | [] | no_license | # coding=utf-8
from collections import namedtuple
import pandas as pd
import numpy as np
from statsmodels.tsa.stattools import grangercausalitytests
def gc(df, maxlag, addconst=True, verbose=False, thershold=0.05):
ssr_ftest_explain = ['teststatistic', 'pvalue', 'u', 'degrees_of_freedom']
s = namedtuple('ssr_ftest', ssr_ftest_explain)
res = grangercausalitytests(df, maxlag, addconst=addconst, verbose=verbose)
x1, x2 = df.columns
h = []
for lag, v_res in res.items():
ft = s(*v_res[0]['ssr_ftest'])
# print(lag, v_res)
if ft.pvalue > thershold:
status = False
else:
status = True
h.append([x1, x2, lag, status])
return pd.DataFrame(h, columns=['var1', 'var2', 'lag', 'var1 does Granger cause var2'])
if __name__ == '__main__':
# ssr_ftest_explain = ['teststatistic', 'pvalue', 'u', 'degrees_of_freedom']
# s = namedtuple('ssr_ftest', ssr_ftest_explain)
# thershold = 0.05
df = pd.DataFrame([[1, 2, 3, 4, 5, 6, 7, 8, 9, 10], [1.21, 2.321, 3.41, 8, 5, 6, 7, 0, 9, 10]],
index=['x1', 'x2']).T
s = gc(df, 2)
print(s)
# res = gc(df, 2)
# x1, x2 = df.columns
# for lag, v_res in res.items():
# ft = s(*v_res[0]['ssr_ftest'])
# print(lag, v_res)
# if ft.pvalue > thershold:
# status = False
# else:
# status = True
#
# x1, x2, lag, status
# print(res)
pass
|
JavaScript | UTF-8 | 1,059 | 3.421875 | 3 | [] | no_license | //var fs = require('fs');
/*console.time('Assincrono');
var counter = 0;
for(var i =0; i < 1000; i++){
fs.readFile('my_file.txt', function (err, data){
if(err){
return console.error(err);
}
counter++;
console.log("Assincrono: " + data.toString());
if (counter === 1000) {
console.timeEnd('Assincrono');
}
});
}*/
//81ms
/*console.time('Sincrono');
for (var i = 0; i < 1000; i++) {
var data = fs.readFileSync('my_file.txt');
console.log('Sincrono: ' + data);
}
console.timeEnd('Sincrono');
*/
//22ms
var fs = require("fs"),
Promise = require('promise');
function read(file){
return new Promise(function(fulfill, reject){
fs.readFile(file, function(err, data){
if (err) {
reject();
}else{
fulfill(data.toString());
}
});
});
}
read('my_file.txt')
.then((data)=>{
console.log(data);
return '111111';
})
.then((data)=>{
console.log(data);
return '222222';
})
.then((data)=>{
console.log(data);
return '333333';
})
.done((data)=>{
console.log(data);
})
|
Java | UTF-8 | 2,565 | 2.21875 | 2 | [] | no_license | /*-
* ========================LICENSE_START=================================
* de.geewhiz.pacify.pacify-maven-plugin
* %%
* Copyright (C) 2011 - 2018 gee-whiz.de
* %%
* 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.
* =========================LICENSE_END==================================
*/
package de.geewhiz.pacify.mavenplugin.mojo;
import java.io.File;
import org.apache.maven.plugin.AbstractMojo;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugin.MojoFailureException;
import org.apache.maven.plugins.annotations.Parameter;
import org.apache.maven.project.MavenProject;
/**
* Base class of all pacify goals
*
*
*/
public abstract class BasePacifyMojo extends AbstractMojo {
@Parameter(defaultValue = "${project}")
protected MavenProject project;
/**
* Should pacify completely be skipped??
*/
@Parameter(property = "skipPacify", defaultValue = "false")
protected boolean skip;
/**
* Which path should be configured.
*
*/
@Parameter(property = "packagePath", required = true)
protected File packagePath;
public void execute() throws MojoExecutionException, MojoFailureException {
if (skip) {
getLog().info("Pacify is skipped.");
return;
}
executePacify();
}
protected abstract void executePacify() throws MojoExecutionException;
protected void checkPackagePath() throws MojoExecutionException {
if (getPackagePath().exists()) {
return;
}
File outputDirectory = new File(project.getBuild().getOutputDirectory());
if (getPackagePath().equals(outputDirectory)) {
getLog().debug("Directory [" + getPackagePath().getAbsolutePath() + "] does not exists. Nothing to do.");
return; // if it is a maven project which doesn't have a target
// folder, do nothing.
}
throw new MojoExecutionException("The folder [" + getPackagePath().getAbsolutePath() + "] does not exist.");
}
public File getPackagePath() {
if (packagePath.isAbsolute()) {
return packagePath;
}
return new File(project.getBasedir(), packagePath.getPath());
}
}
|
Python | UTF-8 | 2,064 | 2.59375 | 3 | [
"Apache-2.0"
] | permissive | #!python
# -*- coding: utf-8 -*-
"""
Helper functions for test cases in Pyhaystack
"""
# Assume unicode literals as per Python 3
from __future__ import unicode_literals
import hszinc
def grid_meta_cmp(msg, expected, actual):
errors = []
for key in set(expected.keys()) | set(expected.keys()):
if key not in expected:
errors.append('%s key %s unexpected' % (msg, key))
elif key not in actual:
errors.append('%s key %s missing' % (msg, key))
else:
ev = expected[key]
av = actual[key]
if ev != av:
errors.append('%s key %s was %r not %r' \
% (msg, key, av, ev))
return errors
def grid_col_cmp(expected, actual):
errors = []
for col in set(expected.keys()) | set(actual.keys()):
if col not in expected:
errors.append('unexpected column %s' % col)
elif col not in actual:
errors.append('missing column %s' % col)
else:
errors.extend(grid_meta_cmp('column %s' % col,
expected[col], actual[col]))
return errors
def grid_cmp(expected, actual):
assert isinstance(expected, hszinc.Grid), 'expected is not a grid'
assert isinstance(actual, hszinc.Grid), 'actual is not a grid'
errors = grid_meta_cmp('grid metadata',
expected.metadata, actual.metadata)
errors.extend(grid_col_cmp(expected.column, actual.column))
for idx in range(0, max(len(expected), len(actual))):
try:
erow = expected[idx]
except IndexError:
erow = None
try:
arow = actual[idx]
except IndexError:
arow = None
if erow is None:
errors.append('Unexpected row %d: %r' % (idx, arow))
elif arow is None:
errors.append('Missing row %d: %r' % (idx, erow))
else:
errors.extend(grid_meta_cmp('Row %d' % idx, erow, arow))
if errors:
assert False, 'Grids do not match:\n- %s' % ('\n- '.join(errors))
|
Python | UTF-8 | 5,114 | 2.640625 | 3 | [] | no_license | from flask import Response, json
import re, warnings
from .googlemovies import GoogleMovies
from .localization_functions import calculate_expiration_time
class MoviesEndpoint:
def __init__(self, near, days_from_now, use_military_time, local_time_cache, military_time_cache):
self.response = None
self.showtimes = None
self.mimetype = 'application/json'
self.local_time_cache = local_time_cache
self.military_time_cache = military_time_cache
# fail fast
if near is None:
self.status = 400
self.response = Response(json.dumps({'error': 'need to specify `near` parameter'}),
status=self.status,
mimetype=self.mimetype)
return None
self.near = near
if days_from_now is not None:
# if not None then request.args holds 'date' as a string and thus it needs to
# be case as an integer
try:
# google ignores negative dates, which means that the
# results for days_from_now = -1 will be the same as
# days_from_now = -7, which means there's no reason to cache
# these as different results.
days_from_now = int(days_from_now)
if days_from_now < 0:
days_from_now = 0
except ValueError:
self.status = 400
self.response = Response(json.dumps({'error': '`date` must be a base-10 integer'}),
status=self.status,
mimetype=self.mimetype)
return None
else:
days_from_now = 0
self.days_from_now = days_from_now
if use_military_time is not None and not use_military_time.lower() in ['true', 'false']:
self.status = 400
self.response = Response(json.dumps({'error': '`militaryTime` must be either true or false'}),
status=self.status,
mimetype=self.mimetype)
return None
elif use_military_time is None or use_military_time.lower() == 'false':
use_military_time = False
elif use_military_time.lower() == 'true':
use_military_time = True
self.use_military_time = use_military_time
self.create_cache_key()
def process_request(self):
# endpoint.response is not None if initialization errored in some way
if self.response:
return self.response
if self.get_showtimes_from_cache():
warnings.warn('Fetched results from cache with name: ' + self.cache_key)
return self.response
if self.get_showtimes_from_google():
return self.response
return "Something went terribly wrong... =("
def create_cache_key(self, sep=':'):
# The cache_key pattern is:
# near_normalize + sep + days_from_now
regexp = '[\s!@#$%^&*()_=+,<.>/?;:\'"{}\[\]\\|]*'
near_normalized = re.sub(regexp, '', self.near).lower()
self.cache_key = '%s%s%s' % (near_normalized, sep, self.days_from_now)
return self.cache_key
def get_showtimes_from_google(self):
try:
url = 'http://google.com/movies'
params = {
'near': self.near,
'date': self.days_from_now
}
self.googlemovies = GoogleMovies(url, params)
self.populate_caches()
self.showtimes = json.dumps(self.googlemovies.to_json(self.use_military_time))
self.status = 200
self.response = Response(self.showtimes, status=self.status, mimetype=self.mimetype)
except Exception as e:
warnings.warn(str(e))
self.status = 500 # server error
self.response = Response(json.dumps({'error': str(e)}), status=self.status, mimetype=self.mimetype)
return self.response
def populate_caches(self):
if self.cache_key:
cache_ex = calculate_expiration_time(self.near)
self.local_time_cache.set(name=self.cache_key,
value=json.dumps(self.googlemovies.to_json(use_military_time=False)),
ex=cache_ex)
self.military_time_cache.set(name=self.cache_key,
value=json.dumps(self.googlemovies.to_json(use_military_time=True)),
ex=cache_ex)
else:
return False
def get_showtimes_from_cache(self):
if self.use_military_time:
self.showtimes = self.military_time_cache.get(self.cache_key)
else:
self.showtimes = self.local_time_cache.get(self.cache_key)
if self.showtimes is None:
return None
self.status = 200
self.response = Response(self.showtimes, status=self.status, mimetype=self.mimetype)
return self
|
JavaScript | UTF-8 | 2,803 | 2.6875 | 3 | [
"MIT"
] | permissive |
import React, { useContext, useState } from 'react';
import { useHistory } from "react-router-dom";
import AuthContext from "../context/AuthContext.js";
import { Link } from 'react-router-dom';
import axios from "axios";
export default function Navbar() {
//username tab password login at the extreme right of navbar
const [ email, setEmail ] = useState('');
const [ password, setPassword ] = useState('');
const { loggedIn } = useContext(AuthContext);
const { getLoggedIn } = useContext(AuthContext);
const history = useHistory();
//event handling for login button
const handleFormSubmit = async (event) => {
event.preventDefault();
try {
const registerData = {
email, password,
};
await axios.post(
"http://localhost:3001/api/users/login",
registerData,
{ withCredentials: true }
);
await getLoggedIn();
history.push("/med-list");
} catch (err) {
console.error(err);
}
};
const handleLogOut = async (event) => {
await axios.get(
"http://localhost:3001/api/users/logout"
);
await getLoggedIn();
history.push("/");
}
return (
<nav className="navbar navbar-expand-lg App-header">
<Link className="navbar-brand" to="/"><strong>Pharm-Assist</strong></Link>
<button className="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
<span className="navbar-toggler-icon"></span>
</button>
<div className="collapse navbar-collapse" id="navbarSupportedContent">
<ul className="navbar-nav mr-auto">
{loggedIn === false && (
<li className="nav-item">
<Link className="navbar-brand" to="/sign-up">Sign Up</Link>
</li>
)}
{loggedIn === true && (
<li className="nav-item">
<Link className="navbar-brand" to="/med-list">Med List</Link>
</li>
)}
</ul>
{loggedIn === false && (
<form onSubmit={handleFormSubmit} className="d-flex">
<input type="text" className="form-control" id="inputUsername" placeholder="Email" onChange={(e) => setEmail(e.target.value)} value={email}/>
<input type="password" className="form-control" id="inputPassword4" placeholder="Password" onChange={(e) => setPassword(e.target.value)} value={password}/>
<button className="btn btn-outline-success" type="submit" >Login</button>
</form>
)}
{loggedIn === true && (
<button onClick={handleLogOut} className="btn btn-outline-success" type="submit">Log Out</button>
)}
</div>
</nav>
);
}
|
Markdown | UTF-8 | 10,217 | 3.359375 | 3 | [] | no_license | ---
layout: post
title: "О локаторах в общем"
date: 2017-02-27
---
Немного(или много) будем говорить о локаторах.
Итак, давайте начнем с основ. Для автоматизированного тестирования мы используем
Selenium WebDriver - драйвер, позволяющий писать программы для управления действиями
web браузера (Firefox, Chrome и т.д.) Взаимодействие с web драйвером выполняется путём
обращения к нему некоторыми методами, определяющими его действие. Например:
**findElement** - (поиск элемента на странице)
Так вот, Selenium WebDriver не умеет читать наши мысли, ему надо четко указать объект,
для которого необходимо применить то или иное действие.
Теперь о видах локаторов:
1) id=<element_id> - соответствует элементу, у которого атрибут id равен
значению element_id.
Например, у нас есть элемент, который в HTML записывается так:
<input type=text id='some_input_id' name='some_input_name' value='' />
В этом случае локатор будет иметь вид: id=some_input_id. Также следует отметить,
что данный вид локаторов является одним из самых быстрых в нахождении и одним из
самых уникальных. Это связано с тем, что в DOM-структуре ссылки на элементы, у
которых задан ID, хранятся в отдельной таблице и через JScript (собственно именно
через него осуществляется доступ к элементам на конечном уровне) обращение к
элементам по ID идет достаточно короткой инструкцией, наподобиеsome_input_id.
2) name=<element_name> - соответствует элементу, у которого атрибут name равен
значению element_name. Эффективно применяется при работе с полями ввода формы
(кнопки, текстовые поля, выпадающие списки). Как правило, значения элементов формы
используются в запросах, которые идут на сервер и как раз атрибут name в этих
запросах ставит в соответствие поле и его значение. Если брать предыдущий пример:
<input type=text id='some_input_id' name='some_input_name' value='' />
Данный элемент может быть также идентифицирован локатором вида name=some_input_name.
Этот тип локаторов тоже является достаточно быстрым в нахождении, но менее
уникальным, так как на странице может быть несколько форм, у которых могут быть
элементы с одинаковым именем.
3) link=<link_text> - специально для ссылок используется отдельно зарезервированный
тип локаторов, который находит нужную ссылку по ее тексту. Это сделано отчасти
потому, что ссылки как правило не имеют таких атрибутов как ID или name.
Соответственно, ссылка, которая в HTML записывается так:
<a href='http://some_url'>Link Text 2345</a>
В Selenium идентифицируется локатором link=Link Text 2345.
И небольшой частный случай:
У ссылки есть фиксированная часть и есть часть, которая может варьироваться.
Допустим, в предыдущем примере у нас число может варьироваться. В этом случае мы
можем использовать wildcards, в частности '*'. Мы можем идентифицировать ссылку
локатором вида: link=Link Text*
и данный локатор будет соответствовать первой ссылке, текст которой будет
начинаться с 'Link Text'.
4) xpath=<xpath_locator> - наиболее универсальный тип локаторов.
Как XPath формируется - HTML, как и его более обобщенная форма - XML, представляет
собой различное сочетание тегов, которые могут содержать вложенные теги, а те в
свою очередь тоже могут содержать теги и т.д. То есть ,выстраивается определенная
иерархия, наподобие структуры каталогов в файловой системе. И задача XPath -
отразить подобный путь к нужному элементу, с учетом иерархии. Например, XPath вида:
A/B/C/D указывает на некоторый элемент с тегом D, который находится внутри тега C,
а тот в свою очередь - внутри тега B, который находится внутри тега A, который
находится на самом верхнем уровне иерархии.
5) css=<css_path> - данный тип локаторов основан на описаниях таблиц стилей
(CSS), соответственно и синтаксис такой же. В отличие от локаторов по ID, по
имени или по тексту ссылки, данный тип локаторов может учитывать иерархию
объектов, а также значения атрибутов, что делает его ближайшим аналогом XPath.
А в силу того, что объект находится по данному локатору быстрее, чем XPath,
рекомендуется прибегать к помощи CSS вместо XPath.
Выглядит все это примерно вот так:
```
Java
WebElement form1 = driver.findElement(By.id("login-form"));
WebElement form2 = driver.findElement(By.tagName("form"));
WebElement form3 = driver.findElement(By.className("login"));
WebElement form4 = driver.findElement(By.cssSelector("form.login"));
WebElement form5 = driver.findElement(By.cssSelector("#login-form"));
WebElement field1 = driver.findElement(By.name("username"));
WebElement field2 = driver.findElement(By.xpath("//input[@name='username']"));
WebElement link = driver.findElement(By.linkText("Logout"));
List<WebElement> links = driver.findElements(By.tagName("a"));
```
Для CSS и XPath есть отличные, такие подсказки как выбрать тот или иной локатор.
<object data="{{ site.url }}/pict/locators/1269-Locators_groups_1_0_2.pdf" width="1100px" height="885px">
<embed src="{{ site.url }}/pict/locators/1269-Locators_groups_1_0_2.pdf">
This browser does not support PDFs. Please download the PDF to view it: <a href="{{ site.url }}/pict/locators/1269-Locators_groups_1_0_2.pdf">Download PDF</a>.</p>
</embed>
</object>
<object data="{{ site.url }}/pict/locators/1269-Locators_table_1_0_2.pdf" width="1100px" height="885px">
<embed src="{{ site.url }}/pict/locators/1269-Locators_table_1_0_2.pdf">
This browser does not support PDFs. Please download the PDF to view it: <a href="{{ site.url }}/pict/locators/1269-Locators_table_1_0_2.pdf">Download PDF</a>.</p>
</embed>
</object>
<object data="{{ site.url }}/pict/locators/css3-cheat-sheet.pdf" width="1100px" height="885px">
<embed src="{{ site.url }}/pict/locators/css3-cheat-sheet.pdf">
This browser does not support PDFs. Please download the PDF to view it: <a href="{{ site.url }}/pict/locators/css3-cheat-sheet.pdf">Download PDF</a>.</p>
</embed>
</object>
Но это была теория которую тоже надо знать а теперь немного практики.
Локатор можно выбрать с помощю SeleniumIDE в FireFox-e если совсем туго вначале.
Просто запускаем селениум и кликаем на элемент локатор которого хотим выбрать и в
СеленуимИДЕ можно посмотреть разного рода локаторы того по чему мы кликнули.
Вот так например выглядят локаторы кнопки "Поиск в Google"

Ну, а что бы правильно и безошибочно начать их выбирать. Это как говорится только через
"Опыт - сын ошибок трудных" ))
Ну удачи мне в этом деле ;)
|
C# | UTF-8 | 7,263 | 2.859375 | 3 | [] | no_license | namespace SQLDAL
{
using IDAL;
using System.Data;
using System.Data.SqlClient;
using System.Text;
/// <summary>
/// 数据访问类:ContactGroup
/// </summary>
public partial class ContactGroup : IContactGroup
{
/// <summary>
/// Initializes a new instance of the <see cref="ContactGroup"/> class.
/// </summary>
public ContactGroup()
{
}
/// <summary>
/// The GetList
/// </summary>
/// <param name="strWhere">The strWhere<see cref="string"/></param>
/// <returns>The <see cref="DataTable"/></returns>
public DataTable GetList(string strWhere)
{
StringBuilder strSql = new StringBuilder();
strSql.Append("select Id,GroupName,Memo ");
strSql.Append(" FROM ContactGroup ");
if (strWhere.Trim() != "")
{
strSql.Append(" where " + strWhere);
}
return SqlDbHelper.ExecuteDataTable(strSql.ToString());
}
/// <summary>
/// 增加一条数据
/// </summary>
/// <param name="model">The model<see cref="Model.ContactGroup"/></param>
/// <returns>The <see cref="bool"/></returns>
public bool Add(Model.ContactGroup model)
{
StringBuilder strSql = new StringBuilder();
strSql.Append("insert into ContactGroup(");
strSql.Append("GroupName,Memo)");
strSql.Append(" values (");
strSql.Append("@GroupName,@Memo)");
strSql.Append(";select @@IDENTITY");
SqlParameter[] parameters = {
new SqlParameter("@GroupName", SqlDbType.NVarChar,50),
new SqlParameter("@Memo", SqlDbType.NVarChar,200)};
parameters[0].Value = model.GroupName;
parameters[1].Value = model.Memo;
int rows = SqlDbHelper.ExecuteNonQuery(strSql.ToString(), CommandType.Text, parameters);
if (rows > 0)
{
return true;
}
else
{
return false;
}
}
/// <summary>
/// The GetModel
/// </summary>
/// <param name="Id">The Id<see cref="int"/></param>
/// <returns>The <see cref="Model.ContactGroup"/></returns>
public Model.ContactGroup GetModel(int Id)
{
StringBuilder strSql = new StringBuilder();
strSql.Append("select top 1 Id,GroupName,Memo from ContactGroup ");
strSql.Append(" where Id=@Id");
SqlParameter[] parameters = {
new SqlParameter("@Id", SqlDbType.Int,4)
};
parameters[0].Value = Id;
Model.ContactGroup model = new Model.ContactGroup();
DataTable dt = SqlDbHelper.ExecuteDataTable(strSql.ToString(), CommandType.Text, parameters);
if (dt.Rows.Count > 0)
{
if (dt.Rows[0]["Id"] != null && dt.Rows[0]["Id"].ToString() != "")
{
model.Id = int.Parse(dt.Rows[0]["Id"].ToString());
}
if (dt.Rows[0]["GroupName"] != null && dt.Rows[0]["GroupName"].ToString() != "")
{
model.GroupName = dt.Rows[0]["GroupName"].ToString();
}
if (dt.Rows[0]["Memo"] != null && dt.Rows[0]["Memo"].ToString() != "")
{
model.Memo = dt.Rows[0]["Memo"].ToString();
}
return model;
}
else
{
return null;
}
}
/// <summary>
/// The GetModel
/// </summary>
/// <param name="groupName">The groupName<see cref="string"/></param>
/// <returns>The <see cref="Model.ContactGroup"/></returns>
public Model.ContactGroup GetModel(string groupName)
{
StringBuilder strSql = new StringBuilder();
strSql.Append("select top 1 Id,GroupName,Memo from ContactGroup ");
strSql.Append(" where GroupName=@GroupName");
SqlParameter[] parameters = {
new SqlParameter("@GroupName", SqlDbType.NVarChar,50)
};
parameters[0].Value = groupName;
Model.ContactGroup model = new Model.ContactGroup();
DataTable dt = SqlDbHelper.ExecuteDataTable(strSql.ToString(), CommandType.Text, parameters);
if (dt.Rows.Count > 0)
{
if (dt.Rows[0]["Id"] != null && dt.Rows[0]["Id"].ToString() != "")
{
model.Id = int.Parse(dt.Rows[0]["Id"].ToString());
}
if (dt.Rows[0]["GroupName"] != null && dt.Rows[0]["GroupName"].ToString() != "")
{
model.GroupName = dt.Rows[0]["GroupName"].ToString();
}
if (dt.Rows[0]["Memo"] != null && dt.Rows[0]["Memo"].ToString() != "")
{
model.Memo = dt.Rows[0]["Memo"].ToString();
}
return model;
}
else
{
return null;
}
}
/// <summary>
/// The Delete
/// </summary>
/// <param name="Id">The Id<see cref="int"/></param>
/// <returns>The <see cref="bool"/></returns>
public bool Delete(int Id)
{
StringBuilder strSql = new StringBuilder();
strSql.Append("delete from ContactGroup ");
strSql.Append(" where Id=@Id");
SqlParameter[] parameters = {
new SqlParameter("@Id", SqlDbType.Int,4)
};
parameters[0].Value = Id;
int rows = SqlDbHelper.ExecuteNonQuery(strSql.ToString(), CommandType.Text, parameters);
if (rows > 0)
{
return true;
}
else
{
return false;
}
}
/// <summary>
/// The Update
/// </summary>
/// <param name="model">The model<see cref="Model.ContactGroup"/></param>
/// <returns>The <see cref="bool"/></returns>
public bool Update(Model.ContactGroup model)
{
StringBuilder strSql = new StringBuilder();
strSql.Append("update ContactGroup set ");
strSql.Append("GroupName=@GroupName,");
strSql.Append("Memo=@Memo");
strSql.Append(" where Id=@Id");
SqlParameter[] parameters = {
new SqlParameter("@GroupName", SqlDbType.NVarChar,50),
new SqlParameter("@Memo", SqlDbType.NVarChar,200),
new SqlParameter("@Id", SqlDbType.Int,4)};
parameters[0].Value = model.GroupName;
parameters[1].Value = model.Memo;
parameters[2].Value = model.Id;
int rows = SqlDbHelper.ExecuteNonQuery(strSql.ToString(), CommandType.Text, parameters);
if (rows > 0)
{
return true;
}
else
{
return false;
}
}
}
}
|
Shell | UTF-8 | 204 | 3.28125 | 3 | [] | no_license | #!/bin/bash
echo "Enter any file name:"
read -p "FileName:" fname
echo "----------------checking-----------------"
sleep 2
if [ -e /root/$fname ]
then
echo "File exists"
else
echo "File not exists"
fi
|
Python | UTF-8 | 170 | 3.03125 | 3 | [] | no_license | import tkinter
def main():
#Create a root window
root = tkinter.Tk ()
#Call the event loop
root.mainloop ()
#Call the function main main()
main() |
JavaScript | UTF-8 | 1,575 | 2.609375 | 3 | [] | no_license | // Import
import React from 'react';
// Local import
// Code
class Header extends React.Component {
// Lifecycle
componentDidMount() {
this.props.actions.loadHeader();
this.checkLogin();
}
checkLogin = () => {
if(localStorage.getItem('username')){
let username = localStorage.getItem('username');
let email = localStorage.getItem('email');
let user = {'username': username, 'email': email};
this.props.actions.checkLogin(user);
}
}
logout = e => {
e.preventDefault();
localStorage.removeItem('username');
localStorage.removeItem('email');
this.props.history.push('/');
}
render() {
const menus = this.props.menus ?
this.props.menus.map((menu, index) => (<a href="/" key={index}>{menu.menu_name}</a>))
:
null
const userConnected = this.props.user == 'guest' ?
<div className="sign-container"><a href="/signup">Sign up</a><a href="/signin">Sing in</a></div>
:
<div className="sign-container"><a href="/account">Account</a><a href="" onClick={this.logout}>Log out</a> <span>Hello {this.props.username}!</span></div>
return (
<div>
<div className="header-container">
<div className="logo-container">
<img src="images/1.jpg" alt="club-logo" />
</div>
<div className="menu-container">
{menus}
{userConnected}
</div>
</div>
</div>
)
}
}
// Export
export default Header;
|
Java | UTF-8 | 891 | 2.015625 | 2 | [] | no_license | package spring.boot.first.mvc.controller;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;
import spring.boot.first.dao.dbOrder.po.Order;
import spring.boot.first.service.service.OrderService;
@RestController
@RequestMapping("/order")
public class OrderController {
@Autowired
private OrderService orderService;
//http://localhost:9090/order/findAll
@RequestMapping("/findAll")
public ModelAndView findAll(){
ModelAndView mv = new ModelAndView();
List<Order> orderList = orderService.findAll();
mv.setViewName("order/findAll");
mv.addObject("orderList", orderList);
return mv;
}
}
|
Swift | UTF-8 | 1,264 | 3.234375 | 3 | [] | no_license | //
// Game.swift
// NumberBaseball
//
// Created by Changhyun Paik on 2020/07/06.
// Copyright © 2020 Changhyun Baek. All rights reserved.
//
class Game {
private(set) var inning: Inning
private(set) var answer: Answer
private(set) var totalInning: Int = 9
private(set) var inningCount: Int = 1
private(set) var gameResult: Bool = false
private var inningResult: (strikeCount: Int, ballCount: Int) = (strikeCount: 0, ballCount: 0)
var inningResultString: String {
"\(inningResult.strikeCount)S \(inningResult.ballCount)B"
}
var isOver: Bool {
inningResult.strikeCount == 3 || (inningCount == totalInning && inning.isEnded)
}
init() {
self.inning = Inning()
self.answer = Answer()
}
func pitchABall(pitchNumber: Int) {
guard
inning.pitching.contains(pitchNumber) == false,
isOver == false
else { return }
inning.pitching.append(pitchNumber)
if inning.isEnded {
inningResult = answer.judgePitching(inning: inning)
if inningResult.strikeCount == 3 {
gameResult = true
}
}
}
func startNextInning() {
inningCount += 1
inning = Inning()
}
}
|
C++ | UTF-8 | 1,461 | 3.515625 | 4 | [] | no_license |
// Print a given linked list in reverse order. Tail first. You cant change any pointer in the linked list
#include <iostream>
#include<bits/stdc++.h>
class node{
public:
int data;
node * next;
node(int data){
this->data=data;
this->next=NULL;
}
};
using namespace std;
// #include "solution.h"
pair<node* , node*> revhelper(node* head)
{
if(head == NULL || head -> next == NULL)
{
pair <node* , node*>p1;
p1.first = head;
p1.second = head;
return p1;
}
pair <node* , node*> smallAns = revhelper(head -> next);
smallAns.second -> next = head;
head -> next = NULL;
smallAns.second = head;
return smallAns;
}
node*rev(node*head)
{
//write your code here
pair<node* , node*> p1 = revhelper(head);
return p1.first;
}
node* takeinput(){
int data;
cin>>data;
node* head=NULL,*tail=NULL;
while(data!=-1){
node *newnode=new node(data);
if(head==NULL) {
head=newnode;
tail=newnode;
}
else{
tail->next=newnode;
tail=newnode;
}
cin>>data;
}
return head;
}
void print(node *head)
{
node*temp=head;
while(temp!=NULL)
{
cout<<temp->data<<" ";
temp=temp->next;
}
cout<<endl;
}
int main()
{
node*head=takeinput();
node* revhead = rev(head);
print(revhead);
return 0;
}
|
Python | UTF-8 | 254 | 3.84375 | 4 | [] | no_license | # Project Euler | Problem 20 | Jacob Waters
# Find the sum of the digits in the number 100!
# 648
# date : 2015.07.20
import math
def factorialDigitSum(n):
return sum([int(i) for i in str(math.factorial(n))])
print factorialDigitSum(100)
|
Markdown | UTF-8 | 2,363 | 2.828125 | 3 | [
"CC-BY-4.0",
"MIT"
] | permissive | ---
title: Can't add a DHCP reservation that is outside of the scope distribution range
description: Provides a solution to an issue where you can't add a DHCP reservation that is outside of the scope distribution range.
ms.date: 05/12/2021
author: Deland-Han
ms.author: delhan
manager: dcscontentpm
audience: itpro
ms.topic: troubleshooting
ms.prod: windows-server
localization_priority: medium
ms.reviewer: kaushika, btoth, miodon, joelch
ms.prod-support-area-path: Dynamic Host Configuration Protocol (DHCP)
ms.technology: networking
---
# You cannot add a DHCP reservation that is outside of the scope distribution range in Windows Server
This article provides a solution to an issue where you can't add a DHCP reservation that is outside of the scope distribution range.
_Applies to:_ Windows Server 2012 R2
_Original KB number:_ 2005980
## Symptoms
In Windows Server, you cannot add a reservation using the Dynamic Host Configuration Protocol (DHCP) MMC or netsh commands if the reservation is outside of the distribution range of the DHCP scope, even if it falls in the subnet defined by the subnet mask of the scope.
Example
Scope: 10.10.0.0
Distribution Range: 10.10.1.21-10.10.1.230
Subnet Mask: 255.255.254.0
Reservation: 10.10.0.164
Adding the IP address 10.10.0.164 will fail. The message that will be displayed is:
> The specified DHCP client is not a reserved client
## Cause
When adding a new reservation, the DHCP server checks if the IP address is within the defined distribution range of the scope.
## Resolution
This is by design. If the DHCP scope range does not cover the whole subnet defined by the subnet mask, you cannot add a reservation outside of the configured range. You can, however, extend the distribution range so that the whole subnet is covered, and specify the reservation after this step. If you do not want to distribute addresses from the whole subnet, you can also define an exclusion range. A reservation that falls into an exclusion range will still work.
## More information
Adding a reservation that is outside of the distribution range of a scope was possible in Windows Server 2003 and Windows Server 2008.
However, this is considered to be an invalid configuration and as such, the behavior has been changed so that it isn't possible anymore to create such a reservation.
|
C | UTF-8 | 338 | 3.71875 | 4 | [] | no_license | #include <stdio.h>
int factorial(int a){
if (a == 1 || a == 0)
{
return 1;
}else if (a%2 == 0)
{
return a/2 * factorial(a-1);
}else
{
return a * factorial(a-1);
}
}
int main(){
int a;
scanf("%d", &a);
printf("%d\n", factorial(a));
return 0;
} |
Python | UTF-8 | 907 | 3.34375 | 3 | [] | no_license | dayWords = ["first", "second", "third", "fourth", "fifth", "sixth", "seventh", "eighth", "ninth", "tenth", "eleventh", "twelfth"]
countWords = ["a", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten", "eleven", "twelve"]
items = [
"Partridge in a Pear Tree",
"Turtle Doves",
"French Hens",
"Calling Birds",
"Gold Rings",
"Geese-a-Laying",
"Swans-a-Swimming",
"Maids-a-Milking",
"Ladies Dancing",
"Lords-a-Leaping",
"Pipers Piping",
"Drummers Drumming"
]
def verse(number):
lyrics = "On the %s day of Christmas my true love gave to me, " % (dayWords[number - 1])
for i in range(number)[:0:-1]:
lyrics += "%s %s, " % (countWords[i], items[i])
if (number > 1):
lyrics += "and "
lyrics += "%s %s.\n" % (countWords[0], items[0])
return lyrics
def verses(start, end):
return '\n'.join(map(verse, range(start, end + 1))) + "\n"
def sing():
return verses(1, 12)
|
Java | UTF-8 | 690 | 1.890625 | 2 | [] | no_license | package com.yhf.xuedaoqian.dao;
import com.yhf.xuedaoqian.model.Leave;
import com.yhf.xuedaoqian.model.reps.LeaveReps;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import java.util.List;
/**
* @author yaohengfeng
* @version 1.0
* @date 2020/3/25 11:16
*/
@Mapper
public interface LeaveDao {
void insertLeave(Leave leave);
void updateLeave(Leave leave);
Leave selectLeaveByLeaveId(String leaveId);
List<Leave> selectLeaveByUserId(@Param("studentId") String studentId,@Param("classId") String classId);
List<LeaveReps> selectLeaveByUserId1(String studentId);
List<Leave> selectLeaveByClassId(String classId);
}
|
Markdown | UTF-8 | 754 | 3.15625 | 3 | [] | no_license | ## 文法
https://www.shido.info/lisp/scheme5.html
### if
```scheme
(define (method i)
(if (= i 1)
i
(* i 2)))
```
### let
第1引数が名前と内容のペアのリスト
第2引数の処理内で↑がバインドされる
```scheme
(define (method i)
(let(
(one 1)
(two 2))
display (+ one two i)))
```
### cond
条件とreturnのペアのリスト
elseあり
```scheme
(define (method i)
(cond ((= i 1) "one!")
((= i 2) "two!")
(else "not one or two!")))
```
### lambda
lambda
```scheme
(lambda (x) (* x x))
```
### begin
begin は与えられた式を前から順番に評価していき、最後の式の値を返します。
### map
```scheme
(map (lambda (x) (* x x) (list 1 2 3)))
```
|
Shell | UTF-8 | 308 | 3.25 | 3 | [] | no_license | #!/bin/bash
stake=100
goal=200
bets=1
won=0
numberOfBet=0
while [[ $stake -lt $goal && $stake -ge $bets ]]
do
numberOfBet=$(($numberOfBet+1))
if [ $((RANDOM%2)) -eq 1 ]
then
stake=$(($stake+$bets))
won=$(($won+1))
else
stake=$(($stake-$bets))
fi
done
echo won = $won
echo number of bet made = $numberOfBet
|
Python | UTF-8 | 193 | 3.734375 | 4 | [] | no_license | print ('====== DESAFIO 05 ======')
n = int(input('Digite um número: '))
a = n - 1
s = n + 1
print('Analisando o valor, podemos ver que seu antecessor é {} e seu sucessor é {}' .format(a, s)) |
Java | UTF-8 | 815 | 3.015625 | 3 | [] | no_license | /**
*
*/
package com.bridgelabz.designpattern.Observerdesignpatern;
/*************************************************************************************************************
*
* purpose:
*
* @author sowjanya467
* @version 1.0
* @since -05-17
*
* **************************************************************************************************/
public class MyTopicSubscriber implements Observer
{
private String name;
private Subject topic;
public MyTopicSubscriber(String nm){
this.name=nm;
}
@Override
public void update() {
String msg = (String) topic.getUpdate(this);
if(msg == null){
System.out.println(name+":: No new message");
}else
System.out.println(name+":: Consuming message::"+msg);
}
@Override
public void setSubject(Subject sub) {
this.topic=sub;
}
}
|
JavaScript | UTF-8 | 385 | 3.796875 | 4 | [] | no_license | (function() {
/*
* method invocation 实际上也是一个 property access expression,
* 因此即可以使用(.), 也可以使用([]);
*/
console.log("\n-------------------------------------------------- 01");
const obj01 = {
x: function fn01() {
console.log(this === obj01);
}
};
/* true */
obj01.x();
/* true */
obj01["x"]();
})();
|
C | UTF-8 | 1,276 | 2.765625 | 3 | [] | no_license | #include "czmq.h"
static int s_timer_event (zloop_t *loop, zmq_pollitem_t *item, void *output)
{
zstr_send (output, "PING");
return 0;
}
static int s_socket_event (zloop_t *loop, zmq_pollitem_t *item, void *arg)
{
// Just end the reactor
return -1;
}
void izloop_test (bool verbose)
{
printf (" * zloop: ");
int rc = 0;
// @selftest
zctx_t *ctx = zctx_new ();
assert (ctx);
void *output = zsocket_new (ctx, ZMQ_PAIR);
assert (output);
zsocket_bind (output, "tcp://*:6565");
void *input = zsocket_new (ctx, ZMQ_PAIR);
assert (input);
zsocket_connect (input, "tcp://localhost:6565");
zloop_t *loop = zloop_new ();
assert (loop);
zloop_set_verbose (loop, verbose);
// After 10 msecs, send a ping message to output
zloop_timer (loop, 10, 1, s_timer_event, output);
fprintf(stderr, "pinged");
// When we get the ping message, end the reactor
zmq_pollitem_t poll_input = { input, 0, ZMQ_POLLIN };
rc = zloop_poller (loop, &poll_input, s_socket_event, NULL);
assert (rc == 0);
zloop_start (loop);
zloop_destroy (&loop);
assert (loop == NULL);
zctx_destroy (&ctx);
// @end
printf ("OK\n");
}
int main( void )
{
izloop_test(true);
return 0;
}
|
Python | UTF-8 | 242 | 2.921875 | 3 | [] | no_license | read = lambda: eval(input())
read_line = lambda: [int(x) for x in input().split(',')]
ns = read_line()
for i in range(len(ns)):
if (not i or ns[i] > ns[i - 1]) and (i == len(ns) - 1 or ns[i] > ns[i + 1]):
print(i)
exit(0) |
Python | UTF-8 | 331 | 4.40625 | 4 | [] | no_license | # -*- coding: utf-8 -*-
"""
Created on Thu May 21 16:03:20 2020
輸入一個字元, 判斷是大寫或小寫或是其他字元
@author: ASUS
"""
ch = (input('輸入一個字元:'))
asc=ord(ch)
if asc >= 65 and asc <= 90:
print('大寫')
elif asc >=97 and asc <=122:
print('小寫')
else:
print('請輸入英文字母') |
PHP | UTF-8 | 4,246 | 3.15625 | 3 | [] | no_license | <?php
namespace App;
class Message{
// customer name
private $name;
// customer email address
private $email;
// customer phone number
private $phone;
// customer message body
private $content;
// customer email recipient
private $recipient;
// customer email body
protected $email_body;
function __construct() {
$this->recipient = "guy-smiley@example.com";
$this->email_body = '<div>';
$this->phone = 'N/A';
$this->content = '';
$this->email = 'N/A';
$this->name = 'N/A';
}
public function getName()
{
return $this->name;
}
public function getEmail()
{
return $this->email;
}
public function getPhone()
{
return $this->phone;
}
public function getConent()
{
return $this->content;
}
public function getMessage()
{
return $this->content;
}
public function getRecipient()
{
return $this->recipient;
}
public function setName($name)
{
$this->name = filter_var($name, FILTER_SANITIZE_STRING);
if(strlen($this->getName()) == 0){
return false;
}
$this->setEmailBody('Customer Name', $this->getName());
return true;
}
public function setEmail($email)
{
$email = str_replace(array("\r", "\n", "%0a", "%0d"), '', $email);
$this->email = filter_var($email, FILTER_VALIDATE_EMAIL);
if($this->getEmail() == false){
return false;
}
$this->setEmailBody('Customer Email', $this->getEmail());
return true;
}
public function setPhone($phone)
{
$phone = preg_replace('/[^0-9]/', '', $phone);
$this->phone = filter_var($phone, FILTER_SANITIZE_NUMBER_INT);
$this->setEmailBody('Customer Phone', $this->getPhone());
}
public function setMessage($message)
{
$this->content = htmlspecialchars($message);
$this->setEmailBody('Message', $this->getMessage());
}
public function setEmailBody($name, $value)
{
$this->email_body .= "<div><label><b>".$name.":</b></label> <span>".$value."</span></div>";
}
public function setRecipient($recipient)
{
$this->recipient = $recipient;
}
public function getEmailBody()
{
return $this->email_body."</div>";
}
// have test plan with
// function setUp() { $this->db->exec("BEGIN"); }
// function tearDown() { $this->db->exec("ROLLBACK"); }
// but will failed phpunit command if does not change database configuration
// so leave it for now
public function saveMessage($conn)
{
// thie query also included in public folder
$sql = "CREATE TABLE IF NOT EXISTS message_log(
id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(50) NOT NULL,
email VARCHAR(50),
phone VARCHAR(20),
message TEXT,
created_by TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
)";
if ($conn->query($sql) === TRUE) {
$sql2 = "INSERT INTO message_log (name, email, phone, message) VALUES('".$this->getName()."','".$this->getEmail()."','".$this->getPhone()."','".$this->getMessage()."')";
$conn->query($sql2);
} else {
return "Error: " . $sql . "<br>" . $conn->error;
}
}
// unable to test this part in local machine
public function sendEmail($recipient = "guy-smiley@example.com")
{
$this->setRecipient($recipient);
// build header of email
$headers = 'MIME-Version: 1.0' . "\r\n"
.'Content-type: text/html; charset=utf-8' . "\r\n"
.'From: ' . $this->getEmail() . "\r\n";
// build title of email
$email_subject = 'Customer Message From '.$this->getName();
// send email
if(mail($this->getRecipient(), $email_subject, $this->getEmailBody(), $headers)) {
return "<p>Thank you for contacting Guy Smiley , ".$this->getName()."</p>";
} else {
return '<p>We are sorry but the email did not go through.</p>';
}
}
} |
C# | UTF-8 | 5,733 | 3.640625 | 4 | [] | no_license | using System;
namespace Extensions
{
/// <summary>
/// Algorithms of finding the greatest common divisor with delegate using.
/// </summary>
public static class EuclideanAlgorithmsRefactoring
{
/// <summary>
/// Delegate
/// </summary>
/// <param name="a"></param>
/// <param name="b"></param>
/// <returns></returns>
public delegate int GCD(int a, int b);
/// <summary>
/// Euclidian's algorithm to find GCD of 2 or more numbers.
/// </summary>
/// <param name="input">Numbers to find greatest common divisor.</param>
/// <returns>The greatest common divisor of presented numbers.</returns>
public static int FindEuclideanGCD(int[] input)
{
return GcdBasic(FindEuclideanGCDForTwoNumbers, input);
}
/// <summary>
/// Stein's algorithm to find GCD of 2 or more numbers.
/// </summary>
/// <param name="input">Numbers to find greatest common divisor.</param>
/// <returns>The greatest common divisor of presented numbers.</returns>
public static int FindSteinsGCD(int[] numbers)
{
return GcdBasic(FindSteinsGCDForTwoNumbers, numbers);
}
/// <summary>
/// Helps to finding GDC of all elements.
/// </summary>
/// <param name="gcdOfTwoNum">GDC of two elements.</param>
/// <param name="input">Numbers to find greatest common divisor.</param>
/// <returns>The greatest common divisor of presented numbers.</returns>
private static int GcdBasic(GCD gcdOfTwoNum, int[] input)
{
ThrowingNullExceptions(input, "No array has been given.");
ThrowingOutOfRangeException(input, "There must be two or more arguments.");
int currentGCD = 0;
currentGCD = gcdOfTwoNum(input[0], input[1]);
for (int k = 2; k < input.Length; k++)
{
currentGCD = gcdOfTwoNum(currentGCD, input[k]);
}
return currentGCD;
}
#region Methods for the delegate
/// <summary>
/// Finds GCD of 2 numbers by Euclidian's algorithm. The method contains information for the delegate.
/// </summary>
/// <param name="firstNum">The first number.</param>
/// <param name="secondNum">The second number.</param>
/// <returns>The greatest common divisor of two numbers.</returns>
private static int FindEuclideanGCDForTwoNumbers(int firstNum, int secondNum)
{
firstNum = Math.Abs(firstNum);
secondNum = Math.Abs(secondNum);
if (firstNum == 0)
{
return secondNum;
}
if (secondNum == 0)
{
return firstNum;
}
while (firstNum != secondNum)
{
if (firstNum > secondNum)
{
firstNum = firstNum - secondNum;
}
else
{
secondNum = secondNum - firstNum;
}
}
return firstNum;
}
/// <summary>
/// Finds GCD of 2 numbers by Stein's algorithm. The method contains information for the delegate.
/// </summary>
/// <param name="firstNum">The first number.</param>
/// <param name="secondNum">The second number.</param>
/// <returns>The greatest common divisor of two numbers.</returns>
private static int FindSteinsGCDForTwoNumbers(int firstNum, int secondNum)
{
firstNum = Math.Abs(firstNum);
secondNum = Math.Abs(secondNum);
if (firstNum == secondNum)
{
return firstNum;
}
if (firstNum == 0 || secondNum == 0)
{
return firstNum | secondNum;
}
if ((~firstNum & 1) != 0)
{
if ((secondNum & 1) != 0)
{
return FindSteinsGCDForTwoNumbers(firstNum >> 1, secondNum);
}
return FindSteinsGCDForTwoNumbers(firstNum >> 1, secondNum >> 1) << 1;
}
if ((~secondNum & 1) != 0)
{
return FindSteinsGCDForTwoNumbers(firstNum, secondNum >> 1);
}
if (firstNum > secondNum)
{
return FindSteinsGCDForTwoNumbers((firstNum - secondNum) >> 1, secondNum);
}
return FindSteinsGCDForTwoNumbers((secondNum - firstNum) >> 1, firstNum);
}
#endregion
/// <summary>
/// Throwing null exception in case of unforeseen consequence.
/// </summary>
/// <param name="array">Array witch can couse an exception.</param>
/// <param name="message">Message to be show.</param>
private static void ThrowingNullExceptions(int[] array, string message)
{
if (array is null)
{
throw new ArgumentNullException(message);
}
}
/// <summary>
/// Throwing out of range exception in case of unforeseen consequence.
/// </summary>
/// <param name="array">Array witch can couse an exception.</param>
/// <param name="message">Message to be show.</param>
private static void ThrowingOutOfRangeException(int[] array, string message)
{
if (array.Length < 2)
{
throw new ArgumentOutOfRangeException();
}
}
}
}
|
Markdown | UTF-8 | 944 | 4 | 4 | [] | no_license | ## Detail
[Happy^^ numbers](https://www.codewars.com/kata/happy-numbers-2/train/haskell)
A happy number is a number defined by the following process: Starting with any positive integer, replace the number by the sum of the squares of its digits, and repeat the process until the number equals 1 (where it will stay), or it loops endlessly in a cycle which does not include 1. Those numbers for which this process ends in 1 are happy numbers, while those that do not end in 1 are unhappy numbers (or sad numbers) (Wikipedia).
For example number 7 is happy because after a number of steps the computed sequence ends up with a 1: `[7,49,97,130,10,1]`
while 3 is not, and would give us an infinite sequence.
`[3,9,81,65,61,37,58,89,145,42,20,4,16,37,58,89,145,42,20,4,16,37 ...`
Write a function that takes n as parameter and return true if and only if n is an happy number.
Happy coding!
## Thinking
Unhappy numbers always contains **4**. |
Markdown | UTF-8 | 11,248 | 2.65625 | 3 | [] | no_license | title: Как знакомиться с девушкой
{align=right width=200}
Прочитаешь статью, и понимаешь, что ты должен быть чуть ли не идеалом в общении с девушкой, что вся вина лежит исключительно на парне. Ощущение, что статья написана женщиной для манипуляции мужчиной. Женщина выставлена в выгодном свете с любой стороны, тебе надо ты и пиши, а это мое дело, отвечать тебе или нет. Мне это напоминает, как короли себе шута горохового выбирали, тот скучный – отсечь голову, тот слишком умный – повесить, тот сильно уродлив – убрать. А вот этот сойдет для шута. Вот так вот и в отношениях с девушкой, выбирает себе королева шута горохового, который будет ее носить на руках, и в замен ничего не прося.
Тем более сейчас мы живем в мире материализма, и в этом мире очень хорошо живется женщинам в первую очередь – потребительство без производства. Да хоть будь ты идеалом во всех отношениях с девушкой, всё равно она выберет себе другого, кто ей будет больше выгоден, потому что это баба. Что с одной сработает, то с другой нет. Если тратит столько времени на то как правильно общаться с девушкой, что ей говорить, как это говорить, как ее соблазнять, как правильно прикасаться, много практиковаться, много читать. Извините, а где же взять время на зарабатывание денег?….кто будет строить карьеру?
---
Да не все и хотят. Большинство девушек хотят дойти домой незаметными. Нормальные мужчины не подходят знакомиться, ибо трусы с полным чемоданном комплексов, а подходят какие то мудилы. И после этих мудил о каких улыбках и милых речах может идти речь? Каждый мужик воспринимается как агрессор и опасность для жизни. Мою подругу ударили в голову со спины, после того как она на ответ : "давай познакомимся", ответила " не интересно". Сзади ударил главное, как шакал. А потом, когда она пришла в себя, еще и второй раз. Ублюдки конченные. Ладно , что девушки и так слабы физически и на все дерьмо излитое мужиками должны молча терпеть, ибо на неправильное слово или жест ранимый мужик взбесится, как истеричка, и приложит свой кулак к обидчице его миниатюрного достоинства! Были бы девушки равны по силе, было бы в мире меньше мудил, которые самоутверждаются на слабых, ибо больше нечем выделиться.
---
Учитесь,щеглы.Зацепился глаз за девушку то,если будешь стоять и рассуждать как,когда подойти,что сказать,а что она ответит,а что люди подумают-разворачивайся и уходи,слабак.Делай так:только в голове щелкнуло,, классная"сразу команда -на лицо улыбку ноги вперёд,как только подойдёшь там уже автоматом все пойдет само.Правда при этом нужно быть посмелее,иметь широкий словарный запас и кругозор но это уже твои проблемы.А успокаивать себя тем,что да ладно с этой не получилось при этом не сделав даже шага в ее сторону и мечтать,что вот если бы она сама комне подошла да я б для нее-у тебя тогда только один выбор с какой рукой ты сегодня спать будешь,правой или левой.Да,если сильно зацепило но с первого раза отказ то повторяй,некоторые любят поломаться.
---
Надо знакомиться так , как я это делал ; подхожу , смотрю в глаза , говорю ей Привет ! 👋😊 Спрашиваю как её зовут ? Если ли у неё парень , если есть , смеюсь и говорю ей такую фразу ; Предупреждать надо ! 😀 Девушка , а , может вы шутите !? Чем я хуже того парня ?! Может все таки познакомимся по - ближе , не стесняйтесь , я вас не укушу , сам боюсь ! Если я вам не понравлюсь , скроюсь за горизонтом , и вы , меня , больше никогда никогда не увидите ! Будет оч жаллль ! 😕😉 А , может вы куда то торопитесь ? Можно я вас провожу ? Если опять облом , и , все же , говорит , что у нее действительно есть парень ... Прощаюсь так ; простите , точно не знал , просто , хотел убедиться ... И все же , вы оч хорошенькая ! Я бы мог продолжить с вами общение , но , боюсь что меня побьет ваш любимый . Пока Пока ! 👋😉 Скрываюсь за горизонтом ! Если предлагает проводить , то парня , точно нет ! Беру её за руку , и , чапаю с ней до места , по ходу , покупаю цветочки . А там , все по плану ; ) ✊😉😂😂😂
---
мне как подойти так и начать разговор не сложно, сложно одно токо, это его поддерживать если не повезло с общими интересами то всё френд зона, да и желательно перед знакомством как-то понять интересен ей ли ты, если нет то и подходить смысла нет + нужно знать какого она уровня, богатая, средняя, бедная или какая ещё там по статусу, вот у меня статус бедного ибо в жизни не повезло с многими вещами
Думаю для девушек я (неудачник) ибо большенство девушек содержанки и им важно твоё состояние кошелька
Не думаю что какая-то дама будет иметь отношения с парнем у которого зарплата 18-20 000 руб в месяц
---
На пикабу очень часто видела, как парни жалуются, что не могут найти себе девушку. Потому что он скромный, закомплексованный, не красивый, и т.д. И на сайтах знакомств совсем не получится, потому что в "реал" выйти огромная проблема. Я предлагаю решение проблемы. Но для этого надо уволиться с работы (хотя бы временно)... И устроиться на местный завод или фабрику! Грузчиком, наладчиком. Чем мельче, тем лучше. О, да! Я тут на престижной работе, нахрен мне все надо бросать и устраиваться на завод? Не надо, так и не надо, не чего потом ныть. Статус жены не устраивает. А это спорный вопрос. Итак, вся суть. Вы просто устриваетесь, обучаетесь и работаете.. и все, дальше все сделают за вас. На заводе не только старые тетки работают, но и молодые красивые девушки. Кто-то учится и работает, кто-то пытается жить самостоятельно, есть очень перспективные. Вряд ли, вы найдёте там девушку из богатой семьи, но так ли оно вам надо? Спустя месяц, вы будете знать, кто приятная хохотушка, кто ленивая, кто работящая, кто за собой следит, а у кого постоянно голова грязная. А под тонким рабочим халатиком вы точно будете знать, соответствует ли девушка вашим запросам, чего нельзя знать в инсте. Но, если вы лицом не вышли, вам придётся повкалывать, чтоб достойная девушка вас выбрала. Нафиг ей лодырь и алкоголик? (хотя и этих "разберут"). Вроде все описала. Если вы забитый и скромный, вы устраиваетесь на завод - и вас " женят", там даже свахи есть. Просто устраиваетесь - и вот вам девушка.))) Если решите сами выбрать, то тут придётся подождать. Отсеять то, что на первый взгляд кажется прекрасным, подождать и присмотреться. А там как жизнь повернет. В знакомом цеху холостой был лишь поехавший головой пожилой грузчик.
Всем удачи.)
|
Python | UTF-8 | 864 | 3.0625 | 3 | [
"MIT"
] | permissive | import sys
sys.setrecursionlimit(1000000000)#just for bigger recursion loop.
x = 1
in_res = None
dec_res = None
def eqnSolve(eqn_state,inc_num):
def solve(eqn:str,increament):
global x
global in_res, dec_res
if eval(eqn) == 0:
y = x
return y
elif eval(eqn) > 0:
x = x-increament
if x == dec_res:
y = x
return dec_res
dec_res = x
solve(eqn, increament)
elif eval(eqn) < 0:
x = x+increament
#print(x)
if x == in_res:
y = x
return in_res
else:
in_res = x
solve(eqn, increament)
solve(eqn, increament)
solve(eqn_state,inc_num)
return x
print(eqnSolve('x**3+x**2-12',0.001))
|
C++ | UTF-8 | 750 | 2.65625 | 3 | [] | no_license | #include "Camera.h"
#include <math.h>
#ifndef FREECAM_H
#define FREECAM_H
class FreeCamera:public Camera
{
private:
float stepSize;
public:
//constructors
//arcball camera has no meaning without object attached...defaults to looking at origin
FreeCamera();
//always set an arcball camera with the xyz of the object being looked at, handle the camera positioning later
FreeCamera(float cx, float cy, float cz);
//computes x y z of camera based on theta phi and radius
void recomputeOrientation();
//handle mouse dragging for changing orientation (based on user input)
void handleCameraDrag(float xOld, float xNew, float yOld, float yNew);
float* getCameraInfo();
void handleForwardKey();
void handleBackwardsKey();
};
#endif |
Java | UTF-8 | 481 | 1.921875 | 2 | [] | no_license | package edu.unc.cs.htmlBuilder.util;
/**
* @author Andrew Vitkus
*
*/
public interface ITableStylable extends IColorable, IBGColorable {
public void setBorderColor(String color);
public String getBorderColor();
public String getBorderCollapse();
public void setBorderCollapse(String collapse);
public String getBorderWidth();
public void setBorderWidth(String width);
public String getBorderStyle();
public void setBorderStyle(String style);
}
|
C++ | UTF-8 | 1,087 | 2.890625 | 3 | [] | no_license | #pragma once
//STD Headers
#include <functional>
//Library Headers
//Coati Headers
#include "core/input/definitions/Input.h"
namespace core {
enum class MouseButton : unsigned {
LEFT = 0,
RIGHT = 1,
MIDDLE = 2,
THUMB_1 = 3,
THUMB_2 = 4
};
using MouseInput = Input<MouseButton>;
static std::unordered_map<std::string, MouseButton> StringToMouseButtonMap = {
{"LEFT", MouseButton::LEFT},
{"RIGHT", MouseButton::RIGHT},
{"MIDDLE", MouseButton::MIDDLE},
{"THUMB_1", MouseButton::THUMB_1},
{"THUMB_2", MouseButton::THUMB_2}
};
inline MouseButton DeserializeMouseButton(const std::string& key, const std::vector<std::string> modifiers) {
return StringToMouseButtonMap.find(key)->second;
}
}
//It is acceptable to extend the std namespace to add template specifications for
//standard library templates to work with custom data types.
namespace std {
template <> struct hash<core::MouseInput> { //Class to define hash function for Keyboard Input
//Hash functor
std::size_t operator()(const core::MouseInput& t) const {
return t.Hash();
}
};
} |
Python | UTF-8 | 1,691 | 3.796875 | 4 | [] | no_license | '''
Title: 841. Keys and Rooms (Medium) https://leetcode.com/problems/keys-and-rooms/
Runtime: 76 ms, faster than 22.86% of Python online submissions for Keys and Rooms.
Memory Usage: 12.3 MB, less than 5.55% of Python online submissions for Keys and Rooms.
Description:
There are N rooms and you start in room 0. Each room has a distinct number in 0, 1, 2, ..., N-1,
and each room may have some keys to access the next room.
Formally, each room i has a list of keys rooms[i], and each key rooms[i][j] is an integer in [0, 1, ..., N-1]
where N = rooms.length. A key rooms[i][j] = v opens the room with number v.
Initially, all the rooms start locked (except for room 0).
You can walk back and forth between rooms freely.
Return true if and only if you can enter every room.
Example:
Input: [[1],[2],[3],[]]
Output: true
Explanation:
We start in room 0, and pick up key 1.
We then go to room 1, and pick up key 2.
We then go to room 2, and pick up key 3.
We then go to room 3. Since we were able to go to every room, we return true.
Input: [[1,3],[3,0,1],[2],[0]]
Output: false
Explanation: We can't enter the room with number 2.
'''
class Solution(object):
def canVisitAllRooms(self, rooms):
"""
:type rooms: List[List[int]]
:rtype: bool
"""
keys = []
keys.append(0)
for j in keys:
for k in rooms[j]:
if k not in keys:
keys.append(k)
if len(keys) == len(rooms):
return True
else:
return False
|
Java | UTF-8 | 640 | 2.140625 | 2 | [] | no_license | package com.zootr.tracker.ootTracker.model;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
@JsonIgnoreProperties(ignoreUnknown = true)
public class ParentObject {
private EntranceParent entrances;
private LocationParent locations;
public ParentObject() {
super();
// TODO Auto-generated constructor stub
}
public EntranceParent getEntrances() {
return entrances;
}
public void setEntrances(EntranceParent entrances) {
this.entrances = entrances;
}
public LocationParent getLocations() {
return locations;
}
public void setLocations(LocationParent locations) {
this.locations = locations;
}
}
|
Java | UTF-8 | 851 | 1.992188 | 2 | [] | no_license | package com.deppon.foss.module.base.baseinfo.api.server.dao.commonselector;
import java.util.List;
import com.deppon.foss.module.base.baseinfo.api.shared.domain.GeneralTaxpayerInfoEntity;
/**
*
* 一般纳税人信息dao接口
* @author 308861
* @date 2016-2-28 下午2:48:41
* @since
* @version
*/
public interface ICommonGeneralTaxpayerInfoDao {
/**
*
* 根据发票抬头查询一般纳税人信息
* @author 308861
* @date 2016-2-24 下午6:10:57
* @param entity
* @return
* @see
*/
List<GeneralTaxpayerInfoEntity> queryTaxpayerInfoList(GeneralTaxpayerInfoEntity entity,int start, int limit);
/**
*
* 查询总条数 ---用于分页
* @author 308861
* @date 2016-2-29 上午9:12:25
* @param entity
* @return
* @see
*/
long queryGeneralTaxpayerInfoCount(GeneralTaxpayerInfoEntity entity);
}
|
Python | UTF-8 | 12,618 | 3.0625 | 3 | [] | no_license | from itertools import product, chain
import numpy as np
recentering_precision = 1e-7
reach_factor = 10
def get_complex_zeros(square_dimension):
"""
Get matrix of complex zeros
:param square_dimension: Dimension of matrix
:return:
"""
return np.zeros((square_dimension, square_dimension), dtype=complex)
def cplx_exp_dot(vec1, vec2):
"""
Get complex exponential of the dot product of two vectors
:param vec1: first vector
:param vec2: second vector
:return:
"""
return np.exp(-1j*np.dot(vec1, vec2))
def conj_dot(vec1, vec2):
"""
Returns complex vector inner product <vec1|vec2>
:param vec1:
:param vec2:
:return:
"""
return np.dot(np.conj(vec1.T), vec2)
def hermite_mat_prod(mat_1, mat_2):
"""
Return conjugate product of the two complex matrices
:param mat_1:
:param mat_2:
:return:
"""
return np.mat(np.dot(np.conj(mat_1.T), mat_2))
def recentre(m1, m2, nk):
"""
Recentre vector m1*a1 + m2*a2 points on a two-dimensional grid by
shifting those which cross beyond the midpoint back by a full periodic
length nk*a1 or nk*a1. a1 and a2 here are the spacing vectors of the grid.
This does not work when the motif is not a regular grid.
:param m1: Point along first axis
:param m2: Point along the second axis
:param nk: Size of the grid
:return:
"""
m1_recentred = m1 - int(m1 > nk // 2)*nk
m2_recentred = m2 - int(m2 > nk // 2)*nk
recentred_coords = [m1_recentred, m2_recentred]
return recentred_coords
def recentre_continuous(r, b1, b2):
"""
Recentre a vector r in a motif of a cell by shifting it backwards by a
full lattice period along the axes where it exceeds the midpoint length
from the origin. Uses reciprocal lattice vectors to find fractional
distance along the cell of the motif vector. This works for when the motif
is not a regular grid of points. The lattice vectors a_i and reciprocal
lattice vectors b_j must obey a_i.b_j = 2*pi*delta_ij
:param r: Vector to be recentred
:param b1: first reciprocal lattice vector
:param b2: second reciprocal lattice vector
:return:
"""
threshold = 0.5 - recentering_precision
x1, x2 = np.dot(b1, r)/2/np.pi, np.dot(b2, r)/2/np.pi
x1p, x2p = x1 - float(int(x1 >= threshold)), x2 - float(int(x2 >= threshold))
return x1p, x2p
def recentre_idx(radius, i, j, nc, a1, a2):
"""Given corner-cetred indices, create spatial vector."""
rec_idx = recentre((i % nc - j % nc) % nc, (i//nc - j//nc) % nc, nc)
return radius + rec_idx[0]*a1 + rec_idx[1]*a2
def fix_consistent_gauge(vector):
"""Fix a vector with a consistent gauge depending on its elements"""
full_sum = vector.ravel().sum()
quotient_phase = full_sum/np.abs(full_sum)
fixed_vector = vector/quotient_phase
return fixed_vector
def get_supercell_positions(a1, a2, nk, cell_wise_centering=True):
"""
Determine all lattice vector points in the supercell.
:param a1: First primitive lattice vector
:param a2: Second primitive lattice vector
:param nk: Size of the periodic lattice (size of the corresponding k-grid)
:param cell_wise_centering: Set to True to recentre the grid.
:return:
"""
position_list = []
for m1, m2 in product(range(nk), range(nk)):
# idx is m1*nk + m2 for reference in future functions
if cell_wise_centering:
ms = recentre(m1, m2, nk)
else:
ms = m1, m2
r_position = ms[0]*a1 + ms[1]*a2
position_list.append(r_position)
return position_list
def get_cumulative_positions(pattern, norb):
"""
Determine the indices that separate groups of elements in the
tight-binding basis that correspond to orbitals on the same atom.
:param pattern: Orbital_pattern e.g. [10, 6, 6]
:param norb: Total number of orbitals in the system
:return:
"""
p_sum = sum(pattern)
p_len = len(pattern)
if norb % p_sum != 0:
raise ValueError("Pattern does not fit periodically in orbital set")
cumul_term = lambda i: (i//p_len)*p_sum + sum(pattern[:(i % p_len) + 1])
cumulative_positions = [0] + [int(cumul_term(i)) for i in range(norb)]
return cumulative_positions
def reduced_tb_vec(v1, v2, nat, cumul_pos):
"""
Reduces two TB vectors to a partial-inner-product vector, by collapsing
only the orbital space.
:param v1: first vector
:param v2: second vector
:param nat: number of atoms in the system
:param cumul_pos: Cumulative position of each atom in the index list of
orbitals.
:return: reduced vector in the subspace of atoms alone (not orbitals)
"""
reduced_vec = np.array([
conj_dot(v1[cumul_pos[i]:cumul_pos[i + 1]],
v2[cumul_pos[i]:cumul_pos[i + 1]])
for i in range(nat)
])
return reduced_vec
def get_band_extrema(eigensystem, energy_cutoff, cell_size):
"""Not used here."""
max_energy_1 = eigensystem[0][0][cell_size ** 2 - 1] + energy_cutoff
max_energy_2 = eigensystem[1][0][cell_size ** 2 - 1] + energy_cutoff
min_energy_1 = eigensystem[0][0][cell_size ** 2] - energy_cutoff
min_energy_2 = eigensystem[1][0][cell_size ** 2] - energy_cutoff
cb_max_1 = list(eigensystem[0][0] < max_energy_1).index(False) + 1
cb_max_2 = list(eigensystem[1][0] < max_energy_2).index(False) + 1
vb_min_1 = list(eigensystem[0][0] >= min_energy_1).index(True)
vb_min_2 = list(eigensystem[1][0] >= min_energy_2).index(True)
return cb_max_1, cb_max_2, vb_min_1, vb_min_2
def extract_exciton_dos(excitons,
frequencies,
broadening_function,
sigma,
spin_split=False):
"""
Get the excitonic density of states given a frequency grid and broadening
function.
:param excitons: excitonic eigensystem
:param frequencies: grid of frequencies
:param broadening_fnc: broadening function (should take only w and w0)
:param sigma: Broadening used for the broadening function
:param spin_split: Set to True to loop over spin in the exciton data.
:return:
"""
frequency_incr = frequencies[1] - frequencies[0]
density_of_states = np.zeros(len(frequencies))
for s0 in range(2):
if not spin_split and s0 == 1:
continue
for idx1, exciton in enumerate(excitons[s0][0]):
closest_idx = int((exciton - min(frequencies))//frequency_incr)
reach_idx = reach_factor*int(sigma//frequency_incr)
lower_idx = max([closest_idx - reach_idx, 0])
upper_idx = min([closest_idx + reach_idx, len(frequencies) - 1])
for idx2 in range(lower_idx, upper_idx):
smearing = broadening_function(exciton, frequencies[idx2])
density_of_states[idx2] += smearing
return density_of_states
def convert_eigenvector_convention(eigenvectors, kpt, motif, orb_pattern):
"""
Change eigenvector block at a k point from convention II to convention I.
:param eigenvectors: Matrix of eigenvectors
:param kpt: k point eigenvectors are calculated at
:param motif: list of motif vectors in order of
:param orbital_pattern: orbital pattern of number of orbitals per position
:return:
"""
nat = len(motif)
phase_vector = [np.exp(-1j*np.dot(kpt, vector)) for vector in motif]
full_pattern = [orb_pattern[i % len(orb_pattern)] for i in range(nat)]
phase_nested_list = [[phase_vector[i]]*full_pattern[i] for i in range(nat)]
phase_array = np.array(list(chain(*phase_nested_list)))
eigenvectors_rotate = np.multiply(phase_array.reshape(-1, 1), eigenvectors)
return eigenvectors_rotate
def convert_all_eigenvectors(eigenvectors,
k_grid,
motif,
orb_pattern,
nbasis,
spin_split=False):
"""
Change all eigenvectors from convention II to convention I.
:param eigenvectors: Matrix of eigenvectors
:param k_grid: k points that eigenvectors are calculated at
:param motif: list of motif vectors in order of
:param orbital_pattern: orbital pattern of number of orbitals per position
:param nbasis: number of elements in the basis
:param spin_split: True if system is spin divided.
:return:
"""
eigenvectors_rotated = np.zeros(eigenvectors.shape, dtype=complex)
for idx, kpt in enumerate(k_grid):
for s in range(2):
if s == 1 and not spin_split:
continue
j1 = idx*nbasis + s*nbasis
j2 = (idx + 1)*nbasis - int(spin_split)*(1 - s)*nbasis
eig_block = eigenvectors[j1:j2, :]
eig_block_rotate = convert_eigenvector_convention(eig_block,
kpt,
motif,
orb_pattern)
eigenvectors_rotated[j1:j2, :] = eig_block_rotate
return eigenvectors_rotated
def unconvert_eigenvector_convention(eigenvectors, kpt, motif, orb_pattern):
"""
Change eigenvector block at a k point from convention II to convention I.
:param eigenvectors: Matrix of eigenvectors
:param kpt: k point eigenvectors are calculated at
:param motif: list of motif vectors in order of
:param orbital_pattern: orbital pattern of number of orbitals per position
:return:
"""
nat = len(motif)
phase_vector = [np.exp(1j*np.dot(kpt, vector)) for vector in motif]
full_pattern = [orb_pattern[i % len(orb_pattern)] for i in range(nat)]
phase_nested_list = [[phase_vector[i]]*full_pattern[i] for i in range(nat)]
phase_array = np.array(list(chain(*phase_nested_list)))
eigenvectors_rotate = np.multiply(phase_array.reshape(-1, 1), eigenvectors)
return eigenvectors_rotate
def unconvert_all_eigenvectors(eigenvectors,
k_grid,
motif,
orb_pattern,
nbasis,
spin_split=False):
"""
Change all eigenvectors from convention II to convention I.
:param eigenvectors: Matrix of eigenvectors
:param k_grid: k points that eigenvectors are calculated at
:param motif: list of motif vectors in order of
:param orbital_pattern: orbital pattern of number of orbitals per position
:param nbasis: number of elements in the basis
:param spin_split: True if system is spin divided.
:return:
"""
eigenvectors_rotated = np.zeros(eigenvectors.shape, dtype=complex)
for idx, kpt in enumerate(k_grid):
for s in range(2):
if s == 1 and not spin_split:
continue
j1 = idx*nbasis + s*nbasis
j2 = (idx + 1)*nbasis - int(spin_split)*(1 - s)*nbasis
eig_block = eigenvectors[j1:j2, :]
eig_block_rotate = unconvert_eigenvector_convention(eig_block,
kpt,
motif,
orb_pattern)
eigenvectors_rotated[j1:j2, :] = eig_block_rotate
return eigenvectors_rotated
def find_repeats(e):
elem, rep = np.unique(np.round(e, decimals=8), return_counts=True)
repeats = elem[np.where(rep > 1)]
return repeats
def orthogonalize_eigenvecs(e, v):
e = np.round(e, decimals=8)
vo = v.copy() # orthogonalized eigenvector matrix
nk = v.shape[0] / v.shape[1] # number of k-points
nb = v.shape[1] # number of bands
for i in range(int(nk)): # for every k-point
# find indices of degenerate eigenvalues
ei = e[i, :] if len(e.shape) > 1 else e
rep = find_repeats(ei)
for j in range(len(rep)):
inds = np.array(np.where(ei == rep[j]))[0]
# assumption: only have doubly degenerate eigenvalues
# take first and second vector
v1 = v[nb*i: nb*(i + 1), inds[0]]
v2 = v[nb*i: nb*(i + 1), inds[1]]
# make new second vector
v2o = v2 - np.dot(v1.conjugate(), v2) * v1
v2o = v2o / np.sqrt(np.dot(v2o.conjugate(), v2o))
# write it into matrix vo
vo[nb*i: nb*(i + 1), inds[1]] = v2o
return vo
|
Python | UTF-8 | 134 | 3.3125 | 3 | [] | no_license | stack=[]
for i in "hello,world!":
stack.append(i)
list=[]
while len(stack)!=0:
list.append(stack.pop())
print("".join(list)) |
Java | UTF-8 | 222 | 2.578125 | 3 | [] | no_license | package 命令模式;
public class Receiver {
public void bakeChilken(){
System.out.println("烤鸡翅.......");
}
public void bakeMie(){
System.out.println("烤羊肉串儿.......");
}
}
|
Python | UTF-8 | 1,648 | 3.375 | 3 | [] | no_license | from os import system
from time import sleep
import numpy as np
def print_frames(frames):
for i, frame in enumerate(frames):
system('cls')
print(frame['frame'])
print(f"Time-step: {i + 1}")
print(f"State: {frame['state']}")
print(f"Action: {frame['action']}")
print(f"Reward: {frame['reward']}")
sleep(.1)
def evaluate_agent(env, q_table):
total_epochs, total_penalties = 0, 0
episodes = 100
for _ in range(episodes):
state = env.reset()
epochs, penalties, reward = 0, 0, 0
done = False
while not done:
action = np.argmax(q_table[state])
state, reward, done, info = env.step(action)
if reward == -10:
penalties += 1
epochs += 1
total_penalties += penalties
total_epochs += epochs
print(f"Results after {episodes} episodes:")
print(f"Average time-steps per episode: {total_epochs / episodes}")
print(f"Average penalties per episode: {total_penalties / episodes}")
def run_agent(env, q_table, state):
done = False
frames = []
while not done:
action = np.argmax(q_table[state])
state, reward, done, info = env.step(action)
frame = {
'frame': env.render(mode='ansi'),
'state': state,
'action': action,
'reward': reward
}
system('cls')
print(frame['frame'])
print(f"State: {frame['state']}")
print(f"Action: {frame['action']}")
print(f"Reward: {frame['reward']}")
sleep(.1)
print_frames(frames)
|
Ruby | UTF-8 | 339 | 3.3125 | 3 | [] | no_license | class Box
def initialize(w,h)
@width,@height=w,h
end
def getWidth
@width
end
def getHeight
@height
end
def setWidth=(value)
@width=value
end
def setHeight=(value)
@height=value
end
end
box=Box.new(10,20)
box.setWidth=30
box.setHeight=40
puts "Width of the box is : #{box.getWidth()}"
puts "Height of the box is : #{box.getHeight()}"
|
Markdown | UTF-8 | 6,833 | 2.671875 | 3 | [] | no_license | ---
layout: post
title: "I spy Alison Spiess kicking some serious a**"
date: 2016-02-24 21:56
author: Beth Crane
tags: [early-career]
location: Texas
company: National Instruments
field: Tech
image: 'images/posts/2015/11/IMG_5322.jpg'
---
*What do you do after a week of being surrounded by women in tech at Grace Hopper? Well if you're Beth, the answer is travel 2 hours to seek out another one! Alison did a semester abroad at the University of New South Wales, which is where I met her - she actually hosted my first ever Friendsgiving. Austin is a beautiful city, and I'm so glad I had Alison to show me around - I only wish it had been a little less hot!*
### Tell us a little about you.
I lived in Iowa for the first 22 years of my life where I got my bachelor's degree in Computer Engineering at Iowa State University. I moved to Austin 2 years ago to work at National Instruments and have stumbled upon an amazing team and a couple of cool managers. I love living in Austin. It's such a funky town with tons of cool people, outdoor activities, music, and good food. I decided I want to stay in Austin for a good while longer so I'm in the process of buying my first house and enjoying doing all the fantasy interior decorating that goes along with it.
One of the first things I did after moving to Austin was buy a pair of rollerskates and join the Texas Rollergirls Recreational League. Austin is a huge city for roller derby, being the source of the modern revival in the early 2000s. I was drawn to it for being a kick-ass woman's dominated sport where there is no shame in being who you are. Plus, beating up on other women (safely!) is such a thrill! Over the last 2 years, I've been working my way up into the Rec League's most advanced level, Team Reckoning. Next year, I'm hoping to try out for Texas Rollergirls League proper, so be on the lookout for me!
### Tell us about what you're wearing.
{% responsive_image path: "images/posts/2015/11/IMG_5346.jpg" %}
Most of what I am wearing is second hand. The [dress](http://amzn.to/20WkUwA), the [shoes](http://amzn.to/21sPIqV), the [vest](http://amzn.to/1TGwson), the [purse](http://amzn.to/21sPGPM), as well as all of the [jeans](http://amzn.to/1TGwwEI) I own. I found them all on different visits to Plato's Closet. Thrift shopping is the easiest way to get exposed to a ton of different styles, especially things you wouldn't normally pick up. It's also super budget friendly, so I don't feel bad buying something I'm not sure I'll wear. The hat is from World Market where I stumbled upon it on my mission to get Tim Tams.
{% responsive_image path: "images/posts/2015/11/IMG_5512.jpg" %}
My coworkers joke that I own hundreds of [shirts with cats](http://amzn.to/20WlfPR) on them. I'd like to use this opportunity to point out that I only own 3 cat shirts. I think I got this particular funky space cat shirt from the men's department at Kohls. It pays off to browse different sections sometimes, you might just find something you like. The jeans are American Eagle, but I got them from Plato's Closet along with the sandals.
{% responsive_image path: "images/posts/2015/11/IMG_5433.jpg" %}
My typical roller derby outfit is a baggy shirt (we LOVE [this one](http://amzn.to/1R3bryo)), a pair of shorts, and a bright sports bra for a bit of pop. We practice in a warehouse so the hot summers can be brutal if you don't have proper air flow and skin exposure. I caught this shirt during a sponsored SXSW party last year. I thought the sassy-ness matched my personality so even though it was far too large for me, I cut off the sleeves and repurposed it into a workout shirt. The shorts and sports bra are from Target's activewear section. I bought my [skates](http://amzn.to/21sQ691) from the local roller derby shop (Medusa Skates) about four months ago. They are my babies.
### How did your style evolve to what it is now?
{% responsive_image path: "images/posts/2015/11/IMG_5489.jpg" %}
I used to be a jeans and t-shirt kind of girl. Well, I still am, I love to be comfortable. You won't find me torturing myself with heels for long periods of time, anything too tight, or bulky jewelry. The simpler the better for me. My style initially started developing in college when I was figuring out who I am. I started gravitating toward to a lot of muted colors and dark neutrals in solids or stripes. I think of it as sort of a laid back, moody, classic style.
The Austin mentality has really started influencing the types of clothes I've been buying lately though. People here are really down to earth and stylish hippy is big. I've been picking things that are bright, flowy, lacey, floral patterned, and great for warm weather. It's different than what I'm used to, but I've been enjoying branching out and trying something new.
### Any advice for a young person thinking about getting into a STEM field?
{% responsive_image path: "images/posts/2015/11/IMG_5457.jpg" %}
I think it's important to remember when you're getting into STEM that you have to be ok with failing sometimes. It'll be difficult. Despite that, you shouldn't forget to praise your own small successes and don't let the mistakes get to you. I always have a hard time admitting when I don't know something, but it's important to remember that it's impossible to know everything and no one can fault you for that. Don't doubt yourself and don't let other people dictate what you should think of what you're doing.
### What would you say is the project you've done that you're proudest of?
{% responsive_image path: "images/posts/2015/11/IMG_5398.jpg" %}
My senior design project has to be it. My team created a home automation system that's goal was to mesh different standards in an easy to setup and control platform. We covered the whole spectrum of programming from kernel and user-mode development, to web back-end, to web and mobile apps. I spent most of my time working on the web page which was something totally different than I had ever done. While I did learn a lot, I'm most proud of our team dynamic and how dedicated we all were to the project. I want to be that dedicated to every project I work on in the future.
### What is the best way (if any) for people to follow you on social media?
{% responsive_image path: "images/posts/2015/11/IMG_5477.jpg" %}
- [Twitter - @alispss](http://twitter.com/alispss)
- [Instagram - @alisonmontag](http://instagram.com/alisonmontag)
*Buying a house, kicking ass at roller derby, working at National Instruments and (not that she mentioned it) baking up a storm too! All that plus some great advice - reading this definitely has me inspired to kick my productivity up a notch, although I don't think either of us'll be brave enough for Roller Derby any time soon (not that Dona would let me anyway!).*
*xx,*
*Beth*
|
PHP | UTF-8 | 2,757 | 2.796875 | 3 | [] | no_license | <?php
session_start();
if ( !isset($_SESSION["login"])){
header('Location: login.php');
exit;
}
require 'functions.php';
// Ambil Rank dari dari URL
$Rank = $_GET["Rank"];
// Query mahasiswa berdasarkan Rank
$blbuls = query("SELECT * FROM blackbulls WHERE Rank = $Rank")[0];
// Cek apakah tombol sudah ditekan atau belum
if (isset($_POST["submit"])){
// Cek apakah data diubah atau tidak
if(ubah($_POST)> 0):
echo "
<script>
alert('Data Berhasil Diubah');
document.location.href = 'index.php';
</script>
";
else:
$feedback = "Data Gagal Diubah";
echo mysqli_error($db);
endif;
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Riss</title>
<link rel="icon" href="img/blackbullspng.png">
<link rel="stylesheet" href="bootstrap-4.5.3-dist/css/bootstrap.css">
<link rel="stylesheet" href="style.css">
</head>
<body class="text-center">
<form class="form-signin" action="" method="post" enctype="multipart/form-data">
<?php if (isset($_POST["submit"])):?>
<h3 class="text-black"><?= $feedback?></h3>
<?php endif;?>
<img class="mb-4" src="img/blackbullspng.png" alt="" width="72" height="72">
<h1 class="h3 mb-3 font-weight-normal text-black ">Edit a Member</h1>
<input type="hidden" name="Rank" value="<?= $blbuls["Rank"]?>">
<input type="hidden" name="samePicture" value="<?= $blbuls["Picture"]?>">
<img src="img/<?= $blbuls['Picture']?>" alt="" width=50">
<input type="file" name="Picture" class="form-control" placeholder="Add Picture..." value="<?= $blbuls["Picture"]?>">
<br>
<input type="text" name="Name" class="form-control" placeholder="Add Name..." required value="<?= $blbuls["Name"]?>">
<br>
<input type="number" name="Power" class="form-control" placeholder="Add Power..." required value="<?= $blbuls["Power"]?>">
<br>
<input type="text" name="Magic"class="form-control" placeholder="Add Magic..." required value="<?= $blbuls["Magic"]?>">
<br>
<input type="text" name="Grimoire" class="form-control" placeholder="Add Grimoire..." required value="<?= $blbuls["Grimoire"]?>">
<br>
<input type="text" name="Position" class="form-control" placeholder="Add Position..." required value="<?= $blbuls["Position"]?>">
<br>
</div>
<br>
<button class="btn btn-lg btn-success btn-block" name="submit" type="submit">Edit Member</button>
<br>
<p class="mt-5 mb-3 text-muted">©Riss 2020</p>
</body>
</html> |
Ruby | UTF-8 | 552 | 3.75 | 4 | [
"MIT"
] | permissive | input = []
File.open("../input.txt", "r").each_line do |line|
input << line.chomp
end
def count_chars(str)
found = {}
str.chars.each do |c|
found[c] = 0 unless found.has_key? c
found[c] += 1
end
counts = {}
found.values.each do |count|
counts[count] = true
end
return counts
end
def checksum(input)
totals = {
2 => 0,
3 => 0,
}
input.each do |id|
counts = count_chars(id)
totals[2] += 1 if counts[2]
totals[3] += 1 if counts[3]
end
return totals[2] * totals[3]
end
puts checksum(input)
|
Java | UTF-8 | 2,861 | 2.359375 | 2 | [
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | package com.st.serviceImpl;
import java.util.Arrays;
import java.util.List;
import java.util.Properties;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import com.st.model.ImageAlignment;
import com.st.service.ImageAlignmentService;
/**
* This class implements the store/retrieve logic to the ST API for the data
* model class "ImageAlignment". The connection to the ST API is handled in a
* RestTemplate object, which is configured in mvc-dispather-servlet.xml
*/
@Service
public class ImageAlignmentServiceImpl implements ImageAlignmentService {
// Note: General service URI logging is performed in CustomOAuth2RestTemplate.
@SuppressWarnings("unused")
private static final Logger logger = Logger.getLogger(ImageAlignmentServiceImpl.class);
@Autowired
RestTemplate secureRestTemplate;
@Autowired
Properties appConfig;
@Override
public ImageAlignment find(String id) {
if (id == null || id.equals("")) { return null; }
String url = appConfig.getProperty("url.imagealignment");
url += id;
ImageAlignment imal = secureRestTemplate.getForObject(url, ImageAlignment.class);
return imal;
}
@Override
public List<ImageAlignment> list() {
String url = appConfig.getProperty("url.imagealignment");
ImageAlignment[] imalArray = secureRestTemplate.getForObject(url, ImageAlignment[].class);
List<ImageAlignment> imalList = Arrays.asList(imalArray);
return imalList;
}
@Override
public ImageAlignment create(ImageAlignment imal) {
String url = appConfig.getProperty("url.imagealignment");
ImageAlignment imalResponse = secureRestTemplate.postForObject(url, imal, ImageAlignment.class);
return imalResponse;
}
@Override
public void update(ImageAlignment imal) {
String url = appConfig.getProperty("url.imagealignment");
String id = imal.getId();
secureRestTemplate.put(url + id, imal);
}
@Override
public void delete(String id) {
String url = appConfig.getProperty("url.imagealignment");
secureRestTemplate.delete(url + id + "?cascade=true");
}
@Override
public List<ImageAlignment> findForChip(String chipId) {
String url = appConfig.getProperty("url.imagealignment");
if (url.endsWith("/")) {
url = url.substring(0, url.length() - 1);
}
url += "?chip=" + chipId;
ImageAlignment[] imalArray = secureRestTemplate.getForObject(url, ImageAlignment[].class);
if (imalArray == null) {
return null;
}
List<ImageAlignment> imalList = Arrays.asList(imalArray);
return imalList;
}
}
|
Java | UTF-8 | 1,820 | 2.484375 | 2 | [] | no_license | package com.app.ebank.mbanking;
import java.util.Date;
/**
* Created by Hichem Himovic on 07/06/2017.
*/
public class PersonModel {
private String nom;
private String prenom;
private String adresse;
private String type;
private String email;
private String password;
private Date date;
public PersonModel(){
}
public PersonModel(String nom,String prenom,String adresse,String type,String email,String password,Date date){
this.setNom(nom);
this.setPrenom(prenom);
this.setAdresse(adresse);
this.setType(type);
this.setEmail(email);
this.setPassword(password);
this.setDate(date);
}
public PersonModel(String nom,String prenom,Date date,String email){
this.nom=nom;
this.prenom=prenom;
this.date=date;
this.email=email;
}
public String getNom() {
return nom;
}
public void setNom(String nom) {
this.nom = nom;
}
public String getPrenom() {
return prenom;
}
public void setPrenom(String prenom) {
this.prenom = prenom;
}
public String getAdresse() {
return adresse;
}
public void setAdresse(String adresse) {
this.adresse = adresse;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public Date getDate() {
return date;
}
public void setDate(Date date) {
this.date = date;
}
}
|
Markdown | UTF-8 | 9,468 | 3.921875 | 4 | [] | no_license | # 正则表达式 #
----------
正则表达式用于对字符串模式匹配及检索替换。
**修饰符**
- `g`,全局模式,即模式将被应用于所有字符串,而非在发现第一个匹配项时立即停止;
- `i`,不区分大小写模式,即在确定匹配项时忽略模式与字符串的大小写;
- `m`,多行模式,即在到达一行文本末尾时还会继续查找下一行中是否存在与模式匹配的项;
**元字符**
元字符是拥有特殊含义的字符。
- `.`,查找单个字符,除了换行和行结束符;
- `\w`,查找单词字符;
- `\W`,查找非单词字符;
- `\d`,查找数字;
- `\D`,查找非数字字符;
- `\s`,查找空白字符;
- `\S`,查找非空白字符;
- `\b`,匹配单词边界;
- `\B`,匹配非单词边界;
- `\0`,查找NULL字符;
- `\n`,查找换行符;
- `\f`,查找换页符;
- `\r`,查找回车符;
- `\t`,查找制表符;
- `\v`,查找垂直制表符;
- `\xxx`,查找以八进制数 xxx 规定的字符;
- `\xdd`,查找以十六进制数 dd 规定的字符;
- `\uxxxx`,查找以十六进制数 xxxx 规定的 Unicode 字符;
**字符组(方括号)**
在正则表达式中,包裹于方括号中的为字符组,字符组的匹配结果是其中的一个字符。
[abc] // 表示匹配一个字符,它可以是a、b、c之一
字符组可以使用范围表示法处理字符组中字符较多的情况:
[abcdef] // 当字符组字符较多时
[a-f] // 使用 - 作为连字符简写上面代码
[ab-] // 当连字符不处于两个字符之间时或前面有专业符号时被当做字符匹配,这个正则会匹配a、b、-三个字符之一
排除字符组,在正则表达式字符组中使用`^`表示排除字符组,查找任何不再方括号之间的字符:
[^abc] // 表示匹配一个不是a、b、c的任意字符
**多选分支(管道符)**
在正则表达式中,管道符`|`用于表示多选分支,支持多个模式任选其一进行匹配。
/aaa|bbb/ // 表示匹配字符串aaa、bbb其中之一,与字符组的区别是匹配其中之一模式,而字符组是匹配其中之一字符
/[ab]|[12]/ // 表示匹配[ab]、[12]字符组的其中之一,然后再匹配字符组中的其中一个字符
/(aaa|bbb)ccc/ // 可以使用括号与分支匹配配合使用,表示部分使用分支匹配规则,其它使用另外的规则
分支匹配是惰性的,当前的匹配上了,后边的就不再尝试了。
var reg = /good|goodbye/g;
var reg2 = /goodbye|good/g;
var str = 'goodbye';
str.match(reg); // ['good']
str.match(reg2); // ['goodbye']
**量词**
量词就是重复,表示匹配字符重复的次数。
- `n{X}`,匹配包含X个n的序列的字符串;
- `n{X,}`,X是一个正整数。前面的模式n连续出现至少X次时匹配;
- `n{X,Y}`,X和Y为正整数。前面的模式n连续出现至少X次,至多Y次时匹配;
- `n+`,匹配任何包含至少一个n的字符串;
- `n*`,匹配任何包含零个或多个n的字符串;
- `n?`,匹配任何包含零个或一个n的字符串;
使用量词匹配时又有贪婪匹配和惰性匹配两种情况:
var reg = /\d{2,5}/g;
var str = '1234';
str.match(reg); // ['1234'],默认贪婪模式,正则表达式会尽可能多的匹配
var reg2 = /\d{2,5}/g; // ['12', '34'],在量词后边加上一个?符号,就是惰性匹配,即刚好满足条件的时候就不再向下继续匹配了
**锚**
位置(锚)是**相邻字符之间的位置**,用于匹配位置。
- `^`,匹配开头,在多行匹配中匹配行开头;
- `$`,匹配结尾,在多行匹配中匹配行结尾;
- `\b`,匹配单词边界;单词边界,具体就是\w与\W之间的位置,也包括\w与^之间的位置,和\w与$之间的位置;
- `\B`,匹配非单词边界;
- `(?=p)`,其中p是一个子模式(子模式可以是正则表达式),即p前面的位置,或者说,该位置后面的字符要匹配p;
- `(?!p)`,仍是p前面的位置,但位置后面的字符满足不匹配p;
可以将位置理解为空字符,而位置匹配匹配便是这些空字符(位置)。
'hello' => '' + 'h' + '' + 'e' + '' + 'l' + '' + 'l' + '' + 'o' + ''
var str = 'hello';
str.replace(/^/g, '#'); // '#hello'
**分组(括号)**
在正则表达式中,括号提供了分组,便于我们引用它。括号捕获的分组引用有两种情形:在JavaScript 里引用它,在正则表达式里引用它。
- 分组,括号可以将正则的一部分分割成一组作为单独一个整体;
var str = 'abbbab';
var reg = /ab+/g; // 量词仅作用于单个字符
var reg2 = /(ab)+/g; // 量词作用于括号中整体
str.match(reg); // ['abbb', 'ab']
str.match(reg2); // ['ab', 'ab']
- 分支结构,括号与管道符配合使用;
var str = 'hello world, hi world';
var reg = /(hello|hi) world/g;
var reg2 = /hello|hi world/g;
str.match(reg); // ['hello world', 'hi world']
str.match(reg2); // ['hello', 'hi world']
在正则括号分组中,会给每一个分组都开辟一个空间,用来储存每一个分组匹配到的数据。当我们需要时。可以提取这些数据:
- `str.match(reg)`,字符串的match方法,返回一个数组,第一个元素是整体匹配结果,然后是各个分组(括号里)匹配的内容,然后此数组还有两个额外属性是匹配下标index,输入的文本input;
- `reg.exec(str)`,正则的exec方法,与字符串的match返回值一致;
- RegExp构造函数全局属性`$1-$9`,且基于最近一次正则表达式操作而改变;
var reg = /(\d{4})-(\d{2})-(\d{2})/;
var str = '2018-01-20';
var arr = str.match(reg);
arr.index; // 0
arr.input; // '2018-01-20'
// 下面两种方法都返回同样的结果,只是方法所属的对象不一样,分组获取的数据会保存在数组第一个元素之后
str.match(reg); // ['2018-01-20, '2018', '01', '20']
reg.exec(str); // ['2018-01-20, '2018', '01', '20']
// 基于最近一次正则操作,例如调用了正则的方法或者字符串的正则方法之后,RegExp才会有保存了分组的全局属性
RegExp.$1; // '2018'
RegExp.$2; // '01'
RegExp.$3; // '20'
// 正则构造函数全局属性场用于替换,下面三种操作结果一致,皆为'01/20/2018'
str.replace(reg, "$2/$3/$1");
str.replace(reg, function () {
return RegExp.$2 + "/" + RegExp.$3 + "/" + RegExp.$1;
});
str.replace(reg, function (match, year, month, day) {
return month + "/" + day + "/" + year;
});
- 正则中使用`\1`结构,`\ + 数字`可以在正则本身里引用分组。但只能引用之前出现的分组,即**反向引用**;
var reg = /\d{4}(-|\/|\.)\d{2}\1\d{2}/; // 正则中使用了\1引用前面分组的结果,所以这有前后一致的情况下才会匹配成功
var str = '2018-01-20';
var str2 = '2018-01/20';
reg.test(str); // true
reg.test(str2); // false
// 使用\ + 数字和$ + 数字引用分组,数组代表的分组,是以左括号为准,第一个左括号中内容就是1,依次向后推
var reg = /^((\d)(\d(\d)))\1\2\3\4$/;
var str = "1231231233";
reg.test(str) ); // true
RegExp.$1; // 123
RegExp.$2; // 1
RegExp.$3; // 23
RegExp.$4; // 3
分组特殊情况:
- 引用了不存在的分组时,此时正则不会报错,只是匹配反向引用的字符本身;
- 分组后面有量词的话,分组最终捕获到的数据是最后一次的匹配;
var reg = /(\d)+/;
var str = '12345';
str.match(reg); // ['12345', '5']数组中保存的分组是最后一次匹配
var reg2 = /(\d)+ \1/;
reg2.test('12345 1'); // false
reg2.test('12345 5'); // true
括号还可以只分组不引用`(?:)`,这种结构的分组将不会出现在引用中。适用于后边不需要引用捕获组的情况,可以节约内存。
**上面所有的操作符优先级从高到低为:转义符(\) => 字符组和分组(括号和方括号) => 量词 => 位置(锚)、元字符、一般字符 => 管道符**
**回溯**
回溯法是正则表达式匹配字符串的原理,回溯法原理:回溯法也称试探法,它的基本思想是从问题的某一种状态(初始状态)出发,搜索从这种状态出发所能达到的所有“状态”,当一条路走到“尽头”的时候(不能再前进),再后退一步或若干步,从另一种可能“状态”出发,继续搜索,直到所有的“路径”(状态)都试探过。这种不断“前进”、不断“回溯”寻找解的方法,就称作“回溯法”。
**正则表达式操作方法**
- 正则表达式方法:
- test,检索字符串中指定的值。返回 true 或 false;
- exec,检索字符串中指定的值。返回找到的值的数组,并确定其位置;
- 字符串的正则表达式方法:
- match,找到一个或多个正则表达式的匹配,同正则的exec方法结果一致;
- search,检索与正则表达式相匹配的值;
- replace,替换与正则表达式匹配的子串;
- split,把字符串分割为字符串数组;
这篇笔记主要是基于老姚的《JavaScript 正则表达式迷你书》整理笔记,十分感谢老姚的分享,[原书地址](https://zhuanlan.zhihu.com/p/29707385)。
|
C# | UTF-8 | 1,533 | 2.71875 | 3 | [
"Apache-2.0"
] | permissive | using System;
using System.Collections.Generic;
using System.Text;
//TODO: perhaps instead of having Initialize() to set the internal state, I should use a factory interface that creates
// immutable IResidualCorrection objects.
//TODO: Join this with the version in PCG
//TODO: ICGConvergence.Initialize() must be called after initializing all properties and before starting the iterations that
// will overwrite them. I am not fond of these dependencies.
namespace MGroup.LinearAlgebra.Iterative.ConjugateGradient
{
/// <summary>
/// Calculates the ratio norm2(f(r)) / norm2(g(r0)), where f and g are vector functions of the residual vector. This ratio
/// will be used by Conjugate Gradient to check convergence.
/// Authors: Serafeim Bakalakos
/// </summary>
public interface ICGResidualConvergence
{
/// <summary>
/// Calculates the ratio norm2(f(r)) / norm2(g(r0)), where f and g are vector functions of the residual vector.
/// </summary>
/// <param name="cg">The Conjugate Gradient Aglorithm that uses this object.</param>
double EstimateResidualNormRatio(CGAlgorithm cg);
/// <summary>
/// Initializes the internal state of this <see cref="ICGResidualConvergence"/> instance. Has to be called immediately
/// after calculating the initial residual r0 and r0*r0.
/// </summary>
/// <param name="cg">The Conjugate Gradient Aglorithm that uses this object.</param>
void Initialize(CGAlgorithm cg);
}
}
|
PHP | UTF-8 | 1,276 | 2.59375 | 3 | [] | no_license | <?php
include("../php_includes/mysqli_connect.php");
if(isset($_POST['bzmobile']) && !empty($_POST['bzmobile'])) {
$bizmobile = preg_replace('#[^0-9+]#i', '', $_POST['bzmobile']);
$mobile = preg_replace('#[^0-9+]#i', '', $_POST['mobile']);
$comment = preg_replace('#[^a-z0-9:.,-?@!=+ \']#i', '', $_POST['comment']);
}
$message = '';
$sql = "SELECT telegramUserId FROM businessdetails WHERE mobile=:mobile";
$stmt = $db_connect->prepare($sql);
$stmt->bindParam(':mobile', $bizmobile, PDO::PARAM_STR);
$stmt->execute();
foreach($stmt->fetchAll() as $row) {
$chat_id = $row['0'];
}
if($chat_id != '') {
$token = "959364317:AAEjHrvMc4bjFj3aZozblHJRoQoewh7RFRc";
$message .= '<b>Customer Mobile:</b> ' .$mobile;
$message .="\n";
$message .= '<b>Information:</b> ' .$comment;
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://api.telegram.org/bot$token/sendMessage");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
$post = array(
'chat_id' => $chat_id,
'text' => $message,
'parse_mode' => 'HTML',
);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
$result = curl_exec($ch);
if($result === false)
{
echo "Error Number:".curl_errno($ch)."<br>";
echo "Error String:".curl_error($ch);
}
curl_close($ch);
}
?>
|
Markdown | UTF-8 | 3,843 | 2.78125 | 3 | [] | no_license | _[mojo](../../modules/mojo/mojo-module.md):[mojo.graphics](../../modules/mojo/mojo-graphics.md).Image_
##### Class Image Extends [std.resource.Resource](../../modules/std/std-resource-resource.md)
The Image class.
An image is a rectangular array of pixels that can be drawn to a canvas using one of the [Canvas.DrawImage](mojo-graphics-canvas.drawimage.md) methods.
Images are similar to pixmap's, except that they are optimized for rendering, and typically live in GPU memory.
To load an image from a file, use one of the [Load](mojo-graphics-load.md), [LoadBump](mojo-graphics-loadbump.md) or [LoadLight](mojo-graphics-loadlight.md) functions.
To create an image from an existing pixmap, use the New( pixmap,... ) constructor.
To create an image that is a 'window' into an existing image, use the New( atlas,rect... ) constructor. This allows you to use images as 'atlases',
To create an 'empty' image, use the New( width,height ) constructor. You can then render to this image by creating a canvas with this image as its render target.
Images also have several properties that affect how they are rendered, including:
* Handle - the relative position of the image's centre (or 'pivot point') for rendering, where (0.0,0.0) means the top-left of the image while (1.0,1.0) means the bottom-right.
* Scale - a fixed scale factor for the image.
* BlendMode - controls how the image is blended with the contents of the canvas. If this is null, this property is ignored and the current canvas blendmode is used to render the image instead.
* Color - when rendering an image to a canvas, this property is multiplied by the current canvas color and the result is multiplied by actual image pixel colors to achieve the final color to be rendered.
| Constructors | |
|:---|:---|
| [New](mojo-graphics-image-new.md) | Creates a new Image. |
| Properties | |
|:---|:---|
| [BlendMode](mojo-graphics-image-blendmode.md) | The image blend mode. |
| [Bounds](mojo-graphics-image-bounds.md) | The image bounds. _(read only)_ |
| [Color](mojo-graphics-image-color.md) | The image color. |
| [FilePath](mojo-graphics-image-filepath.md) | Image filepath. |
| [Handle](mojo-graphics-image-handle.md) | The image handle. |
| [Height](mojo-graphics-image-height.md) | Image bounds height. _(read only)_ |
| [LightDepth](mojo-graphics-image-lightdepth.md) | The image light depth. |
| [Material](mojo-graphics-image-material.md) | Image material. _(read only)_ |
| [Radius](mojo-graphics-image-radius.md) | Image bounds radius. _(read only)_ |
| [Rect](mojo-graphics-image-rect.md) | The image's texture rect. _(read only)_ |
| [Scale](mojo-graphics-image-scale.md) | The image scale. |
| [Shader](mojo-graphics-image-shader.md) | Image shader. |
| [ShadowCaster](mojo-graphics-image-shadowcaster.md) | Shadow caster attached to image. |
| [TexCoords](mojo-graphics-image-texcoords.md) | Image texture coorinates. _(read only)_ |
| [Texture](mojo-graphics-image-texture.md) | The image's primary texture. |
| [Vertices](mojo-graphics-image-vertices.md) | Image vertices. _(read only)_ |
| [Width](mojo-graphics-image-width.md) | Image bounds width. _(read only)_ |
| Methods | |
|:---|:---|
| [GetPixel](mojo-graphics-image-getpixel.md) | Gets a pixel color. |
| [GetPixelARGB](mojo-graphics-image-getpixelargb.md) | Gets a pixel color. |
| [GetTexture](mojo-graphics-image-gettexture.md) | gets an image's texture. |
| [SetTexture](mojo-graphics-image-settexture.md) | Sets an image texture. |
| Functions | |
|:---|:---|
| [Load](mojo-graphics-image-load.md) | Loads an image from file. |
| [LoadBump](mojo-graphics-image-loadbump.md) | Loads a bump image from file(s). |
| [LoadLight](mojo-graphics-image-loadlight.md) | Loads a light image from file. |
| Protected methods | |
|:---|:---|
| [OnDiscard](mojo-graphics-image-ondiscard.md) | |
|
JavaScript | UTF-8 | 735 | 3.59375 | 4 | [] | no_license | function Mostrar()
{
//var numero = prompt("ingrese un número entre 0 y 10.");
/*
while(numero<0 || numero>10) //opcion1
{
numero = prompt("Reingrese un número entre 0 y 10.");
}
alert("Bienvenido");
*/
//numero=parseInt(numero);
//while(isNaN(numero) || (numero<0 || numero>10))
// {
// numero=prompt("ingrese un numero del 1 al 10");
// }
// document.getElementById('Numero').value=numero;
// alert("Correcto");
var numero;
numero=prompt("Ingresar Numero: ");
while(numero<0 || numero>9)
{
alert("El numero es incorecto, reingrese");
numero=prompt("Ingrese numero: ");
document.getElementById('Numero').value=numero;
alert("Correcto");
}
}//FIN DE LA FUNCIÓN |
Java | UTF-8 | 2,723 | 2.3125 | 2 | [] | no_license | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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 de.drv.dsrv.spoc.commons.crypto;
import de.dsrv.core.crypto.CryptoException;
import de.dsrv.core.crypto.FideaHSResponse;
/**
* Definiert die Methoden fuer die Verschluesselung und Entschluesselung von
* Daten mittels des Fidea Health Servers.
*/
public interface FideaHSHelper {
/**
* Fuehrt die Verschluesselung der uebergebenen Daten durch.
*
* @param id
* die eindeutige ID der zu verschluesselnden Daten (wird fuer
* das Logging verwendet)
* @param daten
* die zu verschluesselnden Daten
* @param betriebsnummerEmpfaenger
* die Betriebsnummer des Empfaengers an den die Daten gesendet
* werden sollen
* @param betriebsnummerSender
* die Betriebsnummer des Absenders
* @return das Datenobjekt, welches die Ergebnisse des
* Verschluesselungsdienstes beinhaltet
* @throws CryptoException
* wenn bei Durchfuehrung der Verschluesselung ein technischer
* Fehler auftritt
*/
FideaHSResponse encrypt(final long id, // NOPMD
final byte[] daten, final String betriebsnummerEmpfaenger, // NOPMD
final String betriebsnummerSender) throws CryptoException; // NOPMD
/**
* Fuehrt die Entschluesselung der uebergebenen Daten durch.
*
* @param id
* die eindeutige ID der zu entschluesselnden Daten (wird fuer
* das Logging verwendet)
* @param verschluesselteDaten
* die zu entschluesselnden Daten
* @return das Datenobjekt, welches die Ergebnisse des
* Verschluesselungsdienstes beinhaltet
* @throws CryptoException
* wenn bei Durchfuehrung der Entschluesselung ein technischer
* Fehler auftritt
*/
FideaHSResponse decrypt(long id, // NOPMD
byte[] verschluesselteDaten) throws CryptoException; // NOPMD
}
|
Java | UTF-8 | 2,596 | 2.15625 | 2 | [] | no_license | package com.ecotesch.proy;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.google.zxing.integration.android.IntentIntegrator;
import com.google.zxing.integration.android.IntentResult;
import org.json.JSONException;
import org.json.JSONObject;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
public class ecoweb extends AppCompatActivity {
Button esca;
TextView mos;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_ecoweb);
//Boton de regreso
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
esca = (Button) findViewById(R.id.btnescanerweb);
mos = (TextView) findViewById(R.id.mostrar);
esca.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
escanerweb();
}
});
}
//Accion del boton de back
@Override
public boolean onSupportNavigateUp() {
onBackPressed();
return true;
}
//Metodo escanear web
public void escanerweb(){
IntentIntegrator intentIntegrator = new IntentIntegrator(ecoweb.this);
intentIntegrator.setDesiredBarcodeFormats(IntentIntegrator.QR_CODE_TYPES);
intentIntegrator.setPrompt("Escaner codigo");
intentIntegrator.setCameraId(0);
intentIntegrator.setBeepEnabled(false);
intentIntegrator.setBarcodeImageEnabled(false);
intentIntegrator.initiateScan();
}
//Activar camara
@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
IntentResult result = IntentIntegrator.parseActivityResult(requestCode,resultCode,data);
if(result != null)
if(result.getContents() != null){
mos.setText(result.getContents().toString());
}else{
Toast.makeText(getApplicationContext(),"Error al escaner el codigo", Toast.LENGTH_SHORT).show();
}
}
}
|
JavaScript | UTF-8 | 952 | 2.515625 | 3 | [
"MIT"
] | permissive | const { RichEmbed } = require("discord.js");
const { randomInt } = require('mathjs');
module.exports.run = async (bot, msg) => {
let { config } = bot;
var random;
if(msg.author.id == config.owner){
random = randomInt(1,10000)
}else{
random = randomInt(1,300)
}
let cEmbed = new RichEmbed()
.setColor('#24B8B8')
.setURL('https://disboard.org/server/265505748413448193')
.setTitle(`**DISBOARD: The Public Server List**`)
.setDescription(`<@${msg.author.id}>,\nBump succeeded :thumbsup:\nYou are now bump level ${random}!`)
.setImage('https://cdn.discordapp.com/attachments/555484681135587338/599982089089187870/bot-command-image-bump.png')
msg.channel.send(cEmbed);
}
module.exports.config = {
name: "bump",
description: "Bumps the server!",
usage: ``,
category: `custom`,
accessableby: "Members",
aliases: [],
servers: ['265505748413448193','525114151077675039']
} |
Java | UTF-8 | 7,459 | 2.203125 | 2 | [
"BSD-3-Clause"
] | permissive | package org.openmrs.module.sana.queue.impl;
import java.util.Date;
import java.util.List;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.openmrs.Encounter;
import org.openmrs.Obs;
import org.openmrs.Patient;
import org.openmrs.annotation.Authorized;
import org.openmrs.api.APIException;
import org.openmrs.api.context.Context;
import org.openmrs.api.impl.BaseOpenmrsService;
import org.openmrs.module.sana.ModuleConstants;
import org.openmrs.module.sana.ModuleConstants.Privilege;
import org.openmrs.module.sana.queue.DateItems;
import org.openmrs.module.sana.queue.QueueItem;
import org.openmrs.module.sana.queue.QueueItemService;
import org.openmrs.module.sana.queue.db.QueueItemDAO;
import org.openmrs.util.OpenmrsConstants;
import org.openmrs.util.OpenmrsUtil;
/**
* Implementation of QUeueItemService
*
* @author Sana Development Team
*
*/
public class QueueItemServiceImpl extends BaseOpenmrsService implements
QueueItemService
{
private Log log = LogFactory.getLog(this.getClass());
private QueueItemDAO dao;
public QueueItemServiceImpl() { }
private QueueItemDAO getQueueItemDAO() {
return dao;
}
public void setQueueItemDAO(QueueItemDAO dao) {
this.dao = dao;
}
public QueueItem saveQueueItem(QueueItem queueItem){
log.debug("saveQueueItem(). Entering");
boolean isNew = false;
Date newDate = queueItem.getEncounter().getEncounterDatetime();
log.debug("Encounter date: " + newDate);
Date originalDate = null;
if (queueItem.getQueueItemId() == null) {
isNew = true;
log.debug("Got a new queue item");
}
// Not new we update some of the Encounter info
if (!isNew) {
log.info("Updating previously queued encounter!");
Encounter encounter = queueItem.getEncounter();
Patient p = encounter.getPatient();
originalDate = encounter.getEncounterDatetime();
if (OpenmrsUtil.compare(originalDate, newDate) != 0) {
// if the obs datetime is the same as the
// original encounter datetime, fix it
if (OpenmrsUtil.compare(queueItem.getDateCreated(),
originalDate) == 0) {
encounter.setEncounterDatetime(newDate);
}
}
// if the Person in the encounter doesn't match the Patient in the ,
// fix it
if (!encounter.getPatient().getPersonId().equals(p.getPatientId())){
encounter.setPatient(p);
}
for (Obs obs : encounter.getAllObs(true)) {
// if the date was changed
if (OpenmrsUtil.compare(originalDate, newDate) != 0) {
// if the obs datetime is the same as the
// original encounter datetime, fix it
if (OpenmrsUtil.compare(obs.getObsDatetime(), originalDate) == 0)
{
obs.setObsDatetime(newDate);
}
}
// if the Person in the obs doesn't match the Patient in the
// encounter, fix it
if (!obs.getPerson().getPersonId().equals(p.getPatientId())) {
obs.setPerson(p);
}
}
}
log.debug("Saving queu item.");
dao.saveQueueItem(queueItem);
return queueItem;
}
public void createQueueItem(QueueItem queueItem) throws APIException {
getQueueItemDAO().createQueueItem(queueItem);
}
public QueueItem getQueueItem(Integer queueItemId) throws APIException {
return getQueueItemDAO().getQueueItem(queueItemId);
}
public List<QueueItem> getQueueItems() throws APIException {
return getQueueItemDAO().getQueueItems();
}
public List<QueueItem> getVisibleQueueItems() throws APIException {
return getQueueItemDAO().getVisibleQueueItemsInOrder();
}
public List<QueueItem> getClosedQueueItems() throws APIException {
return getQueueItemDAO().getClosedQueueItemsInOrder();
}
public List<QueueItem> getDeferredQueueItems() throws APIException {
return getQueueItemDAO().getDeferredQueueItemsInOrder();
}
public void updateQueueItem(QueueItem queueItem) throws APIException {
getQueueItemDAO().updateQueueItem(queueItem);
}
public List<QueueItem> getProDateRows(String strpro , int days ,
String checkpro, String checkdate,int iArchieveState,
int startvalue,int endvalue,int sortvalue) throws APIException
{
return getQueueItemDAO().getProDateRows(strpro, days , checkpro ,
checkdate, iArchieveState, startvalue, endvalue,sortvalue);
}
public int getProDateRowsCount(String strpro , int days , String checkpro,
String checkdate,int iArchieveState,int startvalue,int endvalue,
int sortvalue) throws APIException
{
return getQueueItemDAO().getProDateRowsCount(strpro, days , checkpro ,
checkdate, iArchieveState, startvalue, endvalue,sortvalue);
}
public int getProDateRowsClosedCount(String strpro , int days ,
String checkpro, String checkdate,int iArchieveState,
int startvalue,int endvalue,int sortvalue) throws APIException
{
return getQueueItemDAO().getProDateRowsClosedCount(strpro, days ,
checkpro , checkdate, iArchieveState, startvalue, endvalue,
sortvalue);
}
public int getProDateRowsDeferredCount(String strpro , int days ,
String checkpro, String checkdate,int iArchieveState,
int startvalue,int endvalue,int sortvalue) throws APIException
{
return getQueueItemDAO().getProDateRowsDeferredCount(strpro, days ,
checkpro , checkdate, iArchieveState, startvalue, endvalue,
sortvalue);
}
public List<QueueItem> getProDateRowsClosed(String strpro , int days ,
String checkpro, String checkdate, int iArchieveState,
int startvalue,int endvalue,int sortvalue) throws APIException
{
return getQueueItemDAO().getProDateRowsClosed(strpro, days , checkpro,
checkdate,iArchieveState,startvalue, endvalue,sortvalue);
}
public List<QueueItem> getProDateRowsDeferred(String strpro , int days ,
String checkpro, String checkdate, int iArchieveState,
int startvalue,int endvalue,int sortvalue) throws APIException
{
return getQueueItemDAO().getProDateRowsDeferred(strpro, days, checkpro,
checkdate,iArchieveState,startvalue, endvalue,sortvalue);
}
public List<QueueItem> getProcedureAllRows()
{
return getQueueItemDAO().getProcedureAllRows();
}
public List<DateItems> getDateMonths()
{
return getQueueItemDAO().getDateMonths();
}
public List<QueueItem> getArchivedRows()
{
return getQueueItemDAO().getArchivedRows();
}
public List<QueueItem> getClosedArchivedRows()
{
return getQueueItemDAO().getClosedArchivedRows();
}
public List<QueueItem> getDeferredArchivedRows()
{
return getQueueItemDAO().getDeferredArchivedRows();
}
public void getUnArchivedRows(int arr[])
{
getQueueItemDAO().getUnArchivedRows(arr);
}
@Authorized(Privilege.MANAGE_QUEUE)
public QueueItem getQueueItemByUuid(String uuid) {
return getQueueItemDAO().getQueueItemByUuid(uuid);
}
@Authorized(Privilege.MANAGE_QUEUE)
public void purgeQueueItem(QueueItem queueItem) {
getQueueItemDAO().purgeQueueItem(queueItem);
}
@Authorized(Privilege.MANAGE_QUEUE)
public void voidQueueItem(QueueItem queueItem) {
getQueueItemDAO().voidQueueItem(queueItem);
}
}
|
PHP | UTF-8 | 1,551 | 3.15625 | 3 | [] | no_license | <?php
class Promotion {
/**
* @var integer
*/
private $id;
/**
* @var string
*/
private $name;
/**
* @var array
*/
private $variants;
/**
* @var boolean
*/
private $valid = false;
public function __construct($promotion) {
if(!is_array($promotion))
throw new Exception('Not an array');
$this->id = $promotion['id'];
$this->name = $promotion['name'];
$this->variants = [];
foreach($promotion['rules'] as $rule) {
if($rule['type'] == 'contains_product')
$this->variants[] = $rule['configuration']['variant'];
}
if(count($promotion['rules']) == count($this->variants))
$this->valid = true;
}
/**
* @return string
*/
public function getName() {
return $this->name;
}
/**
* @param string $name
*/
public function setName( $name ) {
$this->name = $name;
}
/**
* @return array
*/
public function getVariants() {
return $this->variants;
}
/**
* @param array $variants
*/
public function setVariants( $variants ) {
$this->variants = $variants;
}
public function getVariantsJson(){
return json_encode($this->variants);
}
/**
* @return boolean
*/
public function isValid() {
return $this->valid;
}
/**
* @param boolean $valid
*/
public function setValid( $valid ) {
$this->valid = $valid;
}
/**
* @return int
*/
public function getId() {
return $this->id;
}
public function isAllEventsPresent($events)
{
foreach($this->variants as $variant)
{
if(!in_array($variant, $events))
return false;
}
return true;
}
}
|
C | UTF-8 | 3,188 | 2.546875 | 3 | [] | no_license | #include "common.h"
#define SHMSZ1 800
#define SHMSZ2 100
#define SHMSZ3 100
#define QUEUE_SIZE 5
void Async_API(client_request *q, int *queue_full, sem_t *semlock, int num_req)
{
int req_count = 0; //keeps track of the number of requests made by process
if(!(*queue_full))
*queue_full = 0; // indicates that the queue has something inside it
int *queue_counter = queue_full + 4;
int *queue_fifo_id_counter = queue_full + 8; // to keep track of global fifo_priority ID
client_request *q_index;
while(req_count < num_req)
{ //printf("Request count:%d \n",req_count);
//semwait:
// check to see if semaphore locked (sem_wait) -- TODO
printf("Waiting for lock by %d \n", getpid());
sem_wait(semlock);
printf(" Acquired lock by %d \n", getpid());
q_index = q;
if(*queue_counter < QUEUE_SIZE) // => Queue is not full yet
{
// Iterate through the elements of the queue based to fill in request
int i;
for(i=0; i<QUEUE_SIZE; i++,q_index++)
{
if(!q_index->full)
{
q_index->PID = getpid();
q_index->reqID = req_count++; //current request id
q_index->input = 2;
q_index->fifo_priority = (*queue_fifo_id_counter)++; //fifo prio based on global counter
q_index->full = 1;
if(*queue_full == 0)
{ printf("changing queue full\n");
(*queue_full) = 1;
}
(*queue_counter) += 1;
//req_count++;
// Release the lock -- TODO
printf("valid bit of queue index = %d \n",q_index->valid);
printf("Released lock after insertion %d\n", getpid());
sem_post(semlock);
//inserted_flag = 1;
//break;
}
}
}
else if(*queue_counter == QUEUE_SIZE) // => Queue is full
{
printf("Released lock when queue ful %d\n", getpid());
sem_post(semlock);
//printf("Queue is Full! \n");
q_index = q;
// Iterate through the elements of the queue and check for any complete requests based on client PID
int i;
for(i=1; i<QUEUE_SIZE; i++,q_index++)
{
if(q_index->PID == getpid())
{
if(q_index->valid == 1)
{
// might need to get lock here
sem_wait(semlock);
printf("The result is %d \n", q_index->output);
(*queue_counter) -= 1;
if((*queue_counter) == 0)
{
(*queue_full) = 0;
}
// Release the queue lock held (sem_post)-- TODO
sem_post(semlock);
q_index->full = 0;
q_index->valid = 0;
//break;
}
}
}
}
}
// All requests enqueued, check for pending responses
int request_pending;
do
{
//printf("All request enqueued - waiting for results\n");
q_index = q;
request_pending = 0;
int i;
for(i=0; i<QUEUE_SIZE; i++,q_index++)
{
if(q_index->PID == getpid() && q_index->full==1){
// My own request which is not serviced yet
if(!q_index->valid){
request_pending = 1;
}
else {
// Its my request which has been serviced
printf("The result is %d \n", q_index->output);
q_index->valid = 0;
q_index->full = 0; // Freeing up the request slot
(*queue_counter) -= 1;
if((*queue_counter) == 0)
{
(*queue_full) = 0;
}
}
}
}
}while(request_pending);
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.