qid
int64 1
74.7M
| question
stringlengths 0
58.3k
| date
stringlengths 10
10
| metadata
list | response_j
stringlengths 2
48.3k
| response_k
stringlengths 2
40.5k
|
---|---|---|---|---|---|
11,941,257 |
Last days as a result of some customer complains and discussion with our marketing guys I've got a request to change the default behavior of the configurable products options. They asked me to remove the + $xx.xx from the options drop-down as it is confusing the customers/visitors and just leave the available options without displaying the price change. Fair enough from their point of view, but it is a bit tricky from developers point of view I think. The site is running Magento CE 1.6.2, and the file which we need to override/change is /public\_html/js/varien/configurable.js. We need to change the getOptionLabel function in it so that it does not display the price change.
So my question is: what is the right Magento way to change this file and not touch the core javascript file?
Thanks in advance.
|
2012/08/13
|
[
"https://Stackoverflow.com/questions/11941257",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1177078/"
] |
Just to add to @anton-s's absolutely correct answer, you can also do "full" class rewrites:
```
// Create the original class
var ClassA = Class.create();
ClassA.prototype = {
initialize: function(config) {
this.config = config;
},
test: function(msg) {
console.log('Hi from class A with message ' + msg);
}
};
// Create new class extending the original class
var ClassB = Class.create(ClassA, {
// $super is a reference to the original method
test: function($super, msg) {
console.log('Hi from class B');
console.log('this.config is accessible in class B: ' + this.config);
$super(msg + ' ...')
}
});
// To make the extend an override, you can do this:
ClassA = ClassB;
// ClassA now is ClassB overriding the original ClassA
var a = new ClassA('some config data');
a.test('Call A 1');
```
Since all this only works on prototype classes, not on already instantiated objects, I'll also throw in this hack, which is pretty much what wrap() does, too:
```
// Overriding a method of an already instantiated object
// There are many ways to do this more elegantly thanks to the amazing JS scoping magic
a.origTest = a.test;
a.test = function(msg) {
console.log('Hi from the patched method');
this.origTest(msg);
}
a.test('Call A 2');
```
Keep in mind though that the `wrap()` method is nicer, and can also be used on on class definitions or on concrete instances.
```
// Wrap method of concrete instance
spConfig.getOptionLabel = spConfig.getOptionLabel.wrap(function(parentMethod, option, price) {
return parentMethod(option, price);
});
// Wrap method of class declaration
Product.Config.prototype.getOptionLabel = Product.Config.prototype.getOptionLabel.wrap(function(parentMethod, option, price) {
return parentMethod(option, price);
});
```
|
**How to override \js\varien\configurable.js in Magento 1.9 EE and add new data attribute**
Create file \js\jsoverride\configurable.js:
```
Product.Config.prototype.reloadOptionLabels = Product.Config.prototype.reloadOptionLabels.wrap(function (parentMethod, element) {
var selectedPrice;
if (element.options[element.selectedIndex].config && !this.config.stablePrices) {
selectedPrice = parseFloat(element.options[element.selectedIndex].config.price);
} else {
selectedPrice = 0;
}
for (var i = 0; i < element.options.length; i++) {
if (element.options[i].config) {
element.options[i].text = this.getOptionLabel(element.options[i].config, element.options[i].config.price - selectedPrice);
element.options[i].setAttribute('data-in-stock', element.options[i].config.in_stock);
}
}
});
```
Create or use file: \app\design\frontend\enterprise\YOUR\_THEME\layout\local.xml and add next rows:
```
<?xml version="1.0"?>
<layout version="0.1.0">
<catalog_product_view>
<reference name="head">
<action method="addJs"><script>jsoverride/configurable.js</script></action>
</reference>
</catalog_product_view>
</layout>
```
Note, filling data to element.options[i].config.in\_stock in file
>
> app\design\frontend\enterprise\YOUR\_THEME\template\catalog\product\view\type\options\configurable.phtml
>
>
>
with next row
```
var spConfig = new Product.Config(UPDATED JSON WITH NEW ATTRIBUTE);
```
|
430,442 |
Suppose I have a random variable which I suspect is the product of a lognormally distributed random variable $X$ and an independent uniformly distributed variable $U(0, 1)$. (The variables are the total incomes of workers in a calendar year who started on a random day in that year. The logic is that workers' annual salary is lognormal but they start on a random day of the year)
I'm interested in estimating the parameters `mu` and `sigma` for the lognormal distribution.
```r
x <- runif(10e3) * rlnorm(10e3, 9, 1)
```
If we assume $X \sim U(0, 1) \times \mathrm{LogNormal}(\mu, \sigma)$ then my understanding is
$$\log(X) \sim -\mathrm{Exp}(1) + N(\mu, \sigma)$$
and that this is an exponentially-modified Gaussian distribution. However, when I estimate the parameters using `fitdistr`, it seems to systematically underestimate `mu` or fail to estimate for some other reason (for example trying to estimate `beta` beyond the bounds).
```r
set.seed(810)
library(MASS)
library(brms)
#> Loading required package: Rcpp
#> Registered S3 method overwritten by 'xts':
#> method from
#> as.zoo.xts zoo
#> Loading 'brms' package (version 2.10.0). Useful instructions
#> can be found by typing help('brms'). A more detailed introduction
#> to the package is available through vignette('brms_overview').
x <- runif(10e3) * rlnorm(10e3, 10, 1)
logx <- log(x)
fitdistr(logx,
dexgaussian,
start = list(mu = 7,
sigma = 1,
beta = 1),
lower = c(5, 0.9, 1/10e3),
upper = c(15, 1.1, Inf))
#> mu sigma beta
#> 9.00146956 1.10000000 0.68489168
#> (0.01295792) (0.01039890) (0.02761565)
```
Created on 2019-10-08 by the [reprex package](https://reprex.tidyverse.org) (v0.3.0)
How should I best try to estimate these parameters?
|
2019/10/08
|
[
"https://stats.stackexchange.com/questions/430442",
"https://stats.stackexchange.com",
"https://stats.stackexchange.com/users/21701/"
] |
$\log X$ is not ExpGaussian, however $-\log X$ is; it being the sum of an $\text{Exp}(1)$ and a $N(-\mu,\sigma^2)$.
This may be a part of your problem! If you try the estimation on $-\log X$ and then negate the estimate of $\mu$ you might get a better outcome.
|
I will assume your two random variables are independent (you didn't specify.) Let the $Z=XY$ where $X,Y$ are independent, with $X \sim \mathcal{logNorm}(\mu,\sigma^2)$ and $Y\sim \mathcal{Unif}(0,1)$. We will use mgf's (moment generating functions.) We can find that the density function of $\log Y$ is $f\_{\log Y}(z)=e^z,\quad z\le 0$, and its mgf is
$$
M\_{\log Y}(t)=\frac1{t+1},\quad t>-1.
$$
So the mgf of the sum $\log Z=\log X + \log Y$ is
$$
M\_{\log X}(t)=\frac{e^{\mu t+\frac12 \sigma^2 t^2}}{t+1}\quad\text{for $t>-1$.}
$$
This can be used multiple ways for estimation, you can use differentiation to obtain moments from the mgf, which gives equations for the method of moments, or you could calculate an *empirical mgf* from the data, and estimate by fitting that to the theoretical mgf above. Or you could try to invert the mgf to find the density, thus likelihood function, exactly. Or invert it approximately by the [saddlepoint approximation](https://stats.stackexchange.com/questions/191492/how-does-saddlepoint-approximation-work/191781#191781).
I will come back and post some details, if there isn't any better answer first ...
|
17,179,163 |
I have this code which I use in order to upload a CSV file.
```
$handle = fopen($_FILES['filename']['tmp_name'], "r");
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
$import="INSERT into matching(date, time, location, epos_id, rbpos_id, type_of_payment, basket_information, user_id, points) values('$data[0]', '$data[1]', '$data[2]', '$data[3]', '$data[4]', '$data[5]', '$data[6]', '$data[7]', '$data[8]')";
mysql_query($import) or die(mysql_error());
$query = 'SELECT * FROM users WHERE ID="'.$data[7].'"';
$result = mysql_query($query) or die(mysql_error());
while($row = mysql_fetch_array($result)){
$id_user = $row['user_id'];
$phone = $row['phone'];
echo $name = $row['first_name'];
}
mysql_query($import) or die(mysql_error());
}
fclose($handle);
```
Now, I need to iterate each data on the column `$data[7]`, so I echo the first name of each person who has that user\_id, but apparently it's wrong because nothing is printed.
PS. please note that I'm the only one uploading the data, I'm not concerned about security stuff or whatever.
|
2013/06/18
|
[
"https://Stackoverflow.com/questions/17179163",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2379666/"
] |
You probably set the option [`virtualedit`](http://vimdoc.sourceforge.net/htmldoc/options.html#%27virtualedit%27) somewhere. To turn it off for the instance you can use `:set virtualedit=`. Or to permanently disable it remove it from your vimrc.
|
The feature is call virtual edit. You can disable this with:
```
:set virtualedit=
```
See `:h 've'` for more information.
|
17,033,566 |
I'm working on a small bug in our app which I'll attempt to simplify here.
I have this company model (the actual model has many more associations, but this here displays the problem):
```
class Company < ActiveRecord::Base
has_many :contacts
def self.search(query, page=1)
companies = includes(:contacts).order("companies.name ASC")
if query.present?
companies = companies.where(%(
companies.name ILIKE :q,
OR contacts.name ILIKE :q
), q: "%#{query}%")
end
companies.paginate(page: page)
end
end
```
Now this mostly is working great. The only problem is when a company has 2 or more contacts, and the user searches based on one of the contact names. The company is found correctly, and our auto-complete UI displays the company. HOWEVER, when the user selects the company from the auto-complete they are supposed to be able to select a contact from a dropdown list, but the dropdown ends up only containing the one contact that they had filtered down to. The company should be filtered based on their search criteria, but that dropdown should still have all of the contacts for the company for the user to choose from.
I know *why* it's doing this, it's because rails is doing it's auto-load of all of the associations the moment that query runs so that it can both get all association properties *and* include all conditions at the same time.
It's running a `select {every_attribute_from_every_included_table} left outer join {all_included_tables}` type of query, but what I WANT it to do is this:
```
select companies.* from companies
left outer join contacts <and other included tables> on <join criteria>
where <filter criteria>
```
To filter the companies followed by a:
```
select contacts.* from contacts
where company_id IN (<company_ids from previous query>)
```
Which is how it would include entries normally if the `include` tables were not also involved in the `where` clause.
Rails is doing too much magic here and I want it to go back to it's normal magic instead of it's special magic! How can I do that? Or what's a better way to accomplish what I'm trying to accomplish (still filter based on contact name, but don't stop those other contacts from being included when I call `company.contacts`).
|
2013/06/10
|
[
"https://Stackoverflow.com/questions/17033566",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/649006/"
] |
Okay, let's do the query as you want
```
select companies.* from companies
left outer join contacts <and other included tables> on <join criteria>
where <filter criteria>
```
Let's manually override the `.joins(...)`
```
Company.includes(:contacts).
joins("left outer join contacts c on c.company_id = companies.id").
where(...)
```
This will leave the `:contacts` relation untouched, joining instead on a separate 'alias' of the same `contacts` table.
|
I see that you need two queries:
* one to select the company (or companies)
* one to select the contacts of a (selected) company
Using Rails magic you could select companies by using `joins`:
```
@companies = Company.joins(:contacts).where(...).uniq
```
giving `SELECT DISTINCT "companies".* FROM "companies" INNER JOIN "contacts" ON ... WHERE (...)`
and then get all the contacts of a specific company:
```
company= @companies.first
@contacts = company.contacts
```
|
71,650,269 |
I want to display multiple images at once in one figure (i used a set of 22 images so for the subplot i used 5 rows and 5 columns) , but the problem is they display one by one every time i close the figure, here is how i did it :
```
import cv2
import glob
import matplotlib.pyplot as plt
path="data/*.jpg"
images=[cv2.imread(image) for image in glob.glob(path)]
fig=plt.figure()
for i in range(len(images)):
plt.subplot(5,5,i+1)
plt.imshow(images[i])
plt.show()
```
|
2022/03/28
|
[
"https://Stackoverflow.com/questions/71650269",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18609891/"
] |
I tried disabling all the browser extensions. Before narrowing it down to find that the Apollo Client DevTools extension was the culprit.
|
I had the same error resolved disabling "Keepa - Amazon Price Tracker" extension.
|
62,465,428 |
I'm a Python newbie. What I wanted to do was calculate the differences between float numbers. Differences must be between the number after and the number before. So first difference must be between 2nd number and last number. Here's my code:
```
x = [811.91, 796.04, 796.14, 796.50, 796.81]
i = 0
for i in x:
difference = x[i+1] - x[i-1]
print(difference)
```
And I get "TypeError: list indices must be integers or slices, not float".
|
2020/06/19
|
[
"https://Stackoverflow.com/questions/62465428",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12715822/"
] |
You can do something like this:
```
buttons = []
for i in range(11):
buttons.append( tk.Button(root, text = ('out'+str(i)), bg=random.choice(color), command=lambda:code(i))
if b[0]['bg'] == 'red':
pin = pin[:-1]
```
Now `buttons` is a list with button i at index i. You just have to rewrite your command `code(out1)` for example to take `i` as input instead of `out1`.
|
See classes in python !
class button(self):
and here you put your code about buttons
This is really helpful because you can put more arguments than just self, and then call button(arguments) to create a new button !
|
46,355,137 |
I have a script that loads songs and each song's data from a db (using peewee) and then downloads each song.
```
for music in musiclibrary.select().where(musiclibrary.downloaded == 0):
if not os.path.exists("mp3s/" + music.category + "/" + music.artist_name):
os.makedirs("mp3s/" + music.category + "/" + music.artist_name)
if not os.path.exists("mp3s/" + music.category + "/" + music.artist_name +
"/" + music.album_name):
os.makedirs("mp3s/" + music.category + "/" + music.artist_name +
"/" + music.album_name)
sub_dir = ("mp3s/" + music.category + "/" + music.artist_name +
"/" + music.album_name)
song = requests.get(music.song_mp3_url, timeout=(3,9))
if song.status_code == 200:
try:
with open(os.path.join(sub_dir, song_name), "wb") as f:
for chunk in song.iter_content(chunk_size=1024):
if chunk:
f.write(chunk)
except Exception as e:
print "exp is", e
return
```
I'm getting
>
> `exp is [Errno 2] No such file or directory: u'mp3s/letmiat/\u0627\u0644\u0633\u064a\u062f \u062d\u0633\u064a\u0646 \u0627\u0644\u0645\u0627\u0644\u0643\u064a/\u0644\u0637\u0645\u064a\u0627\u062a \u0645\u062a\u0641\u0631\u0642\u0629 \\\u06357\u0644\u0645\u0627\u0644\u0643\u064a/\u0644\u0637\u0645\u064a7\u0644\u0645\u0627\u0644\u0643\u064a/\u0644\u0637\u0645\u064a\u0627\u062a.mp3`
>
>
>
This error occurs even though the directory already exists. The song name, album name, and artist name are mostly Arabic. I'm running this under Windows.
EDIT
I have a script (run.py) that calls this script (downloader.py) after some other script (written in scrapy) finnishes. run.py is in the project root folder, and downloader.py is one level under it. Just to be sure, I've put the mp3s folder in both places. Here is how it looks
```
-project
--run.py
--mp3s
---downloader.py
---mp3s
```
|
2017/09/22
|
[
"https://Stackoverflow.com/questions/46355137",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5833932/"
] |
Couple of problems with your code:
* you're doing `listToSumbit.push(newEntry)`, which should be `listToSubmit.push(newEntry)`
* starting with `i = "0"` is a bit weird and could cause issues - try `i = 0` instead.
With the typo, I strongly recommend using a good linter in your IDE - eslint is great. It'll help catch these bugs straight off.
|
To get the correct index, you can loop all of the checkboxes:
```js
listToSubmit = []
elements = document.querySelectorAll("input[name=mycheckboxgroup]")
for (i = 0; i < elements.length; i++)
if (elements[i].checked)
listToSubmit.push( { 'ID-Number' : i + 1 + '', 'ID-Data' : elements[i].value } )
console.log(JSON.stringify(listToSubmit))
```
```html
<input type='checkbox' name='mycheckboxgroup' value='ABCD1234' checked \>
<input type='checkbox' name='mycheckboxgroup' value='DEFG5678' checked \>
<input type='checkbox' name='mycheckboxgroup' value='XYZ90' \>
```
|
74,589,883 |
I have array of array double but it won't add element after using `.plusElement`or `.plus`. code below inside from view model that returns it.data which is a list of object
### Code
```
var ageEntry : Int
val dataObject : Array<Array<Double>> = arrayOf()
for (dataWeight in it.data!!){
ageEntry = dataWeight.date.toLocalDate().getAgeInMonth().toString().toInt()
dataObject.plusElement(arrayOf(ageEntry.toDouble(), dataWeight.weight.toDouble()))
Log.d("DATA_SERIES_BARU", "setupViewInstance: ${dataObject.contentToString()}")
}
```
### Log
[](https://i.stack.imgur.com/CP1n2.png)
|
2022/11/27
|
[
"https://Stackoverflow.com/questions/74589883",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7354428/"
] |
The OP's proposed answer is subpar to say the least. If you need a mutable data structure, use a list not an array. I suggest something like this:
```
it.data?.fold(ArrayList<Array<Double>>()) { list, dataWeight ->
val ageEntry = dataWeight.date.toLocalDate().getAgeInMonth().toString().toInt()
list.add(arrayOf(ageEntry.toDouble(), dataWeight.weight.toDouble()))
list
}
```
If you absolutely need an array at the end, you can easily convert it using `toTypedArray()`.
|
**Im adding this function to add array Element**
```
fun <T> appendArray(arr: Array<T>, element: T): Array<T?> {
val array = arr.copyOf(arr.size + 1)
array[arr.size] = element
return array
}
```
**then you can call it**
```
appendArray(copyDataObject, arrayOf(ageEntry,arrayOf(arrayOf(2.0, 3.0)))
```
|
14,912,373 |
I want this button's image use the image stored in database (image path)...
```
private void button15_Click(object sender, EventArgs e)
{
string a = button11.Text;
string connString = "Server=Localhost;Database=test;Uid=*****;password=*****;";
MySqlConnection conn = new MySqlConnection(connString);
MySqlCommand command = conn.CreateCommand();
command.CommandText = ("Select link from testtable where ID=" + a);
try
{
conn.Open();
}
catch (Exception ex)
{
//button11.Image = ex.ToString();
}
MySqlDataReader reader = command.ExecuteReader();
while (reader.Read())
{
button11.Image = reader["path"].ToString();
}
}
```
I think the error lies in `"reader["path"].ToString();"` but I don't know what syntax to use.
|
2013/02/16
|
[
"https://Stackoverflow.com/questions/14912373",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1952807/"
] |
The CUDA Toolkit [Release Notes](http://docs.nvidia.com/cuda/cuda-toolkit-release-notes/index.html) list the supported platforms and compilers.
|
Well I think it's the other way around. The thing is, there is a driver called `nvcc`. it generates device code and host code and sends the host code to a compiler. It should be a C compiler and it should be in the executable path. (EDIT: and it should be gcc on Linux and cl on Windows and I think I should ignore mac as the release note did(?))
nvcc Compiler Info reads:
>
> A general purpose C compiler is needed by nvcc in the following
> situations:
>
>
> 1. During non-CUDA phases (except the run phase), because these phases will be forwarded by nvcc to this compiler
> 2. During CUDA phases, for several preprocessing stages (see also 0). On Linux platforms, the compiler is assumed to be ‘gcc’, or ‘g++’ for linking. On Windows platforms, the compiler is assumed to be ‘cl’. The
> compiler executables are expected to be in the current executable
> search path, unless option -compiler-bin-dir is specified, in which
> case the value of this option must be the name of the directory in
> which these compiler executables reside.
>
>
>
And please don't talk like that about compilers. Your code is in a way that works better with Dev-C++. What is generated is an assembly code. I don't say that they don't make any difference, but maybe 4 to 5%, not 100%.
And absolutely definitely don't blame the compiler for your slow program. It is definitely because of inefficient memory access and incorrect use of different types of memory.
|
34,204,968 |
I have checked all the posts on the subject, and added a callback in the iterator.
However, it seems it does not work.
```js
async.forEachOf(scoreTree.nodes, function (node,key, callback){
if(!node.composition.weights){
mongooseCall.etc.find({}
}
,function (err, data) {
//some synchronous code
//use data to update node...
callback(null);
});
}
},function (err) {
lastCall(err, scoreTree, function () {scoreTree.save();});
});
```
Thank you for your help!
Marouane.
|
2015/12/10
|
[
"https://Stackoverflow.com/questions/34204968",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4622967/"
] |
It seems you want to count how many rows in `table1` have a matching value in either column. One easy way is:
```
select t2.*,
(select count(*)
from table1 t1
where t2.id in (t1.day1, t1.day2)
) as occur
from table2 t2;
```
|
In table 1, you must make a foreign key for the table 2. Probably the id of user. With that:
```
Select t2.id, t2.name, Sum(t1.day)
from table1 t1
innerjoin table2 t2
on t1.id = t2.id
```
|
34,204,968 |
I have checked all the posts on the subject, and added a callback in the iterator.
However, it seems it does not work.
```js
async.forEachOf(scoreTree.nodes, function (node,key, callback){
if(!node.composition.weights){
mongooseCall.etc.find({}
}
,function (err, data) {
//some synchronous code
//use data to update node...
callback(null);
});
}
},function (err) {
lastCall(err, scoreTree, function () {scoreTree.save();});
});
```
Thank you for your help!
Marouane.
|
2015/12/10
|
[
"https://Stackoverflow.com/questions/34204968",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4622967/"
] |
It seems you want to count how many rows in `table1` have a matching value in either column. One easy way is:
```
select t2.*,
(select count(*)
from table1 t1
where t2.id in (t1.day1, t1.day2)
) as occur
from table2 t2;
```
|
Select id and name from table2 and get the amount of occurrences in table1 in a subquery:
```
select
id,
name,
(
select sum
(
case when t1.day1 = t2.id then 1 else 0 end +
case when t1.day2 = t2.id then 1 else 0 end
)
from table1 t1
where t2.id in (t1.day1, t1.day2)
) as occur
from table2 t2
```
|
34,204,968 |
I have checked all the posts on the subject, and added a callback in the iterator.
However, it seems it does not work.
```js
async.forEachOf(scoreTree.nodes, function (node,key, callback){
if(!node.composition.weights){
mongooseCall.etc.find({}
}
,function (err, data) {
//some synchronous code
//use data to update node...
callback(null);
});
}
},function (err) {
lastCall(err, scoreTree, function () {scoreTree.save();});
});
```
Thank you for your help!
Marouane.
|
2015/12/10
|
[
"https://Stackoverflow.com/questions/34204968",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4622967/"
] |
It seems you want to count how many rows in `table1` have a matching value in either column. One easy way is:
```
select t2.*,
(select count(*)
from table1 t1
where t2.id in (t1.day1, t1.day2)
) as occur
from table2 t2;
```
|
Combine `day1` and `day2` column to one, then count.
**Query**
```
select t1.ID, t1.Name, count(t2.[day]) as occur
from table2 t1
left join
(select Day1 as [day] from table1
union all
select Day2 as [day] from table1) t2
on t1.ID = t2.[day]
group by t1.ID, t1.Name;
```
|
23,202,836 |
How can I do something like this in Ruby?
```
if variable = something
do A
do B
do D
elsif variable = something different
do A
do B
do C
do D
else
do A
do C
do D
A = set of loops with if else
B = set of loops with if else
C = set of loops with if else
D = final steps
```
Looking for a way to accomplish something like this in Ruby. I'm sure this question is answered somewhere but I don't know what it would be called. I found some information about a gem that allows you to use goto but I would prefer to learn the correct way to do this (also it seems that this might be a joke). I'd prefer to write the code out myself but I can put my actual code up if that helps answer my question.
If someone could just point me in the right direction.
Also if goto isn't a joke why is it not okay to use?
|
2014/04/21
|
[
"https://Stackoverflow.com/questions/23202836",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3525873/"
] |
Instead of goto just create functions for A, B and so on and use them
for example:
```
def A
# Lot of code
end
```
Now you can `goto` A by just writing `A`.
Also instead of using if/else you can use switch case, so that your code will look like
```
A
case variable
when something
B
D
when something else
B
C
D
else
C
D
end
```
|
This is a classic use for switch case. [Here](https://stackoverflow.com/questions/948135/how-can-i-write-a-switch-statement-in-ruby) is how you do it in ruby. Also, I would make all the do's methods and call them from inside `when`
|
3,630,755 |
Ok so what I want to do is create a background agent that monitors http traffic to/from a certain application and performs actions when there are requests and responses to a certain website. Is there a good way to do this in Cocoa? I'd like to avoid using really low level sniffing and/or requiring root access to do this (admin access is ok).
|
2010/09/02
|
[
"https://Stackoverflow.com/questions/3630755",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/574/"
] |
If the application your trying to monitor supports proxy servers you could write one and use that in your app. That probably is the easiest solution.
If that doesn’t work you could use something like `mach_inject` and `mach_override` to overwrite some socket system calls (`socket` and `write` probably are enough) in the program you’re going to monitor. That’s some kind of *dark art* though, so you’re probably better off using a packet sniffer like `tcpdump` and control that using a pipe.
Admin privileges (which are almost the same as root) are required for all of this, except the proxy solution.
|
Here's [tcpdump](http://www.tcpdump.org/) and it's library libpcap:
<http://www.tcpdump.org/tcpdump_man.html>
and
<http://www.tcpdump.org/pcap3_man.html>
There's a tutorial here:
<http://www.tcpdump.org/pcap.htm>
Like Sven said you'll need admin privileges to do anything spectacular.
|
17,036,623 |
An example of what I'm trying to do is probably best:
```
def repeater(n = 1)
n.times { yield }
end
```
By default, repeater will go through the block given once. However, I want it to go through the block multiple times if given n > 1. For some reason the above code doesn't work.
For instance:
I would expect this to result in `64`, but instead it returns `5`:
```
y = 2
repeater(5) { y *= 2 }
```
Why is this happening? Where am I going wrong? I'm fairly new to `yield`, and don't understand it entirely (clearly).
|
2013/06/11
|
[
"https://Stackoverflow.com/questions/17036623",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2328259/"
] |
The problem is that the return value of `repeater` is the return value of `times`, which will always be `n`, so you should interrogate the resulting value of `y` itself instead:
```
y = 2
repeater(5) { y *= 2 } #=> 5
y #=> 64
```
If you want `repeater` to actually return the final result, you could [`reduce`](http://ruby-doc.org/core-2.0/Enumerable.html#method-i-reduce) over a [Range](http://ruby-doc.org/core-2.0/Range.html):
```
def repeater(n = 1)
(0..n).reduce { yield }
end
y = 2
repeater(5) { y *= 2 } #=> 64
```
|
There is nothing wrong with `yield`. The function returns a result of `n.times { … }` which is obviously equals `5`:
```
> 5.times { }
# => 5
```
You want to accumulate the result of yield and explicitely return it from your function.
|
17,036,623 |
An example of what I'm trying to do is probably best:
```
def repeater(n = 1)
n.times { yield }
end
```
By default, repeater will go through the block given once. However, I want it to go through the block multiple times if given n > 1. For some reason the above code doesn't work.
For instance:
I would expect this to result in `64`, but instead it returns `5`:
```
y = 2
repeater(5) { y *= 2 }
```
Why is this happening? Where am I going wrong? I'm fairly new to `yield`, and don't understand it entirely (clearly).
|
2013/06/11
|
[
"https://Stackoverflow.com/questions/17036623",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2328259/"
] |
The problem is that the return value of `repeater` is the return value of `times`, which will always be `n`, so you should interrogate the resulting value of `y` itself instead:
```
y = 2
repeater(5) { y *= 2 } #=> 5
y #=> 64
```
If you want `repeater` to actually return the final result, you could [`reduce`](http://ruby-doc.org/core-2.0/Enumerable.html#method-i-reduce) over a [Range](http://ruby-doc.org/core-2.0/Range.html):
```
def repeater(n = 1)
(0..n).reduce { yield }
end
y = 2
repeater(5) { y *= 2 } #=> 64
```
|
I managed to solve this using the `times` method as I was attempting to do:
```
def repeater(n = 1)
(n - 1).times { yield }
yield
end
```
The above looks nice, as I wanted, but I was hoping I could do this with `n.times` instead of `(n - 1).times`.
The following is a solution using that, but it doesn't look elegant:
```
def repeater(n = 1)
result = nil
n.times {result = yield}
result
end
```
I'll attempt to find a more elegant solution.
|
270,857 |
on linux server I use [BackupPC](http://backuppc.sourceforge.net/) and I want to do copys for windows clients. What lexic I should use?
i now are using and work good:
\*.pl
```
$Conf{BackupFilesOnly} = {
'C$' => [
'/Testas'
]
};
$Conf{SmbSharePasswd} = '*****';
$Conf{SmbShareUserName} = 'EXAMPLE\\Administrator';
$Conf{XferMethod} = 'smb';
```
I want to do 150 clients copys to folder C:\Documents and Settings\username\My Documents.
\*.pl
```
$Conf{BackupFilesOnly} = {
'C$' => [
'/Documents and Settings/username/My Documents'
]
};
$Conf{SmbSharePasswd} = '*****';
$Conf{SmbShareUserName} = 'EXAMPLE\\Administrator';
$Conf{XferMethod} = 'smb';
```
don't work. why? What lexic I should use?
|
2011/05/18
|
[
"https://serverfault.com/questions/270857",
"https://serverfault.com",
"https://serverfault.com/users/80341/"
] |
Are you already running Nagios?
Check out check\_dirsize or check\_filesize\_dir:
<http://exchange.nagios.org/directory/Plugins/Uncategorized/Operating-Systems/Linux/CheckDirSize/details>
<http://exchange.nagios.org/directory/Plugins/Uncategorized/Operating-Systems/Linux/check_filesize_dir/details>
Both could be easily adapted to run out of cron if you like.
|
I would think that [inotifywait(1)](http://linux.die.net/man/1/inotifywait) from [inotify-tools](http://inotify-tools.sourceforge.net/) would be helpful here.
|
270,857 |
on linux server I use [BackupPC](http://backuppc.sourceforge.net/) and I want to do copys for windows clients. What lexic I should use?
i now are using and work good:
\*.pl
```
$Conf{BackupFilesOnly} = {
'C$' => [
'/Testas'
]
};
$Conf{SmbSharePasswd} = '*****';
$Conf{SmbShareUserName} = 'EXAMPLE\\Administrator';
$Conf{XferMethod} = 'smb';
```
I want to do 150 clients copys to folder C:\Documents and Settings\username\My Documents.
\*.pl
```
$Conf{BackupFilesOnly} = {
'C$' => [
'/Documents and Settings/username/My Documents'
]
};
$Conf{SmbSharePasswd} = '*****';
$Conf{SmbShareUserName} = 'EXAMPLE\\Administrator';
$Conf{XferMethod} = 'smb';
```
don't work. why? What lexic I should use?
|
2011/05/18
|
[
"https://serverfault.com/questions/270857",
"https://serverfault.com",
"https://serverfault.com/users/80341/"
] |
Are you already running Nagios?
Check out check\_dirsize or check\_filesize\_dir:
<http://exchange.nagios.org/directory/Plugins/Uncategorized/Operating-Systems/Linux/CheckDirSize/details>
<http://exchange.nagios.org/directory/Plugins/Uncategorized/Operating-Systems/Linux/check_filesize_dir/details>
Both could be easily adapted to run out of cron if you like.
|
```
#!/bin/bash
DIR=/path/to/dir
SIZE=10000
MAILADDR="[email protected]"
if [ $(du -s $DIR | awk '{print $1}') -gt $SIZE ]; then
echo "$DIR" | mail -s "Directory limit exceeded in $DIR" $MAILADDR
fi
```
SIZE has to be given in Bytes!
|
270,857 |
on linux server I use [BackupPC](http://backuppc.sourceforge.net/) and I want to do copys for windows clients. What lexic I should use?
i now are using and work good:
\*.pl
```
$Conf{BackupFilesOnly} = {
'C$' => [
'/Testas'
]
};
$Conf{SmbSharePasswd} = '*****';
$Conf{SmbShareUserName} = 'EXAMPLE\\Administrator';
$Conf{XferMethod} = 'smb';
```
I want to do 150 clients copys to folder C:\Documents and Settings\username\My Documents.
\*.pl
```
$Conf{BackupFilesOnly} = {
'C$' => [
'/Documents and Settings/username/My Documents'
]
};
$Conf{SmbSharePasswd} = '*****';
$Conf{SmbShareUserName} = 'EXAMPLE\\Administrator';
$Conf{XferMethod} = 'smb';
```
don't work. why? What lexic I should use?
|
2011/05/18
|
[
"https://serverfault.com/questions/270857",
"https://serverfault.com",
"https://serverfault.com/users/80341/"
] |
Are you already running Nagios?
Check out check\_dirsize or check\_filesize\_dir:
<http://exchange.nagios.org/directory/Plugins/Uncategorized/Operating-Systems/Linux/CheckDirSize/details>
<http://exchange.nagios.org/directory/Plugins/Uncategorized/Operating-Systems/Linux/check_filesize_dir/details>
Both could be easily adapted to run out of cron if you like.
|
This answer is based on my specific directory needed but you could easily modify it to suite any volume name or even a multiple volumes. I'm not the best with scripting and adapted some functions I found, it will be good to see responses with improvement. Thanks
Script will check the size of /home and if it is too large then email the user who has the largest directory. Note: any non-human user that has a directory, like a service account, would need to be excluded using an exclude list. Service accounts do not check their email very often. This script assumes that once the top offender clears out all they can and if then the disk is over the limit then the next run will find the next largest disk hog and email them. Suggest running every 15 minutes so you may catch the user while they are still logged in.
```
#!/bin/bash
DISK="/home" # disk to monitor
CURRENT=$(df -h | grep ${DISK} | awk {'print $4'}) # get disk usage from monitored disk
MAX="85%" # max 85% disk usage
DOMAIN="your.com"
# functions #
function max_exceeded() {
# Max Exceeded now find the largest offender
cd $DISK
for i in `ls` ; do du -s $i ; done > /tmp/mail.1
sort -gk 1 /tmp/mail.1 | tail -1 | awk -F " " '{print $2}' > /tmp/mail.offender
OFFENDER=`cat /tmp/mail.offender`
echo $OFFENDER
du -sh $DISK/$OFFENDER > /tmp/mail.over85
mail -s "$HOSTNAME $DISK Alert!" "$OFFENDER@$DOMAIN, admin@$DOMAIN" < /tmp/mail.over85
}
function main() {
# check if current disk usage is greater than or equal to max usage.
if [ ${CURRENT} ]; then
if [ ${CURRENT%?} -ge ${MAX%?} ]; then
# if it is greater than or equal to max usage we call our max_exceeded function and send mail
echo "Max usage (${MAX}) exceeded. The /home disk usage is it at ${CURRENT}. Sending email."
max_exceeded
fi
fi
}
# init #
main
#CLEANUP ON AISLE ONE
rm /tmp/mail.1
rm /tmp/mail.offender
rm /tmp/mail.over85
```
|
270,857 |
on linux server I use [BackupPC](http://backuppc.sourceforge.net/) and I want to do copys for windows clients. What lexic I should use?
i now are using and work good:
\*.pl
```
$Conf{BackupFilesOnly} = {
'C$' => [
'/Testas'
]
};
$Conf{SmbSharePasswd} = '*****';
$Conf{SmbShareUserName} = 'EXAMPLE\\Administrator';
$Conf{XferMethod} = 'smb';
```
I want to do 150 clients copys to folder C:\Documents and Settings\username\My Documents.
\*.pl
```
$Conf{BackupFilesOnly} = {
'C$' => [
'/Documents and Settings/username/My Documents'
]
};
$Conf{SmbSharePasswd} = '*****';
$Conf{SmbShareUserName} = 'EXAMPLE\\Administrator';
$Conf{XferMethod} = 'smb';
```
don't work. why? What lexic I should use?
|
2011/05/18
|
[
"https://serverfault.com/questions/270857",
"https://serverfault.com",
"https://serverfault.com/users/80341/"
] |
```
#!/bin/bash
DIR=/path/to/dir
SIZE=10000
MAILADDR="[email protected]"
if [ $(du -s $DIR | awk '{print $1}') -gt $SIZE ]; then
echo "$DIR" | mail -s "Directory limit exceeded in $DIR" $MAILADDR
fi
```
SIZE has to be given in Bytes!
|
I would think that [inotifywait(1)](http://linux.die.net/man/1/inotifywait) from [inotify-tools](http://inotify-tools.sourceforge.net/) would be helpful here.
|
270,857 |
on linux server I use [BackupPC](http://backuppc.sourceforge.net/) and I want to do copys for windows clients. What lexic I should use?
i now are using and work good:
\*.pl
```
$Conf{BackupFilesOnly} = {
'C$' => [
'/Testas'
]
};
$Conf{SmbSharePasswd} = '*****';
$Conf{SmbShareUserName} = 'EXAMPLE\\Administrator';
$Conf{XferMethod} = 'smb';
```
I want to do 150 clients copys to folder C:\Documents and Settings\username\My Documents.
\*.pl
```
$Conf{BackupFilesOnly} = {
'C$' => [
'/Documents and Settings/username/My Documents'
]
};
$Conf{SmbSharePasswd} = '*****';
$Conf{SmbShareUserName} = 'EXAMPLE\\Administrator';
$Conf{XferMethod} = 'smb';
```
don't work. why? What lexic I should use?
|
2011/05/18
|
[
"https://serverfault.com/questions/270857",
"https://serverfault.com",
"https://serverfault.com/users/80341/"
] |
```
#!/bin/bash
DIR=/path/to/dir
SIZE=10000
MAILADDR="[email protected]"
if [ $(du -s $DIR | awk '{print $1}') -gt $SIZE ]; then
echo "$DIR" | mail -s "Directory limit exceeded in $DIR" $MAILADDR
fi
```
SIZE has to be given in Bytes!
|
This answer is based on my specific directory needed but you could easily modify it to suite any volume name or even a multiple volumes. I'm not the best with scripting and adapted some functions I found, it will be good to see responses with improvement. Thanks
Script will check the size of /home and if it is too large then email the user who has the largest directory. Note: any non-human user that has a directory, like a service account, would need to be excluded using an exclude list. Service accounts do not check their email very often. This script assumes that once the top offender clears out all they can and if then the disk is over the limit then the next run will find the next largest disk hog and email them. Suggest running every 15 minutes so you may catch the user while they are still logged in.
```
#!/bin/bash
DISK="/home" # disk to monitor
CURRENT=$(df -h | grep ${DISK} | awk {'print $4'}) # get disk usage from monitored disk
MAX="85%" # max 85% disk usage
DOMAIN="your.com"
# functions #
function max_exceeded() {
# Max Exceeded now find the largest offender
cd $DISK
for i in `ls` ; do du -s $i ; done > /tmp/mail.1
sort -gk 1 /tmp/mail.1 | tail -1 | awk -F " " '{print $2}' > /tmp/mail.offender
OFFENDER=`cat /tmp/mail.offender`
echo $OFFENDER
du -sh $DISK/$OFFENDER > /tmp/mail.over85
mail -s "$HOSTNAME $DISK Alert!" "$OFFENDER@$DOMAIN, admin@$DOMAIN" < /tmp/mail.over85
}
function main() {
# check if current disk usage is greater than or equal to max usage.
if [ ${CURRENT} ]; then
if [ ${CURRENT%?} -ge ${MAX%?} ]; then
# if it is greater than or equal to max usage we call our max_exceeded function and send mail
echo "Max usage (${MAX}) exceeded. The /home disk usage is it at ${CURRENT}. Sending email."
max_exceeded
fi
fi
}
# init #
main
#CLEANUP ON AISLE ONE
rm /tmp/mail.1
rm /tmp/mail.offender
rm /tmp/mail.over85
```
|
48,061,371 |
here I am trying to validate structure of hive table and CSV file which is stored in s3.
This is schema of CSV file in dataframe.
```
+----+----------------+----+---+-----------+-----------+
|S_No| Variable|Type|Len| Format| Informat|
+----+----------------+----+---+-----------+-----------+
| 1| DATETIME| Num| 8|DATETIME20.|DATETIME20.|
| 2| LOAD_DATETIME| Num| 8|DATETIME20.|DATETIME20.|
| 3| SOURCE_BANK|Char| 1 | null| null|
| 4| EMP_NAME|Char| 50| null| null|
| 5|HEADER_ROW_COUNT| Num| 8| null| null|
| 6| EMP _HOURS| Num| 8| 15.2| 15.1|
+----+----------------+----+---+-----------+-----------+
```
I need to compare it with O/p of
```
import org.apache.spark.sql.hive.HiveContext
val targetTableName = "TableA"
val hc = new HiveContext(sc)
val sqlContext = new org.apache.spark.sql.SQLContext(sc)
val targetRawData = hc.sql("Select datetime,load_datetime,trim(source_bank) as source_bank,trim(emp_name) as emp_name,header_row_count, emp_hours from " + targetTableName)
val schema= targetRawData.schema
```
which is :schema: `org.apache.spark.sql.types.StructType = StructType(StructField(datetime,TimestampType,true), StructField(load_datetime,TimestampType,true), StructField(source_bank,StringType,true), StructField(emp_name,StringType,true), StructField(header_row_count,IntegerType,true), StructField(emp_hours,DoubleType,true))`
|
2018/01/02
|
[
"https://Stackoverflow.com/questions/48061371",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9163827/"
] |
It is been blocked by the PHP Session.
You can't serve to pages that requires access to the same session id.
Although once you close/serve/release the session on the slow page, another page can be served on the same session. On the slow page just call [`Session::save()`](http://api.symfony.com/3.4/Symfony/Component/HttpFoundation/Session/Session.html#method_save) as soon as possible on your controller. This will release the session. Take into consideration that everything you do after saving the session will not be stored in the session.
|
The reason the firewall takes so long is that of **debug is enabled**.
In debug, the listeners are all wrapped with debugging listeners. **All the information in the Firewall is being profiled and logged**.
Try to run the same request with Symfony debug disabled.
|
48,061,371 |
here I am trying to validate structure of hive table and CSV file which is stored in s3.
This is schema of CSV file in dataframe.
```
+----+----------------+----+---+-----------+-----------+
|S_No| Variable|Type|Len| Format| Informat|
+----+----------------+----+---+-----------+-----------+
| 1| DATETIME| Num| 8|DATETIME20.|DATETIME20.|
| 2| LOAD_DATETIME| Num| 8|DATETIME20.|DATETIME20.|
| 3| SOURCE_BANK|Char| 1 | null| null|
| 4| EMP_NAME|Char| 50| null| null|
| 5|HEADER_ROW_COUNT| Num| 8| null| null|
| 6| EMP _HOURS| Num| 8| 15.2| 15.1|
+----+----------------+----+---+-----------+-----------+
```
I need to compare it with O/p of
```
import org.apache.spark.sql.hive.HiveContext
val targetTableName = "TableA"
val hc = new HiveContext(sc)
val sqlContext = new org.apache.spark.sql.SQLContext(sc)
val targetRawData = hc.sql("Select datetime,load_datetime,trim(source_bank) as source_bank,trim(emp_name) as emp_name,header_row_count, emp_hours from " + targetTableName)
val schema= targetRawData.schema
```
which is :schema: `org.apache.spark.sql.types.StructType = StructType(StructField(datetime,TimestampType,true), StructField(load_datetime,TimestampType,true), StructField(source_bank,StringType,true), StructField(emp_name,StringType,true), StructField(header_row_count,IntegerType,true), StructField(emp_hours,DoubleType,true))`
|
2018/01/02
|
[
"https://Stackoverflow.com/questions/48061371",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9163827/"
] |
It is been blocked by the PHP Session.
You can't serve to pages that requires access to the same session id.
Although once you close/serve/release the session on the slow page, another page can be served on the same session. On the slow page just call [`Session::save()`](http://api.symfony.com/3.4/Symfony/Component/HttpFoundation/Session/Session.html#method_save) as soon as possible on your controller. This will release the session. Take into consideration that everything you do after saving the session will not be stored in the session.
|
We had a similar problem. When sending a couple of consecutive requests to the server in a short period, the server became very slow. I enabled the profiler bar, and a lot of time was spent by the ContextListener
[](https://i.stack.imgur.com/lTCsP.png)
The problem was that file server access on our server is very slow, and session information was stored on the file system, as is the default for symfony.
I configured my app to use the [PdoSessionHandler](https://symfony.com/doc/current/doctrine/pdo_session_storage.html), and the problem was gone.
|
1,252,549 |
I would like to know how to get excel to count a value in a column IF it detects a specific (pre-stated) ID within a row.
Specifically, I have two sheets. In workbook A, a person enters data on a video coding project. They list the ID, date, start time, end time, and a variety of variables they may have seen. For instance, in the "PRIMARY" column, a coder may type P, W, or A.
What I am looking for is a way for someone who has access to a master workbook (let's call it workbook B), where I need a formula which searches workbook A for a unique ID (i.e., is video d509 anywhere in the workbook under the video ID column), and if it is, go over to the column that has the PRIMARY label, and count every instance of a "P" when the video ID is listed as d509, then count every instance of a "W" for the video which corresponds to that ID, and then count every instance of an "A" for the video which corresponds to that ID.
I tried using a vlookup / count if function, but it did not work (see below):
=IF(VLOOKUP(B2,'[Coder1 Template.xlsx]ENTRY'!$B$2:$K$7100,7,FALSE),COUNTIF('[Coder1 Template.xlsx]ENTRY'!$H$2:$H$7100,"P"),0)
I also will need this to eventually use multiple crtieria. For instance, it will need to count ONLY the P for that column for that specific video for partner 1. And then it would have to do the same for partner 2.
Any ideas on the best way to achieve this?
I am unsure how to attach the workbook as a sample but here are some images of what a template with dummy data looks like:
Coder (data entry) workbook:[Entry workbook](https://i.imgur.com/4Tjc0X0.png)
Master (data count) workbook: [Master workbook](https://i.imgur.com/8oz84d4.png)
\*NOTE: Sorry, in the images where I wrote "sum" I meant "count". Essentially I want it to count the number of Ps that correspond to each video ID.
|
2017/09/21
|
[
"https://superuser.com/questions/1252549",
"https://superuser.com",
"https://superuser.com/users/773587/"
] |
Contrary to what I wrote in my comment, it turns out that `COUNTIFS` is available in Excel 2010. You can use it to count the number of rows that has a given id in column B and a "P" in column H. If you enter "d509" in cell B2, the following formula will return 5 (assuming the data shown in your Entry Workbook picture.
```
=COUNTIFS('[Coder1 Template.xlsx]ENTRY'!$B$2:$B$7100,B2,'[Coder1 Template.xlsx]ENTRY'!$H$2:$H$7100,"P")
```
The `COUNTIFS` function counts the number if items that meet all the criteria listed.
|
Check whether you have a COUNTIFS function; if so, this is your best answer. You can specify a range and more than one criterion.
Failing that, you may be able to do this with an array formula.
`=SUM( N( B2='[Coder1 Template.xlsx]ENTRY'!$B$2:$K$7100 ) * N('[Coder1 Template.xlsx]ENTRY'!$H$2:$H$7100 = "P" ) )`
using Ctrl-Shift-Enter to enter the formula so that it shows up with curly brackets `{...}` around it (you do not type these). Array formulas are generally fairly fragile but they can do some remarkable things. Here the N() function gives TRUE -> 1 and FALSE -> 0 and we can multiply parallel tests and sum the cases where both are true across the respective arrays.
|
40,161,718 |
Now I have following problem:
```
C:\Program Files\PostgreSQL\9.6\bin>raster2pgsql -s 4326 -I -C -M "C:\Users\I\Landsat.tif" -F -t 100x100 public.elevation > elev.sql psql -h 134.235.282.611 -p 6432 -d some_database -U username
ACCESS DENIED
```
Can anyone help me?
|
2016/10/20
|
[
"https://Stackoverflow.com/questions/40161718",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
The SGML Standard (ISO 8879:1986/A1:1988, 11.2.4) explicitly recommends to **not use** content models like `(#PCDATA, foo, bar)` (emphasis mine):
>
> NOTE - It is recommended that “`#PCDATA`” be used **only** when data characters are to be permitted anywhere in the content of the element; that is, in a content model where it is the sole token, or **where** `or` **is the only connector used in any model group**.
>
>
>
Despite mentioning `#PCDATA` only as the first token in the group, your `outer` element type still is declared to have *mixed content*, so data characters can occur anywhere: that's why the line break (aka a *"record end"*) after `</BAR>` is recognized as a *data character* instead of just a *separator* on the one hand, but there's no corresponding `#PCDATA` token to absorb it on the other hand, hence the error. (And only the omitted `</FOO>` end-tag circumvented the same error in the line before!)
---
The proper and common approach in this case would be to place the "Document Title" into an actual `title` element—for which one can allow omission of *both* the start- and end-tag:
```
<!ELEMENT outer - - (title, foo, bar) >
<!ELEMENT title o o (#PCDATA) >
```
Now
* your document instance is valid without modification,
* the `outer` content model still reflects the proper order of elements,
* the `outer` element has *element content* (**not** any longer *mixed content*),
* and the "Document Title" text ends up in its own `title` element, as it should.
(The same technique is used in several Standard DTDs, like the "General Document" example in annex E of the Standard.)
|
Whitespace that looks innocuous is in fact significant character data, which results in an error. This is sometimes referred to as "pernicious mixed content". You have already hinted at a solution (allowing `#PCDATA` after the `bar` element):
```
<!ELEMENT outer - - (#PCDATA, foo, bar, #PCDATA) >
```
Another option is to allow `#PCDATA` and elements in any order (this is how mixed content must be declared in XML):
```
<!ELEMENT outer - - (#PCDATA|foo|bar)* >
```
I cannot think of anything else. It is not possible to restrict `#PCDATA` content to certain characters only.
|
72,596,666 |
i am making a house management app i have to upload images of the property alongside other data related to the property so i am using two screens one for the general info about the house and the second one specifically to upload images
**Form screen**
[](https://i.stack.imgur.com/m062a.png)
**Image Upload Screen**
[](https://i.stack.imgur.com/9AmeL.png)
from the upload screen i am returning back a list of images to the form screen
```
// i am waiting for the list in the form screen
images = await Navigator.push(context, MaterialPageRoute(builder: (context) => AddPictures()));
// i am returning the list back from the upload screen
Navigator.pop(context,imageStrings);
```
I am failing to show circular progress indicator for some reason beyond my capacity to know itried all ways i know
this is the rest of the code
```
//outiside the widdget build i have two lists
List<XFile> imagesXFiles = []; //for raw image files from the gallery or camera
List<String> imageStrings = []; //for image links from the firebase storage
body: isLoading == true ? CircularProgressIndicator() : Column(
children: [
Expanded(
//the first grid is a button to let the user access camera or gallery
child: GridView.builder(
gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
crossAxisCount: 3,
crossAxisSpacing: 2.0,
mainAxisSpacing: 2.0
),
itemCount: imagesXFiles.length + 1,
itemBuilder: (BuildContext context, int index) {
return index == 0 ? GestureDetector(
onTap: (){
// a function to pick images and add store them to the list "imagesXFiles"
_showPicker(context);
},
child: Container(
decoration: BoxDecoration(
color: Colors.black12,
borderRadius: BorderRadius.circular(5.0),
),
child: Icon(
Icons.add,
color: Colors.black,
size: 30.0,
),
),
): Container(
child: Image(
image: FileImage(File(imagesXFiles[index-1].path)),
fit: BoxFit.fill
),
);
},
),
),
TextButton(
onPressed: ()async{
// for some reason the circular progress doesn't work i dont understand why
setState(() {
isLoading = true;
});
imageStrings = await uploadImages(imagesXFiles).whenComplete(() {
setState(() {
isLoading = false;
Navigator.pop(context,imageStrings);
});
});
},
child: Text("Upload",style: TextStyle(color: Colors.black,fontSize: 25),)),
],
),
```
here is the upload function that uploads the images to firebase
```
Future<List<String>> uploadImages(List<XFile> imagesXFiles) async {
imagesXFiles.forEach((image) async {
final storageRef = storage.ref().child(Random().nextInt(100).toString());
await storageRef.putFile(File(image.path));
String imageURL = await storageRef.getDownloadURL();
imageStrings.add(imageURL);
firebaseFirestore
.collection("housePictures")
.add({
"imageURL" : imageURL,
});
});
return imageStrings;
}
```
|
2022/06/12
|
[
"https://Stackoverflow.com/questions/72596666",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10796813/"
] |
You could look up the indexes of the `marker` elements in the list, and then take sublists based on those positions:
```py
lst = ["elem1", "elem2", "marker1", "elem3", "marker2", "elem4", "elem5"]
idxs = [i for i, v in enumerate(lst) if type(v) == str and v.startswith('marker')]
separated = [lst[i:j] for i, j in zip([0]+idxs, idxs+[len(lst)]) if i < j]
# [['elem1', 'elem2'], ['marker1', 'elem3'], ['marker2', 'elem4', 'elem5']]
lst = ["marker1", "elem1", "elem2", "marker2", "elem3"]
idxs = [i for i, v in enumerate(lst) if type(v) == str and v.startswith('marker')]
separated = [lst[i:j] for i, j in zip([0]+idxs, idxs+[len(lst)]) if i < j]
# [['marker1', 'elem1', 'elem2'], ['marker2', 'elem3']]
```
Adapted from [this answer](https://stackoverflow.com/a/52591055/9473764).
|
this is how `i` look like `[['elem1', 'elem2'],['marker1'],['elem3'],['marker2'],['elem4', 'elem5'],['marker3'],['elem6', 'elem7']]` but in a generator ofcourse
so we use `zip` and `i` as `generator` to compine every 2 lists together `['elem1', 'elem2'] + ['marker1']`
```py
from itertools import groupby
lst = ["elem1", "elem2", "marker1", "elem3", "marker2", "elem4", "elem5", "marker3", "elem6", "elem7"]
i = (list(g) for _, g in groupby(lst, key=lambda x: x.startswith('marker')))
print([a + b for a, b in zip(i, i)])
```
Edit1
```py
from itertools import groupby, zip_longest
lst = ["marker0", "elem1", "elem2", "marker1", "elem3", "marker2", "elem4", "elem5", "marker3", "elem6", "elem7"]
i = (list(g) for _, g in groupby(lst, key=lambda x: x.startswith('marker')))
print([a + b for a, b in zip_longest(i, i, fillvalue=[])])
```
Edit2
```py
from itertools import groupby, zip_longest
lst = ["elem1", "elem2", "marker1", "elem3", "marker2", "elem4", "elem5", "marker3", "elem6", "elem7"]
i = iter([[]] + [list(g) for _, g in groupby(lst, key=lambda x: x.startswith('marker'))])
print([a + b for a, b in zip_longest(i, i, fillvalue=[])])
```
|
72,596,666 |
i am making a house management app i have to upload images of the property alongside other data related to the property so i am using two screens one for the general info about the house and the second one specifically to upload images
**Form screen**
[](https://i.stack.imgur.com/m062a.png)
**Image Upload Screen**
[](https://i.stack.imgur.com/9AmeL.png)
from the upload screen i am returning back a list of images to the form screen
```
// i am waiting for the list in the form screen
images = await Navigator.push(context, MaterialPageRoute(builder: (context) => AddPictures()));
// i am returning the list back from the upload screen
Navigator.pop(context,imageStrings);
```
I am failing to show circular progress indicator for some reason beyond my capacity to know itried all ways i know
this is the rest of the code
```
//outiside the widdget build i have two lists
List<XFile> imagesXFiles = []; //for raw image files from the gallery or camera
List<String> imageStrings = []; //for image links from the firebase storage
body: isLoading == true ? CircularProgressIndicator() : Column(
children: [
Expanded(
//the first grid is a button to let the user access camera or gallery
child: GridView.builder(
gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
crossAxisCount: 3,
crossAxisSpacing: 2.0,
mainAxisSpacing: 2.0
),
itemCount: imagesXFiles.length + 1,
itemBuilder: (BuildContext context, int index) {
return index == 0 ? GestureDetector(
onTap: (){
// a function to pick images and add store them to the list "imagesXFiles"
_showPicker(context);
},
child: Container(
decoration: BoxDecoration(
color: Colors.black12,
borderRadius: BorderRadius.circular(5.0),
),
child: Icon(
Icons.add,
color: Colors.black,
size: 30.0,
),
),
): Container(
child: Image(
image: FileImage(File(imagesXFiles[index-1].path)),
fit: BoxFit.fill
),
);
},
),
),
TextButton(
onPressed: ()async{
// for some reason the circular progress doesn't work i dont understand why
setState(() {
isLoading = true;
});
imageStrings = await uploadImages(imagesXFiles).whenComplete(() {
setState(() {
isLoading = false;
Navigator.pop(context,imageStrings);
});
});
},
child: Text("Upload",style: TextStyle(color: Colors.black,fontSize: 25),)),
],
),
```
here is the upload function that uploads the images to firebase
```
Future<List<String>> uploadImages(List<XFile> imagesXFiles) async {
imagesXFiles.forEach((image) async {
final storageRef = storage.ref().child(Random().nextInt(100).toString());
await storageRef.putFile(File(image.path));
String imageURL = await storageRef.getDownloadURL();
imageStrings.add(imageURL);
firebaseFirestore
.collection("housePictures")
.add({
"imageURL" : imageURL,
});
});
return imageStrings;
}
```
|
2022/06/12
|
[
"https://Stackoverflow.com/questions/72596666",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10796813/"
] |
Create (and include) a new inner list at the start or at a marker, otherwise append to the current inner list ([Try it online!](https://tio.run/##dY7BCoMwDIbvPkXwooII6gZD2CvsBaSHgBFl2pY2MPf0XdtNdxjLIfxN8v399ZMnJduLNs4xWbZwhT4BX326ormTqdMSUlpoPUQTxHvZ7LM2FeUH@3dbf29/@dMuzsFIJMmoDCyWYZYQc3XRHX28m5IUH5Y0GmQaQmaEzvdNQAC3gEV6BKnYY2FYWUbD9jHzlGfv/7MibLBCrUkO@VaI6KzNLDk//AvnXg "Python 3.8 (pre-release) – Try It Online")):
```
a = None
separated = [a := [x] for x in lst if not a or x.startswith('marker') or a.append(x)]
```
Another ([Try it online!](https://tio.run/##dU5BCoMwELz7ipCLCiKoLZRCv9APhBwWjBiqSUgWal@fGlNTSts9LMPMzuyYB45adSdjvUfh0JELYRlZh9EZ7E3YhlaEiknMCbQBRLHduY7y6mX7d9u8b7/9hx0cQxDPskFbMjkkUpGt13lLd8KABRR9qhkGEgouCB521UrwD34J/BqZSDkQpXG9D2LtECy6u8SxyGO5vAwK1GCMUH2xlD/esIXHL3EbKxUWqWXp/RM "Python 3.8 (pre-release) – Try It Online")):
```
separated = [
a
for a in [None]
for x in lst
if not a or x.startswith('marker') or a.append(x)
for a in [[x]]
]
```
Yet another (untested, can't test now):
```
from more_itertools import split_before
separated = list(split_before(lst, lambda s: s.startswith('marker')))
```
|
this is how `i` look like `[['elem1', 'elem2'],['marker1'],['elem3'],['marker2'],['elem4', 'elem5'],['marker3'],['elem6', 'elem7']]` but in a generator ofcourse
so we use `zip` and `i` as `generator` to compine every 2 lists together `['elem1', 'elem2'] + ['marker1']`
```py
from itertools import groupby
lst = ["elem1", "elem2", "marker1", "elem3", "marker2", "elem4", "elem5", "marker3", "elem6", "elem7"]
i = (list(g) for _, g in groupby(lst, key=lambda x: x.startswith('marker')))
print([a + b for a, b in zip(i, i)])
```
Edit1
```py
from itertools import groupby, zip_longest
lst = ["marker0", "elem1", "elem2", "marker1", "elem3", "marker2", "elem4", "elem5", "marker3", "elem6", "elem7"]
i = (list(g) for _, g in groupby(lst, key=lambda x: x.startswith('marker')))
print([a + b for a, b in zip_longest(i, i, fillvalue=[])])
```
Edit2
```py
from itertools import groupby, zip_longest
lst = ["elem1", "elem2", "marker1", "elem3", "marker2", "elem4", "elem5", "marker3", "elem6", "elem7"]
i = iter([[]] + [list(g) for _, g in groupby(lst, key=lambda x: x.startswith('marker'))])
print([a + b for a, b in zip_longest(i, i, fillvalue=[])])
```
|
72,596,666 |
i am making a house management app i have to upload images of the property alongside other data related to the property so i am using two screens one for the general info about the house and the second one specifically to upload images
**Form screen**
[](https://i.stack.imgur.com/m062a.png)
**Image Upload Screen**
[](https://i.stack.imgur.com/9AmeL.png)
from the upload screen i am returning back a list of images to the form screen
```
// i am waiting for the list in the form screen
images = await Navigator.push(context, MaterialPageRoute(builder: (context) => AddPictures()));
// i am returning the list back from the upload screen
Navigator.pop(context,imageStrings);
```
I am failing to show circular progress indicator for some reason beyond my capacity to know itried all ways i know
this is the rest of the code
```
//outiside the widdget build i have two lists
List<XFile> imagesXFiles = []; //for raw image files from the gallery or camera
List<String> imageStrings = []; //for image links from the firebase storage
body: isLoading == true ? CircularProgressIndicator() : Column(
children: [
Expanded(
//the first grid is a button to let the user access camera or gallery
child: GridView.builder(
gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
crossAxisCount: 3,
crossAxisSpacing: 2.0,
mainAxisSpacing: 2.0
),
itemCount: imagesXFiles.length + 1,
itemBuilder: (BuildContext context, int index) {
return index == 0 ? GestureDetector(
onTap: (){
// a function to pick images and add store them to the list "imagesXFiles"
_showPicker(context);
},
child: Container(
decoration: BoxDecoration(
color: Colors.black12,
borderRadius: BorderRadius.circular(5.0),
),
child: Icon(
Icons.add,
color: Colors.black,
size: 30.0,
),
),
): Container(
child: Image(
image: FileImage(File(imagesXFiles[index-1].path)),
fit: BoxFit.fill
),
);
},
),
),
TextButton(
onPressed: ()async{
// for some reason the circular progress doesn't work i dont understand why
setState(() {
isLoading = true;
});
imageStrings = await uploadImages(imagesXFiles).whenComplete(() {
setState(() {
isLoading = false;
Navigator.pop(context,imageStrings);
});
});
},
child: Text("Upload",style: TextStyle(color: Colors.black,fontSize: 25),)),
],
),
```
here is the upload function that uploads the images to firebase
```
Future<List<String>> uploadImages(List<XFile> imagesXFiles) async {
imagesXFiles.forEach((image) async {
final storageRef = storage.ref().child(Random().nextInt(100).toString());
await storageRef.putFile(File(image.path));
String imageURL = await storageRef.getDownloadURL();
imageStrings.add(imageURL);
firebaseFirestore
.collection("housePictures")
.add({
"imageURL" : imageURL,
});
});
return imageStrings;
}
```
|
2022/06/12
|
[
"https://Stackoverflow.com/questions/72596666",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10796813/"
] |
Create (and include) a new inner list at the start or at a marker, otherwise append to the current inner list ([Try it online!](https://tio.run/##dY7BCoMwDIbvPkXwooII6gZD2CvsBaSHgBFl2pY2MPf0XdtNdxjLIfxN8v399ZMnJduLNs4xWbZwhT4BX326ormTqdMSUlpoPUQTxHvZ7LM2FeUH@3dbf29/@dMuzsFIJMmoDCyWYZYQc3XRHX28m5IUH5Y0GmQaQmaEzvdNQAC3gEV6BKnYY2FYWUbD9jHzlGfv/7MibLBCrUkO@VaI6KzNLDk//AvnXg "Python 3.8 (pre-release) – Try It Online")):
```
a = None
separated = [a := [x] for x in lst if not a or x.startswith('marker') or a.append(x)]
```
Another ([Try it online!](https://tio.run/##dU5BCoMwELz7ipCLCiKoLZRCv9APhBwWjBiqSUgWal@fGlNTSts9LMPMzuyYB45adSdjvUfh0JELYRlZh9EZ7E3YhlaEiknMCbQBRLHduY7y6mX7d9u8b7/9hx0cQxDPskFbMjkkUpGt13lLd8KABRR9qhkGEgouCB521UrwD34J/BqZSDkQpXG9D2LtECy6u8SxyGO5vAwK1GCMUH2xlD/esIXHL3EbKxUWqWXp/RM "Python 3.8 (pre-release) – Try It Online")):
```
separated = [
a
for a in [None]
for x in lst
if not a or x.startswith('marker') or a.append(x)
for a in [[x]]
]
```
Yet another (untested, can't test now):
```
from more_itertools import split_before
separated = list(split_before(lst, lambda s: s.startswith('marker')))
```
|
You could look up the indexes of the `marker` elements in the list, and then take sublists based on those positions:
```py
lst = ["elem1", "elem2", "marker1", "elem3", "marker2", "elem4", "elem5"]
idxs = [i for i, v in enumerate(lst) if type(v) == str and v.startswith('marker')]
separated = [lst[i:j] for i, j in zip([0]+idxs, idxs+[len(lst)]) if i < j]
# [['elem1', 'elem2'], ['marker1', 'elem3'], ['marker2', 'elem4', 'elem5']]
lst = ["marker1", "elem1", "elem2", "marker2", "elem3"]
idxs = [i for i, v in enumerate(lst) if type(v) == str and v.startswith('marker')]
separated = [lst[i:j] for i, j in zip([0]+idxs, idxs+[len(lst)]) if i < j]
# [['marker1', 'elem1', 'elem2'], ['marker2', 'elem3']]
```
Adapted from [this answer](https://stackoverflow.com/a/52591055/9473764).
|
10,215,606 |
I have a macro-enabled WorkBook. I need to specify the current folder in which the macro-enabled file is present as the path. I tried setting
```
path = ActiveWorkbook.Path
```
*and*
```
path = CurDir()
```
but neither of these work for me. Any idea on this?
|
2012/04/18
|
[
"https://Stackoverflow.com/questions/10215606",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1270123/"
] |
If the path you want is the one to the workbook running the macro, and that workbook has been saved, then
`ThisWorkbook.Path`
is what you would use.
|
I thought I had misunderstood but I was right. In this scenario, it will be `ActiveWorkbook.Path`
But the main issue was not here. The problem was with these 2 lines of code
```
strFile = Dir(strPath & "*.csv")
```
Which should have written as
```
strFile = Dir(strPath & "\*.csv")
```
and
```
With .QueryTables.Add(Connection:="TEXT;" & strPath & strFile, _
```
Which should have written as
```
With .QueryTables.Add(Connection:="TEXT;" & strPath & "\" & strFile, _
```
|
49,378,743 |
I'm using `react-toastify` and I can't get a simple toast to be rendered...
```
import React from "react";
import { toast } from 'react-toastify';
class MyView extends React.Component<{}, {}> {
constructor() {
super();
this.state = {
};
}
componentDidMount() {
toast("Hello", { autoClose: false });
}
notify = () => toast("Hello", { autoClose: false });
render() {
return (
<div>
<button onClick={this.notify}>Notify</button>
</div>
)}
}
```
package.json (in "dependencies" section)
```
"react": "^16.2.0",
"react-toastify": "^3.2.2"
```
If I debug it, I see that my toasts are queued, \_EventManager2 never gets the \_constant.ACTION.MOUNTED event that normally emits the toasts from the queue...
```
/**
* Wait until the ToastContainer is mounted to dispatch the toast
* and attach isActive method
*/
_EventManager2.default.on(_constant.ACTION.MOUNTED, function (containerInstance) {
container = containerInstance;
toaster.isActive = function (id) {
return container.isToastActive(id);
};
queue.forEach(function (item) {
_EventManager2.default.emit(item.action, item.content, item.options);
});
queue = [];
});
```
..so there might be something wrong with that ToastContainer but what? I just use the sample code from the documentation.
Thank you for your help!
|
2018/03/20
|
[
"https://Stackoverflow.com/questions/49378743",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3387233/"
] |
You need to remember to include the `<ToastContainer />` in your render.
|
To make use of the react-toastify, Please follow below steps:-
1. Install the npm package
npm i toastify --save
2. Import the react-toastify as shown below in that given order
import 'react-toastify/dist/ReactToastify.css'; // import first
import { ToastContainer, toast } from 'react-toastify'; // then this
|
49,378,743 |
I'm using `react-toastify` and I can't get a simple toast to be rendered...
```
import React from "react";
import { toast } from 'react-toastify';
class MyView extends React.Component<{}, {}> {
constructor() {
super();
this.state = {
};
}
componentDidMount() {
toast("Hello", { autoClose: false });
}
notify = () => toast("Hello", { autoClose: false });
render() {
return (
<div>
<button onClick={this.notify}>Notify</button>
</div>
)}
}
```
package.json (in "dependencies" section)
```
"react": "^16.2.0",
"react-toastify": "^3.2.2"
```
If I debug it, I see that my toasts are queued, \_EventManager2 never gets the \_constant.ACTION.MOUNTED event that normally emits the toasts from the queue...
```
/**
* Wait until the ToastContainer is mounted to dispatch the toast
* and attach isActive method
*/
_EventManager2.default.on(_constant.ACTION.MOUNTED, function (containerInstance) {
container = containerInstance;
toaster.isActive = function (id) {
return container.isToastActive(id);
};
queue.forEach(function (item) {
_EventManager2.default.emit(item.action, item.content, item.options);
});
queue = [];
});
```
..so there might be something wrong with that ToastContainer but what? I just use the sample code from the documentation.
Thank you for your help!
|
2018/03/20
|
[
"https://Stackoverflow.com/questions/49378743",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3387233/"
] |
For me moving `ReactToastify.css` above `toast` solved the issue!
```
import 'react-toastify/dist/ReactToastify.css'; // import first
import { ToastContainer, toast } from 'react-toastify'; // then this
```
|
```
import React from "react";
import { ToastContainer,toast } from 'react-toastify'; // <- add ToastContainer
import 'react-toastify/dist/ReactToastify.css'; // <- add line
class MyView extends React.Component<{}, {}> {
constructor() {
super();
this.state = {
};
}
componentDidMount() {
toast("Hello", { autoClose: false });
}
notify = () => toast("Hello", { autoClose: false });
render() {
return (
<div>
<button onClick={this.notify}>Notify</button>
<ToastContainer /> {/* <- add line */}
</div>
)}
}
```
|
49,378,743 |
I'm using `react-toastify` and I can't get a simple toast to be rendered...
```
import React from "react";
import { toast } from 'react-toastify';
class MyView extends React.Component<{}, {}> {
constructor() {
super();
this.state = {
};
}
componentDidMount() {
toast("Hello", { autoClose: false });
}
notify = () => toast("Hello", { autoClose: false });
render() {
return (
<div>
<button onClick={this.notify}>Notify</button>
</div>
)}
}
```
package.json (in "dependencies" section)
```
"react": "^16.2.0",
"react-toastify": "^3.2.2"
```
If I debug it, I see that my toasts are queued, \_EventManager2 never gets the \_constant.ACTION.MOUNTED event that normally emits the toasts from the queue...
```
/**
* Wait until the ToastContainer is mounted to dispatch the toast
* and attach isActive method
*/
_EventManager2.default.on(_constant.ACTION.MOUNTED, function (containerInstance) {
container = containerInstance;
toaster.isActive = function (id) {
return container.isToastActive(id);
};
queue.forEach(function (item) {
_EventManager2.default.emit(item.action, item.content, item.options);
});
queue = [];
});
```
..so there might be something wrong with that ToastContainer but what? I just use the sample code from the documentation.
Thank you for your help!
|
2018/03/20
|
[
"https://Stackoverflow.com/questions/49378743",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3387233/"
] |
You have to also `import 'react-toastify/dist/ReactToastify.css';`
```
import React, { Component } from 'react';
import { ToastContainer, toast } from 'react-toastify';
import 'react-toastify/dist/ReactToastify.css';
// minified version is also included
// import 'react-toastify/dist/ReactToastify.min.css';
class App extends Component {
notify = () => toast("Wow so easy !");
render(){
return (
<div>
<button onClick={this.notify}>Notify !</button>
<ToastContainer />
</div>
);
}
}
```
|
My mistake was importing toast without {} curly braces because my course instructor did so.
Try to change this:
```
import toast from 'react-toastify';
```
To:
```
import { toast } from 'react-toastify';
```
Also according to all other 'react-toastify' stackoverflow responses, installing latest version causes problem. So try uninstalling it and install older version that your course instructor did or version 4.1 seems to be working for most people.
Uninstall first:
```
npm uninstall react-toastify --save
```
Then install 4.1 version:
```
npm i [email protected]
```
|
49,378,743 |
I'm using `react-toastify` and I can't get a simple toast to be rendered...
```
import React from "react";
import { toast } from 'react-toastify';
class MyView extends React.Component<{}, {}> {
constructor() {
super();
this.state = {
};
}
componentDidMount() {
toast("Hello", { autoClose: false });
}
notify = () => toast("Hello", { autoClose: false });
render() {
return (
<div>
<button onClick={this.notify}>Notify</button>
</div>
)}
}
```
package.json (in "dependencies" section)
```
"react": "^16.2.0",
"react-toastify": "^3.2.2"
```
If I debug it, I see that my toasts are queued, \_EventManager2 never gets the \_constant.ACTION.MOUNTED event that normally emits the toasts from the queue...
```
/**
* Wait until the ToastContainer is mounted to dispatch the toast
* and attach isActive method
*/
_EventManager2.default.on(_constant.ACTION.MOUNTED, function (containerInstance) {
container = containerInstance;
toaster.isActive = function (id) {
return container.isToastActive(id);
};
queue.forEach(function (item) {
_EventManager2.default.emit(item.action, item.content, item.options);
});
queue = [];
});
```
..so there might be something wrong with that ToastContainer but what? I just use the sample code from the documentation.
Thank you for your help!
|
2018/03/20
|
[
"https://Stackoverflow.com/questions/49378743",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3387233/"
] |
For me moving `ReactToastify.css` above `toast` solved the issue!
```
import 'react-toastify/dist/ReactToastify.css'; // import first
import { ToastContainer, toast } from 'react-toastify'; // then this
```
|
My mistake was importing toast without {} curly braces because my course instructor did so.
Try to change this:
```
import toast from 'react-toastify';
```
To:
```
import { toast } from 'react-toastify';
```
Also according to all other 'react-toastify' stackoverflow responses, installing latest version causes problem. So try uninstalling it and install older version that your course instructor did or version 4.1 seems to be working for most people.
Uninstall first:
```
npm uninstall react-toastify --save
```
Then install 4.1 version:
```
npm i [email protected]
```
|
49,378,743 |
I'm using `react-toastify` and I can't get a simple toast to be rendered...
```
import React from "react";
import { toast } from 'react-toastify';
class MyView extends React.Component<{}, {}> {
constructor() {
super();
this.state = {
};
}
componentDidMount() {
toast("Hello", { autoClose: false });
}
notify = () => toast("Hello", { autoClose: false });
render() {
return (
<div>
<button onClick={this.notify}>Notify</button>
</div>
)}
}
```
package.json (in "dependencies" section)
```
"react": "^16.2.0",
"react-toastify": "^3.2.2"
```
If I debug it, I see that my toasts are queued, \_EventManager2 never gets the \_constant.ACTION.MOUNTED event that normally emits the toasts from the queue...
```
/**
* Wait until the ToastContainer is mounted to dispatch the toast
* and attach isActive method
*/
_EventManager2.default.on(_constant.ACTION.MOUNTED, function (containerInstance) {
container = containerInstance;
toaster.isActive = function (id) {
return container.isToastActive(id);
};
queue.forEach(function (item) {
_EventManager2.default.emit(item.action, item.content, item.options);
});
queue = [];
});
```
..so there might be something wrong with that ToastContainer but what? I just use the sample code from the documentation.
Thank you for your help!
|
2018/03/20
|
[
"https://Stackoverflow.com/questions/49378743",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3387233/"
] |
The other solutions didn't work for me - turns out I wasn't passing a string to the `toast.*` function. For example:
```
getSomethingFromApi()
.then((response) => {
// this works fine because response.message is a string
toast.notify(response.message)
})
.catch((error) => {
// this will fail to render because error is an object, not a string
toast.error(error)
})
```
|
```
import React from "react";
import { ToastContainer,toast } from 'react-toastify'; // <- add ToastContainer
import 'react-toastify/dist/ReactToastify.css'; // <- add line
class MyView extends React.Component<{}, {}> {
constructor() {
super();
this.state = {
};
}
componentDidMount() {
toast("Hello", { autoClose: false });
}
notify = () => toast("Hello", { autoClose: false });
render() {
return (
<div>
<button onClick={this.notify}>Notify</button>
<ToastContainer /> {/* <- add line */}
</div>
)}
}
```
|
49,378,743 |
I'm using `react-toastify` and I can't get a simple toast to be rendered...
```
import React from "react";
import { toast } from 'react-toastify';
class MyView extends React.Component<{}, {}> {
constructor() {
super();
this.state = {
};
}
componentDidMount() {
toast("Hello", { autoClose: false });
}
notify = () => toast("Hello", { autoClose: false });
render() {
return (
<div>
<button onClick={this.notify}>Notify</button>
</div>
)}
}
```
package.json (in "dependencies" section)
```
"react": "^16.2.0",
"react-toastify": "^3.2.2"
```
If I debug it, I see that my toasts are queued, \_EventManager2 never gets the \_constant.ACTION.MOUNTED event that normally emits the toasts from the queue...
```
/**
* Wait until the ToastContainer is mounted to dispatch the toast
* and attach isActive method
*/
_EventManager2.default.on(_constant.ACTION.MOUNTED, function (containerInstance) {
container = containerInstance;
toaster.isActive = function (id) {
return container.isToastActive(id);
};
queue.forEach(function (item) {
_EventManager2.default.emit(item.action, item.content, item.options);
});
queue = [];
});
```
..so there might be something wrong with that ToastContainer but what? I just use the sample code from the documentation.
Thank you for your help!
|
2018/03/20
|
[
"https://Stackoverflow.com/questions/49378743",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3387233/"
] |
Even better, import minified css:
`import 'react-toastify/dist/ReactToastify.min.css';`
or in case you are importing it in .scss file
`@import '~react-toastify/dist/ReactToastify.min.css';`
|
To make use of the react-toastify, Please follow below steps:-
1. Install the npm package
npm i toastify --save
2. Import the react-toastify as shown below in that given order
import 'react-toastify/dist/ReactToastify.css'; // import first
import { ToastContainer, toast } from 'react-toastify'; // then this
|
49,378,743 |
I'm using `react-toastify` and I can't get a simple toast to be rendered...
```
import React from "react";
import { toast } from 'react-toastify';
class MyView extends React.Component<{}, {}> {
constructor() {
super();
this.state = {
};
}
componentDidMount() {
toast("Hello", { autoClose: false });
}
notify = () => toast("Hello", { autoClose: false });
render() {
return (
<div>
<button onClick={this.notify}>Notify</button>
</div>
)}
}
```
package.json (in "dependencies" section)
```
"react": "^16.2.0",
"react-toastify": "^3.2.2"
```
If I debug it, I see that my toasts are queued, \_EventManager2 never gets the \_constant.ACTION.MOUNTED event that normally emits the toasts from the queue...
```
/**
* Wait until the ToastContainer is mounted to dispatch the toast
* and attach isActive method
*/
_EventManager2.default.on(_constant.ACTION.MOUNTED, function (containerInstance) {
container = containerInstance;
toaster.isActive = function (id) {
return container.isToastActive(id);
};
queue.forEach(function (item) {
_EventManager2.default.emit(item.action, item.content, item.options);
});
queue = [];
});
```
..so there might be something wrong with that ToastContainer but what? I just use the sample code from the documentation.
Thank you for your help!
|
2018/03/20
|
[
"https://Stackoverflow.com/questions/49378743",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3387233/"
] |
Before declaring your class, add the following line:
```
toast.configure();
```
|
The other solutions didn't work for me - turns out I wasn't passing a string to the `toast.*` function. For example:
```
getSomethingFromApi()
.then((response) => {
// this works fine because response.message is a string
toast.notify(response.message)
})
.catch((error) => {
// this will fail to render because error is an object, not a string
toast.error(error)
})
```
|
49,378,743 |
I'm using `react-toastify` and I can't get a simple toast to be rendered...
```
import React from "react";
import { toast } from 'react-toastify';
class MyView extends React.Component<{}, {}> {
constructor() {
super();
this.state = {
};
}
componentDidMount() {
toast("Hello", { autoClose: false });
}
notify = () => toast("Hello", { autoClose: false });
render() {
return (
<div>
<button onClick={this.notify}>Notify</button>
</div>
)}
}
```
package.json (in "dependencies" section)
```
"react": "^16.2.0",
"react-toastify": "^3.2.2"
```
If I debug it, I see that my toasts are queued, \_EventManager2 never gets the \_constant.ACTION.MOUNTED event that normally emits the toasts from the queue...
```
/**
* Wait until the ToastContainer is mounted to dispatch the toast
* and attach isActive method
*/
_EventManager2.default.on(_constant.ACTION.MOUNTED, function (containerInstance) {
container = containerInstance;
toaster.isActive = function (id) {
return container.isToastActive(id);
};
queue.forEach(function (item) {
_EventManager2.default.emit(item.action, item.content, item.options);
});
queue = [];
});
```
..so there might be something wrong with that ToastContainer but what? I just use the sample code from the documentation.
Thank you for your help!
|
2018/03/20
|
[
"https://Stackoverflow.com/questions/49378743",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3387233/"
] |
Before declaring your class, add the following line:
```
toast.configure();
```
|
My mistake was importing toast without {} curly braces because my course instructor did so.
Try to change this:
```
import toast from 'react-toastify';
```
To:
```
import { toast } from 'react-toastify';
```
Also according to all other 'react-toastify' stackoverflow responses, installing latest version causes problem. So try uninstalling it and install older version that your course instructor did or version 4.1 seems to be working for most people.
Uninstall first:
```
npm uninstall react-toastify --save
```
Then install 4.1 version:
```
npm i [email protected]
```
|
49,378,743 |
I'm using `react-toastify` and I can't get a simple toast to be rendered...
```
import React from "react";
import { toast } from 'react-toastify';
class MyView extends React.Component<{}, {}> {
constructor() {
super();
this.state = {
};
}
componentDidMount() {
toast("Hello", { autoClose: false });
}
notify = () => toast("Hello", { autoClose: false });
render() {
return (
<div>
<button onClick={this.notify}>Notify</button>
</div>
)}
}
```
package.json (in "dependencies" section)
```
"react": "^16.2.0",
"react-toastify": "^3.2.2"
```
If I debug it, I see that my toasts are queued, \_EventManager2 never gets the \_constant.ACTION.MOUNTED event that normally emits the toasts from the queue...
```
/**
* Wait until the ToastContainer is mounted to dispatch the toast
* and attach isActive method
*/
_EventManager2.default.on(_constant.ACTION.MOUNTED, function (containerInstance) {
container = containerInstance;
toaster.isActive = function (id) {
return container.isToastActive(id);
};
queue.forEach(function (item) {
_EventManager2.default.emit(item.action, item.content, item.options);
});
queue = [];
});
```
..so there might be something wrong with that ToastContainer but what? I just use the sample code from the documentation.
Thank you for your help!
|
2018/03/20
|
[
"https://Stackoverflow.com/questions/49378743",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3387233/"
] |
The other solutions didn't work for me - turns out I wasn't passing a string to the `toast.*` function. For example:
```
getSomethingFromApi()
.then((response) => {
// this works fine because response.message is a string
toast.notify(response.message)
})
.catch((error) => {
// this will fail to render because error is an object, not a string
toast.error(error)
})
```
|
For me moving `ReactToastify.css` above `toast` solved the issue!
```
import 'react-toastify/dist/ReactToastify.css'; // import first
import { ToastContainer, toast } from 'react-toastify'; // then this
```
|
49,378,743 |
I'm using `react-toastify` and I can't get a simple toast to be rendered...
```
import React from "react";
import { toast } from 'react-toastify';
class MyView extends React.Component<{}, {}> {
constructor() {
super();
this.state = {
};
}
componentDidMount() {
toast("Hello", { autoClose: false });
}
notify = () => toast("Hello", { autoClose: false });
render() {
return (
<div>
<button onClick={this.notify}>Notify</button>
</div>
)}
}
```
package.json (in "dependencies" section)
```
"react": "^16.2.0",
"react-toastify": "^3.2.2"
```
If I debug it, I see that my toasts are queued, \_EventManager2 never gets the \_constant.ACTION.MOUNTED event that normally emits the toasts from the queue...
```
/**
* Wait until the ToastContainer is mounted to dispatch the toast
* and attach isActive method
*/
_EventManager2.default.on(_constant.ACTION.MOUNTED, function (containerInstance) {
container = containerInstance;
toaster.isActive = function (id) {
return container.isToastActive(id);
};
queue.forEach(function (item) {
_EventManager2.default.emit(item.action, item.content, item.options);
});
queue = [];
});
```
..so there might be something wrong with that ToastContainer but what? I just use the sample code from the documentation.
Thank you for your help!
|
2018/03/20
|
[
"https://Stackoverflow.com/questions/49378743",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3387233/"
] |
install react-toastify using command
```sh
npm i react-toastify
```
Then:
```js
import {ToastContainer,toast} from 'react-toastify'
```
and in return add
```js
<ToastContainer />
```
and after that when you do `toast('hy')`
then it will show toast
|
To make use of the react-toastify, Please follow below steps:-
1. Install the npm package
npm i toastify --save
2. Import the react-toastify as shown below in that given order
import 'react-toastify/dist/ReactToastify.css'; // import first
import { ToastContainer, toast } from 'react-toastify'; // then this
|
3,570,592 |
Let $Lip((a,b))$ be the space of Lipschitz functions on $(a,b)$: it is obvious the inclusion $Lip((a,b))\subset \mathcal{C}^0([a,b])$, but I was wondering if maybe this subspace is closed with respct to the supremum norm.
I've studied that $B\_{Lip((a,b))}$, that is the unit ball of $Lip((a,b))$ is compact in $\mathcal{C}^0([a,b])$, but my feeling is that the whole subspace is not closed.
My idea: we know that, on $(0,1)$, $\sqrt{x}$ is not Lipschitz, thus we should be able to construct a sequence $(f\_h)\_h$ of Lipschitz functions such that $$ \lim\_{h\rightarrow \infty} \lVert f\_h-f \rVert\_{\infty}=0,$$
which in particolar yelds the non-closedness of $(Lip((a,b))$.
My question: How to create such a sequence, if it exists?
Any hint, help or answer would be much apppreciate, thanks in advance.
|
2020/03/05
|
[
"https://math.stackexchange.com/questions/3570592",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/746358/"
] |
Any infinite set $B$ has at least a proper subset $C$ such that $|C|=|B|$ (assuming choice, of course, or some weaker axiom thereof).
Since $B$ is infinite, it is not empty. Let $b\_0\in B$ and consider $C=B\setminus\{b\_0\}$.
Then $|B|=|C|$. Indeed, take a countable subset $Z$ of $B$ (it exists by choice). Then $Z\cup\{b\_0\}$ is countable as well, so we can assume $b\_0\in Z$. There exists a bijection $f\colon\mathbb{N}\to Z$ such that $f(0)=b\_0$. Now consider $F\colon B\to C$ defined by
$$
F(x)=\begin{cases}
f(n+1) & \text{if $x\in Z$ and $x=f(n)$} \\[4px]
x & \text{if $x\notin Z$}
\end{cases}
$$
It's easy to prove that $F$ is a bijection.
If $|A|=|B|$, then we can use $F$ to provide also a bijection $A\to C$ and $C$ is a proper subset of $B$.
|
I believe the specification in $(2)$ of proper subsets instead of the full set, $B$, is a historical remnant from Cantor's original formulation of the definition. As the other answer and comment by [**egreg**](https://math.stackexchange.com/users/62967/egreg) and [**JMoravitz**](https://math.stackexchange.com/users/179297/jmoravitz) have demonstrated, the specification is redundant. It is also absent from some later definitions of "larger cardinality than".
---
The effect of the two components of the definition is that (2) establishes that the two sets have unequal cardinalities and then (1) distinguishes the order of the inequality to discern which set is larger. $(2)$ alone would be true for $\{1,2,3\}$ and $\{1,2\}$, since any attempted pairing of their elements leaves an unpaired remainder, but fails to specify the order of the sets sizes. $(1)$ alone would be true for $\mathbb{N}$ and $\mathbb{N}\_{\text{even}}$, despite them being the same size; all natural numbers can be paired with an even number in the subset by doubling them.
The definition of "larger cardinality than" that you cite is due to [(Cantor, 1895 pp. 483-484)](https://web.archive.org/web/20140423224341/http://gdz-lucene.tc.sub.uni-goettingen.de/gcs/gcs?&&action=pdf&metsFile=PPN235181684_0046&divID=LOG_0044&pagesize=original&pdfTitlePage=http%3A%2F%2Fgdz.sub.uni-goettingen.de%2Fdms%2Fload%2Fpdftitle%2F%3FmetsFile%3DPPN235181684_0046%7C&targetFileName=PPN235181684_0046_LOG_0044.pdf&). The following is an abridged excerpt from [(Cantor, 1915 pp. 89-90)](https://archive.org/details/contributionstot003626mbp), the translation of the 1895 publication. This is further discussed in [(Bezhanishvili and Landreth, p. 17)](https://www.maa.org/sites/default/files/images/upload_library/46/Pengelley_projects/Project-5/set_theory_project.pdf). I've rewritten the excerpt with modern notation and terminology. \*
>
> ### "Greater" and "Less" with Powers
>
>
> If for two sets $A$ and $B$ with the cardinalities $b = |B|$ and $a=|A|$, both the conditions:
>
>
> 1. There is a subset $A\_1$ of $A$, such that $|A\_1|=|B|$,
> 2. There is **no subset of $\mathbf{B}$** which is bijective with $A$,
>
>
> are fulfilled ... they express a definite relation of the cardinalities $a$ and $b$ to one another. Further, the equivalence of $A$ and $B$, and thus the equality of $a$ and $b$, is excluded... Thirdly, the relation of $a$ to $b$ is such that it makes impossible the same relation of $b$ to $a$...
>
>
> We express the relation of $a$ to $b$ characterized by $(1)$ and $(2)$ by saying: $b$ is “less” than $a$ or $a$ is “greater” than $b$; in signs $b<a$ or $a > b$.
>
>
>
Cantor's statements $(1)$ and $(2)$ respectively represent your two statements but we see that Cantor's formulation of $(2)$ references the subsets of the smaller set, $B$. To quote the original text, *"Es giebt keinen **Theil** von $M$ der mit $N$ äquivalent ist"*. That is to say "There is no **part** from the smaller set that is equivalent with the larger set".
---
You are vindicated in your questioning since some more modern formulations of the definition, e.g., [(Meyries, p. 8)](https://arxiv.org/pdf/1506.06319.pdf) eschew the redundant stipulation of subsets in $(2)$: \*
>
> The set $A$ is called of larger cardinality than the set $B$, if
>
>
> 1. $B$ is of equal cardinality as
> a subset of $A$
> 2. and **if $\mathbf{B}$** and
> $A$ are not of equal cardinality.
>
>
> In this case one symbolically writes $|A| > |B|$.
>
>
>
Others express the definition using injectivity of functions, again using $B$ itself instead of its subsets, e.g., [(Neely, 2020 p. 12)](http://ee.usc.edu/stochastic-nets/docs/levels-of-infinity.pdf): \*
>
> We say $|B| < |A|$ if:
>
>
> 1. there is an injection $f : B → A$
> 2. there is no injection $f : A → \mathbf{B}$
>
>
>
---
### References
* [G. Cantor, 1895: Beiträge zur Begründung der transfiniten Mengenlehre](https://web.archive.org/web/20140423224341/http://gdz-lucene.tc.sub.uni-goettingen.de/gcs/gcs?&&action=pdf&metsFile=PPN235181684_0046&divID=LOG_0044&pagesize=original&pdfTitlePage=http%3A%2F%2Fgdz.sub.uni-goettingen.de%2Fdms%2Fload%2Fpdftitle%2F%3FmetsFile%3DPPN235181684_0046%7C&targetFileName=PPN235181684_0046_LOG_0044.pdf&)
* [G. Cantor, 1915: Contributions to the Founding of the Theory of Transfinite Numbers](https://archive.org/details/contributionstot003626mbp)
* [G. Bezhanishvili and E. Landreth: An Introduction to Elementary Set Theory](https://www.maa.org/sites/default/files/images/upload_library/46/Pengelley_projects/Project-5/set_theory_project.pdf)
* [M. Meyries, 2015: Infinity A simple, but not too simple introduction](https://arxiv.org/pdf/1506.06319.pdf)
* [M. J. Neely, 2020: Sets, Infinity, and Mappings](http://ee.usc.edu/stochastic-nets/docs/levels-of-infinity.pdf)
---
\* NB: In the excerpts, I have changed their notation of the sets to $A$ and $B$ and swapped the order of the definition's two components to match your $(1)$ and $(2)$.
|
27,689,732 |
I want to set the values of a dropdownList according to the selectedValue of another dropdownList.
So for example :
```
ViewBag.Brand = new SelectList(db.Brand, "Libel", "Libel");
ViewBag.IdModel = new SelectList(db.Model.Where(model => model.Brand == ViewBag.Brand.SelectedValue), "IdModel", "Descriptive");
```
I know this isn't working but it's to show the logic I would like to have.
And this is my view :
```
<div class="form-group">
@Html.LabelFor(model => model.IdModel, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.DropDownList("IdModel", null, htmlAttributes: new { @class = "form-control" })
@Html.ValidationMessageFor(model => model.IdModel, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.Brand, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.DropDownList("Brand", null, htmlAttributes: new { @class = "form-control" })
@Html.ValidationMessageFor(model => model.IdModel, "", new { @class = "text-danger" })
</div>
</div>
```
Is their any simple way to do this?
Thank's !
|
2014/12/29
|
[
"https://Stackoverflow.com/questions/27689732",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3520621/"
] |
In your case your need to ajax call or server call when you change brand dropdown box.
See Below example it is just used static data to identify the when brand model is change then automatically changed model dropdown using jquery(Client Side).
**View Side:-**
```
@*Display the elements in the page*@
@*------------------------------------------------*@
<script type="text/javascript"
src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.1/jquery.min.js"></script>
<div class="form-group">
<div class="col-md-10">
@Html.DropDownList("Brand", (SelectList)ViewBag.Brand, new { htmlAttributes = new { @class =
"form-control" } })
</div>
</div>
<div class="form-group">
<div class="col-md-10">
@Html.DropDownList("IdModel", (SelectList)ViewBag.IdModel, new {htmlAttributes = new {
@class = "form-control" } })
</div>
</div>
@*------------------------------------------------*@
@*Script for call the server side function when you changed brand combo from jquery*@
@*------------------------------------------------*@
<script type="text/javascript">
$(function () {
$("#Brand").change(function () {
var selectedItem = $(this).val();
$.ajax({
cache: false,
type: "GET",
url: "/Home/GetModelFromBrand", // User your action and controller name
data: { "Brandid": selectedItem },
success: function (data) {
$("#IdModel").empty();
$.each(data, function (id, option) {
$("#IdModel").append($('<option>
</option>').val(option.IdModel).html(option.Descriptive));
});
},
error: function (xhr, ajaxOptions, thrownError) {
alert('Failed to retrieve states.');
}
});
});
});
</script>
@*------------------------------------------------*@
```
**Controller Side:-**
```
//Get Method to load the view
//==============================================================
public ActionResult Index()
{
var brands = new SelectList(new[]
{
new {Libel="Brand1",},
new {Libel="Brand2",},
},
"Libel", "Libel");
//=======Suppose Brand1 have idmodels1 , idmodels2 models
var idmodels = new SelectList(new[]
{
new {IdModel="1",Descriptive="idmodels1",},
new {IdModel="2",Descriptive="idmodels2",},
},
"IdModel", "Descriptive");
ViewBag.Brand = brands;
ViewBag.IdModel = idmodels;
return View();
}
//==============================================================
//Get Action when changed brand combo
//==============================================================
[AcceptVerbs(HttpVerbs.Get)]
public ActionResult GetModelFromBrand(string Brandid)
{
var obj = new[] {
new {IdModel = 3,
Descriptive = "idmodels3"},
new {IdModel = 4,
Descriptive = "idmodels4"},
new {IdModel = 5,
Descriptive = "idmodels5"}
};
return Json(obj, JsonRequestBehavior.AllowGet);
}
//==============================================================
```
|
there are 2 ways:
1 do it on client;
2 do it on server
1. On client. Second drop down options should contain ids with brand id, then you could write javascript which should change selected index of second drop down based on selected value of first drop down. Here need to base on your model structure.
2. On server. Do postbacks on each change of first drop down. And return each time new model for second drop down based on posted value from first drop down.
|
294,395 |
The sample XML looks like this:
```
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<root>
<level01>
<field01>AAAAAAAAAAAAAAAAAAAA</field01>
<field02>BBBBBBBB</field02>
<field03>CCCCCCCCCCCCCCCCCCCC</field03>
<field04>DDDDDDDDDDDDDDDDDDDD</field04>
<field05>DDD</field05>
<level02>
<field01>EEEEEEEEE</field01>
<field02>FFF</field02>
<field04>GGGGGGGGGGs</field04>
<field05>HHH</field05>
<level03>
<field01>IIIIIIIII</field01>
<field02>JJJ</field02>
<field04>KKKKKKKKK</field04>
<field05>L</field05>
</level03>
</level02>
</level01>
</root>
```
The desired output looks like:
```
AAAAAA,BBBBB, CCCCCCCCCCCCC ,DDDDDDDDDD ,DDD,EEE,FFF,GGGG,HHH,III,JJJ,KKK,L
```
|
2016/07/07
|
[
"https://unix.stackexchange.com/questions/294395",
"https://unix.stackexchange.com",
"https://unix.stackexchange.com/users/178570/"
] |
**xmlstartlet** arguments are a little bit tricky. You have to see
them as templtes (-t) in the xsl way...
```
xmlstarlet sel -B -t -m '//text()' -c 'concat(.,",")' x1.xml
```
where:
* -B : generically remove spaces
* -t : template in the xsl sense
* -m : match xpath exp
* -c : copy-of xpath exp
This expression, produces an extra ",". Naturally we can uses normal
Unix tools to help:
```
xmlstarlet sel -B -t -v '//text()' x1.xml |
sed -z 's/\n/, /g; s/$/\n/'
```
* -t : a template (in xsl sense)
* -v : value-of (xpath expression)
* sed... to trim ,
|
Using [xml2](http://ofb.net/~egnor/xml2/) (available packaged for debian and most other distros) instead of `xml2starlet`, along with `awk` and `paste`:
```
$ xml2 <sdfsdf.xml | awk -F= '{ print $2 }' | paste -sd,
AAAAAAAAAAAAAAAAAAAA,BBBBBBBB,CCCCCCCCCCCCCCCCCCCC,DDDDDDDDDDDDDDDDDDDD,DDD,EEEEEEEEE,FFF,GGGGGGGGGGs,HHH,IIIIIIIII,JJJ,KKKKKKKKK,L
```
if you want spaces after each comma, add them with `sed`:
```
xml2 <sdfsdf.xml | awk -F= '{ print $2 }' | paste -sd, | sed -e 's/,/, /g'
```
`cut` can also work in place of `awk` but I'm guessing there's other criteria you haven't mentioned yet, so I'll stick with `awk` for now. Anyway, here's the `cut` version:
```
xml2 <sdfsdf.xml | cut -d= -f2 | paste -sd,
```
|
14,025,628 |
My script makes an Ajax request through jQuery. The data received is json\_encoded via a server side script (php). This is further, stringified and then parseJSON'ed using jQuery to yield a recordCollection. I loop through recordCollection and push it onto records array, the variable that was declared outside the scope of the callback function.
The function looks like this:
```
var records = [] ;
$.getJSON(url, {id : recordid}, function(data) {
var recordCollection = jQuery.parseJSON(JSON.stringify(data));
$.each(recordCollection, function(){
records.push(this);
});
console.log(records) // displays all the objects, thus, the above code is right
});
console.log(records); // displays []
```
As you can notice above, the second time I logged records onto the console, it yielded an empty array, which is leading me to two conclusions:
1. Javascript arrays are passed by value, hence records outside the scope of the callback function does not retain it's value.
2. Ajax is asynchronous, hence records is being logged before the ajax call was complete and hence it still retains the value of the empty uninitialized records array and is logging that onto the console.
Now if 1 is true, how can I initialize the records array ?
And if 2 is true, should I make this Ajax call synchronous? This will make javascript block until the value is returned and thus the second time records array is logged onto the console, it will display the updated value of the array ?
The third is that I am completely missing a trick and doing something really dumb here.
I do need the records array to be set with the data returned from the ajax call as it needs to be passed around to different javascript functions in the script and the DOM basically waits for this result to load the data.
Thanks guys!
|
2012/12/24
|
[
"https://Stackoverflow.com/questions/14025628",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/709101/"
] |
You are correct in that, ajax calls are async, hence `Asynchronous Javascript and XML`. You can make it sync, but you shouldn't because your array will then be available for anyone to play with, which can cause some big headaches.
Instead, have an init call that is run once your ajax call is completed.
```
function callback(records) {
// do stuff with records.
}
$.getJSON(url, {id : recordid}, function(data) {
var recordCollection = jQuery.parseJSON(JSON.stringify(data));
callback(recordCollection);
});
```
|
Ajax stands for [Asynchronous JavaScript and XML](http://en.wikipedia.org/wiki/Ajax_%28programming%29) (forget the XML part) so i think you can guess what is right ;-)
I added the execution order with comments:
```
var records = [] ;
// 1. send request and return immediately
$.getJSON(url, {id : recordid}, function(data) {
// 3. response from server is received
var recordCollection = jQuery.parseJSON(JSON.stringify(data));
$.each(recordCollection, function(){
records.push(this);
});
console.log(records)
});
// 2. print records
console.log(records);
```
You should not try to make the request synchronous in any way. If you need to do something with `records` after the data is available you should create a new function and call it after you pushed the values into `records`.
|
61,445,011 |
**The application**
Simple REST API registration service in Spring, after sending proper POST request new user is created in database and Amazon SES sends an email with registration link to verify.
**The problem**
Locally after setting local variables (`AWS_ACCESS_KEY_ID`, `AWS_SECRET_ACCESS_KEY` and `AWS_DEFAULT_REGION`) in my OS (Windows) app works just fine, but the problem starts after deploying it. I have an EC2 Instance with Amazon Linux AMI on AWS:
* created user at AWS Identity and Access Management (IAM), granted AmazonSESFullAccess role
* logging by CMD using shh with the private key file \*.pem
* Tomcat8 service started
* MySQL service started
* application \*.war file deployed
* created environment variables using 'export' command and I checked 'printenv' just to be sure everything is fine
* after sending POST request I got exception (below) which means that user has been created but Amazon SES didn't send an email confirmation because couldn't authenticate
```
{
"timestamp": "2020-04-26T15:44:44.010+0000",
"message": "Unable to load AWS credentials from any provider in the chain: [EnvironmentVariableCredentialsProvider: Unable to load AWS credentials from environment variables (AWS_ACCESS_KEY_ID (or AWS_ACCESS_KEY) and AWS_SECRET_KEY (or AWS_SECRET_ACCESS_KEY)), SystemPropertiesCredentialsProvider: Unable to load AWS credentials from Java system properties (aws.accessKeyId and aws.secretKey), WebIdentityTokenCredentialsProvider: To use assume role profiles the aws-java-sdk-sts module must be on the class path., com.amazonaws.auth.profile.ProfileCredentialsProvider@23fac1a3: profile file cannot be null, com.amazonaws.auth.EC2ContainerCredentialsProviderWrapper@68aa5a98: The requested metadata is not found at http://169.254.169.254/latest/meta-data/iam/security-credentials/]"
}
```
* I checked again local environment variables on my EC2 instance and it was looking fine but to be sure I re-configured it using 'aws configure' command
* exception keeps showing, somehow application cannot get environment variables, I'm fighting with that for over 5 hours now so hopefully someone will come here to rescue me...
Piece of code (works fine locally):
```
AmazonSimpleEmailService client =
AmazonSimpleEmailServiceClientBuilder
.standard()
.withCredentials(DefaultAWSCredentialsProviderChain.getInstance())
.withRegion(Regions.EU_CENTRAL_1)
.build();
```
I am total Linux noob, having problems with simple commands so please be gentle with solutions requiring some console commands.
|
2020/04/26
|
[
"https://Stackoverflow.com/questions/61445011",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12152413/"
] |
If you're running app on EC2, don't use IAM user.
Instead create IAM **role** with same permissions and assign that role to the instance. If app uses AWS SDK it will be able to pick up credentials without any problems.
In your case problem is probably app's environment being different from yours, if you export credentials in your bash session it will not pass to app if it's loaded under different user or bash session.
|
The DefaultAWSCredentialsProvider has multiple places it will look for credentials. Instead of setting up your credentials as an environment variable, you can set up a credentials profile. See this documentation: [Working with AWS Credentials](https://docs.aws.amazon.com/sdk-for-java/v1/developer-guide/credentials.html).
Make sure you have the [AWS CLI installed](https://docs.aws.amazon.com/cli/latest/userguide/cli-chap-install.html), then you can run the following command to configure your profile: *aws configure*
Click [here](https://docs.aws.amazon.com/cli/latest/userguide/cli-chap-configure.html) for the documentation on the aws configure command.
If you have already configured your aws profile and it still does not work, you have most likely configured the profile for the wrong linux user. For example, if a linux user named tomcat8 is the user who is running your tomcat instance, then you need to set up a credentials profile at /home/tomcat8/.aws/credentials/
|
55,235,565 |
I want to visualize a matrix of integer values between 0 and 255 as a gray-scale image in Qt 5.12. First, I built a sample 256x256 uchar array with values between 0 and 255 in each row. then I tried to show the image with QImage and format\_grayscale as the format. But confusingly, the resulting image contains disturbed pixels in the last rows.
The Resulting Image

I also created a gray-scale color map and tried with format\_indexed8, but the same result. Here is my code.
```
uchar imageArray[256][256];
for (int i = 0; i < 256; i++)
{
for (int j = 0; j < 256; j++)
{
imageArray[i][j] = uchar(j);
}
}
QImage image(&imageArray[0][0],
256,
256,
QImage::Format_Grayscale8);
```
|
2019/03/19
|
[
"https://Stackoverflow.com/questions/55235565",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11224648/"
] |
My guess is your buffer is deallocated and partially overwritten before you can get it displayed. It is your responsability to ensure the data buffer remains valid when using a constructor that does not perform a deep copy.
Quoting from [the Qt documentation](https://doc.qt.io/qt-5/qimage.html#QImage-3):
>
> Constructs an image with the given width, height and format, that uses
> an existing memory buffer, data. The width and height must be
> specified in pixels. bytesPerLine specifies the number of bytes per
> line (stride).
>
>
> The buffer must remain valid throughout the life of the QImage and all
> copies that have not been modified or otherwise detached from the
> original buffer. The image does not delete the buffer at destruction.
> You can provide a function pointer cleanupFunction along with an extra
> pointer cleanupInfo that will be called when the last copy is
> destroyed.
>
>
>
|
You should not use a matrix but an array of size 256x256 = 65535 ,
So instead of :
```
uchar imageArray[256][256];
```
use :
```
uchar imageArray[65536];
```
Then fill your array with the values you want.
Then, call the constructor of QImage :
```
QImage image(imageArray, 256, 256, QImage::Format_Grayscale8);
```
|
5,609,727 |
Can you please suggest some books on Software Architecture, which should talk about how to design software at module level and how those modules will interact. There are numerous books which talks about design patterns which are mostly low level details. I know low level details are also important, but I want list of good design architecture book.
Please also suggest some books which talks about case studies of software architecture.
|
2011/04/10
|
[
"https://Stackoverflow.com/questions/5609727",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2302649/"
] |
I *think* this is the book that came to mind when I first read this question. It talks about various architectural styles like pipes-and-filters, blackboard systems, etc. It's an oldie, and I'll let you judge whether it's a 'goodie'.
[Pattern Oriented Software Architecture](https://rads.stackoverflow.com/amzn/click/com/0471958697)
I also particularly like these two, especially the first. The second starts to dig into lower level design patterns, but it's still awesome in various spots:
[Enterprise Integration Patterns](https://rads.stackoverflow.com/amzn/click/com/0321200683)
[Patterns of Enterprise Application Architecture](https://rads.stackoverflow.com/amzn/click/com/0321127420)
I hope these are what you had in mind.
|
I'm not familiar with books that detail architectures and not design pattern. I mostly use the design books to get an understanding of how I would build such a system and I use sources such as [highscalability](http://highscalability.com/) to learn about the architecture of various companies, just look at the "all time favorites" tab on the right and you will see posts regarding the architecture of youtube, twitter, google, amazon, flickr and even [this site](http://highscalability.com/blog/2011/3/3/stack-overflow-architecture-update-now-at-95-million-page-vi.html)...
|
5,609,727 |
Can you please suggest some books on Software Architecture, which should talk about how to design software at module level and how those modules will interact. There are numerous books which talks about design patterns which are mostly low level details. I know low level details are also important, but I want list of good design architecture book.
Please also suggest some books which talks about case studies of software architecture.
|
2011/04/10
|
[
"https://Stackoverflow.com/questions/5609727",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2302649/"
] |
Where can you get knowledge about software architecture? One place is your experience building systems. Another is conversations with other developers or reading their code. Yet another place is books. I am the author of a book on software architecture ([Just Enough Software Architecture](http://rhinoresearch.com/content/software-architecture-book)) but let me instead point you to some classics:
* [Software Architecture in Practice (Bass, Clements, Kazman)](https://rads.stackoverflow.com/amzn/click/com/0321154959). This book from the Software Engineering Institute (SEI) describes how architects should think about problems. It describes the importance of quality attributes (performance, security, modifiability, etc.) and how to make tradeoffs between them, since you cannot maximize all of them.
* [Documenting Software Architectures (lots of SEI/CMU authors)](https://rads.stackoverflow.com/amzn/click/com/0321552687). The title of this book is a bit scary, because many people are trying to avoid writing shelfware documents. But the wonderful thing about the book is that it describes the standard architectural styles / patterns, notations for describing structure and behavior, and a conceptual model of understanding architectures. All these are valuable even if you only ever sketch on a whiteboard.
* [Software Systems Architecture (Rosanski and Woods)](https://rads.stackoverflow.com/amzn/click/com/0321112296). Goes into detail about how to think about a system from multiple perspectives (views). What I like particularly is that it gives checklists for ensuring that a particular concern (say security) has been handled.
* [Essential Software Architecture (Gorton)](https://rads.stackoverflow.com/amzn/click/com/3540287132). Small, straightforward book on IT architecture. Covers the different kinds of things you'll see (databases, event busses, app servers, etc.)
That's just a short list and just because I didn't list something doesn't mean it's a bad book. If you are looking something free to read immediately, I have [three chapters of my book](http://rhinoresearch.com/files/Just_Enough_Software_Architecture__Fairbanks_2010-demo.pdf) available for download on my website.
|
I'm not familiar with books that detail architectures and not design pattern. I mostly use the design books to get an understanding of how I would build such a system and I use sources such as [highscalability](http://highscalability.com/) to learn about the architecture of various companies, just look at the "all time favorites" tab on the right and you will see posts regarding the architecture of youtube, twitter, google, amazon, flickr and even [this site](http://highscalability.com/blog/2011/3/3/stack-overflow-architecture-update-now-at-95-million-page-vi.html)...
|
5,609,727 |
Can you please suggest some books on Software Architecture, which should talk about how to design software at module level and how those modules will interact. There are numerous books which talks about design patterns which are mostly low level details. I know low level details are also important, but I want list of good design architecture book.
Please also suggest some books which talks about case studies of software architecture.
|
2011/04/10
|
[
"https://Stackoverflow.com/questions/5609727",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2302649/"
] |
Where can you get knowledge about software architecture? One place is your experience building systems. Another is conversations with other developers or reading their code. Yet another place is books. I am the author of a book on software architecture ([Just Enough Software Architecture](http://rhinoresearch.com/content/software-architecture-book)) but let me instead point you to some classics:
* [Software Architecture in Practice (Bass, Clements, Kazman)](https://rads.stackoverflow.com/amzn/click/com/0321154959). This book from the Software Engineering Institute (SEI) describes how architects should think about problems. It describes the importance of quality attributes (performance, security, modifiability, etc.) and how to make tradeoffs between them, since you cannot maximize all of them.
* [Documenting Software Architectures (lots of SEI/CMU authors)](https://rads.stackoverflow.com/amzn/click/com/0321552687). The title of this book is a bit scary, because many people are trying to avoid writing shelfware documents. But the wonderful thing about the book is that it describes the standard architectural styles / patterns, notations for describing structure and behavior, and a conceptual model of understanding architectures. All these are valuable even if you only ever sketch on a whiteboard.
* [Software Systems Architecture (Rosanski and Woods)](https://rads.stackoverflow.com/amzn/click/com/0321112296). Goes into detail about how to think about a system from multiple perspectives (views). What I like particularly is that it gives checklists for ensuring that a particular concern (say security) has been handled.
* [Essential Software Architecture (Gorton)](https://rads.stackoverflow.com/amzn/click/com/3540287132). Small, straightforward book on IT architecture. Covers the different kinds of things you'll see (databases, event busses, app servers, etc.)
That's just a short list and just because I didn't list something doesn't mean it's a bad book. If you are looking something free to read immediately, I have [three chapters of my book](http://rhinoresearch.com/files/Just_Enough_Software_Architecture__Fairbanks_2010-demo.pdf) available for download on my website.
|
I *think* this is the book that came to mind when I first read this question. It talks about various architectural styles like pipes-and-filters, blackboard systems, etc. It's an oldie, and I'll let you judge whether it's a 'goodie'.
[Pattern Oriented Software Architecture](https://rads.stackoverflow.com/amzn/click/com/0471958697)
I also particularly like these two, especially the first. The second starts to dig into lower level design patterns, but it's still awesome in various spots:
[Enterprise Integration Patterns](https://rads.stackoverflow.com/amzn/click/com/0321200683)
[Patterns of Enterprise Application Architecture](https://rads.stackoverflow.com/amzn/click/com/0321127420)
I hope these are what you had in mind.
|
325,201 |
As from the title.
I've been receiving this from a security guard, when attending a developer conference, well, a bit overdressed (wearing a suit where all the other nerds just appeared in t-shirt, jeans and sneakers).
But I've also heard that otherwise (not thrown on me, the above anecdote was my only personal experience).
Well, I somehow felt that it's not a compliment, but a subtle insult / belittlement.
I'm not a native speaker. Can someone explain what's the background of that phrase, or where's the joke in it?
|
2016/05/12
|
[
"https://english.stackexchange.com/questions/325201",
"https://english.stackexchange.com",
"https://english.stackexchange.com/users/85265/"
] |
It is impossible to tell from the minimal description of the circumstances surrounding the guard's comment what his intentions were in saying "Nice shoes." On the one hand, there is at least a possibility that the intention was sincerely to compliment you on your shoes. After all, some consultants recommend it as an ingratiating strategy. From David Topus, [*Talk to Strangers: How Everyday, Random Encounters Can Expand Your Business, Career, Income, and Life*](https://books.google.com/books?id=4aBCioax4UEC&pg=PA69&lpg=PA69&dq=%22nice+shoes%22+%22nice+tie%22&source=bl&ots=5lEl8XZp1l&sig=yH_TUisS2LIOoqZEtV7WJ5QVKss&hl=en&sa=X&ved=0ahUKEwi3v_CFjtXMAhVM_WMKHWgRCM4Q6AEIRjAL#v=onepage&q=%22nice%20shoes%22%20%22nice%20tie%22&f=false) (2012):
>
> Show sensitivity to and awareness of the other person as much as possible. Any positive comment you can make about the other person allows you to accomplish this. You can never go wrong with a compliment: nice suit, **nice shoes**, nice tie, nice purse, nice ring, nice briefcase, and so on. These will get you going in a great conversation direction.
>
>
>
On the other hand, the guard probably wasn't trying to butter you up in order to expand his business, career, income, and life—and you note that you were dressed rather more formally than other attendees at the conference—so it's possible that he was calling out a difference that you were already feeling a bit awkward or self-conscious about, as a form of teasing.
Disapproving references (couched as compliments) to unconventional dress have a long history in business and social settings. I remember reading an article years ago about the extreme rigidity of the unspoken dress code at a well-established San Francisco law firm. The author recounted how he had once arrived at work wearing a yellow, long-sleeve button-down shirt, instead of the standard white, long-sleeve button-down shirt that the unspoken code insisted upon—and one of the partners at the firm, who rarely had anything to say to him, said in passing, "Nice shirt." The author says that he immediately recognized the comment as a rebuke: to have one's clothing choices mentioned at all at the firm was a form of indirect criticism.
Something similar happens in Virginia Woolf's short story, "[The New Dress](https://books.google.com/books?id=o1AbAgAAQBAJ&pg=PT2078&dq=%22Mabel%27s+got+a+new+dress%22&hl=en&sa=X&ved=0ahUKEwiVutXajdXMAhVR52MKHUs4DrwQ6AEIPDAF#v=onepage&q=%22Mabel%27s%20got%20a%20new%20dress%22&f=false)," where a character named Mabel Waring convinces herself to alter an old-fashioned yellow dress and wear it to a fancy party at Mrs. Dalloway's house. Feeling more and more like a fly trapped and liable to drown in a saucer of milk, she intercepts a well-tailored acquaintance, trying to put herself at ease:
>
> "It's so old-fashioned," she said to Charles Burt, making him stop (which by itself he hated) on his way to talk to someone else.
>
>
> She meant, or she tried to make herself think that she meant, that it was the picture [on the wall] and not her dress, that was old-fashioned. And one word of praise, one word of affection from Charles would have made all the difference for her at that moment. If he had only said, "Mabel, you're looking charming tonight!" it would have changed her life. But then she ought to have been truthful and direct. Charles said nothing of the kind, of course. He was malice itself. He saw through one, especially if one were feeling particularly mean, paltry, or feeble-minded.
>
>
> "Mabel's got a new dress!" he said, and the poor fly was absolutely shoved into the middle of the saucer [of milk].
>
>
>
---
In a comment above, NVZ cites an entry for "[nice shoes](https://www.urbandictionary.com/define.php?term=Nice%20Shoes)" at Urban Dictionary indicating that the phrase may be used as pick-up line—a sexual come-on. But Urban Dictionary also has the [following entry](http://www.urbandictionary.com/define.php?term=resplect), which uses "nice shoes" as a straightforward compliment without ulterior meaning:
>
> **resplect.** When you reflect the respect. [Example 1:] "Hey man you're wearing a nice tie today" "No dude, I like your tie." Tie resplect [Example 2:] "**Nice shoes**" "No you got nice shoes" Shoes resplect
>
>
>
In short, the guard may have intended "Nice shoes" as a simple compliment, or he may have said it to discomfit you because you were not dressed like most of the other conference attendees. It is highly unlikely that he was trying to proposition you.
|
This complement was likely genuine but likely also meant as a humorous, slightly sarcastic understatement.
It's a stereotype almost to the point of cliche in business that you can tell who really has money by looking not at their suit, but at their shoes. The same mentality is also behind the term "well-heeled" meaning wealthy; shoes typically have a pretty hard life as clothing, and it's very tempting to cut corners and wear a more durable or simply a cheaper pair. Expensive shoes in good condition are a mark of someone with enough money to keep them that way and enough attention to detail to care, while someone more practically minded or less attentive might try to get away with a more durable or cheaper and less dressy shoe. The complement, in this context, carries the hidden meaning of "I have noticed that you are well-put-together, head to foot, and I know what that means".
However, as you noticed, you've been showing up significantly overdressed relative to the others in the room. That's because the Internet Age has ushered in a new well-to-do, in the vein of "I'm wealthy, important or otherwise valuable enough that I don't have to impress you with my clothes". In this context the compliment is meant as a humorous understatement more than anything else: "you are so well-dressed compared to your peers that I'm going to single out the least important element of your ensemble to complement". The doorman could just as easily have said, "nice pocket square" if you happened to be sporting one.
|
12,375,739 |
I am having problems with the following statement, I know its probably something small and silly but I cant seem to find the solution.
```
$field_sql = 'SHOW FIELDS FROM '.$table ' WHERE FIELD '=''.$column';
```
|
2012/09/11
|
[
"https://Stackoverflow.com/questions/12375739",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1658413/"
] |
You're missing a dot and have quotes when you don't need them:
```
$field_sql = 'SHOW FIELDS FROM ' . $table . ' WHERE FIELD = ' . $column;
^ ^^^ ^
Missing Removed extra quotes
```
However, for SQL string values, you probably want the quotes, so you can use different quotes than the ones you're using to denote the string:
```
$field_sql = 'SHOW FIELDS FROM `' . $table . '` WHERE FIELD = "' . $column . '"';
```
I also added backticks for the table name.
|
```
$field_sql = 'SHOW FIELDS FROM ' . $table . ' WHERE FIELD = '.$column;
```
|
12,375,739 |
I am having problems with the following statement, I know its probably something small and silly but I cant seem to find the solution.
```
$field_sql = 'SHOW FIELDS FROM '.$table ' WHERE FIELD '=''.$column';
```
|
2012/09/11
|
[
"https://Stackoverflow.com/questions/12375739",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1658413/"
] |
You're missing a dot and have quotes when you don't need them:
```
$field_sql = 'SHOW FIELDS FROM ' . $table . ' WHERE FIELD = ' . $column;
^ ^^^ ^
Missing Removed extra quotes
```
However, for SQL string values, you probably want the quotes, so you can use different quotes than the ones you're using to denote the string:
```
$field_sql = 'SHOW FIELDS FROM `' . $table . '` WHERE FIELD = "' . $column . '"';
```
I also added backticks for the table name.
|
You cna try with
```
$field_sql= 'SHOW FIELDS FROM ' . $table . ' WHERE FIELD =' . $column;
```
|
84,679 |
Is there a 'psychic mode' plugin for kopete?
Psychic mode is a pidgin plugin that opens up the chat dialog as soon as someone starts talking with you, before message is sent. i'm looking for the same functionality in kopete.
|
2009/12/17
|
[
"https://superuser.com/questions/84679",
"https://superuser.com",
"https://superuser.com/users/17980/"
] |
Here you go : [kopete psyko 0.1](http://opendesktop.org/content/show.php?content=121585),
Same plugin [download link 2](http://linux.softpedia.com/get/Communications/Chat/kopete-psyko-55357.shtml)
Hope this helps!
|
In Configuration->Behavior->General, there is "Message Handling": "Open messages instantly".
|
13,600,351 |
This code works perfect for crome and firefox.. but error in IE8
```
if($('#soundcheck').is(':checked')){
//alert('checked');
var audio = document.createElement('audio');
document.body.appendChild(audio);
audio.src = system_base_url+'/sound/horn.wav';
audio.play();
}
```
IE8 says: Object doesn't support this property or method, and it points to :
```
audio.play();
```
Anyone having similar experience with IE8?
Regards
|
2012/11/28
|
[
"https://Stackoverflow.com/questions/13600351",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1713941/"
] |
The `<audio>` tag is HTML5 and is only supported in newer browsers, such as Internet Explorer 9, Firefox, Opera, Chrome, and Safari.
|
Had the same problem! Try:
```
<a href="javascript: void(0);" onclick="playSound('sound.mp3');">...</a>
<script language="javascript" type="text/javascript">
function playSound(soundfile) {
document.getElementById("dummy").innerHTML=
"<embed src=\""+soundfile+"\" hidden=\"true\" autostart=\"true\" loop=\"false\" />";
}
</script>
```
|
13,600,351 |
This code works perfect for crome and firefox.. but error in IE8
```
if($('#soundcheck').is(':checked')){
//alert('checked');
var audio = document.createElement('audio');
document.body.appendChild(audio);
audio.src = system_base_url+'/sound/horn.wav';
audio.play();
}
```
IE8 says: Object doesn't support this property or method, and it points to :
```
audio.play();
```
Anyone having similar experience with IE8?
Regards
|
2012/11/28
|
[
"https://Stackoverflow.com/questions/13600351",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1713941/"
] |
IE 8 and earlier does not support Audio tag, you need to use some hack.
Hope it can help.
```
<audio id='audio' controls>
<source src="audioes/song.ogg" type="audio/ogg" />
<source src="audioes/song.mp3" type="audio/mp3" />
<div>Your browser doesn't support HTML5 audio</div>
<%--Fall back on the WMP plugin--%>
<object id='mediaPlayer' type="audio/mpeg" width="200" height="40"><param name="src" value="audioes/song.mp3" /></object>
</audio>
<script type="text/javascript">
function play () {
var audio = document.getElementByID('audio');
var mediaPlayer = document.getElementByID('mediaPlayer');
//HTML5 Audio is Supported
if(audio['play'])
{
audio.play();
}
//HTML5 Audio is NOT Supported
else
{
mediaPlayer.object.play();
}
}
</script>
```
|
Had the same problem! Try:
```
<a href="javascript: void(0);" onclick="playSound('sound.mp3');">...</a>
<script language="javascript" type="text/javascript">
function playSound(soundfile) {
document.getElementById("dummy").innerHTML=
"<embed src=\""+soundfile+"\" hidden=\"true\" autostart=\"true\" loop=\"false\" />";
}
</script>
```
|
34,560,936 |
I want to check some user inputs with an `if statement` and depending on them, specify some parameters to send as an `ajax` request.
My approach doesn't work at all. It's just not valid code:
```
$.ajax({
method : "GET",
url : "test.php",
data :
if (...) {
a: "abc",
b: "def"
}else{
b: "ghi",
c: "jkl"
},
success : function(data) {
console.log(data)
},
error : function(data) {
console.log(data);
}
});
```
Does anybody have a better idea?
|
2016/01/01
|
[
"https://Stackoverflow.com/questions/34560936",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/982865/"
] |
I think the cleanest way is to place your condition before the request call :
```
var data;
if (...) {
data = {a: "abc",b: "def"};
}else{
data = {b: "ghi",c: "jkl"};
}
$.ajax({
method : "GET",
url : "test.php",
data : data,
success : function(data) {
console.log(data)
},
error : function(data) {
console.log(data);
}
});
```
Hope this helps.
|
You may use a self executing function to set data as:
```
var i = true;
$.ajax({
method: "GET",
url: '/echo/js/',
data: (function() {
if (i)
return { a: "abc", b: "def" }
else
return { b: "ghi", c: "jkl" }
})(),
complete: function(response) {
console.log(response)
},
error: function() {
console.log("Error")
},
});
```
|
40,728,927 |
I have this table structure:
**product\_skus table**
```
| id |
| 1 |
...
```
**product\_sku\_values table**
```
| product_sku_id | value_id |
| 1 | 1 |
| 1 | 2 |
| 1 | 3 |
...
```
I need the query to find the `product_sku_id`, having the three values ID's (`1`, `2`, and `3`).
I'm trying with this query:
```
select product_sku_id from product_sku_values
where product_sku_values.value_id = 1
or product_sku_values.value_id = 2
or product_sku_values.value_id = 3
group by product_sku_id
having product_sku_id = 1
```
How can I do that? I'm trying lot of possibilities but no one give me the ID that I need. Can somebody help me?
Thanks.
|
2016/11/21
|
[
"https://Stackoverflow.com/questions/40728927",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1535394/"
] |
This is a canonical method:
```
select psv.product_sku_id
from product_sku_values psv
where psv.value_id in (1, 2, 3)
group by psv.product_sku_id
having count(distinct psv.value_id) = 3;
```
If you know that `product_sku_values` have no duplicates, then use `count(*)` in the `having` clause.
|
You can simply use `group by` clause to get all the possible values, e.g.:
```
select product_sku_id, group_concat(value_id)
from product_sku_values
group by product_sku_id;
```
If you are only interested in value\_id 1,2 and 3 then you can add one `where` clause, e.g:
```
select product_sku_id, group_concat(value_id)
from product_sku_values
where value_id in (1,2,3)
group by product_sku_id;
```
|
60,593 |
Looking for movie featuring Dragons vs. Navy (or Army, but the trailer featured battleship trying to shoot the dragons down).
Trailer also showed a dogfight between helicopters and dragons, capping (on the trailer) with a dragon setting a Blackhawk's blades on fire.
|
2014/07/03
|
[
"https://scifi.stackexchange.com/questions/60593",
"https://scifi.stackexchange.com",
"https://scifi.stackexchange.com/users/28220/"
] |
Sounds similar to [Dragon Wars : D-War](https://en.wikipedia.org/wiki/D-War), although I haven't found a specific trailer (of which there are quite a few) with a Blackhawk's blades on fire. Plenty of dragons destroying helicopters in other ways though. Here is a [short trailer](http://www.imdb.com/video/screenplay/vi3466789145), and here is a [longer trailer](https://www.youtube.com/watch?v=YnQXvQ1R4gg). Some of the dialogue in the longer trailer is Korean, but the movie itself is mostly in English.

|
This sounds very like the British film [Reign of Fire](http://en.wikipedia.org/wiki/Reign_of_Fire_%28film%29), which included several scenes of fire-breathing dragons versus helicopters.
The trailer is [here](https://www.youtube.com/watch?v=Wg7bjwEXp7Y) and although there are various helicopter shots there's nothing specifically with the blades on fire.
|
60,593 |
Looking for movie featuring Dragons vs. Navy (or Army, but the trailer featured battleship trying to shoot the dragons down).
Trailer also showed a dogfight between helicopters and dragons, capping (on the trailer) with a dragon setting a Blackhawk's blades on fire.
|
2014/07/03
|
[
"https://scifi.stackexchange.com/questions/60593",
"https://scifi.stackexchange.com",
"https://scifi.stackexchange.com/users/28220/"
] |
I saw that trailer too and then could not find it again , but stumbled across it today ,it is called Crimson Skies
Only other info i could find on this is that it was originaly called Dragon seige but your guess is as good as mine as to wether its movie or game
|
Sounds similar to [Dragon Wars : D-War](https://en.wikipedia.org/wiki/D-War), although I haven't found a specific trailer (of which there are quite a few) with a Blackhawk's blades on fire. Plenty of dragons destroying helicopters in other ways though. Here is a [short trailer](http://www.imdb.com/video/screenplay/vi3466789145), and here is a [longer trailer](https://www.youtube.com/watch?v=YnQXvQ1R4gg). Some of the dialogue in the longer trailer is Korean, but the movie itself is mostly in English.

|
60,593 |
Looking for movie featuring Dragons vs. Navy (or Army, but the trailer featured battleship trying to shoot the dragons down).
Trailer also showed a dogfight between helicopters and dragons, capping (on the trailer) with a dragon setting a Blackhawk's blades on fire.
|
2014/07/03
|
[
"https://scifi.stackexchange.com/questions/60593",
"https://scifi.stackexchange.com",
"https://scifi.stackexchange.com/users/28220/"
] |
Sounds similar to [Dragon Wars : D-War](https://en.wikipedia.org/wiki/D-War), although I haven't found a specific trailer (of which there are quite a few) with a Blackhawk's blades on fire. Plenty of dragons destroying helicopters in other ways though. Here is a [short trailer](http://www.imdb.com/video/screenplay/vi3466789145), and here is a [longer trailer](https://www.youtube.com/watch?v=YnQXvQ1R4gg). Some of the dialogue in the longer trailer is Korean, but the movie itself is mostly in English.

|
MainStay Productions released a trailer on YouTube last year, about a movie project they are working on with BluFire Studios, ostensibly called Crimson Skies.
The premise is that a volcanic island erupts, releasing thousands of dragons from millenia-long slumber, that attack a small fleet of Navy vessels.
I checked on both MainStay and BluFire's websites, neither of which make any mention of the project, which makes me think that the trailer may simply be a "pitch demo" to try and find a studio willing to underwrite it. There is no other mention of the movie, other than the video, that I can find.
Of course, this may also be just another elaborate YouTube hoax.
|
60,593 |
Looking for movie featuring Dragons vs. Navy (or Army, but the trailer featured battleship trying to shoot the dragons down).
Trailer also showed a dogfight between helicopters and dragons, capping (on the trailer) with a dragon setting a Blackhawk's blades on fire.
|
2014/07/03
|
[
"https://scifi.stackexchange.com/questions/60593",
"https://scifi.stackexchange.com",
"https://scifi.stackexchange.com/users/28220/"
] |
I saw that trailer too and then could not find it again , but stumbled across it today ,it is called Crimson Skies
Only other info i could find on this is that it was originaly called Dragon seige but your guess is as good as mine as to wether its movie or game
|
This sounds very like the British film [Reign of Fire](http://en.wikipedia.org/wiki/Reign_of_Fire_%28film%29), which included several scenes of fire-breathing dragons versus helicopters.
The trailer is [here](https://www.youtube.com/watch?v=Wg7bjwEXp7Y) and although there are various helicopter shots there's nothing specifically with the blades on fire.
|
60,593 |
Looking for movie featuring Dragons vs. Navy (or Army, but the trailer featured battleship trying to shoot the dragons down).
Trailer also showed a dogfight between helicopters and dragons, capping (on the trailer) with a dragon setting a Blackhawk's blades on fire.
|
2014/07/03
|
[
"https://scifi.stackexchange.com/questions/60593",
"https://scifi.stackexchange.com",
"https://scifi.stackexchange.com/users/28220/"
] |
This sounds very like the British film [Reign of Fire](http://en.wikipedia.org/wiki/Reign_of_Fire_%28film%29), which included several scenes of fire-breathing dragons versus helicopters.
The trailer is [here](https://www.youtube.com/watch?v=Wg7bjwEXp7Y) and although there are various helicopter shots there's nothing specifically with the blades on fire.
|
MainStay Productions released a trailer on YouTube last year, about a movie project they are working on with BluFire Studios, ostensibly called Crimson Skies.
The premise is that a volcanic island erupts, releasing thousands of dragons from millenia-long slumber, that attack a small fleet of Navy vessels.
I checked on both MainStay and BluFire's websites, neither of which make any mention of the project, which makes me think that the trailer may simply be a "pitch demo" to try and find a studio willing to underwrite it. There is no other mention of the movie, other than the video, that I can find.
Of course, this may also be just another elaborate YouTube hoax.
|
60,593 |
Looking for movie featuring Dragons vs. Navy (or Army, but the trailer featured battleship trying to shoot the dragons down).
Trailer also showed a dogfight between helicopters and dragons, capping (on the trailer) with a dragon setting a Blackhawk's blades on fire.
|
2014/07/03
|
[
"https://scifi.stackexchange.com/questions/60593",
"https://scifi.stackexchange.com",
"https://scifi.stackexchange.com/users/28220/"
] |
I saw that trailer too and then could not find it again , but stumbled across it today ,it is called Crimson Skies
Only other info i could find on this is that it was originaly called Dragon seige but your guess is as good as mine as to wether its movie or game
|
MainStay Productions released a trailer on YouTube last year, about a movie project they are working on with BluFire Studios, ostensibly called Crimson Skies.
The premise is that a volcanic island erupts, releasing thousands of dragons from millenia-long slumber, that attack a small fleet of Navy vessels.
I checked on both MainStay and BluFire's websites, neither of which make any mention of the project, which makes me think that the trailer may simply be a "pitch demo" to try and find a studio willing to underwrite it. There is no other mention of the movie, other than the video, that I can find.
Of course, this may also be just another elaborate YouTube hoax.
|
41,780,284 |
I have an array **InputFields**, in my situation - **six InputFields**. How can I get the text and save it from each InputField?
Everything should work like this: I turn on the app, I change one, two or all of the input field, then turn off the application. Again, I turn on, and input fields have to be values which I wrote earlier.
I have a code that must seem to work properly, but this code works like this: it takes only the last value entered by the user and writes it to the last input field.
```
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class SaveText : MonoBehaviour {
public GameObject[] InputFields;
public static string n;
public void Start ()
{
for(int i = 0; i < InputFields.Length; i++)
{
InputFields[i].GetComponent<InputField> ().text = PlayerPrefs.GetString (InputFields[i].name);
Debug.Log (PlayerPrefs.GetString (InputFields[i].name));
n = InputFields[i].name;
var input = InputFields[i].GetComponent<InputField> ();
var se = new InputField.SubmitEvent ();
se.AddListener (SubmitName);
input.onEndEdit = se;
}
}
public void SubmitName(string arg)
{
PlayerPrefs.SetString (n, arg);
}
```
An array of input fields I initialize dragging in Unity each input field in free cell in Script Component.
|
2017/01/21
|
[
"https://Stackoverflow.com/questions/41780284",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7450427/"
] |
To change the list row header style you must use custom [ListRowPresenter](https://developer.android.com/reference/android/support/v17/leanback/widget/ListRowPresenter.html):
```
public class CustomListRowPresenter extends ListRowPresenter {
public CustomListRowPresenter() {
super();
setHeaderPresenter(new CustomRowHeaderPresenter());
}
}
public class CustomRowHeaderPresenter extends RowHeaderPresenter {
@Override
public Presenter.ViewHolder onCreateViewHolder(ViewGroup parent) {
Presenter.ViewHolder viewHolder = super.onCreateViewHolder(parent);
RowHeaderView rowHeaderView = (RowHeaderView) viewHolder.view;
rowHeaderView.setTypeface(...);
rowHeaderView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, ...);
return viewHolder;
}
}
```
Haven't had any direct experience with BrowseFragment, but I expect there is some kind of a custom presenter too.
|
Another simple way to set color for header text is to override leanback color in xml:
```
<color name="lb_browse_header_color">#f00</color>
```
advantage/drawback: it set color for all headers.
|
41,780,284 |
I have an array **InputFields**, in my situation - **six InputFields**. How can I get the text and save it from each InputField?
Everything should work like this: I turn on the app, I change one, two or all of the input field, then turn off the application. Again, I turn on, and input fields have to be values which I wrote earlier.
I have a code that must seem to work properly, but this code works like this: it takes only the last value entered by the user and writes it to the last input field.
```
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class SaveText : MonoBehaviour {
public GameObject[] InputFields;
public static string n;
public void Start ()
{
for(int i = 0; i < InputFields.Length; i++)
{
InputFields[i].GetComponent<InputField> ().text = PlayerPrefs.GetString (InputFields[i].name);
Debug.Log (PlayerPrefs.GetString (InputFields[i].name));
n = InputFields[i].name;
var input = InputFields[i].GetComponent<InputField> ();
var se = new InputField.SubmitEvent ();
se.AddListener (SubmitName);
input.onEndEdit = se;
}
}
public void SubmitName(string arg)
{
PlayerPrefs.SetString (n, arg);
}
```
An array of input fields I initialize dragging in Unity each input field in free cell in Script Component.
|
2017/01/21
|
[
"https://Stackoverflow.com/questions/41780284",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7450427/"
] |
To change the list row header style you must use custom [ListRowPresenter](https://developer.android.com/reference/android/support/v17/leanback/widget/ListRowPresenter.html):
```
public class CustomListRowPresenter extends ListRowPresenter {
public CustomListRowPresenter() {
super();
setHeaderPresenter(new CustomRowHeaderPresenter());
}
}
public class CustomRowHeaderPresenter extends RowHeaderPresenter {
@Override
public Presenter.ViewHolder onCreateViewHolder(ViewGroup parent) {
Presenter.ViewHolder viewHolder = super.onCreateViewHolder(parent);
RowHeaderView rowHeaderView = (RowHeaderView) viewHolder.view;
rowHeaderView.setTypeface(...);
rowHeaderView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, ...);
return viewHolder;
}
}
```
Haven't had any direct experience with BrowseFragment, but I expect there is some kind of a custom presenter too.
|
Might be a bit late but for whosoever is still looking
```
<style name="AppTheme" parent="@style/Theme.AppCompat.Leanback">
<item name="rowHeaderStyle">@style/MediaHeader</item>
</style>
<style name="MediaHeader">
<item name="android:textAppearance">@style/MyMediaTextStyle</item>
</style>
<style name="MyMediaTextStyle">
<item name="android:fontFamily">@font/roboto</item>
<item name="android:textSize">30sp</item>
<item name="android:textColor">@android:color/white</item>
</style>
```
|
41,780,284 |
I have an array **InputFields**, in my situation - **six InputFields**. How can I get the text and save it from each InputField?
Everything should work like this: I turn on the app, I change one, two or all of the input field, then turn off the application. Again, I turn on, and input fields have to be values which I wrote earlier.
I have a code that must seem to work properly, but this code works like this: it takes only the last value entered by the user and writes it to the last input field.
```
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class SaveText : MonoBehaviour {
public GameObject[] InputFields;
public static string n;
public void Start ()
{
for(int i = 0; i < InputFields.Length; i++)
{
InputFields[i].GetComponent<InputField> ().text = PlayerPrefs.GetString (InputFields[i].name);
Debug.Log (PlayerPrefs.GetString (InputFields[i].name));
n = InputFields[i].name;
var input = InputFields[i].GetComponent<InputField> ();
var se = new InputField.SubmitEvent ();
se.AddListener (SubmitName);
input.onEndEdit = se;
}
}
public void SubmitName(string arg)
{
PlayerPrefs.SetString (n, arg);
}
```
An array of input fields I initialize dragging in Unity each input field in free cell in Script Component.
|
2017/01/21
|
[
"https://Stackoverflow.com/questions/41780284",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7450427/"
] |
To change the list row header style you must use custom [ListRowPresenter](https://developer.android.com/reference/android/support/v17/leanback/widget/ListRowPresenter.html):
```
public class CustomListRowPresenter extends ListRowPresenter {
public CustomListRowPresenter() {
super();
setHeaderPresenter(new CustomRowHeaderPresenter());
}
}
public class CustomRowHeaderPresenter extends RowHeaderPresenter {
@Override
public Presenter.ViewHolder onCreateViewHolder(ViewGroup parent) {
Presenter.ViewHolder viewHolder = super.onCreateViewHolder(parent);
RowHeaderView rowHeaderView = (RowHeaderView) viewHolder.view;
rowHeaderView.setTypeface(...);
rowHeaderView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, ...);
return viewHolder;
}
}
```
Haven't had any direct experience with BrowseFragment, but I expect there is some kind of a custom presenter too.
|
Change rowHeaderStyle in your theme
`<style name="Header" parent="Widget.Leanback.Header"> <item name="android:textAppearance">@style/YourApperance</item> </style>`
|
41,780,284 |
I have an array **InputFields**, in my situation - **six InputFields**. How can I get the text and save it from each InputField?
Everything should work like this: I turn on the app, I change one, two or all of the input field, then turn off the application. Again, I turn on, and input fields have to be values which I wrote earlier.
I have a code that must seem to work properly, but this code works like this: it takes only the last value entered by the user and writes it to the last input field.
```
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class SaveText : MonoBehaviour {
public GameObject[] InputFields;
public static string n;
public void Start ()
{
for(int i = 0; i < InputFields.Length; i++)
{
InputFields[i].GetComponent<InputField> ().text = PlayerPrefs.GetString (InputFields[i].name);
Debug.Log (PlayerPrefs.GetString (InputFields[i].name));
n = InputFields[i].name;
var input = InputFields[i].GetComponent<InputField> ();
var se = new InputField.SubmitEvent ();
se.AddListener (SubmitName);
input.onEndEdit = se;
}
}
public void SubmitName(string arg)
{
PlayerPrefs.SetString (n, arg);
}
```
An array of input fields I initialize dragging in Unity each input field in free cell in Script Component.
|
2017/01/21
|
[
"https://Stackoverflow.com/questions/41780284",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7450427/"
] |
```
public class CustomListRowPresenter extends ListRowPresenter {
public CustomListRowPresenter() {
super();
setHeaderPresenter(new CustomRowHeaderPresenter());
}
}
class CustomRowHeaderPresenter extends RowHeaderPresenter {
@Override
public void onBindViewHolder(Presenter.ViewHolder viewHolder, Object item) {
HeaderItem headerItem = item == null ? null : ((Row) item).getHeaderItem();
RowHeaderPresenter.ViewHolder vh = (RowHeaderPresenter.ViewHolder) viewHolder;
TextView title = vh.view.findViewById(R.id.row_header);
if(!TextUtils.isEmpty(headerItem.getName())) {
title.setText(headerItem.getName());
title.setTextColor(ContextCompat.getColor(FiosTVApplication.getAppContext(),
R.color.white));
title.setTypeface(ResourcesCompat.getFont(title.getContext(), R.font.nhaasgroteskdsstd_bold));
title.setTextSize(TypedValue.COMPLEX_UNIT_SP,16);
}
}
}
```
|
Another simple way to set color for header text is to override leanback color in xml:
```
<color name="lb_browse_header_color">#f00</color>
```
advantage/drawback: it set color for all headers.
|
41,780,284 |
I have an array **InputFields**, in my situation - **six InputFields**. How can I get the text and save it from each InputField?
Everything should work like this: I turn on the app, I change one, two or all of the input field, then turn off the application. Again, I turn on, and input fields have to be values which I wrote earlier.
I have a code that must seem to work properly, but this code works like this: it takes only the last value entered by the user and writes it to the last input field.
```
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class SaveText : MonoBehaviour {
public GameObject[] InputFields;
public static string n;
public void Start ()
{
for(int i = 0; i < InputFields.Length; i++)
{
InputFields[i].GetComponent<InputField> ().text = PlayerPrefs.GetString (InputFields[i].name);
Debug.Log (PlayerPrefs.GetString (InputFields[i].name));
n = InputFields[i].name;
var input = InputFields[i].GetComponent<InputField> ();
var se = new InputField.SubmitEvent ();
se.AddListener (SubmitName);
input.onEndEdit = se;
}
}
public void SubmitName(string arg)
{
PlayerPrefs.SetString (n, arg);
}
```
An array of input fields I initialize dragging in Unity each input field in free cell in Script Component.
|
2017/01/21
|
[
"https://Stackoverflow.com/questions/41780284",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7450427/"
] |
```
public class CustomListRowPresenter extends ListRowPresenter {
public CustomListRowPresenter() {
super();
setHeaderPresenter(new CustomRowHeaderPresenter());
}
}
class CustomRowHeaderPresenter extends RowHeaderPresenter {
@Override
public void onBindViewHolder(Presenter.ViewHolder viewHolder, Object item) {
HeaderItem headerItem = item == null ? null : ((Row) item).getHeaderItem();
RowHeaderPresenter.ViewHolder vh = (RowHeaderPresenter.ViewHolder) viewHolder;
TextView title = vh.view.findViewById(R.id.row_header);
if(!TextUtils.isEmpty(headerItem.getName())) {
title.setText(headerItem.getName());
title.setTextColor(ContextCompat.getColor(FiosTVApplication.getAppContext(),
R.color.white));
title.setTypeface(ResourcesCompat.getFont(title.getContext(), R.font.nhaasgroteskdsstd_bold));
title.setTextSize(TypedValue.COMPLEX_UNIT_SP,16);
}
}
}
```
|
Might be a bit late but for whosoever is still looking
```
<style name="AppTheme" parent="@style/Theme.AppCompat.Leanback">
<item name="rowHeaderStyle">@style/MediaHeader</item>
</style>
<style name="MediaHeader">
<item name="android:textAppearance">@style/MyMediaTextStyle</item>
</style>
<style name="MyMediaTextStyle">
<item name="android:fontFamily">@font/roboto</item>
<item name="android:textSize">30sp</item>
<item name="android:textColor">@android:color/white</item>
</style>
```
|
41,780,284 |
I have an array **InputFields**, in my situation - **six InputFields**. How can I get the text and save it from each InputField?
Everything should work like this: I turn on the app, I change one, two or all of the input field, then turn off the application. Again, I turn on, and input fields have to be values which I wrote earlier.
I have a code that must seem to work properly, but this code works like this: it takes only the last value entered by the user and writes it to the last input field.
```
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class SaveText : MonoBehaviour {
public GameObject[] InputFields;
public static string n;
public void Start ()
{
for(int i = 0; i < InputFields.Length; i++)
{
InputFields[i].GetComponent<InputField> ().text = PlayerPrefs.GetString (InputFields[i].name);
Debug.Log (PlayerPrefs.GetString (InputFields[i].name));
n = InputFields[i].name;
var input = InputFields[i].GetComponent<InputField> ();
var se = new InputField.SubmitEvent ();
se.AddListener (SubmitName);
input.onEndEdit = se;
}
}
public void SubmitName(string arg)
{
PlayerPrefs.SetString (n, arg);
}
```
An array of input fields I initialize dragging in Unity each input field in free cell in Script Component.
|
2017/01/21
|
[
"https://Stackoverflow.com/questions/41780284",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7450427/"
] |
```
public class CustomListRowPresenter extends ListRowPresenter {
public CustomListRowPresenter() {
super();
setHeaderPresenter(new CustomRowHeaderPresenter());
}
}
class CustomRowHeaderPresenter extends RowHeaderPresenter {
@Override
public void onBindViewHolder(Presenter.ViewHolder viewHolder, Object item) {
HeaderItem headerItem = item == null ? null : ((Row) item).getHeaderItem();
RowHeaderPresenter.ViewHolder vh = (RowHeaderPresenter.ViewHolder) viewHolder;
TextView title = vh.view.findViewById(R.id.row_header);
if(!TextUtils.isEmpty(headerItem.getName())) {
title.setText(headerItem.getName());
title.setTextColor(ContextCompat.getColor(FiosTVApplication.getAppContext(),
R.color.white));
title.setTypeface(ResourcesCompat.getFont(title.getContext(), R.font.nhaasgroteskdsstd_bold));
title.setTextSize(TypedValue.COMPLEX_UNIT_SP,16);
}
}
}
```
|
Change rowHeaderStyle in your theme
`<style name="Header" parent="Widget.Leanback.Header"> <item name="android:textAppearance">@style/YourApperance</item> </style>`
|
41,780,284 |
I have an array **InputFields**, in my situation - **six InputFields**. How can I get the text and save it from each InputField?
Everything should work like this: I turn on the app, I change one, two or all of the input field, then turn off the application. Again, I turn on, and input fields have to be values which I wrote earlier.
I have a code that must seem to work properly, but this code works like this: it takes only the last value entered by the user and writes it to the last input field.
```
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class SaveText : MonoBehaviour {
public GameObject[] InputFields;
public static string n;
public void Start ()
{
for(int i = 0; i < InputFields.Length; i++)
{
InputFields[i].GetComponent<InputField> ().text = PlayerPrefs.GetString (InputFields[i].name);
Debug.Log (PlayerPrefs.GetString (InputFields[i].name));
n = InputFields[i].name;
var input = InputFields[i].GetComponent<InputField> ();
var se = new InputField.SubmitEvent ();
se.AddListener (SubmitName);
input.onEndEdit = se;
}
}
public void SubmitName(string arg)
{
PlayerPrefs.SetString (n, arg);
}
```
An array of input fields I initialize dragging in Unity each input field in free cell in Script Component.
|
2017/01/21
|
[
"https://Stackoverflow.com/questions/41780284",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7450427/"
] |
Another simple way to set color for header text is to override leanback color in xml:
```
<color name="lb_browse_header_color">#f00</color>
```
advantage/drawback: it set color for all headers.
|
Might be a bit late but for whosoever is still looking
```
<style name="AppTheme" parent="@style/Theme.AppCompat.Leanback">
<item name="rowHeaderStyle">@style/MediaHeader</item>
</style>
<style name="MediaHeader">
<item name="android:textAppearance">@style/MyMediaTextStyle</item>
</style>
<style name="MyMediaTextStyle">
<item name="android:fontFamily">@font/roboto</item>
<item name="android:textSize">30sp</item>
<item name="android:textColor">@android:color/white</item>
</style>
```
|
41,780,284 |
I have an array **InputFields**, in my situation - **six InputFields**. How can I get the text and save it from each InputField?
Everything should work like this: I turn on the app, I change one, two or all of the input field, then turn off the application. Again, I turn on, and input fields have to be values which I wrote earlier.
I have a code that must seem to work properly, but this code works like this: it takes only the last value entered by the user and writes it to the last input field.
```
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class SaveText : MonoBehaviour {
public GameObject[] InputFields;
public static string n;
public void Start ()
{
for(int i = 0; i < InputFields.Length; i++)
{
InputFields[i].GetComponent<InputField> ().text = PlayerPrefs.GetString (InputFields[i].name);
Debug.Log (PlayerPrefs.GetString (InputFields[i].name));
n = InputFields[i].name;
var input = InputFields[i].GetComponent<InputField> ();
var se = new InputField.SubmitEvent ();
se.AddListener (SubmitName);
input.onEndEdit = se;
}
}
public void SubmitName(string arg)
{
PlayerPrefs.SetString (n, arg);
}
```
An array of input fields I initialize dragging in Unity each input field in free cell in Script Component.
|
2017/01/21
|
[
"https://Stackoverflow.com/questions/41780284",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7450427/"
] |
Another simple way to set color for header text is to override leanback color in xml:
```
<color name="lb_browse_header_color">#f00</color>
```
advantage/drawback: it set color for all headers.
|
Change rowHeaderStyle in your theme
`<style name="Header" parent="Widget.Leanback.Header"> <item name="android:textAppearance">@style/YourApperance</item> </style>`
|
22,060,885 |
here is my code
```
SELECT h.ENTERED_DATE,
d.DENOMINATION,
sum(h.invoice_total-h.TOTTAL_DISCOUNT)as amount
FROM sales_details d
LEFT JOIN sales_header h
ON d.invoice_id=h.invoice_id
WHERE entered_by='2254'
--HERE IS NEED TO GET DETAILS CURRENT MONTH 1st Date to Sysdate
GROUP BY
ENTERED_DATE,
d.DENOMINATION
ORDER BY
entered_date,
denomination
```
* In my application just send only **sysdate** as parameter.
**no need to SYSDATE-30.
need 1st date to SYSDATE**
here shows my two tables
**sales\_header table**

**sales\_details table**

|
2014/02/27
|
[
"https://Stackoverflow.com/questions/22060885",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2224206/"
] |
try this:
```
WHERE entered_by='2254'
AND ENTERED_DATE BETWEEN trunc (sysdate, 'mm')/*current month*/ AND SYSDATE
```
|
Try :
```
SELECT TRUNC(SYSDATE, 'month') FROM DUAL;
```
|
22,060,885 |
here is my code
```
SELECT h.ENTERED_DATE,
d.DENOMINATION,
sum(h.invoice_total-h.TOTTAL_DISCOUNT)as amount
FROM sales_details d
LEFT JOIN sales_header h
ON d.invoice_id=h.invoice_id
WHERE entered_by='2254'
--HERE IS NEED TO GET DETAILS CURRENT MONTH 1st Date to Sysdate
GROUP BY
ENTERED_DATE,
d.DENOMINATION
ORDER BY
entered_date,
denomination
```
* In my application just send only **sysdate** as parameter.
**no need to SYSDATE-30.
need 1st date to SYSDATE**
here shows my two tables
**sales\_header table**

**sales\_details table**

|
2014/02/27
|
[
"https://Stackoverflow.com/questions/22060885",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2224206/"
] |
Mudassir's answer worked for me but I would also check the year to make sure you are not getting last year's records.
```
WHERE TO_CHAR(ENTERED_DATE, 'mm') = TO_CHAR(SYSDATE, 'mm')
AND TO_CHAR(ENTERED_DATE, 'yyyy') = TO_CHAR(SYSDATE, 'yyyy')
```
Also, if you are running a large query, functions in your `WHERE` clause can slow it down. If so, you may want to consider a function based index.
|
Try :
```
SELECT TRUNC(SYSDATE, 'month') FROM DUAL;
```
|
22,060,885 |
here is my code
```
SELECT h.ENTERED_DATE,
d.DENOMINATION,
sum(h.invoice_total-h.TOTTAL_DISCOUNT)as amount
FROM sales_details d
LEFT JOIN sales_header h
ON d.invoice_id=h.invoice_id
WHERE entered_by='2254'
--HERE IS NEED TO GET DETAILS CURRENT MONTH 1st Date to Sysdate
GROUP BY
ENTERED_DATE,
d.DENOMINATION
ORDER BY
entered_date,
denomination
```
* In my application just send only **sysdate** as parameter.
**no need to SYSDATE-30.
need 1st date to SYSDATE**
here shows my two tables
**sales\_header table**

**sales\_details table**

|
2014/02/27
|
[
"https://Stackoverflow.com/questions/22060885",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2224206/"
] |
Try :
```
SELECT TRUNC(SYSDATE, 'month') FROM DUAL;
```
|
```
select 'WITHIN' as result
from dual
where '28-FEB-2019' between trunc(last_day(add_months(sysdate, -1))+1) and trunc(last_day(sysdate));
```
Take care because there are many examples that are using just the month and because of that you could get records from all the year, year is not being considered.
Also as you can see I am using trunc it is to avoid timing inconsistencies and just use the date.
|
22,060,885 |
here is my code
```
SELECT h.ENTERED_DATE,
d.DENOMINATION,
sum(h.invoice_total-h.TOTTAL_DISCOUNT)as amount
FROM sales_details d
LEFT JOIN sales_header h
ON d.invoice_id=h.invoice_id
WHERE entered_by='2254'
--HERE IS NEED TO GET DETAILS CURRENT MONTH 1st Date to Sysdate
GROUP BY
ENTERED_DATE,
d.DENOMINATION
ORDER BY
entered_date,
denomination
```
* In my application just send only **sysdate** as parameter.
**no need to SYSDATE-30.
need 1st date to SYSDATE**
here shows my two tables
**sales\_header table**

**sales\_details table**

|
2014/02/27
|
[
"https://Stackoverflow.com/questions/22060885",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2224206/"
] |
try this:
```
WHERE entered_by='2254'
AND ENTERED_DATE BETWEEN trunc (sysdate, 'mm')/*current month*/ AND SYSDATE
```
|
Compare months in where condition
`WHERE to_char( sysdate, 'mm' ) = to_char( ENTERED_DATE, 'mm' )`
Also
`WHERE EXTRACT(month FROM sysdate)=EXTRACT(month FROM ENTERED_DATE)`
|
22,060,885 |
here is my code
```
SELECT h.ENTERED_DATE,
d.DENOMINATION,
sum(h.invoice_total-h.TOTTAL_DISCOUNT)as amount
FROM sales_details d
LEFT JOIN sales_header h
ON d.invoice_id=h.invoice_id
WHERE entered_by='2254'
--HERE IS NEED TO GET DETAILS CURRENT MONTH 1st Date to Sysdate
GROUP BY
ENTERED_DATE,
d.DENOMINATION
ORDER BY
entered_date,
denomination
```
* In my application just send only **sysdate** as parameter.
**no need to SYSDATE-30.
need 1st date to SYSDATE**
here shows my two tables
**sales\_header table**

**sales\_details table**

|
2014/02/27
|
[
"https://Stackoverflow.com/questions/22060885",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2224206/"
] |
Mudassir's answer worked for me but I would also check the year to make sure you are not getting last year's records.
```
WHERE TO_CHAR(ENTERED_DATE, 'mm') = TO_CHAR(SYSDATE, 'mm')
AND TO_CHAR(ENTERED_DATE, 'yyyy') = TO_CHAR(SYSDATE, 'yyyy')
```
Also, if you are running a large query, functions in your `WHERE` clause can slow it down. If so, you may want to consider a function based index.
|
Compare months in where condition
`WHERE to_char( sysdate, 'mm' ) = to_char( ENTERED_DATE, 'mm' )`
Also
`WHERE EXTRACT(month FROM sysdate)=EXTRACT(month FROM ENTERED_DATE)`
|
22,060,885 |
here is my code
```
SELECT h.ENTERED_DATE,
d.DENOMINATION,
sum(h.invoice_total-h.TOTTAL_DISCOUNT)as amount
FROM sales_details d
LEFT JOIN sales_header h
ON d.invoice_id=h.invoice_id
WHERE entered_by='2254'
--HERE IS NEED TO GET DETAILS CURRENT MONTH 1st Date to Sysdate
GROUP BY
ENTERED_DATE,
d.DENOMINATION
ORDER BY
entered_date,
denomination
```
* In my application just send only **sysdate** as parameter.
**no need to SYSDATE-30.
need 1st date to SYSDATE**
here shows my two tables
**sales\_header table**

**sales\_details table**

|
2014/02/27
|
[
"https://Stackoverflow.com/questions/22060885",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2224206/"
] |
Compare months in where condition
`WHERE to_char( sysdate, 'mm' ) = to_char( ENTERED_DATE, 'mm' )`
Also
`WHERE EXTRACT(month FROM sysdate)=EXTRACT(month FROM ENTERED_DATE)`
|
```
select 'WITHIN' as result
from dual
where '28-FEB-2019' between trunc(last_day(add_months(sysdate, -1))+1) and trunc(last_day(sysdate));
```
Take care because there are many examples that are using just the month and because of that you could get records from all the year, year is not being considered.
Also as you can see I am using trunc it is to avoid timing inconsistencies and just use the date.
|
22,060,885 |
here is my code
```
SELECT h.ENTERED_DATE,
d.DENOMINATION,
sum(h.invoice_total-h.TOTTAL_DISCOUNT)as amount
FROM sales_details d
LEFT JOIN sales_header h
ON d.invoice_id=h.invoice_id
WHERE entered_by='2254'
--HERE IS NEED TO GET DETAILS CURRENT MONTH 1st Date to Sysdate
GROUP BY
ENTERED_DATE,
d.DENOMINATION
ORDER BY
entered_date,
denomination
```
* In my application just send only **sysdate** as parameter.
**no need to SYSDATE-30.
need 1st date to SYSDATE**
here shows my two tables
**sales\_header table**

**sales\_details table**

|
2014/02/27
|
[
"https://Stackoverflow.com/questions/22060885",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2224206/"
] |
try this:
```
WHERE entered_by='2254'
AND ENTERED_DATE BETWEEN trunc (sysdate, 'mm')/*current month*/ AND SYSDATE
```
|
Mudassir's answer worked for me but I would also check the year to make sure you are not getting last year's records.
```
WHERE TO_CHAR(ENTERED_DATE, 'mm') = TO_CHAR(SYSDATE, 'mm')
AND TO_CHAR(ENTERED_DATE, 'yyyy') = TO_CHAR(SYSDATE, 'yyyy')
```
Also, if you are running a large query, functions in your `WHERE` clause can slow it down. If so, you may want to consider a function based index.
|
22,060,885 |
here is my code
```
SELECT h.ENTERED_DATE,
d.DENOMINATION,
sum(h.invoice_total-h.TOTTAL_DISCOUNT)as amount
FROM sales_details d
LEFT JOIN sales_header h
ON d.invoice_id=h.invoice_id
WHERE entered_by='2254'
--HERE IS NEED TO GET DETAILS CURRENT MONTH 1st Date to Sysdate
GROUP BY
ENTERED_DATE,
d.DENOMINATION
ORDER BY
entered_date,
denomination
```
* In my application just send only **sysdate** as parameter.
**no need to SYSDATE-30.
need 1st date to SYSDATE**
here shows my two tables
**sales\_header table**

**sales\_details table**

|
2014/02/27
|
[
"https://Stackoverflow.com/questions/22060885",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2224206/"
] |
try this:
```
WHERE entered_by='2254'
AND ENTERED_DATE BETWEEN trunc (sysdate, 'mm')/*current month*/ AND SYSDATE
```
|
```
select 'WITHIN' as result
from dual
where '28-FEB-2019' between trunc(last_day(add_months(sysdate, -1))+1) and trunc(last_day(sysdate));
```
Take care because there are many examples that are using just the month and because of that you could get records from all the year, year is not being considered.
Also as you can see I am using trunc it is to avoid timing inconsistencies and just use the date.
|
22,060,885 |
here is my code
```
SELECT h.ENTERED_DATE,
d.DENOMINATION,
sum(h.invoice_total-h.TOTTAL_DISCOUNT)as amount
FROM sales_details d
LEFT JOIN sales_header h
ON d.invoice_id=h.invoice_id
WHERE entered_by='2254'
--HERE IS NEED TO GET DETAILS CURRENT MONTH 1st Date to Sysdate
GROUP BY
ENTERED_DATE,
d.DENOMINATION
ORDER BY
entered_date,
denomination
```
* In my application just send only **sysdate** as parameter.
**no need to SYSDATE-30.
need 1st date to SYSDATE**
here shows my two tables
**sales\_header table**

**sales\_details table**

|
2014/02/27
|
[
"https://Stackoverflow.com/questions/22060885",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2224206/"
] |
Mudassir's answer worked for me but I would also check the year to make sure you are not getting last year's records.
```
WHERE TO_CHAR(ENTERED_DATE, 'mm') = TO_CHAR(SYSDATE, 'mm')
AND TO_CHAR(ENTERED_DATE, 'yyyy') = TO_CHAR(SYSDATE, 'yyyy')
```
Also, if you are running a large query, functions in your `WHERE` clause can slow it down. If so, you may want to consider a function based index.
|
```
select 'WITHIN' as result
from dual
where '28-FEB-2019' between trunc(last_day(add_months(sysdate, -1))+1) and trunc(last_day(sysdate));
```
Take care because there are many examples that are using just the month and because of that you could get records from all the year, year is not being considered.
Also as you can see I am using trunc it is to avoid timing inconsistencies and just use the date.
|
495,643 |
I have CentOS 5.8 on my computer, with 5x 1TB hard drives.
I used software RAID. (RAID 1 as a boot partition md0, RAID 0 as a root partition md1 and RAID 5 as /home partition md3).
Unfortunately one of these hard drives failed lately and I want to replace it with a new one.
I want to know that is it possible to change this hard drive without data loss?
The important partition is RAID 5 so in theory if one of hard drives failed I should be able to recover its data without any problem. But in practice how can I do that?
|
2012/10/29
|
[
"https://superuser.com/questions/495643",
"https://superuser.com",
"https://superuser.com/users/163708/"
] |
The folks at this location actually mapped the serial numbers of the physical disks to separate names to help identify those in the RAID array. They used UDEV rules for it. This eliminates the guesswork since serial numbers are typically written on the disk paper labels.
In the below link you'll find real 2 drive failure on a RAID6 setup (+) and recovery. Take a look. You might be able to identify in a similar way which drive you need to unplug.
Regards,
[RAID 6 + XFS + MDADM](http://www.microdevsys.com/WordPress/2012/04/02/linux-htpc-home-backup-mdadm-raid6-lvm-xfs-cifs-and-nfs/3/)
[RAID 6 UDEV Naming](http://www.microdevsys.com/WordPress/2012/04/01/linux-persistent-naming-of-sata-devices-through-udev-rules/)
|
It should be something like
```
mdadm --add /dev/md3 /dev/<disk>
```
… where `<disk>` is of the form `sda1`, `sdb1`, `sdc1`, etc.
|
495,643 |
I have CentOS 5.8 on my computer, with 5x 1TB hard drives.
I used software RAID. (RAID 1 as a boot partition md0, RAID 0 as a root partition md1 and RAID 5 as /home partition md3).
Unfortunately one of these hard drives failed lately and I want to replace it with a new one.
I want to know that is it possible to change this hard drive without data loss?
The important partition is RAID 5 so in theory if one of hard drives failed I should be able to recover its data without any problem. But in practice how can I do that?
|
2012/10/29
|
[
"https://superuser.com/questions/495643",
"https://superuser.com",
"https://superuser.com/users/163708/"
] |
The folks at this location actually mapped the serial numbers of the physical disks to separate names to help identify those in the RAID array. They used UDEV rules for it. This eliminates the guesswork since serial numbers are typically written on the disk paper labels.
In the below link you'll find real 2 drive failure on a RAID6 setup (+) and recovery. Take a look. You might be able to identify in a similar way which drive you need to unplug.
Regards,
[RAID 6 + XFS + MDADM](http://www.microdevsys.com/WordPress/2012/04/02/linux-htpc-home-backup-mdadm-raid6-lvm-xfs-cifs-and-nfs/3/)
[RAID 6 UDEV Naming](http://www.microdevsys.com/WordPress/2012/04/01/linux-persistent-naming-of-sata-devices-through-udev-rules/)
|
Assuming you disk setup is as follows:

With:
sda1 and sdb1 as md1 (mirrored) root
sda2 and sdb2 as md0 (striped) boot
sda3, sdb3, sdc1, sdd1 and sde1 as md2 (RAID5) /home
Since you lost drive 2 (sdb) you:
* You lost md0. A stripe needs \*\*all\* of its drives. You will need to restore this from backup or reinstall it.
* You lost one drive from md1. Since that is a mirror it will still work. (without redundancy atm)
* You lost on drive from md2. Since that is a RAID5 is will work with one drive lost. You should still be able to access all your data.
My first step would be to check my backups. Nothing should go wrong while you fix your RAID arrays. But it is better to be safe and have backups. Since both / and /home are still readable in degraded mode I suggest to start with that.
Afterward pull the broken drive (disk 2, aka sdb), replace it with a new drive and partition the drive. I understood from your comments that it used the same setup as the first drive. Which means that you can configure it correctly from your notes, or 'spy' at sda.
Next fix the three broken RAID arrays.
md0 is lost. You will need to recreate it and restore from backup.
md1 might work with `mdadm --assemble /dev/md1 /dev/sda1 /dev/sdb1`
md2 might work with `mdadm --assemble /dev/md2 /dev/sda3 /dev/sdb3 /dev/sdc1 /dev/sdd1 /dev/sde1`
**Might**. I am a BSD guy (not a Linux user) which uses hardware RAID cards. Please double check everything before committing to these commands. This includes your checking your backups.
|
14,855,400 |
I need to export the images stored in **CompanyImage** table to a *image files*.
How can I do it?
Reading the table I obtain a Bitmap field but how to know the type of image to build the correct extension and save it to file?
|
2013/02/13
|
[
"https://Stackoverflow.com/questions/14855400",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/160787/"
] |
Finally I found the solution.
To export the image from CompanyImage:
```
// Grant clrinterop permission.
new InteropPermission(InteropKind::ClrInterop).assert();
image = new Image();
image.setData(companyImage.Image);
result = image.saveImage(@"c:\test.jpg",3);
CodeAccessPermission::revertAssert();
```
To know the original type:
```
image.saveType();
```
|
The above code wouldn't work right away. Here's the code that would run:
```
bindata bin = new bindata();
str content;
container image;
CompanyImage companyImage;
;
select companyImage;
image = companyImage.Image;
bin.setData(image);
content=bin.base64Encode();
AifUtil::saveBase64ToFile("c:\\temp\\test.tif", content);
```
|
51,983,002 |
In my current application for a company Im having a ForegroundService that is running while the workers are on duty (logged in to the app).
It is important to keep that foreground service running while users are logged in. To recover from cases where this foreground service gets killed somehow (User task swipe accidently or System kill) ive implemented a periodic JOB with Jobscheduler which reactivates the ForegroundService in case it gets shut down. This technique works well pre Android 8 OREO. START\_STICKY and other techniques alone did not do the trick for me.
In Android 8, as soon as the foreground service gets killed, the periodic job gets killed as well. Im getting the notification in logcat that the job is not allowed to run. To my understanding, Jobs schould be able to run even when app is in background or killed. And its working on pre OREO devices the way it should.
To my knowledge, I can fix that by enable the option "autostart" in app settings. But since there is no way to know if employees tunred that on, its not a reliable thing as well.
So my questions:
- Why does the Job scheduler stops working as it should in Android 8?
- Are there any other reliable techniques I could use to let my ForegroundService recover from shutdowns in ANDROID OREO?
Ive read <https://medium.com/exploring-android/exploring-background-execution-limits-on-android-oreo-ab384762a66c> but that did not answer my questions
Thank you very much
|
2018/08/23
|
[
"https://Stackoverflow.com/questions/51983002",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7798869/"
] |
Possible solutions to codepoint slicing
---------------------------------------
>
> I know I can use the `chars()` iterator and manually walk through the desired substring, but is there a more concise way?
>
>
>
If you know the exact byte indices, you can slice a string:
```
let text = "Hello привет";
println!("{}", &text[2..10]);
```
This prints "llo пр". So the problem is to find out the exact byte position. You can do that fairly easily with the `char_indices()` iterator (alternatively you could use `chars()` with `char::len_utf8()`):
```
let text = "Hello привет";
let end = text.char_indices().map(|(i, _)| i).nth(8).unwrap();
println!("{}", &text[2..end]);
```
As another alternative, you can first collect the string into `Vec<char>`. Then, indexing is simple, but to print it as a string, you have to collect it again or write your own function to do it.
```
let text = "Hello привет";
let text_vec = text.chars().collect::<Vec<_>>();
println!("{}", text_vec[2..8].iter().cloned().collect::<String>());
```
Why is this not easier?
-----------------------
As you can see, neither of these solutions is all that great. This is intentional, for two reasons:
As `str` is a simply UTF8 buffer, indexing by unicode codepoints is an O(n) operation. Usually, people expect the `[]` operator to be a O(1) operation. Rust makes this runtime complexity explicit and doesn't try to hide it. In both solutions above you can clearly see that it's not O(1).
But the more important reason:
Unicode codepoints are generally not a useful unit
--------------------------------------------------
What Python does (and what you think you want) is not all that useful. It all comes down to the complexity of language and thus the complexity of unicode. Python slices Unicode *codepoints*. This is what a Rust `char` represents. It's 32 bit big (a few fewer bits would suffice, but we round up to a power of 2).
But what you actually want to do is slice *user perceived characters*. But this is an explicitly loosely defined term. Different cultures and languages regard different things as "one character". The closest approximation is a "grapheme cluster". Such a cluster can consist of one or more unicode codepoints. Consider this Python 3 code:
```
>>> s = "Jürgen"
>>> s[0:2]
'Ju'
```
Surprising, right? This is because the string above is:
* `0x004A` LATIN CAPITAL LETTER J
* `0x0075` LATIN SMALL LETTER U
* `0x0308` COMBINING DIAERESIS
* ...
This is an example of a combining character that is rendered as part of the previous character. Python slicing does the "wrong" thing here.
Another example:
```
>>> s = "fire"
>>> s[0:2]
'fir'
```
Also not what you'd expect. This time, `fi` is actually the ligature `fi`, which is one codepoint.
There are far more examples where Unicode behaves in a surprising way. See the links at the bottom for more information and examples.
So if you want to work with international strings that should be able to work everywhere, don't do codepoint slicing! If you really need to semantically view the string as a series of *characters*, use grapheme clusters. To do that, the crate [`unicode-segmentation`](https://crates.io/crates/unicode-segmentation) is very useful.
---
Further resources on this topic:
* [Blogpost "Let's stop ascribing meaning to unicode codepoints"](https://manishearth.github.io/blog/2017/01/14/stop-ascribing-meaning-to-unicode-code-points/)
* [Blogpost "Breaking our Latin-1 assumptions](https://manishearth.github.io/blog/2017/01/15/breaking-our-latin-1-assumptions/)
* <http://utf8everywhere.org/>
|
A UTF-8 encoded string may contain characters which consists of multiple bytes. In your case, `п` starts at index 6 (inclusive) and ends at position 8 (exclusive) so indexing 7 is not the start of the character. This is why your error occurred.
You may use [`str::char_indices()`](https://doc.rust-lang.org/std/primitive.str.html#method.char_indices) for solving this (remember, that getting to a position in a UTF-8 string is `O(n)`):
```
fn get_utf8_slice(string: &str, start: usize, end: usize) -> Option<&str> {
assert!(end >= start);
string.char_indices().nth(start).and_then(|(start_pos, _)| {
string[start_pos..]
.char_indices()
.nth(end - start - 1)
.map(|(end_pos, _)| &string[start_pos..end_pos])
})
}
```
[playground](https://play.rust-lang.org/?gist=8615dce4ec8a36cc1220b79d2af7751f&version=stable&mode=debug&edition=2015)
You may use [`str::chars()`](https://doc.rust-lang.org/std/primitive.str.html#method.chars) if you are fine with getting a `String`:
```
let string: String = text.chars().take(end).skip(start).collect();
```
|
51,983,002 |
In my current application for a company Im having a ForegroundService that is running while the workers are on duty (logged in to the app).
It is important to keep that foreground service running while users are logged in. To recover from cases where this foreground service gets killed somehow (User task swipe accidently or System kill) ive implemented a periodic JOB with Jobscheduler which reactivates the ForegroundService in case it gets shut down. This technique works well pre Android 8 OREO. START\_STICKY and other techniques alone did not do the trick for me.
In Android 8, as soon as the foreground service gets killed, the periodic job gets killed as well. Im getting the notification in logcat that the job is not allowed to run. To my understanding, Jobs schould be able to run even when app is in background or killed. And its working on pre OREO devices the way it should.
To my knowledge, I can fix that by enable the option "autostart" in app settings. But since there is no way to know if employees tunred that on, its not a reliable thing as well.
So my questions:
- Why does the Job scheduler stops working as it should in Android 8?
- Are there any other reliable techniques I could use to let my ForegroundService recover from shutdowns in ANDROID OREO?
Ive read <https://medium.com/exploring-android/exploring-background-execution-limits-on-android-oreo-ab384762a66c> but that did not answer my questions
Thank you very much
|
2018/08/23
|
[
"https://Stackoverflow.com/questions/51983002",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7798869/"
] |
Possible solutions to codepoint slicing
---------------------------------------
>
> I know I can use the `chars()` iterator and manually walk through the desired substring, but is there a more concise way?
>
>
>
If you know the exact byte indices, you can slice a string:
```
let text = "Hello привет";
println!("{}", &text[2..10]);
```
This prints "llo пр". So the problem is to find out the exact byte position. You can do that fairly easily with the `char_indices()` iterator (alternatively you could use `chars()` with `char::len_utf8()`):
```
let text = "Hello привет";
let end = text.char_indices().map(|(i, _)| i).nth(8).unwrap();
println!("{}", &text[2..end]);
```
As another alternative, you can first collect the string into `Vec<char>`. Then, indexing is simple, but to print it as a string, you have to collect it again or write your own function to do it.
```
let text = "Hello привет";
let text_vec = text.chars().collect::<Vec<_>>();
println!("{}", text_vec[2..8].iter().cloned().collect::<String>());
```
Why is this not easier?
-----------------------
As you can see, neither of these solutions is all that great. This is intentional, for two reasons:
As `str` is a simply UTF8 buffer, indexing by unicode codepoints is an O(n) operation. Usually, people expect the `[]` operator to be a O(1) operation. Rust makes this runtime complexity explicit and doesn't try to hide it. In both solutions above you can clearly see that it's not O(1).
But the more important reason:
Unicode codepoints are generally not a useful unit
--------------------------------------------------
What Python does (and what you think you want) is not all that useful. It all comes down to the complexity of language and thus the complexity of unicode. Python slices Unicode *codepoints*. This is what a Rust `char` represents. It's 32 bit big (a few fewer bits would suffice, but we round up to a power of 2).
But what you actually want to do is slice *user perceived characters*. But this is an explicitly loosely defined term. Different cultures and languages regard different things as "one character". The closest approximation is a "grapheme cluster". Such a cluster can consist of one or more unicode codepoints. Consider this Python 3 code:
```
>>> s = "Jürgen"
>>> s[0:2]
'Ju'
```
Surprising, right? This is because the string above is:
* `0x004A` LATIN CAPITAL LETTER J
* `0x0075` LATIN SMALL LETTER U
* `0x0308` COMBINING DIAERESIS
* ...
This is an example of a combining character that is rendered as part of the previous character. Python slicing does the "wrong" thing here.
Another example:
```
>>> s = "fire"
>>> s[0:2]
'fir'
```
Also not what you'd expect. This time, `fi` is actually the ligature `fi`, which is one codepoint.
There are far more examples where Unicode behaves in a surprising way. See the links at the bottom for more information and examples.
So if you want to work with international strings that should be able to work everywhere, don't do codepoint slicing! If you really need to semantically view the string as a series of *characters*, use grapheme clusters. To do that, the crate [`unicode-segmentation`](https://crates.io/crates/unicode-segmentation) is very useful.
---
Further resources on this topic:
* [Blogpost "Let's stop ascribing meaning to unicode codepoints"](https://manishearth.github.io/blog/2017/01/14/stop-ascribing-meaning-to-unicode-code-points/)
* [Blogpost "Breaking our Latin-1 assumptions](https://manishearth.github.io/blog/2017/01/15/breaking-our-latin-1-assumptions/)
* <http://utf8everywhere.org/>
|
Here is a function which retrieves a utf8 slice, with the following pros:
* handle all edge cases (empty input, 0-width output ranges, out-of-scope ranges);
* never panics;
* use start-inclusive, end-exclusive ranges.
```
pub fn utf8_slice(s: &str, start: usize, end: usize) -> Option<&str> {
let mut iter = s.char_indices()
.map(|(pos, _)| pos)
.chain(Some(s.len()))
.skip(start)
.peekable();
let start_pos = *iter.peek()?;
for _ in start..end { iter.next(); }
Some(&s[start_pos..*iter.peek()?])
}
```
|
51,983,002 |
In my current application for a company Im having a ForegroundService that is running while the workers are on duty (logged in to the app).
It is important to keep that foreground service running while users are logged in. To recover from cases where this foreground service gets killed somehow (User task swipe accidently or System kill) ive implemented a periodic JOB with Jobscheduler which reactivates the ForegroundService in case it gets shut down. This technique works well pre Android 8 OREO. START\_STICKY and other techniques alone did not do the trick for me.
In Android 8, as soon as the foreground service gets killed, the periodic job gets killed as well. Im getting the notification in logcat that the job is not allowed to run. To my understanding, Jobs schould be able to run even when app is in background or killed. And its working on pre OREO devices the way it should.
To my knowledge, I can fix that by enable the option "autostart" in app settings. But since there is no way to know if employees tunred that on, its not a reliable thing as well.
So my questions:
- Why does the Job scheduler stops working as it should in Android 8?
- Are there any other reliable techniques I could use to let my ForegroundService recover from shutdowns in ANDROID OREO?
Ive read <https://medium.com/exploring-android/exploring-background-execution-limits-on-android-oreo-ab384762a66c> but that did not answer my questions
Thank you very much
|
2018/08/23
|
[
"https://Stackoverflow.com/questions/51983002",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7798869/"
] |
A UTF-8 encoded string may contain characters which consists of multiple bytes. In your case, `п` starts at index 6 (inclusive) and ends at position 8 (exclusive) so indexing 7 is not the start of the character. This is why your error occurred.
You may use [`str::char_indices()`](https://doc.rust-lang.org/std/primitive.str.html#method.char_indices) for solving this (remember, that getting to a position in a UTF-8 string is `O(n)`):
```
fn get_utf8_slice(string: &str, start: usize, end: usize) -> Option<&str> {
assert!(end >= start);
string.char_indices().nth(start).and_then(|(start_pos, _)| {
string[start_pos..]
.char_indices()
.nth(end - start - 1)
.map(|(end_pos, _)| &string[start_pos..end_pos])
})
}
```
[playground](https://play.rust-lang.org/?gist=8615dce4ec8a36cc1220b79d2af7751f&version=stable&mode=debug&edition=2015)
You may use [`str::chars()`](https://doc.rust-lang.org/std/primitive.str.html#method.chars) if you are fine with getting a `String`:
```
let string: String = text.chars().take(end).skip(start).collect();
```
|
Here is a function which retrieves a utf8 slice, with the following pros:
* handle all edge cases (empty input, 0-width output ranges, out-of-scope ranges);
* never panics;
* use start-inclusive, end-exclusive ranges.
```
pub fn utf8_slice(s: &str, start: usize, end: usize) -> Option<&str> {
let mut iter = s.char_indices()
.map(|(pos, _)| pos)
.chain(Some(s.len()))
.skip(start)
.peekable();
let start_pos = *iter.peek()?;
for _ in start..end { iter.next(); }
Some(&s[start_pos..*iter.peek()?])
}
```
|
2,016,329 |
>
> If $\alpha = 2\arctan(2\sqrt{2}-1)$ and $\displaystyle \beta = 3\arcsin\left(\frac{1}{3}\right)+\arcsin\left(\frac{3}{5}\right)\;,$ Then prove that $\alpha>\beta$
>
>
>
$\bf{My\; Try::}$ Given $$ \alpha = \arctan \bigg(\frac{2(2\sqrt{2}-1)}{1-(2\sqrt{2}-1)^2}\bigg)=\arctan \bigg(\frac{(2\sqrt{2}-1)}{2\sqrt{2}-4}\bigg)$$
and $$\beta = \arcsin\bigg(1-\frac{4}{27}\bigg)+\arcsin\bigg(\frac{3}{5}\bigg) = \arcsin\bigg(\frac{23}{27}\bigg)+\arcsin\bigg(\frac{3}{5}\bigg)$$
So $$\arcsin\bigg[\frac{23}{27}\cdot \frac{4}{5}+\frac{3}{5}\cdot \frac{10\sqrt{2}}{23}\bigg]$$
Now how can i solve it, Help required, Thanks
|
2016/11/16
|
[
"https://math.stackexchange.com/questions/2016329",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/14311/"
] |
HINT:
As $\arcsin\dfrac13<\arcsin\dfrac12=\dfrac\pi6$
$3\arcsin\dfrac13=\arcsin\dfrac{23}{27}=\arctan\dfrac{23}{10\sqrt2}$
$\arcsin\dfrac35=\arctan\dfrac34$
As $\dfrac{23}{10\sqrt2}\cdot\dfrac34>1,$
using [Inverse trigonometric function identity doubt: $\tan^{-1}x+\tan^{-1}y =-\pi+\tan^{-1}\left(\frac{x+y}{1-xy}\right)$, when $x<0$, $y<0$, and $xy>1$](https://math.stackexchange.com/questions/1837410/inverse-trigonometric-function-identity-doubt-tan-1x-tan-1y-pi-tan),
$$\arctan\dfrac{23}{10\sqrt2}+\arctan\dfrac34=\pi+\arctan\dfrac{\dfrac{23}{10\sqrt2}+\dfrac34}{1-\dfrac{23}{10\sqrt2}\cdot\dfrac34}$$
As $2\sqrt2-1>1$
$$2\arctan(2\sqrt{2}-1)=\pi+\arctan ?$$
Now for $\dfrac\pi2>a>b>-\dfrac\pi2,\arctan a>\arctan b $
|
\begin{align}
\beta&=\sqrt{10}\left(\frac{3}{\sqrt{10}}\arcsin\frac13+\frac{1}{\sqrt{10}}\arcsin\frac35\right)\\
&<\sqrt{10}\arcsin\left(\frac{4\sqrt{10}}{25}\right)
\end{align}
where I use the convexity of $\arcsin$. On the other hand using the definition of $\arctan$ we obtain $$\arcsin\left(\frac{4\sqrt{10}}{25}\right)=\arctan\left(\frac{4\sqrt{2}}{\sqrt{93}}\right).$$
Now further note that $\sqrt{10}<4$ hence we should check wether $$2\arctan\left(\frac{2\sqrt{2}}{\sqrt{93}}\right)<\arctan(2\sqrt2-1)$$
We hence (with $\tan2x=\frac{2\tan x}{1-\tan^2x}$) should prove that $$\frac{8\sqrt{186}}{61}<2\sqrt2-1.$$
|
2,016,329 |
>
> If $\alpha = 2\arctan(2\sqrt{2}-1)$ and $\displaystyle \beta = 3\arcsin\left(\frac{1}{3}\right)+\arcsin\left(\frac{3}{5}\right)\;,$ Then prove that $\alpha>\beta$
>
>
>
$\bf{My\; Try::}$ Given $$ \alpha = \arctan \bigg(\frac{2(2\sqrt{2}-1)}{1-(2\sqrt{2}-1)^2}\bigg)=\arctan \bigg(\frac{(2\sqrt{2}-1)}{2\sqrt{2}-4}\bigg)$$
and $$\beta = \arcsin\bigg(1-\frac{4}{27}\bigg)+\arcsin\bigg(\frac{3}{5}\bigg) = \arcsin\bigg(\frac{23}{27}\bigg)+\arcsin\bigg(\frac{3}{5}\bigg)$$
So $$\arcsin\bigg[\frac{23}{27}\cdot \frac{4}{5}+\frac{3}{5}\cdot \frac{10\sqrt{2}}{23}\bigg]$$
Now how can i solve it, Help required, Thanks
|
2016/11/16
|
[
"https://math.stackexchange.com/questions/2016329",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/14311/"
] |
On the one hand we have
$$\tan{\alpha\over2}=2\sqrt{2}-1>\sqrt{3}=\tan{\pi\over3}\ ,$$
hence ${\alpha\over2}>{\pi\over3}$, or $$\alpha>{2\pi\over3}\ .$$
On the other hand the convexity of $$t\mapsto\arcsin t\qquad(0\leq t\leq{\pi\over2})$$ implies
$$\arcsin{1\over3}<{2\over3}\arcsin{1\over2}={2\over3}\>{\pi\over6}={\pi\over9}\ .$$
Furthermore $\arcsin{3\over5}<\arcsin{1\over\sqrt{2}}={\pi\over4}$. It follows that
$$\beta<3{\pi\over9}+{\pi\over4}={7\pi\over12}<\alpha\ .$$
|
\begin{align}
\beta&=\sqrt{10}\left(\frac{3}{\sqrt{10}}\arcsin\frac13+\frac{1}{\sqrt{10}}\arcsin\frac35\right)\\
&<\sqrt{10}\arcsin\left(\frac{4\sqrt{10}}{25}\right)
\end{align}
where I use the convexity of $\arcsin$. On the other hand using the definition of $\arctan$ we obtain $$\arcsin\left(\frac{4\sqrt{10}}{25}\right)=\arctan\left(\frac{4\sqrt{2}}{\sqrt{93}}\right).$$
Now further note that $\sqrt{10}<4$ hence we should check wether $$2\arctan\left(\frac{2\sqrt{2}}{\sqrt{93}}\right)<\arctan(2\sqrt2-1)$$
We hence (with $\tan2x=\frac{2\tan x}{1-\tan^2x}$) should prove that $$\frac{8\sqrt{186}}{61}<2\sqrt2-1.$$
|
16,432,909 |
I am making a custom Application in Android. I am displaying a html page with an img tag inside a div.
```
<div class="press">
<img src="but.png" width="150" height="62" border="0"/>
</div>
```
In the javascript I am writing:
```
$(".press").bind("click",function()
{
//display something
});
```
When I click on the image, the click is working but the image is surrounded with a blue overlay.
[Image 1](http://amazeinfotainment.com/example/IMG_1313.JPG)
[Image 2 when image clicked](http://amazeinfotainment.com/example/IMG_1315.JPG)
I dont understand how to remove it. I have tried many ways but none of the answers work. Please help. Thanks
|
2013/05/08
|
[
"https://Stackoverflow.com/questions/16432909",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2360830/"
] |
You can prevent selection on your page through css. You can change the \* selector to the element selector you want to prevent from selection.
```
/*IE9*/
*::selection
{
background-color:transparent;
}
*::-moz-selection
{
background-color:transparent;
}
*
{
-webkit-user-select: none;
-moz-user-select: -moz-none;
/*IE10*/
-ms-user-select: none;
user-select: none;
/*You just need this if you are only concerned with android and not desktop browsers.*/
-webkit-tap-highlight-color: rgba(0, 0, 0, 0);
}
input[type="text"], textarea, [contenteditable]
{
-webkit-user-select: text;
-moz-user-select: text;
-ms-user-select: text;
user-select: text;
}
```
|
It may be the background color or the border color on the div that includes the button. Else
use a code like following to remove the css after click completely
```
$("#myButton").click(function(){
$("#displayPanel div").removeClass('someClass');
});
```
|
16,432,909 |
I am making a custom Application in Android. I am displaying a html page with an img tag inside a div.
```
<div class="press">
<img src="but.png" width="150" height="62" border="0"/>
</div>
```
In the javascript I am writing:
```
$(".press").bind("click",function()
{
//display something
});
```
When I click on the image, the click is working but the image is surrounded with a blue overlay.
[Image 1](http://amazeinfotainment.com/example/IMG_1313.JPG)
[Image 2 when image clicked](http://amazeinfotainment.com/example/IMG_1315.JPG)
I dont understand how to remove it. I have tried many ways but none of the answers work. Please help. Thanks
|
2013/05/08
|
[
"https://Stackoverflow.com/questions/16432909",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2360830/"
] |
You can prevent selection on your page through css. You can change the \* selector to the element selector you want to prevent from selection.
```
/*IE9*/
*::selection
{
background-color:transparent;
}
*::-moz-selection
{
background-color:transparent;
}
*
{
-webkit-user-select: none;
-moz-user-select: -moz-none;
/*IE10*/
-ms-user-select: none;
user-select: none;
/*You just need this if you are only concerned with android and not desktop browsers.*/
-webkit-tap-highlight-color: rgba(0, 0, 0, 0);
}
input[type="text"], textarea, [contenteditable]
{
-webkit-user-select: text;
-moz-user-select: text;
-ms-user-select: text;
user-select: text;
}
```
|
Try this:
**CSS**
```
.press, img, .press:focus, img:focus{
outline: 0 !important;
border:0 none !important;
}
```
|
16,432,909 |
I am making a custom Application in Android. I am displaying a html page with an img tag inside a div.
```
<div class="press">
<img src="but.png" width="150" height="62" border="0"/>
</div>
```
In the javascript I am writing:
```
$(".press").bind("click",function()
{
//display something
});
```
When I click on the image, the click is working but the image is surrounded with a blue overlay.
[Image 1](http://amazeinfotainment.com/example/IMG_1313.JPG)
[Image 2 when image clicked](http://amazeinfotainment.com/example/IMG_1315.JPG)
I dont understand how to remove it. I have tried many ways but none of the answers work. Please help. Thanks
|
2013/05/08
|
[
"https://Stackoverflow.com/questions/16432909",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2360830/"
] |
You can prevent selection on your page through css. You can change the \* selector to the element selector you want to prevent from selection.
```
/*IE9*/
*::selection
{
background-color:transparent;
}
*::-moz-selection
{
background-color:transparent;
}
*
{
-webkit-user-select: none;
-moz-user-select: -moz-none;
/*IE10*/
-ms-user-select: none;
user-select: none;
/*You just need this if you are only concerned with android and not desktop browsers.*/
-webkit-tap-highlight-color: rgba(0, 0, 0, 0);
}
input[type="text"], textarea, [contenteditable]
{
-webkit-user-select: text;
-moz-user-select: text;
-ms-user-select: text;
user-select: text;
}
```
|
You could use CSS:
\*\* HTML \*\*
```
<button class="press">
<img src="but.png" width="150" height="62" border="0"/>
</button>
```
\*\* CSS \*\*
```
.press{
outline-width: 0;
}
.press:focus{
outline: none;
}
```
Answer take from here: [How to remove the border highlight on an input text element](https://stackoverflow.com/questions/1457849/how-do-i-disable-the-highlight-border-on-an-html-input-text-element)
|
16,432,909 |
I am making a custom Application in Android. I am displaying a html page with an img tag inside a div.
```
<div class="press">
<img src="but.png" width="150" height="62" border="0"/>
</div>
```
In the javascript I am writing:
```
$(".press").bind("click",function()
{
//display something
});
```
When I click on the image, the click is working but the image is surrounded with a blue overlay.
[Image 1](http://amazeinfotainment.com/example/IMG_1313.JPG)
[Image 2 when image clicked](http://amazeinfotainment.com/example/IMG_1315.JPG)
I dont understand how to remove it. I have tried many ways but none of the answers work. Please help. Thanks
|
2013/05/08
|
[
"https://Stackoverflow.com/questions/16432909",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2360830/"
] |
Try this:
**CSS**
```
.press, img, .press:focus, img:focus{
outline: 0 !important;
border:0 none !important;
}
```
|
It may be the background color or the border color on the div that includes the button. Else
use a code like following to remove the css after click completely
```
$("#myButton").click(function(){
$("#displayPanel div").removeClass('someClass');
});
```
|
16,432,909 |
I am making a custom Application in Android. I am displaying a html page with an img tag inside a div.
```
<div class="press">
<img src="but.png" width="150" height="62" border="0"/>
</div>
```
In the javascript I am writing:
```
$(".press").bind("click",function()
{
//display something
});
```
When I click on the image, the click is working but the image is surrounded with a blue overlay.
[Image 1](http://amazeinfotainment.com/example/IMG_1313.JPG)
[Image 2 when image clicked](http://amazeinfotainment.com/example/IMG_1315.JPG)
I dont understand how to remove it. I have tried many ways but none of the answers work. Please help. Thanks
|
2013/05/08
|
[
"https://Stackoverflow.com/questions/16432909",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2360830/"
] |
You could use CSS:
\*\* HTML \*\*
```
<button class="press">
<img src="but.png" width="150" height="62" border="0"/>
</button>
```
\*\* CSS \*\*
```
.press{
outline-width: 0;
}
.press:focus{
outline: none;
}
```
Answer take from here: [How to remove the border highlight on an input text element](https://stackoverflow.com/questions/1457849/how-do-i-disable-the-highlight-border-on-an-html-input-text-element)
|
It may be the background color or the border color on the div that includes the button. Else
use a code like following to remove the css after click completely
```
$("#myButton").click(function(){
$("#displayPanel div").removeClass('someClass');
});
```
|
364,027 |
in the image suppose A is an observer. a box length of 1 light second is moving away from A with a velocity of half of the speed of light. a laser is shot from the front side of the box(C) to the opposite side of the box meaning that the light is going to the opposite direction of the velocity of the box.
if there is an observer in the box he will see light to reach the end of the box(B) in one second.but in case of observer A will the time taken for the light be shorter than 1 second or longer? it seems like it would be shorter. according to special relativity should it be longer?[](https://i.stack.imgur.com/rmVKx.jpg)
|
2017/10/20
|
[
"https://physics.stackexchange.com/questions/364027",
"https://physics.stackexchange.com",
"https://physics.stackexchange.com/users/136782/"
] |
Before I start, we have to agree on what Huygens’ principle says. The Wikipedia page you cite does a poor job at presenting Huygens’ original idea, instead entirely focusing on Fresnel’s addition to it (the article is titled Huygens-Fresnel principle after all). You may know what I am going to explain but it may be still be useful to clarify for other readers.
If we go down the route of Fresnel modifications, it is rather pointless to stop there as Fresnel’s theory is just a bunch of heuristic guesses to make Huygens’ idea work for diffraction: instead we should go directly to [Kirchhoff’s formula](https://en.wikipedia.org/wiki/Kirchhoff%27s_diffraction_formula) which is grounded in the rigorous treatment of the wave equation. As for Huygens’ original principle, it states
1. that every point on the wave front of a propagating wave (the primary wave) is the source of secondary spherical wavelets; and
2. that the envelope of the wave fronts of all those secondary waves is the wave front of the primary wave.
A key point is that all those waves propagate at the same velocity. This is clearer on a drawing.
[](https://i.stack.imgur.com/Jhf5O.png)
The blue circle is the primary wave front, the dotted circles are the wave fronts of the secondary wavelets and the red circle is the envelope. With this idea, Huygens was able to explain the laws of reflection and refraction but this method fails at explaining diffraction, not without Fresnel’s additions at least.
However we have a big problem: you considered surface waves but Huygens’ principle is not true in 2 dimensions! It is only true in odd dimensions. The only explanation of that I know of requires to study the spherical wave equation. I won’t elaborate on that but a nice exposition can be found on Kevin Brown’s [famous mathpages](http://www.mathpages.com/home/kmath242/kmath242.htm). At least the first half is understandable with a bit of knowledge in calculus. There was also this [question](https://physics.stackexchange.com/questions/129324/why-is-huygens-principle-only-valid-in-an-odd-number-of-spatial-dimensions) on our beloved physics.stackexchange, with answers at various levels of math.
Thus, I shall consider sound waves propagating in the atmosphere instead, in the presence of a steady uniform wind, so that I can work in 3D. In effect, since I will not write any math, it won’t make much difference to the exposition but at least you can feel assured that this is correct!
Now let’s consider an observer, moving at the same velocity as the wind, who claps his hands. By the principle of relativity, what he sees should then be the same as what he would have seen standing still on the ground if there was no wind: the wave fronts are concentric sphere expanding outward and the original Huygens' principle is valid. But now what we are interested in is what another observer standing still on the ground will see.
The essential point is that a wave front of the primary wave is still a sphere but one that is moving with the velocity of the wind. Similarly, the wave front of the secondary wavelets emitted on the primary wave front are also still spheres but moving with the wind speed. This is just a simple Galilean transformation from the frame of the observer moving along with the wind to the frame of the ground. As a result, the envelope of those secondary wave fronts will be the primary wave front further away, and we can conclude that the original Huygens’ principle hold for that observer standing still on the ground.
Owing to the discussion at the beginning of my answer, there is still the question of whether the improved Huygens' principles hold in the presence of the wind, specifically, whether Kirchhoff's formula does. The answer is that the standard form of it does not but that a tweaked version of it can be proven to work [Mor30].
[Mor30] W.R. Morgans. XIV. the Kirchhoff formula extended to a moving surface. The London, Edinburgh, and Dublin Philosophical Magazine and Journal of Science, 9(55):141–161, 1930.
|
The wind basically adds new sources for waves that also have to be considered regarding Huygens' principle. These new wave sources will look different depending on the wind you choose. Maybe you can imagine it as if you would throw a lot of little stone everywhere the wind hits the water. After the wind stops the principle will again hold true with the new formed shapes of wavefronts ect.
|
1,886,580 |
I am in a early stage of a project, graphically modelling the system structure.
Is there any widely accepted graphical notation for showing interface "bundles"?
Interface bundles would be a collection of several separate interfaces (belonging together) which are aggregated in order to reduce figure complexity.
Example would be to visualize a
* direct debit interface,
* voucher interface,
* credit card interface and
* prepaid interface
as one aggregated payment interface with hinting that the actual implementation consists of several interfaces. I am looking for ways to illustrate the "hinting".
|
2009/12/11
|
[
"https://Stackoverflow.com/questions/1886580",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/74168/"
] |
So, it all depends on what you are trying to say from a modeling perspective. Options 3 could be your hinting, but there are other options.
1. Use packages for grouping and add a keyword of 'group'/'interface set' plus name the package what the grouping should be called as, not my personal favorite, but common, because it is easy, and people over use packages for the wrong meaning.
2. Make one large/grouped interface and have it realize the others. This would be very explicit from an inheritance perspective. It would work nice during behavior modeling (sequence diagrams) because the child interface methods would actually be available.
3. Like 2, but instead the use/depends line and add a keyword to the line, you can put a 'hint' keyword like contains, groups, include (this is standard).
4. You could use association, aggregation, composition lines between the a large/grouped interface and contained interfaces like in option 3.
5. If it is more important that they are grouped at realization or the component level, you can put multiple interfaces on 1 port (i.e.) lollipop coming of a component.
If these don't work there might be more complex or behavior related UML modeling options. You could even try and leverage the IBM services profile, but it is more about grouping interfaces (services) for deployment grouping, kind of like 5.
|
If you're using UML, I think the relevant diagram is a component diagram, which you could use to easily capture component ("bundles") and describe their interfaces.
example:
[Component diagram example](http://images.google.com/imgres?imgurl=http://images.devshed.com/ds/stories/Introducing%2520UML/image%25204.jpg&imgrefurl=http://www.devshed.com/c/a/Practices/Introducing-UMLObjectOriented-Analysis-and-Design/4/&usg=__H2GdmQEszl1l5Yut-If0aC8X36I=&h=393&w=478&sz=19&hl=en&start=4&um=1&tbnid=TVe9tx3B2rs2mM:&tbnh=106&tbnw=129&prev=/images%3Fq%3Dcomponent%2Bdiagram%26hl%3Den%26client%3Dfirefox-a%26rlz%3D1R1GGGL_en___NL355%26sa%3DX%26um%3D1)
|
1,886,580 |
I am in a early stage of a project, graphically modelling the system structure.
Is there any widely accepted graphical notation for showing interface "bundles"?
Interface bundles would be a collection of several separate interfaces (belonging together) which are aggregated in order to reduce figure complexity.
Example would be to visualize a
* direct debit interface,
* voucher interface,
* credit card interface and
* prepaid interface
as one aggregated payment interface with hinting that the actual implementation consists of several interfaces. I am looking for ways to illustrate the "hinting".
|
2009/12/11
|
[
"https://Stackoverflow.com/questions/1886580",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/74168/"
] |
So, it all depends on what you are trying to say from a modeling perspective. Options 3 could be your hinting, but there are other options.
1. Use packages for grouping and add a keyword of 'group'/'interface set' plus name the package what the grouping should be called as, not my personal favorite, but common, because it is easy, and people over use packages for the wrong meaning.
2. Make one large/grouped interface and have it realize the others. This would be very explicit from an inheritance perspective. It would work nice during behavior modeling (sequence diagrams) because the child interface methods would actually be available.
3. Like 2, but instead the use/depends line and add a keyword to the line, you can put a 'hint' keyword like contains, groups, include (this is standard).
4. You could use association, aggregation, composition lines between the a large/grouped interface and contained interfaces like in option 3.
5. If it is more important that they are grouped at realization or the component level, you can put multiple interfaces on 1 port (i.e.) lollipop coming of a component.
If these don't work there might be more complex or behavior related UML modeling options. You could even try and leverage the IBM services profile, but it is more about grouping interfaces (services) for deployment grouping, kind of like 5.
|
Sounds like component diagrams would be useful here. Check out the following example:
[](https://i.stack.imgur.com/HeVkP.png)
**UML Component Diagrams: Reference**: <http://msdn.microsoft.com/en-us/library/dd409390%28VS.100%29.aspx>
|
7,778,025 |
I am using TabView for an activity layout. Unfortunately, the first time that I enter the acticity, TabView displays the content of all tabs at the same time, creating corrupted output.
My layout uses an ImageView for the background and adds on top of it the TabHost. The ScrollView is there because the content of some tabs requires scrolling. I do not use separate activities for each tab.
```
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent" android:layout_height="fill_parent"
android:orientation="vertical">
<ImageView android:layout_width="fill_parent"
android:layout_height="fill_parent" android:src="@drawable/background_claims"
android:scaleType="centerCrop" />
<TabHost xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@android:id/tabhost" android:layout_width="fill_parent"
android:layout_height="fill_parent">
<LinearLayout android:orientation="vertical"
android:layout_width="fill_parent" android:layout_height="fill_parent">
<TabWidget android:id="@android:id/tabs"
android:layout_width="fill_parent" android:layout_height="wrap_content" />
<ScrollView android:layout_width="fill_parent"
android:layout_height="fill_parent">
<FrameLayout android:id="@android:id/tabcontent"
android:layout_width="fill_parent" android:layout_height="fill_parent">
<LinearLayout android:id="@+id/overview_tab"
android:orientation="vertical" android:layout_width="fill_parent"
android:layout_height="wrap_content">
</LinearLayout>
<LinearLayout android:id="@+id/journey_tab"
android:orientation="vertical" android:layout_width="fill_parent"
android:layout_height="fill_parent">
</LinearLayout>
<LinearLayout android:id="@+id/delay_tab"
android:orientation="vertical" android:layout_width="fill_parent"
android:layout_height="fill_parent">
</LinearLayout>
<LinearLayout android:id="@+id/personal_tab"
android:orientation="vertical" android:layout_width="fill_parent"
android:layout_height="fill_parent">
</LinearLayout>
<LinearLayout android:id="@+id/ticket_tab"
android:orientation="vertical" android:layout_width="fill_parent"
android:layout_height="fill_parent">
</LinearLayout>
</FrameLayout>
</ScrollView>
</LinearLayout>
</TabHost>
</FrameLayout>
```
...where I ommit the content of the LinearLayouts for brevity.
The LinearLayouts are added as tabs on the Activity's constructor:
```
tabHost = getTabHost();
tabHost.setOnTabChangedListener(this);
tabHost.addTab(tabHost.newTabSpec(LIST1_TAB_TAG)
.setIndicator(LIST1_TAB_TAG)
.setContent(new TabContentFactory() {
public View createTabContent(String arg0) {
return (LinearLayout) findViewById(R.id.overview_tab);
}
}));
```
The first tab is supposed to look like this:

However, the first time that I enter the activity it looks like this:

The additional content that you see is from other tabs in the same activity.
After I click another tab and then go back to the first, the output is fixed (that's how I got the first screenshot). The behaviour is consistent and happens every time I launch the activity. I am using Android 2.3.7 (CM7) on an HD2 if that's relevant.
Thanks a lot for any help!
|
2011/10/15
|
[
"https://Stackoverflow.com/questions/7778025",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/140227/"
] |
How about this (only the changed parts shown):-
```
// Handler interface
interface IHandles<T> where T : ICommand {
void Handle(T command);
}
// Bus interface
interface IBus {
void Publish<T>(T cmd) where T : ICommand;
}
// Bus implementation
class BusImpl : IBus {
public void Publish<T>(T cmd) where T : ICommand {
var handler = (IHandles<T>)IoC.Resolve(typeof(IHandles<T>));
handler.Handle(cmd);
}
}
```
The key here is to make the `Publish` method generic, which means that you get a type reference `T` to the type of the command, which can then be used to make the cast. The type parameter constraints simply ensure that only an `ICommand` can be passed, as before.
BTW - I've tested this and it works, here's the full code:-
```
public static void Main(){
new BusImpl().Publish(new HelloCommand());
}
// IoC wrapper
static class IoC {
public static object Resolve(Type t) {
return new ConcreteHandlerImpl();
}
}
// Handler interface
interface IHandles<T> where T : ICommand {
void Handle(T command);
}
// Command interface
interface ICommand {
}
// Handler implementation
class ConcreteHandlerImpl : IHandles<HelloCommand> {
public void Handle(HelloCommand cmd) {
Console.WriteLine("Hello Command executed");
}
}
public class HelloCommand:ICommand{}
// Bus interface
interface IBus {
void Publish<T>(T cmd) where T : ICommand;
}
// Bus implementation
class BusImpl : IBus {
public void Publish<T>(T cmd) where T : ICommand {
var handler = (IHandles<T>)IoC.Resolve(typeof(IHandles<T>));
handler.Handle(cmd);
}
}
```
-- UPDATE --
As pointed out by Peter Lillevold, you should also think about adding a type parameter to your IOC container method as follows:-
```
// IoC wrapper
static class IoC {
public static T Resolve<T>() {
...
}
}
```
this will simplify your caller like so:-
```
// Bus implementation
class BusImpl : IBus {
public void Publish<T>(T cmd) where T : ICommand {
var handler = IoC.Resolve<IHandles<T>>();
handler.Handle(cmd);
}
}
```
This is a side point to your original question, but would seem a sensible design for the IOC interface.
|
Does this work? Your IoC is returning object, consider returning T instead then you wont have to handle type ambiguity as done below.
```
public void Publish(ICommand cmd) {
var cmdType = cmd.GetType();
var handler = IoC.Resolve(typeof(IHandles<>).MakeGenericType(cmdType)) as IHandles<ICommand>;
if (handler != null)
{
// BEGIN SLOW
handler.Handle(command);
// END SLOW
}
//else throw some exception
}
```
|
8,357,942 |
I'm loading a very large data set into R from java. I have created a Java program that calls R using rJava's jri. This program has been wrapped up into an executable jar file and is being called from the terminal (linux). The data is in region of 50 columns by 13.7 million rows. R alone can handle this without a problem. However, when I run it from the Java program, I get a Java OutofMemory Heap error.
The thing is when I run it with half the rows it works, yet R should only be sending the names of each variable (50 in total) back to java regardless of how many rows there are. This is the code I'm using:
```
re.eval("names(data<-read.csv(file="data.csv", head=TRUE, sep=","));
```
My understanding is that the re.eval function, evaluates an expression in R *and sends the results back to R.* Is there any way for you to evaluate the function and not have the result returned to java?
I asked a similar question before, here is the link:
[Evaluating expressions called from Java in R. Out of Memory Error: Java Heap](https://stackoverflow.com/questions/8036438/evaluating-expressions-called-from-java-in-r-out-of-memory-error-java-heap)
|
2011/12/02
|
[
"https://Stackoverflow.com/questions/8357942",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/952425/"
] |
Have you tried adjusting the JVM Heap size by starting the executable with options?
Like:
```
java -Xmx1024m -Xms1024m myJar
```
You can adjust the memory values, obviously, but the option `-Xmx` sets the maximum heap size for the JVM and `-Xms` sets the initial size.
This may help if you are processing a lot of data that you actually need to retrieve, otherwise options (as suggested by cdeszaq) where you don't get any data back would obviously be best suited for you.
|
One way to do it that would allow you to call R without having anything come back to Java would be to call R as an external process. Since it looks like that is roughly what you are doing anyway, perhaps having the OS execute the call to R, rather than the library inside of Java, would prevent the overflow.
|
14,900,906 |
I am trying to create a image button and I want to give the specific width and height to it, but my image size 512 x 512 and when activity starts layout is distorted because of the image.
Is there anyway I can resize it to some specific size?
```
<Button
android:id="@+id/prev"
android:text=""
android:gravity="center"
android:width="20dp"
android:height="20dp"
android:background="@drawable/go_prev"
/>
```
|
2013/02/15
|
[
"https://Stackoverflow.com/questions/14900906",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1725388/"
] |
Yes. Set your layout\_width and layout\_height to numeric values and it will fix the image to that exact size. You can then control how its scaled or cropped vi the scaleType parameter. Be careful specifying dp or px- dp will let you specify it in 160ths of an inch, px will be phyiscal pixels (but may be any real world size).
|
You can specify the size in `px` which will be physical pixels instead of `dp` (Density-independent pixel); **However**, you should **not** do this if your app should support multiple screens.
Also, consider using `android:layout_height` and `android:layout_width` instead of `height` and `width`
|
70,405,640 |
What should be the css to align them in the same line?
```
<div class="discount-tab">
<h1 class="discount-heading">Book your first adventure with us at 10% discount</h1>
<button class="mdl-button mdl-js-button mdl-button--raised mdl-js-ripple-effect mdl-button--accent">Book now</button>
</div>
```
|
2021/12/18
|
[
"https://Stackoverflow.com/questions/70405640",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17223877/"
] |
You can set the `h1` tag to: `display: inline-block`. It'll only take up the space it needs that way.
Another approach, which might be even better is to make use of flexbox.
Flexbox can align all the items vertically and/or horizontally.
```
.discount-tab {
display: flex;
flex-direction: row;
align-items: center;
}
```
|
You can use `FlexBox` like this:([here](https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Flexible_Box_Layout/Basic_Concepts_of_Flexbox) you can read more about `FlexBox`)
```css
.discount-tab {
display: flex;
align-items: center;
}
```
```html
<div class="discount-tab">
<h1 class="discount-heading">Book your first adventure with us at 10% discount</h1>
<button class="mdl-button mdl-js-button mdl-button--raised mdl-js-ripple-effect mdl-button--accent">Book now</button>
</div>
```
|
70,405,640 |
What should be the css to align them in the same line?
```
<div class="discount-tab">
<h1 class="discount-heading">Book your first adventure with us at 10% discount</h1>
<button class="mdl-button mdl-js-button mdl-button--raised mdl-js-ripple-effect mdl-button--accent">Book now</button>
</div>
```
|
2021/12/18
|
[
"https://Stackoverflow.com/questions/70405640",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17223877/"
] |
You can use `FlexBox` like this:([here](https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Flexible_Box_Layout/Basic_Concepts_of_Flexbox) you can read more about `FlexBox`)
```css
.discount-tab {
display: flex;
align-items: center;
}
```
```html
<div class="discount-tab">
<h1 class="discount-heading">Book your first adventure with us at 10% discount</h1>
<button class="mdl-button mdl-js-button mdl-button--raised mdl-js-ripple-effect mdl-button--accent">Book now</button>
</div>
```
|
You can use [grid](https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Grid_Layout) `display: grid;` and add styling to button a little.
```css
.discount-tab {
display: grid;
align-items: center;
justify-content: center;
grid-template-columns: 4fr 1fr;
}
.mdl-button {
max-width: 100px;
}
```
```html
<div class="discount-tab">
<h1 class="discount-heading">Book your first adventure with us at 10% discount</h1>
<button class="mdl-button mdl-js-button mdl-button--raised mdl-js-ripple-effect mdl-button--accent">Book now</button>
</div>
```
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.