INSTRUCTION
stringlengths 25
999
| RESPONSE
stringlengths 0
999
| SOURCE
stringlengths 16
38
| METADATA
dict |
---|---|---|---|
Using syslog facilities with php error_log
Is posible use syslog **facilities** in php error_log directive or in other way at system/server side?
Something like...
error_log = syslog:local4
error_log = syslog(LOG_LOCAL4)
Using php fpm I can set this with syslog.facility directive in fpm conf, but what about of php cli?
Thanks | Php default syslog's facility is "user" (and cannot be changed)
I use directive **auto_prepend_file** in phi.ini (this script must be under include_path)
auto_prepend_file = log.php
and
root@sp:/etc/php5/cli# cat /usr/share/php5/log.php
<?php
openlog('php-cli', 0, LOG_LOCAL4); | stackexchange-stackoverflow | {
"answer_score": 3,
"question_score": 0,
"tags": "php, syslog"
} |
Java - How to check if a division is an integer or a float?
Couldnt think of a better title. Well the problem is: I have the "int i", it can be any value. my goal is to transform the "int i" to the closest number divisible by **16**.
For example, I got **i = 33**. Then i will be turned to **32** (16x2).But if I get **i = 50** , then it will be turned to **48** (16x3).
I tried many things for example:
for (int x = i; x < 999; x++){
if ( (i - x)/16 *is an integer*){
i = i - x;
}
But I dont know how to check if its an integer. So maybe my previous code work, but I just need to find a way to check if its an integer or a float. So.. any help is appreciated. | Since all ints which are divisible by 16 will have their last 4 bits all set to 0. You can accomplish what you want without a loop or even an if statement:
i &= 0xfffffff0; // Sets i to the greatest multiple of 16 less than i, or 0 for i < 16
For example:
int i = 50;
i &= 0xfffffff0; // i == 48
i = 39;
i &= 0xfffffff0; // i == 32
i = 16;
i &= 0xfffffff0; // i == 16 | stackexchange-stackoverflow | {
"answer_score": 5,
"question_score": 11,
"tags": "java, math, int, division, operation"
} |
Awk add '\t' to output file after inserting a column
I'm using awk to insert a new column in a tab-delimited file, then I want the output to be tab-delimited. However, instead of the expected 5 tab-delimited columns, I'm only getting 2.
awk -v var=$REL_TYPE -F "\t" '{$3=var FS $3 ;}1' $INPUT_FILE > OFS="\t" $OUTPUT_FILE
here is input data:
a1000 a1001 213 1
a1000 a7020 164 2
a1000 a6004 160 3
a1000 a7004 124 4
here is the output data:
a1000 a1001 inserted_column 213 1
a1000 a7020 inserted_column 164 2
a1000 a6004 inserted_column 160 3
a1000 a7004 inserted_column 124 4
At first glance, this looks perfect, however the output has only two columns delimited by '\t', after $3. | You're not setting `OFS` correctly. Putting the assignment after `>` makes it the output file to write to, so it's not parsed as a variable assignment. The following works:
awk -v var=$REL_TYPE -v OFS="\t" -F "\t" '{$3=var FS $3 ;}1' $INPUT_FILE > $OUTPUT_FILE | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "bash, awk"
} |
Are the highlights in this photo a byproduct of the vintage lens or were water particles introduced during shooting?
!enter image description here
The effect seen in this image is popular among garden photographers and most of the time vintage lenses are used. In this case the m42 helios-44m 58mm f2, a lens which i ordered and am anxiously waiting to try out.
I've tried a few times to shoot garden shots against the light source and while sprinkling water, etc with both the Canon f/1.4 50mm and Canon f/2.8 100mm L macro lenses but was never able to achieve such intense, large and perfectly circular highlights.
Can anyone provide the basic recipe on how this is achieved?
Photo source and credit: Frozen 2 by Hana Balasova | I've done similar through rain spotted windows before, so basically the way I would tackle this is with a sheet of clear glass, perhaps from a picture frame, treated with something like Rain-X so that water will bead and then spray it with some water. You could also probably use something like glycerin. Then, basically, shoot through the glass. | stackexchange-photo | {
"answer_score": 7,
"question_score": 10,
"tags": "macro, effect, vintage"
} |
Caching JSON object (.NET C#)
I have the following code that is called on every page request
getJSON('/UserStructure.mvc.aspx/Index', null,
function (dto) {
_userDTO = dto;
}, null, true);
It calls JQuery getJSON behind the scenes.
This seems wasteful, is there anyway of caching this result for the lifetime of the users session?
The session is disabled on the server side for various reasons. | The jqXHR return object could be stored as a session cookie on the browser. If you create a cookie in javascript or C# but do not specify an expiration date, I believe the expiration defaults to the end of the current browsing session. | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": "javascript"
} |
Formation of tetrahydrofuran in the reaction of n-butanol with lead tetraacetate
When n-butanol reacts with lead tetraacetate it forms tetrahydrofuran.
And lead tetraacetate is a good oxidising agent so why doesn't it form n-butanal?
So when does cyclisation take place and why? | The reaction of lead tetraacetate, $\ce{Pb(OAc)4}$ with alkanols, $\ce{R-OH}$, is believed to proceed via an alkoxy-lead acetate, $\ce{R-O-Pb(OAc)3}$.
In this intermediate, the bond between the $\ce{Pb}$ atom and the oxygen of the alkanol cleaves homolytically, this yields an alkoxy radical, $\ce{R-O^.}$ and $\ce{Pb^.(OAc)3}$.
If the alkoxy radical has a hydrogen atom in the $\delta$ position, intramolecular hydrogen atom abstraction may occur.
By this $\ce{CH3CH2CH2CH2O^.}$ is converted to a carbon-centered radical, $\ce{^.CH2CH2CH2CH2OH}$.
The later is oxidized by $\ce{Pb^.(OAc)3}$, which leads to $\ce{Pb(OAc)2}$ and the cation $\ce{^+CH2CH2CH2CH2OH}$.
This cation undergoes cyclization to furnish tetrahydrofuran. | stackexchange-chemistry | {
"answer_score": 6,
"question_score": 5,
"tags": "organic chemistry, reaction mechanism"
} |
unable to use multiple static paths for frontend and backend in expressjs
I am creating a nodejs/backbone application and wish to keep the directories for backend and frontend different. Here is my directory structure:
backend
api
file-uploads
ui
assets
css
images
js
index.html
frontend
assets
index.html
modules
index.js
npm-debug.log
package.json
In the index.js file, i have the following code
app.use(express.static('/admin',__dirname + '/backend/ui/'));
app.use(express.static(__dirname + '/frontend/'));
Now the url / works fine and display the index.html file inside the /frontend directory but the url /admin doesn't work. I am expecting it to display the index.html file inside /backend/ui/ directory. Where I am going wrong here? | You'll want to pass the URL path, `'/admin'`, to [`app.use([path], function)`]( rather than [`express.static(root, [options])`](
app.use('/admin', express.static(__dirname + '/backend/ui/'));
app.use(express.static(__dirname + '/frontend/'));
The middleware only expects a single path, so it's currently attempting to serve files from the `/admin` directory on your harddrive. | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "javascript, node.js, backbone.js, express"
} |
Можно с css изогнуть блок прямоугольник в формы подковы?
Из такого блока как бы практически круг 270 градусов
;
clip-path: polygon(0 0, 100% 0, 100% 90%, 50% 55%, 0 90%);
}
<div></div>
Отвечая на вопрос:
> Можно с css изогнуть блок прямоугольник в формы подковы?
Ответ: однозначно - да. | stackexchange-ru_stackoverflow | {
"answer_score": 2,
"question_score": -1,
"tags": "css"
} |
Adam commutes to school
When the volume of the sound is low, Adam walks home from school. When the volume of the sound is high, he gets a ride. Why? | > The sound is a body of water.
> When the tide is low, he can walk.
> When the tide is high, he goes via boat. | stackexchange-puzzling | {
"answer_score": 8,
"question_score": 7,
"tags": "lateral thinking, situation"
} |
Images use title text, not alt text
> **Possible Duplicate:**
> Also use alt tag as title on images
Alt text does not produce tooltips on Chrome (and maybe other standard compliant browsers).
> The alt attribute specifies alternate text that is rendered when the image cannot be displayed (see below for information on how to specify alternate text ). User agents must render alternate text when they cannot support images, they cannot support a certain image type or when they are configured not to display images. (HTML 4.01 Spec, 13.2)
The standard compliant browser will display only the image, or when that is not possible, only the alt text.
* * *
I propose using:
<img title="This is a tooltip." />
Instead of ~~, or in addition to~~ :
<img alt="This is NOT a tooltip." />
**EDIT:** I am not sure, but I don't think `alt` is valid HTML5.
* * *
> ## References
>
> <
> < | Markdown actually supports both. This:
!Foo
Turns into this:
<img src=" alt="Foo" title="Bar">
And looks like this:
 | stackexchange-meta | {
"answer_score": 13,
"question_score": -2,
"tags": "feature request, alt text"
} |
Array is stored as string. How do I convert it back to any array?
I am using Rails 4.2 with Redis. When I store and retrieve an array with Redis, it returns a formatted string. How do I return this string to an array?
The returned string is exactly this, though the number and value of entries will obviously vary:
"[\"FCF1115A\", \"FCF1116A\"]"
Obviously, it could be parsed, but is there some function that would handle this? I could probably format a better string myself, rather than allowing Redis to do so. Thanks... | If using JSON library is an option. Following is tested in `irb`:
> require 'json'
> puts JSON.parse("[\"FCF1115A\", \"FCF1116A\"]").to_json
=> ["FCF1115A","FCF1116A"] | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 1,
"tags": "ruby on rails, arrays, redis"
} |
Where can I practice MITM raw binary protocols?
I want to try practicing MITMing raw TCP binary protocols as well as MITMing HTTP protocol. What is the best way to do this? Are there any specific tools which help me do this? Like wireshark or ZAP or Burp suite? | I would recommend Kali Linux, formerly known as _BackTrack_ , which has numerous penetration testing tools pre-installed. You could set up either a dedicated machine, or run the OS in a virtualized environment (e.g. VMWare Player).
The tool of most use to you would probably be Ettercap. Wireshark is also included in Kali.
If your computer has multiple NICs, you could start another virtual machine that would act as client. If your computer has only one NIC, you'll need another machine with a network interface (not necessarily a personal computer). | stackexchange-security | {
"answer_score": 0,
"question_score": 0,
"tags": "man in the middle, vulnerability scanners"
} |
What's Ramaze's equivalent to Sinatra's Sinatra::NotFound?
In other words, how do I throw a "404 - not found" in Ramaze? | You can use the `Innate::Helper::Redirect#respond` (source) method which gets included into your controller to return any response:
def my_action
respond("Response body", 404)
end | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 2,
"tags": "ruby, ramaze"
} |
Error when reading in .adf raster file
When reading in a raster dataset I get the below error. Previously I have been able to read this same raster dataset successfully in R in this way, maintaining access to the attribute table and correct field names. I've tried updating the files with backups to eliminate the issue of corrupt files and I still get the below error. Besides corrupt files, what may be causing this error?
> dat2 <\- raster("data/data_LEMMA/lemma_clip/w001001.adf") Error : GDAL Error 3: Failed reading table field info for table lemma_clip.VAT File may be corrupt?
>
> Warning message: In .rasterFromGDAL(x, band = band, objecttype, ...) : Could not read RAT or Category names | This appears to be an ESRI GRID that works fine with Arc, but not with GDAL (when reading the Raster Attribute Table (RAT; or VAT in ESRI speak)). It would be useful if you could make it available for others to look at and look for a solution.
A work-around is to not read the RAT; perhaps that is acceptable in this case.
dat2 <- raster("data/data_LEMMA/lemma_clip/w001001.adf", RAT=FALSE) | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 1,
"tags": "attributes, raster, rgdal"
} |
How to convert column to a row in notepad++
How can I convert
testext
to
t
e
s
t
e
x
t
Please note there is no delimiter. Is there any way? | Go to Search → Find → Replace (Ctrl+F) and type following:
> Find: `(.)`
> Replace: `$1\n`
> SearchMode: `Regular Expression`
> Direction: `Down`
Then place the caret at the beginning of the text and hit "Replace All". | stackexchange-stackoverflow | {
"answer_score": 7,
"question_score": 4,
"tags": "formatting, row, notepad++"
} |
Access Form Paints Too Late
With necessary preliminary tasks in the OnLoad event of my MainForm (via slow-ish called functions: server checks, data retrieval, etc.), the MainForm seems to insist upon painting only upon the conclusion of these preliminary tasks. The result is several seconds of BLANK screen, with no indication anything is happening.
I have provided status messages at each step to a text box on the MainForm (followed by DoEvents), but due to the late painting of the MainForm, they nevery actually appear. However, my code is aware of the controls and their values even though I cannot see them yet.
I have tried sprinkling in Me.Refesh along the way without result.
Any suggestions to paint the form earlier/first, then run those functions? | Move some or all of these calls to a later event:
* OnCurrent
* OnActivate
Or create a _splash screen_ that loads these things, then open your main form.
Set your main form to close the splash screen. | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "ms access, vba"
} |
How to resolve mv cannot stat No such file or directory error
I need to write a bash script. I have a main folder named ABC and the folder contains multiple folders and each folder has multiple files. Now some of the files are named as _servicename_List.java Here `_servicename_` is acting as a placeholder. I need to replace this placeholder with a string that say `XYZ`
I have tried the below solution However It's not working
$Service_Name="XYZ"
cd ABC
for FileName in **/*; do
mv -- "$FileName" "${FileName/_servicename_/$Service_Name}"
done
I'm getting the below error:
mv: cannot stat '**/*': No such file or directory
Can someone help me with the missing part?
Appreciate all your help! Thanks in advance! | You try to use `**` in a glob pattern. By default, this is disabled (you can check it by doing a `shopt globstar`; in your script, it will likely respond with _globstar off_. You can turn it on with
shopt -s globstar | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": "bash"
} |
Azure Auto-scaling Queue includes Dead Letter
I have a worker role with auto-scaling turned on according to queue length on a Service Bus queue. I noticed that my role instances seem to stay scaled up even where there are 0 active items in the queue but several in the dead letter queue.
The metric "Length" on the old portal graph includes the dead letter items. However, it doesn't make sense that the system would scale based on dead letters.
Does anyone know if there is an official statement or documentation on this? | You could leverage auto-forwarding to centralize all of your DLQed messages. This will ensure that your source queues/subscription only contain the messages to be processed. That way your cloud service can scale accurately, based on the number of messages to be processed, without counting DLQed messages in.
Note: your messages will be moved to a centralized DLQ, but will still contain information about source queue. You'll find more info here. | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": "azure, azureservicebus, azure cloud services, autoscaling"
} |
URLmanager настройка
Совсем не разобралась я что-то с urlmanager. Вот есть адрес:
> appt/index.php/appsinfo?id=61
как сделать чтобы он выводился следующим образом:
> appt/index.php/appsinfo/<имя дынных, которые в данный момент показаны на странице>
в конфиге такая картина:
'urlManager'=>array(
'urlFormat'=>'path',
'showScriptName'=>false,
'rules'=>array(
'<controller:\w+>/<id:\d+>'=>'<controller>/view',
'<controller:\w+>/<action:\w+>/<id:\d+>'=>'<controller>/<action>',
'<controller:\w+>/<action:\w+>'=>'<controller>/<action>',
),
.htaacess настроен | ну лучше вообще убрать **index.php** из пути, он там не нужен
'urlManager'=>array(
'urlFormat'=>'path',
'showScriptName'=>false,
**.htaccess**
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*)$ index.php [L,QSA]
А вообще на форуме куча подобных вопросов, они только по разному называются, но по тегу Yii находятся все
Вот пример | stackexchange-ru_stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "url, yii"
} |
css rotated text remove space
<h2><span style="display:inline-block;transform: rotate(90deg);" >###</span>Word</h2>
how can i remove the space between the rotated ### and word (you can see a gap between the objects if you highlight it) I've tried playing with margin and padding but it makes no difference | You can just use a negative value for _margin_.
<h2><span style="display:inline-block;transform: rotate(90deg);margin:-10px;" >###</span>Word</h2> | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 1,
"tags": "css, rotation, css transforms"
} |
Define a compare function for std::map which uses values instead of keys
I can define a compare class for a map like this:
struct classcomp {
bool operator() (const string& lhs, const string& rhs) const
{
if(lhs < rhs)
return true;
else
return false;
}
};
but here `lhs` and `rhs` represent keys. What if I want to compare by values instead of key? How will I do that? | It's not about what _you_ want; it's about what `std::map` wants. The ordering is based on the layout of elements in memory (usually in a tree structure) and it is this process that uses the comparator. Wishing this were not the case does not make it so!
It sounds to me like `std::map` as a container choice does not fit your requirements. Consult a container choice flow chart to decide what to do next. | stackexchange-stackoverflow | {
"answer_score": 4,
"question_score": 3,
"tags": "c++, dictionary, stl, compare, stdmap"
} |
Visual studio keymaps in netbeans (c++)
Is there's a keymap profile for Netbeans that replicate Visual studio's keymapping?
Thanks. | Since it's not possible to map keys depending our your actions (like in VS) its not possible to get an _exact_ dublicate of VS keymapping. Anyway you can make your own:
**`Tools -> Options -> Keymap -> Manage Profiles`** there you duplicate the current one _(as a backup)_
Now you can change the key's towards VS2010. | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 2,
"tags": "c++, visual studio 2010, netbeans"
} |
Proving that R is a partial Order.
> Define the relation $\Bbb R \times \Bbb R$ by $(a,b) \; R$ $ (x,y)$ iff $a \le x$ and $b \le y$ , prove that R is a partial ordering for $\Bbb R\times\Bbb R $ .
A partial order is if R is reflexive on A, antisymmetric and transitive. One must prove these properties true. My question for this problem is trying to comprehend why this problem is antisymmetric and why it is transitive.
$(i)$ $R $ is reflexive as we say $x=a$ and $y = b$. Thus we can conclude that that $x\le x , y\le y$. $(x,y)R(x,y)$.
$(ii)$ if $a\le x$ and $x\le a$ then $x= a $
If $ b \le y $ and $ y \le b$ then $y =b$. Since you interchange these would it not be symmetric?
$(iii)$ Suppose $(a,b) R(x,y)$ and $(x,y) R (c,d)$
This is as far as I got for transitive. Any advice on how prove this partial ordering true would be appreciated. | 1. Of course $R$ is reflexive. For all $(a,b)\in\mathbb{R}\times\mathbb{R}$ it holds $(a,b)R(a,b)$ because $a\leq a$ and $b\leq b$;
2. If $(a,b)R(x,y)$ and $(x,y)R(a,b)$, then both $a\leq x,b\leq y$ and $x\leq a,y\leq b$. It follows $a=x$ and $b=y$, so $(a,b)=(x,y)$
3. Let $(a,b)R(x,y)$ and $(x,y)R(c,d)$. Hence, $a\leq x$ and $x\leq c$, so $a\leq c$. The same for $b\leq d$. Both imply $(a,b)R(c,d)$. | stackexchange-math | {
"answer_score": 2,
"question_score": 3,
"tags": "elementary set theory, relations, order theory"
} |
How to get username from Django Rest Framework JWT token
I am using Django Rest Framework and i've included a 3rd party package called REST framework JWT Auth. It returns a token when you send a username/password to a certain route. Then the token is needed for permission to certain routes. However, how do I get the username from the token? I've looked all through the package documentation and went through StackOverflow. It is a JSON Web Token and I am assuming there is a method like `username = decode_token(token)` but I haven't found such a method. | Basically you could do this
username = request.user.username | stackexchange-stackoverflow | {
"answer_score": 13,
"question_score": 19,
"tags": "django, django rest framework, jwt"
} |
Sharepoint - One feature that creates more than one content type?
Is it possible to create more than just 1 content type with just one feature in Sharepoint?
I've a got a project where a couple of content types inherits from another one and I have 5 features just creating those content types. | Yes. In fact sharepoint has a feature that has basic content types defined in `[12 Hive]/TEMPLATES/FEATURES/ctypes` folder.
Just define multiple `<ContentType>` tags as seen here and it works! | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": "sharepoint, content type"
} |
Adding and Subtracting Timecode in Excel
I need to add and subract timecode in excel. My format for timecode is hh:mm:ss;ff or hours:minutes:seconds;frames.
So an example of subtraction would be 01:01:07;27 - 00:00:06;00 = 01:01:01;27
I need to know how to enter the subtraction formula in Excel. | use this formula:
=TEXT(INT(((LEFT(A1,FIND(";",A1)-1)+(MID(A1,FIND(";",A1)+1,3)/(29.97*24*60*60)))-(LEFT(B1,FIND(";",B1)-1)+(MID(B1,FIND(";",B1)+1,3)/(29.97*24*60*60))))*24*60*60)/(24*60*60),"hh:mm:ss") & ";" & TEXT(MOD(((LEFT(A1,FIND(";",A1)-1)+(MID(A1,FIND(";",A1)+1,3)/(29.97*24*60*60)))-(LEFT(B1,FIND(";",B1)-1)+(MID(B1,FIND(";",B1)+1,3)/(29.97*24*60*60))))*24*60*60,1)*29.97,"00.00")
$
> If $\sec(x) = \frac{a}{b}$, find the exact value of $$\cot(x) - \frac{1}{\sin(x)}$$ and $a$, $b$ are positive real values and $x\in(\frac{3\pi}{2},2\pi)$
* I know that $\sec(x) = \frac{1}{\cos(x)}, $ so: $\cos(x) = \frac{b}{a}$
* I used the right angled triangle to find the third side, which is $\sqrt{a^2-b^2}$
* I used reciprocal functions of $\tan$ and $\sin$ to obtain the values:
$cosec(x) = \frac{a}{(\sqrt{a^2-b^2})}$ and $\cot(x) = \frac{b}{\sqrt{a^2-b^2}}$
and finally getting $\frac{(b-a)}{\sqrt{a^2-b^2}}$ as my answer. But that is not correct. The correct answer is: $\frac{\sqrt{a^2-b^2}}{a+b}$. Now I am wondering how. | * Remember, when using a right-angled triangle to determine trigonometric values, we are actually _**just**_ determining their _absolute_ values (i.e., dropping any negative sign).
This is evidenced by the fact that the process evaluates ratios of triangle _lengths_ , each of which is expressed as a _nonnegative_ value in the form $\sqrt{u^2\pm v^2}.$
In the given example, since $x$ is located in the fourth quadrant, $\operatorname{cosec}x$ must be negative and so equals $\displaystyle\mathbf-\left(\frac a{\sqrt{a^2-b^2}}\right)$ rather than $\displaystyle\frac a{\sqrt{a^2-b^2}}.$ | stackexchange-math | {
"answer_score": 1,
"question_score": 3,
"tags": "algebra precalculus, trigonometry"
} |
AngularJS how can I call functions after multiple ajax requests are succeeded?
I'm using for loop to send ajax requests to delete multiple items in datatables. Is there any way I can call functions after all the requests are succeeded? Calling functions after every request bring some issues for my datatables, also it's not working if calling functions outside of loop cause they're asynchronous requests
for(var i = 0; i < $scope.selectedRows.length; i++) {
$http({
method: 'DELETE',
url: $scope.url + '/' + $scope.selectedRows[i].name + '?recursive=true'
})
.then(function(res) {
// $scope.clearSelect();
// $scope.dtInstance.rerender();
// $mdDialog.hide();
}, function(res) {
console.log('error');
})
} | You should collect the promises of the requests and use the
$q.all(promises).then(...)
Look here: wait for all $http requests to finish | stackexchange-stackoverflow | {
"answer_score": 3,
"question_score": 1,
"tags": "javascript, angularjs"
} |
Pidgin facebook IM protocol line
I spent my last 3hours trying to remove this annoying line from Pidgin facebook IMs. Does anyone know how can I make it disspear? I just want messaging to look clear and compact
Here is the image of what I am talking about: < | Set an alias for yourself. Setting one in facebook directly might work.
If not check the `Accounts->[your facebook account]` menu for a `Set nickname` menu item or `Set User Info` menu item.
If those don't exist or changing them doesn't help your problem then a local account alias definitely will. Select the `Accounts->[your facebook account->Edit Account` menu item and then fill in the `Local alias` field.
None of these will remove that line but they will control what you _see_ for yourself on that line. | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": "pidgin"
} |
CRM 4.0 in C# or .NET
I know this is a stupid question for most of the CRM developers but I'm just a beginner and really want to know more about CRM
Just want to ask if it's possible to construct code using C# in OnLoad/OnChange/OnSave events instead of Javascript.
I know a lot about Javascript but I want to know more on coding CRM using C# and VB.NET
Thank you very much. | the OnLoad/OnChange/OnSave events of a Dynamics CRM Form can be customized only with JavaScript, C# code can't be executed for these client-side events. | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": -4,
"tags": "c#, crm, dynamics crm 4, microsoft dynamics"
} |
Is there a bang version of the 'join' method?
In Ruby, how can I convert an array to a string in the most efficient manner?
@x = ["foo","bar"]
@x = @x.join(", ") #=> "foo, bar"
Just wondering if there's a slightly better way to do this. | > Just wondering if there's a slightly better way to do this.
Would you like this using **_`Array#*`_** ?
x = ["foo","bar"]
x *", " # => "foo, bar"
Note:- `Array#*` method with an string argument will give you a new string object. | stackexchange-stackoverflow | {
"answer_score": 6,
"question_score": 1,
"tags": "ruby"
} |
Redefining a variable inside a newcommand
I have the following code:
\documentclass{article}
\usepackage{tikz}
\usepackage{graphicx}
\newlength{\cm}
\setlength{\cm}{1cm}
\newcommand\scalefactor{2}
\newcommand{\bintree}[5]{
\protect{\renewcommand\scalefactor{#5}}
\resizebox{\scalefactor\cm}{!}{%
\begin{tikzpicture}%
\draw (0,0)--(0,.5);%
\draw (0,.5)--(-.5,1);%
\draw (0,.5)--(.5,1);%
\node[below] at (0,0){#3};%
\node[above] at (-.5,1){#1};%
\node[above] at (.5,1){#2};%
\node[right] at (0,.4){#4};%
\end{tikzpicture}}}
\begin{document}
\bintree{$s$}{$s$}{$s$}{$*$}{1}
\bintree{$s$}{$s$}{$s$}{$*$}{3}
\end{document}
Unfortunately, it doesn't seem to work (I don't get the rescaling I would like). Here's what I obtain:
--(0,.5);%
\draw (0,.5)--(-.5,1);%
\draw (0,.5)--(.5,1);%
\node[below] at (0,0){#3};%
\node[above] at (-.5,1){#1};%
\node[above] at (.5,1){#2};%
\node[right] at (0,.4){#4};%
\end{tikzpicture}}}
\begin{document}
\bintree{$s$}{$s$}{$s$}{$*$}{1}
\bintree{$s$}{$s$}{$s$}{$*$}{3}
\end{document}
although you didn't need `\cm` or `\scalefactor` at all you could just do
\resizebox{#5cm}
and never apply `\protect` to `{` it can never do anything useful and will usually generate weird errors. | stackexchange-tex | {
"answer_score": 2,
"question_score": 2,
"tags": "macros"
} |
Windows hosts: how can I redirect HTTPS site?
I have the following in my `C:\Windows\System32\drivers\etc\hosts`:
127.0.0.1 example.com
It works when I use: <
But does not work when I use: < which gives error ERR_CONNECTION_REFUSED.
Any idea how to use hosts with an HTTPS site?
If not, any alternative? | The following in your `hosts` file
127.0.0.1 example.com
...makes both < and < go to 127.0.0.1, hence: your own machine. (Even more: _anything_ that refers to `example.com`, such as `ping` or `telnet` would go to 127.0.0.1 when run from your computer.)
Apparently you have a web server running on your own computer on port 80 (HTTP), but nothing on port 443 (HTTPS). Even more, getting `ERR_CONNECTION_REFUSED` actually proves your `hosts` file is used, as otherwise you would see the default website from <
Note that if you would have the server on your computer also support HTTPS on port 443, you'd get certificate errors, as there is no way _you_ can buy a certificate for the domain `example.com`. | stackexchange-superuser | {
"answer_score": 12,
"question_score": 15,
"tags": "windows, https, hosts"
} |
Bijectivity of sinx on the interval $[-\pi, \pi]$ to $[-1, 1]$.
how can I prove that sinx is a bijective map from the domain $[-\pi, \pi]$ to the co-domain $[-1,1]$. I had no problem proving that using the graphical representation of sinx, but rigorously could not.
Any help | $\sin$ is not a bijective map from $[-\pi, \pi]$ to $[-1, 1]$. If it was, then $\forall a,b \in [-\pi, \pi]$, $\sin(a) = \sin(b) \implies a = b$. However notice that $\sin(-\pi) = \sin(\pi) = 0$ and $-\pi \neq \pi$. Therefore we have a contradiction.
Restrict yourself to $[-\pi/2, \pi/2]$ and then you have bijectivity. | stackexchange-math | {
"answer_score": 1,
"question_score": 0,
"tags": "algebra precalculus, trigonometry"
} |
Can I return a string using the @helper syntax in Razor?
I have a RazorHelpers.cshtml file in `app_code` which looks like:
@using Molecular.AdidasCoach.Library.GlobalConstants
@helper Translate(string key)
{
@GlobalConfigs.GetTranslatedValue(key)
}
However, I have a case where I want to use the result as the link text in an `@Html.ActionLink(...)`. I cannot cast the result to a string.
Is there any way to return plain strings from Razor helpers so that I can use them both in HTML and within an `@Html` helper? | Razor helpers return `HelperResult` objects.
You can get the raw HTML by calling `ToString()`.
For more information, see my blog post. | stackexchange-stackoverflow | {
"answer_score": 35,
"question_score": 32,
"tags": "string, asp.net mvc 3, razor, type conversion, razor declarative helpers"
} |
Installing Nvidia driver creates GUI?
Ubuntu server by default uses the open source driver nouveau. I have to have the Nvidia driver from what I have read in order for Plex to be able to use it for transcoding. The card is a Quadro K-2000 I install the driver using,
sudo apt-get install nvidia-driver-450
upon reboot, I have a weird GUI that I will try to describe to the best of my abilities.
It is a solid blue with the word 'Activites' in the top left, date in the top center and audio, shutdown in top right. When I click 'Activites' I get to two options, Help and Show Applications.
Is this normal?
If it is, is there a way to use Nvidia's driver without getting this odd GUI that doesn't even have a terminal anywhere I can find? | It looks like _gnome-shell_ is also installed with _nvidia-driver-450_. But the prompt does warm about that as you can see here
Type `Ctrl`+`Alt`+`F3` to switch a terminal (TTY)
Here is an article that explains How To Switch Between TTYs
Edit: I tested installing _nvidia-driver-450_ on a Ubuntu server 20.04 and gnome-shell was installed as well. | stackexchange-askubuntu | {
"answer_score": 1,
"question_score": 0,
"tags": "nvidia, gui, gpu driver"
} |
How to add internal css (<style>) to a Wicket page
I need to include my css file as an _internal css_ using `<style>`. How can I do that with Wicket?
I know about `renderHead()` and `<wicket:link>` as described here. But that creates external links. This is for sending mail, so I need it contained in the generated html. | Here is how I eventually implemented it. Thanks to Nicktar for pointing in the right direction.
@Override
public void renderHead(IHeaderResponse response) {
try {
InputStream in = new CssPackageResource(BusinessMail.class,
"style.css", getLocale(), "?", "?")
.getCacheableResourceStream().getInputStream();
String data = new java.util.Scanner(in).useDelimiter("\\A").next();
response.renderCSS(data, "notneeded");
} catch (ResourceStreamNotFoundException e) {
logger.error("Could not load css", e);
}
} | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "java, wicket"
} |
Move constructor and assignment operator: why no default for derived classes?
Why there is default move constructor or assignment operator not created for derived classes? To demonstrate what I mean; having this setup code:
#include <utility>
struct A
{
A () { }
A (A&&) { throw 0; }
A& operator= (A&&) { throw 0; }
};
struct B : A
{ };
either of the following lines throws:
A x (std::move (A ());
A x; x = A ();
but neither of the following does:
B x (std::move (B ());
B x; x = B ();
In case it matters, I tested with GCC 4.4.
EDIT: Later test with GCC 4.5 showed the same behavior. | Reading through 12.8 in the 0x FCD (12.8/17 in particular for the move ctor), this appears to be a GCC bug. I see the same thing happening in 4.5 as you do in 4.4.
I may be missing a corner case on deleted functions, or something similar, but I don't see any indication of that yet. | stackexchange-stackoverflow | {
"answer_score": 5,
"question_score": 6,
"tags": "c++, c++11, move constructor"
} |
How to run jQuery in my C# class?
I have a ASP.NET MVC project and i want to use jQuery on them. as other mention I put the jQuery on head section and found that they will work in firebug.
Now I want to jQuery in my C# class. how i can use them in C# class. I want to run the code but it's never compile where I goes wrong.
public class Manager
{
public static void Test()
{
// i put here jQuery code but they never compiler i try many time.
}
}
what is the right way to use jQuery in C# class. like in javascript code is work if I write but in c# when I want to try something like ajax request.
$.ajax is work fine in javascript but when I want to run them in C# they not compile. What is the right way to send ajax request from c# class.
Please tell me the way I can use jQuery ajax function in c# class. | The main reason you can't is because jQuery is a JavaScript library, not a C# library so it just won't work. However, I'm not sure why you would want to do that.
Your C# code is running server-side, so what does an AJAX request even mean in that context? You are already running code on the server, there is no need to remotely contact the server over HTTP. Just run whatever C# code you need to get the data you want. Using AJAX would be kind of like trying to call yourself on the telephone to ask yourself something. | stackexchange-stackoverflow | {
"answer_score": 6,
"question_score": 1,
"tags": "c#, jquery, ajax, http, request"
} |
Allow http requests once a user ssh'es in
I got a secure web server (apache) that denies users if they don't come from a certain IP.
Sometimes my ip changes, and I want it to allow me.
One way I was thinking was automatically add the ip once I ssh in. Since ssh'ing is done via passphrase auth, it's pretty secure.
Does anyone have any ideas of implementing something like this? | Why don't you register a host name at one of the several dynamic dns providers and add this host name to your apache "allow from" configuration?
You can register and get a fixed host name at < (there are many others) and follow the instructions there on how to update your dynamic IP when changed. There are several way to do this, some routers have this already implemented, if not you would need to install a dyndns update client. | stackexchange-serverfault | {
"answer_score": 1,
"question_score": 1,
"tags": "ssh, apache 2.2, authentication"
} |
Is .document(uid) the same with .whereEqual("uid", uid)?
Is this operation:
db.collection("users").document(uid)
The same with:
db.collection("users").whereEqual("uid", uid)
If a specific uid does not exist, are we still charged with a read operation? Is this available in both cases? Note, that the document is not created yet, there is nothing that can be read. | This code:
db.collection("users").document(uid)
Does not cost any document reads. No document has been read yet. The only thing it does is build a DocumentReference object that can be used to `get()` the document (or add a listener). The `get()` costs a document read.
This code:
db.collection("users").whereEqual("uid", uid)
Also does not cost a document read until you call `get()` (or add a listener). But if you do call `get()`, then it will always cost **at least** one document read, even if no document is present. This is covered in the documentation for pricing:
> There is a minimum charge of one document read for each query that you perform, even if the query returns no results. | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 0,
"tags": "android, firebase, kotlin, google cloud firestore"
} |
Convert numpy array to tuple
**Note:** This is asking for the reverse of the usual tuple-to-array conversion.
I have to pass an argument to a (wrapped c++) function as a nested tuple. For example, the following works
X = MyFunction( ((2,2),(2,-2)) )
whereas the following _do not_
X = MyFunction( numpy.array(((2,2),(2,-2))) )
X = MyFunction( [[2,2],[2,-2]] )
Unfortunately, the argument I would like to use comes to me as a numpy array. That array always has dimensions 2xN for some N, which may be quite large.
Is there an easy way to convert that to a tuple? I know that I could just loop through, creating a new tuple, but would prefer if there's some nice access the numpy array provides.
If it's not possible to do this as nicely as I hope, what's the prettiest way to do it by looping, or whatever? | >>> arr = numpy.array(((2,2),(2,-2)))
>>> tuple(map(tuple, arr))
((2, 2), (2, -2)) | stackexchange-stackoverflow | {
"answer_score": 227,
"question_score": 156,
"tags": "python, numpy"
} |
Why is a game slower (fps) when using a bigger display?
I'm making a game in `Swift` using `SpriteKit`. I have a `SKSpriteNode` who is running a basic action. When I run it on `Xcode` using an Iphone 4s, everything is smooth(high fps). However, when I run it on a bigger display like an Ipad, it's very slow (low fps). Here's is the basic code I use:
var node = SKSpiteNode()
//...
self.addChild(node)
//...
let action = SkAction.scaleBy(4, duration: 2)
//...
node.runAction(action)
Any ideas why? Thanks in advance... Anton | This is a common phenomena but has nothing to do with the different devices, but with the simulator of Xcode.
**Don't compare the simulator-rendering with the real device-rendering.**
If your game works on your iPhone 4S, it will most likely work on any other device. The Simulator isn't as powerful as the device. In 99.9% of all cases, the performance on a real device is much better.
So if you ever want to check the performance of your game, check it on a real device. Apple allows every developer to test it on the device, without buying a developer-account. | stackexchange-stackoverflow | {
"answer_score": 4,
"question_score": 1,
"tags": "ios, swift, sprite kit, lag, frame rate"
} |
Is there a way to access hardware directly in Python?
I want to learn about graphical libraries by myself and toy with them a bit. I built a small program that defines lines and shapes as lists of pixels, but I cannot find a way to access the screen directly so that I can display the points on the screen without any intermediate.
What I mean is that I do not want to use any prebuilt graphical library such as gnome, cocoa, etc. I usually use Python to code and my program uses Python, but I can also code and integrate C modules with it.
I am aware that accessing the screen hardware directly takes away the multiplatform side of Python, but I disregard it for the sake of learning. So: is there any way to access the hardware directly in Python, and if so, what is it? | This seems a great self-learning path and I would add my two-cents worth and suggest you consider looking at the **GObject** , **Cairo** and **Pygame** modules some time.
The Python **GObject** module may be at a higher level than your current interest, but it enables pixel level drawing with **Cairo** (see the home page) as well as providing a general base for portable GUI apps using Python
**Pygame** also has pixel level methods as well as access methods to the graphics drivers (at the higher level) - here is a quick code example | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 11,
"tags": "python, hardware, graphics"
} |
Regex help: get stream url from soundcloud
I'm using this expression `\"streamUrl":"([^]+)\?s` to get the soundcloud stram url. This is the output from RegExr: `"streamUrl":" I need only the url (< without `"streamUrl":"`. | Use look behind assertion:
(?<="streamUrl":").+\?s
Demo | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": -1,
"tags": "regex"
} |
Dynamically add border on div class
In a series of divs containing tables that can be clicked and removed I removed the bottom border to prevent a 'doubled up' border look. However, now I am stumped as to how to add a bottom border but only on whatever element is last/on the bottom.
JSFiddle here: <
Javascript code below that handles the disappearing act for the divs. Could I augment that function to help here?
$(function () {
var nContainer = $(".notification-popup-container");
$("a.notification-popup-delete").click(function (e) {
e.preventDefault();
$(this).closest(nContainer).remove();
});
}); | You could use `:last-child` css selector.
.notification-popup-container:last-child {
border-style: solid;
border-width: 2px;
}
Fiddle: <
Reference: MDN | stackexchange-stackoverflow | {
"answer_score": 4,
"question_score": 1,
"tags": "javascript, jquery, html, css"
} |
Disable filter for only 1 visual on custom tooltip Power BI
I was wondering if it would be possible to disable a filter on 1 specific visual on a custom tooltip. Let me explain with photos:
Desired result with 3 bars:
 in javascript
I am trying to get the screen dimensions on an IPad.
$wnd.screen.width $wnd.screen.height
When I am in landscape mode, the dimensions return 768x1024. This is not what I expect. How can I get the real dimensions of 1024x768?
Note: I am not changing the orientation, I start in landscape mode and stay in that mode. | As the simplest solution, swap width and height if width is lesser than height so you always get the resolution of landscape mode.
function getResolution(){
return {
width: $wnd.screen.width < $wnd.screen.height
? $wnd.screen.height
: $wnd.scree.width,
height: $wnd.screen.height > $wnd.screen.width
? $wnd.screen.width
: $wnd.scree.height
};
} | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 1,
"tags": "javascript, ipad, dimensions"
} |
How do I use the Thread class to execute an arithmetic-like method?
How do I execute this code inside a Thread object?
I want continuous execution, but I a have poor knowledge working with Thread objects. I have a `Number` class, which receives a number as a parameter.
If the number is even, do something, if odd, do something else, eventually what I am after is a continuous evaluation of the number within this framework of conditions with 'number' getting to 1. All elements are to be stored inside an array and querying the `array.last` to return 1.
class Number
attr_accessor :x
def initialize (number)
@x=[]
if (number % 2 == 0)
@x << number/2
elsif (number % 2 != 0)
@x << (number*3)+1
end
print @x.to_s.concat(" ") // unable to continue
end | I think this is what you are trying to do:
def recurse(x, a = [])
a << x
return a if x == 1
if x % 2 == 0
recurse(x/2, a)
else
recurse((x*3 + 1)/2, a)
end
end
recurse 7
=> [7, 11, 17, 26, 13, 20, 10, 5, 8, 4, 2, 1]
recurse 12
=> [12, 6, 3, 5, 8, 4, 2, 1] | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": "ruby, multithreading, module"
} |
Why the value function in js is not working
First I created a input element which will take the text input from the user ...... `<input style=" font-size: 12 px;" type="text" name="text" id="txt">`
Then to this I used some javascript to get the value of the text that the user gives as an input for that I write the below code.... `const text= document.querySelector('#txt').value console.log(text)`
But with this I am not getting any kind of value actually I am just getting an empty null value in the console can anyone please point out the mistake in the code ... | To read the input that a user has typed you need to add an event listener to the jnput element or to an associated submit button.
This snippet gives a simple example. It executes your Javascript when the user hits enter:
const input = document.querySelector('#txt');
input.addEventListener('change', function() {
console.log(input.value);
});
<input style=" font-size: 12 px;" type="text" name="text" id="txt"> | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": "javascript, html, css, input, null"
} |
Can't connect to SQL Server 2005 x64 SP 4 on Windows 7 x64
I have an issue with connecting to SQL Server 2005 x64 SP 4 on Windows 7 x64 with Visual Studio 2008 DataBase edition. I always receives message about error 26 and named pipes provider. It is irrational because I have disabled firewall, enabled named pipes protocol, enabled sql server browser, enabled remote connections etc. Do anybody have an idea why it is happening? :( Please help. | Ok I found the resolution. Visual Studio Database edition keeps connection string to sql server it two places. (two different text boxes - sic!)
Those places are:
1.Options->Database Tools->Data Connections
2.Options->Database Tools->Design-Time Validation Database
If you have named instance you have to put there only the name of a instance without host name. | stackexchange-serverfault | {
"answer_score": 0,
"question_score": 0,
"tags": "windows 7, sql server 2005, visual studio 2008"
} |
MySQL : Multiple row as comma separated single row
I have two tables : DISH and DISH_HAS_DISHES. Dish table has all the dishes and "Dish_has_dishes" table has a one-to-many relationship with "Dish" table. I.e. a dish can have multiple dishes. For example
**DISH** :
dish_id dish_name
1 dish_1
2 dish_2
3 dish_3
4 dish_4
**DISH_HAS_DISHES** :
meal_id dish_id
1 2
1 3
1 4
Here meal_id and dish_id both are IDs from DISH table. Now I want a format like this:
meal_id dish_ids dish_names
1 2,3,4 dish_2, dish_3, dish_4
That is comma separated dish id and names for each meal. How to do that? | Use GROUP_CONCAT FUNCTION
<
SELEct m.meal_Id,
GROUP_CONCAT(dish_id) dish_ids,
GROUP_CONCAT(dish_name) dish_names
FROM DISH_HAS_DISHES m JOIN DISH d ON (m.dish_id = d.dish_id)
GROUP BY meal_Id | stackexchange-stackoverflow | {
"answer_score": 100,
"question_score": 43,
"tags": "mysql, database"
} |
Another invalid genesis file error
I am getting this error this error at creation of genesis block:
[niko@localhost go-ethereum]$ cat /home/niko/saved-niko-home/aet/genesis-test.json
{
"config": {
"chainId": 777,
"homesteadBlock": 0,
"eip155Block": 0,
"eip158Block": 0
},
"difficulty": 131072,
"gasLimit": 2100000,
"alloc": {
"0db459d44280be8d8999b32cc1b22228ad803fa1" : {"balance":1000}
}
}
[niko@localhost go-ethereum]$ build/bin/geth --datadir=/home/niko/saved-niko-home/aet init /home/niko/saved-niko-home/aet/genesis-test.json
Fatal: invalid genesis file: json: cannot unmarshal number into Go struct field Genesis.alloc of type *math.HexOrDecimal256
[niko@localhost go-ethereum]$
Validated with all online JSON validators out there, strict and non-strict, doesn't show any error. What is the problem here? | The problem is that JSON doesn't have a numeric type with the precision required for some fields in the genesis.json. A workaround is to use strings.
{
"config": {
"chainId": 777,
"homesteadBlock": 0,
"eip155Block": 0,
"eip158Block": 0
},
"difficulty": "131072",
"gasLimit": "2100000",
"alloc": {
"0db459d44280be8d8999b32cc1b22228ad803fa1" : {"balance":"1000"}
}
} | stackexchange-ethereum | {
"answer_score": 2,
"question_score": 0,
"tags": "go ethereum"
} |
How does MySQL 5.5 and InnoDB on Linux use RAM?
Does MySQL 5.5 InnoDB keep indexes in memory and tables on disk? Does it ever do it's own in-memory caching of part or whole tables? Or does it completely rely on the OS page cache (I'm guessing that it does since Facebook's SSD cache that was built for MySQL was done at the OS-level: < Does Linux by default use all of the available RAM for the page cache? So if RAM size exceeds table size + memory used by processes, then when MySQL server starts and reads the whole table for the first time it will be from disk, and from that point on the whole table is in RAM? So using Alchemy Database (SQL on top of Redis, everything always in RAM: < shouldn't be much faster than MySQL, given the same size RAM and database? | Read up on innodb_buffer_pool_size.
That's how you tell innodb how much RAM to hold on to for caching. (not using OS page cache)
MySQL 5.5 docs - <
A Nice Blog to Follow - <
Think of Flashcache as a L1 SSD cache sitting in front of your HDD.
I can't speak to the performance of Redis vs MySQL, but MySQL does have other performance overhead in processing statements, ACID compliance, things like that...
If you're all in RAM, performance will be "GOOD" on any system. | stackexchange-serverfault | {
"answer_score": 1,
"question_score": 1,
"tags": "linux, mysql, database, database performance, mysql5.5"
} |
Progressive disclosure control
In the windows API, how do I implement a Progressive disclosure control? | Gonna be a lot of hand coding, probably. If you're using it for a message box, look into TaskDialog: it has something similar built-in. Otherwise you're probably on your own. | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "c++, winapi"
} |
Kafka Streams Add New Source to Running Application
Is it possible to add another source topic to an existing topology of a running kafka streams java application. Based on the javadoc (< I am guessing the answer is no.
My Use Case: REST api call triggers a new source topic should be processed by an existing processor. Source topics are stored in a DB and used to generate the topology.
I believe the only option is to shutdown the app and restart it allowing for the new topic to be picked up.
Is there any option to add the source topic without shutting down the app? | You cannot modify the program while it's running. As you point out, to change anything, you need to stop the program and create a new `Topology`. Depending on your program and the change, you might actually need to reset the application before restarting it. Cf. < | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 0,
"tags": "apache kafka streams"
} |
Change defined states via Actionscript
I use states in a Flex application to switch from normal to fullscreen view. These states are defined in mxml and in a specific tag:
<local:RSVideo
id="video"
width.normal="534"
height.normal="300"
width.fullScreen="100%"
height.fullScreen="100%"
/>
How can i change the width.fullscreen & height.fullscreen in the AS Sourcecode? I need the dimension of the display that are computed at runtime.
Thanks in advance | i think, i found the solution:
<local:RSVideo
id="video"
width.normal="534"
height.normal="300"
width.fullScreen="{Capabilities.screenResolutionX}"
height.fullScreen="{Capabilities.screenResolutionY}"
/>
Thanks for reading my question. If you got another solution. Please, let me know. | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 1,
"tags": "actionscript, flex4.5"
} |
Is it true that $\sum\limits_{n=1}^N e^{in} = \frac{e^i(1-e^{iN})}{1-e^i}$ even if $| e^i | > 1$?
Is it true that $\sum\limits_{n=1}^N e^{in} = \frac{e^i(1-e^{iN})}{1-e^i}$ even if $| e^i | > 1$?
I know this question is quite trivial and I will understand if it gets removed.
I am trying to show that $\sum\limits_{n=1}^\infty \frac{cos(n)}{\sqrt{n}}$ is convergent by using the Dirichlet's test. And taking, for the one series, $cos(n)$, now
$|\sum\limits_{n=1}^N cos(n) |< |\sum\limits_{n=1}^N (cos(n) + i sin(n))| = |\sum\limits_{n=1}^N e^{in}|$
And I am trying to find a value for $|\sum\limits_{n=1}^N e^{in}|$ | Yes, the statement $$ \sum\limits_{n=1}^N e^{in} = \frac{e^i(1-e^{iN})}{1-e^i} $$ for any choice of $e \in \Bbb C$. The only issue you have is whether the limit exists when $N \to \infty$.
Note that the proof (of this and the general geometric series formula) is not particularly difficult. We have $$ \sum\limits_{n=1}^N e^{in} = e^{i} + e^{2i} + \cdots + e^{iN}\\\ e^i\sum\limits_{n=1}^N e^{in} = e^{2i} + \cdots + e^{iN} + e^{i(N+1)} $$ Subtract the two, factor, and solve. | stackexchange-math | {
"answer_score": 1,
"question_score": 0,
"tags": "sequences and series, summation"
} |
Perform actions based on screen presence (Android JAVA)
Say i have two screens ‘A’ and ‘B’, i want to execute action ‘1’ if screen ‘A’ is shown and action ‘2’ if screen ‘B’ is shown. Initially am checking the screen ‘A’ and ‘B’ presence using the if else statement but didn’t work. here is my code
if(screenAisShown())
{
button1.click;
} else if(screenBisShown) {
button2.click;
}
In the first iteration screen A is shown so the if block executes successfully and in the second iteration screen B is shown but NoSuchElementException thrown for if block and the else if is not executed
TIA | you can create a method **isAScreenDisplayed()** and **isBScreenDisplayed()**.
public static boolean isAScreenDisplayed(){
try{
return elementOfAScreen.isDisplayed();
}catch(Exception e){
return false;
}
}
public static boolean isBScreenDisplayed(){
try{
return elementOfBScreen.isDisplayed();
}catch(Exception e){
return false;
}
}
Now you can use if else condition to check which screen is displayed.
if(isAScreenDisplayed){
//do something
}
else if(isBScreenDisplayed){
//do something
} | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": "appium, appium android"
} |
Objective-C - Replace all double new lines with 1 new line?
I have an html string, and I want to allow 1 linebreak at a time. I am trying to replacing all "\n\n" with "\n". But at the end I end up with double line-breaks.
Is it possible to print the content of a string to see what the content is, so instead of going to a new line display "\n" in the output window.
while ((range = [html rangeOfString:@"\n\n"]).length)
{
[html replaceCharactersInRange:range withString:@"\n"];
}
**EDIT:** html has been converted to plain text (so there are no BR tags in the string) | If you have an indeterminate number of newlines that you want to compress into one, you can use NSRegularExpression. Something like:
NSRegularExpression *squeezeNewlines = [NSRegularExpression regularExpressionWithPattern:@"\n+" options:0 error:nil];
[squeezeNewlines replaceMatchesInString:html options:0 range:NSMakeRange(0, [html length]) withTemplate:@"\n"];
(Written in my browser and not tested since I don't have a recent Mac on hand, so let me know if I messed anything up.) | stackexchange-stackoverflow | {
"answer_score": 4,
"question_score": 1,
"tags": "objective c, nsstring, nsmutablestring"
} |
Report processing has been canceled by the user. (rsProcessingAborted)
I am getting below error message while run reports from SSRS server.
Report processing has been canceled by the user. (rsProcessingAborted)
In the SSRS report i am calling the SP and provided the same user permission to the SP(same used in the datasource) but i am getting rsProcessingAborted error message.
Please help me if anyone have idea about the issue
Already tried below things: \- Updated dataset query time out to 1000 seconds \- updated the SSRS site setting query execution timeout to 1000 seconds. | I have added system database(tempdb, msdb, master, modal) mapping to the SSRS user.
Because i am creating the temp table inside the SP so we need the SSRS user permission to store temporary table in temp db and also require msdb.
After changing above things it's working good.
Thanks Guys for your comments. | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 1,
"tags": "reporting services, ssrs 2012"
} |
MySQLdb and regular expression in python
import MySQLdb
x=raw_input('user> ')
y=raw_input('passwd> ')
db=MySQLdb.Connect(host="localhost", user="%s", passwd="%s" % x,y)
cursor=db.cursor()
cursor.execute('GRANT ALL ON squidctrl.* TO sams@localhost IDENTIFIED BY "connect";')
cursor.execute('GRANT ALL ON squidlog.* TO sams@localhost IDENTIFIED BY "connect";')
cursor.close()
question how can i use it right, i don't want to enter username and password in script in beginning, i want to it by myself as i wish. when i try it run i put username and pass, after that mistake
Traceback (most recent call last):
File "test.py", line 8, in <module>
db=MySQLdb.Connect('host="localhost", user="%s", passwd="%s"' % x,y)
TypeError: not enough arguments for format string | You don't need to use string interpolation (`"%s" % ...`) here.
import MySQLdb
user = raw_input('user> ')
password = raw_input('passwd> ')
db=MySQLdb.connect(host="localhost", user=user, passwd=password)
cursor=db.cursor()
cursor.execute('GRANT ALL ON squidctrl.* TO sams@localhost IDENTIFIED BY "connect";')
cursor.execute('GRANT ALL ON squidlog.* TO sams@localhost IDENTIFIED BY "connect";')
cursor.close() | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": "python, mysql python"
} |
Decimal to BASE-26 representation
I wrote code to convert a decimal number to a corresponding alphabetical representation.
Examples:
1: A
2: B
.
.
.
26: Z
27: AA
.
.
.
703: AAA
Here is my approach:
void print(int n)
{
if( n > 0 )
{
n--;
print( n / 26 );
printf( "%c", ( n % 26 ) + 'A' );
}
}
The above code is working correctly. Can I optimize it in terms of readability?
What is the best way to do it?
Now, I want to modify the above code to work like this:
0: A
1: B
.
.
.
25: Z
26: AA
.
.
.
702: AAA
The obvious approach is to add 1 to the input decimal number and pass it to the function in the original code. How can I modify the first program to work it for the second case without adding 1? | After some observations, i have tried the below code & its working for the `Case: 2`.
void print(int n)
{
if(n < 26)
printf("%c", n + 'A');
else
{
print(n / 26 - 1);
print(n % 26);
}
}
See output here. | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "c, number systems"
} |
set the Accept-Language header for crawler in java
I'd like to find the correct method to set the Accept-Language header for my crawler? I read other related answers like Getting imdb movie titles in a specific language and How to set Accept-Language header on request from applet but they didn't work for me (I get this error: "the method is undefined for type connection" Here is part of code:
String baseUrl = "
org.jsoup.Connection con = Jsoup.connect(baseUrl).userAgent("Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/535.21 (KHTML, like Gecko) Chrome/19.0.1042.0 Safari/535.21");
Please help me, I am really new to java.
Thanks | In JSoup, you use the `header` method to set request headers. So the last line of your code will become this. I've just added line breaks for readability.
org.jsoup.Connection con = Jsoup
.connect(baseUrl)
.userAgent("Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/535.21 (KHTML, like Gecko) Chrome/19.0.1042.0 Safari/535.21")
.header("Accept-Language", /* Put your language here */);
For example, to accept English, you'd write `"en"` in place of that last comment. | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 1,
"tags": "java, web crawler, imdb, http accept language"
} |
Change date every 56 rows in excel
my objective is to have the same date repeated in the first 56 rows and then to vary to the next day in row 57. That is: if I start with date 8/31/2013 I expect to have this same date in the following 56 rows and then change it in 57 to 9/01/2013. So far I have been working with this `formula`:
**=IF(MOD(ROW(),56)=1,OFFSET(B2,-56,-1)+1, "")**
I got to have the dates every 56 rows but still, I need to fill row 2-55 with the same date. Is there any formula or VBA code that helps me do that? | In B1 put your desired start date. Then in B2 put and copy down:
=$B$1+INT((ROW()-1)/56)
^\frac{3}{2}}\mathrm{d}x$$
I tried using linear substitution with $ t = x/a $ and then trying to bring it to some combination of the known integral of $\arctan (x) = \frac{1}{x^2+1}$ but I'm not sure it will be helpful because there isn't just $1 $ in the numerator.
Basically, I got stuck very early in the process:
$$\int_2^3 \frac{1+x^3}{(a^2(\frac{x^2}{a^2}+1))^\frac{3}{2}}\mathrm{d}x$$
Thank you. | I suggest breaking it into two integrals, and using the trig substitution $x=a\tan t$ to turn each one into a trigonometric integral. Thus:
$$\begin{align} \int_2^3 \frac{1+x^3}{(x^2+a^2)^\frac{3}{2}}\mathrm{d}x &= \int_2^3 \frac{dx}{(x^2+a^2)^{3/2}} + \int_2^3\frac{x^3}{(x^2+a^2)^{3/2}}dx\\\ &=\int_{\tan^{-1}(2/a)}^{\tan^{-1}(3/a)}\frac{a\sec^2 t}{a^3\sec^3 t}dt + \int_{\tan^{-1}(2/a)}^{\tan^{-1}(3/a)}\frac{a^3 \tan^3 t \cdot a\sec^2 t}{a^3\sec^3 t}dt\\\ &=\int_{\tan^{-1}(2/a)}^{\tan^{-1}(3/a)}\frac{1}{a^2}\cos t dt + \int_{\tan^{-1}(2/a)}^{\tan^{-1}(3/a)}\frac{a\sin^3 t}{\cos^2 t}dt \end{align}$$
Can you get it from there? | stackexchange-math | {
"answer_score": 1,
"question_score": 3,
"tags": "calculus, integration"
} |
Adding an overlay view to UINavigationBar
I have a transparent `UINavigationBar` set with `appearance`, no subclass involved.
I want to add a view that will "act" as the `UINavigationBar`'s background, this view also has an expand/collapse custom search bar (no a subclass of `UISearchBar`). I will call this view an OverlayView.
The reason for this is mostly because the background color should change dynamically.
I have added my OverlayView as a subview of `UINavigationBar`. It displays correctly and It does everything I need. But I when I tap the search text field it won't pick up the tap, i.e. I can't type anything in the search field.
I have `userInteractionEnabled` set to `YES` on both my OverlayView and the `UINavigationBar`.
Should I add my OverlayView elsewhere? How can I get the taps on that view to be recognized? | Try this that may help you.
UISearchBar *searchBar = [UISearchBar new];
searchBar.showsCancelButton = YES;
[searchBar sizeToFit];
[searchBar becomeFirstResponder];
UIView * OverlayView = [[UIView alloc]initWithFrame:searchBar.bounds];
[OverlayView addSubview:searchBar];
self.navigationItem.titleView = OverlayView; | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 1,
"tags": "ios, objective c"
} |
Can this be done with OpenGL?
I'm making a vector drawing application with OpenGL. Is there a way to implement a clipping mask? Ex: if I have Circle A and Circle B, I only want to see the part of circle B which intersects into Circle A's space. Is there a way to do this that isn't very expensif, I do not want to kill my application. Thanks | Jex,
A quick google search for "clipping mask in openGL" had this as the first result. | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 3,
"tags": "c++, c, opengl"
} |
An Original Source Containing the Sermon of St. Leonard of Port Maurice: The Little Number of Those Who are Saved
This rather famous homily of the eighteenth century Franciscan is rather easy to come by on the internet; for example, see
<
However, I have not been able to find a book from which this sermon was extracted; nor, have any of those that have posted this indicated the "ancient" source from which the sermon (now presented in modern English is derived.)
After the end of the sermon, the above link, for example, indicates "This sermon by Saint Leonard of Port Maurice was preached during the reign of Pope Benedict XIV, who so loved the great missionary."
QUESTION: Can anyone cite an original source (an archived old book, perhaps) which contains this sermon of St. Leonard of Port Maurice?
Thank you. | According to the article "Who Are Saved?" on catholicmagazine.news (near the bottom of the page), the aforesaid sermon can be found in:
"Prediche quaresmali". Assisi: Ottavio Sgariglia, 1806, v. III, pp. 146-182.
Some of the other Volumes of this work can be found on Internet Archive, but I was not able to locate Volume III there. Nevertheless, if one goes to Google Books the proof can indeed be found on p. 146, where begins---
"Del Poco Numero Degli Eletti" (Of the Little Number of Elect). | stackexchange-christianity | {
"answer_score": 3,
"question_score": 3,
"tags": "catholicism, soteriology, eschatology, saint, sermon"
} |
Where is the preferred place for select list options
Writing a grails app and I'm not sure if I should do the "FROM" list in the g:select, or pass it in from a list in the controller.
I know when rendering a list of objects, you have to pass it in through the controller, but what about a simple list? Should I still pass it from the controller or generate it on the GSP? | Well, it depends on your requirement. Passing the list from the controller and making use of `optionKey` and `optionValue` gives more control over the `<select >` tag.
Refer docs for more info.
`Should I still pass it from the controller or generate it on the GSP?`
I think let MVC do its work and follow best practice by generating list in controller and simply pass it to view to render instead of generating list in views. | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "grails, controller, gsp"
} |
http header for downloading Microsoft Word and Excel files
I can download my microsoft word successfully if I named it in the filename by default. But if I use $variables to name it. The document extension will be unknown.
Sample:
$No = 1;
$Name = 'John';
$Test = 'Science';
//Download header
$document->save($doc);
header('Content-Description: File Transfer');
header('Content-Type: application/msword');
header("Content-Disposition: attachment; filename='$No_$Name_$Test.docx");
header('Content-Transfer-Encoding: binary');
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize($doc));
ob_clean();
flush();
readfile($doc);
So if i rename my filename as variables. The file download will be without the docx extension. Anyone can advise?
Thanks | Change this
header('Content-Type: application/msword');
to
header('Content-Type: application/octet-stream');
EDIT:
And change
header("Content-Disposition: attachment; filename='$No_$Name_$Test.docx");
to
header("Content-Disposition: attachment; filename=\"{$No}_{$Name}_{$Test}.docx\""); | stackexchange-stackoverflow | {
"answer_score": 6,
"question_score": 13,
"tags": "php, html"
} |
SSL Cert for custom domain endpoint on Azure CDN
We have some content hosted for our Azure application on the Azure CDN - we can access this nicely over https using the standard endpoint address, however for 'neatness' our customer would like to use a custom domain with https - so we can access our assets from < Is this possible with the Azure CDN? | It's currently not possible to use the Azure CDN to deliver content over SSL with a custom domain name.
It would involve giving Azure access to your private key for them to propagate it to all of their sites, so I can't see them offering it anytime soon.
The closest you could get to this is if you used a traffic manager endpoint and served these from your own Azure instances. This would be more costly than running off the CDN though, and won't offer as many sites to benefit from. | stackexchange-serverfault | {
"answer_score": 4,
"question_score": 6,
"tags": "cdn, azure"
} |
Mysql - Can I fetch a subselect result and use it in a WHERE clause?
I want to both fetch and use in a where clause the value returned from a sub-select in MySQL. Is this possible? It seems unecessary to write the sub-query out twice - however if I need to, will MySQL be clever enough to only run it one?
I have tried the following which does not work:
SELECT
(SELECT 1 FROM table WHERE somereallycomplicatedclause = 'something')
AS subselectresult
FROM content WHERE subselectresult = 1
This generates this error:
#1054 - Unknown column 'subselectresult' in 'where clause'
Thanks | you can't use column aliases in a WHERE clause. try putting it in HAVING and it should work then.
Explanation here: < | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 2,
"tags": "mysql, sql, mysql error 1054"
} |
What is the benefit of hypermedia (HATEOAS)?
I don't understand the benefit to HATEOAS for APIs intended for use by programs (as opposed to humans directly browsing your API). Sure, the customer isn't bound to a URL schema but they are bound to a data schema which is the same thing in my mind.
For example, assume I want to view an item on an order, let's assume I've discovered or know the order URL already.
HATEOAS:
order = get(orderURL);
item = get(order.itemURL[5]);
non-HATEOAS:
order = get(orderURL);
item = get(getItemURL(order,5));
In the first model I have to know the fact that the order object has an itemURL field. In the second model I have to know how to construct an item URL. In both cases I have to "know" something ahead of time so what is HATEOAS actually doing for me? | One difference is that the schema is hopefully a standard, or at least can be reused by others.
For example, let's say you're using the Twitter API and you want to support StatusNet too (or instead). Since they use the same data model as Twitter, if the API follows HATEOAS you now just have to change the main URL. If it doesn't, you now have to change _each single URL_ from the code.
Of course, if you need to change the code to put the service's entry point URL anyway, it might not seem so helpful. It really shines is if that URL is dynamically inserted; for example, if you were building a service like Twillio, which would interact with the user's own API. | stackexchange-softwareengineering | {
"answer_score": 7,
"question_score": 21,
"tags": "web development, rest"
} |
create a folder using last id in php
I want to create a folder from my last ID.
$id = mysqli_insert_id();
mkdir($id, 0777, true);
it is not working. how can I create a folder with last ID? | You have to pass the connection parameter to the method :
> **$con=mysqli_connect( "localhost","my_user","my_password","my_db");**
>
> **$id=mysqli_insert_id($con);**
In addiction, the mkdir method takes as first parameter the path of the folder : < | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": -1,
"tags": "php, mysql, sql"
} |
How does this select in MongoDB
How does this select in MongoDB
select cidade
from rendaxeducação
where idheducacao = (
select max(idheducacao)
from rendaxeducacao
where idh=2000
); | db.rendaxeducacao.aggregate([
{$math : {idh : 2000} // fiter only where idh=2000
},
{$group: { _id: 1,
max_idheducacao : {$max : $idheducacao} // find max
}
},
{$project:{ // select cidade
_id:0,
cidade:1
}
}
])
rendaxeducacao = collection | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": -2,
"tags": "mongodb"
} |
Vapourise Predef.any2stringadd in interpreter
I am having problem with `Predef.any2stringadd` that unfortunately is officially considered not a PITA. I changed my API from
trait Foo {
def +(that: Foo): Foo
}
to a type class approach
object Foo {
implicit def fooOps(f: Foo): Ops = new Ops(f)
final class Ops(f: Foo) {
def +(that: Foo): Foo = ???
}
}
trait Foo
Now I can hide that horrible method in _compiled code_ like this:
import Predef.{any2stringadd => _}
However, this fails in my REPL/interpreter environment.
val in = new IMain(settings, out)
in.addImports("Predef.{any2stringadd => _}") // has no effect?
How can I tell the interpreter to vapourise this annoying method? | A workaround seems to be to take the implicit conversion out of `Foo`'s companion object, and place it in the top hierarchy (package object in my real case):
object Foo {
// implicit def fooOps(f: Foo): Ops = new Ops(f)
final class Ops(f: Foo) {
def +(that: Foo): Foo = ???
}
}
trait Foo
implicit def fooOps(f: Foo): Foo.Ops = new Foo.Ops(f)
While I don't know why that should make any difference, it appears it does enough to make the interpreter forget about `any2stringadd`.
(Still, I think a new ticket should be opened in an attempt to remove that method, also given that string interpolation in Scala 2.10 will make it more superfluous.) | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 5,
"tags": "scala, implicit conversion"
} |
Торговый робот на c#
Доброго дня. Есть задача - написать простенького торгового робота для metatrader. Возможно ли это, не используя встроенный скриптовый язык MQL, а с помощью, например .net или java? | Я не специалист в этой области, но как то получал похожий опыт в академических целях.
Если задача написать простенького робота, и нужно обязательно использовать metatrader, то лучше используете MQL и не заморачивайтесь. Для него есть куча примеров, документация и хорошая интеграция с платформой, тестирование на исторических данных.
Если metatrader не обязателен, можете попробовать Oanda \- у этого брокера есть HTTP API, и уже готовый SDK для Java | stackexchange-ru_stackoverflow | {
"answer_score": 2,
"question_score": 0,
"tags": ".net, mql"
} |
How do i solve the integral $ \int_{-\infty}^{\infty} x^3*e^{-ax^2}dx $
I have a hard time doing this problem can anyone help me please ? | Using integration by parts once gives $$\int x^3e^{-ax^2}\mathrm{d}x=-\frac{x^2}{2a}e^{-ax^2}+\frac1a\int xe^{-ax^2}dx=-\frac{x^2}{2a}e^{-ax^2}-\frac1{2a^2}e^{-ax^2}+C$$ Hence the intgeral is equal to $$\begin{align} \int_{-\infty}^\infty x^3e^{-ax^2}\mathrm{d}x &=\lim_{b\to\infty}\int_{-b}^0 x^3e^{-ax^2}\mathrm{d}x+\lim_{c\to\infty}\int_0^c x^3e^{-ax^2}\mathrm{d}x\\\ &=\lim_{b\to\infty}\left[-\frac{x^2}{2a}e^{-ax^2}-\frac1{2a^2}e^{-ax^2}\right]_{-b}^0+\lim_{c\to\infty}\left[-\frac{x^2}{2a}e^{-ax^2}-\frac1{2a^2}e^{-ax^2}\right]_0^c\\\ &=\lim_{b\to\infty}\left(-\frac1{2a^2}+\frac{b^2}{2a}e^{-ab^2}+\frac1{2a^2}e^{-ab^2}\right)+\lim_{c\to\infty}\left(-\frac{c^2}{2a}e^{-ac^2}-\frac1{2a^2}e^{-ac^2}+\frac1{2a^2}\right)\\\ &=-\frac1{2a^2}+\frac1{2a^2}\\\ &=0\\\ \end{align}$$ | stackexchange-math | {
"answer_score": 1,
"question_score": 1,
"tags": "calculus, multivariable calculus"
} |
First order separable differential equations
$$\frac{d^2y}{dx^2}+2\frac{dy}{xdx} = 0$$
Using change of variable equals to $Z=\frac{dy}{dx}$ what is the 1st order separable differential equation for $Z$ as function of $x$?
and solve for $y(x)$. | Let $Z=\frac{dy}{dx}$. Then $\frac{d^2y}{dx^2}+2\frac{dy}{xdx} = 0$ can be written as $$\frac{dZ}{dx}+2\frac{Z}{x}=0.$$ Then $\frac{dZ}{Z}=-2\frac{dx}{x}$. $$\int\frac{dZ}{Z}=-\int2\frac{dx}{x}$$ So it's easy to get $Z=\frac{C}{x^2}$, where $C$ is a constant. Then for $Z=\frac{dy}{dx}=\frac{C}{x^2}$. We get the solution is $y=-\frac{C}{x}+C_0$, where $C_0$ is a constant. | stackexchange-math | {
"answer_score": 1,
"question_score": -1,
"tags": "ordinary differential equations"
} |
Rails 5: Using a model function in a scope
I am trying to use a model function within a scope and was wondering if something like this is possible?
class WeighIn < ApplicationRecord
belongs_to :client
scope :overweight, -> { where("current_weight >= ?", target_weight) }
def target_weight
client.target_weight
end
end
When I call `WeighIn.overweight` I see the error:
undefined local variable or method `target_weight' for #<WeighIn::ActiveRecord_Relation:0x007fb31baa1fb0>
... which makes sense since the `client_id` is changing depending on the `weigh_in`. Is there a different way to ask this question? | I'm guessing you want to do something like `weigh_in.overweight` to get all `WeighIn` with weight greated than `weigh_in.target_weight`. You can't do that the way you want, since a scope is basically a Class method and `target_weight` is an instance method.
What you can do is to add an argument to the scope:
scope :overweight, ->(weight) { where("current_weight >= ?", weight) }
Then add an instance method
def overweight
WeighIn.overweight(target_weight)
end
and now `weigh_in.overweight` returns what you want.
EDIT: if you want to get all overwight weigh_in related to its user the you have to join the tables like @Michelson's answer, something like:
scpoe :overweight, -> { joins(:clients).where('current_weight >= clients.target_weight') } | stackexchange-stackoverflow | {
"answer_score": 3,
"question_score": 0,
"tags": "ruby on rails"
} |
Can i create a home built aircraft with this engine?
< Would this engine work for a homebuilt ultralight aircraft? I am still in the research phase, so i don't know what the weight of the aircraft will be, but I would like to know what a good prop size and max weight that it will be able to fly. | It's a 100cc engine, and it's in the Radio Control section of that web site. It's an engine for model aircraft.
I suppose, technically, that's a home-built aircraft, but you're not going to sit in it! | stackexchange-aviation | {
"answer_score": 5,
"question_score": 0,
"tags": "engine, weight and balance, homebuilt"
} |
How do I preprocess rows fetched with sqlx?
Consider the following example:
package main
import (
"fmt"
"github.com/jmoiron/sqlx"
_ "github.com/go-sql-driver/mysql"
)
type Data struct {
Stuff string
}
func main() {
db, _ := sqlx.Connect("mysql", "root:root@(localhost:3306)/data")
var datas []Data
db.Select(&datas, "select 'a,b' stuff from data limit 10")
fmt.Println(datas)
}
What I'd like to do is have `Stuff` as `[]string`, where it would be split by `,`. I guess I could add an extra `[]string` field and loop over the results populating this field and removing the source data, but that seems inefficient. What's the canonical way to do this in `sqlx`? | While this is not supported out of the box you can create custom struct implementing Scanner interface (<
type StringList []string
// Scan implements Scanner interface and parses
// database result to StringList struct.
func (s *StringList) Scan(src interface{}) error {
var source string
switch src.(type) {
case string:
source = src.(string)
case []byte:
source = string(src.([]byte))
default:
return errors.New("Incompatible type for StringList")
}
*s = strings.Split(source, ",")
for i := range *s {
(*s)[i] = strings.TrimSpace((*s)[i])
}
return nil
}
And use this struct instead of `string`:
type Data struct {
Stuff StringList
} | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "mysql, go, sqlx"
} |
Pythonic way to extract elements from heapq
I am using a **priority queue** (`heapq`) with `datetime.datetime` as priority.
What is the most pythonic way to extract a subset of element from this list if I have the startTime and endTime to search for. (I can not alter the original list, so I must create a new list and return, or return an iterator)
Below is an example of what I have:
>>> import heapq
>>> timeLine = []
>>> from datetime import datetime
>>> heapq.heappush(timeLine, (datetime.now(),'A'))
>>> heapq.heappush(timeLine, (datetime.now(),'B'))
>>> heapq.heappush(timeLine, (datetime.now(),'C'))
>>> timeLine
[(datetime.datetime(2013, 2, 8, 15, 25, 14, 720000), 'A'), (datetime.datetime(2013, 2, 8, 15, 25, 30, 575000), 'B'), (datetime.datetime(2013, 2, 8, 15, 25, 36, 959000), 'C')]
The real application-list is huge. | Heaps are not the ideal structure to perform this operation; if you stick to `heapq`'s public API, the heap will be altered and made useless for further operations. @Anonymous' solution may work, but (IMHO) relies too much on implementation details. While these are publicly documented, I'm not sure if you should really be using them.
Simply sorting the list and doing two binary searches is an easy way to do what you want:
from bisect import bisect_left, bisect_right
def find_range(timeline, start, end):
l = bisect_left(timeline, start)
r = bisect_right(timeline, end)
for i in xrange(l, r):
yield timeline[i]
The only trouble with this approach is that sorting takes O( _n_ lg _n_ ) time in the worst case, but then so does your way of constructing the heap (`heapq.heapify` would take linear time). | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 2,
"tags": "python, python 2.7, priority queue"
} |
Append only numbers to a list from a mixed file
I have a txt file which looks like this:
100.00 gasoline
20.00 lunch
12.50 cigarettes
I want to take only the numbers (100.00, 20.00, 12.50) and append them to a list, how can I do it? I tried with:
tot_us = []
for float in us_file:
tot_us.append(float)
When I print the list i get:
['100.00\tgasoline\n', '20.00\tlunch\n', '12.50\tcigarettes\n']
I was expecting:
['100.00', '20.00', '12.50']
I know is a noob attempt, how can I solve this? | You need to use `.split()` to break up each line into two sections:
total_us = []
with open('somefile.txt') as f:
for line in f:
if line.strip():
bits = line.split('\t')
total_us.append(bits[0])
print(total_us)
Or, you can use the `csv` module:
import csv
with open('somefile.txt') as f:
reader = csv.reader(f, delimiter='\t')
total_us = [row[0] for row in reader]
print(total_us) | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": "python 2.7"
} |
What is called the first container of a thing
Consider the figure below,
-----------
| A
| ----------
| | B
| | --------
| | | C |
| | --------
| ---------------
------------------
what is called "B"?
* the closest container of C
* the direct container of C
* the first container of C
* you suggest
It is not actually the parent. | Since there are three containers, you could describe them easily this way:
A) The outer container
B) The middle container
C) The center container
Note that you could also refer to C as the innermost container.
You could also refer to B as the second container, since it is the second container from the outermost container A. If you want to be very clear when using "second container", you could describe it as "the second container in" or the "second container from the outside". "Second container in" would be used more commonly as it is shorter and easy to understand. | stackexchange-ell | {
"answer_score": 1,
"question_score": 2,
"tags": "word choice, word request"
} |
Can I mix 2GB RAM with 4GB RAM in my HP 635?
I have question that is probably allready answerd but I read so many answers that now I am confused (some said it's ok some said it's not ok it would hurt performance)
My laptop HP 635 \- Link for HP 635
Memory in HP 635: (Samsung 2GB PC3 SODIMM PC10600, M471B5773DH0-CH9, 204 Pin 1Rx8 DDR3 Non ECC PC, 1333MHz)
Memory that I would add \- Link for memory that would put add
Would this work?
If yes, on what should I pay attention to in the future so I don't spin in circles and asking questions that have already been explained? | Theoretically yes the RAM you would add should work. I'd check the manual for the laptop to ensure it supports a broad range of memory addition. Dual-channel setups may, for example, give you problems unless you are using two of the exact same kits.
RAM spec matching:
* ECC: ECC RAM and non-ECC RAM cannot be mixed.
* Generation: DDR3 must be matched with DDR3, DDR4 with DDR4, etc..
* Frequency: This has a little bit of wiggle room, but for best results always match the frequency (measured in MHz).
* Other considerations: Especially with laptops, be sure to read the manual that came with the laptop (or motherboard, if this is a desktop or similar). Some motherboards do not support anything other than exact kit matches (same SKU, literally the same stick of RAM)
Also please check out < | stackexchange-superuser | {
"answer_score": 1,
"question_score": 1,
"tags": "laptop, memory"
} |
Upload a file on a Sharepoint website through c#
I've a file library on a sharepoint 2010. I'm using the Sharepoint library and I want to upload a file.
I found a lot of example about this, the problem is that I've some additional fields in the sharepoint file library, and I don't see how to specify them.
Here is one of the example I saw: <
One of these fields is mandatory so I've to set it when I add a file.
How can I do this?
Thank you! | Here is a sample of how you might do this ("Method 2" in the example):
<
In a nutshell, you need to upload the file first and then update any required metadata fields. | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 1,
"tags": "c#, file, sharepoint 2010, sharepoint clientobject"
} |
Is $F=\{-1, 0, 1\}$ a subfield of $\mathbb C$?
Is $F=\\{-1, 0, 1\\}$ a subfield of $\mathbb C$?
I have just started reading Linear Algebra text by Kenneth Hoffman and Ray Kunze. They wrote that "any subfield of $\mathbb C$ must contain every rational number", this statement implies that $F$ is not a subfield of $\mathbb C$ even though the operations of addition and multiplication on $F$ are defined in $F$.
Am I overlooking some fact? | $F$ is not a subfield of $\mathbb{C}$; it is not closed under addition.
Example: $1+1=2\notin F$. Although $1$ is an element of $F$, $2$ is not. | stackexchange-math | {
"answer_score": 5,
"question_score": 1,
"tags": "field theory"
} |
Remove www from subdomain and then redirect to subdirectory
I'm trying to add some rules to an .htaccess file in a subdomain to:
1. Remove the www from the subdomain (if present) (E.g.: www.subdomain.domain.com to subdomain.domain.com)
2. Redirect to the /beta subdirectory (E.g: subdomain.domain.com to subdomain.domain.com/beta)
I have the second part only:
# Redirect to /beta
RewriteEngine On
RewriteRule ^$ /beta [L]
I've seen a couple of examples here in StackOverflow but they seem to work only for domains, not subdomains. Any help would be appreciated. | To redirect old domain to new domain this should do:
RewriteEngine On
RewriteCond %{HTTP_HOST} ^www.subdomain.domain.com$ [NC]
RewriteRule ^(.*)$ [R=301]
Note that I omitted the `L` directive here (`[R=301,L]`) because you are probably going to add the second directive (/beta redirect) right after this. | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 0,
"tags": ".htaccess, redirect, subdomain, no www"
} |
Js обрезать строку после первого вхождения символа-метки
строка "s_2015-08-1_1_2" нужно оставить "2015-08-1_1_2"
сплитом разбивать на массив и удалять первый элемент, а потом снова собирать думаю не самое лучшее решение
не факт что значение до первого подчеркивания один символ | "s_2015-08-1_1_2".replace(/^[^_]*_/,'') | stackexchange-ru_stackoverflow | {
"answer_score": 3,
"question_score": 0,
"tags": "javascript"
} |
See all an object's properties and values (including child objects)
I was wondering if there was a built in feature in .Net that could output (at runtime) all the properties and values in a given object and, if possible, even including sub-objects.
I'm thinking of Reflection or XML Serializion and saw some people mentioned JSON, but can't really figure out how to do it the right way... Does anyone know if this is possibly a built in feature in .Net or if there's a good example / tool that either already does this or could guide me in the right direction? | You could use the XmlSerializer class or take a look at the JSON.Net framework. | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": ".net, reflection, properties"
} |
django ignore slash in url and take parameter
hi i have url like this:
path('api/v1/store/download/<str:ix>/', DownloadVideoAPI.as_view(), name='download'),
it accept long string .
I want to keep allthing after `download` key in above URL as the parameter.
but when I enter a long string that contains some slash Django says page not found for example when if enter `"/api/v1/store/download/asdasd2asdsadas/asdasd"` will give me 404 not found ...
how can I do that?
this is my view:
class DownloadVideoAPI(APIView):
def get(self, request, ix):
pre = ix.split(",")
hash = pre[0]
dec = pre[1]
de_hash = decode_data(hash, dec) | Well, It's possible to add the extra parameters in the request. you can use re_path method.
# urls.py
from django.urls import re_path
re_path(r'api/v1/store/download/(?P<ix>\w+)/', DownloadVideoAPI.as_view(), name='download'),
ref: < | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 1,
"tags": "python, django, django rest framework"
} |
How to render all html pages in express.js by one app.listen in index.js
I want to render all HTML pages in my project directory in express.js without writing app.listen for all pages.
Is there any way to accomplish this? | So I found the answer for this. It was quite a struggle but I got:-
// Variables
const express = require('express')
const path = require('path')
const http = require('http')
const PORT = process.env.PORT || 3000
const socketio = require('socket.io')
const app = express()
const server = http.createServer(app)
const io = socketio(server)
// Set Static Folder
app.use(express.static(path.join(__dirname,'app')))
// Start Server
server.listen(PORT,() => console.log(`Server Running at ` + PORT))
This is the code. Thanks for your help! And I used socket.io too. | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": "html, node.js, express"
} |
Define a global variable in Nunit SetUpFixture class
Hi I have to use a variable in all my tests make with Nunit
SimpleContainer container = new SimpleContainer();
so I try to put this definition in the setup class:
[SetUpFixture]
public static class TestSetup
{
public static SimpleContainer container = new SimpleContainer();
}
I use static class for ability to write:
IMyClass myClassExpected = (IMyClass)TestSetup.container.GetInstance(typeof(IMyClass), null);
but after running test I get this error: "TestSetup is an abstract class"
I simply don't understand where is the problem | I would suggest you not bother with having a static instance, and instead, use inheritance.
So create a base class, which includes your object:
public class BaseTestFixture
{
public SimpleContainer Container { get { return new SimpleContainer(); } }
}
Have all your tests inherit from this:
public class GoogleTests : BaseTestFixture
{
[Test]
public void GoToGoogle()
{
Container.GetInstance(.....);
}
} | stackexchange-stackoverflow | {
"answer_score": 3,
"question_score": 0,
"tags": "c#, nunit"
} |
SSRS - Bulk update datasources from dev to prod
We've been developing reports in a dev environment for a few months and we're ready for a data migration and to point these reports to a new location.
What I need to do is change the data source for all of these reports without having to go to each report, change the data source, and re-deploy the reports.
I'm thinking I could be able to just change the current data source from the SSRS portal to point to the new location, but I would still need to touch each report and update them in source control.
I also came across a page for the RS.exe utility here. Not sure if that is going to do what I'm looking for.
Is there a best practice for this or is touching each report the only way to accomplish what I'm looking for? | In order to avoid manually configuring individual Data Sources, you will either have to use an existing 3rd party tool or create one yourself that wraps the reporting services api.
I have two suggestions that might not be useful now, since you are ready to deploy, however, they might prove useful in future report development.
1. Use Shared Data Sources. In your reports, configure each Data Set to point to one Shared Data Source. This would allow you to configure the connection information once per instance.
2. Use a dynamic connection string expression for your report Data Source configuration. | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": "reporting services, ssrs 2016"
} |
Is there a way to convert integers in a column to character in R?
I have a data frame which has different clinical variables for patients who either had a heart failure or not?
I have a column as gender with values 0 and 1, 0 corresponding to females and 1 corresponding to males?
My question is
How can I get my data frame column from this
gender
1
1
0
1
0
0
to this...
gender
Female
Male
Male
Female
Male
Female
Female
Is there a way to convert the integers 0, 1 to text "Female" and "Male" | We can pass a replacement vector after converting to index by adding 1 to it. In `R`, the indexing starts from 1, and thus by adding 1 to 0, 1, the values are changed to 1 and 2 respectively which can be used as a position index for replacement
df1$gender <- c("Female", "Male")[df1$gender + 1] | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 1,
"tags": "r, data analysis, data manipulation"
} |
Is there a CSS property I can set to make a character invisible?
My control buttons can have text in a number of different colors. However the current buttons need to have text that does not show. For this I add a class called `current` I realize I could change the colors but is there any property or way to retain color and make a character not visible? | use `color: transparent;` or `visibility:hidden;` | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "html, css"
} |
App crash on pressing home button in iOS?
I am working on a project where I need to call a web service again and again on a screen. It works fine. But the app crash when somebody press Home button to minimize it or when the device lights get dim (after sometime if nobody touches the device). Is there any way to get rid out of this? Kindly advice. | try this variable:
u set bool variable no in info.plist file like
!enter image description here | stackexchange-stackoverflow | {
"answer_score": 4,
"question_score": 0,
"tags": "iphone, ios"
} |
Should posting answers on an old, already-answered, and inactive question be discouraged?
I have a question on Stack Overflow (How does one remove an image in Docker?) which I asked over two years ago, and which was answered in a timely manner by a few people (timely meaning fast enough that it helped me too).
The thing is, this question is fairly popular and still draws answers - **most of them lower-quality duplicates** of the answer which was accepted over two years ago. There's not even any guarantee that these new answers are original content, instead of copies inspired by what's already there.
I'm referring specifically to all answers on that question below the 4-point threshold. The votes for the first two, timely answers are both above 100 points, so arguably they have been found useful by the community.
Should such low-quality and (arguably) not useful answers be discouraged in any way? | This is why we have a Late Answer Review...
I don't think we should be discouraging late answers per se, but we should be discouraging low quality, duplicate answers regardless of when they're posted.
Unfortunately a lot of these slip through the review queue and need to be handled manually. Downvote, flag, and comment as needed.
If you notice an awful lot of these answers on a specific question, you can flag the question and request that it be "Protected" to prevent new users from posting additional answers. | stackexchange-meta_stackoverflow | {
"answer_score": 32,
"question_score": 16,
"tags": "discussion, old questions, answer quality, late answers, popularity"
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.