INSTRUCTION
stringlengths 25
999
| RESPONSE
stringlengths 0
999
| SOURCE
stringlengths 16
38
| METADATA
dict |
---|---|---|---|
Merging 1D and 2D lists in python
I'm trying to set up data to convert to a numpy array. I have three lists. Two are one dimensional, and one is two dimensional.
a = [1,2,3]
b = [4,5,6]
c = [ [7,8],[9,10],[11,12] ]
I want to end up with this:
[ [1,4,7,8],[2,5,9,10],[3,6,11,12] ]
I've tried using `zip()`, but it doesn't delve into the 2D array.
|
Assuming you don't mind if the use of NumPy in the conversion itself, the following should work.
from numpy import array
a = array([1, 2, 3])
b = array([4, 5, 6])
c = array([[7, 8], [9, 10], [11, 12]])
result = array(list(zip(a, b, c[:, 0], c[:, 1])))
Note that `c[:, n]` will only work with NumPy arrays, not standard Python lists.
|
stackexchange-stackoverflow
|
{
"answer_score": 4,
"question_score": 7,
"tags": "python, list, numpy"
}
|
jQuery DataTables add country icons each column
I want to add in DataTables a country icon on each `country` column (with jQuery) which is the same as the text that is displayed on that column.
So when it contains the country US then there is a image before the text that will link to `us.png`.
So, from this:
!Row without flag icons
to this:
!Row with flag icons
(Edited in Chrome DevTools)
I think it can be done with `aaData`, but I don't know how to use that without replacing the whole column.
Somebody has an answer?
|
Use the `fnRowCallback`.
Refer this example from the datatables documentation <
|
stackexchange-stackoverflow
|
{
"answer_score": 5,
"question_score": 6,
"tags": "javascript, jquery, datatables"
}
|
How can we generate random values in Scrypto?
How can we generate random numbers in Scrypto if floating point libraries are not allowed be used? I want to be able to generate unique IDs for NFTs.
|
There are 2 ways to solve this:
1. Self managed - if the data structure is a Vec, we can use `vec.len() + 1` as the generated ID, making things more trivial.
2. Generated Uuid - Scrypto provides `Runtime::generate_uuid` which is a generated number format in Uuid which _should_ guarantee uniqueness
We can also generate values given a max range:
fn get_random(end: usize) -> usize {
let num = Runtime::generate_uuid();
(num % end as u128) as usize
}
// prints number between 0 - 5
info!("{}", get_random(5));
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": -2,
"tags": "smartcontracts, scrypto"
}
|
jquery html() functions puts text on a new line
When I use the `.html()` function, the text is added to a newline instead of inline.
Even when I stick it in a new table cell, it always appears below row I want it.
function add(id)
{
$('#d'+id).html("Loading <img src='Images/loadingGIF.gif'>");
}
HTML:
<p><input type="submit" onclick="add(25)"> <div id="d25"></div>
<p><input type="submit" onclick="add(26)"> <div id="d26"></div>
How do I get the loading message to show up on the same line as the button?
|
DIVs do not generally stay inline. Try replacing the div with a span. If that does not work, style the DIV like so:
display: inline;
|
stackexchange-stackoverflow
|
{
"answer_score": 4,
"question_score": 1,
"tags": "jquery, html, dom"
}
|
How can I create a group of radio menu items in WPF?
WPF seems to be lacking a `RadioMenuItem` class or similar functionality. In `Windows.Forms`, menu items had a `RadioChecked` property, but WPF menu items only have `IsChecked`. I can put actual `RadioButton`s in a `MenuItem`, but this feels weird and looks awkward.
How can I create a group of menu items that function like radio buttons in a WPF menu? For reference, see the "Zoom" menu in IE8.
|
Change the `Template` of the MenuItem to display a RadioButton instead of the standard display
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 6,
"tags": "c#, .net, wpf, winforms, radio button"
}
|
JavaScript Converting string values to hex
I have an array of string-encoded hex values. I need to convert those strings to actual hex values and then be able to compare them (using standard less-than/greater-than/equals). What is the best way to accomplish this?
|
Use the JavaScript parseInt method to convert hex string values into their integer equivalent.
For example:
var value = parseInt("FF", 16);
if (value < 256) {
// do something...
}
|
stackexchange-stackoverflow
|
{
"answer_score": 12,
"question_score": 5,
"tags": "javascript"
}
|
Best way to call one javascript file from another
I am a JavaScript newb but am familiar with the procedural/dynamic workings of Ruby. What is the simplest way to start executing code from a different JavaScript file? All I know how to do is execute code from one file.
|
Node.js uses what is called the Common.JS module pattern. A module exports an object, which is loaded by whatever required the module.
For instance, suppose I have a file called SomeClass.js:
exports = function SomeClass () {
this.func = function () {
console.log('func!');
}
}
Now in my main app.js:
var SomeClass = require('./SomeClass.js');
var someClass = new SomeClass();
someClass.func(); // outputs "func!" to console
You can read more about this in the official docs: <
|
stackexchange-stackoverflow
|
{
"answer_score": 3,
"question_score": 0,
"tags": "javascript, node.js"
}
|
CSS Before and After boxes
I want to draw a simple pencil using CSS only and i am now faced with a problem: Why does declaring before and after selectors seem not to work? I only see the before selector kick in.
The code for what i got right now is here: <
|
It seem to me that you want this.
.pencil {
position: absolute;
bottom: 0;
left: 50%;
margin-left: -5px;
background: #55A5FF;
width: 20px;
height: 150px;
}
.pencil:before, .pencil:after {
width:10px;
background: #4264E8;
height: 150px;
content: "";
display: block;
position: absolute;
}
.pencil:before {
left: -10px;
}
.pencil:after {
right: -10px;
}
Never forget to _position_ your pseudo-elements.
I do not see, however, how this is necessary. You achieve the exact same thing with `border-left` and `border-right`.
|
stackexchange-stackoverflow
|
{
"answer_score": 3,
"question_score": 2,
"tags": "css, pseudo element"
}
|
Losing quality of image while changing from pdf to image using PythonMagick
I am working on changing pdfs to images using PythonMagick. I am successfully changing the formats, but the quality of the image is diminished during this process.
This is the code that i am using.
sample_pdf="test_pdf"
sample_image="test_image"
pdf='/home/path/'+sample_pdf+''
image='/home/path/images/'+sample_image+''
im = PythonMagick.Image(pdf)
im.write(image)
I am losing the quality of image by this process.
While researching i found that the below code helps in retaining the quality of the image by using ImageMagick
convert -density 300 source.pdf -quality 80 target.jpg
is there something similar in PythonMagick? I cant seem to find any, online.
Thanks in advance.
|
Have you tried the `density` and `quality` methods of your instance?
sample_pdf="test_pdf"
sample_image="test_image"
pdf='/home/path/{}'.format(sample_pdf)
image='/home/path/images/{}'.format(sample_image)
im = PythonMagick.Image(pdf)
im.density("300")
im.quality(80)
im.write(image)
You should have look at the API documentation.
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 2,
"tags": "python, image, pdf, imagemagick, pythonmagick"
}
|
How to declare an override of a Java method that throws checked exceptions in Scala?
I'm trying to override the following Java method:
@Override
public void processMeter(MetricName name, Metered meter, Long epoch)
throws IOException {
// implementation
}
This Scala declaration does not compile:
@throws(classOf[IOException])
override def processMeter(name: MetricName, meter: Metered, epoch: Long) {
// implementation
}
The reported error is:
Error:(30, 18) method processMeter overrides nothing
override def processMeter(name: MetricName, meter: Metered, epoch: Long) {
^
I am specifically using Scala 2.9.0.1.
|
The compiler is seeing `scala.Long` instead of `java.lang.Long` so it can't find the method signature to override. Try this:
@throws(classOf[IOException])
override def processMeter(name: MetricName, meter: Metered, epoch: java.lang.Long) {
// implementation
}
|
stackexchange-stackoverflow
|
{
"answer_score": 3,
"question_score": 0,
"tags": "scala"
}
|
URL to open iOS app in App Store web page and iTunes app simultaneously
What is the preferred URL to use to open an iOS app in it's App Store web page as well as the iTunes app (when available on the host device)?
I've tried using the itms:// protocol but this opens the app details in the iTunes app only and so is of no use when the URL is navigated to from an Android or Windows phone for example.
|
I've discovered that the behaviour of a URL opening an iTunes preview web page before automatically opening the iTunes app on the host device (where available) is triggered by affiliate links (which need to track the click before taking the user to the intended destination).
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "html, ios, url, itunes"
}
|
Indent subsequent lines without hanging indent
In Sublime, long lines are wrapped using hanging indent (also known as "reverse indent"). Example:
(I use `"word_wrap": "true"` in my settings).

It seems there is no way to disable hanging indentation in ST for source code. Indeed, this behavior can cause text to be unviewable if it is indented further than the window width - <
It might be worth logging an issue at < to ask the ST devs to consider making an option to disable the hanging indentation.
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "sublimetext2, sublimetext3, sublimetext, sublime text plugin"
}
|
Button can't change color after click
When I click on button, then can't change color back from black to green, when I make mistake?
Codepen
#msform .action-button, #msform .buttons {
text-align:center;
width: auto;
background: #27AE60;
font-weight: bold;
font-size: 14px;
color: white;
border: 1px solid rgba(0, 0, 0, 0.2);
border-radius: 5px;
cursor: pointer;
padding: 10px 5px;
margin: 10px 5px;
-moz-box-shadow: 1px 1px 5px #000000;
-webkit-box-shadow: 1px 1px 5px #000000;
box-shadow: 1px 1px 5px #000000;
}
|
The mistake that you made is using `:focus` to select the button, once clicked on the button, you are Focused on the option button, and the focus will remains until you click on other object which changes your focus. I would recommend that you can read this or use some javascript magic to finish your work.Hope this can help you!
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 1,
"tags": "html, css"
}
|
Building a server to an android application
I checked this thread which actually looks for the same thing that i look - but he didnt got answered. What i'm looking for is a way to connect between server (as a java application) and a client (as a android application) - in a way that the client will be able to call remote methods in the server, and get remote objects from the server. (doesn't matter if it uses AIDL or not..)
I worked with RMI and it's fine - but it unnable to use on Android, so i have to find another way.
Thanks for help!
|
Two possible avenues:
1. Use servlets on the server and pass data via GET/POST
2. JAX - pass data via SOAP requests
I'm sure there are others, too.
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "java, android"
}
|
Using mod_rewrite for split testing on different designs in different dirs
In order to test if a new design is going to be useful, we're doing A/B testing on it. However, the design integrates a large number of files so we don't want to have to keep moving them around.
Is it possible to use mod_rewrite to mask the fact that we've moved both into their own subdirs?
In other words, someone visits < and they see the design located in "public_html/old/" or "public_html/new/" depending on which we have set to show in .htaccess. However, they never know the designs are in subdirs.
|
Try putting this in the htaccess file in your document root:
RewriteEngine On
RewriteCond %{REQUEST_URI} !^/old/
RewriteRule ^(.*)$ /old/$1 [L]
replacing the instances of `old` with `new` as needed.
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "apache, mod rewrite"
}
|
In-lining C arguments to an array
I want to be able to pass a variable number of objects in C to a function, by wrapping it in an array. As an example:
void test(int arr[]) {}
int main (int argc, char** argv) {
test({1, 2});
}
But I'm not certain how to go about creating an in-line array, and googling the problem leads to a lot of unrelated results.
I've also tried these variations:
test(int[]{1, 2});
test(int[2]{1, 2});
However have not found any reasonable way to create this. How is this possible in C?
As a note, I cannot use `varargs`.
**Edit:**
The code used and the compiler error:
void test(int ex[]) {}
int main() {
test(int[]{1, 2});
}
> test.c:4:10: error: expected expression before 'int'
|
Your first attempt was very close - all you needed is to add parentheses:
test((int[]){1, 2});
// ^ ^
// Here |
// and here
This is the compound literal syntax for arrays, which is added in C99. Similar syntax is available for `struct`s, and it also requires parentheses around the type name.
|
stackexchange-stackoverflow
|
{
"answer_score": 3,
"question_score": 1,
"tags": "c, arrays"
}
|
How to import a package from another package
I have a Java desktop application written in IntelliJ. Under src folder i have 2 packages:
main -> Java -> com -> Class A
test -> Java -> demo -> Class B
How do I make class A recognize class B?
When I write import test.* IntelliJ doesn't recognize the folder / package called test.
|
You must import the last package that contains your classes.
import test.java.demo.*;
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": -1,
"tags": "java, intellij idea, import, package"
}
|
Getting map location Python
Is there any way to get the computer geolocation (as in Google Maps "My Location") from a Python script? The computer would always be connected to the Internet.
|
>>> import re,requests
>>> raw = requests.get('
>>> latlon = re.search("GPoint\(([^)]+)\)",raw).groups(0)
>>> lat,lon = map(float,latlon[0].split(","))
>>> print "Latitude:%s Longitude:%s"%(lat,lon)
Latitude:-117.2455 Longitude:46.7322
a couple of caveats ...
1. This probably is not the best method and should not be done over and over again or you might upset the site owners
2. this uses IP lookups so it may not be as good as GPS/wifi coordinates
|
stackexchange-stackoverflow
|
{
"answer_score": 3,
"question_score": 0,
"tags": "python, google maps, geolocation"
}
|
Count number of records returned by group by
How do I count the number of records returned by a group by query,
For eg:
select count(*)
from temptable
group by column_1, column_2, column_3, column_4
Gives me,
1
1
2
I need to count the above records to get 1+1+1 = 3.
|
You can do both in one query using the OVER clause on another COUNT
select
count(*) RecordsPerGroup,
COUNT(*) OVER () AS TotalRecords
from temptable
group by column_1, column_2, column_3, column_4
|
stackexchange-stackoverflow
|
{
"answer_score": 211,
"question_score": 188,
"tags": "sql server, tsql, count, group by"
}
|
Reviewing iCloud Calendars
**Question:** Is there a way to either confirm that an iCloud calendar is empty or, alternatively, to list the contents of the calendar?
**Background:** I have a number of calendars (iCloud, Google and others) that I have created over the years. I now want to manage them down to a smaller number and remove duplicate events and actions.
Currently I am looking at my iCloud calendars. A couple of the calendars appear to be empty because I cannot see anything from them on my calendar when I scroll back and forward through the months. However, it's possible that the calendar my contain something that I have forgotten but don't want to lose.
|
You can access iCloud calendars using the standard CalDAV protocol. As a recent complication you need to setup an app-specific-password to access your account.
You fail to mention what programming environment you want to do this in, but: Building a CalDAV client is a great resource. Basic stuff like listing calendars can also be done quite easily using tools like `curl` and `xmlstarlet`.
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "calendar, icloud"
}
|
Wix Bootstrapper failing to resolve .Net Framework
I need my installer to install the .Net framework as a prerequisite and according to what Ive found online this is the way to do it:
<Chain>
<PackageGroupRef Id="NetFx45Web" />
<MsiPackage SourceFile="... my msi.." />
</Chain>
However, I get this compilation error:
> Error 53 Unresolved reference to symbol 'ChainPackageGroup:NetFx45Web' in section 'Bundle:SetupBootstrapper'. C:\Source\skystoredesktop\SetupBootstrapper\Bundle.wxs 8 1 SetupBootstrapper
What is wrong?
|
Add a reference to WixNetFxExtension to your bundle project
this can be done on the light command line thus:
light Bundle.wixobj -ext WixNetFxExtension
|
stackexchange-stackoverflow
|
{
"answer_score": 7,
"question_score": 1,
"tags": "wix"
}
|
jQuery to validate a form (check for atleast 10 characters and certain value)
On my webpage I have a form where a user enters information for their article. Right now I use jQuery to check if the entered values are not empty, if they are I show an error message.
**Current validation**
//Story Form
$('.error').hide(); //Hide error message initially
$(".button").click(function() { //On button click
$('.error').hide();
var title = $("input#sc_title").val();
if (title == "") { //if title is empty
$("label#title_error").show(); //show error
$("input#sc_title").focus(); //focus on title field
return false;
}
});
Right now it only checks if `title == ""`. How would I edit the code to also check if there are at least 10 characters entered e.g. if title is empty and less than 10 chars are entered, show an error?
|
if user puts 20 space character in the title field in that case title.length returns 20 and it satisfy true condition so you can use jquery trim also
if ($.trim(title) == "" || $.trim(title).length < 10) {
$("label#title_error").show(); //show error
$("input#sc_title").focus(); //focus on title field
return false;
}
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 0,
"tags": "javascript, jquery"
}
|
CW Models in Hatcher
$ being an $n'$-connected CW model for $(X',A')$ implies that the relative groups $\pi_i(W,Z')$ are zero for $i>n'$. I would appreciate some help. I tried looking at the exact sequence of pairs, but I don't see where the $n$-connectedness comes into play.
|
An n-connected CW model $(Z',A') \to (X',A')$ induces an isomorphism $\pi_k(Z') \to \pi_k(X')$ for k > n'. Since $\pi_k(W) \simeq \pi_k(X')$ the long exact sequence for the pair $(W,Z')$ tells us that $\pi_k(W,Z') = 0$ for k > n'
|
stackexchange-math
|
{
"answer_score": 1,
"question_score": 0,
"tags": "algebraic topology, proof explanation"
}
|
Set font size and color in title of shinydashboard box
How can I change the font size and color of `title` in `shinydashboard box()`?
library(shiny)
library(plotly)
library(shinydashboard)
ui <- dashboardPage(
dashboardHeader(),
dashboardSidebar(),
dashboardBody(
fluidRow(
box(width=12)),
fluidRow(
box(title="Title")
)
)
)
server <- function(input, output) {
}
shinyApp(ui, server)
r
|
You can use a header tag and `style` option within it.
library(shiny)
library(plotly)
library(shinydashboard)
ui <- dashboardPage(
dashboardHeader(),
dashboardSidebar(),
dashboardBody(
fluidRow(
box(width=12)),
fluidRow(
box(title=h3("Title", style = 'font-size:42px;color:blue;'))
)
)
)
server <- function(input, output) {
}
shinyApp(ui, server)
$ such that $x^3-4xy+y^3=-1$
> Find all pairs of integers $x, y$ such that: $$x^3-4xy+y^3=-1$$
My analysis:
1. $x$ and $y$ can't be both negative because all terms would be negative and $(x,y)=(-1,-1) \implies (-1)^3-4(-1)(-1)+(-1)^3 =-6 $ would already be too small.
2. Reducing modulo $4$ gives: $x^3+y^3\equiv 3 \pmod 4 \implies (x,y)\equiv(0,3)$ or $(3,0) \pmod 4$
3. WLOG let $x$ be the larger (+ve) one in a solution pair$\implies x\ge y+1$:
$-1 = x^3-4xy+y^3 \ge (y+1)^3 - 4(y+1)y +y^3$
$-2 \ge 2y^3 - y^2 -y$
$-2 \ge (y-1)(2y^2 + y)$
Since $(2y^2+y)\ge 0$ and $y\le-1$
Indeed $(x,y)=(0,-1)$ is a solution fitting all the above (inconclusive) results. However, I don't know how to find a lower bound for $y$ to lock down all possible pairs of $(x,y).$ What's the missing step? Am I completely off?
|
**Hint:** A messy quadratic is better than a simple cubic while dealing with integers. $$x+y=s\implies x^3-4x(s-x)+(s-x)^3=-1 $$
> Simplifying, $$ (3s+4)x^2-(3s^2+4s)x+s^3+1=0$$
> The discriminant must be non-negative, $$\Delta=-(3s+4)(s^3-4s^2+4)\ge 0$$
> If $s\in (-\infty,-2]$ or $s\in [4,\infty)$, $\Delta<0$. Therefore, $s\in\\{-1,2,3\\}$. Only $s=-1$ results in an integer value for $x$.
> $$(x,y)\in \\{(-1,0),(0,-1)\\}$$
|
stackexchange-math
|
{
"answer_score": 2,
"question_score": 3,
"tags": "elementary number theory, contest math, diophantine equations"
}
|
Gwt for building an Android application
I am looking into building my first Android application and was wondering what is the best approach to take for an experienced GWT developer.
During my research I found phone gap which helps you develop for multiple platforms using Html CSS and javascript, when I kept searching I found mgwt and gwt-phonegap which I guess will be great for a GWT developer. Before I start really looking into it I wanted to ask the experienced phone developers around here if I am in the right direction. Maybe using the plain SDK will be easier for me, after all I only want it to run on Android based phones. Maybe someone can offer other alternatives ? My application is pretty simple but demands using some of the phone's APIs like location and notifications.
Thanks!
|
You might be interested in this video which explains the basic concepts around mgwt and phonegap:
Of course there are many different ways that you can go with developing a mobile app and GWT and Phonegap is one of them.
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 4,
"tags": "android, gwt, cordova, mgwt"
}
|
New Temperature Scale
A new temperature scale is to be sued where freezing and boiling temperature of water is at -100 deg N and 100 deg N respectively. Calculate Absolute Zero in Degree N
Answer is -992.6 Degree N
Absolute Zero in C = 273.15 C
I use Ratio and Proportion:
Total Scale in N = 100 - - 100 = 200
Total Scale in C = 100 - 0 = 100
( Current Temp ) / (Overall Scale) = x/200 = 273.15/100
x = 546.3 N
What am I doing wrong? Any Hint? Am I not supposed to use Ratio and Proportion?
|
We would assume that the new scale is an affine transformation of others (this is not explicitly stated, which is problematic because without this assumption there is no way to solve the problem).
Therefore it's simple: come up with an affine function which relates Celsius to the new system:
$$ f(x) = ax + b $$
They give you two points. The freezing point is $-100$ and the boiling point is $+100$. Since we know that this corresponds to $0^\circ\ C$ and $100^\circ\ C$ this gives:
$$ f(0) = b = -100 \\\ f(100) = 100a + b = 100 \rightarrow 100a - 100 = 100 \rightarrow a = \frac{200}{100} = 2 $$
Therefore:
$$ f(x) = 2x - 100 $$
This gives that $f(-273.15) = -646.3$.
|
stackexchange-math
|
{
"answer_score": 1,
"question_score": 1,
"tags": "algebra precalculus"
}
|
Computed column checksum persisted or not?
I have created a computed column which is the checks`cs_file = (checksum([date],[file_name]))` This column is used to search if file for a particular date already exists(using checksum to boost performance). Select code:
select * from files where cs_file = checksum(@date,@filename) and date = @date and @filename = filename
The column is indexed. Will keeping the computed column persisted improve performance? the table is not too large. data inserted in it is around 250 rows perday.
|
There will be no difference in performance between an index on persisted vs nonpersisted column.
However, I hardly believe that you need it at all, a compound index on (date, file_name) or the other way round, depending on selectivity, should suffice.
I suggest to activated `SET STATISTICS IO ON` option on the session and after executing queries with and without the index on computed column and with and without the index on (date, file_name) check the logical reads. Less is better :)
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "sql server, tsql"
}
|
I want to prove that two norms are equivalent but I am struggling with an upper bound
I want to compare the usual norm on $L^2(-1,1)$ with the following:
$$ \Vert f \Vert_H^{2} = \int_{-1}^1 \vert f(x) \vert^2 \frac{1}{1+x^2}dx $$
Now, for sure I have this:$$\Vert f \Vert_H \leq \Vert f \Vert_{L^2} $$ Because $\frac{1}{1+x^2} \leq 1$
I want to now find some M such that $$\Vert f \Vert_{L^2} \leq M \Vert f \Vert_{H}$$
But I am not sure how to go from here.
EDIT: Forgot to say that we can assume f is measurable.
|
We simply have $$\|f\|_{L^2}^2 =\int_{-1}^1 |f|^2 \le 2\int_{-1}^1 |f(x)|^2 \frac1{1+x^2}=2\|f\|_H^2 $$ because $\frac1{1+x^2}\ge\frac12$ for all $x\in[-1,1]$.
|
stackexchange-math
|
{
"answer_score": 3,
"question_score": 4,
"tags": "functional analysis, inequality, lp spaces, upper lower bounds"
}
|
Syntax highlighting (contains, contained) of only the first match
I think it is possible but can not figure how one can highlight only the first match of contained syntax?
syn clear
syntax cluster TitleParts contains=TitleNum,TitleType,TitleRest
syntax match MyTitle /\v^\s+\d+\)\s+.*$/ contains=@TitleParts
syntax match TitleNum /\v\s+\d+\)\s*/ contained nextgroup=TitleType
syntax match TitleType /\v(this|that)/ contained
syntax match TitleRest /\v\(.+\)/ contained
hi link MyTitle Title
hi link TitleNum Statement
hi link TitleType Type
hi link TitleRest Comment
1) this Hello World this (Bla bla bla 1 2 3 4 5)

syn clear
syntax cluster TitleParts contains=TitleFront,TitleTail
syntax match TitleFront /\v^\s+\d+\)\s((this|that)\s)?/ contains=TitleNum,TitleType containedin=@TitleParts
syntax match MyTitle /\v^\s+\d+\)\s+.*$/ contains=@TitleParts
syntax match TitleNum /\v\s+\d+\)\s*/ contained containedin=TitleFront
syntax match TitleType /\v(this|that)/ contained containedin=TitleFront
syntax match TitleTail /\v\(\d+\)\s\(.{-}\)$/ contained containedin=MyTitle
hi link MyTitle Title
hi link TitleNum Statement
hi link TitleType Type
hi link TitleTail Comment
123) this Hello World this (1) (Bla bla bla 1 2 3 4 5)
1) that Hello World this (22) (Bla bla bla 1 2 3 4 5)
. I need to add possibility for users to send and receive messages via XMPP. So, on server I wish to implement connection pool for XMPP connections, but I think it's already done, but google says nothing... Do you now implementations?
|
You can use XMPPPool. I wrote that a long time ago and I don't support it in any way.
However, there it is. I hope you find it useful.
A bit of documentation is available.
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "java, xmpp, connection pooling"
}
|
calculate linear combinations of areas
it seems very easy or maybe easiest,but i want to make sure that i am not missing anything,that why let us consider following problem !enter image description here
clearly it would be $25/9+ln9=25/9+2*ln3$ is it so simply ?thanks in advance,sorry for such question,but i like to make sure in everything,that's why i have posted it here
|
Yes, it is that simple. Your procedure is correct.
|
stackexchange-math
|
{
"answer_score": 1,
"question_score": 0,
"tags": "calculus"
}
|
SmtpException: Cannot get IIS pickup directory
I am trying to send email from my mvc application. Following is a part of the code I am using:
SmtpClient smtpClient = new SmtpClient();
smtpClient.DeliveryMethod = SmtpDeliveryMethod.PickupDirectoryFromIis;
smtpClient.UseDefaultCredentials = true;
smtpClient.Send(message);
The above code is giving the error:
> Cannot get IIS pickup directory SmtpException.
But if I run my Visual Studio as an Administrator, emails are sent successfully.
If I understand correctly, the issue is regarding access permissions, but I just can't figure out what. If Relevant, the application is an intranet application with windows authentication.
|
try setting the pickup directory manually:
// C#
client.PickupDirectoryLocation = ...;
Or set this in ASP.NET's Web.config instead:
<configuration>
<system.net>
<mailSettings>
<smtp deliveryMethod="SpecifiedPickupDirectory">
<specifiedPickupDirectory
pickupDirectoryLocation="..." />
<network defaultCredentials="false" />
</smtp>
</mailSettings>
</system.net>
</configuration>
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 1,
"tags": "c#, asp.net mvc 4, iis, iis 7.5"
}
|
What is a "brake"?
In his classic novel "Sons and Lovers" D.H. Lawrence wrote:
> Mrs. Morel loved her marketing. In the tiny market-place on the top of the hill, where four roads, from Nottingham and Derby, Ilkeston and Mansfield, meet, many stalls were erected. **Brakes** ran in from surrounding villages. The market-place was full of women, the streets packed with men.
What does the word "brake" mean?
|
I think it refers to:
**_Brake_** :
> (Horse Training, Riding & Manège) an open four-wheeled horse-drawn carriage. Also spelt: break
(Collins Dictionary )

|
stackexchange-english
|
{
"answer_score": 3,
"question_score": 5,
"tags": "meaning"
}
|
Can a prepositional phrase be the direct object?
We're covering grammar in English I, and we just got to gerunds. In one of the exercises, I had the sentence "Pilgrims learned about planting crops from the Wampanoags." I'm supposed to find the gerund, and identify its subject in the sentence.
I thought that the gerund would be "planting crops". When I was trying to find its function in the sentence, I used a method my teacher gave me; asking "verb what?" to identify the direct object. This gives "learned about planting crops".
I was wondering, would the function of "planting crops" in the sentence be the object of a preposition, or would the whole prepositional phrase be the direct object (since the gerund acts as a noun).
Or, do I have the whole thing horribly wrong in the first place? =)
Thanks!
evamvid
|
I think you see the whole thing totally wrong.
A direct object never has a preposition.
* I'm reading a novel - a novel is a direct object. You ask: What am I reading?
* I'm waiting for the bus - for the bus is a prepositional object You ask: What am I waiting for?
In your sentence "Pilgrims learned about planting crops from the Wampanoags." "about planting crops" is a prepositional object and "from the Wampanoags" is a second prepositional object.
Maybe English grammars have other terms, but that's the way I see it.
|
stackexchange-english
|
{
"answer_score": 2,
"question_score": 8,
"tags": "grammar, prepositions, gerunds, prepositional phrases, direct objects"
}
|
Deploy scrapyd spider with external packages
The scrapyd docs include the following note:
> scrapyd-deploy won’t deploy anything outside the project module...
Does that mean that I cannot import from site-packages in my spiders?
My spiders rely on external libraries such as MySQL-python and tldextract. Must I include these libraries within the project module and import from the include libraries as opposed to site-packages?
|
I think Deploying your project documentation paragraph should clarify things:
> Finally, to deploy your project use:
>
>
> scrapyd-deploy scrapyd -p project1
>
>
> This will eggify your project and upload it to the target, printing the JSON response returned from the Scrapyd server. If you have a `setup.py` file in your project, that one will be used. Otherwise a `setup.py` file will be created automatically (based on a simple template) that you can edit later.
In other words, you would/should have `MySQL-python`, `tldextract` or other dependencies listed in `setup.py` which would be automatically installed during deployment.
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 3,
"tags": "python, scrapy, scrapyd"
}
|
Use of the word 한걸요
When and why do we use ' **** '? Like I have seen sentences like
**** (Your dream is so precious)
and **** (Your dream is so sweet).
I looked up the meaning of and according to Papago app it means 'I did it'.
I am new to learning korean.
!
EDIT (from comments by OP): This is part of the lyrics for the song : <
|
Welcome!
The word you are trying to translate, , is actually composed of three parts: -(), -, and -.
It would be easy for you to check out the meaning of , so I'll focus on explaining the latter two.
- is used for verb declension, often used for light interjections. For example,
> , ! Wow, that's really great!
and - is one of the most frequently used postpositions, which makes the whole sentence sound a bit more polite, but informal. You'll see these a lot in Korean lyrics.
|
stackexchange-korean
|
{
"answer_score": 1,
"question_score": 2,
"tags": "spoken korean, korean to english"
}
|
Infinite closed partition of the real line with no closed infinite unions
Is there a partition of the real line into infinitely many closed subsets so that no infinite union of these subsets (except the whole space) is closed?
This question was asked also at math.stackexchange.com. While an interesting construction of a partition with no closed _uncountable_ unions was given, there has not yet been a conclusive answer.
Two observations:
1. No infinite subcollection of the partition can be locally finite since the union of a locally finite collection of closed sets is closed.
2. The partition must be uncountable since the real line cannot be partitioned into countably many (and $\geq 2$) closed subsets by a theorem of Sierpiński.
|
Let $\mathcal{F}$ be this partition. As noted above it must be uncountable. We may as well assume it lives on the interval $(0,1)$ and add the set $ \lbrace 0, 1\rbrace$ to each member to obtain a family of closed subsets of $[0,1]$. Now $\mathcal{F}$ is an uncountable subset of the space of closed subsets of $[0,1]$ endowed with the Hausdorff metric. The latter space is separable metric, so $\mathcal{F}$ contains a non-trivial sequence $\langle F_n:n\in\mathbb{N}\rangle$ that converges to a point $F$ of $\mathcal{F}$. The union $F\cup\bigcup_n F_n$ is closed: if $x$ is outside the union, in particular outside $F$, let $\epsilon=\frac12 d(x,F)$. Then there is an $N$ such that $F_n\subseteq B(F, \epsilon)$ for $n\ge N$. This now easily implies that $x$ is not in the closure of the union.
|
stackexchange-mathoverflow_net_7z
|
{
"answer_score": 3,
"question_score": 6,
"tags": "gn.general topology"
}
|
How do I generate a random n digit integer in Java using the BigInteger class?
I am unsure about how to generate a random n digit integer in Java using the BigInteger class.
|
private static Random rnd = new Random();
public static String getRandomNumber(int digCount) {
StringBuilder sb = new StringBuilder(digCount);
for(int i=0; i < digCount; i++)
sb.append((char)('0' + rnd.nextInt(10)));
return sb.toString();
}
And then you can use it:
new BigInteger(getRandomNumber(10000))
|
stackexchange-stackoverflow
|
{
"answer_score": 16,
"question_score": 15,
"tags": "java, biginteger, digits"
}
|
Tell Excel to parse cells with units of measurement as numbers, including multiplier
I have some Excel files containing cells with values like "20 mA", "3.13 µA" , "1.66 mV" and similar.
Would it be possible to somehow ignore the last character ('A' or 'V') and then multiply the number with the suffix automatically?
For example 20 mA should result in 0.02
|
You could try this kind of formula (if your formula is in `A1`):
=CONVERT(VALUE(MID(A1,1,FIND(" ",A1))), MID(A1,FIND(" ",A1)+1,LEN(A1)), LEFT(A1,1))
**Caveats:**
* Will work for the supported units of the `CONVERT` formula
* Will work for the supported prefixes (e.g. `u` for micro `µ`)
|
stackexchange-superuser
|
{
"answer_score": 3,
"question_score": 1,
"tags": "microsoft excel"
}
|
What is the use of creating perimeter after shield is down?
> Admiral Ackbar: Although the weapon systems on this Death Star are not yet operational, the Death Star does have a strong defense mechanism. It is protected by an energy shield which is generated from the nearby forest moon of Endor. The shield must be deactivated if any attack is to be attempted. Once the shield is down, our cruisers will **create a perimeter** while the fighters fly into the superstructure and attempt to knock out the main reactor.
What is the use of creating perimeter after shield is down?
|
The Death Star isn't just a superlaser, it's also a large scale Imperial base. There were some ships (like Star Destroyers) contained inside. The full plan that Ackbar was describing here was a surprise attack, so it was supposed to go something like this
1. The Endor squad takes down the shield just before the main force arrives
2. The Rebel ships jump in and catch the confused Death Star troops unaware
3. **A perimeter would then be established to contain the exiting Imperial ships and fighters**
4. Rebel ships enter the Death Star and blow it up
Remember, they don't know there's hundreds of Imperial ships already outside the Death Star ready to move in once they arrive. As it turns out, this part of the plan was unused and once the shield went down only a handful of Tie fighters even noticed the Rebel ships going in.
|
stackexchange-scifi
|
{
"answer_score": 5,
"question_score": 3,
"tags": "star wars, return of the jedi"
}
|
URL shortener with counter and/or stats
Is there any free URL shortener that supports counting? And maybe some logging? If possible, without any registration. As simple as tinyurl.com if possible.
|
< can do it, and it seems it has more advanced stats. Specifically adding `.info` to the end of the URL to get some detailed analytics.
|
stackexchange-webapps
|
{
"answer_score": 2,
"question_score": -1,
"tags": "url shortening"
}
|
Using Auto layout with hidden views
I have a view controller with a `UIScrollView`. Inside that scrollview I have two `UIViews`. `viewA` sits onto of `viewB`. I am using Xcode 5 and auto layout in this project. What I would like to do is when viewA is hidden, move viewB to the top where viewA was sitting (technically, still sitting, just hidden).
I looked at this SO answer: How to use auto-layout to move other views when a view is hidden?
However it hasn't really helped me. I connected a IBOutlet which was a constant to the vertical spacing to the top of the scroll view and set it to 0.0f when viewA was hidden. However it makes no changes to my UI at all.
|
First get the Top Space to SuperView NSlayoutConstraints Outlets for both subViews and then do the following:-
[self.aView setHidden:YES];
if([self.aView isHidden])
{
self.bViewTopConstraint.constant = self.aViewTopConstraint.constant;
}
using this the second UiView will go to the place of first UIView.
For Scrollview you have to set the constraints value properly. No need to set any contentsize. Once you set the constriants scrollview will work automatically. Check the attached screenshot.
!enter image description here
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 0,
"tags": "ios, xcode5, autolayout"
}
|
Where is the ifcfg file of a (Host-only) virtual network adapter on CentOS?
I'm using a CentOS virtual machine, i have already assigned two network adapters using the VMware Workstation but the Virtual Network Editor lets you change only the Subnet IP, the Subnet Mask and the MAC.
However, i also need to change the `IPADDR`, the `BROADCAST`, the `DHCP_HOSTNAME`, the `ON_BOOT` and the `DEVICE` variables on each network adapter.
I don't see any `ifcfg` file relevant to those two network adapters inside `/etc/sysconfig/network-scripts`. And i don't see those network adapters using the Network Administration Tool (system-config-network).
What is the most appropriate way to change those variables?
|
The interface configuration file under CentOS are named `/etc/sysconfig/network-scripts/ifcfg-<ifname>` where `<ifname>` is the interface name. For interface `eth0`, the file will be named `ifcfg-eth0`.
In case someone assign an extra network card or change the configuration of an already existing then make sure to restart the network with `service network restart` in terminal.
|
stackexchange-serverfault
|
{
"answer_score": 2,
"question_score": 1,
"tags": "linux, networking, centos, virtual machines, vmware workstation"
}
|
Bootstrap 4 find element with e.relatedTarget
Hi trying to get data attr after e.relatedTarget in bootstrap's carusel.
$('#carouselExampleControls').on('slide.bs.carousel', function(e){
target = e.relatedTarget
});
when i do console.log got this
<div data-title="[555]" class="carousel-item active">
<img class="d-block w-100" data-children="[ data-parent-id="" data-id="977" src=" alt="8.png">
</div>
Trying to get data-title, type of this is object, tried with $.each not sure how to parse it.
|
To get the value of an attribute from any html element do the following:
var element = document.querySelector('.carousel-item.active');
var title = element.getAttribute('data-title');
considering your code, and using jquery:
$('#carouselExampleControls').on('slide.bs.carousel', function(e){
var target = e.relatedTarget
var title = $(target).attr('data-title'); // same as target.getAttribute('data-title');
});
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "javascript, jquery"
}
|
Does declaring many identical anonymous classes waste memory in java?
I recently ran across the following snippet in an existing codebase I'm working on and added the comment you see there. I know this particular piece of code can be rewritten to be cleaner, but I just wonder if my analysis is correct.
Will java create a new class declaration and store it in perm gen space for every call of this method, or will it know to reuse an existing declaration?
protected List<Object> extractParams(HibernateObjectColumn column, String stringVal) {
// FIXME: could be creating a *lot* of anonymous classes which wastes perm-gen space right?
return new ArrayList<Object>() {
{
add("");
}
};
}
|
The class will only be compiled once (at compile time). The compiler extracts a class (named something like `MyOuterClass$1`) and uses it. It will create multiple instances, of course, but they will all be of the same class. You can see that when you compile the `.java` file and look at the `.class` files generated - there will be one for the inner anonymous class.
|
stackexchange-stackoverflow
|
{
"answer_score": 17,
"question_score": 12,
"tags": "java"
}
|
Reference that lists available JavaScript events?
I'm aware of things like `onchange`, `onmousedown` and `onmouseup` but is there a good reference somewhere that lists all of them complete with possibly a list of the elements that they cover?
|
W3Schools seems to have a good Javascript events reference: HTML DOM Events
|
stackexchange-stackoverflow
|
{
"answer_score": 11,
"question_score": 24,
"tags": "javascript, browser, client side"
}
|
Show AdWords for some users
I'm thinking of placing AdSense on my site, but I'd hate to show AdSense to my paying customers.
Does AdSense policy allow this - showing AdSense only for some users - or do they require that they are shown to all users?
|
Yes can do that. Just like you do not have to show ads on every page.
Depending on how your site is implemented, the paying pages may have a different URL and therefore would be considered different pages.
Since I assume, the Googlebot is not a paying customer, they shouldn't even be able to see that!
|
stackexchange-webmasters
|
{
"answer_score": 1,
"question_score": 1,
"tags": "google adsense"
}
|
Codenameone Plugin not Loaded in Android Studio
I am trying to load the Codenameone Plugin to Android Studio 2.1 but it is giving an error Codenameone Plugin not Loaded(Required Plugin AntSupport is not enabled).
But, in the jetbrains site, it is mentioned that it is compatible with Android Studio. <
Kindly, advise if codenameone can be used in Android Studio. Secondly, how much effort will it take to migrate apps built in Android Studio to IntellJ IDEA IDE.(If codenameone doesn't work).
Thirdly, is it a good idea to use codenameone or to learn SWIFT and do ios apps from scratch.
Thanks Sourav
|
The download page explicitly excludes Android Studio from the supported platforms. Unfortunately Google seems to declare that it supports some features (such as Ant) which makes the plugin "seem" to work there but they don't really support those things.
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 2,
"tags": "android, android studio, intellij idea, codenameone"
}
|
Persistent SQL Table lock from C#
I'm trying to create a persistent SQL (SQL Server 2005) lock on a table level. I'm not updating/querying the specified table, but I need to prevent a third party application from updating the locked table as a means to prevent transactions from being posted (the table I wish to lock is the key on their transaction that interferes with my processing).
From my experience the table is only locked for the time a specific transaction is taking place. Any ideas?
The 3rd party developer has logged this feature as an enhancement, but since they are in the middle of rolling out a major release I can expect to wait at least 6 months for this. I know that this isn't a great solution, since their software will fall over but it is of a critical enough nature that we're willing to live with the consequences.
|
Move the table to a different file group, then alter the file group to read-only. The table will be in effect read-only:
ALTER DATABASE dbName
ADD FILEGROUP ReadOnlyFG;
GO
ALTER DATABASE dbName
ADD FILE (
NAME = ...,
FILENAME = '...')
TO FILEGROUP ReadOnlyFG;
GO
ALTER TABLE tableName MOVE TO ReadOnlyFG;
GO
ALTER DATABASE dbName
MODIFY FILEGROUP ReadOnlyFG READONLY;
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "sql, sql server 2005, table lock"
}
|
An orientable compact even dimensional manifolds whose all even cohomologies do not vanish but it does not admit any symplectic structure
What is an example of an orientable compact $2n$ dimensional manifold $M$ whose all even dimensional De Rham cohomology groups $H_{\mathrm{DeR}}^{2i}(M)$ are nonzero, but $M$ does not admit any symplectic structure?
**Added:** As it is indicated in the comments, this post is not a duplicated post.
|
For your $n=2k$, $\mathbb{C} P^n\\#\mathbb{C} P^n$ does not even admit an almost complex structure, so it cannot be symplectic.
See also: 1) Goertsches-Konstantis' paper _"Almost complex structures on connected sums of complex projective spaces"_ which answers the following MO question
2) Does $\Bbb{CP}^{2n} \\# \Bbb{CP}^{2n}$ ever support an almost complex structure?
Including Miller's comment for the remaining (your $n=2k+1$) dimensions: $S^2\times(S^4\times\cdots\times S^4)$
|
stackexchange-mathoverflow_net_7z
|
{
"answer_score": 6,
"question_score": 2,
"tags": "dg.differential geometry, sg.symplectic geometry"
}
|
Can Cmake generate a single makefile that supports both debug and release
It seems like we need to create separate folder for each build type (debug/release), run cmake on each, and generate separate makefile for debug/release configuration. Is it possible to create one single makefile using cmake that supports both debug/release configuration at the same time and when we actually run "make" that will create separate folders for the intermediate and final products (like the dlls, exe).
|
As far as I know, this cannot be achieved using a single set of build scripts. However, what you can do is have two sub-directories of your working area:
build/
build/debug
build/release
Then do:
$ cd build
$
$ cd build/debug
$ cmake -DCMAKE_BUILD_TYPE=Debug ../..
$ make
$
$ cd ../release
$ cmake -DCMAKE_BUILD_TYPE=Release ../..
$ make
If necessary, you can add another build script in the `build` directory as such:
#!/bin/sh
cd debug && make && cd ..
cd release && make && cd ..
|
stackexchange-stackoverflow
|
{
"answer_score": 15,
"question_score": 15,
"tags": "c++, c, cmake"
}
|
Validate Date at MySQL
How do you validate a date in MySQL ? In SQL Server, we have "ISDATE()" to validate whether the expression is a valid date. What function do we use in MySQL ?
|
Simply use date(your_date_here) and that will check if a date is valid.
**EDIT:**
If you really wanna have a isDate returning true or false, you can use this:
CREATE FUNCTION IsDate (sIn varchar(1024)) RETURNS INT
BEGIN
declare tp int;
if (select length(date(sIn)) is null )then
set tp = 0;
else
set tp = 1;
end if;
RETURN tp;
END
cheers
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 2,
"tags": "mysql, ssis"
}
|
How can I make a discord currency system and/or music bot?
[post edited]
How can I make a discord currency system with python and/or how do I download the FFmpeg thing for the music bot as I don't know what to do after installing it.
|
First of all, you need to bring them to the same python file
import discord
from discord.ext import commands
client = commands.Bot(command_prefix="$")
@client.command ()
async def repeat (ctx, arg):
await ctx.send(arg)
@client.event
async def on_message (message):
message.content = message.content.lower()
if message.author == client.user:
return
if message.content.startswith("$hello"):
if str(message.author) == "NAME":
await message.channel.send ("Hello" + str(message.author) + "!")
else:
await message.channel.send("Hello!!")
client.run('TOKEN')
Then it depends on what you mean by "Work toghether". If you need the bot to answer to `$hello` and `$repeat` separately the code is already good.
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": -2,
"tags": "python, discord, discord.py"
}
|
Semantics of x,¨y in APL: ie, what does it mean to map a catenate in APL?
Consider the expression `(1 2 3),¨(4 5 6)`. I expected this to "map the operation `(1 2 3),` on each of `4`, `5`, and `6`, giving the answer as:
(1 2 3),¨(4 5 6)
= (1 2 3),¨((4) (5) (6)) [Using (x) = x]
= (((1 2 3), 4) ((1 2 3), 5) ((1 2 3), 6)) [Using definition of map]
= ((1 2 3 4) (1 2 3 5) (1 2 3 6))
However,this is _not_ the answer! The answer as evaluated in Dyalog APL is:
]display (1 2 3),¨(4 5 6)
→
→ → →
1 4 2 5 3 6
~ ~ ~
∊
How? What's the reasoning behind this answer? Where did I go wrong in my equational reasoning? Are there more "gotchas" that my incorrect mental model of `, (comma)` and `¨(map)` that I should be aware of?
|
`,` is a symmetric function, it simply concatenates its arguments.
`¨` is also symmetric, it pairs up elements from left and and right.
According to APL's scalar extension rules, a single element as argument gets distributed to pair up with all the elements from the other argument.
You speak of _the operation`(1 2 3),`_ but there is no such operation. If you try to give this "function" a name, it'll fail with a `SYNTAX ERROR`.
However, you _can_ create a function which takes its argument and appends it to `1 2 3` as Richard Park demonstrated; `1 2 3∘,` and you can then map that function over the elements of an array with `1 2 3∘,¨`.
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 1,
"tags": "arrays, map function, apl, dyalog"
}
|
Why does is_front_page and is_home always return true for posts in wordpress?
My front page is just a list of the posts separated by category. I'm working on a plugin that get the id of the post but needs to test if the user is currently on the front page:
if(is_front_page()){
do this thing
}
else {
do this other thing
}
problem is, on the post pages it returns true for is_front_page. I tried is_home but get the same result.
I have the home in admin set to "latest posts" (not a static page) and displaying the posts on the main page via loop-home. I'm using is_home in the header and getting the correct response.
|
Turns out since the plugin output in the footer I just had to reset the query: wp_reset_query();
|
stackexchange-wordpress
|
{
"answer_score": 0,
"question_score": 0,
"tags": "plugin development, homepage"
}
|
Segre embedding of $\mathbb{P}^1\times\mathbb{P}^1-\Delta$
I want to try that if $S$ is the Segre's embedding $S\Bigl(\mathbb{P}^1\times\mathbb{P}^1-\Delta\Bigr)$ is an affine variety. Any hints?
|
The diagonal $\Delta\subset X = \mathbb P^1 \times \mathbb P^1$ is a divisor of type $(1,1)$ hence arises as a hyperplane section in the Segre embedding $X \subset \mathbb P^3$. The complement of a hyperplane in $\mathbb P^3$ is isomorphic to $\mathbb A^3$, so $X \cap \mathbb A^3$ exhibits your complement as a quadric surface in affine space, hence it is affine.
More generally, the complement of an ample divisor on a projective variety is always affine by a similar argument.
|
stackexchange-math
|
{
"answer_score": 1,
"question_score": 0,
"tags": "algebraic geometry"
}
|
If $p$ is negative, is it true that $\ln(p^2) = 2\ln(p)$?
Suppose, $p$ is a real negative number. However, $p^2$ is positive. Now,
$$\ln(p^2) = 2 \ln(p)\tag{1}$$
**Question:**
1. Is $(1)$ valid to write?
|
No!
For exactly the reason you mention.
However, for $p\in\mathbb{R}$, $p\neq 0$, it is correct to write $\ln(p^2) = 2\ln(|p|)$.
|
stackexchange-math
|
{
"answer_score": 5,
"question_score": 1,
"tags": "logarithms"
}
|
Is it possible to download a Google Drive folder as a .zip?
I've seen that this is possible in Google+.
How can I do this?
|
Downloading as zip archive is the default behavior for multiple file download in Google Drive.
1. Select multiple files and/or folders
2. Right click selection and choose `Download...` !enter image description here
3. In windows that appears, review your selection and click Download... !enter image description here
4. Wait for the progress to finish !enter image description here
5. Your download will start automatically (if it does not - click the link)
!enter image description here
|
stackexchange-webapps
|
{
"answer_score": 8,
"question_score": 7,
"tags": "google drive, file conversion"
}
|
How to limit Bootstrap Datepicker date view to just Year
I am running Bootstrap 3.3.6 (latest) and Datepicker plugin 1.6.0 (latest).
I want the date box to only accept and display year between a certain range (in my current case 2014, 2015, and 2016).
I have this customization in place:
$('#my-container .my-class').datepicker({
//format: " yyyy", // does not work
minViewMode: "years",
maxViewMode: "years",
startDate: '01/01/2014',
endDate: new Date(),
startView: "year" //does not work
});
Is it possible to limit the input and display to just a 4-digit year?
|
_Try this solution :_
$('.datepicker').datepicker({
autoclose: true,
format: " yyyy",
viewMode: "years",
minViewMode: "years",
startDate: '2014',
endDate: new Date(),
});
See **JsFiddle**. _I hope it works for you, thanks._
|
stackexchange-stackoverflow
|
{
"answer_score": 3,
"question_score": 2,
"tags": "twitter bootstrap 3, bootstrap datepicker"
}
|
Get real text from window handle
I have a window handle to a child window of a PDF file. This child window has the class "AVL_AVView", and its text is "AVPageView".
Can I somehow get the real text of this window?
Thank you!
|
You obtain the window text for a window by calling `GetWindowText`. The window class name that you quote is not a standard one. It is probably a custom control of the PDF viewer program.
If you want the text of the PDF document being displayed then you are unlikely to have any success with Win32 APIs for this custom control. Perhaps the automation APIs will yield results. But a better approach might be to use a PDF library to read the document.
|
stackexchange-stackoverflow
|
{
"answer_score": 3,
"question_score": 1,
"tags": "c#, c++, .net, window"
}
|
A specific but basic tutorial for Corona SDK?
I have been looking at Corona SDK and it would be helpful if I could see a tutorial/example to accomplish the following:
1. Load an image as a background/map
2. Draw a circle on the screen
3. user can tap elsewhere and the circle moves to that location (this can be repeated)
Does anyone know of any examples out there?
|
Very easy to do - here's a plug and play sample;
local background = display.newRect( 0, 0, 320, 480 )
background:setFillColor(0, 200, 255)
local circle = display.newCircle( -100, 0, 20 )
local function moveCircle(event)
circle.x = event.x
circle.y = event.y
end
background:addEventListener("tap", moveCircle)
Though obviously you'd you an image, I'm using a rectangle.
|
stackexchange-gamedev
|
{
"answer_score": 0,
"question_score": 0,
"tags": "corona sdk"
}
|
What kind of algorithms are used to break down data?
I have a table with a large amount of data and need to do lookups on each and break down each of the data. Here's a simplified numeric example. I have this table:
1 [1]
2 [1, 1]
4 [2, 2]
now I want to break down 4. I look up and see 2+2=4. so then I look up 2 and see if breaks down into 1+1 so I know 2+1+1=4 and 1+1+1+1=4. For this problem, I should break it down(using the computed table) into 4 results(the 3 mentioned and 4 *1 =4).
I am not sure but is this a graph problem? or some other type? I think I can solve this by just using a recursions that break this down, but I want to learn if there's an general accepted way and this process will deal with large amounts of data so I'll need to design it in a way that the breakdown can be distributed over multiple CPUs.
Any idea what type of problem this is or the logic to solve it?
|
As close as I can understand your specific example, it could be recursion, it could be a graph problem, it could be several other things, or a combination. Not every programming problem can be sorted into a single neat category, and there are generally at least a half-dozen different valid approaches to any problem.
In terms of dealing with large amounts of data specifically, there are many, many different strategies that may be employed, depending on how it needs to be accessed (sequentially? randomly by offset? randomly by key or some sort of search?), how frequently it will be updated, how much data there is in relationship to the sizes of the various levels of the storage hierarchy, etc.
And then there's multiple CPUs -- parallel processing -- where data synchronization becomes an important issue, in addition to the other problems.
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 1,
"tags": "algorithm, math, graph algorithm"
}
|
Bright colors do not display in watch --color
Given the following python script to print colored text:
for i in range(30, 100):
print(f'\033{i}m{i}\033[0m', end=' ')
print()
Running on bash displays bright colors (FG codes 91-97) properly: [. You should be able to check your version with `watch --version`.
default:
if (attrib >= 30 && attrib <= 37) { /* set foreground color */
fg_col = attrib - 30 + 1;
} else if (attrib >= 40 && attrib <= 47) { /* set background color */
bg_col = attrib - 40 + 1;
} else {
return 0; /* Not understood */
}
The _master_ branch of `watch`contemplates the bright colors, so eventually it will be fixed and picked up by WSL2. In the meantime your only option is to compile it yourself with that code changed.
|
stackexchange-unix
|
{
"answer_score": 1,
"question_score": 1,
"tags": "colors, windows subsystem for linux, watch"
}
|
Moving MS SQL Server image data to MySQL longblob
I'm wondering what is the best route to move image data in a SQL Server database to a MySQL server database? Is it possible via SQL?
So far I have created a linked server on the MS SQL Server that links to the MySQL table. I'm able to upload blobs on the MySQL server when I am on it locally (using the LOAD_FILE function...but trying to stay away from that since the images need to be on the MySQL host for that function to work). Is there another way to insert blobs into MySQL without using the LOAD_FILE?
I'm thinking there should be a way to break down the MS SQL Server image field to binary and then insert that into the MySQL database via the linked server?
|
Yes, I found that SQL Server seems to implicitly convert the image to varbinary(max)....I was able to get this to work using the OPENQUERY method.
{INSERT INTO OPENQUERY(MYSQLLINKEDSRV, 'select name, file from mysqlTable') SELECT TOP 10 name, file from mssqlTable; }
This seemed to work for me as well... {INSERT INTO MYSQL...mysqlTable(name, file) VALUES ('name','xxxxx')}
I did notice that when I was inserting into MySQL through the linkedserver that the first column of the inserted record was null....to fix this I moved my integer columns to the end of my insert statement and it seems to work fine, I'm still looking into how to handle this if there are no integer columns...don't really want to have a dummy column in my mysql table if I don't have to...
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "mysql, sql, sql server, blob, varbinary"
}
|
Enums with positive and negative values
I need to create a large enum which will be used as bit flags. Using the standard doubling i.e. 1, 2, 4 to ensure uniqueness of any combination is fine except that I run out of numbers if I use the int (2 billion upperlimit). I also cannot use a big int as Sql server has a limitation on bitwise operations and will truncate to 10 characters.
What I wanted to know is how to throw negative numbers in there as well and still ensure that all combinations remain unique. (for example some the enum values used in the ADO.NET library seem to have negative integers).
|
You can create an enum based on a `ulong` :
[Flags]
enum Foo : ulong
{
A = 1 ,
B = 2 ,
C = 4 ,
. . .
}
Store that in your database as two integers, something like this:
Save( Foo value )
{
ulong bitfield = (ulong) value ;
int hiNibble = (int)( (bitfield>>32) & 0x00000000FFFFFFFF ) ;
int loNibble = (int)( (bitfield>>0) & 0x00000000FFFFFFFF ) ;
// store the hi and lo nibbles as two integer columns in your database
}
In your database, create the table as something like
create table dbo.some_table
(
hiNibble int ,
loNibble int ,
bitField as convert(bigint, convert(varbinary,hiNibble) + convert(varbinary,loNibble) )
)
Now you have two 32-bit integers you can bit twiddle in SQL and you've got a 64-bit integer you can pass back to your C# code and rehydrate as the `ulong`-based enum it represents.
|
stackexchange-stackoverflow
|
{
"answer_score": 4,
"question_score": 0,
"tags": "c#, sql server, tsql, enums"
}
|
Can I Exit my SSH Client After Starting an Update?
I just ran `sudo aptitude update && sudo aptitude dist-upgrade` through PuTTY (SSH Client) on my Laptop, which was directed at my fresh Ubuntu server. Unfortunately I just realized I need to be out of the house with my Laptop and I'm worried that by exiting my SSH client or having my Laptop disconnect form the internet that the server won't continue updating!
What will happen if I turn my Laptop off now that the server is updating?!
|
You can do it using
nohup sudo aptitude dist-upgrade &
or (better) using screen, for this one better you study a bit how to use it.
You will be happy then with screen
|
stackexchange-serverfault
|
{
"answer_score": 4,
"question_score": 3,
"tags": "ubuntu, ssh, update"
}
|
generating two orthogonal vectors that are orthogonal to a particular direction
What is the simplest and most efficient ways in numpy to generate two orthonormal vectors a and b such that the cross product of the two vectors equals another unit vector k, which is already known?
I know there are infinitely many such pairs, and it doesn't matter to me which pairs I get as long as the conditions axb=k and a.b=0 are satisfied.
|
This will do:
>>> k # an arbitrary unit vector k is not array. k is must be numpy class. np.array
np.array([ 0.59500984, 0.09655469, -0.79789754])
To obtain the 1st one:
>>> x = np.random.randn(3) # take a random vector
>>> x -= x.dot(k) * k # make it orthogonal to k
>>> x /= np.linalg.norm(x) # normalize it
To obtain the 2nd one:
>>> y = np.cross(k, x) # cross product with k
and to verify:
>>> np.linalg.norm(x), np.linalg.norm(y)
(1.0, 1.0)
>>> np.cross(x, y) # same as k
array([ 0.59500984, 0.09655469, -0.79789754])
>>> np.dot(x, y) # and they are orthogonal
-1.3877787807814457e-17
>>> np.dot(x, k)
-1.1102230246251565e-16
>>> np.dot(y, k)
0.0
|
stackexchange-stackoverflow
|
{
"answer_score": 20,
"question_score": 15,
"tags": "arrays, numpy, vector, orthogonal, cross product"
}
|
Set microsoft teams bot username on a per message basis
Is there a way to set the name of a Microsoft Teams bot on a per message basis?
Slack bots allow this and I would have expected teams to do the same, but I'm not seeing anything in the bot service api docs about it.
I've tried changing the `from.name` property of the ActivityObject but it gets ignored (why that property exists I'm not sure).
|
Per this answer:
> The ability to support overriding app settings, including bot name, icon, and messaging endpoint, on a per tenant basis is not currently supported. It is something we are considering, but we do not have a timeframe to share.
The only way to accomplish this would be to design your architecture such that you're literally creating a new Bot Channels Registration with each message. I do not recommend this approach.
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "botframework, microsoft teams, azure bot service"
}
|
Moving Windows 7 encrypted file
I am testing Windows 7 file encryption. A test file was encrypted ( I see green colored file name). that file was shared across the network and it still can opened from other station. That green color file name is also viewable from other computer as well. What am I doing wrong? I admit that I don't know the encryption concept yet.
If I moved that file to shared folder of other computers, message appeared asking "Confirm encryption loss". How can I copy that file with encryption?
I know Truecrypt software but I am testing with Windows Encryption.
|
The NTFS file encryption is using your password hash to encrypt the file. If you connect to the file from another computer you need to supply the user's password, which means the remote computer has the key to decrypt the file.
If you copy the file from the share to the local computer windows will save the key in the remote computer.
The whole idea in the filesystem encryption is that another user cannot use your encrypted files, or someone that get a hold on your hard-drive. But, if you're logged in, all the running applications that has been executed by you or have access to your token (for example, SYSTEM user) can access the file without ever knowing it is encrypted on the disk.
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": -1,
"tags": "windows, file, encryption, filesystems, sharing"
}
|
Show that f(x,y)=x+y (with |x|=|y|) isn't a one way function
I have to prove that the function $f\colon \mathbb N × \mathbb N \to \mathbb N$ defined by $f(x, y) = x + y$ and $|x| = |y|$ isn't a one-way function. How do I go around doing that?
|
A function $f$ is one-way if given $f(z)$ for random $z$, it is hard to find an input $w$ such that $f(w) = f(z)$. So in order to show that $f$ isn't one way, you need to show that given $f(z)$ for random $z$, it is not hard to find an input $w$ such that $f(w) = f(z)$. Good luck!
|
stackexchange-cs
|
{
"answer_score": 1,
"question_score": 0,
"tags": "complexity theory, proof techniques, mathematical analysis, one way functions"
}
|
How to make code unreadable?
Like, we have this:
<?php
$titles[3] = 'three';
$titles[2] = 'two';
$titles[1] = 'one';
print_r( $titles);
foreach ($titles as $t ) {
print "title=$t ";
}
?>
**How to turn it into something, like this?**
<?php eval(gzinflate(str_rot13(base64_decode('PGRpdiBzdHlsZT0nPGRpdiBzdPGRpdiBzdHlsZT0nHlsZT0nandsoon')))); ?>
Absolutely don't understand how its done. What is the magic?
Please describe.
Thanks.
|
The term you are looking for is "obfuscate". If you simply do a google search for "php obfuscators", you'll find software into which you can copy and paste your code and it will obfuscate it for you.
|
stackexchange-stackoverflow
|
{
"answer_score": 6,
"question_score": 2,
"tags": "php, decode, encode"
}
|
Pandas Two Columns With Text - Applying GroupBy
I'm trying to obtain the "DESIRED OUTCOME" shown in my image below. I have a somewhat messy way to do it that i came up with but I was hoping there is a more efficient way this could be done using Pandas? Please advise and thank you in advance!
['Food'].apply(';'.join)
#Name
#Gary Oranges;Pizza
#John Tacos
#Matt Chicken;Steak
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 0,
"tags": "python, python 3.x, pandas"
}
|
How to move my website to wordpress?
I am in need to move a website from okaycms to wordpress, but I can't seem to find efficient way to do that. Can someone please tell me how to do that. I guess there is always option to rebuild everything in wordpress, but that wouldn't be so great of a choice. Thanks in advance.
|
There is no 'easy' way to 'move' or 'convert' a static site to WordPress. That's because WP is database-oriented, with content in the database. The themes/plugins/WP-engine take care of creating/building pages from the database content.
So, if you have a static site (HTML or HTML/PHP), you are going to need to find a theme that makes the site look how you want it to, then manually create pages with your page content.
|
stackexchange-wordpress
|
{
"answer_score": 0,
"question_score": 0,
"tags": "migration"
}
|
PCB target voltage reading too low on Atmel ICE Programmer
I've just had my first batch of PCB prototypes delivered from the manufacturer, and when I went to program them, the target voltage is reading too low. The device is based around an Atmel SAM L21 MCU, and I've attached a schematic for reference. The power supply is 3 AA batteries in series, connected to a Microchip MCP1711 3.3 LDO voltage regulator. In Atmel Studio, when I try to read the target voltage, it reads either 0.2v or 0.3v. I assume that because there is a voltage being read, that power is reaching the board, but I'm not sure why it's reading so low.
Does anyone have any suggestions as to what might be the problem? I've tested the batteries and the reading between them is reading around 4.5v, as it should be. Could this be a problem with the Atmel ICE programmer?
,VLOOKUP(F2,$B$2:$C$8,2,FALSE))
`VLOOKUP` is used for both columns in combination with `IFERROR`. Checking the first column for the lookup value. If found it is returned. If not found, meaning there is an error, the second `VLOOKUP` checks the second column and returns the lookup value.
Drag it down to fill the other cells. Make the appropriate change so the ranges match yours.
**Formula**  for each_string in rawData]
newText = [word for word in text if word not in stopwords.words('english')]
print(newText)
current output: ['game', 'the movie']
desired output ['game', 'movie']
I'd prefer to use list comprehension for this.
|
It took me a while to do this because list comprehensions are not my thing. Anyways, this is how I did it:
import functools
stopwords = ["for", "the"]
rawData = ['for', 'the', 'game', 'the movie']
lst = functools.reduce(lambda x,y: x+y, [i.split() for i in rawData])
newText = [word for word in lst if word not in stopwords]
print(newText)
Basically, line 4 splits the list values to make a nested list AND turns the nested list one dimensional.
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "python, list, nlp, nltk, stop words"
}
|
Why does jquery.serialize change LF to CRLF?
I'm trying to post this form:
<form id="the-form" enctype="multipart/form-data" >
<textarea class="form-control" name="list" id="list"></textarea>
</form>
with this script:
$.post( "/route", $('#the-form').serialize());
and debug of the script shows that `JSON.stringify($('#list').val())`
returns `"line1\nline2\nline3"`
while `$('#the-form').serialize()` returns `wordlist=line1%0D%0Aline2%0D%0Aline3`.
So why does _jquery.serialize_ encodes `\n` to `%0D%0A`? Is there a way to make _serialize_ return string with `%0A` EOL?
|
This is by design, see here:
> When serializing text, encode all line breaks as CRLF pairs per the application/x-www-form-urlencoded specification.
which says:
> Line breaks are represented as "CR LF" pairs (i.e., `%0D%0A').
\--
> Is there a way to make serialize return string with %0A EOL?
None apart from removing `%0D`'s manually after serializing.
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 0,
"tags": "javascript, jquery, eol"
}
|
Electronic items to take from US to India
I am buying some electronic items in the US to give them as gifts to friends and family in India. I wanted to ask if tablets, cameras, laptops bought in the US work fine in India. I mean there is no issue of frequency or volt or anything like that?
I do understand that there is one problem that the charger's plug won't work. Do I need to buy a converter for that? But apart from that, is there any other issue?
I mainly wanted to ask about tablets. Eg. this one
|
India has a 220/240V 50Hz electrical supply, while the United States delivers 110/120V 60Hz electricity. However, most electronic devices like laptops and tablets have dual-voltage power supplies, which accept both. You'll want to make sure this is true for the devices you're buying by checking the label to ensure it also accepts 240V 50Hz power. This will be the case for most electronics, though some appliances won't be compatible if you're looking to bring those back as well.
The tablet you linked appears to be dual voltage, so that would be no problem.
As you have surmised, you will need adapters for the physical plugs so they fit in Indian sockets. Devices that charge via USB could also be charged with a USB charger purchased in India.
You should note the rules regarding import duty for items brought to India so that you are not surprised by any taxes you are required to pay on arrival.
|
stackexchange-travel
|
{
"answer_score": 27,
"question_score": 12,
"tags": "usa, india, international travel, electronic items"
}
|
Oracle 10g A cursor with parameter Error
I can't understand why do I get this error. I have the table but the code sample is not working properly. What's the problem here?
DECLARE
CURSOR c_cust(p_city VARCHAR2) IS
SELECT * FROM cust WHERE cust.city=p_city;
v_cust c_cust%ROWTYPE;
v_city c_cust%TYPE;
BEGIN
v_city := 'London';
OPEN c_cust (v_city);
LOOP
FETCH c_cust INTO v_cust;
EXIT WHEN (c_cust%NOTFOUND);
DBMS_OUTPUT.PUT_LINE (v_cust.cname || ' has ' || v_cust.rating);
END LOOP;
IF (c_cust%ISOPEN) THEN CLOSE c_cust;
END;
> ORA-06550: line 15, column 4: PLS-00103: Encountered the symbol ";" when expecting one of the following: if
>
> 1. DECLARE
> 2. CURSOR c_cust(p_city VARCHAR2) IS
> 3. SELECT * FROM cust WHERE cust.city=p_city;**
>
|
`c_cust%ISOPEN` should be before end loop;
If .... then
....
end if;
you miss the end if;
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "oracle"
}
|
How do I get ALL posts in a category with Wordpress?
This works pretty good except it is limited to 10 posts since my blog is set to show 10 posts maximum.
$featured_query = new WP_Query('cat=3');
while( $featured_query->have_posts() ){
$featured_query->the_post();
$postcount++;
...
How can I override that setting and get ALL posts in that category regardless of the maximum posts setting?
|
Use `showposts=-1`. This will override the defaults posts setting. Per this: <
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 4,
"tags": "wordpress"
}
|
LEI windows Service makes the lotus domino server to crash
I am facing a problem with the LEI windows Service.
Lotus notes Domino Server is the system component LEI - Service
Both are windos service. LEI is dependant on lotus domino server.
Past few days i am experiencing a weird problem, LEI service was not running, when i started it it makes the lotusnotes domino server to crash.
|
I experienced several LEI issues in the past which caused domino crashes. A few suggestions: \- does the server crash on a specific activity? What kind of activity? Can the databases this activity uses be accessed? \- Check the LEI Log (leilog.nsf) when this is corrupt, create a new one. \- Check your LEI Activities. All activities that were running or scheduled to run when the server crashed should be reset using the "Reset Activity" action (Menue actions - activity administration - Reset activity). \- Logging: Do you use heavy logging? There is an option "Buffer log". I had issues with this when there is very nmuch information to be logged (it causes and OutOfMemory, because the log is buffered and not permanently written to the log document)
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "lotus domino"
}
|
JRuby on Rails and calendar_date_select
Anyone have any success with a JRuby on Rails war deployment and calendar_date_select? The gem wouldn't include the helper functions and I would receive the following error since the function wasn't declared in the app:
`undefined method 'calendar_date_select_includes' for #<ActionView::Base:0xbe823>`
After installing calendar_date_select as a plugin, I was able to get it to work in a war file deployment for the development environment. Nevertheless, I'm now receiving the same error with the plugin when the rails environment in the war file is changed to 'production'.
any ideas on which direction to head?
JRuby: 1.3.0 Rails: 2.3.2 Calendar Date Select : 1.15 Tomcat: 6.0
|
I had the same problem and solved it using this patch: <
It's because of `calendar_date_select` building a path for `/public` using `Rails.root` (which, when packaging the app with `Warble` is under `WEB-INF`).
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 1,
"tags": "ruby on rails, plugins, jruby, production"
}
|
Solve failing and not clear why
I define the function:
w[q_, n_, a_] := q/(4 Pi n r^2) (1 - Exp[-2 r/a] (2 (r/a)^2 + 2 (r/a) + 1))
I then want to solve:
q = 1.6*10^(-19);
n = 8.85*10^(-12);
a = 0.529*10^(-10);
Solve[w[q, n, a] == 1000, r]
This does not work and I do not understand why. I think there is a solution. Any ideas?
|
Use `Reals` option with `Solve` since you did not use exact numbers. You'll get an answer (also with `Solve::ratnz`) along with it
Solve[w[q, n, a] == 1000, r, Reals]
!Mathematica graphics
|
stackexchange-mathematica
|
{
"answer_score": 3,
"question_score": 1,
"tags": "equation solving"
}
|
Java resource files
I'm writing a small GUI app that contains some "editor" functionality, and something that I'd like to let users open a few sample text files to test things out quickly. The easiest way of doing this would be to package a separate zip with the appropriate sample files, and have them open them manually; I'd like to make things a little more user-friendly and allow them to pick the files from inside the application and then run them.
So... what do I use? I initially considered .properties but that doesn't seem terribly well suited for the job...
|
You can include a resource file right in the jar and then open it as a resource stream in your app. If you're using Spring, you can inject the resource right into a bean. If not, check out Class.getResourceAsStream()). You just have to be careful about the path you use to get to the resource file.
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 1,
"tags": "java, properties, jar"
}
|
Which A.I. has the highest I.Q. on the Red Dwarf, Kryten, or the Talkie Toaster?
Holly is no longer the sharpest knife in the drawer, having lost his I.Q. of 6,000. Which of the remaining artificial intelligence units on board the Red Dwarf has the highest I.Q, Kryten, or the Talkie Toaster?
|
Even after Kryten accelerated the toaster's CPU in the episode "White Hole" (season 4 episode 4), Kryten was still more intelligent.
Perhaps the overclocked-Toaster had a higher-IQ in the relatively limited field of "bread related breakfast foods", while it lasted.
|
stackexchange-scifi
|
{
"answer_score": 12,
"question_score": 6,
"tags": "tv, novel, red dwarf, artificial intelligence"
}
|
searching concurrent linked list
I have a concurrent linked list. I need to prioritize finds on this list, so if a thread begins iterating over the list and subsequent insert/delete requests show up I'd want to queue those but if there are find requests from other threads I'd let those happen. What's the best way to implement this situation?
EDIT: I don't want to make copies of the list. Too expensive. Mom pays for my hardware.
|
Sounds like you are looking for a readers-/writer-lock. This is a lock that can be used to let many threads read the data-structure, but when one thread has write-access, all others are locked out.
Boost offers an implementation.
|
stackexchange-stackoverflow
|
{
"answer_score": 5,
"question_score": 0,
"tags": "c++, multithreading, synchronization"
}
|
Comprehension list of nested dictionary to get values but got keys
Fairly new to list comprehension and have `the_list` that I want to extract the keys of nested dictionary but I got the values instead. What am I missing or what am I doing wrong?
the_list = [{'size': 0, 'values': [], 'start': 0}, {'size': 2, 'values': [{'user': {'name': 'anna', 'id': 10, 'displayName': 'Anna'}, 'category': 'Secretary'}, {'user': {'name': 'bob', 'id': 11, 'displayName': 'Bobby'}, 'category': 'Manager'}], 'start': 0}, {'size': 1, 'values': [{'user': {'name': 'claire', 'id': 13, 'displayName': 'Clarissa Claire'}, 'category': 'Secretary'}], 'start': 0}]
list_comprehension = []
list_comprehension = [x for x in the_list for x in the_list[1]['values'][0]]
print(list_comprehension)
>> ['user', 'category', 'user', 'category', 'user', 'category']
Want
list_comprehension = [[anna, Secretary], [bob, manager], [claire, Secretary]]
|
You could use this. I personnally try to avoid nested list comprehension as they are hard to read and debug.
[[x['category'], x['user']['displayName']] for nest_list in the_list for x in nest_list["values"] ]
Output:
[['Secretary', 'Anna'], ['Manager', 'Bobby'], ['Secretary', 'Clarissa Claire']]
**EDIT** : A version that doesn't have a nested comprehension list. When doing it I realised that there was one more level than I realised that makes this version a bit long. So in the end I'm not sure which one I would use in prod.
result = []
dict_list = [nest_list["values"] for nest_list in the_list]
for elt in dict_list:
for d in elt:
result.append([d['category'], d['user']['displayName']])
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "python, list comprehension"
}
|
How do I fix an unpushed merge commit(git)?
I (too) often merge branches with significant conflicts, I do this from my IDE which is fairly helpful in resolving these, once I'm done I end up with the merge result already committed locally with any manual adjustments I made in the process. Usually I like this behaviour but I always do some smoke testing before pushing. When this fails I need to fix something, often something silly like add/remove a comma, something I should have done while resolving the merge conflicts. currently I just add an extra commit on top. I would like to go back to the state I was during the merge with all code as it is currently, make the change and finish the merge again. I would not like to undo the entire merge and manually review all conflicts again.
|
After you finished the merge and see "oh, something more needs to be changed", just use `git add <your additional changed file> && git commit --amend -C HEAD`. This will add your changes to the commit HEAD points to, which should be your merge commit if you didn't do anything after the merge. If you already added an extra commit with this change, you can also use `git rebase --interactive` to combine those two commits into one.
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 0,
"tags": "git, version control, git merge"
}
|
Como concatenar condições em várias linhas?
Estou trabalhando com um sistema legado e ele possui alguns IF's com muitas condições, com a intenção de melhorar a legibilidade do código tentei quebrar essas condições em diversas linhas..
If rs(0) = "Visualizar NF"
And Session("idPerfil") <> "19"
And Session("idPerfil") <> "10"
Then
O trecho acima gera o seguinte erro:
Erro de compilação do Microsoft VBScript erro '800a03f9'
'Then' esperado
Gostaria de saber como no ASP 3.0 podemos concatenar diversas condições em estruturas de decisão ou laços de repetição?
|
O ASP Clássico espera o `Then` no final da mesma linha para interpretar o fim da condição, para concatenar as condições em diversas linhas precisamos utilizar o `_`.
Adicionando o underline `_` ao final de cada linha o código será interpretado corretamente.
Exemplo:
If rs(0) = "Visualizar NF" _
And Session("idPerfil") <> "19" _
And Session("idPerfil") <> "10"
Then
|
stackexchange-pt_stackoverflow
|
{
"answer_score": 3,
"question_score": 6,
"tags": "asp"
}
|
JSF Number Validation
Is there any inbuilt number validator tag in JSF that checks whether an input entered in `h:inputext` field is a number?
The first question was answered. Edited to explain the next problem:
<h:inputText id="maxrecs" value="#{simpleBean.numRecords}" required="false" maxlength="4" >
<f:convertNumber longOnly="true"/>
</h:inputText>
Backing Bean
private long numRecords = null;
If I use String or Integer object in the backing bean , value is not being set. Now when I use primitive int, 0 is being printed on the screen. I would like the screen to be empty.
|
You can use `f:convertNumber` (use the `integerOnly` attribute).
You can get more information here.
|
stackexchange-stackoverflow
|
{
"answer_score": 41,
"question_score": 20,
"tags": "jsf"
}
|
Question about a proof in Junod's paper about the Blum-Blum-Shub generator
I am reading Junod's paper about the Blum-Blum-Shub generator. There is one thing I just do not understand about his proof of Lemma 4. On page 17 he writes:
> We conclude that $x=-x_0$ and from Lemma 1 we know that $x \ne x_0$
>
> (So far I understand.)
>
> , so they must have different parities **(Why is this the case?)** , $n$ beeing odd, which is a contradiction.
Could you please explain that to me?
|
If $x_0$ is odd, then $-x_0 = n - x_0$ must be even (and versa-visa).
|
stackexchange-crypto
|
{
"answer_score": 1,
"question_score": 0,
"tags": "pseudo random generator"
}
|
Remove extra white space from between letters in R using gsub()
There are a slew of answers out there on how to remove extra whitespace from between words, which is super simple. However, I'm finding that removing extra whitespace **within** words is much harder. As a reproducible example, let's say I have a vector of data that looks like this:
`x <- c("L L C", "P O BOX 123456", "NEW YORK")`
What I'd like to do is something like this:
`y <- gsub("(\\w)(\\s)(\\w)(\\s)", "\\1\\3", x)`
But that leaves me with this:
`[1] "LLC" "POBOX 123456" "NEW YORK"`
Almost perfect, but I'd really like to have that second value say "PO BOX 123456". Is there a better way to do this than what I'm doing?
|
You may try this,
> x <- c("L L C", "P O BOX 123456", "NEW YORK")
> gsub("(?<=\\b\\w)\\s(?=\\w\\b)", "", x,perl=T)
[1] "LLC" "PO BOX 123456" "NEW YORK"
It just removes the space which exists between two single word characters.
|
stackexchange-stackoverflow
|
{
"answer_score": 8,
"question_score": 4,
"tags": "regex, r, gsub"
}
|
Тип цикла какой подразумевается?
Какой вид цикла имеется в виду, если человек зацикливается на чем-л.?
While или for?
Или это образное сравнение с менструацией?
|
Подразумевается **замкнутый** (повторяющийся) цикл (repeated cycle of thinking). It's about **becoming obsessed** with something. Человек переживает или пытается до конца осмыслить навязчивую тему, но всякий раз возвращается к началу своих переживаний, и всё повторяется.
|
stackexchange-russian
|
{
"answer_score": 2,
"question_score": -3,
"tags": "значения"
}
|
Is starting with my automatic transmission in Neutral a good idea?
I have bought an auto transmission sedan but have no idea how to drive it correctly. All I know is put to D gear, and just drive.
I was wondering, is this the right way to use an automatic gearbox? Should I start with it in neutral or park?
**Start**
1. Get into the car
2. Switch to **N** gear
3. Ignite
4. Switch to **D** gear
5. Hand brake off
6. Go
**Stop**
1. Hand brake on
2. Switch to **N** gear
3. Shut down engine
4. Switch to **P** gear
Is this right?
|
You shouldn't have to go into N to start the car, in normal driving you probably will never really need N. When stationary, and I mean stationary, use P, never select P when moving. After starting and when about to move off select D then release handbrake. Only select R when stationary and wanting to reverse. You can select D when moving forward or even when moving slowly in reverse.
**Starting from P**
Foot on brake
Turn ignition to start engine.
Select D
Release handbrake if applied.
Pull away (obviously following the rules of the road)
**Stopping from D**
Foot on brake to slow down and come to a complete stop.
Handbrake on
Select P
Turn ignition off
Remove foot from brake
.
.
**_Happy Driving._**
|
stackexchange-mechanics
|
{
"answer_score": 3,
"question_score": 1,
"tags": "starting, automatic transmission"
}
|
How can I specify a category for a Gradle task?
I am writing a Gradle task in Intellij IDEA. I have noticed that in the Gradle window, the tasks appear under folders like so:
!enter image description here
I am wondering, how can you give a task a 'category' so that it appears in a folder as shown in the screenshot?
All the tasks I create usually end up in `other`. I am also writing a custom plugin and want it to appear under a 'folder' name of my choosing. but I assume it'll be the same answer for when writing a task.
|
You just need to set the `group` property of your task. Eg (from <
task publish(type: Copy) {
from "sources"
into "output"
}
configure(publish) {
group = 'Publishing'
description = 'Publish source code to output directory'
}
|
stackexchange-stackoverflow
|
{
"answer_score": 54,
"question_score": 46,
"tags": "gradle, intellij idea, groovy, gradle kotlin dsl, gradle groovy dsl"
}
|
Decryption problem using RSA
I have following steps to perform for decryption
1. base64 decode the response
2. Decrypt the first 128 bytes with the RSA1024 public key. Key is in base64 encoded X509 format with PKCS1 padding.
My code looks like this:
$decodedString = $this->base64UrlDecode($string); //does proper url decoding
$publicKey = file_get_contents("public.key",true);
$pub_key = openssl_get_publickey($publicKey);
openssl_public_decrypt($decodedString,$decrypted,$pub_key,OPENSSL_PKCS1_PADDING);
var_dump($decrypted);
I am not able to get anything in $decrypted variable. If I try to base64 decode public key before using it, I am getting error of not a valid public key. What I am missing or doing wrong to achieve mentioned 2 steps?
|
It was actually a problem with how I was getting response. By doing urldecode before base64 decoding I am able to get proper results.
$decodedString = $this->base64UrlDecode(urldecode($string));
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 1,
"tags": "php, rsa, encryption"
}
|
Login information remains after server restart
I have a web application which uses Asp.net Membership for user authenticaton. And as I understand, when user logs in, information about that user is stored in Session, but when I restart the server the user is still logged in.
Shouldnt Session be deleted with server restart? I dont understand how user is still logged in...
|
The information of a user being logged in is stored in a cookie and it goes between the user's browser and the server with each request.
Restarting the server has nothing to do with the cookie, specifically, the cookie is still valid, it decrypts correctly so the user is considered as logged in.
If you really need to terminate all user sessions, one of ways is changing the application's machine key, the crypto key that is used to encrypt/decrypt auth cookies.
<
|
stackexchange-stackoverflow
|
{
"answer_score": 4,
"question_score": 2,
"tags": "asp.net, asp.net mvc, iis, asp.net membership"
}
|
Integtrating MVC3 and Silverlight Projects
I've been working on a project that was run as two separate VS projects. The first a MVC3 project and the second a Silverlight project with dummy MVC project attached. The projects have been working in isolation, but now need to be merged. In the MVC solution I tried adding the SL project expecting it to hook up and ask which website to use, but nothing.
Am I missing a step? Should I merge the physical directories to help the process as well? Any help would be great.
Thanks.
|
Once the silverlight project is added to the solution, go in the MVC Project properties, and select the silverlight applications panel. You should be able to add your silverlight application in your website from here.
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 1,
"tags": "silverlight, visual studio 2010, model view controller, asp.net mvc 3, silverlight 4.0"
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.