text
stringlengths 64
89.7k
| meta
dict |
---|---|
Q:
Is every group isomorphic to some nontrivial quotient group?
For any group $G$, does there exist a group $H$ and a nontrivial normal subgroup $N$ of $H$ such that $H/N\cong G$?
A:
Yes, for example $H:=G\times G$ and $N:=G\times e$
(if $G$ is trivial just take any nontrivial group $H$ and $H=N$, for example $H=N=\Bbb Z $)
A:
Yes, if $N$ (for nontrivial) is any nontrivial group (for instance the one with two elements), then the projection $H=G\times N\to G$ on the first factor has kernel $N\subseteq H$, so $G\cong H/N$.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Linkind date with many folders
I have a CSV folder containing the date (from 7/8/2005 to 9/27/2013).
So the csv contains only one column with the date
I have 50 other folders containing the same structure.
The columns are :
Date [structure of the date is the same as my date.csv ]
Open
High
Low
Close
Volume
Adj. Close
Symbol
I've bolded the columns I'm interested in to get my final output
I give 2 files of those folders :
AI.PA.csv
ALV.DE.csv
My aim (question) is to get a final new file with x column :
Date (same structure date as date.csv)
Symbol AI.PA
Symbol AI.DE
Symbol of all the other files I have
So the column should contain the symbol as column header and the closing price if there is a closing price for the ad hoc date. And if tehre is no closing price it should contain nothing.
I really don't know how to solve the issue. I'm open to solve my issue with any "open source" solution (ideally SQL, Python, R)
A:
Acutally I just solve my issue by using a simple Pivot table on Excel
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How to iterate python windowed() to last element?
According to the more_itertools.windowed specification, you can do:
list(windowed(seq=[1, 2, 3, 4], n=2, step=1))
>>> [(1, 2), (2, 3), (3, 4)]
But what if I want to run it all to the end? Is it possible to get:
>>> [(1, 2), (2, 3), (3, 4), (4, None)]
A:
A workaround but not the best solution is to append None with the sequence.
list(windowed(seq=[1, 2, 3, 4,None], n=2, step=1))
|
{
"pile_set_name": "StackExchange"
}
|
Q:
It is possible to configure both pppoe and dhcp on the same interface?
I would like to setup on a debian 9 machine inside the /etc/interfaces file both the dhcp and pppoe config.
So that I can move my machine with it's eth0 and attach it:
to a friend house that has pppoe, in this case the machine see pppoe available and establish a connection with it (I have the provider config file already setup on the machine)
to my house where I have my router with dhcp, and I benefit from dhcp for getting my IP address
Is it possible to do that?
Should I specify inside interfaces both pppoe and inet dhcp?
A:
To answer your question, yes it should be possible to use both dynamic and static IP interface configurations. You do this by creating virtual interfaces to use the same physical interface. Each virtual interface will need to be configured properly to your network's needs.
I am not as familiar with PPPoE but I have found some links that could help you. This post covers how to configure having both static and dynamic interfaces. Here is the Official Debian Wiki on how to set up PPPoE. Again I suggest you read through the Debian Wiki on how to do network configuration using different interface settings.
According to the aforementioned links, your /etc/network/interfaces should look something like this:
auto lo eth0 eth0:0
iface lo inet loopback
iface eth0 inet dhcp
iface eth0:0 inet manual
auto dsl-provider
iface dsl-provider inet ppp
pre-up /sbin/ifconfig eth0:0 up
provider dsl-provider
Don't forget to run pppoeconf to generate and/or modify /etc/ppp/peers/dsl-provider, /etc/ppp/*ap-secrets files and /etc/network/interfaces.
It is best, in most cases, to keep the suggested answers
I would substitute eth0 with whatever the name of your device actually appears by default to keep things simple. However I highly suggest you read through the Debian manual on how to set up networking before you do anything. Remember to figure out where your network is getting its configuration information from and make the appropriate changes there. Best of Luck!
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Cocoa Touch Question. Should [NSMutableArray array] be retained?
Here is the gist of some code I'm writing. I'm concerned that I am not properly addressing the retain/release issues with the array class method on NSMutableArray. Is the following actually leaking memory?
for(a while) {
// do stuff
NSMutableArray *a = nil;
// do stuff
if (!a) {
a = [NSMutableArray array];
}
} // for(a while)
A:
You wouldn't leak memory in this code, and releasing the array yourself will cause a crash when the array is autoreleased at the end of the run loop.
Most Cocoa classes provide a couple of ways of making a new object, and are very consistent with this convention:
[[NSSomeObject alloc] init] : you are responsible for releasing the object (instance method).
[NSSomeObject someObject] : the object will be autoreleased for you, usually at the end of the run loop (class method). It's roughly equivalent to [[[NSSomeObject alloc] init] autorelease].
The proper use of the instance method would be:
a = [[NSMutableArray alloc] init];
// do stuff
[a release];
The proper use of the class method would be:
a = [NSMutableArray array];
// do stuff, array is in the autorelease pool
Note that Apple has recommended you stay away from the convenience methods as much as possible to improve performance. This is controversial advice, may not save much processor time, and separates the alloc-init from the release on an object you may not actually care much about keeping.
A:
From the Cocoa Memory Managment Rules:
You take ownership of an object if you create it using a method whose name begins with “alloc” or “new” or contains “copy” (for example, alloc, newObject, or mutableCopy), or if you send it a retain message. You are responsible for relinquishing ownership of objects you own using release or autorelease. Any other time you receive an object, you must not release it.
Therefore with the line:
a = [NSMutableArray array];
you do not take ownership of the array, and it will be passed to you autoreleased. The memory will be handled for you automatically by the autorelease pool, and once it is no longer being used, it will be released for you. If you want to keep the array outside the current event, however, you must retain it, otherwise it will be released for you.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Why does the wallet contract convert addresses to integers?
In the multiowned part of the wallet contract, owners are stored in a uint array, such as in line 59 in the constructor. Here is a relevant excerpt:
contract multiowned {
// METHODS
function multiowned(address[] _owners, uint _required) {
m_numOwners = _owners.length + 1;
m_owners[1] = uint(msg.sender);
m_ownerIndex[uint(msg.sender)] = 1;
for (uint i = 0; i < _owners.length; ++i)
{
m_owners[2 + i] = uint(_owners[i]);
m_ownerIndex[uint(_owners[i])] = 2 + i;
}
m_required = _required;
}
// FIELDS
uint[256] m_owners;
mapping(uint => uint) m_ownerIndex;
// why not address[] m_owners and mapping(address => uint) m_ownerIndex ?
}
Why not store them in address-type variables? Is there a special reason for this? Does it make the storage lighter?
Thanks,
A:
I think in the code he uses uint instead address because as you know an array needs an integer as index.and the idea behind if i understand well the snippet it is to return the index of the participant or an owner (while there is multiple owners) using its address without using a loop.
for example if the first sender is 0X123 and the "nth" adress is 0x555
but we don't know the order n.
we need just to call m_ownerIndex[uint(0x555)] to get the value of n without a loop.
if you use an address array for the same example you will need something like
for(int i=0,i<;i++)
{
if (m_ownerIndex[i]==0X555)
return i;break;
}
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Why do I have white spacing around my positioned nav?
This my be a noob quesston but, Why do I have white spacing around my positioned nav?I created a nav that appears at the bottom for moblie devices and I have what looks like top and bottom padding in my nav element, but when I pull up the dev tools there is no padding or anything I would think would cause this, What is it and how can I remove it?
https://jsfiddle.net/7am3d06L/
<html>
<head>
<title>Somalia</title>
<meta charset="utf-8">
<meta name="keywords" content="css, html, test">
<meta name="description" content="This is an html and css review">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<style>
*{
text-align: center;
}
h1,nav{
font-family: arial;
}
#headerNav{
display: none;
}
#footerNav{
position: fixed;
bottom: 0px;
width: 100%;
background-color: white;
padding: 0;
}
nav ul{
padding: 0;
}
nav li{
list-style-type: none;
border: 1px solid black;
margin: 0;
}
nav a{
text-decoration: none;
font-weight: 700;
}
nav a, nav a:visited {
color: green;
}
</style>
</head>
<body>
<header>
<h1>Somalia</h1>
<nav id="headerNav">
<ul>
<li><a href="index.html">Home</a></li>
<li><a href="historyAndPolitics.html">History And Politics</a></li>
<li><a href="Geography">Geography</a></li>
<li><a href="economy.html">Economy</a></li>
<li><a href="cultureAndDemographics.html">Culture And Demographics</a></li>
</ul>
</nav>
</header>
<article>
<p>
Somalia (/səˈmɑːliə, soʊ-, -ljə/ so-mah-lee-ə; Somali: Soomaaliya; Arabic: الصومال aṣ-Ṣūmāl),
officially the Federal Republic of Somalia[1] (Somali: Jamhuuriyadda Federaalka Soomaaliya, Arabic:
<bdi>جمهورية الصومال الفيدرالية</bdi> Jumhūrīyat aṣ-Ṣūmāl al-Fidirālīyah), is a country located in the
Horn of Africa. It is bordered by Ethiopia to the west, Djibouti to the northwest, the Gulf of Aden to the
north, the Indian Ocean to the east, and Kenya to the southwest. Somalia has the longest coastline on
Africa's mainland, and its terrain consists mainly of plateaus, plains and highlands. Climatically, hot
conditions prevail year-round, with periodic monsoon winds and irregular rainfall.
</p>
<p>Somalia has an estimated population of around 12.3 million. Around 85% of its residents are ethnic
Somalis,[3] who have historically inhabited the northern part of the country. Ethnic minorities are largely
concentrated in the southern regions. The official languages of Somalia are Somali and Arabic, both of
which belong to the Afroasiatic family. Most people in the country are Muslim, with the majority being Sunni.
</p>
<p>In antiquity, Somalia was an important commercial centre. It is among the most probable locations of the
fabled ancient Land of Punt. During the Middle Ages, several powerful Somali empires dominated the regional
trade, including the Ajuran Empire, the Adal Sultanate, the Warsangali Sultanate, and the Geledi Sultanate.
In the late 19th century, through a succession of treaties with these kingdoms, the British and Italian
empires gained control of parts of the coast and established the colonies of British Somaliland and Italian
Somaliland.[19][20] In the interior, Mohammed Abdullah Hassan's Dervish State repelled the British Empire
four times and forced it to retreat to the coastal region, before succumbing to defeat in 1920 by British
airpower.[22] The toponym Somalia was coined by the Italian explorer Luigi Robecchi Bricchetti (1855–1926).
Italy acquired full control of the northeastern, central and southern parts of the area after successfully
waging the so-called Campaign of the Sultanates against the ruling Majeerteen Sultanate and Sultanate of
Hobyo.[20] Italian occupation lasted until 1941, yielding to British military administration. British
Somaliland would remain a protectorate, while Italian Somaliland in 1949 became a United Nations
Trusteeship under Italian administration, the Trust Territory of Somaliland. In 1960, the two regions
united to form the independent Somali Republic under a civilian government.</p>
<p>The Supreme Revolutionary Council seized power in 1969 and established the Somali Democratic Republic.
Led by Mohamed Siad Barre, this government later collapsed in 1991 as the Somali Civil War broke out.
Various armed factions began competing for influence in the power vacuum, particularly in the south.
During this period, due to the absence of a central government, Somalia was a "failed state", and residents
returned to customary and religious law in most regions. A few autonomous regions, including the
Somaliland and Puntland administrations emerged in the north. The early 2000s saw the creation of fledgling
interim federal administrations. The Transitional National Government (TNG) was established in 2000,
followed by the formation of the Transitional Federal Government (TFG) in 2004, which reestablished
national institutions such as the military. In 2006, the TFG, assisted by Ethiopian troops,
assumed control of most of the nation's southern conflict zones from the newly formed Islamic Courts Union
(ICU). The ICU subsequently splintered into more radical groups such as Al-Shabaab, which battled the TFG
and its AMISOM allies for control of the region.</p>
<p>By mid-2012, the insurgents had lost most of the territory that they had seized. In 2011–2012, a
political process providing benchmarks for the establishment of permanent democratic institutions was
launched. Within this administrative framework a new provisional constitution was passed in August 2012,
which reformed Somalia as a federation.[29] Following the end of the TFG's interim mandate the same month,
the Federal Government of Somalia, the first permanent central government in the country since the start
of the civil war, was formed[30] and a period of reconstruction began in Mogadishu. Somalia has maintained
an informal economy, mainly based on livestock, remittances from Somalis working abroad, and
telecommunications</p>
</article>
<footer>
<nav id="footerNav">
<ul>
<li><a href="index.html">Home</a></li>
<li><a href="historyAndPolitics.html">History And Politics</a></li>
<li><a href="Geography">Geography</a></li>
<li><a href="economy.html">Economy</a></li>
<li><a href="cultureAndDemographics.html">Culture And Demographics</a></li>
</ul>
</nav>
</footer>
</body>
</html>
A:
You reset the padding but you need to reset the margin also:
nav ul{
padding: 0;
margin: 0;
}
See example
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Classes and Objects. Summing the data
So here's the question:
Create a 'DISTANCE' class with:
data members: feet and inches
member functions:
• Input to input distance
• Output to output distance
• Add to add two distance objects
Write an application program with a main function to create 2 objects of DISTANCE
class, namely d1and d2. Then using object d3, sum the objects d1 and d2 and store the
sum in d3 and then display the object d3.
I tried to do it but i'm getting error messages. Can someone tell me what's wrong with my program? I'm learning it on my own. Any help will be appreciated. Thank you. :)
Here's my code for the .h file:
#ifndef DISTANCE_H
#define DISTANCE_H
#include <iostream>
using namespace std;
class Distance
{
private:
double feet_1,feet_2;
double inches_1,inches_2;
public:
double inputfeet1(double feet1);
double inputfeet2(double feet2);
double inputinch1(double inch1);
double inputinch2(double inch2);
double sumFeet(double feets);
double sumInch(double inches);
};
#endif // DISTANCE_H
This one is for the .cpp file
#include "../include/Distance.h"
#include <iostream>
using namespace std;
double Distance::inputfeet1(double feet1)
{
if(feet1 < 0)
{
cout<<"Cannot be less than zero. Default value of 0 is used.";
}
else
{
feet_1 = feet1;
}
}
double Distance::inputfeet2(double feet2)
{
if(feet2 < 0)
{
cout<<"Cannot be less than zero. Default value of 0 is used.";
}
else
{
feet_2 = feet2;
}
double Distance::inputinch1(double inch1)
{
if(inch1 < 0)
{
cout<<"Cannot be less than zero. Default value of 0 is being used.";
}
else
{
inch_1 = inch1;
}
}
double Distance::inputinch2(double inch2)
{
if(inch2 < 0)
{
cout<<"Cannot be less than zero. Default value of 0 is being used.";
}
else
{
inch_2 = inch2;
}
}
double Distance::sumFeet()
{
return feet_1 + feet_2;
}
double Distance::sumInch()
{
return inches_1 + inches_2;
}
}
And this one is the main.cpp
#include "include/Distance.h"
#include <iostream>
using namespace std;
int main()
{
Distance d1,d2,d3;
double f1,f2,I1,I2;
double sum1,sum2;
cout<<"Distance 1.";
cout<<"\nEnter the feet: ";
cin>>f1;
cout<<"Enter the inch: ";
cin>>I1;
cout<<"Distance 2.";
cout<<"\nEnter the feet: ";
cin>>f2;
cout<<"Enter the inch: ";
cin>>I2;
d1.inputfeet1(f1);
d1.inputfeet2(f2);
d2.inputinch1(I1);
d2.inputinch2(I2);
sum1 = f1 + f2;
d3.sumFeet(sum1);
cout<<"Feet: "<<d3.sumFeet();
return 0;
}
A:
I see only minor errors, and they amount to what you would class as bad punctuation in language:)
I have annotated the changes I made ion the code below: mainly you need to indent your code and ensure that you match all open brackets with a closing bracket.
The next thing to do is ensure you have correct return types. I will post better instructions on the basics tonight when I get home and have the time to post a better tutorial rather than a fix with little instructive value.
I have more correctly indented the .cpp file for distance for you and if you change the code in main.cpp to have
sum1 = d3.sumFeet();
instead of
sum1 = f1 + f2;
d3.sumFeet(sum1);
it will work with the following modifications to the remaining code:
Distance.h needs to be changed to the following:
#ifndef DISTANCE_H
#define DISTANCE_H
#include <iostream>
using namespace std;
class Distance
{
private:
double feet_1,feet_2;
double inches_1,inches_2;
public:
void inputfeet1(double feet1);
void inputfeet2(double feet2);
void inputinch1(double inch1);
void inputinch2(double inch2);
double sumFeet();
double sumInch();
};
#endif // DISTANCE_H
and Distance.cpp needs to be amended as follows:
void Distance::inputfeet1(double feet1)
{
if(feet1 < 0)
{
cout<<"Cannot be less than zero. Default value of 0 is used.";
}
else
{
feet_1 = feet1;
}
}//added this
void Distance::inputfeet2(double feet2)
{
if(feet2 < 0)
{
cout<<"Cannot be less than zero. Default value of 0 is used.";
}
else
{
feet_2 = feet2;
}
}//added this too
void Distance::inputinch1(double inch1)
{
if(inch1 < 0)
{
cout<<"Cannot be less than zero. Default value of 0 is being used.";
}
else
{
inches_1 = inch1;
}
}
void Distance::inputinch2(double inch2)
{
if(inch2 < 0)
{
cout<<"Cannot be less than zero. Default value of 0 is being used.";
}
else
{
inches_2 = inch2;
}
}
double Distance::sumFeet()
{
return feet_1 + feet_2;
}
double Distance::sumInch()
{
return inches_1 + inches_2;
}
//removed curly brace here
Tutorial Section
To achieve your aims I would utilise a more object oriented approach, it may seem like overkill for such a simple problem, however the practice will pay off when you eventually start using larger constructs and hierarchies:
Basic needs:
At the basic level you are dealing with Feet and Inches, we wont bother with them as they are effectively just different names for Doubles in your example code so they are fine as doubles.
Next we have a distance composed of Feet and Inches, so we want to do something with that.... (lets call it DistanceBase)
And then we want to do some things with two distances, we will keep the same name as you had earlier and call it Distance
So we will have a class called DistanceBase composed of Feet and Inches and a class called Distance composed of 2 DistanceBase.
DistanceBase
Header File:
As this is a conceptually trivial (not necessarily trivial in the C++ sense 1) class we can make everything be in the header file, that way it makes the code more portable and transparent, though less secure.
#pragma once
#ifndef DISTANCE_BASE_H
#define DISTANCE_BASE_H
/*
Header file for the DistanceBase class
#pragma once effectively does the same as the #ifndef loop on compilers that support it.
Both are included simply as a belt-and-braces approach
*/
// So that we have a nice simple and clear to read indexing system, lets set up an enum...
enum Units
{
FEET = 0, // typing Units::FEET will be the same as 0 but more readable and maintainable
INCHES = 1 // and likewise Units::INCHES will be the same as 1
};
class DistanceBase
{
private:
double distance[2]; // we can store the 2 doubles in one array (easier to throw around as a pair then:)
public:
void inputFeet(double feet) { distance[0] = feet; } // need a way to set the feet
void inputInches(double inch) { distance[1] = inch; } // and inches
double* getDistance() { return distance; } // a way to get both in one go
double getFeet() { return distance[Units::FEET]; } // a way to get just the feet
double getInches() { return distance[Units::INCHES]; } // a way to get just the inches
};
#endif // DISTANCE_BASE_H
Now that we have a class with such a simple level of complexity we can utilise it to create a simple class for your purposes, Distance:
Distance
Header File
#pragma once
#ifndef DISTANCE_H
#define DISTANCE_H
/*
Header file for the distance class
*/
#include "DistanceBase.h"
class Distance
{
private:
DistanceBase *D1, *D2; // 2 instances of the DistanceBase class to use together
public:
Distance() // this is the constructor, where we can initialise
{ // the 2 instances we created earlier
D1 = new DistanceBase(); // initialise D1
D2 = new DistanceBase(); // initialise D2
}
DistanceBase* getD1() { return D1; } // this will be the function we use to access all of the properties and members of D1
DistanceBase* getD2() { return D2; } // this will be the function we use to access all of the properties and members of D2
double sumFeet() { return D1->getFeet()+D2->getFeet(); } // add the feet components of D1 and D2
double sumInches() { return D1->getInches()+D2->getInches(); } // add the inch components of D1 and D2
};
#endif // DISTANCE_H
Again, as this class is very simple (and for ease of posting) I have made everything fit in the header.
Now for the main function, which is now much more simple as the details are take care of by the respective classes:
#include "Distance.h"
#include <iostream>
using namespace std;
int main() {
Distance *dist = new Distance(); // instantiate a Distance class as dist
dist->getD1()->inputFeet(3); // set the feet of D1 to 3
dist->getD2()->inputFeet(7); // set the feet component of D2 to 7
cout << dist->getD1()->getFeet() << endl; // check that the values stored match the values input
cout << dist->getD2()->getFeet() << endl; // check that the values stored match the values input
cout << dist->sumFeet(); // add the 2 distances together
// now lets use user inputs:
cout << "Please input the first distance in feet: ";
// we can reuse the same variable to save CPU time and memory for all our inputs....
double tempValue;
cin >> tempValue;
dist->getD1()->inputFeet(tempValue);
cout << "Please input the first distances inch component: ";
cin >> tempValue;
dist->getD1()->inputInches(tempValue);
cout << "Please input the Second distance in feet: ";
cin >> tempValue;
dist->getD2()->inputFeet(tempValue);
cout << "Please input the second distances inch component: ";
cin >> tempValue;
dist->getD2()->inputInches(tempValue);
cout << dist->getD1()->getFeet() << endl; // check that the values stored match the values input
cout << dist->getD2()->getFeet() << endl; // check that the values stored match the values input
cout << dist->sumFeet() << endl; // add the 2 distances together
cout << dist->sumInches() << endl; // add the inches components together
return 0;
}
Exploration Points:
Some things you can try out to test yourself:
separate function definitions and prototypes into .cpp and .h files
add functionality to the inches input that turns values greater than 12.0 into feet and inches
add functionality to change any feet component into feet and inches if there is a decimal point present
create a Feet class and Inches class to encapsulate the functionality above
ensure Feet and Inches are using the most minimal type they can (for example int for feet and float for inches)
add error handling to trap things like text input instead of numbers etc.
Let me know if this all seems OK, or if you need more info, I will happy to help :)
Notes:
1 Trivial class: in C++ a trivial class is one defined (defined with class, struct or union) as both trivially constructible and trivially copyable, which implies that:
it utilises the implicitly defined default, copy and move constructors, copy and move assignments, and destructor.
it possesses no virtual members.
it possesses no non-static data members with brace- or equal- initializers.
its base class and non-static data members, if it has any, are likewise trivial.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How could send a value AJAX to controler in ZF2?
I have this code
//ajax script
<SCRIPT>
$('#grupo').on('change', function() {
var opc=$(this).find(":selected").text();
$.ajax({
url: "seleccionGrupos/1",
type: "POST",
cache: false,
ifModifiedBoolean:false,
success:function (data){
$("#tablaGrupos").show();
//value from de CONTROLER
$("#tablaGrupos").html('<?php echo $this->datostablagruposb ?>');
},
error: function(data) {
$("span").append("Oops Something Went Wrong");
}
});
});
</SCRIPT>
i need get query result dynamic how i can get it? any solution?
to dynamically get the query value
A:
Your ajax call:
<script type="text/javascript">
$(function(){
$('#myFormID').bind("submit",function(event) {
event.preventDefault();
$.ajax({
url :$(this).attr("action"),// or the ure of your action
type : $(this).attr("method"),// POST, GET
cache : false,
data : $(this).serializeArray(), // the data from your form , in your case the :selected
success : function( response, status,jQXHR)
{
var result= $.parseJSON(response);// this is needed to decode your JSON data the you get get back you action
},
error : function(jqXHR, textStatus, errorThrown){
alert('Error: '+ errorThrown);
}
});
return false;
});
});
</script>
Your Action should look like this in your Controller:
<?php
public function myAction()
{
// get your form from your entity or model
$form = $this->getForm();
$response = $this->getResponse();
$request = $this->getRequest();
// get some form element and do somthing with theme her
if ($request->isPost()){
$form->setData($request->getPost());
$response->setContent(\Zend\Json\Json::encode(array('data'=>'send any data you wish')));
return $response;
}
?>
And you can send an ajax call from the route by useing $('myButton').target.attr('href') instead of post;. Hope this help.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How to Fetch Value from Joomla 2.5 Database Column, Field Name & Value
I am trying to create a condition in which basis
Column Name
Field Name
Field Value
of mysql database, a conditional script should show in - Attached Table
ColumnName - FormId
Fieldname - Listing
Fieldvalue - Listing Value
Below is script
$max = 1;
$listing = JRequest::getInt('listing');
if($listing) {
$db = JFactory::getDBO();
$db->setQuery("SELECT COUNT(`SubmissionId`) FROM #__rsform_submission_values WHERE `FormId`='".(int) $formId."' AND `FieldName`='listing' AND `FieldValue`='".$listing."' ");
$nrSub = $db->loadResult();
if ($nrSub >= $max) {
$formLayout = '<p>Sorry, no more submissions are accepted for this car.</p>';
}
}
I think am messing up with Fieldvalue column - may be it might not be able to fetch in value. Can someone help and advise pls
A:
You are Quering count, it should be column names or * for all columns, if you need values, see example below:
$db->setQuery("SELECT * FROM #__rsform_submission_values WHERE `FormId`='".(int) $formId."' AND `FieldName`='listing' AND `FieldValue`='".$listing."' ");
$nrSub = $db->loadAssocList();
print_r($nrSub);
Additionally, Please go through with for ref Joomla DB Documentation
EDIT:
$Query = "SELECT
COUNT(`SubmissionId`) SubmissionCount, `FormId`, `FieldName`, `FieldValue`
FROM #__rsform_submission_values
WHERE `FormId`='".(int) $formId."' AND `FieldName`='listing' AND `FieldValue`='".$listing."'
GROUP BY `FormId`, `FieldName`, `FieldValue`";
$db->setQuery($Query);
$nrSub = $db->loadAssocList();
print_r($nrSub);
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Why are a Tableau Data Source and Sheet showing different data?
I've created a Tableau workbook that is based off of a SQL query connecting to an Oracle Database. Let's pretend that the query has 2 fields, ID and Stock number. On the Data Source tab one row shows ID = 2040 and the Stock number = 47 but on Sheet 1, ID = 2040 shows a Stock number = 2040. The remote type of the Stock number field on the Data Source tab is "Fixed precision number" and on Sheet 1 it is "Double-precision floating-point number."
For a reason I do not understand the Stock number is equal to the ID for all rows of the data when looking at the data on Sheet 1 (or any other Sheet for that matter). This is incorrect when I look at the Data Source tab or if I use Oracle SQL Developer to run the query. Why and how is this happening in Tableau?
What I've already tried
Using the Stock number field as a Dimension and a Measure
Using "View Data" on Sheet 1 - It shows that the row where ID = 2040 also has a Stock number = 2040
instead of the correct value of 47
A:
My advice is to start a new workbook and take your query right back to basics. Only have a simple select statement and return a few rows.
Then build up from there. You want to get as simple as you can, with no column aliases if you can avoid it.
From there add more complexity to your query, one step at a time so you can pinpoint the exact moment when your query stops working.
I have seen Tableau get confused by data types before, so make sure you check all of the data types that Tableau suggests when you first build your data source. And update them as necessary.
If you can remove or even blur out any sensitive content and show us a picture that would help immenesly. Obviously a picture tells a thousand words.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Should I flatten multiple customer into one row of dimension or using a bridge table
I'm new to datawarehousing and I have a star schema with a contract fact table. It holds basic contract information like Start date, end date, amount ...etc.
I have to link theses facts to a customer dimension. there's a maximum of 4 customers per contract. So I think that I have two options either I flatten the 4 customers into one row for ex:
DimCutomers
name1, lastName1, birthDate1, ... , name4, lastName4, birthDate4
the other option from what I've heard is to create a bridge table between the facts and the customer dimension. Thus complexifying the model.
What do you think I should do ? What are the advantages / drawbacks of each solution and is there a better solution ?
A:
I would start by creating a customer dimension with all customers in it, and with only one customer per row. A customer dimension can be a useful tool by itself for CRM and other purposes and it means you'll have a single, reliable list of customers, which makes whatever design you then implement much easier.
After that it depends on the relationship between the customer(s) and the contract. The main scenarios I can think of are that a) one contract has 4 customer 'roles', b) one contract has 1-4 customers, all with the same role, and c) one contract has 1-n customers, all with the same role.
Scenario A would be that each contract has 4 customer roles, e.g. one customer who requested the contract, a second who signs it, a third who witnesses it and a fourth who pays for it. In that case your fact table will have one row per contract and 4 customer ID columns, each of which references the customer dimension:
...
RequesterCustomerID int,
SignatoryCustomerID int,
WitnessCustomerID int,
BillableCustomerID int,
...
Of course, if one customer is both a requester and a witness then you'll have the same ID in both RequesterCustomerID and WitnessCustomerID because you only have one row for him in your customer dimension. This is completely normal.
Scenario B is that all customers have the same role, e.g. each contract has 1-4 signatories. If the number of signatories can never be more than 4, and if you're very confident that this will 'always' be true, then the simple solution is also to have one row per contract in the fact table with 4 columns that reference the customer dimension:
...
SignatoryCustomer1 int,
SignatoryCustomer2 int,
SignatoryCustomer3 int,
SignatoryCustomer4 int,
...
Even if most contracts only have 1 or 2 signatories, it's not doing much harm to have 2 less frequently used columns in the table.
Scenario C is where one contract has 1-n customers, where n is a number that varies widely and can even be very large (class action lawsuit?). If you have 50 customers on one contract, then adding 50 columns to the fact table becomes difficult to manage. In this case I would add a bridge table called ContractCustomers or whatever that links the fact table with the customer dimension. This isn't as 'neat' as the other solutions, but a pure star schema isn't very good at handling n:m relationships like this anyway.
There may also be more complex cases, where you mix scenarios A and C: a contract has 3 requesters, 5 signatories, 2 witnesses and the bill is split 3 ways between the requesters. In this case you will have no choice but to create some kind of bridge table that contains the specific customer mix for each contract, because it simply can't be represented cleanly with just one fact and one dimension table.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
C# invoke base constructor with parameters and parameterless constructor of current class
public class A
{
public A() { Console.WriteLine("A parameterless"); }
public A(int a) : this() { Console.WriteLine("A with a"); }
}
public class B : A
{
public B() { Console.WriteLine("B paramterless"); }
public B(int b) : base(b) { Console.WriteLine("B with b"); }
}
public class Program
{
public static void Main(string[] args)
{
new B(3);
}
}
Gives:
A parameterless
A with a
B with b
What can I do to invoke "B parameterless" as well?
So, I'd need something along the lines of:
public B(int b) : base(b), this() { ... }
Or, a virtual constructor, so that when the base class invokes this(), it redirects to child's parameterless constructor.
A:
You cannot do it with constructor chaining. But I dont see any problem with this:
public class A
{
public A()
{
Console.WriteLine("A parameterless");
}
public A(int a) : this()
{
Console.WriteLine("A with a");
}
}
public class B : A
{
public B()
{
ThingsIWant();
}
public B(int b) : base(b)
{
ThingsIWant();
Console.WriteLine("B with b");
}
protected void ThingsIWant()
{
Console.WriteLine("B paramterless");
}
}
public class Program
{
public static void Main(string[] args)
{
new B(3);
}
}
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Graph equation code fix needed!
I am trying to graph this image
using this line of code
Manipulate[ (sol =
NDSolve[{y[t] == h[t]*(Ke^(-h[t]/r)), y[0] == 0.001},
y[t], {t, 0, 1000}];
Plot[Evaluate[x[t] /. sol], {t, 0, 1000},
PlotRange -> {0, 10}]), {{r, 0.01}, 0, 0.05}, {{Ke, 5}, 0, 10}]
But my code isn't working. Can you tell me what's wrong? This is the equation that is supposed to model the graph
$$y=hKe^{-\frac{h}{r}}$$
A:
You gave the equation at the end. Just plot it:
Manipulate[
Plot[h*k*Exp[-h/r], {h, 1, 1000}, PlotRange -> All],
{{k, 50}, 10, 100},
{{r, 50}, 10, 100}
]
|
{
"pile_set_name": "StackExchange"
}
|
Q:
AWS ssl is not working in imported certificate for custom domain
I have dobut in AWS SSL.
I have launched instance in AWS.
Then I got Public IP of launched instance, which pointed to BLUEHOST (only for domain ) DNS record ( Type A).
when I tried subdomain.example.com is working in browser.
Then for SSL, I imported certificate key and crt in certificate manager.And
certificate status is ISSUED.
When I tried HTTPS in browser ( https://subdomain.example.com ) is not working
Any one guide me.
A:
You cannot use the certificate provided by Amazon Certificate Manager(ACM) on EC2 instance. That can only be used with certain AWS services such as Elastic Load Balancer, CloudFront, API Gateway and Elastic Beanstalk.
If you want to use ACM, you can setup a ELB in front of your EC2 instance and have your certificate applied to ELB. When you are requesting for a certificate via ACM make sure to add *.example.com domain to protect your subdomain as well.
If you want to setup SSL on your EC2 instance itself, you can request for SSL certificates from a ssl certificate provider. There are many certificate providers, such as letsencrypt, sslforfree etc..
Here is a guide on how to install SSL certificates obtained from a certificate provider on your EC2 instance.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Questions closed for insufficient information
Recently, I've had a few questions closed or recently closed for insufficient information. Wouldn't it make more sense to ask for specific details, rather than simply closing the question? Generally, when I don't post information, it's because I'm not sure what would be relevant.
A:
Don't panic!
Questions can easily be re-opened once they are edited to conform to the site's standards.
Just edit it, add more relevant information, and members of the community will vote to re-open it as they did to close it.
Feel free to read the FAQ specifically this about closed questions
A:
As Jqan already pointed out, closing is a temporary state, and any question which is closed can later be re-opened. Furthermore, gaming follows a policy of close first, ask questions later. There are a number of reasons for this, but the main ones are:
Users that abandon their questions: A lot of users won't bother improving their question, and will vanish from the site shortly after posting it never to return. In situations like this we prefer to close first so that the question gets closed. If we held off on closing it for some arbitrary amount of time it's likely the question would never get closed at all. Whereas if we close it right away this won't be a problem.
It's easier to improve a question when it's closed: When a question is closed users can't post answers to it. Due to this it's a lot easier to improve a question when it's closed, that way no one posts answers that won't be valid once the question is improved (and will thus require us to clean them up).
Re-Opening a Question is Easy: By design re-opening a question is very easy on Stack Exchange. Due to this there's really no drawback to closing a question and then re-opening if it gets improved. The only drawback would be questions being forgotten by 3k+ users, and never being re-opened, but this is a rare situation. In the vast majority of situations if a user improves their question after it being closed they'll ping one or more of the users who closed the question, who will in turn bring the improved question to the attention of other 3k+ users to ensure it gets re-opened. A users can also flag the question to be re-opened, which will also bring it to the other of 10k+ users and mods.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How to select following siblings until a certain sibling
I'm currently working with VDA message types that have been convert to xml using a custom xml converter. However each header and line record in the source document is at the same level, as in the sample below:
<root>
<row>
<Record_type>512</Record_type>
<Customer_item_Number>A0528406</Customer_item_Number>
<Supplier_item_number>10962915</Supplier_item_number>
</row>
<row>
<Record_type>513</Record_type>
<Date>170306</Date>
<Quantity>115</Quantity>
</row>
<row>
<Record_type>513</Record_type>
<Date>190306</Date>
<Quantity>97</Quantity>
</row>
<row>
<Record_type>512</Record_type>
<Customer_item_Number>A0528433</Customer_item_Number>
<Supplier_item_number>10962916</Supplier_item_number>
</row>
<row>
<Record_type>513</Record_type>
<Date>170306</Date>
<Quantity>115</Quantity>
</row>
<row>
<Record_type>513</Record_type>
<Date>170306</Date>
<Quantity>115</Quantity>
</row>
<row>
<Record_type>513</Record_type>
<Date>170306</Date>
<Quantity>115</Quantity>
</row>
<row>
<Record_type>513</Record_type>
<Date>170306</Date>
<Quantity>115</Quantity>
</row>
</root>
(512) record types are headers, the following (513) record types are lines for the preceding (512) record above it.
I am struggling to format this message, so that the lines (513) are indented underneath each header (512) record.
i.e. required output, something like this.
<root>
<Header>
<Record_type>512</Record_type>
<Customer_item_Number>A0528406</Customer_item_Number>
<Supplier_item_number>10962915</Supplier_item_number>
<Line>
<Record_type>513</Record_type>
<Date>170306</Date>
<Quantity>115</Quantity>
</Line>
<Line>
<Record_type>513</Record_type>
<Date>190306</Date>
<Quantity>97</Quantity>
</Line>
</Header>
<Header>
<Record_type>512</Record_type>
<Customer_item_Number>A0528433</Customer_item_Number>
<Supplier_item_number>10962916</Supplier_item_number>
<Line>
<Record_type>513</Record_type>
<Date>170306</Date>
<Quantity>115</Quantity>
</Line>
<Line>
<Record_type>513</Record_type>
<Date>170306</Date>
<Quantity>115</Quantity>
</Line>
<Line>
<Record_type>513</Record_type>
<Date>170306</Date>
<Quantity>115</Quantity>
</Line>
<Line>
<Record_type>513</Record_type>
<Date>170306</Date>
<Quantity>115</Quantity>
</Line>
</Header>
</root>
I have had some success using following sibling, but I'm unable to link this with preceding-sibling, to filter out only the required records before the next loop.
I am hoping someone will be able to assist. :)
A:
For every row that has a Record_type of 512, create a Header element.
In order to find the row elements for the relevant group of Line elements, you want to select the row elements that are following-sibling from the 512 who's Record_type = 513 and who's first preceding-sibling is the current header.
for $header in $doc/root/row[Record_type = 512]
let $lines := $header/following-sibling::row[Record_type = 513]
[preceding-sibling::row[Record_type = 512][1] = $header]
return
<Header>{
$header/*,
for $line in $lines
return <Line>{ $line/* }</Line>
}</Header>
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How can I use innerHTML without removing entire html inside of tag?
I have searched almost whole internet but couldn't able to get a solution about this..
Suppose that we have a div element with some html inside of it. After selecting this tag by its id (or other selectors, whatever) and if I use "innerHTML" method, I lost all html inside of the tag. What can i do to not destroy html parts inside of the tag? I just want to add something "more", not to "destroy all" and then insert something into new instead.
document.getElementById('something').innerHTML = document.getElementById('something').innerHTML + new_html_to_append;
the method above doesn't work for 3rd iteration, or in a for loop so it's useless for me.. i need something fits infinite supplementation.
Thank You!
(I know .append() method but i am not allowed to use JQuery there.)
A:
appendChild()
...................................
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Tesseract Example for Iphone
I have compiled tesseract for using it in xcode following: http://iphone.olipion.com/cross-compilation/tesseract-ocr
I obtain the .a file, import it as framework in the iphone project, and update the header search path for tesseract header files.
So now I need a simple example in order to get start.
I can't find anything in http :// code.google.com/p/tesseract-ocr/ or by googling.
Anyone can help me give me a starting point (a code snippet)..?!
Many ThankS!
--
Later i found this code:
#include "baseapi.h"
TessBaseAPI::InitWithLanguage(NULL, NULL, language, NULL, false, 0, NULL);
char* text = TessBaseAPI::TesseractRect(imagedata, bytes_per_pixel,
bytes_per_line, 0, 0,
width, height);
TessBaseAPI::End();
but when I try to compile for device (only inserting include statement without the code above) i get the following:
error:syntax error before 'PAGE_RES'
warning:type defaults to 'int' in declaration of 'PAGE_RES'
warning:data definition has no type or storage class
and so on with BLOCK_LIST, IMAGE etc.
if compile for simulator i get
error: expected '=',',',','asm' or 'attribute' before 'PAGE_RES'
and so on with BLOCK_LIST, IMAGE and TessBaseAPI
--- Other Update:
I found solution for include problem:
Where the include occurs must be rename the file.m in .mm extension because we have to tell xcode that we have to use objective-c and c++ together.
A:
http://github.com/nolanbrown/Tesseract-iPhone-Demo
OCRDemo is a demo application that utilizes the Tesseract library (http://code.google.com/p/tesseract-ocr/) as a static library compiled under Mac OS 10.6 using the shell script found at http://robertcarlsen.net/2009/07/15/cross-compiling-for-iphone-dev-884.
The program is only meant to provide a demonstration of the OCR library and it’s abilities on the iPhone, the program is not optimized in any way...
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Role based views in extjs4 mvc
My application has different views for different roles like (admin or standard user).I don't know how can i implement it with extjs4 MVC. Examples of extjs4 documentation consider that application has only one role like standard user so they create one app.js file that manage application but if application has many roles i don't know how can i implement different views for different users.
One matter is i have two app.js files in the application and after i get user role in the server i load appropriate app.js file to use appropriate views,controllers,models,stores and so on.
Is this matter true?
A:
This is a rather standard question that comes up so many times and the answer is always the same:
Access Control belongs to the Server where no user can manipulate it
Simply don't provide a View / a model / a controller to a user where he has no access to
With that in mind it doesn't matter if you have one app or ten.
And because Access Control is nothing that belongs to the frontend there is no implementation within ExtJS.
Update -> Hide UI elements
A ready to go approach would be the use of Ext.direct. This provide the application with a API that can be modified based on custom access of the current user and can then be checked by the frontend.
HowTo:
Create the API based on the user session and check on the Clientside like
if(Booking) {
if (Booking.Create) {
// has access
}
}
or as one line
{
xtype: 'button',
hidden: !(Booking && Booking.Create)
}
This is just a simple example how easy this could be done!
update
This Link helped the op
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Is it worth to pay for TurboTax when filing one W2?
Is it worth to pay for TurboTax when filing one W2? Or just use its FREE version?
A:
It's worth it to actually know how to do taxes for real. On paper, following the instructions yourself.
This is a great time to learn, because you get to learn the new version of the forms.
You can hit the library and get copies of the popular paper forms, or you can get PDF versions of the forms and instructions. Get real Adobe Acrobat Reader, because you can actually type the numbers/values into the PDF versions. I put in everything except my SSN, save it, print it, handwrite the SSN and signature, and stick it in an envelope with a stamp and mail it to the IRS. Now I have a local copy to archive on my PC.
I have to stand behind that 1040. I'd like to be able to acutally see it in the future, not have it be bits and blits in somebody else's cloud, or in some weird file format only one app can read. (Nor do I want my SSN in those places, which could be hacked). PDF is common and reliable. (And again, no SSN there either).
One more thing, IRS can reject online "filings". In effect they strongarm you to accept numbers you disagree with, otherwise you've failed to file. When you file paper, IRS must accept that you filed on time, then you squabble with their Andover office about the details.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Storing a date in .property and comparing with current date
How do I store a future date in a .property file and compare this date with current the current date?
A:
You could:
save a formatted date
if you want, save the format too, adding flexibility
The property file:
myDate=25/01/2012
myDate.pattern=dd/MM/yyyy
Then, in your program you could load the date this way:
// choose one of two lines!
String pattern = "dd/MM/yyyy"; // for a fixed format
String pattern = propertyFile.getProperty("myDate.pattern");
String formattedDate = propertyFile.getProperty("myDate");
SimpleDateFormat format = new SimpleDateFormat(pattern);
Date myDate = format.parse(formattedDate);
Edit: to compare to current...
1. boolean isFuture = myDate.after(new Date())
2. boolean isPast = myDate.before(new Date())
3. int compare = myDate.compareTo(new Date());
// compare < 0 => before
// compare == 0 => equal
// compare > 0 => after
A:
Well, there are a few things to consider here:
Do you genuinely only care about the date, or is it the date and time?
Does the time zone matter? Are you interested in a future instant, or a future local time?
Should the properties file be human readable?
If you're just dealing with an instant and you don't care about anyone being able to understand which instant it is from the properties file, I'd be tempted to store the string representation of a long (i.e. the millis in a java.util.Date) and then to check it, just parse the string and compare the result with System.currentTimeMillis. It avoids the whole messy formatting and parsing of dates and times.
For anything more complicated, I'd thoroughly recommend using Joda Time which will make it easier to understand what concepts you're really dealing with (e.g. LocalDate, LocalTime or DateTime) and which has better formatting and parsing support (IMO) than the JDK.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
What is the best way to install Laravel on HTML website that already use GIT?
I have a complete HTML website with all its folders CSS, JS & Images and already use Version Control by GIT.
What is the best way to install Laravel 5 on this website to keep GIT track the diversion from HTML to Laravel Framework smoothly.
A:
The steps to convert your current HTML website to laravel is very easy unless if you have some js backend:
Install Laravel
Move your CSS,JS,Images to laravel public folder
Move your html files to resource/views and rename them to name.blade.php or just name.php.
Fix the reference links of your css, js and images.
THE BIG PART!!! all your navigation will go through routes and backend logic in controllers.
e.g. you wanna go to your about page! you will have a rule in your route which will redirect to a function in a controller and that function will call the view (html page currently) and optionally pass any information to the view.
These are very simple ways to transfer your website, but once you get into it you can learn many features of laravel that can optimize your site.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Removing punctuation using spaCy; AttribueError
Currently I'm using the following code to lemmatize and calculate TF-IDF values for some text data using spaCy:
lemma = []
for doc in nlp.pipe(df['col'].astype('unicode').values, batch_size=9844,
n_threads=3):
if doc.is_parsed:
lemma.append([n.lemma_ for n in doc if not n.lemma_.is_punct | n.lemma_ != "-PRON-"])
else:
lemma.append(None)
df['lemma_col'] = lemma
vect = sklearn.feature_extraction.text.TfidfVectorizer()
lemmas = df['lemma_col'].apply(lambda x: ' '.join(x))
vect = sklearn.feature_extraction.text.TfidfVectorizer()
features = vect.fit_transform(lemmas)
feature_names = vect.get_feature_names()
dense = features.todense()
denselist = dense.tolist()
df = pd.DataFrame(denselist, columns=feature_names)
df = pd.DataFrame(denselist, columns=feature_names)
lemmas = pd.concat([lemmas, df])
df= pd.concat([df, lemmas])
I need to strip out proper nouns, punctuation, and stop words but am having some trouble doing that within my current code. I've read some documentation and other resources, but am now running into an error:
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-21-e924639f7822> in <module>()
7 if doc.is_parsed:
8 tokens.append([n.text for n in doc])
----> 9 lemma.append([n.lemma_ for n in doc if not n.lemma_.is_punct or n.lemma_ != "-PRON-"])
10 pos.append([n.pos_ for n in doc])
11 else:
<ipython-input-21-e924639f7822> in <listcomp>(.0)
7 if doc.is_parsed:
8 tokens.append([n.text for n in doc])
----> 9 lemma.append([n.lemma_ for n in doc if not n.lemma_.is_punct or n.lemma_ != "-PRON-"])
10 pos.append([n.pos_ for n in doc])
11 else:
AttributeError: 'str' object has no attribute 'is_punct'
Is there an easier way to strip this stuff out of the text, without having to drastically change my approach?
Full code available here.
A:
From what I can see, your main problem here is actually quite simple: n.lemma_ returns a string, not a Token object. So it doesn't have an is_punct attribute. I think what you were looking for here is n.is_punct (whether the token is punctuation).
If you want to do this more elegantly, check out spaCy's new custom processing pipeline components (requires v2.0+). This lets you wrap your logic in a function which is run automatically when you call nlp() on your text. You could even take this one step further, and add a custom attribute to your Doc – for example, doc._.my_stripped_doc or doc._.pd_columns or something. The advantage here is that you can keep using spaCy's performant, built-in data structures like the Doc (and its views Token and Span) as the "single source of truth" of your application. This way, no information is lost and you'll always keep a reference to the original document – which is also very useful for debugging.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Update Single Item in the ObservableCollection without LINQ
I am trying to create a list of the Components running on the network. I am trying to get all the components in the ObservableCollection. ObservableCollection<ClsComponent> Now my question is if one of the component in the collection get changed / modified how would I be able to get it reflected to my ObservableCollection of Component
Is there a way to change the it directly in the collection itself?
What is the fast and efficient way doing it?
I have tried: to change it using the LINQ : Find the Component in the collection and change it?
var CompFound = Components.FirstOrDefault(x=>x.Id == myId);
Components.Remove(CompFound);
Components.Add(UpdatedComp);
I am very sure there should have been more optimized way of doing this. Please suggest.
Edit
I am trying to write the code in the function where I can get the parameters of Source Component and Destination Component. Function looks like this
public void UpdateComponent(ClsComponent SourceComp, ClsComponent DestComp)
{
//do something here
}
After the execution of the function I want to Replace Source Component with Destination Component.
A:
I believe this might work for you. I am sure you might be looking for this
Components.Insert(Components.IndexOf(SourceComp), DestComp);
Components.Remove(SourceComp);
|
{
"pile_set_name": "StackExchange"
}
|
Q:
re implement modulo using bit shifts?
I'm writing some code for a very limited system where the mod operator is very slow. In my code a modulo needs to be used about 180 times per second and I figured that removing it as much as possible would significantly increase the speed of my code, as of now one cycle of my mainloop does not run in 1/60 of a second as it should. I was wondering if it was possible to re-implement the modulo using only bit shifts like is possible with multiplication and division. So here is my code so far in c++ (if i can perform a modulo using assembly it would be even better). How can I remove the modulo without using division or multiplication?
while(input > 0)
{
out = (out << 3) + (out << 1);
out += input % 10;
input = (input >> 8) + (input >> 1);
}
EDIT: Actually I realized that I need to do it way more than 180 times per second. Seeing as the value of input can be a very large number up to 40 digits.
A:
What you can do with simple bitwise operations is taking a power-of-two modulo(divisor) of the value(dividend) by AND'ing it with divisor-1. A few examples:
unsigned int val = 123; // initial value
unsigned int rem;
rem = val & 0x3; // remainder after value is divided by 4.
// Equivalent to 'val % 4'
rem = val % 5; // remainder after value is divided by 5.
// Because 5 isn't power of two, we can't simply AND it with 5-1(=4).
Why it works? Let's consider a bit pattern for the value 123 which is 1111011 and then the divisor 4, which has the bit pattern of 00000100. As we know by now, the divisor has to be power-of-two(as 4 is) and we need to decrement it by one(from 4 to 3 in decimal) which yields us the bit pattern 00000011. After we bitwise-AND both the original 123 and 3, the resulting bit pattern will be 00000011. That turns out to be 3 in decimal. The reason why we need a power-of-two divisor is that once we decrement them by one, we get all the less significant bits set to 1 and the rest are 0. Once we do the bitwise-AND, it 'cancels out' the more significant bits from the original value, and leaves us with simply the remainder of the original value divided by the divisor.
However, applying something specific like this for arbitrary divisors is not going to work unless you know your divisors beforehand(at compile time, and even then requires divisor-specific codepaths) - resolving it run-time is not feasible, especially not in your case where performance matters.
Also there's a previous question related to the subject which probably has interesting information on the matter from different points of view.
A:
Actually division by constants is a well known optimization for compilers and in fact, gcc is already doing it.
This simple code snippet:
int mod(int val) {
return val % 10;
}
Generates the following code on my rather old gcc with -O3:
_mod:
push ebp
mov edx, 1717986919
mov ebp, esp
mov ecx, DWORD PTR [ebp+8]
pop ebp
mov eax, ecx
imul edx
mov eax, ecx
sar eax, 31
sar edx, 2
sub edx, eax
lea eax, [edx+edx*4]
mov edx, ecx
add eax, eax
sub edx, eax
mov eax, edx
ret
If you disregard the function epilogue/prologue, basically two muls (indeed on x86 we're lucky and can use lea for one) and some shifts and adds/subs. I know that I already explained the theory behind this optimization somewhere, so I'll see if I can find that post before explaining it yet again.
Now on modern CPUs that's certainly faster than accessing memory (even if you hit the cache), but whether it's faster for your obviously a bit more ancient CPU is a question that can only be answered with benchmarking (and also make sure your compiler is doing that optimization, otherwise you can always just "steal" the gcc version here ;) ). Especially considering that it depends on an efficient mulhs (ie higher bits of a multiply instruction) to be efficient.
Note that this code is not size independent - to be exact the magic number changes (and maybe also parts of the add/shifts), but that can be adapted.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
RSA Encryption using Python
I'm trying to RSA encrypt a word 2 characters at a time padding with a space using Python but not sure how I go about it.
For example if the encryption exponent was 8 and a modulus of 37329 and the word was 'Pound' how would I go about it? I know I need to start with pow(ord('P') and need to take into consideration that the word is 5 characters and I need to do it 2 characters at a time padding with a space. I'm not sure but do I also need to use <<8 somewhere?
Thank you
A:
Here's a basic example:
>>> msg = 2495247524
>>> code = pow(msg, 65537, 5551201688147) # encrypt
>>> code
4548920924688L
>>> plaintext = pow(code, 109182490673, 5551201688147) # decrypt
>>> plaintext
2495247524
See the ASPN cookbook recipe for more tools for working with mathematical part of RSA style public key encryption.
The details of how characters get packed and unpacked into blocks and how the numbers get encoded is a bit arcane. Here is a complete, working RSA module in pure Python.
For your particular packing pattern (2 characters at a time, padded with spaces), this should work:
>>> plaintext = 'Pound'
>>> plaintext += ' ' # this will get thrown away for even lengths
>>> for i in range(0, len(plaintext), 2):
group = plaintext[i: i+2]
plain_number = ord(group[0]) * 256 + ord(group[1])
encrypted = pow(plain_number, 8, 37329)
print group, '-->', plain_number, '-->', encrypted
Po --> 20591 --> 12139
un --> 30062 --> 2899
d --> 25632 --> 23784
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Is there a way of compiling (i.e. caching) a cupy RawKernel before calling it?
I'm writing a python application that processes a lot of images.
The computation speed of the application is important, thus I'm trying to minimize the execution time by writing cupy kernels.
For the sake of simplicity, assume that I have a cupy raw kernel below.
import cupy as cp
add_kernel = cp.RawKernel(r'''
extern "C" __global__
void add_one(float* dimg, float* y) {
int j = threadIdx.x;
int i = blockIdx.x;
int k = blockDim.x;
int tid = k*i+j;
y[tid] = dimg[tid] + 1;
}
''', 'add_one')
if __name__ == '__main__':
h, w = 192, 256
dimg_cp = cp.zeros(shape=(h, w), dtype=cp.float32)
y = cp.zeros(shape=(h, w), dtype=cp.float32)
add_kernel((h,), (w,), (dimg_cp, y))
print(y)
Here, 'add_kernel' simply copies an input matrix and add one to every element of the copied matrix then return it. It works great but I believe the code can be further optimized in terms of execution speed.
According to the link, when the kernel is called for the first time (i.e. not cached), there will be an overhead for compilation.
I want to avoid this compilation time.
So I want to ask if there is a way of compiling cp.RawKernel prior to calling the kernel for the first time?
Thanks in advance.
A:
There is currently no explicit way to precompile the kernel without calling it. One easy solution is just calling it once with a small input. Note that the compiled kernel is also cached to a file, so the overhead only exists at the first execution of the script in the environment.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Rails 4 render action=>new does not go through new action
I have most common in rails code
def new
@company = Company.new
@companies = Company.order(:name).pluck(:name, :id)
end
def create
@company = Company.find(params["company"]["id"]) rescue nil
unless @company
render action: 'new'
return
end
status = @company.update_attributes(total_licenses: params["company"]["total_licenses"].to_i, assigned_licenses: 0)
if status == true
redirect_to users_super_admin_index_path, flash: {notice: "License has been allocated to company."}
else
render action: 'new'
end
end
but when somthing wrong it should render action new, but it directly render template hence @company remains nil and throws an error
ActionView::Template::Error (First argument in form cannot contain nil or be empty)
I want to find the permanent and right solution, no hacks please :) . And the reason why i am facing this problem.
In my view -
<%= form_for @company, url: licenses_path, method: "post" do |f| %>
<%= f.label :id, 'Select Company' %><br/>
<%= f.select :id, @companies, :include_blank => "Select Company", required: true %><br/><br/>
<%= f.label :total_licenses, 'License' %><br/>
<%= f.text_field :total_licenses, required: true%><br/><br/>
<%= f.submit 'Assign'%>
<% end %>
A:
Remember that render(action: ...) does not actually run the method in question, it just renders out the template. You will need to manually trigger the new method to do this.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Should contractions be avoided in formal emails?
In a formal email of the kind where you begin with "Dear Mr. Surname" and finish with "Best regards", for example, should we use the following contractions? Or are the non contracted forms more appropriate?
We have -> We've
We would -> We'd
There is -> There's
etc.
A:
In formal writing, do not use contractions.
A:
Giving blanket advice about contractions in "formal" writing is impossible because norms differ by discipline or purpose. When using contractions doesn't breach the specific governing norms, you should pursue the greatest clarity and concision, achieved by avoiding expanded verbs that are ordinarily contracted. I discuss this in depth in "The celebration of informality and the unsettled status of contractions."
A:
Short answer: use contractions where appropriate.
The idea behind banning contractions is to avoid upsetting people who entertain the delusion that there’s something wrong with using them in a formal context. Before you decide that you don’t want to risk offending such people (in case there are any still living), it is important to beware the dangers of avoiding contractions:
You could sound pompous.
You risk trying the patience of those who don’t have a problem with contractions (i.e. anyone who reads your e-mail).
Care must be taken when rewording sentences so that meaning is preserved. For example these two sentences do not mean the same thing:
He thought a Christian could not attend church and still be saved.
He thought a Christian couldn't attend church and still be saved.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Restore Azure SQL Database from Another Azure SQL Database
I'm not sure if this question has been asked because it's possible that I don't know how to ask the questino properly, but here goes...
I have two Azure SQL Databases. One is for testing and one is for production. In my CI/CD process, I would like to be able to take a copy of production (database) and restore it on top of the testing database. Everything I've read explains how to delete the existing database and restore a dacpac file in it's place. I don't want to do that because it's difficult as it is to create SQL user accounts and set permissions on them, so I would prefer to simply restore on top of the testing database. Is that possible with Azure SQL Databases? If so, could someone please enlighten me?
A:
No. It is not possible. If you restore from a bacpac or restore from automated backups it will always create a new database as result of the restore. Have you tried to create your test database using CREATE DATABASE AS COPY OF?
DROP DATABASE MyTestDB;
CREATE DATABASE MyTestDB AS COPY OF MyProdDB;
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Check if multiple strings are present in pandas dataframe
I am trying to determine if two variables are found in the dataframe
table:
Code index
600.SI 4th Q 2015
500.SI Full Year
ggr.SI 1st Q 2016
# If variable_code and variable_date is not found in table, print not found
if table['Code'].str.contains(variable_code).any() & table['index'].str.contains(variable_date).any():
print('found')
else:
print('not found')
However, it always return me found.
I think my if statement is structured incorrectly to do a bool comparison for two items.
How can this be solved?
Update
Normally, variable_code will be found in table. if variable_code is found in table, check if variable_date is present too.
What I am trying to achieve is, If both of these conditions are not present, print not found.
A:
With str.contains, regex=True by default, so if you're not careful, you won't be matching the right things. If you want to check for equality rather than containment, use the == operator, like this:
if not table[(table['Code'] == variable_code)
& (table['index'] == variable_date)].empty: # https://stackoverflow.com/a/45780191/4909087
print('Found')
else:
print('Not found')
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How to allocate the elements of a matrix in c++ opencv?
I have always used the C API and am trying to convert a simple project to the C++ API to get a handle on it, but I can't seem to figure out how to allocate the elements of a matrix in C++. For example, I have the following array:
double rotation[] = { 0, 1, 0,
-1, 0, 0,
0, 0, 1 };
I have a 3x3 Mat, allocated with Mat *rotation_vector = new Mat(3,3, CV_64FC1);
In C, it would simply be cvInitMatHeader(rotation_vector, 3, 3, CV_64FC1, rotation);. How is this done in C++?
A:
You should use some variant of the cv::Mat object.
For small matrices where the size is known and fixed, you can use the cv::Matx object:
cv::Matx33d rotation( 0.0, 1.0, 0.0,
-1.0, 0.0, 0.0,
0.0, 0.0, 1.0 );
For dynamically sized, arrays, you use the cv::Mat object
cv::Mat aBigMatrix( 53, 71, cv::CV_64FC1, cv::Scalar::all( 0.0 ) );
This would create a 2d-matrix with width of 53, height of 71, each element is a 64 bit floating point single-channel value ( basically a double ), and all of the elements will be set to 0.
Alternatively, you may use the cv::Mat_ template class, and the benefit is a cleaner initialization ( among other things ):
cv::Mat_<double> anotherBigMatrix( 53, 71, 0.0 );
This would create an equivalent matrix to the one described above.
Finally, you can use the template matrix class with an initialization list similar to the way you would do it in regular C:
There are many trade-offs to using the different classes, so you should make sure that you read the OpenCV documentation so that you pick the right one
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Using of md5 function
On php. How we use md5 encryption method? Suppose a login form. When we want an encrypted text we use
$encryptedtxt=md5('text');
Then we sent this $encryptedtxt to database. Now if we want this $encryptedtxt to compare with user new inputs to login , what should we do? If we should return text from encrypted form of it, how? Tnx.
A:
MD5 is no longer considered safe to use for password hashing, it's 30 years old and is considered "broken".
Use a modern-day method, including prepared statements.
Here are a few articles you can read up on:
https://security.stackexchange.com/questions/37454/why-are-md5-collisions-dangerous
https://www.bentasker.co.uk/blog/security/201-why-you-should-be-asking-how-your-passwords-are-stored
Pulled from ircmaxell's answer https://stackoverflow.com/a/29778421/
Just use a library. Seriously. They exist for a reason.
PHP 5.5+: use password_hash()
PHP 5.3.7+: use password-compat (a compatibility pack for above
All others: use phpass
Don't do it yourself. If you're creating your own salt, YOU'RE DOING IT WRONG. You should be using a library that handles that for you.
$dbh = new PDO(...);
$username = $_POST["username"];
$email = $_POST["email"];
$password = $_POST["password"];
$hash = password_hash($password, PASSWORD_DEFAULT);
$stmt = $dbh->prepare("insert into users set username=?, email=?, password=?");
$stmt->execute([$username, $email, $hash]);
And on login:
$sql = "SELECT * FROM users WHERE username = ?";
$stmt = $dbh->prepare($sql);
$result = $stmt->execute([$_POST['username']]);
$users = $result->fetchAll();
if (isset($users[0]) {
if (password_verify($_POST['password'], $users[0]->password) {
// valid login
} else {
// invalid password
}
} else {
// invalid username
}
|
{
"pile_set_name": "StackExchange"
}
|
Q:
MongoDB aggregate group by sum of distinct column
I have analytics collection with the below sample data.
{ "_id" : ObjectId("55f996a4e4b0cc9c0a392594"), "action" : "apiUploadFile", "assetId" : "55f996a4e4b0cc9c0a392593" },
{ "_id" : ObjectId("5603d384e4b0cf75af10be88"), "action" : "agAsset", "assetId" : "55f996a4e4b0cc9c0a392593"},
{ "_id" : ObjectId("5603d395e4b0cf75af10becc"), "action" : "aAD", "assetId" : "55f996a4e4b0cc9c0a392593" },
{ "_id" : ObjectId("5603d395e4b0cf75af10becd"), "action" : "mobCmd", "assetId" : "55f996a4e4b0cc9c0a392593", sessionId : "123"},
{ "_id" : ObjectId("5603d395e4b0cf75af10bece"), "action" : "mobCmd", "assetId" : "55f996a4e4b0cc9c0a392593", sessionId : "1234" },
{ "_id" : ObjectId("5603d395e4b0cf75af10becf"), "action" : "mobCmd", "assetId" : "55f996a4e4b0cc9c0a392593", sessionId : "1234" }
I need find sum of analytics group by 'assetId' and then for each 'action' type. I have come up with the below query
db.analytics.aggregate(
[
{
$match : {
'assetId' : { "$ne": null }
}
},
{$group :{
_id:
{
assId:'$assetId'
},
viewCount:{
$sum:{
$cond: [ { $eq: [ '$action', 'agAsset' ] }, 1, 0 ]
}
},
sessionCount:{
$sum:{
$cond: [ { $eq: [ '$action', 'mobCmd' ] }, 1, 0 ]
}
}
}
}]
)
This works great except for the fact that I can not find the 'sessionCount' using distinct 'sessionId'. For example here is the current output
{ "_id" : { "assId" : "55f996a4e4b0cc9c0a392593" }, "viewCount" : 1, "sessionCount" : 3 }
The expected output is
{ "_id" : { "assId" : "55f996a4e4b0cc9c0a392593" }, "viewCount" : 1, "sessionCount" : 2 }
I need find the sessionCount for action='mobCmd' and has distinct values for sessionId. How can use distinct inside $sum operation of the 'sessionCount' section?
A:
You will need to group your documents on a compound _id field.
db.collection.aggregate([
{ "$match": { "assetId": { "$ne": null }}},
{ "$group": {
"_id": { "assId": "$assetId", "sessionId": "$sessionId" },
"viewCount": {
"$sum": {
"$cond": [
{ "$eq": [ "$action", "agAsset" ] },
1,
0
]
}
},
"sessionCount": {
"$sum": {
"$cond": [
{ "$eq": [ "$action", "mobCmd" ] },
1,
0
]
}
}
}}
])
Which yields:
{ "_id" : { "assId" : "55f996a4e4b0cc9c0a392593", "sessionId" : "1234" }, "viewCount" : 0, "sessionCount" : 2 }
{ "_id" : { "assId" : "55f996a4e4b0cc9c0a392593", "sessionId" : "123" }, "viewCount" : 0, "sessionCount" : 1 }
{ "_id" : { "assId" : "55f996a4e4b0cc9c0a392593" }, "viewCount" : 1, "sessionCount" : 0 }
Or use the $addToSet operator to return an array of unique sessionId and $unwind the array then regroup your documents.
db.collection.aggregate([
{ "$match": { "assetId": { "$ne": null }}},
{ "$group": {
"_id": "$assetId",
"sessionId": { "$addToSet": "$sessionId" },
"viewCount": {
"$sum": {
"$cond": [
{ "$eq": [ "$action", "agAsset" ] },
1,
0
]
}
}
}},
{ "$unwind": "$sessionId" },
{ "$group": {
"_id": "$_id",
"viewCount": { "$first": "$viewCount" },
"sessionCount": { "$sum": 1 }
}}
])
Which returns:
{ "_id" : "55f996a4e4b0cc9c0a392593", "viewCount" : 1, "sessionCount" : 2 }
|
{
"pile_set_name": "StackExchange"
}
|
Q:
change img src and width
I change the scr of an img tag using jQuery, such as,
$("#img1").attr("src", "pic1.png");
after this, I try to get the width of img (it's not set in html),
$("#img1").width();
it seems the width is not changed with the src, did I miss something? thanks.
A:
If you're trying to do it immediately, it may be because the image isn't fully loaded yet.
Add a single load handler to the image using .one().
$("#img1").attr("src", "pic1.png").one('load',function() {
alert($(this).width());
});
or in case the image was cached, you can try this:
$("#img1").attr("src", "pic1.png").each(function() {
if( this.complete ) {
alert($(this).width());
} else {
$(this).one('load',function() {
alert($(this).width());
});
}
});
As noted by @Humberto, you were using scr instead of the proper src.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Compound assignment operators with self in C++
To compute the square of 2.0, does this code
double a = 2.0;
a *= a;
have well defined behavior? And, equivalently, with all the other compound assignment operations and build-in types.
A:
It's legal, because (C++11, §1.9/15): "The value computations of
the operands of an operator are sequenced before the value
computation of the result of the operator" or (C++03, §5/4):
"Between the previous and next sequence point a scalar object
shall have its stored value modified at most once by the
evaluation of an expression. Furthermore, the prior value shall
be accessed only to determine the value to be stored." (In
a *= a, the a on the left side is accessed only to determine
the value to be stored. And the evaluation of the a on the
left side is a "value computation", without side effects.)
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Ember (data) linkTo without passing model, just fetch new model
When using the linkTo helper in a handlebars template, Ember sets up the correct URL for the link with the help of the serializer I have added to the route:
serialize: function(slug, params) {
var name, object;
object = {};
name = params[0];
object[name] = slug;
return object;
}
And when I click the link, Ember transitions to the correct page with the correct slug and everything, but it doesn't have the correct data, and it says that. I believe it's because what I pass to my linkTo statement as second parameter is just the slug and not the whole model.
Is it possible to get Ember to simply fetch the data as it would if I just typed the URL into the address bar instead of relying on the model (that is not) passed to the linkTo statement?
UPDATE
I have tried this inside the activate method on my route, but now it seems the problem is that the rendering has to wait until this is done.
activate: function() {
this.context.isLoaded = false;
this.model(this.context.query.slug);
}
Any ideas? Maybe even with a prettier solution?
A:
The solution I came up with at last, with help from some guys on IRC, was to use the setupController hook, like you mention, Darshan, and the serializer like this:
CustomRoute = Ember.Route.extend({
setupController: function(controller, model) {
var modelName = this.routeName.substr(0, 1).toUpperCase() + this.routeName.substr(1),
slug = model;
if (model.hasOwnProperty('slug'))
slug = model.slug;
controller.set('model', App[modelName].find({'slug': slug}));
},
serialize: function(slug, params) {
var name, object;
object = {};
name = params[0];
object[name] = slug;
return object;
}
});
This way, you can supply just the slug of the route as the second parameter to the linkTo helper instead of a model, and the serializer will set the URL up properly, and then the setupController will check if the model has a property slug, which properly means it's a proper model, and if it does not, it just guesses that the model is simply the slug, and then it will use the DS.Model.find method to return a promise to the controllers model store.
Because setupController is called everytime a route is entered, where as the model hook is only called sometimes, the DS.Model.find method will be used everytime to fetch the data via the promise, and voila - fetch data each time you enter a route.
This assumes that you use Ember.Data and that your model object is called App.*route name* starting with a capital letter, but it can easily be modified to fit whatever need one might have.
For all of the routes in my app I now subclass (extend) from this route thus getting my desired behaviour for all of my routes.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
how can I extract text from R's help command?
Possible Duplicate:
R help page as object
I can do
temp <- help('ls')
But I can't get a handle on this object. I don't think there's much meat in it except a call is there? unclass, str, attributes don't seem to lead anywhere.
I would like to, for example,
(1) Extract the text of the Details section of the help for ls; and
(2) Extract all the text into one big string.
Any ideas? Thanks
A:
help itself doesn't return anything useful. To get the help text, you can read the contents of the help database for a package, and parse that.
extract_help <- function(pkg, fn = NULL, to = c("txt", "html", "latex", "ex"))
{
to <- match.arg(to)
rdbfile <- file.path(find.package(pkg), "help", pkg)
rdb <- tools:::fetchRdDB(rdbfile, key = fn)
convertor <- switch(to,
txt = tools::Rd2txt,
html = tools::Rd2HTML,
latex = tools::Rd2latex,
ex = tools::Rd2ex
)
f <- function(x) capture.output(convertor(x))
if(is.null(fn)) lapply(rdb, f) else f(rdb)
}
pkg is a character string giving the name of a package
fn is a character string giving the name of a function within that package. If it is left as NULL, then the help for all the functions in that package gets returned.
to converts the help file to txt, tml or whatever.
Example usage:
#Everything in utils
extract_help("utils")
#just one function
extract_help("utils", "browseURL")
#convert to html instead
extract_help("utils", "browseURL", "html")
#a non-base package
extract_help("plyr")
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How to display div with JavaScript depending on which image is clicked
I wish to display certain divs inside a main div dependent on which image is clicked. With out any decent knoweldge of Js or Jquery, I fail to do this without some assistance.
<form>
<input type="hidden" name="prod">
<div id="images">
<img id="one" src="http://lorempixel.com/200/200/">
<img id="two" src="http://lorempixel.com/201/200/ ">
<img id="three" src="http://lorempixel.com/203/200/ ">
<img id="four" src="http://lorempixel.com/204/200/ ">
</div>
</form>
<div id="description">
</div>
<div class="one">Brilliant</div>
<div class="two">Super</div>
<div class="tree">Amazing</div>
<div class="four">Excellent</div>
If the image which has id="one" is clicked, then display <div class="one">Brilliant</div> inside of the description div. Then ofcause if the second image is clicked, then display the the 'super' div inside the description div. I'd like to not have the descriptions visible until clicked, and only one div at a time to be shown.
The images are apart of a form because I need to forward the value of the id on the images to a variable.
Here is the script that does that.
$('#images').delegate('img', 'click', function () {
var $this = $(this);
// Clear formatting
$('#images img').removeClass('border-highlight');
// Highlight with coloured border
$this.addClass('border-highlight');
// Changes the value of the form field prod to the file name shown in the image.
$('[name="prod"]').val($this.attr('id').substring($this.attr('id').lastIndexOf('-') + 1));
//Alert for debugging simplicity
alert($('[name="prod"]').val());
});
Perhaps a function can be implemented into the current script?
Here is a fiddle, and it will all make sense of what I have as a whole currently.
A:
Check out this fidde
You just need to add:
$('#description').html($('.' + $this.attr('id')).html());
At the bottom of your onclick function.
** You have a typo on the 3rd div with text(tree instead of three).
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Android: webView app crashes
I have a webView app. Is a list of links to some tv online streaming channels.
Some links are m3u8 and others are sop.
If I access a m3u8 link it opens in default media player, if i try to open the sop links, and I do not have SopCast Player installed, my app crashes,
and I got the error below.
If I have installed SopCast Player, evetrything is ok.
I'm now with Android.
My files:
Manifest
ManinActivity
Error:
android.content.ActivityNotFoundException: No Activity found to handle Intent { act=android.intent.action.VIEW dat=sop://111.175.143.195:3912/151638 }
at android.app.Instrumentation.checkStartActivityResult(Instrumentation.java:1409)
at android.app.Instrumentation.execStartActivity(Instrumentation.java:1379)
at android.app.Activity.startActivityForResult(Activity.java:2827)
at android.app.Activity.startActivity(Activity.java:2933)
at com.example.tv.MainActivity$1.shouldOverrideUrlLoading(MainActivity.java:47)
at android.webkit.CallbackProxy.uiOverrideUrlLoading(CallbackProxy.java:239)
at android.webkit.CallbackProxy.handleMessage(CallbackProxy.java:346)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:130)
at android.app.ActivityThread.main(ActivityThread.java:3735)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:507)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:904)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:662)
at dalvik.system.NativeStart.main(Native Method)
Please, please, please, help me!!
Sorry for my english.
A:
In your shouldOverrideUrlLoading() you should replace startActivity(i); with
try {
startActivity(i);
} catch (ActivityNotFoundException e) {
// do what you want if appropriate app is not installed
}
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Is it possible to compare tuples in oracle-compatible sql?
I'm not 100% if tuples is the term for what I'm talking about but I'm looking at something like this:
Table grades
user grade
------------
Jim B
Bill C
Tim A
Jim B+
I know I can do:
SELECT COUNT(*)
FROM grades
WHERE (
(user = 'Jim' AND grade = 'B')
OR (user = 'Tim' AND grade = 'C')
);
But is there a way to do something more like this?
SELECT COUNT(*)
FROM grades
WHERE (user, grade) IN (('Jim','B'), ('Tim','C'));
EDIT: As a side note, I'd only tested with:
(user, grade) = ('Tim','C')
And that fails, so I assumed IN would fail as well, but I was wrong (thankfully!).
A:
The query you posted should be valid syntax
SQL> ed
Wrote file afiedt.buf
1 with grades as (
2 select 'Jim' usr, 'B' grade from dual
3 union all
4 select 'Bill', 'C' from dual
5 union all
6 select 'Tim', 'A' from dual
7 union all
8 select 'Jim', 'B+' from dual
9 )
10 select *
11 from grades
12 where (usr,grade) in (('Jim','B'),
13 ('Tim','C'),
14* ('Tim','A'))
SQL> /
USR GR
---- --
Jim B
Tim A
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Extract balls from urn probability
We have two urns, the first with 6 white balls and 7 black balls and the second with 10 white balls and 5 black balls.
We extract a ball from the first urn and introduce it into the second one, then we extract from the second urn 5 balls,reintroducing them back after each extraction.Whats the probability all the 5 balls are white? What scheme could be used here? Is it Poisson and if yes how to use it given the fact that theres and extraction with replacement?
A:
Case 1) We initially extracted a white ball with probability $\frac{6}{13}$. Then the second urn has $11$ white balls and $5$ black balls. The probability that all $5$ selected are white is then $$\left(\frac{11}{16}\right)^5$$
Case 2) We initially extracted a black ball with probability $\frac{7}{13}$. Then the second urn has $10$ white balls and $6$ black balls. The probability that all $5$ selected are white is then $$\left(\frac{10}{16}\right)^5$$
All together we get
$$\left(\frac{6}{13}\cdot\left(\frac{11}{16}\right)^5\right)+\left(\frac{7}{13}\cdot\left(\frac{10}{16}\right)^5\right)\approx0.1222$$
|
{
"pile_set_name": "StackExchange"
}
|
Q:
MSSQL2014 & python 3.7.3: Trying to get stored procedure return value results in "No results. Previous SQL was not a query."
I'm running a python script which connects to a MSSQL database, runs a stored procedure and should take a some actions depending on the stored procedure return value. Here's the code:
'''
sql = """\
SET NOCOUNT ON
DECLARE @rv INT
EXEC @rv = [MY_DB].[dbo].[sp_Load_Actuals]
SELECT @rv
"""
...
conn = pyodbc.connect('Driver={ODBC Driver 13 for SQL Server};'
'Server=MY_SERVER;'
'Database=MY_DB;'
'Trusted_Connection=yes;')
conn.autocommit = True
cursor = conn.cursor()
cursor.execute(sql)
retv = cursor.fetchone()
...
On the execution of the last statement I'm catching the pyodbc.DatabaseError exception with the message "No results. Previous SQL was not a query." I have read all related articles here, but apparently I'm still doing something wrong.
What do I miss?
A:
You have to call cursor.nextset() to skip past any info messages that were output by the called stored procedures, as NOCOUNT ON is not enough here.
But unfortunately cursor doesn't have a .hasrows() method, so you have to catch the exception in a loop.
EG:
import pyodbc
sql = """\
SET NOCOUNT ON
DECLARE @rv INT
EXEC @rv = sp_executesql N'print ''informational message'''
SELECT @rv
"""
conn = pyodbc.connect('Driver={ODBC Driver 17 for SQL Server};'
'Server=localhost;'
'Database=tempdb;'
'Trusted_Connection=yes;')
conn.autocommit = True
cursor = conn.cursor()
cursor.execute(sql)
while True:
try:
retv = cursor.fetchone()
break
except pyodbc.ProgrammingError as e:
if "Previous SQL was not a query." in str(e):
if not cursor.nextset():
throw
print(retv)
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Build object from function parameters
I often find myself writing code like this:
function handleSomeEvent(p1, p2, p3) {
var data = { p1: p1, p2: p2, p3: p3 };
//Or any other function that takes an object
$.ajax('/url', { data: data, ... });
}
Is there a way that I can build the data object automatically from my function's parameters?
I know that I could pass in an object instead, but sometimes it's more convenient to pass in multiple parameters (for example integrating with legacy code, or a project's existing coding style).
A:
ES2015 shorthand object literals reduce some of the repetition:
function handleSomeEvent(a, b, c) {
console.log({ a, b, c })
}
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Jquery draggable outside of overflow hidden?
Here is what i have for now, look on stackoverflow everywhere and all solution didnt worked for me :( The problem is that i use draggable and resizable on some elements etc. pictures that are places in container that has overflow property.That comes the problem with draggable, i want ot move that object over the picture at the top of the page, but the element always goes under the picture on top.Strane issue is if i first to resizable, than i possible to move element over the picture, before that no a change :( Another strane problem is that i first to resizable, second object comes over that element, just overlaping it?
I have tried many solution for this two fixes, but no luck. Here is what i have for now
CSS
#zidomotac{
width:100%;
}
#myWorkContent{
width:100%;
overflow-x: scroll;
white-space: nowrap;
box-sizing:border-box;
margin-bottom:20px
}
.slikezamenjanje{
width: 100px;
float:left;
display: inline-block;
vertical-align: middle;
}
.slikezamenjanje img{
max-height: 120px;
overflow:hidden;
width: 100%;
}
EXTERNAL
<link rel="stylesheet" href="http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js" type="text/javascript"></script>
<script src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script>
FUNCTIONS
<script type="text/javascript">
$(document).ready(function() {
$('.slikezamenjanje').draggable().resizable({
aspectRatio: 16 / 9,
});
});
</script>
HTML
<div id="zidomotac"><img src="http://www.vectorimages.org/09/0920100513111825424.jpg"></div>
<div id="myWorkContent">
<div class="slikezamenjanje"><img src="http://placekitten.com/200/200/"/></div>
<div class="slikezamenjanje"><img src="http://placekitten.com/200/200/"/></div>
</div>
</div>
This is the working jsfiddle
http://jsfiddle.net/gorostas/CS93M/
I hope someone will find solution
EDITED
Maybe i can make first invoke resizable and then inside draggable?
UPDATE
If i use draggable like this
$(document).ready(function() {
$(".slikezamenjanje").draggable({
revert: "invalid" ,
helper: function(){
$copy = $(this).clone();
return $copy;},
appendTo: 'body',
scroll: false
});
});
I can move element over, but the problem it is coming back?
A:
I fixed the fiddle, I hope it does what you wanted !
You can try it here :
DEMO
What I've changed :
JQuery :
$(function() {
$( ".slikezamenjanje" ).draggable({
revert: 'invalid',
helper: 'clone',
start: function(){ //hide original when showing clone
$(this).hide();
},
stop: function(){ //show original when hiding clone
$(this).show();
}
});
$( "#zidomotac" ).droppable({ //set container droppable
drop: function( event, ui ) { //on drop
ui.draggable.css({ // set absolute position of dropped object
top: ui.position.top, left: ui.position.left
}).appendTo('#zidomotac'); //append to container
}
});
});
I added a droppable state on your container, so you will be able to drag and drop inside.
Then I used the drop event which allows me to get the element (ui.draggable) and the position (ui.position) of the dropped element.
So I set the absolute position with .css() and then append to the container with .appendTo().
For .draggable(), I just added start and stop events to show/hide original element when the clone is hidden/shown.
CSS :
/* Custom style for dropped element */
#zidomotac .slikezamenjanje {
position: absolute;
}
Just added this class to apply style for dropped element.
Hope I helped you ;)
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Matrices similar to their inverse or transpose
What can you say about matrix $A\in M_n(\mathbb R)$ if you know that:
1) it is similar to its inverse matrix.
2) it is similar to its transpose matrix and similar to some diagonal matrices.
1) you write that $A=S^{-1}A^{-1}S$, I know that they have same eigenvalues, so $\det A\not =0$ $\operatorname{rank}A=n$, $\dim\ker(A)=0$, but can I say something more about this matrix, I saw that you can write like this $A=(AS)^{-1}S$, but I do not know is that help, can you help me?
2) $A=S^{-1}A^{T}S$ and $A=S^{-1}\Lambda S$, here I have no idea, do you have some idea? I read about similarity but I can not find so much about it, only that they have same rank, eigenvalues, characteristic polynomial.
A:
1) On the one hand, $A$ and $A^{-1}$ have the same eigenvalues, as you observed. On the other hand, the eigenvalues of $A^{-1}$ are the reciprocals of those of $A$ (in general). So you can say quite a lot about the possible eigenvalues.
2) Prove that if $A$ is diagonalizable, then it satisfies this condition.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Look for matches in PHP array then combine the array without any overwriting
I have an array and I can't seem to figure out how to look at each array item and check if a [Product Name] matches another array item's [Product Name] or not?
Below is sample data. For example, array[0] and array[1] both have the same [Product Name] of test but different values for things like [Variant Name] or [Variant Full Stock]. I want to be able to find matches like that and combine those somehow to one array but not overwrite anything.
Array (
[0] => Array (
[Product Name] => test
[Variant Name] => Default
[Variant SKU] =>
[Variant In Stock] => 1
[Variant Full Stock] => 1
[id] => 0
)
[1] => Array (
[Product Name] => test
[Variant Name] => testingVar
[Variant SKU] =>
[Variant In Stock] => 1
[Variant Full Stock] => 2
[id] => 1
)
[2] => Array (
[Product Name] => another test
[Variant Name] => Default
[Variant SKU] =>
[Variant In Stock] => 1
[Variant Full Stock] => 1
[id] => 2
)
)
Ideally, I would want to convert the above array to a new array that would output something like this:
Array (
[0] => Array (
[0] => Array (
[Product Name] => test
[Variant Name] => Default
[Variant SKU] =>
[Variant In Stock] => 1
[Variant Full Stock] => 1
[id] => 0
)
[1] => Array (
[Product Name] => test
[Variant Name] => testingVar
[Variant SKU] =>
[Variant In Stock] => 1
[Variant Full Stock] => 2
[id] => 1
)
)
[1] => Array (
[Product Name] => another test
[Variant Name] => Default
[Variant SKU] =>
[Variant In Stock] => 1
[Variant Full Stock] => 1
[id] => 2
)
)
Any solutions?
A:
All you need to do is iterate the array and group by Product Name
$data =
array(
array(
"Product Name" => "test",
"Variant Name" => "Default",
"Variant SKU" => "",
"Variant In Stock" => 1,
"Variant Full Stock" => 1,
"id" => 0
),
array(
"Product Name" => "test",
"Variant Name" => "testingVar",
"Variant SKU" => "",
"Variant In Stock" => 1,
"Variant Full Stock" => 2,
"id" => 1
),
array(
"Product Name" => "another test",
"Variant Name" => "testingVar",
"Variant SKU" => "",
"Variant In Stock" => 1,
"Variant Full Stock" => 2,
"id" => 2
),
);
$result = array();
foreach($data as $item) {
$key = $item["Product Name"];
$result[$key][] = $item;
}
$result looks like this:
array(2) {
["test"]=>
array(2) {
[0]=>
array(6) {
["Product Name"]=>
string(4) "test"
["Variant Name"]=>
string(7) "Default"
["Variant SKU"]=>
string(0) ""
["Variant In Stock"]=>
int(1)
["Variant Full Stock"]=>
int(1)
["id"]=>
int(0)
}
[1]=>
array(6) {
["Product Name"]=>
string(4) "test"
["Variant Name"]=>
string(10) "testingVar"
["Variant SKU"]=>
string(0) ""
["Variant In Stock"]=>
int(1)
["Variant Full Stock"]=>
int(2)
["id"]=>
int(1)
}
}
["another test"]=>
array(1) {
[0]=>
array(6) {
["Product Name"]=>
string(12) "another test"
["Variant Name"]=>
string(10) "testingVar"
["Variant SKU"]=>
string(0) ""
["Variant In Stock"]=>
int(1)
["Variant Full Stock"]=>
int(2)
["id"]=>
int(2)
}
}
}
Not exactly what you had in mind, but perhaps a bit more usable?
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How to use as.hexmode width
According to the R documentation:
as.hexmode(x)
## S3 method for class 'hexmode'
as.character(x, ...)
## S3 method for class 'hexmode'
format(x, width = NULL, upper.case = FALSE, ...)
## S3 method for class 'hexmode'
print(x, ...)
Arguments
x An object, for the methods inheriting from class "hexmode".
width NULL or a positive integer specifying the minimum field width
to be used, with padding by leading zeroes.
If I call in R 3.02:
> hex <- "5"
> as.hexmode(hex,width=2)
I get the error:
Error in as.hexmode(hex, width = 2) : unused argument (width = 2)
How do I call as.hexmode correctly?
A:
The width parameter belongs to format (well, format.hexmode), not as.hexmode:
format(as.hexmode(hex), width=2)
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Does SetThreadToken() keep the impersonation token alive?
While the main thread impersonates a client, my code creates a thread and assigns it the impersonation token using SetThreadToken. Then the main thread closes the token.
Specifically, the main thread does this:
Get a primary token using LogonUser.
Get an impersonation token using DuplicateToken from the primary token.
Call ImpersonateLoggedOnUser.
Spawn a secondary thread and call SetThreadToken on the thread with the impersonation token.
RevertToSelf.
CloseHandle on both the impersonation and the primary token.
At this point, the secondary thread is still running. Does the impersonation token remain usable for the secondary thread even though the token handle has been closed in the main thread?
A:
windows kernel use reference counting on objects. the TOKEN is object too. when you assign token to thread (via SetThreadToken) the pointer to TOKEN object is stored in ETHREAD object and additional reference added to TOKEN object. of course kernel cannot rely on close you or not original handle (reference) to TOKEN object. this is general pointer counting rule - if A stored pointer to B in self - it add reference to B, for it will be valid until A use B. the token will be valid until your thread not impersonate another token, or end impersonation or exit. anyway after you assign token to thread you can close handle to it - token remain valid
if exist interest, how internal SetThreadToken work:
SetThreadToken call NtSetInformationThread with ThreadImpersonationToken information class. from kernel side implementation called PsAssignImpersonationToken - this api declared in ntifs.h. it implementation call PsImpersonateClient which and reference the passed token. as result it become valid util assigned to thread
The server thread could already be impersonating a client when
PsImpersonateClient is called. If this is the case, the reference
count on the token representing that client is decremented.
but anyway - we not need for this internal knowledge - need general think understand - object reference counting. if pointer to token saved in thread - this token of course must be valid until used by thread. as result it referenced. when thread stop using this token (change pointer or exit) - token dereferenced
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Reducing the size of executable from py2exe
Are there some practices to minimize the size of .exe file created by py2exe when creating executable of python script? My first impression upon using py2exe is, it creates relatively large size file.
A:
There is an option to compress, which you can enable in the config file, but it will always be relatively large (~megabytes) because python interpreter must also be bundled in with the source code.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How prove this $\max_i|\textbf{p}_i(t)|\leq \max_i|\textbf{p}_i(0)|$
Let
$$\sum_{j=1}^N a_{ij}=1, \ \ \ \ i=1,\dots,N$$
and consider
$$\frac{d}{dt}\textbf{p}_i=\bar{\textbf{p}}_i-\textbf{p}_i, \ \ \ \bar{\textbf{p}}_i:=\sum_{j=1}^N a_{ij} \textbf{p}_j.$$
Prove that
$$\max_i|\textbf{p}_i(t)|\leq \max_i|\textbf{p}_i(0)|.$$
A:
When it comes to differential inequalities, you need to add Gronwall's inequality to your belt. If
$$ \frac{d}{dt} y \leq p(t) y$$
then you may conclude (where existence permits)
$$ y(t) \leq y(a) \exp \left (\int_a^t p(s) ds \right)$$
Note that with your condition on $A$ you have
$$\sum_{j=1}^N a_{ij} p_j \leq \max_{i}|p_i|$$
Skipping over a few technical details (which you should verify), we'll see (from your original differential inequality)
$$\frac{d}{dt} \max_{i}|p_i| \leq 0$$
Thus
$$\max_{i}|p_i| \leq \max_{i} | p_i(0)| $$
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Is the word "midst" still in common usage?
In written and spoken English, including today's publications and everyday conversations, is the word midst still in common usage, particularly the phrase, in the midst of? Or has it been replaced by middle (at least in common usage), such as the phrase, in the middle of.
Are there any meaningful distinctions between midst and middle, or between the phrases I cite above? Or is it mostly a matter of style? Is one more dated and old-fashioned than the other? Is midst no longer fashionable?
I notice that the ESV uses midst in Genesis 1:6, so this is at least one piece of evidence that the word is still fashionable, at least in written documents that are relatively recent. But I would be curious to see its usage elsewhere.
A:
I would think it less common than "middle" for this usage but not necessarily unpopular or deprecated. If anything, midst definitely has the air of permeating an ambiance or congruent form, as opposed to middle, which is a more literal representation of location. For example, it is possible to use "midst" and "middle" in the following:
It feels like I am standing in the midst of a fog.
It feels like I am standing in the middle of a fog.
...but while it is possible to use it in this other way, the meaning changes:
There is a pit in the midst of this plum.
There is a pit in the middle of this plum.
Here, "In the midst" gives the implication that it is somewhere within the congruence of the plum (could be up top, however inside, or off to the side) but "In the middle" is clear about the location being dead center. Therefore, "midst" has a meaning that is probably closer to the word "within". For this reason, usage for these words differ, and so the word choice comes down to what you're trying to express.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Custom type in GreenDao with POJO class
This is my sample JSON:
{
"open":true,
"total_products":100,
"product":[
{
"p_id":1,
"price":"5.00",
"name":"blah one"
},
{
"p_id":2,
"price":"15.00",
"name":"blah two"
},
...
]
}
This is my POJO class:
@Entity(nameInDb = "products")
public class ProductsPOJO {
@SerializedName("open")
@Property(nameInDb = "open")
private boolean open;
@SerializedName("total_products")
@Property(nameInDb = "total_products")
private Long total_products;
@Convert(converter = ProductConverter.class, columnType = String.class)
@SerializedName("product")
@Property(nameInDb = "product")
private Product product;
public static class productConverter implements PropertyConverter<Product, String> {
//What shoudl I write in convert part?!
@Override
public Product convertToEntityProperty(String databaseValue) {
if (databaseValue == null) {
return null;
}
for (Product p : Product.values()) {
if (p.id == databaseValue) {
return p;
}
}
return Product.DEFAULT;
}
@Override
public String convertToDatabaseValue(Product entityProperty) {
return entityProperty == null ? null : entityProperty.;
}
//
/*@Override
public Product convertToEntityProperty(String databaseValue) {
return Product.valueOf(databaseValue);
}
@Override
public String convertToDatabaseValue(Product entityProperty) {
return entityProperty.name();
}*/
}
public static class Product{
@Id
@SerializedName("p_id")
private Long p_id;
@SerializedName("price")
@Property(nameInDb = "price")
private String price;
@SerializedName("name")
@Property(nameInDb = "name")
private String name;
//Getters & Setters
}
public Product getProduct() {
return product;
}
public void setProduct(Product data) {
this.product = product;
}
//open & total_products Getters & Setters
}
But I don't know what should I write for productConverter.
In other hand, fields in Product class have multiple types. String and Integer.
I read these:
https://github.com/greenrobot/greenDAO/blob/V3.1.1/examples/DaoExample/src/main/java/org/greenrobot/greendao/example/Note.java#L26-L27
http://greenrobot.org/greendao/documentation/custom-types/
A:
It was because of
"GSON Expected BEGIN_ARRAY but was BEGIN_OBJECT"
Should do something like this:
JsonParser parser = new JsonParser();
JsonObject rootObject = parser.parse(JSON_STRING).getAsJsonObject();
//You can get the "open" and "total_products" here too.//
JsonElement productElement = rootObject.get("product");
Gson gson = new Gson();
List<Product> productList = new ArrayList<>();
//Check if "data" element is an array or an object and parse accordingly...
if (productElement.isJsonObject()) {
//The returned list has only 1 element
Product p = gson.fromJson(productElement, Product.class);
productList.add(p);
}
else if (productElement.isJsonArray()) {
//The returned list has >1 elements
Type productListType = new TypeToken<List<Product>>() {}.getType();
productList = gson.fromJson(productElement, productListType);
}
[ Source: https://stackoverflow.com/a/16656096/421467 ]
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Configuring Logstash when installed as a service
I have installed logstash as a service using the logstash APT repository on Ubuntu 13.10.
So now I can run:
dpkg -s logstash
And it outputs:
Package: logstash
Status: install ok installed
Priority: extra
Section: default
Installed-Size: 93362
Maintainer: <jls@ds4172>
Architecture: all
Version: 1.4.0-1-c82dc09
Depends: java7-runtime-headless | java6-runtime-headless | j2re1.7
Conffiles:
/etc/default/logstash 399f19c4d762840a36f6bc056c3739b8
/etc/default/logstash-web d94db9f8dc1d4ced449175a96e8df09d
/etc/logrotate.d/logstash 9bb11b4b058868bb41c658c9c3152a83
Description: An extensible logging pipeline
License: Apache 2.0
Vendor: Elasticsearch
Homepage: http://logstash.net
So I see that the logstash service was successfully installed.
I know that running logstash (not as a service) I can specify a configuration like so:
bin/logstash -f /path/to/config-file
But how would I specify a specific configuration when I am running logstash as a service?
A:
you got configuration of logstash in directory /etc/logstash/conf.d/
You got all paths in /etc/init.d/logstash
# logstash configuration directory
CONF_DIR=/etc/logstash/conf.d
I got there file /etc/logstash/conf.d/logstash.conf which is automaticlly generated by puppet logstash module :)
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Reducing arrays into array in MPI Fortran
I'm somewhat new to MPI in Fortran. I have a MPI code where each processor does Ns simulations. So at then end I should have (mysize x Ns x 2) results, because I create for each simulation and each proc a 2-D array called PHI and a second array PHI^2 corresponding to squaring each value of PHI.
Then, after all the simulations in Ns, I generate for each proc a PHI_AVG_RANK array that is basically SUM(PHI)/Ns and a PHI^2_AVG_RANK for the PHI^2, similarly.
I want to send all of the resulting matrices PHI_AVG_RANK that are coming from each processor (a total of mysize matrices) to a mother processor through a reduction sum, to then do the average again over mysize, both for the PHI_AVG_RANK and the PHI**2_AVG_RANK. The reason for doing this is that I want to compute the RMS matrix over all (mysize x Ns) realizations, that is, sqrt(SUM(PHI^2_AVG_RANK)/mysize - (SUM(PHI_AVG_RANK)/mysize)^2), and then save it to a txt.
To do so, which datatype can be used? Contiguous, Vector, or Subarray? Is Reduce the best call to be done here?
This is my plan so far (piece of code after doing all the Ns simulations, i come up with a 100x100 matrix called phi_moyen_1_2 for each processor, and want to sum it all into the new matrix 100x100 called mean_2_025, then save it:
call MPI_BARRIER(MPI_COMM_WORLD,ierr)
call MPI_TYPE_CONTIGUOUS(100,MPI_REAL,row,ierr)
call MPI_TYPE_CONTIGUOUS(100,row,matrix,ierr)
if (myrank==0) then
call MPI_REDUCE(phi_moyen1_2,mean_2_025,1,matrix,MPI_SUM,0,MPI_COMM_WORLD,ierr)
open(unit=1234, file='../results/PHI1/TESTE/teste.txt')
do i=0,Nx-1
write(ligne, *) mean_2_025(i,:)
write(1234,'(a)') trim(ligne)
end do
close(unit=1234)
endif
EDIT: After implementing the suggestion by @David Henty, we don't need to use CONTIGUOUS data types. We can actually do it straight withuot any intermediate data types and COMMIT clauses, since Fortran access each array element already. THen I did the followning:
if (myrank==0) then
call MPI_REDUCE(phi_moyen1_2,mean_2_025,100*100,MPI_DOUBLE,MPI_SUM,0,MPI_COMM_WORLD,ierr)
mean_2_025=mean_2_025/(mysize)
write(*,*) mean_2_025(1,1)
But the program does not end (as if it was going through an infinite loop) and it does not print anything into the output file (it was supposed to show nprocs numbers for the 1st entry of the matrix mean_2_025 because of the write above). I've done some cpu_time at the end of the program and it shows nprocs cpu times so it means every processor gets through until the end?
EDIT, SOLVED: As @Vladimir F pointed out, the collective call REDUCE is made by all processors (even though it has a root processor inside the call). Thus it cannot be inside an if clause, causing the infinite loop (other processors were not able to acess the REDUCE).
Thanks to everyone.
A:
All you need to do is specify the type as MPI_REAL and the count as 100*100. For a reduce, the reduction is done separately for each element of the array so this will do exactly what you want, i.e. for all 100*100 values of i and j then, on rank 0, mean_2_025(i,j) will be the sum across all ranks of phi_moyen1_2(i,j).
call MPI_REDUCE(phi_moyen1_2,mean_2_025,100*100,MPI_REAL,MPI_SUM,0,MPI_COMM_WORLD,ierr)
To get the average, just divide by size. On a technical note, you don't need the barrier as MPI does all the synchronisation you require inside the collective.
Using datatypes is overcomplicating things here. You would need to commit them first, but more importantly the reduction operation won't know what to do with data of type "matrix" unless you tell it what to do by defining and registering your own reduction operation.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How many edges does an undirected tree with $n$ nodes have?
How many edges does an undirected tree with $n$ nodes have?
A:
This is a very standard fact; any basic text will tell you that an undirected tree with $n$ nodes must have exactly $n-1$ edges. You can prove this by induction on $n$. Clearly a tree with one node has no edges. Suppose that every tree with $n$ nodes has $n-1$ edges, and let $T$ be a tree with $n+1$ nodes. $T$ must have a leaf, i.e., a node $v$ such that $\deg v=1$. (If not, $T$ would contain a circuit: why?) Remove $v$ and the one edge incident at $v$. What’s left is still a tree (why?), and it has only $n$ vertices, so it has $n-1$ edges. Thus, $T$ must have had $(n-1)+1=n$ edges.
A:
Here is a simple intuitive proof I first saw in a book by Andy Liu:
Imagine the tree being made by beads and strings. Pick one bead between your fingers, and let it hang down.
Since the tree is connected, it all hangs in one piece. And because it has no cycles, each bead lies at the end of one string, and for each string there is a bead at the end. Thus, you can pair each string with exactly one bead: the bead at the end.
This means there are as many strings as the beads you can see. As there is a hidden bead, the number of beads is 1 more than the number of strings....
A:
HINT: Suppose we have an undirected tree T (a loop-free connected undirected graph that contains no cycles) with N vectices (nodes). If T has N or more edges, then there must exist a cycle contradicting that T is a tree.
Why is this?
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Prove that continuous functions mapping irrationals to rationals must be constant
Let $f\colon[0,1] \to \mathbb{R}$ be a continuous function
such that any irrational number is mapped to a rational number. Then $f$ must be a constant.
Well, the context isn't that much, I was reading some interesting function constructions on Hardy's book. Then raised this question.
As the solution suggest it is an elementary exercise. But definitely interesting.
A:
For convenience, let $\mathbb{I} = [0,1]\cap (\mathbb{R}\setminus\mathbb{Q})$, which is uncountable, and $\mathbb{J} = [0,1]\cap\mathbb{Q}$, which is countable.
$f(\mathbb{I}) \subseteq \mathbb{Q}$ is countable.
$f(\mathbb{J})$ is countable since $\mathbb{J}$ is.
So $f([0,1])=f(\mathbb{I})\cup f(\mathbb{J})$ is countable.
Now, $[0,1]$ is an interval, and the image of an interval by a continuous function is an interval. So $f([0,1])$ is a countable interval, which means...
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How can I get a Row in flutter to fill the entire space without overflowing?
I always have problems with UI in flutter, especially when going to rows/colums and their size. Basically what I have is A Row with a picture and a column in it. The first thing I want to have is a Row with MainAxisAllignment.Spacebetween, so that TextA and TextB are as far away from each other as possible. I cannot have two columns, because then the TextD, which can be pretty long, would push TextB off screen. i tried around with some expanded, flexible and mainaxissize, but I have honestly no idea how this should be done.
Usually I'd MSPaint but I'm on a Mac and don't know of anything as perfect as paint, so here my beautiful Drawing of what it looks like. the 'should' state will be TextB on the different end of the inner row
|---------------------------------------------------|
| I |--------------------------------------------||
| M | |TextATextB| ||
| A | |-Row------| ||
| G | TextC ||
| E | TextD ||
| |-Column-------------------------------------||
|-Row-----------------------------------------------|
Row(
children: <Widget>[
Image.network(
picture,
height: 63,
),
SizedBox(
width: 6,
),
Column(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: <Widget>[
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: <Widget>[
Text(_viewModel.time),
Text(_viewModel.session),
],
),
Text(_viewModel.room),
SizedBox(
height: 2,
),
Text(
_viewModel.title,
overflow: TextOverflow.ellipsis,
maxLines: 1,
style: TextStyle(fontWeight: FontWeight.w900),
),
],
),
],
),
And this is the code on how I did this widget. Thanks!
edit: with Excel i made a hopefully not confusing version. basically: i wanna make the row as long as the column is wide
A:
That was a neat question. As per the requirement, you have done most of the part, some improvements were missing, hence, I am adding this into your code, hope that'd help you in great extent :)
CrossAxisAlignment.stretch is the key
Make sure to use Expanded and wrap it around your Column to work
FINAL SOLUTION
// I have not used your data, just used mine for image, texts
Row(
mainAxisAlignment: MainAxisAlignment.start,
children: <Widget>[
Image.network(
"https://images.unsplash.com/photo-1494548162494-384bba4ab999?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&w=1000&q=80",
height: 63.0,
width: 63.0
),
SizedBox(width: 6.0),
Expanded(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.stretch,
children: <Widget>[
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: <Widget>[
Text('Text A'),
Text('Text B'),
],
),
Text('Text C'),
SizedBox(height: 2.0),
Text(
'Text D',
overflow: TextOverflow.ellipsis,
maxLines: 1,
style: TextStyle(fontWeight: FontWeight.w900),
),
]
)
)
]
)
RESULT YOU WILL GET IS
I hope that is what you wanted :) Happy learning
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How to get motion events with the Apple TV remote
Has anybody figured out how to get motion events working with the new apple TV remote? Thanks.
I've tried calling
override func motionBegan(motion: UIEventSubtype, withEvent event: UIEvent?) {
super.motionBegan(motion, withEvent: event)
print("motion!")
}
override func motionEnded(motion: UIEventSubtype, withEvent event: UIEvent?) {
super.motionEnded(motion, withEvent: event)
print("motion ended!")
}
With and without calling super gives me nothing.
A:
A great swift example can be found here:
https://forums.developer.apple.com/message/65560#65560
It's basically what Daniel Storm said above, but following this got it working for me. Here's what I did.
In appDelegate:
var motionDelegate: ReactToMotionEvents? = nil
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
let center = NSNotificationCenter.defaultCenter()
center.addObserver(self, selector: "setupControllers:", name: GCControllerDidConnectNotification, object: nil)
center.addObserver(self, selector: "setupControllers:", name: GCControllerDidDisconnectNotification, object: nil)
GCController.startWirelessControllerDiscoveryWithCompletionHandler { () -> Void in
}
return true
}
func setupControllers(notif: NSNotification) {
print("controller connection")
let controllers = GCController.controllers()
for controller in controllers {
controller.motion?.valueChangedHandler = { (motion: GCMotion)->() in
if let delegate = self.motionDelegate {
delegate.motionUpdate(motion)
}
}
}
}
protocol ReactToMotionEvents {
func motionUpdate(motion: GCMotion) -> Void
}
Where I want it implemented, in my case an SKScene:
import SpriteKit
import GameController
class GameScene: SKScene, ReactToMotionEvents {
override func didMoveToView(view: SKView) {
let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
appDelegate.motionDelegate = self
}
func motionUpdate(motion: GCMotion) {
print("x: \(motion.userAcceleration.x) y: \(motion.userAcceleration.y)")
}
}
|
{
"pile_set_name": "StackExchange"
}
|
Q:
onchange event is not fire on asp checkbox in chrome only
This doesn't work for me in chrome
<asp:CheckBox ID="chkFullReIndex" runat="server" ClientIDMode="Static" onchange="funCalled();" />
<script>
function funCalled() {
if ($('#chkFullReIndex')[0].checked) {
alert('check box checked')
}
else {
alert('check box not checked')
}
}
</script>
This is working perfectly fine in Firefox(21.0) but not working in chrome(Version 27.0.1453.94 m)am not getting any console error for the same
any thought on the same
A:
When using inline event registration you can send this to the function:
<asp:CheckBox ID="chkFullReIndex" runat="server" ClientIDMode="Static" onchange="funCalled(this);" />
and js like:
function funCalled(obj) {
// this is present in the event handler and is sent to the function
// obj now refers to the CheckBox, so we can do
if (obj.checked) {
alert('check box checked')
} else {
alert('check box not checked')
}
}
A:
Try to use onclick event like
<asp:CheckBox runat="server" ID="chkPostback" Text="Check me" onclick="javascript:funCalled(this)"
ClientIDMode="Static" />
Script
function funCalled(obj) {
if (obj.checked) {
alert('check box checked')
} else {
alert('check box not checked')
}
}
Check
|
{
"pile_set_name": "StackExchange"
}
|
Q:
makefile is missing separator
Alright I am stuck on this and I have no idea what I am doing wrong. Everything was going great working on a more complicated makefile but then all of a sudden I got the "Missing separator" error. I was able to isolate it down to a very simple scenario:
test.mk
define push_dir
$(info ${1})
endef
define pop_dir
$(info ${1})
endef
define include_submake
$(call push_dir,${1})
$(call pop_dir,${1})
endef
Simple
include test.mk
INITIAL_SUBMAKE:= includeme.mk
$(call include_submake,${INITIAL_SUBMAKE})
process:
@echo Processed...
And the output:
C:\project>make -f Simple process
includeme.mk
includeme.mk
Simple:4: *** missing separator. Stop.
includeme.mk does not actually exist. I have no idea what is going wrong here I have tried a multitude of things. If I surround the call to include_submake in info like so:
$(info $(call include_submake,${INITIAL_SUBMAKE}))
The missing separator error goes away. Also If in the include_submake define I only call one of the functions it works fine. Additionally if I directly call the functions instead of calling them include_submake it works as well:
include test.mk
INITIAL_SUBMAKE:= includeme.mk
$(call push_dir,${INITIAL_SUBMAKE})
$(call pop_dir,${INITIAL_SUBMAKE})
process:
@echo Processed...
C:\project>make -f Simple process
includeme.mk
includeme.mk
Processed...
I feel like I'm overlooking something fundamental here. Thanks for your help.
A:
The missing separator error happens because of a non-empty return value of include_submake, which is a single line feed character in your case. Make only permits whitespace characters (that is, a space or tab) to occur in an expression which is not assumed to be a part of some rule or another directive.
Rewrite your functions using plain-old Make variable assignment and the error should go away:
push_dir = \
$(info $1)
pop_dir = \
$(info $1)
include_submake = \
$(call push_dir,$1) \
$(call pop_dir,$1)
UPD.: define vs plain old variable assignment
Answering to a question from the first comment. Personally I would prefer using define directive in several cases.
Using with eval function
As the GNU Make manual suggests, define directive is very useful in conjunction with the eval function. Example from the manual (emphasis is mine):
PROGRAMS = server client
server_OBJS = server.o server_priv.o server_access.o
server_LIBS = priv protocol
client_OBJS = client.o client_api.o client_mem.o
client_LIBS = protocol
# Everything after this is generic
.PHONY: all
all: $(PROGRAMS)
define PROGRAM_template
$(1): $$($(1)_OBJS) $$($(1)_LIBS:%=-l%)
ALL_OBJS += $$($(1)_OBJS)
endef
$(foreach prog,$(PROGRAMS),$(eval $(call PROGRAM_template,$(prog))))
$(PROGRAMS):
$(LINK.o) $^ $(LDLIBS) -o $@
clean:
rm -f $(ALL_OBJS) $(PROGRAMS)
Generator templates
Verbatim variables fit perfectly for cases when you want to generate a file from GNU Make. For example, consider generating a header file based on some information from Makefile.
# Args:
# 1. Header identifier.
define header_template
/* This file is generated by GNU Make $(MAKE_VERSION). */
#ifndef $(inclusion_guard)
#define $(inclusion_guard)
$(foreach inc,$($1.includes),
#include <$(inc).h>)
/* Something else... */
#endif /* $(inclusion_guard) */
endef
# 1. Unique header identifier.
inclusion_guard = \
__GEN_$1_H
# Shell escape.
sh_quote = \
'$(subst ','"'"',$1)'
foo.includes := bar baz
HEADERS := foo.h
$(HEADERS) : %.h :
@printf "%s" $(call sh_quote,$(call header_template,$(*F)))> $@
Extended Make syntax
In our project we use our own build system called Mybuild, and it is implemented entirely on top of GNU Make. As one of low-level hacks that we used to improve the poor syntax of the builtin language of Make, we have developed a special script which allows one to use extended syntax for function definitions. The script itself is written in Make too, so it is a sort of meta-programming in Make.
In particular, one can use such features as:
Defining multiline functions without the need to use backslash
Using comments inside functions (in plain-old Make comments can only occur outside variable assignment directives)
Defining custom macros like $(assert ...) or $(lambda ...)
Inlining simple functions like $(eq s1,s2) (string equality check)
This is an example of how a function can be written using the extended syntax. Note that it becomes a valid Make function and can be called as usual after a call to $(def_all).
# Reverses the specified list.
# 1. The list
# Return:
# The list with its elements in reverse order.
define reverse
# Start from the empty list.
$(fold ,$1,
# Prepend each new element ($2) to
# the result of previous computations.
$(lambda $2 $1))
endef
$(def_all)
Using these new features we were able to implement some really cool things (well, at least for Make :-) ) including:
Object-Oriented layer with dynamic object allocation, class inheritance, method invocations and so on
LALR parser runtime engine for parsers generated by GOLD Parser Builder
Modelling library with runtime support for models generated with EMF
Feel free to use any part of the code in your own projects!
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Apache Beam GroupByKey() fails when running on Google DataFlow in Python
I have a pipeline using the Python SDK 2.2.0 for Apache Beam.
This pipeline is almost a typical word count: I have pairs of names in the format ("John Doe, Jane Smith", 1), and I'm trying to figure out how many times each pair of names appears together, like this:
p_collection
| "PairWithOne" >> beam.Map(lambda pair: (', '.join(pair).encode("ascii", errors="ignore").decode(), 1))
| "GroupByKey" >> beam.GroupByKey()
| "AggregateGroups" >> beam.Map(lambda (pair, ones): (pair, sum(ones)))
| "Format" >> beam.Map(lambda element: {'pair': element[0], 'pair_count': element[1]})
When I run this code locally, with a small dataset, it works perfectly.
But when I deploy it to Google Cloud DataFlow, I get the following error:
An exception was raised when trying to execute the workitem
423109085466017585 : Traceback (most recent call last): File
"/usr/local/lib/python2.7/dist-packages/dataflow_worker/batchworker.py",
line 582, in do_work work_executor.execute() File
"/usr/local/lib/python2.7/dist-packages/dataflow_worker/executor.py",
line 167, in execute op.start() File
"dataflow_worker/shuffle_operations.py", line 49, in
dataflow_worker.shuffle_operations.GroupedShuffleReadOperation.start
def start(self): File "dataflow_worker/shuffle_operations.py", line
50, in
dataflow_worker.shuffle_operations.GroupedShuffleReadOperation.start
with self.scoped_start_state: File
"dataflow_worker/shuffle_operations.py", line 65, in
dataflow_worker.shuffle_operations.GroupedShuffleReadOperation.start
with self.shuffle_source.reader() as reader: File
"dataflow_worker/shuffle_operations.py", line 69, in
dataflow_worker.shuffle_operations.GroupedShuffleReadOperation.start
self.output(windowed_value) File
"apache_beam/runners/worker/operations.py", line 154, in
apache_beam.runners.worker.operations.Operation.output
cython.cast(Receiver,
self.receivers[output_index]).receive(windowed_value) File
"apache_beam/runners/worker/operations.py", line 86, in
apache_beam.runners.worker.operations.ConsumerSet.receive
cython.cast(Operation, consumer).process(windowed_value) File
"dataflow_worker/shuffle_operations.py", line 233, in
dataflow_worker.shuffle_operations.BatchGroupAlsoByWindowsOperation.process
self.output(wvalue.with_value((k, wvalue.value))) File
"apache_beam/runners/worker/operations.py", line 154, in
apache_beam.runners.worker.operations.Operation.output
cython.cast(Receiver,
self.receivers[output_index]).receive(windowed_value) File
"apache_beam/runners/worker/operations.py", line 86, in
apache_beam.runners.worker.operations.ConsumerSet.receive
cython.cast(Operation, consumer).process(windowed_value) File
"apache_beam/runners/worker/operations.py", line 339, in
apache_beam.runners.worker.operations.DoOperation.process with
self.scoped_process_state: File
"apache_beam/runners/worker/operations.py", line 340, in
apache_beam.runners.worker.operations.DoOperation.process
self.dofn_receiver.receive(o) File "apache_beam/runners/common.py",
line 382, in apache_beam.runners.common.DoFnRunner.receive
self.process(windowed_value) File "apache_beam/runners/common.py",
line 390, in apache_beam.runners.common.DoFnRunner.process
self._reraise_augmented(exn) File "apache_beam/runners/common.py",
line 415, in apache_beam.runners.common.DoFnRunner._reraise_augmented
raise File "apache_beam/runners/common.py", line 388, in
apache_beam.runners.common.DoFnRunner.process
self.do_fn_invoker.invoke_process(windowed_value) File
"apache_beam/runners/common.py", line 189, in
apache_beam.runners.common.SimpleInvoker.invoke_process
self.output_processor.process_outputs( File
"apache_beam/runners/common.py", line 480, in
apache_beam.runners.common._OutputProcessor.process_outputs
self.main_receivers.receive(windowed_value) File
"apache_beam/runners/worker/operations.py", line 86, in
apache_beam.runners.worker.operations.ConsumerSet.receive
cython.cast(Operation, consumer).process(windowed_value) File
"apache_beam/runners/worker/operations.py", line 339, in
apache_beam.runners.worker.operations.DoOperation.process with
self.scoped_process_state: File
"apache_beam/runners/worker/operations.py", line 340, in
apache_beam.runners.worker.operations.DoOperation.process
self.dofn_receiver.receive(o) File "apache_beam/runners/common.py",
line 382, in apache_beam.runners.common.DoFnRunner.receive
self.process(windowed_value) File "apache_beam/runners/common.py",
line 390, in apache_beam.runners.common.DoFnRunner.process
self._reraise_augmented(exn) File "apache_beam/runners/common.py",
line 431, in apache_beam.runners.common.DoFnRunner._reraise_augmented
raise new_exn, None, original_traceback File
"apache_beam/runners/common.py", line 388, in
apache_beam.runners.common.DoFnRunner.process
self.do_fn_invoker.invoke_process(windowed_value) File
"apache_beam/runners/common.py", line 189, in
apache_beam.runners.common.SimpleInvoker.invoke_process
self.output_processor.process_outputs( File
"apache_beam/runners/common.py", line 480, in
apache_beam.runners.common._OutputProcessor.process_outputs
self.main_receivers.receive(windowed_value) File
"apache_beam/runners/worker/operations.py", line 84, in
apache_beam.runners.worker.operations.ConsumerSet.receive
self.update_counters_start(windowed_value) File
"apache_beam/runners/worker/operations.py", line 90, in
apache_beam.runners.worker.operations.ConsumerSet.update_counters_start
self.opcounter.update_from(windowed_value) File
"apache_beam/runners/worker/opcounters.py", line 63, in
apache_beam.runners.worker.opcounters.OperationCounters.update_from
self.do_sample(windowed_value) File
"apache_beam/runners/worker/opcounters.py", line 81, in
apache_beam.runners.worker.opcounters.OperationCounters.do_sample
self.coder_impl.get_estimated_size_and_observables(windowed_value))
File "apache_beam/coders/coder_impl.py", line 730, in
apache_beam.coders.coder_impl.WindowedValueCoderImpl.get_estimated_size_and_observables
def get_estimated_size_and_observables(self, value, nested=False):
File "apache_beam/coders/coder_impl.py", line 739, in
apache_beam.coders.coder_impl.WindowedValueCoderImpl.get_estimated_size_and_observables
self._value_coder.get_estimated_size_and_observables( File
"apache_beam/coders/coder_impl.py", line 518, in
apache_beam.coders.coder_impl.AbstractComponentCoderImpl.get_estimated_size_and_observables
values[i], nested=nested or i + 1 < len(self._coder_impls)))
RuntimeError: KeyError: 0 [while running 'Transform/Format']
Looking at the source code of where this error pops up from, I thought it could be cause due to the fact that some of the names contain some weird encoded characters, so in a desperate act I tried using the .encode("ascii", errors="ignore").decode() you see on the code, but no luck.
Any ideas as to why this pipeline executes successfully locally, but fails on DataFlow runner?
Thanks!
A:
This isn't so much of a fix to my problem as it is avoiding the problem in the first place, but it did make my code run, thanks to the suggestion of user1093967 in the comments.
I just replaced the GroupByKey and the AggregateGroups by a CombinePerKey(sum) step and the problem didn't occur anymore.
p_collection
| "PairWithOne" >> beam.Map(lambda pair: (', '.join(pair).encode("ascii", errors="ignore").decode(), 1))
| "GroupAndSum" >> beam.CombinePerKey(sum)
| "Format" >> beam.Map(lambda element: {'pair': element[0], 'pair_count': element[1]})
I'd be happy to hear why it works, though.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Dice roll with a 50% chance of rolling 6
So I made this method of rolling a dice 100 times with a 50% chance of rolling 6.
Basic idea is that there are 50% odd numbers and 50% even numbers between 1 and 6, so if an even number is rolled, system prints 6 else it prints a random number between 1 and 5. Do you think this is correct?
public static void printDiceRolls(Random randGenerator) {
for (int i=0; i < 30; i++) {
int temp;
temp = randGenerator.nextInt(6) + 1;
if (temp%2 == 0) {
temp = 6;
}
else
temp = randGenerator.nextInt(5) + 1;
System.out.print(" " + temp + " ");
}
}
A:
Generate a random number between 1 and 10, inclusive on both ends. If the number be 1 to 5, you rolled that number, otherwise, you rolled 6. Note that there are 5 chances in this scheme to roll a 6 (i.e. 50%), and 5 total chances to roll 1 through 5 (i.e. the other 50%).
Random random = new Random();
int roll = random.nextInt(10) + 1;
if (roll > 5) {
System.out.println("You rolled a 6");
}
else {
System.out.println("You rolled a " + roll);
}
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Laravel 5.x. Throwing Manual error from form validations
Is there any way to throw a manual form validation error in laravel. Let's say there's a function that allows to check a credit card's number and if that fails I want to set an error and redirect the user back to the form. I'm looking for something like.
private function validateCreditCard() {...}
if (!validateCreditCard()) {
# Throw a form validation error here.
}
A:
There are actually many ways of validating in Laravel.
From Controller
Validator::make($request->all(), [
'ccv' => 'required|numeric|max:3',
'card_number' => 'required',
'expiry_date' => 'required',
])->validate();
Specify where you want to redirect request to explictly in your code
$validator = Validator::make($request->all(), [
'ccv' => 'required|numeric',
'card_number' => 'required',
'expiry_date' => 'required',
]);
if ($validator->fails()) {
return redirect('pay/with/creditcard')
->withErrors($validator)
->withInput();
}
Do another validation after the first validation e.g (check if card is debitable)
$validator = Validator::make(
'ccv' => 'required|numeric',
'card_number' => 'required',
'expiry_date' => 'required',); //your normal validation here. e.g ccv, required fields etc.
$validator->after(function ($validator) {
if (!$this->validateCreditCard()) { //do another validation e.g check if card is debitable
$validator->errors()->add('credit_card', 'Something is wrong with this credit card!');
}
});
And you can redirect back to payment form. Let's assume your route is 'pay/with/creditcard'
if ($validator->fails()) {
return redirect('pay/with/creditcard')
->withErrors($validator)
->withInput();
}
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Switched from Firefox to HTMLUnit in watir-webdriver. Now all my tests fail. How can I start tracking down why?
All of my automation is in watir-webdriver. I used to configure my browser as Firefox, like so:
@profile = Selenium::WebDriver::Firefox::Profile.new
@profile.native_events = false
@client = Selenium::WebDriver::Remote::Http::Default.new
@client.timeout = 300
@b = Watir::Browser.new :firefox, :profile=>@profile, :http_client=>@client
@b.driver.manage.timeouts.implicit_wait = 30
When I switched to this:
@server = Selenium::Server.new("./selenium-server-standalone-2.20.0.jar", :background=>true)
@server.start
@caps = Selenium::WebDriver::Remote::Capabilities.htmlunit(:javascript_enabled=>true)
@client = Selenium::WebDriver::Remote::Http::Default.new
@client.timeout = 300
@b = Watir::Browser.new(:remote, :url=>"http://127.0.0.1:4444/wd/hub", :desired_capabilities=>@caps, :http_client=>@client)
@b.driver.manage.timeouts.implicit_wait = 30
I start failing on the first, very simple task
@b.link(:text, "Login Again").click
Watir::Exception::UnknownObjectException: unable to locate element, using {:text=>"Login Again", :tag_name=>"a"}
How can I go about figuring out why this is and what I can do about it? I don't know where to start with this.
A:
I'd have a look at the Headless gem. See this blog entry from Alister's Watirmelon blog
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Leaks on NSString that appendformats
I have lots of leaks on a NSString. I use appendformat to append strings to it.
Here's the code :
NSString *textedetails = [[NSMutableString alloc] init];
if([dico objectForKey:@"alertSerie"] != nil)
{[textedetails appendFormat:@"Numéro de Série: %@ \n",[dico objectForKey:@"alertSerie"]];}
if([dico objectForKey:@"alertDate"] != nil)
{[textedetails appendFormat:@"Date de mise en service: %@ \n",[dico objectForKey:@"alertDate"]];}
if([dico objectForKey:@"alertCli"] != nil)
{[textedetails appendFormat:@"Nom du client associé: %@ \n",[dico objectForKey:@"alertCli"]];}
...
//I put the textdetails into a UITextField and...
[textedetails release];
That code give me leaks in the first and the last line of the code above...
and the printscreen of the leaks is HERE !!!
Many thanks to help me !!!
A:
NSString *textedetails = [[NSMutableString alloc] init];
NSMutableString *texterecap = [[NSMutableString alloc] init];
both these are never released.
Try this
NSString *textedetails = [[[NSMutableString alloc] init] autorelease];
NSMutableString *texterecap = [[[NSMutableString alloc] init] autorelease];
or this
NSMutableString *textedetails = [NSMutableString string];
NSMutableString *texterecap = [NSMutableString string];
|
{
"pile_set_name": "StackExchange"
}
|
Q:
What parts of given/when are experimental?
Has the entire "switch" feature become experimental? Are there parts of it I can rely on using without future versions of Perl breaking my code? In general, what is the policy toward changing stable features to experimental?
Background
use feature "switch" has been in Perl since 5.10. From 5.10 to 5.14, perlsyn seems to indicate that this is a stable, supported feature.
Starting with 5.16, however, perlsyn begins to call it "an experimental switch feature" and gets a lot more confusing about what's considered experimental.
Parts of the documentation seem to indicate everything about the feature is experimental:
Under the "switch" feature, Perl gains the experimental keywords given, when, default, continue, and break.
There's even an entire section about the Experimental Details on given and when.
However, perlsyn also says that "The foreach is the non-experimental way to set a topicalizer" and gives an example that seems to imply that foreach/when is not experimental.
As far as I can tell, the "experimental" language came from commit c2f1e22 which references RT #90926 which still doesn't give much context, even when paired with RT# 90906.
A:
Has the entire "switch" feature become experimental?
No. It has always been.
Upd: Oh wow, maybe I'm wrong. I can't find a mention of that in 5.10.0 or .1. Maybe it wasn't? Or maybe they forgot to note it? Either way, it seems they messed up worse than I thought if so! But based on what I've seen since, I think the lesson was learned. (e.g. I still think values $ref is a bad idea, but at least it was marked experimental from day
1.)
Are there parts of it I can rely on using without future versions of Perl breaking my code?
Technically, no, although the devs are always careful when it comes to backwards compatibility.
In general, what is the policy toward changing stable features to experimental?
I don't see that ever happening. The deprecation process would be used instead.
Changes so far:
given is changing from creating a lexical $_ to localising $_ like foreach loops in 5.18 (or did it already happen in 5.16?).
5.10.1 saw some big changes in smart-matching*. Don't use (smart-matching in) 5.10.0.
Possible future changes:
The behaviour of smart-matching* is still a hot topic.
* — True, this is a feature distinct from given-when, but it's the same or closely related in most people's minds.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
What am I doing wrong in ASP.NET
Here is my master page code behind:
namespace mysite.MasterPages
{
public partial class Main : System.Web.UI.MasterPage
{
public bool isLoggedIn;
protected void Page_Load(object sender, EventArgs e)
{
isLoggedIn = Request.IsAuthenticated; // Is the user currently logged in
}
}
}
Here is my register page code behind:
namespace mysite
{
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (((MasterPage)Page.Master).isLoggedIn)
{
Response.Redirect("default.aspx");
}
}
}
}
I'm trying to make the isloggedIn accessible to all pages using that as a master page! I get errors like:
Error 2 The name 'isLoggedIn' does not exist in the current context
Error 3 'System.Web.UI.MasterPage' does not contain a definition for 'isLoggedIn' and no extension method 'isLoggedIn' accepting a first argument of type 'System.Web.UI.MasterPage' could be found (are you missing a using directive or an assembly reference?)
Any help appreciated.
A:
add <%@ MasterType VirtualPath="~/Main.master" %> to your page markup.
and your this.Master's type becomes AlphaPack.MasterPages.Main instead of System.Web.UI.MasterPage. So you will be able to access it without cast:
this.Master.IsLoggednIn
Currently you need do next:
((AlphaPack.MasterPages.Main)this.Master).isLoggednIn
And better - create a property. And hold data not in variable but in ViewState (read Control State vs. View State):
namespace AlphaPack.MasterPages
{
public partial class Main : System.Web.UI.MasterPage
{
protected void Page_Load(object sender, EventArgs e)
{
this.IsLoggedIn = Request.IsAuthenticated;
}
public bool IsLoggedIn
{
get { return this.ViewState["isLoggedIn"] as bool? ?? false; }
set { this.ViewState["isLoggedIn"] = value; }
}
}
}
And what about code-behind. I recommend to use Web App project, not Web Site project (which is out-of-date)!
Next markup syntax is used. Web app:
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="MyPage.aspx.cs" Inherits="MyNamespace.MyPage" MasterPageFile="~/MyMaster.master" Title="MyTitile" %>
and web site:
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="MyPage.aspx.cs" Inherits="MyPage" MasterPageFile="~/MyMaster.master" Title="MyTitile" %>
|
{
"pile_set_name": "StackExchange"
}
|
Q:
VisualForce page with SLDS: apex:inputField lookup button way too big
I have the following piece of code:
<div class="slds-p-horizontal--small slds-size--5-of-12">
<label class="slds-form-element__label" for="select-01">Campaign</label>
<div class="slds-form-element__control">
<apex:inputField value="{!campaignLookup}" styleClass="slds-input"/>
</div>
</div>
It's all working as intended, except there is one style issue.
If I remove the styleClass, then the lookup button still works, it just looks hideous.
If I add the styleClass, it looks just like SLDS (in fact, it IS slds), and I get a text field that is 5-of-12 width, and a button besides it which opens a lookup window.
This button is ALSO 5-of-12 width, meaning I have twice the intended size (simply put: it's WAY too big).
How do I fix it so that I have only once a 5-of-12 size? I don't care if the textfield is 5-of-12 and the button is just slightly over the border, but I don't want the button to have an enormous div for only 32*32 pixels ever.
Edit: Fix:
<style>
.lookupInput a {
border: none !important;
width: 60px !important ;
}
</style>
This removes the border and sets the width of the lookup icon to precisely 60 pixels, instead of the enormous div the text field also has.
A:
Lightning design system do not supports apex input filed. Try to create custom CSS styles for lookups and other field types
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Give Access to a Pointer's Data Without Revealing Pointer Address
I have a class that contains a pointer. I want to keep the user of the class from accessing the address of the pointer (so they can't set it to another address, delete it, or what-not). However, I would like the user to be able to modify the pointer data (or member data if it's not POD) as well as call the pointer's methods (assuming it has any).
Is there any way of returning a pointer or reference that allows you to change the data that a pointer points to without being able to change the pointer value itself?
So:
class A
{
public:
int Value;
void Method();
};
class Wrapper
{
public:
Wrapper()
{
Pointer = new A;
}
// Method that somehow would give access to the object without
// Allowing the caller to access the actual address
A* GetPointer()
{
return Pointer;
}
private:
A* Pointer;
};
int main()
{
Wrapper foo;
foo.GetPointer()->Value = 12; // Allowed
foo.GetPointer()->Method(); // Allowed
A* ptr = foo.GetPointer(); // NOT Allowed
delete foo.GetPointer(); // NOT Allowed
return 0;
}
I realize I could modify member data with getters and setters, but I'm not sure what to do about the methods (pass a method pointer maybe?) and I'd like to know if there is a better way before I accept a solution that I personally think looks messy.
A:
It's not possible. The whole reason why ->Value is legal is because the expression to the left is a (smart) pointer to A*.
Obviously, with a non-smart pointer you already have your A* right there. Since raw pointers are not user-defined types, you cannot mess with the overload resolution.
With a smart pointer, (*ptr).Value has to work. That means you have to return a A& from operator* which in turn means that &(*ptr) gets you the traw pointer from a smart pointer.
There's even std::addressof for classes that try to block operator&.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
SQL Finding information about Person in two rows
I have to following Database called Data1
DateOfBooking | Short | Long | TimeOfBooking | ID
-------------------------------------------------------
14.06.2016 | KAL | blabla| 13:02 | 1
14.06.2016 | DEF | del | 14:02 | 3
14.06.2016 | KAL | blabla| 17:34 | 2
14.06.2016 | DOL | blub | 13:02 | 1
I want to to find the ID of the person were KAL at 13:02 and DOL at 13:02 where booked but only if both were booked (at the same time).
KAL and DOL are always booked at the same TimeOfBooking for one ID but I can't figure out how to get the result.
I tried
SELECT DISTINCT Data1.ID
FROM Data1
WHERE (((Data1.Short = 'KAL') AND (Data1.Long Like 'blabla'))
AND ((((Data1.Short = 'DOL') AND (Data1.Long Like 'blub')))
Group BY Data1.ID
Of course this did not work as it only looks into one row. Is there a way to look into both rows and find the corresponding ID?
Thank you.
A:
Not quite sure what you're asking, but this will return the data when a KOL and a DOL have same id and timestamp:
select tk.*, td.*
from (select * from data1 where Short = 'KAL') tk
join (select * from data1 where Short = 'DOL') td
ON tk.id = td.id and tk.TimeOfBooking = td.TimeOfBooking
|
{
"pile_set_name": "StackExchange"
}
|
Q:
HighChart with multple JSON api data
I am creating a linechart which contain data from different JSON files, and the codes below is working but i'd like to know how may i group up these JSON data from different apis into one by a for each loop to shorter the codes.
//consider the vol1- vol10 looks like var vol1 = ['1123', '1234','5436'];
//because i have other method the convert it to an arrray
//Xvol1 is just something like Xvol1=["Jan","Feb","Mar"]
$('#trendChart').highcharts({
chart: {
type: 'spline'
},
title: {
text: false
},
xAxis: {
categories : Xvol1
},
yAxis: {
title: {
text: 'Volume',
},
min: 0
},
plotOptions: {
spline: {
marker: {
enabled: true
}
}
},
series: [{
name: $(".profileName0").html(),
data: vol1
},
{
name: $(".profileName1").html(),
data: vol2
},
{
name: $(".profileName3").html(),
data: vol3
},
{
name: $(".profileName2").html(),
data: vol4
},
{
name: $(".profileName4").html(),
data: vol5
},
{
name: $(".profileName5").html(),
data: vol6
},
{
name: $(".profileName6").html(),
data: vol7
},
{
name: $(".profileName7").html(),
data: vol8
},
{
name: $(".profileName8").html(),
data: vol9
},
{
name: $(".profileName9").html(),
data: vol10
},
]
});
UPDATE 1:
I have tried but it doesn't seem like working.
var series = [];
for(i = 0; i < 10; i++){
series.push({name: $('.profileName'+i+'"').html(),, data: vol[i]});
}
$('#trendChart').highcharts({
chart: {
type: 'spline'
},
title: {
text: false
},
xAxis: {
categories : Xvol1
},
yAxis: {
title: {
text: 'Volume',
},
min: 0
},
plotOptions: {
spline: {
marker: {
enabled: true
}
}
},
series: [series]
});
});
After i generate the data by a for loop successfully, i am now struggle about how to update the data, i tried to update it using setData() but seem it needs so adjustment in order to work.
var seriesData = [vol1, vol2, vol3, vol4, vol5, vol6 , vol7, vol8, vol9, vol10]; // add all the vols. I have used 2 for example
var series = [];
for(i = 0; i < 5; i++){
series.push({name: names[i], data: seriesData[i]});
}
var trendChart12w = $('#trendChart').highcharts();
trendChart12w.series[0].setData(series);
Solution :
var dataCounting = $(".DataCount").last().html();
var seriesData = [vol1, vol2, vol3, vol4, vol5, vol6 , vol7, vol8, vol9, vol10]; // add all the vols. I have used 2 for example
var trendChart1y = $('#trendChart').highcharts();
trendChart1y.xAxis[0].setCategories(Xvol1);
for(i = 0; i < dataCounting; i++){
trendChart1y.series[i].setData(seriesData[i]);
}
A:
You can an array of the names like var names = [all the names] and an array of your data like var seriesData = [vol1, vol2...]
And then do
var series = [];
for(i = 0; i < names.length; i++){
series.push({name: names[i], data: seriesData[i]});
}
And then set this as your chart series.
UPDATE
Do this outside of your chart.
var seriesData = [vol1, vol2]; // add all the vols. I have used 2 for example
var names = [$(".profileName0").html(), $(".profileName1").html()] // add all names
var series = [];
for(i = 0; i < names.length; i++){
series.push({name: names[i], data: seriesData[i]});
}
And then in your chart, where you set the series, just do
series: series
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Fixing Credit With Several Small Debts
I am a recent graduate from the U.S. with a checkered credit history. I have a few items in collection now totaling about $750 or so. Previously, my attitude would have been to let these slide until enough time has passed, but I've been taking steps to not just be responsible with my money. I want to sow the seeds so I can look into investing down the line, and really turning my extra money into a proper nest egg/savings/retirement -type thing.
So like I said, I have 3 things in collection coming to about $750 or so. Now that I am making enough money to put a sizable distance between my living expenses and what I'm seeing, what would be the ideal way to go about settling these debts in collection? I'm thinking I can either take out a loan from my bank to consolidate it and pay it back, or knock them out one at a time at a rate of maybe one a month. I've got a bit of time before my employee benefits start cutting into my paycheck, as well as some time before my student debts start collecting interest, so I'd like to take advantage of this while there's more breathing room. * edit: these debts are legitimate, so I cannot dispute them.
Thank you all in advance. I really appreciate any feedback, since I'm kind of new to learning all of this financial literacy stuff and I've been lurking here enough to feel that I'm in good hands.
A:
Since you acknowledge that you legitimately owe this money and the debts are relatively small, you should pay them without trying to settle for less.
Don't bother with a consolidation loan for these. The loan, if you can get approved, would be more trouble than it is worth, at the time frame you are looking at. Just pay these off in full as fast as you can. Once you do that, your credit will start to heal.
Get a written statement from the collectors to ensure that you and they are in agreement on exactly how much you owe. When you pay them, don't pay electronically; use a check. (Debt collectors have been known to clean out bank accounts if you set up an electronic payment.)
After you've cleaned these up, I would encourage you to aggressively tackle your student loans and any other debt you have. Now, when you are starting your career, is the time to dig yourself out of the hole and eliminate your debt. This will set you up for success in the future.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Comparing Multidimensional arrays in PHP
I am trying to compare to multidimensional arrays, but I can't just use array_diff_assoc(). The arrays I am trying to compare are both associative arrays, and they are both sorted so the keys are in the same order. For the most part the arrays are identical in structure. I can't seem to figure out how to compare the elements that store arrays, I can compare the elements that hold one value just fine does anyone know what I can do?
A:
If your trying to just see if they are different (and not what specifically is different) you could try something like:
return serialize($array1) == seralize($array2);
That would give you a yea or neah on the equality of the two arrays.
A:
There's a user contributed note on the manual page for array_diff_assoc() that seems like it does what you're asking for.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
SQL Query and Unicode Issue
I have a really weird issue with Sql queries on unicode data. Here's what I've got:
Sql Server Express 2008 R2 AS
Table containing chinese characters/words/phrases (100,000 rows)
When I run the following, I get the correct row + 36 other rows returned... when it should only be the one row:
SELECT TOP 1000 [ID]
,[MyChineseColumn]
,UNICODE([MyChineseColumn])
FROM [dbo].[MyTableName]
WHERE [MyChineseColumn]= N'㐅'
As you'd expect, the row with 㐅 is returned, but also the following: 〇, 宁, 㮸 and a bunch of others...
Anyone have any ideas what is going on here? This has really got me confused and I am not sure how to solve this one (tried "Googling" already)...
Thanks
A:
Please check the column is using an appropriate Chinese collation as that will determine the semantics used in this type of comparison.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Svg Slider in console but not showing
I'm trying to build a slider svg template which I can use to switch from light theme to dark theme, The original idea is to try and replicate a design that I've seen that has a moon, then when it slides position it turns into a sun. I have build a basic template (without any graphics yet). Which I could then animate through JavaScript.
However I can't even get the basic template to show in the browser.
<?xml version="1.0" encoding="UTF-8" standalone="no"?><!-- xml:lang='en' lang='en'-->
<!DOCTYPE svg [
<!-- entities etc. here -->
]>
<svg version="1.1"
baseProfile="full"
xmlns="http://www.w3.org/2000/svg"
xmlns:xlink="http://www.w3.org/1999/xlink"
xmlns:ev="http://www.w3.org/2001/xml-events"
preserveAspectRatio="xMidYMid meet"
viewBox="0 0 145 145"
width="145" height="145" stroke="#ffffff">
<path class="" id="a2aBdbnHKq" fill="black" stroke=""
d="M359.91 269.76C363.84 269.76 367.03 272.95 367.03 276.88C367.03 299.29 367.03 359.4 367.03 381.81C367.03 385.75 363.84 388.93 359.91 388.93C323.48 388.93 221.3 388.93 184.87 388.93C180.94 388.93 177.75 385.75 177.75 381.81C177.75 359.4 177.75 299.29 177.75 276.88C177.75 272.95 180.94 269.76 184.87 269.76C221.3 269.76 323.48 269.76 359.91 269.76Z">
</path>
<path class="circ1" id="C1" fill="#c744f0" stroke=""
d="M242.59 329.35C242.59 362.23 214.59 388.93 180.09 388.93C145.59 388.93 117.58 362.23 117.58 329.35C117.58 296.46 145.59 269.76 180.09 269.76C214.59 269.76 242.59 296.46 242.59 329.35Z">
</path>
<path class="rnd_rect" id="Box1" fill="#c744f0" stroke=""
d="M418.51 329.35C418.51 362.23 390.5 388.93 356 388.93C321.5 388.93 293.49 362.23 293.49 329.35C293.49 296.46 321.5 269.76 356 269.76C390.5 269.76 418.51 296.46 418.51 329.35Z">
</path>
<path class="circ2" id="C2" fill="#c744f0" stroke=""
d="M234.71 329.35C234.71 357.72 210.23 380.76 180.09 380.76C149.94 380.76 125.46 357.72 125.46 329.35C125.46 300.97 149.94 277.94 180.09 277.94C210.23 277.94 234.71 300.97 234.71 329.35Z">
</path>
<defs>
</defs>
</svg>
Using W3 Document Markup Checker, the file validates and shows no errors. What have I missed?
The latest svg docs state not to use a doctype declaration, but regardless it doesn't work with or without them. It is being shown in the console, but no graphics on screen.
I know there are many questions similar to this, but every svg is different and their solutions are not working.
Also as a side question: would anyone explain what these 3 attributes are:
xmlns:sketch="?"
baseProfile="full"
filterUnits="objectBoundingBox"
A:
I can't even get the basic template to show in the browser.
I uploaded your svg file to a vector editor.
The picture shows that your figure is outside the svg canvas
It is located below and to the right and its size exceeds the size of the canvas svg
Therefore, it is necessary to reduce the size of the figure and move it to the left and up
transform="scale(0.5) translate(-120, -183)"
Note
The upper left corner is the origin of the SVG. The positive direction along the axis X - to the right, along the axisY - to the down
<svg version="1.1"
baseProfile="full"
xmlns="http://www.w3.org/2000/svg"
xmlns:xlink="http://www.w3.org/1999/xlink"
xmlns:ev="http://www.w3.org/2001/xml-events"
preserveAspectRatio="xMidYMid meet"
viewBox="0 0 145 145"
width="50vw" height="50vh" stroke="#ffffff" style="border:1px solid red;">
<!-- Reduce the size of the figure and move it to the left and up -->
<g transform="scale(0.5) translate(-120, -183)">
<path class="" id="a2aBdbnHKq" fill="black" stroke=""
d="M359.91 269.76C363.84 269.76 367.03 272.95 367.03 276.88C367.03 299.29 367.03 359.4 367.03 381.81C367.03 385.75 363.84 388.93 359.91 388.93C323.48 388.93 221.3 388.93 184.87 388.93C180.94 388.93 177.75 385.75 177.75 381.81C177.75 359.4 177.75 299.29 177.75 276.88C177.75 272.95 180.94 269.76 184.87 269.76C221.3 269.76 323.48 269.76 359.91 269.76Z">
</path>
<path class="circ1" id="C1" fill="#c744f0" stroke=""
d="M242.59 329.35C242.59 362.23 214.59 388.93 180.09 388.93C145.59 388.93 117.58 362.23 117.58 329.35C117.58 296.46 145.59 269.76 180.09 269.76C214.59 269.76 242.59 296.46 242.59 329.35Z">
</path>
<path class="rnd_rect" id="Box1" fill="#c744f0" stroke=""
d="M418.51 329.35C418.51 362.23 390.5 388.93 356 388.93C321.5 388.93 293.49 362.23 293.49 329.35C293.49 296.46 321.5 269.76 356 269.76C390.5 269.76 418.51 296.46 418.51 329.35Z">
</path>
<path class="circ2" id="C2" fill="#c744f0" stroke=""
d="M234.71 329.35C234.71 357.72 210.23 380.76 180.09 380.76C149.94 380.76 125.46 357.72 125.46 329.35C125.46 300.97 149.94 277.94 180.09 277.94C210.23 277.94 234.71 300.97 234.71 329.35Z">
</path>
</g>
<defs>
</defs>
</svg>
The red frame shows the borders of the svg canvas. Red frame can be removed after debugging the positioning.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
cisco 2900xl - SNMP - Get mac address of device connected to an interface
Basically what i want to do is to find out what is the mac address of a device plugged in to an interface on the switch (FastEthernet0/1 for example)
reading through the switch documentaion i found out that i can configure snmp trap on it to make it notify of any new mac address the switch detects by using the command
snmp-server enable traps mac-notifiction
but for some reason my switch does not support this feature. the only options i see are
CORE_SWITCH(config)#snmp-server enable traps ?
c2900 Enable SNMP c2900 traps
cluster Enable Cluster traps
config Enable SNMP config traps
entity Enable SNMP entity traps
hsrp Enable SNMP HSRP traps
snmp Enable SNMP traps
vlan-membership Enable VLAN Membership traps
vtp Enable SNMP VTP traps
<cr>
so the other way would be for me to run a cronjon on my gateway to poll the switch periodically using snmp to get new mac addresses
i have looked everywhere but cant seem to find the OID that would provide me this information.
any help i can get would me very much appreciated !
here's the output from "show version" on my switch
Cisco Internetwork Operating System Software
IOS (tm) C2900XL Software (C2900XL-C3H2S-M), Version 12.0(5.4)WC(1), MAINTENANCE INTERIM SOFTWARE
Copyright (c) 1986-2001 by cisco Systems, Inc.
Compiled Tue 10-Jul-01 11:52 by devgoyal
Image text-base: 0x00003000, data-base: 0x00333CD8
ROM: Bootstrap program is C2900XL boot loader
CORE_SWITCH uptime is 1 hour, 24 minutes
System returned to ROM by power-on
System image file is "flash:c2900XL-c3h2s-mz.120-5.4.WC.1.bin"
cisco WS-C2912-XL (PowerPC403GA) processor (revision 0x11) with 8192K/1024K bytes of memory.
Processor board ID FAB0409X1WS, with hardware revision 0x01
Last reset from power-on
Processor is running Enterprise Edition Software
Cluster command switch capable
Cluster member switch capable
12 FastEthernet/IEEE 802.3 interface(s)
32K bytes of flash-simulated non-volatile configuration memory.
Base ethernet MAC Address: 00:01:42:D0:67:00
Motherboard assembly number: 73-3397-08
Power supply part number: 34-0834-01
Motherboard serial number: FAB040843G4
Power supply serial number: DAB05030HR8
Model revision number: A0
Motherboard revision number: C0
Model number: WS-C2912-XL-EN
System serial number: FAB0409X1WS
Configuration register is 0xF
thanks,
-ankit
A:
Radius, thanks for pointing me in the right direction. googled up a bit based on your sugestions and i think i have it now.
To anyone else who might need it, this is the procedure ....
1. get the mac address detected on a vlan (1 in this example)
snmpwalk -c public@1 -v2c 10.1.1.10 1.3.6.1.2.1.17.4.3.1.1
SNMPv2-SMI::mib-2.17.4.3.1.1.0.1.66.208.103.0 = Hex-STRING: 00 01 42 D0 67 00
SNMPv2-SMI::mib-2.17.4.3.1.1.0.1.66.208.103.1 = Hex-STRING: 00 01 42 D0 67 01
SNMPv2-SMI::mib-2.17.4.3.1.1.0.1.66.208.103.2 = Hex-STRING: 00 01 42 D0 67 02
SNMPv2-SMI::mib-2.17.4.3.1.1.0.1.66.208.103.3 = Hex-STRING: 00 01 42 D0 67 03
SNMPv2-SMI::mib-2.17.4.3.1.1.0.1.66.208.103.4 = Hex-STRING: 00 01 42 D0 67 04
SNMPv2-SMI::mib-2.17.4.3.1.1.0.1.66.208.103.5 = Hex-STRING: 00 01 42 D0 67 05
SNMPv2-SMI::mib-2.17.4.3.1.1.0.1.66.208.103.6 = Hex-STRING: 00 01 42 D0 67 06
SNMPv2-SMI::mib-2.17.4.3.1.1.0.1.66.208.103.7 = Hex-STRING: 00 01 42 D0 67 07
SNMPv2-SMI::mib-2.17.4.3.1.1.0.1.66.208.103.8 = Hex-STRING: 00 01 42 D0 67 08
SNMPv2-SMI::mib-2.17.4.3.1.1.0.1.66.208.103.9 = Hex-STRING: 00 01 42 D0 67 09
SNMPv2-SMI::mib-2.17.4.3.1.1.0.1.66.208.103.10 = Hex-STRING: 00 01 42 D0 67 0A
SNMPv2-SMI::mib-2.17.4.3.1.1.0.1.66.208.103.11 = Hex-STRING: 00 01 42 D0 67 0B
SNMPv2-SMI::mib-2.17.4.3.1.1.0.1.66.208.103.12 = Hex-STRING: 00 01 42 D0 67 0C
SNMPv2-SMI::mib-2.17.4.3.1.1.0.30.236.196.143.130 = Hex-STRING: 00 1E EC C4 8F 82
SNMPv2-SMI::mib-2.17.4.3.1.1.0.80.191.232.146.174 = Hex-STRING: 00 50 BF E8 92 AE
2. get the bridge port number for each vlan
snmpwalk -c public@1 -v2c 10.1.1.10 1.3.6.1.2.1.17.4.3.1.2
SNMPv2-SMI::mib-2.17.4.3.1.2.0.1.66.208.103.0 = INTEGER: 31
SNMPv2-SMI::mib-2.17.4.3.1.2.0.1.66.208.103.1 = INTEGER: 13
SNMPv2-SMI::mib-2.17.4.3.1.2.0.1.66.208.103.2 = INTEGER: 14
SNMPv2-SMI::mib-2.17.4.3.1.2.0.1.66.208.103.3 = INTEGER: 15
SNMPv2-SMI::mib-2.17.4.3.1.2.0.1.66.208.103.4 = INTEGER: 16
SNMPv2-SMI::mib-2.17.4.3.1.2.0.1.66.208.103.5 = INTEGER: 17
SNMPv2-SMI::mib-2.17.4.3.1.2.0.1.66.208.103.6 = INTEGER: 18
SNMPv2-SMI::mib-2.17.4.3.1.2.0.1.66.208.103.7 = INTEGER: 19
SNMPv2-SMI::mib-2.17.4.3.1.2.0.1.66.208.103.8 = INTEGER: 20
SNMPv2-SMI::mib-2.17.4.3.1.2.0.1.66.208.103.9 = INTEGER: 22
SNMPv2-SMI::mib-2.17.4.3.1.2.0.1.66.208.103.10 = INTEGER: 23
SNMPv2-SMI::mib-2.17.4.3.1.2.0.1.66.208.103.11 = INTEGER: 24
SNMPv2-SMI::mib-2.17.4.3.1.2.0.1.66.208.103.12 = INTEGER: 25
SNMPv2-SMI::mib-2.17.4.3.1.2.0.30.236.196.143.130 = INTEGER: 15
SNMPv2-SMI::mib-2.17.4.3.1.2.0.80.191.232.146.174 = INTEGER: 13
SNMPv2-SMI::mib-2.17.4.3.1.2.255.255.255.255.255.255 = INTEGER: 0
3. get bridge port number to ifindex mapping
snmpwalk -c public@1 -v2c 10.1.1.10 1.3.6.1.2.1.17.1.4.1.2
SNMPv2-SMI::mib-2.17.1.4.1.2.13 = INTEGER: 2
SNMPv2-SMI::mib-2.17.1.4.1.2.14 = INTEGER: 3
SNMPv2-SMI::mib-2.17.1.4.1.2.15 = INTEGER: 4
SNMPv2-SMI::mib-2.17.1.4.1.2.16 = INTEGER: 5
SNMPv2-SMI::mib-2.17.1.4.1.2.17 = INTEGER: 6
SNMPv2-SMI::mib-2.17.1.4.1.2.18 = INTEGER: 7
SNMPv2-SMI::mib-2.17.1.4.1.2.19 = INTEGER: 8
SNMPv2-SMI::mib-2.17.1.4.1.2.20 = INTEGER: 9
SNMPv2-SMI::mib-2.17.1.4.1.2.22 = INTEGER: 10
SNMPv2-SMI::mib-2.17.1.4.1.2.23 = INTEGER: 11
SNMPv2-SMI::mib-2.17.1.4.1.2.24 = INTEGER: 12
SNMPv2-SMI::mib-2.17.1.4.1.2.25 = INTEGER: 13
4. get the ifname
snmpwalk -c public@1 -v2c 10.1.1.10 1.3.6.1.2.1.31.1.1.1.1
IF-MIB::ifName.1 = STRING: VL1
IF-MIB::ifName.2 = STRING: Fa0/1
IF-MIB::ifName.3 = STRING: Fa0/2
IF-MIB::ifName.4 = STRING: Fa0/3
IF-MIB::ifName.5 = STRING: Fa0/4
IF-MIB::ifName.6 = STRING: Fa0/5
IF-MIB::ifName.7 = STRING: Fa0/6
IF-MIB::ifName.8 = STRING: Fa0/7
IF-MIB::ifName.9 = STRING: Fa0/8
IF-MIB::ifName.10 = STRING: Fa0/9
IF-MIB::ifName.11 = STRING: Fa0/10
IF-MIB::ifName.12 = STRING: Fa0/11
IF-MIB::ifName.13 = STRING: Fa0/12
IF-MIB::ifName.14 = STRING: Nu0
so in this case the 2 mac addresses on vlan 1 are on interfaces Fa0/1 and Fa0/3
A:
I'm not sure if it's supported on 2900/IOS 12.0 but you can try to broswe dot1dTpFdbPort (.1.3.6.1.2.1.17.4.3.1.2)
You need to use a special community string including the vlan for which you want to get the mac address table: community@vlan_number
So if your switch is 1.2.3.4, use community snmpro and have vlan 30, try this:
snmpwalk -v2c -c snmpro@30 1.2.3.4 1.3.6.1.2.1.17.4.3.1.2
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How to program without type safety
Java is a hard typed language, and exchanging to Python I fell a little hard to get along with no type safety.
So, can any one help me good practices and concepts to program without type safety.
Do I need to verify on every getter and setter if the value isinstance of the desired type?
How would I use POO without type safety?
How I can encapsulate my objects without type safety?
A:
you should not type check usually. let types free. Forget about type-safety. All code in python are a kind of generic programming.
Object-oriented programming is not combined with type safety.
Python doesn't support encapsulation of instance variable or private function. But sensible pythonista uses _ prefix for private variable or function.
Instead, unit-testing will help you.
In my favorite, nosetests and watchdog are great tools.
nosetest runs all *_test.py files in your project.
watchmedo in watchdog will watch file change and does specific command.
usually I use these two tools like
$ watchmedo shell-command --patterns="*.py" --recursive --wait --command="nosetest -sv"
This one-liner runs unit-test automatically every update in *.py file.
All your code modification will be monitored.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Abstract/Virtual Functions in java
I've heard that all Java functions are implicitly virtual, but I'm still not sure if this will run how I want.
Suppose I have a class A, with child B.
both A and B have functions called foo(), so B's definition is overriding A's.
Suppose also that A has a function called that takes an instance of A as a parameter:
If I pass in an instance of B to the function, which definition of foo() will it call, A's or B's?
A:
As I mentioned in my comment private functions are not virtual and I want to demonstrate it using following example:
class A {
public void foo() {
System.out.println("A#foo()");
}
public void bar() {
System.out.println("A#bar()");
qux();
}
private void qux() {
System.out.println("A#qux()");
}
}
class B extends A {
public void foo() {
System.out.println("B#foo()");
}
private void qux() {
System.out.println("B#qux()");
}
}
Now lets run following code:
A foobar = new B();
foobar.foo(); // outputs B#foo() because foobar is instance of B
foobar.bar(); // outputs A#bar() and A#qux() because B does not have method bar
// and qux is not virtual
A:
B's implementation will be called.
That's exactly what virtual means.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Segfault logic with two threads
I have an application with main thread and additional (detached) process created in it.
In that process we are running network server which sends logs from queue through the network.
The question is: is it possible to do something in segfault handler to wait/finish for sending that log queue. So I want almost 100% delivery of that queue.
A:
While it is possible to write a segfault handler, I highly recommend against it. First off, it's very easy to get your program into a "won't terminate" state due to a segfault in the segfault handler.
Second, as dan3 mentions, the memory of the process is likely in a corrupt state, making it hard to know what will and won't work.
Finally, you lose the opportunity to use the coredump from the process to help track down the problem.
While it's not recommended, it is possible.
My recommendation is to write a small program that avoids memory allocation and the use of pointers as much as possible. Perhaps create buffers as global arrays and only ever access them with limited code that can be reviewed by several skilled developers and tested thoroughly (stress testing is great here). Keep in mind, though, that the message could still get lost by the sender or receiver if they crash, so it may not be worth the effort.
By the way - when Netscape first wrote a version of their browser for Linux, I ran it and it kept getting into a locked-up state. Using the strace program, I quickly found that it was in an infinite segfault loop. Very frustrating, and leading to almost 100% cpu wasted.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Convergence of $a_{n+2}^3+a_{n+2}=a_{n+1}+a_n$
Let $(a_n) _{n\ge 0}$ $a_{n+2}^3+a_{n+2}=a_{n+1}+a_n$,$\forall n\ge 1$, $a_0,a_1 \ge 1$. Prove that $(a_n) _{n\ge 0}$ is convergent.
I could prove that $a_n \ge 1$ by mathematical induction, but here I am stuck.
A:
There might be an easier and more elegant solution, but this should work.
First observe that:
$$
a_{n+1}+a_{n}=a_{n+2}^3+a_{n+2}\geq2\sqrt{a_{n+2}^4}=2a_{n+2}^2\geq4a_{n+2}-2
$$
Here I used the AM-GM inequality and the simply fact that $(a_{n+2}-1)^2\geq0$.
Hence, $a_n\leq b_n$ with
$$
b_{n+2}=\frac{b_{n+1}+b_{n}+2}{4}\\
b_{0,1}=a_{0,1}
$$
Now, the recurrence equation for this reads:
$$
b_{n}=1 + (\tfrac{1 - \sqrt{17}}{8})^n C_1 + (\tfrac{1 + \sqrt{17}}{8})^n C_2
$$
Since $|\tfrac{1 \pm \sqrt{17}}{8}|<1$ we can deduct that $b_n\to1$ for $n\to\infty$. So together with $1\leq a_n\leq b_n$ we can conclude that $a_n\to1$.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Change .NET CLR time zone without using registry
I'd like to change the default time zone of a .NET CLR without using the registry or changing my OS time zone. Is there a way?
EDIT: It looks like the .NET CLR just doesn't support having a default time zone different than the OS's (unlike the JVM).
In other words I'd like this statement to return something other than my OS's time zone:
TimeZoneInfo timeZoneInfo = TimeZoneInfo.Local;
Console.Out.WriteLine("timeZoneInfo = {0}", timeZoneInfo);
The reason I'd like to do this is to run a .NET GUI with the time zone of my users (London) rather than the time zone of my machine (Chicago).
For example, you can change a Java runtime's time zone by adding to the commandline:
-Duser.timezone="Europe/Berlin"
So, for example, if you want DateTime.Now to return a different time zone, you can't without changing all the references to DateTime.Now to something else, which is what I was hoping to avoid in the first place.
A:
You are asking about getting a different result for the time zone setting, but I am assuming in the end you are interested in getting the time returned in another time zone by default.
The .NET framework supports UTC, local, and also a generic time value without a sense of time zone. See the DateTimeKind enumeration.
When dealing with time values I normally use UTC for everything internally and convert to a specific zone when interacting with the user.
So, to answer your question the only way I know to get a local time returned in another time zone is to change the time zone of the machine.
That begin said, to get your desired effect you could write a utility class that gets the time in UTC then use a configuration parameter to store an offset to apply before returning it.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Print using shared printer in JsPrintSetup
I am using firefox jsPrintSetup extension to print a iframe silently. It works well when the printer is directly connected to the PC. When I tried to print it on a shared printer am getting an error 'Selected printer is not available'.
How can I specify an shared printer in jsPrintSetup?
A:
Finally this worked!
Made the shared printer as default printer in the system
Get the list of printers connected to the system using js
Pass the first value of the response array to the jsPrintSetup printer function
|
{
"pile_set_name": "StackExchange"
}
|
Q:
groovy web services
I have tried to use http://groovy.codehaus.org/GroovyWS
In my BuildConfig.groovy I have added: compile 'org.codehaus.groovy.modules:groovyws:0.5.2'
I then go to Refresh Dependencies and after downloading bunch of stuff, I end up with:
Error executing script Compile: loader constraint violation in interface itable initialization: when resolving method "org.apache.xerces.dom.NodeImpl.getChildNodes()Lorg/w3c/dom/NodeList;" the class loader (instance of org/codehaus/groovy/grails/cli/support/GrailsRootLoader) of the current class, org/apache/xerces/dom/NodeImpl, and the class loader (instance of <bootloader>) for interface org/w3c/dom/Node have different Class objects for the type org/w3c/dom/NodeList used in the signature
java.lang.LinkageError: loader constraint violation in interface itable initialization: when resolving method "org.apache.xerces.dom.NodeImpl.getChildNodes()Lorg/w3c/dom/NodeList;" the class loader (instance of org/codehaus/groovy/grails/cli/support/GrailsRootLoader) of the current class, org/apache/xerces/dom/NodeImpl, and the class loader (instance of <bootloader>) for interface org/w3c/dom/Node have different Class objects for the type org/w3c/dom/NodeList used in the signature
at org.apache.xerces.parsers.AbstractDOMParser.startDocument(Unknown Source)
at org.apache.xerces.impl.dtd.XMLDTDValidator.startDocument(Unknown Source)
at org.apache.xerces.impl.XMLDocumentScannerImpl.startEntity(Unknown Source)
at org.apache.xerces.impl.XMLVersionDetector.startDocumentParsing(Unknown Source)
at org.apache.xerces.parsers.XML11Configuration.parse(Unknown Source)
at org.apache.xerces.parsers.XML11Configuration.parse(Unknown Source)
at org.apache.xerces.parsers.XMLParser.parse(Unknown Source)
at org.apache.xerces.parsers.DOMParser.parse(Unknown Source)
at org.apache.xerces.jaxp.DocumentBuilderImpl.parse(Unknown Source)
at javax.xml.parsers.DocumentBuilder.parse(Unknown Source)
at org.apache.ivy.util.XMLHelper.parseToDom(XMLHelper.java:196)
at org.apache.ivy.plugins.parser.m2.PomReader.<init>(PomReader.java:95)
at org.apache.ivy.plugins.parser.m2.PomModuleDescriptorParser.parseDescriptor(PomModuleDescriptorParser.java:118)
at org.apache.ivy.plugins.parser.m2.PomModuleDescriptorParser.parseDescriptor(PomModuleDescriptorParser.java:108)
at org.apache.ivy.core.cache.DefaultRepositoryCacheManager$MyModuleDescriptorProvider.provideModule(DefaultRepositoryCacheManager.java:659)
at org.apache.ivy.core.cache.ModuleDescriptorMemoryCache.getStale(ModuleDescriptorMemoryCache.java:68)
at org.apache.ivy.core.cache.DefaultRepositoryCacheManager.getStaledMd(DefaultRepositoryCacheManager.java:676)
at org.apache.ivy.core.cache.DefaultRepositoryCacheManager.cacheModuleDescriptor(DefaultRepositoryCacheManager.java:993)
at org.apache.ivy.plugins.resolver.BasicResolver.parse(BasicResolver.java:546)
at org.apache.ivy.plugins.resolver.BasicResolver.getDependency(BasicResolver.java:266)
at org.apache.ivy.plugins.resolver.IBiblioResolver.getDependency(IBiblioResolver.java:503)
at org.apache.ivy.plugins.resolver.ChainResolver.getDependency(ChainResolver.java:104)
at org.apache.ivy.core.resolve.IvyNode.loadData(IvyNode.java:169)
at org.apache.ivy.core.resolve.VisitNode.loadData(VisitNode.java:287)
at org.apache.ivy.core.resolve.ResolveEngine.fetchDependencies(ResolveEngine.java:696)
at org.apache.ivy.core.resolve.ResolveEngine.doFetchDependencies(ResolveEngine.java:781)
at org.apache.ivy.core.resolve.ResolveEngine.fetchDependencies(ResolveEngine.java:704)
at org.apache.ivy.core.resolve.ResolveEngine.doFetchDependencies(ResolveEngine.java:781)
at org.apache.ivy.core.resolve.ResolveEngine.fetchDependencies(ResolveEngine.java:704)
at org.apache.ivy.core.resolve.ResolveEngine.doFetchDependencies(ResolveEngine.java:769)
at org.apache.ivy.core.resolve.ResolveEngine.fetchDependencies(ResolveEngine.java:704)
at org.apache.ivy.core.resolve.ResolveEngine.doFetchDependencies(ResolveEngine.java:769)
at org.apache.ivy.core.resolve.ResolveEngine.fetchDependencies(ResolveEngine.java:704)
at org.apache.ivy.core.resolve.ResolveEngine.doFetchDependencies(ResolveEngine.java:781)
at org.apache.ivy.core.resolve.ResolveEngine.fetchDependencies(ResolveEngine.java:704)
at org.apache.ivy.core.resolve.ResolveEngine.getDependencies(ResolveEngine.java:576)
at org.apache.ivy.core.resolve.ResolveEngine.resolve(ResolveEngine.java:237)
at org.apache.ivy.core.resolve.ResolveEngine$resolve.call(Unknown Source)
at grails.util.BuildSettings$_getDefaultCompileDependencies_closure9.doCall(BuildSettings.groovy:293)
at grails.util.BuildSettings$_getDefaultCompileDependencies_closure9.doCall(BuildSettings.groovy)
at grails.util.BuildSettings.getDefaultCompileDependencies(BuildSettings.groovy:293)
at grails.util.BuildSettings.getCompileDependencies(BuildSettings.groovy:278)
at _GrailsClasspath_groovy$_run_closure8.doCall(_GrailsClasspath_groovy:130)
at _GrailsClasspath_groovy$_run_closure8.doCall(_GrailsClasspath_groovy)
at _GrailsClasspath_groovy.setClasspath(_GrailsClasspath_groovy:190)
at _GrailsClasspath_groovy$_run_closure1.doCall(_GrailsClasspath_groovy:39)
at _GrailsEvents_groovy.run(_GrailsEvents_groovy:50)
at _GrailsEvents_groovy$run.call(Unknown Source)
at _GrailsArgParsing_groovy$run.call(Unknown Source)
at _GrailsArgParsing_groovy.run(_GrailsArgParsing_groovy:29)
at _GrailsArgParsing_groovy$run.call(Unknown Source)
at _GrailsInit_groovy$run.call(Unknown Source)
at _GrailsInit_groovy.run(_GrailsInit_groovy:37)
at _GrailsInit_groovy$run.call(Unknown Source)
at _GrailsCompile_groovy$run.call(Unknown Source)
at _GrailsCompile_groovy.run(_GrailsCompile_groovy:28)
at _GrailsCompile_groovy$run.call(Unknown Source)
at Compile.run(Compile.groovy:25)
at Compile$run.call(Unknown Source)
at gant.Gant.prepareTargets(Gant.groovy:606)
Error executing script Compile: loader constraint violation in interface itable initialization: when resolving method "org.apache.xerces.dom.NodeImpl.getChildNodes()Lorg/w3c/dom/NodeList;" the class loader (instance of org/codehaus/groovy/grails/cli/support/GrailsRootLoader) of the current class, org/apache/xerces/dom/NodeImpl, and the class loader (instance of <bootloader>) for interface org/w3c/dom/Node have different Class objects for the type org/w3c/dom/NodeList used in the signature
Anyone can help me with what's gonig on? Why do I get this exception and how to fix it?
Thanks
--MB
A:
Seems like you're entering a dependency madness. Look at your error message for this LinkageError (I've added some emphasis):
Error executing script Compile: loader constraint violation in interface itable initialization: when resolving method "org.apache.xerces.dom.NodeImpl.getChildNodes()Lorg/w3c/dom/NodeList;" the class loader (instance of org/codehaus/groovy/grails/cli/support/GrailsRootLoader) of the current class, org/apache/xerces/dom/NodeImpl, and the class loader (instance of ) for interface org/w3c/dom/Node have different Class objects for the type org/w3c/dom/NodeList used in the signature
To make things a little more clear (if that's not already the case), there is a conflict between two of your dependencies. As you appear to use Grails, I would tend to say to you that the version of GroovyWS you use is not compatible with your current installation of Grails. Have you tried to install groovyWS using Grails command-line ? I mean, calling install-dependency ? If not, I would suggest you replace your dependecy with a call to
install-dependency org.codehaus.groovy.modules:groovyws
This way, Grails would use its own compatibility mechanism.
If that's not enough, try to see in that guide how to exclude offending dependencies.
EDIT You could also follow some advices from this blog entry.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Javascript Array Undefined without size
I'm trying to fill an array with a while loop. When I try to read the data at a certain index it keeps giving me undefined yet the length of the array tells me that there MUST be something added.
var test = [];
while (i < 16)
{
test[i] = i;
i++;
console.log(test.length);
console.log(test[i]);
}
Console output:
1
Fibbo.html:48 undefined
Fibbo.html:47 2
Fibbo.html:48 undefined
Fibbo.html:47 3
Fibbo.html:48 undefined
Fibbo.html:47 4
Fibbo.html:48 undefined
Fibbo.html:47 5
Fibbo.html:48 undefined
Fibbo.html:47 6
Fibbo.html:48 undefined
Fibbo.html:47 7
Fibbo.html:48 undefined
Fibbo.html:47 8
Fibbo.html:48 undefined
Fibbo.html:47 9
Fibbo.html:48 undefined
Fibbo.html:47 10
Fibbo.html:48 undefined
Fibbo.html:47 11
Fibbo.html:48 undefined
Fibbo.html:47 12
Fibbo.html:48 undefined
Fibbo.html:47 13
Fibbo.html:48 undefined
Fibbo.html:47 14
Fibbo.html:48 undefined
Fibbo.html:47 15
Fibbo.html:48 undefined
Fibbo.html:47 16
Fibbo.html:48 undefined
A:
You are inserting at i and checking the value at i+1.This should fix your code -
var i = 0;
var test = [];
while (i < 16)
{
test[i] = i;
console.log(test.length);
console.log(test[i]);
i++;
}
|
{
"pile_set_name": "StackExchange"
}
|
Q:
alternate button text automatically without click
I would like alternate between 2 pieces of text on a button in 2 sec intervals. This is NOT a click event. I just want the button to rotate between 'click here' and 'download'. This is what Im trying with no luck:
<div class="assetClass customButton1_1Div" id="download_btn1">
<input type="button" class="customButton1_1" name="button1_1" value="click here" title="download_btn1" />
</div>
setInterval(toggle, 2000);
function toggle() {
document.getElementByName("button1_1").value = "download";
}
A:
Something like this?
var cnt=0, arr = ['Click Here','Download'];
setTimeout(toggle, 1500);
function toggle() {
$('.btn').val(arr[cnt]);
cnt = (cnt > 0) ? 0 : 1;
setTimeout(toggle, 1500);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="assetClass customButton1_1Div" id="download_btn1">
<input type="button" class="btn" value="Download" />
</div>
Note that setInterval has certain drawbacks compared with a recursive setTimeout:
http://www.erichynds.com/blog/a-recursive-settimeout-pattern
|
{
"pile_set_name": "StackExchange"
}
|
Q:
URLError: urlopen error [Errno 2] No such file or directory
I was perfectly able to use pandas read_csv for reading files in Windows. However I cannot figure out how to set local path in Ubuntu?
If I do this:
data = pd.read_csv(r'file://home/gosper/Desktop/test.csv')
... it throws the error: URLError: <urlopen error [Errno 2] No such file or directory
A:
this should work for Windows's and UNIX's Desktop folder:
data = pd.read_csv(os.path.expanduser('~') + '/Desktop/test.csv')
|
{
"pile_set_name": "StackExchange"
}
|
Q:
CSRF token mismatch larave-echo-server with nuxt
i have realtime application in nuxt and laravel with laravel-echo-server
when i use this
window.Echo.channel(`laravel_database_test-channel`).listen(
"TestEvent",
e => {
console.log(e);
}
);
everything works fine
but when i try in private channel like this
window.Echo.private(`laravel_database_test-channel`).listen(
"TestEvent",
e => {
console.log(e);
}
);
getting error "message": "CSRF token mismatch."
here is full screenshot
A:
goto App\Providers\BroadcastServiceProvider modify this
Broadcast::routes();
to
Broadcast::routes(['prefix' => 'api', 'middleware' => ['auth:api']]);
and in your laravel-echo-server.json
edit this
"authEndpoint": "/api/broadcasting/auth",
this helps me and working fine
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Consumiendo un api Django Rest Framework desde una aplicación Unity Csharp
He serializado mi modelo de usuarios en DJango para tener una pequeña API
en donde tengo el siguiente objeto JSON
{
"url": "https://neurorehabilitacion.herokuapp.com/api/users/pablo/",
"username": "pablo",
"password": "pbkdf2_sha256$24000$K7lhsSs6Y3ux$NZ+PqAm9Wuzo168Lw4eW0IqycqnmY3BIVFDfj8TSaxM=",
"first_name": "Pablo Andres",
"last_name": "Agudelo Marenco",
"birth_date": "1983-07-20",
"address": "Calle 40 D Sur No. 32B 21",
"phone": "31248122992453",
"occupation": "Ingeniero de Sistemas",
"email": "[email protected]",
"photo": "https://neurorehabilitation-project.s3.amazonaws.com/media/avatars/boy.png",
"age": 33,
"sex": "Masculino",
"ethnic_group": "Americano",
"country_of_birth": "COL",
"communication_language": [
"Español",
"Inglés"
],
"is_medical": false,
"is_therapist": false,
"is_patient": true,
"is_staff": true,
"is_active": true,
"is_superuser": false,
"date_joined": "2016-05-17T12:54:54Z",
"last_login": null
}
Desde mi aplicación Unity C# estoy consumiendo estos datos de usuario en JSON a través de esta sección de código:
//This methods loads the information of the client and validates if it is correct.
private IEnumerator LoadInfo() {
string inputFieldName = userInputName.text;
string password = userPassword.text;
if (inputFieldName != "")
{
urlUsuario(inputFieldName);
WWW info = new WWW(url);
yield return info;
try
{
jsonString = info.text;
Debug.Log(url);
Debug.Log(jsonString);
itemData = JsonMapper.ToObject(jsonString);
string jsonName = (string)itemData[0]["username"];
if ((jsonName.ToString() == inputFieldName))
{
string nameJson = (string)itemData[0]["username"];
userName.text = nameJson;
string picUrl = (string)itemData[0]["avatar"];
LoginMenu.enabled = false;
InitialMenu.enabled = true;
StartCoroutine(loadProfilePic(picUrl));
}
} catch (Exception e) {
ErrorMenuConnection();
e.ToString();
Debug.Log("Failed Connection");
Debug.Log(jsonString);
}
}
else
{
ErrorMenu();
}
}
Pero obtengo este mensaje
Básicamente lo que deseo es acceder a los diferentes campos del documento JSON tales como username, password y otros:
Antes tenia una lista o arreglo de un documento JSON como esta:
[{"last_name": "Agudelo Marenco", "slug": "pablo", "first_name": "Pablo Andres", "username": "pablo", "password": "+FtK7BfBFec="}]
Y el consumir los datos funcionaba.
Pero en mi actual implementación de RESTFramework JSON que mostré antes no trabaja adecuadamente.
Una de las cosas es que en el JSON que esta dentro de una lista (en donde me funcionaba), ahí pregunto si en la posición 0 de esa lista existe un atributo username y si coincide lo traiga, pero esta vez el match no se efectua y entonces no se establece conexión y mi intento de consumir datos no funciona.
Cualquier ayuda será apreciada.
A:
Te sobra un acceso al JSON:
string jsonName = (string)itemData[0]["username"];
Esa línea te está lanzando una Exception que se recoge en el try-catch y tu registro dice Failed Connection. El índice 0 de itemData es username, y dentro de username no hay nada, pero tú buscas un elemento con la propiedad username y salta el Exception.
Lo correcto es:
string jsonName = (string)itemData["username"];
... y así con todas las demás.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Resource not found: duke.jpg
So I'm experimenting with the tray menu and I have the line.
final TrayIcon trayIcon = new TrayIcon(createImage("duke.jpg", "tray icon"));
The method createImage is
protected static Image createImage(String path, String description) {
URL imageURL = TrayIconDemo.class.getResource(path);
if (imageURL == null) {
System.err.println("Resource not found: " + path);
return null;
} else {
return (new ImageIcon(imageURL, description)).getImage();
}
}
when I run the program I get the following error
Resource not found: duke.jpg
Exception in thread "AWT-EventQueue-0" java.lang.IllegalArgumentException: creating TrayIcon with null Image
at java.awt.TrayIcon.<init>(Unknown Source)
at misc.TrayIconDemo.createAndShowGUI(TrayIconDemo.java:76)
at misc.TrayIconDemo.access$0(TrayIconDemo.java:68)
at misc.TrayIconDemo$1.run(TrayIconDemo.java:63)
at java.awt.event.InvocationEvent.dispatch(Unknown Source)
at java.awt.EventQueue.dispatchEventImpl(Unknown Source)
at java.awt.EventQueue.access$200(Unknown Source)
at java.awt.EventQueue$3.run(Unknown Source)
at java.awt.EventQueue$3.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
at java.awt.EventQueue.dispatchEvent(Unknown Source)
at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.run(Unknown Source)
Here is a picture of my folder showing where the image is.
http://i.stack.imgur.com/80tFY.png
I would just like to state that I found this http://www.oracle.com/technetwork/articles/javase/systemtray-139788.html and it works regardless if there is an image or if there isn't. Also the image had to be placed in the source folder and NOT the folder the .java was in for it to show so I'm assuming it has to be there for the original code that my questions is in regards to. So if anyone needs help with the System Tray just check the link.
A:
If you change this method like this, it works.
protected static Image createImage() {
String path="bulb.gif";
String description="";
String imageURL = path;
if (imageURL == null) {
System.err.println("Resource not found: " + path);
return null;
} else {
return (new ImageIcon(imageURL, description)).getImage();
}
}
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How to convert a nested list into a one-dimensional list in Python?
I tried everything (in my knowledge) from splitting the array and joining them up together
and even using itertools:
import itertools
def oneDArray(x):
return list(itertools.chain(*x))
The result I want:
a) print oneDArray([1,[2,2,2],4]) == [1,2,2,2,4]
Strangely, it works for
b) print oneDArray([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) == [1, 2, 3, 4, 5, 6, 7, 8, 9]
Question 1) How do I get part a to work the way I want (any hints?)
Question 2) Why does the following code above work for part b and not part a??
A:
You need to recursively loop over the list and check if an item is iterable(strings are iterable too, but skip them) or not.
itertools.chain will not work for [1,[2,2,2],4] because it requires all of it's items to be iterable, but 1 and 4 (integers) are not iterable. That's why it worked for the second one because it's a list of lists.
>>> from collections import Iterable
def flatten(lis):
for item in lis:
if isinstance(item, Iterable) and not isinstance(item, str):
for x in flatten(item):
yield x
else:
yield item
>>> lis = [1,[2,2,2],4]
>>> list(flatten(lis))
[1, 2, 2, 2, 4]
>>> list(flatten([[1, 2, 3], [4, 5, 6], [7, 8, 9]]))
[1, 2, 3, 4, 5, 6, 7, 8, 9]
Works for any level of nesting:
>>> a = [1,[2,2,[2]],4]
>>> list(flatten(a))
[1, 2, 2, 2, 4]
Unlike other solutions, this will work for strings as well:
>>> lis = [1,[2,2,2],"456"]
>>> list(flatten(lis))
[1, 2, 2, 2, '456']
A:
If you're using python < 3 then you can do the following:
from compiler.ast import flatten
list = [1,[2,2,2],4]
print flatten(list)
The manual equivalent in python 3.0 would be (taken from this answer):
def flatten(x):
result = []
for el in x:
if hasattr(el, "__iter__") and not isinstance(el, str):
result.extend(flatten(el))
else:
result.append(el)
return result
print(flatten(["junk",["nested stuff"],[],[[]]]))
You could even do the same in a list comprehension:
list = [1,[2,2,2],4]
l = [item for sublist in list for item in sublist]
Which is the equivalent of:
l = [[1], [2], [3], [4], [5]]
result = []
for sublist in l:
for item in sublist:
result.append(item)
print(result)
A:
To Make A Single list from a Nested List in python we can simply do this :
from functools import reduce
some_list = [[14], [215, 383, 87], [298], [374], [2,3,4,5,6,7]]
single_list = reduce(lambda x,y: x+y, some_list)
print(single_list)
Output:
[14, 215, 383, 87, 298, 374, 2, 3, 4, 5, 6, 7]
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Android encryption and decryption of text fails
I try to encrypt some text (here it is named code) and decrypt it again.
For this i use a 4 digit Pin which is salted.
After this the text is encrypted, also again some Base64 decoding, so i can safely output the String again.
As i understand i have to base64.decode it and then again decrypt it.
But i don't get my encrypted text correctly decrypted back. Just some different text. ( something like this[B@3ceB...)
It is just a small project nothing serious. Also it is my second android app, so some good examples would be great.
String pinstr = new String();
pinstr = "5555";
try {
EncryptDecrypt encryptor = new EncryptDecrypt(pinstr);
//encryptor.encrypt(code);
String encrypted = new String();
encrypted = encryptor.encrypt(code);
String decrypted = new String();
decrypted = encryptor.decrypt(encrypted);
Toast.makeText(MainActivity.this, decrypted, Toast.LENGTH_SHORT).show();
} catch (InvalidKeyException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NoSuchAlgorithmException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NoSuchPaddingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalBlockSizeException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (BadPaddingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
public class EncryptDecrypt {
private SecretKeySpec skeySpec;
private Cipher cipher, cipher2;
EncryptDecrypt(String password) throws NoSuchAlgorithmException,
UnsupportedEncodingException, NoSuchPaddingException,
IllegalBlockSizeException, BadPaddingException, InvalidKeyException {
MessageDigest sha = MessageDigest.getInstance("SHA-1");
byte[] key = Arrays.copyOf(sha.digest(("ThisisMySalt1234" + password).getBytes("UTF-8")),
16);
skeySpec = new SecretKeySpec(key, "AES");
cipher = Cipher.getInstance("AES");
cipher2 = Cipher.getInstance("AES");
}
String encrypt(String clear) throws InvalidKeyException, IllegalBlockSizeException, BadPaddingException, NoSuchAlgorithmException, NoSuchPaddingException {
String encrypted = new String();
cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
byte[] encryptedBytes = null;
encryptedBytes = cipher.doFinal(clear.getBytes());
encrypted = Base64.encodeToString(encryptedBytes, Base64.DEFAULT);
return encrypted;
}
// fehlerhaft
String decrypt(String encryptedBase64) throws InvalidKeyException, IllegalBlockSizeException, BadPaddingException {
String decrypted = new String();
cipher2.init(Cipher.DECRYPT_MODE, skeySpec);
byte[] decodedBytes = null;
decodedBytes = Base64.decode(encryptedBase64, Base64.DEFAULT);
decrypted = cipher2.doFinal(decodedBytes).toString();
return decrypted;
}
}
A:
The output type of Cipher#doFinal(byte[]) is byte[], but Arrays don't have a default way in which their contents are printed. By calling byte[].toString() on an array, you're simply printing its type and hash code. (More on this here)
What you want is
decrypted = new String(cipher2.doFinal(decodedBytes), "UTF-8");
which tells the String constructor that the given byte array contains characters that are encoded in UTF-8.
When you do that, then you also need to get the byte array out of the string in a specific encoding:
clear.getBytes("UTF-8")
If you omit the encoding, then the system default is used which might make your plaintexts unrecoverable when you send the ciphertexts across systems which have different system encoding defaults.
Btw, you don't need both Cipher instances. Only one suffices since you're initiating it always during encryption and decryption.
Other security problems:
Always use a fully qualified cipher string. So change Cipher.getInstance("AES") to Cipher.getInstance("AES/CBC/PKCS5Padding").
Never use ECB mode which is the default when you use "AES" cipher string. It is not semantically secure. Use at least CBC mode with a random IV:
SecureRandom r = new SecureRandom();
byte[] iv = new byte[16];
r.nextBytes(iv);
...
cipher.init(Cipher.ENCRYPT_MODE, skeySpec, new IvParameterSpec(iv));
The IV is not supposed to be secret, so you can simply prepend it to the ciphertext and splice it off before decryption.
Authenticate your ciphertext so that you're not vulnerable to a padding oracle attack and can always check your ciphertexts for integrity. This can be easily done with an encrypt-then-MAC scheme with a strong MAC algorithm like HMAC-SHA256. You can also use an authenticated mode of encryption like GCM or EAX.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
how to get an array by joining two arrays values
I have two arrays
$column_names=array[ 0=>'student_id', 1=>'college_name', 2=>'name' ]
and
$student_details=array[ 0=>array [
0=>'1', 1=>'xxx', 2=>'aaa' ], 1=>array [
0=>'2', 1=>'yyy', 2=>'bbb' ] ]
I want to get an out put array as below:
$student_details=array[ 0=>array [
'student_id'=>'1', 'college_name'=>'xxx', 'name'=>'aaa' ], 1=>array [
'student_id'=>'2', 'college_name'=>'yyy', 'name'=>'bbb' ] ]
Please somebody help me out to get the above output.
A:
You can loop the array and use array_combine
$column_names= [ 0=>'student_id', 1=>'college_name', 2=>'name' ];
$student_details=[ 0=>[
0=>'1', 1=>'xxx', 2=>'aaa' ], 1=>[
0=>'2', 1=>'yyy', 2=>'bbb' ] ];
foreach($student_details as &$sub){
$sub = array_combine($column_names, $sub);
}
var_dump($student_details);
Output:
array(2) {
[0]=>
array(3) {
["student_id"]=>
string(1) "1"
["college_name"]=>
string(3) "xxx"
["name"]=>
string(3) "aaa"
}
[1]=>
&array(3) {
["student_id"]=>
string(1) "2"
["college_name"]=>
string(3) "yyy"
["name"]=>
string(3) "bbb"
}
}
https://3v4l.org/D9kCE
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Is a linear closed and everywhere defined operator bounded?
Let $X$ be a Banach space and let $A \colon X \to X$ be a linear operator. ($D(A) = X$) Prove of disprove that if $A$ is closed then it is necessarly bounded.
(I'm having troubles in finding a connection between closedness and boundedness)
Thank you for your time and help.
A:
Summarizing the comments:
A partially defined linear operator $A \colon D(A) \subset X \to Y$ is called closed if and only if its graph $\{(x,Ax) \mid x \in D(A)\}$ is closed in $X \times Y$.
Now $D(A) = X = Y$ are assumed to be Banach spaces, so you can apply the closed graph theorem.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Is Aunt May friends with Doctor Octavius?
When Hobo-Spidey and Miles infiltrate the Alchemax laboratory out in the forest, they inadvertently come face to face with Dr. Octopus, who in this dimension is actually a female version, Dr. Olivia Octavius. In the screenplay it reads:
HEAD SCIENTIST
My friends actually call me Liv.
(then turning)
My enemies call me Doc Ock.
When all the Spiders are grouped up at Aunt May's house and attacked by Doc Ock and her cronies, Aunt May says:
DOC OCK
Cute place. Real homey.
AUNT MAY
Oh great, it’s Liv.
So if only friends of Doc Ock call her Liv, and Aunt May calls her Liv here, is it safe to say that Aunt May is a friend of Olivia? It seems somewhat possible, considering she also acts as a pseudo-Alfred for Spiderman, what with themed cars, a myriad of suit colors and choices, and many technological upgrades.
A:
There's a suggestion that this is a throwback to deeper Spider-Man lore from the comics like some of the other references and jokes.
In the video above MovieBob talks about how in the Spider-Man comics there have been instances where Doc Ock and Aunt May have had a thing for one another. At the start it was Aunt May working for Doc Ock as a maid, seeing him as a good person and Spider-Man being a bully to him and later (after getting out of prison) Doc Ock dates and goes to marry Aunt May, though this was a scheme to get access to a nuclear power plant on an island Aunt May unknowingly inherited Doc Ock grows to care for her and doesn't want her hurt as apart of the scheme.
^ Spider-man Issue #131
After this MovieBob also mentioned that Marvel has revisited this relationship in the comics indicating Doc Ock and Aunt May had chemistry and may even be hooked up.
How does this relate to Into the Spider-Verse? Well before the timed part, MovieBob suggested they could have been scientists together but there are other throwaway Easter eggs that are for the more devoted fans of the comics who would know about and Doc Ock and Aunt May being a couple would be one of them.
As such MovieBob's opinion is that Aunt May may not be just friends with Doctor Octavius, they could be former lovers, and in that context "Oh great, it’s Liv." does sounds like something someone would say when their ex suddenly appears. *internally screams like a girl for yuri*
|
{
"pile_set_name": "StackExchange"
}
|
Q:
JQuery/Javascript - Redirect to previous page when countdown reaches zero?
This is my first question and i'm fairly new to JS. Anyway, i found this countdown timer on JSFiddle ( http://jsfiddle.net/gPrwW/395/ )and i was wondering what edits need to be made to redirect to the previous page after the timer gets to zero? Thanks for the help!
$(document).ready(function(e) {
var $worked = $("#worked");
function update() {
var myTime = $worked.html();
var ss = myTime.split(":");
var dt = new Date();
dt.setHours(0);
dt.setMinutes(ss[0]);
dt.setSeconds(ss[1]);
var dt2 = new Date(dt.valueOf() - 1000);
var temp = dt2.toTimeString().split(" ");
var ts = temp[0].split(":");
$worked.html(ts[1] + ":" + ts[2]);
setTimeout(update, 1000);
}
setTimeout(update, 1000);
});
A:
Try this out :
<html>
<head>
<script src="https://code.jquery.com/jquery-2.2.3.js" integrity="sha256-laXWtGydpwqJ8JA+X9x2miwmaiKhn8tVmOVEigRNtP4=" crossorigin="anonymous"></script>
<script>
$(document).ready(function(e) {
var $worked = $("#worked");
function update() {
var myTime = $worked.html();
if (myTime == "00:00") {
window.history.back();
return;
}
var ss = myTime.split(":");
var dt = new Date();
dt.setHours(0);
dt.setMinutes(ss[0]);
dt.setSeconds(ss[1]);
var dt2 = new Date(dt.valueOf() - 1000);
var temp = dt2.toTimeString().split(" ");
var ts = temp[0].split(":");
$worked.html(ts[1] + ":" + ts[2]);
setTimeout(update, 1000);
}
setTimeout(update, 1000);
});
</script>
</head>
<body>
<div id="worked">00:10</div>
</body>
</html>
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Plot the longest transcript in GenomicRanges with ggbio
I am trying to plot an specific region using ggbio. I am using the below code that produced my desire output, except that it contains several transcript. Is it possible to only plot the longest transcript? I've not been able to access the genomic ranges object within Homo.sapiens that I assume contains this information.
library(ggbio)
library(Homo.sapiens)
range <- GRanges("chr10" , IRanges(start = 78000000 , end = 79000000))
p.txdb <- autoplot(Homo.sapiens, which = range)
p.txdb
A:
Here is a solution that involves filtering TxDb.Hsapiens.UCSC.hg19.knownGene on the longest transcript by gene_id (which does remove genes without gene_id):
suppressPackageStartupMessages({
invisible(lapply(c("ggbio", "biovizBase", "data.table",
"TxDb.Hsapiens.UCSC.hg19.knownGene",
"org.Hs.eg.db"),
require, character.only = TRUE))})
txdb <- TxDb.Hsapiens.UCSC.hg19.knownGene
# retrieve transcript lengths
txlen <- transcriptLengths(txdb, with.utr5_len=TRUE, with.utr3_len=TRUE)
setDT(txlen)
txlen$len <- rowSums(as.matrix(txlen[, .(tx_len, utr5_len, utr3_len)]))
setkey(txlen, gene_id, len, tx_id)
# filter longesttranscript by gene_id
ltx <- txlen[!is.na(gene_id)][, tail(.SD,1), by=gene_id]$tx_id
# filter txdb object
txb <- as.list(txdb)
txb$transcripts <- txb$transcripts[txb$transcripts$tx_id %in% ltx, ]
txb$splicings <- txb$splicings[txb$splicings$tx_id %in% ltx,]
txb$genes <- txb$genes[txb$genes$tx_id %in% ltx,]
txb <- do.call(makeTxDb, txb)
# plot according to vignette, chapter 2.2.5
range <- GRanges("chr10", IRanges(start = 78000000 , end = 79000000))
gr.txdb <- crunch(txb, which = range)
#> Parsing transcripts...
#> Parsing exons...
#> Parsing cds...
#> Parsing utrs...
#> ------exons...
#> ------cdss...
#> ------introns...
#> ------utr...
#> aggregating...
#> Done
colnames(values(gr.txdb))[4] <- "model"
grl <- split(gr.txdb, gr.txdb$gene_id)
symbols <- select(org.Hs.eg.db, keys=names(grl), columns="SYMBOL", keytype="ENTREZID")
#> 'select()' returned 1:1 mapping between keys and columns
names(grl) <- symbols[match(symbols$ENTREZID, names(grl), nomatch=0),"SYMBOL"]
autoplot(grl, aes(type = "model"), gap.geom="chevron")
#> Constructing graphics...
Created on 2020-05-29 by the reprex package (v0.3.0)
Edit:
To get gene symbols instead of gene (or transcript) ids, just replace the names of grl with the associated gene symbols, e.g. via org.Hs.eg.db, or any other resource that matches them up.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Cannot generate adhoc IPA from command-line but it works in Xcode
I'm trying to generate an adhoc IPA from the command-line but I cannot get it to works.
I can however generate an adhoc IPA from Xcode doing Product -> Archive and Export... in Organizer.
Here is how I proceed to generate an IPA on the command-line
xcodebuild -project DemoApp.xcodeproj -scheme DemoApp archive -archivePath build/DemoApp.xcarchive -configuration Release
xcrun -sdk iphoneos PackageApplication -v build/DemoApp.xcarchive/Products/Applications/DemoApp.app -o build/DemoApp.ipa --sign "iPhone Distribution" --embed DemoApp_Adhoc.mobileprovision
When I install the generated IPA via iTunes, it doesn't install properly on the device. The icon is greyed out and the title says "Installing..." like here.
I've checked the provisioning profile, the UUID, etc.
I tried with shenzhen but got the same behavior.
Can you spot what I'm doing wrong?
Thanks!
A:
Finally I did not find the problem with PackageApplication but as a workaround I used PROVISIONING_PROFILE and CODE_SIGN_IDENTITY environment variable with the xcodebuild step and it worked.
Here are the new commands:
xcodebuild -project DemoApp.xcodeproj -scheme DemoApp archive -archivePath build/DemoApp.xcarchive -configuration Release PROVISIONING_PROFILE="00000000-0000-0000-0000-000000000000" CODE_SIGN_IDENTITY="iPhone Distribution: Company Inc (XXXXXXXXXX)"
xcrun -sdk iphoneos PackageApplication -v build/DemoApp.xcarchive/Products/Applications/DemoApp.app -o build/DemoApp.ipa")
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Does jqueryui have CSS rules for normal HTML elements?
As I have understood, jqueryui has 2 sets of things:
Ready made elements that can be used in developing web apps (like menu, datepicker and so so...)
CSSs ready to use with the elements talked about before
Now my question is:
Are the CSSs ready to be used for Normal HTML Elements, too? Like forms, ul and ol lists, as, and others?
This way, standard HTML elements' style can be compatible with other jqueryui widgets.
Are there also some ready .half, .third, .full-width classes for divs?
Unfortunately I couldn't get the answer even after reading http://api.jqueryui.com/category/theming, http://api.jqueryui.com/theming/css-framework/ and http://api.jqueryui.com/theming/stacking-elements/.
A:
No, jQuery UI doesn't include anything that you mentioned.
jQuery UI is based on widgets. You call one of those widgets on top of your elements and "let the magic happen".
The only styles that you may use in your application CSS are:
.ui-helper-hidden: to hide your element;
.ui-helper-hidden-accessible: to hide your element, but let it be "accessible"
.ui-helper-reset
.ui-helper-clearfix: The famous clearfix hack
.ui-helper-zfix
All the .ui-icons
About the other styles you mentioned:
For styling other elements like forms, lists and the grid system (the .half, .full & etc part of your question), I'd recommend you to give a try to Twitter Bootstrap, if you already haven't.
|
{
"pile_set_name": "StackExchange"
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.