text
stringlengths 15
59.8k
| meta
dict |
---|---|
Q: Burger Menu Drop Down Navbar background colour First of all, I have not coded properly in around nine years, so I'm trying to re-learn from scratch pretty much.
I'm having an issue with the background colour of a drop down menu from a burger menu. The burger menu appears when you minimise the screen. I want the background to be white when you click the burger menu but instead it's coming out a dark grey.
In Codepen it is fine, the background is white. However, on my laptop in all the folders it comes out dark grey. So, I've uploaded the code onto Code Pen and all my folders to Github for folk to try and find the discrepancy which I've been really struggling to spot and understand.
enter code herehttps://codepen.io/cmc89/pen/RwoYZRR)
GitHub: https://github.com/cmc1989/website-toggle.git
<!DOCTYPE html>
<!--[if lt IE 7 ]><html lang="en" class="ie6"> <![endif]-->
<!--[if IE 7 ]><html lang="en" class="ie7"><![endif]-->
<!--[if IE 8 ]><html lang="en" class="ie8"><![endif]-->
<!--[if IE 9 ]><html lang="en" class="ie9"><![endif]-->
<!--[if (gt IE 9)|!(IE)]><!--><html lang="en"><!--<![endif]-->
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1, minimum-scale=1" />
<link rel="stylesheet" type="text/css" href="css/style.css"/>
<script src="js/script.js" defer></script>
<title>Website</title>
</head>
<body>
<div id="wrapper">
<nav class="navbar">
<div class="logo"><a href="home.html"><img src="images/logo.jpg"></a></div>
<a href="#" class="toggle-button">
<span class="bar"></span>
<span class="bar"></span>
<span class="bar"></span>
</a>
<div class="navbar-links">
<ul>
<li>
<a href="artwork.html">Artwork
</a>
<div class="underline"></div>
</li>
<li class="nav-link">
<a href="programming.html">Programming</a>
<div class="underline"></div>
</li>
<li class="nav-link">
<a href="writing.html">Writing</a>
<div class="underline"></div>
</li>
<li class="nav-link">
<a href="talking.html">Talking</a>
<div class="underline"></div>
</li>
<li class="nav-link">
<a href="production.html">Production</a>
<div class="underline"></div>
</li>
<li class="nav-link">
<a href="cv.html">CV</a>
<div class="underline"></div>
</li>
<li class="nav-link">
<a href="about.html">About</a>
<div class="underline"></div>
</li>
</ul>
</div>
</nav>
<div id="content">
<div class="grid-row">
<div class="col-4">
<div class="grid-card">
<img class="grid-card-image" src="images/artwork/americanfuneral2.png" />
<div class="grid-card-content">
<h3>A Feeling for the Organism (2020)</h3>
</div>
</div>
</div>
<div class="col-4">
<div class="grid-card">
<img class="grid-card-image" src="images/artwork/americanfuneral2.png" />
<div class="grid-card-content">
<h3>Organs (2020)</h3>
</div>
</div>
</div>
<div class="col-4">
<div class="grid-card">
<img class="grid-card-image" src="images/artwork/americanfuneral2.png" />
<div class="grid-card-content">
<h3>Private Lives (2019)</h3>
</div>
</div>
</div>
</div>
<div class="grid-row">
<div class="col-4">
<div class="grid-card">
<a href="thesethings.html"><img class="grid-card-image" src="images/artwork/americanfuneral2.png" /></a>
<div class="grid-card-content">
<h3>these were the things that made the step familiar (2019)</h3>
</div>
</div>
</div>
<div class="col-4">
<div class="grid-card">
<img class="grid-card-image" src="images/artwork/americanfuneral2.png" />
<div class="grid-card-content">
<h3>A Strange American Funeral (2019)</h3>
</div>
</div>
</div>
<div class="col-4">
<div class="grid-card">
<img class="grid-card-image" src="images/artwork/americanfuneral2.png" />
<div class="grid-card-content">
<h3>Handwave (2019)</h3>
</div>
</div>
</div>
</div>
<div class="grid-row">
<div class="col-4">
<div class="grid-card">
<img class="grid-card-image" src="images/artwork/americanfuneral2.png" />
<div class="grid-card-content">
<h3>playback (2018)</h3>
</div>
</div>
</div>
<div class="col-4">
<div class="grid-card">
<img class="grid-card-image" src="images/artwork/americanfuneral2.png" />
<div class="grid-card-content">
<h3>correct (2017)</h3>
</div>
</div>
</div>
<div class="col-4">
<div class="grid-card">
<img class="grid-card-image" src="images/artwork/americanfuneral2.png" />
<div class="grid-card-content">
<h3>Magnificent Beach</h3>
</div>
</div>
</div>
</div>
</div>
<footer>
<p>© 2020 Website</p>
</footer>
</div>
CSS:
* {
box-sizing: border-box;
}
body {
margin: 0;
padding: 0;
height: 100%;
background-color:#ffffff;
}
.p1 {
font-family: prestige-elite-std, monospace;
font-weight: bold;
font-size: 20px;
font-style: italic;
}
.p2 {
font-family: prestige-elite-std, monospace;
}
.p3 {
font-family: TNYAdobeCaslonPro,Times New Roman,Times,serif;
font-size: 18px;
}
#wrapper{
background-color:#ccc2c2;
width: 100%;
max-width: 1200px;
position: relative;
margin: 0 auto;
padding: 5px 0;
}
.navbar {
display: flex;
position: relative;
justify-content: space-between;
align-items: center;
background-color: #ffffff;
margin: 10px 0 0 0;
}
.logo {
font-size: 1.5rem;
margin: .5rem;
}
.navbar-links {
height: 100%;
}
.navbar-links ul {
display: flex;
margin: 0;
padding: 0;
}
.navbar-links li {
list-style: none;
padding: 0 20px 0 20px;
}
.navbar-links li a {
font-family: vollkorn, serif;
font-size: 20px;
display: block;
text-decoration: none;
color: #262626;
padding: 5px;
}
.navbar-links li:hover {
}
.navbar-links ul li .underline {
height: 3px;
background-color: transparent;
width: 0%;
transition: width 0.8s, background-color 0.5s;
margin: 0 auto;
}
.navbar-links ul li.active-link .underline {
width: 100%;
background-color: #262626;
}
.navbar-links ul li:hover .underline {
background-color: #262626;
width: 100%;
}
.navbar-links ul li:hover a {
}
.navbar-links ul li:active a {
transition: none;
color: rgba(255,255,255,0.76);
}
.navbar-links ul li:active .underline {
transition: none;
background-color: rgba(255,255,255,0.76);
}
.toggle-button {
position: absolute;
top: 25px;
right: 1rem;
display: none;
flex-direction: column;
justify-content: space-between;
width: 30px;
height: 21px;
}
.toggle-button .bar {
height: 4px;
width: 100%;
background-color: #262626;
border-radius: 10px;
}
@media (max-width: 1028px) {
.navbar {
flex-direction: column;
align-items: flex-start;
background: #FFFFFF;
}
.toggle-button {
display: flex;
}
.navbar-links {
display: none;
width: 100%;
}
.navbar-links ul {
flex-direction: column;
text-align: left;
width: 40%;
position:relative;
left: 35%;
}
.navbar-links ul li {
padding: 10px 0;
text-align: center;
width: auto;
}
.navbar-links ul li a {
padding: .5rem 1rem;
font-family: Arial;
}
.navbar-links.active {
display: flex;
}
}
#content {
padding: 5px 0 5px 0 ;
position: relative;
overflow: hidden;
}
.container {
position: relative;
clear: both;
width: 100%;
max-width: 1200px;
padding: 0;
overflow: hidden;
background: #FFFFFF;
}
/* GRID */
.grid-card {
border: 1px solid #E5E5E5;
margin-bottom: 20px;
}
.grid-card:hover{
opacity: 0.7;
}
.grid-card-image {
max-width: 100%;
max-height: 100%;
}
.grid-card-content {
padding: 5px;
}
.grid-card-content h3 {
margin-top: 0;
margin-bottom: 0;
font-size: 13px;
}
.grid-card-content p {
margin: 0.5em 0;
}
* {
box-sizing: border-box;
}
/* Grid measurements:
*
* 960px wide including 12 gutters (half gutters on both edges)
*
* 60px columns (12)
* 20px gutters (two half-gutters + 11 full gutters, so 12 total)
*
*
* For smaller screens, we always want 20px of padding on either side,
* so 960 + 20 + 20 => 1000px
*
**/
.grid-row {
max-width: 1200px;
padding-left: 20px;
padding-right: 20px;
margin: 0 auto;
}
/* Clearfix */
.grid-row::before,
.grid-row::after {
display: table;
content: '';
}
.grid-row::after {
clear: both;
}
.col-3, .col-4, .col-6, .col-12 {
float: left;
/* Gutters:
* Each column is padded by half-a-gutter on each side,
*
* Half a gutter is 10px, 10/960 (context) = 1.041666%
*
*/
padding-left: 1.04166666%;
padding-right: 1.04166666%;
}
/* Mobile defaults */
.col-3, .col-4, .col-6, .col-12 {
width: 100%;
}
/* Non-mobile, grid */
@media only screen and (min-width: 550px) {
/* 3 columns, 3/12 in % */
.col-3 {
width: 25%;
}
/* 4 columns, 4/12 in % */
.col-4 {
width: 33.333333%;
}
/* 6 columns, 6/12 in % */
.col-6 {
width: 50%;
}
/* 12 columns, 12/12 in % */
.col-12 {
width: 100%;
}
}
/* End of GRID */
/* FOOTER */
footer {
text-align: center;
padding: 3px;
background-color: #FFFF00;
color: #262626;
font-family: prestige-elite-std, monospace;
}
JavaScript:
const toggleButton = document.getElementsByClassName('toggle-button')[0]
const navbarLinks = document.getElementsByClassName('navbar-links')[0]
toggleButton.addEventListener('click', () => {
navbarLinks.classList.toggle('active')
})
Thank you for your time.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/66508282",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Place a background image in a specific position in ggplot2 and take measurements My question is quite challenging for me so far. Hope with your help we can get what I need.
I want to place an image as background of a ggplot.
Data to reproduce : Two objects are necessary: a data frame and an image.
DATA at the end of this question.
Background image:
And this is the image to place as background (molar.png):
What I got so far...
I ggplotted:
library(png)
library(grid)
library(ggplot2)
img <- readPNG("images/molar.png")
g <- rasterGrob(img, interpolate = TRUE)
ggplot(df), aes(x = X, y = Y)) +
coord_fixed(ratio = .75) +
annotation_custom(g, xmin=-Inf, xmax=Inf, ymin=-Inf, ymax=Inf) +
geom_point(alpha = .20, size = 1, shape = 19, color = "red") +
stat_smooth(method = 'lm', formula = y ~ poly(x, 3)) +
xlim(0, 100) + ylim(0, 100) +
theme_minimal() +
geom_hline(aes(yintercept = 0), color = "red", lty = 2) +
geom_vline(aes(xintercept = 0), color = "red", lty = 2)
I got this result:
... and what I really want
1. Adapt the regression to this line
Take this red horizontal line as reference:
The X axis (from 0 to 100) must be fitted to this line, as shown now:
This is really what I want: to adapt the background image (without modifying its proportion) to that horizontal line, from the cusp tip (gray) to the ending of the white area to the right.
This would require to select two landmarks in the image, but don't know how to make it automatic by simply selecting one or two points, so that the regression automatically fits that distance.
2. Take measurements
I would like to measure the distance between the highest point of the regression and the point [100, 0], as shown below in green line.
The point here, how can we reference if we are having a scale in the image?
DATA
df <- structure(list(tooth_num = c(1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 4, 4, 4, 4, 4,
4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4,
4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4,
4, 4, 4, 4, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5,
5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5,
5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6, 6,
6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
6, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 9, 9,
9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
9, 9, 9, 9, 9, 9, 9, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10,
10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10,
10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10),
sample = c(1L, 2L, 3L, 4L, 5L, 6L, 7L, 8L, 9L, 10L, 11L,
12L, 13L, 14L, 15L, 16L, 17L, 18L, 19L, 20L, 21L, 22L, 23L,
24L, 25L, 26L, 27L, 28L, 29L, 30L, 31L, 32L, 33L, 34L, 35L,
36L, 37L, 38L, 39L, 40L, 41L, 42L, 43L, 44L, 45L, 46L, 47L,
48L, 49L, 50L, 51L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 8L, 9L, 10L,
11L, 12L, 13L, 14L, 15L, 16L, 17L, 18L, 19L, 20L, 21L, 22L,
23L, 24L, 25L, 26L, 27L, 28L, 29L, 30L, 31L, 32L, 33L, 34L,
35L, 36L, 37L, 38L, 39L, 40L, 41L, 42L, 43L, 44L, 45L, 46L,
47L, 48L, 49L, 50L, 51L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 8L,
9L, 10L, 11L, 12L, 13L, 14L, 15L, 16L, 17L, 18L, 19L, 20L,
21L, 22L, 23L, 24L, 25L, 26L, 27L, 28L, 29L, 30L, 31L, 32L,
33L, 34L, 35L, 36L, 37L, 38L, 39L, 40L, 41L, 42L, 43L, 44L,
45L, 46L, 47L, 48L, 49L, 50L, 51L, 1L, 2L, 3L, 4L, 5L, 6L,
7L, 8L, 9L, 10L, 11L, 12L, 13L, 14L, 15L, 16L, 17L, 18L,
19L, 20L, 21L, 22L, 23L, 24L, 25L, 26L, 27L, 28L, 29L, 30L,
31L, 32L, 33L, 34L, 35L, 36L, 37L, 38L, 39L, 40L, 41L, 42L,
43L, 44L, 45L, 46L, 47L, 48L, 49L, 50L, 51L, 1L, 2L, 3L,
4L, 5L, 6L, 7L, 8L, 9L, 10L, 11L, 12L, 13L, 14L, 15L, 16L,
17L, 18L, 19L, 20L, 21L, 22L, 23L, 24L, 25L, 26L, 27L, 28L,
29L, 30L, 31L, 32L, 33L, 34L, 35L, 36L, 37L, 38L, 39L, 40L,
41L, 42L, 43L, 44L, 45L, 46L, 47L, 48L, 49L, 50L, 51L, 1L,
2L, 3L, 4L, 5L, 6L, 7L, 8L, 9L, 10L, 11L, 12L, 13L, 14L,
15L, 16L, 17L, 18L, 19L, 20L, 21L, 22L, 23L, 24L, 25L, 26L,
27L, 28L, 29L, 30L, 31L, 32L, 33L, 34L, 35L, 36L, 37L, 38L,
39L, 40L, 41L, 42L, 43L, 44L, 45L, 46L, 47L, 48L, 49L, 50L,
51L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 8L, 9L, 10L, 11L, 12L, 13L,
14L, 15L, 16L, 17L, 18L, 19L, 20L, 21L, 22L, 23L, 24L, 25L,
26L, 27L, 28L, 29L, 30L, 31L, 32L, 33L, 34L, 35L, 36L, 37L,
38L, 39L, 40L, 41L, 42L, 43L, 44L, 45L, 46L, 47L, 48L, 49L,
50L, 51L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 8L, 9L, 10L, 11L, 12L,
13L, 14L, 15L, 16L, 17L, 18L, 19L, 20L, 21L, 22L, 23L, 24L,
25L, 26L, 27L, 28L, 29L, 30L, 31L, 32L, 33L, 34L, 35L, 36L,
37L, 38L, 39L, 40L, 41L, 42L, 43L, 44L, 45L, 46L, 47L, 48L,
49L, 50L, 51L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 8L, 9L, 10L, 11L,
12L, 13L, 14L, 15L, 16L, 17L, 18L, 19L, 20L, 21L, 22L, 23L,
24L, 25L, 26L, 27L, 28L, 29L, 30L, 31L, 32L, 33L, 34L, 35L,
36L, 37L, 38L, 39L, 40L, 41L, 42L, 43L, 44L, 45L, 46L, 47L,
48L, 49L, 50L, 51L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 8L, 9L, 10L,
11L, 12L, 13L, 14L, 15L, 16L, 17L, 18L, 19L, 20L, 21L, 22L,
23L, 24L, 25L, 26L, 27L, 28L, 29L, 30L, 31L, 32L, 33L, 34L,
35L, 36L, 37L, 38L, 39L, 40L, 41L), X = c(0, 1.96207644325269,
3.96448989844662, 6.02285180886395, 8.15165005779206, 10.3635651674945,
12.6674140636077, 15.0640931778694, 17.5406465345979, 20.0647832611694,
22.5857329433686, 25.0458992379799, 27.3978582481916, 29.6291517474813,
31.8764771189544, 34.0520372099874, 36.1615029782313, 38.2134690535817,
40.2184171634735, 42.1879211839819, 44.1341445581471, 46.0695527612659,
48.0067272490216, 49.9582712234201, 51.9366936524031, 53.9541918066236,
56.0223057345439, 58.1471219902002, 60.015986446532, 62.0418690161973,
64.172643764213, 66.3646706538791, 68.5820610043302, 70.7926665021678,
72.9630123083219, 75.0533364802678, 77.0143642675254, 78.7889946597798,
80.3221949636097, 81.6792186440018, 83.1246290439824, 84.6572566946537,
86.2607918541562, 87.9199855179157, 89.6207074088368, 91.349834829432,
93.0950207010492, 94.844403612905, 96.5863082060859, 98.3089189787115,
100, 0, 2.07242714587787, 4.28691224245265, 6.60638277527078,
8.99634804343432, 11.4282251674021, 13.8802080085279, 16.3366019674999,
18.7865642588865, 21.2228067680933, 23.6405691464549, 26.0268342309397,
28.2980527055826, 30.4950596311624, 32.6499592979795, 34.7798224410736,
36.8956207286784, 39.0058437957066, 41.1183659656274, 43.2421092543673,
45.3894713560051, 47.5991212687389, 49.7770452245596, 51.9171025815641,
54.0147450240845, 56.0668835223753, 58.0722874535502, 60.0316719092865,
61.9474399302204, 63.8232002348162, 65.6632101130593, 67.4719472029522,
69.2537602596947, 71.1020020072457, 73.0197406878018, 74.8895017058263,
76.7134344938606, 78.4953847484249, 80.2407780197449, 81.9562954259909,
83.649499477401, 85.3283767502077, 87.0008805605653, 88.6745443161437,
90.3562154355033, 92.0029343703826, 93.595173297479, 95.1912911811735,
96.7911009335273, 98.3943073713479, 100, 0, 2.49538787860394,
4.98986333706054, 7.48094091039875, 9.95158514589746, 12.3765352721187,
14.7826711324534, 17.1741487059107, 19.5379450224354, 21.8376445004796,
24.2011429944043, 26.5151298348149, 28.7199538624058, 31.0167238490571,
33.2844073975993, 35.4322146421557, 37.6300939882099, 39.8422715265431,
41.8385466322099, 43.9606111742119, 46.1772777113709, 48.0735169131695,
50.1458450809683, 52.0775711992983, 54.0389983532847, 56.0114855556445,
57.9507899054059, 59.8445463497116, 61.7655941740918, 63.7919980969677,
65.7952774486913, 67.8300149894114, 69.6945929413499, 71.6911766995294,
73.5625774964864, 75.3913842466844, 77.1888383995349, 78.9539192357634,
80.672317733178, 82.2770969086854, 83.9169027294331, 85.5602445166866,
87.1949684008868, 88.8468983089335, 90.5308901736114, 92.1034422363185,
93.6509365884513, 95.3521507218448, 96.9695007185512, 98.5200274462478,
100, 0, 1.93071662500976, 3.82909585694513, 5.83503737371176,
7.96719181032991, 10.2303413170764, 12.617316402646, 15.1102082752161,
17.6402520534245, 20.1564846032436, 22.6509074609361, 25.0393836587477,
27.3129712478007, 29.4988321446333, 31.6158908190034, 33.5547876344398,
35.4063709991687, 37.2999307397267, 39.3177890463815, 41.2304325787261,
43.1170170017018, 45.1909193214654, 47.1049295380901, 49.1859515610248,
51.13271739105, 53.1310164292379, 55.0797239964915, 57.1128373874235,
58.9454191107869, 60.9254683084337, 62.9947826516433, 65.0902258076096,
67.1539265387035, 69.1321933211508, 71.0068236131378, 72.9528127482717,
74.868864278393, 76.7358744964615, 78.5828026706554, 80.4923369340278,
82.44389985077, 84.3433495275878, 86.0966137745744, 87.9057900961145,
89.7809605893561, 91.5773662545089, 93.2971230872706, 94.8659471916182,
96.5480144068937, 98.2832055612151, 100, 0, 2.45904597118919,
4.9478077699383, 7.4437174468872, 9.93045045419645, 12.3969081092835,
14.8359017068762, 17.2430125015322, 19.6157029336795, 21.9526351315638,
24.2532312350846, 26.5173310764965, 28.744978623416, 30.9362680921638,
33.0912151854599, 35.2096628761033, 37.2911746284744, 39.334940182215,
41.3396279466586, 43.3031840060133, 45.2225306271349, 47.2687426646706,
49.3178157378126, 51.3497697054769, 53.3645511784153, 55.3621224700994,
57.3424678778091, 59.3055999637205, 61.2515438521856, 63.1803529324531,
65.0920931559475, 66.9868618795333, 68.8647627411635, 70.7259245031432,
72.5704916304973, 74.3986274315152, 76.2105077766622, 78.0063242391239,
79.7862840948059, 81.5506040412458, 83.2995196192455, 85.0332663696068,
86.7521175196599, 88.4563337345588, 90.1461348523852, 91.8219291438623,
93.4838736361913, 95.1323766000954, 96.7676892790966, 98.3900943221571,
100, 0, 2.20427029931411, 4.42577825043187, 6.67629529636218,
8.96662563154085, 11.3064974908959, 13.704119943729, 16.165246307201,
18.6916215311874, 21.2788860284595, 23.9143289820342, 26.5756256258544,
29.2320665145903, 31.8490369716412, 34.3727083595587, 36.7961343283599,
39.1127253229244, 41.3113092041144, 43.3888560030568, 45.3501991751572,
47.2064997097139, 48.9732280089765, 50.6683743389121, 52.3111665976677,
53.9212675271295, 55.5183816810814, 57.1220463657154, 58.7515758904346,
60.4258971077205, 62.1633013292058, 63.9808505967227, 65.8934996324456,
67.912799670054, 70.0333597621695, 71.9831740002692, 73.9087652121441,
75.8101919344515, 77.6875628781259, 79.5410090537812, 81.3706865591696,
83.1767905164818, 84.9595299852075, 86.7191558367347, 88.4559245173709,
90.170123135482, 91.862066674033, 93.5320896282075, 95.1805376430287,
96.8077452136806, 98.414102584544, 100, 0, 2.50973310686108,
4.98257000649406, 7.40768627831619, 9.78047063985944, 12.100599944502,
14.3704650807463, 16.5940944776443, 18.776452301705, 20.9230915203372,
23.0399794423239, 25.1335076302947, 27.2106366228331, 29.2791814137006,
31.3594526601995, 33.4580064720123, 35.556233172214, 37.6533199380137,
39.7484638590935, 41.8408600426407, 43.9297035958428, 46.0141896258872,
48.0934993624991, 50.1668041229306, 52.2332633294661, 54.2920126144546,
56.3421658028046, 58.3828149119835, 60.4130261870291, 62.4318202756028,
64.4382019654095, 66.4311244992937, 68.4095034527027, 70.3722187161805,
72.3180946704221, 74.2459160462301, 76.1544160295474, 78.0422683314784,
79.9081070132353, 81.7505086436864, 83.5679982468404, 85.3590473193511,
87.1220777955072, 88.8554739421999, 90.5575664989655, 92.2266544854268,
93.8610012363035, 95.458856208853, 97.0184430879027, 98.537991505764,
100, 0, 2.49186292873155, 4.96628290858449, 7.40387310725186,
9.79133340002794, 12.1468199057625, 14.5011896071325, 16.8431655039685,
19.1723761535772, 21.4884872575346, 23.7911793751244, 26.0801603047613,
28.355162607706, 30.6159386554963, 32.8622655825162, 35.0939428097114,
37.310792044589, 39.5126572812178, 41.6993973713744, 43.8708934533968,
46.0270489521849, 48.1677771977769, 50.2930162830572, 52.4027142060487,
54.4968362987667, 56.5753602746497, 58.6382811811283, 60.6856064470565,
62.7173459775728, 64.7335369169464, 66.7342089805929, 68.7194141704892,
70.6892069648972, 72.6436517472169, 74.582822805987, 76.5067919534617,
78.4156508121718, 80.30948109951, 82.1883843431457, 83.8953343826177,
85.318702783443, 86.7569115580089, 88.2078484355329, 89.6694432420707,
91.1396480902398, 92.6164522369269, 94.0978597967267, 95.5818971707953,
97.0665932365733, 98.5499867766401, 100, 0, 2.61369623570294,
5.25019204546923, 7.89758672867171, 10.4854413123113, 13.0066240676632,
15.4846710718853, 17.9159547041448, 20.2976684759407, 22.6276875072264,
24.9044541625748, 27.1268476764071, 29.2940720764344, 31.4055784162507,
33.4609732842652, 35.4599616217844, 37.4022781047122, 39.2876574089524,
41.115772453938, 42.8862115298645, 44.5984417012627, 46.5824735364946,
48.8579364441288, 51.0689873528466, 53.2187049370753, 55.31212578009,
57.3558486751465, 59.3576503629965, 61.3261515894915, 63.2705517814855,
65.2004117555501, 67.125505044989, 69.0556829505137, 71.0007693255153,
72.9704141903561, 74.9739450593852, 77.0201427878221, 79.1169465130639,
80.9682934274075, 82.7378404654242, 84.4621062867744, 86.1441466931183,
87.7873262684694, 89.3952520481705, 90.9717460715737, 92.5207813382925,
94.0464474990516, 95.5529302701972, 97.0444725499921, 98.5253927168307,
100, 0, 2.19489342240264, 4.47470248895734, 6.80636996136228,
9.16189235515265, 11.5204119968896, 13.8679818386464, 16.1962336516669,
18.5008000956494, 20.7800403414259, 23.0340446346007, 25.2640080457511,
27.4717901812673, 29.6596690589774, 31.8301824946609, 33.9860569994518,
36.1301804326855, 38.2656102060449, 40.395611569574, 42.5237505919975,
44.6539625286031, 46.790726843019, 48.9392449637073, 51.1057000819157,
53.0838372365286, 55.0005198693747, 56.9159691456296, 58.8292579968134,
60.7394374767241, 62.645542230868, 64.5465987006055, 66.4416169190052,
68.3295795719832, 70.2094638760246, 72.080216965747, 73.9407777716216,
75.7900606116825, 77.6269798039636, 79.4504168499154, 81.2592587204191,
83.0523732433488), Y = c(84.5741422911491, 87.0989688246201,
89.5436034157802, 91.8694746551154, 94.0314174040144, 95.9740138468311,
97.628391911438, 98.9112343041615, 99.7302288176452, 100,
99.6682935009841, 98.7381965579207, 97.2664228638507, 95.3825982722905,
93.5434433368078, 91.50049262398, 89.2915552625009, 86.9514674858642,
84.511940176201, 82.0015588642778, 79.4462792120302, 76.8706085478357,
74.2982919192514, 71.7531887159568, 69.2602636348217, 66.8466919870944,
64.5423551809367, 62.3722941413001, 59.6800326256192, 57.2857466826492,
55.128758759083, 53.1294867372666, 51.2007256913408, 49.2527551687403,
47.1957784888164, 44.9429337520794, 42.418488359019, 39.5725891439776,
36.3973083864229, 33.0253591771941, 29.7461795438129, 26.5669349259918,
23.4758099710143, 20.4586262556193, 17.4994139966193, 14.5814411300049,
11.6872895390296, 8.79946487886403, 5.90043469063777, 2.97289519972717,
0, 93.0321380957158, 95.1946109521693, 96.937054277536, 98.2619255824812,
99.1910694062447, 99.7577986711693, 100, 99.9550821661862,
99.6575185832176, 99.1377550776607, 98.4215955114931, 97.4779796804826,
95.9441517048638, 94.1389735933651, 92.2010899059795, 90.1898222195824,
88.1388247774415, 86.0724678936469, 84.0123913148843, 81.9837162612796,
80.0234419211725, 78.2597001700458, 76.3926747068224, 74.4111019409554,
72.3108177571526, 70.0927095898208, 67.7621020453996, 65.3282107888812,
62.802504203367, 60.1968602570691, 57.5234982391254, 54.7931356266002,
52.0153976695973, 49.3678395136313, 46.8461605150396, 44.2290481856401,
41.5261960397215, 38.748799403644, 35.9094871516561, 33.021434271488,
30.098088807609, 27.1525574835635, 24.19719611686, 21.2436096189696,
18.3024472027724, 15.3103597044707, 12.2378569960892, 9.17074715833242,
6.10882539864554, 3.05175039610287, 0, 100, 99.9740960784806,
99.8730270144876, 99.6594688780895, 99.1648671200451, 98.300448086114,
97.3281159413371, 96.2806584450564, 95.1069839916948, 93.6992988433163,
92.5227992310794, 91.1519207300211, 89.4389990501897, 88.0315526476314,
86.5030621141021, 84.637382900149, 82.9008651750625, 81.2041782110219,
79.064856495856, 77.1370635776142, 75.4555767641426, 73.1766285349799,
71.1390523302985, 68.8176471360649, 66.5503178701644, 64.3037992816136,
61.9957638533255, 59.6077485751849, 57.270625947771, 55.1882053198138,
53.005988938906, 50.8933669646611, 48.4803231663425, 46.2904669191802,
43.8645308465569, 41.369278904061, 38.8252432322521, 36.2327421588907,
33.5735116287118, 30.7665372266409, 28.0047653665761, 25.244744309195,
22.4736613621324, 19.7247419854022, 17.0183591556834, 14.1736629139801,
11.3015506938947, 8.6188037004008, 5.82611425658707, 2.95264914351926,
0, 86.7221127164863, 89.2450865945842, 91.8256626160176,
94.2050712850442, 96.3082958568556, 98.0567601186487, 99.356578317864,
100, 99.8266960099512, 99.3672567218446, 98.6837623193952,
97.4546359200075, 95.8095875992727, 93.8391732848531, 91.6986699837336,
89.1914649315853, 86.5315472203614, 83.9427805951582, 81.5889388575256,
79.0374892354799, 76.4382738493923, 74.2129556980193, 71.6847000287053,
69.5197780116735, 67.026504640704, 64.6334322074442, 62.1466653908716,
59.8252416036741, 57.210640130131, 54.8147737058654, 52.5672567218449,
50.3760405702802, 48.1148980958759, 45.6822122284949, 43.0613338436512,
40.5655726724713, 38.0157305521002, 35.3812266768728, 32.7135011003732,
30.1526743852262, 27.6670940579847, 25.0888527413645, 22.2776767773419,
19.7712372021815, 17.1514304851209, 14.4034446464453, 11.542359582815,
8.48492967180167, 5.57098842216043, 2.73145153573813, 0,
99.1041781658029, 99.7254865136605, 100, 99.9614316109632,
99.6447768919466, 99.0834281892782, 98.3070217828948, 97.341621109093,
96.2090754809024, 94.9278903961505, 93.5136855943403, 91.9791492509625,
90.3350457026248, 88.5899864186136, 86.7511628918963, 84.8242550277467,
82.8134769494328, 80.7219434437174, 78.5514867381084, 76.302473278107,
73.9737121158334, 71.8911107192181, 69.810524772861, 67.694531029918,
65.5438623813919, 63.3593433296612, 61.1416609600414, 58.8917313862862,
56.6101958880234, 54.2979247733192, 51.9556967388641, 49.5842904813491,
47.1845305031526, 44.757241306653, 42.303109977166, 39.8229610170695,
37.317527317367, 34.7876333804369, 32.2340120972821, 29.657396358906,
27.058564861999, 24.438158886189, 21.7969571281666, 19.1356924789353,
16.4549604124345, 13.7555396253553, 11.0379797859501, 8.30305959090951,
5.55132870848586, 2.78342841830685, 0, 84.1515543172144,
86.2722836260793, 88.3566153916604, 90.3773896250419, 92.3062620354674,
94.111690717205, 95.7577913244362, 97.203231722867, 98.4009161759049,
99.2995644137824, 99.8474619227218, 100, 99.7284790643066,
99.0275302806241, 97.8277140842702, 96.2611985608363, 94.3983312397508,
92.2676143186827, 89.9054453409169, 87.3514589414394, 84.6443817904904,
81.8193876527848, 78.9076236667722, 75.9361708679116, 72.9289916301439,
69.9079560608225, 66.8938683956418, 63.9077697306659, 60.9718854638001,
58.1105727362662, 55.3511099671633, 52.7239337138365, 50.2623228580521,
47.9794231502588, 45.4070011187705, 42.7981815439979, 40.1541092510553,
37.4757316814164, 34.7641541834675, 32.0204031521378, 29.2455049823579,
26.4404465923295, 23.6062938537105, 20.7439547312464, 17.8544950965959,
14.9388623912317, 11.9979251031726, 9.0326701506196, 6.04400549831871,
3.03283911101569, 0, 100, 99.5848739044175, 98.8739209129315,
97.9105346461211, 96.7351022995956, 95.3831954679074, 93.885250878182,
92.2670226841415, 90.5504870541479, 88.7545871260625, 86.8960843842295,
84.9905164585802, 83.0528356573708, 81.0986594271243, 79.1673905588146,
77.2717198905873, 75.3754106896234, 73.4768134130185, 71.5743849399925,
69.6665023331719, 67.7516224717761, 65.8282022350241, 63.8947517131965,
61.9497011799818, 59.9915873311911, 58.0188670460438, 56.0301302314122,
54.0238603720464, 51.9985941637575, 49.9528949078877, 47.8852726947172,
45.794397247711, 43.6787786571497, 41.5370334354364, 39.3678047005055,
37.1697621758216, 34.941522373788, 32.6818614399924, 30.3895023089609,
28.063247731812, 25.7019536707251, 23.304582510003, 20.8700966339479,
18.3975648489857, 15.8861889891947, 13.3352240997155, 10.7440582533417,
8.11223915605116, 5.43939433041456, 2.72533753771655, 0,
100, 99.9134879636606, 99.4737726511386, 98.7119319033914,
97.6645725261045, 96.4711111592938, 95.2721931018034, 94.0226109361477,
92.7232680879358, 91.374959571704, 89.9785165390125, 88.5348785524954,
87.0449851747857, 85.5095952833957, 83.9297207150073, 82.3061926211812,
80.6400228385995, 78.9320063817987, 77.1831189504364, 75.3942278330975,
73.5662725924159, 71.7000843799518, 69.7965666213147, 67.8565504680649,
65.8809393458113, 63.8706005431396, 61.8262568005362, 59.7488476806353,
57.6390236498756, 55.4977604079147, 53.3256361471427, 51.123554293169,
48.8921653124316, 46.6322280824431, 44.344429206666, 42.0294914255877,
39.6880290686225, 37.3207287392334, 34.9282409038592, 32.3093546108134,
29.3214008878868, 26.3486608522194, 23.3891108304469, 20.4407632862286,
17.5015222721514, 14.5693279778263, 11.6421205928639, 8.71769575877807,
5.79402980220384, 2.86895450167932, 0, 99.0881176828924,
99.616812993443, 99.9245775334157, 100, 99.4144184933504,
98.4080380989905, 97.2482296158507, 95.9447863261935, 94.5072176490275,
92.9445788221548, 91.2653289705444, 89.4773594926569, 87.5879656741198,
85.6037331424258, 83.5306797985592, 81.3743977486237, 79.139712667937,
76.8311379822374, 74.4527045497319, 72.0079322747694, 69.5001707437473,
67.4173241176181, 65.7355478830473, 63.9261751158092, 62.0062376111431,
59.9926536189868, 57.9018588217461, 55.7494373120646, 53.5502067518011,
51.3181332130511, 49.0667285867045, 46.8089938097941, 44.5579865920031,
42.3268498019911, 40.129152103299, 37.979256976578, 35.89220917429,
33.8840753566102, 31.5408977402496, 29.095103557573, 26.6000023276786,
24.0608455207656, 21.4827994480562, 18.8707181711938, 16.2292854338693,
13.56295788917, 10.8759367132551, 8.1722811506567, 5.45590851427953,
2.73059418540176, 0, 96.4662652426023, 98.0232502530471,
99.1147667554613, 99.7607331141328, 100, 99.8803419056255,
99.4511603186742, 98.7585534337238, 97.843294734107, 96.7405371746194,
95.4801583016932, 94.0874997966255, 92.5842056245715, 90.989010880653,
89.3184813331895, 87.587358543869, 85.8094473196242, 83.9978129241588,
82.1654220154131, 80.3260794003192, 78.4945266405658, 76.6880690477,
74.9274631350027, 73.2399733961649, 70.9563625122581, 68.4738638027609,
65.9881111030584, 63.4970829949925, 60.9982157287041, 58.4893399773897,
55.9680398998363, 53.4319489577125, 50.8788978242146, 48.3064706581295,
45.7125474355354, 43.0948602238647, 40.4513876049598, 37.7800095548987,
35.0788032612873, 32.3458952146129, 29.5794612082463)), .Names = c("tooth_num",
"sample", "X", "Y"), row.names = c(NA, 500L), class = "data.frame")
| {
"language": "en",
"url": "https://stackoverflow.com/questions/60817744",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Outlook.com does not allow stylesheet to be loaded externally? It looks like Outlook.com prevents a stylesheet to be loaded from an external url this way:
http://cdn.xxxx.com/email/style.css' rel='stylesheet' type='text/css'>
When I download the email via POP3, everything is just fine. However, when I open the same email in outlook.com somehow the css is blocked. I am suprised that it does not block the images inside the email and prefers to block only the css. How come?? Any ideas how to solve this?
A: Best practice , use inline style on all elements.
It's not just outlook, gmail has similar issues ( security reasons )
A: It is always a good practice when making a mailer always use inline style.
All Outlook versions and others like gmail, yahoo, hotmail have a good support for inline style.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/23407844",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: how to add KASlideShow inside a cell inside the UITableView Before we move into the main purpose of the question, KASlideShow is a library on github. I am using this library for showing a slide show of images. After many searches on to how to implement a custom cell, I found the following: Is it possible to add UITableView within a UITableViewCell. Here is the code that i am using:
#import "HomeTableViewController.h"
#import "KASlideShow.h"
#import "CustomTableViewCell.h"
@interface HomeTableViewController ()
@property (strong,nonatomic) IBOutlet KASlideShow * slideshow;
@end
@implementation HomeTableViewController
- (void)viewDidLoad {
[super viewDidLoad];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
CustomTableViewCell *cell = [self.tableView dequeueReusableCellWithIdentifier:@"SlideShowCell"];
if(cell == nil)
{
cell = [[CustomTableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"SlideShowCell"];
}
[_slideshow setDelay:5]; // Delay between transitions
[_slideshow setTransitionDuration:5]; // Transition duration
[_slideshow setTransitionType:KASlideShowTransitionFade]; // Choose a transition type (fade or slide)
[_slideshow setImagesContentMode:UIViewContentModeScaleAspectFill]; // Choose a content mode for images to display
[_slideshow addImagesFromResources:@[@"adidas.jpg",@"adidas_neo.jpeg"]]; // Add images from resources
[_slideshow addGesture:KASlideShowGestureTap]; // Gesture to go previous/next directly on the image
[_slideshow start];
return cell;
}
@end
#import <UIKit/UIKit.h>
#import "KASlideShow.h"
@interface CustomTableViewCell : UITableViewCell
@property (nonatomic) IBOutlet KASlideShow *slideshow;
#import "CustomTableViewCell.h"
#import "KASlideShow.h"
@implementation CustomTableViewCell
- (void)awakeFromNib {
[super awakeFromNib];
// Initialization code
}
- (void)setSelected:(BOOL)selected animated:(BOOL)animated {
[super setSelected:selected animated:animated];
// Configure the view for the selected state
}
- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
{
self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
if (self) {
// Initialization code
}
return self;
}
@end
@end
KASlideShow never appears inside the UITableViewCell I know there is something wrong but i am not able to know where it is to fix it.
A: why don't u add KASlideShow to a header view in ur UITableViewController ?
First create that headerView and add to it 1 more view and subclass it of KASlideShow
then connect your IBOutlet slideshow with this view
then add KASlideShow settings to ViewDidLoad
your code should look like the following code
#import "SlideShowTableViewController.h"
#import "KASlideShow.h"
@interface SlideShowTableViewController ()
@property (strong,nonatomic) IBOutlet KASlideShow * slideShow;
@end
@implementation SlideShowTableViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
[self.slideShow setDelay:5]; // Delay between transitions
[self.slideShow setTransitionDuration:5]; // Transition duration
[self.slideShow setTransitionType:KASlideShowTransitionFade]; // Choose a transition type (fade or slide)
[self.slideShow setImagesContentMode:UIViewContentModeScaleAspectFill]; // Choose a content mode for images to display
[self.slideShow addImagesFromResources:@[@"adidas.jpg",@"adidas_neo.jpeg"]]; // Add images from resources
[self.slideShow addGesture:KASlideShowGestureTap]; // Gesture to go previous/next directly on the image
[self.slideShow start];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
#pragma mark - Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return 0; // <<-- set your sections count
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return 0; // <<-- set your rows count in section
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"reuseIdentifier" forIndexPath:indexPath];
// Configure the cell...
return cell;
}
and your Interface Builder should look like
| {
"language": "en",
"url": "https://stackoverflow.com/questions/36676658",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Docker file to clone the files which are in git I have a server.xml files for 50 applications which are different for all the applications. i need to write a docker file for all the applications to grab that server.xml.
Where is server.xml: Gitserver private repo uses ssh based clone only
I cannot clone complete repo only for single server.xml file
what is the best approach to grab that file and make part of dockerfile.
Is there any way to do it instead of keeping in dockerfile?
A: You could use an argument to pull the xml file and then build it into the image.
FROM alpine
ARG SERVER_CONF
RUN curl ${SERVER_CONF}
EXEC server.sh
Then you can run build and pass in the location of the xml file
docker build --build-arg SERVER_CONF=http://localhost/server.xml
Alternatively you could set this as an environment variable so that you can get the xml file at runtime.
FROM alpine
ARG SERVER_CONF
ENV SERVER_CONF=${SERVER_CONF}
RUN server.sh --config=$SERVER_CONF
This would allow you to set the config dynamically when you build the image.
If you would like to set the config at runtime then you could pass it as an environment variable when starting the docker container
FROM alpine
RUN server.sh --config=$SERVER_CONF
Then start your container by passing in the environment variable
docker run -e "SERVER_CONF=http://localhost/server.xml" server
You don't have to pass a url, you could pass the entire contents of the xml file as a string. You can use an entry point to write the contents of the environment to a file before your application starts.
A:
Is there any way to do it instead of keeping in dockerfile?
As long as you have fetched that server.xml (or simply copied its content to a local file), you can:
*
*either COPY it in your Dockerfile
*or put it in a public place, remotely accessible, which your container could, at runtime, fetch from (instead of having to try and clone a private repo, which your container should not be able to do)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/50419934",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-2"
} |
Q: WCF Error because The maximum message size quota for incoming messages (65536) has been exceeded i make WCF service on server side to return binary (bytes) of file..
i just can return binary of txt file,otherwise it's say "The maximum message size quota for incoming messages (65536) has been exceeded. To increase the quota, use the MaxReceivedMessageSize property on the appropriate binding element."
<bindings>
<basicHttpBinding>
<binding name="basicHttp" allowCookies="true"
maxReceivedMessageSize="2147483647"
maxBufferSize="2147483647"
maxBufferPoolSize="2147483647"
transferMode="Buffered"
messageEncoding="Text"
textEncoding="utf-8"
bypassProxyOnLocal="false"
useDefaultWebProxy="true" >
<security mode="None" />
<readerQuotas maxDepth="2147483647"
maxArrayLength="2147483647"
maxStringContentLength="2147483647"
maxBytesPerRead="2147483647"
maxNameTableCharCount="2147483647"/>
</binding>
</basicHttpBinding>
</bindings>
<behaviors>
<serviceBehaviors>
<behavior name="">
<serviceMetadata httpGetEnabled="true" httpsGetEnabled="true" />
<serviceDebug includeExceptionDetailInFaults="false" />
</behavior>
</serviceBehaviors>
</behaviors>
can you give me solution?
i need your help..thanks before :)
here is client code side (app.config)
<bindings>
<basicHttpBinding>
<binding name="BasicHttpBinding_IService" />
</basicHttpBinding>
</bindings>
<client>
<endpoint address="http://localhost:3724/Service.svc"
binding="basicHttpBinding"
bindingConfiguration="BasicHttpBinding_IService"
contract="ServiceReference1.IService"
name="BasicHttpBinding_IService" />
</client>
this client is desktop application not website
A: You need to assign the binding you defined to an endpoint you create. Here's an example:
<bindings>
<basicHttpBinding>
<binding name="basicHttp" allowCookies="true"
maxReceivedMessageSize="2147483647"
maxBufferSize="2147483647"
maxBufferPoolSize="2147483647"
transferMode="Buffered"
messageEncoding="Text"
textEncoding="utf-8"
bypassProxyOnLocal="false"
useDefaultWebProxy="true" >
<security mode="None" />
<readerQuotas maxDepth="2147483647"
maxArrayLength="2147483647"
maxStringContentLength="2147483647"
maxBytesPerRead="2147483647"
maxNameTableCharCount="2147483647"/>
</binding>
</basicHttpBinding>
</bindings>
<behaviors>
<serviceBehaviors>
<behavior name="">
<serviceMetadata httpGetEnabled="true" httpsGetEnabled="true" />
<serviceDebug includeExceptionDetailInFaults="false" />
</behavior>
</serviceBehaviors>
</behaviors>
<services>
<service>
<endpoint address="/Service.svc" binding="basicHttpBinding"
bindingCongifuration="basicHttp"
contract="service.IService"/>
</service>
</services>
A couple of things to note - in your comment, your service endpoint was using wsHttpBinding, but you defined basicHttpBinding in your <bindings> section. Also, the bindingConfiguration attribute must be the name assigned to the binding defined. My example above is based on the original posted config file.
Alternatively, if you are using .NET 4.0 or later, you can define a binding in the <bindings> setting and set it as the default definition for that binding by omitting the name attribute on the <binding> element.
By default, .NET 4.0+ uses basicHttpBinding for http. You can change this in the config file in the <protocolMapping> section (which is contained in the <system.serviceModel> section). For example, if you wanted to use wsHttpBinding for all http requests, you would do this:
<protocolMapping>
<add binding="wsHttpBinding" scheme="http" />
</protocolMapping>
Added Client Example
The client side would look very similar, except you'd have a <clients> section instead of a <services> section. Note that some of the settings on the binding apply to the machine (client or server) the application is on, and setting them on one side of the client-server relationship will have no effect on the other side (like maxReceivedMessageSize, for example). Generally the binding type and security have to agree, and in practice it's usually easier to just use the same bindings on both ends, but it is possible to have a scenario where one side would have different buffers or other items.
<bindings>
<basicHttpBinding>
<binding name="BasicHttpBinding_IService" allowCookies="true"
maxReceivedMessageSize="2147483647"
maxBufferSize="2147483647"
maxBufferPoolSize="2147483647"
transferMode="Buffered"
messageEncoding="Text"
textEncoding="utf-8"
bypassProxyOnLocal="false"
useDefaultWebProxy="true" >
<security mode="None" />
<readerQuotas maxDepth="2147483647"
maxArrayLength="2147483647"
maxStringContentLength="2147483647"
maxBytesPerRead="2147483647"
maxNameTableCharCount="2147483647"/>
</binding>
</basicHttpBinding>
</bindings>
<client>
<endpoint address="localhost:3724/Service.svc"
binding="basicHttpBinding"
bindingConfiguration="BasicHttpBinding_IService"
contract="ServiceReference1.IService"
name="BasicHttpBinding_IService" />
</client>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/25272790",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Force bgSave() using Spring Data Redis Is there any way to call bgSave() (force writing to disk) using Spring Data Redis Repositories?
public interface UserRepository extends CrudRepository<User, String> {
}
I've gone through the docs but I couldn't find any reference about bgSave(). The only way I can think of would be by autowiring RedisConnectionFactory, getting the RedisConnection and calling the method, although I'm not sure it would work.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/37676760",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Is it an issue to use "setAdapter()" more than once in recyclerview? Actually I am fetching data from server and showing that on my recyclerview .But it was showing nothing . Even after a lot of question's reference my problem couldn't be solved but then I tried to use setAdapter() method after fetching data and now my problem is solved . But what I'm asking is Is it unusual to use setAdapter more than once? . In my first attempt I was setting adapter first then trying to use adp.notifyDataSetChanged() after fetching data from server. but now I'm setting adapter again after getting data.
Code:
private List<TImelineDataList> timelineDatalist;
@Override
public void onViewCreated(@NonNull View v, @Nullable Bundle savedInstanceState) {
timelineDataList= new ArrayList<>();
adapter=new CustomRecyclerViewAdapter(timelineDataList);
recyclerView.setItemViewCacheSize(30);
recyclerView.setDrawingCacheEnabled(true);
recyclerView.setDrawingCacheQuality(View.DRAWING_CACHE_QUALITY_HIGH);
recyclerView.setLayoutManager(new
LinearLayoutManager(ctx,LinearLayoutManager.HORIZONTAL,false));
recyclerView.setAdapter(adapter);
}
void addTimelineData(String email,String time,String img_link,String caption){
timelineDataList.add(new TimelineData(email,time,img_link,caption));
adapter=new CustomRecyclerViewAdapter(timelineDataList);
adapter.notifyDataSetChanged();
recyclerView.setAdapter(adapter);
}
private Emitter.Listener handlePosts = new Emitter.Listener(){
@Override
public void call(final Object... args){
try {
JSONArray jsonArray=(JSONArray)args[0];
for(int i=0;i<jsonArray.length();i++){
try {
JSONObject ob=jsonArray.getJSONObject(i);
demo_email=ob.getString("_pid");
demo_time=ob.getString("time");
demo_link=ob.getString("img_link");
demo_caption=ob.getString("caption");
addTimelineData(demo_email,demo_time,demo_link,demo_caption);
} catch (JSONException e) {
e.printStackTrace();
}
}
} catch (Exception e) {
Log.e("error",e.toString());
}
}
};
A: Finally I figured out the problem . The problem was there in constructing adapter twice . Now I've removed the next adapter construction and the setAdapter() as well and it's working without any errors.
Previous Code:
private List<TImelineDataList> timelineDatalist;
@Override
public void onViewCreated(@NonNull View v, @Nullable Bundle savedInstanceState) {
timelineDataList= new ArrayList<>();
**adapter=new CustomRecyclerViewAdapter(timelineDataList);**//Here
recyclerView.setItemViewCacheSize(30);
recyclerView.setDrawingCacheEnabled(true);
recyclerView.setDrawingCacheQuality(View.DRAWING_CACHE_QUALITY_HIGH);
recyclerView.setLayoutManager(new
LinearLayoutManager(ctx,LinearLayoutManager.HORIZONTAL,false));
recyclerView.setAdapter(adapter);
}
void addTimelineData(String email,String time,String img_link,String caption){
timelineDataList.add(new TimelineData(email,time,img_link,caption));
**adapter=new CustomRecyclerViewAdapter(timelineDataList);**//Here
adapter.notifyDataSetChanged();
recyclerView.setAdapter(adapter);
}
private Emitter.Listener handlePosts = new Emitter.Listener(){
@Override
public void call(final Object... args){
try {
JSONArray jsonArray=(JSONArray)args[0];
for(int i=0;i<jsonArray.length();i++){
try {
JSONObject ob=jsonArray.getJSONObject(i);
demo_email=ob.getString("_pid");
demo_time=ob.getString("time");
demo_link=ob.getString("img_link");
demo_caption=ob.getString("caption");
addTimelineData(demo_email,demo_time,demo_link,demo_caption);
} catch (JSONException e) {
e.printStackTrace();
}
}
} catch (Exception e) {
Log.e("error",e.toString());
}
}
};
New Code:
private List<TImelineDataList> timelineDatalist= new ArrayList<>();;
@Override
public void onViewCreated(@NonNull View v, @Nullable Bundle savedInstanceState) {
adapter=new CustomRecyclerViewAdapter(timelineDataList);
recyclerView.setItemViewCacheSize(30);
recyclerView.setDrawingCacheEnabled(true);
recyclerView.setDrawingCacheQuality(View.DRAWING_CACHE_QUALITY_HIGH);
recyclerView.setLayoutManager(new
LinearLayoutManager(ctx,LinearLayoutManager.HORIZONTAL,false));
recyclerView.setAdapter(adapter);
}
void addTimelineData(String email,String time,String img_link,String caption){
timelineDataList.add(new TimelineData(email,time,img_link,caption));
adapter.notifyDataSetChanged():
}
private Emitter.Listener handlePosts = new Emitter.Listener(){
@Override
public void call(final Object... args){
try {
JSONArray jsonArray=(JSONArray)args[0];
for(int i=0;i<jsonArray.length();i++){
try {
JSONObject ob=jsonArray.getJSONObject(i);
demo_email=ob.getString("_pid");
demo_time=ob.getString("time");
demo_link=ob.getString("img_link");
demo_caption=ob.getString("caption");
addTimelineData(demo_email,demo_time,demo_link,demo_caption);
} catch (JSONException e) {
e.printStackTrace();
}
}
} catch (Exception e) {
Log.e("error",e.toString());
}
}
};
A: Call adapter.notifyDataSetChanged() method to update RecyclerView adapter after adding data into arraylist which is attached to adapter.
You can also call method notifyItemInserted(index) which can show item added with animation effect.
A: The proper way is to call notifyDataSetChanged on the adapter or other methods from that family.
The problem with setting adapter will be that your scroll position will be lost.
It looks like the problem is in your CustomRecyclerViewAdapter. Good practice is to move timelineDatalist into the CustomRecyclerViewAdapter and have something like:
void addTimelineData(String email,String time,String img_link,String caption){
adapter.addToTimelineDataList(new TimelineData(email,time,img_link,caption));
adapter.notifyDataSetChanged();
}
Please post your CustomRecyclerViewAdapter for more details.
A: I think its usual to use setAdapter multiple times as it won't create any issues in functionality. But if you want to use
notifyDataSetChanged()
then try not to reinitialize your data while receiving the data if you perform
yourData = newData
then this will reinitialize your old data and notifyDataSetChanged() will not work on that
if its string then try concatenating in the current instance.
A: make some change in method like below code ..
void addTimelineData (String email, String time, String img_link, String caption){
timelineDataList.clear()
timelineDataList.add(new TimelineData(email, time, img_link, caption));
setAdapter();
}
and make one setAdapter method like..
public void setAdapter(){
if (adpter==null){
if(!timelineDataList.isEmpty()){
adapter = new CustomRecyclerViewAdapter(timelineDataList);
}
}
else{
adapter.notifyDataSetChanged();
}
}
and remove the code onCreate() define recyclerView.setAdapter(adapter);
| {
"language": "en",
"url": "https://stackoverflow.com/questions/49050568",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Using a .lib built with Visual Studio in Eclipse/CDT/gcc I am having some trouble compiling a programm with gcc on windows which was initially developed with Visual Studio. So far I was able to resolve almost all problems like missing header files and such, but now I am stuck at one last thing: gcc fails to link to one of the third party libs my program uses (FlyCapture2.lib). It tells me that it does not find any of the functions/methods there. I already checked if the library is actually on the library path and that sort of things, but it still does not work.
I searched a bit around and learned that it might have something to do with the format of .libs created with the Microsoft compiler. Is there any way to convert such a lib to be compatible with gcc? Anything else I might have missed?
(I already found this similar question, but its solution won't work here)
A: In this page the author gives several ways to achieve what you want
| {
"language": "en",
"url": "https://stackoverflow.com/questions/2105769",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Filtering long lists take a long time to run I have a Dropdown with about 7000 objects. I have tried using semantic-ui react components but it still takes a long time to search and get results.
My copyList contains all the options and the filteredCopyList is what is rendered in the dropdown onKeyUp. Is it going slow due to rendering a long list of items and filtering them at the same time?
//list of 7000
const copyList = [
{itemDesc: 'itemDesc1', shortDesc: 'shortDesc1'}
]
filterList = () => {
const re = new RegExp(_.escapeRegExp(this.state.searchCopyList),'i');
const isMatch = result => (re.test(result.shortDesc) ||
re.test(result.itemDesc));
this.setState({
filteredCopyList: _.filter(this.state.copyList, isMatch)
});
}
A: You can try with the following package of npm:
Infinite Scrolling package
| {
"language": "en",
"url": "https://stackoverflow.com/questions/55485084",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: send simple email using codeigniter I am trying to send simple email using codeigniter as explain this link codeigniter email class ,but it doesn't work.
This is my form :
<form method="post" action="<?php base_url()?>main/send_email">
<input type="text" placeholder="Name" name="name" class="name">
<input type="text" placeholder="Surname" name="surname" class="surname">
<input type="email" placeholder="email" name="email" class="email">
<textarea placeholder="What's on your mind" name="text" class="text"></textarea>
<input type="submit" value="SEND" class="send_mail" name="send_mail">
</form>
And this is my controller
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Main extends CI_Controller {
public function __construct(){
parent::__construct();
$this->load->helper("common_helper");
date_default_timezone_set('Asia/Tbilisi');
}
public function index()
{
$this->load->view('pages/main');
}
public function send_email()
{
$this->load->library("email");
if($this->input->post("send_mail"))
{
$name = $this->input->post("name");
$surname = $this->input->post("surname");
$email = $this->input->post("email");
$text = $this->input->post("text");
$this->email->from($email, $name);
$this->email->to('[email protected]');
$this->email->subject('Email Test');
$this->email->message('testing email message');
$this->email->send();
}
}
}
I don't have any error.
A: Try the below code.
$email_config = Array(
'protocol' => 'smtp',
'smtp_host' => 'bh-24.webhostbox.net',
'smtp_port' => '465',
'smtp_user' => '[email protected]',
'smtp_pass' => '12feedback34',
'mailtype' => 'html',
'starttls' => true,
'newline' => "\r\n"
);
$this->load->library('email', $email_config);
$this->email->from($to, 'FEEDBACK');
$this->email->to('[email protected]');
$this->email->subject($sub);
$this->email->message($msg);
$this->email->send();
| {
"language": "en",
"url": "https://stackoverflow.com/questions/38583050",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Bokeh Categorical Data Heatmap Not Showing I am trying to create a Heatmap from a csv using python pandas. I keep on getting a blank screen for my output, and I not sure why-- I've exhausted the documentation online to try to figure it out. My code is as follows:
import numpy as np
from bokeh.io import output_file, show
from bokeh.models import (
ColumnDataSource,
HoverTool,
LinearColorMapper,
BasicTicker,
PrintfTickFormatter,
ColorBar,
FactorRange
)
from bokeh.plotting import figure
from bokeh.sampledata.unemployment1948 import data
from bokeh.transform import transform
#Initialize DataFrame
df = pd.read_csv("myData.csv")
df.dropna().astype(float)
df.columns.name = 'Month'
df.index.name = 'Facility'
df_1 = pd.DataFrame(df.stack(), columns=['state']).reset_index()
source = ColumnDataSource(df_1)
#Heatmap
colors = ["#75968f", "#a5bab7", "#c9d9d3", "#e2e2e2", "#dfccce", "#ddb7b1", "#cc7878", "#933b41", "#550b1d"]
mapper = LinearColorMapper(palette=colors, low=df_1.state.min(), high=df_1.state.max())
TOOLS = "hover,save,pan,box_zoom,reset,wheel_zoom"
p = figure(title="WSSDM4",
x_range= list(df.columns), y_range=list(df.index),
x_axis_location="above", plot_width=1800, plot_height=800,
tools= TOOLS, toolbar_location='below',
tooltips=[('Facility', '@Facility'), ('Month', '@Month')])
p.rect(x='Facility', y = 'Month',width=1, height=1, source=source,
line_color=None, fill_color=transform('state', mapper))
color_bar = ColorBar(color_mapper=mapper, major_label_text_font_size="7px",
ticker=BasicTicker(desired_num_ticks=len(colors)),
label_standoff=6, border_line_color=None, location=(0, 0))
p.add_layout(color_bar, 'right')
p.axis.axis_line_color = None
p.axis.major_tick_line_color = None
p.axis.major_label_text_font_size = "7px"
p.axis.major_label_standoff = 0
p.xaxis.major_label_orientation = 1.0
show(p)
I am using Jupyter notebooks and have all the up-to-date libraries.
Thank you!
A: I believe your problem is this line:
df.index.name = 'Facility'
All this would do is name the existing df index (which looks like 0, 1, 2, 3...) "Facility," rather than taking the existing Facility column and making it the index. To do that, you'd want:
df = df.set_index('Facility')
I found this discrepancy by adding a bunch of print(df.head()) statements after each line where your code modified the dataset, and doing the same in the original Bokeh heatmap example, and looking for where they diverged. Might be useful in case there are other problems.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/63274346",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: GET request variable error in PHP I have a simple PHP code, as below.
When I try the URL localhost/df.php?result1=bharat, I get the result Bharat, exactly as I want it. But when I try the URL localhost/df.php?result2=bharat, I get an error, meaning my result2 variable was not read like my result1 variable did.
Could you please correct my code so that it works?
<?php
if(isset($_GET['Result1']))
{
$file = $_GET['Result1'];
}
else
{
echo "Error"; exit;
}
echo "$result1";
?>
elseif(isset($_GET['Result2']))
{
$file = $_GET['Result2'];
}
else
{
echo "Error"; exit;
}
echo "$result2";
?>
A: You have way too many errors in your code. The following is the solution to your problem:
<?php
if(isset($_GET['result1']))
{
$result1 = $_GET['result1'];
echo $result1;
}
elseif(isset($_GET['result2']))
{
$result2 = $_GET['result2'];
echo $result2;
}
else
{
echo "Error";
exit();
}
?>
For the future, I would recommend you to learn PHP and be familiar with the basic syntax, at least, before posting questions about it here.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/32243116",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-3"
} |
Q: AngularJS - Pass dynamic object value and call function from Directive Ctlr.js
app.controller('myCtrl', function($scope) {
$scope.data = {
waterMarkImgPosition: [
{id: 'lowerRight', name: 'Lower Right'},
{id: 'lowerLeft', name: 'Lower Left'},
{id: 'upperRight', name: 'Upper Right'},
{id: 'upperLeft', name: 'Upper left'},
{id: 'center', name: 'Center'}
],
selectedPosition: {id: 'upperRight', name: 'UpperRight'} //This sets the default value of the select in the ui
};
$scope.watermarkPosition = $scope.data.selectedPosition.id; //pass default position for watermark
});
Directive.js
app.directive('waterMark', function($timeout) {
return {
restrict: 'EA',
link: function(scope,element,attrbs) {
scope.videoSnapshotPath = 'img/watermark.png';
scope.watermarkLogoPath = 'img/logo.jpg';
//fetch position selected from dropdown
scope.changePosition = function(imgposition) {
scope.watermarkPosition = imgposition.id;
if(scope.watermarkPosition == 'lowerRight'){
$timeout(function() {
watermark([scope.videoSnapshotPath, scope.watermarkLogoPath])
.image(watermark.image.lowerRight(0.5))
.then(function (img) {
document.getElementById('lowerRight').appendChild(img);
})
}, 5);
}else if(scope.watermarkPosition == 'upperRight'){
$timeout(function() {
watermark([scope.videoSnapshotPath, scope.watermarkLogoPath])
.image(watermark.image.upperRight(0.5))
.then(function (img) {
document.getElementById('upperRight').appendChild(img);
})
}, 5);
}
}
}
}
});
Img Preview
<div class="col-lg-9" data-water-mark id="{{watermarkPosition}}"></div>
Initially div will load with id='upperRight' selected as passed in controller and watermark will set its position accordingly. Now when user selects upperLeft, the position will be passed and bind to div resulting in id='upperLeft'.
*
*How do I execute watermark function conditionally based on
position selected by user without images getting appended ?
*If not conditionally, how can I dynamically pass the position
selected in watermark.image.upperRight(0.5) and
document.getElementById('upperRight').appendChild(img); ?
Watermark Plugin - http://brianium.github.io/watermarkjs/images.html
| {
"language": "en",
"url": "https://stackoverflow.com/questions/38200349",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Clustered vs Non-Clustered My lower level knowledge of SQL (Server 2008) is limited, and is now being challanged by our DBAs. Let me explain (I have mentioned obvious statements in the hope that I am right, but if you see something wrong, please tell me) the scenario:
We have a table which holds 'Court Orders' for people. When I created the table, (Name: CourtOrder), I created it like:
CREATE TABLE dbo.CourtOrder
(
CourtOrderID INT NOT NULL IDENTITY(1,1), (Primary Key)
PersonId INT NOT NULL,
+ around 20 other fields of different types.
)
I then applied a non-clustered index to the primary key (for efficiency). My reasons is that it is a unique field (primary key), and should be indexed, mainly for selection purposes, as we often Select from table where primary key = ...
I then applied a CLUSTERED index on PersonId. The reason was to group orders for a particular person physically, as the vast majority of work is getting orders for a person. So, select from mytable where personId = ...
I have been pulled up on this now. I have been told that we should put the clustered index on the primary key, and the normal index on the personId. That seems very strange to me. First off, why would you put a clustered index on a unique column? what is it clustering? Surely that's a waste of the clustered index? I'd have believed a normal index would be used on a unique column. Also, clustering the index would mean we can't cluster a different column (One per table, right?).
The reasoning for me being told I have made a mistake is that they believe putting a clustered index on the PersonId would make inserts slow. For the 5% gain in speed of a select, we would be getting a 95% degradation in speed on inserts and updates. Is that correct and valid?
They say that because we cluster the personId, SQL Server has to rearrange data when ever we insert or make a change to the PersonId.
So then I have asked, why would SQL have the concept of a CLUSTERED INDEX, if it's so slow? Is it as slow as they're saying? How should I have setup my indexes to achieve optimum performance? I'd have thought SELECT is used more than INSERT... but they say that we're having locking issues on INSERTS...
Hope someone can help me.
A: Some authors do suggest not "wasting" the CI on an identity column if there is an alternative that would benefit range queries.
From MSDN Clustered Index Design Guidelines the key should be chosen according to the following criteria
*
*Can be used for frequently used queries.
*Provide a high degree of uniqueness.
*Can be used in range queries.
Your CourtOrderID column meets 2. Your PersonId meets 1 and 3. As most rows will end up with the uniqueifier added anyway you might as well just declare it as unique and use PersonId,CourtOrderID as this will be the same width but be more useful as the clustered index key is added to all NCIs as the row locator and this will allow them to cover more queries.
The main issue with using PersonId,CourtOrderID as the CI is that logical fragmentation will likely ensue (and this particularly affects the range queries you are trying to help) so you would need to monitor fill factor, and fragmentation levels and perform index maintenance more often.
A: It's explained in the following link: https://msdn.microsoft.com/en-us/ms190457.aspx
Clustered
*
*Clustered indexes sort and store the data rows in the table or view based on their key values. These are the columns included in the index definition. There can be only one clustered index per table, because the data rows themselves can be sorted in only one order.
*The only time the data rows in a table are stored in sorted order is when the table contains a clustered index. When a table has a clustered index, the table is called a clustered table. If a table has no clustered index, its data rows are stored in an unordered structure called a heap.
Nonclustered
*
*Nonclustered indexes have a structure separate from the data rows. A nonclustered index contains the nonclustered index key values and each key value entry has a pointer to the data row that contains the key value.
*The pointer from an index row in a nonclustered index to a data row is called a row locator. The structure of the row locator depends on whether the data pages are stored in a heap or a clustered table. For a heap, a row locator is a pointer to the row. For a clustered table, the row locator is the clustered index key.
*You can add nonkey columns to the leaf level of the nonclustered index to by-pass existing index key limits, 900 bytes and 16 key columns, and execute fully covered, indexed, queries.
A: I am by no means a SQL Expert...so take this as a developer's view rather than a DBA view..
Inserts on clustered (physically ordered) indexes that aren't in sequential order cause extra work for inserts/updates. Also, if you have many inserts happening at once and they are all occurring in the same location, you end up with contention. Your specific performance varies based on your data and how you access it. The general rule of thumb is to build your clustered index on the most unique narrow value in your table (typically the PK)
I'm assuming your PersonId won't be changing, so Updates don't come into play here. But consider a snapshot of a few rows with PersonId of
1
2
3
3
4
5
6
7
8
8
Now insert 20 new rows for PersonId of 3. First, since this is not a unique key, the server adds some extra bytes to your value (behind the scenes) to make it unique (which also adds extra space) and then the location where these will reside has to be altered. Compare that to inserting an auto-incrementing PK where the inserts happen at the end. The non technical explanation would likely come down to this: there is less 'leaf-shuffling' work to do if it's naturally progressing higher values at the end of the table versus reworking location of the existing items at that location while inserting your items.
Now, if you are having issues with Inserts then you are likely inserting a bunch of the same (or similar) PersonId values at once which is causing this extra work in various places throughout the table and the fragmentation is killing you. The downside of switching to the PK being clustered in your case, is if you are having insert issues today on PersonIds that vary in value spread throughout the table, if you switch your clustered index to the PK and all of the inserts now happen in one location then your problem may actually get worse due to increased contention concentration. (On the flip side, if your inserts today are not spread out all over, but are all typically bunched in similar areas, then your problem will likely ease by switching your clustered index away from PersonId to your PK because you'll be minimizing the fragmentation.)
Your performance problems should be analyzed to your unique situation and take these types of answers as general guidelines only. Your best bet is to rely on a DBA that can validate exactly where your problems lie. It sounds like you have resource contention issues that may be beyond a simple index tweak. This could be a symptom of a much larger problem. (Likely design issues...otherwise resource limitations.)
In any case, good luck!
A: The distinction between a clustered vs. non-clustered index is that the clustered index determines the physical order of the rows in the database. In other words, applying the clustered index to PersonId means that the rows will be physically sorted by PersonId in the table, allowing an index search on this to go straight to the row (rather than a non-clustered index, which would direct you to the row's location, adding an extra step).
That said, it's unusual for the primary key not to be the clustered index, but not unheard of. The issue with your scenario is actually the opposite of what you're assuming: you want unique values in a clustered index, not duplicates. Because the clustered index determines the physical order of the row, if the index is on a non-unique column, then the server has to add a background value to rows who have a duplicate key value (in your case, any rows with the same PersonId) so that the combined value (key + background value) is unique.
The only thing I would suggest is not using a surrogate key (your CourtOrderId) column as the primary key, but instead use a compound primary key of the PersonId and some other uniquely-identifying column or set of columns. If that's not possible (or not practical), though, then put the clustered index on CourtOrderId.
A: Some db with some nasty selects, joins in a stored procedure - only diffrence is the index
INDEXES - clustered vs nonclustered
891 rows
10 sec
NONCLUSTERED
OR
891 rows
14 sec
CLUSTERED
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7605707",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "100"
} |
Q: VB.net if Day(Now) = 1 I want this program to do something on a certain day (birthday)
I have tried
If Date.Day(Now) = 1 And Month(Now) = 3 Then
MsgBox("Happy Birthday!")
End If
But Date.Day(Now) does not appear to be correct (Month(Now) works fine).
The error is:
Operator '=' is not defined for types 'Date' and 'Integer'
A: Use the NET Framework DateTime structure and its properties instead
If DateTime.Now.Day = 13 And DateTime.Now.Month = 9 Then
Console.WriteLine("Happy Birthday!")
End If
As hinted below in the comments, you are mixing calls to the VB6 compatibility library (Month(Now) from Microsoft.VisualBasic.dll) and calls to DateTime structure (Date alias), but the DateTime structure doesn't have a shared member called Day, instead it has a shared property named Now and from this property you can extract the Day value.
If you insist in using the Microsoft.VisualBasic compatibility library then your code should be
If Day(Now) = 13 And Month(Now) = 9 Then
.....
| {
"language": "en",
"url": "https://stackoverflow.com/questions/39479246",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
} |
Q: RMQ on static 2D array in constant time The input is an array (n*m 1<n,m< 1000). I have to find the maximum element in every sub-matrice of size( a*b ).
I was trying to do this by iterating x over n-a+1 and y over m-j+1.
*
*2D segment trees or quad trees are not sufficiently fast as the number of queries is large.
*I tried to extend sparse table but was not able to due to shortage of space.
*I have read about solutions with Cartesian trees but some code is needed as I cannot understand it.
Please explain a solution that will answer a query in O(nm) time or in O(1) time by pre-computation. Also, the input array is static.
Note: although I've tried sparse table, it might not have been correct, so feel free to post a solution with it.
I'm a Java coder, so an implementation in Java or c/c++ would be great.
Also this is not a duplicate as I have searched a lot about it without finding anything suitable.
A: Number of possibilities:
(From Number of submatrix of size AxB in a matrix of size MxN)
In a matrix of size (m*n), there are (n-A+1)*(m-B+1) different matrices of size (A*B).
So the total number of possible input for your function is sum((n-A+1)*(m-B+1)) where A=1..n and B=1..m.
EDIT:
This is getting so huge when m=1000.
O(m^2n^2) is O(1000^4)... 1 trillion ... this won't fit in my small computer's memory :)
Structure:
I propose you build an hashmap that you simply index with the boundaries of your matrix:
A string built from a=M(i,j), b=M(k,l) where 0< i < k <(n+1) and 0< j < l <(m+1)
*
*e.g. you can build is so: aHashMap("["+i+","+j+"].["+k+","+l+"]")
Pre-computation:
*
*Have a function that calculates the max of a given matrix (a[i,j],b[k,l]) - say myMax(i,j,k,l). I assume there is no point showing you how.
*Then its easy (sorry I can't easily compile anything so I give only the principle for now):
for i=1 to n-1 do
for j=1 to m-1 do
for k=i to n do
for l=j to m do
aHashMap("["+i+","+j+"].["+k+","+l+"]") = myMax(i,j,k,l)
next
next
next
next
This is O(n^4), but assuming its pre-computational, there's no point, it just make your program bigger and bigger when storing aHashMap.
Good to know
Such problem also seem to be widely addressed at http://cs.stackexchange.com ; e.g. this or that... so this SE could be of interest to the OP.
Implementation of this naive approach:
With 99 x 95 it already gives millions of possibilities to pre-compute, taking about 3Go RAM!
$ ./p1
enter number of rows:99
enter number of cols:95
pre-computing...
hashmap ready with 22572000 entries.
matrix.h
#ifndef myMatrix_JCHO
#define myMatrix_JCHO
typedef unsigned int u_it;
class Matrix
{
public:
Matrix(u_it _n, u_it _m);
Matrix(const Matrix& matr);
Matrix& operator=(const Matrix& matr);
~Matrix();
u_it getNumRows() ;
u_it getNumCols() ;
int getC(u_it i, u_it j);
void setC(u_it i, u_it j, int v);
void printMatrix();
int maxSub(u_it a_i, u_it a_j, u_it b_k, u_it b_l);
private:
u_it n, m;
int **pC;
};
#endif
matrix.cpp
#include <iostream>
#include <string>
#include <sstream>
#include "matrix.h"
Matrix::Matrix(u_it _n, u_it _m) {
n=_n;
m=_m;
int k=0;
pC = new int*[n];
for (u_it i=0; i<n; ++i){
pC[i]=new int[m];
for(u_it j=0; j<m; ++j){
pC[i][j]=++k;
}
}
}
Matrix::~Matrix(){
for (u_it i=0; i<n; ++i){
delete [] pC[i];
}
delete [] pC;
std::cout << "matrix destroyed\n";
}
u_it Matrix::getNumRows() {
return n;
}
u_it Matrix::getNumCols() {
return m;
}
int Matrix::getC(u_it i, u_it j){
return pC[i][j];
}
void Matrix::setC(u_it i, u_it j, int v){
pC[i][j]=v;
}
void Matrix::printMatrix(){
for (u_it i=0; i<n; ++i){
std::cout << "row " <<i<<" [ ";
for(u_it j=0; j<m; ++j){
std::cout << pC[i][j] << '\t';
}
std::cout << "]\n";
}
}
// Return max of submatrix a(i,j); b(k,l)
int Matrix::maxSub(u_it a_i, u_it a_j, u_it b_k, u_it b_l) {
int res = -100000;
if (a_i<=b_k && a_j<=b_l && b_k<n && b_l<m) {
for (u_it i=a_i; i<=b_k; ++i){
for(u_it j=a_j; j<=b_l; ++j){
res= (pC[i][j]>res)? pC[i][j] : res;
}
}
} else {
std::cout << "invalid arguments: out of bounds\n";
return -100000;
}
return res;
}
main.cpp
#include <iostream>
#include <string>
#include <sstream>
#include <map>
#include <cassert>
#include "matrix.h"
std::string hashKey(u_it a_i, u_it a_j, u_it b_k, u_it b_l) {
std::stringstream ss;
ss << "max(a[" << a_i << "," << a_j << "],b[" << b_k << "," << b_l << "]";
return ss.str();
}
int main() {
u_it n_rows, n_cols;
std::cout << " enter number of rows:";
std::cin >> n_rows;
std::cout << " enter number of cols:";
std::cin >> n_cols;
std::cout << " pre-computing...\n";
std::map<std::string, int> myHMap;
Matrix * mat=new Matrix(n_rows,n_cols);
//mat->printMatrix();
// "PRE" computation
for (u_it i=0; i<n_rows; ++i) {
for (u_it j=0; j<n_cols; ++j) {
for (u_it k=i; k<n_rows; ++k) {
for (u_it l=j; l<n_cols; ++l) {
//std::cout <<"max(a["<<i<<","<<j<<"],b["<<k<<","<<l<<"]"<< mat->maxSub(i, j, k, l) <<'\n';
//std::cout << mat->hashKey(i, j, k ,l) <<" -> " << mat->maxSub(i, j, k, l) <<'\n';
myHMap[hashKey(i, j, k ,l)] = mat->maxSub(i, j, k, l);
}
}
}
}
std::cout << " hashmap ready with "<< myHMap.size() <<" entries.\n";
// call to values
u_it cw_i, cw_j, cw_k, cw_l;
cw_i=0;
std::string hKey;
while (cw_i < n_rows+1) {
std::cout << " enter i,:";
std::cin >> cw_i;
std::cout << " enter j,:";
std::cin >> cw_j;
std::cout << " enter k,:";
std::cin >> cw_k;
std::cout << " enter l:";
std::cin >> cw_l;
hKey = hashKey(cw_i, cw_j, cw_k, cw_l);
std::map<std::string, int>::iterator i = myHMap.find(hKey);
assert(i != myHMap.end());
std::cout << i->first <<" -> " << i->second <<'\n';
}
}
make
g++ -std=c++0x -std=c++0x -Wall -c -g matrix.cpp
g++ -std=c++0x -std=c++0x -Wall -c -g main.cpp
g++ -std=c++0x -std=c++0x -Wall -g matrix.o main.o -o p1
A: I found the answer to have it compute in O(mn) - still with a little pre-computation - but this time that last one is easily O(mn.log(mn)) too: its just ordering a list of all the matrix's values.
Pre-compute:
First step is to simply build an orderly structure of the matrix's values, say M(A), then use <algorithm>std::sort to order that structure.
Retreive max of any sub-matrix (a,b):
To get the max of any matrix, just start with the biggest from pre-computed structure M(A) and check if it is within (a,b).
*
*If it is, then you're done
*Else, take the next one in M(A)
matrix.h
#ifndef myMatrix_JCHO
#define myMatrix_JCHO
typedef unsigned int u_it;
typedef std::pair<u_it, u_it> uup;
class Matrix
{
public:
Matrix(u_it _n, u_it _m);
Matrix(const Matrix& matr);
Matrix& operator=(const Matrix& matr);
~Matrix();
u_it getNumRows() ;
u_it getNumCols() ;
int getC(u_it i, u_it j);
void setC(u_it i, u_it j, int v);
void printMatrix();
int maxSub(u_it a_i, u_it a_j, u_it b_k, u_it b_l);
private:
u_it n, m;
int **pC;
};
#endif
matrix.cpp
#include <iostream>
#include <string>
#include <sstream>
#include "matrix.h"
Matrix::Matrix(u_it _n, u_it _m) {
n=_n;
m=_m;
//int k=0;
pC = new int*[n];
for (u_it i=0; i<n; ++i){
pC[i]=new int[m];
for(u_it j=0; j<m; ++j){
pC[i][j]=rand()%1000;
}
}
}
Matrix::~Matrix(){
for (u_it i=0; i<n; ++i){
delete [] pC[i];
}
delete [] pC;
std::cout << "matrix destroyed\n";
}
u_it Matrix::getNumRows() {
return n;
}
u_it Matrix::getNumCols() {
return m;
}
int Matrix::getC(u_it i, u_it j){
return pC[i][j];
}
void Matrix::setC(u_it i, u_it j, int v){
pC[i][j]=v;
}
void Matrix::printMatrix(){
for (u_it i=0; i<n; ++i){
std::cout << "row " <<i<<" [ ";
for(u_it j=0; j<m; ++j){
std::cout << pC[i][j] << '\t';
}
std::cout << "]\n";
}
}
main.cpp
#include <iostream>
#include <string>
#include <utility>
#include <algorithm>
#include <vector>
#include "matrix.h"
// sort function for my vector of pair:
bool oMyV(std::pair<uup, int> x, std::pair<uup, int> y) { return (x.second > y.second); }
// check that p is within matrix formed by a and b
bool isIn_a_b(uup p, uup a, uup b){
bool res = false;
if (p.first >= a.first && p.first <= b.first) {
if (p.second >= a.second && p.second <= b.second) {
res = true;
}
}
return res;
}
int main() {
u_it n_rows, n_cols;
std::cout << " enter number of rows:";
std::cin >> n_rows;
std::cout << " enter number of cols:";
std::cin >> n_cols;
std::cout << " pre-computing...\n";
std::pair<uup, int> *ps;
std::vector<std::pair<uup, int> > myV;
Matrix * mat=new Matrix(n_rows,n_cols);
// print to debug:
mat->printMatrix();
// "PRE" computation
for (u_it i=0; i<n_rows; ++i) {
for (u_it j=0; j<n_cols; ++j) {
ps=new std::pair<uup, int>(std::make_pair(i,j), mat->getC(i,j));
myV.push_back(*ps);
}
}
std::sort(myV.begin(), myV.end(), oMyV);
/* in case you want to print ordered valuet ordered valuess for debug */
for (std::vector<std::pair<uup, int> >::iterator it=myV.begin(); it!=myV.end(); ++it) {
std::cout << it->second << " at [" << it->first.first <<','<<it->first.second<< "]\n";
}
/**/
// call to values
bool byebye=false;
uup a, b;
do {
std::cout << " enter i,:"; std::cin >> a.first;
std::cout << " enter j,:"; std::cin >> a.second;
std::cout << " enter k,:"; std::cin >> b.first;
std::cout << " enter l,:"; std::cin >> b.second;
std::vector<std::pair<uup, int> >::iterator it=myV.begin();
std::cout << " a:["<<a.first<<','<<a.second<<"]-b:["<<b.first<<','<<b.second<<"] in ";
std::cout << " M:[0,0]--:["<<n_rows-1<<','<<n_cols-1<<"]\n";
// check validity:
if ( isIn_a_b(a, std::make_pair(0,0), std::make_pair(n_rows-1, n_cols-1) )
&& isIn_a_b(b, std::make_pair(0,0), std::make_pair(n_rows-1, n_cols-1) )
&& (a.first <= b.first)
&& (a.second <= b.second)
) {
while (! isIn_a_b(it->first, a, b) && it!=myV.end()){
++it;
}
std::cout << "Found:" << it->second << " at [" << it->first.first <<','<<it->first.second<< "]\n";
} else {
std::cout << "makes no sense. bye.\n";
byebye=true;
}
} while (!byebye);
}
Makefile
(don't forget: tabulate in Makefile)
OBJS = matrix.o main.o
CC = g++ -std=c++0x
DEBUG = -g
CFLAGS = -std=c++0x -Wall -c $(DEBUG)
LFLAGS = -std=c++0x -Wall $(DEBUG)
TARFILE = ${HOME}/jcho/good/matrix.tar
p1 : $(OBJS)
$(CC) $(LFLAGS) $(OBJS) -o p1
matrix.o: matrix.cpp matrix.h
$(CC) $(CFLAGS) matrix.cpp
main.o: main.cpp matrix.h
$(CC) $(CFLAGS) main.cpp
clean:
\rm -f *.o *~ p1
tar:
tar cfv $(TARFILE) *.h *.cpp Makefile \
p1 && \
echo "tar $(TARFILE) created successfuly."
| {
"language": "en",
"url": "https://stackoverflow.com/questions/37683084",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: media query for tablet don't work i created responsive web design site.
here is some problem.
visit my site(http://red2.net/rwd2/), and reduce browser's width(768px ~ 959px).
but media query for tablet that can't change site's layout.
below is tablet css.
/* 태블릿용 CSS */
@media all and (min-width:768px){
#toggle-menu{
position:absolute;
/*
top:0;
left:-210px;
display:block;
*/
}
.content{
display:flex;
flex-direction:column;
}
.latest-article{
width:50%;
/* border:1px solid #000; */
/* 스타일이 안먹힌다 -_-a */
}
/* 모바일에서 제목을 제외한 것들을 다시 보여준다. */
#board-table thead tr th:first-child, #board-table tbody tr td:first-child,
#board-table thead tr th:nth-child(2), #board-table tbody tr td:nth-child(2),
#board-table thead tr th:nth-child(4), #board-table tbody tr td:nth-child(4),
/* #board-table thead tr th:nth-child(5), #board-table tbody tr td:nth-child(5), */
#board-table thead tr th:nth-child(6), #board-table tbody tr td:nth-child(6){
display:table-cell;
}
}
full site css
@charset "utf-8";
/* 링크 스타일 */
a:link {
color:#00f;
text-decoration:underline;
}
a:visited {
color: #800080;
text-decoration: underline;
}
a:hover {
color: #f00;
text-decoration: underline;
}
a:active {
color: #f00;
text-decoration: underline;
}
#header-menu a:link, #header-menu a:visited {
color: #000;
text-decoration: none;
}
#header-menu a:hover, #header-menu a:active {
color: #f00;
text-decoration: none;
}
#logo a:link, #logo a:visited {
color: #000;
text-decoration: none;
}
#logo a:hover, #logo a:active {
color: #f00;
text-decoration: none;
}
#toggle-menu a:link, #toggle-menu a:visited {
color: #fff;
text-decoration: none;
}
#toggle-menu a:hover, #toggle-menu a:active {
color: #f00;
text-decoration: none;
}
#toggle-menu section a:link, #toggle-menu section a:visited {
color: #fff;
text-decoration: none;
}
#toggle-menu section a:hover, #toggle-menu section a:active {
color: #f00;
text-decoration: none;
}
.content .latest-article a:link, .content .latest-article a:visited {
color: #000;
text-decoration: none;
}
.content .latest-article a:hover, .content .latest-article a:active {
color: #f00;
text-decoration: none;
}
#sidebar-menu a:link, #sidebar-menu a:visited {
color: #fff;
text-decoration: none;
}
#sidebar-menu a:hover, #sidebar-menu a:active {
color: #f00;
text-decoration: none;
}
#footer a:link, #footer a:visited {
color: #fff;
text-decoration: none;
}
#footer a:hover, #footer a:active {
color: #f00;
text-decoration: none;
}
#board-table thead a:link, #board-table thead a:visited {
color: #fff;
text-decoration: underline;
}
#board-table thead a:hover, #board-table thead a:active {
color: #f00;
text-decoration: underline;
}
#board-table tbody a:link, #board-table tbody a:visited {
color: #004db1;
text-decoration: none;
}
#board-table tbody a:hover, #board-table tbody a:active {
color: #f00;
text-decoration: underline;
}
.content-board h2 a:link, .content-board h2 a:visited {
color: #000;
text-decoration: none;
}
.content-board h2 a:hover, .content-board h2 a:active {
color: #f00;
text-decoration: underline;
}
#board-list-function-top a:link, #board-list-function-top a:visited {
color: #000;
text-decoration: none;
}
#board-list-function-top a:hover, #board-list-function-top a:active {
color: #f00;
text-decoration: none;
}
#board-list-function-bottom a:link, #board-list-function-bottom a:visited {
color: #000;
text-decoration: none;
}
#board-list-function-bottom a:hover, #board-list-function-bottom a:active {
color: #f00;
text-decoration: none;
}
#board-list-function-bottom div a:link, #board-list-function-bottom div a:visited {
color: #fff;
text-decoration: none;
}
#board-list-function-bottom div a:hover, #board-list-function-bottom div a:active {
color: #fff;
text-decoration: none;
}
#board-list-page a:link, #board-list-page a:visited {
color: #000;
text-decoration: none;
}
#board-list-page a:hover, #board-list-page a:active {
color: #f00;
text-decoration: none;
}
/* 모바일용 CSS */
#wrap{
display:flex;
flex-flow:column nowrap;
width:100%; /* 80%; */
margin:0 auto;
max-width:1200px;
background:#e1e1e1;
}
#wrap section, #wrap aside{
box-sizing:border-box;
}
#header-menu{
/* order:1; */
width:100%;
/* background:#2ecc71; */
/* border-bottom:1px solid #39d67c; */
display:none;
}
#header-menu-list{
display:flex;
justify-content:flex-end;
}
#header-menu-list li{
/* width:25%; */
text-align:center;
}
#header-menu-list li a{
display:block;
padding:15px 15px;
padding:0.938rem 0.938rem;
}
#header{
display:flex;
/* order:2; */
flex-direction:column;
position:relative;
width:100%;
}
#logo{
/* order:1; */
width:100%;
height:50px;
/*
padding:14px;
padding:1rem;
font-size:1.188em;
font-size:1.188rem;
line-height:20px;
*/
line-height:50px;
text-align:center;
/* text-transform:uppercase; */
/* background:#e1e1e1; */ /* #2ecc71; */
/* text-shadow:0px 1px 1px #25ab5e; */
font-family:'Verdana Bold';
letter-spacing:-0.2rem;
background:#e1e1e1 url(../images/s_images/logo_small.png) center center no-repeat;
text-indent:-9999px;
}
/*
#logo:hover{
background:#e1e1e1 url(images/s_images/logo_small_over.png) center center no-repeat;
}
*/
#logo a{
margin:0 auto;
display:block;
width:160px;
height:50px;
line-height:50px;
/* border:1px solid #000; */
}
/*
#logo span{
color:#f00;
}
*/
/* px -> rem 계산기 -_-zz */
/* http://foliovision.com/2013/03/responsive-design-calculator */
#toggle-button{
display:block;
width:50px;
width:3.57142857rem;
height:50px;
height:3.57142857rem;
position:absolute;
/* top:10px; */
/* top:0.625rem; */
top:0;
/* right:10px; */
/* right:0.625rem; */
left:0;
text-indent:-9999px;
background:url(../images/s_images/menu_toggle_btn.png) no-repeat;
cursor:pointer;
}
#toggle-menu{
display:none;
background:#333;
color:#fff;
position:relative;
}
#toggle-menu ul ul{
display:none;
/* width:100%; */
/* border:1px solid #000; */
}
#toggle-menu li{
display:flex;
background: #313337;/* #2c3e50; */
/* border-top:1px solid #3f4145; */
/* border-bottom:1px solid #131416; */
}
/* 하위 메뉴 토글 버튼을 누르면 나오는 메뉴 */
#toggle-menu li li{
/* display:block; */
background:#1f2023; /* #3d3d78; */
/* width:100%; */
text-indent:15px;
/* border-bottom:1px solid #000; */
}
#toggle-menu nav li a{
width:80%;
padding:15px; /* 20px 20px; */
padding:1.07142857rem;
/* padding:1.250rem 1.250rem; */
}
#toggle-menu li span{
width:20%;
text-indent:-9999px;
background:url(../images/s_images/sub_menu_toggle_btn.png) center center no-repeat;
cursor:pointer;
/* text-align:center; */
/* vertical-align:middle; */
/* border:1px solid #000; */
/* border-left:1px solid #000; */
}
/* #toggle-menu li span:hover{ */
/* background:url(images/s_images/sub_menu_toggle_btn_hover.png) center center no-repeat; */
/* text-align:center; */
/* vertical-align:middle; */
/* border:1px solid #000; */
/* border-left:1px solid #000; */
/* } */
/* 목록 안의 요소들을 위에서 아래로 배치 -_-! */
#toggle-menu nav *{
display:flex;
flex-direction:column;
}
/* div 안의 요소들을 왼쪽에서 오른쪽으로 배치 */
#toggle-menu div{
display:flex;
flex-direction:row;
}
/*
#search{
display:none;
flex-direction:;
}
*/
#login{
}
#login, #search{
padding:15px;
padding:1.07142857rem;
}
#search-button{
padding:5px;
padding:0.35714286rem;
}
/*
#search input[type="text"]{
width:260px;
border:1px solid #000;
}
*/
.content{
/* padding:40px 12.5%; */
width:100%;
/*
margin:10px auto;
margin:0.71428571rem auto;
padding:5px;
padding:0.35714286rem;
*/
/* 40px ÷ 320px */
background:#fff;
/* order:1; */
}
#sidebar-menu{
/*
margin:10px;
margin:0.71428571rem;
padding:5px;
padding:0.35714286rem;
*/
background:#666;
}
#sidebar-menu h2{
color:#fff;
background:#06c;
padding:5px;
padding:0.35714286rem;
line-height:30px;
line-height:2.14285714rem;
}
#sidebar-menu ul{
list-style-type:none;
text-indent:10px;
text-indent:0.71428571rem;
line-height:30px;
line-height:2.14285714rem;
}
#toggle-menu section{
color:#fff;
background:;#666 /* #1d1e20; */
}
.latest-article{
width:100%;
}
.content .latest-article ul{
padding-left:5px;
padding-left:0.35714286rem;
text-indent:10px;
text-indent:0.71428571rem;
line-height:30px;
line-height:2.14285714rem;
}
.content .latest-article li{
list-style:none; /* square; */
/* list-style-position:inside; */
background:url(../images/s_images/bullet.gif) no-repeat left;
}
/* http://www.w3schools.com/cssref/pr_list-style-position.asp */
.latest-article a, #sidebar-menu a{
width:100%;
display:block;
}
#wrap-content{
/* width:90%; */
/*
margin-bottom:10px;
margin-bottom:0.71428571rem;
*/
/*
padding:14px;
padding:1rem;
*/
background:#fff;
}
#footer{
width:100%;
text-align:center;
background:#333;
color:#fff;
line-height:40px;
line-height:2.85714286rem;
}
#footer ul{
display:flex;
justify-content:center;
}
/*
#footer ul li{
padding-right:1rem;
}
*/
#footer ul li:last-child{
padding-right:0; /* 마지막 목록은 오른쪽 여백이 없음 */
}
#footer a{
padding:10px;
padding:0.71428571rem;
}
/* 모바일, 태블릿에서는 외부 로그인 안뜨게 */
#sidebar-outlogin{
display:none;
}
/* 구글 애드센스 */
#banner-bottom{
/* background:#e1e1e1; */
/* margin-bottom:10px; */
text-align:center;
}
/* 게시판 목록 스타일 */
.content-board{
display:block;
/* flex-direction:row; */
}
#board-table{
width:100%;
margin-bottom:1rem;
}
#board-table caption{
position:absolute;
top:-9999px;
left:-9999px;
width:1px;
height:1px;
overflow:hidden;
visibility:hidden;
}
/* 모바일에서 제목을 제외한 것들을 숨긴다. */
#board-table thead tr th:first-child, #board-table tbody tr td:first-child,
#board-table thead tr th:nth-child(2), #board-table tbody tr td:nth-child(2),
#board-table thead tr th:nth-child(4), #board-table tbody tr td:nth-child(4),
#board-table thead tr th:nth-child(5), #board-table tbody tr td:nth-child(5),
#board-table thead tr th:nth-child(6), #board-table tbody tr td:nth-child(6){
display:none;
}
#board-table thead tr th:first-child, #board-table tbody tr td:first-child,
#board-table thead tr th:nth-child(2), #board-table tbody tr td:nth-child(2),
#board-table thead tr th:nth-child(5), #board-table tbody tr td:nth-child(5),
#board-table thead tr th:nth-child(6), #board-table tbody tr td:nth-child(6){
text-align:center;
}
/* 게시판 테이블 셀 너비 지정 */
#board-table thead tr th:first-child, #board-table tbody tr td:first-child{
width:10%;
}
#board-table thead tr th:first-child, #board-table tbody tr td:nth-child(2){
width:10%;
}
#board-table thead tr th:first-child, #board-table tbody tr td:nth-child(3){
width:45%;
}
#board-table thead tr th:first-child, #board-table tbody tr td:nth-child(4){
width:15%;
}
#board-table thead tr th:first-child, #board-table tbody tr td:nth-child(5){
width:10%;
}
#board-table thead tr th:first-child, #board-table tbody tr td:nth-child(6){
width:10%;
}
#board-table tbody tr{
/* border-bottom:1px dotted #000; */
}
/*
#board-table tbody tr:hover{
background:#00b0ff;
}
*/
/* 참고: http://www.ign.com/boards/forums/pc.7203/ */
#board-table tbody tr:nth-child(odd){
background:#f6f6f6;
}
/*
#board-table tbody tr:nth-child(odd):hover{
background:#d6e7f9;
}
*/
#board-table thead{
color:#fff;
background:#06c;
}
#board-table thead tr th{
padding:10px; /* 18px 0; */
/* padding:1.125rem 0; */
}
#board-table tbody tr td{
padding:10px; /* 22px 0; */
/* padding:1.375rem 0; */
}
/*
#board-table tbody tr:hover{
background:#d6e7f9;
}
*/
/* RSS, 관리자 */
#board-list-function-top{
display:flex;
justify-content:flex-end;
}
#board-list-function-top ul{
display:flex;
}
#board-list-function-top a{
margin-right:5px;
display:block;
padding:10px;
}
/* 목록, 선택삭제, 선택복사, 선택이동 */
#board-list-function-bottom{
display:flex;
justify-content:space-between;
margin-bottom:1rem;
}
#board-list-function-bottom ul{
display:flex;
}
#board-list-function-bottom a{
margin-right:5px;
}
#board-list-function-bottom ul a{
display:block;
padding:10px;
background:#e7e9ea;
}
/* 페이지 */
#board-list-page{
display:flex;
justify-content:center;
margin-bottom:1rem;
}
#board-list-page a{
margin-right:5px;
padding:1px;
}
#board-list-page a:last-child{
margin:0;
}
/* 검색 */
#board-list-search *{
display:flex;
justify-content:center;
line-height:20px;
line-height:1.42857143rem;
}
#board-list-search input{
padding:5px;
padding:0.35714286rem;
margin-right:2px;
}
/*
#board-list-function-bottom li:after{
content:"";
}
*/
/* 글쓰기 */
#board-list-function-bottom div a{
display:block;
padding:10px;
background:#f90; /* #dc3700; */
}
/*
#board-list-function-bottom div a:hover{
background:#ff5219;
}
*/
/*
#board-list-page a{
padding:2px;
}
*/
}
/* 태블릿용 CSS */
@media all and (min-width:768px){
#toggle-menu{
position:absolute;
/*
top:0;
left:-210px;
display:block;
*/
}
.content{
display:flex;
flex-direction:column;
}
.latest-article{
width:50%;
/* border:1px solid #000; */
/* 스타일이 안먹힌다 -_-a */
}
/* 모바일에서 제목을 제외한 것들을 다시 보여준다. */
#board-table thead tr th:first-child, #board-table tbody tr td:first-child,
#board-table thead tr th:nth-child(2), #board-table tbody tr td:nth-child(2),
#board-table thead tr th:nth-child(4), #board-table tbody tr td:nth-child(4),
/* #board-table thead tr th:nth-child(5), #board-table tbody tr td:nth-child(5), */
#board-table thead tr th:nth-child(6), #board-table tbody tr td:nth-child(6){
display:table-cell;
}
}
/* PC용 CSS */
@media all and (min-width:960px){
body{
background:#262626;
}
#header{
margin:0 auto;
margin-bottom:10px;
margin-bottom:0.71428571rem;
width:98%;
height:129px;
}
#header-menu{
display:block;
}
#logo{
height:91px;
background:#fff url(../images/bg/main_image.jpg) no-repeat right;
}
#logo a{
margin:0;
width:188px;
height:91px;
background:url(../images/s_images/logo.png) no-repeat left;
}
#toggle-menu{
width:100%;
/* display:block; */
display:flex;
/* flex-direction:row; */
justify-content:space-between;
}
/* 화살표, 토글 버튼, 로그인 */
#toggle-menu li span, #toggle-button, #toggle-menu #login{
display:none;
}
/* 하위 메뉴 나타나게 합니다 */
/* #toggle-menu li:first-child:hover #toggle-menu-main */
#toggle-menu li:first-child:hover #toggle-menu-main,
#toggle-menu li:nth-child(2):hover #toggle-menu-game,
#toggle-menu li:nth-child(3):hover #toggle-menu-content,
#toggle-menu li:nth-child(4):hover #toggle-menu-comm,
#toggle-menu li:nth-child(5):hover #toggle-menu-down,
#toggle-menu li:nth-child(6):hover #toggle-menu-site{
display:block;
}
/* 검색창을 오른쪽으로 배치 */
#toggle-menu section{
order:2;
}
/* 검색창에 여백을 준다 */
#search{
padding:4px;
}
/* 목록 안의 요소들을 왼쪽에서 오른쪽으로 배치 -_-! */
#toggle-menu nav *{
display:flex;
flex-direction:row;
}
/* 목록안의 앵커 요소에 너비, 높이를 주고 텍스트를 바깥으로 이동시킴 */
#toggle-menu nav li a{
width:93px;
height:38px;
padding:0; /* 15px; */
text-indent:-9999px;
}
/* 하위 목록 앵커 */
#toggle-menu nav li li a{
width:150px;
height:auto;
text-indent:0;
padding:10px; /* 15px; */
z-index:1; /* 이 속성을 주면 모든 하위 메뉴 항목이 나타남 */
}
/* 글로벌 네비게이션 왼쪽에 마진을 준다 */
#toggle-menu ul{
margin-left:185px;
}
#toggle-menu ul ul{
position:relative;
margin-left:0;
}
#toggle-menu li li{
position:relative;
}
/* 이걸 먹이면 하위 메뉴가 한줄이 되어 겹침 */
/*
#toggle-menu li li{
position:absolute;
top:38px;
left:-93px;
}
*/
/* 배경 이미지 롤오버 */
#toggle-menu #main-rollover{
background:#fff url(../images/mainmenu/main.png) no-repeat;
}
#toggle-menu #main-rollover:hover{
background:#fff url(../images/mainmenu/main_over.png) no-repeat;
}
#toggle-menu #game-rollover{
background:#fff url(../images/mainmenu/game.png) no-repeat;
}
#toggle-menu #game-rollover:hover{
background:#fff url(../images/mainmenu/game_over.png) no-repeat;
}
#toggle-menu #content-rollover{
background:#fff url(../images/mainmenu/content.png) no-repeat;
}
#toggle-menu #content-rollover:hover{
background:#fff url(../images/mainmenu/content_over.png) no-repeat;
}
#toggle-menu #comm-rollover{
background:#fff url(../images/mainmenu/comm.png) no-repeat;
}
#toggle-menu #comm-rollover:hover{
background:#fff url(../images/mainmenu/comm_over.png) no-repeat;
}
#toggle-menu #down-rollover{
background:#fff url(../images/mainmenu/down.png) no-repeat;
}
#toggle-menu #down-rollover:hover{
background:#fff url(../images/mainmenu/down_over.png) no-repeat;
}
#toggle-menu #site-rollover{
background:#fff url(../images/mainmenu/site.png) no-repeat;
}
#toggle-menu #site-rollover:hover{
background:#fff url(../images/mainmenu/site_over.png) no-repeat;
}
/* sir의 위토즈님께 감사를 */
/* http://sir.co.kr/qa/?wr_id=30841 */
#toggle-menu #toggle-menu-main{
position:absolute;
top:38px;
left:185px;
}
#toggle-menu #toggle-menu-game{
position:absolute;
top:38px;
left:278px;
}
#toggle-menu #toggle-menu-content{
position:absolute;
top:38px;
left:371px;
}
#toggle-menu #toggle-menu-comm{
position:absolute;
top:38px;
left:464px;
}
#toggle-menu #toggle-menu-down{
position:absolute;
top:38px;
left:557px;
}
#toggle-menu #toggle-menu-site{
position:absolute;
top:38px;
left:650px;
}
#wrap-test{
width:98%;
margin:0 auto;
display:flex;
flex-direction:row;
}
#wrap-content{
width:90%;
order:2;
margin-bottom:10px;
margin-bottom:0.71428571rem;
padding:14px;
padding:1rem;
background:#fff;
}
#sidebar{
margin-right:10px;
margin-right:0.71428571rem;
/* margin-right:5%; */
width:164px;
width:11.71428571rem;
/* width:15%; */
order:1;
/*
width:164px;
width:11.71428571rem;
margin-right:10px;
margin-right:0.71428571rem;
*/
}
/* 외부 로그인 */
#sidebar-outlogin a:link, #sidebar-outlogin a:visited {
color: #000;
text-decoration: none;
}
#sidebar-outlogin a:hover, #sidebar-outlogin a:active {
color: #f00;
text-decoration: none;
}
/* PC에서는 외부 로그인 뜨게 */
#sidebar-outlogin{
display:block;
margin-bottom:10px;
padding:10px;
/* CSS3에서는 그라디언트를 지원해서 배경 이미지가 필요없다 -_-zz */
background:linear-gradient(to bottom, #fefefe, #cdcdcd);
}
#sidebar-outlogin legend,
#sidebar-outlogin [for=login-id],
#sidebar-outlogin [for=login-password]{
display:none;
}
#login-id,
#login-password{
font-size:100%;
}
/* input과 로그인 정렬 */
#wrap-outlogin{
display:flex;
flex-direction:row;
justify-content:space-between;
}
#login-id,
#login-password{
width:95px;
margin-bottom:5px;
}
#sidebar-outlogin [type=submit]{
width:45px;
height:45px;
background:#333; /* #4bc6f7; */
color:#fff;
/* border:1px solid #33bcf1; */
}
#sidebar-outlogin [type=submit]:hover{
background:#06c; /* #4bc6f7; */
color:#fff;
}
#sidebar-outlogin p{
line-height:20px;
/* margin-bottom:5px; */
}
/*
#sidebar-outlogin ul:last-child{
display:flex;
justify-content:flex-end;
}
*/
/*
#sidebar-outlogin div:last-child{
line-height:20px;
margin-bottom:5px;
display:flex;
flex-direction:row;
justify-content:space-between;
}
*/
/* 구글 애드센스 */
#banner-bottom{
margin-bottom:10px;
}
/* 모바일에서 제목을 제외한 것들을 다시 보여준다. */
#board-table thead tr th:first-child, #board-table tbody tr td:first-child,
#board-table thead tr th:nth-child(2), #board-table tbody tr td:nth-child(2),
#board-table thead tr th:nth-child(4), #board-table tbody tr td:nth-child(4),
#board-table thead tr th:nth-child(5), #board-table tbody tr td:nth-child(5),
#board-table thead tr th:nth-child(6), #board-table tbody tr td:nth-child(6){
display:table-cell;
}
#board-list-page a{
padding:5px;
background:#e7e9ea;
}
.content{
/* padding:40px 12.5%; */
width:100%;
/*
margin:10px auto;
margin:0.71428571rem auto;
padding:5px;
padding:0.35714286rem;
*/
/* 40px ÷ 320px */
background:#fff;
/* order:1; */
display:flex;
flex-direction:row;
}
.content-info{
display:block;
/* flex-direction:row; */
}
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/24947992",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: java jtree redisplay tooltip for every item after a delay When a tool tip is displayed on a tree and the mouse is moved the tooltip stays visible and the text changes. Is it possible to hide the tool tip and redisplay it when the mouse moves from one item to the next.
A: Extend DefaultTreeCellRenderer and invoke setToolTipText() as required. The tutorial project TreeIconDemo2, discussed in Customizing a Tree's Display, demonstrates the approach.
Addendum: You can supply the desired text for each node in a TreeCellRenderer, e.g. MyRenderer:
setToolTipText(value + " is in the Tutorial series.");
A: you will have to use setToolTipText(null) to remove the tool tip - it will not disappear with our explicitly doing so.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/3083482",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: What's a good RTOS to use with the LPC1788 microcontroller? I'm trying to find a free/cheap RTOS that others have found works well with the NXP LPC1788 microcontroller. I was originally planning on using FreeRTOS, but it doesn't seem to support that particular processor; the closest supported core is the LPC1768. ThreadX works with the LPC1788, but a license for it will cost several thousand pounds. Suggestions?
EDIT 1: I forgot to mention, I'm working with IAR Embedded Workbench.
EDIT 2: I guess I should also point out that I'm fairly new to embedded programming, let alone using RTOS's. FreeRTOS and ThreadX both seem to be pretty similar, and both have fairly intuitive API's. The more that the API of another RTOS matches with these kinds of API's, the better I suppose.
EDIT 3: I've been looking into one RTOS called embOS. It looks professional, the API looks nice, they support a decent number of processor/IDE combinations (including mine), and I've already got an example project working fine. It's not free, and a license for it will cost around 2500 euros, but that's still around 3 times cheaper than the threadX license. Thanks for the suggestions, I feel kind of bad that I can't choose an accepted answer.
A:
I was originally planning on using FreeRTOS, but it doesn't seem to
support that particular processor
Actually, FreeRTOS support all Cortex-M3 and Cortex-M4 processors with GCC, IAR and Keil. Just because there is not a specific pre-configured demo project for it does not mean it is not supported.
FreeRTOS does not rely on anything outside of the Cortex-M core, because the timer generation and interrupt controller are part of the core itself.
You can take an existing official LPCxx IAR demo project from the FreeRTOS distribution, and simply re-target it by setting up the right linker script for the chip. Any demo tasks that make use of IO that might be different on your particular hardware (ports used for LED outputs, etc.) can be modified to be correct for your IO port assignment, or just removed.
For example, Atollic have 55 FreeRTOS projects running on 55 different hardware platforms, all that actually use the same C source files - only the start up files and linker scripts are different.
A: I have specifically evaluated FreeRTOS, embOS and Keil RTX on Cortex-M3. Of the three FreeRTOS certainly had the slowest context switch times, while RTX had the fastest, but the range was 5us to 15us so probably not critical for all but the most hard real-time applications (it made a difference in my case however).
RTX is of course Keil specific and you are using IAR, it's API is less sophisticated than embOS, and at the time it had a few bugs on CM3 and did not fully support the NVIC interrupt priority scheme. I believe these issues are resolved. FreeRTOS is perhaps the most unconventional of the three in terms of API and architecture, having extensively used embOS and VxWorks and similar "traditional" RTOS systems I was not entirely comfortable with it.
embOS works well with IAR and its debugger, with a level of RTOS aware debug that is useful. The licensing is per-developer/per-processor/per-toolchain, but otherwise royalty free and can be used over many projects using the same architecture and toolchain. The support from Segger is excellent, as is the documentation, and I would suggest that for a commercial product with sufficient volumes and margin it would be well worth it.
You might also consider eCos - this is a more comprehensive solution offering support for USB, netwoking, filesystems and more as well as scheduling and IPC. There is a port for LPC1766 that could probably be ported relatively easy. Most likely however you would have to use the GNU toolchain for development which may have a bearing on your use of existing tools such as JTAG debuggers.
A: I know that Keil mVision IDE have RTOS for NXP chips, it works on 24xx 100%. But this RTOS is not opens source, and only IDE owners can use it.
A: You can try an get RTAI compiled with any linux kernel. Might take some work but should be doable (and free)
A: Linux, it its uClinux form, runs just fine on the LPC1788. Take a look at this video, for instance:
http://www.youtube.com/watch?v=VTemb8P1doI
As mentioned in the comments above, internal SRAM of the LPC1788 is not enough to run Linux, however LPC1788 provides an SDRAM interface making it possible to add external RAM.
A: The Unison RTOS offers the same POSIX calls as Linux including a complete set of I/O calls that you will find missing from things like freertos. The business model is free for DIY and royalty based for commercial products. It tends to be a small fraction of the competitors prices at $999 getting started with serial I/O and a file system. www.rowebots.com for details.
A: I'm working at a RTOS if you want you can find at github
http://www.github.com/geppo12/YasminOS
(path case sensitive)
Is a simple scheduler I'm going to introduce task priority as soon as possible.
I create YasminOS because other OS are too complex or too expensive
Actually I'm developing YasminOS with only one vision: simplicity
There are many application that not require a extreme powerful OS, but just as simple scheduler. Actually it's tested on Spansion FM3 architecture or NXP lpc800 (yes work also for cortex m0) in near future I'll test it on nxp 4088....
| {
"language": "en",
"url": "https://stackoverflow.com/questions/12401426",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: Add static middleware to serve static files in express I have the following folder structure:
/app
server.js
/public
1.jpg
I want to be able to access the 1.jpg image from the URI /1.jpg.
In my server.js file, I added the following middleware at the top:
app.use('/', express.static('../public'));
and in the buttom i have a middleware that catch not found routes:
app.all('*', (req, res) => {
res.status(404).json({
success: false,
message: `Can't find ${req.originalUrl} on this server!`
});
});
When i make a request to: /1.jpg i got the following response:
{
"success": false,
"message": "Can't find /1.jpg on this server!"
}
Even if it should serve the first middleware which is the image
A: The issue might be caused by the relative path to the public directory because the path is relative to the directory from where you launch your app.
If this is the case, then providing the absolute path should fix it:
const path = require('path');
app.use('/', express.static(path.join(__dirname, '../public')))
| {
"language": "en",
"url": "https://stackoverflow.com/questions/62782017",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Getting json data from URL when calling a function I'm working on java for Android to create a function so I can use to call to fetch my mailbox using json.
When I try this:
public void getInbox () {
TextView show_text = findViewById(R.id.txt_show);
SharedPreferences prefs = getSharedPreferences("LOGIN_STATUS", MODE_PRIVATE);
String email = prefs.getString("userEmail", "SAMPLE");
String password = prefs.getString("userPassword", "SAMPLE");
HttpURLConnection urlConnection = null;
StringBuilder result = new StringBuilder();
// GET
try {
URL url = new URL("http://www.example.com/inbox.php?email="+email+"&password="+password);
urlConnection = (HttpURLConnection) url.openConnection();
int code = urlConnection.getResponseCode();
show_text.setText("" + code);
} catch (Exception e) {
e.printStackTrace();
show_text.setText("failed 5");
}
}
It will not connect to the url as it will jump on the catch exception following by this line:
catch (Exception e) {
e.printStackTrace();
show_text.setText("failed 5");
}
So my question is do I have to use something like this?
private class getInbox extends AsyncTask<Void, Void, Void> {
@Override
protected Void doInBackground(Void... params) {
HttpURLConnection urlConnection = null;
StringBuilder result = new StringBuilder();
try {
// my code goes here
Or do I have use like this?
private void getInbox() {
// progressBar.setVisibility(View.VISIBLE);
StringRequest stringRequest = new StringRequest(Request.Method.GET,
URL,
new Response.Listener<String>() {
@Override
public void onResponse(String response) {
try {
// my code goes here
If not could you please show me an example how I could use a function to connect to the url?
I have tried on Google to find the answers, but I couldn't find the answer what I am looking for.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/67202670",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Object based functions in JS?
So, I have seen many JS functions that need two parameters, one of which is specified while calling the function i.e. function(param) and the other is specified using objects i.e. var.function(param) with the function needing var and param. So I want to know how I can get var
| {
"language": "en",
"url": "https://stackoverflow.com/questions/62850575",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to add two stacked area plots in a single page in plotly? So I have created a stacked area plot for two cases:
*
*With Storage
*Without Storage
they both look like this:
With Storage
Without Storage
But they both are on separate pages and I want them to combine. The code that I wrote these graphs is:
import plotly.graph_objs as go
import plotly.offline as pyo
from plotly.subplots import make_subplots
import xlwings as xw
import logging
#Getting the Data
app = xw.App(visible=False)
try:
wb = app.books.open('PCM Fuel Wise Chart.xlsx')
sheet = wb.sheets[0]
dateWithStorage = sheet.range('A2:A8065').value
coalWithStorage = sheet.range('D2:D8065').value
nuclearWithStorage = sheet.range('E2:E8065').value
gasWithStorage = sheet.range('F2:F8065').value
bagasseWithStorage = sheet.range('G2:G8065').value
hydroWithStorage = sheet.range('H2:H8065').value
windWithStorage = sheet.range('I2:I8065').value
solarWithStorage = sheet.range('J2:J8065').value
bessCharging = sheet.range('L2:L8065').value
bessDischarging = sheet.range('M2:M8065').value
time = sheet.range('O2:O8065').value
sheet = wb.sheets[1]
dateWithoutStorage = sheet.range('A2:A8065').value
coalWithoutStorage = sheet.range('D2:D8065').value
nuclearWithoutStorage = sheet.range('E2:E8065').value
gasWithoutStorage = sheet.range('F2:F8065').value
bagasseWithoutStorage = sheet.range('G2:G8065').value
hydroWithoutStorage = sheet.range('H2:H8065').value
windWithoutStorage = sheet.range('I2:I8065').value
solarWithoutStorage = sheet.range('J2:J8065').value
time = sheet.range('O2:O8065').value
except Exception as e:
logging.exception("Something awful happened!")
print(e)
finally:
app.quit()
app.kill()
#Plotting the Data
trace1 = []
trace1.append({'x': dateWithStorage,'y': coalWithoutStorage, 'name': 'Coal', 'mode':'lines', 'line' : dict(width = 0.5, color = 'grey'), 'stackgroup': 'one'})
trace1.append({'x': dateWithStorage,'y': nuclearWithStorage, 'name': 'Nuclear', 'mode':'lines', 'line' : dict(width = 0.5, color = 'red'), 'stackgroup': 'one'})
trace1.append({'x': dateWithStorage,'y': gasWithStorage, 'name': 'Gas', 'mode':'lines', 'line' : dict(width = 0.5, color = 'blue'), 'stackgroup': 'one'})
trace1.append({'x': dateWithStorage,'y': bagasseWithStorage, 'name': 'Bagasse', 'mode':'lines', 'line' : dict(width = 0.5, color = 'purple'), 'stackgroup': 'one'})
trace1.append({'x': dateWithStorage,'y': hydroWithStorage, 'name': 'Hydro', 'mode':'lines', 'line' : dict(width = 0.5, color = 'cyan'), 'stackgroup': 'one'})
trace1.append({'x': dateWithStorage,'y': windWithStorage, 'name': 'Wind', 'mode':'lines', 'line' : dict(width = 0.5, color = 'green'), 'stackgroup': 'one'})
trace1.append({'x': dateWithStorage,'y': solarWithStorage, 'name': 'Solar', 'mode':'lines', 'line' : dict(width = 0.5, color = 'yellow'), 'stackgroup': 'one'})
trace1.append({'x': dateWithStorage,'y': bessCharging, 'name': 'BESS Charging', 'mode':'lines', 'line' : dict(width = 0.5, color = 'brown'), 'stackgroup': 'one'})
trace1.append({'x': dateWithStorage,'y': bessDischarging, 'name': 'BESS Discharging', 'mode':'lines', 'line' : dict(width = 0.5, color = 'orange'), 'stackgroup': 'one'})
fig = go.Figure({'data': trace1})
pyo.plot(fig, filename= 'testing.html')
I don't know how to add subplot and stacked area plot together, So can anyone please help?
I have already created the graphs by using this code, I just need a way to integrate these two graphs into one.
A: You could create a subplot with two rows and then plot that subplot.
This could be a minimal example
import plotly.graph_objs as go
import plotly.offline as pyo
from plotly.subplots import make_subplots
fig = make_subplots(rows=2, cols=1)
# traces WithStorage
trace1 = go.Scatter({'x': [3,3.1],'y': [1,1.1], 'name': 'Coal', 'mode':'lines', 'line' : dict(width = 0.5, color = 'grey'), 'stackgroup': 'one'})
trace2 = go.Scatter({'x': [4,4.2],'y': [2,2.1], 'name': 'Nuclear', 'mode':'lines', 'line' : dict(width = 0.5, color = 'red'), 'stackgroup': 'one'})
#traces WithoutStorage
trace3 = go.Scatter({'x': [5,5.1],'y': [2,2.1], 'name': 'Coal', 'mode':'lines', 'line' : dict(width = 0.5, color = 'grey'), 'stackgroup': 'one'})
trace4 = go.Scatter({'x': [6, 6.1],'y': [3,3.1], 'name': 'Nuclear', 'mode':'lines', 'line' : dict(width = 0.5, color = 'red'), 'stackgroup': 'one'})
fig = make_subplots(rows=2, cols=1)
# we add each trace to their subplot
fig.add_trace(trace1,1,1)
fig.add_trace(trace2,1,1)
fig.add_trace(trace3,2,1)
fig.add_trace(trace4,2,1)
fig.update_layout(height=600, width=600, title_text="Stacked Subplots")
pyo.plot(fig, filename= 'testing.html')
| {
"language": "en",
"url": "https://stackoverflow.com/questions/66225890",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Using MPI_Gather for 3d array in c++? I am trying to parallelize a for loop operation which is sandwiched between two for loops.
After the data (3d array) is calculated in each processor I want to collect the data from each processor back to the root node for my further processing. I tried using the MPI_Gather function to get the data back to the root node. Using this function the data is collected back from root processor and but the data is not collected from the other processors.
int main(int argc, char * argv[]) {
int i,k,l,j;
int Np = 7, Nz = 7, Nr = 4;
int mynode, totalnodes;
MPI_Status status;
long double ***k_p, ***k_p1;
int startvalp,endvalp;
MPI_Init(&argc,&argv);
MPI_Comm_size(MPI_COMM_WORLD, &totalnodes);
MPI_Comm_rank(MPI_COMM_WORLD, &mynode);
// Allocation of memory
Allocate_3D_R(k_p,(Nz+1),(Np+1),(Nr+1));
Allocate_3D_R(k_p1,(Nz+1),(Np+1),(Nr+1));
// startvalp represents the local starting value for each processor
// endvalp represents the local ending value for each processor
startvalp = (Np+1)*mynode/totalnodes - 0;
endvalp = startvalp + (((Np+1)/totalnodes) -1);
for(l = 0 ; l <= 1 ; l++){
for(k=startvalp; k<=endvalp; k++){
// for loop parallelized between the processors
// original loop: for(k=0; k<= Np; k++)
for(i=0; i<=1; i++){
k_p[i][k][l] = l+k+i;
}
}
}
// For Np = 7 and for two processors ;
// k = 0 - 3 is calculated in processor 0;
// k = 4 - 7 is calculated in processor 1;
// Now I need to collect the value of k_p from processor 1
// back to the root processor.
// MPI_Gather function is used.
for(l = 0 ; l <= 1 ; l++){
for(k=startvalp; k<=endvalp; k++){
for(i=0; i<=1; i++){
MPI_Gather(&(k_p[i][k][l]),1, MPI_LONG_DOUBLE,&(k_p1[i][k][l]),1, MPI_LONG_DOUBLE, 0, MPI_COMM_WORLD);
}
}
}
// Using this the k_p is collected from root processor and stored
// in the k_p1 variable, but from the slave processor it is not
// collected back to the root processor.
if(mynode == 0){
for(l = 0 ; l <= 1 ; l++){
for(k=0; k<=Np; k++){
for(i=0i<=1;i++){
cout << "Processor "<<mynode;
cout << ": k_p["<<i<<"]["<<k<<"]["<<l<<"] = " <<k_p1[i][k][l]<<endl;
}
}
}
}
MPI_Finalize();
} // end of main
void Allocate_3D_R(long double***& m, int d1, int d2, int d3) {
m=new long double** [d1];
for (int i=0; i<d1; ++i) {
m[i]=new long double* [d2];
for (int j=0; j<d2; ++j) {
m[i][j]=new long double [d3];
for (int k=0; k<d3; ++k) {
m[i][j][k]=0.0;
}
}
}
}
Here is the output :
Processor 0: k_p[0][0][0] = 0
Processor 0: k_p[1][0][0] = 1
Processor 0: k_p[0][1][0] = 1
Processor 0: k_p[1][1][0] = 2
Processor 0: k_p[0][2][0] = 2
Processor 0: k_p[1][2][0] = 3
Processor 0: k_p[0][3][0] = 3
Processor 0: k_p[1][3][0] = 4
Processor 0: k_p[0][4][0] = 0
Processor 0: k_p[1][4][0] = 0
Processor 0: k_p[0][5][0] = 0
Processor 0: k_p[1][5][0] = 0
Processor 0: k_p[0][6][0] = 0
Processor 0: k_p[1][6][0] = 0
Processor 0: k_p[0][7][0] = 0
Processor 0: k_p[1][7][0] = 0
Processor 0: k_p[0][0][1] = 1
Processor 0: k_p[1][0][1] = 2
Processor 0: k_p[0][1][1] = 2
Processor 0: k_p[1][1][1] = 3
Processor 0: k_p[0][2][1] = 3
Processor 0: k_p[1][2][1] = 4
Processor 0: k_p[0][3][1] = 4
Processor 0: k_p[1][3][1] = 5
Processor 0: k_p[0][4][1] = 0
Processor 0: k_p[1][4][1] = 0
Processor 0: k_p[0][5][1] = 0
Processor 0: k_p[1][5][1] = 0
Processor 0: k_p[0][6][1] = 0
Processor 0: k_p[1][6][1] = 0
Processor 0: k_p[0][7][1] = 0
Processor 0: k_p[1][7][1] = 0
The data from the root processor is transferred but not from the other processor.
I tried using MPI_Send and MPI_Recv functions and did not encounter the above problem but for large values of for loop it takes more time.
Therefore can anyone provide a solution to the above problem?
A: The issues here are actually similar to the issues in 2d: MPI_Type_create_subarray and MPI_Gather ; there's a very lengthy answer there that covers most of the crucial points.
Gathering multidimensional array sections is trickier than just doing 1d arrays, because the data you're gathering actually overlaps. Eg, the first row from rank 1 comes between the first and second rows of rank 0. So you need to (a) use mpi_gatherv, so you can specify the displacments, and (b) set the extents of the data types explicitly to facilitate the overlapping.
Understanding the sending and receiving of complex data structures (in MPI, or in anything else) is all about understanding the layout of data in memory -- which is crucial for getting high performance out of your code anyway.
Speaking of layout of memory, your Allocate3d won't work for the purposes here; the problem is that it allocates memory that may not be contiguous. There's no guarantee that if you allocate a 10x10x10 array this way that element [1][0][0] comes immediately after element [0][9][9]. This is a common problem in C/C++, which doesn't come with any built-in concept of multidimensional arrays. You'll need to do something like this:
void Allocate_3D_R(long double***& m, int d1, int d2, int d3) {
m=new long double** [d1];
for (int i=0; i<d1; ++i) {
m[i]=new long double* [d2];
}
m[0][0] = new long double[d1*d2*d3];
for (int i=0; i<d1; ++i) {
for (int j=0; j<d2; ++j) {
if (i!=0 && j!=0)
m[i][j]=&(m[0][0][(i*d2+j)*d3];
for (int k=0; k<d3; ++k) {
m[i][j][k]=0.0;
}
}
}
plus or minus -- that is, you'll need to allocate a contiguous d1*d2*d3 chunk of memory, and then point the array indicies to the appropriate places in that contiguous memory.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/5605714",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Android share button audio from raw I have various audio files in the raw folder in my Android project. My code is not working. When I click the share button application, it crashes.
This is my code:
public void onClick(View v) {
InputStream inputStream;
FileOutputStream fileOutputStream;
try {
inputStream = getResources().openRawResource(R.raw.numer_1);
fileOutputStream = new FileOutputStream(
new File(Environment.getExternalStorageDirectory(), "sound.mp3"));
byte[] buffer = new byte[1024];
int length;
while ((length = inputStream.read(buffer)) > 0) {
fileOutputStream.write(buffer, 0, length);
}
inputStream.close();
fileOutputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
Intent intent = new Intent(Intent.ACTION_SEND);
intent.putExtra(Intent.EXTRA_STREAM,
Uri.parse("file://" + Environment.getExternalStorageDirectory() + "/sound.mp3" ));
intent.setType("audio/*");
startActivity(Intent.createChooser(intent, "Share sound"));
}
And Android manifest add:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
A: if you use this your app will not crash again. The problem is at **Environment.getExternalStorageDirectory()**you're missing **.getPath()**
use the code below as guide for your intent.
final Intent audIntent = new Intent(android.content.Intent.ACTION_SEND);
String audioName="kidi.mp3";
audIntent.setType("audio/mp3");
audIntent.putExtra(android.content.Intent.EXTRA_STREAM, Uri.parse("file://"+"/Environment.getExternalStorageDirectory().getPath()/"+audioName));
startActivity(Intent.createChooser(audIntent, "Share Audio "));
| {
"language": "en",
"url": "https://stackoverflow.com/questions/53305582",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Dynamic C - char pointers, strcpy, strcat Here is my code:
nodebug void sendLogPacketS(char *func, char *msg)
{
char * log;
memset(log, 0, strlen(func) + strlen(msg) + 1);
strcpy(log, func);
strcat(log, ": ");
strcat(log, msg);
sendUDPLogPacket(log, strlen(log));
}
It's supposed to take two strings, concatenate them together, then pass the new string and its length to a different function. I'm using Dynamic C 9.62, which doesn't have support for the malloc function, so I'm using memset instead.
The problem is when I printf the value of log before it's passed to sendUDPLogPacket, it contains garbage DynamiCUniversal Rabbit BIOS Version 9.50\?^>j. Anyone have any ideas why this isn't working?
A: Your code has undefined behavior.
You cannot validly access the memory pointed at by an uninitialized pointer, like you do.
The memset() function writes to memory, it does not magically allocate new memory (it takes as input the pointer to the memory to be written), you cannot in anyway use it "instead of" malloc().
You can try with an on-stack buffer:
char log[128] = "";
of course you need to take care not to use more than 128 characters; your unbounded strcat() usage is dangerous.
If your fringe compiler supports C99 you can of course do:
const size_t flen = strlen(func);
const size_t mlen = strlen(msg);
char log[flen + 2 + mlen + 1]; // Space for func, msg, colon, space, terminator.
A: Declare an array of chars with the size of func + size of msg instead of an uninitialized char pointer.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/24244853",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Windows global variables in ASP.NET Is there any windows global variables that can be used to read/write data?
And Can i access windows global variables from web application ?
A: You mean environment variables? See http://msdn.microsoft.com/en-us/library/system.environment.getenvironmentvariable%28v=vs.110%29.aspx and http://msdn.microsoft.com/en-us/library/system.environment.setenvironmentvariable%28v=vs.110%29.aspx
You can store strings in it, by I wouldn't store too much data there.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/21201515",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
} |
Q: add missing rows to a data table I have a data table:
library(data.table)
(f <- data.table(id1=c(1,2,3,1,2,3),
id2=as.factor(c("a","a","b","c","b","d")),
v=1:6,
key=c("id1","id2")))
id1 id2 v
1: 1 a 1
2: 1 c 4
3: 2 a 2
4: 2 b 5
5: 3 b 3
6: 3 d 6
> str(f)
Classes ‘data.table’ and 'data.frame': 6 obs. of 3 variables:
$ id1: num 1 1 2 2 3 3
$ id2: Factor w/ 4 levels "a","b","c","d": 1 3 1 2 2 4
$ v : int 1 4 2 5 3 6
- attr(*, "sorted")= chr "id1" "id2"
- attr(*, ".internal.selfref")=<externalptr>
How do I add the "missing" rows?
I.e., for each existing id1 I want all possible values of id2 to be present (with v=0).
So, I need to add 6 rows (3 possible values of id1 * 4 possible values of id2 - 6 existing rows).
A: I'd get the unique values in id1 and id2 and do a join using data.table's cross join function CJ as follows:
# if you've already set the key:
ans <- f[CJ(id1, id2, unique=TRUE)][is.na(v), v := 0L][]
# or, if f is not keyed:
ans <- f[CJ(id1 = id1, id2 = id2, unique=TRUE), on=.(id1, id2)][is.na(v), v := 0L][]
ans
A: f[, {
tab = table(id2)
x = as.numeric(tab)
x[x != 0] = v
list(id2 = names(tab), v = x)
}, by = id1]
## id1 id2 v
## 1: 1 a 1
## 2: 1 b 0
## 3: 1 c 4
## 4: 1 d 0
## 5: 2 a 2
## 6: 2 b 5
## 7: 2 c 0
## 8: 2 d 0
## 9: 3 a 0
## 10: 3 b 3
## 11: 3 c 0
## 12: 3 d 6
| {
"language": "en",
"url": "https://stackoverflow.com/questions/22462405",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "8"
} |
Q: Botpress - how to bring database values into the chat window? I'm trying to build a chatbot using Botpress. I'm a beginner, looking for your help. One of the requirements is to query database to answer questions. This is what I have tried so far:
dbconnect.js
var oracledb = require('oracledb');
var dbConfig = require('./dbconfig.js');
var db = function dbCall(sql, values) {
return new Promise(function(resolve, reject){
oracledb.getConnection(
{
user : dbConfig.user,
password : dbConfig.password,
connectString : dbConfig.connectString
},
function(err, connection) {
if (err) {
reject(err);
return;
}
connection.execute(
sql,
values,
{
maxRows: 1
},
function(err, result) {
if (err) {
console.error(err.message);
return;
}
resolve(result);
doRelease(connection);
}
);
});
});
}
// Note: connections should always be released when not needed
function doRelease(connection) {
connection.close(
function (err) {
if (err) {
console.error(err.message);
}
});
}
module.exports = db;
select.js
var dbConnect = require('../oracledb/dbconnect');
dbConnect('select code from table1' +
' where id=:id', {id:'value1'}).then(function (response) {
console.info(response.rows);
}).catch(function(error) {
console.info(error);
});
everything above works great, if I run select.js. How could I bring the response into the botpress chat window? I tried placing the select.js code in index.js event.reply, it doesn't work.
Thanks,
Babu.
A: I have resolved this by using the promise directly in the action.
return dbConnect('<SQL here>=:id', { id: Id })
.then(function(response) {
var res = response.rows
console.info(res);
const newState = { ...state, status: res}
return newState
})
.catch(function(error) {
console.info(error)
})
Note that response has the resultset.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/49912807",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Why are the labels for my opposite yaxis in Highcharts not showing up? I am puzzled why the second yaxis in my Highcharts graph shows, but without any values. Both of my two graphs are still bound to the first yaxis. Can't get one of them attributed to the second yaxis. Here is a fiddle.
Thanks for any hints!
A: The charts options are case sensitive. You specified 'yaxis' when it should be 'yAxis'. That took me a while to spot !
series: [{
yAxis: 1,
data: [29.9, 71.5, 106.4, 129.2, 144.0, 176.0, 135.6, 148.5, 216.4, 194.1, 95.6, 54.4]
},{
yAxis: 0,
data: [19.9, 21.5, 6.4, 29.2, 44.0, 76.0, 35.6, 48.5, 16.4, 94.1, 95.6, 54.4]
}]
| {
"language": "en",
"url": "https://stackoverflow.com/questions/15635015",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: Summarization-Text rank algorithm What are the advantages of using text rank algorithm for summarization over BERT summarization?
Even though both can be used as extractive summarization method, is there any particular advantage for text rank?
A: TextRank implementations tend to be lightweight and can run fast even with limited memory resources, while the transformer models such as BERT tend to be rather large and require lots of memory. While the TinyML community has outstanding work on techniques to make DL models run within limited resources, there may be a resource advantage for some use cases.
Some of the TextRank implementations can be "directed" by adding semantic relations, which one can consider as a priori structure to enrich the graph used -- or in some cases means of incorporating human-in-the-loop approaches. Those can provide advantages over supervised learning models which have been trained purely on data. Even so, there are similar efforts for DL in general (e.g., variations on the theme of transfer learning) from which transformers may benefit.
Another potential benefit is that TextRank approaches tend to be more transparent, while transformer models can be challenging in terms of explainability. There are tools that help greatly, but this concern becomes important in the context of model bias and fairness, data ethics, regulatory compliance, and so on.
Based on personal experience, while I'm the lead committer for one of the popular TextRank open source implementations, I only use its extractive summarization features for use cases where a "cheap and fast" solution is needed. Otherwise I'd recommend considering more sophisticated approaches to summarization. For example, I recommend keeping watch on the ongoing research by the author of TextRank, Rada Mihalcea, and her graduate students at U Michigan.
In terms of comparing "Which text summarization methods work better?" I'd point toward work on abstractive summarization, particularly recent work by John Bohannon, et al., at Primer. For excellent examples, check the "Daily Briefings" of CV19 research which their team generates using natural language understanding, knowledge graph, abstractive summarization, etc. Amy Heineike discusses their approach in "Machines for unlocking the deluge of COVID-19 papers, articles, and conversations".
| {
"language": "en",
"url": "https://stackoverflow.com/questions/62731497",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: A really very simple expression in Java that is evaluated in a way that it is difficult to follow While developing a web application in JSF, I came across an expression which was evaluated in a way that I couldn't follow. Let's represent the same expression with a simple Java code.
final public class Main
{
public static void main(String[] args)
{
int x=5;
int temp=10;
temp=temp + 1 + x;
System.out.println("temp = "+temp);
int var=10;
var=var++ + x;
System.out.println("var = "+var);
}
}
In the above simple code snippet, the first case is obvious and it displays the value 16 through the statement System.out.println("temp = "+temp);. There is no question at all about it but in the second case, I have represented the same thing using the shorthand operator ++ (var++) and that causes the value 15 to be displayed on the console instead of displaying 16. How is this expression evaluated here?
Here, there is an obvious thing that should be mentioned. In the expression var++, 10 is first passed and that value (not 11) is used to evaluate the entire expression on the right of the assignment which is in this case var++ + x and then var is incremented by 1. Accordingly, the assignment to itself (var) can not be observed here.
Where was the incrementation lost?
A: var++ evaluates to var, and then increments var. So your expression is in fact evaluated to var + x.
The sequence of actions is the following:
*
*evaluate var++ : 10
*increment var : var = 11
*add x to 10 : 15
*assign the result of the addition to var : var = 15
Anyone programming like this should be banned from development, IMHO.
A: Post increment operator like x++ means first you use the value x then you increment and in our case
var=var++ + x;
assignment takes precedence.
Try this
var=++var + x;
and you should get the value of 16.
A: You assigned a value to var,so the auto increment is executed but overwritten.
Your code would be better written as:
int var = 10;
var += x + 1;
System.out.println("var = " + var);
A: According to the Java Language Specification
The value of the postfix increment expression is the value of the variable before the new value is stored.
http://java.sun.com/docs/books/jls/third_edition/html/expressions.html#15.14.2
A: This is the expected behavior of the post-increment operator. You can see what's going on more clearly by running the following:
int var = 10;
var = var++;
System.out.println("var = " + var);
var = 10;
var = var++ + var;
System.out.println("var = " + var);
This should produce the output:
10
21
The post-increment operator returns the current value of the variable in the current expression, then increments it, so the incremented value is only visible the next time that variable is used.
In your code, you overwrite the value of var before the incremented value is ever used (so the incrementation is "lost"). I imagine the byte code is something analogous to:
// r holds the intermediate value of the expression while it's calculated
int x = 5;
int var = 10;
int r = r + var;
var = var + 1; // note var is not read after this point
r = r + x;
var = r;
| {
"language": "en",
"url": "https://stackoverflow.com/questions/8068328",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Significance/Need of setting the properties to nil in viewDidUnload
*
*What is the significance of setting the properties to nil in viewDidUnload in both the aspects i.e. with ARC or without ARC?
*Does it only matter in case of IBOulets? Don't we need to set the other properties (that are not IBOulets) to nil?
*What can be the consequences if I don't do that? I haven't set them nil before and haven't observe any consequences.
Help is really appreciated.
A: Setting IBOutlets to nil in viewDidUnload tells the compiler to release the outlets on memory warning.because on memory warning ..viewDidUnload and didReceiveMemoryWarning of the viewcontrollers gets called..Normally in ViewDidUnload the IBOutlets are set to nil and in didReceiveMemoryWarning properties or objects are released.Hence in such a case memory is regained and thus your app can continue to function else continuous pooling causes in crash due to low memory
A: After reading a lot articles on the web and going through similar questions on stackoverflow.com I reached at the following understanding:
*
*viewDidUnload is called by the compiler in low memory situation.
*We should set those properties to nil in the method, which are being re-instanciated in viewDidLoad. Almost all IBOutlet components falls under the category. So better we declare the IBOutlets to nil in the method. Not doing so will lead to continuous pooling and may cause crash due to low memory in future(the time, the app continues to run).
*I also read that we should not nil the instances of the class like NSString(may cause crash), which is right as per my experience. But reason for that I don't know.
*It has nothing to deal with ARC. Setting a property to nil simply means that the property doesnot keep the refrence of any memory location anymore.
I will keep on updating this answer every time i came to know something more about it.
Thanks.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/12459305",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Instant Run error in Android Studio 2.3 My Android Studio is 2.3 Version.
When I Enable Instant Run (If I Disable Instant Run, there is no error) and Run app, I get error:
I click "OK":
DELETE_FAILED_INTERNAL_ERROR
Error while Installing APKs
Do you have any idea with this error?
A: It can't seem to uninstall the previous version of your app. Just go ahead and uninstall it manually this time. It should work afterwards.
A: If I am understanding correctly, you are attempting to emulate your app on one of the Studio's built in emulators. I believe the problem is your APK is either corrupted, a Gradle Build Error occurred, or the APK and the API of your emulator are two different versions.
I would suggest backing up your project, and then reinstall a newer version of the project.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/42729544",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: Snapshot too old error I am getting 'snapshot too old error' frequently while i am running my workflow when it runs for more than 5 hrs.My source is oracle and target is Teradata. Please help to solve this issue.Thanks in advance
A: The snapshot too old error is more or less directly related to the running time of your queries (often a cursor of a FOR loop). So the best solution is to optimize your queries so they run faster.
As a short term solution you can try to increase the size of the UNDO log.
Update:
The UNDO log stores the previous version of a record before it's updated. It is used to rollback transactions and to retrieve older version of a record for consistent data snapshots for long running queries.
You'll probably need to dive into Oracle DB administration if you want to solve it via increasing the UNDO log. Basically you do (as SYSDBA):
ALTER SYSTEM SET UNDO_RETENTION = 21600;
21600 is 6 hours in seconds.
However, Oracle will only keep 6 hours of old data if the UNDO log files are big enough, which depends on the size of the rollback segments and the amount of updates executed on the database.
So in addition to changing the undo retention time, you should also make sure that few concurrent updates are executed while your job is running. In particular, updates of the data your job is reading should be minimized.
If everything fails, increase the UNDO logs.
A: The best explanation of the ORA-01555 snapshot too old error that I've read, is found in this AskTom thread
Regards.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/11972979",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: What is the best way to Converting SOAP-based WCF Service to RESTful Design I am having SOAP services in my existing project code.
Which consume XML and produces XML as my response.
I need convert of enable this SOAP to RESTful webservice by producing "Application/JSON".
*
*So please suggest is there any tool to convert SOAP to REST or any other way of re-using SOAP as Restful service.
*What is the best way of doing or exposing it.
I trying to analyzed what is the best way to do and refer different links,links
But I could find this link but this is little more generic but i am looking for some concrete and specific to .Net (C# or VB.Net) Implementation.
It will be great help for me and for any one in the future if any one would like to share the best way of doing it.
Thanks in advance.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/41890180",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Enabling geodatabase in AWS RDS PostgreSQL instance Superuser permission is required to create a geodatabase in PostgreSQL.
However, in AWS RDS instance we are receiving:
rds_superuser permission and rds_superuser is not superuser.
Is there a way to enable geodatabase in AWS RDS PostgreSQL with rds_superuser permission?
A: You need to create the database and the sde login manually using e.g. pgAdmin, and grant the rds_superuser group role to the sde login. Also create a schema named sde in your database, and make the sde login the owner of that schema.
Then you can create a .sde database connection in ArcCatalog using the sde login and, importantly, the *.rds.amazonaws.com hostname. Finally you can run the Enable Enterprise Geodatabase using this connection as your input.
This only works if you connect to the database using the *.rds.amazonaws.com hostname. Apparently, ESRI uses the hostname to determine if the database in question is an RDS server.
Once you've enabled the geodatabase you can connect to it with .sde connections using other dns aliases as well.
Refer to the ESRI documentation for further details: http://server.arcgis.com/en/server/latest/cloud/amazon/create-geodatabase-in-amazon-rds-for-postgresql.htm
| {
"language": "en",
"url": "https://stackoverflow.com/questions/32159846",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: How to enable java flight recorder for tomcat installed on my windows machine? I have a web app running inside my tomcat on my windows machine. I am trying to monitor it with Java Mission Control. I am getting an error message to unlock commercial features to access java flight recorder.. Please guide me where and how it needs to be enabled.
Thanks in advance..
A: You might try setting the CATALINA_OPTS environment variable, e.g.:
set CATALINA_OPTS=-XX:+UnlockCommercialFeatures -XX:+FlightRecorder -Dcom.sun.management.jmxremote=true -Dcom.sun.management.jmxremote.rmi.port=7091 -Dcom.sun.management.jmxremote.port=7091 -Dcom.sun.management.jmxremote.authenticate=false -Dcom.sun.management.jmxremote.ssl=false
Then start Tomcat as usual.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/50582705",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Height of BST +1 more than expected I made a function which determines the height of BST, but when the height of the tree is e.g. 2, the result that appears for me is 3, etc. I don't know what I should change in my code. If you need whole code to be able to answer me, tell me, so I'll copy it.
def maxDepth(self, node):
if node is None:
return 0
else:
# Compute the depth of each subtree
lDepth = self.maxDepth(node.left)
rDepth = self.maxDepth(node.right)
# Use the larger one
if (lDepth > rDepth):
return lDepth + 1
else:
return rDepth + 1
A: Instead of return 0 just do return -1 and you'll get desired height smaller by 1. Corrected code is below:
def maxDepth(self, node):
if node is None:
return -1
else:
# Compute the depth of each subtree
lDepth = self.maxDepth(node.left)
rDepth = self.maxDepth(node.right)
# Use the larger one
if (lDepth > rDepth):
return lDepth + 1
else:
return rDepth + 1
Also you can use built-in max() function to make your code shorter:
def maxDepth(self, node):
if node is None:
return -1
return max(self.maxDepth(node.left), self.maxDepth(node.right)) + 1
Note: OP is correct, height should be edge-based, i.e. tree with one node 5 should have height of 0. And empty tree (None-tree) has height -1. There are two proofs of this:
One proof in Wikipedia Tree Article says that height is edge based and Conventionally, an empty tree (tree with no nodes, if such are allowed) has height −1.
And another proof in famous book Cormen T.H. - Introduction to Algorithms:
| {
"language": "en",
"url": "https://stackoverflow.com/questions/67545057",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How to set up things for MediaWiki for my website I am trying to set up a website with MediaWiki on a Shared Hosting service and am getting frustrating results. First I am going to list what I want out of my website and will show the hosting details to show you what kinds of problems I am running into here:
*
*So the main objective of the website is to run a database of events in human history (relating to World War 2)
*I want to use the Visual Editor extension to create a more visual style to edit articles (which requires Parsoid) so that editors won’t have to go through the pain of using the old wiki editor and memorizing the different characters needed for specific things and so that editing the whole thing won’t look like a complete mess.
*I want to make it so that only selected accounts/people can create and edit content on the site.
*I want to be able to have some sort of forum so that people can ask questions and communicate with each other.
*I want my site to have a certain kind of style (which I know is a skin but was wondering what's the best way to create one is. Also, do skins also come with the ability to customize the site to have certain functions? Because I have seen sites like halopedia which seems to be running on MediaWiki but have a lot of different kinds of functions and all that. )
*I want to create some sort of email system for my thing (although I could just maybe use another service which would be easier)
These are pretty much the main things that I want but there are some smaller things that I can ask how to do some other time as they are not mandatory right now. Here are the details for the hosting service that I use for the website just to give you guys a better understanding of my situation here.
*
*I am using Bluehost as the hosting service and cPanel as the file management system
*The website is currently on a shared hosting plan and the best one that I could get without spending a lot a month.
*I used Softaculous to download MediaWiki onto my website.
One of the main things that I have been having trouble with is installing Parsoid to install the VisualEditor extension onto the site. The problem is that to install Parsoid you need Node.js which I can’t install on my hosting service because it is shared hosting. However I tried following the instructions on the page that shows you how to do it using Heroic but have been having trouble with that too.
A: If you wait a few weeks, MediaWiki 1.35 will be released with a PHP implementation of Parsoid.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/60878433",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
} |
Q: How to get bounders of some portion of text in FabricJS? I'm curious if there is a way to find X, Y, WIDTH, and HEIGHT of some portion of a text by using a native function or even workaround?
The purpose of that is that I'll need to draw some rectangle on top of it when client types that word in another Input, kind of word existence indicator... similar to search...
Here is the Textbox example where I need to find "boundaries" of the word NOT (red text)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/52104829",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Facebook Analytics DAU/MAU different numbers when changing time period We're using FB analytics to check our DAU of paying users only, using a Segment.
When viewing the DAU graph for the period of 1/2017-10/2017, we get a graph of results.
But when extending the period to 1/2016-10/2017, the graph is completely different, the values of the same months (1/2017-10/2017) are more then doubled.
When clearing the segment the graph is stable regardless of time period chosen.
Is this a known issue when using segments?
Is there something we can do to fix it?
Is there a way to know which of the graphs is more accurate?
A: This is expected behavior and it's not a matter of which graph is "more accurate" since you're looking at different segments of users in each case.
In the first case, all users who have made a purchase in 1/2017-10/2017 (10 months) are included in the segment. In the second case, all users who have made a purchase in 1/2016-10/2017 (22 months) are included in the segment.
So if you're looking at the number of DAU on, say, 2/1/2017, in the first case, all the users who used your app that day who made a purchase in a 10-month period are included. Whereas in the first case, all the users who used your app that day who made a purchase in a 22-month period are included. This explains why the numbers of users are more than doubled.
If you just want to see the number of unique users who made a purchase each day, you can do so in the Revenue, Dashboards or Events section by selecting the "purchase" event and "unique users" metric. These numbers will be stable regardless of the date range you select, since no event-based segment is applied.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/47199315",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: What does __devexit mean in a function declaration? A driver I looked at has
static void __devexit rtsx_remove(struct pci_dev *pci)
What does __devexit mean in the context of the function definition? Other functions I've seen have, at most, static and a return type.
A: Long-ish story short:
This is a macro that expands to a set of gcc attributes. They are a way of providing the compiler with special information about various stuff in your code, like, in this case, a function.
Different compilers have different syntaxis for this purpose, it isn't standartized. For example, gcc uses attributes, but other compilers use different constructs.
Long-ish story long-ish:
So, I'm no Linux kernel expert, but judging by the source code, this macro is used for Hotplug. I believe it signifies that the function should do something with a specific device exiting.
For example, the function you provided seems to be from the set of Hotplug functions for working with a Realtek PCI-Express card reader driver.
What does that macro actually do? Well, let's take a closer look at the macro's definition:
#define __devexit __section(.devexit.text) __exitused __cold
The first part is __section(.devexit.text):
# define __section(S) __attribute__ ((__section__(#S)))
As you can see, this creates an __attribute__(__section__()) with the section name being ".devexit.text". This means that gcc will compile the assembly code of a function with this attribute into a named section in the compiled binary with the name .devexit.text (instead of the default section).
The second part is __exitused (defined to something only if the MODULE macro is defined):
#define __exitused __used
And __used is, depending on the gcc version, defined either like this:
# define __used __attribute__((__used__))
or like this:
# define __used __attribute__((__unused__))
The former makes sure the function that has this attribute is compiled even if it is not referenced anywhere. The latter suppresses compiler warnings in the same case, although it doesn't affect the compilation in any way.
And, finally, __cold:
#define __cold __attribute__((__cold__))
This is an attribute that informs the compiler that the function with this attribute is not going to be called often, so that it can optimize accordingly.
Sooo, what do we have in the end? Looks like functions marked with __devexit are just functions that aren't called often (if called at all), and stuffed into a named section.
All the source code was taken from here. It looks like the macro has now actually been removed from the Linux Kernel.
A: "...It is most likely just an annotation..." --barak manos
Eureka! It turns out that the mystery element is maybe called an annotation, which adds extra information about a function. This extra information can be checked by the compiler to catch bugs that might otherwise go unnoticed.
Edit: @MattMcNabb says it's not an annotation. Added uncertainty.
A: These attributes were used in the Linux Kernel on certain driver functions and data declarations, putting them in a separate section that could be discarded under certain circumstances.
However, they are no longer used (or defined) from 3.10.x onward. See: https://git.kernel.org/cgit/linux/kernel/git/torvalds/linux.git/commit/?id=54b956b903607
| {
"language": "en",
"url": "https://stackoverflow.com/questions/30948952",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "11"
} |
Q: In React / Redux, how to call the same fetch twice in componentDidMount, setting 2 state variables with results The title is wordy, however a short / simple example will go a long ways in explaining my question. I have the following start to a component:
import React, { Component } from 'react';
import { connect } from 'react-redux';
import { fetchGames } from '../../path-to-action';
class TeamsApp extends Component {
constructor(props) {
super(props);
this.state = {
oldGames: [],
newGames: []
};
}
componentDidMount() {
this.props.dispatch(fetchGames('1617'));
this.setState({ oldGames: this.props.teamGameData });
this.props.dispatch(fetchGames('1718'));
this.setState({ newGames: this.props.teamGameData });
}
...
...
}
function mapStateToProps(reduxState) {
return {
teamGameData: reduxState.GamesReducer.sportsData
};
}
export default connect(mapStateToProps)(TeamsApp);
I would like the action / reducer that corresponds with fetchGames() and gamesReducer to be called twice when the component mounts. This action / reducer grabs some sports data, and I am trying to grab data for two separate seasons (the '1617' season and the '1718' season). The fetchGames() is built correctly to handle the season parameter.
With the current setup, the states aren't being set, and my linter is throwing an error Do not use setState in componentDidMount.
Can I pass a callback to this.props.dispatch that takes the results of the fetchGames() (the teamGameData prop), and sets the oldGames / newGames states equal to this object?
Any help with this is appreciated!
Edit: if i simply remove the this.setState()'s, then my teamGameData prop simply gets overridden with the second this.props.dispatch() call...
Edit 2: I'm not 100% sure at all if having the 2 state variables (oldGames, newGames) is the best approach. I just need to call this.props.dispatch(fetchGames('seasonid')) twice when the component loads, and have the results as two separate objects that the rest of the component can use.
Edit 3: I have the following part of my action:
export const fetchSportsDataSuccess = (sportsData, season) => ({
type: FETCH_NBA_TEAM_GAME_SUCCESS,
payload: { sportsData, season }
});
and the following case in my reducer:
case FETCH_NBA_TEAM_GAME_SUCCESS:
console.log('payload', action.payload);
return {
...state,
loading: false,
sportsData: action.payload.sportsData
};
and the console.log() looks like this now:
payload
{ sportsData: Array(2624), season: "1718" }
but i am not sure how to use the season ID to create a key in the return with this season's data....
Edit 4: found solution to edit 3 - Use a variable as an object key in reducer - thanks all for help on this, should be able to take it from here!
A: Copying data from the redux store to one's component state is an anti-pattern
Instead, you should modify your redux store, for example using an object to store data, so you'll be able to store datas for multiples seasons :
sportsData: {
'1617': { ... },
'1718': { ... },
}
This way you'll be able to fetch both seasons in the same time :
componentDidMount() {
const seasons = ['1718', '1617'];
const promises = seasons.map(fetchGames);
Promise.all(promises).catch(…);
}
And connect them both :
// you can use props here too
const mapStateToProps = (reduxState, props) => ({
// hardcoded like you did
oldGames: reduxState.GamesReducer.sportsData['1617'],
// or using some props value, why not
newGames: reduxState.GamesReducer.sportsData[props.newSeason],
};
Or connect the store as usual and go for the keys:
const mapStateToProps = (reduxState, props) => ({
games: reduxState.GamesReducer.sportsData,
};
…
render() {
const oldGame = this.props.games[1718];
const newGame = this.props.games[1718];
…
}
Redux is you single source of truth, always find a way to put everything you need in Redux instead of copying data in components
| {
"language": "en",
"url": "https://stackoverflow.com/questions/53035470",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Can a Mac OSX Plugin have its own Entitlements? Or extend the Main App's Entitlements? I need to be able to define new entitlements (e.g. network access, file read) for my Print Dialog Extension (PDE) Plugin in Mac OSX 10.7 and above, where apps are now mostly sandboxed.
Is this possible? If yes, how?
Edit: Looked at XPC services. XPC seems to not work, maybe because the PDE plugin runs on top of an app, e.g. Preview, and my XPC service is not within the Main App's bundle.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/15876305",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Phpunit, one test - one method? Is it a must that one test must cover one method? For example:
class Testme()
{
public function testMe ($a)
{
if ($a == 1)
{
throw new Exception ('YAY');
}
else
{
return true;
}
}
}
maybe not a "real" question though. It could be tested with:
/**
* @expectedException Exception
*/
public function test1()
{
new Testme()->testMe (1)
}
public function test2()
{
$this->assertTrue (new Testme()->testMe (2));
}
but it can be put to one method (in this case its a bit harder to test the exception). What is the good way? One method must be in one test method, or is it OK to test a method in even 4 standalone test method?
A: Rather than thinking about tests/method of your class, you should consider it as one test per expected behavior of the class. In your example, you have two different things that should happen
*
*if the parameter is one, throw an exception
*return true for other values
So you would need the two tests because there are two different things are supposed to happen.
Your tests help specify what it is that your code is supposed to DO, not what your code is supposed to look like. A method may result in different things happening depending on the parameters undo which it is run.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/28661399",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: InvalidArgumentError: You must feed a value for placeholder tensor 'ground_truth' with dtype double I am trying to understand the transfer learning through Tensorflow. But I am getting the stated error.
This is my code
def add_final_training_ops(graph, class_count, final_tensor_name,
ground_truth_tensor_name):
"""Adds a new softmax and fully-connected layer for training.
We need to retrain the top layer to identify our new classes, so this function
adds the right operations to the graph, along with some variables to hold the
weights, and then sets up all the gradients for the backward pass.
The set up for the softmax and fully-connected layers is based on:
https://tensorflow.org/versions/master/tutorials/mnist/beginners/index.html
Args:
graph: Container for the existing model's Graph.
class_count: Integer of how many categories of things we're trying to
recognize.
final_tensor_name: Name string for the new final node that produces results.
ground_truth_tensor_name: Name string of the node we feed ground truth data
into.
Returns:
Nothing.
"""
bottleneck_tensor1 = graph.get_tensor_by_name(ensure_name_has_port(
BOTTLENECK_TENSOR_NAME))
bottleneck_tensor = tf.placeholder_with_default(bottleneck_tensor1, shape=[None, 2048])
layer_weights = tf.Variable(
tf.truncated_normal([BOTTLENECK_TENSOR_SIZE, class_count], stddev=0.001),
name='final_weights')
layer_biases = tf.Variable(tf.zeros([class_count]), name='final_biases')
logits = tf.matmul(bottleneck_tensor, layer_weights,
name='final_matmul') + layer_biases
tf.nn.softmax(logits, name=final_tensor_name)
ground_truth_placeholder = tf.placeholder(tf.float64,
[None, class_count],
name=ground_truth_tensor_name)
cross_entropy = tf.nn.softmax_cross_entropy_with_logits(
logits=logits, labels=ground_truth_placeholder)
cross_entropy_mean = tf.reduce_mean(cross_entropy)
train_step = tf.train.GradientDescentOptimizer(FLAGS.learning_rate).minimize(
cross_entropy_mean)
return train_step, cross_entropy_mean
def do_train(sess,X_input, Y_input, X_validation, Y_validation):
ground_truth_tensor_name = 'ground_truth'
mini_batch_size = 10
n_train = X_input.shape[0]
graph = create_graph()
train_step, cross_entropy = add_final_training_ops(
graph, len(classes), FLAGS.final_tensor_name,
ground_truth_tensor_name)
init = tf.initialize_all_variables()
sess.run(init)
evaluation_step = add_evaluation_step(graph, FLAGS.final_tensor_name, ground_truth_tensor_name)
# Get some layers we'll need to access during training.
bottleneck_tensor1 = graph.get_tensor_by_name(ensure_name_has_port(BOTTLENECK_TENSOR_NAME))
bottleneck_tensor = tf.placeholder_with_default(bottleneck_tensor1, shape=[None, 2048])
ground_truth_tensor1 = graph.get_tensor_by_name(ensure_name_has_port(ground_truth_tensor_name))
ground_truth_tensor = tf.placeholder_with_default(ground_truth_tensor1, shape=[None, len(classes)])
i=0
epocs = 1
for epoch in range(epocs):
shuffledRange = np.random.permutation(n_train)
y_one_hot_train = encode_one_hot(len(classes), Y_input)
y_one_hot_validation = encode_one_hot(len(classes), Y_validation)
shuffledX = X_input[shuffledRange,:]
shuffledY = y_one_hot_train[shuffledRange]
for Xi, Yi in iterate_mini_batches(shuffledX, shuffledY, mini_batch_size):
print Xi.shape
print type(Xi)
print type(Yi)
print Yi.shape
print Yi.dtype
print Yi[0]
sess.run(train_step,
feed_dict={bottleneck_tensor: Xi,
ground_truth_tensor: Yi})
Print statements has the following outputs :
(10, 2048)
<type 'numpy.ndarray'>
<type 'numpy.ndarray'>
(10, 5)
float64
[ 0. 0. 0. 1. 0.]
I am getting the error at :
sess.run(train_step,feed_dict={bottleneck_tensor: Xi,ground_truth_tensor: Yi})
Can someone tell me why I am facing this error?
A: The problem is that you created a placeholder in add_final_training_ops that you don't feed. You might think that the placeholder ground_truth_tensor that you create in add_final_training_ops is the same, but it is not, it is a new one, even if it is initialized by the former.
The easiest fix would be perhaps to return the placeholder from add_final_training_ops and use this one instead.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/43736666",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How do I reduce the scannable area in my app? I've written an app which is used to scan barcodes in a paper-based product catalogue which can then be ordered.
The app is written with Xamarin and is using ZXing barcode scanner.
Unfortunately the barcodes are a bit small in the catalogue and very close to each other, which means sometimes more than 1 barcode will fit in the scannable rectangle and leads to the wrong barcode being picked up. It does not appear as though it begins scanning in the middle, it can sometimes pick something up above or below the middle.
I am using the following code base: https://github.com/Redth/ZXing.Net.Mobile/tree/master/src/ZXing.Net.Mobile/Android
I have managed to reduce the size of the overlay rectangle in GetFramingRect(), however this is obviously presentational only and does not modify the actual area that is being scanned.
In the surfaceview class I have used setPreviewSize and setPictureSize to reduce the height/width to mirror the size of the rectangle overlay (hardcoded in testing to ensure exact same sizes), yet the app is still scanning from way outside the rectangle.
I've been searching for days on a way to do this but have not been able to find anything that has worked.
Any help/pointers would be greatly appreciated.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/28447184",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Join operation on attributes from arrow structs Assume I have a json file named 'my_data.json' as below.
{"a": [1, 2], "b": {"c": true, "d": "1991-02-03"}}
{"a": [3, 4, 5], "b": {"c": false, "d": "2019-04-01"}}
If I need to do a join operation based on attribute d, can I do it directly from arrow structs? ( or are there any efficient alternatives?)
Also how nested attributes in json format are mapped into buffers once converted in arrow format?
>>> table = json.read_json("my_data.json")
>>> table
pyarrow.Table
a: list<item: int64>
child 0, item: int64
b: struct<c: bool, d: timestamp[s]>
child 0, c: bool
child 1, d: timestamp[s]
>>> table.to_pandas()
a b
0 [1, 2] {'c': True, 'd': 1991-02-03 00:00:00}
1 [3, 4, 5] {'c': False, 'd': 2019-04-01 00:00:00}
A: You can flatten the table before converting it to pandas: https://arrow.apache.org/docs/python/generated/pyarrow.Table.html#pyarrow.Table.flatten
>>> table.flatten().to_pandas()
a b.c b.d
0 [1, 2] True 1991-02-03
1 [3, 4, 5] False 2019-04-01
Then you can join on column b.d or b.c
| {
"language": "en",
"url": "https://stackoverflow.com/questions/60807709",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: PHP DOM Search HTML and specify the location of an IMG within P I'm looking to parse some HTML which is submitted from ckeditor. The HTML which is posted looks like the below:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" "http://www.w3.org/TR/REC-html40/loose.dtd">#012<html><body><p>Text Before <img alt="HAMBURGER" height="20" src="/sites/all/modules/ckeditor/plugins/apoji/images/emoji-E120.png" title="HAMBURGER" width="20"> Text After</p></body></html>
(formatted, without claiming congruency):
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" "http://www.w3.org/TR/REC-html40/loose.dtd">
<html>
<body>
<p>
Text Before
<img alt="HAMBURGER" height="20" src="/sites/all/modules/ckeditor/plugins/apoji/images/emoji-E120.png" title="HAMBURGER" width="20">
Text After
</p>
</body>
</html>
I've been looking to use something like the below:
$DOM = new DOMDocument;
$DOM->loadHTML($input);
$items = $DOM->getElementsByTagName('*');
foreach ($items as $item) {
switch ($item->nodeName) {
case "p":
$sms .= $item->nodeValue."\n";
break;
case "img":
$img_out .= "IMG Attr: ".$item->getAttribute('title')."\n";
break;
}
}
My aim to to create a plain text string, replacing the image based on its title, so I'd have a string like:
Text Before HAMBURGER Text After
I've started going down the DOM route, as it seems the best way to do it, but now I have two questions:
*
*If I loop over the document as above the IMG ends up AFTER the text,
not in the middle of it. How could I avoid this?
*The best way to extract all the plain text from the DOM document, keeping the order of items (linked to point 1).
Thanks in advance to anyone that can give me some input in to this.
A:
My aim to to create a plain text string, replacing the image based on its title, so I'd have a string like:
Text Before HAMBURGER Text After
An option is to use an XPath query to select the text/titles that you want, and output their respective values.
$html = '<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" "http://www.w3.org/TR/REC-html40/loose.dtd"><html><body><p>Text Before<img alt="HAMBURGER" height="20" src="/sites/all/modules/ckeditor/plugins/apoji/images/emoji-E120.png" title="HAMBURGER" width="20">Text After</p></body></html>';
$doc = new DOMDocument;
$doc->loadHTML($html);
$xpath = new DOMXPath($doc);
$nodes = $xpath->query('/html/body//text() | /html/body//img/@title');
$text = '';
foreach ($nodes as $node) {
$text .= $node->nodeValue . ' ';
}
echo $text; // Text Before HAMBURGER Text After
A: You can use XPath to find specific items and then replace them with new nodes.
E.g.
<?php
foreach( range(0,2) as $i ) {
$doc = new DOMDocument;
$doc->loadhtml( getData($i) );
foo($doc);
}
function foo(DOMDocument $doc) {
$xpath = new DOMXPath($doc);
foreach( $xpath->query('//p/img') as $img ) {
$alt = $img->getAttribute('alt');
$img->parentNode->replaceChild(
$doc->createTextNode($alt),
$img
);
}
echo "\n---\n", $doc->savehtml(), "\n---\n";
}
function getData($i) {
$rv = null;
switch($i) {
case 0; $rv = '<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" "http://www.w3.org/TR/REC-html40/loose.dtd"><html><body><p>Text Before <img alt="HAMBURGER" height="20" src="/sites/all/modules/ckeditor/plugins/apoji/images/emoji-E120.png" title="HAMBURGER" width="20"> Text After</p></body></html>'; break;
case 1; $rv = '<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" "http://www.w3.org/TR/REC-html40/loose.dtd">
<html>
<body>
<p>
Text Before <img alt="HAMBURGER" height="20" src="/sites/all/modules/ckeditor/plugins/apoji/images/emoji-E120.png" title="HAMBURGER" width="20">
Text After
</p>
</body>
</html>';
break;
case 2; $rv = '<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" "http://www.w3.org/TR/REC-html40/loose.dtd">
<html>
<body>
<p>
Text Before <img alt="HAMBURGER" height="20" src="/sites/all/modules/ckeditor/plugins/apoji/images/emoji-E120.png" title="HAMBURGER" width="20">
Text After
</p>
<p>
Text Before <img alt="HAMBURGER2" height="20" src="/sites/all/modules/ckeditor/plugins/apoji/images/emoji-E120.png" title="HAMBURGER" width="20">
Text After
</p>
<p>
Text Before <img alt="HAMBURGER3" height="20" src="/sites/all/modules/ckeditor/plugins/apoji/images/emoji-E120.png" title="HAMBURGER" width="20">
Text After
</p>
</body>
</html>';
break;
}
return $rv;
}
prints
---
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" "http://www.w3.org/TR/REC-html40/loose.dtd">
<html><body><p>Text Before HAMBURGER Text After</p></body></html>
---
---
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" "http://www.w3.org/TR/REC-html40/loose.dtd">
<html><body>
<p>
Text Before HAMBURGER
Text After
</p>
</body></html>
---
---
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" "http://www.w3.org/TR/REC-html40/loose.dtd">
<html><body>
<p>
Text Before HAMBURGER
Text After
</p>
<p>
Text Before HAMBURGER2
Text After
</p>
<p>
Text Before HAMBURGER3
Text After
</p>
</body></html>
---
For your question #2: please elaborate. Can be as simple as echo $doc->documentElement->textContent. But could also end up using XSL(T)
A: You could simply use a regular expression replacement:
<?php
$text = "<!DOCTYPE html PUBLIC \"-//W3C//DTD HTML 4.0 Transitional//EN\" \"http://www.w3.org/TR/REC-html40/loose.dtd\">#012<html><body><p>Text Before <img alt=\"HAMBURGER\" height=\"20\" src=\"/sites/all/modules/ckeditor/plugins/apoji/images/emoji-E120.png\" title=\"HAMBURGER\" width=\"20\"> Text After</p></body></html>";
$match = array();
preg_match("/<p[^>]*>(.*(?=<\/p))/i", $text, $match);
echo preg_replace("/<img[^>]*title=\"([^\"]+)\"[^>]*>/i", "$1", $match[1]);
?>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/9259496",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Unable to get sub element using PHP dom parser Below is my Html
<div class="product4Col">
<div class="fluidprodCol">
<div class="fluid">
<a href="url1">Title 1</a>
</div>
<div class="fluid">
<div>
<a id="">Add To Bag</a>
</div>
</div>
<div class="fluid productName title">
<a href="url2">Subtitle 1</a>
</div>
<div class="fluid productName price"><label>₹</label>2,999
</div>
<div class="fluid productName">
<div class="colorSwatch" ></div>
<div class="colorSwatch" ></div>
<div class="colorSwatch" ></div>
</div>
</div>
</div>
<div class="product4Col">
<div class="fluidprodCol">
<div class="fluid">
<a href="url11">Title 2</a>
</div>
<div class="fluid">
<div>
<a id="">Add To Bag</a>
</div>
</div>
<div class="fluid productName title">
<a href="url22">Subtitle 2</a>
</div>
<div class="fluid productName price"><label>₹</label>2,999
</div>
<div class="fluid productName">
<div class="colorSwatch" ></div>
<div class="colorSwatch" ></div>
</div>
</div>
</div>
i want to get output like below
1: url1 , Title 1 , url2 , Subtitle 1, 3 colorSwatch
2: url11 ,Title 2 , url22 , Subtitle 2, 2 colorSwatch
I tried the below code but it seems not working as expected, I am unable to level 2 data, i want to get url, title and swatches count.
Need help to fix the issue
$dataop = file_get_contents('http://localhost/dataimport.html');
$doc = new DOMDocument();
$doc->loadHTML($dataop);
$xpath = new DomXPath($doc);
$nodeList = $xpath->query("//div[@class='product4Col']");
foreach($nodeList as $prg){
echo "<br>------------------<br>";
$nodeListnx = $prg->query("//div[@class='fluidprodCol']");
foreach($nodeListnx as $prgnx){
echo "<p>new</p>";
}
echo "<br>------------------<br>";
}
A: This code corrects the problem pointed out with the second use of query() and uses the $prg as the context for the next search. But I've also added the . to the start of the query to ensure it reads only the contents of this node.
As this extracts the <a> tags inside this element, it picks out only the data from the 1st and 3rd links. It then looks as the colorSwatch classed elements, not sure what you wanted to do with them, so it just outputs the content...
$doc = new DOMDocument();
$doc->loadHTML($dataop);
$xpath = new DomXPath($doc);
$nodeList = $xpath->query("//div[@class='product4Col']");
foreach($nodeList as $prg){
echo "<br>------------------<br>";
$nodeListnx = $xpath->query(".//div[@class='fluidprodCol']//a", $prg);
echo $nodeListnx[0]->attributes['href']->textContent . " " . $nodeListnx[0]->textContent . "<br /";
echo $nodeListnx[2]->attributes['href']->textContent . " " . $nodeListnx[2]->textContent. "<br /";
$colorSwatchs = $xpath->query(".//div[@class='colorSwatch']", $prg);
foreach ( $colorSwatchs as $colorSwatch ) {
echo $colorSwatch->textContent . "<br />";
}
echo "<br>------------------<br>";
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/65384206",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Recode and Mutate_all in dplyr I am trying to use recode and mutate_all to recode columns. However, for some reason, I am getting an error. I do believe this post is similar to how to recode (and reverse code) variables in columns with dplyr but the answer in that post has used lapply function.
Here's what I tried after reading dplyr package's help pdf.
by_species<-matrix(c(1,2,3,4),2,2)
tbl_species<-as_data_frame(by_species)
tbl_species %>% mutate_all(funs(. * 0.4))
# A tibble: 2 x 2
V1 V2
<dbl> <dbl>
1 0.4 1.2
2 0.8 1.6
So, this works well.
However, this doesn't work:
grades<-matrix(c("A","A-","B","C","D","B-","C","C","F"),3,3)
tbl_grades <- as_data_frame(grades)
tbl_grades %>% mutate_all(funs(dplyr::recode(.,A = '4.0')))
I get this error:
Error in vapply(dots[missing_names], function(x) make_name(x$expr), character(1)) :
values must be length 1,
but FUN(X[[1]]) result is length 3
Can someone please explain what's the problem and why above code isn't working?
I'd appreciate any help.
Thanks
A: @Mir has done a good job describing the problem. Here's one possible workaround. Since the problem is in generating the name, you can supply your own name
tbl_grades %>% mutate_all(funs(recode=recode(.,A = '4.0')))
Now this does add columns rather than replace them. Here's a function that will "forget" that you supplied those names
dropnames<-function(x) {if(is(x,"lazy_dots")) {attr(x,"has_names")<-FALSE}; x}
tbl_grades %>% mutate_all(dropnames(funs(recode=dplyr::recode(.,A = '4.0'))))
This should behave like the original. Although really
tbl_grades %>% mutate_all(dropnames(funs(recode(.,A = '4.0'))))
because dplyr often has special c++ versions of some functions that it can use if it recognized the functions (like lag for example) but this will not happen if you also specify the namespace (if you use dplyr::lag).
A: If we call it without the dplyr:: then it works fine.
funs(recode(., A = '4.0'))
<fun_calls>
$ recode: recode(., A = "4.0")
tbl_grades %>% mutate_all(funs(recode(. ,A = '4.0')))
# A tibble: 3 x 3
V1 V2 V3
<chr> <chr> <chr>
1 4.0 C C
2 A- D C
3 B B- F
The issue lies in the funs call. If we extract that part out the same error appears.
funs(dplyr::recode(., A = '4.0'))
Error in vapply(dots[missing_names], function(x) make_name(x$expr), character(1)) :
values must be length 1, but FUN(X[[1]]) result is length 3
The issue boils down to the fact that :: is a function itself. (see ?`::`). To visualize this a little better, we look at both the infix and prefix ways of writing the function.
`::`(dplyr, recode)
function (.x, ..., .default = NULL, .missing = NULL)
{
UseMethod("recode")
}
<environment: namespace:dplyr>
dplyr::recode
function (.x, ..., .default = NULL, .missing = NULL)
{
UseMethod("recode")
}
<environment: namespace:dplyr>
funs attempts to extract the function names of its arguments by grabbing the first element of the call object and calling as.character on it. The first element of the call object is the calling function and subsequent elements are the argument values. For example:
as.call(quote(recall(., A = '4.0')))
recall(., A = "4.0")
as.call(quote(recall(., A = '4.0')))[[1]]
recall
as.call(quote(recall(., A = '4.0')))[[2]]
.
as.call(quote(recall(., A = '4.0')))[[3]]
"4.0"
as.call(quote(recall(., A = '4.0')))[[4]]
Error in as.call(quote(recall(., A = "4.0")))[[4]] :
subscript out of bounds
This runs into issues when dplyr::recode is used because this creates a nested call object. When we grab the first element, we get not just a name of a function, but an entire function call.
as.call(quote(dplyr::recall(., A = '4.0')))
dplyr::recall(., A = "4.0")
as.call(quote(dplyr::recall(., A = '4.0')))[[1]]
dplyr::recall
as.call(quote(dplyr::recall(., A = '4.0')))[[1]][[1]]
`::`
as.call(quote(dplyr::recall(., A = '4.0')))[[1]][[2]]
dplyr
as.call(quote(dplyr::recall(., A = '4.0')))[[1]][[3]]
recall
In contrast to when recode is called without dplyr::.
as.call(quote(recall(., A = '4.0')))[[1]][[1]]
Error in as.call(quote(recall(., A = "4.0")))[[1]][[1]] :
object of type 'symbol' is not subsettable
Because the first element when dplyr:: is included is a whole function call, as.character results in a vector that has both the name of a function and its arguments.
as.call(quote(dplyr::recall(., A = '4.0')))[[1]] %>% as.character()
[1] "::" "dplyr" "recall"
Funs reasonably expects the name of the function to have only one element, not three, and thus errors out.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/38809509",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
} |
Q: Extracting a substring following a specific pattern using regex in python I have a string:
lx-ss {\n id 1;\n type mx2090;\n template 4-32g;\n}\nlaxmx2k02-ie {\n id 2;\n chss mx2010;\n resource-plate 4co;\n}\ncable {\n id 3;\n chassis mx2010;\n plate 2c;\n}\n
I need to extract cable {\n id 3;\n chassis mx2010;\n plate 2c;\n}\n from the above string.
The regex that I am following is:
[\n\r].*\ncable:\s*([^\n\r]*)
But it's not working.
Kindly help. Thanks in advance.
A: Use re.search and extract your string.
Option 1
.*\n(.*{.*}\n)
m = re.search('.*\n(.*{.*}\n)', string, re.DOTALL | re.M)
print(m.group(1))
'cable {\n id 3;\n chassis mx2010;\n plate 2c;\n}\n'
Regex Details
.* # greedy match (we don't capture this)
\n # newline
( # first capture group - capture everything inside this
.*
{ # opening brace
.* # content within braces (greedy/non-greedy doesn't matter)
} # closing brace
\n
)
Option 2
This one is a bit more flexible, with regards to the positioning of your substring.
(cable\s*{.*?}\n?)
m = re.search('(cable.*?{.*?}\n?)', string, re.DOTALL | re.M).group(1)
print(m.group(1))
'cable {\n id 3;\n chassis mx2010;\n plate 2c;\n}\n'
Regex Details
( # first capture group
cable # match "cable"
\s* # match 0 or more whitespace char
{ # opening brace
.*? # non-greedy matchall
} # closing brace
\n? # optional newline
)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/46353521",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Turn the Tooltip Bootstrap functionality off According the documentation is is possible to turn off the functionality just doing $('body').off('.alert.data-api').
In the case of tooltip I tried the following from js console $('body').off('.tooltip.data-api') but it does not disable the tooltip on bottons.
Any hints how to precede?
A: Can you try:
$('a[rel=tooltip]').tooltip();
$('a[rel=tooltip]').off('.tooltip');
Don't forget to change the selector. Works fine for me... http://jsfiddle.net/D9JTZ/
A: To permanently disable a tooltip:
$('[data-toggle="tooltip"]').tooltip("disable");
To stop the tooltip from being displayed on hover but have the ability to re-enable it:
$('[data-toggle="tooltip"]').tooltip("destroy");
$('[data-toggle="tooltip"]').tooltip(); // re-enabling
A: You can't disable tooltips that way because it has no event listener on the body. Instead, you can disable the tooltips themselves using the code below.
$('[rel=tooltip]').tooltip() // Init tooltips
$('[rel=tooltip]').tooltip('disable') // Disable tooltips
$('[rel=tooltip]').tooltip('enable') // (Re-)enable tooltips
$('[rel=tooltip]').tooltip('destroy') // Hide and destroy tooltips
Edit: For Bootstrap 4, the 'destroy' command has been replaced by the 'dispose' command, so:
$('[rel=tooltip]').tooltip('dispose') // Hide and destroy tooltips in Bootstrap 4
A: I found a way to do it using CSS! Just add .tooltip { visibility: hidden } to your CSS file.
If you want to make your link accessibility friendly without the tooltip, then just add aria-label= "Here's a link description."
Hope this helps!
A: I struggled too with this, but I came up with a solution!
In my case I use Jquery Sortable which is ofcourse annoying when you have tooltips flying around!
So I made a variable
var sort = '0`;
And since almost every tooltip has an init() function, I created
if(window.sort!='1') { // So I'm not sorting
init.tooltip();
}
So, this can be the easiest enable/disable function!
| {
"language": "en",
"url": "https://stackoverflow.com/questions/13414244",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "49"
} |
Q: Grant privileges for an Oracle package? I have a package A, which uses some variables and procedures in another package B in the same schema. Now I want to move package A to a new schema. What privileges should I grant to the new schema for using the package B same way? What is the grant statement for that ?
A: Use GRANT to give execute privileges
grant execute on PACKAGE_B to new_schema;
Then, you need to ensure that any reference in package A includes the full path:
PACKAGE_B.SOME_PROC
It might be worth creating a public synonym in for the package, so that you can avoid referencing the schema too.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/44115791",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "20"
} |
Q: How is Philips TV Browser getting preview images for pages? I want to provide my own preview image for page in Philips TV (NETTV models) browser.
It is displayed near page address in history.
How can I do it?
(image from avforum, obtained from google search)
Philips TV use Opera 11.6 as browser.
userAgent string is:
Opera/9.80 (Linux mips; U; HbbTV/1.1.1 (; Philips; ; ; ; ) CE-HTML/1.0 NETTV/4.0.2; en) Presto/2.10.250 Version/11.60
A: I don't know exactly how the Philips TV browser works, but the most logical thing to try out first would be the og:image tag and see if the TV picks it up.
<meta property="og:image" content="http://example.com/image.png"/>
If not, then the TV is probably using some screen capture library. You could try this workaround to get the desired behaviour:
First, find out your TV's user agent. For example, browse to http://whatsmyuseragent.com/ from your TV.
Then on your page, create a small script that checks the user agent, and if it's the TV, show your preview picture as an overlay for a few seconds.
Hopefully the TV will take a screenshot of the initial render of the page, and then your TV splash will show.
function hideSplash() {
document.getElementById("tv-splash").style.display = "none";
}
// Remove '|Mozilla' when development is ready
if (/Philips|Mozilla/.test(navigator.userAgent)) {
setTimeout(hideSplash, 2000);
} else {
hideSplash();
}
#tv-splash {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
background: #f00 url(http://i.imgur.com/IonCAf7.jpg) center center no-repeat;
background-size: 50%;
z-index: 1;
}
<div id="tv-splash"></div>
<h1>My website</h1>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/32972653",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: laravel attach() function looks for the table in the default database I have multiple databases in my laravel project with the default one named as auth. Most of the tables in my application are in the database inventory. Two tables in this database are documents and items having a many to many relationship. I use the laravel's attach() function to save records in a third table. But I get the following error:
SQLSTATE[42S02]: Base table or view not found: 1146 Table 'auth.document_item' doesn't exist.
Any way I could define that the table document_item is also in the inventory database?
A: It should work if you
*
*Specify which connection every model is using using the $connection property.
*Specify a custom pivot model in your belongsToMany relationship.
use Illuminate\Database\Eloquent\Model;
class Document extends Model
{
protected $connection = 'auth'; // database name
protected $table = 'documents'; // table name
public function items()
{
return $this->belongsToMany(Item::class, 'document_item')->using(DocumentItem::class);
}
use Illuminate\Database\Eloquent\Model;
class Item extends Model
{
protected $connection = 'inventory'; // database name
protected $table = 'items'; // table name
public function documents()
{
return $this->belongsToMany(Document::class, 'document_item')->using(DocumentItem::class);
}
}
use Illuminate\Database\Eloquent\Relations\Pivot;
class DocumentItem extends Pivot
{
protected $connection = 'inventory'; // database name
protected $table = 'document_item'; // table name
public function document()
{
return $this->belongsTo(Document::class);
}
public function item()
{
return $this->belongsTo(Item::class);
}
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/60024706",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to run a script using Django? So I've conntected GMail API to my Django project. When I run quickstart.py alone in PyCharm it runs and works perfectly (that's the script that opens a new tab with GMail log in).
Great but now I have to give a user an opportunity to do the same. So I decided that I'll create a button and with pressing that button the quickstart.py will run and user will log in.
I tried that by creating an action.
Then I tried a usual 'a' tag.
And in both cases was error "Not found".
Also I even tried to run an php where I execute .py script.Sounds crazy.
<?php
echo exec('/quickstart.py');
?>
But the error is the same. I've also tried to play with url.py and write paths. I think I don't understand something. Please, explain.
So again and shortly: Press button -> Run quickstart.py
A: Seems like you have not to run quickstart.py, but create there some function, import your from quickstart import your_function into your views.py and call that your_function from your_custom_view.
Simplified logic like that:
from quickstart import your_function
def your_custom_view(request):
button_was_pressed = request.GET.get("button")
if button_was_pressed:
your_function()
return HttpResponse("Button pressed")
else:
return HttpResponse("No button pressed")
And make your Button work like a link (if you dont need a POST request), smth like:
<a href="{% url "your_custom_view_url" %}?button=True">Button</a>
NOTE: This is not working code, but simplified logic, with so short information that you gave.
UPDATE 1:
settings.py:
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
views.py:
from your_project.settings import BASE_DIR
path_to_json = os.path.join(BASE_DIR, r'client_secret.json')
flow = client.flow_from_clientsecrets(path_to_json, SCOPES)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/50140450",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Unix batch rename folders (underscores to spaces) I have a collection of folders, and I would like to replace all underscores in the folder names with spaces.
Any ideas?
Thanks
A: (bash) This will find all folders in or beneath current directory with an underscore in the name and rename them as you mention:
for d in $(find . -name '*_*' -type d) ; do
new=$(echo $d | sed -e 's/_/ /g')
mv $d $new
done
A: you could try something like
#> ls -l | grep '^d' | awk '{oldname = $9 ; gsub(/_/, " " ,$9); print "mv " oldname " " $9 }' > temp.script
#> chmod 744 temp.script
#> ./temp.script
Test it first of course :)
A: Does your system have a rename command that does what you need? On some systems, it exists and can use some species of regular expression to make the changes. I use a version which uses Perl regular expressions (a Perl script, in other words):
find . -type f -name '*_*' -print0 | xargs -0 rename 's/_+/ /g'
On the other hand, the standard version on Linux tends to be rather feeble by comparison (and wouldn't do what you need).
Note that if you want to rename directories too, then do them before renaming any files, or after renaming all the files. Doing them mixed up will mean that your renaming runs into problems with accessing file names that were in one directory but the directory has been renamed since the file name was generated. Even using -depth as an option to find is not guaranteed to be safe.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/6811099",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How can I use eager loading with scope in complicated nested association? I have 4 models such as below
*
*User (has 1 profile, many communities, and many codes)
*Profile (belongs to user)
*Community (has many codes, belongs to user)
*Code (belongs to both community and user)
Now I'm trying to show 10 records of the code that belongs to particular community.
This code contains external table's info such as
*
*username(in user table)
*comment(in profile table)
*point(in profile table)
Now, it's issuing many sql queries because I'm not using eager loading.
In this case, how can I customize my code to make this eager loading in order to make load speed faster?
controllers/communities_controller.rb
#CanCan load_and_authorize_resouce
load_and_authorize_resource :find_by => :community_name,
models/community.rb
belongs_to :user
has_many :codes
models/code.rb
belongs_to :user, counter_cache: true
belongs_to :community, counter_cache: true
scope :recent, lambda { |n = 10| includes(:user).where('users.deleted_at' => nil).order("users.last_active_at DESC").limit(n) }
models/user.rb
has_one :profile
has_many :communities
has_many :codes
models/profile.rb
belongs_to :user
views/communityes/show.html.erb
<% @community.codes.recent.each do |code| %>
<%= render 'codes/code', {:code => code, :icon_photo => code.user.profile.user_avatar} %>
<% end %>
views/communityes/_code.html.erb
<tr>
Username: <%= code.user.username %> <br />
Code: <%= code.data %> <br />
Comment: <%= code.user.profile.comment %> <br />
Point: <%= code.user.profile.point.to_s %>
</tr>
A: Shouldn't be particularly complicated, just .includes all the bits you want to eager load ..
@community.codes.recent.includes(user: :profile)
Also, are a Community's codes always equal to that of all of it's Users? If so, you should be using a has_many :codes, through: :users association on Community.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/18509004",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Select2 edit value of selected option I want to edit option text and value selecting.
<select id="sel">
<option value="Option one">Option one</option>
<option value="Option two">Option two</option>
<option value="Option three">Option three</option>
<option value="Option four">Option four</option>
</select>
$("#sel").select2({
width: 400,
tags: true
});
Let's say I select Option one, and I want to edit it to First Option, both text and value. How can I do it?
After it should looks like
<select id="sel">
<option value="First option">First option</option>
<option value="Option two">Option two</option>
<option value="Option three">Option three</option>
<option value="Option four">Option four</option>
</select>
Something like this.
Before was tEST after tEDT EDIT, and all this I want to do with input of select2
A: I have solve my problem
var s = $("#sel").select2({
tags: true,
closeOnSelect: false,
width: 400,
});
var $search = s.data('select2').dropdown.$search || $el.data('select2').selection.$search;
s.on("select2:selecting", function(e) {
$search.val(e.params.args.data.text);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.0/js/select2.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/css/select2.css" rel="stylesheet" />
<select id="sel">
<option value="Option one">Option one</option>
<option value="Option two">Option two</option>
<option value="Option three">Option three</option>
<option value="Option four">Option four</option>
</select>
A: Try this:
$('#sel').click(function() {
var selectedOption = $(this).children("option").filter(":selected");
if (selectedOption.val() === 'Option one') {
selectedOption.text('First Option');
selectedOption.attr('value', 'First option');
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="sel">
<option value="Option one">Option one</option>
<option value="Option two" selected="1">Option two</option>
<option value="Option three">Option three</option>
<option value="Option four">Option four</option>
</select>
A: You can use the built-in change event like this :
$("#sel").select2({
width: 400,
tags: true
}).on("change", function (e) {
var elem = $("#sel");
if( elem.val() == "Option one" ){
$('#sel option:contains("Option one")').val('First option').text('First option');
elem.select2("destroy");
elem.select2({
width: 400,
tags: true
});
}
});
Here is the fiddle : https://jsfiddle.net/9aotj2or/17/
| {
"language": "en",
"url": "https://stackoverflow.com/questions/38008653",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: How to save google WEBP image format into database using C#? I am optimizing a MVC application and obviously for optimization the very first thing is optimize images/pictures. I create webp images with google's webp plugin for photoshop. I am just wondering that is there any possibility to save webp images in a SQL database and display it somewhere in a MVC razor view?
Regards
| {
"language": "en",
"url": "https://stackoverflow.com/questions/45823826",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Pointer arithmetic and dereferencing In the following code, can anyone please explain to my what the line in bold is doing.
struct southParkRec {
int stan[4];
int *kyle[4];
int **kenny;
string cartman;
};
int main()
{
southParkRec cartoon;
cartoon.stan[1] = 4;
cartoon.kyle[0] = cartoon.stan + 1;
cartoon.kenny = &cartoon.kyle[2];
*(cartoon.kenny + 1) = cartoon.stan; //What does this line do?
return 0;
}
A: Think of it as
cartoon.kenny[1] = cartoon.stan;
They are basically the same thing
A: If we bring the whole thing to one common style of using the subscript operator [] (possibly with &) instead of a * and + combination, it will look as follows
cartoon.stan[1] = 4;
cartoon.kyle[0] = &cartoon.stan[1];
cartoon.kenny = &cartoon.kyle[2];
cartoon.kenny[1] = &cartoon.stan[0];
After the
cartoon.kenny = &cartoon.kyle[2];
you can think of kenny as an "array" of int * elements embedded into the kyle array with 2 element offset: kenny[0] is equivalent to kyle[2], kenny[1] is equivalent to kyle[3], kenny[2] is equivalent to kyle[4] and so on.
So, when we do
cartoon.kenny[1] = &cartoon.stan[0];
it is equivalent to doing
cartoon.kyle[3] = &cartoon.stan[0];
That's basically what that last line does.
In other words, if we eliminate kenny from the consideration ("kill Kenny"), assuming that the rest of the code (if any) doesn't depend on it, your entire code will be equivalent to
cartoon.stan[1] = 4;
cartoon.kyle[0] = &cartoon.stan[1];
cartoon.kyle[3] = &cartoon.stan[0];
As for what is the point of all this... I have no idea.
A: In cartoon you have:
- stan, an array of 4 ints.
- kyle, an array of 4 pointers to int.
- kenny, a pointer to a pointer to int, that is, let's say, a pointer to an "array of ints".
cartoon.stan[1] = 4; sets second element of stan array (an int) to 1.
cartoon.kyle[0] = cartoon.stan + 1; sets first element of kyle array (a pointer to int) to point to the second element of stan array (which we have just set to 4).
cartoon.kenny = &cartoon.kyle[2]; sets kenny pointer to point to the third element of kyle array.
*(cartoon.kenny + 1) = cartoon.stan; sets fourth element of kyle array (a pointer to int) to point to the first element of stan array (which hasn't been initialised yet). More in detail:
cartoon.kenny gets kenny pointer's address (third element of kyle array),
cartoon.kenny+1 gets the next int after that address (fourth element of kyle array, which happens to be a pointer to int),
*(cartoon.kenny + 1) dereferences that pointer, so we can set it, and
= cartoon.stan sets it to point to the first element of stan array.
A: It is incrementing the pointer at *cartoon.kenny. 'kenny' is a pointer to a pointer, so the first dereference returns a pointer, which is incremented, and a value assigned. So, *(kenny + 1) now points to the beginning of the array 'stan'.
A: It sets the last element of Kyle to point to the first element of Stan.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/3105062",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: Error in web browser control navigating In my web browser app for wp7, i have two xaml pages. One is mainpage.xaml and other is web.xaml.
I have a youtube button in mainpage.xaml, if i click on it, it navigates to youtube.com in web.xaml. But if i press the device back button(to navigate to mainpage) after the youtube is fully navigated, then there is no error. But if i press the back button while the youtube is navigating then it throws an error. Error in recording the history i think(I also have history page to record the history). The error is - "Cannot write to a closed TextWriter". This error will also occur sometime for someother sites too. I have also added the image of that error. Can anyone help me with this? Thanks in advance for your help!
public partial class Web : PhoneApplicationPage
{
List<Uri> HistoryStack;
int HistoryStack_Index;
bool fromHistory;
bool navigationcancelled = false;
public IsolatedStorageFile historyFile = null;
public IsolatedStorageFileStream filestream = null;
public StreamWriter stream = null;
public Web()
{
InitializeComponent();
HistoryStack = new List<Uri>();
historyFile = IsolatedStorageFile.GetUserStoreForApplication();
if (historyFile.FileExists("History.txt"))
{
Error in this line--->filestream = historyFile.OpenFile("History.txt", System.IO.FileMode.Append, FileAccess.Write);--->Error in this line
stream = new StreamWriter(filestream);
}
else
{
filestream = historyFile.OpenFile("History.txt", System.IO.FileMode.Create);
stream = new StreamWriter(filestream);
}
HistoryStack_Index = 0;
fromHistory = false;
browsers[this.currentIndex].Navigated += new EventHandler<System.Windows.Navigation.NavigationEventArgs>(browsers_Navigated);
browsers[this.currentIndex].Navigating += new EventHandler<NavigatingEventArgs>(browsers_Navigating);
}
protected override void OnNavigatedFrom(System.Windows.Navigation.NavigationEventArgs e)
{
base.OnNavigatedFrom(e);
{
stream.Close();
}
}
private void browsers_Navigated(object sender, System.Windows.Navigation.NavigationEventArgs e)
{
if (!fromHistory)
{
if (HistoryStack_Index < HistoryStack.Count)
{
HistoryStack.RemoveRange(HistoryStack_Index, HistoryStack.Count - HistoryStack_Index);
}
HistoryStack.Add(e.Uri);
//HistoryURL temp = new HistoryURL();
//temp.URL = e.Uri.ToString();
//app.historyList.Add(temp);
Thread.Sleep(100);
Dispatcher.BeginInvoke(() =>
{
string title = (string)browsers[this.currentIndex].InvokeScript("eval", "document.title.toString()");
stream.WriteLine(title + ";" + e.Uri.ToString());---> **Error in this line.**
});
}
HistoryStack_Index += 1;
}
fromHistory = false;
navigationcancelled = false;
}
A: If I understand this correctly you are having 2 handlers for navigated event (OnNavigatedFrom and browsers_Navigated).
The problem probably is that in OnNavigatedFrom you are calling stream.Close(); so stream.WriteLine will fail the next time it is called since the stream was closed.
Try moving stream.Close(); to the application close event and use stream.Flush() after stream.WriteLine.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/10932410",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Google Optimize redirect test reloads page We have a Google Optimize redirect test running. We noticed that the page is being loaded twice (that is, reloaded by the Google Optimize javascript right after it first loaded) even when there's no redirect taking place and the URL is the same.
Is there any way to turn this off?
Unfortunately, this happens even after we end the particular test (why?). We keep getting these double loads. We really want to avoid this because it's messing with some pages that use session flash messages.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/65953630",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Python IF/ELIF/ELSE statements producing error I have been working on a project, and to test If/Elif/Else projects, I wrote a little bit of code to get an idea how it worked. I wrote:
opclo = input('>');
if(opclo == 'CLOSED'):
print "Good night.";
elif(opclo == 'WACKED'):
print "wacked";
else:
print "Good morning.";
It gives me this error:
Traceback (most recent call last):
File "python", line 2, in <module>
File "<string>", line 1, in <module>
NameError: name 'CLOSED' is not defined
I am wondering why it does this. I have tried mutliple things, such as removing brackets, adding a opclo = opclo2 (making line 1's opclo into opclo2) and adding a array with "CLOSED" and "WACKED" in it. Any ideas?
Thanks.
A: You are using Python2 so you need to use raw_input instead of input.
opclo = raw_input('>')
if opclo == 'CLOSED':
print "Good night."
elif opclo == 'WACKED':
print "wacked"
else:
print "Good morning."
A: tl;dr
input('>') - for python expressions
raw_input - for strings.
You should use raw_input
| {
"language": "en",
"url": "https://stackoverflow.com/questions/39438642",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Loop through hash in Ruby My search returns this hash bellow
{"product"=>[{:title=>"It's All About Shoes Barbie Shoe Tree 2010 Hallmark Ornament"}, {:title=>"Iron Lady Bug Key Holder - Hide-A-Key"}]}
here is the loop and the code that generates the hash
id = "B003TM2IDS,B004X75EX4"
ids = id.split(',')
response = []
prod = Hash.new
product = Hash.new
#fetch product title from amazon
for aid in ids do
res = Amazon::Ecs.item_lookup(aid, { :response_group => "ItemAttributes"})
res.items.each do |item|
prod[:title] = item.get("ItemAttributes/Title")
end
# hash
product = {"product" => response.push(prod.dup)}
end
#loop to print the titles - Not working
product.each do |item_prod|
puts item_prod.title
end
I do get the
undefined method `title' for # (NoMethodError)
My question are:
*
*Is the Product hash correct?
*Is the loop correct?
I've done this millions of times but some reason I can't see the problem with this
Thanks a lot in advance
A: Do as below:
product["product"].each do |prod|
puts prod[:title]
end
A: product["product"].each { |p| puts p[:title] }
| {
"language": "en",
"url": "https://stackoverflow.com/questions/22275105",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Python code to print a dictionary in Jinja2 templating I'm trying to print a dictionary that looks like for e.g.
groups = {'place': ABC, 'name': XYZ , 'IP': ['1.1.1.1','2.2.2.2']}
in a table in Jinja2 templating format:
I've a word document that looks like this for now:
I know this isn't how it is supposed to look and I'm stuck as I'm a complete beginner in Jinja2. Could someone help me out here? I want to know how I can modify my table in the word document to get the required result.
PS: The code on the word document currently is:
{% tr for key,value in groups.items() %} {{key}} {% for elem in value %}{{ elem }}{% if value|length > 0 and value.index(elem) != value|length-1 %} {%endif%}{% endfor %} {%tr endfor %}
Essentially my dict should look like:
Place
Name
IP
ABC
XYZ
1.1.1.1, 2.2.2.2
The table in the image attached is what I tried for now, but it throws errors
A: you can try something like this.
<table>
<thead>
<tr>
{% for key in groups.keys() %}
<th>{{ key|title }}</th>
{% endfor %}
</tr>
</thead>
<tbody>
<tr>
{% for key in groups.keys() %}
<td>{{ groups[key]}}</td>
{% endfor %}
</tr>
</tbody>
</table>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/75483345",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: FormatException with String.Format and DateTime from DataReader I've written code which uses a stored procedure, that works. But i get a System.FormatException here:
while (rdr.Read())
{
PrichinatextBox.Text = (string)rdr["Prichina"];
dateEdit.Text = (string.Format("{yyyy-MM-dd}", rdr["data"])); //error format exception
}
connection.Close();
MessageBox.Show("Ваши данные добавлены");
Write code for realize it.
A: Let me guess, you get a System.FormatException here
dateEdit.Text = (string.Format("{yyyy-MM-dd}", rdr["data"]));
That is because you can't use String.Format in that way, a format string must have an index or the index must be preceeded like here:
dateEdit.Text = string.Format("{0:yyyy-MM-dd}", rdr["data"]);
or without String.Format but DateTime.ToString:
int columndIndex = rdr.GetOrdinal("data");
DateTime dt = rdr.GetDateTime(columndIndex);
dateEdit.Text = dt.ToString("yyyy-MM-dd");
| {
"language": "en",
"url": "https://stackoverflow.com/questions/36716905",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-6"
} |
Q: Using Or condition in Do While loop VB I've got a Do While....Or.... loop that is as follows;
Do While headingStart <> -1 OrElse count <= 3
...[Statement]...
count = count + 1
Loop
However my count is going above 3 and the operation still occurs. The operation only ends when the headingStart condition is satisfied otherwise an infinite loop occurs.
I've tried replacing Or with OrElse but no success - I assume it's a simple mistake I'm making?
Thanks
Hugh
A: From your text it sounds like you want to use the and operator:
Do While headingStart <> -1 And count <= 3
...[Statement]...
count = count + 1
Loop
That way the loop will only execute when both criteria are met. In other words, you will jump out of the loop if headingStart equals -1 OR when count > 3.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/48519584",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
} |
Q: Solr Index Strategy for Q&A Websites I m pretty new with Solr and I would like to use it for the search on a Q&A website (Quora like) I m building.
Here is how Questions and Anwsers are :
Question
- Title
- Description
- Tags (social tags)
- Score (score comes from user up/down vote the question)
Answers
- Description
- Tags
- Score (score comes from user up/down vote the answer)
Of course you can have as many answer to a question as you want.
There will be three type of documents that need to be index : questions, articles, ...
What would be the best strategy in terms of index to make the Questions and Answers searchable ?
A: If you're using the DataImportHandler, you can have an <entity> for the question and then specify a sub-entities for the answers. For example:
<document name="questions">
<entity name="question" query="select id, question from questions">
<field column="id" name="id" />
<field column="question" name="question" />
<entity name="answer"
query="select question_id, answer from answers"
cacheKey="question_id"
cacheLookup="question.id"
processor="CachedSqlEntityProcessor">
<field name="answer" column="answer" />
</entity>
</entity>
</document>
Note that this example uses CachedSqlEntityProcessor to avoid hitting the database unnecessarily.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/10319145",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How screenlocker applications open their activity instantly? I'm writing an application which should display its main activity (there is only 1 activity) instantly when everytime user turn on the screen. you can think it's like some kind of a screenlocker app. I can display the activity while the phone turns on however sometimes (not everytime) displaying the activity takes 1 or 2 seconds which is my problem. How can I prevent this waiting? How screenlocker apps can show their activity instantly? Is there a way out?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/25740587",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Able to upload file but non retrieve/diplay them - Page not found I am creating a website in Django and Postgres where a user can answer multiple questions and upload some PDFs.
I am able to upload the PDF but not to display it. I want the user to be able to click on a link, and a new webpage opens containing the PDF.
In my details.html I wrote the code:
<a href="{{ MEDIA_URL }}{{project.thirdquestiondetail.third_seven.url}}">Click here to see the file</a>
But, if the user clicks on the links, he gets this messages:
I have the following:
mysite/urls.py
from django.contrib import admin
from django.urls import path, include
from django.views.generic.base import TemplateView
from django.conf import settings
from django.views.static import serve
from django.conf.urls.static import static
urlpatterns = [
path('', TemplateView.as_view(template_name='home.html'), name='home'),
path('conditions/', TemplateView.as_view(template_name='conditions.html'), name='conditions'),
path('admin/', admin.site.urls),
path('users/', include('users.urls')),
path('users/', include('django.contrib.auth.urls')),
path('projects/', include('projects.urls')),
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
mysite/settings.py
STATICFILES_DIRS = [
os.path.join(BASE_DIR, 'mysite/static/')
]
STATIC_ROOT = os.path.join(BASE_DIR, 'static')
STATIC_URL = '/static/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URL = '/media/'
As said, I am pretty sure the PDF is uploaded. In fact, if I login as superuser in the admin panel, I can see the PDF.
HOWEVER if I click it, I get the same 404 error reported above
I think the error is in my settings.py when I definied my /media/. So I checked several similar questions but it seems my settings are in line with the chosen answers.
A: After making those changes quit and rerun manage.py runserver
try changing this <a href="{{ MEDIA_URL }}{{project.thirdquestiondetail.third_seven.url}}">Click here to see the file</a>
to <a href="{% get_media_prefix %}{{project.thirdquestiondetail.third_seven.url}}">Click here to see the file</a>
A: I noticed that also the upload is not actually working.
I solved as follow:
1) In my views.py I have to change the request.POST['chosen-name'] to request.FILES['chosen-name']
2) Add in my hard-coded html form the tag: enctype="multipart/form-data in my template.html
So from:
<form method="post">..</form>
to:
<form method="post" enctype="multipart/form-data">..</form>
Check: Django FileField upload is not working for me
| {
"language": "en",
"url": "https://stackoverflow.com/questions/57608134",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Browser waiting on localhost on POST request I'm building a website, and i have a registration form where i need to submit a form via POST, and register a user in a mongoDB databse. The website works fine so far, but when i submit the registration form the browser just "waits for localhost" forever. I use EJS as my templating engine, although i don't think that matters.
register.ejs:
<% include partials/header %>
<%include partials/nav %>
<h1>REGISTER</h1>
<a href="/login">Login</a>
<form id="registerForm" action="/register" method="post">
<div class="form-group">
<label for="exampleInputEmail1">Email address</label>
<input type="email" name="username" class="form-control" id="exampleInputEmail1" aria-describedby="emailHelp" placeholder="Enter email">
<small id="emailHelp" class="form-text text-muted">We'll never share your email with anyone else.</small>
</div>
<div class="form-group">
<label for="exampleInputPassword1">Password</label>
<input type="password" name="password" class="form-control" id="exampleInputPassword1" placeholder="Password">
<small id="passwordHelp" class="form-text text-muted">Your password must be at least 8 characters long.</small>
</div>
<button type="submit" class="btn btn-primary">Submit</button>
</form>
<% include partials/footer %>
app.js:
var express = require('express'),
app = express(),
mongoose = require('mongoose'),
passport = require("passport"),
bodyParser = require("body-parser"),
User = require("./models/user"),
LocalStrategy = require("passport-local"),
passportLocalMongoose = require("passport-local-mongoose");
//Set up MongoDB
var mongo = require("mongo");
var MongoClient = require('mongodb').MongoClient;
var assert = require('assert');
var ObjectId = require('mongodb').ObjectID;
var url = 'mongodb://localhost:27017/customerapp';
//MongoJS
var mongojs = require("mongojs");
var db = mongojs("customerapp", ["users"]);
//Mongoose
var mongoose = require('mongoose');
mongoose.Promise = global.Promise
mongoose.createConnection("mongodb://localhost:27017/customerapp");
app.set('view engine', 'ejs');
app.use(bodyParser.urlencoded({extended: true}));
app.use(require("express-session")({
secret: "wah wah wah",
resave: false,
saveUninitialized: false
}));
app.use(passport.initialize());
app.use(passport.session());
passport.use(new LocalStrategy(User.authenticate()));
passport.serializeUser(User.serializeUser());
passport.deserializeUser(User.deserializeUser());
var index = require("./routes/index");
var about = require("./routes/about");
var login = require("./routes/login");
//var register = require("./routes/register");
app.all("index", index);
app.all("about", about);
app.all("login", login);
//app.all("register", register);
// AUTH Routes
//Register get request
app.get("/register", function(req, res) {
res.render("register");
});
//Handle post register req. at '/register'
app.post("/register", function(req, res) {
User.register(new User({
username: req.body.username}),
req.body.password,
function(err, user) {
if(err) {
console.log(err);
return res.render("register");
}
passport.authenticate("local")(req, res, function() {
res.redirect("/secret")
})
});
});
app.listen(process.env.PORT || 3000, process.env.IP, function () {
console.log('Example app listening on port 3000!')
})
A: You are using three params instead of two, use it like this.
//Handle post register req. at '/register'
app.post("/register", function(req, res) {
User.register(new User({
username: req.body.username,
password: req.body.password
}),
function(err, user) {
if(err) {
console.log(err);
return res.render("register");
}
passport.authenticate("local")(req, res, function() {
res.redirect("/secret")
})
});
});
A: Check to make sure your versions of mongoDB and mongoose are compatible. You can find a compatibility chart here.
In addition to checking your MongoDB and mongoose versions, you should also check if it's actually connecting to the database by using a callback function when you connect to the server, like so:
//Connecting to database using mongoose.connect with a callback
mongoose.connect("mongodb://localhost:27017/customerapp", function(error) {
if(error) {
console.log("There was an error connecting to MongoDB.");
console.log(error);
} else {
console.log("Successfully connected to MongoDB!");
}
});
This callback may also work with mongoose.createConnection instead of mongoose.connect, but I haven't tried. If neither message prints to the console, then the app is not getting any response from the server, not even an error.
For some reason, as long as mongoDB is running at all, GET requests still seem to work even if the connection attempt hangs, but POST requests run into trouble.
Source: Mongoose never connects to mongodb
| {
"language": "en",
"url": "https://stackoverflow.com/questions/45925314",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Permission denied (publickey). Bitbucket git pull doesn't work I have been trying to debug this problem I am facing since 2 days now. I noticed this problem when I was trying to pull something from bitbucket. It says
[email protected]: Permission denied (publickey).
fatal: Could not read from remote repository.
Please make sure you have the correct access rights
and the repository exists.
I have tried every solution form deleting old ssh keys and adding new ones to adding the existing keys to the ssh-agent. Also, ssh -T [email protected] command again throws [email protected]: Permission denied (publickey) as the error and ssh -vT [email protected] throws the following as the error:
OpenSSH_9.0p1, LibreSSL 3.3.6
debug1: Reading configuration data /Users/amijeetthakur/.ssh/config
debug1: /Users/amijeetthakur/.ssh/config line 1: Applying options for *bitbucket.org
debug1: Reading configuration data /etc/ssh/ssh_config
debug1: /etc/ssh/ssh_config line 21: include /etc/ssh/ssh_config.d/* matched no files
debug1: /etc/ssh/ssh_config line 54: Applying options for *
debug1: Authenticator provider $SSH_SK_PROVIDER did not resolve; disabling
debug1: Connecting to bitbucket.org port 22.
debug1: Connection established.
debug1: identity file /Users/amijeetthakur/.ssh/id_rsa type 0
debug1: identity file /Users/amijeetthakur/.ssh/id_rsa-cert type -1
debug1: Local version string SSH-2.0-OpenSSH_9.0
debug1: Remote protocol version 2.0, remote software version conker_44eee6a33e b7cd6ff70e1a
debug1: compat_banner: no match: conker_44eee6a33e b7cd6ff70e1a
debug1: Authenticating to bitbucket.org:22 as 'git'
debug1: load_hostkeys: fopen /Users/amijeetthakur/.ssh/known_hosts2: No such file or directory
debug1: load_hostkeys: fopen /etc/ssh/ssh_known_hosts: No such file or directory
debug1: load_hostkeys: fopen /etc/ssh/ssh_known_hosts2: No such file or directory
debug1: SSH2_MSG_KEXINIT sent
debug1: SSH2_MSG_KEXINIT received
debug1: kex: algorithm: [email protected]
debug1: kex: host key algorithm: rsa-sha2-512
debug1: kex: server->client cipher: [email protected] MAC: <implicit> compression: none
debug1: kex: client->server cipher: [email protected] MAC: <implicit> compression: none
debug1: expecting SSH2_MSG_KEX_ECDH_REPLY
debug1: SSH2_MSG_KEX_ECDH_REPLY received
debug1: Server host key: ssh-rsa SHA256:zzXQOXSRBEiUtuE8AikJYKwbHaxvSc0ojez9YXaGp1A
debug1: load_hostkeys: fopen /Users/amijeetthakur/.ssh/known_hosts2: No such file or directory
debug1: load_hostkeys: fopen /etc/ssh/ssh_known_hosts: No such file or directory
debug1: load_hostkeys: fopen /etc/ssh/ssh_known_hosts2: No such file or directory
debug1: Host 'bitbucket.org' is known and matches the RSA host key.
debug1: Found key in /Users/amijeetthakur/.ssh/known_hosts:1
debug1: rekey out after 134217728 blocks
debug1: SSH2_MSG_NEWKEYS sent
debug1: expecting SSH2_MSG_NEWKEYS
debug1: SSH2_MSG_NEWKEYS received
debug1: rekey in after 134217728 blocks
debug1: get_agent_identities: bound agent to hostkey
debug1: get_agent_identities: agent returned 2 keys
debug1: Will attempt key: /Users/amijeetthakur/.ssh/id_rsa RSA SHA256:nux65XHIgoNnct40pwEJWQ+kLrA2W2r0oqm9PHGvH1Q explicit agent
debug1: Will attempt key: [email protected] RSA SHA256:1YofMNkb/JQpdGd8OZlyyjaX9RQR0h9c6ZWzZMDlWes agent
debug1: SSH2_MSG_EXT_INFO received
debug1: kex_input_ext_info: server-sig-algs=<ecdsa-sha2-nistp384,ecdsa-sha2-nistp521,[email protected],[email protected],[email protected],[email protected],[email protected],ssh-rsa,rsa-sha2-256,rsa-sha2-512,ssh-dss,ecdsa-sha2-nistp256>
debug1: SSH2_MSG_SERVICE_ACCEPT received
debug1: Authentications that can continue: publickey
debug1: Next authentication method: publickey
debug1: Offering public key: /Users/amijeetthakur/.ssh/id_rsa RSA SHA256:nux65XHIgoNnct40pwEJWQ+kLrA2W2r0oqm9PHGvH1Q explicit agent
debug1: Authentications that can continue: publickey
debug1: Offering public key: [email protected] RSA SHA256:1YofMNkb/JQpdGd8OZlyyjaX9RQR0h9c6ZWzZMDlWes agent
debug1: Authentications that can continue: publickey
debug1: No more authentication methods to try.
[email protected]: Permission denied (publickey).
Note: I observed this error to come after updating my Mac to MacOs Ventura.
A: If you have already added SSH key then try setting URL
get the SSH URL from bit-bucket then,
git remote set-url origin "SSHURL"
paste URL without quotes.
A: Make sure that the ~/.ssh folder and the keys have the correct permissions set.
$ chmod 700 ~/.ssh
$ chmod 400 ~/.ssh/id_rsa
$ chmod 400 ~/.ssh/id_rsa.pub
Remember that you can specify which key to use, in case you got more than one key-pair. Specify the private key, not the public key:
$ ssh -i ~/.ssh/id_rsa user@host
When dealing with several key-pairs, the ssh client needs to know which key to use. Add the following lines in ~/.ssh/config:
Host bitbucket.org
PreferredAuthentications publickey
IdentityFile ~/.ssh/another_private_key
A: You can fix it by adding these two lines to the end of your /etc/ssh/ssh_config file:
HostkeyAlgorithms +ssh-rsa
PubkeyAcceptedAlgorithms +ssh-rsa
Alternatively you can add them to your ~/.ssh/config file either for all hosts or only to a specific one (change * to desired host):
Host *
HostkeyAlgorithms +ssh-rsa
PubkeyAcceptedAlgorithms +ssh-rsa
| {
"language": "en",
"url": "https://stackoverflow.com/questions/74371848",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: (PHP) How to obtain the filename (or file path) when a script is executed as a cron job? I have a PHP script that executes perfectly when called via the browser. It fails, however, when called as a cron job. The failure is because the script needs to access its own filename, which I do via $thefilepath = $_SERVER['REQUEST_URI']. Unfortunately, the $_SERVER['REQUEST_URI'] variable isn't populated when the file is called as a cron job. (I've similarly failed with trying $_SERVER['PHP_SELF']).
In case anyone is interested, the script needs to access its own filename because the filename contains an integer (for example, filename = myfile4.php) that is used in the calculation of a subset of rows in a database table. More specifically, myfile4.php takes rows with IDs from, say, 40-49, whereas myfile5.php takes rows with IDs from 50-59, etc.
So, my question is, given that $_SERVER['REQUEST_URI'] and $_SERVER['PHP_SELF'] fail to provide the filename (or filepath) for use in a cron job, can anyone please suggest an alternative method of accessing a script's own filename within this cron execution context?
Thank you!
A: Use __FILE__ or __DIR__ or dirname(__FILE__)
http://www.php.net/manual/en/language.constants.predefined.php
A: $argv[0] will always contain the name of the script: http://www.php.net/manual/en/reserved.variables.argv.php
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7339705",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Calculate the coord of the center of a circle knowing 2 points
Hello, then I need to calculate the center of a circle O knowing 2 points A and B.
I made a drawing because I am not able to explain in english.
Thanks
A: It is impossible, You need at least 3 points to unambiguously define a circle.
A: Since you have 2 points. Randomly choose a third. Then calculate the circle center point.
This solution meets the criteria of the circle going through the original 2 points.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/9132941",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Splitting two lists and assigning data from one list to values in the other and thank you in advance for the help. My problem concerns methods in Python and is as follows.
I have two lists. One list, x, is made up of rows that contain 2 values, x1 and x2, each. The second list, data is made up of rows that contain 3 values, x0, t, and r, each. I split each row accordingly:
for datum in data:
x0, t, r = data.split()
for item in x:
x1, x2 = x.split()
Values of x1 and x2 may be found within values of x0. If x1 corresponds to a value of x0, I would like to assign to x1 the values of t and r that also correspond to that x0. I would like to perform this for each x2 as well. The end result will be to make some calculation for each pair of x1 and x2 values using the values t and r.
For example: Say we have two lines from data (x0,t,r):
311 0 2
202 5 13
And we have one line from x (x1,x2):
311 202
In the end I'd like to assign the values 0 and 2 to x1 and 5 and 13 to x2 so that I can make an arbitrary calculation such as y=r1-r2+t1*t2, where r1 is the r value assigned to x1, etc. Note that I would like to be able to calculate this for every row in x.
Thanks again!
A: Build a dictionary from data with the key x0:
dataDictionary = {}
for datum in data:
x0, t, r = datum.split()
dataDictionary[x0] = t, r
This allows you to look up values from data based on x0.
Now, when you loop through x, you can get those values and do your calculations:
for item in x:
x1, x2 = item.split()
t1, r1 = dataDictionary[x1]
t2, r2 = dataDictionary[x2]
y = r1 - r2 + t1 * t2
print(y)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/31253914",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Showing percentage without decimal using billboardjs on pie chart I am using billboardjs to draw a pie chart .
When pie chart displayed it's shows percentage as 60.0% and 40.0% like that.
I want to display it as 60% and 40% . I don't want to display decimal part .
Any help .
A: You can use toFixed(x) function that allows you to chose the number of decimal after the comma
Source : https://www.w3schools.com/jsref/jsref_tofixed.asp
For example : (42.4).toFixed(0) === 42
| {
"language": "en",
"url": "https://stackoverflow.com/questions/56438010",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: System.Data.DataViewRow showing instead of value Whenever I try to run my program, after selecting dropdownList1 data, the dropdownlist2 populates with System.Data.DataViewRow text rather than populating the values.
I've tried 6 Hrs searching this but didn't find answer.
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
string s1 = DropDownList1.SelectedValue.ToString();
string perfectid = string.Empty;
con.Open();
SqlDataAdapter sda1 = new SqlDataAdapter("select [Id] from [Table] where movie_name='"+s1+"'",con);
DataTable dt = new DataTable();
sda1.Fill(dt);
GridView g1 = new GridView();
g1.DataSource = dt;
g1.DataBind();
foreach (GridViewRow dr in g1.Rows)
{
perfectid = dr.Cells[0].Text;
}
SqlDataAdapter sda = new SqlDataAdapter("select song_name from songs where id='" + perfectid + "'", con);
DataTable dta = new DataTable();
sda.Fill(dta);
DropDownList2.DataSource = dta;
DropDownList2.DataBind();
con.Close();
}
A: As mentioned in comment:
1] Don't use string concatenation for sql query, use parameterized queries. Check the below code for use of sqlcommand with use of parameters.
2] I've clubbed both the queries using subquery so you only need to connect to database once. [This will work only if there is 1 row returned from the subquery which it should in this case as you are using ID as reference, else use IN operator]
3] Mapping DropDownList2.DataSource = dta; is not sufficient, you need to map DataTextField and DataValueField too to inform exactly which column will be mapped, I've used column ref by index but you can give name too. According to me that's the reason that it's showing System.Data.DataViewRow in dropdown instead of the values.
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
string s1 = DropDownList1.SelectedValue.ToString();
string perfectid = string.Empty;
con.Open();
SqlCommand cmd = new SqlCommand("select song_name from songs where id=(select [Id] from [Table] where movie_name=@moviename",con);
cmd.Parameters.AddWithValue("@moviewname", s1);
SqlDataAdapter sda = new SqlDataAdapter(cmd);
DataTable dta = new DataTable();
sda.Fill(dta);
con.Close();
DropDownList2.DataSource = dta;
DropDownList2.DataTextField = dta.Columns[0].ColumnName;
DropDownList2.DataValueField = dta.Columns[0].ColumnName;
DropDownList2.DataBind();
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/36233880",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: ActiveRecords returning model object from a join table I have the following DB for a simple flash cards example i'm building:
create_table "card_associations", :force => true do |t|
t.integer "card_id"
t.integer "deck_id"
end
create_table "cards", :force => true do |t|
t.string "question"
t.string "answer"
end
create_table "decks", :force => true do |t|
t.string "name"
t.string "description"
end
I've setup the has_many through relationships in all my models.
Now I want to be able to return a list of all cards from the join table, given the deck id.
If I run the query:
CardAssociation.find_by_deck_id(3).card
It retruns the first card with the deck_id of 3. But when I try.
CardAssociation.find_all_by_deck_id(3).card
I get the error
NoMethodError: undefined method `card' for #
Can someone help me with this? I feel like i'm making a very simple mistake.
Thanks for the help
A: The find_all_* methods always return an Array (which could be empty)!
CardAssociation.find_all_by_deck_id(3) # => Array of results
CardAssociation.find_all_by_deck_id(3).first # => first result of the Array or nil if no result
I advise you to first read the Ruby on Rails Style Guide, and then use the Rails3 way of finding object with ActiveRecord:
CardAssociation.where(:deck_id => 3) # => Array of results
CardAssociation.where(:deck_id => 3).first # => first result of the Array if exists
In your case, a scope can be set up on the Card model:
You said: "Now I want to be able to return a list of all cards from the join table, given the deck id"
class Card < ActiveRecord::Base
scope :for_deck, lambda { |deck| joins(:card_associations).where('card_associations.deck_id = ?', deck.try(:id) || deck) }
end
This scope can be used like following:
Card.for_deck(deck) # returns an Array of Card objects matching the deck.id
As defined in the scope, the parameter of Card.for_deck(deck) can be a deck object or a deck_id (type Integer)
Hope this helped!
| {
"language": "en",
"url": "https://stackoverflow.com/questions/13481121",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: CS50 pset4 blur function - trouble figuring out why the tests fails on 3x3 and 4x4 images I've been working on the code for CS50 pset4 blur function.
the function is suppose to calculate the average RGB values of all neighboring pixels, and then apply it to the "middle" pixel (as the pixel can be located on the corners, edges, or anywhere in the middle)
I get no errors when compiling or running the code.
the output images all appear blurred, but when i run the code against check50, it fails on two tests:
:( blur correctly filters 3x3 image
expected "70 85 95\n80 9...", not "70 85 95\n80 9..."
:( blur correctly filters 4x4 image
expected "70 85 95\n80 9...", not "70 85 95\n80 9..."
The other tests pass (testing pixel on edge, corner and middle), so i'm having a hard time understanding what i'm doing wrong.
Here's my code:
// Blur image
void blur(int height, int width, RGBTRIPLE image[height][width])
{
// creating a blank copy
RGBTRIPLE blured[height][width];
// upper left corner (anchored)
for (int i = 0; i < 1; i++)
{
for (int j = 0; j < 1; j++)
{
float trackerRed = 0, trackerGreen = 0, trackerBlue = 0;
for (int k = i; k <= i + 1; k++)
{
for (int l = j; l <= j + 1; l++)
{
trackerRed += (float)image[k][l].rgbtRed;
trackerGreen += (float)image[k][l].rgbtGreen;
trackerBlue += (float)image[k][l].rgbtBlue;
}
}
blured[i][j].rgbtRed = round(trackerRed / 4);
blured[i][j].rgbtGreen = round(trackerGreen / 4);
blured[i][j].rgbtBlue = round(trackerBlue / 4);
}
}
// top middle row
for (int i = 0; i < 1; i++)
{
for (int j = 1; j < width - 1; j++)
{
float trackerRed = 0, trackerGreen = 0, trackerBlue = 0;
for (int k = i; k <= i + 1; k++)
{
for (int l = j - 1; l <= j + 1; l++)
{
trackerRed += (float)image[k][l].rgbtRed;
trackerGreen += (float)image[k][l].rgbtGreen;
trackerBlue += (float)image[k][l].rgbtBlue;
}
}
blured[i][j].rgbtRed = round(trackerRed / 6);
blured[i][j].rgbtGreen = round(trackerGreen / 6);
blured[i][j].rgbtBlue = round(trackerBlue / 6);
}
}
// upper right corner (anchored)
for (int i = 0; i < 1; i++)
{
for (int j = width - 1; j < width; j++)
{
float trackerRed = 0, trackerGreen = 0, trackerBlue = 0;
for (int k = i; k <= i + 1; k++)
{
for (int l = j - 1; l <= j; l++)
{
trackerRed += (float)image[k][l].rgbtRed;
trackerGreen += (float)image[k][l].rgbtGreen;
trackerBlue += (float)image[k][l].rgbtBlue;
}
}
blured[i][j].rgbtRed = round(trackerRed / 4);
blured[i][j].rgbtGreen = round(trackerGreen / 4);
blured[i][j].rgbtBlue = round(trackerBlue / 4);
}
}
// left middle column
for (int i = 1; i < height - 1; i++)
{
for (int j = 0; j < 1; j++)
{
float trackerRed = 0, trackerGreen = 0, trackerBlue = 0;
for (int k = i - 1; k <= i + 1; k++)
{
for (int l = j; l <= j + 1; l++)
{
trackerRed += (float)image[k][l].rgbtRed;
trackerGreen += (float)image[k][l].rgbtGreen;
trackerBlue += (float)image[k][l].rgbtBlue;
}
}
blured[i][j].rgbtRed = round(trackerRed / 6);
blured[i][j].rgbtGreen = round(trackerGreen / 6);
blured[i][j].rgbtBlue = round(trackerBlue / 6);
}
}
// center
for (int i = 1; i < height - 1; i++)
{
for (int j = 1; j < width - 1; j++)
{
float trackerRed = 0, trackerGreen = 0, trackerBlue = 0;
for (int k = i - 1; k <= i + 1; k++)
{
for (int l = j - 1; l <= j + 1; l++)
{
trackerRed += (float)image[k][l].rgbtRed;
trackerGreen += (float)image[k][l].rgbtGreen;
trackerBlue += (float)image[k][l].rgbtBlue;
}
}
blured[i][j].rgbtRed = round(trackerRed / 9);
blured[i][j].rgbtGreen = round(trackerGreen / 9);
blured[i][j].rgbtBlue = round(trackerBlue / 9);
}
}
// right middle column
for (int i = 1; i < height - 1; i++)
{
for (int j = width - 1; j < width; j++)
{
float trackerRed = 0, trackerGreen = 0, trackerBlue = 0;
for (int k = i - 1; k <= i + 1; k++)
{
for (int l = j; l <= j; l++)
{
trackerRed += (float)image[k][l].rgbtRed;
trackerGreen += (float)image[k][l].rgbtGreen;
trackerBlue += (float)image[k][l].rgbtBlue;
}
}
blured[i][j].rgbtRed = round(trackerRed / 6);
blured[i][j].rgbtGreen = round(trackerGreen / 6);
blured[i][j].rgbtBlue = round(trackerBlue / 6);
}
}
// lower left corner (anchored)
for (int i = height - 1; i < height; i++)
{
for (int j = 0; j < height; j++)
{
float trackerRed = 0, trackerGreen = 0, trackerBlue = 0;
for (int k = i - 1; k <= i; k++)
{
for (int l = j; l <= j + 1; l++)
{
trackerRed += (float)image[k][l].rgbtRed;
trackerGreen += (float)image[k][l].rgbtGreen;
trackerBlue += (float)image[k][l].rgbtBlue;
}
}
blured[i][j].rgbtRed = round(trackerRed / 4);
blured[i][j].rgbtGreen = round(trackerGreen / 4);
blured[i][j].rgbtBlue = round(trackerBlue / 4);
}
}
// bottom middle row
for (int i = height - 1; i < height; i++)
{
for (int j = 1; j < width - 1; j++)
{
float trackerRed = 0, trackerGreen = 0, trackerBlue = 0;
for (int k = i - 1; k <= i; k++)
{
for (int l = j - 1; l <= j + 1; l++)
{
trackerRed += (float)image[k][l].rgbtRed;
trackerGreen += (float)image[k][l].rgbtGreen;
trackerBlue += (float)image[k][l].rgbtBlue;
}
}
blured[i][j].rgbtRed = round(trackerRed / 6);
blured[i][j].rgbtGreen = round(trackerGreen / 6);
blured[i][j].rgbtBlue = round(trackerBlue / 6);
}
}
// lower right corner (anchored)
for (int i = height - 1; i < height; i++)
{
for (int j = width - 1; j < width; j++)
{
float trackerRed = 0, trackerGreen = 0, trackerBlue = 0;
for (int k = i - 1; k <= i; k++)
{
for (int l = j - 1; l <= j; l++)
{
trackerRed += (float)image[k][l].rgbtRed;
trackerGreen += (float)image[k][l].rgbtGreen;
trackerBlue += (float)image[k][l].rgbtBlue;
}
}
blured[i][j].rgbtRed = round(trackerRed / 4);
blured[i][j].rgbtGreen = round(trackerGreen / 4);
blured[i][j].rgbtBlue = round(trackerBlue / 4);
}
}
// copy blured image data back to the original image
for (int i = 0; i < height; i++)
{
for (int j = 0; j < width; j++)
{
image[i][j].rgbtRed = blured[i][j].rgbtRed;
image[i][j].rgbtGreen = blured[i][j].rgbtGreen;
image[i][j].rgbtBlue = blured[i][j].rgbtBlue;
}
}
return;
}
Any help is much appreciated
A: I'm also in the class so this might be completely wrong but this is what I saw:
// right middle column
for (int l = j; l <= j; l++)
Your for loop for the int l doesn't seem like it's correct. Shouldn't there be 2 columns?
// lower left corner (anchored)
for (int j = 0; j < height; j++)
j should be width but since its a corner based on your previous code I think it should be 1
| {
"language": "en",
"url": "https://stackoverflow.com/questions/61342447",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Java Streams Map, Get Value - List from Key (With filtering) Assuming I'm writing a method that takes in Map<String, List<Integer>> as shown below, and a String name to filter. My return type is Stream<Integer> how do I convert from a Stream<List<Integer>> to Stream<Integer>?
Map<String, List<Integer>> person = Map.of(
"John", List.of(54, 18),
"Alex", List.of(28), "Tom",
List.of(78, 42)
);
My current implementation returns a Stream<List<Integer>>. Realistically, I would iterate through the list to retrieve all Integers in the list.
Code implementation:
return table.entrySet().stream()
.filter(map -> map.getKey().equals(name))
.map(map -> map.getValue());
A: As @Thomas has pointed out in the comments, iterating over the whole Map would be wasteful. And solution he proposed probably is the cleanest one:
map.getOrDefault(name, Collections.emptyList()).stream()
Alternatively, you can make use of flatMap() without performing redundant iteration through the whole map like that:
public static <K, V> Stream<V> getStreamByKey(Map<K, Collection<V>> map,
K key) {
return Stream.ofNullable(map.get(key))
.flatMap(Collection::stream);
}
The same result can be achieved with Java 16 mapMulti():
public static <K, V> Stream<V> getStreamByKey(Map<K, Collection<V>> map,
K key) {
return Stream.ofNullable(map.get(key))
.mapMulti(Iterable::forEach);
}
A: As others pointed out in comments, use flatMap instead of map in the last step to reduce the double nesting:
return table.entrySet().stream()
.filter(map -> map.getKey().equals(name))
.flatMap(entry -> entry.getValue().stream());
| {
"language": "en",
"url": "https://stackoverflow.com/questions/74285954",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: C++ Binary Read Write Files ok so im on the 2nd Semester on my unversity have done c and doing c++ now
doing the project in DevC.
Currently im making a program that will do the charging processes of a shop while having and editing the database.
Tried writing and reading a full struct but dosent work so i went down writing 2 int numbers and reading them but this also dosent work while getting random number when reading even though if i write txt the numbers seem ok.
//write and read are different fucntion only 1 is called .
//file creation code
int AccountNumber=0;
ofstream FileCreator("Database.dat",ios::binary);
FileCreator<<AccountNumber;
AccountNumber=1;
FileCreator<<AccountNumber;
and
//reading code
int AccountNumber=0;
ifstream FileCreator("Database.dat",ios::binary);
FileCreator.seekg(0,ios::beg);
FileCreator.read(reinterpret_cast<char*>(&AccountNumber), sizeof(AccountNumber));
cout<<AccountNumber<<endl;
FileCreator.read(reinterpret_cast<char*>(&AccountNumber), sizeof(AccountNumber));
cout<<AccountNumber<<endl;
I expect 0 and 1 at the output but get 12592 and 12592.
A: To complete the answer of @Thomas Matthews
but why does it matter ? does << write differently that .write in binary files ?
Out of windows you will not see a difference, under windows the \n are saved/read unchanged if the file open in binary mode, else a writting \n produces \r\n and reading \c\n returns \n. It like the difference between "r"/"rb" and "w"/"wb" for fopen.
You can mix the use of the operator <</>> and read/write in binary mode or not but you have to take care of the separators, for instance :
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
int AccountNumber = 123;
{
ofstream bin("bin",ios::binary);
bin << AccountNumber << '\n'; // a \n to finish the number allowing to read it later
bin.write((char *) &AccountNumber, sizeof(AccountNumber));
}
{
ofstream txt("txt");
txt << AccountNumber << '\n';
txt.write((char *) &AccountNumber, sizeof(AccountNumber));
}
{
ifstream bin("bin",ios::binary);
AccountNumber = 0;
bin >> AccountNumber;
cout << AccountNumber << endl;
// I have to read the \n with read() because >> bypass it.
// Supposing I written '@' rather than '\n' `bin >> c;` can be used
char c;
bin.read(&c, 1);
cout << (int) c << endl;
AccountNumber = 0;
bin.read((char *) &AccountNumber, sizeof(AccountNumber));
cout << AccountNumber << endl;
}
return 0;
}
Compilation and execution (out of Windows) :
pi@raspberrypi:/tmp $ g++ -pedantic -Wextra -Wall f.cc
pi@raspberrypi:/tmp $ ./a.out
123
10
123
pi@raspberrypi:/tmp $ cmp txt bin
pi@raspberrypi:/tmp $
I am not under Windows so to use the binary mode or not changes nothing, the two files are identical
A: For writing binary files, use std::ostream::write() method, not operator<<:
FileCreator.write((char *) &AccountNumber, sizeof(AccountNumber));
The cast is necessary because there is no overload for writing integers to the stream.
Remember, read and write are paired for binary I/O.
Edit 1: Fixed length & variable length records
Be aware that you need the size of the item when writing and reading. This will work for fixed size/length data items and structures. However, it does not work well with variable length data, such as text.
For variable length records, you may want to write the length first followed by the data:
static const char hello[] = "Hello";
static const unsigned int data_size(sizeof(hello) - 1);
FileCreator.write((char *) &data_size, sizeof(data_size));
FileCreator.write(&hello[0], data_size);
In the above example, the "- 1" is there so that the terminating NUL character is not written to the file. You don't need this for binary files, but YMMV (I use the idiom when writing to console and other human readable streams).
| {
"language": "en",
"url": "https://stackoverflow.com/questions/55906812",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Data Annotation MVC How can I add a required field ONLY if I have a value in my username model.
I have:
@Html.PasswordFor(
model => model.Password,
new { required = "This field is required" }
)
I want :
@Html.PasswordFor(
model => model.Password,
new { if (Model.UserName != null) {required = "This field is required"} }
)
Thank you
A: Well instead of using an if statement, you can always use the ternary operator ?:
@Html.PasswordFor(
model => model.Password,
new { required = Model.UserName != null ? "This field is required" : null }
)
Alternatively (if setting required as null does not work) then you could use it one level up:
@Html.PasswordFor(
model => model.Password,
Model.UserName != null
? new { required = "This field is required" }
: new { }
)
A: You can simply use
if(Model.UserName != null)
{
@Html.PasswordFor(model => model.Password, new { required = "This fiels is required"})
}
else
{
@Html.PasswordFor(model => model.Password)
}
Why do you need to complicate thing?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/24159551",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Call function only once after page load completely I want to call function one second after the page is completely loaded
$(window).bind("load", function() {
window.setInterval(function(){ your_func(); }, 1000);
});
It calls every second. I want it to be executed only once
A: You can use $(document).ready();
$(document).ready(function() {
setTimeout(function() { your_func(); }, 1000);
});
A: You may use $( document ).ready(); for that problem:
$( document ).ready(function() {
setTimeout(function() { console.log( "ready!" ); }, 1000);
});
A: Your solution works well, don't need to change to document ready
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
$(window).bind("load", function() {
setTimeout(function() {
console.log('Hey');
}, 1000);
});
</script>
Notice the differences between the events:
The ready event occurs after the HTML document has been loaded, while the onload event occurs later, when all content (e.g. images) also has been loaded.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/50273311",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: how can i add a slection model checkbox in angular-table Angular Table creation code with input type checkbox.
angular.module("tableApp",[]).controller('tableAppCtrl', ['$scope',
function($scope) {
$scope.titleString="Table Demo";
$scope.prodDataTable = [{
"productType": "A",
"productName": "Aaaaaa"
}, {
"productType": "B",
"productName": "Bbbbbb"
}, {
"productType": "C",
"productName": "Cccccc"
}];
}
]);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div ng-app="tableApp" ng-controller="tableAppCtrl">
<h3>{{titleString}}</h3>
<table>
<tr>
<th><input type="button" value="checkALL"></th>
<th>Product Type</th>
<th>Product Name</th>
</tr>
<tr ng-repeat="d in prodDataTable">
<td><input type="checkbox"></td>
<td>{{d.productType}}</td>
<td>{{d.productName}}</td>
</tr>
</table>
</div>
I have been using angular-table and I have to include a selection model to it.
Please suggest ways or links to use it with table.
A: use this but you need to work on the duplicate value creation-
<div ng-app="tableApp" ng-controller="tableAppCtrl">
<h3>{{titleString}}</h3>
<table>
<tr>
<th><input type="button" value="{{(selectAllval==true) ? 'UncheckALL' : 'checkALL'}}" ng-click="selectAll(selectAllval)"></th>
<th>Product Type</th>
<th>Product Name</th>
</tr>
<tr ng-repeat="d in prodDataTable">
<td><input type="checkbox" ng-checked="selectAllval" ng-click="setProductType(d.productType)"></td>
<td>{{d.productType}}</td>
<td>{{d.productName}}</td>
</tr>
</table>
{{setProductTypes}}
angular.module("tableApp",[]).controller('tableAppCtrl', ['$scope', function($scope) {
$scope.titleString="Table Demo";
$scope.selectAllval= false;
$scope.setProductTypes= [];
$scope.selectAll= function(val){
if(val==false){
$scope.selectAllval= true;
} else{
$scope.selectAllval= false;
}
};
$scope.setProductType= function(type){
$scope.setProductTypes.push(type);
};
$scope.prodDataTable = [{ "productType": "A", "productName": "Aaaaaa" }, { "productType": "B", "productName": "Bbbbbb" }, { "productType": "C", "productName": "Cccccc" }]; } ]);
A: try the below code -
angular.module("tableApp",[]).controller('tableAppCtrl', ['$scope',
function($scope) {
$scope.titleString="Table Demo";
$scope.selectAllval= false;
$scope.selectAll= function(val){
if(val==false){
$scope.selectAllval= true;
} else{
$scope.selectAllval= false;
}
};
$scope.prodDataTable = [{
"productType": "A",
"productName": "Aaaaaa"
}, {
"productType": "B",
"productName": "Bbbbbb"
}, {
"productType": "C",
"productName": "Cccccc"
}];
}
]);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div ng-app="tableApp" ng-controller="tableAppCtrl">
<h3>{{titleString}}</h3>
<table>
<tr>
<th><input type="button" value="{{(selectAllval==true) ? 'UncheckALL' : 'checkALL'}}" ng-click="selectAll(selectAllval)"></th>
<th>Product Type</th>
<th>Product Name</th>
</tr>
<tr ng-repeat="d in prodDataTable">
<td><input type="checkbox" ng-checked="selectAllval" ></td>
<td>{{d.productType}}</td>
<td>{{d.productName}}</td>
</tr>
</table>
</div>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/34102022",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Render image in mtlView with Metal Api help me figure out the metal api, I want to render the normal picture via mtlView, but it does not work for me, here's my code, what am I doing wrong? Next, I would like to use the UISlider and CIColorControls to change the contrast of this picture in 60fps, please explain.
import MetalKit
class ViewController: UIViewController, MTKViewDelegate {
let device = MTLCreateSystemDefaultDevice()
let colorSpace = CGColorSpaceCreateDeviceRGB()
lazy var commandQueue: MTLCommandQueue = {
[unowned self] in
return self.device!.makeCommandQueue()
}()!
lazy var ciContext: CIContext = {
[unowned self] in
return CIContext(mtlDevice: self.device!)
}()
@IBOutlet weak var mtlView: MTKView!
let filter = CIFilter(name: "CIPhotoEffectProcess" )
let contrastFilter = CIFilter(name: "CIColorControls")
var image = CIImage()
@IBOutlet weak var slider: UISlider!
override func viewDidLoad() {
super.viewDidLoad()
mtlView.delegate = self
let img = UIImage(named: "picture")
let ciImage = CIImage(image: img!)
image = ciImage!
}
func mtkView(_ view: MTKView, drawableSizeWillChange size: CGSize) {
}
func draw(in view: MTKView) {
guard let targetTexture = view.currentDrawable?.texture else {
return
}
let commandBuffer = commandQueue.makeCommandBuffer()
let bounds = CGRect(origin: CGPoint.zero, size: view.drawableSize)
ciContext.render(image,
to: targetTexture,
commandBuffer: commandBuffer,
bounds: bounds,
colorSpace: colorSpace)
commandBuffer?.present(view.currentDrawable!)
commandBuffer?.commit()
}
}
A: I don't see any code that would set device to the MTKView. An MTKView without a device would be returning empty drawable. I'd suggest adding this to the viewDidLoad:
mtlView.device = device
| {
"language": "en",
"url": "https://stackoverflow.com/questions/51686203",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Performing calculations on a set of values in a pandas data frame with respect to a certain attribute I have to find the year with the best average user rating. My approach is to find all the unique values in the Year column and then find the mean of all the values in the User Rating columns that correspond to those unique values.
I have managed to find unique occurrences in the Year column and have stored them in a list using:
import numpy as np
years = df.['Year'].unique()
years = np.sort(years)
print(years)
Output: [2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019]
I have to find mean value of User Ratings for each of these year values and then display which year has the best average User Rating. Can anyone help?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/69799520",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Array property in JSON object updated via foreach - updates all keys I'm kind of pulling my hair out on this one. I am trying to build an array of JSON objects via a foreach loop. It works great - except for one property. The property that I am having difficulty with - is an array that is updated during each loop. During the first loop, the array would be empty. At the end of the first loop, I add a value to prepare it for the next loop. During the next loop - create a new JSON object to add to the array. When I add the array property, it also updates the previous key. Kinda of strange. The end result, is for each array key (JSON Object), the 'excludedUsers' array is the same.
( function () {
// Pre-populate User Permissions
var userPermissions = $('.js-user-permissions').val();
var numberOfSelects = 1;
var count = 1;
var arraySize;
var viewHtml = '';
var userSelects = [];
var excludedUsers = [];
if(userPermissions) {
userPermissions = jQuery.parseJSON(userPermissions);
// An array of JSON like:
// [{ usersId=57, type="user"}, { usersId=58, type="user"}]
arraySize = userPermissions.length;
for(var idx = 0; idx < userPermissions.length; idx++) {
userSelects[idx] = {};
console.log("Loop #" + idx);
// Set default value of select element
userSelects[idx].usersId = userPermissions[idx].usersId;
userSelects[idx].type = userPermissions[idx].type;
userSelects[idx].disabled = arraySize == count ? null : 'disabled';
userSelects[idx].excludedUsers = excludedUsers;
userSelects[idx].count = numberOfSelects;
userSelects[idx].name = "user" + numberOfSelects;
numberOfSelects++;
console.log("Before Array Push: " + JSON.stringify(userSelects));
excludedUsers[idx] = userPermissions[idx].usersId;
console.log("After Array Push: " + JSON.stringify(userSelects));
count++;
}
}
})();
If you ran - this, I am finding the following output to the console. (NOTE: Watch the property 'excludedUsers').......
Loop #0
Before Array Push: [{"usersId":57,"type":"user","disabled":"disabled","excludedUsers":[],"count":1,"name":"user1"}]
After Array Push: [{"usersId":57,"type":"user","disabled":"disabled","excludedUsers":[57],"count":1,"name":"user1"}]
Loop #1
Before Array Push: [{"usersId":57,"type":"user","disabled":"disabled","excludedUsers":[57],"count":1,"name":"user1"},{"usersId":58,"type":"user","disabled":null,"excludedUsers":[57],"count":2,"name":"user2"}]
After Array Push: [{"usersId":57,"type":"user","disabled":"disabled","excludedUsers":[57,58],"count":1,"name":"user1"},{"usersId":58,"type":"user","disabled":null,"excludedUsers":[57,58],"count":2,"name":"user2"}]
A: You are referencing the same instance of the array in every object that you build.
userSelects[idx].excludedUsers = excludedUsers; does not copy the excludedUsers array into a new array for the object, it assigns a reference to the original array to userSelects[idx].excludedUsers.
If you want to clone the array you can use Array.slice() to do a shallow copy:
userSelects[idx].excludedUsers = excludedUsers.slice(0)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/28575838",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Change default page in ASP.NET Core Razor Page from Index to Home I am changing Default Page
services.AddRazorPages(options =>
{
//...
}).AddRazorPagesOptions(options =>
{
options.Conventions.AddPageRoute("/Home", "");
});
but an exception occured
AmbiguousMatchException: The request matched multiple endpoints. Matches:
/Home
/Index
What can I do?
A: One option is to edit the @page directive in the Index.cshtml and Home.cshtml files to configure the routes:
/* Home.cshtml.cs */
@page "/"
/* Index.cshtml.cs */
@page "/Index"
This applies explicit routes for the two pages, so that the Home Razor Pages page becomes the root page, and the Index page maps only to /Index.
Note that with this approach, the call to AddPageRoute shown in your question is not needed.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/68096730",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: ORACLE Add new record if any field changes I'm trying to write an Oracle procedure. I have a table and currently I'm using a merge statement. When a record is changed, it updates it, if it is new, it adds it.
However, we want to keep track of changed records. So I'm adding three fields: startdate, enddate, currentflag. I don't want to update the record if there are any changes, I want to add a new record instead. But I do want to add an enddate and change the flag on the old record.
So, if I have a table like this:
TableID
Field1
Field2
Field3
StartDate
EndDate
CurrentFlag
And it has data like this
TableID Field1 Field2 Field3 StartDate EndDate CurrentFlag
001 DataA Cow Brown 3-Oct-18 Y
001 DataA Cow White 1-Sep-18 3-Oct-18 N
002 DataB Horse Dapple 3-Oct-18 Y
I want to merge in some data
TableID Field1 Field2 Field3
001 NewData Cow Black
002 DataB Horse Dapple
005 Data3 Cat Black
So that the final table looks like this
TableID Field1 Field2 Field3 StartDate EndDate CurrentFlag
001 DataA Cow Brown 3-Oct-18 10-Oct-18 N
001 DataA Cow White 1-Sep-18 3-Oct-18 N
001 NewData Cow Black 10-Oct-18 Y
002 DataB Horse Dapple 3-Oct-18 Y
005 Data3 Cat Black 10-Oct-18 Y
My pseudocode is
for each record in source file
find current record in dest table (on ID and flag = Y)
if any other fields do not match (Field1, Field2, Field3)
then update current record, set enddate, current flag to n
and add new record with startdate = sysdate, current flag is Y
if no match found, then add new record with startdate = sysdate, current flag is Y
I'm not sure how to turn that pseudocode into Oracle SQL code. Can I use the same MERGE statement, but in the WHEN MATCHED add a check to see if any of the other fields are different?
I will be doing this for several tables, a few of which have a lot of records and many fields. So I need to figure out something that works and isn't as slow as molasses.
UPDATE
I have created a procedure as suggested, with some modifications, so it works:
CREATE OR REPLACE PROCEDURE TESTPROC AS
BEGIN
DECLARE
l_count NUMBER;
CURSOR TRN is
SELECT * from sourceTable;
BEGIN
FOR each_record IN TRN
LOOP
-- if a record found but fields differ ...
l_count := 0;
SELECT COUNT(*) INTO l_count
FROM destTable DIM
WHERE each_record.TableID = DIM.TableID
and (each_record.Field1 <> DIM.Field1
or each_record.Field2 <> DIM.Field2
or each_record.Field13 <> DIM.Field3)
AND DIM.CurrentFlag = 'Y';
-- ... then update existing current record, and add with new data
IF l_count > 0 THEN
UPDATE destTable DIM
SET EndDate = sysdate
,CurrentFlag = 'N'
WHERE each_record.TableID = DIM.TableID;
INSERT INTO destTable
(TableID
, Field1
, Field2
, Field3
, StartDate
, CurrentFlag)
VALUES (each_record.TableID
, each_record.Field1
, each_record.Field2
, each_record.Field3
, sysdate
, 'Y');
COMMIT;
END IF;
-- if no record found with this key...
l_count := 0;
SELECT COUNT(*) INTO l_count
FROM destTable DIM
WHERE each_record.TableID = DIM.TableID;
-- then add a new record
IF l_count = 0 THEN
INSERT INTO destTable
(TableID
, Field1
, Field2
, Field3
, StartDate
, CurrentFlag)
VALUES (each_record.TableID
, each_record.Field1
, each_record.Field2
, each_record.Field3
, sysdate
, 'Y');
END IF;
END LOOP;
COMMIT;
END;
END TESTPROC
And on my small table, it worked nicely. Now I'm trying it on one of my larger tables (800k records, but by no means the largest table), and I'm updating this question while it runs. It's been nearly an hour, and obviously that isn't acceptable. Once my program comes back, I'll add indices on the TableID, and TableID and CurrentFlag. If indices don't help, any suggestions for the slow as molasses aspect?
A: You can write a Simple procedure for the same:
DECLARE
l_count NUMBER;
CURSOR C1 is
-- YOUR DATA FROM SOURCE
BEGIN
for each_record in c1
l_count := 0;
SELECT COUNT(*) into l_count from destination_table where field1=
eachrecord.field1 and .... and flag = 'Y'; -- find current record in dest table (on ID and flag = Y)
-- if any other fields do not match (Field1, Field2, Field3)
IF L_COUNT > 0 THEN
update current record, set enddate, current flag to n
END IF;
INSERT new record with startdate = sysdate, current flag is Y
END;
Mod by OP: That led to the right direction. The following code will do the trick, providing there is also an index on TableID and (TableID, CurrentFlag).
CREATE OR REPLACE PROCEDURE TESTPROC AS
BEGIN
DECLARE
l_count NUMBER;
CURSOR TRN is
SELECT * from sourceTable;
BEGIN
FOR each_record IN TRN
LOOP
-- if a record found but fields differ ...
l_count := 0;
SELECT COUNT(*) INTO l_count
FROM destTable DIM
WHERE each_record.TableID = DIM.TableID
and (each_record.Field1 <> DIM.Field1
or each_record.Field2 <> DIM.Field2
or each_record.Field13 <> DIM.Field3)
AND DIM.CurrentFlag = 'Y';
-- ... then update existing current record, and add with new data
IF l_count > 0 THEN
UPDATE destTable DIM
SET EndDate = sysdate
,CurrentFlag = 'N'
WHERE each_record.TableID = DIM.TableID;
INSERT INTO destTable
(TableID
, Field1
, Field2
, Field3
, StartDate
, CurrentFlag)
VALUES (each_record.TableID
, each_record.Field1
, each_record.Field2
, each_record.Field3
, sysdate
, 'Y');
COMMIT;
END IF;
-- if no record found with this key...
l_count := 0;
SELECT COUNT(*) INTO l_count
FROM destTable DIM
WHERE each_record.TableID = DIM.TableID;
-- then add a new record
IF l_count = 0 THEN
INSERT INTO destTable
(TableID
, Field1
, Field2
, Field3
, StartDate
, CurrentFlag)
VALUES (each_record.TableID
, each_record.Field1
, each_record.Field2
, each_record.Field3
, sysdate
, 'Y');
END IF;
END LOOP;
COMMIT;
END;
END TESTPROC
A: Maybe you could use triggers to perform that.
CREATE OR REPLACE TRIGGER insTableID
BEFORE INSERT OR UPDATE
ON tableID
FOR EACH ROW
DECLARE
v_exists NUMBER := -1;
BEGIN
SELECT COUNT(1) INTO v_exists FROM tableID t where t.Field1 = :new.Field1 and ... ;
IF INSERTING THEN
IF v_exist > 0 THEN
null;--your DML update statement
ELSE
null;--your DML insert statement
END;
END IF;
IF UPDATING THEN
null;--your DML statement for update the old registry and a DML for insert the new registry.
END IF;
END;
In this way, you can update the registry related to the old values and insert a new row with the new values.
I hope that this helps you to solve your problem.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/52746313",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Plotting spheres around given coordinates in 3D in Matlab I am working on model of an object sliding on some rough surface consisting of spheres with a small random variance in position. In the graphics I want the spheres to be of a given radius, however when using scatter3 this wont work, the sizes of the circles change when I zoom in or out. I could easily solve this in 2D by using "rectangle"-function instead but for 3D this doesn't work.
Is there a better function for plotting spheres around points?
I have read this https://se.mathworks.com/matlabcentral/answers/101738-how-do-i-specify-the-size-of-the-markers-created-by-the-scatter-plot-in-units-proportional-to-the-da. But it either doesn't work for scatter3 or I do it wrong.
Sizes change when zooming in.
fig = figure(1);
hold on
daspect([1,1,1]);
surface.xnum = 16;
surface.znum = 16;
surface.r = 1;
circlenumber = 0;
for n = 1:surface.xnum
for m = 1:surface.znum
circlenumber = circlenumber + 1;
surface.circlecentre(circlenumber,:) = [n + 0.1*surface.r*randn , 0, m + 0.1*surface.r*randn ];
plt.surface = scatter3(surface.circlecentre(circlenumber, 1),surface.circlecentre(circlenumber, 2),surface.circlecentre(circlenumber, 3), 850*surface.r,'filled','r','MarkerEdgeColor','k');
end
end
Relevant part of the code. Setting coordinates to center of the spheres and plotting spheres around them.
A: This was the solution i found by the hint from Ander Biguri. I used surf to plot spheres instead of scatter3.
fig = figure(1);
hold on
daspect([1,1,1]);
colormap summer
shading interp % removes the lines in surfplot
surface.xnum = 8;
surface.znum = 8;
surface.r = 0.75;
circlenumber = 0;
for m = 1:surface.xnum
for n = 1:surface.znum
circlenumber = circlenumber + 1;
surface.circlecentre(circlenumber,:) = [m + 0.1*surface.r*randn ,0 , n + 0.1*surface.r*randn ];
[x,y,z] = sphere; surf(x*surface.r+m*2*surface.r+0.1*surface.r*randn, y*surface.r, z*surface.r+n*2*surface.r+0.1*surface.r*randn,'Edgecolor','none');
end
end
| {
"language": "en",
"url": "https://stackoverflow.com/questions/48225185",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: WordPress submenu hover with gradient image background over the parent LI and children LI's (submenu UL) I have the next situation/menu: http://inturnets.com/test/
It is a WordPress generated menu structure.
Please hover your mouse over "Menu #1". When mouse is hovered, i need the Menu #1, Menu #1 - 1 and Menu #1 - 2 to look like http://inturnets.com/test/images/whatineed.jpg
It has a that background image with gradient effect on it. It should start from the top of the menu when hovered, from the top of Menu #1 and to end on the LI's of the submenu UL. When the bg image ends (no-repeat) should continue the colour from the last pixel of it's bottom. In our example for a better visual experience let's take the #ff0000 :)
Does anyone have any clue how to solve that?
For now I tried the next css code:
#menu-top-navigation ul:hover { background: url(images/bg-menutest.jpg) repeat-x center top; }
But as you can see, with this only the LI's are covered on hover. I mean the submenu UL. I think there we need a hover rule for the hovered LI, some rounded corners with radius and another hover rule for the submenu UL with a corner radius and to look with continuity from the top over the bottom, like it looks on the linked image.
A: try to specify background color with selector like this:
#menu-top-navigation > li:hover
This way, you should be able to specify one gradient for whole LI content (in your case UL and LI). Strongly reccomend to use CSS3 gradients.
If this wont help you might need to specify on gradient for
#menu-top-navigation > li:hover {gradient color of XXX to YYY}
and one for
#menu-top-navigation > li:hover > ul {gradient color of YYY to ZZZ}
Note: gradient spec is just an example, it is not the actual syntax. Just wanted to make easier to understand.
Let me know if you have any questions.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/5880176",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Firebird Trace SP's / Steps I need a simple and free program to monitor all transactions on a Firebird Server.
I'm creating a web API that needs to mimic a user creating a new order in a custom made program.
Since I haven't got access to the source code I guess my best chance to properly insert all the data is to use the existing stored procedures. I can see all the SP's on the Firebird server and the details but I haven't got a clue which ones to use and in what order.
So the plan would be to monitor the activities while creating an order.
Many thanks for the help!
A: Thank you Mark & Arioch for contributing.
After hours of failed experimenting with the included fbtrace.exe included in Firebird 2.5 installation i've decided to use "FB TraceManager" Trial version.
Found here: https://www.upscene.com/downloads/fbtm
| {
"language": "en",
"url": "https://stackoverflow.com/questions/59621957",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
} |
Q: How do if statements work? I am making a text based russian roulette game in Python, but I am not nearly finished, as one can see just by looking at my code:
#!/usr/bin/env python
print("The maximum number of bullets is 3")
bulletcounter = input("How many bullets do you want your gun to have?")
print(bulletcounter, "bullets")
paname = input("Enter Player 1's Name: ")
pbname = input("Enter Player 2's Name: ")
print(paname.capitalize(), "Vs.", pbname.capitalize())
if bulletcounter == 1:
bulletcount = 0
print(bulletcount)
bulletaloc = random.randint(1, 6)
while bulletaloc != bulletcount:
bulletcount += 1
For some reason, even if someone enters 1 into bulletcounter, it doesn't trigger the if statement: if bulletcounter == 1. How do I make it trigger the if statement?
A: Use raw_input for your paname and pbname variables. Be sure to import random at the top of your file. It would also be better to use int(raw_input("How many...")) for bulletcounter, too, I think, than input, since this can be used to evaluate any arbitrary python code.
Also, it would be worth checking to see which version of Python you are using, when you invoke it using the env command. If, at the command line, you run:
/usr/bin/env python -V
and are getting "Python 2.x.y" instead of Python 3, and you are expecting to be using Python 3, consider changing that first line to call your Python 3 interpreter instead. The recommendations noted above assume you are using Python 2.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/9576696",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: SQL Server : Copy row and replace first column first char and multipley other column from another table I would like to copy a row in a same table and change the copied row's first cell number (like 1 to 9) and multiply values of other cells with a value from another table.
Table1:
uniqueID ID2 ID3 Number Number
-------------------------------
199000 1 2 20 20
Table2:
MultiplyN ID2 ID3
-----------------
5 1 2
After insert and set and multiply
Table1:
uniqueID ID2 ID3 Number Number
-------------------------------
199000 1 2 20 20
999000 1 2 100 100
Here is my procedure only to copy and change first letter but it does nothing.
What I'm doing wrong ?
ALTER PROCEDURE [dbo].[tableInsertUpdate]
(@kulcs nvarchar(50),
@uzlev int,
@uzlho int,
@uzltip int,
@uzlnev char,
@belfarb int,
@exparb int,
@egyarb int,
@arbjova int,
@allvalt int,
@anyagkolt int,
@energkolt int,
@elabe int,
@kozvetitettszolg int,
@igbevettagjell int,
@igenybevettszolg int,
@berkoltsjar int,
@egyebszem int,
@egyebraf int,
@koltsterh int,
@ecs int,
@berlvhep int,
@berlvheszk int,
@mfee int,
@koltscostcent int,
@penzeredvh int,
@penzeredkulso int,
@arfegyenleg int,
@rendkered int,
@letszam int,
@bérelt_munkaerő int,
@bérelt_munkaerők int)
AS
UPDATE uzlag_2006_copy
SET kulcs = '9' + SUBSTRING (@kulcs, 1, len(kulcs) - 1)
WHERE kulcs = @kulcs
INSERT INTO uzlag_2006_copy (kulcs, uzlev, uzlho, uzltip, uzlnev, belfarb,
exparb, egyarb, arbjova, allvalt, anyagkolt,
energkolt, elabe, kozvetitettszolg,
igbevettagjell, igenybevettszolg,
berkoltsjar, egyebszem, egyebraf,
koltsterh, ecs, berlvhep, berlvheszk,
mfee, koltscostcent, penzeredvh,
penzeredkulso, arfegyenleg, rendkered,
letszam, bérelt_munkaerő, bérelt_munkaerők)
VALUES (@kulcs, @uzlev, @uzlho, @uzltip, @uzlnev, @belfarb, @exparb,
@egyarb, @arbjova, @allvalt, @anyagkolt, @energkolt, @elabe,
@kozvetitettszolg, @igbevettagjell, @igenybevettszolg,
@berkoltsjar, @egyebszem, @egyebraf, @koltsterh, @ecs,
@berlvhep, @berlvheszk, @mfee, @koltscostcent, @penzeredvh,
@penzeredkulso, @arfegyenleg, @rendkered, @letszam,
@bérelt_munkaerő, @bérelt_munkaerők)
A: I think you want something like this:
insert into table1 (uniqueID, ID2, ID3, Number1, Number2)
select stuff(uniqueID, 1, 1, '9')
t1.ID2, t1.ID3,
Number1 * t2.MultiplyBy, t1.Number2 * MultiplyBy
from table1 t1 join
table2 t2
on t1.id2 = t2.id2 and t1.id3 = t2.id3; -- Are both keys needed?
A: Ill made a solution:
temp table inserted from table1 and tabl2 with join converted first char and multiplied the numbers and insert back with new data to original table
| {
"language": "en",
"url": "https://stackoverflow.com/questions/42136065",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to select specific radio button in a group of similar radio buttons in Selenium Web Driver? I am trying to automate a booking process from an airline site.
In the second page of the booking process ('Select Flights'), there are multiple radio buttons which are very similar with other radio buttons available in the page. How can I select the radio button that I want to click?
I have already tried the xpath of the radio button but to no avail.
Here is the html code of the radio button:
Screenshot from booking.airasia.com
Please advise. Thank you
A: First element
Second Element
Well its true that you are getting similar elements for that given xpath but you also have to go through their siblings/parents etc for different scenarios.
Here is the xpath I tried that identified the individual elements that you were looking for, are depicted above.
//div[@class='iradio_square-green']/input[@id='trip_0_date_0_flight_0_fare_0']/following-sibling::ins
For others radio buttons you just have to change the flight number.
Hope this helps...
:)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/41800815",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to get extract image url of the url http://graph.facebook.com/{ANYUSERID}/picture? I want to save the the real image url with .jpg ,to do that i want to get the real image url but i have a url like this - http://graph.facebook.com/543525921/picture
the real image url of this url is
https://fbcdn-profile-a.akamaihd.net/hprofile-ak-snc4/371089_543525921_1936288375_q.jpg
How to display the real image URL always when i gave a url like "http://graph.facebook.com/anyuserid/picture" with php?
i tried alot but i failed..better some one if help me..thank you!
A: Just ran into the same issue here is the code I used to solve.
$url = 'http://graph.facebook.com/' . $userInfo['id'] . '/picture?type=large';
$headers = get_headers($url, 1); // make link request and wait for redirection
if(isset($headers['Location'])) {
$url = $headers['Location']; // this gets the new url
} else {
$url = false;
}
$targetPath = $_SERVER['DOCUMENT_ROOT'] . "/yourImagePath/");
$destFile = "yourFileName.jpg"
if($url){
if (copy($url, $targetPath.$destFile)) {
// file is now copied to your server do what ever you want here
}
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/8516312",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Subsets and Splits