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
|
|---|---|---|---|---|---|---|---|
PHP
|
UTF-8
| 2,224
| 2.53125
| 3
|
[
"MIT"
] |
permissive
|
<?php
namespace App\Http\Controllers\Admin;
use App\Http\Models\BlogUsers;
use Illuminate\Support\Facades\Session;
use Validator;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
class LoginController extends Controller
{
/**
* @param Request
* @return [type]
*/
public function login(Request $request){
// dd($request);
if ($request->method() == 'POST'){
$validator = Validator::make($request->all(),[
'username'=> 'required|min:1',
'password'=> 'required|min:1',
'captcha'=> 'required|captcha',
],[
'required' => ' :attribute 不能为空.',
'captcha' => ' :attribute 错误.',
'min' => ' :attribute 长度不足.',
],[
'username'=>'用户名',
'password'=>'密码',
'captcha'=>'验证码',
]);
if ($validator->fails()) {
return back()
->withErrors($validator)
->withInput();
}
$login_data['username'] = $request->input('username');
$login_data['password'] = $request->input('password');
//验证用户名密码是否符合->数据库
$re_validate = BlogUsers::checkAdmin($login_data);
// $pass = password_hash()
if ($re_validate){
Session::put('admin',$login_data['username']);
return redirect('admin/index');
}else{
$request->flash();
return back()->withInput()->with(['response'=>'用户名或密码错误~']);
}
}
if (!Session::has('admin')){
return view('admin.login');
}else{
return redirect('admin/index');
}
}
/*
* @todo 后台首页
*/
public function view(){
return view('admin.index');
}
/**
* @param string
*/
public function loginout(Request $request)
{
// 清空session
$request->session()->flush();
// 重定向到login
return redirect('admin/login');
}
}
|
Python
|
UTF-8
| 391
| 2.96875
| 3
|
[] |
no_license
|
# Simply read adc values . by Stefania Saladino)
#
import time
# Import the GianoPi.py file (must be in the same directory as this file!).
import GianoPi
# Create an instance of the robot
gianopirobot = GianoPi.GianoPi()
# Now test 4 ground sensors
while(True):
four_line_sensors = gianopirobot.get_ground_sensors()
for i in range (4):
print "C[",i,"] = ", four_line_sensors[i]
|
Java
|
UTF-8
| 1,577
| 2.375
| 2
|
[] |
no_license
|
package com.leyou.gateway.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;
/**
* <p>Description: </P>
*
* @author Wu
* @create 2018-11-01-17:48
*/
@Configuration
public class ClobalCorsConfig
{
@Bean
public CorsFilter corsFilter()
{
//1、允许CORS的配置
CorsConfiguration config = new CorsConfiguration();
//1)允许的域,不要写*,否则cookies无法使用
config.addAllowedOrigin("http://manage.leyou.com");
config.addAllowedOrigin("http://www.leyou.com");
//2)是否发送cookie信息
config.setAllowCredentials(true);
//3)允许的请求方式
config.addAllowedMethod(HttpMethod.GET);
config.addAllowedMethod(HttpMethod.POST);
config.addAllowedMethod(HttpMethod.PUT);
config.addAllowedMethod(HttpMethod.DELETE);
config.addAllowedMethod(HttpMethod.HEAD);
config.addAllowedMethod(HttpMethod.OPTIONS);
config.addAllowedMethod(HttpMethod.PATCH);
//4)允许的请求头信息
config.addAllowedHeader("*");
//5)有效时长
config.setMaxAge(3600L);
//2、添加映射路径,拦截一切请求
UrlBasedCorsConfigurationSource configSource = new UrlBasedCorsConfigurationSource();
configSource.registerCorsConfiguration("/**", config);
//3、返回新的CorsFilter
return new CorsFilter(configSource);
}
}
|
Markdown
|
UTF-8
| 14,781
| 3.296875
| 3
|
[] |
no_license
|
# Loom
[](https://travis-ci.org/warrickbayman/Loom)
[](https://packagist.org/packages/warrickbayman/loom)
[](https://packagist.org/packages/warrickbayman/loom)
[](https://scrutinizer-ci.com/g/warrickbayman/Loom/?branch=1.1)
[](https://packagist.org/packages/warrickbayman/loom)
[](https://insight.sensiolabs.com/projects/77e1616d-b220-4031-9a74-45dbe9258d1d)
Loom is a super simple way to work with units of time (hours, minutes, seconds, etc).
## Why?
Because who knows what this means?
```php
$something = someFunctionWithTime(7200);
```
The `7200` is meaningless. Seconds? Hours? Years? So I started Loom to wrap numbers when working with time constants in a way that was readable:
```php
$loom = Loom::make()->fromHours(2);
$something = someFunctionWithTime($loom->getSeconds());
```
Sure, it's longer, but it's so much easier to read. Plus, you get a bit of functionality to convert from one unit of time to another.
Loom is tested on PHP 5.4, 5.5, 5.6, 7.0 and HHVM. It has no dependencies except for PHPUnit when testing. It is framework agnostic, but I use it quite a bit on a number of projects mostly using the Laravel framework, so it's well tested there.
Let me know if and how you use it.
## Installation
Install Loom via Composer, by adding to the `requires` section of your `composer.json` file.
```json
{
"require": {
"warrickbayman/loom": "~1.0"
}
}
```
Run `composer update` in your project root to install Loom.
## Use
### Creating a new Loom object
There are three methods to choose from when instantiating Loom.
You create a new instance of the `Loom` object:
```php
$loom = new Loom\Loom(new Loom\Seconds(100));
```
To avoid having to use the `Loom` namespace each time, you could add it to your `use` clause:
```php
use Loom\Loom;
use Loom\Seconds;
class MyLoomClass
{
public function translate()
{
$loom = new Loom(new Seconds(100));
}
}
```
A recommended method is to inject the `LoomFactory` class into your constructor and call the available creation methods from there:
```php
class MyLoomClass
{
private $loom;
public function __construct(Loom\LoomFactory $loom)
{
$this->loom = $loom->fromSeconds(240);
}
public function translate()
{
return $this->loom->getMinutes(); // 4
}
}
```
Lastly, the simplest by far, is to call the static `make()` method on the `Loom` object, which returns a new instance of `LoomFactory`. Since the creation methods on `LoomFactory` returns a new `Loom` object, you can chain the translator methods onto the factory creation, and use Loom in a single line:
```php
$minutes = Loom::make()->fromHours(2)->getMinutes(); // 120
```
The creation methods on `LoomFactory`:
```php
$loomFactory->fromMicroseconds($microseconds);
$loomFactory->fromMilliseconds($milliseconds);
$loomFactory->fromSeconds($seconds);
$loomFactory->fromMinutes($minutes);
$loomFactory->fromHours($hours);
$loomFactory->fromDays($days);
$loomFactory->fromWeeks($weeks);
$loomFactory->fromMonths($months);
$loomFactory->fromYears($years);
```
There is also a `fromLoom()` method which creates a new instance of the `Loom` object passed as a paramter.
__Note:__ that the `fromLoom()` used to be named `copy()` but was never documented. Just in case, I've deprecated the `copy()` method until the next major release.
### Using DateTime
The `LoomFactory` object also provides a `fromDateTime` method which allows you to create a Loom object from a `DateTime` object.
```php
$loom = $loomFactory->fromDateTime(new \DateTime('2015-01-21');
```
The new loom object will represent the amount of time that has passed since the Epoc (1970-01-01 00:00:00). So, in other words, doing this...
```php
var_dump($loom->getHours());
```
... will get you the number of hours since the 1st of January 1970. This becomes a little more useful when you you need to get the difference between two specific dates:
```php
$loom = Loom::make()->fromDateTime(new \DateTime('2015-01-21'));
$result = $loom->diff(Loom::make()->fromDateTime(new \DateTime('2015-01-27'));
var_dump($result->getDays()); // 6
var_dump($result->getHours()); // 144
var_dump($result->getMinutes()); // 8640
```
And since libraries like `nesbot\carbon` simply extend the `DateTime` object, you can do things like this as well...
```php
$loom = Loom::make()->fromTime(\Carbon\Carbon::now());
```
### Getters
Loom provides some simple ways to translate from one unit to another.
```php
$microseconds = $loom->getMicroseconds();
$milliseconds = $loom->getMilliseconds();
$seconds = $loom->getSeconds();
$minutes = $loom->getMinutes();
$hours = $loom->getHours();
$days = $loom->getDays();
$weeks = $loom->getWeeks();
$months = $loom->getMonths();
$years = $loom->getYears();
```
Each of the getters return a float.
### Days per month get averaged!
By default, Loom will average the number of days per month. This means results can be unexpected when working with months:
```php
$loom = Loom::make()->fromDays(30);
var_dump($loom->getMonths()); // Returns 0.98630136986301
$loom = Loom::make()->fromMonths(1);
var_dump($loom->getDays()); // Returns 30.416666666667
```
To prevent this from happening, the `getMonths()` method will accept an integer for the number of days in a month, so you could do:
```php
$loom = Loom::make()->fromDays(60);
var_dump($loom->getMonths(30)); // 2
```
You can do the same when creating a new `Loom` object from Months:
```php
$loom = Loom::make()->fromMonths(12, 31);
var_dump($loom->getDays()); // 372
```
### Solar Year
A year is not exactly 365 days long. Instead, it is ever so slightly longer than that. The current mean solar year is 365 days, 5 hours, 48 minutes and 45.19 seconds. Loom can use the solar year length of 365.2421897 days instead of simply 365 days by passing a boolean `true` as the second parameter when using the year methods. By default, Loom uses a flat 365 days to represent a year:
```php
$loom = Loom::make()->fromYears(1, true);
var_dump($loom->getDays()); // 365.2421897
$loom = Loom:make()->fromMonths(12);
var_dump($loom->getYears(true)); // 0.99933690656
```
### Difference
You can use the `diff()` method to get the difference between two Loom objects. The `diff()` method returns a new Loom object.
```php
$loom1 = Loom::make()->fromDays(1);
$loom2 = Loom::make()->fromHours(48);
$diff = $loom1->diff($loom2);
var_dump($diff->getHours()); // Returns 24.
```
It doesn't matter which object you call the `diff()` method on. The result will be the same either way.
There are also two time saving methods available which returns the difference until a specific time, or since a specific
time. The aptly name `until()` and `since()` methods are only really useful if you first create a Loom object from a
PHP `DateTime` object. Both methods return a new Loom object.
```php
$loomPast = Loom::make()->fromDateTime(new \DateTime('now - 5 days'));
$loomFuture = Loom::make()->fromDateTime(new \DateTime('now + 10 days'));
var_dump($loomPast->since()->getHours()); // Returns 120.
var_dump($loomFuture->until()->getHours()); // Returns 240.
```
The `since()` and `until()` methods simply do a `diff()` on the two Loom objects, and since the `diff()` method will
always return a positive number, the `since()` and `until()` methods are actually identical. They exist simply to help make your code a little more readable.
### Comparisons
A number of comparison methods also exist:
```php
$loom1 = Loom::make()->fromDays(1);
$loom2 = Loom::make()->fromHours(48);
// Equal to
$loom1->eq($loom2); // false
// Not equal to
$loom1->neq($loom2); // true
// Greater than
$loom1->gt($loom2); // false
// Greater than or equal to
$loom1->gte($loom2); // false
// Less than
$loom1->lt($loom2); // true
// Less than or equal to
$loom1->lte($loom2); // true
```
Here it _is_ important which object you call the comparison methods on. The object you call on is always on the left of the equasion.
### Between
Loom provides a way to check if a unit falls between two other units. The `isBetween` method takes two Loom objects which means you can use any of the creation methods:
```php
$loom = Loom::make()->fromSeconds(100);
if ($loom->isBetween(
Loom::make()->fromMinutes(1),
Loom::make()->fromMinutes(2)
)) {
echo 'Hooray!';
}
```
The `isBetween` method is also accepts a second boolean parameter to specify if the the limits should be inclusive or exclusive. By default, `isBetween` is exclusive of the limits. In otherwords, if the value you are checking is equal to the upper limit, the result will be `false`.
You can get `isBetween` to include the limits in the comparrison by passing a boolean `true` as the third parameter:
```php
$loom = Loom::make()->fromSeconds(120);
// Default is exclusive. Returns false.
var_dump($loom->isBetween(
Loom::make()->fromMinutes(1),
Loom::make()->fromMinutes(2)
));
// Inclusive. Returns true.
var_dump($loom->isBetween(
Loom::make()->fromMinutes(1),
Loom::make()->fromMinutes(2),
true
));
```
### Simple Arithmetic
You can perform some simple arithmetic through the `add()` and `sub()` methods:
```php
$loom = Loom::make()->fromMinutes(2);
$loom->add(Loom::make()->fromSeconds(30));
var_dump($loom->getSeconds()) // 150
$loom->sub(Loom::make()->fromHours(1));
var_dump($loom->getMilliseconds); // 0
```
A `Loom` object can never have a negative value. Subtracting a larger Loom from a smaller one will always result in 0.
The arithmetic methods will accept an instance of `AbstractUnit`, so you don't need to create another `Loom` object. You can just pass the unit into the methods:
```php
$loom = Loom::make()->fromMinutes(2);
$loom->add(new Loom\Seconds(60));
var_dump($loom->getSeconds()); // 180
$loom->sub(new Loom\Minutes(2));
var_dump($loom->getSeconds()); // 60
```
## Loom Collections
A new `LoomCollection` class is currently in development and is available on the `develop` branch. Loom Collections are based on the Laravel `Collection` class, but with some _Loomness_ built in.
The new `LoomCollection` class constructor accepts an array of Loom objects, but you can also create an empty collection:
```php
$collection = new Loom\LoomCollection();
```
Loom Collections can only contain `Loom` objects. You'll get an exception if you try add anything else.
### Push, Pop, Prepend, Shift
Manipulating the contents of a `LoomCollection` is quite simple. Use the `push` method to push a new Loom object onto the end of the collection, the `pop` method to pull the last Loom object, the `prepend` method to insert a Loom object onto the beginning of the collection and `shift` to pull the first objct.
```php
// Add to the end of the collection
$collection->push(new Loom::make()->fromMinutes(4));
// Add to the beginning of the collection
$collection->prepend(new Loom::make()->fromMinutes(10));
// Pull the last object from the collection
$loom = $collection->pop();
// Pull the first object from the collection
$loom = $collection->shift();
```
### Finding
Loom provides a simple way to grab single Loom objects from the collection. You can always get the first Loom object by using the `first()` method. In the same manner, the `last()` method will always return the last object in the collection.
```php
$first = $collection->first();
$last = $collection->last();
```
Unlike `pop()` and `shift()`, these methods do not alter the collection and only return the Loom object.
Sometimes, you might need to get the shortest, or longest Loom object. You can use the `shortest()` and `longest()` methods to do just that. There is also an `earliest()` method, which is just an alias for `shortest`, and a `latest()`, which is an alias for `longest`.
```php
$shortest = $collection->shortest();
$longest = $collection->longest();
```
### Filtering
No collections class would be complete without the ability to filter the contents of a collection. The best place to start is the `filter` method which accepts a closure. The Loom objects are passed as parameters to the closure. If the closure returns a boolean `true` then that object is included in the filtered results:
```php
$filtered = $collection->filter(function(Loom $loom)
{
return $loom->gt(Loom::make()->fromMinutes(6);
});
```
However, Loom also includes a few extra filter methods that make this process easier. The `after()` method will return all the Loom objects that occure after the specified Loom, and the `before()` method will return lla the objects that occure before the specified Loom.
```php
// After
$newCollection = $collection->after(Loom::make()->fromMinutes(8));
// Before
$newCollection = $collection->before(Loom::make()->fromMinutes(6));
```
There is also a `between()` method that will return objects that occure between the specified start and end Looms.
```php
$newCollection = $collection->between(
Loom::make()->fromMinutes(5),
Loom::make()->fromHours(1)
);
```
### Iterating
The `LoomCollection` class also includes an `each()` method which accepts a closure to which is passed each Loom in the collection.
```php
$newCollection = $collection->each(function(Loom $loom)
{
echo $loom->getMinutes();
});
```
### Sorting
The collection can also be sorted using the appropriately named `sort()` method. By default `sort()` will sort the collection ascending (smallest Loom first), but you can invert the sort by passing a boolean `true` as parameter.
```php
// Ascending
$sorted = $collection->sort();
// Descending
$sorted = $collection->sort(true);
```
## Ranges
Loom provides an interesting feature which allows you to create a range of Loom objects. Ranges are always returned as Loom Collections. Creating a range is fairly simple. Instead of calling the `make()` static method, there is now a `makeRange()` static method on the `Loom` class. You can pass a single Loom object to the `from()` method, and one to the `to()` method. The `steps()` method takes an integer parameter and returns a new `LoomCollection` instance:
```php
$range = Loom::makeRange()
->from(Loom::make()->fromSeconds(1))
->to(Loom::make()->fromSeconds(10))
->steps(10);
```
This will return a new `LoomCollection` consisting of 10 Loom objects. The first one being 1 seconds, and the last one being 10 seconds.
|
Shell
|
UTF-8
| 116
| 2.53125
| 3
|
[
"MIT"
] |
permissive
|
#!/bin/sh
set -e
if ! [ -d 'node_modules' ]; then
npm install
fi
BABEL_ENV=dev exec node -r babel-register "$1"
|
Markdown
|
UTF-8
| 2,942
| 2.640625
| 3
|
[] |
no_license
|
---
categories:
- WordPress
date: "2011-10-30T06:53:37+09:00"
slug: 1066
title: "[WP Plugins] 「Recent Posts Plus」で、サイドバーの最新の記事に「はてなブックマーク数」を表示する"
---
WordPress は、標準で「最新の記事」を表示してません(テーマによっては対応しているようです)。
最近の記事は、いつもトップに表示してあるから別にいいやと思っていたのですが、「ブログは線でなく点で読まれる」という格言を聞いてから、急いで「最新の記事」をサイドバーに用意しました。
今回は、ちょこっと手を加えて、はてなブックマーク数を表示させる方法を忘備録がてら、ご紹介します。
完成予想図はこんな感じになります。青のリンクに赤のはてブが映える!
<img alt="" src="/images/2011/10/1066_1.jpg" width="392" height="324">
## 「Recent Posts Plus」設定手順
最近の記事をサイドバーに表示する「Recent Posts Plus」というプラグインを導入します。
[http://wordpress.org/extend/plugins/recent-posts-plus/](http://wordpress.org/extend/plugins/recent-posts-plus/)
WordPress 公式サイトから zip ファイルをダウンロードして展開後、FTP アプリで「/wp-content/plugins/」にアップロードし、「WordPress 管理画面」→「プラグイン」→「インストール済みプラグイン」で「有効化」する。
もしくは、「WordPress 管理画面」→「プラグイン」→「新規追加」で「Recent Posts Plus」を検索し、「いますぐインストール」→「プラグインを有効化」する。
有効化した後、「WordPress 管理画面」→「外観」→「ウィジェット」に移動します。
「利用できるウィジェット」に「Recent Posts Plus」というのがあるので、それをドラッグアンドドロップでサイドバーに追加します。
<img alt="" src="/images/2011/10/1066_2.jpg" width="301" height="368">
一番下にある「Show expert options」にチェックして、拡張機能を展開します。
<img alt="" src="/images/2011/10/1066_3.jpg" width="301" height="513">
「Widget Output Template」には、最初このように記述されています。
```html
<li>
{THUMBNAIL}
<a title="{TITLE_RAW}" href="{PERMALINK}"> {TITLE} </a>
{EXCERPT}
</li>
```
今回は、記事タイトルの最後に「はてなブックマーク数」を表示するので、「Widget Output Template」を次のように変更します。
```html
<li>
<a title="{TITLE_RAW}" href="{PERMALINK}">{TITLE}</a>
<a href="http://b.hatena.ne.jp/entry/{PERMALINK}" target="_blank">
<img border="0" src="http://b.hatena.ne.jp/entry/image/{PERMALINK}" />
</a>
</li>
```
「保存」をクリックして、完成です。
ブログを確認してみましょう。
|
Java
|
UTF-8
| 4,530
| 2.046875
| 2
|
[] |
no_license
|
package com.origicheck.africababa.fragments.products.categories;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import com.origicheck.africababa.R;
import com.origicheck.africababa.controller.fragments.FragmentWrapper;
import com.origicheck.africababa.controller.intents.Intents;
import com.origicheck.africababa.datamodels.products.categories.ProductCategoriesInfo;
import com.origicheck.africababa.sync.worker.SyncExecutorThread;
import java.util.List;
/**
* Created by victor on 10/2/2015.
*/
public class FragmentCategories extends FragmentWrapper implements AdapterView.OnItemClickListener {
public OnProductCategoryClick onProductCategoryClick;
private View mCategoriesView;
private ListView mCategoriesListView;
private List<ProductCategoriesInfo> productCategoriesInfos;
private List<String> productCategories;
private Receiver receiver;
@Override
public void onCreateFragment(@Nullable Bundle savedInstanceState) {
receiver = new Receiver();
getActivity().registerReceiver(receiver, new IntentFilter(Intents.ACTION_SYNCED_CATEGORY));
}
@NonNull
@Override
public String getActivityTitle() {
return getActivity().getResources().getString(R.string.title_fragment_product_categories);
}
@Override
public void receiveBundle() {
}
@Nullable
@Override
public void onCreateFragmentView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
mCategoriesView = getActivity().getLayoutInflater().inflate(getParentLayout(), container, false);
initChildViews(mCategoriesView);
getContainer().addView(mCategoriesView);
}
@Override
public void consumeBundle() {
}
@Override
public void onAttachFragment() {
onProductCategoryClick = (OnProductCategoryClick) getActivity();
}
@Override
public void onResumeFragment() {
}
@Override
public void performPartialSync() {
if (getUtils().getUserAccountsManager().isExistsUserAccount()) {
if (getUtils().getPrefsManager().isLoggedIn()) {
//FORCE A SYNC
SyncExecutorThread syncExecutor = new SyncExecutorThread(getActivity(), getUtils());
syncExecutor.syncCategory();
}
}
}
@Override
public void onPerformPartialSync() {
populateProductCategories();
}
@Override
public void onPauseFragment() {
}
@Override
public void onDestroyFragment() {
getActivity().unregisterReceiver(receiver);
}
@Override
public int getParentLayout() {
return R.layout.fragment_product_categories;
}
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
if (parent == mCategoriesListView) {
int productCategory = productCategoriesInfos.get(position).getCategoryId();
onProductCategoryClick.onProductCategoryClick(productCategory);
}
}
private void initChildViews(@NonNull View categoriesView) {
mCategoriesListView = (ListView) categoriesView.findViewById(R.id.fragment_product_categories_listView_categories);
populateProductCategories();
mCategoriesListView.setOnItemClickListener(this);
}
private void populateProductCategories() {
productCategoriesInfos = getUtils().getTransactionsManager().getProductCategoriesList();
productCategories = getUtils().getViewCreator().getProductCategoriesList(productCategoriesInfos);
mCategoriesListView.setAdapter(new ArrayAdapter<String>(getActivity(), android.R.layout.simple_list_item_1, productCategories));
}
public interface OnProductCategoryClick {
void onProductCategoryClick(int productCategory);
}
private class Receiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(Intents.ACTION_SYNCED_CATEGORY)) {
onPerformPartialSync();
}
}
}
}
|
Python
|
UTF-8
| 1,867
| 3.0625
| 3
|
[] |
no_license
|
# import logging
# logging.basicConfig(level = logging.DEBUG)
# logging.debug("This will get logged")
# logging.basicConfig(filename='app.log', filemode ='w',
# format = '%(name)s - %(levelname)s - %(message)s')
# logging.warning("This will get logged to a file")
# logging.basicConfig(format='%(process)d-%(levelname)s-%(message)s')
# logging.warning("This is a warning")
# logging.basicConfig(format='%(asctime)s-%(message)s', level = logging.INFO)
# logging.info('Admin logged in')
# logging.basicConfig(format='%(asctime)s-%(message)s', datefmt='%d-%b-%y %H:%M:%S')
# logging.warning('Admin logged out')
# name = "John"
# logging.error(f'{name} raised an error',)
#capturing stack tress
'''
import logging
a=5
b=0
try:
c=a/b
except Exception as e:
# logging.error("Exception occured",exc_info=True)
logging.exception("Exception occurred")
'''
#creating our custom logger and using handlers
'''
import logging
#create a custom logger
logger = logging.getLogger(__name__)
#create handlers
c_handler = logging.StreamHandler()
f_handler = logging.FileHandler('file.log')
c_handler.setLevel(logging.WARNING)
f_handler.setLevel(logging.ERROR)
#create formatters and add it to the handlers
c_format = logging.Formatter('%(name)s - %(levelname)s-%(message)s')
f_format = logging.Formatter('%(asctime)s - %(name)s -%(levelname)s- %(message)s')
c_handler.setFormatter(c_format)
f_handler.setFormatter(f_format)
#add handlers to the logger
logger.addHandler(c_handler)
logger.addHandler(f_handler)
logger.warning('This is a warning')
logger.error('This is an error')
'''
# Other configuration methods
import logging
import logging.config
logging.config.fileConfig(fname ='logging.conf', disable_existing_loggers=False)
#get the logger specified in the file
logger = logging.getLogger(__name__)
logger.debug('This is a debug message')
|
Java
|
UTF-8
| 1,264
| 3.203125
| 3
|
[] |
no_license
|
public class Copo {
//Variaveis/Propriedades de instancia
private String liquido;
private double capacidade;
private double contem;
//Construtores
public Copo(){
liquido="Desconhecido";
capacidade=25.0;
contem=0.0;
}
public Copo(String liq, double volume){
liquido=liq;
capacidade=volume;
contem=0.0;
}
public String getLiquido() {
return liquido;
}
public void encher(double volume){
if(contem + volume>=capacidade){
contem=capacidade;
}
else{
contem +=volume;
}
}
public void setLiquido(String nomeLiquido){
liquido=nomeLiquido;
}
public void esvaziar(double volume){
double aux=contem-volume;
contem=((aux)<=0.0) ? 0.0 : aux;
/*
* if(aux<=0.0){
* contem=0.0;
* else{
* contem=aux;}
*/
}
// -------------------------------------------------------------------------------------------//
public double getCapacidade() {
return capacidade;
}
// -------------------------------------------------------------------------------------------//
public double getContem() {
return contem;
}
public boolean cheio(){
return contem==capacidade;
}
public int quantoEmPercentagem(){
return(int)Math.round(contem/capacidade*100);
}
}
|
Shell
|
UTF-8
| 508
| 2.78125
| 3
|
[] |
no_license
|
#!/bin/bash
cd gke && \
echo "Generando kubeconfig file"
pulumi stack output kubeconfig --show-secrets > kubeconfig.yaml \
ip=$(pulumi stack output ingress_ip) \
echo -e "\nIngress $ip" &&\
echo -e "\nkubectl get pod" &&\
KUBECONFIG=./kubeconfig.yaml kubectl get po &&\
sleep 20 \
echo -e "\nEndpoint greetings:" &&\
curl -XGET "http://$ip/greetings" \
echo -e "\nEndpoint square:" \
curl -XPOST -d number=98746 "http://$ip/square"
|
Python
|
UTF-8
| 300
| 3
| 3
|
[] |
no_license
|
# https://projecteuler.net/problem=53
# How many, not necessarily distinct, values of nCr, for 1 ≤ n ≤ 100,
# are greater than one-million?
from math import factorial as f
def C(n, r): return f(n) // (f(r) * f(n - r))
print(sum(C(n, r) > 1000000 for n in range(23, 101) for r in range(1, n)))
|
JavaScript
|
UTF-8
| 1,738
| 2.8125
| 3
|
[] |
no_license
|
const chai = require("chai");
const {normalizeExchangeRate} = require('../helpers/helper').helper;
const {getAllCurrencies} = require('../helpers/helper').helper;
const expect = chai.expect;
const mockExchangeRates = [{
'$': {
currency: 'USD',
rate: '1.1294'
}
},
{
'$': {
currency: 'JPY',
rate: '125.09'
}
},
{
'$': {
currency: 'ZAR',
rate: '16.0000'
}
}
]
let mockedNormalizedExchangeResult = []
mockedNormalizedExchangeResult['EUROUSD'] = {
sourceCurrency: 'EURO',
targetCurrency: 'USD',
rate: '1.1294'
},
mockedNormalizedExchangeResult['EUROJPY'] = {
sourceCurrency: 'EURO',
targetCurrency: 'JPY',
rate: '125.09'
},
mockedNormalizedExchangeResult['EUROZAR'] = {
sourceCurrency: 'EURO',
targetCurrency: 'ZAR',
rate: '16.0000'
}
const mockedCurrencies = ['EURO', 'USD', 'JPY', 'ZAR']
describe('normalizeExchangeRate', function () {
it('returns an array', function () {
const result = normalizeExchangeRate(mockExchangeRates)
expect(result).to.not.empty
expect(result).to.be.an('array')
})
it('returns the supported currencies', function () {
const result = normalizeExchangeRate(mockExchangeRates)
expect(result[1]).to.eql(mockedCurrencies)
})
it('returns the normalized exchange rates', function () {
const result = normalizeExchangeRate(mockExchangeRates)
expect(result[0]).to.eql(mockedNormalizedExchangeResult)
})
})
describe('getAllCurrencies', function () {
it('return normalized exchange rates for each currency against the other',function(){
const result = getAllCurrencies(mockedNormalizedExchangeResult, mockedCurrencies)
expect(Object.keys(result).length).to.eql(12)
})
})
|
Java
|
UTF-8
| 464
| 3.265625
| 3
|
[] |
no_license
|
package hash;
import java.util.HashMap;
import java.util.Map;
public class Main {
public static void main(String[] args) {
Map<Character, Integer> map = new HashMap<>();
String s = "ABBCDDD";
char[] chars = s.toCharArray();
for (int i = 0; i < chars.length; i++) {
char c = chars[i];
if (map.containsKey(c)) {
Integer value = map.get(c) + 1;
map.put(c, value);
} else {
map.put(c, 1);
}
}
System.out.println(map);
}
}
|
Python
|
UTF-8
| 321
| 3.28125
| 3
|
[] |
no_license
|
long_number = ''
with open('num.txt') as inputfile:
for line in inputfile:
long_number = line.strip().split(',')[0]
total = 0
half_length = len(long_number) / 2
for index, char in enumerate(long_number[:half_length]):
if char == long_number[index+half_length]:
total += int(char)
print total * 2
|
Java
|
UTF-8
| 6,278
| 2.109375
| 2
|
[] |
no_license
|
package ru.kvaga.amphora.svfp.iso8583.lt.loadgenerator.configuration;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Properties;
public class SystemConfigurator extends Configurator {
public String ISO_SERVER_HOST = "10.1.14.56",//"192.168.203.16",
LOG_FILE_COMMON = "ISOServerLogCommon.log",
LOG_FILE_SENDER = "ISOServerLogSender.log",
LOG_FILE_RECEIVER = "ISOServerLogCommon.log",
LOG_FILE_TPS = "ISOServerLogTPS.log",
LOG_FILE_PATH = "log",
LOG_LEVEL_ON_LOAD = "WARN",
FILE_PERSISTENCE_TXN_TRACE_NUMBER = "system/persistence.txn.trace.number.sys";
public static String SendLogFullPath = "",
TPSLogFullPath = "",
RecLogFullPath = "";
public int ISO_SERVER_PORT = 2223,//7488,
SYS_ISO_SERVER_CONNECTION_TIME_OUT = 5000,
MAX_THREADS_COUNT = 50,
THREAD_SLEEP_TIME_MILLIS = 100,
RESTART_GENERATOR_THREADS_COUNT = 0,
WAIT_REC_TXN_AFTER_STOP_LOAD = 10,
MAX_TPS = 0;//default
public static String timeFormat = "yyyy-MM-dd HH:mm:ss,SSS";
public double LOAD_STEP_SIZE = 0;
public boolean LOG_FILE_USE_DEFAULT_LOG_PATH_AND_NAMES = true;
public long SYS_SLEEP_IF_LOAD_SUSPENDED_MILLIS = 1000,
UPDATE_TPS_LOG_FILE_TASK_SLEEP_IN_MILLIS = 1000;
public boolean IS_THREADS_COUNT_MONITOR = false,
DISCONNECT_ISO_CHANNEL = true;
//STOP_LOAD_AFTER_GENERATOR_START=false;
public boolean IS_THREADS_LIVETIME_MONITOR = false;
/**
* Получение системной конфигурации
*
* @return SystemConfigurator
*/
static public SystemConfigurator getInstance() {
if (configurator == null) configurator = new SystemConfigurator();
return configurator;
}
/**
* Загрузка параметров
*
* @param - файл с параметрами
* @return 0 - успех <br>
* -1 - файл не найден <br>
* -2 - ошибка ввода\вывода при чтении файла параметров<br>
* -3 - другая ошибка<br>
*/
public int loadProperties(String fileName) {
try {
Properties p = new Properties();
p.load(new FileInputStream(new File(fileName)));
if (p.getProperty("ISO_SERVER_HOST") != null) ISO_SERVER_HOST = p.getProperty("ISO_SERVER_HOST");
if (p.getProperty("ISO_SERVER_PORT") != null)
ISO_SERVER_PORT = Integer.parseInt(p.getProperty("ISO_SERVER_PORT"));
if (p.getProperty("LOG_FILE_COMMON") != null) LOG_FILE_COMMON = p.getProperty("LOG_FILE_COMMON");
if (p.getProperty("LOG_FILE_SENDER") != null) LOG_FILE_SENDER = p.getProperty("LOG_FILE_SENDER");
if (p.getProperty("LOG_FILE_RECEIVER") != null) LOG_FILE_RECEIVER = p.getProperty("LOG_FILE_RECEIVER");
if (p.getProperty("LOG_FILE_TPS") != null) LOG_FILE_TPS = p.getProperty("LOG_FILE_TPS");
if (p.getProperty("LOG_FILE_PATH") != null) LOG_FILE_PATH = p.getProperty("LOG_FILE_PATH");
if (p.getProperty("LOG_FILE_USE_DEFAULT_LOG_PATH_AND_NAMES") != null)
LOG_FILE_USE_DEFAULT_LOG_PATH_AND_NAMES = Boolean.parseBoolean(p.getProperty("LOG_FILE_USE_DEFAULT_LOG_PATH_AND_NAMES"));
if (p.getProperty("LOG_LEVEL_ON_LOAD") != null && (p.getProperty("LOG_LEVEL_ON_LOAD").equals("INFO") || p
.getProperty("LOG_LEVEL_ON_LOAD").equals("WARN")))
LOG_LEVEL_ON_LOAD = p.getProperty("LOG_LEVEL_ON_LOAD");
if (p.getProperty("SYS_SLEEP_IF_LOAD_SUSPENDED_MILLIS") != null)
SYS_SLEEP_IF_LOAD_SUSPENDED_MILLIS = Long.parseLong(p.getProperty("SYS_SLEEP_IF_LOAD_SUSPENDED_MILLIS"));
if (p.getProperty("SYS_ISO_SERVER_CONNECTION_TIME_OUT") != null)
SYS_ISO_SERVER_CONNECTION_TIME_OUT = Integer.parseInt(p.getProperty("SYS_ISO_SERVER_CONNECTION_TIME_OUT"));
if (p.getProperty("UPDATE_TPS_LOG_FILE_TASK_SLEEP_IN_MILLIS") != null)
UPDATE_TPS_LOG_FILE_TASK_SLEEP_IN_MILLIS = Long.parseLong(p.getProperty("UPDATE_TPS_LOG_FILE_TASK_SLEEP_IN_MILLIS"));
if (p.getProperty("FILE_PERSISTENCE_TXN_TRACE_NUMBER") != null)
FILE_PERSISTENCE_TXN_TRACE_NUMBER = p.getProperty("FILE_PERSISTENCE_TXN_TRACE_NUMBER");
if (p.getProperty("IS_THREADS_LIVETIME_MONITOR") != null)
IS_THREADS_LIVETIME_MONITOR = Boolean.parseBoolean(p.getProperty("IS_THREADS_LIVETIME_MONITOR"));
if (p.getProperty("IS_THREADS_COUNT_MONITOR") != null)
IS_THREADS_COUNT_MONITOR = Boolean.parseBoolean(p.getProperty("IS_THREADS_COUNT_MONITOR"));
if (p.getProperty("MAX_THREADS_COUNT") != null)
MAX_THREADS_COUNT = Integer.parseInt(p.getProperty("MAX_THREADS_COUNT"));
if (p.getProperty("THREAD_SLEEP_TIME_MILLIS") != null)
THREAD_SLEEP_TIME_MILLIS = Integer.parseInt(p.getProperty("THREAD_SLEEP_TIME_MILLIS"));
if (p.getProperty("RESTART_GENERATOR_THREADS_COUNT") != null)
RESTART_GENERATOR_THREADS_COUNT = Integer.parseInt(p.getProperty("RESTART_GENERATOR_THREADS_COUNT"));
if (p.getProperty("MAX_TPS") != null) MAX_TPS = Integer.parseInt(p.getProperty("MAX_TPS"));
if (p.getProperty("LOAD_STEP_SIZE") != null)
LOAD_STEP_SIZE = Double.parseDouble(p.getProperty("LOAD_STEP_SIZE"));
// if(p.getProperty("STOP_LOAD_AFTER_GENERATOR_START")!=null) STOP_LOAD_AFTER_GENERATOR_START = Boolean.parseBoolean(p.getProperty("STOP_LOAD_AFTER_GENERATOR_START"));
if (p.getProperty("DISCONNECT_ISO_CHANNEL") != null)
DISCONNECT_ISO_CHANNEL = Boolean.parseBoolean(p.getProperty("DISCONNECT_ISO_CHANNEL"));
if (p.getProperty("WAIT_REC_TXN_AFTER_STOP_LOAD") != null)
WAIT_REC_TXN_AFTER_STOP_LOAD = Integer.parseInt(p.getProperty("WAIT_REC_TXN_AFTER_STOP_LOAD"));
p.clear();
} catch (FileNotFoundException e) {
e.printStackTrace();
return -1;
} catch (IOException e) {
e.printStackTrace();
return -2;
} catch (Exception e) {
e.printStackTrace();
return -3;
}
return 0;
}
private static SystemConfigurator configurator = null;
}
|
Markdown
|
UTF-8
| 2,869
| 2.984375
| 3
|
[] |
no_license
|
<h1>Level 12</h1>
<h2>Level Goal</h2>
The password for the next level is stored in the file data.txt, which is a hexdump of a file that has been repeatedly compressed. For this level it may be useful to create a directory under /tmp in which you can work using mkdir. For example: mkdir /tmp/myname123. Then copy the datafile using cp, and rename it using mv (read the manpages!)
<h2>Solution</h2>
>//
$ cd ../../tmp
$ mkdir testMariyam
$ cp ../../home/bandit12/data.txt .
$ xxd -r data.txt > data1
$ file data1
>output
data1: gzip compressed data, was "data2.bin", last modified: Thu Dec 28 13:34:36 2017, max compression, from Unix
>//
$ mv data1 data1.gz
$ gzip -d data1.gz
$ file data1
>output
data1: bzip2 compressed data, block size = 900k
>//
$ bzip2 -d data1
$ file data1.out
>output
data1.out: gzip compressed data, was "data4.bin", last modified: Thu Dec 28 13:34:36 2017, max compression, from Unix
>//
$ mv data1.out data1.out.gz
$ gzip -d data1.out.gz
$ file data1.out
>output
data1.out: POSIX tar archive (GNU)
>//
$ tar xvf data1.out
$ file data5.bin
>output
data5.bin: POSIX tar archive (GNU)
>//
$ tar xvf data5.bin
$ file data6.bin
>output
data6.bin: bzip2 compressed data, block size = 900k
>//
$ bzip2 -d data6.bin
$ file data6.bin.out
>output
data6.bin.out: POSIX tar archive (GNU)
>//
$ tar xvf data6.bin.out
$ file data8.bin
>output
data8.bin: gzip compressed data, was "data9.bin", last modified: Thu Dec 28 13:34:36 2017, max compression, from Unix
>//
$ mv data8.bin data8.bin.gz
$ gzip -d data8.bin.gz
$ file data8.bin
>output
data8.bin: ASCII text
>//
$ cat data8.bin
>info
xxd - make a hexdump or do the reverse.
-r | -revert
reverse operation: convert (or patch) hexdump into binary. If not writing to stdout, xxd writes into its output file without truncating it. Use the combination -r -p to read plain hexadecimal
dumps without line number information and without a particular column layout. Additional Whitespace and line-breaks are allowed anywhere.
file -- determine file type
gzip, gunzip, zcat - compress or expand files
-d --decompress --uncompress
Decompress.
bzip2, bunzip2 - a block-sorting file compressor, v1.0.6
bzcat - decompresses files to stdout
bzip2recover - recovers data from damaged bzip2 files
-d --decompress
Force decompression. bzip2, bunzip2 and bzcat are really the same program, and the decision about what actions to take is done on the basis of which name is used. This flag overrides that
mechanism, and forces bzip2 to decompress.
>//
Password: 8ZjyCRiBWFYkneahHwxCv3wb2a1ORpYL
>//
$ ssh -p 2220 bandit13@bandit.labs.overthewire.org
|
C
|
UTF-8
| 11,227
| 2.984375
| 3
|
[] |
no_license
|
/* file: console.c */
/* purpose: source file for console I/O functions */
/* supporting both Windows (using Visual Studio 2008) */
/* and UNIX using GCC 4 platforms */
/* written by: Danny Abesdris, Catherine Leung */
#include <ctype.h>
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
#include "console.h"
void consoleDraw(char *sd, int row, int col, int len)
{
/* This function is used to display a text field containing
the string 'sd' on the screen.*/
int i;
if(sd && row>=0 && col>=0){
consoleMove(row,col); //set position
if(len<=0){
consolePutS((char*)sd);
}else{
for(i=0; i<len && sd[i]!='\0'; i++){
consolePutC(sd[i]);
}
for(;i<len;i++){
consolePutC(' ');
}
}
}
}
void consoleOn(void) {
#if PLATFORM == WINDOWS
/* no startup requirements for windows */
#elif PLATFORM == UNIX || PLATFORM == OSX
initscr( );
noecho( );
cbreak( );
keypad(stdscr, 1);
#endif
}
void consoleOff(void) {
#if PLATFORM == WINDOWS
consoleClear( );
#elif PLATFORM == UNIX || PLATFORM == OSX
refresh( );
endwin( );
#endif
}
void consoleMove(int row, int col) {
#if PLATFORM == WINDOWS /* windows specific routines for cursor control */
HANDLE hStdout;
struct _CONSOLE_SCREEN_BUFFER_INFO x;
hStdout = GetStdHandle(STD_OUTPUT_HANDLE);
GetConsoleScreenBufferInfo(hStdout, &x);
x.dwCursorPosition.X = col;
x.dwCursorPosition.Y = row;
SetConsoleCursorPosition(hStdout, x.dwCursorPosition);
#elif PLATFORM == UNIX || PLATFORM == OSX
move(row, col);
#endif
}
int consoleGetKey(void) {
int key;
#if PLATFORM == WINDOWS
key = getch( );
/* On windows, getch( ) returns 0 for function keys, but
0xE0 for all other non-ascii (extended) keys */
key = (key == 0 || key == 0xE0) ? getch( ) + 1000 : key;
#elif PLATFORM == UNIX || PLATFORM == OSX
key = getch( );
#endif
return key;
}
int consoleGetRows(void) {
int rows;
#if PLATFORM == WINDOWS
HANDLE hStdout;
struct _CONSOLE_SCREEN_BUFFER_INFO x;
hStdout = GetStdHandle(STD_OUTPUT_HANDLE);
GetConsoleScreenBufferInfo(hStdout, &x);
rows = x.dwSize.Y;
#elif PLATFORM == UNIX || PLATFORM == OSX
rows = LINES;
#endif
return rows;
}
int consoleGetCols(void) {
int cols;
#if PLATFORM == WINDOWS
HANDLE hStdout;
struct _CONSOLE_SCREEN_BUFFER_INFO x;
hStdout = GetStdHandle(STD_OUTPUT_HANDLE);
GetConsoleScreenBufferInfo(hStdout, &x);
cols = x.dwSize.X;
#elif PLATFORM == UNIX || PLATFORM == OSX
cols = COLS;
#endif
return cols;
}
void consoleClear(void) {
#if PLATFORM == WINDOWS
DWORD n; /* Number of characters written */
DWORD size; /* number of visible characters */
COORD coord = { 0 }; /* Top left screen position */
struct _CONSOLE_SCREEN_BUFFER_INFO csbi;
/* Get a handle to the console */
HANDLE h = GetStdHandle (STD_OUTPUT_HANDLE);
GetConsoleScreenBufferInfo (h, &csbi);
/* Find the number of characters to overwrite */
size = csbi.dwSize.X * csbi.dwSize.Y;
/* Overwrite the screen buffer with whitespace */
FillConsoleOutputCharacter(h, TEXT(' '), size, coord, &n);
GetConsoleScreenBufferInfo(h, &csbi);
FillConsoleOutputAttribute(h, csbi.wAttributes, size, coord, &n);
/* Reset the cursor to the top left position */
SetConsoleCursorPosition ( h, coord );
#elif PLATFORM == UNIX || PLATFORM == OSX
erase( );
#endif
}
void consolePutC(int c) {
#if PLATFORM == WINDOWS
putch(c);
#elif PLATFORM == UNIX || PLATFORM == OSX
addch(c);
#endif
}
void consolePutS(char *s) {
#if PLATFORM == WINDOWS
cputs(s);
#elif PLATFORM == UNIX || PLATFORM == OSX
addstr(s);
#endif
}
void consoleFlush(void) {
#if PLATFORM == WINDOWS
/* not required to update the screen on windows */
#elif PLATFORM == UNIX || PLATFORM == OSX
refresh( );
#endif
}
/*<CXD> version 2.1 updated to work in both Windows and UNIX*/
int consoleBox(int row, int col, int l, int h, char edge, char top_btm, char ls_rs)
{
int i=0, j=0, row_max, col_max;
row_max = consoleGetRows(); /*return if the window is sufficient for drawing the box*/
col_max = consoleGetCols();
if(row+h > row_max || col+l > col_max) /*if no sufficient screen space then return 1*/
return 0;
else /*with sufficient screen space*/
{
consoleMove(row,col); /*top*/
consolePutC(edge);
for(i=col+1;i<col+l-1;i++)
consolePutC(top_btm);
consolePutC(edge);
for(i=row+1;i<row+h-1;i++) /*middle*/
{
consoleMove(i,col);
consolePutC(ls_rs);
consoleMove(i,col+l-1);
consolePutC(ls_rs);
}
consoleMove(row+h-1,col); /*bottom*/
consolePutC(edge);
for(i=col+1;i<col+l-1;i++)
consolePutC(top_btm);
consolePutC(edge);
return 1; /*return 1 in case of drawing the box successfully*/
}
}
/*Kalid, Michael and Min Wok's function*/
int consoleEdit (char *se, int slen, int row, int col, int flen, int *start, int *offset, int *insert, int ctype){
int done = 0;
int key;
// char * temp; renamed to seTemp below
char* seTemp;
char * seTemp2;
int startTemp = *start; /* initialized intial value of start */
int startTemp2;
int offsetTemp = *offset; /* initialized intial value of offset */
int offsetTemp2;
int i; /*<MB>index for loops*/
int l; /*<MB> String Length*/
int seCurPos; /*<MB>The index number of the char array pointed to by se
which contains what the cursor is focused upon */
int validated;
validated = validateType(se, slen, ctype);
if(validated){
seTemp = (char*) malloc (sizeof(char) * (strlen(se)+1));
strcpy(seTemp, se); /* copy value of se into seTemp */
while(!done){
/*<Min Wok> display interface*/
/*<MB>Must merge with with what i have in MB_Console and Kalid's consolef.c */
seCurPos = *start + *offset;
l = strlen(se);
consoleDraw(se + *offset, row, col, flen);
consoleMove(row, col + *start);
/* consoleMove(row, col + *start-1); /*<MB> Min Wok, Are you sure about the minus 1? Cursor */
/* (replaced with above line) location is numbered starting from 0 */
key = consoleGetKey();
switch(key){
case HOME:
*start = 0;
if(*offset)
*offset = 0;
break;
case END:
if((*offset) + flen <= strlen(se)){
/*<MB> Is this intentionally blank? */
}
else{
consoleMove(row, col+(strlen(se)-(*offset)));
}
break;
case LEFT: /*By Michael*/
if(*start > 0)
(*start)--;
else if(*offset > 0)
(*offset)--;
break;
case RIGHT: /*By Michael*/
if (seCurPos < l){
if(*start < flen)
(*start)++;
else
(*offset)++;
}
break;
case INS:
if(*insert) { *insert = 0; }
else {*insert = 1; }
break;
case BS:
printf("\n\nBackspace! with securpos as : %d\n", seCurPos);
if (seCurPos > 0){
for(i = seCurPos-1; i<l; i++){
se[i] = se[i+1];
}
if(*start > 0)
(*start)--;
else if(*offset > 0)
(*offset)--;
}
break;
case DEL: /*<by michael>*/
printf("\n\nDELETE! with securpos as : %d\n", seCurPos);
if (seCurPos < l){
for(i = seCurPos; i<l; i++){
se[i] = se[i+1];
}
}
break;
case ESC:
*start = startTemp;
*offset = offsetTemp; /* resetting our pointers back to our temp variables */
strcpy(se, seTemp);
done++;
break;
default:
if(key == ENTER || key == TAB || key == UP || key == DOWN || key == PGUP || (key >= F1 && key <= F10 )){
done++;
}else if(key >= 32 && key <= 126) {
seTemp2 = (char*) malloc (sizeof(char) * (l + 1));
offsetTemp2 = *offset;
startTemp2 = *start;
if(*insert){ /*<MB>if insert mode on */
for(i=l; i >= seCurPos; i--){ /*<MB> copies each character in se, from the null byte to the cursor postion up a block in the memory*/
se[i+1] = se[i];
}
se[seCurPos] = key; /*<mb>sets the char at the cursor position of se to be equal to the inserted character*/
if(*start < flen)
(*start)++;
else
(*offset)++;
}else{ /*<MB>if insert mode off */
se[seCurPos] = key;
if(*start < flen)
(*start)++;
else
(*offset)++;
}
validated = validateType(se, slen, ctype); /*<MB> IF NOT VALIDATED, MUST UNDO CHANGES */
if(!validated){
strcpy(se, seTemp2);
*offset = offsetTemp2;
*start = startTemp2;
}
free (seTemp2);
seTemp2 = NULL;
} /*<mb>end of default cases main if statement*/
} /*<mb>end of switch*/
} /*<mb>end of whileloop*/
free (seTemp);
seTemp = NULL;
return key;
} /*<MB>End of if(validated)*/
/* Nearing end of function */
/* release allocated memory then assign them NULL values! */
//free(startTemp);
// free(offseetTemp);
//startTemp = NULL;
//offsetTemp = NULL;
/* if(key <=176 && key >= 32 && strlen(se)<slen){ /* Min Woks work*/ /*
if(*insert){ /*<MB> ABOVE CONDITION IS NO GOOD, if in overtype mode,
slen doesnt matter until you are at the last char of the string*//*
}else
{
}
}else{
}
break;
}
*/
} /* END of consoleEdit function */
int validateType(char *str,int maxstrlen, int type){
int i, retval;
int err = 0;
int len = strlen(str);
if (len > maxstrlen)
err++;
else{
switch(type){
case 1: /*<MB> I Am Assuming Printable characters only */
for (i=0; i<len; i++){
if (str[i] < 32 || str[i] > 126)
err++;
}
break;
case 2: /*<MB>Binary chars only ---But what about white-spaces? */
for (i=0; i<len; i++){
if (str[i] != '0' && str[i] != '1')
err++;
}
break;
case 4: /*<MB>Numeric chars only*/
for (i=0; i<len; i++){
if (str[i] < '0' || str[i] > '9')
err++;
}
break;
case 8: /*octal chars only */
for (i=0; i<len; i++){
if (str[i] < '0' || str[i] > '7')
err++;
}
break;
case 16: /*Hexadecimal chars only*/
for (i=0; i<len; i++){
if (!isxdigit(str[i]))
err++;
}
break;
default:
err++;
}
}
/*<MB> Does the IPC 144 Rule of only one return statement still apply? */
if(err)
retval = 0;
else
retval = 1;
return retval;
}
|
Java
|
UTF-8
| 2,133
| 2.25
| 2
|
[
"Apache-2.0"
] |
permissive
|
package org.openecomp.sdc.be.model;
import org.junit.Test;
import java.util.List;
public class ProductTest {
private Product createTestSubject() {
return new Product();
}
@Test
public void testCtor() throws Exception {
new Product(new ProductMetadataDefinition());
}
@Test
public void testGetFullName() throws Exception {
Product testSubject;
String result;
// default test
testSubject = createTestSubject();
result = testSubject.getFullName();
}
@Test
public void testSetFullName() throws Exception {
Product testSubject;
String fullName = "";
// default test
testSubject = createTestSubject();
testSubject.setFullName(fullName);
}
@Test
public void testGetInvariantUUID() throws Exception {
Product testSubject;
String result;
// default test
testSubject = createTestSubject();
result = testSubject.getInvariantUUID();
}
@Test
public void testSetInvariantUUID() throws Exception {
Product testSubject;
String invariantUUID = "";
// default test
testSubject = createTestSubject();
testSubject.setInvariantUUID(invariantUUID);
}
@Test
public void testGetContacts() throws Exception {
Product testSubject;
List<String> result;
// default test
testSubject = createTestSubject();
result = testSubject.getContacts();
}
@Test
public void testSetContacts() throws Exception {
Product testSubject;
List<String> contacts = null;
// default test
testSubject = createTestSubject();
testSubject.setContacts(contacts);
}
@Test
public void testAddContact() throws Exception {
Product testSubject;
String contact = "";
// default test
testSubject = createTestSubject();
testSubject.addContact(contact);
}
@Test
public void testGetIsActive() throws Exception {
Product testSubject;
Boolean result;
// default test
testSubject = createTestSubject();
result = testSubject.getIsActive();
}
@Test
public void testSetIsActive() throws Exception {
Product testSubject;
Boolean isActive = null;
// default test
testSubject = createTestSubject();
testSubject.setIsActive(isActive);
}
}
|
Markdown
|
UTF-8
| 2,088
| 2.546875
| 3
|
[
"MIT"
] |
permissive
|
---
title: Plague - Feb 07
catalog: true
tags:
- reading
permalink: /r_plague_2_7.html
folder: plague
summary:
---
1. Short, square-shouldered, with a determined-looking face and keen, intelligent eyes, he gave the impression of someone who could <b data-toggle="tooltip" data-original-title="{{site.data.answers.plag_d_4_a1}}">`________([在困境中]坚持、不泄气)`</b> in any circumstances. He <b data-toggle="tooltip" data-original-title="{{site.data.answers.plag_d_4_a2}}">`________(穿着运动服之类的衣服)`</b>.
2. “<b data-toggle="tooltip" data-original-title="{{site.data.answers.plag_d_4_b1}}">`________(我厌恶某人/某事物)`</b> for statements in which something is <b data-toggle="tooltip" data-original-title="{{site.data.answers.plag_d_4_b2}}">`________(隐瞒)`</b>,” he added. “That is why I shall not furnish information in support of yours.”
3. The journalist smiled. “<b data-toggle="tooltip" data-original-title="{{site.data.answers.plag_d_4_c1}}">`________(这是Saint-Just说过的话)`</b>.”
4. The language he used was that of a man who was sick and tired of the world he lived in—though he had much liking for his fellow men—and had resolved, for his part, to <b data-toggle="tooltip" data-original-title="{{site.data.answers.plag_d_4_d1}}">`________(拒绝与...有交往/打交道/有瓜葛)`</b> injustice and compromises with the truth.
5. Rieux asked him how he felt. The concierge wouldn’t go so far as to say he was feeling ill. Still <b data-toggle="tooltip" data-original-title="{{site.data.answers.plag_d_4_e1}}">`________(他觉得不太舒服)`</b>.
6. “Very odd,” Rieux agreed, “and it ends by <b data-toggle="tooltip" data-original-title="{{site.data.answers.plag_d_4_f1}}">`________(让人觉得很烦扰)`</b>.”
7. “No,” Rieux said quietly, they weren’t so bad as that. He had put the question solely to find out if Rambert could or couldn’t state the facts without <b data-toggle="tooltip" data-original-title="{{site.data.answers.plag_d_4_g1}}">`________(混淆事实)`</b>.
|
C++
|
UTF-8
| 9,286
| 2.765625
| 3
|
[] |
no_license
|
#ifndef ETTPNEIGHBORHOOD_H
#define ETTPNEIGHBORHOOD_H
#include <neighborhood/moNeighborhood.h>
#include <neighborhood/moNeighbor.h>
#include "neighbourhood/ETTPneighbor.h"
#include <utils/eoRNG.h>
#define ETTPNEIGHBORHOOD_DEBUG
template <typename EOT>
class ETTPneighborhood : public moNeighborhood<ETTPneighbor<EOT> > {
public:
ETTPneighborhood(boost::shared_ptr<ETTPKempeChainHeuristic<EOT> > const &_kempeChainHeuristic)
: kempeChainHeuristic(_kempeChainHeuristic), feasibleNeigh(true) { }
/**
* @return true if the neighborhood is random (default false)
*/
virtual bool isRandom() {
return true;
}
/**
* Test if a solution has (again) a Neighbor
* @param _solution the related solution
* @return true if _solution has a Neighbor
*/
virtual bool hasNeighbor(typename moNeighborhood<ETTPneighbor<EOT> >::EOT & _solution) {
// In the beginning, this variable is true in order to call randomNeighbor method
return feasibleNeigh;
//#ifdef ETTPNEIGHBORHOOD_DEBUG
// cout << "[hasNeighbor] method" << endl;
//#endif
// if (!neighbourGenerated) {
// // Initialise neighbour
// currentNeighbour.setKempeChainHeuristic(this->kempeChainHeuristic);
// // If there isn't a neighbour generated, generate one
// randomNeighbor(_solution, currentNeighbour);
// }
// return feasibleNeigh;
}
/**
* Initialization of the neighborhood
* @param _solution the solution to explore
* @param _current the first neighbor
*/
virtual void init(typename moNeighborhood<ETTPneighbor<EOT> >::EOT & _solution, ETTPneighbor<EOT> &_current) {
// Initialise neighbour
_current.setKempeChainHeuristic(this->kempeChainHeuristic);
// Generate a random neighbour
randomNeighbor(_solution, _current);
// Set current neighbour
// _current = currentNeighbour;
// Set neighbourGenerated to false to indicate that the current neighbour was evaluated
// and a new one needs to be generated in the next time
// neighbourGenerated = false;
}
/**
* Give the next neighbor
* @param _solution the solution to explore
* @param _current the next neighbor
*/
virtual void next(typename moNeighborhood<ETTPneighbor<EOT> >::EOT & _solution, ETTPneighbor<EOT> &_current) {
//randomNeighbor(_solution, _current);
throw runtime_error("method next - not implemented in ITC2007");
}
/**
* Test if there is again a neighbor
* @param _solution the solution to explore
* @return true if there is again a neighbor not explored
*/
virtual bool cont(typename moNeighborhood<ETTPneighbor<EOT> >::EOT & _solution) {
throw runtime_error("method cont - not implemented in ITC2007");
return true;
}
/**
* Return the class Name
* @return the class name as a std::string
*/
virtual std::string className() const {
return "ETTPNeighborhood";
}
protected:
/**
* @brief randomNeighbor
* @param _solution
* @param _neighbor
*/
void randomNeighbor(typename moNeighborhood<ETTPneighbor<EOT> >::EOT & _solution, ETTPneighbor<EOT> &_neighbor) {
//
// ITC2007 random neighbour generation
//
// Using the Kempe chain heuristic for ITC2007, we don't always get a feasible neighbour
// If the Period-utilisation and After constraints are not verified,
// set solution to be infeasible and return.
_neighbor.build(_solution);
// Determine info if neighbour is feasible
// feasibleNeigh = _neighbor.isFeasible();
// // Set neighbour generated flag to true/false depending if a feasible neighbour was build or not
// neighbourGenerated = feasibleNeigh;
}
/**
* @brief feasibleNeigh Indicates if generated neighbour is feasible or not.
* Because we are using a Kempe chain heuristic, the produced neighbour is
* always feasible
*/
bool feasibleNeigh;
/**
* @brief kempeChainHeuristic Kempe Chain neighbourhood
*/
boost::shared_ptr<ETTPKempeChainHeuristic<EOT> > const &kempeChainHeuristic;
/**
* @brief neighbourGenerated
*/
bool neighbourGenerated;
/**
* @brief currentNeighbour Current neighbour after the exploration of the neighbourhood
*/
ETTPneighbor<EOT> currentNeighbour;
};
#endif // ETTPNEIGHBORHOOD_H
////////////////////////////////////////// TORONTO CODE //////////////////////////////
//template <typename EOT>
//class ETTPneighborhood : public moNeighborhood<ETTPneighbor<EOT> > {
//public:
// ETTPneighborhood(boost::shared_ptr<ETTPKempeChainHeuristic<EOT> > const &_kempeChainHeuristic)
// : kempeChainHeuristic(_kempeChainHeuristic), feasibleNeigh(true) { }
// /**
// * @return true if the neighborhood is random (default false)
// */
// virtual bool isRandom() {
// return true;
// }
// /**
// * Test if a solution has (again) a Neighbor
// * @param _solution the related solution
// * @return true if _solution has a Neighbor
// */
// virtual bool hasNeighbor(typename moNeighborhood<ETTPneighbor<EOT> >::EOT & _solution) {
// // In the beginning, this variable is true in order to call randomNeighbor method
//// return feasibleNeigh;
// if (!neighbourGenerated) {
// // If there isn't a neighbour generated, generate one
// randomNeighbor(_solution, currentNeighbour);
// }
// }
// /**
// * Initialization of the neighborhood
// * @param _solution the solution to explore
// * @param _current the first neighbor
// */
// virtual void init(typename moNeighborhood<ETTPneighbor<EOT> >::EOT & _solution, ETTPneighbor<EOT> &_current) {
//#ifdef ETTPNEIGHBORHOOD_DEBUG
// std::cout << "In [ETTPneighborhood::init()] method:" << std::endl;
//#endif
// // Initialise neighbour
// _current.setKempeChainHeuristic(this->kempeChainHeuristic);
// // Generate a random neighbour
// randomNeighbor(_solution, _current);
//#ifdef ETTPNEIGHBORHOOD_DEBUG
//// std::cout << "In [ETTPneighborhood::init()] method:" << std::endl;
//// std::cout << "Validate solution" << std::endl;
//// _solution.validate();
//#endif
// }
// /**
// * Give the next neighbor
// * @param _solution the solution to explore
// * @param _current the next neighbor
// */
// virtual void next(typename moNeighborhood<ETTPneighbor<EOT> >::EOT & _solution, ETTPneighbor<EOT> &_current) {
// randomNeighbor(_solution, _current);
///// SEE
/////
/////
// }
// /**
// * Test if there is again a neighbor
// * @param _solution the solution to explore
// * @return true if there is again a neighbor not explored
// */
// virtual bool cont(typename moNeighborhood<ETTPneighbor<EOT> >::EOT & _solution) {
// return true;
// }
// /**
// * Return the class Name
// * @return the class name as a std::string
// */
// virtual std::string className() const {
// return "ETTPNeighborhood";
// }
//protected:
// /**
// * @brief randomNeighbor
// * @param _solution
// * @param _neighbor
// */
// void randomNeighbor(typename moNeighborhood<ETTPneighbor<EOT> >::EOT & _solution, ETTPneighbor<EOT> &_neighbor) {
//// // Generate a random neighbour
//// _neighbor.build(_solution);
//// // Using the Kempe chain heuristic, we always get a feasible neighbour
//// feasibleNeigh = true;
// //
// // ITC2007 random neighbour generation
// //
// // Using the Kempe chain heuristic for ITC2007, we don't always get a feasible neighbour
// // If the Period-utilisation and After constraints are not verified,
// // set solution to be infeasible and return.
// _neighbor.build(_solution);
// // Determine info if neighbour is feasible
// feasibleNeigh = _neighbor.isFeasible();
// // Set neighbour generated flag to true/false depending if a feasible neighbour was build or not
// neighbourGenerated = feasibleNeigh;
// }
// /**
// * @brief feasibleNeigh Indicates if generated neighbour is feasible or not.
// * Because we are using a Kempe chain heuristic, the produced neighbour is
// * always feasible
// */
// bool feasibleNeigh;
// /**
// * @brief kempeChainHeuristic Kempe Chain neighbourhood
// */
// boost::shared_ptr<ETTPKempeChainHeuristic<EOT> > const &kempeChainHeuristic;
// /**
// * @brief neighbourGenerated
// */
// bool neighbourGenerated;
// /**
// * @brief currentNeighbour Current neighbour after the exploration of the neighbourhood
// */
// ETTPneighbor<EOT> currentNeighbour;
//};
|
Java
|
UTF-8
| 457
| 1.960938
| 2
|
[] |
no_license
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package Package2;
//import Package1.*;
/**
*
* @author zia
*/
public class NonSubClass {
public void method(){
Package1.ParentClass obj = new Package1.ParentClass();
System.out.println(obj.l);
}
}
|
Java
|
UTF-8
| 2,467
| 2.5625
| 3
|
[] |
no_license
|
package com.everis.academia.java.agenda.digital.entity;
import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.SequenceGenerator;
import javax.persistence.Table;
@Entity
@Table(name = "TB_TELEFONE", schema = "public")
@SequenceGenerator(name = "SQ_TELEFONE", sequenceName = "SQ_TELEFONE", schema = "public", initialValue = 1, allocationSize = 1)
public class Telefone implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(generator = "SQ_TELEFONE", strategy = GenerationType.SEQUENCE)
@Column(name = "COD_TELEFONE")
private Integer codigo;
@Column(name = "NUM_TELEFONE", unique = true)
private Integer numero;
@ManyToOne(fetch = FetchType.EAGER, targetEntity = PrestadorServico.class)
@JoinColumn(name = "COD_PRESTADOR_SERVICO", nullable = false)
private PrestadorServico prestadorServico;
public Telefone() {
super();
}
public Telefone(Integer codigo) {
super();
this.codigo = codigo;
}
public Telefone(Integer codigo, Integer numero) {
this(codigo);
this.numero = numero;
}
public Integer getCodigo() {
return codigo;
}
public void setCodigo(Integer codigo) {
this.codigo = codigo;
}
public Integer getNumero() {
return numero;
}
public void setNumero(Integer numero) {
this.numero = numero;
}
public PrestadorServico getPrestadorServico() {
return prestadorServico;
}
public void setPrestadorServico(PrestadorServico prestadorServico) {
this.prestadorServico = prestadorServico;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((numero == null) ? 0 : numero.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Telefone other = (Telefone) obj;
if (numero == null) {
if (other.numero != null)
return false;
} else if (!numero.equals(other.numero))
return false;
return true;
}
@Override
public String toString() {
return "Telefone [codigo=" + codigo + ", numero=" + numero + ", prestadorServico=" + prestadorServico + "]";
}
}
|
Python
|
UTF-8
| 1,651
| 2.9375
| 3
|
[] |
no_license
|
import pandas as pd
import numpy as np
import sys
spam_data = pd.read_csv('/resources/data/datalaguTriariyani.csv')
spam_data['label'] = np.where(spam_data['label']=='positif',1,0)
print(spam_data.shape)
spam_data.head(20)
import matplotlib.pyplot as plt
import seaborn as sns
spam_data["label"].value_counts().plot(kind = 'pie', explode = [0, 0.1], figsize = (6, 6), autopct = '%1.1f%%', shadow = True)
plt.ylabel("Positif vs Negatif")
plt.legend(["positif", "negatif"])
plt.show()
from sklearn.model_selection import train_test_split
#Split data into train and test sets
X_train, X_test, y_train, y_test = train_test_split(spam_data['text'],spam_data['label'],random_state=0)
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.naive_bayes import MultinomialNB
from sklearn.metrics import roc_auc_score
#Train and evaluate the model
vect = CountVectorizer().fit(X_train)
X_train_vectorized = vect.transform(X_train)
clfrNB = MultinomialNB(alpha = 0.1)
clfrNB.fit(X_train_vectorized, y_train)
preds = clfrNB.predict(vect.transform(X_test))
score = roc_auc_score(y_test, preds)
print(score)
from sklearn.metrics import confusion_matrix
print(confusion_matrix(y_test, preds))
from sklearn.metrics import confusion_matrix
import numpy as np
target = np.array([1,0,1,0])
prediksi = np.array([1, 1, 1, 0])
tn, fp, fn, tp = confusion_matrix(target, prediksi).ravel()
tn = float(tn)
fp = float(fp)
fn = float(fn)
tp = float(tp)
print (tn, fp, fn, tp)
akurasi = ((tp+tn)/(tp+tn+fp+fn))*100
presisi = (tp/(fp+tp))*100
recall = (tp/(fn+tp))*100
print (akurasi,presisi, recall)
|
Python
|
UTF-8
| 645
| 2.921875
| 3
|
[] |
no_license
|
#Librerias Python
import traceback
from datetime import date
from datetime import timedelta
from pathlib import Path
#Librerias Propias
from .datos_bono import datos_bono
from .descargar_casos import descargar_casos
def consolidar_descargar_casos(dias_anteriores,repeticiones,caso = 'todos'):
print('='*80)
lst_bono = ['Bono 600','Bono BFU','Bono RURAL','Bono URBANO']
try:
for tipo_bono in lst_bono:
descargar_casos(tipo_bono,dias_anteriores,repeticiones,caso)
except Exception as e:
print(f"Existe un error: {traceback.format_exc()}, tipo de casos:{caso}")
print('='*80)
|
JavaScript
|
UTF-8
| 1,098
| 2.765625
| 3
|
[] |
no_license
|
export class Route {
constructor () {
this.wayPoints = [];
this.loc = navigator.geolocation || null;
this.geoOptions = {
timeout: 10000 // ms
};
}
addWaypoint () {
var self = this;
if (self.loc) {
return new Promise(function (resolve, reject) {
self.loc.getCurrentPosition(
position => {
self.wayPoints.push({
tstamp: position.timestamp,
lat: position.coords.latitude,
lng: position.coords.longitude,
seq: self.wayPoints.length
});
resolve(self.wayPoints[self.wayPoints.length - 1]);
},
error => {
reject('Add Waypoint Failed. Reason: ' + error);
},
self.geoOptions);
});
}
else {
return Promise.reject('Geolocation Failed');
}
}
}
|
Java
|
UTF-8
| 3,473
| 2.203125
| 2
|
[
"LicenseRef-scancode-unknown-license-reference",
"Apache-2.0",
"LicenseRef-scancode-freemarker",
"MIT",
"LGPL-2.1-only",
"LicenseRef-scancode-other-permissive",
"LGPL-2.0-or-later",
"EPL-1.0",
"BSD-3-Clause",
"GPL-1.0-or-later"
] |
permissive
|
/*
* Copyright 2010 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.migrationanalyzer.render.support.html;
import static org.junit.Assert.assertEquals;
import java.io.InputStream;
import java.io.Reader;
import org.junit.Test;
import org.springframework.migrationanalyzer.analyze.fs.FileSystemEntry;
public class StandardOutputPathGeneratorTests {
private final RootAwareOutputPathGenerator pathGenerator = new StandardOutputPathGenerator();
@Test
public void generateForResultType() {
String path = this.pathGenerator.generatePathFor(Object.class);
assertEquals("result-type/java.lang.Object.html", path);
}
@Test
public void generateForFileSystemEntry() {
String path = this.pathGenerator.generatePathFor(new StubFileSystemEntry("a/b/c/test.xml"));
assertEquals("file-entry/a/b/c/test.xml.html", path);
}
@Test
public void generateForFileSystemEntryContents() {
String path = this.pathGenerator.generatePathForFileSystemEntryContents();
assertEquals("file-entry/contents.html", path);
}
@Test
public void generateForResultTypeContents() {
String path = this.pathGenerator.generatePathForResultTypeContents();
assertEquals("result-type/contents.html", path);
}
@Test
public void generateForIndex() {
String path = this.pathGenerator.generatePathForIndex();
assertEquals("index.html", path);
}
@Test
public void generateForSummary() {
String path = this.pathGenerator.generatePathForSummary();
assertEquals("summary.html", path);
}
@Test
public void generateForFileName() {
String path = this.pathGenerator.generatePathFor("foo/bar.txt");
assertEquals("foo/bar.txt", path);
}
@Test
public void generateRelativePathToRootForClass() {
String path = this.pathGenerator.generateRelativePathToRootFor(getClass());
assertEquals("../", path);
}
@Test
public void generateRelativePathToRootForFileSystemEntry() {
String path = this.pathGenerator.generateRelativePathToRootFor(new StubFileSystemEntry("a/b/c/d.txt"));
// a/b/c/d.txt will generate a path of file-entry/a/b/c/d.txt
assertEquals("../../../../", path);
}
private final static class StubFileSystemEntry implements FileSystemEntry {
private final String name;
public StubFileSystemEntry(String name) {
super();
this.name = name;
}
@Override
public InputStream getInputStream() {
return null;
}
@Override
public String getName() {
return this.name;
}
@Override
public Reader getReader() {
return null;
}
@Override
public boolean isDirectory() {
return false;
}
}
}
|
C++
|
UTF-8
| 585
| 2.53125
| 3
|
[] |
no_license
|
#include <cstdio>
#include <iostream>
#include <vector>
using namespace std;
int main(){
int t,n,a,b,c,rsult=1;
cin >> t; int i=1;
while(i<=t){
cin >> n; vector<double>slopes; vector<int>count; int j=0;rsult=1;
while(j<n){
cin >> a >> b >> c;
double sl=b/a;
for(int yui=0;yui<slopes.size();yui++){
if(sl==slopes[yui]) {count[yui]++; goto con;}}
slopes.push_back(sl);count.push_back(1);
con:
int hj = slopes.size();
j++;
}
for(int yui=0;yui<count.size();yui++){
rsult*=count[yui];
}
cout << rsult << endl;
i++;
}
return 0;
}
|
JavaScript
|
UTF-8
| 336
| 2.828125
| 3
|
[] |
no_license
|
let funcionario = {
email: 'abc@abc.com'
};
let proxyFuncionario = new Proxy(funcionario,{
get(target, prop, receiver){
console.log("Armadilha aqui");
return '**' + Reflect.get(target, prop, receiver) +'**' ;
}
});
console.log(proxyFuncionario.email);
|
Java
|
UTF-8
| 1,513
| 2.546875
| 3
|
[] |
no_license
|
package br.com.corridaKart.util;
import java.io.BufferedReader;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;
import br.com.corridaKart.negocio.CalculaResultadoCorrida;
public class Util {
public static String obterCaminhoArquivoLog() {
return CalculaResultadoCorrida.class.getClassLoader().getResource("corrida_de_kart.log").getPath().substring(1);
}
public static Date converteStringData(String dataString, String formato) {
Date data = null;
try {
SimpleDateFormat format = new SimpleDateFormat(formato);
data = format.parse(dataString);
} catch (ParseException e) {
e.printStackTrace();
}
return data;
}
public static String converteDataString(Date data, String formato) {
SimpleDateFormat format = new SimpleDateFormat(formato);
return format.format(data);
}
public static String obterTrecho(String texto, int posicaoInicial, Integer posicaoFinal) {
String trecho = "";
if (posicaoFinal == null) {
trecho = texto.substring(posicaoInicial).trim();
} else {
trecho = texto.substring(posicaoInicial, posicaoFinal).trim();
}
return trecho;
}
public static List<String> obterArquivoDeLog() throws IOException {
BufferedReader arquivo = Files.newBufferedReader(Paths.get(obterCaminhoArquivoLog()));
return arquivo.lines().collect(Collectors.toList());
}
}
|
Java
|
UTF-8
| 6,571
| 1.703125
| 2
|
[] |
no_license
|
/**
*/
package uw.cs.watform.forml.forml.impl;
import org.eclipse.emf.common.notify.Notification;
import org.eclipse.emf.common.notify.NotificationChain;
import org.eclipse.emf.ecore.EClass;
import org.eclipse.emf.ecore.InternalEObject;
import org.eclipse.emf.ecore.impl.ENotificationImpl;
import uw.cs.watform.forml.forml.Composition;
import uw.cs.watform.forml.forml.Decl;
import uw.cs.watform.forml.forml.FormlPackage;
/**
* <!-- begin-user-doc -->
* An implementation of the model object '<em><b>Composition</b></em>'.
* <!-- end-user-doc -->
* <p>
* The following features are implemented:
* </p>
* <ul>
* <li>{@link uw.cs.watform.forml.forml.impl.CompositionImpl#getWhole <em>Whole</em>}</li>
* <li>{@link uw.cs.watform.forml.forml.impl.CompositionImpl#getPart <em>Part</em>}</li>
* </ul>
*
* @generated
*/
public class CompositionImpl extends RelationshipImpl implements Composition
{
/**
* The cached value of the '{@link #getWhole() <em>Whole</em>}' containment reference.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getWhole()
* @generated
* @ordered
*/
protected Decl whole;
/**
* The cached value of the '{@link #getPart() <em>Part</em>}' containment reference.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getPart()
* @generated
* @ordered
*/
protected Decl part;
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected CompositionImpl()
{
super();
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
protected EClass eStaticClass()
{
return FormlPackage.Literals.COMPOSITION;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public Decl getWhole()
{
return whole;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public NotificationChain basicSetWhole(Decl newWhole, NotificationChain msgs)
{
Decl oldWhole = whole;
whole = newWhole;
if (eNotificationRequired())
{
ENotificationImpl notification = new ENotificationImpl(this, Notification.SET, FormlPackage.COMPOSITION__WHOLE, oldWhole, newWhole);
if (msgs == null) msgs = notification; else msgs.add(notification);
}
return msgs;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public void setWhole(Decl newWhole)
{
if (newWhole != whole)
{
NotificationChain msgs = null;
if (whole != null)
msgs = ((InternalEObject)whole).eInverseRemove(this, EOPPOSITE_FEATURE_BASE - FormlPackage.COMPOSITION__WHOLE, null, msgs);
if (newWhole != null)
msgs = ((InternalEObject)newWhole).eInverseAdd(this, EOPPOSITE_FEATURE_BASE - FormlPackage.COMPOSITION__WHOLE, null, msgs);
msgs = basicSetWhole(newWhole, msgs);
if (msgs != null) msgs.dispatch();
}
else if (eNotificationRequired())
eNotify(new ENotificationImpl(this, Notification.SET, FormlPackage.COMPOSITION__WHOLE, newWhole, newWhole));
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public Decl getPart()
{
return part;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public NotificationChain basicSetPart(Decl newPart, NotificationChain msgs)
{
Decl oldPart = part;
part = newPart;
if (eNotificationRequired())
{
ENotificationImpl notification = new ENotificationImpl(this, Notification.SET, FormlPackage.COMPOSITION__PART, oldPart, newPart);
if (msgs == null) msgs = notification; else msgs.add(notification);
}
return msgs;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public void setPart(Decl newPart)
{
if (newPart != part)
{
NotificationChain msgs = null;
if (part != null)
msgs = ((InternalEObject)part).eInverseRemove(this, EOPPOSITE_FEATURE_BASE - FormlPackage.COMPOSITION__PART, null, msgs);
if (newPart != null)
msgs = ((InternalEObject)newPart).eInverseAdd(this, EOPPOSITE_FEATURE_BASE - FormlPackage.COMPOSITION__PART, null, msgs);
msgs = basicSetPart(newPart, msgs);
if (msgs != null) msgs.dispatch();
}
else if (eNotificationRequired())
eNotify(new ENotificationImpl(this, Notification.SET, FormlPackage.COMPOSITION__PART, newPart, newPart));
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public NotificationChain eInverseRemove(InternalEObject otherEnd, int featureID, NotificationChain msgs)
{
switch (featureID)
{
case FormlPackage.COMPOSITION__WHOLE:
return basicSetWhole(null, msgs);
case FormlPackage.COMPOSITION__PART:
return basicSetPart(null, msgs);
}
return super.eInverseRemove(otherEnd, featureID, msgs);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public Object eGet(int featureID, boolean resolve, boolean coreType)
{
switch (featureID)
{
case FormlPackage.COMPOSITION__WHOLE:
return getWhole();
case FormlPackage.COMPOSITION__PART:
return getPart();
}
return super.eGet(featureID, resolve, coreType);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public void eSet(int featureID, Object newValue)
{
switch (featureID)
{
case FormlPackage.COMPOSITION__WHOLE:
setWhole((Decl)newValue);
return;
case FormlPackage.COMPOSITION__PART:
setPart((Decl)newValue);
return;
}
super.eSet(featureID, newValue);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public void eUnset(int featureID)
{
switch (featureID)
{
case FormlPackage.COMPOSITION__WHOLE:
setWhole((Decl)null);
return;
case FormlPackage.COMPOSITION__PART:
setPart((Decl)null);
return;
}
super.eUnset(featureID);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public boolean eIsSet(int featureID)
{
switch (featureID)
{
case FormlPackage.COMPOSITION__WHOLE:
return whole != null;
case FormlPackage.COMPOSITION__PART:
return part != null;
}
return super.eIsSet(featureID);
}
} //CompositionImpl
|
Python
|
UTF-8
| 2,404
| 3.1875
| 3
|
[] |
no_license
|
import heapq as hq
from collections import namedtuple
from typing import TypeVar, Callable, Iterable, Tuple, Optional, Set, List
T = TypeVar('T')
Info = namedtuple("Info", "maxl nodes")
Queue = List[Tuple[float, T]]
def a_star(start: T, goal: T, h: Callable[[T], float], gen_children: Callable[[T, T], Iterable[T]],
callback: Optional[Callable[[Queue], None]] = None) -> Tuple[List[T], Set[T], Info]:
"""
A* algorithm, receives the start node, the goal node,
the heuristic function h(n), a callable generating node
successors and an optional callback.
@param start: the start node
@param goal: the goal node
@param h: the heuristic function
@param gen_children: the generation callable
@param callback: a callback
@return: the optimum path from start to goal
"""
depth = {start: 0}
parents = {}
queue = [(h(start), start)]
visited = set()
infinite = float("inf")
info = Info(maxl=0, nodes=0)
while queue:
if callback:
callback(queue)
# noinspection PyProtectedMember
info = info._replace(maxl=max(len(queue), info.maxl),
nodes=info.nodes + 1)
current = hq.heappop(queue)[1]
visited.add(current)
if goal(current):
node = current
path = []
while node in parents:
path.append(node)
node = parents[node]
path.append(start)
path.reverse()
return path, visited, info
parent = parents.get(current)
# print("\nVisiting", current, "from", parent)
for generated in gen_children(current, parent):
successor, weight = generated
successor_depth = depth[current] + weight
# print("Generated", generated, "Depth =", successor_depth)
if successor in visited:
continue
if successor_depth < depth.get(successor, infinite):
parents[successor] = current
depth[successor] = successor_depth
h_score = h(successor)
f_score = successor_depth + h_score
# print("h-score of", successor, "=", h_score)
# print("Added", successor, "to queue with score", f_score)
hq.heappush(queue, (f_score, successor))
return None, None, info
|
Java
|
UTF-8
| 339
| 2.46875
| 2
|
[] |
no_license
|
package edu.bu.cs591p1;
public class LoanInterestTransaction extends Transaction {
private final double _interestAmount;
public LoanInterestTransaction(long id, long account, double amount) {
super("LoanInterest", id, account);
_interestAmount = amount;
}
public double getInterestAmount() {
return _interestAmount;
}
}
|
Python
|
UTF-8
| 1,222
| 3.828125
| 4
|
[] |
no_license
|
import random
def create_group():
print("Enter the number of friends joining (including you):")
try:
count = int(input())
except ValueError:
print("No one is joining for the party")
else:
if count <= 0:
print("No one is joining for the party")
else:
dic = {}
print("Enter the name of every friend (including you), each on a new line:")
for _ in range(count):
dic[input()] = 0
return dic
def bill_split(dic):
print("Enter the total bill value: ")
bill = float(input())
print('Do you want to use the "Who is lucky?" feature? Write Yes/No: ')
if input().lower() == "yes":
lucky_one = random.choice(list(dic.keys()))
count = len(dic) - 1
print(lucky_one + " is the lucky one!")
else:
print("No one is going to be lucky")
count = len(dic)
s_bill = round(bill / count, 2)
for friend in dic:
if count == len(dic):
dic[friend] = s_bill
else:
if friend != lucky_one:
dic[friend] = s_bill
return dic
print(bill_split(create_group()))
|
C++
|
UTF-8
| 7,646
| 2.9375
| 3
|
[] |
no_license
|
#pragma once
#include <vector>
#include "IceIncludes.h"
#include "Ogre.h"
#include "LoadSave.h"
#include "boost/any.hpp"
#include "OgreAny.h"
#include "IceScriptParam.h"
namespace Ice
{
/**
A piece of any "basic" data. Supports int, bool, float, string, Vector3 and Quaternion
*/
class DllExport GenericProperty : public LoadSave::Saveable
{
private:
Ogre::Any mData;
public:
GenericProperty() {};
~GenericProperty() {};
enum PropertyTypes
{
INT = 0,
BOOL = 1,
FLOAT = 2,
STRING = 3,
VECTOR3 = 4,
QUATERNION = 5,
ENUM = 6
};
///Retrieves the data type.
PropertyTypes getType() const;
///Sets the value of type T.
template <typename T>
void Set(const T &value) { mData = value;};
///Sets the value using a void pointer and a type identifier.
void Set(void *data, const PropertyTypes &type);
///Converts from a ScriptParam.
void Set(const ScriptParam &scriptParam);
///Retrieves the saved data of type T.
template <typename T>
T Get() const { return Ogre::any_cast<T>(mData); }
///Writes the saved data to a target buffer.
PropertyTypes Get(void *target) const;
void GetAsScriptParam(ScriptParam &scriptParam);
//Load Save methods
void Save(LoadSave::SaveSystem& myManager);
void Load(LoadSave::LoadSystem& mgr);
static void Register(std::string* pstrName, LoadSave::SaveableInstanceFn* pFn) { *pstrName = "GenericProperty"; *pFn = (LoadSave::SaveableInstanceFn)&NewInstance; };
static LoadSave::Saveable* NewInstance() { return new GenericProperty; };
std::string& TellName() { static std::string name = "GenericProperty"; return name; }
};
/**
This class wraps a map<String, GenericProperty>
*/
class DllExport DataMap : public LoadSave::Saveable
{
public:
class DllExport Item : public LoadSave::Saveable
{
public:
Item();
Ogre::String Key;
std::shared_ptr<GenericProperty> Data;
//Load Save methods
void Save(LoadSave::SaveSystem& myManager);
void Load(LoadSave::LoadSystem& mgr);
static void Register(std::string* pstrName, LoadSave::SaveableInstanceFn* pFn) { *pstrName = "DataMapItem"; *pFn = (LoadSave::SaveableInstanceFn)&NewInstance; };
static LoadSave::Saveable* NewInstance() { return new Item; };
std::string& TellName() { static std::string name = "DataMapItem"; return name; };
};
private:
std::vector< std::shared_ptr<Item> > mItems; //this is a vector and not a map because order and random access via index matters
std::vector< std::shared_ptr<Item> >::iterator mIterator;
public:
DataMap();
DataMap(const DataMap &rhs);
~DataMap();
inline DataMap& operator=(const DataMap &rhs)
{
if (this != &rhs)
{
mItems = rhs.mItems;
mIterator = mItems.begin();
}
return *this;
}
//Iterator methods
void First();
bool HasNext();
Item GetNext();
//Inits the datamap from a types key-value string ("vector3 position = x y z; float weight = 8;")
void ParseString(Ogre::String &keyValues);
///Retrieves whether there is an item with key keyname.
bool HasKey(const Ogre::String &keyname);
///Retrieves the data of the item with the key keyname.
template <class templateType>
templateType GetValue(const Ogre::String &keyname) const
{
for (auto i = mItems.begin(); i != mItems.end(); i++)
if ((*i)->Key == keyname) return (*i)->Data->Get<templateType>();
IceAssert(false)
return templateType();
}
///Retrieves the data of the item with the key keyname, retungs defaultVal if it does not exist.
template <class templateType>
templateType GetValue(const Ogre::String &keyname, templateType defaultVal) const
{
for (auto i = mItems.begin(); i != mItems.end(); i++)
if ((*i)->Key == keyname) return (*i)->Data->Get<templateType>();
return defaultVal;
}
///Retrieves the data of the item at the given index.
template <class templateType>
templateType GetValue(unsigned int index) const
{
IceAssert(index < mItems.size())
return mItems[index]->Data->Get<templateType>();
}
//Typed get methods
int GetInt(const Ogre::String &keyname, int defaultVal = 0) const;
bool GetBool(const Ogre::String &keyname, bool defaultVal = false) const;
float GetFloat(const Ogre::String &keyname, float defaultVal = 0.0f) const;
Ogre::Vector3 GetOgreVec3(const Ogre::String &keyname, Ogre::Vector3 defaultVal = Ogre::Vector3(1, 1, 1)) const;
Ogre::ColourValue GetOgreCol(const Ogre::String &keyname, Ogre::ColourValue defaultVal = Ogre::ColourValue()) const;
Ogre::Quaternion GetOgreQuat(const Ogre::String &keyname, Ogre::Quaternion defaultVal = Ogre::Quaternion()) const;
Ogre::String GetOgreString(const Ogre::String &keyname, Ogre::String defaultVal = "") const;
class DllExport Enum
{
public:
Ogre::String toString() const;
void fromString(Ogre::String coded_enum);
std::vector<Ogre::String> choices;
unsigned int selection;
Enum() {}
Enum(const Ogre::String& str) { fromString(str); }
friend DllExport std::ostream& operator<<(std::ostream& o, const Enum &e)
{
o << e.toString();
return o;
}
};
DataMap::Enum GetEnum(const Ogre::String &keyname, DataMap::Enum defaultVal = DataMap::Enum()) const;
///Inserts a new item into the DataMap.
template <class templateType>
void AddItem(const Ogre::String &keyname, const templateType &var)
{
std::shared_ptr<Item> item = std::make_shared<Item>();
item->Key = keyname;
item->Data->Set<templateType>(var);
mItems.push_back(item);
mIterator = mItems.begin();
};
///Inserts a new item into the DataMap, the data is passed using a GenericProperty.
void AddItem(const Ogre::String &keyname, const GenericProperty &prop)
{
std::shared_ptr<Item> item = std::make_shared<Item>();
item->Key = keyname;
*(item->Data.get()) = prop;
mItems.push_back(item);
mIterator = mItems.begin();
}
///Inserts a new item into the DataMap, the data is passed using a void buffer.
void AddItem(const Ogre::String &keyname, void *data, const GenericProperty::PropertyTypes &type)
{
std::shared_ptr<Item> item = std::make_shared<Item>();
item->Key = keyname;
item->Data->Set(data, type);
mItems.push_back(item);
mIterator = mItems.begin();
};
//Typed set methods
void AddBool(const Ogre::String &keyname, const bool val);
void AddInt(const Ogre::String &keyname, const int val);
void AddFloat(const Ogre::String &keyname, const float val);
void AddOgreVec3(const Ogre::String &keyname, const Ogre::Vector3 &vec);
void AddOgreCol(const Ogre::String &keyname, const Ogre::ColourValue &val);
void AddOgreQuat(const Ogre::String &keyname, const Ogre::Quaternion &quat);
void AddOgreString(const Ogre::String &keyname, const Ogre::String &text);
void AddEnum(const Ogre::String &keyname, std::vector<Ogre::String> choices, unsigned int selection = 0);
void AddScriptParam(const Ogre::String &keyname, const ScriptParam ¶m);
//Load Save methods
void Save(LoadSave::SaveSystem& myManager);
void Load(LoadSave::LoadSystem& mgr);
static void Register(std::string* pstrName, LoadSave::SaveableInstanceFn* pFn) { *pstrName = "DataMap"; *pFn = (LoadSave::SaveableInstanceFn)&NewInstance; };
static LoadSave::Saveable* NewInstance() { return new DataMap; };
std::string& TellName() { static std::string name = "DataMap"; return name; };
};
};
|
C++
|
UTF-8
| 1,500
| 2.703125
| 3
|
[] |
no_license
|
//
// Gate Sequencer
// Sync-in -> Gate sequence
//
// 2021.04.27
//
#include <MsTimer2.h>
#define PIN_SYNC_IN (2)
#define PIN_GATE_OUT (12)
#define PIN_GATE_LED (11)
#define PIN_PULSE_WIDTH (A0)
#define CNT_N (8)
byte sequence[CNT_N] = {0};
int cnt = 0;
int pulseWidth = 20;
void gateOff()
{
digitalWrite(PIN_GATE_OUT, LOW);
digitalWrite(PIN_GATE_LED, LOW);
}
void step()
{
digitalWrite(PIN_GATE_OUT, sequence[cnt]);
digitalWrite(PIN_GATE_LED, sequence[cnt]);
cnt++;
if (cnt >= CNT_N) {
cnt = 0;
}
MsTimer2::set(pulseWidth, gateOff);
MsTimer2::start();
}
void setup() {
pinMode(PIN_SYNC_IN, INPUT);
pinMode(PIN_GATE_OUT, OUTPUT);
pinMode(PIN_GATE_LED, OUTPUT);
// DIP switch
pinMode(3, INPUT_PULLUP);
pinMode(4, INPUT_PULLUP);
pinMode(5, INPUT_PULLUP);
pinMode(6, INPUT_PULLUP);
pinMode(7, INPUT_PULLUP);
pinMode(8, INPUT_PULLUP);
pinMode(9, INPUT_PULLUP);
pinMode(10, INPUT_PULLUP);
attachInterrupt(digitalPinToInterrupt(PIN_SYNC_IN), step, RISING);
}
void loop() {
// Read DIP switch
sequence[0] = !digitalRead(10);
sequence[1] = !digitalRead(9);
sequence[2] = !digitalRead(8);
sequence[3] = !digitalRead(7);
sequence[4] = !digitalRead(6);
sequence[5] = !digitalRead(5);
sequence[6] = !digitalRead(4);
sequence[7] = !digitalRead(3);
// Read pulse width
pulseWidth = analogRead(PIN_PULSE_WIDTH) / 10; // 0~102 ms
}
|
Markdown
|
UTF-8
| 1,977
| 3.359375
| 3
|
[] |
no_license
|
# Data Structures
This is a temporary repository containing work done in Data Structures Lab, SY Sem 4 B.Tech Engineering.
## Singly Linked List - LL_Menu.cpp
A menu driven program to perform basic linked lists commands like: display list, create list, insert at start, middle, end, delete at start, middle, end, reverse list and concatinate lists.
## Doubly Linked List - DLL.cpp
A menu driven program to perform basic doubly linked lists commands like: display list, create list, insert at start, middle, end, delete at start, middle, end, reverse list and concatinate lists.
## Circular Linked List - CLL.cpp
A menu driven program to perform basic circular linked lists commands like: display list, create list, insert at start, middle, end, delete at start, middle, end, reverse list and concatinate lists.
## Trees - Tree.cpp
A menu driven program to create a binary tree and has features to perform recursive & iterative tree traversals: in-order, pre-order & post-order.
## Binary Search Tree - BSTree.cpp
A menu driven program to create a simple binary search tree and basic implementation features such as creating list/nodes, searhcing nodes, delete nodes, in-order traversal, etc.
## Depth First Search - DFS.cpp
A menu driven program to create a simple graph and implementation of depth first search alogrithm on it and to display the output.
## Prim's Alogrithm - Prims_Algo.cpp
A menu driven program to create a simple graph and implementation of Prim's alogrithm on it to to find the minimum cost path of a spanning tree and display the output.
## File Organistaion: Direct Access - Direct.c
A program to create a simple database from user and save it in a file, and then implement direct access method to fetch the contents of the file.
## File Organistaion: Sequential Access - Sequential.c
A program to create a simple database from user and save it in a file, and then implement sequential access method to fetch the contents of the file.
|
C#
|
UTF-8
| 6,334
| 2.796875
| 3
|
[] |
no_license
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Globalization;
namespace OMetaSharp
{
public class CodeGen
{
private StringBuilder m_Buffer = new StringBuilder();
private static readonly char PushIndentSignal = char.ConvertFromUtf32(2)[0];
private static readonly char PopIndentSignal = char.ConvertFromUtf32(3)[0];
private static readonly char PushVariableSignal = char.ConvertFromUtf32(5)[0];
private static readonly char PopVariableSignal = char.ConvertFromUtf32(6)[0];
private static readonly char UseVariableSignal = char.ConvertFromUtf32(1)[0];
public CodeGen()
{
}
public CodeGen Write(params object[] objectsToWrite)
{
if (objectsToWrite == null)
{
return this;
}
foreach (var o in objectsToWrite)
{
m_Buffer.Append(o.ToString());
}
return this;
}
public CodeGen WriteLine(params object[] objectsToWrite)
{
Write(objectsToWrite);
bool shouldWriteLinefeed = true;
if (objectsToWrite != null)
{
if (objectsToWrite.Length > 0)
{
object lastObject = objectsToWrite[objectsToWrite.Length - 1];
if(lastObject != null)
{
shouldWriteLinefeed = !lastObject.ToString().EndsWith(Environment.NewLine);
}
}
}
if (shouldWriteLinefeed)
{
m_Buffer.AppendLine();
}
return this;
}
public CodeGen WriteLineEnd(params object[] objectsToWrite)
{
Write(objectsToWrite);
Write(Environment.NewLine);
return this;
}
public CodeGen WriteLines(params object[] linesToWrite)
{
foreach (var currentLine in linesToWrite)
{
WriteLine(currentLine);
}
return this;
}
public CodeGen WriteLeveledVar(string prefix)
{
return Write(LeveledVar(prefix));
}
public static string LeveledVar(string prefix)
{
return prefix + UseVariableSignal;
}
public CodeGen PushIndent()
{
Write(PushIndentSignal);
return this;
}
public CodeGen PopIndent()
{
Write(PopIndentSignal);
return this;
}
public CodeGen PushVariableScope()
{
Write(PushVariableSignal);
return this;
}
public CodeGen PopVariableScope()
{
Write(PopVariableSignal);
return this;
}
public static CodeGen Create()
{
return new CodeGen();
}
public CodeGen Do(Action<CodeGen> actionToPerform)
{
actionToPerform(this);
return this;
}
public static CodeGen Format(OMetaList<HostExpression> format, params object[] args)
{
return Create().Write(FormatString(format.As<CodeGen>().ToString(), args));
}
private static string FormatString(string format, params object[] args)
{
// HACK: Need to fix bugs with using string.Format with special characters.
var currentVal = format;
for (int i = 0; i < args.Length; i++)
{
currentVal = currentVal.Replace("{" + i.ToString() + "}", args[i].ToString());
}
return currentVal;
}
public CodeGen WriteFormattedLine(string format, params object[] args)
{
return WriteLine(FormatString(format, args));
}
public override string ToString()
{
return m_Buffer.ToString();
}
public string ToGeneratedCodeString()
{
string indentSpaces = " ";
int variableScope = 1;
int indentLevel = 0;
// HACK: Won't use Environment.NewLine, since
// we really just care about the last char.
char endOfLine = '\n';
var sb = new StringBuilder();
bool atStartOfLine = true;
for(int ixBufferChar = 0; ixBufferChar < m_Buffer.Length; ixBufferChar++)
{
char c = m_Buffer[ixBufferChar];
if (c == PushIndentSignal)
{
indentLevel++;
}
else if (c == PopIndentSignal)
{
indentLevel--;
}
else if (c == PushVariableSignal)
{
variableScope++;
}
else if (c == PopVariableSignal)
{
variableScope--;
}
else if (c == UseVariableSignal)
{
if (variableScope > 1)
{
sb.Append(variableScope.ToString());
}
}
else if (c == endOfLine)
{
sb.Append(endOfLine);
atStartOfLine = true;
}
else
{
if (atStartOfLine)
{
for (int i = 0; i < indentLevel; i++)
{
sb.Append(indentSpaces);
}
atStartOfLine = false;
}
sb.Append(c);
}
}
return sb.ToString();
}
}
}
|
Python
|
UTF-8
| 471
| 3.5625
| 4
|
[] |
no_license
|
#! /usr/bin/python3
# Program Name: PPC---Challenge-10.py
# Author Name: Thomas Morrissey
# Date Written: 9/30/2014
a=int(input("How on average do you spend on your computer per day?"))
if a < 2:
print("That seems reasonable.")
else:
print("Get a life")
#Self-Review
#I have completed successfully this assignment.
#I had errors with incorrect indentation.
#I solved them by looking at my grok learning programs.
#I didn't find any thing difficult, just a bit confusing.
|
Ruby
|
UTF-8
| 82
| 2.78125
| 3
|
[] |
no_license
|
puts "Bonjour, monde !"
puts #"Et avec une voix sexy ca donne : Bonjour, monde !"
|
Java
|
UTF-8
| 746
| 1.96875
| 2
|
[] |
no_license
|
package com.rudy.dao;
import com.rudy.entity.RoleInfo;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.springframework.stereotype.Repository;
import java.util.List;
@Mapper
@Repository
public interface RoleInfoMapper {
int deleteByPrimaryKey(Integer id);
int insert(RoleInfo record);
int insertSelective(RoleInfo record);
RoleInfo selectByPrimaryKey(Integer id);
List<RoleInfo> selectAllRole();
int updateByPrimaryKeySelective(RoleInfo record);
RoleInfo selectRoleByName(String roleName);
int deleteByIds(@Param("ids") List<String> ids);
int upateRoleDelFlagById(Integer roleId);
int updateRoleDelFlagByIds(@Param("ids") List<String> ids);
}
|
SQL
|
UTF-8
| 15,089
| 4.03125
| 4
|
[] |
no_license
|
-- Q1
select distinct first_name from tajik.public_users
order by length(first_name) desc;
select distinct first_name from tajik.public_users
order by length(first_name) asc;
select count(first_name),first_name from tajik.public_users group by first_name order by count(first_name) desc;
-- or together
-- select distinct first_name,
-- Q2
select distinct U.user_id from tajik.public_users U, tajik.public_friends F
where U.user_id not in F;
-- or
where U.user_id <> F.user_id;
select distinct U.user_id from tajik.public_users U, tajik.public_friends F where U.user_id <> F.user1_id and U.user_id <> F.user2_id;
-- or not exists
select distinct U1.user_id from tajik.public_users U1
where not exists (select U2.user_id from tajik.public_users U2, tajik.public_friends F
where U2.user_id = F.user1_id or U2.user_id = F.user2_id);
-- or not in
select distinct U1.user_id from tajik.public_users U1
where U1.user_id not in (select U2.user_id from tajik.public_users U2, tajik.public_friends F
where U2.user_id = F.user1_id or U2.user_id = F.user2_id);
select distinct U1.user_id from tajik.public_users U1 where U1.user_id not in (select U2.user_id from tajik.public_users U2, tajik.public_friends F where U2.user_id = F.user1_id or U2.user_id = F.user2_id)
-- Q3
create view cur_addr as select * from tajik.public_user_current_city;
create view home_addr as select * from tajik.public_user_hometown_city;
select distinct C.user_id from cur_addr C,home_addr H where H.hometown_city_id <> C.current_city_id and H.user_id=C.user_id;
select distinct C.user_id,U.first_name,U.last_name from tajik.public_user_current_city C, tajik.public_user_hometown_city H, tajik.public_users U where H.hometown_city_id <> C.current_city_id and H.user_id=C.user_id and U.user_id=C.user_id
-- Q4
-- I don't know why this cannot run , after I used view , all things are correct
select distinct count(T.tag_subject_id), T.tag_photo_id from tajik.public_tags T group by T.tag_photo_id order by count(T.tag_subject_id) desc;
-- or
select distinct count(tag_subject_id),tag_photo_id from tags group by tag_photo_id;
create view tags as select * from tajik.public_tags;
select distinct count(tag_subject_id),tag_photo_id from tags group by tag_photo_id order by count(tag_subject_id) desc;
create view top_tags as select distinct count(tag_subject_id) as count_tag_subject_id,tag_photo_id from tajik.public_tags group by tag_photo_id order by count(tag_subject_id) desc;
create view top_tags as select distinct count(tag_subject_id) as count_tag_subject_id,tag_photo_id from tajik.public_tags group by tag_photo_id order by count(tag_subject_id) desc
select distinct T.count_tag_subject_id,T.tag_photo_id,A.album_id,A.album_name,P.photo_caption,P.photo_link,U.user_id,U.first_name,U.last_name from top_tags T, tajik.public_tags TT, tajik.public_albums A, tajik.public_photos P,tajik.public_users U where A.album_id=P.album_id and TT.tag_photo_id=T.tag_photo_id and U.user_id=TT.tag_subject_id and P.photo_id=T.tag_photo_id order by T.count_tag_subject_id desc;
select distinct T.count_tag_subject_id,T.tag_photo_id,P.photo_caption,U.user_id
from top_tags T, tajik.public_tags TT, tajik.public_albums A, tajik.public_photos P,tajik.public_users U
where T.tag_photo_id=TT.tag_photo_id and TT.tag_subject_id=U.user_id and P.photo_id=T.tag_photo_id and A.album_id=P.album_id;
select distinct T.count_tag_subject_id,T.tag_photo_id,A.album_id,A.album_name,P.photo_caption,P.photo_link,U.user_id,U.first_name,U.last_name
from top_tags T, tajik.public_tags TT, tajik.public_albums A, tajik.public_photos P,tajik.public_users U
where A.album_id=P.album_id and TT.tag_photo_id=T.tag_photo_id and U.user_id=TT.tag_subject_id
and P.photo_id=T.tag_photo_id
order by T.count_tag_subject_id desc;
String photoId = "1234567";
String albumId = "123456789";
String albumName = "album1";
String photoCaption = "caption1";
String photoLink = "http://google.com";
PhotoInfo p = new PhotoInfo(photoId, albumId, albumName, photoCaption, photoLink);
TaggedPhotoInfo tp = new TaggedPhotoInfo(p);
tp.addTaggedUser(new UserInfo(12345L, "taggedUserFirstName1", "taggedUserLastName1"));
tp.addTaggedUser(new UserInfo(12345L, "taggedUserFirstName2", "taggedUserLastName2"));
this.photosWithMostTags.add(tp);
select distinct count(T.tag_subject_id),T.tag_photo_id,A.album_id,A.album_name,P.photo_caption,P.photo_link,U.user_id,U.first_name,U.last_name from tajik.public_tags T, tajik.public_albums A, tajik.public_photos P,tajik.public_users U where A.album_id=P.album_id and U.user_id=T.tag_subject_id and P.photo_id=T.tag_photo_id group by T.tag_photo_id order by count(tag_subject_id) desc;
select distinct count(T.tag_subject_id),T.tag_photo_id,A.album_id,A.album_name,P.photo_caption,P.photo_link,U.user_id,U.first_name,U.last_name from tajik.public_tags T, tajik.public_albums A, tajik.public_photos P,tajik.public_users U where A.album_id=P.album_id and U.user_id=T.tag_subject_id and P.photo_id=T.tag_photo_id group by T.tag_photo_id;
-- Q5
select distinct U1.user_id, U2.user_id from tajik.public_users U1
join tajik.public_users U2 on U1.gender='female' and U2.gender='male' and U1.year_of_birth-U2.year_of_birth<=yearDiff and U2.year_of_birth-U1.year_of_birth<=yearDiff
-- join tajik.public_friends F on (U1.user_id=F.user1_id and U2.user_id=F.user2_id) or (U1.user_id=F.user2_id and U2.user_id=F.user1_id)
join tajik.public_tags T1 on U1.user_id=T1.tag_subject_id
join tajik.public_tags T2 on U2.user_id=T2.tag_subject_id and T1.tag_photo_id=T2.tag_photo_id
-- by MINUS
select U1.user_id, U2.user_id from tajik.public_users U1
join tajik.public_users U2 on U1.gender='female' and U2.gender='male' and U1.year_of_birth-U2.year_of_birth<=10 and U2.year_of_birth-U1.year_of_birth<=10
join tajik.public_tags T1 on U1.user_id=T1.tag_subject_id
join tajik.public_tags T2 on U2.user_id=T2.tag_subject_id and T1.tag_photo_id=T2.tag_photo_id
group by U1.user_id,U2.user_id
order by count(*)
MINUS
select U1.user_id, U2.user_id from tajik.public_users U1
join tajik.public_users U2 on U1.gender='female' and U2.gender='male' and U1.year_of_birth-U2.year_of_birth<=10 and U2.year_of_birth-U1.year_of_birth<=10
join tajik.public_friends F on (U1.user_id=F.user1_id and U2.user_id=F.user2_id) or (U1.user_id=F.user2_id and U2.user_id=F.user1_id)
join tajik.public_tags T1 on U1.user_id=T1.tag_subject_id
join tajik.public_tags T2 on U2.user_id=T2.tag_subject_id and T1.tag_photo_id=T2.tag_photo_id
group by U1.user_id,U2.user_id
order by count(*);
select distinct U1.user_id, U2.user_id from tajik.public_users U1
join tajik.public_users U2 on U1.gender='female' and U2.gender='male' and U1.year_of_birth-U2.year_of_birth<=yearDiff and U2.year_of_birth-U1.year_of_birth<=yearDiff
join tajik.public_tags T1 on U1.user_id=T1.tag_subject_id
join tajik.public_tags T2 on U2.user_id=T2.tag_subject_id and T1.tag_photo_id=T2.tag_photo_id
group by U1.user_id,U2.user_id
MINUS
select distinct U1.user_id, U2.user_id from tajik.public_users U1
join tajik.public_users U2 on U1.gender='female' and U2.gender='male' and U1.year_of_birth-U2.year_of_birth<=yearDiff and U2.year_of_birth-U1.year_of_birth<=yearDiff
join tajik.public_friends F on (U1.user_id=F.user1_id and U2.user_id=F.user2_id) or (U1.user_id=F.user2_id and U2.user_id=F.user1_id)
join tajik.public_tags T1 on U1.user_id=T1.tag_subject_id
join tajik.public_tags T2 on U2.user_id=T2.tag_subject_id and T1.tag_photo_id=T2.tag_photo_id
group by U1.user_id,U2.user_id;
-- Q6
-- the newest
create or replace view view_Q6 as
select U1.user_id as user1_id, U2.user_id as user2_id ,count(*) as count_friends
from tajik.public_users U1,tajik.public_users U2,tajik.public_friends F1,tajik.public_friends F2
where U1.user_id<U2.user_id and ((F1.user2_id=U1.user_id and F2.user2_id=U2.user_id and F1.user1_id=F2.user1_id)
or (F1.user1_id=U1.user_id and F2.user2_id=U2.user_id and F1.user2_id=F2.user1_id)
or (U1.user_id=F1.user1_id and U2.user_id=F2.user1_id and F1.user2_id=F2.user2_id))
group by U1.user_id,U2.user_id order by count(*) desc;
"create or replace view view_Q6 as "+
"select U1.user_id as user1_id, U2.user_id as user2_id ,count(*) as count_friends "+
"from tajik.public_users U1,tajik.public_users U2,tajik.public_friends F1,tajik.public_friends F2 "+
"where U1.user_id<U2.user_id and ((F1.user2_id=U1.user_id and F2.user2_id=U2.user_id and F1.user1_id=F2.user1_id) "+
"or (F1.user1_id=U1.user_id and F2.user2_id=U2.user_id and F1.user2_id=F2.user1_id) "+
"or (U1.user_id=F1.user1_id and U2.user_id=F2.user1_id and F1.user2_id=F2.user2_id)) "+
"group by U1.user_id,U2.user_id order by count(*) desc;"
(select V.user1_id,U1.first_name,U2.last_name,V.user2_id,U2.first_name,U2.last_name,F1.user1_id as user3_id,U3.first_name,U3.last_name,V.count_friends
from view_Q6 V, tajik.public_users U1, tajik.public_users U2, tajik.public_friends F1,tajik.public_friends F2,tajik.public_users U3
where V.user1_id=U1.user_id and V.user2_id=U2.user_id and F1.user2_id=U1.user_id and F2.user2_id=U2.user_id and F1.user1_id=F2.user1_id and F1.user1_id=U3.user_id
UNION
select V.user1_id,U1.first_name,U2.last_name,V.user2_id,U2.first_name,U2.last_name,F1.user2_id as user3_id,U3.first_name,U3.last_name,V.count_friends
from view_Q6 V, tajik.public_users U1, tajik.public_users U2, tajik.public_friends F1,tajik.public_friends F2,tajik.public_users U3
where V.user1_id=U1.user_id and V.user2_id=U2.user_id and F1.user1_id=U1.user_id and F2.user2_id=U2.user_id and F1.user2_id=F2.user1_id and F1.user2_id=U3.user_id
UNION
select V.user1_id,U1.first_name,U2.last_name,V.user2_id,U2.first_name,U2.last_name,F1.user2_id as user3_id,U3.first_name,U3.last_name,V.count_friends
from view_Q6 V, tajik.public_users U1, tajik.public_users U2, tajik.public_friends F1,tajik.public_friends F2,tajik.public_users U3
where V.user1_id=U1.user_id and V.user2_id=U2.user_id and F1.user1_id=U1.user_id and F2.user1_id=U2.user_id and F1.user2_id=F2.user2_id and F1.user2_id=U3.user_id);
order by V.count_friends desc, V.user1_id asc, V.user2_id asc;
create or replace view view_Q6 as
select U1.user_id as user1_id, U2.user_id as user2_id, count(*) as count_pair from tajik.public_users U1
join tajik.public_users U2 on U1.user_id<>U2.user_id
join tajik.public_friends F1 on U1.user_id=F1.user1_id and U2.user_id<>F1.user2_id
join tajik.public_friends F2 on U2.user_id=F2.user1_id and U1.user_id<>F2.user2_id and F1.user2_id=F2.user2_id
group by U1.user_id,U2.user_id
order by count(*) desc,U1.user_id asc,U2.user_id asc;
"select V.user1_id,U1.first_name,U2.last_name,V.user2_id,U2.first_name,U2.last_name,F2.user2_id,U3.first_name,U3.last_name,V.count_pair from view_Q6 V "+
"join tajik.public_users U1 on V.user1_id=U1.user_id "+
"join tajik.public_users U2 on V.user2_id=U2.user_id "+
"join tajik.public_friends F1 on U1.user_id=F1.user1_id and U2.user_id<>F1.user2_id "+
"join tajik.public_friends F2 on U2.user_id=F2.user1_id and U1.user_id<>F2.user2_id and F1.user2_id=F2.user2_id "+
"join tajik.public_users U3 on F2.user2_id=U3.user_id "+
"order by V.count_pair desc,U1.user_id asc,U2.user_id asc "
"create view view_Q6 as select U1.user_id as user1_id, U2.user_id as user2_id, count(*)as count_pair,F1.user2_id as user3_id from tajik.public_users U1 join tajik.public_users U2 on U1.user_id<>U2.user_id join tajik.public_friends F1 on U1.user_id=F1.user1_id and U2.user_id<>F1.user2_id join tajik.public_friends F2 on U2.user_id=F2.user1_id and U1.user_id<>F2.user2_id and F1.user2_id=F2.user2_id group by U1.user_id,U2.user_id order by count(*) desc,U1.user_id asc,U2.user_id asc"
-- I don't konw the binary friends relationship
select V.user1_id,U1.first_name,U2.last_name,V.user2_id,U2.first_name,U2.last_name,V.user3_id,U3.first_name,U3.last_name,V.count_pair
from view_Q6 V, tajik.public_users U1, tajik.public_users U2
where V.user1_id=U1.user_id and V.user2_id=U2.user_id
order by V.count_pair desc,U1.user_id asc,U2.user_id asc;
select V.user1_id,U1.first_name,U2.last_name,V.user2_id,U2.first_name,U2.last_name,V.user3_id,U3.first_name,U3.last_name,V.count_pair from view_Q6 V, tajik.public_users U1, tajik.public_users U2 where V.user1_id=U1.user_id and V.user2_id=U2.user_id order by V.count_pair desc,U1.user_id asc,U2.user_id asc
-- Q7
select C.state_name,count(C.state_name) from tajik.public_cities C
join tajik.public_user_events E on C.city_id=E.event_city_id
group by C.state_name
order by count(C.state_name) desc;
select C.state_name,count(*) from tajik.public_cities C join tajik.public_user_events E on C.city_id=E.event_city_id group by C.state_name order by count(*) desc
-- Q8
create view friendsOfUser as
(select user2_id from tajik.public_friends F where F.user1_id='user_id'
UNION
select user1_id from tajik.public_friends F where F.user2_id='user_id');
create view friendsOfUser as (select user2_id from tajik.public_friends F where F.user1_id='user_id' UNION select user1_id from tajik.public_friends F where F.user2_id='user_id')
-- oldest
select F.user_id from friendsOfUser F, tajik.public_users U
where F.user_id=U.user_id
order by U.year_of_birth asc, U.month_of_birth asc, U.day_of_birth asc, F.user_id desc;
select F.user_id,U.first_name,U.last_name from friendsOfUser F, tajik.public_users U where F.user_id=U.user_id order by U.year_of_birth asc, U.month_of_birth asc, U.day_of_birth asc, F.user_id desc
-- youngest
select F.user_id from friendsOfUser F, tajik.public_users U
where F.user_id=U.user_id
order by U.year_of_birth desc, U.month_of_birth desc, U.day_of_birth desc, F.user_id asc;
select F.user_id,U.first_name,U.last_name from friendsOfUser F, tajik.public_users U where F.user_id=U.user_id order by U.year_of_birth desc, U.month_of_birth desc, U.day_of_birth desc, F.user_id asc;
drop view friendsOfUser;
-- Q9
select U1.user_id,U1.first_name,U1.last_name, U2.user_id,U2.first_name,U2.last_name from tajik.public_users U1
join tajik.public_users U2 on U1.user_id<U2.user_id and U1.year_of_birth-U2.year_of_birth<10 and U2.year_of_birth-U1.year_of_birth<10
join tajik.public_friends F on (U1.user_id=F.user1_id and U2.user_id=F.user2_id) or (U1.user_id=F.user2_id and U2.user_id=F.user1_id)
join tajik.public_user_hometown_city H1 on U1.user_id=H1.hometown_city_id
join tajik.public_user_hometown_city H2 on U2.user_id=H2.hometown_city_id and H1.hometown_city_id=H2.hometown_city_id
order by U1.user_id asc, U2.user_id asc;
select U1.user_id,U1.first_name,U1.last_name, U2.user_id,U2.first_name,U2.last_name from tajik.public_users U1
join tajik.public_users U2 on U1.user_id<U2.user_id and U1.year_of_birth-U2.year_of_birth<10 and U2.year_of_birth-U1.year_of_birth<10 and U1.last_name=U2.last_name
join tajik.public_friends F on U1.user_id=F.user1_id and U2.user_id=F.user2_id
join tajik.public_user_hometown_city H1 on U1.user_id=H1.user_id
join tajik.public_user_hometown_city H2 on U2.user_id=H2.user and H1.hometown_city_id=H2.hometown_city_id
order by U1.user_id asc, U2.user_id asc;
|
Shell
|
UTF-8
| 2,298
| 2.71875
| 3
|
[] |
no_license
|
###############################################################################
#
# You need to set CMVS_TOP and CMVS_DEP before doing anything
#
###############################################################################
###############################################################################
#
# 1. CMVS_TOP
#
# specify the top directory of the cmvs, where the settings64.sh locates
# i.e., if you have /home/cudauser/application4/cmvs_v0.0.02/settings64.sh
# export CMVS_TOP=/home/cudauser/application4/cmvs_v0.0.02
#
###############################################################################
export CMVS_TOP=
if `test -e $CMVS_TOP/settings64.sh` ; then
echo $CMVS_TOP;
else
echo Please set CMVS_TOP in settings64.sh ;
return;
fi
###############################################################################
#
# 2. CMVS_DEP
#
# The path to the dependenies of CMVS.
# This script assumes the dependencies are located in the same path.
# This script assumes the following packages are located in the path:
# 1) glew 1.5.2
# 2) libtool 2.2.6b
# 3) imagemagick 6.5.78
# 4) devil 1.7.8
# 5) jhead 2.88
# 6) clapack 3.2.1 (threadsafe)
# 7) gsl 1.15
#
# You may need to add or remove dependent packages according to your system
#
###############################################################################
# example: export CMVS_DEP=/home/cudauser/application4/cmvs_dep
export CMVS_DEP=
if `test -e $CMVS_DEP/settings64.sh` ; then
source $CMVS_DEP/settings64.sh ;
echo $CMVS_TOP;
else
echo Please set CMVS_DEP in settings64.sh ;
return;
fi
# core path
export CMVS_CORE=$CMVS_TOP/core
# graclus
export PATH=$PATH:$CMVS_CORE/graclus/graclus1.2
export C_INCLUDE_PATH=$C_INCLUDE_PATH:$CMVS_CORE/graclus/graclus1.2/metisLib
export CPLUS_INCLUDE_PATH=$CPLUS_INCLUDE_PATH:$CMVS_CORE/graclus/graclus1.2/metisLib
export LIBRARY_PATH=$LIBRARY_PATH:$CMVS_CORE/graclus/graclus1.2
export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:$CMVS_CORE/graclus/graclus1.2
# siftgpu
export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:$CMVS_CORE/siftgpu/SiftGPU/bin
# bundler
export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:$CMVS_CORE/bundler/bundler-v0.4-source/lib
export BUNDLER_BIN_PATH=$CMVS_CORE/bundler/bundler-v0.4-source/bin
# cmvs-pmvs
export PATH=$PATH:$CMVS_CORE/cmvs-pmvs/pmvs-2/program/main
|
Markdown
|
UTF-8
| 5,260
| 2.703125
| 3
|
[
"CC-BY-4.0",
"MIT"
] |
permissive
|
---
title: 加密和解密在 Visual Basic 中的字符串
ms.date: 07/20/2015
helpviewer_keywords:
- encryption [Visual Basic], strings
- strings [Visual Basic], encrypting
- decryption [Visual Basic], strings
- strings [Visual Basic], decrypting
ms.assetid: 1f51e40a-2f88-43e2-a83e-28a0b5c0d6fd
ms.openlocfilehash: 96e56ab315a739fef9d5499b076a077f5294f39e
ms.sourcegitcommit: 3d5d33f384eeba41b2dff79d096f47ccc8d8f03d
ms.translationtype: MT
ms.contentlocale: zh-CN
ms.lasthandoff: 05/04/2018
ms.locfileid: "33651218"
---
# <a name="walkthrough-encrypting-and-decrypting-strings-in-visual-basic"></a>演练:在 Visual Basic 中对字符串进行加密和解密
本演练演示如何使用<xref:System.Security.Cryptography.DESCryptoServiceProvider>类进行加密和解密使用三重数据加密标准的加密服务提供程序 (CSP) 版本字符串 (<xref:System.Security.Cryptography.TripleDES>) 算法。 第一步是创建一个简单的包装类,封装 3DES 算法,并将加密的数据存储为 base 64 编码的字符串。 然后,该包装用于安全地将私人用户数据存储在可公开访问的文本文件。
你可以使用加密保护用户的机密信息 (例如,密码) 和以使未经授权的用户的凭据不可读。 这样可防止授权的用户的标识从此被盗用、 用于保护用户的资源,并提供不可否认性。 加密还可以保护不被未经授权的用户的访问的用户的数据。
有关更多信息,请参阅[加密服务](../../../../standard/security/cryptographic-services.md)。
> [!IMPORTANT]
> Rijndael (现在称为高级加密标准 [AES]) 和三重数据加密标准 (3DES) 算法提供比 DES 更为安全,因为它们是多个计算密集型操作。 有关详细信息,请参阅 <xref:System.Security.Cryptography.DES> 和 <xref:System.Security.Cryptography.Rijndael>。
### <a name="to-create-the-encryption-wrapper"></a>若要创建加密包装器
1. 创建`Simple3Des`类来封装的加密和解密的方法。
[!code-vb[VbVbalrStrings#38](../../../../visual-basic/language-reference/functions/codesnippet/VisualBasic/walkthrough-encrypting-and-decrypting-strings_1.vb)]
2. 将加密命名空间的导入语句添加到包含文件的开头`Simple3Des`类。
[!code-vb[VbVbalrStrings#77](../../../../visual-basic/language-reference/functions/codesnippet/VisualBasic/walkthrough-encrypting-and-decrypting-strings_2.vb)]
3. 在`Simple3Des`类中,添加一个私有字段以存储 3DES 加密服务提供程序。
[!code-vb[VbVbalrStrings#39](../../../../visual-basic/language-reference/functions/codesnippet/VisualBasic/walkthrough-encrypting-and-decrypting-strings_3.vb)]
4. 添加一个私有方法创建从指定的键的哈希指定长度的字节数组。
[!code-vb[VbVbalrStrings#41](../../../../visual-basic/language-reference/functions/codesnippet/VisualBasic/walkthrough-encrypting-and-decrypting-strings_4.vb)]
5. 添加一个构造函数来初始化 3DES 加密服务提供程序。
`key`参数控件`EncryptData`和`DecryptData`方法。
[!code-vb[VbVbalrStrings#40](../../../../visual-basic/language-reference/functions/codesnippet/VisualBasic/walkthrough-encrypting-and-decrypting-strings_5.vb)]
6. 添加一个公共方法,对字符串进行加密。
[!code-vb[VbVbalrStrings#42](../../../../visual-basic/language-reference/functions/codesnippet/VisualBasic/walkthrough-encrypting-and-decrypting-strings_6.vb)]
7. 添加对字符串进行解密的公共方法。
[!code-vb[VbVbalrStrings#43](../../../../visual-basic/language-reference/functions/codesnippet/VisualBasic/walkthrough-encrypting-and-decrypting-strings_7.vb)]
包装类现在可以用于保护用户资产。 在此示例中,它用于安全地将私人用户数据存储在可公开访问的文本文件。
### <a name="to-test-the-encryption-wrapper"></a>若要测试加密包装器
1. 在单独的类中,添加一个方法来使用包装器的`EncryptData`方法加密字符串并将其写入到用户的我的文档文件夹。
[!code-vb[VbVbalrStrings#78](../../../../visual-basic/language-reference/functions/codesnippet/VisualBasic/walkthrough-encrypting-and-decrypting-strings_8.vb)]
2. 添加从用户读取加密的字符串的方法的我的文档文件夹,并解密使用包装器的字符串`DecryptData`方法。
[!code-vb[VbVbalrStrings#79](../../../../visual-basic/language-reference/functions/codesnippet/VisualBasic/walkthrough-encrypting-and-decrypting-strings_9.vb)]
3. 添加用户界面代码来调用`TestEncoding`和`TestDecoding`方法。
4. 运行该应用程序。
当你测试应用程序时,请注意它将解密数据,是否你提供了错误的密码。
## <a name="see-also"></a>请参阅
<xref:System.Security.Cryptography>
<xref:System.Security.Cryptography.DESCryptoServiceProvider>
<xref:System.Security.Cryptography.DES>
<xref:System.Security.Cryptography.TripleDES>
<xref:System.Security.Cryptography.Rijndael>
[加密服务](../../../../standard/security/cryptographic-services.md)
|
Java
|
UTF-8
| 3,213
| 2.140625
| 2
|
[] |
no_license
|
package com.ururu2909.firstapp;
import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;
import android.Manifest;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity implements ActivityCompat.OnRequestPermissionsResultCallback {
public static final int PERMISSION_REQUEST_CODE = 10;
@RequiresApi(api = Build.VERSION_CODES.M)
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
createNotificationChannel();
setContentView(R.layout.activity_main);
if (ContextCompat.checkSelfPermission(this, android.Manifest.permission.READ_CONTACTS) == PackageManager.PERMISSION_GRANTED) {
if (savedInstanceState == null){
addFragment();
}
} else {
requestPermissions(new String[]{Manifest.permission.READ_CONTACTS}, PERMISSION_REQUEST_CODE);
}
}
void addFragment(){
String id = getIntent().getStringExtra("contactId");
if (id != null){
ContactDetailsFragment detailsFragment = ContactDetailsFragment.newInstance(id);
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.replace(R.id.container, detailsFragment);
ft.commit();
} else {
FragmentManager fm = getSupportFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
ContactsFragment fragment = new ContactsFragment();
ft.add(R.id.container, fragment);
ft.commit();
}
}
private void createNotificationChannel() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
CharSequence name = getString(R.string.channel_name);
String description = getString(R.string.channel_description);
int importance = NotificationManager.IMPORTANCE_DEFAULT;
NotificationChannel channel = new NotificationChannel("CHANNEL", name, importance);
channel.setDescription(description);
NotificationManager notificationManager = getSystemService(NotificationManager.class);
notificationManager.createNotificationChannel(channel);
}
}
@RequiresApi(api = Build.VERSION_CODES.M)
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
switch (requestCode) {
case PERMISSION_REQUEST_CODE:
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
addFragment();
} else {
Toast.makeText(this, R.string.need_permission_msg, Toast.LENGTH_LONG).show();
}
}
}
}
|
Python
|
UTF-8
| 3,415
| 2.78125
| 3
|
[
"Apache-2.0"
] |
permissive
|
#!/usr/bin/python3
import os
import sys
# Checking for puremagic
try:
import puremagic as pr
except:
print("Error: >puremagic< module not found.")
sys.exit(1)
# Checking for colorama
try:
from colorama import Fore, Style
except:
print("Error: >colorama< not found.")
sys.exit(1)
# Checking for prettytable
try:
from prettytable import PrettyTable
except:
print("Error: >prettytable< module not found.")
sys.exit(1)
# Checking for oletools
try:
from oletools.olevba import VBA_Parser
except:
print("Error: >oletools< module not found.")
print("Try 'sudo -H pip3 install -U oletools' command.")
sys.exit(1)
# Colors
red = Fore.LIGHTRED_EX
cyan = Fore.LIGHTCYAN_EX
white = Style.RESET_ALL
green = Fore.LIGHTGREEN_EX
yellow = Fore.LIGHTYELLOW_EX
magenta = Fore.LIGHTMAGENTA_EX
# Legends
infoS = f"{cyan}[{red}*{cyan}]{white}"
errorS = f"{cyan}[{red}!{cyan}]{white}"
# Target file
targetFile = str(sys.argv[1])
# A function that finds VBA Macros
def MacroHunter(targetFile):
answerTable = PrettyTable()
answerTable.field_names = [f"{green}Threat Levels{white}", f"{green}Macros{white}", f"{green}Descriptions{white}"]
print(f"\n{infoS} Looking for VBA Macros...")
fileData = open(targetFile, "rb").read()
vbaparser = VBA_Parser(targetFile, data=fileData)
if vbaparser.contains_macros == True:
macroList = list(vbaparser.analyze_macros())
for fi in range(0, len(macroList)):
if macroList[fi][0] == 'Suspicious':
answerTable.add_row([f"{yellow}{macroList[fi][0]}{white}", f"{macroList[fi][1]}", f"{macroList[fi][2]}"])
elif macroList[fi][0] == 'IOC':
answerTable.add_row([f"{magenta}{macroList[fi][0]}{white}", f"{macroList[fi][1]}", f"{macroList[fi][2]}"])
elif macroList[fi][0] == 'AutoExec':
answerTable.add_row([f"{red}{macroList[fi][0]}{white}", f"{macroList[fi][1]}", f"{macroList[fi][2]}"])
else:
answerTable.add_row([f"{macroList[fi][0]}", f"{macroList[fi][1]}", f"{macroList[fi][2]}"])
print(f"{answerTable}\n")
else:
print(f"{errorS} Not any macros found.")
# A function that handles file types, extensions etc.
def MagicParser(targetFile):
# Defining table
resTable = PrettyTable()
# Magic byte parsing
resCounter = 0
resTable.field_names = [f"Extracted File Extensions", "Names", "Byte Matches", "Confidence"]
resourceList = list(pr.magic_file(targetFile))
for res in range(0, len(resourceList)):
extrExt = str(resourceList[res].extension)
extrNam = str(resourceList[res].name)
extrByt = str(resourceList[res].byte_match)
if resourceList[res].confidence >= 0.8:
resCounter += 1
if extrExt == '':
resTable.add_row([f"{red}No Extension{white}", f"{red}{extrNam}{white}", f"{red}{extrByt}{white}", f"{red}{resourceList[res].confidence}{white}"])
else:
resTable.add_row([f"{red}{extrExt}{white}", f"{red}{extrNam}{white}", f"{red}{extrByt}{white}", f"{red}{resourceList[res].confidence}{white}"])
if len(resourceList) != 0:
print(resTable)
# Execution area
if __name__ == '__main__':
MagicParser(targetFile)
try:
MacroHunter(targetFile)
except:
print(f"{errorS} File format not supported for macro scanning.")
|
Java
|
UTF-8
| 2,551
| 3.671875
| 4
|
[] |
no_license
|
import java.util.ArrayList;
public class LineParser {
/*
* Class for parsing words from line and updating sentenceCount in
* Concordance class
*/
public ArrayList<String> parseLine(String line, Concordance concordance) {
// Go through the input line and update the sentenceCount in concordance
for (int i = 0; i < line.length(); i++) {
char c = line.charAt(i);
// check if c is a sentence ending punctuation.
// special check for period to avoid counting periods in words
// like (i.e., e.g.)
if (";?!".indexOf(c) != -1) {
concordance.sentenceCount++;
}
// no periods two spaces left from c
else if (i > 2 && c == '.' && line.charAt(i - 2) != '.') {
if ((i + 2) < line.length()) {
// we are not dealing with words like i.e, e.g
if (line.charAt(i + 2) != '.') {
concordance.sentenceCount++;
}
} else {
concordance.sentenceCount++;
}
}
}
// Go through the input line and split it into words
ArrayList<String> wordList = new ArrayList<String>();
String buffer = "";
for (int i = 0; i < line.length(); i++) {
char c = line.charAt(i);
// check if we encounter the end of a word
if ((" ,;?!:\"\\]\\[\\(\\)".indexOf(c) != -1)
|| (i > 2 && c == '.' && line.charAt(i - 2) != '.'
&& (i + 2) < line.length() && line.charAt(i + 2) != '.')) {
// check if the buffer is indeed a word
String checkedBufferWord = checkBufferWord(buffer);
if (checkedBufferWord != null) {
wordList.add(checkedBufferWord);
}
buffer = "";
} else {
buffer = buffer + c;
}
}
// check the last buffer
String checkedBufferWord = checkBufferWord(buffer);
if (checkedBufferWord != null) {
wordList.add(checkedBufferWord);
}
return wordList;
}
private String checkBufferWord(String word) {
word = word.trim().toLowerCase(); // remove unwanted spaces and convert
// to lowercase
// Ignore empty strings, and strings that are not words
if (word.length() == 0 || !isWord(word))
return null;
return word;
}
// Returns true if the parameter word is composed of just letters and
// possibly apostrophe and period
private boolean isWord(String word) {
// ignore single apostrophe
if (word.equals("'"))
return false;
// check each char and determine whether the word is composed of
// letters, apostrophe or period
boolean isWord = true;
for (char s : word.toCharArray()) {
isWord = isWord
&& ((s >= 'a' && s <= 'z') || (s == '\'') || (s == '.'));
}
return isWord;
}
}
|
Python
|
UTF-8
| 2,231
| 2.78125
| 3
|
[
"MIT"
] |
permissive
|
import sys
import os
import helpers
import json
import csv
class FramerateManager():
def __init__(self,data,new_rate):
data = json.load(open(data))
self.framerates_json = json.load(open(data["framerates_json"]))
self.new_rate = new_rate
self.temp = data["temp"] + "temp.txt"
self.destination_file = data["preprocessed_datasets"] + "{}.csv"
self.original_file = data["extracted_datasets"] + "{}.csv"
def change_rate(self,scene_name):
former_rate = float(self.framerates_json[scene_name])
rate_ratio = int(former_rate/self.new_rate)
# self.destination_file = self.destination_file.format(scene_name)
helpers.remove_file(self.destination_file.format(scene_name))
self.counter = 0
helpers.extract_frames(self.original_file.format(scene_name),self.temp,save=True)
with open(self.temp) as frames:
for frame in frames:
frame = json.loads(frame)
i = frame["frame"]
if i % rate_ratio == 0:
self.__write_frame(frame["ids"],scene_name)
self.counter += 1
helpers.remove_file(self.temp)
def __write_frame(self,frame,scene):
with open(self.destination_file.format(scene),"a") as file_:
file_writer = csv.writer(file_)
for key in frame:
new_line = []
new_line.append(frame[key]["dataset"])
new_line.append(frame[key]["scene"])
new_line.append(self.counter)
new_line.append(key)
for e in frame[key]["coordinates"]:
new_line.append(e)
for e in frame[key]["bbox"]:
new_line.append(e)
new_line.append(frame[key]["type"].split("\n")[0])
file_writer.writerow(new_line)
#python prepare_training/framerate_manager.py parameters/data.json 2.5 lankershim_inter2
def main():
args = sys.argv
framerate_manager = FramerateManager(args[1],float(args[2]))
framerate_manager.change_rate(args[3])
if __name__ == "__main__":
main()
|
C++
|
UTF-8
| 654
| 2.640625
| 3
|
[] |
no_license
|
#include "obstacle.h"
// Constructor
Obstacle::Obstacle(Position* pos, QPixmap* sprite, bool test) : WorldObject(pos, sprite), test(test){}
// Type
std::string Obstacle::type(){return "obstacle";}
// Probe for testing
void Obstacle::probeObstacle(){
int height = RES_Y-pos->getY();
if(!probed && pos->getX() <= 200){
if(height > 340){
qDebug() << "Test non-colliding obstacle: PASSED";
} else{
qDebug() << "Test colliding obstacle: PASSED";
}
probed = true;
}
}
// Update position
void Obstacle::updatePosition(int xChange){
pos->moveX(xChange);
if(test) probeObstacle();
}
|
C++
|
UTF-8
| 3,422
| 2.625
| 3
|
[] |
no_license
|
/////////////////////////////////////////////////////////////////////////////
// Copyright (c) Electronic Arts Inc. All rights reserved.
/////////////////////////////////////////////////////////////////////////////
#ifndef EASTL_ALLOCATOR_H
#define EASTL_ALLOCATOR_H
#include <EASTL/internal/config.h>
#include <EASTL/EABase/nullptr.h>
#include <stddef.h>
#ifdef _MSC_VER
#pragma warning(push)
#pragma warning(disable: 4189) // local variable is initialized but not referenced
#endif
#if defined(EA_PRAGMA_ONCE_SUPPORTED)
#pragma once // Some compilers (e.g. VC++) benefit significantly from using this. We've measured 3-4% build speed improvements in apps as a result.
#endif
namespace eastl
{
/// dummy_allocator
///
/// Defines an allocator which does nothing. It returns NULL from allocate calls.
///
class EASTL_API dummy_allocator
{
public:
EASTL_ALLOCATOR_EXPLICIT dummy_allocator(const char* = NULL)
{}
dummy_allocator(const dummy_allocator&)
{}
dummy_allocator(const dummy_allocator&, const char*)
{}
dummy_allocator& operator=(const dummy_allocator&)
{
return *this;
}
void* allocate(size_t, int = 0)
{
return NULL;
}
void* allocate(size_t, size_t, size_t, int = 0)
{
return NULL;
}
void deallocate(void*, size_t)
{}
const char* get_name() const
{
return "";
}
void set_name(const char*)
{}
};
inline bool operator==(const dummy_allocator&, const dummy_allocator&)
{
return true;
}
inline bool operator!=(const dummy_allocator&, const dummy_allocator&)
{
return false;
}
/// allocate_memory
///
/// This is a memory allocation dispatching function.
/// To do: Make aligned and unaligned specializations.
/// Note that to do this we will need to use a class with a static
/// function instead of a standalone function like below.
///
template <typename Allocator>
void* allocate_memory(Allocator& a, size_t n, size_t alignment, size_t alignmentOffset);
} // namespace eastl
namespace eastl
{
static dummy_allocator default_dummy_allocator {};
/// allocate_memory
///
/// This is a memory allocation dispatching function.
/// To do: Make aligned and unaligned specializations.
/// Note that to do this we will need to use a class with a static
/// function instead of a standalone function like below.
///
template <typename Allocator>
inline void* allocate_memory(Allocator& a, size_t n, size_t alignment, size_t alignmentOffset)
{
void* result;
if(alignment <= EASTL_ALLOCATOR_MIN_ALIGNMENT)
{
result = EASTLAlloc(a, n);
// Ensure the result is correctly aligned. An assertion likely indicates a mismatch between EASTL_ALLOCATOR_MIN_ALIGNMENT and the minimum alignment
// of EASTLAlloc. If there is a mismatch it may be necessary to define EASTL_ALLOCATOR_MIN_ALIGNMENT to be the minimum alignment of EASTLAlloc, or
// to increase the alignment of EASTLAlloc to match EASTL_ALLOCATOR_MIN_ALIGNMENT.
EASTL_ASSERT((reinterpret_cast<size_t>(result) & ~(alignment - 1)) == reinterpret_cast<size_t>(result));
}
else
{
result = EASTLAllocAligned(a, n, alignment, alignmentOffset);
// Ensure the result is correctly aligned. An assertion here may indicate a bug in the allocator.
EASTL_ASSERT((reinterpret_cast<size_t>(result) & ~(alignment - 1)) == reinterpret_cast<size_t>(result));
}
return result;
}
}
#ifdef _MSC_VER
#pragma warning(pop)
#endif
#endif // Header include guard
|
Java
|
UTF-8
| 4,339
| 2.703125
| 3
|
[] |
no_license
|
import com.mysql.jdbc.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import javax.swing.JOptionPane;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;
public class CLIENTS {
NewConnection newConnection = new NewConnection();
//Funtion of adding clients
public boolean addClient(int id,String fname,String lname,String Contact,String email) throws SQLException{
PreparedStatement st;
ResultSet rs;
String addquery = "INSERT INTO `clients`(`id`, `first_name`, `last_name`, `contact_no`, `email`) VALUES (?,?,?,?,?)";
try{
st = (PreparedStatement) newConnection.getConnection().prepareStatement(addquery);
st.setInt(1, id);
st.setString(2, fname);
st.setString(3, lname);
st.setString(4, Contact);
st.setString(5, email);
return (st.executeUpdate() > 0);
}catch (SQLException e){
//Logger.getLogger(CLIENTS.class.getName()).Log(Level.SEVERE, null, ex);
JOptionPane.showMessageDialog(null,e);
return false;
}
}
//Funtion of editing clients
public boolean editClient(int id,String fname,String lname,String Contact,String email) throws SQLException{
PreparedStatement st;
ResultSet rs;
String addquery = "UPDATE `clients` SET `first_name`=?,`last_name`=?,`contact_no`=?,`email`=? WHERE `id`=?";
try{
st = (PreparedStatement) newConnection.getConnection().prepareStatement(addquery);
st.setString(1, fname);
st.setString(2, lname);
st.setString(3, Contact);
st.setString(4, email);
st.setInt(5, id);
return (st.executeUpdate() > 0);
}catch (SQLException e){
//Logger.getLogger(CLIENTS.class.getName()).Log(Level.SEVERE, null, ex);
JOptionPane.showMessageDialog(null,e);
return false;
}
}
//Funtion of deleting clients
public boolean removeClient(int id){
PreparedStatement st;
ResultSet rs;
String deletequery = "DELETE FROM `clients` WHERE `id`=?";
try{
st = (PreparedStatement) newConnection.getConnection().prepareStatement(deletequery);
st.setInt(1, id);
return (st.executeUpdate() > 0);
}catch (SQLException e){
//Logger.getLogger(CLIENTS.class.getName()).Log(Level.SEVERE, null, ex);
JOptionPane.showMessageDialog(null,e);
return false;
}
}
//Funtion of populating clients in jtable
public void fillclientsdataJTable(JTable table){
PreparedStatement ps;
ResultSet rs;
String selectQuery = "SELECT * FROM `clients`";
try{
ps = (PreparedStatement) newConnection.getConnection().prepareStatement(selectQuery);
rs = ps.executeQuery();
DefaultTableModel tableModel = (DefaultTableModel) table.getModel();
Object [] row;
while(rs.next())
{
row = new Object[5];
row [0] = rs.getInt(1);
row [1] = rs.getString(2);
row [2] = rs.getString(3);
row [3] = rs.getString(4);
row [4] = rs.getString(5);
tableModel.addRow(row);
}
}catch (SQLException e){
//Logger.getLogger(CLIENTS.class.getName()).Log(Level.SEVERE, null, ex);
JOptionPane.showMessageDialog(null,e);
// return false;
}
}
}
|
Java
|
UTF-8
| 773
| 1.71875
| 2
|
[] |
no_license
|
package org.camp.used.board.dto;
import java.time.LocalDateTime;
import java.util.List;
import org.camp.used.board.dto.BoardInsertDTO.BoardInsertDTOBuilder;
import org.camp.used.file.dto.FileResDTO;
import org.camp.used.member.dto.MemberGetOneDTO;
import org.camp.used.reply.dto.ReplyResDTO;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@Builder
@AllArgsConstructor
@NoArgsConstructor
public class BoardGetResDTO {
private Long bno;
private boolean bstate;
private String btitle, bcontent, bprice;
private LocalDateTime bregdate;
private LocalDateTime bmoddate;
private List<FileResDTO> fileResDTO;
private MemberGetOneDTO memberGetOneDTO;
private List<ReplyResDTO> ReplyResDTO;
}
|
Swift
|
UTF-8
| 2,302
| 3.4375
| 3
|
[
"BSD-3-Clause",
"LicenseRef-scancode-unknown-license-reference",
"BSD-2-Clause"
] |
permissive
|
import Foundation
public protocol NodeType {
/// Render the node in the given context
func render(_ context:Context) throws -> String
/// Reference to this node's token
var token: Token? { get }
}
/// Render the collection of nodes in the given context
public func renderNodes(_ nodes:[NodeType], _ context:Context) throws -> String {
return try nodes.map {
do {
return try $0.render(context)
} catch {
throw error.withToken($0.token)
}
}.joined(separator: "")
}
public class SimpleNode : NodeType {
public let handler:(Context) throws -> String
public let token: Token?
public init(token: Token, handler: @escaping (Context) throws -> String) {
self.token = token
self.handler = handler
}
public func render(_ context: Context) throws -> String {
return try handler(context)
}
}
public class TextNode : NodeType {
public let text:String
public let token: Token?
public init(text:String) {
self.text = text
self.token = nil
}
public func render(_ context:Context) throws -> String {
return self.text
}
}
public protocol Resolvable {
func resolve(_ context: Context) throws -> Any?
}
public class VariableNode : NodeType {
public let variable: Resolvable
public var token: Token?
public init(variable: Resolvable, token: Token? = nil) {
self.variable = variable
self.token = token
}
public init(variable: String, token: Token? = nil) {
self.variable = Variable(variable)
self.token = token
}
public func render(_ context: Context) throws -> String {
let result = try variable.resolve(context)
return stringify(result)
}
}
func stringify(_ result: Any?) -> String {
if let result = result as? String {
return result
} else if let array = result as? [Any?] {
return unwrap(array).description
} else if let result = result as? CustomStringConvertible {
return result.description
} else if let result = result as? NSObject {
return result.description
}
return ""
}
func unwrap(_ array: [Any?]) -> [Any] {
return array.map { (item: Any?) -> Any in
if let item = item {
if let items = item as? [Any?] {
return unwrap(items)
} else {
return item
}
}
else { return item as Any }
}
}
|
Java
|
UTF-8
| 3,635
| 2.546875
| 3
|
[] |
no_license
|
package com.ReadExcel;
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import library.ExcelDataConfig;
public class RWExcelData {
public static void main(String[] args) throws Exception {
// TODO Auto-generated method stub
//System.out.println(excel.getData(0,0,1));
//System.out.println(excel.getData(0,0,1));
System.setProperty("webdriver.gecko.driver", "C:\\Users\\SamJo\\Desktop\\java sw\\geckodriver-v0.14.0-win64\\geckodriver.exe");
FirefoxDriver Driver=new FirefoxDriver();
ExcelDataConfig excel = new ExcelDataConfig("C:\\Users\\SamJo\\Desktop\\java sw\\excel data\\TestData.xlsx");
//-----------------------------------------------------------
String surl=excel.getData(0,0,0);
String sUN=excel.getData(0,0,1);
String sPWD=excel.getData(0,0,2);
//------------------------------------------------------
//Open application
Driver.get(surl);
//wait for 2 sec
Thread.sleep(2000);
//Verify home page
if(Driver.getTitle().equals("OrangeHRM - New Level of HR Management"))
{
System.out.println("Home Page displayed");
}
else
{
System.out.println("Failed to open home page");
return;
}
//--------------------------------------------
//Create elements for user name,password,login and clear
WebElement objUN=Driver.findElement(By.name("txtUserName"));
WebElement objPWD=Driver.findElement(By.name("txtPassword"));
WebElement objLogin=Driver.findElement(By.name("Submit"));
WebElement objClear=Driver.findElement(By.name("clear"));
//-----------------------------------------------
//Verify user name
if(objUN.isDisplayed())
{
System.out.println("User name diplayed");
}
else
{
System.out.println("Failed to display");
return;
}
//Verify password
if(objPWD.isDisplayed())
{
System.out.println("Password diplayed");
}
else
{
System.out.println("Failed to display");
return;
}
//Verify Login and clear
if(objLogin.isDisplayed() && objClear.isDisplayed())
{
System.out.println("Login and clear diplayed");
}
else
{
System.out.println("Failed to display");
return;
}
//Login to orangeHRM
objUN.clear();
objUN.sendKeys(sUN);
objPWD.clear();
objPWD.sendKeys(sPWD);
objLogin.click();
//wait for 2 seconds
Thread.sleep(2000);
//Verify home page
if(Driver.getTitle().equals("OrangeHRM"))
{
System.out.println("OrangeHRM Page displayed");
}
else
{
System.out.println("Failed to login");
return;
}
//Create elements for Change password and Logout
WebElement objCP=Driver.findElement(By.linkText("Change Password"));
WebElement objLogout=Driver.findElement(By.linkText("Logout"));
//Verify Change Password & Logout
if(objCP.isDisplayed() && objLogout.isDisplayed())
{
System.out.println("Change Password & Logout are displayed");
}
else
{
System.out.println("Failed to display");
return;
}
//--------------------------------------------------------
//Click on logout
objLogout.click();
//wait for 2 sec
Thread.sleep(2000);
//Verify home page
if(Driver.getTitle().equals("OrangeHRM - New Level of HR Management"))
{
System.out.println("Signoff sucessfull & Home Page displayed");
}
else
{
System.out.println("Failed to Signoff");
return;
}
//-------------------------------------------------
Driver.close();
Driver.quit();
}
}
|
C++
|
UTF-8
| 56,599
| 2.765625
| 3
|
[] |
no_license
|
// mpi2.cpp : Этот файл содержит функцию "main". Здесь начинается и заканчивается выполнение программы.
//
#include "pch.h"
#include <iostream>
#include "mpi.h"
#include <stdio.h>
#pragma comment(lib, "msmpi.lib")
#include "vector"
#include "algorithm"
#include <ctime>
#include <ctime>
#include <cmath>
#include <cstdlib>
#include <iomanip>
#include <iostream>
#include <numeric>
//using namespace std;
#include <random>
#include <ctime>
#include <chrono>
#include "math.h"
#include <array>
using namespace std;
typedef double(*pointFunc)(double);
double f(double x) {
return (10 - x);
}
double simpson_integral(pointFunc f, double a, double b, int n) {
const double h = (b - a) / n;
double k1 = 0, k2 = 0;
for (int i = 1; i < n; i += 2) {
k1 += f(a + i * h);
k2 += f(a + (i + 1)*h);
}
return h / 3 * (f(a) + 4 * k1 + 2 * k2);
}
int main(int argc, char **argv)
{
using namespace std;
int rank = 0;
int size = 3;
MPI_Init(&argc, &argv);
MPI_Comm_size(MPI_COMM_WORLD, &size);
MPI_Comm_rank(MPI_COMM_WORLD, &rank);
// 1 & 2 tasks -n 4
//printf("Process %d size %d \n", rank, size); // 1 and 2
//std::cout << "Hello World! MPI";
// 3 task -n 2
//
//if (rank == 0) {
// srand(time(NULL));
// int number =10;
// vector<int> vec(number, 2);
// int ar[10] = { 1,2,3,4,5,6,7,8,9,10 };
// for_each(vec.begin(), vec.end(), [](int &x) {
// x = 1 + rand() % 12;
// });
// MPI_Send(static_cast<void*>(vec.data()), number, MPI_INT, 1, 5, MPI_COMM_WORLD);
//}
//else if (rank == 1) {
// MPI_Status status;
// vector<int> receiver(10,0);
// int number = 10;
// MPI_Recv(static_cast<void*>(receiver.data()), number, MPI_FLOAT, 0, 5, MPI_COMM_WORLD, &status);
// for (int i = 0; i < number; i++)
// {
// cout << receiver.at(i) << " received \n";
// }
//}
// 4 task -n 3 or any number
//int number_amount;
//if (rank == 0) {
// const int MAX_NUMBERS = 10;
// int numbers[MAX_NUMBERS] = {1,2,3,4,5,6,7,8,9};
// // Pick a random amount of integers to send to process one
// srand(time(NULL));
// number_amount = (rand() / (float)RAND_MAX) * MAX_NUMBERS;
// cout << "num of processes is " << size << "\n";
// // Send the random amount of integers to process one
// while (size-1 > 0) {
// MPI_Send(numbers, number_amount, MPI_INT, size-1, 0, MPI_COMM_WORLD);
// printf("0 sent %d numbers to %d\n", number_amount, size-1);
// size--;
// }
// //MPI_Send(numbers, number_amount, MPI_INT, 1, 0, MPI_COMM_WORLD);
//}
//else {
// MPI_Status status;
// // Probe for an incoming message from process zero
// MPI_Probe(0, 0, MPI_COMM_WORLD, &status);
// // When probe returns, the status object has the size and other
// // attributes of the incoming message. Get the message size
// MPI_Get_count(&status, MPI_INT, &number_amount);
// // Allocate a buffer to hold the incoming numbers
// int* number_buf = new int[sizeof(int) * number_amount];
// // Now receive the message with the allocated buffer
// MPI_Recv(number_buf, number_amount, MPI_INT, 0, 0,
// MPI_COMM_WORLD, MPI_STATUS_IGNORE);
// printf("%d dynamically received %d numbers from 0.\n",
// rank, number_amount);
// for (int i = 0; i < number_amount; i++)
// {
// cout << number_buf[i] << "\n";
// }
// delete[] number_buf;
//}
// 5 task -n 10 or 9
//vector<int> proccessesnames = { 2,3,4,6,8 };
//int number_amount;
//if (rank == 0) {
// const int max_numbers = 12;
// vector<int> numbers = {1,2,3,4,5,6,7,8,9,10,11,12};
// // pick a random amount of integers to send to process one
// srand(time(NULL));
// number_amount = (rand() / (float)RAND_MAX) * max_numbers;
// cout << "num of processes is " << size << "\n";
// // send the random amount of integers to process one
// for(int i = 0; i < proccessesnames.size(); i++){
// MPI_Send(numbers.data(), 12/proccessesnames.at(i)+1, MPI_INT, proccessesnames.at(i), 0, MPI_COMM_WORLD);
// printf("0 sent %d numbers to %d\n", 12/proccessesnames.at(i)+1, proccessesnames.at(i));
// size--;
// }
// //mpi_send(numbers, number_amount, mpi_int, 1, 0, mpi_comm_world);
//}
// else if(find(proccessesnames.begin(), proccessesnames.end(), rank) != proccessesnames.end()) {
// MPI_Status status;
// // probe for an incoming message from process zero
// MPI_Probe(0, 0, MPI_COMM_WORLD, &status);
// // when probe returns, the status object has the size and other
// // attributes of the incoming message. get the message size
// MPI_Get_count(&status, MPI_INT, &number_amount);
// // allocate a buffer to hold the incoming numbers
// int* number_buf = new int[sizeof(int) * number_amount];
// // now receive the message with the allocated buffer
// MPI_Recv(number_buf, number_amount, MPI_INT, 0, 0,
// MPI_COMM_WORLD, MPI_STATUS_IGNORE);
// printf("%d dynamically received %d numbers from 0.\n",
// rank, number_amount);
// for (int i = 0; i < number_amount; i++)
// {
// cout << number_buf[i] << "\n";
// }
// delete[] number_buf;
//}
//task 6 -n 4
//
//vector<int> proccessesNames = {1,2,3};
//int number_amount;
//if (rank == 0) {
// const int MAX_NUMBERS = 12;
// vector<int> numbers = { 1,2,3,4,5,6}; // xy pairs
// vector<int> zVector;
// //vector<vector<int>> threeVectors = { {1,1,1},{2,2,2},{0,0,0} };
//
// // Pick a random amount of integers to send to process one
// srand(time(NULL));
// number_amount = (rand() / (float)RAND_MAX) * MAX_NUMBERS;
//
// cout << "num of processes is " << size << "\n";
// // Send the random amount of integers to process one
// int vectorSize = numbers.size();
// for (int i = 0; i < proccessesNames.size(); i++) {
// MPI_Send(numbers.data(), vectorSize /proccessesNames.size(), MPI_INT, proccessesNames.at(i), 0, MPI_COMM_WORLD);
// printf("0 sent %d numbers to %d\n", vectorSize / proccessesNames.size(), proccessesNames.at(i));
// size--;
// numbers.erase(numbers.begin(), (numbers.begin() + 2));
// }
// while (zVector.size() != 3) {
// MPI_Status status;
// static int counter = 0;
// cout << "attemp " << counter << "\n";
// // Probe for an incoming message from process zero
// //MPI_Probe(0, 0, MPI_COMM_WORLD, &status);
//
// // When probe returns, the status object has the size and other
// // attributes of the incoming message. Get the message size
// //MPI_Get_count(&status, MPI_INT, &number_amount);
//
//
//
// for (int k = 1; k <= 3; k++) {
// // Allocate a buffer to hold the incoming numbers
// int* number_buf_z = new int[sizeof(int) * vectorSize / proccessesNames.size()];
// MPI_Recv(number_buf_z, vectorSize / proccessesNames.size()/2, MPI_INT, k, 0,
// MPI_COMM_WORLD, MPI_STATUS_IGNORE);
//
// for (int i = 0; i < vectorSize / proccessesNames.size()/2; i++)
// {
// cout << number_buf_z[i] << " in buf z" << endl;
//
// zVector.push_back(number_buf_z[i]);
//
// }
// //if (zVector.size() == vectorSize / 2) break;
// delete[] number_buf_z;
// }
// cout << "z vec size is " << zVector.size() << endl;
// }
// cout << "vector Z equals to: \n";
// for_each(zVector.begin(), zVector.end(), [](int x){
// cout << x << "\n"; });
//
// //MPI_Send(numbers, number_amount, MPI_INT, 1, 0, MPI_COMM_WORLD);
//}
//else if (find(proccessesNames.begin(), proccessesNames.end(), rank) != proccessesNames.end()) {
// MPI_Status status;
// // Probe for an incoming message from process zero
// MPI_Probe(0, 0, MPI_COMM_WORLD, &status);
//
// // When probe returns, the status object has the size and other
// // attributes of the incoming message. Get the message size
// MPI_Get_count(&status, MPI_INT, &number_amount);
//
// // Allocate a buffer to hold the incoming numbers
// int* number_buf = new int[sizeof(int) * number_amount];
//
// // Now receive the message with the allocated buffer
// MPI_Recv(number_buf, number_amount, MPI_INT, 0, 0,
// MPI_COMM_WORLD, MPI_STATUS_IGNORE);
// printf("%d dynamically received %d numbers from 0.\n",
// rank, number_amount);
// vector<int > resultZvector(number_amount/2);
// for (int i = 0; i < number_amount; i++)
// {
// cout << number_buf[i] << "\n";
//
// }
// for (int i = 0; i < number_amount/2; i++)
// {
// resultZvector.at(i) = number_buf[i] + number_buf[i + 1];
// cout << resultZvector.at(i) << " is Z coordinate." << "\n";
// }
// MPI_Send(resultZvector.data(), resultZvector.size(), MPI_INT, 0, 0, MPI_COMM_WORLD);
//
//
// delete[] number_buf;
//}
// task 7 -n 4
//const int a = 2;
//const int b = 2;
//vector<int> proccessesNames = { 1,2,3 };
//int number_amount;
//if (rank == 0) {
// const int MAX_NUMBERS = 12;
// vector<int> numbers = { 1,2,3,4,5,6 }; // xy pairs
// vector<int> zVector;
// //vector<vector<int>> threeVectors = { {1,1,1},{2,2,2},{0,0,0} };
//
// // Pick a random amount of integers to send to process one
// srand(time(NULL));
// number_amount = (rand() / (float)RAND_MAX) * MAX_NUMBERS;
//
// cout << "num of processes is " << size << "\n";
// // Send the random amount of integers to process one
// int vectorSize = numbers.size();
// for (int i = 0; i < proccessesNames.size(); i++) {
// MPI_Send(numbers.data(), vectorSize / proccessesNames.size(), MPI_INT, proccessesNames.at(i), 0, MPI_COMM_WORLD);
// printf("0 sent %d numbers to %d\n", vectorSize / proccessesNames.size(), proccessesNames.at(i));
// size--;
// numbers.erase(numbers.begin(), (numbers.begin() + 2));
// }
// /*while (zVector.size() != 12) {*/
// MPI_Status status;
// static int counter = 0;
// cout << "attemp " << counter << "\n";
// // Probe for an incoming message from process zero
// //MPI_Probe(0, 0, MPI_COMM_WORLD, &status);
//
// // When probe returns, the status object has the size and other
// // attributes of the incoming message. Get the message size
// //MPI_Get_count(&status, MPI_INT, &number_amount);
//
//
//
// for (int k = 1; k <= 3; k++) {
// // Allocate a buffer to hold the incoming numbers
// int* number_buf_z = new int[sizeof(int) * vectorSize / proccessesNames.size() * 2 + 1];
// MPI_Recv(number_buf_z, vectorSize / proccessesNames.size() * 2 + 1, MPI_INT, k, 0,
// MPI_COMM_WORLD, MPI_STATUS_IGNORE);
//
// for (int i = 0; i < vectorSize / proccessesNames.size() * 2 + 1; i++)
// {
// cout << number_buf_z[i] << " in buf z" << endl;
//
// zVector.push_back(number_buf_z[i]);
//
// }
// //if (zVector.size() == vectorSize / 2) break;
// delete[] number_buf_z;
// }
// cout << "z vec size is " << zVector.size() << endl;
// //}
// cout << "vector Z equals to: \n";
// for_each(zVector.begin(), zVector.end(), [](int x) {
// cout << x << "\n"; });
//
// //MPI_Send(numbers, number_amount, MPI_INT, 1, 0, MPI_COMM_WORLD);
//}
//else if (find(proccessesNames.begin(), proccessesNames.end(), rank) != proccessesNames.end()) {
// MPI_Status status;
// // Probe for an incoming message from process zero
// MPI_Probe(0, 0, MPI_COMM_WORLD, &status);
//
// // When probe returns, the status object has the size and other
// // attributes of the incoming message. Get the message size
// MPI_Get_count(&status, MPI_INT, &number_amount);
//
// // Allocate a buffer to hold the incoming numbers
// int* number_buf = new int[sizeof(int) * number_amount];
//
// // Now receive the message with the allocated buffer
// MPI_Recv(number_buf, number_amount, MPI_INT, 0, 0,
// MPI_COMM_WORLD, MPI_STATUS_IGNORE);
// printf("%d dynamically received %d numbers from 0.\n",
// rank, number_amount);
// vector<int > resultZvector;
// for (int i = 0; i < number_amount; i++)
// {
// cout << number_buf[i] << "\n";
//
// }
// for (int i = 0; i < number_amount / 2; i++)
// {
// int buf_num = 0;
// buf_num = number_buf[i] * a + number_buf[i + 1] * b;
// resultZvector.push_back(buf_num);
// cout << buf_num << " is Z coordinate." << "\n";
//
// buf_num = number_buf[i] * a + number_buf[i + 1] * b;
// resultZvector.push_back(buf_num);
// cout << buf_num << " is new Y coordinate." << "\n";
//
// buf_num = number_buf[i] * number_buf[i + 1];
// resultZvector.push_back(buf_num);
// cout << buf_num << " is again Z coordinate." << "\n";
// resultZvector.push_back(number_buf[i+1]);
// resultZvector.push_back(number_buf[i]);
//
//
// }
// MPI_Send(resultZvector.data(), resultZvector.size(), MPI_INT, 0, 0, MPI_COMM_WORLD);
//
//
// delete[] number_buf;
//}
// task 8 -n 3
//const int a = 2;
//const int b = 2;
//vector<int> proccessesNames = { 1,2 };
//int number_amount;
//if (rank == 0) {
// const int MAX_NUMBERS = 12;
// vector<int> numbers = { 1,2,3,4,5,6 }; // xy pairs
// vector<int> zVector;
// vector<int> matrixA = {1,1,1,1}; // 2x2 matrix
// vector<int> matrixB = {2,2,2,2}; // 2x2 matrix
//
//
// // Pick a random amount of integers to send to process one
// srand(time(NULL));
// //number_amount = (rand() / (float)RAND_MAX) * MAX_NUMBERS;
//
// cout << "num of processes is " << size << "\n";
// // Send the random amount of integers to process one
//
//
// for (int i = 0; i < proccessesNames.size(); i++) {
// vector<int> bufferVector;
// vector<int> bufferBMatrix(matrixB);
// vector<int> bufferAMatrix(matrixA);
// bufferVector.push_back(2);
// for (int j = 0; j < matrixA.size()/2; j++)
// {
//
// bufferVector.push_back(bufferAMatrix.back());
// bufferAMatrix.pop_back();
// }
//
// for (int k = 0; k < matrixB.size(); k++)
// {
// bufferVector.push_back(bufferBMatrix.back());
// bufferBMatrix.pop_back();
// }
//
// MPI_Send(bufferVector.data(), bufferVector.size(), MPI_INT, proccessesNames.at(i), 0, MPI_COMM_WORLD);
// printf("0 sent %d numbers to %d\n", bufferVector.size(), proccessesNames.at(i));
//
// }
// while (zVector.size() != 4) {
// MPI_Status status;
// static int counter = 0;
// cout << "attemp " << counter << "\n";
//
// for (int k = 1; k <= 2; k++) {
// // Allocate a buffer to hold the incoming numbers
// int* number_buf_z = new int[sizeof(int) * matrixB.size()];
// MPI_Recv(number_buf_z, matrixB.size()/2, MPI_INT, k, 0,
// MPI_COMM_WORLD, MPI_STATUS_IGNORE);
//
// for (int i = 0; i < matrixB.size() / 2; i++)
// {
// cout << number_buf_z[i] << " in buf z" << endl;
//
// zVector.push_back(number_buf_z[i]);
//
// }
// //if (zVector.size() == vectorSize / 2) break;
// delete[] number_buf_z;
// }
// cout << "z vec size is " << zVector.size() << endl;
// }
// cout << "vector Z equals to: \n";
// for_each(zVector.begin(), zVector.end(), [](int x) {
// cout << x << "\n"; });
//
// //MPI_Send(numbers, number_amount, MPI_INT, 1, 0, MPI_COMM_WORLD);
//}
//else if (find(proccessesNames.begin(), proccessesNames.end(), rank) != proccessesNames.end()) {
// MPI_Status status;
// // Probe for an incoming message from process zero
// MPI_Probe(0, 0, MPI_COMM_WORLD, &status);
//
// // When probe returns, the status object has the size and other
// // attributes of the incoming message. Get the message size
// MPI_Get_count(&status, MPI_INT, &number_amount);
//
// // Allocate a buffer to hold the incoming numbers
// int* number_buf = new int[sizeof(int) * number_amount];
// cout << number_amount << "count \n";
// // Now receive the message with the allocated buffer
// MPI_Recv(number_buf, number_amount, MPI_INT, 0, 0,
// MPI_COMM_WORLD, MPI_STATUS_IGNORE);
// printf("%d dynamically received %d numbers from 0.\n",
// rank, number_amount);
// vector<int > resultZvector;
// for (int i = 0; i < number_amount; i++)
// {
// cout << number_buf[i] << "\n";
//
// }
//
// int buf_num = 0;
// int i = 0;
// resultZvector.push_back(number_buf[i+1] * number_buf[i + 1 + number_buf[0]] + number_buf[i+2]* number_buf[i + 2 + number_buf[0]]);
// resultZvector.push_back(number_buf[i + 1] * number_buf[i + 3 + number_buf[0]] + number_buf[i + 2] * number_buf[i + 4 + number_buf[0]]);
//
//
//
// MPI_Send(resultZvector.data(), resultZvector.size(), MPI_INT, 0, 0, MPI_COMM_WORLD);
//
//
// delete[] number_buf;
//}
// task 9 -n 3
//const int a = 2;
//const int b = 2;
//vector<int> proccessesNames = { 1,2 };
//int number_amount;
//if (rank == 0) {
// const int MAX_NUMBERS = 12;
// vector<int> numbers = { 1,2,3,4,5,6 }; // xy pairs
// vector<int> zVector;
// vector<int> vectorX = {1,2};
// vector<int> matrixA = { 1,1,1,1 }; // 2x2 matrix
//
// //vector<int> matrixB = { 2,2,2,2 }; // 2x2 matrix
//
//
// // Pick a random amount of integers to send to process one
// srand(time(NULL));
// //number_amount = (rand() / (float)RAND_MAX) * MAX_NUMBERS;
//
// cout << "num of processes is " << size << "\n";
// // Send the random amount of integers to process one
//
//
// for (int i = 0; i < proccessesNames.size(); i++) {
// vector<int> bufferVector;
// //vector<int> bufferBMatrix(matrixB);
// vector<int> bufferAMatrix(matrixA);
// for (int j = 0; j < matrixA.size() / proccessesNames.size(); j++)
// {
//
// bufferVector.push_back(bufferAMatrix.back());
// bufferAMatrix.pop_back();
// }
//
// for (int k = 0; k < vectorX.size(); k++)
// {
// bufferVector.push_back(vectorX.at(k));
// }
//
// MPI_Send(bufferVector.data(), bufferVector.size(), MPI_INT, proccessesNames.at(i), 0, MPI_COMM_WORLD);
// printf("0 sent %d numbers to %d\n", bufferVector.size(), proccessesNames.at(i));
//
// }
// while (zVector.size() != 4) {
// MPI_Status status;
// static int counter = 0;
// cout << "attemp " << counter << "\n";
//
// for (int k = 1; k <= 2; k++) {
// // Allocate a buffer to hold the incoming numbers
// int* number_buf_z = new int[sizeof(int) * matrixA.size()];
// MPI_Recv(number_buf_z, matrixA.size() / 2, MPI_INT, k, 0,
// MPI_COMM_WORLD, MPI_STATUS_IGNORE);
//
// for (int i = 0; i < matrixA.size() / 2; i++)
// {
// cout << number_buf_z[i] << " in buf z" << endl;
//
// zVector.push_back(number_buf_z[i]);
//
// }
// //if (zVector.size() == vectorSize / 2) break;
// delete[] number_buf_z;
// }
// cout << "z vec size is " << zVector.size() << endl;
// }
// cout << "vector Z equals to: \n";
// for_each(zVector.begin(), zVector.end(), [](int x) {
// cout << x << "\n"; });
//
// //MPI_Send(numbers, number_amount, MPI_INT, 1, 0, MPI_COMM_WORLD);
//}
//else if (find(proccessesNames.begin(), proccessesNames.end(), rank) != proccessesNames.end()) {
// MPI_Status status;
// // Probe for an incoming message from process zero
// MPI_Probe(0, 0, MPI_COMM_WORLD, &status);
//
// // When probe returns, the status object has the size and other
// // attributes of the incoming message. Get the message size
// MPI_Get_count(&status, MPI_INT, &number_amount);
//
// // Allocate a buffer to hold the incoming numbers
// int* number_buf = new int[sizeof(int) * number_amount];
// cout << number_amount << "count \n";
// // Now receive the message with the allocated buffer
// MPI_Recv(number_buf, number_amount, MPI_INT, 0, 0,
// MPI_COMM_WORLD, MPI_STATUS_IGNORE);
// printf("%d dynamically received %d numbers from 0.\n",
// rank, number_amount);
// vector<int > resultZvector;
// for (int i = 0; i < number_amount; i++)
// {
// cout << number_buf[i] << "\n";
//
// }
//
// int buf_num = 0;
// int i = 0;
// if(rank == 1)
// resultZvector.push_back(number_buf[1]);
// else {
// resultZvector.push_back(number_buf[2]);
// }
// resultZvector.push_back(number_buf[0] * number_buf[2] + number_buf[1] * number_buf[3]);
//
//
//
// MPI_Send(resultZvector.data(), resultZvector.size(), MPI_INT, 0, 0, MPI_COMM_WORLD);
//
//
// delete[] number_buf;
//}
// task 10 -n 2
//class Timer
//{
//private:
// // Псевдонимы типов используются для удобного доступа к вложенным типам
// using clock_t = std::chrono::high_resolution_clock;
// using second_t = std::chrono::duration<double, std::ratio<1> >;
//
// std::chrono::time_point<clock_t> m_beg;
//
//public:
// Timer() : m_beg(clock_t::now())
// {
// }
//
// void reset()
// {
// m_beg = clock_t::now();
// }
//
// double elapsed() const
// {
// return std::chrono::duration_cast<second_t>(clock_t::now() - m_beg).count();
// }
//};
//
//const int a = 2;
//const int b = 2;
//vector<int> proccessesNames = { 1};
//vector<double> sendflag(1, 1);
//vector<double> getflag(1, 0);
//int number_amount;
//bool typeIsAorB = true; // false == a ping pong
//bool firstHasReceived = false;
//bool secondHasReceived = false;
//int n = 10000; // for pingping more than 100000 is impossible because of some mysterious reason
//Timer pingPingTimer;
//cout << "hy";
//if (rank == 0) {
// const int MAX_NUMBERS = 12;
// vector<int> numbers = { 1,2,3,4,5,6 }; // xy pairs
// vector<int> zVector;
// vector<int> vectorX = {1,2};
// vector<double> matrixA(n,1); // 2x2 matrix
//
//
// srand(time(NULL));
//
// cout << "num of processes is " << size << "\n";
//
// Timer t0;
// MPI_Send(matrixA.data(), matrixA.size(), MPI_DOUBLE, proccessesNames.at(0), 0, MPI_COMM_WORLD);
// printf("0 sent %d numbers to %d\n", matrixA.size(), proccessesNames.at(0));
// //cout << t0.elapsed() << ": 0 process has sent a message. Ping \n";
// //}
// Timer t1;
// //while (zVector.size() != n) {
//
// MPI_Status status;
// /* static int counter = 0;
// cout << "attemp " << counter << "\n";*/
//
// //for (int k = 1; k <= n; k++) {
// // Allocate a buffer to hold the incoming numbers
// double* number_buf_z = new double[sizeof(int) * matrixA.size()];
// MPI_Recv(number_buf_z, matrixA.size(), MPI_DOUBLE, 1, 0,
// MPI_COMM_WORLD, MPI_STATUS_IGNORE);
//
// for (int i = 0; i < matrixA.size(); i++)
// {
// //cout << number_buf_z[i] << " in buf z" << endl;
//
// zVector.push_back(number_buf_z[i]);
//
// }
// //if (zVector.size() == vectorSize / 2) break;
// delete[] number_buf_z;
// //}
// cout << "z vec size is " << zVector.size() << endl;
// //}
// //MPI_Send(sendflag.data(), sendflag.size(), MPI_DOUBLE, 0, 0, MPI_COMM_WORLD);
// MPI_Recv(getflag.data(), getflag.size(), MPI_DOUBLE, 1, 0,
// MPI_COMM_WORLD, MPI_STATUS_IGNORE);
//
// cout << getflag.at(0) << ": flag \n";
//
// firstHasReceived = true;
// if (getflag.at(0) == 1)
// secondHasReceived = true;
// cout << "2 change common val \n";
// if (typeIsAorB == false) {
// cout <<t0.elapsed() << ": process 0 has received the message. Ping Pong \n";
// }
//
// //cout << "vector Z size equals to: "<<zVector.size() << "\n";
// //for_each(zVector.begin(), zVector.end(), [](int x) {
// // cout << x << "\n"; });
//
// //MPI_Send(numbers, number_amount, MPI_INT, 1, 0, MPI_COMM_WORLD);
//}
//else if (find(proccessesNames.begin(), proccessesNames.end(), rank) != proccessesNames.end()) {
// if (typeIsAorB == true) { // if PING PING
//
// MPI_Status status;
// vector<double> sendvector(n, 1);
// vector<double> sendflag(1, 1);
// vector<double> getflag(1, 1);
// MPI_Send(sendvector.data(), sendvector.size(), MPI_DOUBLE, 0, 0, MPI_COMM_WORLD);
//
// // Probe for an incoming message from process zero
// MPI_Probe(0, 0, MPI_COMM_WORLD, &status);
//
// // When probe returns, the status object has the size and other
// // attributes of the incoming message. Get the message size
// MPI_Get_count(&status, MPI_DOUBLE, &number_amount);
//
// // Allocate a buffer to hold the incoming numbers
// double* number_buf = new double[sizeof(int) * number_amount];
// cout << number_amount << "count \n";
// // Now receive the message with the allocated buffer
// MPI_Recv(number_buf, number_amount, MPI_DOUBLE, 0, 0,
// MPI_COMM_WORLD, MPI_STATUS_IGNORE);
// printf("%d dynamically received %d numbers from 0. Ping Ping.\n",
// rank, number_amount);
// MPI_Send(sendflag.data(), sendflag.size(), MPI_DOUBLE, 0, 0, MPI_COMM_WORLD);
// /*MPI_Recv(getflag.data(), getflag.size(), MPI_DOUBLE, 0, 0,
// MPI_COMM_WORLD, MPI_STATUS_IGNORE);
// secondHasReceived = true;*/
// //cout << rank << " has changed the common val \n";
// delete[] number_buf;
//
// }
// else
// {
// Timer t;
// MPI_Status status;
// // Probe for an incoming message from process zero
// MPI_Probe(0, 0, MPI_COMM_WORLD, &status);
//
// // When probe returns, the status object has the size and other
// // attributes of the incoming message. Get the message size
// MPI_Get_count(&status, MPI_DOUBLE, &number_amount);
//
// // Allocate a buffer to hold the incoming numbers
// int* number_buf = new int[sizeof(int) * number_amount];
// cout << number_amount << "count \n";
// // Now receive the message with the allocated buffer
// MPI_Recv(number_buf, number_amount, MPI_DOUBLE, 0, 0,
// MPI_COMM_WORLD, MPI_STATUS_IGNORE);
// printf("%d dynamically received %d numbers from 0.\n",
// rank, number_amount);
//
// MPI_Send(number_buf, number_amount, MPI_DOUBLE, 0, 0, MPI_COMM_WORLD);
//
// delete[] number_buf;
// }
//
//}
//if (typeIsAorB == true && rank == 0)
//{
// while (firstHasReceived != true )
// {
// while (secondHasReceived != true) {}
// }
// cout << pingPingTimer.elapsed() << ": pingping time \n";
//}
// task 11 -n 2
//vector<float > rand_nums(4,2);
//if (rank == 0) {
//
//}
//
//vector<float > receiver(4,0);
//vector<float > localReceiver(4,0);
//float getdata;
//// Scatter the random numbers to all processes
//MPI_Scatter(rand_nums.data(), 2, MPI_FLOAT, receiver.data(),
// 2, MPI_FLOAT, 0, MPI_COMM_WORLD);
//
//// Compute the average of your subset
//cout << receiver.size();
//
//float localSumOfSquare = 0;
//for (int x : receiver) {
// localSumOfSquare += x * x;
//
//cout << x << " is val of " << rank << "\n";
//}
//MPI_Reduce(&localSumOfSquare, &getdata, 1, MPI_FLOAT, MPI_SUM, 0,
// MPI_COMM_WORLD);
//
//// Print the result
//if (rank == 0) {
// printf("Total length i s = %f\n", sqrt(getdata));
//}
//
//task 12 -n 2
// vector<float> twoVectors = {1,2,1,2}; // NB! chess distribution here
//if (rank == 0) {
//
//}
//
//vector<float > receiver(4, 1);
//float getdata;
//// Scatter the random numbers to all processes
//MPI_Scatter(twoVectors.data(), 2, MPI_FLOAT, receiver.data(),
// 2, MPI_FLOAT, 0, MPI_COMM_WORLD);
//
//
//cout << receiver.size();
//
//float localmult = 1;
//for (float x : receiver) {
// localmult *= x;
//
// cout << x << " is a val of rank " << rank << "\n";
//}
//MPI_Reduce(&localmult, &getdata, 1, MPI_FLOAT, MPI_SUM, 0,
// MPI_COMM_WORLD);
//
//// Print the result
//if (rank == 0) {
// printf(" scalar is = %f\n", getdata);
//}
// task13 -n 1
//#define LEN 4
//
// float val[LEN] = {5,1,3,4}; /* local array of values */
//int count = 4; /* local number of values */
//int myrank, minrank, minindex;
//float minval;
//
//struct {
// float value;
// int index;
//} in, out;
//
///* local minloc */
//in.value = val[0];
//in.index = 0;
//for (int i = 1; i < count; i++)
// if (in.value > val[i]) {
// in.value = val[i];
// in.index = i;
// }
//
///* global minloc */
//MPI_Comm_rank(MPI_COMM_WORLD, &myrank);
//in.index = myrank * LEN + in.index;
//MPI_Reduce(&in, &out, 1, MPI_FLOAT_INT, MPI_MINLOC, 0, MPI_COMM_WORLD);
///* At this point, the answer resides on process root
// */
//if (myrank == 0) {
// /* read answer out
// */
// minval = out.value;
// minrank = out.index / LEN;
// minindex = out.index % LEN;
// cout << minval << " " << minindex << "\n";
//}
// task14 -n 2
//#define LEN 4
//
// float val[LEN] = {5,1,3,4}; /* local array of values */
//int count = 4; /* local number of values */
//int myrank, minrank, minindex;
//float minval;
//vector<float> receiver(2);
//struct {
// float value;
// int index;
//} in, out;
//float max = 0;
//MPI_Scatter(&val, 2, MPI_FLOAT, receiver.data(),
// 2, MPI_FLOAT, 0, MPI_COMM_WORLD);
///* local minloc */
//in.value = val[0];
//in.index = 0;
//float sum = 0;
//for_each(receiver.begin(), receiver.end(), [&sum](float x) { sum += x; });
//
///* global minloc */
//MPI_Comm_rank(MPI_COMM_WORLD, &myrank);
//in.index = myrank * LEN + in.index;
//MPI_Reduce(&sum, &max, 1, MPI_FLOAT, MPI_MAX, 0, MPI_COMM_WORLD);
///* At this point, the answer resides on process root
// */
//if (myrank == 0) {
// cout << max << " is max. Norm";
//}
//task15 -n 2
//#define LEN 8
//
//float val[LEN] = {1,1,2,2,1,1,2,2}; /* local array of values */
//vector<float> result(LEN/2, 0); /* local array of values */
//int count = 8; /* local number of values */
//int myrank, minrank, minindex;
//float minval;
//vector<float> receiver(4);
//struct {
// float value;
// int index;
//} in, out;
//
//float max = 0;
//MPI_Scatter(&val, 4, MPI_FLOAT, receiver.data(),
// 4, MPI_FLOAT, 0, MPI_COMM_WORLD);
///* local minloc */
//for (int i = 0; i < 2; i++)
// receiver.at(i) = receiver[i] * receiver[i + 2];
//MPI_Gather(receiver.data(), 2, MPI_INT, result.data(), 2, MPI_INT, 0, MPI_COMM_WORLD);
//
//if (rank == 0) {
// for_each(result.cbegin(), result.cend(), [](const int x) {cout << x << " val \n"; });
//}
// task 16 -n 2
//
//#define LEN 8
//
//float val[LEN] = { 1,1,1,1 }; /* local array of values */
//vector<float> vec(2,2);
//vector<float> result(vec.size()); /* local array of values */
//int count = 8; /* local number of values */
//int myrank, minrank, minindex;
//float minval;
//vector<float> receiver(4);
//struct {
// float value;
// int index;
//} in, out;
//
//float max = 0;
//MPI_Scatter(&val, 2, MPI_FLOAT, receiver.data(),
// 2, MPI_FLOAT, 0, MPI_COMM_WORLD);
//MPI_Bcast(vec.data(), 2, MPI_FLOAT, 0, MPI_COMM_WORLD);
///* local minloc */
//for (int i = 0; i < vec.size()/2; i++)
// vec.at(i) = receiver[i]* vec[i] + receiver[i+1]*vec[i+1];
//
//
//MPI_Gather(vec.data(), 1, MPI_FLOAT, result.data(), 1, MPI_FLOAT, 0, MPI_COMM_WORLD);
//
//if (rank == 0) {
// for_each(result.cbegin(), result.cend(), [](const int x) {cout << x << " val \n"; });
//}
// task 17 -n 2
//#define LEN 8
//
//float val[LEN] = { 1,1,1,1 }; /* local array of values */
//vector<float> vec(2, 2);
//vector<float> result; /* local array of values */
//int count = 8; /* local number of values */
//int myrank, minrank, minindex;
//float minval;
//vector<float> receiver(4);
//struct {
// float value;
// int index;
//} in, out;
//
//float max = 0;
//MPI_Scatter(&val, 2, MPI_FLOAT, receiver.data(),
// 2, MPI_FLOAT, 0, MPI_COMM_WORLD);
//MPI_Bcast(vec.data(), 2, MPI_FLOAT, 0, MPI_COMM_WORLD);
///* local minloc */
////for (int i = 0; i < vec.size() / 2; i++)
//// vec.at(i) = receiver[i] * vec[i] + receiver[i + 1] * vec[i + 1];
//
//if (rank == 0)result.push_back(vec[0]);
////MPI_Gather(vec.data(), 1, MPI_FLOAT, result.data(), 1, MPI_FLOAT, 0, MPI_COMM_WORLD);
//if( rank != 0 )
//MPI_Send(vec.data(), 1, MPI_FLOAT, 0, 0, MPI_COMM_WORLD);
//if (rank == 0) {
//
// while (result.size() != 2) {
// vector<float> buf(1);
// cout << result.size() << "current size! \n";
// for (int k = 1; k < 2; k++) {
//
// MPI_Recv(buf.data(), 1, MPI_FLOAT, k, 0,
// MPI_COMM_WORLD, MPI_STATUS_IGNORE);
// result.push_back(buf.at(0));
// }
// }
// for_each(result.cbegin(), result.cend(), [](const int x) {cout << x << " val \n"; });
//}
//
//task 18
//#define LEN 4 // -n 4
//
//constexpr uint64_t sizeRaw = 5;
//constexpr uint64_t sizeCol = 5;
//static int counter = 0;
//vector<int> vecOfMatrix;
//vector<vector<int>> matrix(sizeRaw);
//for (int i = 0; i < sizeRaw; i++)
// matrix[i].resize(sizeCol);
//std::for_each(matrix.begin(), matrix.end(),
// [&vecOfMatrix, sizeRaw, sizeCol](std::vector<int> &vec) {
// vec.resize(sizeCol);
// std::for_each(vec.begin(), vec.end(), [&vecOfMatrix, sizeRaw, sizeCol](int& x) {
// //x = 1+rand()%sizeCol;
//
// x = counter;
// counter++;
// //vecOfMatrix.push_back(x);
// });
//});
//
//if (rank == 0)
////for_each(vecOfMatrix.cbegin(), vecOfMatrix.cend(), [](const int x) {cout << x << " val " << "\n"; });
//
//cout << "hello \n";
//vector<int> buffer;
//int n = 0;
//int n_halfDivider = 0;
//int m = 0;
//int m_halfDivider = 0;
//int isEvenRaw = 0; // 0 = not even
//int isEvenCol = 0;
//if (sizeCol % 2 == 0) {
// isEvenCol = 1;
// m_halfDivider = sizeCol / 2;
//}
//else
//{
// m_halfDivider = sizeCol / 2 + 1;
//}
//
//if (sizeRaw % 2 == 0) {
// isEvenRaw = 1;
// n_halfDivider = sizeRaw / 2;
//}
//else
//{
// n_halfDivider = sizeRaw / 2 + 1;
//}
//
//cout << "hello \n";
//vector<int > vectorOfSize;
//for (int i = 0; i < 4; i++)
// switch (i)
// {
// case 0:
// n = 0;
// m = 0;
// for (int i = n; i < n_halfDivider; i++)
//{
// for (int j = m; j < m_halfDivider; j++)
// {
//
// vecOfMatrix.push_back(matrix.at(i).at(j));
// }
//}
////cout << vecOfMatrix.size() << " size 0 \n";
// vectorOfSize.push_back(n_halfDivider*m_halfDivider);
// break;
// case 1:
// n = 0;
// m = m_halfDivider;
// for (int i = n; i < n_halfDivider; i++)
// {
// for (int j = m; j < sizeCol; j++)
// {
// vecOfMatrix.push_back(matrix.at(i).at(j));
// }
// }
// vectorOfSize.push_back(n_halfDivider*(sizeCol - m_halfDivider));
// break;
// case 2:
// n = n_halfDivider;
// m = 0;
// for (int i = n; i < sizeRaw; i++)
// {
// for (int j = m; j < m_halfDivider; j++)
// {
// vecOfMatrix.push_back(matrix.at(i).at(j));
// }
// }
// vectorOfSize.push_back((sizeRaw - n_halfDivider)*m_halfDivider);
// break;
// case 3:
// n = n_halfDivider;
// m = m_halfDivider;
//
// for (int i = n; i < sizeRaw; i++)
// {
// for (int j = m; j < sizeCol; j++)
// {
// vecOfMatrix.push_back(matrix.at(i).at(j));
// }
// }
// vectorOfSize.push_back((sizeRaw - n_halfDivider)*(sizeCol - m_halfDivider));
// break;
// default:
// break;
// }
//
//int isEvenMatrix = 0;
//
////vector<float> receiver(1);
//if (rank == 0) {
// if (std::adjacent_find(vectorOfSize.begin(), vectorOfSize.end(), std::not_equal_to<>()) == vectorOfSize.end())
// {
// isEvenMatrix = 1;
// std::cout << "All elements are equal each other" << std::endl;
// }
// cout << vecOfMatrix.size() << "vec of matrix size \n";
// cout << "is even mat: " << isEvenMatrix << " \n";
// cout << "vecOfsize has size: " << vectorOfSize.size() << "\n";
// for_each(vectorOfSize.cbegin(), vectorOfSize.cend(), [rank](int x) {cout << x << " size " << "\n"; });
// for_each(vecOfMatrix.cbegin(), vecOfMatrix.cend(), [rank](int x) {cout << x << " value " << "\n"; });
//
//
//
//}
//
//vector<int> vectorOfProcesses(sizeRaw*sizeCol / 2, -1);
//vector<int> disp;
//disp.push_back(0);
//for (int i = 1; i < vectorOfSize.size(); i++)
//{
// int to_display = 0;
// for (int j = 0; j < i; j++)
// {
// to_display += vectorOfSize.at(j);
// }
// disp.push_back(to_display);
//}
//if (rank == 0)
//for_each(disp.cbegin(), disp.cend(), [rank](int x) {cout << x << " disp " << "\n"; });
//
//
////if (sizeRaw % 2 == 0 && sizeCol % 2 == 0)
//MPI_Scatterv(vecOfMatrix.data(), vectorOfSize.data(), disp.data(), MPI_INT, vectorOfProcesses.data(),
// sizeRaw*sizeCol / 2, MPI_INT, 0, MPI_COMM_WORLD);
//
//for_each(vectorOfProcesses.cbegin(), vectorOfProcesses.cend(), [rank](int x) {cout << x << " val of rank " << rank << "\n"; });
//
//task 19-- -n any num
//int someNum = rank;
//int sum;
//MPI_Reduce(&someNum, &sum, 1, MPI_FLOAT, MPI_SUM, 0,
// MPI_COMM_WORLD);
//
//MPI_Bcast(&sum, 1, MPI_INT, 0, MPI_COMM_WORLD);
//
//
// cout << "rank " << rank << " has received a sum: " << sum << '\n' ;
//
//
//task 20-- -n 3
//MPI_Datatype matrix;
//MPI_Datatype matrix2;
////mpi_datatype matrix2;
//MPI_Status status;
//
//
//
//MPI_Type_vector(4, 8, 16, MPI_DOUBLE, &matrix);
//MPI_Type_vector(1, 32, 1, MPI_DOUBLE, &matrix2);
//MPI_Type_commit(&matrix);
//MPI_Type_commit(&matrix2);
//
////vector<vector<double>> u;
////u.push_back(vector<double>());
////u.push_back(vector<double>());
////u.push_back(vector<double>());
////u.push_back(vector<double>());
////u.push_back(vector<double>());
////u.push_back(vector<double>());
////u.push_back(vector<double>());
////u.push_back(vector<double>());
////std::array<double, 64> u2;
//if (rank == 0) {
// double u2[64];
// vector<double> odd;
// // int counter = 0;
// //std::for_each(u.begin(), u.end(),
// // [&u2, &counter](std::vector<double> &vec) {
// // for_each(vec.begin(), vec.end(),
// // [&vec, &u2, &counter] {
// // vec.push_back(counter);
// // u2.push_back(counter);
// // counter++;
// // });
// //});
// cout << rank << "cur rank \n";
// //if (rank == 0)
// //if (rank == 0) {
//
// for (int i = 0; i < 64; i++)
// {
// u2[i] = i;
// }
//
// int counter = 0;
// for (int i = 0; i < 8; i++)
// {
// for (int u = counter * 8; u < (counter + 1) * 8; u++)
// {
// if (counter % 2 == 1)
// odd.push_back(u);
// }
// counter++;
// }
//
//
// MPI_Send(u2, 1, matrix, 1, 0, MPI_COMM_WORLD);
//
//
// MPI_Send(odd.data(), 1, matrix2, 2, 0, MPI_COMM_WORLD);
//
//
//
//
//
//}
//
// if (rank == 1) {
//
//
// double* recv_buff2 = new double[250];
// for (int i = 0; i < 250; i++)
// {
// recv_buff2[i] = 0;
// }
//
// MPI_Recv(recv_buff2, 1, matrix, 0, 0, MPI_COMM_WORLD, &status);
// //recv_buff = new double*[2];
// for (int i = 0; i < 170; i++)
// {
// cout << recv_buff2[i];
// }
//
// cout << "first've finished \n";
//
//}
// if (rank == 2) {
// double* recv_buff1 = new double[250];
// for (int i = 0; i < 250; i++)
// {
// recv_buff1[i] = 0;
// }
//
// MPI_Recv(recv_buff1, 1, matrix, 0, 0, MPI_COMM_WORLD, &status);
// //recv_buff = new double*[2];
// for (int i = 0; i < 170; i++)
// {
// cout << recv_buff1[i];
// }
//
// cout << "secon've finished \n";
//
// }
//task 21-- du mus alle Felhen ignorieren -n 4
//
//vector<double> u2;
// for (int i = 0; i < 64; i++)
// {
//
// u2.push_back(i);
//
// }
//
//struct MyType {
// double * star = new double[64];
//
//};
//
//
//
//struct MyType my;
//if(rank == 0 )
//for (int i = 0; i < 64; i++)
//{
//
// my.star[i] = i;
//
//}
//else
//for (int i = 0; i < 64; i++)
//{
//
// my.star[i] = 0;
//
//}
//int blocklengths[2] = { 8, 8};
//
//
//MPI_Datatype types[2] = { MPI_DOUBLE, MPI_DOUBLE };
//MPI_Aint address[2];
//MPI_Aint disp[3];
//MPI_Datatype newtype;
//
//
//MPI_Get_address(&my, &address[0]);
//MPI_Get_address(&(my.star[8]), &address[1]);
//MPI_Get_address(&(my.star[40]), &address[2]);
//disp[0] = address[1] - address[0];
//disp[1] = address[2] - address[0];
//MPI_Type_create_struct(2, blocklengths, disp, types, &newtype);
//MPI_Type_commit(&newtype);
//
//if (rank == 0) {
//
//
// for (int i = 1; i <= 3; i++) {
// MPI_Get_address(&my, &address[0]);
// MPI_Get_address(&(my.star[i*8]), &address[1]);
// MPI_Get_address(&(my.star[40 + (i-1) * 8]), &address[2]);
// disp[0] = address[1] - address[0];
// disp[1] = address[2] - address[0];
// MPI_Type_create_struct(2, blocklengths, disp, types, &newtype);
// MPI_Type_commit(&newtype);
// MPI_Send(&my, 1, newtype,i, 0, MPI_COMM_WORLD);
//
//
// }
//}
//else if (rank == 1 || rank == 2 || rank == 3) {
// MPI_Status status;
// MPI_Recv(&my, 1, newtype, 0, 0, MPI_COMM_WORLD, &status);
// //printf("recv rank=1 c=%c f=%f\n", my.c[0], my.f);
// cout << rank << " rank begins receiving \n";
// for (int i = 0; i < 64; i++)
// {
//
// cout << my.star[i];
//
// }
//}
//
//
//MPI_Type_free(&newtype);
//task 22-- -n any num
//
//
//int blocklengths[2] = { 2, 1 };
//
//
//MPI_Datatype types[2] = { MPI_DOUBLE, MPI_DOUBLE };
//MPI_Aint address[2];
//
//MPI_Datatype newtype;
//int stride[2] = { 0, 3 };
//
//MPI_Type_indexed(2, blocklengths, stride, MPI_DOUBLE, &newtype);
//MPI_Type_commit(&newtype);
//
//vector<double> uptriangularmatrix;
//if (rank == 0) {
//
// uptriangularmatrix.push_back(1);
// uptriangularmatrix.push_back(2);
// uptriangularmatrix.push_back(3);
// uptriangularmatrix.push_back(4);
//}
//else
//{
// uptriangularmatrix.push_back(0);
// uptriangularmatrix.push_back(0);
// uptriangularmatrix.push_back(0);
// uptriangularmatrix.push_back(0);
//}
//MPI_Bcast(uptriangularmatrix.data(), 1, newtype, 0, MPI_COMM_WORLD);
//
//
//
//
//cout << "rank " << rank << " has received some mat: ";
//for (double d : uptriangularmatrix) {
// cout << d;
//}
//
//
//
//
//MPI_Type_free(&newtype);
//task 23-- -n 2
//int inteGER[10] = { 0,0 };
//double dobby[8] = { 0,0 };
//int inteGERB[50] = { 0,0 };
//double dobbyB[16] = { 0,0 };
//char buf[1000];
//if (rank == 0) {
// for (int i = 0; i < 10; i++)
// {
//
// inteGER[i] = i;
//
// }for (int i = 0; i < 8; i++)
// {
//
// dobby[i] = i;
//
// }
//}
//
//int position = 0;
//if (rank == 0) {
// MPI_Pack(dobby, 8, MPI_DOUBLE, buf, 1000, &position, MPI_COMM_WORLD);
// MPI_Pack(inteGER, 10, MPI_INT, buf, 1000, &position, MPI_COMM_WORLD);
// MPI_Bcast(buf, 1000, MPI_PACKED, 0, MPI_COMM_WORLD);
//MPI_Send(buffer, position, MPI_PACKED, 1, 100, MPI_COMM_WORLD);
//}
//
//else {
// MPI_Bcast(buf, 1000, MPI_PACKED, 0, MPI_COMM_WORLD);
// cout << rank << "rank\n";
// //MPI_Bcast(&buf, 100, MPI_PACKED, 0, MPI_COMM_WORLD);
// position = 0;
// MPI_Unpack(buf, 1000, &position, dobby, 8, MPI_DOUBLE, MPI_COMM_WORLD);
// MPI_Unpack(buf, 1000, &position, inteGER, 10, MPI_INT, MPI_COMM_WORLD);
// cout << rank << " rank\n";
// cout << "dobby \n";
// for (double d : dobby) {
// cout << d;
// }
// cout << "\n ints \n";
// for (double d : inteGER) {
// cout << d;
// }
//
// //cout << "\n" << &MPI_Comm_group << endl;
//}
//task 24-- -n 15
//int errs = 0, toterr;
//MPI_Group basegroup;
//MPI_Group g1, g2, g3, g4, g5, g6, g7, g8, g9, g10;
//MPI_Group g3a, g3b;
//MPI_Comm comm, newcomm, splitcomm, dupcomm;
//int i, grp_rank, grp_size, result;
//int nranks, *ranks, *ranks_out;
//int range[1][3];
//int worldrank;
//
//MPI_Comm_rank(MPI_COMM_WORLD, &worldrank);
//comm = MPI_COMM_WORLD;
//MPI_Comm_group(comm, &basegroup); // world group
////MPI_Comm_rank(comm, &rank);
////MPI_Comm_size(comm, &size);
//
//ranks = new int[size];
//for (int i = 0; i < size; i++)
//{
// ranks[i] = i;
//}
////cout << size << " " << rank << " world\n";
//ranks[0] = 9;
//ranks[1] = 8;
//ranks[2] = 6;
//ranks[3] = 3;
//ranks[4] = 1;
//
//MPI_Group_incl(basegroup, 5, ranks, &g1);
////ranks[1] = (rank + size - 1) % size;
//MPI_Comm worldcom, newcom;
//MPI_Group world_group;
////MPI_Group_size(g1, &size);
////MPI_Group_rank(g1, &rank);
//
////MPI_Comm_dup(MPI_COMM_WORLD, &worldcom);
////int rank1 = -1;
////cout << size << " " << rank << " newcom\n";
//MPI_Comm_group(MPI_COMM_WORLD, &world_group);
//
//MPI_Comm_create(MPI_COMM_WORLD, g1, &newcom);
////MPI_Group_size(MPI_COMM_WORLD, &size);
////MPI_Group_rank(MPI_COMM_WORLD, &rank);
//
////MPI_Comm comm1, comm2, icomm, local;
////cout << "here";
//MPI_Comm local;
//int rleader;
//if (newcom != MPI_COMM_NULL) { local = newcom; rleader = 0; }
//if (MPI_COMM_WORLD != MPI_COMM_NULL) { local = MPI_COMM_WORLD; rleader = 1;
//}
//
//MPI_Comm icomm;
/////////////////////////////// intercomm part!!!!!!!!!!!!!!!!!!!!!!!!!!!not working ahahahah
//if (newcom != MPI_COMM_NULL) {
// //MPI_Intercomm_create(newcom, 0, MPI_COMM_WORLD, 0, 0, &icomm);
//
// cout << "here in new comm";
// vector<float> vec(8,0);
// if (rank == 9) {
// for (int i = 0; i < 8; i++)
// {
// vec.at(i) = i;
// }
// }
// MPI_Bcast(vec.data(), 8, MPI_FLOAT, 0, newcom);
// cout << "rank is " << rank << endl;
// for (int i = 0; i < 8; i++)
// {
// cout << vec.at(i) << " ";
// }
// if (rank == 1)
// {
// MPI_Send(vec.data(), 8, MPI_FLOAT, 0, 0, MPI_COMM_WORLD);
//
// //MPI_Send(vec.data(), 8, MPI_FLOAT, 0, 0, icomm);
// }
//
// //MPI_Comm_rank(newcom, &rank1);
//}
//vector<float> somevec(8, 0);
//if (rank == 0) {
// MPI_Recv(somevec.data(), 8, MPI_FLOAT, 9, 0, MPI_COMM_WORLD, MPI_STATUSES_IGNORE);
// cout << "rank is " << rank << endl;
// for (int i = 0; i < 8; i++)
// {
// cout << somevec.at(i) << " ";
// }
//}
//if (MPI_COMM_WORLD != MPI_COMM_NULL) {
// MPI_Intercomm_create(MPI_COMM_WORLD, 0, MPI_COMM_WORLD, 1, 0, &icomm);
//
// cout << "here in world comm" << rank;
// vector<float> somevec(8, 0);
// MPI_Status status;
//if (rank == 0) {
// MPI_Recv(somevec.data(), 8, MPI_FLOAT, MPI_ANY_SOURCE, MPI_ANY_TAG, icomm, MPI_STATUSES_IGNORE);
// cout << "rank is " << rank << endl;
// for (int i = 0; i < 8; i++)
// {
// cout << somevec.at(i) << " ";
// }
//}
//}
//task 25-- -n 12
//int ranks1[3] = { 0,1,2 };
//int ranks2[3] = { 3,4,5 };
//int ranks3[3] = { 6,7,8 };
//int ranks4[3] = { 9,10, 11};
//MPI_Group wgroup, group1, group2;
//MPI_Group group3, group4;
//MPI_Comm_group(MPI_COMM_WORLD, &wgroup);
//MPI_Group_incl(wgroup, 3, ranks1, &group1);
//MPI_Group_incl(wgroup, 3, ranks2, &group2);
//MPI_Group_incl(wgroup, 3, ranks3, &group3);
//MPI_Group_incl(wgroup, 3, ranks4, &group4);
//MPI_Comm comm1, comm2, comm3, comm4, icomm, local;
//MPI_Comm_create(MPI_COMM_WORLD, group1, &comm1);
//MPI_Comm_create(MPI_COMM_WORLD, group2, &comm2);
//MPI_Comm_create(MPI_COMM_WORLD, group3, &comm3);
//MPI_Comm_create(MPI_COMM_WORLD, group4, &comm4);
//int rank1 = -1;
//int rank2 = -1;
//int rank3 = -1;
//int rank4 = -1;
//if (comm1 != MPI_COMM_NULL) MPI_Comm_rank(comm1, &rank1);
//if (comm2 != MPI_COMM_NULL) MPI_Comm_rank(comm2, &rank2);
//if (comm3 != MPI_COMM_NULL) MPI_Comm_rank(comm3, &rank3);
//if (comm4 != MPI_COMM_NULL) MPI_Comm_rank(comm4, &rank4);
//printf("rank1=%d, rank2=%d,rank3=%d,rank4=%d, rank=%d\n", rank1, rank2, rank3, rank4, rank);
//int rlead;
//if (comm1 != MPI_COMM_NULL) { local = comm1; rlead = 3; }
//if (comm2 != MPI_COMM_NULL) { local = comm2; rlead = 0; }
//if (comm3 != MPI_COMM_NULL) { local = comm3; rlead = 9; }
//if (comm4 != MPI_COMM_NULL) { local = comm4; rlead = 6; }
//int tag = 777;
//MPI_Intercomm_create(local, 0, MPI_COMM_WORLD, rlead, tag, &icomm);
//vector<int> a(3,0);
//if (comm1 != MPI_COMM_NULL) {
// vector<int> vec(1, 1);
// vector<int> result(3);
// MPI_Gather(vec.data(), 1, MPI_INT, result.data(), 1, MPI_INT, 0, comm1);
// if (rank == 0) {
// for_each(result.cbegin(), result.cend(), [](const int x) {cout << x << " val \n"; });
// }
// if (rank1 == 0) {
// MPI_Send(result.data(), 3, MPI_INT, 0, 12, icomm);
// }
//}
//if (comm2 != MPI_COMM_NULL) {
// vector<int> vec(1, 2);
// vector<int> result(3);
// MPI_Gather(vec.data(), 1, MPI_INT, result.data(), 1, MPI_INT, 0, comm2);
// if (rank2 == 0) {
// for_each(result.cbegin(), result.cend(), [](const int x) {cout << x << " val \n"; });
// MPI_Recv(a.data(), 3, MPI_INT, MPI_ANY_SOURCE, MPI_ANY_TAG, icomm, MPI_STATUSES_IGNORE); printf("a=%d\n", a);
// for_each(a.cbegin(), a.cend(), [](const int x) {cout << x << " received. \n";
// });
//
// }
//}
//if (comm3 != MPI_COMM_NULL) {
// vector<int> vec(1, 3);
// vector<int> result(3);
// MPI_Gather(vec.data(), 1, MPI_INT, result.data(), 1, MPI_INT, 0, comm3);
// if (rank3 == 0) {
// for_each(result.cbegin(), result.cend(), [](const int x) {cout << x << " val \n"; });
// MPI_Send(result.data(), 3, MPI_INT, 0, 12, icomm);
// }
//}
//if (comm4 != MPI_COMM_NULL) {
// vector<int> vec(1, 4);
// vector<int> result(3);
// MPI_Gather(vec.data(), 1, MPI_INT, result.data(), 1, MPI_INT, 0, comm4);
// if (rank4 == 0) {
// for_each(result.cbegin(), result.cend(), [](const int x) {cout << x << " val \n"; });
// MPI_Recv(a.data(), 3, MPI_INT, MPI_ANY_SOURCE, MPI_ANY_TAG, icomm, MPI_STATUSES_IGNORE); printf("a=%d\n", a);
// for_each(a.cbegin(), a.cend(), [](const int x) {cout << x << " received. \n"; });
// }
//}
//
//
//if (comm1 != MPI_COMM_NULL)cout << rank1 << "rank1";
//if (comm2 != MPI_COMM_NULL) cout << rank2 << "rank2";
//if (comm3 != MPI_COMM_NULL) cout << rank3 << "rank3";
//if (comm4 != MPI_COMM_NULL) cout << rank4 << "rank4";
//if (comm1 != MPI_COMM_NULL) MPI_Comm_free(&comm1);
//if (comm2 != MPI_COMM_NULL) MPI_Comm_free(&comm2);
//task 26
//#define LEN 4
//
//float val[LEN] = { 1,1,1,1 }; /* local array of values */
//vector<float> vec(2,2);
//vector<float> result(vec.size()); /* local array of values */
//int count = 8; /* local number of values */
//int myrank, minrank, minindex;
//float minval;
//vector<float> receiver(2);
//struct {
// float value;
// int index;
//} in, out;
//
//float avr = 0;
//MPI_Scatter(&val, 2, MPI_FLOAT, receiver.data(),
// 2, MPI_FLOAT, 0, MPI_COMM_WORLD);
////MPI_Bcast(vec.data(), 2, MPI_FLOAT, 0, MPI_COMM_WORLD);
///* local minloc */
//for (int i = 0; i < vec.size()/2; i++)
// vec.at(0) = receiver[i]+ receiver[i+1];
//
//MPI_Gather(vec.data(), 1, MPI_FLOAT, result.data(), 1, MPI_FLOAT, 0, MPI_COMM_WORLD);
//
//if (rank == 0) {
// int avg = 0;
// for_each(result.begin(), result.end(), [&avg](const int x) {
// avg += x;
// cout << x << " val \n"; });
//
// cout << "avg is " << avg /LEN;
//}
//
//task 27
//#define LEN 4
//
//float val[LEN] = { 1,1,1,1 }; /* local array of values */
//vector<float> vec(2, 2);
//vector<float> result(vec.size()); /* local array of values */
//int count = 8; /* local number of values */
//int myrank, minrank, minindex;
//float minval;
//vector<float> receiver(2);
//struct {
// float value;
// int index;
//} in, out;
//
//float avr = 0;
//MPI_Scatter(&val, 2, MPI_FLOAT, receiver.data(),
// 2, MPI_FLOAT, 0, MPI_COMM_WORLD);
////MPI_Bcast(vec.data(), 2, MPI_FLOAT, 0, MPI_COMM_WORLD);
///* local minloc */
//for (int i = 0; i < vec.size() / 2; i++)
// vec.at(0) = receiver[i] + receiver[i + 1];
//
//MPI_Gather(vec.data(), 1, MPI_FLOAT, result.data(), 1, MPI_FLOAT, 0, MPI_COMM_WORLD);
//
//if (rank == 0) {
// int avg = 0;
// for_each(result.begin(), result.end(), [&avg](const int x) {
// avg += x;
// cout << x << " val \n"; });
//
// cout << "sum is " << avg;
//}
//task 28
//
//std::default_random_engine generator;
//std::uniform_int_distribution<int> distribution(1, 30000);
//
//vector<double> result(2);
// int Npoints = (int)1E3;
// int Nincircle = 0;
// srand(time(0));
// MPI_Bcast(&Npoints, 1, MPI_INT, 0, MPI_COMM_WORLD);
//
// for (int i = 0; i < Npoints; i++)
// {
// double R = 1.0,
// x = (distribution(generator) % (4 * Npoints) - 2 * Npoints) / (2.0*Npoints),
// y = (distribution(generator) % (4 * Npoints) - 2 * Npoints) / (2.0*Npoints);
// if
// ((x*x + y * y) < R*R)
// Nincircle++;
// }
//
// double pi = Nincircle * 4.0 / Npoints;
// cout << pi << " val pi of rank " << rank << "\n";
// MPI_Gather(&pi, 1, MPI_DOUBLE, result.data(), 1, MPI_DOUBLE, 0, MPI_COMM_WORLD);
//
// if (rank == 0)
// {
// for_each(result.begin(), result.end(), [rank](const double x) {
// cout << x << " val pi of rank " << rank <<"\n"; });
// cout << accumulate(result.begin(), result.end(), 0.0) / result.size() << " final pi ";
// }
//task 29
//
//vector<int > forSort = {1,2,3,4,9,8,7,6,54,1};
//vector<int> receiver(forSort.size() / 2);
//vector<int> result(forSort.size());
//vector<int> resultOfResult;
//MPI_Scatter(forSort.data(), 5, MPI_INT, receiver.data(),
// 5, MPI_INT, 0, MPI_COMM_WORLD);
//
// for (int i = 0; i < receiver.size(); i++) {
// // (i % 2) ? 0 : 1 возвращает 1, если i четное, 0, если i не четное
// for (int j = (i % 2) ? 0 : 1; j < receiver.size() - 1; j += 2) {
// if (receiver[j] > receiver[j + 1]) {
// std::swap(receiver[j], receiver[j + 1]);
// }
// }
// }
// MPI_Gather(receiver.data(), 5, MPI_INT, result.data(), 5, MPI_INT, 0, MPI_COMM_WORLD);
// if (rank == 0) {
// for_each(result.begin(), result.end(), [rank](const double x) {
// cout << x << " val of rank " << rank << "\n"; });
//
// cout <<"here \n";
//
// int k = 0;
// int z = result.size() / 2;
// for (int i = 0; i < result.size(); i++)
// {
// if (result[k] < result[z])
// {
// resultOfResult.push_back(result[k]);
// k++;
// }
// else {
// resultOfResult.push_back(result[z]);
// z++;
// }
// }
// for_each(resultOfResult.begin(), resultOfResult.end(), [rank](const double x) {
// cout << x << " val of rank " << rank << "\n"; });
// }
//task 30 -n 2
//vector<int > rand_nums;
//rand_nums.push_back(4);
//rand_nums.push_back(6);
//rand_nums.push_back(6);
//rand_nums.push_back(12);
//
//vector<int > receiver(2,0);
//// Scatter the random numbers to all processes
//MPI_Scatter(rand_nums.data(), 2, MPI_INT, receiver.data(),
// 2, MPI_INT, 0, MPI_COMM_WORLD);
// double a, b, eps;
// double s1, s;
// int n = 1; //начальное число шагов
// //cout << "Введите левую границу интегрирования a = ";
// //cin >> a;
// a = receiver.at(0);
// //cout << "\nВведите правую границу интегрирования b = ";
// //cin >> b;
// b = receiver.at(1);
// //cout << "\nВведите требуемую точность eps = ";
// //cin >> eps;
// eps = 0.0001;
//
// cout <<a << " " << b << '\n' << rank << "rank \n";
// s1 = simpson_integral(f, a, b, n); //первое приближение для интеграла
// do {
// s = s1; //второе приближение
// n = 2 * n; //увеличение числа шагов в два раза,
// //т.е. уменьшение значения шага в два раза
// s1 = simpson_integral(f, a, b, n);
// } while (fabs(s1 - s) > eps); //сравнение приближений с заданной точностью
// cout << "\nintegral = " << s1 << " of rank " << rank << endl;
//
//
//
// double getdata;
// MPI_Reduce(&s1, &getdata, 1, MPI_DOUBLE, MPI_SUM, 0,
// MPI_COMM_WORLD);
//
// if (rank == 0) {
// cout << getdata << " sum result \n";
// }
//
MPI_Finalize();
}
// [](std::vector<int> &vec){
/* std::cout << "Hello World!\n"; */
// Запуск программы: CTRL+F5 или меню "Отладка" > "Запуск без отладки"
// Отладка программы: F5 или меню "Отладка" > "Запустить отладку"
// Советы по началу работы
// 1. В окне обозревателя решений можно добавлять файлы и управлять ими.
// 2. В окне Team Explorer можно подключиться к системе управления версиями.
// 3. В окне "Выходные данные" можно просматривать выходные данные сборки и другие сообщения.
// 4. В окне "Список ошибок" можно просматривать ошибки.
// 5. Последовательно выберите пункты меню "Проект" > "Добавить новый элемент", чтобы создать файлы кода, или "Проект" > "Добавить существующий элемент", чтобы добавить в проект существующие файлы кода.
// 6. Чтобы снова открыть этот проект позже, выберите пункты меню "Файл" > "Открыть" > "Проект" и выберите SLN-файл.
|
Markdown
|
UTF-8
| 3,105
| 2.765625
| 3
|
[
"MIT"
] |
permissive
|
# Tag 2: Wie entwickelt man Klassen?
# Was ist OOP?
## 7. Ein einfaches objektorientiertes Programm
### Aufgabe 7.1
* Führe das Programm `rect.cpp` aus.
* Klärt gemeinsam was der Quelltext tut.
### Aufgabe 7.2
Klärt gemeinsam folgende Begriffe:
* Klasse
* Instanz
* Objektinstanzierung
* Variablendefinition
* Eigenschaft
* Methode
### Aufgabe 7.3
* Welche Vor- und Nachteile hat objektorientierte Programmierung.
## Kapselung
### Aufgabe 1.1
Findet je ein Beispiel für folgende Begriffe:
* Prototyp
* Zuweisung
* Methodenaufruf
* Zugriff auf Eigenschaften
* Objektinstanzierung
* Kapselung (`public` vs. `private`)
### Aufgabe 1.2
Welche Methoden oder Eigenschaften der Klasse `Spiel` kannst Du als `private` deklarieren, ohne daß die Funktion des Programms beeinträchtigt wird?
### Aufgabe 1.3
Warum ist es sinnvoll, nicht einfach alle Elemente einer Klasse als `public` zu deklarieren?
## 2. Weitere C++ Sprachkonzepte
### Aufgabe 2.1
Lies Dir den Abschnitt zu Default-Parametern auf **cpp-tutor** durch. Erkläre das Konzept Deinen Teamkollegen.
### Aufgabe 2.2
Baue einen Default-Parameter in die Funktion `feld_fuellen` im Spiel ein.
### Aufgabe 2.3
Erkläre anhand des Programms `ampel.cpp` den Datentyp **enum**.
## 3. Konstruktoren
### Aufgabe 3.1
Lies Dir die ersten drei Abschnitte des Kapitels zu Konstruktoren bei cpp-tutor durch. Erkläre das Konzept Deinen Teamkollegen.
### Aufgabe 3.2
Schreibe einen Konstruktor für die `Spiel` Klasse, der die Fenstergröße, Fensterposition und Spielfeldgröße als Parameter annimmt.
## 4. Neue Klassen identifizieren
### Aufgabe 4.1
Führe eine **Lexikalische Analyse** durch: Formuliert einen kurzen Text über das geplante Spiel. Schickt den Text zu wordle.com um die häufigsten Wörter herauszubekommen. Diskutiert welche der Wörter sich als Namen von Klassen eignen.
### Aufgabe 4.2
Plane das Spiel in eine Klasse `Spieler` und eine Klasse `Level` zu zerlegen. Überlege im Voraus wofür die Klassen verantwortlich sein sollen.
### Aufgabe 4.3
Implementiere die Klasse `Level`. Schreibt die Klasse so, daß man über den Konstruktor verschiedene Level-Objekte mit unterschiedlichem Aussehen erzeugen kann.
### Aufgabe 4.4
Erstelle ein Level mit Wänden und Punkten als String, z.B.:
#######
#..#..#
##...##
#..#..#
#######
Tauscht die fertigen Levels im Team aus, so daß jeder 4-5 unterschiedliche Levels hat.
### Aufgabe 4.5
Implementiere die `Spieler`-Klasse.
Die Methoden der Spieler-Klasse müssen auf das Level zugreifen können.
### Aufgabe 4.6
Implementiere die *"Wände"*.
### Aufgabe 4.7
Implementiere die *"freßbaren Punkte"*
## 5. UML
### Aufgabe 5.1
Implementiere die Klasse `PunkteZaehler`, die über die gefressenen Punkte Buch führen soll.

### Aufgabe 5.2
Zeichne ein UML-Diagramm aller Klassen im Spiel.
## 6. Zufallslevels
**ZUSATZAUFGABE**
Betrachte die Datei `generate_maze.py`. Sie enthält den in Python geschriebenen Prototyp eines Level-Generators. Setze den Algorithmus in C++ um.
|
Java
|
UTF-8
| 1,689
| 2.84375
| 3
|
[] |
no_license
|
package com.cybertek.tests.day5_xPath;
import com.cybertek.utilities.WebDriverFactory;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
public class XpathLocator {
public static void main(String[] args) throws InterruptedException {
// Test case step1: Open web browser
WebDriver driver = WebDriverFactory.getDriver("CHROME");
// Test case step2: Navigate to the website(Link)
driver.get("http://practice.cybertekschool.com/multiple_buttons");
Thread.sleep(1000);
// Test case step5: Find and click button
WebElement xpathClickButton2 = driver.findElement(By.xpath("//button[@onclick = 'button2()']")); // it returns webElement
xpathClickButton2.click(); // click the "retrieve password" button
Thread.sleep(2000);
// Test case step5: Find and click button
WebElement xpathClickButton6 = driver.findElement(By.xpath("//button[@name = 'button6']")); // it returns webElement
xpathClickButton6.click(); // click the "retrieve password" button
Thread.sleep(2000);
// Test case step5: Find and click button
WebElement xpathClickButton1 = driver.findElement(By.xpath("//button[text()='Button 1']")); // it returns webElement
xpathClickButton1.click(); // click the "retrieve password" button
Thread.sleep(2000);
// Test case step5: Find and click button
WebElement xpathClickButton3 = driver.findElement(By.xpath("//button[starts-with(@id, 'button_')]")); // it returns webElement
xpathClickButton3.click(); // click the "retrieve password" button
}
}
|
Java
|
UTF-8
| 7,628
| 3.125
| 3
|
[] |
no_license
|
package sample;
import java.text.DecimalFormat;
import java.util.ArrayList;
public class Funktsioonid extends Main {
//Muutujad: stringid ja double-id (et ka komadega arvestaks)
String nimi;
Double neto = 0.0; //Algväärtus 0. Kui pole teada, siis saab sisestada 0 või tühjaks jätta. Muul juhul number.
Double bruto = 0.0; //Algväärtus 0. Kui pole teada, siis saab sisestada 0 või tühjaks jätta. Muul juhul number.
Double fondid = 0.0; //Igaühel eraldi palgafond
Double koguFond = 0.0; //Summaarne palgafond ettevõtjale
//Listid muutujate jaoks
/**@Author Marko Esna - näidis*/
ArrayList<String> nimed = new ArrayList<>();
ArrayList<Double> netod = new ArrayList<>();
ArrayList<Double> brutod = new ArrayList<>();
ArrayList<Double> palgafondid = new ArrayList<>();
/**
* Väärtuste listi lisamine.
* @param nimi String
* @param neto Double
* @param bruto Double
*/
public void lisaListi(String nimi, Double neto, Double bruto){
/**@Author Marko Esna - näidis*/
nimed.add(nimi); //Lisab uue inimese nime listi järgmisele kohale
netod.add(neto); //Lisab uue inimese netopalga listi järgmisele kohale
brutod.add(bruto); //Lisab uue inimese brutopalga listi järgmisele kohale
palgafondid.add(fondid); //Lisab uue inimese palgafondi listi järgmisele kohale
}
//Muudab nimed Camel Case'ile vastavaks (esimene täht igas sõnas suurtäht), nagu eesti keele reeglitele kohane.
/** @Author Java With Us
* http://www.javawithus.com/programs/converting-string-to-different-cases-upper-lower-toggle-camel-sentence-case
* @param inputString String
* @return toCamelCase String
**/
public static String toCamelCase(String inputString) {
String result = ""; //Loob muutuja
if (inputString.length() == 0) { //Kui sisendi pikkus on 0, siis jääb nii, nagu on
return result; //Väljastab tulemuse juhul, kui sisend on tühi
}
char firstChar = inputString.charAt(0); //Loob muutuja, mis võtab sisendi esimese märgi
char firstCharToUpperCase = Character.toUpperCase(firstChar); //Muudab esimese tähe suurtäheks
result = result + firstCharToUpperCase; //Lisab esitähe tulemusele
for (int i = 1; i < inputString.length(); i++) { //For tsükkel märkide 1 kuni i läbikäimiseks
char currentChar = inputString.charAt(i); // Määrab ära, milline märk on hetkel käsil
char previousChar = inputString.charAt(i - 1); //Määrab ära eelmise märgi
if (previousChar == ' ') { //If lause, "kui eelmine märk on tühik", siis ...
char currentCharToUpperCase = Character.toUpperCase(currentChar); //Praeguse märgi muudab suureks täheks
result = result + currentCharToUpperCase; //Tulemusele liidab suure märgi
} else {
char currentCharToLowerCase = Character.toLowerCase(currentChar); //Muul juhul muudab väikeseks märgiks
result = result + currentCharToLowerCase; //Liidetakse tähe tulemusele
}
}
return result; //Väljastab tulemuse
}
/**
* Netode, brutode ja palgafondide leidmine ning info väljaprintimine.
*/
public void fondiArvutused(){
DecimalFormat f = new DecimalFormat("##.00"); //Muudab 0,xxxxxxx... numbrid 0,xx-ks.
for (int i = 0; i < nimed.size(); i++) {
//For tsükli abil teeb kõik funktsiooni astmed läbi kõigi massiivi liikmetega lähtudes nimede massiivi liikmetest
String susi=nimed.get(i).replaceAll("[0-9\\+*/_<>=?!#%:\\.;,\\)\\(\\´\\{\\}\"¤&`@£$€§½]+", "");
//Eemaldab veidrad märgid nimedest, kui midagi on sinna sattunud
//Märkide []\| eemaldamisega on probleeme
nimed.set(i, toCamelCase(susi)); //Muudab nimed Camel Case tekstiks toCamelCase meetodi abil
if (brutod.get(i) > 0 && netod.get(i)==0) { //Kui netot ei tea, aga bruto on olemas, siis ...
fondid = brutod.get(i)*(1.384); //Arvutab brutost palgafondi
neto = brutod.get(i)/1.2; //Arvutab brutost neto
//33%=sotsmaksud, 1,8% töötuskindlustusmaks ettevõttele, 1,6% töötuskindlustusmaks töötajale, 2% 2. pensionisammas
//33+1,8+1,6+2=38,4% -> 1,384
netod.set(i, neto); //Viib uue neto õigele kohale netode massiivi
palgafondid.set(i, fondid); //Viib saadud palgafondi õigesse kohta palgafondi massiivi
System.out.println( nimed.get(i) + " neto: " + f.format(netod.get(i)) + " bruto: " + f.format(brutod.get(i))+ ", palgafond: " + f.format(palgafondid.get(i)));
//Trükib kõik andmed välja ühes reas üksteise järel täpsusega kaks kohta pärast koma.
}
else if (brutod.get(i) == 0 && netod.get(i) > 0){ //Kui brutot ei tea, aga neto on olemas, siis ...
fondid = netod.get(i)*1.2*(1.384); //Arvutab netost palgafondi
//33%=sotsmaksud, 1,8% töötuskindlustusmaks ettevõttele, 1,6% töötuskindlustusmaks töötajale, 2% 2. pensionisammas, 20% tulumaksu
bruto = netod.get(i)*1.2; //Arvutab netost bruto
brutod.set(i, bruto); //Viib uue bruto õigele kohale brutode massiivi
palgafondid.set(i, fondid); //Viib saadud palgafondi õigesse kohta palgafondi massiivi
System.out.println( nimed.get(i) + " neto: " + f.format(netod.get(i)) + " bruto: " + f.format(brutod.get(i))+ ", palgafond: " + f.format(palgafondid.get(i)));
//Trükib kõik andmed välja ühes reas üksteise järel täpsusega kaks kohta pärast koma.
}
else {System.out.println("Vigane rida: neto = " + netod.get(i) + ", bruto = "+ brutod.get(i) + ".");}
//Kui ei teata ei netot ega brutot või on sisestatud arv väiksem nullist, siis trükib selle rea täpsusega kaks kohta pärast koma
if (brutod.get(i) >=0 && (netod.get(i)) >=0 ){ //Kui vaadeldavad brutod ja netod on nullist suuremad, siis ...
System.out.println("Palgafond kasutajal " + nimed.get(i)+ " on " + f.format(palgafondid.get(i)) + " eurot.");
//Trükib sellise teksti täpsusega kaks kohta pärast koma
koguFond = koguFond + palgafondid.get(i); //Liidab saadud palgafondi kogufondile juurde
System.out.println("Aastane palgafond kasutajal " + nimed.get(i)+ " on " + f.format(palgafondid.get(i)*12) + " eurot.");
//Leiab aastafondi ja trükib välja
}
else continue; //Muul juhul jätab rea vahele ja liigub järgmise juurde
}
}
/**
* Numbrite ümardamine ja tekstide välja trükkimine.
*/
public void lopp() {
DecimalFormat f = new DecimalFormat("##0.00"); //Muudab 0,xxxxxxx... kujul numbrid 0,xx-ks.
System.out.println("Kogu palgafond kuus on " + f.format(koguFond) + " eurot.");
//Trükib ettevõtte kogu ühe kuu palgafondi
System.out.println("[Nimi, neto, bruto, palgafond]"); //Trükib tabeli esimese rea
for (int i = 0; i < nimed.size(); i++){ //For tsükli abil trükib ekraanile andmed nimede massiivi järjekorra alusel
System.out.println("[" + nimed.get(i) + "; " + f.format(netod.get(i)) + "; " + f.format(brutod.get(i)) + "; "+ f.format(palgafondid.get(i)) + " ]");
//Trükib igast massiivist sama järjekorranumbriga andmed üksteise all tabelisse
}
}
}
|
Markdown
|
UTF-8
| 847
| 2.578125
| 3
|
[
"BSD-3-Clause"
] |
permissive
|
# Server Integrations
These guides will cover how to integrate Panel applications with various external frameworks such as Django, FastAPI and Flask.
::::{grid} 1 3 3 3
:gutter: 1 1 1 2
:::{grid-item-card} Flask
:link: flask
:link-type: doc
Discover to run Panel applications alongside an existing Flask server.

:::
:::{grid-item-card} FastAPI
:link: FastAPI
:link-type: doc
Discover to run Panel applications alongside an existing FastAPI server.

:::
:::{grid-item-card} Django
:link: Django
:link-type: doc
Discover to run Panel applications on a Django server (replacing the standard Tornado based server).

:::
::::
```{toctree}
:titlesonly:
:hidden:
:maxdepth: 2
flask
FastAPI
Django
```
|
Java
|
UTF-8
| 264
| 2.265625
| 2
|
[] |
no_license
|
package com.yytxdy.fim.sso.exceptions;
import com.yytxdy.fim.sso.utils.ErrorCodes;
public class DuplicatedSMSException extends BaseException {
public DuplicatedSMSException() {
super(ErrorCodes.DUPLICATED_SMS, "请勿重复发送验证码");
}
}
|
JavaScript
|
UTF-8
| 858
| 2.84375
| 3
|
[
"MIT"
] |
permissive
|
/**
* Spreadsheets の TextFinder 機能を試すためのコンテナバインドスクリプト
*
* @vesion 1.0
* @author Kenji.Nakahara
* @date: 2019/04/15
* @update: 2019/04/15
* @include libraries:
*/
function findAll(){
var spread = SpreadsheetApp.getActiveSpreadsheet() ;
var sheet = spread.getSheets()[0] ;
var textFinder = sheet.createTextFinder('日本料理');
var ranges = textFinder.findAll();
Logger.log('ranges.length = ' + ranges.length) ;
for ( var i = 0; i < ranges.length; i++ ) {
Logger.log('A1Notation = ' + ranges[i].getA1Notation()) ;
}
}
function replaceAllWith(){
var spread = SpreadsheetApp.getActiveSpreadsheet() ;
var sheet = spread.getSheets()[0] ;
var textFinder = sheet.createTextFinder('日本料理');
var result = textFinder.replaceAllWith('ねこぽん');
Logger.log('result = ' + result) ;
}
|
C++
|
UTF-8
| 611
| 3.25
| 3
|
[] |
no_license
|
#include <iostream>
#include <string>
#include <cmath>
using namespace std;
class Solution {
public:
int reverse(int x) {
int ne = x < 0 ? -1 : 1;
int absx = ne * x;
long re = 0;
while(absx > 0){
re = re * 10 + absx % 10;
absx /= 10;
}
if( ne > 0 && re > 2147483647L){
return 0;
}else if(ne < 0 && re > 2147483648L){
return 0;
}else
return ne * re;
}
};
int main(){
int a = 123456;
cout << Solution().reverse(a)<<endl;
int b = -2147483648;
cout << Solution().reverse(b)<<endl;
int c = -1234563456;
cout << Solution().reverse(c)<<endl;
}
|
TypeScript
|
UTF-8
| 378
| 3.015625
| 3
|
[] |
no_license
|
import { ShapeBuilder } from "./types";
export class CoreShapeBuilder implements ShapeBuilder {
public createLine(start: Point, length: Length, angle: Angle = 0): Line {
const radians = (angle * Math.PI) / 180;
const end: Point = {
x: start.x + length * Math.sin(radians),
y: start.y - length * Math.cos(radians),
};
return { start, end };
}
}
|
Java
|
UTF-8
| 448
| 1.679688
| 2
|
[] |
no_license
|
import play.*;
import play.jobs.*;
import play.test.*;
import models.*;
@OnApplicationStart
public class Bootstrap extends Job {
public void doJob() {
// Check if the database is empty
if(User.count() == 0) {
try
{
//Fixtures.loadModels("initial-data.yml");
}
catch (Exception e)
{
/* Do Nothing */
}
}
}
}
|
Python
|
UTF-8
| 1,117
| 3.078125
| 3
|
[] |
no_license
|
import copy
class Solution():
def countSmaller(self, nums):
# l = len(nums)
# v = copy.deepcopy(nums)
# v.sort()
# bit = [0] * (l + 1)
# print(v)
# m = dict()
# res = 0
# for i in range(l):
# m[nums[i]] = i
# for j in range(l - 1, -1, -1):
# pass
def lower_bound(arr, target):
low, high = 0, len(arr) - 1
pos = len(arr)
while low < high:
mid = (low+high)/2
if arr[mid] <= target:
low = mid+1
else:
high = mid
#pos = high
if arr[low]>=target:
pos = low
return pos
print(lower_bound([1,2,3,4], 2))
def update(self, i, j, bit):
while i < len(bit):
bit[i] += j
i += (i & -i)
def search(self, i, bit):
total = 0
while i > 0:
total += bit[i]
i -= (i & -i)
return total
s = Solution()
s.countSmaller([5,2,6,1])
|
Java
|
UTF-8
| 2,062
| 2.765625
| 3
|
[
"Apache-2.0"
] |
permissive
|
package com.unsupervisedsentiment.analysis.classification;
import java.util.ArrayList;
import java.util.Set;
import com.unsupervisedsentiment.analysis.model.SeedScoreModel;
import com.unsupervisedsentiment.analysis.model.Tuple;
public class PolarityAssigner {
/**
* Necessary because for some reason changes in a Set<E> do not persist!
*
* @param data
* @return
*/
public static ArrayList<Tuple> initTupleArrayList(final Set<Tuple> data) {
ArrayList<Tuple> tuples = new ArrayList<Tuple>();
for (Tuple tuple : data) {
if (tuple != null) {
if (tuple.getSource() != null)
tuple.getSource().setScore(Classification.DEFAULT_SCORE);
if (tuple.getTarget() != null)
tuple.getTarget().setScore(Classification.DEFAULT_SCORE);
tuples.add(tuple);
}
}
return tuples;
}
public static ArrayList<Tuple> assignScoresToSeeds(ArrayList<Tuple> tuples, ArrayList<SeedScoreModel> seeds) {
for (Tuple tuple : tuples) {
for (SeedScoreModel model : seeds) {
String seed = model.getSeed().trim();
String source = tuple.getSource().getValue();
if (tuple.getTarget() != null) {
String target = tuple.getTarget().getValue();
if (seed.equals(source.trim()) || seed.equals(target.trim())) {
double score = model.getScore();
tuple.getSource().setScore(score);
tuple.getTarget().setScore(score);
}
}
}
}
return tuples;
}
public static ArrayList<Tuple> assignScores(ArrayList<Tuple> data, ArrayList<SeedScoreModel> seeds) {
for (Tuple tuple : data) {
if (isSeed(seeds, tuple.getSource().getValue()) || (tuple.getTarget() != null)
&& isSeed(seeds, tuple.getTarget().getValue())) {
if (tuple.getSource().getScore() != Classification.DEFAULT_SCORE) {
ScorePropagator.propagateScore(data, tuple);
}
}
}
return data;
}
private static boolean isSeed(ArrayList<SeedScoreModel> seeds, String word) {
for (SeedScoreModel model : seeds) {
if (model.getSeed().toLowerCase().equals(word.toLowerCase()))
return true;
}
return false;
}
}
|
PHP
|
UTF-8
| 939
| 2.6875
| 3
|
[] |
no_license
|
<?php
include 'check.php';
include('../crud/class/mysql_crud.php');
include '../functions.php';
/*
* Output
*/
$db = new Database();
$db->connect();
$db->select('customers');
$customers = $db->getResult();
$aColumns = array('id', 'name', 'email', 'country', 'phone');
$output = array(
"aaData" => array()
);
$m = 1;
if ($db->numResults == 1)
$customers = array($customers);
foreach ($customers as $customer)
{
$row = array();
for ($i = 0; $i < count($aColumns); $i++)
{
switch ($aColumns[$i])
{
case 'name':
$row[] = $customer['first_name'] . ' ' . $customer['last_name'];
break;
case 'id':
$row[] = $m;
$m++;
break;
default :
$row[] = $customer[$aColumns[$i]];
break;
}
}
$output['aaData'][] = $row;
}
echo json_encode($output);
?>
|
C#
|
UTF-8
| 1,743
| 3.15625
| 3
|
[] |
no_license
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DataAccess
{
public interface IUnitOfWork : IDisposable
{
/// <summary>
/// Push the changes being tracked by the DbContext to the database.
/// </summary>
void Save();
/// <summary>
/// Check to see if any of the models being tracked by the DbContext have validation errors
/// based on the validation attributes that are decorating the class and properties
/// </summary>
/// <returns>True if there are validation errors. False otherwise</returns>
bool HasValidationErrors();
/// <summary>
/// Get the repository that maps to the type
/// </summary>
/// <typeparam name="T"></typeparam>
/// <returns>The repository that handles this entity</returns>
IRepository<T> GetRepository<T>() where T : class;
/// <summary>
/// Executes the passed TSQL command or sproc and returns the results.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="commandText">The command text.</param>
/// <param name="args">The parameters.</param>
/// <returns></returns>
IEnumerable<T> SqlQuery<T>(string query, params object[] args);
/// <summary>
/// Executes the passed TSQL command with no result set.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="commandText">The command text.</param>
/// <param name="args">The parameters.</param>
/// <returns></returns>
void SqlCommand(string command, params object[] args);
}
}
|
Java
|
UTF-8
| 795
| 2.484375
| 2
|
[] |
no_license
|
package shoppingcart;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import shoppingcart.model.Event;
import shoppingcart.model.EventType;
import javax.persistence.Entity;
import javax.persistence.Table;
import java.time.LocalDate;
@AllArgsConstructor
@NoArgsConstructor
@Data
public class EventDto {
private int eventId;
private EventType eventType;
private int amount;
private int category;
private LocalDate date;
private String description;
public static Event convertDtoToEntity(EventDto dto){
Event event = new Event();
event.setEventId(dto.getEventId());
event.setEventType(dto.getEventType());
event.setAmount(dto.getAmount());
return event;
}
}
|
Markdown
|
UTF-8
| 1,912
| 3.0625
| 3
|
[] |
no_license
|
# Frontend Mentor - Social media dashboard with theme switcher solution
This is a solution to the [Social media dashboard with theme switcher challenge on Frontend Mentor](https://www.frontendmentor.io/challenges/social-media-dashboard-with-theme-switcher-6oY8ozp_H). Frontend Mentor challenges help you improve your coding skills by building realistic projects.
## Table of contents
- [Overview](#overview)
- [The challenge](#the-challenge)
- [Screenshot](#screenshot)
- [Links](#links)
- [My process](#my-process)
- [Built with](#built-with)
- [What I learned](#what-i-learned)
- [Continued development](#continued-development)
- [Useful resources](#useful-resources)
- [Author](#author)
## Overview
### Screenshot
Dark theme

Light theme

### Links
- Live Site URL: [Social-Dashboard](https://adamskys.github.io/socialdashboard-mentor/)
## My process
### Built with
- Semantic HTML5 markup
- CSS custom properties
- Flexbox
- CSS Grid
- SASS
- JavaScript
### What I learned
Working with Grid, adding minor JS functionalities and switcher with Flexbox. It helped me understand Grid more, however there is still much to do.
Also I added localstorage, to save chosen theme.
### Continued development
I had issues with adding transition on flexbox switcher, so I need to find out how to do that. Also I am not sure if transition on body is a good way, to make theme changing smooth.
### Useful resources
- [CSS Grid](https://css-tricks.com/snippets/css/complete-guide-grid/) - Great Grid guide.
- [Border gradient](https://dev.to/rumansaleem/gradient-borders-with-css-3mnk) - Trick to make gradient border with radius.
- [Flexbox Switcher](https://www.cssscript.com/ios-toggle-switch-flexbox/) - Guide to make Flexbox switcher.
## Author
- Frontend Mentor - [@adamskys](https://www.frontendmentor.io/profile/adamskys)
|
Markdown
|
UTF-8
| 459
| 2.640625
| 3
|
[] |
no_license
|
# Make Your Move: Image Recognition using Neural Networks
Combined computer vision techniques and convolutional neural networks to accurately classify chess pieces and identified their location on a chessboard. Tools: Python, Google Cloud, Keras, TensorFlow, OpenCV, Pillow, Scikit-learn, NumPy, Seaborn, and others
Project Published on TowardDataScience.com:
https://towardsdatascience.com/board-game-image-recognition-using-neural-networks-116fc876dafa
|
TypeScript
|
UTF-8
| 953
| 2.875
| 3
|
[] |
no_license
|
import { Highlight } from './highlight.pipe';
describe('Highlight Pipe', () => {
let pipe: Highlight;
beforeEach(() => (pipe = new Highlight()));
it('should find a matching text', () => {
const highlight = pipe.transform('Buy', 'Buy');
expect(highlight).toBe('<mark>Buy</mark>');
});
it('should only highlight the found text', () => {
const highlight = pipe.transform('Buy Milk', 'Buy');
expect(highlight).toBe('<mark>Buy</mark> Milk');
});
it('should be case insensitive', () => {
const highlight = pipe.transform('buy Milk', 'Buy');
expect(highlight).toBe('<mark>buy</mark> Milk');
});
it('should pass through if value is not given', () => {
const highlight = pipe.transform(null, 'Buy');
expect(highlight).toBeNull();
});
it('should pass through if query is not given', () => {
const highlight = pipe.transform('Buy milk', null);
expect(highlight).toBe('Buy milk');
});
});
|
Java
|
UTF-8
| 12,277
| 1.867188
| 2
|
[] |
no_license
|
package com.pixeldifusiones.redciudadana;
import android.app.DatePickerDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.PorterDuff;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.v4.app.Fragment;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.ActionBar;
import android.support.v7.widget.AppCompatCheckBox;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.TimePicker;
import android.widget.Toast;
import com.pixeldifusiones.redciudadana.controllers.AccountController;
import com.pixeldifusiones.redciudadana.custom_views.DatePickerFragment;
import com.pixeldifusiones.redciudadana.custom_views.IntervalTimePickerDialog;
import com.pixeldifusiones.redciudadana.custom_views.LoadingFragmentDialog;
import com.pixeldifusiones.redciudadana.services.SendLocationService;
import com.pixeldifusiones.redciudadana.utils.Commons;
import com.pixeldifusiones.redciudadana.utils.PermissionsUtil;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Locale;
public class ToBeVolunteerFragment extends Fragment implements View.OnClickListener {
public static final String TAG = "ToBeVolunteerFragment";
int mStartTime = -1;
int mEndTime = -1;
private AppCompatCheckBox mCheckboxFainting;
private AppCompatCheckBox mCheckboxHeartAttack;
private AppCompatCheckBox mCheckboxInjuredAccident;
private AppCompatCheckBox mCheckboxOther;
private AppCompatCheckBox mCheckboxPanic;
private TextView mTextViewLastRCPTrainingDate;
private TextView mTextViewAvailableStartTime;
private TextView mTextViewAvailableEndTime;
private AccountController mAccountController;
private SeekBar mSeekBarMaxDistance;
public ToBeVolunteerFragment() {
// Required empty public constructor
}
public static ToBeVolunteerFragment newInstance() {
ToBeVolunteerFragment fragment = new ToBeVolunteerFragment();
Bundle args = new Bundle();
fragment.setArguments(args);
return fragment;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
}
mAccountController = AccountController.getInstance(getContext());
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_to_be_volunteer, container, false);
BaseActivity baseActivity = (BaseActivity) getActivity();
ActionBar actionBar = baseActivity.getBaseActivityActionBar();
if (actionBar != null) {
baseActivity.setActionBarTitle(getString(R.string.information));
actionBar.setDisplayHomeAsUpEnabled(true);
}
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(getContext());
mCheckboxFainting = (AppCompatCheckBox) view.findViewById(R.id.checkBoxFainting);
mCheckboxFainting.setChecked(sp.getBoolean(Commons.SHARED_PREFERENCE_EMERGENCY_FAINT, false));
mCheckboxHeartAttack = (AppCompatCheckBox) view.findViewById(R.id.checkBoxHeartAttack);
mCheckboxHeartAttack.setChecked(sp.getBoolean(Commons.SHARED_PREFERENCE_EMERGENCY_HEART_ATTACK, false));
mCheckboxInjuredAccident = (AppCompatCheckBox) view.findViewById(R.id.checkBoxInjuredAccident);
mCheckboxInjuredAccident.setChecked(sp.getBoolean(Commons.SHARED_PREFERENCE_EMERGENCY_WOUND, false));
mCheckboxOther = (AppCompatCheckBox) view.findViewById(R.id.checkBoxOther);
mCheckboxOther.setChecked(sp.getBoolean(Commons.SHARED_PREFERENCE_EMERGENCY_OTHER, false));
mCheckboxPanic = (AppCompatCheckBox) view.findViewById(R.id.checkBoxPanic);
mCheckboxPanic.setChecked(sp.getBoolean(Commons.SHARED_PREFERENCE_EMERGENCY_PANIC, false));
mTextViewLastRCPTrainingDate = (TextView) view.findViewById(R.id.textViewLastRCPTrainingDate);
mTextViewLastRCPTrainingDate.setOnClickListener(this);
mTextViewAvailableStartTime = (TextView) view.findViewById(R.id.textViewAvailableStartTime);
mTextViewAvailableStartTime.setOnClickListener(this);
mStartTime = sp.getInt(Commons.SHARED_PREFERENCE_AVAILABLE_TIME_START, -1);
mTextViewAvailableStartTime.setText((mStartTime == -1) ? getResources().getString(R.string.insert_date) : (mStartTime / 100) + ":" + (mStartTime % 100) + "hs");
mTextViewAvailableEndTime = (TextView) view.findViewById(R.id.textViewAvailableEndTime);
mTextViewAvailableEndTime.setOnClickListener(this);
mEndTime = sp.getInt(Commons.SHARED_PREFERENCE_AVAILABLE_TIME_END, -1);
mTextViewAvailableEndTime.setText((mEndTime == -1) ? getResources().getString(R.string.insert_date) : (mEndTime / 100) + ":" + (mEndTime % 100) + "hs");
final TextView textViewMaxDistance = (TextView) view.findViewById(R.id.textViewMaxDistanceKm);
textViewMaxDistance.setText(String.format(
Locale.getDefault(),
"%.1f %s",
sp.getInt(Commons.SHARED_PREFERENCE_EMERGENCY_RADIO, 2) / 1000f,
getResources().getString(R.string.km))
);
mSeekBarMaxDistance = (SeekBar) view.findViewById(R.id.seekBar);
mSeekBarMaxDistance.getProgressDrawable().setColorFilter(ContextCompat.getColor(
getContext(), R.color.yellow), android.graphics.PorterDuff.Mode.SRC_IN);
mSeekBarMaxDistance.setProgress(sp.getInt(Commons.SHARED_PREFERENCE_EMERGENCY_RADIO, 20) / 100);
mSeekBarMaxDistance.getThumb().setColorFilter(ContextCompat.getColor(getContext(), R.color.yellow), PorterDuff.Mode.MULTIPLY);
mSeekBarMaxDistance.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
@Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
textViewMaxDistance.setText(String.format(Locale.getDefault(), "%.1f %s", progress / 10f, getResources().getString(R.string.km)));
}
@Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
@Override
public void onStopTrackingTouch(SeekBar seekBar) {
}
});
Button buttonSave = (Button) view.findViewById(R.id.buttonSave);
buttonSave.setOnClickListener(this);
buttonSave.setText(
(sp.getBoolean(Commons.SHARED_PREFERENCE_IS_VOLUNTEER, false))
? getResources().getString(R.string.update)
: getResources().getString(R.string.save)
);
return view;
}
@Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.textViewLastRCPTrainingDate: {
DatePickerFragment datePickerFragment = DatePickerFragment.newInstance();
datePickerFragment.setOnDateSetListener(new DatePickerDialog.OnDateSetListener() {
@Override
public void onDateSet(DatePicker datePicker, int year, int month, int day) {
Calendar calendar = Calendar.getInstance();
calendar.set(year, month, day);
SimpleDateFormat format = new SimpleDateFormat("dd/MM/yyyy", Locale.getDefault());
mTextViewLastRCPTrainingDate.setText(format.format(calendar.getTime()));
}
});
datePickerFragment.show(getFragmentManager(), "Date Picker");
}
case R.id.textViewAvailableStartTime: {
int hour = mStartTime / 100;
int minute = mStartTime % 100;
IntervalTimePickerDialog mTimePicker;
mTimePicker = new IntervalTimePickerDialog(getContext(), new IntervalTimePickerDialog.OnTimeSetListener() {
@Override
public void onTimeSet(TimePicker timePicker, int selectedHour, int selectedMinute) {
mTextViewAvailableStartTime.setText(selectedHour + ":" + selectedMinute + "hs");
mStartTime = selectedHour * 100 + selectedMinute;
}
}, hour, minute, true);//Yes 24 hour time
mTimePicker.setTitle("Select Time");
mTimePicker.show();
break;
}
case R.id.textViewAvailableEndTime: {
int hour = mEndTime / 100;
int minute = mEndTime % 100;
IntervalTimePickerDialog mTimePicker;
mTimePicker = new IntervalTimePickerDialog(getContext(), new IntervalTimePickerDialog.OnTimeSetListener() {
@Override
public void onTimeSet(TimePicker timePicker, int selectedHour, int selectedMinute) {
mTextViewAvailableEndTime.setText(selectedHour + ":" + selectedMinute + "hs");
mEndTime = selectedHour * 100 + selectedMinute;
}
}, hour, minute, true);//Yes 24 hour time
mTimePicker.setTitle("Select Time");
mTimePicker.show();
break;
}
case R.id.buttonSave: {
if (mStartTime != -1 && mEndTime != -1) {
mAccountController.setIsVolunteer(
mCheckboxOther.isChecked(),
mCheckboxFainting.isChecked(),
mCheckboxHeartAttack.isChecked(),
mCheckboxInjuredAccident.isChecked(),
mCheckboxPanic.isChecked(),
mSeekBarMaxDistance.getProgress() * 100, //we send distance in meters -> we need to map progress value to meters
mStartTime,
mEndTime);
} else {
Toast.makeText(getContext(), R.string.ingrese_rango_emergencia, Toast.LENGTH_LONG).show();
}
break;
}
}
}
@Override
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
switch (requestCode) {
case PermissionsUtil.PERMISSION_LOCATION: {
// If request is cancelled, the result arrays are empty.
if (PermissionsUtil.hasGrantedPermission(grantResults)) {
getActivity().startService(new Intent(getContext(), SendLocationService.class));
}
}
}
}
// Called in the same thread (default)
public void onEvent(Integer eventMessage) {
switch (eventMessage) {
case Commons.IS_VOLUNTEER_START: {
(new LoadingFragmentDialog()).show(getFragmentManager(), LoadingFragmentDialog.TAG);
break;
}
case Commons.IS_VOLUNTEER_FINISH: {
((LoadingFragmentDialog) getFragmentManager().findFragmentByTag(LoadingFragmentDialog.TAG)).dismiss();
Toast.makeText(getContext(), R.string.ahora_eres_voluntario, Toast.LENGTH_LONG).show();
getActivity().onBackPressed();
break;
}
case Commons.IS_VOLUNTEER_ERROR: {
((LoadingFragmentDialog) getFragmentManager().findFragmentByTag(LoadingFragmentDialog.TAG)).dismiss();
Toast.makeText(getContext(), R.string.error_registro_voluntario, Toast.LENGTH_LONG).show();
break;
}
}
}
@Override
public void onResume() {
super.onResume();
mAccountController.registerForEvents(this);
}
@Override
public void onPause() {
super.onPause();
mAccountController.unregisterForEvents(this);
}
}
|
Ruby
|
UTF-8
| 574
| 2.875
| 3
|
[] |
no_license
|
#!/usr/bin/ruby
require_relative 'advent21'
require 'test/unit'
class TestAdvent21 < Test::Unit::TestCase
TestData1_1 = <<EOF
mxmxvkd kfcds sqjhc nhms (contains dairy, fish)
trh fvjkl sbzzf mxmxvkd (contains dairy)
sqjhc fvjkl (contains soy)
sqjhc mxmxvkd sbzzf (contains fish)
EOF
def setup
@test1_1 = [TestData1_1, 5]
@test2_1 = [TestData1_1, 'mxmxvkd,sqjhc,fvjkl']
end
def test_part1
assert_equal(@test1_1[1], Advent21.new(@test1_1[0]).part1)
end
def test_part2
assert_equal(@test2_1[1], Advent21.new(@test2_1[0]).part2)
end
end
|
PHP
|
UTF-8
| 765
| 2.5625
| 3
|
[
"MIT"
] |
permissive
|
<?php
namespace App;
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Laravel\Passport\HasApiTokens;
use Illuminate\Support\Facades\Hash;
class User extends Authenticatable
{
use Notifiable, HasApiTokens;
protected $fillable = [
'name', 'email', 'password',
];
protected $hidden = [
'password', 'remember_token',
];
public static function exists($email, $password)
{
$user = User::whereEmail($email)->first();
if ( !$user ) return null;
if ( Hash::check($password, $user->password) ) {
return $user;
} else return null;
}
public function loja() {
return $this->hasOne(Loja::class);
}
}
|
PHP
|
UTF-8
| 839
| 2.703125
| 3
|
[] |
no_license
|
<?php
try{
$bdd = new PDO('mysql:host=localhost;dbname=JEU;charset=utf8', 'jeremydata', 'b302937ba5');
} catch(Exception $e) {
die('Erreur : '.$e->getMessage());
}
?>
<?php
session_start();
$id = $_SESSION['id'];
var_dump($id);
$pass = $_POST['new_pass'];
$pass2 = $_POST['new_pass2'];
if (empty($pass || $pass2)){
echo 'Les champs sont vides';
header("Refresh:0;URL=moncompte.php");
}
elseif ($pass == $pass2) {
$hashedPassword = password_hash($pass, PASSWORD_ARGON2I);
$req=$bdd->prepare('UPDATE users SET password = :password WHERE id = :id');
$req->bindParam(':id', $id);
$req->bindParam(':password', $hashedPassword);
echo 'Mot de passe changé avec succès';
header("Refresh:0;URL=moncompte.php");
}
else {
echo 'Les mots de passe sont différents';
header("Refresh:0;URL=moncompte.php");
}
?>
|
Python
|
UTF-8
| 1,764
| 2.5625
| 3
|
[] |
no_license
|
import unittest
import thefs
from the import *
the.use(thefs)
class TestTheFs(unittest.TestCase):
def setUp(self):
self.r = self.assertRaises
self.true = self.assertTrue
def test_basename(self):
self.true(expect("/a/b/c.md").to.have.basename("c.md"))
with self.r(AssertionError):
self.true(expect("/a/b/c.md").to.have.basename("what"))
def test_dirname(self):
self.true(expect("/a/b/c.md").to.have.dirname("/a/b"))
with self.r(AssertionError):
self.true(expect("/a/b/c.md").to.have.dirname("/a/b/"))
def test_extname(self):
self.true(expect("/a/b/c.md").to.have.extname(".md"))
with self.r(AssertionError):
self.true(expect("/a/b/c.md").to.have.extname("md"))
def test_path(self):
self.true(expect(".").to.be.path)
with self.r(AssertionError):
expect(".....s...soooooooooooooo").to.be.path
def test_file(self):
self.true(expect("./test.py").to.be.a.file)
with self.r(AssertionError):
expect(".").to.be.a.file
def test_dir(self):
self.true(expect(".").to.be.a.dir)
with self.r(AssertionError):
expect("./readme.md").to.be.a.dir
def test_absolute_path(self):
self.true(expect("/tmp/readme.md").to.be.an.absolute_path)
with self.r(AssertionError):
expect("./readme.md").to.be.an.absolute_path
def test_readable(self):
self.true(expect("./test.py").to.be.readable)
with self.r(AssertionError):
expect("/a/b/c.md").to.be.readable
def test_mount(self): pass
def test_writable(self): pass
def test_executable(self): pass
if __name__ == '__main__':
unittest.main()
|
Java
|
UTF-8
| 895
| 2.40625
| 2
|
[] |
no_license
|
package bit.dail3.easyandroidanimationsdemo;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;
import com.easyandroidanimations.library.ExplodeAnimation;
public class MainActivity extends AppCompatActivity {
private ImageView imageView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
imageView = (ImageView) findViewById(R.id.imageView);
imageView.setOnClickListener(new ExplodeImageWhenTouchIt());
}
class ExplodeImageWhenTouchIt implements View.OnClickListener {
@Override
public void onClick(View v) {
ExplodeAnimation explodeAnimation = new ExplodeAnimation(imageView);
explodeAnimation.animate();
}
}
}
|
JavaScript
|
UTF-8
| 5,146
| 3.4375
| 3
|
[] |
no_license
|
import React from "react";
import {
Button,
SafeAreaView,
Text,
TouchableHighlight,
View
} from "react-native";
const newGameState = {
squares: Array(9).fill(null), //create an array of length 9 with null in it
xIsNext: true
};
export default class App extends React.Component {
//must call constructor with props and set a state
constructor(props) {
super(props);
this.state = newGameState;
}
whoseTurn() {
return this.state.xIsNext ? "X" : "O";
}
onNewGame() {
this.setState(newGameState);
}
onMove(i) {
let newSquares = this.state.squares.slice(); //returns new array copy
const turn = this.whoseTurn(); // figures out if it is X's turn or O's turn.
//if we have the current square already filled, or if we are in a state of win, then return null
if (this.state.squares[i] || winner(this.state.squares)) return null;
newSquares[i] = turn; //set the value of the square to be the current player's turn mark, either X or O
//call the setState function to update the updated Square matrix, and the turn switch
this.setState({
squares: newSquares,
xIsNext: !this.state.xIsNext
});
}
//every class has a render function, to render the component
render() {
//create a style for the background
const style = {
backgroundColor: "beige",
flex: 1,
alignItems: "center"
};
return (
//we are going to return SafeAreaView just so that the tiles are not printed in unaccesible locations
//use the board component we made, with the squares prop and onmove prop (function that executes the onMove(i))
//use the status, that takes in turn, winner, onNewGameProp, all of which just call functions
<SafeAreaView style={style}>
<Board squares={this.state.squares} onMove={i => this.onMove(i)} />
<Status
turn={this.whoseTurn()}
winner={winner(this.state.squares)}
onNewGame={() => this.onNewGame()}
/>
</SafeAreaView>
);
}
}
//create a functional component Board that takes in an object with parameters squares and onMove.
//create a centered view, with rows that start at different indices of the squares
//pass the squares, into the Row component and the onMove function as well.
const Board = ({ squares, onMove }) => {
return (
<View style={{ flex: 1, justifyContent: "center" }}>
<Row squares={squares} startIndex={0} onMove={onMove} />
<Row squares={squares} startIndex={3} onMove={onMove} />
<Row squares={squares} startIndex={6} onMove={onMove} />
</View>
);
};
//create a functional component Row, that takes in the squares, the startindex, and onmove
//create a row view, that has three Square components, that have the label of the startIndex, startIndex + 1, startIndex + 2
const Row = ({ squares, startIndex, onMove }) => {
return (
<View style={{ flexDirection: "row" }}>
<Square label={squares[startIndex]} onPress={() => onMove(startIndex)} />
<Square
label={squares[startIndex + 1]}
onPress={() => onMove(startIndex + 1)}
/>
<Square
label={squares[startIndex + 2]}
onPress={() => onMove(startIndex + 2)}
/>
</View>
);
};
//make the Square functional component that takes in the label and the onPress function
const Square = ({ label, onPress }) => {
//make some basic styles for the Square, that we will use for the TouchableHighlight, Text
const style = {
width: 100,
height: 100,
borderColor: "black",
borderWidth: 1,
justifyContent: "center"
};
const textStyle = {
textAlign: "center",
fontSize: 36,
fontWeight: "bold"
};
//send in the onPress function that we pass in
return (
<TouchableHighlight style={style} onPress={onPress}>
<Text style={textStyle}>{label}</Text>
</TouchableHighlight>
);
};
//create a Status functional component that takes in a turn, winner and, onNewGame function
const Status = ({ turn, winner, onNewGame }) => {
//make the text that shows the status
const text =
winner === null
? "Tie game :-/"
: winner !== undefined
? winner + " wins!"
: turn + "'s turn";
//send a view with the text, and a button that starts the onNewGame function
return (
<View style={{ flex: 1 }}>
<Text style={{ fontSize: 36, textAlign: "center" }}>{text}</Text>
<Button title="Start new game" onPress={onNewGame} />
</View>
);
};
const winner = squares => {
//basically all the combinations that could result in a win of the game
const lines = [
[0, 1, 2],
[3, 4, 5],
[6, 7, 8],
[0, 3, 6],
[1, 4, 7],
[2, 5, 8],
[0, 4, 8],
[2, 4, 6]
];
for (let i = 0; i < lines.length; i++) {
//go through the squares
const [a, b, c] = lines[i]; //get the first comb
//check if all the same type
if (squares[a] && squares[a] === squares[b] && squares[a] === squares[c]) {
return squares[a];
}
}
if (squares.indexOf(null) === -1) return null; // tie game, this means that every square is filled up.
return undefined;
};
|
Python
|
UTF-8
| 615
| 3.09375
| 3
|
[] |
no_license
|
import pygame
from pygame.time import wait
SCREEN_WIDTH = 320
SCREEN_HEIGHT = 240
SCREEN_BACKGROUND = (0, 0, 0)
RECT_WIDTH = 10
RECT_HEIGHT = 10
RECT_X = 0
RECT_Y = 0
RECT_COLOR = (255, 255, 255)
RECT_STEP = 20
TIME = 1000
def main():
pygame.init()
screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
rect = pygame.Rect(RECT_X, RECT_Y, RECT_WIDTH, RECT_HEIGHT)
while True:
screen.fill(SCREEN_BACKGROUND)
pygame.draw.rect(screen, RECT_COLOR, rect)
rect.right += RECT_STEP
pygame.display.flip()
wait(TIME)
if __name__ == '__main__':
main()
|
Java
|
UTF-8
| 398
| 1.960938
| 2
|
[] |
no_license
|
package com.amiltone.td_iem_411.model.pojo;
import java.util.List;
/**
* Created by amiltonedev_lt027 on 01/11/2016.
*/
public interface BLEDevice {
public static final int OFFLINE = 0;
public static final int AVAILABLE = 1;
public static final int CONNECTED = 2;
int getStatus();
String getLastValue();
List<String> getLastValues();
boolean pairConnectDevice();
}
|
PHP
|
UTF-8
| 2,866
| 3
| 3
|
[] |
no_license
|
<?php
require_once "database.php";
class Customer extends Database{
public function createCustomer($first_name,$last_name,$username,$password,$email,$address,$contact){
$sql = "INSERT INTO customers(first_name,last_name,username,`password`,email,`address`,contact)
VALUES('$first_name','$last_name','$username','$password','$email','$address','$contact')";
if($this->conn->query($sql)){
header("location: ../views/login.php");
}else{
die("Error creating customer".$this->conn->error);
}
}
public function createLogin($username,$password){
$sql="SELECT id,username,`password`
FROM customers
WHERE username='$username'";
$result = $this->conn->query($sql);
if($result->num_rows == 1){
$customer_detail = $result->fetch_assoc();
if(password_verify($password,$customer_detail['password'])){
session_start();
$_SESSION['id'] = $customer_detail['id'];
$_SESSION['username'] = $customer_detail['username'];
if($customer_detail['username'] == 'sho5'){
header("location: ../views/product.php");
exit;
}else{
header("location: ../views/main.php");
exit;
}
}else{
die("Error login".$this->conn->error);
}
}else{
die("Error login".$this->conn->error);
}
}
public function getCustomerList(){
$sql="SELECT id,first_name,last_name,username,`password`,email,`address`,contact FROM customers";
if($result = $this->conn->query($sql)){
return $result;
}else{
die("Error display".$this->conn->error);
}
}
public function deleteCustomer($customer_id){
$sql="DELETE FROM customers WHERE id='$customer_id'";
if($this->conn->query($sql)){
header("location: ../views/customerList.php");
exit;
}else{
die("Error deleting".$this->conn->error);
}
}
public function updateCustomer($customer_id,$first_name,$last_name,$username,$email,$address,$contact){
$sql="UPDATE customers
SET first_name = '$first_name',
last_name ='$last_name',
username ='$username',
email ='$email',
`address` ='$address',
contact ='$contact'
WHERE id = '$customer_id'";
if($this->conn->query($sql)){
header("location: ../views/customerList.php");
exit;
}else{
die("Error updating".$this->conn->error);
}
}
public function getCustomer($customer_id){
$sql="SELECT id,first_name,last_name,username,email,`address`,contact FROM customers WHERE id = '$customer_id'";
if($result = $this->conn->query($sql)){
return $result->fetch_assoc();
}else{
die("Error getting".$this->conn->error);
}
}
}
?>
|
Shell
|
UTF-8
| 431
| 3.484375
| 3
|
[] |
no_license
|
#!/bin/sh
host_list="
server1
server2
"
cur_time=`date +%Y%m%d-%H:%M`
email=your@email
for hosts in `echo $host_list`
do
if ! ping -c 1 $hosts >/dev/null 2>/dev/null
then
sleep 2
if ! ping -c 1 $hosts >/dev/null 2>/dev/null
then
echo "$hosts : Server or Network Died" >> $$.tmp
echo >> $$.tmp
fi
fi
done
if [ -s $$.tmp ]; then
mail -s "[watch.sh] $cur_time" $email < $$.tmp
fi
rm -f $$.tmp
|
C#
|
UTF-8
| 1,464
| 3.0625
| 3
|
[
"Apache-2.0"
] |
permissive
|
namespace SecondAttempt
{
using Microsoft.Xna.Framework;
public class FadeEffect : ImageEffect
{
public float FadeSpeed;
public bool Increase;
public float FadeMax;
public float FadeMin;
public FadeEffect()
{
FadeSpeed = 1;
Increase = false;
FadeMax = 1;
FadeMin = 0;
}
public override void LoadContent(Image Image)
{
base.LoadContent(Image);
}
public override void UnloadContent()
{
base.UnloadContent();
}
public override void Update(GameTime gameTime)
{
base.Update(gameTime);
if (image.IsActive)
{
if (!Increase)
image.Alpha -= FadeSpeed * (float)gameTime.ElapsedGameTime.TotalSeconds;
else
image.Alpha += FadeSpeed * (float)gameTime.ElapsedGameTime.TotalSeconds;
if (image.Alpha < FadeMin)
{
Increase = true;
image.Alpha = FadeMin;
}
else if (image.Alpha > FadeMax)
{
Increase = false;
image.Alpha = FadeMax;
}
}
else
image.Alpha = FadeMax;
}
}
}
|
Python
|
UTF-8
| 793
| 2.5625
| 3
|
[] |
no_license
|
import os
from twilio.rest import Client
# alright then, keep your secrets
# Get the Twilio SID and auth token from environment variables, see startup.sh
twilio_sid = os.environ.get('TWILIO_SID')
twilio_auth = os.environ.get('TWILIO_AUTH')
# set up the Twilio client
client = Client(twilio_sid, twilio_auth)
# Prompt the user for message parameters
# TODO: Sanitize input (at least check for NANP format)
def promptUser():
messageRecipient = raw_input("Recipient number: ")
messageBody = raw_input("Message body: ")
sendMessage(messageRecipient, messageBody)
def sendMessage(messageRecipient, messageBody):
message = client.messages.create(
body=messageBody,
from_='+19705915361',
to=messageRecipient
)
print(message.sid)
promptUser()
|
JavaScript
|
UTF-8
| 860
| 2.875
| 3
|
[] |
no_license
|
$("div.box").css("background-color","blue");
$("div.box").text("Lookie Lookie");
// $("div#box1").on("click",function() {
// $("div#box1").css("height","500px");
// $("div#box1").css("width","500px");
// $("div#box2").css("height","200px");
// $("div#box2").css("width","200px");
// })
// $("div#box2").on("click",function() {
// $("div#box2").css("height","500px");
// $("div#box2").css("width","500px");
// $("div#box1").css("height","200px");
// $("div#box1").css("width","200px");
// })
// var clickCount = 0;
// $("div#box1").on("click",function() {
// clickCount = clickCount + 1;
// if (clickCount === 1) {
// $("div#box1").addClass("bigger");
// } else {
// $("div#box1").removeClass("bigger");
// clickCount = 0;
// }
// })
$("div#box1").on("click",function() {
$("div#box1").toggleClass("bigger");
})
|
Python
|
UTF-8
| 1,473
| 3.25
| 3
|
[
"BSD-3-Clause"
] |
permissive
|
#! /usr/bin/env python
"""
# given a dataset json,
manually add the sample_labels, sample_label_index , feature_labels
Usage:
export dataset json from mongo
./add_samples_to_dataset.py > dataset_with_samples.json
import new dataset json to mongo
Requires the following files to exist in the pwd:
-- dataset.json : dump of the existing dataset without sample labels, etc
-- samples : list of sample IDs with study lables prepended
-- features : list of feature names
"""
import json
import sys
# Are all elements of x unique
def uniq(x):
seen = set()
return not any(i in seen or seen.add(i) for i in x)
def main():
with open("dataset.json") as dataset:
data = json.load(dataset)
with open("samples") as samplines:
samples = [s.rstrip() for s in samplines.readlines()]
with open("features") as featurelines:
features = [f.rstrip() for f in featurelines.readlines()]
# Require unique lists
if((not uniq(samples)) or (not uniq(features))):
print "Samples not unique!"
sys.exit(1)
# study qualifer needs to already be present
data["sample_labels"] = samples
# sample label index
sample_label_index = {}
for idx, sample in enumerate(samples):
sample_label_index[sample] = idx
data["sample_label_index"] = sample_label_index
data["feature_labels"] = features
print (json.dumps(data))
sys.exit(0)
if __name__ == "__main__":
main()
|
JavaScript
|
UTF-8
| 2,430
| 2.703125
| 3
|
[] |
no_license
|
document.addEventListener("DOMContentLoaded", () => {
let path = window.location.pathname;
let pageFile = path.split("/").pop();
let pageName = pageFile.split(".")[0];
const getJSONProductsClass = new GetJSONProductsClass();
const mainCategoriesPageClass = new MainCategoriesPageClass();
getJSONProductsClass
.getJsonData(pageName)
.then((products) => {
mainCategoriesPageClass.displayProducts(products);
Storage.saveProducts(products);
})
.then(() => {
mainCategoriesPageClass.clickPageProducts();
});
});
let categoriesPageGalleryButtons = [];
let chosenItemsArray = [];
class MainCategoriesPageClass {
displayProducts(products) {
let results = "";
let cartPage = document.querySelector(".cart-Page");
products.forEach((prod) => {
results += `
<div class="card m-4 gallery-card">
<img class="card-img-top" src=${prod.image}>
<div class="card-body">
<h5 class="card-title text-center">${prod.name}</h5>
<p class="card-text text-center">$${prod.price}</p>
<a class="add-cart" href="#" class="" data-id=${prod.id} class="btn btn-primary">Add to Cart</a>
</div>
</div>
`;
});
let categoriesPageGalleryDisplay = document.querySelector(".gallery");
categoriesPageGalleryDisplay.innerHTML = results;
}
clickPageProducts() {
const buttons = [...document.querySelectorAll(".add-cart")];
categoriesPageGalleryButtons = buttons;
buttons.forEach((button) => {
let id = button.dataset.id;
button.addEventListener("click", (event) => {
event.target.innerText = "In Cart";
Storage.addsOneToProductsInCart(id);
location.reload();
});
});
}
}
let totalCartItems = 0;
let cartBtnUpperRightHand = document.querySelector(".cartBtnUpperRightHand");
let ssproducts = sessionStorage.getItem("products");
ssproducts = JSON.parse(ssproducts);
ssproducts.map((items) => {
totalCartItems += items.inCart;
sessionStorage.setItem("totalCartItems", JSON.stringify(totalCartItems));
});
cartBtnUpperRightHand.innerHTML = `
<ion-icon name="cart-outline"></ion-icon>
${totalCartItems}
`;
|
Python
|
UTF-8
| 364
| 3
| 3
|
[
"MIT"
] |
permissive
|
from queues.priority_queue.heap import MaxHeap
class PriorityQueue:
def __init__(self):
self.priority_queue = MaxHeap()
def insert(self, name, priority):
self.priority_queue.insert(name, priority)
def remove(self):
return self.priority_queue.extractMax()
def display(self):
return self.priority_queue.getHeap()
|
SQL
|
UTF-8
| 3,712
| 3.390625
| 3
|
[] |
no_license
|
--Creation vue lesdossiers
drop view LesDossiers;
drop table LesLocataires;
drop table LesBillets;
drop table LesInscriptions;
drop table LesLogements;
drop table LesResultats;
drop table LesEpreuves;
drop table LesDossiers_base;
drop table LesSportifs;
drop table LesEquipes;
drop table LesDisciplines;
drop table LesBatiments;
--Creation de tables
create table LesSportifs(
nSportif integer check( nSportif > 0) primary key,
nomS varchar(100), prenomS varchar(100), pays varchar(100),
categorieS varchar(100) check (categorieS in ('feminin','masculin') ),
dateNais date,
constraint pk_identite unique (nomS,prenomS)
);
insert into LesSportifs (select * from JO_INF245.LesSportifs);
create table LesEquipes(
nSportif integer check( nSportif > 0),
nEquipe integer check( nEquipe > 0),
constraint pk_nspeq primary key (nSportif, nEquipe)
);
insert into LesEquipes (select * from JO_INF245.LesEquipes);
create table LesDisciplines(
discipline varchar(100) primary key
);
insert into LesDisciplines (select * from JO_INF245.LesDisciplines);
create table LesEpreuves(
nEpreuve integer check (nEpreuve > 0) primary key,
nomE varchar(100),
forme varchar(100) check (forme in ('par equipe','individuelle','par couple') ),
discipline varchar(100) references LesDisciplines(discipline),
categorieE varchar(100) check (categorieE in ('feminin','masculin','mixte') ),
nbs integer,
dateEpreuve date,
prix real);
insert into LesEpreuves (select * from JO_INF245.LesEpreuves);
create table LesInscriptions(
nInscrit integer check (nInscrit > 0),
nEpreuve integer ,
constraint pk_inscript primary key (nInscrit, nEpreuve),
constraint ref_nep foreign key (nEpreuve) references LesEpreuves(nEpreuve)
);
insert into LesInscriptions (select * from JO_INF245.LesInscriptions);
create table LesResultats(
nEpreuve integer primary key references LesEpreuves(nEpreuve),
gold integer,
silver integer,
bronze integer
);
insert into LesResultats (select * from JO_INF245.LesResultats);
create table LesBatiments(
nomBat varchar(100) primary key,
num integer check(num > 0),
rue varchar(100),
ville varchar(100)
);
insert into LesBatiments (select * from JO_INF245.LesBatiments);
create table LesLogements(
nLogement integer check(nLogement > 0),
capacite integer check(capacite > 0),
nomBat varchar(100) references LesBatiments(nomBat),
constraint pk_log primary key (nLogement,nomBat)
);
insert into LesLogements (select * from JO_INF245.LesLogements);
create table LesLocataires(
nSportif integer primary key references LesSportifs(nSportif),
nLogement integer ,
nomBat varchar(100),
foreign key (nlogement, nombat) references leslogements(nlogement, nombat)
);
insert into LesLocataires (select * from JO_INF245.LesLocataires);
create table LesDossiers_base(
nDossier integer primary key check(nDossier > 0),
nUtil integer check (nUtil > 0),
dateEmission date
);
insert into LesDossiers_base (select * from JO_INF245.LesDossiers_base);
create table LesBillets(
nBillet integer check(nBillet > 0),
nDossier integer check(nDossier > 0),
nEpreuve integer references LesEpreuves(nEpreuve),
constraint pk_lesbillets primary key (nBillet,nDossier),
constraint ref_Dossierlesbillets foreign key (nDossier) references LesDossiers_base(nDossier),
constraint ref_Epreuvelesbillets foreign key (nEpreuve) references LesEpreuves(nEpreuve)
);
insert into LesBillets (select * from JO_INF245.LesBillets);
--Création de la vue
create view LesDossiers(nDossier,nUtil,dateEmission,prix) as
select nDossier, nUtil, dateEmission, sum(prix) as prix
from LesDossiers_base natural join lesBillets natural join
lesEpreuves
group by nDossier, nUtil, dateEmission;
commit;
|
SQL
|
UTF-8
| 1,832
| 4.125
| 4
|
[] |
no_license
|
--Dentre os filmes em cartaz, qual o filme com maior receita e qual sua receita e seu orçamento?
select title, revenue, budget from tb_movie
where now_playing = 'S' and
revenue in (select Max(revenue) from tb_movie);
/*Dentre as produtoras com filmes em cartaz ou filmes a serem lançados, qual teve o maior lucro (receita
– orçamento) acumulado nos últimos 10 anos? Considere que o lucro é distribuído igualmente entre as
companhias produtoras.*/
select
tpc.production_companies,
(tm.revenue - tm.budget) as lucro,
YEAR(tm.release_date) as ano
from tb_movie tm
inner join production_companies tpc
on tpc.id_production_companies = tm.id_production_companies
where tm.now_playing = 'S' or tm.up_coming = 'S'
and ano >= '2010'
group by 1
order by 2 desc
limit 1;
--Que diretor(a) dirigiu filmes com o maior orçamento acumulado dos últimos 20 anos?
select
tp.name,
sum(tm.budget) as acumulado,
YEAR(tm.release_date) as ano
from tb_movie tm
inner join tb_cast tc
on tc.id_movie = tm.movie
inner join crew tcw
on tcw.id_person = tc.id_person
inner join tb_person tp
on tp.id_person = tc.id_person
where tc.job = 'Director'
and ano >= '2000'
group by 1
order by 2 desc;
--Quais os 3 gêneros com maior número de filmes nos últimos 5 anos
select * from (
select count (tm.movies),
YEAR(release_date) as ano, tg.genres
from tb_movie tm
inner join genres tg
on tg.id_genres = tm.id_genres
where ano >= '2015'
order by 1 desc)
limit 3;
--Quais os países com a maior quantidade de filmes em cartaz produzidos em seus territórios?
select count (tm.movies), tpc. production_country from tb_movie tm
inner join tb_production_companies tpc
on tpc. production_countries = tm. production_countries
group by 2
order by 1 desc;
|
PHP
|
UTF-8
| 1,793
| 2.515625
| 3
|
[
"MIT"
] |
permissive
|
<?php
namespace App\Service;
use App\Models\Cadastro;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Arr;
use Exception;
class CadastroService
{
public static function store($request)
{
try{
$cadastro = Cadastro::create($request);
return[
'status' => true,
'contatos' => $cadastro
];
}catch(Exception $erro){
return[
'status'=> false,
'cadastro'=> $erro->getMessage(),
];
}
}
public static function getCadastroPorId($id)
{
try{
$cadastro = Cadastro::findOrFail($id);
return[
'status' => true,
'cadastro' => $cadastro
];
}catch(Exception $erro){
return [
'status' => false,
'erro'=> $erro->getMessage()
];
}
}
public static function upadate($request, $id)
{
try{
$cadastro = Cadastro::findOrFail($id);
$cadastro -> update($request);
return [
'status' => true,
'cadastro' => $cadastro
];
}catch(Exception $erro){
return[
'status' => false,
'erro' => $erro->getMessage()
];
}
}
public static function destroy($id)
{
try{
$cadastro = Cadastro::findOrFail($id);
$cadastro -> delete();
return[
'status' => true
];
}catch(Exception $erro){
return[
'status' => false,
'erro' => $erro->getMessage()
];
}
}
}
|
Java
|
UTF-8
| 2,523
| 2.171875
| 2
|
[] |
no_license
|
package com.example.e_stem;
import androidx.appcompat.app.AppCompatActivity;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
public class Mainscreen extends AppCompatActivity {
ImageView btnstem,btnquiz,btnreview,btnattendence,btnshare,btnreminder;
@SuppressLint("WrongViewCast")
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_mainscreen);
btnstem = findViewById(R.id.btnstem);
btnattendence=findViewById(R.id.btnattendence);
btnquiz = findViewById(R.id.btnquiz);
btnreview = findViewById(R.id.btnreview);
btnshare = findViewById(R.id.btnshare);
btnreminder = findViewById(R.id.btnreminder);
btnstem.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent i = new Intent( Mainscreen.this, STEMActivity.class);
startActivity(i);
}
});
btnquiz.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent i = new Intent( Mainscreen.this, Quizactivity.class);
startActivity(i);
}
});
btnreview.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent i = new Intent( Mainscreen.this, Quizactivity.class);
startActivity(i);
}
});
btnshare.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent i = new Intent( Mainscreen.this, ShareActivity.class);
startActivity(i);
}
});
btnattendence.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent i = new Intent( Mainscreen.this, AttendenceActivity.class);
startActivity(i);
}
});
btnreminder.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent i = new Intent( Mainscreen.this, ReminderActivity.class);
startActivity(i);
}
});
}
}
|
Java
|
UTF-8
| 4,092
| 2.0625
| 2
|
[] |
no_license
|
/*******************************************************************************
* Copyright (c) 2003, 2007 IBM Corporation Licensed Material - Property of IBM. All rights reserved.
*
* US Government Users Restricted Rights - Use, duplication or disclosure v1.0 restricted by GSA ADP
* Schedule Contract with IBM Corp.
*
* Contributors: IBM Corporation - initial API and implementation
*******************************************************************************/
package com.ibm.ccl.soa.deploy.core.validator.resolution.param;
import org.eclipse.emf.ecore.EAttribute;
import org.eclipse.emf.ecore.EStructuralFeature;
import com.ibm.ccl.soa.deploy.core.DeployModelObject;
/**
* A deploy resolution parameter linked to a deploy object attribute.
*/
public class DeployResolutionObjectAttributeParameter extends
DeployResolutionParameter implements
IDeployResolutionObjectAttributeParameter {
protected final DeployModelObject object;
protected final EAttribute objectAttribute;
protected final String objectAttributeName;
/**
* Construct a resolution parameter associated with the value of a DMO EMF
* attribute.
* <p>
* The type of the parameter is derived from the attribute type.
*
* @param resolution
* the resolution which is parameterized.
* @param name
* the name of the parameter.
* @param description
* a description of the resolution parameter.
* @param object
* the object whose attribute was parameterized.
* @param attribute
* the EMF attribute on the object that is parameterized.
*/
public DeployResolutionObjectAttributeParameter(
IDeployParameterizedResolution resolution, String name,
String description, DeployModelObject object, EAttribute attribute) {
super(resolution, attribute.getEAttributeType().getInstanceClass(),
name, description);
assert object != null;
assert attribute != null;
this.object = object;
this.objectAttribute = attribute;
this.objectAttributeName = attribute.getName();
}
/**
* Construct a resolution parameter associated with the value of a DMO
* attribute.
*
* @param resolution
* the resolution which is parameterized.
* @param name
* the name of the parameter.
* @param description
* a description of the resolution parameter.
* @param object
* the object whose attribute was parameterized.
* @param attributeType
* the type of the attribute.
* @param attributeName
* the name of the attribute on the object that is parameterized.
*/
public DeployResolutionObjectAttributeParameter(
IDeployParameterizedResolution resolution, String name,
String description, DeployModelObject object,
Class<?> attributeType, String attributeName) {
super(resolution, attributeType, name, description);
assert object != null;
assert attributeName != null;
this.object = object;
EAttribute attribute = null;
EStructuralFeature feature = object.getEObject().eClass()
.getEStructuralFeature(attributeName);
if ((feature != null) && (feature instanceof EAttribute)) {
attribute = (EAttribute) feature;
}
this.objectAttribute = attribute;
this.objectAttributeName = attributeName;
}
/*
* @see com.ibm.ccl.soa.deploy.core.validator.resolution.param.IDeployResolutionObjectAttributeParameter#getParameterizedObject()
*/
public DeployModelObject getParameterizedObject() {
return object;
}
/*
* @see com.ibm.ccl.soa.deploy.core.validator.resolution.param.IDeployResolutionObjectAttributeParameter#getParameterizedObjectAttribute()
*/
public EAttribute getParameterizedObjectAttribute() {
return objectAttribute;
}
/*
* @see com.ibm.ccl.soa.deploy.core.validator.resolution.param.IDeployResolutionObjectAttributeParameter#getParameterizedObjectAttributeName()
*/
public String getParameterizedObjectAttributeName() {
return objectAttributeName;
}
}
|
Java
|
UTF-8
| 5,923
| 2.265625
| 2
|
[
"Apache-2.0",
"CC-BY-SA-3.0",
"MIT",
"BSD-3-Clause"
] |
permissive
|
/*
* 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 net.jini.discovery;
import java.io.ByteArrayInputStream;
import java.io.DataInputStream;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.InetAddress;
import net.jini.core.lookup.ServiceID;
/**
* Encapsulate the details of unmarshaling an incoming multicast
* request packet.
*
* @author Sun Microsystems, Inc.
*
* @see OutgoingMulticastRequest
*/
@Deprecated
public class IncomingMulticastRequest {
/**
* The address to which any responses should go.
*/
protected InetAddress addr;
/**
* The port to which any responses should connect.
*/
protected int port;
/**
* The ServiceIDs from which the requestor has already heard.
* This set may not be complete.
*/
protected ServiceID[] serviceIDs;
/**
* The groups in which the requestor is interested. This set may
* not be complete.
*/
protected String[] groups;
/**
* The current version of the multicast request protocol.
*/
protected static final int protoVersion = 1;
/**
* Construct a new object, initialized from the contents of the
* given multicast request packet.
*
* @param dgram the packet to unmarshal
* @exception IOException a problem occurred while unmarshaling
* the packet
*/
public IncomingMulticastRequest(DatagramPacket dgram) throws IOException {
ByteArrayInputStream bs = new ByteArrayInputStream(dgram.getData());
DataInputStream ds = new DataInputStream(bs);
int proto = ds.readInt();
if (proto != protoVersion)
throw new IOException("unsupported protocol version: " + proto);
port = ds.readInt();
// Valid port ranges are 1 through 65535 for IPv4.
if (port <= 0 || port >= 65536)
throw new IOException("port number out of range: " + port);
int sidCount = ds.readInt();
// We know that a ServiceID marshals to 8 bytes, so ensure
// that the count can plausibly fit into this packet.
if (sidCount < 0 || sidCount > bs.available() / 8)
throw new IOException("service ID count invalid: " + sidCount);
serviceIDs = new ServiceID[sidCount];
for (int i = 0; i < serviceIDs.length; i++) {
serviceIDs[i] = new ServiceID(ds);
}
int grpCount = ds.readInt();
// We know that the minimal length of a string written with
// DataOutput.writeUTF is two bytes (for the empty string), so
// we make some attempt to see if the count can plausibly fit
// into this packet.
if (grpCount < 0 || grpCount > bs.available() / 2)
throw new IOException("group count invalid: " + grpCount);
groups = new String[grpCount];
for (int i = 0; i < groups.length; i++) {
groups[i] = ds.readUTF();
}
addr = dgram.getAddress();
}
/**
* Return the address of the host to contact in order to start
* unicast discovery.
*
* @return the address of the host to contact in order to start
* unicast discovery
*/
public InetAddress getAddress() {
return addr;
}
/**
* Return the number of the port to connect to on the remote host
* in order to start unicast discovery.
*
* @return the number of the port to connect to on the remote host
* in order to start unicast discovery
*/
public int getPort() {
return port;
}
/**
* Return the set of groups in which the requestor is interested.
* This set may not be complete, but other incoming packets should
* contain the rest of the set.
*
* @return the set of groups in which the requestor is interested.
*/
public String[] getGroups() {
return groups.clone();
}
/**
* Return a set of ServiceIDs from which the requestor has already
* heard. This set may not be complete.
*
* @return a set of service IDs from which the requestor has already
* heard
*/
public ServiceID[] getServiceIDs() {
return serviceIDs.clone();
}
public int hashCode() {
byte[] foo = addr.getAddress();
int code = (foo[0] << 3) ^ (foo[1] << 7) ^ (foo[2] << 5) ^ (foo[3] << 1) ^
~port;
for (int i = 0; i < groups.length; i++) {
code ^= groups[i].hashCode() << i;
}
for (int i = 0; i < serviceIDs.length; i++) {
code ^= serviceIDs[i].hashCode() << i;
}
return code;
}
/**
* Two requests are equal if they have the same address, port,
* groups, and service IDs.
*/
public boolean equals(Object o) {
// We assume here that multiple requests from the same machine
// will have the same source IP address. This is not
// necessarily true.
if (o instanceof IncomingMulticastRequest) {
IncomingMulticastRequest oo = (IncomingMulticastRequest) o;
if (oo.addr.equals(addr) && oo.port == port &&
oo.groups.length == groups.length &&
oo.serviceIDs.length == serviceIDs.length)
{
for (int i = 0; i < groups.length; i++) {
if (!groups[i].equals(oo.groups[i]))
return false;
}
for (int i = 0; i < serviceIDs.length; i++) {
if (!serviceIDs[i].equals(oo.serviceIDs[i]))
return false;
}
return true;
}
}
return false;
}
}
|
PHP
|
UTF-8
| 976
| 2.703125
| 3
|
[
"MIT"
] |
permissive
|
<?php namespace Addon\Module\Addons\Controller\Admin;
use Streams\Controller\AdminController;
class InstallerController extends AdminController
{
/**
* Install an addon.
*
* @param $type
* @param $slug
* @return \Illuminate\Http\RedirectResponse
*/
public function install($type, $slug)
{
$manager = '\\' . \Str::studly($type);
if ($manager::install($slug)) {
// Great
} else {
// Something went wrong - check logs
}
return \Redirect::back();
}
/**
* Uninstall an addon.
*
* @param $type
* @param $slug
* @return \Illuminate\Http\RedirectResponse
*/
public function uninstall($type, $slug)
{
$manager = '\\' . \Str::studly($type);
if ($manager::install($slug)) {
// Great
} else {
// Something went wrong - check logs
}
return \Redirect::back();
}
}
|
Java
|
UTF-8
| 1,906
| 2.4375
| 2
|
[] |
no_license
|
package net.project.hibernate.model;
import java.io.Serializable;
import java.math.BigDecimal;
import org.apache.commons.lang.builder.EqualsBuilder;
import org.apache.commons.lang.builder.HashCodeBuilder;
import org.apache.commons.lang.builder.ToStringBuilder;
/** @author Hibernate CodeGenerator */
public class PnPersonHasSkillPK implements Serializable {
/** identifier field */
private BigDecimal personId;
/** identifier field */
private BigDecimal skillId;
/** full constructor */
public PnPersonHasSkillPK(BigDecimal personId, BigDecimal skillId) {
this.personId = personId;
this.skillId = skillId;
}
/** default constructor */
public PnPersonHasSkillPK() {
}
public BigDecimal getPersonId() {
return this.personId;
}
public void setPersonId(BigDecimal personId) {
this.personId = personId;
}
public BigDecimal getSkillId() {
return this.skillId;
}
public void setSkillId(BigDecimal skillId) {
this.skillId = skillId;
}
public String toString() {
return new ToStringBuilder(this)
.append("personId", getPersonId())
.append("skillId", getSkillId())
.toString();
}
public boolean equals(Object other) {
if ( (this == other ) ) return true;
if ( !(other instanceof PnPersonHasSkillPK) ) return false;
PnPersonHasSkillPK castOther = (PnPersonHasSkillPK) other;
return new EqualsBuilder()
.append(this.getPersonId(), castOther.getPersonId())
.append(this.getSkillId(), castOther.getSkillId())
.isEquals();
}
public int hashCode() {
return new HashCodeBuilder()
.append(getPersonId())
.append(getSkillId())
.toHashCode();
}
}
|
Ruby
|
UTF-8
| 868
| 3.71875
| 4
|
[] |
no_license
|
# Granny's Greeting is awesome because we can use it to introduce our players
# to Granny, and let them know what Granny expects
#
# doctest: An example of using grannys_greeting
# >> grannys_greeting('Sonny')
# => "Hello Sonny!"
def grannys_greeting(name)
"Hello #{name}!"
end
# doctest: prompt_sonny
# >> prompt_sonny test = true
# => "HELLO"
def prompt_sonny(test = false)
test ? "HELLO" : gets.chomp
end
if __FILE__ == $0 # This is an "application guard" or also called a "Library guard"
# Code I wish I had. Wish driven development.
puts "This discussion will continue until you, as our feeble hero 'Sonny', shouts 'BYE'."
puts
puts grannys_greeting('Sonny')
sonny_says = prompt_sonny
until sonny_says == 'BYE'
granny_responds_to(sonny_says)
sonny_says = prompt_sonny
end
puts "Thank you for visiting your Granny!"
end
|
Python
|
UTF-8
| 644
| 3.34375
| 3
|
[] |
no_license
|
import string
from collections import OrderedDict
def solution(s, n):
alphabets = OrderedDict(zip(string.ascii_lowercase,range(1,27)))
result = []
for c in s:
if c.isalpha():
index = (alphabets[c.lower()] + n) % 26
if index == 0:
index = 26
for key,value in alphabets.items():
if value == index:
tmp = key
if c.isupper():
tmp = tmp.upper()
elif c.islower():
tmp = tmp.lower()
result.append(tmp)
else:
result.append(' ')
return "".join(result)
|
Markdown
|
UTF-8
| 5,387
| 3.015625
| 3
|
[
"MIT"
] |
permissive
|
# Laravel Favicon
[](https://packagist.org/packages/beyondcode/laravel-favicon)
[](https://travis-ci.org/beyondcode/laravel-favicon)
[](https://scrutinizer-ci.com/g/beyondcode/laravel-favicon)
[](https://packagist.org/packages/beyondcode/laravel-favicon)
Create dynamic favicons based on your environment settings.

## Laravel Package Development
[](https://phppackagedevelopment.com)
If you want to learn how to create reusable PHP packages yourself, take a look at my upcoming [PHP Package Development](https://phppackagedevelopment.com) video course.
## Installation
You can install the package via composer:
```bash
composer require beyondcode/laravel-favicon
```
The service provider for this package will be automatically registered for you.
## Usage
To make use of this package, make use of the `favicon` helper function that this package provides.
You can simply wrap the function around your favicon icon names, like this:
```html
<link rel="icon" type="image/png" sizes="32x32" href="{{ favicon(asset('favicon-32x32.png')) }}">
<link rel="shortcut icon" href="{{ favicon('favicon.ico') }}" />
```
## Customization
You can completely customize which environments you want to have enabled for the favicon generation, as well as the font and colors that will be used.
To modify the default values, publish the package configuration file using:
```
php artisan vendor:publish --provider='BeyondCode\LaravelFavicon\FaviconServiceProvider' --tag='config'
```
This will publish the `config/favicon.php` file.
This is what the default content looks like:
```php
return [
/*
* The list of enabled environments for the dynamic favicon
* generation. You can specify the text to display as well
* as the font and background color for the text.
*
* If no background color is specified, the text will be
* on a transparent background.
*/
'enabled_environments' => [
'local' => [
'text' => 'DEV',
'color' => '#000000',
'background_color' => '#ffffff',
],
],
/*
* The dynamic favicon text padding to apply.
*/
'padding' => [
'x' => 2,
'y' => 2,
],
/*
* The font file to use for the dynamic favicon generation.
* The default value will use OpenSans Regular.
*/
'font' => null,
/*
* Intervention Image supports "GD Library" and "Imagick" to process images
* internally. You may choose one of them according to your PHP
* configuration. By default PHP's "GD Library" implementation is used.
*
* If you want to convert ICO files, you need to use imagick.
*
* Supported: "gd", "imagick"
*
*/
'image_driver' => 'gd',
/*
* The prefix to use for the dynamic favicon URL.
*/
'url_prefix' => 'laravel-favicon',
/*
* The favicon generator class to use. The default generator
* makes use of the environment settings defined in this file.
* But you can create your own favicon generator if you want.
*/
'generator' => \BeyondCode\LaravelFavicon\Generators\EnvironmentGenerator::class,
];
```
Modify the settings to suit your needs.
## Custom generator
The default favicon generator will write the text on the bottom-right corner of your favicon, in the desired color, font and background-color.
If you want to generate a completely custom favicon, you can create your own FaviconGenerator implementation class and set it in the configuration file.
This is the interface that the generator should implement:
```php
interface FaviconGenerator
{
public function generate(string $icon): Response;
public function shouldGenerateFavicon(): bool;
}
```
The `generate` method receives the icon url/filename and expects you to return an illuminate HTTP response.
The `shouldGenerateFavicon` method can be used to determine if a custom favicon should get generated.
## FAQ
- My ICO files are not working, why?
In order to modify ICO files, you need the Imagick PHP library installed and enabled in your `config/favicon.php` file.
- Is there a performance impact when I'm using this package?
No - the default generator only modifies your favicon when the specified environment is enabled. This means, that production environments only see the static assets that you already have.
### Changelog
Please see [CHANGELOG](CHANGELOG.md) for more information what has changed recently.
## Contributing
Please see [CONTRIBUTING](CONTRIBUTING.md) for details.
### Security
If you discover any security related issues, please email marcel@beyondco.de instead of using the issue tracker.
## Credits
- [Marcel Pociot](https://github.com/mpociot)
- [All Contributors](../../contributors)
## License
The MIT License (MIT). Please see [License File](LICENSE.md) for more information.
|
Java
|
UTF-8
| 6,768
| 2.0625
| 2
|
[] |
no_license
|
/*
* Created on 10/10/2005
*
* TODO To change the template for this generated file go to
* Window - Preferences - Java - Code Style - Code Templates
*/
package mila.lexicon.dbUtils;
/**
* @author dalia bojan
* @version 1.0
*
*/
public class PrefixRecord {
String prefix = "";
String description = "";
boolean definiteArticleTag;
boolean defArtHE;
boolean relHE;
boolean adverbKAF;
boolean subConOrRelSHIN;
boolean tempSubConKAFSHIN;
boolean tempSubConMEMSHIN;
boolean tempSubConLAMEDKAFSHIN;
boolean tempSubConBETSHIN;
boolean relativizerTag;
boolean temporalSubConjTag;
boolean subordinatingConjunctionTag;
boolean prefPartUnit;
boolean prepBET;
boolean prepKAF;
boolean prepLAMED;
boolean prepMEM;
boolean prepositionTag;
boolean conjunctionTag;
/**
* @return Returns the description.
*/
public String getDescription() {
return description;
}
/**
* @return Returns the prefix.
*/
public String getPrefix() {
return prefix;
}
/**
* @return Returns the adverbKAF.
*/
public boolean isAdverbKAF() {
return adverbKAF;
}
/**
* @return Returns the conjunctionTag.
*/
public boolean isConjunctionTag() {
return conjunctionTag;
}
/**
* @return Returns the defArtHE.
*/
public boolean isDefArtHE() {
return defArtHE;
}
/**
* @return Returns the definiteArticleTag.
*/
public boolean isDefiniteArticleTag() {
return definiteArticleTag;
}
/**
* @return Returns the prefPartUnit.
*/
public boolean isPrefPartUnit() {
return prefPartUnit;
}
/**
* @return Returns the prepBET.
*/
public boolean isPrepBET() {
return prepBET;
}
/**
* @return Returns the prepKAF.
*/
public boolean isPrepKAF() {
return prepKAF;
}
/**
* @return Returns the prepLAMED.
*/
public boolean isPrepLAMED() {
return prepLAMED;
}
/**
* @return Returns the prepMEM.
*/
public boolean isPrepMEM() {
return prepMEM;
}
/**
* @return Returns the prepositionTag.
*/
public boolean isPrepositionTag() {
return prepositionTag;
}
/**
* @return Returns the relativizerTag.
*/
public boolean isRelativizerTag() {
return relativizerTag;
}
/**
* @return Returns the relHE.
*/
public boolean isRelHE() {
return relHE;
}
/**
* @return Returns the subConOrRelSHIN.
*/
public boolean isSubConOrRelSHIN() {
return subConOrRelSHIN;
}
/**
* @return Returns the subordinatingConjunctionTag.
*/
public boolean isSubordinatingConjunctionTag() {
return subordinatingConjunctionTag;
}
/**
* @return Returns the temporalSubConjTag.
*/
public boolean isTemporalSubConjTag() {
return temporalSubConjTag;
}
/**
* @return Returns the tempSubConBETSHIN.
*/
public boolean isTempSubConBETSHIN() {
return tempSubConBETSHIN;
}
/**
* @return Returns the tempSubConKAFSHIN.
*/
public boolean isTempSubConKAFSHIN() {
return tempSubConKAFSHIN;
}
/**
* @return Returns the tempSubConLAMEDKAFSHIN.
*/
public boolean isTempSubConLAMEDKAFSHIN() {
return tempSubConLAMEDKAFSHIN;
}
/**
* @return Returns the tempSubConMEMSHIN.
*/
public boolean isTempSubConMEMSHIN() {
return tempSubConMEMSHIN;
}
/**
* @param adverbKAF
* The adverbKAF to set.
*/
public void setAdverbKAF(boolean adverbKAF) {
this.adverbKAF = adverbKAF;
}
/**
* @param conjunctionTag
* The conjunctionTag to set.
*/
public void setConjunctionTag(boolean conjunctionTag) {
this.conjunctionTag = conjunctionTag;
}
/**
* @param defArtHE
* The defArtHE to set.
*/
public void setDefArtHE(boolean defArtHE) {
this.defArtHE = defArtHE;
}
/**
* @param definiteArticleTag
* The definiteArticleTag to set.
*/
public void setDefiniteArticleTag(boolean definiteArticleTag) {
this.definiteArticleTag = definiteArticleTag;
}
/**
* @param description
* The description to set.
*/
public void setDescription(String description) {
this.description = description;
}
/**
* @param prefix
* The prefix to set.
*/
public void setPrefix(String prefix) {
this.prefix = prefix;
}
/**
* @param prefPartUnit
* The prefPartUnit to set.
*/
public void setPrefPartUnit(boolean prefPartUnit) {
this.prefPartUnit = prefPartUnit;
}
/**
* @param prepBET
* The prepBET to set.
*/
public void setPrepBET(boolean prepBET) {
this.prepBET = prepBET;
}
/**
* @param prepKAF
* The prepKAF to set.
*/
public void setPrepKAF(boolean prepKAF) {
this.prepKAF = prepKAF;
}
/**
* @param prepLAMED
* The prepLAMED to set.
*/
public void setPrepLAMED(boolean prepLAMED) {
this.prepLAMED = prepLAMED;
}
/**
* @param prepMEM
* The prepMEM to set.
*/
public void setPrepMEM(boolean prepMEM) {
this.prepMEM = prepMEM;
}
/**
* @param prepositionTag
* The prepositionTag to set.
*/
public void setPrepositionTag(boolean prepositionTag) {
this.prepositionTag = prepositionTag;
}
/**
* @param relativizerTag
* The relativizerTag to set.
*/
public void setRelativizerTag(boolean relativizerTag) {
this.relativizerTag = relativizerTag;
}
/**
* @param relHE
* The relHE to set.
*/
public void setRelHE(boolean relHE) {
this.relHE = relHE;
}
/**
* @param subConOrRelSHIN
* The subConOrRelSHIN to set.
*/
public void setSubConOrRelSHIN(boolean subConOrRelSHIN) {
this.subConOrRelSHIN = subConOrRelSHIN;
}
/**
* @param subordinatingConjunctionTag
* The subordinatingConjunctionTag to set.
*/
public void setSubordinatingConjunctionTag(boolean subordinatingConjunctionTag) {
this.subordinatingConjunctionTag = subordinatingConjunctionTag;
}
/**
* @param temporalSubConjTag
* The temporalSubConjTag to set.
*/
public void setTemporalSubConjTag(boolean temporalSubConjTag) {
this.temporalSubConjTag = temporalSubConjTag;
}
/**
* @param tempSubConBETSHIN
* The tempSubConBETSHIN to set.
*/
public void setTempSubConBETSHIN(boolean tempSubConBETSHIN) {
this.tempSubConBETSHIN = tempSubConBETSHIN;
}
/**
* @param tempSubConKAFSHIN
* The tempSubConKAFSHIN to set.
*/
public void setTempSubConKAFSHIN(boolean tempSubConKAFSHIN) {
this.tempSubConKAFSHIN = tempSubConKAFSHIN;
}
/**
* @param tempSubConLAMEDKAFSHIN
* The tempSubConLAMEDKAFSHIN to set.
*/
public void setTempSubConLAMEDKAFSHIN(boolean tempSubConLAMEDKAFSHIN) {
this.tempSubConLAMEDKAFSHIN = tempSubConLAMEDKAFSHIN;
}
/**
* @param tempSubConMEMSHIN
* The tempSubConMEMSHIN to set.
*/
public void setTempSubConMEMSHIN(boolean tempSubConMEMSHIN) {
this.tempSubConMEMSHIN = tempSubConMEMSHIN;
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.