import { DataSourceApi, DataSourceInstanceSettings, DataSourceJsonData, DataSourcePluginMeta, DataSourceRef, ScopedVars, } from '@grafana/data'; import { GrafanaAlertStateDecision, GrafanaRuleDefinition, PromAlertingRuleState, PromRuleType, RulerAlertingRuleDTO, RulerGrafanaRuleDTO, RulerRuleGroupDTO, RulerRulesConfigDTO, } from 'app/types/unified-alerting-dto'; import { AlertingRule, Alert, RecordingRule, RuleGroup, RuleNamespace } from 'app/types/unified-alerting'; import DatasourceSrv from 'app/features/plugins/datasource_srv'; import { DataSourceSrv, GetDataSourceListFilters, config } from '@grafana/runtime'; import { AlertmanagerAlert, AlertManagerCortexConfig, AlertmanagerGroup, AlertmanagerStatus, AlertState, GrafanaManagedReceiverConfig, Silence, SilenceState, } from 'app/plugins/datasource/alertmanager/types'; let nextDataSourceId = 1; export function mockDataSource( partial: Partial> = {}, meta: Partial = {} ): DataSourceInstanceSettings { const id = partial.id ?? nextDataSourceId++; return { id, uid: `mock-ds-${nextDataSourceId}`, type: 'prometheus', name: `Prometheus-${id}`, access: 'proxy', jsonData: {} as T, meta: ({ info: { logos: { small: 'https://prometheus.io/assets/prometheus_logo_grey.svg', large: 'https://prometheus.io/assets/prometheus_logo_grey.svg', }, }, ...meta, } as any) as DataSourcePluginMeta, ...partial, }; } export const mockPromAlert = (partial: Partial = {}): Alert => ({ activeAt: '2021-03-18T13:47:05.04938691Z', annotations: { message: 'alert with severity "warning"', }, labels: { alertname: 'myalert', severity: 'warning', }, state: PromAlertingRuleState.Firing, value: '1e+00', ...partial, }); export const mockRulerGrafanaRule = ( partial: Partial = {}, partialDef: Partial = {} ): RulerGrafanaRuleDTO => { return { for: '1m', grafana_alert: { uid: '123', title: 'myalert', namespace_uid: '123', namespace_id: 1, condition: 'A', no_data_state: GrafanaAlertStateDecision.Alerting, exec_err_state: GrafanaAlertStateDecision.Alerting, data: [ { datasourceUid: '123', refId: 'A', queryType: 'huh', model: {} as any, }, ], ...partialDef, }, annotations: { message: 'alert with severity "{{.warning}}}"', }, labels: { severity: 'warning', }, ...partial, }; }; export const mockRulerAlertingRule = (partial: Partial = {}): RulerAlertingRuleDTO => ({ alert: 'alert1', expr: 'up = 1', labels: { severity: 'warning', }, annotations: { summary: 'test alert', }, }); from sanic import Sanic, response, Blueprint from sanic.request import RequestParameters from sanic_jinja2 import SanicJinja2 from sanic_session import Session, AIORedisSessionInterface import aiosqlite import aiofiles import aioredis import asyncio import json import html import sys import os import re from route.tool.tool import * from route.mark.py.namumark import * setting_data = json.loads(open('data/setting.json', encoding = 'utf8').read()) version_load = json.loads(open('data/version.json', encoding='utf-8').read()) engine_version = version_load["main"]["engine_version"] markup_version = version_load["main"]["markup_version"] build_count = version_load["main"]["build_count"] renew_count = version_load["main"]["renew_count"] print('') print('VientoEngine') print('engine_version : ' + engine_version) print('markup_version : ' + markup_version) print('build_count : ' + build_count) print('renew_count : ' + renew_count) print('') for route_file in os.listdir("route"): py_file = re.search(r"(.+)\.py$", route_file) if py_file: py_file = py_file.groups()[0] exec("from route." + py_file + " import *") ## 위키 설정 async def run(): server_setting = { "host" : { "setting": "host", "default": "0.0.0.0" }, "port" : { "setting": "port", "default": "3000" }, "lang" : { "setting": "lang", "default": "ko-KR", "list" : ["ko-KR", "en-US"] }, "encode" : { "setting": "encode", "default": "pbkdf2-sha512", "list" : ["sha3", "sha256", "pbkdf2-sha512"] } } try: async with aiofiles.open('data/setting.json', encoding = 'utf8') as f: setting_data = json.loads(await f.read()) if not 'db_type' and 'db_name' and 'host' and 'port' in setting_data: try: os.remove('data/setting.json') except: print('Error : Please delete data/setting.json') raise else: print('db_type : ' + setting_data['db_type']) print('db_name : ' + setting_data['db_name']) print('\n', end='') print('host : ' + setting_data['host']) print('port : ' + setting_data['port']) except: setting_json = ['sqlite', '', '', ''] db_type = ['sqlite'] print('db_type : sqlite') print('db_name : ', end = '') setting_json[1] = str(input()) if setting_json[1] == '': setting_json[1] = 'data' print('\n', end='') print('host (' + server_setting['host']['default'] + ') : ', end = '') setting_json[2] = str(input()) if setting_json[2] == '': setting_json[2] = server_setting['host']['default'] print('port (' + /** * @ Author: SeroBot Team * @ Create Time: 2021-05-31 22:33:11 * @ Modified by: Danang Dwiyoga A (https://github.com/dngda/) * @ Modified time: 2021-06-21 00:40:55 * @ Description: Search kata kotor dan nsfw */ import fs from 'fs-extra' const { readFileSync } = fs const kataKasar = JSON.parse(readFileSync('./settings/katakasar.json')) const nsfwQuery = JSON.parse(readFileSync('./settings/nsfwquery.json')) const inArray = (needle, haystack) => { let length = haystack.length for (let i = 0; i < length; i++) { if (haystack[i] == needle) return true } return false } const cariKasar = (sentence) => new Promise((resolve) => { if (sentence !== undefined) { let words = sentence.split(/\s/g) for (let word of words) { if (inArray(word, kataKasar)) { resolve(true) } } resolve(false) } }) const cariNsfw = (sentence) => new Promise((resolve) => { if (sentence !== undefined) { let words = sentence.split(/\s/g) for (let word of words) { if (inArray(word, nsfwQuery)) { resolve(true) } } resolve(false) } }) export default cariKasar export { cariNsfw } Python Socket gives "[Errno 24] Too many open files"

I have the following UDP class sending arrays of data at about 100Hz

from six import string_types
import socket
import struct

def convert_data(iterable):
    if isinstance(iterable, string_types):
        return str(iterable)
    data = tuple(iterable)
    format = "{0}H".format(len(data))
    print("Sending data:", format, data)
    if max(data) > 2**16 - 1:
        raise ValueError(max(data))
    if min(data) < 0:
        raise ValueError(min(data))
    return struct.pack(format, *data)

class UDP(object):
    def __init__(self, ip, port):
        self._ip = ip
        self._port = port
        self.socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        self.socket.connect((ip, port))

    def send_data(self, data):
        message = convert_data(data)
        return self.socket.sendall(message)

It gives the following error after successfully sending for about a minute:

Traceback (most recent call last):
  File "take_analogue_data.py", line 13, in <module>
  File "take_analogue_data.py", line 8, in main
  File "/home/pi/nio-integration/hardware/raspi/UDP.py", line 22, in __init__
  File "/usr/lib/python2.7/socket.py", line 187, in __init__
socket.error: [Errno 24] Too many open files

I have looked for a solution. This Stack Overflow answer suggests increasing the number of possible files. I really don't think this is the solution I am looking for though.

Is there something I can do? I was thinking that closing the connection each time might work, but I have already played around with a bunch of things. (I have tried send, sendall, and sendto -- none have worked)

Note: I am running Python2.6 on Raspbian Wheezy on a Raspberry Pi

Edit Another module is sending the data. It could look something like

import UDP
udp = UDP.UDP(IP, PORT)
while(True):
    udp.send_data(range(8))
    sleep(0.01)
How do I export a TensorFlow model as a .tflite file?

Background information:

I have written a TensorFlow model very similar to the premade iris classification model provided by TensorFlow. The differences are relatively minor:

  • I am classifying football exercises, not iris species.
  • I have 10 features and one label, not 4 features and one label.
  • I have 5 different exercises, as opposed to 3 iris species.
  • My trainData contains around 3500 rows, not only 120.
  • My testData contains around 330 rows, not only 30.
  • I am using a DNN classifier with n_classes=6, not 3.

I now want to export the model as a .tflite file. But according to the TensorFlow Developer Guide, I need to first export the model to a tf.GraphDef file, then freeze it and only then will I be able to convert it. However, the tutorial provided by TensorFlow to create a .pb file from a custom model only seems to be optimized for image classification models.

Question:

So how do I convert a model like the iris classification example model into a .tflite file? Is there an easier, more direct way to do it, without having to export it to a .pb file, then freeze it and so on? An example based on the iris classification code or a link to a more explicit tutorial would be very useful!


Other information:

  • OS: macOS 10.13.4 High Sierra
  • TensorFlow Version: 1.8.0
  • Python Version: 3.6.4
  • Using PyCharm Community 2018.1.3

Code:

The iris classification code can be cloned by entering the following command:

git clone https://github.com/tensorflow/models

But in case you don't want to download the whole package, here it is:

This is the classifier file called premade_estimator.py:

### User: Explain what .gitignore does, and what happens if I add a file that's already committed? ### Assistant: .gitignore tells git which files not to offer for staging: build artifacts, dependencies, local configs, secrets. It only filters untracked files. The important nuance: if a file is already committed, adding it to .gitignore changes nothing — git keeps tracking its changes. To make git "forget" the file while keeping it on disk, run `git rm --cached path/to/file` and commit that removal. After that, .gitignore applies to it as expected. How does concurrent.futures.as_completed work?

I'm learning about python concurrency and I was introduced with the concept of futures. I read that as_completed() takes an iterable of futures and yields them as they are done.

I want to know how it works internally. Is it yielding completed tasks (futures) immediately? A naive approach would be to iterate all futures and examine each and every future using done(), but this is inefficient.

So what's the magic behind this function?

Thanks!

import scipy.sparse as sp import numpy as np import torch import time import os from configparser import ConfigParser import sys sys.path.append('/home/shiyan/project/gcn_for_prediction_of_protein_interactions/') from src.util.load_data import load_data, sparse_to_tuple, mask_test_edges, preprocess_graph from src.util.loss import arga_loss_function, varga_loss_function from src.util.metrics import get_roc_score from src.util import define_optimizer from src.graph_nheads_att_gan.model import NHGATModelGAN DEVICE = torch.device('cuda' if torch.cuda.is_available() else 'cpu') class Train(): def __init__(self): pass def train_model(self, config_path): if os.path.exists(config_path) and (os.path.split(config_path)[1].split('.')[0] == 'config') and ( os.path.splitext(config_path)[1].split('.')[1] == 'cfg'): # load config file config = ConfigParser() config.read(config_path) section = config.sections()[0] # data catalog path data_catalog = config.get(section, "data_catalog") # train file path train_file_name = config.get(section, "train_file_name") # model save/load path model_path = config.get(section, "model_path") # model param config hidden_dim1 = config.getint(section, "hidden_dim1") hidden_dim2 = config.getint(section, "hidden_dim2") hidden_dim3 = config.getint(section, 'hidden_dim3') num_heads = config.getint(section, 'num_heads') dropout = config.getfloat(section, "dropout") vae_bool = config.getboolean(section, 'vae_bool') alpha = config.getfloat(section, 'alpha') lr = config.getfloat(section, "lr") lr_decay = config.getfloat(section, 'lr_decay') weight_decay = config.getfloat(section, "weight_decay") gamma = config.getfloat(section, "gamma") momentum = config.getfloat(section, "momentum") eps = config.getfloat(section, "eps") clip = config.getfloat(section, "clip") epochs = config.getint(section, "epochs") optimizer_name = config.get(section, "optimizer") # 加载相关数据 adj = load_data(os.path.join(data_catalog, train_file_name)) num_nodes = adj.shape[0] num_edges = adj.sum() features = sparse_to_tuple(sp.identity(num_nodes)) num_features = features[2][1] # 去除对角线元素 # 下边的右部分为:返回adj_orig的对角元素(一维),并增加一维,抽出adj_orig的对角元素并构建只有这些对角元素的对角矩阵 adj_orig = adj - sp.dia_matrix((adj.diagonal()[np.newaxis, :], [0]), shape=adj.shape) adj_orig.eliminate_zeros() adj_train, train_edges, val_edges, val_edges_false, test_edges, test_edges_false = mask_test_edges(adj_orig) adj = adj_train INSERT INTO `control` (`id`, `documento`, `imagen`, `img`, `estado`, `estado_upload`, `observacion`, `users_id`, `fecha_creacion`) VALUES (1, '100', 'cedula', '100.pdf', 'pendiente', 2, 'nuevo200333', 3, '2021-03-09 02:05:14'), (2, '100', 'recibo', '100.png', 'pendiente', 1, 'nuevojjj', 3, '2021-03-09 02:06:23'), (3, '100', 'certificado_postulacion', '100.jpg', 'pendiente', 2, 'grtui', 3, '2021-03-09 02:17:02'), (4, '100', 'certificado_sisben', '100.png', 'Correcto', 1, 'ferty', 3, '2021-03-09 02:39:09'); -- -------------------------------------------------------- -- -- Estructura de tabla para la tabla `users` -- CREATE TABLE `users` ( `id` int(11) NOT NULL, `username` varchar(50) NOT NULL, `email` varchar(80) NOT NULL, `password` varchar(250) NOT NULL, `perfil` varchar(50) NOT NULL, `authKey` varchar(250) NOT NULL, `accessToken` varchar(250) NOT NULL, `activate` tinyint(1) NOT NULL DEFAULT 1 ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -- Volcado de datos para la tabla `users` -- INSERT INTO `users` (`id`, `username`, `email`, `password`, `perfil`, `authKey`, `accessToken`, `activate`) VALUES (1, 'mai', 'mai@gmail.com', 'fsbqobwqC.aMo', 'admin', '709409aef90a926a5df642c31e4ccefe26e37f85af5ad3acb1baceb479331d6f623381346422a6b03c180a814c1c432c6c94e3a45c3044aab007feb079be986ec78e14ebb9810832431fe11dc305675a6c43f8ea5e87a5b93d4257ef428015111be0d3fe', '32f79b3c278f3db2cb36634b36c7c8d639bd56fc2b43edf339141422cdb3e9452d02164aa5aed00d9a2d436845cd7a4b0f107572740e198039142920884796726c8cf21aa4227d09ad3d1790abeb0130b9a5ca26f0814056bce80c102863cc362e2f49e9', 1), (2, 'sak', 'sak@gmail.com', 'fsbqobwqC.aMo', 'funcionario', '25bdd4bdbfb9a49dc90bb5901ea7810ea76495b3da45f6d77731cb551676f9eba7d15c52bd80cfbccc24d554ccbc7edcd9fa8ac0aabcd863b5fd8d4e10caaad713686a51865f0965c5ad5d676f6cebfd4c653c996f23b52cd053f1e2d918546de08e0bc6', '693c86bc5a74101a699e91bf49ab668b6a3d330fb3aabba58075afd66292894f9550879715dec9e7ddfa456c01f1f85969683089122f8fce1c401a0b92411979727fc7c27826470048ecdf2fcc60e11225aaad7de7cc43192042feaa7b8d3c1bccf4b69c', 1), (3, 'admin', 'admin@admin.com', 'fsmNAnxm5cBw.', 'admin', '44863c265a7b62e49cc6568547133ef57aeaba5af8997ae18675c81452a117ec5e5f611c10e2a651f48edc768cb7db5f5097aee2e732a43b663424c9901bf339cd40adf952209e201425e213b289c0c9687dd7d681e681944dde15f28a2d2c4bf40f3abd', '523699c47a98c6f8b14ce532b2deacff00b02ef334cecf03b2fd03abc6a064a5703c2450cbd29298e55bda18f00505b4c32f8201e648f69ddbb90c52ef15e7c6c2b7ea9398f50da1c82bba7aa99d725f68f80e12fe841391fa8f16140e48d3dbf2821447', 1); -- -- Índices para tablas volcadas -- -- -- Indices de la tabla `adulto` -- ALTER TABLE `adulto` ADD PRIMARY KEY (`id`), ADD UNIQUE KEY `documento` (`documento`); -- -- Indices de la tabla `control` -- ALTER TABLE `control` ADD PRIMARY KEY (`id`); -- -- Indices de la tabla `users` -- ALTER TABLE `users` ADD PRIMARY KEY (`id`); -- -- AUTO_INCREMENT de las tablas volcadas -- /* * Copyright 2014 Midokura SARL * * 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.midonet.config; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.util.Properties; import java.util.UUID; import org.junit.After; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.midonet.conf.HostIdGenerator; public class TestHostIdGenerator { static final String uuidPropertyName = "host_uuid"; static final String hostId = "e3f9adc0-5175-11e1-b86c-0800200c9a67"; File propFile; @After public void tearDown() throws Exception { if (propFile.exists()) propFile.delete(); } @Before public void setUp() throws Exception { propFile = new File(HostIdGenerator.useTemporaryHostId()); Properties properties = new Properties(); properties.setProperty(uuidPropertyName, hostId); properties.store(new FileOutputStream(propFile.getAbsolutePath()), null); } @Test public void getIdFromPropertyFile() throws Exception { UUID id = HostIdGenerator.getHostId(); Assert.assertTrue(id.toString().equals(hostId)); } @Test public void generateRandomId() throws Exception { // delete properties file boolean res = propFile.delete(); Assert.assertTrue(res); UUID id = HostIdGenerator.getHostId(); // check that the id has been written in the property file boolean exists = propFile.exists(); Assert.assertTrue(exists); Properties properties = new Properties(); properties.load(new FileInputStream(propFile.getAbsolutePath())); UUID idFromProperty = UUID.fromString( properties.getProperty(uuidPropertyName)); Assert.assertTrue(id.equals(idFromProperty)); } @Test(expected = HostIdGenerator.PropertiesFileNotWritableException.class) public void propertyFileCorrupted() throws Exception { // delete properties file so no ID will be loaded from there boolean res = propFile.delete(); propFile.createNewFile(); propFile.setReadOnly(); UUID id = HostIdGenerator.getHostId(); } } d)arg1 ; +(id)deviceForIDSDeviceID:(id)arg1 fromList:(id)arg2 ; +(id)deviceForIDSDevice:(id)arg1 ; -(NSString *)deviceClass; -(NSString *)systemBuildVersion; -(NSUUID *)pairingID; -(PBCodable *)stateForLogging; -(BOOL)isTargetable; -(BOOL)supportsFileTransferMessageSend; -(id)initWithNRDevice:(id)arg1 ; -(void)_updateStateFlagsPostingNotifications:(BOOL)arg1 ; -(void)_updateCachedStateForProperty:(id)arg1 ; -(long long)deviceCode; -(id)findMatchingIDSDeviceFromList:(id)arg1 ; -(NSDate *)lastActiveDate; -(BOOL)hasCachedNearby; -(void)setHasCachedNearby:(BOOL)arg1 ; -(BOOL)cachedIsNearby; -(void)setCachedIsNearby:(BOOL)arg1 ; -(void)device:(id)arg1 propertyDidChange:(id)arg2 fromValue:(id)arg3 ; -(BOOL)isPaired; -(NSString *)pairingStorePath; -(NRDevice *)nrDevice; -(id)init; -(BOOL)isEqual:(id)arg1 ; -(NSString *)description; -(NSString *)debugDescription; -(long long)state; -(BOOL)isActive; -(void)setState:(long long)arg1 ; -(NSString *)systemVersion; @end /* Created RJudd */ /* SPAWARSYSCEN D881 */ /********************************************************************** // For TASP VSIPL Documentation and Code neither the United States / // Government, the United States Navy, nor any of their employees, / // makes any warranty, express or implied, including the warranties / // of merchantability and fitness for a particular purpose, or / // assumes any legal liability or responsibility for the accuracy, / // completeness, or usefulness of any information, apparatus, / // product, or process disclosed, or represents that its use would / // not infringe privately owned rights / **********************************************************************/ /* $Id: vsip_cvrandn_d.c,v 2.0 2003/02/22 15:18:51 judd Exp $ */ #include #include #include #include void vsip_cvrandn_d( vsip_randstate *state, const vsip_cvview_d *r) { if(state->type) { /* nonportable generator */ vsip_scalar_ue32 a = state->a, c = state->c, X = state->X; vsip_length n = r->length; /* register */ vsip_stride rst = r->stride * r->block->cstride; vsip_scalar_d *rpr = (r->block->R->array) + r->offset * r->block->cstride; vsip_scalar_d *rpi = (r->block->I->array) + r->offset * r->block->cstride; while(n-- > 0){ vsip_scalar_d t2; X = a * X + c; *rpr = (vsip_scalar_d)X/4294967296.0; X = a * X + c; *rpr += (vsip_scalar_d)X/4294967296.0; X = a * X + c; *rpr += (vsip_scalar_d)X/4294967296.0; X = a * X + c; t2 = (vsip_scalar_d)X/4294967296.0; X = a * X + c; t2 += (vsip_scalar_d)X/4294967296.0; X = a * X + c; t2 += (vsip_scalar_d)X/4294967296.0; *rpi = *rpr - t2; *rpr = 3 - t2 - *rpr; rpr += rst; rpi += rst; } state->X = X; } else { /* portable generator */ vsip_scalar_ue32 itemp; vsip_length n = r->length; /* register */ vsip_stride rst = r->stride * r->block->cstride; vsip_scalar_d *rpr = (r->block->R->array) + r->offset * r->block->cstride; vsip_scalar_d *rpi = (r->block->I->array) + r->offset * r->block->cstride; while(n-- > 0){ vsip_scalar_d t2; state->X = state->X * state->a + state->c; state->X1 = state->X1 * state->a1 + state->c1; itemp = state->X - state->X1; if(state->X1 == state->X2){ state->X1++; state->X2++; } *rpr = (vsip_scalar_d)itemp/4294967296.0; state->X = state->X * state->a + state->c; state->X1 = state->X1 * state->a1 + state->c1; itemp = state->X - state->X1; if(state->X1 == state->X2){ state->X1++; st /*! ========================================================= * Argon Design System React - v1.1.0 ========================================================= * Product Page: https://www.creative-tim.com/product/argon-design-system-react * Copyright 2020 Creative Tim (https://www.creative-tim.com) * Licensed under MIT (https://github.com/creativetimofficial/argon-design-system-react/blob/main/LICENSE.md) * Coded by Creative Tim ========================================================= * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. */ import React from "react"; // reactstrap components import { Button, Container, Row, Col } from "reactstrap"; class BasicElements extends React.Component { render() { return ( <>
{/* Basic elements */}

Basic Elements

{/* Buttons */}

Buttons Yay

{/* Button styles */}
{/* Button wizes */}
Pick your size
// Copyright 2016 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 or the MIT license // , at your // option. This file may not be copied, modified, or distributed // except according to those terms. use super::*; pub struct TransposedGraph { base_graph: G, start_node: G::Node, } impl TransposedGraph { pub fn new(base_graph: G) -> Self { let start_node = base_graph.start_node(); Self::with_start(base_graph, start_node) } pub fn with_start(base_graph: G, start_node: G::Node) -> Self { TransposedGraph { base_graph: base_graph, start_node: start_node } } } impl ControlFlowGraph for TransposedGraph { type Node = G::Node; fn num_nodes(&self) -> usize { self.base_graph.num_nodes() } fn start_node(&self) -> Self::Node { self.start_node } fn predecessors<'graph>(&'graph self, node: Self::Node) -> >::Iter { self.base_graph.successors(node) } fn successors<'graph>(&'graph self, node: Self::Node) -> >::Iter { self.base_graph.predecessors(node) } } impl<'graph, G: ControlFlowGraph> GraphPredecessors<'graph> for TransposedGraph { type Item = G::Node; type Iter = >::Iter; } impl<'graph, G: ControlFlowGraph> GraphSuccessors<'graph> for TransposedGraph { type Item = G::Node; type Iter = >::Iter; } Echyridella onekaka is a species of freshwater mussel endemic to New Zealand. E. onekaka is an aquatic bivalve mollusc in the family Unionidae, the river mussels. Taxonomy The species was first recognised as a distinct species by Mark Fenwick and Bruce Marshall in 2006. It can be distinguished from Echyridella menziesii by a more strongly separated anterior pedal retractor muscle. Distribution Echyridella onekaka is found exclusively in the north-west of the South Island. It is the rarest known freshwater mussel species in New Zealand. References Unionidae Bivalves of New Zealand Bivalves described in 2006 Endemic fauna of New Zealand Endemic molluscs of New Zealand html.TextBoxFor and html.Textbox, POSTing values, model in parameters

Alright guys, Need some help!

Im working with asp.net mvc3 razor (and am fairly new to it but did lots of web forms)

Okay so onto the problem

My question revolves around submitting a view. I have a very complicated model that my view is based off (strongly typed).

I want to return the model into the arguments in the HttpPost method of the controller. do basically:

public ActionResult Personal()
    {
        DataModel dataModel = new DataModel();
        FormModel model = new FormModel();
        model.candidateModel = dataModel.candidateModel;
        model.lookupModel = new LookupModel();

        return View(model);
    }

    [HttpPost]
    public ActionResult Personal(FormModel formModel)
    {
        if (ModelState.IsValid)
        {
            //stuff
        }
        return View(formModel);
    }

Now...
I'm having trouble getting values into the formModel parameter on the post method.

This works (meaning i can see the value)but is tedious as i have to write exactly where it sits in a string every single field:

@Html.TextBox("formModel.candidateModel.tblApplicant.FirstName", Model.candidateModel.tblApplicant.FirstName)

It renders like this:

<input name="formModel.candidateModel.tblApplicant.FirstName" id="formModel_candidateModel_tblApplicant_FirstName" type="text" value="Graeme"/>

This doesn't work:

@Html.TextBoxFor(c => c.candidateModel.tblApplicant.FirstName)

It renders like this:

<input name="candidateModel.tblApplicant.FirstName" id="candidateModel_tblApplicant_FirstName" type="text" value="Graeme"/>

Now I'm assuming the problem lies in the discrepancy of the id's

So please answer me this:

  1. Am i going about this the right way
  2. Why doesn't textboxfor get the right value/id, and how do i make it get the right value/id so i can retrieve it in a POST(if that is even the problem)?
  3. Additionally, it seems that textboxfor is restrictive, in the manner that if you have a date time, how do you use the .toshortdate() method? This makes me think textboxfor isn't useful for me.

Quick clarification: when i say textboxfor isn't working, it IS getting values when i GET the form. So they fill, but on the POST / submission, i can't see them in the formModel in the parameters.

Another side note:
None of the html helpers work, this is the problem. They aren't appearing in modelstate either.


Thanks everyone for the help

-- Document editor drop table o_wopi_access; create table o_de_access ( id number(20) generated always as identity, creationdate timestamp not null, lastmodified timestamp not null, o_editor_type varchar(64) not null, o_expires_at timestamp not null, o_mode varchar(64) not null, o_version_controlled number default 0 not null, fk_metadata number(20) not null, fk_identity number(20) not null, primary key (id) ); create table o_de_user_info ( id number(20) generated always as identity, creationdate timestamp not null, lastmodified timestamp not null, o_info varchar(2048) not null, fk_identity number(20) not null, primary key (id) ); create unique index idx_de_userinfo_ident_idx on o_de_user_info(fk_identity); -- Assessment alter table o_as_entry add a_current_run_start timestamp; alter table o_as_mode_course add a_end_status varchar(32); alter table o_qti_assessmenttest_session add q_max_score decimal; -- Disadvantage compensation alter table o_qti_assessmenttest_session add q_compensation_extra_time number(20); create table o_as_compensation ( id number(20) generated always as identity, creationdate timestamp not null, lastmodified timestamp not null, a_subident varchar(512), a_subident_name varchar(512), a_extra_time number(20) not null, a_approved_by varchar(2000), a_approval timestamp, a_status varchar(32), fk_identity number(20) not null, fk_creator number(20) not null, fk_entry number(20) not null, primary key (id) ); alter table o_as_compensation add constraint compensation_ident_idx foreign key (fk_identity) references o_bs_identity (id); create index idx_compensation_ident_idx on o_as_compensation(fk_identity); alter table o_as_compensation add constraint compensation_crea_idx foreign key (fk_creator) references o_bs_identity (id); create index idx_compensation_crea_idx on o_as_compensation(fk_creator); alter table o_as_compensation add constraint compensation_entry_idx foreign key (fk_entry) references o_repositoryentry (repositoryentry_id); create index idx_compensation_entry_idx on o_as_compensation(fk_entry); create table o_as_compensation_log ( id number(20) generated always as identity, creationdate timestamp not null, a_action varchar(32) not null, a_val_before CLOB, a_val_after CLOB, a_subident varchar(512), fk_entry_id number(20) not null, fk_identity_id number(20) not null, fk_compensation_id number(20) not null, fk_author_id number(20), primary key (id) ); create index comp_log_entry_idx on o_as_compensation_log (fk_entry_id); create index comp_log_ident_idx on o_as_compensation_log (fk_identity_id); -- Appointments alter table o_ap_appointment add fk_meeting_id number(20); alter table o_ap_appointment add constraint ap_appointment_meeting_idx foreign key (fk_meeting_id) references o_bbb_meeting (id); create index idx_ap_appointment_meeting_idx on o_ap_appointment(fk_meeting_id); // Connect is a command that tells the Hub to connect a Conn to the given topics. // After connecting, the Conn will receive messages from all the topics until it // disconnects, the topics are closed or the hub is closed. // // If no topics are specified, the Conn will receive all messages from the default topic. Connect struct { Conn Conn Topics []Topic // The total number of messages the connection should receive. // Reset this value for the connection by resending this command with // the same Conn. MessageCount Number // Set this to true if you want the hub to not close the Conn channel automatically // when the Conn isn't connected to any topics, or it has received the specified // number of messages. KeepAlive bool } // ConnectEach is similar to Connect, but you can also specify how many messages // the Conn should receive from each Topic individually. In other words, Connect // would basically be ConnectEach with unset TopicConn.MessageCount. // // If no topics are specified, the Conn will receive all messages from the default topic. ConnectEach struct { Conn Conn Topics []TopicConn MessageCount Number KeepAlive bool } // Disconnect is a command that tells the Hub to stop sending messages from the // given topics to the Conn. If no topics are given, the Conn is disconnected // from the default topic. Also, if KeepAlive wasn't set on connection its channel is also // closed. Disconnect struct { Conn Conn Topics []Topic } // DisconnectAll is the same as Disconnect, but it disconnects the Conn from all the // topics it is connected to. DisconnectAll Conn // Message is a command that tells the Hub to publish the given Message to each // given Topic. If no topic is provided, the Hub publishes is to the default topic. Message struct { Message interface{} Topics []Topic } // Close is a command that tells the hub to disconnect all connections that are // connected to the given topics. If no topics are given the default topic is // closed. Close []Topic // CloseAll is similar to Close, but it disconnects the connections from all topics. CloseAll struct{} ) func (c *Connect) toConnectEach() *ConnectEach { topics := make([]TopicConn, 0, len(c.Topics)) for _, t := range c.Topics { topics = append(topics, TopicConn{Topic: t}) } return &ConnectEach{ Conn: c.Conn, Topics: topics, MessageCount: c.MessageCount, KeepAlive: c.KeepAlive, } } // New creates a Hub channel and starts the command execution loop. // It also returns a channel that blocks until the hub is closed. func New() (Hub, <-chan struct{}) { h := make(Hub) done := make(chan struct{}) go func() { h.Start() close(done) }() return h, done } // Start starts the hub. Run this in a new goroutine. Don't call Start if you have created the // Hub using New! func (h Hub) Start() { m := newManager() defer m.close() Using JPA CriteriaBuilder to generate query where attribute is either in a list or is empty

I am trying to use the JPA CriteriaBuilder to generate a query for an entity called "TestContact" that has a many-to-many join with another entity called "SystemGroup" where the attribute for this join called "groups". The objective of the query is to retrieve records from the "TestContact" entity where the "groups" attribute is either in a list or is empty.

The code I'm using is as follows

public List<TestContact> findWithCriteriaQuery(List<SystemGroup> groups) {

    CriteriaBuilder cb = em.getCriteriaBuilder();
    CriteriaQuery<TestContact> cq = cb.createQuery(TestContact.class);
    Root<TestContact> testContact = cq.from(TestContact.class);
    cq.select(testContact);

    Path<List<SystemGroup>> groupPath = testContact.get("groups");

    // cq.where(groupPath.in(groups));
    // cq.where(cb.isEmpty(groupPath));
    cq.where(cb.or(cb.isEmpty(groupPath), groupPath.in(groups)));

    TypedQuery<TestContact> tq = em.createQuery(cq);

    return tq.getResultList();
}

The problem is this query only returns results where group is in the list "groups" but for some reason isn't also returning the results where group is empty (i.e. there is no entry in the join table)

If I change the where clause to cq.where(cb.isEmpty(groupPath)); then the query correctly returns the results where group is empty.

If I change the where clause to cq.where(groupPath.in(groups)); then the query correctly returns the results where the group is in the list "groups".

What I don't understand is why when I try to combine these two predicates using the CriteriaBuilder or method the results don't include the records where the group is either in the list or is empty.

The groups attribute in the "TestContact" entity is declared as follows

@ManyToMany(fetch=FetchType.EAGER)
@JoinTable(name = "TEST_CONTACT_GROUPS", joinColumns = { @JoinColumn(name = "CONTACT_ID", referencedColumnName = "CONTACT_ID") }, inverseJoinColumns = { @JoinColumn(name = "GROUP_ID", referencedColumnName = "GROUP_ID") })
private List<SystemGroup> groups;

The JPA provider is EclipseLink 2.5.0, the Java EE application server is GlassFish 4 and the database is Oracle 11gR2.

Can anyone please point out where I'm going wrong?

Update

I've tried the suggestion from @Chris but Eclipse is returning the following error on Join<List<SystemGroup>> groupPath = testContact.join("groups", JoinType.LEFT)

Incorrect number of arguments for type Join; it cannot be parameterized with arguments >

Looking at the JavaDoc for Join it says the type parameters are...

/** * agregarModal * * Setea valores mediante JQUERY al modal como el titulo y el boton * ? ya que se usa el mismo modal para crear y editar */ function agregarModal() { $("#exampleModalLabel").text("Agregar - Especialidad"); $("#nombre_especialidad").val(''); $("#accionForm").html(''); $('#formModal').modal({ show: true }); } /** * editarModal * * Setea valores mediante JQUERY al modal como el titulo y el boton * ? ya que se usa el mismo modal para crear y editar * @param id se guarda el id de la especialidad a editar * @param piso_id se guarda el piso_id de la especialidad a editar * @param nombre se muestra el nombre de la especialidad a editar */ function editarModal(id, piso_id, nombre,color,alias) { $("#exampleModalLabel").text("Editar - Especialidad"); $("#especialidad_id").val(id); $("#nombre_especialidad").val(nombre); $("#alias_especialidad").val(alias); $("#comboPiso").val(piso_id); $("#color").val(color); $("#accionForm").html(''); $('#formModal').modal({ show: true }); } /** * InsertarEspecialidad() * * Envia valores del formulario a la accion crear * ! envio mediante POST ajax * @param dir directorio del proyecto * @param nombre nombre de la especialidad a insertar * @param piso piso_id de la especialidad a insertar */ function InsertarEspecialidad() { var nombre = $("#nombre_especialidad").val(); var alias = $("#alias_especialidad").val(); var piso = $("#comboPiso").val(); var color = $("#color").val(); var dir = $('#dir').val(); console.log(color); // Copyright (c) Microsoft Corporation. // Licensed under the MIT License. import { getTracer } from "@azure/core-tracing"; import { Span, SpanOptions, SpanKind } from "@opentelemetry/types"; import { OperationTracingOptions } from "../StorageClient"; /** * Creates a span using the global tracer. * @param name The name of the operation being performed. * @param tracingOptions The tracingOptions for the underlying http request. */ export function createSpan( operationName: string, tracingOptions: OperationTracingOptions = {} ): { span: Span; spanOptions: SpanOptions } { const tracer = getTracer(); const spanOptions: SpanOptions = { ...tracingOptions.spanOptions, kind: SpanKind.INTERNAL }; const span = tracer.startSpan(`Azure.Storage.File.${operationName}`, spanOptions); let newOptions = tracingOptions.spanOptions || {}; if (span.isRecording()) { newOptions = { ...tracingOptions, parent: span }; } return { span, spanOptions: newOptions }; } ### User: write a typescript debounce function with a configurable delay ### Assistant: ```typescript function debounce void>( fn: T, delayMs: number, ): (...args: Parameters) => void { let timer: ReturnType | undefined; return (...args: Parameters) => { if (timer !== undefined) { clearTimeout(timer); } timer = setTimeout(() => { timer = undefined; fn(...args); }, delayMs); }; } // usage: search fires 300ms after the last keystroke const onSearchInput = debounce((query: string) => { runSearch(query); }, 300); ``` If you need a leading-edge variant (fire immediately, then suppress) or a promise-returning one, say so and I'll extend it. Adding CSS in AJAX function

I have an AJAX function to hide and show fields of a form in HTML. I want to add some CSS in the AJAX function.

<script>
    $(function() {

        $('#advo_other').hide();
        $('#advocate').change(function() {

            var val = $(this).val();

            $('#advo_other').hide();

            switch (val) {
                case 'Other':
                    $('#advocate') // want to add css there......
                    $('#advo_other').show();
                    break; 
            }
        });
    });
</script> 

and the style is below:

<style type="text/css">
    .fade {
        color: #CCC;
        border-color:#CCC;
    }
</style>
### User: What is perplexity for language models? Formula welcome. ### Assistant: Perplexity measures how "surprised" a model is by a text: lower means the model predicts the next token better. Formally it's the exponential of the average cross-entropy: PPL = exp(−(1/N) · Σ log p(tᵢ | t₁...tᵢ₋₁)), where p is the probability the model assigned to the actual next token. Intuition: perplexity 20 means the model is on average "torn" between roughly 20 equally likely next tokens. A perfect model that knows the text by heart would score 1. The metric is handy for comparing quantizations of the same model: the perplexity increase relative to the full-precision version shows how much quality the compression ate — but comparing across different models with different tokenizers is meaningless. The first political philosopher to call himself an anarchist () was Pierre-Joseph Proudhon (1809–1865), marking the formal birth of anarchism in the mid-19th century. Since the 1890s and beginning in France, libertarianism has often been used as a synonym for anarchism and its use as a synonym is still common outside the United States. Some usages of libertarianism refer to individualistic free-market philosophy only, and free-market anarchism in particular is termed libertarian anarchism. While the term libertarian has been largely synonymous with anarchism, its meaning has more recently been diluted by wider adoption from ideologically disparate groups, including both the New Left and libertarian Marxists, who do not associate themselves with authoritarian socialists or a vanguard party, and extreme cultural liberals, who are primarily concerned with civil liberties. Additionally, some anarchists use libertarian socialist to avoid anarchism's negative connotations and emphasise its connections with socialism. Anarchism is broadly used to describe the anti-authoritarian wing of the socialist movement. Anarchism is contrasted to socialist forms which are state-oriented or from above. Scholars of anarchism generally highlight anarchism's socialist credentials and criticise attempts at creating dichotomies between the two. Some scholars describe anarchism as having many influences from liberalism, and being both liberal and socialist but more so. Many scholars reject anarcho-capitalism as a misunderstanding of anarchist principles. While opposition to the state is central to anarchist thought, defining anarchism is not an easy task for scholars, as there is a lot of discussion among scholars and anarchists on the matter, and various currents perceive anarchism slightly differently. Major definitional elements include the will for a non-coercive society, the rejection of the state apparatus, the belief that human nature allows humans to exist in or progress toward such a non-coercive society, and a suggestion on how to act to pursue the ideal of anarchy. History Pre-modern era Before the creation of towns and cities, established authority did not exist. It was after the institution of authority that anarchistic ideas were espoused as a reaction. The most notable precursors to anarchism in the ancient world were in China and Greece. In China, philosophical anarchism (the discussion on the legitimacy of the state) was delineated by Taoist philosophers Zhuang Zhou and Laozi. Alongside Stoicism, Taoism has been said to have had "significant anticipations" of anarchism. // Code generated by skv2. DO NOT EDIT. package v1 import ( "k8s.io/client-go/rest" "sigs.k8s.io/controller-runtime/pkg/client" ) // Provider for the apps/v1 Clientset from config func ClientsetFromConfigProvider(cfg *rest.Config) (Clientset, error) { return NewClientsetFromConfig(cfg) } // Provider for the apps/v1 Clientset from client func ClientsProvider(client client.Client) Clientset { return NewClientset(client) } // Provider for DeploymentClient from Clientset func DeploymentClientFromClientsetProvider(clients Clientset) DeploymentClient { return clients.Deployments() } // Provider for DeploymentClient from Client func DeploymentClientProvider(client client.Client) DeploymentClient { return NewDeploymentClient(client) } type DeploymentClientFactory func(client client.Client) DeploymentClient func DeploymentClientFactoryProvider() DeploymentClientFactory { return DeploymentClientProvider } type DeploymentClientFromConfigFactory func(cfg *rest.Config) (DeploymentClient, error) func DeploymentClientFromConfigFactoryProvider() DeploymentClientFromConfigFactory { return func(cfg *rest.Config) (DeploymentClient, error) { clients, err := NewClientsetFromConfig(cfg) if err != nil { return nil, err } return clients.Deployments(), nil } } // Provider for ReplicaSetClient from Clientset func ReplicaSetClientFromClientsetProvider(clients Clientset) ReplicaSetClient { return clients.ReplicaSets() } // Provider for ReplicaSetClient from Client func ReplicaSetClientProvider(client client.Client) ReplicaSetClient { return NewReplicaSetClient(client) } type ReplicaSetClientFactory func(client client.Client) ReplicaSetClient func ReplicaSetClientFactoryProvider() ReplicaSetClientFactory { return ReplicaSetClientProvider } type ReplicaSetClientFromConfigFactory func(cfg *rest.Config) (ReplicaSetClient, error) func ReplicaSetClientFromConfigFactoryProvider() ReplicaSetClientFromConfigFactory { return func(cfg *rest.Config) (ReplicaSetClient, error) { clients, err := NewClientsetFromConfig(cfg) if err != nil { return nil, err } return clients.ReplicaSets(), nil } } n=`expr $n + 1` echo_i "checking recursive lookup to notimp edns server succeeds ($n)" ret=0 resolution_succeeds ednsnotimp. || ret=1 if [ $ret != 0 ]; then echo_i "failed"; fi status=`expr $status + $ret` n=`expr $n + 1` echo_i "checking refused edns server setup ($n)" ret=0 $DIG $DIGOPTS +edns @10.53.0.10 ednsrefused soa > dig.out.1.test$n || ret=1 grep "status: REFUSED" dig.out.1.test$n > /dev/null || ret=1 grep "EDNS: version:" dig.out.1.test$n > /dev/null && ret=1 $DIG $DIGOPTS +noedns @10.53.0.10 ednsrefused soa > dig.out.2.test$n || ret=1 grep "status: NOERROR" dig.out.2.test$n > /dev/null || ret=1 grep "EDNS: version:" dig.out.2.test$n > /dev/null && ret=1 if [ $ret != 0 ]; then echo_i "failed"; fi status=`expr $status + $ret` n=`expr $n + 1` echo_i "checking recursive lookup to refused edns server fails ($n)" ret=0 resolution_fails ednsrefused. || ret=1 if [ $ret != 0 ]; then echo_i "failed"; fi status=`expr $status + $ret` n=`expr $n + 1` echo_i "checking drop edns server setup ($n)" ret=0 $DIG $DIGOPTS +edns @10.53.0.2 dropedns soa > dig.out.1.test$n && ret=1 grep "connection timed out; no servers could be reached" dig.out.1.test$n > /dev/null || ret=1 $DIG $DIGOPTS +noedns @10.53.0.2 dropedns soa > dig.out.2.test$n || ret=1 grep "status: NOERROR" dig.out.2.test$n > /dev/null || ret=1 grep "EDNS: version:" dig.out.2.test$n > /dev/null && ret=1 $DIG $DIGOPTS +noedns +tcp @10.53.0.2 dropedns soa > dig.out.3.test$n || ret=1 grep "status: NOERROR" dig.out.3.test$n > /dev/null || ret=1 grep "EDNS: version:" dig.out.3.test$n > /dev/null && ret=1 $DIG $DIGOPTS +edns +tcp @10.53.0.2 dropedns soa > dig.out.4.test$n && ret=1 grep "connection timed out; no servers could be reached" dig.out.4.test$n > /dev/null || ret=1 if [ $ret != 0 ]; then echo_i "failed"; fi status=`expr $status + $ret` n=`expr $n + 1` echo_i "checking recursive lookup to drop edns server succeeds ($n)" ret=0 resolution_succeeds dropedns. || ret=1 if [ $ret != 0 ]; then echo_i "failed"; fi status=`expr $status + $ret` n=`expr $n + 1` echo_i "checking drop edns + no tcp server setup ($n)" ret=0 $DIG $DIGOPTS +edns @10.53.0.3 dropedns-notcp soa > dig.out.1.test$n && ret=1 grep "connection timed out; no servers could be reached" dig.out.1.test$n > /dev/null || ret=1 $DIG $DIGOPTS +noedns +tcp @10.53.0.3 dropedns-notcp soa > dig.out.2.test$n && ret=1 grep "connection refused" dig.out.2.test$n > /dev/null || ret=1 $DIG $DIGOPTS +noedns @10.53.0.3 dropedns-notcp soa > dig.out.3.test$n || ret=1 grep "status: NOERROR" dig.out.3.test$n > /dev/null || ret=1 grep "EDNS: version:" dig.out.3.test$n > /dev/null && ret=1 if [ $ret != 0 ]; then echo_i "failed"; fi status=`expr $status + $ret` n=`expr $n + 1` echo_i "checking recursive lookup to drop edns + no tcp server succeeds ($n)" ret=0 resolution_succeeds dropedns-notcp. || ret=1 if [ $ret != 0 ]; then echo_i "failed"; fi status=`expr $status + $ret` Problems downloading artifact - error reading signed content

I was just installing Ubuntu and added Eclipse (Indigo) to it. When I tried to add pydev to it I kept on getting this kind of error about halfway through the install. Strangely, when opening Eclipse (Indigo) on my other system on Windows 7 ( I already have PyDev installed here before, so this is supposed to get updates only), I am getting the same error. See below:

Problems downloading artifact: osgi.bundle,org.python.pydev.django,3.0.0.201311051910. Error reading signed content:C:\Users\Dan\AppData\Local\Temp\signatureFile7380103325324291237.jar

Like, a lot of them.

Do you have any idea about this?

Thanks, dh

mysql create multiple tables

I'm working on a project in which i need to create two tables in one query.

I'm writing like this:

DROP TABLE Employee;

CREATE TABLE Employee(
Employee_Id CHAR(12)NOT NULL PRIMARY KEY,
First_name CHAR(30),
Last_name CHAR(30),
Address VARCHAR(50),
City CHAR,
State CHAR,
Salary INT,
Gender CHAR,
Age INT
);

DROP TABLE Job;

CREATE TABLE job(
Exempt_Non_Exempt_Status tinyint(1) NOT NULL PRIMARY KEY,
Job_title CHAR,
Job_description CHAR
); 

But this gives an error like "Unknown table 'job'" even if I didn't create it.

"""Dataset, producer, and config metadata.""" import logging import warnings import sqlalchemy as sa from .._globals import REGISTRY as registry from .. import _tools from .. import backend as _backend __all__ = ['Dataset', 'Producer', 'Config'] log = logging.getLogger(__name__) @registry.mapped class Dataset: """Git commit loaded into the database.""" __tablename__ = '__dataset__' id = sa.Column(sa.Integer, sa.CheckConstraint('id = 1'), primary_key=True) title = sa.Column(sa.Text, sa.CheckConstraint("title != ''"), nullable=False) git_commit = sa.Column(sa.String(40), sa.CheckConstraint('length(git_commit) = 40'), nullable=False, unique=True) git_describe = sa.Column(sa.Text, sa.CheckConstraint("git_describe != ''"), nullable=False, unique=True) clean = sa.Column(sa.Boolean(create_constraint=True), nullable=False) version = sa.Column(sa.Text, sa.CheckConstraint("version != ''")) exclude_raw = sa.Column(sa.Boolean(create_constraint=True), nullable=False) @classmethod def get_dataset(cls, *, bind, strict, fallback=None): table = cls.__tablename__ log.debug('read %r from %r', table, bind) try: result, = _backend.iterrows(sa.select(cls), mappings=True, bind=bind) except sa.exc.OperationalError as e: if 'no such table' in e.orig.args[0]: pass else: log.exception('error selecting %r', table) if strict: # pragma: no cover raise RuntimeError('failed to select %r from %r', table, bind) from e return fallback except ValueError as e: log.exception('error selecting %r', table) if 'not enough values to unpack' in e.args[0] and not strict: return fallback else: # pragma: no cover raise RuntimeError('failed to select %r from %r', table, bind) from e except Exception as e: # pragma: no cover log.exception('error selecting %r', table) raise RuntimeError('failed to select %r from %r', table, bind) from e else: return result # checks if a different username is set in ENV and create if its not existing yet if [ $SSH_USER != "not-set" ] && (! id -u "${SSH_USER}" >/dev/null 2>&1 ); then echo "DOCKWARE: creating additional SSH user...." # create a custom ssh user for our provided settings sudo adduser --disabled-password --uid 8888 --gecos "" --ingroup www-data $SSH_USER sudo usermod -a -G sudo $SSH_USER sudo usermod -m -d /var/www $SSH_USER | true sudo echo "${SSH_USER}:${SSH_PWD}" | sudo chpasswd sudo sed -i "s/${SSH_USER}:x:8888:33:/${SSH_USER}:x:33:33:/g" /etc/passwd # add sudo without password # write user to file cause we loos the var as we executing as root and get a new shell sudo echo "${SSH_USER}" >> /tmp/user.name sudo -u root sh -c 'echo "Defaults:$(cat /tmp/user.name) !requiretty" >> /etc/sudoers' sudo rm -rf /tmp/user.name # disable original ssh access sudo usermod -s /bin/false dockware # allow ssh in sshd_config sudo sed -i "s/AllowUsers dockware/AllowUsers ${SSH_USER}/g" /etc/ssh/sshd_config echo "-----------------------------------------------------------" fi # start the SSH service with the latest setup echo "DOCKWARE: restarting SSH service...." sudo service ssh restart echo "-----------------------------------------------------------" echo "DOCKWARE: starting MySQL...." # somehow its necessary to set permissions, because # sometimes they get lost :) # make sure that it is no longer present from the last run file="/var/run/mysqld/mysqld.sock.lock" if [ -f "$file" ] ; then sudo rm -f "$file" fi sudo chown -R mysql:mysql /var/lib/mysql /var/run/mysqld sudo service mysql start; Getting application version from within application

Is there a simple way of obtaining the application version information from the resource file at runtime?

Effectively what I'd like to do is be able to have a "Version X.Y.Z" displayed at runtime without having a separate variable somewhere that I'd have to keep in sync with my ProductVersion and FileVersion.

To clarify: yes this is a standard C++ Windows project. I am aware of the GetFileVersionInfo method but it seems silly to have to open the binary from within the version in memory just to query the version information - I'm sure I'm missing something obvious here :-)

jQuery Mobile click events on dynamic list items

I'm having trouble getting click events from list items. In this page:

http://bec-systems.com/list-click.html

The first the entries in the list fire click events. However, if I dynamically add 3 more events by pushing the "Refresh Update List" button, the next 3 list entries do not generate click events.

Appreciate any suggestions as to how I can make this work, or generally improve the code.

Thanks, Cliff

Code is also listed below:

<!DOCTYPE html> 
<html> 
    <head> 
    <title>Status</title> 
    <meta name="viewport" content="width=device-width, initial-scale=1"> 
  <link rel="stylesheet" href="http://code.jquery.com/mobile/1.1.1/jquery.mobile-1.1.1.min.css" />
    <script src="http://code.jquery.com/jquery-1.7.1.min.js"></script>
    <script src="http://code.jquery.com/mobile/1.1.1/jquery.mobile-1.1.1.min.js"></script>
  <script type="text/javascript">
$(document).ready(function() {
  $("#refreshUpdateButton").on("click", function(event, ui) {
    console.log("refreshUpdateButton")

    versions = ["0.3", "0.4", "0.5"]

    for (var i=0; i < versions.length; i += 1) {
      $("#updateVersionsList").append('<li><a id="updateVersionItem-' + (i+3) + '">' + versions[i] + '</a></li>');
      if ($("#updateVersionsList").hasClass('ui-listview')) {
        $("#updateVersionsList").listview("refresh");
      } else {
        $("#updateVersionsList").trigger('create');
      }
    }

  })

  $('[id^=updateVersionItem]').on("click", function(event, ui) {
    console.log("updateVersion, selected = " + $(this).attr('id'));
  })

});

  </script>
</head> 
<body> 

<!-- Software update page -->
<div data-role="page" id="software-update-page">
    <div data-role="header">
        <h1>Software Update</h1>
    </div><!-- /header -->
    <div data-role="content">   
    <h1>Select Software version:</h1>
    <ul data-role="listview" id="updateVersionsList">
      <li><a id="updateVersionItem-0">0.0</a></li>
      <li><a id="updateVersionItem-1">0.1</a></li>
      <li><a id="updateVersionItem-2">0.2</a></li>
    </ul>
    <br>
    <a data-role="button" class="ui-btn-left" id="refreshUpdateButton">Refresh Update list</a>
    </div><!-- /content -->
</div>

</body>
</html>
package main import "testing" func TestNewCollectorDirNotExist(t *testing.T) { _, err := NewCollector("dir-not-exist") if err == nil { t.Error("Expected to fail due to dir not exist") } } func TestNewCollectorDirExist(t *testing.T) { _, err := NewCollector("testdata") if err != nil { t.Error("Expected to create since dir exists") } } func TestCollectResults(t *testing.T) { c, err := NewCollector("testdata") if err != nil { t.Error("Expected to create since dir exists") } ts := c.CollectResults() if ts.TotalPassed != 5 { t.Error("Expect 5, got ", ts.TotalPassed) } if ts.TotalFailed != 1 { t.Error("Expect 1, got ", ts.TotalFailed) } if ts.TotalTime != 18.50 { t.Error("Expect 18.50, got ", ts.TotalTime) } if len(ts.Results) != 6 { t.Error("Expect results size to be 6, got ", len(ts.Results)) } if ts.Results[0].Name != "Test case 1" { t.Error("Expect 'Test case 1', got ", ts.Results[0].Name) } // one with a failure if ts.Results[1].Name != "Test case 2" { t.Error("Expect 'Test case 2', got ", ts.Results[1].Name) } if ts.Results[1].Failure.Value != "AssertionError 0 == 1" { t.Error("Expect 'AssertionError 0 == 1', got ", ts.Results[1].Failure.Value) } if ts.Results[5].Name != "Test case 6" { t.Error("Expect 'Test case 6', got ", ts.Results[5].Name) } } constexpr int N = 1024; void InitiationInterval(float const *a_mem, float const *b_mem, float *c_mem) { for (int i = 0; i < N; ++i) { const auto a = a_mem[i]; const auto b = b_mem[i]; // ------------------------- // Try changing the target initiation interval (II) and re-running HLS. // Notice what happens to the total number of cycles to completion, and to // the number of adders instantiated. #pragma HLS PIPELINE II=1 float c = (a + b) * (a - b); // ------------------------- c_mem[i] = c; } } /** * @file UnitActionRenderer.h * @brief Draws Unit Action Tiles * * Loads the images from the bin/img folder to use as assets * Performs checks on the selected units capabilities to draw action tiles * Used by the main Render() function in Battle Mode */ /* Copyright (c) 2015, Christopher Nitta All rights reserved. All source material (source code, images, sounds, etc.) have been provided to University of California, Davis students of course ECS 160 for educational purposes. It may not be distributed beyond those enrolled in the course without prior permission from the copyright holder. All sound files, sound fonts, midi files, and images that have been included that were extracted from original Warcraft II by Blizzard Entertainment were found freely available via internet sources and have been labeld as abandonware. They have been included in this distribution for educational purposes only and this copyright notice does not attempt to claim any ownership of this material. */ #ifndef UNITDACTIONRENDERER_H #define UNITDACTIONRENDERER_H #include "Bevel.h" #include "PlayerAsset.h" #include "GameModel.h" #include #include class CUnitActionRenderer{ protected: std::shared_ptr< CGraphicTileset > DIconTileset; std::shared_ptr< CBevel > DBevel; std::shared_ptr< CPlayerData > DPlayerData; std::vector< int > DCommandIndices; std::vector< EAssetCapabilityType > DDisplayedCommands; EPlayerColor DPlayerColor; int DFullIconWidth; int DFullIconHeight; int DDisabledIndex; public: CUnitActionRenderer(std::shared_ptr< CBevel > bevel, std::shared_ptr< CGraphicTileset > icons, EPlayerColor color, std::shared_ptr< CPlayerData > player); ~CUnitActionRenderer(); int MinimumWidth() const; int MinimumHeight() const; EAssetCapabilityType Selection(const CPosition &pos) const; void DrawUnitAction(std::shared_ptr< CGraphicSurface > surface, const std::list< std::weak_ptr< CPlayerAsset > > &selectionlist, EAssetCapabilityType currentaction); }; #endif ### User: How is a docker container different from a virtual machine, in two paragraphs? ### Assistant: A virtual machine emulates an entire computer: a full guest operating system with its own kernel runs inside it, and a hypervisor divides the physical hardware among such guests. That gives strong isolation but costs a lot: every VM carries gigabytes of OS and takes tens of seconds to boot. A container doesn't emulate a kernel — all containers share the host's kernel, and isolation comes from kernel mechanisms themselves: namespaces separate processes, network and filesystem views, cgroups cap resources. That's why a container weighs megabytes and starts in a fraction of a second, but isolation is weaker, and you can't run, say, a Windows container on a Linux host — the kernel is shared. How to create an alert the fade after a duration in Vuetify?

How to create an Alert in Vuetify that fade after specified number of seconds, similarly to the alerts in Bootstrap Vue. I tried this:

<template>
  <transition name="fade">
    <v-alert v-show="visible" v-bind="$attrs" v-on="$listeners">
      <slot></slot>
    </v-alert>
  </transition>
</template>

<script>
export default {
  inheritAttrs: true,
  data() {
    return {
      visible: true,
      timer: null
    };
  },
  props: {
    duration: {
      required: true,
      type: Number
    }
  },
  methods: {
    fade() {
      let value = parseInt(Math.max(this.duration, 0));
      if (value != 0)
        this.timer = setTimeout(() => (this.visible = false), 1000 * value);
    }
  },
  mounted() {
    this.fade();
  }
};
</script>

Usage in other components:

    <vt-alert
      v-if="hasMessage()"
      :type="message.type"
      :duration="message.duration"
    >{{message.body}}</vt-alert>

hasMessage is utility function which check if the message is set.

But this did not work. More details here,

class SimpleDescriptor(Descriptor, DescriptorBase): def __init__( self, id: str = None, text: str = None, ref: str = None, name: str = None, *args, **kwargs ): super().__init__(*args, **kwargs) self.contents["id"] = id self.contents["text"] = text self.contents["ref"] = ref self.contents["name"] = name class Idempotent(SimpleDescriptor): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.contents["type"] = "idempotent" class ReferencingDescriptor(SimpleDescriptor): def __init__(self, ref: str, *args, **kwargs): super().__init__(*args, **kwargs) self.contents["ref"] = ref class Safe(SimpleDescriptor): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.contents["type"] = "safe" class Semantic(SimpleDescriptor): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.contents["type"] = "semantic" class Unsafe(SimpleDescriptor): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.contents["type"] = "unsafe" func (h KBFSRootHash) String() string { return hex.EncodeToString(h) } func (h KBFSRootHash) Eq(h2 KBFSRootHash) bool { return hmac.Equal(h[:], h2[:]) } func (h HashMeta) String() string { return hex.EncodeToString(h) } func (h HashMeta) Eq(h2 HashMeta) bool { return hmac.Equal(h[:], h2[:]) } func (h *HashMeta) UnmarshalJSON(b []byte) error { hm, err := HashMetaFromString(Unquote(b)) if err != nil { return err } *h = hm return nil } func (h *KBFSRootHash) UnmarshalJSON(b []byte) error { rh, err := KBFSRootHashFromString(Unquote(b)) if err != nil { return err } *h = rh return nil } func SHA512FromString(s string) (ret SHA512, err error) { if s == "null" { return nil, nil } b, err := hex.DecodeString(s) if err != nil { return ret, err } if len(b) != 64 { return nil, fmt.Errorf("Wanted a 64-byte SHA512, but got %d bytes", len(b)) } return SHA512(b), nil } func (s SHA512) String() string { return hex.EncodeToString(s) } func (s SHA512) Eq(s2 SHA512) bool { return hmac.Equal(s[:], s2[:]) } func (s *SHA512) UnmarshalJSON(b []byte) error { tmp, err := SHA512FromString(Unquote(b)) if err != nil { return err } *s = tmp return nil } func (t *ResetType) UnmarshalJSON(b []byte) error { var err error s := strings.TrimSpace(string(b)) var ret ResetType switch s { case "\"reset\"", "1": ret = ResetType_RESET case "\"delete\"", "2": ret = ResetType_DELETE default: err = fmt.Errorf("Bad reset type: %s", s) } *t = ret return err } func (l *LeaseID) UnmarshalJSON(b []byte) error { decoded, err := hex.DecodeString(Unquote(b)) if err != nil { return err } *l = LeaseID(hex.EncodeToString(decoded)) return nil } func (h HashMeta) MarshalJSON() ([]byte, error) { return Quote(h.String()), nil } func KIDFromString(s string) KID { // there are no validations for KIDs (length, suffixes) return KID(s) } func (k KID) IsValid() bool { return len(k) > 0 } func (k KID) String() string { return string(k) } func (k KID) IsNil() bool { return len(k) == 0 } func (k KID) Exists() bool { return !k.IsNil() } func (k KID) Equal(v KID) bool { return k == v } func (k KID) NotEqual(v KID) bool { return !k.Equal(v) } func (k KID) SecureEqual(v KID) bool { return hmac.Equal(k.ToBytes(), v.ToBytes()) } func (k KID) Match(q string, exact bool) bool { if k.IsNil() { return false } if exact { return strings.ToLower(k.String()) == strings.ToLower(q) } if strings.HasPrefix(k.String(), strings.ToLower(q)) { return true } if strings.HasPrefix(k.ToShortIDString(), q) { return true } return false } func (k KID) ToBytes() []byte { b, err := hex.DecodeString(string(k)) if err != nil { return nil } return b } func (k KID) GetKeyType() byte { raw := k.ToBytes() if len(raw) < 2 { return 0 } return raw[1] } func (k KID) ToShortIDString() string { return encode(k.ToBytes()[0:12]) } Umm Qais or Qays () is a town in northern Jordan principally known for its proximity to the ruins of the ancient Gadara. It is the largest city in the Bani Kinanah Department and Irbid Governorate in the extreme northwest of the country, near Jordan's borders with Israel and Syria. Today, the site is divided into three main areas: the archaeological site (Gadara), the traditional village (Umm Qais), and the modern town of Umm Qais. Location Umm Qais is located 28 km north of Irbid and 120 km north of Amman. It expanded from the ruins of ancient Gadara, which are located on a ridge above sea level, overlooking the Sea of Tiberias, the Golan Heights, and the Yarmouk River gorge. Strategically central and located close to multiple water sources, Umm Qais has historically attracted a high level of interest. History Antiquity Gadara was a centre of Greek culture in the region during the Hellenistic and Roman periods. The oldest archaeological evidence at Umm Qais, extends back to the second half of the third century BC. and the site appears to have been founded as a military colony by Alexander the Great's Macedonian Greeks. However, the site's name "Gadara" is not Greek in origin, but rather a Greek version of a local Semitic name meaning "fortifications" or "the fortified city" suggesting the military colony was founded on a pre-existing fortified site. Located on the boundary between Seleucid and Ptolemaic territory, the city was strategically important and was repeatedly the focus of military conquests throughout the succession of Syrian Wars between 274 - 188 BCE. The city's military importance during this period was noted by the Greek historian Polybius' describing it in 218 BCE as a fortress and "the strongest of all places in the region". The Roman-Seleucid War (192 - 188BCE) weakened Seleucid control over the region devolving autonomy in Palestine and trans-Jordan to the Hasmonean, Iturean and Nabatean kingdoms whose rivalries continued to make Gadara a strategically important city and the focus of continued conflict. In 98 BCE the Hasmonean King Alexander Jannaeus subjected the city to a 10 month siege, wresting control of the city and the trade routes to the ports of the Eastern Mediterranean that passed through it from the Nabateans. The Nabatean response culminated in Nabatean King Obdas 1st' decisive victory over Jannaeus at the Battle of Gadara in 93 BCE. In 63 BCE, Roman general Pompey conquered the region, Gadara was rebuilt and became a member of the semi-autonomous Roman Decapolis. 33 years later Augustus attached it to the Jewish kingdom of his ally, Herod. After King Herod's death in 4 BCE, Gadara became part of the Roman province of Syria. //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /// @project Open Space Toolkit ▸ Physics /// @file bindings/python/src/OpenSpaceToolkitPhysicsPy/Coordinate/Spherical.cpp /// @author Lucas Brémond /// @license Apache License 2.0 //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// #include #include //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// inline void OpenSpaceToolkitPhysicsPy_Coordinate_Spherical ( ) { boost::python::object module(boost::python::handle<>(boost::python::borrowed(PyImport_AddModule("ostk.physics.coordinate.spherical")))) ; boost::python::scope().attr("spherical") = module ; boost::python::scope scope = module ; OpenSpaceToolkitPhysicsPy_Coordinate_Spherical_LLA() ; OpenSpaceToolkitPhysicsPy_Coordinate_Spherical_AER() ; } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// Gap after table in LaTeX

I notice that there is some gap after my table. See the following snapshot:

http://i39.tinypic.com/x3e4vd.jpg

My LaTeX code is:

\begin{table}[htb]  
\caption{Error rates VS training size in AdaBoosted stump, SVM and kNN. \label{tab:examplecount8000errerrplot}}  
\begin{center}  
\begin{tabular}{c c}  
\includegraphics[scale=0.4]{../boost.eps}   
&  
\includegraphics[scale=0.4]{../svm.eps}   \\    
\includegraphics[scale=0.4]{../knn.eps}   
& \\    
\end{tabular}  
\end{center}  
\end{table}     
%  
\subsection{Feature Numbers}

Is the gap normal or how can I reduce the gap to be normal?

### User: what's the right way to store api keys in a desktop app? we use tauri ### Assistant: For Tauri the hierarchy is: 1. Best — the OS secret store via `tauri-plugin-keyring` (macOS Keychain, Windows Credential Manager, Secret Service on Linux). The key is encrypted by the system and bound to the user. 2. Acceptable — an encrypted file in the app data directory, with the encryption key derived from machine-specific data. Weaker, but better than plaintext. 3. Never: hardcoded in sources, plaintext config in the project folder, webview localStorage. Separately: if the key is your own (e.g. your backend's key shared across installs), it must not ship in a desktop app at all — it will be extracted from the binary. Such keys live server-side only, and the app talks through your proxy. Weird behavior of the != XPath operator

I'm attempting to create an xsl:choose statement with multiple conditions to test. So far, I have this:

<xsl:choose>
    <xsl:when test="$AccountNumber != '12345' and $Balance != '0'">
       <do stuff here>
       ...

The problem is that the 'and' is being treated as an 'or'. If the account number is 12345 or the balance of an account is 0, the condition is treated as true and the code gets executed. I need the test to be that both conditions must be true... do I have the syntax wrong here?

Thanks in advance, ~Tim

The user specified as a definer does not exist

I get the following error after importing my database's backup into an already existing website:

The user specified as a definer ('someuser'@'%') does not exist

I am already logged into my database, and when I execute

SHOW PRIVILEGES;

I can see that I am allowed

"To give to other users those privileges you posses..."

Consequently, I execute

CREATE USER 'someuser'@'localhost' IDENTIFIED BY 'password';

but I get the following error:

#1227 - Access denied; you need (at least one of) the CREATE USER privilege(s) for this operation

I also tried the

GRANT ALL ON *.* TO 'someuser'@'%' IDENTIFIED BY 'password'; FLUSH PRIVILEGES;

alternative, but got the following response:

#1045 - Access denied for user 'anotheruser'@'%' (using password: YES)

Please someone help me out with this! I've read into another similar posts but those answers didn't work for me since I got the above specified responses.

Since 2004 a large medieval festival organised by the local community, the CHM, The Azincourt Alliance, and various other UK societies commemorating the battle, local history and medieval life, arts and crafts has been held in the village. Prior to this date the festival was held in October, but due to the inclement weather and local heavy clay soil (like the battle) making the festival difficult, it was moved to the last Sunday in July. International relations Azincourt is twinned with Middleham, United Kingdom. See also Communes of the Pas-de-Calais department The neighbourhood of Agincourt, Toronto, Canada, named for Azincourt, not Agincourt, Meurthe-et-Moselle References Communes of Pas-de-Calais Artois #[macro_export] macro_rules! impl_item_arg0 { ($input:expr, $name:expr, $arguments:expr, $item_type:ty) => { if $name == stringify!($item_type) { use nom::Err as NomErr; use crate::error::{ErrorKind, Expectation, ParserError}; return if $arguments.len() == 0 { Ok(($input, Box::new(<$item_type>::new()))) } else { Err(NomErr::Error(ParserError::Base { location: $input, kind: ErrorKind::Expected(Expectation::ArgumentCount(0, $arguments.len())), child: None, })) }; } }; } #[macro_export] macro_rules! impl_item_arg1 { ($input:expr, $name:expr, $arguments:expr, $item_type:ty) => { if $name == stringify!($item_type) { use nom::Err as NomErr; use crate::error::{ErrorKind, Expectation, ParserError}; return if $arguments.len() == 1 { Ok(( $input, Box::new(<$item_type>::new( $arguments[0] .clone() .try_into() .map_err(|err| Err::Error(err))?, )), )) } else { Err(NomErr::Error(ParserError::Base { location: $input, kind: ErrorKind::Expected(Expectation::ArgumentCount(1, $arguments.len())), child: None, })) }; } }; } #[macro_export] macro_rules! impl_item_arg2 { ($input:expr, $name:expr, $arguments:expr, $item_type:ty) => { if $name == stringify!($item_type) { use nom::Err as NomErr; use crate::error::{ErrorKind, Expectation, ParserError}; return if $arguments.len() == 2 { Ok(( $input, Box::new(<$item_type>::new( $arguments[0] .clone() .try_into() .map_err(|err| Err::Error(err))?, $arguments[1] .clone() .try_into() .map_err(|err| Err::Error(err))?, )), )) } else { Err(NomErr::Error(ParserError::Base { location: $input, kind: ErrorKind::Expected(Expectation::ArgumentCount(2, $arguments.len())), child: None, })) }; } }; } #[macro_export] macro_rules! impl_item_arg3 { ($input:expr, $name:expr, $arguments:expr, $item_type:ty) => { if $name == stringify!($item_type) { use nom::Err as NomErr; use crate::error::{ErrorKind, Expectation, ParserError}; ### User: Summarize in one sentence: why do MoE models need less compute per token than dense models of the same size? ### Assistant: Because a router activates only a few experts per token, each token passes through a small fraction of the total weights — so compute per token scales with the active parameters, not the full parameter count. void projected(); void projectedOntoNormalized(); void projectedOntoNormalizedNotNormalized(); void flipped(); void angle(); void angleNotNormalized(); void subclassTypes(); void subclass(); void strictWeakOrdering(); void debug(); }; typedef Math::Constants Constants; typedef Math::Rad Rad; typedef Vector<2, Float> Vector2; typedef Vector<2, Half> Vector2h; typedef Vector<3, Float> Vector3; typedef Vector<4, Float> Vector4; typedef Vector<4, Half> Vector4h; typedef Vector<4, Int> Vector4i; VectorTest::VectorTest() { addTests({&VectorTest::construct, &VectorTest::constructFromData, &VectorTest::constructPad, &VectorTest::constructPadDefaultHalf, &VectorTest::constructDefault, &VectorTest::constructNoInit, &VectorTest::constructOneValue, &VectorTest::constructOneComponent, &VectorTest::constructConversion, &VectorTest::constructCopy, &VectorTest::convert, &VectorTest::isZeroFloat, &VectorTest::isZeroInteger, &VectorTest::isNormalized, &VectorTest::data, &VectorTest::negative, &VectorTest::addSubtract, &VectorTest::multiplyDivide, &VectorTest::multiplyDivideIntegral, &VectorTest::multiplyDivideComponentWise, &VectorTest::multiplyDivideComponentWiseIntegral, &VectorTest::modulo, &VectorTest::bitwise, &VectorTest::compare, &VectorTest::compareComponentWise, &VectorTest::dot, &VectorTest::dotSelf, &VectorTest::length, &VectorTest::lengthInverted, &VectorTest::normalized, &VectorTest::resized, &VectorTest::sum, &VectorTest::product, &VectorTest::min, &VectorTest::max, &VectorTest::minmax, &VectorTest::nanIgnoring, &VectorTest::projected, &VectorTest::projectedOntoNormalized, &VectorTest::projectedOntoNormalizedNotNormalized, &VectorTest::flipped, &VectorTest::angle, &VectorTest::angleNotNormalized, &VectorTest::subclassTypes, &VectorTest::subclass, &VectorTest::strictWeakOrdering, &VectorTest::debug}); } void VectorTest::construct() { constexpr Vector4 a = {1.0f, 2.0f, -3.0f, 4.5f}; CORRADE_COMPARE(a, Vector4(1.0f, 2.0f, -3.0f, 4.5f)); CORRADE_VERIFY((std::is_nothrow_constructible::value)); } void VectorTest::constructFromData() { Float data[] = { 1.0f, 2.0f, 3.0f, 4.0f }; CORRADE_COMPARE(Vector4::from(data), Vector4(1.0f, 2.0f, 3.0f, 4.0f)); }