INSTRUCTION
stringlengths 25
999
| RESPONSE
stringlengths 0
999
| SOURCE
stringlengths 16
38
| METADATA
dict |
---|---|---|---|
Carboy dimensions
What are the dimensions of a 5.5 and 6 gallon standard glass carboy?
|
Mine are:
* 6.5 Gallon: 20.5" tall (neck included) X 12" in diameter
* 5 Gallon: 19.25" tall (neck included) X 10.5" in diameter
|
stackexchange-homebrew
|
{
"answer_score": 4,
"question_score": 3,
"tags": "carboy, equipment"
}
|
How to remove component and its slot in Vue.js
I'm creating component based Tab functionality. Please find the code here
deleteTab: function(selectedTab){
this.tabs = this.tabs.filter(function(tab){
return tab._uid != selectedTab._uid
});
}
In there I've added remove button, which needs to remove the tab and tab details block. Anyone know how to remove the tab details?
|
I will suggest you to follow this video laracasts for a better code.
To delete your tab and content, you will need to do:
deleteTab: function(tab){
tab.isActive=false;
index = this.tabs.indexOf(tab);
if (index > -1) {
this.tabs.splice(index, 1);
}
console.log(tab)
}
check fiddle
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "javascript, vue.js, vuejs2"
}
|
Using an Android resources efficiently
I'm trying to figure out how to use Android's resource system efficiently, both to provide the highest resolution resources and to keep the .apk size low.
My resource folders:
drawable-normal-mdpi
drawable-normal-hdpi
drawable-large-mdpi
Now the way I'm using the resources (a game) the normal-hdpi and large-mdpi are exactly the same. I don't want to include both in my final .apk because its going to inflate the size unnecessarily. Is there a way to get around this? I tried to use a symbolic link (linux) but the android tools follow the links and copy the resources.
|
I think you are looking for an AliasResource.
|
stackexchange-stackoverflow
|
{
"answer_score": 4,
"question_score": 4,
"tags": "android, resources"
}
|
Отличия обычного Telegram бота от асинхронного?
Недавно начал изучать тему создания Telegram ботов на Python. Начал писать на pytelegrambotapi, но на многих сайтах все рекомендуют за место этой библиотеки учить aiogram. Основным его плюсом считают асинхронность. Может ли кто-нибудь разъяснить неопытному программисту, в чем различия асинхронного бота от обычного, и где это пригодится? И стоит ли в таком случае учить aiogram?
|
> в чем различия асинхронного бота от обычного
Пользователи шлют через специальные клиенты telegram боту сообщение. Бот получает сообщение и приступает к выполнению логики, которая как-то зависит от сообщения. На этом этапе `pytelegrambotapi` и `aiogram` ничем не отличаются.
Далее. Эта логика может потребовать получить какую-нибудь информацию из БД, что можно сделать?
1. Послать запрос и смиренно ждать, когда придет ответ. Тем временем очередь входящих сообщений может копиться.
2. Послать запрос и обрабатывать другое сообщение, но вернуться к этому позже, когда результат будет готов.
В первом случае сообщение обрабатывается синхронно, во втором асинхронно. В этом проявляются ключевые различия.
Быть может полезно будет почитать один мой другой ответ про async/await: <
|
stackexchange-ru_stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "python, telegram, pytelegrambotapi, aiogram"
}
|
How to get the right JSONPath?
I have the following JSON structure:
[{"Name":"Ab1","Price":"153"},{"Name":"Cd2","Price":"179"},...]
I want wo write a XPath command which gets the `Price` for the Element which `Name` is `Ab1`
I tried the following: `"//Name[Ab1]/Price"` But this is not working for me.
|
JSONPath syntax is very different from XPath. It's just based on XPath's concept.
This should be the correct JSONPath in your case. Please give it a try:
$[?(@.Name == 'Ab1')].Price
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 0,
"tags": "json, xpath, jsonpath"
}
|
Компиляция массива в GAS
Что означают закомментированные строки?
GAS code
.text
.globl main
main:
pushq %rbp
movq %rsp, %rbp
; subq $48, %rsp
; movq %fs:40, %rax
; movq %rax, -8(%rbp)
; xorl %eax, %eax
movl $1, -48(%rbp)
movl $2, -44(%rbp)
movl $3, -40(%rbp)
movl $4, -36(%rbp)
movl $5, -32(%rbp)
movl $6, -28(%rbp)
movl $7, -24(%rbp)
movl $8, -20(%rbp)
movl $9, -16(%rbp)
; movq -8(%rbp), %rax
; xorq %fs:40, %rax
leave
ret
С code
void main() {
int array[9];
array[0] = 1;
array[1] = 2;
array[2] = 3;
array[3] = 4;
array[4] = 5;
array[5] = 6;
array[6] = 7;
array[7] = 8;
array[8] = 9;
}
|
Это защита от переполнения буфера
subq $48, %rsp ; Выделение стека
movq %fs:40, %rax ; Получение значения "канарейки"
movq %rax, -8(%rbp) ; Сохранение его
xorl %eax, %eax ; Обнуление регистра
...
movq -8(%rbp), %rax ; Загрузка значения "канарейки"
xorq %fs:40, %rax ; Проверка на соответствие оригинальному значению
|
stackexchange-ru_stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "c, ассемблер, gcc"
}
|
How to check if postgresql crashes and restarts?
I am investigating an error with an application that I think is related to the database restarting and crashing periodically, perhaps it's running out of memory. How do I check to see if a postgresql database is crashing and restarting? IS there a query that I can run?
FWIW, the database is an AWS managed RDS postgresql database.
|
The best way to look for those kinds of errors would be in the logs. However, if you just want to see when the database last started, you could use this query:
SELECT pg_postmaster_start_time();
|
stackexchange-stackoverflow
|
{
"answer_score": 5,
"question_score": 0,
"tags": "postgresql"
}
|
What is wrong with this proof of $i = 0$?
This is a proof I made a year ago and at that time, I didn't see any problems with it. Could anyone point out what is wrong here?
> Consider the following expresion: $(-1)^{(4n+3)/2}$, where $n \in \Bbb Z_+$. We have that: \begin{align} (-1)^{(4n+3)/2} &= [(-1)^{4n+3}]^{1/2} = (-1)^{1/2} = i \\\ (-1)^{(4n+3)/2} &= [(-1)^{1/2}]^{4n+3} = i^{4n+3} = -i \end{align} That means $i=-i$ $\implies$ $i=0$.
|
A 'square root' is not a function in complex numbers - there are two distinct values of $\sqrt{-1},$ and if you take the other one, which is $-i$, the result would be $-i=-i.$
|
stackexchange-math
|
{
"answer_score": 1,
"question_score": -4,
"tags": "fake proofs"
}
|
Regex - Is there a way to find across a substring string in any order?
So i'm currently having an issue in getting around Regex for the following situation:
Situation 1(It just states that there is only one country affected): (...)@MT(...)
Situation 2(It shows multiple countries affected): (...)@MT,GR,DE,FR(...) With no defined order whatsoever so it could be like the one above or (...)"@GR,MT,FR,DE"(...), etc
what i reached for the Situation 1 would be quite simple but the rest i'm a bit clueless...
This i what i've already tried going towards to what i want
It gets Situation 1 and "half" of Situation 2 (only the second occurrence)
^.*NOTES="#P\d\s\@(?<affected_MT>(MT|\,MT|(?>\,[A-Z]{2})*\,MT)).*$
My target would be to get to find the instance "MT" in the string taking into account that it could happen in any order
|
You may use
NOTES="#P\d+\s+@(?:[A-Z]{2},)*MT\b
See the regex demo and the Regulex graph*MT%5Cb).
It matches
* `NOTES=#P` \- a `NOTES=#P` substring
* `\d+` \- 1+ digits
* `\s+` \- 1+ whitespaces
* `@` \- a `@` char
* `(?:[A-Z]{2},)*` \- zero or more sequences of 2 uppercase ASCII letters followed with a comma
* `MT\b` \- a whole word `MT` (`\b` is a word boundary).
.*$
RewriteRule ^index\.php$ [R=302,L]
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": ".htaccess, redirect, xenforo, smf, smf forum"
}
|
Git How to undo recent merge commit then change to rebase
The commit history looks like this on remote and local:

.data(data)
.min(12)
.pad(1)
.height(h)
.width(w)
.barSize(35)
.fill(d=>color[d.primary]);
It seems like IE doesn't support that syntax. Can anyone suggest how it should be written instead?
|
Try doing something like this
var bp=viz.bP()
.data(data)
.min(12)
.pad(1)
.height(h)
.width(w)
.barSize(35)
.fill(function(d){
return color[d.primary]
});
Also, in the future, check out caniuse to figure out what you can use in what browsers
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": -2,
"tags": "javascript, internet explorer, d3.js"
}
|
What is the Java Swing layout equivalent of C# WPF’s layout
For those of you who haven’t worked with C# WPF, let me give you a brief overview of the WPF layout. UI Elements in WPF are positioned using three main properties:
You specify horizontal and vertical alignments which can be set (individually, of course) to left, right, center, or stretch (which fills up the parent element either horizontally and/or vertically). An absolute width and height and a margin, which is the distance of the element from the left, top, right, and bottom edges of the screen, can be specified too.
_**What is the Java Swing layout equivalent of this?**_
Edit: How come all the "latecomers" to this question view it so negatively? I'm just trying to find an equivalent layout for this, not talk about how I should be arranging/positioning elements.
Edit 2: You know what, just pretend this question never existed -- my question has been solved and therefore I will be ignoring this thread.
|
You should start by having a look at Laying Out Components Within a Container, which should provide you with enough information to solve the question yourself. I'd personally look towards GridBagLayout, but that's me.
You're unlikely to find an "exact" match, but you could also consider having a look at MigLayout
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": -2,
"tags": "java, c#, wpf, swing, user interface"
}
|
deducing type of multi-parameter type class
I'm trying to get the following code to compile
import IO
data MyInt = MyInt Int
data MyString = MyString String deriving Show
class Show b => MyClass a b where
fn :: a -> b
instance MyClass MyInt MyString where
fn (MyInt i) = MyString (show i)
myprint :: (MyClass a b) => a -> IO ()
myprint a = putStrLn $ show (fn a)
main = myprint (MyInt 3)
with `ghc Main.hs -XMultiParamTypeClasses`. However, the compiler cannot deduce the type of the `b` type variable (which in this case is `MyString`). How can I explicitly tell this information to the compiler?
|
You've run afoul of the "open world" assumption. In this case, there's only one instance in scope that can satisfy the type constraints; but that's not a very declarative way to specify the meaning of `myprint 3`, is it? Given that instances can float in really from any module whatsoever, we can see how the open world assumption protects you from unanticipated changes of type/behaviour as modules are added or updated.
You could try functional dependencies or type families in this case.
class Show b => MyClass a b | a -> b where
...
|
stackexchange-stackoverflow
|
{
"answer_score": 5,
"question_score": 2,
"tags": "haskell, types, typeclass"
}
|
What does the last sentence in chapter 2 of Crime and Punishment really mean?
The sentence I'm referring to is this one.
> ‘And what if I am wrong,’ he cried suddenly after a moment’s thought. ‘What if man is not really a scoundrel, man in general, I mean, the whole race of mankind—then all the rest is prejudice, simply artificial terrors and there are no barriers and it’s all as it should be.’
It's the very last sentence of the second chapter.
I have read a German version but that doesn't really matter. The translation is very similar.
I don't fully understand what this sentence really means. Can someone explain it?
This seems to be an important sentence since we don't get to hear much from Raskolnikov in this chapter besides this sentence. Or maybe the question is: What does Raskolnikov mean with this sentence?
|
When Rodion says he could be wrong, he means his words for the previous sentence:
> Hurrah for Sonia! What a mine they've dug there! And they're making the most of it! Yes, they are making the most of it! They've wept over it and grown used to it. Man grows used to everything, the scoundrel!
So he says that man must be a scoundrel to accept the fact that their own daughter works as a prostitute in order to support the family.
And if _that_ doesn't mean that man is the scoundrel, if _that_ is acceptable in the world of man, then there is no morality at all, and all the notions of good and bad are just superstitions produced by fear. And there are no barriers.
That's how I understand this passage.
|
stackexchange-literature
|
{
"answer_score": 10,
"question_score": 12,
"tags": "meaning, russian language, fyodor dostoyevsky, crime and punishment"
}
|
Sort list of strings using icu-dotnet library for Myanmar collation
I want to sort list of strings using icu-dotnet library for Myanmar collation.
It throw an exception while creating collator for myanmar.
var cultureInfo = new CultureInfo("my-MM");
using (var collator = Collator.Create(cultureInfo.Name))
{
int compareResult = collator.Compare("သန်တ", "သန္တ");
}
|
This throws an _ArgumentException_ because there are no predefined collation rules for _my-MM_ in ICU. However, there are rules for _my_ , so the following would work:
var cultureInfo = new CultureInfo("my");
Or you could allow the fallback to _my_ by passing _FallBackAllowed_ :
using (var collator = Collator.Create(cultureInfo.Name, Collator.Fallback.FallbackAllowed))
{
}
You can see the predefined collators by looking at the icu4c source tree.
The full code to sort a list of strings:
var list = new List<string> {"foo", "baz", "bar", "zoo"};
using (var collator = Collator.Create("en-US"))
{
list.Sort((s1, s2) => collator.Compare(s1, s2));
}
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 1,
"tags": "c#, .net core, icu"
}
|
Does slick care if I have a foreign key setup in my database?
When making joins using slick, does slick care if I have a foreign key constraint setup at the database schema level?
|
Slick will work regardless of if your Slick schema has a foreign key defined or not.
This is from the Constraints section of the docs:
> Independent of the actual constraint defined in the database, such a foreign key can be used to navigate to the referenced data with a join. For this purpose, it behaves the same as a manually defined utility method for finding the joined data.
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "scala, slick"
}
|
From Gogo Shell, get version of com.liferay.portal.kernel
All I have is a Gogo Shell connection to a Liferay server.
From that shell, is there any way to know the version of the com.liferay.portal.kernel package used by that server?
For instance, if I want to know the version of the com.liferay.util.taglib package I would type `lb | grep Taglib | grep Util` and see that the version is `2.9.0`, but the same method does not seem to work for the kernel package.
|
portal-kernel.jar is still in the global classpath (lib/ext folder). Not sure you can handle it through the OSGi container.
You can check the installed version in its manifest file inside that jar.
Anyways, I guess you're asking in order to set the dependency in your developments. If that's the case, I would recomend to set the older version you can use in terms of compatibility (see a post by Nebinger talking about that: <
Your best bet is not always using the latest version for a dependency.
|
stackexchange-stackoverflow
|
{
"answer_score": 4,
"question_score": 3,
"tags": "liferay, osgi, apache felix, liferay 7, gogo shell"
}
|
How to select from two tables in a specific order to associate idT1-idT2
I always had this question:
How to select this in SQL (MySQL):
T1
A
3
4
5
6
7
T2
B
45
63
75
82
95
Result
3-45
4-63
5-75
6-82
7-95
As you can see, the idea is to associate both tables in the same order. I tryed this:
SELECT T1.A, T2.B FROM
(SELECT * FROM T1 ORDER BY A DESC) T1,
(SELECT * FROM T2 ORDER BY B DESC) T2
GROUP BY T1.A DESC
I get:
3-45
4-45
5-45
6-45
7-45
No success.
|
DROP TABLE IF EXISTS T1;
CREATE TABLE t1
(A INT NOT NULL PRIMARY KEY);
INSERT INTO t1 VALUES
(3),
(4),
(5),
(6),
(7);
DROP TABLE IF EXISTS T2;
CREATE TABLE t2
(B INT NOT NULL PRIMARY KEY);
INSERT INTO t2 VALUES
(45),(63),(75),(82),(95);
SELECT x.a
, y.b
FROM
( SELECT a, @i:=@i+1 i FROM t1, (SELECT @i:=0) vars ORDER BY a) x
JOIN
( SELECT b, @j:=@j+1 j FROM t2, (SELECT @j:=0) vars ORDER BY b) y
ON y.j = x.i;
+---+----+
| a | b |
+---+----+
| 3 | 45 |
| 4 | 63 |
| 5 | 75 |
| 6 | 82 |
| 7 | 95 |
+---+----+
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 0,
"tags": "mysql, select"
}
|
Using the Arcade Split function to create a list element in ArcGIS Dashboard
I am making a dashboard in ArcGIS Online. (see figure)
. I want to remove everything contained in brackets. For this purpose, I used Arcade's Split() function as follows:
`Split(Text($datapoint["Nom_biomasse"])," (",1)[0]`
However, the result is still the exact same as `$datapoint["Nom_biomasse"]` (the field containing the biomass names) on its own.
Is there something I am doing wrong or is this just something that cannot be done with dashboard lists?
It seems the Split() function inside the expression works fine. However, I am unable to reference it in the list itself.
|
I figured it out eventually. May this serve as an illustration to the ArcGIS online help.
When enabling advanced formatting, there is a sample code available. My mistake was to ignore this sample code and write my expression from scratch. Following the sample structure, here is my current Arcade expression:
return {
textColor: '',
backgroundColor: '',
separatorColor:'',
selectionColor: '',
selectionTextColor: '',
attributes: {
attribute2: Split($datapoint["Nom_biomasse"], " (")[0]
}
}
The `attribute2` can then be referenced in the list with the following expression:
{expression/attribute2}
(see figure) 
>
> print (iterations)
>
> (as,ad,af,ag,ah,.....sa,sadf,fgh,)
>
> Every possible length and possible arrangement of letter from 1-8 letter long.
|
Easy with itertools.combinations.
from itertools import combinations
from math import factorial as fac # extra
z = "asdfghjk"
n = len(z) # extra
for i in range(1, 9):
print("{} of {}, {} combinations".
format(i, n, fac(n) // (fac(i)*fac(n-i)))) # extra
for combo in combinations(z, i):
print(''.join(combo), end = ', ')
print('\n') # extra
The lines marked '# extra' are non-essential and only added for a nice display.
1 of 8, 8 combinations
a, s, d, f, g, h, j, k,
2 of 8, 28 combinations
as, ad, af, ag, ah, aj, ak, sd, sf, sg, sh, sj, sk, df, ...
(etc)
7 of 8, 8 combinations
asdfghj, asdfghk, asdfgjk, asdfhjk, asdghjk, asfghjk, adfghjk, sdfghjk,
8 of 8, 1 combinations
asdfghjk,
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": -3,
"tags": "python, python 3.x"
}
|
String.Split() removes leading zeros
I am trying to split my current applications version number, but is removes the leading zeros.
How do i change my split to not remove the leading zeros.
Getting the currentVersionNo:
startUpAssembly.GetName().Version.ToString()
So for testing:
string versionNo = "7.01.7000.0";
string[] versionInfo = versionNo.Split('.');
This produces:
7
1 //Here i need it to be 01
7000
0
And i need it to NOT remove the leading zero. How do i achieve this?
Maybe there is a better solution using regex?
|
A `System.Version` isn't an arbitrary string - it's four integers. Leading zeroes are irrelevant, so not included when converting back to a string. That's where you're losing information - not in `String.Split`. You can see this very easily:
using System;
class Test
{
static void Main()
{
Version version = new Version("7.01.7000.0");
Console.WriteLine(version); // 7.1.7000.0
}
}
Basically, your plan is fundamentally flawed, and you should change your design. You shouldn't be _trying_ to represent a version of "7.01.7000.0" to start with.
Additionally, you should take a step back and think about your diagnostic procedure: what made you think that `String.Split` was to blame here? Why wasn't your first step looking at the result of `startUpAssembly.GetName().Version.ToString()`?
|
stackexchange-stackoverflow
|
{
"answer_score": 20,
"question_score": 3,
"tags": "c#, .net, string, split"
}
|
Make a widget expand to available space flutter
I'm trying tu put `FlutterMap` in the right widget to expand it vertically depending on the device it' been drawn on. So far it is in a Container with fixed heigh and width. The same I'd need to do with the Drawer as when it opens it flows outside the screen on small iPhone 6 screen. Can you point me to a good explanation of the expanding widgets? This is the code:
body: SafeArea(
minimum: EdgeInsets.symmetric(horizontal: 20),
child: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: <Widget>[
Container(
height: 400,
width: 350,
child: FlutterMap()),
Row()]
|
You can consider using the **Expanded** widget Try this
SafeArea(
minimum: EdgeInsets.symmetric(horizontal: 20),
child: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: <Widget>[
Expanded(
child: Container(
child: FlutterMap()),
),
Row()]
Hope it works for you
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "flutter"
}
|
ODR error: fcn does not output [n]-shaped array
I'm trying to have a curve fit usign _scipy.odrpack_ but i have encountered a problem with the command _odrpack.ODR_.
This is the code I wrote:
def f(x,i):
return i[0]*numpy.exp(-i[1]*x)
a=pandas.read_csv("~/Untitled.csv")
exp=odrpack.Model(f)
data=odrpack.RealData(a['t'],a['c1'])
myodr=odrpack.ODR(data, exp, beta0=[1.,2.])
myoutput=myodr.run()
myoutput.pprint()
But i get the following error (10 is due to the array's length):
OdrError: fcn does not output [10]-shaped array
Does anyone know why I get this error?
Thanks!
|
You have accidentally swapped the parameters of your fit function:
def f(x,i):
return i[0]*numpy.exp(-i[1]*x)
when it should be
def f(i,x): # note the order of arguments
return i[0]*numpy.exp(-i[1]*x)
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 2,
"tags": "python, arrays, numpy, scipy"
}
|
Why does Excel only invoke the Text Import Wizard for .txt files?
Excel ignores comma delimiters in .csv files, but invokes the Text Import Wizard for .txt files that "appear delimited". Surely it should behave the same way for .csv files?
|
You can always compel the Wizard to appear.
**First** open Excel, then, using the Ribbon, goto the _Data_ tab and then touch _From Text_ in the _Get External Data_ group.
If you do not need the Wizard, then simply double-click the file's icon to open it.
|
stackexchange-superuser
|
{
"answer_score": 0,
"question_score": 1,
"tags": "microsoft excel, csv, microsoft excel 2013, textfiles"
}
|
Hyperelliptic curves in characteristic $2$
Let a field $K$ of characteristic $2$, and $F/K$ an hyperelliptic curve. Then, $F$ is defined by an equation of the form : $$ Y^2+Y=w(x), \quad w(x) \in K(X)$$
My question is : My question is : Why we can take $w(x)$ such that all irreducible polynomials in the denominator of $w(x)$ occur to an odd power and $w$ is either of odd positive or of non-positive degree ?
(actually, what I don't figure out is mainly how we can take $w$ such as it is is either of odd positive or of non-positive degree)
Thank you !
|
Presumably the field of constants $K$ is perfect (for example a finite field of characteristic two). In that case we can adjust $Y$ to meet the requirements you listed.
If $$w(X)=a_{2k}X^{2k}+\cdots + a_1X+a_0$$ is a polynomial of an even degree, then by perfectness there exists $b\in K$ such that $b^2=a_{2k}$. Substitution $\tilde{Y}=Y+bX^k$ into $$ Y^2+Y=w(X) $$ gives $$ \tilde{Y}^2+\tilde{Y}=w(X)+b^2X^{2k}+bX^k, $$ and you see that the terms of degree $2k$ cancel on the right hand side. Rinse - repeat until you are left with an odd degree polynomial.
Observe that using $\tilde{Y}$ instead of $Y$ does not change the function field of the curve (or amounts to a birational morphism).
|
stackexchange-math
|
{
"answer_score": 1,
"question_score": 1,
"tags": "algebraic geometry, curves, algebraic curves, cryptography"
}
|
Как на jquery найти несколько элементов идущих подряд в DOM и обернуть их в контейнер?
Есть следующий код:
<p>
<img src.../>
<img src.../>
</p>
<p>
<img src.../>
<img src.../>
<img src.../>
</p>
<p>
<img src.../>
</p>
Как с помощью jquery обернуть в контейнер те теги img, которые идут **подряд** чтобы стало так?
<p>
<span class='set'>
<img src.../>
<img src.../>
</span>
</p>
<p>
<span class='set'>
<img src.../>
<img src.../>
<img src.../>
</span>
</p>
<p>
<img src.../>
</p>
Есть метод wrapAll, но я не понимаю, что ему передать
$("???").wrapAll("<span class='set'>");
Если делать wrapAll по _img+img_ он обернет второй, третий и последующие, но не первый, а _p>img_ перенесет все шесть img в первый p.
|
$(function(){
$('pre').text("Исходный код: " + $('div').html());
// Перебор всех тегов "p" и "обвертывание" img'ов внутри каждого "p" отдельно.
$("p").each(function(){
if ($(this).children("img").length > 1) $(this).children("img").wrapAll("<span class='set'>");
});
$('pre').text($('pre').text() + "Результат: " + $('div').html());
})
<script src="
<pre>
</pre>
<div hidden>
<p>
<img src />
<img src />
</p>
<p>
<img src />
<img src />
<img src />
</p>
<p>
<img src />
</p>
</div>
|
stackexchange-ru_stackoverflow
|
{
"answer_score": 3,
"question_score": 1,
"tags": "jquery"
}
|
FrameLayout or Nested Fragments?
## My problem
I am in a dilemma. I have a fragment which has 3 different modes. Well, it is a history fragment. The modes are:
* Overview (displays `GridView`);
* Cell (displays `GridView's` cell);
* Empty (displays `ImageView` and `TextView`);
## My question
So I can't understand how to organise this. Should I **use three fragments (use nested fragments) for each mode** as a child into parent fragment? Or just **use one fragment with`FrameLayout`** and switch between different layouts? What is the best solution? Share your ideas!
_I would greatly appreciate for your help. Alex. P.S. Sorry for my English:)_
|
I would go for multiple fragments approach. It does not only help you to build reusable UI elements but also to easily supports multiple screen sizes (<
However, I think you only need two fragments: one fragment for the "Overview" mode and another fragment for the "Cell" mode.
You don't need a fragment for the empty mode. You should construct a view with `ImageView` and `TextView` and set it to the `GridView` of the "Overview" fragment as an `emptyView` (using `GridView.setEmptyView(View)`).
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 0,
"tags": "android, gridview, android fragments, code organization, android framelayout"
}
|
Android Coverflow Starting Position
I am using < coverflow widget in my application. The problem that I have is that I am unable to control the starting position of the widget . I am astonished that no body has asked this , or ashamed that maybe they figured this one out themselves.
When I load a list of say 15 elements , the middle image on the screen is the 3rd. If I swipe to left I will find 2 more , and the rest of them will be when seen when I swipe to the right.
I want the middle image to be the 7th element, so that right and left swipes reveal same number of items.
Aid me please ?
|
You can set your coverFlow selection to 0 in CoverFlowExampleActivity , like this:
coverFlow.setSelection(4, true);
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "java, android"
}
|
How to remove the automatic generation of line DataGridView
I have a `DataGridView` that after entering all the information in it. It always generates an automatic line, worthless.
How can I remove that line there? Can anyone help me?
|
Set the **AllowUserToAddRows** property of the DataGridView to **False** and you're done. MSDN Link
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 0,
"tags": "c#, datagridview"
}
|
How to add a colored overlay in an image while hover?
<div class="col-lg-6">
<ul>
<li><a target="_blank" href=" src="images/stackoverflow.png" alt="Upwork" class="img-responsive" style="width: 35px;display:inline;"></a></li>
</ul>
</div>
This is the image I am using:
;
}
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "jquery, html, css"
}
|
Java Wrapper for Mailchimp API v3.0
I just started working with the Mailchimp API. So far I have configured the open authentication using `Node.js` and `Angular.js`. I want to implement an export of customers (First name, Last name and Email) from my app to a Mailchimp list. I want to do this in a `Java` worker, so I started looking for a Mailchimp API wrapper for `Java`. So far I have managed to find ecwid-mailchimp wrapper, but it is for Mailchimp API v2.0 and it looks like the project is dead.
Is there an active implementation of a `Java` wrapper for Mailchimp API v3.0?
It does not seem a good idea to use the old API (v2.0) and a dead implementation in a new project.
The alternative is to do the implementation by myself, but it is a waste of time if someone has already done it.
|
After a lot of searching I found this project on github. It is incomplete, but I created a pull request with the OAuth and am currently working on batches.
|
stackexchange-stackoverflow
|
{
"answer_score": 4,
"question_score": 11,
"tags": "java, mailchimp, mailchimp api v3.0"
}
|
Cast object to Class who's type was passed as a parameter
What I want to do is:
- (UIView *)getView:(UIView *)recycledView withClass:(Class)myClass
{
myClass *currentItem = (myClass*)recycledView;
....
}
I'm calling this function as follows:
[self getView:myView withClass:[SpecialView class]];
Getting a compilation error, any ideas if it's possible to achieve this?
|
A cast happens during compilation, so attempting to cast to a type that's determined at run time (as in an Objective-C method call) is impossible.
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "iphone, objective c"
}
|
How to convert this apache mod rewrite to iis web.config
I am using apache mod rewrite and i have a .htaccess rewrite statement. I would like to change over to use IIS server and would like to know if any one can give me advice on how to convert my existing .htaccess statement to iis web.config.
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php?url=$1 [PT,L]
</IfModule>
Expert Advice appreciated.
|
Resolved. Download url rewrite from Microsoft web platform installer. Url rewrite module can auto create the web.config when you specify the rules via their ui.
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "mod rewrite, web config, iis express"
}
|
MySQL support for polish letter - ę
I'm having trouble making the letter ę appear in my mysql database. I set all the tables to uf8_polish_ci but still the ę character changes into a ? character. (I'm inputting all data directly into the database) Any advice would be much appreciated.
Thanks, Aleks
|
why not use utf8_general_ci to support all kind of characters?
Define both the table and the fields as utf8_general_ci.
Also if you insert the fields using PHP or some other language, make sure the connection is set to utf-8 as well.
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 1,
"tags": "mysql, database"
}
|
Не будет ли ошибкой поставить для объекта много колайдеров? или лучше сделать через EdgeColider?
Не будет ли ошибкой поставить для объекта много колайдеров? или лучше сделать через EdgeColider?
|
Если мы говорим о том, что лучше - добавить 5 компонентов `BoxCollider2D` или 1 компонент `EdgeColider2D`, то лучше держдать кол-во компонентов по минимуму, т.е. 1 компонент лучше, чем 5.
В общем случае: Если объект будет динамическим, и нужна фигура с закрытыми границами - `BoxCollider2D`. Если объект будет статическим, и проверять нужно просто границу - `EdgeColider2D`.
Но в любом случае, об ошибках тут речи не идет, делайте так, как вам быстрее и удобнее, очень маловероятно что выбор между `BoxCollider2D` или `EdgeColider2D` даст вам ощутимый прирост производительности, или окажется узким местом производительности.
|
stackexchange-ru_stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "unity3d"
}
|
How to force any program to use SOCKS?
I want to use a SOCKS proxy for all my programs that want to connect to Internet. I am connected to my ISP using an ADSL modem.
Is there any virtual system or settings which can let me do this?
I don't want to buy or use VPN.
|
I'm going to take a chance, let me know how it goes
I have heard of these programs mentioned, but haven't tried them
"If the Internet program you are using does not have a socks proxy option you can use Sockscap to make it support socks proxy. Here is a tutorial showing how to use Sockscap." <
and you may be interested in trying this one "Sockschain is a program that allows to work with any Internet service through a chain of SOCKS or HTTP proxies.." <
|
stackexchange-superuser
|
{
"answer_score": 2,
"question_score": 12,
"tags": "windows 7, windows, internet, proxy"
}
|
Solving 2nd order ODE with conditions (problem)
I was reading my notes and I am given 2 equations:
$$(1+x)\frac{dy_0}{dx} + y_0 =0,\ \ \ \ y_0(1) =1$$
$$(1+x)\frac{dy_1}{dx} + y_1 = - \frac{d^2y_{0}}{dx^2} ,\ \ \ \ y_1(1) =0$$
Which have the solutions:
$$y_0(x) = \frac{2}{1+x}$$
$$y_1(x) = \frac{2}{(1+x)^3} - \frac{1}{2(1+x)}$$
The problem I have is that I can't seem to get the 2 solutions. I tried solving the equations, starting with the first one, and what I got was:
$-\ln y_0 = \ln(1+x) + c$
$y_0 = -A(1+x)$ and using $y_0(1) =1$, I get $A = -\frac{1}{2}$ and so $y_0(x) = \frac{1+x}{2}$. Have I done something wrong here?
And how do I solve $$(1+x)\frac{dy_1}{dx} + y_1 = - \frac{d^2y_{0}}{dx^2} ,\ \ \ \ y_1(1) =0?$$ Im kind of confused with the $y_0$ and $y_1$ terms and how to approach it.
|
You have done the integration part correct, but then $-\ln y_0=\ln (1+x)+c\Rightarrow \ln y_0+\ln(1+x)=-c=A\Rightarrow y_0=\frac{A}{1+x}$
For the second part, we have $\frac{dy_0}{dx}=-\frac{2}{(1+x)^2}$. So, your equation becomes, $$(1+x)\frac{dy_1}{dx}+y_1=\frac{d}{dx}\left[\frac{2}{(1+x)^2}\right]$$
$$\Rightarrow (1+x)dy_1+y_1d(1+x)=d\left[\frac{2}{(1+x)^2}\right]$$
$$\Rightarrow d\left[y_1(1+x)\right]=d\left[\frac{2}{(1+x)^2}\right]$$ Integrating, $$y_1(1+x)=\frac{2}{(1+x)^2}+c$$ Using $y_1(1)=0$, we get $c=-2$. Hence,....
|
stackexchange-math
|
{
"answer_score": 1,
"question_score": 1,
"tags": "ordinary differential equations"
}
|
How to loop through columns a given number of times
I have my top row filled with values. I would like to insert two columns between each of these values, until the last non-empty cell in my top row.
I'm stuck there in my code:
Sub AddCol()
'
' AddCol Macro
'
For i = 1 To 2
Sheets("CashFlow").Select
Columns(i + 1).Select
Selection.Insert Shift:=x1ToRight, CopyOrigin:=xlFormatFromLeftOrAbove
Next i
End Sub
|
This will Work For you:
Sub AddCol() ' ' AddCol Macro '
With Thisworkbook.Worksheets("CashFlow")
For i = 1 To .Cells(1, Columns.Count).End(xlToLeft).Column * 3 Step 3
.Columns(i + 1).Insert Shift:=x1ToRight, CopyOrigin:=xlFormatFromLeftOrAbove
.Columns(i + 1).Insert Shift:=x1ToRight, CopyOrigin:=xlFormatFromLeftOrAbove
Next i
End With
End Sub
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 1,
"tags": "excel, vba"
}
|
Is it true that $\Bbb{E}(X_\infty)=\Bbb{E}(X_0)$ if $X$ is a martingale?
> Let us consider a martingale $(X_n)_n$. Let me assume that $\lim_{n\rightarrow \infty} X_n=X_\infty$ exists a.s. and in $L^1$.
My question is, is it then always true that $\Bbb{E}(X_\infty)=\Bbb{E}(X_0)$? I would say it is true if there exists $Y\in L^1$ such that $|X_n|\leq Y$ because then we can apply DCT and get that $\Bbb{E}(X_\infty)=\lim_n \Bbb{E}(X_n)$ and since $X_n$ is a martingale we know that $\Bbb{E}(X_n)=\Bbb{E}(X_0)$ and we are done.
Is it furthermore true that I need the two assumptions that the limit exists a.s. and in $L^1$ if one fails I cannot use the DCT. But if I for example have that the limit exists in $L^p$ then my proof would also work right?
|
1. If $Y_n \to Y$ in $L^{1}$ then $|EY_n-EY|\leq E|Y_n-Y| \to 0$, so $EY_n \to EY$.
2. If $(X_n)$ is martingale then $EX_n=EX_0$ for all $n$.
Once you have $L^{1}$ convergence you don't have to use DCT and you don't have to use almost sure convergence.
|
stackexchange-math
|
{
"answer_score": 2,
"question_score": 1,
"tags": "probability, probability theory, stochastic calculus, martingales"
}
|
How can I convert a Perl regex to work with Boost::Regex?
What is the Boost::Regex equivalent of this Perl regex for words that end with `ing` or `ed` or `en`?
`/ing$|ed$|en$/`
...
|
/^[\.:\,()\'\`-]/
should become
"^[.:,()'`-]"
The special Perl regex delimiter `/` doesn't exist in C++, so regexes are just a string. In those strings, you need to take care to escape backslashes correctly (`\\` for every `\` in your original regex). In your example, though, all those backslashes were unnecessary, so I dropped them completely.
There are other caveats; some Perl features (like variable-length lookbehind) don't exist in the Boost library, as far as I know. So it might not be possible to simply translate any regex. Your examples should be fine, though. Although some of them are weird. `.*[0-9].*` will match any string that contains a number somewhere, not `all numbers`.
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 3,
"tags": "c++, regex, perl, boost regex"
}
|
After Generate rig, the pole doesn't work. why?
After Generate rig.
Press Alt+H to find pole. Click the Pole and moves sideways.
But the knee does not work... why?
Here's a video that shows the problem: <
Here's the .blend file: <
, next is a pole target, witch is hidden by script. And the reason that script always hides the pole target is because it does not use.
There is a switcher between bone rotation and pole target rotation is in `N`-panel has name **pole_vector** :
 to get a boolean equation for the next state bits and the output bit,
but what is the function of ROM here ?
 is a brute force (=absolutely non-minimized) way to implement a combinatoric circuit. Current state bits and inputs together are address, the data stored into that address contains the next state and possible output bits which both can depend on current state and input bits.
When one builds a state machine using standard parts, he probably appreciates a construction where all logic gates in the state transition & output logic are replaced by a single easily programmable IC.
I would add buffer latches to input and output bits to keep sure that inputs are read and outputs are updated in sync, the output bits should in the rom should be surely settled before they are used.
|
stackexchange-electronics
|
{
"answer_score": 14,
"question_score": 2,
"tags": "verilog, shift register, register, state machines, rom"
}
|
Percentage sign in column centered about decimal point
I know how to centre a column about the decimal point using the siunitx package. How do I include a percent sign in the column heading, ie "Heading (%)"? Neither \% or \SI{}{\percent} seem to work.
\documentclass[a4paper]{article}
\usepackage{siunitx}
\begin{document}
\begin{table}
\sisetup{output-decimal-marker = {\cdot}}
\begin{tabular}{S}
\hline
\\ \hline
3.93 \\ \hline
3.3 \\ \hline
\end{tabular}
\end{table}
\end{document}
|
Use `{Heading (\si{\percent})}`. The outer braces are to protect the heading from being recognized as a numerical entry that `siunitx` would otherwise attempt to align.
\documentclass[a4paper]{article}
\usepackage{siunitx}
\begin{document}
\begin{table}
\sisetup{output-decimal-marker = {\cdot}}
\begin{tabular}{S}
\hline
{Heading (\si{\percent})} \\ \hline
3.93 \\ \hline
3.3 \\ \hline
\end{tabular}
\end{table}
\end{document}
!enter image description here
As noted in a comment by daleif, the brace group is not always sufficient for protecting the header contents. In some situations (namely, where the `@{}`, `!{}`, `>{}`, or `<{}` constructs from the `array` package have been used), `\multicolumn{1}{c}{<header content>}` is required instead.
|
stackexchange-tex
|
{
"answer_score": 2,
"question_score": 2,
"tags": "siunitx"
}
|
Help with try/catch and accessing elements within the try
try {
inFile = new Scanner(file);
}
catch (FileNotFoundException e) {
System.out.println("FileNotFoundException");
}
I have this code. However, after the try/catch statement I have the following:
while(inFile.hasNext()) {
}
The compiler is telling me that I have not initialized inFile. Do I need to put all of my code within the try/catch? What am I doing wrong?
|
Initialize inFile:
Scanner inFile = null;
**Edit:**
As others have mentioned, you should be careful that you could potentially get a NullPointerException in your while loop. You should consider moving your while loop into the try block as well:
Scanner inFile = null;
...
try {
inFile = new Scanner(file);
while(inFile.hasNext()) {
}
}
catch (FileNotFoundException e) {
System.out.println("FileNotFoundException");
}
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 1,
"tags": "java, try catch"
}
|
Angular JS custom textbox from a list validation
I am creating dynamic textboxes from a list like the following
**Angular js**
$scope.phonenumbers = [{text: ''},{text: ''},{text: ''}];
HTML Part
<div class="relativeWrap" ng-repeat="phone in phonenumbers">
<input placeholder="Phone Number" pattern="[0-9]{10}" ng-maxlength="10" maxlength="10" type="text" class="form-control input-text phone_number" name="phonenumber[]" ng-model="phone.text" >
</div>
Now I need to do the following validation in form
1. Any one of the following 3 textboxes is mandatory. I put `required` but it is validating all.
Please help
|
You will need to use ng-required and conditionally set the required to true for all the field only when none of the fields have a value. To do this you will need to maintain a flag in your controller and bind that your ng-required.
The method in the controller:
$scope.isValue = false;
$scope.textChange = function(){
$scope.isNoValue = $scope.phonenumbers.some(function(item)){
return item.text;
}
}
Your HTML:
<div class="relativeWrap" ng-repeat="phone in phonenumbers">
<input placeholder="Phone Number" pattern="[0-9]{10}" ng-maxlength="10" maxlength="10" type="text" class="form-control input-text phone_number" name="phonenumber[]" ng-model="phone.text" ng-required="!isValue" ng-change="textChange">
</div>
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "html, angularjs, validation"
}
|
What is meant by a 'pure' wave?
What is meant by a 'pure' wave?
I know it might sound like a basic question, but I've never been taught this.
I saw that a sine wave is a _pure_ wave. I tried Googling what a _pure_ wave is, but all I get is links regarding _Pure Wave Inverters for sale_...which is not what I'm looking for.
|
A sine or cosine wave has just one frequency and it called a pure wave for that reason. If you have a periodic function with a different shape you can Fourier analyze it and get some number of different frequencies. These are not pure waves because of the multiple frequencies.
|
stackexchange-math
|
{
"answer_score": 13,
"question_score": 6,
"tags": "trigonometry"
}
|
"425 Can't open data connection" only from some clients
I have several Windows 7 computers on the same network using the same router. On one of them I installed FileZilla server.
Using Chrome, Internet Explorer, etc. I am able to connect and upload to the server from all client computers.
I also have a .NET program that uploads files using `FtpWebRequest` class. When I try to upload using my program it works from some computers but not from others. I get the following error from the server:
> 425 Can’t open data connection for transfer of
|
This is probably a problem of firewalls blocking data connections into the computer. You need to switch to passive mode, see Is it possible to use “Passive Mode” with FtpWebRequest.
|
stackexchange-superuser
|
{
"answer_score": 0,
"question_score": 0,
"tags": "windows 7, ftp, filezilla"
}
|
C: How do I convert %20 to spaces?
I ran across this program while writing a graphical frontend to the GNU Coreutils `shred` program. When a user drags in a file that has spaces in it, such as `my private data.docx`the GTK+ DND service represents those spaces as `%20`. Using that example i would get (for the filename) `my%20private&20data.docx`. I need to convert those to space characters because I use the `fopen` function from `stdio.h`. `fopen` refuses to open filenames like that because it does not recognize `%20` as a representation for a space.
|
No, you do not replace `%20` with spaces. You decode the URL into a filename, with `g_filename_from_uri`:
gchar *
g_filename_from_uri (const gchar *uri,
gchar **hostname,
GError **error);
and usage therefore
gchar *filename = g_filename_from_uri(uri, NULL, NULL);
at its simplest.
|
stackexchange-stackoverflow
|
{
"answer_score": 3,
"question_score": 0,
"tags": "c, drag and drop, gtk"
}
|
What's the difference between software engineering and software project?
I find that I'm confused between the terms "software engineering" and "software project".
What is the difference between these? I suspect that "software engineering" may focus on a different aspect, but I'm not 100% sure. Can someone please explain?
|
Study of different approaches like design, development, operation, and maintenance of software and applicaiton of these concepts can be termed as software engineering. A project involving Software which has fixed goal and limited resources to complete can be termed as software project.
I tend to think that to execute a software project you need to implement software engineering concepts.
|
stackexchange-pm
|
{
"answer_score": 2,
"question_score": 0,
"tags": "terminology"
}
|
FTP date variable to grab ftp file
I am trying to write a script that will grab a file from an ftp site.
The issue I am having is figuring out how to grab the files that have dates on them. For example on January 1st we run mar2019. February 1st would run apr2019.
I am trying to figure out how to write something to automate this but cannot figure out how to grab the correct dated file.
Any help with this would be greatly appreciated.
**u.ftp**
open ftp.site.com
username
password
mget 'Name.Name.RENEWALS.MAR2019'
disconnect
quit
run with
ftp -i -s:u.ftp
|
The concept to insert a variable into a template and
write that to a file is the same in batch/powershell.
As getting/formatting the date is easier in PowerShell a here string is used for the template:
## Q:\Test\2019\01\02\SO_54009396.ps1
$Month = (Get-Date).AddMonths(2).ToString('MMMyyyy')
$ftpScript = '.\u.ftp'
@"
open ftp.site.com
username
password
mget 'Name.Name.RENEWALS.$Month'
disconnect
quit
"@ | Set-Content $ftpScript
&ftp -i -s:$ftpscript
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 0,
"tags": "powershell, cmd, ftp"
}
|
TinyMCE 4: How to disable/hide tooltip?
I've just upgraded my TinyMCE to version 4, which seems to have a tooltip by default.
How can I disable/hide the tooltip that appears on mouse-over on any tool-bar item?
|
I've been searching for any possible solution, but so far, I have found nothing in the official documentation. What I found in the development `tinymce.js` file (uncompressed version) is that tooltip is hardcoded and set to be included every time.
I tried different things to disable the tooltip, by so far, the easiest and safest way I came up with is by using CSS, include this bit of code in the main css file to hide the tooltip forever:
.mce-widget.mce-tooltip {
display: none !important;
}
This solution avoids using Javascript/jQuery, and also avoids modifying the source file `tinymce.js`.
|
stackexchange-stackoverflow
|
{
"answer_score": 8,
"question_score": 6,
"tags": "tinymce"
}
|
Are the Spring @PostConstruct and @PreDestroy method's annotations annotations a form of AOP?
I have the following doubt related to the Spring **@PostConstruct** and **@PreDestroy** method's annotations.
So the **@PostConstruct** annotation means that the annoted method is automatically performed after the object creation and after the dependency injection done using the setters metthod
The **@PreDestroy** is automatically performed before when the ApplicationContext is closed.
My doubt is: are the **@PostConstruct** and **@PreDestroy** annotations a form of **AOP** or not?
|
AOP is a **programming paradigm** , see here. If I understand your question correctly you are asking are the "@PostConstruct and @PreDestroy" in scope of AOP. My answer would be **yes** , at least because they are developed with using Reflection that isn't OOP.
Note:
> AOP includes programming methods and tools that support the modularization of concerns at the level of the source code.
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 2,
"tags": "java, spring, aop, spring aop, postconstruct"
}
|
When do qubits get entangled?
I was just curious; when do the qubits get entangled? Do the qubits get entangled right after initialization or do they get entangled when we apply Hadamard Gates to the qubits?
|
As mentioned before, qubits are only entangled by means of 2-qubit gates and not by 1-qubit gates, which only cause a rotation of the qubit state in question. Therefore, 2-qubit gates are needed to provide anything meaningful on a quantum computer other than pure random number generation. Practically, 2-qubit gates (typically a CX - gate) are harder to realize than 1-qubit gates, which also leads to a significantly larger quantum error.
|
stackexchange-quantumcomputing
|
{
"answer_score": 1,
"question_score": 1,
"tags": "quantum state, entanglement"
}
|
How to split single day in column in fullcalendar?
I want to split single day of Fullcalendar view in multi column. Some thing like this. How can I achieve this ? !enter image description here
This question partially related to this one Fullcalendar - limit selectable to a single day
Thanks , Any kind of help will greatly appreciated.
|
I found some help here by this link: <
which led me to
<
I took this fork of fullcalendar and was able to replace the 1.5.3 that i was using and then used the resourceDay view.
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 5,
"tags": "javascript, jquery, fullcalendar"
}
|
Apache2 Block IP with 404 Page or Timeout Error
Is there any was to configure Apache2 to block certain IPs, but instead of returning a 403 page; do one of the following:
Return a 404 page
Make the connection time out (as it would say in a web browser)
Refuse the connection (again as it would say in a web browser)
The last option would be best for me, but any of those listed would work.
|
You can use rewrite module to do it.
RewriteCond %{REMOTE_ADDR} !^111.222.333.444$
RewriteRule ^ - [R=404,L]
taken from this thread on stackoverflow <
|
stackexchange-serverfault
|
{
"answer_score": 0,
"question_score": 1,
"tags": "apache 2.4, apache2, http status code 404"
}
|
Getline which awk builtin variables are avaliable
We all know that there are several built-in variables in awk utility like - NF, FS, NR, and positional variables like $0 ... . I have an awk script where I am using getline functionality to get output of a command like below:
while ( ("ls -l" |& getline) > 0) {
}
while ( ("ls -l" | getline) > 0) {
}
while ( ("ls -l" |& getline) > 0) {
}
while ( ("ls -l" |& getline var) > 0) {
}
Please let me know which of the AWK built-in variables I can infer inside the while loop. I tried accessing NR but it always gives me 0? Say I want to write something like below:
while ( ("ls -l" |& getline) > 0) {
if(NR == 1)
{
do something .. by parsing data via a Field Separator
}
}
|
See < and make sure you fully understand it and have a lot of awk experience before being tempted to use getline. The example you give is almost certainly NOT a good candidate for using getline.
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "awk"
}
|
find a special character from string in python and remove the later part
I have a pandas dataframe of more than 100,000 news articles.
What I'm trying to do is to find the last `.` so that I can remove the other strange things after the last sentence.
One of the sample document is like this:
...Trump questioned the independence of an inspector. blah blah [email protected] Plz susbscribe this guys!
I thought of using `.split('.')`, return `stringList[:-1]`, and join the list again so that I can remove the later part.
I am not sure this is an optimal way of doing this. Prob I can search `.` from the back?
Any advice would be appreciated. Thank you!
|
s= '...Trump questioned the independence of an inspector. blah blah [email protected] Plz susbscribe this guys!'
>>> '.' in s
True
>>> print(s.rindex('.'))
75
This will return the last index where the substring (.) was found and then you can use this information to say hereafter this just delete everything after.
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": -1,
"tags": "python, string"
}
|
iterate on scala list and treating last iteration differently
I have a list of objects that I am calling `toString` on, and would like to treat the last object differently as follows:
o1 = Array(...)
o2 = Array(...) // same length as o1
sb = new StringBuilder()
for (i <- 0 to o1.size() - 1)
sb.append(o1.get(i).toString() + " & " o2.get(i).toString())
// if not last iteration then append ", "
is there a simple way to write this in scala rather than checking value of `i` etc?
|
@jwvh's anwser is good.
just give another pattern-matching version.
o1.zip(o2).map({case (item1, item2) => s"$item1 & $item2"}).mkString(", ")
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 0,
"tags": "scala"
}
|
What steps should I take to make sure Synology VPN Server is secure?
We we have a remote office with a Synology NAS and we would like it to connect to the home office Synology NAS. We have setup VPN Server (Synology package) on the home office NAS and enabled OpenVPN. The next step would be to open the appropriate port on our home office firewall to enable the inbound OpenVPN connection, however I am concerned this opens us up to security risks/threats and want to see if there are any steps I can take to make sure this is secure as possible.
What steps can I take to strengthen the security of our Synology VPN setup? Should we change the default OpenVPN port, or will that not matter? Any other steps to harden our configuration?
We have already selected AES256 encryption.
|
At the very least, you'll want to make sure you have the following bases covered:
1. Make sure that your Synology NAS[es] and other endpoints are always caught up on security updates.
2. Make sure both Synology endpoints have valid SSL certificates in use and that all traffic is going through encrypted ports.
3. Configure and use MFA (multi-factor authentication) for all users on your Synology endpoints.
4. Enforce decent password complexity rules.
5. Make sure that you only allow remote access to the local network ports and applications that are truly required over the VPN. Don't open up all of your Synology applications and services just because you can.
6. If you have static IP addresses at your two offices, you can use network ACLs to only allow those IP addresses to connect to the VPN.
|
stackexchange-serverfault
|
{
"answer_score": 2,
"question_score": 1,
"tags": "security, vpn, openvpn, synology"
}
|
A question relted to NSMUtabledata
NSDATA *data1; NSDATA *data2; NSDATA *data3;
I want to convert my this all 3 data's to bytearray and then again i want to append it to the NSMutabledata;
What Should I do For that?
|
There is no need to convert them to a byte array.
NSMutableData *md = [NSMutableData dataWithData:data1];
[md appendData:data2];
[md appendData:data3];
will give you the data in `md`.
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 0,
"tags": "iphone"
}
|
Using Powershell to get Office 365 SMTP: email addresses
Found the exact script I need:
<
Get-Mailbox -ResultSize Unlimited |Select-Object DisplayName,ServerName,PrimarySmtpAddress, @{Name=“EmailAddresses”;Expression={$_.EmailAddresses |Where-Object {$_.PrefixString -ceq “smtp”} | ForEach-Object {$_.SmtpAddress}}}
When I run this using Powershell5 against Office 365, "Email Addresses" is returned blank.
Any ideas?
|
This may have worked on Exchange 2007/2010, where the blog post says it was tested, but O365 mailboxes are a little different.
The `EmailAddresses` property of a mailbox object in O365 is an array list containing strings and they have no `PrefixString` property here. The issue is at this point
Where-Object {$_.PrefixString -ceq “smtp”}
Since `PrefixString` doesn't exist, you get blank results.
Instead, since the `EmailAddresses` array is just a bunch of strings, you can filter on those directly.
Get-Mailbox -ResultSize Unlimited | Select-Object DisplayName,ServerName,PrimarySmtpAddress, @{Name=“EmailAddresses”;Expression={$_.EmailAddresses | Where-Object {$_ -clike “smtp*”}}}
|
stackexchange-stackoverflow
|
{
"answer_score": 4,
"question_score": 2,
"tags": "powershell"
}
|
Get Ruby to identify if child process get a segfault
I am running Ruby as a wrapper to an EDA tool, in RH5.
The tool segfaulted. However, the command line did not show any indication. Only when running the command that Ruby launched, did we learn that the segfault happened. How can I get the segfault message within the wrapper? Thanks.
|
From Kernel#system documentation:
> system returns true if the command gives zero exit status, false for non zero exit status. Returns nil if command execution fails. An error status is available in $?.
So, if you just want to make sure that everything went ok, you just check if the return value of `system` was `true`. If you want to specifically check if there was a segmentation fault, then the return value will be `false` and `$:` will be like this:
puts $?
#=> pid 3658 SIGSEGV (signal 11)
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "ruby, linux, segmentation fault"
}
|
Is that a sundew?
!enter image description here
I have bought the seeds for a sundew/drosera (growbro.nl) but I have pretty serious doubt if that is really the plant I wanted :-)
If not, what kind of plant is that I have grown?
|
This is not a sundew. A simple Google search can confirm that.
;return false;" >DoubleActionLink</a>`
`<script>
function update() {
window.open(" parent.document.getElementById('frame1').src=" }
</script>`
btw, you said
> I want to call an html form
html form means you'll submit something to web server...so you aren't asking for pure html solution. Isn't ?
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 1,
"tags": "html"
}
|
Handling credentials in an app consuming a WCF service with WIF/Geneva
I wonder what are the best practises in a client app ( winforms/ console/ whatever else) regarding consuming WCF that is Authorized and authenticated using WIF (used to be called geneva).
Also at a service level, is it possible to cache the token so the the trip to the STS is not necesary for every WCF operation? ( more info on this also apreciated) Thanks
|
You need to send the token each time, just like you would need to send a username and password each time to a web service secured with usernames and passwords. Just because you're using a SAML token doesn't change this.
You can however cache the token on the client side - each token has a valid from and valid to associated with it so, if the web service is not checking for uniqueness of each token via the assertion ID then you could cache on the client. However a well written web service may well be checking the assertion ID to stop relay attacks.
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 1,
"tags": "wcf, wif, geneva framework"
}
|
How to Change size of split screen emacs windows?
If I have Emacs split horizontally and on top I'm editing elisp code and on the bottom I am in the shell. By default, Emacs makes the two windows equal in size, but I'd like the shell buffer smaller. I was wondering how I could do that.
Original question asked by Steve on SO: How to Change size of split screen emacs windows?
|
`C-x``-` (`shrink-window-if-larger-than-buffer`) to shrink a window to fit its content.
`C-x``+` (`balance-windows`) to make windows the same heights and widths.
`C-x``^` (`enlarge-window`) to increase height by 1 line, or the prefix arg value. A negative arg shrinks the window. Example: `C-u` `-` `3` `C-x` `^`
`C-x``{` (`shrink-window-horizontally`)
`C-x``}` (`enlarge-window-horizontally`)
|
stackexchange-emacs
|
{
"answer_score": 45,
"question_score": 24,
"tags": "window, customize"
}
|
Javascript event like window.onload for subsequent loads
We have a function that changes the iframe height at the window.onload event so we can adjust it to the page contents. The problem is that after clicking in an asp:menu the height its restored to its default and the window.onload event doesnt fire...so we need the event that would fire in subsequent loads (tried window.unload but didnt trigger)
The resize function cant be called on the asp:menu click because the window wouldnt have finished loading so the height calculation would fail...
Any ideas??
|
ASP.Net AJAX exposes a client event model. To execute code after the content is refreshed, use this to bind to the `pageLoaded` event:
Sys.WebForms.PageRequestManager.getInstance().add_pageLoaded(pageLoadedFunction);
Learn more about all of the ASP.Net AJAX JavaScript events here: <
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "c#, javascript, asp.net"
}
|
Android: Difference between FileOutputStream and FileWriter
I was wondering what the exact difference is between Android's FileOutputStream and FileWriter class. When would it be most appropriate to use each one?
|
If I remember correctly, FileOutputStream is more general purpose - it can be used for binary data or text data. FileWriter is used for text only.
<
> FileWriter is meant for writing streams of characters. For writing streams of raw bytes, consider using a FileOutputStream.
|
stackexchange-stackoverflow
|
{
"answer_score": 9,
"question_score": 8,
"tags": "java, android, file io"
}
|
Power generator (wrong verse)
This is a very simple Tikz circuit
\documentclass{standalone}
\usepackage{circuitikz}
\begin{document}
\begin{circuitikz}[american]
\draw (0,0) to V, l={$v$}, i^>={$i$} to (3,3) to R, l={$R$} to (0,0);
\end{circuitikz}
\end{document}
and the results is this one:
 toV ...`
|
Simple solution by using invert
\documentclass{standalone}
\usepackage{circuitikz}
\begin{document}
\begin{circuitikz}[american]
\draw (0,0) to V, l={$v$},invert, i^>={$i$} to (3,3) to R, l={$R$} to (0,0);
\end{circuitikz}
\end{document}
 если можно использовать слайс без указания границ?
Сейчас плотно изучаю нюансы методов встроенных типов, и есть один вопрос, на который не могу найти ответ.
В Python 3.3 ввели метод списка copy(), который делает поверхностную копию. Но то же самое можно было делать, просто взяв срез без границ - list[:]
Зачем было вводить новый метод?
Подозреваю, что какая-то причина есть. Например, сначала я считал таким же ненужным нововведением метод list.clear(), введённый в том же Python 3.3, ведь есть же list = []
А потом я прочитал, что эти две синтаксические конструкции по разному работают в ситуациях, когда на список ссылаются две или более переменных.
Подозреваю, что и для copy() существует такое же очевидное задним числом обоснование, но найти его пока не смог.
|
Чтобы сделать операции `del list_[:]` и `shallow_copy = list_[:]` более очевидными (discoverable) и читаемыми для новичков (`list_.clear()` и `shallow_copy = list_.copy()` соответственно). See Add list.clear() and list.copy()
В целом, в Питоне есть предпочтение к использованию слов вместо пунктуации, например: `and`, `or` вместо `&&`, `||` или `on_true if cond else on_false` вместо `cond ? on_true : on_false` или `re.search(regex)` вместо `/regex/`.
Дополнительно, наличие явного метода `list_.clear()` может уменьшить вероятность возможной ошибки:`list_ = []` существенно отличается от `del list_[:]` (первая конструкция создаёт _новый список_ и привязывает его к имени `list_`, вторая конструкция удаляет все элементы из _существующего объекта_ (изменяемой последовательности такой как список наиболее вероятно)).
Недостаток, что эти методы дублируют функциональность изменяемых последовательностей/отображений (объекты с `__getitem__`, `__delitem__` методами).
|
stackexchange-ru_stackoverflow
|
{
"answer_score": 7,
"question_score": 6,
"tags": "python, python 3.x, списки"
}
|
Twitter Bootstrap and Font-Awesome: Some fonts appear as double (and more)
Specifically...
<i class="icon-ok"></i> and <i class="icon-hand-up"></i>
...appear as double or quadruple.
!This is what I am seeing
|
> Customize Twitter Bootstrap here. Make sure to uncheck the default "Icons" under "Base CSS."
Because you haven't done this, both Glyphicons and Font Awesome icons are visible.
|
stackexchange-stackoverflow
|
{
"answer_score": 11,
"question_score": 6,
"tags": "fonts, twitter bootstrap, font awesome"
}
|
errorCode": "APEX_ERROR", "message": "System.NullPointerException: Argument cannot be null
If i pass date i am able to execute first if condition but if parameter is not passed in URL from postman, i am getting Null pointer exception error.
RestRequest restReq = RestContext.request;
// Reading parametrs from URL
dt = restReq.params.get('date');
Date d = Date.parse(dt);
if(!String.isBlank(dt)){
Record = [SELECT A,B,C,D WHERE E >= :d];
}
if(String.isBlank(dt)){
Record = [SELECT A,B,C,D WHERE E >= :date.today()-7];
}
|
You can't pass `null` to `Date.parse()` method. So, you have to validate it before passing to the `parse` method.
RestRequest restReq = RestContext.request;
String dt = restReq.params.get('date');
if (String.isNotBlank(dt)) {
Date d = Date.parse(dt);
Record = [SELECT A,B,C,D WHERE E >= :d];
// OR
Record = [SELECT A,B,C,D WHERE E >= :date.today()-7];
}
else {
// handle validation
}
|
stackexchange-salesforce
|
{
"answer_score": 1,
"question_score": 0,
"tags": "apex, rest api"
}
|
Priority queue lambda comparator and normal comparator
#include <iostream>
#include <queue>
#include <vector>
#include <array>
using namespace std;
auto cmp2(const array<int, 2>& a, const array<int, 2>& b) {
return a[0]+a[1] > b[0]+b[1];
}
int main() {
auto cmp = [] (const array<int, 2>& a, const array<int, 2>& b) {
return a[0]+a[1] > b[0]+b[1];
};
priority_queue<array<int, 2>, vector<array<int, 2>>, decltype(cmp)> pq(cmp);
priority_queue<array<int, 2>, vector<array<int, 2>>, decltype(cmp2)> pq2(cmp2);
}
There is a lambda comparator in the main function and another comparator outside. Why only the first priority queue can compile while the second one cannot and gives an error of invalidly declared function type. Thank you in advance.
|
`cmp` is a lambda. It's an object with a `()` operator.
But `cmp2()` is a function.
You can't use a function as a callable type, but you can use a function _pointer_ as a callable type, in that case you must use `decltype(&cmp)` to get a function pointer type:
priority_queue<array<int, 2>, vector<array<int, 2>>, decltype(&cmp2)> pq2(&cmp2);
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 1,
"tags": "c++, stl, comparator, priority queue"
}
|
What method is called when a user taps on a tab bar. I need to refresh tabs content
I would like my app to automatically refresh contents of a tab when a user taps on the corresponding tab bar. Once the app is loaded and in the memory, it always loads the existing content of the tab. I have a image on the tab that I want to update/refresh when user tabs on it.
|
That would be the void `viewDidLoad, viewWillAppear & viewDidAppear` methods of the view controller linked to the tab.
You'll probably want to go with `viewWillAppear` or `viewDidAppear` as these are called every time these views will/did appear as opposed to the first time they load before they initially appear.
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 1,
"tags": "ios"
}
|
Deleting cache cookie for chrome using shortcut
I am trying to simulate the shortcut for deleting cache/cookies for chrome using java robot class methods. I does not work for key combination SHIFT+Ctrl+e. Why does this not working? Is it a security reason or my coding error?
Code snippet:
Robot robot = new Robot();
robot.delay(5000);
robot.keyPress(KeyEvent.VK_CONTROL);
robot.keyPress(KeyEvent.VK_SHIFT);
robot.keyPress(KeyEvent.VK_E);
robot.delay(100);
robot.keyRelease(KeyEvent.VK_E);
robot.keyRelease(KeyEvent.VK_SHIFT);
robot.keyRelease(KeyEvent.VK_CONTROL);
|
Firstly as per my info we need : CTRL + SHIFT + DELETE to do this task
Robot robot = new Robot();
robot.delay(5000);
robot.keyPress(KeyEvent.VK_CONTROL);
robot.keyPress(KeyEvent.VK_SHIFT);
robot.keyPress(KeyEvent.VK_DELETE);
robot.delay(100);
robot.keyRelease(KeyEvent.VK_DELETE);
robot.keyRelease(KeyEvent.VK_SHIFT);
robot.keyRelease(KeyEvent.VK_CONTROL);
Thread.sleep(2000);
But why to complicate it, use inbuilt functions:
driver.manage().deleteAllCookies();
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "java, selenium, selenium webdriver, automation"
}
|
How do I print a specific item from a for loop in python?
I have this code that's supposed to select 4 random words from a list and put them together to create a password
passphr = []
for r in range(4):
passphr.append(secrets.choice(words_lst))
print(passphr)
This prints out:
['cognitive']
['cognitive', 'shakespeare']
['cognitive', 'shakespeare', 'connectors']
['cognitive', 'shakespeare', 'connectors', 'municipal']
How do I make it print out only the last line with all the words joined together?
|
You can use join and print outside of the loop.
passphr = []
for r in range(4):
passphr.append(secrets.choice(words_lst))
print(''.join(passphr))
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "python, loops"
}
|
Making Liquid CO2
I recently saw a video on making liquid $\ce{CO2}$: <
Basically we seal some dry ice in a container. As the dry ice sublimates the pressure inside the container increases and so at about 5 atm we reach the triple point of $\ce{CO2}$, at which point the solid $\ce{CO2}$ melts instead of sublimating.
At some point in the video, the teacher cautions that the same experiment should not be done with a Gatorade bottle (similar to a water bottle). However, I'm not sure why this is the case.
Certainly the usual "dry ice bomb", which also has warm water poured into the sealed bottle, is not a good idea. In the present scenario, once all of the solid $\ce{CO2}$ had melted and the liquid $\ce{CO2}$ then goes into the gas phase, the increase in pressure could lead to an explosion: isn't this the same principle as in the case of the "dry ice bomb"? Is the warning because a Gatorade bottle (or water bottle, etc.) cannot withstand 5 atm of pressure?
|
I think these three links nicely summarize what can potentially go wrong when a plastic bottle explodes.
As for your question about how much pressure the Gatorade container can hold, that's a little trickier to figure out. It looks like the Mythbusters found that soda bottles can hold up to 150psi (~11 atm), but gatorade and water bottles aren't designed to hold carbonation, so I'm guessing they'd be closer to the 60psi (~4 atm) that they found for water coolers.
I think ultimately the answer is that the teacher is playing on the safe side: sure, you might be able to hold 10 atm of pressure in a soda bottle at home, and get some cool-looking CO2 out of it, but seeing as you could lose an eye if your bottle was even slightly damaged (and seeing that this has happened before!), is it something you'd want to let high schoolers do on their own?
|
stackexchange-chemistry
|
{
"answer_score": 3,
"question_score": 4,
"tags": "safety, phase"
}
|
string.matches(".*") returns false
In my program, I have a string (obtained from an external library) which doesn't match any regular expression.
String content = // extract text from PDF
assertTrue(content.matches(".*")); // fails
assertTrue(content.contains("S P E C I A L")); // passes
assertTrue(content.matches("S P E C I A L")); // fails
Any idea what might be wrong? When I print `content` to stdout, it looks ok.
Here is the code for extracting text from the PDF (I am using iText 5.0.1):
PdfReader reader = new PdfReader(source);
PdfTextExtractor extractor = new PdfTextExtractor(reader,
new SimpleTextExtractingPdfContentRenderListener());
return extractor.getTextFromPage(1);
|
By default, the `.` does not match line breaks. So my guess is that your `content` contains a line break.
Also note that `matches` will match the entire string, not just a part of it: it does not do what `contains` does!
Some examples:
String s = "foo\nbar";
System.out.println(s.matches(".*")); // false
System.out.println(s.matches("foo")); // false
System.out.println(s.matches("foo\nbar")); // true
System.out.println(s.matches("(?s).*")); // true
The `(?s)` in the last example will cause the `.` to match line breaks as well. So `(?s).*` will match any string.
|
stackexchange-stackoverflow
|
{
"answer_score": 35,
"question_score": 21,
"tags": "java, regex"
}
|
Resource.axd files - Why so many and why so big?
ASP.NET - I've managed to siginificantly reduce the number of .axd requests a page of mine is making by using the ajax ToolkitScriptManager control.
My question now is, why on earth is there SO MUCH JavaScript in those .axd files? I'm talking approx. ~1MB (un-gzipped) just to use a few Ajax controls on a page!
Is there anyway to make this leaner/smaller?
Is there some special way of configuring things that makes it smaller?
I'm guessing ASP.NET tries to only include the js it needs, so can I turn off anything to make the code less bulky?
|
You could compress the .axd files to make them smaller.
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "asp.net, javascript, ajax, asp.net ajax"
}
|
CanJS models: attr function and nested data
In canJS I can set a model property with `person.attr('name', 'John Doe');`, but sometimes that property contains nested data, so I need to do the following:
var address = person.attr('address');
// Update country
address.country = 'USA';
person.attr('address', address);
Is there a shorter solution for this in canJS?
|
person.attr('address.country', 'USA');
< (See the "Engineered limber" section)
PS: I see the `canjs` for the first time, googled the answer in seconds using "canjs nested objects" request
|
stackexchange-stackoverflow
|
{
"answer_score": 3,
"question_score": 2,
"tags": "javascript, jquery, canjs, canjs map"
}
|
iPhone iPad UIView controller popup centered
My application is for iPad.
I have a UIViewController as the main view of my application. I have an UIView at the bottom as a footer, and inside 3 UIView (subviews).
My 3 subviews in the footer banner load for each a different UIViewController and display the view of this controller into their view.
I would like when I click on a button into one of this subview (button that belongs to my UIViewController, with a 240x162px view), to make the subview disappear and display a centered popup (500x350px) with an animation into my main view.
To show you an example, WeatherBug for iPad has what I want, when you click on a block on top, the little view flip and a zoom effect is done, that display a centered uiview with more content.
Please tell me where I should look for! Thank you,
|
Use the delegate pattern. Assign your "root" view controller as the delegate for your "footer" view controller. When the button is tapped (no clicking on the iPhone), the "footer" view controller will hide the banner, then call a delegate method to handle the tap action; in this case, the "root" view controller then shows your centered popup. When the popup is done, the "root" view controller then tells the "footer" view controller go show the banner again and go back to normal.
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "iphone, animation, uiview, popup, flip"
}
|
How to add metadata for other languages?
I've just added an application to iTunes Connect, which is mainly target the danish market. During adding of the application, I was told to enter the metadata information in english. After I added the application, I was trying to add meta in danish, but the language does not exist.
When a user in the danish App Store visit the App, the metadata must be in danish. Should I just change the metadata in english to danish instead?
|
You cannot add metadata in other languages for App Stores that have the English language as their official language (which is the case with the Danish App Store).
Do what most developers do. Add the Danish text in the English description and if you want add below that the English version.
|
stackexchange-stackoverflow
|
{
"answer_score": 3,
"question_score": 1,
"tags": "ios, app store connect"
}
|
How do I make a through-hole via?
Using a simple PCB with copper on both sides but naturally in between, is it feasible for a hobbyist to make through-hole vias like this:
 and I have a function which has as parameters (lat, lon, radius)
then I want to retrieve data which accept the equation (|lon-longitude|/|lat-latitude|)<= radius
I am using laravel 5.4 like the following:
public function calc($lon, $lat, $radius){
$result = Item::where()->get();
}
Any help how will the where condition be to do this equation!!
|
Try this using the whereRaw
public function calc($lon, $lat, $radius){
$result = Item::whereRaw("abs($lon-longitude)/abs($lat-latitude) <= $radius")->get();
}
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": -1,
"tags": "php, mysql, laravel, eloquent"
}
|
Get html object in controller through ajax
I have a Html object(var table) in my jsp page, and i want to send to controller through ajax to write it in a text file. But once i send an object its giving me null pointer exception
var table =$(tabledata);
$.ajax({
url: "htmlToExel.do",
type : "POST",
data : table,
success: function(){
},
error: function(){
}
});
|
POST send text. You want to send HTML object.
If you want send HTML code, you try:
<div class="table">
<table>
<tr>
<td>test</td>
</tr>
</table>
</div>
<script>
$.ajax({
type: "POST",
url: 'url',
data: {
table: $('div.table').html()
}
}).done(function(result){
console.log('ok');
});
</script>
But if you want to send data from a table, you must first serialize them.
|
stackexchange-stackoverflow
|
{
"answer_score": 3,
"question_score": 0,
"tags": "java, jquery"
}
|
How do I add a "search" button in a text input field?
How do I create a similar “search” element to the one in this site?
!enter image description here
If we view source, he has one textbox followed by a `<span>` tag.
<input type="text" name="q" id="site-search-input" autocomplete="off" value="Search" class="gray" />
<span id="g-search-button"></span>
Where do I get a similar "magnifying glass" image?
|
Put the image into the span, for example using `background-image`, then give it a relative position and move it to the left so it overlaps the right end of the search box, for example:
#g-search-button {
display: inline-block;
width: 16px;
height: 16px;
position: relative;
left: -22px;
top: 3px;
background-color: black; /* Replace with your own image */
}
Working example on JSBin
|
stackexchange-stackoverflow
|
{
"answer_score": 26,
"question_score": 23,
"tags": "html, css, icons"
}
|
Delete all checked items rails
i have array tasks[] with items from form
<%= check_box_tag "tasks[]", task.id %>
I see them in console
Processing by TasksController#destroy as HTML
Parameters: {"utf8"=>"?", "authenticity_token"=>"qo6JqGn0a1Yck1j67taz7kEu/ENBrwLg0xs4HbmAehNq7yMVB3llJWYgZvRNrWKPrZqYJtZIaS89EIBFIyDZTA==", "tasks"=>["7", "8"], "commit"=>"Trash All Checked", "id"=>"delete_all"}
But can't delete, action dont work
def delete_all
Task.where(id: params[:id]).destroy_all
redirect_to action: "index"
end
|
Your IDs are present in `params[:tasks]`, so you have to write something like that:
def delete_all
Task.where(id: params[:tasks]).destroy_all
redirect_to action: "index"
end
Anyway, I'd recommed to change `tasks` to `tasks_ids` in the view and the controller. It's a more meaningful name.
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 0,
"tags": "ruby on rails, arrays, action, checked"
}
|
C++ boost regex date error
I am quite new to boost regex library.The following sample code is used to check if the entered date is following the `YYYY-MM-DD` format.However,there seems to be an error in the regex. It always return's`false`. *
> * I am running the console application on windows.
>
* the regex was taken from here
bool regexValidate(string teststring)
{
boost::regex ex("^(20\\d{2})(\\d{2})(\\d{2})");
if (boost::regex_match(teststring, ex)) {
cout << "true";
return true;
}
else {
return false;
}
}
int main()
{
string teststr = "2016-05-15";
cout << teststr << " is ";
if (regexValidate( teststr)) {
cout << " valid!" << endl;
}
else {
cout << " invalid!" << endl;
}
system("PAUSE");
return 0;
}
|
You're almost there; just add hyphens to your regex:
"^(20\\d{2})-(\\d{2})-(\\d{2})"
BTW, this won't parse dates before 2000 or after 2099. And there's no explicit end-of-string ($) at the end. Something more like:
"^(\\d{4})-(\\d{2})-(\\d{2})$"
...I think should make you good anywhere in recent centuries ;-)
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 1,
"tags": "c++, regex, boost"
}
|
What scripting language has both ec2 library & easy to use ncurses api?
I'm looking to write a cli replacement for elasticfox. Would be nice to use python / ruby / bash or something alike.
This is a side project to make our Ubuntu environment a bit more fun, so as much abstraction as possible - I'm loving it :).
|
If you like Python, there's:
* Several 3rd party EC2 modules:
* A built-in ncurses library: <
* A nice and powerful ncurses alternative called 'urwid': <
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "api, command line interface, amazon ec2"
}
|
Celery Chord Callback error
Suppose i have a celery code like this:
@celery.task()
def A(a):
try:
.......
.......
except Exception,e:
raise
@celery.task()
def B(b):
try:
.......
.......
except Exception,e:
raise
def C(c):
try:
.......
.......
except Exception,e:
raise
def final():
callback = C.s()
header = [A.s(something), B.s(something)]
result = chord(header)(callback)
result.get()
Now when i try to run the task final() i always get an error like `C.s() takes exactly 1 argument (2 given)` because callback is applied with the return value of each task in the header. so how can i fix this so that the task C() runs fine????
|
You can use immutable tasks to make independant tasks and not forward the result.
def final():
# C needs an argument, note the use of the shortcut `si`
callback = C.si(something)
header = [A.s(something), B.s(something)]
result = chord(header)(callback)
result.get()
As a completely side-note, the use of `except Exception as e` is preferred if you're running Python 2.6+ or required for Python 3.x (see here for more details).
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 1,
"tags": "python, celery"
}
|
Is there a bracket or brace that I can use to hold my two monitors together?
I have two identical monitors. When I set them side by side, the edges don't quite sit perpindicular to one another. This is most likely due to slight structural differences in the stands that occurred as they cooled after being released from their casts.
I can hold them together with my hands just how I want them to stay, but, of course, they move back into their natural position when I release them.
It seems there would be a sort of plastic brace that I can attach to both monitors to hold them perfectly together. What would such a thing be call if it exists? If there is nothing like it, what ideas do you all have as far as making such a thing?
I put this in superuser because I couldn't find a more appropriate section.
|
Your question belongs here... don't worry about that.
Have you tried using something **simple** , like **tape**? (Duct tape may work best.)
Alternatively, you may want to search monitor mounts and see if anything there is exactly what you’re looking for.
|
stackexchange-superuser
|
{
"answer_score": 0,
"question_score": 4,
"tags": "display"
}
|
Class with same code and send data
I have this C# class to send the data from _DriveInfo_ Class to my window form:
using System;
public class FileSystemInfo
{
public string CheckTotalFreeSpace()
{
System.IO.DriveInfo DInfo = new System.IO.DriveInfo(@"C:\");
return DInfo.TotalFreeSpace.ToString();
}
public string CheckVolumeLabel()
{
System.IO.DriveInfo DInfo = new System.IO.DriveInfo(@"C:\");
return DInfo.VolumeLabel.ToString();
}
}
I want to send huge data from one class (see my example) into my form class (maybe labels or ListBox Control), by using a a good way to solve this issue. Also I don't want to put this line of code into separate c# class method:
System.IO.DriveInfo DInfo
The basic issue for me is: deal and show many info about my computer so I need to put all this info into one structure or something else.
|
You may use `Lazy` class:
using System.IO;
public class FileSystemInfo
{
private readonly Lazy<DriveInfo> dInfo =
new Lazy<DriveInfo>(() => new DriveInfo(@"C:\"));
public string CheckTotalFreeSpace()
{
return dInfo.Value.TotalFreeSpace.ToString();
}
public string CheckVolumeLabel()
{
return dInfo.Value.VolumeLabel.ToString();
}
}
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": -4,
"tags": "c#, winforms"
}
|
Positioning a "list" of images
I'm making an sponsors activity containing 3-6 ImageView's which are suppose to listed vertically on top of each other. And of course be scrollable if they don't fit the screen.
Below I try to illustrate how it should look like.
image1
image2
...
imageX
As of now I'm simply positioning the images with absolutly positioning. What would be a more dynamic way taking different screen sizes into account?
|
As suggested in the comments:
A simple ListView with a custom layout for the entries should do the trick.
For everyone who doesn't know how this would works: Here is a post about an app with a listview which contains country names and there flags as pictures.
The important part is the listitem.xml file which later gets inflated in the getView(...) method of the custom ArrayAdapter.
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 1,
"tags": "android, android layout"
}
|
If a node module includes its own package-lock.json, is that ignored/overridden by the parent package-lock.json?
I have a repository that has a bunch of peer dev dependencies (this repo is a standalone eslint config, like airbnb).
If I used this in a another project as a node module (importing it through github, not retrieving it through npm), will the `package-lock.json` file that is generated in this module be used in the callers project?
|
No. Per the documentation, `package-lock.json` files "will be ignored if found in any place other than the toplevel package."
If you want lock-file behavior in a dependency, use a shrinkwrap file instead.
Assuming you are still installing with the `npm` client, the fact that you are retrieving the package from somewhere other than the npm registry doesn't affect this behavior.
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 1,
"tags": "npm, node modules, eslint, npm install"
}
|
Differing responses to jquery.get in firefox vs chrome
I'm trying to pull JSON data from another source by using the jquery.get method. Unfortunaltey, Firfox 4 and Chrome are giving me different responses. In Firefox I get a string which needs to be parsed, in chrome, I get parsed JSON. Why the difference and how do I avoid it?
//works in Firefox
$.get(url, query, function(resp){
var data = $.parseJSON(resp)
var hits = data.hits.hits
}
//works in Chrome
$.get(url, query, function(resp){
var hits = resp.hits.hits
}
|
It would be better to be explicit: tell jQuery that you're expecting JSON to be returned. This should ensure consistent behaviour.
$.get(url, query, function(resp){
var hits = resp.hits.hits
}, 'json');
|
stackexchange-stackoverflow
|
{
"answer_score": 6,
"question_score": 2,
"tags": "jquery, ajax"
}
|
How to get store by reference in ExtJS MVC?
In ExtJS MVC controller we have `stores` property which is array of Stores.
ExtJS automatically generates getter functions for every store (`this.getUsersStore` for `Users` store etc.)
But what should we do if our store is on 2nd level of folders hierarchy and has name of `shop.Users`?
Is there any auto getters for such stores?
|
That get's handled. In your example you get a getter named `getShopUsersStore()`
The getter creater splits for each dot and concat each of these strings capitalized.
|
stackexchange-stackoverflow
|
{
"answer_score": 7,
"question_score": 4,
"tags": "model view controller, extjs"
}
|
Условный оператор if в цикле while
Как в данном коде сделать так, чтобы при вводе с клавиатуры `0` данное значение просто пропускалось и цикл повторялся. Вот условие задачи:
> Напишите программу для самоконтроля навыков устного счёта: пользователь вводит 6 целых чисел, после чего программа должна вывести их произведение. Чтобы перемножать числа было не слишком легко, нули не учитывайте. Гарантируется, что не все введённые числа — нули.
number = int(input('Введите число\n'))
perem = 0
final = 1
while True:
if number != 0:
perem += 1
final *= number
number = int(input('\n'))
else:
number = int(input('\n'))
if perem == 6:
print(final)
Пытался это сделать через `else`, но выполнения кода всё равно прекращается.
|
А вы уверены, что через while надо делать? Обычно цикл while используется когда неизвестно количество итераций цикла, а тут по условию строго сказано, что цикл должен выполняться 6 раз. Приведу код при помощи цикла for, на мой взгляд так проще.
final = 1
for i in range(6):
num = int(input())
if num is not 0:
final *= num
print(final)
|
stackexchange-ru_stackoverflow
|
{
"answer_score": 2,
"question_score": 0,
"tags": "python"
}
|
Is there a specific term for an accessor method that returns a boolean value?
I seem to recall that there is a specific term for an accessor method that returns a Boolean value but it escapes me. For example: typical methods such as:
class Example {
bool isDirty();
bool hasChildren();
bool isValid(SomeType obj);
};
I will also settle for such a term as applied to a non-member functions.
|
A function from some type `T` to `Boolean` is usually called a _predicate_ , and if you want to make clear that it is a method of an object, i.e. that it takes the implicit `this` argument in addition to its other arguments, then you could call it a _predicate method_. If it takes no other arguments except the implicit `this` argument, then you can call it a _predicate property_.
See for example `Predicate<T>` in .NET and e.g. `javax.sql.rowset.Predicate` or `com.google.common.base.Predicate` in Java.
|
stackexchange-softwareengineering
|
{
"answer_score": 11,
"question_score": 5,
"tags": "object oriented, terminology"
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.