text
stringlengths 64
89.7k
| meta
dict |
---|---|
Q:
java.sql.SQLException: Procedure or function ... expects parameter ..., which was not supplied
While executing daoMethod() I am getting the following exception:
java.sql.SQLException: Procedure or function 'Get_Books' expects parameter '@totalRowsReturned', which was not supplied.
Why? I did define @totalRowsReturned as OUTPUT. And I do not understand why I am required to supply @totalRowsReturned - it is an output parameter, not input.
Dao Class:
public class BookDao {
@Autowired
DataSource dataSource;
public void daoMethod() {
Integer programIdLocal = null;
Map<String, Object> parameters = new HashMap<String, Object>();
parameters.put("bookId", 1);
MyStoredProcedure storedProcedure = new MyStoredProcedure(dataSource);
//Exception!!!!
Map<String, Object> results = storedProcedure.execute(parameters);
}
private class MyStoredProcedure extends StoredProcedure {
private static final String SQL = "dbo.Get_Books";
public MyStoredProcedure(DataSource dataSource) {
setDataSource(dataSource);
setFunction(true);
setSql(SQL);
declareParameter(new SqlReturnResultSet("rs", new BookMapper()));
declareParameter(new SqlOutParameter("totalRowsReturned", Types.INTEGER));
declareParameter(new SqlParameter("bookId", Types.INTEGER));
setFunction(true);
compile();
}
}
}
Stored Procedure:
CREATE PROCEDURE [dbo].[Get_Books]
@bookId int,
@totalRowsReturned int OUTPUT
AS
BEGIN
SET NOCOUNT ON;
DECLARE @SelectQuery NVARCHAR(2000)
DECLARE @first_id int
DECLARE @totalRows int
SET @SelectQuery = 'FROM books b WHERE b.book_id >= @bookId'
Set @SelectQuery = 'SELECT @first_id = b.book_id , @totalRows=Count(*) OVER() ' + @SelectQuery + ' ORDER BY b.book_id'
Execute sp_Executesql @SelectQuery, N'@first_id int, @bookId int, @totalRows int OUTPUT', @first_id, @bookId, @totalRows=@totalRowsReturned OUTPUT
END
A:
There's a important caveat in the Javadoc for StoredProcedure#declareParameter() that you must declare the parameters in the order they are declared in the stored procedure, presumably because the same restriction exists for the underlying CallableStatement class. That means you should be declaring @bookId before @totalRowsReturned.
Also, I'm not all that knowledgable about JdbcTemplate but, based on this example, I don't think you need to declare a result set parameter.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Proper testing of http routes in go
I have 5 end points which have methods such as GET, POST, and DELETE to test. I wrote test cases using the go's in built testing package. I'm worried that I'm missing some cases which are not striking to my mind.I have posted in code review for my test case to be reviewed but I didn't get any response. I have also followed this post Testing HTTP routes in golang. All these test cases are checking for the response codes.
The problem is that, most of my test cases follow similar pattern where I post data in different formats and checking the response codes. I strongly feel like I'm missing something that will break my API when I push it to prod. I need some insight on testing these routes so that I can be confident to push the api to prod.
main_test.go
func TestSigHandler(t *testing.T){
test_cases := []string{"2021205"}
// GET Testing
for _, method := range test_cases{
usersUrl = fmt.Sprintf("%s/1/sig/id/%s", server.URL, method) //Grab the address for the API endpoint
request, err := http.NewRequest("GET", usersUrl, nil)
res, err := http.DefaultClient.Do(request)
if err != nil {
t.Error(err) //Something is wrong while sending request
}
if res.StatusCode != 200 {
t.Errorf("Something went wrong : ", res.StatusCode) //Uh-oh this means our test failed
}
}
// POST Testing
sig := []byte( `{
"raw": "a new sig"
}`)
usersUrl = fmt.Sprintf("%s/1/sig/id/2021205", server.URL) //Grab the address for the API endpoint
request, err := http.NewRequest("POST", usersUrl, bytes.NewBuffer(sig))
if err != nil{
t.Error(err)
}
request.Header.Set("Content-Type", "application/json")
res, err := http.DefaultClient.Do(request)
if err != nil {
t.Error(err) //Something is wrong while sending request
}
if res.StatusCode != 200 {
t.Errorf(" Something Went Wrong: ", res.StatusCode) //Uh-oh this means our test failed
}
// DELETE Testing
sigs_delete_cases := []string{ "1000345"}
for _, sig_to_be_deleted := range sigs_delete_cases{
usersUrl = fmt.Sprintf("%s/1/sig/id/%s", server.URL, sig_to_be_deleted) //Grab the address for the API endpoint
request, err := http.NewRequest("DELETE", usersUrl, nil)
res, err := http.DefaultClient.Do(request)
if err != nil {
t.Error(err) //Something is wrong while sending request
}
if res.StatusCode != 200 {
t.Errorf("Tried to delete a reserved Id : ", res.StatusCode) //Uh-oh this means our test failed
}
}
}
A:
I like to do this way:
Establish Continuous Integration. If your project is Open Source, you may use services like Travis CI - it has very easy installation. This helps you to see how changes affect code.
Set code test coverage. It allows you to see what source code lines are covered with tests and what are not and where very possible bugs will emerge. Of course, code coverage tool is not a panacea. And if line was checked it doesn't mean it is absolutely ok, and it will not fail with other input. But it helps much to maintain good code and look for bugs. For open source you may use coveralls.io. There's a special goveralls plugin for it.
To help the problem above you may use so-called Fuzzy testing - exploratory tests with random input to find a root cause. There're standard https://golang.org/pkg/testing/quick/ and non-standard packages https://github.com/dvyukov/go-fuzz.
Then I experiment with tests, they are both positive and negative. I try check situation with errors, timeouts, incorrect replies.
For my tests I've used as usual client http so httptest package.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
send inline keyboard like t.me/username but for userid in telegram php
I want to send an inline keyboard in which get the user into somebodey's chat whit his chat_id . I know that i can set a Url for inline keyboard like: t.me/username
but something like that doesn't work with
chat_id : t.me/123456
How to do that ?
A:
Just use an https:// prefix at the start of your InlineKeyboardButton's url.
So reply_markup parameter of the sendMessage method should look like this:
"reply_markup": {"inline_keyboard": [[{"text": "button text...", "url": "https://t.me/<chat_id or name of another user>"}]]}.
Full example with curl:
curl -v -H "Content-Type: application/json" -d '{"chat_id": 123456, "text": "here is your chat with <USERNAME>", "reply_markup": {"inline_keyboard": [[{"text": "here is your link to another user", "url": "https://t.me/<USERNAME>"}]]}}' https://api.telegram.org/bot<BOT_ID>:<BOT_TOKEN>/sendMessage
This line sends a Message to user with id = 123456. Message contains inline keyboard with one InlineKeyboardButton. This button has a link to chat with another user with id <USERNAME> and respective page URL https://t.me/<USERNAME>.
update
Unfortunately, if user you're looking for does not have a username, you cannot make a t.me link, so you cannot contact him:
You can write to people who are in your phone contacts and have Telegram. Another way of contacting people is to type their Telegam username into the search field.
...
You can set up a public username on Telegram. It then becomes possible for other users to find you by that username — you will appear in contacts search under ‘global results’. Please note that people who find you will be able to send you messages, even if they don't know your number. If you are not comfortable with this, we advise against setting up a username in Telegram.
So looks like the only solution here is to ensure that every needed contact has a username.
More information can be found here and here.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Internet Explorer 8 ignores closing span tags and continues to apply styles
I have a few classes that adjust font sizing:
.text-tall {
font-size: 1.5em;
}
.text-small {
font-size: .8em;
}
When I apply the class to a paragraph element
<p class="text-tall">Some text goes here.</p>
the styling work as expected. When I apply it to a span element
<p><span class="text-tall">Some text goes here.</span></p>
the adjusted font-size is applied to all text below the element on the page, sometimes resulting in progressively larger and larger text.
The obvious solution would be to simply always apply the class to the paragraph element, but my paragraph bottom margin is relatively sized (margin-bottom: 1.5em), so doing that increases the margin, too, which is something I don't want to do.
This only seems to be a problem in IE8 and lower. Any suggestions would be appreciated!
A:
Thanks for the tips, everyone. Turns out a function in my functions.php file (in WordPress) was removing the ending </span> tags.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
siunitx : forced parenthesis
Is there a way to force siunitx use parenthesis systematically ?
I tried bracket-numbers but it's only if :
There are certain combinations of numerical input which can be ambiguous.
I'd like to avoid a new macro even with optional parameter.
\documentclass{beamer}
\usepackage{polyglossia}
\setdefaultlanguage{french}
\newcommand{\Num}[2][]{$(\num[#1]{#2})$}
\RequirePackage[%
locale=FR,%
detect-all,%
table-number-alignment = center-decimal-marker,
inter-unit-product = \ensuremath{{}\cdot{}},
group-minimum-digits=4,
explicit-sign = +,
bracket-numbers = false
]{siunitx}
\begin{document}
\num{5,3} % -> (+5,3)
\num{-5,3} % -> (-5,3)
\Num{5,3} % -> (+5,3) ok
\Num{-5,3} % -> (-5,3) ok
\end{document}
A:
A slight modification on egreg's idea:
\documentclass{beamer}
\usepackage{polyglossia}
\setdefaultlanguage{french}
\RequirePackage[%
locale=FR,%
detect-all,%
table-number-alignment = center-decimal-marker,
inter-unit-product = \ensuremath{{}\cdot{}},
group-minimum-digits=4,
explicit-sign = +,
bracket-numbers = false
]{siunitx}
\begin{document}
\newcommand{\pair}[1]{(\num{#1})}
\num{5,3} % -> (+5,3)
\num{-5,3} % -> (-5,3)
\pair{5,3}
\pair{-5,3} + \pair{-5,2}
\pair{1} + \pair{-3} = \pair{-2}
\end{document}
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Grouping XML with XSL
i am a little bit stuck with grouping. I have the following XML-Code:
<?xml version="1.0" encoding="UTF-8"?>
<isif_data>
<date>29.05.
<event-date>
<type>type1</type>
<Time Timesort="1845">18.45</Time>
<title>event1</title>
<cell/>
<place>abc</place>
</event-date>
<event-date>
<type>type1</type>
<Time Timesort="0900">9</Time>
<title>event2</title>
<cell/>
<place>abd</place>
</event-date>
<event-date>
<type>type2</type>
<Time Timesort="1930">19.30</Time>
<title>event3</title>
<cell/>
<place>abe</place>
</event-date>
<event-date>
<type>type2</type>
<Time Timesort="1900">19</Time>
<title>event4</title>
<cell/>
<place>abf</place>
</event-date>
</date>
<date>30.05.
<event-date>
<type>type1</type>
<Time Timesort="1845">18.45</Time>
<title>event5</title>
<cell/>
<place>abg</place>
</event-date>
<event-date>
<type>type2</type>
<Time Timesort="0900">9</Time>
<title>event6</title>
<cell/>
<place>abh</place>
</event-date>
<event-date>
<type>type1 </type>
<Time Timesort="1500">15</Time>
<title>event7</title>
<cell/>
<place>abi</place>
</event-date>
<event-date>
<type>type2</type>
<Time Timesort="1700">17</Time>
<title>event8</title>
<cell/>
<place>abj</place>
</event-date>
</date>
</isif_data>
Now i need the resulting XML to look something like this:
<?xml version="1.0" encoding="UTF-8"?>
<isif_data>
<date>29.05.</date>
<type>type1</type>
<Time>9</Time>
<title>event2</title>
<cell/>
<place>abd</place>
<Time>18.45</Time>
<title>event1</title>
<cell/>
<place>abc</place>
<type>type2</type>
<Time>19</Time>
<title>event4</title>
<cell/>
<place>abf</place>
<Time>19.30</Time>
<title>event3</title>
<cell/>
<place>abe</place>
<date>30.05.</date>
<type>type1</type>
<Time>15</Time>
<title>event7</title>
<cell/>
<place>abi</place>
<Time>18.45</Time>
<title>event5</title>
<cell/>
<place>abg</place>
<type>type2</type>
<Time>9</Time>
<title>event6</title>
<cell/>
<place>abh</place>
<Time>17</Time>
<title>event8</title>
<cell/>
<place>abj</place>
</isif_data>
I tried it with the Muenchian Method but i never got it working like i want. Anybody here, who has an idea how to get it working? I need to use xsl version 1.0. If you need more infos just tell me. Thanks in advance :-)
Edit: I tried the following XSLT:
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" encoding="UTF-8" indent="yes" />
<xsl:key name="type" match="event-date" use="type" />
<xsl:template match="isif_data">
<xsl:element name="isif_data">
<xsl:for-each select="date">
<xsl:element name="date"><xsl:value-of select="date"/></xsl:element>
<xsl:element name="cell"/>
<xsl:for-each select="event-date[count(. | key('type', type)[1]) = 1]">
<xsl:sort select="time/@Timesort" />
<xsl:call-template name="type" />
<xsl:for-each select="key('type', type)">
<xsl:call-template name="time" />
<xsl:call-template name="title" />
<xsl:call-template name="place" />
</xsl:for-each>
</xsl:for-each>
</xsl:for-each>
</xsl:element>
</xsl:template>
</xsl:stylesheet>
If you need templates i can provide them too. I'm not really sure if it they are needed.
A:
Is there a possibility to make a group for each date-tag from the
original code?
This:
<xsl:key name="type" match="event-date" use="type" />
will group all event-dates by type, regardless of date. Since you want to group the events by type within each date, you need to use both date and type in the key:
<xsl:key name="type" match="event-date" use="concat (../., '|', type)" />
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Divergent series whose terms converge to zero
I've just begun to teach my class series. We usually have workshops where they work in groups on a tougher problem, and I was thinking of asking them to come up with a divergent series whose terms converge to $0$. While $\sum 1/n$ is the prototypical example, we haven't done the integral test yet. Do you know of any simpler examples?
A:
The simplest one I can think of:
$$ \begin{align} S& = 1 + \frac12 + \frac12 + \frac13 + \frac13 + \frac13 + \frac14 + \frac14 + \frac14 + \frac14 + \cdots \\
&= 1 + \,1\quad +\quad \,\, 1 \quad \quad\, +\quad \quad \,\, 1\, + \cdots
\end{align}
$$
In fact why don't you let your students make the suggestions?
A:
The integral test isn't needed: we can argue by contradiction.
Let $S_n = \sum_{k=1}^n 1/k$. Then:
$$S_{2n} - S_n= \sum_{k=1}^{2n} 1/k - \sum_{k=1}^n1/k = \sum_{k=n+1}^{2n}1/k$$
If $(S_n)$ converges, then $\lim(S_{2n} - S_n) = 0$. However,
$$k \le 2n \implies \frac{1}{2n} \le \frac{1}{k}$$
Applying sums from $n+1$ till $2n$:
$$\frac12 \le S_{2n} - S_n$$
Taking $n \to \infty$, $\lim(S_{2n} - S_n) \ge 1/2$. Contradiction,
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How can I have % of width of an img wrapped in a specific div width?
I just wrapped an image into a div so that I could control exactly the position of my image when the screen is resized. Everything worked so fine, like, a left part was hid when I resize and so the right part was hid too at my specification. But It appears that my img stay the same width, so there's that annoying horizontal scroll bar.
Here's my live demo:
http://jsfiddle.net/U3pB9/11/
HTML:
<div id="slideShow">
<img id="ss1" src="http://i.imgur.com/gDRF4rO.jpg">
</div>
CSS:
#slideShow {
width:1200px;
height:329px;
margin:auto;
}
#ss1 {
width:1920px;
height:329px;
display:block;
position:relative;
left:-360px;
overflow:hidden;
border-bottom:3px solid rgb(254,199,73);
}
So, I tried to have a dynamic weight for my picture, equal to the user screen width but it won't just work. The number was right when the screen is resized but the image width was just wrong. I tried to put a overflow:hidden in my img id, but then again, nothing happen. The scroll bar is still there when you resize the window.
So, when you resize your screen, how to hide that horizontal scroll bar? How to get rid of that right part of the picture?
EDIT PART
Due to my bad english (lol), here's two picture of what I am trying to achieve :
Lets say the user has a 1920px screen width.
My image will look like this :
http://tinypic.com/view.php?pic=29zat0&s=8#.UxSJ5_nxo9U
Then, if the user resize his window to, lets say around 1700, or even 1500 px, my picture will look like this :
http://tinypic.com/view.php?pic=241qpvl&s=8#.UxSJ_Pnxo9U
So as you see, 1200px of my image is centered even when the window is resized until the screen size get 1200px width. So a left part of the image is hid as a right part of the image is hid too! (Then, when the screen will get 1200px, I will just resize it with media queries in %)
A:
Problem
Width is set explicitly. Since the width of the child is larger than the parent, the child will overflow.
[edit] To remove the scroll bar, essentially it's the same problem. Setting overflow: hidden to the child will only affect the child and not the parent. In this case #slideShow will overflow because hidden only affects #ss1.
Solution
Set the width of both the child to 100%. This means it will be 100% of the width of the container.
[edit] Set overflow on the affected parents. In this case it's #slideShow's parent or
Example
body {
overflow: hidden; /*removes scrollbar on the body */
width: 100%;
}
#slideShow {
width: 100%; /* Sets width to body */
}
#ss1 {
width: 100%; /* Sets widht to #slideShow */
}
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How do I associate an Elastic IP with a Fargate container?
I'm exploring using the new Fargate option for my ECS containers. One constraint is that the running task must always be accessible at the same Public IP address.
My first thought was to allocate an Elastic IP but I can't tell what to associate it to. It seems an Elastic IP can be associated to an instance (which is irrelevant for Fargate) or a Network Interface. However, if I associate it with an ENI, I can't see how to ensure my task's container has that Network Interface. When creating a Service, I see that I can put it in a VPC, but that's it.
From experimentation, if I kill a task so that the service restarts a new one, or if I update the service to run a new task revision - the container that starts running the new task will have a new ENI each time.
Is there some way to ensure that a given service has the same public IP address, even if its tasks are killed and restarted?
A:
Fargate does not currently support ENI assignment, so it is not possible to have an Elastic IP associated with a Fargate task definition.
The only way you can use a static IP address with Fargate is via the Application Load Balancer with an alias.
A:
Actually your can do it with Network Load balancer. It is a special type of load balancer, where elastic IP can be added.
This instruction can really help
https://docs.aws.amazon.com/elasticloadbalancing/latest/network/introduction.html
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Titanium ScrollableView height is bigger on iOS
I currently have a scrollable view to scroll through some images.
On Android it's fine, but on iOS the height seems to be a bit bigger as I have some text under the scrollable view and its being pushed down a bit on iOS, while on Android the text is right under where it should be
index.js:
var win = $.index;
if(Alloy.Globals.osname == "android"){
win.backgroundColor = "#000";
}
//If iOS
else{
win.backgroundColor = "#FFF";
}
win.orientationModes = [
Ti.UI.PORTRAIT,
Ti.UI.UPSIDE_PORTRAIT
];
function textColor(){
if(Alloy.Globals.osname == "android"){
return "#FFF";
}
else{
return "#000";
}
}
var button = Titanium.UI.createButton({
title: 'Test Button',
bottom: 30,
width: "75%",
height: "auto",
visible: false
});
var page_view = Titanium.UI.createView({
top: 10,
width: Ti.UI.SIZE,
height: "85%",
layout: "vertical",
visible: false
});
var page_descr = Titanium.UI.createLabel({
text: "This is a description",
width: "75%",
font: { fontSize: 36 },
color: textColor(),
textAlign: Ti.UI.TEXT_ALIGNMENT_CENTER,
});
var page_image1 = Titanium.UI.createImageView({
image: "/images/screens_android/adsteps_1.jpg",
});
var page_image2 = Titanium.UI.createImageView({
image: "/images/screens_android/adsteps_2.jpg",
});
var page_image3 = Titanium.UI.createImageView({
image: "/images/screens_android/adsteps_3.jpg",
});
var page_image4 = Titanium.UI.createImageView({
image: "/images/screens_android/adsteps_4.jpg",
});
//Change the images to the iOS images
if(Alloy.Globals.osname != "android"){
page_image1.image = "/images/screens_ios/ios_1.jpg";
page_image2.image = "/images/screens_ios/ios_2.jpg";
page_image3.image = "/images/screens_ios/ios_3.jpg";
page_image4.image = "/images/screens_ios/ios_4.jpg";
}
var image_scroller = Titanium.UI.createScrollableView({
width: "100%",
height: "auto",
showPagingControl: false,
backgroundColor: "white",
views: [page_image1, page_image2, page_image3, page_image4],
});
image_scroller.addEventListener('scrollend',function(e)
{
label_step.text = steps(image_scroller.currentPage+1);
});
//Create a view to hold the scrollable view
var view_holder = Ti.UI.createScrollView({
width: "75%",
height: "60%",
top: 5,
});
view_holder.add(image_scroller);
var label_step = Titanium.UI.createLabel({
text: "Test text",
top: 5,
width: "70%",
font: {fontSize: 21 },
color: textColor(),
textAlign: Ti.UI.TEXT_ALIGNMENT_CENTER,
});
var label_slide = Titanium.UI.createLabel({
text: "(Swipe to view next step)",
font: {fontSize: 19 },
top: 5,
color: textColor(),
textAlign: Ti.UI.TEXT_ALIGNMENT_CENTER,
width: "70%",
});
page_view.add(page_descr);
page_view.add(label_step);
page_view.add(view_holder);
page_view.add(label_slide);
//Fix fonts
if(Alloy.Globals.osname != "android"){
page_descr.width = "80%";
page_descr.top = 30;
page_descr.font = {fontSize: 19};
label_step.width = "90%";
label_step.font = {fontSize: 15};
label_slide.top = 2;
label_slide.font = {fontSize: 14};
image_scroller.top = -120;
}
else{
page_descr.width = "80%";
page_descr.top = 30;
page_descr.font = {fontSize: 15};
label_step.width = "90%";
label_step.font = {fontSize: 11};
label_slide.top = 5;
label_slide.font = {fontSize: 12};
image_scroller.top = -120;
}
win.add(page_view);
button.addEventListener('click',function(e)
{
alert("I clicked the button!");
});
win.add(button);
win.open();
The android image sizes are all: 768x735px while the iOS images are 475x475px.
Here's a screenshot of what's happening on iOS, it's pushing the text "(Swipe to view next step)" down when it should be directly below the image of the iOS home screen:
http://i.imgur.com/GfDpeDb.jpg
A:
try after commenting the top of label_slide like,
var label_slide = Titanium.UI.createLabel({
text : "(Swipe to view next step)",
font : {
fontSize : 19
},
//top : 5,
color : textColor(),
textAlign : Ti.UI.TEXT_ALIGNMENT_CENTER,
width : "70%",
});
And tell me either it works or not.
A:
The best and easiest way to do this is to use DP values instead of percentages. If you haven't set it up or modified your tiapp.xml yet your iOS devices use DP and Android uses pixels. This is why you are seeing a difference in the layout.
Dp : Density-independent pixels. A measurement which is translated natively to a corresponding pixel measure using a scale factor based on a platform-specific "default" density, and the device's physical density.
In your tiapp.xml change the default unit to dp.
<property name="ti.ui.defaultunit" type="string">dp</property>
If you then recompile the app, clean and build it will be set up to use DP values. Try using these instead of percentages.
Details on this can be seen here -
http://docs.appcelerator.com/titanium/3.0/#!/guide/Layouts,_Positioning,_and_the_View_Hierarchy
|
{
"pile_set_name": "StackExchange"
}
|
Q:
firebase realtime storage getting a specific value from all children
i am building a app using firebase that requires an admin page and in it i want to make a list of all the usernames of users registered in the system and i am using this code:
Usernames = new ArrayList<>();
usersdb = FirebaseDatabase.getInstance().getReference().child("Users");
usersdb.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot user:dataSnapshot.getChildren()) {
Usernames.add(user.child("username").getValue().toString());
}
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
adp = new ArrayAdapter<String>(context,android.R.layout.simple_list_item_1,Usernames);
lv.setAdapter(adp);
and for some reason nothing shows up in the list view in the end anyone knows why?
and my data structure looks like this:(the random letters are user uids)
Users
----sdfbsif
-----------email
-----------username
-----------password
----djgsvnv
-----------email
-----------username
-----------password
A:
You're calling setAdapter() before the data is available from your listener. addValueEventListener is asynchronous and returns immediately, which means you're passing an empty list to the adapter. Put log messages throughout your code to see the order in which it's executing.
Instead, you could call setAdapter in the callback after all the data from the snapshot is available.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Конвертация изображения в 256-цветное, Python
Необходимо значительно сократить вес изображения (в десятки раз). На входе идёт черно-белое изображение в формате .jpeg. Если я правильно понимаю, оно может хранить в себе 256^3 цветов. Но мне необходимы только все серые оттенки. Не знаю, возможно ли это в принципе. Попробовал сохранять в .gif, но начинает весить ещё больше, как в принципе и с любым другим форматом.
from PIL import Image
img = Image.open('1.jpeg').convert('LA')
img.save('1.gif')
A:
convert('LA') — конвертит с альфа-каналом.
convert('L') — конвертит в 8-битовые пиксели ч/б, это похоже на вашу задачу.
Список модов тут: https://pillow.readthedocs.io/en/stable/handbook/concepts.html#concept-modes
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Do you need to put grease on car battery?
Some cars have grease on the battery terminas and some don't. I have just replaced a battery. Is it needed? Why? Can I just go without?
Also I want to clean the top part of my terminals with baking soda and water mix. Do I have to remove the grease first?
A:
The grease is there to prevent corrosion on the battery terminals, when you put the connector on and tighten it down the grease gets squeezed out and what's left prevents corrosion where there's no metal to metal contact. If your battery came greased then there's no reason to clean the terminals unless the grease got rubbed off and the terminals corroded. If there's no corrosion there's no need to clean them.
If there's no grease or insufficient grease after tightening then I like to put a dab of vaseline on the top of the contacts to make sure air can't get in.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Apache Ignite How to set the primary key to automatically grow?
Well, I have a requirement now that requires Apache Ignite SQL. When creating a table, it is similar to setting the primary key to grow automatically in Mysql. When the Apache Ignite creates the table, set the primary key to grow automatically?
A:
There is no autoincrement in Ignite SQL. But you can implement a custom SQL function, that generates IDs, based on IgniteAtomicSequence:
public class SqlFunc {
@QuerySqlFunction
public static long nextId() {
Ignite ignite = Ignition.ignite();
IgniteAtomicSequence seq = ignite.atomicSequence("seq", 0, true);
return seq.getAndIncrement();
}
}
Here is cache a configuration, that allows to use nextId() function in SQL:
<bean class="org.apache.ignite.configuration.CacheConfiguration">
<property name="name" value="cache"/>
<property name="sqlFunctionClasses" value="com.example.SqlFunc"/>
<property name="sqlSchema" value="PUBLIC"/>
</bean>
More on custom SQL functions: https://apacheignite-sql.readme.io/docs/custom-sql-functions
UPD:
Note, that every time IgniteAtomicSequence reserves a range of ids, an internal transaction is started. It may lead to unexpected consequences like deadlocks, if explicit transactions are used.
So, this approach should be used with care. In particular, SQL queries, that use the nextId() function, shouldn't be run within transactions.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Motivation of Moment Generating Functions
What is the motivation of defining the moment generating function of a random variable $X$ as: $E[e^{tX}]$? I know that one can obtain the mean, second moment, etc.. after computing it. But what was the intuition in using $e^{x}$? Is it because its one-to-one and always increasing?
A:
If X and Y are independent then $E[e^{t(X+Y)}] = E[e^{tX}] E[e^{tY}]$, so convolution corresponds to multiplication of the mgf's. Another reason: the moment generating function is actually a Fourier transform.
Now suppose $X_i$ are i.i.d. with zero mean, and define $Y_n = \sum_{i=1}^n X_i/\sqrt{n}$. Define $\phi(t) = E[e^{tX_1}]$. Then $E[e^{tY_n}] = \phi(t/\sqrt{n})^n$. Under reasonable assumptions, $\phi(t) = 1 + V[X_1]t^2/2 + O(t^3)$, and so $E[e^{tY_n}] = (1 + V[X_1]t^2/2n + O(t^3)/n^{1.5})^n \longrightarrow e^{V[X_1]t^2/2}$, and we get the central limit theorem (by continuity of the Fourier transform).
A:
The goal is to to put all the moments in one package. Since
$$
e^{tx} = \sum \frac{x^n}{n!} t^n
$$
the coefficients of $t^n$ in $E(e^{tx})$ are (scaled) moments. In other contexts we can use
$$
(1-xt)^{-1} = \sum x^n t^n
$$
in place of $e^{tx}$. This gives more or less what engineers call the "z-transform"
and in combinatorics it is known as "ordinary generating function". Using the exponential
has the happy advantage that convolution of random variables translates to product
of moment generating functions.
A:
Take the definition of "generating function" for a sequence. Do it where the sequence is the sequence consisting of the moments of $X$. That's it.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Why is this simple Spark program not utlizing multiple cores?
So, I'm running this simple program on a 16 core multicore system. I run it
by issuing the following.
spark-submit --master local[*] pi.py
And the code of that program is the following.
#"""pi.py"""
from pyspark import SparkContext
import random
N = 12500000
def sample(p):
x, y = random.random(), random.random()
return 1 if x*x + y*y < 1 else 0
sc = SparkContext("local", "Test App")
count = sc.parallelize(xrange(0, N)).map(sample).reduce(lambda a, b: a + b)
print "Pi is roughly %f" % (4.0 * count / NUM_SAMPLES)
When I use top to see CPU
consumption, only 1 core is being utilized. Why is it so? Seconldy, spark
documentation says that the default parallelism is contained in property
spark.default.parallelism. How can I read this property from within my
python program?
A:
As none of the above really worked for me (maybe because I didn't really understand them), here is my two cents.
I was starting my job with spark-submit program.py and inside the file I had sc = SparkContext("local", "Test"). I tried to verify the number of cores spark sees with sc.defaultParallelism. It turned out that it was 1. When I changed the context initialization to sc = SparkContext("local[*]", "Test") it became 16 (the number of cores of my system) and my program was using all the cores.
I am quite new to spark, but my understanding is that local by default indicates the use of one core and as it is set inside the program, it would overwrite the other settings (for sure in my case it overwrites those from configuration files and environment variables).
A:
Probably because the call to sc.parallelize puts all the data into one single partition. You can specify the number of partitions as 2nd argument to parallelize:
part = 16
count = sc.parallelize(xrange(N), part).map(sample).reduce(lambda a, b: a + b)
Note that this would still generate the 12 millions points with one CPU in the driver and then only spread them out to 16 partitions to perform the reduce step.
A better approach would try to do most of the work after the partitioning: for example the following generates only a tiny array on the driver and then lets each remote task generate the actual random numbers and subsequent PI approximation:
part = 16
count = ( sc.parallelize([0] * part, part)
.flatMap(lambda blah: [sample(p) for p in xrange( N/part)])
.reduce(lambda a, b: a + b)
)
Finally, (because the more lazy we are the better), spark mllib actually comes already with a random data generation which is nicely parallelized, have a look here: http://spark.apache.org/docs/1.1.0/mllib-statistics.html#random-data-generation. So maybe the following is close to what you try to do (not tested => probably not working, but should hopefully be close)
count = ( RandomRDDs.uniformRDD(sc, N, part)
.zip(RandomRDDs.uniformRDD(sc, N, part))
.filter (lambda (x, y): x*x + y*y < 1)
.count()
)
|
{
"pile_set_name": "StackExchange"
}
|
Q:
What is difference between “+” and “~” selector in CSS?
I have used these selector. However, not able to get the difference them.
It seems like they both work same. Their must be some difference which I am not able to get.
A:
+ will only select the first element that is immediately preceded by the former selector.
~ selector all the sibling preceded by the former selector.
.plusSelector + div {
background: red
}
.tiltSelector ~ div {
background: red
}
<h3>+ Selector</h3>
<div class="example1">
<div class="plusSelector">test</div>
<div>test</div>
<div>test</div>
<div>test</div>
<div>test</div>
</div>
<h3>~ Selector</h3>
<div class="example1">
<div class="tiltSelector">test</div>
<div>test</div>
<div>test</div>
<div>test</div>
<div>test</div>
</div>
|
{
"pile_set_name": "StackExchange"
}
|
Q:
iTunesConnect: "One or more of your app previews could not be loaded. Try again."
Problem
Recently I uploaded App preview video to my app in iTunesConnect
It looks like it was uploaded successfully, I was able to play it but there was a text overlay on the video preview:
Processing App Preview
The app preview can take up to 24 hours to process.
I have closed Safari and go to sleep. Next morning I see this
Questions
How can I get a reason why this happens, as far as I see my video conform to https://help.apple.com/app-store-connect/#/dev4e413fcb8 , here is ffprobe output for it
ffprobe version 4.1.4 Copyright (c) 2007-2019 the FFmpeg developers
built with Apple LLVM version 10.0.1 (clang-1001.0.46.4)
configuration: --prefix=/usr/local/Cellar/ffmpeg/4.1.4_1 --enable-shared --enable-pthreads --enable-version3 --enable-avresample --cc=clang --host-cflags='-I/Library/Java/JavaVirtualMachines/adoptopenjdk-12.0.1.jdk/Contents/Home/include -I/Library/Java/JavaVirtualMachines/adoptopenjdk-12.0.1.jdk/Contents/Home/include/darwin' --host-ldflags= --enable-ffplay --enable-gnutls --enable-gpl --enable-libaom --enable-libbluray --enable-libmp3lame --enable-libopus --enable-librubberband --enable-libsnappy --enable-libtesseract --enable-libtheora --enable-libvorbis --enable-libvpx --enable-libx264 --enable-libx265 --enable-libxvid --enable-lzma --enable-libfontconfig --enable-libfreetype --enable-frei0r --enable-libass --enable-libopencore-amrnb --enable-libopencore-amrwb --enable-libopenjpeg --enable-librtmp --enable-libspeex --enable-videotoolbox --disable-libjack --disable-indev=jack --enable-libaom --enable-libsoxr
libavutil 56. 22.100 / 56. 22.100
libavcodec 58. 35.100 / 58. 35.100
libavformat 58. 20.100 / 58. 20.100
libavdevice 58. 5.100 / 58. 5.100
libavfilter 7. 40.101 / 7. 40.101
libavresample 4. 0. 0 / 4. 0. 0
libswscale 5. 3.100 / 5. 3.100
libswresample 3. 3.100 / 3. 3.100
libpostproc 55. 3.100 / 55. 3.100
Input #0, mov,mp4,m4a,3gp,3g2,mj2, from '/Users/camobap/my_video.mp4':
Metadata:
major_brand : isom
minor_version : 512
compatible_brands: isomiso2avc1mp41
encoder : Lavf58.20.100
Duration: 00:00:30.04, start: 0.000000, bitrate: 1512 kb/s
Stream #0:0(eng): Video: h264 (High) (avc1 / 0x31637661), yuv420p, 886x1920, 1377 kb/s, 25 fps, 25 tbr, 12800 tbn, 50 tbc (default)
Metadata:
handler_name : ?Mainconcept Video Media Handler
Stream #0:1(eng): Audio: aac (LC) (mp4a / 0x6134706D), 48000 Hz, stereo, fltp, 130 kb/s (default)
Metadata:
handler_name : #Mainconcept MP4 Sound Media Handler
Who actually does this video review? Humans or machines?
Is there any automation script to do this validation before upload?
A:
Silly me, looks like 24 hours wasn't passed, once I waited more time this problem just gone
P.S. only Safari show this, there is no error in Google Chrome
P.P.S sometimes it happens even for successfully processed video but after a page refresh, the problem is gone
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Angular и перенос текста в textarea
Пишу приложение на angular, и появилась задача: когда пользователь вводит текст в textarea и нажимает enter, необходимо данную форму отправить, а если ctrl+enter, то сделать перенос.
Проблема в том, что мне необходимо, чтобы перенос работал как стандартный, т.е. чтобы сделать перенос в середине слова, нужно знать координаты курсора (или может это можно сделать как-то по другому?).
Вот какой код у меня есть сейчас:
@HostListener('window:keydown', ['$event']) keyEvent(event: KeyboardEvent) {
if (event.key === "Enter" && (event.ctrlKey === true || event.metaKey === true) && event.shiftKey === false
&& event.altKey === false) {
let mes = this.chatForm.value.message + '\n';
console.log(event);
//console.log(document.caretRangeFromPoint(event.x, event.y));
this.chatForm.setValue({ message: mes });
} else if (event.key === "Enter" && event.ctrlKey === false && event.shiftKey === false && event.altKey === false) {
event.preventDefault();
if (this.chatForm.value.message !== '') {
this.onSubmit(this.chatForm.value);
}
}
}
Я бы мог определить положение курсора и вставить перенос, но у меня кликается клавиатура, а не мышь, поэтому у меня нет координат курсора.
A:
сделать перенос в середине слова, нужно знать координаты курсора
там:
песочница
тут пример:
"use strict";
textarea.addEventListener('keydown', (e) => {
const { code, ctrlKey } = e;
if ('Enter' === code) {
e.preventDefault();
e.stopPropagation();
if (ctrlKey) {
console.log('ctrl enter');
foo(e.currentTarget);
}
else {
console.log('enter');
}
}
});
function foo(textarea) {
const { selectionStart, value } = textarea;
textarea.value = `${value.slice(0, selectionStart)}${'\n'}${value.slice(selectionStart, value.length)}`;
textarea.selectionStart = selectionStart + 1;
textarea.selectionEnd = selectionStart + 1;
}
<textarea id="textarea"></textarea>
selectionStart - https://developer.mozilla.org/ru/docs/Web/API/HTMLInputElement/setSelectionRange
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How to compile a kernel module against a new Source
I am trying to compile a Hello World module. I am having a fresh Ubuntu in my system which doesn't have any compiled kernel.
My kernel is:
2.6.32-34-generic
I gave the following Makefile and got the error:
obj-m += hello-1.o
all:
make -C /lib/modules/$(shell uname -r)/build M=$(PWD) modules
clean:
make -C /lib/modules/$(shell uname -r)/build M=$(PWD) clean
# make
make -C /lib/modules/2.6.32-34-generic/build M=/home/james/Desktop/hello modules
make[1]: Entering directory `/usr/src/linux-headers-2.6.32-34-generic'
make[2]: *** No rule to make target `/home/james/Desktop/hello/hello-1.c', needed by `/home/james/Desktop/hello/hello-1.o'. Stop.
make[1]: *** [_module_/home/james/Desktop/hello] Error 2
make[1]: Leaving directory `/usr/src/linux-headers-2.6.32-34-generic'
make: *** [all] Error 2
The contents of my /lib/modules/2.6.32-34-generic are
total 3864
lrwxrwxrwx 1 root root 40 2011-11-05 15:55 build -> /usr/src/linux-headers-2.6.32-34-generic
drwxr-xr-x 2 root root 4096 2011-11-05 15:49 initrd
drwxr-xr-x 10 root root 4096 2011-11-05 15:49 kernel
.......................................................
.......................................................
The folder /usr/src/linux-headers-2.6.32-34-generic exists.
Since it didnt work, I downloaded the linux-headers-2.6.32-34-generic source from Ubuntu and compiled and changed my Makefile to:
obj-m += hello-1.o
all:
make -C /usr/src/linux-2.6.32/ M=$(PWD) modules
clean:
make -C /usr/src/linux-2.6.32/ M=$(PWD) clean
#make
make -C /usr/src/linux-2.6.32/ M=/home/james/Desktop/hello modules
make[1]: Entering directory `/usr/src/linux-2.6.32'
ERROR: Kernel configuration is invalid.
include/linux/autoconf.h or include/config/auto.conf are missing.
Run 'make oldconfig && make prepare' on kernel src to fix it.
WARNING: Symbol version dump /usr/src/linux-2.6.32/Module.symvers
is missing; modules will have no dependencies and modversions.
make[2]: *** No rule to make target `/home/james/Desktop/hello/hello-1.c', needed by `/home/james/Desktop/hello/hello-1.o'. Stop.
make[1]: *** [_module_/home/james/Desktop/hello] Error 2
make[1]: Leaving directory `/usr/src/linux-2.6.32'
make: *** [all] Error 2
Could someone help me solving this.http://packages.ubuntu.com/lucid-updates/devel/linux-headers-2.6.32-34-generic
I have some general questions to ask.
After a fresh install what is the best way of compiling a kernel. After I compiled the kernel and built a module it worked flawlessly earlier. But I couldnt know what to do this in this situation
A:
make[2]: * No rule to make target
/home/james/Desktop/hello/hello-1.c', needed by/home/james/Desktop/hello/hello-1.o'. Stop
Your are facing this error in the first compilation because hello-1.c file is missing in /home/james/Desktop/hello/ directory.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How good is the JVM at parallel processing? When should I create my own Threads and Runnables? Why might threads interfere?
I have a Java program that runs many small simulations. It runs a genetic algorithm, where each fitness function is a simulation using parameters on each chromosome. Each one takes maybe 10 or so seconds if run by itself, and I want to run a pretty big population size (say 100?). I can't start the next round of simulations until the previous one has finished. I have access to a machine with a whack of processors in it and I'm wondering if I need to do anything to make the simulations run in parallel. I've never written anything explicitly for multicore processors before and I understand it's a daunting task.
So this is what I would like to know: To what extent and how well does the JVM parallel-ize? I have read that it creates low level threads, but how smart is it? How efficient is it? Would my program run faster if I made each simulation a thread? I know this is a huge topic, but could you point me towards some introductory literature concerning parallel processing and Java?
Thanks very much!
Update:
Ok, I've implemented an ExecutorService and made my small simulations implement Runnable and have run() methods. Instead of writing this:
Simulator sim = new Simulator(args);
sim.play();
return sim.getResults();
I write this in my constructor:
ExecutorService executor = Executors.newFixedThreadPool(32);
And then each time I want to add a new simulation to the pool, I run this:
RunnableSimulator rsim = new RunnableSimulator(args);
exectuor.exectue(rsim);
return rsim.getResults();
The RunnableSimulator::run() method calls the Simulator::play() method, neither have arguments.
I think I am getting thread interference, because now the simulations error out. By error out I mean that variables hold values that they really shouldn't. No code from within the simulation was changed, and before the simulation ran perfectly over many many different arguments. The sim works like this: each turn it's given a game-piece and loops through all the location on the game board. It checks to see if the location given is valid, and if so, commits the piece, and measures that board's goodness. Now, obviously invalid locations are being passed to the commit method, resulting in index out of bounds errors all over the place.
Each simulation is its own object right? Based on the code above? I can pass the exact same set of arguments to the RunnableSimulator and Simulator classes and the runnable version will throw exceptions. What do you think might cause this and what can I do to prevent it? Can I provide some code samples in a new question to help?
A:
Java Concurrency Tutorial
If you're just spawning a bunch of stuff off to different threads, and it isn't going to be talking back and forth between different threads, it isn't too hard; just write each in a Runnable and pass them off to an ExecutorService.
You should skim the whole tutorial, but for this particular task, start here.
Basically, you do something like this:
ExecutorService executorService = Executors.newFixedThreadPool(n);
where n is the number of things you want running at once (usually the number of CPUs). Each of your tasks should be an object that implements Runnable, and you then execute it on your ExecutorService:
executorService.execute(new SimulationTask(parameters...));
Executors.newFixedThreadPool(n) will start up n threads, and execute will insert the tasks into a queue that feeds to those threads. When a task finishes, the thread it was running on is no longer busy, and the next task in the queue will start running on it. Execute won't block; it will just put the task into the queue and move on to the next one.
The thing to be careful of is that you really AREN'T sharing any mutable state between tasks. Your task classes shouldn't depend on anything mutable that will be shared among them (i.e. static data). There are ways to deal with shared mutable state (locking), but if you can avoid the problem entirely it will be a lot easier.
EDIT: Reading your edits to your question, it looks like you really want something a little different. Instead of implementing Runnable, implement Callable. Your call() method should be pretty much the same as your current run(), except it should return getResults();. Then, submit() it to your ExecutorService. You will get a Future in return, which you can use to test if the simulation is done, and, when it is, get your results.
A:
You can also see the new fork join framework by Doug Lea. One of the best book on the subject is certainly Java Concurrency in Practice. I would strong recommend you to take a look at the fork join model.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
msqldump without shell interpretation
I am trying to run a command on a remote server via a java program. Part of the code is below:
Process backUp = Runtime.getRuntime().exec(cmd);
BufferedReader stdInput = new BufferedReader(new InputStreamReader(backUp.getInputStream()));
BufferedReader stdError = new BufferedReader(new InputStreamReader(backUp.getErrorStream()));
with the cmd string containing:
sudo mysqldump --host=localhost --no-data --user=root --password=*******
lbs company > /home/ubuntu/michael/***************/lbs.company.sql
I know my problem here is that the ">" is used for shell-interpreted commands which don't work with runtime.exec. How can I format my mysqldump command to get around this? Thanks.
A:
Instead of redirecting the output via ">", you can use --result-file to specify the output of mysqldump. So
mysqldump --host=localhost --user=root --password=******* lbs company > /home/lbs.company.sql
becomes
mysqldump --host=localhost --user=root --password=******* --result-file=/home/lbs.company.sql lbs company
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Concurency thread and lock in ASP.NET
I’m wondering how asp.net handle “simultaneous” web requests. Let’s imagine a trading platform where traders can buy stock in real time. Every time a traders send an order, the system has to be sure that only one request can be in the trading thread. This to protect the integrity of the trade. To take an easy example let say, the system need 1 second to execute the order. During this 1 second all the others trade have to wait to be proceed one after another (this can be optimised but let say it is that simple for the sake of the example).
My question is how ASP.net manage concurrency and thread? If I use a lock on a sensitive part of my code, will all request created by asp.net enter the tread one after another? What is the best way to do that?
How do every threads created by ASP.net interact with each other to be sure that another one is not already in the sensitive locked part ?
I hope my question make sense, ask me if it’s not clear.
EDIT : I should precise that the orders are send via webservices and that the user is expecting an answer ( success or fail).
A:
ASP.NET really doesn't manage concurrency that much. All it does is accept requests and push them as work items to the thread pool. Eventually, the framework calls into application code.
What your app does, then, is your business. ASP.NET doesn't care. If you want to take a lock and wait, so be it. ASP.NET neither does want to know about that fact nor can it find out if it wanted to. To the system it just looks like your work items are taking quite long (because they are blocking on a lock).
There is no way to tell ASP.NET to call your trading system serially. You have to build that coordination yourself.
As you can see, synchronization inside of ASP.NET is similar to synchronization outside of ASP.NET. (I have glossed over quite a few details.)
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How to convert to System.Int32 when doing a select from a DataTable
I've got a DataTable that I've loaded from a CSV file using the KBCsv library. From what I can tell the columns are all numbers in the csv file and there aren't any null rows. I want to do a select on the data table with a query that I've created using String.Format. Here's the query:
String qry = String.Format("GRIDX = {0} AND GRIDY = {1} AND CONVERT([{2}], 'System.Int32') {3} {4}", xc, yc, _testDataColumn, _comparison, _threshold);
Where xc is a double, yc is a double, _testDataColumn is a string, _comparison is a string and _threshold is a double. The table.Select() method converts the string to:
GRIDX = 0 AND GRIDY = 4 AND CONVERT([ST DEVSSI(dBm)], 'System.Int32') = 5
I put that CONVERT in there because before I was getting a
Cannot perform '=' operation on System.String and System.Int32
error message. I've looked at this for help. I don't understand how that last column (ST DEVSSI) became a string. Am I doing the conversion correctly? Is there another way to take care of such errors?
If you run the code with the sample CSV File you should get the same error when it searches for coordinates (0, 4) so it looks like the problem is near the end of the CSV file, but I'm still not sure.
A full example of my code:
using Kent.Boogaart.KBCsv;
using Kent.Boogaart.KBCsv.Extensions;
using Kent.Boogaart.KBCsv.Extensions.Data;
using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
namespace TestCSVReader
{
public partial class MainWindow : Window
{
private String _csvFilePath;
private String _tempFilePath;
private StreamReader _streamReader;
private HeaderRecord _headerRecord = new HeaderRecord();
private Double _threshold = 5;
private String _testDataColumn = "ST DEVSSI(dBm)";
private String _comparison = "=";
private String[] coordinates = { "0,1", "0,2", "0,4", "1,1", "1,2", "1,3", "1,4"};
public MainWindow()
{
InitializeComponent();
_tempFilePath = System.IO.Path.GetTempPath() + @"\temp.csv";
_csvFilePath = "CSV FILE PATH";
using (var streamReader = new StreamReader(_csvFilePath))
{
HeaderRecord headerRecord = new HeaderRecord(streamReader.ReadLine().Split(','));
DataTable table = new DataTable();
using (var reader = new CsvReader(streamReader))
{
reader.HeaderRecord = headerRecord;
table.Fill(reader);
}
foreach (String coordinate in coordinates)
{
var xy = coordinate.Split(',');
double xc = Double.Parse(xy[0]);
double yc = Double.Parse(xy[1]);
String qry = String.Format("GRIDX = {0} AND GRIDY = {1} AND [{2}] {3} {4}", xc, yc, _testDataColumn, _comparison, _threshold);
var results = table.Select(qry);
if (results.Length > 0)
{
Console.WriteLine(String.Format("Found a match for {0}, {1}", xc, yc));
}
else
{
Console.WriteLine(String.Format("Found a match for {0}, {1}", xc, yc));
}
}
}
_streamReader.Close();
}
}
}
That sample code gives me the error above so I attempted to use a CONVERT in the query statement, but I can't seem to get it to work.
A:
There's a lot going on here, but to fix the specific problem you're reporting:
When building the query string, make sure to include a decimal point for the threshold parameter value. The simplest way is {4:f} in the format string.
The reason this works is because the CSV library you're using just makes all of the values in the data table have string types. When you filter, each value is being converted from a string to the type of the value it is being compared against. So if you compare "3" with 3, the string is converted to an integer and it works. But comparing "3.5" with 3 won't just return false, it fails because "3.5" can be converted to an integer. Comparing against a value with a decimal point will convert the string to a double instead of an integer, and then it all works.
It's going to be slow as all heck though. It's parsing strings like crazy here, and the data table is loaded into memory. There are much better approaches - like loading the CSV into a real database that has indexes.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
getting Key from collection of KeyValuePairs
I'm trying to finally get my head around LINQ, but am struggling with the following...
I have a collection of KeyValuePairs, defined as follows:
IList<KeyValuePair<int, MyCustomType>>
where the int Key of the KeyValuePair is allowed to repeat in the collection.
How do I get a collection (array, IList - I don't care) of unique keys from this collection?
I know I need to use Distinct but I'm struggling with the KeyValuePair in my collection and getting at the Key...
A:
Just:
var keys = pairs.Select(x => x.Key)
.Distinct()
.ToList();
Of course if the collection of pairs originally came from a dictionary, you can remove the Distinct() call as they'll already be distinct.
A:
list.Select(pair => pair.Key)
.Distinct()
.ToArray();
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Date periods in clojure
I have a data structure like this:
[{ :2007-08-05 [ { :meat-weight-gain 100} {:meat-weight-loss 80} {:meat-balance 20}]},
{ :2007-08-06 [ { :meat-weight-gain 10} {:meat-weight-loss 60} {:meat-balance -30}]},
{ :2007-08-07 [ { :meat-weight-gain 40} {:meat-weight-loss 80} {:meat-balance -70}]}
{ :2007-08-08 [ { :meat-weight-gain 100} {:meat-weight-loss 0} {:meat-balance 30}]}]
How can i iterate through it and return the data period of when the meat balance was negative? A sample data would be something like this:
[ {:end-period-balance -70, :period-start 2007-08-06, :period-end 2007-08-07 } ]
Other than that, can I improve my data structure or it is already ok? If yes, how? Thank you very much.
A:
i would advice you to change your data shape to a list of tuples, each containing date and map of balance data. Just like this:
(def data [[:2007-08-05 { :meat-weight-gain 100 :meat-weight-loss 80 :meat-balance 20}],
[:2007-08-06 { :meat-weight-gain 10 :meat-weight-loss 60 :meat-balance -30}],
[:2007-08-07 { :meat-weight-gain 40 :meat-weight-loss 80 :meat-balance -70}]
[:2007-08-08 { :meat-weight-gain 100 :meat-weight-loss 0 :meat-balance 30}]
[:2007-08-09 { :meat-weight-gain 19 :meat-weight-loss -20 :meat-balance -10}]])
then it would be easy to classify the periods by weight gain/loss (using partition-by) and collect needed info:
user> (let [parts (partition-by #(-> % second :meat-balance neg?) data)]
(keep #(let [[p-start _] (first %)
[p-end {balance :meat-balance}] (last %)]
(when (neg? balance)
{:period-start p-start
:period-end p-end
:end-period-balance balance}))
parts))
;;=> ({:period-start :2007-08-06, :period-end :2007-08-07, :end-period-balance -70}
;; {:period-start :2007-08-09, :period-end :2007-08-09, :end-period-balance -10})
or a list of maps including date:
(def data [{:date :2007-08-05 :meat-weight-gain 100 :meat-weight-loss 80 :meat-balance 20},
{:date :2007-08-06 :meat-weight-gain 10 :meat-weight-loss 60 :meat-balance -30},
{:date :2007-08-07 :meat-weight-gain 40 :meat-weight-loss 80 :meat-balance -70}
{:date :2007-08-08 :meat-weight-gain 100 :meat-weight-loss 0 :meat-balance 30}
{:date :2007-08-09 :meat-weight-gain 100 :meat-weight-loss 0 :meat-balance -10}])
user> (let [parts (partition-by #(-> % :meat-balance neg?) data)]
(keep #(let [{p-start :date} (first %)
{p-end :date balance :meat-balance} (last %)]
(when (neg? balance)
{:period-start p-start
:period-end p-end
:end-period-balance balance}))
parts))
;;=> ({:period-start :2007-08-06, :period-end :2007-08-07, :end-period-balance -70}
;; {:period-start :2007-08-09, :period-end :2007-08-09, :end-period-balance -10})
UPDATE
if you really need your initial data format, then you can use the same approach, just redefining values retrieval parts:
user> (defn meat-balance [rec]
(some :meat-balance (-> rec first second)))
user> (let [parts (partition-by #(-> % meat-balance neg?) data)]
(keep #(let [p-start (-> % first ffirst)
p-end (-> % last ffirst)
balance (-> % first meat-balance)]
(when (neg? balance)
{:period-start p-start
:period-end p-end
:end-period-balance balance}))
parts))
;;=> ({:period-start :2007-08-06, :period-end :2007-08-07, :end-period-balance -30})
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Canvas draw following the path
I want to do the following on a HTML5 canvas / or SVG:
Have a background path, move cursor over and draw (fill) the background path
After the user complete drawing have a callback function
My problem is that I dont have any idea how to check if the drawed line is following the path.
Can someone explain me how to do this or maybe give some tips?
http://jsbin.com/reguyuxawo/edit?html,js,console,output
function drawBgPath() {
context.beginPath();
context.moveTo(100, 20);
context.lineTo(200, 160);
context.quadraticCurveTo(230, 200, 250, 120);
context.bezierCurveTo(290, -40, 300, 200, 400, 150);
context.lineTo(500, 90);
context.lineWidth = 5;
context.strokeStyle = 'rgba(0,0,0,.2)';
context.stroke();
}
A:
Create a hidden canvas that stores the origin path as question Canvas, lets say, as #q.
Draw the question on the #c.
When user about to draw, get the pixel value from question to see whether its on a line or not.
Decide the draw color by the info above.
var mousePressed = false;
var lastX, lastY;
var ctx;
var canvas = document.getElementById('c');
var context = canvas.getContext('2d');
var canvasq = document.getElementById('q');
var contextq = canvasq.getContext('2d');
canvas.width = 500;
canvas.height = 500;
canvasq.width = 500;
canvasq.height = 500;
$('#c').mousedown(function (e) {
mousePressed = true;
Draw(e.pageX - $(this).offset().left, e.pageY - $(this).offset().top, false);
});
$('#c').mousemove(function (e) {
if (mousePressed) {
Draw(e.pageX - $(this).offset().left, e.pageY - $(this).offset().top, true);
}
});
$('#c').mouseup(function (e) {
mousePressed = false;
});
$('#c').mouseleave(function (e) {
mousePressed = false;
});
function drawBgPath() {
contextq.beginPath();
contextq.moveTo(100, 20);
contextq.lineTo(200, 160);
contextq.quadraticCurveTo(230, 200, 250, 120);
contextq.bezierCurveTo(290, -40, 300, 200, 400, 150);
contextq.lineTo(500, 90);
contextq.lineWidth = 5;
contextq.strokeStyle = 'rgba(0,0,0,.2)';
contextq.stroke();
context.drawImage(canvasq, 0, 0);
}
function Draw(x, y, isDown) {
// If not integer, getImageData will get a 2x2 region.
x = Math.round(x);
y = Math.round(y);
if (isDown) {
var pixel = contextq.getImageData(x, y, 1, 1);
// If the canvas is not draw by line, the opacity value will be 0.
var color = (pixel.data[3] === 0) ? 'red' : 'purple';
context.beginPath();
context.strokeStyle = color;
context.lineWidth = 5;
context.lineJoin = "round";
context.moveTo(lastX, lastY);
context.lineTo(x, y);
context.closePath();
context.stroke();
}
lastX = x; lastY = y;
}
drawBgPath();
Draw();
#q {
display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<canvas id="c"></canvas>
<canvas id="q"></canvas>
Another way is:
Create 2 additional canvas, for answer and question.
When mouse down, draw the path on answer first.
Then compare answer canvas with question canvas.
Draw the compared answer on the canvas for show.
I'll just demo how it can be achieve here. You can clip the draw region to improve the performance.
It's somehow hard to decide whether the path is complete or not. But you can still:
Clip the answer image by question, then compare their pixel value one-by-one.
If pixel on question has color, total + 1, if both pixel have color and color is same, count + 1.
Check if count/total is over a specific threshold.
It may be slow if the image is large, so I'd prefer to only check it when user mouseup or click a check button.
I've also tried to use .toDataURL to compare their value by string, however, its too strict and can't let you have a threshold.
var mousePressed = false;
var lastX, lastY;
var ctx;
// Question part
var qCanvas = document.createElement('canvas');
var qContext = qCanvas.getContext('2d');
var aCanvas = document.createElement('canvas');
var aContext = aCanvas.getContext('2d');
var canvas = document.getElementById('c');
var context = canvas.getContext('2d');
canvas.width = 500;
canvas.height = 500;
qCanvas.width = 500;
qCanvas.height = 500;
aCanvas.width = 500;
aCanvas.height = 500;
$('#c').mousedown(function (e) {
mousePressed = true;
Draw(e.pageX - $(this).offset().left, e.pageY - $(this).offset().top, false);
});
$('#c').mousemove(function (e) {
if (mousePressed) {
Draw(e.pageX - $(this).offset().left, e.pageY - $(this).offset().top, true);
}
});
$('#c').mouseup(function (e) {
mousePressed = false;
});
$('#c').mouseleave(function (e) {
mousePressed = false;
});
function drawBgPath() {
qContext.beginPath();
qContext.moveTo(100, 20);
qContext.lineTo(200, 160);
qContext.quadraticCurveTo(230, 200, 250, 120);
qContext.bezierCurveTo(290, -40, 300, 200, 400, 150);
qContext.lineTo(500, 90);
qContext.lineWidth = 5;
qContext.strokeStyle = 'rgb(0,0,0)';
qContext.stroke();
// Draw Question on canvas
context.save();
context.globalAlpha = 0.2;
context.drawImage(qCanvas, 0, 0);
context.restore();
// Now fill the question with purple.
qContext.fillStyle = 'purple';
qContext.globalCompositeOperation = 'source-atop';
qContext.fillRect(0, 0, qCanvas.width, qCanvas.height);
}
function Draw(x, y, isDown) {
if (isDown) {
// First draw on answer canvas
aContext.beginPath();
aContext.strokeStyle = 'red';
console.log(x, y);
aContext.lineWidth = 5;
aContext.lineJoin = "round";
aContext.moveTo(lastX, lastY);
aContext.lineTo(x, y);
aContext.closePath();
aContext.stroke();
// Compare answer with question.
aContext.save();
aContext.globalCompositeOperation = 'source-atop';
aContext.drawImage(qCanvas, 0, 0);
aContext.restore();
// Draw the result on what you want to show.
context.drawImage(aCanvas, 0, 0);
}
lastX = x; lastY = y;
}
var cv = document.createElement('canvas');
cv.width = 500;
cv.height = 500;
//document.body.appendChild(cv);
var ctx = cv.getContext('2d');
function checkAnswer() {
cv.width = 500;
cv.height = 500;
ctx.globalCompositeOperation = 'source-over';
ctx.drawImage(aCanvas, 0, 0);
ctx.globalCompositeOperation = 'destination-in';
ctx.drawImage(qCanvas, 0, 0);
var qData = qContext.getImageData(0, 0, 500, 500).data;
var aData = ctx.getImageData(0, 0, 500, 500).data;
var idx = 0, i, j;
var count = 0, total = 0;
for (i = 0; i < 500; ++i) {
for (j = 0; j < 500; ++j) {
if (qData[idx] !== 0) {
++total;
if (aData[idx] === qData[idx]) {
++count;
}
}
idx += 4;
}
}
console.log(count,total);
// Threshold.
if (count/total > 0.95) {
alert('Complete');
}
}
drawBgPath();
Draw();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<canvas id="c"></canvas>
<button onclick="checkAnswer()">check</button>
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Do probability using combination
A positive integer from one to six is to be chosen by casting a die. Thus the
elements $c$ of the sample space $C$ are $\{1,2,3,4,5,6\}$. Suppose $C_1 = \{1,2,3,4\}$ and
$C_2 = \{3,4,5,6\}$. If the probability set function $P$ assigns a probability of $1/ 6$ to each of the elements of $C$, compute $P(C_1), P(C_2), P(C_1 \cap C_2)$, and $P(C_1 \cup C_2)$.
I can compute probability straightforwardly but the question asks me for a specific format. The answer is listed as:
$${(a)\quad \left.\binom 64\middle/\binom{16}4\right.\\(b)\quad \left.\binom {10}4\middle/\binom{16}4\right.}$$
How do I get this answer using combination technique (I assume the answer is in combinatoric format? Is it a faster way?
A:
The answers are wrong. We can compucte $C_1$, $C_2$, $C_1 \cap C_2$, $C_1\cup C_2$ directly and compute its probability directly.
For example $P(C_1)=P(\{ 1,2,3,4\})=\frac23$ and it is clearly different from $\frac{\binom64}{\binom{16}4}\approx 0.00824$
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Generate different permutations/combinations in a string
I am given a string (eg "12345678").
I want to generate different combinations using +,-,*,/.
Like :
'1+2+3+4+5+6+7+8'
'1+2*3-4+5+6-7+8'
'1-2+3+4*5+6-7*8'
'1-2-3-4+5*6+7+8'
'1+2+3+4+5+6*7*8'
'1-2+3-4+5-6+7-8'
Any idea how do i generate all different combinations like above?
A:
this is one way to achieve this:
from itertools import product
numbers = "123456"
for operators in product('+-*/', repeat=len(numbers)-1):
ret = numbers[0]
for op, n in zip(operators, numbers[1:]):
ret += op+n
print(ret)
zip creates pairs of elements of two iterators. the rest is just string manipulation (and not in a very good way).
this is a little more compact (and pythonic?) with some more itertools magic:
from itertools import product, zip_longest, chain
numbers = "123456"
operators = '+-*/'
for ops in product(operators, repeat=len(numbers)-1):
print(''.join(chain(*zip_longest(numbers, ops, fillvalue=''))))
product is well documented. with zip_longest i create an iterator that will yield the pairs ('1', '+') , ('2', '*'), ... , ('6', '') (the last item is filled with the fillvalue; ops is one element shorter than numbers). the chain(*...) idiom is a simple way to flatten the tuples to get an iterator over the strings '1', '+', '2', '*', ..., '6', ''. then i simply join these strings.
if you don't like the chain(*...) part, you can replace it with chain.from_iterable(...) (this time without the * which may be a bit cleaner).
|
{
"pile_set_name": "StackExchange"
}
|
Q:
animation of progress bar using JQuery
I would like to animate the progress bar gradually. When i use for loop, the progress bar disappearing
<script type="text/javascript">
$(function() {
// Set the progressbar's initial value to 76%.
$("#progressbar1").progressbar({value:7});
// Set the progressbar's value to 18%.
$("#button1").click(function() {
$("#progressbar1").progressbar("option", "value", 18);
});
// Increment the progressbar's current value by 10%.
$("#button2").click(function() {
var val = $("#progressbar1").progressbar("option", "value");
});
// Decrement the progressbar's current value by 10%.
$("#button3").click(function() {
var val = $("#progressbar1").progressbar("option", "value");
$("#progressbar1").progressbar("option", "value", val-10);
});
});
</script>
<input id="button2" type="button" value="Progress" />
So, when i click on Button 2, the progress bar has to animate gradually.
I will be more thank full, if some one help me to load the animation when page opens with onload() function
Please help me to animate the progress bar gradually and also it should load automatically when i open the file.
Regards,
Chandru.
A:
$('#progressbar').progressbar();
$('#button2').click(function(){
makeProgress($('#progressbar'), 0, 100, 4);
});
function makeProgress(target, start, stop, steps){
var step = (stop - start)/steps;
var increment = function(){
var val = target.progressbar("value");
target.progressbar("option", "value", val + step);
if (val + step < stop) setTimeout(increment, 500);
};
increment();
}
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How can I get a left-navigation column to fill the entire left side of the middle of a webpage using CSS?
I'm working on making this web page:
http://jsfiddle.net/pW8yj/
and I want to get a left navigation area to extend all the way down the left side, from the bottom of the header to the top of the footer. I tried setting height: 100% but that didn't seem to work. Is there something I'm doing wrong here?
A:
This will never work the way you're expecting it to. You cannot set a 100% height to the element as it will go to 100% of its content, not the height of its parent container.
What I recommend doing is removing the background from the leftNAv area, and instead, set a repeating background on div id="middleArea" with the grey part as repeat-y. that way, no matter how big the #middleArea gets, the background will expand regardless.
You can try resources like Faux Columns which may give you the templates and other results you're looking for:
http://www.code-sucks.com/css%20layouts/faux-css-layouts/
Cheers.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How to define a global custom RoutedCommand?
I would like to use the same custom RoutedCommand for 2 buttons, which are in separate windows.
In order to not repeat the code, i want to define the command somewhere in the app and bind it to both buttons.
I thought of using Style to achieve that. Below, I reproduce my issue in a simple sample.
I declare the Style in App.Xaml :
<Application.Resources>
<Style TargetType="{x:Type Window}">
<Setter Property="CommandBindings">
<Setter.Value>
<!--<Window.CommandBindings>--> <!--I tried with or without this. Doesn't change-->
<CommandBinding Command="{x:Static local:App.testBindingCommand}"
Executed="OnExecuted" CanExecute="OnCanExecute" />
<!--</Window.CommandBindings>-->
</Setter.Value>
</Setter>
</Style>
</Application.Resources>
And the custom command in App.Xaml.cs :
public static RoutedCommand testBindingCommand = new RoutedCommand();
private void OnExecuted(object sender, ExecutedRoutedEventArgs e)
{
System.Windows.MessageBox.Show("OnExecuted");
}
private void OnCanExecute(object sender, CanExecuteRoutedEventArgs e)
{
System.Windows.MessageBox.Show("OnCanExecute");
e.CanExecute = true;
}
The compiler does not like the code and give an error :
error MC3080: The Property Setter 'CommandBindings' cannot be set because it does not have an accessible set accessor.
AFAIK, the Window class has a CommandBindings property.
1) Is the use of Style to declare global CommandBindings correct ? If not, how can i do ?
2) Why the property CommandBindings can't be set by the style ?
Thanks!
A:
You are getting that error message because you are setting the value of the CommandBindings property (which is of type CommandBindingsCollection) to an instance of CommandBinding. Even if the property has a setter (which it doesn't), you can't set a CommandBinding to a CommandBindingsCollection.
Consider the case of binding a command normally:
<Window>
<Window.CommandBindings>
<CommandBinding Command="{x:Static local:App.testBindingCommand}"
Executed="OnExecuted" CanExecute="OnCanExecute" />
</Window.CommandBindings>
</Window>
This isn't setting the CommandBinding to the CommandBindings property, but rather adding it to the CommandBindings collection of the Window.
Do you have to use a RoutedCommand? Maybe it would be better to use a different implementation of ICommand - maybe one that calls a delegate when the command is executed. Kent Boogaart has an implementation of DelegateCommand that could work (there are many other similar implementations floating around, too - or you could write your own).
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How reliant is the Solar System on being exactly the way it is?
We know that all objects with mass exert forces on all other objects of mass such that
$$ F = \frac{GMm}{R^2}.$$
And as others have discussed the planets do interfere with each other gravitationally to a small degree.
My question is how reliant the solar system is on its exact structure. If a planet were to change its alignment or orbit or gravitational effect on other planets, through gain of a mass through an asteroidal collision for example.
Would a deviation in the structure of the solar system as it is cause it to collapse? e.g planets change orbits significantly enough to drift away from the sun or drift into it?
A:
This is something I played with while testing a n-body code I wrote during college. Unfortunately I don't have any animations, or even the original code anymore - but I can report qualitative results.
Removing Jupiter and Saturn does indeed have a significant destabilizing effect -- an a chaotic one at that (i.e. depending on precise initial conditions, and varying on numerical accuracy) -- leading to the dynamical instability of numerous planets.
Removing the other planets had no effect on dynamical stability, but there were some small changes to periods, etc.
This result should be expected as the gravitational effects of planets other than Jupiter (and saturn to a lesser degree) are almost entirely negligible on the dynamics of other planets.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Should I use FOR UPDATE in SELECT subquery here DELETE FROM table WHERE id = any(array(SELECT id FROM table WHERE ... LIMIT 100))
I know if I use ctid I should use FOR UPDATE in sub-query because row can be updated by another transaction while my transaction tries to delete it. As result this row will not be deleted. The right way:
DELETE FROM table WHERE ctid = any(array(
SELECT ctid
FROM table
WHERE ...
LIMIT 100
FOR UPDATE));
If I use primary key same way should I need to use FOR UPDATE in SELECT sub-query? If not, why not?
DELETE FROM table WHERE id = any(array(
SELECT id
FROM table
WHERE ...
LIMIT 100
FOR UPDATE));
A:
The same could happen with the primary key, although I'd expect it to happen less often (primary keys should not change).
But you need that FOR UPDATE not only because the row could be modified: without it, the subquery would also see rows that are being deleted by a concurrent statement, and which will prove non-existent when you try to delete them.
Finally, it would be a good thing to have an ORDER BY in the subquery that can use an index. Then all such queries will try to lock rows in the same order, which reduces the likelihood of deadlocks.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Export kyr key of Domino server to PEM or PKCS12
A Lotus Domino is configured for SSL. How to export his certificat (stored in keyring files with .kyr extension).
This means that I need an SSL certificate for the Domino website on the AN OTHER server (like a reverse proxy)
My problem is almost the same as the one exposed in http://labs.groupwave.be/index.php/2009/08/31/exporting-kyr-certificate-for-apache/
I've also read:
http://www-01.ibm.com/support/docview.wss?rs=463&context=SSKTMJ&q1=export+ssl+certificate&uid=swg21097215&loc=en_US&cs=utf-8&lang=en
which explains that it's not possible.
So it works or not ? Maybe am I confusing private key and public key ? Do I need the private key or the public is sufficient on the other server?
A:
So for who google here...
The best way to know "if it works?" is "try and trust yourself!".
So yes! It works! Many credits to http://labs.groupwave.be/index.php/2009/08/31/exporting-kyr-certificate-for-apache/
the OTHER server needs the private key! (BTW simple sense of logic if anyone with your public certificate could do the trick it would mean no security)
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Drawing circles and writing text on them using d3 in javascript
I am a new javascript programmer. I am trying to make a visualization component in which I have to draw a circle and write something on it ("basically a single letter on every circle") the code is as follows
var svgcontainer = d3.select("body").append("svg")
.attr("width",width)
.attr("height",height);
d3.json("real.json",function(json){
var elem = svgcontainer.selectAll("div")
.data(json.residues);
var elemEnter = elem.enter()
.append("g");
var circle = elemEnter.append("circle")
.attr("cx",50)
.attr("cy",50)
.attr("r",10)
.style("fill","red");
elemEnter.append("text")
.attr("dx",-20)
.text(function(d){return d.name});
}) ;
The code is drawing circles but not writing any letters on them. the json example file is as follows
{
"residues":[
{"name":"A","mut":[
{"what":"A1H","type":"non-neutral"}
]},
{"name":"H"}
]}
Please help me fix the code to draw a circle and write a letter on it.
A:
var svgcontainer = d3.select("body").append("svg")
.attr("width", 200)
.attr("height",200);
//d3.json("real.json",function(json){
var json = {
"residues":[
{"name":"A","mut":[
{"what":"A1H","type":"non-neutral"}
],"cx": 50,"cy":50, "r":20},
{"name":"H","cx": 90,"cy":80, "r":20}
]};
var elem = svgcontainer.selectAll("div")
.data(json.residues);
var elemEnter = elem.enter()
.append("g");
var circle = elemEnter.append("circle")
.attr("cx",function(d){ return d.cx;})
.attr("cy",function(d){ return d.cy;})
.attr("r",function(d){ return d.r;})
.style("fill","red");
elemEnter.append("text")
.attr("dy", function(d){
return d.cy+5;
}).attr("dx",function(d){ return d.cx-5;})
.text(function(d){return d.name});
//}) ;
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script>
var circle = elemEnter.append("circle")
.attr("cx",50)
.attr("cy",50)
.attr("r",10)
.style("fill","red");
Don't use static values to set cx, cy and r values of circle, using static values will set all the circle to be in one position, we can't see all the circles only circle will be visible.
elemEnter.append("text")
.attr("dx",-20)
.text(function(d){return d.name});
Here also we are setting dx value of text with -20, negative value will take the element out of svg, so we can't see the text, try to set the dx and dy values of text according to circle cx and cy values this will set both together.
I made all the changes,
Hope you got it.
If not ask me for more.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Remove not closed html elements from end of text
I want to remove all elements which are not closed properly at the end of content e.g in below test
commodi consequatur? Quis autem vel eum iure reprehenderit qui in ea
voluptate velit esse quam nihil molestiae consequatur,
vel illum qui dolorem eum fugiat quo voluptas nulla
pariatur? <a rel="nofollow" class="underline"
I want to remove
<a rel="nofollow" class="underline"
or elements without closing tags
<h2>sample text
or any other html element which is not closed properly at the end.
A:
I have written a function that should do what you want. The idea is to first replace all valid tag-sequences with a #### pattern. Then a regular expression removes everything from the first < till the end of the string. After that, the valid tag-sequences are put back to the buffer (if that part has not been removed due to invalid tag before that part).
Too bad, I can't add a codepad because recursive regular expressions seems not to be supported by the PHP version used by codepad. I've tested this with PHP 5.3.5.
PHP
function StripUnclosedTags($input) {
// Close <br> tags
$buffer = str_ireplace("<br>", "<br/>", $input);
// Find all matching open/close HTML tags (using recursion)
$pattern = "/<([\w]+)([^>]*?) (([\s]*\/>)| (>((([^<]*?|<\!\-\-.*?\-\->)| (?R))*)<\/\\1[\s]*>))/ixsm";
preg_match_all($pattern, $buffer, $matches, PREG_OFFSET_CAPTURE);
// Mask matching open/close tag sequences in the buffer
foreach ($matches[0] as $match) {
$ofs = $match[1];
for ($i = 0; $i < strlen($match[0]); $i++, $ofs++)
$buffer[$ofs] = "#";
}
// Remove unclosed tags
$buffer = preg_replace("/<.*$/", "", $buffer);
// Put back content of matching open/close tag sequences to the buffer
foreach ($matches[0] as $match) {
$ofs = $match[1];
for ($i = 0; $i < strlen($match[0]) && $ofs < strlen($buffer); $i++, $ofs++)
$buffer[$ofs] = $match[0][$i];
}
return $buffer;
}
$str = 'commodi consequatur? Quis autem vel eum iure reprehenderit qui in ea voluptate '
.'velit esse<br> quam nihil molestiae consequatur, vel illum qui dolorem eum '
.'fugiat quo voluptas nulla pariatur? '
.'<a href="test">test<p></p></a><span>test<p></p>bla';
var_dump(StripUnclosedTags($str));
Output
string 'commodi consequatur? Quis autem vel eum iure reprehenderit qui in ea
voluptate velit esse<br/> quam nihil molestiae consequatur,
vel illum qui dolorem eum fugiat quo voluptas nulla
pariatur? <a href="test">test<p></p></a>' (length=226)
|
{
"pile_set_name": "StackExchange"
}
|
Q:
C++ Reading text file line by line
I want to read a txt file and I want to process each number on the line one by one, apply some functions and pass to the other line. When the line is over, I don't know how to apply the same operations to the lines below. Methods will get a different output from each line that is why I have to handle each line separately.
int number;
ifstream readingFile("a.txt");
while(readingFile >> number){
/* Methods will be applied to each number in the line */
}
readingFile.close();
a.txt
23 4 555
2123 44 21 4
1 45 667 2 112
A:
Working C++ Code
To clear doubts Test it in https://www.tutorialspoint.com/compile_cpp11_online.php
Just copy-paste execute
#include <iostream>
#include <string>
#include <sstream>
#include <fstream>
int main ()
{
//code create a file with numbers
std::ofstream myfile;
myfile.open ("file.txt");
myfile << "123 12 32323\n 4444 55 535\n";
myfile.close();
std::ifstream input( "file.txt" );
for( std::string eachLine; getline( input, eachLine ); )
{
std::istringstream strm(eachLine);
std::string splitedLines;
// loop for each string and add to the vector
while ( strm >> splitedLines )
{
std::stringstream geek(splitedLines);
int num; // can be int, float or double
geek >>num;
//perform action on all num in each line one by one
std::cout<<num<<std::endl;
}
}
return 0;
}
Edit: PythonCode read numbers one by one in each line
fileName = open('a.txt', 'r')
line = fileName.readline() //reading first line
while(line):
for eachStringNumber in line.split():
number = int(eachStringNumber)
/// Methods will be applied to each number in the line ///
line = fileName.readline() // reading lines one by one in each loop
fileName.close()
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Changing lower limits integral.
$\displaystyle\int_2^\infty\dfrac1{(x-1)^3}\,\mathrm dx\quad$ Let $u=x-1 \\ \mathrm du=\mathrm dx$
$\displaystyle=\int_1^\infty\dfrac{\mathrm du}{u^3}=\lim_{R\to\infty}\int_1^R\dfrac{\mathrm du}{u^3} \\\displaystyle
=\lim_{R\to\infty}\dfrac{-1}{2u^2}\Bigg|_1^R=\lim_{R\to\infty}\left(\dfrac12-\dfrac1{2R^2}\right)=\dfrac12$
This is a suggested solution to the integral (line $1$). Why do they change the lower limit at line $2$ from $2$ to $1$?
A:
Since $u=x-1$, the lower bound is $x=2$, so $u=1$. The upper bound is $\infty-1=\infty$.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
React Native Navigator custom button onPress
I'm using react-native-navigation as my navigation in an app and I have used the left / right button option (static navigatorButtons) to implement some buttons on each side of the navbar which I can use with onNavigatorEvent(event) and check which one was pressed with event.id
Those work fine but now I have added some custom buttons in the middle using a component (Custom Bar). The issue is I have no idea how to detect onPress of those buttons. The onNavigatorEvent(event) doesn't seem to detect them and not sure how to do this.
Basically I want to display listA if leftButton is pressed or listB if rightButton is pressed but don't know how to listen to the onPress event
Custom Bar
import stuff needed
export default class TopBar extends Component {
constructor(props) {
super(props);
this.state = {
leftPressed: true,
rightPressed: false
};
this.leftButton = this.leftButton.bind(this);
this.rightButton = this.rightButton.bind(this);
}
leftButton(){
this.setState({
leftPressed: true,
rightPressed: false
})
}
rightButton(){
this.setState({
leftPressed: false,
rightPressed: true
})
}
render() {
return (
<View style={Styles.container}>
<View style = {[Styles.wrapper, {borderTopLeftRadius: 20, borderBottomLeftRadius: 20}]}>
<TouchableOpacity style={[Styles.button, {alignSelf: 'flex-start'}]} onPress={ this.leftButton }>
<Text style={[Styles.text, this.state.leftPressed && Styles.textSelected]}>All Tasks</Text>
</TouchableOpacity>
</View>
<View style = {[Styles.wrapper, {borderTopRightRadius: 20, borderBottomRightRadius: 20}]}>
<TouchableOpacity style={[Styles.button, {alignSelf: 'flex-start'}]} onPress={ this.rightButton }>
<Text style={[Styles.text, this.state.rightPressed && Styles.textSelected]}>My Tasks</Text>
</TouchableOpacity>
</View>
</View>
);
}
}
Main Screen
import other stuff needed
import TopBar from '../_shared/components/TopBar';
Navigation.registerComponent('task.TopBar', () => TopBar);
class TaskListComponent extends BaseView {
static navigatorButtons = {
rightButtons: [
{
id: 'Filter',
icon: require('../_shared/components/Images/tune.png'),
},
{
id: 'Search',
icon: require('../_shared/components/Images/search.png'),
}
],
leftButtons: [
{
id: 'Create',
icon: require('../_shared/components/Images/plus.png'),
},
]
}
constructor(props) {
super(props);
this.props.navigator.setOnNavigatorEvent(this.onNavigatorEvent.bind(this));
this.state = {
tasklist: props.TaskList || null
};
onNavigatorEvent(event) {
if (event.type == 'NavBarButtonPress') {
if (event.id == 'Create') {
this.createTask()
}
if (event.id == 'Search') {
this.searchTask()
}
if (event.id == 'Filter') {
this.filterTask()
}
}
}
//code for the left/right buttons goes here
componentDidMount() {
this.props.navigator.setStyle({
navBarCustomView: 'task.TopBar',
navBarComponentAlignment: 'center',
});
}
render() {
if (TopBar leftPressed true) { //I know this is wrong just explaining the logic
return (
<View>
//some stuff
</View>
);
} else {
return (
<View>
//other stuff
</View>
)
}
}
}
A:
When a button is pressed, dispatch a DeepLink and handle the link in the screen. You can dispatch DeepLink statically for example:
Navigation.handleDeepLink({link: 'button1Pressed'});
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Stuck on Download Pending in Play Store after Updating to Lollipop
Good day, as the title states, whenever I download an app from the Play Store, it just says Download Pending.
There is no queued apps being downloaded. I tried the force stop, clear cache, clear data and uninstall updates of Play store and Download Manager, restarted the phone, but still no luck.
One thing I notice is that when I revert it to the factory version, I managed to download an app, but when I tried to download another, it just says Error 907. When I opened the Play Store, it's the latest version again.
I think its in the version, but I'm hoping for other fixes to this
Phone - Cherry Mobile Flare S3
OS - Lollipop
Google Play Store Version - 7.3.07.K-all [0] [PR] 139935798
A:
You need to clear the Play Store data following these instructions.
From the Settings app, choose Apps.
Choose Google Play Store from the list of apps. A new screen will appear.
Click Force Stop.
Click Storage and then Clear data.
At the top right, click the three dots, then Click Uninstall updates to revert to the original version of Play Store that came with the phone.
Follow the same instructions again for the Google Play Services app, but this time use Clear cache instead of Clear data.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
PHP mysql multiple inner join
I am trying to use two inner join as foreign key.
Actually, I have transaction table and this table will be inner join customer and product.
When I make SQL, it occurs error, 'You have an error in your SQL syntax'.
Could you check my SQL syntax for php mysql?
I cannot find error on my eye.
Please help me, and thanks.
$sql = mysql_query("SELECT T.transactionId, P.product_name, P.product_price, P.stock, C.firstName, C.address, C.postCode " +
"FROM transaction T " + "INNER JOIN customer C ON T.customerId = C.customerId " +
"INNER JOIN product P ON T.productId = P.productId");
A:
It looks like you are using a plus sign instead of a period to concatenate your sql query.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How do I change a property of a control several times during a loop in C#
I'm trying to do something like this:
int i;
while(true)
{
label1.Text = i.ToString();
i++;
Thread.Sleep(500);
}
(in reality I'm trying to do something more complex and that makes more sense but this is a simple example of my problem)
I'm expecting that the text of the lable changes each 1/2 seconds..but it is getting stuck.
Thanks you
A:
You can't make the GUI-Thread sleep (Because than the GUI wont respond) (And I'm saying that even though I like sleeping * A LOT *).
Consider one of the following alternatives:
Running this code on a separate thread
Creating a timer with 500 as an interval
Some sort of binding
A:
Sleeping the UI thread makes things worse, as it can't respond to "paint" events until it has finished your method.
The most appropriate option here is a timer, doing a bit of work on each tick.
A lazy and deeply flawed approach is to add Application.DoEvents() - I only mention this to allow me to say DON'T DO THIS!!!
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How to get ALL logs from Chrome console using Protractor?
I want to get all logs from Chrome console using Protractor. I set up next preferences in my Protractor config file:
capabilities: {
loggingPrefs: {
'browser': 'ALL'
}
}
But I get only INFO level logs. And next command returns 'INFO' instead of 'ALL':
browser.driver.manage().logs().get('browser').then(function (entries) {
var pLogs = entries.filter(function (entry) {
console.log("entry level name = ", entry.level.name);
});
});
How can I get ALL log entries? Thank you.
A:
There is an open issue with a workaround inside at Protractor github issue tracker:
loggingPrefs not respected - always INFO logging
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Mongoid self reference with properties for users friendships status
Using Mongo and Rails, I would to build a friendship system like facebook:
- Before making the friendship, the use must accept the friendship request
I found a lots of code to do the relationship but never with a relation's property...
Do you have any idea or clue how to do that to be "respectful" of the NoSQL concept
Thank you for your help
A:
Just use two models, something like this:
class User
include Mongoid::Document
has_many :friendships
end
class Friendship
include Mongoid::Document
belongs_to :owner, :class_name => "User"
belongs_to :friend, :class_name => "User"
field :pending, :type => Boolean, :default => true
end
Does it sound good? Hope this helps!
A:
I had to put in my User model:
has_many :friendships, :inverse_of => :owner
Check out associations in the documentation http://mongoid.org/en/mongoid/docs/relations.html#common
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How do i properly add an element into an array depending on the elements have values or not in php
I'm trying to do something as below :
$location1 = (isset($_POST['location1'])) ? $_POST['location1'] : null ;
$location2 = (isset($_POST['location2'])) ? $_POST['location2'] : null ;
$locations = array($location1, $location2);
print_r($locations);
here print_r($locatios) showing Array ( [0] => location1 [1] => ) , an unnecessary index is being created if $location2 is null. I want if $location2 is null then i get just Array ( [0] => location1)
A:
I think if statement will be better in this case.
$locations = array();
if (isset($_POST['location1'])) {
$locations[] = $_POST['location1'];
}
if (isset($_POST['location2'])) {
$locations[] = $_POST['location2'];
}
|
{
"pile_set_name": "StackExchange"
}
|
Q:
cannot drag and drop calender extender and other ajax controller in content page
Before i added a script manager in my masterpage to display a slideshow image,ajax controller works fine in my content page.Now i cannot drag and drop ajax controller to my content child page even i have removed the script manager.
and i have register ajax reference in content page
Blockquote
##<%@ Register assembly="AjaxControlToolkit" namespace="AjaxControlToolkit.HTMLEditor" tagprefix="asp" %> ##
http://helpme.come
Please guide me the correct way to achieve my objective.
A:
Try this
Tool -> Import Export Setting -> Reset All Settings -> All Settings (This Option is in Visual Studio 2012 Only) -> Finish.
2010 it Will Be -> No, just Reset settings, override my current settings -> General Development Setting -> Finish
Reference Ajax Dll again it will work.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
setting up virtual host on windows apache
I need help configuring virtual hosts in apache on Windows.
I have the following in my hosts file:
127.0.0.1 ebdowns
in httpd-vhosts.conf I have made the following entries:
NameVirtualHost *:80
<VirtualHost 127.0.0.1>
DocumentRoot "C:\wamp\www\"
ServerName localhost
</VirtualHost>
<VirtualHost www.ebdowns>
DocumentRoot "C:\wamp\www\ebdowns"
ServerName www.ebdowns
ServerAlias www.ebdowns
<Directory "C:\wamp\www\ebdowns">
Options Indexes FollowSymLinks Includes ExecCGI
AllowOverride All
Order allow,deny
Allow from all
</Directory>
</VirtualHost>
I try to restart apache but with these entries it won't restart. If I remove the first block the server restarts but then when I enter www.ebdowns into my browser it can't find the site located there
Can anyone help let me know where I've gone wrong please
Thanks
A:
The IP:PORT pattern in your NameVirtualHost directive must be identical to the one you use in your VirtualHost blocks.
So in your case:
NameVirtualHost *:80
<VirtualHost *:80>
ServerName Localhost
# first virtual host directives
</VirtualHost>
<VirtualHost *:80>
ServerName ebdowns
ServerAlias www.ebdowns
# second virtual host directives
</VirtualHost>
It's all explained in the documentastion. You should read it.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Query to get records from table on basis of one field and to check that if the field is not -1
I have a table named Documents, with the fields Document_ID(primary key) and Cluster_ID , now i want all the Document_ID that have same Cluster_ID, on basis on Document_ID (passed as parameter), default value of Cluster_ID is '-1'.
eg: dbo.Documents
Document ID ******** Cluster_ID
- 1****************** -1
- 2****************** 1001
- 3****************** 1001
- 4****************** -1
- 5****************** 1002
- 6****************** 1001
- 7****************** -1
- 8****************** -1
- 9****************** -1
now,
if Document_ID is 2 then i want result as rows with Document_ID=2,3,6 , here i am not able to handle records with cluster_ID=-1;(because -1 id default value to the table and there are hundreds of matching records in table)
i tried a query mentioned below which is working fine but when i execute the query for Document_ID=7 it will return 5 rows with cluster_ID=-1,
SELECT d2.*
FROM dbo.Documents d1
join dbo.Documents d2 on d1.Cluster_ID=d2.Cluster_ID
WHERE d1.Document_ID =2
my issue is:
It is returning all the rows from table which has Cluster_ID=-1, what i want is, If Cluster_ID=-1,return single row else return all rows with the same cluster_ID
A:
Try this query
SELECT
Document_ID,
Cluster_ID
FROM Documents
WHERE Cluster_ID =
(
SELECT
Cluster_ID
FROM Documents
WHERE Document_ID = @Document_ID
)
AND Cluster_ID <> -1
UNION
SELECT
Document_ID,
Cluster_ID
FROM Documents
WHERE Document_ID = @Document_ID
AND Cluster_ID = -1
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Wrapping tag - only partially working
From various SO answers and random web searches (e.g. https://www.sitepoint.com/everything-need-know-html-pre-element), it seems wrapping a long word in a <pre> tag using the CSS can be achieved with a combination of:
CSS white-space property
CSS overflow-wrap property
Example CSS:
pre {
/* Whitespace preserved. Text wraps when necessary, and on line breaks. */
white-space: pre-wrap;
/* normally unbreakable words may be broken at arbitrary points. */
overflow-wrap: break-word;
}
This works, but only wraps one line. Pop over to https://jsonschema.net to see this problem in action.
$id properties can get long very quickly (do this quickly by adding a long Root ID and just submitting the default JSON).
Inspecting the DOM shows the correct CSS applied to the <pre> tag container:
The long string is wrapping, but only where a line break occurs. How can I ensure it wraps beyond one line?
A:
Credit for this answer should go to @stephen-p since their comment resolved my issue. I'm only answering my own question because comments are easily missed:
Yes, or try adding word-break: break-all; and see if that's what you
want. See word-break and especially the Note where it compares it to
overflow-wrap
So word-break: break-all; was all I needed.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Flex box aligment, try to combine 'stretch' on parent and 'center' on one child
I have the code below and the following issues:
I need that all the children of .lt to get the biggest height.(see red border on firs .lt}. for that I use align-items: stretch;
I need the content of the element .left to be v/h center. So I use align-self:center; but this cancel the stretch. (the red border is reduced)
I need the .right elements to be aligned left and top.
.container {
display: flex;
flex-direction:column;
}
.lt{
align-items: stretch;
border: 1px solid #e3e3e3;
display: flex;
margin-bottom: 1.5rem;
}
.left {
border-right: 1px solid red;
flex: 0 0 90px;
padding: 8px;
align-self:center;
justify-content: center;
}
.right {
justify-self: flex-start;
}
<div class="container">
<div class="lt">
<div class="left">
<a href="">
<img src="https://via.placeholder.com/75"/>
abcd
</a>
</div>
<div class="right">
dable English. Many desktop publishing packages and web page editors now use Lorem Ipsum as their default model text, and a search for 'lorem ipsum' will uncover many web sites still in their infancy. Various versions have evolved over the years, sometimes by accident, sometimes on purpose (injected humour and the like).
the years, sometimes by accident, sometimes on purpose (injected humour and the like).
</div>
</div>
<div class="lt">
<div class="left">
<a href="">
<img src="https://via.placeholder.com/75"/>
abcd
</a>
</div>
<div class="right">
dable English. Many desktop publishing packages and web page editors now use Lorem Ipsum as their default mode
</div>
</div>
</div>
A:
You can use a simple gradient to replace the border since you know the width of the image thus you can place it correctly:
.container {
display: flex;
flex-direction: column;
}
.lt {
align-items: stretch;
border: 1px solid #e3e3e3;
display: flex;
margin-bottom: 1.5rem;
background:
linear-gradient(red,red) 105px 0/1px 100% no-repeat;
}
.left {
flex: 0 0 90px;
padding: 8px;
align-self: center;
text-align:center;
}
<div class="container">
<div class="lt">
<div class="left">
<a href="">
<img src="https://via.placeholder.com/75" /> abcd
</a>
</div>
<div class="right">
dable English. Many desktop publishing packages and web page editors now use Lorem Ipsum as their default model text, and a search for 'lorem ipsum' will uncover many web sites still in their infancy. Various versions have evolved over the years, sometimes
by accident, sometimes on purpose (injected humour and the like). the years, sometimes by accident, sometimes on purpose (injected humour and the like).
by accident, sometimes on purpose (injected humour and the like). the years, sometimes by accident, sometimes on purpose (injected humour and the like).
</div>
</div>
<div class="lt">
<div class="left">
<a href="">
<img src="https://via.placeholder.com/75" /> abcd
</a>
</div>
<div class="right">
dable English. Many desktop publishing packages and web page editors now use Lorem Ipsum as their default mode
</div>
</div>
</div>
Or simply use nested flexbox container. Keep the first one stretched and center content inside it:
.container {
display: flex;
flex-direction: column;
}
.lt {
align-items: stretch;
border: 1px solid #e3e3e3;
display: flex;
margin-bottom: 1.5rem;
}
.left {
flex: 0 0 90px;
padding: 8px;
border-right:1px solid red;
display:flex;
flex-direction:column;
justify-content: center;
text-align:center;
}
<div class="container">
<div class="lt">
<div class="left">
<a href="">
<img src="https://via.placeholder.com/75" /> abcd
</a>
</div>
<div class="right">
dable English. Many desktop publishing packages and web page editors now use Lorem Ipsum as their default model text, and a search for 'lorem ipsum' will uncover many web sites still in their infancy. Various versions have evolved over the years, sometimes
by accident, sometimes on purpose (injected humour and the like). the years, sometimes by accident, sometimes on purpose (injected humour and the like).
by accident, sometimes on purpose (injected humour and the like). the years, sometimes by accident, sometimes on purpose (injected humour and the like).
</div>
</div>
<div class="lt">
<div class="left">
<a href="">
<img src="https://via.placeholder.com/75" /> abcd
</a>
</div>
<div class="right">
dable English. Many desktop publishing packages and web page editors now use Lorem Ipsum as their default mode
</div>
</div>
</div>
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Geocoder initialization fails
I am getting a NullPointerException when trying to declare the Geocoder in my application. I have the following declaration :
public class MainActivity extends Activity {
private Geocoder geocoder = new Geocoder(this, Locale.getDefault());
...
}
I get the following LogCat :
03-20 10:48:55.729: D/AndroidRuntime(604): Shutting down VM
03-20 10:48:55.729: W/dalvikvm(604): threadid=1: thread exiting with uncaught exception
(group=0x40a71930)
03-20 10:48:56.209: E/AndroidRuntime(604): FATAL EXCEPTION: main
03-20 10:48:56.209: E/AndroidRuntime(604): java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.example.coord/com.example.coord.MainActivity}: java.lang.NullPointerException
03-20 10:48:56.209: E/AndroidRuntime(604): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2106)
03-20 10:48:56.209: E/AndroidRuntime(604): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2230)
03-20 10:48:56.209: E/AndroidRuntime(604): at android.app.ActivityThread.access$600(ActivityThread.java:141)
03-20 10:48:56.209: E/AndroidRuntime(604): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1234)
03-20 10:48:56.209: E/AndroidRuntime(604): at android.os.Handler.dispatchMessage(Handler.java:99)
03-20 10:48:56.209: E/AndroidRuntime(604): at android.os.Looper.loop(Looper.java:137)
03-20 10:48:56.209: E/AndroidRuntime(604): at android.app.ActivityThread.main(ActivityThread.java:5041)
03-20 10:48:56.209: E/AndroidRuntime(604): at java.lang.reflect.Method.invokeNative(Native Method)
03-20 10:48:56.209: E/AndroidRuntime(604): at java.lang.reflect.Method.invoke(Method.java:511)
03-20 10:48:56.209: E/AndroidRuntime(604): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
03-20 10:48:56.209: E/AndroidRuntime(604): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
03-20 10:48:56.209: E/AndroidRuntime(604): at dalvik.system.NativeStart.main(Native Method)
03-20 10:48:56.209: E/AndroidRuntime(604): Caused by: java.lang.NullPointerException
03-20 10:48:56.209: E/AndroidRuntime(604): at android.content.ContextWrapper.getApplicationContext(ContextWrapper.java:109)
03-20 10:48:56.209: E/AndroidRuntime(604): at com.example.coord.MainActivity.<init>(MainActivity.java:21)
03-20 10:48:56.209: E/AndroidRuntime(604): at java.lang.Class.newInstanceImpl(Native Method)
03-20 10:48:56.209: E/AndroidRuntime(604): at java.lang.Class.newInstance(Class.java:1319)
03-20 10:48:56.209: E/AndroidRuntime(604): at android.app.Instrumentation.newActivity(Instrumentation.java:1054)
03-20 10:48:56.209: E/AndroidRuntime(604): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2097)
Line 21 is my Geocoder declaration. What is wrong with my code?
A:
The context is only available when the activity is started so you cannot initialize the geocoder in the class body. Try to initialize it in the onCreate or onResume method instead...
public class MainActivity extends Activity {
private Geocoder mGeocoder;
@Override
protected void onCreate(Bundle _icicle) {
super.onCreate(_icicle);
mGeocoder = new Geocoder(getApplicationContext(), Locale.getDefault());
}
}
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Drawing something on my LinearLayout?
I'm extending LinearLayout:
public class MyLinearLayout extends LinearLayout {
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
Paint paint = new Paint();
paint.setColor(0xFFFF0000);
canvas.drawLine(0, 0, getWidth(), getHeight(), paint);
}
}
If the layout has child elements, shouldn't the red line above be drawn on top of them? Considering a layout like:
<MyLinearLayout>
<ImageView />
</MyLinearLayout>
I'd expect to get the red line drawn above the child ImageView. But it gets drawn below it. I was assuming all child drawing would have been completed after the super.onDraw() line is finished.
Is there a way to get to the canvas and draw something on it after all child drawing has been completed?
Thanks
A:
Layouts don't draw unless you call setWillNotDraw(false);. They do that for efficiency reasons.
EDIT:
onDraw() really is meant to just allow you to modify the Canvas before the drawing operation happens. It doesn't actually draw. What you want to do is override draw() like so:
@Override
protected void draw(Canvas canvas) {
super.draw(canvas);
Paint paint = new Paint();
paint.setColor(0xFFFF0000);
canvas.drawLine(0, 0, getWidth(), getHeight(), paint);
}
Calling the super will draw all the children in the view. Then it will draw all the lines. I do still believe you need setWillNotDraw(false) to be called though.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Is a finitely generated torsion-free module over a UFD necessarily free?
Is a finitely generated torsion-free module over a unique factorization domain necessarily free ?
A:
No. Consider for example the polynomial ring over a field in two variables $R=K[x,y]$. $R$ is a UFD. Now consider the ideal $I=(x,y)$ generated by $x$ and $y$. It is easy to show that $I$ is not a free $R$-module, but it certainly is finitely generated and torsion-free.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
MPAndroidChart - How to add Annotations or images to the chart
I am currently working with the latest MPAndroidChart Library and am looking for a way to add annotations or images that would be clickable.
Example: once data reaches a certain value an event occurs that I want to be able to display to the user - there a multiple events that can occur so the annotations (not sure if that is the right word) or image could be added at any point in the chart.
Any pointers welcome.
A:
In order to get this to work I downloaded the source code after implemented the features myself by allow a bitmap image be displayed along side the limit line.
Thanks to Philipp Jahoda for the help and for the library.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
General Relativistic Boltzmann Equation Verification
Let $(M,g)$ be a (pseudo)Riemannian manifold. Define on $TM$ the symplectic 2-form $\omega=dx^\mu\wedge dp_\mu$ and use $g$ to define the pull back $\omega_g=dx^\mu\wedge d(g_{\mu\nu}p^\nu)$. Define $$L=\frac{1}{2}g_{\mu\nu}p^\mu p^\nu$$
And the vector field $X_g$ by
$$\iota_{X_g}\omega_g=dL$$
where $\iota$ is the interior product. The solution is
$$X_g=p^\mu\frac{\partial}{\partial x^\mu}-\Gamma_{\alpha\beta}^\mu p^\alpha p^\beta\frac{\partial}{\partial p^\mu}$$
and I wish to verify this. The symplectic form is, using
$$d=dx^\mu\wedge\frac{\partial}{\partial x^\mu}+dp^\mu\frac{\partial}{\partial p^\mu}$$
$$d(g_{\mu\nu}p^\nu)=dg_{\mu\nu} p^\nu+g_{\mu\nu}dp^\nu=\frac{\partial g_{\mu\nu}}{\partial x^\alpha}p^\nu dx^\alpha+g_{\mu\nu}dp^\nu$$
$$\omega_g=\frac{\partial g_{\mu\nu}}{\partial x^\alpha}p^\nu dx^\mu\wedge dx^\alpha+g_{\mu\nu}dx^\mu\wedge dp^\nu=\frac{\partial g_{\mu\nu}}{\partial x^\alpha}p^\nu dx^\mu\wedge dx^\alpha$$
the last term vanishes because of symmetry properties. Now the problem is that when I contract $X_g$ and $\omega_g$ I encounter terms like $$dx^\alpha\left(\frac{\partial}{\partial p^\mu}\right)$$
that I have no clue what to do with. This makes me think I have done something wrong in the above calculation.
Thanks in advance.
EDIT: My calculation for $dL$ is
$$dL=\frac{1}{2}\frac{\partial g_{\alpha\beta}}{\partial x^\mu}p^\alpha p^\beta dx^\mu+g_{\mu\nu}p^\mu dp^\nu$$
Curiously, if $g_{\mu\nu}dx^\mu\wedge dp^\nu\ne 0$, then the following happens when it collides with the first term in $X_g$:
$$g_{\mu\nu}dx^\mu\wedge dp^\nu\left(p^\delta\frac{\partial}{\partial x^\delta}\right)=g_{\delta\nu}p^\delta dp^\nu$$
which is a term in $dL$. This makes me think that $\ne 0$ is appropriate and that $dx^\mu\wedge dp^\nu$ is not antisymmetric. Maybe that's just a coincidence and I screwed up somewhere else.
A:
Contract the equation $\iota_X \omega=dL$ with some vector $Y$ to get
$$\omega(X,Y)=Y(L)$$
Let bars denote momentum coordinates. Then expand $Y$ in bundle coordinates as
$$Y=y^\mu\partial_\mu+\bar y^\mu\bar\partial_\mu$$
The left of the first equation is
$$Y(L)=\frac{1}{2}y^\mu p^\alpha p^\beta\partial_\mu g_{\alpha\beta}+\bar y^\mu g_{\mu\nu} p^\nu$$
You calculate $\omega$ correctly:
$$\omega=\partial_\alpha g_{\mu\nu}p^\nu\,dx^\mu\wedge dx^\alpha+g_{\mu\nu}\,dx^\mu\wedge dp^\nu$$
Now contract with both $X$ and $Y$ to get $Y(L)$ while respecting $dx(\bar\partial)=0$ and $dp(\partial)=0$.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How can I buy an older version of Keynote that's compatible with 10.8?
My work computer can't be upgraded to 10.9 yet, so I'm stuck on 10.8 for now. I've never used Keynote, but one of my coworkers wants to use it for a presentation we have to give. I just tried to buy it, but I'm getting an error that the current version (6.0) isn't compatible with 10.8. How can I buy an older version of Keynote that's 10.8-compatible?
A:
I presume that you're trying to purchase iWork from the App Store.
You can purchase a physical copy of iWork '09 and install it.
If your Mac doesn't have a disc drive, you can use Remote Disk to do so. You'll need access to another computer (either Mac or Windows) that has a disc drive. Apple has complete directions for using Remote Disk here.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Why does my React form auto-refresh the page even if I put "event.preventDefault()" on handleSubmit?
I have two files which work together to render things. The first is App.js, which first renders Form.js. The form will then collect information, which on submission, changes the Form state and calls a function from App.js. This function is called "createProject." Calling "createProject" in Form.js "handleSubmit" makes the page auto-refresh. However, if I remove "createProject" from handleSubmit, the page does not auto-refresh. Here are the two files.
import React, { Component } from "react";
import Project from "./components/Project.js"
import Form from "./Form.js";
class App extends Component {
constructor(props) {
super(props);
this.state = {
projectList: [],
myProjects: [],
userList: [],
submitted: false
};
this.createProject = this.createProject.bind(this);
}
createProject(title, desc, langs, len, exp) {
this.setState({
projectList: this.state.projectList.push([
{
title : title,
description : desc,
language : langs,
length : len,
experience : exp
}
]),
submitted : true
});
}
deleteProject(title) {
const projects = this.state.projectList.filter(
p => p.title !== title
);
this.setState({projects});
}
render() {
let info;
if (this.state.submitted) {
info = (
<div>
<p>cccc</p>
</div>
);
} else {
info = (
<br/>
);
}
return(
<div>
<Form/>
{info}
{this.state.projectList.map((params) =>
<Project {...params}/>)}
</div>
);
}
}
export default App;
import React from "react";
import createProject from "./App.js"
class Form extends React.Component {
constructor(props) {
super(props);
this.state = {
title: "",
description: "",
language: "",
length: 0,
experience: "",
submitted: false
};
this.handleSubmit = this.handleSubmit.bind(this);
this.handleInputChange = this.handleInputChange.bind(this);
}
handleSubmit(event) {
this.setState({
submitted: true
})
createProject(
this.state.title,
this.state.description,
this.state.language,
this.state.length,
this.state.experience
)
event.preventDefault();
}
handleInputChange(event) {
const target = event.target;
const value = target.value;
const name = target.name;
this.setState({
[name]: value
});
}
render() {
let info;
if (this.state.submitted) {
info = (
<div>
<h1>{this.state.title}</h1>
<p>{this.state.description}</p>
<p>{this.state.language}</p>
<p>{this.state.length}</p>
<p>{this.state.experience}</p>
</div>
);
} else {
info = <br/>;
}
return (
<div>
<form onSubmit={this.handleSubmit}>
<label>
Title:
<input
name="title"
type="textbox"
checked={this.state.title}
onChange={this.handleInputChange} />
</label>
<br />
<label>
Description:
<input
name="description"
type="textbox"
checked={this.state.description}
onChange={this.handleInputChange} />
</label>
<br />
<label>
Language:
<input
name="language"
type="textbox"
checked={this.state.language}
onChange={this.handleInputChange} />
</label>
<br />
<label>
Length:
<input
name="length"
type="number"
checked={this.state.length}
onChange={this.handleInputChange} />
</label>
<br />
<label>
Experience:
<input
name="experience"
type="textbox"
checked={this.state.experience}
onChange={this.handleInputChange} />
</label>
<br />
<input type="submit" value="Submit" />
</form>
{info}
</div>
);
}
}
export default Form;
I've also tried adding "new" to the "createProject" in handleSubmit, and while that does stop the auto-refresh, it will not call the createProject function. (Or maybe it does, but none of the code in the createProject function seems to be run.) Can anyone help with preventing this auto refresh while also allowing App's createProject function to run properly?
A:
The page auto refreshes because execution never gets to your event.PreventDefault() line. This is due to an error encountered when react tries to evaluate createProject. To fix this, correct handleSubmit like so.
handleSubmit(event) {
event.preventDefault(); // moved up in execution.
this.setState({
submitted: true
})
createProject(
this.state.title,
this.state.description,
this.state.language,
this.state.length,
this.state.experience
)
}
Notice that moving event.PreventDefault() to the top of your handleSubmit(event) function just before this.setState line prevents default form behaviour on submit.
You however get an error because App.js doesn't export a function called createProject. To maintain the createProject within App instance, you need to pass it as a prop which you can then reference as this.props.createProject.
See this answer on how to do call a Parent method in ReactJS.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Valid use of ISR_NOBLOCK
I am using two timer interrupts:
TIMER0_OVF triggered every 12 ms, with its ISR only polling a pin, conditionally setting a flag and incrementing a value, so it should complete pretty quick
TIMER2_OVF triggered at a rate of 4 kHz, with its ISR only toggling an output pin to make a piezo speaker beep
Since the TIMER2_OVF interrupts are blocked for a short moment every 12 ms by the TIMER0_OVF ISR, the beep doesn't sound clean, it is overlayed by a "rrr...".
Adding ISR_NOBLOCK to the TIMER0_OVF ISR solves this and the beep sounds clean, and the rest still works fine.
However I am unsure if this is a valid use of ISR_NOBLOCK and if there is a more elegant way to generate a "clean" beep?
Reading about ISR_NOBLOCK in <avr/interrupt.h>: Interrupts leaves the impression to me that it is intended for rare cases where nested interrupts are needed and should be used with care.
A:
This is a reasonable use of ISR_NOBLOCK as long as you understand the limitations. If you add more interrupts you may encounter problems.
However, for the beep case, you may be able to get the timer to generate the signal with no CPU intervention. See http://www.wrightflyer.co.uk/Using%20AVR%20Counter.pdf
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Topic Challenge: James Bond and his films [completed]
With the release of Spectre as the 24th installment in the EON-produced James Bond film series and due to popular demand we're starting a new biweekly topic challenge from 2015-10-31 00:00 UTC to 2015-11-13 23:00 UTC asking for any kind of question about James Bond and the films he appeared in (neatly trackable with the james-bond tag).
Once the challenge is over, we'll tally the results and winners (by question votes) here. Also don't forget to suggest and vote for new topics for our next possible challenge.
A:
The challenge is over and the top-voted question (with a score of 6 and ~175 views) was asked by Mason Wheeler, which makes them the winner of this challenge:
1. What is Bond's first line in Spectre?
The other questions asked, in order of votes are (the numbers are the votes and views):
Significance of the painting behind M in the restaurant (4 / ~71)
How was pre-title opening in Spectre shot? (4 / ~177)
Why wasn't Teresa Bond's tombstone written as Tracy Bond? (2 / ~30)
Is there any criteria for selection of James bond? (2 / ~111)
Is Franz Oberhauser related to the original Blofeld? (2 / ~207)
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Android bottom navigation appears when pressing on Flutter bottom navigation bar
I'm using SystemChrome.setEnabledSystemUIOverlays([SystemUiOverlay.top]);
to only display the top system overlay (Where you normally see time and notifications) and disable bottom navigation of the device (3 buttons in android or slider in IOS).
Problem is that when I try to press the Bottom Navigation Bar of my Flutter application, it automatically activates the bottom bar of the system, blocking out the bottom navigation bar of the app.
Resizing the app is not suitable for me. I don't want this to happen, and system navigation should only appear when user slides from the bottom.
Help is appreciated.
A:
Can you share your code so that I can have a better Idea,
// to hide only bottom bar:
SystemChrome.setEnabledSystemUIOverlays ([SystemUiOverlay.top]);
// to hide only status bar:
SystemChrome.setEnabledSystemUIOverlays ([SystemUiOverlay.bottom]);
// to hide both:
SystemChrome.setEnabledSystemUIOverlays ([]);
//to bring them back:
SystemChrome.setEnabledSystemUIOverlays(SystemUiOverlay.values)
Implement the in your code and it should work.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Changing data value in sql table on specific date?
I am trying to build a serial code control system based on Mysql and php as api.
Taking a scenario that a serial has a been generated on 3:00 AM (as the serials will have 1 hour validity ) on 4:00 AM its data will altered in the status column from 1 to 0 (1 means haven't expired 0 means expired).
I have designed the api such that if the serial exist then check for the status if its 1 then true else false
Now, I can't manually change the data from 1 to 0. I want this to be automated
I thought of building another api to return time of each serial then use it in a python script which can run 24/7 and check if time is more than an hour or less based on that it will call another api which will alter the value
I want to know if their are any other ways of doing this rather than running a python script 24/7
A:
You could look into cron jobs to execute the script and run the query every x minutes, say 5.
https://crontab.guru/
|
{
"pile_set_name": "StackExchange"
}
|
Q:
The radius of a sphere is measured as 5 cm ± 0·1 cm. Use differentiation to find the volume of the sphere in the form Vcm^3 ± bcm^3.
I have tried:
V = 4/3πr^3
If the radius is 5 ± 0·1, then V = 4/3π(5 ± 0·1) ^3
giving V = 555.65 or V = 492.81
The provided solution is (524 ± 31) cm^3 but I am not sure how you derive this result. This is from a Year 12 Maths Methods textbook.
A:
This is a "linearization" or "approximation by differentials" problem. The goal is to approximate the error in calculating the volume, knowing the error in measuring the radius. Since $V=\frac{4}{3}\pi r^3$, then $V'= 4 \pi r^2$, and you have:
$$\Delta V \approx dV = 4 \pi r^2 \; dr$$
Let the error in the radius be $\Delta r = dr = 0.1$ and $r=5$ to get
$$\Delta V \approx 4 \pi (5)^2 (0.1)= 31.4\ldots.$$
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How to listen for broadcast packets on any port?
Using .NET, how can I listen to udp broadcast packets sent to .255 on any port without the need of binding to a specific port?
A:
I found a way myself. This is how it works:
mainSocket = new Socket(AddressFamily.InterNetwork, SocketType.Raw, ProtocolType.IP);
mainSocket.Bind(new IPEndPoint(IPAddress.Parse("192.168.0.1"), 0));
mainSocket.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.HeaderIncluded, true);
byte[] byTrue = new byte[4] { 1, 0, 0, 0 };
byte[] byOut = new byte[4] { 1, 0, 0, 0 };
// Socket.IOControl is analogous to the WSAIoctl method of Winsock 2
mainSocket.IOControl(IOControlCode.ReceiveAll, //Equivalent to SIO_RCVALL constant of Winsock 2
byTrue,
byOut);
//Start receiving the packets asynchronously
mainSocket.BeginReceive(byteData,0,byteData.Length,SocketFlags.None,new AsyncCallback(OnReceive),null);
In the async handler, I do a mainSocket.EndReceive(...), parse the data and start a new BeginReceive if wanted (controlled from outside the multithreaded receiver).
Works like a charm. Credits go to Hitesh Sharma (http://www.codeproject.com/KB/IP/CSNetworkSniffer.aspx)
A:
I think you'll need to be lower level than UDP to accomplish this.
If I really wanted to do this, I'd start by downloading an open source packet sniffer/network analyzer (Ethereal.com comes to mind) and peruse the source to see how they read the packets.
Looking further, I found quite a bit about packet capturing at tcpdump.org.
Sorry I can't give specific code snippets, I've always wanted to bind to a specific port.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
find in db with explicitly excluded fields
How can I perform this operation :
link
For example I want to get all documents but without field "name":
err := col.Find([]bson.M{{}, {"name": false}}).All(&result)
In result always will be 0 elements, why?(field name exists in collection)
A:
See https://godoc.org/gopkg.in/mgo.v2#Query.Select
You are supposed to use something like:
err := col.Find(nil).Select(bson.M{"name": 0}).All(&result)
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How to show modalviewcontroller above tabbar
I have tab bar and in view "A" and in "A" I have navigation controller. SO inside my navigation controller in "A" i called
[self presentModalViewController:modalView animated:YES]
But modalView shows under tab bar. How to show it above tab bar?
A:
Try to present modal view from UITabBarController:
[self.tabBarController presentModalViewController:modalView animated:YES];
A:
My case, the modal has a transparent background, I set modalPresentationStyle is .overFullScreen and it show at above tabbar with clear background.
A:
In my case the presented view controller had UIModalPresentationStyle.CurrentContext at .modalPresentationStyle, which made the tab bar overlap
Jus switch back to a default value to fix the issue
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How to get std::chrono::system_clock::time_point from std::chrono::system_clock::time_point.time_since_epoch().count()?
I have a variable stored as a long a value from std::chrono::system_clock::time_point.time_since_epoch().count().
I would now like to restore that std::chrono::system_clock::time_point from the long variable.
So how can I convert a long to a std::chrono::system_clock::time_point?
A:
You first need to convert the integral type to a chrono::duration, and then convert the duration to a system_clock::time_point. But there's a catch:
duration is a template:
template <class Rep, class Period> class duration;
If you convert the integral type to the wrong duration, you'll get the wrong time_point.
Fortunately system_clock itself tells you the correct duration with its nested duration type: system_clock::duration. Additionally, each of these conversions is explicit.
So, in summary:
using namespace std::chrono;
system_clock::time_point tp{system_clock::duration{i}};
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How to pose and arrange people in a group shot?
What are good standard poses for group shots of 3 or 4 people and how can I arrange folks so that they don't just look like they're 'standing around'?
A:
Triangles
A classic approach is to arrange people so their faces form triangles. This is aesthetically pleasing.
Example by "Harriet Bayliss Photography
another Example by ".eti"
Sub-Groups
A technique which is useful when you have lots ( > 4 or so) of people is to arrange them in subgroups, such that each sub-group works on its own, and arrange the sub-groups so that they link together somehow.
Example on Flickr here by "off thedeepend".
Another example, also on Flickr. This one by "Sadie Collins"
Heads Together
Finally, putting the subject's heads close to each other builds interest. It makes them look connected. Here's an example where "Waechor"'s image works because the 3 girls' heads are close/touching.
Good luck. :)
A:
Here's a couple of suggestions:
Classic family or work group portrait: Seat a person or a couple and have the rest stand behind and to the sides. The person or couple sitting down will typically be determined by seniority, but other criteria might create interesting dynamics too, so don't just blindly go by the numbers.
Another classic, especially with younger subjects: Have the group jump and photograph them midair with a fast shutter speed and/or a flash to freeze the motion.
With a more lively and dynamic group, you can also experiment with untraditional poses like for example standing one person a feet or two away from the rest of the group, then have the group look at the one person while the one person looks at the camera, vice versa, or other combinations of looking/not looking.
Arrange the group members like a classic band photo. Place the lead person center and front, and have the other persons stand further behind and to the side. Arrange the people in individual poses.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
$\sigma$ can be extended into an isomorphism $\tilde{\sigma}$ that satisies $\tilde{\sigma}(u)=v$
I am reading the following theorem and its proof:
Theorem.
Let $\sigma : K\rightarrow K'$ be a field isomorphism and let $p(x)=a_0+a_1x+\dots a_nx^n\in K[x]$ be a non-constant irreducible polynomial.
Let $p'(x)=\sigma (a_0)+\sigma (a_0)+\sigma (a_1)x+\dots +\sigma (a_n)x^n\in K'[x]$. If $u, v$ are roots of $p(x)$ and $p'(x)$ (in some appropriate extensions of $K$ and $K'$), respectively, then $\sigma$ can be extended into an isomorphism $\tilde{\sigma}:K[u]\rightarrow K'[v]$ that satisies the $\tilde{\sigma}(u)=v$.
Proof.
For each $u\in K$ we write $\sigma (u)=u'$ and we write the elements of $K'$ in the form $u'=\sigma (u)$ for some (exactly one) $u\in K$.
Firstly we notice that $p'(x)$ is irreducible.
Indeed, because if it was $p'(x)=(a_0'+a_1'x+\dots +a_k'x^k)(b_0'+b_1'x+\dots +b_m'x^m)$ with $k,m\geq 1$, then $p(x)=(a_0+a_1x+\dots +a_kx^k)(b_0+b_1x+\dots +b_mx^m)$, so it would be in contradiction to the assumption for $p(x)$.
Also, since the multiplication of a polynomial with a non-zero constant does not affect its roots, we can, without loss of generality, assume $p(x)$ to be monic (so also $p'(x)$).
The polynomials $p(x), p'(x)$ have the same degree, let $n$, so the $1, u, \dots , u^{n-1}$ consist a basis of $K[u]/K$, but $1, v, \dots , v^{n-1}$ a basis of $K'[v]/K'$.
So, we have that the mapping $\tilde{\sigma}:K[u]\rightarrow K'[v]$, that is defined by the relation $$\tilde{\sigma}(c_0+c_1u+\dots +c_{n-1}u^{n-1})=c_0'+c_1'v+\dots +c_{n-1}'v^{n-1}$$ for all the $c_0, c_1, \dots , c_{n-1}\in K$ it has the properties that are required by the theorem.
$$$$
$$$$
I haven't really understood the theorem... Could you explain it to me?
At the part:
Indeed, because if it was $p'(x)=(a_0'+a_1'x+\dots +a_k'x^k)(b_0'+b_1'x+\dots +b_m'x^m)$ with $k,m\geq 1$, then $p(x)=(a_0+a_1x+\dots +a_kx^k)(b_0+b_1x+\dots +b_mx^m)$, so it would be in contradiction to the assumption for $p(x)$.
do we have that this would be the form of $p(x)$ due o the isomorphism $\sigma$ ?
The polynomials $p(x), p'(x)$ have the same degree, let $n$, so the $1, u, \dots , u^{n-1}$ consist a basis of $K[u]/K$, but $1, v, \dots , v^{n-1}$ a basis of $K'[v]/K'$.
How do we know that these are basis?
So, we have that the mapping $\tilde{\sigma}:K[u]\rightarrow K'[v]$, that is defined by the relation $$\tilde{\sigma}(c_0+c_1u+\dots +c_{n-1}u^{n-1})=c_0'+c_1'v+\dots +c_{n-1}'v^{n-1}$$ for all the $c_0, c_1, \dots , c_{n-1}\in K$ it has the properties that are required by the theorem.
Why do we define $\tilde{\sigma}$ in that way? Why does it satisfy the properties of the theorem?
A:
Do we have that this would be the form of $p(x)$ due to the isomorphism $\sigma$?
Yes, if $p'(x)$ were reducible, then applying $\sigma^{-1}$ would give a factorization of $p(x) = (\sigma^{-1}(a'_0) + \dots + \sigma^{-1}(a'_k)x^k)(\sigma^{-1}(b'_0) + \dots \sigma^{-1}(b'_m)x^m)$ (i.e., $a_i = \sigma^{-1}(a'_i)$ and $b_i = \sigma^{-1}(b'_i)$). Both of these polynomials would be nonconstant in $K[x]$ since $a'_k$ and $b'_m$ are both nonzero in $K'$, and the only element mapped to $0$ under $\sigma$ or $\sigma^{-1}$ is $0$ itself (because $\sigma$ and $\sigma^{-1}$ are isomorphisms).
How do we know that these are basis?
If $1,u,\dots, u^{n-1}$ were linearly dependent, $u$ would satisfy a polynomial $q\in K[x]$ of degree less than or equal to $n-1$. But since $p$ is the minimal polynomial of $u$, this would mean that $p$ divides $q$, which is impossible, as $q$ has degree less than $p$. Moreover, $1,u,\dots, u^{n-1}, u^n$ cannot be linearly dependent, as $p(u) = 0$ gives a linear dependence relation between them. The same reasoning applies to $1,v,\dots, v^{n-1}$.
Why do we define $\tilde{\sigma}$ in that way? Why does it satisfy the properties of the theorem?
Recall that we wanted a map $\tilde{\sigma} : K[u]\to K'[v]$ such that $\tilde{\sigma}(a) = \sigma(a)$ for all $a\in K$ and such that $\tilde{\sigma}(u) = v$. Now every element of $K[u]$ is a polynomial in $u$ with coefficients in $K$, so a map satisfying those properties is $\tilde{\sigma}(\sum_{i = 0}^m a_i u^i) := \sum_{i = 0}^m \sigma(a_i) v^i$ (do you see why $\tilde{\sigma}(a) = \sigma(a)$ for all $a\in K$ and why $\tilde{\sigma}(u) = v$?).
It remains to verify that $\tilde{\sigma}$ is an isomorphism. First, we will show injectivity. If $\sum_{i = 1}^m a_i u^i$ is a nonzero element of $K[u]$, then we may assume that $a_m\neq 0$ and that $m\leq n-1$ (why?), so that $\tilde{\sigma}(\sum_{i = 0}^m a_i u^i) = \sum_{i = 0}^m\sigma(a_i) v^i$. But then $\sigma(a_m)\neq 0$, and since $1,v,\dots, v^m$ are linearly independent, $\sum_{i = 0}^m\sigma(a_i) v^i\neq 0$. Hence, $\tilde{\sigma}$ is injective.
To see that $\tilde{\sigma}$ is surjective, choose any element $\sum_{i = 0}^{n-1} a'_i v^i\in K'[v]$. It is easy to verify that $\sum_{i = 0}^{n-1} \sigma^{-1}(a'_i) u^i$ maps to $\sum_{i = 0}^{n-1} a'_i v^i$ under $\tilde{\sigma}$, so that $\tilde{\sigma}$ is an isomorphism (I'll leave it to you to check that $\tilde{\sigma}$ is additive and multiplicative).
EDIT:
How do we know that $p$ is the minimal polynomial? Do we conclude to that because of the fact that $p$ is irreducible?
Yes, $p$ is the minimal polynomial because it has $u$ as a root and is irreducible. The minimal polynomial of $u$ is the nonzero polynomial $p$ of smallest degree such that $p(u) = 0$. By irreducibility, no polynomial $q$ of smaller degree could have $q(u) = 0$. (If such a $q$ existed, by irreducibility of $p$ we can find polynomials $a$ and $b$ such that $ap + bq = 1$, but $a(u)p(u) + b(u)q(u) = 0\neq 1$, which is a contradiction.)
Does this mean that $\tilde{\sigma}(a) = \sigma(a)$ for all $a\in K$? Or why do we want a map such that $\tilde{\sigma}(a) = \sigma(a)$ for all $a\in K$?
We want to be able to think of $K$ and $K'$ as the same field, since they are isomorphic. If you look at the "same" polynomial in each, their roots should also correspond (because the fields are the "same"). The mathematical way to say this is that the original isomorphism telling you that the fields $K$ and $K'$ were the same actually comes from an isomorphism $L\to L'$, where $L$ is a field containing $K$ and $L'$ is a field containing $K'$, so that indeed the roots of those polynomials can be thought of as the same. This is the same as saying you can extend the isomorphism $\sigma$ to an isomorphism $\tilde{\sigma}$ that restricts to $\sigma$ on the original field.
Do we have this because of the following? ...
I'm not sure what your calculation is trying to show. Think of $a\in K$ as a polynomial in $u$, so that $\tilde{\sigma}(a) = \sigma(a)$, as $a$ is a constant. $u$ is also a polynomial in $u$, and by definition of $\tilde{\sigma}$, $\tilde{\sigma}(u) = v$.
Do we assume that $m$ is the greatest index so that the coefficient is non-zero?
Yes. Such an index exists because the polynomial was not zero, and we can take $m < n$ because there is a linear dependence between $1,u,\dots, u^n$, so that any time you have a polynomial with a power of $u$ higher than $n-1$, you can use that linear dependence to reduce that power to $u$ to lower powers.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Horizontal scrollbar disappeared
My horizontal scroll bar doesn't appear when I decrease the window size of my browser. It is because I have overflow:hidden on two of my containers... however I need this as I am using floating elements and the background images don't show unless I use overflow:hidden. Is there a work-around to use achieve both things? Any help would be greatly appreciated!
http://actorscms.co.uk
A:
I don't think that is a good idea to make the horizontal scroll work. You should probably check some responsivness and media queries and make your website adjusts to viewport width.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Jump to anchor in overflow hidden
<ul id="the-list" style="overflow:hidden;height:100px;>
<li><a id="link1" href="#">Link 1</a></li>
<li><a id="link2" href="#">Link 2</a></li>
<li><a id="link3" href="#">Link 3</a></li>
<li><a id="link4" href="#">Link 4</a></li>
<li><a id="link5" href="#">Link 5</a></li>
<li><a id="link6" href="#">Link 6</a></li>
<li><a id="link7" href="#">Link 7</a></li>
<li><a id="link8" href="#">Link 8</a></li>
<li><a id="link8" href="#">Link 9</a></li>
<ul>
<a href="">more</a> <a href="">less</a>
The div above shows the first three links. When selecting more I want to to show 4-6. It doesn't need to do any smooth scrolling. Found a couple similar examples on stackoverflow but they didnt involve a link outside of the ul like this. Wondering what the simplest option is. Also as a bonus would love a less button that would undo the more. Such as if it advanced to show the next three clicking less would go back 3?
Can use jquery if necessary. Would like to keep it as simply as positive. Thank you for any ideas, I'll keep researching in the meantime.
A:
I'm not sure that I got you right, but if you want to change visible content of #the-list (show next 3 items and hide previous 3), than here's a solution: https://jsfiddle.net/hzonoyg0/
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Add Dynamically loading images using for loop in JToolBar
Possible Duplicate:
Issue regarding dynamically loading Images in loop using Java Swing
Can any one tell how I would add images dynamically using for loop in JToolBar. I tried a lot but it didn't work for dynamic loading of images. I want to create ToolBar where I load images in a loop.
A:
JToolBar is particularly well adapted to adding JButton instances each having a distinct Icon, so I would advocate using ImageIcon. Complete examples maybe found here, and more were cited in comments to an answer to your previous question.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
What's the difference between IDE encoding and project encoding?
I'm using IntelliJ IDEA, and there are encoding options including IDE Encoding and Project Encoding. Some blogs suggest to keep the two options same. So what's the difference between them? I changed one of the two and didn't find the difference.
A:
The Project Encoding is stored inside the project and is shared between developers working on the same project. New files in your project will get this encoding, except when overridden for specific files and directories.
IDE Encoding is the local encoding, stored within your IDE. When you create a new project, it gets this encoding. Files outside your project get this encoding too.
See also the online help about file encodings.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
PTIJ - A non-Jew's involvement in Judaism
The claim is made on this website that a non-Jew is allowed to engage in a central element of the oneg of a se'udah that one might think is reserved for Jews.
you don't have to be jewish to love levy's rye bread
Are there halachic discussions about whether it is or is not appropriate for a non-Jew to enjoy that lechem? Does this claim have any textual basis and is it the position of mainstream yahadut?
This question is Purim Torah and is not intended to be taken completely seriously. See the Purim Torah policy.
A:
The word for rye in Hebrew is שיפון which has a gematria of 446.
This is the same as the gematria of מרקוליס (normally translated as Mercury/Hermes), one of the paradigmatic examples of avodah zarah used by the Talmud. (See e.g. Sanhedrin 7:6.)
The implication is obvious. Even an idol worshiper is permitted to eat rye bread, all the more so other non-Jews with whom we interact today who may very well not have the status of idol worshipers.
Further, note that the traditional way of worshiping Markulis was by throwing stones at it (as noted in the mishnah linked to earlier).
This is clearly in reference to the story of Pharaoh's baker, who accidentally left a stone in Pharaoh's (rye) bread. So, in fact, we have a source from the Torah itself that Pharaoh, a non-Jew, was permitted to eat rye bread.
A:
Y'know, it's been a long time since I've seen those Levi's Jewish rye ads.
It is absolutely permissible for non-Jews to enjoy Levi's Jewish rye. Baruch Hashem that they're interested in this. The alternative is that they would be eating chazir rye!
I would even give such non-Jews an extra bracha, if they ate Levy's Rye bread. Nowadays, most non-Jews prefer bagels. And they're putting their pastrami on a bagel too. A shandeh!
|
{
"pile_set_name": "StackExchange"
}
|
Q:
how to wait for promise resolve in array.map method?
I want to upload photos to firebase storage.
In the state of React component I have array with photos. Photos are files that user browse through file input. Photos has property .needUpload to true, if file need to upload to storage.
Here is upload function:
uploadPhotos = () => {
let photosToSave = []
if (this.state.photos.length) {
photosToSave = this.state.photos
.filter(photo => photo.needUpload && true)
.map(photo => {
const extensionPattern = /(?:\.([^.]+))?$/
const fileName = photo.value.name
const fileExtension = extensionPattern.exec(fileName)[1]
const newFileName = new Date().getTime()
const fileLocation = storageRef.child('estateObjects/' + newFileName + '.' + fileExtension)
return new Promise(resolve => {
fileLocation.put(photo.value).on(
firebase.storage.TaskEvent.STATE_CHANGED,
snapshot => {
//let progress = (snapshot.bytesTransferred / snapshot.totalBytes) * 100
},
null,
() => {
fileLocation.getDownloadURL().then(url => {
resolve({ url: url, file: newFileName + '.' + fileExtension })
})
}
)
})
})
return Promise.all(photosToSave).then(response => {
return response
})
} else return Promise.all(photosToSave).then(response => [])
}
The main problem is that when upload starts, it (patiently) waiting, I guess for upload first 2-3 files, then in 'resolve' array I'm getting duplicated array elements. So something working wrong, but I cant understand what...
maybe problem is with new file name?? When file renames new Date.getTime() returns same time for few files, cause they where uploaded at the same time?
A:
the map loop runs very quickly, so the time won't change between iterations
So, I suggest you use the index to guarantee filename uniqueness
uploadPhotos = () => {
let photosToSave = [];
if (this.state.photos.length) {
photosToSave = this.state.photos.filter(photo => photo.needUpload && true).map((photo, index) => {
const extensionPattern = /(?:\.([^.]+))?$/;
const fileName = photo.value.name;
const fileExtension = extensionPattern.exec(fileName)[1];
const newFileName = `${new Date().getTime()}_${index}`;
const fileLocation = storageRef.child('estateObjects/' + newFileName + '.' + fileExtension);
return new Promise(resolve => {
fileLocation.put(photo.value).on(firebase.storage.TaskEvent.STATE_CHANGED, snapshot => {//let progress = (snapshot.bytesTransferred / snapshot.totalBytes) * 100
}, null, () => {
fileLocation.getDownloadURL().then(url => {
resolve({
url: url,
file: newFileName + '.' + fileExtension
});
});
});
});
});
return Promise.all(photosToSave).then(response => {
return response;
});
} else return Promise.all(photosToSave).then(response => []);
}
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Load one or more views within a CI Template loader class
Referring to the top answer on this post:
Header and footer in CodeIgniter
How could you update this class to support multiple views if required?
e.g. sometimes loading two or more views between the header and footer templates...
Thanks in advance :)
A:
If you want each view to have it's own vars:
public function template($template_names = array(), $vars = array(), $return = FALSE)
{
$content = $this->view('templates/header', $vars, $return);
foreach ($template_names as $template_name -> $template_vars)
{
$content .= $this->view($template_name, $template_vars, $return);
}
$content .= $this->view('templates/footer', $vars, $return);
if ($return)
{
return $content;
}
}
.
$this->load->template(array(
'body' => $vars_for_body,
'body2' => $vars_for_body2,
'body3' => $vars_for_body3
), $headerfooter_vars);
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Is there a concept of session management in WInforms
Today i gone for a interview i have asked why we can not implement state management in winforms like we do in Web applications. So can any give me the proper reason for this.
A:
...why we can not implement state
management in winforms...
It is an incorrect statement. In fact, we implement session management in every winform application and we are so habitual of doing it that we don't even realise we are doing it.
The very nature of desktop application is that all the state information you need is available in process memory and it remains available as long as your application is running. For example, it you set the value of a string variable to "Hello World", it will retain its value as long as that variable is accessible. Unlike web applications, you don't have to do anything explicitly to retain it. So the correct question might be
"Why we do not need to implement session management in WinForm application?"
(although I would be stumped by the obviousness of answer.)
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Angular scrollIntoView after adding an element to NgRx store
I have a list of items that are added dynamically to my view and stored in NgRx:
<app-item *ngFor="let item of items$ | async"></app-item>
If I click on an "Add item" button the item is added to the NgRx store.
I now want to call scrollIntoView on the item reference when a new item is added. I tried to call scrollIntoView at ngOnInit or ngAfterViewInit of the item but it gets triggered also on page load. I only want to center the item in the page when it is added to the list AND it is rendered.
How can I achieve this?
A:
What I can think of:
Create a variable indicating the newly added item index inside items
newestIndex; //the index of the newly added item inside items.
In your addItem() function, update the index.
addItem(item){
// update item , update ngrx store and also update the newestIndex.
}
Use a ViewChildren decorator to get all component items
@ViewChildren(AppItemComponent) appitems: QueryList<AppItemComponent>
And now when items update, you can scroll into view.
items$.pipe(skip(1)) //skip first value as it is not caused by add item.
.subscribe( items =>{
this.appitems[newestIndex].nativeElement.scrollIntoView();
})
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Sorting an array: Firstly by 1 element in a defined order, Then by the total of 2 other elements
I've looked at numerous examples on SO, but I'm unable to find a solution to this problem. I have a large array and I need to sort this by 2 elements.
Firstly, by a priority field in a custom order: S1,S2,S3,S4,S5,D,NS
Secondly, by 2 fields in the array added together. (This bit is working.)
I've made a sorting function which will sort by both of the above, however, it sorts D and NS before S1-S5 since D comes first alphabetically.
- I therefore need to define an array which contains the custom order I want to sort by. Please can anyone help?
The function I'm using is:
function compdaily($a, $b) {
if ($a['Priority'] == $b['Priority'])
{
return ($a['Value1'] + $a['Value2']) < ($b['Value1'] + $b['Value2']);
}
return strcmp($a['Priority'], $b['Priority']);
}
I then call above function in this manner:
usort($Array, 'compdaily');
Which brings the items out in this order:
Array
(
[0] => Array
(
[SomeID] => 1234
[Priority] => D
[Value1] => 250
[Value2] => 100
)
[1] => Array
(
[SomeID] => 456
[Priority] => NS
[Value1] => 250
[Value2] => 100
)
[2] => Array
(
[SomeID] => 124
[Priority] => S1
[Value1] => 200
[Value2] => 200
)
[3] => Array
(
[SomeID] => 1235
[Priority] => S1
[Value1] => 100
[Value2] => 100
)
[4] => Array
(
[SomeID] => 1230
[Priority] => S2
[Value1] => 250
[Value2] => 100
)
[5] => Array
(
[SomeID] => 123495
[Priority] => S3
[Value1] => 250
[Value2] => 100
)
[6] => Array
(
[SomeID] => 123498
[Priority] => S3
[Value1] => 100
[Value2] => 100
)
[7] => Array
(
[SomeID] => 12345
[Priority] => S4
[Value1] => 250
[Value2] => 100
)
)
However, I need them in this order:
Array
(
[0] => Array
(
[SomeID] => 124
[Priority] => S1
[Value1] => 200
[Value2] => 200
)
[1] => Array
(
[SomeID] => 1235
[Priority] => S1
[Value1] => 100
[Value2] => 100
)
[2] => Array
(
[SomeID] => 1230
[Priority] => S2
[Value1] => 250
[Value2] => 100
)
[3] => Array
(
[SomeID] => 123495
[Priority] => S3
[Value1] => 250
[Value2] => 100
)
[4] => Array
(
[SomeID] => 123498
[Priority] => S3
[Value1] => 100
[Value2] => 100
)
[5] => Array
(
[SomeID] => 12345
[Priority] => S4
[Value1] => 250
[Value2] => 100
)
[6] => Array
(
[SomeID] => 1234
[Priority] => D
[Value1] => 250
[Value2] => 100
)
[7] => Array
(
[SomeID] => 456
[Priority] => NS
[Value1] => 250
[Value2] => 100
)
)
I've tried utilising the example at: Sort an array by multiple keys in a certain order
But I was unable to get this to work alongside the above.
A:
Rather than using $a['Priority'] directly in sorting, could use a lookup table to get the actual order
something like...
$mapp = array('S1'=>1, 'S2'=>2, 'S3'=>3, 'S4'=>4, 'S5'=>5, 'D'=>6, 'NS'=>7);
function compdaily($a, $b) {
global $mapp;
...
return ($mapp[$a['Priority']] < $mapp[$b['Priority']]);
}
(the if statement doesn't need changing as can directly compare the strings for equality)
|
{
"pile_set_name": "StackExchange"
}
|
Q:
SQL Select closest smaller date of another date in 2 table
i have two tables
Table A
pk name a_date
1 Peter 01-01-1991
2 Paul 02-01-1991
3 John 03-01-1991
Table B
pk b_date
A 01-01-1991
B 02-01-1991
What i want the result is:
name a_date b_date
Paul 02-01-1991 01-01-1991
John 03-01-1991 02-01-1991
Select the closest smaller date of Table B for Table A
I tried to draw the result before select
1 Peter 01-01-1991 A 01-01-1991
1 Peter 01-01-1991 B 02-01-1991
2 Paul 02-01-1991 A 01-01-1991
2 Paul 02-01-1991 B 02-01-1991
3 John 03-01-1991 A 01-01-1991
3 John 03-01-1991 B 02-01-1991
then i tried select*from A,B where a_date>b_date
but it will return like this:
2 Paul 02-01-1991 A 01-01-1991
3 John 03-01-1991 A 01-01-1991
3 John 03-01-1991 B 02-01-1991
i also tried some thing like sub-query:
where a_date = (select...);
but i think this is a wrong way.
then i think that may be distinct can solve this problem,
but i find i can't use distinct in this case.
A:
This should do it (it assumes that dates are stored as date and not as strings):
SELECT a.name, a.date, MAX(b.date)
FROM a
JOIN b ON b.date < a.date
GROUP BY a.name, a.date
|
{
"pile_set_name": "StackExchange"
}
|
Q:
OSD notification for Irssi
I want to get a notification each time I get a /query message or get highlighted in a channel.
this notification should be in the form of bubble OSD (on screen Display).
If OSD isn't possible for Linux, I'll settle for bringing the terminal window containing the irssi instance to the top of the window stack and flickering window's name in status bar.
A:
This is easy enough to set up using the fnotify script. Set it to autoload and then customise it to print to a file of your choosing:
sub filewrite {
my ($text) = @_;
# FIXME: there is probably a better way to get the irssi-dir...
open(FILE,">>$ENV{HOME}/path/to/your/fnotified");
print FILE $text . "\n";
close (FILE);
}
Then, use inotifywait to watch that directory or file, and trigger a message when new lines are written to it:
#!/usr/bin/env bash
# script to push IRC highlight notifications
dir="$HOME/path/to/your/"
while inotifywait -qqre attrib "$dir" >/dev/null 2>&1; do
echo "IRC:" "You have been pinged..." | notify-send IRC "You have been pinged…" \
-i /usr/share/icons/gnome/48x48/status/dialog-warning.png
done
I run irssi on a headless server, so I sync the watched directory to all of the other machines I use with Pulse, (formerly Syncthing), and then run the inotify script on those local machines so that, wherever I am logged on, I will get notified if I am pinged...
You can run the inotify script from a service file if you use systemd or however you would like to start it on login.
If you don't want to use notify-send, dzen is an excellent choice for an unobtrusive notification application.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
list.pop() and deque.pop() -- is there a performance difference?
This question is a follow up to this one:
deque.popleft() and list.pop(0). Is there performance difference?
In Python, I can pop the last item added to a list using .pop(). I can also pop the last item using dequeue and .pop().
Is there a performance difference between these two? Is there a reason or use case that one should be used over the other?
Edit: Typo.... changed .popright to .pop -- deque's "pop right" is still just .pop -- thanks ShadowRanger
A:
Well, first off, it's called pop for both list and deque, there is no popright method on deques.
There is usually no meaningful performance difference between the two; every once in a while, a pop on a deque will cause a block deallocation (which has fixed overhead, it just makes that particular pop a little more costly), and on a list it can cause a realloc to shrink the underlying storage (which could end up being O(n), but only a tiny fraction of pops will cause it); asymptotically they're both O(1) operations. If your list is truly huge, then shrinks a lot you might get the occasional performance hiccup when it shrinks the underlying storage, but otherwise you're highly unlikely to notice a difference.
In answer to your question, deques are ever-so-slightly more efficient for use as stacks than lists; if you're importing collections anyway, and need a stack based structure, using a deque will get you a tiny benefit (at least on CPython, can't speak to other implementation). But it's not really worth micro-optimizing here; the cost of importing collections in the first place, and the cost of whatever useful code you execute based on this stack, likely dwarfs whatever tiny difference you'll see between list and deque for pops from the right. A simple ipython3 microbenchmark:
In [24]: %%timeit from collections import deque; s = deque([0] * 10000); onethousandnones = (None,) * 1000; pop = s.pop
...: ; push = s.append
...: for _ in onethousandnones:
...: pop()
...: for _ in onethousandnones:
...: push(0)
...:
...:
104 µs ± 7.99 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each)
In [25]: %%timeit s = [0] * 10000; onethousandnones = (None,) * 1000; pop = s.pop; push = s.append
...: for _ in onethousandnones:
...: pop()
...: for _ in onethousandnones:
...: push(0)
...:
...:
131 µs ± 8.93 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each)
So for a 1000 pops followed by 1000 pushes onto our stack, the deque-based stack took 30 µs less (~15 ns less per operation). Now admittedly, if I remove the call parentheses to time the base overhead, the base overhead was around 50 µs, so the overhead specifically attributable to the list is a significant fraction of the "minimum cost" of the deque, but it's still pretty small in the context of a program that is presumably doing something useful, not just pushing and popping to a stack. And it's pretty stable regardless of size; for a stack that's 10x the size, the cost remains unchanged for both deque and list. If the stack was growing and shrinking so much that list's amortized growth was kicking in, it might suffer a little more from the larger reallocations, but it's not normally something to worry about.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
mysql query to increase counter or marker by one for every empty record..?
i had table structure as below.. having column id number i want to add column counter with desired output given below..like 1,1,1,1 then counter is need to increament by 1 on every empty row..so for next rows its 2,2,2,2...until next empty rows..and so on... how to write query for this?? any help would be appreciated.. thanks in advance..
Table structure:
CREATE TABLE `stack` (
`id` int(11) NOT NULL auto_increment,
`number` int(5) default NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=300 ;
--
-- Dumping data for table `stack`
--
INSERT INTO `stack` (`id`, `number`) VALUES
(1, 75201),
(2, 55008),
(3, 55007),
(4, 75222),
(5, 0),
(6, 74992),
(7, 14553),
(8, 54582),
(9, 54581),
(10, 74991),
(11, 14554),
(12, 0),
(13, 71413),
(14, 71414),
(15, 71415),
(16, 71416),
(17, 0),
(18, 59823),
(19, 59824),
(20, 59821),
(21, 59825),
(22, 59826),
(23, 0),
(24, 58220),
(25, 58702),
(26, 18247),
(27, 51753),
(28, 12854),
(29, 15160),
(30, 18248),
(31, 51606),
(32, 18478),
(33, 68747),
(34, 68749),
(35, 58221),
(36, 18233),
(37, 15159),
(38, 18234),
(39, 58701),
(40, 58222),
(41, 68748),
(42, 51754),
(43, 18477),
(44, 51605),
(45, 68750),
(46, 18235),
(47, 18235),
(48, 12853),
(49, 18236),
(50, 0),
(51, 56617),
(52, 16349),
(53, 56612),
(54, 56614),
(55, 56613),
(56, 56616),
(57, 56362),
(58, 56611),
(59, 56363),
(60, 56610),
(61, 56619),
(62, 56620),
(63, 56621),
(64, 16350),
(65, 0),
(66, 64590),
(67, 64153),
(68, 64162),
(69, 64588),
(70, 64587),
(71, 64156),
(72, 64159),
(73, 64589),
(74, 0),
(75, 19152),
(76, 59425),
(77, 12959),
(78, 59426),
(79, 19151),
(80, 12960),
(81, 0),
(82, 54809),
(83, 54810),
(84, 54826),
(85, 14813),
(86, 54703),
(87, 74835),
(88, 74836),
(89, 54704),
(90, 14814),
(91, 54825),
(92, 0),
(93, 56700),
(94, 16128),
(95, 56319),
(96, 56718),
(97, 16723),
(98, 16724),
(99, 56717),
(100, 56320),
(101, 16127),
(102, 56701),
(103, 0),
(104, 56261),
(105, 22625),
(106, 12691),
(107, 16086),
(108, 12639),
(109, 12680),
(110, 22649),
(111, 12609),
(112, 12679),
(113, 12640),
(114, 66020),
(115, 16089),
(116, 17616),
(117, 12687),
(118, 66019),
(119, 16220),
(120, 12675),
(121, 12608),
(122, 16219),
(123, 16021),
(124, 22650),
(125, 12692),
(126, 12610),
(127, 7115),
(128, 56262),
(129, 16022),
(130, 12688),
(131, 22626),
(132, 22688),
(133, 12607),
(134, 16090),
(135, 12676),
(136, 16085),
(137, 17615),
(138, 12687),
(139, 22687),
(140, 7116),
(141, 0),
(142, 38716),
(143, 38455),
(144, 38302),
(145, 38703),
(146, 38402),
(147, 38404),
(148, 38304),
(149, 38702),
(150, 38803),
(151, 38406),
(152, 38306),
(153, 38408),
(154, 38704),
(155, 38101),
(156, 38401),
(157, 38805),
(158, 38410),
(159, 38403),
(160, 38301),
(161, 38802),
(162, 38051),
(163, 38412),
(164, 38308),
(165, 38807),
(166, 38102),
(167, 38405),
(168, 38706),
(169, 38414),
(170, 38707),
(171, 38310),
(172, 38407),
(173, 38202),
(174, 38303),
(175, 38409),
(176, 38416),
(177, 38809),
(178, 38104),
(179, 38708),
(180, 38204),
(181, 38105),
(182, 38710),
(183, 38811),
(184, 38420),
(185, 38413),
(186, 38415),
(187, 38422),
(188, 38601),
(189, 38106),
(190, 38810),
(191, 38813),
(192, 38424),
(193, 38417),
(194, 38312),
(195, 38419),
(196, 38426),
(197, 38305),
(198, 38709),
(199, 38428),
(200, 38711),
(201, 38812),
(202, 38421),
(203, 38602),
(204, 38501),
(205, 38713),
(206, 38430),
(207, 58002),
(208, 38307),
(209, 38432),
(210, 38814),
(211, 38717),
(212, 38423),
(213, 38434),
(214, 38819),
(215, 38314),
(216, 38425),
(217, 38816),
(218, 38719),
(219, 38316),
(220, 38436),
(221, 38318),
(222, 38818),
(223, 38502),
(224, 38429),
(225, 38718),
(226, 38431),
(227, 38720),
(228, 38438),
(229, 38820),
(230, 38107),
(231, 38721),
(232, 38440),
(233, 38722),
(234, 38109),
(235, 38435),
(236, 68007),
(237, 38201),
(238, 38442),
(239, 38309),
(240, 38437),
(241, 38108),
(242, 38444),
(243, 38311),
(244, 38446),
(245, 38110),
(246, 38441),
(247, 38448),
(248, 38206),
(249, 38723),
(250, 38724),
(251, 38313),
(252, 38450),
(253, 38726),
(254, 38315),
(255, 38445),
(256, 38452),
(257, 38447),
(258, 38826),
(259, 38317),
(260, 38831),
(261, 38728),
(262, 38449),
(263, 38725),
(264, 38454),
(265, 38828),
(266, 38451),
(267, 38727),
(268, 38456),
(269, 38319),
(270, 38453),
(271, 38830),
(272, 38321),
(273, 0),
(274, 19016),
(275, 59050),
(276, 59547),
(277, 59548),
(278, 59049),
(279, 19015),
(280, 0),
(281, 52171),
(282, 52174),
(283, 52172),
(284, 52173),
(285, 0),
(286, 12343),
(287, 55713),
(288, 55749),
(289, 75718),
(290, 7525),
(291, 55750),
(292, 7526),
(293, 75722),
(294, 55751),
(295, 55714),
(296, 75717),
(297, 75721),
(298, 12344),
(299, 55752);
Desired output i want:
CREATE TABLE `stack` (
`id` int(11) NOT NULL auto_increment,
`counter` int(5) NOT NULL,
`number` int(5) default NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=300 ;
--
-- Dumping data for table `stack`
--
INSERT INTO `stack` (`id`, `counter`, `number`) VALUES
(1, 1, 75201),
(2, 1, 55008),
(3, 1, 55007),
(4, 1, 75222),
(5, 2, 0),
(6, 2, 74992),
(7, 2, 14553),
(8, 2, 54582),
(9, 2, 54581),
(10, 2, 74991),
(11, 2, 14554),
(12, 3, 0),
(13, 3, 71413),
(14, 3, 71414),
(15, 3, 71415),
(16, 3, 71416),
(17, 4, 0),
(18, 4, 59823),
(19, 4, 59824),
(20, 4, 59821),
(21, 4, 59825),
(22, 4, 59826),
(23, 5, 0),
(24, 5, 58220),
(25, 5, 58702),
(26, 5, 18247),
(27, 5, 51753),
(28, 5, 12854),
(29, 5, 15160),
(30, 5, 18248),
(31, 5, 51606),
(32, 5, 18478),
(33, 5, 68747),
(34, 5, 68749),
(35, 5, 58221),
(36, 5, 18233),
(37, 5, 15159),
(38, 5, 18234),
(39, 5, 58701),
(40, 5, 58222),
(41, 5, 68748),
(42, 5, 51754),
(43, 5, 18477),
(44, 5, 51605),
(45, 5, 68750),
(46, 5, 18235),
(47, 5, 18235),
(48, 5, 12853),
(49, 5, 18236),
(50, 6, 0),
(51, 6, 56617),
(52, 6, 16349),
(53, 6, 56612),
(54, 6, 56614),
(55, 6, 56613),
(56, 6, 56616),
(57, 6, 56362),
(58, 6, 56611),
(59, 6, 56363),
(60, 6, 56610),
(61, 6, 56619),
(62, 6, 56620),
(63, 6, 56621),
(64, 6, 16350),
(65, 7, 0),
(66, 7, 64590),
(67, 7, 64153),
(68, 7, 64162),
(69, 7, 64588),
(70, 7, 64587),
(71, 7, 64156),
(72, 7, 64159),
(73, 7, 64589),
(74, 8, 0),
(75, 8, 19152),
(76, 8, 59425),
(77, 8, 12959),
(78, 8, 59426),
(79, 8, 19151),
(80, 8, 12960),
(81, 9, 0),
(82, 9, 54809),
(83, 9, 54810),
(84, 9, 54826),
(85, 9, 14813),
(86, 9, 54703),
(87, 9, 74835),
(88, 9, 74836),
(89, 9, 54704),
(90, 9, 14814),
(91, 9, 54825),
(92, 10, 0),
(93, 10, 56700),
(94, 10, 16128),
(95, 10, 56319),
(96, 10, 56718),
(97, 10, 16723),
(98, 10, 16724),
(99, 10, 56717),
(100, 10, 56320),
(101, 10, 16127),
(102, 10, 56701),
(103, 11, 0),
(104, 11, 56261),
(105, 11, 22625),
(106, 11, 12691),
(107, 11, 16086),
(108, 11, 12639),
(109, 11, 12680),
(110, 11, 22649),
(111, 11, 12609),
(112, 11, 12679),
(113, 11, 12640),
(114, 11, 66020),
(115, 11, 16089),
(116, 11, 17616),
(117, 11, 12687),
(118, 11, 66019),
(119, 11, 16220),
(120, 11, 12675),
(121, 11, 12608),
(122, 11, 16219),
(123, 11, 16021),
(124, 11, 22650),
(125, 11, 12692),
(126, 11, 12610),
(127, 11, 7115),
(128, 11, 56262),
(129, 11, 16022),
(130, 11, 12688),
(131, 11, 22626),
(132, 11, 22688),
(133, 11, 12607),
(134, 11, 16090),
(135, 11, 12676),
(136, 11, 16085),
(137, 11, 17615),
(138, 11, 12687),
(139, 11, 22687),
(140, 11, 7116),
(141, 12, 0),
(142, 12, 38716),
(143, 12, 38455),
(144, 12, 38302),
(145, 12, 38703),
(146, 12, 38402),
(147, 12, 38404),
(148, 12, 38304),
(149, 12, 38702),
(150, 12, 38803),
(151, 12, 38406),
(152, 12, 38306),
(153, 12, 38408),
(154, 12, 38704),
(155, 12, 38101),
(156, 12, 38401),
(157, 12, 38805),
(158, 12, 38410),
(159, 12, 38403),
(160, 12, 38301),
(161, 12, 38802),
(162, 12, 38051),
(163, 12, 38412),
(164, 12, 38308),
(165, 12, 38807),
(166, 12, 38102),
(167, 12, 38405),
(168, 12, 38706),
(169, 12, 38414),
(170, 12, 38707),
(171, 12, 38310),
(172, 12, 38407),
(173, 12, 38202),
(174, 12, 38303),
(175, 12, 38409),
(176, 12, 38416),
(177, 12, 38809),
(178, 12, 38104),
(179, 12, 38708),
(180, 12, 38204),
(181, 12, 38105),
(182, 12, 38710),
(183, 12, 38811),
(184, 12, 38420),
(185, 12, 38413),
(186, 12, 38415),
(187, 12, 38422),
(188, 12, 38601),
(189, 12, 38106),
(190, 12, 38810),
(191, 12, 38813),
(192, 12, 38424),
(193, 12, 38417),
(194, 12, 38312),
(195, 12, 38419),
(196, 12, 38426),
(197, 12, 38305),
(198, 12, 38709),
(199, 12, 38428),
(200, 12, 38711),
(201, 12, 38812),
(202, 12, 38421),
(203, 12, 38602),
(204, 12, 38501),
(205, 12, 38713),
(206, 12, 38430),
(207, 12, 58002),
(208, 12, 38307),
(209, 12, 38432),
(210, 12, 38814),
(211, 12, 38717),
(212, 12, 38423),
(213, 12, 38434),
(214, 12, 38819),
(215, 12, 38314),
(216, 12, 38425),
(217, 12, 38816),
(218, 12, 38719),
(219, 12, 38316),
(220, 12, 38436),
(221, 12, 38318),
(222, 12, 38818),
(223, 12, 38502),
(224, 12, 38429),
(225, 12, 38718),
(226, 12, 38431),
(227, 12, 38720),
(228, 12, 38438),
(229, 12, 38820),
(230, 12, 38107),
(231, 12, 38721),
(232, 12, 38440),
(233, 12, 38722),
(234, 12, 38109),
(235, 12, 38435),
(236, 12, 68007),
(237, 12, 38201),
(238, 12, 38442),
(239, 12, 38309),
(240, 12, 38437),
(241, 12, 38108),
(242, 12, 38444),
(243, 12, 38311),
(244, 12, 38446),
(245, 12, 38110),
(246, 12, 38441),
(247, 12, 38448),
(248, 12, 38206),
(249, 12, 38723),
(250, 12, 38724),
(251, 12, 38313),
(252, 12, 38450),
(253, 12, 38726),
(254, 12, 38315),
(255, 12, 38445),
(256, 12, 38452),
(257, 12, 38447),
(258, 12, 38826),
(259, 12, 38317),
(260, 12, 38831),
(261, 12, 38728),
(262, 12, 38449),
(263, 12, 38725),
(264, 12, 38454),
(265, 12, 38828),
(266, 12, 38451),
(267, 12, 38727),
(268, 12, 38456),
(269, 12, 38319),
(270, 12, 38453),
(271, 12, 38830),
(272, 12, 38321),
(273, 13, 0),
(274, 13, 19016),
(275, 13, 59050),
(276, 13, 59547),
(277, 13, 59548),
(278, 13, 59049),
(279, 13, 19015),
(280, 14, 0),
(281, 14, 52171),
(282, 14, 52174),
(283, 14, 52172),
(284, 14, 52173),
(285, 15, 0),
(286, 15, 12343),
(287, 15, 55713),
(288, 15, 55749),
(289, 15, 75718),
(290, 15, 7525),
(291, 15, 55750),
(292, 15, 7526),
(293, 15, 75722),
(294, 15, 55751),
(295, 15, 55714),
(296, 15, 75717),
(297, 15, 75721),
(298, 15, 12344),
(299, 15, 55752);
A:
You can try to declare a variable @Val with CASE WHEN to make it.
using CASE WHEN to judgment number. if number is 0 or null do accumulate the @Val
Schema (MySQL v5.7)
CREATE TABLE `stack` (
`id` int(11) NOT NULL auto_increment,
`number` int(5) default NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=23 ;
--
-- Dumping data for table `stack`
--
INSERT INTO `stack` (`id`, `number`) VALUES
(1, 52201),
(2, 53008),
(3, 55007),
(4, 75222),
(5, 0),
(6, 74992),
(7, 14553),
(8, 54582),
(9, 54581),
(10, 74991),
(11, 14554),
(12, 0),
(13, 11413),
(14, 72414),
(15, 31415),
(16, 71416),
(17, 0),
(18, 59823),
(19, 69824),
(20, 59821),
(21, 69825),
(22, 59826);
Query #1
SET @Val= 1;
There are no results to be displayed.
Query #2
SELECT id,
(CASE WHEN coalesce(number,0) = 0 THEN @Val:=@Val+1 ELSE @Val END) counter,
number
FROM `stack` t1
order by id;
| id | number | counter |
| --- | ------ | ------- |
| 1 | 52201 | 1 |
| 2 | 53008 | 1 |
| 3 | 55007 | 1 |
| 4 | 75222 | 1 |
| 5 | 0 | 2 |
| 6 | 74992 | 2 |
| 7 | 14553 | 2 |
| 8 | 54582 | 2 |
| 9 | 54581 | 2 |
| 10 | 74991 | 2 |
| 11 | 14554 | 2 |
| 12 | 0 | 3 |
| 13 | 11413 | 3 |
| 14 | 72414 | 3 |
| 15 | 31415 | 3 |
| 16 | 71416 | 3 |
| 17 | 0 | 4 |
| 18 | 59823 | 4 |
| 19 | 69824 | 4 |
| 20 | 59821 | 4 |
| 21 | 69825 | 4 |
| 22 | 59826 | 4 |
View on DB Fiddle
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Is this a context-free language?
this is the Language
L = {a^i b^j a^i b^k | i, j, k >= 0}
Then, I can to try a grammar for this Language:
S -> ABCD
A -> a | aA | lambda
B -> b | bB | lambda
C -> a | aC | lambda
D -> b | bD | lambda
It's context-free...is it right the grammar ?
A:
Your grammar allows aaba, which it shouldn't, as there should always be a even number of as:
ABCD
aABCD
aaBCD
aabCD
aabaD
aaba
A correct answer would be:
Start → A B
A → a A a | B
B → bB | ε
B generates any number of bs (including none).
A is a sequence of a, followed by B, followed by the same number of a
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Two dimensional NIntegration failure - non-numerical values
I've got this function:
E0[x0_, y0_, z_]:=
A/w[z]*Exp[-(x0^2 + y0^2)/(w[z]*w[z])]*Exp[(I*2*Pi*(x0^2 + y0^2))/(λ*2*R[z])]*Exp[I*ϕ[z]];
Where the w[z], R[z] and Phi[z] are given as presented here.
Second function is as follows:
Transmission1[x0_, y0_] := 2*(1 + Cos[((2*Pi)/λ)*x0 - 2*ArcTan[(y0/x0)]]);
I want to perform an two dimensional NIntegration:
f1[x2_, y2_]:=
NIntegrate[E0[x0,y0,z]*Transmission1[x0, y0]*Exp[I*(kx1*x0 + ky1*y0)],
{y0,-0.00001,0.00001},{x0, -0.00001, 0.00001}];
where:
kx1 = ((2*Pi)/(λ*z))*x2;
ky1 = ((2*Pi)/(λ*z))*y2;
For any {x2,y2} values I get an error which states:
NIntegrate::inumr: "The integrand 2\ E^(I\((20000000 π x0 x2)/633+(20000000 π y0 y2)/633))\ (1+Cos[(2000000000\π\x0)/633-2\ ArcTan[Power[<<2>>]\ y0]])
has evaluated to non-numerical values for all sampling points in the region with boundaries {{-0.00001,0.00001},{-0.00001,0.00001}}"
How can I manage to solve this issue?
A:
Your problem is in how you define kx1 and ky1. When you call f1[], x2 and y2 are substituted in the expression they are immediately visible. And since kx1 and ky1 don't explicitly depend on z and x2 and y2, these values aren't substituted.
To fix this, you should define kx1 and ky1 as functions:
kx1[z_,x2_] = ((2*Pi)/(λ*z))*x2;
ky1[z_,y2_] = ((2*Pi)/(λ*z))*y2;
and use as functions in f1[].
Also, definition of your f1 lacks additional argument of z, so you should add it too (if you don't set its value somewhere, of course - but I couldn't deduce it from your question):
f1[x2_,y2_,z_]:=...
and supply it too for numerical integration to be possible.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Определить характеристики компьютера по JS
Здравствуйте, можно ли с помощью JS или других веб технологий собрать данные о характеристиках (железе) компьютера, и отправить на сервер?
A:
Нет, благо, JS на это не способен, так как это бы нарушило политику безопасности пользователя. Из характеристик о железе Вы можете узнать только размеры экрана.
На это способны браузеры, вплоть до определения уровня заряда на ноутбуке.
Советую вам копать в сторону взаимодействия вашего JS-кода с установленными расширениями.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Rails: storing encrypted data in database
I want to encrypt database because confidential data is being stored. I use mongodb with mongoid. It possible for this kind of database? And what alternatives can you recomend, if it is not?
P.S. Main purpose is: if anybody hack the server and steal DB, it would be unencryptable.
UPDATE: thanks for nickh, I found very many soultions for ActiveRecord, but nothing for Mongoid and other Mongo clinets. It would be great to find some soultion for Mongo and Mongoid!
A:
I have gotten attr_encrypted working with Mongo and Mongoid. It takes only a few tweaks.
Make sure that all of the encrypted_ fields that are automatically created by attr_encrypted are explicitly created in the model. For instance, if you have:
attr_encrypted :email, :key => 'blah blah blah', :encode => true
you need to have:
field :email, :type => String
field :encrypted_email, :type => String
Also notice you need to tell it to encode the encrypted string otherwise Mongo will complain loudly.
Lastly, if you're encrypting a hash, do this:
field :raw_auth_hash, :type => Hash
field :encrypted_raw_auth_hash, :type => String
attr_encrypted :raw_auth_hash, :key => 'blah', :marshal => true, :encode => true
A:
I've had a lot of success with the attr_encrypted gem. However, I've only used it with ActiveRecord. I don't know if it works with MongoMapper or Mongoid.
Regardless of how you implement this, I strongly recommend only encrypting certain fields. Don't encrypt every field in every table. Doing that will make it difficult to use associations, search using LIKE, etc.
A:
Try the mongoid-encrypted-fields gem - it is seamless as it handles encryption using mongoize/demongoize methods.
Just define your field like:
field :ssn, type: Mongoid::EncryptedString
Then you can access it like normal, but the data is stored encrypted.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
NSURLConnection sendAsynchronousRequest - communicating with HTTPS
Am working on an iPhone App which fetches an image from a URL. I was using 'NSData dataWithContentsOfUrl] & it worked fine.
But then, as you might have guessed, the request is synchronous.
I want the request to be asynchronous. So, I tried using the NSURLConnection's sendAsynchronousRequest() call. But this returns the following error in the method 'didFailWithError' :
Error Domain=kCFErrorDomainCFNetwork Code=310 "There was a problem
communicating with the secure web proxy server (HTTPS).
Can someone please help?
This is my NSURLConnection code snippet:
NSURL *url = [NSURL URLWithString:notePicUrl];
NSURLRequest *urlRequest = [NSURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:100.0];
//NSOperationQueue *queue = [[NSOperationQueue alloc] init];
NSURLConnection* _connection = [[NSURLConnection alloc] initWithRequest:urlRequest delegate:self startImmediately:NO];
self.port = [NSPort port];
self.runLoop = [NSRunLoop currentRunLoop];
[self.runLoop addPort:self.port forMode:NSDefaultRunLoopMode];
[_connection scheduleInRunLoop:self.runLoop forMode:NSDefaultRunLoopMode];
[_connection start];
while (self.finished != YES ) {
[self.runLoop runUntilDate:[NSDate dateWithTimeIntervalSinceNow: 0.1]];
}
[self.runLoop removePort:[self port] forMode:NSDefaultRunLoopMode];
[_connection unscheduleFromRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
And the NSURLConnectionDelegate methods (not yet implemented ; just testing to first see if it works) ...
-(void)connection:(NSURLConnection*)connection didReceiveResponse:(NSURLResponse*)response
{
NSLog(@"didReceiveResponse");
//_data = [[NSMutableData alloc] init]; // _data being an ivar
}
-(void)connection:(NSURLConnection*)connection didReceiveData:(NSData*)data
{
NSLog(@"didReceiveData");
//[_data appendData:data];
}
-(void)connection:(NSURLConnection*)connection didFailWithError:(NSError*)error
{
NSLog(@"didFailWithError %@", [error description]);
// Handle the error properly
}
-(void)connectionDidFinishLoading:(NSURLConnection*)connection
{
NSLog(@"connectionDidFinishLoading");
//[self handleDownloadedData]; // Deal with the data
}
A:
I just fixed this ; I tried using the simple code line:
[[NSURLConnection alloc] initWithRequest:urlRequest delegate:self startImmediately:YES];
And then handling the data in the Delegate methods. Earlier, it was attempting to run in a separate thread. this works just fine & is asynchronous.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Excel - formula to find how many cells to sum of N
I want to know how many cells it take to sum N. Please see following example:
number | cells to sum of 100
100 | 1
50 | 2
20 | 3
25 | 4
15 | 4
90 | 2
10 | 2
See the last column, it find the min number of current cell + previous cells to sum of 100.
Is there a way to do so?
Thanks.
A:
In B2, array formula**:
=IFERROR(1+ROWS(A$2:A2)-MATCH(100,MMULT(TRANSPOSE(A$2:A2),0+(ROW(A$2:A2)>=TRANSPOSE(ROW(A$2:A2)))),-1),"Not Possible")
Copy down as required.
Change the hard-coded threshold value (100 here) as required.
As way of an explanation as to the part:
MMULT(TRANSPOSE(A$2:A2),0+(ROW(A$2:A2)>=TRANSPOSE(ROW(A$2:A2))))
using the data provided and taking the version of the above from B5, i.e.:
MMULT(TRANSPOSE(A$2:A5),0+(ROW(A$2:A5)>=TRANSPOSE(ROW(A$2:A5))))
the first part of which, i.e.:
TRANSPOSE(A$2:A5)
returns:
{100,50,20,25}
and the second part of which, i.e.:
0+(ROW(A$2:A5)>=TRANSPOSE(ROW(A$2:A5)))
resolves to:
0+({2;3;4;5}>=TRANSPOSE({2;3;4;5}))
i.e.:
0+({2;3;4;5}>={2,3,4,5})
which is:
0+{TRUE,FALSE,FALSE,FALSE;TRUE,TRUE,FALSE,FALSE;TRUE,TRUE,TRUE,FALSE;TRUE,TRUE,TRUE,TRUE})
which is:
{1,0,0,0;1,1,0,0;1,1,1,0;1,1,1,1}
An understanding of matrix multiplication will tell us that:
MMULT(TRANSPOSE(A$2:A5),0+(ROW(A$2:A5)>=TRANSPOSE(ROW(A$2:A5))))
which is here:
MMULT({100,50,20,25},{1,0,0,0;1,1,0,0;1,1,1,0;1,1,1,1})
is:
{195,95,45,25}
i.e. an array whose four elements are equivalent to, respectively:
=SUM(A2:A5)
=SUM(A3:A5)
=SUM(A4:A5)
=SUM(A5:A5)
Regards
**Array formulas are not entered in the same way as 'standard' formulas. Instead of pressing just ENTER, you first hold down CTRL and SHIFT, and only then press ENTER. If you've done it correctly, you'll notice Excel puts curly brackets {} around the formula (though do not attempt to manually insert these yourself).
|
{
"pile_set_name": "StackExchange"
}
|
Q:
BigQuery: How to use run_date in the query when back-filling
I want to take data from yesterday's firebase analytics events table, transform the data and update an existing partitioned table with the same suffix as the origin events table.
For the destination table, I'm able to use a template: shares_{run_time-24h|"%Y%m%d"}
But in the query itself, all I could think of was:
WHERE
_TABLE_SUFFIX = FORMAT_DATE('%Y%m%d', DATE_SUB(CURRENT_DATE(), INTERVAL 1 DAY))
Which works great when running manually but obviously generates yesterday's date when I use backfill (rather than the backfill run_date)
I tried using @run_date w/ & w/o offset but it's not a valid query.
A:
You should be able to pass @run_date as an argument to FORMAT_DATE:
WHERE _TABLE_SUFFIX = FORMAT_DATE('%Y%m%d', @run_date)
This works since @run_date has type DATE, so you can use it wherever a DATE expression is valid.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Postgresql, get string after multiple ':' character
I have the following column with entries
01:02:02:02
02:01:100:300
128:02:12:02
input
I need a way to choose parts I want to display like
01:02:02
02:01:100
128:02:12
output
or
01:02
02:01
128:02
I tried suggested solutions in similar questions without success like
select substring(column_name, '[^:]*$') from table_name;
how could this work?
A:
To get the first three parts, you can use
SELECT substring(column_name FROM '^(([^:]*:){2}[^:]*)')
FROM table_name;
For the first two parts, omit the {2}. For the first four parts, make it {3}.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Crypto++ giving a compiler error in algparam.h
I have the following lines in a rather large file:
#include <sha.h>
#include <hex.h>
Which, when compiled, throws this compiler error:
1>d:\work\app\tools\cryptopp\algparam.h(322): error C2061: syntax error : identifier 'buffer'
1> d:\work\app\tools\cryptopp\algparam.h(321) : while compiling class template member function 'void CryptoPP::AlgorithmParametersTemplate<T>::MoveInto(void *) const'
1> with
1> [
1> T=bool
1> ]
1> d:\work\app\tools\cryptopp\algparam.h(329) : see reference to class template instantiation 'CryptoPP::AlgorithmParametersTemplate<T>' being compiled
1> with
1> [
1> T=bool
1> ]
I'm pretty sure I'm forgetting something, but I'm not sure what. If I don't include hex.h, I don't have any problems and I get a SHA256 hash just fine, but when I do include hex.h, the error pops up.
Edit
In case anyone wonders, from algparam.h of Crypto++ toolkit:
void MoveInto(void *buffer) const //<=== line 320
{
AlgorithmParametersTemplate<T>* p = new(buffer)
AlgorithmParametersTemplate<T>(*this);
}
CRYPTOPP_DLL_TEMPLATE_CLASS AlgorithmParametersTemplate<bool>; // <== line 329
Edit: Removed unrelated code
A:
I fixed the problem by temporarily undefining new, which was defined as a macro to some extra debugging code.
#pragma push_macro("new")
#undef new
/* #includes for Crypto++ go here */
#pragma pop_macro("new")
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Run exe form another exe and pass parameters
I am trying to make a program that calls another .exe and pass parameters to it. My case is to create a program to open two (dosbox.exe) and pass commands to it to run executables. I am trying to automate the testing process.
I have tried code like this
ShellExecute(NULL, "open", "C:\chat\DOSBox 0.74.lnk.exe", NULL, NULL, SW_SHOWDEFAULT);
But it didn't even work. Any help?
A:
How about: std::system( "dosbox -c myCommand" ); (assuming dosbox.exe and your custom myCommand.exe are in your path)?
To start two in the background, do:
std::system( "start dosbox -c myCommand1" );
std::system( "start dosbox -c myCommand2" );
// Program has launched these in the background
// and continues execution here.
Alternately, you could spin up a thread for each std::system() call:
auto cmd1 = std::async( [] { std::system( "dosbox -c myCommand1" ); } );
auto cmd2 = std::async( [] { std::system( "dosbox -c myCommand2" ); } );
// Program is launching these in the background
// and continues execution here.
You may also want to check the return value for each std::system() call to make sure it succeeded.
Update: You ask how to run two commands in the foreground in a single dosbox, which is located in another folder. You can embed the full path like this:
std::system( "c:\\MyDosBox\\dosbox.exe -c c:\\My\\Progams\\myCommand1.exe p1 p2 && c:\\Other\\myCommand2.exe p3 p4" );`
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Existence of nonstandard elementary extensions of $PA$?
My question follows from the 1958 result of MacDowell–Specker (located originally in Modelle der Arithmetik, J. Symbolic Logic Volume 38, Issue 4 (1973), 651-652) of the proof of the following theorem:
Theorem 1. Every model $M$ of $PA$ has a proper elementary end extension $E_M\subset M$, where we take $\subset$ to mean $E_M\subseteq M$ and $\neg (E_M=M$).
The question I ask is broken into two parts which I believe are answerable in one post. Intuitively it feels that they are related as questions by the Macdowell-Specker as stated below:
Theorem 2. Every nonstandard model $N$ of $PA$ has a proper elementary end extension with $E_N\subseteq N$.
Question 1) Following from the existence of the proper end extension $E_M$ by the Macdowell-Specker theorem, can one assume that $E_N\models\mathrm{PA}$ if each $E_i\subset N$ is nonstandard? Perhaps more briefly, I ask if $E_N\models\mathrm{PA}$ still holds when $E_N$ is not a proper elementary extension of $N$.
Question 2) By the assumption of the "nonstandardess" of $E$, is it a sufficient condition for [Theorem 2] that if $E_N\models\mathrm{PA}$ then $N$ has its proper elementary end extensions $|E_N|\leq \omega$?
Thank you for your help, and I apologize if only one question should be asked in this context. The only similar question on the website I can find possibly related to the above is https://mathoverflow.net/questions/141845/elementary-end-extensions-of-models-of-peano-arithmetic-in-uncountable-languages, but this question concerns uncountability, which I do not feel is straightforwardly related to my question.
A:
I think I understand the question well enough to answer now.
Every model is a (proper, by definition) elementary end-extension of itself, so it's only interesting to prove that there are also elementary end-extensions which aren't proper.
It follows easily from the ordinary proof of Macdowell-Specker that when $M$ is a countable model of PA, $M$ has a countable proper elementary end-extensions.
It follows that if $M$ is countable, there must also be uncountable elementary end-extensions: let $M=M_0$, given $M_\alpha$, let $M_{\alpha+1}$ be a proper elementary end-extension of $M_\alpha$, and when $\lambda$ is a limit ordinal, le $M_\lambda=\bigcup_{\alpha<\lambda}M_\alpha$. Then $M_{\omega_1}$ is an uncountable elementary end-extension of $M$.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
SSIS-handling non English characters-Truncation error
loading non-English characters like Ç,è,Ü,Å from UTF-8 encoded text file into SQL Server Table field with Varchar data type SSIS Flat File connection manager throws data truncation errors even though number of characters in flat file is same as defined as in SQL table field
Example:like say there is 20 non english characters,even though the table is defined as varchar(20) it throws a truncation error.Any idea to resolve the issue
A:
You cant put unicode characters into a varchar field, it will corrupt them, if it works at all. Use nvarchar(20) instead.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Correctly depicting trends in matplotlib python like spreadsheet charts
I have a pretty simple dataset containing dates and petrol prices.
That plots like the below image in WPS Spreadsheet
But the same dataset gets plotted in matplotlib python as follows
The dataframe on which I am plotting is
date price
0 2018-05-12 75.09
1 2018-05-13 75.09
2 2018-05-14 75.28
3 2018-05-15 75.42
4 2018-05-16 75.57
5 2018-05-17 75.78
6 2018-05-18 76.06
7 2018-05-19 76.34
8 2018-05-20 76.66
9 2018-05-21 76.98
10 2018-05-22 77.27
11 2018-05-23 77.55
12 2018-05-24 77.84
13 2018-05-25 78.19
14 2018-05-26 78.32
15 2018-05-27 78.46
16 2018-05-28 78.61
17 2018-05-29 78.76
18 2018-05-30 78.19
19 2018-05-31 78.68
20 2018-06-01 78.60
21 2018-06-02 78.51
22 2018-06-03 78.43
23 2018-06-04 78.43
24 2018-06-05 78.16
25 2018-06-06 78.05
26 2018-06-07 77.97
27 2018-06-08 77.77
28 2018-06-09 77.38
29 2018-06-10 77.15
30 2018-06-11 76.96
31 2018-06-12 76.82
32 2018-06-13 76.82
Here's my code I am using to plot
import matplotlib.pyplot as plt
import Datasets as DS
df = DS.getDataSet_petrol("13-06-2018")
plt.plot(df['date'],df['price'])
plt.show()
Apparently looking the spreadsheet chart shows non-linnear trends while matplotlib shows a linnear trend.
This confuses me about the correct regression model to use linear or polynomial regressions.
So my main question is :
How can I make the python plot look like the spreadsheet one?
A:
It seems the problem is caused by having string objects in your df["price"].
This can be solved by converting it to float prior to plotting it.
plt.plot(df['date'],df['price'].astype('float'))
Or even before doing anything with the data:
df['price'] = df['price'].astype('float')
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How do I use annotations to define different types of relationships in Hibernate 4 and Spring?
I have two classes, Foo and Bar, as follows:
public class Foo {
private Long fooId;
private Bar bar;
//Yes, this doesn't actually make any sense,
//having both a list and a single object here, its an example.
private List<Bar> bars;
}
public class Bar {
private Long barId;
private Foo foo;
}
How do I implement a (uni-directional/bi-directional) one-to-many, many-to-one or many-to-many relationship using annotations for Hibernate 4 for these classes?
Also how do I configure my one-to-many for orphan removal, lazy loading and what causes a LazyInitialiaizationException when dealing with collections and how to solve the problem?
A:
Creating Relationships with Annotations
Assume all classes annotated with @Entity and @Table
Uni-directional One to One Relationship
public class Foo{
private UUID fooId;
@OneToOne
private Bar bar;
}
public class Bar{
private UUID barId;
//No corresponding mapping to Foo.class
}
Bi-Directional One to One Relationship managed by Foo.class
public class Foo{
private UUID fooId;
@OneToOne(cascade = CascadeType.ALL)
@JoinColumn(name = "barId")
private Bar bar;
}
public class Bar{
private UUID barId;
@OneToOne(mappedBy = "bar")
private Foo foo;
}
Uni-Directional One to Many Relationship using user managed join table
public class Foo{
private UUID fooId;
@OneToMany
@JoinTable(name="FOO_BAR",
joinColumns = @JoinColumn(name="fooId"),
inverseJoinColumns = @JoinColumn(name="barId"))
private List<Bar> bars;
}
public class Bar{
private UUID barId;
//No Mapping specified here.
}
@Entity
@Table(name="FOO_BAR")
public class FooBar{
private UUID fooBarId;
@ManyToOne
@JoinColumn(name = "fooId")
private Foo foo;
@ManyToOne
@JoinColumn(name = "barId")
private Bar bar;
//You can store other objects/fields on this table here.
}
Very commonly used with Spring Security when setting up a User object who has a list of Role's that they can perform. You can add and remove roles to a user without having to worry about cascades deleting Role's.
Bi-directional One to Many Relationship using foreign key mapping
public class Foo{
private UUID fooId;
@OneToMany(mappedBy = "bar")
private List<Bar> bars;
}
public class Bar{
private UUID barId;
@ManyToOne
@JoinColumn(name = "fooId")
private Foo foo;
}
Bi-Directional Many to Many using Hibernate managed join table
public class Foo{
private UUID fooId;
@OneToMany
@JoinTable(name="FOO_BAR",
joinColumns = @JoinColumn(name="fooId"),
inverseJoinColumns = @JoinColumn(name="barId"))
private List<Bar> bars;
}
public class Bar{
private UUID barId;
@OneToMany
@JoinTable(name="FOO_BAR",
joinColumns = @JoinColumn(name="barId"),
inverseJoinColumns = @JoinColumn(name="fooId"))
private List<Foo> foos;
}
Bi-Directional Many to Many using user managed join table object
Commonly used when you want to store extra information on the join object such as the date the relationship was created.
public class Foo{
private UUID fooId;
@OneToMany(mappedBy = "bar")
private List<FooBar> bars;
}
public class Bar{
private UUID barId;
@OneToMany(mappedBy = "foo")
private List<FooBar> foos;
}
@Entity
@Table(name="FOO_BAR")
public class FooBar{
private UUID fooBarId;
@ManyToOne
@JoinColumn(name = "fooId")
private Foo foo;
@ManyToOne
@JoinColumn(name = "barId")
private Bar bar;
//You can store other objects/fields on this table here.
}
Determining which side of the bi-directional relationship 'owns' the relationship:
This is one of the trickier aspects of working out Hibernate relationships because Hibernate will operate correctly no matter which way to set up the relationship. The only thing that will change is which table the foreign key is stored on. Generally the object that you have a collection of will own the relationship.
Example: A User object has a list of Roles declared on it. In most applications, the system will be manipulating instances of the User object more often than instances of the Roles object. Hence I would make the Role object the owning side of the relationship and manipulate the Role objects through the list of Role's on a User by cascade. For a practical example see the bi-directional One to Many example. Typically you will cascade all changes in this scenario unless you have a specific requirement to do otherwise.
Determining your fetchType
Lazily fetched collections have resulted in more issues on SO than I care to look at because by default Hibernate will load related objects lazily. It doesn't matter if the relationship is a one-to-one or many-to-many as per the Hibernate docs:
By default, Hibernate uses lazy select fetching for collections and lazy proxy fetching for single-valued associations. These defaults make sense for most associations in the majority of applications.
Consider this my two cents on when to use fetchType.LAZY vs fetchType.EAGER on your objects. If you know that 50% of the time you won't need to access the collection on your parent object, I'd be using fetchType.LAZY.
The performance benefits are of this are huge and only grow as you add more objects to your collection. This is because for an eagerly loaded collection, Hibernate does a ton of behind the scenes checking to ensure that none of your data is out of date. While I do advocate using Hibernate for collections, be aware that there is a performance penalty** for using fetchType.EAGER. However, take our Person object example. Its fairly likely that when we load a Person we will want to know what Roles they perform. I will usually mark this collection as fetchType.EAGER. DON'T REFLEXIVELY MARK YOUR COLLECTION AS fetchType.EAGER SIMPLY TO GET AROUND A LazyInitializationException. Not only is it bad for performance reasons, it generally indicates that you have a design issue. Ask yourself, should this collection actually be an eagerly loaded collection, or am I doing this just to access the collection in this one method. Hibernate has ways around this, that doesn't impact the performance of your operations quite as much. You can use the following code in your Service layer if you want to initialize a lazily loaded collection just for this one call.
//Service Class
@Override
@Transactional
public Person getPersonWithRoles(UUID personId){
Person person = personDAO.find(personId);
Hibernate.initialize(person.getRoles());
return person;
}
The call to Hibernate.initialize forces the creation and loading of the collection object. However, be careful, if you only pass it the Person instance, you will get a proxy of your Person back. See the documentation for more information. The only downside to this method is that you have no control over how Hibernate will actually fetch your collection of objects. If you want to control this, then you can do so in your DAO.
//DAO
@Override
public Person findPersonWithRoles(UUID personId){
Criteria criteria = sessionFactory.getCurrentSession().createCritiera(Person.class);
criteria.add(Restrictions.idEq(personId);
criteria.setFetchMode("roles", FetchMode.SUBSELECT);
}
The performance here depends on what FetchMode you specify. I've read answers that say to use FetchMode.SUBSELECT for performance reasons. The linked answer goes into more detail if you are really interested.
If you want to read me as I repeat myself, feel free to check out my other answer here
Determining Cascade Direction
Hibernate can cascade operations either or both ways in a bi-directional relationship. So if you have a List of Role's on a User you can cascade changes to Role's in both directions. If you change the name of a particular Role on a User Hibernate can automatically update the associated Role on the Role Table.
However this is not always desired behaviour. If you think about it, in this case, making changes to Role's based on changes to User doesn't make any sense. However it makes sense going in the opposite direction. Change a Role's name on the Role object itself, and that change can be cascaded to all User objects that have that Role on it.
In terms of efficiency, it makes sense to create/update Role objects by saving the User object that they belong to. This means you would mark your @OneToMany annotation as the cascading one. I'll give an example:
public User saveOrUpdate(User user){
getCurrentSession.saveOrUpdate(user);
return user;
}
In the above example, Hibernate will generate a INSERT query for the User object, and then cascade the creation of the Role's once the User has been inserted into the database. These insert statements will then be able to use the PK of the User as their foreign key, so you would end up with N + 1 insert statements, where N is the number of Role objects in the list of users.
Conversely if you wanted to save the individual Role objects cascading back to the User object, could be done:
//Assume that user has no roles in the list, but has been saved to the
//database at a cost of 1 insert.
public void saveOrUpdateRoles(User user, List<Roles> listOfRoles){
for(Role role : listOfRoles){
role.setUser(user);
getCurrentSession.saveOrUpdate(role);
}
}
This results in N + 1 inserts where N is the number of Role's in the listOfRoles, but also N update statements being generated as Hibernate cascades the addition of each Role to the User table. This DAO method has a higher time complexity than our previous method, O(n) as opposed to O(1) because you have to iterate through the list of roles. Avoid this if at all possible.
In practice however, usually the owning side of the relationship will be where you mark your cascades, and you will usually cascade everything.
Orphan Removal
Hibernate can work out for you if you remove all associations to an object. Suppose you have a User who has a list of Role's and in this list are links to 5 different roles. Lets say you remove a Role called ROLE_EXAMPLE and it happens that the ROLE_EXAMPLE doesn't exist on any other User object. If you have orphanRemoval = true set on the @OneToMany annotation, Hibernate will delete the now 'orphaned' Role object from the database by cascade.
Orphan removal should not be enabled in every case. In fact, having orphanRemoval in our example above makes no sense. Just because no User can perform whatever action the ROLE_EXAMPLE object is representing, that doesn't mean that any future User will never be able to perform the action.
This Q&A is intended to complement the official Hibernate documentation, which has a large amount of XML configuration for these relationships.
These examples are not meant to be copy-pasted into production code. They are generic examples of how to create and manage various objects and their relationships using JPA annotations to configure Hibernate 4 within the Spring Framework. The examples assume that all classes have ID fields declared in the following format: fooId. The type of this ID field is not relevant.
** We recently had to abandon using Hibernate for an insert job where we were inserting <80,000+ objects into the database through a collection. Hibernate ate up all the heap memory doing checking on the collection and crashed the system.
DISCLAIMER:
I DO NOT KNOW IF THESE EXAMPLES WILL WORK WITH STANDALONE HIBERNATE
I am not in any way affiliated with Hibernate or the Hibernate dev team. I'm providing these examples so I have a reference to point to when I'm answering questions on the Hibernate tag. These examples and discussions are my based on my own opinion as well as how I develop my applications using Hibernate. These examples are in no way comprehensive. I'm basing them on the common situations I've used Hibernate for in the past.
If you encounter issues trying to implement these examples, do not comment and expect me to fix your problem. Part of learning Hibernate is learning the in's and out
's of its API. If there is a mistake with the examples, please feel free to edit them.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Are there specific non-protein substances that pathogens release into their host?
Reading research articles, I have found out that proteins called effectors get released into the host cell when a pathogen attacks a host. My question is, whether pathogens also release non-protein substances?
Have these substances been extensively studied and classified? Is there a list of such compounds? Are these compounds unique to pathogens?
A:
Sticking my neck out (and expecting it to be bitten by a black swan) it appears that all the examples of toxins secreted by bacterial pathogens when they infect an animal host (exotoxins) are proteins.
However fungi secrete a variety of exotic (and often very nasty) small non-protein molecules (mycotoxins). It’s not clear from the question whether you would be interested in these systems as they differ somewhat from those involving bacteria. One difference from bacterial toxins is that fungal toxins not secreted inside an infected cell, but just into their environment. Thus, cercosporin is secreted onto the surface of plants on which Cercospora reside and may be taken up through lesions in the plant. However it is not clear whether the plant is the main target of such toxins, rather than bacterial ‘foes’. So the host/pathogen concept is less clear in this context.
A similarly ambiguous host/pathogen situation would appear to exists with toxins such as saxitoxin, the paralytic shellfish toxin secreted by certain marine algae and cyanobacteria.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Javascript: cannot read property value of null
I keep receiving the error "cannot read property value of null" in my javascript. Originally the error was occurring when assigning a variable the element value:
var breakCal = document.getElementById("breakfast").value;
I placed the assignments in conditionals and now I'm receiving the error when trying to change the css property of those elements here:
if(passBreakCal == false){ document.getElementById("breakfast").style.borderColor="red"; }
does anyone have any suggestions?
function verifyDailySum2(){
if(document.getElementById("breakfast") !== null){
var breakCal = document.getElementById("breakfast").value;
}
else{
var breakCal = null;
}
if (document.getElementById("lunch") !== null) {
var lunchCal = document.getElementById("lunch").value;
}
else{
var lunchCal = null;
}
if (document.getElementById("dinner") !== null) {
var dinnerCal = document.getElementById("dinner").value;
}
else {
var dinnerCal = null;
}
if(document.getElementById("snack") !== null){
var snackCal = document.getElementById("snack").value;
}
else{
var snackCal = null;
}
if(document.getElementById("weight") !== null){
var weight = document.getElementById("weight").value;
}
else{
var weight = null;
}
alert(breakCal + "$" + lunchCal + "$" + dinnerCal + "$" + snackCal + "$" + weight);
var pattern = /^[0-9]+$/;
var passBreakCal = pattern.test(breakCal);
var passLunchCal = pattern.test(lunchCal);
var passDinnerCal = pattern.test(dinnerCal);
var passSnackCal = pattern.test(snackCal);
var passWeight = pattern.test(weight);
if(passBreakCal == false || passLunchCal == false || passDinnerCal == false ||
+ passSnackCal == false || passWeight == false){
alert("One of the fields is empty. Or contains characters other than numbers");
if(passBreakCal == false){
document.getElementById("breakfast").style.borderColor="red";
}
if(passLunchCal == false){
document.getElementById("lunch").style.borderColor="red";
}
if(passDinnerCal == false){
document.getElementById("dinner").style.borderColor="red";
}
if(passSnackCal == false){
document.getElementById("snack").style.borderColor="red";
}
if(passWeight == false){
document.getElementById("weight").style.borderColor="red";
}
return false;
}
else{
return true;
}
}
Here's the php page calling the function. All markup is bootstrap.
<?php
include('session.php');
include('header.php');
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns = "http://www.w3.org/1999/xhtml">
<head>
<title> Workout Daily Summary </title>
<link href = "bootstrap-theme.css" rel = "stylesheet" type ="text/css"/>
<link href = "bootstrap.css" rel = "stylesheet" type ="text/css"/>
<link href = "is448_project.css" rel = "stylesheet" type ="text/css"/>
<link href = "bootstrap.min.css" rel = "stylesheet" type ="text/css"/>
<script type="text/javascript" src="dailySum.js"></script>
</head>
<body>
<div class = "row">
<div class = "col-sm-4">
<div class = "border">
<h3> Daily Summary: </h3>
<p>
Please list calories consumed for each meal today:
</p>
<form action = "dailySumTable.php" method="post">
Breakfast: <input type = "text" name = "breakfast" size = "4" maxlength = "4"/>
<br/> <br/>
Lunch: <input type = "text" name = "lunch" size = "4" maxlength = "4"/>
<br/> <br/>
Dinner: <input type = "text" name = "dinner" size = "4" maxlength = "4"/>
<br/> <br/>
Snack: <input type = "text" name = "snack" size = "4" maxlength = "4"/>
<br/> <br/>
Activities Completed Today:<br/>
<select name = "activity">
<option value="Running">Running</option>
<option value="Walking">Walking</option>
<option value="Weight_Lifting">Weight Lifting</option>
<option value="Swimming">Swimming</option>
<option value="Biking">Biking</option>
<option value="Yoga">Yoga</option>
</select> Time (in minutes): <input type = "text" name = "time1" size = "4" maxlength = "4"/><br/><br/>
<select name = "activity2">
<option value="Biking">Biking</option>
<option value="Running">Running</option>
<option value="Walking">Walking</option>
<option value="Weight_Lifting">Weight Lifting</option>
<option value="Swimming">Swimming</option>
<option value="Yoga">Yoga</option>
</select> Time (in minutes): <input type = "text" name = "time2" size = "4" maxlength = "4"/><br/><br/>
<select name = "activity3">
<option value="Weight_Lifting">Weight Lifting</option>
<option value="Running">Running</option>
<option value="Walking">Walking</option>
<option value="Swimming">Swimming</option>
<option value="Biking">Biking</option>
<option value="Yoga">Yoga</option>
</select> Time (in minutes): <input type = "text" name = "time3" size = "4" maxlength = "4"/><br/><br/>
<select name = "activity4">
<option value="Swimming">Swimming</option>
<option value="Running">Running</option>
<option value="Walking">Walking</option>
<option value="Weight_Lifting">Weight Lifting</option>
<option value="Biking">Biking</option>
<option value="Yoga">Yoga</option>
</select> Time (in minutes): <input type = "text" name = "time4" size = "4" maxlength = "4"/><br/><br/>
<select name = "activity5">
<option value="Other">Other</option>
<option value="Swimming">Swimming</option>
<option value="Running">Running</option>
<option value="Walking">Walking</option>
<option value="Weight_Lifting">Weight Lifting</option>
<option value="Biking">Biking</option>
<option value="Yoga">Yoga</option>
</select> Time (in minutes): <input type = "text" name = "time5" size = "4" maxlength = "4"/><br/> <br/>
Daily Weigh in: <br/> <br/>
Weight:<input type = "text" name = "weight" size = "4" maxlength = "4"/>
<br/>
<input type = "reset" value = "Clear" />
<input type = "submit" value = "Submit" onclick = "return verifyDailySum2()" />
</form>
</div>
</div>
<div class = "col-sm-7"> <img class = "curls" src="salad.jpg" alt ="salad"/> </div>
</div>
</body>
</html>
A:
There's no element with the id "breakfast". Only the name of the input is set to that value.
Breakfast: <input type="text" name="breakfast" size="4" maxlength="4"/>
Update your element so that it has id="breakfast".
<!----------------------------vvvvvvvvvvvvv--->
Breakfast: <input type="text" id="breakfast" name="breakfast" size="4" maxlength="4"/>
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How to specify additional include directories for msbuild.exe
I am attempting to install the nodejs module ibm_db. The issue I am having is that in order to install this module node-gyp needs to build it using msbuild, but it won't detect some header files I have installed.
How do I add the directory of my additional header files to some path so hatt msbuild.exe will find them when trying to compile any project? On linux I simply set cpath= and everything build just fine.
Thanks!
A:
MSBuild exposes special properties for resolving references in build time.
You can set AssemblySearchPaths and AdditionalLibPaths.
E.g. msbuild your.sln /p:AssemblySearchPaths="C:\Dev\Lib\Foo;C:\Dev\Lib\Bar;"
See Common MSBuild Project Properties
|
{
"pile_set_name": "StackExchange"
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.