text
stringlengths 184
4.48M
|
---|
package studip.app.view.util;
import java.util.ArrayList;
import studip.app.R;
import studip.app.db.User;
import studip.app.net.ServerItem;
import studip.app.view.activities.ActivitiesItem;
import studip.app.view.courses.CoursesItem;
import studip.app.view.news.NewsItem;
import studip.app.view.slideout.MenuItem;
import android.content.Context;
import android.text.Html;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
public class GeneralArrayAdapter extends ArrayAdapter<ArrayAdapterItem> {
public GeneralArrayAdapter(Context context, int textViewResourceId, ArrayList<ArrayAdapterItem> objects) {
super(context, textViewResourceId, objects);
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
//MenuItem
if (getItem(position) instanceof MenuItem) {
MenuItem mi;
LayoutInflater inflater = LayoutInflater.from(this.getContext());
convertView = inflater.inflate(R.layout.menu_item, parent, false);
mi = (MenuItem)getItem(position);
mi.textTV = (FontTextView)convertView.findViewById(R.id.menuItemText);
mi.imageIV = (ImageView)convertView.findViewById(R.id.menuItemImage);
convertView.setTag(mi);
mi.textTV.setText(((MenuItem)getItem(position)).getTitel());
mi.imageIV.setImageResource(((MenuItem)getItem(position)).drawableID);
//ActivitiesItem
} else if (getItem(position) instanceof ActivitiesItem) {
ActivitiesItem ai;
LayoutInflater inflater = LayoutInflater.from(this.getContext());
convertView = inflater.inflate(R.layout.activities_item, parent, false);
ai = (ActivitiesItem)getItem(position);
ai.authorIV = (ImageView)convertView.findViewById(R.id.image);
ai.authorTV = (FontTextView)convertView.findViewById(R.id.author);
ai.timeTV = (FontTextView)convertView.findViewById(R.id.time);
ai.titleTV = (FontTextView)convertView.findViewById(R.id.title);
ai.bodyTV = (FontTextView)convertView.findViewById(R.id.body);
convertView.setTag(ai);
ai.authorIV.setImageDrawable(((ActivitiesItem)getItem(position)).author.getImage(User.MEDIUM_IMAGE));
ai.authorTV.setText(((ActivitiesItem) getItem(position)).author.getName());
ai.timeTV.setText(((ActivitiesItem) getItem(position)).activity.getTime());
ai.titleTV.setText(((ActivitiesItem) getItem(position)).activity.title);
ai.bodyTV.setText(Html.fromHtml(((ActivitiesItem) getItem(position)).activity.summary));
//NewsItem
} else if (getItem(position) instanceof NewsItem) {
NewsItem ni;
LayoutInflater inflater = LayoutInflater.from(this.getContext());
convertView = inflater.inflate(R.layout.news_item, parent, false);
ni = (NewsItem)getItem(position);
ni.authorIV = (ImageView)convertView.findViewById(R.id.image);
ni.authorTV = (FontTextView)convertView.findViewById(R.id.author);
ni.timeTV = (FontTextView)convertView.findViewById(R.id.time);
ni.topicTV = (FontTextView)convertView.findViewById(R.id.title);
ni.bodyTV = (FontTextView)convertView.findViewById(R.id.body);
convertView.setTag(ni);
ni.authorIV.setImageDrawable(((NewsItem)getItem(position)).author.getImage(User.MEDIUM_IMAGE));
ni.authorTV.setText(((NewsItem) getItem(position)).author.getName());
ni.timeTV.setText(((NewsItem) getItem(position)).news.getTime());
ni.topicTV.setText(((NewsItem) getItem(position)).news.topic);
ni.bodyTV.setText(Html.fromHtml(((NewsItem) getItem(position)).news.body));
//TextItem
} else if (getItem(position) instanceof TextItem) {
TextItem ti;
LayoutInflater inflater = LayoutInflater.from(this.getContext());
convertView = inflater.inflate(R.layout.text_item, parent, false);
ti = (TextItem) getItem(position);
ti.textTV = (FontTextView) convertView.findViewById(R.id.text);
convertView.setTag(ti);
ti.textTV.setText(((TextItem) getItem(position)).text);
//CoursesItem
} else if (getItem(position) instanceof CoursesItem) {
CoursesItem ci;
LayoutInflater inflater = LayoutInflater.from(this.getContext());
convertView = inflater.inflate(R.layout.courses_item, parent, false);
ci = (CoursesItem) getItem(position);
ci.icon = (ImageView)convertView.findViewById(R.id.image);
ci.titleTV = (FontTextView) convertView.findViewById(R.id.title);
convertView.setTag(ci);
ci.icon.setImageDrawable(this.getContext().getResources().getDrawable(R.drawable.seminar));
ci.titleTV.setText(((CoursesItem) getItem(position)).course.title);
//ServerItem
} else if(getItem(position) instanceof ServerItem) {
ServerItem si;
LayoutInflater inflater = LayoutInflater.from(this.getContext());
convertView = inflater.inflate(R.layout.image_text_item, parent, false);
si = (ServerItem) getItem(position);
si.tv = (FontTextView) convertView.findViewById(R.id.text);
convertView.setTag(si);
si.tv.setText(((ServerItem)getItem(position)).server.NAME);
}
return convertView;
}
} |
package ShadowSiren.relics;
import ShadowSiren.ShadowSirenMod;
import ShadowSiren.powers.ChargePower;
import ShadowSiren.util.TextureLoader;
import basemod.abstracts.CustomRelic;
import com.badlogic.gdx.graphics.Texture;
import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.megacrit.cardcrawl.actions.common.ApplyPowerAction;
import com.megacrit.cardcrawl.actions.common.RelicAboveCreatureAction;
import com.megacrit.cardcrawl.dungeons.AbstractDungeon;
import com.megacrit.cardcrawl.relics.AbstractRelic;
import com.megacrit.cardcrawl.ui.panels.EnergyPanel;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.HashMap;
import static ShadowSiren.ShadowSirenMod.makeRelicOutlinePath;
import static ShadowSiren.ShadowSirenMod.makeRelicPath;
public class TastyTonic extends CustomRelic {
// ID, images, text.
public static final String ID = ShadowSirenMod.makeID("TastyTonic");
private static final Texture IMG = TextureLoader.getTexture(makeRelicPath("TastyTonic.png"));
private static final Texture OUTLINE = TextureLoader.getTexture(makeRelicOutlinePath("TastyTonic.png"));
HashMap<String, Integer> stats = new HashMap<>();
private final String CHARGE_STAT = DESCRIPTIONS[1];
private final String PER_COMBAT_STRING = DESCRIPTIONS[2];
private final String PER_TURN_STRING = DESCRIPTIONS[3];
public TastyTonic() {
super(ID, IMG, OUTLINE, RelicTier.RARE, LandingSound.CLINK);
resetStats();
}
// Description
@Override
public String getUpdatedDescription() {
return DESCRIPTIONS[0];
}
@Override
public void onPlayerEndTurn() {
if (EnergyPanel.totalCount > 0) {
flash();
this.addToTop(new RelicAboveCreatureAction(AbstractDungeon.player, this));
this.addToTop(new ApplyPowerAction(AbstractDungeon.player, AbstractDungeon.player, new ChargePower(AbstractDungeon.player, EnergyPanel.totalCount)));
stats.put(CHARGE_STAT, stats.get(CHARGE_STAT) + EnergyPanel.totalCount);
}
}
public String getStatsDescription() {
return CHARGE_STAT + stats.get(CHARGE_STAT);
}
public String getExtendedStatsDescription(int totalCombats, int totalTurns) {
// You would just return getStatsDescription() if you don't want to display per-combat and per-turn stats
StringBuilder builder = new StringBuilder();
builder.append(getStatsDescription());
float stat = (float)stats.get(CHARGE_STAT);
// Relic Stats truncates these extended stats to 3 decimal places, so we do the same
DecimalFormat perTurnFormat = new DecimalFormat("#.###");
builder.append(PER_TURN_STRING);
builder.append(perTurnFormat.format(stat / Math.max(totalTurns, 1)));
builder.append(PER_COMBAT_STRING);
builder.append(perTurnFormat.format(stat / Math.max(totalCombats, 1)));
return builder.toString();
}
public void resetStats() {
stats.put(CHARGE_STAT, 0);
}
public JsonElement onSaveStats() {
// An array makes more sense if you want to store more than one stat
Gson gson = new Gson();
ArrayList<Integer> statsToSave = new ArrayList<>();
statsToSave.add(stats.get(CHARGE_STAT));
return gson.toJsonTree(statsToSave);
}
public void onLoadStats(JsonElement jsonElement) {
if (jsonElement != null) {
JsonArray jsonArray = jsonElement.getAsJsonArray();
stats.put(CHARGE_STAT, jsonArray.get(0).getAsInt());
} else {
resetStats();
}
}
@Override
public AbstractRelic makeCopy() {
// Relic Stats will always query the stats from the instance passed to BaseMod.addRelic()
// Therefore, we make sure all copies share the same stats by copying the HashMap.
TastyTonic newRelic = new TastyTonic();
newRelic.stats = this.stats;
return newRelic;
}
} |
# Chapter3 유니언과 리터럴
## 유니언 (union)
타입을 두 가지 이상으로 확장하는 것
## 유니언 타입
- 타입의 값이 정확히 어떤 타입인지 모르지만 두개 이상 옵션 중 하나라는 것을 알고있는 경우 코드를 처리하는 개념을 **유니언**이라고 한다.
- **예제 코드**를 보면 **mathematician** 변수의 값은 **undefined** 혹은 **string**가 될 수 있는 것을 알수 있고 변수에 마우스를 가져가면 `let mathematician : string | undefined`로 타입이 간주되는 것을 알수 있다.
```tsx
let mathematician = Math.random()>0.5 ? undefined : "Mark Golberg";
```
## 유니언 타입 선언
- 유니언 타입을 타입 애너테이션으로 선언하여 사용이 가능하다.
- **예제 코드**를 보면 **thinker** 변수 초기값을 `null` 이지만 `null` 대신 `string` 값이 할당 될 수 있다는 것을 알 수 있다.
```tsx
let thinker : string : null = null;
if(Math.random() > 0.5){
thinker = "Susanne Langer";
}
```
<aside>
💡 유니언 타입 선언의 순서는 중요하지 않다.
</aside>
## **유니언 속성**
- 타입 스크립트는 값이 유니언 타입일때 선언한 모든 타입에 존재하는 **값 속성에 접근이 가능**하다**.**
- 유니온 외의 타입에 접근하려고 하면 **타입검사 오류가 발생**한다.
- 예제코드에 `number | string`을 타입으로 선언하고 값의 속성을 사용할 때 `toUpperCase( )`는 에러가 발생한다.
- 이유는 `toString( )`는 number, string에 속성이 존재하고 `toUpperCase( )`는 string에만 존재하기 때문에 타입스크립트에서 존재 하지않는 속성에 대한 접근하여 에러 발생을 막으려는 안전장치이다.
```tsx
let physicist = Math.random()>0.5 ? "Marie Curie" : 84;
physicist.toString();
physicist.toUpperCase(); //error
```
## 내로잉
- 값의 정의, 선언 혹은 이전에 유추된 것보다 더 **구체적인 타입**임을 코드에서 유추하는 것이다.
- 타입스크립트가 코드에서 타입을 좁혀 값을 구체적인 타입으로 취급하는데 이러한 타입을 좁히는데 사용되는 논리적 검사를 **타입가드**라고 한다.
## 흔히 사용되는 두가지 타입 가드
### 값 할당을 통한 내로잉
- 변수에 값을 할당하여 변수의 타입을 할당된 타입으로 좁히는 방식
- 예제코드에서 **admiral**에 문자열 값이 할당되었고 타입스크립트에서는 string으로 타입이 좁혀진 것을 알고 string 속성에 없는 `toFix()`속성 사용에 대해 타입 검사 오류를 발생 시킨 것을 알수있다.
```tsx
let admiral : number | string;
admiral = "Grace Hopper";// type string
admiral.toUpperCase();
admiral.toFix(); //error
```
- 아래 예제코드에서 유니언 타입 선언하고 초기값을 문자열로 할당하면 타입스크립트는 문자열이 할당 되었기 때문에 타입이 string 타입으로 좁혀진 것을 알수있다.
```tsx
let admiral : number | string = "Grace Hopper";
admiral.toUpperCase();
admiral.toFix(); //error
```
### 조건 검사를 통한 내로잉
- 변수가 알려진 값과 같은지 확인하기 위해 **if**문을 통해 변수의 값을 좁히는 방법
- 예제코드에서 **if**문을 사용하여 변수의 값이 stirng 타입으로 좁혀진 것을 알수있다.
```tsx
// number | string 타입
let scientist = Math.random() > 0.5 ? "Rosalind Franklin" : 51;
if(scientist === "Rosalind Franklin"){
// string 타입
scientist.toUpperCase();
}
// number | string 타입
scientist.toUpperCase(); //error
```
### typeof 검사를 통한 내로잉
- typeof 연산자를 사용하여 변수의 값을 좁히는 방법
- if문 조건으로 typeof 연산자를 사용하여 변수의 값 타입이 string인지 유추한 것을 알수있다.
```tsx
// number | string 타입
let scientist = Math.random() > 0.5 ? "Rosalind Franklin" : 51;
if(typeof scientist === "string"){
// string 타입
scientist.toUpperCase();
}
```
## 리터럴 타입
- 원시 타입 값 중 어떤 것이 아닌 **특정 원싯값**으로 알려진 타입이 리터럴 타입이다.
- 예제코드를 보면 타입이 string라고 알수 있는데 하지만 string 타입이 아닌 "Hypatia" 라는 특별한 타입이고 리터럴 타입의 개념이라고 알수있다.
- philosopher값에 마우스를 갔다대면 `const philosopher :"Hypatia"` 일반적인 원시타입 대신 리터럴 타입이 표시되는것을 알수있다.
```tsx
const philosopher = "Hypatia";
```
<aside>
💡 변수를 **const**로 선언하고 직접 리터럴 값을 할당하면 타입스트립트는 해당변수를 리터럴 값으로 유추한다.
</aside>
- 원시 타입은 해당 타입의 모든 리터럴 값의 집합이다.
- boolean, null, undefined 타입 외에 string, number과 같은 원시타입에는 무한할 수의 리터럴 타입의 있다.
- **boolean** : true | false
- **null과 undefined** : 자기자신 , 오직 하나의 리터럴 값만 가짐
- **number** : 0 | 1 | 2…| 0.1 | 0.2….
- **string** : “” | “a” | “b” |… | “aa” | “bb” |….
- 유니언 타입 애네테이셔에서는 리터널과 원시타입을 섞어서 사용이 가능하다.
```tsx
let lifespan: number | "ongoing" | "uncertain";
lifespan = 89;
lifespan = "ongoing";
lifespan = true; //error
```
- 리터럴 타입은 0,1 처럼 원시타입이 같아도 서로 다른 리터럴타입을 할당 할수 없다.
```tsx
let specificallAda :"Ada";
specificallAda = "Ada";
specificallAda = "Byron"; //error
```
### 엄격한 null 검사
- 타입 시스템에서 사용하는 **null**이나 **undefined** 값을 사용하지 못하게 하는 기능
- **십억 달러의 실수**를 잡기위해 도입한 타입스크립트의 기능
- 사용법은 `tsconfing.js`에서 `strictNullChecks : true` 설정해주면 된다 .
- `strictNullChecks`비활성화시 코드의 모든 타입에 null | undefined를 추가해야 모든 변수에 null 또는 undefined값을 할당 할수 있다.
- `strictNullChecks`활성화 시 코드가 null 또는undefined 값으로 인한 오류로 부터 안전한지 여부를 파악할 수 있다
### 십억달러의 실수
- 1965년 null 참조의 발명으로 수많은 오류, 취약성 및 시스템 충돌이 발생 했으며 지난 40년 동안 십억달러의 고통과 피해
### 참검사를 통한 내로잉
- 잠재적인 값중 truthy로 변수의 타입을 좁힐수 있다.
- &&연산자와 optional chaning은 참여부 확인 외 다른 기능을 제공하지 않는다.
- if~else를 사용하여 변수의 타입을 좁힐수 있다
```tsx
// string | undefined 타입
//truthy를 사용한 참여부 확인
let gebeticist = Math.random() > 0.5 ? "Rosalind Franklin" : undefined;
if(gebeticist){
gebeticist.toUpperCase();// string 타입
}
gebeticist.toUpperCase();
// Error : Object is possibly 'undefined'
// &&연산자와 optional chaning은 참여부 확인
gebeticist&& gebeticist.toUpperCase();
gebeticist?.toUpperCase()'
//if~else 참여부 확인
let biologist = Math.random() > 0.5 ? "Rosalind Franklin" : 0.5;
if(biologist){
biologist// string 타입
}else{
biologist // false | string 타입
}
```
### 초기값 없는 변수
- 자바스크립트에서 초기값이 없는 변수는 기본적으로 undefined가 된다.
- 타입스크립트는 타입이 선언되어도 값이 할당 되기전까지 undefined로 인지한다.
- 값이 할당되기전에 접근시 예제코드와 같은 오류메시지를 나타낸다.
```tsx
let mathematician : string;
mathematician?.length;
//Error : Variavle "mathematician" is used before being assigned
```
- 변수 타입에 undefined를 추가하면 undefined는 유효한 타입이기 때문에 사용전에 값을 할당 하지 않아도 에러가 발생하지 않는다
```tsx
let mathematician : string | undefined;
mathematician?.length;
```
## 타입 별칭
- 반복성 유니언 타입 혹은 타입이 복잡해질 때 재사용 가능한 타입으로 할당하는 것
- type 새로운 이름 = 타입 형태를 가지며 타입 별칭은 파스칼 케이스로 이름을 짓는다.
- 타입 별칭은 타입스크립트에에만 존재하며 자바스크립트로 컴파일 되지 않는다.
- 타입 스크립트는 런타임에 존재하지 않아 런타임 코드에서 참조 할 수 없다
- 타입 별칭은 개발 시에만 존재한다.
```tsx
type RawData = boolean | number | string | null | undefined;
let rawDataFirst : RawData;
let rawDataSecond : RawData
let rawDataThrid : RawData
//런타임 코드
console.log(RawData);//error
```
## 타입 별칭 결합
- 기존에 만든 타입 별칭에 다른 타입 별칭을 참조하는 것
```tsx
type Id = number | string;
type IdMaybe Id | undefined | null;
//사용 순서대로 선언하지 않아도 된다
type IdMaybe Id | undefined | null;
type Id = number | string;
```
<aside>
💡 사용 순서대로 타입 별칭을 선언 하지 않아도 사용이 가능하다
</aside> |
// SPDX-License-Identifier: Apache-2.0 and MIT
// Copyright 2015-2023 Christoph Zengler
// Copyright 2023-20xx BooleWorks GmbH
package com.booleworks.logicng.datastructures;
import com.booleworks.logicng.formulas.FormulaFactory;
import com.booleworks.logicng.formulas.Literal;
import com.booleworks.logicng.formulas.implementation.noncaching.LngNativeVariable;
/**
* An auxiliary variable for encoding results.
* <p>
* This variable is used, if the result is added directly to a solver. In this
* case no variable on the factory has to be created.
* @version 3.0.0
* @since 1.1
*/
final class EncodingAuxiliaryVariable extends LngNativeVariable {
final boolean negated;
/**
* Constructs a new auxiliary variable
* @param name the literal name
* @param negated {@code true} if the variables is negated, {@code false}
* otherwise
*/
EncodingAuxiliaryVariable(final String name, final boolean negated) {
super(name, null);
this.negated = negated;
}
@Override
public Literal negate(final FormulaFactory f) {
return new EncodingAuxiliaryVariable(name(), !negated);
}
@Override
public String toString() {
return name();
}
} |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
.header {
text-align: center;
}
</style>
</head>
<body>
<!-- html -->
<div id="app">
<!-- header component 위치 -->
<our-header></our-header>
<!-- body component 위치 -->
<our-body></our-body>
<!-- footer component 위치 -->
<our-footer></our-footer>
</div>
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<!-- vue -->
<script>
// 컴포넌트 정의
// header 컴포넌트
Vue.component("our-header", {
/*html*/
template:
`
<div class="header">
<p><h4>여기에 방문하신걸 환영합니당</p></h4>
</div>
`
});
// body 컴포넌트
Vue.component("our-body", {
template: "<div>body 컴포넌트가 등록되었습니다.</div>"
});
// footer 컴포넌트
Vue.component("our-footer", {
template: "<div>footer 컴포넌트가 등록되었습니다.</div>"
});
// Vue 생성
let vm = new Vue({
el: "#app"
});
</script>
</body>
</html> |
//
// MovieUtilTest.swift
// MovieManiaTests
//
// Created by Ahmad Ubaidillah on 13/07/21.
//
import XCTest
@testable import MovieMania
class MovieUtilTest: XCTestCase {
var movieUtil: MovieUtil!
var realmRepo : RealmRepo!
override func setUp() {
super.setUp()
movieUtil = MovieUtil()
realmRepo = RealmRepo()
}
override func tearDown() {
movieUtil = nil
realmRepo = nil
super.tearDown()
}
func testConvertionMovieToMovieRealm(){
var listResponse: ListResponse
var movieList = [Movie]()
var movie: Movie!
var movieRealm: MovieRealm
if let path = Bundle.main.path(forResource: "MockData", ofType: "json"){
print(path)
do{
let data = try Data(contentsOf: URL(fileURLWithPath: path))
listResponse = try JSONDecoder().decode(ListResponse.self, from: data)
movieList = listResponse.results
}catch{
print(error)
}
}
movie = movieList.first
movieRealm = movieUtil.movieToMovieRealm(movie: movie)
XCTAssertNotNil(movieRealm)
XCTAssertEqual(movieRealm.id, movie.id)
XCTAssertEqual(movieRealm.title, movie.title)
XCTAssertEqual(movieRealm.overview, movie.overview)
XCTAssertNotNil(movieRealm.backdrop_path)
XCTAssertNotNil(movieRealm.poster_path)
}
} |
// const inquirer = require('inquirer');
let inquirer;
// Use dynamic import to resolve the ES Module issue
try {
inquirer = require('inquirer');
} catch (error) {
console.error(
'Error loading inquirer module. Try running "npm install inquirer" to install it.'
);
process.exit(1);
}
const fs = require('fs');
const generateMarkdown = require('./utils/generateMarkdown');
// License options array
const licenseOptions = [
'MIT',
'Apache 2.0',
'GPL 3.0',
'BSD 3',
'None'
// Add more license options as needed
];
// Questions for the user
const questions = [
{
type: 'input',
name: 'title',
message: 'What is the title of your project?',
},
{
type: 'input',
name: 'description',
message: 'Provide a short description of your project:',
},
{
type: 'input',
name: 'installation',
message: 'Provide installation instructions:',
},
{
type: 'input',
name: 'usage',
message: 'Provide usage information:',
},
{
type: 'list',
name: 'license',
message: 'Choose a license for your application:',
choices: licenseOptions,
},
{
type: 'input',
name: 'contributing',
message: 'Provide contribution guidelines:',
},
{
type: 'input',
name: 'tests',
message: 'Provide test instructions:',
},
{
type: 'input',
name: 'username',
message: 'Enter your GitHub username:',
},
{
type: 'input',
name: 'email',
message: 'Enter your email address:',
},
];
// Function to initialize the application
async function init() {
try {
// Prompt the user with questions
const userResponses = await inquirer.prompt(questions);
// Generate the README content
const markdown = generateMarkdown(userResponses);
// Save the markdown content to a README.md file
fs.writeFileSync('README.md', markdown);
console.log('README.md generated successfully!');
} catch (error) {
console.error('Error generating README:', error);
}
}
// Invoke the application
init(); |
from django.db import transaction
from django.core.exceptions import ObjectDoesNotExist
from django.contrib.auth.models import AnonymousUser
from rest_framework import serializers
from ..models import BlogPost
from permission.models import PostPermission, Category, Permission, CategoryName
class BlogPostSerializer(serializers.ModelSerializer):
class Meta:
model = BlogPost
fields = ('id', 'title', 'content', 'author')
def to_representation(self, instance: BlogPost):
response = {
'id': instance.id,
'title': instance.title,
'content': instance.content,
'content_html': instance.content_html,
'excerpt': instance.excerpt,
'createdAt': instance.created_at,
'author': {
'id': instance.author.id,
'nickname': instance.author.nickname,
'email': instance.author.email,
'team': {
'id': instance.author.team.id,
'name': instance.author.team.name
}
},
'permissions': {
cat_perm.category.name: {'id':cat_perm.permission.id, 'name':cat_perm.permission.name} for cat_perm in instance.reverse_post.all()
},
'likes': instance.likes.count(),
'comments': instance.comments.count()
}
user = self.context.get('request').user
if not isinstance(user, AnonymousUser):
like_count = instance.likes.filter(id=user.id).count()
response['post_liked'] = True if like_count > 0 else False;
return response
class PostPermissionSerializer(serializers.Serializer):
category_id = serializers.IntegerField()
permission_id = serializers.IntegerField()
class BlogPostCreateSerializer(serializers.ModelSerializer):
permissions = serializers.ListField(child=PostPermissionSerializer(), write_only=True, required=True)
class Meta:
model = BlogPost
fields = ('id', 'title', 'content', 'author', 'permissions', 'content_html')
def validate_permissions(self, permissions: list):
allowed_categories = [choice for choice, _ in CategoryName.choices]
set_categories = set([permission['category_id'] for permission in permissions])
if len(set_categories) != len(allowed_categories):
raise serializers.ValidationError("Missing permission for some category.")
return permissions
@transaction.atomic
def create(self, validated_data):
permissions_data = validated_data.pop('permissions')
post = BlogPost.objects.create(**validated_data)
self._save_permissions(permissions_data, post)
return post
@transaction.atomic
def update(self, instance: BlogPost, validated_data):
permissions_data = validated_data.pop('permissions')
instance.title = validated_data.get('title')
instance.content = validated_data.get('content')
instance.content_html = validated_data.get('content_html')
instance.save()
self._save_permissions(permissions_data, instance)
return instance
def _save_permissions(self, permissions_data, post):
for permission_dict in permissions_data:
try:
categoryObj = Category.objects.get(pk=permission_dict['category_id'])
permissionObj = Permission.objects.get(pk=permission_dict['permission_id'])
except ObjectDoesNotExist as err:
raise serializers.ValidationError({'permissions': [err]})
PostPermission.objects.update_or_create(category=categoryObj, post=post, defaults={'permission':permissionObj}) |
<template>
<div class="footer-collapse">
<header>
<h6 @click="toggle">
{{ title }}
</h6>
</header>
<div v-if="isExpanded" class="footer-collapse__content">
<slot />
</div>
</div>
</template>
<script lang="ts">
import { defineComponent, ref } from '@nuxtjs/composition-api'
import { useToggle } from '@vueuse/core'
import useBreakpoints from '~/utils/useBreakpoints'
export default defineComponent({
props: {
title: {
type: String,
required: true,
},
},
setup() {
const { isDesktop } = useBreakpoints()
const isExpanded = ref(true)
const toggle = useToggle(isExpanded)
return {
isDesktop,
isExpanded,
toggle,
}
},
})
</script>
<style lang="scss" scoped>
.footer-collapse {
}
</style> |
#include <iostream>
#include <boost/asio.hpp>
#include <boost/version.hpp>
#include <tbb/concurrent_queue.h>
#include <thread>
#include <chrono>
namespace asio = boost::asio;
using asio::ip::tcp;
using namespace std::chrono_literals;
class Session;
tbb::concurrent_bounded_queue<std::shared_ptr<Session>> queue{};
class Session : public std::enable_shared_from_this<Session>{
public:
tcp::socket socket;
explicit Session(tcp::socket &&socket):
socket(std::move(socket)){}
void start() {
asio::streambuf buf;
boost::system::error_code err;
asio::read_until(socket, buf, "\0", err);
if(err && err != asio::error::eof) {
std::cerr << "receive failed: " << err.message() << std::endl;
}else {
auto data = asio::buffer_cast<const char*>(buf.data());
std::cout << "receive: " << data << std::endl;
queue.push(shared_from_this());
}
}
};
// call GPU at here
void read_thread() {
for(;;) {
std::shared_ptr<Session> req;
queue.pop(req);
// call gpu at here
std::string msg = "inference completed";
boost::system::error_code err;
asio::write(req->socket, asio::buffer(msg), err);
req->socket.close();
}
}
class Server {
tcp::acceptor acceptor;
public:
explicit Server(asio::io_context &io_context, unsigned short port):
acceptor(io_context, tcp::endpoint(tcp::v4(), port))
{}
void doAccept() {
acceptor.async_accept([this](const boost::system::error_code &err, tcp::socket socket) {
if(err) {
std::cerr << err.message() << std::endl;
}else {
std::make_shared<Session>(std::move(socket))->start();
}
doAccept();
});
}
};
int main() {
std::thread reader(read_thread);
asio::io_service io_service;
Server server(io_service, 12346);
server.doAccept();
io_service.run();
reader.join();
} |
import React, { useState, useEffect } from 'react';
import axios from 'axios';
import Match from '../home/Match';
import {
mdiCardsHeartOutline,
mdiChevronRight,
mdiMessageReplyOutline,
} from '@mdi/js';
import Icon from '@mdi/react';
import ExploreNavbar from './ExploreNavbar';
import MatchDetail from '../home/OpenMatch';
import Message from './Message';
import Messages from './Messages';
import whiteRing from '../images/white-ring.png';
const ExploreHome = () => {
const [userInfo, setUserInfo] = useState({
username: '',
email: '',
location: '',
school: '',
interests: [],
likes: [],
matches: [],
description: '',
userImage: '',
firstName: '',
email: '',
});
const [usersToExplore, setUsersToExplore] = useState([]);
const [currentIndex, setCurrentIndex] = useState(0);
const [activeView, setActiveView] = useState('matches');
const [showMatchDetails, setShowMatchDetails] = useState(false);
const [selectedMatchId, setSelectedMatchId] = useState(null);
const [currentRightView, setCurrentRightView] = useState('default');
const [isMatchConfirmed, setIsMatchConfirmed] = useState(false);
useEffect(() => {
fetchUserInfo();
fetchUsersToExplore();
}, []);
const fetchUsersToExplore = async () => {
try {
const userId = localStorage.getItem('userId');
const response = await axios.get(`/api/explore/users/${userId}`);
const usersData = await Promise.all(
response.data.map(async (user) => {
let imageDataUrl = '';
if (
user.userImage &&
user.userImage.data &&
user.userImage.contentType
) {
const blob = new Blob([new Uint8Array(user.userImage.data.data)], {
type: user.userImage.contentType,
});
imageDataUrl = await new Promise((resolve, reject) => {
const reader = new FileReader();
reader.onloadend = () => resolve(reader.result);
reader.onerror = reject;
reader.readAsDataURL(blob);
});
}
let interestsArray = [];
if (Array.isArray(user.interests) && user.interests.length > 0) {
try {
interestsArray = JSON.parse(user.interests[0]);
} catch (e) {
console.error('Error parsing interests:', e);
interestsArray = [];
}
} else if (typeof user.interests === 'string') {
try {
interestsArray = JSON.parse(user.interests);
} catch (e) {
console.error('Error parsing interests:', e);
interestsArray = [];
}
}
const institution = user.institution?.replace(/"/g, '') || '';
const location = user.location?.replace(/"/g, '') || '';
const description = user.description?.replace(/"/g, '') || '';
return {
...user,
userImage: imageDataUrl,
interests: interestsArray,
institution,
location,
description,
};
})
);
setUsersToExplore(usersData);
} catch (error) {
console.error('Error fetching users:', error);
}
};
const showExplorePage = () => {
setCurrentRightView('matches');
};
const fetchUserInfo = async () => {
const userId = localStorage.getItem('userId');
if (!userId) {
console.log('No user ID found');
return;
}
try {
const response = await axios.get(`/api/profile/${userId}`);
const {
username,
email,
location,
age,
school,
interests,
likes,
matches,
description,
userImage,
} = response.data;
const firstName = response.data.firstName?.replace(/"/g, '') || '';
const lastName = response.data.lastName?.replace(/"/g, '') || '';
const imageDataUrl = userImage
? `data:${userImage.contentType};base64,${userImage.data}`
: '';
setUserInfo({
username,
email,
location,
age,
school,
interests,
likes,
matches,
description,
userImage: imageDataUrl,
firstName,
lastName,
});
} catch (error) {
console.error('Error fetching user info:', error);
}
console.log('image', userInfo.userImage);
};
const handleMatchSelect = async (selectedId) => {
try {
const response = await axios.post(
`/api/notifications/explore/${selectedId}`
);
console.log(response.data);
} catch (error) {
console.error('Error updating match exploration status:', error);
}
setShowMatchDetails(true);
setSelectedMatchId(selectedId);
console.log(selectedMatchId);
setCurrentRightView('matchDetail');
};
const handleMessageClick = (matchId) => {
console.log('here we are', matchId);
setSelectedMatchId(matchId);
setCurrentRightView('message');
};
const handleUserInteraction = async (liked, likedUserId) => {
const cardElement = document.querySelector('.user-profile-card');
if (cardElement) {
cardElement.classList.add('fade-out-animation');
if (liked) {
try {
const userId = localStorage.getItem('userId');
const response = await axios.post(`/api/profile/like`, {
userId: userId,
likedUserId: likedUserId,
});
if (response.data.message === 'Match found!') {
setIsMatchConfirmed(true);
console.log('Match found with user ID:', likedUserId);
} else {
console.log('Liked user with ID:', likedUserId);
}
} catch (error) {
console.error('Error updating likes:', error);
}
}
// setTimeout(() => {
// setCurrentIndex(currentIndex + 1);
// cardElement.classList.remove('fade-out-animation');
// // find a way to remove the "its a match, maybe display none class"
// }, 500);
}
};
const setActiveViewWithStyle = (view) => {
setActiveView(view);
};
return (
<div className='explore-home-container'>
<div className='explore-left'>
<div className='current-user'>
<img
src={userInfo.userImage}
alt={userInfo.username}
className='user-image'
/>
<div className='current-user-info'>
<h4>
{userInfo.firstName} {userInfo.lastName}
</h4>
<h4 className='current-email'>{userInfo.email} </h4>
</div>
</div>
<hr className='explore-hr' />
<div className='matches-messages-container relative bg-black rounded-full overflow-hidden cursor-pointer'>
<div
className={`slider-indicator rounded-full transition-all duration-300 ease-in-out`}
style={{
transform: `translateX(${
activeView === 'matches' ? '0' : '100%'
})`,
}}
></div>
<button
onClick={() => setActiveViewWithStyle('matches')}
className={`toggle-button absolute w-1/2 top-0.5 ${
activeView === 'matches' ? 'text-white' : 'text-gray-400'
}`}
>
Matches
</button>
<button
onClick={() => setActiveViewWithStyle('messages')}
className={`toggle-button absolute w-1/2 top-0.5 right-0 ${
activeView === 'messages' ? 'text-white' : 'text-gray-400'
}`}
>
Messages
</button>
</div>
{activeView === 'matches' && (
<div className='explore'>
{userInfo.matches.length > 0 ? (
userInfo.matches.map((matchId, index) => (
<Match
key={index}
matchId={matchId}
onSelectMatch={handleMatchSelect}
/>
))
) : (
<div className='bg-inherit'>
<h2 className='bg-inherit'>You have no matches yet</h2>
<h4 className='bg-inherit text-gray-400'>
Explore to receive matches
</h4>
</div>
)}
</div>
)}
{activeView === 'messages' && (
<div className='explore'>
<Messages onSelectMessage={handleMessageClick} />
</div>
)}
</div>
{isMatchConfirmed && (
<div className='match-confirmed'>
<h2>It's a Match!</h2>
</div>
)}
<div className='explore-right'>
<ExploreNavbar onExploreClick={showExplorePage} />
{currentRightView === 'matchDetail' ? (
<div>
<MatchDetail matchId={selectedMatchId} />
<div
className='message-button'
onClick={() => handleMessageClick(selectedMatchId)}
>
<h4>Message</h4>
<Icon
className='message-icon'
path={mdiMessageReplyOutline}
size={1}
/>
</div>
</div>
) : currentRightView === 'message' && selectedMatchId ? (
<Message matchId={selectedMatchId} />
) : usersToExplore.length > 0 &&
currentIndex < usersToExplore.length ? (
<div className='card-wrapper'>
<div className='user-profile-card'>
<div className='user-card-top'>
<div className='user-info'>
<img
src={usersToExplore[currentIndex].userImage}
alt={usersToExplore[currentIndex].username}
className='profile-image'
/>
</div>
<div className='user-information'>
<h2 className='font-semibold'>
{usersToExplore[currentIndex].username}{' '}
</h2>
<h3 className='font-light'>
<span className='gray bg-inherit'>Age:</span>{' '}
{usersToExplore[currentIndex].age}{' '}
</h3>
<h3 className='font-light'>
<span className='gray bg-inherit'>Location:</span>{' '}
{usersToExplore[currentIndex].location}
</h3>
<h3 className='font-light'>
<span className='gray bg-inherit'>Establishment:</span>{' '}
{usersToExplore[currentIndex].institution}
</h3>
</div>
</div>
<div className='user-card-bottom'>
<h3 className='user-card-title pb-2'>Subjects:</h3>
<div className='interest-card-container'>
{usersToExplore[currentIndex].interests.map(
(interest, index) => (
<div className='user-interests' key={index}>
{interest}
</div>
)
)}
</div>
<h3 className='user-card-title py-5'>Description :</h3>
<div className='user-details'></div>
<div className='user-description'>
<p>{usersToExplore[currentIndex].description}</p>
</div>
</div>
</div>
<div className='next-card-placeholder'></div>
<div>
{' '}
<Icon
onClick={() => handleUserInteraction(false)}
path={mdiChevronRight}
size={2}
horizontal
vertical
rotate={180}
className='next-card-icon'
/>
</div>
<div className='interaction-buttons'>
<div
className='like'
onClick={() =>
handleUserInteraction(true, usersToExplore[currentIndex]._id)
}
>
<Icon
path={mdiCardsHeartOutline}
title='like'
size={1.1}
horizontal
vertical
rotate={180}
className='like-icon'
/>
<h3 className='font-medium'>Like</h3>
</div>
<div
className='next'
onClick={() => handleUserInteraction(false)}
>
<Icon
path={mdiChevronRight}
title='checkmark'
size={1.5}
horizontal
vertical
rotate={180}
className='next-icon gray'
/>
<h3 className='gray font-medium'>Next</h3>
</div>
</div>
</div>
) : (
<div
id='explore-end'
style={{
display: 'flex',
justifyContent: 'center',
alignItems: 'center',
position: 'relative',
width: '300px',
height: '300px',
}}
>
<img
src={whiteRing}
style={{
width: '100%',
height: '100%',
background: 'none',
}}
alt=''
/>
<div
style={{
position: 'absolute',
textAlign: 'center',
width: '70%',
top: '50%',
transform: 'translateY(-50%)',
background: 'none',
}}
>
No more users to explore
</div>
</div>
)}
</div>
</div>
);
};
export default ExploreHome; |
import API_KEY from "./apikey.js";
import weatherConditions from "./assets/weather_conditions.json" assert { type: "json" };
const search = document.getElementById("search");
const suggestions = document.querySelector(".suggestions");
search.addEventListener("input", async () => {
const value = search.value;
suggestions.innerHTML = "";
if (value && value.length >= 3) {
const request = await fetch(
`https://api.weatherapi.com/v1/search.json?key=${API_KEY}&q=${value}`,
{ mode: "cors" },
);
const data = await request.json();
data.forEach((item) => {
const elem = document.createElement("li");
elem.textContent = `${item.name}, ${item.country}`;
elem.addEventListener("click", async () => {
let data = await getWeatherDataByLocationID(item.id);
suggestions.innerHTML = "";
displayCurrentForecast(data);
displayWeeklyForecast(data);
search.value = "";
});
suggestions.appendChild(elem);
console.log(item);
});
}
});
function displayCurrentForecast(data) {
const forecast_today = data.forecast.forecastday[0];
document.querySelector(".cityName").textContent = data.location.name;
document.querySelector(".countryName").textContent = data.location.country;
const date = new Date(data.location.localtime);
document.querySelector(".time").textContent = `${
date.getHours() < 10 ? "0" + date.getHours() : date.getHours()
}:${date.getMinutes() < 10 ? "0" + date.getMinutes() : date.getMinutes()}`;
document.querySelector(".date").textContent =
`${date.getDayOfWeek()}, ${date.getDate()} ${date.getFullMonth()}`;
document.querySelector(".conditionText").textContent =
data.current.condition.text;
document.querySelector(".temp").textContent = data.current.temp_c + " °C";
document.querySelector(".feelslike").textContent =
"Feels like " + data.current.feelslike_c + " °C";
document.querySelector(".wind").textContent = data.current.wind_kph + " km/h";
document.querySelector(".humidity").textContent = data.current.humidity + "%";
document.querySelector(".rainChance").textContent =
forecast_today.day.daily_chance_of_rain + "%";
document.querySelector(".conditionIcon").src = getIconSrc(
data.current.condition.code,
data.current.is_day,
);
}
function displayWeeklyForecast(data) {
const weeklyForecast = document.querySelector(".weeklyForecast");
const children = weeklyForecast.children;
data.forecast.forecastday.forEach((day, index) => {
const current = document.querySelectorAll(".card")[index];
current.querySelector(".cardTempHigh").textContent =
day.day.maxtemp_c + " °C";
current.querySelector(".cardTempLow").textContent =
day.day.mintemp_c + " °C";
const date = new Date(day.date);
current.querySelector("header").textContent =
`${date.getDayOfWeek()}, ${date.getDate()} ${date.getFullMonth()}`;
current.querySelector("img").src = getIconSrc(day.day.condition.code, 1);
});
}
Date.prototype.getDayOfWeek = function () {
return [
"Sunday",
"Monday",
"Tuesday",
"Wednesday",
"Thursday",
"Friday",
"Saturday",
][this.getDay()];
};
Date.prototype.getFullMonth = function () {
return [
"January",
"February",
"March",
"April",
"May",
"June",
"July",
"August",
"September",
"October",
"November",
"December",
][this.getMonth()];
};
function getIconSrc(iconcode, is_day) {
const icon = weatherConditions.find((icon) => icon.code === iconcode).icon;
const time = is_day ? "day" : "night";
return `./assets/weather/64x64/${time}/${icon}.png`;
}
function createElement(element, classname, textContent) {
const el = document.createElement(element);
el.classname = classname;
el.textContent = textContent;
return el;
}
function displayLoading() {
document.querySelector("#content").classList.add("hidden");
document.querySelector("#loadingscreen").classList.add("display");
}
function hideLoading() {
document.querySelector("#loadingscreen").classList.remove("display");
document.querySelector("#content").classList.remove("hidden");
}
async function getWeatherDataByIp() {
displayLoading();
const ip = await getIp();
const response = await fetch(
`https://api.weatherapi.com/v1/forecast.json?key=${API_KEY}&q=${ip}&days=3`,
{ mode: "cors" },
);
const data = await response.json();
hideLoading();
return data;
}
async function getWeatherDataByLocationID(id) {
displayLoading();
const response = await fetch(
`https://api.weatherapi.com/v1/forecast.json?key=${API_KEY}&q=id:${id}&days=5`,
{ mode: "cors" },
);
const data = await response.json();
hideLoading();
return data;
}
async function getIp() {
const ip_response = await fetch("https://api.ipify.org/?format=json", {
mode: "cors",
});
const ip = await ip_response.json();
return ip.ip;
}
let data = await getWeatherDataByIp();
console.log(data);
displayCurrentForecast(data);
displayWeeklyForecast(data); |
import OpenAI from 'openai';
import { NextRequest, NextResponse } from 'next/server';
import { Stream } from 'openai/streaming';
import { ulid } from 'ulidx';
import { createMessage } from '@/app/api/utils/messages';
import { getOpenAIObjectForAssistant } from '@/app/api/openai/util';
import prisma from '@/app/api/utils/prisma';
const getId = (req: Request) => {
const url = new URL(req.url);
return url.pathname.split('/').splice(-2, 1)[0];
};
export async function POST(req: NextRequest, res: NextResponse) {
try {
let threadId = getId(req);
let assistantId = req.headers.get('X-Assistant-Id');
const openai = (await getOpenAIObjectForAssistant(req)) as OpenAI;
const runResponse: Stream<any> = await openai.beta.threads.runs.create(
threadId,
{ assistant_id: assistantId ? assistantId : '', stream: true }
);
let msgId = 'msg_' + ulid();
let buffer = '';
const stream = new ReadableStream({
async start(controller) {
try {
let completed = false;
for await (const event of runResponse) {
if (event.event === 'thread.message.delta') {
let data = event.data.delta.content[0].text.value;
buffer += data;
controller.enqueue(data);
}
if (event.event === 'thread.run.completed') {
completed = true;
}
}
if (completed) {
await createMessage(
assistantId ? assistantId : '',
threadId,
msgId,
buffer
);
}
} catch (error) {
controller.error(error);
}
controller.close();
},
});
return new Response(stream);
} catch (err: any) {
console.log(err);
return Response.json({ message: err.message }, { status: err.status });
}
} |
# Standard Library Imports
from datetime import datetime
# 3rd Party Imports
# Local Imports
from PokeAlarm.Utils import get_time_as_str, get_gmaps_link, \
get_applemaps_link, get_dist_as_str
from . import Event
from PokeAlarm import Unknown
class Egg(Event):
""" Event representing the change occurred in a Gym. """
def __init__(self, data):
""" Creates a new Stop Event based on the given dict. """
super(Egg, self).__init__('egg')
check_for_none = Event.check_for_none
# Identification
self.gym_id = data.get('gym_id')
# Time Remaining
self.hatch_time = datetime.utcfromtimestamp(
data.get('start') or data.get('raid_begin')) # RM or Monocle
self.raid_end = datetime.utcfromtimestamp(
data.get('end') or data.get('raid_end')) # RM or Monocle
# Location
self.lat = float(data['latitude'])
self.lng = float(data['longitude'])
self.distance = Unknown.SMALL # Completed by Manager
self.direction = Unknown.TINY # Completed by Manager
# Egg Info
self.egg_level = check_for_none(int, data.get('level'), 0)
# Gym Details (currently only sent from Monocle)
self.gym_name = check_for_none(
str, data.get('name'), Unknown.REGULAR).strip()
self.gym_description = check_for_none(
str, data.get('description'), Unknown.REGULAR).strip()
self.gym_image_url = check_for_none(
str, data.get('url'), Unknown.REGULAR)
self.current_team_id = Unknown.TINY
def generate_dts(self, locale):
""" Return a dict with all the DTS for this event. """
hatch_time = get_time_as_str(self.hatch_time)
raid_end_time = get_time_as_str(self.raid_end)
return {
# Identification
'gym_id': self.gym_id,
# Time Remaining
'hatch_time_left': hatch_time[0],
'12h_hatch_time': hatch_time[1],
'24h_hatch_time': hatch_time[2],
'raid_end': raid_end_time[0],
'12h_raid_end': raid_end_time[1],
'24h_raid_end': raid_end_time[2],
# Location
'lat': self.lat,
'lng': self.lng,
'lat_5': "{:.5f}".format(self.lat),
'lng_5': "{:.5f}".format(self.lng),
'distance': get_dist_as_str(self.distance),
'direction': self.direction,
'gmaps': get_gmaps_link(self.lat, self.lng),
'applemaps': get_applemaps_link(self.lat, self.lng),
# Egg info
'egg_level': self.egg_level,
# Gym Details
'gym_name': self.gym_name,
'gym_description': self.gym_description,
'gym_image_url': self.gym_image_url,
'team_id': self.current_team_id,
'team_name': locale.get_team_name(self.current_team_id),
'team_leader': locale.get_leader_name(self.current_team_id)
} |
<?php
namespace Database\Factories;
use App\Models\User;
use Illuminate\Database\Eloquent\Factories\Factory;
/**
* @extends \Illuminate\Database\Eloquent\Factories\Factory<\App\Models\Expense>
*/
class ExpenseFactory extends Factory
{
/**
* Define the model's default state.
*
* @return array<string, mixed>
*/
public function definition()
{
return [
'title' => $this->faker->word(),
'user_id' => User::factory(),
'amount' => $this->faker->numberBetween(0, 10000),
];
}
} |
[](https://gptcall.net/chat.html?data=%7B%22contact%22%3A%7B%22id%22%3A%2245kpKz5BpHuRK6l_4XWV8%22%2C%22flow%22%3Atrue%7D%7D)
# GymGPT | [Start Chat](https://gptcall.net/chat.html?data=%7B%22contact%22%3A%7B%22id%22%3A%2245kpKz5BpHuRK6l_4XWV8%22%2C%22flow%22%3Atrue%7D%7D)
This prompt creates a gym plan for the user
# Prompt
```
let's play a game, you are going to act as GymGPT, an artificial intelligence capable of telling me gym plans, based on what the user says. for example, if the user wants a plan to workout on monday an saturday and he wants to train the back, you must give him a list of exercises to train the back based on what intensity the user asks for, that he will set later. obviously you have to be balanced with the exercises and if for example, he wanted to do the back on monday and he wanted to train something on tuesday you can't give him the back again because he would be physically destroyed. you'll be based on commands, here they are:
/new (this generates a new gym plan, but it will require to ask the user some questions in the exact format i’m going to give you: “ # GymGPT Plan
Intensity of the training:
Places to train:
Days you want to train:
Please give an answer to this question in the following syntax: “7, Full Body, Monday, Thursday, Saturday””, and after the user gave his input, you must show the exercises like this “ # GymGPT Plan
Intensity of the training: {user input}(it must be a value from 1 to 10)
Places to train: {user input}
Days you want to train: {user input}
According to these informations, the plan i created for you is:
{first exercise}: {explanation of it}
{second exercise}: {explanation of it}
(and so on until you gave the user all the exercises)”)
/modify {exercise to modify} = {new exercise} (this makes the user modify an exercise and replace it with the exercise he wants)
/add {exercise} (this lets the user add an exercise of his choice to the plan).
these are all the commands, and there will be an additional command that is “/help {command}”, this basically shows the syntax of the commands just like i showed you before, like this “/modify {exercise to modify} = {new exercise}” and so on with the other commands.
your first output is “ # GymGPT “, and the subtitle is “ ### *Made by Shadow* “, then create another subtitle that says “If you find any bug in this prompt, please contact [Shadow’s Secondary Number](wa.me/+16039996703), if the number isn’t available, contact [Shadow’s Telegram](https://t.me/Shadow_is_here666) and report the bug.”. then create another subtitle and finally say “Here are the commands:
/new
/modify
/add
To know their syntax, write “/help {command}”.”.
```
## Conversation
**ASSISTANT**: # GymGPT
### *Made by Shadow*
If you find any bug in this prompt, please contact [Shadow’s Secondary Number](wa.me/+16039996703), if the number isn’t available, contact [Shadow’s Telegram](https://t.me/Shadow_is_here666) and report the bug.
### Here are the commands:
/new
/modify
/add
To know their syntax, write "/help {command}".
**USER**: /new
**ASSISTANT**: To generate a new gym plan, please provide the following information in the specified format:
```
# GymGPT Plan
Intensity of the training: {value from 1 to 10}
Places to train: {muscle groups or full body}
Days you want to train: {comma-separated list of days}
```
Please provide your answers in the above format.
**USER**: 7, Full body, Monday, Wednesday, Saturday
**ASSISTANT**: # GymGPT Plan
Intensity of the training: 7
Places to train: Full body
Days you want to train: Monday, Wednesday, Saturday
According to these informations, the plan I created for you is:
- Squats: Squats are a compound exercise that targets multiple muscle groups, including the quadriceps, hamstrings, glutes, and core. They help improve lower body strength and stability.
- Bench Press: Bench press is a compound exercise that primarily targets the chest, shoulders, and triceps. It helps build upper body strength and muscle mass.
- Deadlifts: Deadlifts are a compound exercise that targets the entire posterior chain, including the hamstrings, glutes, lower back, and traps. They are excellent for overall strength and muscle development.
- Shoulder Press: Shoulder press is a great exercise for targeting the shoulders, specifically the deltoids. It helps build shoulder strength and improves upper body pressing movements.
- Rows: Rows are an effective exercise for targeting the back muscles, including the lats, rhomboids, and traps. They help improve posture and upper body pulling strength.
- Lunges: Lunges are a unilateral exercise that targets the quadriceps, glutes, and hamstrings. They help improve lower body strength and balance.
- Plank: Plank is a core exercise that targets the abdominal muscles and helps improve core stability and endurance.
Feel free to adjust the number of sets, reps, and weights based on your fitness level and goals. |
import "dart:math";
import "package:flutter/material.dart";
import 'package:random_avatar/random_avatar.dart';
// import "package:get/get.dart";
import "package:go_router/go_router.dart";
// import 'package:tripmating/Controller/SignupController.dart';
import "package:tripmating/model/login-model/SignupDTO.dart";
import "package:tripmating/service/LoginService.dart";
enum Gender { male, female }
class SignUp extends StatefulWidget {
const SignUp({super.key});
@override
State<SignUp> createState() => _SignUpState();
}
class _SignUpState extends State<SignUp> {
// final SignupController _signupController = Get.put(SignupController());
final _emailController = TextEditingController();
final _passwordController = TextEditingController();
final _nameController = TextEditingController();
final _phoneNumberController = TextEditingController();
final _birthDateController = TextEditingController();
final _genderController = TextEditingController();
Gender gender = Gender.male;
String avatarKey = "000000000000";
Widget avatar = RandomAvatar("000000000000", width: 100, height: 100);
@override
void dispose() {
_emailController.dispose();
_passwordController.dispose();
_nameController.dispose();
_phoneNumberController.dispose();
_birthDateController.dispose();
_genderController.dispose();
super.dispose();
}
@override
void initState() {
makeRandomAvatar();
super.initState();
}
Widget makeRandomAvatar(){
String avatarKey = "";
for(int i = 0; i < 6; i++){
avatarKey += Random().nextInt(48).toString();
}
avatar = RandomAvatar(avatarKey, width: 100, height: 100);
return avatar;
}
void remakeRandomAvatar(){
String avatarKey = "";
for(int i = 0; i < 6; i++){
avatarKey += Random().nextInt(48).toString();
}
setState(() {
avatar = RandomAvatar(avatarKey, width: 100, height: 100);
});
print(avatarKey);
}
@override
Widget build(BuildContext context) {
return SafeArea(
child: Scaffold(
appBar: PreferredSize(preferredSize: const Size.fromHeight(50), child: AppBar(
title: const Text("Sign Up"),
),),
body: SingleChildScrollView(
child: SafeArea(
child: Padding(
padding: const EdgeInsets.all(20.0),
child: Column(
//email, password, name, phoneNumber, profileImg, birthDate, gender
children: [
Stack(
alignment: Alignment.bottomRight,
children: [
avatar,
IconButton(onPressed: (){ remakeRandomAvatar(); }, icon: const Icon(Icons.refresh))
],
),
const SizedBox(height: 30),
SizedBox(
width: 300,
height: 50,
child: TextField(
decoration: const InputDecoration(
border: OutlineInputBorder(),
labelText: "email",
),
controller: _emailController,
),
),
const SizedBox(height: 10),
SizedBox(
width: 300,
height: 50,
child: TextField(
obscureText: true,
decoration: const InputDecoration(
border: OutlineInputBorder(),
labelText: "password",
),
controller: _passwordController,
),
),
const SizedBox(height: 10),
SizedBox(
width: 300,
height: 50,
child: TextField(
decoration: const InputDecoration(
border: OutlineInputBorder(),
labelText: "name",
),
controller: _nameController,
),
),
const SizedBox(height: 10),
SizedBox(
width: 300,
height: 50,
child: TextField(
decoration: const InputDecoration(
border: OutlineInputBorder(),
labelText: "phone number",
),
controller: _phoneNumberController,
keyboardType: TextInputType.phone,
),
),
const SizedBox(height: 10),
SizedBox(
width: 300,
height: 50,
child: TextField(
decoration: const InputDecoration(
border: OutlineInputBorder(),
labelText: "birthDate(ex.2000-01-01})",
),
controller: _birthDateController,
keyboardType: TextInputType.datetime,
),
),
const SizedBox(height: 10),
Row(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.center,
children: [
SizedBox(
width: 140,
height: 30,
child: RadioListTile(
title: const Text("Male"),
value: Gender.male,
groupValue: gender,
onChanged: (value) {
setState(() {
gender = value!;
});
},
),
),
SizedBox(
width: 160,
height: 30,
child: RadioListTile(
title: const Text("Female"),
value: Gender.female,
groupValue: gender,
onChanged: (value) {
setState(() {
gender = value!;
});
},
),
),
],
),
const SizedBox(height: 30),
Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: [
ElevatedButton(
onPressed: () {
LoginService.signUp(SignupDTO(
email: _emailController.text,
password: _passwordController.text,
name: _nameController.text,
phoneNumber: _phoneNumberController.text,
profileImg: avatarKey,
birthDate: DateTime.parse(_birthDateController.text),
gender: gender == Gender.male ? "MALE" : "FEMALE",
));
//post
context.go("/login");
},
child: Text("sign up")),
ElevatedButton(
onPressed: () {
context.go("/login");
},
child: Text("cancel")),
],
),
]),
),
),
),
),
);
}
} |
package scalatagame
import (
"github.com/alarmfox/game-repository/api"
"github.com/alarmfox/game-repository/model"
"gorm.io/gorm"
)
type Repository struct {
db *gorm.DB
}
func NewRepository(db *gorm.DB) *Repository {
return &Repository{
db: db,
}
}
func (gs *Repository) Create(r *CreateRequest) (ScalataGame, error) {
var (
scalatagame = model.ScalataGame{
ScalataName: r.ScalataName,
PlayerID: r.PlayerID,
CreatedAt: r.CreatedAt,
}
)
err := gs.db.Transaction(func(tx *gorm.DB) error {
return tx.Create(&scalatagame).Error
})
if err != nil {
return ScalataGame{}, api.MakeServiceError(err)
}
return fromModel(&scalatagame), nil
}
func (gs *Repository) FindById(id int64) (ScalataGame, error) {
var scalataGame model.ScalataGame
// err := gs.db.
// //Preload("Players").
// First(&scalataGame, id).
// Error
err := gs.db.
Preload("Games").
First(&scalataGame, id).
Error
return fromModel(&scalataGame), api.MakeServiceError(err)
}
func (gs *Repository) FindByInterval(accountId string, i api.IntervalParams, p api.PaginationParams) ([]ScalataGame, int64, error) {
var (
scalataGames []model.ScalataGame
n int64
err error
)
// TODO: check if accountId is used in this case
// if accountId != "" {
// err = gs.db.Transaction(func(tx *gorm.DB) error {
// association := tx.Model(&model.Player{AccountID: accountId}).
// Scopes(api.WithInterval(i, "games.created_at"),
// api.WithPagination(p)).
// Order("games.created_at desc").
// Association("Games")
// n = association.Count()
// return association.Find(&scalataGames)
// })
// } else {
err = gs.db.Preload("Games").Scopes(api.WithInterval(i, "scalata_games.created_at"),
api.WithPagination(p)).
Find(&scalataGames).
Count(&n).
Error
// }
res := make([]ScalataGame, len(scalataGames))
for i, scalata := range scalataGames {
res[i] = fromModel(&scalata)
}
return res, n, api.MakeServiceError(err)
}
func (gs *Repository) Delete(id int64) error {
db := gs.db.
Where(&model.ScalataGame{ID: id}).
Delete(&model.ScalataGame{})
if db.Error != nil {
return api.MakeServiceError(db.Error)
} else if db.RowsAffected < 1 {
return api.ErrNotFound
}
return nil
}
func (gs *Repository) Update(id int64, r *UpdateRequest) (ScalataGame, error) {
var (
scalataGame model.ScalataGame = model.ScalataGame{ID: id}
err error
)
err = gs.db.Model(&scalataGame).Updates(r).Error
if err != nil {
return ScalataGame{}, api.MakeServiceError(err)
}
return fromModel(&scalataGame), api.MakeServiceError(err)
} |
import { nanoid } from "nanoid";
import { z } from "zod";
import {
createTRPCRouter,
publicProcedure,
protectedProcedure,
} from "~/server/api/trpc";
import { messageArrayValidator, messageValidator } from "~/utils/utils";
export const ChatRouter = createTRPCRouter({
ChatMessages: protectedProcedure
.input(z.object({ chatId: z.string() }))
.query(async ({ input, ctx }) => {
const chat = (
await ctx.db.zrange(`chat:${input.chatId}:messages`, 0, -1)
).reverse();
messageArrayValidator.parse(chat);
return chat as Message[];
}),
chatPartner: protectedProcedure
.input(z.object({ chatId: z.string() }))
.query(async ({ input, ctx }) => {
const [userId1, userId2] = input.chatId.toString().split("--");
const chatPartnerId = ctx.session.user.id === userId1 ? userId2 : userId1;
return await ctx.db.get(`user:${chatPartnerId as string}`);
}),
sendMessage: protectedProcedure
.input(z.object({ text: z.string(), chatId: z.string() }))
.mutation(async ({ input, ctx }) => {
const [userId1, userId2] = input.chatId?.toString().split("--");
if (ctx.session.user.id !== userId1 && ctx.session.user.id !== userId2) {
return "UNAUTHORIZED!!!";
}
const chatPartnerId = ctx.session.user.id === userId1 ? userId2 : userId1;
const friendID = await ctx.db.smembers(
`user:${ctx.session.user.id}:friends`
);
const isFriend = friendID.includes(chatPartnerId as string);
if (!isFriend) return "UNAUTHORIZED!!!";
const sender = await ctx.db.get(`user:${ctx.session.user.id}`);
const timestamp = Date.now();
const text = input.text;
const messageData: Message = {
id: nanoid(),
senderId: ctx.session.user.id,
text,
timestamp,
};
const message = messageValidator.parse(messageData);
await ctx.db.zadd(`chat:${input.chatId}:messages`, {
score: timestamp,
member: JSON.stringify(message),
});
return "OK";
}),
}); |
import {Field, ID, ObjectType, registerEnumType} from "type-graphql";
import {Role} from "@prisma/client";
import {Member} from "./Member";
@ObjectType()
export class Student {
@Field(type => ID)
id: number;
@Field()
name: string;
@Field()
surname: string;
@Field()
uid: string;
@Field()
email: string;
@Field(() => Role)
role: Role;
@Field(type => Member, {
nullable: true
})
member?: Member | null;
}
registerEnumType(Role, {
name: "Role",
}); |
<p align="center">
<img width="900px" src="https://github.com/beatriz-lafuente/AirplaneDetection/blob/main/images/plane1.jpg" align="center" alt="Computer Vision: Airplane Detection" />
<h2 align="center">Computer Vision: Airplane Detection</h2>
<p align="center">The goal of this project is to use a CNN that can identify airplanes and create a rectangle around their position.</p>
# Index
- [Introduction](#introduction)
- [Workflow](#workflow)
- [Image Collection](#image-collection)
- [Create Ground Truth](#create-ground-truth)
- [Detect Objects](#detect-objects)
- [Calculate IoU](#calculate-iou)
- [Calculate Precision and Recall](#calculate-precision-and-recall)
- [Conclusion](#conclusion)
# Introduction
In this project I use a dataset of 18 images containning one or more airplanes. The goal is to use a CNN that can identify these airplanes and create a rectangle around their position. This is a problem of object detection, these CNN's are hard to train, that's why in this example I will used a pre-trained CNN for object detection, in this case MobileNet, know for being a light-weighted neuronal network.
# Workflow
<p align="center">
<img width="800px" src="https://user-images.githubusercontent.com/121397357/209863857-bf04192a-4e59-4373-ac39-79dda1ae9428.png" align="center" />
## Image Collection
The first step of this script is to gather the 18 images, that were extracted from the internet. After the image collection phase, some of the collected images are shown bellow. It is possible to see that the images contain different number and types of airplanes.
<p align="center">
<img width="600px" src="https://user-images.githubusercontent.com/121397357/209855221-1081fb63-8c3e-47ad-a757-c7d29ed3498e.png" align="center" />
## Create Ground Truth
In this second phase, imageLabel is used to draw rectangles around the objects to detect, and save their "coordinates" into a XML file.
This process is called the definition of the ground truth, if this was a classification or regression problem, the ground truth would be the target variable.
Since the target variable is not available, we need to create it.
This phase is important to evaluate the performance of the model, given that it will allow the comparison of the identification of objects between humans and the CNN.
These annotated images are saved into the `images/gt` directory located in the main branch.
## Detect Objects
### Get locations of the Detected Objects
To detect the airplanes, pre-trained MobileNet CNN is used. Firstly, the import of the model and some extra need information is done, such as the configuration file of the model, and the classes that this model is trained to detect.
These informations are saved in `MobileNet` directory located in the main branch.
* First, import model with CV2 and TensorFlow
* Define confidence level, but what is this value?
The algorithm will detect objects of several classes, and for each detection there will be a probability level. For example, the algorithm may detect a car with 0.99 trust or detect a sheep with 0.1 trust.
So the `CONFIDENCE_THRESHOLD` variable will be used to select the detections that present a trust level above 0.50.
```{python}
# Define threshold
CONFIDENCE_THRESHOLD = 0.50
# Load model
model = cv2.dnn.readNet(model=MODEL_FILE, config=CONFIG_FILE, framework="TensorFlow")
```
The following code itters through all the images.
For each image, the MobileNet is used to detect objects of 91 diferent classes.
From all of these detections, only consider the ones that are airplanes with a trust level higher than 0.5, these are saved into a dataframe (predicted_boxes).
After the execution of this code, images with rectangles, corresponding to the identified airplanes, are saved into the directory `images/predicted`.
This will allow the visualization of the original images with the detected objects.
```{python}
predicted_boxes = pd.DataFrame({})
TP = 0
FP = 0
# Get location of Detected Objects
for image_path in os.listdir("images/normal"):
# Read image and get shape
img = cv2.imread(f"images/normal/{image_path}")
img_height, img_width, img_channels = img.shape
img_height, img_width, channels = img.shape
# Normalize data dimensions
blob = cv2.dnn.blobFromImage(image=img, size=(300, 300), swapRB=True)
model.setInput(blob)
output = model.forward()
for detection in output[0, 0, :, :]: #[0, class_id, trust, box_x, box_y, box_w, box_h]
# Trust
confidence = detection[2]
if detection[1] == 5:
if confidence > CONFIDENCE_THRESHOLD:
class_id = detection[1] # Class id
class_name = class_names[int(class_id) - 1]
# obter as coordenadas e dimensoes das bounding boxes, normalizadas para coordenadas da imagem
bbox_x = detection[3] * img_width
bbox_y = detection[4] * img_height
bbox_width = detection[5] * img_width
bbox_height = detection[6] * img_height
predicted_boxes = predicted_boxes.append({"name": image_path,
"x": bbox_x,
"y": bbox_y,
"x_size": bbox_width,
"y_size": bbox_height}, ignore_index=True)
# colocar retangulos e texto a marcar os objetos identificados
cv2.rectangle(img, (int(bbox_x), int(bbox_y)), (int(bbox_width), int(bbox_height)), 1, thickness=2)
cv2.putText(img, class_name, (int(bbox_x), int(bbox_y - 5)), cv2.FONT_HERSHEY_SIMPLEX, 1, 1, 2)
TP += 1
else:
FP += 1
cv2.imwrite("images/predicted/"+image_path, img)
```
### Get locations of Ground Truth
To evaluate the performance of the model the locations of the ground truth and the detected airplanes are needed.
The locations of the detected objects were already calculated on the last code chunk, and saved into the predicted_boxes dataframe.
Now it's necessary to store the same information for the ground truth, the following code will save the locations inside the actual_boxes dataframe.
```{python}
actual_boxes = pd.DataFrame({})
for image_path in os.listdir("images/gt"):
tree = ET.parse(f'images/gt/{image_path}')
root = tree.getroot()
sample_annotations = []
for neighbor in root.iter('bndbox'):
xmin = int(neighbor.find('xmin').text)
ymin = int(neighbor.find('ymin').text)
xmax = int(neighbor.find('xmax').text)
ymax = int(neighbor.find('ymax').text)
actual_boxes = actual_boxes.append({"name": image_path,
"x": xmin,
"y": ymin,
"x_size": xmax,
"y_size": ymax}, ignore_index=True)
```
## Calculate IoU
Now it is possible to calculate the intersection over union metric.
This metric is used to evaluate the performance of the model in corretly identifying the locations of the objects. To do that, a ratio between the intersection of both rectangles and the union of both rectangles is calculated. This way, if the two rectangles completely overlap, the areas of the intersection rectangle and union rectangle are coincident, giving origin to a IoU of 1. On the other hand, if the two rectangles don't share any area in common, the area of the intersection rectangle is 0, giving origin to a IoU of 0.
* The function bellow compute the IoU:
```{python}
def IoU(boxA, boxB):
# determine the (x, y) - coordinates of the intersection rectangle
xA = max(boxA[1], boxB[1])
yA = max(boxA[3], boxB[3])
xB = min(boxA[2], boxB[2])
yB = min(boxA[4], boxB[4])
# compute the area of intersection rectangle
interArea = max(0, xB - xA + 1) * max(0, yB - yA + 1)
# Area of both boxes
boxAArea = (boxA[2] - boxA[1] + 1) * (boxA[4] - boxA[3] + 1)
boxBArea = (boxB[2] - boxB[1] + 1) * (boxB[4] - boxB[3] + 1)
return interArea / float(boxAArea + boxBArea - interArea)
```
## Calculate Precision and Recall
* If `IoU > 0.5` -> classify the object detection as True Positive (TP)
* If `Iou < 0.5` -> wrong detection and classify as False Positive (FP)
* If ground truth is present in the image and model fail to detect the object -> classify as False Negative (FN)
The `precision` represents the percentage of identified objects that are actual airplanes, from all the identified objects.
The `recall` shows how accurate the detections are. In this case the value is 1, this means that all the identifyed objects are actual airplanes.
# Conclusion
The precision level is low because the model identifies 315 planes with a trust level under 0.5, and only 25 planes with a trust higher than 0.5.
Despite that the percentage of correctly identified airplanes is 100%, given that no planes were wrongly identified.
* * *
# :sparkling_heart: Support the project
If you liked this project please leave a star 🌟 and contributions are welcome! ❤️
Thanks! :heart: |
import { Component, OnDestroy, OnInit } from "@angular/core";
import { DocumentData, DocumentSnapshot, QueryDocumentSnapshot, QuerySnapshot } from "@angular/fire/firestore";
import { FormControl, FormGroup, Validators } from "@angular/forms";
import { MatDialog, MatDialogConfig } from "@angular/material/dialog";
import { ActivatedRoute, Router } from "@angular/router";
import { ConfirmDialogComponent } from "src/app/components/confirm-dialog/confirm-dialog.component";
import { Account } from "src/app/models/account.model";
import { AccountService } from "src/app/services/account.service";
import { ApplicationService } from "src/app/services/application.service";
import { ErrorUtils } from "src/app/utils/error.utils";
@Component({
selector: 'account-form',
templateUrl: 'account-form.component.html',
styleUrls: ['account-form.component.css']
})
export class AccountFormComponent implements OnInit {
id: string = '';
isEditing: boolean = false;
isLoading: boolean = true;
form: FormGroup;
dialogDeleteRef: any;
constructor(private accountService: AccountService, private router: Router, private _appService: ApplicationService, private _activatedRoute: ActivatedRoute, public dialog: MatDialog) {
this.form = new FormGroup({
name: new FormControl(null, Validators.required),
color: new FormControl(null, Validators.required)
});
this.id = this._activatedRoute.snapshot.paramMap.get('id') || '';
this.isEditing = this.id !== '';
this._appService.setBackArrowRoute('/account');
this._appService.setNavBar(this.isEditing ? 'Editar cuenta' : 'Crear cuenta');
}
ngOnInit(): void {
if (this.isEditing) {
this._loadData();
} else {
this.isLoading = false;
}
}
private _loadData() {
this.accountService.get(this.id)
.then((result: DocumentSnapshot<DocumentData>) => {
this.form.patchValue(result.data() || []);
this.isLoading = false;
})
.catch(error => ErrorUtils.handleError(error));
}
public save(): void {
this.isLoading = true;
if (this.isEditing) {
this.accountService.update({ id: this.id, ...this.form.value })
.then(() => {
this.router.navigate(['/account'])
})
.catch(error => ErrorUtils.handleError(error));
} else {
this.accountService.create(this.form.value)
.then(() => this.router.navigate(['/account']))
.catch(error => ErrorUtils.handleError(error));
}
}
onConfirmDelete(): void {
const dialogConfig = new MatDialogConfig();
dialogConfig.autoFocus = true;
dialogConfig.data = {
text: '¿Confirma que desea eliminar la cuenta?',
type: 'delete',
action: this.onDelete.bind(this, this.id),
}
this.dialogDeleteRef = this.dialog.open(ConfirmDialogComponent, dialogConfig);
}
onDelete(id: string): void {
this.isLoading = true;
this.accountService.delete(id)
.then(() => {
this.dialogDeleteRef.close();
this._appService.showToast('Cuenta borrada');
this.router.navigate(['/account'])
})
.catch(error => ErrorUtils.handleError(error));
}
} |
import { useState, useEffect } from "react";
import React from "react";
import IconBtn from "../../../../components/common/IconBtn";
import { useNavigate } from "react-router-dom";
import { useDispatch, useSelector } from "react-redux";
import { addJobPost } from "../../../../services/operations/jobPostAPI";
import { useForm } from "react-hook-form";
import { getAllServices } from "../../../../services/operations/serviceDetailsAPI";
import { Country, State, City } from 'country-state-city';
const PostJob = () => {
// console.log(Country.getAllCountries())
console.log("state: ",JSON.stringify(State.getAllStates()))
console.log("city: ", City.getCitiesOfCountry("TR"))
const { user } = useSelector((state) => state.profile);
// const { token } = useSelector((state) => state.auth)
const token = user.token;
console.log("token : ", token);
//token ki dikkat h kl check krungaa
const navigate = useNavigate();
const dispatch = useDispatch();
const [loading, setLoading] = useState(false)
const [services, setServices] = useState([]);
const [src1Checked, setSrc1Checked] = useState(false);
const [src2Checked, setSrc2Checked] = useState(false);
const [src3Checked, setSrc3Checked] = useState(false);
const [src4Checked, setSrc4Checked] = useState(false);
const {
register,
handleSubmit,
formState: { errors },
setValue,
watch,
} = useForm();
const watchedValues = watch();
const handleSrc1Change = () => {
setSrc1Checked(!src1Checked);
if (!src1Checked) {
setSrc2Checked(true);
} else {
setSrc2Checked(false);
}
};
const handleSrc2Change = () => {
setSrc2Checked(!src2Checked);
};
const handleSrc3Change = () => {
setSrc3Checked(!src3Checked);
if (!src3Checked) {
setSrc4Checked(true);
} else {
setSrc4Checked(false);
}
};
const handleSrc4Change = () => {
setSrc4Checked(!src4Checked);
};
useEffect(() => {
const getServices = async () => {
setLoading(true);
const services = await getAllServices();
if (services.length > 0) {
// console.log("categories", categories)
setServices(services);
}
setLoading(false);
};
// if form is in edit mode
// if (editCourse) {
// // console.log("data populated", editCourse)
// setValue("courseTitle", course.courseName)
// setValue("courseShortDesc", course.courseDescription)
// setValue("coursePrice", course.price)
// setValue("courseTags", course.tag)
// setValue("courseBenefits", course.whatYouWillLearn)
// setValue("courseCategory", course.category)
// setValue("courseRequirements", course.instructions)
// setValue("courseImage", course.thumbnail)
// }
getServices();
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
const submitJobPostForm = async (data) => {
console.log("Form Data - ", data);
// console.log("token - ", token)
try {
dispatch(
addJobPost(data, token)
);
} catch (error) {
console.log("ERROR MESSAGE - ", error.message);
}
};
return (
<form onSubmit={handleSubmit(submitJobPostForm)}>
{/* jJob Information */}
<h1 className="mb-14 text-3xl font-medium text-richblack-5">
Create Job Post
</h1>
<div className="my-10 flex flex-col gap-y-6 rounded-md border-[1px] border-richblack-700 bg-richblack-800 p-8 px-12">
<h2 className="text-lg font-semibold text-richblack-5">
Basic Details
</h2>
{/* ROW 1 */}
<div className="flex flex-col gap-5 lg:flex-row">
{/* JOb Title service */}
<div className="flex flex-col gap-2 lg:w-[25%]">
<label htmlFor="title" className="lable-style">
Job Title
</label>
<input
type="text"
name="title"
id="title"
placeholder="Enter job title"
className="form-style"
{...register("title", { required: true })}
// defaultValue={user?.adminProfileDetails?.firstName}
/>
{errors.title && (
<span className="-mt-1 text-[12px] text-yellow-100">
Please enter your job title .
</span>
)}
</div>
<div className="flex flex-col space-y-2 lg:w-[25%] ">
<label
className="lable-style"
htmlFor="service"
>
Service <sup className="text-pink-200">*</sup>
</label>
<select
{...register("service", { required: true })}
defaultValue=""
id="service"
className="form-style w-full"
>
<option value="" disabled>
Choose a Service
</option>
{!loading &&
services?.map((service, indx) => (
<option key={indx} value={service?._id}>
{service?.serviceName}
</option>
))}
</select>
{errors.service && (
<span className="ml-2 text-xs tracking-wide text-pink-200">
Service is required
</span>
)}
</div>
<div className="flex flex-col gap-2 lg:w-[25%]">
<label htmlFor="companyName" className="lable-style">
Company Name
</label>
<input
type="text"
name="companyName"
id="companyName"
placeholder="Enter company name"
className="form-style"
{...register("companyName", { required: true })}
// defaultValue={user?.adminDetails?.lastName}
/>
{errors.companyName && (
<span className="-mt-1 text-[12px] text-yellow-100">
Please enter your company name.
</span>
)}
</div>
<div className="flex flex-col gap-2 lg:w-[25%]">
<label htmlFor="skills" className="lable-style">
Required Skills
</label>
<input
type="text"
name="skills"
id="skills"
placeholder="Enter required skills"
className="form-style"
{...register("skills", { required: true })}
// defaultValue={user?.adminDetails?.lastName}
/>
{errors.skills && (
<span className="-mt-1 text-[12px] text-yellow-100">
Please enter required skills.
</span>
)}
</div>
</div>
{/* ROW 2 */}
<div className="flex flex-col gap-5 lg:flex-row">
<div className="flex flex-col gap-2 lg:w-[25%]">
<label htmlFor="requiredExperience" className="lable-style">
Required Experience
</label>
<input
type="number"
name="requiredExperience"
id="requiredExperience"
placeholder="Enter required experience "
className="form-style"
{...register("requiredExperience", { required: true })}
// defaultValue={user?.adminDetails?.post}
/>
{errors.requiredExperience && (
<span className="-mt-1 text-[12px] text-yellow-100">
Please select your required experience.
</span>
)}
</div>
<div className="flex flex-col gap-2 lg:w-[25%]">
<label htmlFor="salaryRange" className="lable-style">
Salary Range
</label>
<div className="flex gap-3 relative">
<input
type="text"
name="salaryRange"
id="salaryRange"
placeholder="Enter salary range "
className="form-style ml-1"
{...register("salaryRange", { required: true })}
// defaultValue={user?.adminDetails?.post}
/>
<span className="flex flex-start absolute lable-style my-auto ml-2 mt-3 ">$</span>
</div>
{errors.salaryRange && (
<span className="-mt-1 text-[12px] text-yellow-100">
Please select your salary range.
</span>
)}
</div>
<div className="flex flex-col gap-2 lg:w-[25%]">
<label htmlFor="jobType" className="lable-style">
Job Type
</label>
<select
type="text"
name="jobType"
id="jobType"
placeholder="Choose job type "
className="form-style"
{...register("jobType", { required: true })}
// defaultValue={user?.adminDetails?.post}
>
<option value="" disabled >Choose Job Type</option>
<option value="Full Time" >Full Time</option>
<option value="Part Time" >Part Time</option>
<option value="Internship" >Internship</option>
</select>
{errors.jobType && (
<span className="-mt-1 text-[12px] text-yellow-100">
Please select your job type.
</span>
)}
</div>
<div className="flex flex-col gap-2 lg:w-[25%]">
<label htmlFor="salaryType" className="lable-style">
Salary Type
</label>
<select
type="text"
name="salaryType"
id="salaryType"
placeholder="Choose salary type "
className="form-style"
{...register("salaryType", { required: true })}
// defaultValue={user?.adminDetails?.post}
>
<option value="" disabled >Choose Salary Type</option>
<option value="Hourly" >Hourly</option>
<option value="Weekly" >Weekly</option>
<option value="Monthly" >Monthly</option>
<option value="Yearly" >Yearly</option>
</select>
{errors.salaryType && (
<span className="-mt-1 text-[12px] text-yellow-100">
Please select your salary type.
</span>
)}
</div>
</div>
{/* ROW 3 */}
<div className="flex flex-col gap-5 lg:flex-row">
{/* need to edit location using a package */}
<div className="flex flex-col gap-2 lg:w-[25%]">
<label htmlFor="location" className="lable-style">
Choose Location
</label>
<select
type="text"
name="location"
id="location"
placeholder="Choose location "
className="form-style"
{...register("location", { required: true })}
// defaultValue={user?.adminDetails?.post}
>
<option value="" disabled>
Choose a Category
</option>
{!loading &&
State.getStatesOfCountry("TR")?.map((state, indx) => (
<option key={indx} value={state?.name}>
{state?.name}
</option>
))}
</select>
{errors.location && (
<span className="-mt-1 text-[12px] text-yellow-100">
Please select your required location.
</span>
)}
</div>
<div className="flex flex-col gap-2 lg:w-[25%]">
<label htmlFor="startDate" className="lable-style">
Select Start Date
</label>
<input
type="date"
name="startDate"
id="startDate"
placeholder="Select start date"
className="form-style"
{...register("startDate", { required: true })}
// defaultValue={user?.adminDetails?.post}
/>
{errors.startDate && (
<span className="-mt-1 text-[12px] text-yellow-100">
Please select your start date.
</span>
)}
</div>
<div className="flex flex-col gap-2 lg:w-[25%]">
<label htmlFor="endDate" className="lable-style">
Select End Date
</label>
<input
type="date"
name="endDate"
id="endDate"
placeholder="Select end date"
className="form-style"
{...register("endDate", { required: true })}
// defaultValue={user?.adminDetails?.post}
/>
{errors.endDate && (
<span className="-mt-1 text-[12px] text-yellow-100">
Please select your end date.
</span>
)}
</div>
<div className="flex flex-col gap-2 lg:w-[25%]">
<label htmlFor="vacancy" className="lable-style">
No. Of Vacancies
</label>
<input
type="number"
name="vacancy"
id="vacancy"
placeholder="Choose vacancy"
className="form-style"
{...register("vacancy", { required: true })}
// defaultValue={user?.adminDetails?.post}
/>
{errors.vacancy && (
<span className="-mt-1 text-[12px] text-yellow-100">
Please select your no. of vacancy.
</span>
)}
</div>
</div>
{/* ROW 4 */}
<div className="flex flex-col gap-5 lg:flex-row">
<div className="flex flex-col space-y-2 w-full">
<label className="text-sm text-richblack-5" htmlFor="description">
Job Short Description <sup className="text-pink-200">*</sup>
</label>
<textarea
id="description"
placeholder="Enter Description"
{...register("description", { required: true })}
className="form-style resize-x-none min-h-[130px] w-full"
/>
{errors.description && (
<span className="ml-2 text-xs tracking-wide text-pink-200">
Job Description is required
</span>
)}
</div>
</div>
</div>
<div className="my-10 flex flex-col gap-y-6 rounded-md border-[1px] border-richblack-700 bg-richblack-800 p-8 px-12">
<h2 className="text-lg font-semibold text-richblack-5">
Main Certificates
</h2>
{/* ROW 1 */}
<div className="flex flex-col gap-5 lg:flex-row">
<div className="flex flex-col gap-2 lg:w-[25%]">
<label htmlFor="licenseType" className="lable-style">
License Type
</label>
<select
type="text"
name="licenseType"
id="licenseType"
placeholder="Choose license type "
className="form-style"
{...register("licenseType", { required: true })}
// defaultValue={user?.adminDetails?.post}
>
<option value="" disabled >Choose License Type</option>
<option value="Type 1" >Type 1</option>
<option value="Type 2" >Type 2</option>
<option value="Type 3" >Type 3</option>
</select>
{errors.licenseType && (
<span className="-mt-1 text-[12px] text-yellow-100">
Please select your license type.
</span>
)}
</div>
<div className="flex flex-col space-y-2 lg:w-[33%] text-white">
<label
className="lable-style"
>
SRCBox <sup className="text-pink-200">*</sup>
</label>
<div className="flex-col gap-4">
<label htmlFor="isSrc1">
SRC 1
<input
type="checkbox"
name="isSrc1"
value="SRC 1"
onChange={handleSrc1Change}
checked={src1Checked}
/>
</label>
<label htmlFor="isSrc2">
SRC 2
<input
type="checkbox"
name="isSrc2"
value="SRC 2"
onChange={handleSrc2Change}
checked={src2Checked}
/>
</label>
</div>
<div className="flex-col gap-4">
<label htmlFor="isSrc3">
SRC 3
<input
type="checkbox"
name="isSrc3"
value="SRC 3"
onChange={handleSrc3Change}
checked={src3Checked}
/>
</label>
<label htmlFor="isSrc4">
SRC 4
<input
type="checkbox"
name="isSrc4"
value="SRC 4"
onChange={handleSrc4Change}
checked={src4Checked}
/>
</label>
</div>
</div>
<div className="flex flex-col gap-2 lg:w-[33%]">
<label htmlFor="psikoteknik" className="lable-style">
Psikoteknik
</label>
<input
type="date"
name="psikoteknik"
id="psikoteknik"
className="form-style"
{...register("psikoteknik", { required: true })}
// defaultValue={user?.adminDetails?.lastName}
/>
{errors.psikoteknik && (
<span className="-mt-1 text-[12px] text-yellow-100">
Please select your psikoteknik date.
</span>
)}
</div>
<div className="flex flex-col gap-2 lg:w-[33%]">
<label htmlFor="adrDriverLicence" className="lable-style">
ADR Driver Licence
</label>
<input
type="date"
name="adrDriverLicence"
id="adrDriverLicence"
className="form-style"
{...register("adrDriverLicence", { required: true })}
// defaultValue={user?.adminDetails?.lastName}
/>
{errors.adrDriverLicence && (
<span className="-mt-1 text-[12px] text-yellow-100">
Please select ADR Driver Licence date.
</span>
)}
</div>
</div>
</div>
<div className="my-10 flex flex-col gap-y-6 rounded-md border-[1px] border-richblack-700 bg-richblack-800 p-8 px-12">
<h2 className="text-lg font-semibold text-richblack-5">
Required Abilities
</h2>
{/* Row 1 */}
<div className="flex flex-col gap-5 lg:flex-row">
{/* passport,visa,abroadExperience, */}
<div className="flex flex-col gap-2 lg:w-[25%]">
<label htmlFor="passport" className="lable-style">
Passport
</label>
<select
type="text"
name="passport"
id="passport"
placeholder="Choose passport type "
className="form-style"
{...register("passport", { required: true })}
// defaultValue={user?.adminDetails?.post}
>
<option value="" disabled >Choose Passport Type</option>
<option value="Type 1" >Type 1</option>
<option value="Type 2" >Type 2</option>
<option value="Type 3" >Type 3</option>
</select>
{errors.passport && (
<span className="-mt-1 text-[12px] text-yellow-100">
Please select your passport type.
</span>
)}
</div>
<div className="flex flex-col gap-2 lg:w-[25%]">
<label htmlFor="visa" className="lable-style">
Visa
</label>
<select
type="text"
name="visa"
id="visa"
placeholder="Choose visa type "
className="form-style"
{...register("visa", { required: true })}
// defaultValue={user?.adminDetails?.post}
>
<option value="" disabled >Choose Visa Type</option>
<option value="Type 1" >Type 1</option>
<option value="Type 2" >Type 2</option>
<option value="Type 3" >Type 3</option>
</select>
{errors.visa && (
<span className="-mt-1 text-[12px] text-yellow-100">
Please select your visa type.
</span>
)}
</div>
<div className="flex flex-col gap-2 lg:w-[25%]">
<label htmlFor="abroadExperience" className="lable-style">
Abroad Experience
</label>
<input
type="number"
name="abroadExperience"
id="abroadExperience"
placeholder="Select Abroad Experience "
className="form-style"
{...register("abroadExperience", { required: true })}
// defaultValue={user?.adminDetails?.post}
>
</input>
{errors.abroadExperience && (
<span className="-mt-1 text-[12px] text-yellow-100">
Please select your Abroad Experience.
</span>
)}
</div>
</div>
{/* isBlindSpotTraining,isSafeDrivingTraining,isFuelEconomyTraining */}
{/* ROW 2 */}
<div className="flex flex-col gap-5 lg:flex-row text-white">
<div className="flex flex-col gap-2 lg:w-[25%] items-center">
<label>
Is Blind Spot Training
</label>
<input
type="checkbox"
name="isBlindSpotTraining"
onChange={(e) => setValue('isBlindSpotTraining', e.target.checked)}
checked={watchedValues.isBlindSpotTraining}
/>
</div>
<div className="flex flex-col gap-2 lg:w-[25%] items-center">
<label>
Is Safe Driving Training
</label>
<input
type="checkbox"
name="isSafeDrivingTraining"
onChange={(e) => setValue('isSafeDrivingTraining', e.target.checked)}
checked={watchedValues.isSafeDrivingTraining}
/>
</div>
<div className="flex flex-col gap-2 lg:w-[25%] items-center">
<label>
Is Fuel Economy Training
</label>
<input
type="checkbox"
name="isFuelEconomyTraining"
onChange={(e) => setValue('isFuelEconomyTraining', e.target.checked)}
checked={watchedValues.isFuelEconomyTraining}
/>
</div>
</div>
</div>
<div className="flex justify-end gap-2">
<button
onClick={() => {
navigate("/dashboard/my-services");
}}
className="cursor-pointer rounded-md bg-richblack-700 py-2 px-5 font-semibold text-richblack-50"
>
Cancel
</button>
<IconBtn type="submit" text="Save" />
</div>
</form>
);
};
export default PostJob; |
//
// CryptoListPresentableItem.swift
// CoinGekoiOS
//
// Created by Carlos Caraccia on 6/17/24.
//
import Foundation
// Type that we'll use to display inside the view model
struct CryptocurrencyListPresentableItem: Identifiable {
let id: String
let name: String
let symbol: String
let price: String
var price24h: String
var volume24h: String
let marketCap: String
let isPriceChangePositive: Bool
init(domainModel: Cryptocurrency) {
self.id = domainModel.id
self.name = domainModel.name
self.symbol = domainModel.symbol
self.price = String(domainModel.price) + " $"
self.marketCap = String(domainModel.marketCap.twoDecimalPlacesFormatted()) + " $"
if let price24h = domainModel.price24h, let volume24h = domainModel.volume24h {
self.volume24h = String(volume24h.twoDecimalPlacesFormatted()) + " $"
self.isPriceChangePositive = price24h > 0
self.price24h = "\(isPriceChangePositive ? "+" : "")" + String(price24h.twoDecimalPlacesFormatted()) + " %"
} else {
// we'll show a dash when there's not value
self.price24h = "-"
self.volume24h = "-"
self.isPriceChangePositive = true
}
}
} |
import React from "react";
import SquarebagelDesktop from "./SquarebagelDesktop";
import SquarebagelMobile from "./SquarebagelMobile";
export const App = () => {
const [isMobile, setIsMobile] = React.useState(window.innerWidth <= 768);
React.useEffect(() => {
const handleResize = () => {
setIsMobile(window.innerWidth <= 768);
};
window.addEventListener("resize", handleResize);
return () => {
window.removeEventListener("resize", handleResize);
};
}, []);
return <>{isMobile ? <SquarebagelMobile /> : <SquarebagelDesktop />}</>;
}; |
export const colorSchemePipe:Record<string, Function> = {
'red': function () { return '#ef4b44'; },
'orange': function () { return '#ff9900'; },
'green': function () { return '#01d092'; },
'blue': function () { return '#57c0ff'; },
'cap-coc': function (value:number) {
if (value < 0) return colorSchemePipe.red();
else if (value <= 0.02) return '';
else if (value <= 0.05) return colorSchemePipe.orange();
else return colorSchemePipe.green();
},
'perf': function (value:number) {
if (value < 0) return colorSchemePipe.red();
else if (value <= 0.02) return '';
else if (value <= 0.05) return colorSchemePipe.orange();
else return colorSchemePipe.green();
},
'tenPointRating': function (value:number) {
if (value < 3) return colorSchemePipe.red();
else if (value >= 8) return colorSchemePipe.green();
else return '';
},
'posNeg': function (value:number) {
if (value < 0) return colorSchemePipe.red();
else if (value > 0) return colorSchemePipe.green();
else return '';
},
'invPosNeg': function (value:number) {
if (value > 0) return colorSchemePipe.red();
else if (value < 0) return colorSchemePipe.green();
else return '';
},
'rentAnalyzerMarker': function (value:string) {
if (value == 'higher')
return colorSchemePipe.red();
else if (value == 'moderate')
return colorSchemePipe.blue();
else if (value == 'lower')
return colorSchemePipe.green();
},
}
export function colorSchemePipeStyle(scheme: string, value: any) {
if (colorSchemePipe[scheme] && value != undefined && value != null)
return { color: colorSchemePipe[scheme](value) };
return {};
} |
# This code is importing necessary modules and functions for the Flask web application.
from flask import Flask, render_template, request, jsonify
from text_sentiment_prediction import *
# `app = Flask(__name__)` creates an instance of the Flask class and assigns it to the variable `app`.
# The `__name__` argument is a special Python variable that represents the name of the current module.
# By passing `__name__` as an argument, Flask knows where to find the static and template files for
# the application.
app = Flask(__name__)
# `@app.route('/')` is a decorator in Flask that associates a URL route with a function. In this case,
# it associates the root URL ("/") with the `index()` function. So when a user visits the root URL of
# the web application, the `index()` function will be executed and the returned value will be
# displayed in the browser.
@app.route('/')
def index():
"""
The function returns the rendered template for the index.html file.
:return: the result of the `render_template('index.html')` function call.
"""
return render_template('index.html')
# `@app.route('/predict-emotion', methods=["POST"])` is a decorator in Flask that associates the URL
# route "/predict-emotion" with the `predict_emotion()` function. It specifies that the function
# should be executed when a POST request is made to the "/predict-emotion" URL.
@app.route('/predict-emotion', methods=["POST"])
def predict_emotion():
"""
The function `predict_emotion()` takes input text from a POST request, predicts the emotion
associated with the text, and returns the predicted emotion and an image URL representing the
emotion.
:return: a JSON response. If the input text is undefined, it returns an error response with a
message. If the input text is defined, it returns a success response with the predicted emotion and
the URL of an image representing the predicted emotion.
"""
# Get Input Text from POST Request
input_text = request.json.get("text")
if not input_text:
# Response to send if the input_text is undefined
response = {
"status": "error",
"message": "Please enter some text to predict emotion!"
}
return jsonify(response)
else:
predicted_emotion,predicted_emotion_img_url = predict(input_text)
# Response to send if the input_text is not undefined
response = {
"status": "success",
"data": {
"predicted_emotion": predicted_emotion,
"predicted_emotion_img_url": predicted_emotion_img_url
}
}
# Send Response
return jsonify(response)
# `app.run(debug=True)` starts the Flask development server. The `debug=True` argument enables debug
# mode, which provides more detailed error messages and automatically reloads the server when changes
# are made to the code. This is useful during development to quickly see any errors and test changes
# without manually restarting the server.
app.run(debug=True) |
// SPDX-License-Identifier: GPL-3.0-only
/*
* Prism Launcher - Minecraft Launcher
* Copyright (c) 2022 flowln <flowlnlnln@gmail.com>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, version 3.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*
* This file incorporates work covered by the following copyright and
* permission notice:
*
* Copyright 2013-2021 MultiMC Contributors
*
* 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.
*/
#pragma once
#include <QFileInfo>
#include "Screenshot.h"
#include "net/NetRequest.h"
class ImgurUpload : public Net::NetRequest {
public:
class Sink : public Net::Sink {
public:
Sink(ScreenShot::Ptr shot) : m_shot(shot){};
virtual ~Sink() = default;
public:
auto init(QNetworkRequest& request) -> Task::State override;
auto write(QByteArray& data) -> Task::State override;
auto abort() -> Task::State override;
auto finalize(QNetworkReply& reply) -> Task::State override;
auto hasLocalData() -> bool override { return false; }
private:
ScreenShot::Ptr m_shot;
QByteArray m_output;
};
ImgurUpload(QFileInfo info) : m_fileInfo(info) {}
virtual ~ImgurUpload() = default;
static NetRequest::Ptr make(ScreenShot::Ptr m_shot);
void init() override;
private:
virtual QNetworkReply* getReply(QNetworkRequest&) override;
const QFileInfo m_fileInfo;
}; |
import "dotenv/config";
import { typeDefs, resolvers } from "./grapqhl";
import { ApolloServer, CorsOptions } from "apollo-server-express";
import express, { Application, CookieOptions } from "express";
import { connectDatabase } from "./database";
import bodyParser from "body-parser";
import multer from "multer";
import compression from "compression";
import cors from "cors";
import session, { Session } from "express-session";
export type SessionViewer = Session & { viewer: string };
const cookieOptions: CookieOptions = {
httpOnly: true,
sameSite: true,
secure: process.env.NODE_ENV === "production",
maxAge: 365 * 24 * 60 * 60 * 1000, // 1 year,
};
const corsOptions: CorsOptions = {
credentials: true,
origin: process.env.PUBLIC_URL,
};
const mount = async (app: Application) => {
const db = await connectDatabase();
const upload = multer();
if (process.env.NODE_ENV === "production") {
app.use(compression());
app.set("trust proxy", 1);
// app.use(express.static(`${__dirname}/client`));
// app.get("/*", (_req, res) =>
// res.sendFile(`${__dirname}/client/index.html`)
// );
}
app.use(cors(corsOptions));
app.use(bodyParser.json({ limit: "2mb" }));
// not work on client
// app.use(cookieParser(process.env.SECRET));
app.use(
session({
secret: `${process.env.SECRET}`,
cookie: {
...cookieOptions,
},
})
);
app.post("/statusDone", upload.single("image"), (_req, res) =>
res.send({ status: "done" })
);
const apolloServer = new ApolloServer({
introspection: true,
playground: true,
typeDefs,
resolvers,
context: ({ res, req }) => ({ db, res, req }),
});
apolloServer.applyMiddleware({ app, path: "/api", cors: corsOptions });
app.listen(process.env.PORT);
console.log(`Server listen on ${process.env.PUBLIC_URL}:${process.env.PORT}`);
};
mount(express()); |
import React, { useState, useEffect } from "react";
import axios from "axios";
import "./Storage.css";
function Storage({ userName }) {
const [images, setImages] = useState([]);
useEffect(() => {
fetchImages();
}, [userName]);
const fetchImages = () => {
axios
.post(`http://127.0.0.1:5000/display`, { userName })
.then((response) => {
setImages(response.data);
})
.catch((error) => {
console.error("Error fetching images:", error);
});
};
const downloadImage = (image) => {
const link = document.createElement("a");
link.href = `data:image/jpeg;base64,${image}`;
link.download = `image_${Date.now()}.jpg`;
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
};
const deleteImage = (index) => {
const imageToDelete = images[index];
axios
.post("http://127.0.0.1:5000/delete_image", {
image: imageToDelete,
userName: userName
})
.then(() => {
// After deletion, fetch images again to update the UI
fetchImages();
})
.catch((error) => {
console.error("Error deleting image:", error);
});
};
return (
<div>
{/* <h2>Images for {userName}:</h2> */}
<div className="image-tile">
{images.map((image, index) => (
<div key={index} className="image-wrapper">
<div className="image-container">
<button
className="delete-button"
onClick={() => deleteImage(index)}
></button>
<img
src={`data:image/jpeg;base64,${image}`}
alt={`Image ${index + 1}`}
/>
</div>
<button onClick={() => downloadImage(image)}>
Download
</button>
</div>
))}
</div>
</div>
);
}
export default Storage; |
const sequelize = require('sequelize');
class AnimalsService {
constructor(db) {
this.sequelize = db.sequelize;
this.Animal = db.Animal;
this.Specie = db.Specie;
this.Size = db.Size;
this.Temperament = db.Temperament;
}
async getAnimals() {
const animals = await this.sequelize.query(
'SELECT `Animal`.`Name`, `Animal`.`id`, `Animal`.`BirthDate`, `Animal`.`UserId`, ' +
"DATE_FORMAT(FROM_DAYS(DATEDIFF(NOW(), BirthDate)), '%Y') + 0 AS `Age`, " +
'`Specie`.`id` AS `Specie.id`, `Specie`.`Name` AS `SpecieName`, ' +
'`Size`.`id` AS `Size.id`, `Size`.`Name` AS `SizeName`, ' +
'group_concat(`Temperaments`.`id`) AS `Temperaments.id`, ' +
' group_concat(`Temperaments`.`name`) AS `TemperamentsName` ' +
' FROM `Animals` AS `Animal` INNER JOIN `Species` AS ' +
'`Specie` ON `Animal`.`SpecieId` = `Specie`.`id` INNER JOIN `Sizes` ' +
' AS `Size` ON `Animal`.`SizeId` = `Size`.`id` ' +
' INNER JOIN ( `AnimTempes` AS `Temperaments->AnimTempe` INNER JOIN ' +
' `Temperaments` AS `Temperaments` ON ' +
' `Temperaments`.`id` = `Temperaments->AnimTempe`.`TemperamentId`) ON ' +
' `Animal`.`id` = `Temperaments->AnimTempe`.`AnimalId` GROUP BY `Animal`.`id` ' +
' ORDER BY `Animal`.`id` ASC '
);
// const animals = await this.Animal.findAll({
// attributes: [
// 'Name',
// 'id',
// 'BirthDate',
// 'UserId',
// [
// sequelize.literal(
// `DATE_FORMAT(FROM_DAYS(DATEDIFF(NOW(), BirthDate)), '%Y') + 0`
// ),
// 'Age',
// ],
// ],
// where: {},
// order: [['id', 'Asc']],
// include: [
// {
// model: this.Specie,
// required: true,
// attributes: ['Name'],
// },
// {
// model: this.Size,
// required: true,
// attributes: ['Name'],
// },
// {
// model: this.Temperament,
// required: true,
// through: { attributes: [] },
// },
// ],
// });
// animals.forEach((animal) => {
// let arr = [];
// animal.Temperaments.forEach((temperament) => arr.push(temperament.name));
// animal.Temperament = arr.join(', ');
// });
return animals[0];
}
async getAnimalsPopularName() {
const animals = await this.sequelize.query(
'SELECT `Animal`.`Name`, count(`Animal`.`Name`) as id,count(`Animal`.`Name`) as count from Animals as Animal group by `Animal`.`Name`'
);
return animals[0];
}
async getAdoptedAnimals() {
const animals = await this.sequelize.query(
'SELECT `Animal`.`Name`, `Animal`.`id`, `Animal`.`BirthDate`, `Animal`.`UserId`, ' +
"DATE_FORMAT(FROM_DAYS(DATEDIFF(NOW(), BirthDate)), '%Y') + 0 AS `Age`, " +
'`Specie`.`id` AS `Specie.id`, `Specie`.`Name` AS `SpecieName`, ' +
'`Size`.`id` AS `Size.id`, `Size`.`Name` AS `SizeName`, ' +
'group_concat(`Temperaments`.`id`) AS `Temperaments.id`, ' +
' group_concat(`Temperaments`.`name`) AS `TemperamentsName` ' +
' FROM `Animals` AS `Animal` INNER JOIN `Species` AS ' +
'`Specie` ON `Animal`.`SpecieId` = `Specie`.`id` INNER JOIN `Sizes` ' +
' AS `Size` ON `Animal`.`SizeId` = `Size`.`id` ' +
' INNER JOIN ( `AnimTempes` AS `Temperaments->AnimTempe` INNER JOIN ' +
' `Temperaments` AS `Temperaments` ON ' +
' `Temperaments`.`id` = `Temperaments->AnimTempe`.`TemperamentId`) ON ' +
' `Animal`.`id` = `Temperaments->AnimTempe`.`AnimalId` where `Animal`.`UserId`>0 GROUP BY `Animal`.`id` ' +
' ORDER BY `Animal`.`id` ASC '
);
return animals[0];
}
async getAnimalsByAge() {
const animals = await this.sequelize.query(
'SELECT `Animal`.`Name`, `Animal`.`id`, `Animal`.`BirthDate`, `Animal`.`UserId`, ' +
"DATE_FORMAT(FROM_DAYS(DATEDIFF(NOW(), BirthDate)), '%Y') + 0 AS `Age`, " +
'`Specie`.`id` AS `Specie.id`, `Specie`.`Name` AS `SpecieName`, ' +
'`Size`.`id` AS `Size.id`, `Size`.`Name` AS `SizeName`, ' +
'group_concat(`Temperaments`.`id`) AS `Temperaments.id`, ' +
' group_concat(`Temperaments`.`name`) AS `TemperamentsName` ' +
' FROM `Animals` AS `Animal` INNER JOIN `Species` AS ' +
'`Specie` ON `Animal`.`SpecieId` = `Specie`.`id` INNER JOIN `Sizes` ' +
' AS `Size` ON `Animal`.`SizeId` = `Size`.`id` ' +
' INNER JOIN ( `AnimTempes` AS `Temperaments->AnimTempe` INNER JOIN ' +
' `Temperaments` AS `Temperaments` ON ' +
' `Temperaments`.`id` = `Temperaments->AnimTempe`.`TemperamentId`) ON ' +
' `Animal`.`id` = `Temperaments->AnimTempe`.`AnimalId` GROUP BY `Animal`.`id` ' +
' ORDER BY `Age` DESC'
);
return animals[0];
}
async getAnimalsBySize() {
const sizes = await this.sequelize.query(
'SELECT `Animal`.`SizeId`,`Size`.`Name` , count(`Size`.`id`) as count, count(`Size`.`id`) as id from Animals as Animal ' +
'INNER JOIN `Sizes` AS `Size` ON `Animal`.`SizeId` = `Size`.`id` group by `Size`.`Name` order by count desc;'
);
return sizes[0];
}
async adoptAnimal(id, userId) {
const tmp = await this.Animal.update(
{
UserId: userId,
},
{
where: { id: id },
returning: true,
plain: true,
}
);
}
async cancelAdoption(id) {
const tmp = await this.Animal.update(
{
UserId: null,
},
{
where: { id: id },
returning: true,
plain: true,
}
);
}
}
module.exports = AnimalsService; |
<?php
/**
* Tatoeba Project, free collaborative creation of multilingual corpuses project
* Copyright (C) 2009 BEN YAALA Salem <salem.benyaala@gmail.com>
* Copyright (C) 2011 HO Ngoc Phuong Trang <tranglich@gmail.com>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* PHP version 5
*
* @category PHP
* @package Tatoeba
* @author BEN YAALA Salem <salem.benyaala@gmail.com>
* @license Affero General Public License
* @link http://tatoeba.org
*/
/**
* profile view for Users.
*
* @category Users
* @package View
* @author BEN YAALA Salem <salem.benyaala@gmail.com>
* @license Affero General Public License
* @link http://tatoeba.org
*/
$userId = $user['id'];
$realName = Sanitize::html($user['name']);
$username = Sanitize::html($user['username']);
$userDescription = Sanitize::html($user['description']);
$homepage = $user['homepage'];
$birthday = $user['birthday'];
$userSince = $user['since'];
$userStatus = $members->groupName($groupId);
$statusClass = 'status'.$groupId;
$currentMember = CurrentUser::get('username');
$languagesSettings = $user['lang'];
$userImage = 'unknown-avatar.png';
if (!empty($user['image'])) {
$userImage = Sanitize::html($user['image']);
}
if (!empty($realName)) {
$this->pageTitle = "$username ($realName) - Tatoeba";
} else {
$this->pageTitle = "$username - Tatoeba";
}
?>
<div id="annexe_content">
<?php
echo $this->element(
'users_menu',
array('username' => $username)
);
?>
<div class="module">
<h2><?php __('Stats'); ?></h2>
<dl>
<dt><?php __('Comments posted'); ?></dt>
<dd><?php echo $userStats['numberOfComments']; ?></dd>
<dt><?php __('Sentences owned'); ?></dt>
<dd><?php echo $userStats['numberOfSentences']; ?></dd>
<dt><?php __('Sentences favorited'); ?></dt>
<dd><?php echo $userStats['numberOfFavorites']; ?></dd>
<dt><?php __('Contributions'); ?></dt>
<dd><?php echo $userStats['numberOfContributions']; ?></dd>
</dl>
<div>
=>
<?php
echo $html->link(
sprintf(__("Show latest activity", true)),
array(
'controller' => 'users',
'action' => 'show',
$userId
)
);
?>
</div>
</div>
<?php
if ($isDisplayed) {
?>
<div class="module">
<h2><?php __('Settings'); ?></h2>
<ul class="annexeMenu">
<li class="item">
<?php
if ($notificationsEnabled) {
__('Email notifications are ENABLED.');
} else {
__('Email notifications are DISABLED.');
}
?>
</li>
<li class="item">
<?php
if ($isPublic) {
__(
'Access to this profile is PUBLIC. '.
'All the information can be seen by everyone.'
);
} else {
__(
'Access to this profile is RESTRICTED. '.
'Only Tatoeba members can see the personal information '.
'and the description.'
);
}
?>
</li>
<?php
if (!empty($languagesSettings)) {
?>
<li class="item">
<?php echo $languagesSettings; ?>
</li>
<?php
}
?>
</ul>
<p>
<?php
if ($username == $currentMember) {
$members->displayEditButton(
array(
'controller' => 'user',
'action' => 'settings'
)
);
}
?>
</p>
</div>
<?php
}
?>
</div>
<div id="main_content">
<div class="module profileSummary">
<?php
if ($username == $currentMember) {
$members->displayEditButton(
array(
'controller' => 'user',
'action' => 'edit_profile'
)
);
}
?>
<?php
echo $html->image(
IMG_PATH . 'profiles_128/'.$userImage,
array(
'alt' => $username
)
);
?>
<div class="info">
<div class="username"><?php echo $username; ?></div>
<?php
if ($isDisplayed) {
if (!empty($birthday)) {
$birthday = date('F j, Y', strtotime($birthday));
}
if (!empty($homepage)) {
$homepage = $clickableLinks->clickableURL($homepage);
}
$userSince = date('F j, Y', strtotime($userSince));
$fields = array(
__('Name', true) => $realName,
__('Country', true) => $countryName,
__('Birthday', true) => $birthday,
__('Homepage', true) => $homepage
);
foreach ($fields as $fieldName => $value) {
?>
<div>
<span class="field <?php echo $statusClass ?>">
<?php echo $fieldName; ?>
</span>
<span class="value">
<?php
if (!empty($value)) {
echo $value;
} else {
echo ' - ';
}
?>
</span>
</div>
<?php
}
}
?>
<div>
<span class="field <?php echo $statusClass ?>">
<?php echo __('Member since'); ?>
</span>
<span class="value"><?php echo $userSince; ?></span>
</div>
</div>
<div class="status <?php echo $statusClass ?>">
<?php echo $userStatus; ?>
</div>
</div>
<?php
if (!empty($userDescription)) {
$descriptionContent = $clickableLinks->clickableURL($userDescription);
$descriptionContent = nl2br($descriptionContent);
} else {
$descriptionContent = '<div class="tip">';
$descriptionContent.= __('No description.', true);
$descriptionContent.= '<br/><br/>';
if ($username == $currentMember) {
$descriptionContent.= __(
'TIP: We encourage you to indicate the languages you know.', true
);
} else {
$descriptionContent.= __(
'TIP: Encourage this user to indicate the languages '.
'he or she knows.', true
);
}
$descriptionContent.= '</div>';
}
if ($isDisplayed) {
?>
<div class="module profileDescription">
<?php
if ($username == $currentMember) {
$members->displayEditButton(
array(
'controller' => 'user',
'action' => 'edit_profile',
'#' => 'description'
)
);
}
?>
<div class="content">
<?php
echo $descriptionContent;
?>
</div>
</div>
<?php
}
?>
</div> |
import { Bike } from "./bike";
import { Rent } from "./rent";
import { User } from "./user";
import crypto from 'crypto'
export class App {
users: User[] = []
bikes: Bike[] = []
rents: Rent[] = []
findUser(email: string): User | undefined {
return this.users.find(user => { return user.email === email })
}
registerUser(user: User): void {
for (const rUser of this.users) {
if (rUser.email === user.email) {
throw new Error('Duplicate user.')
}
}
user.id = crypto.randomUUID()
this.users.push(user)
}
removeUser(user: User): void {
var index = this.users.indexOf(user)
if (index === -1) return
this.users.splice(index, 1)
}
registerBike(bike: Bike): void {
for (const rBike of this.bikes) {
if (rBike.name === bike.name) {
throw new Error('Duplicate bike.')
}
}
bike.id = crypto.randomUUID()
this.bikes.push(bike)
}
findBike(name: string): Bike | undefined {
return this.bikes.find(bike => { return bike.name === name })
}
rentBike(bike: Bike, user: User, startDate: Date, endDate: Date): Rent {
const rent = Rent.create(this.rents, bike, user, startDate, endDate)
this.rents.push(rent)
return rent
}
returnBike(bike: Bike): void {
const date = new Date()
for (const rent of this.rents) {
if (rent.bike.name === bike.name && date >= rent.dateFrom && date <= rent.dateTo) {
rent.dateReturned = date
break
}
}
}
} |
"""
Lambda function
Lambda function merupakan bentuk sintaks penyederhanaan terhadap suatu fungsi spesifik. Lambda function secara implisit sudah menghasilkan return value dari expressionnya sehingga tidak perli mendeklarasikan return value. Struktur fungsi lambda dibentuk sebagai berikut.
variabel_output = lambda argument : expression
Fungsi lambda expression :
- data sorting list -> sebagai key dalam proses sorting
- data filter list -> sebagai parameter dalam proses filter
"""
def f_kuadrat(angka) :
return angka ** 2
print(f"hasil fungsi kuadrat = {f_kuadrat(3)}")
# kita coba dengan lambda
# struktur lambda function -> output = lambda argument: expression
kuadrat = lambda angka : angka ** 2
print(f"hasil lambda kuadrat = {kuadrat(5)}") # fungsi yang dicari merupakan kuadrat yang merupakan fungsi lambda, 5 sebagai input parameter fungsi lambda yaitu angka dan dari angka tersebut kemudian diproses dengan expression di dalammya yaitu angka ** 2 dan kemudian di kembalikan (return value) secara otomatis melalui expressionnya
# fungsi lambda dengan dua input parameter
pangkat = lambda num,pow : num ** pow
print(f"hasil lambda pangkat = {pangkat(4,2)}")
## kegunaan apa bang?
# sorting untuk list biasa
data_list = ["Otong", "Ucup", "Dudung"]
data_list.sort()
print(f"sorted list = {data_list}")
# sorting dia pakai panjang
def panjang_nama(nama) :
return len(nama) # menggunakan struktur fungsi normal
data_list.sort(key=len) # parameter key dalam method sort berfungsi untuk mengatur sorting berdasarkan aturan key apa dimana dalam hal ini berdasarkan panjang karakter tiap data pada list yang akan disorting (len)
print(f"sorted list by len = {data_list}")
data_list.sort(key=panjang_nama)
print(f"sorted list by panjang = {data_list}")
# sort pakai lambda
data_list = ["Otong", "Ucup", "Dudung"]
data_list.sort(key=lambda nama : len(nama)) # menggunakan lambda function
print(f"sorted list by lambda = {data_list}")
# filter
data_angka = [1,2,3,4,5,6,7,8,9,10,11,12]
def kurang_dari_lima(angka) :
return angka < 5
data_angka_baru = list(filter(kurang_dari_lima, data_angka))
print(data_angka_baru)
data_angka_baru = list(filter(lambda x : x < 7, data_angka))
print(data_angka_baru)
# kasus genap (memfilter angka genap)
data_genap = list(filter(lambda x : (x % 2 == 0), data_angka))
print(data_genap)
# kasus genap (memfilter angka ganjil)
data_ganjil = list(filter(lambda x : (x % 2 != 0), data_angka))
print(data_ganjil)
# kelipatan 3
data_3 = list(filter(lambda x : (x % 3 == 0), data_angka))
print(data_3)
"""
Anonymous function
Anonymous function dibuat berdasarkan teknik currying oleh Haskell Curry. Anonymous function merupakan teknik fungsi currying untuk membuat fungsi tidak menjadi fixed dan kita bisa mengassign fungsi tersebut menjadi sebuah variabel. Salah satu contoh anonymous function adalah lambda yaitu fungsi yang tidak memiliki atau didefinisikan sebuah nama.
Anonymous function juga dapat dipanggil secara langsung tanpa harus membuat variabel dengan cara mendefinisikan nilai basis untuk lambda function yang kemudian diikuti dengan nilai inputan parameter untuk lambda function tsb seperti :
fungsi(basis_lambda)(input_parameter)
Pada intinya, anonymous function membuat fungsi dasar yang dapat diubah parameter-parameter operasi berdasarkan basisnya melalui assign variabel sehingga variabel yang menampung anonymous function menjadi sebuah fungsi yang memiliki basis dasar tertentu. Anonymous function biasanya digunakan untuk functional programming
"""
def pangkat(angka,n) :
hasil = angka ** n
return hasil
data_hasil = pangkat(5,2)
print(f"fungsi biasa = {data_hasil}")
# dengan currying menjadi
def pangkat(n) :
return lambda angka : angka ** n
pangkat2 = pangkat(2) # mengassign n sebagai nilai basis pangkat dalam fungsi lambda
print(f"pangkat2 = {pangkat2(5)}") # dengan adanya anonymous function fungsi pangkat dapat diaplikasikan dalam variabel dan kita memanggil fungsi berdasarkan variabel tersebut
pangkat3 = pangkat(3) # mengassign n sebagai nilai basis pangkat dalam fungsi lambda
print(f"pangkat3 = {pangkat3(3)}") # menghasilkan nilai pangkat 3 dari 5
print(f"pangkat bebas = {pangkat(4)(5)}") # nilai parameter (4) dan (5) masing-masing merujuk pada basis pangkat dan nilai angkat yang ingin dipangkatkan sehingga menghasilkan 5^4 |
import React from "react";
import { useState } from 'react';
import Row from 'react-bootstrap/Row';
import Col from 'react-bootstrap/Col';
import Container from "react-bootstrap/Container";
import Button from 'react-bootstrap/Button';
import Form from 'react-bootstrap/Form';
import styles from "./languageEditModal.module.css";
import SlidingPane from "react-sliding-pane";
import "react-sliding-pane/dist/react-sliding-pane.css";
export default function LanguageeditModal (props){
const [name, setName] = useState(props.selectedCard ? props.selectedCard.name : "");
const [info, setInfo] = useState(props.selectedCard ? props.selectedCard.info : "");
const [image, setImage] = useState(props.selectedCard ? props.selectedCard.img : "");
const handleUpdate = () => {
// Perform validation or other necessary checks before updating the data
const updatedLanguage = {
...props.selectedCard,
name: name,
info: info,
img: image,
};
props.onUpdate(updatedLanguage); // Call the onUpdate function from the parent component
props.onHide(); // Close the sliding pane after updating
};
return (
<SlidingPane
{...props}
isOpen={props.show}
title="Edit Language"
from="right"
onRequestClose={props.onHide} >
<Container>
<Form>
<Row>
<Form.Group className="mb-3">
<Form.Label>Language Name</Form.Label>
<Form.Control type="text" value={name} onChange={(e) => setName(e.target.value)} placeholder="enter new language name" />
<Form.Text className="text-muted">
Please enter a valid language name.
</Form.Text>
</Form.Group>
</Row>
<Row>
<Col>
<Form.Group className="mb-3" >
<Form.Label>Information</Form.Label>
<Form.Control as="textarea" aria-label="With textarea" value={info} onChange={(e) => setInfo(e.target.value)} placeholder="enter language descriptions" />
</Form.Group>
</Col>
</Row>
<Row>
<Form.Group className="mb-3" controlId="formFile">
<Form.Label>Image</Form.Label>
<Form.Control type="text" value={image} onChange={(e) => setImage(e.target.value)} placeholder="enter language country flag image" />
</Form.Group>
</Row>
<Row>
<Col lg={3}>
<Button variant="primary" type="submit" onClick={handleUpdate}>Update</Button>
</Col>
</Row>
</Form>
</Container>
</SlidingPane>
);
} |
<?php
namespace App\Http\Controllers\Api\admin;
use App\Http\Controllers\Controller;
use App\Http\Requests\StorePostRequest;
use App\Models\Category;
use App\Models\Post;
use App\Models\Tag;
use Illuminate\Http\Request;
use Intervention\Image\Facades\Image;
class PostController extends Controller
{
public function getPostCategories()
{
$categories = Category::orderBy('name', 'ASC')->where('model_type', 'پست ها')->get();
return response()->json(["categories" => $categories], 200);
}
public function index()
{
$posts = Post::with(["category", "author"])->latest()->take(3)->get();
return response()->json(["posts" => $posts], 200);
}
public function store(StorePostRequest $request)
{
if ($request->image) {
$image = $request->file('image');
$name = hexdec(uniqid()) . '.' . $image->getClientOriginalExtension();
$img = Image::make($request->image)->resize(800, 600);
$upload_path = 'upload/post/';
$image_url = $upload_path . $name;
$img->save($image_url);
}
$admin_id = auth()->guard("admin-api")->user()->id;
$post = new Post();
$post->admin_id = $admin_id;
$post->category_id = $request->category_id;
$post->title = $request->title;
$post->slug = str_replace(" ", "-", $request->title);
$post->image = '/' . $image_url;
$post->body = $request->body;
$post->seo_title = $request->seo_title;
$post->meta_description = $request->meta_description;
$post->meta_keywords = $request->meta_keywords;
$post->status = $request->status;
$post->featured = $request->featured;
$post->isImportant = $request->isImportant;
$post->save();
$listOfTags = explode(',', $request->tags);
foreach ($listOfTags as $tag) {
$repeatTag = Tag::where('name', $tag)->first();
if (!isset($repeatTag)) {
$tags = new Tag();
$tags->name = $tag;
$tags->slug = strtolower(str_replace(" ", "-", $tag));
$tags->save();
$post->tags()->attach($tags->id);
$post->save();
} else {
$post->tags()->attach($repeatTag->id);
$post->save();
}
}
return response()->json(["message" => " پست با موفقیت ذخیره شد "], 200);
}
public function show($id)
{
$post = Post::with(["category", "tags", "author", "comments"])->find($id);
return response()->json(["post" => $post], 200);
}
public function editPost(StorePostRequest $request, $id)
{
$post = Post::findOrFail($id);
if ($request->image) {
$path = ltrim($post->image, "/");
@unlink(public_path($path));
$image = $request->file('image');
$name = hexdec(uniqid()) . '.' . $image->getClientOriginalExtension();
$img = Image::make($request->image)->resize(800, 600);
$upload_path = 'upload/post/';
$image_url = $upload_path . $name;
$img->save($image_url);
}
$admin_id = auth()->guard("admin-api")->user()->id;
$post->admin_id = $admin_id;
$post->category_id = $request->category_id;
$post->title = $request->title;
$post->slug = str_replace(" ", "-", $request->title);
$post->image = isset($image_url) ? ('/' . $image_url) : $post->image;
$post->body = $request->body;
$post->seo_title = $request->seo_title;
$post->meta_description = $request->meta_description;
$post->meta_keywords = $request->meta_keywords;
$post->status = $request->status;
$post->featured = $request->featured;
$post->isImportant = $request->isImportant;
$post->save();
//delete tags
$post->tags()->detach();
$listOfTags = explode(',', $request->tags);
foreach ($listOfTags as $tag) {
$repeatTag = Tag::where('name', $tag)->first();
if (!isset($repeatTag)) {
$tags = new Tag();
$tags->name = $tag;
$tags->slug = strtolower(str_replace(" ", "-", $tag));
$tags->save();
$post->tags()->attach($tags->id);
$post->save();
} else {
$post->tags()->attach($repeatTag->id);
$post->save();
}
}
return response()->json(["message" => " پست با موفقیت ویرایش شد "], 200);
}
public function destroy(Post $post)
{
$path = ltrim($post->image, "/");
@unlink(public_path($path));
$post->tags()->detach();
$post->delete();
return response()->json(["message" => "حذف با موفقیت انجام شد"], 200);
}
} |
import { useId } from 'react'
import {
breakpoints,
CSSPropertyValue,
CSSProperties,
CustomCSSProps
} from '@common/utils'
import { Breakpoint } from '@hooks/useBreakpoints'
const ROOT_SELECTOR = '.root'
const stylePropMap = {
p: ['padding'],
pt: ['padding-top'],
pb: ['padding-bottom'],
pl: ['padding-left'],
pr: ['padding-right'],
py: ['padding-top', 'padding-bottom'],
px: ['padding-inline-start', 'padding-inline-end'],
m: ['margin'],
mt: ['margin-top'],
mb: ['margin-bottom'],
ml: ['margin-left'],
mr: ['margin-right'],
my: ['margin-top', 'margin-bottom'],
mx: ['margin-inline-start', 'margin-inline-end'],
bg: ['background'],
bgColor: ['background-color'],
bgGradient: ['background-image'],
bgClip: ['background-clip'],
w: ['width'],
h: ['height'],
minW: ['min-width'],
minH: ['min-height'],
maxW: ['max-width'],
maxH: ['max-height'],
boxSize: ['width', 'height'],
borderX: ['border-left', 'border-right'],
borderY: ['border-top', 'border-bottom']
}
type CustomPropName = keyof CustomCSSProps
export interface CustomStyle {
selector?: string
css: CSSProperties
}
export type CustomStyles = CustomStyle | CustomStyle[]
export const toKebabCase = (string: any) => {
return string
.replace(/([a-z])([A-Z])/g, '$1-$2')
.replace(/[\s_]+/g, '-')
.toLowerCase()
}
function cssPropsToJsx(
propName: CustomPropName,
value: CSSPropertyValue<any>,
selector: string
) {
//// resolve prop value without breakpoints
if (typeof value === 'string' || typeof value === 'number') {
return `${selector} {
${toKebabCase(propName)}:${value};
}`
}
let rules = ''
////resolve props with multiple breakpoints
for (const breakpoint in value) {
const queryValue =
breakpoint in breakpoints
? breakpoints[(breakpoint as Breakpoint) || 'xs']
: breakpoint
//// avoid creating media queries for min-width="0"
if (queryValue === 0) {
rules += `
${selector} {
${toKebabCase(propName)}:${value[breakpoint]};
}
`
}
rules += `
@media (min-width: ${queryValue}px) {
${selector} {
${toKebabCase(propName)}:${value[breakpoint]};
}
}
`
}
return rules
}
function customPropsToJsx(
propName: CustomPropName,
value: CSSPropertyValue<any>,
selector: string
) {
//// resolve prop value without breakpoints
if (typeof value === 'string' || typeof value === 'number') {
return `${selector} {
${stylePropMap[propName].map((prop) => `${prop}:${value};`).join(' ')}
}`
}
let rules = ''
////resolve props with multiple breakpoints
for (const breakpoint in value) {
const queryValue =
breakpoint in breakpoints
? breakpoints[(breakpoint as Breakpoint) || 'xs']
: breakpoint
//// avoid creating media queries for min-width="0"
if (queryValue === 0) {
rules += `${selector} {
${stylePropMap[propName]
.map((prop) => `${prop}:${value[breakpoint]};`)
.join(' ')}
}`
}
rules += `
@media (min-width: ${queryValue}px) {
${selector} {
${stylePropMap[propName]
.map((prop) => `${prop}:${value[breakpoint]};`)
.join(' ')}
}
}
`
}
return rules
}
const solveMultiClass = (rootClass: string, selector: string) => {
if (selector === ROOT_SELECTOR) return `.${rootClass}${selector}`
const classes = selector.split(',')
if (classes.length === 1) return `.${rootClass}${selector}`
const formattedSelector = classes
.map((className) => `.${rootClass}${className}`)
.join(',')
return formattedSelector
}
function createStyleString(selector: string, css: CSSProperties) {
if (!css || !selector) return ' '
let jsx = ''
for (const propName in css) {
//// resolve customProp real css propriety or proprieties
if (stylePropMap[propName as CustomPropName]) {
jsx += ` ${customPropsToJsx(
propName as CustomPropName,
css[propName as keyof CSSProperties],
selector
)} `
} else {
/// resolve camelCase props
jsx += ` ${cssPropsToJsx(
propName as any,
css[propName as keyof CSSProperties],
selector
)} `
}
}
return jsx
}
export function createStyle(styles: CustomStyles, rootClass: string) {
let jsx = ''
if (Array.isArray(styles)) {
jsx = styles
.map((style: CustomStyle) =>
createStyleString(
solveMultiClass(rootClass, style?.selector || ROOT_SELECTOR),
style.css
)
)
.join(' ')
} else {
jsx = createStyleString(
solveMultiClass(rootClass, styles?.selector || ROOT_SELECTOR),
styles.css
)
}
return { className: rootClass, styles: jsx }
}
export function useClassName() {
const id = useId().toString()
const className = id.slice(1, id.length - 1)
return className
}
export function useCustomStyles(cs?: CustomStyles) {
/// creates a unique className
const rootClass = useClassName()
if (!cs) {
return { className: '', styles: '' }
}
const customStyles = createStyle(cs, rootClass)
return customStyles
}
export type ExtraStyles = {
className: string
styles: string
}
export function combineCustomStyles(
customStyles: CustomStyle | CustomStyle[],
customStyles2: CustomStyle | CustomStyle[] | undefined
): CustomStyles {
if (!customStyles2) return customStyles
if (Array.isArray(customStyles2) && Array.isArray(customStyles)) {
return groupSelectorProps([...customStyles, ...customStyles2])
}
if (Array.isArray(customStyles2)) {
return groupSelectorProps([customStyles, ...customStyles2] as CustomStyle[])
}
if (Array.isArray(customStyles)) {
return groupSelectorProps([...customStyles, customStyles2] as CustomStyle[])
}
return groupSelectorProps([customStyles, customStyles2] as CustomStyle[])
}
function groupSelectorProps(stylesArr: CustomStyle[]) {
const selectorMap: { [key: string]: CSSProperties } = {}
stylesArr.forEach((styleObj) => {
const selector = styleObj.selector || ROOT_SELECTOR
if (selector in selectorMap) {
selectorMap[selector] = Object.assign(selectorMap[selector], styleObj.css)
} else {
selectorMap[selector] = styleObj.css
}
})
const resolveStyle: CustomStyle[] = []
for (const selector in selectorMap) {
resolveStyle.push({
selector: selector,
css: selectorMap[selector]
})
}
return resolveStyle
} |
"use client"
import { useState, useEffect } from 'react'
import { IPitchMap } from "@/common/types"
import { chromaticPitches, getMajorTriadPitchMaps, pitchMapsAreSimilar, PITCH_MAP_DISPLAY_MODE } from "@/common/utils/pitch-map"
import PitchMapPicker from "@/frontend/components/PitchMapPicker"
import PitchMapResults from '@/frontend/components/PitchMapResults'
import { getRandomElement, shuffleArray } from '@/common/utils/helpers'
interface IAnswer {
correctAnswer: IPitchMap[],
userAnswer: IPitchMap[]
}
const POOL_STORAGE_KEY = 'quizzes:triads:question-pool'
export default function TriadsPageContent() {
const storedQuestionPool = window.localStorage.getItem(POOL_STORAGE_KEY)
let initialQuestionPool = storedQuestionPool ? JSON.parse(storedQuestionPool) : []
initialQuestionPool = initialQuestionPool && initialQuestionPool.length > 0 ? initialQuestionPool : [...chromaticPitches]
const initialQuestion = getRandomElement<IPitchMap>(initialQuestionPool)
const [questionPool, setQuestionPool] = useState<IPitchMap[]>(initialQuestionPool)
const [question, setQuestion] = useState<IPitchMap>(initialQuestion)
const [correctAnswer, setCorrectAnswer] = useState<IPitchMap[]>(getMajorTriadPitchMaps(initialQuestion))
const [userAnswer, setUserAnswer] = useState<IPitchMap[]>([])
const [showResults, setShowResult] = useState<boolean>(false)
const [randomOrderedPitchMaps, setRandomOrderedPitchMaps] = useState<IPitchMap[]>(shuffleArray<IPitchMap>(chromaticPitches))
const [numCorrect, setNumCorrect] = useState<number>(0)
const handleQuestionPoolChange = (pool: IPitchMap[]) => {
localStorage.setItem(POOL_STORAGE_KEY, JSON.stringify(pool));
setQuestionPool(pool)
}
const handleUserAnswerChange = (answer: IPitchMap[]) => {
setUserAnswer(answer)
}
const handleSubmitClick = () => {
setNumCorrect(numCorrect + (pitchMapsAreSimilar(correctAnswer, userAnswer) ? 1 : 0))
setShowResult(true)
}
const handleNextClick = () => {
const questionRootPitch = getRandomElement(questionPool)
const questionTriad = getMajorTriadPitchMaps(questionRootPitch)
setRandomOrderedPitchMaps(shuffleArray<IPitchMap>(chromaticPitches))
setQuestion(questionRootPitch)
setUserAnswer([])
setCorrectAnswer(questionTriad)
setShowResult(false)
}
return (
<section className='page-body'>
<header>
<h1>Triads Quiz</h1>
</header>
<section>
<p>Number correct: <strong><em>{numCorrect}</em></strong></p>
<p>Select the notes in a <strong><em>{question.preferredNoteName || JSON.stringify(question)} major</em></strong> triad.</p>
<p>
{
showResults ? (
<PitchMapResults
keyRootPitchMap={question}
displayMode={PITCH_MAP_DISPLAY_MODE.KEY_CONTEXTED_NOTE_NAME}
visible={randomOrderedPitchMaps}
chosen={userAnswer || []}
expected={correctAnswer || []}
/>
) : (
<PitchMapPicker
keyRootPitchMap={question}
displayMode={PITCH_MAP_DISPLAY_MODE.KEY_CONTEXTED_NOTE_NAME}
onChange={handleUserAnswerChange}
visible={randomOrderedPitchMaps}
selected={userAnswer}
/>
)
}
</p>
</section>
<section className="cta-row">
<button onClick={handleSubmitClick} disabled={!!showResults || !(userAnswer.length === 3)}>submit</button>
<button onClick={handleNextClick} disabled={!showResults}>next</button>
</section>
<section className='push-bottom'>
<h2>Settings</h2>
<p><strong>Triad Bank</strong></p>
<PitchMapPicker onChange={handleQuestionPoolChange} visible={chromaticPitches} selected={questionPool}/>
</section>
</section>
)
} |
Assignment 12
Prompt the user for a number of coin flips (x) and then simulate (x) number of coin flips and print the results to the terminal.
Hint: Look up the srand() function.
Example Output
```
tokyo:~/LearningC/ # ./assignment12
How many times would you like to flip the coin? 5000
After flipping the coin 5000 times, the results were
2536 heads
2464 tails
```
------
### CODE
```
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main(void) {
unsigned int flip;
//unsigned int random;
// Seed the random number generator with the current time
srand((unsigned int)time(NULL));
printf("How many times would you like to flip the coin?\n");
scanf_s("%u", &flip);
if (!flip) {
printf("Enter a positive number");
return 1;
}
int tails = 0;
int heads = 0;
for (int i = 0; i < flip; i++) {
int result = rand() % 2;
if (result == 1) {
heads++;
}
else {
tails++;
}
}
printf("Heads: %d\n", heads);
printf("Tails: %d\n", tails);
return 0;
}
``` |
"use client"
import { useAppStore } from "@/store/store";
import { useUser } from "@clerk/nextjs"
import { useState } from "react";
import { Button } from "@/components/ui/button"
import {
Dialog,
DialogClose,
DialogContent,
DialogDescription,
DialogFooter,
DialogHeader,
DialogTitle,
DialogTrigger,
} from "@/components/ui/dialog"
import { Input } from "@/components/ui/input"
import { doc, updateDoc } from "firebase/firestore";
import { db } from "@/firebase";
import toast from "react-hot-toast";
function RenameModal() {
const { user } = useUser();
const [input, setInput] = useState("");
const [isRenameModalOpen, setIsRenameModalOpen, fileId, filename] = useAppStore((state) => [
state.isRenameModalOpen,
state.setIsRenameModalOpen,
state.fileId,
state.filename,
]);
const renameFile = async () => {
if(!user || !fileId) return;
const toastId = toast.loading("Renaming...");
await updateDoc(doc(db, "users", user.id, "files", fileId), {
filename: input,
});
toast.success("Renamed Successfully!", {
id: toastId,
});
setInput("");
setIsRenameModalOpen(false);
}
return (
<Dialog
open={isRenameModalOpen}
onOpenChange={(isOpen) => { setIsRenameModalOpen(isOpen)}}>
<DialogContent className="sm:max-w-md">
<DialogHeader>
<DialogTitle className="pb-2">Rename the File</DialogTitle>
</DialogHeader>
<Input
id="link"
defaultValue={filename}
onChange={e => setInput(e.target.value)}
onKeyDownCapture={e => {
if(e.key === "Enter"){
renameFile();
}
}}
/>
<div className="flex items-center justify-between space-x-2 py-3">
<Button size="sm" className="px-3" variant={"ghost"} onClick={() => setIsRenameModalOpen(false)}>
<span className="sr-only">Cancel</span>
<span>Cancel</span>
</Button>
<Button type="submit" size="sm" className="px-3" onClick={() => renameFile()}>
<span className="sr-only">Rename</span>
<span>Rename</span>
</Button>
</div>
</DialogContent>
</Dialog>
)
}
export default RenameModal |
1. Linux系统简介
- Unix与Linux发展史
- 开源软件简介
- Linux应用领域
- Linux学习方法
2. Linux系统安装
- VMware虚拟机安装与使用
- 系统分区
- Linux系统安装
- 远程登录管理工具
3. 初学者建议
4. Linux常用命令
- 文件处理命令
- 命令格式与目录处理命令ls
- 命令格式:命令 [-选项] [参数]。 例:ls -la -/etc
- 说明:1. 个别命令使用不遵守此格式。2.当有多个选项时,可以写在一起。3.简化选项与完整选项,-a 等于 --all
- 目录处理命令: ls
- 命令名称:ls
- 命令英文原意:list
- 命令所在路径:/bin/ls
- 执行权限:所有用户
- 功能描述:显示目录文件
- 语法:ls 选项[-ald] [文件或目录]
- -a 显示所有文件,包括隐藏文件
- -l 详细信息显示
- -d 查看目录属性
- ls; ls -l; ls -lh; ls -ld
- -rw-r--r--:
- (-)文件类型, - 二进制文件,d 目录,l 软链接文件
- rw-r--r-- (u所有者,g所属组,o其他人)(r读,w写,x执行)
- 目录处理命令
- 目录处理命令:mkdir
- 命令名称:mkdir
- 命令英文原意:make directories
- 命令所在路径:/bin/mkdir
- 执行权限:所有用户
- 语法:mkdir -p[目录名]
- 功能描述:创建新目录,-p 递归创建
- 范例:$ mkdir -p /tmp/Japan/boduo
\$ mkdir /tmp/Japan/longze /tmp/Japan/cangjing
- 目录处理命令:cd
- 命令名称:cd
- 命令英文原意:change directory
- 命令所在路径:shell内置命令
- 执行权限:所有用户
- 语法:cd[目录]
- 功能描述:切换目录
- 范例:$ cd /tmp/Japan/boduo 切换到指定目录
\$ cd .. 回到上一级目录
- 目录处理命令:pwd
- 命令名称:pwd
- 命令英文原意:print working directory
- 命令所在路径:/bin/pwd
- 执行权限:所有用户
- 语法:pwd
- 功能描述:显示当前目录
- 范例:$ pwd
/tmp/Japan
- 目录处理命令:rmdir
- 命令名称:rmdir
- 命令英文原意:remove empty directories
- 命令所在路径:/bin/rmdir
- 执行权限:所有用户
- 语法:rmdir[目录名]
- 功能描述:删除空目录
- 范例:$ rmdir /tmp/Japan/boduo
- 目录处理命令:cp
- 命令名称:cp
- 命令英文原意:copy
- 命令所在路径:/bin/cp
- 执行权限:所有用户
- 语法: cp -rp [原文件或目录] [目标目录]
-r 复制目录
-p 保留文件属性
- 功能描述:复制文件或目录,可以复制过去并且改目录名
- 目录处理命令:mv
- 命令名称:mv
- 命令英文原意:move
- 命令所在路径:/bin/mv
- 执行权限:所有用户
- 语法: mv [原文件或目录] [目标目录]
- 功能描述:剪切文件、改名
- 目录处理命令:rm
- 命令名称:rm
- 命令英文原意:remove
- 命令所在路径:/bin/rm
- 执行权限:所有用户
- 语法:rm -rf [文件或目录]
-r 删除目录
-f 强制删除
- 功能描述:剪切文件、改名
- 文件处理命令
- touch
- 命令名称:touch
- 命令所在路径:/bin/touch
- 执行权限:所有用户
- 语法:touch [文件名]
- 功能描述:创建空文件
- 范例:$ touch Japanlovestory.list
- cat
- 命令名称:cat
- 命令所在路径:/bin/cat
- 执行权限:所有用户
- 语法:cat [文件名]
- 功能描述:显示文件内容
-n 显示行号
- 范例:$ cat /etc/issue
\$ -n /etc/services
- tac
- 命令名称:tac
- 命令所在路径:/usr/bin/tac
- 执行权限:所有用户
- 语法:tac [文件名]
- 功能描述:显示文件内容(反向列示)
- 范例:$ tac /etc/issue
- more
- 命令名称:more
- 命令所在路径:/bin/more
- 执行权限:所有用户
- 语法:more [文件名]
(空格)或f:翻页
(Enter):换行
q或Q:退出
- 功能描述:分页显示文件内容
- 范例:$ more /etc/services
- less
- 命令名称:less
- 命令所在路径:/usr/bin/less
- 执行权限:所有用户
- 语法:less [文件名]
- 功能描述:分页显示文件内容(可向上翻页)
- 范例:$ less /etc/services
- 搜索:/xxx, n 找下一处
- head
- 命令名称:head
- 命令所在路径:/usr/bin/head
- 执行权限:所有用户
- 语法:head [文件名]
- 功能描述:显示文件前面几行
-n 指定行数 (默认显示前十行)
- 范例:$ head -n 20 /etc/services
- tail
- 命令名称:tail
- 命令所在路径:/usr/bin/tail
- 执行权限:所有用户
- 语法:tail [文件名]
- 功能描述:显示文件后面几行
-n 指定行数
-f 动态显示文件末尾内容
- 范例:$ tail -n 18 /etc/services
- 链接命令
- ln
- 命令名称:ln
- 命令英文原意:link
- 命令所在路径:/bin/ln
- 执行权限:所有用户
- 语法:ln -s [原文件] [目标文件]
-s 创建软链接
- 功能描述:生成链接文件
- 软链接特征:类似Windows快捷方式
- lrwxrwxrwx, 软链接文件权限都为rwxrwxrwx
- 文件大小-很小,只是符号链接
- /tmp/issue.soft -> /etc/issue,箭头指向源文件
- 硬链接特征:
- 拷贝cp -p + 同步更新。 (echo "www.lampbrother.net" >> /etc/issue)
- 通过i节点识别
- 不能跨分区
- 不能针对目录使用
- 权限管理命令
- 权限管理命令chmod
- chmod
- 命令名称:chmod
- 命令英文原意:change the permissions mode of a file
- 命令所在路径:/bin/chmod
- 执行权限:所有用户
- 语法:chmod [{ugoa}{+-=}{rwx}] [文件或目录]
chmod 640 xxx.txt
[mode=421] [文件或目录]
(权限的数字表示:r --- 4, w --- 2, x --- 1)
(rwxrw-r--:764)
-R 递归修改
- 功能描述:改变文件或目录权限
- 其他权限管理命令
- 权限管理命令:chown
- 命令名称:chown
- 命令英文原意:change file ownership
- 命令所在路径:/bin/chown
- 执行权限:所有用户
- 语法:chown [用户] [文件或目录]
- 功能描述:改变文件或目录的所有者
- 范例:$ chown shenchao fengjie (改变文件fengjie的所有者为shenchao)
- 权限管理命令:chgrp
- 命令名称:chgrp
- 命令英文原意:change file group ownership
- 命令所在路径:/bin/chgrp
- 执行权限:所有用户
- 语法:chgrp [用户组] [文件或目录]
- 功能描述:改变文件或目录的所属组
- 范例:$ chgrp lampbrother fengjie (改变文件fengjie的所属组为lampbrother)
- 权限管理命令:umask
- 命令名称:umask
- 命令英文原意:the user file-creation mask
- 命令所在路径:Shell内置命令
- 执行权限:所有用户
- 语法:umask [-S]
-S:以rwx形式显示新建文件默认权限
- 功能描述:显示、设置文件的默认权限
- 范例:$ umask -S
- 文件搜索命令
- 文件搜索命令find
- 帮助命令
- 用户管理命令
- 压缩解压命令
- 网络命令
- 关机重启命令 |
using Microsoft.AspNetCore.Mvc.RazorPages;
using System;
using System.Collections.Generic;
using System.Linq;
namespace Projeto.Pages
{
public class CriarPedidoModel : PageModel
{
public string Mensagem { get; set; }
public void OnGet()
{
// Lógica para processar a solicitação GET, se necessário
}
public void OnPost()
{
// Acesso aos dados do formulário usando o objeto Request.Form
var tipoServico = Request.Form["tipoServico"];
var detalhes = Request.Form["detalhes"];
var arquitetoDesigner = Request.Form["arquitetoDesigner"];
var data = Request.Form["data"];
// Verifica se os campos são nulos ou vazios
if (string.IsNullOrWhiteSpace(tipoServico) ||
string.IsNullOrWhiteSpace(detalhes) ||
string.IsNullOrWhiteSpace(arquitetoDesigner) ||
string.IsNullOrWhiteSpace(data))
{
Mensagem = "Por favor, preencha todos os campos do formulário.";
return;
}
// Verificar se o tipo de serviço está disponível
if (!TipoServicoDisponivel(tipoServico))
{
Mensagem = "Tipo de serviço não encontrado.";
return;
}
// Verificar palavras-chave na descrição
if (DescricaoContemPalavrasChave(detalhes))
{
Mensagem = "Detalhes do serviço contêm palavras-chave proibidas.";
return;
}
// Verificar disponibilidade do arquiteto ou designer
if (!ArquitetoDesignerDisponivel(arquitetoDesigner, tipoServico))
{
Mensagem = $"O {arquitetoDesigner} não está disponível para este tipo de serviço.";
return;
}
// Verificar se o trabalhador se apresenta naquela localidade (simulação)
if (!TrabalhadorNaLocalidade(arquitetoDesigner, "LocalidadeDoCliente"))
{
Mensagem = $"{arquitetoDesigner} não está disponível nesta localidade.";
return;
}
// Simulando o armazenamento em uma lista
var pedido = new Pedido
{
TipoServico = tipoServico,
Detalhes = detalhes,
ArquitetoDesigner = arquitetoDesigner,
Data = DateTime.Parse(data)
};
PedidoService.SalvarPedido(pedido);
Mensagem = "Pedido criado com sucesso!";
}
private bool TipoServicoDisponivel(string tipoServico)
{
return TipoServicoService.TipoServicoDisponivel(tipoServico);
}
private bool DescricaoContemPalavrasChave(string descricao)
{
string[] palavrasChaveProibidas = { "orçamento", "materiais" };
foreach (var palavra in palavrasChaveProibidas)
{
if (descricao.Contains(palavra, StringComparison.OrdinalIgnoreCase))
{
return true;
}
}
return false;
}
private bool ArquitetoDesignerDisponivel(string arquitetoDesigner, string tipoServico)
{
// Lógica para verificar se o arquiteto ou designer está disponível para o tipo de serviço
// Você pode implementar a lógica de acordo com seus requisitos
return true;
}
private bool TrabalhadorNaLocalidade(string arquitetoDesigner, string localidade)
{
// Lógica para verificar se o arquiteto ou designer está disponível na localidade
// Você pode implementar a lógica de acordo com seus requisitos
return true;
}
// Simulação de uma classe de serviço que interage com uma lista
public class PedidoService
{
private static readonly List<Pedido> _bancoDeDados = new List<Pedido>();
public static void SalvarPedido(Pedido pedido)
{
// Simula a adição do pedido à lista
_bancoDeDados.Add(pedido);
}
}
// Simulação da entidade Pedido
public class Pedido
{
public string TipoServico { get; set; }
public string Detalhes { get; set; }
public string ArquitetoDesigner { get; set; }
public DateTime Data { get; set; }
}
public class TipoServicoService
{
private static readonly List<string> _tiposDeServicoDisponiveis = new List<string>
{
"Tipo1",
"Tipo2",
"Tipo3",
"Tipo4"
};
public static bool TipoServicoDisponivel(string tipoServico)
{
// Substitua pelo código real para verificar na sua lista
return _tiposDeServicoDisponiveis.Contains(tipoServico, StringComparer.OrdinalIgnoreCase);
}
}
}
} |
import {
Catch,
ExceptionFilter,
ArgumentsHost,
HttpException,
} from '@nestjs/common';
import { I18nContext } from 'nestjs-i18n';
import { I18nTranslations } from 'src/generated';
@Catch(HttpException)
export class HttpExceptionFilter implements ExceptionFilter {
catch(exception: HttpException, host: ArgumentsHost) {
const ctx = host.switchToHttp();
const response = ctx.getResponse();
const i18n = I18nContext.current<I18nTranslations>(host)!;
const request = ctx.getRequest();
const statusCode = exception?.getStatus() || 400;
const message =
exception.message || i18n.t('app.errors.internalServerError');
response.status(statusCode).json({
status: false,
statusCode,
message,
path: request.path,
time: new Date().toISOString(),
data: null,
});
}
} |
# Collections Examples, Kristopher Cooper v0.2a
# LIST -- ORDERED,CHANGEABLE, ALLOWS DUPLICATE VALUES
breakfastFoods = ["Bacon", "Waffles", "Pancakes","Ceral", "Milk"]
# Each item on the list is known as an ELEMENT.
# The position in the list for each is the INDEX.
# The element "Bacon" is at index 0.
# Python Only: index -1 it is the last item on the list
testScores = [95, 100, 25, 15, 27, 35]
classGPA = [3.14, 2.25, 1.74, 1.99, 0.99, 4.25]
# Printing Cotents of an List
#print(breakfastFoods)
#print(testScores)
#print(classGPA)
# Accessing Specific List Elements -- REMEBER FRIST ELEMENT IS INDEX 0
#print(breakfastFoods[0])
#print(testScores[0])
#print(classGPA[0])
# Accessing Last Element in Lists
#print(breakfastFoods[-1])
#print(testScores[-1])
#print(classGPA[-1])
# Pasue - WYOC -- Access the 3rd Element in Each List
#print(breakfastFoods[2])
#print(testScores[2])
#print(classGPA[2])
# Changing Items in a List
#breakfastFoods[0] = "Sausage"
#testScores[0] = 97
#classGPA[0] = 3.57
#print(breakfastFoods[0])
#print(testScores[0])
#print(classGPA[0])
#print(breakfastFoods)
#print(testScores)
#print(classGPA)
# Pause -- WYOC -- Change 5th Element
breakfastFoods[4] = "Eggs"
testScores[4] = 100
classGPA[4] = 4.0
print(breakfastFoods)
print(testScores)
print(classGPA) |
/*---------------------------------------------------------------------------*\
========= |
\\ / F ield | OpenFOAM: The Open Source CFD Toolbox
\\ / O peration |
\\ / A nd | www.openfoam.com
\\/ M anipulation |
-------------------------------------------------------------------------------
Copyright (C) 2007-2022 PCOpt/NTUA
Copyright (C) 2013-2022 FOSS GP
-------------------------------------------------------------------------------
License
This file is part of OpenFOAM.
OpenFOAM is free software: you can redistribute it and/or modify it
under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
OpenFOAM is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
for more details.
You should have received a copy of the GNU General Public License
along with OpenFOAM. If not, see <http://www.gnu.org/licenses/>.
Class
Foam::objectives::objectiveUniformityPatch
Description
Computes and minimizes (half) the variance of the velocity distribution in
a given set of patches
SourceFiles
objectiveUniformityPatch.C
\*---------------------------------------------------------------------------*/
#ifndef objectiveUniformityPatch_H
#define objectiveUniformityPatch_H
#include "objectiveIncompressible.H"
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
namespace Foam
{
namespace objectives
{
/*---------------------------------------------------------------------------*\
Class objectiveUniformityPatch Declaration
\*---------------------------------------------------------------------------*/
class objectiveUniformityPatch
:
public objectiveIncompressible
{
// Private data
//- Where to define the objective
labelList patches_;
//- Mean velocity value per objective patch
vectorField UMean_;
//- Velocity variance per objective patch
scalarField UVar_;
// Private Member Functions
//- Return the objectiveReportPatches
void initialize();
public:
//- Runtime type information
TypeName("uniformityPatch");
// Constructors
//- from components
objectiveUniformityPatch
(
const fvMesh& mesh,
const dictionary& dict,
const word& adjointSolverName,
const word& primalSolverName
);
//- Destructor
virtual ~objectiveUniformityPatch() = default;
// Member Functions
//- Return the objective function value
virtual scalar J();
//- Update values to be added to the adjoint outlet velocity
virtual void update_boundarydJdv();
//- Update values to be added to the adjoint outlet pressure
virtual void update_boundarydJdvn();
//- Update values to be added to the adjoint outlet tangential velocity
virtual void update_boundarydJdvt();
// Helper write functions
//- Write headers for additional columns
virtual void addHeaderColumns() const;
//- Write information to additional columns
virtual void addColumnValues() const;
};
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
} // End namespace objectives
} // End namespace Foam
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
#endif
// ************************************************************************* // |
interface Person{
name:string;
age: number;
dob: Date;
gender: "Male"|"Female"; //literal type
address?:{
building: string,
area:string,
zip: number,
province: string,
}
}
const Man:Person = {
name: "Qasim",
age: 223,
dob: new Date(),
gender:"Male",
address:{
building:'AABC Tower',
area:'Shahr-e-Faisal',
zip: 22221,
province: 'Sind'
}
};
console.log(Man); |
#
# (C) Tenable Network Security, Inc.
#
# The descriptive text and package checks in this plugin were
# extracted from Amazon Linux AMI Security Advisory ALAS-2013-163.
#
include("compat.inc");
if (description)
{
script_id(69722);
script_version("$Revision: 1.7 $");
script_cvs_date("$Date: 2015/01/30 14:43:53 $");
script_cve_id("CVE-2013-0169", "CVE-2013-1486");
script_xref(name:"ALAS", value:"2013-163");
script_xref(name:"RHSA", value:"2013:0273");
script_name(english:"Amazon Linux AMI : java-1.6.0-openjdk (ALAS-2013-163)");
script_summary(english:"Checks rpm output for the updated packages");
script_set_attribute(
attribute:"synopsis",
value:"The remote Amazon Linux AMI host is missing a security update."
);
script_set_attribute(
attribute:"description",
value:
"An improper permission check issue was discovered in the JMX component
in OpenJDK. An untrusted Java application or applet could use this
flaw to bypass Java sandbox restrictions. (CVE-2013-1486)
It was discovered that OpenJDK leaked timing information when
decrypting TLS/SSL protocol encrypted records when CBC-mode cipher
suites were used. A remote attacker could possibly use this flaw to
retrieve plain text from the encrypted packets by using a TLS/SSL
server as a padding oracle. (CVE-2013-0169)"
);
script_set_attribute(
attribute:"see_also",
value:"https://alas.aws.amazon.com/ALAS-2013-163.html"
);
script_set_attribute(
attribute:"solution",
value:"Run 'yum update java-1.6.0-openjdk' to update your system."
);
script_set_cvss_base_vector("CVSS2#AV:N/AC:L/Au:N/C:C/I:C/A:C");
script_set_attribute(attribute:"plugin_type", value:"local");
script_set_attribute(attribute:"cpe", value:"p-cpe:/a:amazon:linux:java-1.6.0-openjdk");
script_set_attribute(attribute:"cpe", value:"p-cpe:/a:amazon:linux:java-1.6.0-openjdk-debuginfo");
script_set_attribute(attribute:"cpe", value:"p-cpe:/a:amazon:linux:java-1.6.0-openjdk-demo");
script_set_attribute(attribute:"cpe", value:"p-cpe:/a:amazon:linux:java-1.6.0-openjdk-devel");
script_set_attribute(attribute:"cpe", value:"p-cpe:/a:amazon:linux:java-1.6.0-openjdk-javadoc");
script_set_attribute(attribute:"cpe", value:"p-cpe:/a:amazon:linux:java-1.6.0-openjdk-src");
script_set_attribute(attribute:"cpe", value:"cpe:/o:amazon:linux");
script_set_attribute(attribute:"patch_publication_date", value:"2013/03/02");
script_set_attribute(attribute:"plugin_publication_date", value:"2013/09/04");
script_end_attributes();
script_category(ACT_GATHER_INFO);
script_copyright(english:"This script is Copyright (C) 2013-2015 Tenable Network Security, Inc.");
script_family(english:"Amazon Linux Local Security Checks");
script_dependencies("ssh_get_info.nasl");
script_require_keys("Host/local_checks_enabled", "Host/AmazonLinux/release", "Host/AmazonLinux/rpm-list");
exit(0);
}
include("audit.inc");
include("global_settings.inc");
include("rpm.inc");
if (!get_kb_item("Host/local_checks_enabled")) audit(AUDIT_LOCAL_CHECKS_NOT_ENABLED);
if (!get_kb_item("Host/AmazonLinux/release")) audit(AUDIT_OS_NOT, "Amazon Linux AMI");
if (!get_kb_item("Host/AmazonLinux/rpm-list")) audit(AUDIT_PACKAGE_LIST_MISSING);
flag = 0;
if (rpm_check(release:"ALA", reference:"java-1.6.0-openjdk-1.6.0.0-56.1.11.8.51.amzn1")) flag++;
if (rpm_check(release:"ALA", reference:"java-1.6.0-openjdk-debuginfo-1.6.0.0-56.1.11.8.51.amzn1")) flag++;
if (rpm_check(release:"ALA", reference:"java-1.6.0-openjdk-demo-1.6.0.0-56.1.11.8.51.amzn1")) flag++;
if (rpm_check(release:"ALA", reference:"java-1.6.0-openjdk-devel-1.6.0.0-56.1.11.8.51.amzn1")) flag++;
if (rpm_check(release:"ALA", reference:"java-1.6.0-openjdk-javadoc-1.6.0.0-56.1.11.8.51.amzn1")) flag++;
if (rpm_check(release:"ALA", reference:"java-1.6.0-openjdk-src-1.6.0.0-56.1.11.8.51.amzn1")) flag++;
if (flag)
{
if (report_verbosity > 0) security_hole(port:0, extra:rpm_report_get());
else security_hole(0);
exit(0);
}
else
{
tested = pkg_tests_get();
if (tested) audit(AUDIT_PACKAGE_NOT_AFFECTED, tested);
else audit(AUDIT_PACKAGE_NOT_INSTALLED, "java-1.6.0-openjdk / java-1.6.0-openjdk-debuginfo / etc");
} |
const STORAGE_NAME = "qb41tc90zEkiDiOh6UcjD0ChhuSmRyfh";
const SPELL_NAMES = get_spell_names();
let undo = () => {};
function get_spell_names() {
let spells = Object.values(all_spells).sort(compare_spells);
return spells.map((spell) => spell.name);
}
function get_card_names() {
let state = Array.from(
document.querySelectorAll("#cards-container .card")
).map((card) => card.dataset.title);
return state;
}
/* There are 3 where we can undo:
- remove_card
- remove_all
- add_card
*/
function make_undo(callback) {
// Get the button element
const button = document.getElementById("undo-button");
// Disable the button
button.disabled = false;
undo = () => {
callback();
sort_cards();
serialize();
undo = () => {};
button.disabled = true;
};
}
function remove_card(name, undoable) {
const cards = document.querySelectorAll(".card");
cards.forEach((card) => {
if (card.dataset.title === name) {
card.remove();
}
});
// sort_cards(); // no need to sort on remove
serialize();
if (undoable) {
make_undo(() => {
console.log("Undoing remove", name);
add_card(name, false);
});
}
}
function remove_all(undoable) {
const names = get_card_names();
if (names.length == 0) {
return;
}
let div = document.getElementById("cards-container");
div.innerHTML = "";
// sort_cards(); // no need to sort on remove
serialize();
if (undoable) {
make_undo(() => {
console.log("Undoing remove_all", names);
names.forEach((name) => {
add_card(name, false);
});
});
}
}
function add_card(name, undoable) {
let spell = all_spells[name];
const container = document.getElementById("cards-container");
const card = document.createElement("div");
card.className = "card";
card.dataset.title = name;
if (spell.casting_time.includes("bonus action")) {
card.classList.add("bonusaction");
} else if (spell.casting_time.includes("reaction")) {
card.classList.add("reaction");
} else {
card.classList.add("action");
}
card.onclick = function (event) {
event.preventDefault();
remove_card(spell.name, true);
};
card.innerHTML = make_card(spell);
container.appendChild(card);
sort_cards();
serialize();
if (undoable) {
make_undo(() => {
console.log("Undoing add", spell.name);
remove_card(name, false);
});
}
}
function compare_spells(a, b) {
// order by level and then by name
if (a.level === b.level) {
if (a.name < b.name) {
return -1;
}
if (a.name > b.name) {
return 1;
}
return 0;
}
return a.level < b.level ? -1 : 1;
}
function compare_cards(card1, card2) {
return compare_spells(card2spell(card1), card2spell(card2));
}
function card2spell(card) {
const h1 = card.querySelector("h1#spellname");
let name = h1.textContent.trim();
return all_spells[name];
}
function sort_cards() {
let cards = Array.from(document.querySelectorAll(".card"));
cards = cards.sort(compare_cards);
let container = document.getElementById("cards-container");
container.innerHTML = "";
// Re-append the sorted div elements to the container
cards.forEach((card) => container.appendChild(card));
}
function serialize() {
const state = get_card_names();
const serializedState = JSON.stringify(state);
localStorage.setItem(STORAGE_NAME, serializedState);
console.log("Data stored: ", serializedState);
}
function restore() {
const serializedState = localStorage.getItem(STORAGE_NAME);
if (serializedState) {
const state = JSON.parse(serializedState);
console.log("Data retrieved:", state);
for (let name of state) {
add_card(name);
}
sort_cards();
}
}
function make_card(spell) {
return `
<div class="card-header">
<h1 id="spellname">${spell.name}</h1>
${
spell.duration.includes("Concentration")
? `<div class="card-c">C</div>`
: ``
}
</div>
<h2 id="spellschool">${spell.school}</h2>
<div class="details">
<div class="detail">
<strong>CASTING TIME</strong>
<span>${spell.casting_time}</span>
</div>
<div class="detail">
<strong>RANGE</strong>
<span>${spell.range}</span>
</div>
<div class="detail">
<strong>COMPONENTS</strong>
<span>${spell.components}</span>
</div>
<div class="detail">
<strong>DURATION</strong>
<span>${spell.duration}</span>
</div>
</div>
<div class="description">
${
spell.materials
? "<p><strong>Materials:</strong> " + spell.materials + "</p>"
: ""
}
${spell.description}
${
spell.upcast
? "<p><strong>At Higher Levels:</strong> " + spell.upcast + "</p>"
: ""
}`;
}
document.addEventListener("click", function (event) {
const suggestions = document.getElementById("suggestions");
const searchInput = document.getElementById("searchInput");
if (!suggestions.contains(event.target) && event.target !== searchInput) {
clear_suggestions();
}
});
function clear_suggestions() {
const suggestions = document.getElementById("suggestions");
const searchInput = document.getElementById("searchInput");
suggestions.innerHTML = ""; // Clear suggestions if clicked outside
searchInput.value = ""; // also clear input field
}
document.querySelector("#searchInput").addEventListener("input", function () {
const input = this.value;
const suggestions = document.getElementById("suggestions");
suggestions.innerHTML = ""; // Clear previous suggestions
const cards = get_card_names();
if (input.length > 0) {
const filteredKeys = SPELL_NAMES.filter(
(key) =>
key.toLowerCase().includes(input.toLowerCase()) && !cards.includes(key)
);
filteredKeys.forEach((key) => {
const li = document.createElement("li");
let spell = all_spells[key];
li.innerHTML = `<strong>${key}</strong>${number_to_level(spell.level)}`;
li.onclick = function () {
add_card(spell.name, true);
clear_suggestions();
};
suggestions.appendChild(li);
});
}
});
function number_to_level(num) {
switch (num) {
case 0:
return "Cantrip";
case 1:
return "1st";
case 2:
return "2nd";
case 3:
return "3rd";
default:
return String(num) + "th";
}
}
document.getElementById("save-button").addEventListener("click", function () {
const data = get_card_names();
const encoded = encodeURIComponent(JSON.stringify(data));
const dataStr = `data:text/json;charset=utf-8,${encoded}`;
const downloadAnchorNode = document.createElement("a");
downloadAnchorNode.setAttribute("href", dataStr);
downloadAnchorNode.setAttribute("download", "cards.json");
document.body.appendChild(downloadAnchorNode); // Required for Firefox
downloadAnchorNode.click();
downloadAnchorNode.remove();
});
document
.getElementById("load-spells")
.addEventListener("change", function (event) {
const file = event.target.files[0];
if (!file || file.type !== "application/json") {
console.error("Please select a valid JSON file.");
event.target.value = ""; // Reset the file input value
return;
}
const reader = new FileReader();
reader.onload = function (e) {
let jsonContent;
const content = e.target.result;
try {
jsonContent = Array.from(JSON.parse(content));
} catch (err) {
console.error("Error parsing JSON:", err);
return;
}
remove_all();
jsonContent.forEach((name) => {
if (all_spells[name]) {
console.log("Adding", name);
add_card(name, false);
}
});
sort_cards();
};
reader.readAsText(file);
// Reset the file input value so that the change event can be triggered again
event.target.value = "";
});
restore(); |
"""
SQL-style merge routines
"""
from __future__ import annotations
import copy
import datetime
from functools import partial
import hashlib
import string
from typing import (
TYPE_CHECKING,
Hashable,
cast,
)
import warnings
import numpy as np
from pandas._libs import (
Timedelta,
hashtable as libhashtable,
join as libjoin,
lib,
)
from pandas._typing import (
ArrayLike,
DtypeObj,
FrameOrSeries,
IndexLabel,
Suffixes,
)
from pandas.errors import MergeError
from pandas.util._decorators import (
Appender,
Substitution,
)
from pandas.core.dtypes.cast import find_common_type
from pandas.core.dtypes.common import (
ensure_float64,
ensure_int64,
ensure_object,
is_array_like,
is_bool,
is_bool_dtype,
is_categorical_dtype,
is_datetime64tz_dtype,
is_dtype_equal,
is_extension_array_dtype,
is_float_dtype,
is_integer,
is_integer_dtype,
is_list_like,
is_number,
is_numeric_dtype,
is_object_dtype,
needs_i8_conversion,
)
from pandas.core.dtypes.generic import (
ABCDataFrame,
ABCSeries,
)
from pandas.core.dtypes.missing import (
isna,
na_value_for_dtype,
)
from pandas import (
Categorical,
Index,
MultiIndex,
Series,
)
from pandas.core import groupby
import pandas.core.algorithms as algos
from pandas.core.arrays import ExtensionArray
import pandas.core.common as com
from pandas.core.construction import extract_array
from pandas.core.frame import _merge_doc
from pandas.core.internals import concatenate_managers
from pandas.core.sorting import is_int64_overflow_possible
if TYPE_CHECKING:
from pandas import DataFrame
from pandas.core.arrays import DatetimeArray
@Substitution("\nleft : DataFrame or named Series")
@Appender(_merge_doc, indents=0)
def merge(
left: DataFrame | Series,
right: DataFrame | Series,
how: str = "inner",
on: IndexLabel | None = None,
left_on: IndexLabel | None = None,
right_on: IndexLabel | None = None,
left_index: bool = False,
right_index: bool = False,
sort: bool = False,
suffixes: Suffixes = ("_x", "_y"),
copy: bool = True,
indicator: bool = False,
validate: str | None = None,
) -> DataFrame:
op = _MergeOperation(
left,
right,
how=how,
on=on,
left_on=left_on,
right_on=right_on,
left_index=left_index,
right_index=right_index,
sort=sort,
suffixes=suffixes,
copy=copy,
indicator=indicator,
validate=validate,
)
return op.get_result()
if __debug__:
merge.__doc__ = _merge_doc % "\nleft : DataFrame"
def _groupby_and_merge(by, left: DataFrame, right: DataFrame, merge_pieces):
"""
groupby & merge; we are always performing a left-by type operation
Parameters
----------
by: field to group
left: DataFrame
right: DataFrame
merge_pieces: function for merging
"""
pieces = []
if not isinstance(by, (list, tuple)):
by = [by]
lby = left.groupby(by, sort=False)
rby: groupby.DataFrameGroupBy | None = None
# if we can groupby the rhs
# then we can get vastly better perf
if all(item in right.columns for item in by):
rby = right.groupby(by, sort=False)
for key, lhs in lby:
if rby is None:
rhs = right
else:
try:
rhs = right.take(rby.indices[key])
except KeyError:
# key doesn't exist in left
lcols = lhs.columns.tolist()
cols = lcols + [r for r in right.columns if r not in set(lcols)]
merged = lhs.reindex(columns=cols)
merged.index = range(len(merged))
pieces.append(merged)
continue
merged = merge_pieces(lhs, rhs)
# make sure join keys are in the merged
# TODO, should merge_pieces do this?
merged[by] = key
pieces.append(merged)
# preserve the original order
# if we have a missing piece this can be reset
from pandas.core.reshape.concat import concat
result = concat(pieces, ignore_index=True)
result = result.reindex(columns=pieces[0].columns, copy=False)
return result, lby
def merge_ordered(
left: DataFrame,
right: DataFrame,
on: IndexLabel | None = None,
left_on: IndexLabel | None = None,
right_on: IndexLabel | None = None,
left_by=None,
right_by=None,
fill_method: str | None = None,
suffixes: Suffixes = ("_x", "_y"),
how: str = "outer",
) -> DataFrame:
"""
Perform merge with optional filling/interpolation.
Designed for ordered data like time series data. Optionally
perform group-wise merge (see examples).
Parameters
----------
left : DataFrame
right : DataFrame
on : label or list
Field names to join on. Must be found in both DataFrames.
left_on : label or list, or array-like
Field names to join on in left DataFrame. Can be a vector or list of
vectors of the length of the DataFrame to use a particular vector as
the join key instead of columns.
right_on : label or list, or array-like
Field names to join on in right DataFrame or vector/list of vectors per
left_on docs.
left_by : column name or list of column names
Group left DataFrame by group columns and merge piece by piece with
right DataFrame.
right_by : column name or list of column names
Group right DataFrame by group columns and merge piece by piece with
left DataFrame.
fill_method : {'ffill', None}, default None
Interpolation method for data.
suffixes : list-like, default is ("_x", "_y")
A length-2 sequence where each element is optionally a string
indicating the suffix to add to overlapping column names in
`left` and `right` respectively. Pass a value of `None` instead
of a string to indicate that the column name from `left` or
`right` should be left as-is, with no suffix. At least one of the
values must not be None.
.. versionchanged:: 0.25.0
how : {'left', 'right', 'outer', 'inner'}, default 'outer'
* left: use only keys from left frame (SQL: left outer join)
* right: use only keys from right frame (SQL: right outer join)
* outer: use union of keys from both frames (SQL: full outer join)
* inner: use intersection of keys from both frames (SQL: inner join).
Returns
-------
DataFrame
The merged DataFrame output type will the be same as
'left', if it is a subclass of DataFrame.
See Also
--------
merge : Merge with a database-style join.
merge_asof : Merge on nearest keys.
Examples
--------
>>> df1 = pd.DataFrame(
... {
... "key": ["a", "c", "e", "a", "c", "e"],
... "lvalue": [1, 2, 3, 1, 2, 3],
... "group": ["a", "a", "a", "b", "b", "b"]
... }
... )
>>> df1
key lvalue group
0 a 1 a
1 c 2 a
2 e 3 a
3 a 1 b
4 c 2 b
5 e 3 b
>>> df2 = pd.DataFrame({"key": ["b", "c", "d"], "rvalue": [1, 2, 3]})
>>> df2
key rvalue
0 b 1
1 c 2
2 d 3
>>> merge_ordered(df1, df2, fill_method="ffill", left_by="group")
key lvalue group rvalue
0 a 1 a NaN
1 b 1 a 1.0
2 c 2 a 2.0
3 d 2 a 3.0
4 e 3 a 3.0
5 a 1 b NaN
6 b 1 b 1.0
7 c 2 b 2.0
8 d 2 b 3.0
9 e 3 b 3.0
"""
def _merger(x, y) -> DataFrame:
# perform the ordered merge operation
op = _OrderedMerge(
x,
y,
on=on,
left_on=left_on,
right_on=right_on,
suffixes=suffixes,
fill_method=fill_method,
how=how,
)
return op.get_result()
if left_by is not None and right_by is not None:
raise ValueError("Can only group either left or right frames")
elif left_by is not None:
if isinstance(left_by, str):
left_by = [left_by]
check = set(left_by).difference(left.columns)
if len(check) != 0:
raise KeyError(f"{check} not found in left columns")
result, _ = _groupby_and_merge(left_by, left, right, lambda x, y: _merger(x, y))
elif right_by is not None:
if isinstance(right_by, str):
right_by = [right_by]
check = set(right_by).difference(right.columns)
if len(check) != 0:
raise KeyError(f"{check} not found in right columns")
result, _ = _groupby_and_merge(
right_by, right, left, lambda x, y: _merger(y, x)
)
else:
result = _merger(left, right)
return result
def merge_asof(
left: DataFrame | Series,
right: DataFrame | Series,
on: IndexLabel | None = None,
left_on: IndexLabel | None = None,
right_on: IndexLabel | None = None,
left_index: bool = False,
right_index: bool = False,
by=None,
left_by=None,
right_by=None,
suffixes: Suffixes = ("_x", "_y"),
tolerance=None,
allow_exact_matches: bool = True,
direction: str = "backward",
) -> DataFrame:
"""
Perform an asof merge.
This is similar to a left-join except that we match on nearest
key rather than equal keys. Both DataFrames must be sorted by the key.
For each row in the left DataFrame:
- A "backward" search selects the last row in the right DataFrame whose
'on' key is less than or equal to the left's key.
- A "forward" search selects the first row in the right DataFrame whose
'on' key is greater than or equal to the left's key.
- A "nearest" search selects the row in the right DataFrame whose 'on'
key is closest in absolute distance to the left's key.
The default is "backward" and is compatible in versions below 0.20.0.
The direction parameter was added in version 0.20.0 and introduces
"forward" and "nearest".
Optionally match on equivalent keys with 'by' before searching with 'on'.
Parameters
----------
left : DataFrame or named Series
right : DataFrame or named Series
on : label
Field name to join on. Must be found in both DataFrames.
The data MUST be ordered. Furthermore this must be a numeric column,
such as datetimelike, integer, or float. On or left_on/right_on
must be given.
left_on : label
Field name to join on in left DataFrame.
right_on : label
Field name to join on in right DataFrame.
left_index : bool
Use the index of the left DataFrame as the join key.
right_index : bool
Use the index of the right DataFrame as the join key.
by : column name or list of column names
Match on these columns before performing merge operation.
left_by : column name
Field names to match on in the left DataFrame.
right_by : column name
Field names to match on in the right DataFrame.
suffixes : 2-length sequence (tuple, list, ...)
Suffix to apply to overlapping column names in the left and right
side, respectively.
tolerance : int or Timedelta, optional, default None
Select asof tolerance within this range; must be compatible
with the merge index.
allow_exact_matches : bool, default True
- If True, allow matching with the same 'on' value
(i.e. less-than-or-equal-to / greater-than-or-equal-to)
- If False, don't match the same 'on' value
(i.e., strictly less-than / strictly greater-than).
direction : 'backward' (default), 'forward', or 'nearest'
Whether to search for prior, subsequent, or closest matches.
Returns
-------
merged : DataFrame
See Also
--------
merge : Merge with a database-style join.
merge_ordered : Merge with optional filling/interpolation.
Examples
--------
>>> left = pd.DataFrame({"a": [1, 5, 10], "left_val": ["a", "b", "c"]})
>>> left
a left_val
0 1 a
1 5 b
2 10 c
>>> right = pd.DataFrame({"a": [1, 2, 3, 6, 7], "right_val": [1, 2, 3, 6, 7]})
>>> right
a right_val
0 1 1
1 2 2
2 3 3
3 6 6
4 7 7
>>> pd.merge_asof(left, right, on="a")
a left_val right_val
0 1 a 1
1 5 b 3
2 10 c 7
>>> pd.merge_asof(left, right, on="a", allow_exact_matches=False)
a left_val right_val
0 1 a NaN
1 5 b 3.0
2 10 c 7.0
>>> pd.merge_asof(left, right, on="a", direction="forward")
a left_val right_val
0 1 a 1.0
1 5 b 6.0
2 10 c NaN
>>> pd.merge_asof(left, right, on="a", direction="nearest")
a left_val right_val
0 1 a 1
1 5 b 6
2 10 c 7
We can use indexed DataFrames as well.
>>> left = pd.DataFrame({"left_val": ["a", "b", "c"]}, index=[1, 5, 10])
>>> left
left_val
1 a
5 b
10 c
>>> right = pd.DataFrame({"right_val": [1, 2, 3, 6, 7]}, index=[1, 2, 3, 6, 7])
>>> right
right_val
1 1
2 2
3 3
6 6
7 7
>>> pd.merge_asof(left, right, left_index=True, right_index=True)
left_val right_val
1 a 1
5 b 3
10 c 7
Here is a real-world times-series example
>>> quotes = pd.DataFrame(
... {
... "time": [
... pd.Timestamp("2016-05-25 13:30:00.023"),
... pd.Timestamp("2016-05-25 13:30:00.023"),
... pd.Timestamp("2016-05-25 13:30:00.030"),
... pd.Timestamp("2016-05-25 13:30:00.041"),
... pd.Timestamp("2016-05-25 13:30:00.048"),
... pd.Timestamp("2016-05-25 13:30:00.049"),
... pd.Timestamp("2016-05-25 13:30:00.072"),
... pd.Timestamp("2016-05-25 13:30:00.075")
... ],
... "ticker": [
... "GOOG",
... "MSFT",
... "MSFT",
... "MSFT",
... "GOOG",
... "AAPL",
... "GOOG",
... "MSFT"
... ],
... "bid": [720.50, 51.95, 51.97, 51.99, 720.50, 97.99, 720.50, 52.01],
... "ask": [720.93, 51.96, 51.98, 52.00, 720.93, 98.01, 720.88, 52.03]
... }
... )
>>> quotes
time ticker bid ask
0 2016-05-25 13:30:00.023 GOOG 720.50 720.93
1 2016-05-25 13:30:00.023 MSFT 51.95 51.96
2 2016-05-25 13:30:00.030 MSFT 51.97 51.98
3 2016-05-25 13:30:00.041 MSFT 51.99 52.00
4 2016-05-25 13:30:00.048 GOOG 720.50 720.93
5 2016-05-25 13:30:00.049 AAPL 97.99 98.01
6 2016-05-25 13:30:00.072 GOOG 720.50 720.88
7 2016-05-25 13:30:00.075 MSFT 52.01 52.03
>>> trades = pd.DataFrame(
... {
... "time": [
... pd.Timestamp("2016-05-25 13:30:00.023"),
... pd.Timestamp("2016-05-25 13:30:00.038"),
... pd.Timestamp("2016-05-25 13:30:00.048"),
... pd.Timestamp("2016-05-25 13:30:00.048"),
... pd.Timestamp("2016-05-25 13:30:00.048")
... ],
... "ticker": ["MSFT", "MSFT", "GOOG", "GOOG", "AAPL"],
... "price": [51.95, 51.95, 720.77, 720.92, 98.0],
... "quantity": [75, 155, 100, 100, 100]
... }
... )
>>> trades
time ticker price quantity
0 2016-05-25 13:30:00.023 MSFT 51.95 75
1 2016-05-25 13:30:00.038 MSFT 51.95 155
2 2016-05-25 13:30:00.048 GOOG 720.77 100
3 2016-05-25 13:30:00.048 GOOG 720.92 100
4 2016-05-25 13:30:00.048 AAPL 98.00 100
By default we are taking the asof of the quotes
>>> pd.merge_asof(trades, quotes, on="time", by="ticker")
time ticker price quantity bid ask
0 2016-05-25 13:30:00.023 MSFT 51.95 75 51.95 51.96
1 2016-05-25 13:30:00.038 MSFT 51.95 155 51.97 51.98
2 2016-05-25 13:30:00.048 GOOG 720.77 100 720.50 720.93
3 2016-05-25 13:30:00.048 GOOG 720.92 100 720.50 720.93
4 2016-05-25 13:30:00.048 AAPL 98.00 100 NaN NaN
We only asof within 2ms between the quote time and the trade time
>>> pd.merge_asof(
... trades, quotes, on="time", by="ticker", tolerance=pd.Timedelta("2ms")
... )
time ticker price quantity bid ask
0 2016-05-25 13:30:00.023 MSFT 51.95 75 51.95 51.96
1 2016-05-25 13:30:00.038 MSFT 51.95 155 NaN NaN
2 2016-05-25 13:30:00.048 GOOG 720.77 100 720.50 720.93
3 2016-05-25 13:30:00.048 GOOG 720.92 100 720.50 720.93
4 2016-05-25 13:30:00.048 AAPL 98.00 100 NaN NaN
We only asof within 10ms between the quote time and the trade time
and we exclude exact matches on time. However *prior* data will
propagate forward
>>> pd.merge_asof(
... trades,
... quotes,
... on="time",
... by="ticker",
... tolerance=pd.Timedelta("10ms"),
... allow_exact_matches=False
... )
time ticker price quantity bid ask
0 2016-05-25 13:30:00.023 MSFT 51.95 75 NaN NaN
1 2016-05-25 13:30:00.038 MSFT 51.95 155 51.97 51.98
2 2016-05-25 13:30:00.048 GOOG 720.77 100 NaN NaN
3 2016-05-25 13:30:00.048 GOOG 720.92 100 NaN NaN
4 2016-05-25 13:30:00.048 AAPL 98.00 100 NaN NaN
"""
op = _AsOfMerge(
left,
right,
on=on,
left_on=left_on,
right_on=right_on,
left_index=left_index,
right_index=right_index,
by=by,
left_by=left_by,
right_by=right_by,
suffixes=suffixes,
how="asof",
tolerance=tolerance,
allow_exact_matches=allow_exact_matches,
direction=direction,
)
return op.get_result()
# TODO: transformations??
# TODO: only copy DataFrames when modification necessary
class _MergeOperation:
"""
Perform a database (SQL) merge operation between two DataFrame or Series
objects using either columns as keys or their row indexes
"""
_merge_type = "merge"
def __init__(
self,
left: DataFrame | Series,
right: DataFrame | Series,
how: str = "inner",
on: IndexLabel | None = None,
left_on: IndexLabel | None = None,
right_on: IndexLabel | None = None,
axis: int = 1,
left_index: bool = False,
right_index: bool = False,
sort: bool = True,
suffixes: Suffixes = ("_x", "_y"),
copy: bool = True,
indicator: bool = False,
validate: str | None = None,
):
_left = _validate_operand(left)
_right = _validate_operand(right)
self.left = self.orig_left = _left
self.right = self.orig_right = _right
self.how = how
# bm_axis -> the axis on the BlockManager
self.bm_axis = axis
# axis --> the axis on the Series/DataFrame
self.axis = 1 - axis if self.left.ndim == 2 else 0
self.on = com.maybe_make_list(on)
self.left_on = com.maybe_make_list(left_on)
self.right_on = com.maybe_make_list(right_on)
self.copy = copy
self.suffixes = suffixes
self.sort = sort
self.left_index = left_index
self.right_index = right_index
self.indicator = indicator
self.indicator_name: str | None
if isinstance(self.indicator, str):
self.indicator_name = self.indicator
elif isinstance(self.indicator, bool):
self.indicator_name = "_merge" if self.indicator else None
else:
raise ValueError(
"indicator option can only accept boolean or string arguments"
)
if not is_bool(left_index):
raise ValueError(
f"left_index parameter must be of type bool, not {type(left_index)}"
)
if not is_bool(right_index):
raise ValueError(
f"right_index parameter must be of type bool, not {type(right_index)}"
)
# warn user when merging between different levels
if _left.columns.nlevels != _right.columns.nlevels:
msg = (
"merging between different levels is deprecated and will be removed "
f"in a future version. ({left.columns.nlevels} levels on the left,"
f"{right.columns.nlevels} on the right)"
)
# stacklevel chosen to be correct when this is reached via pd.merge
# (and not DataFrame.join)
warnings.warn(msg, FutureWarning, stacklevel=3)
self._validate_specification()
cross_col = None
if self.how == "cross":
(
self.left,
self.right,
self.how,
cross_col,
) = self._create_cross_configuration(self.left, self.right)
self.left_on = self.right_on = [cross_col]
self._cross = cross_col
# note this function has side effects
(
self.left_join_keys,
self.right_join_keys,
self.join_names,
) = self._get_merge_keys()
# validate the merge keys dtypes. We may need to coerce
# to avoid incompatible dtypes
self._maybe_coerce_merge_keys()
# If argument passed to validate,
# check if columns specified as unique
# are in fact unique.
if validate is not None:
self._validate(validate)
def get_result(self) -> DataFrame:
if self.indicator:
self.left, self.right = self._indicator_pre_merge(self.left, self.right)
join_index, left_indexer, right_indexer = self._get_join_info()
llabels, rlabels = _items_overlap_with_suffix(
self.left._info_axis, self.right._info_axis, self.suffixes
)
lindexers = {1: left_indexer} if left_indexer is not None else {}
rindexers = {1: right_indexer} if right_indexer is not None else {}
result_data = concatenate_managers(
[(self.left._mgr, lindexers), (self.right._mgr, rindexers)],
axes=[llabels.append(rlabels), join_index],
concat_axis=0,
copy=self.copy,
)
typ = self.left._constructor
result = typ(result_data).__finalize__(self, method=self._merge_type)
if self.indicator:
result = self._indicator_post_merge(result)
self._maybe_add_join_keys(result, left_indexer, right_indexer)
self._maybe_restore_index_levels(result)
self._maybe_drop_cross_column(result, self._cross)
return result.__finalize__(self, method="merge")
def _maybe_drop_cross_column(
self, result: DataFrame, cross_col: str | None
) -> None:
if cross_col is not None:
result.drop(columns=cross_col, inplace=True)
def _indicator_pre_merge(
self, left: DataFrame, right: DataFrame
) -> tuple[DataFrame, DataFrame]:
columns = left.columns.union(right.columns)
for i in ["_left_indicator", "_right_indicator"]:
if i in columns:
raise ValueError(
"Cannot use `indicator=True` option when "
f"data contains a column named {i}"
)
if self.indicator_name in columns:
raise ValueError(
"Cannot use name of an existing column for indicator column"
)
left = left.copy()
right = right.copy()
left["_left_indicator"] = 1
left["_left_indicator"] = left["_left_indicator"].astype("int8")
right["_right_indicator"] = 2
right["_right_indicator"] = right["_right_indicator"].astype("int8")
return left, right
def _indicator_post_merge(self, result: DataFrame) -> DataFrame:
result["_left_indicator"] = result["_left_indicator"].fillna(0)
result["_right_indicator"] = result["_right_indicator"].fillna(0)
result[self.indicator_name] = Categorical(
(result["_left_indicator"] + result["_right_indicator"]),
categories=[1, 2, 3],
)
result[self.indicator_name] = result[self.indicator_name].cat.rename_categories(
["left_only", "right_only", "both"]
)
result = result.drop(labels=["_left_indicator", "_right_indicator"], axis=1)
return result
def _maybe_restore_index_levels(self, result: DataFrame) -> None:
"""
Restore index levels specified as `on` parameters
Here we check for cases where `self.left_on` and `self.right_on` pairs
each reference an index level in their respective DataFrames. The
joined columns corresponding to these pairs are then restored to the
index of `result`.
**Note:** This method has side effects. It modifies `result` in-place
Parameters
----------
result: DataFrame
merge result
Returns
-------
None
"""
names_to_restore = []
for name, left_key, right_key in zip(
self.join_names, self.left_on, self.right_on
):
if (
self.orig_left._is_level_reference(left_key)
and self.orig_right._is_level_reference(right_key)
and name not in result.index.names
):
names_to_restore.append(name)
if names_to_restore:
result.set_index(names_to_restore, inplace=True)
def _maybe_add_join_keys(
self,
result: DataFrame,
left_indexer: np.ndarray | None,
right_indexer: np.ndarray | None,
) -> None:
left_has_missing = None
right_has_missing = None
keys = zip(self.join_names, self.left_on, self.right_on)
for i, (name, lname, rname) in enumerate(keys):
if not _should_fill(lname, rname):
continue
take_left, take_right = None, None
if name in result:
if left_indexer is not None and right_indexer is not None:
if name in self.left:
if left_has_missing is None:
left_has_missing = (left_indexer == -1).any()
if left_has_missing:
take_right = self.right_join_keys[i]
if not is_dtype_equal(
result[name].dtype, self.left[name].dtype
):
take_left = self.left[name]._values
elif name in self.right:
if right_has_missing is None:
right_has_missing = (right_indexer == -1).any()
if right_has_missing:
take_left = self.left_join_keys[i]
if not is_dtype_equal(
result[name].dtype, self.right[name].dtype
):
take_right = self.right[name]._values
elif left_indexer is not None and is_array_like(self.left_join_keys[i]):
take_left = self.left_join_keys[i]
take_right = self.right_join_keys[i]
if take_left is not None or take_right is not None:
if take_left is None:
lvals = result[name]._values
else:
# TODO: can we pin down take_left's type earlier?
take_left = extract_array(take_left, extract_numpy=True)
lfill = na_value_for_dtype(take_left.dtype)
lvals = algos.take_nd(take_left, left_indexer, fill_value=lfill)
if take_right is None:
rvals = result[name]._values
else:
# TODO: can we pin down take_right's type earlier?
take_right = extract_array(take_right, extract_numpy=True)
rfill = na_value_for_dtype(take_right.dtype)
rvals = algos.take_nd(take_right, right_indexer, fill_value=rfill)
# if we have an all missing left_indexer
# make sure to just use the right values or vice-versa
mask_left = left_indexer == -1
mask_right = right_indexer == -1
# error: Item "bool" of "Union[Any, bool]" has no attribute "all"
if mask_left.all(): # type: ignore[union-attr]
key_col = Index(rvals)
result_dtype = rvals.dtype
# error: Item "bool" of "Union[Any, bool]" has no attribute "all"
elif (
right_indexer is not None
and mask_right.all() # type: ignore[union-attr]
):
key_col = Index(lvals)
result_dtype = lvals.dtype
else:
key_col = Index(lvals).where(~mask_left, rvals)
result_dtype = find_common_type([lvals.dtype, rvals.dtype])
if result._is_label_reference(name):
result[name] = Series(
key_col, dtype=result_dtype, index=result.index
)
elif result._is_level_reference(name):
if isinstance(result.index, MultiIndex):
key_col.name = name
idx_list = [
result.index.get_level_values(level_name)
if level_name != name
else key_col
for level_name in result.index.names
]
result.set_index(idx_list, inplace=True)
else:
result.index = Index(key_col, name=name)
else:
result.insert(i, name or f"key_{i}", key_col)
def _get_join_indexers(self) -> tuple[np.ndarray, np.ndarray]:
"""return the join indexers"""
# Both returned ndarrays are np.intp
return get_join_indexers(
self.left_join_keys, self.right_join_keys, sort=self.sort, how=self.how
)
def _get_join_info(
self,
) -> tuple[Index, np.ndarray | None, np.ndarray | None]:
# Both returned ndarrays are np.intp (if not None)
left_ax = self.left.axes[self.axis]
right_ax = self.right.axes[self.axis]
if self.left_index and self.right_index and self.how != "asof":
join_index, left_indexer, right_indexer = left_ax.join(
right_ax, how=self.how, return_indexers=True, sort=self.sort
)
elif self.right_index and self.how == "left":
join_index, left_indexer, right_indexer = _left_join_on_index(
left_ax, right_ax, self.left_join_keys, sort=self.sort
)
elif self.left_index and self.how == "right":
join_index, right_indexer, left_indexer = _left_join_on_index(
right_ax, left_ax, self.right_join_keys, sort=self.sort
)
else:
(left_indexer, right_indexer) = self._get_join_indexers()
if self.right_index:
if len(self.left) > 0:
join_index = self._create_join_index(
self.left.index,
self.right.index,
left_indexer,
how="right",
)
else:
join_index = self.right.index.take(right_indexer)
left_indexer = np.array([-1] * len(join_index), dtype=np.intp)
elif self.left_index:
if self.how == "asof":
# GH#33463 asof should always behave like a left merge
join_index = self._create_join_index(
self.left.index,
self.right.index,
left_indexer,
how="left",
)
elif len(self.right) > 0:
join_index = self._create_join_index(
self.right.index,
self.left.index,
right_indexer,
how="left",
)
else:
join_index = self.left.index.take(left_indexer)
right_indexer = np.array([-1] * len(join_index), dtype=np.intp)
else:
join_index = Index(np.arange(len(left_indexer)))
if len(join_index) == 0:
join_index = join_index.astype(object)
return join_index, left_indexer, right_indexer
def _create_join_index(
self,
index: Index,
other_index: Index,
indexer: np.ndarray,
how: str = "left",
) -> Index:
"""
Create a join index by rearranging one index to match another
Parameters
----------
index : Index being rearranged
other_index : Index used to supply values not found in index
indexer : np.ndarray[np.intp] how to rearrange index
how : str
Replacement is only necessary if indexer based on other_index.
Returns
-------
Index
"""
if self.how in (how, "outer") and not isinstance(other_index, MultiIndex):
# if final index requires values in other_index but not target
# index, indexer may hold missing (-1) values, causing Index.take
# to take the final value in target index. So, we set the last
# element to be the desired fill value. We do not use allow_fill
# and fill_value because it throws a ValueError on integer indices
mask = indexer == -1
if np.any(mask):
fill_value = na_value_for_dtype(index.dtype, compat=False)
index = index.append(Index([fill_value]))
return index.take(indexer)
def _get_merge_keys(self):
"""
Note: has side effects (copy/delete key columns)
Parameters
----------
left
right
on
Returns
-------
left_keys, right_keys
"""
left_keys = []
right_keys = []
# error: Need type annotation for 'join_names' (hint: "join_names: List[<type>]
# = ...")
join_names = [] # type: ignore[var-annotated]
right_drop = []
left_drop = []
left, right = self.left, self.right
is_lkey = lambda x: is_array_like(x) and len(x) == len(left)
is_rkey = lambda x: is_array_like(x) and len(x) == len(right)
# Note that pd.merge_asof() has separate 'on' and 'by' parameters. A
# user could, for example, request 'left_index' and 'left_by'. In a
# regular pd.merge(), users cannot specify both 'left_index' and
# 'left_on'. (Instead, users have a MultiIndex). That means the
# self.left_on in this function is always empty in a pd.merge(), but
# a pd.merge_asof(left_index=True, left_by=...) will result in a
# self.left_on array with a None in the middle of it. This requires
# a work-around as designated in the code below.
# See _validate_specification() for where this happens.
# ugh, spaghetti re #733
if _any(self.left_on) and _any(self.right_on):
for lk, rk in zip(self.left_on, self.right_on):
if is_lkey(lk):
left_keys.append(lk)
if is_rkey(rk):
right_keys.append(rk)
join_names.append(None) # what to do?
else:
if rk is not None:
right_keys.append(right._get_label_or_level_values(rk))
join_names.append(rk)
else:
# work-around for merge_asof(right_index=True)
right_keys.append(right.index)
join_names.append(right.index.name)
else:
if not is_rkey(rk):
if rk is not None:
right_keys.append(right._get_label_or_level_values(rk))
else:
# work-around for merge_asof(right_index=True)
right_keys.append(right.index)
if lk is not None and lk == rk:
# avoid key upcast in corner case (length-0)
if len(left) > 0:
right_drop.append(rk)
else:
left_drop.append(lk)
else:
right_keys.append(rk)
if lk is not None:
left_keys.append(left._get_label_or_level_values(lk))
join_names.append(lk)
else:
# work-around for merge_asof(left_index=True)
left_keys.append(left.index)
join_names.append(left.index.name)
elif _any(self.left_on):
for k in self.left_on:
if is_lkey(k):
left_keys.append(k)
join_names.append(None)
else:
left_keys.append(left._get_label_or_level_values(k))
join_names.append(k)
if isinstance(self.right.index, MultiIndex):
right_keys = [
lev._values.take(lev_codes)
for lev, lev_codes in zip(
self.right.index.levels, self.right.index.codes
)
]
else:
right_keys = [self.right.index._values]
elif _any(self.right_on):
for k in self.right_on:
if is_rkey(k):
right_keys.append(k)
join_names.append(None)
else:
right_keys.append(right._get_label_or_level_values(k))
join_names.append(k)
if isinstance(self.left.index, MultiIndex):
left_keys = [
lev._values.take(lev_codes)
for lev, lev_codes in zip(
self.left.index.levels, self.left.index.codes
)
]
else:
left_keys = [self.left.index._values]
if left_drop:
self.left = self.left._drop_labels_or_levels(left_drop)
if right_drop:
self.right = self.right._drop_labels_or_levels(right_drop)
return left_keys, right_keys, join_names
def _maybe_coerce_merge_keys(self) -> None:
# we have valid merges but we may have to further
# coerce these if they are originally incompatible types
#
# for example if these are categorical, but are not dtype_equal
# or if we have object and integer dtypes
for lk, rk, name in zip(
self.left_join_keys, self.right_join_keys, self.join_names
):
if (len(lk) and not len(rk)) or (not len(lk) and len(rk)):
continue
lk_is_cat = is_categorical_dtype(lk.dtype)
rk_is_cat = is_categorical_dtype(rk.dtype)
lk_is_object = is_object_dtype(lk.dtype)
rk_is_object = is_object_dtype(rk.dtype)
# if either left or right is a categorical
# then the must match exactly in categories & ordered
if lk_is_cat and rk_is_cat:
if lk._categories_match_up_to_permutation(rk):
continue
elif lk_is_cat or rk_is_cat:
pass
elif is_dtype_equal(lk.dtype, rk.dtype):
continue
msg = (
f"You are trying to merge on {lk.dtype} and "
f"{rk.dtype} columns. If you wish to proceed you should use pd.concat"
)
# if we are numeric, then allow differing
# kinds to proceed, eg. int64 and int8, int and float
# further if we are object, but we infer to
# the same, then proceed
if is_numeric_dtype(lk.dtype) and is_numeric_dtype(rk.dtype):
if lk.dtype.kind == rk.dtype.kind:
continue
# check whether ints and floats
elif is_integer_dtype(rk.dtype) and is_float_dtype(lk.dtype):
if not (lk == lk.astype(rk.dtype))[~np.isnan(lk)].all():
warnings.warn(
"You are merging on int and float "
"columns where the float values "
"are not equal to their int representation",
UserWarning,
)
continue
elif is_float_dtype(rk.dtype) and is_integer_dtype(lk.dtype):
if not (rk == rk.astype(lk.dtype))[~np.isnan(rk)].all():
warnings.warn(
"You are merging on int and float "
"columns where the float values "
"are not equal to their int representation",
UserWarning,
)
continue
# let's infer and see if we are ok
elif lib.infer_dtype(lk, skipna=False) == lib.infer_dtype(
rk, skipna=False
):
continue
# Check if we are trying to merge on obviously
# incompatible dtypes GH 9780, GH 15800
# bool values are coerced to object
elif (lk_is_object and is_bool_dtype(rk.dtype)) or (
is_bool_dtype(lk.dtype) and rk_is_object
):
pass
# object values are allowed to be merged
elif (lk_is_object and is_numeric_dtype(rk.dtype)) or (
is_numeric_dtype(lk.dtype) and rk_is_object
):
inferred_left = lib.infer_dtype(lk, skipna=False)
inferred_right = lib.infer_dtype(rk, skipna=False)
bool_types = ["integer", "mixed-integer", "boolean", "empty"]
string_types = ["string", "unicode", "mixed", "bytes", "empty"]
# inferred bool
if inferred_left in bool_types and inferred_right in bool_types:
pass
# unless we are merging non-string-like with string-like
elif (
inferred_left in string_types and inferred_right not in string_types
) or (
inferred_right in string_types and inferred_left not in string_types
):
raise ValueError(msg)
# datetimelikes must match exactly
elif needs_i8_conversion(lk.dtype) and not needs_i8_conversion(rk.dtype):
raise ValueError(msg)
elif not needs_i8_conversion(lk.dtype) and needs_i8_conversion(rk.dtype):
raise ValueError(msg)
elif is_datetime64tz_dtype(lk.dtype) and not is_datetime64tz_dtype(
rk.dtype
):
raise ValueError(msg)
elif not is_datetime64tz_dtype(lk.dtype) and is_datetime64tz_dtype(
rk.dtype
):
raise ValueError(msg)
elif lk_is_object and rk_is_object:
continue
# Houston, we have a problem!
# let's coerce to object if the dtypes aren't
# categorical, otherwise coerce to the category
# dtype. If we coerced categories to object,
# then we would lose type information on some
# columns, and end up trying to merge
# incompatible dtypes. See GH 16900.
if name in self.left.columns:
typ = lk.categories.dtype if lk_is_cat else object
self.left = self.left.assign(**{name: self.left[name].astype(typ)})
if name in self.right.columns:
typ = rk.categories.dtype if rk_is_cat else object
self.right = self.right.assign(**{name: self.right[name].astype(typ)})
def _create_cross_configuration(
self, left: DataFrame, right: DataFrame
) -> tuple[DataFrame, DataFrame, str, str]:
"""
Creates the configuration to dispatch the cross operation to inner join,
e.g. adding a join column and resetting parameters. Join column is added
to a new object, no inplace modification
Parameters
----------
left : DataFrame
right : DataFrame
Returns
-------
a tuple (left, right, how, cross_col) representing the adjusted
DataFrames with cross_col, the merge operation set to inner and the column
to join over.
"""
cross_col = f"_cross_{hashlib.md5().hexdigest()}"
how = "inner"
return (
left.assign(**{cross_col: 1}),
right.assign(**{cross_col: 1}),
how,
cross_col,
)
def _validate_specification(self) -> None:
if self.how == "cross":
if (
self.left_index
or self.right_index
or self.right_on is not None
or self.left_on is not None
or self.on is not None
):
raise MergeError(
"Can not pass on, right_on, left_on or set right_index=True or "
"left_index=True"
)
return
# Hm, any way to make this logic less complicated??
elif self.on is None and self.left_on is None and self.right_on is None:
if self.left_index and self.right_index:
self.left_on, self.right_on = (), ()
elif self.left_index:
raise MergeError("Must pass right_on or right_index=True")
elif self.right_index:
raise MergeError("Must pass left_on or left_index=True")
else:
# use the common columns
left_cols = self.left.columns
right_cols = self.right.columns
common_cols = left_cols.intersection(right_cols)
if len(common_cols) == 0:
raise MergeError(
"No common columns to perform merge on. "
f"Merge options: left_on={self.left_on}, "
f"right_on={self.right_on}, "
f"left_index={self.left_index}, "
f"right_index={self.right_index}"
)
if (
not left_cols.join(common_cols, how="inner").is_unique
or not right_cols.join(common_cols, how="inner").is_unique
):
raise MergeError(f"Data columns not unique: {repr(common_cols)}")
self.left_on = self.right_on = common_cols
elif self.on is not None:
if self.left_on is not None or self.right_on is not None:
raise MergeError(
'Can only pass argument "on" OR "left_on" '
'and "right_on", not a combination of both.'
)
if self.left_index or self.right_index:
raise MergeError(
'Can only pass argument "on" OR "left_index" '
'and "right_index", not a combination of both.'
)
self.left_on = self.right_on = self.on
elif self.left_on is not None:
if self.left_index:
raise MergeError(
'Can only pass argument "left_on" OR "left_index" not both.'
)
if not self.right_index and self.right_on is None:
raise MergeError('Must pass "right_on" OR "right_index".')
n = len(self.left_on)
if self.right_index:
if len(self.left_on) != self.right.index.nlevels:
raise ValueError(
"len(left_on) must equal the number "
'of levels in the index of "right"'
)
self.right_on = [None] * n
elif self.right_on is not None:
if self.right_index:
raise MergeError(
'Can only pass argument "right_on" OR "right_index" not both.'
)
if not self.left_index and self.left_on is None:
raise MergeError('Must pass "left_on" OR "left_index".')
n = len(self.right_on)
if self.left_index:
if len(self.right_on) != self.left.index.nlevels:
raise ValueError(
"len(right_on) must equal the number "
'of levels in the index of "left"'
)
self.left_on = [None] * n
if self.how != "cross" and len(self.right_on) != len(self.left_on):
raise ValueError("len(right_on) must equal len(left_on)")
def _validate(self, validate: str) -> None:
# Check uniqueness of each
if self.left_index:
left_unique = self.orig_left.index.is_unique
else:
left_unique = MultiIndex.from_arrays(self.left_join_keys).is_unique
if self.right_index:
right_unique = self.orig_right.index.is_unique
else:
right_unique = MultiIndex.from_arrays(self.right_join_keys).is_unique
# Check data integrity
if validate in ["one_to_one", "1:1"]:
if not left_unique and not right_unique:
raise MergeError(
"Merge keys are not unique in either left "
"or right dataset; not a one-to-one merge"
)
elif not left_unique:
raise MergeError(
"Merge keys are not unique in left dataset; not a one-to-one merge"
)
elif not right_unique:
raise MergeError(
"Merge keys are not unique in right dataset; not a one-to-one merge"
)
elif validate in ["one_to_many", "1:m"]:
if not left_unique:
raise MergeError(
"Merge keys are not unique in left dataset; not a one-to-many merge"
)
elif validate in ["many_to_one", "m:1"]:
if not right_unique:
raise MergeError(
"Merge keys are not unique in right dataset; "
"not a many-to-one merge"
)
elif validate in ["many_to_many", "m:m"]:
pass
else:
raise ValueError("Not a valid argument for validate")
def get_join_indexers(
left_keys, right_keys, sort: bool = False, how: str = "inner", **kwargs
) -> tuple[np.ndarray, np.ndarray]:
"""
Parameters
----------
left_keys : ndarray, Index, Series
right_keys : ndarray, Index, Series
sort : bool, default False
how : {'inner', 'outer', 'left', 'right'}, default 'inner'
Returns
-------
np.ndarray[np.intp]
Indexer into the left_keys.
np.ndarray[np.intp]
Indexer into the right_keys.
"""
assert len(left_keys) == len(
right_keys
), "left_key and right_keys must be the same length"
# get left & right join labels and num. of levels at each location
mapped = (
_factorize_keys(left_keys[n], right_keys[n], sort=sort, how=how)
for n in range(len(left_keys))
)
zipped = zip(*mapped)
llab, rlab, shape = (list(x) for x in zipped)
# get flat i8 keys from label lists
lkey, rkey = _get_join_keys(llab, rlab, shape, sort)
# factorize keys to a dense i8 space
# `count` is the num. of unique keys
# set(lkey) | set(rkey) == range(count)
lkey, rkey, count = _factorize_keys(lkey, rkey, sort=sort, how=how)
# preserve left frame order if how == 'left' and sort == False
kwargs = copy.copy(kwargs)
if how in ("left", "right"):
kwargs["sort"] = sort
join_func = {
"inner": libjoin.inner_join,
"left": libjoin.left_outer_join,
"right": lambda x, y, count, **kwargs: libjoin.left_outer_join(
y, x, count, **kwargs
)[::-1],
"outer": libjoin.full_outer_join,
}[how]
# error: Cannot call function of unknown type
return join_func(lkey, rkey, count, **kwargs) # type: ignore[operator]
def restore_dropped_levels_multijoin(
left: MultiIndex,
right: MultiIndex,
dropped_level_names,
join_index: Index,
lindexer: np.ndarray,
rindexer: np.ndarray,
) -> tuple[list[Index], np.ndarray, list[Hashable]]:
"""
*this is an internal non-public method*
Returns the levels, labels and names of a multi-index to multi-index join.
Depending on the type of join, this method restores the appropriate
dropped levels of the joined multi-index.
The method relies on lidx, rindexer which hold the index positions of
left and right, where a join was feasible
Parameters
----------
left : MultiIndex
left index
right : MultiIndex
right index
dropped_level_names : str array
list of non-common level names
join_index : Index
the index of the join between the
common levels of left and right
lindexer : np.ndarray[np.intp]
left indexer
rindexer : np.ndarray[np.intp]
right indexer
Returns
-------
levels : list of Index
levels of combined multiindexes
labels : intp array
labels of combined multiindexes
names : List[Hashable]
names of combined multiindex levels
"""
def _convert_to_multiindex(index: Index) -> MultiIndex:
if isinstance(index, MultiIndex):
return index
else:
return MultiIndex.from_arrays([index._values], names=[index.name])
# For multi-multi joins with one overlapping level,
# the returned index if of type Index
# Assure that join_index is of type MultiIndex
# so that dropped levels can be appended
join_index = _convert_to_multiindex(join_index)
join_levels = join_index.levels
join_codes = join_index.codes
join_names = join_index.names
# lindexer and rindexer hold the indexes where the join occurred
# for left and right respectively. If left/right is None then
# the join occurred on all indices of left/right
if lindexer is None:
lindexer = range(left.size)
if rindexer is None:
rindexer = range(right.size)
# Iterate through the levels that must be restored
for dropped_level_name in dropped_level_names:
if dropped_level_name in left.names:
idx = left
indexer = lindexer
else:
idx = right
indexer = rindexer
# The index of the level name to be restored
name_idx = idx.names.index(dropped_level_name)
restore_levels = idx.levels[name_idx]
# Inject -1 in the codes list where a join was not possible
# IOW indexer[i]=-1
codes = idx.codes[name_idx]
restore_codes = algos.take_nd(codes, indexer, fill_value=-1)
join_levels = join_levels + [restore_levels]
join_codes = join_codes + [restore_codes]
join_names = join_names + [dropped_level_name]
return join_levels, join_codes, join_names
class _OrderedMerge(_MergeOperation):
_merge_type = "ordered_merge"
def __init__(
self,
left: DataFrame | Series,
right: DataFrame | Series,
on: IndexLabel | None = None,
left_on: IndexLabel | None = None,
right_on: IndexLabel | None = None,
left_index: bool = False,
right_index: bool = False,
axis: int = 1,
suffixes: Suffixes = ("_x", "_y"),
copy: bool = True,
fill_method: str | None = None,
how: str = "outer",
):
self.fill_method = fill_method
_MergeOperation.__init__(
self,
left,
right,
on=on,
left_on=left_on,
left_index=left_index,
right_index=right_index,
right_on=right_on,
axis=axis,
how=how,
suffixes=suffixes,
sort=True, # factorize sorts
)
def get_result(self) -> DataFrame:
join_index, left_indexer, right_indexer = self._get_join_info()
llabels, rlabels = _items_overlap_with_suffix(
self.left._info_axis, self.right._info_axis, self.suffixes
)
left_join_indexer: np.ndarray | None
right_join_indexer: np.ndarray | None
if self.fill_method == "ffill":
# error: Argument 1 to "ffill_indexer" has incompatible type
# "Optional[ndarray]"; expected "ndarray"
left_join_indexer = libjoin.ffill_indexer(
left_indexer # type: ignore[arg-type]
)
# error: Argument 1 to "ffill_indexer" has incompatible type
# "Optional[ndarray]"; expected "ndarray"
right_join_indexer = libjoin.ffill_indexer(
right_indexer # type: ignore[arg-type]
)
else:
left_join_indexer = left_indexer
right_join_indexer = right_indexer
lindexers = {1: left_join_indexer} if left_join_indexer is not None else {}
rindexers = {1: right_join_indexer} if right_join_indexer is not None else {}
result_data = concatenate_managers(
[(self.left._mgr, lindexers), (self.right._mgr, rindexers)],
axes=[llabels.append(rlabels), join_index],
concat_axis=0,
copy=self.copy,
)
typ = self.left._constructor
result = typ(result_data)
self._maybe_add_join_keys(result, left_indexer, right_indexer)
return result
def _asof_function(direction: str):
name = f"asof_join_{direction}"
return getattr(libjoin, name, None)
def _asof_by_function(direction: str):
name = f"asof_join_{direction}_on_X_by_Y"
return getattr(libjoin, name, None)
_type_casters = {
"int64_t": ensure_int64,
"double": ensure_float64,
"object": ensure_object,
}
def _get_cython_type_upcast(dtype: DtypeObj) -> str:
"""Upcast a dtype to 'int64_t', 'double', or 'object'"""
if is_integer_dtype(dtype):
return "int64_t"
elif is_float_dtype(dtype):
return "double"
else:
return "object"
class _AsOfMerge(_OrderedMerge):
_merge_type = "asof_merge"
def __init__(
self,
left: DataFrame | Series,
right: DataFrame | Series,
on: IndexLabel | None = None,
left_on: IndexLabel | None = None,
right_on: IndexLabel | None = None,
left_index: bool = False,
right_index: bool = False,
by=None,
left_by=None,
right_by=None,
axis: int = 1,
suffixes: Suffixes = ("_x", "_y"),
copy: bool = True,
fill_method: str | None = None,
how: str = "asof",
tolerance=None,
allow_exact_matches: bool = True,
direction: str = "backward",
):
self.by = by
self.left_by = left_by
self.right_by = right_by
self.tolerance = tolerance
self.allow_exact_matches = allow_exact_matches
self.direction = direction
_OrderedMerge.__init__(
self,
left,
right,
on=on,
left_on=left_on,
right_on=right_on,
left_index=left_index,
right_index=right_index,
axis=axis,
how=how,
suffixes=suffixes,
fill_method=fill_method,
)
def _validate_specification(self) -> None:
super()._validate_specification()
# we only allow on to be a single item for on
if len(self.left_on) != 1 and not self.left_index:
raise MergeError("can only asof on a key for left")
if len(self.right_on) != 1 and not self.right_index:
raise MergeError("can only asof on a key for right")
if self.left_index and isinstance(self.left.index, MultiIndex):
raise MergeError("left can only have one index")
if self.right_index and isinstance(self.right.index, MultiIndex):
raise MergeError("right can only have one index")
# set 'by' columns
if self.by is not None:
if self.left_by is not None or self.right_by is not None:
raise MergeError("Can only pass by OR left_by and right_by")
self.left_by = self.right_by = self.by
if self.left_by is None and self.right_by is not None:
raise MergeError("missing left_by")
if self.left_by is not None and self.right_by is None:
raise MergeError("missing right_by")
# GH#29130 Check that merge keys do not have dtype object
if not self.left_index:
left_on = self.left_on[0]
if is_array_like(left_on):
lo_dtype = left_on.dtype
else:
lo_dtype = (
self.left[left_on].dtype
if left_on in self.left.columns
else self.left.index.get_level_values(left_on)
)
else:
lo_dtype = self.left.index.dtype
if not self.right_index:
right_on = self.right_on[0]
if is_array_like(right_on):
ro_dtype = right_on.dtype
else:
ro_dtype = (
self.right[right_on].dtype
if right_on in self.right.columns
else self.right.index.get_level_values(right_on)
)
else:
ro_dtype = self.right.index.dtype
if is_object_dtype(lo_dtype) or is_object_dtype(ro_dtype):
raise MergeError(
f"Incompatible merge dtype, {repr(ro_dtype)} and "
f"{repr(lo_dtype)}, both sides must have numeric dtype"
)
# add 'by' to our key-list so we can have it in the
# output as a key
if self.left_by is not None:
if not is_list_like(self.left_by):
self.left_by = [self.left_by]
if not is_list_like(self.right_by):
self.right_by = [self.right_by]
if len(self.left_by) != len(self.right_by):
raise MergeError("left_by and right_by must be same length")
self.left_on = self.left_by + list(self.left_on)
self.right_on = self.right_by + list(self.right_on)
# check 'direction' is valid
if self.direction not in ["backward", "forward", "nearest"]:
raise MergeError(f"direction invalid: {self.direction}")
def _get_merge_keys(self):
# note this function has side effects
(left_join_keys, right_join_keys, join_names) = super()._get_merge_keys()
# validate index types are the same
for i, (lk, rk) in enumerate(zip(left_join_keys, right_join_keys)):
if not is_dtype_equal(lk.dtype, rk.dtype):
if is_categorical_dtype(lk.dtype) and is_categorical_dtype(rk.dtype):
# The generic error message is confusing for categoricals.
#
# In this function, the join keys include both the original
# ones of the merge_asof() call, and also the keys passed
# to its by= argument. Unordered but equal categories
# are not supported for the former, but will fail
# later with a ValueError, so we don't *need* to check
# for them here.
msg = (
f"incompatible merge keys [{i}] {repr(lk.dtype)} and "
f"{repr(rk.dtype)}, both sides category, but not equal ones"
)
else:
msg = (
f"incompatible merge keys [{i}] {repr(lk.dtype)} and "
f"{repr(rk.dtype)}, must be the same type"
)
raise MergeError(msg)
# validate tolerance; datetime.timedelta or Timedelta if we have a DTI
if self.tolerance is not None:
if self.left_index:
lt = self.left.index
else:
lt = left_join_keys[-1]
msg = (
f"incompatible tolerance {self.tolerance}, must be compat "
f"with type {repr(lt.dtype)}"
)
if needs_i8_conversion(lt):
if not isinstance(self.tolerance, datetime.timedelta):
raise MergeError(msg)
if self.tolerance < Timedelta(0):
raise MergeError("tolerance must be positive")
elif is_integer_dtype(lt):
if not is_integer(self.tolerance):
raise MergeError(msg)
if self.tolerance < 0:
raise MergeError("tolerance must be positive")
elif is_float_dtype(lt):
if not is_number(self.tolerance):
raise MergeError(msg)
if self.tolerance < 0:
raise MergeError("tolerance must be positive")
else:
raise MergeError("key must be integer, timestamp or float")
# validate allow_exact_matches
if not is_bool(self.allow_exact_matches):
msg = (
"allow_exact_matches must be boolean, "
f"passed {self.allow_exact_matches}"
)
raise MergeError(msg)
return left_join_keys, right_join_keys, join_names
def _get_join_indexers(self) -> tuple[np.ndarray, np.ndarray]:
# Both returned ndarrays are np.intp
"""return the join indexers"""
def flip(xs) -> np.ndarray:
"""unlike np.transpose, this returns an array of tuples"""
# error: Item "ndarray" of "Union[Any, Union[ExtensionArray, ndarray]]" has
# no attribute "_values_for_argsort"
xs = [
x
if not is_extension_array_dtype(x)
else extract_array(x)._values_for_argsort() # type: ignore[union-attr]
for x in xs
]
labels = list(string.ascii_lowercase[: len(xs)])
dtypes = [x.dtype for x in xs]
labeled_dtypes = list(zip(labels, dtypes))
return np.array(list(zip(*xs)), labeled_dtypes)
# values to compare
left_values = (
self.left.index._values if self.left_index else self.left_join_keys[-1]
)
right_values = (
self.right.index._values if self.right_index else self.right_join_keys[-1]
)
tolerance = self.tolerance
# we require sortedness and non-null values in the join keys
if not Index(left_values).is_monotonic:
side = "left"
if isna(left_values).any():
raise ValueError(f"Merge keys contain null values on {side} side")
else:
raise ValueError(f"{side} keys must be sorted")
if not Index(right_values).is_monotonic:
side = "right"
if isna(right_values).any():
raise ValueError(f"Merge keys contain null values on {side} side")
else:
raise ValueError(f"{side} keys must be sorted")
# initial type conversion as needed
if needs_i8_conversion(left_values):
left_values = left_values.view("i8")
right_values = right_values.view("i8")
if tolerance is not None:
tolerance = Timedelta(tolerance)
tolerance = tolerance.value
# a "by" parameter requires special handling
if self.left_by is not None:
# remove 'on' parameter from values if one existed
if self.left_index and self.right_index:
left_by_values = self.left_join_keys
right_by_values = self.right_join_keys
else:
left_by_values = self.left_join_keys[0:-1]
right_by_values = self.right_join_keys[0:-1]
# get tuple representation of values if more than one
if len(left_by_values) == 1:
left_by_values = left_by_values[0]
right_by_values = right_by_values[0]
else:
left_by_values = flip(left_by_values)
right_by_values = flip(right_by_values)
# upcast 'by' parameter because HashTable is limited
by_type = _get_cython_type_upcast(left_by_values.dtype)
by_type_caster = _type_casters[by_type]
# error: Cannot call function of unknown type
left_by_values = by_type_caster(left_by_values) # type: ignore[operator]
# error: Cannot call function of unknown type
right_by_values = by_type_caster(right_by_values) # type: ignore[operator]
# choose appropriate function by type
func = _asof_by_function(self.direction)
return func(
left_values,
right_values,
left_by_values,
right_by_values,
self.allow_exact_matches,
tolerance,
)
else:
# choose appropriate function by type
func = _asof_function(self.direction)
return func(left_values, right_values, self.allow_exact_matches, tolerance)
def _get_multiindex_indexer(
join_keys, index: MultiIndex, sort: bool
) -> tuple[np.ndarray, np.ndarray]:
# Both returned ndarrays are np.intp
# left & right join labels and num. of levels at each location
mapped = (
_factorize_keys(index.levels[n], join_keys[n], sort=sort)
for n in range(index.nlevels)
)
zipped = zip(*mapped)
rcodes, lcodes, shape = (list(x) for x in zipped)
if sort:
rcodes = list(map(np.take, rcodes, index.codes))
else:
i8copy = lambda a: a.astype("i8", subok=False, copy=True)
rcodes = list(map(i8copy, index.codes))
# fix right labels if there were any nulls
for i in range(len(join_keys)):
mask = index.codes[i] == -1
if mask.any():
# check if there already was any nulls at this location
# if there was, it is factorized to `shape[i] - 1`
a = join_keys[i][lcodes[i] == shape[i] - 1]
if a.size == 0 or not a[0] != a[0]:
shape[i] += 1
rcodes[i][mask] = shape[i] - 1
# get flat i8 join keys
lkey, rkey = _get_join_keys(lcodes, rcodes, shape, sort)
# factorize keys to a dense i8 space
lkey, rkey, count = _factorize_keys(lkey, rkey, sort=sort)
return libjoin.left_outer_join(lkey, rkey, count, sort=sort)
def _get_single_indexer(
join_key, index: Index, sort: bool = False
) -> tuple[np.ndarray, np.ndarray]:
# Both returned ndarrays are np.intp
left_key, right_key, count = _factorize_keys(join_key, index._values, sort=sort)
return libjoin.left_outer_join(left_key, right_key, count, sort=sort)
def _left_join_on_index(
left_ax: Index, right_ax: Index, join_keys, sort: bool = False
) -> tuple[Index, np.ndarray | None, np.ndarray]:
# Both returned ndarrays are np.intp (if not None)
if len(join_keys) > 1:
if not (
isinstance(right_ax, MultiIndex) and len(join_keys) == right_ax.nlevels
):
raise AssertionError(
"If more than one join key is given then "
"'right_ax' must be a MultiIndex and the "
"number of join keys must be the number of levels in right_ax"
)
left_indexer, right_indexer = _get_multiindex_indexer(
join_keys, right_ax, sort=sort
)
else:
jkey = join_keys[0]
left_indexer, right_indexer = _get_single_indexer(jkey, right_ax, sort=sort)
if sort or len(left_ax) != len(left_indexer):
# if asked to sort or there are 1-to-many matches
join_index = left_ax.take(left_indexer)
return join_index, left_indexer, right_indexer
# left frame preserves order & length of its index
return left_ax, None, right_indexer
def _factorize_keys(
lk: ArrayLike, rk: ArrayLike, sort: bool = True, how: str = "inner"
) -> tuple[np.ndarray, np.ndarray, int]:
"""
Encode left and right keys as enumerated types.
This is used to get the join indexers to be used when merging DataFrames.
Parameters
----------
lk : array-like
Left key.
rk : array-like
Right key.
sort : bool, defaults to True
If True, the encoding is done such that the unique elements in the
keys are sorted.
how : {‘left’, ‘right’, ‘outer’, ‘inner’}, default ‘inner’
Type of merge.
Returns
-------
np.ndarray[np.intp]
Left (resp. right if called with `key='right'`) labels, as enumerated type.
np.ndarray[np.intp]
Right (resp. left if called with `key='right'`) labels, as enumerated type.
int
Number of unique elements in union of left and right labels.
See Also
--------
merge : Merge DataFrame or named Series objects
with a database-style join.
algorithms.factorize : Encode the object as an enumerated type
or categorical variable.
Examples
--------
>>> lk = np.array(["a", "c", "b"])
>>> rk = np.array(["a", "c"])
Here, the unique values are `'a', 'b', 'c'`. With the default
`sort=True`, the encoding will be `{0: 'a', 1: 'b', 2: 'c'}`:
>>> pd.core.reshape.merge._factorize_keys(lk, rk)
(array([0, 2, 1]), array([0, 2]), 3)
With the `sort=False`, the encoding will correspond to the order
in which the unique elements first appear: `{0: 'a', 1: 'c', 2: 'b'}`:
>>> pd.core.reshape.merge._factorize_keys(lk, rk, sort=False)
(array([0, 1, 2]), array([0, 1]), 3)
"""
# Some pre-processing for non-ndarray lk / rk
lk = extract_array(lk, extract_numpy=True, extract_range=True)
rk = extract_array(rk, extract_numpy=True, extract_range=True)
# TODO: if either is a RangeIndex, we can likely factorize more efficiently?
if is_datetime64tz_dtype(lk.dtype) and is_datetime64tz_dtype(rk.dtype):
# Extract the ndarray (UTC-localized) values
# Note: we dont need the dtypes to match, as these can still be compared
lk = cast("DatetimeArray", lk)._ndarray
rk = cast("DatetimeArray", rk)._ndarray
elif (
is_categorical_dtype(lk.dtype)
and is_categorical_dtype(rk.dtype)
and is_dtype_equal(lk.dtype, rk.dtype)
):
assert isinstance(lk, Categorical)
assert isinstance(rk, Categorical)
# Cast rk to encoding so we can compare codes with lk
rk = lk._encode_with_my_categories(rk)
lk = ensure_int64(lk.codes)
rk = ensure_int64(rk.codes)
elif isinstance(lk, ExtensionArray) and is_dtype_equal(lk.dtype, rk.dtype):
# error: Incompatible types in assignment (expression has type "ndarray",
# variable has type "ExtensionArray")
lk, _ = lk._values_for_factorize()
# error: Incompatible types in assignment (expression has type
# "ndarray", variable has type "ExtensionArray")
# error: Item "ndarray" of "Union[Any, ndarray]" has no attribute
# "_values_for_factorize"
rk, _ = rk._values_for_factorize() # type: ignore[union-attr,assignment]
klass: type[libhashtable.Factorizer] | type[libhashtable.Int64Factorizer]
if is_integer_dtype(lk.dtype) and is_integer_dtype(rk.dtype):
# GH#23917 TODO: needs tests for case where lk is integer-dtype
# and rk is datetime-dtype
klass = libhashtable.Int64Factorizer
lk = ensure_int64(np.asarray(lk))
rk = ensure_int64(np.asarray(rk))
elif needs_i8_conversion(lk.dtype) and is_dtype_equal(lk.dtype, rk.dtype):
# GH#23917 TODO: Needs tests for non-matching dtypes
klass = libhashtable.Int64Factorizer
lk = ensure_int64(np.asarray(lk, dtype=np.int64))
rk = ensure_int64(np.asarray(rk, dtype=np.int64))
else:
klass = libhashtable.ObjectFactorizer
lk = ensure_object(lk)
rk = ensure_object(rk)
rizer = klass(max(len(lk), len(rk)))
llab = rizer.factorize(lk)
rlab = rizer.factorize(rk)
assert llab.dtype == np.intp, llab.dtype
assert rlab.dtype == np.intp, rlab.dtype
count = rizer.get_count()
if sort:
uniques = rizer.uniques.to_array()
llab, rlab = _sort_labels(uniques, llab, rlab)
# NA group
lmask = llab == -1
lany = lmask.any()
rmask = rlab == -1
rany = rmask.any()
if lany or rany:
if lany:
np.putmask(llab, lmask, count)
if rany:
np.putmask(rlab, rmask, count)
count += 1
if how == "right":
return rlab, llab, count
return llab, rlab, count
def _sort_labels(
uniques: np.ndarray, left: np.ndarray, right: np.ndarray
) -> tuple[np.ndarray, np.ndarray]:
# Both returned ndarrays are np.intp
llength = len(left)
labels = np.concatenate([left, right])
_, new_labels = algos.safe_sort(uniques, labels, na_sentinel=-1)
assert new_labels.dtype == np.intp
new_left, new_right = new_labels[:llength], new_labels[llength:]
return new_left, new_right
def _get_join_keys(llab, rlab, shape, sort: bool):
# how many levels can be done without overflow
nlev = next(
lev
for lev in range(len(shape), 0, -1)
if not is_int64_overflow_possible(shape[:lev])
)
# get keys for the first `nlev` levels
stride = np.prod(shape[1:nlev], dtype="i8")
lkey = stride * llab[0].astype("i8", subok=False, copy=False)
rkey = stride * rlab[0].astype("i8", subok=False, copy=False)
for i in range(1, nlev):
with np.errstate(divide="ignore"):
stride //= shape[i]
lkey += llab[i] * stride
rkey += rlab[i] * stride
if nlev == len(shape): # all done!
return lkey, rkey
# densify current keys to avoid overflow
lkey, rkey, count = _factorize_keys(lkey, rkey, sort=sort)
llab = [lkey] + llab[nlev:]
rlab = [rkey] + rlab[nlev:]
shape = [count] + shape[nlev:]
return _get_join_keys(llab, rlab, shape, sort)
def _should_fill(lname, rname) -> bool:
if not isinstance(lname, str) or not isinstance(rname, str):
return True
return lname == rname
def _any(x) -> bool:
return x is not None and com.any_not_none(*x)
def _validate_operand(obj: FrameOrSeries) -> DataFrame:
if isinstance(obj, ABCDataFrame):
return obj
elif isinstance(obj, ABCSeries):
if obj.name is None:
raise ValueError("Cannot merge a Series without a name")
else:
return obj.to_frame()
else:
raise TypeError(
f"Can only merge Series or DataFrame objects, a {type(obj)} was passed"
)
def _items_overlap_with_suffix(
left: Index, right: Index, suffixes: Suffixes
) -> tuple[Index, Index]:
"""
Suffixes type validation.
If two indices overlap, add suffixes to overlapping entries.
If corresponding suffix is empty, the entry is simply converted to string.
"""
if not is_list_like(suffixes, allow_sets=False):
warnings.warn(
f"Passing 'suffixes' as a {type(suffixes)}, is not supported and may give "
"unexpected results. Provide 'suffixes' as a tuple instead. In the "
"future a 'TypeError' will be raised.",
FutureWarning,
stacklevel=4,
)
to_rename = left.intersection(right)
if len(to_rename) == 0:
return left, right
lsuffix, rsuffix = suffixes
if not lsuffix and not rsuffix:
raise ValueError(f"columns overlap but no suffix specified: {to_rename}")
def renamer(x, suffix):
"""
Rename the left and right indices.
If there is overlap, and suffix is not None, add
suffix, otherwise, leave it as-is.
Parameters
----------
x : original column name
suffix : str or None
Returns
-------
x : renamed column name
"""
if x in to_rename and suffix is not None:
return f"{x}{suffix}"
return x
lrenamer = partial(renamer, suffix=lsuffix)
rrenamer = partial(renamer, suffix=rsuffix)
llabels = left._transform_index(lrenamer)
rlabels = right._transform_index(rrenamer)
dups = []
if not llabels.is_unique:
# Only warn when duplicates are caused because of suffixes, already duplicated
# columns in origin should not warn
dups = llabels[(llabels.duplicated()) & (~left.duplicated())].tolist()
if not rlabels.is_unique:
dups.extend(rlabels[(rlabels.duplicated()) & (~right.duplicated())].tolist())
if dups:
warnings.warn(
f"Passing 'suffixes' which cause duplicate columns {set(dups)} in the "
f"result is deprecated and will raise a MergeError in a future version.",
FutureWarning,
stacklevel=4,
)
return llabels, rlabels |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Caesar Cipher</title>
<style>
body {
font-family: Arial;
}
h1,
h3 {
text-align: center;
}
.wrapper {
display: flex;
gap: 1em;
max-width: 1000px;
margin: 2em auto;
}
form {
border: 1px solid black;
padding: 1em;
}
.info {
max-width: 1000px;
margin: 2em auto;
line-height: 2em;
}
a {
font-weight: bold;
}
span {
background-color: rgb(250, 62, 62);
padding: 0 0.2em;
}
button {
background-color: limegreen;
border: none;
padding: 0.2em 0.4em;
cursor: pointer;
}
button:hover {
background-color: yellowgreen;
}
</style>
</head>
<body>
<header><h1>CAESAR CIPHER</h1></header>
<div><h3>John Loyd H. Mulit</h3></div>
<div class="wrapper">
<form>
<div>
<input type="text" name="input" id="input" />
<label for="input">Text to encrypt</label>
</div>
<br />
<div>
<input type="number" name="shift" id="shift" />
<label for="shift">Shift key</label>
</div>
<br />
<div>
<button type="button" onclick="encrypt()">Encrypt</button>
</div>
<br />
<textarea
name="cipher"
id="cipher"
placeholder="Encrypted text`"
disabled
cols="30"
rows="10"
></textarea>
</form>
<form>
<div>
<input type="text" name="text" id="text" />
<label for="input">Text to decrypt</label>
</div>
<br />
<div>
<input
type="number"
name="decypt-shift"
id="decrypt-shift"
/>
<label for="shift">Shift key</label>
</div>
<br />
<div>
<button type="button" onclick="decrypt()">Decrypt</button>
</div>
<br />
<textarea
name="decrypted"
id="decrypted"
placeholder="Decrypted text"
disabled
cols="30"
rows="10"
></textarea>
</form>
<div class="options">
<input
type="checkbox"
name="reverse"
id="reverse"
onchange="getDirection()"
/>
<label for="reverse">Reverse shift direction</label>
</div>
</div>
<div class="info">
<p>
This is a Caesar Cipher implementation in JavaScript. This is
based on the work of
<a href="https://github.com/AlanCowap-OCJA2015" target="_blank"
>AlanCowap-OCJA2015</a
>
from Github. The original source code is written in java and can
be found
<a
href="https://github.com/AlanCowap-OCJA2015/CaesarCipher/blob/master/OCJA_CodeChallenges/src/com/ocja/smsm/ccipher/CaesarCipher.java"
target="_blank"
>here</a
>. The <span>reverse</span> option is an added feature in the
original source code. The reverse option, if checked, will
reverse the shifting direction. If reversed, character shift
will go backwards.
</p>
</div>
</body>
<script>
let alphabet = 'abcdefghijklmnopqrstuvwxyz'
let checkbox = document.getElementById('reverse')
let reverse = false
//Get the direction of key-shift. Reverse = left, non-reverse = right
function getDirection() {
if (checkbox.checked == true) {
reverse = true
} else {
reverse = false
}
}
//Encrypt the inputed text by the shift value
function encrypt() {
let input = document
.getElementById('input')
.value.replace(/\s+/g, '')
.toLowerCase()
let shift = Number(document.getElementById('shift').value)
let textarea = document.getElementById('cipher')
let cipher = ''
inputArray = input.split('')
for (let i = 0; i < inputArray.length; i++) {
//Check if reverse-shift is turned on
if (reverse) {
//Check if shift key will overflow from the alphabet
let index = alphabet.indexOf(inputArray[i]) - shift
if (index < 0) {
//if shift will overflow, circle back to last character in the alphabet
let overflow = alphabet.length + index
cipher += alphabet.charAt(overflow)
} else {
cipher += alphabet.charAt(index)
}
} else {
//Run code below if reverse-shift is not on
let index = alphabet.indexOf(inputArray[i]) + shift + 1
if (index > alphabet.length) {
//if shift will overflow, circle back to first character in the alphabet
let overflow = index - alphabet.length
cipher += alphabet.charAt(--overflow)
} else {
cipher += alphabet.charAt(--index)
}
}
}
textarea.value = cipher
}
//Decrypt the cipher text with the given shift key
function decrypt() {
let text = document
.getElementById('text')
.value.replace(/\s+/g, '')
.toLowerCase()
let decryptKey = Number(
document.getElementById('decrypt-shift').value
)
let decryptedText = document.getElementById('decrypted')
let originalText = ''
textArray = text.split('')
for (let i = 0; i < textArray.length; i++) {
if (reverse) {
let index = alphabet.indexOf(textArray[i]) + decryptKey + 1
if (index > alphabet.length) {
let overflow = index - alphabet.length
originalText += alphabet.charAt(--overflow)
} else {
originalText += alphabet.charAt(--index)
}
} else {
let index = alphabet.indexOf(textArray[i]) - decryptKey
if (index < 0) {
let overflow = alphabet.length + index
originalText += alphabet.charAt(overflow)
} else {
originalText += alphabet.charAt(index)
}
}
}
decryptedText.value = originalText
}
</script>
</html> |
<!--
~ This program is part of the OpenLMIS logistics management information system platform software.
~ Copyright © 2013 VillageReach
~
~ This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
~
~ This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details.
~ You should have received a copy of the GNU Affero General Public License along with this program. If not, see http://www.gnu.org/licenses. For additional information contact info@OpenLMIS.org.
-->
<script id="template/accordion/accordion.html" type="text/ng-template">
<div class="accordion" ng-transclude></div>
</script>
<script id="template/accordion/accordion-group.html" type="text/ng-template">
<div class="accordion-group">
<div class="accordion-heading"><a class="accordion-toggle" ng-click="isOpen = !isOpen">{{heading}}</a></div>
<div class="accordion-body" collapse="!isOpen">
<div class="accordion-inner" ng-transclude></div>
</div>
</div>
</script>
<div xmlns="http://www.w3.org/1999/html" tab-scroll>
<div ng-hide="user.id"><h2 openlmis-message="create.user.label"></h2></div>
<div ng-show="user.id">
<h2 id="editUserLabel" openlmis-message="edit.user.label"></h2>
</div>
<form ng-submit="saveUser()" id="create-user" name="userForm" novalidate select2-blur>
<div class="app-form">
<div class="form-group">
<h3 openlmis-message="label.basicInformation"></h3>
<div class="form-row clearfix">
<div class="form-cell">
<label for="userName" openlmis-message="create.user.userName"><span class="label-required"> *</span></label>
<div class="form-field">
<input ng-model="user.userName" name="userName" id="userName" type="text" maxlength="50"
ng-required="true" ng-change="validateUserName()"/>
<span class="field-error" ng-show="userForm.userName.$error.required && showError"
openlmis-message="missing.value">
</span>
<span class="field-error" ng-show="userNameInvalid" openlmis-message="create.user.invalid.userName">
</span>
</div>
</div>
<div class="form-cell">
<label for="email" openlmis-message="create.user.email"><span class="label-required"> *</span></label>
<div class="form-field">
<input ng-model="user.email" name="email" id="email" type="text" maxlength="50" ng-required="true"/>
<span class="field-error" ng-show="userForm.email.$error.required && showError"
openlmis-message="missing.value">
</span>
</div>
</div>
</div>
<div class="form-row clearfix">
<div class="form-cell">
<label for="firstName" openlmis-message="create.user.firstName"><span class="label-required">
*</span></label>
<div class="form-field">
<input ng-model="user.firstName" name="firstName" id="firstName" type="text" maxlength="50"
ng-required="true"/>
<span class="field-error" ng-show="userForm.firstName.$error.required && showError"
openlmis-message="missing.value">
</span>
</div>
</div>
<div class="form-cell">
<label for="lastName" openlmis-message="create.user.lastName"><span class="label-required"> *</span></label>
<div class="form-field">
<input ng-model="user.lastName" name="lastName" id="lastName" type="text" maxlength="50"
ng-required="true"/>
<span class="field-error" ng-show="userForm.lastName.$error.required && showError"
openlmis-message="missing.value">
</span>
</div>
</div>
</div>
<div class="form-row clearfix">
<div class="form-cell">
<label for="employeeId" openlmis-message="create.user.employeeId"></label>
<div class="form-field">
<input ng-model="user.employeeId" id="employeeId" type="text" maxlength="50"/>
</div>
</div>
<div class="form-cell">
<label for="jobTitle" openlmis-message="create.user.jobTitle"> </label>
<div class="form-field">
<input ng-model="user.jobTitle" id="jobTitle" type="text" maxlength="50"/>
</div>
</div>
</div>
<div class="form-row clearfix">
<div class="form-cell">
<label for="officePhone" openlmis-message="create.user.officePhone"> </label>
<div class="form-field">
<input ng-model="user.officePhone" id="officePhone" type="text" maxlength="30"/>
</div>
</div>
<div class="form-cell">
<label for="cellPhone" openlmis-message="create.user.cellPhone"> </label>
<div class="form-field">
<input ng-model="user.cellPhone" id="cellPhone" type="text" maxlength="30"/>
</div>
</div>
</div>
<div class="form-row clearfix">
<div class="form-cell">
<label for="primaryNotificationMethod" openlmis-message="create.user.primaryNotificationMethod"> </label>
<div class="form-field">
<input ng-model="user.primaryNotificationMethod" id="primaryNotificationMethod" type="text"
maxlength="50"/>
</div>
</div>
<div class="form-cell">
<label openlmis-message="create.user.restrictLogin"><span class="label-required"> *</span></label>
<div class="form-field radio-group">
<input id="restrictLoginYes" ng-model="user.restrictLogin" type="radio" name="restrictLogin"
ng-value="true"
ng-required="user.restrictLogin == null || user.restrictLogin == undefined"/>
<strong openlmis-message="button.yes"></strong>
<input id="restrictLoginNo" ng-model="user.restrictLogin" type="radio" name="restrictLogin"
ng-value="false"/>
<strong openlmis-message="button.no"></strong>
<span class="field-error" ng-show="userForm.restrictLogin.$error.required && showError"
openlmis-message="select.value">
</span>
</div>
</div>
</div>
<div class="form-row clearfix">
<div class="form-cell">
<label for="searchFacility" openlmis-message="create.user.homeFacility"> </label>
<div class="form-field autosuggest-input">
<div class="suggest-field">
<input id="searchFacility" type="text" ng-change="showFacilitySearchResults()" ng-model="query"
openlmis-message="placeholder.facility.search" ng-hide="facilitySelected"/>
<div class="facility-list" ng-show="query.length > 2">
<ul>
<li ng-repeat="facility in filteredFacilities">
<a href="" id="result{{$index}}" ng-click="setSelectedFacility(facility)">{{facility.code}}
-
{{facility.name}}</a>
</li>
<li ng-show="resultCount == 0">
<a href="" openlmis-message="msg.no.matches|query"></a>
</li>
</ul>
</div>
<div ng-show="facilitySelected">
<span ng-bind="facilitySelected.name"></span>
<a href="" class="clear-search" ng-click="confirmFacilityDelete()"
openlmis-message="create.user.clear"></a>
</div>
</div>
<div class="form-tip" openlmis-message="search.threeCharacters"></div>
</div>
</div>
</div>
<div class="form-row clearfix">
<div class="form-cell">
<label openlmis-message="label.is.verified"></label>
<ng-switch on="!!user.verified">
<span ng-switch-when="true" openlmis-message="button.yes"></span>
<span ng-switch-when="false" openlmis-message="button.no"></span>
</ng-switch>
</div>
</div>
</div>
<div class="container-fluid">
<div class="row-fluid">
<div class="accordion">
<div class="pull-right control-accordion">
<a id="expandAll" href="javascript:void(0);" onClick="expandCollapse('expand')">Expand All</a> / <a
id="collapseAll"
href="javascript:void(0);"
onClick="expandCollapse('collapse')">Collapse
All</a>
</div>
<div class="clearfix"></div>
<div class="accordion-section" ng-show='facilitySelected'>
<div class="accordion-heading" onClick="expandCollapseToggle(this)">
<span><b>+</b><a
id="homeFacilityRoles" href="javascript:void(0);">{{getMessage('create.user.homeFacility.roles')}}</a></span>
</div>
<div class="accordion-body prog-role-grid">
<ng-include src="'/public/pages/admin/user/partials/user-role-assignment.html'"></ng-include>
</div>
</div>
<div class="accordion-section">
<div class="accordion-heading" onClick="expandCollapseToggle(this)">
<span><b>+</b><a
id="supervisoryRoles" href="javascript:void(0);">{{getMessage('create.user.superVisoryRoles')}}</a></span>
</div>
<div class="accordion-body prog-role-grid">
<ng-include
src="'/public/pages/admin/user/partials/user-supervisory-role-assignment.html'"></ng-include>
</div>
</div>
<div class="accordion-section">
<div class="accordion-heading" onClick="expandCollapseToggle(this)">
<span><b>+</b><a
id="orderFulfillmentRoles" href="javascript:void(0);">{{getMessage('create.user.order.fulfillment.roles')}}</a></span>
</div>
<div class="accordion-body prog-role-grid">
<ng-include src="'/public/pages/admin/user/partials/user-warehouse-roles.html'"></ng-include>
</div>
</div>
<div class="accordion-section">
<div class="accordion-heading" onClick="expandCollapseToggle(this)">
<span><b>+</b><a
id="allocationRoles" href="javascript:void(0);">{{getMessage('create.user.allocationRoles')}}</a></span>
</div>
<div class="accordion-body prog-role-grid">
<ng-include
src="'/public/pages/admin/user/partials/user-delivery-zone-role-assignment.html'"></ng-include>
</div>
</div>
<div class="accordion-section">
<div class="accordion-heading" onClick="expandCollapseToggle(this)">
<span><b>+</b><a
id="adminRoles"
href="javascript:void(0);">{{getMessage('create.user.adminRoles')}}</a></span>
</div>
<div class="accordion-body prog-role-grid">
<ng-include src="'/public/pages/admin/user/partials/user-admin-role-assignment.html'"></ng-include>
</div>
</div>
<div class="accordion-section">
<div class="accordion-heading" onClick="expandCollapseToggle(this)">
<span><b>+</b><a href="javascript:void(0);">Report Viewing Role</a></span>
</div>
<div class="accordion-body prog-role-grid">
<ng-include src="'/public/pages/admin/user/partials/user-report-role-assignment.html'"></ng-include>
</div>
</div>
</div>
</div>
</div>
<div form-toolbar id="action_buttons" class="action-buttons">
<div class="form-cell button-row">
<input id="userSaveButton" type="submit" class="btn btn-primary save-button" openlmis-message="button.save"/>
<input id="userCancelButton" type="button" class="btn btn-cancel cancel-button" openlmis-message="button.cancel"
ng-click="cancelUserSave()"/>
<input id="userDisableButton" type="button" class="btn btn-danger delete-button"
ng-show="user.active && user.id!=null"
ng-click="showConfirmUserDisableModal()" openlmis-message="button.disable"/>
<input id="userEnableButton" type="button" class="btn btn-primary enable-button"
ng-show="(!user.active && user.id!=null)"
openlmis-message="button.enable"
ng-click="showConfirmUserRestoreModal()"/>
</div>
<div class="toolbar-error" id="saveErrorMsgDiv" openlmis-message="error" ng-show="error"/>
<div class="toolbar-success" id="saveSuccessMsgDiv" openlmis-message="message" ng-show="message"/>
</div>
</div>
</form>
</div> |
# Nested Lists
Given the names and grades for each student in a class of **N** students, store them in a nested list and print the name(s) of any student(s) having the second lowest grade.
**Note:** If there are multiple students with the second lowest grade, order their names alphabetically and print each name on a new line.
**Example**
records = [["chi", 20.0], ["beta", 50.0], ["alpha", 50.0]]
The ordered list of scores is `[20.0, 50.0]` , so the second lowest score is `50.0` . There are two students with that score: `["beta", "alpha"]` . Ordered alphabetically, the names are printed as:
alpha
beta
**Input Format**
The first line contains an integer, **N** , the number of students.
The **2N** subsequent lines describe each student over **2** lines.
- The first line contains a student's name.
- The second line contains their grade.
**Constraints**
- `2<=N<=5
- There will always be one or more students having the second lowest grade.
**Output Format**
Print the name(s) of any student(s) having the second lowest grade in. If there are multiple students, order their names alphabetically and print each one on a new line.
**Sample Input 0**
5
Harry
37.21
Berry
37.21
Tina
37.2
Akriti
41
Harsh
39
**Sample Output 0**
Berry
Harry
**Explanation 0**
There are **5** students in this class whose names and grades are assembled to build the following list:
python students = [['Harry', 37.21], ['Berry', 37.21], ['Tina', 37.2], ['Akriti', 41], ['Harsh', 39]]
The lowest grade of **37.2** belongs to _Tina_. The second lowest grade of **37.21** belongs to both _Harry_ and _Berry_, so we order their names alphabetically and print each name on a new line. |
---
layout: article
title: Vagrantで開発環境構築
tags:
aside:
toc: true
---
[Vagrant公式サイトのQuick Start](https://learn.hashicorp.com/tutorials/vagrant/getting-started-index?in=vagrant/getting-started)を読みながら進めます
## Vagrantをインストール
- 公式サイトからVagrantをインストール
https://www.vagrantup.com/downloads
- 公式サイトからVirtualBoxをインストール
https://www.virtualbox.org/
補足: Homebrewでもよかったかも
```
brew cask install vagrant
brew cask install virtualbox
```
## Vagrantを初期化
```
vagrant init bento/ubuntu-18.04
```
#### `init`コマンドの解説:
>仮想環境を作成するための初期化コマンドです。”boxファイル名”のところには、Vagrant Cloud等にアップされているboxファイル名を入力します。 例えば、CentOS 7の仮想環境を作りたい場合は、下記のコマンドを実行します。
[よく使うVagrantコマンドの意味や使い方をまとめました](https://dev83.com/vagrant02/#:~:text=vagrant%20box-,vagrant%20init%20%E2%80%9Cbox%E3%83%95%E3%82%A1%E3%82%A4%E3%83%AB%E5%90%8D%E2%80%9D,%E3%82%B3%E3%83%9E%E3%83%B3%E3%83%89%E3%82%92%E5%AE%9F%E8%A1%8C%E3%81%97%E3%81%BE%E3%81%99%E3%80%82)
#### BOXの解説:
Vagrangで使えるBoxは[ここ](https://app.vagrantup.com/boxes/search?utf8=%E2%9C%93&sort=downloads&provider=&q=ubuntu)で検索可能!
`Ubuntu`で検索すると`ubuntu/trusty64`とか`ubuntu/xenial64`とかいろいろ出てくる。

その中でも`Bento`が一番いいらしい🍱
[VagrantでUbuntuを使うならBento Boxを使う](https://scrapbox.io/kb84tkhr-pub/Vagrant%E3%81%A7Ubuntu%E3%82%92%E4%BD%BF%E3%81%86%E3%81%AA%E3%82%89Bento_Box%E3%82%92%E4%BD%BF%E3%81%86)
## Boxを追加
initコマンドは初期化なので使うのは最初だけ。
以降、仮想環境に新しいOSなどを追加したければ`add`コマンドを使います。
```
vagrant box add bento/ubuntu-18.04
```
成功すると以下のメッセージが出ます。
```
==> box: Successfully added box 'bento/ubuntu-18.04' (v202010.24.0) for 'virtualbox'!
```
一覧を確認してみます。
```
vagrant box list
bento/ubuntu-18.04 (virtualbox, 202010.24.0)
```
できてる☀️。
## upする
```
vagrant up
```
エラーでなかったらOK
VMの解説:
この仮想マシンの実態はVirtualBox。
VirtualBoxのアプリを立ち上げると、`up`で指定したVMが立ち上がっているのが確認できる。

## エラーがでたら
```
Couldn't open file /Users/hinako/Scala/base
```
`vagrant init`のときにBOX名を指定しないと出るエラー。
Vagrantfileを消して、再度 `init`すればOK(BOX名をいれて)
```
rm Vagrantfile
vagrant init ボックス名
vagrant up
```
## 接続
```
vagrant ssh
```
実行結果
```
Welcome to Ubuntu 18.04.5 LTS (GNU/Linux 4.15.0-122-generic x86_64)
* Documentation: https://help.ubuntu.com
* Management: https://landscape.canonical.com
* Support: https://ubuntu.com/advantage
System information as of Wed Nov 25 09:00:46 UTC 2020
System load: 0.0 Processes: 90
Usage of /: 2.3% of 61.80GB Users logged in: 0
Memory usage: 11% IP address for eth0: .....
Swap usage: 0%
This system is built by the Bento project by Chef Software
More information can be found at https://github.com/chef/bento
```
## destroyする
仮想マシンを止めたければ`destroy`すればOK
だたしVagrantファイルが消えるわけではない。
```
vagrant destroy
```
以上 |
/**
Instructions:
Make use of .map(), .filter() and .find() methods.
You can make use of basic methods such as .length, toLowerCase(), toUpperCase() if needed.
Do NOT use for-loops.
*/
/** 1. Given an array of objects representing people, write an ES6 function to return a new array containing only the names of the people.
const people = [
{ name: 'Raj', age: 28 },
{ name: 'Swapnil', age: 42 },
{ name: 'Anushka', age: 35 }
];
console.log(names); // Output: ['Raj', 'Swapnil', 'Anushka'] */
const people = [
{ name: "Raj", age: 28 },
{ name: "Swapnil", age: 42 },
{ name: "Anushka", age: 35 },
];
const names = (people) => people.map((person) => person.name);
// console.log(names(people));
/** 2. Given an array, write an ES6 function to return a new array with all the elements multiplied by 5.
const numbers = [1, 2, 3, 4];
console.log(multiplyByFive); // Output: [5, 10, 15, 20] */
const multiplyByFive = (numbers) => numbers.map((num) => num * 5);
const numbers = [1, 2, 3, 4];
// console.log(multiplyByFive(numbers));
/** 3. Given employee’s data, write an ES6 function which greets them with a personalized message for onboarding.
const employeeData = [
{name: "ram", dept: "marketer"},
{name: "Radha", dept: "SDE"},
{name: "shyam", dept: "finance professional"},
]
console.log(greetEmployeeMessages);
// Output: ['Hi ram we are glad to have you as a marketing', 'Hi Radha we are glad to have you as a SDE','Hi shyam we are glad to have you as a finance professional'] */
const greetEmployeeMessages = (employeData) =>
employeData.map(
(employee) =>
`Hi ${employee.name} we are glad to have you as a ${employee.dept}`
);
const employeeData = [
{ name: "ram", dept: "marketer" },
{ name: "Radha", dept: "SDE" },
{ name: "shyam", dept: "finance professional" },
];
// console.log(greetEmployeeMessages(employeeData));
/** 4. Write an ES6 function that takes an array of objects representing books and returns an array with only the titles of each book.
const books = [
{ title: 'The Great Gatsby', author: 'F. Scott Fitzgerald' },
{ title: 'To Kill a Mockingbird', author: 'Harper Lee' },
{ title: '1984', author: 'George Orwell' },
{ title: 'Pride and Prejudice', author: 'Jane Austen' },
];
const titles = getBookTitles(books);
console.log(titles); // Output: ['The Great Gatsby', 'To Kill a Mockingbird', '1984', 'Pride and Prejudice'] */
const books = [
{ title: "The Great Gatsby", author: "F. Scott Fitzgerald" },
{ title: "To Kill a Mockingbird", author: "Harper Lee" },
{ title: "1984", author: "George Orwell" },
{ title: "Pride and Prejudice", author: "Jane Austen" },
];
const getBookTitles = (books) => books.map((book) => book.title);
// console.log(getBookTitles(books));
/** 5. Write an ES6 function which takes out the names of the students whose first letter starts with ‘A’.
const studentName = ["Ram", "Anjali", "Arpit", "Bhanu Kumar", "Jaya", "Ankit", "shayam"]
console.log(studentNames);
// Output: ["Anjali", "Arpit", "Ankit"] */
const studentNamesStartWithA = (names) =>
names.filter((name) => name.includes("A"));
const studentName = [
"Ram",
"Anjali",
"Arpit",
"Bhanu Kumar",
"Jaya",
"Ankit",
"shayam",
];
// console.log(studentNamesStartWithA(studentName));
/** 6. Write an ES6 function which filters out the products which have a price greater than 40.
const productData = [
{prodName: "Dairy Milk", price: 10},
{prodName: "Dairy Milk Silk", price: 70},
{prodName: "Five Star", price: 20},
{prodName: "Mars", price: 50}
]
console.log(getProducts(productData, 40))
// Output: [{prodName: 'Dairy Milk Silk', price: 70}, {prodName: 'Mars', price: 50}] */
const getProducts = (products) =>
products.filter((product) => product.price > 40);
const productData = [
{ prodName: "Dairy Milk", price: 10 },
{ prodName: "Dairy Milk Silk", price: 70 },
{ prodName: "Five Star", price: 20 },
{ prodName: "Mars", price: 50 },
];
// console.log(getProducts(productData));
/** 7. Write an ES6 function that takes an array of numbers and returns the first number that is divisible by 7.
const numbers = [1, 2, 3, 21, 14, 7];
console.log(isDivisibleBy7)
// Output: 21 */
const isDivisibleBy7 = (numbers) => numbers.find((number) => number % 7 == 0);
const numbers1 = [1, 2, 3, 21, 14, 7];
// console.log(isDivisibleBy7(numbers1));
/** 8. Write an ES6 function that takes an array of strings and returns the first string that is longer than
8 characters.
const names = ["Mohan", "Anjali", "Geetanjali", "Ankit", "Bhanu Kumar", "Ramakrishnan"],
console.log(isNamesGreaterThan8(names));
// Output: "Geetanjali" */
const isNamesGreaterThan8 = (names) => names.find((name) => name.length > 8);
const names2 = [
"Mohan",
"Anjali",
"Geetanjali",
"Ankit",
"Bhanu Kumar",
"Ramakrishnan",
];
// console.log(isNamesGreaterThan8(names2));
/** 9. Write an ES6 function that takes an array of objects representing students with properties name and grade. Return the first student object that has a grade of "A".
const students = [
{ name: "John", grade: "B" },
{ name: "Mary", grade: "A" },
{ name: "Sam", grade: "C" },
{ name: "Sarah", grade: "A" },
];
const studentWithGradeA = findStudentWithGradeA(students);
console.log(studentWithGradeA);
// Output: { name: "Mary", grade: "A" } */
const studentWithGradeA = (students) =>
students.find((student) => student.grade == "A");
const students = [
{ name: "John", grade: "B" },
{ name: "Mary", grade: "A" },
{ name: "Sam", grade: "C" },
{ name: "Sarah", grade: "A" },
];
// console.log(studentWithGradeA(students));
/** 10. Write an ES6 function that takes an array of objects representing students with properties name,grade and scholarship. Return the first student object that has a grade of "A" or they are a scholarship student.
const students = [
{ name: "John", grade: "B", scholarship: false },
{ name: "Mary", grade: "B", scholarship: true },
{ name: "Sam", grade: "A", scholarship: false },
{ name: "Sarah", grade: "A", scholarship: true },
];
const student = findStudent(students);
console.log(student);
// Output: { name: "Sarah", grade: "A", scholarship: true }s*/
const students2 = [
{ name: "John", grade: "B", scholarship: false },
{ name: "Mary", grade: "B", scholarship: true },
{ name: "Sam", grade: "A", scholarship: false },
{ name: "Sarah", grade: "A", scholarship: true },
];
const StudentWithGradeAandScholarship = (students) =>
students.find(
(student) => student.grade == "A" && student.scholarship == true
);
// console.log(StudentWithGradeAandScholarship(students2));
/** 11. Write an ES6 function that takes an array of objects representing students with properties name and grade. Return the first student object that has a grade of "B" and they are also a scholarship student.
const students = [
{ name: "John", grade: "B", scholarship: false },
{ name: "Mary", grade: "A", scholarship: true },
{ name: "Sam", grade: "A", scholarship: false },
{ name: "Sarah", grade: "B", scholarship: true },
];
const student = findStudent(students);
console.log(student);
// Output: { name: "Sarah", grade: "B", scholarship: true } */
const students3 = [
{ name: "John", grade: "B", scholarship: false },
{ name: "Mary", grade: "A", scholarship: true },
{ name: "Sam", grade: "A", scholarship: false },
{ name: "Sarah", grade: "B", scholarship: true },
];
const StudentWithGradeBandScholarship = (students) =>
students.find(
(student) => student.grade == "B" && student.scholarship == true
);
// console.log(StudentWithGradeBandScholarship(students3));
/** 12. Write an ES6 function that takes an array of objects containing Bollywood movie information (title, director, year, rating) and returns an array with only the movie titles that were made before 1990 and has a rating above 8.0. (Question Level: tough)
const bollywoodMovies = [
{ title: 'Sholay', director: 'Ramesh Sippy', year: 1975, rating: 8.2 },
{ title: 'Amar Akbar Anthony', director: 'Manmohan Desai', year: 1977, rating: 7.6 },
{ title: 'Namak Halaal', director: 'Prakash Mehra', year: 1982, rating: 7.4 },
{ title: 'Mr. India', director: 'Shekhar Kapur', year: 1987, rating: 7.8 },
{ title: 'Qayamat Se Qayamat Tak', director: 'Mansoor Khan', year: 1988, rating: 7.6 },
{ title: 'Parinda', director: 'Vidhu Vinod Chopra', year: 1989, rating: 8.1 },
{ title: 'Dil', director: 'Indra Kumar', year: 1990, rating: 7.8 }
];
const bestOldMovies = getBestOldBollywoodMovies(bollywoodMovies);
console.log(bestOldMovies); // Output: ['Sholay', 'Parinda' */
const bollywoodMovies = [
{ title: "Sholay", director: "Ramesh Sippy", year: 1975, rating: 8.2 },
{
title: "Amar Akbar Anthony",
director: "Manmohan Desai",
year: 1977,
rating: 7.6,
},
{
title: "Namak Halaal",
director: "Prakash Mehra",
year: 1982,
rating: 7.4,
},
{ title: "Mr. India", director: "Shekhar Kapur", year: 1987, rating: 7.8 },
{
title: "Qayamat Se Qayamat Tak",
director: "Mansoor Khan",
year: 1988,
rating: 7.6,
},
{
title: "Parinda",
director: "Vidhu Vinod Chopra",
year: 1989,
rating: 8.1,
},
{ title: "Dil", director: "Indra Kumar", year: 1990, rating: 7.8 },
];
const getBestOldBollywoodMovies = (movies) => {
return movies
.filter((movie) => movie.year < 1990 && movie.rating > 8.0)
.map((movie) => movie.title);
};
// console.log(getBestOldBollywoodMovies(bollywoodMovies)); |
import 'package:flutter/material.dart';
import 'package:peliculas/models/models.dart';
import 'package:peliculas/widgets/widgets.dart';
//El key es una manera de identificar el widget en el arbol de widgets
class DetailsScreen extends StatelessWidget {
const DetailsScreen({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
// TODO: Cambiar luego por una instancia de movie
// Los dos simbolos de ?? declaran que si todo lo anterior es nulo se le mandara otra cosa
final Movie movie = ModalRoute.of(context)!.settings.arguments as Movie;
print(movie.title);
return Scaffold(
body: CustomScrollView(
//Los slivers son ciertos widgets que tienen cierto funcionamiento programado cuando se hace scroll en el contenido del padre
slivers: [
_CustomAppBar(movie),
SliverList(
delegate: SliverChildListDelegate(
[
_PosterAndTitle(movie),
_Overview(movie),
_Overview(movie),
_Overview(movie),
_Overview(movie),
_Overview(movie),
CastingCards(movie.id),
]
))
],
),
);
}
}
class _CustomAppBar extends StatelessWidget {
//const _CustomAppBar({Key? key}) : super(key: key);
final Movie movie;
const _CustomAppBar(this.movie);
@override
Widget build(BuildContext context) {
return SliverAppBar(
backgroundColor: Colors.indigo,
expandedHeight: 200,
floating: false,
pinned: true,
flexibleSpace: FlexibleSpaceBar(
centerTitle: true,
titlePadding: EdgeInsets.all(0),
title: Container(
width: double.infinity,
alignment: Alignment.bottomCenter,
color: Colors.black12,
child: Text(
'${movie.title}',
style: TextStyle(fontSize: 16),
),
),
background: FadeInImage(
placeholder: AssetImage('assets/loading.gif'),
image: NetworkImage('${movie.fullBackdropPath}'),
fit: BoxFit.cover,),
),
);
}
}
class _PosterAndTitle extends StatelessWidget {
final Movie movie;
const _PosterAndTitle(this.movie);
@override
Widget build(BuildContext context) {
final TextTheme textTheme = Theme.of(context).textTheme;
final size = MediaQuery.of(context).size;
return Container(
margin: EdgeInsets.only(top: 20),
padding: EdgeInsets.symmetric(horizontal: 20),
child: Row(
children: [
ClipRRect(
borderRadius: BorderRadius.circular(20),
child: FadeInImage(
placeholder: AssetImage('assets/no-image.jpg'),
image: NetworkImage(movie.fullPosterImg),
// width: 150,
height: 150,
width: 110,
),
),
SizedBox(width: 20,),
ConstrainedBox(
constraints: BoxConstraints(maxWidth: size.width - 200),
child: Column(
//Para que quede alineado al inicio en este caso a la izquierda
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(movie.title, style: textTheme.headline5, overflow: TextOverflow.ellipsis, maxLines: 2,),
//Text(movie.title, style: textTheme.headline5, overflow: TextOverflow.ellipsis, maxLines: 2,),
Text(movie.originalTitle, style: textTheme.subtitle2, overflow: TextOverflow.ellipsis, maxLines: 2,),
Row(
children: [
Icon(Icons.star, size: 15, color: Colors.grey,),
SizedBox(width: 5,),
Text('${movie.voteAverage}', style: textTheme.caption,),
],
)
],
),
)
],
),
);
}
}
//El overview es un simple contenedor en el cual va a tener un texto
class _Overview extends StatelessWidget {
//const _Overview({Key? key}) : super(key: key);
final Movie movie;
const _Overview(this.movie);
@override
Widget build(BuildContext context) {
return Container(
padding: EdgeInsets.symmetric(horizontal: 30, vertical: 10),
child: Text(movie.overview,
textAlign: TextAlign.justify,
style: Theme.of(context).textTheme.subtitle1),
);
}
} |
import React, { useContext } from "react";
import { ThemeContext } from "../App";
import Frame1 from "../Img/Group 9.svg";
import style from "../styles/style.module.css";
import { motion } from "framer-motion";
const Experience = () => {
const theme = useContext(ThemeContext);
return (
<motion.main
className="main__container"
initial={{ width: "40%" }}
animate={{ width: "100%" }}
exit={{ x: "100%", opacity: "0" }}
transition={{duration: 2}}
>
<section
className={`${style.experience_section} p-6 pb-[8rem] w-[90%] h-[70vh] overflow-y-auto relative z-10 top-[150px] bottom-[150px] mx-auto ${theme ? `bg-[#f4ddce]` : `bg-[#070b0e]`}`}
id="Experience"
>
<div className={`mb-10`}>
<h1 className={`font-base text-2xl md:text-3xl ${theme ? `text-[#071e1e]` : `text-[#fcfcfc] `}`}>
<span className={`${style.name} text-[#af5c3b] font-bold text-[45px]`}>
<span
className={`${style.name} font-extrabold text-[#af5c3b] text-7xl md:text-9xl`}
>
E
</span>
XPERIENCE
</span>
</h1>
</div>
<div className={`lg:w-[870px] mx-auto`}>
<div className={`md:flex justify-between items-start md:mb-10`}>
<div className={`relative md:w-[45%] mb-10 md:mb-0 flex`}>
<img src={Frame1} alt="" className={``} />
<div className={`ml-8`}>
<h1 className={`font-bold text-lg mb-2 ${theme ? `text-[#071e1e]` : `text-[#fcfcfc]`}`}>
Sololearn 2021
</h1>
<p className={`text-[#54646e] mb-4`}>
Completed a course and series of challenges by demonstrating
theoritical understanding of HTML & CSS. Certificate issued by
Sololearn.
</p>
<a
href="https://drive.google.com/file/d/1JMH_NetIQNbxRb55nxmkGq1CuzS7qXlI/view?usp=drivesdk"
target="_blank"
rel="noopener noreferrer"
className={`rounded p-2 bg-[#af5c3b] hover:bg-gradient-to-r hover:bg-[#a04d2c] font-bold text-lg transition duration-700 ease-in-out ${theme ? `text-[#fcfcfc]` : `text-[#fcfcfc]`}`}
>
Access Certificate
</a>
</div>
</div>
<div className={`relative flex md:w-[45%] mb-10 md:mb-0 text-right flex-row-reverse md:text-left md:flex-row `}>
<img src={Frame1} alt="" className={``} />
<div className={`mr-8 md:ml-8`}>
<h1 className={`font-bold text-lg mb-2 ${theme ? `text-[#071e1e]` : `text-[#fcfcfc]`}`}>
Women Techsters 2021
</h1>
<p className={`text-[#54646e] mb-4`}>
Successfully completed a 2-week Bootcamp training in software
development with the Women Techsters in collaboration with
Microsoft.
</p>
<a
href="https://drive.google.com/file/d/1JJw8wtUiOhX6k1Qt_gtTGcW8NDOoRiry/view?usp=drivesdk"
target="_blank"
rel="noopener noreferrer"
className={`rounded p-2 bg-[#af5c3b] hover:bg-gradient-to-r hover:bg-[#a04d2c] font-bold text-lg transition duration-700 ease-in-out ${theme ? `text-[#fcfcfc]` : `text-[#fcfcfc]`}`}
>
Access Certificate
</a>
</div>
</div>
</div>
<div className={`md:flex justify-between items-start md:mb-10 pb-4`}>
<div className={`relative md:w-[45%] mb-10 flex md:mb-0`}>
<img src={Frame1} alt="" className={``} />
<div className={`ml-8`}>
<h1 className={`font-bold text-lg mb-2 ${theme ? `text-[#071e1e]` : `text-[#fcfcfc]`}`}>
I4GxZuri 2022
</h1>
<p className={`text-[#54646e] mb-4`}>
Participated in an intensive 3 months training in Fullstack development
program sponsored by I4GxZuri. Collaborated in teams to build and
deploy projects.
</p>
<a
href="https://drive.google.com/file/d/10-NmffnavC7I0GUaJ40GbnGPnkdNtqhn/view?usp=drivesdk"
target="_blank"
rel="noopener noreferrer"
className={`rounded p-2 bg-[#af5c3b] hover:bg-gradient-to-r hover:bg-[#a04d2c] font-bold text-lg transition duration-700 ease-in-out ${theme ? `text-[#fcfcfc]` : `text-[#fcfcfc]`}`}
>
Access Certificate
</a>
</div>
</div>
<div className={`relative md:w-[45%] mb-10 text-right md:text-left flex flex-row-reverse md:flex-row`}>
<img src={Frame1} alt="" className={``} />
<div className={`mr-8 md:ml-8 md:mr-0`}>
<h1 className={`font-bold text-lg mb-2 ${theme ? `text-[#071e1e]` : `text-[#fcfcfc]`}`}>
HNG Internship 2022
</h1>
<p className={`text-[#54646e] mb-4`}>
Enrolled and successfully completed the HNG Internship program. A remote, large scale, fast-paced virtual internship that improves skills by working on a real world project.
</p>
<a
href="#."
target="_blank"
rel="noopener noreferrer"
className={`rounded p-2 bg-[#af5c3b] hover:bg-gradient-to-r hover:bg-[#a04d2c] font-bold text-lg transition duration-700 ease-in-out ${theme ? `text-[#fcfcfc]` : `text-[#fcfcfc]`}`}
>
Access Certificate
</a>
</div>
</div>
</div>
</div>
</section>
</motion.main>
);
};
export default Experience; |
import PropTypes from 'prop-types';
import { Button, ButtonItem, ButtonList } from './FeedbackOptions.module';
export const FeedbackOptions = ({ options, onLeaveFeedback }) => {
return (
<ButtonList>
{options.map(option => (
<ButtonItem key={option}>
<Button name={option} type="button" onClick={onLeaveFeedback}>
{option}
</Button>
</ButtonItem>
))}
</ButtonList>
);
};
FeedbackOptions.propTypes = {
options: PropTypes.arrayOf(PropTypes.string).isRequired,
onLeaveFeedback: PropTypes.func.isRequired,
}; |
package com.github.hoseinzare67.training.telegram.bot.game;
import com.github.hoseinzare67.training.telegram.bot.game.exception.InternalBotException;
import com.github.hoseinzare67.training.telegram.bot.game.exception.PlayerHistoryStoreDataException;
import com.github.hoseinzare67.training.telegram.bot.game.handler.RequestHandler;
import com.github.hoseinzare67.training.telegram.bot.game.handler.factory.RequestHandlerFactory;
import com.github.hoseinzare67.training.telegram.bot.game.service.MemoryPlayLogicRepository;
import com.github.hoseinzare67.training.telegram.bot.game.service.PlayLogicRepository;
import com.github.hoseinzare67.training.telegram.bot.game.service.data.FilePlayerHistoryRepository;
import com.github.hoseinzare67.training.telegram.bot.game.service.data.PlayerHistoryRepository;
import org.telegram.telegrambots.api.methods.send.SendMessage;
import org.telegram.telegrambots.api.objects.Update;
import org.telegram.telegrambots.bots.TelegramLongPollingBot;
import org.telegram.telegrambots.exceptions.TelegramApiException;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* @author hosseinzare67
*/
public class GameBot extends TelegramLongPollingBot {
private static final Logger LOGGER = Logger.getLogger(GameBot.class.getName());
private PlayLogicRepository playLogicRepository;
private PlayerHistoryRepository playerHistoryRepository;
public GameBot() throws PlayerHistoryStoreDataException {
playLogicRepository = new MemoryPlayLogicRepository();
playerHistoryRepository = new FilePlayerHistoryRepository();
}
@Override
public void onUpdateReceived(Update update) {
RequestHandler handler = RequestHandlerFactory.getHandler(this, update);
try {
sendApiMethod(handler.handle());
} catch (InternalBotException | TelegramApiException e) {
LOGGER.log(Level.SEVERE, e.getMessage(), e);
try {
sendApiMethod(new SendMessage(update.getMessage().getChatId(), "Sorry an Internal Error occured , please try again"));
} catch (TelegramApiException e1) {
LOGGER.log(Level.SEVERE, "Error Sending message to Telegram");
LOGGER.log(Level.SEVERE, e.getMessage(), e);
}
}
}
@Override
public String getBotUsername() {
return "<bot_user_name>";
}
@Override
public String getBotToken() {
return "<bot_token>";
}
public PlayLogicRepository getPlayLogicRepository() {
return playLogicRepository;
}
public PlayerHistoryRepository getPlayerHistoryRepository() {
return playerHistoryRepository;
}
} |
<?php
namespace App\Http\Requests\User;
use Illuminate\Foundation\Http\FormRequest;
class LoginRequest extends FormRequest
{
/*
* @return boolean
*/
public function authorize()
{
return true;
}
/*
* @return array
*/
public function rules()
{
return [
'email' => [
'required',
'email',
'max:255',
],
'password' => [
'required',
'max:255',
],
'remember_me' => [
'required',
'in:0,1',
],
];
}
} |
package info.ilong.oms.pojo;
import java.util.ArrayList;
import java.util.List;
public class ProductRelExample {
protected String orderByClause;
protected boolean distinct;
protected List<Criteria> oredCriteria;
public ProductRelExample() {
oredCriteria = new ArrayList<Criteria>();
}
public void setOrderByClause(String orderByClause) {
this.orderByClause = orderByClause;
}
public String getOrderByClause() {
return orderByClause;
}
public void setDistinct(boolean distinct) {
this.distinct = distinct;
}
public boolean isDistinct() {
return distinct;
}
public List<Criteria> getOredCriteria() {
return oredCriteria;
}
public void or(Criteria criteria) {
oredCriteria.add(criteria);
}
public Criteria or() {
Criteria criteria = createCriteriaInternal();
oredCriteria.add(criteria);
return criteria;
}
public Criteria createCriteria() {
Criteria criteria = createCriteriaInternal();
if (oredCriteria.size() == 0) {
oredCriteria.add(criteria);
}
return criteria;
}
protected Criteria createCriteriaInternal() {
Criteria criteria = new Criteria();
return criteria;
}
public void clear() {
oredCriteria.clear();
orderByClause = null;
distinct = false;
}
protected abstract static class GeneratedCriteria {
protected List<Criterion> criteria;
protected GeneratedCriteria() {
super();
criteria = new ArrayList<Criterion>();
}
public boolean isValid() {
return criteria.size() > 0;
}
public List<Criterion> getAllCriteria() {
return criteria;
}
public List<Criterion> getCriteria() {
return criteria;
}
protected void addCriterion(String condition) {
if (condition == null) {
throw new RuntimeException("Value for condition cannot be null");
}
criteria.add(new Criterion(condition));
}
protected void addCriterion(String condition, Object value, String property) {
if (value == null) {
throw new RuntimeException("Value for " + property + " cannot be null");
}
criteria.add(new Criterion(condition, value));
}
protected void addCriterion(String condition, Object value1, Object value2, String property) {
if (value1 == null || value2 == null) {
throw new RuntimeException("Between values for " + property + " cannot be null");
}
criteria.add(new Criterion(condition, value1, value2));
}
public Criteria andToolIdIsNull() {
addCriterion("tool_id is null");
return (Criteria) this;
}
public Criteria andToolIdIsNotNull() {
addCriterion("tool_id is not null");
return (Criteria) this;
}
public Criteria andToolIdEqualTo(Integer value) {
addCriterion("tool_id =", value, "toolId");
return (Criteria) this;
}
public Criteria andToolIdNotEqualTo(Integer value) {
addCriterion("tool_id <>", value, "toolId");
return (Criteria) this;
}
public Criteria andToolIdGreaterThan(Integer value) {
addCriterion("tool_id >", value, "toolId");
return (Criteria) this;
}
public Criteria andToolIdGreaterThanOrEqualTo(Integer value) {
addCriterion("tool_id >=", value, "toolId");
return (Criteria) this;
}
public Criteria andToolIdLessThan(Integer value) {
addCriterion("tool_id <", value, "toolId");
return (Criteria) this;
}
public Criteria andToolIdLessThanOrEqualTo(Integer value) {
addCriterion("tool_id <=", value, "toolId");
return (Criteria) this;
}
public Criteria andToolIdIn(List<Integer> values) {
addCriterion("tool_id in", values, "toolId");
return (Criteria) this;
}
public Criteria andToolIdNotIn(List<Integer> values) {
addCriterion("tool_id not in", values, "toolId");
return (Criteria) this;
}
public Criteria andToolIdBetween(Integer value1, Integer value2) {
addCriterion("tool_id between", value1, value2, "toolId");
return (Criteria) this;
}
public Criteria andToolIdNotBetween(Integer value1, Integer value2) {
addCriterion("tool_id not between", value1, value2, "toolId");
return (Criteria) this;
}
public Criteria andPieceIdIsNull() {
addCriterion("piece_id is null");
return (Criteria) this;
}
public Criteria andPieceIdIsNotNull() {
addCriterion("piece_id is not null");
return (Criteria) this;
}
public Criteria andPieceIdEqualTo(Integer value) {
addCriterion("piece_id =", value, "pieceId");
return (Criteria) this;
}
public Criteria andPieceIdNotEqualTo(Integer value) {
addCriterion("piece_id <>", value, "pieceId");
return (Criteria) this;
}
public Criteria andPieceIdGreaterThan(Integer value) {
addCriterion("piece_id >", value, "pieceId");
return (Criteria) this;
}
public Criteria andPieceIdGreaterThanOrEqualTo(Integer value) {
addCriterion("piece_id >=", value, "pieceId");
return (Criteria) this;
}
public Criteria andPieceIdLessThan(Integer value) {
addCriterion("piece_id <", value, "pieceId");
return (Criteria) this;
}
public Criteria andPieceIdLessThanOrEqualTo(Integer value) {
addCriterion("piece_id <=", value, "pieceId");
return (Criteria) this;
}
public Criteria andPieceIdIn(List<Integer> values) {
addCriterion("piece_id in", values, "pieceId");
return (Criteria) this;
}
public Criteria andPieceIdNotIn(List<Integer> values) {
addCriterion("piece_id not in", values, "pieceId");
return (Criteria) this;
}
public Criteria andPieceIdBetween(Integer value1, Integer value2) {
addCriterion("piece_id between", value1, value2, "pieceId");
return (Criteria) this;
}
public Criteria andPieceIdNotBetween(Integer value1, Integer value2) {
addCriterion("piece_id not between", value1, value2, "pieceId");
return (Criteria) this;
}
public Criteria andTypeIsNull() {
addCriterion("type is null");
return (Criteria) this;
}
public Criteria andTypeIsNotNull() {
addCriterion("type is not null");
return (Criteria) this;
}
public Criteria andTypeEqualTo(Integer value) {
addCriterion("type =", value, "type");
return (Criteria) this;
}
public Criteria andTypeNotEqualTo(Integer value) {
addCriterion("type <>", value, "type");
return (Criteria) this;
}
public Criteria andTypeGreaterThan(Integer value) {
addCriterion("type >", value, "type");
return (Criteria) this;
}
public Criteria andTypeGreaterThanOrEqualTo(Integer value) {
addCriterion("type >=", value, "type");
return (Criteria) this;
}
public Criteria andTypeLessThan(Integer value) {
addCriterion("type <", value, "type");
return (Criteria) this;
}
public Criteria andTypeLessThanOrEqualTo(Integer value) {
addCriterion("type <=", value, "type");
return (Criteria) this;
}
public Criteria andTypeIn(List<Integer> values) {
addCriterion("type in", values, "type");
return (Criteria) this;
}
public Criteria andTypeNotIn(List<Integer> values) {
addCriterion("type not in", values, "type");
return (Criteria) this;
}
public Criteria andTypeBetween(Integer value1, Integer value2) {
addCriterion("type between", value1, value2, "type");
return (Criteria) this;
}
public Criteria andTypeNotBetween(Integer value1, Integer value2) {
addCriterion("type not between", value1, value2, "type");
return (Criteria) this;
}
public Criteria andRemarkIsNull() {
addCriterion("remark is null");
return (Criteria) this;
}
public Criteria andRemarkIsNotNull() {
addCriterion("remark is not null");
return (Criteria) this;
}
public Criteria andRemarkEqualTo(String value) {
addCriterion("remark =", value, "remark");
return (Criteria) this;
}
public Criteria andRemarkNotEqualTo(String value) {
addCriterion("remark <>", value, "remark");
return (Criteria) this;
}
public Criteria andRemarkGreaterThan(String value) {
addCriterion("remark >", value, "remark");
return (Criteria) this;
}
public Criteria andRemarkGreaterThanOrEqualTo(String value) {
addCriterion("remark >=", value, "remark");
return (Criteria) this;
}
public Criteria andRemarkLessThan(String value) {
addCriterion("remark <", value, "remark");
return (Criteria) this;
}
public Criteria andRemarkLessThanOrEqualTo(String value) {
addCriterion("remark <=", value, "remark");
return (Criteria) this;
}
public Criteria andRemarkLike(String value) {
addCriterion("remark like", value, "remark");
return (Criteria) this;
}
public Criteria andRemarkNotLike(String value) {
addCriterion("remark not like", value, "remark");
return (Criteria) this;
}
public Criteria andRemarkIn(List<String> values) {
addCriterion("remark in", values, "remark");
return (Criteria) this;
}
public Criteria andRemarkNotIn(List<String> values) {
addCriterion("remark not in", values, "remark");
return (Criteria) this;
}
public Criteria andRemarkBetween(String value1, String value2) {
addCriterion("remark between", value1, value2, "remark");
return (Criteria) this;
}
public Criteria andRemarkNotBetween(String value1, String value2) {
addCriterion("remark not between", value1, value2, "remark");
return (Criteria) this;
}
}
public static class Criteria extends GeneratedCriteria {
protected Criteria() {
super();
}
}
public static class Criterion {
private String condition;
private Object value;
private Object secondValue;
private boolean noValue;
private boolean singleValue;
private boolean betweenValue;
private boolean listValue;
private String typeHandler;
public String getCondition() {
return condition;
}
public Object getValue() {
return value;
}
public Object getSecondValue() {
return secondValue;
}
public boolean isNoValue() {
return noValue;
}
public boolean isSingleValue() {
return singleValue;
}
public boolean isBetweenValue() {
return betweenValue;
}
public boolean isListValue() {
return listValue;
}
public String getTypeHandler() {
return typeHandler;
}
protected Criterion(String condition) {
super();
this.condition = condition;
this.typeHandler = null;
this.noValue = true;
}
protected Criterion(String condition, Object value, String typeHandler) {
super();
this.condition = condition;
this.value = value;
this.typeHandler = typeHandler;
if (value instanceof List<?>) {
this.listValue = true;
} else {
this.singleValue = true;
}
}
protected Criterion(String condition, Object value) {
this(condition, value, null);
}
protected Criterion(String condition, Object value, Object secondValue, String typeHandler) {
super();
this.condition = condition;
this.value = value;
this.secondValue = secondValue;
this.typeHandler = typeHandler;
this.betweenValue = true;
}
protected Criterion(String condition, Object value, Object secondValue) {
this(condition, value, secondValue, null);
}
}
} |
import React, {useState} from 'react';
import Box from '@mui/material/Box';
import {DataGrid} from '@mui/x-data-grid';
import {randomStatusOptions, randomPrice} from '@mui/x-data-grid-generator';
import {styled} from "@mui/material";
const usdPrice = {
type: 'number',
width: 130,
valueFormatter: ({value}) => currencyFormatter.format(value),
cellClassName: 'font-tabular-nums',
};
const currencyFormatter = new Intl.NumberFormat('en-US', {
style: 'currency',
currency: 'USD',
});
const StyledDataGrid = styled(DataGrid)(({theme}) => ({
border: 0,
color:
theme.palette.mode === 'light' ? 'rgba(0,0,0,.85)' : 'rgba(255,255,255,0.85)',
fontFamily: [
'-apple-system',
'BlinkMacSystemFont',
'"Segoe UI"',
'Roboto',
'"Helvetica Neue"',
'Arial',
'sans-serif',
'"Apple Color Emoji"',
'"Segoe UI Emoji"',
'"Segoe UI Symbol"',
].join(','),
WebkitFontSmoothing: 'auto',
letterSpacing: 'normal',
'& .MuiDataGrid-columnsContainer': {
backgroundColor: theme.palette.mode === 'light' ? '#fafafa' : '#1d1d1d',
},
'& .MuiDataGrid-iconSeparator': {
display: 'none',
},
'& .MuiDataGrid-columnHeader, .MuiDataGrid-cell': {
borderRight: `1px solid ${
theme.palette.mode === 'light' ? '#f0f0f0' : '#303030'
}`,
},
'& .MuiDataGrid-columnsContainer, .MuiDataGrid-cell': {
borderBottom: `1px solid ${
theme.palette.mode === 'light' ? '#f0f0f0' : '#303030'
}`,
},
'& .MuiDataGrid-cell': {
color:
theme.palette.mode === 'light' ? 'rgba(0,0,0,.85)' : 'rgba(255,255,255,0.65)',
},
'& .MuiPaginationItem-root': {
borderRadius: 0,
},
}));
const columns = [
{field: 'id', headerName: 'ID', width: 90},
{
field: 'reference',
headerName: 'Concepto',
width: 200,
editable: true,
},
{
field: 'tipoTransaccion',
headerName: 'Tipo',
width: 200,
editable: true,
},
{
field: 'monto',
headerName: 'Monto',
width: 150,
editable: true,
...usdPrice
},
{
field: 'fechaTransaccion',
headerName: 'Fecha de creación',
width: 250,
editable: true,
},
{
field: 'fechaRegistro',
headerName: 'Fecha de Registro',
width: 150,
editable: true,
}
];
/*const rows = [
{
id: 1,
tipoTransaccion: 'Transferencia',
monto: randomPrice(),
fechaTransaccion: "2022-12-12",
fechaRegistro: "2023-12-12"
},
{
id: 2,
tipoTransaccion: 'Transferencia',
monto: randomPrice(),
fechaTransaccion: "2022-12-12",
fechaRegistro: "2023-12-12"
},
{
id: 3,
tipoTransaccion: 'Transferencia',
monto: randomPrice(),
fechaTransaccion: "2022-12-12",
fechaRegistro: "2023-12-12"
},
{
id: 4,
tipoTransaccion: 'Transferencia',
monto: randomPrice(),
fechaTransaccion: "2022-12-12",
fechaRegistro: "2023-12-12"
},
{
id: 5,
tipoTransaccion: 'Transferencia',
monto: randomPrice(),
fechaTransaccion: "2022-12-12",
fechaRegistro: "2023-12-12"
},
{
id: 6,
tipoTransaccion: 'Transferencia',
monto: randomPrice(),
fechaTransaccion: "2022-12-12",
fechaRegistro: "2023-12-12"
},
{
id: 7,
tipoTransaccion: 'Transferencia',
monto: randomPrice(),
fechaTransaccion: "2022-12-12",
fechaRegistro: "2023-12-12"
},
{
id: 8,
tipoTransaccion: 'Transferencia',
monto: randomPrice(),
fechaTransaccion: "2022-12-12",
fechaRegistro: "2023-12-12"
},
{
id: 9,
tipoTransaccion: 'Transferencia',
monto: randomPrice(),
fechaTransaccion: "2022-12-12",
fechaRegistro: "2023-12-12"
},
];*/
export default function TransactionsGrid(data) {
const transactions = [data.data]
const rows = transactions.map((transaction) => ({
id: transaction.uniqueKey,
reference: transaction.reference,
tipoTransaccion: transaction.transactionType,
monto: transaction.amount,
fechaTransaccion: transaction.valueDate,
fechaRegistro: transaction.creationDate
}));
return (
<Box sx={{height: 400, width: '100%'}}>
<StyledDataGrid
rows={rows}
columns={columns}
initialState={{
pagination: {
paginationModel: {
pageSize: 5,
},
},
columns:{
columnVisibilityModel: {
id: false,
}
}
}}
pageSizeOptions={[5]}
disableRowSelectionOnClick
/>
</Box>
);
} |
// @(#)root/unix:$Id: 887c618d89c4ed436e4034fc133f468fecad651b $
// Author: Fons Rademakers 15/09/95
/*************************************************************************
* Copyright (C) 1995-2000, Rene Brun and Fons Rademakers. *
* All rights reserved. *
* *
* For the licensing terms see $ROOTSYS/LICENSE. *
* For the list of contributors see $ROOTSYS/README/CREDITS. *
*************************************************************************/
// //
// TUnixSystem //
// //
// Class providing an interface to the UNIX Operating System. //
// //
#include "RConfigure.h"
#include <ROOT/RConfig.hxx>
#include <ROOT/FoundationUtils.hxx>
#include "TUnixSystem.h"
#include "TROOT.h"
#include "TError.h"
#include "TOrdCollection.h"
#include "TRegexp.h"
#include "TPRegexp.h"
#include "TException.h"
#include "Demangle.h"
#include "TEnv.h"
#include "Getline.h"
#include "TInterpreter.h"
#include "TApplication.h"
#include "TObjString.h"
#include "TVirtualMutex.h"
#include "ThreadLocalStorage.h"
#include "TObjArray.h"
#include "snprintf.h"
#include "strlcpy.h"
#include <iostream>
#include <fstream>
#include <map>
#include <algorithm>
#include <atomic>
//#define G__OLDEXPAND
#include <unistd.h>
#include <stdlib.h>
#include <sys/types.h>
#if defined(R__SUN) || defined(R__AIX) || \
defined(R__LINUX) || defined(R__SOLARIS) || \
defined(R__FBSD) || defined(R__OBSD) || \
defined(R__MACOSX) || defined(R__HURD)
#define HAS_DIRENT
#endif
#ifdef HAS_DIRENT
# include <dirent.h>
#else
# include <sys/dir.h>
#endif
#if defined(ULTRIX) || defined(R__SUN)
# include <sgtty.h>
#endif
#if defined(R__AIX) || defined(R__LINUX) || \
defined(R__FBSD) || defined(R__OBSD) || \
defined(R__LYNXOS) || defined(R__MACOSX) || defined(R__HURD)
# include <sys/ioctl.h>
#endif
#if defined(R__AIX) || defined(R__SOLARIS)
# include <sys/select.h>
#endif
#if defined(R__MACOSX)
# include <mach-o/dyld.h>
# include <sys/mount.h>
extern "C" int statfs(const char *file, struct statfs *buffer);
#elif defined(R__LINUX) || defined(R__HURD)
# include <sys/vfs.h>
#elif defined(R__FBSD) || defined(R__OBSD)
# include <sys/param.h>
# include <sys/mount.h>
#else
# include <sys/statfs.h>
#endif
#include <utime.h>
#include <syslog.h>
#include <sys/stat.h>
#include <setjmp.h>
#include <signal.h>
#include <sys/param.h>
#include <pwd.h>
#include <grp.h>
#include <errno.h>
#include <sys/resource.h>
#include <sys/wait.h>
#include <time.h>
#include <sys/time.h>
#include <sys/file.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netinet/tcp.h>
#if defined(R__AIX)
# define _XOPEN_EXTENDED_SOURCE
# include <arpa/inet.h>
# undef _XOPEN_EXTENDED_SOURCE
# if !defined(_AIX41) && !defined(_AIX43)
// AIX 3.2 doesn't have it
# define HASNOT_INETATON
# endif
#else
# include <arpa/inet.h>
#endif
#include <sys/un.h>
#include <netdb.h>
#include <fcntl.h>
#if defined(R__SOLARIS)
# include <sys/systeminfo.h>
# include <sys/filio.h>
# include <sys/sockio.h>
# define HASNOT_INETATON
# ifndef INADDR_NONE
# define INADDR_NONE (UInt_t)-1
# endif
#endif
#if defined(R__SOLARIS)
# define HAVE_UTMPX_H
# define UTMP_NO_ADDR
#endif
#if defined(MAC_OS_X_VERSION_10_5)
# define HAVE_UTMPX_H
# define UTMP_NO_ADDR
#endif
#if defined(R__FBSD)
# include <sys/param.h>
# if __FreeBSD_version >= 900007
# define HAVE_UTMPX_H
# endif
#endif
#if defined(R__AIX) || defined(R__FBSD) || \
defined(R__OBSD) || defined(R__LYNXOS) || \
(defined(R__MACOSX) && !defined(MAC_OS_X_VERSION_10_5))
# define UTMP_NO_ADDR
#endif
#if (defined(R__AIX) && !defined(_AIX43)) || \
(defined(R__SUNGCC3) && !defined(__arch64__))
# define USE_SIZE_T
#elif defined(R__GLIBC) || defined(R__FBSD) || \
(defined(R__SUNGCC3) && defined(__arch64__)) || \
defined(R__OBSD) || defined(MAC_OS_X_VERSION_10_4) || \
(defined(R__AIX) && defined(_AIX43)) || \
(defined(R__SOLARIS) && defined(_SOCKLEN_T))
# define USE_SOCKLEN_T
#endif
#if defined(R__LYNXOS)
extern "C" {
extern int putenv(const char *);
extern int inet_aton(const char *, struct in_addr *);
};
#endif
#ifdef HAVE_UTMPX_H
#include <utmpx.h>
#define STRUCT_UTMP struct utmpx
#else
#include <utmp.h>
#define STRUCT_UTMP struct utmp
#endif
#if !defined(UTMP_FILE) && defined(_PATH_UTMP) // 4.4BSD
#define UTMP_FILE _PATH_UTMP
#endif
#if defined(UTMPX_FILE) // Solaris, SysVr4
#undef UTMP_FILE
#define UTMP_FILE UTMPX_FILE
#endif
#ifndef UTMP_FILE
#define UTMP_FILE "/etc/utmp"
#endif
// stack trace code
#if (defined(R__LINUX) || defined(R__HURD)) && !defined(R__WINGCC)
# if __GLIBC__ == 2 && __GLIBC_MINOR__ >= 1
# define HAVE_BACKTRACE_SYMBOLS_FD
# endif
# define HAVE_DLADDR
#endif
#if defined(R__MACOSX)
# define HAVE_BACKTRACE_SYMBOLS_FD
# define HAVE_DLADDR
#endif
#ifdef HAVE_BACKTRACE_SYMBOLS_FD
# include <execinfo.h>
#endif
#ifdef HAVE_DLADDR
# ifndef __USE_GNU
# define __USE_GNU
# endif
# include <dlfcn.h>
#endif
#ifdef HAVE_BACKTRACE_SYMBOLS_FD
// The maximum stack trace depth for systems where we request the
// stack depth separately (currently glibc-based systems).
static const int kMAX_BACKTRACE_DEPTH = 128;
#endif
// FPE handling includes
#if (defined(R__LINUX) && !defined(R__WINGCC))
#include <fpu_control.h>
#include <fenv.h>
#include <sys/prctl.h> // for prctl() function used in StackTrace()
#endif
#if defined(R__MACOSX) && defined(__SSE2__)
#include <xmmintrin.h>
#endif
#if defined(R__MACOSX) && !defined(__SSE2__) && !defined(__xlC__) && \
!defined(__i386__) && !defined(__x86_64__) && !defined(__arm__) && \
!defined(__arm64__)
#include <fenv.h>
#include <signal.h>
#include <ucontext.h>
#include <stdlib.h>
#include <stdio.h>
#include <mach/thread_status.h>
#define fegetenvd(x) asm volatile("mffs %0" : "=f" (x));
#define fesetenvd(x) asm volatile("mtfsf 255,%0" : : "f" (x));
enum {
FE_ENABLE_INEXACT = 0x00000008,
FE_ENABLE_DIVBYZERO = 0x00000010,
FE_ENABLE_UNDERFLOW = 0x00000020,
FE_ENABLE_OVERFLOW = 0x00000040,
FE_ENABLE_INVALID = 0x00000080,
FE_ENABLE_ALL_EXCEPT = 0x000000F8
};
#endif
#if defined(R__MACOSX) && !defined(__SSE2__) && \
(defined(__i386__) || defined(__x86_64__) || defined(__arm__) || defined(__arm64__))
#include <fenv.h>
#endif
// End FPE handling includes
namespace {
// Depending on the platform the struct utmp (or utmpx) has either ut_name or ut_user
// which are semantically equivalent. Instead of using preprocessor magic,
// which is bothersome for cxx modules use SFINAE.
template<typename T>
struct ut_name {
template<typename U = T, typename std::enable_if<std::is_member_pointer<decltype(&U::ut_name)>::value, int>::type = 0>
static char getValue(U* ue, int) {
return ue->ut_name[0];
}
template<typename U = T, typename std::enable_if<std::is_member_pointer<decltype(&U::ut_user)>::value, int>::type = 0>
static char getValue(U* ue, long) {
return ue->ut_user[0];
}
};
static char get_ut_name(STRUCT_UTMP *ue) {
// 0 is an integer literal forcing an overload pickup in case both ut_name and ut_user are present.
return ut_name<STRUCT_UTMP>::getValue(ue, 0);
}
}
struct TUtmpContent {
STRUCT_UTMP *fUtmpContents;
UInt_t fEntries; // Number of entries in utmp file.
TUtmpContent() : fUtmpContents(nullptr), fEntries(0) {}
~TUtmpContent() { free(fUtmpContents); }
STRUCT_UTMP *SearchUtmpEntry(const char *tty)
{
// Look for utmp entry which is connected to terminal tty.
STRUCT_UTMP *ue = fUtmpContents;
UInt_t n = fEntries;
while (n--) {
if (get_ut_name(ue) && !strncmp(tty, ue->ut_line, sizeof(ue->ut_line)))
return ue;
ue++;
}
return nullptr;
}
int ReadUtmpFile()
{
// Read utmp file. Returns number of entries in utmp file.
FILE *utmp;
struct stat file_stats;
size_t n_read, size;
fEntries = 0;
R__LOCKGUARD2(gSystemMutex);
utmp = fopen(UTMP_FILE, "r");
if (!utmp)
return 0;
if (fstat(fileno(utmp), &file_stats) == -1) {
fclose(utmp);
return 0;
}
size = file_stats.st_size;
if (size <= 0) {
fclose(utmp);
return 0;
}
fUtmpContents = (STRUCT_UTMP *) malloc(size);
if (!fUtmpContents) {
fclose(utmp);
return 0;
}
n_read = fread(fUtmpContents, 1, size, utmp);
if (!ferror(utmp)) {
if (fclose(utmp) != EOF && n_read == size) {
fEntries = size / sizeof(STRUCT_UTMP);
return fEntries;
}
} else
fclose(utmp);
free(fUtmpContents);
fUtmpContents = 0;
return 0;
}
};
const char *kServerPath = "/tmp";
const char *kProtocolName = "tcp";
//------------------- Unix TFdSet ----------------------------------------------
#ifndef HOWMANY
# define HOWMANY(x, y) (((x)+((y)-1))/(y))
#endif
const Int_t kNFDBITS = (sizeof(Long_t) * 8); // 8 bits per byte
#ifdef FD_SETSIZE
const Int_t kFDSETSIZE = FD_SETSIZE; // Linux = 1024 file descriptors
#else
const Int_t kFDSETSIZE = 256; // upto 256 file descriptors
#endif
class TFdSet {
private:
ULong_t fds_bits[HOWMANY(kFDSETSIZE, kNFDBITS)];
public:
TFdSet() { memset(fds_bits, 0, sizeof(fds_bits)); }
TFdSet(const TFdSet &org) { memcpy(fds_bits, org.fds_bits, sizeof(org.fds_bits)); }
TFdSet &operator=(const TFdSet &rhs) { if (this != &rhs) { memcpy(fds_bits, rhs.fds_bits, sizeof(rhs.fds_bits));} return *this; }
void Zero() { memset(fds_bits, 0, sizeof(fds_bits)); }
void Set(Int_t n)
{
if (n >= 0 && n < kFDSETSIZE) {
fds_bits[n/kNFDBITS] |= (1UL << (n % kNFDBITS));
} else {
::Fatal("TFdSet::Set","fd (%d) out of range [0..%d]", n, kFDSETSIZE-1);
}
}
void Clr(Int_t n)
{
if (n >= 0 && n < kFDSETSIZE) {
fds_bits[n/kNFDBITS] &= ~(1UL << (n % kNFDBITS));
} else {
::Fatal("TFdSet::Clr","fd (%d) out of range [0..%d]", n, kFDSETSIZE-1);
}
}
Int_t IsSet(Int_t n)
{
if (n >= 0 && n < kFDSETSIZE) {
return (fds_bits[n/kNFDBITS] & (1UL << (n % kNFDBITS))) != 0;
} else {
::Fatal("TFdSet::IsSet","fd (%d) out of range [0..%d]", n, kFDSETSIZE-1);
return 0;
}
}
ULong_t *GetBits() { return (ULong_t *)fds_bits; }
};
/// Unix signal handler.
static void SigHandler(ESignals sig)
{
if (gSystem)
((TUnixSystem*)gSystem)->DispatchSignals(sig);
}
static const char *GetExePath()
{
TTHREAD_TLS_DECL(TString,exepath);
if (exepath == "") {
#if defined(R__MACOSX)
exepath = _dyld_get_image_name(0);
#elif defined(R__LINUX) || defined(R__SOLARIS) || defined(R__FBSD)
char buf[kMAXPATHLEN]; // exe path name
// get the name from the link in /proc
#if defined(R__LINUX)
int ret = readlink("/proc/self/exe", buf, kMAXPATHLEN);
#elif defined(R__SOLARIS)
int ret = readlink("/proc/self/path/a.out", buf, kMAXPATHLEN);
#elif defined(R__FBSD)
int ret = readlink("/proc/curproc/file", buf, kMAXPATHLEN);
#endif
if (ret > 0 && ret < kMAXPATHLEN) {
buf[ret] = 0;
exepath = buf;
}
#else
if (!gApplication)
return exepath;
TString p = gApplication->Argv(0);
if (p.BeginsWith("/"))
exepath = p;
else if (p.Contains("/")) {
exepath = gSystem->WorkingDirectory();
exepath += "/";
exepath += p;
} else {
char *exe = gSystem->Which(gSystem->Getenv("PATH"), p, kExecutePermission);
if (exe) {
exepath = exe;
delete [] exe;
}
}
#endif
}
return exepath;
}
#if defined(HAVE_DLADDR) && !defined(R__MACOSX)
static void SetRootSys()
{
#ifdef ROOTPREFIX
if (gSystem->Getenv("ROOTIGNOREPREFIX")) {
#endif
void *addr = (void *)SetRootSys;
Dl_info info;
if (dladdr(addr, &info) && info.dli_fname && info.dli_fname[0]) {
char respath[kMAXPATHLEN];
if (!realpath(info.dli_fname, respath)) {
if (!gSystem->Getenv("ROOTSYS"))
::SysError("TUnixSystem::SetRootSys", "error getting realpath of libCore, please set ROOTSYS in the shell");
} else {
TString rs = gSystem->GetDirName(respath);
gSystem->Setenv("ROOTSYS", gSystem->GetDirName(rs.Data()).Data());
}
}
#ifdef ROOTPREFIX
}
#endif
}
#endif
#if defined(R__MACOSX)
static TString gLinkedDylibs;
static void DylibAdded(const struct mach_header *mh, intptr_t /* vmaddr_slide */)
{
static int i = 0;
static Bool_t gotFirstSo = kFALSE;
static TString linkedDylibs;
// to copy the local linkedDylibs to the global gLinkedDylibs call this
// function with mh==0
if (!mh) {
gLinkedDylibs = linkedDylibs;
return;
}
TString lib = _dyld_get_image_name(i++);
TRegexp sovers = "libCore\\.[0-9]+\\.*[0-9]*\\.*[0-9]*\\.so";
TRegexp dyvers = "libCore\\.[0-9]+\\.*[0-9]*\\.*[0-9]*\\.dylib";
#ifdef ROOTPREFIX
if (gSystem->Getenv("ROOTIGNOREPREFIX")) {
#endif
if (lib.EndsWith("libCore.dylib") || lib.EndsWith("libCore.so") ||
lib.Index(sovers) != kNPOS || lib.Index(dyvers) != kNPOS) {
char respath[kMAXPATHLEN];
if (!realpath(lib, respath)) {
if (!gSystem->Getenv("ROOTSYS"))
::SysError("TUnixSystem::DylibAdded", "error getting realpath of libCore, please set ROOTSYS in the shell");
} else {
TString rs = gSystem->GetDirName(respath);
gSystem->Setenv("ROOTSYS", gSystem->GetDirName(rs.Data()).Data());
}
}
#ifdef ROOTPREFIX
}
#endif
// when libSystem.B.dylib is loaded we have finished loading all dylibs
// explicitly linked against the executable. Additional dylibs
// come when they are explicitly linked against loaded so's, currently
// we are not interested in these
if (lib.EndsWith("/libSystem.B.dylib")) {
gotFirstSo = kTRUE;
if (linkedDylibs.IsNull()) {
// TSystem::GetLibraries() assumes that an empty GetLinkedLibraries()
// means failure to extract the linked libraries. Signal "we did
// manage, but it's empty" by returning a single space.
linkedDylibs = ' ';
}
}
// add all libs loaded before libSystem.B.dylib
if (!gotFirstSo && (lib.EndsWith(".dylib") || lib.EndsWith(".so"))) {
sovers = "\\.[0-9]+\\.*[0-9]*\\.so";
Ssiz_t idx = lib.Index(sovers);
if (idx != kNPOS) {
lib.Remove(idx);
lib += ".so";
}
dyvers = "\\.[0-9]+\\.*[0-9]*\\.dylib";
idx = lib.Index(dyvers);
if (idx != kNPOS) {
lib.Remove(idx);
lib += ".dylib";
}
if (!gSystem->AccessPathName(lib, kReadPermission)) {
if (linkedDylibs.Length())
linkedDylibs += " ";
linkedDylibs += lib;
}
}
}
#endif
ClassImp(TUnixSystem);
TUnixSystem::TUnixSystem() : TSystem("Unix", "Unix System")
{ }
/// Reset to original state.
TUnixSystem::~TUnixSystem()
{
UnixResetSignals();
delete fReadmask;
delete fWritemask;
delete fReadready;
delete fWriteready;
delete fSignals;
}
/// Initialize Unix system interface.
Bool_t TUnixSystem::Init()
{
if (TSystem::Init())
return kTRUE;
fReadmask = new TFdSet;
fWritemask = new TFdSet;
fReadready = new TFdSet;
fWriteready = new TFdSet;
fSignals = new TFdSet;
//--- install default handlers
UnixSignal(kSigChild, SigHandler);
UnixSignal(kSigBus, SigHandler);
UnixSignal(kSigSegmentationViolation, SigHandler);
UnixSignal(kSigIllegalInstruction, SigHandler);
UnixSignal(kSigAbort, SigHandler);
UnixSignal(kSigSystem, SigHandler);
UnixSignal(kSigAlarm, SigHandler);
UnixSignal(kSigUrgent, SigHandler);
UnixSignal(kSigFloatingException, SigHandler);
UnixSignal(kSigWindowChanged, SigHandler);
UnixSignal(kSigUser2, SigHandler);
#if defined(R__MACOSX)
// trap loading of all dylibs to register dylib name,
// sets also ROOTSYS if built without ROOTPREFIX
_dyld_register_func_for_add_image(DylibAdded);
#elif defined(HAVE_DLADDR)
SetRootSys();
#endif
// This is a fallback in case TROOT::GetRootSys() can't determine ROOTSYS
gRootDir = ROOT::FoundationUtils::GetFallbackRootSys().c_str();
return kFALSE;
}
//---- Misc --------------------------------------------------------------------
/// Set the application name (from command line, argv[0]) and copy it in
/// gProgName. Copy the application pathname in gProgPath.
/// If name is 0 let the system set the actual executable name and path
/// (works on MacOS X and Linux).
void TUnixSystem::SetProgname(const char *name)
{
if (gProgName)
delete [] gProgName;
if (gProgPath)
delete [] gProgPath;
if (!name || !*name) {
name = GetExePath();
gProgName = StrDup(BaseName(name));
gProgPath = StrDup(DirName(name));
} else {
gProgName = StrDup(BaseName(name));
char *w = Which(Getenv("PATH"), gProgName);
gProgPath = StrDup(DirName(w));
delete [] w;
}
}
/// Set DISPLAY environment variable based on utmp entry. Only for UNIX.
void TUnixSystem::SetDisplay()
{
if (!Getenv("DISPLAY")) {
char *tty = ::ttyname(0); // device user is logged in on
if (tty) {
tty += 5; // remove "/dev/"
TUtmpContent utmp;
utmp.ReadUtmpFile();
STRUCT_UTMP *utmp_entry = utmp.SearchUtmpEntry(tty);
if (utmp_entry) {
if (utmp_entry->ut_host[0]) {
if (strchr(utmp_entry->ut_host, ':')) {
Setenv("DISPLAY", utmp_entry->ut_host);
Warning("SetDisplay", "DISPLAY not set, setting it to %s",
utmp_entry->ut_host);
} else {
char disp[260];
snprintf(disp, sizeof(disp), "%s:0.0", utmp_entry->ut_host);
Setenv("DISPLAY", disp);
Warning("SetDisplay", "DISPLAY not set, setting it to %s",
disp);
}
}
#ifndef UTMP_NO_ADDR
else if (utmp_entry->ut_addr) {
struct sockaddr_in addr;
addr.sin_family = AF_INET;
addr.sin_port = 0;
memcpy(&addr.sin_addr, &utmp_entry->ut_addr, sizeof(addr.sin_addr));
memset(&addr.sin_zero[0], 0, sizeof(addr.sin_zero));
struct sockaddr *sa = (struct sockaddr *) &addr; // input
char hbuf[NI_MAXHOST + 4];
if (getnameinfo(sa, sizeof(struct sockaddr), hbuf, sizeof(hbuf), nullptr, 0, NI_NAMEREQD) == 0) {
assert( strlen(hbuf) < NI_MAXHOST );
strcat(hbuf, ":0.0");
Setenv("DISPLAY", hbuf);
Warning("SetDisplay", "DISPLAY not set, setting it to %s",
hbuf);
}
}
#endif
}
}
#ifndef R__HAS_COCOA
if (!gROOT->IsBatch() && !getenv("DISPLAY")) {
Error("SetDisplay", "Can't figure out DISPLAY, set it manually\n"
"In case you run a remote ssh session, restart your ssh session with:\n"
"=========> ssh -Y");
}
#endif
}
}
/// Return system error string.
const char *TUnixSystem::GetError()
{
Int_t err = GetErrno();
if (err == 0 && GetLastErrorString() != "")
return GetLastErrorString();
#if defined(R__SOLARIS) || defined (R__LINUX) || defined(R__AIX) || \
defined(R__FBSD) || defined(R__OBSD) || defined(R__HURD)
return strerror(err);
#else
if (err < 0 || err >= sys_nerr)
return Form("errno out of range %d", err);
return sys_errlist[err];
#endif
}
/// Return the system's host name.
const char *TUnixSystem::HostName()
{
if (fHostname == "") {
char hn[64];
#if defined(R__SOLARIS)
sysinfo(SI_HOSTNAME, hn, sizeof(hn));
#else
gethostname(hn, sizeof(hn));
#endif
fHostname = hn;
}
return (const char *)fHostname;
}
//---- EventLoop ---------------------------------------------------------------
/// Add a file handler to the list of system file handlers. Only adds
/// the handler if it is not already in the list of file handlers.
void TUnixSystem::AddFileHandler(TFileHandler *h)
{
R__LOCKGUARD2(gSystemMutex);
TSystem::AddFileHandler(h);
if (h) {
int fd = h->GetFd();
if (h->HasReadInterest()) {
fReadmask->Set(fd);
fMaxrfd = TMath::Max(fMaxrfd, fd);
}
if (h->HasWriteInterest()) {
fWritemask->Set(fd);
fMaxwfd = TMath::Max(fMaxwfd, fd);
}
}
}
/// Remove a file handler from the list of file handlers. Returns
/// the handler or 0 if the handler was not in the list of file handlers.
TFileHandler *TUnixSystem::RemoveFileHandler(TFileHandler *h)
{
if (!h) return nullptr;
R__LOCKGUARD2(gSystemMutex);
TFileHandler *oh = TSystem::RemoveFileHandler(h);
if (oh) { // found
TFileHandler *th;
TIter next(fFileHandler);
fMaxrfd = -1;
fMaxwfd = -1;
fReadmask->Zero();
fWritemask->Zero();
while ((th = (TFileHandler *) next())) {
int fd = th->GetFd();
if (th->HasReadInterest()) {
fReadmask->Set(fd);
fMaxrfd = TMath::Max(fMaxrfd, fd);
}
if (th->HasWriteInterest()) {
fWritemask->Set(fd);
fMaxwfd = TMath::Max(fMaxwfd, fd);
}
}
}
return oh;
}
/// Add a signal handler to list of system signal handlers. Only adds
/// the handler if it is not already in the list of signal handlers.
void TUnixSystem::AddSignalHandler(TSignalHandler *h)
{
R__LOCKGUARD2(gSystemMutex);
TSystem::AddSignalHandler(h);
UnixSignal(h->GetSignal(), SigHandler);
}
/// Remove a signal handler from list of signal handlers. Returns
/// the handler or 0 if the handler was not in the list of signal handlers.
TSignalHandler *TUnixSystem::RemoveSignalHandler(TSignalHandler *h)
{
if (!h) return nullptr;
R__LOCKGUARD2(gSystemMutex);
TSignalHandler *oh = TSystem::RemoveSignalHandler(h);
Bool_t last = kTRUE;
TSignalHandler *hs;
TIter next(fSignalHandler);
while ((hs = (TSignalHandler*) next())) {
if (hs->GetSignal() == h->GetSignal())
last = kFALSE;
}
if (last)
ResetSignal(h->GetSignal(), kTRUE);
return oh;
}
/// If reset is true reset the signal handler for the specified signal
/// to the default handler, else restore previous behaviour.
void TUnixSystem::ResetSignal(ESignals sig, Bool_t reset)
{
if (reset)
UnixResetSignal(sig);
else
UnixSignal(sig, SigHandler);
}
/// Reset signals handlers to previous behaviour.
void TUnixSystem::ResetSignals()
{
UnixResetSignals();
}
/// If ignore is true ignore the specified signal, else restore previous
/// behaviour.
void TUnixSystem::IgnoreSignal(ESignals sig, Bool_t ignore)
{
UnixIgnoreSignal(sig, ignore);
}
/// When the argument is true the SIGALRM signal handler is set so that
/// interrupted syscalls will not be restarted by the kernel. This is
/// typically used in case one wants to put a timeout on an I/O operation.
/// By default interrupted syscalls will always be restarted (for all
/// signals). This can be controlled for each a-synchronous TTimer via
/// the method TTimer::SetInterruptSyscalls().
void TUnixSystem::SigAlarmInterruptsSyscalls(Bool_t set)
{
UnixSigAlarmInterruptsSyscalls(set);
}
/// Return the bitmap of conditions that trigger a floating point exception.
Int_t TUnixSystem::GetFPEMask()
{
Int_t mask = 0;
#if defined(R__LINUX) && !defined(__powerpc__)
#if defined(__GLIBC__) && (__GLIBC__>2 || __GLIBC__==2 && __GLIBC_MINOR__>=1)
#if __GLIBC_MINOR__>=3
Int_t oldmask = fegetexcept();
#else
fenv_t oldenv;
fegetenv(&oldenv);
fesetenv(&oldenv);
#if __ia64__
Int_t oldmask = ~oldenv;
#else
Int_t oldmask = ~oldenv.__control_word;
#endif
#endif
if (oldmask & FE_INVALID ) mask |= kInvalid;
if (oldmask & FE_DIVBYZERO) mask |= kDivByZero;
if (oldmask & FE_OVERFLOW ) mask |= kOverflow;
if (oldmask & FE_UNDERFLOW) mask |= kUnderflow;
# ifdef FE_INEXACT
if (oldmask & FE_INEXACT ) mask |= kInexact;
# endif
#endif
#endif
#if defined(R__MACOSX) && defined(__SSE2__)
// OS X uses the SSE unit for all FP math by default, not the x87 FP unit
Int_t oldmask = ~_MM_GET_EXCEPTION_MASK();
if (oldmask & _MM_MASK_INVALID ) mask |= kInvalid;
if (oldmask & _MM_MASK_DIV_ZERO ) mask |= kDivByZero;
if (oldmask & _MM_MASK_OVERFLOW ) mask |= kOverflow;
if (oldmask & _MM_MASK_UNDERFLOW) mask |= kUnderflow;
if (oldmask & _MM_MASK_INEXACT ) mask |= kInexact;
#endif
#if defined(R__MACOSX) && !defined(__SSE2__) && \
(defined(__i386__) || defined(__x86_64__) || defined(__arm__) || defined(__arm64__))
fenv_t oldenv;
fegetenv(&oldenv);
fesetenv(&oldenv);
#if defined(__arm__)
Int_t oldmask = ~oldenv.__fpscr;
#elif defined(__arm64__)
Int_t oldmask = ~oldenv.__fpcr;
#else
Int_t oldmask = ~oldenv.__control;
#endif
if (oldmask & FE_INVALID ) mask |= kInvalid;
if (oldmask & FE_DIVBYZERO) mask |= kDivByZero;
if (oldmask & FE_OVERFLOW ) mask |= kOverflow;
if (oldmask & FE_UNDERFLOW) mask |= kUnderflow;
if (oldmask & FE_INEXACT ) mask |= kInexact;
#endif
#if defined(R__MACOSX) && !defined(__SSE2__) && !defined(__xlC__) && \
!defined(__i386__) && !defined(__x86_64__) && !defined(__arm__) && \
!defined(__arm64__)
Long64_t oldmask;
fegetenvd(oldmask);
if (oldmask & FE_ENABLE_INVALID ) mask |= kInvalid;
if (oldmask & FE_ENABLE_DIVBYZERO) mask |= kDivByZero;
if (oldmask & FE_ENABLE_OVERFLOW ) mask |= kOverflow;
if (oldmask & FE_ENABLE_UNDERFLOW) mask |= kUnderflow;
if (oldmask & FE_ENABLE_INEXACT ) mask |= kInexact;
#endif
return mask;
}
/// Set which conditions trigger a floating point exception.
/// Return the previous set of conditions.
Int_t TUnixSystem::SetFPEMask(Int_t mask)
{
if (mask) { } // use mask to avoid warning
Int_t old = GetFPEMask();
#if defined(R__LINUX) && !defined(__powerpc__)
#if defined(__GLIBC__) && (__GLIBC__>2 || __GLIBC__==2 && __GLIBC_MINOR__>=1)
Int_t newm = 0;
if (mask & kInvalid ) newm |= FE_INVALID;
if (mask & kDivByZero) newm |= FE_DIVBYZERO;
if (mask & kOverflow ) newm |= FE_OVERFLOW;
if (mask & kUnderflow) newm |= FE_UNDERFLOW;
# ifdef FE_INEXACT
if (mask & kInexact ) newm |= FE_INEXACT;
# endif
#if __GLIBC_MINOR__>=3
// clear pending exceptions so feenableexcept does not trigger them
feclearexcept(FE_ALL_EXCEPT);
fedisableexcept(FE_ALL_EXCEPT);
feenableexcept(newm);
#else
fenv_t cur;
fegetenv(&cur);
#if defined __ia64__
cur &= ~newm;
#else
cur.__control_word &= ~newm;
#endif
fesetenv(&cur);
#endif
#endif
#endif
#if defined(R__MACOSX) && defined(__SSE2__)
// OS X uses the SSE unit for all FP math by default, not the x87 FP unit
Int_t newm = 0;
if (mask & kInvalid ) newm |= _MM_MASK_INVALID;
if (mask & kDivByZero) newm |= _MM_MASK_DIV_ZERO;
if (mask & kOverflow ) newm |= _MM_MASK_OVERFLOW;
if (mask & kUnderflow) newm |= _MM_MASK_UNDERFLOW;
if (mask & kInexact ) newm |= _MM_MASK_INEXACT;
_MM_SET_EXCEPTION_MASK(_MM_GET_EXCEPTION_MASK() & ~newm);
#endif
#if defined(R__MACOSX) && !defined(__SSE2__) && \
(defined(__i386__) || defined(__x86_64__) || defined(__arm__) || defined(__arm64__))
Int_t newm = 0;
if (mask & kInvalid ) newm |= FE_INVALID;
if (mask & kDivByZero) newm |= FE_DIVBYZERO;
if (mask & kOverflow ) newm |= FE_OVERFLOW;
if (mask & kUnderflow) newm |= FE_UNDERFLOW;
if (mask & kInexact ) newm |= FE_INEXACT;
fenv_t cur;
fegetenv(&cur);
#if defined(__arm__)
cur.__fpscr &= ~newm;
#elif defined(__arm64__)
cur.__fpcr &= ~newm;
#else
cur.__control &= ~newm;
#endif
fesetenv(&cur);
#endif
#if defined(R__MACOSX) && !defined(__SSE2__) && !defined(__xlC__) && \
!defined(__i386__) && !defined(__x86_64__) && !defined(__arm__) && \
!defined(__arm64__)
Int_t newm = 0;
if (mask & kInvalid ) newm |= FE_ENABLE_INVALID;
if (mask & kDivByZero) newm |= FE_ENABLE_DIVBYZERO;
if (mask & kOverflow ) newm |= FE_ENABLE_OVERFLOW;
if (mask & kUnderflow) newm |= FE_ENABLE_UNDERFLOW;
if (mask & kInexact ) newm |= FE_ENABLE_INEXACT;
Long64_t curmask;
fegetenvd(curmask);
curmask = (curmask & ~FE_ENABLE_ALL_EXCEPT) | newm;
fesetenvd(curmask);
#endif
return old;
}
/// Dispatch a single event.
void TUnixSystem::DispatchOneEvent(Bool_t pendingOnly)
{
Bool_t pollOnce = pendingOnly;
while (1) {
// first handle any X11 events
if (gXDisplay && gXDisplay->Notify()) {
if (fReadready->IsSet(gXDisplay->GetFd())) {
fReadready->Clr(gXDisplay->GetFd());
fNfd--;
}
if (!pendingOnly) return;
}
// check for file descriptors ready for reading/writing
if (fNfd > 0 && fFileHandler && fFileHandler->GetSize() > 0)
if (CheckDescriptors())
if (!pendingOnly) return;
fNfd = 0;
fReadready->Zero();
fWriteready->Zero();
if (pendingOnly && !pollOnce)
return;
// check synchronous signals
if (fSigcnt > 0 && fSignalHandler->GetSize() > 0)
if (CheckSignals(kTRUE))
if (!pendingOnly) return;
fSigcnt = 0;
fSignals->Zero();
// check synchronous timers
Long_t nextto;
if (fTimers && fTimers->GetSize() > 0)
if (DispatchTimers(kTRUE)) {
// prevent timers from blocking file descriptor monitoring
nextto = NextTimeOut(kTRUE);
if (nextto > kItimerResolution || nextto == -1)
return;
}
// if in pendingOnly mode poll once file descriptor activity
nextto = NextTimeOut(kTRUE);
if (pendingOnly) {
if (fFileHandler && fFileHandler->GetSize() == 0)
return;
nextto = 0;
pollOnce = kFALSE;
}
// nothing ready, so setup select call
*fReadready = *fReadmask;
*fWriteready = *fWritemask;
int mxfd = TMath::Max(fMaxrfd, fMaxwfd);
mxfd++;
// if nothing to select (socket or timer) return
if (mxfd == 0 && nextto == -1)
return;
fNfd = UnixSelect(mxfd, fReadready, fWriteready, nextto);
if (fNfd < 0 && fNfd != -2) {
int fd, rc;
TFdSet t;
for (fd = 0; fd < mxfd; fd++) {
t.Set(fd);
if (fReadmask->IsSet(fd)) {
rc = UnixSelect(fd+1, &t, 0, 0);
if (rc < 0 && rc != -2) {
SysError("DispatchOneEvent", "select: read error on %d", fd);
fReadmask->Clr(fd);
}
}
if (fWritemask->IsSet(fd)) {
rc = UnixSelect(fd+1, 0, &t, 0);
if (rc < 0 && rc != -2) {
SysError("DispatchOneEvent", "select: write error on %d", fd);
fWritemask->Clr(fd);
}
}
t.Clr(fd);
}
}
}
}
/// Sleep milliSec milliseconds.
void TUnixSystem::Sleep(UInt_t milliSec)
{
struct timeval tv;
tv.tv_sec = milliSec / 1000;
tv.tv_usec = (milliSec % 1000) * 1000;
select(0, 0, 0, 0, &tv);
}
/// Select on file descriptors. The timeout to is in millisec. Returns
/// the number of ready descriptors, or 0 in case of timeout, or < 0 in
/// case of an error, with -2 being EINTR and -3 EBADF. In case of EINTR
/// the errno has been reset and the method can be called again. Returns
/// -4 in case the list did not contain any file handlers or file handlers
/// with file descriptor >= 0.
Int_t TUnixSystem::Select(TList *act, Long_t to)
{
Int_t rc = -4;
TFdSet rd, wr;
Int_t mxfd = -1;
TIter next(act);
TFileHandler *h = 0;
while ((h = (TFileHandler *) next())) {
Int_t fd = h->GetFd();
if (fd > -1) {
if (h->HasReadInterest()) {
rd.Set(fd);
mxfd = TMath::Max(mxfd, fd);
}
if (h->HasWriteInterest()) {
wr.Set(fd);
mxfd = TMath::Max(mxfd, fd);
}
h->ResetReadyMask();
}
}
if (mxfd > -1)
rc = UnixSelect(mxfd+1, &rd, &wr, to);
// Set readiness bits
if (rc > 0) {
next.Reset();
while ((h = (TFileHandler *) next())) {
Int_t fd = h->GetFd();
if (rd.IsSet(fd))
h->SetReadReady();
if (wr.IsSet(fd))
h->SetWriteReady();
}
}
return rc;
}
/// Select on the file descriptor related to file handler h.
/// The timeout to is in millisec. Returns the number of ready descriptors,
/// or 0 in case of timeout, or < 0 in case of an error, with -2 being EINTR
/// and -3 EBADF. In case of EINTR the errno has been reset and the method
/// can be called again. Returns -4 in case the file handler is 0 or does
/// not have a file descriptor >= 0.
Int_t TUnixSystem::Select(TFileHandler *h, Long_t to)
{
Int_t rc = -4;
TFdSet rd, wr;
Int_t mxfd = -1;
Int_t fd = -1;
if (h) {
fd = h->GetFd();
if (fd > -1) {
if (h->HasReadInterest())
rd.Set(fd);
if (h->HasWriteInterest())
wr.Set(fd);
h->ResetReadyMask();
mxfd = fd;
rc = UnixSelect(mxfd+1, &rd, &wr, to);
}
}
// Fill output lists, if required
if (rc > 0) {
if (rd.IsSet(fd))
h->SetReadReady();
if (wr.IsSet(fd))
h->SetWriteReady();
}
return rc;
}
//---- handling of system events -----------------------------------------------
/// Check if some signals were raised and call their Notify() member.
Bool_t TUnixSystem::CheckSignals(Bool_t sync)
{
TSignalHandler *sh;
Int_t sigdone = -1;
{
TOrdCollectionIter it((TOrdCollection*)fSignalHandler);
while ((sh = (TSignalHandler*)it.Next())) {
if (sync == sh->IsSync()) {
ESignals sig = sh->GetSignal();
if ((fSignals->IsSet(sig) && sigdone == -1) || sigdone == sig) {
if (sigdone == -1) {
fSignals->Clr(sig);
sigdone = sig;
fSigcnt--;
}
if (sh->IsActive())
sh->Notify();
}
}
}
}
if (sigdone != -1)
return kTRUE;
return kFALSE;
}
/// Check if children have finished.
void TUnixSystem::CheckChilds()
{
#if 0 //rdm
int pid;
while ((pid = UnixWaitchild()) > 0) {
TIter next(zombieHandler);
register UnixPtty *pty;
while ((pty = (UnixPtty*) next()))
if (pty->GetPid() == pid) {
zombieHandler->RemovePtr(pty);
pty->DiedNotify();
}
}
#endif
}
/// Check if there is activity on some file descriptors and call their
/// Notify() member.
Bool_t TUnixSystem::CheckDescriptors()
{
TFileHandler *fh;
Int_t fddone = -1;
Bool_t read = kFALSE;
TOrdCollectionIter it((TOrdCollection*)fFileHandler);
while ((fh = (TFileHandler*) it.Next())) {
Int_t fd = fh->GetFd();
if ((fd <= fMaxrfd && fReadready->IsSet(fd) && fddone == -1) ||
(fddone == fd && read)) {
if (fddone == -1) {
fReadready->Clr(fd);
fddone = fd;
read = kTRUE;
fNfd--;
}
if (fh->IsActive())
fh->ReadNotify();
}
if ((fd <= fMaxwfd && fWriteready->IsSet(fd) && fddone == -1) ||
(fddone == fd && !read)) {
if (fddone == -1) {
fWriteready->Clr(fd);
fddone = fd;
read = kFALSE;
fNfd--;
}
if (fh->IsActive())
fh->WriteNotify();
}
}
if (fddone != -1)
return kTRUE;
return kFALSE;
}
//---- Directories -------------------------------------------------------------
/// Make a Unix file system directory. Returns 0 in case of success and
/// -1 if the directory could not be created.
int TUnixSystem::MakeDirectory(const char *name)
{
TSystem *helper = FindHelper(name);
if (helper)
return helper->MakeDirectory(name);
return UnixMakedir(name);
}
/// Open a Unix file system directory. Returns 0 if directory does not exist.
void *TUnixSystem::OpenDirectory(const char *name)
{
TSystem *helper = FindHelper(name);
if (helper)
return helper->OpenDirectory(name);
return UnixOpendir(name);
}
/// Close a Unix file system directory.
void TUnixSystem::FreeDirectory(void *dirp)
{
TSystem *helper = FindHelper(0, dirp);
if (helper) {
helper->FreeDirectory(dirp);
return;
}
if (dirp)
::closedir((DIR*)dirp);
}
/// Get next Unix file system directory entry. Returns 0 if no more entries.
const char *TUnixSystem::GetDirEntry(void *dirp)
{
TSystem *helper = FindHelper(0, dirp);
if (helper)
return helper->GetDirEntry(dirp);
if (dirp)
return UnixGetdirentry(dirp);
return nullptr;
}
/// Change directory. Returns kTRUE in case of success, kFALSE otherwise.
Bool_t TUnixSystem::ChangeDirectory(const char *path)
{
Bool_t ret = (Bool_t) (::chdir(path) == 0);
if (fWdpath != "")
fWdpath = ""; // invalidate path cache
return ret;
}
/// Return working directory.
const char *TUnixSystem::WorkingDirectory()
{
// don't use cache as user can call chdir() directly somewhere else
//if (fWdpath != "")
// return fWdpath.Data();
R__LOCKGUARD2(gSystemMutex);
static char cwd[kMAXPATHLEN];
FillWithCwd(cwd);
fWdpath = cwd;
return fWdpath.Data();
}
/// Return working directory.
std::string TUnixSystem::GetWorkingDirectory() const
{
char cwd[kMAXPATHLEN];
FillWithCwd(cwd);
return std::string(cwd);
}
/// Fill buffer with current working directory.
void TUnixSystem::FillWithCwd(char *cwd) const
{
if (::getcwd(cwd, kMAXPATHLEN) == 0) {
Error("WorkingDirectory", "getcwd() failed");
}
}
/// Return the user's home directory.
const char *TUnixSystem::HomeDirectory(const char *userName)
{
return UnixHomedirectory(userName);
}
/// Return the user's home directory.
std::string TUnixSystem::GetHomeDirectory(const char *userName) const
{
char path[kMAXPATHLEN], mydir[kMAXPATHLEN] = { '\0' };
auto res = UnixHomedirectory(userName, path, mydir);
if (res) return std::string(res);
else return std::string();
}
/// Return a user configured or systemwide directory to create
/// temporary files in.
const char *TUnixSystem::TempDirectory() const
{
const char *dir = gSystem->Getenv("TMPDIR");
if (!dir || gSystem->AccessPathName(dir, kWritePermission))
dir = "/tmp";
return dir;
}
/// Create a secure temporary file by appending a unique
/// 6 letter string to base. The file will be created in
/// a standard (system) directory or in the directory
/// provided in dir. The full filename is returned in base
/// and a filepointer is returned for safely writing to the file
/// (this avoids certain security problems). Returns 0 in case
/// of error.
FILE *TUnixSystem::TempFileName(TString &base, const char *dir)
{
char *b = ConcatFileName(dir ? dir : TempDirectory(), base);
base = b;
base += "XXXXXX";
delete [] b;
char *arg = StrDup(base);
int fd = mkstemp(arg);
base = arg;
delete [] arg;
if (fd == -1) {
SysError("TempFileName", "%s", base.Data());
return nullptr;
} else {
FILE *fp = fdopen(fd, "w+");
if (!fp)
SysError("TempFileName", "converting filedescriptor (%d)", fd);
return fp;
}
}
/// Concatenate a directory and a file name.
const char *TUnixSystem::PrependPathName(const char *dir, TString& name)
{
if (name.IsNull() || name == ".") {
if (dir) {
name = dir;
if (dir[strlen(dir) - 1] != '/')
name += '/';
} else name = "";
return name.Data();
}
if (!dir || !dir[0])
dir = "/";
else if (dir[strlen(dir) - 1] != '/')
name.Prepend('/');
name.Prepend(dir);
return name.Data();
}
//---- Paths & Files -----------------------------------------------------------
/// Returns FALSE if one can access a file using the specified access mode.
/// Mode is the same as for the Unix access(2) function.
/// Attention, bizarre convention of return value!!
Bool_t TUnixSystem::AccessPathName(const char *path, EAccessMode mode)
{
TSystem *helper = FindHelper(path);
if (helper)
return helper->AccessPathName(path, mode);
if (::access(StripOffProto(path, "file:"), mode) == 0)
return kFALSE;
GetLastErrorString() = GetError();
return kTRUE;
}
/// Copy a file. If overwrite is true and file already exists the
/// file will be overwritten. Returns 0 when successful, -1 in case
/// of file open failure, -2 in case the file already exists and overwrite
/// was false and -3 in case of error during copy.
int TUnixSystem::CopyFile(const char *f, const char *t, Bool_t overwrite)
{
if (!AccessPathName(t) && !overwrite)
return -2;
FILE *from = fopen(f, "r");
if (!from)
return -1;
FILE *to = fopen(t, "w");
if (!to) {
fclose(from);
return -1;
}
const int bufsize = 1024;
char buf[bufsize];
int ret = 0;
while (!ret && !feof(from)) {
size_t numread = fread (buf, sizeof(char), bufsize, from);
size_t numwritten = fwrite(buf, sizeof(char), numread, to);
if (numread != numwritten)
ret = -3;
}
fclose(from);
fclose(to);
return ret;
}
/// Rename a file. Returns 0 when successful, -1 in case of failure.
int TUnixSystem::Rename(const char *f, const char *t)
{
int ret = ::rename(f, t);
GetLastErrorString() = GetError();
return ret;
}
/// Returns TRUE if the url in 'path' points to the local file system.
/// This is used to avoid going through the NIC card for local operations.
Bool_t TUnixSystem::IsPathLocal(const char *path)
{
TSystem *helper = FindHelper(path);
if (helper)
return helper->IsPathLocal(path);
return TSystem::IsPathLocal(path);
}
/// Get info about a file. Info is returned in the form of a FileStat_t
/// structure (see TSystem.h).
/// The function returns 0 in case of success and 1 if the file could
/// not be stat'ed.
int TUnixSystem::GetPathInfo(const char *path, FileStat_t &buf)
{
TSystem *helper = FindHelper(path);
if (helper)
return helper->GetPathInfo(path, buf);
return UnixFilestat(path, buf);
}
/// Get info about a file system: id, bsize, bfree, blocks.
/// Id is file system type (machine dependend, see statfs())
/// Bsize is block size of file system
/// Blocks is total number of blocks in file system
/// Bfree is number of free blocks in file system
/// The function returns 0 in case of success and 1 if the file system could
/// not be stat'ed.
int TUnixSystem::GetFsInfo(const char *path, Long_t *id, Long_t *bsize,
Long_t *blocks, Long_t *bfree)
{
return UnixFSstat(path, id, bsize, blocks, bfree);
}
/// Create a link from file1 to file2. Returns 0 when successful,
/// -1 in case of failure.
int TUnixSystem::Link(const char *from, const char *to)
{
return ::link(from, to);
}
/// Create a symlink from file1 to file2. Returns 0 when successful,
/// -1 in case of failure.
int TUnixSystem::Symlink(const char *from, const char *to)
{
#if defined(R__AIX)
return ::symlink((char*)from, (char*)to);
#else
return ::symlink(from, to);
#endif
}
/// Unlink, i.e. remove, a file or directory. Returns 0 when successful,
/// -1 in case of failure.
int TUnixSystem::Unlink(const char *name)
{
TSystem *helper = FindHelper(name);
if (helper)
return helper->Unlink(name);
#if defined(R__SEEK64)
struct stat64 finfo;
if (lstat64(name, &finfo) < 0)
#else
struct stat finfo;
if (lstat(name, &finfo) < 0)
#endif
return -1;
if (S_ISDIR(finfo.st_mode))
return ::rmdir(name);
else
return ::unlink(name);
}
//---- expand the metacharacters as in the shell -------------------------------
// expand the metacharacters as in the shell
const char
#ifdef G__OLDEXPAND
kShellEscape = '\\',
*kShellStuff = "(){}<>\"'",
#endif
*kShellMeta = "~*[]{}?$";
#ifndef G__OLDEXPAND
/// Expand a pathname getting rid of special shell characters like ~.$, etc.
/// For Unix/Win32 compatibility use $(XXX) instead of $XXX when using
/// environment variables in a pathname. If compatibility is not an issue
/// you can use on Unix directly $XXX. Returns kFALSE in case of success
/// or kTRUE in case of error.
Bool_t TUnixSystem::ExpandPathName(TString &path)
{
const char *p, *patbuf = (const char *)path;
// skip leading blanks
while (*patbuf == ' ')
patbuf++;
// any shell meta characters ?
for (p = patbuf; *p; p++)
if (strchr(kShellMeta, *p))
goto expand;
return kFALSE;
expand:
// replace $(XXX) by $XXX
path.ReplaceAll("$(","$");
path.ReplaceAll(")","");
return ExpandFileName(path);
}
#endif
#ifdef G__OLDEXPAND
/// Expand a pathname getting rid of special shell characters like ~.$, etc.
/// For Unix/Win32 compatibility use $(XXX) instead of $XXX when using
/// environment variables in a pathname. If compatibility is not an issue
/// you can use on Unix directly $XXX. Returns kFALSE in case of success
/// or kTRUE in case of error.
Bool_t TUnixSystem::ExpandPathName(TString &patbuf0)
{
const char *patbuf = (const char *)patbuf0;
const char *hd, *p;
// char cmd[kMAXPATHLEN],
char stuffedPat[kMAXPATHLEN], name[70];
char *q;
FILE *pf;
int ch;
// skip leading blanks
while (*patbuf == ' ')
patbuf++;
// any shell meta characters ?
for (p = patbuf; *p; p++)
if (strchr(kShellMeta, *p))
goto needshell;
return kFALSE;
needshell:
// replace $(XXX) by $XXX
patbuf0.ReplaceAll("$(","$");
patbuf0.ReplaceAll(")","");
// escape shell quote characters
EscChar(patbuf, stuffedPat, sizeof(stuffedPat), (char*)kShellStuff, kShellEscape);
TString cmd("echo ");
// emulate csh -> popen executes sh
if (stuffedPat[0] == '~') {
if (stuffedPat[1] != '\0' && stuffedPat[1] != '/') {
// extract user name
for (p = &stuffedPat[1], q = name; *p && *p !='/';)
*q++ = *p++;
*q = '\0';
hd = UnixHomedirectory(name);
if (hd == 0)
cmd += stuffedPat;
else {
cmd += hd;
cmd += p;
}
} else {
hd = UnixHomedirectory(0);
if (hd == 0) {
GetLastErrorString() = GetError();
return kTRUE;
}
cmd += hd;
cmd += &stuffedPat[1];
}
} else
cmd += stuffedPat;
if ((pf = ::popen(cmd.Data(), "r")) == 0) {
GetLastErrorString() = GetError();
return kTRUE;
}
// read first argument
patbuf0 = "";
int cnt = 0;
#if defined(R__AIX)
again:
#endif
for (ch = fgetc(pf); ch != EOF && ch != ' ' && ch != '\n'; ch = fgetc(pf)) {
patbuf0.Append(ch);
cnt++;
}
#if defined(R__AIX)
// Work around bug timing problem due to delay in forking a large program
if (cnt == 0 && ch == EOF) goto again;
#endif
// skip rest of pipe
while (ch != EOF) {
ch = fgetc(pf);
if (ch == ' ' || ch == '\t') {
GetLastErrorString() = "expression ambigous";
::pclose(pf);
return kTRUE;
}
}
::pclose(pf);
return kFALSE;
}
#endif
/// Expand a pathname getting rid of special shell characaters like ~.$, etc.
/// For Unix/Win32 compatibility use $(XXX) instead of $XXX when using
/// environment variables in a pathname. If compatibility is not an issue
/// you can use on Unix directly $XXX. The user must delete returned string.
/// Returns the expanded pathname or 0 in case of error.
/// The user must delete returned string (delete []).
char *TUnixSystem::ExpandPathName(const char *path)
{
TString patbuf = path;
if (ExpandPathName(patbuf))
return nullptr;
return StrDup(patbuf.Data());
}
/// Set the file permission bits. Returns -1 in case or error, 0 otherwise.
int TUnixSystem::Chmod(const char *file, UInt_t mode)
{
return ::chmod(file, mode);
}
/// Set the process file creation mode mask.
int TUnixSystem::Umask(Int_t mask)
{
return ::umask(mask);
}
/// Set a files modification and access times. If actime = 0 it will be
/// set to the modtime. Returns 0 on success and -1 in case of error.
int TUnixSystem::Utime(const char *file, Long_t modtime, Long_t actime)
{
if (!actime)
actime = modtime;
struct utimbuf t;
t.actime = (time_t)actime;
t.modtime = (time_t)modtime;
return ::utime(file, &t);
}
/// Find location of file "wfil" in a search path.
/// The search path is specified as a : separated list of directories.
/// Return value is pointing to wfile for compatibility with
/// Which(const char*,const char*,EAccessMode) version.
const char *TUnixSystem::FindFile(const char *search, TString& wfil, EAccessMode mode)
{
TString show;
if (gEnv->GetValue("Root.ShowPath", 0))
show.Form("Which: %s =", wfil.Data());
gSystem->ExpandPathName(wfil);
if (wfil[0] == '/') {
#if defined(R__SEEK64)
struct stat64 finfo;
if (access(wfil.Data(), mode) == 0 &&
stat64(wfil.Data(), &finfo) == 0 && S_ISREG(finfo.st_mode)) {
#else
struct stat finfo;
if (access(wfil.Data(), mode) == 0 &&
stat(wfil.Data(), &finfo) == 0 && S_ISREG(finfo.st_mode)) {
#endif
if (show != "")
Printf("%s %s", show.Data(), wfil.Data());
return wfil.Data();
}
if (show != "")
Printf("%s <not found>", show.Data());
wfil = "";
return nullptr;
}
if (!search)
search = ".";
TString apwd(gSystem->WorkingDirectory());
apwd += "/";
for (const char* ptr = search; *ptr;) {
TString name;
if (*ptr != '/' && *ptr !='$' && *ptr != '~')
name = apwd;
const char* posEndOfPart = strchr(ptr, ':');
if (posEndOfPart) {
name.Append(ptr, posEndOfPart - ptr);
ptr = posEndOfPart + 1; // skip ':'
} else {
name.Append(ptr);
ptr += strlen(ptr);
}
if (!name.EndsWith("/"))
name += '/';
name += wfil;
gSystem->ExpandPathName(name);
#if defined(R__SEEK64)
struct stat64 finfo;
if (access(name.Data(), mode) == 0 &&
stat64(name.Data(), &finfo) == 0 && S_ISREG(finfo.st_mode)) {
#else
struct stat finfo;
if (access(name.Data(), mode) == 0 &&
stat(name.Data(), &finfo) == 0 && S_ISREG(finfo.st_mode)) {
#endif
if (show != "")
Printf("%s %s", show.Data(), name.Data());
wfil = name;
return wfil.Data();
}
}
if (show != "")
Printf("%s <not found>", show.Data());
wfil = "";
return nullptr;
}
//---- Users & Groups ----------------------------------------------------------
/// Returns the user's id. If user = 0, returns current user's id.
Int_t TUnixSystem::GetUid(const char *user)
{
if (!user || !user[0])
return getuid();
else {
struct passwd *apwd = getpwnam(user);
if (apwd)
return apwd->pw_uid;
}
return 0;
}
/// Returns the effective user id. The effective id corresponds to the
/// set id bit on the file being executed.
Int_t TUnixSystem::GetEffectiveUid()
{
return geteuid();
}
/// Returns the group's id. If group = 0, returns current user's group.
Int_t TUnixSystem::GetGid(const char *group)
{
if (!group || !group[0])
return getgid();
else {
struct group *grp = getgrnam(group);
if (grp)
return grp->gr_gid;
}
return 0;
}
/// Returns the effective group id. The effective group id corresponds
/// to the set id bit on the file being executed.
Int_t TUnixSystem::GetEffectiveGid()
{
return getegid();
}
/// Returns all user info in the UserGroup_t structure. The returned
/// structure must be deleted by the user. In case of error 0 is returned.
UserGroup_t *TUnixSystem::GetUserInfo(Int_t uid)
{
typedef std::map<Int_t /*uid*/, UserGroup_t> UserInfoCache_t;
static UserInfoCache_t gUserInfo;
UserInfoCache_t::const_iterator iUserInfo = gUserInfo.find(uid);
if (iUserInfo != gUserInfo.end())
return new UserGroup_t(iUserInfo->second);
struct passwd *apwd = getpwuid(uid);
if (apwd) {
UserGroup_t *ug = new UserGroup_t;
ug->fUid = apwd->pw_uid;
ug->fGid = apwd->pw_gid;
ug->fUser = apwd->pw_name;
ug->fPasswd = apwd->pw_passwd;
ug->fRealName = apwd->pw_gecos;
ug->fShell = apwd->pw_shell;
UserGroup_t *gr = GetGroupInfo(apwd->pw_gid);
if (gr) ug->fGroup = gr->fGroup;
delete gr;
gUserInfo[uid] = *ug;
return ug;
}
return nullptr;
}
/// Returns all user info in the UserGroup_t structure. If user = 0, returns
/// current user's id info. The returned structure must be deleted by the
/// user. In case of error 0 is returned.
UserGroup_t *TUnixSystem::GetUserInfo(const char *user)
{
return GetUserInfo(GetUid(user));
}
/// Returns all group info in the UserGroup_t structure. The only active
/// fields in the UserGroup_t structure for this call are:
/// fGid and fGroup
/// The returned structure must be deleted by the user. In case of
/// error 0 is returned.
UserGroup_t *TUnixSystem::GetGroupInfo(Int_t gid)
{
struct group *grp = getgrgid(gid);
if (grp) {
UserGroup_t *gr = new UserGroup_t;
gr->fUid = 0;
gr->fGid = grp->gr_gid;
gr->fGroup = grp->gr_name;
return gr;
}
return nullptr;
}
/// Returns all group info in the UserGroup_t structure. The only active
/// fields in the UserGroup_t structure for this call are:
/// fGid and fGroup
/// If group = 0, returns current user's group. The returned structure
/// must be deleted by the user. In case of error 0 is returned.
UserGroup_t *TUnixSystem::GetGroupInfo(const char *group)
{
return GetGroupInfo(GetGid(group));
}
//---- environment manipulation ------------------------------------------------
/// Set environment variable.
void TUnixSystem::Setenv(const char *name, const char *value)
{
::setenv(name, value, 1);
}
/// Get environment variable.
const char *TUnixSystem::Getenv(const char *name)
{
return ::getenv(name);
}
/// Unset environment variable.
void TUnixSystem::Unsetenv(const char *name)
{
::unsetenv(name);
}
//---- Processes ---------------------------------------------------------------
/// Execute a command.
int TUnixSystem::Exec(const char *shellcmd)
{
return ::system(shellcmd);
}
/// Open a pipe.
FILE *TUnixSystem::OpenPipe(const char *command, const char *mode)
{
return ::popen(command, mode);
}
/// Close the pipe.
int TUnixSystem::ClosePipe(FILE *pipe)
{
return ::pclose(pipe);
}
/// Get process id.
int TUnixSystem::GetPid()
{
return ::getpid();
}
/// Exit the application.
void TUnixSystem::Exit(int code, Bool_t mode)
{
// Insures that the files and sockets are closed before any library is unloaded
// and before emptying CINT.
TROOT::ShutDown();
if (mode)
::exit(code);
else
::_exit(code);
}
/// Abort the application.
void TUnixSystem::Abort(int)
{
IgnoreSignal(kSigAbort);
::abort();
}
#ifdef R__MACOSX
/// Use CoreSymbolication to retrieve the stacktrace.
#include <mach/mach.h>
extern "C" {
// Adapted from https://github.com/mountainstorm/CoreSymbolication
// Under the hood the framework basically just calls through to a set of C++ libraries
typedef struct {
void* csCppData;
void* csCppObj;
} CSTypeRef;
typedef CSTypeRef CSSymbolicatorRef;
typedef CSTypeRef CSSourceInfoRef;
typedef CSTypeRef CSSymbolOwnerRef;
typedef CSTypeRef CSSymbolRef;
CSSymbolicatorRef CSSymbolicatorCreateWithPid(pid_t pid);
CSSymbolRef CSSymbolicatorGetSymbolWithAddressAtTime(CSSymbolicatorRef cs, vm_address_t addr, uint64_t time);
CSSourceInfoRef CSSymbolicatorGetSourceInfoWithAddressAtTime(CSSymbolicatorRef cs, vm_address_t addr, uint64_t time);
const char* CSSymbolGetName(CSSymbolRef sym);
CSSymbolOwnerRef CSSymbolGetSymbolOwner(CSSymbolRef sym);
const char* CSSymbolOwnerGetPath(CSSymbolOwnerRef symbol);
const char* CSSourceInfoGetPath(CSSourceInfoRef info);
int CSSourceInfoGetLineNumber(CSSourceInfoRef info);
}
bool CSTypeRefIdValid(CSTypeRef ref) {
return ref.csCppData || ref.csCppObj;
}
void macosx_backtrace() {
void* addrlist[kMAX_BACKTRACE_DEPTH];
// retrieve current stack addresses
int numstacks = backtrace( addrlist, sizeof( addrlist ) / sizeof( void* ));
CSSymbolicatorRef symbolicator = CSSymbolicatorCreateWithPid(getpid());
// skip TUnixSystem::Backtrace(), macosx_backtrace()
static const int skipFrames = 2;
for (int i = skipFrames; i < numstacks; ++i) {
// No debug info, try to get at least the symbol name.
CSSymbolRef sym = CSSymbolicatorGetSymbolWithAddressAtTime(symbolicator,
(vm_address_t)addrlist[i],
0x80000000u);
CSSymbolOwnerRef symOwner = CSSymbolGetSymbolOwner(sym);
if (const char* libPath = CSSymbolOwnerGetPath(symOwner)) {
printf("[%s]", libPath);
} else {
printf("[<unknown binary>]");
}
if (const char* symname = CSSymbolGetName(sym)) {
printf(" %s", symname);
}
CSSourceInfoRef sourceInfo
= CSSymbolicatorGetSourceInfoWithAddressAtTime(symbolicator,
(vm_address_t)addrlist[i],
0x80000000u /*"now"*/);
if (const char* sourcePath = CSSourceInfoGetPath(sourceInfo)) {
printf(" %s:%d", sourcePath, (int)CSSourceInfoGetLineNumber(sourceInfo));
} else {
printf(" (no debug info)");
}
printf("\n");
}
}
#endif // R__MACOSX
/// Print a stack trace.
void TUnixSystem::StackTrace()
{
if (!gEnv->GetValue("Root.Stacktrace", 1))
return;
#ifndef R__MACOSX
TString gdbscript = gEnv->GetValue("Root.StacktraceScript", "");
gdbscript = gdbscript.Strip();
if (gdbscript != "") {
if (AccessPathName(gdbscript, kReadPermission)) {
fprintf(stderr, "Root.StacktraceScript %s does not exist\n", gdbscript.Data());
gdbscript = "";
}
}
if (gdbscript == "") {
gdbscript = "gdb-backtrace.sh";
gSystem->PrependPathName(TROOT::GetEtcDir(), gdbscript);
if (AccessPathName(gdbscript, kReadPermission)) {
fprintf(stderr, "Error in <TUnixSystem::StackTrace> script %s is missing\n", gdbscript.Data());
return;
}
}
gdbscript += " ";
TString gdbmess = gEnv->GetValue("Root.StacktraceMessage", "");
gdbmess = gdbmess.Strip();
std::cout.flush();
fflush(stdout);
std::cerr.flush();
fflush(stderr);
int fd = STDERR_FILENO;
const char *message = " Generating stack trace...\n";
if (fd && message) { } // remove unused warning (remove later)
if (gApplication && !strcmp(gApplication->GetName(), "TRint"))
Getlinem(kCleanUp, 0);
#if defined(USE_GDB_STACK_TRACE)
char *gdb = Which(Getenv("PATH"), "gdb", kExecutePermission);
if (!gdb) {
fprintf(stderr, "gdb not found, need it for stack trace\n");
return;
}
// write custom message file
TString gdbmessf = "gdb-message";
if (gdbmess != "") {
FILE *f = TempFileName(gdbmessf);
fprintf(f, "%s\n", gdbmess.Data());
fclose(f);
}
// use gdb to get stack trace
gdbscript += GetExePath();
gdbscript += " ";
gdbscript += GetPid();
if (gdbmess != "") {
gdbscript += " ";
gdbscript += gdbmessf;
}
gdbscript += " 1>&2";
Exec(gdbscript);
delete [] gdb;
return;
#elif defined(R__AIX)
TString script = "procstack ";
script += GetPid();
Exec(script);
return;
#elif defined(R__SOLARIS)
char *cppfilt = Which(Getenv("PATH"), "c++filt", kExecutePermission);
TString script = "pstack ";
script += GetPid();
if (cppfilt) {
script += " | ";
script += cppfilt;
delete [] cppfilt;
}
Exec(script);
return;
#elif defined(HAVE_BACKTRACE_SYMBOLS_FD) && defined(HAVE_DLADDR) // linux + MacOS X >= 10.5
// we could have used backtrace_symbols_fd, except its output
// format is pretty bad, so recode that here :-(
// take care of demangling
Bool_t demangle = kTRUE;
// check for c++filt
const char *cppfilt = "c++filt";
const char *cppfiltarg = "";
#ifdef R__B64
const char *format1 = " 0x%016lx in %.200s %s 0x%lx from %.200s\n";
#ifdef R__MACOSX
const char *format2 = " 0x%016lx in %.200s\n";
#else
const char *format2 = " 0x%016lx in %.200s at %.200s from %.200s\n";
#endif
const char *format3 = " 0x%016lx in %.200s from %.200s\n";
const char *format4 = " 0x%016lx in <unknown function>\n";
#else
const char *format1 = " 0x%08lx in %.200s %s 0x%lx from %.200s\n";
#ifdef R__MACOSX
const char *format2 = " 0x%08lx in %.200s\n";
#else
const char *format2 = " 0x%08lx in %.200s at %.200s from %.200s\n";
#endif
const char *format3 = " 0x%08lx in %.200s from %.200s\n";
const char *format4 = " 0x%08lx in <unknown function>\n";
#endif
char *filter = Which(Getenv("PATH"), cppfilt, kExecutePermission);
if (!filter)
demangle = kFALSE;
#if (__GNUC__ >= 3)
// try finding supported format option for g++ v3
if (filter) {
FILE *p = OpenPipe(TString::Format("%s --help 2>&1", filter), "r");
TString help;
while (help.Gets(p)) {
if (help.Index("gnu-v3") != kNPOS) {
cppfiltarg = "--format=gnu-v3";
break;
} else if (help.Index("gnu-new-abi") != kNPOS) {
cppfiltarg = "--format=gnu-new-abi";
break;
}
}
ClosePipe(p);
}
#endif
// gdb-backtrace.sh uses gdb to produce a backtrace. See if it is available.
// If it is, use it. If not proceed as before.
#if (defined(R__LINUX) && !defined(R__WINGCC))
// Declare the process that will be generating the stacktrace
// For more see: http://askubuntu.com/questions/41629/after-upgrade-gdb-wont-attach-to-process
#ifdef PR_SET_PTRACER
prctl(PR_SET_PTRACER, getpid(), 0, 0, 0);
#endif
#endif
char *gdb = Which(Getenv("PATH"), "gdb", kExecutePermission);
if (gdb) {
// write custom message file
TString gdbmessf = "gdb-message";
if (gdbmess != "") {
FILE *f = TempFileName(gdbmessf);
fprintf(f, "%s\n", gdbmess.Data());
fclose(f);
}
// use gdb to get stack trace
#ifdef R__MACOSX
gdbscript += GetExePath();
gdbscript += " ";
#endif
gdbscript += GetPid();
if (gdbmess != "") {
gdbscript += " ";
gdbscript += gdbmessf;
}
gdbscript += " 1>&2";
Exec(gdbscript);
delete [] gdb;
} else {
// addr2line uses debug info to convert addresses into file names
// and line numbers
#ifdef R__MACOSX
char *addr2line = Which(Getenv("PATH"), "atos", kExecutePermission);
#else
char *addr2line = Which(Getenv("PATH"), "addr2line", kExecutePermission);
#endif
if (addr2line) {
// might take some time so tell what we are doing...
if (write(fd, message, strlen(message)) < 0)
Warning("StackTrace", "problems writing line numbers (errno: %d)", TSystem::GetErrno());
}
// open tmp file for demangled stack trace
TString tmpf1 = "gdb-backtrace";
std::ofstream file1;
if (demangle) {
FILE *f = TempFileName(tmpf1);
if (f) fclose(f);
file1.open(tmpf1);
if (!file1) {
Error("StackTrace", "could not open file %s", tmpf1.Data());
Unlink(tmpf1);
demangle = kFALSE;
}
}
#ifdef R__MACOSX
if (addr2line)
demangle = kFALSE; // atos always demangles
#endif
char buffer[4096];
void *trace[kMAX_BACKTRACE_DEPTH];
int depth = backtrace(trace, kMAX_BACKTRACE_DEPTH);
for (int n = 5; n < depth; n++) {
ULong_t addr = (ULong_t) trace[n];
Dl_info info;
if (dladdr(trace[n], &info) && info.dli_fname && info.dli_fname[0]) {
const char *libname = info.dli_fname;
const char *symname = (info.dli_sname && info.dli_sname[0]) ?
info.dli_sname : "<unknown>";
ULong_t libaddr = (ULong_t) info.dli_fbase;
ULong_t symaddr = (ULong_t) info.dli_saddr;
Bool_t gte = (addr >= symaddr);
ULong_t diff = (gte) ? addr - symaddr : symaddr - addr;
if (addr2line && symaddr) {
Bool_t nodebug = kTRUE;
#ifdef R__MACOSX
if (libaddr) { } // use libaddr
#if defined(MAC_OS_X_VERSION_10_10)
snprintf(buffer, sizeof(buffer), "%s -p %d 0x%016lx", addr2line, GetPid(), addr);
#elif defined(MAC_OS_X_VERSION_10_9)
// suppress deprecation warning with opti
snprintf(buffer, sizeof(buffer), "%s -d -p %d 0x%016lx", addr2line, GetPid(), addr);
#else
snprintf(buffer, sizeof(buffer), "%s -p %d 0x%016lx", addr2line, GetPid(), addr);
#endif
#else
ULong_t offset = (addr >= libaddr) ? addr - libaddr :
libaddr - addr;
TString name = TString(libname);
Bool_t noPath = kFALSE;
Bool_t noShare = kTRUE;
if (name[0] != '/') noPath = kTRUE;
if (name.Contains(".so") || name.Contains(".sl")) noShare = kFALSE;
if (noShare) offset = addr;
if (noPath) name = "`which " + name + "`";
snprintf(buffer, sizeof(buffer), "%s -e %s 0x%016lx", addr2line, name.Data(), offset);
#endif
if (FILE *pf = ::popen(buffer, "r")) {
char buf[2048];
if (fgets(buf, 2048, pf)) {
buf[strlen(buf)-1] = 0; // remove trailing \n
if (strncmp(buf, "??", 2)) {
#ifdef R__MACOSX
snprintf(buffer, sizeof(buffer), format2, addr, buf);
#else
snprintf(buffer, sizeof(buffer), format2, addr, symname, buf, libname);
#endif
nodebug = kFALSE;
}
}
::pclose(pf);
}
if (nodebug)
snprintf(buffer, sizeof(buffer), format1, addr, symname,
gte ? "+" : "-", diff, libname);
} else {
if (symaddr)
snprintf(buffer, sizeof(buffer), format1, addr, symname,
gte ? "+" : "-", diff, libname);
else
snprintf(buffer, sizeof(buffer), format3, addr, symname, libname);
}
} else {
snprintf(buffer, sizeof(buffer), format4, addr);
}
if (demangle)
file1 << buffer;
else
if (write(fd, buffer, ::strlen(buffer)) < 0)
Warning("StackTrace", "problems writing buffer (errno: %d)", TSystem::GetErrno());
}
if (demangle) {
TString tmpf2 = "gdb-backtrace";
FILE *f = TempFileName(tmpf2);
if (f) fclose(f);
file1.close();
snprintf(buffer, sizeof(buffer), "%s %s < %s > %s", filter, cppfiltarg, tmpf1.Data(), tmpf2.Data());
Exec(buffer);
std::ifstream file2(tmpf2);
TString line;
while (file2) {
line = "";
line.ReadString(file2);
if (write(fd, line.Data(), line.Length()) < 0)
Warning("StackTrace", "problems writing line (errno: %d)", TSystem::GetErrno());
}
file2.close();
Unlink(tmpf1);
Unlink(tmpf2);
}
delete [] addr2line;
}
delete [] filter;
#elif defined(HAVE_EXCPT_H) && defined(HAVE_PDSC_H) && \
defined(HAVE_RLD_INTERFACE_H) // tru64
// Tru64 stack walk. Uses the exception handling library and the
// run-time linker's core functions (loader(5)). FIXME: Tru64
// should have _RLD_DLADDR like IRIX below. Verify and update.
char buffer [128];
sigcontext context;
int rc = 0;
exc_capture_context (&context);
while (!rc && context.sc_pc) {
// FIXME: Elf32?
pdsc_crd *func, *base, *crd
= exc_remote_lookup_function_entry(0, 0, context.sc_pc, 0, &func, &base);
Elf32_Addr addr = PDSC_CRD_BEGIN_ADDRESS(base, func);
// const char *name = _rld_address_to_name(addr);
const char *name = "<unknown function>";
sprintf(buffer, " 0x%012lx %.200s + 0x%lx\n",
context.sc_pc, name, context.sc_pc - addr);
write(fd, buffer, ::strlen(buffer));
rc = exc_virtual_unwind(0, &context);
}
#endif
#else //R__MACOSX
macosx_backtrace();
#endif //R__MACOSX
}
//---- System Logging ----------------------------------------------------------
/// Open connection to system log daemon. For the use of the options and
/// facility see the Unix openlog man page.
void TUnixSystem::Openlog(const char *name, Int_t options, ELogFacility facility)
{
int fac = 0;
switch (facility) {
case kLogLocal0:
fac = LOG_LOCAL0;
break;
case kLogLocal1:
fac = LOG_LOCAL1;
break;
case kLogLocal2:
fac = LOG_LOCAL2;
break;
case kLogLocal3:
fac = LOG_LOCAL3;
break;
case kLogLocal4:
fac = LOG_LOCAL4;
break;
case kLogLocal5:
fac = LOG_LOCAL5;
break;
case kLogLocal6:
fac = LOG_LOCAL6;
break;
case kLogLocal7:
fac = LOG_LOCAL7;
break;
}
::openlog(name, options, fac);
}
/// Send mess to syslog daemon. Level is the logging level and mess the
/// message that will be written on the log.
void TUnixSystem::Syslog(ELogLevel level, const char *mess)
{
// ELogLevel matches exactly the Unix values.
::syslog(level, "%s", mess);
}
/// Close connection to system log daemon.
void TUnixSystem::Closelog()
{
::closelog();
}
//---- Standard output redirection ---------------------------------------------
/// Redirect standard output (stdout, stderr) to the specified file.
/// If the file argument is 0 the output is set again to stderr, stdout.
/// The second argument specifies whether the output should be added to the
/// file ("a", default) or the file be truncated before ("w").
/// This function saves internally the current state into a static structure.
/// The call can be made reentrant by specifying the opaque structure pointed
/// by 'h', which is filled with the relevant information. The handle 'h'
/// obtained on the first call must then be used in any subsequent call,
/// included ShowOutput, to display the redirected output.
/// Returns 0 on success, -1 in case of error.
Int_t TUnixSystem::RedirectOutput(const char *file, const char *mode,
RedirectHandle_t *h)
{
// Instance to be used if the caller does not passes 'h'
static RedirectHandle_t loch;
Int_t rc = 0;
// Which handle to use ?
RedirectHandle_t *xh = (h) ? h : &loch;
if (file) {
// Save the paths
Bool_t outdone = kFALSE;
if (xh->fStdOutTty.IsNull()) {
const char *tty = ttyname(STDOUT_FILENO);
if (tty) {
xh->fStdOutTty = tty;
} else {
if ((xh->fStdOutDup = dup(STDOUT_FILENO)) < 0) {
SysError("RedirectOutput", "could not 'dup' stdout (errno: %d)", TSystem::GetErrno());
return -1;
}
outdone = kTRUE;
}
}
if (xh->fStdErrTty.IsNull()) {
const char *tty = ttyname(STDERR_FILENO);
if (tty) {
xh->fStdErrTty = tty;
} else {
if ((xh->fStdErrDup = dup(STDERR_FILENO)) < 0) {
SysError("RedirectOutput", "could not 'dup' stderr (errno: %d)", TSystem::GetErrno());
if (outdone && dup2(xh->fStdOutDup, STDOUT_FILENO) < 0) {
Warning("RedirectOutput", "could not restore stdout (back to original redirected"
" file) (errno: %d)", TSystem::GetErrno());
}
return -1;
}
}
}
// Make sure mode makes sense; default "a"
const char *m = (mode[0] == 'a' || mode[0] == 'w') ? mode : "a";
// Current file size
xh->fReadOffSet = 0;
if (m[0] == 'a') {
// If the file exists, save the current size
FileStat_t st;
if (!gSystem->GetPathInfo(file, st))
xh->fReadOffSet = (st.fSize > 0) ? st.fSize : xh->fReadOffSet;
}
xh->fFile = file;
// Redirect stdout & stderr
if (freopen(file, m, stdout) == 0) {
SysError("RedirectOutput", "could not freopen stdout (errno: %d)", TSystem::GetErrno());
return -1;
}
if (freopen(file, m, stderr) == 0) {
SysError("RedirectOutput", "could not freopen stderr (errno: %d)", TSystem::GetErrno());
if (freopen(xh->fStdOutTty.Data(), "a", stdout) == 0)
SysError("RedirectOutput", "could not restore stdout (errno: %d)", TSystem::GetErrno());
return -1;
}
} else {
// Restore stdout & stderr
fflush(stdout);
if (!(xh->fStdOutTty.IsNull())) {
if (freopen(xh->fStdOutTty.Data(), "a", stdout) == 0) {
SysError("RedirectOutput", "could not restore stdout (errno: %d)", TSystem::GetErrno());
rc = -1;
}
xh->fStdOutTty = "";
} else {
if (close(STDOUT_FILENO) != 0) {
SysError("RedirectOutput",
"problems closing STDOUT_FILENO (%d) before 'dup2' (errno: %d)",
STDOUT_FILENO, TSystem::GetErrno());
rc = -1;
}
if (dup2(xh->fStdOutDup, STDOUT_FILENO) < 0) {
SysError("RedirectOutput", "could not restore stdout (back to original redirected"
" file) (errno: %d)", TSystem::GetErrno());
rc = -1;
}
if (close(xh->fStdOutDup) != 0) {
SysError("RedirectOutput",
"problems closing temporary 'out' descriptor %d (errno: %d)",
TSystem::GetErrno(), xh->fStdOutDup);
rc = -1;
}
}
fflush(stderr);
if (!(xh->fStdErrTty.IsNull())) {
if (freopen(xh->fStdErrTty.Data(), "a", stderr) == 0) {
SysError("RedirectOutput", "could not restore stderr (errno: %d)", TSystem::GetErrno());
rc = -1;
}
xh->fStdErrTty = "";
} else {
if (close(STDERR_FILENO) != 0) {
SysError("RedirectOutput",
"problems closing STDERR_FILENO (%d) before 'dup2' (errno: %d)",
STDERR_FILENO, TSystem::GetErrno());
rc = -1;
}
if (dup2(xh->fStdErrDup, STDERR_FILENO) < 0) {
SysError("RedirectOutput", "could not restore stderr (back to original redirected"
" file) (errno: %d)", TSystem::GetErrno());
rc = -1;
}
if (close(xh->fStdErrDup) != 0) {
SysError("RedirectOutput",
"problems closing temporary 'err' descriptor %d (errno: %d)",
TSystem::GetErrno(), xh->fStdErrDup);
rc = -1;
}
}
// Reset the static instance, if using that
if (xh == &loch)
xh->Reset();
}
return rc;
}
//---- dynamic loading and linking ---------------------------------------------
///dynamic linking of module
Func_t TUnixSystem::DynFindSymbol(const char * /*module*/, const char *entry)
{
return TSystem::DynFindSymbol("*", entry);
}
/// Load a shared library. Returns 0 on successful loading, 1 in
/// case lib was already loaded and -1 in case lib does not exist
/// or in case of error.
int TUnixSystem::Load(const char *module, const char *entry, Bool_t system)
{
return TSystem::Load(module, entry, system);
}
/// Unload a shared library.
void TUnixSystem::Unload(const char *module)
{
if (module) { TSystem::Unload(module); }
}
/// List symbols in a shared library.
void TUnixSystem::ListSymbols(const char * /*module*/, const char * /*regexp*/)
{
Error("ListSymbols", "not yet implemented");
}
/// List all loaded shared libraries.
void TUnixSystem::ListLibraries(const char *regexp)
{
TSystem::ListLibraries(regexp);
}
/// Get list of shared libraries loaded at the start of the executable.
/// Returns 0 in case list cannot be obtained or in case of error.
const char *TUnixSystem::GetLinkedLibraries()
{
static TString linkedLibs;
static Bool_t once = kFALSE;
R__LOCKGUARD2(gSystemMutex);
if (!linkedLibs.IsNull())
return linkedLibs;
if (once)
return nullptr;
#if !defined(R__MACOSX)
const char *exe = GetExePath();
if (!exe || !*exe)
return nullptr;
#endif
#if defined(R__MACOSX)
DylibAdded(0, 0);
linkedLibs = gLinkedDylibs;
#if 0
FILE *p = OpenPipe(TString::Format("otool -L %s", exe), "r");
TString otool;
while (otool.Gets(p)) {
TString delim(" \t");
TObjArray *tok = otool.Tokenize(delim);
TString dylib = ((TObjString*)tok->At(0))->String();
if (dylib.EndsWith(".dylib") && !dylib.Contains("/libSystem.B.dylib")) {
if (!linkedLibs.IsNull())
linkedLibs += " ";
linkedLibs += dylib;
}
delete tok;
}
if (p) {
ClosePipe(p);
}
#endif
#elif defined(R__LINUX) || defined(R__SOLARIS) || defined(R__AIX)
#if defined(R__WINGCC )
const char *cLDD="cygcheck";
const char *cSOEXT=".dll";
size_t lenexe = strlen(exe);
if (strcmp(exe + lenexe - 4, ".exe")
&& strcmp(exe + lenexe - 4, ".dll")) {
// it's not a dll and exe doesn't end on ".exe";
// need to add it for cygcheck to find it:
char* longerexe = new char[lenexe + 5];
strlcpy(longerexe, exe,lenexe+5);
strlcat(longerexe, ".exe",lenexe+5);
exe = longerexe; // memory leak
#error "unsupported platform, fix memory leak to use it"
}
TRegexp sovers = "\\.so\\.[0-9]+";
#else
const char *cLDD="ldd";
#if defined(R__AIX)
const char *cSOEXT=".a";
TRegexp sovers = "\\.a\\.[0-9]+";
#else
const char *cSOEXT=".so";
TRegexp sovers = "\\.so\\.[0-9]+";
#endif
#endif
FILE *p = OpenPipe(TString::Format("%s '%s'", cLDD, exe), "r");
if (p) {
TString ldd;
while (ldd.Gets(p)) {
TString delim(" \t");
TObjArray *tok = ldd.Tokenize(delim);
// expected format:
// libCore.so => /home/rdm/root/lib/libCore.so (0x40017000)
TObjString *solibName = (TObjString*)tok->At(2);
if (!solibName) {
// case where there is only one name of the list:
// /usr/platform/SUNW,UltraAX-i2/lib/libc_psr.so.1
solibName = (TObjString*)tok->At(0);
}
if (solibName) {
TString solib = solibName->String();
Ssiz_t idx = solib.Index(sovers);
if (solib.EndsWith(cSOEXT) || idx != kNPOS) {
if (idx != kNPOS)
solib.Remove(idx+3);
if (!AccessPathName(solib, kReadPermission)) {
if (!linkedLibs.IsNull())
linkedLibs += " ";
linkedLibs += solib;
}
}
}
delete tok;
}
ClosePipe(p);
}
#endif
once = kTRUE;
if (linkedLibs.IsNull())
return nullptr;
return linkedLibs;
}
//---- Time & Date -------------------------------------------------------------
/// Get current time in milliseconds since 0:00 Jan 1 1995.
TTime TUnixSystem::Now()
{
return UnixNow();
}
/// Handle and dispatch timers. If mode = kTRUE dispatch synchronous
/// timers else a-synchronous timers.
Bool_t TUnixSystem::DispatchTimers(Bool_t mode)
{
if (!fTimers) return kFALSE;
fInsideNotify = kTRUE;
TOrdCollectionIter it((TOrdCollection*)fTimers);
TTimer *t;
Bool_t timedout = kFALSE;
while ((t = (TTimer *) it.Next())) {
// NB: the timer resolution is added in TTimer::CheckTimer()
Long64_t now = UnixNow();
if (mode && t->IsSync()) {
if (t->CheckTimer(now))
timedout = kTRUE;
} else if (!mode && t->IsAsync()) {
if (t->CheckTimer(now)) {
UnixSetitimer(NextTimeOut(kFALSE));
timedout = kTRUE;
}
}
}
fInsideNotify = kFALSE;
return timedout;
}
/// Add timer to list of system timers.
void TUnixSystem::AddTimer(TTimer *ti)
{
TSystem::AddTimer(ti);
ResetTimer(ti);
}
/// Remove timer from list of system timers.
TTimer *TUnixSystem::RemoveTimer(TTimer *ti)
{
if (!ti) return nullptr;
R__LOCKGUARD2(gSystemMutex);
TTimer *t = TSystem::RemoveTimer(ti);
if (ti->IsAsync())
UnixSetitimer(NextTimeOut(kFALSE));
return t;
}
/// Reset a-sync timer.
void TUnixSystem::ResetTimer(TTimer *ti)
{
if (!fInsideNotify && ti && ti->IsAsync())
UnixSetitimer(NextTimeOut(kFALSE));
}
//---- RPC ---------------------------------------------------------------------
/// Get Internet Protocol (IP) address of host. Returns an TInetAddress
/// object. To see if the hostname lookup was successfull call
/// TInetAddress::IsValid().
TInetAddress TUnixSystem::GetHostByName(const char *hostname)
{
TInetAddress ia;
struct addrinfo hints;
struct addrinfo *result, *rp;
memset(&hints, 0, sizeof(struct addrinfo));
hints.ai_family = AF_INET; // only IPv4
hints.ai_socktype = 0; // any socket type
hints.ai_protocol = 0; // any protocol
hints.ai_flags = AI_CANONNAME; // get canonical name
#ifdef R__MACOSX
// Anything ending on ".local" causes a 5 second delay in getaddrinfo().
// See e.g. https://apple.stackexchange.com/questions/175320/why-is-my-hostname-resolution-taking-so-long
// Only reasonable solution: remove the "domain" part if it's ".local".
size_t lenHostname = strlen(hostname);
std::string hostnameWithoutLocal{hostname};
if (lenHostname > 6 && !strcmp(hostname + lenHostname - 6, ".local")) {
hostnameWithoutLocal.erase(lenHostname - 6);
hostname = hostnameWithoutLocal.c_str();
}
#endif
// obsolete gethostbyname() replaced by getaddrinfo()
int rc = getaddrinfo(hostname, nullptr, &hints, &result);
if (rc != 0) {
if (rc == EAI_NONAME) {
if (gDebug > 0) Error("GetHostByName", "unknown host '%s'", hostname);
ia.fHostname = "UnNamedHost";
} else {
Error("GetHostByName", "getaddrinfo failed for '%s': %s", hostname, gai_strerror(rc));
ia.fHostname = "UnknownHost";
}
return ia;
}
std::string hostcanon(result->ai_canonname ? result->ai_canonname : hostname);
ia.fHostname = hostcanon.data();
ia.fFamily = result->ai_family;
ia.fAddresses[0] = ntohl(((struct sockaddr_in *)(result->ai_addr))->sin_addr.s_addr);
// with getaddrinfo() no way to get list of aliases for a hostname
if (hostcanon.compare(hostname) != 0) ia.AddAlias(hostname);
// check on numeric hostname
char tmp[sizeof(struct in_addr)];
if (inet_pton(AF_INET, hostcanon.data(), tmp) == 1) {
char hbuf[NI_MAXHOST];
if (getnameinfo(result->ai_addr, result->ai_addrlen, hbuf, sizeof(hbuf), nullptr, 0, 0) == 0)
ia.fHostname = hbuf;
}
// check other addresses (if exist)
rp = result->ai_next;
for (; rp != nullptr; rp = rp->ai_next) {
UInt_t arp = ntohl(((struct sockaddr_in *)(rp->ai_addr))->sin_addr.s_addr);
if ( !(std::find(ia.fAddresses.begin(), ia.fAddresses.end(), arp) != ia.fAddresses.end()) )
ia.AddAddress(arp);
}
freeaddrinfo(result);
return ia;
}
/// Get Internet Protocol (IP) address of host and port #.
TInetAddress TUnixSystem::GetSockName(int sock)
{
struct sockaddr addr;
#if defined(USE_SIZE_T)
size_t len = sizeof(addr);
#elif defined(USE_SOCKLEN_T)
socklen_t len = sizeof(addr);
#else
int len = sizeof(addr);
#endif
TInetAddress ia;
if (getsockname(sock, &addr, &len) == -1) {
SysError("GetSockName", "getsockname failed");
return ia;
}
if (addr.sa_family != AF_INET) return ia; // only IPv4
ia.fFamily = addr.sa_family;
struct sockaddr_in *addrin = (struct sockaddr_in *)&addr;
ia.fPort = ntohs(addrin->sin_port);
ia.fAddresses[0] = ntohl(addrin->sin_addr.s_addr);
char hbuf[NI_MAXHOST];
if (getnameinfo(&addr, sizeof(struct sockaddr), hbuf, sizeof(hbuf), nullptr, 0, 0) != 0) {
Error("GetSockName", "getnameinfo failed");
ia.fHostname = "????";
} else
ia.fHostname = hbuf;
return ia;
}
/// Get Internet Protocol (IP) address of remote host and port #.
TInetAddress TUnixSystem::GetPeerName(int sock)
{
struct sockaddr addr;
#if defined(USE_SIZE_T)
size_t len = sizeof(addr);
#elif defined(USE_SOCKLEN_T)
socklen_t len = sizeof(addr);
#else
int len = sizeof(addr);
#endif
TInetAddress ia;
if (getpeername(sock, &addr, &len) == -1) {
SysError("GetPeerName", "getpeername failed");
return ia;
}
if (addr.sa_family != AF_INET) return ia; // only IPv4
ia.fFamily = addr.sa_family;
struct sockaddr_in *addrin = (struct sockaddr_in *)&addr;
ia.fPort = ntohs(addrin->sin_port);
ia.fAddresses[0] = ntohl(addrin->sin_addr.s_addr);
char hbuf[NI_MAXHOST];
if (getnameinfo(&addr, sizeof(struct sockaddr), hbuf, sizeof(hbuf), nullptr, 0, 0) != 0) {
Error("GetPeerName", "getnameinfo failed");
ia.fHostname = "????";
} else
ia.fHostname = hbuf;
return ia;
}
/// Get port # of internet service.
int TUnixSystem::GetServiceByName(const char *servicename)
{
struct servent *sp;
if ((sp = getservbyname(servicename, kProtocolName)) == 0) {
Error("GetServiceByName", "no service \"%s\" with protocol \"%s\"\n",
servicename, kProtocolName);
return -1;
}
return ntohs(sp->s_port);
}
/// Get name of internet service.
char *TUnixSystem::GetServiceByPort(int port)
{
struct servent *sp;
if ((sp = getservbyport(htons(port), kProtocolName)) == 0) {
//::Error("GetServiceByPort", "no service \"%d\" with protocol \"%s\"",
// port, kProtocolName);
return Form("%d", port);
}
return sp->s_name;
}
/// Connect to service servicename on server servername.
int TUnixSystem::ConnectService(const char *servername, int port,
int tcpwindowsize, const char *protocol)
{
if (!strcmp(servername, "unix")) {
return UnixUnixConnect(port);
} else if (!gSystem->AccessPathName(servername) || servername[0] == '/') {
return UnixUnixConnect(servername);
}
if (!strcmp(protocol, "udp")){
return UnixUdpConnect(servername, port);
}
return UnixTcpConnect(servername, port, tcpwindowsize);
}
/// Open a connection to a service on a server. Returns -1 in case
/// connection cannot be opened.
/// Use tcpwindowsize to specify the size of the receive buffer, it has
/// to be specified here to make sure the window scale option is set (for
/// tcpwindowsize > 65KB and for platforms supporting window scaling).
/// Is called via the TSocket constructor.
int TUnixSystem::OpenConnection(const char *server, int port, int tcpwindowsize, const char *protocol)
{
return ConnectService(server, port, tcpwindowsize, protocol);
}
/// Announce TCP/IP service.
/// Open a socket, bind to it and start listening for TCP/IP connections
/// on the port. If reuse is true reuse the address, backlog specifies
/// how many sockets can be waiting to be accepted.
/// Use tcpwindowsize to specify the size of the receive buffer, it has
/// to be specified here to make sure the window scale option is set (for
/// tcpwindowsize > 65KB and for platforms supporting window scaling).
/// Returns socket fd or -1 if socket() failed, -2 if bind() failed
/// or -3 if listen() failed.
int TUnixSystem::AnnounceTcpService(int port, Bool_t reuse, int backlog,
int tcpwindowsize)
{
return UnixTcpService(port, reuse, backlog, tcpwindowsize);
}
/// Announce UDP service.
int TUnixSystem::AnnounceUdpService(int port, int backlog)
{
return UnixUdpService(port, backlog);
}
/// Announce unix domain service on path "kServerPath/<port>"
int TUnixSystem::AnnounceUnixService(int port, int backlog)
{
return UnixUnixService(port, backlog);
}
/// Announce unix domain service on path 'sockpath'
int TUnixSystem::AnnounceUnixService(const char *sockpath, int backlog)
{
return UnixUnixService(sockpath, backlog);
}
/// Accept a connection. In case of an error return -1. In case
/// non-blocking I/O is enabled and no connections are available
/// return -2.
int TUnixSystem::AcceptConnection(int sock)
{
int soc = -1;
while ((soc = ::accept(sock, 0, 0)) == -1 && GetErrno() == EINTR)
ResetErrno();
if (soc == -1) {
if (GetErrno() == EWOULDBLOCK)
return -2;
else {
SysError("AcceptConnection", "accept");
return -1;
}
}
return soc;
}
/// Close socket.
void TUnixSystem::CloseConnection(int sock, Bool_t force)
{
if (sock < 0) return;
#if !defined(R__AIX) || defined(_AIX41) || defined(_AIX43)
if (force)
::shutdown(sock, 2); // will also close connection of parent
#endif
while (::close(sock) == -1 && GetErrno() == EINTR)
ResetErrno();
}
/// Receive a buffer headed by a length indicator. Length is the size of
/// the buffer. Returns the number of bytes received in buf or -1 in
/// case of error.
int TUnixSystem::RecvBuf(int sock, void *buf, int length)
{
Int_t header;
if (UnixRecv(sock, &header, sizeof(header), 0) > 0) {
int count = ntohl(header);
if (count > length) {
Error("RecvBuf", "record header exceeds buffer size");
return -1;
} else if (count > 0) {
if (UnixRecv(sock, buf, count, 0) < 0) {
Error("RecvBuf", "cannot receive buffer");
return -1;
}
}
return count;
}
return -1;
}
/// Send a buffer headed by a length indicator. Returns length of sent buffer
/// or -1 in case of error.
int TUnixSystem::SendBuf(int sock, const void *buf, int length)
{
Int_t header = htonl(length);
if (UnixSend(sock, &header, sizeof(header), 0) < 0) {
Error("SendBuf", "cannot send header");
return -1;
}
if (length > 0) {
if (UnixSend(sock, buf, length, 0) < 0) {
Error("SendBuf", "cannot send buffer");
return -1;
}
}
return length;
}
/// Receive exactly length bytes into buffer. Use opt to receive out-of-band
/// data or to have a peek at what is in the buffer (see TSocket). Buffer
/// must be able to store at least length bytes. Returns the number of
/// bytes received (can be 0 if other side of connection was closed) or -1
/// in case of error, -2 in case of MSG_OOB and errno == EWOULDBLOCK, -3
/// in case of MSG_OOB and errno == EINVAL and -4 in case of kNoBlock and
/// errno == EWOULDBLOCK. Returns -5 if pipe broken or reset by peer
/// (EPIPE || ECONNRESET).
int TUnixSystem::RecvRaw(int sock, void *buf, int length, int opt)
{
int flag;
switch (opt) {
case kDefault:
flag = 0;
break;
case kOob:
flag = MSG_OOB;
break;
case kPeek:
flag = MSG_PEEK;
break;
case kDontBlock:
flag = -1;
break;
default:
flag = 0;
break;
}
int n;
if ((n = UnixRecv(sock, buf, length, flag)) <= 0) {
if (n == -1 && GetErrno() != EINTR)
Error("RecvRaw", "cannot receive buffer");
return n;
}
return n;
}
/// Send exactly length bytes from buffer. Use opt to send out-of-band
/// data (see TSocket). Returns the number of bytes sent or -1 in case of
/// error. Returns -4 in case of kNoBlock and errno == EWOULDBLOCK.
/// Returns -5 if pipe broken or reset by peer (EPIPE || ECONNRESET).
int TUnixSystem::SendRaw(int sock, const void *buf, int length, int opt)
{
int flag;
switch (opt) {
case kDefault:
flag = 0;
break;
case kOob:
flag = MSG_OOB;
break;
case kDontBlock:
flag = -1;
break;
case kPeek: // receive only option (see RecvRaw)
default:
flag = 0;
break;
}
int n;
if ((n = UnixSend(sock, buf, length, flag)) <= 0) {
if (n == -1 && GetErrno() != EINTR)
Error("SendRaw", "cannot send buffer");
return n;
}
return n;
}
/// Set socket option.
int TUnixSystem::SetSockOpt(int sock, int opt, int val)
{
if (sock < 0) return -1;
switch (opt) {
case kSendBuffer:
if (setsockopt(sock, SOL_SOCKET, SO_SNDBUF, (char*)&val, sizeof(val)) == -1) {
SysError("SetSockOpt", "setsockopt(SO_SNDBUF)");
return -1;
}
break;
case kRecvBuffer:
if (setsockopt(sock, SOL_SOCKET, SO_RCVBUF, (char*)&val, sizeof(val)) == -1) {
SysError("SetSockOpt", "setsockopt(SO_RCVBUF)");
return -1;
}
break;
case kOobInline:
if (setsockopt(sock, SOL_SOCKET, SO_OOBINLINE, (char*)&val, sizeof(val)) == -1) {
SysError("SetSockOpt", "setsockopt(SO_OOBINLINE)");
return -1;
}
break;
case kKeepAlive:
if (setsockopt(sock, SOL_SOCKET, SO_KEEPALIVE, (char*)&val, sizeof(val)) == -1) {
SysError("SetSockOpt", "setsockopt(SO_KEEPALIVE)");
return -1;
}
break;
case kReuseAddr:
if (setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, (char*)&val, sizeof(val)) == -1) {
SysError("SetSockOpt", "setsockopt(SO_REUSEADDR)");
return -1;
}
break;
case kNoDelay:
if (setsockopt(sock, IPPROTO_TCP, TCP_NODELAY, (char*)&val, sizeof(val)) == -1) {
SysError("SetSockOpt", "setsockopt(TCP_NODELAY)");
return -1;
}
break;
case kNoBlock:
if (ioctl(sock, FIONBIO, (char*)&val) == -1) {
SysError("SetSockOpt", "ioctl(FIONBIO)");
return -1;
}
break;
case kProcessGroup:
#ifndef R__WINGCC
if (ioctl(sock, SIOCSPGRP, (char*)&val) == -1) {
SysError("SetSockOpt", "ioctl(SIOCSPGRP)");
return -1;
}
#else
Error("SetSockOpt", "ioctl(SIOCGPGRP) not supported on cygwin/gcc");
return -1;
#endif
break;
case kAtMark: // read-only option (see GetSockOpt)
case kBytesToRead: // read-only option
default:
Error("SetSockOpt", "illegal option (%d)", opt);
return -1;
}
return 0;
}
/// Get socket option.
int TUnixSystem::GetSockOpt(int sock, int opt, int *val)
{
if (sock < 0) return -1;
#if defined(USE_SOCKLEN_T) || defined(_AIX43)
socklen_t optlen = sizeof(*val);
#elif defined(USE_SIZE_T)
size_t optlen = sizeof(*val);
#else
int optlen = sizeof(*val);
#endif
switch (opt) {
case kSendBuffer:
if (getsockopt(sock, SOL_SOCKET, SO_SNDBUF, (char*)val, &optlen) == -1) {
SysError("GetSockOpt", "getsockopt(SO_SNDBUF)");
return -1;
}
break;
case kRecvBuffer:
if (getsockopt(sock, SOL_SOCKET, SO_RCVBUF, (char*)val, &optlen) == -1) {
SysError("GetSockOpt", "getsockopt(SO_RCVBUF)");
return -1;
}
break;
case kOobInline:
if (getsockopt(sock, SOL_SOCKET, SO_OOBINLINE, (char*)val, &optlen) == -1) {
SysError("GetSockOpt", "getsockopt(SO_OOBINLINE)");
return -1;
}
break;
case kKeepAlive:
if (getsockopt(sock, SOL_SOCKET, SO_KEEPALIVE, (char*)val, &optlen) == -1) {
SysError("GetSockOpt", "getsockopt(SO_KEEPALIVE)");
return -1;
}
break;
case kReuseAddr:
if (getsockopt(sock, SOL_SOCKET, SO_REUSEADDR, (char*)val, &optlen) == -1) {
SysError("GetSockOpt", "getsockopt(SO_REUSEADDR)");
return -1;
}
break;
case kNoDelay:
if (getsockopt(sock, IPPROTO_TCP, TCP_NODELAY, (char*)val, &optlen) == -1) {
SysError("GetSockOpt", "getsockopt(TCP_NODELAY)");
return -1;
}
break;
case kNoBlock:
int flg;
if ((flg = fcntl(sock, F_GETFL, 0)) == -1) {
SysError("GetSockOpt", "fcntl(F_GETFL)");
return -1;
}
*val = flg & O_NDELAY;
break;
case kProcessGroup:
#if !defined(R__LYNXOS) && !defined(R__WINGCC)
if (ioctl(sock, SIOCGPGRP, (char*)val) == -1) {
SysError("GetSockOpt", "ioctl(SIOCGPGRP)");
return -1;
}
#else
Error("GetSockOpt", "ioctl(SIOCGPGRP) not supported on LynxOS and cygwin/gcc");
return -1;
#endif
break;
case kAtMark:
#if !defined(R__LYNXOS)
if (ioctl(sock, SIOCATMARK, (char*)val) == -1) {
SysError("GetSockOpt", "ioctl(SIOCATMARK)");
return -1;
}
#else
Error("GetSockOpt", "ioctl(SIOCATMARK) not supported on LynxOS");
return -1;
#endif
break;
case kBytesToRead:
#if !defined(R__LYNXOS)
if (ioctl(sock, FIONREAD, (char*)val) == -1) {
SysError("GetSockOpt", "ioctl(FIONREAD)");
return -1;
}
#else
Error("GetSockOpt", "ioctl(FIONREAD) not supported on LynxOS");
return -1;
#endif
break;
default:
Error("GetSockOpt", "illegal option (%d)", opt);
*val = 0;
return -1;
}
return 0;
}
// //
// Static Protected Unix Interface functions. //
// //
//---- signals -----------------------------------------------------------------
static struct Signalmap_t {
int fCode;
SigHandler_t fHandler;
struct sigaction *fOldHandler;
const char *fSigName;
} gSignalMap[kMAXSIGNALS] = { // the order of the signals should be identical
{ SIGBUS, 0, 0, "bus error" }, // to the one in TSysEvtHandler.h
{ SIGSEGV, 0, 0, "segmentation violation" },
{ SIGSYS, 0, 0, "bad argument to system call" },
{ SIGPIPE, 0, 0, "write on a pipe with no one to read it" },
{ SIGILL, 0, 0, "illegal instruction" },
{ SIGABRT, 0, 0, "abort" },
{ SIGQUIT, 0, 0, "quit" },
{ SIGINT, 0, 0, "interrupt" },
{ SIGWINCH, 0, 0, "window size change" },
{ SIGALRM, 0, 0, "alarm clock" },
{ SIGCHLD, 0, 0, "death of a child" },
{ SIGURG, 0, 0, "urgent data arrived on an I/O channel" },
{ SIGFPE, 0, 0, "floating point exception" },
{ SIGTERM, 0, 0, "termination signal" },
{ SIGUSR1, 0, 0, "user-defined signal 1" },
{ SIGUSR2, 0, 0, "user-defined signal 2" }
};
/// Call the signal handler associated with the signal.
static void sighandler(int sig)
{
for (int i= 0; i < kMAXSIGNALS; i++) {
if (gSignalMap[i].fCode == sig) {
(*gSignalMap[i].fHandler)((ESignals)i);
return;
}
}
}
/// Handle and dispatch signals.
void TUnixSystem::DispatchSignals(ESignals sig)
{
switch (sig) {
case kSigAlarm:
DispatchTimers(kFALSE);
break;
case kSigChild:
CheckChilds();
break;
case kSigBus:
case kSigSegmentationViolation:
case kSigIllegalInstruction:
case kSigAbort:
case kSigFloatingException:
if (gExceptionHandler)
gExceptionHandler->HandleException(sig);
else {
if (sig == kSigAbort)
return;
Break("TUnixSystem::DispatchSignals", "%s", UnixSigname(sig));
StackTrace();
if (gApplication)
//sig is ESignal, should it be mapped to the correct signal number?
gApplication->HandleException(sig);
else
//map to the real signal code + set the
//high order bit to indicate a signal (?)
Exit(gSignalMap[sig].fCode + 0x80);
}
break;
case kSigSystem:
case kSigPipe:
Break("TUnixSystem::DispatchSignals", "%s", UnixSigname(sig));
break;
case kSigWindowChanged:
Gl_windowchanged();
break;
case kSigUser2:
Break("TUnixSystem::DispatchSignals", "%s: printing stacktrace", UnixSigname(sig));
StackTrace();
// Intentional fall-through; pass the signal to handlers (or terminate):
default:
fSignals->Set(sig);
fSigcnt++;
break;
}
// check a-synchronous signals
if (fSigcnt > 0 && fSignalHandler->GetSize() > 0)
CheckSignals(kFALSE);
}
/// Set a signal handler for a signal.
void TUnixSystem::UnixSignal(ESignals sig, SigHandler_t handler)
{
if (gEnv && !gEnv->GetValue("Root.ErrorHandlers", 1))
return;
if (gSignalMap[sig].fHandler != handler) {
struct sigaction sigact;
gSignalMap[sig].fHandler = handler;
gSignalMap[sig].fOldHandler = new struct sigaction();
#if defined(R__SUN)
sigact.sa_handler = (void (*)())sighandler;
#elif defined(R__SOLARIS)
sigact.sa_handler = sighandler;
#elif defined(R__LYNXOS)
# if (__GNUG__>=3)
sigact.sa_handler = sighandler;
# else
sigact.sa_handler = (void (*)(...))sighandler;
# endif
#else
sigact.sa_handler = sighandler;
#endif
sigemptyset(&sigact.sa_mask);
sigact.sa_flags = 0;
#if defined(SA_RESTART)
sigact.sa_flags |= SA_RESTART;
#endif
if (sigaction(gSignalMap[sig].fCode, &sigact,
gSignalMap[sig].fOldHandler) < 0)
::SysError("TUnixSystem::UnixSignal", "sigaction");
}
}
/// If ignore is true ignore the specified signal, else restore previous
/// behaviour.
void TUnixSystem::UnixIgnoreSignal(ESignals sig, Bool_t ignore)
{
TTHREAD_TLS(Bool_t) ignoreSig[kMAXSIGNALS] = { kFALSE };
TTHREAD_TLS_ARRAY(struct sigaction,kMAXSIGNALS,oldsigact);
if (ignore != ignoreSig[sig]) {
ignoreSig[sig] = ignore;
if (ignore) {
struct sigaction sigact;
#if defined(R__SUN)
sigact.sa_handler = (void (*)())SIG_IGN;
#elif defined(R__SOLARIS)
sigact.sa_handler = (void (*)(int))SIG_IGN;
#else
sigact.sa_handler = SIG_IGN;
#endif
sigemptyset(&sigact.sa_mask);
sigact.sa_flags = 0;
if (sigaction(gSignalMap[sig].fCode, &sigact, &oldsigact[sig]) < 0)
::SysError("TUnixSystem::UnixIgnoreSignal", "sigaction");
} else {
if (sigaction(gSignalMap[sig].fCode, &oldsigact[sig], 0) < 0)
::SysError("TUnixSystem::UnixIgnoreSignal", "sigaction");
}
}
}
/// When the argument is true the SIGALRM signal handler is set so that
/// interrupted syscalls will not be restarted by the kernel. This is
/// typically used in case one wants to put a timeout on an I/O operation.
/// By default interrupted syscalls will always be restarted (for all
/// signals). This can be controlled for each a-synchronous TTimer via
/// the method TTimer::SetInterruptSyscalls().
void TUnixSystem::UnixSigAlarmInterruptsSyscalls(Bool_t set)
{
if (gSignalMap[kSigAlarm].fHandler) {
struct sigaction sigact;
#if defined(R__SUN)
sigact.sa_handler = (void (*)())sighandler;
#elif defined(R__SOLARIS)
sigact.sa_handler = sighandler;
#elif defined(R__LYNXOS)
# if (__GNUG__>=3)
sigact.sa_handler = sighandler;
# else
sigact.sa_handler = (void (*)(...))sighandler;
# endif
#else
sigact.sa_handler = sighandler;
#endif
sigemptyset(&sigact.sa_mask);
sigact.sa_flags = 0;
if (set) {
#if defined(SA_INTERRUPT) // SunOS
sigact.sa_flags |= SA_INTERRUPT;
#endif
} else {
#if defined(SA_RESTART)
sigact.sa_flags |= SA_RESTART;
#endif
}
if (sigaction(gSignalMap[kSigAlarm].fCode, &sigact, 0) < 0)
::SysError("TUnixSystem::UnixSigAlarmInterruptsSyscalls", "sigaction");
}
}
/// Return the signal name associated with a signal.
const char *TUnixSystem::UnixSigname(ESignals sig)
{
return gSignalMap[sig].fSigName;
}
/// Restore old signal handler for specified signal.
void TUnixSystem::UnixResetSignal(ESignals sig)
{
if (gSignalMap[sig].fOldHandler) {
// restore old signal handler
if (sigaction(gSignalMap[sig].fCode, gSignalMap[sig].fOldHandler, 0) < 0)
::SysError("TUnixSystem::UnixSignal", "sigaction");
delete gSignalMap[sig].fOldHandler;
gSignalMap[sig].fOldHandler = 0;
gSignalMap[sig].fHandler = 0;
}
}
/// Restore old signal handlers.
void TUnixSystem::UnixResetSignals()
{
for (int sig = 0; sig < kMAXSIGNALS; sig++)
UnixResetSignal((ESignals)sig);
}
//---- time --------------------------------------------------------------------
/// Get current time in milliseconds since 0:00 Jan 1 1995.
Long64_t TUnixSystem::UnixNow()
{
static std::atomic<time_t> jan95{0};
if (!jan95) {
struct tm tp;
tp.tm_year = 95;
tp.tm_mon = 0;
tp.tm_mday = 1;
tp.tm_hour = 0;
tp.tm_min = 0;
tp.tm_sec = 0;
tp.tm_isdst = -1;
jan95 = mktime(&tp);
if ((int)jan95 == -1) {
::SysError("TUnixSystem::UnixNow", "error converting 950001 0:00 to time_t");
return 0;
}
}
struct timeval t;
gettimeofday(&t, 0);
return Long64_t(t.tv_sec-(Long_t)jan95)*1000 + t.tv_usec/1000;
}
/// Set interval timer to time-out in ms milliseconds.
int TUnixSystem::UnixSetitimer(Long_t ms)
{
struct itimerval itv;
itv.it_value.tv_sec = 0;
itv.it_value.tv_usec = 0;
itv.it_interval.tv_sec = 0;
itv.it_interval.tv_usec = 0;
if (ms > 0) {
itv.it_value.tv_sec = time_t(ms / 1000);
itv.it_value.tv_usec = time_t((ms % 1000) * 1000);
}
int st = setitimer(ITIMER_REAL, &itv, 0);
if (st == -1)
::SysError("TUnixSystem::UnixSetitimer", "setitimer");
return st;
}
//---- file descriptors --------------------------------------------------------
/// Wait for events on the file descriptors specified in the readready and
/// writeready masks or for timeout (in milliseconds) to occur. Returns
/// the number of ready descriptors, or 0 in case of timeout, or < 0 in
/// case of an error, with -2 being EINTR and -3 EBADF. In case of EINTR
/// the errno has been reset and the method can be called again.
int TUnixSystem::UnixSelect(Int_t nfds, TFdSet *readready, TFdSet *writeready,
Long_t timeout)
{
int retcode;
fd_set *rd = (readready) ? (fd_set*)readready->GetBits() : 0;
fd_set *wr = (writeready) ? (fd_set*)writeready->GetBits() : 0;
if (timeout >= 0) {
struct timeval tv;
tv.tv_sec = Int_t(timeout / 1000);
tv.tv_usec = (timeout % 1000) * 1000;
retcode = select(nfds, rd, wr, 0, &tv);
} else {
retcode = select(nfds, rd, wr, 0, 0);
}
if (retcode == -1) {
if (GetErrno() == EINTR) {
ResetErrno(); // errno is not self reseting
return -2;
}
if (GetErrno() == EBADF)
return -3;
return -1;
}
return retcode;
}
//---- directories -------------------------------------------------------------
/// Returns the user's home directory.
const char *TUnixSystem::UnixHomedirectory(const char *name)
{
static char path[kMAXPATHLEN], mydir[kMAXPATHLEN] = { '\0' };
return UnixHomedirectory(name, path, mydir);
}
/// Returns the user's home directory.
const char *TUnixSystem::UnixHomedirectory(const char *name, char *path, char *mydir)
{
struct passwd *pw;
if (name) {
pw = getpwnam(name);
if (pw) {
strncpy(path, pw->pw_dir, kMAXPATHLEN-1);
path[kMAXPATHLEN-1] = '\0';
return path;
}
} else {
if (mydir[0])
return mydir;
pw = getpwuid(getuid());
if (pw && pw->pw_dir) {
strncpy(mydir, pw->pw_dir, kMAXPATHLEN-1);
mydir[kMAXPATHLEN-1] = '\0';
return mydir;
} else if (gSystem->Getenv("HOME")) {
strncpy(mydir, gSystem->Getenv("HOME"), kMAXPATHLEN-1);
mydir[kMAXPATHLEN-1] = '\0';
return mydir;
}
}
return nullptr;
}
/// Make a Unix file system directory. Returns 0 in case of success and
/// -1 if the directory could not be created (either already exists or
/// illegal path name).
int TUnixSystem::UnixMakedir(const char *dir)
{
return ::mkdir(StripOffProto(dir, "file:"), 0755);
}
/// Open a directory.
void *TUnixSystem::UnixOpendir(const char *dir)
{
struct stat finfo;
const char *edir = StripOffProto(dir, "file:");
if (stat(edir, &finfo) < 0)
return nullptr;
if (!S_ISDIR(finfo.st_mode))
return nullptr;
return (void*) opendir(edir);
}
#if defined(_POSIX_SOURCE)
// Posix does not require that the d_ino field be present, and some
// systems do not provide it.
# define REAL_DIR_ENTRY(dp) 1
#else
# define REAL_DIR_ENTRY(dp) (dp->d_ino != 0)
#endif
/// Returns the next directory entry.
const char *TUnixSystem::UnixGetdirentry(void *dirp1)
{
DIR *dirp = (DIR*)dirp1;
#ifdef HAS_DIRENT
struct dirent *dp;
#else
struct direct *dp;
#endif
if (dirp) {
for (;;) {
dp = readdir(dirp);
if (!dp)
return nullptr;
if (REAL_DIR_ENTRY(dp))
return dp->d_name;
}
}
return nullptr;
}
//---- files -------------------------------------------------------------------
/// Get info about a file. Info is returned in the form of a FileStat_t
/// structure (see TSystem.h).
/// The function returns 0 in case of success and 1 if the file could
/// not be stat'ed.
int TUnixSystem::UnixFilestat(const char *fpath, FileStat_t &buf)
{
const char *path = StripOffProto(fpath, "file:");
buf.fIsLink = kFALSE;
#if defined(R__SEEK64)
struct stat64 sbuf;
if (path && lstat64(path, &sbuf) == 0) {
#else
struct stat sbuf;
if (path && lstat(path, &sbuf) == 0) {
#endif
buf.fIsLink = S_ISLNK(sbuf.st_mode);
if (buf.fIsLink) {
#if defined(R__SEEK64)
if (stat64(path, &sbuf) == -1) {
#else
if (stat(path, &sbuf) == -1) {
#endif
return 1;
}
}
buf.fDev = sbuf.st_dev;
buf.fIno = sbuf.st_ino;
buf.fMode = sbuf.st_mode;
buf.fUid = sbuf.st_uid;
buf.fGid = sbuf.st_gid;
buf.fSize = sbuf.st_size;
buf.fMtime = sbuf.st_mtime;
return 0;
}
return 1;
}
/// Get info about a file system: id, bsize, bfree, blocks.
/// Id is file system type (machine dependend, see statfs())
/// Bsize is block size of file system
/// Blocks is total number of blocks in file system
/// Bfree is number of free blocks in file system
/// The function returns 0 in case of success and 1 if the file system could
/// not be stat'ed.
int TUnixSystem::UnixFSstat(const char *path, Long_t *id, Long_t *bsize,
Long_t *blocks, Long_t *bfree)
{
struct statfs statfsbuf;
#if (defined(R__SOLARIS) && !defined(R__LINUX))
if (statfs(path, &statfsbuf, sizeof(struct statfs), 0) == 0) {
*id = statfsbuf.f_fstyp;
*bsize = statfsbuf.f_bsize;
*blocks = statfsbuf.f_blocks;
*bfree = statfsbuf.f_bfree;
#else
if (statfs((char*)path, &statfsbuf) == 0) {
#ifdef R__OBSD
// Convert BSD filesystem names to Linux filesystem type numbers
// where possible. Linux statfs uses a value of -1 to indicate
// an unsupported field.
if (!strcmp(statfsbuf.f_fstypename, MOUNT_FFS) ||
!strcmp(statfsbuf.f_fstypename, MOUNT_MFS))
*id = 0x11954;
else if (!strcmp(statfsbuf.f_fstypename, MOUNT_NFS))
*id = 0x6969;
else if (!strcmp(statfsbuf.f_fstypename, MOUNT_MSDOS))
*id = 0x4d44;
else if (!strcmp(statfsbuf.f_fstypename, MOUNT_EXT2FS))
*id = 0xef53;
else if (!strcmp(statfsbuf.f_fstypename, MOUNT_CD9660))
*id = 0x9660;
else if (!strcmp(statfsbuf.f_fstypename, MOUNT_NCPFS))
*id = 0x6969;
else
*id = -1;
#else
*id = statfsbuf.f_type;
#endif
*bsize = statfsbuf.f_bsize;
*blocks = statfsbuf.f_blocks;
*bfree = statfsbuf.f_bavail;
#endif
return 0;
}
return 1;
}
/// Wait till child is finished.
int TUnixSystem::UnixWaitchild()
{
int status;
return (int) waitpid(0, &status, WNOHANG);
}
//---- RPC -------------------------------------------------------------------
/// Open a TCP/IP connection to server and connect to a service (i.e. port).
/// Use tcpwindowsize to specify the size of the receive buffer, it has
/// to be specified here to make sure the window scale option is set (for
/// tcpwindowsize > 65KB and for platforms supporting window scaling).
/// Is called via the TSocket constructor. Returns -1 in case of error.
int TUnixSystem::UnixTcpConnect(const char *hostname, int port,
int tcpwindowsize)
{
short sport;
struct servent *sp;
if ((sp = getservbyport(htons(port), kProtocolName)))
sport = sp->s_port;
else
sport = htons(port);
TInetAddress addr = gSystem->GetHostByName(hostname);
if (!addr.IsValid()) return -1;
UInt_t adr = htonl(addr.GetAddress());
struct sockaddr_in server;
memset(&server, 0, sizeof(server));
memcpy(&server.sin_addr, &adr, sizeof(adr));
server.sin_family = addr.GetFamily();
server.sin_port = sport;
// Create socket
int sock;
if ((sock = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
::SysError("TUnixSystem::UnixTcpConnect", "socket (%s:%d)",
hostname, port);
return -1;
}
if (tcpwindowsize > 0) {
gSystem->SetSockOpt(sock, kRecvBuffer, tcpwindowsize);
gSystem->SetSockOpt(sock, kSendBuffer, tcpwindowsize);
}
while (connect(sock, (struct sockaddr*) &server, sizeof(server)) == -1) {
if (GetErrno() == EINTR)
ResetErrno();
else {
::SysError("TUnixSystem::UnixTcpConnect", "connect (%s:%d)",
hostname, port);
close(sock);
return -1;
}
}
return sock;
}
/// Creates a UDP socket connection
/// Is called via the TSocket constructor. Returns -1 in case of error.
int TUnixSystem::UnixUdpConnect(const char *hostname, int port)
{
short sport;
struct servent *sp;
if ((sp = getservbyport(htons(port), kProtocolName)))
sport = sp->s_port;
else
sport = htons(port);
TInetAddress addr = gSystem->GetHostByName(hostname);
if (!addr.IsValid()) return -1;
UInt_t adr = htonl(addr.GetAddress());
struct sockaddr_in server;
memset(&server, 0, sizeof(server));
memcpy(&server.sin_addr, &adr, sizeof(adr));
server.sin_family = addr.GetFamily();
server.sin_port = sport;
// Create socket
int sock;
if ((sock = socket(AF_INET, SOCK_DGRAM, 0)) < 0) {
::SysError("TUnixSystem::UnixUdpConnect", "socket (%s:%d)",
hostname, port);
return -1;
}
while (connect(sock, (struct sockaddr*) &server, sizeof(server)) == -1) {
if (GetErrno() == EINTR)
ResetErrno();
else {
::SysError("TUnixSystem::UnixUdpConnect", "connect (%s:%d)",
hostname, port);
close(sock);
return -1;
}
}
return sock;
}
/// Connect to a Unix domain socket.
int TUnixSystem::UnixUnixConnect(int port)
{
return UnixUnixConnect(TString::Format("%s/%d", kServerPath, port));
}
/// Connect to a Unix domain socket. Returns -1 in case of error.
int TUnixSystem::UnixUnixConnect(const char *sockpath)
{
if (!sockpath || strlen(sockpath) <= 0) {
::SysError("TUnixSystem::UnixUnixConnect", "socket path undefined");
return -1;
}
int sock;
struct sockaddr_un unserver;
unserver.sun_family = AF_UNIX;
if (strlen(sockpath) > sizeof(unserver.sun_path)-1) {
::Error("TUnixSystem::UnixUnixConnect", "socket path %s, longer than max allowed length (%u)",
sockpath, (UInt_t)sizeof(unserver.sun_path)-1);
return -1;
}
strcpy(unserver.sun_path, sockpath);
// Open socket
if ((sock = socket(AF_UNIX, SOCK_STREAM, 0)) < 0) {
::SysError("TUnixSystem::UnixUnixConnect", "socket");
return -1;
}
while (connect(sock, (struct sockaddr*) &unserver, strlen(unserver.sun_path)+2) == -1) {
if (GetErrno() == EINTR)
ResetErrno();
else {
::SysError("TUnixSystem::UnixUnixConnect", "connect");
close(sock);
return -1;
}
}
return sock;
}
/// Open a socket, bind to it and start listening for TCP/IP connections
/// on the port. If reuse is true reuse the address, backlog specifies
/// how many sockets can be waiting to be accepted. If port is 0 a port
/// scan will be done to find a free port. This option is mutual exlusive
/// with the reuse option.
/// Use tcpwindowsize to specify the size of the receive buffer, it has
/// to be specified here to make sure the window scale option is set (for
/// tcpwindowsize > 65KB and for platforms supporting window scaling).
/// Returns socket fd or -1 if socket() failed, -2 if bind() failed
/// or -3 if listen() failed.
int TUnixSystem::UnixTcpService(int port, Bool_t reuse, int backlog,
int tcpwindowsize)
{
const short kSOCKET_MINPORT = 5000, kSOCKET_MAXPORT = 15000;
short sport, tryport = kSOCKET_MINPORT;
struct servent *sp;
if (port == 0 && reuse) {
::Error("TUnixSystem::UnixTcpService", "cannot do a port scan while reuse is true");
return -1;
}
if ((sp = getservbyport(htons(port), kProtocolName)))
sport = sp->s_port;
else
sport = htons(port);
// Create tcp socket
int sock;
if ((sock = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
::SysError("TUnixSystem::UnixTcpService", "socket");
return -1;
}
if (reuse)
gSystem->SetSockOpt(sock, kReuseAddr, 1);
if (tcpwindowsize > 0) {
gSystem->SetSockOpt(sock, kRecvBuffer, tcpwindowsize);
gSystem->SetSockOpt(sock, kSendBuffer, tcpwindowsize);
}
struct sockaddr_in inserver;
memset(&inserver, 0, sizeof(inserver));
inserver.sin_family = AF_INET;
inserver.sin_addr.s_addr = htonl(INADDR_ANY);
inserver.sin_port = sport;
// Bind socket
if (port > 0) {
if (::bind(sock, (struct sockaddr*) &inserver, sizeof(inserver))) {
::SysError("TUnixSystem::UnixTcpService", "bind");
close(sock);
return -2;
}
} else {
int bret;
do {
inserver.sin_port = htons(tryport);
bret = ::bind(sock, (struct sockaddr*) &inserver, sizeof(inserver));
tryport++;
} while (bret < 0 && GetErrno() == EADDRINUSE && tryport < kSOCKET_MAXPORT);
if (bret < 0) {
::SysError("TUnixSystem::UnixTcpService", "bind (port scan)");
close(sock);
return -2;
}
}
// Start accepting connections
if (::listen(sock, backlog)) {
::SysError("TUnixSystem::UnixTcpService", "listen");
close(sock);
return -3;
}
return sock;
}
/// Open a socket, bind to it and start listening for UDP connections
/// on the port. If reuse is true reuse the address, backlog specifies
/// how many sockets can be waiting to be accepted. If port is 0 a port
/// scan will be done to find a free port. This option is mutual exlusive
/// with the reuse option.
int TUnixSystem::UnixUdpService(int port, int backlog)
{
const short kSOCKET_MINPORT = 5000, kSOCKET_MAXPORT = 15000;
short sport, tryport = kSOCKET_MINPORT;
struct servent *sp;
if ((sp = getservbyport(htons(port), kProtocolName)))
sport = sp->s_port;
else
sport = htons(port);
// Create udp socket
int sock;
if ((sock = socket(AF_INET, SOCK_DGRAM, 0)) < 0) {
::SysError("TUnixSystem::UnixUdpService", "socket");
return -1;
}
struct sockaddr_in inserver;
memset(&inserver, 0, sizeof(inserver));
inserver.sin_family = AF_INET;
inserver.sin_addr.s_addr = htonl(INADDR_ANY);
inserver.sin_port = sport;
// Bind socket
if (port > 0) {
if (::bind(sock, (struct sockaddr*) &inserver, sizeof(inserver))) {
::SysError("TUnixSystem::UnixUdpService", "bind");
close(sock);
return -2;
}
} else {
int bret;
do {
inserver.sin_port = htons(tryport);
bret = ::bind(sock, (struct sockaddr*) &inserver, sizeof(inserver));
tryport++;
} while (bret < 0 && GetErrno() == EADDRINUSE && tryport < kSOCKET_MAXPORT);
if (bret < 0) {
::SysError("TUnixSystem::UnixUdpService", "bind (port scan)");
close(sock);
return -2;
}
}
// Start accepting connections
if (::listen(sock, backlog)) {
::SysError("TUnixSystem::UnixUdpService", "listen");
close(sock);
return -3;
}
return sock;
}
/// Open a socket, bind to it and start listening for Unix domain connections
/// to it. Returns socket fd or -1.
int TUnixSystem::UnixUnixService(int port, int backlog)
{
int oldumask;
// Assure that socket directory exists
oldumask = umask(0);
int res = ::mkdir(kServerPath, 0777);
umask(oldumask);
if (res == -1)
return -1;
// Socket path
TString sockpath;
sockpath.Form("%s/%d", kServerPath, port);
// Remove old socket
unlink(sockpath.Data());
return UnixUnixService(sockpath, backlog);
}
/// Open a socket on path 'sockpath', bind to it and start listening for Unix
/// domain connections to it. Returns socket fd or -1.
int TUnixSystem::UnixUnixService(const char *sockpath, int backlog)
{
if (!sockpath || strlen(sockpath) <= 0) {
::SysError("TUnixSystem::UnixUnixService", "socket path undefined");
return -1;
}
struct sockaddr_un unserver;
int sock;
// Prepare structure
memset(&unserver, 0, sizeof(unserver));
unserver.sun_family = AF_UNIX;
if (strlen(sockpath) > sizeof(unserver.sun_path)-1) {
::Error("TUnixSystem::UnixUnixService", "socket path %s, longer than max allowed length (%u)",
sockpath, (UInt_t)sizeof(unserver.sun_path)-1);
return -1;
}
strcpy(unserver.sun_path, sockpath);
// Create socket
if ((sock = socket(AF_UNIX, SOCK_STREAM, 0)) < 0) {
::SysError("TUnixSystem::UnixUnixService", "socket");
return -1;
}
if (::bind(sock, (struct sockaddr*) &unserver, strlen(unserver.sun_path)+2)) {
::SysError("TUnixSystem::UnixUnixService", "bind");
close(sock);
return -1;
}
// Start accepting connections
if (::listen(sock, backlog)) {
::SysError("TUnixSystem::UnixUnixService", "listen");
close(sock);
return -1;
}
return sock;
}
/// Receive exactly length bytes into buffer. Returns number of bytes
/// received. Returns -1 in case of error, -2 in case of MSG_OOB
/// and errno == EWOULDBLOCK, -3 in case of MSG_OOB and errno == EINVAL
/// and -4 in case of kNoBlock and errno == EWOULDBLOCK.
/// Returns -5 if pipe broken or reset by peer (EPIPE || ECONNRESET).
int TUnixSystem::UnixRecv(int sock, void *buffer, int length, int flag)
{
ResetErrno();
if (sock < 0) return -1;
int once = 0;
if (flag == -1) {
flag = 0;
once = 1;
}
if (flag == MSG_PEEK)
once = 1;
int n, nrecv = 0;
char *buf = (char *)buffer;
for (n = 0; n < length; n += nrecv) {
if ((nrecv = recv(sock, buf+n, length-n, flag)) <= 0) {
if (nrecv == 0)
break; // EOF
if (flag == MSG_OOB) {
if (GetErrno() == EWOULDBLOCK)
return -2;
else if (GetErrno() == EINVAL)
return -3;
}
if (GetErrno() == EWOULDBLOCK)
return -4;
else {
if (GetErrno() != EINTR)
::SysError("TUnixSystem::UnixRecv", "recv");
if (GetErrno() == EPIPE || GetErrno() == ECONNRESET)
return -5;
else
return -1;
}
}
if (once)
return nrecv;
}
return n;
}
/// Send exactly length bytes from buffer. Returns -1 in case of error,
/// otherwise number of sent bytes. Returns -4 in case of kNoBlock and
/// errno == EWOULDBLOCK. Returns -5 if pipe broken or reset by peer
/// (EPIPE || ECONNRESET).
int TUnixSystem::UnixSend(int sock, const void *buffer, int length, int flag)
{
if (sock < 0) return -1;
int once = 0;
if (flag == -1) {
flag = 0;
once = 1;
}
int n, nsent = 0;
const char *buf = (const char *)buffer;
for (n = 0; n < length; n += nsent) {
if ((nsent = send(sock, buf+n, length-n, flag)) <= 0) {
if (nsent == 0)
break;
if (GetErrno() == EWOULDBLOCK)
return -4;
else {
if (GetErrno() != EINTR)
::SysError("TUnixSystem::UnixSend", "send");
if (GetErrno() == EPIPE || GetErrno() == ECONNRESET)
return -5;
else
return -1;
}
}
if (once)
return nsent;
}
return n;
}
//---- Dynamic Loading ---------------------------------------------------------
/// Get shared library search path. Static utility function.
static const char *DynamicPath(const char *newpath = 0, Bool_t reset = kFALSE)
{
static TString dynpath;
static Bool_t initialized = kFALSE;
if (!initialized) {
// force one time initialization of gROOT before we start
// (otherwise it might be done as a side effect of gEnv->GetValue and
// TROOT's initialization will call this routine).
gROOT;
}
if (newpath) {
dynpath = newpath;
} else if (reset || !initialized) {
initialized = kTRUE;
TString rdynpath = gEnv->GetValue("Root.DynamicPath", (char*)0);
rdynpath.ReplaceAll(": ", ":"); // in case DynamicPath was extended
if (rdynpath.IsNull()) {
rdynpath = ".:"; rdynpath += TROOT::GetLibDir();
}
TString ldpath;
#if defined (R__AIX)
ldpath = gSystem->Getenv("LIBPATH");
#elif defined(R__MACOSX)
ldpath = gSystem->Getenv("DYLD_LIBRARY_PATH");
if (!ldpath.IsNull())
ldpath += ":";
ldpath += gSystem->Getenv("LD_LIBRARY_PATH");
if (!ldpath.IsNull())
ldpath += ":";
ldpath += gSystem->Getenv("DYLD_FALLBACK_LIBRARY_PATH");
#else
ldpath = gSystem->Getenv("LD_LIBRARY_PATH");
#endif
if (ldpath.IsNull())
dynpath = rdynpath;
else {
dynpath = ldpath; dynpath += ":"; dynpath += rdynpath;
}
if (!dynpath.Contains(TROOT::GetLibDir())) {
dynpath += ":"; dynpath += TROOT::GetLibDir();
}
if (gCling) {
dynpath += ":"; dynpath += gCling->GetSTLIncludePath();
} else
initialized = kFALSE;
#if defined(R__WINGCC) || defined(R__MACOSX)
if (!dynpath.EndsWith(":")) dynpath += ":";
dynpath += "/usr/local/lib:/usr/X11R6/lib:/usr/lib:/lib:";
dynpath += "/lib/x86_64-linux-gnu:/usr/local/lib64:/usr/lib64:/lib64:";
#else
// trick to get the system search path
std::string cmd("LD_DEBUG=libs LD_PRELOAD=DOESNOTEXIST ls 2>&1");
FILE *pf = popen(cmd.c_str (), "r");
std::string result = "";
char buffer[128];
while (!feof(pf)) {
if (fgets(buffer, 128, pf) != NULL)
result += buffer;
}
pclose(pf);
std::size_t from = result.find("search path=", result.find("(LD_LIBRARY_PATH)"));
std::size_t to = result.find("(system search path)");
if (from != std::string::npos && to != std::string::npos) {
from += 12;
std::string sys_path = result.substr(from, to-from);
sys_path.erase(std::remove_if(sys_path.begin(), sys_path.end(), isspace), sys_path.end());
if (!dynpath.EndsWith(":")) dynpath += ":";
dynpath += sys_path.c_str();
}
dynpath.ReplaceAll("::", ":");
#endif
if (gDebug > 0) std::cout << "dynpath = " << dynpath.Data() << std::endl;
}
return dynpath;
}
/// Add a new directory to the dynamic path.
void TUnixSystem::AddDynamicPath(const char *path)
{
if (path) {
TString oldpath = DynamicPath(0, kFALSE);
oldpath.Append(":");
oldpath.Append(path);
DynamicPath(oldpath);
}
}
/// Return the dynamic path (used to find shared libraries).
const char *TUnixSystem::GetDynamicPath()
{
return DynamicPath(0, kFALSE);
}
/// Set the dynamic path to a new value.
/// If the value of 'path' is zero, the dynamic path is reset to its
/// default value.
void TUnixSystem::SetDynamicPath(const char *path)
{
if (!path)
DynamicPath(0, kTRUE);
else
DynamicPath(path);
}
/// Returns the path of a shared library (searches for library in the
/// shared library search path). If no file name extension is provided
/// it first tries .so, .sl, .dl and then .a (for AIX).
const char *TUnixSystem::FindDynamicLibrary(TString& sLib, Bool_t quiet)
{
char buf[PATH_MAX + 1];
char *res = realpath(sLib.Data(), buf);
if (res) sLib = buf;
TString searchFor = sLib;
if (gSystem->FindFile(GetDynamicPath(), sLib, kReadPermission)) {
return sLib;
}
sLib = searchFor;
const char* lib = sLib.Data();
int len = sLib.Length();
if (len > 3 && (!strcmp(lib+len-3, ".so") ||
!strcmp(lib+len-3, ".dl") ||
!strcmp(lib+len-4, ".dll") ||
!strcmp(lib+len-4, ".DLL") ||
!strcmp(lib+len-6, ".dylib") ||
!strcmp(lib+len-3, ".sl") ||
!strcmp(lib+len-2, ".a"))) {
if (gSystem->FindFile(GetDynamicPath(), sLib, kReadPermission)) {
return sLib;
}
if (!quiet)
Error("FindDynamicLibrary",
"%s does not exist in %s", searchFor.Data(), GetDynamicPath());
return nullptr;
}
static const char* exts[] = {
".so", ".dll", ".dylib", ".sl", ".dl", ".a", 0 };
const char** ext = exts;
while (*ext) {
TString fname(sLib);
fname += *ext;
++ext;
if (gSystem->FindFile(GetDynamicPath(), fname, kReadPermission)) {
sLib.Swap(fname);
return sLib;
}
}
if (!quiet)
Error("FindDynamicLibrary",
"%s[.so | .dll | .dylib | .sl | .dl | .a] does not exist in %s",
searchFor.Data(), GetDynamicPath());
return nullptr;
}
//---- System, CPU and Memory info ---------------------------------------------
#if defined(R__MACOSX)
#include <sys/resource.h>
#include <mach/mach.h>
#include <mach/mach_error.h>
/// Get system info for Mac OS X.
static void GetDarwinSysInfo(SysInfo_t *sysinfo)
{
FILE *p = gSystem->OpenPipe("sysctl -n kern.ostype hw.model hw.ncpu hw.cpufrequency "
"hw.busfrequency hw.l2cachesize hw.memsize", "r");
TString s;
s.Gets(p);
sysinfo->fOS = s;
s.Gets(p);
sysinfo->fModel = s;
s.Gets(p);
sysinfo->fCpus = s.Atoi();
s.Gets(p);
Long64_t t = s.Atoll();
sysinfo->fCpuSpeed = Int_t(t / 1000000);
s.Gets(p);
t = s.Atoll();
sysinfo->fBusSpeed = Int_t(t / 1000000);
s.Gets(p);
sysinfo->fL2Cache = s.Atoi() / 1024;
s.Gets(p);
t = s.Atoll();
sysinfo->fPhysRam = Int_t(t / 1024 / 1024);
gSystem->ClosePipe(p);
p = gSystem->OpenPipe("hostinfo", "r");
while (s.Gets(p)) {
if (s.BeginsWith("Processor type: ")) {
TPRegexp("Processor type: ([^ ]+).*").Substitute(s, "$1");
sysinfo->fCpuType = s;
}
}
gSystem->ClosePipe(p);
}
/// Get CPU load on Mac OS X.
static void ReadDarwinCpu(long *ticks)
{
mach_msg_type_number_t count;
kern_return_t kr;
host_cpu_load_info_data_t cpu;
ticks[0] = ticks[1] = ticks[2] = ticks[3] = 0;
count = HOST_CPU_LOAD_INFO_COUNT;
kr = host_statistics(mach_host_self(), HOST_CPU_LOAD_INFO, (host_info_t)&cpu, &count);
if (kr != KERN_SUCCESS) {
::Error("TUnixSystem::ReadDarwinCpu", "host_statistics: %s", mach_error_string(kr));
} else {
ticks[0] = cpu.cpu_ticks[CPU_STATE_USER];
ticks[1] = cpu.cpu_ticks[CPU_STATE_SYSTEM];
ticks[2] = cpu.cpu_ticks[CPU_STATE_IDLE];
ticks[3] = cpu.cpu_ticks[CPU_STATE_NICE];
}
}
/// Get CPU stat for Mac OS X. Use sampleTime to set the interval over which
/// the CPU load will be measured, in ms (default 1000).
static void GetDarwinCpuInfo(CpuInfo_t *cpuinfo, Int_t sampleTime)
{
Double_t avg[3];
if (getloadavg(avg, sizeof(avg)) < 0) {
::Error("TUnixSystem::GetDarwinCpuInfo", "getloadavg failed");
} else {
cpuinfo->fLoad1m = (Float_t)avg[0];
cpuinfo->fLoad5m = (Float_t)avg[1];
cpuinfo->fLoad15m = (Float_t)avg[2];
}
Long_t cpu_ticks1[4], cpu_ticks2[4];
ReadDarwinCpu(cpu_ticks1);
gSystem->Sleep(sampleTime);
ReadDarwinCpu(cpu_ticks2);
Long_t userticks = (cpu_ticks2[0] + cpu_ticks2[3]) -
(cpu_ticks1[0] + cpu_ticks1[3]);
Long_t systicks = cpu_ticks2[1] - cpu_ticks1[1];
Long_t idleticks = cpu_ticks2[2] - cpu_ticks1[2];
if (userticks < 0) userticks = 0;
if (systicks < 0) systicks = 0;
if (idleticks < 0) idleticks = 0;
Long_t totalticks = userticks + systicks + idleticks;
if (totalticks) {
cpuinfo->fUser = ((Float_t)(100 * userticks)) / ((Float_t)totalticks);
cpuinfo->fSys = ((Float_t)(100 * systicks)) / ((Float_t)totalticks);
cpuinfo->fTotal = cpuinfo->fUser + cpuinfo->fSys;
cpuinfo->fIdle = ((Float_t)(100 * idleticks)) / ((Float_t)totalticks);
}
}
/// Get VM stat for Mac OS X.
static void GetDarwinMemInfo(MemInfo_t *meminfo)
{
static Int_t pshift = 0;
static DIR *dirp;
vm_statistics_data_t vm_info;
mach_msg_type_number_t count;
kern_return_t kr;
struct dirent *dp;
Long64_t total, used, free, swap_total, swap_used;
count = HOST_VM_INFO_COUNT;
kr = host_statistics(mach_host_self(), HOST_VM_INFO, (host_info_t)&vm_info, &count);
if (kr != KERN_SUCCESS) {
::Error("TUnixSystem::GetDarwinMemInfo", "host_statistics: %s", mach_error_string(kr));
return;
}
if (pshift == 0) {
for (int psize = getpagesize(); psize > 1; psize >>= 1)
pshift++;
}
used = (Long64_t)(vm_info.active_count + vm_info.inactive_count + vm_info.wire_count) << pshift;
free = (Long64_t)(vm_info.free_count) << pshift;
total = (Long64_t)(vm_info.active_count + vm_info.inactive_count + vm_info.free_count + vm_info.wire_count) << pshift;
// Swap is available at same time as mem, so grab values here.
swap_used = vm_info.pageouts << pshift;
// Figure out total swap. This adds up the size of the swapfiles */
dirp = opendir("/private/var/vm");
if (!dirp)
return;
swap_total = 0;
while ((dp = readdir(dirp)) != 0) {
struct stat sb;
char fname [MAXNAMLEN];
if (strncmp(dp->d_name, "swapfile", 8))
continue;
strlcpy(fname, "/private/var/vm/",MAXNAMLEN);
strlcat (fname, dp->d_name,MAXNAMLEN);
if (stat(fname, &sb) < 0)
continue;
swap_total += sb.st_size;
}
closedir(dirp);
meminfo->fMemTotal = (Int_t) (total >> 20); // divide by 1024 * 1024
meminfo->fMemUsed = (Int_t) (used >> 20);
meminfo->fMemFree = (Int_t) (free >> 20);
meminfo->fSwapTotal = (Int_t) (swap_total >> 20);
meminfo->fSwapUsed = (Int_t) (swap_used >> 20);
meminfo->fSwapFree = meminfo->fSwapTotal - meminfo->fSwapUsed;
}
/// Get process info for this process on Mac OS X.
/// Code largely taken from:
/// http://www.opensource.apple.com/source/top/top-15/libtop.c
/// The virtual memory usage is slightly over estimated as we don't
/// subtract shared regions, but the value makes more sense
/// then pure vsize, which is useless on 64-bit machines.
static void GetDarwinProcInfo(ProcInfo_t *procinfo)
{
#ifdef _LP64
#define vm_region vm_region_64
#endif
// taken from <mach/shared_memory_server.h> which is obsoleted in 10.5
#define GLOBAL_SHARED_TEXT_SEGMENT 0x90000000U
#define GLOBAL_SHARED_DATA_SEGMENT 0xA0000000U
#define SHARED_TEXT_REGION_SIZE 0x10000000
#define SHARED_DATA_REGION_SIZE 0x10000000
struct rusage ru;
if (getrusage(RUSAGE_SELF, &ru) < 0) {
::SysError("TUnixSystem::GetDarwinProcInfo", "getrusage failed");
} else {
procinfo->fCpuUser = (Float_t)(ru.ru_utime.tv_sec) +
((Float_t)(ru.ru_utime.tv_usec) / 1000000.);
procinfo->fCpuSys = (Float_t)(ru.ru_stime.tv_sec) +
((Float_t)(ru.ru_stime.tv_usec) / 1000000.);
}
task_basic_info_data_t ti;
mach_msg_type_number_t count;
kern_return_t kr;
task_t a_task = mach_task_self();
count = TASK_BASIC_INFO_COUNT;
kr = task_info(a_task, TASK_BASIC_INFO, (task_info_t)&ti, &count);
if (kr != KERN_SUCCESS) {
::Error("TUnixSystem::GetDarwinProcInfo", "task_info: %s", mach_error_string(kr));
} else {
// resident size does not require any calculation. Virtual size
// needs to be adjusted if traversing memory objects do not include the
// globally shared text and data regions
mach_port_t object_name;
vm_address_t address;
vm_region_top_info_data_t info;
vm_size_t vsize, vprvt, rsize, size;
rsize = ti.resident_size;
vsize = ti.virtual_size;
vprvt = 0;
for (address = 0; ; address += size) {
// get memory region
count = VM_REGION_TOP_INFO_COUNT;
if (vm_region(a_task, &address, &size,
VM_REGION_TOP_INFO, (vm_region_info_t)&info, &count,
&object_name) != KERN_SUCCESS) {
// no more memory regions.
break;
}
if (address >= GLOBAL_SHARED_TEXT_SEGMENT &&
address < (GLOBAL_SHARED_DATA_SEGMENT + SHARED_DATA_REGION_SIZE)) {
// This region is private shared.
// Check if this process has the globally shared
// text and data regions mapped in. If so, adjust
// virtual memory size and exit loop.
if (info.share_mode == SM_EMPTY) {
vm_region_basic_info_data_64_t b_info;
count = VM_REGION_BASIC_INFO_COUNT_64;
if (vm_region_64(a_task, &address,
&size, VM_REGION_BASIC_INFO,
(vm_region_info_t)&b_info, &count,
&object_name) != KERN_SUCCESS) {
break;
}
if (b_info.reserved) {
vsize -= (SHARED_TEXT_REGION_SIZE + SHARED_DATA_REGION_SIZE);
//break; // only for vsize
}
}
// Short circuit the loop if this isn't a shared
// private region, since that's the only region
// type we care about within the current address range.
if (info.share_mode != SM_PRIVATE) {
continue;
}
}
switch (info.share_mode) {
case SM_COW: {
if (info.ref_count == 1) {
vprvt += size;
} else {
vprvt += info.private_pages_resident * getpagesize();
}
break;
}
case SM_PRIVATE: {
vprvt += size;
break;
}
default:
break;
}
}
procinfo->fMemResident = (Long_t)(rsize / 1024);
//procinfo->fMemVirtual = (Long_t)(vsize / 1024);
procinfo->fMemVirtual = (Long_t)(vprvt / 1024);
}
}
#endif
#if defined(R__LINUX)
/// Get system info for Linux. Only fBusSpeed is not set.
static void GetLinuxSysInfo(SysInfo_t *sysinfo)
{
TString s;
FILE *f = fopen("/proc/cpuinfo", "r");
if (f) {
while (s.Gets(f)) {
if (s.BeginsWith("model name")) {
TPRegexp("^.+: *(.*$)").Substitute(s, "$1");
sysinfo->fModel = s;
}
if (s.BeginsWith("cpu MHz")) {
TPRegexp("^.+: *([^ ]+).*").Substitute(s, "$1");
sysinfo->fCpuSpeed = s.Atoi();
}
if (s.BeginsWith("cache size")) {
TPRegexp("^.+: *([^ ]+).*").Substitute(s, "$1");
sysinfo->fL2Cache = s.Atoi();
}
if (s.BeginsWith("processor")) {
TPRegexp("^.+: *([^ ]+).*").Substitute(s, "$1");
sysinfo->fCpus = s.Atoi();
sysinfo->fCpus++;
}
}
fclose(f);
}
f = fopen("/proc/meminfo", "r");
if (f) {
while (s.Gets(f)) {
if (s.BeginsWith("MemTotal")) {
TPRegexp("^.+: *([^ ]+).*").Substitute(s, "$1");
sysinfo->fPhysRam = (s.Atoi() / 1024);
break;
}
}
fclose(f);
}
f = gSystem->OpenPipe("uname -s -p", "r");
if (f) {
s.Gets(f);
Ssiz_t from = 0;
s.Tokenize(sysinfo->fOS, from);
s.Tokenize(sysinfo->fCpuType, from);
gSystem->ClosePipe(f);
}
}
/// Get CPU load on Linux.
static void ReadLinuxCpu(long *ticks)
{
ticks[0] = ticks[1] = ticks[2] = ticks[3] = 0;
TString s;
FILE *f = fopen("/proc/stat", "r");
if (!f) return;
s.Gets(f);
// user, user nice, sys, idle
sscanf(s.Data(), "%*s %ld %ld %ld %ld", &ticks[0], &ticks[3], &ticks[1], &ticks[2]);
fclose(f);
}
/// Get CPU stat for Linux. Use sampleTime to set the interval over which
/// the CPU load will be measured, in ms (default 1000).
static void GetLinuxCpuInfo(CpuInfo_t *cpuinfo, Int_t sampleTime)
{
Double_t avg[3] = { -1., -1., -1. };
#ifndef R__WINGCC
if (getloadavg(avg, sizeof(avg)) < 0) {
::Error("TUnixSystem::GetLinuxCpuInfo", "getloadavg failed");
} else
#endif
{
cpuinfo->fLoad1m = (Float_t)avg[0];
cpuinfo->fLoad5m = (Float_t)avg[1];
cpuinfo->fLoad15m = (Float_t)avg[2];
}
Long_t cpu_ticks1[4], cpu_ticks2[4];
ReadLinuxCpu(cpu_ticks1);
gSystem->Sleep(sampleTime);
ReadLinuxCpu(cpu_ticks2);
Long_t userticks = (cpu_ticks2[0] + cpu_ticks2[3]) -
(cpu_ticks1[0] + cpu_ticks1[3]);
Long_t systicks = cpu_ticks2[1] - cpu_ticks1[1];
Long_t idleticks = cpu_ticks2[2] - cpu_ticks1[2];
if (userticks < 0) userticks = 0;
if (systicks < 0) systicks = 0;
if (idleticks < 0) idleticks = 0;
Long_t totalticks = userticks + systicks + idleticks;
if (totalticks) {
cpuinfo->fUser = ((Float_t)(100 * userticks)) / ((Float_t)totalticks);
cpuinfo->fSys = ((Float_t)(100 * systicks)) / ((Float_t)totalticks);
cpuinfo->fTotal = cpuinfo->fUser + cpuinfo->fSys;
cpuinfo->fIdle = ((Float_t)(100 * idleticks)) / ((Float_t)totalticks);
}
}
/// Get VM stat for Linux.
static void GetLinuxMemInfo(MemInfo_t *meminfo)
{
TString s;
FILE *f = fopen("/proc/meminfo", "r");
if (!f) return;
while (s.Gets(f)) {
if (s.BeginsWith("MemTotal")) {
TPRegexp("^.+: *([^ ]+).*").Substitute(s, "$1");
meminfo->fMemTotal = (s.Atoi() / 1024);
}
if (s.BeginsWith("MemFree")) {
TPRegexp("^.+: *([^ ]+).*").Substitute(s, "$1");
meminfo->fMemFree = (s.Atoi() / 1024);
}
if (s.BeginsWith("SwapTotal")) {
TPRegexp("^.+: *([^ ]+).*").Substitute(s, "$1");
meminfo->fSwapTotal = (s.Atoi() / 1024);
}
if (s.BeginsWith("SwapFree")) {
TPRegexp("^.+: *([^ ]+).*").Substitute(s, "$1");
meminfo->fSwapFree = (s.Atoi() / 1024);
}
}
fclose(f);
meminfo->fMemUsed = meminfo->fMemTotal - meminfo->fMemFree;
meminfo->fSwapUsed = meminfo->fSwapTotal - meminfo->fSwapFree;
}
/// Get process info for this process on Linux.
static void GetLinuxProcInfo(ProcInfo_t *procinfo)
{
struct rusage ru;
if (getrusage(RUSAGE_SELF, &ru) < 0) {
::SysError("TUnixSystem::GetLinuxProcInfo", "getrusage failed");
} else {
procinfo->fCpuUser = (Float_t)(ru.ru_utime.tv_sec) +
((Float_t)(ru.ru_utime.tv_usec) / 1000000.);
procinfo->fCpuSys = (Float_t)(ru.ru_stime.tv_sec) +
((Float_t)(ru.ru_stime.tv_usec) / 1000000.);
}
procinfo->fMemVirtual = -1;
procinfo->fMemResident = -1;
TString s;
FILE *f = fopen(TString::Format("/proc/%d/statm", gSystem->GetPid()), "r");
if (f) {
s.Gets(f);
fclose(f);
Long_t total, rss;
sscanf(s.Data(), "%ld %ld", &total, &rss);
procinfo->fMemVirtual = total * (getpagesize() / 1024);
procinfo->fMemResident = rss * (getpagesize() / 1024);
}
}
#endif
/// Returns static system info, like OS type, CPU type, number of CPUs
/// RAM size, etc into the SysInfo_t structure. Returns -1 in case of error,
/// 0 otherwise.
int TUnixSystem::GetSysInfo(SysInfo_t *info) const
{
if (!info) return -1;
static SysInfo_t sysinfo;
if (!sysinfo.fCpus) {
#if defined(R__MACOSX)
GetDarwinSysInfo(&sysinfo);
#elif defined(R__LINUX)
GetLinuxSysInfo(&sysinfo);
#endif
}
*info = sysinfo;
return 0;
}
/// Returns cpu load average and load info into the CpuInfo_t structure.
/// Returns -1 in case of error, 0 otherwise. Use sampleTime to set the
/// interval over which the CPU load will be measured, in ms (default 1000).
int TUnixSystem::GetCpuInfo(CpuInfo_t *info, Int_t sampleTime) const
{
if (!info) return -1;
#if defined(R__MACOSX)
GetDarwinCpuInfo(info, sampleTime);
#elif defined(R__LINUX)
GetLinuxCpuInfo(info, sampleTime);
#endif
return 0;
}
/// Returns ram and swap memory usage info into the MemInfo_t structure.
/// Returns -1 in case of error, 0 otherwise.
int TUnixSystem::GetMemInfo(MemInfo_t *info) const
{
if (!info) return -1;
#if defined(R__MACOSX)
GetDarwinMemInfo(info);
#elif defined(R__LINUX)
GetLinuxMemInfo(info);
#endif
return 0;
}
/// Returns cpu and memory used by this process into the ProcInfo_t structure.
/// Returns -1 in case of error, 0 otherwise.
int TUnixSystem::GetProcInfo(ProcInfo_t *info) const
{
if (!info) return -1;
#if defined(R__MACOSX)
GetDarwinProcInfo(info);
#elif defined(R__LINUX)
GetLinuxProcInfo(info);
#endif
return 0;
} |
using Promptlet.Infrastructure.Models;
using System.Diagnostics.CodeAnalysis;
namespace Promptlet.Infrastructure.Data
{
[ExcludeFromCodeCoverage]
public static class DbInit
{
public static void Init(PromptletDbContext dbContext)
{
if (dbContext.PromptletCollections.Any()) { return; }
var promptletArtifacts = GetPromptletArtifacts();
var composedPromptlets = GetComposedPromptlets(promptletArtifacts);
var promptletCollection = GetPromptletCollections(composedPromptlets);
dbContext.AddRange(promptletCollection);
dbContext.SaveChanges();
}
private static PromptletCollection[] GetPromptletCollections(ComposedPromptlet[] composedPromptlets)
{
return new PromptletCollection[]
{
new PromptletCollection
{
PromptletCollectionName = "Programming",
ComposedPromptlets = composedPromptlets
}
};
}
private static ComposedPromptlet[] GetComposedPromptlets(PromptletArtifact[] promptletArtifacts)
{
return new ComposedPromptlet[]
{
new ComposedPromptlet
{
ComposedPromptletName="Code Review",
ComposedPromptletDescription="Perform a standard code review",
ComposedPromptletHeader="",
ComposedPromptletFooter="",
PromptletArtifacts=promptletArtifacts
}
};
}
private static PromptletArtifact[] GetPromptletArtifacts()
{
return new PromptletArtifact[]
{
new PromptletArtifact
{
PromptletArtifactOrder = 1,
PromptletArtifactName = "Analyze Code Smells",
PromptletArtifactContent = "Analyze the given [language] code for code smells and suggest improvements: [code snippet]",
VariableStartDeliminator = "[",
VariableEndDeliminator = "]"
},
new PromptletArtifact
{
PromptletArtifactOrder = 2,
PromptletArtifactName = "Check for logging and monitoring",
PromptletArtifactContent = "Check the following [language] code for proper logging and monitoring practices: [code snippet]",
VariableStartDeliminator = "[",
VariableEndDeliminator = "]"
},
new PromptletArtifact
{
PromptletArtifactOrder = 3,
PromptletArtifactName = "Check for scalibility",
PromptletArtifactContent = "Review the given [language] code for potential scalability issues: [code snippet]",
VariableStartDeliminator = "[",
VariableEndDeliminator = "]"
},
new PromptletArtifact
{
PromptletArtifactOrder = 4,
PromptletArtifactName = "Check for test coverage",
PromptletArtifactContent = "Assess the test coverage of the following [language] code: [code snippet]",
VariableStartDeliminator = "[",
VariableEndDeliminator = "]"
}
};
}
}
} |
import express from "express";
import handlebars from "express-handlebars";
import morgan from "morgan";
import session from "express-session";
import passport from "passport";
import { errorHandler } from "./middlewares/errorHandler.js";
import userSession from "./middlewares/userSession.js";
import { __dirname, mongoStoreOptions } from "./utils.js";
import productRouter from "./routes/product.routes.js";
import cartRouter from "./routes/cart.routes.js";
import viewsRouter from "./routes/views.routes.js";
import userRouter from "./routes/user.routes.js";
import "./passport/local-strategy.js";
import "./passport/github-strategy.js";
const app = express();
const PORT = 8080;
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
app.use(errorHandler);
app.use(morgan("dev"));
app.use(express.static(__dirname + "/public"));
app.use(userSession);
app.engine("handlebars", handlebars.engine());
app.set("view engine", "handlebars");
app.set("views", __dirname + "/views");
app.use(session(mongoStoreOptions));
app.use(passport.initialize());
app.use(passport.session());
app.use("/api/products", productRouter);
app.use("/api/carts", cartRouter);
app.use("/users", userRouter);
app.use("/", viewsRouter);
app.listen(PORT, () => {
console.log(`Server ok en puerto ${PORT}`);
}); |
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.WsClient = exports.subprotocolsV3 = exports.subprotocolsV2 = void 0;
const client_js_1 = require("../client.js");
const index_js_1 = require("../encoding/index.js");
const errors_js_1 = require("../errors.js");
const id_alloc_js_1 = require("../id_alloc.js");
const result_js_1 = require("../result.js");
const sql_js_1 = require("../sql.js");
const util_js_1 = require("../util.js");
const stream_js_1 = require("./stream.js");
const json_encode_js_1 = require("./json_encode.js");
const protobuf_encode_js_1 = require("./protobuf_encode.js");
const json_decode_js_1 = require("./json_decode.js");
const protobuf_decode_js_1 = require("./protobuf_decode.js");
exports.subprotocolsV2 = new Map([
["hrana2", { version: 2, encoding: "json" }],
["hrana1", { version: 1, encoding: "json" }],
]);
exports.subprotocolsV3 = new Map([
["hrana3-protobuf", { version: 3, encoding: "protobuf" }],
["hrana3", { version: 3, encoding: "json" }],
["hrana2", { version: 2, encoding: "json" }],
["hrana1", { version: 1, encoding: "json" }],
]);
/** A client for the Hrana protocol over a WebSocket. */
class WsClient extends client_js_1.Client {
#socket;
// List of callbacks that we queue until the socket transitions from the CONNECTING to the OPEN state.
#openCallbacks;
// Have we already transitioned from CONNECTING to OPEN and fired the callbacks in #openCallbacks?
#opened;
// Stores the error that caused us to close the client (and the socket). If we are not closed, this is
// `undefined`.
#closed;
// Have we received a response to our "hello" from the server?
#recvdHello;
// Subprotocol negotiated with the server. It is only available after the socket transitions to the OPEN
// state.
#subprotocol;
// Has the `getVersion()` function been called? This is only used to validate that the API is used
// correctly.
#getVersionCalled;
// A map from request id to the responses that we expect to receive from the server.
#responseMap;
// An allocator of request ids.
#requestIdAlloc;
// An allocator of stream ids.
/** @private */
_streamIdAlloc;
// An allocator of cursor ids.
/** @private */
_cursorIdAlloc;
// An allocator of SQL text ids.
#sqlIdAlloc;
/** @private */
constructor(socket, jwt) {
super();
this.#socket = socket;
this.#openCallbacks = [];
this.#opened = false;
this.#closed = undefined;
this.#recvdHello = false;
this.#subprotocol = undefined;
this.#getVersionCalled = false;
this.#responseMap = new Map();
this.#requestIdAlloc = new id_alloc_js_1.IdAlloc();
this._streamIdAlloc = new id_alloc_js_1.IdAlloc();
this._cursorIdAlloc = new id_alloc_js_1.IdAlloc();
this.#sqlIdAlloc = new id_alloc_js_1.IdAlloc();
this.#socket.binaryType = "arraybuffer";
this.#socket.addEventListener("open", () => this.#onSocketOpen());
this.#socket.addEventListener("close", (event) => this.#onSocketClose(event));
this.#socket.addEventListener("error", (event) => this.#onSocketError(event));
this.#socket.addEventListener("message", (event) => this.#onSocketMessage(event));
this.#send({ type: "hello", jwt });
}
// Send (or enqueue to send) a message to the server.
#send(msg) {
if (this.#closed !== undefined) {
throw new errors_js_1.InternalError("Trying to send a message on a closed client");
}
if (this.#opened) {
this.#sendToSocket(msg);
}
else {
const openCallback = () => this.#sendToSocket(msg);
const errorCallback = () => undefined;
this.#openCallbacks.push({ openCallback, errorCallback });
}
}
// The socket transitioned from CONNECTING to OPEN
#onSocketOpen() {
const protocol = this.#socket.protocol;
if (protocol === undefined) {
this.#setClosed(new errors_js_1.ClientError("The `WebSocket.protocol` property is undefined. This most likely means that the WebSocket " +
"implementation provided by the environment is broken. If you are using Miniflare 2, " +
"please update to Miniflare 3, which fixes this problem."));
return;
}
else if (protocol === "") {
this.#subprotocol = { version: 1, encoding: "json" };
}
else {
this.#subprotocol = exports.subprotocolsV3.get(protocol);
if (this.#subprotocol === undefined) {
this.#setClosed(new errors_js_1.ProtoError(`Unrecognized WebSocket subprotocol: ${JSON.stringify(protocol)}`));
return;
}
}
for (const callbacks of this.#openCallbacks) {
callbacks.openCallback();
}
this.#openCallbacks.length = 0;
this.#opened = true;
}
#sendToSocket(msg) {
const encoding = this.#subprotocol.encoding;
if (encoding === "json") {
const jsonMsg = (0, index_js_1.writeJsonObject)(msg, json_encode_js_1.ClientMsg);
this.#socket.send(jsonMsg);
}
else if (encoding === "protobuf") {
const protobufMsg = (0, index_js_1.writeProtobufMessage)(msg, protobuf_encode_js_1.ClientMsg);
this.#socket.send(protobufMsg);
}
else {
throw (0, util_js_1.impossible)(encoding, "Impossible encoding");
}
}
/** Get the protocol version negotiated with the server, possibly waiting until the socket is open. */
getVersion() {
return new Promise((versionCallback, errorCallback) => {
this.#getVersionCalled = true;
if (this.#closed !== undefined) {
errorCallback(this.#closed);
}
else if (!this.#opened) {
const openCallback = () => versionCallback(this.#subprotocol.version);
this.#openCallbacks.push({ openCallback, errorCallback });
}
else {
versionCallback(this.#subprotocol.version);
}
});
}
// Make sure that the negotiated version is at least `minVersion`.
/** @private */
_ensureVersion(minVersion, feature) {
if (this.#subprotocol === undefined || !this.#getVersionCalled) {
throw new errors_js_1.ProtocolVersionError(`${feature} is supported only on protocol version ${minVersion} and higher, ` +
"but the version supported by the WebSocket server is not yet known. " +
"Use Client.getVersion() to wait until the version is available.");
}
else if (this.#subprotocol.version < minVersion) {
throw new errors_js_1.ProtocolVersionError(`${feature} is supported on protocol version ${minVersion} and higher, ` +
`but the WebSocket server only supports version ${this.#subprotocol.version}`);
}
}
// Send a request to the server and invoke a callback when we get the response.
/** @private */
_sendRequest(request, callbacks) {
if (this.#closed !== undefined) {
callbacks.errorCallback(new errors_js_1.ClosedError("Client is closed", this.#closed));
return;
}
const requestId = this.#requestIdAlloc.alloc();
this.#responseMap.set(requestId, { ...callbacks, type: request.type });
this.#send({ type: "request", requestId, request });
}
// The socket encountered an error.
#onSocketError(event) {
const eventMessage = event.message;
const message = eventMessage ?? "WebSocket was closed due to an error";
this.#setClosed(new errors_js_1.WebSocketError(message));
}
// The socket was closed.
#onSocketClose(event) {
let message = `WebSocket was closed with code ${event.code}`;
if (event.reason) {
message += `: ${event.reason}`;
}
this.#setClosed(new errors_js_1.WebSocketError(message));
}
// Close the client with the given error.
#setClosed(error) {
if (this.#closed !== undefined) {
return;
}
this.#closed = error;
for (const callbacks of this.#openCallbacks) {
callbacks.errorCallback(error);
}
this.#openCallbacks.length = 0;
for (const [requestId, responseState] of this.#responseMap.entries()) {
responseState.errorCallback(error);
this.#requestIdAlloc.free(requestId);
}
this.#responseMap.clear();
this.#socket.close();
}
// We received a message from the socket.
#onSocketMessage(event) {
if (this.#closed !== undefined) {
return;
}
try {
let msg;
const encoding = this.#subprotocol.encoding;
if (encoding === "json") {
if (typeof event.data !== "string") {
this.#socket.close(3003, "Only text messages are accepted with JSON encoding");
this.#setClosed(new errors_js_1.ProtoError("Received non-text message from server with JSON encoding"));
return;
}
msg = (0, index_js_1.readJsonObject)(JSON.parse(event.data), json_decode_js_1.ServerMsg);
}
else if (encoding === "protobuf") {
if (!(event.data instanceof ArrayBuffer)) {
this.#socket.close(3003, "Only binary messages are accepted with Protobuf encoding");
this.#setClosed(new errors_js_1.ProtoError("Received non-binary message from server with Protobuf encoding"));
return;
}
msg = (0, index_js_1.readProtobufMessage)(new Uint8Array(event.data), protobuf_decode_js_1.ServerMsg);
}
else {
throw (0, util_js_1.impossible)(encoding, "Impossible encoding");
}
this.#handleMsg(msg);
}
catch (e) {
this.#socket.close(3007, "Could not handle message");
this.#setClosed(e);
}
}
// Handle a message from the server.
#handleMsg(msg) {
if (msg.type === "none") {
throw new errors_js_1.ProtoError("Received an unrecognized ServerMsg");
}
else if (msg.type === "hello_ok" || msg.type === "hello_error") {
if (this.#recvdHello) {
throw new errors_js_1.ProtoError("Received a duplicated hello response");
}
this.#recvdHello = true;
if (msg.type === "hello_error") {
throw (0, result_js_1.errorFromProto)(msg.error);
}
return;
}
else if (!this.#recvdHello) {
throw new errors_js_1.ProtoError("Received a non-hello message before a hello response");
}
if (msg.type === "response_ok") {
const requestId = msg.requestId;
const responseState = this.#responseMap.get(requestId);
this.#responseMap.delete(requestId);
if (responseState === undefined) {
throw new errors_js_1.ProtoError("Received unexpected OK response");
}
this.#requestIdAlloc.free(requestId);
try {
if (responseState.type !== msg.response.type) {
console.dir({ responseState, msg });
throw new errors_js_1.ProtoError("Received unexpected type of response");
}
responseState.responseCallback(msg.response);
}
catch (e) {
responseState.errorCallback(e);
throw e;
}
}
else if (msg.type === "response_error") {
const requestId = msg.requestId;
const responseState = this.#responseMap.get(requestId);
this.#responseMap.delete(requestId);
if (responseState === undefined) {
throw new errors_js_1.ProtoError("Received unexpected error response");
}
this.#requestIdAlloc.free(requestId);
responseState.errorCallback((0, result_js_1.errorFromProto)(msg.error));
}
else {
throw (0, util_js_1.impossible)(msg, "Impossible ServerMsg type");
}
}
/** Open a {@link WsStream}, a stream for executing SQL statements. */
openStream() {
return stream_js_1.WsStream.open(this);
}
/** Cache a SQL text on the server. This requires protocol version 2 or higher. */
storeSql(sql) {
this._ensureVersion(2, "storeSql()");
const sqlId = this.#sqlIdAlloc.alloc();
const sqlObj = new sql_js_1.Sql(this, sqlId);
const responseCallback = () => undefined;
const errorCallback = (e) => sqlObj._setClosed(e);
const request = { type: "store_sql", sqlId, sql };
this._sendRequest(request, { responseCallback, errorCallback });
return sqlObj;
}
/** @private */
_closeSql(sqlId) {
if (this.#closed !== undefined) {
return;
}
const responseCallback = () => this.#sqlIdAlloc.free(sqlId);
const errorCallback = (e) => this.#setClosed(e);
const request = { type: "close_sql", sqlId };
this._sendRequest(request, { responseCallback, errorCallback });
}
/** Close the client and the WebSocket. */
close() {
this.#setClosed(new errors_js_1.ClientError("Client was manually closed"));
}
/** True if the client is closed. */
get closed() {
return this.#closed !== undefined;
}
}
exports.WsClient = WsClient; |
import { Button, Form, Input, Spin, Card } from 'antd';
import { useNavigate } from 'react-router-dom';
import { useMutation, useQuery } from '@apollo/client';
import { EDIT_USER } from '../utils/mutations';
import { QUERY_ME } from '../utils/queries';
import { LoadingOutlined } from '@ant-design/icons';
import { toast } from 'react-toastify';
const UserEdit = () => {
// Queries and mutations to use apollo client
const { data, error, loading, refetch } = useQuery(QUERY_ME);
const [editUser, { loading: loadingEdit }] = useMutation(EDIT_USER);
const navigate = useNavigate();
// Update the user info
const handleFormSubmit = async (values) => {
if (values?.password == values?.confirmPassword) {
try {
const { data } = await editUser({
variables: { ...values },
});
toast.success('Successfully edited')
refetch();
navigate('/');
} catch (err) {
toast.error('Something went wrong');
}
} else {
toast.error('Passwords must match');
}
};
// Before rendering the main content, show spinner while loading.
if (loading) {
return (
<>
{loading && (
<Spin tip="Loading" size="large">
<div className="content" />
</Spin>
)}
</>
);
}
return (
<Card
style={{
maxWidth: 900,
margin: 'auto',
padding: '1rem',
}}
>
<Form
name="basic"
labelCol={{
span: 4,
}}
onFinish={handleFormSubmit}
initialValues={{
username: data?.me?.username,
email: data?.me?.email,
}}
layout="vertical"
>
<h2 style={{fontSize: '1.7rem', marginBottom: '1rem'}}>Edit User</h2>
<Form.Item
label="Username"
name="username"
rules={[
{
required: true,
message: 'Please input your username!',
},
]}
>
<Input />
</Form.Item>
<Form.Item
label="Email"
name="email"
rules={[
{
required: true,
message: 'Please input your email!',
},
{
type: 'email',
message: 'Please enter a valid email address!',
},
]}
>
<Input />
</Form.Item>
<Form.Item label="Password" name="password">
<Input.Password />
</Form.Item>
<Form.Item label="Confirm Password" name="confirmPassword">
<Input.Password />
</Form.Item>
<Form.Item>
<Button type="primary" htmlType="submit">
Edit
{loadingEdit && (
<Spin
indicator={
<LoadingOutlined
style={{
fontSize: 16,
color: 'white',
marginLeft: '.5rem',
}}
spin
/>
}
/>
)}
</Button>
<Button onClick={() => {navigate('/')}} style={{marginLeft: 10}}>
Cancel
</Button>
</Form.Item>
</Form>
</Card>
);
};
export default UserEdit; |
README qmail SMTP Authentication
Scope:
------
This patch supports RFC 2554 "SMTP Service Extension for Authentication" and
RFC 4409 "Message Submission for Mail" for
* qmail-smtpd and
* qmail-remote
and supports commonly the AUTH methods
- CRAM-MD5
- LOGIN (unsecure)
- PLAIN (unsecure)
Additionally, RFC 1870 is honoured ("SMTP Service Extension for Message Size Declaration").
For more technical details see: http://www.fehcom.de/qmail/docu/smtpauth.html.
Installation:
-------------
* Untar the source in the qmail-1.03 home direcotry.
* Run ./install_auth.
* Re-make qmail.
Setup for qmail-smtpd:
----------------------
1. Prereqs:
In order to use SMTP Authentication you have to use a 'Pluggable Authentication Module'
PAM to be called by qmail-smtpd; typically
/var/qmail/bin/qmail-smtpd /bin/checkpassword true 2>&1
Since qmail-smtpd does not run as root, checkpassword has to be made sticky.
There is no need to include additionally the hostname in the call.
In order to compute the CRAM-MD5 challenge, qmail-smtpd uses the 'tcplocalhost' information.
2. Invocation:
In order activate SMTP authentication, you need to provide the environment
variable 'SMTPAUTH' to qmail-smtpd.
Possible choices:
a) SMTPAUTH=""; qmail-smtpd supports auth of type PLAIN and/or LOGIN.
b) SMTPAUTH="+cram"; qmail-smtpd will additionally annonce CRAM-MD5,
this requires a CRAM-MD5 supporting PAM.
c) SMTPAUTH="cram"; qmail-smtpd will only annonce CRAM-MD5.
d) SMTPAUTH="!"; this instructs qmail-smtpd to require (any type) authentication for this connection.
This behavior is equivalent to the Submission feaure.
e) SMTPAUTH="!cram"; same as d) but now CRAM-MD5 is the only method instead.
Setup for qmail-remote:
-----------------------
SMTP Authentication with qmail-remote is faclitated by two means:
a) SMTP Authentication by sender/sending domain as provided in the 'Mail From:'
The control file 'authsenders' which works similar to 'control/smtproutes'
but with additional authentication information (username + password):
@example.com:relay.example.com|user|passwd
info@example.com:relay.example.com:26|infouser|infopasswd
:mailrelay.example.com:587|e=mc2|testpass
Note: The choice of the AUTH method depends on the capabilities of the server.
b) SMTP Authentication by recipient domain:
The control file 'smtproutes' is enhanced with the authentication information:
authdomain.com:mx.authdomain.com:125|myuserid|mypassword
:mailrelay.example.com:587|e=mc2|testpass
Historical Notes:
-----------------
SMTP authentication for qmail-smtpd was initially provided by Krysztof Dabrowski (version 0.31):
Changes wrt. Krysztof Dabrowski's patch:
* Avoid the 'hostname' in the call of the PAM.
* Confirm to Dan Bernstein's checkpassword interface even for CRAM-MD5.
* Doesn't close FD 2; thus not inhibiting logging to STDERR.
* Fixed bugs in base64.c.
* Modified unconditional close of FD 3 in order to sustain reading of 'control/morecpthosts.cdb'.
* Evaluation of the (informational) Mail From: < > Auth=username.
* Additional support for the advertised "Size" via 'Mail From: <return-path> SIZE=123456780' (RFC 1870).
* RFC 3848 conformance for Received header in case of SMTP Auth (keyword ESMTPA).
* Added SMTPAUTH environment variable.
* The particular Submission feature has been removed; obsolete.
SMTP authentication for qmail-remote is taken from Bjoern Kalkbrenner.
Changes wrt. Bjoern Kalkbrenner's patch (version 0.0.1 / 20020715):
* Uniform, modular support for LOGIN and PLAIN.
* Added 'Mail From: < > Auth=username' information in provisionally XTEXT format.
* Added CRAM-MD5 support.
* Added authentication by recipient domain.
Release Notes:
--------------
Version: Notes: Date:
-------------------------------------------------------------------
0.5.9 qmail-smtpd AUTH (only) 25.3.2008
0.6.9 qmail-authentication 1.2.2010
0.7.0 Based on qmail-authentication 0.69
including now CRAM-MD5 support
for qmail-remote 31.7.2010
0.7.1 cosmetics for qmail-remote 5.8.2010
0.7.2 authorization-id = authentication-id
for qmail-remote;
added SMTPAUTH environment variable
for qmail-smtpd; backport from SC 2.7 29.4.2012
0.7.3 Fixed missing AUTH for qmai-smtpd announcement.
Improved SUBMISSION port handling. 2.5.2012
0.7.4 Fixed missing 250 statements for AUTH.
Changed SMTPAUTH settings for cram-md5 18.5.2012
0.7.5 Fixed bug in qmail-remote not respecting
announced AUTH types. Tx. Callum Gibson.
Added '432' server code evaluation for
AUTH password expired in qmail-remote. 23.10.2012
0.7.6 Fixed order of SMTP commands (tx roberto).
02.02.2013
0.8.0 Added authentication by recipient domain
for qmail-remote.
Removed SUBMISSION port feature for
qmail-smtpd. 22.03.2013
0.8.1 Added SMTPAUTH="!+crom" feature. 24.03.2013
0.8.2 Bug fix: qmail-smtpd ACCEPTS auth commands
even if SMTPAUTH="-". (tx chris). 21.01.2015
0.8.3 Fixed bug in MD5 calculation for AMD64.
Fixed 'die_nomem' bug in qmail-smtpd. 23.08.2015
Erwin Hoffmann - Hoehn 2015-08-23 (www.fehcom.de) |
{% extends 'base.html.twig' %}
{% block title %}Nouveau Medecin
{% endblock %}
{% block content %}
<div class="page-wrapper">
<div class="content">
<div class="row">
<div class="col-sm-12">
<div class="card">
<div class="card-body">
{{ form_start(form, {'attr': {'novalidate': 'novalidate'}}) }}
<div class="row">
<div class="col-12">
<div class="form-heading">
<h4>Ajouter Medecin</h4>
</div>
</div>
<div class="col-12 col-md-6 col-xl-4">
<div class="form-group local-forms">
<label>Nom
<span class="login-danger">*</span>
</label>
{{ form_widget(form.nom, {attr:{'class':'form-control'}}) }}
{% if form_errors(form.nom) is not empty %}
<div class="alert alert-danger" {{ form_errors(form.nom) }}
</div>
{% endif %}
</div>
</div>
<div class="col-12 col-md-6 col-xl-4">
<div class="form-group local-forms">
<label>Prenom
<span class="login-danger">*</span>
</label>
{{ form_widget(form.prenom,
{attr:{'class':'form-control'}}) }}
{% if form_errors(form.prenom) is not empty %}
<div class="alert alert-danger" {{ form_errors(form.prenom) }}
</div>
{% endif %}
</div>
</div>
<div class="col-12 col-md-6 col-xl-4">
<div class="form-group local-forms">
<label>Carte D'identité
<span class="login-danger">*</span>
</label>
{{ form_widget(form.cin,
{attr:{'class':'form-control'}}) }}
{% if form_errors(form.cin) is not empty %}
<div class="alert alert-danger" {{
form_errors(form.cin) }} </div>
{% endif %}
</div>
</div>
<div class="col-12 col-md-6 col-xl-4">
<div class="form-group local-forms">
<label>Sexe
<span class="login-danger">*</span>
</label>
{{ form_widget(form.sexe, {attr:{'class':'form-control'}}) }}
</div>
</div>
<div class="col-12 col-md-6 col-xl-4">
<div class="form-group local-forms">
<label>Telephone
<span class="login-danger">*</span>
</label>
{{ form_widget(form.telephone,
{attr:{'class':'form-control'}}) }}
{% if form_errors(form.telephone) is not empty %}
<div class="alert alert-danger" {{
form_errors(form.telephone) }} </div>
{% endif %}
</div>
</div>
<div class="col-12 col-md-6 col-xl-4">
<div class="form-group local-forms">
<label>Telephone Fixe
<span class="login-danger">*</span>
</label>
{{ form_widget(form.fixe,
{attr:{'class':'form-control'}}) }}
{% if form_errors(form.fixe) is not empty %}
<div class="alert alert-danger" {{
form_errors(form.fixe) }} </div>
{% endif %}
</div>
</div>
<div class="col-12 col-md-6 col-xl-6">
<div class="form-group local-forms">
<label>Gouvernorat<span class="login-danger">*</span>
</label>
{{ form_widget(form.gouvernorat, {attr:{'class':'form-control'}}) }}
</div>
</div>
<div class="col-12 col-md-6 col-xl-6">
<div class="form-group local-forms">
<label>Titre
<span class="login-danger">*</span>
</label>
{{ form_widget(form.titre, {attr:{'class':'form-control'}}) }}
</div>
</div>
<div class="col-12 col-md-6 col-xl-4">
<div class="form-group local-forms">
<label>Email
<span class="login-danger">*</span>
</label>
{{ form_widget(form.email,
{attr:{'class':'form-control'}}) }}
{% if form_errors(form.email) is not empty %}
<div class="alert alert-danger" {{
form_errors(form.email) }} </div>
{% endif %}
</div>
</div>
<div class="col-12 col-md-6 col-xl-4">
<div class="form-group local-forms">
<label>
Password
<span class="login-danger">*</span>
</label>
{{ form_widget(form.password, {attr:{'class':'form-control'}}) }}
{{ form_errors(form.password) }}
</div>
</div>
<div class="col-12 col-md-6 col-xl-4">
<div class="form-group local-forms">
<label>Confirme Password
<span class="login-danger">*</span>
</label>
{{ form_widget(form.confirm_password, {attr:{'class':'form-control'}}) }}
{{ form_errors(form.confirm_password) }}
</div>
</div>
<div class="col-12 col-md-6 col-xl-4">
<div class="form-group local-forms">
<label>Tarif<span class="login-danger">*</span>
</label>
{{ form_widget(form.tarif,
{attr:{'class':'form-control'}}) }}
{% if form_errors(form.tarif) is not empty %}
<div class="alert alert-danger" {{ form_errors(form.tarif) }}
</div>
{% endif %}
</div>
</div>
<div class="col-12 col-md-6 col-xl-4">
<div class="form-group local-forms">
<label>Spécialité<span class="login-danger">*</span>
</label>
{{ form_widget(form.specialites, {attr:{'class':'form-control'}}) }}
</div>
</div>
<div class="col-12 col-md-6 col-xl-4">
<div class="form-group local-forms">
<label>CNAM<span class="login-danger">*</span>
</label>
{{ form_widget(form.cnam, {attr:{'class':'form-control'}}) }}
</div>
</div>
<div class="col-12 col-sm-12">
<div class="form-group local-forms">
<label>Address
<span class="login-danger">*</span>
</label>
{{ form_widget(form.adresse,
{attr:{'class':'form-control'}}) }}
{% if form_errors(form.adresse) is not empty %}
<div class="alert alert-danger" {{ form_errors(form.adresse) }}
</div>
{% endif %}
</div>
</div>
<div class="col-12 col-sm-12">
<div class="form-group local-forms">
<label>Addresse Cabinet
<span class="login-danger">*</span>
</label>
{{ form_widget(form.adresse_cabinet,
{attr:{'class':'form-control'}}) }}
{% if form_errors(form.adresse_cabinet) is not empty %}
<div class="alert alert-danger" {{ form_errors(form.adresse_cabinet) }}
</div>
{% endif %}
</div>
</div>
<div class="col-12 col-sm-12">
<div class="form-group local-forms">
<label>Diplome et Formation<span class="login-danger">*</span>
</label>
{{ form_widget(form.diplome_formation,
{attr:{'class':'form-control'}}) }}
{% if form_errors(form.diplome_formation) is not empty %}
<div class="alert alert-danger" {{ form_errors(form.diplome_formation) }}
</div>
{% endif %}
</div>
</div>
<div class="container">
<div class="row">
<div class="col-lg-12">
<div class="form-group">
<div class="call-option file-option ">
<input type="file" id="radio1" name="selector" class="option-radio">
<a class="btn-profile"><img src="{{asset('client/assets/img/icons/file.png')}}" alt=""></a>
<label for="radio1" class="call-lable verify-lable verify-file">
Upload Image</label>
{{ form_widget(form.photo, {attr:{'class':'file'}}) }}
{{ form_errors(form.photo) }}
</div>
</div>
<div class="col-12">
<div class="doctor-submit text-end">
<div class="text-right">
{{ form_row(form.Enregistrer , {attr:{'class':'btn btn-primary save-btn'}}) }}
</div>
</div>
</div>
</div>
{{ form_end(form) }}
</div>
</div>
</div>
</div>
</div>
</div>
{% endblock %} |
// 这题的关键在于,要知道,当手上拿到不同的key的情况下,是不同的state。我想到了一个例子,如下。这种情况要走三步,而不是BFS简单的1步。看了答案才知道用如下的解法。有人用bit 方法来存state,会更快。但是我不知道怎么做。我这里用TreeSet,最主要的是在visited, equals的时候,需要是有序的。也有人用StringBuilder来存,因为拿到锁的顺序永远是固定的,用BFS的话。锁只会更多,不会更少。如果确定每一把锁只有一个,则可以有优化的解法。不要太纠结,我觉得能写出来这样,已经不错了。
class Solution {
public int shortestPathAllKeys(String[] grid) {
int n = grid.length, m = grid[0].length(), startX = 0, startY = 0;
TreeSet<Character> targetKeys = new TreeSet<>();
for (int x = 0; x < n; x++) {
for (int y = 0; y < m; y++) {
char c = grid[x].charAt(y);
if (Character.isLowerCase(c)) {
targetKeys.add(c);
} else if (c == '@') {
startX = x;
startY = y;
}
}
}
int[][] moves = new int[][]{{-1,0}, {0, -1}, {0, 1}, {1, 0}};
Set<String> visited = new HashSet<>();
Queue<State> queue = new LinkedList<>();
int steps = 0;
State startState = new State(startX, startY, new TreeSet<>());
queue.add(startState);
visited.add(startState.toString());
while (!queue.isEmpty()) {
int levelSize = queue.size();
while (levelSize-- > 0) {
State state = queue.poll();
if (state.keys.equals(targetKeys)) return steps;
for (int[] move : moves) {
int nextX = state.x + move[0], nextY = state.y + move[1];
if (nextX < 0 || nextY < 0 || nextX >= n || nextY >= m) continue;
char c = grid[nextX].charAt(nextY);
if (c == '#' || Character.isUpperCase(c) && !state.keys.contains(Character.toLowerCase(c))) continue;
TreeSet<Character> newKeys = new TreeSet<>(state.keys);
if (Character.isLowerCase(c)) {
newKeys.add(c);
}
State nextState = new State(nextX, nextY, newKeys);
if (!visited.contains(nextState.toString())) {
queue.offer(nextState);
visited.add(nextState.toString());
}
}
}
steps++;
}
return -1;
}
private class State {
int x, y;
TreeSet<Character> keys;
State(int x, int y, TreeSet<Character> keys) {
this.x = x;
this.y = y;
this.keys = keys;
}
public String toString() {
return x + "," + y + "," + keys.toString();
}
}
} |
import { Injectable } from '@angular/core';
import { Http, Response, RequestOptions, Headers, Request, RequestMethod } from '@angular/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/do';
import 'rxjs/add/operator/publishReplay';
let sending;
let sent;
let headers = null;
let options = null;
let thisDate = new Date();
let utcDate = new Date(thisDate.toUTCString());
utcDate.setHours(utcDate.getHours() - 8);
let myDate = new Date(utcDate);
let dailyDate = myDate.toISOString().slice(0, 10).replace(/-/g, "");
//console.log(dailyDate, 'today\'s date');
@Injectable()
export class InfoService {
info: Observable < any > = null;
stats: Observable < any > = null;
env: Observable < any > = null;
gameid: Observable < any > = null;
daily: Observable < any > = null;
schedule: Observable < any > = null;
score: Observable < any > = null;
play: Observable <any> = null;
constructor(private http: Http) {}
sendHeaderOptions(h, o) {
console.log('got headers & options in info service...')
headers = h;
options = o;
}
getDailySchedule() {
//get all games for today get game ID and find a pitchers opponent
if (!this.schedule) {
console.log('getting stat data from API...');
let url5 = 'https://api.mysportsfeeds.com/v1.2/pull/mlb/2018-regular/daily_game_schedule.json?fordate='+dailyDate;
this.schedule = this.http.get(url5, options)
.map(response => response.json())
}
return this.schedule;
}
getEnv() {
console.log("trying to get heroku env...");
this.env = this.http.get('/heroku-env').map(response => response)
return this.env;
}
sendStats(statsArray) {
console.log("sending stats to service...");
sending = statsArray;
}
getSentStats() {
console.log("stats sent to component...");
sent = sending;
return sent;
}
clearCache() {
this.info = null;
}
getInfo() {
if (!this.info) {
let url2 = 'https://api.mysportsfeeds.com/v1.2/pull/mlb/2018-regular/active_players.json?position=P';
console.log('getting player info data from API...');
this.info = this.http.get(url2, options)
.map(response => response.json())
.publishReplay(1) // this tells Rx to cache the latest emitted value
.refCount()
}
return this.info;
}
getStats() {
if (!this.stats) {
console.log('getting stat data from API...');
let url = 'https://api.mysportsfeeds.com/v1.2/pull/mlb/2018-regular/cumulative_player_stats.json?position=P&sort=STATS.Pitching-NP.D&limit=180';
this.stats = this.http.get(url, options)
.map(response => response.json())
}
return this.stats;
}
getGameId() {
if (!this.gameid) {
console.log('getting pitch speed data from API...');
let url3 = 'https://api.mysportsfeeds.com/v1.2/pull/mlb/2018-regular/full_game_schedule.json?date=from-8-days-ago-to-2-days-ago';
this.gameid = this.http.get(url3, options)
.map(response => response.json())
}
return this.gameid;
}
getDaily() {
if (!this.daily) {
let url4 = 'https://api.mysportsfeeds.com/v1.2/pull/mlb/2018-regular/daily_player_stats.json?fordate='+dailyDate+'&position=P';
console.log('getting daily stats for pitchers from API...');
this.daily = this.http.get(url4, options)
.map(response => response.json())
}
return this.daily;
}
getScore() {
if (!this.score) {
let url5 = 'https://api.mysportsfeeds.com/v1.2/pull/mlb/2018-regular/scoreboard.json?fordate='+dailyDate;
console.log('getting daily scores of todays games from API...');
this.score = this.http.get(url5, options)
.map(response => response.json())
}
return this.score;
}
getPlay() {
if (!this.play) {
let url6 = 'https://api.mysportsfeeds.com/v1.2/pull/mlb/2018-regular/game_playbyplay.json?gameid=20171004-COL-ARI;'
console.log('getting daily scores of todays games from API...');
this.play = this.http.get(url6, options)
.map(response => response.json())
}
return this.play;
}
} |
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:the_helper/src/common/extension/build_context.dart';
import 'package:the_helper/src/common/widget/search_bar/river_debounce_search_bar.dart';
import 'package:the_helper/src/features/news/domain/news_query.dart';
import 'package:the_helper/src/features/news/presentation/news_list/controller/news_list_mod_controller.dart';
class OrganizationNewsListAppBar extends ConsumerWidget {
const OrganizationNewsListAppBar({super.key});
@override
Widget build(BuildContext context, WidgetRef ref) {
final showSearchBox = ref.watch(showSearchBoxProvider);
ref.watch(searchPatternProvider);
final sort = ref.watch(sortProvider);
return SliverAppBar(
leading: showSearchBox
? BackButton(
onPressed: () =>
ref.read(showSearchBoxProvider.notifier).state = false,
)
: null,
title: showSearchBox
? RiverDebounceSearchBar.autoDispose(
provider: searchPatternProvider,
small: true,
)
: const Text(
'Organization News',
),
floating: true,
actions: !showSearchBox
? [
IconButton(
icon: const Icon(Icons.search),
onPressed: () {
ref.read(showSearchBoxProvider.notifier).state = true;
},
),
PopupMenuButton(
icon: const Icon(Icons.sort),
position: PopupMenuPosition.under,
onSelected: (value) {
ref.read(sortProvider.notifier).state = value;
},
itemBuilder: (context) => [
NewsQuerySort.dateDesc,
NewsQuerySort.popularityDesc,
NewsQuerySort.viewsDesc
]
.map(
(item) => PopupMenuItem(
value: item,
child: Text(
'Sort by ${item.substring(1)}',
style: TextStyle(
color: sort == item
? context.theme.primaryColor
: null,
),
),
),
)
.toList(),
),
]
: null,
);
}
} |
package com.yedam.java.ch0605;
public class Car {
// 필드
public String model;
public int speed;
// 정적 필드 - 생산 수량
public static int count;
// 생성자
// 생성자 만들었기 때문에 자바는 기본 생성자 만들지 않음
public Car(String model) {
this.model = model;
// car라는 생성자를 호출한다는 것은 이미 인스턴스를 만들겠다고 자바한테 예고한것 => 자바는 this를 생성할 객체로 인식한다
Car.count++; // static이 쓰인 필드도 this가능한데 쓰지말자 매개변수 이름과 정적필드 이름 동일하면
// 클래스명.정적필드명으로 쓰자
}
// 메소드
public void setSpeed(int speed) {
this.speed = speed;
}
public void run() {
for(int i = 10; i <= 50; i += 10) {
this.setSpeed(i);
System.out.println(this.model + "가 달립니다.(시속:" + this.speed + "km/h)");
}
}
} |
# -*- coding: utf-8 -*-
# Example code for telegrambot.py module
from telegram.ext import CommandHandler, MessageHandler, Filters
from django_telegrambot.apps import DjangoTelegramBot
from django.contrib.auth.models import User
from loginsys.models import Link_with_email
import logging
logger = logging.getLogger(__name__)
# Define a few command handlers. These usually take the two arguments bot and
# update. Error handlers also receive the raised TelegramError object in error.
def start(bot, update):
row_personal_id = update.message.text
personal_id = row_personal_id[7:]
chat_id = update.message.chat_id
our_user = User.objects.get(pk = personal_id)
link = Link_with_email.objects.create(email = our_user.email,chat_id = chat_id,get_notice = True)
link.save()
bot.sendMessage(update.message.chat_id, text=our_user.email)
def startgroup(bot, update):
bot.sendMessage(update.message.chat_id, text='Hi!')
#bot.sendMessage(update.message.chat_id, text=update.start)
def me(bot, update):
bot.sendMessage(update.message.chat_id, text='Your information:\n{}'.format(update.effective_user))
def chat(bot, update):
bot.sendMessage(update.message.chat_id, text='This chat information:\n {}'.format(update.effective_chat))
def forwarded(bot, update):
bot.sendMessage(update.message.chat_id, text='This msg forwaded information:\n {}'.format(update.effective_message))
def help(bot, update):
bot.sendMessage(update.message.chat_id, text='Help!')
def echo(bot, update):
update.message.reply_text(update.message.text)
def error(bot, update, error):
logger.warning('Update "%s" caused error "%s"' % (update, error))
def main():
logger.info("Loading handlers for telegram bot")
# Default dispatcher (this is related to the first bot in settings.TELEGRAM_BOT_TOKENS)
dp = DjangoTelegramBot.dispatcher
# To get Dispatcher related to a specific bot
# dp = DjangoTelegramBot.getDispatcher('BOT_n_token') #get by bot token
# dp = DjangoTelegramBot.getDispatcher('BOT_n_username') #get by bot username
# on different commands - answer in Telegram
dp.add_handler(CommandHandler("start", start))
dp.add_handler(CommandHandler("help", help))
dp.add_handler(CommandHandler("startgroup", startgroup))
dp.add_handler(CommandHandler("me", me))
dp.add_handler(CommandHandler("chat", chat))
dp.add_handler(MessageHandler(Filters.forwarded , forwarded))
# on noncommand i.e message - echo the message on Telegram
dp.add_handler(MessageHandler(Filters.text, echo))
# log all errors
dp.add_error_handler(error) |
using System.Data.Entity;
using LinqKit;
using System.Linq.Dynamic.Core;
using System.Linq.Expressions;
using System.Reflection;
using System.Text.RegularExpressions;
using Domain.Common.PagedList;
using Mapster;
using Domain.Common.Queries.Interface;
namespace Persistence.Common
{
internal static class EntityFrameworlExtensions
{
public static IQueryable<TEntity> WhereWithExist<TEntity>(this IQueryable<TEntity> query,
Expression<Func<TEntity, bool>>? condition = null)
where TEntity : class
{
ArgumentNullException.ThrowIfNull(query, nameof(query));
if (condition != null)
{
return query.Where(condition.AddExistCondition());
}
return query;
}
public static IQueryable<TEntity> WhereByStringWithExist<TEntity>(this IQueryable<TEntity> query,
string? condition = null)
where TEntity : class
{
string existCondition = "e => e.IsDeleted = false";
ArgumentNullException.ThrowIfNull(query, nameof(query));
if (!string.IsNullOrEmpty(condition))
{
return query.Where(existCondition + "&&" + condition);
}
return query.Where(existCondition);
}
/// <summary>
/// Formmate (fieldNname:(asc|desc))
/// </summary>
/// <typeparam name="TEntity"></typeparam>
/// <param name="query"></param>
/// <param name="orderByString"></param>
/// <returns></returns>
/// <exception cref="ArgumentException"></exception>
public static IQueryable<TEntity> OrderByWithFormmat<TEntity>(this IQueryable<TEntity> query, string? orderByString)
{
if (string.IsNullOrEmpty(orderByString))
return query;
ArgumentNullException.ThrowIfNull(query, nameof(query));
if (Regex.Match(orderByString, "^\\s*\\w+\\s*:\\s*(asc|desc)\\s*(?:,\\s*\\w+\\s*:\\s*(asc|desc)\\s*)*$\r\n").Success)
throw new ArgumentException("orderByString is invalid formmat");
var orderbyStringFmoratted = orderByString.Replace(":", " ");
return query.OrderBy(orderbyStringFmoratted);
}
public static IQueryable<TEntity> IncludeIf<TEntity, TProperty>(
this IQueryable<TEntity> query,
bool condition,
Expression<Func<TEntity, TProperty>> predicate)
{
if (condition == true)
{
query.Include(predicate);
}
return query;
}
public static string GetPrimaryKeyName<TEntity>()
where TEntity : class
{
var entityIdName = typeof(TEntity).Name + "Id";
var primaryKeyProperty = typeof(TEntity).GetProperty(entityIdName);
if (primaryKeyProperty == null)
{
throw new ArgumentException($"Entity {typeof(TEntity).Name} has not Id property");
}
return primaryKeyProperty.Name;
}
public static IQueryable<TResult> SelectWithField<TEntity, TResult>(this IQueryable<TEntity> query,
Expression<Func<TEntity, TResult>>? selector = null)
where TEntity : class
where TResult : class
{
ArgumentNullException.ThrowIfNull(query, nameof(query));
if (selector == null)
return query.ProjectToType<TResult>();
return query.Select(selector);
}
public static async Task<IPagedList<TResult>> ToPagedListAsync<TEntity, TResult>(this IQueryable<TEntity> query,
IPagingQuery<TResult> pagingQuery)
where TEntity : class
where TResult : class
{
var pagedList = new PagedList<TResult>();
var resultQuery = query.ProjectToType<TResult>();
await pagedList.LoadDataAsync(resultQuery, pagingQuery);
return pagedList;
}
public static async Task<IPagedList<TEntity>> ToPagedListAsync<TEntity>(this IQueryable<TEntity> query,
IPagingQuery<TEntity> pagingQuery)
where TEntity : class
{
pagingQuery ??= new PagingQuery<TEntity>();
var pagedList = new PagedList<TEntity>();
await pagedList.LoadDataAsync(query, pagingQuery);
return pagedList;
}
#region Private Methods
private static Expression<Func<TEntity, bool>> AddExistCondition<TEntity>(this Expression<Func<TEntity, bool>>? filter)
where TEntity : class
{
PropertyInfo? isDeletedProperty = typeof(TEntity).GetProperty("IsDeleted");
if (isDeletedProperty == null)
throw new ArgumentNullException($"Entity {typeof(TEntity).Name} has not IsDeleted property");
ParameterExpression parameter = Expression.Parameter(typeof(TEntity), "isDeleted");
MemberExpression isDeletedPropertyAccess = Expression.Property(parameter, isDeletedProperty);
ConstantExpression isDeleted_is_false = Expression.Constant(false);
BinaryExpression equalityExpression = Expression.Equal(isDeletedPropertyAccess, isDeleted_is_false);
Expression<Func<TEntity, bool>> isNotDeleteCondition = Expression.Lambda<Func<TEntity, bool>>(equalityExpression, parameter);
return filter == null
? isNotDeleteCondition
: isNotDeleteCondition.And(filter);
}
#endregion
}
} |
/*
* CS 315 Programming Assignment 3: Graphs
* Description: Implements Dijkstra's algorithm, along with Graph and minheap implementation
* Jacob Schuetter
* Created 3 Nov 2023
* History:
* 3-Nov: Implemented testHeap function to ensure functionality
* 6-Nov: Implemented testGraph function with BFS functionality to test Graph class and current member functions
* 8-Nov: Implemented Dijkstra functionality into testGraph function
*/
#include <stdlib.h>
#include <cstdlib>
#include <string>
#include <iostream>
#include "Graph.h"
#include "Graph.cpp""
#include "Minheap.h"
#include "Minheap.cpp"
#include "PQueue.h"
using namespace std;
const string NODES_PATH = "RomaniaVertices.txt";
const string EDGES_PATH = "RomaniaEdges.txt";
void testHeap(int size);
void testGraph();
int main() {
//testHeap(10);
testGraph();
return 0;
}
//Test heap class - draw trees!
void testHeap(int size) {
//Generate random vector of numbers
vector<int> values;
Minheap<int> heap;
srand(time(NULL));
for (int i = 0; i < size; i++) {
int r = rand() % 100;
values.push_back(r);
heap.ins(r, r);
}
cout << "Values generated: \n";
for (auto i = values.begin(); i != values.end(); i++) {
cout << *i << ", ";
}
cout << endl;
heap.print();
}
//Test graph class - all algorithm member functions
void testGraph() {
Graph<string> romania;
romania.build(NODES_PATH, EDGES_PATH);
//cout << "Initial construction\n";
romania.print();
cout << endl;
//Determine which edges to test
vector<string> destinations = { "Sibiu", "Craiova", "Bucharest" };
vector<vector<string>> paths = romania.bfs_findPath("Arad", destinations);
//Print out shortest paths
cout << "Shortest paths (unweighted): " << endl;
romania.printPaths(paths);
//Test Dijkstra's algorithm
vector<string> pathDijkstra = romania.dijkstra_findPath("Arad", "Bucharest");
cout << "Shortest path (weighted): " << endl;
romania.printPaths(pathDijkstra);
//Test Prim's Algorithm
romania.prim("Arad");
unordered_map<string, string> pred = romania.getPredecessors();
cout << "Prim's Minimum Spanning Tree\n";
cout << "Source node: Arad\n";
cout << setw(15) << "Vertex: " << " | Predecesor: \n";
for (auto it = pred.begin(); it != pred.end(); it++) {
cout << setw(15) << it->first << " | " << it->second << endl;
}
} |
import { Component, OnInit, ViewChild } from '@angular/core';
import {
MatDialog,
MatDialogRef,
MAT_DIALOG_DATA,
} from '@angular/material/dialog';
import { MatPaginator } from '@angular/material/paginator';
import { MatSort } from '@angular/material/sort';
import { MatTableDataSource } from '@angular/material/table';
import {
DialogComponent,
DialogComponentCategory,
DialogComponentContent,
} from './dialog/dialog.component';
import { ApiService } from './services/api.service';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.scss'],
})
export class AppComponent implements OnInit {
title = 'angular-crud';
displayedColumns: string[] = [
'productName',
'category',
'freshness',
'date',
'price',
'comment',
'action',
];
dataSource!: MatTableDataSource<any>;
@ViewChild(MatPaginator) paginator!: MatPaginator;
@ViewChild(MatSort) sort!: MatSort;
value: string = '';
constructor(private dialog: MatDialog, private api: ApiService) {}
ngOnInit(): void {
this.getAllProducts();
}
openDialog() {
this.dialog
.open(DialogComponent, {
width: '30%',
})
.afterClosed()
.subscribe((val) => {
if (val === 'save') {
this.getAllProducts();
}
});
}
getAllProducts() {
this.api.getProduct().subscribe({
next: (res) => {
// console.log(res);
this.dataSource = new MatTableDataSource(res);
this.dataSource.paginator = this.paginator;
this.dataSource.sort = this.sort;
},
error: (err) => {
console.log('Error found! ' + err);
},
});
}
editProduct(row: any) {
this.dialog
.open(DialogComponent, {
width: '30%',
data: row,
})
.afterClosed()
.subscribe((val) => {
this.getAllProducts();
});
}
deleteProduct(id: number) {
this.dialog
.open(DialogComponentContent, {
width: '30%',
})
.afterClosed()
.subscribe((val) => {
if (val) {
this.api.deleteProduct(id).subscribe({
next: (res) => {
alert('Product Deleted Successfully');
this.getAllProducts();
},
error: () => {
alert('Error while deleting the product');
},
});
}
});
}
onClear() {
this.value = '';
this.getAllProducts();
}
// Category
openDialogCategory() {
this.dialog.open(DialogComponentCategory, {
width: '30%',
});
// .afterClosed()
// .subscribe((val) => {
// if (val === 'save') {
// this.getAllProducts();
// }
// });
}
getAllCategories() {
this.api.getCategory().subscribe({
next: (res) => {
console.log(res);
// this.dataSource = new MatTableDataSource(res);
// this.dataSource.paginator = this.paginator;
// this.dataSource.sort = this.sort;
},
error: (err) => {
console.log('Error found! ' + err);
},
});
}
applyFilter(event: Event) {
const filterValue = (event.target as HTMLInputElement).value;
this.dataSource.filter = filterValue.trim().toLowerCase();
if (this.dataSource.paginator) {
this.dataSource.paginator.firstPage();
}
}
} |
/*
* Copyright (C) 2004
* Swiss Federal Institute of Technology, Lausanne. All rights reserved.
*
* Developed at the Autonomous Systems Lab.
* Visit our homepage at http://asl.epfl.ch/
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
* USA
*/
#include "Polygon.hpp"
#include <sfl/util/functors.hpp>
#include <cmath>
#include <iostream>
using std::shared_ptr;
using namespace std;
namespace sfl {
Polygon::
Polygon()
{
}
Polygon::
Polygon(const Polygon & p)
{
for(pointlist_t::const_iterator i(p.m_point.begin());
i != p.m_point.end();
++i)
AddPoint((*i)->X(), (*i)->Y());
}
void Polygon::
AddPoint(double x,
double y)
{
m_point.push_back(shared_ptr<Point>(new Point(x, y)));
}
shared_ptr<Polygon> Polygon::
CreateConvexHull()
const
{
// constructs ccw convex hull
// (ccw in the sense of the list of resulting points)
shared_ptr<Polygon> hull(new Polygon());
if(m_point.empty())
return hull;
// find lowest point in vector
pointlist_t::const_iterator ipoint(m_point.begin());
shared_ptr<const Point> lowest( * ipoint);
++ipoint;
while(ipoint != m_point.end()){
if(((*ipoint)->Y() < lowest->Y()) || // take lowest, or
(((*ipoint)->Y() == lowest->Y()) && // if tied,
((*ipoint)->X() < lowest->X()))) // take leftmost point
lowest = *ipoint;
++ipoint;
}
// perform Jarvis' march
shared_ptr<const Point> p0(lowest);
shared_ptr<const Point> pc;
do{ // while(p0 != lowest);
// add new p0 to polygon
hull->AddPoint(p0->X(), p0->Y());
// find Point pc that is clockwise from all others
int count(0);
for(ipoint = m_point.begin(); ipoint != m_point.end(); ++ipoint){
// skip p0
if(*ipoint == p0)
continue;
// count how many points have been explored
++count;
// assume first point is clockwise
if(count == 1){
pc = *ipoint;
continue;
}
// determine whether ipoint is clockwise from pc
double z(((*ipoint)->X() - p0->X()) * (pc->Y() - p0->Y()) -
((*ipoint)->Y() - p0->Y()) * (pc->X() - p0->X()));
if((z > 0) || // ipoint is clockwise, or
((z == 0) && // if tied, take farthest point
(sqrt(pow((*ipoint)->X() - p0->X(), 2) +
pow((*ipoint)->Y() - p0->Y(), 2))
>
sqrt(pow( pc->X() - p0->X(), 2) +
pow( pc->Y() - p0->Y(), 2)))))
pc = *ipoint;
} // for(ipoint = point.begin(); ipoint != point.end(); ++ipoint){
// prepare to find next point on hull
p0 = pc;
// until reaching the lowest point again
} while(p0 != lowest);
return hull;
}
void Polygon::
ComputeBoundingBox(double & x0,
double & y0,
double & x1,
double & y1)
const
{
if(m_point.empty()){
x0 = 0;
y0 = 0;
x1 = 0;
y1 = 0;
return;
}
pointlist_t::const_iterator ipoint(m_point.begin());
x0 = (*ipoint)->X();
x1 = (*ipoint)->X();
y0 = (*ipoint)->Y();
y1 = (*ipoint)->Y();
++ipoint;
while(ipoint != m_point.end()){
if((*ipoint)->X() < x0)
x0 = (*ipoint)->X();
if((*ipoint)->X() > x1)
x1 = (*ipoint)->X();
if((*ipoint)->Y() < y0)
y0 = (*ipoint)->Y();
if((*ipoint)->Y() > y1)
y1 = (*ipoint)->Y();
++ipoint;
}
}
bool Polygon::
Contains(double x,
double y)
const
{
if(m_point.size() < 3)
return false;
pointlist_t::const_iterator ipoint(m_point.begin());
const Point * previous(ipoint->get());
++ipoint;
while(ipoint != m_point.end()){
if(((*ipoint)->X() - x) * (previous->Y() - y) -
((*ipoint)->Y() - y) * (previous->X() - x) > 0)
return false;
previous = ipoint->get();
++ipoint;
}
ipoint = m_point.begin();
if(((*ipoint)->X() - x) * (previous->Y() - y) -
((*ipoint)->Y() - y) * (previous->X() - x) > 0)
return false;
return true;
}
shared_ptr<Polygon> Polygon::
CreateGrownPolygon(double padding)
const
{
shared_ptr<Polygon> polygon(new Polygon());
if(m_point.size() < 3)
return polygon;
size_t lastpoint = m_point.size() - 1;
// special treatment for first point
Point v0(m_point[lastpoint]->X() - m_point[0]->X(),
m_point[lastpoint]->Y() - m_point[0]->Y());
Point v1(m_point[1]->X() - m_point[0]->X(),
m_point[1]->Y() - m_point[0]->Y());
double l0(sqrt(v0.X() * v0.X() + v0.Y() * v0.Y()));
double l1(sqrt(v1.X() * v1.X() + v1.Y() * v1.Y()));
Point u(v0.X() / l0 + v1.X() / l1,
v0.Y() / l0 + v1.Y() / l1);
double mu(padding * l0 / (v0.X() * u.Y() - v0.Y() * u.X()));
polygon->AddPoint(m_point[0]->X() + mu * u.X(),
m_point[0]->Y() + mu * u.Y());
// normal treatment for all except last point
for(size_t ii(1); ii < lastpoint; ++ii){
v0.X(m_point[ii - 1]->X() - m_point[ii]->X());
v0.Y(m_point[ii - 1]->Y() - m_point[ii]->Y());
v1.X(m_point[ii + 1]->X() - m_point[ii]->X());
v1.Y(m_point[ii + 1]->Y() - m_point[ii]->Y());
l0 = sqrt(v0.X() * v0.X() + v0.Y() * v0.Y());
l1 = sqrt(v1.X() * v1.X() + v1.Y() * v1.Y());
u.X(v0.X() / l0 + v1.X() / l1);
u.Y(v0.Y() / l0 + v1.Y() / l1);
mu = padding * l0 / (v0.X() * u.Y() - v0.Y() * u.X());
polygon->AddPoint(m_point[ii]->X() + mu * u.X(),
m_point[ii]->Y() + mu * u.Y());
}
// special treatment for last point
v0.X(m_point[lastpoint - 1]->X() - m_point[lastpoint]->X());
v0.Y(m_point[lastpoint - 1]->Y() - m_point[lastpoint]->Y());
v1.X(m_point[0]->X() - m_point[lastpoint]->X());
v1.Y(m_point[0]->Y() - m_point[lastpoint]->Y());
l0 = sqrt(v0.X() * v0.X() + v0.Y() * v0.Y());
l1 = sqrt(v1.X() * v1.X() + v1.Y() * v1.Y());
u.X(v0.X() / l0 + v1.X() / l1);
u.Y(v0.Y() / l0 + v1.Y() / l1);
mu = padding * l0 / (v0.X() * u.Y() - v0.Y() * u.X());
polygon->AddPoint(m_point[lastpoint]->X() + mu * u.X(),
m_point[lastpoint]->Y() + mu * u.Y());
// finished
return polygon;
}
double Polygon::
CalculateRadius()
const
{
if(m_point.empty())
return 0;
double r2Max(0);
for(pointlist_t::const_iterator ipoint(m_point.begin());
ipoint != m_point.end();
++ipoint){
double r2((*ipoint)->X() * (*ipoint)->X() +
(*ipoint)->Y() * (*ipoint)->Y());
if(r2 > r2Max)
r2Max = r2;
}
return sqrt(r2Max);
}
shared_ptr<Line> Polygon::
_GetLine(size_t index)
const
{
if(index >= m_point.size())
return shared_ptr<Line>();
if(index == m_point.size() - 1)
return shared_ptr<Line>(new Line(m_point[m_point.size() - 1]->X(),
m_point[m_point.size() - 1]->Y(),
m_point[0]->X(),
m_point[0]->Y()));
return shared_ptr<Line>(new Line(m_point[index ]->X(),
m_point[index ]->Y(),
m_point[index + 1]->X(),
m_point[index + 1]->Y()));
}
ostream & operator << (ostream & os,
const Polygon & polygon)
{
Polygon::pointlist_t::const_iterator ipoint(polygon.m_point.begin());
os << "(";
while(ipoint != polygon.m_point.end()){
os << "(" << (*ipoint)->X() << ", " << (*ipoint)->Y() << ")";
++ipoint;
}
os << ")";
return os;
}
const Point * Polygon::
GetPoint(size_t index)
const
{
if(index >= m_point.size())
return 0;
return m_point[index].get();
}
} |
<script setup>
import { InformationCircleIcon, PlayIcon } from "@heroicons/vue/24/outline";
import DesktopLayout from "../../layouts/desktop/DesktopLayout.vue";
import List from "@/components/core/list/List.vue";
import ListItem from "@/components/core/list/ListItem.vue";
import Modal from "@/components/core/modal/modal.vue";
import logo from "@/assets/logo.png";
import { onMounted, ref } from 'vue'
const { ipcRenderer, shell } = window.require('electron');
let token_value = ref("LOADING");
let port_value = ref("LOADING");
let version_value = ref("x.x.x");
let msg_value = ref("");
let is_restarting = ref(false);
let tag_w_msg = ref("");
let tag_w_open = ref(true);
const loadConfig = () => {
ipcRenderer.send('getApiToken');
};
onMounted(()=> {
ipcRenderer.on('displayConfig', (event, config) => {
if (config.token) {
token_value.value = config.token;
} else {
token_value.value = "EMPTY"
}
if (config.port) {
port_value.value = config.port;
} else {
port_value.value = "EMPTY"
}
if (config.version) {
version_value.value = config.version
}
});
ipcRenderer.on('infoOut', (event, data) => {
if (!is_restarting.value) {
msg_value.value = data.toString();
}
});
const tickerId = setInterval(() => {
ipcRenderer.send('isAppReady');
}, 1500);
ipcRenderer.on('appReady', (event, msg) => {
console.log("appReady");
if (msg == "110011") {
if (tickerId != null) {
clearInterval(tickerId);
}
tag_w_open.value = false;
loadConfig();
} else {
tag_w_msg.value = msg;
}
});
loadConfig();
});
const onRestart = () => {
const config = { token : token_value.value, port: port_value.value };
ipcRenderer.send('trigRestart', config);
is_restarting.value = true;
msg_value.value = "Restarting.......";
setTimeout(() => {
is_restarting.value = false;
}, 10000);
}
const openLink = (link) => {
shell.openExternal(link);
}
</script>
<template>
<DesktopLayout>
<Modal v-model:open="tag_w_open" :showLoader="false" :show-cover="true">
<template v-slot:body>
<div class="mt-10">
<div class="text-center">this is cover page text</div>
</div>
</template>
<template v-slot:cover>
<div class="h-full">
<div class="relative h-full">
<div class="relative text-black rounded h-full items-center justify-center flex">
<svg viewBox="0 0 24 24" fill="none" class="w-4 h-4 animate animate-spin">
<circle cx="12" cy="12" r="10" class="stroke-slate-300" stroke-width="4" />
<path d="M12 22C14.6522 22 17.1957 20.9464 19.0711 19.0711C20.9464 17.1957 22 14.6522 22 12C22 9.34784 20.9464 6.8043 19.0711 4.92893C17.1957 3.05357 14.6522 2 12 2" class="stroke-indigo-500" stroke-width="4" />
</svg>
<span class="ml-3 text-xs flex-inline text-gray-600">{{ tag_w_msg }}</span>
</div>
</div>
</div>
</template>
</Modal>
<form class="space-y-6 divide-y divide-gray-200 divide-gray-200">
<div>
<h1 class="text-2xl leading-6">
<img style="width:25px;heigh:25px;" class="inline" :src="logo" />
gaganode.com desktop
</h1>
<p class="mt-3">
<span class="badge">Version:{{ version_value }}</span> For latest updates and earnings please go to official website:
<span class="href cursor-pointer" @click="openLink('https://gaganode.com')">
https://gaganode.com
</span>
</p>
</div>
<div class="pt-2">
<List class="border">
<ListItem>
<template v-slot:title>Input your token:</template>
<template v-slot:body>
<div class="input-wrap mt-1">
<input type="text" id="token" class="rounded" v-model="token_value"/>
</div>
</template>
<template v-slot:suffix>
<div class="btn-secondary xs"
v-tippy="{ placement: 'top', content: 'click to https://gaganode.com ,register and get your token' }"
@click="openLink('https://gaganode.com')"
>
how to get my token <InformationCircleIcon class="ml-1 icon inline"></InformationCircleIcon>
</div>
</template>
</ListItem>
<ListItem>
<template v-slot:title>[optional] Input your service port:</template>
<template v-slot:body>
<div class="input-wrap mt-1">
<input type="text" id="port" class="rounded" v-model="port_value" />
</div>
</template>
<template v-slot:subject>change this if and only if you are running a server in data center</template>
<template v-slot:suffix>
<div class="btn-secondary xs"
v-tippy="{ placement: 'top', content: 'click to tutorial' }"
@click="openLink('https://docs.gaganode.com/gaganode-service_port.html')"
>
help <InformationCircleIcon class="ml-1 icon inline"></InformationCircleIcon>
</div>
</template>
</ListItem>
</List>
<div class="pt-5 lg:grid lg:grid-cols-10 lg:gap-4">
<div>
<button type="button" class="btn-success sm mt-2" :disabled="is_restarting" @click="onRestart">
<div v-if="!is_restarting" class="flex">
<PlayIcon class="prefix-icon"/>Restart
</div>
<div v-if="is_restarting" class="flex">
<InformationCircleIcon class="prefix-icon"/>Loading
</div>
</button>
</div>
<div class="lg:col-span-9 mt-2">
<textarea id="node_log" rows="30" class="rounded bg-gray-50 text-gray-500" disabled v-model="msg_value"></textarea>
</div>
</div>
</div>
</form>
</DesktopLayout>
</template>
<!-- <div>
<label for="username" class="flex">Input your token</label>
<p> </p>
</div>
<div class="lg:col-span-2 mt-2">
<div class="input-wrap">
<input type="text" id="token" class="rounded"/>
</div>
</div> --> |
/*
* Copyright (c) 2008-2012, Matthias Mann
*
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of Matthias Mann nor the names of its contributors may
* be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections.Generic;
using System.Reflection;
namespace XNATWL.Utils
{
public abstract class AbstractMathInterpreter : SimpleMathParser.Interpreter
{
public interface Function
{
Object Execute(params Object[] args);
}
private List<Object> _stack;
private Dictionary<String, Function> _functions;
public AbstractMathInterpreter()
{
this._stack = new List<Object>();
this._functions = new Dictionary<String, Function>();
RegisterFunction("min", new FunctionMin());
RegisterFunction("max", new FunctionMax());
}
public abstract void AccessVariable(string name);
public void RegisterFunction(String name, Function function)
{
if (function == null)
{
throw new NullReferenceException("function");
}
_functions.Add(name, function);
}
public Number Execute(String str)
{
_stack.Clear();
SimpleMathParser.Interpret(str, this);
if (_stack.Count != 1)
{
throw new InvalidOperationException("Expected one return value on the stack");
}
return PopNumber();
}
public int[] ExecuteIntArray(String str)
{
_stack.Clear();
int count = SimpleMathParser.InterpretArray(str, this);
if (_stack.Count != count)
{
throw new InvalidOperationException("Expected " + count + " return values on the stack");
}
int[] result = new int[count];
for (int i = count; i-- > 0;)
{
result[i] = PopNumber().IntValue();
}
return result;
}
public T ExecuteCreateObject<T>(String str, Type type)
{
_stack.Clear();
int count = SimpleMathParser.InterpretArray(str, this);
if (_stack.Count != count)
{
throw new InvalidOperationException("Expected " + count + " return values on the stack");
}
if (count == 1 && type.IsInstanceOfType(_stack[0]))
{
return (T)_stack[0];
}
foreach (ConstructorInfo c in type.GetConstructors())
{
ParameterInfo[] parameters = c.GetParameters();
if (parameters.Length == count)
{
bool match = true;
for (int i = 0; i < count; i++)
{
if (!ClassUtils.IsParamCompatible(parameters[i], _stack[i]))
{
match = false;
break;
}
}
if (match)
{
try
{
return (T) c.Invoke(_stack.ToArray());
}
catch (Exception ex)
{
System.Diagnostics.Debug.WriteLine("AbstractMathInterpreter can't instantiate object", ex);
}
}
}
}
throw new ArgumentOutOfRangeException("Can't construct a " + type + " from expression: \"" + str + "\"");
}
protected void Push(Object obj)
{
if (obj.GetType() == typeof(Single))
{
System.Diagnostics.Debug.WriteLine("objPush: " + obj.GetType().FullName);
}
_stack.Add(obj);
}
protected Object Pop()
{
int size = _stack.Count;
if (size == 0)
{
throw new InvalidOperationException("stack underflow");
}
object item = _stack[size - 1];
_stack.RemoveAt(size - 1);
return item;
}
protected Number PopNumber()
{
Object obj = Pop();
if (obj is Number)
{
return (Number)obj;
}
System.Diagnostics.Debug.WriteLine(obj);
throw new InvalidOperationException("expected number on stack - found: " +
((obj != null) ? obj.GetType().Name : "null"));
}
public void LoadConst(Number n)
{
Push(n);
}
public void Add()
{
Number b = PopNumber();
Number a = PopNumber();
bool oIsFloat = IsFloat(a) || IsFloat(b);
Push(a + b);
}
public void Sub()
{
Number b = PopNumber();
Number a = PopNumber();
bool oIsFloat = IsFloat(a) || IsFloat(b);
Push(a - b);
}
public void Mul()
{
Number b = PopNumber();
Number a = PopNumber();
bool oIsFloat = IsFloat(a) || IsFloat(b);
Push(a * b);
}
public void Div()
{
Number b = PopNumber();
Number a = PopNumber();
bool oIsFloat = IsFloat(a) || IsFloat(b);
Push(a / b);
}
public void Negate()
{
Number a = PopNumber();
Push(-a);
}
public void AccessArray()
{
Number idx = PopNumber();
Object obj = Pop();
if (obj == null)
{
throw new InvalidOperationException("null pointer");
}
if (!obj.GetType().IsArray)
{
throw new InvalidOperationException("array expected");
}
try
{
Push(((Array)obj).GetValue(idx.IntValue()));
}
catch (IndexOutOfRangeException ex)
{
throw new InvalidOperationException("array index out of bounds", ex);
}
}
public virtual void AccessField(String field)
{
Object obj = Pop();
if (obj == null)
{
throw new InvalidOperationException("null pointer");
}
Object result = AccessField(obj, field);
Push(result);
}
protected virtual Object AccessField(Object obj, String field)
{
Type clazz = obj.GetType();
try
{
if (clazz.IsArray)
{
if ("length".Equals(field))
{
return ((Array)obj).Length;
}
}
else
{
MethodInfo m = FindGetter(clazz, field);
if (m == null)
{
foreach (Type i in clazz.GetInterfaces())
{
m = FindGetter(i, field);
if (m != null)
{
break;
}
}
}
if (m != null)
{
if (m.ReturnType == typeof(Int32))
{
return new Number((Int32)m.Invoke(obj, new object[0]));
}
else if (m.ReturnType == typeof(float))
{
return new Number((float)m.Invoke(obj, new object[0]));
}
return m.Invoke(obj, new object[0]);
}
}
}
catch (Exception ex)
{
throw new InvalidOperationException("error accessing field '" + field +
"' of class '" + clazz + "'", ex);
}
throw new InvalidOperationException("unknown field '" + field +
"' of class '" + clazz + "'");
}
private static MethodInfo FindGetter(Type clazz, String field)
{
foreach (MethodInfo m in clazz.GetMethods())
{
if (!m.IsStatic &&
m.ReturnType != typeof(void) &&
m.IsPublic &&
m.GetParameters().Length == 0 &&
(CmpName(m, field, "get") || CmpName(m, field, "get_") || CmpName(m, field, "is")))
{
return m;
}
}
return null;
}
private static bool CmpName(MethodInfo m, String fieldName, String prefix)
{
return (prefix + fieldName).ToLower() == m.Name.ToLower();
}
public void CallFunction(String name, int args)
{
Object[] values = new Object[args];
for (int i = args; i-- > 0;)
{
values[i] = Pop();
}
Function function = _functions[name];
if (function == null)
{
throw new ArgumentOutOfRangeException("Unknown function");
}
Push(function.Execute(values));
}
protected static bool IsFloat(Number n)
{
return !n.IsRational();
}
public abstract class NumberFunction : Function
{
protected abstract Object Execute(params int[] values);
protected abstract Object Execute(params float[] values);
public Object Execute(params Object[] args)
{
foreach (Object o in args)
{
if (!(o is Int32)) {
float[] fvalues = new float[args.Length];
for (int i = 0; i < fvalues.Length; i++)
{
fvalues[i] = ((Number)args[i]).FloatValue();
}
return Execute(fvalues);
}
}
int[] values = new int[args.Length];
for (int i = 0; i < values.Length; i++)
{
values[i] = ((Number)args[i]).IntValue();
}
return Execute(values);
}
}
public class FunctionMin : NumberFunction
{
protected override Object Execute(params int[] values)
{
int result = values[0];
for (int i = 1; i < values.Length; i++)
{
result = Math.Min(result, values[i]);
}
return result;
}
protected override Object Execute(params float[] values)
{
float result = values[0];
for (int i = 1; i < values.Length; i++)
{
result = Math.Min(result, values[i]);
}
return result;
}
}
public class FunctionMax : NumberFunction
{
protected override Object Execute(params int[] values)
{
int result = values[0];
for (int i = 1; i < values.Length; i++)
{
result = Math.Max(result, values[i]);
}
return result;
}
protected override Object Execute(params float[] values)
{
float result = values[0];
for (int i = 1; i < values.Length; i++)
{
result = Math.Max(result, values[i]);
}
return result;
}
}
}
} |
#include <fstream>
#include <iostream>
#include <sstream>
#include <chrono>
#include "condition_record.hpp"
bool cConditionRecord::foldingEnabled = false;
void cConditionRecord::GlobalEnableFolding(const bool arg_enableFolding)
{
foldingEnabled = arg_enableFolding;
}
std::list<cConditionRecord> cConditionRecord::ParseFile(const std::string& arg_path)
{
std::ifstream file(arg_path);
if (!file.is_open())
{
std::cout << "File is not found." << std::endl;
exit(EXIT_FAILURE);
}
std::list<cConditionRecord> records;
std::string line;
while (!file.eof())
{
std::getline(file, line);
cConditionRecord record(line);
records.push_back(record);
}
file.close();
return records;
}
cConditionRecord::cConditionRecord(const std::string& arg_record) :
record(),
groups()
{
uint32_t spaceIndex = arg_record.find(' ');
record = arg_record.substr(0U, spaceIndex);
if (foldingEnabled)
{
const std::string addition = "?" + record;
for (uint8_t i = 0U; i < 4U; i++)
{
record += addition;
}
}
ParseGroups(arg_record.substr(spaceIndex + 1U));
}
void cConditionRecord::ParseGroups(const std::string& arg_groupsStr)
{
const auto target = std::regex{ "," };
std::string groupsStr = std::regex_replace(arg_groupsStr, target, " ");
std::stringstream ss(groupsStr);
uint16_t group;
while (ss >> group)
{
groups.push_back(group);
}
if (foldingEnabled)
{
std::vector<uint16_t> groupsOriginal = groups;
for (uint16_t i = 0U; i < 4U; i++)
{
for (auto item : groupsOriginal)
{
groups.push_back(item);
}
}
}
}
uint64_t cConditionRecord::NumberOfPossibleWay(const std::list<cConditionRecord>& arg_records)
{
uint64_t sum = 0U;
auto start = std::chrono::high_resolution_clock::now();
for (auto& record : arg_records)
{
const uint64_t possibilities = record.NumberOfPossibleWay();
sum += possibilities;
}
auto end = std::chrono::high_resolution_clock::now();
auto runtime = std::chrono::duration_cast<std::chrono::milliseconds>(end - start);
std::cout << "(" << runtime.count() << "ms) ";
return sum;
}
uint64_t cConditionRecord::NumberOfPossibleWay(void) const
{
std::unordered_map<std::string, uint64_t> cache;
return NumberOfPossibleWay(0U, 0U, 0U, cache);
}
uint64_t cConditionRecord::NumberOfPossibleWay(uint16_t arg_recordIndex, uint16_t arg_groupIndex, uint16_t arg_springsConsumed,
std::unordered_map<std::string, uint64_t>& arg_cache) const
{
// Check group index
const bool allGroupsConsumed = arg_groupIndex == groups.size();
const bool lastGroupConsumed = (arg_groupIndex == (groups.size() - 1U)) && (groups[arg_groupIndex] == arg_springsConsumed);
if (allGroupsConsumed || lastGroupConsumed)
{
// Check that all springs was consumed
const bool allSpringConsumed = arg_recordIndex == record.size();
const bool noSpringsLeft = (record.find("#", arg_recordIndex) == std::string::npos);
return (allSpringConsumed || noSpringsLeft) ? 1U : 0U;
}
// Run out of springs and some groups left
if (arg_recordIndex == record.size())
{
return 0U;
}
// Check cache
std::string key = std::to_string(arg_recordIndex) + "-" + std::to_string(arg_groupIndex) + "-" + std::to_string(arg_springsConsumed);
if (arg_cache.find(key) != arg_cache.end())
{
return arg_cache[key];
}
uint64_t result = 0U;
const char currentSpring = record[arg_recordIndex];
const bool currentGroupDone = (groups[arg_groupIndex] == arg_springsConsumed) && ((currentSpring == '.') || (currentSpring == '?'));
/* Group is fully consumed */
if (currentGroupDone)
{
result = NumberOfPossibleWay(arg_recordIndex + 1U, arg_groupIndex + 1U, 0U, arg_cache);
}
/* First spring in group */
else if (arg_springsConsumed == 0U)
{
/* Consume demaged spring */
if (currentSpring == '#')
{
result = NumberOfPossibleWay(arg_recordIndex + 1U, arg_groupIndex, 1U, arg_cache);
}
/* Consume operational spring */
else if (currentSpring == '.')
{
result = NumberOfPossibleWay(arg_recordIndex + 1U, arg_groupIndex, 0U, arg_cache);
}
/* Consume unknown spring */
else /* (currentSpring == '?') */
{
result += NumberOfPossibleWay(arg_recordIndex + 1U, arg_groupIndex, 1U, arg_cache);
result += NumberOfPossibleWay(arg_recordIndex + 1U, arg_groupIndex, 0U, arg_cache);
}
}
/* Next spring in group */
else if ((currentSpring == '#') || (currentSpring == '?'))
{
result = NumberOfPossibleWay(arg_recordIndex + 1U, arg_groupIndex, arg_springsConsumed + 1U, arg_cache);
}
// Cache and return result
arg_cache[key] = result;
return result;
} |
<?xml version='1.0' encoding='UTF-8' ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:cc="http://xmlns.jcp.org/jsf/composite"
xmlns:h="http://xmlns.jcp.org/jsf/html"
xmlns:f="http://xmlns.jcp.org/jsf/core"
xmlns:ui="http://xmlns.jcp.org/jsf/facelets"
xmlns:p="http://xmlns.jcp.org/jsf/passthrough">
<!-- INTERFACE -->
<cc:interface>
<cc:attribute name="coach" required="true" type="edu.iit.sat.itmd4515.rbalasubramanian1.model.Coach" />
<cc:attribute name="readonly" required="false" default="true" type="java.lang.Boolean" />
<cc:attribute name="action" required="false" method-signature="java.lang.String action()" />
</cc:interface>
<!-- IMPLEMENTATION -->
<cc:implementation>
<h:form>
<h:panelGroup layout="block" class="form-group">
<h:outputLabel for="id" value="ID: #{cc.attrs.coach.id}" />
<h:inputHidden class="form-control" id="id" value="#{cc.attrs.coach.id}" />
<h:message for="id" errorClass="text-danger"/>
</h:panelGroup>
<h:panelGroup layout="block" class="form-group">
<h:outputLabel for="version" value="Version: #{cc.attrs.coach.version}" />
<h:inputHidden class="form-control" id="version" value="#{cc.attrs.coach.version}" />
<h:message for="version" errorClass="text-danger"/>
</h:panelGroup>
<h:panelGroup layout="block" class="form-group">
<h:outputLabel for="ownerFName" value="First Name:" />
<h:inputText class="form-control" id="ownerFName" value="#{cc.attrs.coach.firstName}" />
<h:message for="ownerFName" errorClass="text-danger"/>
</h:panelGroup>
<h:panelGroup layout="block" class="form-group">
<h:outputLabel for="ownerLName" value="Last Name:" />
<h:inputText class="form-control" id="ownerLName" value="#{cc.attrs.coach.lastName}" />
<h:message for="ownerLName" errorClass="text-danger"/>
</h:panelGroup>
<h:panelGroup layout="block" class="form-group">
<h:outputLabel for="age" value="Age: " />
<h:inputText
readonly="#{cc.attrs.readonly ? 'true' : 'false'}"
class="form-control" id="age" value="#{cc.attrs.coach.age}"
onkeypress="if(event.which < 48 || event.which > 57) return false;"/>
<h:message for="age" errorClass="text-danger"/>
</h:panelGroup>
<h:panelGroup layout="block" class="form-group">
<h:outputLabel for="teamName" value="Team Name:" />
<h:inputText
class="form-control"
id="teamName"
value="#{cc.attrs.coach.team.teamName}"
readonly="#{cc.attrs.coach.team != null ? 'false' : 'true'}"/>
<h:message for="teamName" errorClass="text-danger"/>
</h:panelGroup>
<h:panelGroup layout="block" class="form-group">
<h:outputLabel for="capName" value="Captain Name:" />
<h:inputText
class="form-control"
id="capName"
value="#{cc.attrs.coach.team.captainName}"
readonly="#{cc.attrs.coach.team != null ? 'false' : 'true'}"/>
<h:message for="capName" errorClass="text-danger"/>
</h:panelGroup>
<h:panelGroup layout="block" class="form-group">
<h:outputLabel for="contact" value="Contact:" />
<h:inputText readonly="#{cc.attrs.coach.team != null ? 'false' : 'true'}" class="form-control" id="contact" value="#{cc.attrs.coach.team.contact}" />
<h:message for="contact" errorClass="text-danger"/>
</h:panelGroup>
<ui:fragment rendered="#{not cc.attrs.readonly}">
<h:commandButton value="Save"
class="btn btn-primary"
action="#{cc.attrs.action}">
<f:param name="id" value="#{cc.attrs.coach.id}" />
</h:commandButton>
</ui:fragment>
</h:form>
</cc:implementation>
</html> |
#+author: conao
#+date: <2018-12-14 Fri>
*DEPRECATED*: This package is deprecated. Please use package.el.
Technical Notes: Package maintainers assume that the packages they develop will be
installed at run-time with package.el.
Therefore, they may ask the user for interactive input during installation.
I conclude that this makes headless multiplexing difficult, as it is not known until
the actual installation.
[[https://github.com/conao3/feather.el][https://raw.githubusercontent.com/conao3/files/master/blob/headers/png/feather.el.png]]
[[https://github.com/conao3/feather.el/blob/master/LICENSE][https://img.shields.io/github/license/conao3/feather.el.svg?style=flat-square]]
[[https://github.com/conao3/feather.el/releases][https://img.shields.io/github/tag/conao3/feather.el.svg?style=flat-square]]
[[https://github.com/conao3/feather.el/actions][https://github.com/conao3/feather.el/workflows/Main%20workflow/badge.svg]]
[[https://app.codacy.com/project/conao3/feather.el/dashboard][https://img.shields.io/codacy/grade/1108333059ce4bc7a833a42a4eaf417c.svg?logo=codacy&style=flat-square]]
[[https://www.patreon.com/conao3][https://img.shields.io/badge/patreon-become%20a%20patron-orange.svg?logo=patreon&style=flat-square]]
[[https://twitter.com/conao_3][https://img.shields.io/badge/twitter-@conao__3-blue.svg?logo=twitter&style=flat-square]]
[[https://join.slack.com/t/conao3-support/shared_invite/enQtNjUzMDMxODcyMjE1LTA4ZGRmOWYwZWE3NmE5NTkyZjk3M2JhYzU2ZmRkMzdiMDdlYTQ0ODMyM2ExOGY0OTkzMzZiMTNmZjJjY2I5NTM][https://img.shields.io/badge/chat-on_slack-blue.svg?logo=slack&style=flat-square]]
* Table of Contents
- [[#description][Description]]
- [[#install][Install]]
- [[#usage][Usage]]
- [[#information][Information]]
- [[#donation][Donation]]
- [[#community][Community]]
- [[#contribution][Contribution]]
- [[#license][License]]
- [[#author][Author]]
- [[#contributors][Contributors]]
* Description
[[https://raw.githubusercontent.com/conao3/files/master/blob/feather.el/feather-dashboard-teaser.gif]]
~feather.el~ is a wrapper for ~package.el~ that supports parallel fetching/byte-compiling.
It have already prepared front end for [[https://github.com/conao3/leaf.el][leaf.el]] in leaf-keywword.el, and you can seamlessly manage Emacs packages with ~feather.el~.
When ~feather-mode~ is enabled, ~feather.el~ advices ~package-install~ in ~package.el~.
So, all installation using ~package.el~ is handled by ~feather.el~.
~feather.el~ is a ~package.el~ wrapper that supports parallel fetch/byte-compilation.
When ~feather-mode~ is enabled, ~feather.el~ sets advice to ~package-install~, handles all package installations, and executes them asynchronously.
Originally conceived as a completely new package manager,
but in the middle of development it was thought that simply handling ~package-install~ would be sufficient to achieve the goal,
so it provides your Emacs with a powerful asynchronous installation that preserves the ~package.el~ experience.
* Install
~feather~ is available via ~el-get~
#+begin_src emacs-lisp
(leaf feather
:el-get conao3/feather.el
:config (feather-mode))
#+end_src
* Usage
Just enable ~feather-mode~ and install some package via ~package.el~ (~package-install~, ~list-package~,,,)
* Notice
~feather~ sets the advice to run ~package-install~ asynchronously.
That is, ~package-install~ returns the moment it is executed, and the subsequent S-exp is executed (if any).
Therefore, the following configuration will result in an error.
#+begin_src emacs-lisp
(package-install 'leaf-keywords)
(leaf-keywords-init)
#+end_src
If you want execute ~leaf-keywords-init~ after ~leaf-keywords~ is installed as intended, you need to register an S-exp with ~father~.
This allows ~feather~ to execute the registered S-exp after the package is installed.
#+begin_src emacs-lisp
(package-install 'leaf-keywords)
(feather-add-after-installed-hook-sexp leaf-keywords
(leaf-keywords-init))
#+end_src
However, this is generally cumbersome, so the easiest solution is to use [[https://github.com/conao3/leaf.el][leaf]].
Using the ~:feather~ keyword as a trigger, the S-exp that should be executed after the package is installed is automatically registered with the ~feather~.
#+begin_src emacs-lisp
(leaf leaf-keywordsq
:feather t
:config (leaf-keywords-init))
#+end_src
If you want to switch to a feather install for all the ~:ensure~ keywords, you can do so by setting ~leaf-alias-keyword-alist~.
With ~leaf-alias-keyword-alist~ is ~((:ensure . :feather))~, the leaf block below has the same meaning as a leaf block using the ~:feather~ keyword.
#+begin_src emacs-lisp
(leaf leaf-keywords
:ensure t
:config (leaf-keywords-init))
#+end_src
* Information
** Donation
I love OSS and I am dreaming of working on it as *full-time* job.
*With your support*, I will be able to spend more time at OSS!
[[https://www.patreon.com/conao3][https://c5.patreon.com/external/logo/become_a_patron_button.png]]
** Community
All feedback and suggestions are welcome!
You can use github issues, but you can also use [[https://join.slack.com/t/conao3-support/shared_invite/enQtNjUzMDMxODcyMjE1LTA4ZGRmOWYwZWE3NmE5NTkyZjk3M2JhYzU2ZmRkMzdiMDdlYTQ0ODMyM2ExOGY0OTkzMzZiMTNmZjJjY2I5NTM][Slack]]
if you want a more casual conversation.
** Contribution
Feel free to send PR!
** License
#+begin_example
General Public License Version 3 (GPLv3)
Copyright (c) Naoya Yamashita - https://conao3.com
https://github.com/conao3/feather.el/blob/master/LICENSE
#+end_example
** Author
- Naoya Yamashita ([[https://github.com/conao3][conao3]])
** Contributors
- Not yet... Now send PR and add your name!! |
//
// CategoriesDataSource.swift
// News
//
// Created by Tomas Pecuch on 09/11/2018.
// Copyright © 2018 Tomas Pecuch. All rights reserved.
//
import Foundation
import UIKit
//structure that represents single category
struct CategoryData {
let key: String
let name: String
}
class CategoryDataSource: NSObject, UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout {
// singleton
static var shared = CategoryDataSource()
private var indexOfCellBeforeDragging = 0
var categories = [CategoryData]()
private var selectedCellIndex: Int = 0
var collectionView: UICollectionView?
var mainVC: MainVC?
// MARK: - UICollectionView delegate
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return categories.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "CategoryCollectionCell", for: indexPath) as! CategoryCollectionCell
cell.nameLabel.text = categories[indexPath.row].name
cell.setChosen(chosen: selectedCellIndex == indexPath.row ? true : false, animated: false)
return cell
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
let text = categories[indexPath.row].name
let width = UILabel.textWidth(font: UIFont.systemFont(ofSize: 17.0), text: text)
return CGSize(width: width + 10, height: collectionView.frame.height)
}
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
// if selecting selected cell do nothing
if indexPath.row == selectedCellIndex { return }
// deselect the previous cell
let cellToSelect = collectionView.cellForItem(at: indexPath) as! CategoryCollectionCell
if let cellToDeselect = collectionView.cellForItem(at: IndexPath(row: selectedCellIndex, section: 0)) as? CategoryCollectionCell {
cellToDeselect.setChosen(chosen: false, animated: true)
}
cellToSelect.setChosen(chosen: true, animated: true)
mainVC?.selectCategoryAtIndex(newIndex: indexPath.row, oldIndex: selectedCellIndex)
selectedCellIndex = indexPath.row
}
func collectionView(_ collectionView: UICollectionView, willDisplay cell: UICollectionViewCell, forItemAt indexPath: IndexPath) {
guard let categoryCell = cell as? CategoryCollectionCell else { return }
categoryCell.setChosen(chosen: selectedCellIndex == indexPath.row, animated: false)
}
// MARK: - Other
/// selects category with the given key
///
/// - Parameter categoryKey: key of the category to select
func selectCategory(categoryKey: String) {
for (index,category) in categories.enumerated() {
if category.key == categoryKey {
selectCategoryAtIndex(index: index)
}
}
}
/// selects the cell at the given index
///
/// - Parameter index: index of the cell to select
func selectCategoryAtIndex(index: Int) {
// if selecting selected cell do nothing
if index == selectedCellIndex { return }
if let cellToSelect = collectionView?.cellForItem(at: IndexPath(row: index, section: 0)) as? CategoryCollectionCell {
cellToSelect.setChosen(chosen: true, animated: true)
}
if let cellToDeselect = collectionView?.cellForItem(at: IndexPath(row: selectedCellIndex, section: 0)) as? CategoryCollectionCell {
cellToDeselect.setChosen(chosen: false, animated: true)
}
selectedCellIndex = index
}
/// Creates categories array from downloaded dictionary
///
/// - Parameter categories: dictionary containing keys and name of the categories
func setCategories(categories: [String: Any]) {
self.categories.removeAll()
for categoryKey in categories.keys {
let key = categoryKey
if let name = (categories[key] as! [String : String])["name"] {
self.categories.append(CategoryData(key: key, name: name))
}
}
}
/// sorts categories
///
/// - Parameter keysArray: array of key according to which it sorts categories
func sortCategories(keysArray: [String]) {
var sortedCategories = [CategoryData]()
sortedCategories.append(CategoryData(key: "all", name: "All"))
for key in keysArray {
for category in categories {
if key == category.key {
sortedCategories.append(category)
}
}
}
categories = sortedCategories
self.collectionView?.reloadData()
}
/// sorts categories
///
/// - Parameter keysDict: dictionary of key according to which it sorts categories
func sortCategories(keysDict: [Int: Any]) {
var sortedCategories = [CategoryData]()
sortedCategories.append(CategoryData(key: "all", name: "All"))
for (_,value) in keysDict.enumerated() {
for category in categories {
if let categoryKey = value.value as? String {
if categoryKey == category.key {
sortedCategories.append(category)
}
}
}
}
categories = sortedCategories
self.collectionView?.reloadData()
}
} |
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<title>Digital Hub_about</title>
<!-- Meta -->
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta name="description" content="Blog Template" />
<meta name="author" content="Xiaoying Riley at 3rd Wave Media" />
<link rel="shortcut icon" href="favicon.ico" />
<!-- FontAwesome JS-->
<script
defer
src="https://use.fontawesome.com/releases/v5.7.1/js/all.js"
integrity="sha384-eVEQC9zshBn0rFj4+TU78eNA19HMNigMviK/PU/FFjLXqa/GKPgX58rvt5Z8PLs7"
crossorigin="anonymous"
></script>
<!-- Theme CSS -->
<link id="theme-style" rel="stylesheet" href="assets/css/theme1.css" />
<link rel="stylesheet" href="/assets/css/about.css" />
<link rel="stylesheet" href="/assets/css/profile.css" />
</head>
<body>
<header class="header text-center" id="main-header" name="main-header">
<h1 class="blog-name pt-lg-4 mb-0">
<a href="/home">
<span th:text="${session.Member.name}"></span>'s Digital Hub
</a>
<!--블로그 주인 이름 -->
</h1>
<nav class="navbar navbar-expand-lg navbar-dark">
<button
class="navbar-toggler"
type="button"
data-toggle="collapse"
data-target="#navigation"
aria-controls="navigation"
aria-expanded="false"
aria-label="Toggle navigation"
>
<span class="navbar-toggler-icon"></span>
</button>
<div id="navigation" class="collapse navbar-collapse flex-column">
<div class="profile-section pt-3 pt-lg-0">
<img
class="profile-image mb-3 rounded-circle mx-auto"
th:src="${session.Member.image != null ? session.Member.image : 'assets/images/default-profile.png'}"
alt="image"
/>
<div class="bio mb-3" th:text="${session.Member.introduce}">
<br /><a href="/about">회원정보 수정하기</a>
</div>
<!--//bio-->
<ul class="social-list list-inline py-3 mx-auto">
<li class="list-inline-item">
<!--깃허브 링크-->
<a href="#"><i class="fab fa-github-alt fa-fw"></i></a>
</li>
</ul>
<!--//social-list-->
<hr />
</div>
<!--//profile-section-->
<ul class="navbar-nav flex-column text-left">
<li class="nav-item active">
<a class="nav-link" href="/home"
><i class="fas fa-home fa-fw mr-2"></i>Digital Hub 홈
<span class="sr-only">(current)</span></a
>
</li>
<li class="nav-item">
<a class="nav-link" href="/bloglist"
><i class="fas fa-bookmark fa-fw mr-2"></i>Digital Hub 포스트</a
>
</li>
</ul>
<div class="my-2 my-md-3">
<a
class="btn btn-primary"
data-toggle="tooltip"
data-html="true"
th:title="|<span style='display: block; margin-bottom: 5px;'><i class='fab fa-github'></i> ${#strings.substringAfter(session.Member.githubLink, 'https://github.com/')} </span><span style='display: block;'><i class='fas fa-envelope'></i> ${session.Member.email}</span>|"
>연락하기</a></div>
<div class="my-2 my-md-3">
<a
class="btn btn-primary"
href="/boardwrite"
>작성하기</a
>
</div>
<div class="my-2 my-md-3">
<a
class="btn btn-primary"
href="/logout.do"
>로그아웃</a>
</div>
</div>
</div>
</nav>
</header>
<div class="main-wrapper">
<div class="mypage">
<form method="post" id="update-form" action="/update" enctype="multipart/form-data">
<div>
<img class="preview" id="preview" th:src="${session.Member.image != null ? session.Member.image : 'assets/images/default-profile.png'}" alt="프로필 사진 미리보기" style="width: 200px; height: 200px;">
</div>
<br>
<div class="filebox">
<label for="profileimage">사진 변경</label>
<input type="file" class="profile" id="profileimage" name="profileimage" accept="images/*">
</div>
<div class="grp">
<label for="name">이름:</label>
<input type="text" id="name" name="name" th:value="${session.Member.name}" placeholder="이름"/>
</div>
<div class="grp">
<label for="email">이메일:</label>
<input
type="email"
id="email"
name="email"
th:value="${session.Member.email}"
placeholder="이메일"
/>
<span id="email-error" class="error-message"></span>
</div>
<div class="grp">
<label for="email">자기소개:</label>
<input
type="text"
id="introduce"
name="introduce"
th:value="${session.Member.introduce}"
placeholder="인사말을 남겨주세요!"
/>
</div>
<div class="grp">
<label for="password">새 비밀번호:</label>
<input type="password" id="password" name="password" placeholder="새 비밀번호" /><br/>
</div>
<div class="grp">
<label for="password2">새 비밀번호 확인:</label>
<input type="password" id="password2" name="password2" placeholder="새 비밀번호 확인" /><br/>
</div>
<div class="grp github-link-grp">
<label for="githublink">깃허브 링크:</label>
<input type="text" id="githublink" name="githublink" th:value="${session.Member.githubLink}" placeholder="깃허브 링크"/>
</div>
<button type="submit" class="svbtn" id="update-btn">저장</button>
</form>
<form method="post" id="delete-form" action="/delete">
<button type="button" class="delbtn" id="delete-btn">회원 탈퇴</button>
</form>
</div>
</div>
<!--//main-wrapper-->
<!-- *****CONFIGURE STYLE (REMOVE ON YOUR PRODUCTION SITE)****** -->
<div id="config-panel" class="config-panel d-none d-lg-block">
<div class="panel-inner">
<a
id="config-trigger"
class="config-trigger config-panel-hide text-center"
href="#"
><i class="fas fa-cog fa-spin mx-auto" data-fa-transform="down-6"></i
></a>
<h5 class="panel-title">Choose Colour</h5>
<ul id="color-options" class="list-inline mb-0">
<li class="theme-1 active list-inline-item">
<a data-style="assets/css/theme-1.css" href="#"></a>
</li>
<li class="theme-2 list-inline-item">
<a data-style="assets/css/theme-2.css" href="#"></a>
</li>
<li class="theme-3 list-inline-item">
<a data-style="assets/css/theme-3.css" href="#"></a>
</li>
<li class="theme-4 list-inline-item">
<a data-style="assets/css/theme-4.css" href="#"></a>
</li>
<li class="theme-5 list-inline-item">
<a data-style="assets/css/theme-5.css" href="#"></a>
</li>
<li class="theme-6 list-inline-item">
<a data-style="assets/css/theme-6.css" href="#"></a>
</li>
<li class="theme-7 list-inline-item">
<a data-style="assets/css/theme-7.css" href="#"></a>
</li>
<li class="theme-8 list-inline-item">
<a data-style="assets/css/theme-8.css" href="#"></a>
</li>
</ul>
<a id="config-close" class="close" href="#"
><i class="fa fa-times-circle"></i
></a>
</div>
<!--//panel-inner-->
</div>
<!--//configure-panel-->
<!-- Javascript -->
<script src="assets/plugins/jquery-3.3.1.min.js"></script>
<script src="assets/plugins/popper.min.js"></script>
<script src="assets/plugins/bootstrap/js/bootstrap.min.js"></script>
<script src="/assets/js/about.js"></script>
<!-- Style Switcher (REMOVE ON YOUR PRODUCTION SITE) -->
<script src="assets/js/demo/style-switcher.js"></script>
<script>
$(document).ready(function () {
$('[data-toggle="tooltip"]').tooltip();
});
</script>
<script>
document.getElementById("profileimage").onchange = function(event) {
var reader = new FileReader();
reader.onload = function() {
var output = document.getElementById("preview");
output.src = reader.result;
};
if (event.target.files[0]) {
reader.readAsDataURL(event.target.files[0]);
} else {
document.getElementById("preview").src = "assets/images/default-profile.png";
}
};
</script>
</body>
</html> |
import {
Column,
CreateDateColumn,
Entity,
ManyToOne,
PrimaryGeneratedColumn,
UpdateDateColumn,
} from 'typeorm';
import { User } from '../user/user.entity';
@Entity({ name: 'reports' })
export class Report {
@PrimaryGeneratedColumn('uuid')
id: string;
@Column()
price: number;
@Column()
make: string;
@Column()
model: string;
@Column()
year: number;
@Column()
lng: number;
@Column()
lat: number;
@Column()
km: number;
@Column({ default: false })
approved: boolean;
@CreateDateColumn({ name: 'created_at', type: 'timestamptz' })
createdAt: Date;
@UpdateDateColumn({ name: 'updated_at', type: 'timestamptz' })
updatedAt: Date;
@ManyToOne(() => User, (user) => user.reports)
user: User;
} |
import React from 'react';
import axios from 'axios';
import { Text, View, TextInput, Button as TextButton, Image, ScrollView } from 'react-native';
import Styles from '../Styles.js';
import { Button, RadioButton, Searchbar, Menu } from 'react-native-paper';
import TopicLink from './TopicLink.jsx';
class Level extends React.Component {
constructor(){
super();
this.state = {
topics: [],
levelID: ''
}
}
async componentDidMount(){
if(this.props.route.params){
if(this.props.route.params.levelID){
const newState = {
levelID: this.props.route.params.levelID,
};
this.setState(newState, () => {
axios.get(`${process.env.STRAPI_URL}/levels/${this.props.route.params.levelID}?populate[topics][populate][0]=FeaturedMedia%2Cchallenges`)
.then(res => {
const data = res.data;
const level = data.data;
const topics = level.attributes.topics.data;
this.setState({
topics,
loaded: true,
});
})
})
}
}
}
renderMedia(topic){
if(topic.FeaturedImage){
switch(topic.FeaturedImage.mime){
case 'image/jpeg':
return (
<View style={Styles.fullWidth}>
<Image source={{uri: `${process.env.STRAPI_URL}${topic.FeaturedImage.url}`}}
style={{height: 400, width: '100%'}}
/>
</View>
);
default:
return <Text>Invalid media</Text>
}
}
}
randomChallenges(topic){
return topic.attributes.challenges.data.sort(() => .5 - Math.random()).slice(0, 5);
}
render(){
return (
<ScrollView>
{this.state.topics ?
this.state.topics.map((topic) =>
<View key={topic.id}>
<View style={{ ...Styles.pad, width: 400 }}>
<View style={{...Styles.flex, ...Styles.column, ...Styles.fullWidth, ...Styles.xCenter}}>
<TopicLink topic={topic} levelID={topic.levelID} navigation={this.props.navigation}/>
{topic.attributes.challenges.data ?
<ScrollView horizontal>
<View style={{...Styles.pad, width: 400}}>
<Text style={{...Styles.subHeading, textAlign: 'center'}}>Need a quick refresher? Slide forward to preview challenges.</Text>
</View>
{this.randomChallenges(topic).map((challenge) =>
<View key={`${topic.id}_${challenge.id}`} style={{...Styles.flex, ...Styles.column, ...Styles.fullWidth, ...Styles.xCenter}}>
<View style={Styles.pad}>
<Text style={Styles.heading}>{challenge.attributes.Title}</Text>
<Text>{challenge.attributes.Content}</Text>
</View>
</View>
)}
</ScrollView>
:
<Text>No challenges</Text>
}
</View>
</View>
</View>
)
:
<Text>No topics</Text>
}
</ScrollView>
);
}
}
export default Level; |
//
// ContentView-ViewModel.swift
// Faces
//
// Created by Giorgio Latour on 5/21/23.
//
import Foundation
import UIKit
extension ContentView {
@MainActor class ViewModel: ObservableObject {
@Published var inputImage: UIImage?
@Published var showingImagePicker: Bool = false
@Published var showingPersonNameInput: Bool = false
@Published var personFirstName: String = ""
@Published var personLastName: String = ""
@Published var personNote: String = ""
@Published private(set) var people: [Person]
@Published var locationFetcher = LocationFetcher()
let savePath = FileManager.documentsDirectory.appendingPathComponent("SavedPeople")
init() {
do {
let data = try Data(contentsOf: savePath)
people = try JSONDecoder().decode([Person].self, from: data)
people.sort()
} catch {
people = [Person]()
}
self.locationFetcher.start()
}
func createPerson() {
var latitude = 0.0
var longitude = 0.0
if let location = self.locationFetcher.lastKnownLocation {
latitude = location.latitude
longitude = location.longitude
}
let newPerson = Person(id: UUID(), firstName: personFirstName, lastName: personLastName, note: personNote, imageFileName: UUID().uuidString, latitude: latitude, longitude: longitude)
personFirstName = ""
personLastName = ""
personNote = ""
saveCurrentImageToDocuments(withFileName: newPerson.imageFileName)
people.append(newPerson)
people.sort()
save()
}
func removeAt(offsets: Foundation.IndexSet) {
people.remove(atOffsets: offsets)
}
func saveCurrentImageToDocuments(withFileName filename: String) {
guard let inputImage = inputImage else { return }
let imageSaver = ImageSaver()
imageSaver.successHandler = {
print("Success!")
}
imageSaver.errorHandler = {
print("Oops! \($0.localizedDescription)")
}
imageSaver.writeToDocuments(image: inputImage, imageName: filename)
}
func save() {
do {
let data = try JSONEncoder().encode(people)
try data.write(to: savePath, options: [.atomic, .completeFileProtection])
} catch {
print("unable to save data.")
}
}
}
} |
import Moralis from "moralis/dist/moralis.js";
import { NftMetadata, NftOwnerModel, ListedNftModel, MumbaiDepositLPModel } from "../../interfaces/models/NftOwnerModel";
import axios from "axios";
import { useContract } from "./contract";
import { useMoralis } from "./moralis";
import { useAlert } from "../layout/alert";
import { useIPFS } from "./ipfs";
import { useCurrency } from "../settings/currency";
import { BigNumber } from "bignumber.js";
import { useMoralisObject } from "./moralisObject";
import { useOdds } from "../settings/odds";
import { NFTMintStatus } from "../../interfaces/enums/NFTMintStatus";
import { ref, Ref } from "vue";
import { MatchedBetModel } from "../../interfaces/models/MatchedBetModel";
import { useDownload } from "../download";
import { useTimezone } from "../settings/timezone";
import { useSubscription } from "./subscription";
import { NFTTQueryParms } from "@/interfaces/queries/NFTQueryParms";
import { useChain } from "./chain";
const { showError, showSuccess } = useAlert();
const placeholder = "https://via.placeholder.com/600x600.png?text=Image%20not%20found";
const NftMintStatus = NFTMintStatus;
const nfts: Ref<Array<NftOwnerModel> | undefined> = ref();
var delistedOfferingIds: Array<string> = [];
var listedNfts: Ref<Array<ListedNftModel> | undefined> = ref();
var depositLPNfts: Ref<Array<MumbaiDepositLPModel> | undefined> = ref();
/**
* Get user nfts and subscribe for new nfts
*
* @returns Promise
*/
const getNFTs = async (): Promise<Ref<Array<NftOwnerModel> | undefined>> => {
const { userAddress } = useMoralis();
if (userAddress.value) {
const { getClassName } = useChain();
const { createQuery } = useMoralisObject(getClassName("NFTOwners"));
const nftQuery = createQuery() as Moralis.Query<NftOwnerModel>;
//nftQuery.equalTo("name", collectionName);
nftQuery.equalTo("owner_of", userAddress.value);
nftQuery.descending("block_number");
nftQuery.include("lp");
nfts.value = (await nftQuery.find()) as Array<NftOwnerModel>;
// Create live subscriptions
const { subscribe, subscribeToCreate, subscribeToUpdate } = useSubscription();
subscribe(nftQuery).then((subscription: Moralis.LiveQuerySubscription) => {
subscribeToCreate(subscription, nfts.value);
subscribeToUpdate(subscription, nfts.value, "id");
});
}
return nfts;
};
/**
* NFT query create helper
*
* @param {NFTTQueryParms} parms
* @returns Moralis
*/
const getNFTQuery = (parms: NFTTQueryParms): Moralis.Query => {
const { getClassName } = useChain();
const { createQuery, handleQuery } = useMoralisObject(getClassName("NFTOwners"));
let query: Moralis.Query = createQuery();
if (parms.filter?.hasBetOrLP) {
const queryBet = createQuery();
const queryLp = createQuery();
queryBet.exists("bet");
queryLp.exists("lp");
query = Moralis.Query.or(queryBet, queryLp);
} else {
if (parms.filter?.hasBet) {
query.exists("bet");
}
if (parms.filter?.hasLP) {
query.exists("lp");
}
}
handleQuery(query, parms);
if (parms.filter?.tokenId) {
query.equalTo("token_id", parms.filter?.tokenId);
}
if (parms.filter?.hasOffer) {
query.exists("offer");
}
return query;
};
/**
* Mint nft from matched bet
* TODO can be more then one matched bet, becuase of partial matches
*
* @param object
* @param base64
* @returns Promise
*/
const mint = async (matchedBet: MatchedBetModel, blob: Blob, customMessage: any): Promise<void> => {
const { userAddress, web3 } = useMoralis();
if (userAddress.value) {
const tokenId = getTokenId(matchedBet, userAddress.value);
const { blobToB64 } = useDownload();
const base64 = (await blobToB64(blob)) as string;
const { saveJsonToIPFS, saveBase64ImageToIPFS } = useIPFS();
const image = await saveBase64ImageToIPFS(matchedBet.id, base64); // save image to ipfs
const metadata = generateMetadata(matchedBet, tokenId, image.ipfs()); // generate metadata with image
if (metadata) {
const tokenUri = await saveJsonToIPFS(matchedBet.id, metadata); // save metadata to ipfs
const { bettingContract } = useContract();
setTimeout(() => {
customMessage.message = "Waiting for user confirmation";
}, 2000);
bettingContract.value.methods
.transferBetToNFT(matchedBet.get("apiId"), matchedBet.get("betSide"), 0, matchedBet.get("selection"), matchedBet.get("odds"), tokenUri.ipfs())
.send(
{
from: userAddress.value,
},
async (err: any, result: any) => {
if (!err) {
matchedBet.set("isMinted", true);
matchedBet.set("tokenId", tokenId);
await matchedBet.save();
customMessage.show = false;
showSuccess("Bet successfully minted, wait for confirmation");
} else {
showError(err.message);
customMessage.show = false;
}
}
);
}
}
};
/**
* Generates NFT Token Id from matched bet
*
* @param {MatchedBetModel} matchedBet
* @returns string
*/
const getTokenId = (matchedBet: MatchedBetModel, address: string): string => {
const { web3 } = useMoralis();
const hashedTokenId = web3.value.utils.keccak256(
web3.value.eth.abi.encodeParameters(
["string", "address", "uint8", "uint8", "uint8", "uint16"],
[
matchedBet.attributes.apiId,
address,
Number(matchedBet.attributes.betSide),
Number(matchedBet.attributes.betType),
Number(matchedBet.attributes.selection),
Number(matchedBet.attributes.odds),
]
)
);
const converted = web3.value.utils.toBN(hashedTokenId);
const convertedAnd = web3.value.utils.toBN("0xfff");
const tokenId = converted.and(convertedAnd).toNumber();
return String(tokenId);
};
/**
* Generate metadata for nft
*
* @param {MatchedBetModel} matchedBet
* @param {string} imageUrl
* @returns NftMetadata
*/
const generateMetadata = (matchedBet: MatchedBetModel, tokenId: string, imageUrl: string): NftMetadata | undefined => {
if (matchedBet.attributes.event) {
const { convertCurrency } = useCurrency();
const { decodeOdds } = useOdds();
const { format, selectedTimezone } = useTimezone();
const eventName = matchedBet.attributes.event.getName();
let position = "";
if (matchedBet.get("selection") == 1) {
position = "Home";
} else if (matchedBet.get("selection") == 2) {
position = "Away";
} else if (matchedBet.get("selection") == 3) {
position = "Draw";
}
return {
name: eventName + " Bet #" + tokenId,
description: "Bet Details from Match " + eventName,
external_url: "",
image: imageUrl,
attributes: [
{
trait_type: "Match",
value: eventName,
},
{
trait_type: "Event Id",
value: matchedBet.get("apiId"),
},
{
trait_type: "Start",
value: format(matchedBet.attributes.event.get("start"), "YYYY-MM-DD HH:mm") + " " + selectedTimezone.value.tzCode,
},
{
trait_type: "League",
value: matchedBet.attributes.event.attributes.league.attributes.name,
},
{
trait_type: "Season",
value: String(matchedBet.attributes.event.attributes.league.attributes.season),
},
{
trait_type: "Side",
value: matchedBet.get("betSide") == 0 ? "Back" : "Lay",
},
{
trait_type: "Bet Type",
value: "Match Winner",
},
{
trait_type: "Position",
value: position,
},
{
trait_type: "Odds",
value: new BigNumber(decodeOdds(matchedBet.get("odds"))),
},
{
trait_type: "Amount",
value: new BigNumber(convertCurrency(matchedBet.get("amount"))),
},
],
};
}
};
/**
* Get Opensea link from web3api nft
*
* @param nft
* @returns
*/
const getOpenseaLink = (nft: NftOwnerModel): string => {
return "https://testnets.opensea.io/assets/mumbai/0xb4de4d37e5766bc3e314f3eda244b1d0c097363c/" + nft?.attributes?.token_id;
};
/**
* Resolve metadata from moralis nft model
*
* @param {NftOwnerPendingModel|NftOwnerModel} nft
* @returns Promise
*/
const resolveMetadataFromNft = async (uri: string): Promise<NftMetadata | undefined> => {
try {
const response = await axios.get(uri);
if (response) {
return response.data;
}
} catch (err) {
console.log(uri + " fetch resulted in error = " + err);
}
};
const getNFTsDeListedOnMarketplace = async () => {
const queryAll = new Moralis.Query("MumbaiClosedOfferings");
//queryAll.equalTo("hostContract", "0xb4de4d37e5766bc3e314f3eda244b1d0c097363c");
const deListedNfts: Ref<Array<ListedNftModel> | undefined> = ref();
deListedNfts.value = (await queryAll.find()) as Array<ListedNftModel>;
//console.log("getNFTsDeListedOnMarketplace");
//console.log(deListedNfts);
deListedNfts.value.forEach((nft: ListedNftModel) => {
delistedOfferingIds.push(nft.attributes.offeringId);
});
};
const getNFTsListedOnMarketplace = async (): Promise<Ref<Array<ListedNftModel> | undefined>> => {
const queryAll = new Moralis.Query("MumbaiPlacedOfferings");
//queryAll.equalTo("tokenId", "2");
//queryAll.equalTo("hostContract", "0xec3cd0be96e26841ed17cf9e8585b00926488cd5");
listedNfts.value = (await queryAll.find()) as Array<ListedNftModel>;
//console.log("getNFTsListedOnMarketplace");
//console.log(listedNfts);
//console.log('Total number of nfts fetched from db = ' + listedNfts.value.length);
await getNFTsDeListedOnMarketplace();
//console.log(delistedOfferingIds);
/**
* Resolve metadata from nft
*/
listedNfts.value.forEach(async (nft: ListedNftModel, index) => {
let notFound = true;
delistedOfferingIds.forEach((delistedOffering: string) => {
if (nft.attributes.offeringId == delistedOffering) {
notFound = false;
}
});
if (notFound) {
//console.log("pushing this nft index = " + index);
//console.log(nft);
nft.parsed_metadata = await resolveMetadataFromNft(nft.attributes.uri);
if (nft.parsed_metadata) {
//console.log('printing metadata')
//console.log(nft.parsed_metadata);
} else {
//console.log("if metadata is undefined, don't bother with this nft. index = " + index);
listedNfts?.value?.splice(index, 1);
//console.log('number of nfts are removing for metadata problem = ' + listedNfts.value.length);
}
} else {
//console.log('Ignoring this nft since it is no longer listed, index = ' + index);
//console.log(nft);
listedNfts?.value?.splice(index, 1);
//console.log(listedNfts);
}
});
//console.log(listedNfts);
// console.log("number of nfts are filtering = " + listedNfts.value.length);
return listedNfts;
};
/**
* Get user nfts and subscribe for new nfts
*
* @returns Promise
*/
const getDepositLPNFTs = async (): Promise<Ref<Array<MumbaiDepositLPModel> | undefined>> => {
const { moralisUser } = useMoralis();
if (moralisUser.value) {
// Get nfts from user
const queryAll = new Moralis.Query("MumbaiDepositLP");
depositLPNfts.value = (await queryAll.find()) as Array<MumbaiDepositLPModel>;
// console.log(depositLPNfts.value)
depositLPNfts.value.forEach(async (nft: MumbaiDepositLPModel, index) => {
nft.parsed_metadata = await resolveMetadataFromNft(nft.attributes.uri);
if (nft.parsed_metadata) {
//console.log('printing metadata of LP Token')
// console.log(nft.parsed_metadata);
} else {
/*
console.log("if metadata is undefined, don't bother with this nft. index = " + index);
depositLPNfts?.value?.splice(index, 1);
console.log('number of nfts are removing for metadata problem = ' + depositLPNfts.value.length);
*/
}
});
}
return depositLPNfts;
};
const generateLPTokenURI = async (marketMakeraddress: string, amount: string, imageUrl: string): Promise<string | undefined> => {
const { userAddress } = useMoralis();
if (userAddress.value) {
const { convertCurrency } = useCurrency();
const { saveJsonToIPFS } = useIPFS();
const metadata = {
name: "LP NFT",
description: "Liquidity Provider NFT ",
external_url: "",
image: imageUrl,
attributes: [
{
trait_type: "Market Maker contract",
value: marketMakeraddress,
},
{
trait_type: "Amount",
value: new BigNumber(convertCurrency(amount)),
},
],
};
const tokenUri = await saveJsonToIPFS(userAddress.value, metadata);
return tokenUri.ipfs();
}
};
export const useNFTs = () => {
return {
NftMintStatus,
placeholder,
getNFTs,
getNFTQuery,
getTokenId,
mint,
getOpenseaLink,
resolveMetadataFromNft,
getNFTsListedOnMarketplace,
getNFTsDeListedOnMarketplace,
getDepositLPNFTs,
generateLPTokenURI,
};
}; |
# Data config for ConvNet experiments
import os
import torch
import pandas as pd
import numpy as np
from torchvision import datasets, transforms
from torch.utils.data import Dataset, DataLoader, Sampler
from sklearn.model_selection import RepeatedKFold
from os import path as osp
import forge
from forge import flags
# # aspects of data managmement
# flags.DEFINE_boolean("cross_validate",True,"Do K-fold cross-validation")
# flags.DEFINE_boolean("rot_augment",True,"Augment data by 90 deg rotations.")
# # Job management
# flags.DEFINE_float("train_split",0.8,'Fraction of data to use for training.')
# flags.DEFINE_integer("n_repeats",1,"Times to repeat K-fold cross-validation")
# flags.DEFINE_integer("split_seed",3,"Seed for KFold split (integer for reproducibility")
# "wavelengths between 0.05 and 1 mm in 0.025 mm increments."
LSPACE = np.arange(0.05,1.05,0.025) # corresponds to 39 non-coord columns of data
L_INDS = None #None # specific indices of data to select
HEADINGS = np.array(['aaa0043','aaa0044','aaa0060','aaa0061','aaa0063','aaa0064','aaa0066','aaa0069','aaa0086','aaa0087','aaa_0051','aaa_0053','aaa_0054','aaa_0059','aaa_0071','aaa_0072'])
class PennImageData(Dataset):
def __init__(self,data_inds = None,rot_augment = False,k_inds = None):
self.data_dir = "./penn_image_data" # this may need to be adjusted! hope not
self.data = torch.load(osp.join(self.data_dir,'img_kvals_interp_avgK.pt'))
# shape (K,72,72)
self.labels = torch.load(osp.join(self.data_dir,'img_labels_interp_avgK.pt'))
# shape (72,72)
if rot_augment:
for i in range(len(self.data)):
dat = self.data[i]
labs = self.labels[i]
for k in [1,2,3]: # number of 90deg rotations
self.data.append(torch.rot90(dat,k = k,dims = [1,2]))
self.labels.append(torch.rot90(labs,k = k,dims = [0,1]))
if data_inds is not None:
self.data = [self.data[i].float() for i in data_inds]
self.labels = [self.labels[i].long() for i in data_inds]
if k_inds is not None:
self.data = [x[k_inds,...] for x in self.data]
def __len__(self):
return len(self.data)
def __getitem__(self,i):
return self.data[i],self.labels[i]
def __getstate__(self):
state = {
'data': self.data,
'label': self.labels,
}
return state
def __setstate__(self, state):
# Set the object's state from the provided dictionary
self.data = state['data']
self.labels = state['label']
def load(config):
allDat = PennImageData(rot_augment = config.rot_augment)
n_images = len(allDat)
n_splits = 5 # int(1/((1-config.train_split)))
K_INDS = range(39) # wavelength measurements to consider (can't list this dtype in flags I think)
kf = RepeatedKFold(n_splits = n_splits, n_repeats = config.n_repeats, random_state = config.split_seed) # K-fold cross validation
kf_dataloaders = []
for i, (train_inds, test_inds) in enumerate(kf.split(range(n_images))): # for each K-fold split,
n_test = len(test_inds)
n_train = len(train_inds)
# set up training DataLoader
train_data = PennImageData(data_inds = train_inds, k_inds = K_INDS,rot_augment = True)
train_loader = DataLoader(train_data,batch_size = min(config.batch_size, len(train_data)),num_workers=0)
# set up test DataLoader
test_data = PennImageData(data_inds = test_inds, k_inds = K_INDS,rot_augment = True)
test_loader = DataLoader(test_data,batch_size = min(config.batch_size, len(test_data)),num_workers=0)
dataloaders = {'train':train_loader,
'test':test_loader,
'train_inds':train_inds,
'test_inds':test_inds
}
kf_dataloaders.append(dataloaders)
if not config.cross_validate:
break
return kf_dataloaders,K_INDS |
## Elasticsearch的Java客户端
es官方支持的客户端列表
https://www.elastic.co/guide/en/elasticsearch/client/index.html
java客户端:
https://www.elastic.co/guide/en/elasticsearch/client/java-api-client/current/index.html
spring-data-elasticsearch
https://spring.io/projects/spring-data-elasticsearch/
### 1. 引入依赖
gradle
```groovy
dependencies {
implementation 'co.elastic.clients:elasticsearch-java:8.7.0'
implementation 'com.fasterxml.jackson.core:jackson-databind:2.12.3'
}
```
maven
```xml
<dependencies>
<dependency>
<groupId>co.elastic.clients</groupId>
<artifactId>elasticsearch-java</artifactId>
<version>8.7.0</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.12.3</version>
</dependency>
</dependencies>
```
项目的完整pom.xml
```xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>3.0.5</version>
</parent>
<groupId>com.xingray</groupId>
<artifactId>es-demo</artifactId>
<version>1.0.0</version>
<properties>
<maven.compiler.source>19</maven.compiler.source>
<maven.compiler.target>19</maven.compiler.target>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependencies>
<dependency>
<groupId>co.elastic.clients</groupId>
<artifactId>elasticsearch-java</artifactId>
<version>8.7.0</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.12.7.1</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.yaml</groupId>
<artifactId>snakeyaml</artifactId>
<version>2.0</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
</dependencies>
</project>
```
### 3. 配置
https://www.elastic.co/guide/en/elasticsearch/client/java-api-client/8.7/_basic_authentication.html#_basic_authentication
https://www.elastic.co/guide/en/elasticsearch/client/java-api-client/current/connecting.html
在 resource下创建 elasticsearch.properties
```properties
elasticsearch.username=elastic
elasticsearch.password=NkJlhp03WQ0Yn9pnkkSm
elasticsearch.host=localhost
elasticsearch.port=9200
```
创建cofig包,在config目录下创建
```java
package com.xingray.demo.es.config;
import ...
@Configuration
@PropertySource("classpath:elasticsearch.properties")
public class ElasticSearchConfig {
@Value("${elasticsearch.username}")
private String esUsername;
@Value("${elasticsearch.password}")
private String esPassword;
@Value("${elasticsearch.host}")
private String esHost;
@Value("${elasticsearch.port}")
private Integer esPort;
@Bean
public ElasticsearchClient elasticsearchClient() {
CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(esUsername, esPassword));
RestClient restClient = RestClient.builder(new HttpHost(esHost, esPort))
.setHttpClientConfigCallback(builder -> {
builder.disableAuthCaching();
return builder.setDefaultCredentialsProvider(credentialsProvider);
})
.build();
RestClientTransport transport = new RestClientTransport(restClient, new JacksonJsonpMapper());
return new ElasticsearchClient(transport);
}
}
```
注意: 使用 @PropertySource("classpath:elasticsearch.properties") 注解引入配置文件,文件名前加上 classpath:
使用@Value注解引入配置值,@Value("${elasticsearch.username}") 配置值的key要在 ${} 中
### 4. 测试
创建 po 包,添加pojo类
```java
package com.xingray.demo.es.po;
import com.fasterxml.jackson.annotation.JsonProperty;
import lombok.Data;
@Data
public class BankAccount {
@JsonProperty("account_number")
private Long accountNumber;
@JsonProperty("address")
private String address;
@JsonProperty("age")
private Integer age;
@JsonProperty("balance")
private Long balance;
@JsonProperty("city")
private String city;
@JsonProperty("email")
private String email;
@JsonProperty("employer")
private String employer;
@JsonProperty("firstname")
private String firstname;
@JsonProperty("lastname")
private String lastname;
@JsonProperty("gender")
private String gender;
@JsonProperty("state")
private String state;
}
```
这里使用lombok简化代码,es支持使用jackson做JSON转化
在测试目录下创建测试类 ElasticSearchClientTest
```java
package com.xingray.demo.es.test;
import co.elastic.clients.elasticsearch.ElasticsearchClient;
import co.elastic.clients.elasticsearch._types.query_dsl.QueryBuilders;
import co.elastic.clients.elasticsearch.core.SearchRequest;
import co.elastic.clients.elasticsearch.core.SearchResponse;
import co.elastic.clients.elasticsearch.core.search.Hit;
import com.xingray.demo.es.po.BankAccount;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import java.io.IOException;
import java.util.List;
@SpringBootTest
public class ElasticSearchClientTest {
private final ElasticsearchClient client;
@Autowired
public ElasticSearchClientTest(ElasticsearchClient client) {
this.client = client;
}
@Test
public void testSearch01() throws IOException {
SearchRequest searchRequest = new SearchRequest.Builder().index("bank-account-v2").query(QueryBuilders.matchAll(builder -> builder)).build();
SearchResponse<BankAccount> response = client.search(searchRequest, BankAccount.class);
List<Hit<BankAccount>> hits = response.hits().hits();
for(Hit<BankAccount> hit : hits){
BankAccount bankAccount = hit.source();
System.out.println(bankAccount);
}
}
}
```
执行测试得到结果:
```bash
2023-04-30T14:56:44.788+08:00 INFO 17756 --- [ main] c.x.d.es.test.ElasticSearchClientTest : Starting ElasticSearchClientTest using Java 19.0.2 with PID 17756 (started by leixing in D:\code\workspace\demo\java\es-demo)
2023-04-30T14:56:44.789+08:00 INFO 17756 --- [ main] c.x.d.es.test.ElasticSearchClientTest : No active profile set, falling back to 1 default profile: "default"
2023-04-30T14:56:45.861+08:00 INFO 17756 --- [ main] c.x.d.es.test.ElasticSearchClientTest : Started ElasticSearchClientTest in 1.289 seconds (process running for 1.894)
BankAccount(accountNumber=1, address=880 Holmes Lane, age=32, balance=39225, city=Brogan, email=amberduke@pyrami.com, employer=Pyrami, firstname=Amber, lastname=Duke, gender=M, state=IL)
BankAccount(accountNumber=6, address=671 Bristol Street, age=36, balance=5686, city=Dante, email=hattiebond@netagy.com, employer=Netagy, firstname=Hattie, lastname=Bond, gender=M, state=TN)
BankAccount(accountNumber=13, address=789 Madison Street, age=28, balance=32838, city=Nogal, email=nanettebates@quility.com, employer=Quility, firstname=Nanette, lastname=Bates, gender=F, state=VA)
BankAccount(accountNumber=18, address=467 Hutchinson Court, age=33, balance=4180, city=Orick, email=daleadams@boink.com, employer=Boink, firstname=Dale, lastname=Adams, gender=M, state=MD)
BankAccount(accountNumber=20, address=282 Kings Place, age=36, balance=16418, city=Ribera, email=elinorratliff@scentric.com, employer=Scentric, firstname=Elinor, lastname=Ratliff, gender=M, state=WA)
BankAccount(accountNumber=25, address=171 Putnam Avenue, age=39, balance=40540, city=Nicholson, email=virginiaayala@filodyne.com, employer=Filodyne, firstname=Virginia, lastname=Ayala, gender=F, state=PA)
BankAccount(accountNumber=32, address=702 Quentin Street, age=34, balance=48086, city=Veguita, email=dillardmcpherson@quailcom.com, employer=Quailcom, firstname=Dillard, lastname=Mcpherson, gender=F, state=IN)
BankAccount(accountNumber=37, address=826 Fillmore Place, age=39, balance=18612, city=Tooleville, email=mcgeemooney@reversus.com, employer=Reversus, firstname=Mcgee, lastname=Mooney, gender=M, state=OK)
BankAccount(accountNumber=44, address=502 Baycliff Terrace, age=37, balance=34487, city=Yardville, email=aureliaharding@orbalix.com, employer=Orbalix, firstname=Aurelia, lastname=Harding, gender=M, state=DE)
BankAccount(accountNumber=49, address=451 Humboldt Street, age=23, balance=29104, city=Sunriver, email=fultonholt@anocha.com, employer=Anocha, firstname=Fulton, lastname=Holt, gender=F, state=RI)
```
### 6. 对文档进行操作
创建对象类
```java
package com.xingray.demo.es.test.po;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Product {
private String sku;
private String name;
private Double price;
}
```
#### 6.1 插入数据
向es中插入数据,如果index不存在会自动创建
执行测试:
```java
@Test
public void indexTest01() throws IOException {
Product product = new Product("bk-1", "City bike", 123.0);
IndexResponse response = client.index(i -> i
.index("products")
.id(product.getSku())
.document(product)
);
System.out.println("Indexed with version " + response.version());
}
```
在es中创建索引并存入一个product对象,查询一下:
```json
GET /products/_search
{
"query": {
"match_all": {}
}
}
```
返回
```json
{
"took": 0,
"timed_out": false,
"_shards": {
"total": 1,
"successful": 1,
"skipped": 0,
"failed": 0
},
"hits": {
"total": {
"value": 1,
"relation": "eq"
},
"max_score": 1,
"hits": [
{
"_index": "products",
"_id": "bk-1",
"_score": 1,
"_source": {
"sku": "bk-1",
"name": "City bike",
"price": 123
}
}
]
}
}
```
#### 6.2 更新数据
```java
@Test
public void indexUpdateTest() throws IOException {
Product product = new Product("bk-1", "new City bike", 150.0);
IndexResponse response = client.index(i -> i
.index("products")
.id(product.getSku())
.document(product)
);
System.out.println("Indexed with version " + response.version());
}
```
这里 id 值为 product.getSku() 任然是 "bk-1" ,更新了 name 和 price
搜索结果:
```json
{
"took": 467,
"timed_out": false,
"_shards": {
"total": 1,
"successful": 1,
"skipped": 0,
"failed": 0
},
"hits": {
"total": {
"value": 1,
"relation": "eq"
},
"max_score": 1,
"hits": [
{
"_index": "products",
"_id": "bk-1",
"_score": 1,
"_source": {
"sku": "bk-1",
"name": "new City bike",
"price": 150
}
}
]
}
}
```
#### 6.3 删除数据
根据id删除
```
@Test
public void deleteDocumentTest() throws IOException {
Product product = new Product("bk-1", "new City bike", 150.0);
DeleteResponse response = client.delete(builder -> {
builder.index("products")
.id(product.getSku());
return builder;
});
System.out.println(response);
}
```
返回:
```bash
DeleteResponse: {"_id":"bk-1","_index":"products","_primary_term":1,"result":"deleted","_seq_no":2,"_shards":{"failed":0.0,"successful":1.0,"total":2.0},"_version":3}
```
#### 6.4 查看数据
等价于请求:
```json
GET /products/_search
{
"query": {
"match_all": {}
}
}
```
java代码实现:
```java
@Test
public void queryDocumentTest() throws IOException {
SearchResponse<Product> searchResponse = client.search(search -> {
search.index("products");
search.query(query -> query.matchAll(matchAll -> matchAll));
return search;
}, Product.class);
System.out.println(searchResponse);
}
```
结果:
```bash
SearchResponse: {"took":0,"timed_out":false,"_shards":{"failed":0.0,"successful":1.0,"total":1.0,"skipped":0.0},"hits":{"total":{"relation":"eq","value":1},"hits":[{"_index":"products","_id":"bk-1","_score":1.0,"_source":"Product(sku=bk-1, name=new City bike, price=150.0)"}],"max_score":1.0}}
```
### 7. 检索
### 8.聚合
如下:
```
GET /bank-account-v2/_search
{
"query": {
"match_all": {}
},
"size": 0,
"aggs": {
"ageAgg":{
"terms": {
"field": "age",
"size": 10
}
},
"ageAvg":{
"avg": {
"field": "age"
}
},
"balanceAvg":{
"avg": {
"field": "balance"
}
}
}
}
```
java代码实现:
```java
@Test
public void mappingCreate() throws IOException {
SearchResponse<BankAccount> searchResponse = client.search(search ->
search.index("bank-account-v2")
.query(query -> query.matchAll(matchAll -> matchAll))
.aggregations("ageAgg", ageAgg ->
ageAgg.terms(terms ->
terms.field("age")))
.aggregations("ageAvg", ageAvg -> {
return ageAvg.avg(avg ->
avg.field("age"));
})
.aggregations("balanceAvg", balanceAvg ->
balanceAvg.avg(avg ->
avg.field("balance"))),
BankAccount.class);
System.out.println(searchResponse);
}
```
返回:
```json
{
"_shards":{
"total":1.0,
"failed":0.0,
"successful":1.0,
"skipped":0.0
},
"hits":{
"hits":[
{
"_index":"bank-account-v2",
"_source":"BankAccount(accountNumber=1, address=880 Holmes Lane, age=32, balance=39225, city=Brogan, email=amberduke@pyrami.com, employer=Pyrami, firstname=Amber, lastname=Duke, gender=M, state=IL)",
"_id":"1",
"_score":1.0
},
{
"_index":"bank-account-v2",
"_source":"BankAccount(accountNumber=6, address=671 Bristol Street, age=36, balance=5686, city=Dante, email=hattiebond@netagy.com, employer=Netagy, firstname=Hattie, lastname=Bond, gender=M, state=TN)",
"_id":"6",
"_score":1.0
},
{
"_index":"bank-account-v2",
"_source":"BankAccount(accountNumber=13, address=789 Madison Street, age=28, balance=32838, city=Nogal, email=nanettebates@quility.com, employer=Quility, firstname=Nanette, lastname=Bates, gender=F, state=VA)",
"_id":"13",
"_score":1.0
},
{
"_index":"bank-account-v2",
"_source":"BankAccount(accountNumber=18, address=467 Hutchinson Court, age=33, balance=4180, city=Orick, email=daleadams@boink.com, employer=Boink, firstname=Dale, lastname=Adams, gender=M, state=MD)",
"_id":"18",
"_score":1.0
},
{
"_index":"bank-account-v2",
"_source":"BankAccount(accountNumber=20, address=282 Kings Place, age=36, balance=16418, city=Ribera, email=elinorratliff@scentric.com, employer=Scentric, firstname=Elinor, lastname=Ratliff, gender=M, state=WA)",
"_id":"20",
"_score":1.0
},
{
"_index":"bank-account-v2",
"_source":"BankAccount(accountNumber=25, address=171 Putnam Avenue, age=39, balance=40540, city=Nicholson, email=virginiaayala@filodyne.com, employer=Filodyne, firstname=Virginia, lastname=Ayala, gender=F, state=PA)",
"_id":"25",
"_score":1.0
},
{
"_index":"bank-account-v2",
"_source":"BankAccount(accountNumber=32, address=702 Quentin Street, age=34, balance=48086, city=Veguita, email=dillardmcpherson@quailcom.com, employer=Quailcom, firstname=Dillard, lastname=Mcpherson, gender=F, state=IN)",
"_id":"32",
"_score":1.0
},
{
"_index":"bank-account-v2",
"_source":"BankAccount(accountNumber=37, address=826 Fillmore Place, age=39, balance=18612, city=Tooleville, email=mcgeemooney@reversus.com, employer=Reversus, firstname=Mcgee, lastname=Mooney, gender=M, state=OK)",
"_id":"37",
"_score":1.0
},
{
"_index":"bank-account-v2",
"_source":"BankAccount(accountNumber=44, address=502 Baycliff Terrace, age=37, balance=34487, city=Yardville, email=aureliaharding@orbalix.com, employer=Orbalix, firstname=Aurelia, lastname=Harding, gender=M, state=DE)",
"_id":"44",
"_score":1.0
},
{
"_index":"bank-account-v2",
"_source":"BankAccount(accountNumber=49, address=451 Humboldt Street, age=23, balance=29104, city=Sunriver, email=fultonholt@anocha.com, employer=Anocha, firstname=Fulton, lastname=Holt, gender=F, state=RI)",
"_id":"49",
"_score":1.0
}
],
"total":{
"value":1000,
"relation":"eq"
},
"max_score":1.0
},
"took":2,
"timed_out":false,
"aggregations":{
"lterms#ageAgg":{
"doc_count_error_upper_bound":0,
"sum_other_doc_count":463,
"buckets":[
{
"doc_count":61,
"key":31
},
{
"doc_count":60,
"key":39
},
{
"doc_count":59,
"key":26
},
{
"doc_count":52,
"key":32
},
{
"doc_count":52,
"key":35
},
{
"doc_count":52,
"key":36
},
{
"doc_count":51,
"key":22
},
{
"doc_count":51,
"key":28
},
{
"doc_count":50,
"key":33
},
{
"doc_count":49,
"key":34
}
]
},
"avg#ageAvg":{
"value":30.171
},
"avg#balanceAvg":{
"value":25714.837
}
}
}
```
附:
elasticsearch.properties:
```properties
elasticsearch.username=elastic
elasticsearch.password=NkJlhp03WQ0Yn9pnkkSm
elasticsearch.host=localhost
elasticsearch.port=9200
```
Config:
```java
@PropertySource("classpath:elasticsearch.properties")
public class ElasticSearchConfig {
@Value("${elasticsearch.username}")
private String esUsername;
@Value("${elasticsearch.password}")
private String esPassword;
@Value("${elasticsearch.host}")
private String esHost;
@Value("${elasticsearch.port}")
private Integer esPort;
@Bean
public ElasticsearchClient elasticsearchClient() {
CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(esUsername, esPassword));
RestClient restClient = RestClient.builder(new HttpHost(esHost, esPort))
.setHttpClientConfigCallback(builder -> {
builder.disableAuthCaching();
return builder.setDefaultCredentialsProvider(credentialsProvider);
})
.build();
RestClientTransport transport = new RestClientTransport(restClient, new JacksonJsonpMapper());
return new ElasticsearchClient(transport);
}
}
```
Test:
```java
@SpringBootTest
public class ElasticSearchClientTest {
private final ElasticsearchClient client;
@Autowired
public ElasticSearchClientTest(ElasticsearchClient client) {
this.client = client;
}
@Test
public void testSearch01() throws IOException {
SearchRequest searchRequest = new SearchRequest.Builder().index("bank-account-v2").query(QueryBuilders.matchAll(builder -> builder)).build();
SearchResponse<BankAccount> response = client.search(searchRequest, BankAccount.class);
List<Hit<BankAccount>> hits = response.hits().hits();
for (Hit<BankAccount> hit : hits) {
BankAccount bankAccount = hit.source();
System.out.println(bankAccount);
}
}
@Test
public void indexTest01() throws IOException {
Product product = new Product("bk-1", "City bike", 123.0);
IndexResponse response = client.index(i -> i
.index("products")
.id(product.getSku())
.document(product)
);
System.out.println("Indexed with version " + response.version());
}
@Test
public void indexUpdateTest() throws IOException {
Product product = new Product("bk-1", "new City bike", 150.0);
IndexResponse response = client.index(i -> i
.index("products")
.id(product.getSku())
.document(product)
);
System.out.println("Indexed with version " + response.version());
}
@Test
public void deleteDocumentTest() throws IOException {
Product product = new Product("bk-1", "new City bike", 150.0);
DeleteResponse response = client.delete(builder -> {
builder.index("products")
.id(product.getSku());
return builder;
});
System.out.println(response);
}
@Test
public void queryDocumentTest() throws IOException {
SearchResponse<Product> searchResponse = client.search(search -> {
search.index("products");
search.query(query -> query.matchAll(matchAll -> matchAll));
return search;
}, Product.class);
System.out.println(searchResponse);
}
@Test
public void mappingCreate() throws IOException {
SearchResponse<BankAccount> searchResponse = client.search(search ->
search.index("bank-account-v2").from(0).size(10)
.query(query -> query.matchAll(matchAll -> matchAll))
.aggregations("ageAgg", ageAgg ->
ageAgg.terms(terms ->
terms.field("age")))
.aggregations("ageAvg", ageAvg -> {
return ageAvg.avg(avg ->
avg.field("age"));
})
.aggregations("balanceAvg", balanceAvg ->
balanceAvg.avg(avg ->
avg.field("balance"))),
BankAccount.class);
System.out.println(searchResponse);
}
}
``` |
import * as React from 'react';
import Paper from '@mui/material/Paper';
import Table from '@mui/material/Table';
import TableBody from '@mui/material/TableBody';
import TableCell from '@mui/material/TableCell';
import TableContainer from '@mui/material/TableContainer';
import TableHead from '@mui/material/TableHead';
import TablePagination from '@mui/material/TablePagination';
import TableRow from '@mui/material/TableRow';
import {
alpha,
AlphalinxInc,
Emily,
Moneybuy,
Rollerduster,
SoNowWhat,
WhyNot,
zello,
} from '../assets/images';
const columns = [
{ id: 'name', label: 'Name', minWidth: 120 },
{ id: 'incorporator', label: 'Incorporator', minWidth: 100 },
{
id: 'jurisdiction',
label: 'Jurisdiction',
minWidth: 120,
align: 'right',
},
{
id: 'industry',
label: 'Industry',
minWidth: 120,
align: 'right',
},
{
id: 'mailbox',
label: 'Mailbox',
minWidth: 120,
align: 'right',
},
{
id: 'lastactionon',
label: 'Last Action On',
minWidth: 120,
align: 'right',
},
];
function createData(name, incorporator, jurisdiction, industry, mailbox, lastactionon, image) {
return { name, incorporator, jurisdiction, industry, mailbox, lastactionon, image };
}
const rows = [
createData('Alpha inc.', 'Jake Gyllenhaal', 'Freezone', 'B2B', 'Abu Dhabi', '23/12/2022', alpha),
createData('Alphalinx Inc.', 'Jake Gyllenhaal', 'Mainland', 'B2C', 'Jabal Jais', '23/12/2022', AlphalinxInc),
createData('Emily Henry-Jones', 'Jake Gyllenhaal', 'Freezone', 'B2B', 'Burj Province', '23/12/2022', Emily),
createData('Rollerduster', 'Jake Gyllenhaal', 'Freezone', 'B2B', 'Burj Province', '23/12/2022', Rollerduster),
createData('Zeropy', 'Jake Gyllenhaal', 'Mainland', 'B2C', 'Abu Dhabi', '23/12/2022', AlphalinxInc),
createData('Wellson', 'Jake Gyllenhaal', 'Freezone', 'B2B', 'Jabal Jais', '23/12/2022', alpha),
createData('WhyNot Inc.', 'Jake Gyllenhaal', 'Mainland', 'B2C', 'Burj Province', '23/12/2022', WhyNot),
createData('Moneybuy', 'Jake Gyllenhaal', 'Freezone', 'B2B', 'Abu Dhabi', '23/12/2022', Moneybuy),
createData('SoNowWhat Inc.', 'Jake Gyllenhaal', 'Mainland', 'B2C', 'Jabal Jais', '23/12/2022', SoNowWhat),
];
const TableComponent = () => {
const [page, setPage] = React.useState(0);
const [rowsPerPage, setRowsPerPage] = React.useState(10);
const handleChangePage = (event, newPage) => {
setPage(newPage);
};
const handleChangeRowsPerPage = (event) => {
setRowsPerPage(+event.target.value);
setPage(0);
};
return (
<Paper sx={{ width: '100%', overflow: 'hidden' }}>
<TableContainer sx={{ maxHeight: 440 }}>
<Table stickyHeader aria-label="sticky table">
<TableHead>
<TableRow>
{columns.map((column) => (
<TableCell
key={column.id}
align={column.align}
style={{ minWidth: column.minWidth, background: '#E4E4E4', color: '#6A6A6D' }}
>
{column.label}
</TableCell>
))}
</TableRow>
</TableHead>
<TableBody>
{rows
.slice(page * rowsPerPage, page * rowsPerPage + rowsPerPage)
.map((row) => {
return (
<TableRow hover role="checkbox" tabIndex={-1} key={row.code}>
{columns.map((column) => {
const value = row[column.id];
if (column.id === 'name') {
return (
<TableCell key={column.id} align={column.align} style={{ display: "flex", alignItems: "center" }}>
<img src={row.image} alt="Company Logo" style={{ width: 28, height: 28, marginRight: 8 }} />
{value}
</TableCell>
);
}
return (
<TableCell key={column.id} align={column.align}>
{column.format && typeof value === 'number' ? column.format(value) : value}
</TableCell>
);
})}
</TableRow>
);
})}
</TableBody>
</Table>
</TableContainer>
<TablePagination
rowsPerPageOptions={[10, 25, 100]}
component="div"
count={rows.length}
rowsPerPage={rowsPerPage}
page={page}
onPageChange={handleChangePage}
onRowsPerPageChange={handleChangeRowsPerPage}
/>
</Paper>
);
}
export default TableComponent; |
<script setup>
const format = (percentage) => (percentage / 10)
import { ref } from "vue";
const isShow = ref(false);
const showMore = () =>{
isShow.value =! isShow.value;
}
</script>
<template>
<div class="flex flex-col items-center justify-center space-y-5">
<div class="flex items-center justify-center space-x-5">
<p
class="py-1 px-5 bg-green-500 text-white text-xl font-bold ring-1 ring-green-400"
>
7.5
</p>
<p class="text-green-500 font-bold text-xl">Good</p>
</div>
<div class="demo-progress grid grid-cols-1 gap-1 items-center">
<div class="flex justify-center">
<p class="text-blue-700 px-4 w-48 text-right">Cleanliness</p>
<el-progress max="10" :percentage="83" :format="format" />
</div>
<div class="flex justify-center">
<p class="text-blue-700 px-4 w-48 text-right">Comfort</p>
<el-progress :percentage="83" :format="format"/>
</div>
<div class="flex justify-center">
<p class="text-blue-700 px-4 w-48 text-right">Location</p>
<el-progress :percentage="76" :format="format"/>
</div>
<div class="flex justify-center">
<p class="text-blue-700 px-4 w-48 text-right">Facilities</p>
<el-progress :percentage="63" :format="format"/>
</div>
<div class="flex justify-center">
<p class="text-blue-700 px-4 w-48 text-right">Staff</p>
<el-progress :percentage="93" :format="format"/>
</div>
<div class="flex justify-center">
<p class="text-blue-700 px-4 w-48 text-right">Value for money</p>
<el-progress :percentage="43" :format="format"/>
</div>
</div>
<div class="grid grid-cols-2 gap-8 px-16 p-2 pb-4" >
<div class="bg-white flex flex-col p-6 space-y-3">
<h1 class="text-xl font-bold text-gray-800">Good Choice at Phnom Penh</h1>
<div class="flex space-x-2">
<img class="py-2 pr-3 w-auto h-8 flex" src="https://upload.wikimedia.org/wikipedia/commons/thumb/8/83/Flag_of_Cambodia.svg/125px-Flag_of_Cambodia.svg.png" alt="">
<p class="text-justify text-gray-500"> Lorem ipsum dolor sit amet consectetur adipisicing elit. Odit obcaecati optio distinctio corporis atque! Animi illum dignissimos ab accusamus quo blanditiis reiciendis eaque, nulla vero obcaecati fugit soluta!</p>
</div>
</div>
<div class="bg-white flex flex-col p-6 space-y-3 h-auto">
<h1 class="text-xl font-bold text-gray-800">Good Choice at Phnom Penh</h1>
<div class="flex space-x-2">
<img class="py-2 pr-3 w-auto h-8" src="https://upload.wikimedia.org/wikipedia/commons/thumb/8/83/Flag_of_Cambodia.svg/125px-Flag_of_Cambodia.svg.png" alt="">
<p class="text-justify text-gray-500"> Lorem ipsum dolor sit amet consectetur adipisicing elit. Odit obcaecati optio distinctio corporis atque! Animi illum dignissimos ab accusamus quo blanditiis reiciendis eaque, nulla vero obcaecati fugit soluta! </p>
</div>
</div>
<div class="bg-white flex flex-col p-6 space-y-3 m-0">
<h1 class="text-xl font-bold text-gray-800">Good Choice at Phnom Penh</h1>
<div class="flex space-x-2">
<img class="py-2 pr-3 w-auto h-8 flex" src="https://upload.wikimedia.org/wikipedia/commons/thumb/8/83/Flag_of_Cambodia.svg/125px-Flag_of_Cambodia.svg.png" alt="">
<p class="text-justify text-gray-500"> Lorem ipsum dolor sit amet consectetur adipisicing elit. Odit obcaecati optio distinctio corporis atque! Animi illum dignissimos ab accusamus quo blanditiis reiciendis eaque, nulla vero obcaecati fugit soluta!</p>
</div>
</div>
<div class="bg-white flex flex-col p-6 space-y-3">
<h1 class="text-xl font-bold text-gray-800">Good Choice at Phnom Penh</h1>
<div class="flex space-x-2">
<img class="py-2 pr-3 w-auto h-8 flex" src="https://upload.wikimedia.org/wikipedia/commons/thumb/8/83/Flag_of_Cambodia.svg/125px-Flag_of_Cambodia.svg.png" alt="">
<p class="text-justify text-gray-500"> Lorem ipsum dolor sit amet consectetur adipisicing elit. Odit obcaecati optio distinctio corporis atque! Animi illum dignissimos ab accusamus quo blanditiis reiciendis eaque, nulla vero obcaecati fugit soluta!</p>
</div>
</div>
<div class="" v-if="isShow">
<div class="bg-white flex flex-col p-6 space-y-3">
<h1 class="text-xl font-bold text-gray-800">Good Choice at Cambodia</h1>
<div class="flex space-x-2">
<img class="py-2 pr-3 w-auto h-8 flex" src="https://upload.wikimedia.org/wikipedia/commons/thumb/8/83/Flag_of_Cambodia.svg/125px-Flag_of_Cambodia.svg.png" alt="">
<p class="text-justify text-gray-500"> Lorem ipsum dolor sit amet consectetur adipisicing elit. Odit obcaecati optio distinctio corporis atque! Animi illum dignissimos ab accusamus quo blanditiis reiciendis eaque, nulla vero obcaecati fugit soluta!</p>
</div>
</div>
</div>
</div>
<div class="flex justify-center pb-6">
<p @click="showMore" class="p-3 ring-1 ring-blue-700 text-blue-700 font-medium cursor-pointer hover:bg-blue-700 hover:text-white">
<span v-if="isShow" >SHOW LESS REVIEW</span>
<span v-else >SHOW ALL REVIEW</span>
</p>
</div>
</div>
</template>
<style>
.demo-progress .el-progress--line {
margin-bottom: 15px;
width: 350px;
}
.el-progress-bar__inner {
background-color: rgb(29 78 216);
}
.demo-progress .el-progress--line {
margin: 0;
}
</style> |
import request from "supertest";
import { Connection } from "typeorm";
import { v4 as uuidV4 } from "uuid";
import { app } from "../../../../app";
import createConnection from "../../../../database/index";
import { hash } from "bcryptjs";
let connection: Connection;
describe("Show User Profile Controller", () => {
beforeAll(async () => {
connection = await createConnection();
await connection.runMigrations();
const id = uuidV4();
const password = await hash("admin", 8);
await connection.query(
`INSERT INTO USERS (
id, name, email, password, created_at, updated_at)
VALUES (
'${id}', 'admin', 'admin@mail.com', '${password}', 'now()', 'now()')`
);
});
afterAll(async () => {
await connection.dropDatabase();
await connection.close();
});
it("should be able to list an user profile", async () => {
const responseToken = await request(app).post("/api/v1/sessions").send({
email: "admin@mail.com",
password: "admin",
});
const { token } = responseToken.body;
const response = await request(app)
.get("/api/v1/profile")
.send()
.set({
Authorization: `Bearer ${token}`,
});
expect(response.status).toBe(200);
expect(response.body.name).toBe("admin");
expect(response.body.email).toBe("admin@mail.com");
});
}); |
load(file = "./data/spain_geodata_temperature_1989_spring.RData")
## librerias básicas
library(dplyr)
library(ggplot2)
library(ggpubr)
library(readr)
library(reshape2)
## Librerias de geo estadística
library(geoR)
library(gstat)
library(rgdal)
library(sp)
library(spdep)
library(MASS)
powerTransform <- function(y, lambda1, lambda2 = NULL, method = "boxcox") {
boxcoxTrans <- function(x, lam1, lam2 = NULL) {
# if we set lambda2 to zero, it becomes the one parameter transformation
lam2 <- ifelse(is.null(lam2), 0, lam2)
if (lam1 == 0L) {
log(y + lam2)
} else {
(((y + lam2)^lam1) - 1) / lam1
}
}
switch(method
, boxcox = boxcoxTrans(y, lambda1, lambda2)
, tukey = y^lambda1
)
}
bc2 <- boxcoxfit(sp_data_final$temp, lambda2 = F)
bcfit = boxcox(lm(sp_data_final$temp ~ 1),
lambda = seq(-0.5,2.5,0.01),
plotit = T)
bcfit
lambda <- bcfit$x[which.max(bcfit$y)]
temp_sqrt <- powerTransform(sp_data_final$temp, 0.5)
temp_quad <- powerTransform(sp_data_final$temp, 2)
temp_opti <- powerTransform(sp_data_final$temp, lambda)
temp_log <- powerTransform(sp_data_final$temp, 0)
sp_data_final$temp_sqrt = temp_sqrt
sp_data_final$temp_quad = temp_quad
sp_data_final$temp_opti = temp_opti
sp_data_final$temp_log = temp_log
sp_data_final
d = sp_data_final %>% dplyr::select(longitude,latitude,temp_5) # guardamos el set de datos recortado en un objeto
coordinates(d) = ~longitude+latitude
gd <- as.geodata(d) # lo pasamos a un objetivo geodata para poder graficarlo
plot(gd, lowess=TRUE)
temp_sqrt <- powerTransform(sp_data_bin$temp, 0.5)
temp_quad <- powerTransform(sp_data_bin$temp, 2)
temp_opti <- powerTransform(sp_data_bin$temp, lambda)
temp_log <- powerTransform(sp_data_bin$temp, 0)
sp_data_bin$temp_sqrt = temp_sqrt
sp_data_bin$temp_quad = temp_quad
sp_data_bin$temp_opti = temp_opti
sp_data_bin$temp_log = temp_log
write.csv(sp_data_final,'./data/spain_temp_preprocessed_BoxCox_training_data.csv')
write.csv(sp_data_bin,'./data/spain_temp_preprocessed_BoxCox_validation_data.csv') |
//Generics - Reusable Types.
// We use this technique to create customizable classes.
// Syntax
class KeyValuePair<K, V>{
constructor(
public key: K,
public value: V
) { }
}
let pair = new KeyValuePair<number, string>(1, 'Alfredo')
//Generic Functions
class ArrayUtils {
wrapInArray<T>(value: T) {
return [value]
}
}
let utils = new ArrayUtils();
utils.wrapInArray(2);
// Generic Interfaces
interface Result<T> {
data: T | null,
error: string | null
}
function fetch<T>(url: string): Result<T> {
return { data: null, error: null }
}
interface User {
name: string
}
interface Product {
title: string
}
let result = fetch<User>('url');
result.data?.name;
//Generic Contraints
function echo<T extends number | string>(value: T): T {
return value;
}
echo(2);
function echo1<T extends { name: string } | string>(value: T): T {
return value;
}
echo1({ name: 'Alfredo' });
// Extending Generic Classes
interface Product {
name: string,
price: number
}
class Store<T>{
protected _objects: T[] = [];
add(obj: T): void {
this._objects.push(obj)
}
}
//Pass on the generic type parameter
class CompressibleStore<T> extends Store<T>{
compress(){}
}
// Restrict the generic type parameter
class SearchableStore<T extends {name: string}> extends Store<T>{
find(name: string): T | undefined{
return this._objects.find(obj => obj.name === name)
}
}
//Fixing the generic Type Parameter
class ProductStore extends Store<Product>{
filterByCategory(category: string): Product[]{
return []
}
}
//Type Mapping
type ReadOnly<T> = {
// Index Signature
// keyof
readonly [K in keyof T]: T[K]
} |
<?php
/**
* Created by IntelliJ IDEA.
* User: gayan
* Date: 7/10/18
* Time: 10:23 AM
*/ ?>
@extends('admin_template')
@section('content')
<div class="container-fluid" ng-controller="poCtrl" ng-app="poApp">
<div class="card" id="main">
<div class="card-header">
@if($grn_details[0]->status ==APPROVED_PO ||$grn_details[0]->status ==REJECTED_PO)
<button class="btn btn-primary btn-sm" id="print" ng-click="print()"><i class="fa fa-print">
print</i>
</button>
@endif
<div class="card-title float-right font-weight-bold">SUPPLIER INVOICE</div>
</div>
<div class="card-body">
@if (session('alert') =='Grn Approved !')
<div class="alert alert-success">
<button type="button"
class="close"
data-dismiss="alert"
aria-hidden="true">×
</button>
{{ 'Approved' }}
</div>
@endif
@if (session('alert') =='Grn Rejected !')
<div class="alert alert-danger">
<button type="button"
class="close"
data-dismiss="alert"
aria-hidden="true">×
</button>
{{ 'Rejected' }}
</div>
@endif
<div class="card">
<div class="card-header">
<div class="row small">
<div class="col-lg-12">
<div class="form-group">
<img class="small" width="90" src="{{ asset('images/logo_company.png') }}"
alt="">
<label for="" class="float-right"><b>Stock In No:</b>{{$grn_details[0]->id}}</label>
</div>
<div class="form-group">
<!--<span class="small">343 Horana Rd, Panadura 12500, www.bestlife.lk, info@bestlifeltd.com</span>-->
<label for="" class="float-right"><b>DATE:</b>{{$grn_details[0]->created_at}}
</label>
</div>
<div class="form-group">
<label for="" class="float-right"><b>INVOICE:</b>{{$grn_details[0]->invoice}}
</label>
</div>
</div>
</div>
</div>
<div class="card-body form-group">
<div class="row small">
<div class="col-sm-12 form-group">
<div class="card">
<div class="card-body">
<div class="form-group small">
<label class="font-weight-bold float-left" for="">SUPPLIER
:</label><span>{{$grn_details[0]->comapany_name}}</span>
</div>
<div class="form-group small">
<label class="font-weight-bold float-left" for="">SUPPLIER
:</label><span>{{$grn_details[0]->comapany_name}}</span>
</div>
</div>
</div>
</div>
</div>
<div class="card form-group">
<div class="card-body small">
<table class="table table-bordered table-responsive-sm small">
<tr>
<th>ITEM CODE</th>
<th>ITEM NAME</th>
<th>UNIT CP</th>
<th>QTY</th>
<th>TOTAL CP</th>
</tr>
<?php
$total_cost = 0;
?>
@foreach($grn_details['details'] as $grn_detail)
<?php
$cost = $grn_detail->cost_price * $grn_detail->qty;
$total_cost += $cost;
?>
<tr>
<td>{{$grn_detail->product}}</td>
<td>{{$grn_detail->description}}</td>
<td>LKR: {{number_format($grn_detail->cost_price,2)}}</td>
<td>{{$grn_detail->qty}}</td>
<td>LKR: {{number_format($cost,2)}}</td>
</tr>
@endforeach
<tr class="bg-light">
<td colspan="4" class="font-weight-bold">TOTALS</td>
<td>LKR: {{number_format($total_cost,2)}}</td>
</tr>
</table>
</div>
</div>
@if($grn_details[0]->status ==APPROVED_GRN)
<img class="small float-left" width="250" src="{{ asset('images/approved.jpg') }}"
alt="">
@endif
@if($grn_details[0]->status ==REJECTED_GRN)
<img class="small float-left" width="200" src="{{ asset('images/rejected.png') }}"
alt="">
@endif
<div class="form-group float-right">
<label class="col-form-label">Remarks:</label>
<textarea disabled class="form-control" name="" id="" cols="60" rows="2">{{$grn_details[0]->remarks}}</textarea>
</div>
<div class=""></div>
</div>
<div class="card-footer">
@if($grn_details[0]->status ==PENDING_GRN)
<input type="submit" class="btn btn-primary float-right" value="Approve"
ng-click="approveGrn({{$grn_details[0]->id}})">
<input type="button" class="btn btn-danger float-right" value="Reject"
ng-click="rejectGrn({{$grn_details[0]->id}})">
@endif
@if($grn_details[0]->status ==APPROVED_GRN)
<div class="small float-right">
<span><b>Created By:</b>{{$grn_details[0]->user_created}}</span>
<span><b>Approved By:</b>{{$grn_details[0]->user_authorized}}</span>
</div>
@endif
@if($grn_details[0]->status ==REJECTED_GRN)
<div class="small float-right">
<span><b>Created By:</b>{{$grn_details[0]->user_created}}</span>
<span><b>Rejected By:</b>{{$grn_details[0]->user_authorized}}</span>
</div>
@endif
</div>
</div>
</div>
</div>
</div>
<script>
$('div.alert').delay(2000).slideUp(300);
var app = angular.module('poApp', []);
app.controller('poCtrl', function ($scope, $http) {
$scope.print = function () {
window.print();
}
$scope.approveGrn = function (grn) {
bootbox.dialog({
message: "Do you want to approve this grn?",
buttons: {
confirm: {
label: 'Yes',
className: 'btn-success',
callback: function () {
window.open('/stock/approve/' + grn, '_self');
}
},
cancel: {
label: 'No',
className: 'btn-danger'
}
}
});
}
$scope.rejectGrn = function (grn) {
bootbox.dialog({
message: "Do you want to reject this grn?",
buttons: {
confirm: {
label: 'Yes',
className: 'btn-success',
callback: function () {
window.open('/stock/reject/' + grn, '_self');
}
},
cancel: {
label: 'No',
className: 'btn-danger'
}
},
});
}
});
</script>
<style>
@media print {
#print {
visibility: hidden;
}
.main-footer {
visibility: hidden;
}
}
</style>
@endsection |
#!/bin/bash
# Calculate address range from given ip address with mask
# @ Version 1.0
# © 2018 Leonardo Ziviani all rights reserved
# Text color and style
DEFAULT='\e[0m'
RED='\e[0;31m'
GREEN='\e[0;32m'
YELLOW='\e[0;33m'
# Global variables
MASK="32"
MASK_BIT="8"
MASK_MAX_DEC="255"
MASK_MAX_BIN="11111111"
MASK_MIN_DEC="0"
MASK_MIN_BIN="00000000"
# Get network address
function network {
ip=$1
counter=$2
for i in {0..7}
do
pos=$(($MASK_BIT - $counter + 1))
if [ $counter -lt 0 ]; then
break;
fi
counter=$(($counter - 1))
ip=$(echo $ip | sed "s/./0/${pos}")
done
echo $ip
}
# Get broadcast address
function broadcast {
ip=$1
counter=$2
for i in {0..7}
do
pos=$(($MASK_BIT - $counter + 1))
if [ $counter -lt 0 ]; then
break;
fi
counter=$(($counter - 1))
ip=$(echo $ip | sed "s/./1/${pos}")
done
echo $ip
}
# Add zeroes to match 8 bit mask
function add-zeroes {
length=$(echo ${#1})
missing=$(($MASK_BIT - $length))
out=$1
if [ $missing -ne 0 ]; then
for i in `seq 1 $missing`;
do
out="0$out"
done
fi
echo $out
}
# Arguments check
if [ -z $1 ]; then
echo -e "$RED Missing ipv4 address... $DEFAULT"
echo " Use ip-mask-calculator <ipv4 address> <mask>"
echo " Ex. ban-ip 1.1.1.1 24"
exit -1
fi
# Arguments check
if [ -z $2 ]; then
echo -e "$RED Missing netmask... $DEFAULT"
echo " Use ip-mask-calculator <ipv4 address> <mask>"
echo " Ex. ban-ip 1.1.1.1 24"
exit -1
fi
# Check if given ip address is valid
if [[ $1 =~ ^[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+$ ]]; then
for i in 1 2 3 4; do
if [ $(echo "$1" | cut -d. -f$i) -gt 254 ]; then
echo -e "$RED Malformed ip address... $DEFAULT"
echo " You cannot insert a value greater than 254 in an address.."
exit -1
fi
done
else
echo -e "$RED Malformed ip address... $DEFAULT"
echo " Use only ipv4 style ip address"
echo " Ex. 1.1.1.1"
exit -1
fi
# Check if given ip address contains a 0 at the end
if [[ $1 == *".0" ]]; then
echo -e "$RED Malformed ip address... $DEFAULT"
echo " You cannot insert a network address..."
exit -1
fi
# Check if given mask is smaller than 24
if [ $2 -lt 24 ]; then
echo -e "$RED Wrong mask number... $DEFAULT"
echo " Mask must be between 2 and 30"
exit -1
fi
# Check if given mask is bigger than 30
if [ $2 -gt 30 ]; then
echo -e "$RED Wrong mask number... $DEFAULT"
echo "Mask must be between 2 and 30"
exit -1
fi
# Install missing package if needed
if [ $(dpkg-query -W -f='${Status}' bc 2>/dev/null | grep -c "ok installed") -eq 0 ];
then
echo "$YELLOW Installing missing package... $DEFAULT"
apt-get -y install bc
fi
# Get network range for broadcast and net address calculation
range=$(($MASK - $2))
# Split ip in 4 bas 10 numbers
ip1_dec=$(echo "$1" | cut -d. -f1)
ip2_dec=$(echo "$1" | cut -d. -f2)
ip3_dec=$(echo "$1" | cut -d. -f3)
ip4_dec=$(echo "$1" | cut -d. -f4)
# Convert base 10 split in base 2
ip1_bin=$(echo "obase=2; $ip1_dec" | bc)
ip2_bin=$(echo "obase=2; $ip2_dec" | bc)
ip3_bin=$(echo "obase=2; $ip3_dec" | bc)
ip4_bin=$(echo "obase=2; $ip4_dec" | bc)
# Add 0s to match 8 bit length
ip1_bin=$(add-zeroes $ip1_bin)
ip2_bin=$(add-zeroes $ip2_bin)
ip3_bin=$(add-zeroes $ip3_bin)
ip4_bin=$(add-zeroes $ip4_bin)
# Calculate broadcast and network address
broadcast_bin=$(broadcast $ip4_bin $range)
network_bin=$(network $ip4_bin $range)
# Convert in base 10
broadcast_dec=$(echo "ibase=2; $broadcast_bin" | bc)
network_dec=$(echo "ibase=2; $network_bin" | bc)
# Get minumum and maximum usable ips
min=$(($network_dec + 2))
max=$(($broadcast_dec - 1))
clear
echo ""
echo -e " Subnet: \t $GREEN$1$DEFAULT / $YELLOW$2$DEFAULT"
echo -e " Network: \t $GREEN$ip1_dec.$ip2_dec.$ip3_dec.$YELLOW$network_dec$DEFAULT"
echo -e " Broadcast: \t $GREEN$ip1_dec.$ip2_dec.$ip3_dec.$YELLOW$broadcast_dec$DEFAULT"
echo -e " Range: \t $GREEN$ip1_dec.$ip2_dec.$ip3_dec.$YELLOW$min$DEFAULT - $YELLOW$max$DEFAULT"
echo ""
exit 0 |
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* Bureaucrat.cpp :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: zyunusov <zyunusov@student.42wolfsburg.de> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2023/03/15 23:44:52 by zyunusov #+# #+# */
/* Updated: 2023/03/17 17:37:58 by zyunusov ### ########.fr */
/* */
/* ************************************************************************** */
#include "Bureaucrat.hpp"
Bureaucrat::Bureaucrat(std::string const &name, int grade): _name(name), _grade(grade)
{
if (grade < 1)
throw Bureaucrat::GradeTooHighException();
else if (grade > 150)
throw Bureaucrat::GradeTooLowException();
else
std::cout << "Bureaucrat Constructor called\n";
}
Bureaucrat::~Bureaucrat()
{
std::cout << "Bureaucrat Destructor called\n";
}
Bureaucrat& Bureaucrat::operator=(const Bureaucrat& src)
{
this->_grade = src._grade;
std::cout << "Bureaucrat Copy assignment operator called\n";
return (*this);
}
Bureaucrat::Bureaucrat(const Bureaucrat& src): _name(src._name), _grade(src._grade)
{
std::cout << "Bureaucrat Copy constructor called\n";
}
const std::string& Bureaucrat::getName() const
{
return (this->_name);
}
int Bureaucrat::getGrade() const
{
return (this->_grade);
}
void Bureaucrat::increase()
{
this->_grade -= 1;
if (this->_grade < 1)
throw Bureaucrat::GradeTooHighException();
}
void Bureaucrat::decrease()
{
this->_grade += 1;
if (this->_grade > 150)
throw Bureaucrat::GradeTooLowException();
}
std::ostream& operator<<(std::ostream &output, Bureaucrat const &src)
{
output << "Name: " << src.getName() << ", Grade: " << src.getGrade() << std::endl;
return (output);
}
void Bureaucrat::executeForm(AForm const & form) {
if ( this->_grade > form.getGradeToExecute())
throw Bureaucrat::GradeTooLowException();
if (!form.getIsSigned())
throw AForm::FormNotSignException();
std::cout << "bureaucrat executed form\n";
}
void Bureaucrat::signForm(AForm const &src)
{
if (this->_grade <= src.getGradeToSign())
std::cout << this->_name << " signed " << src.getName() << std::endl;
else
std::cout << this->_name << " couldn’t sign " << src.getName() << " because required grade is too high" << std::endl;
} |
<ui:composition xmlns="http://www.w3.org/1999/xhtml"
xmlns:ui="http://java.sun.com/jsf/facelets"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:p="http://primefaces.org/ui"
template="/templates/templateContenido.xhtml"
xmlns:a="http://xmlns.jcp.org/jsf/passthrough">
<ui:define name="cuerpo">
<h2>
Inventario <small>Edición Produto</small>
</h2>
<div class="box box-primary">
<div class="box-header">
<h3 class="box-title">Información Producto</h3>
</div>
<br />
<!-- /.box-header -->
<h:form role="form">
<div class="box-body">
<div class="form-group">
<label for="tfnombre">Nombre Producto (*)</label>
<h:inputText for="tfnombre" class="form-control" id="tfnombre"
a:placeholder="Nombre" value="#{inventarioEditController.nombre}" />
<p:message for="tfnombre" />
</div>
<div class="form-group">
<label for="tftipoPro">Tipo de Producto (*)</label> <br></br>
<h:selectOneMenu id="cbtipoProducto"
value="#{inventarioEditController.tipoProducto}"
converter="tipoProConverter" style="width:240px">
<f:selectItems value="#{inventarioController.tipoproductos}"
var="tipoPro" itemValue="#{tipoPro}"
itemLabel="#{tipoPro.nombre}" />
</h:selectOneMenu>
</div>
<div class="form-group">
<label for="tffecha">Fecha de Ingreso (*)</label>
<div class="input-group">
<div class="input-group-addon">
<i class="fa fa-calendar"></i>
</div>
<p:inputMask id="tffecha" placeholder="Año-Mes-Dia"
value="#{inventarioEditController.fechaIngreso}">
<f:convertDateTime pattern="yyyy-MM-dd" />
</p:inputMask>
</div>
<p:message for="tffecha" />
</div>
<div class="form-group">
<label for="tfdes">Descripción</label>
<p:inputTextarea type="text" class="form-control" id="tfdes"
a:placeholder="Descripción"
value="#{inventarioEditController.descripcion}" />
<p:message for="tfdes" />
</div>
<div class="form-group">
<label for="tfcant"> Cantidad (*)</label><br />
<p:spinner min="0" id="tfcant"
value="#{inventarioEditController.cantidadProducto}"
style="width:240px" />
<p:message for="tfcant" />
</div>
<div class="form-group">
<label for="tfcodigolote">Codigo Lote (*)</label><br />
<h:inputText type="text" class="form-control" id="tfcodigolote"
a:placeholder="Codigo lote"
value="#{inventarioEditController.codigoLote}" />
<p:message for="tfcodigolote" />
</div>
<div class="form-group">
<label for="tfpeso"> Peso </label>
<p:selectOneButton value="#{inventarioEditController.pesoOpcion}">
<h:inputText id="tfpeso" value="#{inventarioEditController.peso}"
a:placeholder="Peso" class="form-control" />
<f:selectItem itemValue="Libras" itemLabel="Libras" />
<f:selectItem itemValue="Gramos" itemLabel="Gramos" />
<f:selectItem itemValue="Kilogramos" itemLabel="Kilogramos" />
<f:selectItem itemValue="Toneladas" itemLabel="Toneladas" />
</p:selectOneButton>
<p:message for="tfpeso" />
</div>
<div class="form-group">
<label for="tfdimen">Dimensiones</label>
<h:inputText type="text" class="form-control" id="tfdimen"
a:placeholder="Dimensiones"
value="#{inventarioEditController.dimensiones}" />
<p:message for="tfdimen" />
</div>
<div class="form-group">
<i class="fa fa-user"></i> <label>Empleado (*) </label><br />
<p:autoComplete id="empleado"
value="#{inventarioEditController.empleado}"
completeMethod="#{inventarioController.completeTheme}" var="emp"
itemLabel="#{emp.nombre} #{emp.apellido}" itemValue="#{emp}"
converter="empleadoConverter" forceSelection="true">
<p:column>
<i class="icon ion-android-person"></i>
</p:column>
<p:column>
<h:outputText value="#{emp.nombre} #{emp.apellido}" />
</p:column>
</p:autoComplete>
<!-- /.input group -->
</div>
<div class="form-group">
<label for="totalVenta">Valor (*)</label>
<div class="input-group">
<div class="input-group-addon">
<i class="fa fa-usd"></i>
</div>
<h:inputText id="totalVenta" a:placeholder="Valor"
value="#{inventarioEditController.valor}" class="form-control" />
</div>
<p:message for="totalVenta" />
<!-- /.input group -->
</div>
<div class="box-footer">
<p:commandButton value="Editar Producto" ajax="false"
update=""
class="btn btn-primary" action="#{inventarioEditController.editar}" />
<p:commandButton value="Cancelar" ajax="false"
update=""
class="btn btn-danger" action="#{inventarioEditController.cancelar}" />
</div>
</div>
<!-- /.box-body -->
</h:form>
</div>
<br />
</ui:define>
</ui:composition> |
-- Revisão de edição de tabelas
CREATE TABLE TABELA(
COLUNA1 VARCHAR(30),
COLUNA2 VARCHAR(30),
COLUNA3 VARCHAR(30)
);
-- Podemos adicionar uma propriedade com ADD
ALTER TABLE TABELA
ADD PRIMARY KEY (COLUNA1);
-- Também podemos adicionar uma nova coluna
ALTER TABLE TABELA
ADD COLUNA4 VARCHAR(30);
-- Podemos adicionar uma coluna em uma certa posição
ALTER TABLE TABELA
ADD COLUNA5 VARCHAR(30) NOT NULL UNIQUE
AFTER COLUNA4;
-- Podemos modificar o tipo de um campo
ALTER TABLE TABELA
MODIFY COLUNA2 DATE NOT NULL;
-- E renomear a tabela
ALTER TABLE TABELA
RENAME PESSOA;
-- Podemos extrair mais informações sobre uma tabela com SHOW (dicionário de dados)
SHOW CREATE TABLE PESSOA;
| PESSOA | CREATE TABLE `PESSOA` (
`COLUNA1` varchar(30) NOT NULL,
`COLUNA2` date NOT NULL,
`COLUNA3` varchar(30) DEFAULT NULL,
`COLUNA4` varchar(30) DEFAULT NULL,
`COLUNA5` varchar(30) NOT NULL,
PRIMARY KEY (`COLUNA1`),
UNIQUE KEY `COLUNA5` (`COLUNA5`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci | |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.