text
stringlengths 15
59.8k
| meta
dict |
---|---|
Q: Creating Angular router that handles multiple states with a single url I have an issue with ui-routing in AngularJs. I have multiple pages that i want be able to load without changing the route(url), but I also want to load particular page with changing the url.
Can some help?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/47752485",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Find index of a given number in a list python3 I've written a program that gives me the index of a given integer of my choosing (x) in a list. Also, when a given integer isn't in the list, I want the program to give me the output -1 (or None).
list = [7,13,6,1]
x = 5
for i,j in enumerate(list):
if j==x:
print(i)
else:
print(-1)
However. If I use this on for instance the list given above, the output will be
-1
-1
-1
-1
Where I only want -1. Any thoughts?
Update
I also want the program to give me only the index of the first integer it finds, whereas it now gives me the index of all the numbers, equal to x, which it finds in the list
A: You can use index, which returns the first index value if it exists and if not raises a ValueError, and a try-except clause to handle the error:
l = [7,13,6,1]
x = 5
try:
print(l.index(x))
except ValueError:
print(-1)
A: the else clause will happen on each run through the loop, if you unindent it to be on the for loop instead it will only run if the for loop does not break, and if you do find one that matches then you should break out so that it only shows the first occurence:
for i,j in enumerate(list):
if j==x:
print(i)
break
else:
print(-1)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/37141456",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: "Cannot call method 'oEmbed' of null" when embedding Soundcloud player in dynamically generated Div Using the Soundcloud JavaScript API, I want to dynamically generate a page of player widgets using track search results. My code is as follows:
<html>
<head>
<script src="http://connect.soundcloud.com/sdk.js"></script>
<script>
function makeDivsFromTracks(tracks,SC)
{
var track;
var permUrl;
var newDiv;
for(var ctr=0;ctr<tracks.length;ctr++)
{
newDiv=document.createElement("div");
newDiv.id="track"+ctr;
track=tracks[ctr];
SC.oEmbed(track.permalink_url,{color:"ff0066"},newDiv);
document.body.appendChild(newDiv);
}
}
</script>
</head>
<body>
<script>
SC.initialize({
client_id: 'MY_CLIENT_ID'
});
SC.get('/tracks',{duration:{to:900000},tags:'hitech',downloadable:true},
function(tracks,SC)
{
makeDivsFromTracks(tracks,SC);
});
</script>
</body>
</html>
When I load this, the SC.oEmbed() call throws an error:
Uncaught TypeError: Cannot call method 'oEmbed' of null
which would seem to indicate that either the divs aren't being generated or the search results aren't being returned, but if I remove the SC.oEmbed() call and replace it with:
newDiv.innerHTML=track.permalink_url;
then I get a nice list of the URLs for my search results.
And if I create a widget using a static div and static URL, e.g.
<body>
<div id="putTheWidgetHere"></div>
<script>
SC.initialize({
client_id: 'MY_CLIENT_ID'
});
SC.oEmbed("http://soundcloud.com/exampleTrack", {color: "ff0066"}, document.getElementById("putTheWidgetHere"));
</script>
</body>
then that works fine as well. So what's the problem with my oEmbed() call with these dynamically created elements?
A: Solved it. I took out the SC argument from the callback function and makeDivsFromTracks(), and now all the players show up. Not sure exactly why this works--maybe it has to do with the SC object being defined in the SDK script reference, so it's globally available and doesn't need to be passed into functions?
Anyways, working code is:
<html>
<head>
<script src="http://connect.soundcloud.com/sdk.js"></script>
<script>
function makeDivsFromTracks(tracks)
{
var track;
var permUrl;
var newDiv;
for(var ctr=0;ctr<tracks.length;ctr++)
{
newDiv=document.createElement("div");
newDiv.id="track"+ctr;
track=tracks[ctr];
//newDiv.innerHTML=track.permalink_url;
SC.oEmbed(track.permalink_url,{color:"ff0066"},newDiv);
document.body.appendChild(newDiv);
}
}
</script>
</head>
<body>
<script>
SC.initialize({
client_id: 'MY_CLIENT_ID'
});
SC.get('/tracks',{duration:{from:180000,to:900000},tags:'hitech',downloadable:true},function
(tracks){makeDivsFromTracks(tracks);});
</script>
</body>
</html>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/15355384",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: What's the proper way to reduce the space between the graph and the modebar in Dash? I'm trying to live plot some data and the sidebar is getting pushed to the right too much because of the figure dimensions. What's the proper way to control that gap?
My code:
app = dash.Dash(__name__)
app.layout = html.Div(
[
dash.dcc.Graph(id='live-graph'),
dash.dcc.Interval(id='time', interval=250),
],
style={"display": "inline-block"}
)
@app.callback(Output('live-graph', 'figure'),
[
Input('time', 'n_intervals')
]
)
def update(t):
if t is None:
return dash.no_update
fig = go.Figure(data={'data':
[
go.Scatter3d(...),
go.Scatter3d(...)
]
}
)
fig.update_layout(uirevision='constant',
scene_camera=camera,
width=2000,
height=2000,
margin=dict(l=20, r=0, t=20, b=20, pad=0),
scene=dict(xaxis=dict(range=[-10, 10]), yaxis=dict(range=[-10, 10]), zaxis=dict(range=[0, 3])))
return fig
| {
"language": "en",
"url": "https://stackoverflow.com/questions/72199366",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Why does removing "http" from a link fix it's color? Consider the following script:
a:link {
color: red;
}
<p><a href="www.honda.com">Go to Honda's official wesite </a></p>
<p><a href="http://www.honda.com">Go to Honda's official wesite once again</a></p>
The anchor element whose address doesn't start with http:// doesn't open and gives 404 error. When I open the script with notepad++ and clicks on the first link I get redirected to file:///C:/Users/user31782/Desktop/www.honda.com
*
*Why doesn't the anchor element, whose address doesn't start with http://, get redirected to www.honda.com and change to purple(as being visited) ?
A: They are both red when you first see them. After you click on one of the and come back that one becomes blue since it's marked as visited.
If you want it to still be red then you need to add this to the css rules:
a:visited {
color: red;
}
A: Short answer: you need to color the visited links:
a:visited {
color: red;
}
Long answer: links have four states (unvisited, visited, hover and active). There are four pseudo selectors that enable you to style the state of the links:
a:link {
color: red;
}
a:visited {
color: red;
}
a:hover {
color: red;
}
a:active {
color: red;
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/35799689",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Split an array into slices, with groupings I've got some Ruby code here, that works, but I'm certain I'm not doing it as efficiently as I can.
I have an Array of Objects, along this line:
[
{ name: "foo1", location: "new york" },
{ name: "foo2", location: "new york" },
{ name: "foo3", location: "new york" },
{ name: "bar1", location: "new york" },
{ name: "bar2", location: "new york" },
{ name: "bar3", location: "new york" },
{ name: "baz1", location: "chicago" },
{ name: "baz2", location: "chicago" },
{ name: "baz3", location: "chicago" },
{ name: "quux1", location: "chicago" },
{ name: "quux2", location: "chicago" },
{ name: "quux3", location: "chicago" }
]
I want to create some number of groups - say 3 - where each group contains a semi-equal amount of items, but interspersed by location.
I tried something like this:
group_size = 3
groups = []
group_size.times do
groups.push([])
end
i = 0
objects.each do |object|
groups[i].push(object)
if i < (group_size - 1)
i += 1
else
i = 0
end
end
This returns a groups object, that looks like:
[
[{:name=>"foo1", :location=>"new york"},
{:name=>"bar1", :location=>"new york"},
{:name=>"baz1", :location=>"chicago"},
{:name=>"quux1", :location=>"chicago"}],
[{:name=>"foo2", :location=>"new york"},
{:name=>"bar2", :location=>"new york"},
{:name=>"baz2", :location=>"chicago"},
{:name=>"quux2", :location=>"chicago"}],
[{:name=>"foo3", :location=>"new york"},
{:name=>"bar3", :location=>"new york"},
{:name=>"baz3", :location=>"chicago"},
{:name=>"quux3", :location=>"chicago"}]
]
So you can see there's a couple of objects from each location in each grouping.
I played around with each_slice() and group_by(), even tried to use inject([]) - but I couldn't figure out a more elegant method to do this.
I'm hoping it's something that I'm overlooking - and I need to account for more locations and a non-even number of Objects.
A: Yes, this bookkeeping with i is usually a sign there should be something better. I came up with:
ar =[
{ name: "foo1", location: "new york" },
{ name: "foo2", location: "new york" },
{ name: "foo3", location: "new york" },
{ name: "bar1", location: "new york" },
{ name: "bar2", location: "new york" },
{ name: "bar3", location: "new york" },
{ name: "baz1", location: "chicago" },
{ name: "baz2", location: "chicago" },
{ name: "baz3", location: "chicago" },
{ name: "quux1", location: "chicago" },
{ name: "quux2", location: "chicago" },
{ name: "quux3", location: "chicago" }
]
# next line handles unsorted arrays, irrelevant with this data
ar = ar.sort_by{|h| h[:location]}
num_groups = 3
groups = Array.new(num_groups){[]}
wheel = groups.cycle
ar.each{|h| wheel.next << h}
# done.
p groups
# => [[{:name=>"baz1", :location=>"chicago"}, {:name=>"quux1", :location=>"chicago"}, {:name=>"foo1", :location=>"new york"}, ...]
because I like the cycle method.
A: a.each_slice(group_size).to_a.transpose
Will work given that your data is accurately portrayed in the example. If it is not please supply accurate data so that we can answer the question more appropriately.
e.g.
a= [
{ name: "foo1", location: "new york" },
{ name: "foo2", location: "new york" },
{ name: "foo3", location: "new york" },
{ name: "bar1", location: "new york" },
{ name: "bar2", location: "new york" },
{ name: "bar3", location: "new york" },
{ name: "baz1", location: "chicago" },
{ name: "baz2", location: "chicago" },
{ name: "baz3", location: "chicago" },
{ name: "quux1", location: "chicago" },
{ name: "quux2", location: "chicago" },
{ name: "quux3", location: "chicago" }
]
group_size = 3
a.each_slice(group_size).to_a.transpose
#=> [
[
{:name=>"foo1", :location=>"new york"},
{:name=>"bar1", :location=>"new york"},
{:name=>"baz1", :location=>"chicago"},
{:name=>"quux1", :location=>"chicago"}
],
[
{:name=>"foo2", :location=>"new york"},
{:name=>"bar2", :location=>"new york"},
{:name=>"baz2", :location=>"chicago"},
{:name=>"quux2", :location=>"chicago"}
],
[
{:name=>"foo3", :location=>"new york"},
{:name=>"bar3", :location=>"new york"},
{:name=>"baz3", :location=>"chicago"},
{:name=>"quux3", :location=>"chicago"}
]
]
each_slice 3 will turn this into 4 equal groups (numbered 1,2,3) in your example. transpose will then turn these 4 groups into 3 groups of 4.
If the locations are not necessarily in order you can add sorting to the front of the method chain
a.sort_by { |h| h[:location] }.each_slice(group_size).to_a.transpose
Update
It was pointed out that an uneven number of arguments for transpose will raise. My first though was to go with @CarySwoveland's approach but since he already posted it I came up with something a little different
class Array
def indifferent_transpose
arr = self.map(&:dup)
max = arr.map(&:size).max
arr.each {|a| a.push(*([nil] * (max - a.size)))}
arr.transpose.map(&:compact)
end
end
then you can still use the same methodology
a << {name: "foobar1", location: "taiwan" }
a.each_slice(group_size).to_a.indifferent_transpose
#=> [[{:name=>"foo1", :location=>"new york"},
{:name=>"bar1", :location=>"new york"},
{:name=>"baz1", :location=>"chicago"},
{:name=>"quux1", :location=>"chicago"},
#note the extras values will be placed in the group arrays in order
{:name=>"foobar4", :location=>"taiwan"}],
[{:name=>"foo2", :location=>"new york"},
{:name=>"bar2", :location=>"new york"},
{:name=>"baz2", :location=>"chicago"},
{:name=>"quux2", :location=>"chicago"}],
[{:name=>"foo3", :location=>"new york"},
{:name=>"bar3", :location=>"new york"},
{:name=>"baz3", :location=>"chicago"},
{:name=>"quux3", :location=>"chicago"}]]
A: Here's another way to do it.
Code
def group_em(a, ngroups)
a.each_with_index.with_object(Array.new(ngroups) {[]}) {|(e,i),arr|
arr[i%ngroups] << e}
end
Example
a = [
{ name: "foo1", location: "new york" },
{ name: "foo2", location: "new york" },
{ name: "foo3", location: "new york" },
{ name: "bar1", location: "new york" },
{ name: "bar2", location: "new york" },
{ name: "bar3", location: "new york" },
{ name: "baz1", location: "chicago" },
{ name: "baz2", location: "chicago" },
{ name: "baz3", location: "chicago" },
{ name: "quux1", location: "chicago" },
{ name: "quux2", location: "chicago" }
]
Note that I've omitted the last element of a from the question in order for a to have an odd number of elements.
group_em(a,3)
#=> [[{:name=>"foo1", :location=>"new york"},
# {:name=>"bar1", :location=>"new york"},
# {:name=>"baz1", :location=>"chicago" },
# {:name=>"quux1", :location=>"chicago" }],
# [{:name=>"foo2", :location=>"new york"},
# {:name=>"bar2", :location=>"new york"},
# {:name=>"baz2", :location=>"chicago" },
# {:name=>"quux2", :location=>"chicago" }],
# [{:name=>"foo3", :location=>"new york"},
# {:name=>"bar3", :location=>"new york"},
# {:name=>"baz3", :location=>"chicago" }]]
| {
"language": "en",
"url": "https://stackoverflow.com/questions/30989340",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Why does the Eclipse debugger open up random classes when debugging? I'm new to Java and use Eclipse.
When using the debugger's step into button, it will sometimes open up a new class with loads of code and comments. It will then start stepping through a few lines of the new class it opened and then jump back to my class.
Sometimes it opens up more than one class and takes 20 steps to jump back to my code.
Can someone give me a simplified explanation why this happens and what the new class it opened is for?
A: Quoting from the article
Step into – An action to take in the debugger. If the line does not contain a function it behaves the same as “step over” but if it
does the debugger will enter the called function and continue
line-by-line debugging there.
Step over – An action to take in the debugger that will step over a given line. If the line contains a function the function will be
executed and the result returned without debugging each line.
So what is happening in your case is debugger is going through function's implementation from the framework or library that you used, which is invoked in your code.
As mentioned in the comments used step over instead of step into, so the debugger will not go through those framework or library source code.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/58478909",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Switch between remote and local sources with Typeahead.js/Bloodhound.js I've played around with every setting I can think of, e.g., .clear() and .typeahead('destroy'), and once I've set the source as remote I can't make the typeahead use a local source.
Any thoughts?
Here's the code below that gets called onclick:
var create_typeahead = function(is_remote, titles){
filters_typeahead.typeahead('destroy');
if(is_remote){
var remote_url = titles;
var titles = new Bloodhound({
queryTokenizer: Bloodhound.tokenizers.whitespace,
datumTokenizer: Bloodhound.tokenizers.whitespace,
remote: {
url: remote_url,
q=%QUERY',
wildcard: '%QUERY'
}
});
}
else{
var titles0 = titles;
var titles = new Bloodhound({
queryTokenizer: Bloodhound.tokenizers.whitespace,
datumTokenizer: Bloodhound.tokenizers.whitespace,
local: titles0
});
}
titles.initialize();
filters_typeahead.typeahead({
highlight: true,
minLength: 2,
},
{
name: 'titles',
displayKey: 'name',
source: titles,
templates: {
suggestion: function(data) {
return '<div>' + data.name + '</div>';
}
}
});
};
A: My answer is a little more involved than yours, but hopefully it will point you in the right direction.
When you want to change a remote source using bloodhound, you will have to clear the bloodhound object and reinitialize it.
Here I am creating an initializing a bloodhound instance:
var taSource = new Bloodhound({
datumTokenizer: Bloodhound.tokenizers.obj.whitespace('Value'),
queryTokenizer: Bloodhound.tokenizers.whitespace,
identify: function(obj) {
return obj.Value;
},
remote: remoteSrc
});
taSource.initialize(true);
In the logic to switch I call both clear() and initialize(true), passing true for the reinitialize paramter:
taSource.clear();
taSource.initialize(true);
I handle changing the URL in the prepare method that is available as part of the remote object.
prepare: function(query, settings) {
settings.url = urlRoot + '/' + whichType + '?q=' + query;
console.log(settings.url);
return settings;
},
Here is a full example show how I handle it.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/36298830",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Html go on top of page I have problem with tag. I create a simple page,without css file, jus to to show my problem:
http://jsfiddle.net/c7nge/
Just find select field, try to select ,and all content go up, on top of page...
Crazy :)
Here is html code :
<
!DOCTYPE html>
<html>
<head>
<title>Depaco|Strap|Box|Analise</title></title>
</head>
<body>
<header>
<div class="container clearfix">
<p class="packing ">Depaco <span>Box</span></p>
<nav>
<ul>
<li><a href="#" class="curl-top-left">Depaco <span>Stretch</span></a></li>
<li><a href="strap.php" class="curl-top-left">Depaco <span>Strap</span></a</li>
<li><a href="#" class="curl-top-left">Depaco <span>Box</span></a</li>
<li><a href="#" class="curl-top-left">Depaco <span>Analyse</span></a</li>
<li><a href="#"><span>Calculator</span></a</li>
</ul>
</nav>
</div><!-- end containe -->
</header>
<div class="content clearfix">
<form>
<div class="container ">
<div class="left-box">
<p class="red">For theoretical compression strength of box, please fill all fields...</p>
<p class="grey">Depako box is a statistical method that gives the theoretical value of box compression strength. It applies to the RSC boxes.</p>
<div class="roki"><p class="text1-box">Characteristics of box</p></div>
<div class="box-box clearfix"> <!-- Box 1-->
<p class="text">Only for box without Inner carton (reinforcement) and
without laminating the box .</p>
</div><!-- END Box 1-->
</div><!-- end left -->
<div class="right-box">
<img src="" alt="Depako Box" Title="Depako Box" class="strap-img"></img></br></br>
Here is problem: </br></br></br>
<select>
<option value ="sydney">Sydney</option>
<option value ="melbourne">Melbourne</option>
<option value ="cromwell" selected>TRY</option>
<option value ="queenstown">Queenstown</option>
</select>
</br></br></br></br>
<p class="text">Technical requirements for theoretical of compression strength: </br></br>
Maximum dimension of box is: Lx Bx H= 550x 350x 350 mm</br></br>
Maximum grammage of corrugated fiberboard is: 900 g/m2</br></br>
For other cases, please contact us.</br>
</br></p></br></br>
</div><!-- end right -->
</form>
<div class="clearfix"></div>
<footer>
<div id="footer">
<div id="logo">
<img src="images/logo.png" alt="DEPACO logo"></img>
</div><!-- end logo -->
</div>
</div><!-- end container2 -->
</footer>
</div><!-- end content -->
</div><!-- end container -->
</body>
</html>
Tnx, P
A: Maybe you should have a look at validating your HTML.
Your problem is this line:
<li><a href="#"><span>Calculator</span></a</li>
It should be:
<li><a href="#"><span>Calculator</span></a></li>
You never closed the a tag and therefor everything after it will be part of the link, also the select box.
So you are clicking on the link, not the select box.
A good way of overcoming these kinds of problems is using a good editor that will complete your code and highlights problems.
Another good way is to put your code in the http://validator.w3.org and check for errors there.
A: The only problem I see is that some of your </a> tags are cut off so they're just </a. Correcting that, it all works fine for me.
A: Many of your tags are not closed correctly (i.e. </a instead of </a>), this fixes it: http://jsfiddle.net/c7nge/1/
| {
"language": "en",
"url": "https://stackoverflow.com/questions/24762577",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-9"
} |
Q: Magento : Custom Options fields position Can you help me how can I change the position of Custom Options on product page. I mean: First product-options fields are displayed, then add_to_cart fields. I'm Very appreciated for your help.
A: If you want to change the position of the custom options then the right place for you to look is in
app/diesign/frontend/base/default/layout/catalog.xml
First you should copy this file to you theme and edit there(Is the good practice in magento).
In this file search for the code snippet as below.
<catalog_product_view translate="label">
In this reference handle you will see the blocks
<block type="catalog/product_view" name="product.info.addto" as="addto" template="catalog/product/view/addto.phtml"/>
<block type="catalog/product_view" name="product.info.addtocart" as="addtocart" template="catalog/product/view/addtocart.phtml"/>
Place these two blocks below the blocks which renders the custom options block i.e.
<block type="catalog/product_view" name="product.info.options.wrapper" as="product_options_wrapper" template="catalog/product/view/options/wrapper.phtml" translate="label">
<label>Info Column Options Wrapper</label>
<block type="core/template" name="options_js" template="catalog/product/view/options/js.phtml"/>
<block type="catalog/product_view_options" name="product.info.options" as="product_options" template="catalog/product/view/options.phtml">
<action method="addOptionRenderer"><type>text</type><block>catalog/product_view_options_type_text</block><template>catalog/product/view/options/type/text.phtml</template></action>
<action method="addOptionRenderer"><type>file</type><block>catalog/product_view_options_type_file</block><template>catalog/product/view/options/type/file.phtml</template></action>
<action method="addOptionRenderer"><type>select</type><block>catalog/product_view_options_type_select</block><template>catalog/product/view/options/type/select.phtml</template></action>
<action method="addOptionRenderer"><type>date</type><block>catalog/product_view_options_type_date</block><template>catalog/product/view/options/type/date.phtml</template></action>
</block>
<block type="core/html_calendar" name="html_calendar" as="html_calendar" template="page/js/calendar.phtml"/>
</block>
This should do the trick.
Hope this will help.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/28776764",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Programmatically select menu items of front program in objective-c Is there a method in objective-c or swift to select menu items by name and application identifier if the application is running? I see this functionality is available to the operating system under system preferences > keyboard > shortcuts, but was wondering if there was a developer facing API that would allow the same thing. The menu item should be executed without any visual queues to the user, if possible.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/41066305",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: how would i upgrade this code to work with jquery 1.6.2 how would i upgrade this code to work with jquery 1.6.2 as it only seems to work if i use Version 1.2.6.
<script type="text/javascript" charset="utf-8">
window.onload = function () {
var container = $('div.sliderGallery');
var ul = $('ul', container);
var itemsWidth = ul.innerWidth() - container.outerWidth();
$('.slider', container).slider({
min: 0,
max: itemsWidth,
handle: '.handle',
stop: function (event, ui) {
console.log(ui.value);
ul.animate({
'left': ui.value * -1
}, 500);
},
slide: function (event, ui) {
ul.css('left', ui.value * -1);
console.log(ui.value);
}
});
};
</script>
link to my issue: http://www.floodgateone.com/catering/index1.html
thanks for any help
A: If you're upgrading jQuery, then also upgrade to the latest jQuery UI where slider setup is much easier:
$(".slider").slider();
EDIT:
Working example, using latest jQuery and jQuery UI: Fiddle
Full-screen link: here
| {
"language": "en",
"url": "https://stackoverflow.com/questions/6740487",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Math ML MO uses What do following snippets of code do in Math ML files? I removed those lines and it still worked fine for me.
<mo>⁡</mo>
<mo>⁢</mo>
<mo></mo>
Answering to any of them or just letting me know what they are would be very much appreciated.
A: The first two are ⁡ function application and ⁢ invisible times. They help indicate semantic information, see this Wikipedia entry
The last one, , could be anything since it lies in the Unicode Private Use Area which is provided so that font developers can store glyphs that do not correspond to regular Unicode positions. (Unless it's a typo and really 6349 in which case it's a a Han character.)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/28889230",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: JSON object to php variables I need to convert a JSON object that the php receive from the html form into php variable. I have two forms form1 gives the values and form2 submits them. this is where I give form2 the JSON string value
-html--javascript function-
var myObj = {
"username" : theUsername,
"name" : theName,
"surname" : theSurName,
"email" : theEmail,
"password" : thePass,
"confirmpass" : thePass2,
"dob" : theDate,
"gender" : theGender,
"age" : theAge
};
var jsonstr=JSON.stringify(myObj);
document.forms["form2"]["hide"].value = jsonstr; //form2 gets the whole string
-php-
//$jstr = $_REQUEST["hide"];
//$newObj=JSON.parse(jstr);
//$name = $newObj.name;
This is what I tried, but it doesn't work
I used the post method in the html.
How do I now convert it back into seperate variables in php ?
A: Take a look at json_decode
The result of a json_decode is an associative array with the keys and values that were present in your javascript object.
If you don't know how to get the information after you've posted to a PHP script, take a look at the superglobal $_POST. If you're not familiar with that however, I suggest buying a PHP book or read trough some tutorials :)
A: If you want the string index from de JSON send it to a php page
var myObj = {
"username" : theUsername,
"name" : theName,
"surname" : theSurName,
"email" : theEmail,
"password" : thePass,
"confirmpass" : thePass2,
"dob" : theDate,
"gender" : theGender,
"age" : theAge
}
Then in the PHP Page:
extract($_POST);
Then you should see your variables $name, $surname, $email...
Source http://php.net/extract
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7088524",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Django multiple foreign keys or one enough? I'm fairly new to Django having up to this point used to it display data from other sources.
I'm embarking on a new project and have a query about the way Django handles model relations (did some searching couldn't find much for this specific instance) and am wondering the most efficient way of accomplishing it.
I have 3 Models, User(obviously :S), Project and Report. Now a report is part of a project and done by a user but project is also 'owned' by a user. In that other users cannot see either the reports/projects of another user. Do i need two foreign keys for Report or just one (e.g User creates projectA and Report1, since Report1 is linked to Project it is also linked to User) ie:
Class Report(models.Model):
user = models.ForeignKey(User)
project = models.ForeignKey(Project)
or
Class Report(models.Model):
project = models.ForeignKey(Project)
A: If a report is only associated with a user through the project (this means specifically that it makes no sense to have a report with a different user than its project) then the second one is better. You will always be able to access the user by (report object).project.user, or in search queries as 'project__user'. If you use the first one you risk getting the user data for the report and the project out of sync, which would not make sense for your app.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/10390663",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: header() loads everything on same page ajax when I click login it loads home.php on index.php and looks very strange.. is it possible to make it redirect or erase everything on index.php then load home.php
function login(){
var name = $('input#answer').val();
var pass = $('input#password').val();
if( $(name) == '' || $(pass) == '' )
$('#output').html('Please enter both username and password.');
else
$.post( ('php/login.php'), $('#myForm :input').serializeArray(),
function(data){
$('#output').html(data);
});
$('#myForm').submit(function(){
return false;
});
};
<?php
session_start();
if(isset($_SESSION['users']) != ""){
header("Location: ../php/home.php");
}
require '../php/dbConnect.php';
$username = $_POST['username'];
$password = $_POST['password'];
$query = ("SELECT * FROM `accounts` WHERE username = '$username'")or die(mysql_error());
$response = mysql_query($query);
$row = mysql_fetch_array($response);
if($row['password'] == md5($password))
{
$_SESSION['user'] = $row['username'];
header("Location: ../php/home.php");
}
else{
echo("Wrong Credentials");
}
?>
A: Perhaps try:
$_SESSION['user'] = $row['username'];
header("Location: ../php/home.php");
die();
You usually need to issue a die() command after the header() statement.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/39760997",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: change from Statements to PreparedStatements I have a simple code which sending some info into mysql.
Connection connection = null;
Statement stmt;
Properties connInfo = new Properties();
connInfo.put("user", "Main");
connInfo.put("password", "poiuyt");
connection = DriverManager.getConnection("jdbc:mysql://localhost/ABCNews", connInfo);
String sql = "insert into abcnews_topics VALUES (null, '" + text_topic + "');";
stmt = (Statement) connection.createStatement();
stmt.executeUpdate(sql);
"text_topic" it`s variable with my info.
this code i have in cycle, and in each step the value of my variable (text_topic) changes.
and i want to use Prepared Statements instead my decision.
how to do it?
A: // Create the connection (unchanged)
Properties connInfo = new Properties();
connInfo.put("user", "Main");
connInfo.put("password", "poiuyt");
Connection connection = DriverManager.getConnection("jdbc:mysql://localhost/ABCNews", connInfo);
// Prepare the statement - should only be done once, even if you are looping.
String sql = "insert into abcnews_topics VALUES (null, ?)";
PrepatedStatement stmt = connection.prepareStatement(sql);
// Bind varaibles
stmt.setString (1, text_topic); // Note that indexes are 1-based.
// Execute
stmt.executeUpdate();
A: You should parameterize your SQL, and call prepareStatement:
String sql = "insert into abcnews_topics VALUES (null, ?)";
try (PreparedStatement statement = connection.prepareStatement(sql)) {
statement.setString(1, textTopic);
statement.execute();
}
(The try-with-resources statement will close the PreparedStatement automatically. If you're using Java 6 or earlier, use a try/finally block to do it yourself.)
Note that I've changed the text_topic variable to textTopic to follow Java naming conventions, renamed stmt to statement to avoid abbreviation, and also moved the declaration of statement to the assignment. (There's no point in declaring it earlier: try to limit scope where possible.)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/19815336",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
} |
Q: Angular 2+ get specific value on selected value In the following Angular 2+ code, I have an Array in TypeScript:
models = [{idModele: 1, model: "Bianca", price: 500}, {idModele: 2, model: "etc", price: 600} ]
I would like to know, how it's done so that when I choose a specific model, I automatically receive its price in < p > balise or something else.
Here is my HTML Example:
<select class="form-control" id="modeles" formControlName="modeles">
<option selected>Choisir...</option>
<option *ngFor="let modele of modeles">{{ modele.modele }}</option>
</select>
A: Try below Code.
HTML Code:
<select class="form-control" id="modeles" [(ngModel)]="selectedValue">
<option *ngFor="let model of models" [value]="model.price">{{ model.name }}</option>
</select>
<p>{{selectedValue}}</p>
Typescript Code:
selectedValue: number;
models = [
{ idModele: 1, name: "Bianca", price: 500 },
{ idModele: 2, name: "etc", price: 600 }
];
A: You can do this easily:
Just add app.component.ts code like:
export class AppComponent {
selectedPrice:Number
models:Array<Object> = [
{idModele: 1, model: "Bianca", price: 500},
{idModele: 2, model: "etc", price: 600}
]
}
and add app.component.html code like:
<h1>Selecting Model</h1>
<select [(ngModel)]="selectedPrice">
<option *ngFor="let model of models" [ngValue]="model.price">
{{model.model}}
</option>
</select>
<hr>
<p>{{ selectedPrice }}</p>
A: Please try this
in html
<select . . . [(ngModel)]="selectedValue">
<option *ngFor="let model of models" [value]="model?.price">{{model.name}}</option>
</select>
{{selectedValue}}
in ts
selectedValue: number;
models = [
{ idModele: 1, name: "Bianca", price: 500 },
{ idModele: 2, name: "etc", price: 600 }
];
| {
"language": "en",
"url": "https://stackoverflow.com/questions/61883465",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Update header after login on GraphQL I try to update my GraphQL headers on login success. I use Apollo.
My default settings is this :
const { API_GRAPHQL_URL } = config;
const httpLink = createHttpLink({
uri: API_GRAPHQL_URL
});
const getToken = async () => await AsyncStorage.getItem('userToken');
const authLink = setContext(async (_, { headers }) => {
const token = await getToken();
return {
headers: {
...headers,
authorization: token ? `Bearer ${token}` : ''
}
};
});
const client = new ApolloClient({
link: authLink.concat(httpLink),
cache: new InMemoryCache()
});
But, if i'm not logged, the token is null. On login success, i would like update my header, or refresh, for load the token saved on localstorage (using React-Native).
Anyone know if an middleware exist or other solution ?
Thank you community !
| {
"language": "en",
"url": "https://stackoverflow.com/questions/57176409",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Xcode "Could not launch". Only reports "Security" as error I've edited the app name out. Other than that the dialog is exactly like this.
I'm developing an enterprise app and I've tried restarting xcode and the iPhone I'm developing on.
No change. Anyone encountered this? Are there any log posts that could point me in the right direction or get me more details. There is nothing in the regular log from what I can see.
Update
Found this in the device log:
<Warning>: Unable to launch com.bundleID.etc because it has an invalid code signature, inadequate entitlements or its profile has not been explicitly trusted by the user.
Which is a bit weird since it worked yesterday and all profiles etc. were issued a week ago.
A: I had the problem of not having the app on my device, so I couldn't manually launch it to accept the prompt. For me, I got this to work after deleting all expired provisioning profiles from my device, which forced Xcode to install a new one.
After this, I was able to get my app to run.
A: I just got this issue running on an iOS 8 device for the first time as it required me to launch manually on the device (it copies it fine but doesn't launch it) and then state that I trust the developer.
A: I had the same issue solved like this:
It can be happen because your developer profile is not assigned as TRUSTED in your phone or watchos settings.
You can set your profile as TRUSTED as below:
*
*Go to Settings,
*Profile
*Assign your profile as Trusted there.
A: If you sign the app with Enterprise provisioning you will get this error. It will still install the app on your phone, but apparently you cannot debug an app signed this way. You must either sign the app with Developer provisioning or manually launch the app in the phone.
A: *
*Choose Window->Devices.
*Right click on the device in left column, choose "Show Provisioning Profiles".
*Click on the provisioning profile in question.
*Press the "-" button Continue to removing all affected profiles.
*Re-install the app.
A: To fix the process launch failed: Security issue, tap the app icon on your iOS device after running the app via Xcode.
Be sure to tap the app icon while the Xcode alert is still shown. Otherwise the app will not run.
*
*Run the app via Xcode. You will see the security alert below. Do not press OK.
*On your iOS device, tap the newly installed app icon:
*After tapping the icon, you should now see an alert asking you to "Trust" the Untrusted App Developer. After doing so the app will immediately run, unconnected to the Xcode debugger.
*
*If you do not see this "Trust" alert, you likely pressed "OK" in Xcode too soon. Do not press "OK" on the Xcode alert until after trusting the developer.
*Finally, go back and press "OK" on the Xcode alert. You will have to re-run the app to connect the running app on your iOS device to the Xcode debugger.
A: Happened to me when my iPhone was in offline mode. Giving it access to the Internet fixed the problem.
A: Using xcode 7 with an iOS device running version 9.2, I had to:
*
*Open 'Settings'
*Tap 'General'
*Tap 'Device Management'
*Tap 'Developer App' that's in the list
*Tap 'Trust (developer name)'
*Tap 'Trust' in the popup
The app should load and launch when you run xcode.
A: Apparently after upgrading the OS and such you must manually launch the app on the device and say that you trust the developer of the software.
That error message disappeared now.
A: I had the same problem as above and resolved it by changing the code signing identity to iOS Developer
(I had tried all of the other steps above first)
I can now run the app in xcode and see debug output
A: My solution was, use Internet on your phone cause the app must verify the email, then build again, this time will show a popup in which you can press trust and now everything works fine.
Side note: I'am developing with Flutter
| {
"language": "en",
"url": "https://stackoverflow.com/questions/19112794",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "103"
} |
Q: not getting previous month record using datepart in sybase Using below depart syntax to fetch for previous month record, it is working fine till previous year,however it is giving 0 value in January month.How can we get pervious month with date part even if year is change ?
DATEPART(month(GETDATE()) -1
A: I understand that I used another type of DB, but I want to give a hint. I am using sql server 2019.
Firstly, you need to substitute date and only then take datepart from it.
Queries:
--dateadd -1 would subtract 1 from current month
--(Jan - 1 2022), would be December 2021
select datepart(month, dateadd(month, -1, getdate()))
--also date add covers internally the problem with 30,31 days.
--May always has 31 days, April 30. So -1 subtraction from 31th of May,would result in 30th of April.
select dateadd(month, -1, cast('2021-05-31 10:00:00' as datetime))
| {
"language": "en",
"url": "https://stackoverflow.com/questions/70617813",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: In C#, how could I move my label right at a certain speed to a certain area? I'm trying to make my label which in its original position is top left. What I want to happen is when the program starts, it'll gradually in about 1.5 seconds in a glide motion go to the center top of the application.
So how could I do that? I'm pretty sure there's a variable(s) that needs to be set. I am using Windows Forms.
A: You can do several things:
*
*Use Label control
*Use Timer and tick 1.5 seconds interval for glide motion
*On the Tick event of the timer change the location of Label.Location gradually to the center top of the application
OR
*
*Subscribe to OnPaint event
*Manually draw the label via Graphics.DrawString()
*Reposition the location of the text via DrawString() location
*Use the Timer to invalidate the painting every 1.5seconds, and Invalidate() the text position
SAMPLE
public partial class Form1 : Form
{
public Form1()
{
this.InitializeComponent();
this.InitializeTimer();
}
private void InitializeTimer()
{
this.timer1.Interval = 1500; //1.5 seconds
this.timer1.Enabled = true; //Start
}
private void timer1_Tick(object sender, EventArgs e)
{
int step = 5; //Move 5 pixels every 1.5 seconds
//Limit and stop till center-x of label reaches center-x of the form's
if ((this.label1.Location.X + (this.label1.Width / 2)) < (this.ClientRectangle.Width / 2))
//Move from left to right by incrementing x
this.label1.Location = new Point(this.label1.Location.X + step, this.label1.Location.Y);
else
this.timer1.Enabled = false; //Stop
}
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/31800185",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How can read data from Kepware server I would like to development a client app to read data from machine PLC. On this machine there is a bridge pc that have the Kepware server installed, so if I run kepware client demo toolkit I can read the value of machine. So I would like to development a client for read data from this machine.
I have find this program online but I have a problem with library when I try to run it
http://support.automation.siemens.com/WW/llisapi.dll?func=cslib.csinfo&objId=25229521&lang=en&siteid=cseus&aktprim=0&objaction=csview&extranet=standard&viewreg=WW
I see the comunication is on OPC Protocol (OLE for Process Control).
Can we help me?
A: Download and install QuickOPC 5.23(.NET Framework 3.5 or 4.0) or QuickOPC 5.31(.NET Framework 4.5) from http://opclabs.com/products/quickopc/downloads
Create a VB.NET project in VisualStudio.
Add the reference, OpcLabs.EasyOpcClassic.dll to the project.
Use the following code to read data from Kepware server using VB.NET
Imports OpcLabs.EasyOpc
Imports OpcLabs.EasyOpc.DataAccess
Public Class Demand
Private Sub frm_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
ReadPLCvalue()
End Sub
Private Sub ReadPLCvalue()
Dim objClient As New EasyDAClient
Dim sValue As Object
Try
sValue = objClient.ReadItemValue(KepwareServerMachineName, KepwareServerID, PLCTagName)
Catch ex As OpcException
End Try
StoreToDB(sValue)
End Sub
Private Sub StoreToDB(ByVal source As Object)
'Database operations to store the value.
End Sub
End Class
| {
"language": "en",
"url": "https://stackoverflow.com/questions/26676656",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: calcuate opening debit and credit and balance I am using the query to fetch data from tables to calculate the opening balance, debit, credit and closing balance from each account.The query which I am using is as below:
SELECT detail.acc_code,name, (SUM(debit) - SUM(credit)) AS opening, SUM(debit),SUM(credit) FROM header , detail ,account
WHERE header.v_id = detail.v_id
AND detail.acc_code =account.acc_code
AND date < '2020-01-01' AND date BETWEEN '2020-01-01' AND '2020-04-10'
GROUP BY detail.acc_code
please note that the date <'2020-01-01' I am using for opening balance and date between '2020-01-01' AND '2020-04-10' for calculate sum of debit and credit ahead
and I want to result is as below:
acc_code | fname | opening |debit |credit |balance
2034 | david | 100 | 200 | 50 | 250
can any body help me in this matter?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/61065028",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: No match for call operator when std::bind-ing a std::function with a std::future When I try to std::bind a std::future<T> to a std::function<void(std::future<T>)> I get a compiler i.e. template error I not completely understand. It seems to me the std::bind template deduction goes haywire but I am also not sure how to properly stick the template parameters manually.
#include <iostream>
#include <functional>
#include <future>
#include <utility>
#include <exception>
int main() {
using my_result_t = int;
std::function<void(std::future<my_result_t>)> callback {
[] (auto result) {
try {
auto result_value = result.get();
std::cout << "Result " << result_value << "\n";
} catch (std::exception& exception) {
std::cerr << exception.what() << "\n";
throw;
}
}
};
std::promise<my_result_t> promise{};
promise.set_exception(std::make_exception_ptr(std::runtime_error("Foo")));
std::future<my_result_t> future = promise.get_future();
auto f = std::bind(callback, std::move(future));
f();
}
24:7: error: no match for call to ‘(std::_Bind<std::function<void(std::future<int>)>(std::future<int>)>) ()’
24 | f();
Full error text from gcc :
[ 50%] Building CXX object CMakeFiles/untitled5.dir/main.cpp.o
/home/markus/CLionProjects/untitled5/main.cpp: In function ‘int main()’:
/home/markus/CLionProjects/untitled5/main.cpp:24:7: error: no match for call to ‘(std::_Bind<std::function<void(std::future<int>)>(std::future<int>)>) ()’
24 | f();
| ^
In file included from /home/markus/CLionProjects/untitled5/main.cpp:2:
/usr/include/c++/9.3.0/functional:480:2: note: candidate: ‘template<class ... _Args, class _Result> _Result std::_Bind<_Functor(_Bound_args ...)>::operator()(_Args&& ...) [with _Args = {_Args ...}; _Result = _Result; _Functor = std::function<void(std::future<int>)>; _Bound_args = {std::future<int>}]’
480 | operator()(_Args&&... __args)
| ^~~~~~~~
/usr/include/c++/9.3.0/functional:480:2: note: template argument deduction/substitution failed:
/usr/include/c++/9.3.0/functional: In substitution of ‘template<class _Functor, class ... _Bound_args> template<class _Fn, class _CallArgs, class ... _BArgs> using _Res_type_impl = typename std::result_of<_Fn&(std::_Bind<_Functor(_Bound_args ...)>::_Mu_type<_BArgs, _CallArgs>&& ...)>::type [with _Fn = std::function<void(std::future<int>)>; _CallArgs = std::tuple<>; _BArgs = {std::future<int>}; _Functor = std::function<void(std::future<int>)>; _Bound_args = {std::future<int>}]’:
/usr/include/c++/9.3.0/functional:447:8: required by substitution of ‘template<class _Functor, class ... _Bound_args> template<class _CallArgs> using _Res_type = std::_Bind<_Functor(_Bound_args ...)>::_Res_type_impl<_Functor, _CallArgs, _Bound_args ...> [with _CallArgs = std::tuple<>; _Functor = std::function<void(std::future<int>)>; _Bound_args = {std::future<int>}]’
/usr/include/c++/9.3.0/functional:478:9: required from here
/usr/include/c++/9.3.0/functional:443:8: error: no type named ‘type’ in ‘class std::result_of<std::function<void(std::future<int>)>&(std::future<int>&)>’
443 | using _Res_type_impl
| ^~~~~~~~~~~~~~
/usr/include/c++/9.3.0/functional:491:2: note: candidate: ‘template<class ... _Args, class _Result> _Result std::_Bind<_Functor(_Bound_args ...)>::operator()(_Args&& ...) const [with _Args = {_Args ...}; _Result = _Result; _Functor = std::function<void(std::future<int>)>; _Bound_args = {std::future<int>}]’
491 | operator()(_Args&&... __args) const
| ^~~~~~~~
/usr/include/c++/9.3.0/functional:491:2: note: template argument deduction/substitution failed:
/usr/include/c++/9.3.0/functional: In substitution of ‘template<class _Functor, class ... _Bound_args> template<class _Fn, class _CallArgs, class ... _BArgs> using _Res_type_impl = typename std::result_of<_Fn&(std::_Bind<_Functor(_Bound_args ...)>::_Mu_type<_BArgs, _CallArgs>&& ...)>::type [with _Fn = std::add_const<std::function<void(std::future<int>)> >::type; _CallArgs = std::tuple<>; _BArgs = {std::add_const<std::future<int> >::type}; _Functor = std::function<void(std::future<int>)>; _Bound_args = {std::future<int>}]’:
/usr/include/c++/9.3.0/functional:454:8: required by substitution of ‘template<class _Functor, class ... _Bound_args> template<class _CallArgs, template<class _CallArgs, template<class> class __cv_quals> template<class _Functor, class ... _Bound_args> template<class> class __cv_quals> using _Res_type_cv = std::_Bind<_Functor(_Bound_args ...)>::_Res_type_impl<typename __cv_quals<typename std::enable_if<(bool)((std::tuple_size<_Tuple>::value + 1)), _Functor>::type>::type, _CallArgs, typename __cv_quals<_Bound_args>::type ...> [with _CallArgs = std::tuple<>; __cv_quals = std::add_const; _Functor = std::function<void(std::future<int>)>; _Bound_args = {std::future<int>}]’
/usr/include/c++/9.3.0/functional:489:9: required from here
/usr/include/c++/9.3.0/functional:443:8: error: no type named ‘type’ in ‘class std::result_of<const std::function<void(std::future<int>)>&(const std::future<int>&)>’
443 | using _Res_type_impl
| ^~~~~~~~~~~~~~
/usr/include/c++/9.3.0/functional:509:2: note: candidate: ‘template<class ... _Args, class _Result> _Result std::_Bind<_Functor(_Bound_args ...)>::operator()(_Args&& ...) volatile [with _Args = {_Args ...}; _Result = _Result; _Functor = std::function<void(std::future<int>)>; _Bound_args = {std::future<int>}]’
509 | operator()(_Args&&... __args) volatile
| ^~~~~~~~
/usr/include/c++/9.3.0/functional:509:2: note: template argument deduction/substitution failed:
/usr/include/c++/9.3.0/functional: In substitution of ‘template<class _Functor, class ... _Bound_args> template<class _Fn, class _CallArgs, class ... _BArgs> using _Res_type_impl = typename std::result_of<_Fn&(std::_Bind<_Functor(_Bound_args ...)>::_Mu_type<_BArgs, _CallArgs>&& ...)>::type [with _Fn = std::add_volatile<std::function<void(std::future<int>)> >::type; _CallArgs = std::tuple<>; _BArgs = {std::add_volatile<std::future<int> >::type}; _Functor = std::function<void(std::future<int>)>; _Bound_args = {std::future<int>}]’:
/usr/include/c++/9.3.0/functional:454:8: required by substitution of ‘template<class _Functor, class ... _Bound_args> template<class _CallArgs, template<class _CallArgs, template<class> class __cv_quals> template<class _Functor, class ... _Bound_args> template<class> class __cv_quals> using _Res_type_cv = std::_Bind<_Functor(_Bound_args ...)>::_Res_type_impl<typename __cv_quals<typename std::enable_if<(bool)((std::tuple_size<_Tuple>::value + 1)), _Functor>::type>::type, _CallArgs, typename __cv_quals<_Bound_args>::type ...> [with _CallArgs = std::tuple<>; __cv_quals = std::add_volatile; _Functor = std::function<void(std::future<int>)>; _Bound_args = {std::future<int>}]’
/usr/include/c++/9.3.0/functional:506:9: required from here
/usr/include/c++/9.3.0/functional:443:8: error: no type named ‘type’ in ‘class std::result_of<volatile std::function<void(std::future<int>)>&(volatile std::future<int>&)>’
443 | using _Res_type_impl
| ^~~~~~~~~~~~~~
/usr/include/c++/9.3.0/functional:521:2: note: candidate: ‘template<class ... _Args, class _Result> _Result std::_Bind<_Functor(_Bound_args ...)>::operator()(_Args&& ...) const volatile [with _Args = {_Args ...}; _Result = _Result; _Functor = std::function<void(std::future<int>)>; _Bound_args = {std::future<int>}]’
521 | operator()(_Args&&... __args) const volatile
| ^~~~~~~~
/usr/include/c++/9.3.0/functional:521:2: note: template argument deduction/substitution failed:
/usr/include/c++/9.3.0/functional: In substitution of ‘template<class _Functor, class ... _Bound_args> template<class _Fn, class _CallArgs, class ... _BArgs> using _Res_type_impl = typename std::result_of<_Fn&(std::_Bind<_Functor(_Bound_args ...)>::_Mu_type<_BArgs, _CallArgs>&& ...)>::type [with _Fn = std::add_cv<std::function<void(std::future<int>)> >::type; _CallArgs = std::tuple<>; _BArgs = {std::add_cv<std::future<int> >::type}; _Functor = std::function<void(std::future<int>)>; _Bound_args = {std::future<int>}]’:
/usr/include/c++/9.3.0/functional:454:8: required by substitution of ‘template<class _Functor, class ... _Bound_args> template<class _CallArgs, template<class _CallArgs, template<class> class __cv_quals> template<class _Functor, class ... _Bound_args> template<class> class __cv_quals> using _Res_type_cv = std::_Bind<_Functor(_Bound_args ...)>::_Res_type_impl<typename __cv_quals<typename std::enable_if<(bool)((std::tuple_size<_Tuple>::value + 1)), _Functor>::type>::type, _CallArgs, typename __cv_quals<_Bound_args>::type ...> [with _CallArgs = std::tuple<>; __cv_quals = std::add_cv; _Functor = std::function<void(std::future<int>)>; _Bound_args = {std::future<int>}]’
/usr/include/c++/9.3.0/functional:518:9: required from here
/usr/include/c++/9.3.0/functional:443:8: error: no type named ‘type’ in ‘class std::result_of<const volatile std::function<void(std::future<int>)>&(const volatile std::future<int>&)>’
443 | using _Res_type_impl
| ^~~~~~~~~~~~~~
A: std::bind stores copies of its arguments (here a move-constructed future), and later, uses them as lvalue arguments (with some exceptions to that rule that include reference wrappers, placeholders and other bind expressions; none applicable here).
std::future is not copy-constructible. That is, a function that accepts a parameter by-value, of a type that is not copy-constructible, like your callback does, is not callable with an lvalue.
In order to make your code work, you need to adjust the signature of the callback:
std::function<void(std::future<my_result_t>&)> callback = [] (auto& result) {
// ~^~ ~^~
Preferably, though, don't use std::bind at all.
A: It might be worth mentioning that the actual solution is used was to replace the bind by a lambda. What I forgot to mention in my question was that changing the signature of the callback to a reference is not a suitable option for me, since the f callable will be copied/moved into an asynchronous queue, i.e. reactor pattern, i.e. boost::asio::post. A reference would rise lifetime challenges for the lifetime of that future. I didn't mentioned it first since I hope it would still be somehow possible with std::bind, but @piotr-skotnicki did nicely explain why its not possible. So for completeness of other searches without further ado:
std::future<my_result_t> future = promise.get_future();
auto f = [callback, future = std::move(future)] () mutable{
callback(std::move(future));
};
f();
| {
"language": "en",
"url": "https://stackoverflow.com/questions/62001192",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Unity random characters in string How do I repeat generating a random char? I want to make a glitched text effect so I set:
textbox.text = st[Random.Range(0, st.Length)];
in my update method. I do however only get one character out of this line - how would I repeat this process in a string with the length of 5? What I am trying to achieve is to randomly generate 5 characters over and over again. There must be a better way than this:
randomChar + randomChar + randomChar + randomChar + randomChar
Thank you in advance!
A: Could use something similar:
public static readonly char[] CHARS = { 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z' };
static void Main(string[] args)
{
static string GenerateGlitchedString(uint wordCount,uint wordslength)
{
string glitchedString = "";
for (int i = 0; i < wordCount; i++)
{
for (int j = 0; j < wordslength; j++)
{
Random rnd = new Random();
glitchedString += CHARS[rnd.Next(CHARS.Length)];
}
glitchedString += " "; //Add spaces
}
return glitchedString;
}
string output = GenerateGlitchedString(5, 5);
Console.WriteLine(output);
}
A: You can use Linq to generate any number of random characters from an enumerable:
int howManyChars = 5;
var newString = String.Join("", Enumerable.Range(0, howManyChars).Select(k => st[Random.Range(0, st.Length)]));
textbox.text = newString;
A: If you want completely glitchy strings, go the way of Mojibake. Take a string, convert it to one encoding and then decode it differently. Most programmers end up familiar with this kind of glitch eventually. For example this code:
const string startWith = "Now is the time for all good men to come to the aid of the party";
var asBytes = Encoding.UTF8.GetBytes(startWith);
var glitched = Encoding.Unicode.GetString(asBytes);
Debug.WriteLine(glitched);
consistently results in:
潎⁷獩琠敨琠浩潦污潧摯洠湥琠潣敭琠桴楡景琠敨瀠牡祴
But, if you just want some text with some random glitches, how about something like this. It uses a set of characters that should be glitched in, a count of how many glitches there should be in a string (based on the string length) and then randomly inserts glitches:
private static Random _rand = new Random();
private const string GlitchChars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890!@#$%&";
public static string GlitchAString(string s)
{
var glitchCount = s.Length / 5;
var buffer = s.ToCharArray();
for (var i = 0; i < glitchCount; ++i)
{
var position = _rand.Next(s.Length);
buffer[position] = GlitchChars[_rand.Next(GlitchChars.Length)];
}
var result = new string(buffer);
Debug.WriteLine(result);
return result;
}
The first two times I ran this (with that same Now is the time... string), I got:
Original String:
Now is the time for all good men to come to the aid of the party
First Two Results:
LowmiW HhZ7time for all good mea to comX to ths aid oV the p1ray
Now is fhO P!me forjall gKod men to @ome to the a@d of F5e Nawty
The algorithm is, to some extent, tunable. You can have more or fewer glitches. You can change the set of glitch chars - whatever you'd like.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/65781121",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Differences with cookies between getJSON and ajax when doing CORS I have a REST based web service running in my Tomcat Java EE servlet container.
I am writing a jquery client that is from another domain and is therefore using CORS. It hits the login web service, followed by another call. I originally implemented these two calls using getJSON and the calls were working fine, but I wasn't getting the JSESSIONID cookie to stay on the second call, so the web service had an unauthenticated session and threw and error.
After doing research, I ran across doing ajax withCredentials and thought that this is what I needed to do. The AJAX login call failed in preflight.
So, when I sniff the traffic to my webserver, the getJSON calls run as two gets and look fine except that the cookie doesn't come back with the second call. When I run the ajax call, it does an OPTIONS call to my server, gets a 200 status back on the client and then fails inside of jQuery for reasons I can't seem to find.
var jqxhr = jQuery.getJSON(loginUrl, {
xhrFields: {
withCredentials: true
},
crossDomain: true
})
.done(function(response) {
AgileJurySessionKey = response;
AgileJuryLoggedIn = true;
doneCallback();
})
.fail(function() {
failCallback();
});
Here is the AJAX version of the same call:
jQuery.ajax(loginUrl, {
type: "GET",
contentType: "application/json; charset=utf-8",
success: function(data, status, xhr) {
alert(data);
doneCallback;
},
error: function(jqxhr, textStatus, errorThrown) {
alert(errorThrown);
failCallback;
},
xhrFields: {
withCredentials: true
},
crossDomain: true
});
What's different between these two?
Here's the filter I put in to the web server for CORS:
/**
* This filter allows access to our web services from clients that are not on the local domain
*
* @author Xerox
*/
public class CorsFilter extends OncePerRequestFilter {
/* (non-Javadoc)
* @see org.springframework.web.filter.OncePerRequestFilter#doFilterInternal(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse, javax.servlet.FilterChain)
*/
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
throws ServletException, IOException {
response.addHeader("Access-Control-Allow-Origin", "*");
if (request.getHeader("Access-Control-Request-Method") != null && "OPTIONS".equals(request.getMethod())) {
// CORS "pre-flight" request
response.addHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE");
response.addHeader("Access-Control-Allow-Headers", "X-Requested-With,Origin,Content-Type,Accept,Set-Cookie");
response.addHeader("Access-Control-Max-Age", "1800");//30 min
}
filterChain.doFilter(request, response);
}
}
A:
jQuery.getJSON(loginUrl, {
xhrFields: {
withCredentials: true
},
crossDomain: true
})
The second parameter of $.getJSON is the data you want to send, not an options object. To use those, you will need to call $.ajax directly.
A: getJSON isn't really a method, it's just a convenience function that is basically a shortcut for:
$.ajax({
dataType: "json",
});
So basically, $.getJSON() should behave the same as $.ajax() with the dataType set to "json"
A: Due to continual issues with CORS, I finally gave up on this one as intractable and worked the problem from the other end.
I used a session key coming back to track the length of the session and then re-attaching security based on this, which is how I'd designed security to work in the first place.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/17704919",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Start android application from code I need simple start an application from my code, like Skype, or other one.
I read some thread, on the internet, but I haven't solution.
I tried this methode:
Intent startApp = new Intent("com.android.gesture.builder");
startActivity(startApp);
I wrote this in try/catch blokk, and the LogCat told me: ApplicationNotFound exception handled by Intent. I read the "Hello" tutorial on the Android Developers site, but it's too comlicated, to my solution...
I can't register this application starting activity to my manifest file.
I think I need to implement a new class, that extends from Activity, and implement, the code above, and try again?
Please help me, how can I start other application from my main activity easy...
A: You were nearly there!:
You just need to supply the package and class of the app you want.
// Try
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setComponent(new ComponentName("com.htc.Camera", "com.htc.Camera.Camera"));
startActivity(intent);
// catch not found (only works on HTC phones)
ComponentName
I also just saw you can do it a second way:
PackageManager packageManager = getPackageManager();
startActivity(packageManager.getLaunchIntentForPackage("com.skype.android"));
See: SOQ Ref
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7146431",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
} |
Q: Netbeans update generated project files from command line I need to setup a periodic pull & build of a native Netbeans project on a Linux box and I don't want to open the project in the Netbeans GUI to make the generated files up-to-date.
There can be at least one file in a native Netbeans project that should be different on different machines: nbproject/private/private.properties. Here's an example of a web application to build for Glassfish:
deploy.ant.properties.file=/home/admin/.netbeans/8.2/config/GlassFishEE6/Properties/gfv3-155092097.properties
j2ee.platform.is.jsr109=true
j2ee.server.domain=/opt/glassfish-4.1.2/glassfish4/glassfish/domains/domain1
j2ee.server.home=/opt/glassfish-4.1.2/glassfish4/glassfish
j2ee.server.instance=[/opt/glassfish-4.1.2/glassfish4/glassfish:/opt/glassfish-4.1.2/glassfish4/glassfish/domains/domain1]deployer:gfv3ee6wc:localhost:4848
j2ee.server.middleware=/opt/glassfish-4.1.2/glassfish4
user.properties.file=/home/admin/.netbeans/8.2/build.properties
It is not under version control, but without it Ant cannot build projects that use the Glassfish server registered in Netbeans:
[admin@funktest v24testear]$ ant -quiet clean dist
BUILD SUCCESSFUL
Total time: 16 seconds
[admin@funktest v24testear]$ rm -f nbproject/private/private.properties
[admin@funktest v24testear]$ ant -quiet clean dist
BUILD FAILED
/home/admin/Downloads/v24test/v24testear/nbproject/build-impl.xml:156: The libs.CopyLibs.classpath property is not set up.
There's also build-impl.xml that is derived from project.xml and I would like to re-generate it too.
A: A workaround to this is including and referencing the required lib in your project. For example:
*
*locate the JAR-file org-netbeans-modules-java-j2seproject-copylibstask.jar, which will typically reside in a location like C:\Program Files\NetBeans 8.2\java\ant\extra on a computer with NetBeans.
*Copy that JAR into your project, f.x. project/ant/org-netbeans-modules-java-j2seproject-copylibstask.jar.
*Open nbproject/project.properties and at the end of it add the line:
libs.CopyLibs.classpath=ant/org-netbeans-modules-java-j2seproject-copylibstask.jar
With the lib in your project and project.properties pointing to its location Ant should be able to build without an actual NetBeans installation.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/52648608",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Shrink an outer div to the size of a scaled (transformed) inner div I have an inner div that has been scaled by an arbitrary amount. I would like the size of the container div to be that of the inner div, but instead it is sized as if the inner contents were not scaled. How can I get it to shrinkwrap correctly?
#content {
background-color: blue;
height: 200px;
width: 200px;
}
#scaler {
transform: scale(0.5);
transform-origin: 0 0;
}
#outer {
background-color: red;
display: inline-block;
}
<div id="outer">
<div id="scaler">
<div id="content">
</div>
</div>
</div>
A: Too nice a challenge to pass.
Pretty sure not achievable via CSS alone, I expected it to be easier with JS.
Ended up as a bit of both:
class zoomFactor {
constructor(el) {
this.el = this.query(el, document);
this.update();
this.query('input').addEventListener('input', () => this.update());
window.addEventListener('resize', () => this.update())
}
query(s, el = this.el) {
return el.querySelector(s);
}
value() {
return this.query('input') ?
this.query('input').value :
parseFloat(this.el.dataset('scale')) || 1;
}
update() {
let val = this.value(),
z1 = this.query('z-1'),
z2 = this.query('z-2'),
z3 = this.query('z-3');
z1.style = z2.style = z3.style = '';
z2.style.width = z1.clientWidth * val + 'px';
z1.style.width = z2.style.width;
z3.style.transform = 'scale(' + val + ')';
z3.style.width = z2.clientWidth / val + 'px';
z1.style.height = z3.clientHeight * val + 'px';
}
}
new zoomFactor('zoom-factor');
.range {
display: flex;
justify-content: center;
}
.range input {
width: 70%;
}
zoom-factor {
position: relative;
display: block;
}
z-1,
z-2,
z-3 {
display: block;
color: white;
}
z-1 {
width: 50%;
float: left;
overflow: hidden;
position: relative;
margin: 1em 1em .35em;
}
z-2 {
position: absolute;
width: 100%;
background-color: red;
}
z-3 {
transform-origin: left top;
background-color: blue;
}
z-3 p {
text-align: justify;
}
p,
h3 {
padding-right: 1em;
padding-left: 1em;
}
h3 {
margin-top: 0;
padding-top: 1em;
}
z-3>*:last-child {
padding-bottom: 1em;
}
<zoom-factor>
<div class="range">
<input type="range" value=".8" min="0.05" max="1.95" step="0.01">
</div>
<z-1>
<z-2>
<z-3>
<h3>Transformed content</h3>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Elit ut aliquam purus sit amet. Non pulvinar neque laoreet suspendisse interdum consectetur libero. Sed euismod nisi porta
lorem mollis aliquam ut. Mattis nunc sed blandit libero volutpat. Bibendum at varius vel pharetra vel. Nibh situs amet commodo nulla facilisi nullam vehicula ipsum. Metus aliquam eleifend mi in nulla posuere sollicitudin. Dolor morbi non arcu
risus. Venenatis urna cursus eget nunc.</p>
<p>In tellus integer feugiat scelerisque varius morbi enim nunc faucibus. Urna molestie at elementum eu facilisis sed odio. Arcu risus quis varius quam quisque. Lorem ipsum dolor sit amet. Fringilla est ullamcorper eget nulla facilisi etiam dignissim
diam quis. Arcu bibendum at varius vel pharetra vel turpis. Consectetur a erat nam at lectus urna. Faucibus pulvinar elementum integer enim neque volutpat ac tincidunt. Diam quam nulla porttitor massa id neque aliquam vestibulum. Nam libero
justo laoreet sit amet cursus sit amet dictum. Imperdiet sed euismod nisi porta lorem. Varius vel pharetra vel turpis nunc eget lorem dolor. Vitae auctor eu augue ut lectus arcu bibendum at varius. Aliquet enim tortor at auctor urna nunc id
cursus metus. Non curabitur gravida arcu ac tortor.</p>
</z-3>
</z-2>
</z-1>
<h3>Normal content</h3>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Elit ut aliquam purus sit amet. Non pulvinar neque laoreet suspendisse interdum consectetur libero. Sed euismod nisi porta lorem
mollis aliquam ut. Mattis nunc sed blandit libero volutpat. Bibendum at varius vel pharetra vel. Nibh sit amet commodo nulla facilisi nullam vehicula ipsum. Metus aliquam eleifend mi in nulla posuere sollicitudin. Dolor morbi non arcu risus. Venenatis
urna cursus eget nunc.</p>
<p>In tellus integer feugiat scelerisque varius morbi enim nunc faucibus. Urna molestie at elementum eu facilisis sed odio. Arcu risus quis varius quam quisque. Lorem ipsum dolor sit amet. Fringilla est ullamcorper eget nulla facilisi etiam dignissim diam
quis. Arcu bibendum at varius vel pharetra vel turpis. Consectetur a erat nam at lectus urna. Faucibus pulvinar elementum integer enim neque volutpat ac tincidunt. Diam quam nulla porttitor massa id neque aliquam vestibulum. Nam libero justo laoreet
sit amet cursus sit amet dictum. Imperdiet sed euismod nisi porta lorem. Varius vel pharetra vel turpis nunc eget lorem dolor. Vitae auctor eu augue ut lectus arcu bibendum at varius. Aliquet enim tortor at auctor urna nunc id cursus metus. Non curabitur
gravida arcu ac tortor.</p>
<p>In metus vulputate eu scelerisque felis. Quam quisque id diam vel quam elementum pulvinar etiam. Porttitor leo a diam sollicitudin tempor id eu nisl. Feugiat in fermentum posuere urna nec tincidunt praesent semper feugiat. Mattis rhoncus urna neque
viverra. Euismod elementum nisi quis eleifend quam adipiscing. Enim diam vulputate ut pharetra sit amet. Adipiscing tristique risus nec feugiat in fermentum posuere urna nec. Risus sed vulputate odio ut. Augue interdum velit euismod in pellentesque.
Consequat interdum varius sit amet mattis vulputate enim nulla aliquet. At quis risus sed vulputate odio ut enim. In egestas erat imperdiet sed euismod nisi porta.</p>
<p>In arcu cursus euismod quis viverra nibh. Adipiscing commodo elit at imperdiet. Consectetur adipiscing elit duis tristique sollicitudin. Dui ut ornare lectus sit amet est placerat in. Felis eget nunc lobortis mattis. Pellentesque dignissim enim sit
amet. Senectus et netus et malesuada. A lacus vestibulum sed arcu non odio. Congue quisque egestas diam in arcu cursus euismod quis viverra. Nisi scelerisque eu ultrices vitae auctor eu augue. Sapien faucibus et molestie ac feugiat sed. Ullamcorper
a lacus vestibulum sed arcu.</p>
<p>Varius vel pharetra vel turpis nunc eget lorem. Odio ut enim blandit volutpat maecenas volutpat. Tellus in hac habitasse platea dictumst vestibulum rhoncus est. Sed sed risus pretium quam. Vel pharetra vel turpis nunc eget lorem dolor. Sit amet porttitor
eget dolor morbi. Mattis nunc sed blandit libero volutpat sed. Sit amet nulla facilisi morbi tempus iaculis urna id volutpat. Maecenas ultricies mi eget mauris pharetra et ultrices neque. Congue nisi vitae suscipit tellus. Accumsan tortor posuere
ac ut consequat semper viverra. In fermentum posuere urna nec tincidunt praesent semper feugiat nibh. Sed velit dignissim sodales ut. Tempus urna et pharetra pharetra massa massa ultricies. Ornare aenean euismod elementum nisi quis eleifend quam.
Aliquet nibh praesent tristique magna sit amet purus gravida. Euismod lacinia at quis risus sed vulputate. Ultrices mi tempus imperdiet nulla.</p>
</zoom-factor>
Most likely you won't want the input[type="range"] and want to control the scale from outside. You can simply pass <zoom-factor> a data-scale attribute and init it:
const zFactor = new zoomFactor('zoom-factor');
You don't really need to store it in a const, but it's useful for changing the scale:
zFactor.el.dataset('scale') = 0.5;
zFactor.update();
I'll probably wrap it up as a plugin, but I want to test it cross-browser and provide a few more options (i.e. allow changing the transform origin to center or right, create an auto-init method, etc...), to make it more flexible.
| {
"language": "la",
"url": "https://stackoverflow.com/questions/53485320",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: React - How does this 'SetInterval' work? I'm learning React, following their tutorial. They made a clock component which updates itself, and has these functions:
tick () {
this.setState({
date: new Date()
});
}
componentDidMount() {
this.timer = setInterval(
() => this.tick(),
1000
);
}
They called setInterval with an anonymous (arrow) function, that only calls tick.
My Question:
Why does the above work, while placing this.tick like I did below doesn't?
componentDidMount() {
this.timer = setInterval(
this.tick,
1000
);
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/42598271",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Identifying patterns in time series data I'm currently aiming to build out a system that identifies patterns in time series data.
The end goal is: Given N sections of at rest time series data, classify the section with the largest similarity between the N signals. The subpatterns are all identical or pseudo identical, but time shifted at various intervals.
I've looked at a variety of things including Dynamic Time Warping, Bag of Patterns searches, Kalman filters, and a couple other signal processing techniques that I can remember from college (Convolution, Fourier, Laplace).
However, all of them seem to fall short as the pattern isn't predefined so I can't use something like a match filter. I'm assuming I have to dip into something like an RNN or LSTM to identify the pattern between the signals.
I'm wondering if there are resources on this topic, or a proposed optimal solution before I switch over to modeling the RNN.
A: Your problem is slightly ill-defined. However, I am 99% confidenct that the answer is the matrix profile [a][b]
If you want more help, give me a more rigorous problem definition.
[a] https://www.cs.ucr.edu/~eamonn/PID4481997_extend_Matrix%20Profile_I.pdf
[b] https://www.cs.ucr.edu/~eamonn/Matrix_Profile_Tutorial_Part1.pdf
| {
"language": "en",
"url": "https://stackoverflow.com/questions/53710873",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: setting identity specification on in c# code I am trying to write a c# method to set on the identity specification. But it is not working. This is my code:
string sql = "SET IDENTITY_INSERT " + table + " ON";
string sql2 = "SET IDENTITY_INSERT " + table + " OFF";
SqlCommand cmd = new SqlCommand(sql, conn);
SqlCommand cmd2 = new SqlCommand(sql2, conn);
conn.Open();
if (identity == true)
{
cmd.ExecuteReader();
}
else
{
cmd2.ExecuteReader();
}
conn.Close();
}
The terms "table" and "identity" are parameters.
Am I doing anything wrong? Could you help me, please?
Thank you, very much!
A: The problem isn't with your code, but with your logic. Setting IDENTITY_INSERT, along with lots of other settings, is done on a per-session basis:
The Transact-SQL programming language provides several SET statements that change the current session handling of specific information.
(emphasis mine)
As soon as your connection is closed, your session is gone, and therefore the setting is also gone.
You'll need to refactor your code to include the setting of IDENTITY_INSERT so it is in the same session as the code that makes use of it.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/38332767",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to make a view from pieces aligned to each other with different behavior android Let's say I have an animal face in pieces. I have an exterior, right ear, left ear, nose, mouse, eyes.
Each of this part is independent component, so even when all of it gathered into one, animation of nose is different from ears and doesn't happen at the same time.
So my question is how can I gather items together, so in future it will be a unit, but with separated behavior? Also I don't know how to place it, that ear is animating along the face, not overlaying and not with a hole between them.
Any ideas? Thanks.
Edit
This is an example of image I have (Original cannot share).
So on this image as on example nose, eyes, hair, eyebrows are separated elements. For example if I press on hair it will start one type of animation, if I drag nose (right or left) it will animate and change volume in video player.
My best idea for now is making each component as separated view and then in layout try to gather it together somehow, but I'm not sure it is correct and good idea at all.
A: Exactly as you wrote, make separated view for each element with specific listener. Extending View should be sufficient solution - it gives you needed interfaces (e.g. OnDragListener or OnClickListener) and let you to keep clear your solution.
This seems to me like really pleasant task, which you can solve step by step, task by taks, component by component...
As to container for all animal's parts, it depends on requirements. If in all cases the eyes, ears, hairs etc. would be on the same or proportional location for every animal and you put the animal more then once, it would be worth to think about custom ViewGroup - probably RelativeLayout.
It is hard to give you more precise tips, because there will be a lot of minor and major requirements like I mentioned. For example, if size of eyes' images of two different animals aren't equal I would my components (rather than View) extend ImageView, which gives us scaling features.
Edit: I' not sure it will be possible to accomplish it in this way, but I would try to do it like that:
<RelativeLayout ...>
<!-- LAYER 1: Face - background -->
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:weightSum="100"
android:gravity="center">
<custom.path.FaceBaseComponent
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="60"
android:src="@drawable/face_drawable"/>
</LinearLayout>
<!-- LAYER 1: Ears -->
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center">
<!-- Left ear -->
<custom.path.EarComponent
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="30"
android:src="@drawable/left_ear"/>
<!-- Filler -->
<View
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="40"/>
<!-- Right ear -->
<custom.path.EarComponent
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="30"
android:src="@drawable/right_ear"/>
</LinearLayout>
</RelativeLayout>
This help you to save proportions between each element. Keep trying to merge as many "layers" as you can (maybe you can put ears and eyes inside single LinearLayout?).
| {
"language": "en",
"url": "https://stackoverflow.com/questions/30067045",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Openshift webhook branch filter I successfully installed Openshift Origin (latest), and performed automated builds.
I.e., once I pushed something on master branch, I get a build triggered through a git webhook, using the URL provided by Openshift triggers.
Now I would like to trigger a build only when a specific branch is updated.
I created a new dev branch, and added a new build with its dedicated service and route.
But when I push in master, the dev build is also triggered. The same occurs for master when I push in dev, though I updated Source ref: with the correct branch name.
However, master build uses the master branch, and dev build is done with dev branch. But I want only the dev build to be triggered when I push in dev branch only.
Here is the YAML output of the following command : oc get buildconfigs lol-master --output=yaml
apiVersion: v1
kind: BuildConfig
metadata:
annotations:
openshift.io/generated-by: OpenShiftWebConsole
creationTimestamp: 2016-04-22T06:02:16Z
labels:
app: lol-master
name: lol-master
namespace: lol
resourceVersion: "33768"
selfLink: /oapi/v1/namespaces/lol/buildconfigs/lol-master
uid: c3d383c3-084f-11e6-978b-525400659b2e
spec:
output:
to:
kind: ImageStreamTag
name: lol-master:latest
namespace: lol
postCommit: {}
resources: {}
source:
git:
ref: master
uri: http://git-ooo-labs.apps.10.2.2.2.xip.io/ooo/lol.git
secrets: null
type: Git
strategy:
sourceStrategy:
from:
kind: ImageStreamTag
name: ruby:latest
namespace: openshift
type: Source
triggers:
- github:
secret: cd02b3ebed15bc98
type: GitHub
- generic:
secret: 7be2f555e9d8a809
type: Generic
- type: ConfigChange
- imageChange:
lastTriggeredImageID: centos/ruby22-centos7@sha256:990326b8ad8c4ae2619b24d019b7871bb10ab08c41e9d5b19d0b72cb0200e28c
type: ImageChange
status:
lastVersion: 18
Am I missing something ?
Many thanks
A: You're pointing to master branch in your BuildConfig:
source:
git:
ref: master
uri: http://git-ooo-labs.apps.10.2.2.2.xip.io/ooo/lol.git
secrets: null
type: Git
but should rather point to dev, as you're saying. Generally you need separate BC for the master and dev branches and each will have the webhook configured accordingly. Additionally the format for the branch is refs/heads/dev, since that's the information OpenShift gets from github.
In the code we're checking for matching branches and ignore the hook if it doesn't match. Please check once again, and if you're still experiencing problem I'd ask you to open a bug against https://github.com/openshift/origin with detailed description.
A: I created an issue on Github related to this behavior (GitHub issue #8600). I've been said I need to use a Github webhook, and not a generic webhook in this case.
I switched the webhooks to github type, and it works like a charm.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/36789424",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How to add project reference to another Project by using latest roslyn api I am using Following Code but it did not work
MSBuildWorkspace workspace = MSBuildWorkspace.Create();
Microsoft.CodeAnalysis.Solution originalSolution = workspace.OpenSolutionAsync(sol.SolutionPath).Result;
Microsoft.CodeAnalysis.Solution newSolution = originalSolution;
ProjectReference pr = new ProjectReference(pid);
CodeAnalysis.Project prj = newSolution.Projects.Last();
prj = prj.AddProjectReference(pr);
newSolution = prj.Solution;
workspace.TryApplyChanges(newSolution);
A: MSBuildWorkspace just doesn't support propagating project references back to the project files when you call TryApplyChanges. I see you've filed the bug on CodePlex, but until that gets fixed (we're open source -- you can fix it too!) there's no workaround. If you only need to analyze the world as if that project reference exists, then you don't need to call that and can just use the Solution object you're trying to apply. If your goal is just to edit project files, another option is to use the MSBuild or XML APIs of your choice to directly manipulate the project files.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/27142506",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: printing slowly (Simulate typing) I am trying to make a textual game in python. All goes well however, I would like to make a function that will allow me to print something to the terminal, but in a fashion hat looks like typing.
Currently I have:
def print_slow(str):
for letter in str:
print letter,
time.sleep(.1)
print_slow("junk")
The output is:
j u n k
Is there a way to get rid of the spaces between the letters?
A: Try this:
def print_slow(str):
for letter in str:
sys.stdout.write(letter)
sys.stdout.flush()
time.sleep(0.1)
print_slow("Type whatever you want here")
A: This is my "type like a real person" function:
import sys,time,random
typing_speed = 50 #wpm
def slow_type(t):
for l in t:
sys.stdout.write(l)
sys.stdout.flush()
time.sleep(random.random()*10.0/typing_speed)
print ''
A: In Python 2.x you can use sys.stdout.write instead of print:
for letter in str:
sys.stdout.write(letter)
time.sleep(.1)
In Python 3.x you can set the optional argument end to the empty string:
print(letter, end='')
A: Try this:
import sys,time
def sprint(str):
for c in str + '\n':
sys.stdout.write(c)
sys.stdout.flush()
time.sleep(3./90)
sprint('hello world')
| {
"language": "en",
"url": "https://stackoverflow.com/questions/4099422",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "9"
} |
Q: Reading strange unicode character in Java? I have the following text file:
The file was saved with utf-8 encoding.
I used the following code to read the content of the file:
FileReader fr = new FileReader("f.txt");
BufferedReader br = new BufferedReader(fr);
String s1 = br.readLine();
String s2 = br.readLine();
System.out.println("s1 = " + s1.length());
System.out.println("s2 = " + s2.length());
the output:
s1 = 5
s2 = 4
Then I tried to use s1.charAt(0); to get the first character of s1 and it was '' (blank) character. That's why s1 has the length of 5. Even if I tried to use s1.trim(); its length still 5.
I dont know why that happened? It worked correctly if the file was saved with ASCII encoding.
A: Notepad apparently saved the file with a byte order mark, a nonprintable character at the beginning that just marks it as UTF-8 but is not required (and indeed not recommended) to use. You can ignore or remove it; other text editors often give you the choice of using UTF-8 with or without a BOM.
A: That's actually not a blank character, it's a BOM - Byte Order Mark. Windows uses the BOM to mark files as unicode (UTF-8, UTF-16 and UTF-32) encoded files.
I think you can save the files without the BOM even in Notepad (it's not required actually).
A: Well, you may be trying to read your file using a different encoding.
You need to use the OutputStreamReader class as the reader parameter for your BufferedReader. It does accept an encoding. Review Java Docs for it.
Somewhat like this:
BufeferedReader out = new BufferedReader(new OutputStreamReader(new FileInputStream("jedis.txt),"UTF-8")))
Or you can set the current system encoding with the system property file.encoding to UTF-8.
java -Dfile.encoding=UTF-8 com.jediacademy.Runner arg1 arg2 ...
You may also set it as a system property at runtime with System.setProperty(...) if you only need it for this specific file, but in a case like this I think I would prefer the OutputStreamWriter.
By setting the system property you can use FileReader and expect that it will use UTF-8 as the default encoding for your files. In this case for all the files that you read and write.
If you intend to detect decoding errors in your file you would be forced to use the OutputStreamReader approach and use the constructor that receives an decoder.
Somewhat like
CharsetDecoder decoder = Charset.forName("UTF-8").newDecoder();
decoder.onMalformedInput(CodingErrorAction.REPORT);
decoder.onUnmappableCharacter(CodingErrorAction.REPORT);
BufeferedReader out = new BufferedReader(new InputStreamReader(new FileInputStream("jedis.txt),decoder));
You may choose between actions IGNORE | REPLACE | REPORT
A: the null character, for example. when you use (char)0, is translated to ''
It might be that filereader is reading in a null character at the start of the file. I'm not sure why though...
A:
Even if I tried to use s1.trim(); its length still 5.
I expect that you are doing this:
s1.trim();
That doesn't do what you want it to do. Java Strings are immutable, and the trim() method is creating a new String ... which you are then throwing away. You need to do this:
s1 = s1.trim();
... which assigns the reference to the new String created by trim() to something so that you can use it.
(Note: trim() doesn't always create a new String. If the original string has no leading or trailing whitespace, the trim() method simply returns it as-is.)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/9889064",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: ComboBox Binding TextBlock Text to value DisplayMemberPath I have many comboboxes with different DisplayMemberPathes
I need create the one style with TextWrapping
App.xaml:
<Setter Property="ItemTemplate" >
<Setter.Value>
<DataTemplate >
<TextBlock Text="{Binding *what here?*}" TextWrapping="Wrap"/>
</DataTemplate>
</Setter.Value>
</Setter>
ComboBoxes:
<ComboBox DisplayMemberPath="val1" />
<ComboBox DisplayMemberPath="val2" />
<ComboBox DisplayMemberPath="val3" />
So, I know, that I can create the property Value in each ComboBoxItem class and use it
<TextBlock Text="{Binding Value }" TextWrapping="Wrap"/>
But may be there is another way without create special property?
A: If you are binding to a value type, such as a string or an int, you can simply use {Binding}, here's an example:
<DataTemplate >
<TextBlock Text="{Binding}" TextWrapping="Wrap"/>
</DataTemplate>
This kind of binding will bind to the object itself as opposed to a Property on said object.
Note: What gets displayed in the Text will be whatever gets returned by the .ToString() method on that object.
You could then override the .ToString() method in your classes to return something useful back, like this:
public class MyClass
{
public string Name { get; set; }
public override string ToString()
{
return Name;
}
}
This will force MyClass to be displayed as whatever is inside the Name property in your ComboBox.
Taking this a step further, your requirements are that you may need to put objects of different types in a single ComboBox. Not a problem, you can make use of the DataType property in a DataTemplate, see below:
<DataTemplate DataType="{x:Type myNamespace:myClass}">
...
</DataTemplate>
Note that these should be declared in a ResourceDictionary, and will affect all objects that are displayed of that type. This allows you to define what gets displayed for a given type.
A: Indeed you cannot set both DisplayMemberPath property and a specific ItemTemplate at the same time. They are mutually exclusive.
You can read it here
This property [i.e. DisplayMemberPath] is a simple way to define a default template that describes how to display the data objects
So if you need a specific item template, simply do not set the DisplayMemberPath property of your combobox (there is no need to do it).
| {
"language": "en",
"url": "https://stackoverflow.com/questions/32755652",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: javascript: var is undefined only in IE I am running into a problem in IE (works fine in chrome, firefox, and safari) where a var that I declared at the document scope is undefined and cannot be written to. It looks something like this:
myFile.js
var background;
var opacity;
var zIndex;
function backupValues() {
var overlay = $(".ui-widget-overlay");
background = overlay.css("background");
opacity = overlay.css("opacity");
zIndex = overlay.css("z-index");
}
function restoreValue() {
$(".ui-widget-overlay").css("background", background).css("opacity", opacity).css("z-index", zIndex);
}
I have debugged this in IE and found that both before and after each assignment, all the values are 'undefined'. What is wrong here? Why does this work in other browsers? Does IE have some special caveats concerning document scope variables?
A: If they're undefined after the assignment, that might mean there is simply no value assigned in the css style of the element.
That they're undefined before the assignment is how it should be in all browsers anyway. The value undefined is the default value of any (declared) variable.
Also note that "document scope" variables are actually appended to the global object (in your case most likely the window object) and it's quite a bad practice to pollute the global namespace in this way. One way to overcome it could be to have an anonymous function closure around the whole thing, like:
(function() {
var background;
var opacity;
var zIndex;
function backupValues() {
var overlay = $(".ui-widget-overlay");
background = overlay.css("background");
opacity = overlay.css("opacity");
zIndex = overlay.css("z-index");
}
function restoreValue() {
$(".ui-widget-overlay").css("background", background).css("opacity", opacity).css("z-index", zIndex);
}
window.my.fancy.namespace = {
backupValues: backupValues,
restoreValues: restoreValues
};
}());
This would make the variables local to the scope. The "undefined" behavior stays the same though, as this is how it should behave.
EDIT : although not directly related to your question, I updated the code to show how you can expose the functions to be accessible from outside while keeping the variables local.
A: Turns out the problem was in the .css() function. The jQuery function .css() is supposed to encapsulate the difference between browsers (namely IE uses a different style attribute for opacity than other browsers). However, it seems to be broken on opacity in IE. To make this work on all browsers I would have to manage a lot of properties and cases, which is a bad idea.
The solution was to avoid the problem altogether and use an overall more elegant solution. Instead of backing up the values in vars, I defined a new style in my css file for the values I was going to override. Instead of calling backupValues() and restoreValues(), I simply called .addClass("myClass") and .removeClass("myClass"). This gave me the exact same effect and doesn't have to compensate for differences in browsers which are at times quite complicated.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/9401559",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: What does 'InvokeRequired' and 'Invoke' mean in .Net? I have been working a lot with threading in a few programs I am working on, and I have always been curious as to what exactly something is doing.
Take for instance the following code, which is ran from a thread to update the UI:
Public Sub UpdateGrid()
If Me.InvokeRequired Then
Me.Invoke(New MethodInvoker(AddressOf UpdateGrid))
Else
DataGridView1.DataSource = dtResults
DataGridView1.Refresh()
btnRun.Text = "Run Query"
btnRun.ForeColor = Color.Black
End If
End Sub
What exactly does the Me.InvokeRequired check for, and what exactly is the Me.Invoke doing? I understand that somehow it gives me access to items on the UI, but how does it accomplish this?
On a side note, let's say UpdateGrid() was a function that returned a value and had a required parameter. How would I pass the parameter and how would I get the return value after I call the Me.Invoke method? I tried this without the parameter but 'nothing' was getting returned, and I couldn't figure out how to attach the parameter when invoking.
A: Me.InvokeRequired is checking to see if it's on the UI thread if not it equals True, Me.Invoke is asking for a delegate to handle communication between the diff threads.
As for your side note. I typically use an event to pass data - this event is still on the diff thread, but like above you can delegate the work.
Public Sub UpdateGrid()
'why ask if I know it on a diff thread
Me.Invoke(Sub() 'lambda sub
DataGridView1.DataSource = dtResults
DataGridView1.Refresh()
btnRun.Text = "Run Query"
btnRun.ForeColor = Color.Black
End Sub)
End Sub
A: Invoke() makes sure that the invoked method will be invoked on the UI thread. This is useful when you want to make an UI adjustment in another thread (so, not the UI thread).
InvokeRequired checks whether you need to use the Invoke() method.
A: From the example you posted, the section that needs to update the UI is part of the Invoke logic, while the retrieval of the data can be done on a worker/background thread.
If Me.InvokeRequired Then
This checks to see if Invoke() is necessary or not.
Me.Invoke(New MethodInvoker(AddressOf UpdateGrid))
This guarantees that this logic will run on the UI thread and since it is handling interacting with the UI (grid), then if you tried to run this on a background thread it would not work.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/18662905",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: if taxonomy is set show code html - wordpress Hi I have a little problem with php/wordpress and can't find answer.
There is a list and one <li> I want to show, when anything in custom taxonomy is set:
<li class="">Taste: <span><a href="#"><?php printRecipeTaste($post_ID); ?></a></span></li>
I have some php in another <li> which is working like I want but only for meta:
<?php if ( get_post_meta( get_the_ID(), 'iba', true ) ) : ?>
<img class="iba" src="<?php echo esc_url(home_url('/')); ?>/images/iba.jpg" alt="" />
<?php endif; ?>
I tried with get taxonomy_exists and is_taxonomy but I fail.
Anyone can help? Ty.
A: You should be able to use get_the_terms($id, $taxonomy). Returns false if no terms of that taxonomy are attached to the post.
https://codex.wordpress.org/Function_Reference/get_the_terms
| {
"language": "en",
"url": "https://stackoverflow.com/questions/34052916",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: parameter &usqp=mq331AQCCAE= at the url from AMP Since some days there are reffers from AMP with the &usqp=mq331AQCCAE=paramater at the url. I must rewrite this to clear my analytics reports. So:
Do some one know what is it?
A: I have ask Malte Ubl on Twitter. His anwser is:
This controls an experiment on the AMP cache.
A: According to this Google Analytics forum, the said unusual parameter has been removed. Kindly confirm if this has been reflected on yours as well.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/45089466",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Unable to find bundled Java version when installing flutter Unable to find bundled Java version when installing flutter.
A: If you check closer, there are 3 versions of Android Studio installed: version 1.2, version 1.5 and version 3.0.
Among the 3 versions, it seems that the 2 older version were the one's getting those error. And for the record it was mentioned in the documentation that you only needed the latest version of Android Studio. It means that you only need one version of Android Studio.
Before trying this, make sure that you’re on the latest version of
Android Studio and the Flutter plugins.
Also, here is a bug that was filed for this issue as reference.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/49294681",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Add and remove from ManyToMany junction table with typeorm I need to add or remove products to a group. my entities are like:
@Entity()
export class Product {
@PrimaryGeneratedColumn('uuid')
id: string;
//... some columns
@Column()
storeId: string;
@ManyToOne(() => Store, { onDelete: 'CASCADE' })
store: Store;
@ManyToMany(() => ProductGroup, (group) => group.products)
groups: ProductGroup[];
}
@Entity()
export class ProductGroup {
@PrimaryGeneratedColumn('uuid')
id: string;
//... some columns
@Column()
storeId: string;
@ManyToOne(() => Store, { onDelete: 'CASCADE' })
store: Store;
@ManyToMany(() => Product, (product) => product.albums)
@JoinTable()
products: Product[];
}
I need to verify that updating products and the group have the given storeId.
so far I came up with this solution:
async addProducts(
id: string,
storeId: string,
productIds: string[],
) {
const album = await this.productAlbumRepository.findOne({
where: { id, storeId },
relations: ['products'],
});
if (!album) new NotFoundException('product-album.notFound');
const products = await this.productsService.findBy({
storeId,
id: In(productIds),
});
album.products.push(...products);
return this.productAlbumRepository.save(album);
}
This is working fine. but my concern is that for adding a single row, I need to bring all of the related products into memory!!! can't I just push these products without joining the relations?
The other solution I thought of was to create the junction table with another entity. but I'm looking for a way to stay with @ManyToMany()
| {
"language": "en",
"url": "https://stackoverflow.com/questions/73136896",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: React Router is not rendering I am trying to understand nested react router structure. I have implemented some code from a tutorial but it is not working as expected. Here is my routes.js file.
import React from "react";
import {
BrowserRouter as Router,
Switch
} from "react-router-dom";
const ROUTES = [
{ path: "/", key: "ROOT", exact: true, component: () => <h1>Log in</h1> },
{
path: "/app",
key: "APP",
component: RenderRoutes,
routes: [
{
path: "/app",
key: "APP_ROOT",
exact: true,
component: () => <h1>App Index</h1>,
},
{
path: "/app/page",
key: "APP_PAGE",
exact: true,
component: () => <h1>App Page</h1>,
},
],
},
];
export default ROUTES;
function RouteWithSubRoutes(route) {
return (
<Router
path={route.path}
exact={route.exact}
render={props => <route.component {...props} routes={route.routes} />}
/>
);
}
export function RenderRoutes(routes ) {
return (
<Switch>
{routes.map((route, i) => {
return <RouteWithSubRoutes key={route.key} {...route} />;
})}
<Router component={() => <h1>Not Found!</h1>} />
</Switch>
);
}
I have imported
BrowserRouter
in index.js as usual. In my App component I tried to render RenderRoutes(ROUTES):
function App() {
return (
<div style={{ display: "flex", height: "100vh", alignItems: "stretch" }}>
<div style={{ flex: 0.3, backgroundColor: "#f2f2f2" }}>route menu</div>
<div>
{/* <RenderRoutes routes={ROUTES} /> This way also is not working*/}
{RenderRoutes(ROUTES)}
</div>
</div>
);
}
Here I am trying to render subcomponents but the page is not showing anything except (root menu) text from app.js. Let me know what am I doing wrong. Thanks in advance
A: The react router structure usually follows 1 Switch 1 Router and multiple Routes
<Router>
<Switch>
<Route exact path="/">
<HomePage />
</Route>
<Route path="/YOUR_PATH">
<BlogPost />
</Route>
</Switch>
</Router>,
You are returning multiple Router in RouteWithSubRoutes change that to Route
function RouteWithSubRoutes(route) {
return (
<Route
path={route.path}
exact={route.exact}
render={props => <route.component {...props} routes={route.routes} />}
/>
);
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/63658675",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: TestCafe visibilityCheck does not wait for element to appear I am trying to get TestCafe to wait for an element to appear in the dom. Currently I am using { visibilityCheck: true } but it does not seem to do anything and the test will time out and be considered a failure.
Goals:
*
*Go to page
*Wait for searchIconElement to load
Code:
fixture`Library /all`.page(page.libraryScreen).beforeEach(async t => {
await t.useRole(page.adminUser);
});
test('Search Bar', async t => {
const searchIcon = Selector('div').withAttribute('class', 'CampaignsPage-fab1');
const searchIconElement = searchIcon.with({ visibilityCheck: true })();
const microAppNameInput = Selector('input').withAttribute('placeholder', 'Search');
const microAppTitle = Selector('div').withAttribute('class', 'SetCard-title ').innerText;
await t
.click(searchIconElement)
.typeText(microAppNameInput, testMicroAppTitle)
.expect(microAppTitle)
.eql(testMicroAppTitle);
});
A: try adding timeout
const searchIconElement = searchIcon.with({ visibilityCheck: true }).with({ timeout: 10000 });
A: When a selector is passed to a test action as the target element's identifier, the target element should be visible regardless of the visibilityCheck option. If the target element becomes visible too late, you can try to increase the selector timeout.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/62866992",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Efficient Approach: JSON File Write or File Append Which approach is more efficient
1) Append few json objects in a file
2) Clear file and rewrite json
JSON Structure
{
"Regex":[],
"Entity": {"":"","":"","":""}
}
Here,I want to append some new entries in Entity.
A: Appending is much efficient, as the system is aware of the position. Whole file rewriting will take more time. Go with appending,
| {
"language": "en",
"url": "https://stackoverflow.com/questions/33493374",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Dynamic Side menu using three tier Can anyone please provide the complete c# codes for a data driven side menu in three tier architecture.i have tried for that but I don't know how to make menu dynamic
| {
"language": "en",
"url": "https://stackoverflow.com/questions/59457922",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Matlab make plot3 look like surface plot I have 3 vectors x, y and z. I am able to plot these points with plot3 however I want it to be more fancy and filled with colors like how plots look 3 dimensional with surf. Actually, my aim was for it to be like that of a surf plot however I am unable to get the results I need with surf
This is what I currently have.
x = 0:90;
y = 0:4:360;
z = ones(size(x));
z(50) = 3.6;
z(80) = 2.8;
z(10) = 2;
plot3(x,y,z);
| {
"language": "en",
"url": "https://stackoverflow.com/questions/52933506",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Cannot Login using Spring security facebook in Grails I am using the spring security facebook plugin to implement login in my grails application. I am using the 0.14.5 version of spring security facebook plugin. It was working fine until couple of months ago, now I cannot login to my application. I get the following error:
2014-12-12 16:52:50,197 [http-bio-8080-exec-1] ERROR [/testApp].[default] - Servlet.service() for servlet [default] in context with path [/testApp] threw exception [Filter execution threw an exception] with root cause
Message: org.codehaus.jackson.JsonNode
Line | Method
->> 175 | findClass in org.codehaus.groovy.tools.RootLoader
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
| 423 | loadClass in java.lang.ClassLoader
| 147 | loadClass . . . . . . . . in org.codehaus.groovy.tools.RootLoader
| 356 | loadClass in java.lang.ClassLoader
| 2451 | privateGetDeclaredMethods in java.lang.Class
| 1810 | getDeclaredMethods in ''
| 46 | getLocked . . . . . . . . in org.codehaus.groovy.util.LazyReference
| 33 | get in ''
| 59 | create . . . . . . . . . in testApp.user.FacebookAuthService
| 118 | create in com.the6hours.grails.springsecurity.facebook.DefaultFacebookAuthDao
| 67 | authenticate . . . . . . in com.the6hours.grails.springsecurity.facebook.FacebookAuthProvider
| 40 | attemptAuthentication in com.the6hours.grails.springsecurity.facebook.FacebookAuthRedirectFilter
| 1145 | runWorker . . . . . . . . in java.util.concurrent.ThreadPoolExecutor
| 615 | run in java.util.concurrent.ThreadPoolExecutor$Worker
^ 722 | run . . . . . . . . . . . in java.lang.Thread
I tried to upgrade the plugin but that did not help. During debuggin I found that I was getting access token from facebook and the error was occurring in following line
Facebook facebook = new FacebookTemplate(token.accessToken.accessToken)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/27438468",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Atom editor still let work with merged and deleted branch I needed merge additional branch to main. Github say it's successfully done but Atom still let edit merged and removed branch. What I made incorrect and how to fix it?
I made successfull pull, merged additional branch to main branch and after deleted merged additional branch successfully - all using GitHub. GitHub show I have only 1 branch now and it's main branch but my atom editor still let me switch and edit already deleted additional branch.
I tried fetch and reboot but nothing helped. I also didn't find same theme disscussion here.
My repository: https://github.com/iuriimigushin/learninghtml
A: You can do this by command prompt.
First
git checkout master
git merge page-switcher-fix
at the end
git branch -d page-switcher-fix
I hope I could have helped
A: Seems it's possible to delete removed branch .git\refs\heads in cause I step back by timemachine and bug fixed.
Anyway, best choise is step back by timemachine or same like snapshots in Virtual Machine
A: A distinction is made between remote and local branches. As you describe your case you deleted your branch remotely. For further context please see the code below for the command prompt:
# delete branch remotely
git push origin --delete page-switcher-fix
And as the solution of @Mohammad Afshar correctly suggests you can delete your branch locally as follows:
# delete branch locally
git branch -d page-switcher-fix
| {
"language": "en",
"url": "https://stackoverflow.com/questions/68716422",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How to disable Pydio password? I found this question on stack and I need to do the same thing but with their newer product Pydio. Any thoughts? The same type of config file is not present??
@user962284: Im using ajaxplorer on a local server and I dont want to use the user
authentication each time I open my browser (write the user and
password)
ajaxplorer is created with php and ajax, and I think modifying the
source code is possible to disable the user authentication, or at
least use a blank password
but, what lines of the code are necessary to modify?
The answer for this query was to:
ENABLE_USERS : Toggle user accounts on/off. If set to 0, the
application is not protected! ALLOW_GUEST_BROWSING : Toggle whether
guests (unauthenticated users) can browse your files.
How do I do this in Pydio??
A: You can enable from GUI of Pydio >> Settings >> Application Core >> Authentication >> Sele
| {
"language": "en",
"url": "https://stackoverflow.com/questions/29532440",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Using Google analytics need to papulate a report how many user comes to our site through fecebook ads We are using Word Press Multiple sites network for our organization: www.exaple.com/[multiple-subsites-here]
like www.example.com/subsite1/, www.example.com/subsite2/, www.example.com/subsite3/ etc
Also we have a sub domain like: survey.example.com where we have a survey web form.
Now we are trying to track number of users who could reach on each sub-sites using facebook to survey site and then subsite.
Some more Details:
Users comes to survey.example.com through facebook ads and after completing survey we are forwarding user to one of our sub site based on survey answer. So user flow is like:
User A: ads.facebook.com->webform.example.com->www.example.com/subsite1/
User B: ads.facebook.com->webform.example.com->www.example.com/subsite2/
User C: ads.facebook.com->webform.example.com->www.example.com/subsite6/
User D: ads.facebook.com->webform.example.com->www.example.com/subsite1/
So for all sub-sites we have created Google analytics views in a single account Like:
Webform view for:webform.example.com
Sub-site1 view for:www.example.com/subsite1/
Sub site2 view for:www.example.com/subsite2/ etc.
On “Webform” View:
We are able to calculate the user who comes from facebook Ads using Google analytic Gols through referrers etc.
On “subsite1” view:
We are able to calculate how many user comes from survey web forms to sub-site using Google analytic Gols through referrers etc.
The Issue is:
We need to calculate the user who comes from facebook to survey site and then reached to each sub-site.Any Idea how it could be achieve?
Umair
| {
"language": "en",
"url": "https://stackoverflow.com/questions/41220021",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Card Reader turns off after removal of RFID tag, won't turn back on until program is restarted I am trying to use a ACR122u NFC reader to communicate with an NFC tag. The program starts fine, and it is able to read and do all the desired operations on a tag when one is connected. However, once the NFC tag is removed, the reader turns off and will not turn on until the program restarts. Here is my code for polling the reader:
def CheckNFCCard():
getUIDCommand = [0xFF, 0xCA, 0x00, 0x00, 0x00]
turnOffBeepCommand = [0xFF, 0x00, 0x52, 0x00, 0x00]
getDataCommand = [0xFF, 0xB0, 0x00, 0x07, 0x10]
updateBlockCommandFirst=[0xFF, 0xD6, 0x00, 0x07, 0x04, 0x65, 0x6E, 0x75, 0x73]
updateBlockCommandSecond=[0xFF, 0xD6, 0x00, 0x08, 0x04, 0x65, 0x64, 0xFE, 0x00]
#get NFC reader
r = readers()
reader = r[0]
#select reader, connect
conn = reader.createConnection()
while(True):
print('NFC routine restart')
try:
conn.connect()
except:
time.sleep(1)
continue
#send hex command to turn off beeps on scan.
conn.transmit(turnOffBeepCommand)
#get data encoded on tag.
data, sw1, sw2 = conn.transmit(getDataCommand)
if (sw1, sw2) == (0x90, 0x0):
print("Status: The operation completed.")
#Turn decimal numbers into characters
stringList = [chr(x) for x in data]
#
identifierString = ''.join(stringList)[2:6]
if (identifierString == "used"):
pub.sendMessage('NFCDetected', arg1='used')
elif (identifierString == "new_"):
data, sw1, sw2 = conn.transmit(updateBlockCommandFirst)
if (sw1, sw2) == (0x90, 0x0):
conn.transmit(updateBlockCommandSecond)
Thread(target=pub.sendMessage, args=('NFCDetected',), kwargs={'new' : arg1}).Start()
time.sleep(1)
continue
The loop continues to run as expected, but the reader is shut off and will not connect again.
Any help would be much appreciated.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/59647625",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How can i change state in React for a single item inside map with onClick button? I'm trying to set state for one item whenever i click the button on it.
i have a map that runs on a list of products, it returns a card with a button in it.
i want to click on the button and then set the variable as it needs to be for the item.
for example:
const [isShown, setIsShown] = useState(false) // the state. obviously, it's going to show the result on every card inside that map.
let handleClick = (id: number) => {
getAmountOfTimesPurchased(id) // a function that returns a number
}
return (
<div>
{products.map((product: IProduct) => {
return <Card key={product.id}>
<Card.Body>
<Card.Text>
<Card.Title>
{product.name}
</Card.Title>
${product.price}
<br />
{product.amount}
</Card.Text>
</Card.Body>
<Card.Footer>
<Button onClick={() => {
handleClick(product.id)
}}>Purchased For:</Button>{isShown && timesPurchased}
</Card.Footer>
</Card>
})}
</div>
)
so, how can I show the result only for the card that I'm clicking on?
thank you so much for your help in advance!
A: Instead of a single isShown state that is a boolean value that all rendered cards are using, store the id of the card that is clicked on and is associated with the fetched data.
Example:
const [isShownId, setIsShownId] = useState(null);
const handleClick = (id: number) => {
getAmountOfTimesPurchased(id);
setIsShownId(id);
};
return (
<div>
{products.map((product: IProduct) => {
return (
<Card key={product.id}>
...
<Card.Footer>
<Button
onClick={() => {
handleClick(product.id);
}}
>
Purchased For:
</Button>
{isShownId === product.id && timesPurchased}
</Card.Footer>
</Card>
);
})}
</div>
);
| {
"language": "en",
"url": "https://stackoverflow.com/questions/74255393",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: How to pass props if it already has some value passed? function UpdatePngf(index, id) {
const [Cards, setCards] = props.value.Cards
let CardsData = Cards
var CardsObj = {
link: Cards[index].link,
icon: Cards[index].icon,
name: Cards[index].name,
png: Cards[index].png,
id: id,
}
CardsData[index] = CardsObj
setCards(CardsData)
}
export const UpdatePng = withUserData(UpdatePngf)
this is my function I want to pass props..but how I am supposed to do so??
should I do this way function UpdatePngf(index, id,props) {}? or other way
/** @format */
import React, { createContext } from 'react'
const UserData = createContext(null)
export const withUserData = (Component) => (props) => {
return (
<UserData.Consumer>
{(value) => <Component {...props} value={value}></Component>}
</UserData.Consumer>
)
}
export default UserData
This is my userData hoc..
A: I saw index, id also is props. You just update UpdatePngf:
function UpdatePngf({index, id, ...props}) { ... }
And pass props to UpdatePng wwhen using it: <UpdatePng id="...." index="..." ...yourProps>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/67454114",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Expo EAS build failure cannot load such file -- colored2 I am getting the following error when attempting to build the iOS version of my expo app using eas build -p ios --local:
[INSTALL_PODS] [!] Invalid `Podfile` file: cannot load such file -- colored2.
[INSTALL_PODS] # from /private/var/folders/yr/7xc177dn2cz107wsvzg573_m0000gn/T/eas-build-local-nodejs/c132d044-2136-499b-9471-1b0e11438b09/build/React/ios/Podfile:1
[INSTALL_PODS] # -------------------------------------------
[INSTALL_PODS] > require File.join(File.dirname(`node --print "require.resolve('expo/package.json')"`), "scripts/autolinking")
[INSTALL_PODS] # require File.join(File.dirname(`node --print "require.resolve('react-native/package.json')"`), "scripts/react_native_pods")
[INSTALL_PODS] # -------------------------------------------
This app runs locally just fine in ExpoGo but fails with the eas build both in the cloud and locally.
This issue began after running expo upgrade to update my project to expo v47.
I did a global search on my project (including node_modules folder) and didn't find any references to colored2
When I run expo doctor this is the output:
Expected package @expo/config-plugins@^5.0.2
Found invalid:
@expo/[email protected]
@expo/[email protected]
(for more info, run: npm why @expo/config-plugins)
Expected package @expo/prebuild-config@^5.0.5
Found invalid:
@expo/[email protected]
(for more info, run: npm why @expo/prebuild-config)
A: I was able to fix this by upgrading cocoapods on my computer by running brew install cocoapods. I then closed out of the terminal I was using and opened a new one.
This post helped me understand the issue
| {
"language": "en",
"url": "https://stackoverflow.com/questions/74802274",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How do I retrieve the value from table cell and send it to update page using jeditable I have mysql table-activity which has three columns, namely - id, clientname, status; and I am displaying only two columns, namely -,clientname and status using datatables.
Now I want to update my clientname value in database as well as displayed in my datatable dynamically on editing it. So for this, I used jeditable with datatable, but now I don't know how to retrieve the current cell's id and value and pass them through jeditable to my php page to edit them.Please help me out.
Thanks in advance.
Here is what i have tried so far-
Html code-
<tbody >
<?php
$sql= "SELECT * FROM `activity` ORDER BY clientname asc";
$result = mysqli_query($conn,$sql);
while($row = mysqli_fetch_assoc($result))
{
$id = $row['id'];
$name = $row['clientname'];
echo "<tr id=".$row['id']."class='edit_tr'>";
echo $id;
echo " <td class='edit'>".$row['clientname']."</td>
<td>".$row['status']."</td>
</tr>";
}
?>
</tbody>
Jquery code-
<script>
$(document).ready(function() {
/* Init DataTables */
var oTable = $('#clientsheet').dataTable();
/* Apply the jEditable handlers to the table */
$('td', oTable.fnGetNodes()).editable( 'save.php', {
tooltip : 'Click cell to edit value...',
indicator : 'Saving...',
style : 'display:block;',
submit : 'OK',
cancel : 'Cancel',
data : " {'keyid':'id','keyname':'name'}",
type : 'select',
"Callback": function( sValue, x) {
var aPos = oTable.fnGetPosition( this );
oTable.fnUpdate( sValue, aPos[0], aPos[1]);
/* Redraw the table from the new data on the server */
oTable.fnClearTable( 0 );
oTable.fnDraw();
},
"submitdata": function ( value, settings ) {
var aPos2 = oTable.fnGetPosition( this );
var id2 = oTable.fnGetData( aPos2[0] );
return {
"row_id": this.parentNode.getAttribute('id'),
"id2": id2[0],
"column": oTable.fnGetPosition( this )[ 2 ]
};
},
"height": "14px",
} );
} );
</script>
php code-
<?php
include('db.php');
$sql = "UPDATE `activity` SET clientname = '".$_POST['keyname']."' WHERE `id` = '".$_POST['id']."' ";
if($nameresult = $conn->query($sql)){
echo "successful";
}
else{
echo "failed";
}
?>
Please help me out..
Thanks in advance
| {
"language": "en",
"url": "https://stackoverflow.com/questions/38571080",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Django IntegrityError 'Column tag_id cannot be null' I'll describe the models first and explain the issue i'm having after.
class Tag(models.Model):
id = models.CharField(_(u'id'), max_length=128, primary_key=True)
class Post(models.Model):
tags = models.ManyToManyField(Tag, blank=True, null=True)
When I execute this code I get the error in the subject:
post_obj = Post.objects.get(id='someid')
tag_obj = Tag.objects.get(id='')
post_obj.tags.add(tag_obj)
Notice how the tag id is an empty string.
I've looked into what sql is being executed and it looks something like this:
INSERT INTO `post_tags` (`post_id`, `tag_id`) VALUES ('someid', NULL)
The empty string tag_id is being converted into a NULL value.
Mysql show columns output from post_tag (manytomany table):
+---------------------+--------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+---------------------+--------------+------+-----+---------+----------------+
| id | int(11) | NO | PRI | NULL | auto_increment |
| post_id | varchar(128) | NO | MUL | NULL | |
| tag_id | varchar(128) | NO | MUL | NULL | |
+---------------------+--------------+------+-----+---------+----------------+
So django is converting my empty string to NULL when adding the tag. How can I stop django from doing this?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/23766191",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Refactoring method for getting Json from a stored procedure in ASP.NET Core Please, please don't close or mark this question as duplicate, I have already looked StackOverflow and online but couldn't find solution.
Below code works great that I receive data from SQL Server via a stored procedure, then assign to a list of book model and return Json:
public IActionResult GetAllBooks()
{
List<BookViewModel> book = new List<BookViewModel>();
DataTable dataTable = new DataTable();
using (SqlConnection sqlConnection = new SqlConnection(_configuration.GetConnectionString("xxx")))
{
sqlConnection.Open();
SqlDataAdapter sqlData = new SqlDataAdapter("proc_GetBookList", sqlConnection);
sqlData.SelectCommand.CommandType = CommandType.StoredProcedure;
sqlData.Fill(dataTable);
foreach (DataRow dr in dataTable.Rows)
{
book.Add(new BookViewModel
{
Name = dr["Name"].ToString(),
Stock = Convert.ToInt32(dr["Stock"]),
});
}
}
return Json(book);
}
But I am trying to find a better way or best practice e.g serialize or any other techniques so that I don't need to create (View model and Assigning them values) like below. This is small example of only two properties but sometimes I need to map like 20 or more properties, do you guy see any problem in above code? I am new in software development world, any suggestion would be appreciated.
new BookViewModel
{
Name = dr["Name"].ToString(),
Stock = Convert.ToInt32(dr["Stock"]),
};
A: I have used Newtonsoft JSON (NuGet package) for this purpose.
Example:
using Newtonsoft.JSON;
public string DataTableToJSONWithJSONNet(DataTable table) {
string JSONString = string.Empty;
JSONString = JSONConvert.SerializeObject(table);
return JSONString;
}
You can find this Newtonsoft example and a few other methods here.
A: Using a query like you are using is pretty much going to make you use this style of assignment. Switching to Entity Framework to query your DB is going be your best bet, since it will do assignment to objects/classes automatically. But I get that doing so after a project is started can be a PITA or nearly impossible (or a very significantly large amount of work) to do. There's also a bit of a learning curve, if you've never used it before.
What you can do to make things easier is to create a constructor for your model that takes in a DataRow and assigns the data on a single place.
public BookViewModel(DataRow dr)
{
Name = dr["Name"].ToString();
Stock = Convert.ToInt32(dr["Stock"]);
}
Then you just call "book.Add(new BookViewModel(dr));" in your foreach loop. This works well if you have to do this in multiple places in your code, so you don't have to repeat the assignments when you import rows.
You might also be able to use Reflection to automatically assign the values for you. This also has a bit of a learning curve, but it can make conversions much simpler, when you have it set up.
Something similar to Reflection is AutoMapper, but that's not as popular as it used to be.
I was going to suggest using a JSON package like Newtonsoft or the built in package for C#, but it looks I got beat to that punchline.
Another option is using Dapper. It's sort of a half-step between your current system and Entity. It can use SQL or it's own query language to cast the results directly to a model. This might be the easiest and most straight forward way to refactor your code.
Dapper and Entity are examples of object relational mappers (ORMs). There are others around you can check out.
I've only listed methods I've actually used and there are many other ways to get the same thing done, even without an ORM. They all have their pros and cons, so do your research to figure out what you're willing to commit to.
A: Simply just replace your "return Json(book)" with
return Ok(book)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/69996706",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-2"
} |
Q: Is there any way to connect my google calendar to google colab? I created a project using the Google Cloud Console and created an OAuth screen. But when I used Python in colab to access the calendar, I got an error message that I don't have a proper redirect uri. Is there any way to bypass accessing my Google Calendar with my login credentials rather than using an access token
| {
"language": "en",
"url": "https://stackoverflow.com/questions/74948261",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Delete multiple datas sharing a same child from Firebase - Java I have the following Firebase database
lessons :
Id_lesson : "XXX1"
Name_lesson : "Geography"
Date_lesson : "25/09/2018"
Id_lesson : "XXX2"
Name_lesson : "Mathematics"
Date_lesson : "25/09/2018"
Id_lesson : "XXX1"
Name_lesson : "Physics"
Date_lesson : "26/09/2018"
Id_lesson : "XXX2"
Name_lesson : "Biology"
Date_lesson : "26/09/2018"
I need to delete all the lessons entries from a specific date (sharing the same Date_lesson child).
I tried this method :
private void Delete_CR_Lessons(Date date) {
final String date_to_delete_string = DateFormat.getDateInstance(DateFormat.SHORT).format(date);
Log.i("Tag", "date to delete : "+date_to_delete_string);
DatabaseReference drTest = FirebaseDatabase.getInstance().getReference();
drTest.child("lessons").addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot snapshot) {
for(DataSnapshot dataSnapshot:snapshot.getChildren()) {
Log.i("Tag", "iteration for dataSnap");
if(dataSnapshot.hasChild(date_to_delete_string)){
dataSnapshot.getRef().setValue(null);
}
}
}
@Override
public void onCancelled(DatabaseError databaseError) {
Log.w("TAG: ", databaseError.getMessage());
}
});
During execution of the method (with String date "25/09/2018" for example), the entries are not deleted from Firebase Database. I see the two logs I specified but I also see a log called
"I/chatty: uid=10298(com.example.myname.lessonsmanagment) identical 2 lines"
I suppose that the method doesn't work because it cannot detect both Lessons from date 25/09/2018 (Geography and Mathematics) on the same time.
Does anyone have an idea on how to make it work ?
A: first of all, you need to query/order the data with the date
you can simply do it using this sample.
mRef.child("lessons").orderByKey().equalTo(Date_lesson)
.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot postsnapshot :dataSnapshot.getChildren()) {
String key = postsnapshot.getKey();
dataSnapshot.getRef().removeValue();
}
});
where mRefis you lessons branch ref
| {
"language": "en",
"url": "https://stackoverflow.com/questions/52355632",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Destructuring object passed like argument to a function Don't know if is possible with ES6.
I'm working in a project that have a function which is passed an Object with lots of properties. Right now the code is as follows:
function foo({arg1,arg2,arg3,arg4,arg5,arg6,arg7,arg8}){
this.model = arg1;
this.model = arg2;
// and so on...
};
obj = {
arg1: 'some',
arg2: 'whatever',
arg3: 'text'
// and so on up to 8
arg8: 'end text'
}
foo(obj);
Mi DESIRED output would be,if possible, accessing the parameters like this:
function foo( {...args} ){ // not working
this.model = arg1;
this.model = arg2;
// and so on...
};
obj = {
arg1: 'some',
arg2: 'whatever',
arg3: 'text'
// and so on up to 8
arg8: 'end text'
}
foo(obj);
So question is: is there any way for the function to get parameter object in a single var (args) AND have them destructured to be ready to use?
A: there are couple of ways to do it.
the first one would be to store all argumens in a variable then do destruct it
function foo(...args){
const { arg1, arg2 } = args
this.model = arg1;
this.model = arg2;
// and so on...
};
Or
function foo({ arg1, arg2 }){
this.model = arg1;
this.model = arg2;
// and so on...
};
| {
"language": "en",
"url": "https://stackoverflow.com/questions/54130263",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Backbone.js View removing and unbinding when my page opens, I call the collection and populate the view:
var pagColl = new pgCollection(e.models);
var pagView = new pgView({collection: pagColl});
Separately (via a Datepicker), I wish to want to populate the same collection with different models and instantiate the view again.
The problem I have is how to close the original pagView and empty the pagColl before I open the new one, as this "ghost view" is creating problems for me. The variables referred to above are local variables? is it that I need to create a global pagColl and reset() this?
A: well there has been many discussion on this topic actually,
backbone does nothing for you, you will have to do it yourself and this is what you have to take care of:
*
*removing the view (this delegates to jQuery, and jquery removes it from the DOM)
// to be called from inside your view... otherwise its `view.remove();`
this.remove();
this removes the view from the DOM and removes all DOM events bound to it.
*removing all backbone events
// to be called from inside the view... otherwise it's `view.unbind();`
this.unbind();
this removes all events bound to the view, if you have a certain event in your view (a button) which delegates to a function that calls this.trigger('myCustomEvent', params);
if you want some idea's on how to implement a system I suggest you read up on Derrick Bailey's blogpost on zombie views: http://lostechies.com/derickbailey/2011/09/15/zombies-run-managing-page-transitions-in-backbone-apps/.
another option
another option would be to reuse your current view, and have it re-render or append certain items in the view, bound to the collection's reset event
A: I was facing the same issue. I call the view.undelegateEvents() method.
Removes all of the view's delegated events. Useful if you want to disable or remove a view from the DOM temporarily.
A: I use the stopListening method to solve the problem, usually I don't want to remove the entire view from the DOM.
view.stopListening();
Tell an object to stop listening to events. Either call stopListening
with no arguments to have the object remove all of its registered
callbacks ... or be more precise by telling it to remove just the
events it's listening to on a specific object, or a specific event, or
just a specific callback.
http://backbonejs.org/#Events-stopListening
A: Here's one alternative I would suggest to use, by using Pub/Sub pattern.
You can set up the events bound to the View, and choose a condition for such events.
For example, PubSub.subscribe("EVENT NAME", EVENT ACTIONS, CONDITION); in the condition function, you can check if the view is still in the DOM.
i.e.
var unsubscribe = function() {
return (this.$el.closest("body").length === 0);
};
PubSub.subscribe("addSomething",_.bind(this.addSomething, this), unsubscribe);
Then, you can invoke pub/sub via PubSub.pub("addSomething"); in other places and not to worry about duplicating actions.
Of course, there are trade-offs, but this way not seems to be that difficult.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/9080763",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: BETWEEN query using JDBC with MySQL public int getdata(String startDate, String endDate) {
PreparedStatement ps;
int id = 0;
try {
/*
* SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yyyy");
* java.util.Date startDat = formatter.parse(startDate);
* java.util.Date endDat = formatter.parse(endDate);
*/
// ps = connection.prepareStatement("select * from project.order Where PO_Date Between " + startDate + "' AND '" + endDate + "'");
//ps = connection.prepareStatement("select * from project.order where PO_Date between ? AND DATE_ADD( ?, INTERVAL 1 DAY) ");
//ps = connection.prepareStatement("SELECT * FROM project.order WHERE PO_Date between ? AND ?");
ps = connection.prepareStatement("SELECT * FROM project.order WHERE PO_Date >= ? AND PO_Date <= ?");
//ps = connection.prepareStatement("SELECT * FROM project.order WHERE PO_Date(now())>= ? AND PO_Date(now())<=?");
/*
* ps.setDate(1, new java.sql.Date(startDate)); ps.setDate(2, new
* java.sql.Date(endDate.getTime()));
*/
ps.setString(1, startDate);
ps.setString(2, endDate);
ResultSet rs = ps.executeQuery();
// System.out.println("value of rs "+rs);
while (rs.next()) {
ArrayList<String> arrlist = new ArrayList<String>();
System.out.println(rs.getString(2));
System.out.println(rs.getInt(1));
System.out.println(rs.getString(4));
System.out.println(rs.getString(5));
System.out.println(rs.getString(6));
System.out.println("***************");
// System.out.print(rs.getDate("endDate"));
Iterator<String> itr = arrlist.iterator();
while (itr.hasNext()) {
System.out.println(itr.next());
}
}
rs.close();
} catch (Exception e) {
System.out.println(e.getMessage());
}
return id;
}
}
I tried to solve but I am getting out except last date means endDate which we give as a input.
I tried around 5 different queries but still I am getting the same.
A: In MySQL, the DATE type maps to the Java class java.sql.Timestamp. So you should be working with this type to build your query, and not java.util.Date. Here is code which generates the two timestamps you will need:
SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yyyy");
java.util.Date startDate = formatter.parse(startDate);
java.util.Date endDate = formatter.parse(endDate);
java.sql.Timestamp start = new Timestamp(startDate.getTime());
java.sql.Timestamp end = new Timestamp(endDate.getTime());
Then use your first BETWEEN query to get your result:
PreparedStatement ps = con.prepareStatement("SELECT * FROM project.order
WHERE PO_Date BETWEEN ? AND ?");
ps.setTimestamp(1, start);
ps.setTimestamp(2, end)
Note here that I am using a parametrized PreparedStatement, which avoids (or at least greatly lessens) the possibility of SQL injection.
A: Try this
SELECT * FROM project.order po
WHERE po.PO_Date IS NOT NULL
AND TO_DATE(PO_Date, 'DD/MM/RRRR') >=
TO_DATE('17/02/2015', 'DD/MM/RRRR')
AND TO_DATE(PO_Date, 'DD/MM/RRRR') <=
TO_DATE('20/06/2015', 'DD/MM/RRRR');
| {
"language": "en",
"url": "https://stackoverflow.com/questions/35599459",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
} |
Q: how to select many different data"s" from two table? I have two tables tableA, tableB
Two of them have col "ip",like this...
tableA-ip
1.1.1.1
1.1.1.2
1.1.1.3
1.1.1.4
1.1.1.5
1.1.1.6
1.1.1.7
1.1.1.8
tableB-ip
1.1.1.3
1.1.1.4
1.1.1.5
And what I want is
1.1.1.1
1.1.1.2
1.1.1.6
1.1.1.7
1.1.1.8
How to select it?
A: It looks like you want the set difference (that is, IPs in A that are not also in B), soooooo:
SELECT a.ip FROM tableA a WHERE tableA.ip NOT IN (SELECT b.ip FROM tableB)
A: Use NOT IN:
SELECT ip FROM TableA WHERE TableA.ip NOT IN (SELECT ip FROM TableB)
A: You can combine two result sets with UNION.
select ip from tableA
union
select ip from tableB;
http://dev.mysql.com/doc/refman/5.0/en/union.html
The default behavior is to remove duplicate rows.
If you want duplicate rows use UNION ALL.
A: select a.id from a minus select b.id from b
or
select a.id from a where a.id not in (select b.id from b)
A: SELECT col1, col2, .. , Ip from TableA
UNION
SELECT col, col2, ...., Ip from TableB
To get the differences you can use the MINUS Operator instead of UNION
| {
"language": "en",
"url": "https://stackoverflow.com/questions/8676646",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How would I go about connecting to a database securely via Java? I wish to connect to a Mysql Database with Java without revealing the password to anyone that may decompile my code? I can efficiently connect to a database, but my ways will openly show my password in the code :( and wish only a response on how to hide the password. Thanks is advance, Josh Aurora
A: OAuth allows client connection without storing credentials on client ( used widely on mobile devices or to identify tweitte applications ). It also allows to remove access permissions from rogue clients. But I doubt that mysql suzpports this directly,. so you will have to wrap your database with some kind of service layer. One of usable imaplementations of OAuth:
http://code.google.com/p/oauth-signpost/
(IIRC, used by Qipe )
A: Assuming that the database which will be accessed will be on your machines, two things that come to mind:
*
*Set up a small secure REST service (as shown here) which will, upon a certain request with certain credentials, pass the password to your database. This however might be an issue if your application is sitting behind some corporate firewall since you might need to add firewall exceptions, which is something that not all administrators are enthusiastic about.
*You could use a mix of Cryptography and Obfuscation to encrypt the password to the database and then obfuscate all your code.
As a note though, either of these methods can, in time be broken. This is basically the rule about all security related software.
If it where up to me, I would go about this problem using the first approach and make sure that the credentials through which the service is accessed are changed often.
However, databases which are used as part of a client solution contain pretty sensitive data which is in the client's interest not to tamper with, so the client will most likely not mess around with it, he/she will be happy as long as the system works.
If on the other hand, the database is not deployed onto one of your machines then you can't really do much about it. You could recommend that the server will be stored on a remote machine with access only over the intranet, but other than that, I do not think you can do much about it.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/12453594",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: python3 KTinker grid load time incredibly long I'm trying to write a fairly basic grid which I've noticed generates fairly quickly but takes minutes to actually display anything. It runs through the loop but the window is plain until everything appears at once a few minutes later
i = 0
for i,element in enumerate(headerArray):
label = tk.Label(text=element).grid(row=0,column=i)
for itter in outputArray:
line=re.split(r'\s{2,}',itter)
if not (nextLineColor is None):
nextLineColor = None
if(len(line) == 1):
continue
elif(len(line) == 6):
for j,col in enumerate(line):
ele = None
if(j==0):
ele = tk.Button(self,text=col)
ele.config(command=lambda val=col: self.node_selected(val))
else:
ele = tk.Label(text=col)
ele.grid(row=i,column=j)
i = i + 1
| {
"language": "en",
"url": "https://stackoverflow.com/questions/51365762",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: cannot find symbol Serializable? Why does this:
package com.example;
import com.example.Foo.Bar.Baz;
import java.io.Serializable; // I did import Serializable...
public class Foo implements Serializable {
public final Bar bar;
public Foo(Bar bar) {
this.bar = bar == null ? new Bar(Baz.ONE) : bar;
}
public static class Bar implements Serializable { // this is line 15, where the compiler error is pointing
public enum Baz {
ONE
}
public final Baz baz;
public Bar(Baz baz) {
this.baz = baz;
}
}
}
Give me this:
[ERROR] <path to file>/Foo.java:[15,44] cannot find symbol
[ERROR] symbol: class Serializable
[ERROR] location: class com.example.Foo
If I replace the Serializable interface to something else like :
public interface MyMarkerInterface {}
then the code compiles. (even Cloneable works!)
What makes this happen?
intelliJ didn't spot anything wrong through static analysis.
A: Don't try and import the internal class. That's causing your compiler error
// import com.example.Foo.Bar.Baz;
import java.io.Serializable;
public class Foo implements Serializable {
public final Bar bar;
public Foo(Bar bar) {
this.bar = bar == null ? new Bar(Bar.Baz.ONE) : bar;
}
public static class Bar implements Serializable {
public enum Baz {
ONE
}
public final Baz baz;
public Bar(Baz baz) {
this.baz = baz;
}
}
}
A: in java7 and java8 compiling depended on order of imports.
your code works in java >= 9. see https://bugs.openjdk.java.net/browse/JDK-8066856 and https://bugs.openjdk.java.net/browse/JDK-7101822
to make it compile in java7 and java8 just reorder the imports
| {
"language": "en",
"url": "https://stackoverflow.com/questions/27664385",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Setting border for checkable QListWidgetItem I have added some check-able QListWidgetItem and I have challenge setting the border color for the checkboxes. setForeground function only sets the color of the checkbox text.
Any suggestion please.
This is my sample code creating the check-able QListWidgetItems:
watch_list = ["Protesters", "Local news staff", "Techfluencers"]
for category in watch_list:
self.checkBox = QtWidgets.QListWidgetItem(category)
self.checkBox.setFlags(self.checkBox.flags() | QtCore.Qt.ItemIsUserCheckable)
self.checkBox.setCheckState(QtCore.Qt.Unchecked)
self.checkBox.setForeground(QtGui.QColor('#FFFFFF'))
self.watchListslistWidget.addItem(self.checkBox)
I have tried
self.watchListslistWidget.setStyleSheet("""
QListWidget::item {
border:1px #FFFFFF
}
""")
But it sets the all background of the QListWidget to white.
A: You can use a delegate:
from PyQt5 import QtCore, QtGui, QtWidgets
class CheckBoxDelegate(QtWidgets.QStyledItemDelegate):
def initStyleOption(self, option, index):
super().initStyleOption(option, index)
option.palette.setBrush(QtGui.QPalette.Button, QtGui.QColor("red"))
class MainWindow(QtWidgets.QMainWindow):
def __init__(self, parent=None):
super().__init__(parent)
self.watchListslistWidget = QtWidgets.QListWidget()
self.setCentralWidget(self.watchListslistWidget)
watch_list = ["Protesters", "Local news staff", "Techfluencers"]
for category in watch_list:
checkBox = QtWidgets.QListWidgetItem(category)
checkBox.setFlags(checkBox.flags() | QtCore.Qt.ItemIsUserCheckable)
checkBox.setCheckState(QtCore.Qt.Unchecked)
self.watchListslistWidget.addItem(checkBox)
delegate = CheckBoxDelegate(self.watchListslistWidget)
self.watchListslistWidget.setItemDelegate(delegate)
def main():
import sys
app = QtWidgets.QApplication(sys.argv)
w = MainWindow()
w.show()
sys.exit(app.exec_())
if __name__ == "__main__":
main()
A: I got it working by using indicator as follows:
self.watchListslistWidget.setStyleSheet("""
QListWidget::indicator{
border: 1px solid white;
}
""")
| {
"language": "en",
"url": "https://stackoverflow.com/questions/62466345",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: display json data that contains html I have the following json
[{
"date": "2011",
"content": "<p>Hello world?</p>"
},
{
"date": "2012",
"content": "<p><strong>Hello again</strong></p>"
}]
my controller has
public function index() {
$data['json'] = json_decode(file_get_contents('location_of_json_file.json'));
return view('index', $data);
}
my view has
@foreach ($json as $a)
{{ $a->content }}
@endforeach
but what i get is
<p>Hello world?</p>
<p><strong>Hello again</strong></p>
how can i make it parse the html code instead of displaying the syntax? i've tried htmlentities and html_entity_decode. i tried to json_encode in different place of the code, i'm lost. please help.
A: The Blade output tags changed between Laravel 4 and Laravel 5. You're looking for:
{!! $a->content !!}
In Laravel 4, {{ $data }} would echo data as is, whereas {{{ $data }}} would echo data after running it through htmlentities.
However, Laravel 5 has changed it so that {{ $data }} will echo data after running it through htmlentities, and the new syntax {!! $data !!} will echo data as is.
Documentation here.
A: In Laravel 5, by default {{ ... }} will escape the output using htmlentities. To output raw HTML that get's interpreted use {!! ... !!}:
@foreach ($json as $a)
{!! $a->content !!}
@endforeach
Here's a comparison between the different echo brackets and how to change them
| {
"language": "en",
"url": "https://stackoverflow.com/questions/28865293",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: WPF: Making child elements' MinWidth/MinHeight constrain the Window I have a WPF Window that contains a UserControl with a MinWidth and MinHeight. How can I prevent the user from resizing the Window down to a point where that UserControl's minimum size is violated?
Here's a simplified version of a Window I'm working on. My real app's UserControl is replaced here by a Border:
<Window xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<DockPanel>
<StackPanel DockPanel.Dock="Bottom" Orientation="Horizontal">
<Button Content="OK"/>
<Button Content="Cancel"/>
</StackPanel>
<Border BorderBrush="Green" BorderThickness="10"
MinWidth="200" MinHeight="150"/>
</DockPanel>
</Window>
If I shrink the window small enough, the Border's right and bottom edges are cut off. I want to prevent the window from getting that small -- I want my window's minimum size to be exactly the point at which the Border is at its minimum size. Some frameworks (like the Delphi VCL) automatically aggregate child controls' minimum sizes up to the window; I expected WPF to do the same, but clearly it does not.
I could always explicitly set the Window's MinWidth and MinHeight, but to calculate those correctly, I would have to factor in the Buttons' ActualHeight, which would mean waiting for at least one layout pass (or calling Measure manually). Messy.
Is there any better way to keep the Window from resizing too small for its content?
A: The simplest way I've found is to tell the Window to size to its content:
<Window ... SizeToContent="WidthAndHeight" ...>
and then, once it's done sizing (which will take the child elements' MinWidth and MinHeight into account), run some code that sets MinWidth and MinHeight to the window's ActualWidth and ActualHeight. It's also a good idea to turn SizeToContent back off at this point, lest the window resize when its content changes.
The next question is, where to put this code? I finally settled on OnSourceInitialized:
protected override void OnSourceInitialized(EventArgs e)
{
base.OnSourceInitialized(e);
MinWidth = ActualWidth;
MinHeight = ActualHeight;
ClearValue(SizeToContentProperty);
}
I also tried the Loaded event, but in my case, that was too soon -- Loaded happens before databindings have been evaluated, and I had databindings that affected my layout (a Label with a binding for its Content -- its size changed after the binding took effect). Moving the code into OnSourceInitialized, which fires after databinding, corrected the problem.
(There were also other events that fired after binding, but before the window was shown -- SizeChanged and LayoutUpdated -- but they both fire multiple times as the window is shown, and again later if the user resizes the window; OnSourceInitialized only fires once, which I consider ideal.)
A: Have you tried using an ElementName style binding from the Window to the UserControl at hand? It seems like it would be feasible to bind the Window's MinWidth/Height to those of the Button. Still not pretty, but it shouldn't require extra passes once the binding is in place and will adapt if you change the values on the Button.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/5228410",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
} |
Q: Form that has a date picker input. And I’m sending my data to the database using nodejs My problem is: when I set the data type of my date picker to just “date” my data makes it to the database(even though it’s not the current date), BUT when I set the data type of my date picker to “datetime-local” it doesn’t make it, instead it’s just giving me an error.
*
*Date picker image
<form action="/formdata" method="POST"class="row g-12 needs-validation" novalidate>
<div class="row">
<div class="col-md-4">
<label for="inputState" class="form-label">End Shift</label>
<div class="form-group"> <input name="datepicker" id="datepicker"
class="form-
control" type="datetime-local" required> </div>
</div>
</div>
*This is how I'm adding the data to the database (SQL Server)
class forms {
constructor(datepicker,site,line,units){
this.d = datepicker;
this.s = site;
this.l = line;
this.u = units;
}
}
app.use(bodyParser.urlencoded({ extended: true}));
app.use(bodyParser.json());
//make directory static
app.use(express.static(__dirname + '/public'));
//we getting the home.html page
app.get("/",(req,res)=>{
res.sendFile(__dirname+"/public/home.html");
});
//creating a route for form data
app.post("/formdata",(req,res)=>{
const userDetails = new
forms(req.body.datepicker,req.body.site,req.body.line,req.body.units);
//Requesting database
var request = new sql.Request();
// let datetime =userDetails.d ;
console.log(userDetails.d);
const date = moment(userDetails.d).format('YYYY-MM-DD HH:mm:ss');
// Insert data into the database
let mssql = (`INSERT INTO DataEntry(Date,TimeStamp,Line,Units,Site)
Values(${date},'25114','${userDetails.l}','${userDetails.u}','${userDetails.s}');`);
request.query(mssql,function (err, data) {
if (err) throw err;
console.log("User data is successfully inserted");
});
res.sendFile(__dirname+"/public/home.html");
});
//Listern to port 3002
app.listen(port,(e)=>{
if(e) throw e;
console.log("html page provided");
});
*This is the error I'm getting
originalError: Error: Incorrect syntax near '11'.
*This is the date format on my database
Databasecolums and data format
*And this is how the date appears in my database when when the date picker datatype is set to "datetime-local".
Date entry to the database
As you can see things look pretty broken, please help me figure out this problem.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/68678937",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: .bash_profile permission denied I'm trying to make one of my first projects published with github but I'm having trouble testing the build locally.
I'm following the steps here:
https://jekyllrb.com/docs/installation/macos/
and I am stuck on the following command line runs:
echo "source $(brew --prefix)/opt/chruby/share/chruby/chruby.sh" >> ~/.bash_profile
echo "source $(brew --prefix)/opt/chruby/share/chruby/auto.sh" >> ~/.bash_profile
echo "chruby ruby-3.1.2" >> ~/.bash_profile # run 'chruby' to see actual version
Each time I run the first one, I get the following error:
-bash: /Users/account/.bash_profile: Permission denied
This is all very new to me and honestly I have no clue what I'm doing when it comes to the console. I am on MacOS Monetory and my shell is bash. Any help would be really appreciated!
A: Something has corrupted or changed ownership to root your .bash_profile script.
Open Terminal.app and do these:
*
*mv -f ~/.bash_profile ~/.bash_profile
*cp ~/.bash_profile.old ~/.bash_profile
These commands show not produce errors.
Now try to re-run your scripts to append to .bash_profile.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/73315913",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: IE10 anchor tag z-index issue In IE 10, I have a relatively positioned wrapper div with some content (an image / text). Inside of that div is an absolutely positioned anchor tag which is positioned to "cover" the entire wrapper div. It has a z-index set. So the entire area inside the wrapper div should be clickable. However, only the areas in the wrapper div that don't have content are clickable. The entire wrapper div is clickable in all other browsers except for IE 10. Here is a fiddle: http://jsfiddle.net/NUyhF/3/. Help?
<div class="wrapper">
<div class="imgWrapper">
<img src="http://www.google.com/images/srpr/logo4w.png" />
</div>
<p>Here is some text</p>
<a href="#"></a>
</div>
.wrapper { position : relative; width: 500px; height: 300px; }
.wrapper a { position: absolute; top: 0px; width: 500px; height: 300px; z-index: 2; }
A: It is now semantically correct to wrap block level elements in an anchor tag (using the html5 doctype). I would suggest amending your markup to this.
HTML
<a href="#">
<div class="imgWrapper">
<img src="http://www.google.com/images/srpr/logo4w.png" />
</div>
<p>Here is some text</p>
</a>
A: I have found this to be an annoying trait of IE for some time, to solve it I had to make a transparent image and use it as the background of the anchor tag:
background:url(transparent1x1.gif) repeat;
http://jsfiddle.net/NUyhF/6/
| {
"language": "en",
"url": "https://stackoverflow.com/questions/15662687",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Multiprocessing pool.imap with large chunksize is skipping processing some records in iterable I am processing a list of string using multiprocessing pool.imap() with passing chunksize. My list length is 1821 and process in imap is 4. I was trying to give almost equal number of chunk size to each process so set chunk size as 455. Also tried with 500. But this makes my imap to skip some of the records.
Skipping was not so random too as it is ordered list. Once I changed the chunk size to 200, imap started sending all the records to my target function.
Can some one explain why the chunksize > 450 is causing issue here, while as per documentation it should be divided 1821/4 = 455 or 456 rec in each process ideally.
Also note , in my function I am using that string and running some steps which takes few seconds for each. While for testing I tried to writing the string only in file inside target function and even then it was skipping some records.
def process_init(self,l):
global process_lock
process_lock = l
def _run_multiprocess(self,num_process,input_list,target_func,chunk):
l = mp.Lock()
with mp.Pool(processes=(num_process),initializer=self.process_init, initargs=(l,)) as p:
start = time.time()
async_result = p.imap(target_func, input_list,chunksize =chunk)
p.close()
p.join()
print("Completed the multiprocess")
end = time.time()
print('total time (s)= ' + str(end-start))
chunksize = 500
self._run_multiprocess(4,iterator_source,self._process_data,chunksize)
def _process_data(self,well_name):
with open("MultiProcessMethod_RecordReceived.csv","a") as openfile:
process_lock.acquire()
openfile.write( "\t" +well_name.upper() + "\n")
openfile.flush()
process_lock.release()
| {
"language": "en",
"url": "https://stackoverflow.com/questions/66817760",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Unable to choose order of buttons in UIAlertController I was under the impression that if the normal action is a destructive action and the other is a cancel action in their UIAlertController that the destructive one should be on the left and the cancel should be on the right.
If the normal action is not destructive, then the normal action should be on the right and the cancel should be on the left.
That said, I have the following:
var confirmLeaveAlert = UIAlertController(title: "Leave", message: "Are you sure you want to leave?", preferredStyle: .Alert)
let leaveAction = UIAlertAction(title: "Leave", style: .Destructive, handler: {
(alert: UIAlertAction!) in
//Handle leave
}
)
let cancelAction = UIAlertAction(title: "Cancel", style: .Cancel, handler: nil)
confirmLeaveAlert.addAction(leaveAction)
confirmLeaveAlert.addAction(cancelAction)
self.presentViewController(confirmLeaveAlert, animated: true, completion: nil)
I was under the impression that if I add the leaveAction first, then the cancelAction that the leaveAction would be the button on the left. This was not the case. I tried adding the buttons in the opposite order as well and it also resulted in the buttons being added in the same order.
Am I wrong? Is there no way to achieve this?
A: My solution to this was to use the .Default style instead of .Cancel for the cancelAction.
A: Since iOS9 there is a preferredAction property on UIAlertController. It places action on right side. From docs:
When you specify a preferred action, the alert controller highlights the text of that action to give it emphasis. (If the alert also contains a cancel button, the preferred action receives the highlighting instead of the cancel button.)
The action object you assign to this property must have already been added to the alert controller’s list of actions. Assigning an object to this property before adding it with the addAction: method is a programmer error.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/32260191",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "10"
} |
Q: ASP.NET custom HttpHandler in IIS 7, 7.5 My web.config is setup as following. My handler lives in an assembly called TestProject.Custom. I am calling this handler via jQuery post, works great in VS 2010 (of course!) but when I push it out to IIS 7.5 or IIS 7, it throws 404 about not being able to find TestHandler.ashx. Not sure what I am missing.
<system.webServer>
<validation validateIntegratedModeConfiguration="false" />
<handlers>
<add name="TestHandler"
verb="*" preCondition="integratedMode"
path="TestProject.Custom.HttpHandlers.TestHandler.ashx"
type="TestProject.Custom.HttpHandlers.TestHandler, TestProject.Custom"/>
</handlers>
Edit: I am calling this handler with jQuery and the handler is behind forms authentication (which I don't think is the problem):
jQuery(function () {
jQuery.ajax({
type: "POST",
url: "TestHandler.ashx",
data: { "test_data": "some test data" }
});
});
A: I think the "path" attribute should be "TestHandler.ashx" instead of its current value. It must match the URL you use in jQuery. Otherwise, 404 is expected.
A: 404 usually means a problem with the registration, basically it just can't find something to handle the request that came in.
Inside of the add node, try adding the following attribute at the end: resourceType="Unspecified"
That tells IIS not to look for a physical file when it sees the request for the ashx. I think that's causing the 404
| {
"language": "en",
"url": "https://stackoverflow.com/questions/9422856",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: org.apache.catalina.LifecycleException: Failed to start component i am getting this error when starting my tomcat server with my application.
I don't really understand it but if i "clean" in eclipse a few times or if i stop start the tomcat server a few times it somehow works, but then it happens over again if i stop.
any ideas?
WARNING: [SetContextPropertiesRule]{Context} Setting property 'source' to 'org.eclipse.jst.j2ee.server:datalinx-backend' did not find a matching property.
May 27, 2014 11:23:36 AM org.apache.catalina.loader.WebappClassLoader validateJarFile
INFO: validateJarFile(D:\Applications\STS\vfabric-tc-server-developer- 2.9.2.RELEASE\base-instance\wtpwebapps\datalinx-backend\WEB-INF\lib\javax.el-api-2.2.4.jar) - jar not loaded. See Servlet Spec 2.3, section 9.7.2. Offending class: javax/el/Expression.class
May 27, 2014 11:23:36 AM org.apache.catalina.loader.WebappClassLoader validateJarFile
INFO: validateJarFile(D:\Applications\STS\vfabric-tc-server-developer-2.9.2.RELEASE\base-instance\wtpwebapps\datalinx-backend\WEB-INF\lib\javax.servlet-api-3.0.1.jar) - jar not loaded. See Servlet Spec 2.3, section 9.7.2. Offending class: javax/servlet/Servlet.class
May 27, 2014 11:23:36 AM org.apache.catalina.loader.WebappClassLoader validateJarFile
INFO: validateJarFile(D:\Applications\STS\vfabric-tc-server-developer-2.9.2.RELEASE\base-instance\wtpwebapps\datalinx-backend\WEB-INF\lib\tomcat-embed-core-7.0.52.jar) - jar not loaded. See Servlet Spec 2.3, section 9.7.2. Offending class: javax/servlet/Servlet.class May 27, 2014 11:23:36 AM org.apache.catalina.loader.WebappClassLoader validateJarFile
INFO: validateJarFile(D:\Applications\STS\vfabric-tc-server-developer-2.9.2.RELEASE\base-instance\wtpwebapps\datalinx-backend\WEB-INF\lib\tomcat-embed-el-7.0.52.jar) - jar not loaded. See Servlet Spec 2.3, section 9.7.2. Offending class: javax/el/Expression.class
May 27, 2014 11:23:39 AM org.apache.catalina.core.ContainerBase addChildInternal
SEVERE: ContainerBase.addChild: start:
org.apache.catalina.LifecycleException: Failed to start component [StandardEngine[Catalina].StandardHost[localhost].StandardContext[/backend]]
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:154)
at org.apache.catalina.core.ContainerBase.addChildInternal(ContainerBase.java:901)
at org.apache.catalina.core.ContainerBase.addChild(ContainerBase.java:877)
at org.apache.catalina.core.StandardHost.addChild(StandardHost.java:633)
at org.apache.catalina.startup.HostConfig.deployDescriptor(HostConfig.java:657)
at org.apache.catalina.startup.HostConfig$DeployDescriptor.run(HostConfig.java:1637)
at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:471)
at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:334)
at java.util.concurrent.FutureTask.run(FutureTask.java:166)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
at java.lang.Thread.run(Thread.java:724)
Caused by: java.lang.IllegalStateException: Unable to complete the scan for annotations for web application [/backend] due to a StackOverflowError. Possible root causes include a too low setting for -Xss and illegal cyclic inheritance dependencies. The class hierarchy being processed was [org.bouncycastle.asn1.ASN1EncodableVector->org.bouncycastle.asn1.DEREncodableVector->org.bouncycastle.asn1.ASN1EncodableVector]
at org.apache.catalina.startup.ContextConfig.checkHandlesTypes(ContextConfig.java:2179)
at org.apache.catalina.startup.ContextConfig.processAnnotationsStream(ContextConfig.java:2126)
at org.apache.catalina.startup.ContextConfig.processAnnotationsJar(ContextConfig.java:2001)
at org.apache.catalina.startup.ContextConfig.processAnnotationsUrl(ContextConfig.java:1967)
at org.apache.catalina.startup.ContextConfig.processAnnotations(ContextConfig.java:1952)
at org.apache.catalina.startup.ContextConfig.webConfig(ContextConfig.java:1326)
at org.apache.catalina.startup.ContextConfig.configureStart(ContextConfig.java:878)
at org.apache.catalina.startup.ContextConfig.lifecycleEvent(ContextConfig.java:369)
at org.apache.catalina.util.LifecycleSupport.fireLifecycleEvent(LifecycleSupport.java:119)
at org.apache.catalina.util.LifecycleBase.fireLifecycleEvent(LifecycleBase.java:90)
at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5269)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
... 11 more
May 27, 2014 11:23:39 AM org.apache.catalina.startup.HostConfig deployDescriptor
SEVERE: Error deploying configuration descriptor D:\Applications\STS\vfabric-tc-server-developer-2.9.2.RELEASE\base-instance\conf\Catalina\localhost\backend.xml
java.lang.IllegalStateException: ContainerBase.addChild: start: org.apache.catalina.LifecycleException: Failed to start component [StandardEngine[Catalina].StandardHost[localhost].StandardContext[/backend]]
at org.apache.catalina.core.ContainerBase.addChildInternal(ContainerBase.java:904)
at org.apache.catalina.core.ContainerBase.addChild(ContainerBase.java:877)
at org.apache.catalina.core.StandardHost.addChild(StandardHost.java:633)
at org.apache.catalina.startup.HostConfig.deployDescriptor(HostConfig.java:657)
at org.apache.catalina.startup.HostConfig$DeployDescriptor.run(HostConfig.java:1637)
at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:471)
at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:334)
at java.util.concurrent.FutureTask.run(FutureTask.java:166)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
at java.lang.Thread.run(Thread.java:724)
May 27, 2014 11:23:39 AM org.apache.catalina.startup.HostConfig deployDirectory
A: First of all, that looks like Pivotal's tc Server rather than Apache Tomcat. tc Server is based on Apache Tomcat but they are not exactlt the same and it always helps to provide the most accurrate information you can.
There is something seriously wrong with your dependencies. Tomcat is detecting the following class heirarchy:
org.bouncycastle.asn1.ASN1EncodableVector
->org.bouncycastle.asn1.DEREncodableVector
->org.bouncycastle.asn1.ASN1EncodableVector
This is a cyclic dependency. In Java it is illegal for A to extend B if B extends A.
Cleaning out your dependencies and ensuring you are using only using one version of the bouncy castle JAR should fix this.
If the problem persists and can be reproduced on a clean install of the latest stable Tomcat 7 release then please do open a bug against Apache Tomcat and provide the web application that demonstrates the issue.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/23884755",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Connectionless UDP vs connection-oriented TCP over an open connection If a TCP connection is established between a client and server, is sending data faster on this connection-oriented route compared to a connectionless given there is less header info in the packets? So a TCP connection is opened and bytes sent down the open connection as and when required. Or would UDP still be a better choice via a connectionless route where each packet contains the destination address?
Is sending packets via an established TCP connection (after all hand shaking has been done) a method to be faster than UDP?
A: I suggest you read a little bit more about this topic.
just as a quick answer. TCP makes sure that all the packages are delivered. So if one is dropped for whatever reason. The sender will continue sending it until the receiver gets it. However, UDP sends a packet and just forgets it, so you might loose some of the packets. As a result of this, UDP sends less number of packets over network.
This is why they use UDP for videos because first loosing small amount of data is not a big deal plus even if the sender sends it again it is too late for receiver to use it, so UDP is better. In contrast, you don't want your online banking be over UDP!
Edit: Remember, the speed of sending packets for both UDP and TCP is almost same, and depends on the network! However, after handshake is done in TCP, still receiver needs to send the acks, and sender has to wait for ack before sending new batch of data, so still would be a little slower.
A: In general, TCP is marginally slower, despite less header info, because the packets must arrive in order, and, in fact, must arrive. In a UDP situation, there is no checking of either.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/8930717",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to have few options as checked in the entity/choice type in symfony I want to render the choice type from entity and its working fine. I want to few options to be checked by default when the form is rendered. For e.g. I have 10 options out of it only 3 options to be checked by default and when it persisted and in edit page whatever is saved to database should be rendered not the default 3 items. In the below title is fieldname
->add('attendee', EntityType::class, [
'label' => 'Select any information you would like to
require per Attendee:',
'multiple' => true,
'expanded' => true,
'required' => true,
'class' => 'AppBundle\\Entity\\Registrant',
'choice_label' => 'title',
])
A: if you have saved some values, then symfony will select the values in the form itself. You don't need to preselect them. You need in your form type the method "configureOptions" like this:
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults(array(
'data_class' => 'AppBundle\Entity\MyClass'
));
}
If it is not working anyway, post more code.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/40780493",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: phonegap Google Analytics plugin for android returns class not found when i call one of the methods Good evening,
I am currently developing an application for android using phonegap and sencha touch 1.1.
I am having trouble with the GoogleAnalyticsTracker plugin for Android. I followed all the instructions on github on how to import the necessery code for the plugin to work but I am having trouble with initialization.
In my plugins.xml I have added the following line:
< plugin name="Analytics" value="com.phonegap.plugins.analytics.GoogleAnalyticsTracker" />
As indicated in the readme.md file in github. I also added the GoogleAnalyticsTracker.java file inside com/phonegap/plugins/analytics and referenced the js file in my html... every thing seems to work fine except the part where I call the start method with my account id... The method returns the failure callback with error 'Class not found'. any ideas why phonegap cannot find the class specified in the xml?
if you need more info on this please do not hesitate to ask.
Thank you in advance!
PS. i am using phonegap 1.4.1
-L_Sonic
A: I took a look at the src and I see that the PhoneGap.exec calls in analytics.js does not match the plugin name. You have two ways to fix this.
*
*In plugins.xml make the plugin line:
<plugin name="GoogleAnalyticsTracker" value="com.phonegap.plugins.analytics.GoogleAnalyticsTracker"/>
*Or in analytics.js replace all instances of 'GoogleAnalyticsTracker' with 'Analytics'
This is a bug in the way the code is setup in github. You should message the author to get them to fix it.
A: Rather than using the PhoneGap plugin, I would recommend using the Google Analytics SDK for tracking usage of application developed using PhoneGap or any web based mobile app.
Ensure that you respect your users privacy and dont send any other data to Google Analytics.
Besides you should also adhere to Google Analytics privacy policy.
Heres how to do it.
http://www.the4thdimension.net/2011/11/using-google-analytics-with-html5-or.html
| {
"language": "en",
"url": "https://stackoverflow.com/questions/9507183",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: XLSX Writer Python- 3 Color Scale with Number as Midpoint I'm trying to conditional formatting in XLSX writer with a 3 color scale with a 0 midpoint value in the middle. I want all negative values to scale from red (lowest number) to yellow (when the value is zero) and all positive numbers to scale from yellow (at zero) to green (at the highest).
The scaling gets all messed up when I try the following..
Something that would look like the following in Excel:
I can figure out how to do a 3 color scale in XLSX writer, but there doesnt seem to be an option (I can see) for midpoint being a number:
worksheet.conditional_format('G2:G83', {'type': '3_color_scale',
'min_color': "red",
'mid_color': "yellow",
'max_color': "green"})
I then tried to break it down with a criteria with one format applied to values above zero and one below zero
worksheet.conditional_format('G2:G83', {'type': '2_color_scale',
'criteria': '<',
'value': 0,
'min_color': "red",
'max_color': "yellow"})
worksheet.conditional_format('G2:G83', {'type': '2_color_scale',
'criteria': '>',
'value': 0,
'min_color': "yellow",
'max_color': "green"})
But that doesn't seem to work either - if anybody has any ideas.. please let me know.. would really appreciate it.
Complete sample code:
import xlsxwriter
workbook = xlsxwriter.Workbook('conditional_format.xlsx')
worksheet1 = workbook.add_worksheet()
# Add a format. Light red fill with dark red text.
format1 = workbook.add_format({'bg_color': '#FFC7CE',
'font_color': '#9C0006'})
# Add a format. Green fill with dark green text.
format2 = workbook.add_format({'bg_color': '#C6EFCE',
'font_color': '#006100'})
# Some sample data to run the conditional formatting against.
data = [
[34, 72, -38, 30, 75, 48, 75, 66, 84, 86],
[-6, -24, 1, -84, 54, 62, 60, 3, 26, 59],
[-28, 0, 0, 13, -85, 93, 93, 22, 5, 14],
[27, -71, -40, 17, 18, 79, 90, 93, 29, 47],
[0, 25, -33, -23, 0, 1, 59, 79, 47, 36],
[-24, 100, 20, 88, 29, 33, 38, 54, 54, 88],
[6, -57, -88, 0, 10, 26, 37, 7, 41, 48],
[-52, 78, 1, -96, 26, -45, 47, 33, 96, 36],
[60, -54, -81, 66, 81, 90, 80, 93, 12, 55],
[-70, 5, 46, 14, 71, -19, 66, 36, 41, 21],
]
for row, row_data in enumerate(data):
worksheet1.write_row(row + 2, 1, row_data)
worksheet1.conditional_format('B2:B12', {'type': '2_color_scale',
'criteria': '<',
'value': 0,
'min_color': "red",
'max_color': "yellow"})
worksheet1.conditional_format('C2:C12', {'type': '2_color_scale',
'criteria': '>',
'value': 0,
'min_color': "yellow",
'max_color': "green"})
worksheet1.conditional_format('C2:C12', {'type': '2_color_scale',
'criteria': '<',
'value': 0,
'min_color': "red",
'max_color': "yellow"})
worksheet1.conditional_format('D2:D12', {'type': '3_color_scale',
'min_color': "red",
'mid_color': "yellow",
'max_color': "green"})
workbook.close()
writer.save()
This is what I get:
As you can see, column B (the first column) has no green
Column C has no red
Column D has 0 as green
Any ideas how to do the 3 step scaling with zero in the middle?
Thanks
A:
I can figure out how to do a 3 color scale in XLSX writer, but there doesnt seem to be an option (I can see) for midpoint being a number:
You can use the min_type, mid_type and max_type parameters to set the following types:
min (for min_type only)
num
percent
percentile
formula
max (for max_type only)
See Conditional Format Options
So in your case it should be something like.
worksheet1.conditional_format('D2:D12', {'type': '3_color_scale',
'min_color': "red",
'mid_color': "yellow",
'max_color': "green",
'mid_type': "num"})
However, I'm not sure if that will fix your overall problem. Maybe add that to your example and if it doesn't work then open a second question.
One thing that you will have to figure out is how to do what you want in Excel first. After that it is generally easier to figure out what is required in XlsxWriter.
A: I know this is an old question but I just ran into this problem and figured out how to solve it.
Below is a copy of a utility function I wrote for my work. The main thing is that the min, mid and max types ALL need to be 'num' and they need to specify values for these points.
If you only set the mid type to 'num' and value to 0 then the 3 color scale will still use min and max for the end points. This means that if the contents of the column are all on one side of the pivot point the coloring will in effect disregard the pivot.
from xlsxwriter.utility import xl_col_to_name as index_to_col
MIN_MIN_FORMAT_VALUE = -500
MAX_MAX_FORMAT_VALUE = 500
def conditional_color_column(
worksheet, df, column_name, min_format_value=None, pivot_value=0, max_format_value=None):
"""
Do a 3 color conditional format on the column.
The default behavior for the min and max values is to take the min and max values of each column, unless said value
is greater than or less than the pivot value respectively at which point the values MIN_MIN_FORMAT_VALUE and
MAX_MAX_FORMAT_VALUE are used. Also, if the min and max vales are less than or greater than respectively of
MIN_MIN_FORMAT_VALUE and MAX_MAX_FORMAT_VALUE then the latter will be used
:param worksheet: The worksheet on which to do the conditional formatting
:param df: The DataFrame that was used to create the worksheet
:param column_name: The column to format
:param min_format_value: The value below which all cells will have the same red color
:param pivot_value: The pivot point, values less than this number will gradient to red, values greater will gradient to green
:param max_format_value: The value above which all cells will have the same green color
:return: Nothing
"""
column = df[column_name]
min_value = min(column)
max_value = max(column)
last_column = len(df.index)+1
column_index = df.columns.get_loc(column_name)
excel_column = index_to_col(column_index)
column_to_format = f'{excel_column}2:{excel_column}{last_column}'
if min_format_value is None:
min_format_value = max(min_value, MIN_MIN_FORMAT_VALUE)\
if min_value < pivot_value else MIN_MIN_FORMAT_VALUE
if max_format_value is None:
max_format_value = min(max_value, MAX_MAX_FORMAT_VALUE)\
if max_value > pivot_value else MAX_MAX_FORMAT_VALUE
color_format = {
'type': '3_color_scale',
'min_type': 'num',
'min_value': min_format_value,
'mid_type': 'num',
'mid_value': pivot_value,
'max_type': 'num',
'max_value': max_format_value
}
worksheet.conditional_format(column_to_format, color_format)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/43381230",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "7"
} |
Q: multi-select with search ability in angularjs I started angularjs two weeks ago. I should make a multi select input with search ability.
What I made has 2 problems that I can't fix.
first when I search for "a" it won't filter correctly to only show "a" but the other work fine
second it has a bug when I select "a" to "d" and then deselect from "a" to "d" the last 2 won't delete and the second time that I do this it get's worse.
*
*please try to edit my own code if possible because I'm not good at reading other people's code
appreciate any help
var app = angular.module("myApp", []);
app.controller("myCtrl", function ($scope, $http) {
$scope.selectEnable = false;
$scope.selectedItems = [];
$scope.openSelect = function () {
$scope.selectEnable = !$scope.selectEnable;
};
$scope.itemChecked = function (data) {
data.flag = !data.flag;
var selected = $scope.datas.indexOf(data);
var x = $scope.selectedItems.indexOf(data);
if ((data.flag == true) && (x == -1)) {
$scope.selectedItems.push(data.item);
} else {
$scope.selectedItems.splice(selected, 1);
}
};
$scope.datas = [
{
"item": "a",
/*"category": "x",*/
"flag": false
},
{
"item": "b",
/*"category": "y",*/
"flag": false
},
{
"item": "c",
/*"category": "x",*/
"flag": false
},
{
"item": "d",
/*"category": "y",*/
"flag": false
}
];
});
ul li {
list-style: none;
text-align: center;
}
#category {
text-align: center;
background: #ddd;
}
#listContainer {
width: 20%;
}
span {
cursor: pointer;
}
<!DOCTYPE html>
<html lang="en" ng-app="myApp">
<head>
<meta charset="UTF-8">
<title>Document</title>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.0/angular.js"></script>
<link rel="stylesheet" href="stylesheet/style.css">
</head>
<body ng-controller="myCtrl">
<input type="text" ng-click="openSelect()">
<div id="selectContainer" ng-show="selectEnable">
<div>{{selectedItems.toString()}}</div>
<input type="text" id="searchField" ng-model="searchField">
<div id="listContainer">
<ul>
<li ng-repeat="data in datas | filter: searchField">
<input type="checkbox" ng-change="itemChecked(data)" name="select" ng-model="selectedItems">
{{data.item}}
</li>
</ul>
</div>
</div>
<script src="script.js"></script>
</body>
</html>
A: Follow these steps:
1- Change your itemChecked function to this
$scope.itemChecked = function(data) {
var selected = $scope.selectedItems.findIndex(function(itm) {
return itm == data.item
});
if (selected == -1) {
$scope.selectedItems.push(data.item);
} else {
$scope.selectedItems.splice(selected, 1);
}
};
2- Add an array for showing data after any filtering. Also add a function which filter your data according to input text:
$scope.filter = function() {
if (!$scope.searchField) {
$scope.data2Show = angular.copy($scope.data);
} else {
$scope.data2Show = [];
$scope.data.map(function(itm) {
if (itm.item.indexOf($scope.searchField) != -1) {
$scope.data2Show.push(itm);
}
});
}
};
$scope.data2Show = [];
Use this array to show items in list:
<li ng-repeat="data in data2Show">
3- Write a function to check if an item is selected or not and use:
$scope.isChecked = function (data) {
var selected = $scope.selectedItems.findIndex(function(itm) {
return itm == data.item;
});
if (selected == -1) {
return false;
} else {
return true;
}
}
And usage in html :
<input type="checkbox" ng-change="itemChecked(data)" name="select" ng-model="selectedItems" ng-checked="isChecked(data)">
4- Change checkbox ngModels from selectedItems to data.flag
ng-model="data.flag"
Final code:
var app = angular.module("myApp", []);
app.controller("myCtrl", function($scope, $http) {
$scope.selectEnable = false;
$scope.selectedItems = [];
$scope.openSelect = function() {
$scope.selectEnable = !$scope.selectEnable;
};
$scope.itemChecked = function(data) {
var selected = $scope.selectedItems.findIndex(function(itm) {
return itm == data.item;
});
if (selected == -1) {
$scope.selectedItems.push(data.item);
} else {
$scope.selectedItems.splice(selected, 1);
}
};
$scope.filter = function() {
if (!$scope.searchField) {
$scope.data2Show = angular.copy($scope.data);
} else {
$scope.data2Show = [];
$scope.data.map(function(itm) {
if (itm.item.indexOf($scope.searchField) != -1) {
$scope.data2Show.push(itm);
}
});
}
};
$scope.isChecked = function(data) {
var selected = $scope.selectedItems.findIndex(function(itm) {
return itm == data.item;
});
if (selected == -1) {
return false;
} else {
return true;
}
}
$scope.data2Show = [];
$scope.data = [{
item: "a",
/*"category": "x",*/
flag: false
},
{
item: "b",
/*"category": "y",*/
flag: false
},
{
item: "c",
/*"category": "x",*/
flag: false
},
{
item: "d",
/*"category": "y",*/
flag: false
}
];
$scope.filter();
});
ul li {
list-style: none;
text-align: center;
}
#category {
text-align: center;
background: #ddd;
}
#listContainer {
width: 20%;
}
span {
cursor: pointer;
}
<html lang="en" ng-app="myApp">
<head>
<meta charset="UTF-8">
<title>Document</title>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.0/angular.js"></script>
<link rel="stylesheet" href="stylesheet/style.css">
</head>
<body ng-controller="myCtrl">
<input type="text" ng-click="openSelect()">
<div id="selectContainer" ng-show="selectEnable">
<div>{{selectedItems.toString()}}</div>
<input type="text" id="searchField" ng-model="searchField" ng-change="filter()">
<div id="listContainer">
<ul>
<li ng-repeat="data in data2Show">
<input type="checkbox" ng-change="itemChecked(data)" name="select" ng-model="data.flag" ng-checked="isChecked(data)"> {{data.item}}
</li>
</ul>
</div>
</div>
</body>
</html>
There are some prepared directives for multi-selecting. for example this one Angular-strap selects
| {
"language": "en",
"url": "https://stackoverflow.com/questions/50552034",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-2"
} |
Q: AngularJS : Seqential Promise chain Function one passes value to two and then two passes value to three. Any of these functions could take any amount of time to return data. How can I make them wait for value instead of rushing ahead and printing undefined.
var deferred = $q.defer();
var one = function (msg) {
$timeout(function () {
console.log(msg);
return "pass this to two";
}, 2000);
};
var two = function (msg) {
console.log(msg);
return "pass this to three";
};
var three = function (msg) {
console.log(msg);
};
deferred.promise
.then(one)
.then(two)
.then(three);
deferred.resolve("pass this to one");
A: You need to return a promise from every function that does something asynchronous.
In your case, your one function returns undefined, while it would need to return the promise that you created for the "pass this to two" value after the timeout:
function one (msg) {
return $timeout(function () {
//^^^^^^
console.log(msg);
return "pass this to two";
}, 2000);
}
Btw, instead of using var deferred = $q.defer();, the chain is better written as:
one("pass this to one")
.then(two)
.then(three);
| {
"language": "en",
"url": "https://stackoverflow.com/questions/25894105",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Angular dynamic form, sub-components not updating top level form As the title suggests, I've created a dynamic form using a mix of tutorials I've read.
I have a parent component which creates a empty form group which I then (try) to populate with sub-groups via child components. These components are passed a reference to the parent form, and the child component then creates its own formgroup and attempts to bind this to the parent.
The form model should then look like the following:
FormGroup
-- FormGroup1
---- FormControl1
---- FormControl2
-- FormGroup2
---- FormControl3
---- FormControl4
However, even thought the lower level form controls all render, the parent form doesn't seem to know they exist. My issue seems like it might be related to Angular 2: How to link form elements across a dynamically created components? but I was unable to figure out what he actually did to fix his issue.
Any thoughts?
See https://stackblitz.com/edit/angular-imi6j6?file=app%2Fapp.component.html for what I'm doing.
A: Wow... I just figured it out.
I was trying to add my subgroups to the parent via just assigning properties, but I should have been using FormGroup.addControl(new <FormGroup>).
Works perfectly now.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/49724263",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: type 'ObjectId' is not a subtype of type 'String' of 'value' I am trying to insert a document into my Mongo Database using the package mongo_dart
var db = await Db.create(MONGO_CONN_STRING);
await db.open();
var coll = db.collection('reports');
await coll.insertOne({
"username": "Tom",
"action": "test",
"dateTime": "today",
});
Runtime error on line 4
Unhandled Exception: type 'ObjectId' is not a subtype of type 'String' of 'value'
Is it an issue with the package or is something wrong with my code?
A: try this one
var db = await Db.create(MONGO_CONN_STRING);
await db.open();
var coll = db.collection('reports');
await coll.insertOne({
"username": "Tom",
"action": "test",
"dateTime": "today",
}).toList();
A: Are you using the latest version of the package?
I think your problem is related to this issue in the GitHub Repo of the package but it is closed at Jul 25, 2015.
A: The error is arising because you declared variables db and (collection name) outside the static connect() async function; declare them inside the function.
var db = await Db.create(MONGO_CONN_STRING);
await db.open();
var coll = db.collection('reports');
await coll.insertOne({
"username": "Tom",
"action": "test",
"dateTime": "today",
});
static connect() async {
var db = await Db.create(MONGO_CONN_STRING);
await db.open();
var coll = db.collection('reports');
await coll.insertOne({
"username": "Tom",
"action": "test",
"dateTime": "today",
});
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/72484782",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How to change permission of a kvm-qemu serial console output log I have a virtual machine with this config to redirect serial console log to another file:
<devices>
...
<console type="pty">
<target type="sclp"/>
<log file="/home/nptusk/serial-console.log" append="on"/>
</console>
</devices>
For automation reasons I want the log to have the permission other than root:root. What can I do to achieve this without using chown afterwards, in other words the log file when generated already has my desired user and group.
A: Kvm deamon is running on root.Otherwise it changes its uid,there is no way to change owner.But you can change its permssion to 665 or 664 so that you can access it,or change its ACL for more security
| {
"language": "en",
"url": "https://stackoverflow.com/questions/70561360",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How load Partial View with JavaScript In my view I have JavaScript to load a partial view.
<p>
<div id="AREA_PARTIAL_VIEW">
</div>
</p>
<script type="text/javascript">
$(document).ready(function ()
{
window.location.href = '@Url.Content("Insert", "Customers","Insert_Partial_View")';
});
</script>
@using (Html.BeginForm(@MyChoise, "Corr_Exit"))
{
@Html.AntiForgeryToken()
<div class="panel-group">
<div class="panel panel-primary">
</html> etc...........
I'd load this partial between <div> tag
<div id="AREA_PARTIAL_VIEW">
</div>
But my code doesn't work. Why?
Someone can help me please?
A: I have used load ajax for this
$('#AREA_PARTIAL_VIEW').load('@Url.Action("Insert_Partial_View","Customers")');
| {
"language": "en",
"url": "https://stackoverflow.com/questions/49054643",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Ansible ec2_vpc_route_table playbook error was: 'dict object' has no attribute subnet I have a previously working piece of Ansible that I've inherited for a previous contractor, and I'm getting an error message that doesn't lead me in the right direction. I have tried searching for a few days now, with no joy, and my colleagues can't figure it out either.
The Ansible in question is :-
- name: Routes | Set up NAT-protected route table
ec2_vpc_route_table:
vpc_id: "{{ ec2_vpc_net_reg.vpc.id }}"
region: "{{ vpc_region }}"
tags:
Name: "Internal {{ item.subnet_id }}"
subnets:
- "{{ az_to_private_sub[public_subnets_to_az[item.subnet_id]] }}"
- "{{ az_to_private_data_sub[public_subnets_to_az[item.subnet_id]] }}"
routes:
- dest: 0.0.0.0/0
gateway_id: "{{ item.nat_gateway_id }}"
loop: "{{ existing_nat_gateways.result|flatten(levels=1) }}"
#with_items: "{{ existing_nat_gateways.result }}"
register: nat_route_table
retry: 2
delay: 10
And the error message is :-
fatal: [localhost]: FAILED! => {"msg": "The task includes an option with an undefined variable. The error was: 'dict object' has no attribute u'subnet-0facefaceface9'\n\nThe error appears to have been in '/cup/core-kubernetes-linux/ansible/roles/aws_vpc/tasks/routes.yml': line 62, column 3, but may\nbe elsewhere in the file depending on the exact syntax problem.\n\nThe offending line appears to be:\n\n\n- name: Routes | Set up NAT-protected route table\n ^ here\n"}
I have tried adding extra debug, for az_to_private_sub and public_subnet_to_az, and these look OK. I've tried reading the docs
Can anyone suggest where I should look next?
Thanks!
A: After speaking to a different colleague, they pointed out that the version which works uses Ansible 2.5.5 and I was trying with 2.5.1 also the boto python libraries need to be using the correct version.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/54305600",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Interesting behaviour with infix notation One sometimes try to get away from your girlfriend by hiding behind your computer screen. However, I find that Scala is sometimes exactly like my girl...
This prints the intersection between two lists:
val boys = List(Person("John"), Person("Kim"), Person("Joe"), Person("Piet"), Person("Alex"))
val girls = List(Person("Jana"), Person("Alex"), Person("Sally"), Person("Kim"))
println("Unisex names: " + boys.intersect(girls))
This prints absolutely nothing:
val boys = List(Person("John"), Person("Kim"), Person("Joe"), Person("Piet"), Person("Alex"))
val girls = List(Person("Jana"), Person("Alex"), Person("Sally"), Person("Kim"))
println("Unisex names: " + boys intersect girls)
There are no compiler warnings and the statement prints absolutely nothing to the console. Could someone please explain gently (I have a hangover), why this is so.
A: It gets desugared to this:
println("Unisex names: ".+(boys).intersect(girls))
then according to the -Xprint:typer compiler option it gets rewritten like this:
println(augmentString("Unisex names: ".+(boys.toString)).intersect[Any](girls))
where augmentString is an implicit conversion from type String to StringOps, which provides the intersect method.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/23925713",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: iPhone SDK:NSScanner crashing randomly I have an application that scans text from a website in order to get the information and put it into my application. So in this case I'm retrieveing the number of notifications that the user has on facebook. Everything works fine except that the application crashes randomly. This is the code I have for searching for the number inside the text:
NSScanner *theScanner = [NSScanner scannerWithString:facebookTextF];
NSScanner *theScanner2 = [NSScanner scannerWithString:facebookTextFa];
[theScanner scanUpToString:@"Notifications" intoString:&facebookTextFa] ;
[theScanner scanUpToString:@"\n" intoString:&facebookTextF] ;
NSString *NotificationsValue;
if ([facebookTextF isEqualToString:@"Notifications"]) {
NotificationsValue = @"0";
NSLog(@"%@", NotificationsValue);
} else {
[theScanner2 scanUpToString:@"Notifications" intoString:nil] ;
[theScanner2 setScanLocation:([theScanner2 scanLocation] + 13)];
[theScanner2 scanUpToString:@"\n" intoString:&facebookTextFa] ;
NSLog(@"%@", facebookTextFa);
}
This code works well but just randomly crashes. Here is the crash log I get:
iphone[654:907] *** Terminating app due to uncaught exception 'NSRangeException', reason: '*** -[NSConcreteScanner setScanLocation:]: Range or index out of bounds'
* First throw call stack:
(0x3361b6c3 0x398b397f 0x3361b5e5 0x34d2632f 0x25147 0x34dbf78b 0x335f09ff 0x335f06b1 0x335ef321 0x3356239d 0x33562229 0x39fad31b 0x3402b8f9 0x22267 0x22208)
libc++abi.dylib: terminate called throwing an exception
This crash occurs randomly no matter what. For example if I leave it running for a while, after 7 minutes is just randomly crashes. Not sure what is wrong.
Thank you for looking. IF you need any more information please let me know.
A: You are getting that error message because (apparently) the string sometimes doesn't have the word "Notifications", so the theScanner2 sets its scan location to the end of the string. Then, when you try to set the scan location 13 characters ahead, it's past the end of the string, and you get an out of range error.
A: Trying to setScanLocation in NSScanner which is out of bound means the end of the string and beyond which doesnot exists by setting scan location
| {
"language": "en",
"url": "https://stackoverflow.com/questions/12224027",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Parser for Pipfiles (get a list of all packages used in a Pipfile) Is there any parser out there for reading in a Pipfile and returning a list of all packages used in the Pipfile?
If not, how would one go about this? I was thinking a regular expression could do the job, but I am not sufficiently acquainted with the structure of Pipfiles to confirm that is the case.
A: first install pipfile pip install pipfile.
then just use the parser it provides
from pipfile import Pipfile
parsed = Pipfile.load(filename=pipfile_path)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/53015705",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: Bash Regex to print out the matched string only? Im trying to read a file line by line and trying to match few strings,and im not able to echo the matched line using "$?" im not sure which "$" function to use. can anyone help? i dont want using grep, thanks in advance.
#!/usr/bin/bash
while read EachLine
do
if [[ "$EachLine =~ ^Pass: [0-9]\{1,\}" ]]
then
echo "$?"
fi
done < zoix.progress-N0
exit
A: If you just want to put out the lines that match your pattern in a file, have you tried the following:
grep -E "^Pass: [0-9]+" zoix.progress-N0
| {
"language": "en",
"url": "https://stackoverflow.com/questions/54036023",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: hibernate validator, json schema generation and using common constraints We use Spring MVC, Jackson for json, Hibernate ORM. We need to add front end validations. I came across hibernate validator.
We have a set of Domain classes [DO classes] annotated with JPA.
We have another set of POJO classes [DTO classes] annotated for Json binding.
We want to implement infrastructure that does the following:
*
*DTO classes refer to the DO class constraints [where applicable] so that the truth is one place.
*Generate json schema , again by reusing the JPA annotations.
*Validate input to the rest calls.
For example, instead of the following:
PersonDTO{
@NotNull
@Size(min=2, max=60)
private String firstName;
}
How about:
PersonDTO{
@MapsTo(com.xyz.domain.PersonDO.firstName.Size) // referring to the JPA annotation
private String firstName;
}
And then, a custom validator figures out the constraints to uphold by looking at the JPA annotation.
Is the strategy I outlined a typical approach? Any feedback or opinions is appreciated. Can you point me to relevant any articles?
Thank you.
A: There is no out-of-the-box functionality for copying constraints from one model to another in Hibernate Validator, but you could implement it yourself using existing APIs.
More specifically, there is an API for retrieving constraint metadata (standardized by Bean Validation) and an API for dynamically putting constraints to your types at runtime (provided by Hibernate Validator). You could use the former to read the constraints of your domain model and drive the creation of equivalent constraints on your DTO model using the latter. For that you'd of course need a strategy for matching corresponding types and properties of your source and target model.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/21120760",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: C++ A multiple inheritance pproblem with pure virtual functions I have produced a minimal example to replicate the problem I am seeing with a more complex class hierarchy structure:
#include <string>
#include <iostream>
class A
{
protected:
virtual
~A() = 0;
};
inline
A::~A() {}
class B : public A
{
public:
virtual
~B()
{
}
std::string B_str;
};
class BB : public A
{
public:
virtual
~BB()
{
}
std::string BB_str;
};
class C : public A
{
protected:
virtual
~C()
{
}
virtual
void Print() const = 0;
};
class D : public B, public BB, public C
{
public:
virtual
~D()
{
}
};
class E : public C
{
public:
void Print() const
{
std::cout << "E" << std::endl;
}
};
class F : public E, public D
{
public:
void Print_Different() const
{
std::cout << "Different to E" << std::endl;
}
};
int main()
{
F f_inst;
return 0;
}
Compiling with g++ --std=c++11 main.cpp produces the error:
error: cannot declare variable ‘f_inst’ to be of abstract type ‘F’
F f_inst;
note: because the following virtual functions are pure within ‘F’:
class F : public E, public D
^
note: virtual void C::Print() const
void Print() const = 0;
^
So the compiler thinks that Print() is pure virtual.
But, I have specified what Print() should be in class E.
So, I've misunderstood some of the rules of inheritance.
What is my misunderstanding, and how can I correct this problem?
Note: It will compile if I remove the inheritance : public D from class F.
A: Currently your F is derived from C in two different ways. This means that an F object has two separate C bases, and so there are two instances of C::Print().
You only override the one coming via E currently.
To solve this you must take one of the following options:
*
*Also override the one coming via D, either by implementing D::Print() or F::Print()
*Make Print non-pure
*Use virtual inheritance so that there is only a single C base.
For the latter option, the syntax adjustments would be:
class E : virtual public C
and
class D : public B, public BB, virtual public C
This means that D and E will both have the same C instance as their parent, and so the override E::Print() overrides the function for all classes 'downstream' of that C.
For more information , look up "diamond inheritance problem". See also Multiple inheritance FAQ
| {
"language": "en",
"url": "https://stackoverflow.com/questions/35975050",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Recording Xero check payments via payments endpoint - will they automatically match bank statement? I'm trying to work around the Xero API's lack of support for payment via checks.
If I use the payments endpoint to create and apply new payments to existing invoices, and as part of the PUT add the check number to the reference field, does anyone know if that will be automatically matched when the check is cashed and shows up in our bank statement feed? I can't find Xero's internal reconciliation rules detailed anywhere.
Our issue is that we write about 2k checks per month and many have the same amounts, so we rely on the check number to match and reconcile. Currently Xero automatically matches 95%+ of our checks to bank statement lines we get via our bank feed. My concern is that without a check number linked to the API-created payment, Xero won't match checks to the correct bank statement items, and then we've got 2,000 payments that have to each be reconciled by manual searches for the reference number.
I've imported a test CSV bank rec file and that matched 3 of 3 test payments, but need to explore this more using identical amounts. In the demo company I could create 1,000 bill payments, apply 1,000 payments to them, and import 1,000 statement lines and see how the reconciliation screen looks, but wanted to see if someone already knew the answer!
(I believe we'll also lose the ability to quickly search payments via the check register but we may have to accept that. We send our check list to an outside printing/mailing firm so don't actually need to print the checks in Xero.)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/56961311",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: convert Json object to java object: The logic I have a json weather API that forecasts five days every three hours. I put part of the json with two forcasts since it is too long and repetitive:
{
"cod": "200",
"message": 0.4194,
"city": {
"id": 1851632,
"name": "Shuzenji",
"coord": {
"lon": 138.933334,
"lat": 34.966671
},
"country": "JP",
"population": 0
},
"cnt": 40,
"list": [
{
"dt": 1399950000,
"main": {
"temp": 287.82,
"temp_min": 287.82,
"temp_max": 287.82,
"pressure": 923.74,
"sea_level": 1018.93,
"grnd_level": 923.74,
"humidity": 100,
"temp_kf": 0
},
"weather": [
{
"id": 501,
"main": "Rain",
"description": "moderate rain",
"icon": "10d"
}
],
"clouds": {
"all": 92
},
"wind": {
"speed": 0.51,
"deg": 226.005
},
"rain": {
"3h": 6
},
"sys": {
"pod": "d"
},
"dt_txt": "2014-05-13 03:00:00"
},
{
"dt": 1399960800,
"main": {
"temp": 291.36,
"temp_min": 291.358,
"temp_max": 291.36,
"pressure": 921.65,
"sea_level": 1016.09,
"grnd_level": 921.65,
"humidity": 87,
"temp_kf": 0
},
"weather": [
{
"id": 500,
"main": "Rain",
"description": "light rain",
"icon": "10d"
}
],
"clouds": {
"all": 20
},
"wind": {
"speed": 0.87,
"deg": 12.0018
},
"rain": {
"3h": 0.5
},
"sys": {
"pod": "d"
},
"dt_txt": "2014-05-13 06:00:00"
},
My problem is that I do not understand the logic of making java objects. I used jsongen for generating the java objects, but it seems it does not give me the right objects.
by jsongen my java object classes are:
public class Jweather {
private Number cod;
private Number message;
private City city;
private Number cnt;
private myList list;
...
}
public class City{
private Coord coord;
private String country;
private Number id;
private String name;
private Number population;
...
}
public class Coord{
private Number lat;
private Number lon;
...
}
public class myList{
List list = new ArrayList();
private Number clouds;
private Number deg;
private Number dt;
private Number humidity;
private Number pressure;
private Number speed;
private Temp temp;
private List weather;
...
}
public class Temp{
private Number day;
private Number eve;
private Number max;
private Number min;
private Number morn;
private Number night;
...
}
public class Weather{
private City city;
private Number cnt;
private String cod;
private List list;
private Number message;
...
}
I think myList, temp, weather classes are wrong. Am I write or wrong?
I think list.java should contain dt, main, weather, clouds, wind, rain, sys and dt_txt
and I also need a main.java class including: temp, temp_min, temp_max, pressure, sea_level, grnd_level, humidity and temp_kf
and a cloud.java class including: all
and wind class including: speed, deg
and rain class including:3h
and a sys class including: pob
Any help would be highly appreciated.
A: Based on the JSON you pasted in, I agree that the generated classes don't look correct. For example, morn does not seem to appear in the JSON at all. Did you paste in the entire JSON content that was used to generate the classes?
What are you using to serialize/deserialize the JSON? Jackson is a common framework with which to do that. You would need to define mappers from the beans that store the deserialized JSON to the POJO beans.
I've not used it myself (I use Jackson and create the JSON and POJO beans myself), but based on the json gen doc, it appears that it's intended to generate the JSON-bean side of things. So you would still need to (at least potentially) define your POJO beans (unless they happened to map 100%, which seems unlikely for a variety of reasons, from different JSON property names versus POJO field names, etc.).
| {
"language": "en",
"url": "https://stackoverflow.com/questions/23622686",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: NuGet Packages claiming to not be correctly installed I have a project that references
WindowsAzure.ServiceBus
However, when I rebuild the project, I get the error:
1>C:\Users\xyz\documents\visual studio
2017\Projects\MyProject\Class.cs(1,17,1,27): error
CS0234: The type or namespace name 'ServiceBus' does not exist in the
namespace 'Microsoft' (are you missing an assembly reference?)
1>C:\Users\xyz\documents\visual studio
2017\Projects\MyProject\Class.cs(12,24,12,38): error
CS0246: The type or namespace name 'EventHubClient' could not be found
(are you missing a using directive or an assembly reference?)
I've removed and restored the packages directory for the solution, but to no avail. I've tried re-installing the NuGet packages:
Update-Package -reinstall
Which claimed to successfully restore the package. I can Build the project successfully, but a Rebuild fails. Issuing an MSBuild in the command prompt also fails.
Just to alay any theories that there's no using statement, Class.cs:
using Microsoft.ServiceBus.Messaging;
I'm at a loss to how to progress with this; can anyone offer any ideas where to go next?
A: Posting for the points :) (I love them)
Other thing that comes to my mind is to Upgrade your .NET Framework version. If nuget dll was build for higher .NET runtime, there is just a Warning message printed in Output window and Error window stays clear. But Build fails.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/50639272",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.