text
stringlengths 64
81.1k
| meta
dict |
---|---|
Q:
Pandas: Group by operation on dynamically selected columns with conditional filter
I have a dataframe as follows:
Date Group Value Duration
2018-01-01 A 20 30
2018-02-01 A 10 60
2018-01-01 B 15 180
2018-02-01 B 30 210
2018-03-01 B 25 238
2018-01-01 C 10 235
2018-02-01 C 15 130
I want to use group_by dynamically i.e. do not wish to type the column names on which group_by would be applied. Specifically, I want to compute mean of each Group for last two months.
As we can see that not each Group's data is present in the above dataframe for all dates. So the tasks are as follows:
Add a dummy row based on the date, in case data pertaining to Date = 2018-03-01not present for each Group (e.g. add row for A and C).
Perform group_by to compute mean using last two month's Value and Duration.
So my approach is as follows:
For Task 1:
s = pd.MultiIndex.from_product(df['Date'].unique(),df['Group'].unique()],names=['Date','Group'])
df = df.set_index(['Date','Group']).reindex(s).reset_index().sort_values(['Group','Date']).ffill(axis=0)
can we have a better method for achieving the 'add row' task? The reference is found here.
For Task 2:
def cond_grp_by(df,grp_by:str,cols_list:list,*args):
df_grp = df.groupby(grp_by)[cols_list].transform(lambda x : x.tail(2).mean())
return df_grp
df_cols = df.columns.tolist()
df = cond_grp_by(dealer_f_filt,'Group',df_cols)
Reference of the above approach is found here.
The above code is throwing IndexError : Column(s) ['index','Group','Date','Value','Duration'] already selected
The expected output is
Group Value Duration
A 10 60 <--------- Since a row is added for 2018-03-01 with
B 27.5 224 same value as 2018-02-01,we are
C 15 130 <--------- computing mean for last two values
A:
Use GroupBy.agg instead transform if need output filled by aggregate values:
def cond_grp_by(df,grp_by:str,cols_list:list,*args):
return df.groupby(grp_by)[cols_list].agg(lambda x : x.tail(2).mean()).reset_index()
df = cond_grp_by(df,'Group',df_cols)
print (df)
Group Value Duration
0 A 10.0 60.0
1 B 27.5 224.0
2 C 15.0 130.0
If need last value per groups use GroupBy.last:
def cond_grp_by(df,grp_by:str,cols_list:list,*args):
return df.groupby(grp_by)[cols_list].last().reset_index()
df = cond_grp_by(df,'Group',df_cols)
| {
"pile_set_name": "StackExchange"
} |
Q:
systemctl Failed to start service, Invalid argument
I need to run a Qt application on startup with root permission , below is the script I created using systemctl named QtApp.service
[Unit]
Description=QtApp
[Service]
ExecStart= exec su -l user -c 'export DISPLAY=:0; /QtInst/QtApp'
Restart=always
[Install]
WantedBy=multi-user.target
But when I run the command to start the service sudo systemctl start QtApp.service I am getting following error
Failed to start QtApp.service: Unit QtApp.service is not loaded properly: Invalid argument.
Here is the details of error
systemctl status QtApp.service
● QtApp.service - QtApp
Loaded: error (Reason: Invalid argument)
Active: inactive (dead)
Jul 06 15:23:54 user-pc systemd[1]: [/etc/systemd/system/QtApp.service:5] Executable path is not absolute, ignoring: exec su -l user -c 'export DISPLAY=:0; /QtInst/QtApp'
Jul 06 15:23:54 user-pc systemd[1]: QtApp.service: Service lacks both ExecStart= and ExecStop= setting. Refusing.
Jul 06 15:26:08 user-pc systemd[1]: [/etc/systemd/system/QtApp.service:5] Executable path is not absolute, ignoring: exec su -l user -c 'export DISPLAY=:0; /QtInst/QtApp'
Jul 06 15:26:08 user-pc systemd[1]: QtApp.service: Service lacks both ExecStart= and ExecStop= setting. Refusing.
A:
Executable path is not absolute -- it means exec.
Generally exec makes no sense here. It's a shell builtin that replaces the shell with a given command. There is no absolute path to exec executable because there is no executable.
su is an executable. The line may be
ExecStart=/bin/su -l user -c 'export DISPLAY=:0; /QtInst/QtApp'
But using su may not be a good idea in systemd service. See: How do I make my systemd service run via specific user and start on boot?
| {
"pile_set_name": "StackExchange"
} |
Q:
t_delta too long error on Freenas 0.7.1
I am using FreeNas 0.7.1 (FreeBSD 7.2-release-p6) Recently I have been getting a series of these error messages to the console. I am using ZFS pools mirrored on the FreeNAS system, and they report as healthy and in good status.
I think this error message is related to the FreeBSD underneath. The ZFSpools are iscsi targets for a VMWare installation over Gigabit network. Is the delta_t they are referring to talking about a potential time out for packets over iSCSI? Has anyone experienced this error message? I have attached an image below.
A:
It's an error with the time clock on your computer, has nothing to do with ZFS, iSCSI, etc.
Try updating your MB's BIOS. Or post the make/model and we might be of more help. In any case it's nothing to worry about if the clock is still correct.
| {
"pile_set_name": "StackExchange"
} |
Q:
overflow:auto does not work with CSS3 transformed child elements. Suggested workaround?
Problem: css3 transforms applied to a child element inside a div are ignored by the browser (FF5, Chrome12, IE9) when calculating the scrollHeight and scrollWidth of the containing div's scrollbars when using "overflow: auto;".
<style type="text/css">
div{ width: 300px;height:500px;overflow:auto; }
div img {
-moz-transform: scale(2) rotate(90deg);
-webkit-transform: scale(2) rotate(90deg);
-ms-transform: scale(2) rotate(90deg);
}
</style>
<div><img src="somelargeimage.png" /></div>
I have put together a small test on jsfiddle showing the undesired behavior.
http://jsfiddle.net/4b9BJ/
Essentially I am trying to create a simple web based image viewer using css3 transforms for rotate and scale and would like a containing div with fixed width/height to be able to scroll to see the full content of the image it contains.
Is there an intelligent way to handle this issue, or even a rough workaround? Any help is appreciated.
A:
I added an extra div to each of the transformations and by setting fixed widths for those divs and clipping overflow I manged to make them the correct size. But then I had to use position: relative and top: blah; left: blah to shift the images into the correct position.
http://jsfiddle.net/4b9BJ/7/
| {
"pile_set_name": "StackExchange"
} |
Q:
Update qty on cart page doesn't work because of formkey conflict
Configuration: Varnish + Pagecache module, Redirect all pages to www. in htaccess
Issue: Whenever someone hits non-www page a PAGECACHE_FORMKEY cookie is stored. Then they get redirected to www. and another PAGECACHE_FORMKEY cookie is stored but with a different value.
My code has the formkey:
<form action="<?php echo $this->getUrl('checkout/cart/updatePost') ?>" method="post">
<?php echo $this->getBlockHtml('formkey'); ?>
Tried with:
<form action="<?php echo $this->getUrl('checkout/cart/updatePost') ?>" method="post">
<input type="hidden" name="form_key" value="<?php echo Mage::getSingleton('core/session')->getFormKey(); ?>"/>
Still doesn't work, as Mage::getSingleton('core/session')->getFormKey() outputs the second formkey. If I delete the first PAGECACHE_FORMKEY then it will work.
How can I bypass formkey verification on checkout/cart/updatePost?
(This has nothing to do with my theme, it happens with the default theme too, so I guess it is an issue with the connection that PageCache module establishes between varnish and the magento application. )
A:
The solution was to disable formkey validation on the checkout_cart_updatePost event.
function disableCsrf($observer)
{
$events = array(
'checkout_cart_updatePost',
);
$route = $observer->getEvent()->getControllerAction()->getFullActionName();
if (in_array($route, $events)) {
$key = Mage::getSingleton('core/session')->getFormKey();
Mage::app()->getRequest()->setParam('form_key', $key);
}
}
Same as in SupportDesk_CartFormKey module.
| {
"pile_set_name": "StackExchange"
} |
Q:
NSDate() - Playground vs. Swift Xcode
I noticed that when I am in a Swift playground, a call to NSDate() generates a date with this format:
< date time AM|PM >
However, inside xcode/app, NSDate() generates a date with this format
< date time UTC >
I am not clear why there is such a difference? How can I force xcode to always generate NSDate as < date time AM|PM >?
A:
NSDate is used to represent a point in time. It does not have any notion of format.
What you want to use to print the content of an NSDate is NSDateFormatter
let dateFormatter = NSDateFormatter()
dateFormatter.dateStyle = NSDateFormatterStyle.LongStyle
dateFormatter.timeStyle = NSDateFormatterStyle.MediumStyle
print(dateFormatter.stringFromDate(NSDate()))
A:
NSDate doesen't have any concept of a time zone per se. From the docs
The sole primitive method of NSDate, timeIntervalSinceReferenceDate,
provides the basis for all the other methods in the NSDate interface.
This method returns a time value relative to an absolute reference
date—00:00:00 UTC on 1 January 2001.
In the playground if you just write let date = NSDate() its doing some kind of date formatting on its own (which is interesting but should not be expected). If you print(date) if will show you what the date actually contains.
If you want to format dates inside of your app you should look at using the NSDateFormatter class.
| {
"pile_set_name": "StackExchange"
} |
Q:
Is there a standardized "Astronomical Alert" system?
“Who saw” the binary neutron star merger first? What was the sequence of events? (GRB/GW170817) highlights a particularly notable astronomical alert, but I am sure that there are alerts triggered by various systems sent to various other systems.
Question: Is there a standardized "Astronomical Alert" system? Or are there many decentralized and specialized systems for each of various specific scenarios, such as the one described in Does the Zwicky Transient Facility only run when triggered by a cell phone?
The question occurred to me after posting Will LSST make a significant increase in the rate of astronomical event alerts?
A:
In general, no there is not a standardized alert system (unless you count email...). Most subareas of time-domain astronomy that deal with alerts tend to have their own central clearing houses and alert distribution mechanisms. Most of the high energy/explosive (supernovae, novae, blackhole transients (stellar or massive)) transient community tends to announce things via Astronomers Telegram which have basically replaced the older IAU Circulars and the Central Bureau for Astronomical Telegrams for announcing things. More recently, those working on comet outbursts have also sent notifications via ATel e.g. the recent Comet 29P outburst.
The NEO community tends to coordinate through the Minor Planet Center NEO Confirmation Page (NEOCP) for newly discovered NEO candidates found by the surveys. In recent years, this has been supplemented by the JPL/CNEOS Scout system which performs risk analysis on the NEOCP candidates and sends out email alerts for close passing objects or where they may be issues with the measurements - follow-up and discussion on these is done via email.
The Gamma Ray Burst (GRB) community has had the GCN Circulars as previously mentioned which started around the end of Compton Gamma Ray Observatory and the start of BeppoSAX when better location of GRBs become possible. An issue with both ATels and GCN Circulars is that they are written in English text and are sent via email and are mainly designed for human consumption and reaction. This has been recognized as an issue for many years and lead to the development of the VOEvent 2.0 which became an IVOA Recommendation in 2011. Quoting from the Abstract of the document:
VOEvent [20] defines the content and meaning of a standard information packet for representing, transmitting, publishing and archiving information about a transient celestial event, with the implication that timely follow-up is of interest. The objective is to motivate the observation of targets-of-opportunity, to drive robotic telescopes, to trigger archive searches, and to alert the community. VOEvent is focused on the reporting of photon events, but events mediated by disparate phenomena such as neutrinos, gravitational waves, and solar or atmospheric particle bursts may also be reported. Structured data is used, rather than natural language, so that automated systems can effectively interpret VOEvent packets. Each packet may contain zero or more of the "who, what, where, when & how" of a detected event, but in addition, may contain a hypothesis (a "why") regarding the nature of the underlying physical cause of the event.
It's fair to say that adoption of VOEvent has been slow and limited, driven in part by a lack of easy-to-use libraries or toolkits, but usage is picking up with the LIGO/VIRGO gravitational wave alerts going out in VOEvent XML format (Alerts User Guide) and a standard for reporting Fast Radio Bursts. Sending of VOEvents from the LSST brokers is also planned and so the standard is likely to see greater adoption.
| {
"pile_set_name": "StackExchange"
} |
Q:
how to add tag in soap response
Using gsoap I have generated server C++ codes.
Using SoapUI, I send a message to server and get the response. Until here every thing is fine.
I wanted to add more tags on the response. To do that, I have manipulated server codes. Originally the code generated by gsoap that produces the response is:
if (soap_end_count(soap)
|| soap_response(soap, SOAP_OK)
|| soap_envelope_begin_out(soap)
|| soap_putheader(soap)
|| soap_body_begin_out(soap)
|| tempuri__IsAliveResponse.soap_put(soap, "tempuri:IsAliveResponse", "")
|| soap_body_end_out(soap)
|| soap_envelope_end_out(soap)
|| soap_end_send(soap))
return soap->error;
This gives me the response below:
<SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" xmlns:SOAP-ENC="http://schemas.xmlsoap.org/soap/encoding/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:ser="http://schemas.microsoft.com/2003/10/Serialization/" xmlns:tempuri="http://tempuri.org/">
<SOAP-ENV:Header/>
<SOAP-ENV:Body>
<tempuri:IsAliveResponse/>
</SOAP-ENV:Body>
</SOAP-ENV:Envelope>
But when I want to add some tag more in the response:
if (soap_end_count(soap)
|| soap_response(soap, SOAP_OK)
|| soap_envelope_begin_out(soap)
|| soap_putheader(soap)
|| soap_body_begin_out(soap)
|| tempuri__IsAliveResponse.soap_put(soap, "tempuri:IsAliveResponse", "")
|| tempuri__IsAliveResponse.soap_put(soap, "newTag", "")
|| soap_body_end_out(soap)
|| soap_envelope_end_out(soap)
|| soap_end_send(soap))
return soap->error;
Then I get a cut, partial response:
<?xml version="1.0" encoding="UTF-8"?>
<SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" xmlns:SOAP-ENC="http://schemas.xmlsoap.org/soap/encoding/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:ser="http://schemas.microsoft.com/2003/10/Serialization/" xmlns:tempuri="http://tempuri.org/">
<SOAP-ENV:Header></SOAP-ENV:Header>
<SOAP-ENV:Body>
<tempuri:IsAliveResponse></tempuri:IsAliveResponse>
<newTag></newTag>
</SOAP-ENV:Body>
</
Then I have discovered that Content-Length: is always 524. Moreover, every character that I add is counted as 2.
I do not see where is decided this fixed 524 length. Does it come from a buffer size? If so, how could I generate the code with larger buffer size?
How could I add more data on response in a gsoap generated C++ soap server code?
A:
To add more parameter tags to the response is easy. Just edit the interface .h file (generated by wsdl2h). This file has a tempuri__IsAliveResponse class. Add more members to this class to add the response parameters you want. Then let soapcpp2 generate fresh source code with the additional params. These tags will appear within the IsAliveResponse tag.
To create a response with multiple tags that aren't nested in IsAliveResponse, define a class with two leading underscores to make that class "invisible" to the serializer, for example class __tempuri__MyResponse. Then add the member tempuri__IsAliveResponse tempuri__IsAliveResponse_ (note the ending _ here to avoid a name clash) and other members that you want as tags. Use the new class __tempuri__MyResponse as the response type for the service operation.
| {
"pile_set_name": "StackExchange"
} |
Q:
Integrating Leaflet and Bootstrap: help refactoring my css
I'm trying to use Bootstrap to structure a page containing a leaflet map.
Here is how it looks like:
I've been unable to do it with bootstrap.
I wrote some ugly css which barely works:
HTML
<div class="container-fluid fill">
<div class="row-fluid fill">
<div class="span9 fill-height">
<div id="map"></div>
</div>
<div class="span3">
<div id="filters">
</div>
</div>
</div>
</div>
CSS
#map
{
width: 100px;
height:100px;
min-height: 100%;
min-width: 100%;
display: block;
}
html, body
{
height: 100%;
}
.fill
{ padding-left: 0px;
min-height: 100%;
height: 100%;
width: 100%;
min-width: 100%;
}
.fill-height
{ padding-left: 0px;
min-height: 100%;
height: 100%;
}
body
{
padding-top: 40px; /*for navbar*/
-webkit-box-sizing: border-box; /* Safari/Chrome, other WebKit */
-moz-box-sizing: border-box; /* Firefox, other Gecko */
box-sizing: border-box; /* Opera/IE 8+ */
}
I had to remove the padding to prevent overflow, so now my form has no padding.
My question:
How do I obtain that structure with the bootstrap classes? How can I keep the padding but only for the form?
A:
Still a lot of css, needed, but padding problems solved:
#map
{
width: 100px;
height:100px;
min-height: 100%;
min-width: 100%;
display: block;
}
html, body
{
height: 100%;
}
.fill
{ padding: 0px;
min-height: 100%;
height: 100%;
width: 100%;
min-width: 100%;
}
.fill-height
{ padding: 0px;
min-height: 100%;
height: 100%;
}
body
{
padding-top: 40px; /*for navbar*/
-webkit-box-sizing: border-box; /* Safari/Chrome, other WebKit */
-moz-box-sizing: border-box; /* Firefox, other Gecko */
box-sizing: border-box; /* Opera/IE 8+ */
}
| {
"pile_set_name": "StackExchange"
} |
Q:
How to socket.io with express generator? Individual socket, for individual link
I have typical express-generator app. In my controllers folder I have code:
router.get('/:id([A-Za-z0-9_]{5,25})', function(req, res, next) {
res.render('my-page.html', { title: 'Messages'});
//How to implement socket.io code for this page?
/*
io.on('connection', function(socket){
console.log('a user connected');
});
*/
});
I tried simple guide from socket.io website and from stackoverflow advices, but it isn't working.
Try to imagine, that here is many different chat rooms, and for every room, I need to open individual socket... I know how to make it global, but have no idea, how to make personal socket, for personal page...
A:
That's what rooms are made for.
socket.join(<ROOM_NAME>)
If you'd like to join a room, named for URL you got connected from, you can use socket.request.url. For instance:
io.sockets.on('connection', (socket) =>
{
const _req = socket.request
console.log(_req.url) // do something with it
}
edit
and do not put socket.io logic in your REST route. Make one, global connection logic, which you can (obviously) make modular.
| {
"pile_set_name": "StackExchange"
} |
Q:
printing int in c by %s in printf
The compiler doesn't mark it as any error.
I know that it's wrong,
but I want to know why it's showing the name of the company.
And it doesn't show this message if I type any value less than 4,
it gives different outputs for different such values, try some
values like 50, 100,etc.
Why it's showing such strange outputs.
Here is the program.
void main()
{
int a=6;
printf("%s",a);
}
A:
Your program behaviour is undefined since %s is not a valid format specifier for an int.
Exactly why it gives you the values it does is down to conjecture. The compiler also reserves the right to eat your cat. And your dog given that void main() is not compliant with later C standards.
C intentionally does not guard against your doing this as that would compromise the performance of the language. It's difficult (although not impossible as C is statically typed) for a compiler to warn you of this.
A:
It shows you not name of the company. Compiler treats 6 as pointer and prints character data from that address until it finds escape sequence \0
If you compile this code with different compiler, you will most likely get different results, thats why it is called undefined behavior, as it been rightfully pointed in other answers.
A:
First of all you should really start to use the minimum standard.
There are a lot of code missing in here and of course you are using an invalid format specifier.
You started with an int but you try to print it as a String (%d vs %s)
Also your Main Function it's not ok and the return type is missing too.
This is what you need:
#include<stdio.h>
int main(void){
int a=6;
printf("%d",a);
return 0;
}
| {
"pile_set_name": "StackExchange"
} |
Q:
One Query output execution in another query
Description
select maximum reflectance value as max and minimum reflectance value as min where
wavelength between 650 and 800 and apply formula (max+min)/2+min as radiance
select the reflectance where wavelength nearer to 700 as r700 and
select the reflectance where wavelength nearer to 740 as r740
Apply Formula
700+(radiance-r700)/(r740-r700)*40
output value as radtera and i want to display radiance value and radtera value as output
I tried this query, It is showing so many values in radiance and it shows many null values in radtera, but i want only display one radiance value and one radtera value
SELECT radiance, (700+(radiance-r700))/((r740-r700)*40) as radtera
FROM (
SELECT (MAX(reflectance)+MIN(reflectance))/2+MIN(reflectance) as radiance,
case when wavelength=700 then reflectance end as r700,
case when wavelength=740 then reflectance end as r740
FROM table_name
WHERE wavelength between 650 and 800
GROUP BY wavelength,reflectance
) AS SE_23693370
If i remove
GROUP BY wavelength,reflectance
this from query, it is showing error
Here is SQL fiddle.
I checked it, i dont know how it is displaying many values instead of one value show.. Anyone help me to correct mistakes please...
I tried using case statement in SQL fiddle.
select reip,700+(reip-r45)/(r72-r45)*40 as reipw
from (
select (mx+mn))/2+mn as reip
from (
select case max(tert) as mx,
case min(tert) as mn
case when iner=44.5 then tert end as r45,
case when iner=72.1 then tert end as r72
from table_name
where iner between 43 and 79)bar
)as SE_23693370
It shows *ERROR: subquery in FROM must have an alias: select reip,700+(reip-r45)/(r72-r45)40 as reipw from ( select (mx+mn))/2+mn as reip from ( select case max(tert) as mx, case min(tert) as mn case when iner=44.5 then tert end as r45, case when iner=72.1 then tert end as r72 from table_name where iner between 43 and 79) )as SE_23693370
A:
You could do this with the ROW_NUMBER function. It is available in SQL Server, Oracle, and PostgreSQL, amongst others.
select radiance, r700, r740,
(700+(radiance-r700))/((r740-r700)*40) as radtera
from
(select t.reflectance as radiance,
t700.wavelength as r700, t740.wavelength as r740
from
(select max(reflectance) as reflectance
from table_name) t,
(SELECT reflectance, wavelength,
row_number() over (order by abs(wavelength-700)) as rn700
FROM table_name
WHERE wavelength between 650 and 800) as t700,
(SELECT reflectance,wavelength,
row_number() over (order by abs(wavelength-740)) as rn740
FROM table_name
WHERE wavelength between 650 and 800) as t740
where t700.rn700=1 and t740.rn740=1) as di
Fiddle
| {
"pile_set_name": "StackExchange"
} |
Q:
How to make an external js file write to the html
I'm trying to write a function in an external javascript file linked to the index.html, which when called writes; for example between the <script></script> tags in the index.html file on line 18. Is it possible to do this with plain Javascript or jQuery? If so, how could this be done?
EDIT: I want to only have one script tag in my index.html.
function writeToScriptTags() {
// this function should write alert("Hello") to the <script></script> tags in the index.html file.
}
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<!-- Dependencies -->
<script src="https://code.jquery.com/jquery-3.3.1.min.js" charset="utf-8"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.min.js" charset="utf-8"></script>
<script src="https://code.jquery.com/color/jquery.color-2.1.2.min.js" charset="utf-8"></script>
<title>CodeDragon</title>
<link rel="stylesheet" href="/css/master.css">
</head>
<body>
<div id="Dragon"></div>
<input type="text" name="_input" value="" id="_input">
<script src="script.js" charset="utf-8"></script>
<script>
// Javascript file should write alert("Hello") here
</script>
</body>
</html>
A:
If the script tag already exists then you can set it's text/textContent/innerText value to whatever code you want to execute. But the script would need to have been empty beforehand, ie no text not even whitespace, otherwise it would not run.
//use an appropriate css selector to find the correct script
//this just selects the first script it finds
var s = document.querySelector('script');
s.text = 'alert("Here")';
It would probably be better to just create a new script element and add the code to that as then you would not need to worry about wither or not the script tag had already previously been used.
var s = document.createElement('script');
document.head.appendChild(s);
s.text = 'alert("Here")';
And of course if the script is set with a src attribute setting the text of the script will not run any code as it is ignored for externally linked script elements.
| {
"pile_set_name": "StackExchange"
} |
Q:
python/pandas: using regular expressions remove anything in square brackets in string
Working from a pandas dataframe trying to sanitize a column from something like $12,342 to 12342 and make the column into an int or float. Found one row though with 736[4] so I have to remove everything within the square brackets, brackets included.
Code so far
df2['Average Monthly Wage $'] = df2['Average Monthly Wage $'].str.replace('$','')
df2['Average Monthly Wage $'] = df2['Average Monthly Wage $'].str.replace(',','')
df2['Average Monthly Wage $'] = df2['Average Monthly Wage $'].str.replace(' ','')
The line below is what's supposed to handle and remove the square brackets and intentionally with it's content too.
df2['Average Monthly Wage $'] = df2['Average Monthly Wage $'].str.replace(r'[[^]]*\)','')
To some dev's this is trivial but I've not really used regular expressions often enough to know this and I've also checked around and from one such stack example formulated the above.
A:
I think you need:
df2 = pd.DataFrame({'Average Monthly Wage $': ['736[4]','7336[445]', '[4]345[5]']})
print (df2)
Average Monthly Wage $
0 736[4]
1 7336[445]
2 [4]345[5]
df2['Average Monthly Wage $'] = df2['Average Monthly Wage $'].str.replace(r'\[.*?\]','')
print (df2)
Average Monthly Wage $
0 736
1 7336
2 345
regex101.
| {
"pile_set_name": "StackExchange"
} |
Q:
Function to build an unknown number of dictionaries
What is the best solution for creating the necessary number of dictionaries based on the number of lists that have a value matching a specified value? And how do I specify an intuitive name for the dictionaries?
I made a (rookie) mistake. I hard-coded a predefined set of dictionaries ignoring potential future cases.
My snippet:
primarytuesday = {}
secondarytuesday = {}
primarythursday = {}
secondarythursday = {}
coaches = [["4/27/1976", "Person One", "Site 1"], ["4/27/1976", "Person Two", "Site 1"],
["4/29/1976", "Person Three", "Site 1"], ["4/29/1976", "Person Four", "Site 1"]]
def sort_coaches(date, primary, secondary):
for eachsession in coaches:
if eachsession[0] == date:
if eachsession[2] in primary:
secondary[eachsession[2]] = eachsession[1]
else:
primary[eachsession[2]] = eachsession[1]
sort_coaches("4/27/1976", primarytuesday, secondarytuesday)
sort_coaches("4/29/1976", primarythursday, secondarythursday)
Output (working as intended):
primarytuesday == {'Site 1': 'Person One'}
secondarytuesday == {'Site 1': 'Person Two'}
primarythursday == {'Site 1': 'Person Three'}
secondarythursday == {'Site 1': 'Person Four'}
Issue: The issue comes if a third value for a particular day is added to the list as in...
coaches = [["4/27/1976", "Person One", "Site 1"], ["4/27/1976", "Person Two", "Site 1"], ["4/27/1976", "Person Three", "Site 1"]
["4/29/1976", "Person Four", "Site 1"], ["4/29/1976", "Person Five", "Site 1"]]
The output changes the value in secondarytuesday to the third individual and gets rid of the second individual completely. Makes sense, but not what is intended.
My first thought is to scrap the entire code and create a nested function for each list within the list. This would probably require some use of zip, but I'm not completely sure.
As an aside: I'm sure there are more efficient ways as opposed to iterating over the entire list and comparing eachsession[0] to date within the for loop, but let that serve as an example of where I am as a coder.
A:
You should use lists at the output of your function instead of individual variables. This will allow you to have any number of primary, secondary, tertiary, ... entries that you can manipulate using indexes within a day.
In fact, you can convert the whole thing to a master dictionary indexed on dates in one pass and then use the dictionary:
coaches = [["4/27/1976", "Person One", "Site 1"], ["4/27/1976", "Person Two", "Site 1"], ["4/27/1976", "Person Three", "Site 1"],
["4/29/1976", "Person Four", "Site 1"], ["4/29/1976", "Person Five", "Site 1"]]
sortedCoaches = dict()
for date,person,site in coaches:
day = sortedCoaches.setdefault(date,list())
d = next((d for d in day if site not in d),dict())
if not d: day.append(d)
d[site] = person
dayInfo = sortedCoaches["4/27/1976"]
[{'Site 1': 'Person One'}, {'Site 1': 'Person Two'}, {'Site 1': 'Person Three'}]
dayInfo = sortedCoaches["4/29/1976"]
[{'Site 1': 'Person Four'}, {'Site 1': 'Person Five'}]
| {
"pile_set_name": "StackExchange"
} |
Q:
How to compare time ranges in text file with time ranges that entered by user in qt?
I have a text file as follows:
05:59:57 - [0x1010001]05:59:57 - (2576) WRITING TO NON-VOLATILE MEMORY IS DONE
06:00:00 - [0x1010001]06:00:00 - (23371) T_Check_Buddy !!!
06:00:00 - DMA:310127952,01,REQ:BRDTIM 82 07 83 29 05 0f 04 12 06 00
06:00:00 -
06:00:00 - EvmTbl............
06:00:00 - Maintenancing & Filling VboxTbl...DONE
06:00:01 - DMA:310128070,01,IND:KTSPER 96 10 85 fc 00 28 58
06:00:01 - DMA:310128071,01,REQ:KTSIDK 82 10 85 fc 81 00 47 02
06:00:01 - DMA:310128091,01,IND:KTSPER 96 10 86 fc 00 28 58
06:00:01 - DMA:310128091,01,REQ:KTSIDK 82 10 86 fc 81 00 47 02
06:00:02 - SIP:310129384, REQ: KINFO To:1800 To-Host:192.168.178.230 Ktext: 02 78 0e
06:00:30 - [0x1010001]06:00:30 - (23371) T_Check_Buddy !!!
06:00:32 - SIP:310159385, REQ: KINFO To:1800 To-Host:192.168.178.230 Ktext: 02 78 0e
06:00:46 - IPT:310173571,255,IND: CONFIG 87 03 4c 43 4e
The code is as follows:
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <fstream>
#include <iostream>
#include <string>
#include <sstream>
#include<QFile>
#include<QTextStream>
#include<QStringList>
#include<QDebug>
#include<QMessageBox>
using namespace std;
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
}
MainWindow::~MainWindow()
{
delete ui;
}
I performed button and lineedits in form.After, I splitted time ranges hh:mm:ss format.Because I have to do error checking on time ranges.
void MainWindow::on_pushButton_3_clicked()
{
QString output;
QString line;
QStringList splitted;
QString times;
int sayac1=0,sayac2=0;
bool control1=false;
bool control2=false;
QString firsttime=ui->lineEdit->text(); //first time range that entered
by user.
QStringList list1=firsttime.split(":"); //Girilen time split edildi.
if (list1.size() < 3)
QMessageBox::warning(this,"LIST","ALANLAR BOŞ BIRAKILAMAZ!");
QString hour1=list1[0];
hour1.toInt();
QString minute1=list1[1];
minute1.toInt();
QString second1=list1[2];
second1.toInt();
QString secondtime=ui->lineEdit_2->text(); //second time range that
entered by user.
QStringList list2=secondtime.split(":"); //Girilen aralık split
edildi.
if(list2.size() < 3)
QMessageBox::warning(this,"LIST","ALANLAR BOŞ BIRAKILAMAZ!");
QString hour2=list2[0];
hour2.toInt();
QString minute2=list2[1];
minute2.toInt();
QString second2=list2[2];
second2.toInt();
I read text file and splitted file.I have to need compare time ranges in text file with time ranges that entered by user.
QFile file("C:\\kaynak\\naile.txt");
if(file.open(QIODevice::ReadOnly | QIODevice::Text)){
QTextStream in(&file);
while(!in.atEnd())
{
line = in.readLine()+"\n";
output.append(line);
if(line.contains(" - ")){
splitted=line.split(" - ");
times=times+" "+splitted[0];
}
if(splitted[0]!=firsttime && control1==false){
sayac1 = sayac1+1;
}
else
control1=true;
if(splitted[0]!=secondtime && control2==false){
sayac2++;
}
else
control2=true;
}
In following code,I did error checking as I mentioned above.And,I tried display records at specified time intervals.But when I run the code,nothing seems in textbrowser that I created to display records.I don't understand why this is happening.Also,no error occurs.For example,user entered 05:59:57 to first lineedit and 06:00:46 to second lineedit.Then user clicked button to display records at this time intervals.I want to display records from 05:59:57 to 06:00:46.But,there are no records in textbrowser.Nothing seems.HOW CAN I SOLVE THIS PROBLEM?
if(hour1<=hour2){
int i;
QString list;
QString newline=splitted[0]+" - "+splitted[1];
list.append(newline);
if(times.contains(firsttime) && times.contains(secondtime)){
for(i=sayac1+1;i<=sayac2+1;i++){
ui->textBrowser_3->setText(list.at(i));
}
}
else
QMessageBox::warning(this,"LIST","GİRDİĞİNİZ ZAMAN ARALIKLARI
EŞLEŞMİYOR!");
}
if(hour1>hour2)
QMessageBox::warning(this,"LIST","İKİNCİ SAAT BİRİNCİDEN BÜYÜK
OLAMAZ!");
file.close();
// return output;
}
}
A:
To compare times we must use the QTime class, this class provides implements the time comparison operators. Along with this it is advisable to use QTimeEdit which provides a suitable widget for these parameters so I recommend you to change them instead of using QLineEdit.
An appropriate format has to be established, for this the following is done:
#define FORMAT "hh:mm:ss"
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
ui->fromTimeEdit->setDisplayFormat(FORMAT);
ui->toTimeEdit->setDisplayFormat(FORMAT);
ui->toTimeEdit->setTime(QTime::fromString("23:59:59", FORMAT));
}
Then in the slot that is called when you press the button we do the task of filtering for it we get the times, we do some checks if the limits are adequate. After we read the file and we get the first 8 characters we convert it in time and if it is valid and it is between the times we change the flag, if instead it is not valid we leave it as it was, all of the above was implemented in the following code:
void MainWindow::on_pushButton_clicked()
{
const QTime from = ui->fromTimeEdit->time();
const QTime to = ui->toTimeEdit->time();
bool copyLog = false;
if(from <= to){
QFile file("/path/of/kaynak.log");
ui->textEdit->clear();
if(file.open(QIODevice::ReadOnly | QIODevice::Text)){
QTextStream in(&file);
while(!in.atEnd()){
const QString line = in.readLine();
const QTime timeLog = QTime::fromString(line.left(8), FORMAT);
if(timeLog.isValid()){
copyLog = timeLog >= from && timeLog <= to;
}
if(copyLog){
ui->textEdit->append(line);
QApplication::processEvents();
}
}
}
}
}
The following image shows the result:
The complete example can be found in the following link
| {
"pile_set_name": "StackExchange"
} |
Q:
Fitting an exponential function
Could someone please help me with this exercise and tell me if I am on the right track?
Assume that based on a data set with a large number of observations of an independent variable $x$ and a dependent variable $y$ we have
estimated the coefficients $\alpha$ and $\beta$ in $\ln(y) = \alpha + \beta \cdot x$.
Compute the predicted change in $y$ (denoted $\Delta y$) that results from increasing $x$ by $\Delta x$ (from $x$ to $x + \Delta x$).
I thought maybe to put $e$ in the equation.
$e(\ln(y))=e^\alpha + \beta (x+\Delta x)$
so $e(\ln)$ cancel and I have $y=e^\alpha + \beta(x+\Delta x)$ where I have substituted $x+\Delta x$
into $x$.
Would this equation show the change in $y$?
When is $\Delta y$ positive/negative/zero?
If it is an exponential function, then it just approaches zero no?
Help appreciated! Thank you!
A:
For
$$
\ln(y) = \alpha + \beta \cdot x
$$
We get
$$
\frac{d \ln(y)}{dx} = \frac{1}{y} \frac{dy}{dx} = \beta
$$
and notice
$$
\Delta y \approx \frac{dy}{dx}\Delta x = \beta \, y \, \Delta x
$$
| {
"pile_set_name": "StackExchange"
} |
Q:
Annotation-specified bean name conflicts with existing, non-compatible bean def
I'm having a problem with some Spring bean definitions. I have a couple of context xml files that are being loaded by my main() method, and both of them contain almost exclusively a tag. When my main method starts up, I get this error from Spring:
Caused by: org.springframework.context.annotation.ConflictingBeanDefinitionException: Annotation-specified bean name 'converterDAO' for bean class [my.package.InMemoryConverterDaoImpl] conflicts with existing, non-compatible bean definition of same name and class [my.other.package.StaticConverterDAOImpl]
Both DAO classes are annotated this way:
@Repository("converterDAO")
public class StaticConverterDAOImpl implements ConverterDAO {
...
}
The in-memory dao also has the @Repository("converterDAO") annotation. The dao is referenced in other classes like this:
...
private @Autowired @Qualifier("converterDAO") ConverterDAO converterDAO;
...
I want one DAO to override the definition of the other one, which as I always understood it was one of the principal reasons to use a DI framework in the first place. I've been doing this with xml definitions for years and never had any problems. But not so with component scans and annotated bean definitions? And what does Spring mean when it says they are not "compatible"? They implement the same interface, and they are autowired into fields that are of that interface type. Why the heck are they not compatible?
Can someone provide me with a way for one annotated, component-scanned bean to override another?
-Mike
A:
In an XML file, there is a sequence of declarations, and you may override a previous definition with a newer one. When you use annotations, there is no notion of before or after. All the beans are at the same level. You defined two beans with the same name, and Spring doesn't know which one it should choose.
Give them a different name (staticConverterDAO, inMemoryConverterDAO for example), create an alias in the Spring XML file (theConverterDAO for example), and use this alias when injecting the converter:
@Autowired @Qualifier("theConverterDAO")
A:
I had a similar problem, with two jar libraries (app1 and app2) in one project. The bean "BeanName" is defined in app1 and is extended in app2 and the bean redefined with the same name.
In app1:
package com.foo.app1.pkg1;
@Component("BeanName")
public class Class1 { ... }
In app2:
package com.foo.app2.pkg2;
@Component("BeanName")
public class Class2 extends Class1 { ... }
This causes the ConflictingBeanDefinitionException exception in the loading of the applicationContext due to the same component bean name.
To solve this problem, in the Spring configuration file applicationContext.xml:
<context:component-scan base-package="com.foo.app2.pkg2"/>
<context:component-scan base-package="com.foo.app1.pkg1">
<context:exclude-filter type="assignable" expression="com.foo.app1.pkg1.Class1"/>
</context:component-scan>
So the Class1 is excluded to be automatically component-scanned and assigned to a bean, avoiding the name conflict.
A:
I had a similar issue with Spring 4.x using @RestController. Two different packages had a class with the same name...
package com.x.catalog
@RestController
public class TextureController {
...
package com.x.cms
@RestController
public class TextureController {
...
The fix was easy...
package com.x.catalog
@RestController("CatalogTextureController")
public class TextureController {
...
package com.x.cms
@RestController("CMSTextureController")
public class TextureController {
...
The problem seems to be that the annotation gets autowired and takes the class name by default. Giving it an explicit name in the @RestController annotation allows you to keep the class names.
| {
"pile_set_name": "StackExchange"
} |
Q:
Why are options contracts traded speculatively when investors could just trade the underlying asset?
I'm currently trying to understand why anyone would trade options contracts speculatively. So far I've found 3 possible reasons:
Because the underlying asset cannot be traded directly (i.e. you can't directly trade wheat without taking physical delivery).
To leverage their position
"Options may be used conservatively to create a position with the same profit potential as the underlying asset, but with less risk of loss"
With regards to the first of these points, I can understand that in a minority of cases, this may be a valid point. However, you still hear of people trading futures on stocks, currencies and tradable assets.
The second of these points does not explain the practice either, as most brokers offer customers the ability to leverage their positions when trading an asset directly.
The third point is something I have read online, and I assume that it must be false, since it would otherwise contradict the no arbitrage principle.
So what reason is their to trade options contracts speculatively (rather than just trading the underlying asset directly), presuming that there is a market for the asset.
A:
You are confining your perspective to just the delta or directional bets on equities. There are other bets that are embedded in options besides delta. The most obvious is the bet on volatility. Being long options will allow investors to take a view that the volatility of the stock will be greater than where this is trading currently.
There are two ways to benefit from an increase in volatility--(1) the actual volatility (gamma) increases above the price (implied volatility) and/or (2) the price of volatility goes up (implied volatility increases). And example can be found here: What really is Gamma scalping?. Relatedly, there may be some skew benefit to being long the options--in equities, this tends to be on the downside on stocks.
Others might prefer to sell volatility (implied volatility) and extract the "volatility premium" as an additional source of potential income and extract the theta. Implied in this is the roll down if there is a upward slope to the term structure of volatility.
And yet still others are benefiting from using options in other hedged strategies.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to make soft popsicles
Frozen juice or frozen punch freeze up as a solid block of ice. I want them to be more like a sorbet or gelato, though still solid enough to hold the shape.
How might I make them softer? Either aerated, or polycrystalline without having to "do anything" while it's in the freezer?
One thought is to somehow make it more syrupy so it will hold air long enough to stay there while freezing. Gelatin comes to mind, but I wonder if something better is advised?
A:
The main factors are a gelling agent, alcohol, sugar and air/stirring.
Sugars may decrease the freezig point - add enough sugar and your ice remains soft-ish. Unfortunately this can mean your ice gets too sweet. So instead of using plain sugar, add some "inverted sugar": glucose syrup (aka corn syrup), which stays runny and doesn't crystalize.
You could even take it up a notch and use trehalose, which is basically two linked glucose molecules. It is used in ice-cream making to inhibit the formation of ice crystals. It tastes also less sweet than regular sugar, allowing for less sweet ice cream. Find an award-winning sample recipe here (further down). And if you really must have some hard science, a study on the use of trehalose in ice cream.
Alcohol has a low freezing point. But apart from the question whether you want to use it at all, you should note that you need a certain amount of ethanol to have a noticeable effect - high-proof alcohol and yes, you will taste it.
Glycerine (a sugar alcohol) helps keep ice cream soft.
Likewise the addition of gelling agents may inhibit the formation of ice crystals - locust bean gum is often used to replace eggs in custard-based ice cream and agar agar and pectin may serve a simmilar purpose.
And finally you can mechanically avoid / hinder the formation of large ice crystals by churning your juice first and freezing the slush instead of pouring the juice straight in the molds. The ice will still be rather hard, but not as much of a "solid icicle", especially if combined with one of the additives above.
A:
I love to make popsicles out of store bought yogurt. They stay creamy and are delicious in any yogurt flavor.
| {
"pile_set_name": "StackExchange"
} |
Q:
What is the strategy for detecting time drift in a linux based data centre?
What is the strategy for detecting time drift in all linux based data centre? This is a more difficult problem than it seems at first.
Time drift can cause serious problems for certain applications and often, even though NTP is installed, it's possible to fail for the following (and many more) reasons:
NTP was not correctly set up to automatically restart on reboot.
The settings on a server are incorrect so the time server it points to is unreachable or inaccurate.
The master time server is unreachable and all servers are syncing with it are now syncing to an unreliable source.
I would like a way to detect if all the individual servers are correct. Bear in mind that the server with the testing script/application may not be right.
A:
This is easy to control. Configuration management is the key...
Ensure that the ntp service is running and configured...
For example, using Monit to make sure ntpd is running and to restart it if it fails is an easy approach... It may make sense to add cron and other essential daemons to that sort of check.
Another option is using a configuration management tool like Puppet to force the same ntpd.conf to your servers and ensure that ntpd is installed, configured and running.
There are enough redundancies in the NTP protocol to deal with the instance of a time server being unreachable. Specify multiple sources.
A:
There are a variety of check_ntp plugins for nagios out there.
Here's one:
http://nagiosplugins.org/man/check_ntp
Add this check to your nagios host and get alerts if anything goes awry.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to create SQL statement for the following result?
I have a table with following contents -
I am trying to create 4 columns out of this called as follows -
Risk
Risk_Count
Revenue
Revenue_Count
The following SQL query gets me the desired 4 columns but it also produces NULL values.
select CASE when "BUCKET"='High Revenue' OR "BUCKET"='Low Revenue' OR "BUCKET"='Medium Revenue' then BUCKET end as Revenue,
CASE when "BUCKET"='High Revenue' OR "BUCKET"='Low Revenue' OR "BUCKET"='Medium Revenue' then CUSTOMER_COUNT end as Revenue_count,
CASE when "BUCKET"='High Risk' OR "BUCKET"='Low Risk' OR "BUCKET"='Medium Risk' then BUCKET end as Risk,
CASE when "BUCKET"='High Risk' OR "BUCKET"='Low Risk' OR "BUCKET"='Medium Risk' then CUSTOMER_COUNT end as Risk_count
FROM "TABLE_NAME"
Result -
How to remove the NULL values and have the results in one row so ideally the output should contain 3 rows with 4 columns.
Regards
A:
You want SUM() or MAX():
select MAX(CASE when "BUCKET"='High Revenue' OR "BUCKET"='Low Revenue' OR "BUCKET"='Medium Revenue' then BUCKET end) as Revenue,
MAX(CASE when "BUCKET"='High Revenue' OR "BUCKET"='Low Revenue' OR "BUCKET"='Medium Revenue' then CUSTOMER_COUNT end) as Revenue_count,
MAX(CASE when "BUCKET"='High Risk' OR "BUCKET"='Low Risk' OR "BUCKET"='Medium Risk' then BUCKET end) as Risk,
MAX(CASE when "BUCKET"='High Risk' OR "BUCKET"='Low Risk' OR "BUCKET"='Medium Risk') then CUSTOMER_COUNT end as Risk_count
FROM "TABLE_NAME"
Then you can simplify the logic using IN or LIKE:
select max(case when "BUCKET" in ('High Revenue', 'Low Revenue', 'Medium Revenue') then BUCKET end) as Revenue,
max(case when "BUCKET" in ('High Revenue', 'Low Revenue', 'Medium Revenue') then CUSTOMER_COUNT end) as Revenue_count,
max(case when "BUCKET" in ('High Risk', 'Low Risk', 'Medium Risk') then BUCKET end) as Risk,
max(case when "BUCKET" in ('High Risk', 'Low Risk', 'Medium Risk') then CUSTOMER_COUNT end as Risk_count
FROM "TABLE_NAME";
I would also advise you to get rid of the double quotes around the identifiers. Only quote identifiers when you really have to -- and then choose identifiers (such as the ones you have) that do not need to be quoted.
EDIT:
I think you want:
select max(case when bucket like '%Revenue' then BUCKET end) as Revenue,
max(case when bucket like '%Revenue' then CUSTOMER_COUNT end) as Revenue_count,
max(case when bucket like '%Risk' then BUCKET end) as Risk,
max(case when bucket like '%Risk' then CUSTOMER_COUNT end) as Risk_count
FROM "TABLE_NAME"
GROUP BY LEFT(bucket, 3) -- sufficient to distinct high/medium/low
| {
"pile_set_name": "StackExchange"
} |
Q:
Base and derived class in one header
I want to put two clasess in one header file. The one is a base class and the second is derived form this base class, what I mean is something like this:
class Drawable{
public:
Drawable();
void setPosition(math::Vector3 position);
void draw();
};
class Box: public Drawable{} ;
But I get error "undefined reference to `Drawable::Drawable()' ". In source file I have:
class Drawable {
public:
math::Vector3 position;
math::Vector3 rotation;
Drawable() {
position = math::Vector3(1.0, 1.0, 1.0);
rotation = math::Vector3(0.0, 0.0, 0.0);
}
void setPosition(math::Vector3 position) {
this->position = position;
}
void draw() {
}
};
class Box: public Drawable {
public:
void draw() {
glBegin(GL_TRIANGLES);
drawPoint(this->position + math::Vector3(1.0f, 1.0f, 1.0f));
drawPoint(this->position + math::Vector3(-1.0f, 1.0f, 1.0f));
drawPoint(this->position + math::Vector3(-1.0f, 1.0f, 1.0f));
drawPoint(this->position + math::Vector3(1.0f, 1.0f, 1.0f));
drawPoint(this->position + math::Vector3(1.0f, 1.0f, -1.0f));
drawPoint(this->position + math::Vector3(1.0f, -1.0f, 1.0f));
glEnd();
}
};
So it seems to me impossible to accomplish this because the derivated class in header not already knows about the constructor of the base class. Am I right?
A:
You need to do something like this:
example.h
class Drawable
{
public:
Drawable();
void setPosition(math::Vector3 position);
virtual void draw();
math::Vector3 position;
math::Vector3 rotation;
};
class Box: public Drawable
{
public:
virtual void draw();
};
example.cpp
#include "example.h"
Drawable::Drawable() {
position = math::Vector3(1.0, 1.0, 1.0);
rotation = math::Vector3(0.0, 0.0, 0.0);
}
void Drawable::setPosition(math::Vector3 position) {
this->position = position;
}
void Drawable::draw() {
}
void Box::draw() {
glBegin(GL_TRIANGLES);
drawPoint(this->position + math::Vector3(1.0f, 1.0f, 1.0f));
drawPoint(this->position + math::Vector3(-1.0f, 1.0f, 1.0f));
drawPoint(this->position + math::Vector3(-1.0f, 1.0f, 1.0f));
drawPoint(this->position + math::Vector3(1.0f, 1.0f, 1.0f));
drawPoint(this->position + math::Vector3(1.0f, 1.0f, -1.0f));
drawPoint(this->position + math::Vector3(1.0f, -1.0f, 1.0f));
glEnd();
}
Header defines:
Constructor/Destructor signatures
Member variables
Member function signatures
Source defines
Constructor/Destructor implementation
Member function implementation
Note: Use a scope resolution operator :: to refer to the class members.
| {
"pile_set_name": "StackExchange"
} |
Q:
how to get last three filename of user from mysql server in android
this is my code. i want to get the last three file sent by user on mysql server,i am getting the all file of user by this code but i want to get last three file.on server side id is autoincremented so every time user gets new id ,i had ialso tried to get the largest three id of user by this i can get the file of user but that was unsucessfull.
public class ABC extends AsyncTask<String,String,String> {
@Override
protected String doInBackground(String... params) {
// Date d = new Date();
// Log.e("dip",""+d);
CharSequence s = DateFormat.format("MMMM d, yyyy ", d.getTime());
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost("http://www.synergyb.com/dev/abcd.php");
HttpResponse httpResponse = null;
try {
httpResponse = httpClient.execute(httpPost);
} catch (IOException e) {
e.printStackTrace();
}
HttpEntity httpEntity = httpResponse.getEntity();
try {
is = httpEntity.getContent();
} catch (IOException e) {
e.printStackTrace();
}
BufferedReader br = null;
try {
br = new BufferedReader(new InputStreamReader(is, "ISO-8859-1"), 8);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
StringBuilder sb = new StringBuilder();
String ab = null;
try {
while ((ab = br.readLine()) != null) {
sb.append(ab + "\n");
data = sb.toString();
}
} catch (IOException e) {
e.printStackTrace();
}
Log.e("data", data);
try {
JSONArray jsonArray1 = new JSONArray(data);
for (int i = 0; i <= jsonArray1.length(); i++) {
JSONObject jsonObject = jsonArray1.getJSONObject(i);
username = jsonObject.getString("username");
dat = jsonObject.getString("Date");
Log.e("date", dat);
String dattt = s.toString();
if (username.matches(str5)) {
if (id ==8 && id ==18) {
// List<Integer> list = new ArrayList<>();
//
// list.add(id);
//
// Collections.sort(list);
// list.get(list.size() - 1);
//
//// Integer data = list.get(1);
// Log.e("dd",""+list);
// System.out.println(list.get(list.size()-2));
// if (id==list.get(list.size()-2))
filename = jsonObject.getString("filename");
Model m = new Model(filename);
l.add(m);
Log.e("filename", filename);
}
}
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
CustomAdapter adapter= new CustomAdapter(History.this, R.layout.activity_main, l);
lv.setAdapter(adapter);
}
A:
i got the answer edit the server side php code will solve the issues...
<?php
$con=mysql_connect('localhost','username','password');
mysql_select_db("database namet",$con);
$username = $_POST['username'];
$result = mysql_query("SELECT * FROM details where username='$username' ORDER BY id DESC LIMIT 3");
while($row = mysql_fetch_assoc($result))
{ $output[]=$row;
}
print(json_encode($output));
mysql_close($con);
?>
| {
"pile_set_name": "StackExchange"
} |
Q:
Javascript Window object Cross-Domain accessible properties
So I realize that with two windows of different domains, there is very little information that can exchanged. Withholding of course using postMessage or similar methods, what specific properties can two windows of different domains acquire?
For one simple example, if I open a child popup of a different domain, I know that the parent has access to the closed property of the child. Is there a list of other accessible properties?
A:
Here's the spec : https://html.spec.whatwg.org/multipage/browsers.html#cross-origin-objects.
Firefox does the following : https://developer.mozilla.org/en-US/docs/Web/Security/Same-origin_policy
| {
"pile_set_name": "StackExchange"
} |
Q:
Mysql recursive substracting and multiplying grouped values
Couldn't really explain my problem with words, but with an example I can show it clearly:
I have a table like this:
id num val flag
0 3 10 1
1 5 12 2
2 7 12 1
3 11 15 2
And I want to go through all the rows, and calculate the increase of the "num", and multiply that difference with the "val" value. And when I calculated all of these, I want to add these results together, but grouped based on the "flag" values.
This is the mathematical equation, that I want to run on the table:
Result_1 = (3-0)*10 + (7-3)*12
Result_2 = (5-0)*12 + (11-5)*15
78 = Result_1
150 = Result_2
Thank you.
A:
Interesting question. Unfortunately MYSQL doesn't support recursive queries, so you'll need to be a little creative here. Something like this could work:
select flag,
sum(calc)
from (
select flag,
(num-if(@prevflag=flag,@prevnum,0))*val calc,
@prevnum:=num prevnum,
@prevflag:=flag prevflag
from yourtable
join (select @prevnum := 0, @prevflag := 0) t
order by flag
) t
group by flag
SQL Fiddle Demo
| {
"pile_set_name": "StackExchange"
} |
Q:
SP that returns all or filtered data
I have a stored procedure (below) that returns the entire table. I am trying to make it so it will return the entire table OR return a certain date range in one Proc. Is this possible or do I need two procs for this? Thanks!
ALTER PROCEDURE [dbo].[GetLeads]
AS
SELECT name
, lastname
, title
, company
, address
, address2
, city
, [state]
, zip
, country
FROM
lead
A:
ALTER PROCEDURE [dbo].[GetLeads]
@LastNameSearch varchar(100) = null
AS
SELECT name
, lastname
, title
, company
, address
, address2
, city
, [state]
, zip
, country
FROM
lead
where
((@LastNameSearch is null) or (lastname = @LastNameSearch))
The above will result in a stored procedure that if you don't pass a parameter value to it, it'll return all of the data. If you do pass a parameter value, it'll only return rows where lastname = @LastNameSearch.
| {
"pile_set_name": "StackExchange"
} |
Q:
custom css being overridden by bootstrap css
I am using Bootstrap 3 and I have a table showing some data. in this table I have applied some javascript for conditional formatting, in the event that a condition is met, I set the element's class to "red"
.red {
background-color:red;
color:white;
}
the elements HTML is as follows:
<td class="red">0</td>
I now have a conflict on odd rows the text color applies but the background color is overridden by the following css from bootstrap.
.table-striped > tbody > tr:nth-child(odd) > td,
.table-striped > tbody > tr:nth-child(odd) > th {
background-color: #f9f9f9;
}
how can I resolve this conflict and assure that the red class takes presedence?
A:
Specificity
Your issue is most likely regarding specificity. Chris Coyier has a great article on CSS specificity. I would also suggest you check out this handy specificity calculator.
Using that calculator, we can see that .table-striped > tbody > tr:nth-child(odd) > td has a specificity of 23. As such, to override that, any new rule needs to have a specificity of something equal to or greater than 23. .red is at 10, so that isn't going to cut it.
In this case, it should be as simple as matching the existing specificity, and then adding your class to it. .table-striped > tbody > tr:nth-child(odd) > td.red gives us a specificity of 33. As 33 is greater than 23, your rule should now work.
See a working example here: http://bootply.com/91756
!important
In general, you should never use !important unless you never want that rule to be overridden. !important is basically the nuclear option. I am moderately confident in saying that if you understand specificity, you should never need to !important to make a custom rule work properly in a framework like Bootstrap.
Update
After a bit of thought, the rule I provide here is probably a bit too specific. What happens if you want to higlight a cell on a table that isn't stripped? To make your rule a bit more global while still having enough specificity to work in stripped tables, I would go with .table > tbody > tr > td.red. This has the same specificity as the Bootstrap stripping, but will also work on tables that are not zebra stripped. Updated example is here: http://bootply.com/91760
A:
Firstly, read Sean Ryan's answer - it is very good and informative, but I had to tweak his answer enough before implementing in my code that I wanted have a distinct answer that might help the next person.
I had almost the same question as the OP but also needed to be able to highlight the row, too. Below is how I enhanced(?) Sean Ryan's answer and turned it into my final implementation, which allows you to add a class to most any random element, including to a "tr" or a "td"
See this on bootply.com
CSS
/* enable 'highlight' to be applied to most anything, including <tr> & <td>, including bootstrap's aggressive 'table-stripe'
see: http://stackoverflow.com/questions/19768794/custom-css-being-overridden-by-bootstrap-css
FYI: In the stack overflow question, the class is 'red' instead of 'highlight'
FYI: This is forked from http://www.bootply.com/91756
I used three different colors here for illustration, but we'd
likely want them to all be the same color.
*/
.highlight {
background-color: lightyellow;
}
/* supersede bootstrap at the row level by being annoyingly specific
*/
.table-striped > tbody > tr:nth-child(odd).highlight > td {
background-color: pink;
}
/* supersede bootstrap at the cell level by being annoyingly specific */
.table-striped > tbody > tr:nth-child(odd) > td.highlight {
background-color:lightgreen;
}
HTML
<table class="table table-striped">
<thead>
<tr>
<th>Col 1</th>
<th>Col 2</th>
<th>Col 3</th>
</tr>
</thead>
<tbody>
<tr>
<td>1hi</td>
<td>hi</td>
<td>hi</td>
</tr>
<tr class="highlight">
<td>2hi</td>
<td>This row highlights fine since it was an even row to begin with, and therefore not highlighted by bootstrap</td>
<td>hi</td>
</tr>
<tr class="highlight">
<td>3hi</td>
<td>This whole row should be highlighted.</td>
<td>hi</td>
</tr>
<tr>
<td>4hi</td>
<td>hi</td>
<td>hi</td>
</tr><tr>
<td>5hi</td>
<td class="highlight">Just a specific cell to be highlighted</td>
<td>hi</td>
</tr>
</tbody>
</table>
| {
"pile_set_name": "StackExchange"
} |
Q:
Determining that the given integer is greater than all roots of given polynomial
Given the integer $k$ and the polynomial $p(x)$ with all real roots and integer coefficients, how can I determine that $k$ is greater than all roots of $p(x)$, without calculating the exact values of its roots? For example, $k=6$ is greater than all roots of polynomial $p(x)=x^2-2x-8$, whose roots are -2 and 4.
(This is a part of some algorithm problem.)
Edit I missed one condition: $p(x)$ has exactly $n$ distinct real roots where $n$ is the degree of $p(x)$.
A:
For the given example, let $\,x = t+6\,$ then $\,q(t)=p(x-6)=t^3 + 18 t^2 + 106 t + 196\,$. It follows by Descartes' rule of signs that $\,q(t)\,$ has no positive roots, therefore $\,p(x)\,$ has no root larger than $6$.
In general, the location of the real roots can be algorithmically determined using Sturm sequences.
| {
"pile_set_name": "StackExchange"
} |
Q:
Loop over start date and end date through strtotime not working PHP
I've an array like this:
Array
(
[0] => Array
(
[start_date] => 2010-09-16
)
[1] => Array
(
[end_date] => 2010-10-16
)
[2] => Array
(
[start_date] => 2011-12-24
)
[3] => Array
(
[end_date] => 2012-01-23
)
[4] => Array
(
[start_date] => 2012-11-10
)
[5] => Array
(
[end_date] => 2012-12-10
)
[6] => Array
(
[start_date] => 2013-05-14
)
[7] => Array
(
[end_date] => 2013-06-13
)
[8] => Array
(
[start_date] => 2014-10-20
)
[9] => Array
(
[end_date] => 2014-11-19
)
);
I've written following foreach loop to iterate over an array and in foreach loop I want to get date between start date and end date by using while loop through strtotime (Referencing this article)
foreach ($dateArray as $key => $data) {
$start_date = $dateArray[$key]['start_date'];
$end_date = $dateArray[$key]['end_date'];
while (strtotime($start_date) <= strtotime($end_date)) {
echo "$start_date\n";
$start_date = date("Y-m-d", strtotime("+1 day", strtotime($start_date)));
}
}
But its taking lot of time to loading the page and showing wrong output something like:
1970-01-02
1970-01-03
1970-01-04
1970-01-05
1970-01-06
1970-01-07
.
.
.
and so on...
But if I'm passing hard code value to it like:
foreach ($dateArray as $key => $data) {
$start_date = $dateArray[$key]['start_date'];
$end_date = $dateArray[$key]['end_date'];
while (strtotime('2009-12-06') <= strtotime('2020-12-31')) {
echo "$start_date\n";
$start_date = date("Y-m-d", strtotime("+1 day", strtotime($start_date)));
}
}
Then its working fine and showing proper result.
Any help would be appreciated.
A:
$array = array_chunk($dateArray,2);
foreach ($array as $key => $data) {
$start_date = data[0]['start_date'];
$end_date =data[1]['end_date'];
while (strtotime($start_date) <= strtotime($end_date)) {
echo "$start_date\n";
$start_date = date("Y-m-d", strtotime("+1 day", strtotime($start_date)));
}
}
| {
"pile_set_name": "StackExchange"
} |
Q:
REPLACE in mysql can't work with free space. how to rename free space?
text to replace
Probijalniki/Ĺ karje za pločevino
i want to use REPLACE in mysql
UPDATE pages SET title = REPLACE(title, 'Ĺ ', 'Š');
but i get Affected rows: 0
Why i can not replace 'Ĺ ' with 'Š'. I can replace 'Ĺ' but not with space 'Ĺ '
A:
It should work. But there is one good reason why it wouldn't.
You don't have any 'Ĺ ' in your db. You might have something that LOOKS like a space but isn't.
Create test data and manually type in 'Ĺ ' into the table and run your query. It worked for me.
| {
"pile_set_name": "StackExchange"
} |
Q:
Flutter Dependency Audit
So I have this fully created app that uses a few plugins. When the app is compiled in either iOS or Android I would like to audit and list which external libraries belong to which plugin.
I noticed some undesired libraries on my builds (the specific libraries do not matter) but tracking down which plugin is slow and time consuming (looking at platform code, plugin yaml files etc)
Is there a way to list the external dependencies related to each plugin on the console?
Thanks
A:
In your command line, please run:
flutter pub deps
Output:
Dart SDK 2.7.0
Flutter SDK 1.12.13+hotfix.5
flutter_news 1.0.0+1
|-- build_runner 1.7.2
| |-- args...
| |-- async...
| |-- build 1.2.2
| | |-- analyzer...
| | |-- async...
| | |-- convert...
| | |-- crypto...
| | |-- glob...
| | |-- logging...
| | |-- meta...
| | '-- path...
| |-- build_config 0.4.1+1
| | |-- checked_yaml 1.0.2
| | | |-- json_annotation...
| | | |-- source_span...
| | | '-- yaml...
| | |-- json_annotation...
| | |-- meta...
| | |-- path...
| | |-- pubspec_parse...
| | '-- yaml...
| |-- build_daemon 2.1.2
| | |-- built_collection 4.3.0
| | | |-- collection...
| | | '-- quiver...
| | |-- built_value 7.0.0
| | | |-- built_collection...
| | | |-- collection...
| | | |-- fixnum 0.10.11
| | | '-- quiver...
| | |-- http_multi_server...
| | |-- logging...
...
For platform specific audits, you really have to review each plugin you're adding (at least for the 3rd party ones).
Android: How do I show dependencies tree in Android Studio?
Android: Look for the plugin's android/app/build.gradle file.
iOS: Look for the plugin's ios/Podfile.
More on:
https://dart.dev/tools/pub/cmd/pub-deps
Do you mind sharing your current pubspec.yaml file? So we could further help.
| {
"pile_set_name": "StackExchange"
} |
Q:
Cannot install calcurse on RHEL8
I am unable to install calcurse on RHEL8.1. The error is that the ./configure file in the tarball does not recognize ncurses as installed:
# git clone https://github.com/lfos/calcurse
# cd calcurse
# ./configure
[...]
checking for initscr in -lncursesw... no
checking for initscr in -lncurses... no
configure: error: Either ncurses or ncursesw library is required to build calcurse!
The package ncurses is however installed:
# yum -y install ncurses
[...]
Package ncurses-6.1-7.20180224.el8.x86_64 is already installed.
Dependencies resolved.
Nothing to do.
Complete!
A:
ncurses is the runtime package; to build software with ncurses, you need to install the development package, ncurses-devel.
| {
"pile_set_name": "StackExchange"
} |
Q:
Ending a while loop when it reaches matching numbers
I need to end this while loop when it reaches a matching number such as 88, 77, and so on.
import java.util.Scanner;
public class LabProgram {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int userNum = scan.nextInt();
if ((userNum >= 20) && (userNum <= 98)){
System.out.print(userNum + " ");
while ((userNum != 11) || (userNum != 22) || (userNum != 33) || (userNum != 44) || (userNum != 55) || (userNum != 66) || (userNum != 77) || (userNum != 88) || (userNum != 99)){
userNum = userNum - 1;
System.out.print(userNum + " ");
}
}
else{
System.out.print("Input must be 20-98");
}
System.out.print("\n");
}
}
However, when it runs it never leaves the loop, even when the number reaches one of the matching ones I had in the while loop. please help.
A:
if(userNum != 11) || (userNum != 22) || (userNum != 33) || (userNum != 44) || (userNum != 55) || (userNum != 66) || (userNum != 77) || (userNum != 88) || (userNum != 99)
Will always be true, because userNum cannot be all of those values at once. Substitute || for &&:
if(userNum != 11) && (userNum != 22) && (userNum != 33) && (userNum != 44) && (userNum != 55) && (userNum != 66) && (userNum != 77) && (userNum != 88) && (userNum != 99)
This can be made easier using the modulus operator:
if(userNum % 11 != 0)
| {
"pile_set_name": "StackExchange"
} |
Q:
How to translate i tag of html into rails' link_to helper?
I would like to translate below code into link_to helper. How to do that?
<a href="#"><i class="fa fa-twitter"></i></a>
A:
You can recreate the above link by using link_to's block format, like so:
<%= link_to "#" do %>
<i class="fa fa-twitter"></i>
<% end %>
Hope it helps!
| {
"pile_set_name": "StackExchange"
} |
Q:
Changing file locations in Python shell?
When using the python shell, how can I change to lets say, C:\etc.? I have a batch file that changes to the shell, and I want a way to change it back.
A:
The Python interpreter has a file path pointing to the location where Python is installed unless you launch it from another location (i.e. from terminal/batch-file/file explorer/application) then it will take the location of that instead. If you want to go to a file location you must program it.
The os module can do what you want. It provides extensive file/folder manipulation including changing dictionary using os.chdir(). Both full paths and relative paths are supported.
For example:
>>>import os
>>>os.getcwd()
'C:\\Users\\Username\\AppData\\Local\\Programs\\Python\\Python36-32'
>>>os.chdir('C:/ect')
>>>os.getcwd()
'C:\\ect'
You can delete and rename files using this module as well.
| {
"pile_set_name": "StackExchange"
} |
Q:
Find and replace consecutive string values in a list
Suppose I have a list that holds a list of column names:
columns = [
'Village Trustee V Belleville', 'Unnamed: 74', 'Unnamed: 75',
'Village President V Black Earth', 'Village Trustee V Black Earth',
'Unnamed: 78', 'Unnamed: 79', 'Village President V Blue Mounds',
'Village Trustee V Blue Mounds', 'Unnamed: 82',
'Village Trustee V Cottage Grove', 'Unnamed: 94', 'Unnamed: 95',
'Village President V Cross Plains', 'Village Trustee V Cross Plains',
'Unnamed: 98', 'Unnamed: 99'
]
And I want to find all Unnamed: XX values and replace them consecutively with the first valid string. For example:
Input:
'Village Trustee V Belleville', 'Unnamed: 74', 'Unnamed: 75'
Output:
'Village Trustee V Belleville', 'Village Trustee V Belleville', 'Village Trustee V Belleville'
For this I have a function:
def rename_unnamed(columns):
current_value = None
pattern = re.compile(r'^Unnamed:\s\d+$')
for column_index, column in enumerate(columns):
if re.match(pattern, column):
columns[column_index] = current_value
else:
current_value = column
return columns
Which does the job pretty fine, however, I was wondering if this could be improved and/or simplified, as this looks like a mouthful for rather a simple task.
A:
Don't mutate input and return.
If I need to pass columns unedited to two different functions, than your function will seem like it's not mutating columns and I wouldn't have to perform a copy of the data. But this isn't the case.
You may want to potentially error if there are no values before the first "Unnamed" value.
You may want to make pattern an argument, to allow reusability of the function. And instead use change it to a callback to allow even more reusability.
Overall your function's pretty good. I don't think it can be made much shorter.
def value_or_previous(iterator, undefined, default=None):
prev_item = default
for item in iterator:
if not undefined(item):
prev_item = item
yield prev_item
def rename_unnamed(columns):
return list(value_or_previous(columns, re.compile(r'^Unnamed:\s\d+$').match))
A:
In case you need to modify the initial columns list (mutable data structure) you don't need to return it.
The crucial pattern can be moved out to the top making it reusable and accessible for other potential routines or inline conditions:
UNNAMED_PAT = re.compile(r'^Unnamed:\s\d+$')
As the function's responsibility is to back fill (backward filling) items matched by specific regex pattern I'd rename it appropriately like say backfill_by_pattern. The search pattern is passed as an argument.
I'll suggest even more concise solution based on replacement of search items by the item at the previous index:
def backfill_by_pattern(columns, pat):
fill_value = None
for i, column in enumerate(columns):
if pat.match(column):
columns[i] = columns[i - 1] if i else fill_value
Sample usage:
backfill_by_pattern(columns, pat=UNNAMED_PAT)
print(columns)
The output:
['Village Trustee V Belleville',
'Village Trustee V Belleville',
'Village Trustee V Belleville',
'Village President V Black Earth',
'Village Trustee V Black Earth',
'Village Trustee V Black Earth',
'Village Trustee V Black Earth',
'Village President V Blue Mounds',
'Village Trustee V Blue Mounds',
'Village Trustee V Blue Mounds',
'Village Trustee V Cottage Grove',
'Village Trustee V Cottage Grove',
'Village Trustee V Cottage Grove',
'Village President V Cross Plains',
'Village Trustee V Cross Plains',
'Village Trustee V Cross Plains',
'Village Trustee V Cross Plains']
| {
"pile_set_name": "StackExchange"
} |
Q:
Match multiple condition on large dataframe in R
I have below mentioned two dataframe:
DF_1
Val1 Val2
COPPAR Ert Metal
Bittar Gourd vegetble
Blackbery d Fruite
DF_2
Val4 Val5 Type
Copper Metal A-I
Bitter Gourd Vegetable B-II
Blackberry Fruit C-III
I have some error in DF_1 in Val1 and Val2 (Where same like string in Val1 and Val2 are different in spelling) and have the correct list in DF_2. Just want to Match Val1 of DF_1 with Val4 of DF_2 and based on the correct value (New_Val1) I want the Val5 in New_Val2 and Type, in the output dataframe.
Output Dataframe:
Val1 Val2 New_Val1 New_Val2 Type
COPPAR Metal Copper Ert Metal A-I
Bittar Gourd vegetble Bitter Gourd Vegetable B-II
Blackbery Fruite Blackberry Fruit C-III
A:
This is base on soundex
library(phonics)
df1['match1']=soundex(df1$Val1)
df1['match2']=soundex(df1$Val2)
df2['match1']=soundex(df2$Val4)
df2['match2']=soundex(df2$Val5)
merge(df1,df2,by=c('match1','match2'))
match1 match2 Val1 Val2 Val4 Val5 Type
1 B360 V231 Bittar Gourd vegetble Bitter Gourd Vegetable B-II
2 B421 F630 Blackbery d Fruite Blackberry Fruit C-III
3 C160 M340 COPPAR Ert Metal Copper Metal A-I
| {
"pile_set_name": "StackExchange"
} |
Q:
How to Change Text Value with jquery
I have list Item with edit link each of them. If I click the Edit link it open a Input filed with SAVE and CANCEL button. If I click cancel it goes back to original view. Upto this it fine.
FIDDLE
But I want when save button is clicked , If I write something in the input field it will save and will replace previous text.
Like I have TEXT 'Cras justo odio' , if I click edit it opens a input field and I write "THIS IS COOL" and press save. Now text 'Cras justo odio' will replace with "THIS IS COOL". How I can do this ?
Thanks in advance.
JS
$(".btn-link").click(function () {
$(this).parent('.view-mode').hide();
$(this).parent('.view-mode').siblings('.edit-mode').show();
});
$(".cancel-edit").click(function () {
$(this).parent('.edit-mode').hide();
$(this).parent('.edit-mode').siblings('.view-mode').show();
});
A:
You have to add:
$(".confirm-edit").click(function () {
var inptext = $(this).siblings('input').val();
$(this).parent('.edit-mode').siblings('.view-mode').children('span').text(inptext);
$(this).parent('.edit-mode').hide();
$(this).parent('.edit-mode').siblings('.view-mode').show();
});
Fiddle: http://jsfiddle.net/has9L9Lh/38/
| {
"pile_set_name": "StackExchange"
} |
Q:
Use derive Insertable for float
I started with diesel and rocket in Rust and have a problem with inserting floating values to the database.
My struct looks like:
#[derive(Serialize, Deserialize, Insertable)]
#[table_name = "database"]
pub struct New_Data{
pub data1: f64,
pub data2: f64,
pub data3: f64,
}
and I get this error: the trait bound f64: diesel::Expression is not satisfied
label: the trait diesel::Expression is not implemented for f64,
note: required because of the requirements on the impl of diesel::expression::AsExpression<diesel::sql_types::Numeric> for f64
I've read that diesel kinda uses its own data/SQL types but I have no idea how to declare a Float.
I also tried to use diesel::sql_types::Float with a similar error message.
A:
This looks like a mismatch between the schema type of the field, as defined in the diesel auto-generated schema.rs, and the type of the field you defined in New_Data. Look inside the auto-generated schema for a data1 -> definition, you may find something like:
data1 -> Float4
In this case the type of the field needs to be f32. Otherwise, if it's Float8, then the type should be f64. This mapping between the language of diesel schema types extends further to Option and Nullable. If it appears as Nullable<Float4> in the schema, then it should be Option<f32> in the type.
| {
"pile_set_name": "StackExchange"
} |
Q:
Who maintains Stack Exchange sites
I am in active participation in Stack Overflow, Meta Stack Overflow and Programmers.SE. It has been a great experience for me to discuss problems in Stack Exchange sites.
I was wondering who are the makers and creators of this community portal? Who is responsible for making rules and regulations, setting guidelines for the community? Is there a special team of board members operating the various stack exchange accounts or these are the top users who are responsible for maintaining these accounts and other regulations?
A:
Thanx @GamecatisToonKrijthe, found the answer.
In 2008, Jeff Atwood and Joel Spolsky created site Stack Overflow
and here is the team who operates stack exchange accounts..
[Stack Exchange Team]
| {
"pile_set_name": "StackExchange"
} |
Q:
Disable Command-W in the terminal
Is there any way to disable Command+W in the terminal?
On several occasions I have accidentally closed a terminal window containing important information when I meant to close a Safari tab and did not realize that the terminal was the active window.
A:
To disable ⌘W in Terminal, do the following:
From the menu in the top left corner of the screen, select System Preferences. Click on Keyboard then Keyboard Shortcuts then Application Shortcuts.
Click the + button to add a new shortcut
Select "Terminal.app" for the application, and for the command, type Close Window (this is case sensitive). In the shortcut box, give it a different shortcut, like ⌘ControlW
Now ⌘W will not close your terminal windows.
A:
You can set a prompt before closing in the preferences:
Terminal Preferences → Settings → Shell
A:
I tried all of the above, and none worked for me.
What worked was changing the shortcut for the "Close" command.
| {
"pile_set_name": "StackExchange"
} |
Q:
IAsyncAction OnCompleted event handler called prematurely
Something weird happening in my application and I cannot comprehend it. I create a background task for network communication using the ThreadPool class. In this task I call some methods asynchronously. The reason is that sometimes synchronous methods are not provided by Microsoft (for example there is not method DatagramSocket.Connect so I must use method DatagramSocket.ConnectAsync). But because I need to call these methods synchronously, I must use keyword "await" and mark the method as "async". When I do this, event handler for background task created in Button_Click event handler start is called prematurely. When the background task really finishes its job (for example by breaking the execution in debugger in manually moving execution pointer to the end of UdpSend method), OnCompleted event handler is not called. Is this normal ? Am I missing something important ?
/// <summary>
/// An empty page that can be used on its own or navigated to within a Frame.
/// </summary>
public sealed partial class MainPage : Page
{
IAsyncAction work;
public MainPage()
{
this.InitializeComponent();
}
private void Button_Click(object sender, RoutedEventArgs e)
{
if (work == null)
{
ButtonStart.Content = "Stop UDP test";
work = ThreadPool.RunAsync(UdpSend);
work.Completed = OnUdpSendFinish;
}
else
{
work.Cancel();
}
}
private async void UdpSend(IAsyncAction work)
{
DatagramSocket socket = new DatagramSocket();
socket.MessageReceived += Socket_MessageReceived;
HostName host_name = new HostName("10.0.0.2");
await socket.ConnectAsync(host_name, "1234");
DataWriter writer = new DataWriter(socket.OutputStream);
uint data = 0;
int payload_size = 512;
int payload_len = payload_size / sizeof(uint);
while (work.Status != AsyncStatus.Canceled)
{
for (int i = 0; i < payload_len; i++)
{
writer.WriteUInt32(data++);
}
await writer.StoreAsync();
}
}
private void Socket_MessageReceived(DatagramSocket sender, DatagramSocketMessageReceivedEventArgs args)
{
throw new System.NotImplementedException();
}
private async void OnUdpSendFinish(IAsyncAction asyncInfo, AsyncStatus asyncStatus)
{
await CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Normal,
() =>
{
ButtonStart.Content = "Start UDP test";
});
work = null;
}
}
A:
That's because of how the await keyword works. It allows you to write all the code in the same method for readability, but in truth the method is split in two. Let's take a simple example:
private async void Example()
{
DoSomething();
await AsyncCall();
DoSomethingElse();
}
After compilation, the method is rewritten to something like (it's much more complicated):
private void Example()
{
DoSomething();
AsyncCall();
}
private void ExampleContinuation()
{
DoSomethingElse();
}
How the method is executed depends on what context it runs on. In your case, since you've used the thread pool, Example is run in the task you created (your IAsyncAction). After AsyncCall, the Example method returns, and so your Completed event is triggered. And only then, the runtime spins a new thread from the threadpool and uses it to run ExampleContinuation.
I workaround could be to use Task.Run instead of directly the threadpool. Task.Run will also use the threadpool under the cover, but with all the plumber y to handle those corner cases:
private Task work;
private void Button_Click(object sender, RoutedEventArgs e)
{
if (work == null)
{
ButtonStart.Content = "Stop UDP test";
work = Task.Run(UdpSend);
work.ContinueWith(_ => OnUdpSendFinish());
}
else
{
work.Cancel();
}
}
Then change the return type of your "UdpSend" method (it should have no incidence on the contents of the method, but it indicates the task that your call should be awaited):
private async Task UdpSend(IAsyncAction work)
Lastly, change the signature of your Completed handler:
private async void OnUdpSendFinish()
And you're done ;)
| {
"pile_set_name": "StackExchange"
} |
Q:
Getting external IP using Adobe AIR
We can get external IP from this service using Java, C# or VB.NET. But I want to do that using Adobe AIR. How to make request to that link and get its string?
A:
It will be like this:
private function makeRequest():void
{
var loader:URLLoader = new URLLoader();
configureListeners(loader);
var req:URLRequest=new URLRequest("http://www.whatismyip.com/automation/n09230945.asp");
try
{
var header:URLRequestHeader=new URLRequestHeader("content-type", "text/plain");
var header2:URLRequestHeader = new URLRequestHeader("pragma", "no-cache");
req.requestHeaders.push(header);
req.requestHeaders.push(header2);
req.method = URLRequestMethod.POST;
loader.dataFormat = URLLoaderDataFormat.TEXT;
loader.load(req);
}
catch (error:Error)
{
trace("Unable to load requested document.");
}
}
private function configureListeners(dispatcher:IEventDispatcher):void
{
dispatcher.addEventListener(Event.COMPLETE, completeHandler);
}
private function completeHandler(event:Event):void
{
var loader:URLLoader = URLLoader(event.target);
mx.controls.Alert.show("" + loader.data);
}
| {
"pile_set_name": "StackExchange"
} |
Q:
jquery selector for start with but only certain length/level children?
<div id='1'></div>
<div id='1_1'></div>
<div id='1_1_1'></div>
<div id='1_1_2'></div>
<div id='1_2'></div>
<div id='2'></div>
<div id='2_1'></div>
<div id='2_2'></div>
<div id='2_2_1'></div>
Given this (psuedo) set of tags, I would like to be able to get all of the "level below" tags.
e.g.
id=1 gets 1_1 and 1_2, but not 1_1_1 etc.
id=2_2 gets 2_2_1 etc
I have tried the div[id^=1] but this returns all levels below.
Note, these are NOT nested tags, so Children doesn't work :(
How can I restrict to just id_?
e.g. div[id=1_1_?]
Is there a single character wildcard, or a way of restricting the length of the selector?
A:
You could use the attribute starts-with selector you mentioned, and then filter the results:
var elems = $("div[id^='1']").filter(function() {
return this.id.length <= 3;
});
Here's a working example. Note that this also returns the div with just 1 as it's id. You could prevent that by adding another condition to the return statement:
var elems = $("div[id^='1']").filter(function() {
return this.id.length <= 3 && this.id.length > 1;
});
Finally, note that id values cannot start with a number unless you're using the HTML5 doctype.
| {
"pile_set_name": "StackExchange"
} |
Q:
Are flash videos and interactive projects accessible?
I have a couple interactive elements and old flash videos that allow users to click. I want to know if flash is considered accessible and I don't need to do anything to them?
if it's not accessible, is it best practice to add:
aria-hidden="true"
to the div that contains the flash so the screen reader skips it?
Thanks in advance
A:
Short answer: Probably not. While there are many ways you can make your flash elements more accessible, there are far too many unknowns to be able to say if your usage of them would be accessible.
Longer answer:
Flash presents many challenges to a user - not just a screen reader user. As web content, an 'accessible' flash element needs to meet the required guidelines to be accessible - which is usually defined by WCAG 2.0. These criteria can include meeting contrast ratios, animation restrictions, access to controls and alternative content (amongst others). Simply hiding a flash element from a screen reader could still leave issues in other areas of the WCAG.
Keep in mind that many devices stopped supporting flash quite some time ago and support across platforms on modern devices and assistive technology is likely shaky at best. While I don't have statistics to back this up, there is a good chance that a large portion of users will not be able to access the flash content at all - regardless of disability - since flash is no longer supported on many devices.
If the flash content is used for any non-decorational purposes on the page, it would be wise to include that content in some format other than flash to allow more people to use your page. This technique is also permitted for accessible content (see: Conforming Alternate Version definition)
| {
"pile_set_name": "StackExchange"
} |
Q:
assigning values to multiple objects in a for loop
I have a bit of code in my project which reads data from a database and assigns it to the text on buttons. There are 25 buttons in a grid pattern in the program. The current solution is messy and has issues with empty data.
This is the current solution:
rs.Read()
Productbutton1.Text = (rs(0))
rs.Read()
Productbutton2.Text = (rs(0))
rs.Read()
Productbutton3.Text = (rs(0))
rs.Read()
Productbutton4.Text = (rs(0))
rs.Read()
Productbutton5.Text = (rs(0))
rs.Read()
Productbutton6.Text = (rs(0))
rs.Read()
Productbutton7.Text = (rs(0))
rs.Read()
Productbutton8.Text = (rs(0))
rs.Read()
Productbutton9.Text = (rs(0))
rs.Read()
Productbutton10.Text = (rs(0))
rs.Read()
Productbutton11.Text = (rs(0))
rs.Read()
Productbutton12.Text = (rs(0))
rs.Read()
Productbutton13.Text = (rs(0))
rs.Read()
Productbutton14.Text = (rs(0))
rs.Read()
Productbutton15.Text = (rs(0))
rs.Read()
Productbutton16.Text = (rs(0))
rs.Read()
Productbutton17.Text = (rs(0))
rs.Read()
Productbutton18.Text = (rs(0))
rs.Read()
Productbutton19.Text = (rs(0))
rs.Read()
Productbutton20.Text = (rs(0))
rs.Read()
Productbutton21.Text = (rs(0))
rs.Read()
Productbutton22.Text = (rs(0))
rs.Read()
Productbutton23.Text = (rs(0))
rs.Read()
Productbutton24.Text = (rs(0))
rs.Read()
Productbutton25.Text = (rs(0))
The problem I am facing is that I can't use a for loop in the sense:
For i = 1 To 25
rs.Read()
Productbutton(i).text = (rs(0))
Next
Because Visual basic wont allow me to substitute part of the button name for a variable. I have been told a while loop could be implemented as so: (while rs.Read = true). However I don't know how to progress through all of the button names in a while loop.
A:
Assuming you are using VB.NET and assuming Productbutton[1-25] always exist, you can do this:
For i = 1 To 25
rs.Read()
' Locate the button with the name on the form.
Dim btn As Button = Me.Controls.Find("Productbutton" & i, True)
btn.Text = rs(0)
Next
A:
You can use the DirectCast to Cast Text into a button
For i = 1 To 25
rs.Read()
dim newButton = DirectCast(Controls("Productbutton" & i.ToString()), Button)
newButton.text = (rs(0))
Next
| {
"pile_set_name": "StackExchange"
} |
Q:
Python struct.pack() not working in script
I have some problems here when I try to use struct.pack from a script. Everything is fine in the interpreter:
>>> import struct
>>> k=2
>>> struct.pack(">b", k)
'\x02'
Now when I do the same from a script I have problems:
k=2
p = struct.pack(">b", k)
print "p is %s"%(p,)
return p
Result:
p is
what am I doing wrong? I really don't understand this and would be glad if somebody could help me. Thanks
A:
Everything is fine. The character is unprintable.
print "p is %r" % (p,)
| {
"pile_set_name": "StackExchange"
} |
Q:
Client to use the slave when the master is down in MySQL replication
Is it possible for the client to use the slave when the master is down in mysql replication?
I have already setup a simple mysql replication having a master and a slave.
The client connects to the master to access the database, any changes made to the master server is replication onto the slave. How shall I configure that when the master server is down, the client automatically connects to the slave server?
I am using MySQL Server 5.1 and MySQL workbench 5.2 CE. I edited the my.ini files for both master and slave.
The client uses a J2EE application.
What additional commands must I input in the master my.ini file to make the changes?
Also is there a way to increase or decrease the time interval between replications?
A:
Since you have Master/Slave, you may want to implement the use of two things
Circular Replication
Database Virtual IP (aka DBVIP)
Circular Replication
Circular Replication is nothing more than first setting up Master/Slave then performing the same steps using the Slave as the Master's Master and the Master as the Slave's Slave. It just entails
explicitly user a different server_id on each DB Server
enabling binary logging on both DB servers
making sure the replication user is defined on both DB servers
Database Virtual IP (aka DBVIP)
There are products you can download and install to setup a DBVIP. One such product I use is ucarp. Another product is Linux Heartbeat. I normally do not use such things with MySQL Circular Replication or Master/Slave. Why?
Since those products can perform automatic failover, you do not want to do that in the event a Slave is some number of seconds behind in replication lag.
You should perform manual failovers.
Here is a poor man's approach to implementing DBVIP management.
Suppose you have this setup
DB Server1 has IP 10.1.2.30
DB Server2 has IP 10.1.2.40
You want to use DBVIP 10.1.2.50
Create the Script called /usr/local/sbin/MyAppDBVIP like this
echo echo 10.1.2.50 > /usr/local/sbin/MyAppDBVIP
Create the Script called /usr/local/sbin/dbvip-up
DBVIP=`/usr/local/sbin/MyAppDBVIP`
ip addr add ${DBVIP}/24 dev eth1
Create the Script called /usr/local/sbin/dbvip-down
DBVIP=`/usr/local/sbin/MyAppDBVIP`
ip addr del ${DBVIP}/24 dev eth1
Make sure all scripts are executable
chmod +x /usr/local/sbin/MyAppDBVIP
chmod +x /usr/local/sbin/dbvip-up
chmod +x /usr/local/sbin/dbvip-down
Make sure these script exist on both DB Servers
Simply run dbvip on whichever server you choose. .
So the failover process and protocol are the following:
Run dbvip-down on the DB Server that has the DBVIP. If you cannot
Run dbvip-up on the DB Server that you want to have the DBVIP
Just remember you should not run dbvip-up on both machines
After running dbvip-up, restart apache, JBoss, or any other app server contacting MySQL via the old Master
| {
"pile_set_name": "StackExchange"
} |
Q:
How do I get a default value from first in Clojure?
(> 1 (first [])) returns NullPointerException.
How can I make (first []) return a default value, such as 0, instead of nil?
A:
You can use or to bypass the nil value
(> 1 (or (first []) 0))
Because in Clojure, nil is treated as a falsy value.
| {
"pile_set_name": "StackExchange"
} |
Q:
getting element from td (Javascript)?
How can i get the href from such a table?
<table class="file_slot" cellpadding=0 cellspacing=3>
<tr>*****************</tr>
<tr>
<td><b>Size:</b></td>
<td>452<small><a href="http://www.google.com">Google</a></small></td>
</tr>
I tried using getElementsByClassName but i don't get to the <a> tag.
Thanks in advance
A:
You can do
var href = document.querySelector('.file_slot a').href;
A:
You want getElementsByTagName instead:
var aTags = document.getElementsByTagName("a");
| {
"pile_set_name": "StackExchange"
} |
Q:
Get Most Recent Post
Currently I'm trying to get only the most recent post in my index view that is marked as 'featured'.
In my controller I have
@featured = Post.featured
In my 'Post' Model I have
scope :featured, -> { where(:featured => true) }
And in my view I have
<% @featured.each do |post| %>
<%= post.title %>
<% end %>
What I'm trying to do is literally just get the first post that is marked as featured.
Any help is greatly appreciated, thanks in advance!
A:
Try this in your controller:
@featured = Post.featured.order("created_at").last
Note: if you're only storing one featured post in the @featured instance variable then you can change your view code to this:
<%= @featured.title %>
It isn't necessary to loop over one item with the each method.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to modify accurate 3D models to protect technical know-how
I have a 3D model from our engineering department with accurate measures of our product (format: VRML) that I want to give to a third party. The third party doesn't need an accurate model for what they are supposed to do with it. Now I want to modify the whole model with little effort to protect our technical know-how.
Does anybody know a solution in Blender to accomplish that?
I played a little bit with the decimate modifier and it looked promising.
The draw back I see with it, is the disproportionate effort I have to make since I don't know how to apply the modifier on ALL faces of ALL objects in the model.
Is it possible to get a short step-by-step tutorial to get all faces modified at once?
Another question that comes to my mind regarding the protection effect: If I modify the model and export it again to the VRML-format, then the modification I made in Blender is definite/destructive in opposite to the Blender-format itself where it stays non-destructive and I can adjust the modifier again. Am I right?
A:
Setup your decimate modifier on one of the objects.
Then, in object mode, select all objects (A) or all needed object (Shift+RMB).
Make sure your decimated object is active (different color, usually brighter orange), if it's not, Shift+RMB on it.
Use Ctrl+L to open the link menu and select "modifiers"
All the selected objects will now have the exact same modifiers as the active object.
About export : modifiers are applied when exporting, so it will be destructive. There can be a checkbox (depending on file format) to apply modifiers or not.
| {
"pile_set_name": "StackExchange"
} |
Q:
how to wait until ControlTemplate applied to the control WPF
I have added a function in my CustomControl called AddColumn
public void AddColumn(string ColumnHeader)
{
Grid MainGrid = this.Template.FindName("MainGrid", this) as Grid;
Border Header = this.Template.FindName("header", this) as Border;
if (MainGrid != null)
{
MainGrid.Children.Add(HeaderText);
// ...
MainGrid.ColumnDefinitions.Add(new ColumnDefinition() { Width =
MainGrid.Children.Add(...);
// ...
GridSplitter Splitter = new GridSplitter() { HorizontalAlignment
MainGrid.Children.Add(Splitter);
// ...
Grid.SetColumnSpan(Header, ColumnCounter-1);
}
}
In this method, as you can see, there are two calls of ControlTemplate Items.
I can't use this method before Templating job done. my ControlTemplate is global and I don't know where should I wait for it.
Can I wait or apply ControlTemplate in a correct way to be able to call this method whenever I wanted?
A:
The answer is that your control should override OnApplyTemplate (MSDN)
Derived classes of FrameworkElement can use this method as a notification for a variety of possible scenarios:
You can call your own implementation of code that builds the remainder of an element visual tree.
You can run code that relies on the visual tree from templates having been applied, such as obtaining references to named elements that came from a template.
You can introduce services that only make sense to exist after the visual tree from templates is complete.
You can set states and properties of elements within the template that are dependent on other factors. For instance, property values might only be discoverable by knowing the parent element, or when a specific derived class uses a common template.
Without knowing your use case though; I'd strongly suspect this is an XY problem and that you really want some sort of bound ItemsControl instead.
| {
"pile_set_name": "StackExchange"
} |
Q:
Soft keyboard not present, cannot hide keyboard - Appium android
I am getting following exception:
org.openqa.selenium.WebDriverException: An unknown server-side error occurred while processing the command. (Original error: Soft keyboard not present, cannot hide keyboard) (WARNING: The server did not provide any stacktrace information)
Command duration or timeout: 368 milliseconds
I am using driver.hideKeyboard() to hide soft input keyboard that is open on the screen.How to ensure that keyboard is open before hiding it? OR any other workaround?
A:
I also get this error, i correct it by using the following code in the setUp method :
capabilities.setCapability("unicodeKeyboard", true);
capabilities.setCapability("resetKeyboard", true);
You can check answers here :
Keyboard in Android physical device isn’t always hidden while using Appium
A:
Use adb command to check whether keyboard has popped up or not
adb shell dumpsys input_method | grep mInputShown
Output : mShowRequested=true mShowExplicitlyRequested=false mShowForced=false mInputShown=true
if mInputShown=true then yes software keyboard has popped up. Then use driver.pressKeyCode(AndroidKeyCode.BACK);
One way to do using java is
Process p = Runtime.getRuntime().exec("adb shell dumpsys input_method | grep mInputShown");
BufferedReader in = new BufferedReader(new InputStreamReader(p.getInputStream()));
String outputText = "";
while ((outputText = in.readLine()) != null) {
if(!outputText.trim().equals("")){
String keyboardProperties[]=outputText.split(" ");
String keyValue[]=keyboardProperties[keyboardProperties.length-1].split("=");
String softkeyboardpresenseValue=keyValue[keyValue.length-1];
if(softkeyboardpresenseValue.equalsIgnoreCase("false")){
isKeyboardPresent=false;
}else{
isKeyboardPresent=true;
}
}
}
in.close();
PS: Please do not use driver.navigate().back() as its behavior may not be same on all devices.
| {
"pile_set_name": "StackExchange"
} |
Q:
Is it correct to use splice and push for (old) state array change? Or we need to use newArray with ( slice and spread)?
Is it correct to use splice and push for (old) state array change? Or we need to use newArray with ( slice and spread) ?
How to work correct? and how to get senior level in React?
A:
Official document have mentioned about this clearly. https://reactjs.org/docs/react-component.html#state
Never mutate this.state directly, as calling setState() afterwards may replace the mutation you made. Treat this.state as if it were immutable.
So we need to create another one for changing the state.
| {
"pile_set_name": "StackExchange"
} |
Q:
Users with 5k+ rep have "approve tag wiki edits" privilege but can't see list of suggested edits
The approve-tag-wiki-edits page states that users need 5k reputation to approve tag wiki edits. However, there seems to be no way to see the list of suggested edits. The /review/suggested-edits page only shows a 404 Not Found error. Apparently, only users with 10k who have access to moderator tools can see the suggested edits.
I have experienced this on tex.sx where I have over 5k reputation, but I assume it is so on all Stack Exchange sites and Stack Overflow.
A:
Seeing all pending edits is a 10k ability -- otherwise you should see edit (0) or edit (1) under a question in the normal course of browsing questions...
(source: stackoverflow.com)
... and you can approve them then.
Update (Jan 31, 2012): 5k users can now view the suggested edits queue.
A:
This is status-bydesign, and is the same for regular suggested edit approvals (2k to approve, 10k to view). You can approve the edits as you come across them, but they want you to have some time before they let you power through the list.
| {
"pile_set_name": "StackExchange"
} |
Q:
Include Files in Yii
I am building an application in Yii that used the SwiftMailer Extension. The SwiftMailer examples show that I should include all of the information in the controller file however would it not be more organized and better to put all of the information for the email in a seperate file and include that file?
If yes, what would be the best way to include that file? I am used to just using the include function but I am assuming with Yii it should be its own class under the components folder?
A:
Ya, you probably want to make a custom class and put your SwiftMailer function in there, as well as any related functions, as appropriate. You can either put it in your components directory or a custom "classes" directory depending on how yo want to import it.
In that class, you can include the SwiftMailer libary (see here for an example of how), in your constructor function or similar.
| {
"pile_set_name": "StackExchange"
} |
Q:
QLabel::setPixmap() and QScrollArea::setWidget()
I've been tracking down a bug that boils down to this - if you show an image label inside a scroll area, the label will not be resized to the image's size if QLabel::setPixmap() is called after QScrollArea::setWidget().
This example illustrates the problem, just replace /path/to/some/image.png with some real image on your computer:
QScrollArea *scrollArea = new QScrollArea;
QLabel *label = new QLabel(scrollArea);
scrollArea->setWidget(label);
label->setPixmap(QPixmap("/path/to/some/image.png"));
scrollArea->show();
If you swap the lines to call setPixmap() before setWidget(), the label will be properly resized.
Why does this happen, and how can I force the label to resize properly?
A:
Set your scroll area's widgetResizable property to true:
scrollArea->setWidgetResizable(true);
| {
"pile_set_name": "StackExchange"
} |
Q:
How to get more information about "Error loading extension"?
How do I get more information why a specific extension is not working and showing me "Error loading extension" when trying to enable it?
A:
Run
sudo journalctl /usr/bin/gnome-shell
and look for errors associated with the extension while trying to enable it. Alternatively you can use grep to filter logs by extension name:
sudo journalctl /usr/bin/gnome-shell | grep 'system-monitor'
Also sometimes an extension works alright if you just manually add your GNOME shell version (which is not officially supported by the extension) to the extension's metadata.json file.
To do that (if you have installed the extension not as the root) go to ~/.local/share/gnome-shell/extensions/ and look for the directory associated with the extension. Open it and you should find a metadata.json file inside. Open the file, add your GNOME shell version under the "shell-version": section and save the file. Relogin and if you're lucky the extension may start working.
A:
You can see details of GNOME extensions, including errors, using GNOME's Looking Glass tool:
press Alt+F2, type lg, then Return.
go to the "Extensions" section
search the relevant extension and click on "Show Errors" for it
| {
"pile_set_name": "StackExchange"
} |
Q:
Read text files into 2D array?
I want to read a list of text files into a 2D array. The code throws a run time error on reading into the array. How can I fix this?
public static void main(String[] args) throws IOException
{
byte[][] str = null;
File file=new File("test1.txt");
str[0]= readFile1(file);
File file2=new File("test2.txt");
str[1]= readFile1(file2);
}
public static byte[] readFile1 (File file) throws IOException {
RandomAccessFile f = new RandomAccessFile(file, "r");
try {
long longlength = f.length();
int length = (int) longlength;
if (length != longlength) throw new IOException("File size >= 2 GB");
byte[] data = new byte[length];
f.readFully(data);
return data;
}
finally {
f.close();
}
}
A:
To begin with
byte[][] str = null;
File file=new File("test1.txt");
str[0]= readFile1(file);
the last statement will throw NullPointerException since str is null at this point. You need to allocate the array:
byte[][] str = new byte[2][];
| {
"pile_set_name": "StackExchange"
} |
Q:
Kendo ui Disable column when add new record
How do I achieve this, I want to disable radio button on Status Column only when Add New Record and checked on YES.
I don't know which part of script should I give. But here I provide some of it.
My KendoGrid Script
$("#grid").kendoGrid({
dataSource: dataSource,
dataBound: setColor,
height:400,
sortable: true,
columns: [
{ field: "segmentActive", title:"STATUS", width: "120px", editor: RadioSegmentActive,
template: data => data.segmentActive == "y" ? "Yes" : "No" }, // <-- displaying Yes/No insted of y/n
{ field: "marketSegmentName", title:"SEGMENT NAME", width: "120px" },
{ field: "publicPrice", title:"PUBLIC PRICE", width: "120px", editor: RadioPublicPrice,
template: data => data.publicPrice == "y" ? "Yes" : "No"},
{ field: "isHouseUse", title:"HOUSE USE", width: "120px", editor: RadioHouseUse,
template: data => data.isHouseUse == "y" ? "Yes" : "No"},
{ command: ["edit",{ name: "destroy", text: "De-active" }], title: " ", width: "120px" },
],
editable: "inline",
...........
My RadioSegmentActive function
function RadioSegmentActive(container, options) {
var guid = kendo.guid();
$('<input class="k-radio" id="radio3" name="segmentActive" type="radio" value="y" >').appendTo(container);
$('<label class="k-radio-label" for="radio3">YES</label>').appendTo(container); //YES
$('<br>').appendTo(container);
$('<input class="k-radio" id="radio4" name="segmentActive" type="radio" value="n" >').appendTo(container);
$('<label class="k-radio-label" for="radio4">NO</label>').appendTo(container); //NO
}
A:
I am not sure what you mean by "Checked on Yes", but you can do that by handling the edit event of the grid:
editable: "inline",
edit: function(e) {
if (e.model.isNew()) { // We are adding
// if ($("#radio3").prop("checked")) { // Check some field...
$("#radio3").attr('checked', true); // Set yes radio button
$('input[name=segmentActive]').attr("disabled",true); // Disable radio buttons
// }
}
}
| {
"pile_set_name": "StackExchange"
} |
Q:
ocamlyacc with empty string
So I have a grammar that includes the empty string. The grammar is something like this:
S->ε
S->expression ;; S
I'm getting the error "No more states to discard" when I run my parser so I believe I'm not representing the empty string correctly. So how would I go about representing it, specifically in the lexer .mll file?
I know I need to make a rule for it so I think I have that down. This is what I think it should look like for the parser .mly file, excluding the stuff for expression.
s:
| EMPTY_STRING { [] }
| expression SEMICOLON s { $1::$3 }
A:
You're thinking of epsilon as a token, but it's not a token. It's a 0-length sequence of tokens. Since there are no tokens there, it's not something your scanner needs to know about. Just the parser needs to know about it.
Here's a grammar something like what I think you want:
%token X
%token SEMICOLON
%token EOF
%start main
%type <char list> main
%%
main :
s EOF { $1 }
s :
| epsilon { $1 }
| X SEMICOLON s { 'x' :: $3 }
epsilon :
{ [] }
Note that epsilon is a non-terminal (not a token). Its definition is an empty sequence of symbols.
| {
"pile_set_name": "StackExchange"
} |
Q:
Find the limit of the multivariable function $f(x,y)=\frac{x}{\sqrt{x^2+y^2}}$ at $(0,0)$
I have the function $f(x,y)=\frac{x}{\sqrt{x^2+y^2}}$. I want the limit of this function as $(x,y)$ approach $(0,0)$. My try is to approach $(0,0)$ by two ways:
$y=x$ and $y=x^2$. If we do so, we get the same result for both, i.e $f(x,y)$ approaches 1. My question is whether this result is correct or not. Using direct substitution, I get something else.
A:
Substitution $y=mx$ will give the limit as $\frac{1}{\sqrt{1+m^2}}$, which takes different values for different $m\in\mathbb{R}$. Thus, limit does not exist.
| {
"pile_set_name": "StackExchange"
} |
Q:
Transfer values between 2 dataframes based on time granularity
I have one dataframe, df_60 that is of 60 minute time granularity. And another with 30 minute granularity, df_30. I want to move the values from a column on df_60 to a column in df_30, and maintain the duration of when the value appears.
So say I had a date of 2011-01-05 00:00:00 0, an hourly granularity, and it had a value in a column val, of 1. How do I "fill in" the values of a 30 moinute timeframe at all times that a column in the 60 minute dataframe was equal to x ?
>>>df_60
dt_hr_idx val #here val = 1 for times between 2am and 4am
2011-01-05 00:00:00 0
2011-01-05 01:00:00 0
2011-01-05 02:00:00 1
2011-01-05 03:00:00 1
2011-01-05 04:00:00 0
>>>df_30
dt_hlaf_hr_idx val #df_30 val column is currently blank
2011-01-05 00:00:00 0
2011-01-05 00:30:00 0
2011-01-05 01:00:00 0
2011-01-05 01:30:00 0
2011-01-05 02:00:00 0
2011-01-05 02:30:00 0
2011-01-05 03:00:00 0
2011-01-05 03:30:00 0
2011-01-05 04:00:00 0
#desired df
df_30
dt_hlaf_hr_idx val #val should be 1 for values between 2am and 4am
2011-01-05 00:00:00 0
2011-01-05 00:30:00 0
2011-01-05 01:00:00 0
2011-01-05 01:30:00 0
2011-01-05 02:00:00 1
2011-01-05 02:30:00 1
2011-01-05 03:00:00 1
2011-01-05 03:30:00 1
2011-01-05 04:00:00 0
I could hack something out with loops, but is there a sane method available?
Thanks.
A:
Use Series.reindex with ffill:
df = df_60.reindex(df_30.index, method='ffill')
print (df)
val
2011-01-05 00:00:00 0
2011-01-05 00:30:00 0
2011-01-05 01:00:00 0
2011-01-05 01:30:00 0
2011-01-05 02:00:00 1
2011-01-05 02:30:00 1
2011-01-05 03:00:00 1
2011-01-05 03:30:00 1
2011-01-05 04:00:00 0
Another solution with merge_asof:
df = pd.merge_asof(df_30, df_60, left_index=True, right_index=True)
print (df)
val_x val_y
2011-01-05 00:00:00 0 0
2011-01-05 00:30:00 0 0
2011-01-05 01:00:00 0 0
2011-01-05 01:30:00 0 0
2011-01-05 02:00:00 0 1
2011-01-05 02:30:00 0 1
2011-01-05 03:00:00 0 1
2011-01-05 03:30:00 0 1
2011-01-05 04:00:00 0 0
| {
"pile_set_name": "StackExchange"
} |
Q:
asp.net mvc client side validation not working?
For some reason my client side validation does not seem to be working:
Here is my html:
@using (Html.BeginForm("Create", "Home", FormMethod.Post))
{
<hr />
@Html.ValidationSummary(true)
<hr />
<p>
<label>Select Client_ID: </label>
<span class="field">
<select name="clientId" id="clientId">
@foreach (var item in Model.ClientId)
{
<option value="@item">@item</option>
}
</select>
</span>
</p>
<p>
<label>@Html.LabelFor(model => model.UserModel.name)</label>
<span class="field">
@Html.EditorFor(model => model.UserModel.name)
</span>
@Html.ValidationMessageFor(model => model.UserModel.name)
</p>
<p>
<label>@Html.LabelFor(model => model.UserModel.password)</label>
<span class="field">
@*<input name="password" id="password" type="password" />*@
@Html.EditorFor(model => model.UserModel.password)
</span>
@Html.ValidationMessageFor(model => model.UserModel.password)
</p>
<p>
<label>@Html.LabelFor(model => model.UserModel.email)</label>
<span class="field">
@*<input name="email" id="email" type="email" />*@
@Html.EditorFor(model => model.UserModel.email)
</span>
@Html.ValidationMessageFor(model => model.UserModel.email)
</p>
<p>
<label>Select: </label>
<span class="field">
<select name="accessLevel" id="accessLevel">
<option value="3">Company</option>
<option value="5">End-User</option>
</select>
</span>
</p>
<input type="submit" value="Submit" />
Here is my model:
public class CreateUserModel
{
[Required]
[Display(Name = "Client_ID")]
public string clientId { get; set; }
[Required(ErrorMessage = "A name is required")]
[MaxLength(20), MinLength(2, ErrorMessage = "Name must be 2 character or more")]
[Display(Name = "Name")]
public string name { get; set; }
[Display(Name = "Email Address")]
[Required(ErrorMessage = "Email is Required")]
[RegularExpression(@"^([a-zA-Z0-9_\-\.]+)@((\[[0-9]{1,3}" +
@"\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\" +
@".)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$",
ErrorMessage = "Email is not valid")]
public string email { get; set; }
[Required]
[MaxLength(20), MinLength(6, ErrorMessage = "Password Must be 6 or more chataters long")]
[Display(Name = "Password")]
public string password { get; set; }
[Required]
public int accessLevel { get; set; }
}
and I do have client side enabled in the webconfig:
<appSettings>
<add key="webpages:Version" value="3.0.0.0" />
<add key="webpages:Enabled" value="false" />
<add key="ClientValidationEnabled" value="true" />
<add key="UnobtrusiveJavaScriptEnabled" value="true" />
{EDIT} added rendered html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Home Page - My ASP.NET Application</title>
<link href="/Content/bootstrap.css" rel="stylesheet"/>
<link href="/Content/site.css" rel="stylesheet"/>
<script src="/Scripts/modernizr-2.6.2.js"></script>
</head>
<body>
<script src="/Scripts/jquery.validate.js"></script>
<div class="jumbotron">
<h1>Add Users to the website</h1>
</div>
<form action="/Home/Create" method="post"> <hr />
<hr />
<p>
<label for="UserModel_name">Name</label>
<span class="field">
<input type="text" name="name" />
</span>
<span class="field-validation-valid" data-valmsg-for="UserModel.name" data-valmsg-replace="true"></span>
</p>
<p>
<label for="UserModel_password">Password</label>
<span class="field">
<input name="password" id="password" type="password" />
</span>
<span class="field-validation-valid" data-valmsg-for="UserModel.password" data-valmsg-replace="true"></span>
</p>
<p>
<label for="UserModel_email">Email Address</label>
<span class="field">
<input name="email" id="email" type="email" />
</span>
<span class="field-validation-valid" data-valmsg-for="UserModel.email" data-valmsg-replace="true"></span>
</p>
<p>
<label>Select: </label>
<span class="field">
<select name="accessLevel" id="accessLevel">
<option value="3">Company</option>
<option value="5">End-User</option>
</select>
</span>
</p>
<input type="submit" value="Submit" />
</form>
<hr />
<footer>
<p>© 2014 - My ASP.NET Application</p>
</footer>
</div>
<script src="/Scripts/jquery-2.1.0.js"></script>
<script src="/Scripts/bootstrap.js"></script>
A:
For some reason the Html helpers does not have generated validation attributes in the inputs (data-val="true" and the others), check that. Besides to check the order in which the javascript libraries are loaded:
<script src="~/Scripts/jquery.js"></script>
<script src="~/Scripts/jquery.validation.js"></script>
<script src="~/Scripts/jquery.validation.unobtrusive.js"></script>
A:
Your problem is likely that you have jQuery at the bottom of your file, but you are putting jquery.validate at the top. jQuery has to come before jQuery.validate. I would suggest always putting jQuery in your header, not in the body, and it should be the first thing after modernizr.
Also, you do know that jQuery 2.x does not work with IE8 ore earlier, right?
A:
It seems that your jquery.validate.js is in wrong position. It must be after main jquery ref.
For MVC 5, it should be as following:
_Layout.cshtml: (bottom of page)
<body>
...
...
@Scripts.Render("~/bundles/jquery")
@Scripts.Render("~/bundles/bootstrap")
@Scripts.Render("~/bundles/jqueryval") <!-- *required for client side validation! -->
@RenderSection("scripts", required: false)
</body>
where ~/bundles/jqueryval is defined in BundleConfig.cs: RegisterBundles() method:
bundles.Add(new ScriptBundle("~/bundles/jqueryval").Include(
"~/Scripts/jquery.validate*"));
| {
"pile_set_name": "StackExchange"
} |
Q:
Why is there a constant -1A current through the voltage source at resonance?
Below circuit is at resonance. Shouldn't the circuit offer infinite impedance to the voltage source ? I thought, then the current through the source would be 0A. But the simulation shows that the circuit draws a constant current of -1A. Why is this so ?
simulate this circuit – Schematic created using CircuitLab
EDIT : As suggested, with 0.1 ohm resistor in series with the inductor, the current slowly dies out
A:
Why is this so?
This is because at the start of the simulation (take a look during the first 50 \$\mu\$s for instance) the sinewave is positive for 2 quarts of a cycle. During this period the coil is 'charged' to 2 A. If you'd have applied a cosine (I think you can't in this CircuitLab), you would of course have seen an infinite current spike in the capacitor but also that in the first quarter cycle the coil's current would go to 1 A, then in the next back to zero, then go to -1 A, then 0 etc. etc. In other words: your expected behavior.
This is all a matter of bad timing, the initial build up of flux in the coil is not compensated with a braking down of it because of the two positive quart cycles at the start of the simulation.
The same 'problem' appears when you connect a transformer to the grid.
Done at the 'wrong' time, i.e. at zero voltage crossing, the inductor will be 'charged' to the normal operating amplitude, then however 'overcharged' to double the peak flux during normal operation. Mostly that's a region of heavy saturation, associated with a huge inrush current which can reach factors more than the mere double of the current amplitude during normal operation.
In your case however there's no resistance in the circuit, so this 'charge' will never be consumed and from the source will be drawn a constant 1 A, instead of average 0 A. Add a small resistor of 0.01 \$\Omega\$ in series of L and then see what happens.
| {
"pile_set_name": "StackExchange"
} |
Q:
Restarting server with bat file
I'm trying to make a simple bat file that restarts a server. It looks like this:
shutdown -r -f -t 60
But all it does is loop inside the cmd window, printing the command > new line > priting the command. Over and over.
Control + Alt + Delete only opens up the menu on the machine where I RDP in from and not on the server itself.
A:
Is your batch file called shutdown.bat? If so, the script won't call system restart, the name causes the script to loop.
Try to rename your batch file to something else, or, as a good geek, move to PowerShell. If you decide to switch, you'll need the Restart-Computer command.
| {
"pile_set_name": "StackExchange"
} |
Q:
Hadoop - textouputformat.separator use ctrlA ( ^A )
I'm trying to use ^A as the separator between Key and Value in my reduce output files.
I found that the config setting "mapred.textoutputformat.separator" is what I want and this correctly switches the separator to ",":
conf.set("mapred.textoutputformat.separator", ",");
But it can't handle the ^A character:
conf.set("mapred.textoutputformat.separator", "\u0001");
throws this error:
ERROR security.UserGroupInformation: PriviledgedActionException as:user (auth:SIMPLE) cause:org.apache.hadoop.ipc.RemoteException: java.io.IOException: java.lang.RuntimeException: org.xml.sax.SAXParseException; lineNumber: 68; columnNumber: 94; Character reference "&#
I found this ticket https://issues.apache.org/jira/browse/HADOOP-7542 and see they tried to fix this but reverted the patch due to XML1.1 concerns.
SO I'm wondering if anyone has had success setting the separator to ^A (seems pretty common), using an easy work around. Or if I should just settle and use tab separator.
Thanks!
I'm running Hadoop 0.20.2-cdh3u5 on CentOS 6.2
A:
Looking around it looks like there are maybe three options that i've found for solving this problem:
Character reference “” is an invalid XML character - similar SO question
Unicode characters/Ctrl G or Ctrl A as TextOutputFormat (Hadoop) delimiter
The possible solutions as detailed in the link above are:
You can Base64 encode the separator character. You then need to create a custom TextOutputFormat that overrides the getRecordWriter method and decodes the Base64 encoded separator.
Create a custom TextOutputFormat again, except change the default separator character from a tab.
Provide the delimiter through an XML resource file. You can specify a custom resource file using the addResource() method of the jobs Configuration.
| {
"pile_set_name": "StackExchange"
} |
Q:
Calculate difference between two rows of the same type
Suppose I have the following table (see below), and I want to find the entries where the "memsize" or "totalstorage" for the same machine (= same vmnaam value) has changed.
ID VMNaam Memsize totalstorage dataentrytime
1 x 12 150 blabla
2 x 12 150 blabla
3 x 14 150 blabla
4 Y 12 150 blabla
5 Y 20 150 blabla
6 Y 18 150 blabla
The following query finds those rows
SELECT realTable.VMnaam,
realTable.memsize,
realTable.totalstorage
FROM vmresourcetest realTable
LEFT OUTER JOIN (
SELECT (ID+1) AS 'virtualId',
(ID) AS 'realId',
vmnaam AS 'vmnaamVirtual',
memsize AS 'virtualMemsize',
totalstorage AS 'virtualTotalstorage'
FROM vmresourcetest
ORDER BY vmnaam
) virtual
ON virtual.virtualId = realTable.id and virtual.vmnaamVirtual = realTable.vmnaam
where IFNULL((realTable.memsize - virtual.virtualMemsize), 0) <> 0 or IFNULL((realTable.totalstorage - virtual.virtualTotalstorage), 0) <> 0
However, when the machine rows are scrambled, my query obviously doesn't work anymore because the ID of the previous machine entry might be the ID of another machine
E.g
1 x blablabla
2 y blablalba
3 y blablabll
4 x blablbla
I somehow want to change ID+1 into (select id from realtable where id > id), but that doesn't work.
Any ideas on how to fix my problem?
A:
This should get you going:
SELECT curr.VMnaam,
curr.memsize,
curr.totalstorage
FROM vmresourcetest curr LEFT JOIN
vmresourcetest nxt ON curr.id < nxt.id
AND curr.vmnaam = curr.vmnaam
AND (curr.memsize != nxt.memsize
OR curr.totalstorage != nxt.totalstorage)
AND NOT EXISTS ( -- there is no record between current and next record
SELECT *
FROM vmresourcetest
WHERE id > curr.id AND id < nxt.id AND vmnaam = curr.vmnaam)
| {
"pile_set_name": "StackExchange"
} |
Q:
Double sink with disposal - water shoots up when disposal runs
I have a double sink with a disposal on the right side. The disposal joins the left sink drain via a slip joint baffle tee below the left sink then the drain goes to the P-trap and out. It was installed by a licensed plumber.
Every time the disposal is turned on water shoots up into the left sink which is where we like to keep a dish drainer. What can be done to stop the water from shooting up?
A:
My instincts are inline with the comments by MonkeyZues and Solar Mike. The impeller design of some disposals accelerates the discharge. A partially plugged trap will send water up, following the path of least resistance (and still let the sinks drain). If the discharge from the disposal swept down (with a swept tee) the discharge would be directed down instead of splashing into the vertical-side of the straight tee. Both ideas are simple and inexpensive - cleaning the trap and swapping the tee.
| {
"pile_set_name": "StackExchange"
} |
Q:
center image in a square responsive container
I have a container (.inner). It contains a square div (.square) and is responsive. I need the image in it to be centered vertically and horizontally. I dont want to use background url property. My html markup:
<div class="thumb">
<div class="square">
<a href="">
<img src=""/>
</a>
</div>
</div>
How my square works in css:
.thumb {
position: relative;
width: 100%;
}
.square{
position: absolute;
top: 0;
left: 0;
bottom: 0;
right: 0;
overflow:hidden;
display: inline-block;
vertical-align: middle;
}
At the moment, I added a class to the image with javascript for landscape images to fit both portrait and landscape images with css to the square containers height and width.
img {
max-width: 100%;
height: auto;
width: auto;
}
img.landscape {
max-width: none;
height: 100%;
width:auto!important;
}
But i have no ideas how to center them. I already read a lot of articles here but none of them worked. Thanks for help
Here a picture of what im searching for, should also work vertical if possible:
A:
Your CSS is trying to center the .square itself and not the contained image. margin: auto; along with absolute positioning of the image does the trick.
This is a simple example showing how to center; you can modify it to suit your needs. The image's opacity is lowered to show that it is centered horizontally and vertically inside its container. The JavaScript animates the height and width of the container to simulate responsiveness.
http://jsfiddle.net/6py8o6b8/4/
TweenMax.to($(".square"), 2, {
width: "100%",
height: "250px",
repeat: -1,
repeatDelay: 1,
yoyo: true,
ease: "linear"
});
.square {
border: 2px solid red;
height: 100px;
position: relative;
width: 100px;
margin: 70px auto;
}
img {
position: absolute;
top: -9999px;
left: -9999px;
right: -9999px;
bottom: -9999px;
margin: auto;
opacity: 0.5;
}
<script src="http://cdnjs.cloudflare.com/ajax/libs/gsap/latest/TweenMax.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="square">
<img src="http://www.collativelearning.com/PICS%20FOR%20WEBSITE/stills%202/black%20screen.jpg" />
</div>
| {
"pile_set_name": "StackExchange"
} |
Q:
Static ArrayList between Fragments
I have a static ArrayList defined in my activity, being used by several fragments within it. This ArrayList is sometimes modified.
Is this bad practice? Should I be using bundles/SQLite instead?
A:
Yes static is always bad (you should avoid it whenever possible), because even if you dont have access to the Activity instance you can modify it like this SomeActivitiy.list.removeAll(); for example.
What I would suggest it the use of a DataProvider that contains your data and you just have to inject it in your fragments.
The SQLite option in the other hand should only be used when you have to persist the data, so you don't have to delete after using it.
| {
"pile_set_name": "StackExchange"
} |
Q:
Detect active NSSplitViewItem
I have a SplitView with (several) SplitViewItems. Echt SplitViewItem has a ViewController with multiple views in it.
I need to detect which of the SplitViewItems has the focus of the user.
For example: if the user clicks on any control/view (or navigates to it in any other way), the background of the SplitViewItem that contains that view item should change. As I do not know which/how many views will be enclosed in the ViewController in the SplitViewItem, I'd prefer to detect which SplitViewItem is the 'active' one in the SplitViewController.
I have been searching for a solution all day long. I could not find any kind of notification, nor found a way to solve this managing the responder chain.
Can anybody please point me in the right direction? A (swift) code example would be highly appreciated.
Thanks!
A:
It took me quite some research, but I found a working solution. Not the most elegant, but working.
I found the best approach to be to add an event monitor to the SplitViewController.
In viewDidLoad() add the following code:
NSEvent.addLocalMonitorForEvents(matching: [.keyDown, .leftMouseDown, .flagsChanged]) { [unowned self] (theEvent) -> NSEvent? in
let eventLocation = theEvent.locationInWindow
let numberOfSplitViews = self.splitViewItems.count
var activeIndex: Int?
for index in 0..<numberOfSplitViews {
let view = self.splitViewItems[index].viewController.view
let locationInView = view.convert(eventLocation, from: nil)
if ((locationInView.x > 0) && (locationInView.x < view.bounds.maxX) && (locationInView.y > 0) && (locationInView.y < view.bounds.maxY)) {
activeIndex = index
break
}
}
switch theEvent.type {
case .keyDown:
print("key down in pane \(activeIndex)")
self.keyDown(with: theEvent)
case .leftMouseDown, .rightMouseDown:
print("mouse down in pane \(activeIndex)")
self.mouseDown(with: theEvent)
case .flagsChanged:
print("flags changed in pane \(activeIndex)")
self.flagsChanged(with: theEvent)
default:
print("captured some unhandled event in pane \(activeIndex)")
}
return theEvent
}
(you may have to tweak the relevant events to your own liking. Also, you may need to remover the monitor using NSEvent.removeMonitor(_:)).
In addition (out of scope of this question), you might also want to consider making the variable activeIndex an observable class variable (I did this using RxSwift), allowing you to easily react on any change happening inside the 'active pane'.
Any more elegant/simple solutions are welcome!
| {
"pile_set_name": "StackExchange"
} |
Q:
Try to match a regex pattern in text always returns None Python
I have a regex defined in python and I am trying to extract a matching text using python. But it always returns None.
This is the configuration file text which is defined as myConf.conf
input {
name: "abc",
age: "20"
}
filter {
name: "pqr",
age: "25"
if [message] =~ "TRANSACTION:request" {
grok {
match => { "message" => "\[%{TIMESTAMP_ISO8601:timestamp}] %{LOGLEVEL:level} \{% {DATA:logtype}}
}
map['method'] = event.get('method')
map['request'] = event.get('body')
}
drop {}
aggregate {
task_id => "%{tid}"
}
}
output {
stdout{}
}
This is my python code. It reads data from the myConf.conf file and try to match the defined regex
import re
path = "./myConf.conf"
file = open(path, "r+")
text_val = str(file.read())
pattern = re.compile(r"^filter\s*\{[\w\W]+?\n\}$")
result = pattern.search(text_val)
print(result)
No issues in the regex. It works fine
Working regex
I am a Java programmer and totally new to python programming. What I am doing wrong here?
A:
You need to use the multiline flag:
pattern = re.compile(r"^filter\s*\{[\w\W]+?\n\}$", re.MULTILINE)
| {
"pile_set_name": "StackExchange"
} |
Q:
Optimizing Oracle database query/fetchall
The database design is far from optimum but I have to deal with it and now I'm really stuck.
Edit: I'm using cx_Oracle
OK so this is my query:
query="select degree, spectraldev.event.eventnumber \
from spectraldev.degree \
join spectraldev.alignment on \
(spectraldev.version_id = alignment.version_id) \
join spectraldev.event on \
(alignment.timestamp between event.eventstart and event.eventstop) \
join spectraldev.eventsetup on \
(spectraldev.event.eventsetup = spectraldev.eventsetup.oid) \
where spectraldev.event.eventnumber>=" + options.start + " AND spectraldev.event.eventnumber<=" + options.stop + " AND \
HITS>=" + str(options.minimum_hits)+" \
order by spectraldev.event.eventnumber"
db_cursor.execute(query)
Which returns a bunch of degrees (12.34 etc.) for many events, which are identified by a unique number (eventnumber like 346554).
So I get a table like this:
454544 45.2
454544 12.56
454544 41.1
454544 45.4
454600 22.3
454600 24.13
454600 21.32
454600 22.53
454600 54.51
454600 33.87
454610 32.7
454610 12.99
And so on…
Now I need to create a dictionary with the average degree for each event (summing up all corresponding floats and dividing by the number of them).
I think this could be done in SQL but I just can't get it work. At the moment I'm using python to do this, but the fetch command takes 1-2 hours to complete about 2000 Events, which is far too slow, since I need to process about 1000000 events.
This is my fetching part, which takes so long:
_degrees = []
for degree, eventNumber in cursor.fetchall():
_degrees.append([eventNumber, degree])
and then sorting (which is really fast, < 1sec) and calculating averages (also really fast):
_d={}
for eventNumber, degree in _degrees:
_d.setdefault(eventNumber, []).append(degree)
for event in events:
_curDegree = _degrees[int(event)]
_meanDegree = sum(_curDegree) / float(len(_curDegree))
meanDegrees.append(_meanDegree)
Is there a way to do the python part in SQL?
A:
This is an aside, but an important one. You're wide open to SQL Injection. It may not matter in your particular instance but it's best to always code for the worst.
You don't mention what module you're using but assuming it's something that's PEP 249 compliant (you're probably using cx_Oracle) then you can pass a dictionary with the named bind parameters. A typical query might look like this:
query = """select column1 from my_table where id = :my_id"""
bind_vars = {'my_id' : 1}
db_cursor.execute(query, bind_vars)
On your actual query you're converting some variables (options.start for instance) to a string in Python, but not quoting them in SQL, which means they're being implicitly converted back to a number. This almost definitely isn't needed.
In relation to your actual problem 1-2 hours to complete 2,000 events is, you're correct, ridiculous. You haven't posted a schema but my guess is you're lacking any indexes.
To get the average number of degrees per event number you should use the avg() function. This would make your query:
select spectraldev.event.eventnumber, avg(degree) as degree
from spectraldev.degree
join spectraldev.alignment
-- I think this is wrong on your query
on (degree.version_id = alignment.version_id)
join spectraldev.event
on (alignment.timestamp between event.eventstart and event.eventstop)
join spectraldev.eventsetup
on (spectraldev.event.eventsetup = spectraldev.eventsetup.oid)
where spectraldev.event.eventnumber >= :start
and spectraldev.event.eventnumber <= :stop
and hits >= :minimum_hits
group by spectraldev.event.eventnumber
order by spectraldev.event.eventnumber
I've formatted your query to make it slightly more readable (from my point of view) and to make it more obvious where you need the indexes.
Judging by this you need an index on the following tables and columns;
EVENT - eventnumber, eventstart, eventstop, eventsetup
DEGREE - version_id
ALIGNMENT - version_id, tstamp
EVENTSETUP - oid
and wherever hits might be.
Having said all that your problem may be the indexes. You haven't provided your explain plan or the schema, or the number of rows so this is going to be a guess. However, if you're selecting a significant proportion of the rows in a table the CBO may be using the indexes when it shouldn't. Forcing a full table scan using the full hint, /*+ full(event) */ for instance, may solve your problem.
Removing the order by, if it's not required may also significantly speed up your query.
| {
"pile_set_name": "StackExchange"
} |
Q:
Serialize JavaScript's navigator object
I'm creating a page to help diagnose the problem our users are experiencing with our web pages (you know, asking a user "What browser are you using?" usually leads to "Internet").
This page already submits to me all the HTTP headers and now I'm trying to have JavaScript give some more informations, so I thought it would be great to have the user's navigator JavaScript object and I started looking how to serialize it so I can submit it through a form.
The problem is I'm not able to serialize the navigator object using any JSON library I know of, everyone returns an empty object (?!), so I decided to write an ad-hoc serializer.
You can find the code here:
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.5.0/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript">
function serialize (object) {
var type = typeof object;
if (object === null) {
return '"nullValue"';
}
if (type == 'string' || type === 'number' || type === 'boolean') {
return '"' + object + '"';
}
else if (type === 'function') {
return '"functionValue"';
}
else if (type === 'object') {
var output = '{';
for (var item in object) {
if (item !== 'enabledPlugin') {
output += '"' + item + '":' + serialize(object[item]) + ',';
}
}
return output.replace(/\,$/, '') + '}';
}
else if (type === 'undefined') {
return '"undefinedError"';
}
else {
return '"unknownTypeError"';
}
};
$(document).ready(function () {
$('#navigator').text(serialize(navigator));
});
</script>
<style type="text/css">
#navigator {
font-family: monospaced;
}
</style>
<title>Serialize</title>
</head>
<body>
<h1>Serialize</h1>
<p id="navigator"></p>
</body>
</html>
This code seems to work perfectly in Firefox, Opera, Chrome and Safari but (obviously) doesn't work in Internet Explorer (at least version 8.0), it complains that "Property or method not supported by the object" at line for (var item in object) {.
Do you have any hint on how to fix the code or how to reach the goal (serialize the navigator object) by other means?
Solution (v 2.0):
Replace
for (var item in object) {
if (item !== 'enabledPlugin') {
output += '"' + item + '":' + serialize(object[item]) + ',';
}
}
with
for (var item in object) {
try {
if (item !== 'enabledPlugin') {
output += '"' + item + '":' + serialize(object[item]) + ',';
}
}
catch (e) {
}
}
and it works.
A:
Try putting it inside a new object
var _navigator = {};
for (var i in navigator) _navigator[i] = navigator[i];
And then serialize it (maybe using some JSON library if the browser doesn't have native JSON API, I use json2.js):
$('#navigator').text(JSON.stringify(_navigator));
Edit: It seems that Internet Explorer doesn't allow navigator.plugins and navigator.mimeTypes to be iterated over, so this works:
var _navigator = {};
for (var i in navigator) _navigator[i] = navigator[i];
delete _navigator.plugins;
delete _navigator.mimeTypes;
$('#navigator').text(JSON.stringify(_navigator));
A:
JSON in accepted answer contains only top level elements. Check this out https://jsfiddle.net/j1zb7qm0/ - _navigator.connection is empty. I've wrote a small func to collect all nested properties:
function recur(obj) {
var result = {}, _tmp;
for (var i in obj) {
// enabledPlugin is too nested, also skip functions
if (i === 'enabledPlugin' || typeof obj[i] === 'function') {
continue;
} else if (typeof obj[i] === 'object') {
// get props recursively
_tmp = recur(obj[i]);
// if object is not {}
if (Object.keys(_tmp).length) {
result[i] = _tmp;
}
} else {
// string, number or boolean
result[i] = obj[i];
}
}
return result;
}
You can use it like this var _navigator = recur(navigator) or create your own wrapper. In fact you can use it to iterate over and copy any nested object.
| {
"pile_set_name": "StackExchange"
} |
Q:
Powershell nested DataTable
I am trying to nest a DataTable in a Powershell script.
Consider a very simple datatable:
$somedt = New-Object System.Data.DataTable
[void]$somedt.Columns.Add('foo')
[void]$somedt.Columns.Add('bar')
[void]$somedt.Rows.Add('boo', 'bah')
[void]$somedt.Rows.Add('typed', 'better')
$somedt.gettype()
IsPublic IsSerial Name BaseType
-------- -------- ---- --------
True True DataTable System.ComponentModel.MarshalByValueComponent
I would like to have this as a value in another datatable. So let's create one:
$dt = New-Object System.Data.DataTable
[void]$dt.Columns.Add('Title')
$dtcol = New-Object System.Data.DataColumn
$dtcol.ColumnName = "TableData"
$dtcol.DataType = "System.Data.DataTable"
$dtcol.DefaultValue = New-Object System.Data.DataTable
[void]$dt.Columns.Add($dtcol)
[void]$dt.Rows.Add("Orange")
[void]$dt.Rows.Add("Red")
$dt | Format-Table -AutoSize
Title TableData
----- ---------
Orange {}
Red {}
And we verify:
$dt.Columns["TableData"].DataType
IsPublic IsSerial Name BaseType
-------- -------- ---- --------
True True DataTable System.ComponentModel.MarshalByValueComponent
And
$dt.Rows[1].TableData.gettype()
IsPublic IsSerial Name BaseType
-------- -------- ---- --------
True True DataTable System.ComponentModel.MarshalByValueComponent
So now I verify $somedt's type and create a new DataRow which holds $somedt as it's 'TableData' value:
$somedt.gettype()
$myrow = $dt.NewRow()
$myrow["Title"] = 'Blue'
$myrow["TableData"] = $somedt
$myrow
IsPublic IsSerial Name BaseType
-------- -------- ---- --------
True True DataTable System.ComponentModel.MarshalByValueComponent
Type of value has a mismatch with column type Couldn't store in TableData Column. Expected type is DataTable.
At line:5 char:1
+ $myrow["TableData"] = $somedt
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : OperationStopped: (:) [], ArgumentException
+ FullyQualifiedErrorId : System.ArgumentException
Title : Blue
TableData : {}
So why does this fail? It seems that Powershell Takes the DataTable and converts it into a collection of DataRows. How can I prevent this from happening?
It is kind of the reverse of the "comma trick" used when returning values from a function, or so it seems.
I can remove the DataType restriction from the 'TableData' column but that just leads to default empty DataTables not added and the nested datatble is added as a collection of DataRows
Title TableData
----- ---------
Orange
Red
Blue System.Data.DataRow System.Data.DataRow
I would really like to be able to use some of the functionality of DataTables but I also need the nesting. If not I would need to rethink / refactor quite a bit. The documentation on DataColumn.DataType does not mention these complex types but that part of the code seems to work fine initially.
Am I doing something wrong? or is this simply not possible?
P.s. this needs to work in Powershell v3.0 / .Net 4.5
A:
Your exception happens due to PowerShell wrap result of New-Object cmdlet into PSObject object:
$DataTable = New-Object System.Data.DataTable
$DataTableUnwrapped = $DataTable.PSObject.BaseObject
[Type]::GetTypeArray(($DataTable,$DataTableUnwrapped)).FullName
This commands will print:
System.Management.Automation.PSObject
System.Data.DataTable
In some cases PowerShell unwrap PSObject automatically:
[Object]::ReferenceEquals($DataTable,$DataTableUnwrapped) #return True
In other cases, like assignment to property or indexer with type Object:
$myrow["TableData"] = $somedt
$myrow.TableData = $somedt
unwrapping does not happens and property or indexer accessor got PSObject instance.
As System.Data API is not PowerShell aware, it does not know how to unwrap PSObject or convert it to DataTable. So that, it refuse to store PSObject in column typed as DataTable.
| {
"pile_set_name": "StackExchange"
} |
Q:
Why are some of the Stunts in The Expanse RPG labelled 'Core'?
The system for The Expanse is the AGE system, so I'm hoping someone with another game which uses AGE can answer this. Neither The Expanse core rules nor the Blue Rose RPG have any rules about it!
In all the lists of stunts, the first few have the label (Core) written before their name. For instance the first five of the General Combat Stunts are:
(Core) Adrenaline Rush
(Core) Momentum
(Core) Duck and Weave
Take Cover
Guardian Angel
What does Core mean? Does it have a game mechanic effect which applies to using or choosing those particular stunts?
A:
Core stunts are simply the suggested stunts for each list. The tag has no mechanical effect. This blog post on the publisher's site clarifies that.
Every stunt list has labeled Core Stunts. These have low or variable
costs, and are generally useful, so when you can’t decide on your
stunts, these are your picks.
| {
"pile_set_name": "StackExchange"
} |
Q:
django model methods not accessible in templates
I've used model methods many times in templates, but for some reason on this project I'm running into a problem where I can't access the methods in the templates. Take for example this model:
class Post(models.Model):
'''
Data about blog posts. The guts of everything.
'''
blog = models.ForeignKey(PersonalBlog)
title = models.CharField(max_length=50)
body = models.TextField()
create_date = models.DateTimeField(auto_now_add=True)
active = models.BooleanField(default=True)
slug = models.SlugField(unique=True, blank=True)
def get_absolute_url(self):
from django.core.urlresolvers import reverse
return reverse('blog-post', kwargs={'blog':self.blog.slug, 'post':self.slug})
def hello(self):
return 'hello'
And then in the template if I do something like:
{% for p in posts %}
<a href="{{ p.get_absolute_url }}"><h3>{{ p.title }}</h3></a>
{% endfor %}
I don't get anything back from get_absolute_url. After validating that the method works correctly in terminal, I made a dummy method called hello above. That returns in terminal as well, but nothing shows up in the template. I've restarted the server, and stood on my head while forcing reload. Nothing seems to be working for something that usually is trivial.
I'm guessing it's going to be something stupid on my part, but I haven't been able to find it after way too long of troubleshooting something so simple. Any ideas?
A:
I don't know why I overlooked it, but the problem was in the view that created the posts object. I'm using TastyPie and in the API call the method was not accessible. Needed to change the API resource to expose the function.
| {
"pile_set_name": "StackExchange"
} |
Q:
Android - Gradle causes lots of troube
with the newest version of Android Studio I'm forced to create my apps with Gradle.
I get several issues with this.
1) At first: Why should I use Gradle at all? The traditional structure was logical and efficient.
2) The app takes much longer for compiling because the Gradle excecutioner (or how this thing is called) needs to do some things every time. Any way to avoid this?
3) My SVN is going crazy when working together with other people. It adds/removes files for scheduling, adding a library is not working and the settings are in chaos sometimes. Any best practices how to virtually enable SVN support for multi-users? I checked the .gradle files and ignored all those folders and files from my SVN but still the same issues.
Thanks!
Ronny
A:
I agree that Gradle adds a lot of unneeded complexity (for many projects), especially since it is not properly integrated into the IDE yet (i.e. a lot of file editing is required instead of changing options via configuration dialogs). That said, so much more can be achieved (build wise) by using Gradle, and it is definitely the right way to go - I just think they are forcing it on us prematurely. It is sad that they are removing the option to use the old build method from Android Studio, but this seems to be the way it is going.
I do think that eventually they will properly integrate Gradle into the IDE (they have already added a lot of stuff since initial release) at which point it will be quite painless to use and the advanced features will be easily available to all. This is something I think we can all look forward to.
At this point though, with Android Studio still in the early release alpha phase (and let's be honest, Google has a track record of leaving products in pre-release/beta stages for years) it is probably better to not use Android Studio unless you really need the features offered by the Gradle build system.
The best solution for users that do not require any of the advanced features offered by Gradle is to use IntelliJ IDEA Community Edition instead of Android Studio. IntelliJ being the foundation on which Android Studio is built offers everything in AS, but still allows use of the original build system (in addition to Gradle). The transition is painless and you can keep Android Studio around if you ever need to use it for some reason.
I know that this does not directly answer your questions, but instead it might help you not have to ask them :)
As a final note, one thing you could do to speed up Gradle build is to set it to offline mode, as follows:
Enter settings File -> Settings
Go to: Compiler -> Gradle
Toggle the Offline mode setting at the bottom
| {
"pile_set_name": "StackExchange"
} |
Q:
Visual Studio Express 2013 to 2017
I am having issues porting visual Studio Express solutions over to Visual Studio 2017. I have attempted to follow the advice in this article which has not solved the issue.
When I load my solution in 2017, I get an error stating "one or more projects in the solution were not loaded correctly" with the following output:
C:\Users\mikegjohn\Documents\Service Hub\Service_Hub\WindowsApplication1\Service_Hub.vbproj : error : The imported project "C:\Program Files (x86)\Microsoft Visual Studio\2017\Community\MSBuild\Microsoft\VisualStudio\v15.0\SSDT\Microsoft.Data.Tools.Schema.Sql.UnitTesting.targets" was not found. Also, tried to find "Microsoft\VisualStudio\v15.0\SSDT\Microsoft.Data.Tools.Schema.Sql.UnitTesting.targets" in the fallback search path(s) for $(MSBuildExtensionsPath32) - "C:\Program Files (x86)\MSBuild" . These search paths are defined in "C:\Users\mikegjohn\AppData\Local\Microsoft\VisualStudio\15.0_825df01c\devenv.exe.config". Confirm that the path in the declaration is correct, and that the file exists on disk in one of the search paths. C:\Users\mikegjohn\Documents\Service Hub\Service_Hub\WindowsApplication1\Service_Hub.vbproj
My solution explorer shows nothing and i cannot view any of the properties.
Can anyone point me in the right direction?
A:
I managed to fix this with the help of Lex Li Jun. I reinstalled a number of SQL modules which were left out on the standard VS2017 package and this solved my problem!
| {
"pile_set_name": "StackExchange"
} |
Q:
Adobe Analytics DTM custom script prop not setting
I am trying to show the last time I made a published change and the current library version
I created a data element Global - Example:
return "DTM:" + _satellite.publishDate.split(" ")[0] + "|" + "Adobe:" + s.version;
Then I set a prop to my %Global - Example%.
It doesn't work. So I tried to debug in the console. When console.log("DTM:" + _satellite.publishDate.split(" ")[0] + "|" + "Adobe:" + s.version); it works in the console and I get the the last publish date and the current version of the library. However, it won't work for some reason in dtm.
A:
Using a Data Element in this case will have an impact on timing.
If you add your code to the Adobe Analytics Custom Code section of a rule or AA Global Code you should be able to set your prop just fine.
s.prop1 = _satellite.publishDate.split(" ")[0] + "|" + "Adobe:" + s.version);
Hope this helps.
| {
"pile_set_name": "StackExchange"
} |
Q:
How can I output the "Name" value in pandas?
After I do an iloc (df.iloc[3]) , I get an output with all the column names and their values for a given row.
What should the code be if I only want to out put the "Name" value for the same row?
Eg:
Columns 1 Value 1
Columns 2 Value 2
Name: Row 1, dtype: object
So, in this case "Row 1".
A:
>>> df = pd.DataFrame({'Name': ['Uncle', 'Sam', 'Martin', 'Jacob'], 'Salary': [1000, 2000, 3000, 1500]})
>>> df
Name Salary
0 Uncle 1000
1 Sam 2000
2 Martin 3000
3 Jacob 1500
df.iloc[3] gives the following:
>>> df.iloc[3]
Name Jacob
Salary 1500
Name: 3, dtype: object
However, df.iloc[3, 'Name'] throws the following exception:
>>> df.iloc[3, 'Name']
Traceback (most recent call last):
File "/home/nikhil/anaconda3/lib/python3.7/site-packages/pandas/core/indexing.py", line 235, in _has_valid_tuple
self._validate_key(k, i)
File "/home/nikhil/anaconda3/lib/python3.7/site-packages/pandas/core/indexing.py", line 2035, in _validate_key
"a [{types}]".format(types=self._valid_types)
ValueError: Can only index by location with a [integer, integer slice (START point is INCLUDED, END point is EXCLUDED), listlike of integers, boolean array]
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/home/nikhil/anaconda3/lib/python3.7/site-packages/pandas/core/indexing.py", line 1418, in __getitem__
return self._getitem_tuple(key)
File "/home/nikhil/anaconda3/lib/python3.7/site-packages/pandas/core/indexing.py", line 2092, in _getitem_tuple
self._has_valid_tuple(tup)
File "/home/nikhil/anaconda3/lib/python3.7/site-packages/pandas/core/indexing.py", line 239, in _has_valid_tuple
"[{types}] types".format(types=self._valid_types)
ValueError: Location based indexing can only have [integer, integer slice (START point is INCLUDED, END point is EXCLUDED), listlike of integers, boolean array] types
Use df.loc[3, 'Name'] instead:
>>> df.loc[3, 'Name']
'Jacob'
| {
"pile_set_name": "StackExchange"
} |
Q:
Categories columns in second row to the first row in DataFrame Pandas?
I had this database:
Unnamed=0 2001 2002 2003
General 456 567 543
Cleaning 234 234 344
After transpose data, I got the variables in the second row in Jupyter Notebook:
df = df.T.rename_axis('Date').reset_index()
df
Date 1 2
1 General Cleaning
2 2001 456 234
3 2002 567 234
4 2003 543 344
How do I place them in the first row in the DataFrame so I can group and manipulate the values?
Date General Cleaning
1 2001 456 234
2 2002 567 234
3 2003 543 344
A:
You were close with the attempt you showed above. Instead, reset the index to move the dates from the index to the first column, and then rename that date column from index to Date:
df = df.T.reset_index().rename(columns={'index':'Date'})
df
Output:
Date General Cleaning
0 2001 456 234
1 2002 567 234
2 2003 543 344
| {
"pile_set_name": "StackExchange"
} |
Q:
Is it possible to get mouse events from a Spark Line or Path object in Flex 4?
I'm drawing an arrow as a <s:Path> and I need to get notified when the mouse is over it. How can I do that?
The arrow is an element of a Group container.
I tried registering for MOUSE_OVER events for both the container and the arrow and none seem to fire...
A:
Path doesn't extend InteractiveObject and therefore does not allow fur mouse interaction. Your best bet is to wrap up your path inside another component that can extend InteractiveObject, such as a Sprite.
You can make your own "ClickablePath" class.
| {
"pile_set_name": "StackExchange"
} |
Q:
Invoker ultimate(DOTA 2) combination... How is it calculated?
While playing DOTA 2 with invoker I thought how the total combination of his ultimate calculated.
Description:
He has 9 element. lets say 3(blue) , 3 (pink) and 3(yellow) . Every time he can choose 3 element from there. How many way is there to pick? Answer is 10. I didn't get it.
A dumb question to start with sorry for that.
Here is the picture with all combination
A:
The general solution for this is calculated using Stars and bars (Theorem 2 on Wikipedia).
For n = k = 3, you get C(n+k-1,n) = C(3+3-1,3-1) = C(5,2) = 10.
| {
"pile_set_name": "StackExchange"
} |
Q:
NSStream, NSError, error code
I'm developing small FTP upload app. for mac (10.6 if it matters)
Have problem with NSStream, actually I cannot understand how to find our error by its code.
NSError code=14 domain=NSPOSIXErrorDomain
Where to check what does 14 means?
Thank you.
Just in case here is my code (maybe you can also tell me why I have an error)
NSString * filePath;
NSInputStream * fStream;
NSStreamStatus * status;
NSError * error;
filePath = @"/Users/Vic/Desktop/ftptest.txt";
fStream = [NSInputStream inputStreamWithFileAtPath:filePath];
[fStream open];
uint8_t * buffer;
NSInteger bytesRead;
bytesRead = [fStream read:buffer maxLength:32768];
error = [fStream streamError];
NSLog(@"error code=%d domain=%@",error.code,error.domain);
A:
Each domain has the error codes in a different place, but there's a summary in the Error Handling Guide for Cocoa. There's even a summary of some of the POSIX ones there. 14 is EFAULT.
Lots of times if you know the underlying system call you can view its man page to get more information about the error code. For instance in this case, you can invoke man 2 read from the terminal and it states:
[EFAULT] Buf points outside the allocated address space.
| {
"pile_set_name": "StackExchange"
} |
Q:
Is L2TP preshared key anywhere stored in plaintext on w2k8?
Some time ago I have configured l2tp vpn server on w2k8 rras that uses preshared key. Now I am trying to setup another client but the key that I have documented does not seem to be correct. I have full access to server and one client that both have correct key remembered but asterisks are all I can see. Any ideas where to look?
A:
The password is stored in an encrypted form that's next to impossible to manually decrypt. PSK VPN connections really weren't meant for your use case, Certificate based authentication was, which is why you're finding it hard to do what you want.
| {
"pile_set_name": "StackExchange"
} |
Q:
Razor syntax inside attributes of html elements (ASP MVC 3)
I have a table with repeating customer rows, I would like to add the customer ID to the ID attribute of my table rows like this:
<tr id="row<customer id>"></tr>
I try adding this code:
@foreach(var c in Model) {
<tr id="[email protected]"></tr>
}
Which gives me the following output:
<tr id="[email protected]"></tr>
<tr id="[email protected]"></tr>
etc.
But I would like it to be:
<tr id="row1"></tr>
<tr id="row2"></tr>
etc.
I also tried to add <tr>row@{c.id}</tr> but it did not work..
A:
have you tried <tr>row@(c.id)</tr>?
The actual reason why this doesn't work is because your [email protected] matches the regex for an email address. So the parser assumes it's an email and not actually an attempt to call code. The reason row@{c.id} doesn't work is because the @{} doesn't output and is meant to contain blocks of code.
When in doubt you should use @() as it will force what's contained between the () to be parsed as code.
| {
"pile_set_name": "StackExchange"
} |
Q:
Vagrant box_check_update error
I try to use a Vagrant environment. I have Vagrantfile and every other needs. I use Vagrant 1.4.3 version on Ubuntu 12.04.03.
After vagrant up get following errors.
vm:
* The following settings shouldn't exist: box_check_update
* The box 'ubuntu/vivid64' could not be found.
I've checked my Vagrantfile, and see config.vm.box_check_update = false.
Ubuntu/vivid64 is here: https://atlas.hashicorp.com/ubuntu/boxes/vivid64
A:
config.vm.box_check_update and config.vm.box = "ubuntu/vivid64" are features of vagrant 1.5 (see blog announcement https://www.vagrantup.com/blog/vagrant-1-5-and-vagrant-cloud.html and https://www.vagrantup.com/blog/feature-preview-vagrant-1-5-boxes-2-0.html)
upgrade to Vagrant 1.5 (or better latest version) and it will run fine.
| {
"pile_set_name": "StackExchange"
} |
Q:
Unable to generate signed APK (java.lang.RuntimeException)
I'm able to run the app on my device using ADB, however, when I am trying to generate a signed APK, the console is throwing all this:
java.lang.RuntimeException: Job failed, see logs for details
at com.android.build.gradle.internal.transforms.ProGuardTransform.transform(ProGuardTransform.java:196)
at com.android.build.gradle.internal.pipeline.TransformTask$2.call(TransformTask.java:221)
at com.android.build.gradle.internal.pipeline.TransformTask$2.call(TransformTask.java:217)
at com.android.builder.profile.ThreadRecorder.record(ThreadRecorder.java:102)
at com.android.build.gradle.internal.pipeline.TransformTask.transform(TransformTask.java:212)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.gradle.internal.reflect.JavaMethod.invoke(JavaMethod.java:73)
at org.gradle.api.internal.project.taskfactory.IncrementalTaskAction.doExecute(IncrementalTaskAction.java:46)
at org.gradle.api.internal.project.taskfactory.StandardTaskAction.execute(StandardTaskAction.java:39)
at org.gradle.api.internal.project.taskfactory.StandardTaskAction.execute(StandardTaskAction.java:26)
at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter$1.run(ExecuteActionsTaskExecuter.java:121)
at org.gradle.internal.progress.DefaultBuildOperationExecutor$RunnableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:336)
at org.gradle.internal.progress.DefaultBuildOperationExecutor$RunnableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:328)
at org.gradle.internal.progress.DefaultBuildOperationExecutor.execute(DefaultBuildOperationExecutor.java:199)
at org.gradle.internal.progress.DefaultBuildOperationExecutor.run(DefaultBuildOperationExecutor.java:110)
at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.executeAction(ExecuteActionsTaskExecuter.java:110)
at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.executeActions(ExecuteActionsTaskExecuter.java:92)
at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.execute(ExecuteActionsTaskExecuter.java:70)
at org.gradle.api.internal.tasks.execution.OutputDirectoryCreatingTaskExecuter.execute(OutputDirectoryCreatingTaskExecuter.java:51)
at org.gradle.api.internal.tasks.execution.SkipUpToDateTaskExecuter.execute(SkipUpToDateTaskExecuter.java:62)
at org.gradle.api.internal.tasks.execution.ResolveTaskOutputCachingStateExecuter.execute(ResolveTaskOutputCachingStateExecuter.java:54)
at org.gradle.api.internal.tasks.execution.ValidatingTaskExecuter.execute(ValidatingTaskExecuter.java:60)
at org.gradle.api.internal.tasks.execution.SkipEmptySourceFilesTaskExecuter.execute(SkipEmptySourceFilesTaskExecuter.java:97)
at org.gradle.api.internal.tasks.execution.CleanupStaleOutputsExecuter.execute(CleanupStaleOutputsExecuter.java:87)
at org.gradle.api.internal.tasks.execution.ResolveTaskArtifactStateTaskExecuter.execute(ResolveTaskArtifactStateTaskExecuter.java:52)
at org.gradle.api.internal.tasks.execution.SkipTaskWithNoActionsExecuter.execute(SkipTaskWithNoActionsExecuter.java:52)
at org.gradle.api.internal.tasks.execution.SkipOnlyIfTaskExecuter.execute(SkipOnlyIfTaskExecuter.java:54)
at org.gradle.api.internal.tasks.execution.ExecuteAtMostOnceTaskExecuter.execute(ExecuteAtMostOnceTaskExecuter.java:43)
at org.gradle.api.internal.tasks.execution.CatchExceptionTaskExecuter.execute(CatchExceptionTaskExecuter.java:34)
at org.gradle.execution.taskgraph.DefaultTaskGraphExecuter$EventFiringTaskWorker$1.run(DefaultTaskGraphExecuter.java:248)
at org.gradle.internal.progress.DefaultBuildOperationExecutor$RunnableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:336)
at org.gradle.internal.progress.DefaultBuildOperationExecutor$RunnableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:328)
at org.gradle.internal.progress.DefaultBuildOperationExecutor.execute(DefaultBuildOperationExecutor.java:199)
at org.gradle.internal.progress.DefaultBuildOperationExecutor.run(DefaultBuildOperationExecutor.java:110)
at org.gradle.execution.taskgraph.DefaultTaskGraphExecuter$EventFiringTaskWorker.execute(DefaultTaskGraphExecuter.java:241)
at org.gradle.execution.taskgraph.DefaultTaskGraphExecuter$EventFiringTaskWorker.execute(DefaultTaskGraphExecuter.java:230)
at org.gradle.execution.taskgraph.DefaultTaskPlanExecutor$TaskExecutorWorker.processTask(DefaultTaskPlanExecutor.java:123)
at org.gradle.execution.taskgraph.DefaultTaskPlanExecutor$TaskExecutorWorker.access$200(DefaultTaskPlanExecutor.java:79)
at org.gradle.execution.taskgraph.DefaultTaskPlanExecutor$TaskExecutorWorker$1.execute(DefaultTaskPlanExecutor.java:104)
at org.gradle.execution.taskgraph.DefaultTaskPlanExecutor$TaskExecutorWorker$1.execute(DefaultTaskPlanExecutor.java:98)
at org.gradle.execution.taskgraph.DefaultTaskExecutionPlan.execute(DefaultTaskExecutionPlan.java:626)
at org.gradle.execution.taskgraph.DefaultTaskExecutionPlan.executeWithTask(DefaultTaskExecutionPlan.java:581)
at org.gradle.execution.taskgraph.DefaultTaskPlanExecutor$TaskExecutorWorker.run(DefaultTaskPlanExecutor.java:98)
at org.gradle.internal.concurrent.ExecutorPolicy$CatchAndRecordFailures.onExecute(ExecutorPolicy.java:63)
at org.gradle.internal.concurrent.ManagedExecutorImpl$1.run(ManagedExecutorImpl.java:46)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at org.gradle.internal.concurrent.ThreadFactoryImpl$ManagedThreadRunnable.run(ThreadFactoryImpl.java:55)
at java.lang.Thread.run(Thread.java:745)
Caused by: java.io.IOException: Please correct the above warnings first.
at proguard.Initializer.execute(Initializer.java:473)
at proguard.ProGuard.initialize(ProGuard.java:233)
at proguard.ProGuard.execute(ProGuard.java:98)
at com.android.build.gradle.internal.transforms.BaseProguardAction.runProguard(BaseProguardAction.java:61)
at com.android.build.gradle.internal.transforms.ProGuardTransform.doMinification(ProGuardTransform.java:253)
at com.android.build.gradle.internal.transforms.ProGuardTransform.access$000(ProGuardTransform.java:63)
at com.android.build.gradle.internal.transforms.ProGuardTransform$1.run(ProGuardTransform.java:173)
at com.android.builder.tasks.Job.runTask(Job.java:47)
at com.android.build.gradle.tasks.SimpleWorkQueue$EmptyThreadContext.runTask(SimpleWorkQueue.java:41)
at com.android.builder.tasks.WorkQueue.run(WorkQueue.java:282)
... 1 more
I'm using Android Studio 3.1.3.
The app is otherwise working fine on my physical device when I'm running the app on it using ADB, it's only this signed APK thing that's giving all this.
A:
I seen previous accepted answer but that wasn't best solution. Becuase Why we are going to scrafice our app sequrity and also app size.
I also faced same problem. I update all old dependency and ClassPaths from Project level gradle files.
classpath 'com.android.tools.build:gradle:3.3.1'
classpath 'com.google.gms:google-services:4.2.0'
You can try one time, This can solve your issue.
Thanks.
| {
"pile_set_name": "StackExchange"
} |
Q:
Is there a name for a rhetorical technique where a deceptive exaggeration is used openly and with admission in order to effect a desired emotion?
I'm talking about a specific usage of language where the deceit is passive and consistent - an arguer might use an exaggerated word, or a word entirely incorrectly, to alter an audience's reception to an argument, but without actively maintaining the deceit of argument. Importantly, a person employing this technique is knowingly and intentionally being deceitful - it is not just a difference of opinion.
It is perhaps much easier to explain via example:
Arguer A: "We should no longer associate with Person C, as they screamed at us over this simple misunderstanding."
Arguer B: "Person C did not scream at us. I was present, and Person C only slightly raised their voice."
Arguer A: "That is just how I define the word 'screaming.' We don't need to associate with someone who will subject us to screaming conniptions over simple misunderstandings."
In a way, I am almost thinking of a dysphemism - in this case the word choice is used to intentionally increase the emotional impact of the word, even though it is understood to be a lie. If the use of exaggeration to alter the truth is confronted, the arguer might openly admit to the exaggeration, but then continue to use the exaggeration anyway because it will give the audience a certain emotional impression regardless of the deceit being laid bare.
A more insidious example might be:
Arguer A: "Person C is a felon, and can not be trusted to interact safely with the public if we employ them."
Arguer B: "Person C was convicted of possession of cannabis, and has no history of violent crimes."
Arguer A: "You're right, but person C is still a felon, and you can't trust felon criminals to respect people's safety."
Here the word "felon" is not an exaggeration, but is still being used deceptively to give listeners a certain impression about Person C, even though the arguer admits to the deception. By continuing to use the word, the truth of the matter is dulled by the emotional response the word inspires.
A:
Welcome to ELU, Zack. Your question spreads across a number of fields about which we have to be clear: language use, rhetoric and logical argument.
The technical term for the rhetorical use of exaggeration is hyperbole. Actually, this is only the Greek term for exaggeration, which is derived from Latin". It just happens that the use of hyperbole is (or can be) very effective on the emotions of an audience. You could say a hyperbolic use is metaphorical, though strictly that is not quite so. Nevertheless, the meaning intention of an hyberbole, like your example of the word scream is one in which the meaning intention of Arguer A is not to claim that the person literally screamed. If that had been the intention, then your example would not count as an example. Arguer B would simply be right: Arguer A would simply not be telling the truth.
However, Even here, it is possible that what we have is a simple difference of subjective perception: what one person takes as forceful argument may be received as screaming - indeed this is a common feature of domestic quarrels!.
Your second case is a bit different. Here there is no hyperbole. It is a misuse of reasoning. It is almost a case of the logical fallacy known as illicit conversion. And example would be:
All criminals come from poor families.
Fred comes from a poor family.
Therefore Fred is a criminal.
This is a fallacy that many a politician exploits. But the false nature of it is obvious:
All As is Bs and
Fred is an A entails that
Fred is a B - not the other way around (hence the term illicit conversion)
So there are two different types of fallacy going on here. What would link them to rhetoric would be the intention to deceive an audience.
The sort of phenomena are hard to define as a single class of language use or rhetoric. Think of photographs. We can take a picture and most people to enhance and modify the picture to some degree. You can enhance the colour and light and shade. You can darken the lighting in a picture of a political opponent and enhance lines on her face or shadow round his jaw. Or you can highlight the visual strengths of your favourite politician. Are these visual deception, or just visual 'hyperbole', highlighting how you feel and how, therefore, everyone else should feel. When does it move from that to deception? It's a widish grey area.
Similarly, the use even of illicit conversion covers its own grey area.
At some point, hyperbole (and its opposite, litotes) may cross the threshold into outright deception. One such case was the calling of a failure by a senior UK government officer to acknowledge a statement of the full truth in a story some year ago involving an intervention by the UK Crown in the governance of Australia some years ago as "an economical use of the truth" was a compromise between admitting that the person in question had been dishonest and denying that anything untoward had happened.
You could try to coin the term dysphemism. It's clever. But it would be covering a much too wide a range of utterances than euphemism. Indeed, it would render my example a case of both euphemism and dysphemism at the same time. So they would make very odd antonyms,
| {
"pile_set_name": "StackExchange"
} |
Q:
PDO : Need to escape string or not ?
I use this code to insert some data into my database.
I adapt my previous code based on mysqli to use PDO now.
For the 2 parameters name and id, do i need to escape them using a function like mysqli_real_escape_string with PDO ? or is it OK to pass these params direclty in the query ?
<?php
try
{
$pdo = new PDO('mysql:host='.$servername.';port='.$dbport.';dbname='.$dbname.'', $username, $decodedPwd);
$pdo->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$json = $_POST['jsonData'];
$id = $json["id"]
$name = $json["name"]
$pdo->beginTransaction();
// do request
$pdo->query('INSERT INTO test(id, name) VALUES ('$id', '$name')');
$pdo->commit();
echo 'Everything is OK';
}
catch(Exception $e)
{
$pdo->rollback();
echo 'An error occurred :<br />';
echo 'Error : '.$e->getMessage().'<br />';
echo 'N° : '.$e->getCode();
exit();
}
A:
You need to prepare your statement, try this:
$query = $pdo->prepare('INSERT INTO test(id, name) VALUES (:theid, :thename)');
$query->execute(array(
'theid' => $id,
'thename' => $name
));
| {
"pile_set_name": "StackExchange"
} |
Q:
Delete vertices of degree 2 and rewire graph
I want to delete all vertices of degree 2 from a graph and rewire it.
Given a graph like graphA, I want to obtain graphB.
edges1 = {1 <-> 2, 2 <-> 3, 3 <-> 4, 4 <-> 5, 5 <-> 6, 5 <-> 7,
1 <-> 9, 1 <-> 8};
graphA = Graph[edges1, VertexLabels -> "Name"]
edges2 = {1 <-> 9, 1 <-> 8, 1 <-> 5, 5 <-> 6, 5 <-> 7};
graphB = Graph[edges2, VertexLabels -> "Name"]
I have this simple algorithm, which I find easy to implement using a for loop in Python or Java.
Get indices of all nodes with degree = 2.
Pick a node of degree = 2 (call it N) and get its end points X and Y.
Rewire X to Y, delete N
Repeat 1 until there are no more nodes of degree 2
I know using a for loop would be painfully slow in big graphs. So what's the Mathematica-savvy way of doing this?
A:
I've never played with Graphs much in Mathematica. Call it laziness, whatever, but I just never had a need. So, what better time to learn?
Here's how I approached it.
First we define a function that uses VertexContract to "rewire" the graph at every degree 2 vertices. Since this will be iterative, we only want it to act when the graph still contains a vertices with degree 2.
contract[graph_] /; MemberQ[VertexDegree[graph], 2] :=
Module[{vd = VertexDegree[graph], vl = VertexList[graph], loc},
loc = Cases[EdgeList[graph], UndirectedEdge[a___, b : vl[[First@FirstPosition[vd, 2]]], c___] :> {a, b, c}][[1]];
VertexContract[graph, loc]];
contract[graph_] := Graph[EdgeList[graph], VertexLabels -> "Name"];
To use it, we can use FixedPoint:
FixedPoint[contract, graphA]
To see how it progress, we can use FixedPointList:
FixedPointList[contract, graphA]
On more complicated graphs:
FixedPointList[contract, RandomGraph[{10, 11}, VertexLabels -> "Name"]]
A:
The following works on v9 and makes use of the Orderless attribute, which for unknown reasons isn't attached to UndirectedEdge by default
reduceG[g_Graph] := Module[{t, el, newEl, ue, p},
SetAttributes[ue, Orderless];
NestWhile[(
t = VertexList[#][[p[[1, 1]]]];
el = ue @@@ EdgeList[#];
newEl = el /. {x___, ue[t, a_], y___, ue[t, b_], z___} :> Union@{x, y, z, ue[a, b]};
Graph[newEl /. ue :> UndirectedEdge, VertexLabels -> "Name"]) &,
g,
(p = Position[VertexDegree[#], 2, 1, 1]) != {} &]
]
reduceG[Graph[edges1]]
| {
"pile_set_name": "StackExchange"
} |
Q:
gcc compiling error: member of nested class A in template class Table is not visible in nested friend class. Why?
I am trying to compile some code in mingw32 on windows XP and I got an error. So, I have write a simplified version of that code and got same error.
Here it is:
template <class T>
class Table
{
public:
class A
{
private:
int nEntry;
friend class B;
};
class B : public A
{
public:
void Remove()
{
nEntry = 1;
}
};
};
Compiler error message:
E:\cbProjects\projects\1\main.cpp||In member function 'void Table<T>::B::Remove()':|
E:\cbProjects\projects\1\main.cpp|24|error: 'nEntry' was not declared in this scope|
||=== Build finished: 1 errors, 0 warnings ===|
Where I can read the items why it's so? (links will be usefull - it may be happen that some other similar errors or compiler bags can appear)
A:
Within a template, member access must sometimes be preceded by an explicit this->, as in this case. You can make your code work this way:
this->nEntry = 1;
| {
"pile_set_name": "StackExchange"
} |
Q:
Does `dd` work on physical level or on filesystem level?
When you delete a file from a device, let's say an USB stick, then (without doing any further stuff) only the entry in the filesystem is deleted, the raw bytes of this file are still on the device (that's why file recovery tools work by scanning the physical sectors on the drive one by one).
Now, if I do
dd if=/path/to/usbdrive of=/backup/usbdrive.img
the content of USB drive will be copied to the specified file.
When arriving at the location where the deleted file was, will dd copy zeros or will it copy the file content that physically is still there?
A:
dd merely copies an input stream of bytes to an output stream of bytes. Both input and output must be an actual file. It won't operate on a directory. So in your example above, if /path/to/usbdrive is a device node (i.e. /dev/usb or whatever) then it does a block-level copy since /dev/usb is a block device. It will copy the file content that was still there in that case. But you wouldn't be able to point the input stream to the file you just deleted because you wouldn't have the handle to it anymore.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to check if any child exist in jquery
I have an <div> with several child's inside it which is removed one after another and I want to check when all elements inside are removed .
I tried checking with if($('#data').html()=="") but its not working, probably because of white spaces and tab spaces.
Keeping track of each and every elements and checking can be done but I am sure it will be worse idea for this simple task so is there any easy way to do this ?
A:
if($('#data').children().length > 0) is the best solution in my opinion
or shorter if($('#data').children().length)
API
| {
"pile_set_name": "StackExchange"
} |
Q:
Deleting Azure App Registration from Linux Terminal
I wanted to know if there is a way to delete Azure App Registrations from the Linux Terminal? I couldn't find the command for it in the azure documentation
A:
You can install both Azure Powershell and the Azure CLI on Linux.
https://docs.microsoft.com/bs-latn-ba/powershell/azure/azurerm/install-azurermps-maclinux?view=azurermps-4.4.1
https://docs.microsoft.com/en-us/cli/azure/install-azure-cli?view=azure-cli-latest
To delete the app registrations:
1.Run the Login-AzureRMAccount command and log in again using your global admin account.
2. Enter Get-AzureRmADApplication to get a list of all App Registrations.
3. Run Remove-AzureRmADApplication -objectid <ObjectId from above> for each App Registration found in your Azure Active Directory, making sure you enter “Y” to confirm that you want to delete it.
You can also use the script below to find and delete all App Registrations in one shot:
$ObjectIds = (Get-AzureRmADApplication).ObjectId
For ($i=0; $i -lt $ObjectIds.Length; $i++)
{
Remove-AzureRmADApplication -objectid $ObjectIds[$i]
}
| {
"pile_set_name": "StackExchange"
} |
Q:
How can I authenticate against ADXProxy using app key authentication?
I am trying to access an Azure Application Insights resource via Redash, using the (preview) ADXProxy feature.
I've created an App Registration in Azure, and I've got some proof-of-concept python code which can successfully access my Application Insights resource and execute a Kusto query (traces | take 1) using an application token:
import azure.kusto
import azure.kusto.data.request
import msal
cluster = 'https://ade.applicationinsights.io/subscriptions/<MY_SUBSCRIPTION>/resourcegroups/<MY_RESOURCE_GROUP>/providers/microsoft.insights/components/<MY_APP_INSIGHTS_RESOURCE>'
app_id = '<MY_APP_ID>'
app_key = '<MY_SECRET>'
authority_id = '<MY_AAD_SUBSCRIPTION_ID>'
def run():
app = msal.ConfidentialClientApplication(
client_id=app_id,
client_credential=app_key,
authority='https://login.microsoftonline.com/<MY_AAD_SUBSCRIPTION_ID>')
token = app.acquire_token_for_client(['https://help.kusto.windows.net/.default'])
kcsb = azure.kusto.data.request.KustoConnectionStringBuilder.with_aad_application_token_authentication(
connection_string=cluster,
application_token=token['access_token']
)
client = azure.kusto.data.request.KustoClient(kcsb)
result = client.execute('<MY_APP_INSIGHTS_RESOURCE>', 'traces | take 1')
for res in result.primary_results:
print(res)
return 1
if __name__ == "__main__":
run()
However, Redash doesn't support application token authentication: it uses application key authentication, making a call like:
kcsb = azure.kusto.data.request.KustoConnectionStringBuilder.with_aad_application_key_authentication(
connection_string = cluster,
aad_app_id = app_id,
app_key = app_key,
authority_id = '<MY_AAD_SUBSCRIPTION_ID>'
)
I can't successfully connect to my App Insights resource using this type of flow. If I substitute this KustoConnectionStringBuilder into my program above, I get an exception telling me:
The resource principal named https://ade.applicationinsights.io was not found in the tenant named <MY_AAD_SUBSCRIPTION_ID>. This can happen if the application has not been installed by the administrator of the tenant or consented to by any user in the tenant. You might have sent your authentication request to the wrong tenant.
Is there something I can do in code or Azure Portal configuration to connect my 'tenant' to the ade.applicationinsights.io resource principal and get this connection working?
A:
Adxproxy supports only tokens minted by Azure Active Directory (AAD). The token must be created for an Azure Data Explorer cluster (ADX), that you own. If you don't have your own ADX cluster, and for whatever reason you want to access your Application Insights resources via Adxproxy, you can always authenticate to 'https://help.kusto.windows.net' and use that token.
| {
"pile_set_name": "StackExchange"
} |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.