INSTRUCTION
stringlengths 25
999
| RESPONSE
stringlengths 0
999
| SOURCE
stringlengths 16
38
| METADATA
dict |
---|---|---|---|
Add a file to an MSI
How can I add a file to a precompiled msi and configure it such that when I run the msi the file is put into the program's application directory? I can add a file as a stream to the msi using msidb.exe /a but when I run the installer the file doesn't show up anywhere.
|
Use Orca to edit the msi file to tell the windows installer where to put the file. Read up on the **File**, **Directory** and **Component** tables on MSDN and start from there
|
stackexchange-stackoverflow
|
{
"answer_score": 4,
"question_score": 0,
"tags": "windows installer"
}
|
Find the form of $f(x,y)$ knowing the form of contour lines in the $XZ$ and $YZ$ planes
I am trying to find the form of $z=f(x,y)$. I know that:
Contour lines in the $XZ$ plane are of the form: $$z=A*ln(x)+B$$
(the $A$ and $B$ parameters vary with $y$)
Contour lines in the $YZ$ plane are of the form: $$z=Cy^2+Dy+E$$
(the $C$, $D$ and $E$ parameters vary with $x$)
What is then the form of $z=f(x,y)$ ?
|
I'm not sure what you mean by $A$ and $B$ varying with $y$ in the context of contour lines in the $XZ$ plane (and likewise for $x$ and $YZ$). I'll assume what you mean is that there is a function $z=f(x,y)$ and the first equation describes the relationship between $x$ and $z$ if you hold $y$ fixed and the second equation describes the relationship between $y$ and $z$ if you hold $x$ fixed.
Since the two expressions for $z$ have to be equal, the dependency of the parameters on $y$ in the first equation must be such that a quadratic function of $y$ results for all $x$. Since $\ln x$ takes different values for different $x$, this can only happen if $A$ and $B$ are both quadratic functions of $y$. Thus, the most general form for $z$ compatible with the given conditions is
$$z=(a_2y^2+a_1y+a_0)\ln x+b_2y^2+b_1y+b_0$$
with
$$ \begin{eqnarray} A&=&a_2y^2+a_1y+a_0\;,\\\ B&=&b_2y^2+b_1y+b_0\;,\\\ C&=&a_2\ln x+b_2\;,\\\ D&=&a_1\ln x+b_1\;,\\\ E&=&a_0\ln x+b_0\;.\\\ \end{eqnarray} $$
|
stackexchange-math
|
{
"answer_score": 3,
"question_score": 2,
"tags": "3d, tomography"
}
|
Ordinary Differential Equation rewriting
I've a certainly stupid question. I have the following dynamical system of autonomous ODEs.
\begin{align} \frac{dx_1}{dt}=f(x_1,x_2) \\\ \frac{dx_2}{dt}=g(x_1,x_2) \end{align}
May I change the system to:
$$ \frac{dx_1}{dx_2} = \frac{f(x_1,x_2)}{g(x_1,x_2)} $$
Thank you
|
It can be helpful if you are investigating the phase plane (portrait) of the given system of ODEs, since the dimension of your system is two. See the following link as an example, <
|
stackexchange-math
|
{
"answer_score": 0,
"question_score": 3,
"tags": "ordinary differential equations"
}
|
Which key mode is funk saxophone played in?
I am analysing the musical style of playing saxophone on dance beats, or dubstep, like in this song.
Would you characterise this as funk? And what is the key they use. My closest guess is a minor or major blues scale, but I could be totally wrong.
|
1. No. 2. C blues. Really, that's all I wanted to say.
|
stackexchange-music
|
{
"answer_score": 4,
"question_score": 1,
"tags": "theory, saxophone, key, modes"
}
|
Determine if the current user is above the record owner in the role hierarchy
I am looking to write a validation rule that prevents everyone from editing a record in a certain status, unless they are above the record owner in the role hierarchy.
So for example here is my fake hierarchy:
Role CEO -> Role Exec -> Role Drone
Once a drone has created a record and saved it as locked, the drone can not longer edit the record.
But the Exec or CEO can edit the record. Is this possible using a validation rule?
|
You cannot take away sharing access to the owner of the record, but you can prevent the owner from saving an edited record: $User.Id <> OwnerId where $User is the current user. Everything else is sharing based.
|
stackexchange-salesforce
|
{
"answer_score": 2,
"question_score": 1,
"tags": "validation"
}
|
My Downloads folder disappeared
In Windows 7, my _Downloads_ folder in my user directory disappeared. How can I recreate it? I just created as a new folder, but it does not have the special folder icon that it used to have. That means it is not a system folder.
How can I recover my original Downloads folder?
|
Please try with this answer, it's for Vista but might work for Windows 7. Check in the website, at the bottom, recover the Downloads registry key.
Restore missing Downloads folder due to missing link
|
stackexchange-superuser
|
{
"answer_score": 2,
"question_score": 1,
"tags": "windows 7"
}
|
Android device ID while unrooting phone
If I perform below steps,
1. I root Android phone,
2. From third party apps available on Play Store, I change 16 digit Android device id(Let say from **aaaaaaaaaaaaaaaaa** to **bbbbbbbbbbbbbbbb** )
3. And then again unroot the phonne.
Will unrooting the phone also change Android device id again or it will remain bbbbbbbbbbbbbbbb only?
Thanks in advance.
|
Unrooting your phone doesn't reverse the changes you made to `/system`. These changes are reversed only when you flash a stock / custom ROM. Of course, apps that you had installed earlier which had root privileges will not work
To sum up, your changed ID will remain till the next factory reset
|
stackexchange-android
|
{
"answer_score": 1,
"question_score": 1,
"tags": "applications, rooting, unrooting"
}
|
Data Paging with specific layout
I am trying to use data paging (not custom data paging - just normal inefficient paging) for about max 125 records, over 5 pages, 25 records per page. But most samples out there seem to be using a gridview or a datagrid, however I want each record to look like this:
Record 1 Title
Record 1 Description
Record 1 Time: Record 1 Contact:
Record 2 Title
Record 2 Description
Record 2 Time: Record 2 Contact:
etc etc, however with grids they result is like a table with bound fields for each column so I can't display it like that using paging, I thought of using a Repeater however I think I will need to use viewstate for that as it doesn't have paging built in and don't want to use ViewState as I have disabled this - can anyone help?
|
I think what you are looking for is a DataView or a Repeater
> The Repeater control is a basic templated data-bound list. It has no built-in layout or styles, so you must explicitly declare all layout, formatting, and style tags within the control's templates.
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "asp.net, paging"
}
|
AttributeError: 'Web3' has no attribute 'shh'
Web3.py version: 4.2.1 Python: 3.5.2 OS: linux geth version: 1.8.0-unstable
I am running geth with --shh flag and --rpcapi "admin,eth,net,web3,debug,shh"
from web3 import Web3, HTTPProvider
web3 = Web3(HTTPProvider('
print ("web3 =", web3.version.api) #4.2.1
print(web3.shh) #error occurs
When I try to run following code above, I am having following error:
Traceback (most recent call last):
File "dd.py", line 11, in <module>
print(web3.shh)
AttributeError: 'Web3' object has no attribute 'shh'
|
You need to do the following:
from web3.shh import Shh
Shh.attach(web3, "shh")
print(web3.shh)
|
stackexchange-ethereum
|
{
"answer_score": 1,
"question_score": 0,
"tags": "ethereumjs, web3.py"
}
|
Change of parameters on ouput graph
I have generated the graph, but i lost the settings, i would like to make the Plotmarkers slightly bigger. Is there anything to do this without redoing the computation?\rightarrow \operatorname{Sh}(X,\mathbb{Z})$ is the functor such that $j_!\mathcal{F}$ is the sheaf associated to the presheaf $$V\mapsto\left\\{\begin{array}{ll} \mathcal{F}(V) & \text{if $V\subset U$}\\\ 0 &\text{ otherwise}\end{array}\right. $$ The sheaf $j_!\mathcal{F}$ has the nice property that $(j_!\mathcal{F})_x=\mathcal{F}_x$ if $x\in U$ and $(j_!\mathcal{F})_x=0$ otherwise. From this it is obvious that the support of $j_!\mathbb{Z}$ is simply $U$ which is open.
This example also shows that there are sheaves with non closed support on any non discrete space !
|
stackexchange-math
|
{
"answer_score": 11,
"question_score": 5,
"tags": "algebraic geometry, sheaf theory"
}
|
IntentService life cycle
I have an IntentService that handles asynchronous calls to a Drupal Services module. Currently, I have my DrupalXmlRpcService object being initialized every time in onHandleIntent because I was under the impression that the service would be killed after the thread is finished. Should this object be initialized in the constructor of the IntentService object?
|
If your `DrupalXmlRpcService` object is expensive to create and you use it often, consider saving a reference in the global `Application` object, or possibly making it a singleton (make sure it's thread-safe). As for your question, if you send multiple Intents to the same service, `handleIntent()` might be called multiple times, so you might want to init in the constructor (but if it takes too long that might block the main thread).
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 2,
"tags": "android, service, intentservice"
}
|
Excel Macro to pick values from one table/array to another
I have the following "table" in an Excel sheet. I would like to do the following change:
Each time when there is a "x" I would like to report on another sheet the corresponding value of the first row and corresponding value of the first column:
"Original Table"
a1 a2 a3 a7 a8 a9
main main main main main main
u1 X X X
u2 X X
u3
u4
u5 X
u6 X
"Transformed Table":
u1 a1
u1 a2
u1 a3
u2 a2
u2 a3
u5 a1
u6 a3
Could you please tell me what is the Excel macro that will do this ?
Thank you in advance.
|
This assumes that sheet(2) exists (ie doesn't check). It will populate sheet(2) with the row and column headers as you've given in your example:
Sub ReportOnAllXs()
Dim r As Integer, c As Integer, r2 As Integer
r2 = 1
With Sheets(1)
For r = 3 To .Cells(.Rows.Count, "A").End(xlUp).row
For c = 2 To .Cells(1, .Columns.Count).End(xlToLeft).Column
If .Cells(r, c).Value = "X" Then
Sheets(2).Cells(r2, 1).Value = .Cells(r, 1).Value
Sheets(2).Cells(r2, 2).Value = .Cells(1, c).Value
r2 = r2 + 1
End If
Next
Next
End With
End Sub
I'm also assuming that you want the resulting row and column values in separate cells on sheet(2).
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "excel, copy, row, element, vba"
}
|
Having POCOs, Entities and ViewModels in a solution feels like overkill
The latest version of the Entity Framework got me in love, still at good as it is I don't like using entities objects as domain objects for all the obvious headaches, so what I'm doing is translating retrieved entity objects in my services and returning POCOs to whomever consumes the service. Thanks to automapper the translation from pocos to entities and back results in some easily maintainable code inside the services. Where things get hairy is when you add ViewModels to the picture and you end up mapping a viewmodel to the poco in the controller and then mapping the poco to the entity object in the service to be stored in the repository.
Would you consider this an overkill or am I being too nitpicking ?
|
It's not 'overkill' but 'overhead'. And It is inevitable when you want proper layering. The ViewModels belong to the UI layer, you don't want to mix that with the POCOs.
And while you might call it 'overkill' for a small app, which boundary would you rather sacrifice?
|
stackexchange-stackoverflow
|
{
"answer_score": 4,
"question_score": 1,
"tags": ".net, asp.net mvc, model view controller"
}
|
Any way to prevent an account from up/down voting or flagging?
Is there a badge/status that gives privileges to prevent few accounts from up/down voting posts? What happens if a family/friend/colleague who is a programmer who uses the same machine keeps up/down voting/ flagging just for the fun of it?
|
> Is there a badge/status that gives privileges to prevent few accounts from up/down voting posts?
That status is a diamond.
If someone is abusing their voting privileges to either cheat the system for their personal gain or make someone else's life miserable, flag one of their posts and we'll deal with it. Depending on the severity this may entail suspending their account, preventing them from voting or flagging for the duration of their suspension.
If someone is flagging just for the fun of it, well let's just say they'll learn **very** quickly that flags are not a toy for them to play with.
|
stackexchange-meta_stackoverflow
|
{
"answer_score": 12,
"question_score": -6,
"tags": "discussion"
}
|
Spurious high disk IOrate alerts from remote server
I have a server running on linode. The server is a headless Ubuntu 10.0.4 64 bit installation.
I have recently started getting high disk I/O alerts from the server. As far as I know, nothing much has changed on the server.
Is there a *nix utility that I can run on the server to either monitoring and log, or perhaps analyze an existing log in order to find out which process(es) are "trashing" the disk?
|
some ideas:
IOtop: <
Atop: <
Nmon: <
Collectl: <
|
stackexchange-superuser
|
{
"answer_score": 1,
"question_score": 1,
"tags": "ubuntu, performance, disk utility, utilization"
}
|
Horizontal progress bar
In html and jQuery, how do you show multiple horizontal progress bars? I have an idea for class. Students vote on topics and as they vote, the progress bars move left and right. If you've ever participated in a poll on Adobe Connect, that's the kind of look I'm thinking about.
It can be in html5 because I'll be the only person displaying the results (at the front of the class).
It cannot be in flash because I don't know flash that well.
I'll just have the page auto refresh every 15 seconds or so.
|
Surely you searched for this and found < What additional questions do you have?
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 0,
"tags": "jquery, html"
}
|
In group with order of $pq$ what are the possible values for order of an element?
I have to find the possible values for $o(a)$.here is my question:
Suppose $(G,*)$ is a group with $o(G)=pq$ where $p,q$ are distinct primes. For any $a\in G$ find alll possible values of $o(a)$
I can't figure it out. any one can give me a hint
|
_Hint:_ Note that $o(a)=|\langle a \rangle|$ and use Lagrange's theorem).
Actually, all you need is this result:
> If $G$ is a finite group and $a \in G$, then the order of $a$ divides the order of $G$.
The simplest proof I know is this: take $a \in G$ and consider the map $f\colon G \to G$ given by $f(x)=ax$. Consider now the _orbits_ of $f$, that is, the sets $\mathcal{O}(x)=\\{ x, f(x), f(f(x)), \dots \\} = \\{ x, ax, a^2x, \dots \\}$. All orbits have the same number of elements because $z\mapsto zx^{-1}y$ is a bijection $\mathcal{O}(x) \to \mathcal{O}(y)$. By definition, $|\mathcal{O}(e)| = o(a)$. Hence $o(a)$ divides $|G|$ because $G$ is the disjoint union of orbits.
Going back to your problem, we conclude that the possible orders of an element in $G$ are $1,p,q,pq$.
You'll learn later that every group of order $pq$ has an element of order $p$ and an element of order $q$ (a result called Cauchy's theorem), but not necessarily an element of order $pq$ if $G$ is not abelian.
|
stackexchange-math
|
{
"answer_score": 1,
"question_score": 1,
"tags": "group theory, finite groups"
}
|
Extract an array out of a multidimensional array in php
I have an multidimensional array in php as follows.
MyArray
(
[0] => Array
(
[id] => c
[val] => 290
)
[2] => Array
(
[id] => a
[val] => 160
)
[3] => Array
(
[id] => v
[val] => 150
)
)
out of this array i want to extract `array(c,a,v)` I am not able to extract this particular array out of the above multidimensional array. How can i achieve it?
|
Using `array_map` might help.
array_map(function($elem) { return array_values($elem)[0]; }, $array);
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "php, arrays, multidimensional array"
}
|
SAS text to date
I have an excel file and I read it into SAS using proc import. The Date column has a Text value: Mar 2017 How can I convert it to a date corresponding to the last day of the month? i.e.31MAR2017
|
You can refer to the following code for this
data have;
dt='Mar2017';
output;
dt='Apr2017';
output;
dt='May2017';
output;
dt='Aug2017';
output;
run;
data want;
set have;
newdt=input(dt,MONYY7.); /*Convert text into date, it will point to first day*/
lastDay=intnx ('month',newdt,0,'E'); /*Find the last day of month*/
format newdt lastDay date9.;
run;
|
stackexchange-stackoverflow
|
{
"answer_score": 3,
"question_score": 1,
"tags": "sas"
}
|
How to check which cache features are turned on? [PHP/MYSQL]
Is there an application or a code I can use to check which cache functions are turned on?
On this app I'm working on, I thought there was mysql cacheing, but since I started using the SELECT SQL_NO_CACHE in one of my queries (applied yesterday), the cacheing has not stopped. This leads me to assume it's a php cache function that's occurring.
I looked over php.ini for any possible cache features, but didn't see anything that stood out.
Which leads me to this: Is there an app I can download or a Shell function I can input to tell me which cache functions are on or what may be causing the cache.
|
You probably already know that MySQL has a query caching mechanism. For instance if you have a table named users, and run a query like this:
SELECT COUNT(*) FROM `users`
It may take 3 seconds to run. However if you run the query _again_ , it may only take 0.02 seconds to run. That's because MySQL has cached the results from the first query. However MySQL will clear it's cache if you update the users table in any way. Such as inserting new rows, updating a row, etc. So it's doubtful that MySQL is the problem here.
My hunch is your browser is caching the data. It's also possible that logic in your code is grabbing the old row, updating it, and then displaying the old row data in the form. I really can't say without seeing your code.
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "mysql, caching, php"
}
|
Android Studio overlays
I want to start creating long running applications. For instance, you choose some settings and then they are used while you browsing or playing a game. For example shortcut apps. You click somewhere in the corner, and something pop ups, with list of applications you want to go to.
My problem: I don't know how to create buttons, which would be on phone screen, like triggers, when you touch, something happens. I heard it's called overlays, but I couldn't manage to find tutorials about it.
Application example: Pie Control on Google Play. <
Thanks for helping me out.
|
use system alert window .
**example**
View mView = new View(this);
WindowManager.LayoutParams params = new WindowManager.LayoutParams(
WindowManager.LayoutParams.TYPE_SYSTEM_OVERLAY,
WindowManager.LayoutParams.FLAG_WATCH_OUTSIDE_TOUCH,
PixelFormat.TRANSLUCENT);
params.gravity = Gravity.RIGHT | Gravity.TOP;
WindowManager wm = (WindowManager) getSystemService(WINDOW_SERVICE);
wm.addView(mView, params);
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 1,
"tags": "java, android"
}
|
Image conversion to Grayscale using ImageMagick is very dark
I converted a bunch of "normal" JPG photos via
convert infile -colorspace Gray outfile
to monochrome. However the result is for all images very dark. Here a sample conversion: original photo and converted monochrome image.
Is there a better way to convert a photo-realistic image with ImageMagick to gray-scale?
|
The documentation states that when changing the color space, the colors are converted from their original gamma to linear before the conversion. You need to convert them back to an appropriate gamma.
convert infile -colorspace Gray -gamma 2.2 outfile
|
stackexchange-stackoverflow
|
{
"answer_score": 18,
"question_score": 12,
"tags": "image processing, imagemagick, grayscale, brightness, monochrome"
}
|
Printing Grid Control with multiple elements
I am trying to print a grid control with multiple elements in it.
I am doing this,
PrintDialog printDialog = new PrintDialog();
if (printDialog.ShowDialog() == true)
{
printDialog.PrintVisual(gridReport, "Visit Report");
}
gridReport is my grid name. As my grid contains a lot of child elements, only a part of it is getting printed and rest is getting chopped.
How should i solve this ?
|
I had the same problem a month ago. As far as i know .Net print dialog only prints one page and cuts everything beyond that page. If you want to print multi pages you have to write some logic yourself.
I created a bmp file and cut it to multiple pages, added the pages to a list and at the end printed the list of pages.
I found this article very helpful (it has a solution that cuts the bmpwhenever the height of one page is exceeded, so you will also have to implement a similar logic to cut your bmp when the width of a page is exceeded)
<
i hope this will help.
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 2,
"tags": "c#, wpf"
}
|
how i can transport table in mysql
 as Agendas, (select count(id) from publications) as Publication, (select count(id) from achievements) as Achievements from agenda_details
How can I take result in the following view?
| serial No| Category | Counts|
| 1 | Agendas | 5 |
| 2 | Publications | 5 |
| 3 | Achievements | 5 |
|
Try a query like this:
select 1 as serial_No, 'Agendas' as Category, count(id) as Counts from agenda_details
union
select 2 as serial_No, 'Publications' as Category, count(id) as Counts from publications
union
select 3 as serial_No, 'Achievements ' as Category, count(id) as Counts from achievements
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "mysql"
}
|
Magento - I need to automatically list the left nav alphabetically
I need to automatically list the left nav alphabetically.
I have this code, but the problem is it only does it for category number 4 and I need it to do it for the current category. Any ideas how to get it to load the current category and not a specific number?
<?php
$cats = Mage::getModel('catalog/category')->load(4)->getChildren();
$catIds = explode(',',$cats);
$categories = array();
foreach($catIds as $catId) {
$category = Mage::getModel('catalog/category')->load($catId);
$categories[$category->getName()] = $category->getUrl();
}
ksort($categories, SORT_STRING);
?>
<ul>
<?php foreach($categories as $name => $url): ?>
<li>
<a href="<?php echo $url; ?>"><?php echo $name; ?></a>
</li>
<?php endforeach; ?>
</ul>
Many thanks,
Kirsty
|
<?php
if(Mage::registry('current_category')) {
$cats = Mage::registry('current_category')->getChildren();
$catIds = explode(',',$cats);
$categories = array();
foreach($catIds as $catId) {
$category = Mage::getModel('catalog/category')->load($catId);
$categories[$category->getName()] = $category->getUrl();
}
ksort($categories, SORT_STRING);
?>
<ul>
<?php foreach($categories as $name => $url): ?>
<li>
<a href="<?php echo $url; ?>"><?php echo $name; ?></a>
</li>
<?php endforeach; ?>
</ul>
<?php } ?>
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "php, magento, categories"
}
|
How can I convert milliseconds to "hhmmss" format using javascript?
I am using javascript Date object trying to convert millisecond to how many hour, minute and second it is.
I have the currentTime in milliseconds
var currentTime = new Date().getTime()
and I have futureTime in milliseconds
var futureTime = '1432342800000'
I wanted to get difference in millisecond
var timeDiff = futureTime - currentTime
the the timeDiff was
timeDiff = '2568370873'
I want to know how many hours, minutes, seconds it is.
Could anyone help?
|
const secDiff = timeDiff / 1000; //in s
const minDiff = timeDiff / 60 / 1000; //in minutes
const hDiff = timeDiff / 3600 / 1000; //in hours
**updated**
function msToHMS( ms ) {
// 1- Convert to seconds:
let seconds = ms / 1000;
// 2- Extract hours:
const hours = parseInt( seconds / 3600 ); // 3,600 seconds in 1 hour
seconds = seconds % 3600; // seconds remaining after extracting hours
// 3- Extract minutes:
const minutes = parseInt( seconds / 60 ); // 60 seconds in 1 minute
// 4- Keep only seconds not extracted to minutes:
seconds = seconds % 60;
alert( hours+":"+minutes+":"+seconds);
}
const timespan = 2568370873;
msToHMS( timespan );
**Demo**
|
stackexchange-stackoverflow
|
{
"answer_score": 22,
"question_score": 16,
"tags": "javascript, datetime"
}
|
Kendo Numeric Textbox Text Padding
I have a Kendo NumericTextBox in which I would like to right-align the text with some padding.
Here's telerik's demo page: <
I have applied the following style, which aligns the text ok:
/*Right align numeric text*/
.k-numerictextbox .k-input {
text-align: right;
}
My problem is, whenever I add padding, the up/down arrows are squished instead of my text shifting.
I've tried setting the box-sizing to border-box, but can't quite get it right.
Anyone with some css skills want to take a look?
|
I've applied the following style to achieve the goal.
.k-numerictextbox .k-input {
width: 96%;
text-align: right;
padding-right: 5px !important;
}
|
stackexchange-stackoverflow
|
{
"answer_score": 9,
"question_score": 4,
"tags": "css, kendo ui, kendonumerictextbox"
}
|
$\lim\limits_{n \to \infty}\sum_{i=1}^{n}{i^r \over n^{r+1}}={1 \over 1+r}$
If $r\in\Bbb N$ then $\lim\limits_{n \to \infty}\sum_{i=1}^{n}{i^r \over n^{r+1}}={1 \over 1+r}$
How to prove above equality?
|
This question works on the fact that limits of a summation is equal to an integral, i.e a Riemann sum.
The question can be written as $$ \lim_{n\rightarrow\infty} \frac1n \sum_{i=1}^n \left(\frac in\right)^r$$
This is equivalent to $$\int_0^1 x^r dx$$
Which becomes $$\left[\frac{x^{r+1}}{r+1}\right]_0^1 = \frac1{r+1}$$
|
stackexchange-math
|
{
"answer_score": 4,
"question_score": -2,
"tags": "calculus"
}
|
VBE6.dll not found when opening Access 2007 database in Access 2010
I have an access 2007 database that has some VBA code in it. I need to open this database in Access 2010, but when I first open it I get an error that says:
> the expression on open you entered as the event property setting produced the following error: file not found: VBE6.dll
I believe it's becuase Access 2010 references VBE7.dll when it loads up, and my database was built to reference VBE6.dll. I've tried putting VBE6.dll in the same folder that VBE7.dll resides in, hoping it would just get loaded up, but no luck.
What can I do to resolve this?
|
Sounds like either a registration problem (i.e., which version of Access is registered as the canonical version) or a permissions problem. Try opening and close A2010 without any database. This should run the "reinstalling" process and properly register A2010. Then opening your database should work. Alternatively, maybe you're not running as administrator and you need to for some reason (though that's only relevant on Vista/Win7). Try changing your A2010 shortcut to run as administrator (or however you're launching A2010). Other than that, I have no idea -- this is something that should be fixed up for you on the fly without any issues.
Also, just Googling a bit, I notice that some advise disabling sandbox mode, and cite this Knowledge Base article:
<
|
stackexchange-superuser
|
{
"answer_score": 1,
"question_score": 0,
"tags": "microsoft office, microsoft office 2007, microsoft access, office 2010 beta"
}
|
Regular Expression for SSN
I have a method in C# that says FormatSSN that takes a SSN in a string format and replaces the dashes. I mean I am expecting the SSN to be in XXX-XX-XXXX format. I want to write a regular expression that makes sure that the SSN is in the format I have mentioned.
Can anyone help me construct a regular expression??
|
^\d{3}-\d{2}-\d{4}$
`\d` is a digit, `{X}` is repeat the previous element `X` times.
As Dmitry pointed out in comments, adding `^` at the beginning and `$` at the end will cause the regex to only match if the entire string is a SSN. Without those anchors strings like `abc123-45-6789xyz` would also match.
|
stackexchange-stackoverflow
|
{
"answer_score": 22,
"question_score": 10,
"tags": "c#, regex"
}
|
opengl API Gdx.gl20 vs Gdx.gl in libgdx v0.9.9
I'm working with the libgdx framework and I'm not sure what is the preferred way to access the opengl API, My application uses OpenGl 2.0 (the useGL20 flag is set to true). Now to clear for example the screen I can do:
Gdx.gl20.glClearColor(0, 0, 0, 0xff);
Gdx.gl20.glClear(GL20.GL_COLOR_BUFFER_BIT);
but I can also do:
Gdx.gl.glClearColor(0, 0, 0, 0xff);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);*
Of course both have the same result, but is one way preferred above the other? What is the resulting difference when using `Gdx.gl20` vs `Gdx.gl`?
Note that in the latest version of libgdx, openGl 1.x is completely removed and `Gdx.gl` is simply an interface wrapping of `Gdx.Gl20`. However I'm using an older version (v.0.9.9) of libgdx which still has support for openGl 1.x
|
It doesn't matter, since it references the same object. If you want to support GLES 3.0 down the road (when it's fully implemented in libgdx), I'd go with `gl` so you won't have to refactor as much code later. Then in your AndroidLauncher class, you can select which one you want (2.0 or 3.0) in your ApplicationConfiguration, based on the device capabilities. Most of your core code won't even need to know which one's being used; you would only need to worry about checking in places where you use 3.0-specific features.
|
stackexchange-stackoverflow
|
{
"answer_score": 3,
"question_score": 1,
"tags": "java, opengl, libgdx"
}
|
How separate search results by category? MySQL + PHP
## Hi!
I didn't get any code that worked. Of course I could have use then wrongly because I'm a beginner. Some told me to use MySQL subqueries other told me to use PHP foreach achieve it. What I want is to show the search results of a keyword separated by groups of categories, something like that:
> Search results for _Item_ , 3 itens in 2 categories:
>
> ### Category 1:
>
> * Item 1
> * Item 10
>
> ### Category 2:
>
> * Item 1003
>
Can someone explain me it as simple as possible.
Thanks n advance!
|
I use a single request which return name of category for each item and I use PHP to display it
<?php
$cat;
while($result = $statement->fetch()) {
if($result['cat'] !== $cat) {
$cat = $result['cat'];
/* display cat */
}
/* display items */
}
?>
|
stackexchange-stackoverflow
|
{
"answer_score": 5,
"question_score": 2,
"tags": "php, mysql"
}
|
Proper translation/explanation for business sector, business field
I am German. I am currently developing a system which acts like a data provider for company infos.
A company needs to be assigned to one or more "business sectors". I currently deal with companies doing the following:
* Repairing vehicles
* Towing services
* Handicraft businesses
* Motor vehicle experts
The above types I called "business sectors".
Below these can be "business fields", like:
Handicraft businesses
* mason
* carpenter, etc
So my question is, how would a native speaker call these two levels? So far I've seen industrial sectors, branches, etc... I am confused ;)
|
"Business sectors" or "Industrial sectors" is fine for your first level.
To me the examples in your second list are "trades" or "skills".
By the way (not germane to your specific question) "info" is a mass noun in English. "Infos" is not common and might not be understood.
|
stackexchange-english
|
{
"answer_score": 1,
"question_score": 2,
"tags": "translation"
}
|
How to get a part of url in Django view?
I have two urls:
url(r'^(?P<slug>[^\.]+)/reviews/$', Someview.as_view(), name="someview"),
url(r'^(?P<slug>[^\.]+)/tips/$', Someview.as_view(), name="someview")
I need to get a `reviews` or `tips` part in a view to apply different logic in the same view according to that part of url, how do I do that?
|
You can do this:
`url(r'^(?P<slug>[^\.]+)/(?P<reviews>reviews)/$', Someview.as_view(), name="someview"),`
`url(r'^(?P<slug>[^\.]+)/(?P<tips>tips)/$', Someview.as_view(), name="someview")`
In views you can get them like:
Class Based Views:
class SomeView(ListView):
def my_fn(self):
reviews = self.kwargs.get('reviews', None):
...
Function Based Views:
def SomeView(request, reviews):
#you can use it in the view now
revews = reviews
...
You can get more variables by passing a dictionary in the url.
url(r'^(?P<slug>[^\.]+)/reviews/$', Someview.as_view(), {'reviews':'reviews','tips':'tips'}, name="someview")
|
stackexchange-stackoverflow
|
{
"answer_score": 6,
"question_score": 1,
"tags": "django, django templates, django views, django urls"
}
|
how to add elements within a list together in clojure?
I am trying to make a function that add elements within a list like below
editted to "Nathan Davis" correction without nil:
(defn sumv [s1]
(for [x1 s1 x2 s1
:when (< x1 x2)]
(+ x1 x2)))
|
If you want to explicitly use recursion, consider also using `lazy-seq`:
(defn add-pairs [[x & [y :as r]]]
(lazy-seq
(if y
(cons (+ x y) (add-pairs r)))))
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": -1,
"tags": "list, clojure"
}
|
Handle a specific error in golang
I am trying to simply ignore the `csv.ErrFieldCount` error in our code but cannot seem to only look at that one error. What am I doing wrong here?
record, err := reader.Read()
if err != nil {
if err == csv.ErrFieldCount {
return nil
}
return err
}
But when I run the code the last line of the csv file gives me this error paniced `line 11535, column 0: wrong number of fields in line`
|
`csv.Reader` doesn't return that error, it returns a `csv.ParseError`. You first need to check if you have a ParseError, then check the Err field:
if err, ok := err.(*csv.ParseError); ok && err.Err == csv.ErrFieldCount {
return nil
}
|
stackexchange-stackoverflow
|
{
"answer_score": 19,
"question_score": 9,
"tags": "csv, go, error handling"
}
|
Declaring val in scala object different to in function
This code results in `system` being `null:
object Main extends App {
val system = ActorSystem("mySystem")
override def main(args: Array[String]): Unit = {
println("Done")
}
}
But if I move the declaration of `system` into `main`, it is correctly initialised. Why is that?
|
From the documentation of `App` (emphasis mine):
> ## Caveats
>
> It should be noted that this trait is implemented using the `DelayedInit` functionality, which means that **fields of the object will not have been initialized before the main method has been executed**.
>
> It should also be noted that **the`main` method should not be overridden**: the whole class body becomes the “main method”.
Just do
object Main extends App {
val system = ActorSystem("mySystem")
println("Done")
}
or
object Main {
def main(args: Array[String]): Unit = {
val system = ActorSystem("mySystem")
println("Done")
}
}
|
stackexchange-stackoverflow
|
{
"answer_score": 5,
"question_score": 1,
"tags": "scala"
}
|
Delete Item from Array in Angular at Index value
Maybe simple but, I am trying to delete item from an array of objects in Angular, But my current code only returns an _undefined_ in the console as i'm sure it's not finding the right index value. It is also for a Kendo Grid. So I need to Splice based on what the user clicks, not a specific id. Link to demo: <
data structure is:
export const data = [
{
id: 1,
name: "Element 1"
},
{
id: 2,
name: "Element 2"
},
{
id: 3,
name: "Element 3"
},
];
ts file
public gridData: any[] = data;
public removeItem(id) {
let index = data.findIndex(e => e.id === id);
if (index !== -1) {
data.splice(index, 1);
}
console.log(id)
}
|
The actual problem is that you pass nothing to `removeItem`. So, in your html I just wrote `removeItem(dataItem)` instead of `removeItem(id)`. In the ts the change is `let index = data.findIndex(e => e.id === dataItem.id);`.
Please check the updated <
|
stackexchange-stackoverflow
|
{
"answer_score": 3,
"question_score": 3,
"tags": "angular, kendo grid, kendo ui angular2"
}
|
My Horse sniffs my head?
When I'm mucking out around her in the evening or if I generally just crouch low to the floor my young horse will always come over and sniff my head.
She used to occassionally go to bite (never managed to make contact) until one day my head made contact with her teeth when I stood up. Now she just stands there sniffing me.
I feel that this is normal and she's quite curious to see what I'm doing but I could be wrong. Is there any explanation for this?
|
This is open to interpretation, but there's a couple of more obvious reasons for this behaviour.
In part, particularly for younger horses, this is a modified grooming action. My young horses do this and even nibble on my hair when I'm scratching their necks or backs, as if you watch horses mutually grooming, that is what they are attempting to do to me. With the one exception, they have been taught not to use their teeth on people. My rising 6yo mare does this with me.
They also sniff as a way to gain information. Where you have been, who and what you have been mingling with. Such busybodies! Horses will greet each other frequently and sniff as a way of checking each other out. Particularly given we humans put so many different scents on us throughout the day with a showering and deodorant routine. I avoid wearing perfume of body sprays around my horses and try and use a non-invasive smelling deodorant.
.fit_transform vs. pd.get_dummies for categorical coding
It was recently brought to my attention that if you have a dataframe `df` like this:
A B C
0 0 Boat 45
1 1 NaN 12
2 2 Cat 6
3 3 Moose 21
4 4 Boat 43
You can encode the categorical data automatically with `pd.get_dummies`:
df1 = pd.get_dummies(df)
Which yields this:
A C B_Boat B_Cat B_Moose
0 0 45 1.0 0.0 0.0
1 1 12 0.0 0.0 0.0
2 2 6 0.0 1.0 0.0
3 3 21 0.0 0.0 1.0
4 4 43 1.0 0.0 0.0
I typically use `LabelEncoder().fit_transform` for this sort of task before putting it in `pd.get_dummies`, but if I can skip a few steps that'd be desirable.
Am I losing anything by simply using `pd.get_dummies` on my entire dataframe to encode it?
|
Yes, you can skip the use of `LabelEncoder` if you only want to encode string features. On the other hand if you have a categorical column of integers (instead of strings) then `pd.get_dummies` will leave as it is (see your A or C column for example). In that case you should use `OneHotEncoder`. Ideally `OneHotEncoder` would support both integer and strings but this is being worked on at the moment.
|
stackexchange-stackoverflow
|
{
"answer_score": 6,
"question_score": 4,
"tags": "python, pandas, scikit learn, sklearn pandas"
}
|
Problem with connectorConfig in direct link for MULTIPLE field
When transferring connector config via a direct link, it does not work for MULTIPLE field. I tried different options:
* `
* `{"project_id":"11"}`
* `{"project_id":["11"]}`
* `{"project_id":"[\"11\"]"}`
function getConfig(request) {
var cc = DataStudioApp.createCommunityConnector();
var config = cc.getConfig();
var option1 = config.newOptionBuilder()
.setLabel("11")
.setValue("11");
var info1 = config.newSelectMultiple()
.setId('project_id')
.setName('Name project')
.addOption(option1)
.setAllowOverride(true);
config.setDateRangeRequired(true);
return config.build();
}
|
Edit: 10-17-2019
Turns out this was a bug! Thanks for bringing up the issue. It should be resolved now. The correct format is an array of strings (the second 3rd bullet point above).
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "google data studio"
}
|
Сколько прошло времени?
Доброе утро ХэшКод.
Как сделать отсчет того, сколько времени прошло после (например, добавления новости), я делал так
$date = date("G:i:s", time() - $res["date"])
echo $date;
Но беда в том, что даже если добавит в базу текущее время, отсчет начинается, и не с 0 часов 0 минут и 0 секунд, а сразу как будто я отправил сообщение 2 часа назад, т.е отсчет идёт не от нуля, а от 2-х.
|
$date = date("G:i:s", time() - $res["date"])
echo $date;
Я обычно ставлю **H** а не **G**
G Часы в 24-часовом формате без ведущего нуля
H Часы в 24-часовом формате с ведущим нулём
time() Возвращает количество секунд
$res["date"] откуда берется?
**Но скорее вопрос именно в Букве при выводе.**
**//UPD** Ну вот чтобы огород не городить уже отвечал на вопрос тут
|
stackexchange-ru_stackoverflow
|
{
"answer_score": 2,
"question_score": 0,
"tags": "php, дата"
}
|
Regex do not allow only numbers
I am trying to use regex to validate some data, I need it to match the following rules...
* Only allow alphanumeric characters
* Have at least 2 characters
* Does not consist of only numbers
I have this regex so far <
(?:\s*[a-zA-Z0-9]{2,}\s*)*
This is working apart from it allows it to consist of all numbers. So for example the following test data should all fail....
47
4
83874
But the following should pass
47 apple
apple
Can anyone help?
|
You can use this regex:
^(?![0-9]+$)[a-zA-Z0-9 ]{2,}$
### Online Demo
|
stackexchange-stackoverflow
|
{
"answer_score": 4,
"question_score": 5,
"tags": "regex"
}
|
Make JWPlayer fit the screen size
I added JWPlayerController to the UIView. Using
_jwConfig.size = CGSizeMake(400, 400); the video is moving out of the screen. I wouldn't want to hard-code values in CGSizeMake because it will be played on variety of devices.  onReady {
self.jwPlayer.view.frame = self.jwPlayerView.frame;
}
This solved my problem.
Additionally, there is a problem with the new XCode. The frame size by default is taken as 1000, 1000, because of which the self.jwPlayerView.frame.size; wasn't giving the correct size. You need to use 'layoutIfNeeded' method to get the correct size. I defined the frame in 'onReady' method though.
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 1,
"tags": "ios, objective c, uiview, frame, jwplayer"
}
|
How do I recursively set the date created attribute to the date modified attribute on NTFS-3G?
In my first question: How do I get the creation date of a file on an NTFS logical volume, I asked how to get the "Date created" field in NTFS-3G. Now, that I know I can get the "Date created", I have started adding files onto my NTFS-3G partition and would like to set the "Date created" of each file to its "Date modified" value.
Since this needs to be done on a whole repository of files, I would like to recursively apply it to a single directory on down. If I know how to do this for a single file, I could probably do the recursion myself, but if you want to add that in I would be more than happy.
|
The `system.ntfs_times` extended attribute contains 32 bytes that consist of the btime, mtime, atime, ctime as 64bit integers.
You can list them with for instance:
getfattr --only-values -n system.ntfs_times -- "$file" |
perl -MPOSIX -0777 -ne 'print ctime $_/10000000-11644473600 for unpack("Q4",$_)'
So you can just copy the second integer to the first with something like:
getfattr -n system.ntfs_times -e hex -- "$file" |
sed '2s/0x.\{16\}\(.\{16\}\)/0x\1\1/' |
setfattr --restore=-
|
stackexchange-unix
|
{
"answer_score": 1,
"question_score": 3,
"tags": "files, date, file copy, ntfs, ntfs 3g"
}
|
Cronjob and Mavericks sleep mode
I've installed the new Mavericks OS on my mac and the sleep mode seems to stop everything including cronjobs, logmein service, etc.
Do you guys have the same issue? How could we fix this?
Thanks a lot.
|
I found my answer here : <
My point is that Mountain Lion was still running cron jobs while asleep with default energy saver configuration, but Mavericks doesn't anymore (and without installing anything like anacron, etc.)
If someone find out how Mountain Lion was doing so, I'd be interested. Thanks.
|
stackexchange-stackoverflow
|
{
"answer_score": 3,
"question_score": 3,
"tags": "cron, osx mavericks"
}
|
win7 64bit - manually change driver signature
I want to edit/change driver signature. Because when i start it, I got message, that signature isn't set. The only option now is to click F8 and then "Disable driver signature enforcement". But I don't really want to use this option, it's insecure. So how I can set signature for that driver? Or maybe disable driver signature enforcement for ONLY selected driver? Any ideas?
Thanks
|
If you purchase a code signing certificate from Verisign or Globalsign (other CAs won't work), you can remove existing signature if it's present for the driver and then apply your own signature by signing the driver file. Signing is done using signtool.exe from Windows SDK or from Windows Driver Kit. When the driver is signed, you need to include a cross-signing certificate.
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 1,
"tags": "windows, driver, signature"
}
|
Calling ExecutorService submit() inside an infinite loop
My question is regarding the `shutdown()` method from the ExecutorService class. If i am calling the `submit()` method in an infinite loop... do i ever need to call `shutdown()`? Essentially i have something like this (pseudo-code here):
for(;;){
for(some event){
if(some event does something i want to capture){
threadPool.submit()
}
}
}
So with a set up like the above when is it appropriate to call `shutdown()` ? In my actual code when i try to call shutdown() outside the infinite loop i get unreachable code error - which i understand. But it seems to me that i would probably not call the `shutdown()` method. What do you guys think?
|
Suggest passing a _stop_ event type that instructs the loop to `break`:
boolean have_received_stop_event = false;
while (!have_received_stop_event)
{
for(some event)
{
if(stop-event)
{
have_received_stop_event = true;
break;
}
if(some event does something i want to capture)
{
threadPool.submit()
}
}
}
Then call `shutdown()` after main loop exits.
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 0,
"tags": "java, multithreading, executorservice"
}
|
custom changes removed after plugin update
Ok that's something normal, files are being downloaded again and the code changes.
What should I do if I don't want some changes to take place?
For example a gallery plugin I use recently updated and a border I didn't want to appear in the gallery now exists again.
Updates should always take place for security reasons but how should I override such behavior? Is there a way I can have another file that doesn't allow for example that border effect to take place ?
Maybe with jQuery somehow ?
|
If it's just a CSS change, load your own CSS stylesheet to override their CSS. If it's the HTML of the plugin, then you will need to look at filter hooks to see what you can change. Some plugins are developer friendly and supply some filter hooks allowing you to change various things the plugin does; for others, you will need to get creative.
|
stackexchange-wordpress
|
{
"answer_score": 1,
"question_score": 1,
"tags": "plugins, jquery, css, updates"
}
|
Compute $E(X\mid X+Y)$ if $(X,Y)$ is centered normal with known covariance matrix
> The random variable $(X,Y)$ has a two dimensional normal distribution with mean $(0,0)$ and covariance matrix $\begin{pmatrix} 4&2 \\\ 2&2 \end{pmatrix}$. Find $E(X\mid X+Y)$.
I am completely lost with this question.
|
Let's pose $Z = X+Y$. The random variable $(X,Z)$ has a two dimensional normal distribution with mean $$(E(X),E(Z)) ) (E(X), E(X)+E(Y)) = (0,0)$$ and covariance matrix $$\pmatrix{E(X^2) & E(XZ)\\\E(ZX) & E(Z^2)} = \pmatrix{E(X^2) & E(X^2)+E(XY) \\\E(X^2) + E(YX) & E(X^2)+E(Y^2)+E(2XY)} = \\\ \pmatrix{4 & 4+2 \\\4 + 2 & 4 + 2 + 2\cdot2} = \pmatrix{4 & 6\\\6 & 10}.$$
The correlation coefficient of $X$ and $Z$ is:
$$\rho = \frac{E(XZ)}{\sqrt{E(X^2)E(Z^2)}} = \frac{6}{\sqrt{4 \cdot 10}} = 3\frac{\sqrt{10}}{10}.$$
The conditional expected value is:
$$E(X\mid Z) = \mu_X + \rho \sqrt{\frac{E(X^2)}{E(Z^2)}}(Z-\mu_Z) = \\\ = 0 + 3\frac{\sqrt{10}}{10}\sqrt{\frac{4}{10}}(Z-0) = \frac{3}{5}Z.$$
For the last step, take a look here.
|
stackexchange-math
|
{
"answer_score": 4,
"question_score": 5,
"tags": "probability, covariance"
}
|
Use StringTokenizer to count number of words and characters in words
The objective is to get a sentence input from the user, tokenize it, and then give information about the first three words only (word itself, length, and then average the first 3 word lengths). I'm not sure how to turn the tokens into strings. I just need some guidance - not sure how to proceed. I've got this so far:
public static void main(String[] args) {
String delim = " ";
String inSentence = JOptionPane.showInputDialog("Please enter a sentence of three or more words: ");
StringTokenizer tk = new StringTokenizer(inSentence, delim);
int sentenceCount = tk.countTokens();
// Output
String out = "";
out = out + "Total number of words in the sentence: " +sentenceCount +"\n";
JOptionPane.showMessageDialog(null, out);
}
I'd really appreciate any guidance!
|
If you just wanted to get the first 3 tokens, then you could do something like this:
String first = tk.nextToken();
String second = tk.hasMoreTokens() ? tk.nextToken() : "";
String third = tk.hasMoreTokens() ? tk.nextToken() : "";
From there should be pretty easy to calculate the other requirements
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 2,
"tags": "java, string, token, stringtokenizer"
}
|
unsafe value used in a resource URL context Angular Error
Hello Guys I want to show a dynamic pdf. At first it was showing me CORS error. I solved that using DOM Sanitizer. Now it is showing me unsafe url Any Help is appreciated.
HTML Code :
<iframe src="{{Url}}"></iframe>
TS Code : Here pdfSrc stores the dynamic generated pdf path;
this.pdfSrc = ' + this.pdfPath;
this.Url = this.sanitizer.bypassSecurityTrustUrl(this.pdfSrc);
|
Finally got the solution just changed the HTML Part & TS PART AS BELOW
<iframe [src]='Url' width="100%" height="1000px"></iframe>
constructor(private sanitizer:DomSanitizer){}
this.Url = this.sanitizer.bypassSecurityTrustResourceUrl(this.pdfSrc);
|
stackexchange-stackoverflow
|
{
"answer_score": 14,
"question_score": 4,
"tags": "angular, typescript, iframe"
}
|
В матрице записать строку в столбец
Предположим, что у нас есть матрица 4 на 4, на главной диагонали стоят 0:
0 1 2 3
0 0 4 5
0 0 0 6
0 0 0 0
Надо записать строку в столбец так, чтоб у нас получилась симметричная матрица.
0 1 2 3
1 0 4 5
2 4 0 6
3 5 6 0
|
#include <iostream>
using namespace std;
int main() {
int n = 4;
int m = 4;
int a[n][m] = {{0,1,2,3},
{0,0,4,5},
{0,0,0,6},
{0,0,0,0}};
int b[n][m];
for(int i = 0; i < n; ++i) {
for(int j = 0; j < m; ++j)
cout << a[i][j] << " ";
cout << endl;
}
cout << endl;
for(int i = 0; i < n; ++i) {
for(int j = 0; j < m; ++j)
if(i>j){
b[i][j] = a[j][i];
}else{
b[i][j] = a[i][j];
}
}
for(int i = 0; i < n; ++i) {
for(int j = 0; j < m; ++j)
cout << b[i][j] << " ";
cout << endl;
}
}
|
stackexchange-ru_stackoverflow
|
{
"answer_score": 0,
"question_score": -3,
"tags": "java, c#, c++"
}
|
CSS: Floating two div elements with 100% width off screen?
I remember asking this question a while back but i can't seem to find it again! I've searched but i can't seem to find the solution i'm looking for.
Let's say i have two divs with 100% width floated next to each other. As they take up the entire screenwidth, there is no longer any space left for them to float on, and therefore the second div appear below the first one. What i want is to make the second div continue floating off screen next to the first one.
I _think_ the solution i got was to set the _display_ property to something else, but i'm not entirely sure.
Any suggestions?
|
I believe you would have to have a container and set the container width to 200%. The two inside divs with 50% width will fit inside.
#container_div{ width:200%}
.inner_div {width:50%}
|
stackexchange-stackoverflow
|
{
"answer_score": 5,
"question_score": 5,
"tags": "css, html, css float, off screen"
}
|
scrapy: what is wrong with this simple pipeline
I have two scrapy spiders, let's say `spider1` and `spider2`. `spider1` crawls some pages and collects urls in a file. Here is the code:
class FileWriterPipeline(object):
def __init__(self):
self.file = open('somefile.txt'), 'wb')
def process_item(self, item, spider):
if spider.name == 'spider1':
line = item['url'] + "\n"
self.file.write(line)
return item
The problem is that as soon as I run `spider2`, `somefile.txt` is getting wiped clean. Would anyone know what is wrong here?
|
Regardless of what you do later, as soon as you call:
open('somefile.txt', 'wb')
with the `'wb'` argument, the file is erased completely. If you want to append, you should instead use `'ab'`.
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "python, scrapy"
}
|
copy clipboard of linux into windows clip-board in network
I am writing a small tool, that copies clipboard of linux into windows clip-board. Let me take an example, both linux and windows in network connection. I copy something in linux to clip-board, then when I press some keys in windows lets take CTRL+ALT+v what is copied in linux should print in linux.
What I thought is executing some script in linux from windows through ssh connection. That script shall copy the clip-board into some file in windows, then windows shall put the file content into windows clip-board.
My problem is connection with linux from windows and executing the script. How can I achieve this ?
And please share if you have any better idea to do this.
Thanks a lot :).
|
There is a free, cross-platform, open-source program called Synergy that does exactly what you are describing (and more), and I have tested it with a Windows/Linux connection. You could take a look at the source code and see how the clipboard functions are implemented, or it might fit your needs already.
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 0,
"tags": "windows, linux, ssh, clipboard"
}
|
Premiere Pro: Possible to add several images on one video track?
I have this image 
I'm a professional pianist and have been playing for eight years now. I recently noticed a problem in my left hand: if we enumerate the fingers consecutively, 1 beeing the thumb, my fourth finger is very weak compared to the fourth finger of my right hand, and if I position my left hand completely open and try to bend only the third and fourth fingers, I can't manage to keep them together while doing this. Could I have injured myself from practicing too hard?
I'm especially worried, since when I was little I used to bend my fingers backwards really hard, to the point that some of my knuckles got bigger and stayed this way even after I stopped. What kind of injuries could this cause, and what type of doctor should I visit to get my hand checked?
|
Go see an orthopedic surgeon; it's not exactly the most classical story but you might have some form of carpal tunnel syndrome. In most cases in can be effectively treated with rest, painkillers and stretching/exercise (so you don't get unnecessarily scared about the "surgeon" part); either way, considering it's your profession, I definitely think it is justified to be evaluated by a professional.
<
|
stackexchange-health
|
{
"answer_score": 1,
"question_score": 0,
"tags": "hand, repetitive strain injury, fingers, irreversible damage, knuckles"
}
|
Glassfish 3.1.1: Retrieve HTTP-Authentication in RESTful Webservice
I´m using HTTP-Authentication based on my customer-table. After the user is authenticated a restful webservice is called. But how can I access in the webservice the HTTP-Authentication (the Header Data of the HttpRequest)? My code looks like this:
@GET
@Path("{id}")
@Produces({"application/xml"})
public ObjectList read(@PathParam("id") Integer id) {
... //how to get here the HTTP-Username and Password?
}
|
In order to get the `Principal` and its role, inject @Context `SecurityContext` in the class body or in the method input parameters.
import javax.ws.rs.core;
//
public ObjectList read(
@PathParam("id") Integer id,
@Context SecurityContext sc) {
String principalUserName = sc.getUserPrincipal().getName();
if (sc.isUserInRole("MyRole")) {
return new MyRoleResource();
} else {
return new MyDefaultRoleResource();
}
}
|
stackexchange-stackoverflow
|
{
"answer_score": 3,
"question_score": 3,
"tags": "java, web services, jakarta ee, java ee 6, jax rs"
}
|
nested if vs loop condition
I have to do a comparison and I want to know which will be faster.
1)
for (i=0;i<4;i++){
if (object1(i)==object2(i))
retval = true;
else {
retval = false;
break;
}
}
2)
if ( (object1(0)==object2(0) && (object1(1)==object2(1) && (object1(2)==object2(2) && (object1(3)==object2(3)){
retval = true;
else
retval = false;
Or both will perform the same?
Thanks for Advice
|
Strictly speaking the most efficient path would be:
retval = object1(0) == object2(0) && object1(1) == object2(1).....
This basically does the same as your loop, but doesn't have to compare the result to `true` to determine the outcome of the condition.
However, I strongly recommend keeping the loop, as it is far easier to adapt to add or remove numbers.
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 0,
"tags": "c++, performance, visual c++"
}
|
Pandas: fillna every columns with some value
I have dataframe and there are `NaN` values:
col1 col2 col3
234 NaN 1
NaN NaN 18
9 2 NaN
I have list with values [12, 15, 3] and I need to fill this columns:
Desire output
col1 col2 col3
234 15 1
12 15 18
9 2 3
I can do it with
for (col, mean) in zip(df.columns, means):
df[col].fillna(mean, inplace=True)
But is any way to do it without loop?
|
Build a dict of those , then `fillna`
l1= [12, 15, 3]
df.fillna(dict(zip(df.columns,l1)))
Out[120]:
col1 col2 col3
0 234.0 15.0 1.0
1 12.0 15.0 18.0
2 9.0 2.0 3.0
|
stackexchange-stackoverflow
|
{
"answer_score": 4,
"question_score": 1,
"tags": "python, pandas"
}
|
Go back to } in vim - equivalent of [} or ]{
In vim I can hit `[{` to go back to the first unmatched `{` or `]}` to go forward likewise. Is there something (short) that acts like `[}` so I can go back to the last `}`?
|
I don't believe that there is a built in command to do what you want. I think it'd be easiest to add a simple mapping like
map <Leader>} ?}<Cr>
to let you hit leader} (leader is \ if you haven't remapped it) and go back to the most recent }.
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 4,
"tags": "vim"
}
|
How do you set a texture to tile in Sprite Kit
I am making a sprite kit game and it is obviously more efficient to have one big SKSpriteNode with a tiled texture, than having multiple SKSpriteNodes with the tile texture. My Problem is that when I try to make a 5x5 tile using
SKTexture* tex = [SKTexture textureWithRect:CGRectMake(0,0,5,5) inTexture:[SKTexture textureWithImageNamed:@"tile.png"]];
SKSpriteNode* node = [SKSpriteNode spriteNodeWithTexture:tex size:CGSizeMake(100,100)];
The image is re sized appropriately, but it is clamped and not tiled. In openGL terms I am getting a GL_CLAMP_TO_EDGE where I want a GL_REPEAT. Is there anyway I could achieve the tiling effect of a texture in a single SKSpriteNode, without creating a very large image.
Here is an image of my problem: !enter image description here
|
Afaik, there is no way to create sprite with tiled texture. But what you can do, is render lot's of sprites in a single drawing pass.
From Apple's documentation (Sprite Kit Best Practices -> Drawing your content):
> If all of the children of a node use the same blend mode and texture atlas, then Sprite Kit can usually draw these sprites in a single drawing pass. On the other hand, if the children are organized so that the drawing mode changes for each new sprite, then Sprite Kit might perform as one drawing pass per sprite, which is quite inefficient.
|
stackexchange-stackoverflow
|
{
"answer_score": 10,
"question_score": 7,
"tags": "ios, objective c, sprite kit"
}
|
ASP.NET MVC brakes JS call
I have the string with javascript call which is bound to HTML Select event:
@Html.DropDownList(Model.DropDownName, Model.ItemsForView, new { onchange = "someMethod('someArgumentValue')" })
which is rendered to the following code:
onchange="someMethod('someArgumentValue')"
Is there any way to make ' symbol render "as is"?
|
It would be better to use unobtrusive javascript:
@Html.DropDownList(Model.DropDownName, Model.ItemsForView, new { id = "foo" })
and in a separate `.js` file:
$(function() {
$('#foo').change(function() {
someMethod('someArgumentValue');
});
});
There are at least two benefits:
* You are not mixing script and markup
* Markup is reduced and scripts are cached by the browser
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 1,
"tags": "c#, .net, asp.net, asp.net mvc"
}
|
How can a browser client consume a GraphQL subscription without libraries like Apollo or Relay?
Assuming a GraphQL server has already implemented subscription operations, how could a browser client consume a subscription without the use of libraries like Apollo or Relay?
Using the WebSocket API, what are the steps required to consume a GraphQL subscription in the browser?
|
From my research, it seems that client side websocket implementations are quite specific to server implementations. Since I am using Elixir / Absinthe, I've found a JavaScript library made for my server's implementation.
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 3,
"tags": "javascript, websocket, graphql"
}
|
Whining noise from valve cover region, Nissan Primera P11 1999
Recently I've been hearing a whining noise from the engine bay. After checking, it seems to come from the valve cover. I've checked the motor oil; level seems ok although the oil is black but not smelly. There´s no white foam in the oil either. It is about a year ago (c:a 13000 kilometers) since I changed oil and oil-filter. The car is a Nissan Primera P11 hatchback with CVT automatic gearbox. The whining noise is there all the time, already at idle revs.
|
Ok, as it turns out, the "whining" noise, was actually caused by a leaking hose (ventilation from the valve cover), annoying and hard to find, one of my friends nailed it right away. Thanks a lot for your help after all.
|
stackexchange-mechanics
|
{
"answer_score": 1,
"question_score": 3,
"tags": "oil, nissan, primera"
}
|
Enter Data to main form
!enter image description hereI Made an application. The Main form Name is Form1. And the other Form is called PoP.
public partial class pops : Form
{
public pops()
{
InitializeComponent();
CenterToScreen();
}
private void pops_Load(object sender, EventArgs e)
{
}
private void button1_Click(object sender, EventArgs e)
{
Close();
}
private void lblAdminNo_Click(object sender, EventArgs e)
{
}
}
|
Make two public properties on popup form and retrieve them from parent form.
string username = string.Empty;
string password = string.Empty;
using (LoginForm form = new LoginForm ())
{
DialogResult result = form.ShowDialog();
if (result == DialogResult.Ok)
{
username = form.Username;
password = form.Password;
}
}
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 0,
"tags": "c#, windows, winforms, label"
}
|
Special characters in html output
I want characters like 'ø' to be printed directly, but in the source 'ø' shows up as `ø`
If the output goes through `Html.Encode()` it won't render the correct character, but `ø`
in the config I have
<globalization
fileEncoding="utf-8"
requestEncoding="utf-8"
responseEncoding="utf-8"
culture="nb-NO"
uiCulture="nb-NO"
/>
Source:
<li><%: Html.ActionLink("Støvletter", "ListProducts", "Tag", new { tag = "Stovletter" }, null)%></li>
This outputs:
<li><a href="/Tag/Stovletter">Støvletter</a></li>
But output should look like:
<li><a href="/Tag/Stovletter">Støvletter</a></li>
|
You could try to create output with `<%=` instead of html encoded `<%:`
(I post this after your positive comment to my comment)
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 3,
"tags": "c#, asp.net, asp.net mvc"
}
|
Bootstrap Form Design
I'm trying to redesign my registration form using bootstrap. I'm following this documentation to convert my already finished registration page into a bootstrap based page. My registration page is broken into 3 parts, Options/Information/Payment. But I want pages to slide into each other like a slider where you can go back and forth. Something like this. So how do I break this form into three pieces and slide into each other with bootstrap?
|
I think Bootstrap Tabs will do what you need.
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "html, css, forms, frameworks, twitter bootstrap"
}
|
Filter objects by exact position of character
I have a list of codes where each character as a meaning:
i.e.
> code:
>
> 1) 0000.ABCD
>
> 2) 1111.CACC
>
> position: 012345678
I want' to make a search for all the codes with `A` at position 5.
> 1) 0000.ABCD
So the research should return only the first code.
I've looked at django look_up functions but this isn't the case neither for an iexact or an icontains.
Is there a way to make a search like this?
|
You could use a regex lookup.
Model.objects.filter(code__regex=r'^.{5}A')
|
stackexchange-stackoverflow
|
{
"answer_score": 5,
"question_score": 3,
"tags": "django, django queryset"
}
|
Is it possible to use a c++ library in a javascript application
I'm trying to build a javascript app and i need to use a c++ library. Is there any way to include a c++ library in a javascript application?
|
Yes. You can utilize emscripten to convert C++ to JavaScript. You can alternatively
* use Native Messaging to communicate with a shell script
* use a local server to `POST` commands to a shell script which runs the native shell script, e.g., see `shell_exec()` calls at PHP at How to programmatically send a unix socket command to a system server autospawned by browser or convert JavaScript to C++ souce code for Chromium?
|
stackexchange-stackoverflow
|
{
"answer_score": 4,
"question_score": 2,
"tags": "javascript, c++, libraries"
}
|
Does the SimpleSAMLphp frontend need to be on for the service provider to act like a service provider?
Pretty simple, setup simpleSAMLphp and went through all the configuration.
The default simpleSAMLphp seems very 'open', and a little unprofessional (under reset password it says "Too Bad! Contact your university"). I know I could technically just edit out some of those messages as a theme, but does it actually need to be on at all?
Or could I simply just turn the web front end off?
|
There are two steps, it seems, to cut down what is shown on that front page without heavily modifying the theme and core files.
Paths are relative to the home directory of simpleSAMLphp.
1. Edit the `./config/config.php` and add an `auth.adminpassword` and also set `admin.protectindexpage` to `true`
2. Edit `./dictionaries/login.definitions.json` and remove the 'university' instructions to something that is more fitting to your business.
|
stackexchange-stackoverflow
|
{
"answer_score": 3,
"question_score": 3,
"tags": "php, saml, simplesamlphp"
}
|
Custom Softkeyboard urdu set Cursor Right side
I have created custom softkeyboard for urdu language. it's working fine.
As per urdu language It cursor should start from right side of editbox.
But when I use that keyboard in device in some applications it starts from left side i.e whatsup. and in some application cursor start from right side. i.e. inbuilt message application.
What code should I do in application so that in every application cursor starts from right side?
Thanks.
|
There is no way to do this. It depends on app and system.
|
stackexchange-stackoverflow
|
{
"answer_score": -2,
"question_score": 2,
"tags": "android, android softkeyboard"
}
|
Locally installed versus globally installed NPM modules
In my `package.json` file, I have bower listed as a dependency. After I run `npm install`, bower gets installed locally. When I try to run bower after installing it locally I get an error
> "bower" is not recognized as an internal or external command
It seems the only way to resolve this is to install bower globally. Why should I have to do this? If my project contains a local copy of bower, why won't node use it?
|
Installing locally makes bower available to the current project (where it stores all of the node modules in `node_modules`). This is usually only good for using a module like so `var module = require('module');` It will not be available as a **command** that the shell can resolve until you install it globally `npm install -g module` where npm will install it in a place where your path variable will resolve this **command**.
**Edit:** This documentation explains it pretty thorougly.
|
stackexchange-stackoverflow
|
{
"answer_score": 49,
"question_score": 42,
"tags": "node.js, npm, windows 7, bower"
}
|
Find the first case of a wildcard plus a number and letter using VBA
I'm writing a macro in Access that pulls data from a file in Excel. I will know the row the data is housed in, but I won't know the column.
I can determine the column by searching for the first instance of a cell that ends in a number immediately followed by the letter "E". For instance "02/10E" or "10 15E".
I am able to open the Excel file from Access. I can also get to the tab where the data is stored.
**How, from Access VBA, can I run a search to find the upper left-most occurrence of a cell in Excel that ends in a number, then a letter?** I assume I should use a wildcard and then some type of regex?
|
This uses Excel **VBA** and not Access. We scan along row#5 looking for a cell in which:
* the last character is **E**
* the next-to-last is numeric
.
Sub FindTheCell()
Dim MyRow As Long, v As Variant
MyRow = 5
For i = 1 To Columns.Count
v = Cells(MyRow, i).Value
If Right(v, 1) = "E" And IsNumeric(Left(Right(v, 2), 1)) Then
MsgBox "Found the data in column " & i
End If
Next i
End Sub
As you see, regex is not required. _This may be adaptable to Access._
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "excel, ms access, vba, ms access 2010"
}
|
Using a custom formula as part of a conditional formatting rule
Ive got a spreadsheet with 3 columns A, B, C, i want to add the 3 columns together in column E, if there is a value in column C, i want the summed number to be shown in red.
If there is a value in column C, there will not be a value in column B and visa versa, so the logic for the conditional formatting will be something like `=if(not(isblank(C2)), , )`
What im struggling with is how to use the above `if` statement as part of a conditional formatting rule inside of Google sheets, as when i try to paste it in the conditional formatting wizard it dose not work.
Ive created a screenshot of what I've tried so far below, as-well as a link to the Google sheet HERE. If you would like to experiment with the Google Sheet, please make a copy using file > make a copy.
Any ideas ?
)`
|
stackexchange-webapps
|
{
"answer_score": 1,
"question_score": 1,
"tags": "google sheets, conditional formatting"
}
|
Plivo outbound call using Auth ID and Auth Token
I am using plivo Android SDK and trying plivo android example to make outbound call. It was successful to login and make call with my username and password of my account. But right now i just want to make a call using my AUTH_ID and AUTH_TOKEN, not username & password. Is that possible using android SDK?
Thanks.
|
Plivo Sales Engineer here.
Android and iOS SDKs use SIP Endpoints to make and receive calls. The endpoints are created against your Plivo account and while using Android/iOS SDKs in your app, it is required to use your SIP Endpoint username and password to register that endpoint with Plivo. It is not possible to use your Auth ID and Auth Token in the app to make calls.
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "android, plivo"
}
|
names function in R not working as expected
I have a vector named v as follows:
> v
Moe Larry Curly Harry Tevez Kagiso Harry Sierra
10 20 30 40 50 60 70 NA 110 NA 1110 1210
Now, I am trying to replace the empty names at v[9:12] with a 4 element vector, using :
names(v[9:12]) = c("A", "B", "C", "D")
The command runs OK, but when I print the vector v, the result is same as before.
Any suggestions, where am I wrong ?
Earlier when I had, v as below, it had worked OK.
`> v Moe Larry Curly Harry Tevez Kagiso
10 20 30 40 50 60 70 NA`
I had used :
`> names(v)[7:8] = c("Harry","Sierra")`
`> v Moe Larry Curly Harry Tevez Kagiso Harry Sierra 10 20 30 40 50 60 70 NA`
|
You are assigning names to the new vector `110, NA, 1110, 1210`.
Try
names(v) <- c(names(v)[1:8], "A", "B", "C", "D")
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": -1,
"tags": "r, vector, names"
}
|
laravel 5.1 route direct to public folder
this is my route to access index.php ....< if i write < it does pick public bydefault
i want to write .htaccess file to direct < call to < so my url will not hurt..
in short i want < and by dont even change directory struture of laravel.
|
I have figured it out myself, it was so damn easy. just change server.php file to index.php and change the file paths to public folder and u will be all set to go.
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 3,
"tags": ".htaccess, routes, laravel 5.1"
}
|
Removing the zero level of an imagemap using ggplot2
I'm using the `geom_tile` to draw an imagemap and want to clear out the zero level for clarity.
#dummy data
set.seed(1)
tdata <- data.frame(cat1=rep(letters[1:3],4),cat2=sort(rep(LETTERS[1:4],3)),val=rpois(12,1.5))
tdata$val<-tdata$val/max(tdata$val)
I have found 2 ways to do this but both have their drawbacks:
**1)**
qplot(cat1,cat2,data=tdata,geom="tile",fill=val) + scale_fill_continuous(limits=c(.Machine$double.eps,1))
This has the drawback that the min value colour isn't printed in the scale.
**2)**
qplot(cat1,cat2,data=tdata,geom="tile",fill=val,alpha=ifelse(val,1,0))
This has the drawback that the alpha scale is plotted too. Wrapping the alpha argument in an `I()` causes it to fail.
Is there a way to do this without the drawbacks?
|
You can subset your data.
qplot(..., data=subset(tdata, val > 0), ...)
qplot(cat1,cat2,data=subset(tdata, val >0),geom="tile",fill=val)
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 0,
"tags": "r, ggplot2"
}
|
Retrieving URL from saved plist file
Hi i am new with objective c.
I am saving my URL data in plist file under resource. here is my code.
NSString *plistPath =[[[NSBundle mainBundle] resourcePath]
stringByAppendingPathComponent:@"myfile.plist"];
NSDictionary *plistDict = [[NSUserDefaults standardUserDefaults]
dictionaryRepresentation];
if([plistDict writeToFile:plistPath atomically:YES]) {
NSLog(@"success");
} else {
NSLog(@"error");
}
Now i want to retrieve URL from that saved plist (my file.plist), How i can retrieve this that i can use that url for web view.
e.g:
urlString.stringValue = ????
Here i am using `urlString.stringValue` for webview.
[[webview mainFrame] loadRequest:[NSURLRequest requestWithURL:
[NSURL URLWithString:urlString.stringValue]]];
Thanks
|
First, you don't need to save NSUserDefaults to a file yourself. Its contents are saved automatically at periodic intervals, or you can call `synchronize` to save immediately.
But if you want to save a dictionary to a plist, use the `writeToFile:atomically:` method as you already have. Then you can load it again by creating a new dictionary with the contents of the plist:
[NSDictionary dictionaryWithContentsOfFile:plistPath];
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "objective c, xcode, macos, cocoa"
}
|
r trycatch for conduct a forever loop for web crawling Q
I recently learn to web crawling.
I use the While(TRUE) to let my function of web crawling to run forever.
However, my internet is not stable, so it sometimes shows error when my internet failed.
I tried to figure it out use the trycatch function
rf() is my function of web crawling.
if(tryCatch(rf(), error=function(cond) FALSE)==FALSE){
Sys.sleep(60+sample(1:5,1))
rf()
}
I ask R to run it again after a while because the Internet usually would be fine after a while.
However, this code is not good enough because if the internet failed for the second time then R stop.
I thought if i use repeat and it might be better, as followed.
Am I right?
repeat {
if(tryCatch(rf(), error=function(cond) FALSE)==FALSE){
Sys.sleep(60+sample(1:5,1))
rf()
}
Sys.sleep(900+sample(1:30,1))#second
}
|
If you want to wait a longer time period if the requests fails, try this code:
while(TRUE) {
tryCatch({
rf()
print("wait normal")
Sys.sleep(60+sample(1:5,1))
}, error = function(e) {
print("wait longer")
Sys.sleep(900+sample(1:30,1))
}
)
}
Note that your rf() function must be in a try statement so that errors are catched and not raised further.
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "r, web crawler"
}
|
How to access items from ndarray with dtype=object
How can I access data inside a numpy array with `dtype=object`?
b = numpy.array({"a":[1,2,3]}, dtype=object)
The following raises an `IndexError`.
print(b["a"])
IndexError: only integers, slices (`:`), ellipsis (`...`), numpy.newaxis (`None`) and integer or boolean arrays are valid indices
|
Since you passed in the dict to `numpy.array()` without putting it in a list, this is a zero-dimensional array. To index into a zero-dimensional array, you can use `b.item()` to access the element inside. For completeness, to access the data in the `"a"` key in your dictionary, you can use this.
>>> b.item()["a"]
[1, 2, 3]
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 0,
"tags": "python, numpy, numpy ndarray"
}
|
Have external php script output to block
I have a folder in magento root dir with a php script and want to run/output it in a block. What code is needed to run the script in a block?
|
You can try using include inside block's template.
|
stackexchange-magento
|
{
"answer_score": 1,
"question_score": 0,
"tags": "magento2, php"
}
|
Dynamic terminal title: show server load status at X second interval
When I have a bunch of terminals open in my WM it would be nice if terminal window titles reflected current user and host (easy) along with dynamic server load details, updated at some interval (hard-er).
Using PROMPT_COMMAND I can get the desired data into terminal window title; however, it requires _my doing something_ (changing directories for example) for the window title to update with latest information. Ideally, like many, I would prefer to do nothing.
So, is there some kind of set timeout interval-y magic I can apply to get the window title dynamically updated without user interaction?
function curr_load {
# interval wrapper here, or somewhere at any rate ;-)
uptime
}
PROMPT_COMMAND='echo -ne "\033]0;${USER}@${HOSTNAME} [`curr_load`]\007"'
Thanks for clues
|
The only way I'd know of would be a background process. You could either start this automatically with .bash_profile or similar (but you would probably want to check you were in an xterm and also this will cause load as every window will display it), or start it once manually when you login.
So for example using your code above, create a file in the PATH called printload set to exec containing:
#!/bin/bash
function curr_load {
# interval wrapper here, or somewhere at any rate ;-)
uptime
}
while true;
do
echo -ne "\033]0;${USER}@${HOSTNAME} [`curr_load`]\007"
sleep 3
done
And then just start printload with:
printload &
Which you can of course put itself into a script to be called automatically or manually.
** NOTE: Not tested for syntax but should work in theory **
|
stackexchange-superuser
|
{
"answer_score": 2,
"question_score": 0,
"tags": "terminal, resource usage, title"
}
|
Expression language for IP address
what is the corressponding expression for getting ip adress of server, as ${pageContext.request.serverName} is for getting the server name
|
${pageContext.request.localAddr}
|
stackexchange-stackoverflow
|
{
"answer_score": 4,
"question_score": 0,
"tags": "jsp, el"
}
|
PHPEXCEL cambiar formato de fecha
Estoy teniendo un problema al recoger fechas de la base de datos con `PHP` y mostrarlas en un `xls`. Os comento, tengo una base de datos donde los campos con fechas se muestran con este formato: **2017-04-07 00:00:00**
Leo estos datos con una consulta y los escribo en un `xls` usando la librería `PHPEXCEL`, mi problema es que necesito obtener las fechas en formato **dd/mm/aaaa** y sólo estoy consiguiendo obtener el mismo formato de la base de datos con `$sheet->setCellValueByColumnAndRow(10,$fila,$row['FUV']);` o si utilizo el siguiente código para la fecha que he puesto antes:
$sheet->setCellValueByColumnAndRow(10,$fila,PHPExcel_Shared_Date::PHPToExcel($row['FUV']));
Obtengo el número **42415** en la celda.
Sé que estoy haciendo algo mal o me falta algo por hacer pero no veo mas información.
Gracias de antemano
|
Eso puedes hacerlo en la consulta `SELECT` que trae los datos de la base de datos, aplicando **`DATE_FORMAT`** a la columna de fecha.
Por ejemplo, asumiendo que tu columna se llama `FUV`, sería cuestión de escribir la consulta así:
SELECT DATE_FORMAT(FUV, "%d-%m-%Y") AS FUV FROM tuTabla;
Haciendo eso, la columna `FUV` ya vendrá en formato `dd-mm-yyyy` y podrás mostrarla tal cual en el Excel.
|
stackexchange-es_stackoverflow
|
{
"answer_score": 2,
"question_score": 2,
"tags": "php, date, phpexcel, formato"
}
|
CSS Button with both Radius and Arrow, Possible?
I'm creating a site where I need both of these styles on the same button. I need a radius on the left hand side with the right hand side being an arrow. I've tried a few things. example the old fashioned background image with it aligned right for the arrow. Adding the web-kit radius to the button which didn't work out to good.
In the past I'd create the button as a back ground image. But with CSS3 and a bit of magic I'm sure there's a much better way to achieve this?
Anyone got a cleaner solution to the problem? I've had a google with a few coffee's But nothing quite does what I'm trying to do.
-I'm using bootstrap 2.3 has a framework so this would need to work on as many browsers as possible and at multiscreen resolutions.
!IMAGE OF WHAT THE BUTTONS LOOK LIKE ON THE PSD.
|
This is possible through usage of the `:before`/`:after` pseudo elements.
**jsFiddle here** \- Basic example
**HTML** \- pretty simple
<div></div>
**CSS**
div {
width: 200px;
height: 50px;
background: black;
position: relative;
border-top-left-radius: 10px;
border-bottom-left-radius: 10px;
}
div:before {
content: '\A';
position: absolute;
right: -20px;
width: 0;
height: 0;
border-top: 25px solid transparent;
border-bottom: 25px solid transparent;
border-left: 30px solid black;
z-index: 10;
}
div:after {
content: '\A';
position: absolute;
right: -30px;
width: 0;
height: 0;
border-top: 25px solid transparent;
border-bottom: 25px solid transparent;
border-left: 30px solid blue;
}
|
stackexchange-stackoverflow
|
{
"answer_score": 5,
"question_score": 2,
"tags": "html, css"
}
|
Amorphous to crystalline: Opposite trend?
Well my book says that on heating- amorphous solids crystalline at some temperature. As far as I know , amorphous solids have a very disordered structure compared to crystalline solids and on further heating the level of disorder should increase. So why do they become more ordered or crystalline at high temperatures or am I missing something fundamental in here?
|
What they say in your book is right. Take the case of polyethylene terephthalate (PET) which is a kind of polyester used in water bottles for example. It's an amorphous polymer (remember the bottles are transparent). When it is heated, the strained chains have the possibility to move and reorder themselves and the polymer becomes partially crystalline. This fact can readily be proved experimentally by heating a piece of PET (over its glass transition temperature, around $74 ^0\mathrm{C}$), then quenching the sample. It becomes white and not transparent which means it's partially crystalline. We can monitor this transformation using a specific instrument called differential scanning calorimeter, where we can notice the formation of an exothermic peak corresponding to crystallization.
|
stackexchange-chemistry
|
{
"answer_score": 4,
"question_score": 4,
"tags": "crystal structure, solid state chemistry"
}
|
ReferenceError: gethostname is not defined
I tried to assign a var with `gethostname()` (1) and with `$_SERVER`(2) and I keep on getting `ReferenceError: gethostname is not defined`.
All I want is to get the current system name into a var using JS which runs in my PHP. What am I doing wrong?
**UPDATE:**
var myVar = gethostname();
or
var myVar = $_SERVER;
|
So, I approached this whole issue a little differently, and my initially approach was wrong to begin with.
I decided to get the IP address by executing
$ipAddress = getenv("REMOTE_ADDR");
Then I wanted to get the host name, so I did a shell execution:
$myArg = "nslookup $ipAddress";
Eventually I used `stripos` to get the start ("name = ") and end ("domain.name") positions of the host name, and eventually I used `substr` to get the hostname out.
I will use the result to pass it to the JS.
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 1,
"tags": "javascript, php, system, server name"
}
|
http handlers and modules for WCF
I realize that handlers and modules are part of the asp.net lifecycle so my question is, is there an equivalent to handlers or modules that can be applied to WCF or ASMX?
The goal is to quickly apply an unhandled error logging module to each of our asp.net sites as well as services without rebuilding them. I was able to build a module for the asp.net sites and easily add it in with a single config change.
|
ASMX being a deprecated technology I prefer not talk about it, let's leave it die peacefully and as quickly as possible.
As far as WCF is concerned the best way to handle errors is by implementing a custom IErrorHandler and wrap any unmanaged exceptions that might have propagated from operation contracts into fault contracts.
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 0,
"tags": "asp.net, wcf"
}
|
Using Telerik Kendo in ASP.NET Core MVC Web application
I am starting with usage of Telerik Kendo UI in my ASP.NET core sample web application. I am following the guide descried here: < I have paid account for Telerik and the same I am using to install NugetPackge in my solution from private Nuget feed of Telerik.
We are doing a collaborative development using Bitbucket and when others download my solution they get error while Restoration of Packages in .Net Core MVC web app.
Error: Unable to resolve 'Telerik.UI.for.AspNet.Core (>= 2017.1.118)' for '.NETCoreApp,Version=v1.0'.
Do I need to configure the Telerik private feed in every developer's Visual Studio? Can anyone please point me in the right direction how can we use Telerik Kendo for our Product in Production environment. I am new to this, kindly pardon my meager understanding(s).
Thanks.
|
You will need to either:
1) setup the private nuget feed on each other developers environment so they can restore the Telerik Kendo UI package
or
2) configure the private feed in the nuget.config file in the .nuget folder of the solution
<packageSources>
<add key="nuget.org" value=" protocolVersion="3" />
<add key="Contoso Package Source" value=" />
<add key="Test source" value="c:\packages" />
</packageSources>
Reference: <
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 1,
"tags": "kendo ui, asp.net core, telerik"
}
|
How can I find out which site a particular chat room is associated with
Chat rooms are created with a particular site as parent, or with SE as parent (ie no affiliation at all) but when trying to look through chat rooms to see who should have what kind of access I have not been able to find an easy way to identify the parent site.
Is there a quick/easy way to do this?
|
This other answer is for the case you're already inside a room.
If you're looking in the lobby, i.e. list of chat rooms, the parent site icon appears in the top right, below the favorite star icon:
>  and **like dust in the wind** (used to indicate ephemeralness).
|
stackexchange-english
|
{
"answer_score": 1,
"question_score": 2,
"tags": "comparisons, simile"
}
|
How can I compare corresponding items in a python dictionary?
For example, I have two dictionaries:
a = {
'Letters': ['Alpha', 'Beta', 'Theta'],
'Animals': ['Dog', 'Cat', 'Ox']
}
I need to satisfy a condition such that I return a list so that only the values in 'Letters' that are greater than/equal to/less than (as specified) the corresponding values in 'Animals' are included.
Basically, is there a simple way to only compare the values in the list at matching indexes?
'Alpha' vs. 'Dog'
'Beta' vs. 'Cat'
'Theta' vs. 'Ox'
|
To get corresponding pairs, you can use `zip` (think of how a jacket zipper behaves):
>>> a = {'Letters': ['Alpha', 'Beta', 'Theta'], 'Animals': ['Dog', 'Cat', 'Ox']}
>>> zip(a["Letters"], a["Animals"])
[('Alpha', 'Dog'), ('Beta', 'Cat'), ('Theta', 'Ox')]
If you don't care about the order, only about the correspondence, you could reduce this to
>>> zip(*a.values())
[('Dog', 'Alpha'), ('Cat', 'Beta'), ('Ox', 'Theta')]
(In Python 3, make that `list(zip(..))` to get a list, but you can still iterate over it, as in `for pair in zip(*a.values()): print(pair)`, without materializing it.)
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 1,
"tags": "python, list, dictionary, comparison"
}
|
PHP plugin not working in intellij community edition 13.1
I tried enabling it as mentioned here
but nothing worked, any suggestion???
Thanks
|
Because "Some features described here are available in Ultimate edition only." (at the top of this page)
!enter image description here (source: < )
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 0,
"tags": "intellij idea, intellij plugin"
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.