#include "Magnum/Math/Half.h"
#include "Magnum/Math/Vector.h"
#include "Magnum/Math/StrictWeakOrdering.h"
struct Vec3 {
float x, y, z;
};
namespace Magnum { namespace Math {
namespace Implementation {
template<> struct VectorConverter<3, Float, Vec3> {
constexpr static Vector<3, Float> from(const Vec3& other) {
return {other.x, other.y, other.z};
}
constexpr static Vec3 to(const Vector<3, Float>& other) {
return {other[0], other[1], other[2]};
}
};
}
namespace Test { namespace {
struct VectorTest: Corrade::TestSuite::Tester {
explicit VectorTest();
void construct();
void constructFromData();
void constructPad();
void constructPadDefaultHalf();
void constructDefault();
void constructNoInit();
void constructOneValue();
void constructOneComponent();
void constructConversion();
void constructCopy();
void convert();
void isZeroFloat();
void isZeroInteger();
void isNormalized();
void data();
void negative();
void addSubtract();
void multiplyDivide();
void multiplyDivideIntegral();
void multiplyDivideComponentWise();
void multiplyDivideComponentWiseIntegral();
void modulo();
void bitwise();
void compare();
void compareComponentWise();
void dot();
void dotSelf();
void length();
void lengthInverted();
void normalized();
void resized();
void sum();
void product();
void min();
void max();
void minmax();
void nanIgnoring();
rsync over SSH preserve ownership only for www-data owned files
I am using rsync to replicate a web folder structure from a local server to a remote server. Both servers are ubuntu linux. I use the following command, and it works well:
rsync -az /var/www/ user@10.1.1.1:/var/www/
The usernames for the local system and the remote system are different. From what I have read it may not be possible to preserve all file and folder owners and groups. That is OK, but I would like to preserve owners and groups just for the www-data user, which does exist on both servers.
Is this possible? If so, how would I go about doing that?
** EDIT **
There is some mention of rsync being able to preserve ownership and groups on remote file syncs here: http://lists.samba.org/archive/rsync/2005-August/013203.html
** EDIT 2 **
I ended up getting the desired affect thanks to many of the helpful comments and answers here. Assuming the IP of the source machine is 10.1.1.2 and the IP of the destination machine is 10.1.1.1. I can use this line from the destination machine:
sudo rsync -az user@10.1.1.2:/var/www/ /var/www/
This preserves the ownership and groups of the files that have a common user name, like www-data. Note that using rsync without sudo does not preserve these permissions.
Java: Convert String to TimeStamp
I have an issue while I try to convert a String to a TimeStamp. I have an array that has the date in the format of yyyy-MM-dd and I want to change it to the format of yyyy-MM-dd HH:mm:ss.SSS. So, I use this code:
final String OLD_FORMAT = "yyyy-MM-dd";
final String NEW_FORMAT = "yyyy-MM-dd HH:mm:ss.SSS";
String oldDateString = createdArray[k];
String newDateString;
final DateFormat formatter = new SimpleDateFormat(OLD_FORMAT);
final Date d = formatter.parse(oldDateString);
((SimpleDateFormat) formatter).applyPattern(NEW_FORMAT);
newDateString = formatter.format(d);
System.out.println(newDateString);
final Timestamp ts = Timestamp.valueOf(newDateString);
System.out.println(ts);
and I get the following result.
2009-10-20 00:00:00.000
2009-10-20 00:00:00.0
but when I try to simply do
final String text = "2011-10-02 18:48:05.123";
ts = Timestamp.valueOf(text);
System.out.println(ts);
I get the right result:
2011-10-02 18:48:05.123
Do you know what I might be doing wrong?
Thanks for the help.
How to download a file with WinHTTP in C/C++?
I know how to download an html/txt page. For example :
//Variables
DWORD dwSize = 0;
DWORD dwDownloaded = 0;
LPSTR pszOutBuffer;
vector <string> vFileContent;
BOOL bResults = FALSE;
HINTERNET hSession = NULL,
hConnect = NULL,
hRequest = NULL;
// Use WinHttpOpen to obtain a session handle.
hSession = WinHttpOpen( L"WinHTTP Example/1.0",
WINHTTP_ACCESS_TYPE_DEFAULT_PROXY,
WINHTTP_NO_PROXY_NAME,
WINHTTP_NO_PROXY_BYPASS, 0);
// Specify an HTTP server.
if (hSession)
hConnect = WinHttpConnect( hSession, L"nytimes.com",
INTERNET_DEFAULT_HTTP_PORT, 0);
// Create an HTTP request handle.
if (hConnect)
hRequest = WinHttpOpenRequest( hConnect, L"GET", L"/ref/multimedia/podcasts.html",
NULL, WINHTTP_NO_REFERER,
NULL,
NULL);
// Send a request.
if (hRequest)
bResults = WinHttpSendRequest( hRequest,
WINHTTP_NO_ADDITIONAL_HEADERS,
0, WINHTTP_NO_REQUEST_DATA, 0,
0, 0);
// End the request.
if (bResults)
bResults = WinHttpReceiveResponse( hRequest, NULL);
// Keep checking for data until there is nothing left.
if (bResults)
do
{
// Check for available data.
dwSize = 0;
if (!WinHttpQueryDataAvailable( hRequest, &dwSize))
printf( "Error %u in WinHttpQueryDataAvailable.\n",
GetLastError());
// Allocate space for the buffer.
pszOutBuffer = new char[dwSize+1];
if (!pszOutBuffer)
{
printf("Out of memory\n");
dwSize=0;
}
else
{
// Read the Data.
ZeroMemory(pszOutBuffer, dwSize+1);
if (!WinHttpReadData( hRequest, (LPVOID)pszOutBuffer,
dwSize, &dwDownloaded))
{
printf( "Error %u in WinHttpReadData.\n",
GetLastError());
}
else
{
printf("%s", pszOutBuffer);
// Data in vFileContent
vFileContent.push_back(pszOutBuffer);
}
// Free the memory allocated to the buffer.
delete [] pszOutBuffer;
}
} while (dwSize>0);
// Report any errors.
if (!bResults)
printf("Error %d has occurred.\n",GetLastError());
// Close any open handles.
if (hRequest) WinHttpCloseHandle(hRequest);
if (hConnect) WinHttpCloseHandle(hConnect);
if (hSession) WinHttpCloseHandle(hSession);
export const mockRulerRuleGroup = (partial: Partial = {}): RulerRuleGroupDTO => ({
name: 'group1',
rules: [mockRulerAlertingRule()],
...partial,
});
export const mockPromAlertingRule = (partial: Partial = {}): AlertingRule => {
return {
type: PromRuleType.Alerting,
alerts: [mockPromAlert()],
name: 'myalert',
query: 'foo > 1',
lastEvaluation: '2021-03-23T08:19:05.049595312Z',
evaluationTime: 0.000395601,
annotations: {
message: 'alert with severity "{{.warning}}}"',
},
labels: {
severity: 'warning',
},
state: PromAlertingRuleState.Firing,
health: 'OK',
...partial,
};
};
export const mockPromRecordingRule = (partial: Partial = {}): RecordingRule => {
return {
type: PromRuleType.Recording,
query: 'bar < 3',
labels: {
cluster: 'eu-central',
},
health: 'OK',
name: 'myrecordingrule',
lastEvaluation: '2021-03-23T08:19:05.049595312Z',
evaluationTime: 0.000395601,
...partial,
};
};
export const mockPromRuleGroup = (partial: Partial = {}): RuleGroup => {
return {
name: 'mygroup',
interval: 60,
rules: [mockPromAlertingRule()],
...partial,
};
};
export const mockPromRuleNamespace = (partial: Partial = {}): RuleNamespace => {
return {
dataSourceName: 'Prometheus-1',
name: 'default',
groups: [mockPromRuleGroup()],
...partial,
};
};
export const mockAlertmanagerAlert = (partial: Partial = {}): AlertmanagerAlert => {
return {
annotations: {
summary: 'US-Central region is on fire',
},
endsAt: '2021-06-22T21:49:28.562Z',
fingerprint: '88e013643c3df34ac3',
receivers: [{ name: 'pagerduty' }],
startsAt: '2021-06-21T17:25:28.562Z',
status: { inhibitedBy: [], silencedBy: [], state: AlertState.Active },
updatedAt: '2021-06-22T21:45:28.564Z',
generatorURL: 'https://play.grafana.com/explore',
labels: { severity: 'warning', region: 'US-Central' },
...partial,
};
};
export const mockAlertGroup = (partial: Partial = {}): AlertmanagerGroup => {
return {
labels: {
severity: 'warning',
region: 'US-Central',
},
receiver: {
name: 'pagerduty',
},
alerts: [
mockAlertmanagerAlert(),
mockAlertmanagerAlert({
status: { state: AlertState.Suppressed, silencedBy: ['123456abcdef'], inhibitedBy: [] },
labels: { severity: 'warning', region: 'US-Central', foo: 'bar', ...partial.labels },
}),
],
...partial,
};
};
Is there a way to list all gradle dependencies programmatically?
I know that doing:
gradle dependencies
Lists the full dependency tree. Now, I'm looking for a way to manipulate that dependencies tree programmatically so that I can print the same hierarchy but in JSON instead of the format the gradle cli uses right now in the console.
Which are the groovy classes I should use to achieve that?
EDITED
I would like to obtain (in JSON) some like this:
"dependencies" : [
{
"groupId" : "com.something",
"artifactId" : "somethingArtifact",
"version" : "1.0",
"dependencies" : [
"groupId" : "com.leaf",
"artifactId" : "standaloneArtifact",
"version" : "2.0",
]
},
{
"groupId" : "com.leaf",
"artifactId" : "anotherStandaloneArtifact",
"version" : "1.0",
"dependencies" : []
}
]
As you can see here with this I know which dependency depends on which other dependencies transitively.
import * as React from 'react';
import { Helmet } from 'react-helmet';
import { HeroBanner } from '../components/HomePage/HeroBanner';
import { Badges } from '../components/HomePage/Badges';
import { ValueProps } from '../components/HomePage/ValueProps';
import { Support } from '../components/HomePage/Support';
import { Installation } from '../components/HomePage/Installation';
import { Community } from '../components/HomePage/Community';
import { Companies } from '../components/HomePage/Companies';
import { Examples } from '../components/HomePage/Examples';
import { Extensions } from '../components/HomePage/Extensions';
import { Authors } from '../components/HomePage/Authors';
import { Testimonials } from '../components/HomePage/Testimonials';
import { GroupedSection } from '../components/HomePage/GroupedSection';
import { Footer } from '../components/HomePage/Footer';
import { colors } from '../utils/css';
export default function HomePage({ data }) {
const siteMetadata = data.site.siteMetadata;
return (
<>
{siteMetadata.title}
>
);
}
Microsoft Excel cannot access the file "...". There are several possible reasons Windows Server 2008 R2 with Microsoft Office 2010
I have a problem with starting the Excel Application under a particular user.
I try to schedule this script (C#) through an application X (not Windows Task Scheduler. And this application will always use a service account to run services on the server). If I run the C# script in command prompt under the same user, it runs. Under the application X, which uses the exact same user, to initiate the C# script, it fails to open the Excel application (not sufficient permission?).
This script calls:
app.Workbooks.Open(ExcelFileName,0,false,Type.missing....), yet it gives the following error:
Microsoft Excel cannot access the file "...". There are several possible reasons:
-The file name or path does not exist.
-The file is being used by another program.
-The workbook you are trying to save has the same name as a currently open workbook.
I tried all the methods that I found online to no avail.
Create directory “C:\Windows\SysWOW64\config\systemprofile\Desktop” (for 64 bit Windows) or “C:\Windows\System32\config\systemprofile\Desktop” (for 32 bit Windows). Then Set full control permissions on Desktop directory above (for example in Win7 & IIS 7 & DefaultAppPool set permissions for user “IIS AppPool\DefaultAppPool”)
Changed the DCOM config for the Microsoft Excel application to include this user for Local/Remote Launch and Access
Enabled all macros in Excel and set the Trust Center.
Add the user to have full control on all folders that contain the Excel file.
Under DCOM config, Microsoft Excel Application, if I modify the Identity tab to check on "This User" and enter the username/password to let Excel always run under that user. Then the application runs perfectly. However, other users can't run the excel application on their own with the following error: "Cannot use object linking and embedding". If I check "Use the launching user", then Excel can't be launched. No errors in the logs or events anywhere to check.
Yet, still the same error. I think it's permission but I am not sure where and what to do for this to work.
Now, normally, when I run this excel report, I can double-click on the file and it'd automatically run, save the new parameters into the current file and generate a new excel file (with date attached to the file name). That means there is a change (save) to the original file.
I appreciate all your help!
// Copyright (c) 2022 Nicolas Chevalier
//
// 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.
pub use libtorrent_sys::ffi::*;
export const query = graphql`
query HomePage {
site {
siteMetadata {
title
url
}
}
...ValuePropsImages
...CompaniesImages
...CodeExamples
...CodeInstallation
...Support
...AuthorsImages
...CommunityImages
homeYaml(id: { regex: "/home/home.yaml/" }) {
...HomePageHeroBanner
...HomePageValueProps
...HomePageCompanies
...HomePageExtensions
...HomePageCommunity
...HomePageTestimonials
...HomePageAuthors
}
}
`;
/*
---------------------------------------------------------------------------------
-------- FULL HOMEPAGE QUERY (use for debugging content api in graphiql) --------
---------------------------------------------------------------------------------
query HomePage {
site {
siteMetadata {
title
url
}
}
...ValuePropsImages
...CompaniesImages
...CodeExamples
...CodeInstallation
...AuthorsImages
...CommunityImages
homeYaml(id: {regex: "/home/home.yaml/"}) {
...HomePageHeroBanner
...HomePageValueProps
...HomePageCompanies
...HomePageSupport
...HomePageCommunity
...HomePageExtensions
...HomePageTestimonials
...HomePageAuthors
}
}
fragment HomePageValueProps on HomeYaml {
valueProps {
title
description
icon
}
}
fragment ValuePropsImages on RootQueryType {
valuePropsImages: allImageSharp(filter: {id: {regex: "/images/value_props/"}}) {
edges {
node {
resolutions(width: 120) {
originalName
}
}
}
}
}
fragment HomePageCompanies on HomeYaml {
companies {
title
}
}
fragment CompaniesImages on RootQueryType {
companiesImages: allImageSharp(filter: {id: {regex: "/images/companies/"}}) {
edges {
node {
resolutions(width: 140) {
originalName
}
}
}
}
}
fragment CodeExamples on RootQueryType {
codeExamples: allMarkdownRemark(filter: {id: {regex: "/home/examples/"}}, sort: {fields: [frontmatter___order], order: ASC}) {
edges {
node {
html
}
}
}
}
fragment CodeInstallation on RootQueryType {
codeInstallation: markdownRemark(id: {regex: "/home/installation/"}) {
html
}
}
fragment HomePageAuthors on HomeYaml {
authors {
title
authors {
name
githubHandle
twitterHandle
image
}
}
}
fragment AuthorsImages on RootQueryType {
authorsImages: allImageSharp(filter: {id: {regex: "/images/authors/"}}) {
edges {
node {
resolutions(width: 150) {
originalName
}
}
}
}
}
fragment CommunityImages on RootQueryType {
communityImages: allImageSharp(
filter: { id: { regex: "/images/community/" } }
) {
edges {
node {
resolutions(width: 120) {
originalName
}
}
}
}
}
fragment HomePageHeroBanner on HomeYaml {
heroBanner {
title
howToSay
tagLine
cta
}
}
case STATE_MULTILINE:
if (This->response[0] == '.' && !This->response[1])
{
This->valid_info = FALSE;
This->state = STATE_DONE;
return S_OK;
}
sscanf(This->response, "%lu", &uidl->dwPopId);
if ((p = strchr(This->response, ' ')))
{
while (*p == ' ') p++;
uidl->pszUidl = p;
This->valid_info = TRUE;
return S_OK;
}
default:
WARN("parse error\n");
This->state = STATE_DONE;
return S_FALSE;
}
}
static HRESULT parse_stat_response(POP3Transport *This, POP3STAT *stat)
{
char *p;
stat->cMessages = 0;
stat->cbMessages = 0;
switch (This->state)
{
case STATE_OK:
if ((p = strchr(This->ptr, ' ')))
{
while (*p == ' ') p++;
sscanf(p, "%lu %lu", &stat->cMessages, &stat->cbMessages);
This->valid_info = TRUE;
This->state = STATE_DONE;
return S_OK;
}
default:
WARN("parse error\n");
This->state = STATE_DONE;
return S_FALSE;
}
}
static HRESULT parse_list_response(POP3Transport *This, POP3LIST *list)
{
char *p;
list->dwPopId = 0;
list->cbSize = 0;
switch (This->state)
{
case STATE_OK:
if (This->type == POP3CMD_GET_POPID)
{
if ((p = strchr(This->ptr, ' ')))
{
while (*p == ' ') p++;
sscanf(p, "%lu %lu", &list->dwPopId, &list->cbSize);
This->valid_info = TRUE;
}
This->state = STATE_DONE;
return S_OK;
}
This->state = STATE_MULTILINE;
return S_OK;
case STATE_MULTILINE:
if (This->response[0] == '.' && !This->response[1])
{
This->valid_info = FALSE;
This->state = STATE_DONE;
return S_OK;
}
sscanf(This->response, "%lu", &list->dwPopId);
if ((p = strchr(This->response, ' ')))
{
while (*p == ' ') p++;
sscanf(p, "%lu", &list->cbSize);
This->valid_info = TRUE;
return S_OK;
}
default:
WARN("parse error\n");
This->state = STATE_DONE;
return S_FALSE;
}
}
static HRESULT parse_dele_response(POP3Transport *This, DWORD *dwPopId)
{
switch (This->state)
{
case STATE_OK:
*dwPopId = 0; /* FIXME */
This->state = STATE_DONE;
return S_OK;
default:
WARN("parse error\n");
This->state = STATE_DONE;
return S_FALSE;
}
}
static HRESULT parse_retr_response(POP3Transport *This, POP3RETR *retr)
{
switch (This->state)
{
case STATE_OK:
retr->fHeader = FALSE;
retr->fBody = FALSE;
retr->dwPopId = This->msgid;
retr->cbSoFar = 0;
retr->pszLines = This->response;
retr->cbLines = 0;
1988–2002
In 1987, Wai traveled to Paris, France, to conduct a nude photoshoot for Playboy. The photos were taken by Byron Newman. The photo book was published in 1989.
2003–2010: Return and TVB
In 2005, she quietly returned to the Hong Kong entertainment industry. In addition to film, she joined television network TVB and was nominated for a TVB Anniversary Award for Best Supporting Actress in 2009 for Rosy Business and in 2010 for A Fistful of Stances.
In 2009, Wai won the 46th Golden Horse Awards for Best Supporting Actress for her role as a possessive mother in At the End of Daybreak. The film has also won the 16th the Hong Kong Institute of Film Critics award for Best Actress, the 4th Asian Film Awards for Best Supporting Actress, the 29th Hong Kong film awards Best Actress, the 10th Chinese movie media awards "best actress", the 10th China Changchun film festival Best Actress in Vladivostok, Russia international film festival has won seven awards Best Actress.
2011–present
Wai made her first mainland TV appearance in the series The Glamorous Imperial Concubine. She took a pay cut to play Wu Zetian in her next mainland drama, Women of the Tang Dynasty. The role garnered her a Best Supporting Actress nomination at the 13th Huading Awards.
In 2012, Wai officially transferred to the king of the arts and is now a contract actress. In 2013, Wai signed a one-year drama contract with HKTV. Her first role with them was as the Black Rose on Incredible Mama. She won Best Supporting Actress for the Malaysian film The Wedding Diary (2011) at the 2013 Golden Wau Awards, a ceremony celebrating Chinese language films in Malaysia.
In 2014, Wai won the Best Supporting Actress award at the 33rd Hong Kong Film Awards for her film Rigor Mortis.
In 2017, she won the Best Actress Award at the 36th Hong Kong film awards for Happiness.
In March 2018, Wai won the Excellence In Asian Cinema Award at the 12th Asian Film Awards.
In October 2018, she was awarded the Bronze Bauhinia Star for her outstanding achievements in the performing arts industry by the Chief Executive Carrie Lam.
In 2018, Wai starred as the conservative wife of a closeted transgender woman in Tracey. The film earned Wai the Award for Best Supporting Actress at the 38th Hong Kong Film Awards and the Award for Best Supporting Actress at the 13th Asian Film Awards.
In 2019, Wai earned critical acclaim with her role as Chief Superintendent Man Hei-wah (Madam Man) in the TVB crime drama The Defected, for which she won the Best Actress award at the 2019 TVB Anniversary Awards.
In 2021, Wai and Hugo Ng Doi-Yung starred in the movie "Sunshine of my life" as a blind parent of a normal child, played by Karena Ng. In the same year, she starred in the TVB crime thriller Murder Diary, in which she portrayed Yeung Bik-sum, a mental hospital assistant with schizophrenia, and was once again highly praised for her acting skills.
Filmography
Film
1970s
1980s
1990s
2000s
2010s
import styled from "styled-components";
export const Card = styled.div`
display: grid;
grid-gap: 2rem;
margin-bottom: 4rem;
grid-template-columns: 1fr;
border-bottom: 1px solid rgb(0, 0, 0);
padding-bottom: 2rem;
@media (min-width: 992px) {
grid-template-columns: 1fr 1fr;
border-bottom: 0;
padding-bottom: 0;
}
`;
export const CardLeft = styled.div`
background: #151418;
border-radius: 5px;
padding: 5px;
justify-self: center;
img {
border-radius: 3px;
height: auto;
}
`;
export const CardRight = styled.div`
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
h4 {
font-size: 1.5rem;
font-weight: 400;
}
p {
font-weight: 400;
max-width: 400px;
margin-top: 10px;
margin-bottom: 1rem;
color: rgba(0, 0, 0, 0.815);
text-align: center;
@media (min-width: 992px) {
text-align: start;
}
}
@media (min-width: 992px) {
align-items: flex-start;
margin-top: 1rem;
}
`;
export const Stack = styled.div`
display: flex;
align-items: center;
margin-bottom: 5px;
.stackTitle {
font-weight: 500;
margin-right: 10px;
font-size: 17px;
}
.tags {
font-size: 15px;
font-weight: 400;
}
`;
export const BtnGroup = styled.div`
height: 70px;
display: flex;
align-items: center;
`;
ediaQueryTresholds.L}px)`]: {
".moving-featured &, .is-aside &": {
margin: "0 0 0 .5em"
}
}
}
});
class ListItem extends React.Component {
state = {
hidden: false
};
componentDidUpdate(prevProps, prevState) {
if (prevProps.categoryFilter !== this.props.categoryFilter) {
const category = this.props.post.node.frontmatter.category;
const categoryFilter = this.props.categoryFilter;
if (categoryFilter === "all posts") {
this.setState({ hidden: false });
} else if (category !== categoryFilter) {
this.setState({ hidden: true });
} else if (category === categoryFilter) {
this.setState({ hidden: false });
}
}
}
render() {
const { classes, post, linkOnClick } = this.props;
return (
{/*
*/}
{post.node.frontmatter.title}
{post.node.frontmatter.subTitle && {post.node.frontmatter.subTitle} }
);
}
}
ListItem.propTypes = {
classes: PropTypes.object.isRequired,
post: PropTypes.object.isRequired,
linkOnClick: PropTypes.func.isRequired,
categoryFilter: PropTypes.string.isRequired
};
export default injectSheet(styles)(ListItem);
// Generated from definition io.k8s.apiextensions-apiserver.pkg.apis.apiextensions.v1.CustomResourceDefinitionVersion
/// CustomResourceDefinitionVersion describes a version for CRD.
#[derive(Clone, Debug, Default, PartialEq)]
pub struct CustomResourceDefinitionVersion {
/// additionalPrinterColumns specifies additional columns returned in Table output. See https://kubernetes.io/docs/reference/using-api/api-concepts/#receiving-resources-as-tables for details. If no columns are specified, a single column displaying the age of the custom resource is used.
pub additional_printer_columns: Vec,
/// deprecated indicates this version of the custom resource API is deprecated. When set to true, API requests to this version receive a warning header in the server response. Defaults to false.
pub deprecated: Option,
/// deprecationWarning overrides the default warning returned to API clients. May only be set when `deprecated` is true. The default warning indicates this version is deprecated and recommends use of the newest served version of equal or greater stability, if one exists.
pub deprecation_warning: Option,
/// name is the version name, e.g. “v1”, “v2beta1”, etc. The custom resources are served under this version at `/apis/\/\/...` if `served` is true.
pub name: String,
/// schema describes the schema used for validation, pruning, and defaulting of this version of the custom resource.
pub schema: Option,
/// served is a flag enabling/disabling this version from being served via REST APIs
pub served: bool,
/// storage indicates this version should be used when persisting custom resources to storage. There must be exactly one version with storage=true.
pub storage: bool,
/// subresources specify what subresources this version of the defined custom resource have.
pub subresources: Option,
}
impl<'de> crate::serde::Deserialize<'de> for CustomResourceDefinitionVersion {
fn deserialize(deserializer: D) -> Result where D: crate::serde::Deserializer<'de> {
#[allow(non_camel_case_types)]
enum Field {
Key_additional_printer_columns,
Key_deprecated,
Key_deprecation_warning,
Key_name,
Key_schema,
Key_served,
Key_storage,
Key_subresources,
Other,
}
impl<'de> crate::serde::Deserialize<'de> for Field {
fn deserialize(deserializer: D) -> Result where D: crate::serde::Deserializer<'de> {
struct Visitor;
are updated health checks causing App Engine deployment to fail?
we updated our google app engine health checks from the legacy version to the new version using and now our deployments are failing. Nothing else on the project has changed. We tested the default settings and then extended checks just in case.
This is the error:
ERROR: (gcloud.app.deploy) Error Response: [4] Your deployment has failed to become healthy in the allotted time and therefore was rolled back. If you believe this was an error, try adjusting the 'app_start_timeout_sec' setting in the 'readiness_check' section.
This is our app.yaml:
liveness_check:
check_interval_sec: 120
timeout_sec: 40
failure_threshold: 5
success_threshold: 5
initial_delay_sec: 500
readiness_check:
check_interval_sec: 120
timeout_sec: 40
failure_threshold: 5
success_threshold: 5
app_start_timeout_sec: 1500
Unfortunately, no matter the configuration, both the readiness and liveness checks are throwing 404s.
What could be causing the problem? and how can we debug this?
Is it possible to rollback to the legacy health checks?
return if $arguments.len() == 3 {
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))?,
$arguments[2]
.clone()
.try_into()
.map_err(|err| Err::Error(err))?,
)),
))
} else {
Err(NomErr::Error(ParserError::Base {
location: $input,
kind: ErrorKind::Expected(Expectation::ArgumentCount(3, $arguments.len())),
child: None,
}))
};
}
};
}
#[macro_export]
macro_rules! impl_item_arg4 {
($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() == 4 {
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))?,
$arguments[2]
.clone()
.try_into()
.map_err(|err| Err::Error(err))?,
$arguments[3]
.clone()
.try_into()
.map_err(|err| Err::Error(err))?,
)),
))
} else {
Err(NomErr::Error(ParserError::Base {
location: $input,
kind: ErrorKind::Expected(Expectation::ArgumentCount(4, $arguments.len())),
child: None,
}))
};
}
};
}
#[macro_export]
macro_rules! impl_tests_for_item_arg0 {
($test_module_name:ident, $item:ident, $item_type:ty) => {
mod $test_module_name {
use super::*;
use cool_asserts::assert_matches;
use nom::Err as NomErr;
use crate::error::{ParserError, Expectation, ErrorKind};
# -*- coding: utf-8 -*-
# Copyright 2017 IBM RESEARCH. 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.
# =============================================================================
"""
two-qubit ZZ-rotation gate.
"""
from qiskit import CompositeGate
from qiskit import Gate
from qiskit import QuantumCircuit
from qiskit._instructionset import InstructionSet
from qiskit._quantumregister import QuantumRegister
from qiskit.extensions.standard import header # pylint: disable=unused-import
class RZZGate(Gate):
"""Two-qubit ZZ-rotation gate."""
def __init__(self, theta, ctl, tgt, circ=None):
"""Create new rzz gate."""
super().__init__("rzz", [theta], [ctl, tgt], circ)
def qasm(self):
"""Return OPENQASM string."""
ctl = self.arg[0]
tgt = self.arg[1]
theta = self.param[0]
return self._qasmif("rzz(%s) %s[%d],%s[%d];" % (theta,
ctl[0].name, ctl[1],
tgt[0].name, tgt[1]))
def inverse(self):
"""Invert this gate."""
self.param[0] = -self.param[0]
return self
def reapply(self, circ):
"""Reapply this gate to corresponding qubits in circ."""
self._modifiers(circ.rzz(self.param[0], self.arg[0], self.arg[1]))
def rzz(self, theta, ctl, tgt):
"""Apply RZZ to circuit."""
if isinstance(ctl, QuantumRegister) and \
isinstance(tgt, QuantumRegister) and len(ctl) == len(tgt):
instructions = InstructionSet()
for i in range(ctl.size):
instructions.add(self.rzz(theta, (ctl, i), (tgt, i)))
return instructions
self._check_qubit(ctl)
self._check_qubit(tgt)
self._check_dups([ctl, tgt])
return self._attach(RZZGate(theta, ctl, tgt, self))
# Add to QuantumCircuit and CompositeGate classes
QuantumCircuit.rzz = rzz
CompositeGate.rzz = rzz
qreal thisPitchValue = SpecialAccelerometerPedometer::calculatePitch(
SpecialAccelerometerPedometer::reading()->x(),
SpecialAccelerometerPedometer::reading()->y(),
SpecialAccelerometerPedometer::reading()->z()
);
//qDebug() << "Pitch value calculated: " << thisRollValue << "\n";
//if m_pitchValue is not equal to this pitch value
if(SpecialAccelerometerPedometer::pitch() != thisPitchValue)
{
SpecialAccelerometerPedometer::setPitchValue(thisPitchValue); //set m_pitchValue to thisPitchValue
emit pitchValueChanged(); //emit signal for roll value changed
}
//qDebug() << "Pitch value set: " << SpecialAccelerometerPedometer::pitch() << "\n";
}
//Yaw
//function to return m_yawValue
qreal SpecialAccelerometerPedometer::yaw() const{return m_yawValue;}
//function to set m_yawValue
void SpecialAccelerometerPedometer::setYawValue(qreal value){m_yawValue = value;}
//function to calculate yaw value and set it
qreal SpecialAccelerometerPedometer::calculateYaw(qreal x, qreal y, qreal z)
{
return -(qAtan(z / qSqrt(y * y + x * x)) * 57.2957795);
}
//function to set roll with calculate roll
void SpecialAccelerometerPedometer::setYawBasedOnYawCalculatedFromReadings()
{
qreal thisYawValue = SpecialAccelerometerPedometer::calculateYaw(
SpecialAccelerometerPedometer::reading()->x(),
SpecialAccelerometerPedometer::reading()->y(),
SpecialAccelerometerPedometer::reading()->z()
);
//qDebug() << "Yaw value calculated: " << thisYawValue << "\n";
//if m_pitchValue is not equal to this pitch value
if(SpecialAccelerometerPedometer::yaw() != thisYawValue)
{
SpecialAccelerometerPedometer::setYawValue(thisYawValue); //set m_yawValue to thisYawValue
emit yawValueChanged(); //emit signal for roll value changed
}
//qDebug() << "Yaw value set: " << SpecialAccelerometerPedometer::yaw() << "\n";
}
/*
****************************************
************ Step Counting *************
****************************************
*/
//function to return number of steps
qint8 SpecialAccelerometerPedometer::stepCount() const{return m_num_steps;}
//function to reset number of steps
void SpecialAccelerometerPedometer::resetNumberOfSteps(){m_num_steps = 0;}
//function to set m_num_steps
void SpecialAccelerometerPedometer::setNumberOfSteps(qint8 num){m_num_steps = num;}
//function to increment m_num_steps
void SpecialAccelerometerPedometer::incrementNumberOfSteps(){m_num_steps += 1;}
### User:
Explain what a race condition is with a short code example.
### Assistant:
A race condition is when the outcome depends on the unpredictable timing of concurrent operations. Classic example — two threads incrementing a shared counter:
```python
import threading
counter = 0
def work():
global counter
for _ in range(100_000):
counter += 1 # read, add, write — three steps, not atomic!
threads = [threading.Thread(target=work) for _ in range(2)]
for t in threads: t.start()
for t in threads: t.join()
print(counter) # expected 200000, prints less
```
`counter += 1` is a read-modify-write. Two threads can both read the same value, both add one, and both write back — losing an increment. Fixes: a `threading.Lock` around the increment, an atomic type, or restructuring so each worker owns its data and results merge at the end.
//! Function to create a time object from an initialized FILETIME struct.
/*! Function to create a time object from an initialized FILETIME struct.
* A FILETIME struct holds 100-nanosecond units (0.0000001). When
* built with microsecond resolution the FILETIME's sub second value
* will be truncated. Nanosecond resolution has no truncation.
*
* \note FILETIME is part of the Win32 API, so it is not portable to non-windows
* platforms.
*
* \note The function is templated on the FILETIME type, so that
* it can be used with both native FILETIME and the ad-hoc
* boost::date_time::winapi::file_time type.
*/
template< typename TimeT, typename FileTimeT >
inline
TimeT from_ftime(const FileTimeT& ft)
{
return boost::date_time::time_from_ftime(ft);
}
#endif // BOOST_HAS_FTIME
} } //namespace boost::posix_time
#endif
@Override
public void onInitialized() {
super.onInitialized();
setRadius(mRadius);
setCenter(mCenter);
setRefractiveIndex(mRefractiveIndex);
}
@Override
public void onOutputSizeChanged(int width, int height) {
mAspectRatio = (float) height / width;
setAspectRatio(mAspectRatio);
super.onOutputSizeChanged(width, height);
}
private void setAspectRatio(float aspectRatio) {
mAspectRatio = aspectRatio;
setFloat(mAspectRatioLocation, aspectRatio);
}
/**
* The index of refraction for the sphere, with a default of 0.71
*
* @param refractiveIndex default 0.71
*/
public void setRefractiveIndex(float refractiveIndex) {
mRefractiveIndex = refractiveIndex;
setFloat(mRefractiveIndexLocation, refractiveIndex);
}
/**
* The center about which to apply the distortion, with a default of (0.5, 0.5)
*
* @param center default (0.5, 0.5)
*/
public void setCenter(PointF center) {
mCenter = center;
setPoint(mCenterLocation, center);
}
/**
* The radius of the distortion, ranging from 0.0 to 1.0, with a default of 0.25
*
* @param radius from 0.0 to 1.0, default 0.25
*/
public void setRadius(float radius) {
mRadius = radius;
setFloat(mRadiusLocation, radius);
}
}
#if defined(ARDUINO_ARCH_ESP8266)
#include
#include
#include
#include
#include
#include
#elif defined(ARDUINO_ARCH_ESP32)
#include
#include
#include
#include
#endif
#include
#include "config.h"
// ********************** Config **********************
const char* GitHubhost PROGMEM = "api.github.com";
const char* HShost PROGMEM = "smogomierz.hs-silesia.pl";
const int httpsPort = 443;
// Last update: 21.03.2019
const char GitHubfingerprint[] PROGMEM = "5F F1 60 31 09 04 3E F2 90 D2 B0 8A 50 38 04 E8 37 9F BC 76"; // api.github.com
const char HSfingerprint[] PROGMEM = "10 ED 27 F6 39 5E 46 F0 90 8B 10 D2 6B 96 8A EF 43 7C FB 4F"; // https://smogomierz.hs-silesia.pl
// ******************** Config End ********************
#if defined(ARDUINO_ARCH_ESP32)
/**
* This is lets-encrypt-x3-cross-signed.pem
*/
const char* rootCACertificate PROGMEM = \
"-----BEGIN CERTIFICATE-----\n" \
"MIIEkjCCA3qgAwIBAgIQCgFBQgAAAVOFc2oLheynCDANBgkqhkiG9w0BAQsFADA/\n" \
"MSQwIgYDVQQKExtEaWdpdGFsIFNpZ25hdHVyZSBUcnVzdCBDby4xFzAVBgNVBAMT\n" \
"DkRTVCBSb290IENBIFgzMB4XDTE2MDMxNzE2NDA0NloXDTIxMDMxNzE2NDA0Nlow\n" \
"SjELMAkGA1UEBhMCVVMxFjAUBgNVBAoTDUxldCdzIEVuY3J5cHQxIzAhBgNVBAMT\n" \
"GkxldCdzIEVuY3J5cHQgQXV0aG9yaXR5IFgzMIIBIjANBgkqhkiG9w0BAQEFAAOC\n" \
"AQ8AMIIBCgKCAQEAnNMM8FrlLke3cl03g7NoYzDq1zUmGSXhvb418XCSL7e4S0EF\n" \
"q6meNQhY7LEqxGiHC6PjdeTm86dicbp5gWAf15Gan/PQeGdxyGkOlZHP/uaZ6WA8\n" \
"SMx+yk13EiSdRxta67nsHjcAHJyse6cF6s5K671B5TaYucv9bTyWaN8jKkKQDIZ0\n" \
"Z8h/pZq4UmEUEz9l6YKHy9v6Dlb2honzhT+Xhq+w3Brvaw2VFn3EK6BlspkENnWA\n" \
"a6xK8xuQSXgvopZPKiAlKQTGdMDQMc2PMTiVFrqoM7hD8bEfwzB/onkxEz0tNvjj\n" \
"/PIzark5McWvxI0NHWQWM6r6hCm21AvA2H3DkwIDAQABo4IBfTCCAXkwEgYDVR0T\n" \
"AQH/BAgwBgEB/wIBADAOBgNVHQ8BAf8EBAMCAYYwfwYIKwYBBQUHAQEEczBxMDIG\n" \
"CCsGAQUFBzABhiZodHRwOi8vaXNyZy50cnVzdGlkLm9jc3AuaWRlbnRydXN0LmNv\n" \
"bTA7BggrBgEFBQcwAoYvaHR0cDovL2FwcHMuaWRlbnRydXN0LmNvbS9yb290cy9k\n" \
"c3Ryb290Y2F4My5wN2MwHwYDVR0jBBgwFoAUxKexpHsscfrb4UuQdf/EFWCFiRAw\n" \
"VAYDVR0gBE0wSzAIBgZngQwBAgEwPwYLKwYBBAGC3xMBAQEwMDAuBggrBgEFBQcC\n" \
"ARYiaHR0cDovL2Nwcy5yb290LXgxLmxldHNlbmNyeXB0Lm9yZzA8BgNVHR8ENTAz\n" \
"MDGgL6AthitodHRwOi8vY3JsLmlkZW50cnVzdC5jb20vRFNUUk9PVENBWDNDUkwu\n" \
"Y3JsMB0GA1UdDgQWBBSoSmpjBH3duubRObemRWXv86jsoTANBgkqhkiG9w0BAQsF\n" \
"AAOCAQEA3TPXEfNjWDjdGBX7CVW+dla5cEilaUcne8IkCJLxWh9KEik3JHRRHGJo\n" \
"uM2VcGfl96S8TihRzZvoroed6ti6WqEBmtzw3Wodatg+VyOeph4EYpr/1wXKtx8/\n" \
"wApIvJSwtmVi4MFU5aMqrSDE6ea73Mj2tcMyo5jMd6jmeWUHK8so/joWUoHOUgwu\n" \
"X4Po1QYz+3dszkDqMp4fklxBwXRsW10KXzPMTZ+sOPAveyxindmjkW8lGy+QsRlG\n" \
"PfZ+G6Z6h7mjem0Y+iWlkYcV4PIWL1iwBi8saCbGS5jN2p8M+X+Q7UNKEkROb3N6\n" \
"KOqkqm57TH2H3eDJAkSnh6/DNFu0Qg==\n" \
"-----END CERTIFICATE-----\n";
#endif
// Set time via NTP, as required for x.509 validation
void setUpdateClock() {
configTime(0, 0, "pool.ntp.org", "time.nist.gov"); // UTC
bool isNotColonOrSlash(UChar c)
{
return c != ':' && c != '/';
}
bool isMediaTypeCharacter(UChar c)
{
return !isASCIISpace(c) && c != '/';
}
// CSP 1.0 Directives
static const char connectSrc[] = "connect-src";
static const char defaultSrc[] = "default-src";
static const char fontSrc[] = "font-src";
static const char frameSrc[] = "frame-src";
static const char imgSrc[] = "img-src";
static const char mediaSrc[] = "media-src";
static const char objectSrc[] = "object-src";
static const char reportURI[] = "report-uri";
static const char sandbox[] = "sandbox";
static const char scriptSrc[] = "script-src";
static const char styleSrc[] = "style-src";
// CSP 1.1 Directives
static const char baseURI[] = "base-uri";
static const char formAction[] = "form-action";
static const char pluginTypes[] = "plugin-types";
static const char scriptNonce[] = "script-nonce";
static const char reflectedXSS[] = "reflected-xss";
bool isDirectiveName(const String& name)
{
return (equalIgnoringCase(name, connectSrc)
|| equalIgnoringCase(name, defaultSrc)
|| equalIgnoringCase(name, fontSrc)
|| equalIgnoringCase(name, frameSrc)
|| equalIgnoringCase(name, imgSrc)
|| equalIgnoringCase(name, mediaSrc)
|| equalIgnoringCase(name, objectSrc)
|| equalIgnoringCase(name, reportURI)
|| equalIgnoringCase(name, sandbox)
|| equalIgnoringCase(name, scriptSrc)
|| equalIgnoringCase(name, styleSrc)
#if ENABLE(CSP_NEXT)
|| equalIgnoringCase(name, baseURI)
|| equalIgnoringCase(name, formAction)
|| equalIgnoringCase(name, pluginTypes)
|| equalIgnoringCase(name, scriptNonce)
|| equalIgnoringCase(name, reflectedXSS)
#endif
);
}
FeatureObserver::Feature getFeatureObserverType(ContentSecurityPolicy::HeaderType type)
{
switch (type) {
case ContentSecurityPolicy::PrefixedEnforce:
return FeatureObserver::PrefixedContentSecurityPolicy;
case ContentSecurityPolicy::Enforce:
return FeatureObserver::ContentSecurityPolicy;
case ContentSecurityPolicy::PrefixedReport:
return FeatureObserver::PrefixedContentSecurityPolicyReportOnly;
case ContentSecurityPolicy::Report:
return FeatureObserver::ContentSecurityPolicyReportOnly;
}
ASSERT_NOT_REACHED();
return FeatureObserver::NumberOfFeatures;
}
const ScriptCallFrame& getFirstNonNativeFrame(PassRefPtr stack)
{
int frameNumber = 0;
if (!stack->at(0).lineNumber() && stack->size() > 1 && stack->at(1).lineNumber())
frameNumber = 1;
return stack->at(frameNumber);
}
} // namespace
static bool skipExactly(const UChar*& position, const UChar* end, UChar delimiter)
{
if (position < end && *position == delimiter) {
++position;
return true;
}
return false;
}
package cn.co.willow.android.ultimate.gpuimage.core_render_filter.conversion_filter;
import android.graphics.PointF;
import android.opengl.GLES30;
import cn.co.willow.android.ultimate.gpuimage.core_render_filter.GPUImageFilter;
/**
* 变换滤镜:球形折射,图形倒立
* make a sphere based on image. sphere will show refelection of selecting region
*/
public class GPUImageSphereRefractionFilter extends GPUImageFilter {
public static final String SPHERE_FRAGMENT_SHADER = "" +
"varying highp vec2 textureCoordinate;\n" +
"\n" +
"uniform sampler2D inputImageTexture;\n" +
"\n" +
"uniform highp vec2 center;\n" +
"uniform highp float radius;\n" +
"uniform highp float aspectRatio;\n" +
"uniform highp float refractiveIndex;\n" +
"\n" +
"void main()\n" +
"{\n" +
"highp vec2 textureCoordinateToUse = vec2(textureCoordinate.x, (textureCoordinate.y * aspectRatio + 0.5 - 0.5 * aspectRatio));\n" +
"highp float distanceFromCenter = distance(center, textureCoordinateToUse);\n" +
"lowp float checkForPresenceWithinSphere = step(distanceFromCenter, radius);\n" +
"\n" +
"distanceFromCenter = distanceFromCenter / radius;\n" +
"\n" +
"highp float normalizedDepth = radius * sqrt(1.0 - distanceFromCenter * distanceFromCenter);\n" +
"highp vec3 sphereNormal = normalize(vec3(textureCoordinateToUse - center, normalizedDepth));\n" +
"\n" +
"highp vec3 refractedVector = refract(vec3(0.0, 0.0, -1.0), sphereNormal, refractiveIndex);\n" +
"\n" +
"gl_FragColor = texture2D(inputImageTexture, (refractedVector.xy + 1.0) * 0.5) * checkForPresenceWithinSphere; \n" +
"}\n";
private PointF mCenter;
private int mCenterLocation;
private float mRadius;
private int mRadiusLocation;
private float mAspectRatio;
private int mAspectRatioLocation;
private float mRefractiveIndex;
private int mRefractiveIndexLocation;
public GPUImageSphereRefractionFilter() {
this(new PointF(0.5f, 0.5f), 0.25f, 0.71f);
}
public GPUImageSphereRefractionFilter(PointF center, float radius, float refractiveIndex) {
super(NO_FILTER_VERTEX_SHADER, SPHERE_FRAGMENT_SHADER);
mCenter = center;
mRadius = radius;
mRefractiveIndex = refractiveIndex;
}
@Override
public void onInit() {
super.onInit();
mCenterLocation = GLES30.glGetUniformLocation(getProgram(), "center");
mRadiusLocation = GLES30.glGetUniformLocation(getProgram(), "radius");
mAspectRatioLocation = GLES30.glGetUniformLocation(getProgram(), "aspectRatio");
mRefractiveIndexLocation = GLES30.glGetUniformLocation(getProgram(), "refractiveIndex");
}
Brigadier General Marshall Magruder (12 October 1885 – 4 July 1956) was born in Washington, D.C. He served in both World War I and World War II. His son was noted aircraft designer Peyton M. Magruder. BG Magruder retired from the US Army in 1946. He was buried at Arlington National Cemetery in Section 30, Site 1092.
Career
11 June 1935- 28 August 1935 Commanding Officer 13th Field Artillery Regiment
1939–1940 Commanding Officer Armored Cavalry Regiment
1942–1943 Commanding Officer 14th Field Artillery Brigade
1943–1946 Member of War Department Manpower Board
References
Generals from USA
United States Army generals
1885 births
1956 deaths
Burials at Arlington National Cemetery
package antlr;
/* ANTLR Translator Generator
* Project led by Terence Parr at http://www.jGuru.com
* Software rights: http://www.antlr.org/RIGHTS.html
*
* $Id: //depot/code/org.antlr/release/antlr-2.7.1/antlr/TokenStreamBasicFilter.java#1 $
*/
import antlr.collections.impl.BitSet;
/** This object is a TokenStream that passes through all
* tokens except for those that you tell it to discard.
* There is no buffering of the tokens.
*/
public class TokenStreamBasicFilter implements TokenStream {
/** The set of token types to discard */
protected BitSet discardMask;
/** The input stream */
protected TokenStream input;
public TokenStreamBasicFilter(TokenStream input) {
this.input = input;
discardMask = new BitSet();
}
public void discard(int ttype) {
discardMask.add(ttype);
}
public void discard(BitSet mask) {
discardMask = mask;
}
public Token nextToken() throws TokenStreamException {
Token tok = input.nextToken();
while ( tok!=null && discardMask.member(tok.getType()) ) {
tok = input.nextToken();
}
return tok;
}
}
ate->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++;
state->X2++;
}
*rpr += (vsip_scalar_d)itemp/4294967296.0;
/* end t1 */
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++;
}
t2 = (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++;
state->X2++;
}
t2 += (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++;
state->X2++;
}
t2 += (vsip_scalar_d)itemp/4294967296.0;
/* end t2 */
*rpi = *rpr - t2;
*rpr = 3 - t2 - *rpr;
rpr += rst;
rpi += rst;
}
}
return;
}
The Ojai Valley News is an adjudicated newspaper published weekly in print and daily online. Locally owned and operated by Ojai Media LLC. The newspaper in Ojai, California, has been in continuous publication since 1891. First known as The Ojai, the Ojai Valley News serves a population of 30,000 people Ojai Valley residents and provides reporting to surrounding areas. Ojai Magazine is a quarterly free regional publication published by the Ojai Valley News since 1982 formerly as Ojai Valley Visitors Guide, and Ojai Valley Guide.
External links
Ojai Valley News website
Mass media in Ventura County, California
Weekly newspapers published in California
Ojai, California
Companies based in Ventura County, California
1891 establishments in California
Newspapers established in 1891
Kara Wai Ying-hung BBS (; born 3 February 1960) is a Hong Kong actress best known internationally for her roles in wuxia films produced by the Shaw Brothers Studio in the 1970s and 1980s.
Wai has since portrayed a wide range of roles on screen and on television with much success. She is the inaugural and a three-time recipient of Hong Kong Film Award for Best Actress. Her portrayal of a mother in the 2009 film At the End of Daybreak won her acting awards at the Hong Kong Film Awards, Hong Kong Film Critics Society Awards, Changchun Film Festival, Pacific Meridian, Asian Film Awards, and Golden Horse Awards. In following years, she went on to win multiple acting trophies throughout Asia Pacific from film roles, making her as one of the most celebrated Hong Kong actresses.
On 1 July 2018, she was awarded Bronze Bauhinia Star (BBS) by the Chief Executive of Hong Kong Special Administration Region, in recognition of her contribution to Hong Kong film industry and acting performances.
Personal life
Born in Hong Kong, she is the fourth oldest out of six children. She is of Manchu descent. Her elder brother was Austin Wai. In her early years, Wai's family resided in the poor shanty town of Rennie's Mill. She didn't keep studying since she finish primary school. In her interview on Be My Guest, Wai revealed her family lost their savings due to her father's business acquaintances. Left penniless, Wai's mother, herself, and her siblings were forced to peddle goods on the streets of Hong Kong. As a teen, she often sold gum and souvenirs in Wan Chai to sailors.
At the age of 14, she began taking dance lessons at the defunct Miramar nightclub and Northern style weaponry lessons from Donnie Yen's mother, Bow-sim Mark. Wai did Chinese dance for three years.
Director Chang Cheh is her godfather.
In 1999, she suffered from depression, and her career was in low ebb. She attempted suicide at the age of 40. In 2003, with the help of friends and relatives, Wai began to recover.
In March 2021, Wai expressed her support for cotton produced in Xinjiang after several companies announced they will stop purchasing cotton from the region due to concerns over forced labour from Uyghurs; a move echoed by most Chinese celebrities.
Career
1977–1987: Shaw Brothers Studio
During the film shoot for Dirty Ho (1979), the lead actress quit due to the strain of the martial arts stunts. Wai was then an extra in the film. Director Liu Chia-Liang had seen Wai's audition tape for The Brave Archer (1977) and decided to substitute her in as the lead actress. This was their first time working together. Impressed by her performance, Liu would go on to cast Wai in his other projects.
Wai reached her career apex with My Young Auntie (1982), for which she was earned the Award for Best Actress at the 1st Hong Kong Film Awards.
Wai's last film with Shaw Brothers was The Eight Diagram Pole Fighter (1984).
Accessing list data from a different site in Sharepoint Designer workflow
Does anyone know if it is possible to Lookup list data from a different site when creating a workflow with Sharepoint Designer 2007? The Define Workflow Lookup dialog only allows you to pick from lists in the current Sharepoint site you are creating the workflow in.
Ideally I'd like to be able to pick from a list in the parent site, or a site from a given URL (eg. http://myserver/mysite )
Wildcard targets in a Makefile
How can I compact the folllowing Makefile targets?
$(GRAPHDIR)/Complex.png: $(GRAPHDIR)/Complex.dot
dot $(GRAPHDIR)/Complex.dot -Tpng -o $(GRAPHDIR)/Complex.png
$(GRAPHDIR)/Simple.png: $(GRAPHDIR)/Simple.dot
dot $(GRAPHDIR)/Simple.dot -Tpng -o $(GRAPHDIR)/Simple.png
$(GRAPHDIR)/IFileReader.png: $(GRAPHDIR)/IFileReader.dot
dot $(GRAPHDIR)/IFileReader.dot -Tpng -o $(GRAPHDIR)/IFileReader.png
$(GRAPHDIR)/McCabe-linear.png: $(GRAPHDIR)/McCabe-linear.dot
dot $(GRAPHDIR)/McCabe-linear.dot -Tpng -o $(GRAPHDIR)/McCabe-linear.png
graphs: $(GRAPHDIR)/Complex.png $(GRAPHDIR)/Simple.png $(GRAPHDIR)/IFileReader.png $(GRAPHDIR)/McCabe-linear.png
--
Using GNU Make 3.81.
Curl authorization
I have spring security with https settings.
I'm seeing an unexpected behavior when trying to run curl GET on a URL in a secure way.
When curl first sends a request to the server, it does it with no authorization data (why? I specifically added it). Then, the server reply with Authentication Error (401).
The client then re-transmits the request, this time with authorization data, and the server replies properly with the required data.
Any idea why this happens?
Curl command:
curl -v --insecure --anyauth --user username:password -H "Accept: application/json" -H "Content-Type: application/json" -X GET localhost:8443/myresource
Request 1:
> GET /myresource HTTP/1.1
> User-Agent: curl/7.21.3 (x86_64-redhat-linux-gnu) libcurl/7.21.3 NSS/3.13.1.0 zlib/1.2.5 libidn/1.19 libssh2/1.2.7
> Host: localhost:8443
> Accept: application/json
> Content-Type: application/json
Response 1:
< HTTP/1.1 401 Unauthorized
< Server: Apache-Coyote/1.1
< Set-Cookie: JSESSIONID=B56A7F49E715795B5D1158DB192710AA; Path=/myresource ; Secure; HttpOnly
< WWW-Authenticate: Digest realm="Protected", qop="auth", nonce="MTM0Njg2MjYwMjY0ODozNDk5ZDkxNTYxNjMxMDJmNDA4MWQ1NTBmZjk5OGQ5Nw=="
< Content-Type: text/html;charset=utf-8
< Content-Length: 1119
< Date: Wed, 05 Sep 2012 16:29:52 GMT
Request 2:
> GET /myresource HTTP/1.1
> Authorization: Digest username="username", realm="Protected", nonce="MTM0Njg2MjYwMjY0ODozNDk5ZDkxNTYxNjMxMDJmNDA4MWQ1NTBmZjk5OGQ5Nw==", uri="/myresource", cnonce="ODczNjg0", nc=00000001, qop="auth", response="58faded9ae5f639ba0056fb86edca71f"
> User-Agent: curl/7.21.3 (x86_64-redhat-linux-gnu) libcurl/7.21.3 NSS/3.13.1.0 zlib/1.2.5 libidn/1.19 libssh2/1.2.7
> Host: localhost:8443
> Accept: application/json
> Content-Type: application/json
Response 2:
< HTTP/1.1 200 OK
< Server: Apache-Coyote/1.1
< Set-Cookie: JSESSIONID=37F375C5663C4A049D95D49C7C1CF0FD; Path=/myresource ; Secure; HttpOnly
< Content-Type: application/json
< Transfer-Encoding: chunked
< Date: Wed, 05 Sep 2012 16:29:52 GMT
import { Component } from '@angular/core';
import { ICellRenderer } from "@ag-grid-community/angular";
@Component({
selector: 'app-loading-cell-renderer',
template: `
+
-
{{value}}
`
})
export class CallsCellRenderer implements ICellRenderer {
private params: any;
private value: number;
agInit(params: any): void {
this.params = params;
this.value = params.value;
}
onAdd(): void {
var oldData = this.params.node.data;
var oldCallRecords = oldData.callRecords;
var newCallRecords = oldCallRecords.slice(0); // make a copy
newCallRecords.push({
name: ["Bob","Paul","David","John"][Math.floor(Math.random()*4)],
callId: Math.floor(Math.random()*1000),
duration: Math.floor(Math.random()*100) + 1,
switchCode: "SW5",
direction: "Out",
number: "(02) " + Math.floor(Math.random()*1000000)
}); // add one item
var minutes = 0;
newCallRecords.forEach( (r: any) => minutes += r.duration );
var newData = {
name: oldData.name,
account: oldData.account,
calls: newCallRecords.length,
minutes: minutes,
callRecords: newCallRecords
};
this.params.api.applyTransaction({update: [newData]});
this.params.node.setExpanded(true);
}
onRemove(): void {
var oldData = this.params.node.data;
var oldCallRecords = oldData.callRecords;
if (oldCallRecords.length==0) { return; }
var newCallRecords = oldCallRecords.slice(0); // make a copy
newCallRecords.pop(); // remove one item
var minutes = 0;
newCallRecords.forEach( (r:any) => minutes += r.duration );
var newData = {
name: oldData.name,
account: oldData.account,
calls: newCallRecords.length,
minutes: minutes,
callRecords: newCallRecords
};
this.params.api.applyTransaction({update: [newData]});
}
}
// Copyright 2018 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package text
import (
"bytes"
"fmt"
"math"
"strconv"
"strings"
"github.com/schattian/protobuf/internal/flags"
)
// Kind represents a token kind expressible in the textproto format.
type Kind uint8
// Kind values.
const (
Invalid Kind = iota
EOF
Name // Name indicates the field name.
Scalar // Scalar are scalar values, e.g. "string", 47, ENUM_LITERAL, true.
MessageOpen
MessageClose
ListOpen
ListClose
// comma and semi-colon are only for parsing in between values and should not be exposed.
comma
semicolon
// bof indicates beginning of file, which is the default token
// kind at the beginning of parsing.
bof = Invalid
)
func (t Kind) String() string {
switch t {
case Invalid:
return ""
case EOF:
return "eof"
case Scalar:
return "scalar"
case Name:
return "name"
case MessageOpen:
return "{"
case MessageClose:
return "}"
case ListOpen:
return "["
case ListClose:
return "]"
case comma:
return ","
case semicolon:
return ";"
default:
return fmt.Sprintf("", uint8(t))
}
}
// NameKind represents different types of field names.
type NameKind uint8
// NameKind values.
const (
IdentName NameKind = iota + 1
TypeName
FieldNumber
)
func (t NameKind) String() string {
switch t {
case IdentName:
return "IdentName"
case TypeName:
return "TypeName"
case FieldNumber:
return "FieldNumber"
default:
return fmt.Sprintf("", uint8(t))
}
}
// Bit mask in Token.attrs to indicate if a Name token is followed by the
// separator char ':'. The field name separator char is optional for message
// field or repeated message field, but required for all other types. Decoder
// simply indicates whether a Name token is followed by separator or not. It is
// up to the prototext package to validate.
const hasSeparator = 1 << 7
// Scalar value types.
const (
numberValue = iota + 1
stringValue
literalValue
)
// Bit mask in Token.numAttrs to indicate that the number is a negative.
const isNegative = 1 << 7
import React, { useState } from 'react'
import useForm from '../Functions/UseForm'
import FormRenderer from './FormRenderer';
import {
Col,
FormGroup,
Input,
Label,
Row,
Modal,
ModalHeader,
ModalBody,
ModalFooter,
Alert
} from 'reactstrap';
import { ToastContainer, toast } from 'react-toastify'
import 'react-toastify/dist/ReactToastify.css'
import MatButton from '@material-ui/core/Button'
import * as actions from "../../actions/patients";
import { connect } from 'react-redux'
const FormRendererModal = (props ) => {
const [errorMsg, setErrorMsg] = useState('')
const [showErrorMsg, setShowErrorMsg] = useState(false)
const [loading, setLoading] = useState(false)
const onDismiss = () => setShowErrorMsg(false)
const toggle = () => {
return props.setShowModal(!props.showModal)
}
return (
{props.title || ''}
{errorMsg}
);
}
const mapStateToProps = state => {
return {
patient: state.patients.patient
}
}
const mapActionToProps = {
}
export default connect(mapStateToProps, mapActionToProps)(FormRendererModal)
Uten sko (2011)
Livet er for kjipt (2011)
Er så lei (2012), with Johnny Gellein
…og det var langt på natt (2012)
En natt til (2012)
Bare vent (2012)
Oh My Mind (Toby & Helfner Metal Remix) (2012)
Frøken Möet (Trekant) (2012)
Russ 2013 (du er deilig, du er spretten) (2013)
Kaptein Morgan (2013), with Jesper Borgen
Kings of Asia (2013), with Kings of Asia
Metal Sessions (2013)
Haldens nummer 9 (Trollmannen fra Os) (2013), with Bingobanden
Se så glad nissen er (2013)
Brun og blid (TIX Remix) (2014), with Katastrofe & M.M.B
Ballongmannen (2014), with Ballongmannen and Morgan Sulele
Brun og blid (Disco Jumperz Remix) (2014)
Et drikkehjem (2014), with Martin Tungevaag
Russ 2014 (du er født i '95) (2014)
Min skyld (2014), with Ole I'Dole
18 Wiener (2014), with Katastrofe
En godt stekt pizza (2015), with Katastrofe
20 kilo ekstra (2015), with Torgeir and Kjendisene
Skilles Johanne (2015)
Lærerinna (2015), with Innertier
Alle gutta (2015)
Hjem til deg (2015)
En sinnsykt godt stekt pizza (2016)
Her er rompa mi (2016)
Frågan (2016, under the name Lasse Stianz)
En siste gang (2017)
KJØRR (2017), with Klish
Muggene er megasvære (elsker øl) (2017), with DJ Anton
Om 100 år er allting glemt (2017), with Lothepus
Kyss meg (2018)
Participating in
Lars Corleone ft. Howard: Uten sko (2014)
Sony Music Entertainment: Kule Kidz – Stjernemix 1 (2014)
Morgan Sulele: Morgans kleineste (2015)
ESS Engros: Livets glade gutter 2 – 19 norske festfavoritter (2015)
Sony Music Entertainment: Julebord 2015 (2015)
Torgeir & Kjendisene: En runde til (2016)
Elov & Beny: Kör (2017)
Sony Music Entertainment: Raggarbilshits Vol. 3: Raggaerrock & Rockabilly (2018)
Bibliography
How to become a norsk superkjendis (English: How to become a Norwegian superstar) (2016)
References
External links
Norwegian actors
People from Fredrikstad
Norwegian songwriters
1982 births
Living people
Heartland Championship Team
2015 Steelform Wanganui Heartland extended squad
Forwards: Brett Turner (Pirates); Bryn Hudson (Ngamatapouri); Cole Baldwin (Border); Daniel Fitzgerald (Marist); Fraser Hammond (Ruapehu); Kamipeli Latu (Border); Kieran Hussey (Border); Lasa Ulukuta (Pirates); Malakai Volau (Utiku OB); Peter Rowe (Ruapehu)(Captain); Renato Tikoilosomone (Border); Roman Tutauha (Ruapehu); Sam Madams (Border); Tololi Moala (Pirates); Viki Tofa (Marist). * John Smyth Brought in as injury cover.
Backs: Areta Lama (Kaierau); Ace Malo (Kaierau); Denning Tyrell (Pirates); Jaye Flaws (Taihape); Kane Tamou (Ratana); Lindsay Horrocks (Border); Michael Nabuliwaqe (Utiku OB); Poasa Waqanibau (Border); Samu Kubunavanua (Utiku OB); Simon Dibben (Marist); Stephen Pereofeta (Wanganui Collegiate); Troy Brown (Ruapehu); William Short (Ruapehu); Zyon Hekenui (Ruapehu); Trinity Spooner-Neera (Hawkes Bay)
Ranfurly Shield
Matches
Wanganui v Taranaki challenge of 1964
A 15-all draw against the powerful Taranaki side of 1964 remains the closest the men from Wanganui have ever come to winning the Ranfurly Shield.
Into the last minutes of the match Wanganui held a 12–11 lead and even if on paper and in the match itself they had seemed the inferior team it seemed as if they would hang on. Their hero was wing Colin Pierce who had kicked all of Wanganui's points from penalties to put them ahead even though Taranaki had gained tries to John McCullough and Ross Brown.
Wanganui might well have won as the match approached the final minute but for excitement of their supporters who thinking they were part of a historic moment as Wanganui had never won the Ranfurly Shield crowded the touchline.
A desperate Brown had dropped for goal trying to gain the winning points. When it had missed Pierce had dashed to the 22 and taken a quick drop out. In the event his hurried kick had landed among the Wanganui spectators and they gave referee John Pring and touch judge George Brightwell a dilemma for they were both unsighted by the sideline mayhem were not sure whether the ball had bounced or gone out on a full.
Pring ruled that it had been on the full and so that last scrum of the match in what was the last set-piece took place on the Wanganui 22 and it was from there that Taranaki worked the move from which replacement wing Kerry Hurley grubber kicked ahead and won the chase as the ball bounced just a feet from touch over the Wanganui goal-line. And that was it: Taranaki had won 14–12.
Wanganui in Super Rugby
Wanganui, along with Wellington, Wairarapa Bush, East Coast, Poverty Bay, Hawke's Bay, Manawatu and Horowhenua-Kapiti make up the Hurricanes region.
All Blacks
There have been 17 players selected for the All Blacks while playing club rugby in Whanganui:
return self.HEAD() && !self.inRebase() && !self.inMerge();
});
this.canStashAll = ko.computed(function() {
return !self.amend();
});
this.showNux = ko.computed(function() {
return self.files().length == 0 && !self.amend() && !self.inRebase() && !self.emptyCommit();
});
this.commitValidationError = ko.computed(function() {
if (!self.emptyCommit() && !self.amend() && !self.files().some(function(file) { return file.editState() === 'staged' || file.editState() === 'patched'; }))
return "No files to commit";
if (self.files().some(function(file) { return file.conflict(); }))
return "Files in conflict";
if (!self.commitMessageTitle() && !self.inRebase()) return "Provide a title";
if (self.textDiffType.value() === 'sidebysidediff') {
var patchFiles = self.files().filter(function(file) { return file.editState() === 'patched'; });
if (patchFiles.length > 0) return "Cannot patch with side by side view."
}
return "";
});
this.toggleSelectAllGlyphClass = ko.computed(function() {
if (self.allStageFlag()) return 'glyphicon-unchecked';
else return 'glyphicon-check';
});
rspec failing error: expected false to respond to `false?`
I am running this portion of a test:
describe Dictionary do
before do
@d = Dictionary.new
end
it 'can check whether a given keyword exists' do
@d.include?('fish').should be_false
end
With this code:
class Dictionary
def initialize
@hash = {}
end
def add(new_entry)
new_entry.class == String ? @hash[new_entry] = nil : new_entry.each { |noun, definition| @hash[noun] = definition}
end
def entries
@hash
end
def keywords
@hash.keys
end
def include?(word)
if @hash.has_key?(word)
true
else
false
end
end
end
I don't know what I'm doing wrong, but my tests keep failing and saying this:
> 1) Dictionary can check whether a given keyword exists
> Failure/Error: @d.include?('fish').should be_false
> expected false to respond to `false?`
I am confused at the error since it seems to be giving the correct answer. I would really appreciate if someone could take a few minutes to tell me what's wrong with my code.
Thank you tons.
Context path for web application on Glassfish 3.1.2.2
I'm trying to find a way to explicitly specify the context path of a web application being deployed to Glassfish 3.1.2.2 but I've had no luck so far. Can anyone provide guidance on this? The background to this is below:
I have a web application that consists of two separate Netbeans (7.0) projects. The first is a web service and is called FooWS. The second is a user facing web application which uses the FooWS webservice. It's called FooApp.
I've recently upgraded glassfish to 3.1.2.2 in the hope of resolving some other issue and now when I deploy the FooWS app, it deploys successfully but with the context path /web rather than /FooWS. This is not something I would particularly care about except that when I try to deploy FooApp, glassfish also tries to deploy that to /web leading to the following error:
SEVERE: Exception while loading the app : java.lang.Exception: WEB0113: Virtual server [server] already has a web module [FooWS] loaded at [/web]; therefore web module [FooApp] cannot be loaded at this context path on this virtual server.
The web.xml for FooApp looks as follows:
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.0" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">
<context-param>
<param-name>defaultWebRootId</param-name>
<param-value>2631</param-value>
</context-param>
<listener>
<listener-class>com.foo.service.AppInitialiser</listener-class>
</listener>
<session-config>
<session-timeout>
30
</session-timeout>
</session-config>
</web-app>
The configuration for FooWS is similar. Neither contains any mention of the application context so my expectation is that it should use /FooWS rather than default to /web.
The obvious solution would seem to be to override the context path in the web.xml but I can't find any way of doing this. Any suggestions?
Just some follow up, I accidentally changed the context path to /FooW. This time it deployed as expected to /FooW. Changing it back if /FooWS causes the old behaviour to return, that is, it deploys again to /web. It seems like I have a workaround for the moment.
For the benefit of anyone following this, I got the same behaviour with 3.1.2. I have now returned to 3.1 (b43) and it behaves as expected.
echo "complete -C '/usr/local/bin/aws_completer' aws" >> /home/ec2-user/.bashrc
#mkdir /home/ec2-user/CA
mkdir /home/ec2-user/.aws
echo '[default]' > /home/ec2-user/.aws/config
echo 'output = json' >> /home/ec2-user/.aws/config
echo "region = $REGION" >> /home/ec2-user/.aws/config
chmod 400 /home/ec2-user/.aws/config
chown -R ec2-user:ec2-user /home/ec2-user/.aws
IOT_ENDPOINT_OLD=$(aws iot describe-endpoint --region $REGION | jq -r '.endpointAddress')
IOT_ENDPOINT=$(aws iot describe-endpoint --region $REGION --endpoint-type iot:Data-ATS | jq -r '.endpointAddress')
echo "export IOT_ENDPOINT_OLD=$IOT_ENDPOINT_OLD" >> /home/ec2-user/.bashrc
echo "export IOT_ENDPOINT=$IOT_ENDPOINT" >> /home/ec2-user/.bashrc
echo 'export PATH=$PATH:/usr/local/bin' >> /home/ec2-user/.bashrc
cat /home/ec2-user/banner.txt >> /home/ec2-user/.bashrc
rm -f /home/ec2-user/banner.txt
test ! -e /home/ec2-user/.ssh && mkdir -m 700 /home/ec2-user/.ssh
echo '=== Prepare for Greengrass ==='
echo "$(date) === Get repository" >> /tmp/bootstrap.log
if ! getent passwd ggc_user; then
echo "adding ggc_user"
useradd -r ggc_user
fi
echo "-> ggc_group"
if ! getent group ggc_group; then
echo "adding ggc_group"
groupadd -r ggc_group
fi
echo "-> hardlink and symlink protection"
if [ -e /etc/sysctl.d/00-defaults.conf ]; then
if ! grep '^fs.protected_hardlinks\s*=\s*1' /etc/sysctl.d/00-defaults.conf; then
echo 'fs.protected_hardlinks = 1' >> /etc/sysctl.d/00-defaults.conf
fi
if ! grep '^fs.protected_symlinks\s*=\s*1' /etc/sysctl.d/00-defaults.conf; then
echo 'fs.protected_symlinks = 1' >> /etc/sysctl.d/00-defaults.conf
fi
else
echo '# AWS Greengrass' >> /etc/sysctl.d/00-defaults.conf
echo 'fs.protected_hardlinks = 1' >> /etc/sysctl.d/00-defaults.conf
echo 'fs.protected_symlinks = 1' >> /etc/sysctl.d/00-defaults.conf
fi
sysctl -p
sysctl -p /etc/sysctl.d/00-defaults.conf
echo '# AWS Greengrass' >> /etc/fstab
echo 'cgroup /sys/fs/cgroup cgroup defaults 0 0' >> /etc/fstab
mount -a
echo '=== Install Greengrass ==='
echo "$(date) === Install Greengrass" >> /tmp/bootstrap.log
cd /tmp/
wget ${GG_LINK}
tar -xzvf ${GG_FILE} -C /
cp ggcredentials/cert.pem /greengrass/certs/
cp ggcredentials/private.key /greengrass/certs/
cp ggcredentials/config.json /greengrass/config/
wget -O /greengrass/certs/root.ca.pem https://www.amazontrust.com/repository/AmazonRootCA1.pem
echo '=== Prepare Greengrass ML Workshop ==='
echo "$(date) === Prepare Greengrass ML Workshop" >> /tmp/bootstrap.log
cd /tmp/
cp -R MachineHealthWorkshop/lambdas/PredictionLambda/ /home/ec2-user/environment/
chown -R ec2-user:ec2-user /home/ec2-user/environment/PredictionLambda
cp -R MachineHealthWorkshop/lambdas/OPCUALambda/ /home/ec2-user/environment/
chown -R ec2-user:ec2-user /home/ec2-user/environment/OPCUALambda
echo '=== Reboot in 1 minute ==='
echo "$(date) === Reboot in 1 minute" >> /tmp/bootstrap.log
/*
* Generated by asn1c-0.9.24 (http://lionet.info/asn1c)
* From ASN.1 module "S1AP-PDU"
* found in "/home/liu/openairinterface5g/openair3/S1AP/MESSAGES/ASN1/R10.5/S1AP-PDU.asn"
* `asn1c -gen-PER`
*/
#ifndef _S1ap_Paging_H_
#define _S1ap_Paging_H_
#include
/* Including external dependencies */
#include
#include
#include
#ifdef __cplusplus
extern "C" {
#endif
/* Forward declarations */
struct S1ap_IE;
/* S1ap-Paging */
typedef struct S1ap_Paging {
struct S1ap_Paging__s1ap_Paging_ies {
A_SEQUENCE_OF(struct S1ap_IE) list;
/* Context for parsing across buffer boundaries */
asn_struct_ctx_t _asn_ctx;
} s1ap_Paging_ies;
/*
* This type is extensible,
* possible extensions are below.
*/
/* Context for parsing across buffer boundaries */
asn_struct_ctx_t _asn_ctx;
} S1ap_Paging_t;
/* Implementation */
extern asn_TYPE_descriptor_t asn_DEF_S1ap_Paging;
#ifdef __cplusplus
}
#endif
/* Referred external types */
#include "S1ap-IE.h"
#endif /* _S1ap_Paging_H_ */
#include
template class c++
i try to design a template for my university project. i wrote the follwing code:
#ifndef _LinkedList_H_
#define _LinkedList_H_
#include "Link.h"
#include <ostream>
template <class L>//error one
class LinkedList
{
private:
Link<L> *pm_head;
Link<L> * pm_tail;
int m_numOfElements;
Link<L>* FindLink(L * dataToFind);
public:
LinkedList();
~LinkedList();
int GetNumOfElements(){return m_numOfElements;}
bool Add( L * data);
L *FindData(L * data);
template <class L> friend ostream & operator<<(ostream& os,const LinkedList<L> listToprint);//error two
L* GetDataOnTop();
bool RemoveFromHead();
L* Remove(L * toRemove);
this templete uses the link class templete
#ifndef _Link_H_
#define _Link_H_
template <class T>//error 3
class Link
{
private:
T* m_data;
Link* m_next;
Link* m_prev;
public:
Link(T* data);
~Link(void);
bool Link::operator ==(const Link& other)const;
/*getters*/
Link* GetNext()const {return m_next;}
Link* GetPrev()const {return m_prev;}
T* GetData()const {return m_data;}
//setters
void SetNext(Link* next) {m_next = next;}
void SetPrev(Link* prev) {m_prev = prev;}
void SetData(T* data) {m_data = data;}
};
error one: shadows template parm `class L'
error two:declaration of `class L'
error three: shadows template parm `class T'
i dont understand what is the problem. i can really use your help
thank you :)
Joda Time gives wrong time zone
I'm using the Joda time (1.6) libraries and it keeps returning DateTime objects with the wrong time zone, British Summer Time instead of GMT.
My Windows workstation (running JDK 1.6.0_16) thinks it's in GMT and if I get the default time zone from the JDK date/time classes it is correct (GMT). I get the same behaviour on our Linux servers as well. I thought it could be an error in the time zone database files in Joda so I rebuilt the jar with the latest database but with no change.
import java.util.TimeZone;
import org.joda.time.DateTime;
import org.joda.time.DateTimeZone;
import org.joda.time.LocalTime;
import org.joda.time.format.DateTimeFormatter;
import org.joda.time.format.ISODateTimeFormat;
public class TimeZoneTest {
public static void main(String[] args) {
DateTimeFormatter timeParser = ISODateTimeFormat.timeParser();
TimeZone timeZone = TimeZone.getDefault();
System.out.println(timeZone.getID()); // "Europe/London"
System.out.println(timeZone.getDisplayName()); // "Greenwich Mean Time"
DateTimeZone defaultTimeZone = DateTimeZone.getDefault();
System.out.println(defaultTimeZone.getID()); //"Europe/London"
System.out.println(defaultTimeZone.getName(0L)); //"British Summer Time"
DateTime currentTime = new DateTime();
DateTimeZone currentZone = currentTime.getZone();
System.out.println(currentZone.getID()); //"Europe/London"
System.out.println(currentZone.getName(0L)); //"British Summer Time"
}
}
Debugging through the static initialiser in org.joda.time.DateTimeZone I see that the System.getProperty("user.timezone") call gives "Europe/London" as expected.
// SPDX-License-Identifier: MPL-2.0
// SPDX-FileCopyrightText: 2021 The vanadinite developers
//
// This Source Code Form is subject to the terms of the Mozilla Public License,
// v. 2.0. If a copy of the MPL was not distributed with this file, You can
// obtain one at https://mozilla.org/MPL/2.0/.
#![allow(clippy::match_bool, clippy::identity_op)]
#![allow(incomplete_features)]
#![feature(
alloc_error_handler,
allocator_api,
arbitrary_self_types,
asm,
const_btree_new,
const_fn_fn_ptr_basics,
const_fn,
const_fn_trait_bound,
const_generics,
destructuring_assignment,
extern_types,
fn_align,
inline_const,
maybe_uninit_ref,
naked_functions,
new_uninit,
raw_ref_op,
thread_local
)]
#![no_std]
#![no_main]
#[cfg(not(target_pointer_width = "64"))]
compile_error!("vanadinite assumes a 64-bit pointer size, cannot compile on non-64 bit systems");
extern crate alloc;
pub mod asm;
pub mod boot;
pub mod cpu_local;
pub mod csr;
pub mod drivers;
pub mod interrupts;
pub mod io;
pub mod mem;
pub mod platform;
pub mod scheduler;
pub mod sync;
pub mod syscall;
pub mod task;
pub mod trap;
pub mod utils;
use {
core::sync::atomic::{AtomicUsize, Ordering},
drivers::{generic::plic::Plic, CompatibleWith},
interrupts::PLIC,
mem::{
kernel_patching,
paging::{PhysicalAddress, VirtualAddress},
phys::{PhysicalMemoryAllocator, PHYSICAL_MEMORY_ALLOCATOR},
phys2virt,
},
sync::SpinMutex,
utils::Units,
};
use alloc::boxed::Box;
use drivers::InterruptServicable;
use fdt::Fdt;
use mem::kernel_patching::kernel_section_v2p;
use sbi::{hart_state_management::hart_start, probe_extension, ExtensionAvailability};
use scheduler::Scheduler;
pub use vanadinite_macros::{debug, error, info, trace, warn};
static N_CPUS: AtomicUsize = AtomicUsize::new(1);
static TIMER_FREQ: AtomicUsize = AtomicUsize::new(0);
static INIT_FS: &[u8] = include_bytes!("../../../initfs.tar");
static BLOCK_DEV: SpinMutex> = SpinMutex::new(None);
cpu_local! {
static HART_ID: core::cell::Cell = core::cell::Cell::new(0);
}
#[no_mangle]
#[repr(align(4))]
extern "C" fn kmain(hart_id: usize, fdt: *const u8) -> ! {
csr::stvec::set(trap::stvec_trap_shim);
let heap_frame_alloc = unsafe { PHYSICAL_MEMORY_ALLOCATOR.lock().alloc_contiguous(64) };
let heap_start = mem::phys2virt(heap_frame_alloc.expect("moar memory").as_phys_address());
unsafe { mem::heap::HEAP_ALLOCATOR.init(heap_start.as_mut_ptr(), 64 * 4.kib()) };
unsafe { crate::cpu_local::init_thread_locals() };
HART_ID.set(hart_id);
crate::io::logging::init_logging();
let fdt: Fdt<'static> = match unsafe { Fdt::from_ptr(fdt) } {
Ok(fdt) => fdt,
Err(e) => crate::platform::exit(crate::platform::ExitStatus::Error(&e)),
};
/*
* This header is generated by classdump-dyld 1.0
* on Saturday, June 1, 2019 at 6:46:33 PM Mountain Standard Time
* Operating System: Version 12.1.1 (Build 16C5050a)
* Image Source: /System/Library/PrivateFrameworks/CompanionSync.framework/CompanionSync
* classdump-dyld is licensed under GPLv3, Copyright © 2013-2016 by Elias Limneos.
*/
#import
#import
@class NRDevice, NSUUID, NSString, NSDate, PBCodable;
@interface SYDevice : NSObject {
NRDevice* _nrDevice;
NSUUID* _pairingID;
NSString* _pairingStorePath;
NSString* _deviceClass;
NSString* _systemVersion;
NSString* _systemBuildVersion;
NSDate* _lastActiveDate;
BOOL _hasCachedNearby;
BOOL _cachedIsNearby;
long long _state;
}
@property (nonatomic,readonly) NRDevice * nrDevice; //@synthesize nrDevice=_nrDevice - In the implementation block
@property (assign,nonatomic) long long state; //@synthesize state=_state - In the implementation block
@property (getter=isTargetable,nonatomic,readonly) BOOL targetable;
@property (getter=isPaired,nonatomic,readonly) BOOL paired;
@property (getter=isActive,nonatomic,readonly) BOOL active;
@property (nonatomic,copy,readonly) NSString * pairingStorePath; //@synthesize pairingStorePath=_pairingStorePath - In the implementation block
@property (nonatomic,readonly) NSUUID * pairingID; //@synthesize pairingID=_pairingID - In the implementation block
@property (nonatomic,readonly) long long deviceCode;
@property (nonatomic,readonly) NSString * deviceClass; //@synthesize deviceClass=_deviceClass - In the implementation block
@property (nonatomic,readonly) NSString * systemVersion; //@synthesize systemVersion=_systemVersion - In the implementation block
@property (nonatomic,readonly) NSString * systemBuildVersion; //@synthesize systemBuildVersion=_systemBuildVersion - In the implementation block
@property (nonatomic,readonly) NSDate * lastActiveDate; //@synthesize lastActiveDate=_lastActiveDate - In the implementation block
@property (nonatomic,readonly) BOOL supportsFileTransferMessageSend;
@property (assign,nonatomic) BOOL hasCachedNearby; //@synthesize hasCachedNearby=_hasCachedNearby - In the implementation block
@property (assign,nonatomic) BOOL cachedIsNearby; //@synthesize cachedIsNearby=_cachedIsNearby - In the implementation block
@property (readonly) unsigned long long hash;
@property (readonly) Class superclass;
@property (copy,readonly) NSString * description;
@property (copy,readonly) NSString * debugDescription;
@property (nonatomic,readonly) PBCodable * stateForLogging;
+(id)targetableDevice;
+(id)knownDevices;
+(id)deviceForNRDevice:(i
var SECTION = "15.5.4.8-1";
var VERSION = "ECMA_1";
startTest();
var TITLE = "String.prototype.split";
writeHeaderToLog( SECTION + " "+ TITLE);
new TestCase( SECTION, "String.prototype.split.length", 2, String.prototype.split.length );
new TestCase( SECTION, "delete String.prototype.split.length", false, delete String.prototype.split.length );
new TestCase( SECTION, "delete String.prototype.split.length; String.prototype.split.length", 2, eval("delete String.prototype.split.length; String.prototype.split.length") );
// test cases for when split is called with no arguments.
// this is a string object
new TestCase( SECTION,
"var s = new String('this is a string object'); typeof s.split()",
"object",
eval("var s = new String('this is a string object'); typeof s.split()") );
new TestCase( SECTION,
"var s = new String('this is a string object'); Array.prototype.getClass = Object.prototype.toString; (s.split()).getClass()",
"[object Array]",
eval("var s = new String('this is a string object'); Array.prototype.getClass = Object.prototype.toString; (s.split()).getClass()") );
new TestCase( SECTION,
"var s = new String('this is a string object'); s.split().length",
1,
eval("var s = new String('this is a string object'); s.split().length") );
new TestCase( SECTION,
"var s = new String('this is a string object'); s.split()[0]",
"this is a string object",
eval("var s = new String('this is a string object'); s.split()[0]") );
// this is an object object
new TestCase( SECTION,
"var obj = new Object(); obj.split = String.prototype.split; typeof obj.split()",
"object",
eval("var obj = new Object(); obj.split = String.prototype.split; typeof obj.split()") );
new TestCase( SECTION,
"var obj = new Object(); obj.split = String.prototype.split; Array.prototype.getClass = Object.prototype.toString; obj.getClass()",
"[object Array]",
eval("var obj = new Object(); obj.split = String.prototype.split; Array.prototype.getClass = Object.prototype.toString; obj.split().getClass()") );
new TestCase( SECTION,
"var obj = new Object(); obj.split = String.prototype.split; obj.split().length",
1,
eval("var obj = new Object(); obj.split = String.prototype.split; obj.split().length") );
new TestCase( SECTION,
"var obj = new Object(); obj.split = String.prototype.split; obj.split()[0]",
"[object Object]",
eval("var obj = new Object(); obj.split = String.prototype.split; obj.split()[0]") );
// this is a function object
new TestCase( SECTION,
"var obj = new Function(); obj.split = String.prototype.split; typeof obj.split()",
"object",
eval("var obj = new Function(); obj.split = String.prototype.split; typeof obj.split()") );
-- phpMyAdmin SQL Dump
-- version 4.9.0.1
-- https://www.phpmyadmin.net/
--
-- Servidor: 127.0.0.1
-- Tiempo de generación: 28-05-2021 a las 04:22:04
-- Versión del servidor: 10.4.6-MariaDB
-- Versión de PHP: 7.3.9
SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
SET AUTOCOMMIT = 0;
START TRANSACTION;
SET time_zone = "+00:00";
/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8mb4 */;
--
-- Base de datos: `inscripcion`
--
-- --------------------------------------------------------
--
-- Estructura de tabla para la tabla `adulto`
--
CREATE TABLE `adulto` (
`id` int(11) NOT NULL,
`nombre` varchar(255) NOT NULL,
`documento` varchar(50) NOT NULL,
`fecha_expedicion` date NOT NULL,
`fecha_nacimiento` date NOT NULL,
`sexo` varchar(50) NOT NULL,
`direccion` varchar(255) DEFAULT NULL,
`telefono` varchar(50) NOT NULL,
`sisben` varchar(50) DEFAULT NULL,
`nombre_contacto` varchar(255) NOT NULL,
`telefono_contacto` varchar(50) DEFAULT NULL,
`celular_contacto` varchar(50) NOT NULL,
`direccion_contacto` varchar(255) DEFAULT NULL,
`cedula` varchar(50) DEFAULT NULL,
`recibo` varchar(50) NOT NULL,
`certificado_postulacion` varchar(50) NOT NULL,
`certificado_sisben` varchar(50) NOT NULL,
`fecha_creacion` timestamp NOT NULL DEFAULT current_timestamp()
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
--
-- Volcado de datos para la tabla `adulto`
--
INSERT INTO `adulto` (`id`, `nombre`, `documento`, `fecha_expedicion`, `fecha_nacimiento`, `sexo`, `direccion`, `telefono`, `sisben`, `nombre_contacto`, `telefono_contacto`, `celular_contacto`, `direccion_contacto`, `cedula`, `recibo`, `certificado_postulacion`, `certificado_sisben`, `fecha_creacion`) VALUES
(1, 'Marina', '100', '2021-03-08', '2021-03-09', 'Femenino', 'Blas de Lezo', '300', '32', 'Abelardo', '32432', '3423', 'Calle 70', '100.pdf', '100.png', '100.jpg', '100.png', '2021-03-09 02:04:52');
-- --------------------------------------------------------
--
-- Estructura de tabla para la tabla `control`
--
CREATE TABLE `control` (
`id` int(11) NOT NULL,
`documento` varchar(50) NOT NULL,
`imagen` varchar(50) NOT NULL,
`img` varchar(255) NOT NULL,
`estado` varchar(50) NOT NULL,
`estado_upload` int(11) NOT NULL DEFAULT 1,
`observacion` text DEFAULT NULL,
`users_id` int(11) NOT NULL,
`fecha_creacion` timestamp NOT NULL DEFAULT current_timestamp()
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
--
-- Volcado de datos para la tabla `control`
--
### User:
Is it faster to run a million small SQLite inserts one by one or in a single transaction? Why?
### Assistant:
A single transaction — faster by orders of magnitude, sometimes hundreds of times. By default SQLite wraps each statement in its own transaction, and every transaction ends with an fsync — a forced flush to disk for durability. A million single inserts = a million fsyncs, and an fsync costs milliseconds even on SSDs. Inside one transaction, fsync happens once at COMMIT.
Practically: wrap the batch in `BEGIN ... COMMIT`, use a prepared statement, and enable `PRAGMA journal_mode=WAL` — with WAL, writes don't block readers and commits are cheaper.
Linux C++: Linker is outputting strange errors
Alright, here is the output I get:
arm-none-linux-gnueabi-ld --entry=main -dynamic-linker=/system/bin/linker -rpath-link=/home/oem/android-ndk-r3/build/platforms/android-5/arch-arm/usr/lib -L/home/oem/android-ndk-r3/build/platforms/android-5/arch-arm/usr/lib -nostdlib -lstdc++ -lm -lGLESv1_CM -rpath=/home/oem/android-ndk-r3/build/platforms/android-5/arch-arm/usr/lib -rpath=../../YoghurtGum/lib/Android -L./lib/Android intermediate/Alien.o intermediate/Bullet.o intermediate/Game.o intermediate/Player.o ../../YoghurtGum/bin/YoghurtGum.a -o bin/Galaxians.android
intermediate/Game.o: In function `Galaxians::Init()':
/media/YoghurtGum/Tests/Galaxians/src/Game.cpp:45: undefined reference to `__cxa_end_cleanup'
/media/YoghurtGum/Tests/Galaxians/src/Game.cpp:44: undefined reference to `__cxa_end_cleanup'
intermediate/Game.o:(.ARM.extab+0x18): undefined reference to `__gxx_personality_v0'
intermediate/Game.o: In function `Player::Update()':
/media/YoghurtGum/Tests/Galaxians/src/Player.h:41: undefined reference to `__cxa_end_cleanup'
intermediate/Game.o:(.ARM.extab.text._ZN6Player6UpdateEv[_ZN6Player6UpdateEv]+0x0): undefined reference to `__gxx_personality_v0'
intermediate/Game.o:(.rodata._ZTIN10YoghurtGum4GameE[_ZTIN10YoghurtGum4GameE]+0x0): undefined reference to `vtable for __cxxabiv1::__class_type_info'
intermediate/Game.o:(.rodata._ZTI6Player[_ZTI6Player]+0x0): undefined reference to `vtable for __cxxabiv1::__si_class_type_info'
intermediate/Game.o:(.rodata._ZTIN10YoghurtGum6EntityE[_ZTIN10YoghurtGum6EntityE]+0x0): undefined reference to `vtable for __cxxabiv1::__si_class_type_info'
intermediate/Game.o:(.rodata._ZTIN10YoghurtGum6ObjectE[_ZTIN10YoghurtGum6ObjectE]+0x0): undefined reference to `vtable for __cxxabiv1::__class_type_info'
intermediate/Game.o:(.rodata._ZTI6Bullet[_ZTI6Bullet]+0x0): undefined reference to `vtable for __cxxabiv1::__si_class_type_info'
intermediate/Game.o:(.rodata._ZTI5Alien[_ZTI5Alien]+0x0): undefined reference to `vtable for __cxxabiv1::__si_class_type_info'
intermediate/Game.o:(.rodata+0x20): undefined reference to `vtable for __cxxabiv1::__si_class_type_info'
../../YoghurtGum/bin/YoghurtGum.a(Sprite.o):(.rodata._ZTIN10YoghurtGum16SpriteDataOpenGLE[_ZTIN10YoghurtGum16SpriteDataOpenGLE]+0x0): undefined reference to `vtable for __cxxabiv1::__si_class_type_info'
../../YoghurtGum/bin/YoghurtGum.a(Sprite.o):(.rodata._ZTIN10YoghurtGum10SpriteDataE[_ZTIN10YoghurtGum10SpriteDataE]+0x0): undefined reference to `vtable for __cxxabiv1::__class_type_info'
make: *** [bin/Galaxians.android] Fout 1
Here's an error I managed to decipher:
intermediate/Game.o: In function `Galaxians::Init()':
/media/YoghurtGum/Tests/Galaxians/src/Game.cpp:45: undefined reference to `__cxa_end_cleanup'
/media/YoghurtGum/Tests/Galaxians/src/Game.cpp:44: undefined reference to `__cxa_end_cleanup'
This is line 43 through 45:
#!/bin/bash
echo ""
echo " _____ ____ _____ _ ____ __ _____ ______ "
echo "| __ \ / __ \ / ____| |/ /\ \ / /\ | __ \| ____|"
echo "| | | | | | | | | ' / \ \ /\ / / \ | |__) | |__ "
echo "| | | | | | | | | < \ \/ \/ / /\ \ | _ /| __| "
echo "| |__| | |__| | |____| . \ \ /\ / ____ \| | \ \| |____ "
echo "|_____/ \____/ \_____|_|\_\ \/ \/_/ \_\_| \_\______|"
echo ""
echo "68 69 20 64 65 76 65 6C 6F 70 65 72 2C 20 6E 69 63 65 20 74 6F 20 6D 65 65 74 20 79 6F 75"
echo "6c 6f 6f 6b 69 6e 67 20 66 6f 72 20 61 20 6a 6f 62 3f 20 77 72 69 74 65 20 75 73 20 61 74 20 6a 6f 62 73 40 64 61 73 69 73 74 77 65 62 2e 64 65"
echo ""
echo "*******************************************************"
echo "** DOCKWARE IMAGE: dev"
echo "** Tag: 6.1.1"
echo "** Version: 1.4.3"
echo "** Built: $(cat /build-date.txt)"
echo "** Copyright 2021 dasistweb GmbH"
echo "*******************************************************"
echo ""
echo "launching dockware...please wait..."
echo ""
set -e
source /etc/apache2/envvars
# it's possible to add a custom boot script on startup.
# so we test if it exists and just execute it
file="/var/www/boot_start.sh"
if [ -f "$file" ] ; then
sh $file
fi
echo "DOCKWARE: setting timezone to ${TZ}..."
sudo ln -sf /usr/share/zoneinfo/${TZ} /etc/localtime
sudo dpkg-reconfigure -f noninteractive tzdata
echo "-----------------------------------------------------------"
if [ $XDEBUG_ENABLED = 1 ]; then
sh /var/www/scripts/bin/xdebug_enable.sh
else
sh /var/www/scripts/bin/xdebug_disable.sh
fi
if [ $FILEBEAT_ENABLED = 1 ]; then
echo "DOCKWARE: activating Filebeat..."
sudo service filebeat start --strict.perms=false
echo "-----------------------------------------------------------"
fi
if [ $COMPOSER_VERSION = 1 ]; then
echo "DOCKWARE: switching to composer 1..."
sudo composer self-update --1
echo "-----------------------------------------------------------"
fi
if [ $COMPOSER_VERSION = 2 ]; then
echo "DOCKWARE: switching to composer 2..."
sudo composer self-update --stable
echo "-----------------------------------------------------------"
fi
if [ $TIDEWAYS_KEY != "not-set" ]; then
echo "DOCKWARE: activating Tideways...."
sudo sed -i 's/__DOCKWARE_VAR_TIDEWAYS_ENV__/'${TIDEWAYS_ENV}'/g' /etc/default/tideways-daemon
sudo sed -i 's/__DOCKWARE_VAR_TIDEWAYS_API_KEY__/'${TIDEWAYS_KEY}'/g' /etc/php/$PHP_VERSION/fpm/conf.d/20-tideways.ini
sudo sed -i 's/__DOCKWARE_VAR_TIDEWAYS_SERVICE__/'${TIDEWAYS_SERVICE}'/g' /etc/php/$PHP_VERSION/fpm/conf.d/20-tideways.ini
sudo sed -i 's/__DOCKWARE_VAR_TIDEWAYS_API_KEY__/'${TIDEWAYS_KEY}'/g' /etc/php/$PHP_VERSION/cli/conf.d/20-tideways.ini
sudo sed -i 's/__DOCKWARE_VAR_TIDEWAYS_SERVICE__/'${TIDEWAYS_SERVICE}'/g' /etc/php/$PHP_VERSION/cli/conf.d/20-tideways.ini
sudo service tideways-daemon start
echo "-----------------------------------------------------------"
fi
The script resource is behind a redirect, which is disallowed
I'm implementing firebase messaging but i'm getting a error on console in chrome.
The script resource is behind a redirect, which is disallowed.
/firebase-messaging-sw.js Failed to load resource: net::ERR_UNSAFE_REDIRECT
The file /firebase-messaging-sw.js is in public folder and i'm using FCM installation like this https://github.com/firebase/quickstart-js/tree/master/messaging
But the link the authorization is a link like https://09029e3f.ngrok.io/admin/pt/settings/notifications .
but the main web site is on main.domain.com
Islam is the most widespread religion in Bosnia and Herzegovina. It was introduced to the local population in the 15th and 16th centuries as a result of the Ottoman conquest of Bosnia and Herzegovina.
Muslims comprise the single largest religious community in Bosnia and Herzegovina (50%) (the other two large groups being Eastern Orthodox Christians (31%), almost all of whom identify as Serbs, and Roman Catholics (16%), almost all of whom identify as Croats. Another estimate done by PEW Research states that 50% of the population is Muslim, 35% Orthodox and only 9% Catholic.
Almost all of Bosnian Muslims identify as Bosniaks; until 1993, Bosnians of Muslim culture or origin (regardless of religious practice) were defined by Yugoslav authorities as Muslimani (Muslims) in an ethno-national sense (hence the capital M), though some people of Bosniak or Muslim backgrounds identified their nationality (in an ethnic sense rather than strictly in terms of citizenship) as "Yugoslav" prior to the early 1990s. A small minority of non-Bosniak Muslims in Bosnia and Herzegovina include Albanians, Roma and Turks.
Albeit traditionally adherent to Sunni Islam of the Hanafi school of jurisprudence, a 2012 survey found 54% of Bosnia and Herzegovina's Muslims to consider themselves just Muslims, while 38% told that they are Sunni Muslims. There is also a small Sufi community, located primarily in Central Bosnia. A small Shia Muslim community is also present in Bosnia. Almost all Muslim congregations in Bosnia and Herzegovina refer to the Islamic Community of Bosnia and Herzegovina as their religious organisation.
The Constitution of Bosnia and Herzegovina guarantees freedom of religion, which is generally upheld throughout the country.
History
The Ottoman era
Islam was first introduced to the Balkans on a large scale by the Ottomans in the mid-to-late 15th century who gained control of most of Bosnia in 1463, and seized Herzegovina in the 1480s. Over the next century, the Bosnians – composed of native Christians and Slavic tribes living in the Bosnian kingdom under the name of Bošnjani – were converted to Islam in great numbers during the Islamization of Bosnia under Ottoman rule. During the Ottoman era the name Bošnjanin was definitely transformed into the current Bošnjak ('Bosniak'), with the suffix -ak replacing the traditional -anin. By the early 1600s, approximately two thirds of the population of Bosnia were Muslim. Bosnia and Herzegovina remained a province in the Ottoman Empire and gained autonomy after the Bosnian uprising in 1831. Large numbers of mosques were built all over the province. Most mosques erected during the Ottoman era were of relatively modest construction, often with a single minaret and central prayer hall with few adjoining foyers.
#!/bin/sh
#
# Copyright (C) Internet Systems Consortium, Inc. ("ISC")
#
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
#
# See the COPYRIGHT file distributed with this work for additional
# information regarding copyright ownership.
SYSTEMTESTTOP=..
. $SYSTEMTESTTOP/conf.sh
DIGOPTS="-p ${PORT} +tries=1 +time=2"
# Check whether the SOA record for the name provided in $1 can be resolved by
# ns1. Return 0 if resolution succeeds as expected; return 1 otherwise.
resolution_succeeds() {
_ret=0
$DIG $DIGOPTS +tcp +tries=3 +time=5 @10.53.0.1 ${1} SOA > dig.out.test$n || _ret=1
grep "status: NOERROR" dig.out.test$n > /dev/null || _ret=1
return $_ret
}
# Check whether the SOA record for the name provided in $1 can be resolved by
# ns1. Return 0 if resolution fails as expected; return 1 otherwise. Note that
# both a SERVFAIL response and timing out mean resolution failed, so the exit
# code of dig does not influence the result (the exit code for a SERVFAIL
# response is 0 while the exit code for not getting a response at all is not 0).
resolution_fails() {
_servfail=0
_timeout=0
$DIG $DIGOPTS +tcp +tries=3 +time=5 @10.53.0.1 ${1} SOA > dig.out.test$n
grep "status: SERVFAIL" dig.out.test$n > /dev/null && _servfail=1
grep "connection timed out" dig.out.test$n > /dev/null && _timeout=1
if [ $_servfail -eq 1 ] || [ $_timeout -eq 1 ]; then
return 0
else
return 1
fi
}
status=0
n=0
n=`expr $n + 1`
echo_i "checking formerr edns server setup ($n)"
ret=0
$DIG $DIGOPTS +edns @10.53.0.8 ednsformerr soa > dig.out.1.test$n || ret=1
grep "status: FORMERR" 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.8 ednsformerr 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 formerr edns server succeeds ($n)"
ret=0
resolution_succeeds ednsformerr. || ret=1
if [ $ret != 0 ]; then echo_i "failed"; fi
status=`expr $status + $ret`
n=`expr $n + 1`
echo_i "checking notimp edns server setup ($n)"
ret=0
$DIG $DIGOPTS +edns @10.53.0.9 ednsnotimp soa > dig.out.1.test$n || ret=1
grep "status: NOTIMP" 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.9 ednsnotimp 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`
Why am I getting a 404 response from my POST in web api?
I have the following action in my Web api controller:
// POST api/<controller>
[AllowAnonymous]
[HttpPost]
public bool Post(string user, string password)
{
return true;
}
I am getting the following error with a 404 status when hitting it with either fiddler or a test jQuery script:
{"Message":"No HTTP resource was found that matches the request URI 'http://localhost/amsi-v8.0.0/api/account '.","MessageDetail":"No action was found on the controller 'Account' that matches the request."}
My http route is as follows:
RouteTable.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
Gets work fine. I found another question here which talks about removing WebDAV from IIS. I tried that, still same issue.
Why do I get a 404?
package com.example.mobilesafe01;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
import com.example.mobilesafe01.adapter.CacheAdapter;
import com.example.mobilesafe01.bean.CacheBean;
import android.app.Activity;
import android.content.Context;
import android.content.pm.ApplicationInfo;
import android.content.pm.IPackageDataObserver;
import android.content.pm.IPackageStatsObserver;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.content.pm.PackageStats;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.SystemClock;
import android.text.format.Formatter;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.animation.TranslateAnimation;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
public class CacheCleanActivity extends Activity implements OnClickListener {
private Context mContext;
private RelativeLayout rl_scan;
private ImageView iv_icon;
private ImageView iv_line;
private ProgressBar pb;
private TextView tv_name;
private TextView tv_size;
private RelativeLayout rl_finish;
private Button bt_scan;
private TextView tv_result;
private ListView lv_scan;
private List list;
private CacheAdapter cacheAdapter;
private PackageManager pm;
private Task task;
private Button bt_one_clean;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_cache_clean);
mContext = this;
initView();
initData();
initEvent();
}
private void initEvent() {
bt_one_clean.setOnClickListener(this);
bt_scan.setOnClickListener(this);
}
private ClearCacheObserver mClearCacheObserver;
class ClearCacheObserver extends IPackageDataObserver.Stub {
public void onRemoveCompleted(final String packageName,
final boolean succeeded) {
}
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.activity_cache_clean_bt_scan://快速扫描,重新扫描一次
initData();
break;
case R.id.activity_cache_clean_bt_one_clean://一键清理
if (mClearCacheObserver == null) {
mClearCacheObserver = new ClearCacheObserver();
}
try {
Method method =
pm.getClass().getMethod("freeStorageAndNotify",
long.class, IPackageDataObserver.class);
method.invoke(pm, Long.MAX_VALUE, mClearCacheObserver);
The Austro-Hungarian era
After the 1878 Congress of Berlin, Bosnia and Herzegovina came under the control of Austria-Hungary. In 1908, Austria-Hungary formally annexed the region. Unlike post-Reconquista Spain, the Austro-Hungarian authorities made no attempt to convert the citizens of this newly-acquired territory as the December Constitution guaranteed freedom of religion, and so Bosnia and Herzegovina remained Muslim.
Bosnia, along with Albania and Kosovo were the only parts of the Ottoman Empire in the Balkans where large numbers of people were converted to Islam, and remained there after independence. In other areas of the former Ottoman Empire where Muslims formed the majority or started to form the majority, those Muslims were either expelled, assimilated/Christianized, massacred, or fled elsewhere (Muhajirs).
The post-war period
Many Islamic religious buildings were damaged or destroyed in the Bosnian War during the 90s, with up to 80% of well-over 4000 different buildings, and several mosques were rebuilt with the aid of funds from Saudi Arabia and other countries from the Middle and far East.
Historically, Bosnian Muslims had always practiced a form of Islam that is strongly influenced by Sufism. Since the Bosnian War, however, some remnants of groups of foreign fighters from the Middle East fighting on the side of Bosnian Army, remained for some time and attempted to spread Wahhabism among locals. With very limited success these foreigners only created friction between local Muslim population, steeped in their own traditional practice of the faith, and without any previous contact with this strain in Islam, and themselves.
Although these communities were relatively small and peaceful, restricted to a certain number of villages around central and northern Bosnia, the issue was highly politicized by local nationalists and officials, as well as officials and diplomats from countries like Croatia, Czech Republic and Serbia, to the point of outright fiction. Security Minister of Bosnia and Herzegovina at the time, Dragan Mektić of SDS, reacted strongly on such falsehoods by pointing on seriousness of such conspiratorial claims, and warned on possibility of further dangerous politicization and even acts of violence with an aim of labeling Bosnian Muslims as radicals.
Demographics
In the 2013 census the declared religious affiliation of the population was: Islam (1,790,454 people) and Muslim (22,068 people). Islam has 1.8 million adherents, making up about 51% of the population in Bosnia and Herzegovina. PEW survey says that there are 52% Muslims in Bosnia and Herzegovina.
The municipalities of Bužim (99.7%) and Teočak (99.7%) have the highest share of Muslims in Bosnia and Herzegovina.
Contemporary relations
How to use CSS to position div popup when using :hover...?
I am trying to create a popup in CSS. In this case, it's a small div containing text labeling the image you're hovering. However, I am definitely doing it wrong. I am either positioning the :hover div in CSS incorrectly (I've tried different positions (fixed, absolute, float, clear, etc.), but it keeps showing up inside the main div. I could wrong with my HTML, as I'm placing it within the main div that you hover for the popup to appear. But I'd think it has to be there to show up when you hover the main div. Any help is appreciated. Code below:
HTML:
<div class="topIcons topIconsHover topLabelHover">
<a href="image.html"><img src="icons/image.png" /></a>
<div class="topLabelHover">Image</div>
</div>
CSS:
.topIcons {
padding:14px 6px 10px 6px;
float:right;
}
.topIconsHover:hover {
background-color:#555555;
cursor:pointer
}
.topLabelHover:hover {
background-color:#555555;
width:80px;
height:24px;
position:fixed;
top:40px;
}
I am fine with using JavaScript (or JQuery) if it's necessary, but it seems like something simple enough for CSS. Also, is it better to use CSS over JavaScript (or Jquery) when possible because perhaps it's faster? I could be mistaken there, but would be interested to of the best practice.
edit* Still having trouble so thought I'd explain further what I'm trying to do with my page layout and perhaps it'll help. I have a series of icons in a navigation bar, all floated right. Upon hovering, I'd like the background to change (which I've managed in CSS with the "topIconsHover" class) and for a "label" div to appear beneath the related hovered icon div in the navigation bar when hovered.
HTML5 Audio stop function
I am playing a small audio clip on click of each link in my navigation
HTML Code:
<audio tabindex="0" id="beep-one" controls preload="auto" >
<source src="audio/Output 1-2.mp3">
<source src="audio/Output 1-2.ogg">
</audio>
JS code:
$('#links a').click(function(e) {
e.preventDefault();
var beepOne = $("#beep-one")[0];
beepOne.play();
});
It's working fine so far.
Issue is when a sound clip is already running and i click on any link nothing happens.
I tried to stop the already playing sound on click of link, but there is no direct event for that in HTML5's Audio API
I tried following code but it's not working
$.each($('audio'), function () {
$(this).stop();
});
Any suggestions please?
How to create a new project in adobe-brackets?
I've started using adobe-brackets for editing JavaScript, HTML and CSS.
Currently I have the "Getting Started" project open in my side bar. I would like to create a new project , but there is no such "New Project" item in the File menu.
I tried clicking on "Project settings", but that just gives me this:
How do you get rid of the default "Getting Started" project, and start a fresh new one?
let repoUrl;
let userPromise;
if (options.user) {
userPromise = Promise.resolve(options.user);
} else {
userPromise = getUser();
}
return userPromise.then(user =>
getRepo(options)
.then(repo => {
repoUrl = repo;
const clone = path.join(options.getCacheDir(), filenamify(repo));
log('Cloning %s into %s', repo, clone);
return Git.clone(repo, clone, options.branch, options);
})
.then(git => {
return git.getRemoteUrl(options.remote).then(url => {
if (url !== repoUrl) {
const message =
'Remote url mismatch. Got "' +
url +
'" ' +
'but expected "' +
repoUrl +
'" in ' +
git.cwd +
'. Try running the `gh-pages-clean` script first.';
throw new Error(message);
}
return git;
});
})
.then(git => {
// only required if someone mucks with the checkout between builds
log('Cleaning');
return git.clean();
})
.then(git => {
log('Fetching %s', options.remote);
return git.fetch(options.remote);
})
.then(git => {
log('Checking out %s/%s ', options.remote, options.branch);
return git.checkout(options.remote, options.branch);
})
.then(git => {
if (!options.history) {
return git.deleteRef(options.branch);
} else {
return git;
}
})
.then(git => {
if (!options.add) {
log('Removing files');
return git.rm(only.join(' '));
} else {
return git;
}
})
.then(git => {
log('Copying files');
return copy(files, basePath, path.join(git.cwd, options.dest)).then(
function() {
return git;
}
);
})
.then(git => {
log('Adding all');
return git.add('.');
})
.then(git => {
if (!user) {
return git;
}
return git.exec('config', 'user.email', user.email).then(() => {
if (!user.name) {
return git;
}
return git.exec('config', 'user.name', user.name);
});
})
.then(git => {
log('Committing');
return git.commit(options.message);
})
.then(git => {
if (options.tag) {
log('Tagging');
return git.tag(options.tag).catch(error => {
// tagging failed probably because this tag alredy exists
log(error);
log('Tagging failed, continuing');
return git;
});
} else {
return git;
}
})
.then(git => {
if (options.push) {
log('Pushing');
return git.push(options.remote, options.branch, !options.history);
} else {
return git;
}
})
.then(
()
// 释放完缓存, 重新加载一次数据
initData();
} catch (Exception e) {
e.printStackTrace();
}
break;
default:
break;
}
}
private void initData() {
task = new Task();
task.execute();
}
// 扫描是否完成的标志位,用来解决异步任务导致ListView无法回到第一个条目的问题,mStatsObserver响应获取数据需要时间
private boolean isScanFinished = false;
//获取缓存数据的回调对象
final IPackageStatsObserver.Stub mStatsObserver = new IPackageStatsObserver.Stub() {
public void onGetStatsCompleted(PackageStats stats, boolean succeeded) {
CacheBean cacheBean = new CacheBean();
long cacheSize = stats.cacheSize;//获取缓存数据
cacheBean.size = cacheSize;
//Log.e("ming", Formatter.formatFileSize(mContext, cacheSize));
String packageName = stats.packageName;//获取包名
cacheBean.packageName = packageName;
try {
cacheBean.icon = pm.getApplicationIcon(packageName);
ApplicationInfo info = pm.getApplicationInfo(packageName, 0);
cacheBean.label = pm.getApplicationLabel(info).toString();
} catch (NameNotFoundException e) {
e.printStackTrace();
//名字找不着时显示的数据
cacheBean.icon = mContext.getResources().getDrawable(R.drawable.ic_launcher);
cacheBean.label = packageName;
}
//LogUtils.e("notifyChange");
//通知onProgressUpdate()更新数据,将封装数据的bean还回
task.notifyChange(cacheBean);
}
};
//增加标志位判断当前Activity是否失去焦点
private boolean isActivityFocus = false;
@Override
protected void onStart() {
super.onStart();
isActivityFocus = true;
}
@Override
protected void onPause() {
super.onPause();
isActivityFocus = false;
}
//•需求 : 在高版本系统上AsyncTask的执行是单线程的,如果多次打开清理页面,再退出,会导致页面数据展示出现异常.
//•实现 : 增加标志位,如果当前Activity失去焦点,中断for循环
#!/bin/bash
FN="ChimpHumanBrainData_1.32.0.tar.gz"
URLS=(
"https://bioconductor.org/packages/3.14/data/experiment/src/contrib/ChimpHumanBrainData_1.32.0.tar.gz"
"https://bioarchive.galaxyproject.org/ChimpHumanBrainData_1.32.0.tar.gz"
"https://depot.galaxyproject.org/software/bioconductor-chimphumanbraindata/bioconductor-chimphumanbraindata_1.32.0_src_all.tar.gz"
)
MD5="c51727597298ea23ef24be72f276c4d5"
# Use a staging area in the conda dir rather than temp dirs, both to avoid
# permission issues as well as to have things downloaded in a predictable
# manner.
STAGING=$PREFIX/share/$PKG_NAME-$PKG_VERSION-$PKG_BUILDNUM
mkdir -p $STAGING
TARBALL=$STAGING/$FN
SUCCESS=0
for URL in ${URLS[@]}; do
curl $URL > $TARBALL
[[ $? == 0 ]] || continue
# Platform-specific md5sum checks.
if [[ $(uname -s) == "Linux" ]]; then
if md5sum -c <<<"$MD5 $TARBALL"; then
SUCCESS=1
break
fi
else if [[ $(uname -s) == "Darwin" ]]; then
if [[ $(md5 $TARBALL | cut -f4 -d " ") == "$MD5" ]]; then
SUCCESS=1
break
fi
fi
fi
done
if [[ $SUCCESS != 1 ]]; then
echo "ERROR: post-link.sh was unable to download any of the following URLs with the md5sum $MD5:"
printf '%s\n' "${URLS[@]}"
exit 1
fi
# Install and clean up
R CMD INSTALL --library=$PREFIX/lib/R/library $TARBALL
rm $TARBALL
rmdir $STAGING
/**
* Given a string, return its encoding version.
*
* @param {String} str
* @return {String}
*
* @example
* For aabbbc should return 2a3bc
*
*/
function encodeLine(str) {
let i = 0;
const array = str.split('');
let result = '';
while (i < array.length) {
let lett = '';
let summ = 1;
while (array[i + 1] === array[i] && i < array.length) {
lett = array[i];
i++;
summ++;
}
if (summ === 1) {
result += array[i];
} else {
result = lett + result + summ;
}
i++;
}
return result;
}
module.exports = encodeLine;
prop_meta = {
"child_action": MoPropertyMeta("child_action", "childAction", "string", VersionMeta.Version212a, MoPropertyMeta.INTERNAL, 0x2, None, None, r"""((deleteAll|ignore|deleteNonPresent),){0,2}(deleteAll|ignore|deleteNonPresent){0,1}""", [], []),
"color": MoPropertyMeta("color", "color", "string", VersionMeta.Version212a, MoPropertyMeta.READ_ONLY, None, None, None, None, ["amber", "blue", "green", "red", "unknown"], []),
"dn": MoPropertyMeta("dn", "dn", "string", VersionMeta.Version212a, MoPropertyMeta.READ_ONLY, 0x4, 0, 256, None, [], []),
"health_led_state": MoPropertyMeta("health_led_state", "healthLedState", "string", VersionMeta.Version212a, MoPropertyMeta.READ_ONLY, None, None, None, None, ["critical", "minor", "normal"], []),
"health_led_state_qualifier": MoPropertyMeta("health_led_state_qualifier", "healthLedStateQualifier", "string", VersionMeta.Version212a, MoPropertyMeta.READ_ONLY, None, 0, 510, None, [], []),
"id": MoPropertyMeta("id", "id", "uint", VersionMeta.Version212a, MoPropertyMeta.READ_WRITE, 0x8, None, None, None, [], []),
"name": MoPropertyMeta("name", "name", "string", VersionMeta.Version212a, MoPropertyMeta.READ_WRITE, 0x10, None, None, r"""[\-\.:_a-zA-Z0-9]{0,16}""", [], []),
"oper_state": MoPropertyMeta("oper_state", "operState", "string", VersionMeta.Version212a, MoPropertyMeta.READ_ONLY, None, None, None, None, ["blinking", "eth", "fc", "off", "on", "unknown", "unsupported"], []),
"rn": MoPropertyMeta("rn", "rn", "string", VersionMeta.Version212a, MoPropertyMeta.READ_ONLY, 0x20, 0, 256, None, [], []),
"sacl": MoPropertyMeta("sacl", "sacl", "string", VersionMeta.Version302c, MoPropertyMeta.READ_ONLY, None, None, None, r"""((none|del|mod|addchild|cascade),){0,4}(none|del|mod|addchild|cascade){0,1}""", [], []),
"status": MoPropertyMeta("status", "status", "string", VersionMeta.Version212a, MoPropertyMeta.READ_WRITE, 0x40, None, None, r"""((removed|created|modified|deleted),){0,3}(removed|created|modified|deleted){0,1}""", [], []),
}
prop_map = {
"childAction": "child_action",
"color": "color",
"dn": "dn",
"healthLedState": "health_led_state",
"healthLedStateQualifier": "health_led_state_qualifier",
"id": "id",
"name": "name",
"operState": "oper_state",
"rn": "rn",
"sacl": "sacl",
"status": "status",
}
def __init__(self, parent_mo_or_dn, **kwargs):
self._dirty_mask = 0
self.child_action = None
self.color = None
self.health_led_state = None
self.health_led_state_qualifier = None
self.id = None
self.name = None
self.oper_state = None
self.sacl = None
self.status = None
ManagedObject.__init__(self, "EquipmentHealthLed", parent_mo_or_dn, **kwargs)
SQL Server : add characters to a column
I have problem with getting SQL code: in a column I have a value with 5 or 6 characters before that values I need put character :0 and value in column must have 7 characters.
Column
------
123456
123456
12345
12345
123456
This is my code which does not work (I am using SQL Server):
Update table
set column = CONCAT( '0', ( column ) )
where LEN( + RTRIM ( column ) ) < 7
Update table
set column = CONCAT( '0', RTRIM ( column ) )
where LEN( RTRIM( column ) ) < 7
UPDATE table
SET column = '0' + column
WHERE LEN(column) = 7
My result : after my attempt, I get 0 before values but somewhere still 0 missing.
Column
-------
0123456
0123456
012345
012345
0123456
I need :
Column
-------
0123456
0123456
0012345
0012345
0123456
Thanks for updating my code
// Calculate the height of the header
const margins: [number, number, number, number] = useMemo(() => {
if (layoutCollapsed) {
return [headerRect?.height || 0, 0, footerHeight ? footerHeight + 2 : 2, 0]
}
return [0, 0, 2, 0]
}, [layoutCollapsed, footerHeight, headerRect])
const formViewHidden = activeView.type !== 'form'
const activeViewNode = useMemo(
() =>
activeView.type === 'component' &&
activeView.component &&
createElement(activeView.component, {
document: {
draft: editState?.draft || null,
displayed: displayed || value,
historical: displayed,
published: editState?.published || null,
},
documentId,
options: activeView.options,
schemaType: documentSchema,
}),
[
activeView,
displayed,
documentId,
documentSchema,
editState?.draft,
editState?.published,
value,
]
)
// Scroll to top as `documentId` changes
useEffect(() => {
if (!documentScrollElement?.scrollTo) return
documentScrollElement.scrollTo(0, 0)
}, [documentId, documentScrollElement])
return (
{activeView.type === 'form' && !isPermissionsLoading && ready && (
<>
>
)}
{activeViewNode}
)
}
Antonio Tomás González (born 19 January 1985) is a Spanish former professional footballer who played as a defensive midfielder.
Club career
Tomás was born in Torrelavega, Cantabria. He came through the youth ranks at local giants Racing de Santander, making his La Liga debut on 30 October 2005 by starting in a 1–1 away draw against Valencia CF and finishing the season with 23 games.
In 2006, Tomás was signed by Deportivo de La Coruña and immediately loaned to his former team for one year, returning for the 2007–08 campaign and playing sparingly as Depor finished ninth. From 2009 to 2011 he was regularly used by manager Miguel Ángel Lotina – only three of his 51 league appearances were not starts– but the Galicians were relegated in the second season and he was subsequently released.
On 27 September 2011, Tomás joined Real Zaragoza on a one-year contract. On 20 February of the following year, however, he severed his ties with the Aragonese and signed for 16 months with Bulgarian club PFC CSKA Sofia.
Tomás returned to his country for 2012–13, going on to spend four Segunda División campaigns with CD Numancia. On 17 July 2016, he agreed to a one-year deal at Super League Greece side Veria F.C. for an undisclosed fee.
Tomás returned to the Campos de Sport de El Sardinero in summer 2017, with Racing now in the Segunda División B.
Career statistics
References
External links
1985 births
Living people
People from Torrelavega
Spanish men's footballers
Footballers from Cantabria
Men's association football midfielders
La Liga players
Segunda División players
Segunda División B players
Tercera División players
Rayo Cantabria players
Racing de Santander players
Deportivo de La Coruña players
Real Zaragoza players
CD Numancia players
First Professional Football League (Bulgaria) players
PFC CSKA Sofia players
Super League Greece players
Veria F.C. players
Spanish expatriate men's footballers
Expatriate men's footballers in Bulgaria
Expatriate men's footballers in Greece
Spanish expatriate sportspeople in Bulgaria
Spanish expatriate sportspeople in Greece
Getting Serial Number of the Hard Drive Provided by the manufacturer through PHP
Getting Serial Number of the Hard Drive
Provided by the manufacturer through PHP :
How can it be done?
I want to store it in a file.
OS : windows 2000,XP,ME,Vista...
Yes, I want the serial number of the hard drive of the Server.
Or can it be done through Adobe AIR?
Or can it be done through a C program on Windows?
C:\Documents and Settings\Administrator>dir
Volume in drive C has no label.
Volume Serial Number is BC16-5D5F
Is this number : BC16-5d5f unique for a hard drive?
How is it different from the manufacturer given serial number?
wmic DISKDRIVE GET SerialNumber
Displays only the following text on my Vista Machine:
SerialNumber
On my XP machine, the command is unrecognized.
//! 一个关闭中断的互斥锁 [`Lock`]
use spin::{Mutex, MutexGuard};
/// 关闭中断的互斥锁
#[derive(Default)]
pub struct Lock(pub(self) Mutex);
/// 封装 [`MutexGuard`] 来实现 drop 时恢复 sstatus
pub struct LockGuard<'a, T> {
/// 在 drop 时需要先 drop 掉 [`MutexGuard`] 再恢复 sstatus
guard: Option>,
/// 保存的关中断前 sstatus
sstatus: usize,
}
impl Lock {
/// 创建一个新对象
pub fn new(obj: T) -> Self {
Self(Mutex::new(obj))
}
/// 获得上锁的对象
pub fn get<'a>(&'a self) -> LockGuard<'a, T> {
let sstatus: usize;
unsafe {
llvm_asm!("csrrci $0, sstatus, 1 << 1" : "=r"(sstatus) ::: "volatile");
}
LockGuard {
guard: Some(self.0.lock()),
sstatus,
}
}
/// 不安全:获得不上锁的对象引用
///
/// 这个只用于 [`PROCESSOR::run()`] 时使用
///
/// [`PROCESSOR::run()`]: crate::process::processor::Processor::run
pub unsafe fn unsafe_get(&self) -> &'static mut T {
let addr = &mut *self.0.lock() as *mut T;
&mut *addr
}
}
/// 释放时,先释放内部的 MutexGuard,再恢复 sstatus 寄存器
impl<'a, T> Drop for LockGuard<'a, T> {
fn drop(&mut self) {
self.guard.take();
unsafe { llvm_asm!("csrs sstatus, $0" :: "r"(self.sstatus & 2) :: "volatile") };
}
}
impl<'a, T> core::ops::Deref for LockGuard<'a, T> {
type Target = T;
fn deref(&self) -> &Self::Target {
self.guard.as_ref().unwrap().deref()
}
}
impl<'a, T> core::ops::DerefMut for LockGuard<'a, T> {
fn deref_mut(&mut self) -> &mut Self::Target {
self.guard.as_mut().unwrap().deref_mut()
}
}
execute the async task in serial order in android4.0
I have implemented the 2 asyn tasks, I am using android4.0. where one asyntask is executed continuously, second one is executed based on requirement(may be mulitpe times).
For example.
class AsynTask1 exetends AsyncTask<Void, Bitmap, Void>{
protected Void doInBackground(Void... params) {
while(true){
publishProgress(bmp);
}
}
}
class AsynTask2 extends AsyncTask<String, Void,Void>{
protected Void doInBackground(String... params){
System.out.println(params[0])
}
}
In activity class
class MainActivity extends Activity{
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
new AsynTask1().execute();
int i=0;
while(i<100)
{
if(i%2==0)
new AsynTask2().execute("no is even"+i);
i++
}
}
}
In the above case the AsynTask2 is not executed .
If tried with executeOnExecutor(AsyncTask.THREAD_POOL_Executor,params), then both asyntask are executed and I am getting the print messages from the AsynTask2, but those are not in order(like 0 2 6 4 10 8 12 14 ....).
Is there any way to execute the AsynTask1 continuously and AsynTask2 in Sequential order so that the order(like 0 2 4 6 8 10 12 14....) is prevented.
Thanks & Regards
mini.
ransportclose
* @emits score - (score: ProducerScore[])
* @emits videoorientationchange - (videoOrientation: ProducerVideoOrientation)
* @emits trace - (trace: ProducerTraceEventData)
* @emits @close
*/
constructor({ internal, data, channel, payloadChannel, appData, paused }: {
internal: any;
data: any;
channel: Channel;
payloadChannel: PayloadChannel;
appData?: any;
paused: boolean;
});
/**
* Producer id.
*/
get id(): string;
/**
* Whether the Producer is closed.
*/
get closed(): boolean;
/**
* Media kind.
*/
get kind(): MediaKind;
/**
* RTP parameters.
*/
get rtpParameters(): RtpParameters;
/**
* Producer type.
*/
get type(): ProducerType;
/**
* Consumable RTP parameters.
*
* @private
*/
get consumableRtpParameters(): RtpParameters;
/**
* Whether the Producer is paused.
*/
get paused(): boolean;
/**
* Producer score list.
*/
get score(): ProducerScore[];
/**
* App custom data.
*/
get appData(): any;
/**
* Invalid setter.
*/
set appData(appData: any);
/**
* Observer.
*
* @emits close
* @emits pause
* @emits resume
* @emits score - (score: ProducerScore[])
* @emits videoorientationchange - (videoOrientation: ProducerVideoOrientation)
* @emits trace - (trace: ProducerTraceEventData)
*/
get observer(): EnhancedEventEmitter;
/**
* Close the Producer.
*/
close(): void;
/**
* Transport was closed.
*
* @private
*/
transportClosed(): void;
/**
* Dump Producer.
*/
dump(): Promise;
/**
* Get Producer stats.
*/
getStats(): Promise;
/**
* Pause the Producer.
*/
pause(): Promise;
/**
* Resume the Producer.
*/
resume(): Promise;
/**
* Enable 'trace' event.
*/
enableTraceEvent(types?: ProducerTraceEventType[]): Promise;
/**
* Send RTP packet (just valid for Producers created on a DirectTransport).
*/
send(rtpPacket: Buffer): void;
private _handleWorkerNotifications;
}
//# sourceMappingURL=Producer.d.ts.map
state.runData.teams.push(teamData);
},
addNewPlayer(state, { teamID }): void {
const teamIndex = state.runData.teams.findIndex((team) => teamID === team.id);
if (teamIndex >= 0) {
const data = clone(defaultPlayer);
data.id = uuid();
data.teamID = teamID;
state.runData.teams[teamIndex].players.push(data);
}
},
removeTeam(state, { teamID }): void {
const teamIndex = state.runData.teams.findIndex((team) => teamID === team.id);
if (teamIndex >= 0) {
state.runData.teams.splice(teamIndex, 1);
}
},
removePlayer(state, { teamID, id }): void {
const teamIndex = state.runData.teams.findIndex((team) => teamID === team.id);
const playerIndex = (teamIndex >= 0)
? state.runData.teams[teamIndex].players.findIndex((player) => id === player.id) : -1;
if (teamIndex >= 0 && playerIndex >= 0) {
state.runData.teams[teamIndex].players.splice(playerIndex, 1);
}
},
},
actions: {
async saveRunData({ state }): Promise {
const noTwitchGame = await nodecg.sendMessage('modifyRun', {
runData: state.runData,
prevID: state.prevID,
updateTwitch: state.updateTwitch,
});
Vue.set(state, 'prevID', undefined);
Vue.set(state, 'updateTwitch', false);
return noTwitchGame;
},
},
});
Use of SET ROWCOUNT in SQL Server - Limiting result set
I have a sql statement that consists of multiple SELECT statements. I want to limit the total number of rows coming back to let's say 1000 rows. I thought that using the SET ROWCOUNT 1000 directive would do this...but it does not. For example:
SET ROWCOUNT 1000
select orderId from TableA
select name from TableB
My initial thought was that SET ROWCOUNT would apply to the entire batch, not the individual statements within it. The behavior I'm seeing is it will limit the first select to 1000 and then the second one to 1000 for a total of 2000 rows returned. Is there any way to have the 1000 limit applied to the batch as a whole?
Does Materialize CSS framework have a "container-fluid" equivalent?
I am creating a website for a friends band, and I decided it'd be a good time to learn a new mobile first framework.
One of the biggest things I see bands doing is adding full width images (example ), and I remembered reading this article about full-width rows in Bootstrap, and searched through Materialize's grid documentation, to no avail.
What I need is a way to create this "full width" row, ideally without breaking responsiveness. From my understanding, Bootstrap utilizes padding & margins in "container-fluid" (e.g., width: 100%;, padding: 0; margin: -15px;, where body I believe has a margin: 15px; padding: 15px;), which easily allows for the full-width rows, but Materiallize does not. Any help would be greatly appreciated, my design skills are not the best!
Permission issue with PostgreSQL in docker container
I'm trying to run a docker image with PostgreSQL that has a volume configured for persisting data.
docker-compose.yml
version: '3.1'
services:
db:
image: postgres
restart: always
volumes:
- ./data:/var/lib/postgresql/data
environment:
POSTGRES_PASSWORD: example
When I start the container I see the output
fixing permissions on existing directory /var/lib/postgresql/data ... ok
and the data folder is no longer readable for me.
If I elevate myself and access the data directory I can see that the files are there. Furthermore, the command ls -ld data gives me
drwx------ 19 systemd-coredump root 4096 May 17 16:22 data
I can manually set the directory permission with sudo chmod 755 data, but that only works until I restart the container.
Why does this happen, and how can I fix it?
Xframe option in tomcat 7
I have added the below code snippet in my tomcat web.xml to prevent clickjacking.
In the section to add built-in filter, I have added
<filter>
<filter-name>httpHeaderSecurity</filter-name>
<filter-class>org.apache.catalina.filters.HttpHeaderSecurityFilter</filter-class>
<init-param>
<param-name>antiClickJackingOption</param-name>
<param-value>SAMEORIGIN</param-value>
</init-param>
</filter>
For filter-mapping part I have added.
<filter-mapping>
<filter-name>httpHeaderSecurity</filter-name>
<url-pattern>/*</url-pattern>
<dispatcher>REQUEST</dispatcher>
</filter-mapping>
After editing and making these two changes,test page (html page where I am trying to open the target page in <frame>) passes (not able to open the target page inside frames).
But the apache welcome page gives 404 with the new changes.
Please let me know if I am missing anything.
Android Export aborted because fatal error were founds
I can't export signed or unsigned application package
*Export Aborted
Export aborted because fatal Lin error were founds. These are listed in the
problems view. Either fix these before running Export Again, or turn off "Run
full error check when exporting app" in the Android > Lint Error Cheking preference page.*
Solution :
Window>Preferences>Android>Lint Error Checking
uncheck Run full error check when exporting app
### User:
What's the difference between mmap and regular file reading? When should I prefer mmap for loading large model weights?
### Assistant:
Regular reading (`read()`) copies file data into a buffer you allocated: the kernel reads from disk into the page cache, then copies into your buffer. `mmap()` maps the file's pages directly into your address space — no second copy, and pages load lazily on first access (page fault), not upfront.
For large model weights mmap is usually right because: (1) you avoid doubling memory during load, (2) startup is nearly instant since nothing is read until accessed, (3) the OS can evict clean pages under memory pressure and transparently re-read them, which is what makes running models slightly larger than RAM possible at all.
Prefer plain reads when you need predictable latency (page faults mid-inference cause stalls), when the file sits on slow storage accessed randomly, or when you'll transform the data anyway and need a private mutable copy.
Gradle throw app:mergedebugresources exception
This project previously from intellij, now migrate to android studio as Gradle android project.
I wish to add google play service dependency using gradle later, I can't find specific jar elsewhere...
Previously this project was running fine using ant, after import as gradle in android studio, I get Gradle mergedebugresources exception.
I tried to rebuild project, sync project with gradle file, but didn't work for me... Am I missing something?
Hope someone guide me, I'm new to Gradle & android studio.
Executing tasks: [:app:generateDebugSources, :app:mockableAndroidJar, :app:prepareDebugUnitTestDependencies, :app:generateDebugAndroidTestSources]
Configuration on demand is an incubating feature.
Incremental java compilation is an incubating feature.
:app:preBuild UP-TO-DATE
:app:preDebugBuild UP-TO-DATE
:app:checkDebugManifest
:app:prepareDebugDependencies
:app:compileDebugAidl UP-TO-DATE
:app:compileDebugRenderscript UP-TO-DATE
:app:generateDebugBuildConfig UP-TO-DATE
:app:generateDebugResValues UP-TO-DATE
:app:generateDebugResources UP-TO-DATE
:app:mergeDebugResources
Error: java.util.concurrent.ExecutionException: com.android.ide.common.process.ProcessException:
:app:mergeDebugResources FAILED
FAILURE: Build failed with an exception.
What went wrong:
Execution failed for task ':app:mergeDebugResources'.
Error: java.util.concurrent.ExecutionException: com.android.ide.common.process.ProcessException:
Try:
Run with --info or --debug option to get more log output.
Exception is:
org.gradle.api.tasks.TaskExecutionException: Execution failed for task ':app:mergeDebugResources'.
at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.executeActions(ExecuteActionsTaskExecuter.java:69)
at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.execute(ExecuteActionsTaskExecuter.java:46)
at org.gradle.api.internal.tasks.execution.PostExecutionAnalysisTaskExecuter.execute(PostExecutionAnalysisTaskExecuter.java:35)
at org.gradle.api.internal.tasks.execution.SkipUpToDateTaskExecuter.execute(SkipUpToDateTaskExecuter.java:66)
at org.gradle.api.internal.tasks.execution.ValidatingTaskExecuter.execute(ValidatingTaskExecuter.java:58)
at org.gradle.api.internal.tasks.execution.SkipEmptySourceFilesTaskExecuter.execute(SkipEmptySourceFilesTaskExecuter.java:52)
at org.gradle.api.internal.tasks.execution.SkipTaskWithNoActionsExecuter.execute(SkipTaskWithNoActionsExecuter.java:52)
at org.gradle.api.internal.tasks.execution.SkipOnlyIfTaskExecuter.execute(SkipOnlyIfTaskExecuter.java:53)
at org.gradle.api.internal.tasks.execution.ExecuteAtMostOnceTaskExecuter.execute(ExecuteAtMostOnceTaskExecuter.java:43)
at org.gradle.execution.taskgraph.DefaultTaskGraphExecuter$EventFiringTaskWorker.execute(DefaultTaskGraphExecuter.j
How would I use ON DUPLICATE KEY UPDATE in my CodeIgniter model?
I have a CodeIgniter/PHP Model and I want to insert some data into the database.
However, I have this set in my 'raw' SQL query:
ON DUPLICATE KEY UPDATE duplicate=duplicate+1
I am using CodeIgniter and am converting all my previous in-controller SQL queries to ActiveRecord . Is there any way to do this from within the ActiveRecord-based model?
Thanks!
Jack
#!/usr/bin/env python
import csv
import os
import argparse
import dateutil.parser
import json
def parse_args():
parser = argparse.ArgumentParser()
parser.add_argument("-d", "--dir", type=str, required=True,
help="name of the data directory")
args = parser.parse_args()
return args.dir
def convert_ts(ts_str):
return dateutil.parser.parse(ts_str).timestamp()
def get_data(data, fname):
with open(fname, newline='') as csvfile:
content = csv.reader(csvfile, delimiter=',', quotechar='"')
for line in content:
if len(line) < 5:
continue
try:
ts = convert_ts(line[2])
adm = [line[1]]
if line[0] != '':
adm.append(line[0])
data.append(
{
'date': ts,
'adm': adm,
'infected': int(line[3]),
'deaths': int(line[4]),
'recovered': int(line[5]),
'sex': 'NaN', # Not sure why this is needed????
# 'source': 'JHU',
'source': ObjectId("5e75f8d7745bde4a48972b42")
})
except ValueError as ve:
# If there is a problem e.g. converting the ts
# just go on.
pass
def convert2json(dir_name):
data = []
for fname in os.listdir(dir_name):
get_data(data, os.path.join(dir_name, fname))
return data
def main():
dir_name = parse_args()
data = convert2json(dir_name)
print(json.dumps(data))
if __name__ == '__main__':
main()
Looping through the text file in typescript
I have read a local file flight.txt
1 DFW BOM 2016-05-20 12:20 2016-05-21 02:40 1084.00 JetAirways 100
2 DFW DEL 2016-04-24 17:15 2016-04-25 07:20 1234.00 Lufthansa 100
3 DFW FRA 2016-06-05 13:30 2016-06-05 03:32 674.00 AmericanAirlines 100
Code used to read a file in typescript.
populateFlightList() {
let data = fs.readFileSync('flight.txt').toString('utf-8'); {
let textByLine = data.split("\n")
console.log(textByLine);
};
now i want to loop and read from the file and parse data into flight objects
by creating a new object in each iteration and adding it to an arraylist.
try {
Scanner fin = new Scanner(file);
while(fin.hasNext()) {
int number = fin.nextInt(); //flight numer
String from = fin.next(); //Departure airport
String to = fin.next(); //Arrival airport
}**Code in Java**
how do i do this in typescript?
Serial.print(F("Waiting for NTP time sync: "));
time_t now = time(nullptr);
while (now < 8 * 3600 * 2) {
yield();
delay(500);
Serial.print(F("."));
now = time(nullptr);
}
Serial.println(F(""));
struct tm timeinfo;
gmtime_r(&now, &timeinfo);
Serial.print(F("Current time: "));
Serial.print(asctime(&timeinfo));
}
bool checkUpdate(int checkUpdateSW) {
const char* ServerSW;
String Data[3];
#if defined(ARDUINO_ARCH_ESP8266)
WiFiClient client;
// setUpdateClock();
// WiFiClientSecure client;
// BearSSL::WiFiClientSecure client;
// client.setCACert_P(rootCACertificate, strlen(rootCACertificate));
// Reading data over SSL may be slow, use an adequate timeout
// client.setInsecure();
// client.setFingerprint(HSfingerprint);
// client.setTimeout(12000); // 12 Seconds
#elif defined(ARDUINO_ARCH_ESP32)
setUpdateClock();
WiFiClientSecure client;
client.setCACert(rootCACertificate);
// Reading data over SSL may be slow, use an adequate timeout
client.setTimeout(12000);
#endif
HTTPClient https;
#if defined(ARDUINO_ARCH_ESP8266)
String latestJSONlink = "http://smogomierz.hs-silesia.pl/firmware/latest_esp8266.json";
#elif defined(ARDUINO_ARCH_ESP32)
String latestJSONlink = "https://smogomierz.hs-silesia.pl/firmware/latest_esp32.json";
#endif
if (https.begin(client, latestJSONlink)) {
delay(50);
int httpCode = https.GET();
//Serial.printf("GET... code: %d\n", httpCode);
if (httpCode > 0) {
// header has been send and Server response header has been handled
//Serial.printf("GET... code: %d\n", httpCode);
// file found at server
if (httpCode == HTTP_CODE_OK || httpCode == HTTP_CODE_MOVED_PERMANENTLY) {
String payload = https.getString();
delay(10);
/*
Serial.println(payload);
Serial.println(PMSENSORVERSION);
Serial.println(checkUpdateSW);
*/
StaticJsonDocument<400> jsonBuffer;
deserializeJson(jsonBuffer, payload);
JsonObject json = jsonBuffer.as();
if (checkUpdateSW == 0) {
ServerSW = json[PMSENSORVERSION];
} else if (checkUpdateSW == 1) {
ServerSW = json["PMS-SparkFunBME280"];
} else if (checkUpdateSW == 2) {
ServerSW = json["SDS"];
} else if (checkUpdateSW == 3) {
ServerSW = json["HPMA115S0"];
} else if (checkUpdateSW == 4) {
ServerSW = json["PMS"];
} else if (checkUpdateSW == 5) {
ServerSW = json["SPS30"];
} else if (checkUpdateSW >= 6) {
ServerSW = json[PMSENSORVERSION];
}
}
} else {
if (DEBUG) {
Serial.printf("GET... failed, error: %s\n", https.errorToString(httpCode).c_str());
}
}
} else {
if (DEBUG) {
Serial.print(F("Unable to connect\n"));
}
}
https.end();
strncpy(SERVERSOFTWAREVERSION, ServerSW, 32);
Data[0] = SERVERSOFTWAREVERSION;
// @ts-nocheck
import { RecipeInterface, User } from "../../emailpassword/types";
import { RecipeInterface as ThirdPartyEmailPasswordRecipeInterface } from "../types";
export default class RecipeImplementation implements RecipeInterface {
recipeImplementation: ThirdPartyEmailPasswordRecipeInterface;
constructor(recipeImplementation: ThirdPartyEmailPasswordRecipeInterface);
signUp: ({
email,
password,
}: {
email: string;
password: string;
}) => Promise<
| {
status: "OK";
user: User;
}
| {
status: "EMAIL_ALREADY_EXISTS_ERROR";
}
>;
signIn: ({
email,
password,
}: {
email: string;
password: string;
}) => Promise<
| {
status: "OK";
user: User;
}
| {
status: "WRONG_CREDENTIALS_ERROR";
}
>;
getUserById: ({ userId }: { userId: string }) => Promise;
getUserByEmail: ({ email }: { email: string }) => Promise;
createResetPasswordToken: ({
userId,
}: {
userId: string;
}) => Promise<
| {
status: "OK";
token: string;
}
| {
status: "UNKNOWN_USER_ID_ERROR";
}
>;
resetPasswordUsingToken: ({
token,
newPassword,
}: {
token: string;
newPassword: string;
}) => Promise<{
status: "OK" | "RESET_PASSWORD_INVALID_TOKEN_ERROR";
}>;
/**
* @deprecated
* */
getUsersOldestFirst: (_: {
limit?: number | undefined;
nextPaginationToken?: string | undefined;
}) => Promise;
/**
* @deprecated
* */
getUsersNewestFirst: (_: {
limit?: number | undefined;
nextPaginationToken?: string | undefined;
}) => Promise;
/**
* @deprecated
* */
getUserCount: () => Promise;
updateEmailOrPassword: (input: {
userId: string;
email?: string | undefined;
password?: string | undefined;
}) => Promise<{
status: "OK" | "EMAIL_ALREADY_EXISTS_ERROR" | "UNKNOWN_USER_ID_ERROR";
}>;
}
/**
* For either null or a value coming from `arb`
*
* @param arb - Arbitrary that will be called to generate a non null value
*
* @remarks Since 0.0.6
* @public
*/
function option(arb: Arbitrary): Arbitrary;
/**
* For either null or a value coming from `arb` with custom frequency
*
* @param arb - Arbitrary that will be called to generate a non null value
* @param freq - The probability to build a null value is of `1 / freq`
*
* @deprecated
* Superceded by `fc.option(arb, {freq})` - see {@link https://github.com/dubzzz/fast-check/issues/992 | #992}.
* Ease the migration with {@link https://github.com/dubzzz/fast-check/tree/main/codemods/unify-signatures | our codemod script}.
*
* @remarks Since 0.0.6
* @public
*/
function option(arb: Arbitrary, freq: number): Arbitrary;
/**
* For either nil or a value coming from `arb` with custom frequency
*
* @param arb - Arbitrary that will be called to generate a non nil value
* @param constraints - Constraints on the option
*
* @remarks Since 1.17.0
* @public
*/
function option(arb: Arbitrary, constraints: OptionConstraints): Arbitrary;
function option(arb: Arbitrary, constraints?: number | OptionConstraints): Arbitrary {
if (!constraints) return new OptionArbitrary(arb, 5, null as any);
if (typeof constraints === 'number') return new OptionArbitrary(arb, constraints, null as any);
return new OptionArbitrary(
arb,
constraints.freq == null ? 5 : constraints.freq,
Object.prototype.hasOwnProperty.call(constraints, 'nil') ? constraints.nil : (null as any)
);
}
export { option };
How to get generated ID after I inserted into a new data record in database using Spring JDBCTemplate?
I got a very common question when I was using Spring JDBCTemplate, I want to get the ID value after I inserted a new data record into database, this ID value will be referred to another related table. I tried the following way to insert it, but I always return 1 rather than its real unique ID. (I use MySQL as the database)
public int insert(BasicModel entity) {
String insertIntoSql = QueryUtil.getInsertIntoSqlStatement(entity);
log.info("SQL Statement for inserting into: " + insertIntoSql);
return this.jdbcTemplate.update(insertIntoSql);
}
#!/bin/bash -v
date
echo "$(date) === Start Cloud9 Bootstrapping" >> /tmp/bootstrap.log
REPOSITORY=https://github.com/mstfldmr/MachineHealthWorkshop
GG_LINK=https://d1onfpft10uf5o.cloudfront.net/greengrass-core/downloads/1.10.0/greengrass-linux-x86-64-1.10.0.tar.gz
GG_FILE=greengrass-linux-x86-64-1.10.0.tar.gz
GG_VER_CUR=1.10.0
export PATH=$PATH:/usr/local/bin
echo 'export PATH=$PATH:/usr/local/bin' >> /root/.bashrc
echo LANG=en_US.utf-8 >> /etc/environment
echo LC_ALL=en_US.UTF-8 >> /etc/environment
. /home/ec2-user/.bashrc
echo '=== Get repository ==='
echo "$(date) === Get repository" >> /tmp/bootstrap.log
cd /tmp
git clone ${REPOSITORY}
echo '=== Remove old software ==='
echo "$(date) === Remove old software" >> /tmp/bootstrap.log
yum -y remove aws-cli
yum -y install sqlite telnet jq strace tree gcc glibc-static python27-pip
echo '=== Install Python 2.7 and some packages ==='
echo "$(date) === Install Python 2.7 and some packages" >> /tmp/bootstrap.log
# python27
for l in boto3 awscli AWSIoTPythonSDK AWSIoTDeviceDefenderAgentSDK \
greengrasssdk urllib3 geopy pyOpenSSL pandas
do
pip install $l
done
pip install --upgrade python-daemon
echo '=== Install Python 3.7 and some packages ==='
echo "$(date) === Install Python 3.7 and some packages" >> /tmp/bootstrap.log
yum -y install gcc bzip2-devel ncurses-devel gdbm-devel xz-devel \
sqlite-devel openssl-devel tk-devel uuid-devel \
readline-devel zlib-devel libffi-devel
test ! -d /usr/local/src && mkdir -p /usr/local/src
cd /usr/local/src
cp /tmp/MachineHealthWorkshop/resources/python37-compiled.tar.gz ./
tar zxf python37-compiled.tar.gz
cd Python-3.7.0/
make install
echo "/usr/local/lib" > /etc/ld.so.conf.d/local.conf
ldconfig
cd /tmp/
/usr/local/bin/pip3 install --upgrade pip
for l in boto3 awscli AWSIoTPythonSDK AWSIoTDeviceDefenderAgentSDK \
greengrasssdk urllib3 geopy pyOpenSSL pandas
do
/usr/local/bin/pip3 install $l
done
/usr/local/bin/pip3 install --upgrade python-daemon
echo '=== Install NodeJS ==='
echo "$(date) === Install NodeJS" >> /tmp/bootstrap.log
rm -rf /home/ec2-user/.nvm
curl -sL https://rpm.nodesource.com/setup_10.x | sudo bash -
yum -y install nodejs
ln -s /usr/bin/node /usr/bin/nodejs8.10
echo '=== Configure awscli and environment variables ==='
echo "$(date) === Configure awscli and environment variables" >> /tmp/bootstrap.log
Displaying a tree in ASCII
As a time-pass activity, I decided to implement a Tree (like) structure in python.
I implemented a Node class (which alone serves the purpose here) like so:
class Node:
def __init__(self, name, parent, *data):
self.name = name
self.parent = parent
self.data = data
self.children = []
self.is_root = False
def __repr__(self):
return 'Node '+repr(self.name)
def dic(self):
retval = {self:[]}
for i in self.children:
retval[self].append(i.dic())
return retval
def display(self): # Here
pass
def has_children(self):
return bool(self.children)
def get_parent(self):
return self.parent
def add_child(self, name, *data):
child = Node(name, self,*data)
self.children.append(child)
return child
As you can see the display function is not implemented.
Here's an example tree.
A = Node('A',Node)
A.is_root = True
B = A.add_child('B')
D = B.add_child('D')
C = A.add_child('C')
E = C.add_child('E')
F = C.add_child('F')
G = C.add_child('G')
Here's some sample output for display.
>>> A.display()
A
+-^-+
B C
| +-+-+
D E F G
>>> C.display()
C
+-+-+
E F G
In the shortest form,
How can I "build" an ASCII tree (like above) from the Node class??
In a longer form,
The "Logic" of printing is:
When there is only one child, | is put above the child. (D)
Else, Every child has a + above it, (B,C,E,F)
When there are even no. of children, ^ is put below the parent. (A)
Else, (there are odd no. of children) + is put below the parent. (C)
I have been thinking of starting from below.
I realized that there has to be a call to the each of the children, but have been unable to implement anything (of that sorts or otherwise) that gave anything close to it.
/*
Package hub provides primitives for working with the publish-subscribe messaging model.
All the types are Go channels, so the usage is identical to theirs.
The pattern is simple: publish messages to given topics. To do this a series of commands
are sent to the Hub, which is a plain channel, commands that are executed afterwards. Most
commands take topics as parameters, but if the topics are not specified a default topic
(a topic identified by the nil interface) is used.
*/
package hub
type (
// Hub is the coordinator channel on which commands are sent. Even though in general
// channels don't have to be closed, the Hub must be, or resources will be leaked otherwise.
Hub chan interface{}
// Conn is a connection. It is a channel on which the Hub sends messages
// from each Topic the Conn is connected to.
//
// Message a Conn as a command and the Hub will connect it to the default topic.
Conn chan interface{}
// Topic is an identifier for a topic.
Topic interface{}
// Number is an alias for int. If a struct field of a command that manipulates a connections has this type,
// it means that the first time the command is sent negative values are ignored,
// and on subsequent times negative values do not reset specific properties of
// the connections that the respective values manipulate.
Number = int
// TopicConn represents a connection to a topic. Use it with ConnectEach
// to describe how the connection connects to topics.
TopicConn struct {
Topic Topic
// The number of messages the connection should receive from the given topic.
// If the ConnectEach command is sent multiple times for the same connection,
// the number of messages is reset to the new value.
MessageCount Number
}
Cannot start wcf service host
I'm trying to create a service host for my WCF application. When I start the app I get an error saying
The service cannot be started. This service has no endpoint defined.
Please add at least one endpoint for the service in config file and
try again.
I followed the tutorial on PluralSight and this is the code I came up with
using System.ServiceModel;
using FreedomService;
namespace ConsoleHost
{
class Program
{
static void Main(string[] args)
{
var host = new ServiceHost(typeof(PeopleService));
host.AddServiceEndpoint(typeof (IPeopleService), new BasicHttpBinding(),
"http://localhost:8080/people/basic");
host.AddServiceEndpoint(typeof(IPeopleService), new WSHttpBinding(),
"http://localhost:8080/people/ws");
host.AddServiceEndpoint(typeof(IPeopleService), new NetTcpBinding(),
"net.tcp://localhost:8081/people");
try
{
host.Open();
PrintServiceInfo(host);
Console.ReadLine();
host.Close();
}
catch (Exception e)
{
Console.WriteLine(e);
host.Abort();
}
}
static void PrintServiceInfo(ServiceHost host)
{
Console.WriteLine("{0} is up and running with these endpoints:",host.Description.ServiceType);
foreach (var endpoint in host.Description.Endpoints)
{
Console.WriteLine(endpoint.Address);
}
}
}
}
IPeopleService.cs
[ServiceContract]
public interface IPeopleService
{
[OperationContract]
string GetData(int value);
[OperationContract]
PersonType GetPersonById(int id);
}
PeopleService.cs
public class PeopleService : IPeopleService, IDisposable
{
private ICollection<PersonType> People = new Collection<PersonType>
{
//...
};
public string GetData(int value)
{
return string.Format("You entered: {0}", value);
}
public PersonType GetPersonById(int id)
{
var person = People.First(p => p.Id == id);
if (person!= null)
return person;
throw new InvalidDataException(string.Format("No Person with the id: {0} found.",id));
}
public void Dispose()
{
this.People = null;
}
}
app.config
import numpy as np
from numpy import (reciprocal, einsum, maximum, minimum, zeros_like,
atleast_1d, squeeze)
from scipy.linalg import eig, eigvals, matrix_balance, norm
from harold._classes import Transfer, transfer_to_state
from harold._discrete_funcs import discretize
from harold._arg_utils import _check_for_state, _check_for_state_or_transfer
__all__ = ['simulate_linear_system', 'simulate_step_response',
'simulate_impulse_response']
def simulate_linear_system(sys, u, t=None, x0=None, per_channel=False):
"""
Compute the linear model response to an input array sampled at given time
instances.
Parameters
----------
sys : {State, Transfer}
The system model to be simulated
u : array_like
The real-valued input sequence to force the model. 1D arrays for single
input models and 2D arrays that has as many columns as the number of
inputs are valid inputs.
t : array_like, optional
The real-valued sequence to be used for the evolution of the system.
The values should be equally spaced otherwise an error is raised. For
discrete time models increments different than the sampling period also
raises an error. On the other hand for discrete models this can be
omitted and a time sequence will be generated automatically.
x0 : array_like, optional
The initial condition array. If omitted an array of zeros is assumed.
Note that Transfer models by definition assume zero initial conditions
and will raise an error.
per_channel : bool, optional
If this is set to True and if the system has multiple inputs, the
response of each input is returned individually. For example, if a
system has 4 inputs and 3 outputs then the response shape becomes
(num, p, m) instead of (num, p) where k-th slice (:, :, k) is the
response from the k-th input channel. For single input systems, this
keyword has no effect.
Returns
-------
yout : ndarray
The resulting response array. The array is 1D if sys is SISO and
has p columns if sys has p outputs.
tout : ndarray
The time sequence used in the simulation. If the parameter t is not
None then a copy of t is given.
Notes
-----
For Transfer models, first conversion to a state model is performed and
then the resulting model is used for computations.
"""
_check_for_state_or_transfer(sys)
-- Organiation role rights
create table o_org_role_to_right (
id number(20) generated always as identity,
creationdate timestamp not null,
o_role varchar(255) not null,
o_right varchar(255) not null,
fk_organisation number(20) not null,
primary key (id)
);
alter table o_org_role_to_right add constraint org_role_to_right_to_org_idx foreign key (fk_organisation) references o_org_organisation (id);
create index idx_org_role_to_r_to_org_idx on o_org_role_to_right(fk_organisation);
-- Lectures
alter table o_lecture_reason add l_enabled number default 1 not null;
-- Absences
alter table o_lecture_absence_category add l_enabled number default 1 not null;
-- Contact tracing
create table o_ct_location (
id number(20) generated always as identity,
creationdate date not null,
lastmodified date not null,
l_reference varchar2(255),
l_titel varchar2(255),
l_room varchar2(255),
l_building varchar2(255),
l_sector varchar2(255),
l_table varchar2(255),
l_qr_id varchar2(255) not null,
l_qr_text varchar2(4000),
l_guests number default 1 not null,
l_printed number default 0 not null,
unique(l_qr_id),
primary key (id)
);
create table o_ct_registration (
id number(20) generated always as identity,
creationdate date not null,
l_deletion_date date not null,
l_start_date date not null,
l_end_date date,
l_nick_name varchar2(255),
l_first_name varchar2(255),
l_last_name varchar2(255),
l_street varchar2(255),
l_extra_line varchar2(255),
l_zip_code varchar2(255),
l_city varchar2(255),
l_email varchar2(255),
l_institutional_email varchar2(255),
l_generic_email varchar2(255),
l_private_phone varchar2(255),
l_mobile_phone varchar2(255),
l_office_phone varchar2(255),
fk_location number(20) not null,
primary key (id)
);
alter table o_ct_registration add constraint reg_to_loc_idx foreign key (fk_location) references o_ct_location (id);
create index idx_reg_to_loc_idx on o_ct_registration (fk_location);
// Copyright (c) 2011-2014 The Bitcoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "sendcoinsdialog.h"
#include "ui_sendcoinsdialog.h"
#include "addresstablemodel.h"
#include "bitcoinunits.h"
#include "coincontroldialog.h"
#include "guiutil.h"
#include "optionsmodel.h"
#include "sendcoinsentry.h"
#include "walletmodel.h"
#include "base58.h"
#include "coincontrol.h"
#include "ui_interface.h"
#include
#include
#include
SendCoinsDialog::SendCoinsDialog(QWidget *parent) :
QDialog(parent),
ui(new Ui::SendCoinsDialog),
model(0)
{
ui->setupUi(this);
#ifdef Q_OS_MAC // Icons on push buttons are very uncommon on Mac
ui->addButton->setIcon(QIcon());
ui->clearButton->setIcon(QIcon());
ui->sendButton->setIcon(QIcon());
#endif
GUIUtil::setupAddressWidget(ui->lineEditCoinControlChange, this);
addEntry();
connect(ui->addButton, SIGNAL(clicked()), this, SLOT(addEntry()));
connect(ui->clearButton, SIGNAL(clicked()), this, SLOT(clear()));
// Coin Control
connect(ui->pushButtonCoinControl, SIGNAL(clicked()), this, SLOT(coinControlButtonClicked()));
connect(ui->checkBoxCoinControlChange, SIGNAL(stateChanged(int)), this, SLOT(coinControlChangeChecked(int)));
connect(ui->lineEditCoinControlChange, SIGNAL(textEdited(const QString &)), this, SLOT(coinControlChangeEdited(const QString &)));
Maria Sorvillo is an Italian football defender, currently playing for UPC Tavagnacco in Italy's Serie A. She has won five leagues with SS Lazio, CF Bardolino and Torres CF.
She has been a member of the Italian national team.
References
1982 births
Living people
Italian women's footballers
Italy women's international footballers
Serie A (women's football) players
SS Lazio Women 2015 players
Torres Calcio Femminile players
A.S.D. AGSM Verona F.C. players
ASD UPC Tavagnacco players
Women's association football defenders
Torino Women A.S.D. players
Roma CF players
People from Aversa
Footballers from the Province of Caserta
__all__ = ("group_attempts", "fails_filter", "reduce_to_failures",)
def group_attempts(sequence, filter_func=None):
if filter_func is None:
filter_func = lambda x:True
last, l = None, []
for x in sequence:
if isinstance(x, tuple) and x[0] == 'inspecting':
if l:
yield last, l
last, l = x[1], []
elif last is not None:
if filter_func(x):
# inline ignored frames
if getattr(x, 'ignored', False):
l.extend(y for y in x.events if filter_func(y))
else:
l.append(x)
if l:
yield last, l
def fails_filter(x):
if not isinstance(x, tuple):
return not x.succeeded
if x[0] == "viable":
return not x[1]
return x[0] != "inspecting"
def reduce_to_failures(frame):
if frame.succeeded:
return []
l = [frame]
for pkg, nodes in group_attempts(frame.events, fails_filter):
l2 = []
for x in nodes:
if not isinstance(x, tuple):
l2.append(reduce_to_failures(x))
else:
l2.append(x)
l.append((pkg, l2))
return l
Nested classes' scope?
I'm trying to understand scope in nested classes in Python. Here is my example code:
class OuterClass:
outer_var = 1
class InnerClass:
inner_var = outer_var
The creation of class does not complete and I get the error:
<type 'exceptions.NameError'>: name 'outer_var' is not defined
Trying inner_var = Outerclass.outer_var doesn't work.
I get:
<type 'exceptions.NameError'>: name 'OuterClass' is not defined
I am trying to access the static outer_var from InnerClass.
Is there a way to do this?
How to add TemplateField to a gridview in the code behind?
I have a DropDownList which has a list of tables. Under it there is GridView . Based on the table selected from the drop down list box, I will populate the GridView dynamically. Since the tables could have different column names, I need to create the template field for the GridView dynamically.
Following is my bind method. I have two problems:
I couldn’t wrap the binding part in if (!IsPostBack) since the GridView is populated based on the selection of the DropDownList, so everytime I change the selection, the columns will be duplicated.
And I don’t have any data, I think I need to set ItemTemplate of the tField (TemplateField), but how do I do that?
My bind method
private void BindGridView()
{
DataSet ds = new DataSet();
try
{
ds = …
if (ds.Tables.Count > 0)
{
foreach (DataColumn dc in ds.Tables[0].Columns)
{
TemplateField tField = new TemplateField();
tField.HeaderText = dc.ColumnName;
GridView2.Columns.Add(tField);
}
GridView2.DataSource = ds.Tables[0];
GridView2.DataBind();
}
else
{
…
}
}
catch (Exception ex)
{
…
}
}
begin_unit|revision:0.9.5;language:Java;cregit-version:0.0.1
begin_comment
comment|/** * 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. */
end_comment
begin_package
package|package
name|org
operator|.
name|apache
operator|.
name|activemq
operator|.
name|advisory
package|;
end_package
begin_import
import|import
name|org
operator|.
name|apache
operator|.
name|activemq
operator|.
name|broker
operator|.
name|region
operator|.
name|virtual
operator|.
name|CompositeDestination
import|;
end_import
begin_import
import|import
name|org
operator|.
name|apache
operator|.
name|activemq
operator|.
name|broker
operator|.
name|region
operator|.
name|virtual
operator|.
name|VirtualDestination
import|;
end_import
begin_import
import|import
name|org
operator|.
name|apache
operator|.
name|activemq
operator|.
name|broker
operator|.
name|region
operator|.
name|virtual
operator|.
name|VirtualTopic
import|;
end_import
begin_import
import|import
name|org
operator|.
name|apache
operator|.
name|activemq
operator|.
name|command
operator|.
name|ActiveMQDestination
import|;
end_import
begin_import
import|import
name|org
operator|.
name|apache
operator|.
name|activemq
operator|.
name|command
operator|.
name|ActiveMQQueue
import|;
end_import
begin_import
import|import
name|org
operator|.
name|apache
operator|.
name|activemq
operator|.
name|filter
operator|.
name|DestinationFilter
import|;
end_import
begin_comment
comment|/** * This class will use a destination filter to see if the activeMQ destination matches * the given virtual destination * */
end_comment
Higher order functions in C
Is there a "proper" way to implement higher order functions in C.
I'm mostly curious about things like portability and syntax correctness here and if there are more than one ways what the merits and flaws are.
Edit:
The reason I want to know how to create higher order functions are that I have written a system to convert PyObject lists (which you get when calling python scripts) into a list of C structures containing the same data but organized in a way not dependant on the python.h libraries. So my plan is to have a function which iterates through a pythonic list and calls a function on each item in the list and places the result in a list which it then returns.
So this is basically my plan:
typedef gpointer (converter_func_type)(PyObject *)
gpointer converter_function(PyObject *obj)
{
// do som stuff and return a struct cast into a gpointer (which is a void *)
}
GList *pylist_to_clist(PyObject *obj, converter_func_type f)
{
GList *some_glist;
for each item in obj
{
some_glist = g_list_append(some_glist, f(item));
}
return some_glist;
}
void some_function_that_executes_a_python_script(void)
{
PyObject *result = python stuff that returns a list;
GList *clist = pylist_to_clist(result, converter_function);
}
And to clearify the question: I want to know how to do this in safer and more correct C. I would really like to keep the higher order function style but if that is frowned upon I greatly appreciate ways to do this some other way.
mod get;
mod utils;
use async_std::task;
use chrono::{Duration, NaiveDate, NaiveDateTime, NaiveTime, Weekday};
use get::get_html;
use scraper::{Html, Selector};
use std::error::Error;
use std::str::FromStr;
use tide::{http::Mime, Request, Response, StatusCode};
use utils::{get_period_time, parse_list_uint, parse_weekday, to_ics};
use std::collections::HashMap;
fn main() {
task::block_on(async {
let mut app = tide::new();
app.at("/").get(|_| async {
let mut res = Response::new(StatusCode::Accepted);
res.set_content_type(tide::http::mime::HTML);
res.set_body(include_str!("index.html"));
Ok(res)
});
app.at("/ics/*").get(|req: Request<()>| async move {
let info: String = req.url().path().replace("/ics/", "");
if info.find('_').is_some() {
let vec = info.split('_').collect::>();
let content = process(&vec[0].to_uppercase(), &vec[1]).await;
let content = to_ics(content.unwrap_or(Vec::new()));
let mut res = Response::new(StatusCode::Accepted);
res.set_content_type(Mime::from_str("text/calendar").unwrap());
res.set_body(content);
Ok(res)
} else {
Ok("Example CT010101_Passwd".into())
}
});
app.at("/json/*").get(|req: Request<()>| async move {
let path = req.url().path().replace("/json/", "");
let (usr, pwd) = path.split_at(path.find('/').unwrap_or(0));
let pwd: String = pwd[1..].to_string();
let vec = process(&usr.to_uppercase(), &pwd).await.unwrap_or(Vec::new());
let doc = vec.iter()
.map(|dat| dat.to_map())
.collect::>>();
let mut res = Response::new(StatusCode::Accepted);
res.set_content_type(Mime::from_str("application/json")?);
res.set_body(tide::Body::from_json(&doc)?);
Ok(res)
});
let port = std::env::var("PORT").unwrap_or("8080".to_string());
app.listen(format!("0.0.0.0:{}", port)).await.unwrap();
});
}
async fn process(usr: &str, pwd: &str)
-> Result, Box>
{
let vec = parse_html(get_html(usr, pwd).await?)?;
Ok(vec.iter()
.map(|(cl, ts, ps)| Data::parse(cl, ts, ps))
.flatten()
.collect())
}
#[derive(Debug)]
pub struct Data {
class: String,
time_begin: NaiveDateTime,
time_end: NaiveDateTime,
place: String,
}
# 返回D^{-0.5}SD^{-0.5}的coords, data, shape,其中S=A+I
adj_norm = preprocess_graph(adj)
adj_label = adj_train + sp.eye(adj_train.shape[0])
# adj_label = sparse_to_tuple(adj_label)
adj_label = torch.FloatTensor(adj_label.toarray()).to(DEVICE)
'''
注意,adj的每个元素非1即0。pos_weight是用于训练的邻接矩阵中负样本边(既不存在的边)和正样本边的倍数(即比值),这个数值在二分类交叉熵损失函数中用到,
如果正样本边所占的比例和负样本边所占比例失衡,比如正样本边很多,负样本边很少,那么在求loss的时候可以提供weight参数,将正样本边的weight设置小一点,负样本边的weight设置大一点,
此时能够很好的平衡两类在loss中的占比,任务效果可以得到进一步提升。参考:https://www.zhihu.com/question/383567632
负样本边的weight都为1,正样本边的weight都为pos_weight
'''
pos_weight = float(adj.shape[0] * adj.shape[0] - num_edges) / num_edges
norm = adj.shape[0] * adj.shape[0] / float((adj.shape[0] * adj.shape[0] - adj.sum()) * 2)
# create model
print('create model ...')
model = NHGATModelGAN(num_features, hidden_dim1=hidden_dim1, hidden_dim2=hidden_dim2, hidden_dim3=hidden_dim3, num_heads=num_heads, dropout=dropout, alpha=alpha, vae_bool=vae_bool)
# define optimizer
if optimizer_name == 'adam':
optimizer = define_optimizer.define_optimizer_adam(model, lr=lr, weight_decay=weight_decay)
elif optimizer_name == 'adamw':
optimizer = define_optimizer.define_optimizer_adamw(model, lr=lr, weight_decay=weight_decay)
elif optimizer_name == 'sgd':
optimizer = define_optimizer.define_optimizer_sgd(model, lr=lr, momentum=momentum,
weight_decay=weight_decay)
elif optimizer_name == 'adagrad':
optimizer = define_optimizer.define_optimizer_adagrad(model, lr=lr, lr_decay=lr_decay,
weight_decay=weight_decay)
elif optimizer_name == 'rmsprop':
optimizer = define_optimizer.define_optimizer_rmsprop(model, lr=lr, weight_decay=weight_decay,
momentum=momentum)
elif optimizer_name == 'adadelta':
optimizer = define_optimizer.define_optimizer_adadelta(model, lr=lr, weight_decay=weight_decay)
else:
raise NameError('No define optimization function name!')
Apache Camel failed to create endpoint
I'm new on Apache Camel and I need to integrate it with Apache ActiveMQ.
I tried a basic example, I installed on my computer FileZilla Server and ActiveMQ (works both) and I want to copy a file from the local server to the JMS queue that I created in Active MQ; the problem is that the method start() of CamelContext throws org.apache.camel.FailedToCreateRouteException
Here is my code (the address in ftpLocation is the static address of my computer):
import javax.jms.ConnectionFactory;
import org.apache.activemq.ActiveMQConnection;
import org.apache.activemq.ActiveMQConnectionFactory;
import org.apache.camel.CamelContext;
import org.apache.camel.Exchange;
import org.apache.camel.Processor;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.component.jms.JmsComponent;
import org.apache.camel.impl.DefaultCamelContext;
public class FtpToJmsExample
{
private static String url = ActiveMQConnection.DEFAULT_BROKER_URL;
private static String ftpLocation = "ftp://192.168.1.10/incoming?username=Luca&password=Luca";
public void start() throws Exception
{
CamelContext context = new DefaultCamelContext();
ConnectionFactory connectionFactory = new ActiveMQConnectionFactory(url);
context.addComponent("jms", JmsComponent.jmsComponentAutoAcknowledge(connectionFactory));
context.addRoutes(
new RouteBuilder() {
public void configure()
{
from(ftpLocation).
process(executeFirstProcessor()).
to("jms:TESTQUEUE");
}
});
System.out.println("START");
context.start();
System.out.println("wait");
System.out.println(loaded);
Thread.sleep(3000);
while (loaded == false)
{
System.out.println("in attesa\n");
}
context.stop();
System.out.println("stop context!");
System.out.println(loaded);
}
public static void main(String args[]) throws Exception
{
FtpToJmsExample example = new FtpToJmsExample();
example.start();
}
private Processor executeFirstProcessor()
{
return new Processor() {
@Override
public void process(Exchange exchange)
{
System.out.println("We just downloaded : "+
exchange.getIn().getHeader("CamelFileName"));
loaded = true;
}
};
}
}
This is the POM.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
Dynamic choices field in Django Models
My models.py:
SHOP1_CHOICES = (
('Food Court', 'Food Court'),
('KFC', 'KFC'),
)
SHOP2_CHOICES = (
('Sports Arena', 'Sports Arena'),
('Disco D', 'Disco D'),
)
SHOP3_CHOICES = (
('Bowling Arena', 'Bowling Arena'),
('Cinemax', 'Cinemax'),
)
class Feed(models.Model):
gender = models.CharField(max_length=5, choices=GENDER_CHOICES, default='girl')
name =models.CharField(max_length=25)
shop=models.CharField(max_length=20)
location=models.CharField(max_length=25, choices=SHOP1_CHOICES)
Here if Feed.shop == 'shop1' I want to load SHOP1_CHOICES on Feed.location. Currently irrespective of what shop, it just displays the SHOP1_CHOICES (no surprise).How can I implement it? I am stuck, please help.
Failed to load resource: the server responded with a status of 404 (NOT FOUND)
I am uisng python,To display data from json file to a page,i am getting the below errors
Failed to load resource: the server responded with a status of 404 (NOT FOUND) http://localhost:8000/static/script/jquery-1.9.1.min.js
Failed to load resource: the server responded with a status of 404 (NOT FOUND) http://localhost:8000/static/script/myscript.js
myscript.js file
$("#button").click(function(){
$.getJSON("item.json",function(obj){
$.each(obj,function(key,value){
$("ul").append("<li>+value.item1+"</li>");
$("ul").append("<li>+value.item2+"</li>");
$("ul").append("<li>+value.item3+"</li>");
});
});
});
.json file is
{
"p1":{
"item1":"apple",
"item2":"orange",
"item3":"banana",
},
"p2":{
"item1":"water",
"item2":"milk",
"item3":"alcohol",
}
}
template is
<html>
<head>
<body>
<ul></ul>
<button></button>
<script src="script/jquery-1.9.1,min.js" type="text/javascript"></script>
<script src="script/myscript.js" type="text/javascript"></script>
</body>
</head>
</html>
1).js file is in my project folder and path also setted.
2).I am not doing any query in my views.py,as i am new to this i am confused with this.So any codings need to perform in the views.py for fetching the data from json.
3).Not able to sort out the above errors,please provide me the possible reason so that i can run this function.
Thanks
// Copyright (C) 2017 The Android Open Source Project
//
// 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.gerrit.server.index.group;
import com.google.common.collect.ImmutableSet;
import com.google.gerrit.index.IndexConfig;
import com.google.gerrit.index.query.FieldBundle;
import com.google.gerrit.reviewdb.client.AccountGroup;
import com.google.gerrit.reviewdb.client.RefNames;
import com.google.gerrit.server.config.AllUsersName;
import com.google.gerrit.server.git.GitRepositoryManager;
import com.google.inject.Inject;
import com.google.inject.Singleton;
import java.io.IOException;
import java.util.Optional;
import org.eclipse.jgit.lib.ObjectId;
import org.eclipse.jgit.lib.Ref;
import org.eclipse.jgit.lib.Repository;
/**
* Checks if documents in the group index are stale.
*
* An index document is considered stale if the stored SHA1 differs from the HEAD SHA1 of the
* groups branch.
*
*
Note: This only applies to NoteDb.
*/
@Singleton
public class StalenessChecker {
public static final ImmutableSet FIELDS =
ImmutableSet.of(GroupField.UUID.getName(), GroupField.REF_STATE.getName());
private final GroupIndexCollection indexes;
private final GitRepositoryManager repoManager;
private final IndexConfig indexConfig;
private final AllUsersName allUsers;
@Inject
StalenessChecker(
GroupIndexCollection indexes,
GitRepositoryManager repoManager,
IndexConfig indexConfig,
AllUsersName allUsers) {
this.indexes = indexes;
this.repoManager = repoManager;
this.indexConfig = indexConfig;
this.allUsers = allUsers;
}
public boolean isStale(AccountGroup.UUID uuid) throws IOException {
GroupIndex i = indexes.getSearchIndex();
if (i == null) {
return false; // No index; caller couldn't do anything if it is stale.
}
Optional result =
i.getRaw(uuid, IndexedGroupQuery.createOptions(indexConfig, 0, 1, FIELDS));
if (!result.isPresent()) {
// The document is missing in the index.
try (Repository repo = repoManager.openRepository(allUsers)) {
Ref ref = repo.exactRef(RefNames.refsGroups(uuid));
// Stale if the group actually exists.
return ref != null;
}
}
### User:
my tauri app fails to build on windows: LINK : fatal error LNK1181: cannot open input file 'WebView2Loader.dll.lib'
### Assistant:
Classic WebView2 linking issue with Tauri on Windows. Usually one of these fixes it:
1. Make sure the Microsoft Edge WebView2 Runtime is installed, plus the "C++ Build Tools" workload in Visual Studio Installer (you need the MSVC toolchain, not MinGW).
2. Clear the build cache: delete `src-tauri/target` and rebuild — a stale artifact from an older `webview2-com-sys` often lingers there.
3. Check that Rust targets MSVC: `rustup default stable-x86_64-pc-windows-msvc`.
4. In CI, confirm the runner is `windows-latest` and consider the `webview2-com/static` feature in Cargo.toml for static linking.
Most of the time it's #2: a poisoned target cache after a toolchain update.
# Estimation of the variance when sigma2 is unspecified
if sigma2 is None:
xubar = (1 + tauubar) * (1 + alpha / tauubar)
eH_ub = int(np.min([np.ceil(L / (1 + alpha)) - 1, H])) - 1
# upper_bound = (np.sum(s**2)+residual)/(L*M)
# lower_bound = np.max(
# [s[eH_ub+1]**2/(M*xubar), np.mean(s[eH_ub+1:]**2)/M])
upper_bound = (torch.sum(s**2) + residual) / (L * M)
lower_bound = torch.max(torch.stack(
[s[eH_ub + 1]**2 / (M * xubar), torch.mean(s[eH_ub + 1:]**2) / M], dim=0))
scale = 1. # /lower_bound
s = s * np.sqrt(scale)
residual = residual * scale
lower_bound = lower_bound * scale
upper_bound = upper_bound * scale
sigma2_opt = minimize_scalar(
EVBsigma2, args=(L, M, s.cpu().numpy(), residual, xubar),
bounds=[lower_bound.cpu().numpy(), upper_bound.cpu().numpy()],
method='Bounded')
sigma2 = sigma2_opt.x
# Threshold gamma term
threshold = np.sqrt(M * sigma2 * (1 + tauubar) * (1 + alpha / tauubar))
# pos = np.sum(s > threshold)
pos = torch.sum(s > threshold)
# Formula (15) from [2]
# d = torch.multiply(s[:pos]/2,
# 1-torch.divide(
# torch.tensor((L+M)*sigma2, device=s.device),
# s[:pos]**2) + torch.sqrt((1-torch.divide(
# torch.tensor(
# (L+M)*sigma2, device=s.device),
# s[:pos]**2))**2 -
# 4*L*M*sigma2**2/s[:pos]**4))
# d = np.multiply(s[:pos]/2, 1-np.divide((L+M)*sigma2, s[:pos]**2) + np.sqrt(
# (1-np.divide((L+M)*sigma2, s[:pos]**2))**2 - 4*L*M*sigma2**2/s[:pos]**4))
d = (s[:pos] / 2) * (1 - (L + M) * sigma2 / s[:pos]**2
+ torch.sqrt((1 -
(L + M) * sigma2 / s[:pos]**2)**2 - 4 * L * M * sigma2**2 / s[:pos]**4))
# Computation of the posterior
# post = {}
# post['ma'] = np.zeros(H)
# post['mb'] = np.zeros(H)
# post['sa2'] = np.zeros(H)
# post['sb2'] = np.zeros(H)
# post['cacb'] = np.zeros(H)
# tau = np.multiply(d, s[:pos])/(M*sigma2)
# delta = np.multiply(np.sqrt(np.divide(M*d, L*s[:pos])), 1+alpha/tau)
# post['ma'][:pos] = np.sqrt(np.multiply(d, delta))
# post['mb'][:pos] = np.sqrt(np.divide(d, delta))
# post['sa2'][:pos] = np.divide(sigma2*delta, s[:pos])
# post['sb2'][:pos] = np.divide(sigma2, np.multiply(delta, s[:pos]))
# post['cacb'][:pos] = np.sqrt(np.multiply(d, s[:pos])/(L*M))
# post['sigma2'] = sigma2
# post['F'] = 0.5*(L*M*np.log(2*np.pi*sigma2) +
# (residual+np.sum(s**2))/sigma2 + np.sum(
# M*np.log(tau+1) + L*np.log(tau/alpha + 1) - M*tau))
return U[:, :pos], torch.diag(d), V[:, :pos] # , post
def EVBsigma2(sigma2, L, M, s, residual, xubar):
H = len(s)
alpha = L / M
x = s**2 / (M * sigma2)
SSIS (ASCII needed): "Code page is 1252 and is required to be 20127"
I have a requirement to export a database to a tab-delimited file in the ASCII format. I am using derived columns to convert any Unicode strings to non-Unicode strings. For example, a former Unicode text stream is now casted as this:
(DT_TEXT,20127)incomingMessage
But SSIS is still looking for ANSI. I am still seeing an error at the Flat File Destination:
The code page on input column <column_name> is 1252 and is required to be 20127.
This happens for any column in the table, not just Unicode ones.
This is what I have been doing to ensure ASCII is used:
In the Flat File Connection Manager, used Code page "20127 (US-ASCII)"
Used a Derived Column to cast data types
In the OLE DB source, set the default code page to 20127
Any thoughts?
### User:
Why does my Node server leak memory when I attach a listener inside the request handler?
app.get('/data', (req, res) => {
emitter.on('update', (d) => res.write(JSON.stringify(d)));
...
});
### Assistant:
Because every request adds a **new** listener to a long-lived emitter and nothing ever removes it. The emitter holds references to the closure, which holds `res`, which holds the socket and buffers — none of it can be garbage-collected, and the listener array grows forever (you'll also see the MaxListenersExceededWarning).
Fix: remove the listener when the response ends.
```javascript
app.get('/data', (req, res) => {
const onUpdate = (d) => res.write(JSON.stringify(d));
emitter.on('update', onUpdate);
res.on('close', () => emitter.off('update', onUpdate));
});
```
Rule of thumb: any `.on()` targeting an object that outlives the current scope needs a matching `.off()` on a well-defined lifecycle event.
let current_cpu = fdt.cpus().find(|cpu| cpu.ids().first() == hart_id).unwrap();
let timebase_frequency = current_cpu.timebase_frequency();
TIMER_FREQ.store(timebase_frequency, Ordering::Relaxed);
let mut stdout_interrupts = None;
let stdout = fdt.chosen().stdout();
if let Some((node, reg, compatible)) = stdout.and_then(|n| Some((n, n.reg()?.next()?, n.compatible()?))) {
let stdout_addr = reg.starting_address as *mut u8;
if let Some(device) = crate::io::ConsoleDevices::from_compatible(compatible) {
let stdout_phys = PhysicalAddress::from_ptr(stdout_addr);
let ptr = phys2virt(stdout_phys);
unsafe { device.set_raw_console(ptr.as_mut_ptr()) };
if let Some(interrupts) = node.interrupts() {
// Try to get stdout loaded ASAP, so register interrupts later
// on if there are any
stdout_interrupts = Some((device, interrupts, ptr));
}
}
}
let mut init_path = "init";
if let Some(args) = fdt.chosen().bootargs() {
let split_args = args.split(' ').map(|s| {
let mut parts = s.splitn(2, '=');
(parts.next().unwrap(), parts.next())
});
for (option, value) in split_args {
match option {
"log-filter" => io::logging::parse_log_filter(value),
"init" => match value {
Some(path) => init_path = path,
None => log::warn!("No path provided for init process! Defaulting to `init`"),
},
"no-color" | "no-colour" => io::logging::USE_COLOR.store(false, Ordering::Relaxed),
"console" => match value {
Some("sbi") => {
if let ExtensionAvailability::Available(_) = probe_extension(sbi::legacy::CONSOLE_PUTCHAR_EID) {
let this_is_awful = Box::leak(Box::new(io::LegacySbiConsoleOut));
io::set_console(this_is_awful);
}
}
Some(fdt_node) => {
if let Some((node, reg, compatible)) =
fdt.find_node(fdt_node).and_then(|n| Some((n, n.reg()?.next()?, n.compatible()?)))
{
let stdout_addr = reg.starting_address as *mut u8;
if let Some(device) = crate::io::ConsoleDevices::from_compatible(compatible) {
let stdout_phys = PhysicalAddress::from_ptr(stdout_addr);
let ptr = phys2virt(stdout_phys);
unsafe { device.set_raw_console(ptr.as_mut_ptr()) };
### User:
Write a Python function that returns the median of a list. Handle the empty-list case.
### Assistant:
Here's a version with edge cases handled:
```python
def median(values: list[float]) -> float:
"""Return the median of a list of numbers.
Raises ValueError for an empty list.
"""
if not values:
raise ValueError("median() arg is an empty list")
ordered = sorted(values)
n = len(ordered)
mid = n // 2
if n % 2 == 1:
return float(ordered[mid])
return (ordered[mid - 1] + ordered[mid]) / 2.0
```
For an even count it averages the two middle elements. If your input may contain NaN, filter with `math.isnan` before sorting — otherwise the comparison order breaks.
Leaflet: Add a link to the markers
Pretty simple question: How can I make the map markers in Leaflet clickable and route the user to an other page? Every marker has its own page.
I've tried the following without success; somehow all the markers point to the same page, which is the last assigned URI.
var markers = [
{ coords: [51.505, -0.09], uri: '/some-page' },
...
];
for(x in markers)
{
L.marker(markers[x].coords).on('click', function() {
window.location = markers[x].uri;
}).addTo(map);
}
This issue is really driving me nuts.
import clone from 'clone';
import uuid from 'uuid/v4';
import Vue from 'vue';
import Vuex from 'vuex';
import { RunData, RunDataPlayer, RunDataTeam } from '../../../types';
import { msToTimeStr } from '../_misc/helpers';
import { store as repStore } from '../_misc/replicant-store';
Vue.use(Vuex);
enum Mode {
New = 'New',
EditActive = 'EditActive',
EditOther = 'EditOther',
Duplicate = 'Duplicate',
}
const defaultRunData: RunData = {
teams: [],
customData: {},
id: uuid(),
};
const defaultTeam: RunDataTeam = {
id: uuid(),
players: [],
};
const defaultPlayer: RunDataPlayer = {
id: uuid(),
teamID: '',
name: '',
social: {},
};
export default new Vuex.Store({
state: {
runData: clone(defaultRunData),
mode: 'New' as Mode,
prevID: undefined as string | undefined,
updateTwitch: false,
},
mutations: {
updateRunData(state, { value }): void {
Vue.set(state, 'runData', clone(value));
Vue.set(state, 'updateTwitch', false);
},
updateMode(state, { value }): void {
Vue.set(state, 'mode', value);
},
updateTwitch(state, { value }): void {
Vue.set(state, 'updateTwitch', value);
},
setAsDuplicate(state): void {
Vue.set(state, 'prevID', state.runData.id);
Vue.set(state.runData, 'id', uuid());
},
setPreviousRunID(state, { value }): void {
Vue.set(state, 'prevID', value);
},
resetRunData(state): void {
Vue.set(state, 'runData', clone(defaultRunData));
if (repStore.state.defaultSetupTime) { // Fill in default setup time if available.
Vue.set(state.runData, 'setupTimeS', repStore.state.defaultSetupTime);
Vue.set(state.runData, 'setupTime', msToTimeStr(
repStore.state.defaultSetupTime * 1000,
));
}
Vue.set(state.runData, 'id', uuid());
Vue.set(state, 'updateTwitch', false);
},
addNewTeam(state): void {
const teamData = clone(defaultTeam);
teamData.id = uuid();
// Adds an empty player as well for ease of use.
const playerData = clone(defaultPlayer);
playerData.id = uuid();
playerData.teamID = teamData.id;
teamData.players.push(playerData);
How to install Delphi 7 on Vista
I tried to install Delphi 7 on Vista several times and Vista prevented me from doing so by telling me that there are known problems with this application (Delphi 7). Several other people in my company experienced problems with installing D7 on Vista.
This lead to the conclusion that we were at risk with our D7 application, as the company could within the lifetime of the app switch to Vista or Windows 7 and newer Delphi versions are not in the policy of the company. Therefore management decided on rewriting the app in C#.
My question(s):
How to install D7 on Vista
Experience with such an installation
Risk assessment concerning stability of IDE and developed programs
Risk assessment concerning executability under Windows 7
Not using any third party components or database - there should be no problem running the developed app under Vista. If not able to develop and debug under Vista (which at the point being will be the only customer platform, yes, internal programming) will result in a sort of cross platform development - if we would be allowed to keep XP as the development platform.
It is not a developers decision to rewrite, it has been done in the company for the last 3 years: if you had to significantly touch an app developed in Delphi or if there was a certain risk of it not to survive the planned life circle/life span, it had to be rewritten. The life cycle just expanded to 2015 due to canceling another project.
So the main issue here would really be: I would like to have educated arguments about the risks.
The Teahouse, about an immigrant restaurant owner trying to protect his family from juvenile gangs, takes a scathing look at the criminal justice system in Hong Kong and is considered one of Kuei's landmark works. The film is also a strong example of Kuei's penchant for eschewing studio sets for the realistic immediacy of urban locations, vividly depicting the harsh environment of lower-class immigrant life. It was followed by a hit sequel in 1975, Big Brother Cheng, with kung fu star Kuan Tai Chen reprising the eponymous role. Kuei transcended the tired revenge tropes of many action sequels, making Big Brother Cheng a compelling and uncompromising examination of crime, juvenile delinquency and social injustice.
Though Kuei's contributions to Hong Kong cinema have often been neglected in recent decades, one film in particular ensured that he would enjoy a devoted cult audience for many years to come. Reaching new extremes in graphic sex and violence, the horror movie The Killer Snakes, is still considered one of Kuei's most notorious and controversial pictures. The plot centers on a young man's special powers with venomous snakes, which allow him to take revenge on those who have wronged him. Several over-the-top scenes of S&M sex and of course lethal snake attacks earned The Killer Snakes its following as a midnight movie classic and to some degree, cemented Kuei's reputation as a maverick filmmaker. The movie is also noteworthy for actor Kam Kwok-Leung's crazily committed performance and the use of hundreds of live poisonous snakes.
Kuei continued to challenge himself by directing segments for The Criminals film series, an acclaimed anthology based on actual Hong Kong cases. His episodes (across four films from 1975 to 1977) included "The Deaf Mute Killer," "The Informer" and "Arson". During the late '70s, Kuei also expanded his filmography to include Cantonese-language comedies (Mr. Funnybone, Crazy Imposters, The Reckless Cricket) and kung fu (The Iron Dragon Strikes Back).
The 1980s saw the versatile Kuei reinventing himself once again, this time with the popular supernatural fantasy, Hex and its two sequels, Hex vs. Witchcraft and Hex After Hex. The latter contained Kuei's signature social satire, taking on such hot-button topics as real estate development and Hong Kong's looming reunification with China. In fact, an early cut of the 1982 film featured a sequence where a character is branded on his behind with "1997" the year mainland China would resume control over Hong Kong. Deemed too politically sensitive, the scene was re-edited and the branded posterior featured "SB" (for Shaw Brothers) instead. Still, Kuei ingeniously found a way to insert a visual gag at the studio's expense.
Kuei also delved into the wuxia genre for the first time with Killer Constable (1980). Though a box-office disappointment at the time of its release, today Killer Constable is considered one of Kuei's finest, most accomplished movies.
package consul
import (
"context"
"errors"
"fmt"
"math/rand"
"net"
"net/http"
"net/url"
"regexp"
"strconv"
"strings"
"sync"
"sync/atomic"
"time"
"github.com/hashicorp/consul/api"
log "github.com/hashicorp/go-hclog"
"github.com/hashicorp/go-secure-stdlib/parseutil"
"github.com/hashicorp/go-secure-stdlib/strutil"
"github.com/hashicorp/go-secure-stdlib/tlsutil"
"github.com/hashicorp/vault/sdk/helper/consts"
sr "github.com/hashicorp/vault/serviceregistration"
"github.com/hashicorp/vault/vault/diagnose"
atomicB "go.uber.org/atomic"
"golang.org/x/net/http2"
)
const (
// checkJitterFactor specifies the jitter factor used to stagger checks
checkJitterFactor = 16
// checkMinBuffer specifies provides a guarantee that a check will not
// be executed too close to the TTL check timeout
checkMinBuffer = 100 * time.Millisecond
// consulRetryInterval specifies the retry duration to use when an
// API call to the Consul agent fails.
consulRetryInterval = 1 * time.Second
// defaultCheckTimeout changes the timeout of TTL checks
defaultCheckTimeout = 5 * time.Second
// DefaultServiceName is the default Consul service name used when
// advertising a Vault instance.
DefaultServiceName = "vault"
// reconcileTimeout is how often Vault should query Consul to detect
// and fix any state drift.
reconcileTimeout = 60 * time.Second
// metaExternalSource is a metadata value for external-source that can be
// used by the Consul UI.
metaExternalSource = "vault"
)
var hostnameRegex = regexp.MustCompile(`^(([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9\-]*[a-zA-Z0-9])\.)*([A-Za-z0-9]|[A-Za-z0-9][A-Za-z0-9\-]*[A-Za-z0-9])$`)
// serviceRegistration is a ServiceRegistration that advertises the state of
// Vault to Consul.
type serviceRegistration struct {
Client *api.Client
logger log.Logger
serviceLock sync.RWMutex
redirectHost string
redirectPort int64
serviceName string
serviceTags []string
serviceAddress *string
disableRegistration bool
checkTimeout time.Duration
notifyActiveCh chan struct{}
notifySealedCh chan struct{}
notifyPerfStandbyCh chan struct{}
notifyInitializedCh chan struct{}
isActive *atomicB.Bool
isSealed *atomicB.Bool
isPerfStandby *atomicB.Bool
isInitialized *atomicB.Bool
}
// NewConsulServiceRegistration constructs a Consul-based ServiceRegistration.
func NewServiceRegistration(conf map[string]string, logger log.Logger, state sr.State) (sr.ServiceRegistration, error) {
// Allow admins to disable consul integration
disableReg, ok := conf["disable_registration"]
var disableRegistration bool
if ok && disableReg != "" {
b, err := parseutil.ParseBool(disableReg)
if err != nil {
return nil, fmt.Errorf("failed parsing disable_registration parameter: %w", err)
}
disableRegistration = b
}
if logger.IsDebug() {
logger.Debug("config disable_registration set", "disable_registration", disableRegistration)
}
java.lang.StackOverflowError when persisting an object jpa
I am building an application using JPA, JSF, EJB, Derby. At this point the application is still small. I have a form in the application to add new products. When adding data to the db it goes smoothly until I restart the application or the server. When I restart either the server or app I get java.lang.StackOverflowError, I still can query the db for the data represented by the product db, but creation product is not possible. I have only 5 entries in the db, as of now, but I am concerned about this happening so early.
This is the Ejb (Getter, setter and constructors removed for simplicity):
@Stateless
public class ProductEJB{
@PersistenceContext(unitName = "luavipuPU")
private EntityManager em;
public List<Product> findAllProducts()
{
TypedQuery<Product> query = em.createNamedQuery("findAllProducts", Product.class);
return query.getResultList();
}
public Product findProductById(int productId)
{
return em.find(Product.class, productId);
}
public Product createProduct(Product product)
{
product.setDateAdded(productCreationDate());
em.persist(product);
return product;
}
public void updateProduct(Product product)
{
em.merge(product);
}
public void deleteProduct(Product product)
{
product = em.find(Product.class, product.getProduct_id());
em.remove(em.merge(product));
}
this is the ProductController (Getter, setter and constructors removed for simplicity):
@Named
@RequestScoped
public class ProductController {
@EJB
private ProductEJB productEjb;
@EJB
private CategoryEJB categoryEjb;
private Product product = new Product();
private List<Product> productList = new ArrayList<Product>();
private Category category;
private List<Category> categoryList = new ArrayList<Category>();
public String doCreateProduct()
{
product = productEjb.createProduct(product);
productList = productEjb.findAllProducts();
return "listProduct?faces-redirect=true";
}
public String doDeleteProduct()
{
productEjb.deleteProduct(product);
return "deleteProduct?faces-redirect=true";
}
public String cancelDeleteAction()
{
return "listProduct?faces-redirect=true";
}
@PostConstruct
public void init()
{
categoryList = categoryEjb.findAllCategory();
productList = productEjb.findAllProducts();
}
Category Entity (Getters, setters, hash() and constructors removed for simplicity):
import { Random } from '../../random/generator/Random';
import { Arbitrary } from './definition/Arbitrary';
import { Shrinkable } from './definition/Shrinkable';
import { nat } from './IntegerArbitrary';
/**
* Constraints to be applied on {@link option}
* @remarks Since 2.2.0
* @public
*/
export interface OptionConstraints {
/**
* The probability to build a nil value is of `1 / freq`
* @remarks Since 1.17.0
*/
freq?: number;
/**
* The nil value (default would be null)
* @remarks Since 1.17.0
*/
nil?: TNil;
}
/** @internal */
class OptionArbitrary extends Arbitrary {
readonly isOptionArb: Arbitrary;
constructor(readonly arb: Arbitrary, readonly frequency: number, readonly nil: TNil) {
super();
this.isOptionArb = nat(frequency); // 1 chance over to have non nil
}
private static extendedShrinkable(s: Shrinkable, nil: TNil): Shrinkable {
function* g(): IterableIterator> {
yield new Shrinkable(nil);
}
return new Shrinkable(s.value_ as T | TNil, () =>
s
.shrink()
.map((v) => OptionArbitrary.extendedShrinkable(v, nil))
.join(g())
);
}
generate(mrng: Random): Shrinkable {
return this.isOptionArb.generate(mrng).value === 0
? new Shrinkable(this.nil)
: OptionArbitrary.extendedShrinkable(this.arb.generate(mrng), this.nil);
}
withBias(freq: number) {
return new OptionArbitrary(this.arb.withBias(freq), this.frequency, this.nil);
}
}
### User:
What does this bash do? find . -name '*.log' -mtime +7 -exec rm {} +
### Assistant:
It deletes all `.log` files older than seven days, recursively from the current directory.
Piece by piece: `find .` walks the tree from here; `-name '*.log'` matches files ending in .log; `-mtime +7` filters to files modified more than 7 full days ago; `-exec rm {} +` runs `rm` on the matches, batching many files per invocation (the `+` terminator) instead of one `rm` per file (which is what `\;` would do — slower).
Safety tip: dry-run it first by replacing `-exec rm {} +` with `-print` to see what would be deleted.
Error: [$injector:unpr] Unknown provider: modalInstanceProvider <- modalInstance <- modalCtrl with the latest ui bootstrap
EDIT - as the code below is, the modal will work - my issue was I had included ng-app and ng-controller in my HTML template for my modal, however they are not included in the below question.
I've my main controller, modal controller and my modal template HTML
Everything seems to be in order and I cannot for the life of me work out (or find out from stackoverflow) why I keep getting Error: [$injector:unpr] Unknown provider: modalInstanceProvider <- modalInstance <- modalCtrl error.
BTW $modal is now depricated, it's $ubiModal now.
Main ctrl:
var module = angular.module("app", ["agGrid", "ngAnimate", "ngSanitize", "ngDialog", "ui.bootstrap"])
module.controller("mainCtrl", ["$scope", "dataService", "$timeout", "dateFilter", "ngDialog", "$http", "$uibModal", function ($scope, dataService, $timeout, dateFilter, ngDialog, $http, $uibModal) {
$scope.open = function () {
var uibModalInstance= $uibModal.open({
templateUrl: "views/Modal.html",
controller: "modalCtrl",
show: true,
})
};
}]);
my modal controller:
module.controller("modalCtrl", ["$scope", "ngDialog", "dataService", "$uibModalInstance", function ($scope, ngDialog, dataService, $uibModalInstance) {
//do stuff
}]);
and my HTML template:
<div id="loginModal" class="modal show" tabindex="-1" role="dialog" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" ng-click="closeThisDialog(); printArray()" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h1 class="text-center" style="text-align: center">Entities:</h1>
</div>
<div class="modal-body">
<div>
<div>
<input type="text" placeholder="Search" ng-model="entity">
</div>
</div>
<div ng-repeat="entity in entityArray | filter:entity">
<label>
<input style="float: left; margin-top: 5px" type="checkbox" ng-model="entityChecked" ng-change="getEntityFromModal(entity, entityChecked)" />
<span>{{entity}}</span>
</label>
</div>
</div>
<button ng-click="okButtonEntity();" >OK</button>
</div>
</div>
</div>
Tortoise SVN does not ask for user/pass and fails
I installed tortoiseSVN and was able to do a checkout of the dirs/files that are already in the repository (I don't need to authenticate for that)
When I try to commit changes I get the following error:
Server sent unexpected return value (403 Forbidden) in response to CHECKOUT
I am never asked to enter my user/pass for authentication.
Tried googling it a bit, and found various mentions of this, but no definite answer.
I talked with the people in charge of the SVN server on our campus, and they claim that everything is OK on the server side...
Any help would be greatly appreciated :)
impl Data {
pub fn to_map(&self) -> HashMap<&'static str, String> {
let mut map = HashMap::new();
map.insert("title", format!("{}\n{}", self.class, self.place));
map.insert("start", utils::to_utc(self.time_begin).to_rfc3339());
map.insert("end", utils::to_utc(self.time_end).to_rfc3339());
map
}
pub fn class(&self) -> String {
self.class.to_string()
}
pub fn place(&self) -> String {
self.place.to_string()
}
pub fn begin(&self) -> NaiveDateTime {
self.time_begin
}
pub fn end(&self) -> NaiveDateTime {
self.time_end
}
fn parse(class: &str, times: &str, places: &str) -> Vec {
let mut default = String::new();
let mut map = HashMap::new();
if places.find("(").is_some() {
places.split("(")
.skip(1)
.map(|s| s
.split(")")
.map(|s| s.trim())
.collect::>()
).map(|vec| (vec.get(0).unwrap_or(&"1").clone(),
vec.get(1).unwrap_or(&"N/A").clone())
).map(|(i, p)| (parse_list_uint(i), p))
.map(|(vec, p)| vec
.iter()
.map(|i| map.insert(i.clone() as usize, p.to_string()))
.all(|_| true)
).all(|_| true);
} else {
default = places.to_string();
}
times
.split("Từ ")
.skip(1)
.enumerate()
.map(|(i, s)| s.replace(&format!("({})", i + 1), ""))
.map(|s| {
s.split(':')
.map(|s| s.trim().to_string())
.collect::>()
})
.map(|vec| (vec[0].clone(), vec[1].clone()))
.map(|(r, o)| (Data::parse_range(&r), Data::parse_wd_period(&o)))
.map(|(r, d)| Data::merge_date_time(r, d))
.enumerate()
.map(|(i, vec)| {
vec.iter()
.map(|(b, e)| Data {
class: class.to_string(),
time_begin: *b,
time_end: *e,
place: map.get(&(i+1)).unwrap_or(&default).clone(),
})
.collect::>()
})
.flatten()
.collect()
}
},
skewX: {
20: 40
},
color: {
'cyan': 'orange'
},
duration: 300
});
p = html._props;
return expect(html._renderProps).toEqual(['borderWidth', 'borderRadius']);
});
it('should not copy customProperties to _renderProps', function() {
var customProperties, html;
customProperties = {
originX: {
type: 'number',
"default": 0
},
draw: function() {
return {};
}
};
html = new Html({
el: el,
borderWidth: '20px',
borderRadius: '40px',
originX: 20,
customProperties: customProperties
});
return expect(html._renderProps).toEqual(['borderWidth', 'borderRadius']);
});
it('should call _createDeltas method ->', function() {
var html;
html = new Html({
el: el,
borderWidth: '20px',
borderRadius: '40px',
x: {
20: 40
},
color: {
'cyan': 'orange'
}
});
spyOn(html, '_createDeltas');
html._extendDefaults();
return expect(html._createDeltas).toHaveBeenCalledWith(html._addDefaults(html._o));
});
it('should parse el ->', function() {
var div, html;
div = document.createElement('div');
div.setAttribute('id', 'js-el');
document.body.appendChild(div);
html = new Html({
el: '#js-el',
borderWidth: '20px',
borderRadius: '40px',
x: {
20: 40
},
color: {
'cyan': 'orange'
}
});
html._props.el = null;
html._extendDefaults();
expect(html._props.el instanceof HTMLElement).toBe(true);
return expect(html._props.el).toBe(div);
});
it('should save _props.el to el ->', function() {
var div, html;
div = document.createElement('div');
html = new Html({
el: div,
borderWidth: '20px',
borderRadius: '40px',
x: {
20: 40
},
color: {
'cyan': 'orange'
}
});
return expect(html.el).toBe(div);
});
return it('should use props if passed ->', function() {
var html, props;
props = {};
html = new Html({
el: document.createElement('div'),
props: props
});
return expect(html._props).toBe(props);
});
});
describe('_createDeltas method ->', function() {
it('should create deltas with passed object', function() {
var html;
html = new Html({
el: el,
borderWidth: '20px',
borderRadius: '40px',
x: {
20: 40
},
color: {
'cyan': 'orange'
}
});
How to use single & multiple comment line in twig
I'm new in twig project. I need to comment some code like // or /**/. how to use comment in twig?
{%if role=3 %}
<div class="col-md-6">
<div class="form-group">
<label class="control-label"> </label>
<select multiple class="form-control" id="path_attachment" name="path_attachment[]"></select>
</div>
</div>
{% else %}
<div class="col-md-6"></div>
{% endif %}
Overwrite font: in CSS
I have an existing web page on which there is a CSS file that I am unable to change which has the following CSS in it:
body {
background: none repeat scroll 0 0 #FFFFFF;
color: #000000;
font: 0.8em Verdana,Arial,sans-serif;
}
I am adding in an additional CSS file, and for the part of the page that its controlling I need to be able to overwrite the font size that is above, and set the size to the auto size as supplied by the browser and a different font family.
I know about putting the !important tag on there so changing the font family hasn't been a problem, but if I don't put a size in there it strips it out when the page compiles.
I thought I could use font-size: to override it, but I'm unclear as to how to set that to be whatever the browser has automatically.
All help would be much appreciated! I'm a bit of a CSS novice!
use std::collections::BTreeMap;
use k8s_openapi::{api::core::v1::ConfigMap, chrono::Utc};
use super::utils;
#[derive(Clone)]
pub struct KubeConfigMap {
pub name: String,
pub namespace: String,
pub data: BTreeMap,
pub age: String,
}
impl KubeConfigMap {
pub fn from_api(cm: &ConfigMap) -> Self {
let data = match cm.data.as_ref() {
Some(d) => d.to_owned(),
_ => BTreeMap::new(),
};
KubeConfigMap {
name: cm.metadata.name.clone().unwrap_or_default(),
namespace: cm.metadata.namespace.clone().unwrap_or_default(),
age: utils::to_age(cm.metadata.creation_timestamp.as_ref(), Utc::now()),
data,
}
}
}
# -*- coding: utf8 -*-
def filter_event(event, happening_before):
"""Check if the following keys are present. These
keys only show up when using the API. If fetching
from the iCal, JSON, or RSS feeds it will just compare
the dates
"""
status = True
visibility = True
actions = True
if 'status' in event:
status = event['status'] == 'upcoming'
if 'visibility' in event:
visibility = event['visibility'] == 'public'
if 'self' in event:
actions = 'announce' not in event['self']['actions']
return (status and visibility and actions and
event['time'] < happening_before)
Is *this* really the best way to start a second JVM from Java code?
This is a followup to my own previous question and I'm kind of embarassed to ask this... But anyway: how would you start a second JVM from a standalone Java program in a system-independent way? And without relying on for instance an env variable like JAVA_HOME as that might point to a different JRE than the one that is currently running. I came up with the following code which actually works but feels just a little awkward:
public static void startSecondJVM() throws Exception {
String separator = System.getProperty("file.separator");
String classpath = System.getProperty("java.class.path");
String path = System.getProperty("java.home")
+ separator + "bin" + separator + "java";
ProcessBuilder processBuilder =
new ProcessBuilder(path, "-cp",
classpath,
AnotherClassWithMainMethod.class.getName());
Process process = processBuilder.start();
process.waitFor();
}
Also, the currently running JVM might have been started with some other parameters (-D, -X..., ...) that the second JVM would not know about.
Can I download file from URL link generated by google apps script
Please help I'm learning google-apps-script for short time.
I want to download file from remote site by url generating from data that stores in my spreadsheet.
for example, i have 2 paremeters:
Cell1 = val1, val2, ... valN
Cell2 = val21, val22, ... val2N
I split string from cell data to Arrays and than generate URL. for example: http://mysite.com/files/file.val1.val22.zip
Than i need to download file from this link...
Can I do this process automaticaly ?
// |reftest| shell-option(--enable-private-methods) skip-if(!xulRuntime.shell) async -- requires shell-options
// This file was procedurally generated from the following sources:
// - src/dstr-binding/ary-ptrn-elem-id-init-undef.case
// - src/dstr-binding/default/cls-expr-async-private-gen-meth-dflt.template
/*---
description: Destructuring initializer with an undefined value (private class expression async generator method (default parameter))
esid: sec-class-definitions-runtime-semantics-evaluation
features: [class, class-methods-private, async-iteration]
flags: [generated, async]
info: |
ClassExpression : class BindingIdentifieropt ClassTail
1. If BindingIdentifieropt is not present, let className be undefined.
2. Else, let className be StringValue of BindingIdentifier.
3. Let value be the result of ClassDefinitionEvaluation of ClassTail
with argument className.
[...]
14.5.14 Runtime Semantics: ClassDefinitionEvaluation
21. For each ClassElement m in order from methods
a. If IsStatic of m is false, then
i. Let status be the result of performing
PropertyDefinitionEvaluation for m with arguments proto and
false.
[...]
Runtime Semantics: PropertyDefinitionEvaluation
AsyncGeneratorMethod :
async [no LineTerminator here] * PropertyName ( UniqueFormalParameters )
{ AsyncGeneratorBody }
1. Let propKey be the result of evaluating PropertyName.
2. ReturnIfAbrupt(propKey).
3. If the function code for this AsyncGeneratorMethod is strict mode code, let strict be true.
Otherwise let strict be false.
4. Let scope be the running execution context's LexicalEnvironment.
5. Let closure be ! AsyncGeneratorFunctionCreate(Method, UniqueFormalParameters,
AsyncGeneratorBody, scope, strict).
[...]
13.3.3.6 Runtime Semantics: IteratorBindingInitialization
SingleNameBinding : BindingIdentifier Initializeropt
[...]
6. If Initializer is present and v is undefined, then
a. Let defaultValue be the result of evaluating Initializer.
b. Let v be GetValue(defaultValue).
[...]
7. If environment is undefined, return PutValue(lhs, v).
8. Return InitializeReferencedBinding(lhs, v).
---*/
var callCount = 0;
var C = class {
async * #method([x = 23] = [undefined]) {
assert.sameValue(x, 23);
callCount = callCount + 1;
}
get method() {
return this.#method;
}
};
new C().method().next().then(() => {
assert.sameValue(callCount, 1, 'invoked exactly once');
}).then($DONE, $DONE);
server_setting['port']['default'] + ') : ', end = '')
setting_json[3] = str(input())
if setting_json[3] == '':
setting_json[3] = server_setting['port']['default']
async with aiofiles.open('data/setting.json', 'w', encoding = 'utf8') as f:
await f.write('{ "db_name" : "' + setting_json[1] + '", "db_type" : "' + setting_json[0] + '", "host" : "' + setting_json[2] + '", "port" : "' + setting_json[3] + '" }')
async with aiofiles.open('data/setting.json', encoding = 'utf8') as f:
setting_data = json.loads(await f.read())
db = await aiosqlite.connect(setting_data['db_name'] + '.db')
db_create = {}
db_create['table'] = ['doc', 'doc_cac', 'doc_his', 'rec_dis', 'rec_ban', 'rec_log', 'mbr', 'mbr_set', 'mbr_log', 'ban', 'dis', 'dis_log', 'acl', 'backlink', 'wiki_set', 'list_per', 'list_fil', 'html_fil', 'list_alarm', 'list_watch', 'list_inter']
for i in db_create['table']:
try:
await db.execute('select test from ' + i + ' limit 1')
except:
try:
await db.execute('create table ' + i + '(test longtext)')
except:
await db.execute("alter table " + i + " add test longtext default ''")
db_setup = 0
try:
db_ver = await db.execute('select data from wiki_set where name = "db_ver"')
db_ver = await db_ver.fetchall()
if not db_ver:
db_setup = 1
else:
if int(version_load['main']['renew_count']) > int(db_ver[0][0]):
db_setup = 1
except:
db_setup = 1
if db_setup != 0:
db_create['doc'] = ['title', 'data']
db_create['doc_cac'] = ['title', 'data']
db_create['doc_his'] = ['id', 'title', 'data', 'date', 'ip', 'send', 'leng', 'hide', 'type']
db_create['rec_dis'] = ['title', 'sub', 'date', 'band', 'stop', 'agree']
db_create['rec_ban'] = ['block', 'end', 'today', 'blocker', 'why', 'band']
db_create['rec_log'] = ['who', 'what', 'time']
db_create['mbr'] = ['id', 'pw', 'acl', 'date', 'email']
db_create['mbr_set'] = ['name', 'id', 'data']
db_create['mbr_log'] = ['name', 'ip', 'ua', 'today', 'sub']
db_create['ban'] = ['block', 'end', 'why', 'band', 'login']
db_create['dis'] = ['doc', 'title', 'id', 'state', 'date', 'agree']
db_create['dis_log'] = ['id', 'data', 'date', 'ip', 'block', 'top', 'code', 'doc']
db_create['acl'] = ['title', 'decu', 'dis', 'view', 'why']
db_create['backlink'] = ['title', 'link', 'type']
db_create['wiki_set'] = ['name', 'data', 'coverage']
db_create['list_per'] = ['name', 'acl']
db_create['list_fil'] = ['name', 'regex', 'sub']
db_create['html_fil'] = ['html', 'kind', 'plus']
db_create['list_alarm'] = ['name', 'data', 'date']
db_create['list_watch'] = ['user', 'title']
db_cre
/*
* Copyright (c), Recep Aslantas.
*
* MIT License (MIT), http://opensource.org/licenses/MIT
* Full license can be found in the LICENSE file
*/
#ifndef cglmc_affine_h
#define cglmc_affine_h
#ifdef __cplusplus
extern "C"
{
#endif
#include "../cglm.h"
CGLM_EXPORT
void glmc_translate_make(mat4 m, vec3 v);
CGLM_EXPORT
void glmc_translate_to(mat4 m, vec3 v, mat4 dest);
CGLM_EXPORT
void glmc_translate(mat4 m, vec3 v);
CGLM_EXPORT
void glmc_translate_x(mat4 m, float to);
CGLM_EXPORT
void glmc_translate_y(mat4 m, float to);
CGLM_EXPORT
void glmc_translate_z(mat4 m, float to);
CGLM_EXPORT
void glmc_scale_make(mat4 m, vec3 v);
CGLM_EXPORT
void glmc_scale_to(mat4 m, vec3 v, mat4 dest);
CGLM_EXPORT
void glmc_scale(mat4 m, vec3 v);
CGLM_EXPORT
void glmc_scale_uni(mat4 m, float s);
CGLM_EXPORT
void glmc_rotate_x(mat4 m, float rad, mat4 dest);
CGLM_EXPORT
void glmc_rotate_y(mat4 m, float rad, mat4 dest);
CGLM_EXPORT
void glmc_rotate_z(mat4 m, float rad, mat4 dest);
CGLM_EXPORT
void glmc_rotate_make(mat4 m, float angle, vec3 axis);
CGLM_EXPORT
void glmc_rotate(mat4 m, float angle, vec3 axis);
CGLM_EXPORT
void glmc_rotate_at(mat4 m, vec3 pivot, float angle, vec3 axis);
CGLM_EXPORT
void glmc_rotate_atm(mat4 m, vec3 pivot, float angle, vec3 axis);
CGLM_EXPORT
void glmc_decompose_scalev(mat4 m, vec3 s);
CGLM_EXPORT
bool glmc_uniscaled(mat4 m);
CGLM_EXPORT
void glmc_decompose_rs(mat4 m, mat4 r, vec3 s);
CGLM_EXPORT
void glmc_decompose(mat4 m, vec4 t, mat4 r, vec3 s);
/* affine-mat */
CGLM_EXPORT
void glmc_mul(mat4 m1, mat4 m2, mat4 dest);
CGLM_EXPORT
void glmc_mul_rot(mat4 m1, mat4 m2, mat4 dest);
CGLM_EXPORT
void glmc_inv_tr(mat4 mat);
#ifdef __cplusplus
}
#endif
#endif /* cglmc_affine_h */
Run multiple insert queries against firebird database using isql
I have requirement of inserting enormous data in table of firebird database around 40K entries. I got my scripts ready but while executing it using flameRobin, the UI just got hang forever while inserting such enormous data in one go.
I know it would be fine if i execute my insert queries in blocks of 255 queries but i want to know if there is any bulk insert tool available for Firebird to do such entries while reading from my scripts.sql file.
After some googling, I came across isql tool but not able to execute the scripts against it. Can someone guide me to any other tool or the proper documentation to enter such enormous data in one go?
I have firebird version 2.5 installed on my system.
void DrawTex_CvNormDist(
const std::vector &aNormDist,
const delfem2::opengl::CTexRGB &tex0,
const float *R,
const float *t,
const float *K)
{
namespace lcl = ::delfem2::opengl::tex;
const unsigned int nw = tex0.width;
const unsigned int nh = tex0.height;
assert(aNormDist.size()==nw*nh*4);
::glMatrixMode(GL_MODELVIEW);
::glPushMatrix();
float A[16];
delfem2::Mat4_AffineTrans_RotTransl(
A,
R, t);
::glMultMatrixf(A);
//
double Kinv[9];
delfem2::Inverse_Mat3(Kinv, K);
// double ratio0 = 1. / Kinv[8];
float B[16];
delfem2::Mat4_Mat3(B, Kinv);
float C[16];
delfem2::Transpose_Mat4(C, B);
::glMultMatrixf(C);
//
::glDisable(GL_POLYGON_OFFSET_FILL);
::glEnable(GL_TEXTURE_2D);
::glBindTexture(GL_TEXTURE_2D, tex0.id_tex);
::glColor3d(1, 1, 1);
::glBegin(GL_QUADS);
for (unsigned int iw = 0; iw < nw - 1; ++iw) {
for (unsigned int ih = 0; ih < nh - 1; ++ih) {
const float x0[3] = {float(iw)+0.5f,float(ih)+0.5f,1.f};
const float x1[3] = {float(iw)+1.5f,float(ih)+0.5f,1.f};
const float x2[3] = {float(iw)+1.5f,float(ih)+1.5f,1.f};
const float x3[3] = {float(iw)+0.5f,float(ih)+1.5f,1.f};
float Kix0[3]; MatVec3(Kix0, Kinv, x0);
float Kix1[3]; MatVec3(Kix1, Kinv, x1);
float Kix2[3]; MatVec3(Kix2, Kinv, x2);
float Kix3[3]; MatVec3(Kix3, Kinv, x3);
float ntKix0 = lcl::Dot3(aNormDist.data()+((ih + 0) * nw + (iw + 0))*4, Kix0);
float ntKix1 = lcl::Dot3(aNormDist.data()+((ih + 0) * nw + (iw + 1))*4, Kix1);
float ntKix2 = lcl::Dot3(aNormDist.data()+((ih + 1) * nw + (iw + 1))*4, Kix2);
float ntKix3 = lcl::Dot3(aNormDist.data()+((ih + 1) * nw + (iw + 0))*4, Kix3);
// std::cout << ntKix0 << " " << ntKix1 << " " << ntKix2 << " " << ntKix3 << std::endl;
double z0 = -aNormDist[((ih + 0) * nw + (iw + 0))*4+3] / ntKix0;
double z1 = -aNormDist[((ih + 0) * nw + (iw + 1))*4+3] / ntKix1;
double z2 = -aNormDist[((ih + 1) * nw + (iw + 1))*4+3] / ntKix2;
double z3 = -aNormDist[((ih + 1) * nw + (iw + 0))*4+3] / ntKix3;
::glTexCoord2d((iw + 0.5) / nw, (ih + 0.5) / nh);
::glVertex3d(z0 * (iw + 0.5), z0 * (ih + 0.5), z0);
::glTexCoord2d((iw + 1.5) / nw, (ih + 0.5) / nh);
::glVertex3d(z1 * (iw + 1.5), z1 * (ih + 0.5), z1);
::glTexCoord2d((iw + 1.5) / nw, (ih + 1.5) / nh);
::glVertex3d(z2 * (iw + 1.5), z2 * (ih + 1.5), z2);
::glTexCoord2d((iw + 0.5) / nw, (ih + 1.5) / nh);
::glVertex3d(z3 * (iw + 0.5), z3 * (ih + 1.5), z3);
}
}
::glEnd();
//
::glPopMatrix();
}
}
#endif
(function() {
var Html, el, h;
Html = mojs.Html;
h = mojs.h;
el = document.createElement('div');
describe('Html ->', function() {
it('should extend Thenable', function() {
var html;
html = new Html({
el: el
});
return expect(html instanceof mojs.Thenable).toBe(true);
});
describe('_extendDefaults method ->', function() {
it('should copy all non-delta properties to _props', function() {
var html, p;
html = new Html({
el: el,
borderWidth: '20px',
borderRadius: '40px',
y: 40,
x: {
20: 40
},
skewX: {
20: 40
},
color: {
'cyan': 'orange'
}
});
p = html._props;
expect(p['borderWidth']).toBe('20px');
expect(p['borderRadius']).toBe('40px');
expect(p['y']).toBe('40px');
expect(p['z']).toBe(0);
expect(p['skewY']).toBe(0);
expect(p['angleX']).toBe(0);
expect(p['angleY']).toBe(0);
expect(p['angleZ']).toBe(0);
expect(p['scale']).toBe(1);
expect(p['scaleX']).toBe(1);
expect(p['scaleY']).toBe(1);
expect(p['isRefreshState']).toBe(true);
expect(p['isShowStart']).toBe(true);
expect(p['isShowEnd']).toBe(true);
expect(p['isSoftHide']).toBe(true);
expect(p['isForce3d']).toBe(false);
expect(html._renderProps).toEqual(['borderWidth', 'borderRadius']);
return expect(html._drawProps).toEqual(['color']);
});
it('should not copy tween properties _drawProps', function() {
var html, p;
html = new Html({
el: el,
borderWidth: '20px',
borderRadius: '40px',
y: 40,
x: {
20: 40
},
skewX: {
20: 40
},
color: {
'cyan': 'orange'
},
duration: 300,
timeline: {
delay: 300
}
});
p = html._props;
return expect(html._drawProps).toEqual(['color']);
});
it('should not copy customProperties _drawProps', function() {
var customProperties, html, p;
customProperties = {
originX: {
type: 'number',
"default": 0
},
draw: function() {
return {};
}
};
html = new Html({
el: el,
color: {
'cyan': 'red'
},
originX: {
20: 40
},
customProperties: customProperties
});
p = html._props;
return expect(html._drawProps).toEqual(['color']);
});
it('should not copy tween properties _renderProps', function() {
var html, p;
html = new Html({
el: el,
borderWidth: '20px',
borderRadius: '40px',
y: 40,
x: {
20: 40
PSQLException: The column index is out of range: 2, number of columns: 1
The following error occured when try to query a list of email with provided email,password. Actually the subscribers_table has 10 columns with column names of email and password .
[PSQLException: The column index is out of range: 2, number of columns: 1.]
My LoginProcess Model code:
case class LoginProcess(email:String,password:String)
//error occured in this line
implicit val getLoginProcessResult = GetResult(r => LoginProcess(r.nextString, r.nextString))
def check_Login_Success_Query(email: String,password:String) = sql"select email from provisions_schema.subscribers_table where email = $email and password=$password ".as[LoginProcess]
val login_Success_Query_List = check_Login_Success_Query(email_ip,password_ip).list
println("login_Success_Query_List.length ->" +login_Success_Query_List.length)
What is a "django backend"?
I've been encountering quite a few django Apps mentioning 'backend', but don't exactly know what it is. Searching around google does not give much results regarding django backends in general. Could someone give an explanation?
To be specific, take these examples:
Actually I think the first two and the third are a bit different, what I was more unsure about was the first two: backends included in Apps.
#pragma once
namespace pumipic {
/**
* Distributes current and new particles across a number of processes, then rebuilds
* @param[in] new_element view of ints representing new elements for each current particle (-1 for removal)
* @param[in] new_process view of ints representing new processes for each current particle
* @param[in] dist Distributor set up for keeping track of processes
* @param[in] new_particle_elements view of ints representing new elements for new particles (-1 for removal)
* @param[in] new_particle_info array of views filled with particle data
*/
template
void CSR::migrate(kkLidView new_element, kkLidView new_process,
Distributor dist,
kkLidView new_particle_elements,
MTVs new_particle_info) {
const auto btime = prebarrier();
Kokkos::Profiling::pushRegion("csr_migrate");
Kokkos::Timer timer;
// Distributor size & rank for performing migration
int comm_size = dist.num_ranks();
int comm_rank;
MPI_Comm_rank(dist.mpi_comm(), &comm_rank);
// If serial, skip migration
if (comm_size == 1) {
RecordTime("CSR particle migration", timer.seconds(), btime);
rebuild(new_element, new_particle_elements, new_particle_info);
Kokkos::Profiling::popRegion();
return;
}
import java.net.InetSocketAddress;
import java.net.UnknownHostException;
import java.nio.ByteBuffer;
import java.util.Collections;
import org.java_websocket.WebSocket;
import org.java_websocket.drafts.Draft;
import org.java_websocket.drafts.Draft_17;
import org.java_websocket.handshake.ClientHandshake;
import org.java_websocket.server.WebSocketServer;
public class AutobahnServerTest extends WebSocketServer {
private static int counter = 0;
public AutobahnServerTest( int port , Draft d ) throws UnknownHostException {
super( new InetSocketAddress( port ), Collections.singletonList( d ) );
}
public AutobahnServerTest( InetSocketAddress address, Draft d ) {
super( address, Collections.singletonList( d ) );
}
@Override
public void onOpen( WebSocket conn, ClientHandshake handshake ) {
counter++;
System.out.println( "///////////Opened connection number" + counter );
}
@Override
public void onClose( WebSocket conn, int code, String reason, boolean remote ) {
System.out.println( "closed" );
}
@Override
public void onError( WebSocket conn, Exception ex ) {
System.out.println( "Error:" );
ex.printStackTrace();
}
@Override
public void onMessage( WebSocket conn, String message ) {
conn.send( message );
}
@Override
public void onMessage( WebSocket conn, ByteBuffer blob ) {
conn.send( blob );
}
public static void main( String[] args ) throws UnknownHostException {
WebSocket.DEBUG = false;
int port;
try {
port = new Integer( args[ 0 ] );
} catch ( Exception e ) {
System.out.println( "No port specified. Defaulting to 9003" );
port = 9003;
}
new AutobahnServerTest( port, new Draft_17() ).start();
}
}
How to use UIPanGestureRecognizer to move object? iPhone/iPad
There are several examples of the UIPanGestureRecognizer class. For example I have read this and I am still not able to use it...
On the nib file that I am working on I have a UIView (white rectangle on image) that I wish to drag with that class:
and in my .m file I have placed:
- (void)setTranslation:(CGPoint)translation inView:(UIView *)view
{
NSLog(@"Test to see if this method gets executed");
}
and that method does not get executed when I drag the mouse across the UIView. I have also tried placing:
- (void)pan:(UIPanGestureRecognizer *)gesture
{
NSLog(@"testing");
}
And that method does not get executed either. Maybe I am wrong but I think this methods should work like the - (void) touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event method where I just have to place that method and it will get called whenever there are touches.
What am I doing wrong? Maybe do I have to draw a connection to that method? If so how can I do that?
import {BoundaryElementProvider, Flex, PortalProvider, usePortal, useElementRect} from '@sanity/ui'
import React, {createElement, useEffect, useMemo, useRef, useState} from 'react'
import {ScrollContainer} from '@sanity/base/components'
import {unstable_useDocumentValuePermissions as useDocumentValuePermissions} from '@sanity/base/hooks'
import styled, {css} from 'styled-components'
import {SchemaType} from '@sanity/types'
import {PaneContent} from '../../../components/pane'
import {usePaneLayout} from '../../../components/pane/usePaneLayout'
import {useDeskTool} from '../../../contexts/deskTool'
import {useDocumentPane} from '../useDocumentPane'
import {DocumentPanelHeader} from './header'
import {FormView} from './documentViews'
import {PermissionCheckBanner} from './PermissionCheckBanner'
import {ReferenceChangedBanner} from './ReferenceChangedBanner'
function getSchemaType(typeName: string): SchemaType | null {
const schemaMod = require('part:@sanity/base/schema')
const schema = schemaMod.default || schemaMod
const type = schema.get(typeName)
if (!type) return null
return type
}
interface DocumentPanelProps {
footerHeight: number | null
rootElement: HTMLDivElement | null
}
const Scroller = styled(ScrollContainer)<{$disabled: boolean}>(({$disabled}) => {
if ($disabled) {
return {height: '100%'}
}
return css`
height: 100%;
overflow: auto;
position: relative;
scroll-behavior: smooth;
outline: none;
`
})
export const DocumentPanel = function DocumentPanel(props: DocumentPanelProps) {
const {footerHeight, rootElement} = props
const {
activeViewId,
displayed,
documentId,
documentSchema,
editState,
value,
views,
ready,
documentType,
} = useDocumentPane()
const {collapsed: layoutCollapsed} = usePaneLayout()
const parentPortal = usePortal()
const {features} = useDeskTool()
const [headerElement, setHeaderElement] = useState(null)
const headerRect = useElementRect(headerElement)
const portalRef = useRef(null)
const [documentScrollElement, setDocumentScrollElement] = useState(null)
const requiredPermission = value._createdAt ? 'update' : 'create'
const liveEdit = useMemo(() => Boolean(getSchemaType(documentType)?.liveEdit), [documentType])
const docPermissionsInput = useMemo(() => {
return {...value, _id: liveEdit ? 'dummy-id' : 'drafts.dummy-id'}
}, [liveEdit, value])
const [permissions, isPermissionsLoading] = useDocumentValuePermissions({
document: docPermissionsInput,
permission: requiredPermission,
})
const activeView = useMemo(
() => views.find((view) => view.id === activeViewId) || views[0] || {type: 'form'},
[activeViewId, views]
)
// Use a local portal container when split panes is supported
const portalElement: HTMLElement | null = features.splitPanes
? portalRef.current || parentPortal.element
: parentPortal.element
Stian Thorbjørnsen (born 10 March 1982 in Gressvik), known under the stage name Staysman, is a Norwegian singer, songwriter and presenter.
Background
Together with Lasse Jensen, Thorbjørnsen formed the duo Staysman & Lazz, before they disbanded in 2020. The duo was discovered when they took part in a singing competition organized by the weekly magazine Se og Hør with the song "Uten sko" in 2010. In 2015, they participated in Melodi Grand Prix with his song "En goodt stekt pizza" and ended up in third place in the final.
He became known to a larger audience in 2012, when he participated in season 4 of the TV3 series Paradise Hotel. He was a participant in the TV3 series "Robinsonekspedisjonen" in 2013.
In 2015, he participated in the program Skal vi danse on TV 2, where he finished in second place. In 2018 and 2019, he led the question program 10 at the top on NRK. In the spring of 2021, Thorbjørnsen was part of Hver gang vi møtes on TV 2, together with the artists Arne Hurlen, Hanne Krogh, Maria Mena, Agnete Saba, Trygve Skaug and Hkeem.
In 2023, he led Melodi Grand Prix 2023 together with Arian Engebø.
Discography
Own publications
Staysvan (2014), with Katastrofe
Good Vibes 2014 (2014), with Björklund and Morgan Sulele
Vardafjell 2014 (2014)
Bleik og sur (2014), with Katastrofe & M.M.B
Et drikkehjem 2014 (2014), with Martin Tungevaag
Smaker så godt (2014), with Bøbben
10 liter kaffe og hjemmebrent (2015), with Folloruss 2015
Step Brothers 2016 (2016), with Adrian Emile and Carl León ft. Morgan Sulele
Baris (Staysman Remix) (2017), with Mr. Pimp-Lotion and Oral Bee
Trang trikot (2018), with Boblandslaget, Vegard Harm, Svein Østvik & Emil Gukild
Staysman & Lazz
Albums
1998–2008 (2013)
Helt sykt store hits (2014)
Helt sykt Vol. 2 (2017)
The Essential Staysman & Lazz (2021)
Singles/EPs
import AxiosLogic from '@/services/AxiosLogic.js'
const labels = {
namespaced: true,
state: {
labels: []
},
mutations: {
SET_LABELS(state, data) {
state.labels = data
},
ADD_LABEL(state, payload) {
state.labels.push(payload)
},
DELETE_LABEL(state, index) {
state.labels.splice(index, 1)
},
RENAME_LABEL(state, payload) {
let newTitle = payload.newTitle
let index = payload.index
state.labels[index].title = newTitle
}
},
actions: {
loadLabels({ commit }) {
AxiosLogic.getLabels()
.then(res => {
commit('SET_LABELS', res.data)
})
.catch(error => console.log(error))
},
postLabel({ commit }, payload) {
return AxiosLogic.postLabel(payload)
.then(() => {
commit('ADD_LABEL', payload)
})
.catch(error => console.log(error))
},
deleteLabel({ commit }, payload) {
return AxiosLogic.deleteLabel(payload.id)
.then(() => {
commit('DELETE_LABEL', payload.index)
})
.catch(error => console.log(error))
},
renameLabel({ commit }, payload) {
return AxiosLogic.patchLabel(payload.id, { title: payload.newTitle })
.then(() => {
commit('RENAME_LABEL', payload)
})
.catch(error => console.log(error))
}
}
}
export default labels
Meaning of %04X in C and how to write the same in java
In the java project i am working on, some portion of the project was written previously by someone else in C and now i need to write the same in Java.
There is a statement in C code for printing to a file:
fprintf(ff, "%04X ", image[y*width+x]);
Firstly i am not sure about the meaning of %04X. I think it means that if image[i] has length five or more then print only leftmost four chararacters. To do the same in Java i thought about masking the value using and operation
image[i] & 0xFFFF
Can someone please tell me the correct meaning of %04X and how to do the same in Java? Thanks.
import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { SpringBootAngularCrudComponent } from './spring-boot-angular-crud.component';
describe('SpringBootAngularCrudComponent', () => {
let component: SpringBootAngularCrudComponent;
let fixture: ComponentFixture;
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [ SpringBootAngularCrudComponent ]
})
.compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(SpringBootAngularCrudComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
});
SELECT data FROM two tables in MySQL
What I have: The next structure:
table_zero
-> id (PRIMARY with auto increment)
-> other
table_1
-> id (foreign key to table zero id)
-> varchar(80) Example value: (aahellobbb)
-> one_field
table_2
-> id (foreign key to table zero id)
-> varchar(160) Example value: (aaececehellobbb)
-> other_field
What I want: Search and get an (id,varchar) array containing all matches with the LIKE '%str%' on the varchar field. For example, if I search with the "hello" string, then I should get both example values with their respective ids. These ids are always going to be different, since they are references to a PRIMARY KEY.
What I tried : I tried with UNION ALL but it does not work with LIMITS in my example.
from python_dwd.additionals.functions import check_parameters, retrieve_time_resolution_from_filename,\
retrieve_parameter_from_filename, retrieve_period_type_from_filename, determine_parameters
from python_dwd.enumerations.period_type_enumeration import PeriodType
from python_dwd.enumerations.time_resolution_enumeration import TimeResolution
from python_dwd.enumerations.parameter_enumeration import Parameter
def test_check_parameters():
assert check_parameters(Parameter.PRECIPITATION, TimeResolution.MINUTE_10, PeriodType.HISTORICAL)
def test_retrieve_time_resolution_from_filename():
assert retrieve_time_resolution_from_filename('10minutenwerte_2019.csv') == TimeResolution.MINUTE_10
assert retrieve_time_resolution_from_filename('1minutenwerte_2019.csv') == TimeResolution.MINUTE_1
assert retrieve_time_resolution_from_filename('tageswerte__2019.csv') == TimeResolution.DAILY
assert retrieve_time_resolution_from_filename('tageswerte2019.csv') == None
def test_retrieve_parameter_from_filename():
assert retrieve_parameter_from_filename('bidb_!!_st_.xml', TimeResolution.HOURLY) == Parameter.SOLAR
assert retrieve_parameter_from_filename('10000_historical_nieder_.txt', TimeResolution.MINUTE_1) \
== Parameter.PRECIPITATION
assert retrieve_parameter_from_filename('klima_climate_kl_.csv', TimeResolution.DAILY) == Parameter.CLIMATE_SUMMARY
assert retrieve_parameter_from_filename('klima_climate_kl_.csv', TimeResolution.MINUTE_1) is None
def test_retrieve_period_type_from_filename():
assert retrieve_period_type_from_filename('_hist.xml') == PeriodType.HISTORICAL
assert retrieve_period_type_from_filename('no_period_type') is None
def test_determine_parameters():
assert determine_parameters('10minutenwerte_hist_nieder_') == (Parameter.PRECIPITATION,
TimeResolution.MINUTE_10,
PeriodType.HISTORICAL)
from audio import Stream, AudioSettings
class PhraseRecognizer(object):
def __init__(self, config, audio_settings: AudioSettings):
self._config = config
self._audio_settings = audio_settings
def get_config(self):
return self._config
def get_audio_settings(self) -> AudioSettings:
return self._audio_settings
async def recognize(self, stream: Stream, recv_callback):
raise Exception('Not implemented "recognize"')
class HotwordRecognizer(object):
def __init__(self, config):
self._config = config
def get_audio_settings(self) -> AudioSettings:
raise Exception('Not implemented "get_audio_settings"')
def start(self):
pass
def is_hotword(self, raw_frames) -> bool:
raise Exception('Not implemented "is_hotword"')
class VADRecognizer(object):
def __init__(self, config):
self._config = config
def get_audio_settings(self) -> AudioSettings:
raise Exception('Not implemented "get_audio_settings"')
def is_speech(self, raw_frames) -> bool:
raise Exception('Not implemented "is_speech"')
class PhraseRecognizerConfig(object):
def create_phrase_recognizer(self) -> PhraseRecognizer:
raise Exception('Not implemented "create_phrase_recognizer"')
class HotwordRecognizerConfig(object):
def create_hotword_recognizer(self) -> HotwordRecognizer:
raise Exception('Not implemented "create_hotword_recognizer"')
class VADRecognizerConfig(object):
def create_vad_recognizer(self) -> VADRecognizer:
raise Exception('Not implemented "create_vad_recognizer"')
Kuei Chih-Hung (桂治洪, aka Kwei Chi Hung, Gui Zhi-Hong, Gwai Chi-hung) (20 December 1937 – 1 October 1999) was a filmmaker who worked for the Hong Kong-based Shaw Brothers Studios, directing more than 40 films throughout the late 1960s, 1970s and early 1980s. Kuei found critical and commercial success working in a variety of genres, including the hard-boiled crime drama of The Teahouse (1974) and its sequel, Big Brother Cheng (1975), wuxia film Killer Constable (1981), The Killer Snakes (1975) and Hex (1980). Kuei often depicted the poverty of the public housing system, police corruption and colonial government rule.
Early life
Kuei was born in Guangzhou (in the southern Chinese province of Guangdong) on 20 December 1937. Kuei's passion for cinema began as a high school student in Hong Kong, where he would cobble together makeshift shorts from a shoebox projector and discarded film stock. After graduating from high school, he studied stage production and filmmaking at Taiwan's National School of the Arts, experimenting on several 8 mm films. After writing a few film scripts for the Taiwan film industry, Kuei joined the Shaw Brothers Studio in the early 1960s. Initially hired as an assistant director on two Taiwan-shot Shaw films, Lovers' Rock (1964) and Song of Orchid Island (1965), he then lead projects in Hong Kong and an apprenticeship in Japan, where Kuei continued to work.
Shaw Brothers career
At the large Shaw Brothers Studio, Kuei gained a reputation as one of the most promising assistant film directors on numerous Hong Kong productions. In 1970, at the age of 34, he finally got the opportunity to direct a feature, Love Song Over the Sea. Shot in Singapore and Malaysia, the troubled production was initially suspended after the film's star Peter Chen Ho, fell ill. The original director, Shi Mashan, left due to contractual reasons, allowing Kuei to step in. Pleased with his work on this film, the studio quickly gave him a number of directorial projects, including the musical comedy, A Time for Love and The Lady Professional (1971), both starring Lily Ho.
In 1973, he joined forces with the popular Shaw Brothers filmmaker, Chang Cheh, co-directing The Delinquent, an edgy action drama about a young dishwasher who falls into a life of crime. Though a collaboration between the two men, it is Kuei who is credited with the film's distinctive visual style, including the then pioneering use of on-location shoots in Hong Kong's gritty streets and public housing complexes. The film's success led to a string of early '70s hits with Kuei as the sole director, including the women-in prison exploitation flick, The Bamboo House of Dolls and the acclaimed vigilante drama, The Teahouse. He proved a versatile, imaginative filmmaker with a distinctive style that carried through to a number of diverse genres including comedy (The Bod Squad, Rat Catcher) and horror (Ghost Eyes).
// Get the service name to advertise in Consul
service, ok := conf["service"]
if !ok {
service = DefaultServiceName
}
if !hostnameRegex.MatchString(service) {
return nil, errors.New("service name must be valid per RFC 1123 and can contain only alphanumeric characters or dashes")
}
if logger.IsDebug() {
logger.Debug("config service set", "service", service)
}
// Get the additional tags to attach to the registered service name
tags := conf["service_tags"]
if logger.IsDebug() {
logger.Debug("config service_tags set", "service_tags", tags)
}
// Get the service-specific address to override the use of the HA redirect address
var serviceAddr *string
serviceAddrStr, ok := conf["service_address"]
if ok {
serviceAddr = &serviceAddrStr
}
if logger.IsDebug() {
logger.Debug("config service_address set", "service_address", serviceAddrStr)
}
checkTimeout := defaultCheckTimeout
checkTimeoutStr, ok := conf["check_timeout"]
if ok {
d, err := parseutil.ParseDurationSecond(checkTimeoutStr)
if err != nil {
return nil, err
}
min, _ := durationMinusBufferDomain(d, checkMinBuffer, checkJitterFactor)
if min < checkMinBuffer {
return nil, fmt.Errorf("consul check_timeout must be greater than %v", min)
}
checkTimeout = d
if logger.IsDebug() {
logger.Debug("config check_timeout set", "check_timeout", d)
}
}
// Configure the client
consulConf := api.DefaultConfig()
// Set MaxIdleConnsPerHost to the number of processes used in expiration.Restore
consulConf.Transport.MaxIdleConnsPerHost = consts.ExpirationRestoreWorkerCount
SetupSecureTLS(context.Background(), consulConf, conf, logger, false)
consulConf.HttpClient = &http.Client{Transport: consulConf.Transport}
client, err := api.NewClient(consulConf)
if err != nil {
return nil, fmt.Errorf("client setup failed: %w", err)
}
// Setup the backend
c := &serviceRegistration{
Client: client,
logger: logger,
serviceName: service,
serviceTags: strutil.ParseDedupLowercaseAndSortStrings(tags, ","),
serviceAddress: serviceAddr,
checkTimeout: checkTimeout,
disableRegistration: disableRegistration,
notifyActiveCh: make(chan struct{}),
notifySealedCh: make(chan struct{}),
notifyPerfStandbyCh: make(chan struct{}),
notifyInitializedCh: make(chan struct{}),
isActive: atomicB.NewBool(state.IsActive),
isSealed: atomicB.NewBool(state.IsSealed),
isPerfStandby: atomicB.NewBool(state.IsPerformanceStandby),
isInitialized: atomicB.NewBool(state.IsInitialized),
}
return c, nil
}
func SetupSecureTLS(ctx context.Context, consulConf *api.Config, conf map[string]string, logger log.Logger, isDiagnose bool) error {
if addr, ok := conf["address"]; ok {
consulConf.Address = addr
if logger.IsDebug() {
logger.Debug("config address set", "address", addr)
}
Azincourt (), historically known in English as Agincourt ( ), is a commune in the Pas-de-Calais department in northern France. It is situated north-west of Saint-Pol-sur-Ternoise on the D71 road between Hesdin and Fruges.
The Late Medieval Battle of Agincourt between the English and the French took place in the commune in 1415.
Toponym
The name is attested as Aisincurt in 1175, derived from a Germanic masculine name Aizo, Aizino and the early Northern French word curt (which meant a farm with a courtyard; derived from the Late Latin cortem). The name has no etymological link with Agincourt, Meurthe-et-Moselle (attested as Egincourt 875), which is derived separately from another Germanic male name *Ingin-.
History
Azincourt is known for being near the site of the battle fought on 25 October 1415 in which the army led by King Henry V of England defeated the forces led by Charles d'Albret on behalf of Charles VI of France, which has gone down in history as the Battle of Agincourt. According to M. Forrest, the French knights were so encumbered by their armour that they were exhausted even before the start of the battle.
After he became king in 1509, Henry VIII is purported to have commissioned an English translation of a Life of Henry V so that he could emulate him, on the grounds that he thought that launching a campaign against France would help him to impose himself on the European stage. In 1513, Henry VIII crossed the English Channel, stopping by at Azincourt.
The battle, as was the tradition, was named after a nearby castle called Azincourt. The castle has since disappeared and the settlement now known as Azincourt adopted the name in the seventeenth century.
John Cassell wrote in 1857 that "the village of Azincourt itself is now a group of dirty farmhouses and wretched cottages, but where the hottest of the battle raged, between that village and the commune of Tramecourt, there still remains a wood precisely corresponding with the one in which Henry placed his ambush; and there are yet existing the foundations of the castle of Azincourt, from which the king named the field."
Population
Sights
The original battlefield museum in the village featured model knights made out of Action Man figures. This has now been replaced by the Centre historique médiéval d'Azincourt (CHM)a more professional museum, conference centre and exhibition space incorporating laser, video, slide shows, audio commentaries, and some interactive elements. The museum building is shaped like a longbow similar to those used at the battle by archers under King Henry.
Custom Validator not firing
I realize there are lots of similar posts, however I have not found one that has worked for me unfortunately. Basically, I have an asp:customvalidator that I am trying to add to a validationgroup with other validators so that all error messages appear in the same alert. Here is the customvalidator
<asp:TextBox runat="server" ID="txtVideo1Url" Columns="20" Width="98%" />
<asp:CustomValidator runat="server" ID="valURL1" ControlToValidate="txtVideo1Url" OnServerValidate="txtVideo1Url_ServerValidate" Display="None" ValidationGroup="submission" />
and here is the event
protected void txtVideo1Url_ServerValidate(object sender, ServerValidateEventArgs e)
{
e.IsValid = false;
valURL1.Text = "FAIL!";
}
The event isn't firing at all and I have no idea why. Once I can get the event firing I can put some actual logic into it, lol
UPDATE: I've noticed that I am now able to get the event firing, however the validationsummary is set to display all errors in a messagebox and this error isn't getting added to the messagebox.
JS: "The callee (server [not server application]) is not available and disappeared." accessing window.opener
In our (quite large and old) ASP.NET application we use a lot of pages loaded into frames, iframes, and modal dialogs (using window.showModalDialog). We are starting to see the error above quite a bit, and I can't seem to find a single rational explanation for it anywhere.
Popup Blockers. Nope. We're not running them. Not even the built-in blocker.
Trusted Zone. Nope. The application runs on LocalHost right now, and it's in the trusted sites list.
Stray Cosmic Rays. Possible, but not probable. It's way too consistent.
I did eventually find the error message buried on Microsoft's site in some dusty tome about retrieving automation error message information. In it, they were talking about Excel, and they said: "In this example, Microsoft Excel is the server application. Referencing a workbook object once it is destroyed (or closed) generates the error. "
That is probably as close as I've ever come to an explanation for the cause of the error, without a real, concrete explanation. Someone tried to use something after their reference to it was disposed of. Oddly, you can still see the windows on the screen. Curiously, however, this smacks suspiciously to me of the accepted answer to this .
So here's what happens.
Page A is the main page.
PageA displays PageB in a frame. PageB is a toolbar.
PageA displays PageC in another frame. That's the content.
PageC displays PageD in a nonmodal dialog.
PageD, for reasons unknown to me, wants to modify the controls in PageB. It's trying to use window.opener to do that, and failing horribly.
If someone could enlighten me as to why this is the case (the code works in FF), I'd appreciate it.
Unable to set SCSS variable to CSS variable?
Consider the following SCSS:
$color-black: #000000;
body {
--color: $color-black;
}
When it is compiled with node-sass version 4.7.2 , it produces following CSS:
body {
--color: #000000;
}
When I compile the same SCSS with version 4.8.3 or higher , it produces following:
body {
--color: $color-black;
}
What am I missing? I checked release logs, but could not found anything useful. Also, I wonder if this change is genuine why does it have only minor version change? Should it not be a major release?
Also, what is my alternative? Should I use Interpolation ?
#ifndef POSIX_TIME_CONVERSION_HPP___
#define POSIX_TIME_CONVERSION_HPP___
/* Copyright (c) 2002-2005 CrystalClear Software, Inc.
* Use, modification and distribution is subject to the
* Boost Software License, Version 1.0. (See accompanying
* file LICENSE_1_0.txt or http://www.boost.org/LICENSE_1_0.txt)
* Author: Jeff Garland, Bart Garst
* $Date$
*/
#include
#include
#include
#include
#include
#include
#include // absolute_value
#include
namespace boost {
namespace posix_time {
//! Function that converts a time_t into a ptime.
inline
ptime from_time_t(std::time_t t)
{
return ptime(gregorian::date(1970,1,1)) + seconds(t);
}
//! Function that converts a ptime into a time_t
inline
std::time_t to_time_t(ptime pt)
{
return (pt - ptime(gregorian::date(1970,1,1))).total_seconds();
}
//! Convert a time to a tm structure truncating any fractional seconds
inline
std::tm to_tm(const boost::posix_time::ptime& t) {
std::tm timetm = boost::gregorian::to_tm(t.date());
boost::posix_time::time_duration td = t.time_of_day();
timetm.tm_hour = td.hours();
timetm.tm_min = td.minutes();
timetm.tm_sec = td.seconds();
timetm.tm_isdst = -1; // -1 used when dst info is unknown
return timetm;
}
//! Convert a time_duration to a tm structure truncating any fractional seconds and zeroing fields for date components
inline
std::tm to_tm(const boost::posix_time::time_duration& td) {
std::tm timetm;
std::memset(&timetm, 0, sizeof(timetm));
timetm.tm_hour = date_time::absolute_value(td.hours());
timetm.tm_min = date_time::absolute_value(td.minutes());
timetm.tm_sec = date_time::absolute_value(td.seconds());
timetm.tm_isdst = -1; // -1 used when dst info is unknown
return timetm;
}
//! Convert a tm struct to a ptime ignoring is_dst flag
inline
ptime ptime_from_tm(const std::tm& timetm) {
boost::gregorian::date d = boost::gregorian::date_from_tm(timetm);
return ptime(d, time_duration(timetm.tm_hour, timetm.tm_min, timetm.tm_sec));
}
#if defined(BOOST_HAS_FTIME)
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (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.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is Mozilla Communicator client code, released
* March 31, 1998.
*
* The Initial Developer of the Original Code is
* Netscape Communications Corporation.
* Portions created by the Initial Developer are Copyright (C) 1998
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
/**
File Name: 15.5.4.8-1.js
ECMA Section: 15.5.4.8 String.prototype.split( separator )
Description:
Returns an Array object into which substrings of the result of converting
this object to a string have been stored. The substrings are determined by
searching from left to right for occurrences of the given separator; these
occurrences are not part of any substring in the returned array, but serve
to divide up this string value. The separator may be a string of any length.
As a special case, if the separator is the empty string, the string is split
up into individual characters; the length of the result array equals the
length of the string, and each substring contains one character.
If the separator is not supplied, then the result array contains just one
string, which is the string.
Author: christine@netscape.com, pschwartau@netscape.com
Date: 12 November 1997
Modified: 14 July 2002
Reason: See http://bugzilla.mozilla.org/show_bug.cgi?id=155289
ECMA-262 Ed.3 Section 15.5.4.14
The length property of the split method is 2
*
*/
ng rate')
parser.add_argument('--weight-decay', '-wd', dest='weight_decay', action='store',
default=0.0,
help='weight decay')
parser.add_argument('--momentum', '-mm', dest='momentum', action='store',
default=0.0,
help='momentum')
parser.add_argument('--plateau', '-pt', dest='plateau', action='store',
default=1000,
help='Robbins Munro Schedule plateau length')
parser.add_argument('--hidden', dest='num_hidden', action='store',
default=16,
help='Number of hidden units')
parser.add_argument('--supernode-samples', '-ss', dest='supernode_samples', action='store',
default=1,
help='Number of samples to include in the supernode')
parser.add_argument('--gpu-id', dest='gpu_id', action='store',
default=-1,
help='gpu_id')
parser.add_argument('--gpu-limit', dest='gpu_limit', action='store',
default=18,
help='gpu_limit')
parser.add_argument('--filename', dest='filename', action='store',
default='temp_local',
help='filename')
parser.add_argument('--final-likelihood', dest='final_likelihood', action='store_const',
const=True, default=False,
help='compute final likelihood')
parser.add_argument('--log-tour', dest='LOG_TOUR', action='store_const',
const=True, default=False,
help='LOG_TOUR')
parser.add_argument('--name', dest='name', action='store',
default=None,
help='Name this run')
args = parser.parse_args()
return args.LOCAL, args.BASE_FOLDER, args
LOCAL, BASE_FOLDER, ARGS = parse_top_level_arguments()
print("Config.BASE_FOLDER=%s" % BASE_FOLDER)
print("Config.LOCAL=%s" % LOCAL)
DATA_FOLDER = BASE_FOLDER + 'data/'
MODEL_FOLDER = BASE_FOLDER + 'data/model/'
OUTPUT_FOLDER = BASE_FOLDER + 'output/'
MNIST_FOLDER = BASE_FOLDER + 'py/MNIST_data/'
PLOT_OUTPUT_FOLDER = BASE_FOLDER + 'plots/'
SQLITE_FILE = DATA_FOLDER + 'results.db'
SERVER_SQLITE_FILE = DATA_FOLDER + 'results_server.db' if LOCAL else SQLITE_FILE
GPU_LIMIT = int(ARGS.gpu_limit)
USE_GPU = torch.cuda.is_available() and not LOCAL
LOG_TOUR = ARGS.LOG_TOUR
TOUR_LENGTHS_TABLE = "TOUR_LENGTH_DISTRIBUTIONS"
# These are hardcoded for the MNIST dataset
WIDTH = 28
HEIGHT = 28
# These options do not work right now, we'll fix them soon
PIN = False
GPU_ID = int(ARGS.gpu_id) if int(ARGS.gpu_id) >= 0 else None
// Token provides a parsed token kind and value. Values are provided by the
// different accessor methods.
type Token struct {
// Kind of the Token object.
kind Kind
// attrs contains metadata for the following Kinds:
// Name: hasSeparator bit and one of NameKind.
// Scalar: one of numberValue, stringValue, literalValue.
attrs uint8
// numAttrs contains metadata for numberValue:
// - highest bit is whether negative or positive.
// - lower bits indicate one of numDec, numHex, numOct, numFloat.
numAttrs uint8
// pos provides the position of the token in the original input.
pos int
// raw bytes of the serialized token.
// This is a subslice into the original input.
raw []byte
// str contains parsed string for the following:
// - stringValue of Scalar kind
// - numberValue of Scalar kind
// - TypeName of Name kind
str string
}
// Kind returns the token kind.
func (t Token) Kind() Kind {
return t.kind
}
// RawString returns the read value in string.
func (t Token) RawString() string {
return string(t.raw)
}
// Pos returns the token position from the input.
func (t Token) Pos() int {
return t.pos
}
// NameKind returns IdentName, TypeName or FieldNumber.
// It panics if type is not Name.
func (t Token) NameKind() NameKind {
if t.kind == Name {
return NameKind(t.attrs &^ hasSeparator)
}
panic(fmt.Sprintf("Token is not a Name type: %s", t.kind))
}
// HasSeparator returns true if the field name is followed by the separator char
// ':', else false. It panics if type is not Name.
func (t Token) HasSeparator() bool {
if t.kind == Name {
return t.attrs&hasSeparator != 0
}
panic(fmt.Sprintf("Token is not a Name type: %s", t.kind))
}
// IdentName returns the value for IdentName type.
func (t Token) IdentName() string {
if t.kind == Name && t.attrs&uint8(IdentName) != 0 {
return string(t.raw)
}
panic(fmt.Sprintf("Token is not an IdentName: %s:%s", t.kind, NameKind(t.attrs&^hasSeparator)))
}
// TypeName returns the value for TypeName type.
func (t Token) TypeName() string {
if t.kind == Name && t.attrs&uint8(TypeName) != 0 {
return t.str
}
panic(fmt.Sprintf("Token is not a TypeName: %s:%s", t.kind, NameKind(t.attrs&^hasSeparator)))
}
// FieldNumber returns the value for FieldNumber type. It returns a
// non-negative int32 value. Caller will still need to validate for the correct
// field number range.
func (t Token) FieldNumber() int32 {
if t.kind != Name || t.attrs&uint8(FieldNumber) == 0 {
panic(fmt.Sprintf("Token is not a FieldNumber: %s:%s", t.kind, NameKind(t.attrs&^hasSeparator)))
}
// Following should not return an error as it had already been called right
// before this Token was constructed.
num, _ := strconv.ParseInt(string(t.raw), 10, 32)
return int32(num)
}
// String returns the string value for a Scalar type.
func (t Token) String() (string, bool) {
if t.kind != Scalar || t.attrs != stringValue {
return "", false
}
return t.str, true
}
// Copyright (c) 2012 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.
#include "remoting/host/desktop_session_proxy.h"
#include "base/compiler_specific.h"
#include "base/logging.h"
#include "base/process/process_handle.h"
#include "base/memory/shared_memory.h"
#include "base/single_thread_task_runner.h"
#include "ipc/ipc_channel_proxy.h"
#include "ipc/ipc_message_macros.h"
#include "remoting/base/capabilities.h"
#include "remoting/host/chromoting_messages.h"
#include "remoting/host/client_session.h"
#include "remoting/host/client_session_control.h"
#include "remoting/host/desktop_session_connector.h"
#include "remoting/host/ipc_audio_capturer.h"
#include "remoting/host/ipc_input_injector.h"
#include "remoting/host/ipc_screen_controls.h"
#include "remoting/host/ipc_video_frame_capturer.h"
#include "remoting/proto/audio.pb.h"
#include "remoting/proto/control.pb.h"
#include "remoting/proto/event.pb.h"
#include "third_party/webrtc/modules/desktop_capture/desktop_frame.h"
#include "third_party/webrtc/modules/desktop_capture/desktop_geometry.h"
#include "third_party/webrtc/modules/desktop_capture/shared_memory.h"
#if defined(OS_WIN)
#include "base/win/scoped_handle.h"
#endif // defined(OS_WIN)
const bool kReadOnly = true;
const char kSendInitialResolution[] = "sendInitialResolution";
const char kRateLimitResizeRequests[] = "rateLimitResizeRequests";
namespace remoting {
class DesktopSessionProxy::IpcSharedBufferCore
: public base::RefCountedThreadSafe {
public:
IpcSharedBufferCore(int id,
base::SharedMemoryHandle handle,
base::ProcessHandle process,
size_t size)
: id_(id),
#if defined(OS_WIN)
shared_memory_(handle, kReadOnly, process),
#else // !defined(OS_WIN)
shared_memory_(handle, kReadOnly),
#endif // !defined(OS_WIN)
size_(size) {
if (!shared_memory_.Map(size)) {
LOG(ERROR) << "Failed to map a shared buffer: id=" << id
#if defined(OS_WIN)
<< ", handle=" << handle
#else
<< ", handle.fd=" << handle.fd
#endif
<< ", size=" << size;
}
}
int id() { return id_; }
size_t size() { return size_; }
void* memory() { return shared_memory_.memory(); }
webrtc::SharedMemory::Handle handle() {
#if defined(OS_WIN)
return shared_memory_.handle();
#else
return shared_memory_.handle().fd;
#endif
}
private:
virtual ~IpcSharedBufferCore() {}
friend class base::RefCountedThreadSafe;
int id_;
base::SharedMemory shared_memory_;
size_t size_;
DISALLOW_COPY_AND_ASSIGN(IpcSharedBufferCore);
};
import React from "react";
import Link from "gatsby-link";
import PropTypes from "prop-types";
import injectSheet from "react-jss";
import LazyLoad from "react-lazyload";
const styles = theme => ({
listItem: {
margin: "0 0 .7em 0",
transition: "height 1s",
[`@media (min-width: ${theme.mediaQueryTresholds.M}px)`]: {
margin: "0 0 1.5rem 0"
},
[`@media (min-width: ${theme.mediaQueryTresholds.L}px)`]: {
".moving-featured &, .is-aside &": {
margin: "0 0 0 0"
}
}
},
listLink: {
display: "flex",
alignContent: "center",
alignItems: "center",
justifyContent: "flex-start",
flexDirection: "row",
padding: ".7em 1em .7em 1em",
color: theme.navigator.colors.postsListItemLink,
"@media (hover: hover)": {
"&:hover": {}
}
},
listItemPointer: {
position: "relative",
flexShrink: 0,
overflow: "hidden",
borderRadius: "10%",
width: "80px",
height: "80px",
margin: "0",
transition: "all .5s",
"& img": {
width: "100%",
height: "100%"
},
[`@media (min-width: ${theme.mediaQueryTresholds.M}px)`]: {
marginRight: ".5em",
width: "90px",
height: "90px"
},
[`@media (min-width: ${theme.mediaQueryTresholds.L}px)`]: {
marginRight: ".6em",
width: "100px",
height: "100px",
transition: "all .3s",
transitionTimingFunction: "ease",
".moving-featured &, .is-aside &": {
width: "30px",
height: "30px"
}
}
},
listItemText: {
margin: "0 0 0 1.5em",
flexGrow: 1,
display: "flex",
flexDirection: "column",
width: "100%",
"& h1": {
lineHeight: 1.15,
fontWeight: 500,
letterSpacing: "-0.03em",
margin: 0,
fontSize: `${theme.navigator.sizes.postsListItemH1Font}em`,
[`@media (min-width: ${theme.mediaQueryTresholds.M}px)`]: {
fontSize: `${theme.navigator.sizes.postsListItemH1Font *
theme.navigator.sizes.fontIncraseForM}em`
},
[`@media (min-width: ${theme.mediaQueryTresholds.L}px)`]: {
fontSize: `${theme.navigator.sizes.postsListItemH1Font *
theme.navigator.sizes.fontIncraseForL}em`,
".moving-featured &, .is-aside &": {
fontSize: "1em",
fontWeight: 400
}
}
},
"& h2": {
lineHeight: 1.2,
display: "block",
fontSize: `${theme.navigator.sizes.postsListItemH2Font}em`,
margin: ".3em 0 0 0",
[`@media (min-width: ${theme.mediaQueryTresholds.M}px)`]: {
fontSize: `${theme.navigator.sizes.postsListItemH2Font *
theme.navigator.sizes.fontIncraseForM}em`
},
[`@media (min-width: ${theme.mediaQueryTresholds.L}px)`]: {
fontSize: `${theme.navigator.sizes.postsListItemH2Font *
theme.navigator.sizes.fontIncraseForL}em`,
".moving-featured &, .is-aside &": {
display: "none"
}
}
},
[`@media (min-width: ${theme.m
Articles published in the 1970s and later suggest that Debierne's results published in 1904 conflict with those reported in 1899 and 1900. Furthermore, the now-known chemistry of actinium precludes its presence as anything other than a minor constituent of Debierne's 1899 and 1900 results; in fact, the chemical properties he reported make it likely that he had, instead, accidentally identified protactinium, which would not be discovered for another fourteen years, only to have it disappear due to its hydrolysis and adsorption onto his laboratory equipment. This has led some authors to advocate that Giesel alone should be credited with the discovery. A less confrontational vision of scientific discovery is proposed by Adloff. He suggests that hindsight criticism of the early publications should be mitigated by the then nascent state of radiochemistry: highlighting the prudence of Debierne's claims in the original papers, he notes that nobody can contend that Debierne's substance did not contain actinium. Debierne, who is now considered by the vast majority of historians as the discoverer, lost interest in the element and left the topic. Giesel, on the other hand, can rightfully be credited with the first preparation of radiochemically pure actinium and with the identification of its atomic number 89.
The name actinium originates from the Ancient Greek aktis, aktinos (ακτίς, ακτίνος), meaning beam or ray. Its symbol Ac is also used in abbreviations of other compounds that have nothing to do with actinium, such as acetyl, acetate and sometimes acetaldehyde.
Properties
Actinium is a soft, silvery-white, radioactive, metallic element. Its estimated shear modulus is similar to that of lead. Owing to its strong radioactivity, actinium glows in the dark with a pale blue light, which originates from the surrounding air ionized by the emitted energetic particles. Actinium has similar chemical properties to lanthanum and other lanthanides, and therefore these elements are difficult to separate when extracting from uranium ores. Solvent extraction and ion chromatography are commonly used for the separation.
The first element of the actinides, actinium gave the set its name, much as lanthanum had done for the lanthanides. The actinides are much more diverse than the lanthanides and therefore it was not until 1945 that the most significant change to Dmitri Mendeleev's periodic table since the recognition of the lanthanides, the introduction of the actinides, was generally accepted after Glenn T. Seaborg's research on the transuranium elements (although it had been proposed as early as 1892 by British chemist Henry Bassett).
React Native "onViewableItemsChanged" not working while scrolling on dynamic data
I have a React Native FlatList.
base on Documentation I used onViewableItemsChanged for getting the current showing item on the screen. but while scrolling or when scrolling stops nothing happens and I can't get the current Id.
How Can I use it in correct way?
export default class TimeLine extends Component {
constructor(props) {
super(props);
this.renderTimeline = this.renderTimeline.bind(this);
this.state = {
timeline: [],
};
this.handleViewableItemsChanged = this.handleViewableItemsChanged.bind(this);
this.viewabilityConfig = {
itemVisiblePercentThreshold: 50,
};
}
...
renderTimelineList(timeline_data) {
return (
<Card key={timeline_data.unique_id}>
<CardItem style={styles.header}>
<Left>
<Icon type="MaterialIcons" name={this.timelineIcon(timeline_data.type)}/>
<Body>
<Text style={styles.header_title}>{timeline_data.title}</Text>
</Body>
</Left>
</CardItem>
<CardItem>
{this.renderTimeline(timeline_data)}
</CardItem>
<CardItem>
<Left>
<Icon small name="time" style={styles.small_font}/>
<Text note style={styles.small_font}>{timeline_data.release_date}</Text>
</Left>
<Right>
<Text note style={styles.small_font}>{timeline_data.duration}</Text>
</Right>
</CardItem>
</Card>
);
}
render() {
return (
<Container>
<Content>
<FlatList
key={this.state.key}
onViewableItemsChanged={this.handleViewableItemsChanged}
viewabilityConfig={this.viewabilityConfig}
data={this.state.timeline}
renderItem={({item}) => this.renderTimelineList(item)}
/>
</Content>
</Container>
);
};
}
import numpy
import mysql.connector
from sklearn.preprocessing import LabelEncoder
from sklearn.preprocessing import OneHotEncoder
from sklearn import tree
##--------------------------Catch Data from data base--------------------------------
cnx = mysql.connector.connect(user = [type your user] , password = [type your password] ,
host = [type your host] , database = [type your database name] )
cur = cnx.cursor()
cur.execute("SELECT Neighborhood, Area, rooms, Antiquity FROM specifications")
inputData = cur.fetchall()
cur.execute("SELECT Price FROM specifications")
outputData = cur.fetchall()
if cur:
cur.close()
if cnx:
cnx.close()
## TestData
newApartments = [['ولنجک', 120, '2','2'],
['میرداماد', 110, '2','0'],
['هروی', 200, '4','2']]
for i in newApartments: ## Add newApartments to input of table
inputData.append(i)
Neighborhood = list()
Area = list()
rooms = list()
Antiquity = list()
for i in inputData :
Neighborhood.append(i[0])
Area.append(i[1])
rooms.append(i[2])
Antiquity.append(i[3])
# Encode Neighborhood
values = numpy.array(Neighborhood)
# integer encode
labelEncoder = LabelEncoder()
integer_encoded = labelEncoder.fit_transform(values)
# binary encode
NeighborhoodOHE = OneHotEncoder(sparse=False)
integer_encoded = integer_encoded.reshape(len(integer_encoded), 1)
NeighborhoodOHE = NeighborhoodOHE.fit_transform(integer_encoded)
test= Area+rooms
x = numpy.column_stack((NeighborhoodOHE, Area,rooms, Antiquity))
y = outputData
print(x[1])
print(len(x))
print(len(x[1]))
temp = numpy.split(x, [(-1)*len(newApartments)])
x = temp[0]
newApartments_enc = temp[1]
# Start training and testing
clf = tree.DecisionTreeClassifier()
clf = clf.fit(x, y)
# Encode New Apartment
answer = clf.predict(newApartments_enc)
for i in range(len(answer)):
print("The price of Apartment in %s with %i metters Area, is approaximately %s Tomans." % (newApartments[i][0],newApartments[i][1], answer[i]))
/*
* Copyright 2009-2017 Alibaba Cloud 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.
*/
#ifndef ALIBABACLOUD_SMARTAG_MODEL_CREATEQOSPOLICYREQUEST_H_
#define ALIBABACLOUD_SMARTAG_MODEL_CREATEQOSPOLICYREQUEST_H_
#include
#include
#include
#include
#include
namespace AlibabaCloud {
namespace Smartag {
namespace Model {
class ALIBABACLOUD_SMARTAG_EXPORT CreateQosPolicyRequest : public RpcServiceRequest {
public:
CreateQosPolicyRequest();
~CreateQosPolicyRequest();
std::vector getDpiGroupIds() const;
void setDpiGroupIds(const std::vector &dpiGroupIds);
long getResourceOwnerId() const;
void setResourceOwnerId(long resourceOwnerId);
std::string getSourcePortRange() const;
void setSourcePortRange(const std::string &sourcePortRange);
std::string getSourceCidr() const;
void setSourceCidr(const std::string &sourceCidr);
std::string getDescription() const;
void setDescription(const std::string &description);
std::string getStartTime() const;
void setStartTime(const std::string &startTime);
std::string getDestCidr() const;
void setDestCidr(const std::string &destCidr);
std::vector getDpiSignatureIds() const;
void setDpiSignatureIds(const std::vector &dpiSignatureIds);
std::string getRegionId() const;
void setRegionId(const std::string ®ionId);
std::string getQosId() const;
void setQosId(const std::string &qosId);
std::string getResourceOwnerAccount() const;
void setResourceOwnerAccount(const std::string &resourceOwnerAccount);
std::string getIpProtocol() const;
void setIpProtocol(const std::string &ipProtocol);
std::string getOwnerAccount() const;
void setOwnerAccount(const std::string &ownerAccount);
std::string getEndTime() const;
void setEndTime(const std::string &endTime);
long getOwnerId() const;
void setOwnerId(long ownerId);
int getPriority() const;
void setPriority(int priority);
std::string getDestPortRange() const;
void setDestPortRange(const std::string &destPortRange);
std::string getName() const;
void setName(const std::string &name);
private:
std::vector dpiGroupIds_;
long resourceOwnerId_;
std::string sourcePortRange_;
std::string sourceCidr_;
std::string description_;
std::string startTime_;
std::string destCidr_;
std::vector
Get the list of installed packages by user in R
How we can get the list of installed packages by user in R along with its version?
I know about the command installed.packages() which will give information about all packages (base or non-base). But how we can get those installed by user to have something like this:
Package Version
X 3.01
Y 2.0.1
Z 1.0.2
For all user installed packages (i.e. those package you installed via install.packages("X"))
/*
* Copyright (C) 2016 Nishant Srivastava
*
* 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.github.nisrulz.sensey;
import static com.github.nisrulz.sensey.TouchTypeDetector.SCROLL_DIR_DOWN;
import static com.github.nisrulz.sensey.TouchTypeDetector.SCROLL_DIR_LEFT;
import static com.github.nisrulz.sensey.TouchTypeDetector.SCROLL_DIR_RIGHT;
import static com.github.nisrulz.sensey.TouchTypeDetector.SCROLL_DIR_UP;
import static com.github.nisrulz.sensey.TouchTypeDetector.SWIPE_DIR_DOWN;
import static com.github.nisrulz.sensey.TouchTypeDetector.SWIPE_DIR_LEFT;
import static com.github.nisrulz.sensey.TouchTypeDetector.SWIPE_DIR_RIGHT;
import static com.github.nisrulz.sensey.TouchTypeDetector.SWIPE_DIR_UP;
import static org.mockito.Mockito.*;
import android.content.Context;
import android.view.MotionEvent;
import com.github.nisrulz.sensey.TouchTypeDetector.TouchTypListener;
import org.junit.*;
import org.junit.runner.*;
import org.robolectric.RobolectricTestRunner;
import org.robolectric.RuntimeEnvironment;
@RunWith(RobolectricTestRunner.class)
public class TouchTypeDetectorTest {
private TouchTypListener mockListener;
private TouchTypeDetector testTouchTypeDetector;
@Test
public void detectNoScrollWhenEventCoorsAreEqual() {
MotionEvent ev1 = MotionEvent.obtain(10, 10, 0, 50, 2, 0);
MotionEvent ev2 = MotionEvent.obtain(10, 10, 0, 50, 2, 0);
testTouchTypeDetector.gestureListener.onScroll(ev1, ev2, 0, 0);
verifyNoMoreInteractions(mockListener);
}
@Test
public void detectNothingForSlightlyScrollDown() {
MotionEvent ev1 = MotionEvent.obtain(10, 10, 0, 0, 1, 0);
MotionEvent ev2 = MotionEvent.obtain(10, 10, 0, 0, 2, 0);
testTouchTypeDetector.gestureListener.onScroll(ev1, ev2, 0, 0);
verifyNoMoreInteractions(mockListener);
}
@Test
public void detectNothingForSlightlyScrollLeft() {
MotionEvent ev1 = MotionEvent.obtain(10, 10, 0, 1, 0, 0);
MotionEvent ev2 = MotionEvent.obtain(10, 10, 0, 2, 0, 0);
testTouchTypeDetector.gestureListener.onScroll(ev1, ev2, 0, 0);
verifyNoMoreInteractions(mockListener);
}