repo_name stringlengths 6 101 | path stringlengths 4 300 | text stringlengths 7 1.31M |
|---|---|---|
InterTurstCo/ActiveFrame5 | CM5/Core/model/src/main/java/ru/intertrust/cm/core/business/api/dto/ColumnInfoConverter.java | <gh_stars>1-10
package ru.intertrust.cm.core.business.api.dto;
import ru.intertrust.cm.core.config.*;
/**
* Конвертирует ColumnInfo в конфигуцию поля типа ДО
*/
public class ColumnInfoConverter {
public static <T extends FieldConfig> FieldConfig convert(ColumnInfo columnInfo, T fieldConfig) {
if (fieldConfig instanceof LongFieldConfig) {
LongFieldConfig longFieldConfig = new LongFieldConfig();
setBasicAttributes(longFieldConfig, columnInfo);
return longFieldConfig;
} else if (fieldConfig instanceof DateTimeFieldConfig) {
DateTimeFieldConfig dateTimeFieldConfig = new DateTimeFieldConfig();
setBasicAttributes(dateTimeFieldConfig, columnInfo);
return dateTimeFieldConfig;
} else if (fieldConfig instanceof ReferenceFieldConfig) {
ReferenceFieldConfig referenceFieldConfig = new ReferenceFieldConfig();
setBasicAttributes(referenceFieldConfig, columnInfo);
return referenceFieldConfig;
} else if (fieldConfig instanceof PasswordFieldConfig) {
PasswordFieldConfig passwordFieldConfig = new PasswordFieldConfig();
setBasicAttributes(passwordFieldConfig, columnInfo);
passwordFieldConfig.setLength(columnInfo.getLength());
return passwordFieldConfig;
} else if (fieldConfig instanceof TimelessDateFieldConfig) {
TimelessDateFieldConfig timelessDateFieldConfig = new TimelessDateFieldConfig();
setBasicAttributes(timelessDateFieldConfig, columnInfo);
return timelessDateFieldConfig;
} else if (fieldConfig instanceof DateTimeWithTimeZoneFieldConfig) {
DateTimeWithTimeZoneFieldConfig timeWithTimeZoneFieldConfig = new DateTimeWithTimeZoneFieldConfig();
setBasicAttributes(timeWithTimeZoneFieldConfig, columnInfo);
return timeWithTimeZoneFieldConfig;
} else if (fieldConfig instanceof DecimalFieldConfig) {
DecimalFieldConfig decimalFieldConfig = new DecimalFieldConfig();
setBasicAttributes(decimalFieldConfig, columnInfo);
decimalFieldConfig.setPrecision(columnInfo.getPrecision());
decimalFieldConfig.setScale(columnInfo.getScale());
return decimalFieldConfig;
} else if (fieldConfig instanceof TextFieldConfig) {
TextFieldConfig textFieldConfig = new TextFieldConfig();
setBasicAttributes(textFieldConfig, columnInfo);
return textFieldConfig;
} else if (fieldConfig instanceof BooleanFieldConfig) {
BooleanFieldConfig booleanFieldConfig = new BooleanFieldConfig();
setBasicAttributes(booleanFieldConfig, columnInfo);
return booleanFieldConfig;
} else if (fieldConfig instanceof StringFieldConfig) {
StringFieldConfig stringFieldConfig = new StringFieldConfig();
setBasicAttributes(stringFieldConfig, columnInfo);
stringFieldConfig.setLength(columnInfo.getLength());
return stringFieldConfig;
}
throw new IllegalArgumentException("Unknown type of field config '" + fieldConfig.getClass().getName() + "'");
}
private static void setBasicAttributes(FieldConfig fieldConfig, ColumnInfo columnInfo) {
fieldConfig.setName(columnInfo.getName());
fieldConfig.setNotNull(columnInfo.isNotNull());
}
}
|
dmijatovic/dv4all-wcp | icons/src/flag/htmlFlag.js |
export default ({title='Flag'})=>(`
<style>
:host{
display: inline-block;
}
/* SCALE SVG TO PARENT */
svg{
width:100%;
height:100%;
}
</style>
<svg version="1.1"
xmlns="http://www.w3.org/2000/svg"
width="64"
height="64"
viewBox="0 0 64 64">
<title>${title}</title>
<path d="M0 0h8v64h-8v-64z"></path>
<path d="M52 40.188c5.164 0 9.661-1.249 12-3.094v-32c-2.339 1.845-6.836 3.094-12 3.094s-9.661-1.249-12-3.094v32c2.339 1.845 6.836 3.094 12 3.094z"></path>
<path d="M38 2.033c-2.932-1.246-7.22-2.033-12-2.033-6.025 0-11.271 1.249-14 3.094v32c2.729-1.845 7.975-3.094 14-3.094 4.78 0 9.068 0.787 12 2.033v-32z"></path>
</svg>
`) |
VladTheEvilCat/mcheli-port-1.12.2 | mcheli/mcheli/particles/MCH_ParticleParam.java | /* */ package mcheli.mcheli.particles;
/* */
/* */ import net.minecraft.world.World;
/* */
/* */ public class MCH_ParticleParam
/* */ {
/* */ public final World world;
/* */ public final String name;
/* */ public double posX;
/* */ public double posY;
/* */ public double posZ;
/* 12 */ public double motionX = 0.0D;
/* 13 */ public double motionY = 0.0D;
/* 14 */ public double motionZ = 0.0D;
/* 15 */ public float size = 1.0F;
/* 16 */ public float a = 1.0F;
/* 17 */ public float r = 1.0F;
/* 18 */ public float g = 1.0F;
/* 19 */ public float b = 1.0F;
/* */ public boolean isEffectWind = false;
/* 21 */ public int age = 0;
/* */ public boolean diffusible = false;
/* */ public boolean toWhite = false;
/* 24 */ public float gravity = 0.0F;
/* 25 */ public float motionYUpAge = 2.0F;
/* */
/* */
/* */ public MCH_ParticleParam(World w, String name, double x, double y, double z) {
/* 29 */ this.world = w;
/* 30 */ this.name = name;
/* 31 */ this.posX = x;
/* 32 */ this.posY = y;
/* 33 */ this.posZ = z;
/* */ }
/* */
/* */
/* */
/* */
/* */ public MCH_ParticleParam(World w, String name, double x, double y, double z, double mx, double my, double mz, float size) {
/* 40 */ this(w, name, x, y, z);
/* 41 */ this.motionX = mx;
/* 42 */ this.motionY = my;
/* 43 */ this.motionZ = mz;
/* 44 */ this.size = size;
/* */ }
/* */
/* */ public void setColor(float a, float r, float g, float b) {
/* 48 */ this.a = a;
/* 49 */ this.r = r;
/* 50 */ this.g = g;
/* 51 */ this.b = b;
/* */ }
/* */
/* */ public void setMotion(double x, double y, double z) {
/* 55 */ this.motionX = x;
/* 56 */ this.motionY = y;
/* 57 */ this.motionZ = z;
/* */ }
/* */ }
/* Location: C:\Users\danie\Desktop\Mod Porting Tools\MC1.7.10_mcheli_1.0.3.jar!\mcheli\mcheli\particles\MCH_ParticleParam.class
* Java compiler version: 6 (50.0)
* JD-Core Version: 1.1.3
*/ |
tanhleno/pegparser | test/java18/test/no/WHILEErr.java | <reponame>tanhleno/pegparser
public class WHILEErr {
public static void main(String[] args) {
do
a = 1;
hile(a == 2);
}
} |
Riphiphip/website | committees/admin.py | <filename>committees/admin.py<gh_stars>0
from django.contrib import admin
# Register your models here.
from .models import Committee
admin.site.register(Committee)
|
bisnukundu/007helpdesk | node_modules/flaschenpost/src/Middleware/index.js | 'use strict';
const { Writable } = require('stream');
const stackTrace = require('stack-trace');
class Middleware extends Writable {
constructor (level, source) {
if (!level) {
throw new Error('Level is missing.');
}
/* eslint-disable global-require */
const flaschenpost = require('../flaschenpost');
/* eslint-enable global-require */
const options = {};
options.objectMode = true;
options.source = source || stackTrace.get()[1].getFileName();
super(options);
this.level = level;
this.logger = flaschenpost.getLogger(options.source);
if (!this.logger[this.level]) {
throw new Error('Level is invalid.');
}
}
_write (chunk, encoding, callback) {
this.logger[this.level](chunk);
callback();
}
}
module.exports = Middleware;
|
haibowen/AndroidStudy | AmazeFileManager-master/app/src/main/java/com/amaze/filemanager/asynchronous/asynctasks/LoadFilesListTask.java | <reponame>haibowen/AndroidStudy
/*
* Copyright (C) 2014 <NAME> <<EMAIL>>, <NAME> <<EMAIL>>
* <NAME> <<EMAIL>>
*
* This file is part of Amaze File Manager.
*
* Amaze File Manager 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.
*
* 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 <http://www.gnu.org/licenses/>.
*/
package com.amaze.filemanager.asynchronous.asynctasks;
import android.content.Context;
import android.database.Cursor;
import android.os.AsyncTask;
import android.provider.MediaStore;
import android.support.v4.util.Pair;
import android.text.format.Formatter;
import com.amaze.filemanager.R;
import com.amaze.filemanager.adapters.data.LayoutElementParcelable;
import com.amaze.filemanager.database.SortHandler;
import com.amaze.filemanager.database.UtilsHandler;
import com.amaze.filemanager.exceptions.CloudPluginException;
import com.amaze.filemanager.filesystem.HybridFile;
import com.amaze.filemanager.filesystem.HybridFileParcelable;
import com.amaze.filemanager.filesystem.RootHelper;
import com.amaze.filemanager.fragments.CloudSheetFragment;
import com.amaze.filemanager.fragments.MainFragment;
import com.amaze.filemanager.utils.DataUtils;
import com.amaze.filemanager.utils.OTGUtil;
import com.amaze.filemanager.utils.OnAsyncTaskFinished;
import com.amaze.filemanager.utils.OnFileFound;
import com.amaze.filemanager.utils.OpenMode;
import com.amaze.filemanager.utils.application.AppConfig;
import com.amaze.filemanager.utils.cloud.CloudUtil;
import com.amaze.filemanager.utils.files.FileListSorter;
import com.cloudrail.si.interfaces.CloudStorage;
import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Collections;
import java.util.Date;
import java.util.LinkedList;
import jcifs.smb.SmbAuthException;
import jcifs.smb.SmbException;
import jcifs.smb.SmbFile;
public class LoadFilesListTask extends AsyncTask<Void, Void, Pair<OpenMode, ArrayList<LayoutElementParcelable>>> {
private String path;
private MainFragment ma;
private Context c;
private OpenMode openmode;
private boolean showHiddenFiles, showThumbs;
private DataUtils dataUtils = DataUtils.getInstance();
private OnAsyncTaskFinished<Pair<OpenMode, ArrayList<LayoutElementParcelable>>> listener;
public LoadFilesListTask(Context c, String path, MainFragment ma, OpenMode openmode,
boolean showThumbs, boolean showHiddenFiles,
OnAsyncTaskFinished<Pair<OpenMode, ArrayList<LayoutElementParcelable>>> l) {
this.path = path;
this.ma = ma;
this.openmode = openmode;
this.c = c;
this.showThumbs = showThumbs;
this.showHiddenFiles = showHiddenFiles;
this.listener = l;
}
@Override
protected Pair<OpenMode, ArrayList<LayoutElementParcelable>> doInBackground(Void... p) {
HybridFile hFile = null;
if (openmode == OpenMode.UNKNOWN) {
hFile = new HybridFile(OpenMode.UNKNOWN, path);
hFile.generateMode(ma.getActivity());
openmode = hFile.getMode();
if (hFile.isSmb()) {
ma.smbPath = path;
}
}
if(isCancelled()) return null;
ma.folder_count = 0;
ma.file_count = 0;
final ArrayList<LayoutElementParcelable> list;
switch (openmode) {
case SMB:
if (hFile == null) {
hFile = new HybridFile(OpenMode.SMB, path);
}
try {
SmbFile[] smbFile = hFile.getSmbFile(5000).listFiles();
list = ma.addToSmb(smbFile, path, showHiddenFiles);
openmode = OpenMode.SMB;
} catch (SmbAuthException e) {
if (!e.getMessage().toLowerCase().contains("denied")) {
ma.reauthenticateSmb();
}
return null;
} catch (SmbException | NullPointerException e) {
e.printStackTrace();
return null;
}
break;
case SFTP:
HybridFile sftpHFile = new HybridFile(OpenMode.SFTP, path);
list = new ArrayList<LayoutElementParcelable>();
sftpHFile.forEachChildrenFile(c, false, file -> {
LayoutElementParcelable elem = createListParcelables(file);
if(elem != null) list.add(elem);
});
break;
case CUSTOM:
switch (Integer.parseInt(path)) {
case 0:
list = listImages();
break;
case 1:
list = listVideos();
break;
case 2:
list = listaudio();
break;
case 3:
list = listDocs();
break;
case 4:
list = listApks();
break;
case 5:
list = listRecent();
break;
case 6:
list = listRecentFiles();
break;
default:
throw new IllegalStateException();
}
break;
case OTG:
list = new ArrayList<>();
listOtg(path, file -> {
LayoutElementParcelable elem = createListParcelables(file);
if(elem != null) list.add(elem);
});
openmode = OpenMode.OTG;
break;
case DROPBOX:
case BOX:
case GDRIVE:
case ONEDRIVE:
CloudStorage cloudStorage = dataUtils.getAccount(openmode);
list = new ArrayList<>();
try {
listCloud(path, cloudStorage, openmode, file -> {
LayoutElementParcelable elem = createListParcelables(file);
if(elem != null) list.add(elem);
});
} catch (CloudPluginException e) {
e.printStackTrace();
AppConfig.toast(c, c.getResources().getString(R.string.failed_no_connection));
return new Pair<>(openmode, list);
}
break;
default:
// we're neither in OTG not in SMB, load the list based on root/general filesystem
list = new ArrayList<>();
RootHelper.getFiles(path, ma.getMainActivity().isRootExplorer(), showHiddenFiles,
mode -> openmode = mode, file -> {
LayoutElementParcelable elem = createListParcelables(file);
if(elem != null) list.add(elem);
});
break;
}
if (list != null && !(openmode == OpenMode.CUSTOM && ((path).equals("5") || (path).equals("6")))) {
int t = SortHandler.getSortType(ma.getContext(), path);
int sortby;
int asc;
if (t <= 3) {
sortby = t;
asc = 1;
} else {
asc = -1;
sortby = t - 4;
}
Collections.sort(list, new FileListSorter(ma.dsort, sortby, asc));
}
return new Pair<>(openmode, list);
}
@Override
protected void onPostExecute(Pair<OpenMode, ArrayList<LayoutElementParcelable>> list) {
super.onPostExecute(list);
listener.onAsyncTaskFinished(list);
}
private LayoutElementParcelable createListParcelables(HybridFileParcelable baseFile) {
if (!dataUtils.isFileHidden(baseFile.getPath())) {
String size = "";
long longSize= 0;
if (baseFile.isDirectory()) {
ma.folder_count++;
} else {
if (baseFile.getSize() != -1) {
try {
longSize = baseFile.getSize();
size = Formatter.formatFileSize(c, longSize);
} catch (NumberFormatException e) {
e.printStackTrace();
}
}
ma.file_count++;
}
LayoutElementParcelable layoutElement = new LayoutElementParcelable(baseFile.getName(),
baseFile.getPath(), baseFile.getPermission(), baseFile.getLink(), size,
longSize, false, baseFile.getDate() + "", baseFile.isDirectory(),
showThumbs, baseFile.getMode());
return layoutElement;
}
return null;
}
private ArrayList<LayoutElementParcelable> listImages() {
ArrayList<LayoutElementParcelable> images = new ArrayList<>();
final String[] projection = {MediaStore.Images.Media.DATA};
final Cursor cursor = c.getContentResolver().query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
projection, null, null, null);
if (cursor == null)
return images;
else if (cursor.getCount() > 0 && cursor.moveToFirst()) {
do {
String path = cursor.getString(cursor.getColumnIndex
(MediaStore.Files.FileColumns.DATA));
HybridFileParcelable strings = RootHelper.generateBaseFile(new File(path), showHiddenFiles);
if (strings != null) {
LayoutElementParcelable parcelable = createListParcelables(strings);
if(parcelable != null) images.add(parcelable);
}
} while (cursor.moveToNext());
}
cursor.close();
return images;
}
private ArrayList<LayoutElementParcelable> listVideos() {
ArrayList<LayoutElementParcelable> videos = new ArrayList<>();
final String[] projection = {MediaStore.Images.Media.DATA};
final Cursor cursor = c.getContentResolver().query(MediaStore.Video.Media.EXTERNAL_CONTENT_URI,
projection, null, null, null);
if (cursor == null)
return videos;
else if (cursor.getCount() > 0 && cursor.moveToFirst()) {
do {
String path = cursor.getString(cursor.getColumnIndex
(MediaStore.Files.FileColumns.DATA));
HybridFileParcelable strings = RootHelper.generateBaseFile(new File(path), showHiddenFiles);
if (strings != null) {
LayoutElementParcelable parcelable = createListParcelables(strings);
if(parcelable != null) videos.add(parcelable);
}
} while (cursor.moveToNext());
}
cursor.close();
return videos;
}
private ArrayList<LayoutElementParcelable> listaudio() {
String selection = MediaStore.Audio.Media.IS_MUSIC + " != 0";
String[] projection = {
MediaStore.Audio.Media.DATA
};
Cursor cursor = c.getContentResolver().query(
MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
projection,
selection,
null,
null);
ArrayList<LayoutElementParcelable> songs = new ArrayList<>();
if (cursor == null)
return songs;
else if (cursor.getCount() > 0 && cursor.moveToFirst()) {
do {
String path = cursor.getString(cursor.getColumnIndex
(MediaStore.Files.FileColumns.DATA));
HybridFileParcelable strings = RootHelper.generateBaseFile(new File(path), showHiddenFiles);
if (strings != null) {
LayoutElementParcelable parcelable = createListParcelables(strings);
if(parcelable != null) songs.add(parcelable);
}
} while (cursor.moveToNext());
}
cursor.close();
return songs;
}
private ArrayList<LayoutElementParcelable> listDocs() {
ArrayList<LayoutElementParcelable> docs = new ArrayList<>();
final String[] projection = {MediaStore.Files.FileColumns.DATA};
Cursor cursor = c.getContentResolver().query(MediaStore.Files.getContentUri("external"),
projection, null, null, null);
String[] types = new String[]{".pdf", ".xml", ".html", ".asm", ".text/x-asm", ".def", ".in", ".rc",
".list", ".log", ".pl", ".prop", ".properties", ".rc",
".doc", ".docx", ".msg", ".odt", ".pages", ".rtf", ".txt", ".wpd", ".wps"};
if (cursor == null)
return docs;
else if (cursor.getCount() > 0 && cursor.moveToFirst()) {
do {
String path = cursor.getString(cursor.getColumnIndex
(MediaStore.Files.FileColumns.DATA));
if (path != null && Arrays.asList(types).contains(path)) {
HybridFileParcelable strings = RootHelper.generateBaseFile(new File(path), showHiddenFiles);
if (strings != null) {
LayoutElementParcelable parcelable = createListParcelables(strings);
if(parcelable != null) docs.add(parcelable);
}
}
} while (cursor.moveToNext());
}
cursor.close();
Collections.sort(docs, (lhs, rhs) -> -1 * Long.valueOf(lhs.date).compareTo(rhs.date));
if (docs.size() > 20)
for (int i = docs.size() - 1; i > 20; i--) {
docs.remove(i);
}
return docs;
}
private ArrayList<LayoutElementParcelable> listApks() {
ArrayList<LayoutElementParcelable> apks = new ArrayList<>();
final String[] projection = {MediaStore.Files.FileColumns.DATA};
Cursor cursor = c.getContentResolver()
.query(MediaStore.Files.getContentUri("external"), projection, null, null, null);
if (cursor == null)
return apks;
else if (cursor.getCount() > 0 && cursor.moveToFirst()) {
do {
String path = cursor.getString(cursor.getColumnIndex
(MediaStore.Files.FileColumns.DATA));
if (path != null && path.endsWith(".apk")) {
HybridFileParcelable strings = RootHelper.generateBaseFile(new File(path), showHiddenFiles);
if (strings != null) {
LayoutElementParcelable parcelable = createListParcelables(strings);
if(parcelable != null) apks.add(parcelable);
}
}
} while (cursor.moveToNext());
}
cursor.close();
return apks;
}
private ArrayList<LayoutElementParcelable> listRecent() {
UtilsHandler utilsHandler = new UtilsHandler(c);
final LinkedList<String> paths = utilsHandler.getHistoryLinkedList();
ArrayList<LayoutElementParcelable> songs = new ArrayList<>();
for (String f : paths) {
if (!f.equals("/")) {
HybridFileParcelable hybridFileParcelable = RootHelper.generateBaseFile(new File(f), showHiddenFiles);
if (hybridFileParcelable != null) {
hybridFileParcelable.generateMode(ma.getActivity());
if (!hybridFileParcelable.isSmb() && !hybridFileParcelable.isDirectory() && hybridFileParcelable.exists()) {
LayoutElementParcelable parcelable = createListParcelables(hybridFileParcelable);
if (parcelable != null) songs.add(parcelable);
}
}
}
}
return songs;
}
private ArrayList<LayoutElementParcelable> listRecentFiles() {
ArrayList<LayoutElementParcelable> recentFiles = new ArrayList<>();
final String[] projection = {MediaStore.Files.FileColumns.DATA, MediaStore.Files.FileColumns.DATE_MODIFIED};
Calendar c = Calendar.getInstance();
c.set(Calendar.DAY_OF_YEAR, c.get(Calendar.DAY_OF_YEAR) - 2);
Date d = c.getTime();
Cursor cursor = this.c.getContentResolver().query(MediaStore.Files
.getContentUri("external"), projection,
null,
null, null);
if (cursor == null) return recentFiles;
if (cursor.getCount() > 0 && cursor.moveToFirst()) {
do {
String path = cursor.getString(cursor.getColumnIndex
(MediaStore.Files.FileColumns.DATA));
File f = new File(path);
if (d.compareTo(new Date(f.lastModified())) != 1 && !f.isDirectory()) {
HybridFileParcelable strings = RootHelper.generateBaseFile(new File(path), showHiddenFiles);
if (strings != null) {
LayoutElementParcelable parcelable = createListParcelables(strings);
if(parcelable != null) recentFiles.add(parcelable);
}
}
} while (cursor.moveToNext());
}
cursor.close();
Collections.sort(recentFiles, (lhs, rhs) -> -1 * Long.valueOf(lhs.date).compareTo(rhs.date));
if (recentFiles.size() > 20)
for (int i = recentFiles.size() - 1; i > 20; i--) {
recentFiles.remove(i);
}
return recentFiles;
}
/**
* Lists files from an OTG device
*
* @param path the path to the directory tree, starts with prefix {@link com.amaze.filemanager.utils.OTGUtil#PREFIX_OTG}
* Independent of URI (or mount point) for the OTG
*/
private void listOtg(String path, OnFileFound fileFound) {
OTGUtil.getDocumentFiles(path, c, fileFound);
}
private void listCloud(String path, CloudStorage cloudStorage, OpenMode openMode,
OnFileFound fileFoundCallback) throws CloudPluginException {
if (!CloudSheetFragment.isCloudProviderAvailable(c)) {
throw new CloudPluginException();
}
CloudUtil.getCloudFiles(path, cloudStorage, openMode, fileFoundCallback);
}
}
|
clatisus/armeria | core/src/test/java/com/linecorp/armeria/server/RouterTest.java | <reponame>clatisus/armeria
/*
* Copyright 2017 LINE Corporation
*
* LINE Corporation licenses this file to you under the Apache License,
* version 2.0 (the "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at:
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package com.linecorp.armeria.server;
import static com.google.common.collect.ImmutableList.toImmutableList;
import static com.linecorp.armeria.server.RoutingContextTest.virtualHost;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import java.util.List;
import java.util.Map.Entry;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.BiConsumer;
import java.util.function.Function;
import java.util.stream.Stream;
import org.assertj.core.util.Lists;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Maps;
import com.linecorp.armeria.common.HttpMethod;
import com.linecorp.armeria.common.MediaType;
import com.linecorp.armeria.common.RequestHeaders;
class RouterTest {
private static final Logger logger = LoggerFactory.getLogger(RouterTest.class);
private static final BiConsumer<Route, Route> REJECT = (a, b) -> {
throw new IllegalStateException("duplicate route: " + a + " vs. " + b);
};
@Test
void testRouters() {
final List<Route> routes = Lists.newArrayList(
Route.builder().path("exact:/a").build(), // router 1
Route.builder().path("/b/{var}").build(),
Route.builder().path("prefix:/c").build(),
Route.builder().path("regex:/d([^/]+)").build(), // router 2
Route.builder().path("glob:/e/**/z").build(),
Route.builder().path("exact:/f").build(), // router 3
Route.builder().path("/g/{var}").build(),
Route.builder().path("glob:/h/**/z").build(), // router 4
Route.builder().path("prefix:/i").build() // router 5
);
final List<Router<Route>> routers =
Routers.routers(routes, null, null, Function.identity(), REJECT, false);
assertThat(routers).hasSize(5);
// Map of a path string and a router index
final List<Entry<String, Integer>> args = Lists.newArrayList(
Maps.immutableEntry("/a", 0),
Maps.immutableEntry("/b/1", 0),
Maps.immutableEntry("/c/1", 0),
Maps.immutableEntry("/dxxx/", 1),
Maps.immutableEntry("/e/1/2/3/z", 1),
Maps.immutableEntry("/f", 2),
Maps.immutableEntry("/g/1", 2),
Maps.immutableEntry("/h/1/2/3/z", 3),
Maps.immutableEntry("/i/1/2/3", 4)
);
args.forEach(entry -> {
for (int i = 0; i < 5; i++) {
final Routed<Route> result = routers.get(i).find(routingCtx(entry.getKey()));
assertThat(result.isPresent()).isEqualTo(i == entry.getValue());
}
});
}
@ParameterizedTest
@MethodSource("generateRouteMatchData")
void testFindAllMatchedRouters(String path, int expectForFind, List<Integer> expectForFindAll) {
final List<Route> routes = Lists.newArrayList(
Route.builder().path("prefix:/a").build(),
Route.builder().path("/a/{var}").build(),
Route.builder().path("prefix:/c").build(),
Route.builder().path("regex:/d/([^/]+)").build(),
Route.builder().path("glob:/d/**").build(),
Route.builder().path("exact:/e").build(),
Route.builder().path("glob:/h/**/z").build(),
Route.builder().path("prefix:/h").build()
);
final List<Router<Route>> routers =
Routers.routers(routes, null, null, Function.identity(), REJECT, false);
final CompositeRouter<Route, Route> router = new CompositeRouter<>(routers, Function.identity());
final RoutingContext routingCtx = routingCtx(path);
assertThat(router.find(routingCtx).route()).isEqualTo(routes.get(expectForFind));
final List<Route> matched = router.findAll(routingCtx)
.stream().map(Routed::route).collect(toImmutableList());
final List<Route> expected = expectForFindAll.stream().map(routes::get).collect(toImmutableList());
assertThat(matched).containsAll(expected);
}
private static DefaultRoutingContext routingCtx(String path) {
return new DefaultRoutingContext(virtualHost(), "example.com",
RequestHeaders.of(HttpMethod.GET, path),
path, null, null, RoutingStatus.OK);
}
static Stream<Arguments> generateRouteMatchData() {
return Stream.of(
Arguments.of("/a/1", 1, ImmutableList.of(0, 1)),
Arguments.of("/c/1", 2, ImmutableList.of(2)),
Arguments.of("/d/12", 3, ImmutableList.of(3, 4)),
Arguments.of("/e", 5, ImmutableList.of(5)),
Arguments.of("/h/1/2/3/z", 6, ImmutableList.of(6, 7))
);
}
@Test
void duplicateRoutes() {
// Simple cases
testDuplicateRoutes(Route.builder().path("exact:/a").build(),
Route.builder().path("exact:/a").build());
testDuplicateRoutes(Route.builder().path("exact:/a").build(),
Route.builder().path("/a").build());
testDuplicateRoutes(Route.builder().path("prefix:/").build(),
Route.ofCatchAll());
}
/**
* Should detect the duplicates even if the mappings are split into more than one router.
*/
@Test
void duplicateMappingsWithRegex() {
// Ensure that 3 routers are created first really.
assertThat(Routers.routers(ImmutableList.of(Route.builder().path("/foo/:bar").build(),
Route.builder().regex("not-trie-compatible").build(),
Route.builder().path("/bar/:baz").build()),
null, null, Function.identity(), REJECT, false)).hasSize(3);
testDuplicateRoutes(Route.builder().path("/foo/:bar").build(),
Route.builder().regex("not-trie-compatible").build(),
Route.builder().path("/foo/:qux").build());
}
@Test
void duplicatePathWithHeaders() {
// Duplicate if supported methods overlap.
testDuplicateRoutes(Route.builder().path("/foo").methods(HttpMethod.GET).build(),
Route.builder().path("/foo").methods(HttpMethod.GET, HttpMethod.POST).build());
// Duplicate if supported methods overlap.
testDuplicateRoutes(Route.builder().path("/foo").build(), // This route contains all methods.
Route.builder().path("/foo").methods(HttpMethod.GET).build());
testNonDuplicateRoutes(Route.builder().path("/foo").methods(HttpMethod.GET).build(),
Route.builder().path("/foo").methods(HttpMethod.POST).build());
// Duplicate if consume types overlap.
testDuplicateRoutes(Route.builder()
.path("/foo")
.methods(HttpMethod.POST)
.consumes(MediaType.PLAIN_TEXT_UTF_8, MediaType.JSON_UTF_8)
.build(),
Route.builder()
.path("/foo")
.methods(HttpMethod.POST)
.consumes(MediaType.JSON_UTF_8)
.build());
testNonDuplicateRoutes(Route.builder()
.path("/foo")
.methods(HttpMethod.POST)
.consumes(MediaType.PLAIN_TEXT_UTF_8)
.build(),
Route.builder()
.path("/foo")
.methods(HttpMethod.POST)
.consumes(MediaType.JSON_UTF_8)
.build());
// Duplicate if produce types overlap.
testDuplicateRoutes(Route.builder()
.path("/foo")
.methods(HttpMethod.POST)
.produces(MediaType.PLAIN_TEXT_UTF_8, MediaType.JSON_UTF_8)
.build(),
Route.builder()
.path("/foo")
.methods(HttpMethod.POST)
.produces(MediaType.PLAIN_TEXT_UTF_8)
.build());
testNonDuplicateRoutes(Route.builder()
.path("/foo")
.methods(HttpMethod.POST)
.produces(MediaType.PLAIN_TEXT_UTF_8)
.build(),
Route.builder()
.path("/foo")
.methods(HttpMethod.POST)
.produces(MediaType.JSON_UTF_8)
.build());
}
private static void testDuplicateRoutes(Route... routes) {
assertThatThrownBy(() -> Routers.routers(ImmutableList.copyOf(routes), null, null,
Function.identity(), REJECT, false))
.isInstanceOf(IllegalStateException.class)
.hasMessageStartingWith("duplicate route:");
}
private static void testNonDuplicateRoutes(Route... routes) {
Routers.routers(ImmutableList.copyOf(routes), null, null, Function.identity(), REJECT, false);
}
@Test
void exactPathAndParameter() {
final List<HttpMethod> methods =
ImmutableList.of(HttpMethod.GET, HttpMethod.DELETE, HttpMethod.POST, HttpMethod.PUT);
final AtomicInteger i = new AtomicInteger(0);
final List<Route> routes =
methods.stream()
.map(method -> Route.builder().path(i.incrementAndGet() % 2 == 0 ? "/foo" : "/{id}")
.methods(method).build())
.collect(toImmutableList());
final List<Router<Route>> routers =
Routers.routers(routes, null, null, Function.identity(), REJECT, false);
assertThat(routers.size()).isOne();
methods.forEach(method -> {
final RoutingContext ctx = mock(RoutingContext.class);
when(ctx.method()).thenReturn(method);
when(ctx.path()).thenReturn("/foo");
when(ctx.query()).thenReturn(null);
when(ctx.acceptTypes()).thenReturn(ImmutableList.of());
when(ctx.contentType()).thenReturn(null);
final Routed<Route> routed = routers.get(0).find(ctx);
assertThat(routed.route().methods()).contains(method);
});
}
}
|
raulfdias/api_node_default | src/__tests__/integration/controllers/CollegeSubjectApi.js | <reponame>raulfdias/api_node_default
const request = require('supertest');
const server = require('../../../config/server');
const truncate = require('../../utils/ClearTables'),
testMass = require('../../utils/TestMass');
let massDataTesting = {};
module.exports = () => {
describe('College Subject API Controller', () => {
beforeAll(async () => {
await truncate();
massDataTesting = await testMass.createTestMass('CollegeSubjectApi');
massDataTesting.auth = await request(server).post('/api/v1/token').auth(massDataTesting.user.usu_ds_email, massDataTesting.userPassword);
});
test('must return the college subject created', async () => {
const { auth } = massDataTesting;
const response = await request(server).post('/api/v1/college-subject/create').send({
name: '<NAME>',
status: '1'
}).set({ Authorization: `Bearer ${auth.body.token}` });
const { body } = response;
massDataTesting.collegeSubject = body.collegeSubject;
expect(response.status).toBe(200);
expect(body).toHaveProperty('message');
expect((body.message === null)).toBe(true);
expect(body).toHaveProperty('bagError');
expect(((Object.keys(body.bagError).length) === 0)).toBe(true);
expect(body).toHaveProperty('collegeSubject');
expect((body.collegeSubject !== null)).toBe(true);
});
test('must return the list of college subjects', async () => {
const { auth } = massDataTesting;
const response = await request(server).get('/api/v1/college-subject/list').set({ Authorization: `Bearer ${auth.body.token}` });
const { body } = response;
expect(response.status).toBe(200);
expect(body).toHaveProperty('message');
expect((body.message === null)).toBe(true);
expect(body).toHaveProperty('bagError');
expect(((Object.keys(body.bagError).length) === 0)).toBe(true);
expect(body).toHaveProperty('collegeSubjects');
expect((body.collegeSubjects.length > 0)).toBe(true);
});
test('must return the list of filtered college subjects', async () => {
const { auth, collegeSubject } = massDataTesting;
const data = {
name: collegeSubject.cos_ds_name,
email: collegeSubject.cos_en_status
};
const response = await request(server).get('/api/v1/college-subject/search').send(data).set({ Authorization: `Bearer ${auth.body.token}` });
const { body } = response;
expect(response.status).toBe(200);
expect(body).toHaveProperty('message');
expect((body.message === null)).toBe(true);
expect(body).toHaveProperty('bagError');
expect(((Object.keys(body.bagError).length) === 0)).toBe(true);
expect(body).toHaveProperty('collegeSubjects');
expect((body.collegeSubjects.length > 0)).toBe(true);
});
test('must return the updated college subjects', async () => {
const { auth, collegeSubject } = massDataTesting;
const id = collegeSubject.cos_id_college_subject;
const data = {
name: '<NAME> 001',
status: '1'
};
const response = await request(server).put(`/api/v1/college-subject/${id}/update`).send({ data }).set({ Authorization: `Bearer ${auth.body.token}` });
const { body } = response;
massDataTesting.collegeSubject = body.collegeSubject;
expect(response.status).toBe(200);
expect(body).toHaveProperty('message');
expect((body.message === null)).toBe(true);
expect(body).toHaveProperty('bagError');
expect(((Object.keys(body.bagError).length) === 0)).toBe(true);
expect(body).toHaveProperty('collegeSubject');
expect((body.collegeSubject !== null)).toBe(true);
expect((body.collegeSubject.cos_ds_name === data.name)).toBe(true);
});
test('must return the informed college subject', async () => {
const { auth, collegeSubject } = massDataTesting;
const id = collegeSubject.cos_id_college_subject;
const response = await request(server).get(`/api/v1/college-subject/${id}/show`).set({ Authorization: `Bearer ${auth.body.token}` });
const { body } = response;
expect(response.status).toBe(200);
expect(body).toHaveProperty('message');
expect((body.message === null)).toBe(true);
expect(body).toHaveProperty('bagError');
expect(((Object.keys(body.bagError).length) === 0)).toBe(true);
expect(body).toHaveProperty('collegeSubject');
expect((body.collegeSubject !== null)).toBe(true);
expect((body.collegeSubject.cos_id_college_subject === id)).toBe(true);
});
test('must return the teachers associated with the college subject', async () => {
const { auth, collegeSubject } = massDataTesting;
const id = collegeSubject.cos_id_college_subject;
const response = await request(server).get(`/api/v1/college-subject/${id}/teachers`).set({ Authorization: `Bearer ${auth.body.token}` });
const { body } = response;
expect(response.status).toBe(200);
expect(body).toHaveProperty('message');
expect((body.message === null)).toBe(true);
expect(body).toHaveProperty('bagError');
expect(((Object.keys(body.bagError).length) === 0)).toBe(true);
expect(body).toHaveProperty('teachers');
expect((body.teachers.length >= 0)).toBe(true);
});
test('must return the removed college subject', async () => {
const { auth, collegeSubject } = massDataTesting;
const id = collegeSubject.cos_id_college_subject;
const response = await request(server).delete(`/api/v1/college-subject/${id}/delete`).set({ Authorization: `Bearer ${auth.body.token}` });
const { body } = response;
expect(response.status).toBe(200);
expect(body).toHaveProperty('message');
expect((body.message === null)).toBe(true);
expect(body).toHaveProperty('bagError');
expect(((Object.keys(body.bagError).length) === 0)).toBe(true);
expect(body).toHaveProperty('deleted');
expect(body.deleted).toBe(true);
});
});
};
|
Fauntleroy/Igneous | test/postprocessors/sass.js | <reponame>Fauntleroy/Igneous<filename>test/postprocessors/sass.js
var should = require('should');
var sass = require('../../lib/postprocessors/sass.js');
describe( 'postprocessor - SASS', function(){
it( 'converts SASS to CSS', function( cb ){
var contents = '$blue: #3bbfce;\n'+
'$margin: 16px;\n'+
'\n'+
'.content-navigation {\n'+
' border-color: $blue;\n'+
' color: darken($blue, 9%);\n'+
'}\n'+
'\n'+
'.border {\n'+
' padding: $margin / 2;\n'+
' margin: $margin / 2;\n'+
' border-color: $blue;\n'+
'}\n';
var config = {};
sass( contents, config, function( processed ){
processed.should.equal('.content-navigation {\n'+
' border-color: #3bbfce;\n'+
' color: #2ca2af; }\n'+
'\n'+
'.border {\n'+
' padding: 8px;\n'+
' margin: 8px;\n'+
' border-color: #3bbfce; }\n')
cb();
});
});
}); |
uwydoc/the-practices | boost/mpi.cpp | <reponame>uwydoc/the-practices
// mpi.cpp
//
#include <iostream>
#include <string>
#include <boost/mpi.hpp>
#include <boost/serialization/string.hpp>
namespace test {
class animal
{
public:
animal() {}
animal(const std::string& name, int legs)
: name_(name), legs_(legs) {}
const std::string& name() const { return name_; }
int legs() const { return legs_; }
private:
std::string name_;
int legs_;
};
template<typename Archive>
void serialize(Archive& ar, animal& a, const unsigned int version)
{
if (version != 0)
return;
if (Archive::is_saving::value) {
///@note the following 2 lines of code failed to compile, because
/// the interface is defined as follows:
/// [code] interface_oarchive::operator<<(T& t) [/code]
/// non-const reference is required.
///
/// i think Boost.Serialization should provide the const reference
/// version instead
//ar << a.name();
//ar << a.legs();
std::string name = a.name();
int legs = a.legs();
ar & name;
ar & legs;
} else if (Archive::is_loading::value) {
std::string name;
int legs;
ar & name;
ar & legs;
a = animal(name, legs);
}
}
std::ostream& operator<<(std::ostream& os, const animal& a)
{
return (os << "animal(" << a.name() << "," << a.legs() << ")");
}
enum {
k_tag_msg = 16
, k_tag_animal
};
}
int main(int argc, char* argv[])
{
namespace mpi = boost::mpi;
mpi::environment env(argc, argv);
mpi::communicator world_comm;
std::cout << "[info]" << env.processor_name() << ", "
<< world_comm.rank() << ", " << world_comm.size() << '\n';
if (world_comm.rank() == 0) {
std::string msg;
mpi::status status = world_comm.recv(mpi::any_source, test::k_tag_msg, msg);
std::cout << "source: " << status.source() << ", msg: " << msg << '\n';
test::animal a;
status = world_comm.recv(mpi::any_source, test::k_tag_animal, a);
std::cout << "source: " << status.source() << ", animal: " << a << '\n';
} else {
world_comm.send(0, test::k_tag_msg, std::string("hello world"));
world_comm.send(0, test::k_tag_animal, test::animal("bird", 2));
}
}
|
mendelmaleh/td | cmd/gotdecho/main.go | // Binary gotdecho provides example of Telegram echo bot.
package main
import (
"context"
"fmt"
"os"
"os/signal"
"path/filepath"
"strconv"
"go.uber.org/zap"
"go.uber.org/zap/zapcore"
"golang.org/x/net/proxy"
"golang.org/x/xerrors"
"github.com/gotd/td/telegram"
"github.com/gotd/td/tg"
"github.com/gotd/td/transport"
)
func run(ctx context.Context) error {
logger, _ := zap.NewDevelopment(zap.IncreaseLevel(zapcore.DebugLevel))
defer func() { _ = logger.Sync() }()
// Reading app id from env (never hardcode it!).
appID, err := strconv.Atoi(os.Getenv("APP_ID"))
if err != nil {
return xerrors.Errorf("APP_ID not set or invalid: %w", err)
}
appHash := os.Getenv("APP_HASH")
if appHash == "" {
return xerrors.New("no APP_HASH provided")
}
// Setting up session storage.
home, err := os.UserHomeDir()
if err != nil {
return err
}
sessionDir := filepath.Join(home, ".td")
if err := os.MkdirAll(sessionDir, 0600); err != nil {
return err
}
dispatcher := tg.NewUpdateDispatcher()
client := telegram.NewClient(appID, appHash, telegram.Options{
Logger: logger,
SessionStorage: &telegram.FileSessionStorage{
Path: filepath.Join(sessionDir, "session.json"),
},
Transport: transport.Intermediate(transport.DialFunc(proxy.Dial)),
UpdateHandler: dispatcher.Handle,
})
dispatcher.OnNewMessage(func(ctx tg.UpdateContext, u *tg.UpdateNewMessage) error {
switch m := u.Message.(type) {
case *tg.Message:
switch peer := m.PeerID.(type) {
case *tg.PeerUser:
user := ctx.Users[peer.UserID]
logger.With(
zap.String("text", m.Message),
zap.Int("user_id", user.ID),
zap.String("user_first_name", user.FirstName),
zap.String("username", user.Username),
).Info("Got message")
return client.SendMessage(ctx, &tg.MessagesSendMessageRequest{
Message: m.Message,
Peer: &tg.InputPeerUser{
UserID: user.ID,
AccessHash: user.AccessHash,
},
})
}
}
return nil
})
return client.Run(ctx, func(ctx context.Context) error {
self, err := client.Self(ctx)
if err != nil || !self.Bot {
if err := client.AuthBot(ctx, os.Getenv("BOT_TOKEN")); err != nil {
return xerrors.Errorf("failed to perform bot login: %w", err)
}
logger.Info("Bot login ok")
}
state, err := tg.NewClient(client).UpdatesGetState(ctx)
if err != nil {
return xerrors.Errorf("failed to get state: %w", err)
}
logger.Sugar().Infof("Got state: %+v", state)
<-ctx.Done()
return ctx.Err()
})
}
func withSignal(ctx context.Context) (context.Context, context.CancelFunc) {
ctx, cancel := context.WithCancel(ctx)
c := make(chan os.Signal, 1)
signal.Notify(c, os.Interrupt)
go func() {
select {
case <-c:
cancel()
case <-ctx.Done():
}
}()
return ctx, func() {
signal.Stop(c)
cancel()
}
}
func main() {
ctx, cancel := withSignal(context.Background())
defer cancel()
if err := run(ctx); err != nil {
_, _ = fmt.Fprintf(os.Stderr, "%+v\n", err)
os.Exit(2)
}
}
|
wja30/cortex_0.31 | async-gateway/queue.go | /*
Copyright 2021 Cortex Labs, Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package main
import (
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/session"
awssqs "github.com/aws/aws-sdk-go/service/sqs"
)
// Queue is an interface to abstract communication with event queues
type Queue interface {
SendMessage(message string, uniqueID string) error
}
type sqs struct {
queueURL string
client *awssqs.SQS
}
// NewSQS creates a new SQS client that satisfies the Queue interface
func NewSQS(queueURL string, sess *session.Session) Queue {
client := awssqs.New(sess)
return &sqs{queueURL: queueURL, client: client}
}
// SendMessage sends a string
func (q *sqs) SendMessage(message string, uniqueID string) error {
_, err := q.client.SendMessage(&awssqs.SendMessageInput{
MessageBody: aws.String(message),
MessageDeduplicationId: aws.String(uniqueID),
MessageGroupId: aws.String(uniqueID),
QueueUrl: aws.String(q.queueURL),
})
return err
}
|
polarloves/skrivet | supports/supports-data/supports-data-service-impl/src/main/java/com/skrivet/supports/data/service/impl/system/SystemServiceImpl.java | package com.skrivet.supports.data.service.impl.system;
import com.skrivet.core.common.annotations.DynamicDataBase;
import com.skrivet.core.common.annotations.PublishEvent;
import com.skrivet.core.common.entity.LoginUser;
import com.skrivet.core.common.entity.PageList;
import com.skrivet.core.common.exception.DataExistExp;
import com.skrivet.plugins.queue.core.Channels;
import com.skrivet.plugins.queue.core.annotations.Publish;
import com.skrivet.plugins.security.core.annotations.RequiresPermissions;
import com.skrivet.plugins.service.core.BasicService;
import com.skrivet.supports.data.dao.core.system.SystemDao;
import com.skrivet.supports.data.dao.core.system.entity.add.SystemAddDQ;
import com.skrivet.supports.data.dao.core.system.entity.select.*;
import com.skrivet.supports.data.dao.core.system.entity.update.SystemUpdateDQ;
import com.skrivet.supports.data.service.core.system.SystemService;
import com.skrivet.supports.data.service.core.system.entity.add.SystemAddSQ;
import com.skrivet.supports.data.service.core.system.entity.select.*;
import com.skrivet.supports.data.service.core.system.entity.update.SystemUpdateSQ;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.cache.annotation.Caching;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import java.util.List;
@Service("systemService")
@DynamicDataBase
@CacheConfig(cacheNames = "systemConfigCache")
public class SystemServiceImpl extends BasicService implements SystemService {
@Autowired
private SystemDao systemDao;
@Autowired(required = false)
private CacheManager cacheManager;
@Caching(evict = {
@CacheEvict(cacheNames = "systemConfigGroupCache", key = "#entity.groupId"),
@CacheEvict(key = "#result")
})
@PublishEvent(id = "#result", name = "system", action = "add")
@Transactional(transactionManager = "dataTM")
@RequiresPermissions(value = "skrivet:system:add")
@Override
public String insert(SystemAddSQ entity, LoginUser loginUser) {
if (systemDao.selectByGroupKey(entity.getGroupId(), entity.getSysKey()) != null) {
throw new DataExistExp().variable(entity.getGroupId() + "-" + entity.getSysKey());
}
String id = idGenerator.generate();
SystemAddDQ data = entityConvert.convert(entity, SystemAddDQ.class);
data.setId(id);
systemDao.insert(data);
return id;
}
@PublishEvent(id = "#id", name = "system", action = "delete",opportunity = PublishEvent.Opportunity.BEFORE)
@CacheEvict(key = "#id")
@RequiresPermissions(value = "skrivet:system:delete")
@Transactional(transactionManager = "dataTM")
@Override
public Long deleteById(String id, LoginUser loginUser) {
if (cacheManager != null) {
SystemService current = current(SystemService.class);
SystemDetailSP systemDetailSP = current.selectOneById(id, LoginUser.IGNORED);
if (systemDetailSP != null) {
//删除缓存
cacheManager.getCache("systemGroupCache").evict(systemDetailSP.getGroupId());
}
}
return systemDao.deleteById(id);
}
@RequiresPermissions(value = "skrivet:system:delete")
@Transactional(transactionManager = "dataTM")
@Override
public Long deleteMultiById(String[] ids, LoginUser loginUser) {
SystemService current = current(SystemService.class);
long result = 0;
for (String id : ids) {
result = result + current.deleteById(id, loginUser);
}
return result;
}
@Caching(evict = {
@CacheEvict(cacheNames = "systemConfigGroupCache", key = "#entity.groupId"),
@CacheEvict(key = "#entity.id")
})
@PublishEvent(id = "#entity.id", name = "system", action = "update")
@RequiresPermissions(value = "skrivet:system:update")
@Transactional(transactionManager = "dataTM")
@Override
public Long update(SystemUpdateSQ entity, LoginUser loginUser) {
SystemDetailDP detailDP = systemDao.selectByGroupKey(entity.getGroupId(), entity.getSysKey());
if (detailDP != null && !detailDP.getId().equals(entity.getId())) {
throw new DataExistExp().variable(entity.getGroupId() + "-" + entity.getSysKey());
}
SystemUpdateDQ data = entityConvert.convert(entity, SystemUpdateDQ.class);
return systemDao.update(data);
}
@RequiresPermissions(value = "skrivet:system:detail")
@Cacheable(key = "#id")
@Override
public SystemDetailSP selectOneById(String id, LoginUser loginUser) {
SystemDetailDP entity = systemDao.selectOneById(id);
return entityConvert.convert(entity, SystemDetailSP.class);
}
@Cacheable(key = "#groupId", cacheNames = "systemConfigGroupCache")
@Override
public List<SystemListSP> selectListByGroupId(String groupId, LoginUser loginUser) {
List<SystemListDP> response = systemDao.selectListByGroupId(groupId);
return entityConvert.convertList(response, SystemListSP.class);
}
@Override
public SystemDetailSP selectByKeyGroupId(String groupId, String key) {
SystemService current = current(SystemService.class);
List<SystemListSP> lists = current.selectListByGroupId(groupId, LoginUser.IGNORED);
if (!CollectionUtils.isEmpty(lists)) {
for (SystemListSP list : lists) {
if (list.getSysKey().equals(key)) {
return entityConvert.convert(list, SystemDetailSP.class);
}
}
}
return null;
}
@RequiresPermissions(value = "skrivet:system:list")
@Override
public PageList<SystemListSP> selectPageList(SystemSelectPageSQ condition, LoginUser loginUser) {
PageList<SystemListSP> page = new PageList<SystemListSP>();
SystemSelectPageDQ request = entityConvert.convert(condition, SystemSelectPageDQ.class);
page.setCount(systemDao.selectPageCount(request));
page.setData(entityConvert.convertList(systemDao.selectPageList(request), SystemListSP.class));
return page;
}
@RequiresPermissions(value = "skrivet:system:groups")
@Override
public List<SystemGroupSP> groups(LoginUser loginUser) {
return entityConvert.convertList(systemDao.groups(), SystemGroupSP.class);
}
}
|
knksknsy/cnc-shop | middleware/models/users.model.js | /**
* Copyright (C) 2017
*
* <NAME>.
* <NAME>.
*
* MIT License
*/
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var bcrypt = require('bcryptjs'); // TODO: for a better performance we should use basic bcrypt, but this would have a bunch of dependencies
var CRYPT_FACTOR = 11;
var userSchema = new Schema({
email: { type: String, unique: true, required: true },
password: { type: String, required: true },
name: { type: String, required: true },
surname: { type: String, required: true },
street: { type: String, required: true },
postcode: { type: String, required: true },
city: { type: String, required: true },
state: { type: String, required: true },
orderId: { type: String, required: false },
isAdmin: { type: Boolean, default: false }
});
// Generate hashed, salted and bcrypted passwords
userSchema.pre('save', function (next) {
var user = this;
if (!user.isModified('password')) {
return next();
}
bcrypt.genSalt(CRYPT_FACTOR, function (err, salt) {
if (err) return next(err);
bcrypt.hash(user.password, salt, function (err, hash) {
if (err) return next(err);
user.password = hash;
next();
});
});
});
userSchema.methods.comparePassword = function (password, callback) {
bcrypt.compare(password, this.password, function (err, isMatch) {
if (err) return callback(err);
callback(null, isMatch);
});
};
module.exports = mongoose.model('Users', userSchema);
|
SAIC-ATS/ARTTECH-3039 | Session_02/03_Pixels_Brightest/src/ofApp.cpp | #include "ofApp.h"
void ofApp::setup()
{
ofBackground(80);
ofLoadImage(myPixels, "puppy.jpg");
myTexture.loadData(myPixels);
}
void ofApp::update()
{
float brightestBrightness = 0;
for (std::size_t x = 0; x < myPixels.getWidth(); x++)
{
for (std::size_t y = 0; y < myPixels.getHeight(); y++)
{
ofColor color = myPixels.getColor(x, y);
float brightnessOfThisPixel = color.getBrightness();
if (brightnessOfThisPixel >= brightestBrightness)
{
brightestBrightness = brightnessOfThisPixel;
brightestX = x;
brightestY = y;
}
}
}
}
void ofApp::draw()
{
ofSetColor(255);
myTexture.draw(0, 0);
ofNoFill();
ofSetColor(ofColor::red);
ofDrawCircle(brightestX, brightestY, 10);
}
void ofApp::keyPressed(int key)
{
}
|
rholang/archive-old | packages/media/smart-card/dist/cjs/view/CardWithUrl/loader.js | <reponame>rholang/archive-old
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var tslib_1 = require("tslib");
var React = tslib_1.__importStar(require("react"));
var media_ui_1 = require("@atlaskit/media-ui");
var analytics_1 = require("../../utils/analytics");
var CardWithURLRenderer = /** @class */ (function (_super) {
tslib_1.__extends(CardWithURLRenderer, _super);
function CardWithURLRenderer() {
return _super !== null && _super.apply(this, arguments) || this;
}
CardWithURLRenderer.moduleImporter = function (target) {
Promise.resolve().then(function () { return tslib_1.__importStar(require(/* webpackChunkName:"@atlaskit-internal-smartcard-urlcardcontent" */ './component')); }).then(function (module) {
CardWithURLRenderer.CardContent = module.LazyCardWithUrlContent;
target.forceUpdate();
});
};
CardWithURLRenderer.prototype.componentDidMount = function () {
if (CardWithURLRenderer.CardContent === null) {
(this.props.importer || CardWithURLRenderer.moduleImporter)(this);
}
};
CardWithURLRenderer.prototype.render = function () {
var _a = this.props, url = _a.url, appearance = _a.appearance, isSelected = _a.isSelected, onClick = _a.onClick, createAnalyticsEvent = _a.createAnalyticsEvent, container = _a.container, onResolve = _a.onResolve;
// Wrapper around analytics.
var dispatchAnalytics = function (evt) {
return analytics_1.fireSmartLinkEvent(evt, createAnalyticsEvent);
};
if (!url) {
throw new Error('@atlaskit/smart-card: url property is missing.');
}
return CardWithURLRenderer.CardContent !== null ? (React.createElement(CardWithURLRenderer.CardContent, { url: url, appearance: appearance, onClick: onClick, isSelected: isSelected, dispatchAnalytics: dispatchAnalytics, container: container, onResolve: onResolve })) : (React.createElement(media_ui_1.CardLinkView, { key: 'chunk-placeholder', link: url }));
};
CardWithURLRenderer.CardContent = null;
return CardWithURLRenderer;
}(React.PureComponent));
exports.CardWithURLRenderer = CardWithURLRenderer;
//# sourceMappingURL=loader.js.map |
tiagoadmstz/angular-spring-algaworks | algamoney-api/src/main/java/io/github/tiagoadmstz/algamoney/api/models/Entry.java | <gh_stars>0
package io.github.tiagoadmstz.algamoney.api.models;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.fasterxml.jackson.annotation.JsonProperty;
import lombok.Data;
import javax.persistence.*;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
import java.io.Serializable;
import java.math.BigDecimal;
import java.time.LocalDate;
@Data
@Entity
@Table(name = "entry")
@SequenceGenerator(name = "entry_sequence", allocationSize = 1)
public class Entry implements Serializable {
private static final long serialVersionUID = 9011357890249098191L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@NotNull
@Size(min = 5, max = 50)
@Column(name = "description", length = 50)
private String description;
@NotNull
@JsonProperty("due-date")
@Column(name = "due_date")
@JsonFormat(pattern = "dd/MM/yyyy")
private LocalDate dueDate;
@Column(name = "payday")
@JsonFormat(pattern = "dd/MM/yyyy")
private LocalDate payday;
@NotNull
@Column(name = "entry_value", length = 10, scale = 2)
private BigDecimal value;
@Size(max = 100)
@Column(name = "note", length = 100)
private String note;
@JsonProperty("type")
@Column(name = "type")
@Enumerated(EnumType.STRING)
private EntryType entryType;
@NotNull
@ManyToOne
@JoinColumn(name = "category_id")
private Category category;
@NotNull
@ManyToOne
@JoinColumn(name = "person_id")
private Person person;
}
|
gstackio/bosh-ext-cli | src/github.com/bosh-tools/bosh-ext-cli/web/inputs.go | package web
const inputs string = `
<script type="text/javascript">
function NewSearchCriteriaExpandingInput($input) {
function setUp() {
$input
.focus(function() { $(this).addClass("expanded"); })
.blur(function() {
var $el = $(this);
setTimeout(function() { $el.removeClass("expanded"); }, 100);
});
}
setUp();
return {};
}
function NewSearchCriteriaClearButton($input) {
function setUp() {
var $button = $("<a class='search-criteria-clear-button'>x</a>").click(function(event) {
event.preventDefault();
$input.val("");
$input.focus();
});
$input.after($button);
}
setUp();
return {};
}
</script>
<style>
.canvas input { width: 100px; }
.canvas input.expanded { width: 300px; }
.search-criteria-clear-button {
background: none;
border: none;
vertical-align: top;
padding: 5px;
font-size: 12px;
font-family: system-ui;
cursor: pointer;
}
</style>
`
|
avalan4e57/personalWebSite | src/js/components/App.js | import React, { Component } from 'react'
import styles from '../../styles/App.scss'
import ContactIcons from './ContactIcons'
import Home from './Home.js'
import VisibleProjects from '../containers/VisibleProjects'
import ContactForm from '../containers/ContactForm'
const App = () => (
<div className={ styles.app }>
{/* <ContactIcons /> */}
<Home />
<VisibleProjects />
<ContactForm />
</div>
)
export default App
|
heyogrady/tickety | db/migrate/20150508005636_create_checkouts.rb | class CreateCheckouts < ActiveRecord::Migration
def change
create_table :checkouts do |t|
t.references :user, index: true, null: false
t.references :plan, index: true, null: false
t.string :stripe_coupon_id
t.timestamps
end
add_foreign_key :checkouts, :users
add_foreign_key :checkouts, :plans
end
end
|
AppSecAI-TEST/qalingo-engine | apis/api-core/api-core-common/src/main/java/org/hoteia/qalingo/core/dao/LocalizationDao.java | <filename>apis/api-core/api-core-common/src/main/java/org/hoteia/qalingo/core/dao/LocalizationDao.java
/**
* Most of the code in the Qalingo project is copyrighted Hoteia and licensed
* under the Apache License Version 2.0 (release version 0.8.0)
* http://www.apache.org/licenses/LICENSE-2.0
*
* Copyright (c) Hoteia, 2012-2014
* http://www.hoteia.com - http://twitter.com/hoteia - <EMAIL>
*
*/
package org.hoteia.qalingo.core.dao;
import java.util.ArrayList;
import java.util.List;
import org.hibernate.Criteria;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
import org.hoteia.qalingo.core.domain.Localization;
import org.hoteia.qalingo.core.domain.MarketArea;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Repository;
@Repository("localizationDao")
public class LocalizationDao extends AbstractGenericDao {
private final Logger logger = LoggerFactory.getLogger(getClass());
public Localization getLocalizationById(final Long localizationId, Object... params) {
Criteria criteria = createDefaultCriteria(Localization.class);
criteria.add(Restrictions.eq("id", localizationId));
Localization localization = (Localization) criteria.uniqueResult();
return localization;
}
public Localization getLocalizationByCode(final String code, Object... params) {
Criteria criteria = createDefaultCriteria(Localization.class);
criteria.add(Restrictions.eq("code", handleCodeValue(code)));
Localization localization = (Localization) criteria.uniqueResult();
return localization;
}
public Localization getDefaultLocalizationByCountryCode(final String countryCode, Object... params) {
Criteria criteria = createDefaultCriteria(Localization.class);
criteria.add(Restrictions.eq("country", handleCodeValue(countryCode)));
criteria.add(Restrictions.eq("isDefault", true));
Localization localization = (Localization) criteria.uniqueResult();
return localization;
}
public List<Localization> getLocalizationByCountryCode(final String countryCode, Object... params) {
Criteria criteria = createDefaultCriteria(Localization.class);
criteria.add(Restrictions.eq("country", handleCodeValue(countryCode)));
@SuppressWarnings("unchecked")
List<Localization> localizations = criteria.list();
return localizations;
}
public List<Localization> findLocalizations(Object... params) {
Criteria criteria = createDefaultCriteria(Localization.class);
criteria.addOrder(Order.asc("language"));
@SuppressWarnings("unchecked")
List<Localization> localizations = criteria.list();
return localizations;
}
public List<Localization> findActiveLocalizations(Object... params) {
Criteria criteria = createDefaultCriteria(Localization.class);
criteria.add(Restrictions.eq("active", true));
criteria.addOrder(Order.asc("language"));
@SuppressWarnings("unchecked")
List<Localization> localizations = criteria.list();
return localizations;
}
public List<Localization> findLocalizationsByMarketAreaCode(final String marketAreaCode, Object... params) {
Criteria criteria = createDefaultCriteria(MarketArea.class);
criteria.add(Restrictions.eq("code", handleCodeValue(marketAreaCode)));
MarketArea marketArea = (MarketArea) criteria.uniqueResult();
List<Localization> localizations = new ArrayList<Localization>(marketArea.getLocalizations());
return localizations;
}
public Localization saveOrUpdateLocalization(Localization localization) {
if (localization.getId() != null) {
if(em.contains(localization)){
em.refresh(localization);
}
Localization mergedLocalization = em.merge(localization);
em.flush();
return mergedLocalization;
} else {
em.persist(localization);
return localization;
}
}
public void deleteLocalization(Localization localization) {
em.remove(em.contains(localization) ? localization : em.merge(localization));
}
} |
FateRevoked/mage | Mage.Sets/src/mage/cards/a/ArisenGorgon.java | <reponame>FateRevoked/mage
package mage.cards.a;
import java.util.UUID;
import mage.MageInt;
import mage.abilities.common.SimpleStaticAbility;
import mage.abilities.condition.common.PermanentsOnTheBattlefieldCondition;
import mage.abilities.decorator.ConditionalContinuousEffect;
import mage.abilities.effects.common.continuous.GainAbilitySourceEffect;
import mage.abilities.keyword.DeathtouchAbility;
import mage.constants.SubType;
import mage.cards.CardImpl;
import mage.cards.CardSetInfo;
import mage.constants.CardType;
import mage.constants.Duration;
import mage.constants.Zone;
import mage.filter.common.FilterControlledPlaneswalkerPermanent;
/**
*
* @author TheElk801
*/
public final class ArisenGorgon extends CardImpl {
private static final FilterControlledPlaneswalkerPermanent filter
= new FilterControlledPlaneswalkerPermanent(
SubType.LILIANA,
"a Liliana planeswalker"
);
public ArisenGorgon(UUID ownerId, CardSetInfo setInfo) {
super(ownerId, setInfo, new CardType[]{CardType.CREATURE}, "{1}{B}{B}");
this.subtype.add(SubType.ZOMBIE);
this.subtype.add(SubType.GORGON);
this.power = new MageInt(3);
this.toughness = new MageInt(3);
// Arisen Gorgon has deathtouch as long as you control a Liliana planeswalker.
this.addAbility(new SimpleStaticAbility(
Zone.BATTLEFIELD,
new ConditionalContinuousEffect(
new GainAbilitySourceEffect(
DeathtouchAbility.getInstance(),
Duration.WhileOnBattlefield
),
new PermanentsOnTheBattlefieldCondition(filter),
"{this} has deathtouch as long as you control a Liliana planeswalker"
)
));
}
public ArisenGorgon(final ArisenGorgon card) {
super(card);
}
@Override
public ArisenGorgon copy() {
return new ArisenGorgon(this);
}
}
|
LuN4t1k0/es6 | prototype/app.js | //Objetos
//prototype sirve para asignar metodos a nuestros objetos de forma que estos no puedan ser utilizados por otros elementos
function Tarea(nombre, urgencia) {
this.nombre = nombre;
this.urgencia = urgencia;
}
//agregar un prototype a tarea
Tarea.prototype.mostrarInformacionTarea = function() {
return `La tarea ${this.nombre}, tiene una urgencia de ${this.urgencia}`;
};
//crear una nueva tarea
const tarea1 = new Tarea("<NAME>", "Urgente");
console.log(tarea1);
console.log(tarea1.mostrarInformacionTarea());
|
wuyazero/Elastos.App.UnionSquare.iOS | ELA/MeVC/model/HWMDIDInfoModel.h | //
// HWMDIDInfoModel.h
// elastos wallet
//
// Created by on 2019/11/14.
//
#import <Foundation/Foundation.h>
NS_ASSUME_NONNULL_BEGIN
@interface HWMDIDInfoModel : NSObject
@property(copy,nonatomic)NSString *didName;
@property(copy,nonatomic)NSString *did;
@property(copy,nonatomic)NSString *nickname;
@property(copy,nonatomic)NSString *gender;//1男2nv
@property(copy,nonatomic)NSString *avatar;//头像
@property(copy,nonatomic)NSString *email;
@property(copy,nonatomic)NSString *phone;
@property(copy,nonatomic)NSString *phoneCode;
@property(copy,nonatomic)NSString *nation;//使用area code
@property(copy,nonatomic)NSString *introduction;// 简介
@property(copy,nonatomic)NSString *homePage;//主页
@property(copy,nonatomic)NSString *wechat;
@property(copy,nonatomic)NSString *twitter;
@property(copy,nonatomic)NSString *weibo;
@property(copy,nonatomic)NSString *facebook;
@property(copy,nonatomic)NSString *googleAccount;
@property(copy,nonatomic)NSString *editTime;
@property(copy,nonatomic)NSString *birthday;
@property(copy,nonatomic)NSString *endString;
@property (copy, nonatomic) NSString *customInfos;
@end
NS_ASSUME_NONNULL_END
|
jack0331/peddler | lib/peddler/xml_response_parser.rb | <reponame>jack0331/peddler
require 'peddler/xml_parser'
module Peddler
# @api private
class XMLResponseParser < XMLParser
def next_token
parse.fetch('NextToken', false)
end
private
def find_data
results = xml.values.first.find { |k, _| k.include?('Result') } ||
xml.values.first.find { |k, _| k == 'Message' }
results ? results.last : nil
end
end
end
|
seekdoor/anew-server | api/v1/system/sys_dict.go | package system
import (
"anew-server/api/request"
"anew-server/api/response"
"anew-server/dao"
"anew-server/models/system"
"anew-server/pkg/common"
"anew-server/pkg/utils"
"github.com/gin-gonic/gin"
)
// 查询所有字典
func GetDicts(c *gin.Context) {
// 绑定参数
var req request.DictListReq
err := c.Bind(&req)
if err != nil {
response.FailWithCode(response.ParmError)
return
}
// 创建服务
s := dao.New()
dicts := s.GetDicts(&req)
if req.DictKey != "" || req.DictValue != "" || req.TypeKey != "" {
var newResp []response.DictTreeResp
utils.Struct2StructByJson(dicts, &newResp)
response.SuccessWithData(newResp)
} else {
if req.AllType {
resp := dao.GenDictMap(nil, dicts)
response.SuccessWithData(resp)
}
}
var resp []response.DictTreeResp
resp = dao.GenDictTree(nil, dicts)
response.SuccessWithData(resp)
}
// 创建字典
func CreateDict(c *gin.Context) {
user := GetCurrentUserFromCache(c)
// 绑定参数
var req request.CreateDictReq
err := c.Bind(&req)
if err != nil {
response.FailWithCode(response.ParmError)
return
}
// 参数校验
err = common.NewValidatorError(common.Validate.Struct(req), req.FieldTrans())
if err != nil {
response.FailWithMsg(err.Error())
return
}
// 记录当前创建人信息
req.Creator = user.(system.SysUser).Name
// 创建服务
s := dao.New()
err = s.CreateDict(&req)
if err != nil {
response.FailWithMsg(err.Error())
return
}
response.Success()
}
// 更新字典
func UpdateDictById(c *gin.Context) {
// 绑定参数
var req request.UpdateDictReq
err := c.Bind(&req)
if err != nil {
response.FailWithCode(response.ParmError)
return
}
dictId := utils.Str2Uint(c.Param("dictId"))
if dictId == 0 {
response.FailWithMsg("字典编号不正确")
return
}
// 创建服务
s := dao.New()
// 更新数据
err = s.UpdateDictById(dictId, req)
if err != nil {
response.FailWithMsg(err.Error())
return
}
response.Success()
}
// 批量删除字典
func BatchDeleteDictByIds(c *gin.Context) {
var req request.IdsReq
err := c.Bind(&req)
if err != nil {
response.FailWithCode(response.ParmError)
return
}
// 创建服务
s := dao.New()
// 删除数据
err = s.DeleteDictByIds(req.Ids)
if err != nil {
response.FailWithMsg(err.Error())
return
}
response.Success()
}
|
bsteker/bdf2 | bdf2-import/src/main/java/com/bstek/bdf2/importexcel/model/ExcelDataWrapper.java | package com.bstek.bdf2.importexcel.model;
import java.util.ArrayList;
import java.util.Collection;
public class ExcelDataWrapper implements java.io.Serializable {
private static final long serialVersionUID = 1L;
public String excelModelId;
/**
* excel对应的模型信息
*/
public ExcelModel excelModel;
/**
* 解析的excel数据集合
*/
public Collection<RowWrapper> rowWrappers = new ArrayList<RowWrapper>();
/**
* 数据是否通过验证
*/
public boolean validate;
/**
* 采用的数据处理器
*/
public String processor;
private String tableName;
private String tableLabel;
public ExcelModel getExcelModel() {
return excelModel;
}
public Collection<RowWrapper> getRowWrappers() {
return rowWrappers;
}
public void setExcelModel(ExcelModel excelModel) {
this.excelModel = excelModel;
}
public void setRowWrappers(Collection<RowWrapper> rowWrappers) {
this.rowWrappers = rowWrappers;
}
public boolean isValidate() {
return validate;
}
public void setValidate(boolean validate) {
this.validate = validate;
}
public String getProcessor() {
return processor;
}
public void setProcessor(String processor) {
this.processor = processor;
}
public String getExcelModelId() {
return excelModelId;
}
public void setExcelModelId(String excelModelId) {
this.excelModelId = excelModelId;
}
public String getTableName() {
return tableName;
}
public void setTableName(String tableName) {
this.tableName = tableName;
}
public String getTableLabel() {
return tableLabel;
}
public void setTableLabel(String tableLabel) {
this.tableLabel = tableLabel;
}
}
|
gazsiazasz/gekko | core/workers/dateRangeScan/parent.js | let ForkTask = require('relieve').tasks.ForkTask;
let fork = require('child_process').fork;
module.exports = function(config, done) {
let debug = typeof v8debug === 'object';
if (debug) {
process.execArgv = [];
}
let task = new ForkTask(fork(__dirname + '/child'));
task.send('start', config);
task.once('ranges', ranges => {
return done(false, ranges);
});
task.on('exit', code => {
if (code !== 0)
done('ERROR, unable to scan dateranges, please check the console.');
});
};
|
kloose/XS2A-Sandbox | online-banking/oba-rest-server/src/main/java/de/adorsys/ledgers/oba/rest/server/resource/ResponseUtils.java | <reponame>kloose/XS2A-Sandbox
/*
* Copyright 2018-2022 adorsys GmbH & Co KG
*
* 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 https://www.gnu.org/licenses/.
*
* This project is also available under a separate commercial license. You can
* contact us at <EMAIL>.
*/
package de.adorsys.ledgers.oba.rest.server.resource;
import de.adorsys.ledgers.oba.service.api.domain.OnlineBankingResponse;
import de.adorsys.psd2.sandbox.auth.SecurityConstant;
import lombok.RequiredArgsConstructor;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.web.util.UrlUtils;
import org.springframework.stereotype.Service;
import javax.servlet.http.HttpServletResponse;
@Service
@RequiredArgsConstructor
public class ResponseUtils {
private static final String LOCATION_HEADER_NAME = "Location";
public void addAccessTokenHeader(HttpServletResponse response, String accessToken) {
response.setHeader(SecurityConstant.ACCESS_TOKEN, accessToken);
}
@SuppressWarnings("PMD.AvoidReassigningParameters")
public <T extends OnlineBankingResponse> ResponseEntity<T> redirect(String locationURI, HttpServletResponse httpResp) {
HttpHeaders headers = new HttpHeaders();
if (!UrlUtils.isAbsoluteUrl(locationURI)) {
locationURI = "http://" + locationURI;
}
headers.add(LOCATION_HEADER_NAME, locationURI);
return new ResponseEntity<>(headers, HttpStatus.FOUND);
}
}
|
gwasserfall/matcha | database.py | import config
from helpers.pymysqlpool import Pool
from threading import Thread
from time import sleep
pool = Pool(max_size=20, timeout=20, **config.database)
|
dk00/old-stuff | ntuj/0324.cpp | <gh_stars>0
#include<set>
#include<cstdio>
using namespace std;
int a[100000],u[100000];
main()
{
int i,j,k,n,m;
multiset<int> h;
while(scanf("%d %d",&m,&n)==2)
{
h.clear();
for(i=0;i<m;i++)
scanf("%d",a+i);
for(i=0;i<n;i++)
scanf("%d",u+i);
set<int>::iterator p;
for(i=j=0;i<m;i++)
{
h.insert(a[i]);
if(!i)p=h.begin();
else if(a[i]<*p)p--;
while(j<n && i+1==u[j])
{
if(j++)p++;
printf("%d\n",*p);
}
}
}
}
|
arepraneeth/p2 | pkg/audit/rc.go | <filename>pkg/audit/rc.go
package audit
import (
"encoding/json"
pc_fields "github.com/square/p2/pkg/pc/fields"
"github.com/square/p2/pkg/types"
"github.com/square/p2/pkg/util"
)
const (
// RcRetargetingEvent represents events in which an RC changes the set of
// nodes that it is targeting. This can be used to log the set of nodes that
// an RC or pod cluster manages over time
RCRetargetingEvent EventType = "REPLICATION_CONTROLLER_RETARGET"
)
type RCRetargetingDetails struct {
PodID types.PodID `json:"pod_id"`
AvailabilityZone pc_fields.AvailabilityZone `json:"availability_zone"`
ClusterName pc_fields.ClusterName `json:"cluster_name"`
Nodes []types.NodeName `json:"nodes"`
}
func NewRCRetargetingEventDetails(
podID types.PodID,
az pc_fields.AvailabilityZone,
name pc_fields.ClusterName,
nodes []types.NodeName,
) (json.RawMessage, error) {
details := RCRetargetingDetails{
PodID: podID,
AvailabilityZone: az,
ClusterName: name,
Nodes: nodes,
}
bytes, err := json.Marshal(details)
if err != nil {
return nil, util.Errorf("could not marshal rc retargeting details as json: %s", err)
}
return json.RawMessage(bytes), nil
}
|
junluan/shadow | shadow/operators/kernels/layer_norm.hpp | <gh_stars>10-100
#ifndef SHADOW_OPERATORS_KERNELS_LAYER_NORM_HPP_
#define SHADOW_OPERATORS_KERNELS_LAYER_NORM_HPP_
#include "group_norm.hpp"
namespace Shadow {
class LayerNormKernel : public Kernel {
public:
virtual void Run(const std::shared_ptr<Blob>& input,
const std::shared_ptr<Blob>& scale,
const std::shared_ptr<Blob>& bias,
std::shared_ptr<Blob>& output, Workspace* ws,
const VecInt& normalized_shape, float eps) = 0;
};
template <DeviceType D>
class LayerNormKernelDefault : public LayerNormKernel {
public:
void Run(const std::shared_ptr<Blob>& input,
const std::shared_ptr<Blob>& scale,
const std::shared_ptr<Blob>& bias, std::shared_ptr<Blob>& output,
Workspace* ws, const VecInt& normalized_shape, float eps) override {
const auto* in_data = input->data<float>();
auto* out_data = output->mutable_data<float>();
int inner_num = input->count(input->num_axes() - normalized_shape.size());
int count = input->count(), outer_num = count / inner_num;
ws->GrowTempBuffer((2 * outer_num + count + inner_num) * sizeof(float));
auto mean = ws->CreateTempBlob({outer_num}, DataType::kF32);
auto variance = ws->CreateTempBlob({outer_num}, DataType::kF32);
auto temp = ws->CreateTempBlob(input->shape(), DataType::kF32);
auto sum_inner_multiplier = ws->CreateTempBlob({inner_num}, DataType::kF32);
Blas::Set<D, float>(inner_num, 1,
sum_inner_multiplier->mutable_data<float>(), 0,
ws->Ctx().get());
Blas::BlasSgemv<D, float>(0, outer_num, inner_num, 1.f / inner_num, in_data,
0, sum_inner_multiplier->data<float>(), 0, 0,
mean->mutable_data<float>(), 0, ws->Ctx().get());
Vision::SubtractMeanAndSquare<D, float>(
in_data, mean->data<float>(), count, inner_num, out_data,
temp->mutable_data<float>(), ws->Ctx().get());
Blas::BlasSgemv<D, float>(
0, outer_num, inner_num, 1.f / inner_num, temp->data<float>(), 0,
sum_inner_multiplier->data<float>(), 0, 0,
variance->mutable_data<float>(), 0, ws->Ctx().get());
Vision::DivideVariance<D, float>(out_data, variance->data<float>(), count,
inner_num, eps, out_data, ws->Ctx().get());
if (scale != nullptr && bias != nullptr) {
CHECK(scale->shape() == normalized_shape);
CHECK(bias->shape() == normalized_shape);
Vision::ScaleBias<D, float>(out_data, count, scale->data<float>(),
bias->data<float>(), inner_num, 1, out_data,
ws->Ctx().get());
}
}
DeviceType device_type() const override { return D; }
std::string kernel_type() const override { return "Default"; }
};
} // namespace Shadow
#endif // SHADOW_OPERATORS_KERNELS_LAYER_NORM_HPP_
|
soulwing/prospecto | prospecto-api/src/main/java/org/soulwing/prospecto/spi/ViewWriterFactoryProvider.java | /*
* File created on Mar 9, 2016
*
* Copyright (c) 2016 <NAME>, Jr
* and others as noted
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.soulwing.prospecto.spi;
import org.soulwing.prospecto.api.ViewWriterFactory;
import org.soulwing.prospecto.api.options.Options;
/**
* A provider for a {@link ViewWriterFactory}.
* <p>
* A provider supports a single textual representation format.
*
* @author <NAME>
*/
public interface ViewWriterFactoryProvider {
/**
* Gets the provider name (e.g. 'XML', 'JSON').
* @return provider name
*/
String getName();
/**
* Creates a new factory that will produce writers for the textual
* representation supported by this provider.
* @param options configuration options
* @return factory instance
*/
ViewWriterFactory newFactory(Options options);
}
|
thinking-github/nbone | nbone/nbone-framework/src/main/java/org/nbone/persistence/SqlBuilder.java | <gh_stars>1-10
package org.nbone.persistence;
import org.nbone.lang.MathOperation;
import org.nbone.mvc.domain.GroupQuery;
import org.nbone.persistence.exception.BuilderSQLException;
import org.nbone.persistence.mapper.FieldMapper;
import org.nbone.persistence.model.SqlModel;
import org.springframework.jdbc.core.RowMapper;
import javax.servlet.ServletRequest;
import java.io.Serializable;
import java.util.Collection;
import java.util.List;
import java.util.Map;
/**
* 构建ORM映射超级接口
* @author thinking
* @since 2015-12-12
*
*/
public interface SqlBuilder {
/**
* 由传入的对象的参数生成insert sql语句(不校验空值)
* @param object
* @return {@link SqlModel}
* @throws BuilderSQLException
*/
SqlModel<Object> insertSql(Object object) throws BuilderSQLException;
/**
* 由传入的对象的参数生成insert sql语句(参数值不为空的加入)
* @param object
* @return {@link SqlModel}
* @throws BuilderSQLException
*/
SqlModel<Object> insertSelectiveSql(Object object) throws BuilderSQLException;
/**
* 获取主键信息
*
* @param entityClass
* @return
*/
List<FieldMapper> getPrimaryKeys(Class<?> entityClass);
/***
* 获取主键信息
* @param entityClass
* @return
*/
FieldMapper getPrimaryKey(Class<?> entityClass);
/**
* 由传入的对象生成update sql语句
*
* @param object 实体对象
* @param properties 更新的属性字段 可为空,为空时选择全部字段
* @param conditionFields 属性条件 可为空, 为空时默认使用主键作为条件
* @return
* @throws BuilderSQLException
*/
SqlModel<Object> updateSql(Object object,String[] properties,String[] conditionFields) throws BuilderSQLException;
/**
* 由传入的对象生成update sql语句(参数值不为空的加入)(启用安全属性设置,即为空的属性值不进行更新)
* @param object 实体对象
* @param conditionFields 属性条件 可为空, 为空时默认使用主键作为条件
* @return
* @throws BuilderSQLException
*/
SqlModel<Object> updateSelectiveSql(Object object,String[] conditionFields) throws BuilderSQLException;
/**
* 由传入的对象生成update sql语句
* @param object 更新实体数据
* @param properties 需要更新的属性字段 可为空
* @param isSelective 是否只更新不为null的值
* @param conditionFields 属性条件 可为空, 为空时默认使用主键作为条件
* @param whereSql where 部分sql id=1 and name ='chen', 可为null
* @return
* @throws BuilderSQLException
*/
SqlModel<Object> updateSql(Object object,String[] properties,boolean isSelective,String[] conditionFields,String whereSql) throws BuilderSQLException;
/**
* 由传入的Map对象生成update sql语句
* @param entityClass
* @param fieldsMap
* @param isDbFieldName map的key是否采用数据库的字段名称(默认采用数据库的字段名称效率高不用转化)
* @return
* @throws BuilderSQLException
*/
<T> SqlModel<Map<String,?>> updateSql(Class<T> entityClass,Map<String,?> fieldsMap,boolean isDbFieldName) throws BuilderSQLException;
/**
* 由传入的对象生成update sql语句 <br>
* (首选根据对propertys字段进行计算, 当propertys为空时,参数值不为空且为数字的加入进行数学计算)
* @param object
* @param property 计算字段名称 可为空,为空时 参数值不为空且为数字的加入进行数学计算
* @param mathOperation 数学运算类型 {@link MathOperation}
* @param conditionFields where 条件字段 可为空,默认使用主键
* @param whereSql where 部分sql id=1 and name ='chen', 可为null
* @return
* @throws BuilderSQLException
*/
SqlModel<Object> updateMathOperationSql(Object object, String property, MathOperation mathOperation, String[] conditionFields,String whereSql)
throws BuilderSQLException;
/**
* 由传入的对象生成delete sql语句(包括不为null的属性生成sql)
* @param object
* @param primaryKey true 只包括主键参数(根据对象主键生成), <code>false</code> 包括不为null的属性参数
* @param tableName 支持分表查询,可为空
* @return
* @throws BuilderSQLException
*/
SqlModel<Object> deleteSqlByEntity(Object object, boolean primaryKey, String tableName)
throws BuilderSQLException;
/**
* 由传入的sqlConfig 生成delete sql语句
*
* @param sqlConfig sqlConfig
* @return
* @throws BuilderSQLException
*/
SqlModel<Object> deleteSql(SqlConfig sqlConfig) throws BuilderSQLException;
/**
* 根据主键Id删除
* @param entityClass
* @param id
* @return
* @throws BuilderSQLException
*/
<T> SqlModel<Map<String,?>> deleteSqlById(Class<T> entityClass,Serializable id,String tableName)
throws BuilderSQLException;
/**
* 根据主键列表Id删除
* @param entityClass
* @param ids
* @return
* @throws BuilderSQLException
*/
<T> SqlModel<T> deleteSqlByIds(Class<T> entityClass,Object[] ids,String tableName) throws BuilderSQLException;
/**
* 根据主键Id查询
* @param id
* @param entityClass
* @return
* @throws BuilderSQLException
*/
<T> SqlModel<Map<String,?>> selectSqlById(Class<T> entityClass,Serializable id,String tableName)
throws BuilderSQLException;
/**
* 根据实体中的主键Id查询
* @param object
* @return
* @throws BuilderSQLException
*/
SqlModel<Object> selectSqlById(Object object,String tableName) throws BuilderSQLException;
/**
* 查询全表sql(小数量时使用)
* @param entityClass
* @return
* @throws BuilderSQLException
*/
<T> SqlModel<T> selectAllSql(Class<T> entityClass,String tableName) throws BuilderSQLException;
/**
* 统计单表的数量行数
* @param entityClass
* @param afterWhere 增加条件语句 如: and id in(1,2,3)
* @return
* @throws BuilderSQLException
*/
<T> SqlModel<T> countSql(Class<T> entityClass,String afterWhere) throws BuilderSQLException;
/**
*
* 根据实体的参数统计单表的行数
* @param object 参数实体
* @param sqlConfig 增加条件语句 如: and id in(1,2,3)
*
* @throws BuilderSQLException
*/
SqlModel<Object> countSql(Object object, SqlConfig sqlConfig) throws BuilderSQLException;
/**
* 根据主键列表查询
* @param entityClass
* @param ids
* @return
* @throws BuilderSQLException
*/
<T> SqlModel<T> selectSqlByIds(Class<T> entityClass,Collection<?> ids,String tableName)
throws BuilderSQLException;
/**
* 根据主键列表查询
* @param entityClass
* @param ids
* @return
* @throws BuilderSQLException
*/
<T> SqlModel<T> selectSqlByIds(Class<T> entityClass,Object[] ids,String tableName) throws BuilderSQLException;
/**
* 根据实体中的参数查询
* @param object
* @param sqlConfig 特殊参数定义
* @return
* @throws BuilderSQLException
*/
SqlModel<Map<String,?>> objectModeSelectSql(Object object,SqlConfig sqlConfig) throws BuilderSQLException;
/**
* 根据实体中的参数查询
* <ol>
* <li> -1: number use = ;String use = (全部使用等号)</li>
* <li> simpleModel: number use = ;String use Like</li>
* <li> middleModel: </li>
* <li>highModel: </li>
* </ol>
*
* @param object 参数对象
* @param sqlConfig 特殊参数定义
* @return
* @throws BuilderSQLException
*/
SqlModel<Object> selectSql(Object object, SqlConfig sqlConfig) throws BuilderSQLException;
SqlModel<Map<String, ?>> selectSql(Map<String,?> columnMap, SqlConfig sqlConfig) throws BuilderSQLException;
/**
* 根据Servlet ServletRequest parameter 构建sql进行查询
*
* @param request ServletRequest
* @param sqlConfig
* @return
*/
SqlModel<Map<String,Object>> requestQuery(ServletRequest request, SqlConfig sqlConfig);
<T>RowMapper<T> getRowMapper(GroupQuery groupQuery);
}
|
ghsecuritylab/tomato_egg | release/src/router/samba3/source/auth/auth_util.c | <gh_stars>100-1000
/*
Unix SMB/CIFS implementation.
Authentication utility functions
Copyright (C) <NAME> 1992-1998
Copyright (C) <NAME> 2001
Copyright (C) <NAME> 2000-2001
Copyright (C) <NAME> 2002
Copyright (C) <NAME> 2006
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., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
#include "includes.h"
#undef DBGC_CLASS
#define DBGC_CLASS DBGC_AUTH
static struct nt_user_token *create_local_nt_token(TALLOC_CTX *mem_ctx,
const DOM_SID *user_sid,
BOOL is_guest,
int num_groupsids,
const DOM_SID *groupsids);
/****************************************************************************
Create a UNIX user on demand.
****************************************************************************/
static int smb_create_user(const char *domain, const char *unix_username, const char *homedir)
{
pstring add_script;
int ret;
pstrcpy(add_script, lp_adduser_script());
if (! *add_script)
return -1;
all_string_sub(add_script, "%u", unix_username, sizeof(pstring));
if (domain)
all_string_sub(add_script, "%D", domain, sizeof(pstring));
if (homedir)
all_string_sub(add_script, "%H", homedir, sizeof(pstring));
ret = smbrun(add_script,NULL);
flush_pwnam_cache();
DEBUG(ret ? 0 : 3,("smb_create_user: Running the command `%s' gave %d\n",add_script,ret));
return ret;
}
/****************************************************************************
Create an auth_usersupplied_data structure
****************************************************************************/
static NTSTATUS make_user_info(auth_usersupplied_info **user_info,
const char *smb_name,
const char *internal_username,
const char *client_domain,
const char *domain,
const char *wksta_name,
DATA_BLOB *lm_pwd, DATA_BLOB *nt_pwd,
DATA_BLOB *lm_interactive_pwd, DATA_BLOB *nt_interactive_pwd,
DATA_BLOB *plaintext,
BOOL encrypted)
{
DEBUG(5,("attempting to make a user_info for %s (%s)\n", internal_username, smb_name));
*user_info = SMB_MALLOC_P(auth_usersupplied_info);
if (*user_info == NULL) {
DEBUG(0,("malloc failed for user_info (size %lu)\n", (unsigned long)sizeof(*user_info)));
return NT_STATUS_NO_MEMORY;
}
ZERO_STRUCTP(*user_info);
DEBUG(5,("making strings for %s's user_info struct\n", internal_username));
(*user_info)->smb_name = SMB_STRDUP(smb_name);
if ((*user_info)->smb_name == NULL) {
free_user_info(user_info);
return NT_STATUS_NO_MEMORY;
}
(*user_info)->internal_username = SMB_STRDUP(internal_username);
if ((*user_info)->internal_username == NULL) {
free_user_info(user_info);
return NT_STATUS_NO_MEMORY;
}
(*user_info)->domain = SMB_STRDUP(domain);
if ((*user_info)->domain == NULL) {
free_user_info(user_info);
return NT_STATUS_NO_MEMORY;
}
(*user_info)->client_domain = SMB_STRDUP(client_domain);
if ((*user_info)->client_domain == NULL) {
free_user_info(user_info);
return NT_STATUS_NO_MEMORY;
}
(*user_info)->wksta_name = SMB_STRDUP(wksta_name);
if ((*user_info)->wksta_name == NULL) {
free_user_info(user_info);
return NT_STATUS_NO_MEMORY;
}
DEBUG(5,("making blobs for %s's user_info struct\n", internal_username));
if (lm_pwd)
(*user_info)->lm_resp = data_blob(lm_pwd->data, lm_pwd->length);
if (nt_pwd)
(*user_info)->nt_resp = data_blob(nt_pwd->data, nt_pwd->length);
if (lm_interactive_pwd)
(*user_info)->lm_interactive_pwd = data_blob(lm_interactive_pwd->data, lm_interactive_pwd->length);
if (nt_interactive_pwd)
(*user_info)->nt_interactive_pwd = data_blob(nt_interactive_pwd->data, nt_interactive_pwd->length);
if (plaintext)
(*user_info)->plaintext_password = data_blob(plaintext->data, plaintext->length);
(*user_info)->encrypted = encrypted;
(*user_info)->logon_parameters = 0;
DEBUG(10,("made an %sencrypted user_info for %s (%s)\n", encrypted ? "":"un" , internal_username, smb_name));
return NT_STATUS_OK;
}
/****************************************************************************
Create an auth_usersupplied_data structure after appropriate mapping.
****************************************************************************/
NTSTATUS make_user_info_map(auth_usersupplied_info **user_info,
const char *smb_name,
const char *client_domain,
const char *wksta_name,
DATA_BLOB *lm_pwd, DATA_BLOB *nt_pwd,
DATA_BLOB *lm_interactive_pwd, DATA_BLOB *nt_interactive_pwd,
DATA_BLOB *plaintext,
BOOL encrypted)
{
const char *domain;
NTSTATUS result;
BOOL was_mapped;
fstring internal_username;
fstrcpy(internal_username, smb_name);
was_mapped = map_username(internal_username);
DEBUG(5, ("make_user_info_map: Mapping user [%s]\\[%s] from workstation [%s]\n",
client_domain, smb_name, wksta_name));
/* don't allow "" as a domain, fixes a Win9X bug
where it doens't supply a domain for logon script
'net use' commands. */
if ( *client_domain )
domain = client_domain;
else
domain = lp_workgroup();
/* do what win2k does. Always map unknown domains to our own
and let the "passdb backend" handle unknown users. */
if ( !is_trusted_domain(domain) && !strequal(domain, get_global_sam_name()) )
domain = my_sam_name();
/* we know that it is a trusted domain (and we are allowing them) or it is our domain */
result = make_user_info(user_info, smb_name, internal_username,
client_domain, domain, wksta_name,
lm_pwd, nt_pwd,
lm_interactive_pwd, nt_interactive_pwd,
plaintext, encrypted);
if (NT_STATUS_IS_OK(result)) {
(*user_info)->was_mapped = was_mapped;
}
return result;
}
/****************************************************************************
Create an auth_usersupplied_data, making the DATA_BLOBs here.
Decrypt and encrypt the passwords.
****************************************************************************/
BOOL make_user_info_netlogon_network(auth_usersupplied_info **user_info,
const char *smb_name,
const char *client_domain,
const char *wksta_name,
uint32 logon_parameters,
const uchar *lm_network_pwd,
int lm_pwd_len,
const uchar *nt_network_pwd,
int nt_pwd_len)
{
BOOL ret;
NTSTATUS status;
DATA_BLOB lm_blob = data_blob(lm_network_pwd, lm_pwd_len);
DATA_BLOB nt_blob = data_blob(nt_network_pwd, nt_pwd_len);
status = make_user_info_map(user_info,
smb_name, client_domain,
wksta_name,
lm_pwd_len ? &lm_blob : NULL,
nt_pwd_len ? &nt_blob : NULL,
NULL, NULL, NULL,
True);
if (NT_STATUS_IS_OK(status)) {
(*user_info)->logon_parameters = logon_parameters;
}
ret = NT_STATUS_IS_OK(status) ? True : False;
data_blob_free(&lm_blob);
data_blob_free(&nt_blob);
return ret;
}
/****************************************************************************
Create an auth_usersupplied_data, making the DATA_BLOBs here.
Decrypt and encrypt the passwords.
****************************************************************************/
BOOL make_user_info_netlogon_interactive(auth_usersupplied_info **user_info,
const char *smb_name,
const char *client_domain,
const char *wksta_name,
uint32 logon_parameters,
const uchar chal[8],
const uchar lm_interactive_pwd[16],
const uchar nt_interactive_pwd[16],
const uchar *dc_sess_key)
{
char lm_pwd[16];
char nt_pwd[16];
unsigned char local_lm_response[24];
unsigned char local_nt_response[24];
unsigned char key[16];
ZERO_STRUCT(key);
memcpy(key, dc_sess_key, 8);
if (lm_interactive_pwd)
memcpy(lm_pwd, lm_interactive_pwd, sizeof(lm_pwd));
if (nt_interactive_pwd)
memcpy(nt_pwd, nt_interactive_pwd, sizeof(nt_pwd));
#ifdef DEBUG_PASSWORD
DEBUG(100,("key:"));
dump_data(100, (char *)key, sizeof(key));
DEBUG(100,("lm owf password:"));
dump_data(100, lm_pwd, sizeof(lm_pwd));
DEBUG(100,("nt owf password:"));
dump_data(100, nt_pwd, sizeof(nt_pwd));
#endif
if (lm_interactive_pwd)
SamOEMhash((uchar *)lm_pwd, key, sizeof(lm_pwd));
if (nt_interactive_pwd)
SamOEMhash((uchar *)nt_pwd, key, sizeof(nt_pwd));
#ifdef DEBUG_PASSWORD
DEBUG(100,("decrypt of lm owf password:"));
dump_data(100, lm_pwd, sizeof(lm_pwd));
DEBUG(100,("decrypt of nt owf password:"));
dump_data(100, nt_pwd, sizeof(nt_pwd));
#endif
if (lm_interactive_pwd)
SMBOWFencrypt((const unsigned char *)lm_pwd, chal,
local_lm_response);
if (nt_interactive_pwd)
SMBOWFencrypt((const unsigned char *)nt_pwd, chal,
local_nt_response);
/* Password info paranoia */
ZERO_STRUCT(key);
{
BOOL ret;
NTSTATUS nt_status;
DATA_BLOB local_lm_blob;
DATA_BLOB local_nt_blob;
DATA_BLOB lm_interactive_blob;
DATA_BLOB nt_interactive_blob;
if (lm_interactive_pwd) {
local_lm_blob = data_blob(local_lm_response,
sizeof(local_lm_response));
lm_interactive_blob = data_blob(lm_pwd,
sizeof(lm_pwd));
ZERO_STRUCT(lm_pwd);
}
if (nt_interactive_pwd) {
local_nt_blob = data_blob(local_nt_response,
sizeof(local_nt_response));
nt_interactive_blob = data_blob(nt_pwd,
sizeof(nt_pwd));
ZERO_STRUCT(nt_pwd);
}
nt_status = make_user_info_map(
user_info,
smb_name, client_domain, wksta_name,
lm_interactive_pwd ? &local_lm_blob : NULL,
nt_interactive_pwd ? &local_nt_blob : NULL,
lm_interactive_pwd ? &lm_interactive_blob : NULL,
nt_interactive_pwd ? &nt_interactive_blob : NULL,
NULL, True);
if (NT_STATUS_IS_OK(nt_status)) {
(*user_info)->logon_parameters = logon_parameters;
}
ret = NT_STATUS_IS_OK(nt_status) ? True : False;
data_blob_free(&local_lm_blob);
data_blob_free(&local_nt_blob);
data_blob_free(&lm_interactive_blob);
data_blob_free(&nt_interactive_blob);
return ret;
}
}
/****************************************************************************
Create an auth_usersupplied_data structure
****************************************************************************/
BOOL make_user_info_for_reply(auth_usersupplied_info **user_info,
const char *smb_name,
const char *client_domain,
const uint8 chal[8],
DATA_BLOB plaintext_password)
{
DATA_BLOB local_lm_blob;
DATA_BLOB local_nt_blob;
NTSTATUS ret = NT_STATUS_UNSUCCESSFUL;
/*
* Not encrypted - do so.
*/
DEBUG(5,("make_user_info_for_reply: User passwords not in encrypted "
"format.\n"));
if (plaintext_password.data) {
unsigned char local_lm_response[24];
#ifdef DEBUG_PASSWORD
DEBUG(10,("Unencrypted password (len %d):\n",
(int)plaintext_password.length));
dump_data(100, (const char *)plaintext_password.data,
plaintext_password.length);
#endif
SMBencrypt( (const char *)plaintext_password.data,
(const uchar*)chal, local_lm_response);
local_lm_blob = data_blob(local_lm_response, 24);
/* We can't do an NT hash here, as the password needs to be
case insensitive */
local_nt_blob = data_blob(NULL, 0);
} else {
local_lm_blob = data_blob(NULL, 0);
local_nt_blob = data_blob(NULL, 0);
}
ret = make_user_info_map(
user_info, smb_name, client_domain,
get_remote_machine_name(),
local_lm_blob.data ? &local_lm_blob : NULL,
local_nt_blob.data ? &local_nt_blob : NULL,
NULL, NULL,
plaintext_password.data ? &plaintext_password : NULL,
False);
data_blob_free(&local_lm_blob);
return NT_STATUS_IS_OK(ret) ? True : False;
}
/****************************************************************************
Create an auth_usersupplied_data structure
****************************************************************************/
NTSTATUS make_user_info_for_reply_enc(auth_usersupplied_info **user_info,
const char *smb_name,
const char *client_domain,
DATA_BLOB lm_resp, DATA_BLOB nt_resp)
{
return make_user_info_map(user_info, smb_name,
client_domain,
get_remote_machine_name(),
lm_resp.data ? &lm_resp : NULL,
nt_resp.data ? &nt_resp : NULL,
NULL, NULL, NULL,
True);
}
/****************************************************************************
Create a guest user_info blob, for anonymous authenticaion.
****************************************************************************/
BOOL make_user_info_guest(auth_usersupplied_info **user_info)
{
NTSTATUS nt_status;
nt_status = make_user_info(user_info,
"","",
"","",
"",
NULL, NULL,
NULL, NULL,
NULL,
True);
return NT_STATUS_IS_OK(nt_status) ? True : False;
}
/****************************************************************************
prints a NT_USER_TOKEN to debug output.
****************************************************************************/
void debug_nt_user_token(int dbg_class, int dbg_lev, NT_USER_TOKEN *token)
{
size_t i;
if (!token) {
DEBUGC(dbg_class, dbg_lev, ("NT user token: (NULL)\n"));
return;
}
DEBUGC(dbg_class, dbg_lev,
("NT user token of user %s\n",
sid_string_static(&token->user_sids[0]) ));
DEBUGADDC(dbg_class, dbg_lev,
("contains %lu SIDs\n", (unsigned long)token->num_sids));
for (i = 0; i < token->num_sids; i++)
DEBUGADDC(dbg_class, dbg_lev,
("SID[%3lu]: %s\n", (unsigned long)i,
sid_string_static(&token->user_sids[i])));
dump_se_priv( dbg_class, dbg_lev, &token->privileges );
}
/****************************************************************************
prints a UNIX 'token' to debug output.
****************************************************************************/
void debug_unix_user_token(int dbg_class, int dbg_lev, uid_t uid, gid_t gid,
int n_groups, gid_t *groups)
{
int i;
DEBUGC(dbg_class, dbg_lev,
("UNIX token of user %ld\n", (long int)uid));
DEBUGADDC(dbg_class, dbg_lev,
("Primary group is %ld and contains %i supplementary "
"groups\n", (long int)gid, n_groups));
for (i = 0; i < n_groups; i++)
DEBUGADDC(dbg_class, dbg_lev, ("Group[%3i]: %ld\n", i,
(long int)groups[i]));
}
/******************************************************************************
Create a token for the root user to be used internally by smbd.
This is similar to running under the context of the LOCAL_SYSTEM account
in Windows. This is a read-only token. Do not modify it or free() it.
Create a copy if your need to change it.
******************************************************************************/
NT_USER_TOKEN *get_root_nt_token( void )
{
static NT_USER_TOKEN *token = NULL;
DOM_SID u_sid, g_sid;
struct passwd *pw;
if ( token )
return token;
if ( !(pw = sys_getpwnam( "root" )) ) {
DEBUG(0,("get_root_nt_token: getpwnam\"root\") failed!\n"));
return NULL;
}
/* get the user and primary group SIDs; although the
BUILTIN\Administrators SId is really the one that matters here */
uid_to_sid(&u_sid, pw->pw_uid);
gid_to_sid(&g_sid, pw->pw_gid);
token = create_local_nt_token(NULL, &u_sid, False,
1, &global_sid_Builtin_Administrators);
return token;
}
static int server_info_dtor(auth_serversupplied_info *server_info)
{
TALLOC_FREE(server_info->sam_account);
ZERO_STRUCTP(server_info);
return 0;
}
/***************************************************************************
Make a server_info struct. Free with TALLOC_FREE().
***************************************************************************/
static auth_serversupplied_info *make_server_info(TALLOC_CTX *mem_ctx)
{
struct auth_serversupplied_info *result;
result = TALLOC_ZERO_P(mem_ctx, auth_serversupplied_info);
if (result == NULL) {
DEBUG(0, ("talloc failed\n"));
return NULL;
}
talloc_set_destructor(result, server_info_dtor);
/* Initialise the uid and gid values to something non-zero
which may save us from giving away root access if there
is a bug in allocating these fields. */
result->uid = -1;
result->gid = -1;
return result;
}
/***************************************************************************
Is the incoming username our own machine account ?
If so, the connection is almost certainly from winbindd.
***************************************************************************/
static BOOL is_our_machine_account(const char *username)
{
BOOL ret;
char *truncname = NULL;
size_t ulen = strlen(username);
if (ulen == 0 || username[ulen-1] != '$') {
return False;
}
truncname = SMB_STRDUP(username);
if (!truncname) {
return False;
}
truncname[ulen-1] = '\0';
ret = strequal(truncname, global_myname());
SAFE_FREE(truncname);
return ret;
}
/***************************************************************************
Make (and fill) a user_info struct from a struct samu
***************************************************************************/
NTSTATUS make_server_info_sam(auth_serversupplied_info **server_info,
struct samu *sampass)
{
struct passwd *pwd;
gid_t *gids;
auth_serversupplied_info *result;
int i;
size_t num_gids;
DOM_SID unix_group_sid;
const char *username = pdb_get_username(sampass);
if ( !(pwd = getpwnam_alloc(NULL, username)) ) {
DEBUG(1, ("User %s in passdb, but getpwnam() fails!\n",
username));
return NT_STATUS_NO_SUCH_USER;
}
if ( !(result = make_server_info(NULL)) ) {
TALLOC_FREE(pwd);
return NT_STATUS_NO_MEMORY;
}
result->sam_account = sampass;
result->unix_name = talloc_strdup(result, pwd->pw_name);
result->gid = pwd->pw_gid;
result->uid = pwd->pw_uid;
TALLOC_FREE(pwd);
if (IS_DC && is_our_machine_account(username)) {
/*
* Ensure for a connection from our own
* machine account (from winbindd on a DC)
* there are no supplementary groups.
* Prevents loops in calling gid_to_sid().
*/
result->sids = NULL;
gids = NULL;
result->num_sids = 0;
/*
* This is a hack of monstrous proportions.
* If we know it's winbindd talking to us,
* we know we must never recurse into it,
* so turn off contacting winbindd for this
* entire process. This will get fixed when
* winbindd doesn't need to talk to smbd on
* a PDC. JRA.
*/
winbind_off();
DEBUG(10, ("make_server_info_sam: our machine account %s "
"setting supplementary group list empty and "
"turning off winbindd requests.\n",
username));
} else {
NTSTATUS status = pdb_enum_group_memberships(result, sampass,
&result->sids, &gids,
&result->num_sids);
if (!NT_STATUS_IS_OK(status)) {
DEBUG(10, ("pdb_enum_group_memberships failed: %s\n",
nt_errstr(status)));
result->sam_account = NULL; /* Don't free on error exit. */
TALLOC_FREE(result);
return status;
}
}
/* Add the "Unix Group" SID for each gid to catch mapped groups
and their Unix equivalent. This is to solve the backwards
compatibility problem of 'valid users = +ntadmin' where
ntadmin has been paired with "Domain Admins" in the group
mapping table. Otherwise smb.conf would need to be changed
to 'valid user = "Domain Admins"'. --jerry */
num_gids = result->num_sids;
for ( i=0; i<num_gids; i++ ) {
if ( !gid_to_unix_groups_sid( gids[i], &unix_group_sid ) ) {
DEBUG(1,("make_server_info_sam: Failed to create SID "
"for gid %d!\n", gids[i]));
continue;
}
if (!add_sid_to_array_unique( result, &unix_group_sid,
&result->sids, &result->num_sids )) {
result->sam_account = NULL; /* Don't free on error exit. */
TALLOC_FREE(result);
return NT_STATUS_NO_MEMORY;
}
}
/* For now we throw away the gids and convert via sid_to_gid
* later. This needs fixing, but I'd like to get the code straight and
* simple first. */
TALLOC_FREE(gids);
DEBUG(5,("make_server_info_sam: made server info for user %s -> %s\n",
pdb_get_username(sampass), result->unix_name));
*server_info = result;
return NT_STATUS_OK;
}
/*
* Add alias SIDs from memberships within the partially created token SID list
*/
static NTSTATUS add_aliases(const DOM_SID *domain_sid,
struct nt_user_token *token)
{
uint32 *aliases;
size_t i, num_aliases;
NTSTATUS status;
TALLOC_CTX *tmp_ctx;
if (!(tmp_ctx = talloc_init("add_aliases"))) {
return NT_STATUS_NO_MEMORY;
}
aliases = NULL;
num_aliases = 0;
status = pdb_enum_alias_memberships(tmp_ctx, domain_sid,
token->user_sids,
token->num_sids,
&aliases, &num_aliases);
if (!NT_STATUS_IS_OK(status)) {
DEBUG(10, ("pdb_enum_alias_memberships failed: %s\n",
nt_errstr(status)));
TALLOC_FREE(tmp_ctx);
return status;
}
for (i=0; i<num_aliases; i++) {
DOM_SID alias_sid;
sid_compose(&alias_sid, domain_sid, aliases[i]);
if (!add_sid_to_array_unique(token, &alias_sid,
&token->user_sids,
&token->num_sids)) {
DEBUG(0, ("add_sid_to_array failed\n"));
TALLOC_FREE(tmp_ctx);
return NT_STATUS_NO_MEMORY;
}
}
TALLOC_FREE(tmp_ctx);
return NT_STATUS_OK;
}
static NTSTATUS log_nt_token(TALLOC_CTX *tmp_ctx, NT_USER_TOKEN *token)
{
char *command;
char *group_sidstr;
size_t i;
if ((lp_log_nt_token_command() == NULL) ||
(strlen(lp_log_nt_token_command()) == 0)) {
return NT_STATUS_OK;
}
group_sidstr = talloc_strdup(tmp_ctx, "");
for (i=1; i<token->num_sids; i++) {
group_sidstr = talloc_asprintf(
tmp_ctx, "%s %s", group_sidstr,
sid_string_static(&token->user_sids[i]));
}
command = talloc_string_sub(
tmp_ctx, lp_log_nt_token_command(),
"%s", sid_string_static(&token->user_sids[0]));
command = talloc_string_sub(tmp_ctx, command, "%t", group_sidstr);
if (command == NULL) {
return NT_STATUS_NO_MEMORY;
}
DEBUG(8, ("running command: [%s]\n", command));
if (smbrun(command, NULL) != 0) {
DEBUG(0, ("Could not log NT token\n"));
return NT_STATUS_ACCESS_DENIED;
}
return NT_STATUS_OK;
}
/*******************************************************************
*******************************************************************/
static NTSTATUS add_builtin_administrators( struct nt_user_token *token )
{
DOM_SID domadm;
/* nothing to do if we aren't in a domain */
if ( !(IS_DC || lp_server_role()==ROLE_DOMAIN_MEMBER) ) {
return NT_STATUS_OK;
}
/* Find the Domain Admins SID */
if ( IS_DC ) {
sid_copy( &domadm, get_global_sam_sid() );
} else {
if ( !secrets_fetch_domain_sid( lp_workgroup(), &domadm ) )
return NT_STATUS_CANT_ACCESS_DOMAIN_INFO;
}
sid_append_rid( &domadm, DOMAIN_GROUP_RID_ADMINS );
/* Add Administrators if the user beloongs to Domain Admins */
if ( nt_token_check_sid( &domadm, token ) ) {
if (!add_sid_to_array(token, &global_sid_Builtin_Administrators,
&token->user_sids, &token->num_sids)) {
return NT_STATUS_NO_MEMORY;
}
}
return NT_STATUS_OK;
}
/*******************************************************************
*******************************************************************/
static NTSTATUS create_builtin_users( void )
{
NTSTATUS status;
DOM_SID dom_users;
status = pdb_create_builtin_alias( BUILTIN_ALIAS_RID_USERS );
if ( !NT_STATUS_IS_OK(status) ) {
DEBUG(0,("create_builtin_users: Failed to create Users\n"));
return status;
}
/* add domain users */
if ((IS_DC || (lp_server_role() == ROLE_DOMAIN_MEMBER))
&& secrets_fetch_domain_sid(lp_workgroup(), &dom_users))
{
sid_append_rid(&dom_users, DOMAIN_GROUP_RID_USERS );
status = pdb_add_aliasmem( &global_sid_Builtin_Users, &dom_users);
if ( !NT_STATUS_IS_OK(status) ) {
DEBUG(0,("create_builtin_users: Failed to add Domain Users to"
" Users\n"));
return status;
}
}
return NT_STATUS_OK;
}
/*******************************************************************
*******************************************************************/
static NTSTATUS create_builtin_administrators( void )
{
NTSTATUS status;
DOM_SID dom_admins, root_sid;
fstring root_name;
enum lsa_SidType type;
TALLOC_CTX *ctx;
BOOL ret;
status = pdb_create_builtin_alias( BUILTIN_ALIAS_RID_ADMINS );
if ( !NT_STATUS_IS_OK(status) ) {
DEBUG(0,("create_builtin_administrators: Failed to create Administrators\n"));
return status;
}
/* add domain admins */
if ((IS_DC || (lp_server_role() == ROLE_DOMAIN_MEMBER))
&& secrets_fetch_domain_sid(lp_workgroup(), &dom_admins))
{
sid_append_rid(&dom_admins, DOMAIN_GROUP_RID_ADMINS);
status = pdb_add_aliasmem( &global_sid_Builtin_Administrators, &dom_admins );
if ( !NT_STATUS_IS_OK(status) ) {
DEBUG(0,("create_builtin_administrators: Failed to add Domain Admins"
" Administrators\n"));
return status;
}
}
/* add root */
if ( (ctx = talloc_init("create_builtin_administrators")) == NULL ) {
return NT_STATUS_NO_MEMORY;
}
fstr_sprintf( root_name, "%s\\root", get_global_sam_name() );
ret = lookup_name( ctx, root_name, LOOKUP_NAME_DOMAIN, NULL, NULL, &root_sid, &type );
TALLOC_FREE( ctx );
if ( ret ) {
status = pdb_add_aliasmem( &global_sid_Builtin_Administrators, &root_sid );
if ( !NT_STATUS_IS_OK(status) ) {
DEBUG(0,("create_builtin_administrators: Failed to add root"
" Administrators\n"));
return status;
}
}
return NT_STATUS_OK;
}
/*******************************************************************
Create a NT token for the user, expanding local aliases
*******************************************************************/
static struct nt_user_token *create_local_nt_token(TALLOC_CTX *mem_ctx,
const DOM_SID *user_sid,
BOOL is_guest,
int num_groupsids,
const DOM_SID *groupsids)
{
struct nt_user_token *result = NULL;
int i;
NTSTATUS status;
gid_t gid;
DEBUG(10, ("Create local NT token for %s\n", sid_string_static(user_sid)));
if (!(result = TALLOC_ZERO_P(mem_ctx, NT_USER_TOKEN))) {
DEBUG(0, ("talloc failed\n"));
return NULL;
}
/* Add the user and primary group sid */
if (!add_sid_to_array(result, user_sid,
&result->user_sids, &result->num_sids)) {
return NULL;
}
/* For guest, num_groupsids may be zero. */
if (num_groupsids) {
if (!add_sid_to_array(result, &groupsids[0],
&result->user_sids, &result->num_sids)) {
return NULL;
}
}
/* Add in BUILTIN sids */
if (!add_sid_to_array(result, &global_sid_World,
&result->user_sids, &result->num_sids)) {
return NULL;
}
if (!add_sid_to_array(result, &global_sid_Network,
&result->user_sids, &result->num_sids)) {
return NULL;
}
if (is_guest) {
if (!add_sid_to_array(result, &global_sid_Builtin_Guests,
&result->user_sids, &result->num_sids)) {
return NULL;
}
} else {
if (!add_sid_to_array(result, &global_sid_Authenticated_Users,
&result->user_sids, &result->num_sids)) {
return NULL;
}
}
/* Now the SIDs we got from authentication. These are the ones from
* the info3 struct or from the pdb_enum_group_memberships, depending
* on who authenticated the user.
* Note that we start the for loop at "1" here, we already added the
* first group sid as primary above. */
for (i=1; i<num_groupsids; i++) {
if (!add_sid_to_array_unique(result, &groupsids[i],
&result->user_sids, &result->num_sids)) {
return NULL;
}
}
/* Deal with the BUILTIN\Administrators group. If the SID can
be resolved then assume that the add_aliasmem( S-1-5-32 )
handled it. */
if ( !sid_to_gid( &global_sid_Builtin_Administrators, &gid ) ) {
/* We can only create a mapping if winbind is running
and the nested group functionality has been enabled */
if ( lp_winbind_nested_groups() && winbind_ping() ) {
become_root();
status = create_builtin_administrators( );
if ( !NT_STATUS_IS_OK(status) ) {
DEBUG(2,("create_local_nt_token: Failed to create BUILTIN\\Administrators group!\n"));
/* don't fail, just log the message */
}
unbecome_root();
}
else {
status = add_builtin_administrators( result );
if ( !NT_STATUS_IS_OK(status) ) {
/* just log a complaint but do not fail */
DEBUG(3,("create_local_nt_token: failed to check for local Administrators"
" membership (%s)\n", nt_errstr(status)));
}
}
}
/* Deal with the BUILTIN\Users group. If the SID can
be resolved then assume that the add_aliasmem( S-1-5-32 )
handled it. */
if ( !sid_to_gid( &global_sid_Builtin_Users, &gid ) ) {
/* We can only create a mapping if winbind is running
and the nested group functionality has been enabled */
if ( lp_winbind_nested_groups() && winbind_ping() ) {
become_root();
status = create_builtin_users( );
if ( !NT_STATUS_IS_OK(status) ) {
DEBUG(2,("create_local_nt_token: Failed to create BUILTIN\\Users group!\n"));
/* don't fail, just log the message */
}
unbecome_root();
}
}
/* Deal with local groups */
if (lp_winbind_nested_groups()) {
become_root();
/* Now add the aliases. First the one from our local SAM */
status = add_aliases(get_global_sam_sid(), result);
if (!NT_STATUS_IS_OK(status)) {
unbecome_root();
TALLOC_FREE(result);
return NULL;
}
/* Finally the builtin ones */
status = add_aliases(&global_sid_Builtin, result);
if (!NT_STATUS_IS_OK(status)) {
unbecome_root();
TALLOC_FREE(result);
return NULL;
}
unbecome_root();
}
get_privileges_for_sids(&result->privileges, result->user_sids,
result->num_sids);
return result;
}
/*
* Create the token to use from server_info->sam_account and
* server_info->sids (the info3/sam groups). Find the unix gids.
*/
NTSTATUS create_local_token(auth_serversupplied_info *server_info)
{
TALLOC_CTX *mem_ctx;
NTSTATUS status;
size_t i;
mem_ctx = talloc_new(NULL);
if (mem_ctx == NULL) {
DEBUG(0, ("talloc_new failed\n"));
return NT_STATUS_NO_MEMORY;
}
/*
* If winbind is not around, we can not make much use of the SIDs the
* domain controller provided us with. Likewise if the user name was
* mapped to some local unix user.
*/
if (((lp_server_role() == ROLE_DOMAIN_MEMBER) && !winbind_ping()) ||
(server_info->was_mapped)) {
status = create_token_from_username(server_info,
server_info->unix_name,
server_info->guest,
&server_info->uid,
&server_info->gid,
&server_info->unix_name,
&server_info->ptok);
} else {
server_info->ptok = create_local_nt_token(
server_info,
pdb_get_user_sid(server_info->sam_account),
server_info->guest,
server_info->num_sids, server_info->sids);
status = server_info->ptok ?
NT_STATUS_OK : NT_STATUS_NO_SUCH_USER;
}
if (!NT_STATUS_IS_OK(status)) {
TALLOC_FREE(mem_ctx);
return status;
}
/* Convert the SIDs to gids. */
server_info->n_groups = 0;
server_info->groups = NULL;
/* Start at index 1, where the groups start. */
for (i=1; i<server_info->ptok->num_sids; i++) {
gid_t gid;
DOM_SID *sid = &server_info->ptok->user_sids[i];
if (!sid_to_gid(sid, &gid)) {
DEBUG(10, ("Could not convert SID %s to gid, "
"ignoring it\n", sid_string_static(sid)));
continue;
}
add_gid_to_array_unique(server_info, gid, &server_info->groups,
&server_info->n_groups);
}
debug_nt_user_token(DBGC_AUTH, 10, server_info->ptok);
status = log_nt_token(mem_ctx, server_info->ptok);
TALLOC_FREE(mem_ctx);
return status;
}
/*
* Create an artificial NT token given just a username. (Initially indended
* for force user)
*
* We go through lookup_name() to avoid problems we had with 'winbind use
* default domain'.
*
* We have 3 cases:
*
* unmapped unix users: Go directly to nss to find the user's group.
*
* A passdb user: The list of groups is provided by pdb_enum_group_memberships.
*
* If the user is provided by winbind, the primary gid is set to "domain
* users" of the user's domain. For an explanation why this is necessary, see
* the thread starting at
* http://lists.samba.org/archive/samba-technical/2006-January/044803.html.
*/
NTSTATUS create_token_from_username(TALLOC_CTX *mem_ctx, const char *username,
BOOL is_guest,
uid_t *uid, gid_t *gid,
char **found_username,
struct nt_user_token **token)
{
NTSTATUS result = NT_STATUS_NO_SUCH_USER;
TALLOC_CTX *tmp_ctx;
DOM_SID user_sid;
enum lsa_SidType type;
gid_t *gids;
DOM_SID *group_sids;
DOM_SID unix_group_sid;
size_t num_group_sids;
size_t num_gids;
size_t i;
tmp_ctx = talloc_new(NULL);
if (tmp_ctx == NULL) {
DEBUG(0, ("talloc_new failed\n"));
return NT_STATUS_NO_MEMORY;
}
if (!lookup_name_smbconf(tmp_ctx, username, LOOKUP_NAME_ALL,
NULL, NULL, &user_sid, &type)) {
DEBUG(1, ("lookup_name_smbconf for %s failed\n", username));
goto done;
}
if (type != SID_NAME_USER) {
DEBUG(1, ("%s is a %s, not a user\n", username,
sid_type_lookup(type)));
goto done;
}
if (!sid_to_uid(&user_sid, uid)) {
DEBUG(1, ("sid_to_uid for %s (%s) failed\n",
username, sid_string_static(&user_sid)));
goto done;
}
if (sid_check_is_in_our_domain(&user_sid)) {
BOOL ret;
/* This is a passdb user, so ask passdb */
struct samu *sam_acct = NULL;
if ( !(sam_acct = samu_new( tmp_ctx )) ) {
result = NT_STATUS_NO_MEMORY;
goto done;
}
become_root();
ret = pdb_getsampwsid(sam_acct, &user_sid);
unbecome_root();
if (!ret) {
DEBUG(1, ("pdb_getsampwsid(%s) for user %s failed\n",
sid_string_static(&user_sid), username));
DEBUGADD(1, ("Fall back to unix user %s\n", username));
goto unix_user;
}
result = pdb_enum_group_memberships(tmp_ctx, sam_acct,
&group_sids, &gids,
&num_group_sids);
if (!NT_STATUS_IS_OK(result)) {
DEBUG(10, ("enum_group_memberships failed for %s\n",
username));
DEBUGADD(1, ("Fall back to unix user %s\n", username));
goto unix_user;
}
/* see the smb_panic() in pdb_default_enum_group_memberships */
SMB_ASSERT(num_group_sids > 0);
*gid = gids[0];
/* Ensure we're returning the found_username on the right context. */
*found_username = talloc_strdup(mem_ctx,
pdb_get_username(sam_acct));
} else if (sid_check_is_in_unix_users(&user_sid)) {
/* This is a unix user not in passdb. We need to ask nss
* directly, without consulting passdb */
struct passwd *pass;
/*
* This goto target is used as a fallback for the passdb
* case. The concrete bug report is when passdb gave us an
* unmapped gid.
*/
unix_user:
uid_to_unix_users_sid(*uid, &user_sid);
pass = getpwuid_alloc(tmp_ctx, *uid);
if (pass == NULL) {
DEBUG(1, ("getpwuid(%d) for user %s failed\n",
*uid, username));
goto done;
}
if (!getgroups_unix_user(tmp_ctx, username, pass->pw_gid,
&gids, &num_group_sids)) {
DEBUG(1, ("getgroups_unix_user for user %s failed\n",
username));
goto done;
}
if (num_group_sids) {
group_sids = TALLOC_ARRAY(tmp_ctx, DOM_SID, num_group_sids);
if (group_sids == NULL) {
DEBUG(1, ("TALLOC_ARRAY failed\n"));
result = NT_STATUS_NO_MEMORY;
goto done;
}
} else {
group_sids = NULL;
}
for (i=0; i<num_group_sids; i++) {
gid_to_sid(&group_sids[i], gids[i]);
}
/* In getgroups_unix_user we always set the primary gid */
SMB_ASSERT(num_group_sids > 0);
*gid = gids[0];
/* Ensure we're returning the found_username on the right context. */
*found_username = talloc_strdup(mem_ctx, pass->pw_name);
} else {
/* This user is from winbind, force the primary gid to the
* user's "domain users" group. Under certain circumstances
* (user comes from NT4), this might be a loss of
* information. But we can not rely on winbind getting the
* correct info. AD might prohibit winbind looking up that
* information. */
uint32 dummy;
num_group_sids = 1;
group_sids = TALLOC_ARRAY(tmp_ctx, DOM_SID, num_group_sids);
if (group_sids == NULL) {
DEBUG(1, ("TALLOC_ARRAY failed\n"));
result = NT_STATUS_NO_MEMORY;
goto done;
}
sid_copy(&group_sids[0], &user_sid);
sid_split_rid(&group_sids[0], &dummy);
sid_append_rid(&group_sids[0], DOMAIN_GROUP_RID_USERS);
if (!sid_to_gid(&group_sids[0], gid)) {
DEBUG(1, ("sid_to_gid(%s) failed\n",
sid_string_static(&group_sids[0])));
goto done;
}
gids = gid;
/* Ensure we're returning the found_username on the right context. */
*found_username = talloc_strdup(mem_ctx, username);
}
/* Add the "Unix Group" SID for each gid to catch mapped groups
and their Unix equivalent. This is to solve the backwards
compatibility problem of 'valid users = +ntadmin' where
ntadmin has been paired with "Domain Admins" in the group
mapping table. Otherwise smb.conf would need to be changed
to 'valid user = "Domain Admins"'. --jerry */
num_gids = num_group_sids;
for ( i=0; i<num_gids; i++ ) {
gid_t high, low;
/* don't pickup anything managed by Winbind */
if ( lp_idmap_gid(&low, &high) && (gids[i] >= low) && (gids[i] <= high) )
continue;
if ( !gid_to_unix_groups_sid( gids[i], &unix_group_sid ) ) {
DEBUG(1,("create_token_from_username: Failed to create SID "
"for gid %d!\n", gids[i]));
continue;
}
if (!add_sid_to_array_unique(tmp_ctx, &unix_group_sid,
&group_sids, &num_group_sids )) {
result = NT_STATUS_NO_MEMORY;
goto done;
}
}
/* Ensure we're creating the nt_token on the right context. */
*token = create_local_nt_token(mem_ctx, &user_sid,
is_guest, num_group_sids, group_sids);
if ((*token == NULL) || (*found_username == NULL)) {
result = NT_STATUS_NO_MEMORY;
goto done;
}
result = NT_STATUS_OK;
done:
TALLOC_FREE(tmp_ctx);
return result;
}
/***************************************************************************
Build upon create_token_from_username:
Expensive helper function to figure out whether a user given its name is
member of a particular group.
***************************************************************************/
BOOL user_in_group_sid(const char *username, const DOM_SID *group_sid)
{
NTSTATUS status;
uid_t uid;
gid_t gid;
char *found_username;
struct nt_user_token *token;
BOOL result;
TALLOC_CTX *mem_ctx;
mem_ctx = talloc_new(NULL);
if (mem_ctx == NULL) {
DEBUG(0, ("talloc_new failed\n"));
return False;
}
status = create_token_from_username(mem_ctx, username, False,
&uid, &gid, &found_username,
&token);
if (!NT_STATUS_IS_OK(status)) {
DEBUG(10, ("could not create token for %s\n", username));
return False;
}
result = nt_token_check_sid(group_sid, token);
TALLOC_FREE(mem_ctx);
return result;
}
BOOL user_in_group(const char *username, const char *groupname)
{
TALLOC_CTX *mem_ctx;
DOM_SID group_sid;
BOOL ret;
mem_ctx = talloc_new(NULL);
if (mem_ctx == NULL) {
DEBUG(0, ("talloc_new failed\n"));
return False;
}
ret = lookup_name(mem_ctx, groupname, LOOKUP_NAME_ALL,
NULL, NULL, &group_sid, NULL);
TALLOC_FREE(mem_ctx);
if (!ret) {
DEBUG(10, ("lookup_name for (%s) failed.\n", groupname));
return False;
}
return user_in_group_sid(username, &group_sid);
}
/***************************************************************************
Make (and fill) a user_info struct from a 'struct passwd' by conversion
to a struct samu
***************************************************************************/
NTSTATUS make_server_info_pw(auth_serversupplied_info **server_info,
char *unix_username,
struct passwd *pwd)
{
NTSTATUS status;
struct samu *sampass = NULL;
gid_t *gids;
char *qualified_name = NULL;
TALLOC_CTX *mem_ctx = NULL;
DOM_SID u_sid;
enum lsa_SidType type;
auth_serversupplied_info *result;
if ( !(sampass = samu_new( NULL )) ) {
return NT_STATUS_NO_MEMORY;
}
status = samu_set_unix( sampass, pwd );
if (!NT_STATUS_IS_OK(status)) {
return status;
}
result = make_server_info(NULL);
if (result == NULL) {
TALLOC_FREE(sampass);
return NT_STATUS_NO_MEMORY;
}
result->sam_account = sampass;
result->unix_name = talloc_strdup(result, unix_username);
result->uid = pwd->pw_uid;
result->gid = pwd->pw_gid;
status = pdb_enum_group_memberships(result, sampass,
&result->sids, &gids,
&result->num_sids);
if (!NT_STATUS_IS_OK(status)) {
DEBUG(10, ("pdb_enum_group_memberships failed: %s\n",
nt_errstr(status)));
TALLOC_FREE(result);
return status;
}
/*
* The SID returned in server_info->sam_account is based
* on our SAM sid even though for a pure UNIX account this should
* not be the case as it doesn't really exist in the SAM db.
* This causes lookups on "[in]valid users" to fail as they
* will lookup this name as a "Unix User" SID to check against
* the user token. Fix this by adding the "Unix User"\unix_username
* SID to the sid array. The correct fix should probably be
* changing the server_info->sam_account user SID to be a
* S-1-22 Unix SID, but this might break old configs where
* plaintext passwords were used with no SAM backend.
*/
mem_ctx = talloc_init("make_server_info_pw_tmp");
if (!mem_ctx) {
TALLOC_FREE(result);
return NT_STATUS_NO_MEMORY;
}
qualified_name = talloc_asprintf(mem_ctx, "%s\\%s",
unix_users_domain_name(),
unix_username );
if (!qualified_name) {
TALLOC_FREE(result);
TALLOC_FREE(mem_ctx);
return NT_STATUS_NO_MEMORY;
}
if (!lookup_name(mem_ctx, qualified_name, LOOKUP_NAME_ALL,
NULL, NULL,
&u_sid, &type)) {
TALLOC_FREE(result);
TALLOC_FREE(mem_ctx);
return NT_STATUS_NO_SUCH_USER;
}
TALLOC_FREE(mem_ctx);
if (type != SID_NAME_USER) {
TALLOC_FREE(result);
return NT_STATUS_NO_SUCH_USER;
}
if (!add_sid_to_array_unique(result, &u_sid,
&result->sids,
&result->num_sids)) {
TALLOC_FREE(result);
return NT_STATUS_NO_MEMORY;
}
/* For now we throw away the gids and convert via sid_to_gid
* later. This needs fixing, but I'd like to get the code straight and
* simple first. */
TALLOC_FREE(gids);
*server_info = result;
return NT_STATUS_OK;
}
/***************************************************************************
Make (and fill) a user_info struct for a guest login.
This *must* succeed for smbd to start. If there is no mapping entry for
the guest gid, then create one.
***************************************************************************/
static NTSTATUS make_new_server_info_guest(auth_serversupplied_info **server_info)
{
NTSTATUS status;
struct samu *sampass = NULL;
DOM_SID guest_sid;
BOOL ret;
static const char zeros[16] = { 0, };
if ( !(sampass = samu_new( NULL )) ) {
return NT_STATUS_NO_MEMORY;
}
sid_copy(&guest_sid, get_global_sam_sid());
sid_append_rid(&guest_sid, DOMAIN_USER_RID_GUEST);
become_root();
ret = pdb_getsampwsid(sampass, &guest_sid);
unbecome_root();
if (!ret) {
TALLOC_FREE(sampass);
return NT_STATUS_NO_SUCH_USER;
}
status = make_server_info_sam(server_info, sampass);
if (!NT_STATUS_IS_OK(status)) {
TALLOC_FREE(sampass);
return status;
}
(*server_info)->guest = True;
status = create_local_token(*server_info);
if (!NT_STATUS_IS_OK(status)) {
DEBUG(10, ("create_local_token failed: %s\n",
nt_errstr(status)));
return status;
}
/* annoying, but the Guest really does have a session key, and it is
all zeros! */
(*server_info)->user_session_key = data_blob(zeros, sizeof(zeros));
(*server_info)->lm_session_key = data_blob(zeros, sizeof(zeros));
return NT_STATUS_OK;
}
static auth_serversupplied_info *copy_serverinfo(auth_serversupplied_info *src)
{
auth_serversupplied_info *dst;
dst = make_server_info(NULL);
if (dst == NULL) {
return NULL;
}
dst->guest = src->guest;
dst->uid = src->uid;
dst->gid = src->gid;
dst->n_groups = src->n_groups;
if (src->n_groups != 0) {
dst->groups = (gid_t *)TALLOC_MEMDUP(
dst, src->groups, sizeof(gid_t)*dst->n_groups);
} else {
dst->groups = NULL;
}
if (src->ptok) {
dst->ptok = dup_nt_token(dst, src->ptok);
if (!dst->ptok) {
TALLOC_FREE(dst);
return NULL;
}
}
dst->user_session_key = data_blob_talloc( dst, src->user_session_key.data,
src->user_session_key.length);
dst->lm_session_key = data_blob_talloc(dst, src->lm_session_key.data,
src->lm_session_key.length);
dst->sam_account = samu_new(NULL);
if (!dst->sam_account) {
TALLOC_FREE(dst);
return NULL;
}
if (!pdb_copy_sam_account(dst->sam_account, src->sam_account)) {
TALLOC_FREE(dst);
return NULL;
}
dst->pam_handle = NULL;
dst->unix_name = talloc_strdup(dst, src->unix_name);
if (!dst->unix_name) {
TALLOC_FREE(dst);
return NULL;
}
return dst;
}
static auth_serversupplied_info *guest_info = NULL;
BOOL init_guest_info(void)
{
if (guest_info != NULL)
return True;
return NT_STATUS_IS_OK(make_new_server_info_guest(&guest_info));
}
NTSTATUS make_server_info_guest(auth_serversupplied_info **server_info)
{
*server_info = copy_serverinfo(guest_info);
return (*server_info != NULL) ? NT_STATUS_OK : NT_STATUS_NO_MEMORY;
}
BOOL copy_current_user(struct current_user *dst, struct current_user *src)
{
gid_t *groups;
NT_USER_TOKEN *nt_token;
groups = (gid_t *)memdup(src->ut.groups,
sizeof(gid_t) * src->ut.ngroups);
if ((src->ut.ngroups != 0) && (groups == NULL)) {
return False;
}
nt_token = dup_nt_token(NULL, src->nt_user_token);
if (nt_token == NULL) {
SAFE_FREE(groups);
return False;
}
dst->conn = src->conn;
dst->vuid = src->vuid;
dst->ut.uid = src->ut.uid;
dst->ut.gid = src->ut.gid;
dst->ut.ngroups = src->ut.ngroups;
dst->ut.groups = groups;
dst->nt_user_token = nt_token;
return True;
}
BOOL set_current_user_guest(struct current_user *dst)
{
gid_t *groups;
NT_USER_TOKEN *nt_token;
groups = (gid_t *)memdup(guest_info->groups,
sizeof(gid_t) * guest_info->n_groups);
if (groups == NULL) {
return False;
}
nt_token = dup_nt_token(NULL, guest_info->ptok);
if (nt_token == NULL) {
SAFE_FREE(groups);
return False;
}
TALLOC_FREE(dst->nt_user_token);
SAFE_FREE(dst->ut.groups);
/* dst->conn is never really dereferenced, it's only tested for
* equality in uid.c */
dst->conn = NULL;
dst->vuid = UID_FIELD_INVALID;
dst->ut.uid = guest_info->uid;
dst->ut.gid = guest_info->gid;
dst->ut.ngroups = guest_info->n_groups;
dst->ut.groups = groups;
dst->nt_user_token = nt_token;
return True;
}
/***************************************************************************
Purely internal function for make_server_info_info3
Fill the sam account from getpwnam
***************************************************************************/
static NTSTATUS fill_sam_account(TALLOC_CTX *mem_ctx,
const char *domain,
const char *username,
char **found_username,
uid_t *uid, gid_t *gid,
struct samu *account,
BOOL *username_was_mapped)
{
NTSTATUS nt_status;
fstring dom_user, lower_username;
fstring real_username;
struct passwd *passwd;
fstrcpy( lower_username, username );
strlower_m( lower_username );
fstr_sprintf(dom_user, "%s%c%s", domain, *lp_winbind_separator(),
lower_username);
/* Get the passwd struct. Try to create the account is necessary. */
*username_was_mapped = map_username( dom_user );
if ( !(passwd = smb_getpwnam( NULL, dom_user, real_username, True )) )
return NT_STATUS_NO_SUCH_USER;
*uid = passwd->pw_uid;
*gid = passwd->pw_gid;
/* This is pointless -- there is no suport for differing
unix and windows names. Make sure to always store the
one we actually looked up and succeeded. Have I mentioned
why I hate the 'winbind use default domain' parameter?
--jerry */
*found_username = talloc_strdup( mem_ctx, real_username );
DEBUG(5,("fill_sam_account: located username was [%s]\n", *found_username));
nt_status = samu_set_unix( account, passwd );
TALLOC_FREE(passwd);
return nt_status;
}
/****************************************************************************
Wrapper to allow the getpwnam() call to strip the domain name and
try again in case a local UNIX user is already there. Also run through
the username if we fallback to the username only.
****************************************************************************/
struct passwd *smb_getpwnam( TALLOC_CTX *mem_ctx, char *domuser,
fstring save_username, BOOL create )
{
struct passwd *pw = NULL;
char *p;
fstring username;
/* we only save a copy of the username it has been mangled
by winbindd use default domain */
save_username[0] = '\0';
/* don't call map_username() here since it has to be done higher
up the stack so we don't call it mutliple times */
fstrcpy( username, domuser );
p = strchr_m( username, *lp_winbind_separator() );
/* code for a DOMAIN\user string */
if ( p ) {
fstring strip_username;
pw = Get_Pwnam_alloc( mem_ctx, domuser );
if ( pw ) {
/* make sure we get the case of the username correct */
/* work around 'winbind use default domain = yes' */
if ( !strchr_m( pw->pw_name, *lp_winbind_separator() ) ) {
char *domain;
/* split the domain and username into 2 strings */
*p = '\0';
domain = username;
fstr_sprintf(save_username, "%s%c%s", domain, *lp_winbind_separator(), pw->pw_name);
}
else
fstrcpy( save_username, pw->pw_name );
/* whew -- done! */
return pw;
}
/* setup for lookup of just the username */
/* remember that p and username are overlapping memory */
p++;
fstrcpy( strip_username, p );
fstrcpy( username, strip_username );
}
/* just lookup a plain username */
pw = Get_Pwnam_alloc(mem_ctx, username);
/* Create local user if requested but only if winbindd
is not running. We need to protect against cases
where winbindd is failing and then prematurely
creating users in /etc/passwd */
if ( !pw && create && !winbind_ping() ) {
/* Don't add a machine account. */
if (username[strlen(username)-1] == '$')
return NULL;
smb_create_user(NULL, username, NULL);
pw = Get_Pwnam_alloc(mem_ctx, username);
}
/* one last check for a valid passwd struct */
if ( pw )
fstrcpy( save_username, pw->pw_name );
return pw;
}
/***************************************************************************
Make a server_info struct from the info3 returned by a domain logon
***************************************************************************/
NTSTATUS make_server_info_info3(TALLOC_CTX *mem_ctx,
const char *sent_nt_username,
const char *domain,
auth_serversupplied_info **server_info,
NET_USER_INFO_3 *info3)
{
static const char zeros[16] = { 0, };
NTSTATUS nt_status = NT_STATUS_OK;
char *found_username;
const char *nt_domain;
const char *nt_username;
struct samu *sam_account = NULL;
DOM_SID user_sid;
DOM_SID group_sid;
BOOL username_was_mapped;
uid_t uid;
gid_t gid;
size_t i;
auth_serversupplied_info *result;
/*
Here is where we should check the list of
trusted domains, and verify that the SID
matches.
*/
sid_copy(&user_sid, &info3->dom_sid.sid);
if (!sid_append_rid(&user_sid, info3->user_rid)) {
return NT_STATUS_INVALID_PARAMETER;
}
sid_copy(&group_sid, &info3->dom_sid.sid);
if (!sid_append_rid(&group_sid, info3->group_rid)) {
return NT_STATUS_INVALID_PARAMETER;
}
if (!(nt_username = unistr2_tdup(mem_ctx, &(info3->uni_user_name)))) {
/* If the server didn't give us one, just use the one we sent
* them */
nt_username = sent_nt_username;
}
if (!(nt_domain = unistr2_tdup(mem_ctx, &(info3->uni_logon_dom)))) {
/* If the server didn't give us one, just use the one we sent
* them */
nt_domain = domain;
}
/* try to fill the SAM account.. If getpwnam() fails, then try the
add user script (2.2.x behavior).
We use the _unmapped_ username here in an attempt to provide
consistent username mapping behavior between kerberos and NTLM[SSP]
authentication in domain mode security. I.E. Username mapping
should be applied to the fully qualified username
(e.g. DOMAIN\user) and not just the login name. Yes this means we
called map_username() unnecessarily in make_user_info_map() but
that is how the current code is designed. Making the change here
is the least disruptive place. -- jerry */
if ( !(sam_account = samu_new( NULL )) ) {
return NT_STATUS_NO_MEMORY;
}
/* this call will try to create the user if necessary */
nt_status = fill_sam_account(mem_ctx, nt_domain, sent_nt_username,
&found_username, &uid, &gid, sam_account,
&username_was_mapped);
/* if we still don't have a valid unix account check for
'map to guest = bad uid' */
if (!NT_STATUS_IS_OK(nt_status)) {
TALLOC_FREE( sam_account );
if ( lp_map_to_guest() == MAP_TO_GUEST_ON_BAD_UID ) {
make_server_info_guest(server_info);
return NT_STATUS_OK;
}
return nt_status;
}
if (!pdb_set_nt_username(sam_account, nt_username, PDB_CHANGED)) {
TALLOC_FREE(sam_account);
return NT_STATUS_NO_MEMORY;
}
if (!pdb_set_username(sam_account, nt_username, PDB_CHANGED)) {
TALLOC_FREE(sam_account);
return NT_STATUS_NO_MEMORY;
}
if (!pdb_set_domain(sam_account, nt_domain, PDB_CHANGED)) {
TALLOC_FREE(sam_account);
return NT_STATUS_NO_MEMORY;
}
if (!pdb_set_user_sid(sam_account, &user_sid, PDB_CHANGED)) {
TALLOC_FREE(sam_account);
return NT_STATUS_UNSUCCESSFUL;
}
if (!pdb_set_group_sid(sam_account, &group_sid, PDB_CHANGED)) {
TALLOC_FREE(sam_account);
return NT_STATUS_UNSUCCESSFUL;
}
if (!pdb_set_fullname(sam_account,
unistr2_static(&(info3->uni_full_name)),
PDB_CHANGED)) {
TALLOC_FREE(sam_account);
return NT_STATUS_NO_MEMORY;
}
if (!pdb_set_logon_script(sam_account,
unistr2_static(&(info3->uni_logon_script)),
PDB_CHANGED)) {
TALLOC_FREE(sam_account);
return NT_STATUS_NO_MEMORY;
}
if (!pdb_set_profile_path(sam_account,
unistr2_static(&(info3->uni_profile_path)),
PDB_CHANGED)) {
TALLOC_FREE(sam_account);
return NT_STATUS_NO_MEMORY;
}
if (!pdb_set_homedir(sam_account,
unistr2_static(&(info3->uni_home_dir)),
PDB_CHANGED)) {
TALLOC_FREE(sam_account);
return NT_STATUS_NO_MEMORY;
}
if (!pdb_set_dir_drive(sam_account,
unistr2_static(&(info3->uni_dir_drive)),
PDB_CHANGED)) {
TALLOC_FREE(sam_account);
return NT_STATUS_NO_MEMORY;
}
if (!pdb_set_acct_ctrl(sam_account, info3->acct_flags, PDB_CHANGED)) {
TALLOC_FREE(sam_account);
return NT_STATUS_NO_MEMORY;
}
if (!pdb_set_pass_last_set_time(
sam_account,
nt_time_to_unix(info3->pass_last_set_time),
PDB_CHANGED)) {
TALLOC_FREE(sam_account);
return NT_STATUS_NO_MEMORY;
}
if (!pdb_set_pass_can_change_time(
sam_account,
nt_time_to_unix(info3->pass_can_change_time),
PDB_CHANGED)) {
TALLOC_FREE(sam_account);
return NT_STATUS_NO_MEMORY;
}
if (!pdb_set_pass_must_change_time(
sam_account,
nt_time_to_unix(info3->pass_must_change_time),
PDB_CHANGED)) {
TALLOC_FREE(sam_account);
return NT_STATUS_NO_MEMORY;
}
result = make_server_info(NULL);
if (result == NULL) {
DEBUG(4, ("make_server_info failed!\n"));
TALLOC_FREE(sam_account);
return NT_STATUS_NO_MEMORY;
}
/* save this here to _net_sam_logon() doesn't fail (it assumes a
valid struct samu) */
result->sam_account = sam_account;
result->unix_name = talloc_strdup(result, found_username);
/* Fill in the unix info we found on the way */
result->uid = uid;
result->gid = gid;
/* Create a 'combined' list of all SIDs we might want in the SD */
result->num_sids = 0;
result->sids = NULL;
/* and create (by appending rids) the 'domain' sids */
for (i = 0; i < info3->num_groups2; i++) {
DOM_SID sid;
if (!sid_compose(&sid, &info3->dom_sid.sid,
info3->gids[i].g_rid)) {
DEBUG(3,("could not append additional group rid "
"0x%x\n", info3->gids[i].g_rid));
TALLOC_FREE(result);
return NT_STATUS_INVALID_PARAMETER;
}
if (!add_sid_to_array(result, &sid, &result->sids,
&result->num_sids)) {
TALLOC_FREE(result);
return NT_STATUS_NO_MEMORY;
}
}
/* Copy 'other' sids. We need to do sid filtering here to
prevent possible elevation of privileges. See:
http://www.microsoft.com/windows2000/techinfo/administration/security/sidfilter.asp
*/
for (i = 0; i < info3->num_other_sids; i++) {
if (!add_sid_to_array(result, &info3->other_sids[i].sid,
&result->sids,
&result->num_sids)) {
TALLOC_FREE(result);
return NT_STATUS_NO_MEMORY;
}
}
result->login_server = unistr2_tdup(result,
&(info3->uni_logon_srv));
/* ensure we are never given NULL session keys */
if (memcmp(info3->user_sess_key, zeros, sizeof(zeros)) == 0) {
result->user_session_key = data_blob(NULL, 0);
} else {
result->user_session_key = data_blob_talloc(
result, info3->user_sess_key,
sizeof(info3->user_sess_key));
}
if (memcmp(info3->lm_sess_key, zeros, 8) == 0) {
result->lm_session_key = data_blob(NULL, 0);
} else {
result->lm_session_key = data_blob_talloc(
result, info3->lm_sess_key,
sizeof(info3->lm_sess_key));
}
result->was_mapped = username_was_mapped;
*server_info = result;
return NT_STATUS_OK;
}
/***************************************************************************
Free a user_info struct
***************************************************************************/
void free_user_info(auth_usersupplied_info **user_info)
{
DEBUG(5,("attempting to free (and zero) a user_info structure\n"));
if (*user_info != NULL) {
if ((*user_info)->smb_name) {
DEBUG(10,("structure was created for %s\n",
(*user_info)->smb_name));
}
SAFE_FREE((*user_info)->smb_name);
SAFE_FREE((*user_info)->internal_username);
SAFE_FREE((*user_info)->client_domain);
SAFE_FREE((*user_info)->domain);
SAFE_FREE((*user_info)->wksta_name);
data_blob_free(&(*user_info)->lm_resp);
data_blob_free(&(*user_info)->nt_resp);
data_blob_clear_free(&(*user_info)->lm_interactive_pwd);
data_blob_clear_free(&(*user_info)->nt_interactive_pwd);
data_blob_clear_free(&(*user_info)->plaintext_password);
ZERO_STRUCT(**user_info);
}
SAFE_FREE(*user_info);
}
/***************************************************************************
Make an auth_methods struct
***************************************************************************/
BOOL make_auth_methods(struct auth_context *auth_context, auth_methods **auth_method)
{
if (!auth_context) {
smb_panic("no auth_context supplied to "
"make_auth_methods()!\n");
}
if (!auth_method) {
smb_panic("make_auth_methods: pointer to auth_method pointer "
"is NULL!\n");
}
*auth_method = TALLOC_P(auth_context->mem_ctx, auth_methods);
if (!*auth_method) {
DEBUG(0,("make_auth_method: malloc failed!\n"));
return False;
}
ZERO_STRUCTP(*auth_method);
return True;
}
/****************************************************************************
Duplicate a SID token.
****************************************************************************/
NT_USER_TOKEN *dup_nt_token(TALLOC_CTX *mem_ctx, const NT_USER_TOKEN *ptoken)
{
NT_USER_TOKEN *token;
if (!ptoken)
return NULL;
token = TALLOC_P(mem_ctx, NT_USER_TOKEN);
if (token == NULL) {
DEBUG(0, ("talloc failed\n"));
return NULL;
}
ZERO_STRUCTP(token);
if (ptoken->user_sids && ptoken->num_sids) {
token->user_sids = (DOM_SID *)TALLOC_MEMDUP(
token, ptoken->user_sids, sizeof(DOM_SID) * ptoken->num_sids );
if (token->user_sids == NULL) {
DEBUG(0, ("TALLOC_MEMDUP failed\n"));
TALLOC_FREE(token);
return NULL;
}
token->num_sids = ptoken->num_sids;
}
/* copy the privileges; don't consider failure to be critical here */
if ( !se_priv_copy( &token->privileges, &ptoken->privileges ) ) {
DEBUG(0,("dup_nt_token: Failure to copy SE_PRIV!. "
"Continuing with 0 privileges assigned.\n"));
}
return token;
}
/****************************************************************************
Check for a SID in an NT_USER_TOKEN
****************************************************************************/
BOOL nt_token_check_sid ( const DOM_SID *sid, const NT_USER_TOKEN *token )
{
int i;
if ( !sid || !token )
return False;
for ( i=0; i<token->num_sids; i++ ) {
if ( sid_equal( sid, &token->user_sids[i] ) )
return True;
}
return False;
}
BOOL nt_token_check_domain_rid( NT_USER_TOKEN *token, uint32 rid )
{
DOM_SID domain_sid;
/* if we are a domain member, the get the domain SID, else for
a DC or standalone server, use our own SID */
if ( lp_server_role() == ROLE_DOMAIN_MEMBER ) {
if ( !secrets_fetch_domain_sid( lp_workgroup(),
&domain_sid ) ) {
DEBUG(1,("nt_token_check_domain_rid: Cannot lookup "
"SID for domain [%s]\n", lp_workgroup()));
return False;
}
}
else
sid_copy( &domain_sid, get_global_sam_sid() );
sid_append_rid( &domain_sid, rid );
return nt_token_check_sid( &domain_sid, token );\
}
/**
* Verify whether or not given domain is trusted.
*
* @param domain_name name of the domain to be verified
* @return true if domain is one of the trusted once or
* false if otherwise
**/
BOOL is_trusted_domain(const char* dom_name)
{
DOM_SID trustdom_sid;
BOOL ret;
/* no trusted domains for a standalone server */
if ( lp_server_role() == ROLE_STANDALONE )
return False;
/* if we are a DC, then check for a direct trust relationships */
if ( IS_DC ) {
become_root();
DEBUG (5,("is_trusted_domain: Checking for domain trust with "
"[%s]\n", dom_name ));
ret = secrets_fetch_trusted_domain_password(dom_name, NULL,
NULL, NULL);
unbecome_root();
if (ret)
return True;
}
else {
NSS_STATUS result;
/* If winbind is around, ask it */
result = wb_is_trusted_domain(dom_name);
if (result == NSS_STATUS_SUCCESS) {
return True;
}
if (result == NSS_STATUS_NOTFOUND) {
/* winbind could not find the domain */
return False;
}
/* The only other possible result is that winbind is not up
and running. We need to update the trustdom_cache
ourselves */
#ifndef AVM_SMALLER
update_trustdom_cache();
#endif
}
/* now the trustdom cache should be available a DC could still
* have a transitive trust so fall back to the cache of trusted
* domains (like a domain member would use */
#ifndef AVM_SMALLER
if ( trustdom_cache_fetch(dom_name, &trustdom_sid) ) {
return True;
}
#endif
return False;
}
|
sbilly/BAS | Engine/projectbackup.cpp | #include "projectbackup.h"
#include "every_cpp.h"
#include <QDateTime>
#include <QDir>
namespace BrowserAutomationStudioFramework
{
ProjectBackup::ProjectBackup(QObject *parent) : QObject(parent)
{
milliseconds = 5 * 60000;
CodeEditor = 0;
Timer = 0;
DestFolder = "../../projectbackups";
}
void ProjectBackup::SetCodeEditor(ICodeEditor * CodeEditor)
{
this->CodeEditor = CodeEditor;
}
void ProjectBackup::SetPeriod(int milliseconds)
{
this->milliseconds = milliseconds;
}
void ProjectBackup::SetDestFolder(const QString& DestFolder)
{
this->DestFolder = DestFolder;
}
void ProjectBackup::Start()
{
Timer = new QTimer(this);
Timer->setInterval(milliseconds);
Timer->setSingleShot(false);
connect(Timer,SIGNAL(timeout()),this,SLOT(DoBackups()));
Timer->start();
}
void ProjectBackup::DoBackups()
{
if(!CodeEditor)
{
return;
}
QString Code = CodeEditor->GetText();
if(LastProject == Code)
return;
QDateTime CurrentDateTime = QDateTime::currentDateTime();
QDir dir(DestFolder + QDir::separator() + CurrentDateTime.toString("yyyy.MM.dd"));
if(!dir.exists())
dir.mkpath(".");
QString path = dir.absoluteFilePath(QString("%1.xml").arg(CurrentDateTime.toString("hh.mm.ss")));
QFile file(path);
if(!file.open(QIODevice::WriteOnly))
return;
file.write(Code.toUtf8());
file.close();
LastProject = Code;
}
}
|
Abhisheknishant/javaclay | src/main/java/es/bsc/dataclay/util/prefetchingspec/analysisscopes/BranchAnalysisScope.java |
/**
* @file BranchAnalysisScope.java
*
* @date Dec 11, 2015
*/
package es.bsc.dataclay.util.prefetchingspec.analysisscopes;
/**
* This class represents a branch analysis scope (e.g. an "if" or an "else" scope). Its parent is ALWAYS of type
* MultiBranchAnalysisScope.
*
*
*/
public class BranchAnalysisScope extends AnalysisScope {
/**
* Creates a new BranchAnalysisScope object with the specified parameters.
*
* @param startInstrIndex
* the index of the start instruction of the new scope
* @param endInstrIndex
* the index of the end instruction of the new scope
* @param parent
* the parent of the new scope
*/
public BranchAnalysisScope(final int startInstrIndex, final int endInstrIndex, final MultiBranchAnalysisScope parent) {
super(startInstrIndex, endInstrIndex, parent);
}
}
|
happibum/calcium | testcases/20.js | // context-sensitively analyze all functions
function id(x) { return x; }
var x = id(1);
var y = id(true);
function foo(y) { return y; }
var a = foo(1);
var b = foo(true);
|
rhickman/cellbots3 | RobotsideApp-master/common/src/androidTest/java/ai/ticktock/common/PointOfInterestValidatorTest.java | <reponame>rhickman/cellbots3
package ai.cellbots.common;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import java.util.Random;
import java.util.UUID;
import ai.cellbots.common.data.PointOfInterest;
import ai.cellbots.common.data.PointOfInterestVars;
import ai.cellbots.common.data.Transform;
import ai.cellbots.common.utils.PointOfInterestValidator;
public class PointOfInterestValidatorTest {
private PointOfInterest poi;
@Before
public void setUp() {
poi = new PointOfInterest();
poi.name = "Unused Name";
poi.type = "point_of_interest";
poi.uuid = UUID.randomUUID().toString();
poi.variables = new PointOfInterestVars();
// Range for each transform value: -10000.0 to 10000.0 (in meters) for testing
double min = -10000.0;
double max = 10000.0;
poi.variables.location = new Transform(
randDouble(min, max),
randDouble(min, max),
randDouble(min, max),
randDouble(min, max),
randDouble(min, max),
randDouble(min, max),
randDouble(min, max),
randDouble(0, Double.MAX_VALUE)
);
poi.variables.name = "My Real POI Name";
}
@After
public void tearDown() {
poi = null;
}
@Test
public void shouldReturnTrueIfAllFieldsAreValid() {
assertTrue();
}
/**
* This name is a duplicate of PointOfInterest.variables.name and unused.
* Should be true no matter what.
*/
@Test
public void shouldReturnTrueIfNameIsNull() {
poi.name = null;
assertTrue();
}
/**
* This name is a duplicate of PointOfInterest.variables.name and unused.
* Should be true no matter what.
*/
@Test
public void shouldReturnTrueIfNameIsEmpty() {
poi.name = "";
assertTrue();
}
@Test
public void shouldReturnFalseForNullPOI() {
poi = null;
assertFalse();
}
@Test
public void shouldReturnFalseIfTypeIsNotPointOfInterest() {
poi.type = "some type";
assertFalse();
}
@Test
public void shouldReturnFalseIfTypeIsNull() {
poi.type = null;
assertFalse();
}
@Test
public void shouldReturnFalseIfTypeIsEmpty() {
poi.type = "";
assertFalse();
}
@Test
public void shouldReturnFalseIfUUIDIsNull() {
poi.uuid = null;
assertFalse();
}
@Test
public void shouldReturnFalseIfUUIDIsEmpty() {
poi.uuid = "";
assertFalse();
}
@Test
public void shouldReturnFalseIfUUIDIsInvalid() {
poi.uuid = "some string but not a uuid";
assertFalse();
}
@Test
public void shouldReturnFalseIfVariablesIsNull() {
poi.variables = null;
assertFalse();
}
@Test
public void shouldReturnFalseIfVariablesLocationIsNull() {
poi.variables.location = null;
assertFalse();
}
@Test
public void shouldReturnFalseIfVariablesNameIsNull() {
poi.variables.name = null;
assertFalse();
}
@Test
public void shouldReturnFalseIfVariablesNameIsEmpty() {
poi.variables.name = "";
assertFalse();
}
private void assertTrue() {
Assert.assertEquals(true, PointOfInterestValidator.areAllFieldsValid(poi));
}
private void assertFalse() {
Assert.assertEquals(false, PointOfInterestValidator.areAllFieldsValid(poi));
}
private double randDouble(double min, double max) {
Random random = new Random();
return min + (max - min) * random.nextDouble();
}
}
|
cndavy/docker-office | custom_apps/maps/l10n/uk.js | <reponame>cndavy/docker-office
OC.L10N.register(
"maps",
{
"Maps" : "Мапи",
"Personal" : "Особисте",
"Not grouped" : "Не згруповані",
"Home" : "Домашній",
"Work" : "Робочий",
"All contacts" : "Всі контакти",
"Rename" : "Перейменувати",
"Export" : "Експорт",
"Delete" : "Видалити",
"Phone" : "Телефон",
"Device" : "Пристрій",
"Date" : "Date",
"Name" : "Ім'я",
"Category" : "Категорія",
"Comment" : "Коментар",
"Move" : "Перемістити",
"right" : "праворуч",
"left" : "ліворуч",
"Destination" : "Destination",
"min" : "хв",
"Cinema" : "Кінотеатр",
"Dentist" : "Стоматолог",
"Add to favorites" : "Додати до обраного",
"Open" : "Відкрити",
"Closed" : "Закрите",
"File" : "Файл",
"Link" : "Посилання",
"Description" : "Опис",
"Your photos" : "Ваші фотографії",
"Sort by name" : "Впорядкувати за ім’ям",
"Sort by date" : "Сортувати за датою",
"Settings" : "Налаштування"
},
"nplurals=4; plural=(n % 1 == 0 && n % 10 == 1 && n % 100 != 11 ? 0 : n % 1 == 0 && n % 10 >= 2 && n % 10 <= 4 && (n % 100 < 12 || n % 100 > 14) ? 1 : n % 1 == 0 && (n % 10 ==0 || (n % 10 >=5 && n % 10 <=9) || (n % 100 >=11 && n % 100 <=14 )) ? 2: 3);");
|
pebble2015/cpoi | src/org/apache/poi/sl/draw/DrawAutoShape.cpp | // Generated from /POI/java/org/apache/poi/sl/draw/DrawAutoShape.java
#include <org/apache/poi/sl/draw/DrawAutoShape.hpp>
#include <org/apache/poi/sl/usermodel/AutoShape.hpp>
poi::sl::draw::DrawAutoShape::DrawAutoShape(const ::default_init_tag&)
: super(*static_cast< ::default_init_tag* >(0))
{
clinit();
}
poi::sl::draw::DrawAutoShape::DrawAutoShape(::poi::sl::usermodel::AutoShape* shape)
: DrawAutoShape(*static_cast< ::default_init_tag* >(0))
{
ctor(shape);
}
void poi::sl::draw::DrawAutoShape::ctor(::poi::sl::usermodel::AutoShape* shape)
{
super::ctor(shape);
}
extern java::lang::Class *class_(const char16_t *c, int n);
java::lang::Class* poi::sl::draw::DrawAutoShape::class_()
{
static ::java::lang::Class* c = ::class_(u"org.apache.poi.sl.draw.DrawAutoShape", 36);
return c;
}
java::lang::Class* poi::sl::draw::DrawAutoShape::getClass0()
{
return class_();
}
|
arthurvenicio/blip-desk-scheduler | src/pages/Home/components/ListWeek/index.js | <gh_stars>1-10
import ListWeek from './ListWeek';
export default ListWeek;
|
uk-gov-mirror/hmcts.bulk-scan-orchestrator | src/main/java/uk/gov/hmcts/reform/bulkscan/orchestrator/client/caseupdate/model/request/ExceptionRecord.java | package uk.gov.hmcts.reform.bulkscan.orchestrator.client.caseupdate.model.request;
import com.fasterxml.jackson.annotation.JsonProperty;
import uk.gov.hmcts.reform.bulkscan.orchestrator.client.model.request.OcrDataField;
import uk.gov.hmcts.reform.bulkscan.orchestrator.client.model.request.ScannedDocument;
import uk.gov.hmcts.reform.bulkscan.orchestrator.services.servicebus.domains.envelopes.model.Classification;
import java.time.LocalDateTime;
import java.util.List;
public class ExceptionRecord {
public final String id;
@JsonProperty("case_type_id")
public final String caseTypeId;
@JsonProperty("po_box")
public final String poBox;
@JsonProperty("po_box_jurisdiction")
public final String poBoxJurisdiction;
@JsonProperty("journey_classification")
public final Classification journeyClassification;
@JsonProperty("form_type")
public final String formType;
@JsonProperty("delivery_date")
public final LocalDateTime deliveryDate;
@JsonProperty("opening_date")
public final LocalDateTime openingDate;
@JsonProperty("scanned_documents")
public final List<ScannedDocument> scannedDocuments;
@JsonProperty("ocr_data_fields")
public final List<OcrDataField> ocrDataFields;
public ExceptionRecord(
String id,
String caseTypeId,
String poBox,
String poBoxJurisdiction,
Classification journeyClassification,
String formType,
LocalDateTime deliveryDate,
LocalDateTime openingDate,
List<ScannedDocument> scannedDocuments,
List<OcrDataField> ocrDataFields
) {
this.id = id;
this.caseTypeId = caseTypeId;
this.poBox = poBox;
this.poBoxJurisdiction = poBoxJurisdiction;
this.journeyClassification = journeyClassification;
this.formType = formType;
this.deliveryDate = deliveryDate;
this.openingDate = openingDate;
this.scannedDocuments = scannedDocuments;
this.ocrDataFields = ocrDataFields;
}
}
|
jochenater/catboost | library/cpp/yt/assert/assert.cpp | #include "assert.h"
#include <util/system/yassert.h>
#include <util/system/compiler.h>
namespace NYT::NDetail {
////////////////////////////////////////////////////////////////////////////////
Y_WEAK void AssertTrapImpl(
TStringBuf trapType,
TStringBuf expr,
TStringBuf file,
int line,
TStringBuf function)
{
// Map to Arcadia assert, poorly...
::NPrivate::Panic(
::NPrivate::TStaticBuf(file.data(), file.length()),
line,
function.data(),
expr.data(),
"%s",
trapType.data());
}
////////////////////////////////////////////////////////////////////////////////
} // namespace NYT::NDetail
|
hfp/plaidml | pmlc/dialect/comp/analysis/mem_sync_tracker.h | // Copyright 2020 Intel Corporation
#pragma once
#include "mlir/Support/LLVM.h"
#include "pmlc/dialect/comp/ir/dialect.h"
namespace pmlc::dialect::comp {
/// Class tracking status of synchronization between memories.
/// Two memories are in sync when they hold the same content.
class MemorySynchronizationTracker {
public:
/// Returns whether two memories hold the same content.
bool areInSync(mlir::Value a, mlir::Value b);
/// Returns whether specified memory is tracked.
bool isTracked(mlir::Value mem);
/// Modifies synchronization status by effects of "operation".
/// Returns true if tracked connections changed.
bool handleOperation(mlir::Operation *operation);
bool handleTransferOp(MemoryTransferOpInterface op);
bool handleAllocOp(Alloc op);
bool handleGeneralOp(mlir::Operation *op);
bool syncMemory(mlir::Value src, mlir::Value dst);
bool desyncMemory(mlir::Value mem);
private:
mlir::DenseMap<mlir::Value, mlir::DenseSet<mlir::Value>> inSyncMap;
};
} // namespace pmlc::dialect::comp
|
vipulchodankar/gec-computer-engineering | second-year/semester-3/DSA/experiment-3/Hashing.c | #include <stdio.h>
#include <string.h>
#include <stdlib.h>
struct bike
{
int pid;
char model[20];
float price;
};
struct hashtable
{
struct bike b;
int status;
};
int MAX;
int hash(char key[])
{
int sum=0,i;
for(i=0;i<strlen(key);i++)
sum+=(int)key[i];
return (sum%MAX);
}
void insert_hashtable(struct bike bh,struct hashtable ht[])
{
int i, location, h;
char key [20];
strcpy( key,bh.model );
h = hash( key );
location = h;
for ( i = 1; i < MAX ; i++ )
{
if(ht[location].status==-1 || ht[location].status==1)
{
ht[location].b=bh;
ht[location].status=0;
break;
}
location=(h+i)%MAX;
}
if(i==MAX)
printf("The hash table is full.\n");
}
void display_hashtable(struct hashtable ht[])
{
int i;
printf("\nBike ID\t\tModel\tPrice\tLocation\t Status\n");
for( i=0;i<MAX;i++)
{
if(ht[i].status==0)
{
printf("%d\t%s\t\t%f\t%d\t%s\n",ht[i].b.pid,ht[i].b.model,ht[i].b.price,i,"OCCUPIED");
}
else if(ht[i].status==-1)
{
printf("\t\t\t\t\t%d\t%s\n",i,"EMPTY");
}
else if(ht[i].status==1)
printf("\t\t\t\t\t%d\t %s\n",i,"DELTED");
}
}
int search_table(char m[],struct hashtable ht[])
{
int i,loc,h;
h=hash(m);
loc=h;
for(i=1;i<MAX;i++)
{
if(ht[loc].status==0&&strcmp(ht[loc].b.model,m)==0)
return loc;
else if(ht[loc].status==-1)
return -1;
loc=(h+i)%MAX;
}
}
int delete_table(char m[],struct hashtable ht[])
{
int loc=search_table(m,ht);
printf("***%d***\n",loc);
if(loc==-1)
return -1;
else
ht[loc].status=1;
}
int main()
{
int i=-1, n, ch, opt;
char model[20];
struct hashtable *ht;
ht=(struct hashtable*)malloc(MAX*sizeof(struct hashtable));
struct bike bh;
for( i=0;i<MAX;i++)
ht[i].status=-1;
int nb;
char m[20];
char m1[20];
while(1){
printf("\n1. Insert\n2. Display\n3.Search\n4. Delete\n5. Exit\nEnter your choice: ");
scanf("%d",&opt);
switch(opt)
{
case 1:
printf("\nenter no of bikes\n");
scanf("%d",&nb);
for(i=0;i<nb;i++)
{
printf("Enter details of bike %d\n",(i+1));
printf("Enter id ,model & price: \n");
scanf("%d %s %f",&bh.pid, (bh.model), &bh.price);
insert_hashtable(bh, ht);
}
break;
case 2:
display_hashtable(ht);
break;
case 3:
printf("Enter the model to be searched\n");
scanf("%s",&m);
int f = search_table(m,ht);
if(f==-1)
printf("Bike not found.\n");
else
printf("Bike found at location %d\n",f);
break;
case 4:
printf("Enter the model to be deleted\n");
scanf("%s",&m1);
int d=delete_table(m1,ht);
if(d==-1)
printf("No such bike was found.\n");
else
printf("The Bike has been deleted.\n");
break;
case 5:
exit(1);
}
}
} |
csoap/csoap.github.io | sourceCode/dotNet4.6/vb/language/compiler/commandline/resource.h | <filename>sourceCode/dotNet4.6/vb/language/compiler/commandline/resource.h
//-------------------------------------------------------------------------------------------------
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// STRIDs should be defined in the following ranges:
//
// 1 - 100 - non localized STRID (main common compiler DLLs)
// 101 - 500 - non localized STRID (main specific compiler DLLs)
// 1000 - 1008 - localized STRID (intl common compiler DLLs)
// 1009 - 1022 - localized STRID (intl specific compiler DLLs)
// 1023 - 1030 - localized STRID (intl common compiler DLLs)
// 1031 - 1100 - localized STRID (intl specific compiler DLLs)
// 1101 - 1199 - localized STRID (intl common compiler DLLs)
// 1200 - 29999 - localized STRID (intl specific compiler DLLs)
//
//-------------------------------------------------------------------------------------------------
// Make sure to only use the ranges for the specific DLL's,
// not the ones in common.
#define IDS_HELP_COLUMN_SPACE 101 // Non-localized
#define IDS_FATALERROR 2001
#define IDS_ERROR 2002
#define IDS_WARNING 2003
#define IDS_ERR_INITERROR 2004
#define IDS_ERR_FILENOTFOUND 2005
#define IDS_ERR_NOMEMORY 2006
#define IDS_ERR_NORESPONSEFILE 2007
#define IDS_WRN_BADSWITCH 2009
#define IDS_ERR_NOSOURCES 2011
#define IDS_ERR_ARGUMENTREQUIRED 2013
#define IDS_ERR_DUPLICATERESPONSEFILE 2014
#define IDS_WRN_FILEALREADYINCLUDED 2015
#define IDS_ERR_LIBNOTFOUND 2016
#define IDS_ERR_CANTOPENFILEWRITE 2017
#define IDS_ERR_INVALIDSWITCHVALUE 2019
#define IDS_ERR_BINARYFILE 2020
#define IDS_ERR_BADCODEPAGE 2021
#define IDS_ERR_COMPILEFAILED 2022
#define IDS_ERR_SWITCHNEEDSBOOL 2024
#define IDS_ERR_INTLLIBNOTFOUND 2025
#define IDS_ERR_MAXIMUMERRORS 2026
#define IDS_ERR_ICONFILEANDWIN32RES 2029
#define IDS_WRN_RESERVEDREFERENCE 2030
#define IDS_WRN_NOCONFIGINRESPONSEFILE 2031
#define IDS_WRN_INVALIDWARNINGID 2032
#define IDS_ERR_WATSONSENDNOTOPTEDIN 2033
#define IDS_WRN_SWITCHNOBOOL 2034
#define IDS_ERR_NOSOURCESOUT 2035
#define IDS_ERR_NEEDMODULE 2036
#define IDS_ERR_INVALIDASSEMBLYNAME 2037
#define IDS_ERR_CONFLICTINGMANIFESTSWITCHES 2038
#define IDS_WRN_IGNOREMODULEMANIFEST 2039
#define IDS_ERR_NODEFAULTMANIFEST 2040
#define IDS_ERR_INVALIDSWITCHVALUE1 2041
#define IDS_ERR_VBCORENETMODULECONFLICT 2042
#define IDS_BANNER1 10001
// Don't use see bug 60618
// #define IDS_BANNER1PART2 10002
#define IDS_BANNER2 10003
#define IDS_HELP_BANNER 10004
#define IDS_GROUP_OUTPUT_FILE 13005
#define IDS_GROUP_INPUT_FILES 13006
#define IDS_GROUP_RESOURCES 13007
#define IDS_GROUP_CODEGEN 13008
#define IDS_GROUP_WARNING 13009
#define IDS_GROUP_LANGUAGE 13010
#define IDS_GROUP_MISC 13011
#define IDS_GROUP_ADVANCED 13012
#define IDS_GROUP_DEBUG 13013
#define IDS_ARG_FILE 13100
#define IDS_ARG_FILELIST 13101
#define IDS_ARG_NUMBER 13102
#define IDS_ARG_STRING 13103
#define IDS_ARG_WILDCARD 13104
#define IDS_ARG_SYMLIST 13105
#define IDS_ARG_PATHLIST 13106
#define IDS_ARG_RESINFO 13107
#define IDS_ARG_CLASS 13108
#define IDS_ARG_IMPORTLIST 13109
#define IDS_ARG_PATH 13110
#define IDS_NUMBERLIST 13111
#define IDS_ARG_ASSEMBLY_NAME 13112
#define IDS_ARG_VERSION 13113
#define IDS_HELP_SHORTFORM 13200
#define IDS_HELP_OUT 13302
#define IDS_HELP_TARGET_EXE 13303
#define IDS_HELP_TARGET_WIN 13304
#define IDS_HELP_TARGET_LIB 13305
#define IDS_HELP_TARGET_MOD 13306
#define IDS_HELP_TARGET_APPCTR 13307
#define IDS_HELP_TARGET_WINMDOBJ 13308
#define IDS_HELP_RECURSE 13310
#define IDS_HELP_MAIN 13311
#define IDS_HELP_REFERENCE 13312
#define IDS_HELP_RESOURCE 13314
#define IDS_HELP_RESINFO 13315
#define IDS_HELP_LINKRESOURCE 13316
#define IDS_HELP_WIN32ICON 13317
#define IDS_HELP_WIN32RESOURCE 13318
#define IDS_HELP_DEBUG 13320
#define IDS_HELP_OPTIMIZE 13321
#define IDS_HELP_LANGUAGE 13323
#define IDS_HELP_ROOTNAMESPACE 13324
#define IDS_HELP_IMPORTS 13325
#define IDS_HELP_DEFINE 13326
#define IDS_HELP_REMOVEINT 13327
#define IDS_HELP_OPTCOMPARE_BIN 13328
#define IDS_HELP_OPTCOMPARE_TXT 13329
#define IDS_HELP_OPTEXPLICIT 13330
#define IDS_HELP_OPTSTRICT 13331
#define IDS_HELP_OPTINFER 13332
#define IDS_HELP_RESPONSE 13333
#define IDS_HELP_NOLOGO 13334
#define IDS_HELP_HELP 13335
#define IDS_HELP_BUGREPORT 13336
#define IDS_HELP_TIME 13337
#define IDS_HELP_VERBOSE 13338
#define IDS_HELP_BASEADDRESS 13340
// UNAVAILABLE 13341
#define IDS_HELP_LIBPATH 13342
#define IDS_HELP_KEYFILE 13343
#define IDS_HELP_KEYCONTAINER 13344
#define IDS_HELP_DEBUGFULL 13345
#define IDS_HELP_DEBUGPDBONLY 13346
#define IDS_HELP_NOWARN 13347
#define IDS_HELP_WARNASERROR 13348
#define IDS_HELP_DELAYSIGN 13349
#define IDS_HELP_ADDMODULE 13350
#define IDS_HELP_UTF8OUTPUT 13351
#define IDS_HELP_QUIET 13352
#define IDS_HELP_SDKPATH 13353
#define IDS_HELP_STARLITE 13354
#define IDS_HELP_DOC 13355
#define IDS_HELP_NOCONFIG 13356
#define IDS_HELP_CODEPAGE 13357
#define IDS_HELP_FILEALIGN 13358
#define IDS_HELP_DOC_TO_FILE 13359
#define IDS_HELP_PLATFORM 13360
#define IDS_HELP_ERRORREPORT 13361
// UNAVAILABLE 13362
#define IDS_HELP_NOSTDLIB 13363
#define IDS_HELP_NOWARNLIST 13364
#define IDS_HELP_WARNASERRORLIST 13365
#define IDS_HELP_OPTSTRICTCUST 13366
#define IDS_HELP_MODULEASSEMBLYNAME 13367
#define IDS_HELP_WIN32MANIFEST 13368
#define IDS_HELP_WIN32NOMANIFEST 13369
#define IDS_HELP_VBRUNTIME 13370
#define IDS_HELP_VBRUNTIME_FILE 13371
#define IDS_HELP_LANGVERSION 13372
#define IDS_HELP_LINKREFERENCE 13373
#define IDS_HELP_HIGHENTROPYVA 13374
#define IDS_HELP_SUBSYSTEMVERSION 13375
#define IDS_REPROTITLE 12000
#define IDS_REPROVER 12001
#define IDS_REPROOS 12002
#define IDS_REPROUSER 12003
#define IDS_REPROCOMMANDLINE 12004
#define IDS_REPROSOURCEFILE 12005
#define IDS_REPRODIAGS 12006
#define IDS_REPROISSUETYPE 12007
#define IDS_REPRODESCRIPTION 12008
#define IDS_REPROCORRECTBEHAVIOR 12009
#define IDS_REPROURTVER 12010
#define IDS_BUGREPORT1 12040
#define IDS_BUGREPORT2 12041
#define IDS_BUGREPORT3 12042
#define IDS_ENTERDESC 12050
#define IDS_ENTERCORRECT 12051
#define IDS_MSG_ADDSOURCEFILE 12052
#define IDS_MSG_ADDREFERENCE 12053
#define IDS_MSG_ADDRESOURCEFILE 12054
#define IDS_MSG_ADDIMPORT 12056
#define IDS_MSG_COMPILING 12057
#define IDS_MSG_COMPILE_OK 12058
#define IDS_MSG_COMPILE_BAD1 12059
#define IDS_MSG_COMPILE_BAD2 12060
#define IDS_MSG_ELAPSED_TIME 12061
#define IDS_MSG_COMPILE_WARN1 12062
#define IDS_MSG_COMPILE_WARN2 12063
#define IDS_MSG_COMPILE_WARN1BAD1 12064
#define IDS_MSG_COMPILE_WARN2BAD1 12065
#define IDS_MSG_COMPILE_WARN1BAD2 12066
#define IDS_MSG_COMPILE_WARN2BAD2 12067
#define IDS_MSG_ADDMODULE 12068
#define IDS_MSG_ADDLINKREFERENCE 12069
|
iceBear67/Krystalic | src/main/java/com/github/icebear67/craftpp/api/interfaces/IMachine.java | package com.github.icebear67.craftpp.api.interfaces;
import com.github.icebear67.craftpp.InteractType;
import com.github.icebear67.craftpp.machine.result.Result;
import org.bukkit.Location;
import org.bukkit.entity.Player;
import java.util.UUID;
public interface IMachine {
String getId();
Result onUpdate();
boolean onInteract(InteractType interactType, Player player, Location location);
UUID getUUID();
}
|
King-Maverick007/websites | git/smart-new/smart-mvc/src/main/java/com/smart/mvc/validator/annotation/ValidateParam.java | <reponame>King-Maverick007/websites
package com.smart.mvc.validator.annotation;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import com.smart.mvc.validator.Validator;
/**
* 自定义请求参数注解
*
* @author Joe
*/
@Target(ElementType.PARAMETER)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface ValidateParam {
/**
* 验证器
* @return
*/
Validator[] value() default {};
/**
* 参数的描述名称
* @return
*/
String name() default "";
}
|
CloudNativeDataPlane/cndp | lib/core/osal/cne_stdio.h | <reponame>CloudNativeDataPlane/cndp<filename>lib/core/osal/cne_stdio.h<gh_stars>0
/* SPDX-License-Identifier: BSD-3-Clause
* Copyright (c) <2019-2021> Intel Corporation.
*/
#ifndef __CNE_STDIO_H_
#define __CNE_STDIO_H_
// IWYU pragma: no_include <bits/termios-struct.h>
#include <termios.h>
#include <stdint.h> // for int16_t
#include <cne_atomic.h> // for atomic_exchange, atomic_int_least32_t, atomic...
#ifdef __cplusplus
extern "C" {
#endif
#include <cne_common.h>
#include <vt100_out.h>
/**
* @file
* CNE simple cursor and color support for VT100 using ANSI color escape codes.
*
*/
#include <string.h> // for strlen
#include <stdio.h> // for FILE
#include <stdarg.h> // for va_list
#include <unistd.h> // for write
#include <cne_system.h>
#include "cne_common.h" // for CNDP_API
/**
* A printf like routine to output to tty file descriptor.
*
* @param fmt
* The formatting string for a printf like API
*/
CNDP_API int cne_printf(const char *fmt, ...) __attribute__((format(printf, 1, 2)));
/**
* cursor position the text at the given location for r and c.
*
* @param r
* The row to place the text.
* @param c
* The column to place the text.
* @param fmt
* The cne_printf() like format string.
*/
CNDP_API int cne_printf_pos(int16_t r, int16_t c, const char *fmt, ...)
__attribute__((format(printf, 3, 0)));
/**
* Routine similar to fprintf() to output text to a file descriptor.
*
* @param f
* The file descriptor to output the text to.
* @param fmt
* The format string to output.
* @return
* The number of bytes written
*/
CNDP_API int cne_fprintf(FILE *f, const char *fmt, ...) __attribute__((format(printf, 2, 0)));
/**
* Format a string with color formatting and return the number of bytes
*
* @param buff
* The buffer to place the formatted string with color
* @param len
* The max length of the *buff* array
* @param fmt
* The formatting string to use with any arguments
* @return
* The number of bytes written into the *buff* array
*/
CNDP_API int cne_snprintf(char *buff, int len, const char *fmt, ...)
__attribute__((format(printf, 3, 4)));
/**
* Output a string at a given row/column using printf like formatting.
* Centering the text on the console display, using the *ncols* value
*
* @param r
* The row to start the print out of the string.
* @param ncols
* Number of columns on the line. Used to center the text on the line.
* @param fmt
* The formatting string to use to print the text data.
*/
CNDP_API int cne_cprintf(int16_t r, int16_t ncols, const char *fmt, ...)
__attribute__((format(printf, 3, 4)));
/**
* vsnprintf() like function using va_list pointer with color tags.
*
* @param buff
* The output buffer to place the text
* @param len
* The length of the buff array
* @param fmt
* The format string with color tags
* @param ap
* The va_list pointer to be used byt vsnprintf()
* @return
* The number of bytes in the buff array or -1 on error
*/
CNDP_API int cne_vsnprintf(char *buff, int len, const char *fmt, va_list ap)
__attribute__((format(printf, 3, 0)));
/**
* vprintf() like function using va_list pointer with color tags.
*
* @param fmt
* The format string with color tags
* @param ap
* The va_list pointer to be used
* @return
* number of bytes written to output or -1 on error
*/
CNDP_API int cne_vprintf(const char *fmt, va_list ap) __attribute__((format(printf, 1, 0)));
#ifdef __cplusplus
}
#endif
#endif /* __CNE_STDIO_H_ */
|
bessovistnyj/jvm-byte-code | Spring/IoC/src/test/java/ru/napadovskiu/storage/StorageTest.java | <reponame>bessovistnyj/jvm-byte-code
package ru.napadovskiu.storage;
import org.junit.Before;
import org.junit.Test;
import static org.junit.Assert.assertThat;
import org.springframework.context.ApplicationContext;
import static org.junit.Assert.assertEquals;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import ru.napadovskiu.models.User;
public class StorageTest {
private User firstUser;
private User secondUser;
@Before
public void initTest() {
this.firstUser = new User();
this.firstUser.setUserId(1);
this.firstUser.setUserName("first");
this.secondUser = new User();
this.secondUser.setUserId(2);
this.secondUser.setUserName("second");
}
@Test
public void whenAddUserMemoryStorage() {
ApplicationContext context = new ClassPathXmlApplicationContext("spring-context.xml");
Storage storage = context.getBean(MemoryStorage.class);
storage.add(this.firstUser);
storage.add(this.secondUser);
Integer userId = storage.get(secondUser.getUserId()).getUserId();
assertEquals(userId, this.secondUser.getUserId());
}
@Test
public void whenAddUserJdbcStorage() {
ApplicationContext context = new ClassPathXmlApplicationContext("spring-context.xml");
Storage storage = context.getBean(JdbcStorage.class);
storage.add(this.firstUser);
storage.add(this.secondUser);
Integer userId = storage.get(secondUser.getUserId()).getUserId();
assertEquals(userId, this.secondUser.getUserId());
}
}
|
aTechathon/atechathon.github.io | athonia/19/154386/197089.js |
init();
function init() {
tileX = 154386;
tileY = 197089;
msg.innerHTML += 'Hello, world! from ' + tileX + ' ' + tileY
geometry = new THREE.BoxGeometry( 100, 20, 150 );
material = new THREE.MeshNormalMaterial();
mesh = new THREE.Mesh( geometry, material );
placeTile( mesh, tileX, tileY );
} |
FrederikWR/course-02443-stochastic-virus-outbreak | code/world/tools.py |
from .regions import regions
def airline_connections(region):
"""Find indgoing and outgoing airline connections
Parameters
---------
region : Region object to check for ingoing and outgoing connections
Returns
-------
(outgoing, ingoing) route objects
"""
outgoing_routes = region.airlines
ingoing_routes = []
for other_region in regions.values():
if other_region == region: continue
for airline in other_region.airlines:
if airline.destination == region:
ingoing_routes.append(airline)
return (outgoing_routes, ingoing_routes)
|
Hrom131/terraform-provider-tokend | vendor/gitlab.com/tokend/regources/v2/account.go | package regources
// AccountResponse - response on /account request
type AccountResponse struct {
Data Account `json:"data"`
Included Included `json:"included"`
}
// Account - Resource object representing AccountEntry
type Account struct {
Key
Relationships AccountRelationships `json:"relationships"`
}
type AccountRelationships struct {
Role *Relation `json:"role,omitempty"`
Balances *RelationCollection `json:"balances,omitempty"`
Fees *RelationCollection `json:"fees,omitempty"`
Referrer *Relation `json:"referrer,omitempty"`
Limits *RelationCollection `json:"limits,omitempty"`
ExternalSystemIDs *RelationCollection `json:"external_system_ids,omitempty"`
}
|
findy-network/findy-issuer-tool | frontend/src/store/actions.js | export const FETCH_USER = 'FETCH_USER';
export const fetchUser = (username) => ({
type: FETCH_USER,
payload: username,
});
export const FETCH_USER_FULFILLED = 'FETCH_USER_FULFILLED';
export const fetchUserFulfilled = (payload) => ({
type: FETCH_USER_FULFILLED,
payload,
});
export const FETCH_LEDGER = 'FETCH_LEDGER';
export const fetchLedger = (payload) => ({ type: FETCH_LEDGER, payload });
export const FETCH_LEDGER_FULFILLED = 'FETCH_LEDGER_FULFILLED';
export const fetchLedgerFulfilled = (payload) => ({
type: FETCH_LEDGER_FULFILLED,
payload,
});
export const FETCH_LEDGER_REJECTED = 'FETCH_LEDGER_REJECTED';
export const fetchLedgerRejected = (payload) => ({
type: FETCH_LEDGER_REJECTED,
payload,
});
export const FETCH_CONNECTIONS = 'FETCH_CONNECTIONS';
export const fetchConnections = (payload) => ({
type: FETCH_CONNECTIONS,
payload,
});
export const FETCH_CONNECTIONS_FULFILLED = 'FETCH_CONNECTIONS_FULFILLED';
export const fetchConnectionsFulfilled = (payload) => ({
type: FETCH_CONNECTIONS_FULFILLED,
payload,
});
export const FETCH_CONNECTIONS_REJECTED = 'FETCH_CONNECTIONS_REJECTED';
export const fetchConnectionsRejected = (payload) => ({
type: FETCH_CONNECTIONS_REJECTED,
payload,
});
export const FETCH_PAIRWISE_INVITATION = 'FETCH_PAIRWISE_INVITATION';
export const fetchPairwiseInvitation = (payload) => ({
type: FETCH_PAIRWISE_INVITATION,
payload,
});
export const FETCH_PAIRWISE_INVITATION_FULFILLED =
'FETCH_PAIRWISE_INVITATION_FULFILLED';
export const fetchPairwiseInvitationFulfilled = (payload) => ({
type: FETCH_PAIRWISE_INVITATION_FULFILLED,
payload,
});
export const FETCH_PAIRWISE_INVITATION_REJECTED =
'FETCH_PAIRWISE_INVITATION_REJECTED';
export const fetchPairwiseInvitationRejected = (payload) => ({
type: FETCH_PAIRWISE_INVITATION_REJECTED,
payload,
});
export const SET_TOKEN = 'SET_TOKEN';
export const setToken = (payload) => ({
type: SET_TOKEN,
payload,
});
export const SAVE_SCHEMA = 'SAVE_SCHEMA';
export const saveSchema = (payload) => ({
type: SAVE_SCHEMA,
payload,
});
export const SAVE_SCHEMA_FULFILLED = 'SAVE_SCHEMA_FULFILLED';
export const saveSchemaFulfilled = (payload) => ({
type: SAVE_SCHEMA_FULFILLED,
payload,
});
export const SAVE_SCHEMA_REJECTED = 'SAVE_SCHEMA_REJECTED';
export const saveSchemaRejected = (payload) => ({
type: SAVE_SCHEMA_REJECTED,
payload,
});
export const SAVE_CRED_DEF = 'SAVE_CRED_DEF';
export const saveCredDef = (payload) => ({
type: SAVE_CRED_DEF,
payload,
});
export const SAVE_CRED_DEF_FULFILLED = 'SAVE_CRED_DEF_FULFILLED';
export const saveCredDefFulfilled = (payload) => ({
type: SAVE_CRED_DEF_FULFILLED,
payload,
});
export const SAVE_CRED_DEF_REJECTED = 'SAVE_CRED_DEF_REJECTED';
export const saveCredDefRejected = (payload) => ({
type: SAVE_CRED_DEF_REJECTED,
payload,
});
export const FETCH_EVENTS_LOG = 'FETCH_EVENTS_LOG';
export const fetchEventsLog = (payload) => ({
type: FETCH_EVENTS_LOG,
payload,
});
export const FETCH_EVENTS_LOG_FULFILLED = 'FETCH_EVENTS_LOG_FULFILLED';
export const fetchEventsLogFulfilled = (payload) => ({
type: FETCH_EVENTS_LOG_FULFILLED,
payload,
});
export const FETCH_EVENTS_LOG_REJECTED = 'FETCH_EVENTS_LOG_REJECTED';
export const fetchEventsLogRejected = (payload) => ({
type: FETCH_EVENTS_LOG_REJECTED,
payload,
});
export const SEND_BASIC_MESSAGE = 'SEND_BASIC_MESSAGE';
export const sendBasicMessage = (payload) => ({
type: SEND_BASIC_MESSAGE,
payload,
});
export const SEND_BASIC_MESSAGE_FULFILLED = 'SEND_BASIC_MESSAGE_FULFILLED';
export const sendBasicMessageFulfilled = (payload) => ({
type: SEND_BASIC_MESSAGE_FULFILLED,
payload,
});
export const SEND_BASIC_MESSAGE_REJECTED = 'SEND_BASIC_MESSAGE_REJECTED';
export const sendBasicMessageRejected = (payload) => ({
type: SEND_BASIC_MESSAGE_REJECTED,
payload,
});
export const SEND_PROOF_REQUEST = 'SEND_PROOF_REQUEST';
export const sendProofRequest = (payload) => ({
type: SEND_PROOF_REQUEST,
payload,
});
export const SEND_PROOF_REQUEST_FULFILLED = 'SEND_PROOF_REQUEST_FULFILLED';
export const sendProofRequestFulfilled = (payload) => ({
type: SEND_PROOF_REQUEST_FULFILLED,
payload,
});
export const SEND_PROOF_REQUEST_REJECTED = 'SEND_PROOF_REQUEST_REJECTED';
export const sendProofRequestRejected = (payload) => ({
type: SEND_PROOF_REQUEST_REJECTED,
payload,
});
export const SEND_CREDENTIAL = 'SEND_CREDENTIAL';
export const sendCredential = (payload) => ({
type: SEND_CREDENTIAL,
payload,
});
export const SEND_CREDENTIAL_FULFILLED = 'SEND_CREDENTIAL_FULFILLED';
export const sendCredentialFulfilled = (payload) => ({
type: SEND_CREDENTIAL_FULFILLED,
payload,
});
export const SEND_CREDENTIAL_REJECTED = 'SEND_CREDENTIAL_REJECTED';
export const sendCredentialRejected = (payload) => ({
type: SEND_CREDENTIAL_REJECTED,
payload,
});
|
forgems/instana-agent-operator | src/test/java/com/instana/operator/AgentDeployerTest.java | <reponame>forgems/instana-agent-operator<gh_stars>0
package com.instana.operator;
import com.google.common.collect.ImmutableMap;
import com.instana.operator.customresource.InstanaAgent;
import com.instana.operator.customresource.InstanaAgentSpec;
import com.instana.operator.env.Environment;
import io.fabric8.kubernetes.api.model.Container;
import io.fabric8.kubernetes.api.model.EnvVar;
import io.fabric8.kubernetes.api.model.apps.DaemonSet;
import io.fabric8.kubernetes.client.DefaultKubernetesClient;
import org.junit.jupiter.api.Test;
import java.util.Collections;
import static com.instana.operator.env.Environment.RELATED_IMAGE_INSTANA_AGENT;
import static java.util.Collections.emptyMap;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.allOf;
import static org.hamcrest.Matchers.hasItem;
import static org.hamcrest.Matchers.is;
class AgentDeployerTest {
private final DefaultKubernetesClient client = new DefaultKubernetesClient();
@Test
void daemonset_must_include_environment() {
AgentDeployer deployer = new AgentDeployer();
deployer.setEnvironment(empty());
InstanaAgentSpec agentSpec = new InstanaAgentSpec();
agentSpec.setAgentEnv(ImmutableMap.<String, String>builder()
.put("INSTANA_AGENT_MODE", "APM")
.build());
InstanaAgent crd = new InstanaAgent();
crd.setSpec(agentSpec);
DaemonSet daemonSet = deployer.newDaemonSet(
crd,
client.inNamespace("instana-agent").apps().daemonSets());
Container agentContainer = getAgentContainer(daemonSet);
assertThat(agentContainer.getEnv(), allOf(
hasItem(new EnvVar("INSTANA_AGENT_MODE", "APM", null))));
}
@Test
void daemonset_must_include_specified_image() {
AgentDeployer deployer = new AgentDeployer();
deployer.setEnvironment(empty());
InstanaAgentSpec agentSpec = new InstanaAgentSpec();
agentSpec.setAgentImage("other/image:some-tag");
InstanaAgent crd = new InstanaAgent();
crd.setSpec(agentSpec);
DaemonSet daemonSet = deployer.newDaemonSet(
crd,
client.inNamespace("instana-agent").apps().daemonSets());
Container agentContainer = getAgentContainer(daemonSet);
assertThat(agentContainer
.getImage(), is("other/image:some-tag"));
}
@Test
void daemonset_must_include_image_from_csv_if_specified() {
AgentDeployer deployer = new AgentDeployer();
deployer.setEnvironment(singleVar(RELATED_IMAGE_INSTANA_AGENT, "other/image:some-tag"));
InstanaAgent crd = new InstanaAgent();
crd.setSpec(new InstanaAgentSpec());
DaemonSet daemonSet = deployer.newDaemonSet(
crd,
client.inNamespace("instana-agent").apps().daemonSets());
Container agentContainer = getAgentContainer(daemonSet);
assertThat(agentContainer.getImage(), is("other/image:some-tag"));
}
private Container getAgentContainer(DaemonSet daemonSet) {
return daemonSet.getSpec().getTemplate().getSpec().getContainers().get(0);
}
private Environment empty() {
return Environment.fromMap(emptyMap());
}
private Environment singleVar(String key, String value) {
return Environment.fromMap(Collections.singletonMap(key, value));
}
}
|
bryanjeanty/kryptodash | client/components/bootstrap/Footer.js | <reponame>bryanjeanty/kryptodash<filename>client/components/bootstrap/Footer.js
import React, { Component, Fragment } from "react";
import Link from "next/link";
export class Footer extends Component {
render() {
return (
<Fragment>
<div className="footer-wrapper">
© 2019 Copyright:
<Link href="/">
<a> KryptoDash.com</a>
</Link>
</div>
<style jsx>{`
.footer-wrapper {
padding: 3px 0;
color: rgba(256, 256, 256, 0.75);
font-weight: 300;
}
a {
color: #fff;
text-decoration: none;
}
`}</style>
</Fragment>
);
}
}
|
oxelson/gempak | gempak/source/driver/active/xw/xtext.c | <gh_stars>10-100
#include "xwcmn.h"
void xtext ( float *xr, float *yr, char strout[], int *lenstr,
int *ixoff, int *iyoff, float *rotat, int *ispanx,
int *ispany, int *icleft, int *icrght, int *icbot,
int *ictop, int *iret )
/************************************************************************
* xtext *
* *
* This subroutine draws a character string for the X window driver. *
* Location of the given text string is determined by the given point *
* and the alignment type. Rotation has not been implemented in current *
* version. *
* *
* xtext ( xr, yr, strout, lenstr, ixoff, iyoff, rotat, *
* ispanx, ispany, icleft, icrght, icbot, ictop, iret ) *
* *
* Input parameters: *
* *xr float X coordinate *
* *yr float Y coordinate *
* strout[] char String *
* *lenstr int Length of string *
* *ixoff int X offset *
* *iyoff int Y offset *
* *rotat float Rotation angle *
* *ispanx int Direction of increasing x *
* *ispany int Direction of increasing y *
* *icleft int Left clipping bound *
* *icrght int Right clipping bound *
* *icbot int Bottom clipping bound *
* *ictop int Top clipping bound *
* *
* Output parameters: *
* *iret int Reutrn code *
* G_NORMAL = normal return *
** *
* Log: *
* <NAME>/SSAI 7/91 C call for X device driver *
* S. Jacobs/NMC 7/94 General clean up *
* C. Lin/EAI 7/94 Multi-window, multi-pixmap *
* S. Jacobs/NCEP 9/97 Added justification code from XTEXTC *
* S. Jacobs/NCEP 12/97 Added clipping flag to justification *
* S. Jacobs/NCEP 1/98 Added adjustment for starting location *
* S. Jacobs/NCEP 7/98 Added alignment and bound checks *
* E. Safford/GSC 12/99 updated for new xwcmn.h *
* S. Law/GSC 01/00 changed curpxm to an array *
* S. Law/GSC 08/00 removed nmap vs nmap2 references *
***********************************************************************/
{
int ipxm, lp, direction, ascent, descent;
int width, jx, jy, jxoend;
float xo, yo, xx, yy, xadj;
Pixmap gempixmap;
GC gemgc;
Window_str *cwin;
XCharStruct overall;
/*---------------------------------------------------------------------*/
*iret = G_NORMAL;
cwin = &(gemwindow[current_window]);
lp = cwin->curr_loop;
ipxm = cwin->curpxm[lp];
gempixmap = cwin->pxms[lp][ipxm];
gemgc = gemwindow[current_window].gc;
/*
* Get string width for alignment
*/
XQueryTextExtents ( gemdisplay, XGContextFromGC(gemgc),
strout, *lenstr, &direction, &ascent,
&descent, &overall );
width = overall.width;
/*
* Set the alignment.
*/
if ( kjust == 1 ) {
xadj = 0.0;
}
else if ( kjust == 3 ) {
xadj = width - ( width / *lenstr );
}
else {
xadj = ( width - ( width / *lenstr ) ) / 2.0;
}
/*
* Convert the text location to integers.
*/
xo = ( ( *ixoff - 0.75 ) / 2.0 ) * txszx * txsize_req - xadj;
xx = *xr + xo * *ispanx;
jx = G_NINT ( xx );
yo = ( ( *iyoff - 0.75 ) / 2.0 ) * txszy * txsize_req ;
yy = *yr + yo * *ispany;
jy = G_NINT ( yy );
/*
* Check to see if the start point is outside the clipping
* window. Then the end point is checked. Rotation is not
* taken into account.
*/
jxoend = jx + width;
if ( ( *ispanx * ( jx - *icleft ) < 0 ) ||
( *ispanx * ( jx - *icrght ) > 0 ) ||
( *ispany * ( jy - *icbot ) < 0 ) ||
( *ispany * ( jy - *ictop ) > 0 ) ||
( *ispanx * ( jxoend - *icrght ) > 0 ) ) return;
/*
* Draw string on window
*/
XDrawString (gemdisplay, gempixmap, gemgc, jx, jy, strout, *lenstr);
}
|
seijikun/ractive | src/parse/utils/refineExpression.js | <filename>src/parse/utils/refineExpression.js<gh_stars>1000+
import { REFERENCE, BRACKETED, MEMBER, REFINEMENT } from 'config/types';
import flattenExpression from './flattenExpression';
export default function refineExpression(expression, mustache) {
let referenceExpression;
if (expression) {
while (expression.t === BRACKETED && expression.x) {
expression = expression.x;
}
if (expression.t === REFERENCE) {
const n = expression.n;
if (!~n.indexOf('@context')) {
mustache.r = expression.n;
} else {
mustache.x = flattenExpression(expression);
}
} else {
if ((referenceExpression = getReferenceExpression(expression))) {
mustache.rx = referenceExpression;
} else {
mustache.x = flattenExpression(expression);
}
}
return mustache;
}
}
// TODO refactor this! it's bewildering
function getReferenceExpression(expression) {
const members = [];
let refinement;
while (expression.t === MEMBER && expression.r.t === REFINEMENT) {
refinement = expression.r;
if (refinement.x) {
if (refinement.x.t === REFERENCE) {
members.unshift(refinement.x);
} else {
members.unshift(flattenExpression(refinement.x));
}
} else {
members.unshift(refinement.n);
}
expression = expression.x;
}
if (expression.t !== REFERENCE) {
return null;
}
return {
r: expression.n,
m: members
};
}
|
asphaltpanthers/libjson-rpc-cpp | src/jsonrpc/specification.h | /*************************************************************************
* libjson-rpc-cpp
*************************************************************************
* @file specification.h
* @date 30.04.2013
* @author <NAME> <<EMAIL>>
* @license See attached LICENSE.txt
************************************************************************/
#ifndef SPECIFICATION_H
#define SPECIFICATION_H
#define KEY_METHOD_NAME "method"
#define KEY_NOTIFICATION_NAME "notification"
#define KEY_PROCEDURE_PARAMETERS "params"
#define KEY_RETURN_TYPE "returns"
namespace jsonrpc
{
/**
* This enum describes whether a Procdeure is a notification procdeure or a method procdeure
* @see http://groups.google.com/group/json-rpc/web/json-rpc-2-0
*/
typedef enum
{
RPC_METHOD, RPC_NOTIFICATION
} procedure_t;
/**
* This enum represents all processable json Types of this framework.
*/
enum jsontype_t
{
JSON_STRING = 1,
JSON_BOOLEAN = 2,
JSON_INTEGER = 3,
JSON_REAL = 4,
JSON_OBJECT = 5,
JSON_ARRAY = 6,
JSON_NULL = 7
} ;
}
#endif // SPECIFICATION_H
|
DreVinciCode/TEAM-08 | MRTK/h/Il2CppOutputProject/IL2CPP/libil2cpp/os/Atomic.h | #pragma once
#include <stdint.h>
#include "utils/NonCopyable.h"
#include "c-api/Atomic-c-api.h"
namespace il2cpp
{
namespace os
{
class Atomic : public il2cpp::utils::NonCopyable
{
public:
// All 32bit atomics must be performed on 4-byte aligned addresses. All 64bit atomics must be
// performed on 8-byte aligned addresses.
// Add and Add64 return the *result* of the addition, not the old value! (i.e. they work like
// InterlockedAdd and __sync_add_and_fetch).
static inline void FullMemoryBarrier()
{
UnityPalFullMemoryBarrier();
}
static inline int32_t Add(int32_t* location1, int32_t value)
{
return UnityPalAdd(location1, value);
}
static inline uint32_t Add(uint32_t* location1, uint32_t value)
{
return (uint32_t)Add((int32_t*)location1, (int32_t)value);
}
#if IL2CPP_ENABLE_INTERLOCKED_64_REQUIRED_ALIGNMENT
static inline int64_t Add64(int64_t* location1, int64_t value)
{
return UnityPalAdd64(location1, value);
}
#endif
template<typename T>
static inline T* CompareExchangePointer(T** dest, T* newValue, T* oldValue)
{
return static_cast<T*>(UnityPalCompareExchangePointer((void**)dest, newValue, oldValue));
}
template<typename T>
static inline T* ExchangePointer(T** dest, T* newValue)
{
return static_cast<T*>(UnityPalExchangePointer((void**)dest, newValue));
}
static inline int64_t Read64(int64_t* addr)
{
return UnityPalRead64(addr);
}
static inline uint64_t Read64(uint64_t* addr)
{
return (uint64_t)Read64((int64_t*)addr);
}
static inline int32_t LoadRelaxed(const int32_t* addr)
{
return UnityPalLoadRelaxed(addr);
}
template<typename T>
static inline T* ReadPointer(T** pointer)
{
#if IL2CPP_SIZEOF_VOID_P == 4
return reinterpret_cast<T*>(Add(reinterpret_cast<int32_t*>(pointer), 0));
#else
return reinterpret_cast<T*>(Read64(reinterpret_cast<int64_t*>(pointer)));
#endif
}
static inline int32_t Increment(int32_t* value)
{
return UnityPalIncrement(value);
}
static inline uint32_t Increment(uint32_t* value)
{
return (uint32_t)Increment((int32_t*)value);
}
#if IL2CPP_ENABLE_INTERLOCKED_64_REQUIRED_ALIGNMENT
static inline int64_t Increment64(int64_t* value)
{
return UnityPalIncrement64(value);
}
static inline uint64_t Increment64(uint64_t* value)
{
return (uint64_t)Increment64((int64_t*)value);
}
#endif
static inline int32_t Decrement(int32_t* value)
{
return UnityPalDecrement(value);
}
static inline uint32_t Decrement(uint32_t* value)
{
return (uint32_t)Decrement((int32_t*)value);
}
#if IL2CPP_ENABLE_INTERLOCKED_64_REQUIRED_ALIGNMENT
static inline int64_t Decrement64(int64_t* value)
{
return UnityPalDecrement64(value);
}
static inline uint64_t Decrement64(uint64_t* value)
{
return (uint64_t)Decrement64((int64_t*)value);
}
#endif
static inline int32_t CompareExchange(int32_t* dest, int32_t exchange, int32_t comparand)
{
return UnityPalCompareExchange(dest, exchange, comparand);
}
static inline uint32_t CompareExchange(uint32_t* value, uint32_t newValue, uint32_t oldValue)
{
return (uint32_t)CompareExchange((int32_t*)value, newValue, oldValue);
}
static inline int64_t CompareExchange64(int64_t* dest, int64_t exchange, int64_t comparand)
{
return UnityPalCompareExchange64(dest, exchange, comparand);
}
static inline uint64_t CompareExchange64(uint64_t* value, uint64_t newValue, uint64_t oldValue)
{
return (uint64_t)CompareExchange64((int64_t*)value, newValue, oldValue);
}
static inline int32_t Exchange(int32_t* dest, int32_t exchange)
{
return UnityPalExchange(dest, exchange);
}
static inline uint32_t Exchange(uint32_t* value, uint32_t newValue)
{
return (uint32_t)Exchange((int32_t*)value, newValue);
}
#if IL2CPP_ENABLE_INTERLOCKED_64_REQUIRED_ALIGNMENT
static inline int64_t Exchange64(int64_t* dest, int64_t exchange)
{
return UnityPalExchange64(dest, exchange);
}
static inline uint64_t Exchange64(uint64_t* value, uint64_t newValue)
{
return (uint64_t)Exchange64((int64_t*)value, newValue);
}
#endif
};
}
}
|
m3rlin5ky/wasp | plugins/database/cleantesting.go | package database
import (
"github.com/iotaledger/goshimmer/dapps/valuetransfers/packages/address"
"github.com/iotaledger/hive.go/kvstore"
)
// temporary. Until DeletePrefix is fixed
func deletePartition(addr *address.Address) error {
dbase := GetPartition(addr)
keys := make([][]byte, 0)
err := dbase.IterateKeys(kvstore.EmptyPrefix, func(key kvstore.Key) bool {
k := make([]byte, len(key))
copy(k, key)
keys = append(keys, k)
return true
})
if err != nil {
return err
}
b := dbase.Batched()
for _, k := range keys {
if err = b.Delete(k); err != nil {
b.Cancel()
return err
}
}
return b.Commit()
}
|
Ayvytr/MvpCommons | lib/qrscan/src/main/java/com/wanshare/wscomponent/qrscan/activity/CaptureActivity.java | package com.wanshare.wscomponent.qrscan.activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import androidx.appcompat.app.AppCompatActivity;
import com.wanshare.wscomponent.qrscan.OnScanListener;
import com.wanshare.wscomponent.qrscan.QrUtils;
import com.wanshare.wscomponent.qrscan.R;
/**
* 默认的二维码扫描Activity.
*
* @author wangdunwei
* @since 1.0.0
*/
public class CaptureActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.layout_camera);
CaptureFragment captureFragment = new CaptureFragment();
captureFragment.setOnScanListener(onScanListener);
getSupportFragmentManager().beginTransaction().replace(R.id.fl_zxing_container, captureFragment).commit();
}
/**
* 二维码解析回调函数
*/
OnScanListener onScanListener = new OnScanListener() {
@Override
public void onSucceed(Bitmap mBitmap, String result) {
Intent resultIntent = new Intent();
Bundle bundle = new Bundle();
bundle.putString(QrUtils.RESULT, result);
resultIntent.putExtras(bundle);
setResult(RESULT_OK, resultIntent);
finish();
}
@Override
public void onFailed() {
Intent resultIntent = new Intent();
Bundle bundle = new Bundle();
bundle.putString(QrUtils.RESULT, "");
resultIntent.putExtras(bundle);
finish();
}
};
} |
vijayraavi/jmeter-to-k6 | src/element/HeaderManager.js | const { Header } = require('../symbol')
const properties = require('../common/properties')
const makeResult = require('../result')
function HeaderManager (node, context) {
const result = makeResult()
if (node.attributes.enabled === 'false') return result
const settings = new Map()
for (const key of Object.keys(node.attributes)) attribute(node, key, result)
const children = node.children
const props = children.filter(node => /Prop$/.test(node.name))
for (const prop of props) property(prop, context, settings)
if (settings.size) {
result.defaults.push({ [Header]: settings })
}
return result
}
function attribute (node, key, result) {
switch (key) {
case 'enabled':
case 'guiclass':
case 'testclass':
case 'testname':
break
default: throw new Error('Unrecognized HeaderManager attribute: ' + key)
}
}
function property (node, context, settings) {
const name = node.attributes.name.split('.').pop()
switch (name) {
case 'comments':
break
case 'headers':
headers(node, context, settings)
break
default: throw new Error('Unrecognized HeaderManager property: ' + name)
}
}
function headers (node, context, settings) {
const props = node.children.filter(node => /Prop$/.test(node.name))
for (const prop of props) header(prop, context, settings)
}
function header (node, context, settings) {
const props = properties(node, context)
if (!(props.name && props.value)) throw new Error('Invalid header entry')
settings.set(props.name, props.value)
}
module.exports = HeaderManager
|
alleindrach/calculix-desktop | FastCAE_Linux/Code/GeometryWidgets/release/qui/ui_dialogMakeExtrusion.h | /********************************************************************************
** Form generated from reading UI file 'dialogMakeExtrusion.ui'
**
** Created by: Qt User Interface Compiler version 5.14.2
**
** WARNING! All changes made in this file will be lost when recompiling UI file!
********************************************************************************/
#ifndef UI_DIALOGMAKEEXTRUSION_H
#define UI_DIALOGMAKEEXTRUSION_H
#include <QtCore/QVariant>
#include <QtWidgets/QApplication>
#include <QtWidgets/QCheckBox>
#include <QtWidgets/QDialog>
#include <QtWidgets/QDialogButtonBox>
#include <QtWidgets/QDoubleSpinBox>
#include <QtWidgets/QGridLayout>
#include <QtWidgets/QGroupBox>
#include <QtWidgets/QHBoxLayout>
#include <QtWidgets/QLabel>
#include <QtWidgets/QLineEdit>
#include <QtWidgets/QPushButton>
#include <QtWidgets/QRadioButton>
QT_BEGIN_NAMESPACE
class Ui_CreateExtrusion
{
public:
QGridLayout *gridLayout_4;
QGroupBox *groupBox_3;
QHBoxLayout *horizontalLayout;
QLabel *edglabel;
QPushButton *geoSelectCurve;
QDialogButtonBox *buttonBox;
QGroupBox *groupBox_2;
QGridLayout *gridLayout_2;
QRadioButton *radioButtonUser;
QHBoxLayout *horizontalLayout_5;
QDoubleSpinBox *doubleSpinBoxX;
QDoubleSpinBox *doubleSpinBoxY;
QDoubleSpinBox *doubleSpinBoxZ;
QHBoxLayout *horizontalLayout_4;
QRadioButton *radioButtonX;
QRadioButton *radioButtonY;
QRadioButton *radioButtonZ;
QCheckBox *reversecheckBox;
QCheckBox *solidCheckBox;
QGroupBox *groupBox_5;
QGridLayout *gridLayout;
QLabel *label_2;
QLineEdit *lineEditDistance;
void setupUi(QDialog *CreateExtrusion)
{
if (CreateExtrusion->objectName().isEmpty())
CreateExtrusion->setObjectName(QString::fromUtf8("CreateExtrusion"));
CreateExtrusion->resize(431, 319);
gridLayout_4 = new QGridLayout(CreateExtrusion);
gridLayout_4->setObjectName(QString::fromUtf8("gridLayout_4"));
groupBox_3 = new QGroupBox(CreateExtrusion);
groupBox_3->setObjectName(QString::fromUtf8("groupBox_3"));
horizontalLayout = new QHBoxLayout(groupBox_3);
horizontalLayout->setObjectName(QString::fromUtf8("horizontalLayout"));
edglabel = new QLabel(groupBox_3);
edglabel->setObjectName(QString::fromUtf8("edglabel"));
horizontalLayout->addWidget(edglabel);
geoSelectCurve = new QPushButton(groupBox_3);
geoSelectCurve->setObjectName(QString::fromUtf8("geoSelectCurve"));
geoSelectCurve->setMinimumSize(QSize(32, 32));
geoSelectCurve->setMaximumSize(QSize(32, 32));
geoSelectCurve->setStyleSheet(QString::fromUtf8("background-image: url(:/QUI/geometry/selectwire.png);"));
horizontalLayout->addWidget(geoSelectCurve);
gridLayout_4->addWidget(groupBox_3, 0, 0, 1, 1);
buttonBox = new QDialogButtonBox(CreateExtrusion);
buttonBox->setObjectName(QString::fromUtf8("buttonBox"));
buttonBox->setOrientation(Qt::Horizontal);
buttonBox->setStandardButtons(QDialogButtonBox::Cancel|QDialogButtonBox::Ok);
gridLayout_4->addWidget(buttonBox, 5, 0, 1, 1);
groupBox_2 = new QGroupBox(CreateExtrusion);
groupBox_2->setObjectName(QString::fromUtf8("groupBox_2"));
gridLayout_2 = new QGridLayout(groupBox_2);
gridLayout_2->setObjectName(QString::fromUtf8("gridLayout_2"));
radioButtonUser = new QRadioButton(groupBox_2);
radioButtonUser->setObjectName(QString::fromUtf8("radioButtonUser"));
gridLayout_2->addWidget(radioButtonUser, 1, 0, 1, 1);
horizontalLayout_5 = new QHBoxLayout();
horizontalLayout_5->setObjectName(QString::fromUtf8("horizontalLayout_5"));
doubleSpinBoxX = new QDoubleSpinBox(groupBox_2);
doubleSpinBoxX->setObjectName(QString::fromUtf8("doubleSpinBoxX"));
doubleSpinBoxX->setMinimum(-1000.000000000000000);
doubleSpinBoxX->setMaximum(1000.000000000000000);
horizontalLayout_5->addWidget(doubleSpinBoxX);
doubleSpinBoxY = new QDoubleSpinBox(groupBox_2);
doubleSpinBoxY->setObjectName(QString::fromUtf8("doubleSpinBoxY"));
doubleSpinBoxY->setMinimum(-1000.000000000000000);
doubleSpinBoxY->setMaximum(1000.000000000000000);
horizontalLayout_5->addWidget(doubleSpinBoxY);
doubleSpinBoxZ = new QDoubleSpinBox(groupBox_2);
doubleSpinBoxZ->setObjectName(QString::fromUtf8("doubleSpinBoxZ"));
doubleSpinBoxZ->setMinimum(-1000.000000000000000);
doubleSpinBoxZ->setMaximum(1000.000000000000000);
doubleSpinBoxZ->setValue(1.000000000000000);
horizontalLayout_5->addWidget(doubleSpinBoxZ);
gridLayout_2->addLayout(horizontalLayout_5, 2, 0, 1, 1);
horizontalLayout_4 = new QHBoxLayout();
horizontalLayout_4->setObjectName(QString::fromUtf8("horizontalLayout_4"));
radioButtonX = new QRadioButton(groupBox_2);
radioButtonX->setObjectName(QString::fromUtf8("radioButtonX"));
horizontalLayout_4->addWidget(radioButtonX);
radioButtonY = new QRadioButton(groupBox_2);
radioButtonY->setObjectName(QString::fromUtf8("radioButtonY"));
horizontalLayout_4->addWidget(radioButtonY);
radioButtonZ = new QRadioButton(groupBox_2);
radioButtonZ->setObjectName(QString::fromUtf8("radioButtonZ"));
radioButtonZ->setChecked(true);
horizontalLayout_4->addWidget(radioButtonZ);
gridLayout_2->addLayout(horizontalLayout_4, 0, 0, 1, 1);
reversecheckBox = new QCheckBox(groupBox_2);
reversecheckBox->setObjectName(QString::fromUtf8("reversecheckBox"));
gridLayout_2->addWidget(reversecheckBox, 3, 0, 1, 1);
radioButtonUser->raise();
reversecheckBox->raise();
gridLayout_4->addWidget(groupBox_2, 2, 0, 1, 1);
solidCheckBox = new QCheckBox(CreateExtrusion);
solidCheckBox->setObjectName(QString::fromUtf8("solidCheckBox"));
solidCheckBox->setLayoutDirection(Qt::LeftToRight);
solidCheckBox->setChecked(true);
gridLayout_4->addWidget(solidCheckBox, 4, 0, 1, 1);
groupBox_5 = new QGroupBox(CreateExtrusion);
groupBox_5->setObjectName(QString::fromUtf8("groupBox_5"));
QSizePolicy sizePolicy(QSizePolicy::Preferred, QSizePolicy::Minimum);
sizePolicy.setHorizontalStretch(0);
sizePolicy.setVerticalStretch(0);
sizePolicy.setHeightForWidth(groupBox_5->sizePolicy().hasHeightForWidth());
groupBox_5->setSizePolicy(sizePolicy);
groupBox_5->setMaximumSize(QSize(16777215, 16777215));
gridLayout = new QGridLayout(groupBox_5);
gridLayout->setObjectName(QString::fromUtf8("gridLayout"));
label_2 = new QLabel(groupBox_5);
label_2->setObjectName(QString::fromUtf8("label_2"));
QSizePolicy sizePolicy1(QSizePolicy::Preferred, QSizePolicy::Preferred);
sizePolicy1.setHorizontalStretch(0);
sizePolicy1.setVerticalStretch(0);
sizePolicy1.setHeightForWidth(label_2->sizePolicy().hasHeightForWidth());
label_2->setSizePolicy(sizePolicy1);
gridLayout->addWidget(label_2, 0, 0, 1, 1);
lineEditDistance = new QLineEdit(groupBox_5);
lineEditDistance->setObjectName(QString::fromUtf8("lineEditDistance"));
QSizePolicy sizePolicy2(QSizePolicy::Preferred, QSizePolicy::Fixed);
sizePolicy2.setHorizontalStretch(0);
sizePolicy2.setVerticalStretch(0);
sizePolicy2.setHeightForWidth(lineEditDistance->sizePolicy().hasHeightForWidth());
lineEditDistance->setSizePolicy(sizePolicy2);
gridLayout->addWidget(lineEditDistance, 0, 1, 1, 1);
gridLayout_4->addWidget(groupBox_5, 1, 0, 1, 1);
retranslateUi(CreateExtrusion);
QObject::connect(buttonBox, SIGNAL(accepted()), CreateExtrusion, SLOT(accept()));
QObject::connect(buttonBox, SIGNAL(rejected()), CreateExtrusion, SLOT(reject()));
QMetaObject::connectSlotsByName(CreateExtrusion);
} // setupUi
void retranslateUi(QDialog *CreateExtrusion)
{
CreateExtrusion->setWindowTitle(QCoreApplication::translate("CreateExtrusion", "Create Extrusion", nullptr));
groupBox_3->setTitle(QCoreApplication::translate("CreateExtrusion", "Select", nullptr));
edglabel->setText(QCoreApplication::translate("CreateExtrusion", "Selected edge(0)", nullptr));
geoSelectCurve->setText(QString());
groupBox_2->setTitle(QCoreApplication::translate("CreateExtrusion", "Direction", nullptr));
radioButtonUser->setText(QCoreApplication::translate("CreateExtrusion", "User define", nullptr));
radioButtonX->setText(QCoreApplication::translate("CreateExtrusion", "X axis", nullptr));
radioButtonY->setText(QCoreApplication::translate("CreateExtrusion", "Y axis", nullptr));
radioButtonZ->setText(QCoreApplication::translate("CreateExtrusion", "Z axis", nullptr));
reversecheckBox->setText(QCoreApplication::translate("CreateExtrusion", "Reverse", nullptr));
#if QT_CONFIG(tooltip)
solidCheckBox->setToolTip(QString());
#endif // QT_CONFIG(tooltip)
solidCheckBox->setText(QCoreApplication::translate("CreateExtrusion", "Generate Solid", nullptr));
groupBox_5->setTitle(QCoreApplication::translate("CreateExtrusion", "Distance", nullptr));
label_2->setText(QCoreApplication::translate("CreateExtrusion", "Distance", nullptr));
lineEditDistance->setText(QCoreApplication::translate("CreateExtrusion", "10.00", nullptr));
} // retranslateUi
};
namespace Ui {
class CreateExtrusion: public Ui_CreateExtrusion {};
} // namespace Ui
QT_END_NAMESPACE
#endif // UI_DIALOGMAKEEXTRUSION_H
|
LeksiDor/JaraboTransientRendering | src/Film/Film.h | <filename>src/Film/Film.h
/*
* Copyright (C) 2015, <NAME> (http://giga.cps.unizar.es/~ajarabo/)
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom
* the Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included
* in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
* DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE
* OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#ifndef _FILM_H_
#define _FILM_H_
#include "bunnykiller.h"
#include <algorithm>
#include <array>
#include <cmath>
#include <cstddef>
#include <cstdio>
#include <memory>
#include <string>
#include <vector>
#include "LinearAlgebra/Vector2.h"
#include "Filter/BoxFilter.h"
#include "Sampling/Sample.h"
#include "Integrator/RadianceSample.h"
#include "Color/Spectrum.h"
#include "Color/PolarizedSpectrum.h"
#include "Image/Image.h"
#include "Image/ImageIO.h"
#include "Film/FilmComponents.h"
/** A render Film for RGB images in Real format. */
template<unsigned D, class Radiance>
class Film
{
protected:
using RadianceSampleR = RadianceSample<D, Radiance>;
using RadianceSampleRecordR = RadianceSampleRecord<D, Radiance>;
using RadianceSampleRecordVectorR = RadianceSampleRecordVector<D, Radiance>;
protected:
/* The components stored by the film */
FilmComponents m_components;
/* Reconstruction filter */
Filter* m_filter;
/* Buffer containing the image */
std::array<Imaging::Image<Real>, Radiance::components> m_image;
Imaging::Image<Real> m_weight;
/* Buffers with additional components */
std::unique_ptr<Imaging::Image<Real>> m_depth_comp;
std::unique_ptr<Imaging::Image<Real>> m_positions_comp;
std::unique_ptr<Imaging::Image<Real>> m_normals_comp;
/* Width and height of film */
size_t width, height;
size_t shift_x, shift_y;
Real ratio;
/* Half width and height of film */
Real xw2, yw2;
bool averaged;
/* Film name */
std::string m_name;
std::string m_extension;
void get_film_samples(const Vector2 &position, std::vector<Vector2>& samples) const
{
samples.clear();
int size_kernel = m_filter->get_size();
int half_size = size_kernel / 2;
int x = (int) (position[0]);
int y = (int) (position[1]);
size_t init_x = std::max(0, x - half_size);
size_t init_y = std::max(0, y - half_size);
size_t end_x = std::min(x + half_size, int(width - 1));
size_t end_y = std::min(y + half_size, int(height - 1));
for (size_t j = init_y; j <= end_y; j++) {
for (size_t i = init_x; i <= end_x; i++) {
samples.push_back(Vector2(Real(i) + .5, Real(j) + .5));
}
}
}
void get_film_samples(const Real x, const unsigned int d, std::vector<Real>& samples) const
{
samples.clear();
int size_kernel = m_filter->get_size();
int half_size = size_kernel / 2;
int x_int = (int) (std::floor(x));
size_t init_x = std::max(0, x_int - half_size);
size_t end_x = std::min(x_int + half_size, (d ? int(width - 1) : int(height - 1)));
for (size_t i = init_x; i <= end_x; i++) {
samples.push_back(Real(i) + .5);
}
}
inline void draw_pixel(unsigned int x, unsigned int y, const Radiance& cv, Real w = -1.);
template<class Record>
inline void add_components(unsigned int x, unsigned int y, const Record& rec, Real w)
{
if (m_components && FilmComponents::DEPTH) {
Real dis = rec.distance * w;
m_depth_comp->add(x, y, &dis, 1);
}
if (m_components && FilmComponents::POSITIONS) {
VectorN<D> pos = rec.pos * w;
m_positions_comp->add(x, y, &pos[0], D);
}
if (m_components && FilmComponents::NORMALS) {
VectorN<D> normal = rec.normal * w;
m_normals_comp->add(x, y, &normal[0], D);
}
}
void average_and_write(FilmComponents comp, const char* name = nullptr);
public:
/* Constructs a Film with specified dimensions */
Film(unsigned w, unsigned h, Filter* _filter = nullptr,
FilmComponents comp = FilmComponents::RADIANCE) :
m_components(comp),
m_filter(_filter ? _filter : (new BoxFilter(1))),
m_image(),
m_weight(w, h, 1),
m_depth_comp(),
m_positions_comp(),
m_normals_comp(),
width(w),
height(h),
shift_x(0),
shift_y(0),
ratio(Real(w) / Real(h)),
xw2(Real(w) / 2.0),
yw2(Real(h) / 2.0),
averaged(false),
m_name("image"),
m_extension("hdr")
{
m_image.fill(Imaging::Image<Real>(width, height, Radiance::spectral_samples));
if (m_components && FilmComponents::DEPTH) {
m_depth_comp = std::make_unique<Imaging::Image<Real>>(width, height, 1);
}
if (m_components && FilmComponents::POSITIONS) {
m_positions_comp = std::make_unique<Imaging::Image<Real>>(width, height, D);
}
if (m_components && FilmComponents::NORMALS) {
m_normals_comp = std::make_unique<Imaging::Image<Real>>(width, height, D);
}
}
virtual ~Film()
{
}
virtual Real get_time_length() const
{
return 0.;
}
virtual Real get_time_offset() const
{
return 0.;
}
virtual unsigned int get_time_resolution() const
{
return 0;
}
virtual Real get_exposure_time() const
{
return 0.;
}
/* Returns width of Film */
int get_width() const
{
return width;
}
/* Returns height of Film */
int get_height() const
{
return height;
}
/** 2D transform from window coordinates to image coordinates.
Image coordinates are in the [-0.5, 0.5] x [-0.5/ratio, 0.5/ratio] range */
const Vector2 window_coords2image_coords(const Vector2& p) const
{
return Vector2((p[0] - xw2 + shift_x) / width, (p[1] - yw2 + shift_y) / height / ratio);
}
void set_shift(const unsigned int sx, const unsigned int sy)
{
shift_x = sx;
shift_y = sy;
}
void set_aspect_ratio(Real aspectRatioY)
{
ratio *= aspectRatioY;
}
// Allows setting the name of the streak images
virtual void set_name(const char *name, const char *ext)
{
m_name = std::string(name);
m_extension = std::string(ext);
}
virtual void add_sample(const Sample& sample, const RadianceSampleRecordR& rec)
{
averaged = false;
std::vector<Vector2> film_samples;
get_film_samples(sample.position, film_samples);
for (const Vector2& s : film_samples) {
Real w = m_filter->evaluate(s - sample.position) * sample.weight;
unsigned int sx = (unsigned int) (s[0]);
unsigned int sy = (unsigned int) (s[1]);
draw_pixel(sx, sy, rec.sample.radiance, w);
add_components(sx, sy, rec, w);
}
}
virtual void add_samples(const Sample& sample, const RadianceSampleRecordVectorR& rec)
{
averaged = false;
std::vector<Vector2> film_samples;
get_film_samples(sample.position, film_samples);
for (const Vector2& s : film_samples) {
Real w = m_filter->evaluate(s - sample.position) * sample.weight;
unsigned int sx = (unsigned int) (s[0]);
unsigned int sy = (unsigned int) (s[1]);
m_weight.add(sy, sx, &w);
// Now, we can iterate over all samples
for (const RadianceSampleR& s : rec.samples) {
draw_pixel(sx, sy, s.radiance * w, -1.);
}
add_components(sx, sy, rec, w);
}
}
virtual void average(FilmComponents comp = FilmComponents::ALL)
{
Film::average_and_write(comp & m_components);
averaged = true;
}
virtual void write(const char* name = nullptr)
{
name = (name) ? name : m_name.c_str();
Film::average_and_write(m_components, name);
averaged = true;
}
void clean()
{
for (size_t i = 0; i < Radiance::components; i++) {
m_image[i].clean();
}
if (m_components && FilmComponents::DEPTH) {
m_depth_comp->clean();
}
if (m_components && FilmComponents::POSITIONS) {
m_positions_comp->clean();
}
if (m_components && FilmComponents::NORMALS) {
m_normals_comp->clean();
}
}
public:
Imaging::Image<Real>& image(unsigned int i = 0)
{
return m_image[i];
}
}; /* class Film */
template<unsigned D, class Radiance>
void Film<D, Radiance>::draw_pixel(unsigned int x, unsigned int y, const Radiance& cv, Real w)
{
if (w > 0.) {
Radiance data = cv * w;
m_image[0].add(x, y, &data[0], Radiance::spectral_samples);
m_weight.add(x, y, &w, 1);
} else {
Radiance data = cv;
m_image[0].add(x, y, &data[0], Radiance::spectral_samples);
}
}
template<>
void Film<3, PolarizedLight<3>>::draw_pixel(unsigned int x, unsigned int y,
const PolarizedLight<3>& cv, Real w)
{
Real wp = 1.;
if (w > 0.) {
m_weight.add(x, y, &w, 1);
wp = w;
}
for (size_t c = 0; c < PolarizedLight<3>::components; c++) {
Spectrum data = cv[c] * wp;
m_image[c].add(x, y, &data[0], PolarizedLight<3>::spectral_samples);
}
}
template<unsigned D, class Radiance>
void Film<D, Radiance>:: average_and_write(FilmComponents comp, const char* name)
{
/* Image information */
Imaging::Image<Real>* out_image;
unsigned channels = 0, rad_components = 0;
/* Buffer to store the name */
char nimg[2048];
const char* ext;
/* Buffer for the name for each sub-component */
char nimg_comp[2048];
while (true) {
int nimg_size = 0;
if (name)
nimg_size += sprintf(nimg, "%s", name);
/* Component-specific information */
if (comp && FilmComponents::RADIANCE) {
comp = comp ^ FilmComponents::RADIANCE;
channels = Radiance::spectral_samples;
rad_components = Radiance::components;
ext = "hdr";
out_image = &m_image[0];
} else if (comp && FilmComponents::DEPTH) {
comp = comp ^ FilmComponents::DEPTH;
channels = 1;
rad_components = 1;
if (name)
nimg_size += sprintf(nimg + nimg_size, "_depth");
ext = "hdr";
out_image = m_depth_comp.get();
} else if (comp && FilmComponents::POSITIONS) {
comp = comp ^ FilmComponents::POSITIONS;
channels = D;
rad_components = 1;
if (name)
nimg_size += sprintf(nimg + nimg_size, "_positions");
ext = "raw";
out_image = m_positions_comp.get();
} else if (comp && FilmComponents::NORMALS) {
comp = comp ^ FilmComponents::NORMALS;
channels = D;
rad_components = 1;
if (name)
nimg_size += sprintf(nimg + nimg_size, "_normals");
ext = "raw";
out_image = m_normals_comp.get();
} else {
/* If not an individual component, ignore */
return;
}
/* Store all the sub-components */
for (size_t c = 0; c < rad_components; c++) {
if (!averaged) {
/* Compensate by filter weight */
out_image[c].weight(m_weight);
if (c != 0) {
/* Normalize value to 0..1, nonnegative */
out_image[c].weight(out_image[0]);
out_image[c].weight(2.0);
out_image[c].add(0.5);
}
}
if (name) {
int nimg_comp_size = 0;
if (rad_components > 1) {
nimg_comp_size += sprintf(nimg_comp, "%s_s%d",
nimg, unsigned(c));
} else {
nimg_comp_size += sprintf(nimg_comp, "%s", nimg);
}
/* Store all */
if (channels > 3) {
/* Using one image per channel */
for (size_t channel = 0; channel < channels; channel++) {
Imaging::Image<Real> channel_image =
out_image[c].channels(channel, channel);
sprintf(nimg_comp + nimg_comp_size, "channel%d.%s",
unsigned(channel), ext);
Imaging::save(channel_image, nimg_comp);
}
} else {
/* All RGB channels in a single image */
sprintf(nimg_comp + nimg_comp_size, ".%s", ext);
Imaging::save(out_image[c], nimg_comp);
}
}
}
}
}
#endif // _FILM_H_
|
cy-sohn/junkyard | opencv_filtering/runme.py | # -*- coding: utf-8 -*-
# Take snapshot using web camera, OpenCV and Tkinter.
import os
import tkinter as tk
from opencv.logic_logger import init_logging, logging
from opencv.gui_main import MainGUI
from opencv.logic_camera import MyValidationError
class TkErrorCatcher:
""" Handle MyValidationError in the tkinter mainloop """
def __init__(self, func, subst, widget):
self.func = func
self.subst = subst
self.widget = widget
def __call__(self, *args):
try:
if self.subst:
args = self.subst(*args)
return self.func(*args)
except MyValidationError as err: # handle MyValidationError in the mainloop
raise err
tk.CallWrapper = TkErrorCatcher # catch some validation errors
if __name__ == '__main__':
init_logging()
logging.info('Start software')
this_dir = os.path.dirname(os.path.realpath(__file__)) # path to this directory
os.chdir(this_dir) # make path to this dir the current path
try:
app = MainGUI(tk.Tk()) # start the application
app.mainloop() # application is up and running
except MyValidationError:
pass
finally:
logging.info('Finish software')
|
mdal-bot/MDAL | tests/unittests/test_mdal_utils.cpp | <gh_stars>0
/*
MDAL - Mesh Data Abstraction Library (MIT License)
Copyright (C) 2019 <NAME> (zilolv at gmail dot com)
*/
#include "gtest/gtest.h"
#include <limits>
#include <cmath>
#include <string>
#include <vector>
//mdal
#include "mdal.h"
#include "mdal_utils.hpp"
#include "mdal_testutils.hpp"
struct SplitTestData
{
SplitTestData( const std::string &input,
const std::vector<std::string> &results ):
mInput( input ), mExpectedResult( results ) {}
std::string mInput;
std::vector<std::string> mExpectedResult;
};
TEST( MdalUtilsTest, SplitString )
{
std::vector<SplitTestData> tests =
{
SplitTestData( "a;b;c", {"a", "b", "c"} ),
SplitTestData( "a;;b;c", {"a", "b", "c"} ),
SplitTestData( "a;b;", {"a", "b"} ),
SplitTestData( ";b;", {"b"} ),
SplitTestData( "a", {"a"} ),
SplitTestData( "", {} )
};
for ( const auto &test : tests )
{
EXPECT_EQ( test.mExpectedResult, MDAL::split( test.mInput, ";" ) );
}
// now test for string with multiple chars
std::vector<SplitTestData> tests2 =
{
SplitTestData( "a;;;b;c", {"a", "b;c"} ),
SplitTestData( "a;;;b;;;c", {"a", "b", "c"} ),
SplitTestData( "a;;b;c", {"a;;b;c"} ),
SplitTestData( "b;;;", {"b"} )
};
for ( const auto &test : tests2 )
{
EXPECT_EQ( test.mExpectedResult, MDAL::split( test.mInput, ";;;" ) );
}
}
TEST( MdalUtilsTest, SplitChar )
{
std::vector<SplitTestData> tests =
{
SplitTestData( "a;b;c", {"a", "b", "c"} ),
SplitTestData( "a;;b;c", {"a", "b", "c"} ),
SplitTestData( "a;b;", {"a", "b"} ),
SplitTestData( ";b;", {"b"} ),
SplitTestData( "a", {"a"} ),
SplitTestData( "", {} )
};
for ( const auto &test : tests )
{
EXPECT_EQ( test.mExpectedResult, MDAL::split( test.mInput, ';' ) );
}
}
TEST( MdalUtilsTest, TimeParsing )
{
std::vector<std::pair<std::string, double>> tests =
{
{ "seconds since 2001-05-05 00:00:00", 3600 },
{ "minutes since 2001-05-05 00:00:00", 60 },
{ "hours since 1900-01-01 00:00:0.0", 1 },
{ "hours", 1 },
{ "days since 1961-01-01 00:00:00", 1.0 / 24.0 },
{ "invalid format of time", 1 }
};
for ( const auto &test : tests )
{
EXPECT_EQ( test.second, MDAL::parseTimeUnits( test.first ) );
}
}
TEST( MdalUtilsTest, CF_TimeUnitParsing )
{
std::vector<std::pair<std::string, MDAL::RelativeTimestamp::Unit>> tests =
{
{ "seconds since 2001-05-05 00:00:00", MDAL::RelativeTimestamp::seconds },
{ "minutes since 2001-05-05 00:00:00", MDAL::RelativeTimestamp::minutes },
{ "hours since 1900-01-01 00:00:0.0", MDAL::RelativeTimestamp::hours },
{ "days since 1961-01-01 00:00:00", MDAL::RelativeTimestamp::days },
{ "weeks since 1961-01-01 00:00:00", MDAL::RelativeTimestamp::weeks },
{ "month since 1961-01-01 00:00:00", MDAL::RelativeTimestamp::months_CF },
{ "months since 1961-01-01 00:00:00", MDAL::RelativeTimestamp::months_CF },
{ "year since 1961-01-01 00:00:00", MDAL::RelativeTimestamp::exact_years },
};
for ( const auto &test : tests )
{
EXPECT_EQ( test.second, MDAL::parseCFTimeUnit( test.first ) );
}
}
TEST( MdalUtilsTest, CF_ReferenceTimePArsing )
{
std::vector<std::pair<std::string, MDAL::DateTime>> tests =
{
{ "seconds since 2001-05-05 00:00:00", MDAL::DateTime( 2001, 5, 5, 00, 00, 00 ) },
{ "hours since 1900-05-05 10:00:0.0", MDAL::DateTime( 1900, 5, 5, 10, 00, 00 ) },
{ "days since 1200-05-05 00:05:00", MDAL::DateTime( 1200, 5, 5, 00, 5, 00 ) },
{ "weeks since 1961-05-05 00:01:10", MDAL::DateTime( 1961, 5, 5, 00, 1, 10 ) },
};
for ( const auto &test : tests )
{
EXPECT_EQ( test.second, MDAL::parseCFReferenceTime( test.first, "gregorian" ) );
}
}
|
Snewmy/swordie | scripts/field/russianRoulette_enter.py | <filename>scripts/field/russianRoulette_enter.py
# using a map script cuz i cant get the clock to show up immediately after forcing a cc
sm.sendAutoEventClock() |
Pradeepkn/StationApp | Train/Train/TableCells/ImagesGalleryView.h | <filename>Train/Train/TableCells/ImagesGalleryView.h
//
// ImagesGalleryView.h
// Train
//
// Created by <NAME> on 10/18/16.
// Copyright © 2016 Pradeep. All rights reserved.
//
#import <UIKit/UIKit.h>
@interface ImagesGalleryView : UIView
@property (weak, nonatomic) IBOutlet UIImageView *imageView;
@end
|
Baneeishaque/Spring-Shop-Max | src/main/java/com/ecommerce/one/ecommerce/controller/WishListController.java | <gh_stars>0
package com.ecommerce.one.ecommerce.controller;
import com.ecommerce.one.ecommerce.domain.customer;
import com.ecommerce.one.ecommerce.domain.product;
import com.ecommerce.one.ecommerce.domain.wishlist;
import com.ecommerce.one.ecommerce.service.WishListService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import javax.servlet.http.HttpSession;
import java.util.List;
@Controller
public class WishListController {
@Autowired
private WishListService wishListService;
@GetMapping("wishlist")
public String wishlist(Model model, product Product){
List<wishlist> wishListProducts = wishListService.findAllProducts();
model.addAttribute("wishlist", wishListProducts);
return "whishlist";
}
@GetMapping("/saveToWishlist")
public String addToWishlist (@RequestParam("prodId") Integer prodId, HttpSession session) {
wishlist wishList = new wishlist();
wishList.setProductid(prodId);
customer user = (customer) session.getAttribute("user");
wishList.setCustomeriid(user.getCustomeriid());
wishListService.addToWishList(wishList);
return "redirect:/shop";
}
}
|
skymysky/jackrabbit | jackrabbit-jca/src/main/java/org/apache/jackrabbit/jca/JCAConnectionManager.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.jackrabbit.jca;
import javax.resource.ResourceException;
import javax.resource.spi.ConnectionManager;
import javax.resource.spi.ConnectionRequestInfo;
import javax.resource.spi.ManagedConnection;
import javax.resource.spi.ManagedConnectionFactory;
/**
* This class implements the default connection manager.
*/
public final class JCAConnectionManager implements ConnectionManager {
private static final long serialVersionUID = 1479445982219812432L;
/**
* The method allocateConnection gets called by the resource adapter's
* connection factory instance.
*/
public Object allocateConnection(ManagedConnectionFactory mcf, ConnectionRequestInfo cri)
throws ResourceException {
ManagedConnection mc = mcf.createManagedConnection(null, cri);
return mc.getConnection(null, cri);
}
}
|
daodao10/chart | cn/603777_d.js | <gh_stars>1-10
var data=[['20161012',11.214],
['20161013',12.414],
['20161014',13.736],
['20161017',15.186],
['20161018',16.786],
['20161019',18.543],
['20161020',20.479],
['20161021',22.607],
['20161024',24.950],
['20161025',27.521],
['20161026',30.350],
['20161027',33.464],
['20161028',36.893],
['20161031',40.664],
['20161101',42.671],
['20161102',47.014],
['20161103',46.093],
['20161104',44.836],
['20161107',45.529],
['20161108',45.021],
['20161109',48.379],
['20161110',53.293],
['20161111',50.329],
['20161114',46.471],
['20161115',45.986],
['20161116',44.350],
['20161117',44.500],
['20161118',43.686],
['20161121',45.243],
['20161122',44.793],
['20161123',45.943],
['20161124',43.064],
['20161125',41.779],
['20161128',41.136],
['20161129',40.036],
['20161130',39.379],
['20161201',43.393],
['20161202',43.457],
['20161205',40.593],
['20161206',41.186],
['20161207',42.643],
['20161208',41.114],
['20161209',40.393],
['20161212',37.650],
['20161213',37.700],
['20161214',36.514],
['20161215',37.157],
['20161216',40.950],
['20161219',38.550],
['20161220',38.950],
['20161221',39.621],
['20161222',39.414],
['20161223',39.586],
['20161226',40.864],
['20161227',40.136],
['20161228',38.807],
['20161229',37.536],
['20161230',37.136],
['20170103',37.593],
['20170104',37.514],
['20170105',37.493],
['20170106',34.421],
['20170109',32.707],
['20170110',32.707],
['20170111',31.357],
['20170112',30.400],
['20170113',30.071],
['20170116',27.300],
['20170117',29.257],
['20170118',27.986],
['20170119',28.350],
['20170120',28.571],
['20170123',28.757],
['20170124',27.514],
['20170125',27.779],
['20170126',27.793],
['20170203',27.871],
['20170206',29.193],
['20170207',29.129],
['20170208',29.864],
['20170209',29.943],
['20170210',29.050],
['20170213',29.393],
['20170214',29.279],
['20170215',30.029],
['20170216',29.429],
['20170217',28.343],
['20170220',27.721],
['20170221',28.443],
['20170222',28.707],
['20170223',29.029],
['20170224',29.307],
['20170227',29.771],
['20170228',29.993],
['20170301',30.864],
['20170302',30.221],
['20170303',29.729],
['20170306',30.386],
['20170307',31.350],
['20170308',30.886],
['20170309',31.364],
['20170310',31.121],
['20170313',31.793],
['20170314',31.357],
['20170315',30.700],
['20170316',31.379],
['20170317',30.757],
['20170320',32.236],
['20170321',32.329],
['20170322',33.300],
['20170323',34.664],
['20170324',33.993],
['20170327',32.921],
['20170328',32.607],
['20170329',30.071],
['20170330',28.143],
['20170331',28.314],
['20170405',28.686],
['20170406',28.514],
['20170407',28.050],
['20170410',26.121],
['20170411',26.557],
['20170412',26.071],
['20170413',26.114],
['20170414',24.843],
['20170417',23.193],
['20170418',22.200],
['20170419',22.779],
['20170420',22.786],
['20170421',22.521],
['20170424',21.414],
['20170425',21.557],
['20170426',23.793],
['20170427',25.414],
['20170428',24.786],
['20170502',24.593],
['20170503',25.214],
['20170504',24.579],
['20170505',24.264],
['20170508',23.843],
['20170509',23.586],
['20170510',23.600],
['20170511',24.529],
['20170512',24.457],
['20170515',25.207],
['20170516',25.843],
['20170517',25.643],
['20170518',24.750],
['20170519',24.793],
['20170522',22.850],
['20170523',21.500],
['20170524',21.929],
['20170525',21.950],
['20170526',22.621],
['20170531',22.971],
['20170601',21.664],
['20170602',23.064],
['20170605',23.286],
['20170606',23.886],
['20170607',24.164],
['20170608',23.450],
['20170609',24.379],
['20170612',23.450],
['20170613',24.986],
['20170614',26.257],
['20170615',26.671],
['20170616',25.829],
['20170619',25.664],
['20170620',25.564],
['20170621',24.950],
['20170622',24.793],
['20170623',25.779],
['20170626',25.957],
['20170627',25.493],
['20170628',25.600],
['20170629',25.550],
['20170630',25.986],
['20170703',25.850],
['20170704',25.429],
['20170705',25.379],
['20170706',24.936],
['20170707',26.071],
['20170710',25.086],
['20170711',23.793],
['20170712',23.693],
['20170713',23.593],
['20170714',23.300],
['20170717',21.136],
['20170718',21.871],
['20170719',21.921],
['20170720',21.836],
['20170721',21.829],
['20170724',22.200],
['20170725',22.321],
['20170726',21.979],
['20170727',22.771],
['20170728',22.500],
['20170731',22.493],
['20170801',22.350],
['20170802',21.786],
['20170803',21.893],
['20170804',21.636],
['20170807',21.786],
['20170808',21.821],
['20170809',22.036],
['20170810',21.650],
['20170811',21.293],
['20170814',21.614],
['20170815',21.736],
['20170816',22.114],
['20170817',22.129],
['20170818',22.350],
['20170821',22.464],
['20170822',22.743],
['20170823',22.221],
['20170824',22.350],
['20170825',22.564],
['20170828',23.043],
['20170829',23.300],
['20170830',22.743],
['20170831',22.971],
['20170901',22.843],
['20170904',22.786],
['20170905',22.579],
['20170906',22.286],
['20170907',22.364],
['20170908',22.193],
['20170911',22.757],
['20170912',22.279],
['20170913',22.543],
['20170914',22.300],
['20170915',22.129],
['20170918',22.714],
['20170919',22.579],
['20170920',22.771],
['20170921',23.221],
['20170922',22.964],
['20170925',21.779],
['20170926',21.821],
['20170927',21.843],
['20170928',21.543],
['20170929',21.729],
['20171009',21.864],
['20171010',22.157],
['20171011',22.193],
['20171012',22.793],
['20171013',23.264],
['20171016',22.436],
['20171017',24.736],
['20171018',24.371],
['20171019',23.943],
['20171020',23.114],
['20171023',23.700],
['20171024',24.129],
['20171025',24.029],
['20171026',23.557],
['20171027',23.679],
['20171030',22.300],
['20171031',22.350],
['20171101',22.129],
['20171102',22.057],
['20171103',22.093],
['20171106',23.164],
['20171107',23.371],
['20171108',23.371],
['20171109',23.257],
['20171110',22.714],
['20171113',22.443],
['20171114',22.250],
['20171115',22.357],
['20171116',22.321],
['20171117',21.021],
['20171120',20.907],
['20171121',21.193],
['20171122',20.736],
['20171123',20.007],
['20171124',20.114],
['20171127',19.571],
['20171128',19.771],
['20171129',19.621],
['20171130',19.350],
['20171201',19.400],
['20171204',18.721],
['20171205',18.036],
['20171206',18.221],
['20171207',18.264],
['20171208',19.314],
['20171211',19.107],
['20171212',18.771],
['20171213',18.893],
['20171214',19.079],
['20171215',19.000],
['20171218',18.379],
['20171219',18.543],
['20171220',18.800],
['20171221',18.464],
['20171222',18.464],
['20171225',17.736],
['20171226',18.207],
['20171227',18.157],
['20171228',18.900],
['20171229',18.571],
['20180102',18.550],
['20180103',18.650],
['20180104',18.893],
['20180105',18.750],
['20180108',18.750],
['20180109',18.971],
['20180110',18.579],
['20180111',18.664],
['20180112',18.543],
['20180115',17.886],
['20180116',18.129],
['20180117',18.250],
['20180118',18.293],
['20180119',18.286],
['20180122',18.786],
['20180123',18.664],
['20180124',18.714],
['20180125',18.557],
['20180126',18.686],
['20180129',18.564],
['20180130',18.757],
['20180131',18.893],
['20180201',16.950],
['20180202',15.921],
['20180205',15.757],
['20180206',14.129],
['20180207',14.400],
['20180208',14.600],
['20180209',14.200],
['20180212',14.521],
['20180213',14.514],
['20180214',14.543],
['20180222',14.829],
['20180223',14.921],
['20180226',15.407],
['20180227',15.414],
['20180228',15.286],
['20180301',15.414],
['20180302',15.371],
['20180305',15.257],
['20180306',15.557],
['20180307',15.300],
['20180308',15.429],
['20180309',15.850],
['20180312',16.100],
['20180313',15.886],
['20180314',15.743],
['20180315',15.314],
['20180316',15.743],
['20180319',15.643],
['20180320',15.621],
['20180321',15.907],
['20180322',16.507],
['20180323',15.007],
['20180326',14.893],
['20180327',15.143],
['20180328',15.121],
['20180329',15.521],
['20180330',15.771],
['20180402',15.621],
['20180403',15.414],
['20180404',15.643],
['20180409',15.479],
['20180410',15.864],
['20180411',16.071],
['20180412',16.250],
['20180413',16.686],
['20180416',16.086],
['20180417',15.579],
['20180418',15.600],
['20180419',15.507],
['20180420',14.986],
['20180423',14.921],
['20180424',15.229],
['20180425',15.286],
['20180426',14.800],
['20180427',14.621],
['20180502',14.371],
['20180503',14.671],
['20180504',14.750],
['20180507',15.021],
['20180508',15.514],
['20180509',15.479],
['20180510',15.979],
['20180511',15.386],
['20180514',15.293],
['20180515',16.129],
['20180516',17.321],
['20180517',16.550],
['20180518',18.257],
['20180521',18.636],
['20180522',18.436],
['20180523',17.886],
['20180524',17.779],
['20180525',18.050],
['20180528',17.971],
['20180529',17.300],
['20180530',17.064],
['20180531',18.821],
['20180601',18.721],
['20180604',18.450],
['20180605',18.743],
['20180606',18.980],
['20180607',17.940],
['20180608',17.420],
['20180611',17.110],
['20180612',18.850],
['20180613',20.760],
['20180614',19.400],
['20180615',18.770],
['20180619',16.870],
['20180620',17.870],
['20180621',18.510],
['20180622',18.630],
['20180625',19.510],
['20180626',19.450],
['20180627',18.710],
['20180628',17.560],
['20180629',18.180],
['20180702',18.750],
['20180703',18.610],
['20180704',18.430],
['20180705',16.970],
['20180706',16.680],
['20180709',16.870],
['20180710',16.780],
['20180711',15.660],
['20180712',16.040],
['20180713',16.280],
['20180716',16.020],
['20180717',16.090],
['20180718',16.480],
['20180719',15.980],
['20180720',15.990],
['20180723',15.940],
['20180724',16.320],
['20180725',16.370],
['20180726',16.400],
['20180727',16.250],
['20180730',15.570],
['20180731',15.470],
['20180801',15.760],
['20180802',14.810],
['20180803',14.930],
['20180806',13.770],
['20180807',13.650],
['20180808',12.610],
['20180809',12.640],
['20180810',12.910],
['20180813',13.150],
['20180814',13.070],
['20180815',12.830],
['20180816',12.540],
['20180817',12.030],
['20180820',12.070],
['20180821',12.310],
['20180822',11.900],
['20180823',12.190],
['20180824',12.030],
['20180827',12.200],
['20180828',11.990],
['20180829',11.970],
['20180830',11.740],
['20180831',11.130],
['20180903',11.330],
['20180904',11.700],
['20180905',11.320],
['20180906',11.320],
['20180907',11.450],
['20180910',10.880],
['20180911',11.090],
['20180912',11.300],
['20180913',11.260],
['20180914',10.970],
['20180917',10.870],
['20180918',11.040],
['20180919',11.130],
['20180920',11.080],
['20180921',11.680],
['20180925',11.330],
['20180926',11.350],
['20180927',10.960],
['20180928',11.060],
['20181008',10.600],
['20181009',10.660],
['20181010',10.770],
['20181011',9.680],
['20181012',9.250],
['20181015',8.980],
['20181016',8.950],
['20181017',9.060],
['20181018',9.000],
['20181019',9.280],
['20181022',9.710],
['20181023',9.510],
['20181024',9.670],
['20181025',9.510],
['20181026',9.520],
['20181029',9.350],
['20181030',9.450],
['20181031',9.640],
['20181101',9.680],
['20181102',9.980],
['20181105',10.390],
['20181106',10.250],
['20181107',10.200],
['20181108',10.140],
['20181109',10.050],
['20181112',10.270],
['20181113',10.410],
['20181114',10.380],
['20181115',10.600],
['20181116',10.930],
['20181119',11.010],
['20181120',10.470],
['20181121',10.530],
['20181122',10.550],
['20181123',9.970],
['20181126',10.480],
['20181127',10.340],
['20181128',10.350],
['20181129',9.960],
['20181130',10.050],
['20181203',10.460],
['20181204',10.860],
['20181205',10.690],
['20181206',10.440],
['20181207',10.520],
['20181210',10.770],
['20181211',10.640],
['20181212',10.590],
['20181213',10.600],
['20181214',10.490],
['20181217',10.040],
['20181218',9.990],
['20181219',9.790],
['20181220',9.820],
['20181221',9.850],
['20181224',9.850],
['20181225',9.580],
['20181226',9.550],
['20181227',9.300],
['20181228',9.380],
['20190102',9.560],
['20190103',9.530],
['20190104',9.740],
['20190107',9.890],
['20190108',10.050],
['20190109',9.920],
['20190110',9.920],
['20190111',10.080],
['20190114',10.000],
['20190115',10.140],
['20190116',11.180],
['20190117',10.990],
['20190118',10.770],
['20190121',10.750],
['20190122',10.530],
['20190123',10.560],
['20190124',10.890],
['20190125',10.760],
['20190128',10.950],
['20190129',10.990],
['20190130',10.020],
['20190131',9.420],
['20190201',9.690],
['20190211',9.900],
['20190212',10.000],
['20190213',10.090],
['20190214',10.070],
['20190215',10.230],
['20190218',10.530],
['20190219',10.470],
['20190220',10.640],
['20190221',10.650],
['20190222',10.720],
['20190225',11.120],
['20190226',11.050],
['20190227',11.010],
['20190228',11.050],
['20190301',10.980],
['20190304',11.050],
['20190305',11.250],
['20190306',11.550],
['20190307',11.790],
['20190308',10.950],
['20190311',11.310],
['20190312',11.490],
['20190313',11.580],
['20190314',11.250],
['20190315',11.650],
['20190318',12.090],
['20190319',11.820],
['20190320',11.720],
['20190321',11.660],
['20190322',11.950],
['20190325',11.610],
['20190326',11.100],
['20190327',11.340],
['20190328',11.090],
['20190329',11.420],
['20190401',11.760],
['20190402',12.240],
['20190403',12.640],
['20190404',12.350],
['20190408',12.190],
['20190409',12.160],
['20190410',12.050],
['20190411',12.290],
['20190412',12.120],
['20190415',11.740],
['20190416',11.690],
['20190417',11.880],
['20190418',11.720],
['20190419',11.880],
['20190422',11.950],
['20190423',12.190],
['20190424',12.600],
['20190425',11.730],
['20190426',12.930],
['20190429',12.650],
['20190430',13.240],
['20190506',14.590],
['20190507',16.070],
['20190508',17.700],
['20190509',15.910],
['20190510',15.190],
['20190513',15.460],
['20190514',14.250],
['20190515',15.170],
['20190516',14.840],
['20190517',15.350],
['20190520',13.790],
['20190521',13.210],
['20190522',12.820],
['20190523',12.110],
['20190524',12.120],
['20190527',12.520],
['20190528',12.420],
['20190529',12.840],
['20190530',13.020],
['20190531',12.500],
['20190603',12.060],
['20190604',12.000],
['20190605',12.420],
['20190606',12.600],
['20190610',12.940],
['20190611',14.020],
['20190612',13.450],
['20190613',13.610],
['20190614',12.830],
['20190617',13.000],
['20190618',12.630],
['20190619',12.820],
['20190620',12.990],
['20190621',13.590],
['20190624',13.420],
['20190625',13.220],
['20190626',13.760],
['20190627',14.070],
['20190628',14.010],
['20190701',14.740],
['20190702',15.120],
['20190703',15.160],
['20190704',14.250],
['20190705',14.420],
['20190708',14.980],
['20190709',14.240],
['20190710',13.710],
['20190711',13.890],
['20190712',13.980],
['20190715',14.320],
['20190716',14.100],
['20190717',13.670],
['20190718',13.100],
['20190719',13.040],
['20190722',12.410],
['20190723',12.700],
['20190724',12.830],
['20190725',13.180],
['20190726',12.920],
['20190729',12.860],
['20190730',12.940],
['20190731',12.720],
['20190801',12.900],
['20190802',12.340],
['20190805',12.230],
['20190806',12.300],
['20190807',11.980],
['20190808',11.970],
['20190809',11.900],
['20190812',12.300],
['20190813',12.220],
['20190814',12.160],
['20190815',12.160],
['20190816',12.170],
['20190819',12.430],
['20190820',12.350],
['20190821',12.410],
['20190822',12.260],
['20190823',12.130],
['20190826',11.960],
['20190827',12.400],
['20190828',13.380],
['20190829',12.690],
['20190830',12.300],
['20190902',12.540],
['20190903',12.530],
['20190904',12.550],
['20190905',12.640],
['20190906',12.820],
['20190909',12.990],
['20190910',13.190],
['20190911',12.800],
['20190912',12.850],
['20190916',12.750],
['20190917',12.460],
['20190918',12.890],
['20190919',13.100],
['20190920',13.350],
['20190923',13.300],
['20190924',13.000],
['20190925',14.310],
['20190926',13.900],
['20190927',13.570],
['20190930',13.370],
['20191008',12.250],
['20191009',11.960],
['20191010',12.010],
['20191011',11.960],
['20191014',12.190],
['20191015',11.920],
['20191016',11.710],
['20191017',12.020],
['20191018',12.430],
['20191021',12.370],
['20191022',12.400],
['20191023',12.160],
['20191024',11.980],
['20191025',12.120],
['20191028',11.570],
['20191029',11.410],
['20191030',11.070],
['20191031',11.100],
['20191101',11.250],
['20191104',11.100],
['20191105',11.110],
['20191106',10.900],
['20191107',10.920],
['20191108',10.830],
['20191111',10.510],
['20191112',10.580],
['20191113',10.520],
['20191114',10.600],
['20191115',10.380],
['20191118',10.210],
['20191119',10.510],
['20191120',10.650],
['20191121',10.580],
['20191122',10.410],
['20191125',10.300],
['20191126',10.210],
['20191127',10.140],
['20191128',10.090],
['20191129',10.090],
['20191202',10.250],
['20191203',10.310],
['20191204',10.330],
['20191205',10.350],
['20191206',10.540],
['20191209',10.550],
['20191210',10.650],
['20191211',10.570],
['20191212',10.990],
['20191213',10.930],
['20191216',10.970],
['20191217',11.030],
['20191218',11.200],
['20191219',11.650],
['20191220',11.520],
['20191223',11.200],
['20191224',11.590],
['20191225',11.480],
['20191226',11.470],
['20191227',11.700],
['20191230',11.600],
['20191231',11.670],
['20200102',12.530],
['20200103',12.410],
['20200106',12.870],
['20200107',12.520],
['20200108',12.090],
['20200109',12.190],
['20200110',12.520],
['20200113',12.520],
['20200114',12.350],
['20200115',12.120],
['20200116',12.110],
['20200117',11.980],
['20200120',12.040],
['20200121',11.710],
['20200122',11.440],
['20200123',10.910],
['20200203',9.810],
['20200204',9.280],
['20200205',9.860],
['20200206',9.980],
['20200207',9.920],
['20200210',10.120],
['20200211',9.970],
['20200212',10.190],
['20200213',9.960],
['20200214',9.940],
['20200217',10.230],
['20200218',10.760],
['20200219',10.790],
['20200220',11.360],
['20200221',11.260],
['20200224',11.310],
['20200225',11.100],
['20200226',10.940],
['20200227',11.210],
['20200228',10.410],
['20200302',10.760],
['20200303',10.810],
['20200304',11.480],
['20200305',11.900],
['20200306',11.510],
['20200309',11.120],
['20200310',11.330],
['20200311',11.510],
['20200312',12.110],
['20200313',11.910],
['20200316',12.100],
['20200317',12.850],
['20200318',12.440],
['20200319',12.600],
['20200320',12.850],
['20200323',11.860],
['20200324',12.240],
['20200325',12.990],
['20200326',12.790],
['20200327',12.290],
['20200330',11.900],
['20200331',12.510],
['20200401',11.900],
['20200402',11.690],
['20200403',11.560],
['20200407',12.000],
['20200408',12.150],
['20200409',12.560],
['20200410',12.500],
['20200413',12.670],
['20200414',13.130],
['20200415',12.820],
['20200416',12.840],
['20200417',12.420],
['20200420',12.560],
['20200421',13.830],
['20200422',15.220],
['20200423',15.080],
['20200424',14.130],
['20200427',13.740],
['20200428',13.840],
['20200429',13.300],
['20200430',13.480],
['20200506',14.840],
['20200507',16.330],
['20200508',16.610],
['20200511',16.560],
['20200512',16.830],
['20200513',17.040],
['20200514',18.750],
['20200515',18.040],
['20200518',18.160],
['20200519',19.020],
['20200520',17.480],
['20200521',16.990],
['20200522',16.690],
['20200525',17.700],
['20200526',18.780],
['20200527',18.550],
['20200528',18.140],
['20200529',18.480],
['20200601',18.980],
['20200602',17.950],
['20200603',17.890],
['20200604',17.910],
['20200605',16.900],
['20200608',16.800],
['20200609',16.850],
['20200610',16.770],
['20200611',16.220],
['20200612',16.690],
['20200615',16.440],
['20200616',16.650],
['20200617',16.940],
['20200618',16.540],
['20200619',16.530],
['20200622',16.740],
['20200623',17.000],
['20200624',16.570],
['20200629',16.300],
['20200630',16.720],
['20200701',17.800],
['20200702',17.740],
['20200703',17.550],
['20200706',17.700],
['20200707',18.030],
['20200708',18.100],
['20200709',19.090],
['20200710',18.730],
['20200713',20.610],
['20200714',20.900],
['20200715',20.600],
['20200716',18.550],
['20200717',18.130],
['20200720',18.600],
['20200721',18.590],
['20200722',19.470],
['20200723',19.360],
['20200724',17.920],
['20200727',17.260],
['20200728',17.740],
['20200729',18.510],
['20200730',18.460],
['20200731',19.100],
['20200803',21.010],
['20200804',20.000],
['20200805',21.210],
['20200806',20.840],
['20200807',20.010],
['20200810',19.990],
['20200811',20.100],
['20200812',19.110],
['20200813',18.760],
['20200814',19.110],
['20200817',19.390],
['20200818',19.720],
['20200819',20.160],
['20200820',20.250],
['20200821',21.690],
['20200824',21.700],
['20200825',20.690],
['20200826',19.200],
['20200827',20.300],
['20200828',18.270],
['20200831',17.380],
['20200901',17.000],
['20200902',17.030],
['20200903',16.400],
['20200904',16.030],
['20200907',16.200],
['20200908',16.260],
['20200909',15.680],
['20200910',15.010],
['20200911',15.400],
['20200914',15.310],
['20200915',15.400],
['20200916',15.060],
['20200917',15.080],
['20200918',15.280],
['20200921',15.880],
['20200922',15.490],
['20200923',15.430],
['20200924',14.890],
['20200925',14.690],
['20200928',14.360],
['20200929',14.520],
['20200930',14.490]];
var source='wstock.net'; |
olleolleolle/docker-template | spec/rspec/helper.rb | <reponame>olleolleolle/docker-template<filename>spec/rspec/helper.rb
# Frozen-string-literal: true
# Copyright: 2015 - 2016 <NAME> - Apache v2.0 License
# Encoding: utf-8
ENV.delete("CI")
require "support/coverage"
require "luna/rspec/formatters/checks"
require "docker/template"
require "rspec/helpers"
ENV["RSPEC_RUNNING"] ||= "true"
Dir[File.expand_path("../../support/**/*.rb", __FILE__)].each do |f|
require f
end
|
1690296356/jdk | test/jdk/sun/security/pkcs11/Cipher/TestChaChaPolyNoReuse.java | /*
* Copyright (c) 2021, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code 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
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/**
* @test
* @bug 8255410
* @library /test/lib ..
* @run main/othervm TestChaChaPolyNoReuse
* @summary Test PKCS#11 ChaCha20-Poly1305 Cipher Implementation
* (key/nonce reuse check)
*/
import java.util.*;
import javax.crypto.Cipher;
import java.security.spec.AlgorithmParameterSpec;
import java.security.Provider;
import java.security.NoSuchAlgorithmException;
import javax.crypto.spec.ChaCha20ParameterSpec;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import javax.crypto.AEADBadTagException;
import javax.crypto.SecretKey;
import java.security.InvalidKeyException;
import java.security.InvalidAlgorithmParameterException;
public class TestChaChaPolyNoReuse extends PKCS11Test {
private static final String KEY_ALGO = "ChaCha20";
private static final String CIPHER_ALGO = "ChaCha20-Poly1305";
/**
* Basic TestMethod interface definition
*/
public interface TestMethod {
/**
* Runs the actual test case
*
* @param provider the provider to provide the requested Cipher obj.
*
* @return true if the test passes, false otherwise.
*/
boolean run(Provider p);
}
public static class TestData {
public TestData(String name, String keyStr, String nonceStr, int ctr,
int dir, String inputStr, String aadStr, String outStr) {
testName = Objects.requireNonNull(name);
HexFormat hex = HexFormat.of();
key = hex.parseHex(keyStr);
nonce = hex.parseHex(nonceStr);
if ((counter = ctr) < 0) {
throw new IllegalArgumentException(
"counter must be 0 or greater");
}
direction = dir;
if (direction != Cipher.ENCRYPT_MODE) {
throw new IllegalArgumentException(
"Direction must be ENCRYPT_MODE");
}
input = hex.parseHex(inputStr);
aad = (aadStr != null) ? hex.parseHex(aadStr) : null;
expOutput = hex.parseHex(outStr);
}
public final String testName;
public final byte[] key;
public final byte[] nonce;
public final int counter;
public final int direction;
public final byte[] input;
public final byte[] aad;
public final byte[] expOutput;
}
public static final List<TestData> aeadTestList =
new LinkedList<TestData>() {{
add(new TestData("RFC 7539 Sample AEAD Test Vector",
"808182838485868788898a8b8c8d8e8f909192939495969798999a9b9c9d9e9f",
"070000004041424344454647",
1, Cipher.ENCRYPT_MODE,
"4c616469657320616e642047656e746c656d656e206f662074686520636c6173" +
"73206f66202739393a204966204920636f756c64206f6666657220796f75206f" +
"6e6c79206f6e652074697020666f7220746865206675747572652c2073756e73" +
"637265656e20776f756c642062652069742e",
"50515253c0c1c2c3c4c5c6c7",
"d31a8d34648e60db7b86afbc53ef7ec2a4aded51296e08fea9e2b5a736ee62d6" +
"3dbea45e8ca9671282fafb69da92728b1a71de0a9e060b2905d6a5b67ecd3b36" +
"92ddbd7f2d778b8c9803aee328091b58fab324e4fad675945585808b4831d7bc" +
"3ff4def08e4b7a9de576d26586cec64b61161ae10b594f09e26a7e902ecbd060" +
"0691"));
}};
/**
* Make sure we do not use this Cipher object without initializing it
* at all
*/
public static final TestMethod noInitTest = new TestMethod() {
@Override
public boolean run(Provider p) {
System.out.println("----- No Init Test -----");
try {
Cipher cipher = Cipher.getInstance(CIPHER_ALGO, p);
TestData testData = aeadTestList.get(0);
// Attempting to use the cipher without initializing it
// should throw an IllegalStateException
try {
cipher.updateAAD(testData.aad);
throw new RuntimeException(
"Expected IllegalStateException not thrown");
} catch (IllegalStateException ise) {
// Do nothing, this is what we expected to happen
}
} catch (Exception exc) {
System.out.println("Unexpected exception: " + exc);
exc.printStackTrace();
return false;
}
return true;
}
};
/**
* Attempt to run two full encryption operations without an init in
* between.
*/
public static final TestMethod encTwiceNoInit = new TestMethod() {
@Override
public boolean run(Provider p) {
System.out.println("----- Encrypt 2nd time without init -----");
try {
AlgorithmParameterSpec spec;
Cipher cipher = Cipher.getInstance(CIPHER_ALGO, p);
TestData testData = aeadTestList.get(0);
spec = new IvParameterSpec(testData.nonce);
SecretKey key = new SecretKeySpec(testData.key, KEY_ALGO);
// Initialize and encrypt
cipher.init(testData.direction, key, spec);
cipher.updateAAD(testData.aad);
cipher.doFinal(testData.input);
System.out.println("First encryption complete");
// Now attempt to encrypt again without changing the key/IV
// This should fail.
try {
cipher.updateAAD(testData.aad);
} catch (IllegalStateException ise) {
// Do nothing, this is what we expected to happen
}
try {
cipher.doFinal(testData.input);
throw new RuntimeException(
"Expected IllegalStateException not thrown");
} catch (IllegalStateException ise) {
// Do nothing, this is what we expected to happen
}
} catch (Exception exc) {
System.out.println("Unexpected exception: " + exc);
exc.printStackTrace();
return false;
}
return true;
}
};
/**
* Encrypt once successfully, then attempt to init with the same
* key and nonce.
*/
public static final TestMethod encTwiceInitSameParams = new TestMethod() {
@Override
public boolean run(Provider p) {
System.out.println("----- Encrypt, then init with same params " +
"-----");
try {
AlgorithmParameterSpec spec;
Cipher cipher = Cipher.getInstance(CIPHER_ALGO, p);
TestData testData = aeadTestList.get(0);
spec = new IvParameterSpec(testData.nonce);
SecretKey key = new SecretKeySpec(testData.key, KEY_ALGO);
// Initialize then encrypt
cipher.init(testData.direction, key, spec);
cipher.updateAAD(testData.aad);
cipher.doFinal(testData.input);
System.out.println("First encryption complete");
// Initializing after the completed encryption with
// the same key and nonce should fail.
try {
cipher.init(testData.direction, key, spec);
throw new RuntimeException(
"Expected IKE or IAPE not thrown");
} catch (InvalidKeyException |
InvalidAlgorithmParameterException e) {
// Do nothing, this is what we expected to happen
}
} catch (Exception exc) {
System.out.println("Unexpected exception: " + exc);
exc.printStackTrace();
return false;
}
return true;
}
};
public static final List<TestMethod> testMethodList =
Arrays.asList(noInitTest, encTwiceNoInit, encTwiceInitSameParams);
@Override
public void main(Provider p) throws Exception {
System.out.println("Testing " + p.getName());
try {
Cipher.getInstance(CIPHER_ALGO, p);
} catch (NoSuchAlgorithmException nsae) {
System.out.println("Skip; no support for " + CIPHER_ALGO);
return;
}
int testsPassed = 0;
int testNumber = 0;
for (TestMethod tm : testMethodList) {
testNumber++;
boolean result = tm.run(p);
System.out.println("Result: " + (result ? "PASS" : "FAIL"));
if (result) {
testsPassed++;
}
}
System.out.println("Total Tests: " + testNumber +
", Tests passed: " + testsPassed);
if (testsPassed < testNumber) {
throw new RuntimeException(
"Not all tests passed. See output for failure info");
}
}
public static void main(String[] args) throws Exception {
main(new TestChaChaPolyNoReuse(), args);
}
}
|
yury-s/v8-inspector | Source/chrome/tools/telemetry/telemetry/user_story/user_story_unittest.py | # Copyright 2014 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import unittest
from telemetry.story import shared_state
from telemetry import user_story
# pylint: disable=abstract-method
class SharedStateBar(shared_state.SharedState):
pass
class UserStoryFoo(user_story.UserStory):
def __init__(self, name='', labels=None):
super(UserStoryFoo, self).__init__(
SharedStateBar, name, labels)
class UserStoryTest(unittest.TestCase):
def testUserStoriesHaveDifferentIds(self):
u0 = user_story.UserStory(SharedStateBar, 'foo')
u1 = user_story.UserStory(SharedStateBar, 'bar')
self.assertNotEqual(u0.id, u1.id)
def testNamelessUserStoryDisplayName(self):
u = UserStoryFoo()
self.assertEquals('UserStoryFoo', u.display_name)
def testNamedUserStoryDisplayName(self):
u = UserStoryFoo('Bar')
self.assertEquals('Bar', u.display_name)
def testUserStoryFileSafeName(self):
u = UserStoryFoo('Foo Bar:Baz~0')
self.assertEquals('Foo_Bar_Baz_0', u.file_safe_name)
def testNamelessUserStoryAsDict(self):
u = user_story.UserStory(SharedStateBar)
u_dict = u.AsDict()
self.assertEquals(u_dict['id'], u.id)
self.assertNotIn('name', u_dict)
def testNamedUserStoryAsDict(self):
u = user_story.UserStory(SharedStateBar, 'Foo')
u_dict = u.AsDict()
self.assertEquals(u_dict['id'], u.id)
self.assertEquals('Foo', u_dict['name'])
def testMakeJavaScriptDeterministic(self):
u = user_story.UserStory(SharedStateBar)
self.assertTrue(u.make_javascript_deterministic)
u = user_story.UserStory(
SharedStateBar, make_javascript_deterministic=False)
self.assertFalse(u.make_javascript_deterministic)
u = user_story.UserStory(
SharedStateBar, make_javascript_deterministic=True)
self.assertTrue(u.make_javascript_deterministic)
|
kzborisov/SoftUni | 2. Programming Fundamentals With Python (May 2021)/21. Exercise - Dictionaries/04_legendary_farming.py | <reponame>kzborisov/SoftUni<filename>2. Programming Fundamentals With Python (May 2021)/21. Exercise - Dictionaries/04_legendary_farming.py
def add_to_junk(key_materials_dict, material_to_add, qty_to_add):
if material_to_add not in key_materials_dict:
key_materials_dict[material_to_add] = qty_to_add
else:
key_materials_dict[material_to_add] += qty_to_add
def is_item_obtained():
global item_obtained
if key_materials['shards'] >= 250:
item_obtained = "Shadowmourne"
key_materials['shards'] -= 250
return True
elif key_materials['fragments'] >= 250:
item_obtained = "Valanyr"
key_materials['fragments'] -= 250
return True
elif key_materials['motes'] >= 250:
item_obtained = "Dragonwrath"
key_materials['motes'] -= 250
return True
return False
key_materials = {"shards": 0, "fragments": 0, "motes": 0}
junk = {}
item_obtained = ""
while not item_obtained:
materials = input().split()
for i in range(0, len(materials), 2):
qty = int(materials[i])
material = materials[i+1].lower()
if material in key_materials:
key_materials[material] += qty
else:
add_to_junk(junk, material, qty)
if is_item_obtained():
break
print(f"{item_obtained} obtained!")
for k, v in sorted(key_materials.items(), key=lambda kvp: (-kvp[1], kvp[0])):
print(f"{k}: {v}")
for k, v in sorted(junk.items(), key=lambda kvp: kvp[0]):
print(f"{k}: {v}")
|
sempr-tk/rete | test/GlobalConstants.cpp | #include <iostream>
#include <fstream>
#include "../rete-reasoner/Reasoner.hpp"
#include "../rete-reasoner/RuleParser.hpp"
#include "../rete-rdf/ReteRDF.hpp"
using namespace rete;
namespace {
void save(Network& net, const std::string& filename)
{
std::ofstream out(filename);
out << net.toDot();
out.close();
}
bool containsTriple(Reasoner& reasoner,
const std::string& s, const std::string& p, const std::string& o)
{
auto wmes = reasoner.getCurrentState().getWMEs();
for (auto wme : wmes)
{
auto triple = std::dynamic_pointer_cast<Triple>(wme);
if (triple &&
triple->subject == s &&
triple->predicate == p &&
triple->object == o)
{
return true;
}
}
return false;
}
// save(reasoner.net(), __func__ + std::string(".dot"));
bool global_const_allows_string()
{
RuleParser p;
Reasoner reasoner;
auto rules = p.parseRules(
"$foo : \"Hello, World\"\n"
"[true() -> print(\"dummy\")]",
reasoner.net()
);
return true;
}
bool global_const_allows_number()
{
RuleParser p;
Reasoner reasoner;
auto rules = p.parseRules(
"$foo : 3.14159"
"[true() -> print(\"dummy\")]",
reasoner.net()
);
return true;
}
bool global_const_allows_full_uri()
{
RuleParser p;
Reasoner reasoner;
auto rules = p.parseRules(
"$foo : <http://something.com/plex/this#that>"
"[true() -> print(\"dummy\")]",
reasoner.net()
);
return true;
}
bool global_const_allows_shorthand_uri()
{
RuleParser p;
Reasoner reasoner;
auto rules = p.parseRules(
"@PREFIX something: <http://something.com/plex/this#>\n"
"$foo : something:that"
"[true() -> print(\"dummy\")]",
reasoner.net()
);
return true;
}
bool global_const_string_can_be_used_in_triple_condition()
{
RuleParser p;
Reasoner reasoner;
auto rules = p.parseRules(
"$foo : \"Hello, World!\""
"[(?a ?b $foo) -> (<test> <is> <successfull>)]",
reasoner.net()
);
auto data = p.parseRules(
"[true() -> (<foo> <bar> \"Hello, World!\")]",
reasoner.net()
);
reasoner.performInference();
save(reasoner.net(), __func__ + std::string(".dot"));
return containsTriple(reasoner, "<test>", "<is>", "<successfull>");
}
bool global_const_number_can_be_used_in_triple_condition()
{
RuleParser p;
Reasoner reasoner;
auto rules = p.parseRules(
"$foo : 3.14159"
"[(?a ?b $foo) -> (<test> <is> <successfull>)]",
reasoner.net()
);
auto data = p.parseRules(
"[true() -> (<foo> <bar> 3.14159)]",
reasoner.net()
);
reasoner.performInference();
save(reasoner.net(), __func__ + std::string(".dot"));
return containsTriple(reasoner, "<test>", "<is>", "<successfull>");
}
bool global_const_shorthand_uri_can_be_used_in_triple_condition()
{
RuleParser p;
Reasoner reasoner;
auto rules = p.parseRules(
"@PREFIX something: <http://something.com/plex/this#>\n"
"$foo : something:that\n"
"[(?a ?b $foo) -> (<test> <is> <successfull>)]",
reasoner.net()
);
auto data = p.parseRules(
"[true() -> (<foo> <bar> <http://something.com/plex/this#that>)]",
reasoner.net()
);
reasoner.performInference();
save(reasoner.net(), __func__ + std::string(".dot"));
return containsTriple(reasoner, "<test>", "<is>", "<successfull>");
}
bool global_const_number_can_be_used_in_math_builtin()
{
RuleParser p;
Reasoner reasoner;
auto rules = p.parseRules(
"$foo : 21\n"
"[true(), sum(?s $foo $foo) -> (<the-answer> <is> ?s)]",
reasoner.net()
);
reasoner.performInference();
save(reasoner.net(), __func__ + std::string(".dot"));
return containsTriple(reasoner, "<the-answer>", "<is>", std::to_string(42));
}
bool global_const_string_can_be_used_in_triple_consequence()
{
RuleParser p;
Reasoner reasoner;
auto rules = p.parseRules(
"$foo : \"Hello, World!\"\n"
"[true() -> (<greeting> <message> $foo)]",
reasoner.net()
);
reasoner.performInference();
save(reasoner.net(), __func__ + std::string(".dot"));
return containsTriple(reasoner, "<greeting>", "<message>", "\"Hello, World!\"");
}
#define TEST(function) \
{ \
bool ok; \
try { \
ok = (function)(); \
} catch (std::exception& e) { \
std::cout << e.what() << std::endl; \
ok = false; \
}\
std::cout << (ok ? "passed test: " : "failed test: ") \
<< #function << std::endl; \
if (!ok) failed++; \
}
}
int main()
{
int failed = 0;
TEST(global_const_allows_string);
TEST(global_const_allows_number);
TEST(global_const_allows_full_uri);
TEST(global_const_allows_shorthand_uri);
TEST(global_const_string_can_be_used_in_triple_condition);
TEST(global_const_number_can_be_used_in_triple_condition);
TEST(global_const_shorthand_uri_can_be_used_in_triple_condition);
TEST(global_const_number_can_be_used_in_math_builtin);
TEST(global_const_string_can_be_used_in_triple_consequence);
return failed;
}
|
Walkud/JudyBridge | module/ModuleC/src/main/java/com/zly/module/c/ModuleCActivity.java | <reponame>Walkud/JudyBridge<gh_stars>10-100
package com.zly.module.c;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
/**
* Created by Zhuliya on 2018/9/17
*/
public class ModuleCActivity extends AppCompatActivity {
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.mc_activity_module_c);
}
}
|
sylvainbouxin/wdp | wdp/src/main/java/org/whtcorp/wdp/WebSphereAbstractMojo.java | package org.whtcorp.wdp;
import java.util.Properties;
import org.apache.maven.plugin.AbstractMojo;
import com.ibm.websphere.management.AdminClient;
import com.ibm.websphere.management.AdminClientFactory;
public abstract class WebSphereAbstractMojo extends AbstractMojo {
/**
* @parameter
*/
private WebSphereAdminClientModel serverConnectionDefinition;
private AdminClient adminClient;
private void createAdminClientConnection() {
Properties props = new Properties();
props.setProperty(AdminClient.CACHE_DISABLED, "false");
props.setProperty(AdminClient.CONNECTOR_AUTO_ACCEPT_SIGNER, "true");
props.setProperty(AdminClient.CONNECTOR_HOST, serverConnectionDefinition.getHostname());
props.setProperty(AdminClient.CONNECTOR_PORT, serverConnectionDefinition.getPort());
props.setProperty(AdminClient.CONNECTOR_TYPE, AdminClient.CONNECTOR_TYPE_SOAP);
props.setProperty(AdminClient.PASSWORD, serverConnectionDefinition.getPassword());
props.setProperty(AdminClient.USERNAME, serverConnectionDefinition.getUsername());
if (serverConnectionDefinition.getConnector_security_enabled() != null) {
props.setProperty(AdminClient.CONNECTOR_SECURITY_ENABLED, serverConnectionDefinition.getConnector_security_enabled());
} else {
props.setProperty(AdminClient.CONNECTOR_SECURITY_ENABLED, "true");
}
if (serverConnectionDefinition.getSsl_trustStore() != null) {
props.setProperty("javax.net.ssl.trustStore", serverConnectionDefinition.getSsl_trustStore());
props.setProperty("javax.net.ssl.keyStore", serverConnectionDefinition.getSsl_keyStore());
props.setProperty("javax.net.ssl.trustStorePassword", serverConnectionDefinition.getSsl_trustStorePassword());
props.setProperty("javax.net.ssl.keyStorePassword", serverConnectionDefinition.getSsl_keyStorePassword());
}
try {
setAdminClient(AdminClientFactory.createAdminClient(props));
} catch (Exception e) {
e.printStackTrace();
}
}
public AdminClient getAdminClient() {
createAdminClientConnection();
return adminClient;
}
private void setAdminClient(AdminClient adminClient) {
this.adminClient = adminClient;
}
}
|
OcZi/Margaret | Bukkit/src/main/java/me/oczi/bukkit/objects/PartnershipHome.java | <filename>Bukkit/src/main/java/me/oczi/bukkit/objects/PartnershipHome.java
package me.oczi.bukkit.objects;
import com.google.common.base.Objects;
import org.bukkit.Location;
import org.bukkit.entity.Player;
import java.util.Date;
/**
* A {@link Home} implementation.
*/
public class PartnershipHome implements Home {
private final String id;
private final Date creationDate;
private String alias;
private Location location;
public PartnershipHome(String id,
Date creationDate,
String alias,
Location location) {
this.id = id;
this.creationDate = creationDate;
this.alias = alias;
this.location = location;
}
@Override
public boolean isEmpty() {
return false;
}
@Override
public void setAlias(String alias) {
this.alias = alias;
}
@Override
public void setLocation(Location location) {
this.location = location;
}
@Override
public boolean hasAlias() {
return !alias.isEmpty();
}
@Override
public Location getLocation() {
return location;
}
@Override
public Date getCreationDate() {
return creationDate;
}
@Override
public String getId() {
return id;
}
@Override
public String getAlias() {
return alias;
}
@Override
public void teleport(Player player) {
player.teleport(location);
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
PartnershipHome that = (PartnershipHome) o;
return Objects.equal(id, that.id);
}
@Override
public int hashCode() {
return Objects.hashCode(id);
}
@Override
public String toString() {
return Objects.toStringHelper(this)
.add("id", id)
.add("alias", alias)
.add("location", location)
.toString();
}
}
|
ZOrangeBandit/Silent-Gear | src/main/java/net/silentchaos512/gear/block/grader/GraderBlock.java | package net.silentchaos512.gear.block.grader;
import net.minecraft.core.BlockPos;
import net.minecraft.core.Direction;
import net.minecraft.world.*;
import net.minecraft.world.entity.player.Player;
import net.minecraft.world.item.context.BlockPlaceContext;
import net.minecraft.world.level.BlockGetter;
import net.minecraft.world.level.Level;
import net.minecraft.world.level.block.Block;
import net.minecraft.world.level.block.SimpleWaterloggedBlock;
import net.minecraft.world.level.block.entity.BlockEntity;
import net.minecraft.world.level.block.entity.BlockEntityTicker;
import net.minecraft.world.level.block.entity.BlockEntityType;
import net.minecraft.world.level.block.state.BlockState;
import net.minecraft.world.level.block.state.StateDefinition;
import net.minecraft.world.level.block.state.properties.BlockStateProperties;
import net.minecraft.world.level.block.state.properties.BooleanProperty;
import net.minecraft.world.level.block.state.properties.DirectionProperty;
import net.minecraft.world.level.material.FluidState;
import net.minecraft.world.level.material.Fluids;
import net.minecraft.world.phys.BlockHitResult;
import net.minecraft.world.phys.shapes.CollisionContext;
import net.minecraft.world.phys.shapes.VoxelShape;
import net.silentchaos512.gear.block.ModContainerBlock;
import net.silentchaos512.gear.init.ModBlockEntities;
import javax.annotation.Nullable;
public class GraderBlock extends ModContainerBlock<GraderTileEntity> implements SimpleWaterloggedBlock {
private static final DirectionProperty FACING = BlockStateProperties.HORIZONTAL_FACING;
private static final BooleanProperty LIT = BlockStateProperties.LIT;
private static final BooleanProperty WATERLOGGED = BlockStateProperties.WATERLOGGED;
private static final VoxelShape SHAPE = Block.box(1, 0, 0, 15, 12, 16);
public GraderBlock(Properties properties) {
super(GraderTileEntity::new, properties);
registerDefaultState(defaultBlockState().setValue(FACING, Direction.SOUTH).setValue(LIT, false).setValue(WATERLOGGED, false));
}
@Override
protected void createBlockStateDefinition(StateDefinition.Builder<Block, BlockState> builder) {
builder.add(FACING, LIT, WATERLOGGED);
}
@SuppressWarnings("deprecation")
@Override
public FluidState getFluidState(BlockState state) {
return state.getValue(WATERLOGGED) ? Fluids.WATER.getSource(false) : super.getFluidState(state);
}
@Override
public void onRemove(BlockState state, Level worldIn, BlockPos pos, BlockState newState, boolean isMoving) {
BlockEntity tileEntity = worldIn.getBlockEntity(pos);
if (tileEntity instanceof Container) {
Container inventory = (Container) tileEntity;
Containers.dropContents(worldIn, pos, inventory);
}
super.onRemove(state, worldIn, pos, newState, isMoving);
}
@Override
public InteractionResult use(BlockState state, Level worldIn, BlockPos pos, Player player, InteractionHand handIn, BlockHitResult hit) {
BlockEntity tileEntity = worldIn.getBlockEntity(pos);
if (tileEntity instanceof MenuProvider) {
player.openMenu((MenuProvider) tileEntity);
}
return InteractionResult.SUCCESS;
}
@Nullable
@Override
public BlockState getStateForPlacement(BlockPlaceContext context) {
FluidState fluidState = context.getLevel().getFluidState(context.getClickedPos());
Direction facing = context.getHorizontalDirection().getOpposite();
return defaultBlockState().setValue(FACING, facing).setValue(WATERLOGGED, fluidState.getType() == Fluids.WATER);
}
@SuppressWarnings("deprecation")
@Override
public VoxelShape getShape(BlockState state, BlockGetter worldIn, BlockPos pos, CollisionContext context) {
return SHAPE;
}
@Nullable
@Override
public <T extends BlockEntity> BlockEntityTicker<T> getTicker(Level level, BlockState state, BlockEntityType<T> blockEntityType) {
return level.isClientSide ? null : createTickerHelper(blockEntityType, ModBlockEntities.MATERIAL_GRADER.get(), GraderTileEntity::tick);
}
}
|
romsom/HISE | extras/demo_project/Scripts/Example.cpp | #define SAFE
class HiseJitClass
{
public:
const Buffer b(6);
void init()
{
b[0] = 1.0f;
};
void prepareToPlay(double sampleRate, int blockSize)
{
// Setup the playback configuration here
};
/** The NativeJIT code for the additive synthesiser. */
double uptime = 0.0;
double uptimeDelta = 0.03;
// Buffer is a custom type which correlates to the Buffer type in Javascript
// Treat them like a float array (there is a buffer overrun protection)
const Buffer lastValues(6);
const float a = 0.99f;
const float invA = 0.01f;
float process(float input)
{
const float uptimeFloat = (float)uptime;
const float a0 = (lastValues[0]*0.99f + b[0]*0.01f);
const float a1 = (lastValues[1]*0.99f + b[1]*0.01f);
const float a2 = (lastValues[2]*0.99f + b[2]*0.01f);
const float a3 = (lastValues[3]*0.99f + b[3]*0.01f);
const float a4 = (lastValues[4]*0.99f + b[4]*0.01f);
const float a5 = (lastValues[5]*0.99f + b[5]*0.01f);
const float v0 = a0 * sinf(uptimeFloat);
const float v1 = a1 * sinf(2.0f*uptimeFloat);
const float v2 = a2 * sinf(3.0f*uptimeFloat);
const float v3 = a3 * sinf(4.0f*uptimeFloat);
const float v4 = a4 * sinf(5.0f*uptimeFloat);
const float v5 = a5 * sinf(6.0f*uptimeFloat);
lastValues[0] = a0;
lastValues[1] = a1;
lastValues[2] = a2;
lastValues[3] = a3;
lastValues[4] = a4;
lastValues[5] = a5;
uptime += uptimeDelta;
return v0+v1+v2+v3+v4+v5;
};
private:
// Define private variables here
}; |
fkjava/oa | identity/src/main/java/org/fkjava/oa/identity/controller/RoleController.java | <reponame>fkjava/oa
package org.fkjava.oa.identity.controller;
import java.util.List;
import org.fkjava.oa.identity.domain.Role;
import org.fkjava.oa.identity.service.IdentityService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
@Controller
@RequestMapping("/identity/role")
public class RoleController {
@Autowired
private IdentityService identityService;
@GetMapping
public ModelAndView index() {
ModelAndView mav = new ModelAndView("identity/role/index");
List<Role> roles = this.identityService.findAllRoles();
mav.addObject("roles", roles);
return mav;
}
@PostMapping
public String save(Role role) {
this.identityService.save(role);
return "redirect:/identity/role";
}
@DeleteMapping("{id}")
@ResponseBody
public String delete(@PathVariable("id") String id) {
this.identityService.deleteRole(id);
return "OK";
}
}
|
IceIce1ce/Lab-Basic-Programming-HCMUS | Conditional Statement/H03/18127070_week03/Ex14/Ex14.cpp | <reponame>IceIce1ce/Lab-Basic-Programming-HCMUS
#include<iostream>
#include<math.h>
using namespace std;
int main()
{
double a, b, c;
cout << "Nhap do dai canh a: ";
cin >> a;
cout << "Nhap do dai canh b: ";
cin >> b;
cout << "Nhap do dai canh c: ";
cin >> c;
if (a == 0 || b == 0 || c == 0)
{
cout << "khong the tao thanh tam giac" << endl;
}
else
{
if ((a == b && a == c) || (a == b && b == c))
{
cout << "tam giac deu" << endl;
}
else
{
if (a == b || b == c || a == c)
{
if (c == sqrt(a * a + b * b) || b == sqrt(a * a + c * c) || a == sqrt(b * b + c * c))
{
cout << "tam giac vuong can" << endl;
}
else
{
cout << "tam giac can." << endl;
}
}
else
{
if (c == sqrt(a * a + b * b) || b == sqrt(a * a + c * c) || a == sqrt(b * b + c * c))
{
cout << "tam giac vuong" << endl;
}
else
{
cout << "tam giac thuong" << endl;
}
}
}
}
system("pause");
return 0;
} |
hw233/home3 | core/server/clientProject/commonClient/src/main/java/com/home/commonClient/net/request/func/item/FuncCleanUpItemRequest.java | package com.home.commonClient.net.request.func.item;
import com.home.commonClient.constlist.generate.GameRequestType;
import com.home.commonClient.net.request.func.base.FuncRRequest;
import com.home.shine.bytes.BytesWriteStream;
import com.home.shine.control.BytesControl;
/** 整理物品容器消息(generated by shine) */
public class FuncCleanUpItemRequest extends FuncRRequest
{
/** 数据类型ID */
public static final int dataID=GameRequestType.FuncCleanUpItem;
public FuncCleanUpItemRequest()
{
_dataID=GameRequestType.FuncCleanUpItem;
}
@Override
protected void copyData()
{
super.copyData();
}
/** 获取数据类名 */
@Override
public String getDataClassName()
{
return "FuncCleanUpItemRequest";
}
/** 写入字节流(完整版) */
@Override
protected void toWriteBytesFull(BytesWriteStream stream)
{
super.toWriteBytesFull(stream);
stream.startWriteObj();
stream.endWriteObj();
}
/** 创建实例 */
public static FuncCleanUpItemRequest create(int funcID)
{
FuncCleanUpItemRequest re=(FuncCleanUpItemRequest)BytesControl.createRequest(dataID);
re.funcID=funcID;
return re;
}
}
|
google/splot-java | smcp/src/test/java/com/google/iot/smcp/HostedThingAdapterTest.java | /*
* Copyright (C) 2018 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.iot.smcp;
import static org.junit.jupiter.api.Assertions.*;
import com.google.iot.coap.Client;
import com.google.iot.coap.Code;
import com.google.iot.coap.Message;
import com.google.iot.coap.Transaction;
import com.google.iot.m2m.base.*;
import com.google.iot.m2m.trait.*;
import java.net.URI;
import java.util.*;
import java.util.logging.Logger;
import org.junit.jupiter.api.Test;
@SuppressWarnings("ConstantConditions")
class HostedThingAdapterTest extends SmcpTestBase {
private static final boolean DEBUG = false;
private static final Logger LOGGER =
Logger.getLogger(HostedThingAdapterTest.class.getCanonicalName());
@Test
void hostedAdapterCombinedTest() throws Exception {
SmcpTechnology techHosting = new SmcpTechnology(mContextA);
SmcpTechnology techBacking = new SmcpTechnology(mContextA);
MyLightBulb localFe = new MyLightBulb();
techHosting
.getServer()
.addLocalEndpoint(
techHosting.getLocalEndpointManager().getLocalEndpointForScheme("loop"));
techHosting.host(localFe);
techHosting.getServer().start();
Thing remoteFe =
techBacking.getThingForNativeUri(URI.create("loop://localhost/1/"));
Client client =
new Client(
techBacking.getLocalEndpointManager(), URI.create("loop://localhost/1/"));
Transaction transaction =
client.newRequestBuilder()
.changePath(SceneTrait.METHOD_SAVE.getName() + "&sid=test")
.setCode(Code.METHOD_POST)
.send();
Message response = transaction.getResponse();
if (DEBUG) LOGGER.info(response.toString());
URI location = response.getOptionSet().getLocation();
assertEquals(Code.RESPONSE_CREATED, response.getCode(), Code.toString(response.getCode()));
assertEquals(
"/1/" + Splot.SECTION_FUNC + "/" + SceneTrait.TRAIT_ID + "/test/",
location.toASCIIString());
// Verify that the created resource is listed
transaction =
client.newRequestBuilder()
.changePath(
"/1/" + Splot.SECTION_FUNC + "/" + SceneTrait.TRAIT_ID + "/")
.setCode(Code.METHOD_GET)
.send();
response = transaction.getResponse();
if (DEBUG) LOGGER.info(response.toString());
assertEquals(Code.RESPONSE_CONTENT, response.getCode(), Code.toString(response.getCode()));
// TODO: Actually verify that the created resource is listed
// Verify that the created resource is accessible.
transaction =
client.newRequestBuilder()
.changePath(location.toASCIIString() + Splot.SECTION_STATE + "/")
.setCode(Code.METHOD_GET)
.send();
response = transaction.getResponse();
if (DEBUG) LOGGER.info(response.toString());
assertEquals(Code.RESPONSE_CONTENT, response.getCode(), Code.toString(response.getCode()));
}
@Test
void hostedAdapterMethodCallTest() throws Exception {
SmcpTechnology techHosting = new SmcpTechnology(mContextA);
SmcpTechnology techBacking = new SmcpTechnology(mContextA);
MyLightBulb localFe = new MyLightBulb();
techHosting
.getServer()
.addLocalEndpoint(
techHosting.getLocalEndpointManager().getLocalEndpointForScheme("loop"));
techHosting.host(localFe);
techHosting.getServer().start();
Thing remoteFe =
techBacking.getThingForNativeUri(URI.create("loop://localhost/1/"));
Client client =
new Client(
techBacking.getLocalEndpointManager(), URI.create("loop://localhost/1/"));
Transaction transaction =
client.newRequestBuilder()
.changePath(SceneTrait.METHOD_SAVE.getName() + "&sid=test")
.setCode(Code.METHOD_POST)
.send();
Message response = transaction.getResponse();
if (DEBUG) LOGGER.info(response.toString());
URI location = response.getOptionSet().getLocation();
assertEquals(Code.RESPONSE_CREATED, response.getCode(), Code.toString(response.getCode()));
assertEquals(
"/1/" + Splot.SECTION_FUNC + "/" + SceneTrait.TRAIT_ID + "/test/",
location.toASCIIString());
// Verify that the resource was indeed created
Set<String> childIdSet = new HashSet<>();
for (Thing child : localFe.fetchChildrenForTrait(SceneTrait.TRAIT_ID).get()) {
childIdSet.add(localFe.getIdForChild(child));
}
assertTrue(childIdSet.contains("test"));
}
@Test
void hostedAdapterChildTest() throws Exception {
SmcpTechnology techHosting = new SmcpTechnology(mContextA);
SmcpTechnology techBacking = new SmcpTechnology(mContextA);
MyLightBulb localFe = new MyLightBulb();
techHosting
.getServer()
.addLocalEndpoint(
techHosting.getLocalEndpointManager().getLocalEndpointForScheme("loop"));
techHosting.host(localFe);
techHosting.getServer().start();
Thing remoteFe =
techBacking.getThingForNativeUri(URI.create("loop://localhost/1/"));
Client client =
new Client(
techBacking.getLocalEndpointManager(), URI.create("loop://localhost/1/"));
Thing testScene =
remoteFe.invokeMethod(
SceneTrait.METHOD_SAVE,
SceneTrait.PARAM_SCENE_ID.with("hostedAdapterChildTest"))
.get();
assertNotNull(testScene);
// Verify that the created resource is listed
Transaction transaction =
client.newRequestBuilder()
.changePath(
"/1/" + Splot.SECTION_FUNC + "/" + SceneTrait.TRAIT_ID + "/")
.setCode(Code.METHOD_GET)
.send();
Message response = transaction.getResponse();
if (DEBUG) LOGGER.info(response.toString());
assertEquals(Code.RESPONSE_CONTENT, response.getCode(), Code.toString(response.getCode()));
// TODO: Actually verify that the created resource is listed
// Verify that the created resource is accessible.
transaction =
client.newRequestBuilder()
.changePath(
"/1/"
+ Splot.SECTION_FUNC
+ "/"
+ SceneTrait.TRAIT_ID
+ "/hostedAdapterChildTest/"
+ Splot.SECTION_STATE
+ "/")
.setCode(Code.METHOD_GET)
.send();
response = transaction.getResponse();
if (DEBUG) LOGGER.info(response.toString());
assertEquals(Code.RESPONSE_CONTENT, response.getCode(), Code.toString(response.getCode()));
}
}
|
woshisunzewei/EIP | UI/EIP.Web/Scripts/app/system/app/list.js | <filename>UI/EIP.Web/Scripts/app/system/app/list.js
define([
'list',
'layout'
],
function () {
initLayout();
initGird();
});
var $grid;
//初始化布局
function initLayout() {
$("body").layout({
"north": {
size: 29,
closable: true,
resizable: false,
sliderTip: "显示/隐藏侧边栏",
togglerTip_open: "关闭",
togglerTip_closed: "打开",
resizerTip: "上下拖动可调整大小", //鼠标移到边框时,提示语
slidable: true
},
"center": {
onresize_end: function () {
//获取调整后高度
$grid.jqGrid("setGridHeight", $("#uiCenter").height() - 50).jqGrid("setGridWidth", $("#uiCenter").width() - 2);
}
}
});
}
//初始化表格
function initGird() {
$grid = $("#list").jgridview(
{
multiselect: false,
shrinkToFit:true,
url: "/System/App/GetApp",
colModel: [
{ name: "AppId", hidden: true },
{ label: "代码", name: "Code", width: 100, fixed: true },
{ label: "名称", name: "Name", width: 200 },
{ label: "简称", name: "ShortName", width: 100, fixed: true },
{ label: "域名/Ip", name: "Domain", width: 200, fixed: true },
{ label: "程序Dll文件", name: "DllPath", width: 200},
{ label: "备注", name: "Remark", width: 100, fixed: true },
{ label: "排序", name: "OrderNo", width: 50, fixed: true }
],
height: $("#uiCenter").height() - 51
});
}
//获取表格数据
function getGridData() {
UtilAjaxPost("/System/App/GetApp", {}, function (data) { GridReloadLoadOnceData($grid, data); });
}
//操作:新增
function add() {
ArtDialogOpen("/System/App/Edit", "新增应用系统配置", true, 380, 580);
}
//操作:编辑
function edit() {
//查看是否选中
GridIsSelect($grid, function () {
var info = GridGetSingSelectData($grid);
ArtDialogOpen("/System/App/Edit?id=" + info.AppId, "修改应用系统配置-" + info.Name, true, 380, 580);
});
}
//删除匹配项
function del() {
//查看是否选中
GridIsSelect($grid, function () {
ArtDialogConfirm(Language.common.deletemsg, function () {
UtilAjaxPostWait(
"/System/App/DeleteApp",
{ id: GridGetSingSelectData($grid).AppId },
perateStatus
);
});
});
}
//请求完成
function perateStatus(data) {
DialogAjaxResult(data);
if (data.ResultSign === 0) {
getGridData();
}
}
|
hwbyuehen/pattern-design | src/main/java/com/yuehen/pattern/structure/proxy/refactor/news/BankCardServiceNew.java | package com.yuehen.pattern.structure.proxy.refactor.news;
import com.yuehen.pattern.structure.proxy.refactor.old.IBankCardService;
public class BankCardServiceNew implements IBankCardService {
public void queryUserByBankcard(){
//
System.out.println("查询用户信息业务功能。。。");
}
}
|
jsavikko/futurice-ldap-user-manager | fum/urls.py | <gh_stars>100-1000
from django.conf import settings
from django.conf.urls import patterns, include, url
from django.conf.urls.static import static
from django.template import add_to_builtins
from django.contrib import admin
admin.autodiscover()
from views import IndexView
urlpatterns = patterns('',
url(r'^$', IndexView.as_view(), name='index'),
url(r'^', include('fum.common.urls')),
url(r'^users/', include('fum.users.urls')),
url(r'^groups/', include('fum.groups.urls')),
url(r'^servers/', include('fum.servers.urls')),
url(r'^projects/', include('fum.projects.urls')),
url(r'^api/', include('fum.api.urls')),
url(r'^admin/', include(admin.site.urls)),
url(r'^rest-api/', include('rest_framework_docs.urls')),
url(r'^hsearch/', include('haystack.urls')),
url(r'^history/', include('djangohistory.urls')),
)
if settings.DEBUG:
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
if settings.DEBUG:
try:
import debug_toolbar
urlpatterns += patterns('',
url(r'^__debug__/', include(debug_toolbar.urls)),
)
except Exception, e:
print("Debug Toolbar not in use, ignored")
add_to_builtins('fum.common.templatetags.tags')
|
Gankro/geo-kit | src/js/structures/primitives/Box.js | <reponame>Gankro/geo-kit
var gk = (function(gk){
var Point = gk.Point;
var Edge = gk.LineSegment;
var Drawable = gk.Drawable;
function Box(ptA, ptB){
this.ptA = ptA;
this.ptB = ptB;
}
Box.displayName = "Box";
Box.icon = "box";
Box.createPrimitive = function(mouse){
return new Box(new Point(mouse.x, mouse.y), new Point(mouse.x, mouse.y));
}
Box.prototype = new Drawable();
Box.prototype.updateMousePrimitive = function(oldMouse, curMouse){
this.ptB.updateMousePrimitive(oldMouse, curMouse);
this.invalidate();
}
Box.prototype.updateMouse = function(oldMouse, curMouse){
this.ptA.updateMouse(oldMouse, curMouse);
this.ptB.updateMouse(oldMouse, curMouse);
this.invalidate();
}
Box.prototype.draw = function(options){
this.startRender(options);
var ctx = this.getContext(options);
ctx.beginPath();
var pts = this.points;
var pt = pts[pts.length-1];
ctx.moveTo(pt.x, pt.y);
for(var i=0; i<pts.length; ++i){
var pt = pts[i];
ctx.lineTo(pt.x, pt.y);
}
ctx.closePath();
this.applyEdgeSelectionStyle(ctx, options);
ctx.stroke();
this.finishRender(options);
}
Box.prototype.tryToSelect = function(mouse, options){
var result;
var edges = this.edges;
for(var i=0; i<edges.length; ++i){
result = edges[i].tryToSelect(mouse, options);
if(result){
return result;
}
}
return false;
}
Box.prototype.tryToSelectFromBox = function(box, options){
return this.minX <= box.maxX && this.maxX >= box.minX
&& this.minY <= box.maxY && this.maxY >= box.minY;
}
Box.prototype.tryToSnap = function(mouse, options){
if(options.snapToPoints){
var points = this.points;
for(var i=0; i<points.length; ++i){
var result = points[i].tryToSnap(mouse, options);
if(result){
return result;
}
}
}
if(options.snapToEdges){
var edges = this.edges;
for(var i=0; i<edges.length; ++i){
var result = edges[i].tryToSnap(mouse, options);
if(result){
return result;
}
}
}
return null;
}
Box.prototype.clone = function(deep){
if(deep){
return new Box(ptA.clone(deep), ptB.clone(deep));
}else{
return new Box(ptA, ptB);
}
}
Box.prototype.invalidate = function(){
delete this._edges;
delete this._points;
}
Box.prototype.__defineGetter__("edges", function(){
if(!this._edges){
this._edges = [];
var pts = this.points;
for(var i=0; i<pts.length-1; ++i){
this._edges.push(new Edge(pts[i], pts[i+1]));
}
this._edges.push(new Edge(pts[pts.length-1], pts[0]));
}
return this._edges;
});
Box.prototype.__defineGetter__("points", function(){
if(!this._points){
this._points = [
new Point(this.minX, this.minY)
, new Point(this.minX, this.maxY)
, new Point(this.maxX, this.maxY)
, new Point(this.maxX, this.minY)
];
}
return this._points;
});
Box.prototype.__defineGetter__("minX", function(){
return Math.min(this.ptA.x, this.ptB.x);
});
Box.prototype.__defineGetter__("maxX", function(){
return Math.max(this.ptA.x, this.ptB.x);
});
Box.prototype.__defineGetter__("minY", function(){
return Math.min(this.ptA.y, this.ptB.y);
});
Box.prototype.__defineGetter__("maxY", function(){
return Math.max(this.ptA.y, this.ptB.y);
});
Box.prototype.__defineGetter__("hashCode", function(){
return this.minX+","+this.minY+","+this.maxX+","+this.maxY;
});
Box.prototype.serialize = function(){
var result = Drawable.prototype.serialize.call(this);
result.type = Box.displayName;
result.ptA = this.ptA.serialize();
result.ptB = this.ptB.serialize();
return result;
};
gk.serialization.registerDeserializer(Box.displayName, function(obj){
var result = new Box();
result.ptA = gk.serialization.deserialize(obj.ptA);
result.ptB = gk.serialization.deserialize(obj.ptB);
Drawable.prototype._deserialize.call(this);
return result;
});
gk.Box = Box;
gk.registerPrimitive(Box);
return gk;
})(gk || {});
|
soundvibe/reacto | src/main/java/net/soundvibe/reacto/discovery/types/Status.java | package net.soundvibe.reacto.discovery.types;
public enum Status {
/**
* The service is published and is accessible.
*/
UP,
/**
* The service has been withdrawn, it is not accessible anymore.
*/
DOWN,
/**
* The service is still published, but not accessible (maintenance).
*/
OUT_OF_SERVICE,
/**
* Unknown status.
*/
UNKNOWN
} |
peterkong1024/cpg | cpg-core/src/test/java/de/fraunhofer/aisec/cpg/enhancements/templates/FunctionTemplateTest.java | /*
* Copyright (c) 2021, Fraunhofer AISEC. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* $$$$$$\ $$$$$$$\ $$$$$$\
* $$ __$$\ $$ __$$\ $$ __$$\
* $$ / \__|$$ | $$ |$$ / \__|
* $$ | $$$$$$$ |$$ |$$$$\
* $$ | $$ ____/ $$ |\_$$ |
* $$ | $$\ $$ | $$ | $$ |
* \$$$$$ |$$ | \$$$$$ |
* \______/ \__| \______/
*
*/
package de.fraunhofer.aisec.cpg.enhancements.templates;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import de.fraunhofer.aisec.cpg.BaseTest;
import de.fraunhofer.aisec.cpg.TestUtils;
import de.fraunhofer.aisec.cpg.graph.declarations.*;
import de.fraunhofer.aisec.cpg.graph.edge.Properties;
import de.fraunhofer.aisec.cpg.graph.statements.expressions.*;
import de.fraunhofer.aisec.cpg.graph.types.ObjectType;
import de.fraunhofer.aisec.cpg.graph.types.ParameterizedType;
import de.fraunhofer.aisec.cpg.graph.types.Type;
import de.fraunhofer.aisec.cpg.graph.types.UnknownType;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import org.junit.jupiter.api.Test;
class FunctionTemplateTest extends BaseTest {
private final Path topLevel =
Path.of("src", "test", "resources", "templates", "functiontemplates");
@Test
void testDependentType() throws Exception {
List<TranslationUnitDeclaration> result =
TestUtils.analyze(
List.of(Path.of(topLevel.toString(), "functionTemplate.cpp").toFile()), topLevel, true);
List<VariableDeclaration> variableDeclarations =
TestUtils.subnodesOfType(result, VariableDeclaration.class);
VariableDeclaration x = TestUtils.findByUniqueName(variableDeclarations, "x");
assertEquals(UnknownType.getUnknownType(), x.getType());
List<DeclaredReferenceExpression> declaredReferenceExpressions =
TestUtils.subnodesOfType(result, DeclaredReferenceExpression.class);
DeclaredReferenceExpression xDeclaredReferenceExpression =
TestUtils.findByUniqueName(declaredReferenceExpressions, "x");
assertEquals(UnknownType.getUnknownType(), xDeclaredReferenceExpression.getType());
List<BinaryOperator> binaryOperators = TestUtils.subnodesOfType(result, BinaryOperator.class);
BinaryOperator dependentOperation =
TestUtils.findByUniquePredicate(
binaryOperators, b -> Objects.equals(b.getCode(), "val * N"));
assertEquals(UnknownType.getUnknownType(), dependentOperation.getType());
}
void testFunctionTemplateArguments(
CallExpression callFloat3, ObjectType floatType, Literal<Integer> int3) {
assertEquals(2, callFloat3.getTemplateParameters().size());
assertEquals(floatType, ((TypeExpression) callFloat3.getTemplateParameters().get(0)).getType());
assertEquals(
0, callFloat3.getTemplateParametersPropertyEdge().get(0).getProperty(Properties.INDEX));
assertEquals(
TemplateDeclaration.TemplateInitialization.EXPLICIT,
callFloat3
.getTemplateParametersPropertyEdge()
.get(0)
.getProperty(Properties.INSTANTIATION));
assertEquals(int3, callFloat3.getTemplateParameters().get(1));
assertEquals(
1, callFloat3.getTemplateParametersPropertyEdge().get(1).getProperty(Properties.INDEX));
assertEquals(
TemplateDeclaration.TemplateInitialization.EXPLICIT,
callFloat3
.getTemplateParametersPropertyEdge()
.get(1)
.getProperty(Properties.INSTANTIATION));
}
@Test
void testFunctionTemplateStructure() throws Exception {
List<TranslationUnitDeclaration> result =
TestUtils.analyze(
List.of(Path.of(topLevel.toString(), "functionTemplate.cpp").toFile()), topLevel, true);
// This test checks the structure of FunctionTemplates without the TemplateExpansionPass
FunctionTemplateDeclaration functionTemplateDeclaration =
TestUtils.subnodesOfType(result, FunctionTemplateDeclaration.class).get(0);
// Check FunctionTemplate Parameters
List<TypeParamDeclaration> typeParamDeclarations =
TestUtils.subnodesOfType(result, TypeParamDeclaration.class);
assertEquals(1, typeParamDeclarations.size());
TypeParamDeclaration typeParamDeclaration = typeParamDeclarations.get(0);
assertEquals(typeParamDeclaration, functionTemplateDeclaration.getParameters().get(0));
ParameterizedType T = new ParameterizedType("T");
ObjectType intType =
new ObjectType(
"int",
Type.Storage.AUTO,
new Type.Qualifier(),
new ArrayList<>(),
ObjectType.Modifier.SIGNED,
true);
ObjectType floatType =
new ObjectType(
"float",
Type.Storage.AUTO,
new Type.Qualifier(),
new ArrayList<>(),
ObjectType.Modifier.SIGNED,
true);
assertEquals(T, typeParamDeclaration.getType());
assertEquals(intType, typeParamDeclaration.getDefault());
ParamVariableDeclaration N =
TestUtils.findByUniqueName(
TestUtils.subnodesOfType(result, ParamVariableDeclaration.class), "N");
Literal<Integer> int2 =
TestUtils.findByUniquePredicate(
TestUtils.subnodesOfType(result, Literal.class), l -> l.getValue().equals(2));
Literal<Integer> int3 =
TestUtils.findByUniquePredicate(
TestUtils.subnodesOfType(result, Literal.class), l -> l.getValue().equals(3));
Literal<Integer> int5 =
TestUtils.findByUniquePredicate(
TestUtils.subnodesOfType(result, Literal.class), l -> l.getValue().equals(5));
assertEquals(N, functionTemplateDeclaration.getParameters().get(1));
assertEquals(intType, N.getType());
assertEquals(5, ((Literal) N.getDefault()).getValue());
assertTrue(N.getPrevDFG().contains(int5));
assertTrue(N.getPrevDFG().contains(int3));
assertTrue(N.getPrevDFG().contains(int2));
// Check the realization
assertEquals(1, functionTemplateDeclaration.getRealization().size());
FunctionDeclaration fixed_multiply = functionTemplateDeclaration.getRealization().get(0);
assertEquals(T, fixed_multiply.getType());
ParamVariableDeclaration val = fixed_multiply.getParameters().get(0);
assertEquals(T, val.getType());
// Check the invokes
CallExpression callInt2 =
TestUtils.findByUniquePredicate(
TestUtils.subnodesOfType(result, CallExpression.class),
c -> c.getLocation().getRegion().getStartLine() == 12);
assertEquals(1, callInt2.getInvokes().size());
assertEquals(fixed_multiply, callInt2.getInvokes().get(0));
CallExpression callFloat3 =
TestUtils.findByUniquePredicate(
TestUtils.subnodesOfType(result, CallExpression.class),
c -> c.getLocation().getRegion().getStartLine() == 13);
assertEquals(1, callFloat3.getInvokes().size());
assertEquals(fixed_multiply, callFloat3.getInvokes().get(0));
// Check return values
assertEquals(intType, callInt2.getType());
assertEquals(floatType, callFloat3.getType());
// Check template arguments
testFunctionTemplateArguments(callFloat3, floatType, int3);
}
@Test
void testInvocationWithCallTarget() throws Exception {
// Check invocation target with specialized function alongside template with same name
List<TranslationUnitDeclaration> result =
TestUtils.analyze(
List.of(Path.of(topLevel.toString(), "functionTemplateInvocation1.cpp").toFile()),
topLevel,
true);
FunctionDeclaration doubleFixedMultiply =
TestUtils.findByUniquePredicate(
TestUtils.subnodesOfType(result, FunctionDeclaration.class),
f -> f.getName().equals("fixed_multiply") && f.getType().getName().equals("double"));
CallExpression call =
TestUtils.findByUniquePredicate(
TestUtils.subnodesOfType(result, CallExpression.class),
c -> c.getName().equals("fixed_multiply"));
// Check invocation
assertEquals(1, call.getInvokes().size());
assertEquals(doubleFixedMultiply, call.getInvokes().get(0));
// Check return value
assertEquals("double", call.getType().getName());
}
@Test
void testInvocationWithoutCallTarget() throws Exception {
// Check if a CallExpression is converted to a TemplateCallExpression if a compatible target
// exists
List<TranslationUnitDeclaration> result =
TestUtils.analyze(
List.of(Path.of(topLevel.toString(), "functionTemplateInvocation2.cpp").toFile()),
topLevel,
true);
FunctionTemplateDeclaration templateDeclaration =
TestUtils.findByUniquePredicate(
TestUtils.subnodesOfType(result, FunctionTemplateDeclaration.class),
t -> t.getName().equals("fixed_multiply"));
FunctionDeclaration fixedMultiply =
TestUtils.findByUniquePredicate(
TestUtils.subnodesOfType(result, FunctionDeclaration.class),
f -> f.getName().equals("fixed_multiply") && f.getType().getName().equals("T"));
// Check realization of template maps to our target function
assertEquals(1, templateDeclaration.getRealization().size());
assertEquals(fixedMultiply, templateDeclaration.getRealization().get(0));
CallExpression call =
TestUtils.findByUniquePredicate(
TestUtils.subnodesOfType(result, CallExpression.class),
c -> c.getName().equals("fixed_multiply"));
// Check invocation target
assertEquals(1, call.getInvokes().size());
assertEquals(fixedMultiply, call.getInvokes().get(0));
// Check template parameters
ObjectType doubleType =
new ObjectType(
"double",
Type.Storage.AUTO,
new Type.Qualifier(),
new ArrayList<>(),
ObjectType.Modifier.SIGNED,
true);
Literal<?> literal5 =
TestUtils.findByUniquePredicate(
TestUtils.subnodesOfType(result, Literal.class), l -> l.getValue().equals(5));
assertEquals(2, call.getTemplateParameters().size());
assertEquals(doubleType, ((TypeExpression) call.getTemplateParameters().get(0)).getType());
assertEquals(literal5, call.getTemplateParameters().get(1));
// Check return value
assertEquals(doubleType, call.getType());
}
@Test
void testInvocationWithAutoDeduction() throws Exception {
// Check if a TemplateCallExpression without template parameters performs autodeduction
List<TranslationUnitDeclaration> result =
TestUtils.analyze(
List.of(Path.of(topLevel.toString(), "functionTemplateInvocation3.cpp").toFile()),
topLevel,
true);
FunctionTemplateDeclaration templateDeclaration =
TestUtils.findByUniquePredicate(
TestUtils.subnodesOfType(result, FunctionTemplateDeclaration.class),
t -> t.getName().equals("fixed_multiply"));
FunctionDeclaration fixedMultiply =
TestUtils.findByUniquePredicate(
TestUtils.subnodesOfType(result, FunctionDeclaration.class),
f -> f.getName().equals("fixed_multiply") && f.getType().getName().equals("T"));
// Check realization of template maps to our target function
assertEquals(1, templateDeclaration.getRealization().size());
assertEquals(fixedMultiply, templateDeclaration.getRealization().get(0));
CallExpression call =
TestUtils.findByUniquePredicate(
TestUtils.subnodesOfType(result, CallExpression.class),
c -> c.getName().equals("fixed_multiply"));
// Check invocation target
assertEquals(1, call.getInvokes().size());
assertEquals(fixedMultiply, call.getInvokes().get(0));
// Check template parameters
Literal<?> literal5 =
TestUtils.findByUniquePredicate(
TestUtils.subnodesOfType(result, Literal.class), l -> l.getValue().equals(5));
assertEquals(2, call.getTemplateParameters().size());
assertEquals("double", call.getTemplateParameters().get(0).getName());
assertEquals(literal5, call.getTemplateParameters().get(1));
// Check return value
assertEquals("double", call.getType().getName());
}
@Test
void testInvocationWithDefaults() throws Exception {
// test invocation target when no autodeduction is possible, but defaults are provided
List<TranslationUnitDeclaration> result =
TestUtils.analyze(
List.of(Path.of(topLevel.toString(), "functionTemplateInvocation4.cpp").toFile()),
topLevel,
true);
FunctionTemplateDeclaration templateDeclaration =
TestUtils.findByUniquePredicate(
TestUtils.subnodesOfType(result, FunctionTemplateDeclaration.class),
t -> t.getName().equals("fixed_multiply"));
FunctionDeclaration fixedMultiply =
TestUtils.findByUniquePredicate(
TestUtils.subnodesOfType(result, FunctionDeclaration.class),
f -> f.getName().equals("fixed_multiply") && f.getType().getName().equals("T"));
// Check realization of template maps to our target function
assertEquals(1, templateDeclaration.getRealization().size());
assertEquals(fixedMultiply, templateDeclaration.getRealization().get(0));
CallExpression call =
TestUtils.findByUniquePredicate(
TestUtils.subnodesOfType(result, CallExpression.class),
c -> c.getName().equals("fixed_multiply"));
// Check invocation target
assertEquals(1, call.getInvokes().size());
assertEquals(fixedMultiply, call.getInvokes().get(0));
// Check template parameters
ObjectType intType =
TestUtils.findByUniquePredicate(
TestUtils.subnodesOfType(result, ObjectType.class), t -> t.getName().equals("int"));
Literal<?> literal5 =
TestUtils.findByUniquePredicate(
TestUtils.subnodesOfType(result, Literal.class), l -> l.getValue().equals(5));
assertEquals(2, call.getTemplateParameters().size());
assertEquals(intType, ((TypeExpression) call.getTemplateParameters().get(0)).getType());
assertEquals(literal5, call.getTemplateParameters().get(1));
// Check return value
assertEquals(intType, call.getType());
}
@Test
void testInvocationWithPartialDefaults() throws Exception {
// test invocation target when no autodeduction is possible, but defaults are partially used
List<TranslationUnitDeclaration> result =
TestUtils.analyze(
List.of(Path.of(topLevel.toString(), "functionTemplateInvocation5.cpp").toFile()),
topLevel,
true);
FunctionTemplateDeclaration templateDeclaration =
TestUtils.findByUniquePredicate(
TestUtils.subnodesOfType(result, FunctionTemplateDeclaration.class),
t -> t.getName().equals("fixed_multiply"));
FunctionDeclaration fixedMultiply =
TestUtils.findByUniquePredicate(
TestUtils.subnodesOfType(result, FunctionDeclaration.class),
f -> f.getName().equals("fixed_multiply") && f.getType().getName().equals("T"));
// Check realization of template maps to our target function
assertEquals(1, templateDeclaration.getRealization().size());
assertEquals(fixedMultiply, templateDeclaration.getRealization().get(0));
CallExpression call =
TestUtils.findByUniquePredicate(
TestUtils.subnodesOfType(result, CallExpression.class),
c -> c.getName().equals("fixed_multiply"));
// Check invocation target
assertEquals(1, call.getInvokes().size());
assertEquals(fixedMultiply, call.getInvokes().get(0));
// Check template parameters
ObjectType doubleType =
new ObjectType(
"double",
Type.Storage.AUTO,
new Type.Qualifier(),
new ArrayList<>(),
ObjectType.Modifier.SIGNED,
true);
Literal<?> literal5 =
TestUtils.findByUniquePredicate(
TestUtils.subnodesOfType(result, Literal.class), l -> l.getValue().equals(5));
assertEquals(2, call.getTemplateParameters().size());
assertEquals(doubleType, ((TypeExpression) call.getTemplateParameters().get(0)).getType());
assertEquals(literal5, call.getTemplateParameters().get(1));
// Check return value
assertEquals(doubleType, call.getType());
}
@Test
void testInvocationWithImplicitCastToOverridenTemplateParameter() throws Exception {
// test invocation target when template parameter produces a cast in an argument
List<TranslationUnitDeclaration> result =
TestUtils.analyze(
List.of(Path.of(topLevel.toString(), "functionTemplateInvocation6.cpp").toFile()),
topLevel,
true);
FunctionTemplateDeclaration templateDeclaration =
TestUtils.findByUniquePredicate(
TestUtils.subnodesOfType(result, FunctionTemplateDeclaration.class),
t -> t.getName().equals("fixed_multiply"));
FunctionDeclaration fixedMultiply =
TestUtils.findByUniquePredicate(
TestUtils.subnodesOfType(result, FunctionDeclaration.class),
f -> f.getName().equals("fixed_multiply") && f.getType().getName().equals("T"));
// Check realization of template maps to our target function
assertEquals(1, templateDeclaration.getRealization().size());
assertEquals(fixedMultiply, templateDeclaration.getRealization().get(0));
CallExpression call =
TestUtils.findByUniquePredicate(
TestUtils.subnodesOfType(result, CallExpression.class),
c -> c.getName().equals("fixed_multiply"));
// Check invocation target
assertEquals(1, call.getInvokes().size());
assertEquals(fixedMultiply, call.getInvokes().get(0));
// Check template parameters
ObjectType intType =
TestUtils.findByUniquePredicate(
TestUtils.subnodesOfType(result, ObjectType.class), t -> t.getName().equals("int"));
Literal<?> literal5 =
TestUtils.findByUniquePredicate(
TestUtils.subnodesOfType(result, Literal.class), l -> l.getValue().equals(5));
assertEquals(2, call.getTemplateParameters().size());
assertEquals(intType, ((TypeExpression) call.getTemplateParameters().get(0)).getType());
assertEquals(literal5, call.getTemplateParameters().get(1));
// Check return value
assertEquals(intType, call.getType());
// Check cast
assertEquals(1, call.getArguments().size());
assertTrue(call.getArguments().get(0) instanceof CastExpression);
CastExpression arg = (CastExpression) call.getArguments().get(0);
assertEquals(intType, arg.getCastType());
assertEquals(20.3, ((Literal) arg.getExpression()).getValue());
}
@Test
void testInvocationWithImplicitCast() throws Exception {
// test invocation target when signature does not match but implicitcast can be applied
List<TranslationUnitDeclaration> result =
TestUtils.analyze(
List.of(Path.of(topLevel.toString(), "functionTemplateInvocation7.cpp").toFile()),
topLevel,
true);
FunctionTemplateDeclaration templateDeclaration =
TestUtils.findByUniquePredicate(
TestUtils.subnodesOfType(result, FunctionTemplateDeclaration.class),
t -> t.getName().equals("f") && !t.isInferred());
FunctionDeclaration f =
TestUtils.findByUniquePredicate(
TestUtils.subnodesOfType(result, FunctionDeclaration.class),
func ->
func.getName().equals("f")
&& !templateDeclaration.getRealization().contains(func)
&& !func.isInferred());
CallExpression f1 =
TestUtils.findByUniquePredicate(
TestUtils.subnodesOfType(result, CallExpression.class),
c -> c.getLocation().getRegion().getStartLine() == 9);
CallExpression f2 =
TestUtils.findByUniquePredicate(
TestUtils.subnodesOfType(result, CallExpression.class),
c -> c.getLocation().getRegion().getStartLine() == 10);
CallExpression f3 =
TestUtils.findByUniquePredicate(
TestUtils.subnodesOfType(result, CallExpression.class),
c -> c.getLocation().getRegion().getStartLine() == 11);
CallExpression f4 =
TestUtils.findByUniquePredicate(
TestUtils.subnodesOfType(result, CallExpression.class),
c -> c.getLocation().getRegion().getStartLine() == 12);
assertEquals(1, f1.getInvokes().size());
assertEquals(f, f1.getInvokes().get(0));
assertEquals(1, f2.getInvokes().size());
assertEquals(templateDeclaration.getRealization().get(0), f2.getInvokes().get(0));
assertEquals(1, f3.getInvokes().size());
assertEquals(f, f3.getInvokes().get(0));
assertEquals(2, f3.getArguments().size());
assertEquals("int", f3.getArguments().get(0).getType().getName());
assertEquals("int", f3.getArguments().get(1).getType().getName());
assertTrue(f3.getArguments().get(1) instanceof CastExpression);
CastExpression castExpression = (CastExpression) f3.getArguments().get(1);
assertEquals('b', ((Literal) castExpression.getExpression()).getValue());
assertEquals(1, f4.getInvokes().size());
assertTrue(f4.getInvokes().get(0).isInferred());
}
@Test
void testFunctionTemplateInMethod() throws Exception {
List<TranslationUnitDeclaration> result =
TestUtils.analyze(
List.of(Path.of(topLevel.toString(), "functionTemplateMethod.cpp").toFile()),
topLevel,
true);
RecordDeclaration recordDeclaration =
TestUtils.findByUniquePredicate(
TestUtils.subnodesOfType(result, RecordDeclaration.class),
c -> c.getName().equals("MyClass"));
FunctionTemplateDeclaration templateDeclaration =
TestUtils.findByUniquePredicate(
TestUtils.subnodesOfType(result, FunctionTemplateDeclaration.class),
t -> t.getName().equals("fixed_multiply") && !t.isImplicit());
assertEquals(2, templateDeclaration.getParameters().size());
assertEquals(1, recordDeclaration.getTemplates().size());
assertTrue(recordDeclaration.getTemplates().contains(templateDeclaration));
MethodDeclaration methodDeclaration =
TestUtils.findByUniquePredicate(
TestUtils.subnodesOfType(result, MethodDeclaration.class),
m -> !(m.isImplicit()) && m.getName().equals("fixed_multiply"));
assertEquals(1, templateDeclaration.getRealization().size());
assertTrue(templateDeclaration.getRealization().contains(methodDeclaration));
// Test callexpression to invoke the realization
CallExpression callExpression =
TestUtils.findByUniquePredicate(
TestUtils.subnodesOfType(result, CallExpression.class),
c -> c.getCode() != null && c.getCode().equals("myObj.fixed_multiply<int>(3);"));
assertEquals(1, callExpression.getInvokes().size());
assertEquals(methodDeclaration, callExpression.getInvokes().get(0));
assertEquals(templateDeclaration, callExpression.getTemplateInstantiation());
assertEquals(2, callExpression.getTemplateParameters().size());
assertEquals("int", callExpression.getTemplateParameters().get(0).getName());
assertEquals(
TemplateDeclaration.TemplateInitialization.EXPLICIT,
callExpression
.getTemplateParametersPropertyEdge()
.get(0)
.getProperty(Properties.INSTANTIATION));
assertEquals(
0, callExpression.getTemplateParametersPropertyEdge().get(0).getProperty(Properties.INDEX));
Literal<Integer> int5 =
TestUtils.findByUniquePredicate(
TestUtils.subnodesOfType(result, Literal.class), l -> l.getValue().equals(5));
assertEquals(int5, callExpression.getTemplateParameters().get(1));
assertEquals(
1, callExpression.getTemplateParametersPropertyEdge().get(1).getProperty(Properties.INDEX));
assertEquals(
TemplateDeclaration.TemplateInitialization.DEFAULT,
callExpression
.getTemplateParametersPropertyEdge()
.get(1)
.getProperty(Properties.INSTANTIATION));
}
@Test
void testCreateInferred() throws Exception {
// test invocation target when template parameter produces a cast in an argument
List<TranslationUnitDeclaration> result =
TestUtils.analyze(
List.of(Path.of(topLevel.toString(), "functionTemplateInvocation8.cpp").toFile()),
topLevel,
true);
// Check inferred for first fixed_division call
FunctionTemplateDeclaration templateDeclaration =
TestUtils.findByUniquePredicate(
TestUtils.subnodesOfType(result, FunctionTemplateDeclaration.class),
t -> t.getCode().equals("fixed_division<int,2>(10)"));
FunctionDeclaration fixedDivision =
TestUtils.findByUniquePredicate(
TestUtils.subnodesOfType(result, FunctionDeclaration.class),
f -> f.getCode().equals("fixed_division<int,2>(10)") && f.isInferred());
assertEquals(1, templateDeclaration.getRealization().size());
assertEquals(fixedDivision, templateDeclaration.getRealization().get(0));
assertEquals(2, templateDeclaration.getParameters().size());
assertTrue(templateDeclaration.getParameters().get(0) instanceof TypeParamDeclaration);
assertTrue(templateDeclaration.getParameters().get(1) instanceof ParamVariableDeclaration);
assertEquals(1, fixedDivision.getParameters().size());
CallExpression callInt2 =
TestUtils.findByUniquePredicate(
TestUtils.subnodesOfType(result, CallExpression.class),
c -> c.getLocation().getRegion().getStartLine() == 12);
assertEquals(1, callInt2.getInvokes().size());
assertEquals(fixedDivision, callInt2.getInvokes().get(0));
assertTrue(
callInt2
.getTemplateParameters()
.get(1)
.getNextDFG()
.contains(templateDeclaration.getParameters().get(1)));
// Check inferred for second fixed_division call
templateDeclaration =
TestUtils.findByUniquePredicate(
TestUtils.subnodesOfType(result, FunctionTemplateDeclaration.class),
t -> t.getCode().equals("fixed_division<double,3>(10.0)"));
fixedDivision =
TestUtils.findByUniquePredicate(
TestUtils.subnodesOfType(result, FunctionDeclaration.class),
f -> f.getCode().equals("fixed_division<double,3>(10.0)") && f.isInferred());
assertEquals(1, templateDeclaration.getRealization().size());
assertEquals(fixedDivision, templateDeclaration.getRealization().get(0));
assertEquals(2, templateDeclaration.getParameters().size());
assertTrue(templateDeclaration.getParameters().get(0) instanceof TypeParamDeclaration);
assertTrue(templateDeclaration.getParameters().get(1) instanceof ParamVariableDeclaration);
assertEquals(1, fixedDivision.getParameters().size());
CallExpression callDouble3 =
TestUtils.findByUniquePredicate(
TestUtils.subnodesOfType(result, CallExpression.class),
c -> c.getLocation().getRegion().getStartLine() == 13);
assertEquals(1, callDouble3.getInvokes().size());
assertEquals(fixedDivision, callDouble3.getInvokes().get(0));
assertTrue(
callDouble3
.getTemplateParameters()
.get(1)
.getNextDFG()
.contains(templateDeclaration.getParameters().get(1)));
// Check return values
assertEquals(UnknownType.getUnknownType(), callInt2.getType());
assertEquals(UnknownType.getUnknownType(), callDouble3.getType());
}
}
|
DaveVoorhis/Rel | DBrowser/src/org/reldb/dbrowser/ui/content/rel/view/VarViewPlayer.java | <reponame>DaveVoorhis/Rel<filename>DBrowser/src/org/reldb/dbrowser/ui/content/rel/view/VarViewPlayer.java
package org.reldb.dbrowser.ui.content.rel.view;
import org.eclipse.swt.custom.CTabItem;
import org.reldb.dbrowser.ui.content.rel.DbTreeAction;
import org.reldb.dbrowser.ui.content.rel.DbTreeItem;
import org.reldb.dbrowser.ui.content.rel.RelPanel;
import org.reldb.dbrowser.ui.content.rel.var.ExpressionResultViewerTab;
public class VarViewPlayer extends DbTreeAction {
public VarViewPlayer(RelPanel relPanel) {
super(relPanel);
}
@Override
public void go(DbTreeItem item, String imageName) {
CTabItem tab = relPanel.getTab(item);
if (tab != null) {
if (tab instanceof ExpressionResultViewerTab) {
relPanel.setTab(tab);
return;
} else
tab.dispose();
}
ExpressionResultViewerTab viewer = new ExpressionResultViewerTab(relPanel, item, null);
relPanel.setTab(viewer, imageName);
}
}
|
ralscha/eds-starter6-jpa | client/app/view/base/LockingWindow.js | /**
* This class provides the modal Ext.Window support for all Authentication forms. It's
* layout is structured to center any Authentication dialog within it's center
*/
Ext.define('Starter.view.base.LockingWindow', {
extend: 'Ext.window.Window',
cls: 'auth-locked-window',
closable: false,
resizable: false,
autoShow: true,
titleAlign: 'center',
maximized: true,
modal: true,
layout: {
type: 'vbox',
align: 'center',
pack: 'center'
}
});
|
Kanma/Athena-Core | unittests/Athena-Core/tests/test_LocationManager.cpp | #include <UnitTest++.h>
#include <Athena-Core/Data/LocationManager.h>
#include <Athena-Core/Data/DataStream.h>
#include <Athena-Core/Data/Serialization.h>
using namespace Athena;
using namespace Athena::Data;
using namespace std;
TEST(LocationManager_Singleton)
{
CHECK(!LocationManager::getSingletonPtr());
LocationManager* pLocationManager = new LocationManager();
CHECK(pLocationManager == LocationManager::getSingletonPtr());
delete pLocationManager;
CHECK(!LocationManager::getSingletonPtr());
}
struct LocationEnvironment
{
LocationEnvironment()
{
pLocationManager = new LocationManager();
}
~LocationEnvironment()
{
delete pLocationManager;
}
LocationManager* pLocationManager;
};
SUITE(LocationManager_Groups)
{
TEST_FIXTURE(LocationEnvironment, OneGroup)
{
pLocationManager->addLocation("group1", ATHENA_CORE_UNITTESTS_DATA_PATH);
CHECK_EQUAL(1, pLocationManager->nbGroups());
LocationManager::tGroupsList groups = pLocationManager->groups();
CHECK_EQUAL(1, groups.size());
CHECK_EQUAL("group1", groups[0]);
}
TEST_FIXTURE(LocationEnvironment, TwoGroups)
{
pLocationManager->addLocation("group1", ATHENA_CORE_UNITTESTS_DATA_PATH);
pLocationManager->addLocation("group2", ATHENA_CORE_UNITTESTS_DATA_PATH);
CHECK_EQUAL(2, pLocationManager->nbGroups());
LocationManager::tGroupsList groups = pLocationManager->groups();
CHECK_EQUAL(2, groups.size());
CHECK((groups[0] == "group1") || (groups[0] == "group2"));
CHECK((groups[1] == "group1") || (groups[1] == "group2"));
CHECK(groups[0] != groups[1]);
}
}
SUITE(LocationManager_Locations)
{
TEST_FIXTURE(LocationEnvironment, UnknownGroup)
{
LocationManager::tLocationsList locations = pLocationManager->locations("unknown");
CHECK_EQUAL(0, locations.size());
}
TEST_FIXTURE(LocationEnvironment, OneLocation)
{
pLocationManager->addLocation("default", ATHENA_CORE_UNITTESTS_DATA_PATH);
LocationManager::tLocationsList locations = pLocationManager->locations("default");
CHECK_EQUAL(1, locations.size());
CHECK_EQUAL(ATHENA_CORE_UNITTESTS_DATA_PATH, locations[0]);
}
TEST_FIXTURE(LocationEnvironment, TwoLocations)
{
pLocationManager->addLocation("default", ATHENA_CORE_UNITTESTS_DATA_PATH);
pLocationManager->addLocation("default", ATHENA_CORE_UNITTESTS_DATA_PATH + string(".."));
LocationManager::tLocationsList locations = pLocationManager->locations("default");
CHECK_EQUAL(2, locations.size());
CHECK_EQUAL(ATHENA_CORE_UNITTESTS_DATA_PATH, locations[0]);
CHECK_EQUAL(ATHENA_CORE_UNITTESTS_DATA_PATH + string(".."), locations[1]);
}
TEST_FIXTURE(LocationEnvironment, TwoGroups)
{
pLocationManager->addLocation("group1", ATHENA_CORE_UNITTESTS_DATA_PATH);
pLocationManager->addLocation("group2", ATHENA_CORE_UNITTESTS_DATA_PATH + string(".."));
LocationManager::tLocationsList locations = pLocationManager->locations("group1");
CHECK_EQUAL(1, locations.size());
CHECK_EQUAL(ATHENA_CORE_UNITTESTS_DATA_PATH, locations[0]);
locations = pLocationManager->locations("group2");
CHECK_EQUAL(1, locations.size());
CHECK_EQUAL(ATHENA_CORE_UNITTESTS_DATA_PATH + string(".."), locations[0]);
}
TEST_FIXTURE(LocationEnvironment, FromJSONFile)
{
rapidjson::Document document;
loadJSONFile(ATHENA_CORE_UNITTESTS_DATA_PATH "locations.json", document);
pLocationManager->addLocations(document);
LocationManager::tLocationsList locations = pLocationManager->locations("group1");
CHECK_EQUAL(2, locations.size());
CHECK_EQUAL("/location1", locations[0]);
CHECK_EQUAL("/location2", locations[1]);
locations = pLocationManager->locations("group2");
CHECK_EQUAL(2, locations.size());
CHECK_EQUAL("/location3", locations[0]);
CHECK_EQUAL("/location4", locations[1]);
}
}
SUITE(LocationManager_Paths)
{
TEST_FIXTURE(LocationEnvironment, UnknownGroup)
{
string path = pLocationManager->path("unknown", "lines.txt");
CHECK_EQUAL("", path);
}
TEST_FIXTURE(LocationEnvironment, UnknownFile)
{
pLocationManager->addLocation("default", ATHENA_CORE_UNITTESTS_DATA_PATH);
string path = pLocationManager->path("default", "unknown.txt");
CHECK_EQUAL("", path);
}
TEST_FIXTURE(LocationEnvironment, ExistingFile)
{
pLocationManager->addLocation("default", ATHENA_CORE_UNITTESTS_DATA_PATH);
string path = pLocationManager->path("default", "lines.txt");
CHECK_EQUAL(string(ATHENA_CORE_UNITTESTS_DATA_PATH) + "lines.txt", path);
}
}
SUITE(LocationManager_DataStream)
{
TEST_FIXTURE(LocationEnvironment, UnknownGroup)
{
DataStream* pStream = pLocationManager->open("unknown", "lines.txt");
CHECK(!pStream);
}
TEST_FIXTURE(LocationEnvironment, UnknownFile)
{
pLocationManager->addLocation("default", ATHENA_CORE_UNITTESTS_DATA_PATH);
DataStream* pStream = pLocationManager->open("default", "unknown.txt");
CHECK(!pStream);
}
TEST_FIXTURE(LocationEnvironment, ExistingFile)
{
pLocationManager->addLocation("default", ATHENA_CORE_UNITTESTS_DATA_PATH);
DataStream* pStream = pLocationManager->open("default", "lines.txt");
CHECK(pStream);
delete pStream;
}
}
|
Kinway050/bk-ci | src/backend/booster/bk_dist/controller/pkg/dashboard/dashboard.go | /*
* Copyright (c) 2021 THL A29 Limited, a Tencent company. All rights reserved
*
* This source code file is licensed under the MIT License, you may obtain a copy of the License at
*
* http://opensource.org/licenses/MIT
*
*/
package dashboard
import (
"net/http"
"github.com/Tencent/bk-ci/src/booster/common/http/httpserver"
"github.com/gobuffalo/packr/v2"
)
// RegisterStaticServer add the static server to router
func RegisterStaticServer(svr *httpserver.HTTPServer) error {
box := packr.New("controller_box", "../../../dashboard/static/controller")
svr.GetWebContainer().Handle("/", http.FileServer(box))
return nil
}
|
sridharshree303/MyProject | Dairy-Management-System-Chandhu/src/main/java/com/cg/dms/Status.java | <filename>Dairy-Management-System-Chandhu/src/main/java/com/cg/dms/Status.java
package com.cg.dms;
public enum Status {
APPROVED,PENDING,REJECTED;
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.