text
stringlengths 15
59.8k
| meta
dict |
|---|---|
Q: find data type of the output column An Example:
sel date '2008-03-07'- date '2009-04-10'
(2008-03-07-2009-04-10)
1 -399
What would be the data type of the result here?
It's INTERVAL DAY (please correct if this is wrong) here in this case I know but, is there a function available to return the data type characteristics of the resultant column?
A: The mistery function is called TYPE :-)
select type(date '2008-03-07'- date '2009-04-10')
It's not INTERVAL DAY, it's an INTEGER.
You only get INTERVALS when you request them explicitly, but they're hardly used as the maximum number of digits is only 4:
select date '2008-03-07'- date '2009-04-10' MONTH(4)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/21346423",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Multiple polygon edit in matplotlib I am trying to make plot that it has two polygon patches over it. I want to use the example given in Matplotlib.org web page called PloygonInteractor. My code as follows;
import numpy as np
from matplotlib.lines import Line2D
from matplotlib.artist import Artist
import matplotlib.pyplot as plt
from matplotlib.patches import Polygon
def dist(x, y):
"""
Return the distance between two points.
"""
d = x - y
return np.sqrt(np.dot(d, d))
def dist_point_to_segment(p, s0, s1):
"""
Get the distance of a point to a segment.
*p*, *s0*, *s1* are *xy* sequences
This algorithm from
http://geomalgorithms.com/a02-_lines.html
"""
v = s1 - s0
w = p - s0
c1 = np.dot(w, v)
if c1 <= 0:
return dist(p, s0)
c2 = np.dot(v, v)
if c2 <= c1:
return dist(p, s1)
b = c1 / c2
pb = s0 + b * v
return dist(p, pb)
class PolygonInteractor:
"""
A polygon editor.
Key-bindings
't' toggle vertex markers on and off. When vertex markers are on,
you can move them, delete them
'd' delete the vertex under point
'i' insert a vertex at point. You must be within epsilon of the
line connecting two existing vertices
"""
showverts = True
epsilon = 5 # max pixel distance to count as a vertex hit
def __init__(self, ax, poly):
if poly.figure is None:
raise RuntimeError('You must first add the polygon to a figure '
'or canvas before defining the interactor')
self.ax = ax
canvas = poly.figure.canvas
self.poly = poly
x, y = zip(*self.poly.xy)
self.line = Line2D(x, y,
marker='o', markerfacecolor='r',
animated=True)
self.ax.add_line(self.line)
self.cid = self.poly.add_callback(self.poly_changed)
self._ind = None # the active vert
canvas.mpl_connect('draw_event', self.on_draw)
canvas.mpl_connect('button_press_event', self.on_button_press)
canvas.mpl_connect('key_press_event', self.on_key_press)
canvas.mpl_connect('button_release_event', self.on_button_release)
canvas.mpl_connect('motion_notify_event', self.on_mouse_move)
self.canvas = canvas
def on_draw(self, event):
self.background = self.canvas.copy_from_bbox(self.ax.bbox)
self.ax.draw_artist(self.poly)
self.ax.draw_artist(self.line)
# do not need to blit here, this will fire before the screen is
# updated
def poly_changed(self, poly):
"""This method is called whenever the pathpatch object is called."""
# only copy the artist props to the line (except visibility)
vis = self.line.get_visible()
Artist.update_from(self.line, poly)
self.line.set_visible(vis) # don't use the poly visibility state
def get_ind_under_point(self, event):
"""
Return the index of the point closest to the event position or *None*
if no point is within ``self.epsilon`` to the event position.
"""
# display coords
xy = np.asarray(self.poly.xy)
xyt = self.poly.get_transform().transform(xy)
xt, yt = xyt[:, 0], xyt[:, 1]
d = np.hypot(xt - event.x, yt - event.y)
indseq, = np.nonzero(d == d.min())
ind = indseq[0]
if d[ind] >= self.epsilon:
ind = None
return ind
def on_button_press(self, event):
"""Callback for mouse button presses."""
if not self.showverts:
return
if event.inaxes is None:
return
if event.button != 1:
return
self._ind = self.get_ind_under_point(event)
def on_button_release(self, event):
"""Callback for mouse button releases."""
if not self.showverts:
return
if event.button != 1:
return
self._ind = None
def on_key_press(self, event):
"""Callback for key presses."""
if not event.inaxes:
return
if event.key == 't':
self.showverts = not self.showverts
self.line.set_visible(self.showverts)
if not self.showverts:
self._ind = None
elif event.key == 'd':
ind = self.get_ind_under_point(event)
if ind is not None:
self.poly.xy = np.delete(self.poly.xy,
ind, axis=0)
self.line.set_data(zip(*self.poly.xy))
elif event.key == 'i':
xys = self.poly.get_transform().transform(self.poly.xy)
p = event.x, event.y # display coords
for i in range(len(xys) - 1):
s0 = xys[i]
s1 = xys[i + 1]
d = dist_point_to_segment(p, s0, s1)
if d <= self.epsilon:
self.poly.xy = np.insert(
self.poly.xy, i+1,
[event.xdata, event.ydata],
axis=0)
self.line.set_data(zip(*self.poly.xy))
break
if self.line.stale:
self.canvas.draw_idle()
def on_mouse_move(self, event):
"""Callback for mouse movements."""
if not self.showverts:
return
if self._ind is None:
return
if event.inaxes is None:
return
if event.button != 1:
return
x, y = event.xdata, event.ydata
self.poly.xy[self._ind] = x, y
if self._ind == 0:
self.poly.xy[-1] = x, y
elif self._ind == len(self.poly.xy) - 1:
self.poly.xy[0] = x, y
self.line.set_data(zip(*self.poly.xy))
self.canvas.restore_region(self.background)
self.ax.draw_artist(self.poly)
self.ax.draw_artist(self.line)
self.canvas.blit(self.ax.bbox)
x1 = np.array([-1.5, -1.5, -1.0, -1.0])
y1 = np.array([-1.0, -1.5, -1.5, -1.0])
poly1 = Polygon(np.column_stack([x1, y1]), color='gray', fill=False, animated=True)
x2 = np.array([-1.5, -1.5, -1.0, -1.0])
y2 = np.array([ 0.0, 0.5, 0.5, 0.0])
poly2 = Polygon(np.column_stack([x2, y2]), color='b', fill=False, animated=True)
fig, ax = plt.subplots()
ax.add_patch(poly1)
ax.add_patch(poly2)
p1 = PolygonInteractor(ax, poly1)
p2 = PolygonInteractor(ax, poly2)
ax.set_xlim((-2, 2))
ax.set_ylim((-2, 2))
plt.show()
and this creates a plot like this:
My problem is that when trying to adjust polygon 2 (bottom), polygon 1 (upper) disappears. What should I do for this?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/67005624",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: I need to write a query which repeats the rows by incrementing the values I have a table with three columns say ID with identity, name and location and for this columns say I have values as
(1,'RAM','CA'),
(2,'SAM','IA'),
(3,'PAM','MI')
etc....
Now want to get 100 rows, say after 3rd row, the 4th row should again start with same name and same location but adding one value to it, say 4th row will be values
(4,'RAM1','CA1'), similarly 5th row will be (5,'SAM1','IA1') and 6th row will be (6,'PAM1','MI1'). Again for 7th row it should give values as (7,'RAM2','CA2') and so on. So it should continue like this till 100th row, for that I need to write the code, I could not able to figure it out, can you please help me in this.
Thanks,
Aparanjit
A: Try this:
Fiddle demo
--Your table
create table t (id int identity(1,1), col1 varchar(10),
col2 varchar(10))
--Insert query
insert into t
select c1 + case when number = 1 then '' else convert(varchar(10),number-1) end col1,
c2 + case when number = 1 then '' else convert(varchar(10),number-1) end col2
from master..spt_values cross join
(values ('RAM','CA'),('SAM','IA'),('PAM','MI')) AS temp (c1,c2)
where type='p' and number between 1 and 100
--Results
| ID | COL1 | COL2 |
------|-------|------|--
| 1 | RAM | CA |
| 2 | SAM | IA |
| 3 | PAM | MI |
| 4 | RAM1 | CA1 |
| 5 | SAM1 | IA1 |
| 6 | PAM1 | MI1 |
| 7 | RAM2 | CA2 |
| 8 | SAM2 | IA2 |
| 9 | PAM2 | MI2 |
| 10 | RAM3 | CA3 |
| 11 | SAM3 | IA3 |
| 12 | PAM3 | MI3 |
...
A: Using a recursive CTE You could try something like
DECLARE @Table TABLE(
ID INT IDENTITY(1,1),
[name] VARCHAR(20),
location varchar(20)
)
INSERT INTO @Table VALUES ('RAM','CA'), ('SAM','IA'), ('PAM','MI')
DECLARE @NumberOfRows INT = 100
;WITH RowIDs AS (
SELECT 1 RowID
UNION ALL
SELECT RowID + 1
FROM RowIDs
WHERE RowID + 1 <= @NumberOfRows
)
, JoinIDs AS (
SELECT RowID,
((RowID - 1) % 3 + 1) JoinID
FROM RowIDs
)
SELECT j.RowID,
t.name,
t.location
FROM JoinIDs j INNER JOIN
@Table t ON j.JoinID = t.ID
OPTION (MAXRECURSION 0)
SQL Fiddle DEMO
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/19153286",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: PhpStorm understanding of magic methods Our classes don't have explictic getPropertyName() and setPropertyName() methods. Instead we're using trait, which implements combination of magic __get(), __set() and __call() methods, so, we can have following as result:
class Device {
use ModelAttributes;
/**
* @var \string
*/
protected $title;
/**
* @var \string
*/
protected $subtitle;
}
$device = new Device();
$device->setTitle('PC');
$device->getTitle();
But the problem is, that now PhpStorm can't recognize and highlights these methods.
I know, that I can add @method string getTitle() into class phpDoc, but this will mean, taht I again need to add all get-ers and set-ers, but in form of phpDoc commetns, and I want to avoid this.
It would be really great, if I could do something like:
/**
* @var \string
* @get
* @set
*/
protected $title;
Does someone have experience with such situation?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/19047758",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Can't set properly my Dialog Window size and placement target I've built a dialog window that i plan to use in my whole application instead of using a message box. Whenever i need to use it, i would call it in the code behind of my Window i'm currently working with this syntax:
public void ShowDialogWindow(object sender, DialogEventArgs e)
{
DialogWindow dialog = new DialogWindow(e.MessageToShow, DialogType.Error, ButtonsType.OkOnly, this.ActualWidth, this.ActualHeight, this);
dialog.ShowDialog();
}
this is the constructor of my Dialog Window
public DialogWindow(string messageToDisplay, DialogType dialog, ButtonsType buttons, double width, double height, object Owner)
{
InitializeComponent();
this.DataContext = this;
this.Owner = Owner as Window;
AWidth = width;
AHeight = height;
-----
}
and this is the opening Window tag in the xaml
<Window x:Class="DialogWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
---
mc:Ignorable="d" WindowStyle="None"
WindowStartupLocation="CenterOwner"
AllowsTransparency="True"
Width="{Binding AWidth}" Height="{Binding AHeight}"
MinHeight="720" MinWidth="1080">
Now my problem is. When i call this dialog when the owner is Minimized (having set MinWidth = 1080 and MinHeght = 720) the dialog "kinda" fits (ActualWidth and Actual Height of both Window and DialogWindow are the same, but visually the DialogWindow seems a little bit bigger than the Owner)
But when i go full screen it happens this:
Not only the ActualHeight is different to the property AHeight (which is set correctly to the ActualHeight of the Owner), but also is not centered on the Owner window at all, but overflow on my second screen. What cause this, and how can i solve it?
A: So i'm going to post what it solved my problem, but i have absolutely no idea why that happened, so if anyone has a better answer i will check that as accepted.
To solve my problems i removed the binding for width and height and simply added in the constructor of the DialogWindow
this.Width = OwnerActualWidth;
this.Height = OwnerActualHeight;
since i am passing those parameter in input
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/54256342",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: I need sql query for getting the Required format i am having table Category with the columns like
id(AutoIncrement),Parent_id,Level,Name
initially for level 1 datas has Parent_id is 0. autoincrement id will be Parent_id for next levels .my table table table datas will bw like this
id Parent_id Level Name
1 0 1 Indian
2 0 1 International
3 0 1 Nri
4 1 2 BC
5 2 2 Christian
6 2 2 Muslim
7 4 3 MBC-1
8 7 4 OBC-2
9 1 2 FC
i want to show records in this format (its like a tree view)
id Parent_id Level Name
1 0 1 Indian
4 1 2 BC
7 4 3 MBC-1
8 7 4 OBC-2
9 1 2 FC
5 2 2 Christian
6 2 2 Muslim
2 0 1 International
3 0 1 Nri
4 1 2 BC
Can any one should help me to get this arrangement of datas using sql Query?
A: If it does not have a set number of branches you likely want to loop over a query in your app or write an SP to obtain all nodes. Some good reading here:
http://mikehillyer.com/articles/managing-hierarchical-data-in-mysql/
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/9601253",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: omitempty does not work in encoding/xml when using pointers? I am consuming a REST API that returns XML and am trying to Unmarshal the XML and am having issues that appear that the omitempty is not working. Here is an example of a working XML file:
<?xml version='1.0' encoding='UTF-8'?>
<customer uri="/api/customers/339/" id="339">
<name>
<first>Firstname</first>
<last>Lastname</last>
</name>
<email>myemail@example.com</email>
<billing>
<address>
<address1>123 Main St.</address123>
<address2></address2>
<city>Nowhere</city>
<state>IA</state>
<country>USA</country>
<zip>12345</zip>
</address>
</billing>
</customer>
Here is an example of a "bad" record
<?xml version='1.0' encoding='UTF-8'?>
<customer uri="/api/customers/6848/" id="6848">
<name>
<first>Firstname</first>
<last>Lastname</last>
</name>
<email/>
<billing/>
</customer>
Now I have my structs set up like the following:
type Customer struct {
ID int `xml:"id,attr"`
Name *Name `xml:"name,omitempty"`
Billing *Billing `xml:"billing,omitempty"`
}
type Billing struct {
Address *Address `xml:"address,omitempty"`
}
type Address struct {
address_1 string `xml:",omitempty"`
address_2 string `xml:",omitempty"`
city string `xml:",omitempty"`
postal string `xml:",omitempty"`
country string `xml:",omitempty"`
}
type Name struct {
first, last string
}
Reading through all of the records it works when the XML follows the pattern of the first example <billing></billing> but when it hits a record that has something like <billing/> it throws the following error: panic: runtime error: invalid memory address or nil pointer dereference
Can someone help me figure out what's going on and how to resolve it?
A: You're probably misunderstanding what ,omitempty means. It takes effect when marshalling data, only. If you unmarshal <billing/> onto a pointer field with ,omitempty, it will still initialize the field. Then, since the XML element is empty, the fields of Billing itself won't be set. In practice, if you assume that customer.Billing != nil means customer.Billing.Address != nil, you'll get the observed panic.
Note: http://play.golang.org/p/dClkfOVLXh
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/18394911",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Use @CachePut in springmvc project,but get the key and the value two separate data in redis In the spring MVC project, I'm try to cache data with @CachePut, but in redis, there are two separate data for key and value:
At the same time, I did the same thing with the springboot project and got the normal results:
The configuration in springmvc project:
<bean id="poolConfig" class="redis.clients.jedis.JedisPoolConfig">
<property name="maxTotal" value="${spring.redis.pool.maxTotal}"></property>
<property name="maxIdle" value="${spring.redis.pool.maxIdle}"></property>
<property name="minIdle" value="${spring.redis.pool.minIdle}"></property>
<property name="maxWaitMillis" value="${spring.redis.pool.maxWait}"></property>
</bean>
<bean id="connectionFactory"
class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory">
<property name="poolConfig" ref="poolConfig"></property>
<property name="hostName" value="${spring.redis.host}"></property>
<property name="port" value="${spring.redis.port}"></property>
<property name="password" value="${spring.redis.password}"></property>
<property name="database" value="${spring.redis.database}"></property>
<property name="timeout" value="${spring.redis.timeout}"></property>
</bean>
<bean id="redisCacheManager" class="org.springframework.data.redis.cache.RedisCacheManager">
<constructor-arg name="redisOperations" ref="redisTemplate" />
</bean>
<bean class="redis.clients.jedis.JedisPool">
<constructor-arg ref="poolConfig"/>
<constructor-arg value="${spring.redis.host}"/>
<constructor-arg type="int" value="${spring.redis.port}"/>
<constructor-arg type="int" value="${spring.redis.timeout}"/>
<constructor-arg type="java.lang.String" value="${spring.redis.password}"/>
<constructor-arg type="int" value="${spring.redis.database}"/>
</bean>
and
@Bean
public RedisTemplate<String , Object> redisTemplate(RedisConnectionFactory connectionFactory) {
RedisTemplate<String, Object> template = new RedisTemplate<>();
template.setConnectionFactory(connectionFactory);
Jackson2JsonRedisSerializer serializer = new Jackson2JsonRedisSerializer(Object.class);
ObjectMapper mapper = new ObjectMapper();
JavaTimeModule javaTimeModule = new JavaTimeModule();
javaTimeModule.addSerializer(LocalDate.class, new LocalDateSerializer(properties.dateFormatter()));
javaTimeModule.addSerializer(LocalTime.class, new LocalTimeSerializer(properties.timeFormatter()));
javaTimeModule.addSerializer(YearMonth.class, new YearMonthSerializer(properties.yearMonthFormatter()));
javaTimeModule.addSerializer(MonthDay.class, new MonthDaySerializer(properties.monthDayFormatter()));
javaTimeModule.addSerializer(LocalDateTime.class, new LocalDateTimeSerializer(properties.dateTimeFormatter()));
javaTimeModule.addDeserializer(LocalDate.class, new LocalDateDeserializer(properties.dateFormatter()));
javaTimeModule.addDeserializer(LocalTime.class, new LocalTimeDeserializer(properties.timeFormatter()));
javaTimeModule.addDeserializer(YearMonth.class, new YearMonthDeserializer(properties.yearMonthFormatter()));
javaTimeModule.addDeserializer(MonthDay.class, new MonthDayDeserializer(properties.monthDayFormatter()));
javaTimeModule.addDeserializer(LocalDateTime.class, new LocalDateTimeDeserializer(properties.dateTimeFormatter()));
mapper.registerModule(javaTimeModule);
mapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
mapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
serializer.setObjectMapper(mapper);
template.setKeySerializer(new StringRedisSerializer());
template.setValueSerializer(serializer);
template.afterPropertiesSet();
return template;
}
Is there a problem with the configuration ?
A: In RedisCacheManager ,property usePrefix default value is false,so we should set usePrefix=true in JavaConfig:
@Bean
public RedisCacheManager cacheManager(RedisTemplate<String, Object> redisTemplate) {
RedisCacheManager cacheManager = new RedisCacheManager(redisTemplate);
cacheManager.setUsePrefix(true);
return cacheManager;
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/45940780",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Django Allauth saving profile information with signup form I am new in Django, I am using allauth app to create a user registration. There are some extra field I wish to have in my signup form. Not only (username, first_name, last_name) I wish to also include info to the registration form.
When I submit the registration form only the first_name and the last_name are saved in database, info is not saved. I guess it should be saved in Profile Model, but its not there.
class Profile(models.Model):
user = models.OneToOneField(User)
info = models.CharField(max_length=128)
class CustomSignUpForm(Signup Form):
first_name = forms.CharField(max_length=30)
last_name = forms.CharField(max_length=30)
info = forms.CharField(max_length=50)
def signup(self, request, user):
user.first_name = self.cleaned_data['first_name']
user.last_name = self.cleaned_data['last_name']
user.save()
user.profile.info = self.cleaned_data['info']
user.profile.save()
ACCOUNT_FORM = 'signup' 'myapp.forms.CustomSignupForm'
A: Are you sure the Profile object exists for that user and you are not getting RelatedObjectDoesNotExist error in logs? If yes then you have to create a Profile object, in the above signup form.
Profile.objects.update_or_create(user=user, defaults={"info":self.cleaned_data['info']})
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/60419392",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Igraph Identifying nodes based on centrality scores I'm running the igraph package for some network analysis on this example dataset
structure(list(ï..Column1 = c(NA, NA, NA, NA), Column2 = c(NA,
NA, NA, NA), Column3 = c(NA, NA, NA, NA), Column4 = c(NA, NA,
NA, NA), Column5 = structure(c(2L, 1L, 4L, 3L), .Label = c("Eric ",
"Jim", "Matt", "Tim"), class = "factor"), Column6 = c(NA, NA,
NA, NA), Column7 = structure(c(1L, 3L, 2L, 3L), .Label = c("Eric",
"Erica", "Mary "), class = "factor"), Column8 = structure(c(3L,
2L, 1L, 3L), .Label = c("Beth", "Loranda", "Matt"), class = "factor"),
Column9 = structure(c(2L, 3L, 1L, 3L), .Label = c("Courtney ",
"Heather ", "Patrick"), class = "factor"), Column10 = structure(4:1, .Label = c("Beth",
"Heather", "John", "Loranda "), class = "factor"), Column11 = c(NA,
NA, NA, NA), Column12 = c(NA, NA, NA, NA), Column13 = c(NA,
NA, NA, NA), Column14 = c(NA, NA, NA, NA), Column15 = c(NA,
NA, NA, NA)), class = "data.frame", row.names = c(NA, -4L
))
Here is the edgelist for anyone who wants to skip the step of finding that
structure(c("Jim", "Eric ", "Tim", "Matt", "Jim", "Eric ", "Tim",
"Matt", "Jim", "Eric ", "Tim", "Matt", "Jim", "Eric ", "Tim",
"Matt", "Eric", "Mary ", "Erica", "Mary ", "Matt", "Loranda",
"Beth", "Matt", "Heather ", "Patrick", "Courtney ", "Patrick",
"Loranda ", "John", "Heather", "Beth"), .Dim = c(16L, 2L), .Dimnames = list(
NULL, c("Column5", "value")))
I'm trying to calculate centrality for each of the nodes in the network using this code (mat is my edgelist matrix)
g1=graph_from_edgelist(mat)
degree.cent <- centr_degree(g1, mode = "all")
degree.cent
My output is something like this
> degree.cent
$`res`
[1] 4 1 4 2 4 1 6 1 2 1 2 1 1 1 1
$centralization
[1] 0.1479592
$theoretical_max
[1] 392
I know 'degree$res` is my centrality score measures, but what isn't clear to me is which nodes are actually receiving that score. I looked up a tutorial here, but all it says is the first score is "node 1". There's no indication of what node 1 is or an easy way to identify that
A: Firstly, you are getting incorrect results as some of the names contain spaces (Eric, Marry, Heather, ...). So, let
mat <- gsub(" ", "", mat)
g1 <- graph_from_edgelist(mat)
degree.cent <- centr_degree(g1, mode = "all")
Now we may extract the corresponding names of vertices and combine them with your result:
setNames(degree.cent$res, V(g1)$name)
# Jim Eric Mary Tim Erica Matt Loranda Beth Heather
# 4 5 2 4 1 6 2 2 2
# Patrick Courtney John
# 2 1 1
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/54067326",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: VBA - String changes when SaveAs My code creates a new Excel file, and gathers data into it. Then it should save it into a specified folder (on the hard drive), with a specified name.
The path - with the file name at the end - is built up by the code and stored in a string.
Right before the SaveAs command, I use Debug.Print to check the string, and it's a 100% good.
Still the SaveAs line runs to this error:
"Run-time error '1004':
Microsoft Excel cannot access the file
[here comes the entire path]
There are several possible reasons:
*
*The file name or path does not exist.
*The file is being used by another program.
*The workbook you are trying to save has the same name as a"
(The rest is not visible because of the size of the window, but whatever.)
The path in the error message is ok, but instead of the file name there is a 6-character code made of (seemingly) random numbers and letters. And it changes with every run.
How does the filename string get exchanged to that? Can it have anything to do with cloud-based stuff and/or sharepoint and/or syncronization (of which I'm not expert)?
Are there any solutions?
Thanks
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/74158807",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Camel route xpath filter i m stuck with xpath filter in camel route, and i don t find solution...
here is my xml message
<env:Envelope xmlns:env="http://www.w3.org/2003/05/soap-envelope"
xmlns:ct="http://com/fr/test">
<env:Header>
<receptionTime xmlns="http://com/fr/test">2016-02-12T14:40:56+0100
</receptionTime>
<correlationId xmlns="http://com/fr/test">944689bc-9605-4292-929a-3b2e8a5eddd7
</correlationId>
<equipmentType xmlns="http://com/fr/test">WCA</equipmentType>
<messageType xmlns="http://com/fr/test">Reservation</messageType>
</env:Header>
<env:Body>
<content xmlns="http://com/fr/test"></content>
</env:Body>
and my route lokk like this :
from("activemq-ext-in:queue:" + queueName)
.id("amq-transfert-downward-route")
.filter().xpath("/env:Envelope/env:Header/equipmentType/text()='WCA'")
//.when(body().contains("WCA"))
.to("activemq-ext-out:topic:" + topicName);
and my message never arrived in my out topic :( if i uncomment the when clause, and comment the filter, my message is correctly send, but i want to use filter
can someone help me how to find the good xpath expression?
possibly i can use .choice().when(xpath...).to(...)?
i just need a correct solution :)
thanks a lot!
A: Looks like a namespace prefix issue. You're qualifying Envelope with "env:" which is good as long as that prefix is mapped to the right namespace. However, you are missing a suitable qualifier on equipmentTest which is in a different namespace.
See the Camel docs on how to configure a namespaces.
Namespaces ns = new Namespaces("ct", "http://com/fr/test")
.add("env", "http://www.w3.org/2003/05/soap-envelope");
from("activemq-ext-in:queue:" + queueName)
.id("amq-transfert-downward-route")
.filter(
ns.xpath("/env:Envelope/env:Header/ct:equipmentType/text()='WCA'")
).to("activemq-ext-out:topic:" + topicName);
Updated: changed to use the OP example instead of the one from the Camel docs. I haven't tested this but it looks about right.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/41398116",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: iOS Storyboard - Navigation Controller Not Working I am having trouble with a Navigation Controller in my iOS project which uses Storyboards.
The main part of the project is a UITabBar. When the app loads for the very first time the screen RegisterViewController is presented:
When the user taps on the "Register" button a HTTP POST request is made, then upon receiving the response (JSON object) the screen QuestionnaireViewController is presented using:
UIStoryboard *mainStoryboard = [UIStoryboard storyboardWithName:@"MainStoryboard" bundle:nil];
QuestionnaireViewController *questionnaireViewController = [mainStoryboard instantiateViewControllerWithIdentifier:@"QuestionnaireView"];
[questionnaireViewController setModalTransitionStyle:UIModalTransitionStyleCrossDissolve];
[questionnaireViewController setQuestionsAndAnswers:_questionsAndAnswers];
[self presentViewController:questionnaireViewController animated:NO completion:nil];
When the user taps on a cell in QuestionnaireViewController a message is sent to prepareForSegue:sender:
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
UINavigationController *navigationController = segue.destinationViewController;
AnswersViewController *answersViewController = [[navigationController viewControllers] objectAtIndex:0];
NSIndexPath *indexPath = [self.tableView indexPathForCell:sender];
NSArray *answers = [[_questionsAndAnswers objectAtIndex:indexPath.row] objectForKey:@"answers"];
[answersViewController setAnswers:answers];
}
At this point the app crashes with an error of:
-[AnswersViewController viewControllers]: unrecognized selector sent to instance.
Below is a more comprehensive overview of my storyboard, which may help in understanding where I have gone wrong:
I am stumped as to how to fix this, and am hoping that someone out there is able to help.
Thanks,
Nick
A: First, you should present the navigation controller, not its root view controller. Then when you want to populate the root view controller with some data, you need to reference it as the navigation controller's root view controller:
UINavigationcontroller *questionnaireNavController = [self.storyboard instantiateViewControllerWithIdentifier:@"QuestionnaireNavigationController"];
[questionnaireNavController setModalTransitionStyle:UIModalTransitionStyleCrossDissolve];
QuestionnaireViewController *qvc = (QuestionnaireViewController *)[questionnaireNavController topViewController];
[qvc setQuestionsAndAnswers:_questionsAndAnswers];
[self presentViewController:questionnaireNavController animated:NO completion:nil];
Second, in prepareForSegue:sender: you don't need to reference a navigation controller at all:
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
AnswersViewController *answersVC = segue.destinationViewController;
NSIndexPath *indexPath = [self.tableView indexPathForCell:sender];
NSArray *answers = [[_questionsAndAnswers objectAtIndex:indexPath.row] objectForKey:@"answers"];
[answersVC setAnswers:answers];
}
A: You are not getting the navigationController properly. Instead of segue.destinationViewController, use self.navigationController
By calling segue.destinationViewController, you are getting a pointer to the VC you are segueing to (AnswersViewController) which doesn't understand the message viewControllers because it is not a UINavigationController.
Also the AnswersViewController is objectAtIndex:1 I believe, check this though.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/17932778",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Method with @Receiver AndroidAnnotation in Service (extends FirebaseMessagingService) not called My service shows notification with cancel and accept action. And I want to use @Receiver (androidannotation libs) inside my service to handle cancel action. Here is my code:
private PendingIntent setupCancelIntent(String id, int notificationId) {
//set up pending intent for cancel action
Intent dismissIntent = new Intent(CANCEL_ACTION);
dismissIntent.putExtra(Constant.ID, id);
dismissIntent.putExtra(Constant.NOTIFICATION_ID, notificationId);
return PendingIntent.getBroadcast(this, notificationId, dismissIntent,
PendingIntent.FLAG_UPDATE_CURRENT);
}
@Receiver(actions = CANCEL_ACTION)
public void actionCancel(@Receiver.Extra(Constant.ID) String id,
@Receiver.Extra(Constant.NOTIFICATION_ID) int notificationId, Context context) {
Toast.makeText(context, "Cancel action " + id, Toast.LENGTH_SHORT).show();
if (notificationId != -1) {
NotificationManager manager =
(NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
manager.cancel(notificationId);
}
}
My notification is showed, but when press cancel button, the actionCancel method is not called. What am I missed!
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/40629775",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: array_intersect Inside multidimensional-array i have an multidimensioanl array which can increase based on user input.i want to do array_intersect inside the array to get the common values between the key.
like example
Array ( [php] => Array ( [0] => 36 [1] => 51 [2] => 116 [3] => 171 [4] => 215 [5] => 219 [6] => 229 [7] => 247 [8] => 316 ) [java] => Array ( [0] => 14 [1] => 16 [2] => 19 [3] => 24 [4] => 25 [5] => 26 [6] => 29 [7] => 31 [8] => 33 [9] => 34 [10] => 35 [11] => 36 [12] => 37 [13] => 40 [14] => 45 [15] => 49 [16] => 51 ) )
expected output should be like (36,51)
and this is i am able to get it
via this,
$intersected_array = call_user_func_array('array_intersect', $array);
but if my array had a third key also which doesnot had a common value in all three of them
like
Array ( [php] => Array ( [0] => 36 [1] => 51 [2] => 116 [3] => 171 [4] => 215 [5] => 219 [6] => 229 [7] => 247 [8] => 316 ) [java] => Array ( [0] => 14 [1] => 16 [2] => 19 [3] => 24 [4] => 25 [5] => 26 [6] => 29 [7] => 31 [8] => 33 [9] => 34 [10] => 35 [11] => 36 [12] => 37 [13] => 40 [14] => 45 [15] => 49 [16] => 51 ) [ajax] => Array ( [0] => 91 [1] => 110 [2] => 113 [3] => 172 ) )
then it is throwing me output as the result of the key having max values. in this case it will return me all the values of java key.
but my expected output is 0. please help.
A: I copyed you example and for me it works:
<?php
$array = array(
'php' => array(
36,
51,
116,
171,
215,
219,
229,
247,
316,
),
'java' => array(
14,
16,
19,
24,
25,
26,
29,
31,
33,
34,
35,
36,
37,
40,
45,
49,
51,
),
'ajax' => array(
91,
110,
113,
172,
),
);
$intersected_array = call_user_func_array('array_intersect',$array);
print_r($intersected_array);
// RESULT: "Array ( ) "
Please copy exactly this code and tell me your output.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/14291340",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Angular JS: ng-repeat is not updated inside ng-view When I update the data in the variable $scope.userMovies, ng-repeat does not update if inside a ng-view. Outside ng-view it gets updated correctly.
What am I missing that ng-repeat does not work as I expect?
UPDATE:
As requested I moved the code to Plunker to better undestand my problem:
Plunker Code Example
UPDATE:
Solved saving the variable userMovies in the rootScope.
A: ng-view creates its own scope. What is likely happening is that you are creating $scope property userMovies on this ng-view child scope, which your MovieboxCtrl scope can not see/access. As @darkporter alluded to in a comment, your MovieboxCtrl should create an empty userMovies array. Then when the MovieCtrl sets userMovies, it will update the existing object reference, rather than create a new property.
Here is a plunker that stores the data in the service, rather than in a controller.
angular.module('moviebox.services', [])
.factory('movieboxApi', function() {
var model = { movies: [] };
model.getMoviesByTitle = function(query) {
angular.copy([{'title': 'foo'},{'title': 'foo1'},
{'title': 'foo2'},{'title': 'foo3'},
{'title': 'foo4'}], model.movies);
};
return model;
});
app.controller('MainCtrl', function($scope, movieboxApi) {
$scope.getMoviesByTitle = function() {
movieboxApi.getMoviesByTitle($scope.query);
};
$scope.userMovies = movieboxApi.movies;
});
app.controller('MovieboxCtrl', function ($scope, movieboxApi) {
$scope.userMovies = movieboxApi.movies;
});
HTML change:
<body ng-controller="MainCtrl">
angular.copy() is used because the controllers have a reference to the model.movies array that the service initially created. We want to modify that array, not assign a new one.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/16196611",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Adaptive parent relative to children's attributes in a recursive array I'm trying to make a simple tree structure where every task has a certain percentage of completion and its parent has to inherit average completion of its direct children, as seen conceptually on the picture below. (0s are percentages of completion, for example subtask2 could be 100% and subtask2 0%, which would give task1 50% completion and therefore stackoverflow would have 25%, given task2 is at 0)
The issue I'm having is that I need to start, apparently, from the deepest children, but I can't seem to figure out how to implement such reversal traversal from leafs to root.
I have tried with normal recursive as well as double for loop and both only achieve first level calculations (in the picture example task1 is calculated, but stackoverflow will remain 0).
Note: Only leafs can actually have completion percentage, since every other element, which is not a leaf, inherits percentage from its children. (how paradoxical)
If any of you have any ideas on how to implement such an algorithm, be it conceptually or actual code, I would very much appreciate any input.
Below is structure of this array (only kept relevant information):
[0] => Array
(
[title] => stackoverflow
[completion] => 0
[children] => Array
(
[0] => Array
(
[title] => task2
[completion] => 0
)
[1] => Array
(
[title] => task1
[completion] => 0
[children] => Array
(
[0] => Array
(
[title] => subtask2
[completion] => 100
)
[1] => Array
(
[title] => subtask1
[completion] => 0
)
)
)
)
)
I seem to be having a similar issue than the issue in this thread: Percentages and trees however, I need my task to have actual percentages, not only completed/non-completed. All math is completely linear, meaning that parent's percentage = (addition of all percentages of children) / (number of children)
Also var_export:
array (
0 =>
array (
'uuid' => '157ed2b2-0d0c-4f0c-b1d2-7126255f4023',
'title' => 'stackoverflow',
'completed' => '0',
'parent' => NULL,
'children' =>
array (
0 =>
array (
'uuid' => '72ce49a6-76e5-495e-a3f8-0f13d955a3b5',
'title' => 'task2',
'completed' => '0',
'parent' => '157ed2b2-0d0c-4f0c-b1d2-7126255f4023',
),
1 =>
array (
'uuid' => '4975d08d-55f0-4cd8-9de5-2d056111ec2d',
'title' => 'task1',
'completed' => '0',
'parent' => '157ed2b2-0d0c-4f0c-b1d2-7126255f4023',
'children' =>
array (
0 =>
array (
'uuid' => 'ac5e9d37-8f14-4169-bcf2-e7b333c5faea',
'title' => 'subtask2',
'completed' => '0',
'parent' => '4975d08d-55f0-4cd8-9de5-2d056111ec2d',
),
1 =>
array (
'uuid' => 'f74b801f-c9f1-40df-b491-b0a274ffd301',
'title' => 'subtask1',
'completed' => '0',
'parent' => '4975d08d-55f0-4cd8-9de5-2d056111ec2d',
),
),
),
),
),
)
A: Here is a recursive function that passes the parent by reference until it finds a leaf and updates totals working backward.
function completionTree(&$elem, &$parent=NULL) {
// Handle arrays that are used only as a container... if we have children but no uuid, simply descend.
if (is_array($elem) && !isset($elem['uuid'])) {
foreach($elem AS &$child) {
completionTree($child, $elem);
}
}
// This array has children. Iterate recursively for each child.
if (!empty($elem['children'])) {
foreach ($elem['children'] AS &$child) {
completionTree($child, $elem);
}
}
// After recursion to handle children, pass completion percentages up to parent object
// If this is the top level, nothing needs to be done (but suppress that error)
if (@$parent['completed'] !== NULL) {
// Completion must be multiplied by the fraction of children it represents so we always add up to 100. Since values are coming in as strings, cast as float to be safe.
$parent['completed'] = floatval($parent['completed']) + (floatval($elem['completed']) * (1/count($parent['children'])));
}
}
// Data set defined statically for demonstration purposes
$tree = array(array (
'uuid' => '157ed2b2-0d0c-4f0c-b1d2-7126255f4023',
'title' => 'stackoverflow',
'completed' => '0',
'parent' => NULL,
'children' =>
array (
0 =>
array (
'uuid' => '72ce49a6-76e5-495e-a3f8-0f13d955a3b5',
'title' => 'task2',
'completed' => '0',
'parent' => '157ed2b2-0d0c-4f0c-b1d2-7126255f4023',
),
1 =>
array (
'uuid' => '4975d08d-55f0-4cd8-9de5-2d056111ec2d',
'title' => 'task1',
'completed' => '0',
'parent' => '157ed2b2-0d0c-4f0c-b1d2-7126255f4023',
'children' =>
array (
0 =>
array (
'uuid' => 'ac5e9d37-8f14-4169-bcf2-e7b333c5faea',
'title' => 'subtask2',
'completed' => '0',
'parent' => '4975d08d-55f0-4cd8-9de5-2d056111ec2d',
),
1 =>
array (
'uuid' => 'f74b801f-c9f1-40df-b491-b0a274ffd301',
'title' => 'subtask1',
'completed' => '100',
'parent' => '4975d08d-55f0-4cd8-9de5-2d056111ec2d',
),
),
),
),
),
);
// Launch recursive calculations
completionTree($tree);
// Dump resulting tree
var_dump($tree);
A: Though this is answered, I'd like to leave a solution that seems a bit more intuitive (IMHO). Instead of passing down the parent, just handle the children first:
/**
* @param array $nodes
*
* @return array
*/
function calcCompletion(array $nodes): array {
// for each node in nodes
return array_map(function (array $node): array {
// if it has children
if (array_key_exists('children', $node) && is_array($node['children'])) {
// handle the children first
$node['children'] = calcCompletion($node['children']);
// update this node by *averaging* the children values
$node['completed'] = array_reduce($node['children'], function (float $acc, array $node): float {
return $acc + floatval($node['completed']);
}, 0.0) / count($node['children']);
}
return $node;
}, $nodes);
}
A: Well, this might be a little overhead, but you can use RecursiveArrayIterator. First, you must extend it to handle your tree structure:
class MyRecursiveTreeIterator extends RecursiveArrayIterator
{
public function hasChildren()
{
return isset($this->current()['children'])
&& is_array($this->current()['children']);
}
public function getChildren()
{
return new static($this->current()['children']);
}
}
Then using RecursiveIteratorIterator you can create an iterator which will process your tree starting from leaves:
$iterator = new RecursiveIteratorIterator(
new MyRecursiveTreeIterator($tasks),
RecursiveIteratorIterator::CHILD_FIRST
);
Then with this one, you can add your calculation logic:
$results = [];
$temp = [];
$depth = null;
foreach ($iterator as $node) {
if ($iterator->getDepth() === 0) {
// If there were no children use 'completion'
// else use children average
if (
is_null($depth)
|| !isset($temp[$depth])
|| !count($temp[$depth])
) {
$percentage = $node['completed'];
} else {
$percentage = array_sum($temp[$depth]) / count($temp[$depth]);
}
$results[$node['title']] = $percentage;
continue;
}
// Set empty array for current tree depth if needed.
if (!isset($temp[$iterator->getDepth()])) {
$temp[$iterator->getDepth()] = [];
}
// If we went up a tree, collect the average of children
// else push 'completion' for children of current depth.
if ($iterator->getDepth() < $depth) {
$percentage = array_sum($temp[$depth]) / count($temp[$depth]);
$temp[$depth] = [];
$temp[$iterator->getDepth()][] = $percentage;
} else {
$temp[$iterator->getDepth()][] = $node['completed'];
}
$depth = $iterator->getDepth();
}
Here is a demo.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/47877492",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Include and Execute EXE in C# Command Line App So I found a great little EXE command line app (we'll call it program.exe) that outputs some data I would like to manipulate with C#.
I was wondering if there was a way to "package" program.exe into my visual studio project file, so that I could hand my compiled application to a co-worker without having to send them program.exe too.
Any help is appreciated.
A: There are several ways you could accomplish this. First, you should add program.exe to the project. You would do this by right-clicking the project in Visual Studio, and selecting Add > Existing Item... Select program.exe, and it will appear in the project. Viewing its properties, you can set "Copy to Output Directory" to "Copy Always", and it will appear in your output directory beside your application.
Another way to approach the problem is to embed it as a resource. After adding program.exe to your project, change the Build Action property of the item from Content to Embedded Resource. At runtime, you could extract the command-line executable using Assembly.GetManifestResourceStream and execute it.
private static void ExtractApplication(string destinationPath)
{
// The resource name is defined in the properties of the embedded
string resourceName = "program.exe";
Assembly executingAssembly = Assembly.GetExecutingAssembly();
Stream resourceStream = executingAssembly.GetManifestResourceStream(resourceName);
FileStream outputStream = File.Create(destinationPath);
byte[] buffer = new byte[1024];
int bytesRead = resourceStream.Read(buffer, 0, buffer.Length);
while (bytesRead > 0)
{
outputStream.Write(buffer, 0, bytesRead);
bytesRead = resourceStream.Read(buffer, 0, buffer.Length);
}
outputStream.Close();
resourceStream.Close();
}
A: You might try something like:
try
{
System.Diagnostics.Process foobar = Process.Start("foobar.exe");
}
catch (Exception error)
{
// TODO: HANDLE error.Message
}
A: You can add any miscellaneous file to your project by rightclicking on the project and selecting add new
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/3238744",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: SQL; Plus + or Minus – Instead of Dates (ASP.NET-C#) I am Working On ASP.NET_C# Application
I am pulling out some Dates form SQL on a Grid View.
But instead of those Dates, I like to see how mush “Plus +” or “minus –“ It is form Today’s Date.
For Example
Today’s Date is = 11/02/2012
If the Date from SQL is 07/02/2012, I like my Grid to show -4
Or
If the Date from SQL is 17/02/2012, I like my Grid to show +6
Please Help me, How do I go about doing that….
This is My SQL Query; That I am working With
SELECT MAX(AmountPay.DateUpto) AS [ PaidUpTo], TimeTable.Name, TimeTable.Ref, TimeTable.Time11to12 FROM AmountPay FULL OUTER JOIN TimeTable ON AmountPay.Ref = TimeTable.Ref WHERE (TimeTable.Time11to12 = @Time11to12) GROUP BY TimeTable.Name, TimeTable.Ref, TimeTable.Time11to12
AmountPay.DateUpto is the Date I Like see as + or -
I have Been Suggested Datediff Function; and I have Used datediff function for working out things like Age from Date of Birth but I can't work out; how I can use this in the Case
Thanks in Advance
A: You can use Timespan
DateTime oldDate = DateTime.Now.AddDays(-4);
DateTime today = DateTime.Now;
TimeSpan span = oldDate.Subtract(today);
string diff = span.Days.ToString();
A: Since you are using MySQL, your select statement should be like:
SELECT DATEDIFF(CURDATE(), MAX(AmountPay.DateUpto)) AS [ PaidUpTo],
TimeTable.Name,
......
DATEDIFF will give you values like -1, 1, -5 ...and your DataGridView should display those values just fine.
A: SELECT DATEDIFF(day,GetDate(), MAX(AmountPay.DateUpto)) AS [ PaidUpTo], TimeTable.Name, TimeTable.Ref, TimeTable.Time11to12 FROM AmountPay FULL OUTER JOIN TimeTable ON AmountPay.Ref = TimeTable.Ref WHERE (TimeTable.Time11to12 = @Time11to12) GROUP BY TimeTable.Name, TimeTable.Ref, TimeTable.Time11to12
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/9245427",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to print colored text with Python in Windows I am currently making a very long Python program (sorry I cannot post it here since it is 400 lines long) and I wanted to print colored Text. I know this question has already been asked but they only worked with Linux (for me...). I use the termcolor module. Here is a part of the program :
if user_id_signin == user_id :
print('Welcome', colored(name_signin, 'red'))
When I run this code on Windows I get this output :
But when I run my code on my Raspberry Pi I get this output :
I have checked Pip and all required modules are installed on my Windows PC...
I have also tried other methods (with colorama module) and I get the same thing
Why is this not working only on Windows ?
Thanks for helping me
(and sorry for my English)
Clement
A: I suggest this new library Printy
Just released version 1.2.0 as a cross-platform library.
Check it out:
Printy on github
It is based on flags so you can do stuff like
from printy import printy
# with global flags, this will apply a bold (B) red (r) color and an underline (U) to the whole text
printy("Hello world", "rBU")
# with inline formats, this will apply a dim(D)
#blue (b) to the word 'Hello' and a striked (S)
#yellow (y) to the word 'world', the rest will remain as the predefined format
printy("this is a [bD]Hello@ [yS]world@ text")
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/61228983",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Highcharts - Highstocks. Show all x-axis labels I have highstocks set up to display two series of data.
When I zoom all the way the x-axis label for one of the series is always missing.
jsfiddle link
$(function() {
Highcharts.setOptions({
global: {
useUTC: false
}
});
var chart = new Highcharts.StockChart({
chart: {
"renderTo": "container"
},
plotOptions: {
"column": {
"stacking": "normal"
}
},
series: [{
"type": "column",
"name": "column 1",
"color": "#1d8ecd",
"data": [
[1296511200000, 974],
[1301605200000, 1618],
[1306875600000, 990],
[1312146000000, 1720],
[1317416400000, 516],
[1322690400000, 1472],
[1328047200000, 349],
[1333227600000, 1781],
[1338498000000, 649],
[1343768400000, 1124],
[1349038800000, 829],
[1354312800000, 1615],
[1359669600000, 1181]
]
}, {
"type": "column",
"name": "column 2",
"color": "#636466",
"data": [
[1293832800000, 1913],
[1298930400000, 1269],
[1304197200000, 567],
[1309467600000, 668],
[1314824400000, 722],
[1320098400000, 442],
[1325368800000, 1558],
[1330552800000, 1831],
[1335819600000, 373],
[1341090000000, 275],
[1346446800000, 1540],
[1351720800000, 998]
]
}],
});
});
Any ideas why is this happening and if I can force it to display all x-axis labels, at least when there is space for it?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/29095330",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Use external object in Jersey GET response I am developing a rest API service with Jersey and Jetty.
It is pretty simple and I have a number of endpoints like this:
@GET
@Path("/username/{username : [a-zA-Z][a-zA-Z_0-9]}")
@Produces(MediaType.TEXT_PLAIN)
public String getUsername(@Context UriInfo uriInfo, String content) {
MultivaluedMap<String, String> queryParams = uriInfo.getQueryParameters();
String nameParam = queryParams.getFirst("name");
//Dataset<Row> df = GetDataFrame.getDF();
return "test";
}
in the getUserName method, I need to use an object which I have created in the main class.
The main class is at the moment like this:
SourceHandler source = new SparkHandler(inputSource);
source.loadIntoMemory();
Server server = new Server(8080);
ServletContextHandler ctx =
new ServletContextHandler(ServletContextHandler.NO_SESSIONS);
ctx.setContextPath("/");
server.setHandler(ctx);
ServletHolder serHol = ctx.addServlet(ServletContainer.class, "/rest/*");
serHol.setInitOrder(1);
serHol.setInitParameter("jersey.config.server.provider.packages",
"com.ed7.res");
I would like to use the source object in the GET responses.
Is there a best practice to do that in Jersey?
Otherwise, I would create another class with a static field/static method that returns that particular object.
A: You can use HK2 DI. What you can do to configure it is create a standalone ServiceLocator and set that locator to be the parent locator of the app, using a Jersey property.
public static void main(String... args) {
SourceHandler source = new SparkHandler(inputSource);
ServiceLocator locator = ServiceLocatorUtilities.bind(new AbstractBinder() {
@Override
protected void configure() {
bind(source).to(SourceHandler.class);
}
});
ServletHolder serHol = ctx.addServlet(ServletContainer.class, "/rest/*");
serHol.setInitParameter(ServletProperties.SERVICE_LOCATOR, locator);
}
Then you can just @Inject the SourceHandler anywhere you need it
@Path("whatever")
public class Resource {
@Inject
private SourceHandler sourceHandler;
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/50896087",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: JWT authentication ignoring Lockout settings? I'm playing around with Identity and JWTs based on based on dualauthcore, and have tested getting a user locked out. I could not do it by attempting to log in with an incorrect password, and also not by including invalid tokens in the header.
options.Lockout.DefaultLockoutTimeSpan = TimeSpan.FromMinutes(30);
options.Lockout.MaxFailedAccessAttempts = 10;
options.Lockout.AllowedForNewUsers = true;
Is there a way to get JwtBearer authentication to obey Identity's lockout settings, or is JwtBearer authentication just free of such concerns?
A: JWT can be revoked, so next time you log in lockout will kick in.
Lockout is a log in/sign in process concept. After logging in you can get your token for authN/authZ activities.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/46882676",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Linearlayout overlay another linearlayout I have some problem with add linearlayout dynamically. It's add on the top of screen, overlay other linearlayout.
Here XML,code and results.
XML:
<TextView
android:id="@+id/top_km"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:background="#888"
android:gravity="top"
android:textColor="#fff"
android:textSize="30dip"
android:layout_centerHorizontal="true"/>
<RelativeLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_below="@+id/top_km"
android:id="@id/textLayout">
</RelativeLayout>
Code:
myLayout = (RelativeLayout) page.findViewById(R.id.textLayout);
LinearLayout linLayout = new LinearLayout(this);
linLayout.setOrientation(LinearLayout.VERTICAL);
LayoutParams params = new LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT);
myLayout.addView(linLayout);
LinearLayout hozLayout = new LinearLayout(this);
hozLayout.setOrientation(LinearLayout.HORIZONTAL);
LayoutParams params = new LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT);
myLayout.addView(hozLayout);
Results:
enter link description here
Thanks
A: Don't use a RelativeLayout as your holder. Use a LinearLayout with orientation="vertical" instead.
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_below="@+id/top_km"
android:orientation="vertical"
android:id="@id/textLayout" />
then in code
myLayout = (LinearLayout) page.findViewById(R.id.textLayout);
followed by
// rest of your code
A: It's because you use RealativeLayout for proper adding use
1. RelativeLayout.LayoutParams for st LayoutParams
2. In LayoutParams use field below
Example:
RelativeLayout rl=new RelativeLayout(this);
LinearLayout ll1=new LinearLayout(this);
TextView tx1=new TextView(this);
tx1.setText("Test1");
ll1.addView(tx1);
rl.addView(ll1);
LinearLayout ll2=new LinearLayout(this);
TextView tx2=new TextView(this);
tx2.setText("Test1");
ll2.addView(tx1);
rl.addView(ll2);
RelativeLayout.LayoutParams lp2=(LayoutParams) ll2.getLayoutParams();
And then use lp2.addRule
Here some help:
Parameters
verb One of the verbs defined by RelativeLayout, such as ALIGN_WITH_PARENT_LEFT.
anchor The id of another view to use as an anchor, or a boolean value(represented as TRUE) for true or 0 for false). For verbs that don't refer to another sibling (for example, ALIGN_WITH_PARENT_BOTTOM) just use -1.
A: Maybe it's easier for you to add it in the XML file with android:visibility="GONE" and then in the code just show it (View.VISIBLE) or hide it (View.GONE).
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/16923738",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: kafka-connector with java in gradle enviroment i'm studying kafka with spring. now i want to make kafka-connector.
i heard that kafka-connector can't execute itself. so i hav to compile my java files and add that as plugin. ( and for this im using gradle.)
here's the my gradle.
plugins {
id 'java'
}
group 'org.pipeline'
version '1.0-SNAPSHOT'
repositories {
mavenCentral()
}
dependencies {
implementation 'com.google.code.gson:gson:2.9.0'
implementation 'org.apache.kafka:connect-api:2.5.0'
implementation 'org.elasticsearch.client:elasticsearch-rest-high-level-client:7.9.2'
implementation 'org.slf4j:slf4j-api:1.7.24'
implementation 'org.slf4j:slf4j-simple:1.7.24'
testImplementation 'org.junit.jupiter:junit-jupiter-api:5.8.1'
testRuntimeOnly 'org.junit.jupiter:junit-jupiter-engine:5.8.1'
}
jar{
from{
configurations.implementation.collect { it.isDirectory() ? it : zipTree(it) }
}
}
test {
useJUnitPlatform()
}
and when i execute 'gradle-jar' i've got errror code below
Build file '/MyPath/project-name/elsticsearch-kafka-connector/build.gradle' line: 25
Could not determine the dependencies of task ':jar'.
> Resolving dependency configuration 'implementation' is not allowed as it is defined as 'canBeResolved=false'.
Instead, a resolvable ('canBeResolved=true') dependency configuration that extends 'implementation' should be resolved.
* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.
help plz?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/73258463",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Javascript - Why won't the innerHTML of the tag change? I'm trying to change my tag's innerHTML through Javascript in the following code:
window.onload = function() {
var doSomethingAJAX = function (el, url) {
var xhr = new XMLHttpRequest();
xhr.open("GET", url, true);
xhr.onload = function () {
var data = JSON.parse(xhr.responseText);
var tabs = document.getElementsByClassName("tab");
var tab = tabs[0];
var taskName = data.data[0].name;
alert(tab + " - " + taskName);
var taskId = data.data[0].id;
tab.innerHTML = taskName;
getFormProperties(taskId);
};
xhr.onerror = function () { alert("error") };
xhr.send();
};
code continues.....
The alert displays [object HTMLHeadingElement] and the task name correctly but it won't change the innerHTML the way it should. Am I missing something obvious?
HTML:
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<script type="text/javascript" src="js/apitest.js"></script>
<style type="text/css" media="screen">@import "css/tabs.css";</style>
<title>Tabs and REST</title>
</head>
<body>
<div id='tab-container'>
<div class="tab-content">
<h1 class="tab" title="title for page 1">Page 1</h1>
<form id="form" action="CompleteTask" method="post">
</form>
</div>
<div class="tab-content">
<h1 class="tab" title="title for page 2">Page 2</h1>
<p>This is the content of tab 2 on container 1</p>
</div>
<div class="tab-content">
<h1 class="tab" title="title for page 3">Page 3</h1>
<p>This is the content of tab 3 on container 1</p>
</div>
</div>
<script type="text/javascript" src="js/tabs.js"></script>
</body>
</html>
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/29847063",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Copied this SQL code from class and it won't run. I'm attempting to use JOIN Error message says "unrecognizable at 10:3"
SELECT
employees.name AS employee_name,
employees.role AS employee_role,
depatments.name AS department_name
FROM
`strategic-volt-320816.employee_data.employees`
INNER JOIN
`strategic-volt-320816.employee_data.departments`
ON
employees.department_id = departments.department_id
A: You are missing the tables aliases:
SELECT
employees.name AS employee_name,
employees.role AS employee_role,
depatments.name AS department_name
FROM
`strategic-volt-320816.employee_data.employees` employees
INNER JOIN
`strategic-volt-320816.employee_data.departments` departments
ON
employees.department_id = departments.department_id
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/68958122",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to recover an integer from an ActiveSupport::Duration object How can I recover the integer corresponding to an ActiveSupport::Duration object?
At the same time, is it possible to recover the type of time duration?
exemple:
foo = 2.day
bar = foo.duration_integer # expected "2"
baz = foo.duration_type # expected "day" or "days"
A: You can use the parts accessor like this. The first element is what you call the duration_type and the last one the integer value:
2.day.parts
=> [:days, 2]
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/28647309",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How does one programmatically discover a blog feed on a given domain? I have a list of 10,000 company websites and am trying to discover their blog feeds if they have one (any and all rss versions). I don't want to crawl them if i don't have to, so are there any tools, or specific tricks that would find a large percentage of their feeds if one exists?
My first thought was to look for the standard location of a blog feed, but most of these sites aren't primarily blogs, they are corporate sites. Any suggestions are welcome.
PHP based tools are preferred.
A: Crawling them is the only sensible option, you probably only need to hit their homepages. I'd make use of Feed::Find to fetch the pages and detect the feed URIs.
A: When you just paste a blog URL to google reader, it can automatically save RSS path. Most probably what Google Reader does is inspecting the source code for things like
<link rel="alternate" type="application/atom+xml" .. or
<link rel="alternate" type="application/rss" ..
That's how Firefox and some other browsers can show a RSS icon when you are surfing on a regular page. You can see Firefox source code for a healthy result.
In addition to those, you may consider looking at /blog, /rss, /blog/feed, blog.*.com/feed, /atom or URLs like *.xml, *.feed, *.rss Those are almost most popular RSS paths imho.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/6515744",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: How to make a nav tab active from outside with a button? <ul class="nav nav-tabs piluku-tabs " role="tablist">
<li role="presentation" class="active">
<a href="#home" aria-controls="home" role="tab" data-toggle="tab">Personal Detail</a>
</li>
<li role="presentation">
<a href="#join" aria-controls="join" role="tab" data-toggle="tab">Joining Detail</a>
</li>
<li role="presentation">
<a href="#education" aria-controls="education" role="tab" data-toggle="tab" id ="id2">Education Detail</a>
</li>
<li role="presentation">
<a href="#experience" aria-controls="education" role="tab" data-toggle="tab">Experience Detail</a>
</li>
</ul>
<a href="#join" aria-controls="join" role="tab" data-toggle="tab"><button type="button" class="btn btn-primary clickme">Next</button></a>
I am using a next button to move next tab. The tab is changing, but active stands only in first tab of the nav tab. How to change the active from first to selected tab?
A: Fire event on button click like this
$('.clickme').click(function(){
$('.nav-tabs > .active').next('li').find('a').trigger('click');
});
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/35263816",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: MIPS with Mars sim. - how to read a value from a keyboard input automatically (i.e. - no pressing enter to get the value) Is there a specific syscall or something I am missing in order to accomplish this?
A: You have to use syscall #12 to read a character.
See the MARS syscall sheet for further details.
Here goes an example that reads a character from console and prints the next ASCII code char
loop:
li $v0, 12
syscall # Read Character
addiu $a0, $v0, 1 # $a0 gets the next char
li $v0, 11
syscall # Write Character
b loop
nop
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/5065189",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: Does SKPaymentQueue's restoreCompletedTransactions() update the apps receipt? So SKPaymentQueue's restoreCompletedTransactions() retrieves transactions executed on another device onto the current device, therefore the respective product becomes available over multiple devices.
However, seeing that it returns a transaction(s), and saving those is a no no in apples books as there should only be one source of truth, how are those restored transactions persisted (in what ever form)?
Does the app's transaction receipt get updated too, by the restore? I ask because if the app is restarted I do not see it making sense to have to do another restoreCompletedTransactions() to check again if the user has a valid transaction for the product.
So, does restoreCompletedTransactions also update the app receipt?
Note: I already have the mechanics to access the receipt data, but don't have a second device to simulate a full restore.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/59188426",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: PHP use variable from global space inside class Hi I'm writing some code in PHP. I need to use a variable from the global scope inside my class but it doesn't work. I don't know if I need to use namespace or not and how ? Thank you
Sample :
<?PHP
$plantask_global_script = array("one", "two");
$plantask_global_config = array("three", "four");
$myvar = array_merge($plantask_global_script, $plantask_global_config);
class Env implements ArrayAccess
{
static private $container = $myvar;
public function offsetSet($offset, $value)
{
if (is_null($offset)) {
self::$container[] = $value;
} else {
self::$container[$offset] = $value;
}
}
public function offsetExists($offset)
{
return isset(self::$container[$offset]);
}
public function offsetUnset($offset)
{
unset(self::$container[$offset]);
}
public function offsetGet($offset)
{
return isset(self::$container[$offset]) ? self::$container[$offset] : null;
}
}
A: Try calling $myvar as a superglobal:
private static $container = $GLOBALS['myvar'];
Although, as Ron Dadon pointed out, this is generally bad practice in OOP.
EDIT:
I jumped the gun here. My above solution does not actually work, at least not for me. So, a better way to achieve this would be the following:
$myvar = array_merge($plantask_global_script, $plantask_global_config);
class Env implements ArrayAccess
{
private static $container = null;
public static function init($var)
{
self::$container = $var;
}
...
}
Env::init($myvar);
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/30563973",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: What Encryption Algorithm does SQL Server CE use? Including the following in a connection string to create a SQL Server CE database will cause the created database to be encrypted. However I need to know what encryption algorithm is used, and how this differs across different operating systems?
Encrypt Database = True;
Password = 'password';
The following resource under the heading "Encryption algorithms" seems to Triple-DES will be used on all operating systems prior to Windows Vista SP1, then AES265 on operating systems above this? I'm not sure if I'm interoperating the table correctly or if this table even relates to SQL Server CE.
http://technet.microsoft.com/en-us/library/dd125380(WS.10).aspx
A: See http://blogs.msdn.com/b/laxmi/archive/2008/04/15/sql-server-compact-database-file-security.aspx and http://blogs.msdn.com/b/sqlservercompact/archive/2010/07/07/introducing-sql-server-compact-4-0-the-next-gen-embedded-database-from-microsoft.aspx
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/9018491",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Getting error stating that my if statement is always false, what do i need to do? So i have been given a task for my degree level programming in Java, the task can be seen below:
My problem is getting errors stating:
*
*Condition 'a >= 18' is always 'false'
Condition 'a < 11' is always 'false'
Task
1)In a new command line project, write code which will prompt the
user for the age of a young person (between the age of 11 and 18,
and determine the highest category of film they can view at the
cinema unaccompanied. The categories are PG (any age), 12, 15 and 18
2)Add a default clause stating that they are too young to see a film
unaccompanied.
3)Add an 'if' statement to check if the age entered is over 18. If
so, print a message stating that they can see any film they like,
but if the value is under 18, ensure the switch statement is
executed
My code can be seen below:
package im.ucm.co4025;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Please enter your age: ");
int a = sc.nextInt();
sc.nextLine();
switch (a) {
case 11 -> System.out.println("You can view up to PG rated films unaccompanied");
case 12, 13, 14 -> System.out.println("You can view films up to a 12 age rating unaccompanied");
case 15, 16, 17 -> {
System.out.println("You can view films up to a 15 age rating unaccompanied");
if (a >= 18) {
System.out.println("You can watch any film unaccompanied");
}
if (a < 11) {
System.out.println("You are too young to view a film unaccompanied");
}
}
}
}
}
A: The following solutions can be provided:
*
*if statement to check adult age could be placed outside switch
then default in switch is referring to minor ages `[0..10].
if (a >= 18) {
System.out.println("You can watch any film unaccompanied");
} else {
switch (a) {
case 11 -> System.out.println("You can view up to PG rated films unaccompanied");
case 12, 13, 14 -> System.out.println("You can view films up to a 12 age rating unaccompanied");
case 15, 16, 17 -> System.out.println("You can view films up to a 15 age rating unaccompanied");
default -> System.out.println("You are too young to view a film unaccompanied at the age of " + a);
}
}
*replace if with a ternary operator in the default:
switch (a) {
case 11 -> System.out.println("You can view up to PG rated films unaccompanied");
case 12, 13, 14 -> System.out.println("You can view films up to a 12 age rating unaccompanied");
case 15, 16, 17 -> System.out.println("You can view films up to a 15 age rating unaccompanied");
default -> System.out.println(a >= 18 ?
"You can watch any film unaccompanied" :
"You are too young to view a film unaccompanied at the age of " + a);
}
A: The reason you're getting this is because the if statements are in the case for 15,16,17.
Thus the only situation where if(a>=18) or if(a<11) is ran the only possible things a could be is 15, 16, or 17.
A: You have some errors in your code which you must fix.
You can't have if statements in a switch. Better move them outside.
Here's what the working example should be:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Please enter your age: ");
int a = sc.nextInt();
if (a >= 18) {
System.out.println("You can watch any film unaccompanied");
}else if (a < 11) {
System.out.println("You are too young to view a film unaccompanied");
}
switch (a) {
case 11:
System.out.println("You can view up to PG rated films unaccompanied");
break;
case 12:
System.out.println("You can view films up to a 12 age rating unaccompanied");
break;
case 13:
System.out.println("You can view films up to a 12 age rating unaccompanied");
break;
case 14:
System.out.println("You can view films up to a 12 age rating unaccompanied");
break;
case 15:
System.out.println("You can view films up to a 15 age rating unaccompanied");
break;
case 16:
System.out.println("You can view films up to a 12 age rating unaccompanied");
break;
case 17:
System.out.println("You can view films up to a 12 age rating unaccompanied");
break;
}
}
}
Sample I/O
Input
12
Output
You can view films up to a 12 age rating unaccompanied
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/64158726",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: How to use Semantic Logging Application Block (SLAB) to configure multiple sinks based on level in C# (in-process) When setting up Semantic Logging Application Block (SLAB) to use multiple sinks (for example a flat file and rolling file) it's not writing to each sink based on the level in my logic; I am trying to understand why. I can get it to write to different sinks base on Keywords but not based on EventLevel.
I wanted one sink to get all logs and another sink to get only logs with a level of Warning (or worst). When I defined 2 listeners, one sink with level of "EventLevel.LogAlways" and another sink with level of "EventLevel.Warning", I am not getting any logging entries. (I define an EventSource method with a EventLevel of Verbose and was expecting to see logging from the listener defined with EventLevel.LogAlways)
Bellow is the logic I am trying to implement (Please let me know if this is not enough logic and I will update accordingly):
1) Using the aExpense as an example bellow, this is how the listeners are defined in my Application_Start:
//Log to file with EventLevel of at least Warning
this.fileListener = FlatFileLog.CreateListener("aExpense.DataAccess.log", formatter: new XmlEventTextFormatter(EventTextFormatting.Indented), isAsync: true);
fileListener.EnableEvents(AExpenseEvents.Log, EventLevel.Warning, Keywords.All);
//Log to Rolling file with any EventLevel
this.rollingfileListener = RollingFlatFileLog.CreateListener("aExpense.UserInterface.log", rollSizeKB: 10, timestampPattern: "yyyy", rollFileExistsBehavior: RollFileExistsBehavior.Increment, rollInterval: RollInterval.Day, formatter: new JsonEventTextFormatter(EventTextFormatting.Indented), isAsync: true);
rollingfileListener.EnableEvents(AExpenseEvents.Log, EventLevel.LogAlways, Keywords.All);
2) Writing a log is done like this:
//Log the event for application starting using Symmantic Logging (in-process)
AExpenseEvents.Log.ApplicationStarting();
3) The AExpenseEvents (EventSource) method for ApplicationStarting() is:
[Event(100, Level = EventLevel.Verbose, Keywords = Keywords.Application, Task = Tasks.Initialize, Opcode = Opcodes.Starting, Version = 1)]
public void ApplicationStarting()
{
if (this.IsEnabled(EventLevel.Verbose, Keywords.Application))
{
this.WriteEvent(100);
}
}
A: I have done similar implementation with a small change. You can change implementation as follows. The public method ApplicationStarting checks that logging is enabled or not. It has decorated with with [NoEvent] which indicates SLAB not to generate an event when method is invoked. If logging is enabled then the private method will be called to write the event.
[NonEvent]
public void ApplicationStarting()
{
if (this.IsEnabled(EventLevel.Verbose, Keywords.Application))
{
this.ApplicationStartingImplementation();
}
}
[Event(100, Level = EventLevel.Verbose, Keywords = Keywords.Application, Task = Tasks.Initialize, Opcode = Opcodes.Starting, Version = 1)]
private void ApplicationStartingImplementation()
{
this.WriteEvent(100);
}
A: Removing the if statement (which is checking if a particular EventLevel or Keyword IsEnabled) before calling this.WriteEvent accomplished my goal; I now have multiple sinks listening to different EventLevel's.
In my original question above, numbers 1 and 2 would stay the same, and #3 would look like this:
3) The AExpenseEvents (EventSource) method for ApplicationStarting() is:
[Event(100, Level = EventLevel.Verbose, Keywords = Keywords.Application, Task = Tasks.Initialize, Opcode = Opcodes.Starting, Version = 1)]
public void ApplicationStarting()
{
this.WriteEvent(100);
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/33181504",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to fix "Execution failed for task ':app:processDebugResources'. > Android resource linking failed"[Android/Flutter] It happened out of nowhere. One day I was running my code which was working just fine, and the next day, without touching my build.gradle files or any other build files this error popped up.
I have tried a lot of different solutions like changing my buildToolsVersion or setting a specific flag of AAPT(can't remember which) to false. Nothing works.
My app\build.gradle file:
android {
compileSdkVersion 27
buildToolsVersion '27.0.3'
sourceSets {
main.java.srcDirs += 'src/main/kotlin'
}
lintOptions {
disable 'InvalidPackage'
}
defaultConfig {
// TODO: Specify your own unique Application ID
(https://developer.android.com/studio/build/application-id.html).
applicationId "com.skydevs.bookx"
minSdkVersion 16
targetSdkVersion 27
versionCode flutterVersionCode.toInteger()
versionName flutterVersionName
testInstrumentationRunner
"android.support.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
// TODO: Add your own signing config for the release build.
// Signing with the debug keys for now, so `flutter run --release`
works.
signingConfig signingConfigs.debug
}
}
}
flutter {
source '../..'
}
dependencies {
implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
testImplementation 'junit:junit:4.12'
androidTestImplementation 'com.android.support.test:runner:1.0.2'
androidTestImplementation 'com.android.support.test.espresso:espresso-
core:3.0.2'
implementation 'com.google.firebase:firebase-core:16.0.1'
}
apply plugin: 'com.google.gms.google-services'
The error I'm getting is:
Execution failed for task ':app:processDebugResources'.
> Android resource linking failed
Output: C:\Users\baada\AndroidStudioProjects\bookx\build\app\intermediates\incremental\mergeDebugResources\merged.dir\values-v28\values-v28.xml:7: error: resource android:attr/dialogCornerRadius not found.
C:\Users\baada\AndroidStudioProjects\bookx\build\app\intermediates\incremental\mergeDebugResources\merged.dir\values-v28\values-v28.xml:11: error: resource android:attr/dialogCornerRadius not found.
C:\Users\baada\AndroidStudioProjects\bookx\build\app\intermediates\incremental\mergeDebugResources\merged.dir\values\values.xml:905: error: resource android:attr/fontVariationSettings not found.
C:\Users\baada\AndroidStudioProjects\bookx\build\app\intermediates\incremental\mergeDebugResources\merged.dir\values\values.xml:905: error: resource android:attr/ttcIndex not found.
error: failed linking references.
Command: C:\Users\baada\.gradle\caches\transforms-1\files-1.1\aapt2-3.2.1-4818971-windows.jar\a5cc63922d025d4315a498efa486650c\aapt2-3.2.1-4818971-windows\aapt2.exe link -I\
C:\Users\baada\AppData\Local\Android\sdk\platforms\android-27\android.jar\
--manifest\
C:\Users\baada\AndroidStudioProjects\bookx\build\app\intermediates\merged_manifests\debug\processDebugManifest\merged\AndroidManifest.xml\
-o\
C:\Users\baada\AndroidStudioProjects\bookx\build\app\intermediates\processed_res\debug\processDebugResources\out\resources-debug.ap_\
-R\
@C:\Users\baada\AndroidStudioProjects\bookx\build\app\intermediates\incremental\processDebugResources\resources-list-for-resources-debug.ap_.txt\
--auto-add-overlay\
--java\
C:\Users\baada\AndroidStudioProjects\bookx\build\app\generated\not_namespaced_r_class_sources\debug\processDebugResources\r\
--custom-package\
com.example.bookx\
-0\
apk\
--output-text-symbols\
C:\Users\baada\AndroidStudioProjects\bookx\build\app\intermediates\symbols\debug\R.txt\
--no-version-vectors
Daemon: AAPT2 aapt2-3.2.1-4818971-windows Daemon #0
Output: C:\Users\baada\.gradle\caches\transforms-1\files-1.1\appcompat-1.0.2.aar\aa44270b14856bd5a0b17a3c0a45cb34\res\values-v28\values-v28.xml:9:5-12:13: AAPT: error: resource android:attr/dialogCornerRadius not found.
C:\Users\baada\AndroidStudioProjects\bookx\build\app\intermediates\incremental\mergeDebugResources\merged.dir\values-v28\values-v28.xml:11: AAPT: error: resource android:attr/dialogCornerRadius not found.
C:\Users\baada\.gradle\caches\transforms-1\files-1.1\core-1.0.1.aar\bc8b94f938baa5558925fd51b49cb6bf\res\values\values.xml:89:5-125:25: AAPT: error: resource android:attr/fontVariationSettings not found.
C:\Users\baada\.gradle\caches\transforms-1\files-1.1\core-1.0.1.aar\bc8b94f938baa5558925fd51b49cb6bf\res\values\values.xml:89:5-125:25: AAPT: error: resource android:attr/ttcIndex not found.
error: failed linking references.
Command: C:\Users\baada\.gradle\caches\transforms-1\files-1.1\aapt2-3.2.1-4818971-windows.jar\a5cc63922d025d4315a498efa486650c\aapt2-3.2.1-4818971-windows\aapt2.exe link -I\
C:\Users\baada\AppData\Local\Android\sdk\platforms\android-27\android.jar\
--manifest\
C:\Users\baada\AndroidStudioProjects\bookx\build\app\intermediates\merged_manifests\debug\processDebugManifest\merged\AndroidManifest.xml\
-o\
C:\Users\baada\AndroidStudioProjects\bookx\build\app\intermediates\processed_res\debug\processDebugResources\out\resources-debug.ap_\
-R\
@C:\Users\baada\AndroidStudioProjects\bookx\build\app\intermediates\incremental\processDebugResources\resources-list-for-resources-debug.ap_.txt\
--auto-add-overlay\
--java\
C:\Users\baada\AndroidStudioProjects\bookx\build\app\generated\not_namespaced_r_class_sources\debug\processDebugResources\r\
--custom-package\
com.example.bookx\
-0\
apk\
--output-text-symbols\
C:\Users\baada\AndroidStudioProjects\bookx\build\app\intermediates\symbols\debug\R.txt\
--no-version-vectors
Daemon: AAPT2 aapt2-3.2.1-4818971-windows Daemon #0
A: Today, I got the same error at my project which I was working on yesterday without any problem.
Some upgrade causes this error IMO, my solution is:
*
*Open the project via Android Studio
*Open android/build.gradle and android/app/build.gradle
*Just correct things what IDE warns about, it usually warns your SDK, Kotlin and Gradle versions etc.
It's not mandatory but you can check your .bashrc exports or environment variables, sometimes it can fix some problems.
Edit: When you are updating your SDK versions, don't forget to upgrade also your project dependencies.
A: I think it depends on android emulator API level you are using.
In my case I used android emulator API 30, but compileSdkVersion was 28, so i got the error! By updating compileSdkVersion to 30, everything worked correctly!
OS: Ubuntu 20.04 LTS
Android emulator API 30
Dart 2.10.2
Flutter 1.22.2
A: Kindly check your strings.xml and It should be like:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="app_name">App Name here</string>
<string name="facebook_app_id">2206883509627625</string>
<string name="fb_login_protocol_scheme">fb2206883509627625</string>
</resources>
Special attention to add this line:
<string name="app_name">App Name here</string>
A: I had the same error while using flutter, but in my case the problem was caused by an incorrect line in a file in the 'res' folder in my Adroid projects.
You need to check your code, in my case it was calling a resource that doesn't exist in my android / app / src / main / res / launcher / drawable / launch_background.xml file, make sure all your resources and xml files are ok.
A: check that
How to fix "Execution failed for task ':app:processDebugResources'. > Android resource linking failed"[Android/Flutter]
I had the same error while using flutter, but in my case the problem was caused by an incorrect line in a file in the 'res' folder in my Adroid projects.
You need to check your code, in my case it was calling a resource that doesn't exist in my android / app / src / main / res / launcher / drawable / launch_background.xml file, make sure all your resources and xml files are ok.
A: To resolve this issue, run your flutter project in Android Studio rather than Visual Studio Code.
A: Make sure you are connected to the Internet and rebuild the project. That solves the problem for me.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/54152209",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "9"
}
|
Q: View object/property state in Xcode while debugging So I'm new to Xcode, working on an iOS project and I'm having a heck of a time with the most fundamental debugging. Specifically I need to be able to view the state of objects as I step through the code (that's not crazy is it?), but I can't for the life of me figure out how to do this in Xcode.
Whenever I try, it seems the furthest I get is a memory address that can't be expanded to show its objective contents. Nor can I figure out any way to even manually dereference the pointer in the debug console to view the state of that object.
Here I am trying to view the contents of the store.storeHours array, with no luck whatsoever. In fact the view on the left tells me there are 0 objects in the array, and won't show anything when I try to expand it, but when I po store.storeHours the console shows 7 objects, albeit uselessly portrayed as memory addresses.
Please tell me I'm not crazy and I'm just missing something!
Update: So things get even weirder! When I switch the variable display to "Local" instead of "Auto" suddenly, self.store.storeHours becomes fully navigable! I'm wondering if perhaps there was a glitch accessing the correct "storeHours" instance or something because it's clearly identifying 7 objects in the array when I view it now! Not to mention the objects are expandable as I was originally hoping.
A: The instances are actually providing that information themselves. You need to implement the description method, which is inherited from NSObject, for your custom classes in order for them to be able to print themselves as something other than a memory address (which is what NSObject's implementation does).
I've no idea what properties your Hours class has, but this is as simple as something like:
- (NSString *)description
{
return [NSString stringWithFormat:@"Open: %i Close: %i", self.openTime, self.closeTime];
}
The method just needs to return an NSString containing whatever information you think is important to see when inspecting the object.
This is also how classes represent themselves when you use the %@ format specifier in NSLog().
A: In your example, store.storeHours is an empty NSArray. So, naturally, you can't look inside it.
For more clarity in the debugger, try adding a method (inherited from NSObject)
- (NSString*) description
to your objects like Hours that tells you more about their contents. See also debugDescription.
A: implement
-(NSString*)description{
//Return a string in whatever way you like to describe this instance. That is what xcode debugger reads.
//This is implemented in the parent to return the address, that's why you see that way.
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/15102082",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "8"
}
|
Q: How to launch Microsoft Edge (with no address bar if possible) from a batch script? I've been trying to write a script in which I want to launch a web app in Microsoft Edge specifically (if it is installed). But executing the .exe file doesn't seem to work.
The path that I've found for Edge on my computer, using the task manager as the reference, seems to be C:\Windows\SystemApps\Microsoft.MicrosoftEdge_8wekyb3d8bbwe\MicrosoftEdge.exe. This part seems a bit arbitrary, as 8wekyb3d8bbwe in the folder name doesn't really seem like a constant. On another computer, this would probably be different? Furthermore, when I navigate to that folder, and double click MicrosoftEdge.exe or MicrosoftEdgeCP.exe, nothing happens.
For comparison I've tried Firefox's .exe file, and it executes properly from the script by doing:
START "Web App" "%programfiles(x86)%\Mozilla Firefox\firefox.exe" -chrome http://www.example.com/app
Additionally, if possible, can Microsoft Edge be launched without the address bar and the tabs? It's the equivalent to running Firefox with the -chrome parameter, and Google Chrome with the --app parameter.
A: This is how:
msedge.exe --kiosk https://google.com/ --edge-kiosk-type=fullscreen --no-first-run
You can find more information about Edge and kiosk mode:
https://learn.microsoft.com/en-us/deployedge/microsoft-edge-configure-kiosk-mode
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/33827350",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Should I use condition variables from the C++ standard or from the Windows API? When implementing condition variables into a Win32 C++ program, would it be better to use Win32 functions, classes, and data types (e.g. CreateThread, SleepConditionVariableCS, WaitForSingleObjectEx, ReleaseMutex, CONDITION_VARIABLE) or those from the C++11 standard libraries (e.g. thread, wait, join, unlock, condition_variable)?
Since the answer to this question is probably not binary, what considerations should one take into account when making such a decision?
A: The C++ synchronization mechanisms are designed to C++ principles. They free their resources in the destructor, and they also use RAII to ensure safe locking. They use exceptions to signal errors.
Essentially, they are much harder to use incorrectly than the function-based native Windows API. This means that if you can use them (your implementation supports them), you always should use them.
Oh, and they are cross-platform.
A: One consideration should be what your compiler can handle. For example, when you install MinGW on Windows, you can choose whether to install the API for POSIX threads or Win32 threads. On the other hand, if you use TDM-GCC, you should be aware that versions 4.7.1 and lower use Win32 threads, while versions 4.8.1 and higher use POSIX threads. And as woolstar mentioned above, if you're using Microsoft's compiler, you should check to see whether the bugs in its support for these classes have been worked out.
If your compiler supports POSIX threads, you can use the C++ thread classes of the Standard Library (e.g. thread, mutex, condition_variable). If your compiler supports Win32 threads, you can use the Win32 thread functions.
In my case, I originally had TDM-GCC 4.7.1 and tried to use the C++ Standard Library classes, but that didn't work (for reasons explained above). So I installed MinGW by itself and chose "posix" in the "threads" option of the installer. Then I was able to use those classes.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/21385705",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
}
|
Q: python: outfile to another text file if exceed certain file size I using scapy with python in ubuntu. I would like to ask if anyone would know how to code the example:
let say I have two text files which are writing while the script is running then I would like to check the file is exceed example 500bytes, if does then it will store whatever in the file and create a new text file to write. (output1.txt, output2.txt,etc..)
Would be appreciated if any expertise will help. Thanks
part of my code is:
file = open("output.txt","w")
def example(p):
if p.haslayer(Dot11Beacon):
if p.addr2 not in uniqueAP:
file.writelines(p.addr2 + "\n")
so while the script is running in the terminal, it will write it into the file called output.txt but i would want to improve the script to check file size of the text file and if exceed it would stop writing in the current and create a new output2.txt for example and continue.
A: A simple example if you don't want to use RotatingFileHandler.
You should use os.stat('filename').st_size to check file sizes.
import os
import sys
class RotatingFile(object):
def __init__(self, directory='', filename='foo', max_files=sys.maxint,
max_file_size=50000):
self.ii = 1
self.directory, self.filename = directory, filename
self.max_file_size, self.max_files = max_file_size, max_files
self.finished, self.fh = False, None
self.open()
def rotate(self):
"""Rotate the file, if necessary"""
if (os.stat(self.filename_template).st_size>self.max_file_size):
self.close()
self.ii += 1
if (self.ii<=self.max_files):
self.open()
else:
self.close()
self.finished = True
def open(self):
self.fh = open(self.filename_template, 'w')
def write(self, text=""):
self.fh.write(text)
self.fh.flush()
self.rotate()
def close(self):
self.fh.close()
@property
def filename_template(self):
return self.directory + self.filename + "_%0.2d" % self.ii
if __name__=='__main__':
myfile = RotatingFile(max_files=9)
while not myfile.finished:
myfile.write('this is a test')
After running this...
[mpenning@Bucksnort ~]$ ls -la | grep foo_
-rw-r--r-- 1 mpenning mpenning 50008 Jun 5 06:51 foo_01
-rw-r--r-- 1 mpenning mpenning 50008 Jun 5 06:51 foo_02
-rw-r--r-- 1 mpenning mpenning 50008 Jun 5 06:51 foo_03
-rw-r--r-- 1 mpenning mpenning 50008 Jun 5 06:51 foo_04
-rw-r--r-- 1 mpenning mpenning 50008 Jun 5 06:51 foo_05
-rw-r--r-- 1 mpenning mpenning 50008 Jun 5 06:51 foo_06
-rw-r--r-- 1 mpenning mpenning 50008 Jun 5 06:51 foo_07
-rw-r--r-- 1 mpenning mpenning 50008 Jun 5 06:51 foo_08
-rw-r--r-- 1 mpenning mpenning 50008 Jun 5 06:51 foo_09
[mpenning@Bucksnort ~]$
A: Another way (a bit shorter) would be to use a with clause having an if condition checking for the file size:-
def RotateFile(count, file_size, file_name):
indX = 0
while indX < count:
with open(file_name,"a") as fd:
##
fd.write("DUMMY TEXT\n")
##
if int(os.path.getsize(file_name)) > file_size:
indX += 1
file_name = "new_file"+str(indX)+".txt"
with statement creates a context manager, so by the time you reach the end of if condition , the file object in fd will have been automatically closed.
Next is to specify the options you need and pass on to the method:
if __name__ == "__main__":
count = 10 ## 10 number of files
file_size = 10000 ## 10KB in size
file_name = "new_file.txt" ## with this name
RotateFile(count, file_size, file_name)
After execution, it will give 10 files of size 10KB each (in the current dir)...
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/10894692",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "7"
}
|
Q: How to get a vector of all dates in the current month the goal is quite straightforward, I want a vector made of all the dates in this month.
Why?
Because I'll later be able to transform this vector and get the first day of the month, or alternatively, a vector with just the 1st and 16th of the month, or even a vector with all the Mondays of the month... list goes on, but POSIXlt should serve us better since it also stores the weekday.
require("lubridate")
v.d.CheckDates <- as.POSIXlt(seq(as.POSIXlt(Sys.Date() - days(31)), length.out=62, by="day"))
v.d.CheckDates[v.d.CheckDates$mon == as.numeric(format(Sys.Date() , format = "%m")) - 1]
it's basically creating a 62 day vector centered on today (first line) and then trimming the other months (second line)
So, does anyone have a more cleaver and more efficient (preferably also one liner) way of doing it?
A: You can use floor_date to get 1st date of current month, ceiling_date to get 1st date of next month subtract - 1 to get last day of current month and create sequence.
library(lubridate)
todays_date <- Sys.Date()
seq(floor_date(todays_date, 'month'),
ceiling_date(todays_date, 'month') - 1, by = 1)
Also other similar variations,
floor_date(todays_date, 'month') + 1:days_in_month(todays_date) - 1
seq(floor_date(todays_date, 'month'),
length.out = days_in_month(todays_date), by = 1)
This returns object of class 'Date', there are function in base R as well as lubridate to get whichever part of Date you want.
A: Package timeperiodsR has a handy function for that :
timeperiodsR::this_month(part = "sequence")
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/64044387",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: How to solve JSON Error for Android application ? Here is Error log:
03-13 10:00:15.778: W/System.err(2558): org.json.JSONException: No value for objects
03-13 10:00:15.778: W/System.err(2558): at org.json.JSONObject.get(JSONObject.java:354)
03-13 10:00:15.778: W/System.err(2558): at org.json.JSONObject.getJSONArray(JSONObject.java:544)
03-13 10:00:15.778: W/System.err(2558): at com.app.Main$ListTask.doInBackground(Main.java:104)
03-13 10:00:15.778: W/System.err(2558): at com.app.Main$ListTask.doInBackground(Main.java:1)
03-13 10:00:15.778: W/System.err(2558): at android.os.AsyncTask$2.call(AsyncTask.java:287)
03-13 10:00:15.778: W/System.err(2558): at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305)
03-13 10:00:15.778: W/System.err(2558): at java.util.concurrent.FutureTask.run(FutureTask.java:137)
03-13 10:00:15.778: W/System.err(2558): at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
03-13 10:00:15.778: W/System.err(2558): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1076)
03-13 10:00:15.778: W/System.err(2558): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:569)
03-13 10:00:15.778: W/System.err(2558): at java.lang.Thread.run(Thread.java:856)
Activity code
package com.app;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Arrays;
import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.util.Log;
import android.view.Menu;
import android.widget.ArrayAdapter;
import android.widget.ListView;
public class Main extends Activity {
ListView List;
ArrayList<String> listArray = new ArrayList<String>();
ArrayAdapter<String> Adapter;
Context context;
String url = "http://sandzak.today/api/1/categories/?format=json/api/projekti/10?=";
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
context = this;
List = (ListView) findViewById(R.id.lista);
Adapter = new ArrayAdapter<String>(this, R.layout.lista, listArray);
List.setAdapter(Adapter);
VideoListTask loaderTask = new VideoListTask();
loaderTask.execute();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
public class VideoListTask extends AsyncTask<Void, Void, Void>{
ProgressDialog dialog;
@Override
protected void onPreExecute()
{
dialog = new ProgressDialog(context);
dialog.setTitle("Loading Category");
dialog.show();
super.onPreExecute();
}
@Override
protected Void doInBackground(Void... params)
{
HttpClient client = new DefaultHttpClient();
HttpGet getRequest = new HttpGet(url);
try
{
HttpResponse responce = client.execute(getRequest);
StatusLine statusLine = responce.getStatusLine();
int statusCode = statusLine.getStatusCode();
if(statusCode != 200)
{
return null;
}
InputStream jsonStream = responce.getEntity().getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(jsonStream));
StringBuilder builder = new StringBuilder();
String line;
while((line = reader.readLine())!=null)
{
builder.append(line);
}
String jsonData = builder.toString();
JSONObject json = new JSONObject(jsonData);
JSONObject meta = json.getJSONObject("meta");
JSONArray objects = meta.getJSONArray("objects");
for(int i =0; i<objects.length(); i++)
{
JSONObject video = objects.getJSONObject(i);
listArray.add(video.getString("name"));
}
}
catch (ClientProtocolException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (JSONException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(Void result) {
dialog.dismiss();
Adapter.notifyDataSetChanged();
super.onPostExecute(result);
}
}
}
How can I solve this ?
A: make a point on this node you are append the string and then you pass it to the object.In the object you need to pass the string which is key term of your json.
while((line = reader.readLine())!=null)
{
builder.append(line);
}
A: *
*Their is an easy way to turn a inputstrem to a string:
InputStream inputStream = url.openStream();
Scanner in = new Scanner(inputStream).useDelimiter("\\A");
String str = in.hasNext() ? in.next() : null;
*prefer to use JSONObject.optXxx(field) rather than JSONObject.getXxx(field), this you don' t need to worry whether a field in the json data or whether it can convert to your desired type. Besides, JSONObject.optXxx(field, fallback) has a fallback value if the field doesn' t exist or cannot conver to the specific type.
*(optional) if you would like to use JSONObject.getXxx(), you can first check the whether the filed in the json data using JSONObject.has(fieldname)
hope it' s useful.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/22373744",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
}
|
Q: Using R Programming Language with FANN Neural Network Library I do a lot of computational intelligence research. I have used Matlab almost exclusively as my programming medium for a decade or so. I am now trying to move to OSS. I have settled on R as my new environment.
After a long search for neural net software, the only Matlab-comparable OSS packages are Stuttgart NN and FANN (this can be debated another time =). The former doesn't appear to be maintained so I'd like to go with the latter. So my question is:
Does anyone have experience using R and FANN?
FANN has C++ bindings and R seems to have a couple of packages for a C++ interface, but since I'm a R newbie I need an idea of where exactly to start. Any guidance or recommendations would be appreciated.
Cheers.
A: I do not know anything abuot FANN but I can assure you that R has an actively maintained interface to the Stuttgart Neural Net Simulator (SNNS) library via the
RSNNS package --- as RSNNS happens to employ the
Rcpp package for interfacing R and C++ which I am involved in.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/6284844",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: how much to sort data in php vs. mysql? I'd like to group an array that I've returned from a mysql database. I've named the array $item_info and I'd like to group it by folder_id.
First, two related questions:
*
*Is doing a single query to get the data below and creating new array keys always (or most likely) faster than 2 separate queries (one involving the desired GROUP BY and the other not).
*From what I read on SO it seems it is best to keep the MySQL query simple and sort out the data with PHP. Comments on that general philosophy?
here's what my database gives back:
$item_info=array(
array("id"=>"1", 'folder_id'="1", "img"=>"/images/button_01.gif"),
array("id"=>"2", 'folder_id'="1", "img"=>"/images/button_02.gif"),
array("id"=>"3", 'folder_id'="2", "img"=>"/images/button_03.gif"),
array("id"=>"4", 'folder_id'="2", "img"=>"/images/button_04.gif"),
array("id"=>"5", 'folder_id'="3", "img"=>"/images/button_05.gif"),
array("id"=>"6", 'folder_id'="3", "img"=>"/images/button_06.gif")
);
here's how i'd like to array:
$item_info=array(
array(
array("id"=>"1", 'folder_id'="1", "img"=>"/images/button_01.gif"),
array("id"=>"2", 'folder_id'="1", "img"=>"/images/button_02.gif")
),
array(
array("id"=>"3", 'folder_id'="2", "img"=>"/images/button_03.gif"),
array("id"=>"4", 'folder_id'="2", "img"=>"/images/button_04.gif")
),
array(
array("id"=>"5", 'folder_id'="3", "img"=>"/images/button_05.gif"),
array("id"=>"6", 'folder_id'="3", "img"=>"/images/button_06.gif")
));
A: Since you already have the data in RAM, grouping in PHP seems more than reasonable, since it takes not a lot of processing.
You might want to try
$item_info_tmp=array();
foreach ($item_info as $ii) {
if (!isset($item_info_tmp[$ii['folder_id']]))
$item_info_tmp[$ii['folder_id']]=array();
$item_info_tmp[$ii['folder_id']][]=$ii;
}
$item_info=array_values($item_info_tmp);
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/10542266",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: WPF setting cell padding collapses DataGrid's columns I would like to set DataGrid cell's padding, I have tried both major solutions from the widely accepted question Set a padding on dataGridCells in WPF.
However none of the solutions work properly, they cause auto-sized columns to collapse to header's width:
How can I set cell padding so that it does not break the DataGrid column's auto sizing?
Code sample:
<DataGrid IsReadOnly="True" CanUserResizeColumns="False" AutoGenerateColumns="False"
xmlns:sys="clr-namespace:System;assembly=mscorlib">
<DataGrid.ItemsSource>
<x:Array Type="{x:Type sys:DateTime}">
<sys:DateTime/>
</x:Array>
</DataGrid.ItemsSource>
<DataGrid.CellStyle>
<Style TargetType="{x:Type DataGridCell}">
<Setter Property="Padding" Value="10,2"/>
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type DataGridCell}">
<Border Padding="{TemplateBinding Padding}" SnapsToDevicePixels="True">
<ContentPresenter SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}"/>
</Border>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</DataGrid.CellStyle>
<DataGrid.Columns>
<DataGridTextColumn Header="Some short header" Binding="{Binding Path=., StringFormat=dddd MMMM yyyy HH:mm:ss}"/>
<DataGridTextColumn Header="Stretching" Binding="{Binding}" Width="*"/>
</DataGrid.Columns>
</DataGrid>
Note: the issue appears consistently only during runtime, in editor window it looks OK after making any changes, until building the solution and/or running the app that is.
A: I've tried to simply add this Width="Auto" into the first DataGridTextColumn and it worked for me.
Code:
<DataGrid IsReadOnly="True" CanUserResizeColumns="False" AutoGenerateColumns="False"
xmlns:sys="clr-namespace:System;assembly=mscorlib">
<DataGrid.ItemsSource>
<x:Array Type="{x:Type sys:DateTime}">
<sys:DateTime/>
</x:Array>
</DataGrid.ItemsSource>
<DataGrid.CellStyle>
<Style TargetType="{x:Type DataGridCell}">
<Setter Property="Padding" Value="10,2"/>
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type DataGridCell}">
<Border Padding="{TemplateBinding Padding}" SnapsToDevicePixels="True">
<ContentPresenter SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}"/>
</Border>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</DataGrid.CellStyle>
<DataGrid.Columns>
<DataGridTextColumn Header="Some short header" Width="Auto" Binding="{Binding Path=., StringFormat=dddd MMMM yyyy HH:mm:ss}"/>
<DataGridTextColumn Header="Stretching" Binding="{Binding}" Width="*"/>
</DataGrid.Columns>
</DataGrid>
Result:
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/57287754",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Unknown syntax error when trying to nest if statement inside of a do while loop I am writing a program that reads in a number that the user enters, checks to see if it is between 0 and 100, if it is then the number is square rooted. If the number is less than 0, an error message is printed. If the number is between 100 and 200 then the natural log of the number is found and if it is over 200 then the loop terminates.
#include <stdio.h>
#include <math.h>
int main (void)
{
float num;
double x, y;
do {
printf("Please enter a number \n");
scanf("%f", &num);
if (num > 0 && num <= 100)
{
x = sqrt(num);
printf("The square root of the number entered is %f \n", x);
}
else if (num <= 0)
{
printf("Please enter a positive number \n");
}
else (num > 100)
{
y = log(num);
printf("The natural log of the number entered is %f \n", y);
}
} while (num <= 200);
return 0;
}
The problem I am having, is when I build the solution, I get an error statement saying that a ; is expected after the
else (num > 100)
What is the reason for this as I would not expect there to be one needed here?
A: else (num > 100)
should be
else if (num > 100)
else clause doesn't any condition - it's just a syntax error.
You should also check if scanf() call succeeded:
if (scanf("%f", &num) != 1) {
printf("Input error");
exit(1);
}
A: else does not take an expression, it is associated with the lexically nearest preceding if that is allowed by the syntax.
The format is
if ( expression ) statement else statement
Quoting C11, chapter §6.8.4.1
[...] the first substatement is executed if the expression compares unequal to 0.
In the else form, the second substatement is executed if the expression compares equal to 0. If the first substatement is reached via a label, the second substatement is not
executed.
So, to check for another condition, you need to have another if clause.
Compile your code with warnings enabled and you'll get to see a compiler screaming like
warning: statement with no effect [-Wunused-value]
else (num > 100)
^
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/40576669",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Dont Match escaped characters in Regex I have some string which in a sunny day scenario looks like
'abcd' => 'efgh'
Where i want to get abcd and efgh in capture groups like
"'([^']*)'\s*=>\s*'([^']*)'"
My Problem now is, that => or \\' might occur within the capture sequences. I already tried
"'([^']|[\\\\^]*)'\s*=>\s*'([^']|[\\\\']*)'"
But this did not get me to the desired result.
How do i filter out those to values?
A: Regular expressions are not the right choice, when it comes to parsing text.
Parsing for example includes the functionality of counting backslashes, quotes, etc.
Use a parser library (like ANTLR), or live with a semi-robust regular expression solution.
A: if you want to get those strings before and after "=>" you can use this:
String s = "'ab'cd' => 'e\\fg\\'h'";
Pattern p = Pattern.compile("'(.+)'\\s\\=>\\s'(.+)'");
Matcher m = p.matcher(s);
if (m.matches()) {
System.out.println(m.group(1));
System.out.println(m.group(2));
}
You will get "ab'cd" and "e\fg\'h" in this concrete case.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/41042512",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Color swatches in select list with CSS :Before pseudo element. Only works in Firefox I am working on a custom stole configurator that can be viewed here: stoles.com/stoles
The site is password protected, username is: "alex", password is: "superman".
I have a standard html select list for stole color, trim color and text color. I am trying to add color swatches to the left of each select option. I have implemented a CSS pseudo element, ":before" to accomplish this. The problem is that it only work in firefox, no chrome, safari or IE. I need it to work at least in chrome, safari, IE9+ and Firefox. Is there any way to get a color swatch next to my select option without using a crazy jquery list to select type of plugin? I'd really like to stick with a standard select list here.
Here is my code:
<select class="" name="stoleColor" id="stoleColor">
<option value="">...</option>
<option class="colorSwatch cAntiqueGold" value="antique-gold">Antique Gold</option>
<option class="colorSwatch cBlack" value="black">Black</option>
<option class="colorSwatch cBrown" value="brown">Brown</option>
<option class="colorSwatch cEmeraldGreen" value="emerald-green">Emerald Green</option>
<option class="colorSwatch cGold" value="gold">Gold</option>
<option class="colorSwatch cGreen" value="green">Green</option>
<option class="colorSwatch cHunterGreen" value="hunter-green">Hunter Green</option>
<option class="colorSwatch cLightBlue" value="light-blue">Light Blue</option>
<option class="colorSwatch cMaroon" value="maroon">Maroon</option>
<option class="colorSwatch cNavyBlue" value="navy-blue">Navy Blue</option>
<option class="colorSwatch cOrange" value="orange">Orange</option>
<option class="colorSwatch cPink" value="pink">Pink</option>
<option class="colorSwatch cPurple" value="purple">Purple</option>
<option class="colorSwatch cRed" value="red">Red</option>
<option class="colorSwatch cRoyalBlue" value="royal-blue">Royal Blue</option>
<option class="colorSwatch cSilver" value="silver">Silver</option>
<option class="colorSwatch cWhite" value="white">White</option>
</select>
And here is my CSS:
option.colorSwatch:before {
content: " ";
height: 10px;
width: 20px;
border-radius: 0px;
border:2px solid #ebebeb;
margin-right:10px;
display: inline-block;
}
option.cAntiqueGold:before {
background:#9C6600;
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/14530421",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to add a divider between each grid of RecyclerView? I need to add a divider between each grid of the RecyclerView.
RecyclerView recyclerView= (RecyclerView) profileView.findViewById(R.id.profile_recycler_view);
StaggeredGridLayoutManager layoutManager = new StaggeredGridLayoutManager(2, StaggeredGridLayoutManager.VERTICAL);
recyclerView.setLayoutManager(layoutManager);
Adapter Adapter = new Adapter(getActivity());
recyclerView.setAdapter(profileAdapter);
Please help me.
Example:
A: You need Decoration for this.
Here is the example:
public class ItemOffsetDecoration extends RecyclerView.ItemDecoration {
private int offset;
public ItemOffsetDecoration(int offset) {
this.offset = offset;
}
@Override
public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
outRect.left = offset;
outRect.right = offset;
outRect.bottom = offset;
if(parent.getChildAdapterPosition(view) == 0) {
outRect.top = offset;
}
}
}
And in your activity/fragment
grid.setLayoutManager(new GridLayoutManager(this, 2));
grid.addItemDecoration(new ItemOffsetDecoration(1));
A: I think, that Jagadesh Seeram was talking about horizontal divider between items, but RecyclerView.ItemDecoration adds divider everywhere.
If you don't use autoscroll to some item, you should write like this:
public class ItemOffsetDecoration extends RecyclerView.ItemDecoration {
private int offset;
public ItemOffsetDecoration(int offset) {
this.offset = offset;
}
@Override
public void getItemOffsets(Rect outRect, View view,
RecyclerView parent, RecyclerView.State state) {
int bottonIndex;
if (parent.getAdapter().getItemCount() % 2 == 0){
bottonIndex = parent.getAdapter().getItemCount() - 2;
} else {
bottonIndex = parent.getAdapter().getItemCount() - 1;
}
if (parent.getChildAdapterPosition(view) < bottonIndex){
outRect.bottom = offset;
} else {
outRect.bottom = 0;
}
if(parent.getChildAdapterPosition(view) > 1 ) {
outRect.top = offset;
} else {
outRect.top = 0;
}
if( (parent.getChildAdapterPosition(view) % 2 ) == 0) {
outRect.right = offset;
outRect.left = 0;
} else {
outRect.right = 0;
outRect.left = offset;
}
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/32654844",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Crash app in Thread.setDefaultUncaughtExceptionHandler I would like to crash my app on purpose after logging my own error. The Handler is registered in Application.onCreate():
// set global exception handler
Thread.setDefaultUncaughtExceptionHandler(new UncaughtExceptionHandler() {
@Override
public void uncaughtException(Thread thread, final Throwable ex) {
// unregister
Thread.setDefaultUncaughtExceptionHandler(null);
// do report ...
// crash app -does not work, app is frozen
if (ex instanceof RuntimeException)
throw (RuntimeException) ex;
throw new RuntimeException("Re-throw", ex);
}
However, my app freezes instead of crashing with a dialog. How can I crash the application as it would if I hadn't registered the handler?
A: This bit of code is never going to work.
An uncaught exception handler is called after a thread has terminated due to an exception that was not caught. If you then attempt to re-throw the exception, there will be nothing else to catch it.
*
*If you want to have your re-thrown exception handled in the normal, you have to do the logging further up the stack.
*The only other option you have is to explicitly chain to another UncaughtExceptionHandler.
I suspect that the freeze is you are experiencing is a direct consequence of the current thread dying.
FOLLOWUP:
... is there some other way in Android to intercept exceptions at a global level, without using Thread.setDefaultUncaughtExceptionHandler?
AFAIK, no.
Or how would the chaining look like?
Something like this:
public void uncaughtException(Thread thread, final Throwable ex) {
// do report ...
getSomeOtherHandler(...).uncaughtException(thread, ex);
}
Or, since ThreadGroup implements UncaughtExceptionHandler, ...
public void uncaughtException(Thread thread, final Throwable ex) {
// do report ...
thread.getThreadGoup().uncaughtException(thread, ex);
}
Basically, you just call some other handler. It's not rocket science.
But note that you can't catch and recover from an exception in the "normal" way once you've landed in one of these handlers.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/18440592",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Mysql CREATE FUNCTION syntax error CREATE DEFINER = CURRENT_USER FUNCTION GET_DISTANCE (LatBegin float,LngBegin float,LatEnd float,LngEnd float)
RETURNS float
BEGIN
DECLARE Distance FLOAT
DECLARE EARTH_RADIUS FLOAT
SET EARTH_RADIUS = 6378137.00
DECLARE dlat FLOAT
DECLARE dlng FLOAT
SET LatBegin = LatBegin * PI()/ 180.0
SET LngBegin = LngBegin * PI() / 180.0
SET LatEnd = LatEnd * PI() / 180.0
SET LngEnd = LngEnd * PI() / 180.0
SET dlat = LatBegin - LatEnd
SET dlng = LngBegin - LngEnd
SET Distance = (1-cos(dlat))/2.0+cos(LatBegin)*cos(LatEnd)*((1-cos(dlng))/2.0)
SET Distance = asin(sqrt(Distance)) * EARTH_RADIUS *2.0
SET Distance = Round(Distance * 10000,2) / 10000
RETURN Distance
END
[Err] 1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'DECLARE v_dlat FLOAT;
DECLARE dlng FLOAT;
SET LatBegin = LatBegin * PI(' at line 8
A: You've written the whole function as one big statement. You need to use delimiters. Here's the example from the MySQL manual:
mysql> delimiter //
mysql> CREATE PROCEDURE simpleproc (OUT param1 INT)
-> BEGIN
-> SELECT COUNT(*) INTO param1 FROM t;
-> END//
Query OK, 0 rows affected (0.00 sec)
mysql> delimiter ;
mysql> CALL simpleproc(@a);
Query OK, 0 rows affected (0.00 sec)
A: You must end each line/command with a ; so
BEGIN
DECLARE Distance FLOAT;
DECLARE EARTH_RADIUS FLOAT;
SET EARTH_RADIUS = 6378137.00;
etc .....
A: Add ';' as ManseUK suggested.
All declarations must be at the begining of the BEGIN...END clause -
CREATE DEFINER = CURRENT_USER FUNCTION GET_DISTANCE(LatBegin FLOAT,
LngBegin FLOAT,
LatEnd FLOAT,
LngEnd FLOAT
)
RETURNS FLOAT
BEGIN
DECLARE Distance FLOAT;
DECLARE EARTH_RADIUS FLOAT;
DECLARE dlat FLOAT;
DECLARE dlng FLOAT;
SET EARTH_RADIUS = 6378137.00;
SET LatBegin = LatBegin * PI() / 180.0;
SET LngBegin = LngBegin * PI() / 180.0;
SET LatEnd = LatEnd * PI() / 180.0;
SET LngEnd = LngEnd * PI() / 180.0;
SET dlat = LatBegin - LatEnd;
SET dlng = LngBegin - LngEnd;
SET Distance = (1 - COS(dlat)) / 2.0 + COS(LatBegin) * COS(LatEnd) * ((1 - COS(dlng)) / 2.0);
SET Distance = ASIN(SQRT(Distance)) * EARTH_RADIUS * 2.0;
SET Distance = ROUND(Distance * 10000, 2) / 10000;
RETURN Distance;
END
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/10085796",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: SQL get Distinct rows from joined tables I'm trying to determine the following from the joining of two tables:
Sample TableA: Contains 1 column consisting of unique IDs
ID Name Department
1 John IT
2 Jason Sales
3 Dany IT
4 Mike HR
5 Alex HR
Sample TableB: Contains multiple columns, including ID from TableA. For example:
ID AccountNumber WebID
1 10725 ABC1
1 10726 ABC1
1 10727 ABC1
2 20100 ABC2
2 20101 ABC2
3 30100 ABC3
4 40100 NULL
I want to get the following results:
ID Name WebID
1 John ABC1
2 Jason ABC2
3 Dany ABC3
4 Mike NULL
5 Alex NULL
I tried the following query, which is returning the correct rows for these sample tables:
Select count(a.ID), a.ID, a.Name, b.WebID from TableA a
left join TableB b on a.ID = b.ID
group by a.ID, a.Name, b.WebID
But my Actual Database tables, this query does not return correct number of rows: (30992)
TableA contains 29066 rows and TableB contains 23033 rows
The query should return 29066 rows, as it is Left Join.
When I checked the IDs that are in TableA, but not in TableB, there were 6033 rows:
Select * from TableA where ID not in (Select ID from TableB)
Am I missing something in the query?
A: TABLE B has duplicates of the ID column... the code below should work (but might not be the results you expect since I just do a max on the webid column which is fine if it is always the same but I need a rule if not)
I just saw you had a count... I added that in.
SELECT A.ID, A.Name, B.WebID
FROM TABLEA A
LEFT JOIN (
SELECT ID, MAX(WebID) AS WebID, count(*) as CNT
FROM TABLEB
GROUP BY ID
) B ON A.ID = B.ID
A: I think your query is as simple as that:
select a.ID,a.Name,b.WebID
from TableA a
left join TableB b on a.ID = b.ID
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/73980150",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Binary converter misses mscorlib on ARM I have a telegram bot written in c# and using .net-core 2.1. Now I am trying to run this application in a docker container on a raspberry pi. During the run I save a configuration file using the formatter System.Runtime.Serialization.Formatters.Binary. According to this question this binary formatter should be included in .net-core 2.1, right? But writing using the binary formatter fails with this exception. (Reading seems to work although the file is incomplete since writing always fails):
Exception when writing the modules: System.TypeInitializationException: The type initializer for 'System.Runtime.Serialization.Formatters.Binary.Converter' threw an exception. ---> System.IO.FileNotFoundException: Could not load file or assembly 'mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089'. The system cannot find the file specified.
I can run the application on windows 10, in a container in docker for windows 10 and on hypriot linux on the raspberry with ARM. The exception only happens in the docker container on the raspberry pi.
Any idea how I can solve this? Will I have to switch to a different serializer even though the binary formatter is supposed to be included in .net-core 2.1? I come from java and the easiest included approach there is binary so I just used it in c# as well.
You can find the whole project in this github project. The file dockerARM contains the docker configuration for docker on the raspberry pi. If you want to run the application you need a telegram bot API key. The whole docker-compose build log including the exception can be found here. There are a bunch of errors in the dotnet publish step I can't say I understand them. But the step succeeds.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/53101972",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Codeigniter : Grocery CRUD template doesn't exist help ...I don't know where to start debugging
I downloaded codeigniter grocery crud . installed every requirement. Now its giving me .
grocery crud template doesn't exist
libraries / grocery_crud.php
at line 1388...
EDIT
if(!file_exists($this->theme_path.$this->theme.'/views/list_template.php'))
{
throw new Exception('The template does not exist. Please check your files and try again.', 12);
die();
}
It has something to do with this code..... I cant find list_template.php
even in the downloaded zip file
A: dump($this->theme_path); and dump($this->theme); and check what is the path in these objects if the root path is ok than check your directory that you have this file or not
your_project_folder\assets\grocery_crud\themes\datatables\views\list_template.php
your_project_folder\assets\grocery_crud\themes\flexigrid\views\list_template.php
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/15944446",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: AWS S3 as Docker volume?
I'm trying to set up a Gitlab CI Pipeline using Docker on AWS EC2. Everything worked as expected until I hit the storage cap on my EC2 instance (8GB). As I quickly learn, a pipeline could easily use up 1-2 GB of data. Having 4 on the server and everything stop.
Granted I could look into optimising Docker storage usage e.g. using Alpine, however I do need a more permanent solution because 8GB would hardly suffice.
I have been trying to use s3 bucket, with s3fs, as Docker volume to handle my data hunger pipelines but to no avail. Docker volume use hardlinks which are not supported by s3fs.
Is this possible to configure Docker to use symlink instead? Or alternatively, if are there other packages which mount s3 as a "true" filesystem?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/47648430",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: How to make link underline effect that transitions from left to the right in Tailwind? I can make a growing underline effect which will grow to full width and then shrink to its origin:
<a href="#" class="group font-normal">
Home
<span class="block max-w-0 group-hover:max-w-full transition-all h-0.5 bg-slate-200"/>
</a>
How do I create a similar effect but with the underline exiting to the right like in version 1 of this demo
A: Something like this I believe you looking for
<a href="#" class="hover:before:scale-x-100 hover:before:origin-left relative before:w-full before:h-1 before:origin-right before:transition-transform before:duration-300 before:scale-x-0 before:bg-red-500 before:absolute before:left-0 before:bottom-0 ">
Hover me
</a>
The trick here is to change CSS transform-origin direction on hover
before:origin-right hover:before:origin-left
A: use this as your base and add your styles to it
this one goes to left
<button class="relative py-1 after:absolute after:bottom-0 after:left-0 after:w-full after:scale-x-0 hover:after:scale-x-100 after:transition-all after:origin-left after:h-[2px] after:bg-black">Hover Me</button>
and this one to right
<button class="relative py-1 after:absolute after:bottom-0 after:left-0 after:w-full after:scale-x-0 hover:after:scale-x-100 after:transition-all after:origin-right after:h-[2px] after:bg-black">Hover Me</button>
chnage origin-[direction] to whatever direction you want
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/74597491",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Default to an empty array whenever column is nil Like the title says, I would like to set a model's default value to an empty array whenever it's nil. Is there any ideal way to do this? The fields are serialize in the db, should be an array at all times.
I was thinking about doing something like:
before_validation :set_defaults
def set_defaults
some_field ||= []
other_field ||= []
end
A: why do you wish to have an empty array as a default column values? That isn't correct to assign an empty array to value of DB column, because it must be specifically serialized. Instead define methods in model, which will return empty array for specific column:
def some_field
read_attribute(:some_field) || []
end
def other_field
read_attribute(:other_field) || []
end
But better way is to define that methods not in model, but in a serializer or decorator.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/34519742",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: angularjs material design nested list I want to create nested list (tree) in my application exactly like below. Please suggest me how can i create list like this .
A: As of Angular 1.2 you can use ng-start/ng-end to create nested trees/iterate over nested lists.
<md-list flex>
<md-list-item style="margin-left: 10px;"ng-repeat-start="item in nestedList">{{item.id}}</md-list-item>
<md-list-item style="margin-left: 50px;" ng-repeat-end ng-repeat="child in item.children">{{child.id}}</md-list-item>
</md-list>
http://codepen.io/jdeyrup/pen/JRPNyW
A: Unfortunately, as to the last releases of angular material, there is no such directive to make a tree menu like that, you should combine different directive such as the sidebar and the vertical menu.
I used the sidebar in my project:
<section class="wrapper" layout="row" flex>
<md-sidenav class="md-sidenav-left md-whiteframe-z3 background-red" md-component-id="left" md-is-locked-open="$mdMedia('gt-md')">
<md-toolbar>
<img class="logo" src="images/logo.png" />
</md-toolbar>
<md-content ng-controller="LeftCtrl">
<menu></menu>
<md-button ng-click="close()" class="md-primary" hide-gt-md>
Close Sidenav Left
</md-button>
</md-content>
<div flex></div>
<div class="copy">Copyright © 2015</div>
</md-sidenav>
<md-content class="wrapper" flex>
<div class="wrapper ngview-wrapper" layout="column" layout-fill layout-align="top center" ng-view></div>
<div flex></div>
</md-content>
</section>
You won't need the part that handle opening and closing of the sidebar.
Inside the menu directive you will be able to put everything you want as menu
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/34257902",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: using VBA to hide various rows based on changing cell value I presently have the following coding:
Private Sub Worksheet_Change(ByVal Target As Range)
Dim arCases As Variant
Dim res As Variant
arCases = Array("Term", "Indeterminate", "Transfer", "Student", "Term extension", "As required", "Assignment", "Indéterminé", "Mutation", "Selon le besoin", "Terme", "prolongation du terme", "affectation", "Étudiant(e)")
If Target.Address <> "$C$37" Then Exit Sub
res = Application.Match(Target, arCases, 0)
If IsError(res) Then
Rows("104:112").Hidden = False
Else
Rows("104:112").Hidden = True
End If
End Sub
The issue that I am having is that I need to add to this such as if value in Cell C37 is "X" then rows 42:49 are hidden and if value on Cell H4 is "Y" then rows 101:114 are hidden...etc.....
can you advise on how do so?
A: You need to change that condition to only execute the code if it matches the cell address, rather than not execute the code unless the address is matched. This will allow you to add further conditions matched on cell address.
I'd recommend changing a hard-coded cell address like "$C$37" to a named range and that named range should ideally be unique throughout the workbook.
arCases = Array("Term", "Indeterminate", "Transfer", "Student", "Term extension", "As required", "Assignment", "Indéterminé", "Mutation", "Selon le besoin", "Terme", "prolongation du terme", "affectation", "Étudiant(e)")
If Target.Address = "$C$37" Then
res = Application.Match(Target, arCases, 0)
If IsError(res) Then
Rows("104:112").Hidden = False
Else
Rows("104:112").Hidden = True
End If
ElseIf Target.Address = "$H$4" Then
' Do something else
End If
End Sub
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/53063061",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: If "match" else In XSLT I often match nodes using the following command
<xsl:template match="*[local-name() = 'Proposal']/*[local-name() = 'ApplicationData']">
which would get the nodes from
<?xml version="1.0" encoding="utf-8"?><?xfa generator="XFA2_4" APIVersion="2.8.9029.0"?>
<xdp:xdp xmlns:xdp="http://ns.adobe.com/xdp/" timeStamp="2013-03-01T09:48:58Z" uuid="3e3468da-104d-4532-8077-0dc001ca166b">
<xfa:datasets xmlns:xfa="http://www.xfa.org/schema/xfa-data/1.0/">
<xfa:data>
<Proposal xmlns="http://www.govtalk.gov.uk/planning/OneAppProposal-2006" Version="">
<oneapp:ApplicationData xmlns:oneapp="http://www.govtalk.gov.uk/planning/OneAppProposal-2006">
<oneapp:TreesHedgesWales/>
<oneapp:OtherLowCarbonEnergy/>
</oneapp:ApplicationData>
</Proposal>
...
matching
<oneapp:ApplicationData xmlns:oneapp="http://www.govtalk.gov.uk/planning/OneAppProposal-2006">
<oneapp:TreesHedgesWales/>
<oneapp:OtherLowCarbonEnergy/>
</oneapp:ApplicationData>
How could I determine whether ApplicationData existed, and if not, insert it?
A: You would need to add the logic to a template that matched the 'Proposal' element
<xsl:template match="*[local-name() = 'Proposal']">
Then, you would just write an xsl:if statement, like so:
<xsl:if test="not(*[local-name() = 'ApplicationData'])">
<oneapp:ApplicationData xmlns:oneapp="http://www.govtalk.gov.uk/planning/OneAppProposal-2006">
<oneapp:TreesHedgesWales/>
<oneapp:OtherLowCarbonEnergy/>
</oneapp:ApplicationData>
</xsl:if>
You would need to wrap this in an xsl:copy if you wanted to retain the Proposal element.
If you didn't already have an existing template matching Proposal in your XSLT, you could add the test to template match itself
<xsl:template match="*[local-name() = 'Proposal'][not(*[local-name() = 'ApplicationData'])]">
<xsl:copy>
<oneapp:ApplicationData xmlns:oneapp="http://www.govtalk.gov.uk/planning/OneAppProposal-2006">
<oneapp:TreesHedgesWales/>
<oneapp:OtherLowCarbonEnergy/>
</oneapp:ApplicationData>
</xsl:copy>
</xsl:template>
As michael.hor257k mentioned in comments, it would be much cleaner if you declared your namespaces in your XSLT, and used namespace prefixes in the matching....
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0"
xmlns:oneapp="http://www.govtalk.gov.uk/planning/OneAppProposal-2006">
<xsl:template match="oneapp:Proposal[not(oneapp:ApplicationData)]">
<xsl:copy>
<oneapp:ApplicationData>
<oneapp:TreesHedgesWales/>
<oneapp:OtherLowCarbonEnergy/>
</oneapp:ApplicationData>
</xsl:copy>
</xsl:template>
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/27021941",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: AWS EC2 - yum update does not work in AutoScaling LaunchConfig UserData I can successfully run sudo yum update when ssh-ing to my EC2 instance. However, when I attach the same command to the userData of my launch configuration, I see the following error (in /var/log/cloud-init-output.log):
launch script..
Loaded plugins: extras_suggestions, langpacks, priorities, update-motd
One of the configured repositories failed (Unknown),
and yum doesn't have enough cached data to continue. At this point the only
safe thing yum can do is fail. There are a few ways to work "fix" this:
My script:
#!/bin/bash
echo "launch script.."
sudo yum update -y
sudo yum install java-1.8.0 -y
aws s3 cp s3://bucket/app.jar ./app.jar
java -jar app.jar >> out.log
How can I run yum commands at EC2 instance startup?
A: Make sure that you actually have a route to the internet from your EC2 instance. That typically means either a public IP or a route to a NAT instance/gateway, and an Internet Gateway in your VPC.
It may be that the userdata script begins to run before connectivity has been established. You may need to verify that the instance has outbound network access before your script runs yum update, for example:
#!/bin/bash
echo "launch script.."
until ping -c1 www.google.com &>/dev/null; do
echo "Waiting for network ..."
sleep 1
done
yum update -y
# other things here
There are other options to wait for the network (here and here).
Also note that user data scripts are executed as the root user, so you do not need sudo.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/54050975",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to get cell on label or imageview tap - UITapGestureRecognizer My goal is to perform segue when i tap on imageview of that cell. but the error does not appear when i use addTarget on a button.
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
{
cell.imageView.userInteractionEnabled = true
let tapImageView = UITapGestureRecognizer(target: self, action: #selector(HomeFeedViewController.tapImageView(_:)))
cell.imageView.addGestureRecognizer(tapImageView)
return cell as CastleCell
}
func tapImageView(sender: AnyObject) {
let center = sender.center
let point = sender.superview!!.convertPoint(center, toView:self.tableView) //line of error
let indexPath = self.tableView.indexPathForRowAtPoint(point)
let cell = self.tableView.cellForRowAtIndexPath(indexPath!) as! CastleCell
performSegueWithIdentifier("SegueName", sender: self)
}
The line of error is let point =...
The error i get is:
fatal error: unexpectedly found nil while unwrapping an Optional value
(lldb)
but the error does not appear when i use addTarget on a button. what could be wrong? thanks.
A: Am not really fond of playing with points and Superview. What is can suggest is to make a class for UITapGestureRecognizer as follows which can hold extra data. In your case it would be an index path
class CustomGesture: UITapGestureRecognizer {
let indexPath:NSIndexPath? = nil
}
And then in your didSelect you can add the index path to the newly created CustomGesture class which be would be like:
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
{
cell.imageView.userInteractionEnabled = true
let tapImageView = CustomGesture(target: self, action: #selector(HomeFeedViewController.tapImageView(_:)))
tapImageView.indexPath = indexPath// Add the index path to the gesture itself
cell.imageView.addGestureRecognizer(tapImageView)
return cell as CastleCell
}
Now since you have added the indexPath you don't need to play around with super view's and you can access the cell like this:
func tapImageView(gesture: CustomGesture) {
let indexPath = gesture.indexPath!
let cell = self.tableView.cellForRowAtIndexPath(indexPath!) as! CastleCell
performSegueWithIdentifier("SegueName", sender: self)
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/38961052",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
}
|
Q: Aurelia binding for button callback function I want to pass an array of objects that define buttons to a custom element, like this:
<my-panel header="My Title"
view-buttons.bind="[{icon: 'fa-plus', display: 'New', action: onNew}]">
</my-panel>
In my custom element, I'm displaying the buttons like this:
<button repeat.for="btn of viewButtons" class="btn btn-default" click.delegate="goButton(btn)">
<i class="fa ${btn.icon} fa-fw"></i> ${btn.display}
</button>
The called function in my custom element's view-model is:
goButton(btn) {
if (btn.action) {
btn.action();
}
}
The called function in my parent view-model is:
onNew() {
window.alert("HORRAY!!! Now why is this not working?");
console.log("view=", this.view); // should be 'home', but displays 'undefined'
this.view = 'new_view';
}
The button displays correctly and I get the window.alert message which means the parent function was called. However, it appears that the scope/context of the function is wrong (it's not seeing or updating the parent's this.view).
What am I doing wrong? My guess is that it's related to action: onNew but I don't know how to fix it. If it were a bound parameter, I think I could use action.call="onNew" but not in an array of objects. Help!
A: That's how javascript works. To solve this you can use:
{icon: 'fa-plus', display: 'New', action: this.onNew.bind(this) }
Running example: https://gist.run/?id=cefe45c5a402c348d01d41d9cde42489
Explanation:
https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_objects/Function/bind
Javascript call() & apply() vs bind()?
https://alexperry.io/personal/2016/04/03/How-to-use-apply-bind-and-call.html
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/41984741",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Calling functions inside functions in sequence I started studiyng python this week, its my first language and this is my first question.
I've been trying to learn by myself and this is one of the projects that i'm currently working on to study.
The results should be:
When you use one of the arrow keys(let's call, make a choice), it should print a message and call a function that leads to other choices to be made, and so on.
The purpose of the game its to walk around a house, meaning you can enter the rooms in sequence, and even go back to previous one.
Sorry in advance if i've not made myself clear.
I'm posting just a part of the code(this is like a essencial part), so I can just know how it's done, and get the others part to work.
When I run my code, I can only get the output from the function on_press_outside, it's not jumping to the next one when I make an input. So i looks like I'm stuck in that function. For exemple, when I press the up arrow key, on the "on_press_outside" it should lead me to "on_press_hall", in "on_press_hall" i should be able now to press, for exemple, the right arrow key, and would led me to the "on_press_living", and so on. In resume, in this code, I'm stuck at "on_press_outside", I can't jump to next function and the print even repeats if the input repeats.
Thank You!
from pynput.keyboard import Key, Listener
print("Welcome!")
print("Here, you will walk through my house")
print("\nNow, You'll find yourself outside")
print("To return to your previous room, press the Down arrow key")
print("Are you going to the entrance hall(up), or the garage(right)?")
def on_press_outside(key):
while True:
if key == Key.up:
print("You are now at the entrance hall, do you want to go to the kitchen(left) or to the living room(right)")#print the message that appears when select the Hall
on_press_hall(key) #means you entered the Hall and can now
break #choose the possibilities of the function on_press_hall
elif key == Key.right:
print("You are now at the garage, do you want to go the kitchen(right) or to the bathroom(up)")
#on_press_garage(key) --> I have not created this one yet
break
elif key == Key.down:
print("You are oustide, are you going to the entrance hall(up), or the garage(right)?")
on_press_outside(key) #go back to the starting function, so the choice can be made again
break
else:
print("Please, use the correct arrow keys on your keyboard!")
break
def on_press_hall(key):
while True:
if key == Key.right:
print("You are now at the living room, do you want to stay and watch some TV(Up, This ends the game), or do you want to go back to the Hall(down)")
#on_press_living(key) --> I have not created this function yet
break
elif key == Key.left:
print("You are at the kitchen, are you going to the garden(up) or the laundry room(right)?")
#on_press_kitchen(key) --> I have not created this function yet
break
elif key == Key.down:
print("You are oustide, are you going to the entrance hall(up), or the garage(right)?")
on_press_outside(key) #go back to the starting function, so the choice can be made again
break
else:
print("Please, use the correct arrow keys on your keyboard!")
break
with Listener(
on_press1=on_press_hall,
on_press=on_press_outside) as listener:
listener.join()
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/67824016",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Laravel remove single data from a many to many pivot table i'm trying to delete single item in my pivot table, and i don't know how to make it work? is it possible? if my method is wrong please correct me . i will show below my own approach.
This is getting the list of level attached that belongs to the term id, and when you click the Edit Button you will go to the second page..
Now displaying the levels which belongs to the term_id and here you can check the checkbox if you want to remove the level.
Now this is my questions:
*
*how to delete the selected level if i check the particular checkbox.
*inside my form action what route should i put<form action="#" method="POST" >in order to point it to the delete function.
*do i need to create Route::post in my router?to perform delete action
Here is my controller:
public function edit_term($id){
$terms = Term::with('level')->where('id','=',$id)->get();
return view('term_level.edit',compact('terms'));}
public function detach_term($id)
{//this is for deleting the data}
Here is my route:
Route::get('term/get/{id}/edit', 'ListController@edit_term');
Route::post('term/get/{id}/edit', 'ListController@detach_term');
Blade:
<form action="term/get/{id}/deleteLevel/{levelId}" method="POST" >{{ csrf_field() }}
@foreach($terms as $term)
@foreach($term->level as $levels>
<input type="checkbox" name="level_id[]" value="{{ $levels->id }}">
{{ $levels->levelname }}
@endforeach
@endforeach
A: You need term id and level id in `detach_term
Route
Route::post('term/{id}/deleteLevel', 'ListController@detach_term');
Controller Action
public function detach_term(Request $request, $id)
{
$term = Term::with('level')->find($id);
if($term){
$postData = $request->all();
$term->level()->detach($postData['level_id']);
return redirect('term/get/' . $term->id);
}else{
abort(400, 'Invalid term');
}
}
Html Form in (term/get/2/edit) (Be sure you have $term sent from controller to view)
<form action="/term/{{$term->id}}/deleteLevel" method="POST" >
{{ csrf_field() }}
@foreach($term->level as $levels>
<input type="checkbox" name="level_id[]" value="{{ $levels->id }}">
{{ $levels->levelname }}
@endforeach
<button type="submit">Delete</button>
</form>
Check Attaching / Detaching of https://laravel.com/docs/5.6/eloquent-relationships#many-to-many
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/51131193",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Create woocommerce order with gravity forms metadata I have a interesting and bit complicated task to do with gravity forms and Woocommerce.
On our website, we offer free sample to every new customer registered. We tried to build something like as soon as new user fill their details like email, name and address as well as the free sample they want to get and submit, it should create an order in Woocommerce. Is it possible with gravity forms or its not possible at all?
I tried myself, it didn't work for me.
A: It's possible, but there are a lot of variables that need to be taken into consideration, so it's really hard to help without you doing an attempt first.
This will only show you where to start, you need to figure out the rest:
add_action( 'gform_after_submission', 'post_to_third_party', 10, 2 );
function post_to_third_party( $entry, $form ) {
global $woocommerce;
// use this to find out $entry output
var_dump($entry);
// Make sure to add hidden field somewhere in the form with product id and define it here, If you have some other way of defining products in the form you need to make sure product id is returned in the variable below somehow
$product_id = rgar( $entry, '12' );
$address = array(
'first_name' => rgar( $entry, '5' ),
'last_name' => rgar( $entry, '2' ),
'company' => rgar( $entry, '3' ),
'email' => rgar( $entry, '4' ),
'phone' => rgar( $entry, '5' ),
'address_1' => rgar( $entry, '6' ),
'address_2' => rgar( $entry, '7' ),
'city' => rgar( $entry, '8' ),
'state' => rgar( $entry, '9' ),
'postcode' => rgar( $entry, '10' ),
'country' => rgar( $entry, '11' ),
);
$prices = array( 'totals' => array(
'subtotal' => 0,
'total' => 0,
) );
$order = wc_create_order();
$order->add_product( wc_get_product($product_id), 1, $prices);
$order->set_address( $address, 'billing' );
$order->calculate_totals();
$order->update_status("processing", 'Sample Order', TRUE);
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/47296951",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Cutting a time elapsed variable into manageable things flight_time
11:42:00
19:37:06
18:11:17
I am having trouble working with the time played variable in the dataset. I can't seem to figure out how to get R to treat this value as a numeric.
Apologies if this has been asked before.
EDIT:
Okay well given the stuff posted below I've realised there's a few things I didn't know/check before.
First of all this is a factor variable. I read through the lubridate package documentation, and since I want to perform arithmetic operations (if this is the right terminology) I believe the duration function is the correct one.
However looking at the examples - I am not entirely sure what the syntax is for applying this to a whole column in a large(ish) data from. Since I have 4.5k observations, I'm not sure exactly how to appply this. I don't need an excessive amount of granularity - ideally even hours and minutes are fine.
So I'm thinking I would want my code to look like:
conversion from factor variable to character string > conversion from character string to duration/as.numeric.
A: Try this code:
#dummy data with factors
df <- data.frame(flight_time=c("11:42:00","19:37:06","18:11:17"))
#add Seconds column
df$Seconds <-
sapply(as.character(df$flight_time), function(i)
sum(as.numeric(unlist(strsplit(i,":"))) * c(60^2,60,1)))
#result
df
# flight_time Seconds
# 1 11:42:00 42120
# 2 19:37:06 70626
# 3 18:11:17 65477
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/30360175",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Calculations with JavaScript without submitting the form I have a couple of buttons on my form that do mileage calculations and the other updates the cost. These work as expected but they also submit the form.
Here are the fields:
@Html.EditorFor(model => model.Miles, new { htmlAttributes = new { @class = "form-control", @id = "number" } })
<button onclick="roundTrip()">Round Trip?</button>
<button onclick="updatedPrice()">Update Price</button>
@Html.EditorFor(model => model.Cost, new { htmlAttributes = new { @class = "form-control", @id = "price" } })
Here is my JavaScript:
function updatedPrice() {
var price = $("#number").val() * @calcMiles;
var calPrice = price.toFixed(2)
$("#price").val(calPrice);
}
function roundTrip() {
var calc = $("#number").val() * 2;
$("#number").val(calc);
}
Maybe I need to do a replace? Not sure why it submits when I click either one of these.
Thanks for your help!
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/69110566",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to enable offline reading in my application? Context
I have a news activity which contains a ListView . Each item in the list contains some text and one image. Now every time the user opens the activity, the application makes a request to the server for getting data. Unfortunately if the user doesn't have an active internet connection, I simply put a Toast saying "Please check your internet connection"
Requirements
I would like to show news article from the last session if the user doesn't have an active internet connection. I define session as the time when user launches the activity and exits it by pressing back button.
Libraries used
I am using Retrofit Library for making Http Requests and Picasso for loading images.
What I have tried so far
While exploring Retrofit, I found out that retrofit by default caches the response for some time. So without any internet connection also I am able to get the data. In Picasso also, I found that we can save the image to any location on the device.
How to go for its Implementation ?
Since it will be a big change in my application, I wanted to know what is the best way to enable offline reading using the above two libraries? How do other applications manage to do so? Also if I can get some references or some blogs regarding this implementation, then it would be great.
A: Use the internal storage of the application.
Parse the image to a byteArray and the text to a single String so you can easily convert this also to a byteArray.
Name the files so you can easily retrieve them and link them back together.
A: You can storage the last updated data on local, with SharedPreferences or json file.
Instead of show toast, you can load the last updated data from local.
A: Picasso is a good choice for images, it saves images locally and reuse it automatically later.
For your items, I suggest to use a small local DataBase : in Android, we use SQLiteDataBase. here is a small tutorial : http://www.androidhive.info/2011/11/android-sqlite-database-tutorial/
So, I suggest you this pattern
*
*user opens activity
*system retrieves data from database
*in parallel, system starts to download the new items.
*When new items have been downloaded, you should notice user like 9gag or Facebook apps do.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/34391710",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Simple if statement question for record not found I've got the following statement:
@all_comments = Comment.find(@task.id)
The problem is, if there are no comments it throws a record not found error. How can I get this to fail silently, so it just returns nothing?
A: what you are trying to do can never work.
The line find(@task.id) will look for comments that have the same id as the task which is normally not how you set up relations.
Normally you would have a task, and a comments table, and the comments table would have a column called task_id. If that is the case, you could write your models as follows:
class Task
has_many :comments
end
class Comment
belongs_to :task
end
and then you can simply write:
@all_comments = @task.comments
A: I don't use AR, but I believe just:
@all_comments = Comment.find(:first, @task.id)
will return nil if there is no record found, unlike #find without any modifiers.
EDIT | There's a shortcut too:
@all_comments = Comment.first(@task.id)
A: I think that your failure is a different one you expect. Your query asks for a Comment with the ID @task.id (which is the ID of the Task).
Your query should go like that:
@all_comments = Comment.where(:task_id => @task.id)
or even better
@task.comments
This should work if you have declared your relations accordingly, and allows some more options (adding comments, ...).
Have a look at the "Rails Guides", and there the "Active Record Query Interface".
A: The rails throws RecordNotfound exception for find calls. Use find_by calls to avoid this.
If you are trying to get a list of tasks by task_id then user the find_all_by method:
# returns an empty array when no tasks are found
@comments = Comment.find_all_by_task_id(@task.id)
Otherwise use find_by
# returns nil when no task is found
@comment = Comment.find_by_task_id(@task.id)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7554284",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Can anyone suggest how to implement the sorting by price of a product in android Recycler View As I needed to sort the values of an array List, I'm unable to get the sorting algorithms for the different algorithms like Selection sort, quick sort and bubble sort. I'm new to Android app development, please help me to solve this. thanks in advance
public class TestingSort {
public static void main(String args[]){
ToSort toSort1 = new ToSort(new Float(3), "3");
ToSort toSort2 = new ToSort(new Float(6), "6");
ToSort toSort3 = new ToSort(new Float(9), "9");
ToSort toSort4 = new ToSort(new Float(1), "1");
ToSort toSort5 = new ToSort(new Float(5), "5");
ToSort toSort6 = new ToSort(new Float(0), "0");
ToSort toSort7 = new ToSort(new Float(3), "3");
ToSort toSort8 = new ToSort(new Float(-3), "-3");
List<ToSort> sortList = new ArrayList<ToSort>();
sortList.add(toSort1);
sortList.add(toSort2);
sortList.add(toSort3);
sortList.add(toSort4);
sortList.add(toSort5);
sortList.add(toSort6);
sortList.add(toSort7);
sortList.add(toSort8);
Collections.sort(sortList);
for(ToSort toSort : sortList){
System.out.println(toSort.toString());
}
}
}
public class ToSort implements Comparable<ToSort> {
private Float val;
private String id;
public ToSort(Float val, String id){
this.val = val;
this.id = id;
}
@Override
public int compareTo(ToSort f) {
if (val.floatValue() > f.val.floatValue()) {
return 1;
}
else if (val.floatValue() < f.val.floatValue()) {
return -1;
}
else {
return 0;
}
}
@Override
public String toString(){
return this.id;
}
}
A: You need to use Comparator with Collections.sort()
Collections.sort(YourArraylist, new Comparator<ModelObject>(){
public int compare(ModelObject o1, ModelObject o2){
return o1.getPrice() - o2.getPrice();
}
});
If you are using Java 8, You can use following code.
Collections.sort(YourArraylist, (o1, o2) -> o1.getPrice() - o2.getPrice());
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/54703812",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-5"
}
|
Q: Amazon AWS EC2 Dashboard and SSH - Saving Text Files to Volumes As a new user of SSH and the Amazon AWS EC2 Dashboard, I am trying to test to see whether I can, in one instance, save data onto a volume, then access that data from another instance by adding the volume to the instance (after terminating the first instance).
When I create the first instance, the AMI is "Amazon Linux AMI 2014.03.2 (HVM)" and the family is "general purpose" with EBS storage only. I automatically assign a public IP address to the instance. I configure the root volume so that it does NOT delete on termination.
As soon as the instance is launched, I open up PuTTY and set the host name to the instance's Public IP Address under Port 22, and authenticate using a private key saved onto the disc that I have already generated earlier.
Upon signing into the instance, I create a text file by typing the following code:
echo "testing">test.txt
I then confirm that the text "testing" is saved to the file "test.txt":
less test.txt
I see the text "testing", thus confirming that it is saved to the file. (I am assuming at this point that it is saved onto the volume, but I am not entirely sure.)
I then proceed to terminate the instance. I launch another one using the same AMI, same instance type, and a different public IP address. In addition to the root volume, I attempt to add the volume that was used as the root volume for the previous instance. (Oddly enough, the snapchat IDs for the previous volume and the root volume of the new instance are identical.) In addition, I use the same tag instance, the same security group and the same key pair as the previous instance.
I open up PuTTY again, this time using the Public IP Address of the new instance, but still using the same private key and port used for the previous instance. Opening logging in, I type:
less test.txt
but I am greeted with this message:
test.txt: No such file or directory
Is there any advice that anyone can offer me regarding this issue. Is it even possible to store a text file onto a volume? If so, am I performing this operation incorrectly?
A: As the secondary volume has the same UUID and the Amazon Linux used UUID based identification for root, then there might be a chance that the secondary volume was taken as the root volume. This may be the reason why there would be a mess up in choosing the root volume and the initial attempt to find test.txt would fail.
The reboot might have allowed it to take a different order which is why you were able to find it.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/24998831",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Python cannot import name from some scipy.signal methods import numpy as np
from scipy.integrate import odeint
from scipy.signal import find_peaks
The third line triggers the following error:
ImportError: cannot import name find_peaks
What is going on here? I haven't made any changes to the scipy package that I am aware of. Also it is worth noting that just importing scipy.signal does not produce an error.
A: Check your scipy version:
import scipy
print(scipy.__version__)
find_peaks is new in version 1.1.0.
If you want to update:
pip install scipy --upgrade
A: I just had to reinstall scipy and it worked on Mac OS with M1 and Python 3.9
pip uninstall scipy
and then
pip install scipy
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/52999871",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: Send email notification when new work item created in Azure DevOps I have a requirement like, send an email notification with work item id when new work item created in Azure DevOps.
Is it possible to configure a notification with new work item id?
A: User ADO service hooks: https://learn.microsoft.com/en-us/azure/devops/extend/develop/add-service-hook?view=azure-devops
Search through available list and there you will see possible actions to react on. API hooks allows you to receive data based on Boards changes (e.g. Task status change etc).
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/71255429",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to recognize a plugin that is good for Vundle ? - Vim I'm in trouble with some plugins, I can't say if they are for Vundle or not, as a consequence I can't say if the problem is Vundle itself or not, most of the vim docs are horribly paginated, so I'm asking, there is a way to know for sure that a plugin is designed to run under Vundle ?
A: Plugins are generally not designed for use with a specific plugin manager. They all use more or less the same mechanisms and standardized file structure and should work the same way whether they are installed manually or "managed" with Vundle, Pathogen or some other script.
You should read Vundle's and your non-working plugin's documentation to see if you can find the why and how of your issue.
Also, what plugins do you have issues with? How did you install them? Are you asking a question with the hope of getting help or just thinking out loud?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/16822230",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-4"
}
|
Q: FsRtlIsNameInExpression never matches anything I do string matching in a kernel driver using the Boyer-Moore algorithm, but I also need to implement basic wildcard support. This answer on SO mentionned the function FsRtlIsNameInExpression, which looks just right for my needs. It even looks like it handles case insensitivity for Unicode strings.
But it can't even get it to match a simple string with itself.
I tried a few things, but FsRtlIsNameInExpression never matches anything. Here is some code I used to test (I put the call to MyTest at the end of my DriverEntry routine).
NTSTATUS MyTest()
{
int matches = 0;
UNICODE_STRING a3times;
UNICODE_STRING A5times;
UNICODE_STRING bbb;
UNICODE_STRING patterna;
UNICODE_STRING patternb;
RtlInitUnicodeString(&a3times, L"aaa");
RtlInitUnicodeString(&A5times, L"AAAAA");
RtlInitUnicodeString(&bbb, L"bbb");
RtlInitUnicodeString(&patterna, L"a*a");
RtlInitUnicodeString(&patternb, L"b*");
if(FsRtlIsNameInExpression(&patterna, &a3times, TRUE, 0))
++matches; // a*a should match aaa
if(FsRtlIsNameInExpression(&patterna, &A5times, FALSE, 0))
++matches; // a*a should match (insensitive) AAAAA
if(FsRtlIsNameInExpression(&a3times, &a3times, TRUE, 0))
++matches; //aaa should match aaa
if(FsRtlIsNameInExpression(&patternb, &bbb, TRUE, 0))
++matches; //b* should match bbb
return matches; //Should be 4, but is 0
}
For the record :
*
*I am using WDK version 7600.16385.1, checked build (my code, not Windows)
*The driver runs in a Virtual Box hosted Windows 7 Pro 64 bits on my Windows 7 Ultimate 64 bits
*The driver is signed by a test certificate
*I trace the code in a kernel debugger
*The code does not crash, but can't be called in user mode
What is the obvious that I am missing ?
A: The documentation says
If IgnoreCase is TRUE, Expression must be uppercase.
Note that, per your comments, you misunderstood the case-sensitivity parameter. It is IgnoreCase not CaseSensitive.
As for the results:
*
*Lower-case expression with IgnoreCase set to TRUE - won't work
*Lower-case expression, IgnoreCase set to FALSE, upper case pattern - won't match
*Lower-case expression with IgnoreCase set to TRUE - won't work
*Lower-case expression with IgnoreCase set to TRUE - won't work
Just really bad luck that not a single one worked :)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/10492118",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: Spring Data JDBC - Clob column to String property in POJO not working I have an Oracle database with a table that has a DESCRIPTION column of type CLOB.
My POJO looks like this:
import java.util.Date;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import org.springframework.data.relational.core.mapping.Column;
import org.springframework.data.relational.core.mapping.Table;
import org.springframework.data.annotation.Id;
import lombok.Data;
@Data
@Table("MY_ITEMS")
@JsonIgnoreProperties(ignoreUnknown = true)
public class MyItem {
@Column("ID") @Id Long id;
@Column("DESCRIPTION") String description;
}
And my repository looks like this
import java.util.List;
import com.myapp.mymodel.MyItem;
import org.springframework.data.jdbc.repository.query.Query;
import org.springframework.data.repository.CrudRepository;
public interface MyItemsRepository extends CrudRepository<MyItem, Long> {
// other methods deleted...
@Query(
"select m.ID"
+ ", m.DESCRIPTION"
+ " from MY_ITEM m "
)
List<MyItem> findMyItems();
}
When I call the repository method I get an error saying there is no converter for CLOB to String.
Any help is appreciated.
A: There's a very nice example here that solves the problem:
https://github.com/spring-projects/spring-data-examples/tree/master/jdbc/basics
The solution amounts to adding a configuration that registers a converter that can extract the CLOB data to the String property
import java.sql.Clob;
import java.sql.SQLException;
import java.util.Arrays;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.convert.converter.Converter;
import org.springframework.data.jdbc.core.convert.JdbcCustomConversions;
import org.springframework.data.jdbc.repository.config.AbstractJdbcConfiguration;
import org.springframework.data.jdbc.repository.config.EnableJdbcRepositories;
import org.springframework.data.relational.core.mapping.Embedded.Nullable;
@Configuration
@EnableJdbcRepositories
public class AggregateJdbcConfiguration extends AbstractJdbcConfiguration {
@Override
public JdbcCustomConversions jdbcCustomConversions() {
return new JdbcCustomConversions(Arrays.asList(new Converter<Clob, String>() {
@Nullable
@Override
public String convert(Clob clob) {
try {
return Math.toIntExact(clob.length()) == 0 //
? "" //
: clob.getSubString(1, Math.toIntExact(clob.length()));
} catch (SQLException e) {
throw new IllegalStateException("Failed to convert CLOB to String.", e);
}
}
}));
}
}
Here are a few of my favorite videos on the subject
https://www.youtube.com/watch?v=EaHlancPA14&list=PLsC0nE-wJ1I4ra6KYXTPOXipdrJ_IdhaO&index=3&t=0s
https://www.youtube.com/watch?v=GOSW911Ox6s&list=PLsC0nE-wJ1I4ra6KYXTPOXipdrJ_IdhaO&index=4&t=59s
https://www.youtube.com/watch?v=AnIouYdwxo0&list=PLsC0nE-wJ1I4ra6KYXTPOXipdrJ_IdhaO&index=5&t=2730s
And a couple of blog posts
https://spring.io/blog/2018/09/24/spring-data-jdbc-references-and-aggregates
https://spring.io/blog/2018/09/17/introducing-spring-data-jdbc
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/60041952",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: I can no longer debug classic asp code with visual studio 2008 I've finally found a way to debug classic asp code in visual studio 2008 ... but...
has anybody been able to debug asp classic code with visual studio 2005 or later?
... but ...
it only lasted a few days...
I'm following these steps
http://www.codeproject.com/KB/debug/DebugVBScriptVS2008.aspx
http://codepagoda.com/2009/04/30/debugging-classic-asp-with-visual-studio-2008-sp1-and-35-framework/
but now, when I do "attach process" I can no longer see the "Script, x86" process anymore...
so I can not debug classic asp code...
I tried restarting the machine, creating a new project, startgin from scrath, the only thing I haven't tried so far is to reinstall IIS...
any idea???
PLEASE HELP!!!!
edit: some info about my environment
Windows XP 2002 SP 3, IIS 5.1, Visual Studio 2008 9.0.30729.1 SP
A: The most likely reason for this is because the process hasn't spun up yet. You need to hit an ASP page first before IIS spins up the DLLHOST.exe in which it runs an application if you have that application set to have high isolation (recommended for debugging purposes).
Hence debugging bia attachment requires the you use the browser to ping an ASP page in your site first, then open the Attach to process list.
A: I had the same problem. I fixed it out installing Service Pack 1 for my Visual Studio 2008. And now I attach to "inetinfo.exe" process instead of "dllhost.exe".
A: The following steps might help you:
*
*Host the site is IIS and make sure it's running
*Change the Application Configuration to enable debugging
*Then Attach the debugger to w3wp (IIS worker process)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/1060780",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: C++ Header files for shared library, which headers to install? (best practice) When creating a shared C++ library, what is best practice for installing header files? More specifically, I have the following two questions:
*
*I am working on a shared library project with headers which have complex interdependencies, so do I simply install them all, or is there a way of restricting the number of headers needed?
*I plan to install headers to a subdirectory of e.g. /usr/local/include to avoid polluting the top level directory, is this the right thing to do?
Other info: I only really want to provide an interface to the library. The project is an autotools project and I am using the pkginclude_HEADERS command in my Makefile.am files to install the headers in the appropriate subdirectory. I am actually converting this project from a program that used static libraries, to a shared library and small program that links to the library. People are unlikely to use just a small part of the library rather than the whole thing.
Edit:
In response to a vote to close for being opinion based, I would also consider a valid answer that this is purely project-specific, or down to taste, and there is no accepted best practice, but I doubt this to be the case, or I would not have asked.
A: One common approach is to put public header files in a include directory and the rest of the source files (both hpp and cpp) in a src directory. For example, suppose you're working on a project called foo. A possible file hierarchy would be the following:
foo
include
foo
x.hpp
y.hpp
src
x.cpp
y.cpp
z.cpp
z.hpp
In this case, you can simply add the include directory to the include path and you'll then be able to include the public header files like this: #include <foo/x.hpp>.
A: I want to share my ideas while I am not sure if I have the right answer:).
A:
*
*If the headers have complex inter-dependencies, it will be safer to simply install them all. Or you might want to read the source codes and clean the inter-dependencies.
*It is the right thing to put all the headers in one discretionary. :)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/20046480",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: Timer with read BLE Characteristic I'm building an Android Service. This Service should to connect of BLE device and download all informatio that it have storage in yuor memory.
Now I want that this Service can running in background.
This is my BlePowerService that extends Service
public class BlePowerService extends Service {
public DbLayer db;
Setting settingApp;
List<ScanFilter> filters;
String[] stringSequence = new String[] {CHARACTERISTIC_FORZA_STRING, CHARACTERISTIC_TEMPERATURA_STRING};
BluetoothAdapter mBluetoothAdapter;
BluetoothGatt mGatt;
BluetoothDevice currDevice;
static final long SCAN_PERIOD = 500;
static String SPLIT_CHAR =";";
BluetoothLeScanner mLEScanner;
Handler mHandler;
int ReadQueueIndex;
List<BluetoothGattCharacteristic> ReadQueue;
BluetoothGattCharacteristic caratteristicaDaLeggere;
ScanSettings settings;
Integer ultimaForzaLetta,ultimaTemperaturaLetta;
boolean continuaLetturaForza, continuaLetturaTemperatura;
boolean isReading = true;
String LOG_CODE = "NOTIFSRV";
GattClientCallback gattClientCallback;
private static final int PERMISSION_REQUEST_COARSE_LOCATION = 1;
public BlePowerService() {
}
@Override
public IBinder onBind(Intent intent) {
// TODO: Return the communication channel to the service.
//throw new UnsupportedOperationException("Not yet implemented");
return null;
}
@Override
public void onCreate() {
super.onCreate();
mHandler = new Handler();
Context sharedContext = null;
try {
sharedContext = this.createPackageContext(
"com.care.devicesensor",
Context.CONTEXT_INCLUDE_CODE);
if (sharedContext == null) {
return;
}
db=new DbLayer(sharedContext);
db.open();
} catch (Exception e) {
String error = e.getMessage();
// Log.d(LOG_CODE,"DB error : " + error);
return;
}
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
try {
//RECUPERO LE IMPOSTAZIONI SETTATE DALL'UTENTE
settingApp = db.fetchSetting();
if (settingApp != null && settingApp.getAddressBleSX()!=null) {
//POSSO FILTRARE DIRETTAMENTE PER L'UUID DEL DISPOSITIVO MEMORIZZATO
//DALL'UTENTE
ScanFilter.Builder scanFilterMac =
null;
scanFilterMac = new ScanFilter.Builder().setDeviceAddress(settingApp.getAddressBleSX());
if(filters==null)
filters = new ArrayList<ScanFilter>();
//if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
filters.add(scanFilterMac.build());
//}
//FILTRO ANCHE PER LA CARATTERISTICA DI FORZA
ScanFilter filter = null;
filter = new ScanFilter.Builder().setServiceUuid(ParcelUuid.fromString(CHARACTERISTIC_FORZA_STRING)).build();
filters.add(filter);
final BluetoothManager bluetoothManager =
(BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
mBluetoothAdapter = bluetoothManager.getAdapter();
//mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
mLEScanner = mBluetoothAdapter.getBluetoothLeScanner();
settings = new ScanSettings.Builder()
.setScanMode(ScanSettings.SCAN_MODE_LOW_POWER)
.build();
scanLeDevice(true);
mTimer = new Timer();
//ogni 2 ore
continuaLetturaForza = true;
continuaLetturaTemperatura = true;
int nSecondi = settingApp.getFrequenzaDownload()!= null ? settingApp.getFrequenzaDownload() : 1;
mTimer.schedule(timerTask, 10000, 1000 * nSecondi);
}
} catch (Exception e) {
// Log.e("POWER_SERVICE", e.getMessage());
}
return super.onStartCommand(intent, flags, startId);
}
private Timer mTimer;
TimerTask timerTask = new TimerTask() {
@RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR2)
@Override
public void run() {
//LEGGO TUTTI I DATI DAL SENSORE FINCHE CI SONO VALORI
int counter = 0;
while(continuaLetturaForza || continuaLetturaTemperatura){
counter++;
Log.v("CICLO WHILE", counter+"");
if (currDevice != null) {
if(ReadQueue!= null && ReadQueue.size()>0){
int index =0;
for(index=0; index < ReadQueue.size(); index++){
isReading = mGatt.readCharacteristic(ReadQueue.get(index));
while(isReading){
try {
Thread.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}else{
//provo a ricollegarmi al dispositivo probabile, abbia perso la connessione con esso
scanLeDevice(true);
try {
Thread.sleep(2500);
} catch (InterruptedException e) {
e.printStackTrace();
}
if(currDevice == null && counter == 25){
//in questo caso non è riuscito a trovare il dispositivo BLE
//esco dal ciclo
continuaLetturaForza = false;
continuaLetturaTemperatura = false;
continue;
}
}
}
if(gattClientCallback!=null && mGatt != null)
gattClientCallback.disconnectGattServer();
}
};
public void connectToDevice(BluetoothDevice device) {
//VERIFICO SE IL DEVICE è QUELLO CHE VOGLIO IO
if (mGatt == null && settingApp != null
&& device.getAddress().equals(settingApp.getAddressBleSX())) {
currDevice = device;
gattClientCallback = new GattClientCallback();
mGatt = currDevice.connectGatt(getBaseContext(), false, gattClientCallback);
scanLeDevice(false);// will stop after first device detection
}
}
private BluetoothAdapter.LeScanCallback mLeScanCallback =
new BluetoothAdapter.LeScanCallback() {
@Override
public void onLeScan(final BluetoothDevice device, int rssi,
byte[] scanRecord) {
Handler h = new Handler(getApplicationContext().getMainLooper());
// Although you need to pass an appropriate context
h.post(new Runnable() {
@Override
public void run() {
// Log.i("onLeScan", device.toString());
connectToDevice(device);
}
});
}
};
private void scanLeDevice(final boolean enable) {
if (enable) {
mHandler.postDelayed(new Runnable() {
@Override
public void run() {
if (Build.VERSION.SDK_INT < 21) {
mBluetoothAdapter.stopLeScan(mLeScanCallback);
} else {
mLEScanner.stopScan(mScanCallback);
}
}
}, SCAN_PERIOD);
if (Build.VERSION.SDK_INT < 21) {
mBluetoothAdapter.startLeScan(mLeScanCallback);
} else {
mLEScanner.startScan(filters, settings, mScanCallback);
}
} else {
if (Build.VERSION.SDK_INT < 21) {
mBluetoothAdapter.stopLeScan(mLeScanCallback);
} else {
mLEScanner.stopScan(mScanCallback);
}
}
}
private ScanCallback mScanCallback = new ScanCallback() {
@Override
public void onScanResult(int callbackType, ScanResult result) {
// Log.i("callbackType", String.valueOf(callbackType));
// Log.i("result", result.toString());
BluetoothDevice btDevice = null;
btDevice = result.getDevice();
connectToDevice(btDevice);
}
@Override
public void onBatchScanResults(List<ScanResult> results) {
for (ScanResult sr : results) {
Log.i("ScanResult - Results", sr.toString());
}
}
@Override
public void onScanFailed(int errorCode) {
Log.e("Scan Failed", "Error Code: " + errorCode);
}
};
private class GattClientCallback extends BluetoothGattCallback {
@Override
public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {
try{
super.onConnectionStateChange(gatt, status, newState);
Log.i("tag", "onConnectionStateChange newState: " + newState);
if (status == BluetoothGatt.GATT_FAILURE) {
Log.e("ERROR_SERVICE", "Connection Gatt failure status " + status);
if(mGatt == null){
}else{
try {
gatt.close();
} catch (Exception e) {
Log.d("", "close ignoring: " + e);
}
mGatt = null;
}
return;
} else if (status != BluetoothGatt.GATT_SUCCESS) {
// handle anything not SUCCESS as failure
Log.e("ERROR_SERVICE", "Connection not GATT sucess status " + status);
if(mGatt == null){
}else{
try {
gatt.close();
} catch (Exception e) {
Log.d("", "close ignoring: " + e);
}
mGatt = null;
}
return;
}
if (newState == BluetoothProfile.STATE_CONNECTED) {
//Log.i("INFO", "Connected to device " + gatt.getDevice().getAddress());
gatt.discoverServices();
} else if (newState == BluetoothProfile.STATE_DISCONNECTED) {
Log.i("INFO", "Disconnected from device");
if(mGatt == null){
}else{
try {
gatt.close();
} catch (Exception e) {
Log.d("", "close ignoring: " + e);
}
mGatt = null;
}
}
}catch(Exception e){
Log.e("tag", e.getMessage());
continuaLetturaForza = true;
continuaLetturaTemperatura = true;
}
}
public void disconnectGattServer() {
//Log.i("INFo", "Closing Gatt connection");
// clearLogs();
//mConnected = false;
//mEchoInitialized = false;
continuaLetturaForza = false;
continuaLetturaTemperatura = false;
if (mGatt == null) {
}
else{
try{
mGatt.disconnect();
// mGatt.close();
}catch(Exception e){
mGatt = null;
}
}
//mGatt = null;
//currDevice = null;
}
@Override
public void onServicesDiscovered(BluetoothGatt gatt, int status) {
super.onServicesDiscovered(gatt, status);
if (status != BluetoothGatt.GATT_SUCCESS) {
// Log.i("INFO", "Device service discovery unsuccessful, status " + status);
return;
}
List<BluetoothGattCharacteristic> matchingCharacteristics =
BluetoothUtils.findCharacteristics(gatt,stringSequence);
if (matchingCharacteristics.isEmpty()) {
// Log.e("ERROR_SERVICE","Unable to find characteristics.");
return;
}else {
//INIZIALIZZO LA LISTA DI CARATTERISTICHE CHE DEVO ANDARE A LEGGERE
ReadQueue = new ArrayList<>();
for (BluetoothGattCharacteristic characterist : matchingCharacteristics) {
ReadQueue.add(characterist);
}
}
}
@Override
public void onCharacteristicRead(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) {
super.onCharacteristicRead(gatt, characteristic, status);
if (status == BluetoothGatt.GATT_SUCCESS) {
Log.v("INSERT_DB", "*****************************************");
Log.v("INSERT_DB", "*****************************************");
Log.v("INSERT_DB", "*****************************************");
Log.v("INSERT_DB", "INSERISCO LE CARATTERISTICHE LETTE SUL DB");
//readCharacteristic(characteristic);
String valoreRestituito = characteristic.getStringValue(0);
if(valoreRestituito==null){
int i = 0;
i = i + 1;
return;
}
//SPLITTO PER IL CARATTERE ;
String[] arrayValori = valoreRestituito.split(SPLIT_CHAR);
//1 valore è l ID
try{
int id = new Integer(arrayValori[0]);
//VERIFICO SE STO LEGGENDO TEMPERATURA O FORZA
if(characteristic.getUuid().equals(CHARACTERISTIC_FORZA_UUID)){
Log.v("CARATTERISTICA", "*****************************************");
Log.v("FORZA", "*****************************************");
if(ultimaForzaLetta!= null && ultimaForzaLetta == id){
continuaLetturaForza = false;
isReading = false;
return;
}
ultimaForzaLetta = id;
}else if(characteristic.getUuid().equals( CHARACTERISTIC_TEMPERATURA_UUID)){
Log.v("CARATTERISTICA", "*****************************************");
Log.v("TEMPERATURA", "*****************************************");
if(ultimaTemperaturaLetta!= null && ultimaTemperaturaLetta == id){
continuaLetturaTemperatura = false;
isReading = false;
return;
}
ultimaTemperaturaLetta = id;
}
SensorData mSenData = new SensorData();
mSenData.setIdType(id);
mSenData.setValue1(arrayValori[1]);
mSenData.setValue2(arrayValori[2]);
mSenData.setValue3(arrayValori[3]);
mSenData.setValue4(arrayValori[4]);
mSenData.setValue5(arrayValori[5]);
mSenData.setValue6(arrayValori[6]);
mSenData.setValue7(arrayValori[7]);
mSenData.setValue8(arrayValori[8]);
//TO-DO HO COMMENTATO QUESTA RIGA DI CODICE
// mSenData.setIdType(st.getId());
mSenData.setCharacteristic(characteristic.getUuid().toString());
mSenData.setValueTimestamp(db.getDateTime(true));
//inserisco i dati nel db
Log.v("INSERT_DB",valoreRestituito);
Log.v("INSERT_DB", "*****************************************");
Log.v("INSERT_DB", "*****************************************");
Log.v("INSERT_DB", "*****************************************");
Log.v("INSERT_DB", "*****************************************");
Log.v("INSERT_DB", "*****************************************");
Log.v("INSERT_DB", "*****************************************");
Log.v("INSERT_DB", "FINE LE CARATTERISTICHE LETTE SUL DB");
db.insertSensorData(mSenData);
EventBus.getDefault().post(new MessageEvent("update"));
//EventBus.getDefault().post(new UnfriendEvent(userId));
}catch (Exception e){
Log.e("ERROR", e.getMessage());
}
isReading = false;
} else {
isReading = false;
Log.e("ERROR_SERVICE", "Characteristic read unsuccessful, status: " + status);
Log.e("ERROR_SERVICE", "Characteristic read unsuccessful, status: " + status);
Log.e("ERROR_SERVICE", "Characteristic read unsuccessful, status: " + status);
Log.e("ERROR_SERVICE", "Characteristic read unsuccessful, status: " + status);
Log.e("ERROR_SERVICE", "Characteristic read unsuccessful, status: " + status);
Log.e("ERROR_SERVICE", "Characteristic read unsuccessful, status: " + status);
Log.e("ERROR_SERVICE", "Characteristic read unsuccessful, status: " + status);
Log.e("ERROR_SERVICE", "Characteristic read unsuccessful, status: " + status);
Log.e("ERROR_SERVICE", "Characteristic read unsuccessful, status: " + status);
// Trying to read from the Time Characteristic? It doesnt have the property or permissions
// set to allow this. Normally this would be an error and you would want to:
disconnectGattServer();
return;
}
}
}
public void onDestroy() {
try {
db.close();
Log.d(LOG_CODE,"DB connection closed" );
mTimer.cancel();
timerTask.cancel();
} catch (Exception e) {
e.printStackTrace();
}
}
}
In the onStartCommand method I create a Timer that run the service every X time.
The "cycle while" can download all information of BLE device, throught onCharacteristicRead method.
Now the question is, if unit I can to read a characteristic, I turn off the BLE device, I can rileve this status change connection by onConnectionStateChange method, but the Timer it is never performed again.
Why the Timer is not execute again?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/50293780",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Basic loop and totaling positive inputs Consider:
print("Welcome to the number program")
number = input("Please give me a number \n")
number = int(number)
total_number = 0
entries = 0
while number > 0:
total_number = total_number + number
print(total_number)
number = input("Please give me another number! \n")
number = int(number)
entries = int(entries) + 1
if number < 0:
print("Sorry, this value needs to be positive. Please enter a
different number.")
if number == -999:
print(total_number)
print(entries)
print(total_number/entries)
I'm in a beginners programming class, and the book is not very helpful at times. I'm trying to write a basic program that takes positive numbers, totals them, and averages them out at the end. It also rejects negative numbers, and asks if -999 is entered. I print the average of all entries, amount of entries, and the value tally.
The program runs ok, but it just doesn't write out some things I wanted.
A: From what you wrote and the comments in your code I am guessing that you want the program to continue running and asking for input if you enter a non-positive number. In that case I would rewrite it as:
print("Welcome to the number program")
total_number = 0
entries = 0
while True:
number = input("Please give me a number \n")
number = int(number)
if number == -999:
break
if number <= 0:
print("Sorry, this value needs to be positive. Please enter a different number.")
continue
total_number = total_number + number
entries += 1
print(total_number)
print(total_number)
print(entries)
print(total_number / entries)
Also, you can increment numbers with entries += 1
A: *
*In most cases you should NOT create variables first, however this case you should. Create number = 0, tally = 0 and total_number = 0 first
*Accept your first number inside your while loop and handle all of the logic in there as well.
*Your while loop should continue to loop until the final condition is met which seems to be number == -999
*Should tally be incremented if you enter a negative number? I assume not. What about a 0? Wrap the increment for tally and the addition to total_number in an if number > -1: condition. Use an if else to check for number == -999, and an else for handling invalid entries.
*Finally, move your print statements outside of your while loop. It also doesn't need a condition around it because now, if you've exited your while loop, that condition has been satisfied.
Final note here, and this is just a nice to know/have and purely syntactic sugar, MOST languages support abbreviated incrementing. Theres a better word for it, but the gist is simply this.
total_number += number
# is exactly the same as
total_number = total_number + number
# but way nicer to read and write :)
print("Welcome to the number program")
number = 0
total_number = 0
entries = 0
while number != -999:
number = input("Please enter a number! \n")
number = int(number)
if number >= 0
total_number += number
entries += 1
print("Current sum: " + total_number)
elif number == -999:
break
else
print("Sorry, this value needs to be positive.")
print("Sum of entries: "+str(total_number))
print("Number of entries: " + str(entries))
print("Average entry: " +str(total_number/entries))
A: I have rewritten your code. But I am not sure what the goal was. Anyways, if the value were ever to be under 0 the loop would have been exited and a new value would have never been accepted from an input.
Also some things I have written more elegant.
print("Welcome to the number program")
number=int(input("Please give me a number \n"))
total_number=0
entries=0
while number > 0:
total_number += number
print(total_number)
number = int(input("Please give me another number! \n"))
entries += 1
if number == -999:
print(total_number)
print(entries)
print(total_number/entries)
break
elif number < 0:
number = input("Sorry, this value needs to be positive. Please enter a different number!")
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/75422800",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
}
|
Q: Find and replace multiple character in a string VBA I have a large amount of data which i want to replace with the help of macro. I am using code below right now but problem is that it will only replace one value which is D in below code.
Sub Replace()
what = "D"
replc = ""
Sheets("Sheet1").Select
Cells.replace What:=word, Replacement:=replc, LookAt:=xlPart, _
SearchOrder:=xlByRows, MatchCase:=True, SearchFormat:=False, _
ReplaceFormat:=False
End Sub
My sample data is below. As you can see that some value have alphabetical characters, symbol or combination of character at the end or as a cell value, which i want to replace or remove and also some value will be replaced with other values. I create macro with all possibilities to find the required value and replace it.
0065D 2089 2797 3270 3315
0066D 2095 2799 3300 3334
0067D 2105 2802 3582aX a
2089 – 2812 3307 3383
2095 2111 1164D 3315 3385
2105 2112 1165D 3334 3400
2110 2114 2841 3336F 3507
0771N 2121 2881 3365 3515N
*0908P* 2130 2883 3372X 3548
0913P 2131 2913 3373 3559
2111 2143 2915 3373 3574
You also notice that there are some lower case characters as well. Right now i was trying to use IF condition with Find but could not succeed. I am making above macro with every possible condition to replace and run it from another macro which is something like below algo.
IF find "D" Then
Run macro "Replace"
Elseif find "X"
Run macro "Replace"
Elseif find "F"
Run macro "Replace"
and so on....
but if the macro didn't find required character in the sheet then it skips to next step and so on. I want this so bad. I have to perform this replace routine on number of times.
So any help will be appreciated.
Thanks
A: You can add/remove necessary characters from the toRemove() array.
Sub replaceChars()
Dim toRemove()
toRemove() = Array("D", "X", "F")
For Each itm In toRemove()
For Each iCell In ActiveSheet.UsedRange
iCell.Replace What:=itm, Replacement:="", MatchCase:=True
Next iCell
Next itm
End Sub
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/21826106",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Groovy regex when replacing tokens in file I have a text file that has the token "%%#%" located all over the place inside of it. I am trying to write a quick-and-dirty Groovy shell script to replace all instances of "%%#%" with a dollar sign "$".
So far I have:
#!/usr/bin/env groovy
File f = new File('path/to/my/file.txt')
f.withWriter{ it << f.text.replace("%%#%", "$") }
But when I run this script, nothing happens (no exceptions and no string replacement). I wonder if any of the characters I'm searching for, or the dollar sign itself, is being interpreted as a special char by the regex engine under the hood. In any event, Where am I going awry?
A: I had to read the file content first, and then write on the file. Seems like withWriter erases the file contents:
def f = new File('/tmp/file.txt')
text = f.text
f.withWriter { w ->
w << text.replaceAll("(?s)%%#%", /\$/)
}
You might want to do a per line read if the file is too large. Otherwise, you can use that multiline (?s) regex.
Note I escaped $, because replace and replaceAll behaves differently, in a sense that replace accepts a char and, thus, will be unaffected by regex strings, whereas replaceAll will need escaping.
Here is my test:
$ echo "%%#%
aaaa
bbbb
cccc%%#%dddd" > file.txt && groovy Subst.groovy && cat file.txt
$
aaaa
bbbb
cccc$dddd
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/25246034",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
}
|
Q: Is it safe when compare 2 float/double directly in Java? Is it safe if I use comparision like this (a is int, b and c is float/double):
a == b
b == c
It may hear ridiculous, but in my old programing language, sometimes 1 + 2 == 3 is false (because left side returns 2.99999999999...). And, what about this:
Math.sqrt(b) == Math.sqrt(c)
b / 3 == 10 / 3 //In case b = 10, does it return true?
A: You do need to exercise some care.
1.0 + 2.0 == 3.0
is true because integers are exactly representable.
Math.sqrt(b) == Math.sqrt(c)
if b == c.
b / 3.0 == 10.0 / 3.0
if b == 10.0 which is what I think you meant.
The last two examples compare two different instances of the same calculation. When you have different calculations with non representable numbers then exact equality testing fails.
If you are testing the results of a calculation that is subject to floating point approximation then equality testing should be done up to a tolerance.
Do you have any specific real world examples? I think you will find that it is rare to want to test equality with floating point.
A: b / 3 != 10 / 3 - if b is a floating point variable like b = 10.0f, so b / 3 is 3.3333, while 10 / 3 is integer division, so is equal to 3.
If b == c, then Math.sqrt(b) == Math.sqrt(c) - this is because the sqrt function returns double anyways.
In general, you shouldn't be comparing doubles/floats for equation, because they are floating point numbers so you might get errors. You almost always want to compare them with a given precision, i.e.:
b - c < 0.000001
A: The safest way to compare a float/double with something else is actually to use see if their difference is a small number.
e.g.
Math.abs(a - b) < EPS
where EPS can be something like 0.0000001.
In this way you make sure that precision errors do not affect your results.
A: == comparison is not particularly safe for doubles/floats in basically any language. An epsilon comparison method (where you check that the difference between two floats is reasonably small) is your best bet.
For:
Math.sqrt(b) == Math.sqrt(c)
I'm not sure why you wouldn't just compare b and c, but an epsilon comparison would work here too.
For:
b / 3 == 10 / 3
Since 10/3 = 3 because of integer division, this will not necessarily give the results you're looking for. You could use 10.0 / 3, though i'm still not sure why you wouldn't just compare b and 10 (using the epsilon comparison method in either case).
A: In general, no it is not safe due to the fact that so many decimal numbers cannot be precisely represented as float or double values. The often stated solution is test if the difference between the numbers is less than some "small" value (often denoted by a greek 'epsilon' character in the maths literature).
However - you need to be a bit careful how you do the test. For instance, if you write:
if (Math.abs(a - b) < 0.000001) {
System.err.println("equal");
}
where a and b are supposed to be "the same", you are testing the absolute error. If you do this, you can get into trouble if a and b are (say_ 1,999,999.99 and 2,000,000.00 respectively. The difference between these two numbers is less than the smallest representable value at that scale for a float, and yet it is much bigger than our chosen epsilon.
Arguably, a better approach is to use the relative error; e.g. coded (defensively) as
if (a == b ||
Math.abs(a - b) / Math.max(Math.abs(a), Math.abs(b)) < 0.000001) {
System.err.println("close enough to be equal");
}
But even this is not the complete answer, because it does not take account of the way that certain calculations cause the errors to build up to unmanageable proportions. Take a look at this Wikipedia link for more details.
The bottom line is that dealing with errors in floating point calculations is a lot more difficult than it appears at first glance.
The other point to note is (as others have explained) integer arithmetic behaves very differently to floating point arithmetic in a couple of respects:
*
*integer division will truncate if the result is not integral
*integer addition subtraction and multiplication will overflow.
Both of these happen without any warning, either at compile time or at runtime.
A: Float wrapper class's compare method can be used to compare two float values.
Float.compare(float1,float2)==0
It will compare integer bits corresponding to each float object.
A: In java you can compare a float with another float,and a double with another double.And you will get true when comparing a double with a float when their precision is equal
A: b is float and 10 is integer then if you compare both with your this critearia then it will give false because...
b = flaot (meance ans 3.33333333333333333333333)
10 is integer so that make sence.
A: If you want a more complete explanation, here there is a good one: http://download.oracle.com/docs/cd/E19957-01/806-3568/ncg_goldberg.html (but it is a little bit long)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/6786254",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
}
|
Q: HA-Proxy balancing by source doesnt appear consistent Using HA-Proxy 1.4.18 I am using balance source as the option to balance a tcp stream to 2 servers. However from an admittedly very small sample set of connections it appears that they all just go to the one server - the server listed first in the haproxy config.
*
*listen videos *:1935
*balance source
*mode tcp
*server server1 192.168.0.1:1935
*server server2 192.168.0.2:1935
I have not seen it split the load onto the 2 boxes. This does work when I use balance roundrobin however for this particular application I cannot use this method.
Any ideas for an otherwise persistent session loadbalanced between these 2 machines from the clients?
Cheers
A: How did you test the balance ?, the doc says :
The source IP address is hashed and divided by the total
weight of the running servers to designate which server will
receive the request. This ensures that the same client IP
address will always reach the same server as long as no
server goes down or up. If the hash result changes due to the
number of running servers changing, many clients will be
directed to a different server. This algorithm is generally
used in TCP mode where no cookie may be inserted. It may also
be used on the Internet to provide a best-effort stickiness
to clients which refuse session cookies. This algorithm is
static by default, which means that changing a server's
weight on the fly will have no effect, but this can be
changed using "hash-type"
If you tested with just 2 different IP source you maybe fall in a particular case.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/15907219",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Android - Erasing view above fragment introduces delay in touch event The context
I'm developing an application where the user can reveal a content (mapfragment) through erasing with its fingers the view in front.
I've created a customView (similar to google fingerpaint - erasing sample) handling the drawing and I add this view in front of my content.
I've added a function to log the time between two ontouchevent moves.
case MotionEvent.ACTION_MOVE:
mTime = System.currentTimeMillis()-mTime;
mTimeList.add(mTime);
mTime = System.currentTimeMillis();
[...]
path.lineTo(event.getX(), event.getY());
invalidate();
break;
case MotionEvent.ACTION_UP:
int listSize = mTimeList.size();
long value =0;
for (Long time : mTimeList) {
value = value+time;
}
int finalvalue = (int) ((value/listSize));
Log.i("MotionEvent", "Average time : "+Long.toString(finalvalue));
break;
My problem
*
*When I create my activity and set layout to my custom view, it works very well. There is only my customView, and the time between two moves is around 17ms.
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(new MyView(this));
*When I create my activity and add my custom view to an empty mainlayout (relativelayout), the time between two moves is almost the same.
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.mapfullscreen_hotcold);
RelativeLayout mainLayout = (RelativeLayout)findViewById(R.id.mapfullscreen_relativeLayout);
MyView view = new MyView(this);
mainLayout.addView(view);
*When I create my activity and add my custom view to a mainlayout (relativelayout) which includes a mapfragment, the time between two moves is around 47ms.
---ACTIVITY---
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.mapfullscreen_hotcold);
RelativeLayout mainLayout = (RelativeLayout)findViewById(R.id.mapfullscreen_relativeLayout);
MyView view = new MyView(this);
mainLayout.addView(view);
---XML---
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/mapfullscreen_relativeLayout"
android:layout_width="match_parent"
android:layout_height="match_parent">
<fragment
android:id="@+id/mapfullscree_mapLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:name="com.google.android.gms.maps.MapFragment" />
</RelativeLayout>
What can I do to make it faster?
When I touch the view, the content below should not impact my view-motionevent, right?
EDIT:
And when I add my custom view to a mainlayout (relativelayout) which includes an imageView populated with mapsStaticAPI, the time between two moves is around 17ms/19ms.
What are the solutions to keep a googleMapsFragment with a short delay between two moves?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/18404175",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Doctrine: merge 2 requests in 1 I would like to merge these 2 requests in 1 but I have no clue on how to do this. Any idea ?
$productsCount = Doctrine::getTable('Product')
->createQuery('p')
->where('p.store_id = ?', $store_id)
->andWhere('p.collection = ?', $this->product->getCollection())
->andWhere('p.image_path IS NOT NULL')
->count();
$productsCollection = Doctrine::getTable('Product')
->createQuery('p')
->where('p.store_id = ?', $store_id)
->andWhere('p.collection = ?', $this->product->getCollection())
->andWhere('p.status_id = ?', Product::_ONLINE)
->andWhere('p.id<>?', $this->product_id)
->offset(rand(0, $productsCount - 1))
->execute();
*
*Doctrine: 1.2
*Symfony: 1.4
*PHP: 5.3
A: You can use subquery, because your query is not identical. Here DQL: Doctrine Query Language some example. And here is pseudocode, I do not know if it will work at once.
$q = Doctrine_Query::create()
->from('Product p')
->select('id, sum(id) as sumEntries')
->addSelect('(SELECT id, name) // and else fields that you need
FROM Product a
WHERE (
a.store_id = '.$store_id.'
AND
a.collection = '.$this->product->getCollection().'
AND
a.id<>= '.$this->product_id.'
)
OFFSET '.rand(0, $productsCount - 1).') // I am not sure in this line
as resultSubquery')
->where('p.store_id = ?', $store_id)
->andWhere('p.collection = ?', $this->product->getCollection())
->andWhere('p.image_path IS NOT NULL')
$result = $q->execute(array(), Doctrine_Core::HYDRATE_ARRAY); //This greatly speeds up query
You get an array in $result. Do var_dump() and check its contents. I'm not sure that this code will work at once, but I advise you to move in this direction.
p.s: I recommend you this interesting presentation about Doctrine query optimization: Doctrine 1.2 Optimization
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/13313491",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Create custom object array with jQuery.map() function
I have table as seen above and I want to create a custom array to pass values.
Currently I am using the following lines of code:
var arr = $('input[type=text].editfield').map(function () {
return this;
}).get();
var objArr = jQuery.map(arr, function (i) {
return {
myDate: i.parentElement.previousSibling.previousSibling.previousSibling.previousSibling.previousSibling.previousSibling.childNodes[0].textContent,
myValue: i.value
}
}).get();
and I expect to have an array of objects of all items in my grid with Date and Value as properties respectively.
But something is wrong and I can not solve. For example the code above says "jQuery.map(...).get is not a function"
How can I correct my code to perform the correct action?
A: There is no need to use .get() on the static jQuery.map() function, it returns a proper array, while the plugin method .map() returns a jQuery object on which you have to call .get() to get an array.
Also there is no need to use 2 loops,
var objArr = $('input[type=text].editfield').map(function (idx, i) {
//the element selection used here is cruel, if you can share the html used we can help you to clean it
return {
// you can try myDate: $(this).parent().prevAll().eq(5).text() - not testable without the html and what is the expected output
myDate: i.parentElement.previousSibling.previousSibling.previousSibling.previousSibling.previousSibling.previousSibling.childNodes[0].textContent,
myValue: i.value
};
}).get();
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/21426947",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Exception ActiveRecord::AdapterNotSpecified occurs when connecting Heroku <-> Postgres (EC2) I've a Heroku app that is trying to connect to a Postgres DB on EC2. Here is the issue that I'm getting:
2011-05-30T23:07:48+00:00 app[web.1]: /app/.bundle/gems/ruby/1.8/gems/activerecord-3.0.0/lib/active_record/connection_adapters/abstract/connection_specification.rb:66:in `establish_connection': database configuration does not specify adapter (ActiveRecord::AdapterNotSpecified)
2011-05-30T23:07:48+00:00 app[web.1]: from /app/.bundle/gems/ruby/1.8/gems/activerecord-3.0.0/lib/active_record/connection_adapters/abstract/connection_specification.rb:60:in `establish_connection'
I've followed the heroku instructions described here to set up the database configurations on the heroku app. Here are some other things that might help:
*
*I can connect to the postgresql db using a psgql admin on my computer (showcasing that the port forwarding and listening to hosts is set up correctly ..and no I'm not allowing ONLY my IP to enter - its wild carded so that all ips can connect)
*The version of postgresql that i'm running on EC2 is 8.4 while Heroku normally uses 9.0 on their shared databases. Could this be the problem? (the reason I've not fixed this is because I don't know where to find pg_upgrade...)
Thanks in advance!
A: @amehta, no, 8.4 and 9.0 is not your problem. My naive guess is that your configuration is missing:
adapter: postgresql
The problem is entirely local inside of your Heroku setup. Try manually connecting from Heroku to EC2:
require 'postgres'
conn = PGconn.connect('amazone-host', 5432, '', '', 'dbname', 'username', 'pass')
puts conn.exec('SELECT version()')[0]
to see if you can further isolate the problem.
A: the problem is that heroku overwrites the database.yml....so when you call ActiveRecord::Base.establish_connection(:external_db) there is no .yml definition for that db
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/6181976",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: call activity from service It has been asked a few times before but the solution provided couldn't solve my problem. I am working on the app which has several classes: mainactivity, SMS, and MService. service has a timer. I am trying to call SMS to send a text message every time timer is over. Can please someone help me ....
Thanks for consideration...
public class MService extends Service {
private Handler HandleIt = new Handler();
private final int INTERVAL = 60 * 1000;
private Timer timer = new Timer();
boolean timeout = false;
public interface SmsService
{
void SmsServiceSenter();
}
@Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
class TimeDisplayTimerTask extends TimerTask {
@Override
public void run() {
HandleIt.post(new Runnable(){
public void run(){
Toast.makeText(getApplicationContext(), TextonScreen(), Toast.LENGTH_SHORT).show();
// Intent smsintent = new Intent(getBaseContext(), SMS.class);
// startService(smsintent);
}
});
}
}
private String TextonScreen()
{
timeout = true;
return "it is running";
}
boolean isTimeout()
{
return timeout;
}
@Override
public void onCreate() {
// TODO Auto-generated method stub
super.onCreate();
Toast.makeText(this, "Service is created", Toast.LENGTH_SHORT).show();
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
// TODO Auto-generated method stub
// Display the Toast Message
Toast.makeText(this, "Start it", Toast.LENGTH_SHORT).show();
// Execute an action after period time
//comes from the TimeDisplayTimerTask class
timer.scheduleAtFixedRate(new TimeDisplayTimerTask(), 0, INTERVAL);
return super.onStartCommand(intent, flags, startId);
}
@Override
public void onDestroy() {
// Display the Toast Message
Toast.makeText(this, "Stop it", Toast.LENGTH_SHORT).show();
super.onDestroy();
}
}
public class SMS extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
message();;
}
boolean issent = false;
String text = "I am here";
String num = "2085578209";
SmsManager smsManager = SmsManager.getDefault();
public void message()
{
// if(Timeout.isTimeout()) {
smsManager.sendTextMessage(num, null, text, null, null);
issent = true;
// }
}
boolean isSent()
{
return issent;
}
}
A: It is really simple.
After you create your Intent variable, before starting activity add a flag to it like below
Intent launch = new Intent(this, MyActivity.class);
launch.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(launch);
With this above code you can call activity from service
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/40415836",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: I want to create a persistent mapped network drive with ftp I want to create a persistent mapped network drive with ftp. I have mounted already a ftp path with the file explorer of windows in order to not input the credentials again. What is the solution please?
Here is my code:
New-PSDrive -Persist -Name "X" -PSProvider "FileSystem" -Root "ftp://localhost/"
I have this error:
New-PSDrive: D:\powershell\Untitled-2.ps1:1:1
Line 1
New-PSDrive -Persist -Name "X" -PSProvider "FileSystem" -Root "ftp:// …
When you use the Persist parameter, the root must be a file system location on a remote computer.
A: Let me clarify few of the things.
Mapped network drives are saved in Windows on the local computer. They're persistent, not session-specific,and can be viewed and managed in File Explorer and other tools.
When you scope the command locally, without dot-sourcing, the Persist parameter doesn't persist the creation of a PSDrive beyond the scope in which you run the command. If you run New-PSDrive inside a script, and you want the new drive to persist indefinitely, you must dot-source the script. For best results, to force a new drive to persist, specify Global as the value of the Scope parameter and include Persist in your command.
The name of the drive must be a letter, such as D or E. The value of Root parameter must be a UNC path of a different computer. The PSProvider parameter's value must be FileSystem.
So technically, you dont need to persist, you just need to specify the -Root properly:
New-PSDrive -PSProvider filesystem -Root C:\full\path\ -Name anyname
In your case the full path would be an UNC path \\remoteserver\full\path of FTP
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/66372071",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Combining information from multiple lists I have multiple string[] that are defined like this:
var allEntities = new[] { "a", "b", "c", "d", "e", "f", "g", "h", "i" }
var entitiesWithPriority = new[] { "c", "d", "g" }
var entitiesWithIssue = new [] { "d", "h", "i" }
var entitiesWith... = new [] { ... }
Now I'd like to compile a single list from those arrays by using the following class structure:
class Entity {
public string Name { get; set; }
public bool HasPriority { get; set; }
public bool HasIssue { get; set; }
}
The result of the operation should therefore be something like this:
[
{ "name": "a", "hasPriority": false, "hasIssue": false }
{ "name": "b", "hasPriority": false, "hasIssue": false }
{ "name": "c", "hasPriority": true, "hasIssue": false }
{ "name": "d", "hasPriority": true, "hasIssue": true }
{ "name": "e", "hasPriority": false, "hasIssue": false }
{ "name": "f", "hasPriority": false, "hasIssue": false }
{ "name": "g", "hasPriority": true, "hasIssue": false }
{ "name": "h", "hasPriority": false, "hasIssue": true }
{ "name": "i", "hasPriority": false, "hasIssue": true }
]
I could do something in the lines of the following code, but I think this solution is not perfect at all:
var result = allEntities.Select(entityName => new Entity()
{
Name = entityName,
HasPriority = entitiesWithPriority.Contains(entityName),
HasIssue = entitiesWithIssue.Contains(entityName)
});
How can I compile such a list while being performance efficient.
A: You can use a Dictionary or a Hashset to reduce Any and Contains complexity from O(n) to O(1):
The idea above can still be used for large lists to replace list/array/IEnumarable<> Contains which is O(n) with Hashset's Contains which is O(1).
var entitiesWithPriorityMap = entitiesWithPriority.ToDictionary(e => e.entityName, e => true);
var entitiesWithIssueMap = entitiesWithIssue.ToDictionary(e => e.entityName, e => true);
var result = allEntities.Select(entityName => new Entity()
{
Name = entityName,
HasPriority = entitiesWithPriorityMap.ContainsKey(entityName),
HasIssue = entitiesWithIssueMap.ContainsKey(entityName)
});
Note: This works when dealing with Linq2Object nor Linq2Sql (cannot generate SQL out of Contains in this scenario).
Hashset version
var entitiesWithPriorityMap = new HashSet<Entity>(entitiesWithPriority);
var entitiesWithIssueMap = new HashSet<Entity>(entitiesWithIssue);
// replace ContainsKey with Contains
A: You could join them together:
var entities =
from name in allEntities
join pr in entitiesWithPriority on name equals pr into np
from priority in np.DefaultIfEmpty()
join iss in entitiesWithIssue on name equals iss into npi
from issue in npi.DefaultIfEmpty()
select new Entity
{
Name = name,
HasPriority = !string.IsNullOrEmpty(priority),
HasIssue = !string.IsNullOrEmpty(issue)
};
A: First create a dictionary <string>,<entity> and populate it from all entities with all hasXXX defaults to false
After that, lookup is O(1)
foreach (var key in EntitiesWithPriority)
{
dict[key].hasPriority = true
}
and so on
A: If the construction can be List<> instead from an array, we can create a List<> with the following generic type: List<Dictionary<string, dynamic>>
To achieve such construction you need to create following method:
public List<List<Dictionary<string, dynamic>>> MethodName()
{
var list = new List<List<Dictionary<string, dynamic>>>();
HasPriority = false;
HasIssue = false;
foreach (var item in allEntities)
{
if (entitiesWithPriority.Contains(item.ToString()))
HasPriority = true;
if (entitiesWithIssue.Contains(item.ToString()))
HasIssue = true;
list.Add(new List<Dictionary<string, dynamic>>()
{
(new Dictionary<string, dynamic>() { { "name", item } }),
(new Dictionary<string, dynamic>() { { "hasPriority", HasPriority } }),
(new Dictionary<string, dynamic>() { { "hasIssue", HasIssue } })
});
}
return list;
}
I'm not sure if all properties in your class are necessary. In case you'd want to add more arrays with conditions you should modify foreach loop.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/47498929",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: how to prevent idea auto resolve maven dependency I am new to idea and maven ,I find that every time, when I am edit the dependency in the pom.xml ,before I finished writing, idea tryed to resolve the dependency and create some folder in my native repo , for example , when I am edit the dependency, and it looks like this now
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-a</artifactId>
</dependency>
idea has create a folder in my native repo like this,how to prevent it and I have set my setting like this,but it seems no use, and the file is auto saved as usual
A: I'm guessing you have enabled the "Import Maven projects automatically" option. To disable it, go to Preferences... > Build, Execution, Deployment > Build Tools > Maven > Importing, then uncheck the option from there, like so:
After doing so, it will be up to you to run the imports when you're ready. To import manually, right-click your project in the Project view, then click Maven > Reimport:
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/41296035",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
}
|
Q: check for valid date which is declared in varchar2 My table looks like below which is declared in VARCHAR2:
YMD
20101010
20101112
20100231
20150101
20160101
I have to check for valid dates and filter future dates from sysdate, which are in valid format.
I write the function as below to check for valid dates:
create or replace FUNCTION VALIDATE_DATE (p_string in string) return date is
begin
return to_date(p_string, 'YYYYMMDD');
exception when others then
begin
return to_date(p_string, 'YYYY-MM-DD');
exception when others then
begin
return to_date(p_string, 'RR-MON-DD');
exception when others then
return null;
end;
end;
end;
and written this query to check for valid dates and replace with null for invalid dates
select ymd, VALIDATE_DATE(ymd) as Valid
from temp
and to check future dates I wrote the following query, but it throws error
ORA-01839
select ymd
from temp
where validate_date(ymd)='YES'
and to_date(ymd,'yyyymmdd')>sysdate
How to check future dates in my table if exists?
A: I will rather fix the design issue as a permanent fix rather than wasting time on the workaround.
Firstly, NEVER store DATE as VARCHAR2. All this overhead is due to the fact that your design is flawed.
'20100231'
How on earth could that be a valid date? Which calendar has a 31 days in FEBRUARY?
Follow these steps:
*
*Add a new column with DATE DATA TYPE.
*Update the new column with date values from the old column using TO_DATE.
*Do the required DATE arithmetic on the new DATE column, or handle this in the UPDATE statement in step 2 itself.
*Drop the old column.
*Rename the new column to the old column.
UPDATE Adding a demo
Setup
SQL> CREATE TABLE t
2 (ymd varchar2(8));
Table created.
SQL>
SQL> INSERT ALL
2 INTO t (ymd)
3 VALUES ('20101112')
4 --INTO t (ymd)
5 -- VALUES ('20100231')
6 INTO t (ymd)
7 VALUES ('20150101')
8 INTO t (ymd)
9 VALUES ('20160101')
10 SELECT * FROM dual;
3 rows created.
SQL>
SQL> COMMIT;
Commit complete.
SQL>
Add new column:
SQL> ALTER TABLE t ADD (dt DATE);
Table altered.
SQL>
DO the required update
SQL> UPDATE t
2 SET dt =
3 CASE
4 WHEN to_date(ymd, 'YYYYMMDD') > SYSDATE
5 THEN NULL
6 ELSE to_date(ymd, 'YYYYMMDD')
7 END;
3 rows updated.
SQL>
SQL> COMMIT;
Commit complete.
SQL>
Let's check:
SQL> SELECT * FROM t;
YMD DT
-------- ---------
20101112 12-NOV-10
20150101 01-JAN-15
20160101
SQL>
Drop the old column:
SQL> ALTER TABLE t DROP COLUMN ymd;
Table altered.
SQL>
Rename the new column to old column name
SQL> ALTER TABLE t RENAME COLUMN dt TO ymd;
Table altered.
SQL>
You have just fixed the issue
SQL> SELECT * FROM t;
YMD
---------
12-NOV-10
01-JAN-15
SQL>
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/29625519",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Count particular values in a Spark DF column combined with window functions Sample DF:
var some_df = Seq(
("A", "no"),
("B", "yes"),
("B", "yes"),
("B", "no")
).toDF(
"user_id", "phone_number")
some_df.show()
+-------+------------+
|user_id|phone_number|
+-------+------------+
| A| no|
| B| yes|
| B| yes|
| B| no|
+-------+------------+
I am trying to count the number of "yes" for each user_id.
Code:
val omg_window = Window.partitionBy($"user_id")
some_df = some_df.withColumn("my_col",
count($"phone_number"==="yes").over(omg_window)).drop("phone_number")
some_df.show()
My OP:
+-------+------+
|user_id|my_col|
+-------+------+
| B| 3|
| B| 3|
| B| 3|
| A| 1|
+-------+------+
Expected OP:
User Id . my_col
B . 2
A . 0
Any suggestions on where I am going wrong will be highly helpful
A: Since you are reducing the data frame, use groupBy.agg instead of window function; Here you compare the phone_number column with yes string ($"phone_number" === "yes") and convert the result to integer which turns true into 1 and false into 0 and then we count 1s by suming up the column:
some_df.groupBy("user_id").agg(
sum(($"phone_number" === "yes").cast("integer")).as("my_col")
).show
+-------+------+
|user_id|my_col|
+-------+------+
| B| 2|
| A| 0|
+-------+------+
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/50958265",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: angularjs ui-router : How to change state or page from inside controller I am using Angularjs and Ui-router. I am able to call the pages with ui-sref from HTML. I want to call for a new page from controller when using ui-router. How to do you do it. I have given the code below.
var app = angular.module('starter', ['ionic'])
app.config(function($stateProvider, $urlRouterProvider) {
$urlRouterProvider.otherwise('/')
$stateProvider.state('home', {
url: '/home',
views: {
home: {
templateUrl: 'home.html'
}
}
})
$stateProvider.state('results', {
url: '/results',
views: {
results: {
templateUrl: 'results.html'
}
}
})
$stateProvider.state('help', {
url: '/help',
views: {
help: {
templateUrl: 'help.html'
}
}
})
})
.run(function($ionicPlatform) {
$ionicPlatform.ready(function() {
if(window.cordova && window.cordova.plugins.Keyboard) {
// Hide the accessory bar by default (remove this to show the accessory bar above the keyboard
// for form inputs)
cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true);
// Don't remove this line unless you know what you are doing. It stops the viewport
// from snapping when text inputs are focused. Ionic handles this internally for
// a much nicer keyboard experience.
cordova.plugins.Keyboard.disableScroll(true);
}
if(window.StatusBar) {
StatusBar.styleDefault();
}
});
})
.controller ("mainCtrl", function($scope) {
$scope.devList1 = [
{text:'Most Accurate', checked: false},
{text:'Accurate', checked: false},
{text:'Neutral', checked: false},
{text:'Inaccurate', checked: false},
{text:'Most Inaccurate', checked: false}];
$scope.indexToShow = 0;
$scope.questionlist = ["one", "two" , "three", "four", "five"];
$scope.imChanged = function(isChecked, index){
angular.forEach($scope.devList1, function (items) {
items.checked= false;
});
$scope.devList1[index].checked=true;
$scope.okaychecked = true;
}
$scope.nextquestion = function(){
$scope.okaychecked = false;
angular.forEach($scope.devList1, function (items) {
items.checked= false;
});
if (($scope.indexToShow) < ($scope.questionlist.length - 1)){
$scope.indexToShow = ($scope.indexToShow + 1) % $scope.questionlist.length;
}
else {
$state.go('home',"");
}
}
})
and html below
<body ng-app="starter" ng-controller = "mainCtrl">
<ion-nav-bar class="bar-positive">
</ion-nav-bar>
<ion-tabs class="tabs-positive" tabs-icon-top>
<ion-tab icon="ion-home" ui-sref="home">
<ion-nav-view name="home"></ion-nav-view>
</ion-tab>
<ion-tab icon="ion-help" ui-sref="help">
<ion-nav-view name="help"></ion-nav-view>
</ion-tab>
</ion-tabs>
<script type="text/ng-template" id="home.html">
<ion-view title="Single">
<ion-content padding="true">
<h2>Single Construct</h2>
<p>Here Single Constructs.</p>
</ion-content>
</ion-view>
</script>
<script type="text/ng-template" id="results.html">
<ion-view title="Results">
<ion-content padding="true">
<h2>Results</h2>
<p>Results here</p>
</ion-content>
</ion-view>
</script>
<script type="text/ng-template" id="help.html" >
<ion-view title="Multiple">
<ion-content padding = "true">
<div class="card">
<div class="item item-text-wrap" ng-repeat="item in questionlist track by $index" ng-show="$index == indexToShow">
{{item}}
</div>
</div>
<ion-checkbox ng-repeat="items in devList1" ng-model="items.checked" ng-change="imChanged(items.checked, $index)" ng-value = "items">{{items.text}}
</ion-checkbox>
<div ng-show="okaychecked">
<a class="button icon-right ion-chevron-right button-positive" ng-click = "nextquestion()" >NEXT</a>
</div>
</ion-content>
</ion-view>
</script>
</body>
</html>
I hv to call the state change or call new page at
$state.go('results',""); position. How do you do it.
$state.go don't seem to work. I want to go to results page
A: You have to inject $state in your controller
.controller ("mainCtrl", function($scope, $state) {
Then, you can use it
$state.go('results');
A: You have to use $state.go('results'); in stead of $state.go('results', "");. The second field is for setting the options of the $state.go method. I guess it's not working because you leave this as an empty string. If you don't put anything there, it will use the default values.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/36172252",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: How to map two Oberservable arrays based on a value? I have two observable arrays.
habits$: Observable<Habit[]>;
status$: Observable<Status[]>;
The habit has the following structure:
export interface Habit {
habitId: number;
name: string;
repeatVal: number;
notification: string;
color: string;
question: string;
id: number;
}
The status array has the habitId, date and status as keys.
I want to merge both habits$ and status$ into one Observable array based on the habitId attribute present in both of them.
I have done some research and a combination of mergeMap() and forkJoin() seems to be the way to go, like shown here
Combine multiple observable arrays into new object array
But I can't figure out a syntax that will work for me.
This is how my code looks at the moment:
ngOnInit() {
this.habits$ = this.habitService.fetchAllById(this.authService.userId);
console.log(this.habits$);
this.status$ = this.statusService.fetchAll();
this.habits$.pipe(
mergeMap(habits => {
this.status$ = this.statusService.fetchAll().filter(status => status.habitId == habits.habitId);
}));
console.log(this.joined$);}
A: I would use forkJoin in the following fashion:
ngOnInit() {
forkJoin([
this.habitService.fetchAllById(this.authService.userId),
this.status$ = this.statusService.fetchAll()
]).subscribe(([habits, statuses]) => {
this.joined = habits.map(habit => ({
...statuses.find(t => t.habitId === habit.habitId),
...habit
}));
});
}
see simple demo
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/67012411",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How can I change the position of an element? I just started in web dev and my first project is a resume website. I am trying to separate the education and experience sections with an hr element. It was working, then I used the float property in CSS to align education descriptions to the left and corresponding dates to the right. Now, the line that came after the education section is in the wrong area. Here is some code:
<section>
<h2>EDUCATION</h2>
<p id='e1'><strong>M.A. in Teaching</strong>, University of North Carolina</p>
<p id='e2'><strong>June 2021 - May 2022</strong></p>
<p id='e1'><strong>B.A., Human Development & Family Studies major & Education minor</strong>, University of North Carolina</p>
</section>
<hr>
<section>
<h2>EXPERIENCE</h2>
The id e1 just floats left, and the id e2 floats right. How can I get the hr element to actually appear between the two sections, instead of in the middle of the education section?
A:
.edu{
display: flex;
flex-direction: row;
align-self: flex-start;
}
<body>
<section>
<h2>EDUCATION</h2>
<div class="edu">
<p id='e1'><strong>M.A. in Teaching</strong>, University of North Carolina</p>
<p id='e2'><strong>June 2021 - May 2022</strong></p>
<p id='e3'><strong>B.A., Human Development & Family Studies major & Education minor</strong>, University of North Carolina</p>
</div>
</section>
<hr>
<section>
<h2>EXPERIENCE</h2>
</body>
A: *
*id should be unique so change #e1 from third p element to your choice but diff.
*Used clear:left so that float property on left of hr is cleared
*You can also use cleafix hack to <hr> , by adding clearfix class to <hr> and add this CSS
.clearfix::after {
content: "";
clear: both;
display: table;
}
*
*You can also add vertical rules using border-right as I specified in code
* {
box-sizing: border-box/*So that padding used below don't effect width*/
}
hr {
clear: left
}
#e1 {
float: left;
width: 33%; /*Width so that content is divided in 3colums*/
height: 100px;
/*Height specified so that border become equal for all others and act as a vertical rule*/
border-right: 2px solid red;
padding: 5px;
}
#e2 {
float: right;
width: 33%;
height: 100px;
padding: 5px;
}
#e3 {
float: left;
width: 33%;
height: 100px;
border-right: 2px solid red;
padding: 5px;
}
<section>
<h2>EDUCATION</h2>
<p id='e1'><strong>M.A. in Teaching</strong>, University of North Carolina</p>
<p id='e2'><strong>June 2021 - May 2022</strong></p>
<p id='e3'><strong>B.A., Human Development & Family Studies major & Education minor</strong>, University of North Carolina</p>
</section>
<hr>
<section class="hed2">
<h2>EXPERIENCE</h2>
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/68882476",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: sql query takes too long to execute I am having trouble with this query. It takes 10 hours to execute.
WITH CONSUM AS (
SELECT C.ID_MEASURER,C.ID_MEASURING_POINT,C.CONSUM_TYPE
FROM GCGT_RE_CONSUM_H_E C
WHERE C.DAY BETWEEN 20130201 AND 20130228 AND ACTIVE = 1
),
CORE AS (SELECT
SS.NISS,
CO.ID_CONTRACT,
CO.FROM_DATE AS FECHA_INI_CONTRATO,
SS.ID_DISTRIBUTER,
SS.ID_SECTOR_SUPPLY,
MP.CUPS,
M.ID_COMBINATION_USAGE_TYPE,
MP.MP_FUNCTION,
NVL (MP.FLAG_TELEMETRY, 0) AS TELEMEDIDO,
NVL (CTYP.RELEVANCE, 0) AS RELEVANT_CONSUM_TYPE,
MP.ID_MEASURER,
CTYP.COD_USAGE_TYPE AS CONSUM_TYPE,
0 AS VALUE_1,
0 AS VALUE_2,
0 AS VALUE_3,
0 AS VALUE_4,
0 AS VALUE_5,
0 AS VALUE_6,
0 AS VALUE_7,
0 AS VALUE_8,
0 AS VALUE_9,
0 AS VALUE_10,
0 AS VALUE_11,
0 AS VALUE_12,
0 AS VALUE_13,
0 AS VALUE_14,
0 AS VALUE_15,
0 AS VALUE_16,
0 AS VALUE_17,
0 AS VALUE_18,
0 AS VALUE_19,
0 AS VALUE_20,
0 AS VALUE_21,
0 AS VALUE_22,
0 AS VALUE_23,
0 AS VALUE_24,
0 AS VALUE_25,
'' AS SOURCE_1,
'' AS SOURCE_2,
'' AS SOURCE_3,
'' AS SOURCE_4,
'' AS SOURCE_5,
'' AS SOURCE_6,
'' AS SOURCE_7,
'' AS SOURCE_8,
'' AS SOURCE_9,
'' AS SOURCE_10,
'' AS SOURCE_11,
'' AS SOURCE_12,
'' AS SOURCE_13,
'' AS SOURCE_14,
'' AS SOURCE_15,
'' AS SOURCE_16,
'' AS SOURCE_17,
'' AS SOURCE_18,
'' AS SOURCE_19,
'' AS SOURCE_20,
'' AS SOURCE_21,
'' AS SOURCE_22,
'' AS SOURCE_23,
'' AS SOURCE_24,
'' AS SOURCE_25,
0 AS QUALITY_1,
0 AS QUALITY_2,
0 AS QUALITY_3,
0 AS QUALITY_4,
0 AS QUALITY_5,
0 AS QUALITY_6,
0 AS QUALITY_7,
0 AS QUALITY_8,
0 AS QUALITY_9,
0 AS QUALITY_10,
0 AS QUALITY_11,
0 AS QUALITY_12,
0 AS QUALITY_13,
0 AS QUALITY_14,
0 AS QUALITY_15,
0 AS QUALITY_16,
0 AS QUALITY_17,
0 AS QUALITY_18,
0 AS QUALITY_19,
0 AS QUALITY_20,
0 AS QUALITY_21,
0 AS QUALITY_22,
0 AS QUALITY_23,
0 AS QUALITY_24,
0 AS QUALITY_25,
20130228 AS DAY,
TRUNC(20130228 ,-2) AS FIRST_DAY,
TRUNC(20130228 ,-2) + 31 AS LAST_DAY,
NVL (MTY.COD_USER, '') AS ORIGIN,
SC.ID_CONTRACTED_SERVICE,
0 AS BAJA,
NVL(SC.IND_GUARANTOR, 0) AS GESTION_ATR,
SC.NISC
FROM GCGT_RE_MEASUREMENT_POINT MP
INNER JOIN GCCOM_SECTOR_SUPPLY SS ON MP.ID_SECTOR_SUPPLY = SS.ID_SECTOR_SUPPLY
INNER JOIN GCGT_ME_MEASURER M ON M.ID_MEASURER = MP.ID_MEASURER
INNER JOIN GCCOM_CONTRACTED_SERVICE SC ON SC.ID_SECTOR_SUPPLY = SS.ID_SECTOR_SUPPLY
INNER JOIN GCCOM_CONTRACT CO ON CO.ID_CONTRACT = SC.ID_CONTRACT
INNER JOIN GCGT_RE_MP_NATURE NAT ON NAT.ID_MP_NATURE = MP.ID_MP_NATURE
INNER JOIN GCGT_ME_MEA_CTYPE_HIST CTYP ON MP.ID_MEASURER = CTYP.ID_MEASURER
INNER JOIN GCGT_RE_MODE_TYPE MTY ON MTY.COD_DEVELOP = NAT.COD_MODO
WHERE
1 = 1
AND 1 = 1
AND CTYP.FROM_DATE <= 20130228
AND (CTYP.TO_DATE IS NULL OR CTYP.TO_DATE >= 20130201 )
AND CTYP.COD_USAGE_TYPE NOT IN ('AEH', 'R1H', 'AEQ', 'R1Q')
AND MP.CUPS IS NOT NULL
AND SC.STATUS NOT IN ('ESTSC00004', 'ESTSC00005')
AND (SC.DROP_DATE is null or SC.DROP_DATE >= (TO_DATE(20130228 , 'YYYYMMDD')) )
/*and to_char(SC.FROM_DATE,'YYYYMM') <= SUBSTR (:P_INI_DATE, 1, 6) PMR */
AND SC.FROM_DATE <= LAST_DAY(TO_DATE(20130201 , 'YYYYMMDD'))
AND (CO.STATUS not in ('ESTCO00005','ESTCO00004') or (CO.END_DATE >= (TO_DATE (20130201 , 'YYYYMMDD')) and CO.STATUS = 'ESTCO00005' ) or (CO.DROP_DATE >= (TO_DATE (20130201 , 'YYYYMMDD')) and CO.STATUS = 'ESTCO00004'))
AND EXISTS
(SELECT UTM.ID_MEASURER
FROM GCGT_ME_USAGE_TYPE_METER UTM
WHERE UTM.ID_MEASURER = MP.ID_MEASURER
AND UTM.COD_USAGE_TYPE = CTYP.COD_USAGE_TYPE
)
AND NOT EXISTS(
SELECT 1
FROM CONSUM C
WHERE C.ID_MEASURER = MP.ID_MEASURER
AND C.ID_MEASURING_POINT = MP.ID_MEASURING_POINT
AND C.CONSUM_TYPE = CTYP.COD_USAGE_TYPE))
SELECT
CORE.NISS,
CORE.ID_CONTRACT,
'' AS MOT_BLOQ,
CORE.FECHA_INI_CONTRATO,
SUBSTR (CORE.DAY, 1, 6) AS PERIODO,
EATT.FOREIGN_CONTRACT_NUMBER AS ATR_POLICY,
COM.NAME_TYPE AS COD_DISTRIBUIDORA,
--NVL (ROC.IND_CALC_ORDER, 0) AS IND_CALC_ORDER,
(SELECT COUNT (1)
FROM gccom_delivery_note dn
WHERE dn.id_contracted_service = CORE.ID_CONTRACTED_SERVICE
AND dn.delivery_note_status in ('BIDOCST001', 'BIDOCST003' )
AND dn.ind_simulated = 0
AND TO_CHAR (dn.forecast_billing_date, 'YYYYMM') >= SUBSTR (CORE.DAY, 1, 6)
AND ROWNUM < 2)
AS IND_CALC_ORDER,
--NVL (ROC.IND_SENT_FACT, 0) AS IND_SENT_FACT,
(SELECT COUNT (1)
FROM gccom_delivery_note dn
WHERE dn.id_contracted_service = CORE.ID_CONTRACTED_SERVICE
AND dn.delivery_note_status = 'BIDOCST001'
AND dn.ind_simulated = 0
AND (dn.ind_not_billed = 0 or dn.ind_not_billed is null)
AND TO_CHAR (dn.forecast_billing_date, 'YYYYMM') >= SUBSTR (CORE.DAY, 1, 6)
AND ROWNUM < 2)
AS IND_SENT_FACT,
--NVL (ROC3.IND_SENT_FACT, 0) AS IND_SENT_FACT_ANT,
(SELECT COUNT (1)
FROM gccom_delivery_note dn
WHERE dn.id_contracted_service = CORE.ID_CONTRACTED_SERVICE
AND dn.delivery_note_status = 'BIDOCST001'
AND dn.ind_simulated = 0
AND (dn.ind_not_billed = 0 or dn.ind_not_billed is null)
AND TO_CHAR(dn.forecast_billing_date, 'YYYYMM') = (select TO_CHAR(max(dn.forecast_billing_date),'YYYYMM')
FROM gccom_delivery_note dn
where dn.id_contracted_service = CORE.ID_CONTRACTED_SERVICE
and TO_CHAR(dn.forecast_billing_date, 'YYYYMM') < SUBSTR (CORE.DAY, 1, 6))
AND ROWNUM <2 )AS IND_SENT_FACT_ANT,
CORE.CUPS,
FAR.SHORT_NAME_TYPE AS TARIFA,
CT.DESCRIPTION AS TIPO_CLIENTE,
CORE.TELEMEDIDO,
CORE.RELEVANT_CONSUM_TYPE,
(
SELECT COUNT (1)
FROM GCGT_RE_READING_E RE
WHERE RE.ID_MEASURER = CORE.ID_MEASURER
AND RE.DAY BETWEEN CORE.FIRST_DAY AND CORE.LAST_DAY
) AS CLOSED,
(
SELECT COUNT (1)
FROM GCGT_RE_MEASUREMENT_POINT RRMP
WHERE RRMP.ID_SECTOR_SUPPLY = CORE.ID_SECTOR_SUPPLY
) AS MULTIPLEPM,
NVL(
(
SELECT CGMV.NAME_TYPE
FROM GCCOM_LOST_HISTORY_SS GLH
INNER JOIN GCCOM_MASTER_VALUES CGMV ON GLH.COD_VALUE = CGMV.COD_VALUE
WHERE GLH.ID_SECTOR_SUPPLY = CORE.ID_SECTOR_SUPPLY
AND TO_DATE(CORE.DAY, 'YYYYMMDD') BETWEEN GLH.INIT_DATE AND GLH.END_DATE AND ROWNUM < 2
), '') AS ITC,
CORE.CONSUM_TYPE,
CORE.VALUE_1,
CORE.VALUE_2,
CORE.VALUE_3,
CORE.VALUE_4,
CORE.VALUE_5,
CORE.VALUE_6,
CORE.VALUE_7,
CORE.VALUE_8,
CORE.VALUE_9,
CORE.VALUE_10,
CORE.VALUE_11,
CORE.VALUE_12,
CORE.VALUE_13,
CORE.VALUE_14,
CORE.VALUE_15,
CORE.VALUE_16,
CORE.VALUE_17,
CORE.VALUE_18,
CORE.VALUE_19,
CORE.VALUE_20,
CORE.VALUE_21,
CORE.VALUE_22,
CORE.VALUE_23,
CORE.VALUE_24,
CORE.VALUE_25,
CORE.SOURCE_1,
CORE.SOURCE_2,
CORE.SOURCE_3,
CORE.SOURCE_4,
CORE.SOURCE_5,
CORE.SOURCE_6,
CORE.SOURCE_7,
CORE.SOURCE_8,
CORE.SOURCE_9,
CORE.SOURCE_10,
CORE.SOURCE_11,
CORE.SOURCE_12,
CORE.SOURCE_13,
CORE.SOURCE_14,
CORE.SOURCE_15,
CORE.SOURCE_16,
CORE.SOURCE_17,
CORE.SOURCE_18,
CORE.SOURCE_19,
CORE.SOURCE_20,
CORE.SOURCE_21,
CORE.SOURCE_22,
CORE.SOURCE_23,
CORE.SOURCE_24,
CORE.SOURCE_25,
CORE.QUALITY_1,
CORE.QUALITY_2,
CORE.QUALITY_3,
CORE.QUALITY_4,
CORE.QUALITY_5,
CORE.QUALITY_6,
CORE.QUALITY_7,
CORE.QUALITY_8,
CORE.QUALITY_9,
CORE.QUALITY_10,
CORE.QUALITY_11,
CORE.QUALITY_12,
CORE.QUALITY_13,
CORE.QUALITY_14,
CORE.QUALITY_15,
CORE.QUALITY_16,
CORE.QUALITY_17,
CORE.QUALITY_18,
CORE.QUALITY_19,
CORE.QUALITY_20,
CORE.QUALITY_21,
CORE.QUALITY_22,
CORE.QUALITY_23,
CORE.QUALITY_24,
CORE.QUALITY_25,
CORE.DAY,
ORI.DESCRIPTION AS ORIGIN,
CORE.ID_CONTRACTED_SERVICE,
CORE.BAJA,
CORE.GESTION_ATR,
NVL ((SELECT IND_COGENERATION
FROM GCCOM_CONTSERV_SPECIALTYPES SP
WHERE CORE.ID_CONTRACTED_SERVICE = SP.ID_CONTRACTED_SERVICE
AND (SP.END_DATE IS NULL OR SP.END_DATE >= TO_DATE (20130228 , 'YYYYMMDD'))
AND SP.INI_DATE <= TO_DATE (20130228 , 'YYYYMMDD')), 0) AS COGENERADOR,
CORE.NISC
FROM CORE,
GCGT_ELECTRIC_ATTRIBUTES EATT,
GCCOM_COMPANY COM,
GCGT_ME_RATE_METER RM,
GCGT_ME_COMBINATION_USAGE_TYPE CUT,
GCCOM_FARE FAR,
GCGT_RE_MP_CUSTOMER_TYPE CT,
GCGT_RE_ORIGIN ORI
WHERE EATT.ID_SECTOR_SUPPLY = CORE.ID_SECTOR_SUPPLY
AND COM.ID_COMPANY = CORE.ID_DISTRIBUTER
AND CUT.ID_COMBINATION_USAGE_TYPE (+) = CORE.ID_COMBINATION_USAGE_TYPE
AND CUT.ID_RATE_METER = RM.ID_RATE_METER (+)
AND FAR.ID_FARE (+) = RM.ID_FARE
AND (CT.COD_DEVELOP = CORE.MP_FUNCTION or CORE.MP_FUNCTION is null)
AND ORI.COD_DEVELOP = CORE.ORIGIN;
The explain plan shows like this:
PLAN_TABLE_OUTPUT
-------------------------------------------------------------------------------------------------------------------------------------------------------------
Plan hash value: 398847285
-------------------------------------------------------------------------------------------------------------------------------------------------
| Id | Operation | Name | Rows | Bytes |TempSpc| Cost (%CPU)| Time | Pstart| Pstop |
-------------------------------------------------------------------------------------------------------------------------------------------------
| 0 | SELECT STATEMENT | | 186K| 63M| | 1352K (1)| 04:30:26 | | |
| 1 | SORT AGGREGATE | | 1 | 28 | | | | | |
|* 2 | COUNT STOPKEY | | | | | | | | |
| 3 | PARTITION RANGE ALL | | 2 | 56 | | 75 (0)| 00:00:01 | 1 | 108 |
|* 4 | TABLE ACCESS BY LOCAL INDEX ROWID | GCCOM_DELIVERY_NOTE | 2 | 56 | | 75 (0)| 00:00:01 | 1 | 108 |
|* 5 | INDEX RANGE SCAN | IDX_GCCOM_DELIVERY_NOTE_28 | 33 | | | 65 (0)| 00:00:01 | 1 | 108 |
| 6 | SORT AGGREGATE | | 1 | 30 | | | | | |
|* 7 | COUNT STOPKEY | | | | | | | | |
| 8 | PARTITION RANGE ALL | | 2 | 60 | | 75 (0)| 00:00:01 | 1 | 108 |
|* 9 | TABLE ACCESS BY LOCAL INDEX ROWID | GCCOM_DELIVERY_NOTE | 2 | 60 | | 75 (0)| 00:00:01 | 1 | 108 |
|* 10 | INDEX RANGE SCAN | IDX_GCCOM_DELIVERY_NOTE_28 | 33 | | | 65 (0)| 00:00:01 | 1 | 108 |
| 11 | SORT AGGREGATE | | 1 | 30 | | | | | |
|* 12 | COUNT STOPKEY | | | | | | | | |
|* 13 | FILTER | | | | | | | | |
| 14 | PARTITION RANGE ALL | | 32 | 960 | | 75 (0)| 00:00:01 | 1 | 108 |
|* 15 | TABLE ACCESS BY LOCAL INDEX ROWID | GCCOM_DELIVERY_NOTE | 32 | 960 | | 75 (0)| 00:00:01 | 1 | 108 |
|* 16 | INDEX RANGE SCAN | IDX_GCCOM_DELIVERY_NOTE_28 | 33 | | | 65 (0)| 00:00:01 | 1 | 108 |
| 17 | SORT AGGREGATE | | 1 | 14 | | | | | |
| 18 | PARTITION RANGE ALL | | 2 | 28 | | 75 (0)| 00:00:01 | 1 | 108 |
|* 19 | TABLE ACCESS BY LOCAL INDEX ROWID| GCCOM_DELIVERY_NOTE | 2 | 28 | | 75 (0)| 00:00:01 | 1 | 108 |
|* 20 | INDEX RANGE SCAN | IDX_GCCOM_DELIVERY_NOTE_28 | 33 | | | 65 (0)| 00:00:01 | 1 | 108 |
| 21 | SORT AGGREGATE | | 1 | 12 | | | | | |
|* 22 | INDEX RANGE SCAN | IDX_GCGT_RE_READING_E_16 | 1 | 12 | | 1 (0)| 00:00:01 | | |
| 23 | SORT AGGREGATE | | 1 | 6 | | | | | |
|* 24 | INDEX RANGE SCAN | IDX_GCGT_REMEASPOINT_SSMP_01 | 1 | 6 | | 1 (0)| 00:00:01 | | |
|* 25 | COUNT STOPKEY | | | | | | | | |
| 26 | NESTED LOOPS | | | | | | | | |
| 27 | NESTED LOOPS | | 1 | 61 | | 2 (0)| 00:00:01 | | |
|* 28 | TABLE ACCESS BY INDEX ROWID | GCCOM_LOST_HISTORY_SS | 1 | 30 | | 1 (0)| 00:00:01 | | |
|* 29 | INDEX RANGE SCAN | IDX_GCCOMLOSTHISTORYSS_01 | 1 | | | 1 (0)| 00:00:01 | | |
|* 30 | INDEX UNIQUE SCAN | PK_GCCOM_MASTER_VALUES | 1 | | | 1 (0)| 00:00:01 | | |
| 31 | TABLE ACCESS BY INDEX ROWID | GCCOM_MASTER_VALUES | 1 | 31 | | 1 (0)| 00:00:01 | | |
|* 32 | TABLE ACCESS BY INDEX ROWID | GCCOM_CONTSERV_SPECIALTYPES | 1 | 24 | | 1 (0)| 00:00:01 | | |
|* 33 | INDEX RANGE SCAN | IDX_GCCOMCONTSERVSPETYP_01 | 1 | | | 1 (0)| 00:00:01 | | |
|* 34 | FILTER | | | | | | | | |
|* 35 | HASH JOIN | | 186K| 63M| | 146K (1)| 00:29:16 | | |
| 36 | TABLE ACCESS FULL | GCCOM_COMPANY | 1116 | 34596 | | 9 (0)| 00:00:01 | | |
|* 37 | HASH JOIN | | 194K| 60M| 22M| 146K (1)| 00:29:16 | | |
| 38 | PART JOIN FILTER CREATE | :BF0000 | 722K| 13M| | 5316 (1)| 00:01:04 | | |
| 39 | PARTITION REFERENCE ALL | | 722K| 13M| | 5316 (1)| 00:01:04 | 1 | 10 |
| 40 | TABLE ACCESS FULL | GCGT_ELECTRIC_ATTRIBUTES | 722K| 13M| | 5316 (1)| 00:01:04 | 1 | 10 |
|* 41 | HASH JOIN | | 207K| 61M| | 136K (1)| 00:27:21 | | |
| 42 | TABLE ACCESS FULL | GCGT_RE_ORIGIN | 3 | 42 | | 3 (0)| 00:00:01 | | |
|* 43 | HASH JOIN | | 207K| 58M| 22M| 136K (1)| 00:27:21 | | |
| 44 | PARTITION REFERENCE ALL | | 486K| 17M| | 4618 (1)| 00:00:56 | 1 | 10 |
|* 45 | TABLE ACCESS FULL | GCCOM_CONTRACT | 486K| 17M| | 4618 (1)| 00:00:56 | 1 | 10 |
|* 46 | HASH JOIN | | 207K| 50M| 19M| 128K (1)| 00:25:41 | | |
| 47 | PART JOIN FILTER CREATE | :BF0001 | 286K| 16M| | 7118 (1)| 00:01:26 | | |
| 48 | PARTITION HASH ALL | | 286K| 16M| | 7118 (1)| 00:01:26 | 1 | 16 |
|* 49 | TABLE ACCESS FULL | GCCOM_CONTRACTED_SERVICE | 286K| 16M| | 7118 (1)| 00:01:26 | 1 | 16 |
|* 50 | HASH JOIN RIGHT OUTER | | 559K| 104M| | 114K (1)| 00:22:57 | | |
| 51 | TABLE ACCESS FULL | GCCOM_FARE | 374 | 3366 | | 6 (0)| 00:00:01 | | |
|* 52 | HASH JOIN RIGHT OUTER | | 559K| 99M| | 114K (1)| 00:22:57 | | |
| 53 | TABLE ACCESS FULL | GCGT_ME_RATE_METER | 59 | 590 | | 3 (0)| 00:00:01 | | |
| 54 | NESTED LOOPS SEMI | | 559K| 94M| | 114K (1)| 00:22:57 | | |
|* 55 | HASH JOIN | | 559K| 89M| 74M| 114K (1)| 00:22:57 | | |
|* 56 | TABLE ACCESS FULL | GCGT_ME_MEA_CTYPE_HIST | 2115K| 50M| | 50950 (1)| 00:10:12 | | |
|* 57 | HASH JOIN RIGHT OUTER | | 521K| 70M| | 56226 (1)| 00:11:15 | | |
| 58 | TABLE ACCESS FULL | GCGT_ME_COMBINATION_USAGE_TYPE | 378 | 3024 | | 4 (0)| 00:00:01 | | |
|* 59 | HASH JOIN | | 521K| 66M| 67M| 56219 (1)| 00:11:15 | | |
|* 60 | HASH JOIN | | 521K| 61M| 25M| 18543 (1)| 00:03:43 | | |
| 61 | PARTITION HASH AND | | 771K| 16M| | 8246 (1)| 00:01:39 |KEY(AP)|KEY(AP)|
| 62 | TABLE ACCESS FULL | GCCOM_SECTOR_SUPPLY | 771K| 16M| | 8246 (1)| 00:01:39 |KEY(AP)|KEY(AP)|
|* 63 | HASH JOIN | | 521K| 50M| | 6235 (1)| 00:01:15 | | |
|* 64 | HASH JOIN | | 260 | 11440 | | 15 (7)| 00:00:01 | | |
| 65 | MERGE JOIN CARTESIAN | | 15 | 435 | | 12 (0)| 00:00:01 | | |
| 66 | TABLE ACCESS FULL | GCGT_RE_MP_CUSTOMER_TYPE | 5 | 70 | | 3 (0)| 00:00:01 | | |
| 67 | BUFFER SORT | | 3 | 45 | | 9 (0)| 00:00:01 | | |
| 68 | TABLE ACCESS FULL | GCGT_RE_MODE_TYPE | 3 | 45 | | 2 (0)| 00:00:01 | | |
| 69 | VIEW | index$_join$_011 | 52 | 780 | | 3 (34)| 00:00:01 | | |
|* 70 | HASH JOIN | | | | | | | | |
| 71 | INDEX FAST FULL SCAN | FK_RE_MP_NATUR_RE_MODE_TYPE_01 | 52 | 780 | | 1 (0)| 00:00:01 | | |
| 72 | INDEX FAST FULL SCAN | PK_GCGT_RE_MP_NATURE | 52 | 780 | | 1 (0)| 00:00:01 | | |
|* 73 | TABLE ACCESS FULL | GCGT_RE_MEASUREMENT_POINT | 454K| 25M| | 6210 (1)| 00:01:15 | | |
| 74 | TABLE ACCESS FULL | GCGT_ME_MEASURER | 7195K| 68M| | 26770 (1)| 00:05:22 | | |
|* 75 | INDEX UNIQUE SCAN | IDX_GCGTMEUSAGETYPEMETER_08 | 10M| 96M| | 1 (0)| 00:00:01 | | |
|* 76 | TABLE ACCESS BY GLOBAL INDEX ROWID | GCGT_RE_CONSUM_H_E | 1 | 25 | | 7 (0)| 00:00:01 | 87 | 87 |
|* 77 | INDEX RANGE SCAN | IDX_GCGTRECONSUMHE02 | 1 | | | 1 (0)| 00:00:01 | | |
-------------------------------------------------------------------------------------------------------------------------------------------------
147 filas seleccionadas.
I tried with the indexes :
index IDX_GCCOM_DELIVERY_NOTE_30
on GCCOM_DELIVERY_NOTE("ID_CONTRACTED_SERVICE",TO_CHAR("FORECAST_BILLING_DATE",'YYYYMM'))
index IDX_GCCOM_DELIVERY_NOTE_31
on GCCOM_DELIVERY_NOTE("ID_CONTRACTED_SERVICE","DELIVERY_NOTE_STATUS","IND_SIMULATED",TO_CHAR("FORECAST_BILLING_DATE",'YYYYMM'));
index IDX_GCCOMLOSTHISTORYSS_02
on GCCOM_LOST_HISTORY_SS("ID_SECTOR_SUPPLY","END_DATE","COD_VALUE");
but the explain plan do not show great improvement:
PLAN_TABLE_OUTPUT
--------------------------------------------------------------------------------------------------------------------------------------------------------------------
Plan hash value: 2244861761
--------------------------------------------------------------------------------------------------------------------------------------------------
| Id | Operation | Name | Rows | Bytes |TempSpc| Cost (%CPU)| Time | Pstart| Pstop |
--------------------------------------------------------------------------------------------------------------------------------------------------
| 0 | SELECT STATEMENT | | 186K| 63M| | 1352K (1)| 04:30:26 | | |
| 1 | SORT AGGREGATE | | 1 | 25 | | | | | |
|* 2 | COUNT STOPKEY | | | | | | | | |
| 3 | INLIST ITERATOR | | | | | | | | |
|* 4 | INDEX RANGE SCAN | IDX_GCCOM_DELIVERY_NOTE_31 | 2 | 50 | | 1 (0)| 00:00:01 | | |
| 5 | SORT AGGREGATE | | 1 | 27 | | | | | |
|* 6 | COUNT STOPKEY | | | | | | | | |
|* 7 | TABLE ACCESS BY GLOBAL INDEX ROWID | GCCOM_DELIVERY_NOTE | 2 | 54 | | 1 (0)| 00:00:01 | ROWID | ROWID |
|* 8 | INDEX RANGE SCAN | IDX_GCCOM_DELIVERY_NOTE_30 | 1 | | | 1 (0)| 00:00:01 | | |
| 9 | SORT AGGREGATE | | 1 | 27 | | | | | |
|* 10 | COUNT STOPKEY | | | | | | | | |
|* 11 | TABLE ACCESS BY GLOBAL INDEX ROWID | GCCOM_DELIVERY_NOTE | 1 | 27 | | 1 (0)| 00:00:01 | ROWID | ROWID |
|* 12 | INDEX RANGE SCAN | IDX_GCCOM_DELIVERY_NOTE_30 | 1 | | | 1 (0)| 00:00:01 | | |
| 13 | SORT AGGREGATE | | 1 | 19 | | | | | |
| 14 | TABLE ACCESS BY GLOBAL INDEX ROWID| GCCOM_DELIVERY_NOTE | 2 | 38 | | 1 (0)| 00:00:01 | ROWID | ROWID |
|* 15 | INDEX RANGE SCAN | IDX_GCCOM_DELIVERY_NOTE_30 | 1 | | | 1 (0)| 00:00:01 | | |
| 16 | SORT AGGREGATE | | 1 | 12 | | | | | |
|* 17 | INDEX RANGE SCAN | IDX_GCGT_RE_READING_E_16 | 1 | 12 | | 1 (0)| 00:00:01 | | |
| 18 | SORT AGGREGATE | | 1 | 6 | | | | | |
|* 19 | INDEX RANGE SCAN | IDX_GCGT_REMEASPOINT_SSMP_01 | 1 | 6 | | 1 (0)| 00:00:01 | | |
|* 20 | COUNT STOPKEY | | | | | | | | |
| 21 | NESTED LOOPS | | | | | | | | |
| 22 | NESTED LOOPS | | 1 | 61 | | 2 (0)| 00:00:01 | | |
|* 23 | TABLE ACCESS BY INDEX ROWID | GCCOM_LOST_HISTORY_SS | 1 | 30 | | 1 (0)| 00:00:01 | | |
|* 24 | INDEX RANGE SCAN | IDX_GCCOMLOSTHISTORYSS_02 | 1 | | | 1 (0)| 00:00:01 | | |
|* 25 | INDEX UNIQUE SCAN | PK_GCCOM_MASTER_VALUES | 1 | | | 1 (0)| 00:00:01 | | |
| 26 | TABLE ACCESS BY INDEX ROWID | GCCOM_MASTER_VALUES | 1 | 31 | | 1 (0)| 00:00:01 | | |
|* 27 | TABLE ACCESS BY INDEX ROWID | GCCOM_CONTSERV_SPECIALTYPES | 1 | 24 | | 1 (0)| 00:00:01 | | |
|* 28 | INDEX RANGE SCAN | IDX_GCCOMCONTSERVSPETYP_01 | 1 | | | 1 (0)| 00:00:01 | | |
|* 29 | FILTER |
I am comparing the explain plans before and after applying indexes.
I see some changes in Access paths, but the overall result is the same.
So has the query any improvement ?
Those are the TABLE ACCESS FULL, Do I have to créate indexes on them ?
Line 43: | 36 | TABLE ACCESS FULL | GCCOM_COMPANY | 1116 | 34596 | | 9 (0)| 00:00:01 | | |
Line 47: | 40 | TABLE ACCESS FULL | GCGT_ELECTRIC_ATTRIBUTES | 722K| 13M| | 5316 (1)| 00:01:04 | 1 | 10 |
Line 49: | 42 | TABLE ACCESS FULL | GCGT_RE_ORIGIN | 3 | 42 | | 3 (0)| 00:00:01 | | |
Line 52: |* 45 | TABLE ACCESS FULL | GCCOM_CONTRACT | 486K| 17M| | 4618 (1)| 00:00:56 | 1 | 10 |
Line 56: |* 49 | TABLE ACCESS FULL | GCCOM_CONTRACTED_SERVICE | 286K| 16M| | 7118 (1)| 00:01:26 | 1 | 16 |
Line 58: | 51 | TABLE ACCESS FULL | GCCOM_FARE | 374 | 3366 | | 6 (0)| 00:00:01 | | |
Line 60: | 53 | TABLE ACCESS FULL | GCGT_ME_RATE_METER | 59 | 590 | | 3 (0)| 00:00:01 | | |
Line 63: |* 56 | TABLE ACCESS FULL | GCGT_ME_MEA_CTYPE_HIST | 2115K| 50M| | 50950 (1)| 00:10:12 | | |
Line 65: | 58 | TABLE ACCESS FULL | GCGT_ME_COMBINATION_USAGE_TYPE | 378 | 3024 | | 4 (0)| 00:00:01 | | |
Line 69: | 62 | TABLE ACCESS FULL | GCCOM_SECTOR_SUPPLY | 771K| 16M| | 8246 (1)| 00:01:39 |KEY(AP)|KEY(AP)|
Line 73: | 66 | TABLE ACCESS FULL | GCGT_RE_MP_CUSTOMER_TYPE | 5 | 70 | | 3 (0)| 00:00:01 | | |
Line 75: | 68 | TABLE ACCESS FULL | GCGT_RE_MODE_TYPE | 3 | 45 | | 2 (0)| 00:00:01 | | |
Line 80: |* 73 | TABLE ACCESS FULL | GCGT_RE_MEASUREMENT_POINT | 454K| 25M| | 6210 (1)| 00:01:15 | | |
Line 81: | 74 | TABLE ACCESS FULL | GCGT_ME_MEASURER | 7195K| 68M| | 26770 (1)| 00:05:22 | | |
I did not took into account to execute the query with GATHER_TABLE_STATS's hint, let me try !!
I come back with the results !!
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/25230194",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.