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
|
---|---|---|---|---|---|
37,534 |
I have a slightly high pH, 7.2. Nothing bad but I would like to bring it down a little. I was looking at two elements/products whatever you want to call them. One was Aluminum Sulfate and the other was Sulfur.
The things I know is it does not take near as much S to bring down pH, were it does take a lot of AlS.
But I do not know if there is anything wrong with AlS or S. I would really like to know the negative effects of either, if any. Thanks!
AlS - Aluminum Sulfate
S - Sulfur
|
2018/03/14
|
[
"https://gardening.stackexchange.com/questions/37534",
"https://gardening.stackexchange.com",
"https://gardening.stackexchange.com/users/14214/"
] |
Lowering soil ph isn't a one off treatment - it needs to be ongoing, with frequent soil tests to check its not getting too low. Sulphur is the safest from a planting point of view, but takes longer to work in cold weather. Aluminium sulphate works more quickly, but its easy to overdose - it can build up in the soil to toxic levels, and reduces phosphorus levels, which can cause significant problems for plants. Sulphate of iron is sometimes used, and can create similar issues with phosphorus availability. Another factor is whether there is free lime or chalk in your soil - if there is, then attempts at lowering the ph are not likely to be successful. Information here <https://www.rhs.org.uk/advice/profile?PID=82>
Aluminium sulphate and sulphate of iron are usually applied around specific plants rather than applied to a whole area, the former often to produce bluer flowers in Hydrangea, and the latter for similar reasons and to correct leaf chlorosis in acid loving shrubs. You might want to consider finding plants that suit the soil you've got rather than trying to keep the ph lower ongoing if you were thinking to change soil ph in a large area.
|
As noted , you need a large amount of material to change soil pH. I have used calcium sulfate aka, gypsum / dry wall. I could get broken wall dry wall for free in pick-up truck quantities ( for a 1500 sq ft garden) . There is a little nuisance with the paper surfaces. It is not as satisfying as the pouring conc. sulfuric on the garden , but that is not for everyone.
|
37,534 |
I have a slightly high pH, 7.2. Nothing bad but I would like to bring it down a little. I was looking at two elements/products whatever you want to call them. One was Aluminum Sulfate and the other was Sulfur.
The things I know is it does not take near as much S to bring down pH, were it does take a lot of AlS.
But I do not know if there is anything wrong with AlS or S. I would really like to know the negative effects of either, if any. Thanks!
AlS - Aluminum Sulfate
S - Sulfur
|
2018/03/14
|
[
"https://gardening.stackexchange.com/questions/37534",
"https://gardening.stackexchange.com",
"https://gardening.stackexchange.com/users/14214/"
] |
The classic old method: manure, especially on your case, where you have a nearly neutral soil. But in general fertilizers acidify the soil, so often this is enough for vegetable garden (one fertilize near seedling). Not doing lawn scarifier helps (also this remove acidity, which is bad for lawn in a acid soil, but not so bad on normal soils). On flower garden: some plants/tree help to acidify soil, so with a good placement of element, you can have a acid corner. Peat-like substances are (should be) also acidifier.
Normally plants usually tolerate acid soil (but not extreme), but only plants evolved to tolerate Calcium can live in a non-acid soil: roots absorb nutrients, but if there is much calcium, acid plants absorb calcium and not the other needed substances.
About your product: "Sulphur" usually (and unfortunately) is just a nametag. Also that should be a sulphur salt/component.
The possible problem: the soil is huge, so nutrients moves, and basic soil will neutralize your acidifier, but the real problem is the watering. Usually water is also not neutral if your soil is not neutral. So you need to acidify periodically. Microorganism could not like many changes on acidity, so soil could become poorer. But this is often a problem on the inverse step: there is already acid parts on soil (see decomposition of leaves), so also acidophile organism. Soil pollution is also a problem, because acidifier could go into groundwater. But this is usually a problem with huge fields (and fertilizing at the same instant such large area).
So: check acidity of your water, and the structure of your soil. If water is not so basic, it is ok, else consider to collect rain water (before soil will increase the pH). If soil is light and sandy, your acidification will fail, and basic ions will enter so easily (so you need a waterproof "wall" inside the soil). On the other cases (more common): if you are building new gardening (in deep), you can uses several (and slow) acidifier on the base of soil. In any case, try with more natural methods and limited near root of the vegetables you need to acidify. Sulphur is not so bad (it is a common natural element), just it could wash away and cause some problem on other places, and drastic pH changes kill the soil, but nature will recover quickly.
|
Applying elemental sulfur, or brimstone, to acidify alkaline soil with a high lime content is not cost effective. Bacteria act on the sulfur to turn it into sulfuric acid which acidifies the soil temporarily but then the carbonates present in the soil will return the pH back to what it was before.
[](https://i.stack.imgur.com/ZdLcJ.jpg)
You are better off to apply composted manure and other organic materials. The humic acid present in the compost will free up phosphorus to the plants. You need to maintain a high level of organic material in the ground.
<https://www.agvise.com/educational-articles/does-elemental-sulfur-lower-soil-ph/>
|
37,534 |
I have a slightly high pH, 7.2. Nothing bad but I would like to bring it down a little. I was looking at two elements/products whatever you want to call them. One was Aluminum Sulfate and the other was Sulfur.
The things I know is it does not take near as much S to bring down pH, were it does take a lot of AlS.
But I do not know if there is anything wrong with AlS or S. I would really like to know the negative effects of either, if any. Thanks!
AlS - Aluminum Sulfate
S - Sulfur
|
2018/03/14
|
[
"https://gardening.stackexchange.com/questions/37534",
"https://gardening.stackexchange.com",
"https://gardening.stackexchange.com/users/14214/"
] |
The classic old method: manure, especially on your case, where you have a nearly neutral soil. But in general fertilizers acidify the soil, so often this is enough for vegetable garden (one fertilize near seedling). Not doing lawn scarifier helps (also this remove acidity, which is bad for lawn in a acid soil, but not so bad on normal soils). On flower garden: some plants/tree help to acidify soil, so with a good placement of element, you can have a acid corner. Peat-like substances are (should be) also acidifier.
Normally plants usually tolerate acid soil (but not extreme), but only plants evolved to tolerate Calcium can live in a non-acid soil: roots absorb nutrients, but if there is much calcium, acid plants absorb calcium and not the other needed substances.
About your product: "Sulphur" usually (and unfortunately) is just a nametag. Also that should be a sulphur salt/component.
The possible problem: the soil is huge, so nutrients moves, and basic soil will neutralize your acidifier, but the real problem is the watering. Usually water is also not neutral if your soil is not neutral. So you need to acidify periodically. Microorganism could not like many changes on acidity, so soil could become poorer. But this is often a problem on the inverse step: there is already acid parts on soil (see decomposition of leaves), so also acidophile organism. Soil pollution is also a problem, because acidifier could go into groundwater. But this is usually a problem with huge fields (and fertilizing at the same instant such large area).
So: check acidity of your water, and the structure of your soil. If water is not so basic, it is ok, else consider to collect rain water (before soil will increase the pH). If soil is light and sandy, your acidification will fail, and basic ions will enter so easily (so you need a waterproof "wall" inside the soil). On the other cases (more common): if you are building new gardening (in deep), you can uses several (and slow) acidifier on the base of soil. In any case, try with more natural methods and limited near root of the vegetables you need to acidify. Sulphur is not so bad (it is a common natural element), just it could wash away and cause some problem on other places, and drastic pH changes kill the soil, but nature will recover quickly.
|
As noted , you need a large amount of material to change soil pH. I have used calcium sulfate aka, gypsum / dry wall. I could get broken wall dry wall for free in pick-up truck quantities ( for a 1500 sq ft garden) . There is a little nuisance with the paper surfaces. It is not as satisfying as the pouring conc. sulfuric on the garden , but that is not for everyone.
|
37,534 |
I have a slightly high pH, 7.2. Nothing bad but I would like to bring it down a little. I was looking at two elements/products whatever you want to call them. One was Aluminum Sulfate and the other was Sulfur.
The things I know is it does not take near as much S to bring down pH, were it does take a lot of AlS.
But I do not know if there is anything wrong with AlS or S. I would really like to know the negative effects of either, if any. Thanks!
AlS - Aluminum Sulfate
S - Sulfur
|
2018/03/14
|
[
"https://gardening.stackexchange.com/questions/37534",
"https://gardening.stackexchange.com",
"https://gardening.stackexchange.com/users/14214/"
] |
As noted , you need a large amount of material to change soil pH. I have used calcium sulfate aka, gypsum / dry wall. I could get broken wall dry wall for free in pick-up truck quantities ( for a 1500 sq ft garden) . There is a little nuisance with the paper surfaces. It is not as satisfying as the pouring conc. sulfuric on the garden , but that is not for everyone.
|
Applying elemental sulfur, or brimstone, to acidify alkaline soil with a high lime content is not cost effective. Bacteria act on the sulfur to turn it into sulfuric acid which acidifies the soil temporarily but then the carbonates present in the soil will return the pH back to what it was before.
[](https://i.stack.imgur.com/ZdLcJ.jpg)
You are better off to apply composted manure and other organic materials. The humic acid present in the compost will free up phosphorus to the plants. You need to maintain a high level of organic material in the ground.
<https://www.agvise.com/educational-articles/does-elemental-sulfur-lower-soil-ph/>
|
74,203,490 |
is there a filtered view of a collection (a subset of it) in Java, so that adding new item to it can also affect the source collection?
e.g.
```
List<String> source = new ArrayList<>();
source.add("a");
source.add("b");
List<String> view = source.stream().filter(i -> "b".equals(i)).collect(...);
view.add("c"); // source now contains also "c"
```
|
2022/10/26
|
[
"https://Stackoverflow.com/questions/74203490",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1589188/"
] |
JDK provides only index-based view of the list with the method [`List::subList`](https://docs.oracle.com/javase/8/docs/api/java/util/List.html#subList-int-int-):
>
> The returned list is backed by this list, so non-structural changes in the returned list are reflected in this list, and vice-versa.
>
>
>
Thus, the changes to the view can be applied to the source list too if the "filter" is constructed using `List::indexOf` and/or `List::lastIndexOf`.
This should be enough for a limited case of having *a single range* matching the condition:
```java
List<String> source = new ArrayList<>();
source.add("a");
source.add("b");
source.add("b");
List<String> view = source.subList(source.indexOf("b"), source.lastIndexOf("b") + 1);
System.out.println("view: " + view);
view.add("c");
System.out.println("added view: " + view);
System.out.println("fixed src: " + source);
```
Output:
```
view: [b, b]
added view: [b, b, c]
fixed src: [a, b, b, c]
```
---
As for the *filtered view* of a list which stores all the source's elements matching some condition, such view would have to maintain a collection of sublists/subranges in general case and implement `List` interface appropriately.
The Guava [`Collections2.filter`](https://guava.dev/releases/19.0/api/docs/com/google/common/collect/Collections2.html#filter(java.util.Collection,%20com.google.common.base.Predicate)) mentioned by @Wilderness Ranger [above](https://stackoverflow.com/a/74206671/13279831) may be an example of the filtered view, however, its documentation states that its methods `add`/`addAll` would throw `IllegalArgumentException` if the predicate is not satisfied, so in your example an attempt to add "c" would fail for the predicate `"b"::equals`.
|
Of course. You can create one by yourself by subclassing `AbstractCollection` (which implements most of the methods in `Collection` and you just need to write a few methods according to your needs). Then add the underlying collection as a member, override getters to apply the predicate to it and return the filtered results, override `add(E)` to put elements, and then it can basically work.
In fact, [Guava](https://guava.dev/) library has already provided [`Collections2.filter(Collection, Predicate)`](https://guava.dev/releases/snapshot-jre/api/docs/com/google/common/collect/Collections2.html#filter(java.util.Collection,com.google.common.base.Predicate)) (and also its set and map versions, but no list variant as indices become a problem when filtered) through which you can create a performant filtered view of any `Collection` by a predicate function easily, allowing additions if the underlying collection is mutable and *the predicate is satisfied*. (Its mechanism is not complex, so you can also copy its implementation if not willing to include one more library ;) Please note that, however, as `"c"` does not satisfy the predicate above, `IllegalArgumentException` will be thrown in OP's example. But still, you can subclass `AbstractCollection` and pass everything else to the filtered view but add to the underlying collection directly. The only problem is this kind of "add" operation will not follow collection's general contract.
**Update:** However, there seems to be no way to construct a two-way view from `Stream` like OP's example, as operators do not know the sources of streams, and streams flow in one way.
|
44,923,551 |
Im' trying to iterate over an object with an an array of string in it but I'm struggling to do it
Output of the **var\_dump** of the object I'm trying to iterate:
```
object(fooClass)#88(2) {
["property1:protected"]=> string(3) "foo"
["property2"]=> array(2) {
["foo1"]=> string(4) "foo1"
["foo2"]=> string(4) "foo2"}
}
```
(**Edit**)But when I try to use an arrayIterator to iterate over the object with this code:
```
$obj = new ArrayObject($value);
$it = $obj->getIterator();
echo "iterating over: " . $obj->count() . " values <br />";
while ($it->valid()){
echo $it->key() . "=" . $it->current() . "<br />" ;
$it->next();
}
```
I have this **output**:
```
iterating over: 1 values
*property1=foo
```
**Edit:** What I'm expecting is something like that:
```
iterating over 3 values
*property1=foo
*foo1=foo1
*foo2=foo2
```
|
2017/07/05
|
[
"https://Stackoverflow.com/questions/44923551",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6322913/"
] |
It's hard to guess what you want from your question. You mentioned "correct order" without defining it.
[You can use `GROUP_CONCAT()` in these ways.](https://dev.mysql.com/doc/refman/5.7/en/group-by-functions.html#function_group-concat)
```
GROUP_CONCAT(a.b) -- gets all the items in column b -- cardinality preserved
GROUP_CONCAT(DISTINCT a.b) -- distinct values in column b -- cardinality reduced
GROUP_CONCAT(a.b ORDER BY a.b) -- all items in b in order
GROUP_CONCAT(DISTINCT a.b ORDER BY a.b) -- distinct items in b in order
GROUP_CONCAT(a.b ORDER BY a.c) -- all items in b in the same order as c
```
I'm not completely sure what it means to an application to add DISTINCT to the last one.
If you're trying to get two concatenated columns in corresponding order, you can't use `DISTINCT` in either one; `DISTINCT` has the potential to remove duplicate values.
Your result set column mentions `_average`. You get an actual average (arithmetic mean) with `AVG(value)`. and that gives a single aggregate number.
If you want a list of scores in one column and a corresponding list of titles in another, try this.
```
GROUP_CONCAT(
recommendations.recommendations_vote_average
ORDER BY recommendations.recommendations_title
) AS recommendations_vote_average,
GROUP_CONCAT(
recommendations.recommendations_title
ORDER BY recommendations.recommendations_title
) AS recommendations_title
```
That presents the two concatenated lists in order by the title.
You may not be aware of this: rows in DBMS tables **have no inherent order**. If you say `SELECT * FROM table` (without an `ORDER BY` clause) more than once, and the rows come out in the same order each time, **it is an accident.** There's nothing in your recommendations table -- no unique id values for example -- to give the order of those items except the scores and the titles. So you may not be able to get the exact order you want.
Many tables contain an autoincrementing `id` column (but yours does not). Using such an `id` column in `ORDER BY` clauses is a way to get repeatable ordering.
**Pro tip:** Denormalized data (comma separated data in columns, for example) is often considered harmful. `GROUP_CONCAT()` turns normalized data, like your input, into denormalized data. So use it sparingly and only when you need it.
|
To get the requested result I think all you need to do is to remove DISTINCT, but I would also recommend introducing an ORDER BY
```
SELECT
tmdb_movies.movie_title
, GROUP_CONCAT(r.recommendations_vote_average
ORDER BY r.recommendations_vote_average DESC
SEPARATOR ', '
) as recommendations
, GROUP_CONCAT(r.recommendations_title
ORDER BY r.recommendations_vote_average DESC
SEPARATOR ', '
) as recommendations
FROM tmdb_movies
LEFT JOIN recommendations r ON r.recommendations_tmdb_id=tmdb_movies.tmdb_id
Where tmdb_movies.tmdb_id=1
GROUP BY tmdb_movies.movie_title
;
recommendations | recommendations |
+----+-----------------+----------------------------------------------+---------------------------------------------------------------------------------+
| 1 | The Dark Knight | 8.1, 8, 8, 7.9, 7.9, 7.5, 7.5, 7.3, 6.6, 6.6 | The Lord of the Rings: The Return of the King, Inception, |
| | | | The Lord of the Rings: The The Fellowship of the Ring, The Matrix, |
| | | | The Lord of the Rings: The Two Towers, Batman Begins, |
| | | | The Dark Knight Rises, Iron Man, Captain America: The First Avenger, Iron Man 2 |
+----+-----------------+----------------------------------------------+---------------------------------------------------------------------------------+
```
If it were up to me I would be combining the recommendation score with title (manual line breaks added for presentation):
```
+----+-----------------+-------------------------------------------------------------------------
| | movie_title | recommendations |
+----+-----------------+-------------------------------------------------------------------------
| 1 | The Dark Knight | 8.1(The Lord of the Rings: The Return of the King);
| 8(Inception); 8(The Lord of the Rings: The The Fellowship of the Ring);
| 7.9(The Matrix); 7.9(The Lord of the Rings: The Two Towers);
| 7.5(Batman Begins); 7.5(The Dark Knight Rises);
| 7.3(Iron Man); 6.6(Captain America: The First Avenger); 6.6(Iron Man 2)
```
which was produced by this query:
```
SELECT
tmdb_movies.movie_title
, GROUP_CONCAT(DISTINCT concat(r.recommendations_vote_average,'(',r.recommendations_title,')')
ORDER BY r.recommendations_vote_average DESC
SEPARATOR '; '
) as recommendations
FROM tmdb_movies
LEFT JOIN recommendations r ON r.recommendations_tmdb_id=tmdb_movies.tmdb_id
Where tmdb_movies.tmdb_id=1
GROUP BY tmdb_movies.movie_title
```
---
more info.
The following query reverses the table precedence and doesn't use group\_concat
```
select
m.movie_title, r.*
from recommendations r
left join tmdb_movies m ON r.recommendations_tmdb_id=m.tmdb_id
;
```
Result:
```
+----+-----------------+-------------------------+-------------------------------------------------------+------------------------------+
| | movie_title | recommendations_tmdb_id | recommendations_title | recommendations_vote_average |
+----+-----------------+-------------------------+-------------------------------------------------------+------------------------------+
| 1 | The Dark Knight | 1 | The Dark Knight Rises | 7.5 |
| 2 | The Dark Knight | 1 | Batman Begins | 7.5 |
| 3 | The Dark Knight | 1 | Iron Man | 7.3 |
| 4 | The Dark Knight | 1 | The Lord of the Rings: The Return of the King | 8.1 |
| 5 | The Dark Knight | 1 | The Lord of the Rings: The The Fellowship of the Ring | 8 |
| 6 | The Dark Knight | 1 | The Lord of the Rings: The Two Towers | 7.9 |
| 7 | The Dark Knight | 1 | The Matrix | 7.9 |
| 8 | The Dark Knight | 1 | Inception | 8 |
| 9 | The Dark Knight | 1 | Iron Man 2 | 6.6 |
| 10 | The Dark Knight | 1 | Captain America: The First Avenger | 6.6 |
+----+-----------------+-------------------------+-------------------------------------------------------+------------------------------+
```
sample data (should have been in question):
```
CREATE TABLE tmdb_movies (
tmdb_id INTEGER NOT NULL PRIMARY KEY,
movie_title TEXT NOT NULL
);
INSERT INTO tmdb_movies (tmdb_id, movie_title) VALUES
(1, 'The Dark Knight');
CREATE TABLE recommendations (
recommendations_tmdb_id INTEGER NOT NULL,
recommendations_title TEXT NOT NULL,
recommendations_vote_average TEXT NOT NULL
);
INSERT INTO recommendations (recommendations_tmdb_id, recommendations_title, recommendations_vote_average) VALUES
(1, 'The Dark Knight Rises', '7.5'),
(1, 'Batman Begins', '7.5'),
(1, 'Iron Man', '7.3'),
(1, 'The Lord of the Rings: The Return of the King', '8.1'),
(1, 'The Lord of the Rings: The The Fellowship of the Ring', '8'),
(1, 'The Lord of the Rings: The Two Towers', '7.9'),
(1, 'The Matrix', '7.9'),
(1, 'Inception', '8'),
(1, 'Iron Man 2', '6.6'),
(1, 'Captain America: The First Avenger', '6.6');
```
|
44,705,195 |
There is a .NET WCF service running under an app pool in IIS 8 in Windows Server 2012. The memory usage of the app pool keeps increasing every time the service is called. (It drops slightly when the service is idle). The memory consumption is now at 1GB. The memory usage reduces only when the app pool gets recycled which is currently set at its default of 29 hrs.
Is this type of memory consumption an expected behavior? I was under the impression that the memory would be released once the request is complete
|
2017/06/22
|
[
"https://Stackoverflow.com/questions/44705195",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8201061/"
] |
Whether this is expected or not is going to depend on a number of things, including what the service does, what the code looks like, what resources are used, what kind of service activation you configured and the binding and more.
The question is going to be to figure out if what you're really seeing a memory leak or not, but that will require a lot more information, including a careful analysis of the "CLR Memory" performance counters and OS counters such as "Process\Handle Count" and "Process\Private Bytes".
I'd suggest starting first with a through analysis of performance counters to determine if you're really seeing a leak or not, and then using tools such as PerfView and dump analysis to figure out what's going on.
|
Normlaly .NET garbage collector will release the memory after use provided you have written code perfectley fine.In your case your application is having memory leak as some part of the code or some library you are using is consuming the memory and not releaseit.A simple example can be
*A static collection defined which loads some data from database . This will never be collected by GC as in our code we have defined it as static.Similarly there are other causes like a Session data ,[MemoryCache](https://msdn.microsoft.com/en-us/library/system.runtime.caching.memorycache(v=vs.110).aspx), [dynamic assemblies,](https://blogs.msdn.microsoft.com/tess/2010/05/05/net-memory-leak-xslcompiledtransform-and-leaked-dynamic-assemblies/) and countless others.*
For more information on how it can happen ,check [Common Causes of Memory Leaks](https://blogs.msdn.microsoft.com/davidklinems/2005/11/16/three-common-causes-of-memory-leaks-in-managed-applications/) , [what to do for memory leak](https://blogs.msdn.microsoft.com/tess/2005/11/25/i-have-a-memory-leak-what-do-i-do-defining-the-where/) ,[causes of leak SO post](https://stackoverflow.com/questions/672810/what-are-the-most-common-and-often-overlooked-causes-of-memory-leaks-in-manage).
>
> In effect,first you have to [investigate the cause of the memory leak](https://www.codeproject.com/Articles/42721/Best-Practices-No-Detecting-NET-application-memo)
> and then fix the code or library which is leaking memory.
>
>
>
|
63,433,370 |
i am trying to pass values of filtered chips that a user has selected in order to retrieve only the required shops he want in that particular criteria.
now i created everything and the data i am getting after finishing from my FilterActivity is being passed into my HomeActivity. but this data is not being 'read' or 'accepted' inside my query since it doesn't produce the correct output. When i use a static value inside the query it would work. now i need it to be a changing value depending on what the use has selected.
This is inside my HomeActivity that opens the Filter Activity:
```
filterBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent = new Intent(HomeActivity.this,FilterActivity.class);
startActivityForResult(intent,101);
}
});
```
this is my FilterActivity with a few examples:
```
private Chip rate2,rate3,rate4;
private ArrayList<String> selectedChipData;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_filter);
rate2 = findViewById(R.id.chip_Rate_2);
selectedChipData = new ArrayList<>();
CompoundButton.OnCheckedChangeListener checkedChangeListener = new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton compoundButton, boolean isChecked) {
if(isChecked){
selectedChipData.add(compoundButton.getText().toString().trim());
}else{
selectedChipData.remove(compoundButton.getText().toString().trim());
}
}
};
rate2.setOnCheckedChangeListener(checkedChangeListener);
}
```
and this is the button the user clicks when he wants to apply one of the filter options:
```
filter_reset = findViewById(R.id.filter_reset);
filter_reset.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent resultIntent = new Intent();
resultIntent.putExtra("data",selectedChipData.toString().trim());
setResult(101,resultIntent);
finish();
}
});
```
now in my HomeActivity i created the onActivityResult:
```
String Data;
@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode==101){
Data = data.getStringExtra("data");
Log.d("TAG", data.getStringExtra("data"));
Query q = firebaseFirestore.collection("Shops").whereEqualTo("location",Data);
}
}
Query q = firebaseFirestore.collection("Shops").whereEqualTo("location",Data);
// this is my query and how i am trying to pass the matched users selected chip to the location of the Shops table.
```
What am i missing or doing wrong inside my query and how to fix it? can someone advise?
|
2020/08/16
|
[
"https://Stackoverflow.com/questions/63433370",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
Simple answer - you can't, because there is no way to mount a volume for `docker build` command.
I'm assuming your end goal is a Docker image that runs contains your project's built jar or war.
To accomplish that you need two Dockerfiles - one that can be used to create a container that will build your project and exit and a second one that will describe the image that you actually want - one that can be used to create a container that runs your project.
There is a nice article describing how to create and use the first one [here](https://dzone.com/articles/maven-build-local-project-with-docker-why). As
for the second one, that depends on whether your project builds as jar or a war and how it needs to be started/deployed.
|
There is two ways of managing libraries (including private):
1. (old way) copy your compiled library to your project lib directory and make sure your project pick it up.
2. use some repository management software. Good options is - Artifactory <https://jfrog.com/artifactory> or Nexus repository management - <https://www.sonatype.com/product-nexus-repository>
|
56,382,562 |
I wanted to make a method writing to DB as async using `@Async` annotation.
I marked the class with the annotation `@EnableAsync`:
```
@EnableAsync
public class FacialRecognitionAsyncImpl {
@Async
public void populateDataInPushQueue(int mediaId, int studentId) {
//myCode
}
}
```
while calling the `populateDataInPushQueue` method, the write operation should be executed in another thread and the flow should continue from the class I am calling this method. But this is not happening and the program execution is waiting for this method to complete.
|
2019/05/30
|
[
"https://Stackoverflow.com/questions/56382562",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6641035/"
] |
The [`@Async`](https://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/scheduling/annotation/Async.html) annotation has few limitations - check whether those are respected:
* it must be applied to `public` methods only
* it cannot be called from the same class as defined
* the return type must be either `void` or [`Future`](https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/Future.html)
The following can be found at the documentation of [`@EnableAsync`](https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/scheduling/annotation/EnableAsync.html):
>
> Please note that proxy mode allows for the interception of calls through the proxy only; local calls within the same class cannot get intercepted that way.
>
>
>
Another fact is that the class annotated with [`@EnableAsync`](https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/scheduling/annotation/EnableAsync.html) must be a [`@Configuration`](https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/context/annotation/Configuration.html) as well. Therefore start with an empty class:
```
@EnableAsync
@Configuration
public class AsyncConfiguration { }
```
|
In my opinion, you are missing `@Configuration` annotation and your async service is not component scanned. Here is an example code fragment that should do the trick:
```
@Configuration
@EnableAsync //should be placed together.
public class FacialRecognitionAsyncService {
@Async
public void populateDataInPushQueue(int mediaId, int studentId) {
//myCode
}
}
@Configuration
@EnableAsync
public class FacialServiceConfig {
// this will make your service to be scanned.
@Bean
public FacialRecognitionAsyncService createFacialRecognitionService() {
return new FacialRecognitionAsyncService();
}
}
```
Now the service bean that is invoking the async method. Notice that it has been dependency injected. This way spring AOP proxies will be invoked on each invocation fo the `facialService`. Spring uses AOP in the back scenes in order to implement `@Async`.
```
@Service
public class MyBusinessService {
@Autowire
FacialRecognitionAsyncService facialService;
public myBusinessMethod() {
facialService.populateDataInPushQueue()
}
```
Notice that `FacialService` is injected in `MyService` through dependency injection.
|
24,212 |
>
> **Possible Duplicate:**
>
> [Suitable alternative to trackbar control](https://ux.stackexchange.com/questions/22330/suitable-alternative-to-trackbar-control)
>
>
>
In our application, there are settings that have a high dynamic range (e.g. 0-10000 in steps of 0.1). I am in need of a UI to adjust these using touch control only and limited screen space, since this appltcation is running on an embedded device.
What we tried so far and found lacking:
* a standard slider (not sensitive enough)
* buttons like +0.1, +1, +10, +100 (require lots of clicks or lots of buttons and are deemed unsexy by marketing)
* a centered slider controlling the velocity of change, i.e. pulling the slider to the right makes the value increase (testers found this difficult to grasp)
Are there any tried and true ways to do this?
|
2012/08/01
|
[
"https://ux.stackexchange.com/questions/24212",
"https://ux.stackexchange.com",
"https://ux.stackexchange.com/users/10279/"
] |
I can't comment on the technical side of this - that might be a question fro Stack Overflow - but for a UX perspective I think the most obvious way to do this on a touch screen is a touch-and-hold with a scale of sensitivity.
Strange example I know, but the only place I can think of this being used is on treadmills at the gym. The speed increments are 0.1 if you press the button to go up. If you hold it, the speed will increase by 0.1kmph 3 or 4 times, then 0.5kmph a couple of times, then 1kmph.
As you're looking to use touch controls the user doesn't need to go looking for the functionality if you use this approach. They will natrually press and hold to go up (some may multi tap) unlike the other methods where the user has to first figure out what to do.
Just so I know I've read correctly, is 10.000 meant to represent 10.00 or 10,000.00 - i.e. if your increment value is 0.1 do you have 100 potential values or 100,000 potential values?
|
If it's that hard, why don't you consider a simple numeric keypad?
```
1 2 3
4 5 6
7 8 9
. 0 <
```
And they can use any increment they want :)
But yes, touch-and-hold is also a possible solution, just like microwave ovens do.
And any way make sure that there's a confirmation step, exactly because of the overshoot.
Or go logarhythmic, those who want 0.1 increments might not want to set it to 0.1 degree...
|
2,237,858 |
I need help finding the partial fraction decomposition for this function, I am just lost on it, here it is:
$(x^2 + x + 1)/(2x^4+3x^2+1)$. the help is appreciated. thank you.
|
2017/04/17
|
[
"https://math.stackexchange.com/questions/2237858",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/437234/"
] |
$$\begin{array}{rcl}
\displaystyle \sum\_{n=0}^\infty \dfrac{(-1)^n}{2n+1}
&=& \displaystyle \sum\_{n=0}^\infty \int\_0^1 (-1)^n x^{2n} \ \mathrm dx \\
&=& \displaystyle \sum\_{n=0}^\infty \int\_0^1 (-x^2)^n \ \mathrm dx \\
&=& \displaystyle \int\_0^1 \sum\_{n=0}^\infty (-x^2)^n \ \mathrm dx \\
&=& \displaystyle \int\_0^1 \dfrac1{1+x^2} \ \mathrm dx \\
&=& \displaystyle \left(\arctan x\right)\_0^1 \\
&=& \displaystyle \dfrac\pi4 \\
\displaystyle \sum\_{n=0}^\infty \dfrac{(-1)^n}{(2n+1)(2n+3)}
&=& \dfrac12 \displaystyle \sum\_{n=0}^\infty \dfrac{(-1)^n}{2n+1} - \dfrac12\displaystyle \sum\_{n=0}^\infty \dfrac{(-1)^n}{2n+3} \\
&=& \dfrac12 \displaystyle \sum\_{n=0}^\infty \dfrac{(-1)^n}{2n+1} + \dfrac12\displaystyle \sum\_{n=1}^\infty \dfrac{(-1)^n}{2n+1} \\
&=& \displaystyle \sum\_{n=0}^\infty \dfrac{(-1)^n}{2n+1} - \dfrac12 \\
&=& \dfrac\pi4 - \dfrac12 \\
\end{array}$$
|
Maybe you will like this method. Let
$$ f(x)=\sum\_{n=0}^\infty \frac{(-1)^n}{(2n+3)(2n+1)}x^{2n+3}.$$
Then
$$ f'(x)=\sum\_{n=0}^\infty \frac{(-1)^n}{2n+1}x^{2n+2}, (\frac{f(x)}{x})'=\sum\_{n=0}^\infty(-1)^nx^{2n}=\frac{1}{1+x^2}.$$
So
$$ f(1)=\int\_0^1x\int\_0^x\frac{1}{1+t^2}dtdx=\int\_0^1x\arctan xdx=\frac{\pi}{4}-\frac12. $$
|
1,736,551 |
Let $\psi$ be a smooth function with compact support, and $\phi$ is smooth and $\phi'(x) \neq 0$ for any $x$ in support of $\psi$. Define $$I(\lambda) = \int\_\mathbb{R} e^{i\lambda \phi(x)}\psi(x) dx$$ for $\lambda > 0.$ Then there exists a constant $c$ such that $$|I(\lambda)| \leq c\lambda^{-a}$$ for any $a > 0$ as $\lambda \rightarrow \infty.$
I guess I should apply integration by parts to have some term related to $\lambda$, but it does not work. Any suggestion or guidance what to try ?
--------------------------------- update ------------------------------
First set $$F(\psi)(\lambda) = I(\lambda),$$ then $$F(\psi')(\lambda) = \int\_\mathbb{R} e^{i\lambda \phi(x)}\psi'(x) dx = (-i\lambda)F(\phi'\psi).$$
Generally, $$F(\psi^p)(\lambda) = (-i\lambda)^pF((\phi')^p\psi)$$ for $p \in \mathbb{N}.$ Then, by compactness of $\psi$, $$|\int\_\mathbb{R} e^{i\lambda \phi(x)}\psi(x)(\phi')^p dx| \leq C.$$
I want to show that, somehow,
$|I(\lambda)| \leq k|\int\_\mathbb{R} e^{i\lambda \phi(x)}\psi(x)(\phi')^p dx| $ for some constant $k$, but I get stuck.
|
2016/04/10
|
[
"https://math.stackexchange.com/questions/1736551",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/117375/"
] |
The thing to remember is $\log b^c = c \log b.$ In your cases, $\log 5^{\log x} = \log x \; \log 5$ and $\log x^{\log 5} = \log 5 \; \log x.$ Put them together,
$$ 5^{\log x} = x^{\log 5} $$
|
Rewrite the statement:
$$5^{\ln{x}} + 5\cdot5^{\log\_{5}{x}\ln{5}} = 5^{\ln{x}} + 5\cdot5^{lnx} = 6\cdot5^{\ln{x}} = 3$$,then $$x = e^{\log\_{5}{\frac{1}{2}}}$$
|
2,238,103 |
I am new to iPhone development. I want to access a string variable in all the class methods, and I want to access that string globally. How can I do this?
Please help me out.
|
2010/02/10
|
[
"https://Stackoverflow.com/questions/2238103",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/249916/"
] |
Leaving aside the issue of global variables and if they are good coding practice...
Create your string outside of any Objective-C class in a `.m` file in your project:
```
NSString *myGlobalString = @"foo";
```
Then put the declaration in a header file that is included by every other file that wants to access your string:
```
extern NSString *myGlobalString;
```
OK, well I can't leave it entirely aside. Have you considered putting your "global" string somewhere else, perhaps inside your application delegate as a (possibly read-only) property?
|
The preferred methods for creating a global variable are:
1. Create a singleton class that stores
the variables as an attributes.
2. Create a class that has class methods that return the variables.
Put the class interface in the
universal header so all classes in
the project inherit it.
The big advantage of method (2) is that it is encapsulated and portable. Need to use classes that use the global in another project? Just move the class with the variables along with them.
|
2,238,103 |
I am new to iPhone development. I want to access a string variable in all the class methods, and I want to access that string globally. How can I do this?
Please help me out.
|
2010/02/10
|
[
"https://Stackoverflow.com/questions/2238103",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/249916/"
] |
Leaving aside the issue of global variables and if they are good coding practice...
Create your string outside of any Objective-C class in a `.m` file in your project:
```
NSString *myGlobalString = @"foo";
```
Then put the declaration in a header file that is included by every other file that wants to access your string:
```
extern NSString *myGlobalString;
```
OK, well I can't leave it entirely aside. Have you considered putting your "global" string somewhere else, perhaps inside your application delegate as a (possibly read-only) property?
|
You can achieve that by implementing getter and setters in the delegate class.
In delegate .h file
Include UIApplication delegate
```
@interface DevAppDelegate : NSObject <UIApplicationDelegate>
NSString * currentTitle;
- (void) setCurrentTitle:(NSString *) currentTitle;
- (NSString *) getCurrentTitle;
```
In Delegate implementation class .m
```
-(void) setCurrentLink:(NSString *) storydata{
currentLink = storydata;
}
-(NSString *) getCurrentLink{
if ( currentLink == nil ) {
currentLink = @"Display StoryLink";
}
return currentLink;
}
```
So the variable you to assess is set in the currentlink string by setters method and class where you want the string ,just use the getter method.
All the best
|
2,238,103 |
I am new to iPhone development. I want to access a string variable in all the class methods, and I want to access that string globally. How can I do this?
Please help me out.
|
2010/02/10
|
[
"https://Stackoverflow.com/questions/2238103",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/249916/"
] |
Leaving aside the issue of global variables and if they are good coding practice...
Create your string outside of any Objective-C class in a `.m` file in your project:
```
NSString *myGlobalString = @"foo";
```
Then put the declaration in a header file that is included by every other file that wants to access your string:
```
extern NSString *myGlobalString;
```
OK, well I can't leave it entirely aside. Have you considered putting your "global" string somewhere else, perhaps inside your application delegate as a (possibly read-only) property?
|
I posted an article about my methodology for doing this:
<http://www.pushplay.net/2011/02/quick-tip-global-defines/>
This is something I primarily use for notification keys. Creating a globals.h file and adding it to the (your\_project\_name)\_Prefix.pch file will ensure it is accessible globally...
|
2,238,103 |
I am new to iPhone development. I want to access a string variable in all the class methods, and I want to access that string globally. How can I do this?
Please help me out.
|
2010/02/10
|
[
"https://Stackoverflow.com/questions/2238103",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/249916/"
] |
The preferred methods for creating a global variable are:
1. Create a singleton class that stores
the variables as an attributes.
2. Create a class that has class methods that return the variables.
Put the class interface in the
universal header so all classes in
the project inherit it.
The big advantage of method (2) is that it is encapsulated and portable. Need to use classes that use the global in another project? Just move the class with the variables along with them.
|
I posted an article about my methodology for doing this:
<http://www.pushplay.net/2011/02/quick-tip-global-defines/>
This is something I primarily use for notification keys. Creating a globals.h file and adding it to the (your\_project\_name)\_Prefix.pch file will ensure it is accessible globally...
|
2,238,103 |
I am new to iPhone development. I want to access a string variable in all the class methods, and I want to access that string globally. How can I do this?
Please help me out.
|
2010/02/10
|
[
"https://Stackoverflow.com/questions/2238103",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/249916/"
] |
You can achieve that by implementing getter and setters in the delegate class.
In delegate .h file
Include UIApplication delegate
```
@interface DevAppDelegate : NSObject <UIApplicationDelegate>
NSString * currentTitle;
- (void) setCurrentTitle:(NSString *) currentTitle;
- (NSString *) getCurrentTitle;
```
In Delegate implementation class .m
```
-(void) setCurrentLink:(NSString *) storydata{
currentLink = storydata;
}
-(NSString *) getCurrentLink{
if ( currentLink == nil ) {
currentLink = @"Display StoryLink";
}
return currentLink;
}
```
So the variable you to assess is set in the currentlink string by setters method and class where you want the string ,just use the getter method.
All the best
|
I posted an article about my methodology for doing this:
<http://www.pushplay.net/2011/02/quick-tip-global-defines/>
This is something I primarily use for notification keys. Creating a globals.h file and adding it to the (your\_project\_name)\_Prefix.pch file will ensure it is accessible globally...
|
25,782,118 |
I just started in Swing and using the `Timer`. The program I wrote basically move a rectangle up and down to the specific point on the screen, I used the timer to get it run slowly and smoothly. But I got problem when trying to stop it. Here is the code below:
Lift class change y position of rectangle:
```
public void moveUp(int destination){
speed++;
if(speed>5){
speed = 5;
}
System.out.println("Speed is: "+speed);
yPos -= speed;
if(yPos < destination){
yPos = destination;
isStop = true;
}
setPos(xPos, yPos);
}
```
And the class that got `Timer` and `MouseListener`:
```
this.addMouseListener(new MouseListener() {
@Override
public void mouseReleased(MouseEvent arg0) {
// TODO Auto-generated method stub
}
@Override
public void mousePressed(MouseEvent e) {
if (e.getButton() == MouseEvent.BUTTON1) {
Timer timer = new Timer(100, new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
liftArray.get(0).moveUp(rowDisctance / 2);
repaint();
}
});
timer.start();
}
}
```
|
2014/09/11
|
[
"https://Stackoverflow.com/questions/25782118",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3600620/"
] |
if i did understood you correctly you are looking for something like this , you need two timers to control up and down mechanism , timer1 one moves down ,timer2 moves up or vice versa. You need to stop timer1 then inside timer1 you need to start timer2 , here is the code and animation below.

**add your fields**
```
Point rv;
```
**set initial location to your dialog (rectangle) within constructor**
```
rv= rectangle.this.getLocation();
```
**your button action performed**
```
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
timer1.setInitialDelay(0);
timer1.start();
jTextArea1.append("Timer 1 Started Moving Down\n");
}
```
**copy paste these two timer1 and timer2 like method in java**
```
private Timer timer1 = new Timer(10, new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
rv.y++;
if (rv.y == 500) {
timer1.stop();
jTextArea1.append("Timer 1 Stopped\n");
jTextArea1.append("Timer 2 Started Moving Up\n");
timer2.setInitialDelay(0);
timer2.start();
}
rectangle.this.setLocation(rv.x , rv.y);
rectangle.this.repaint();
}
});
private Timer timer2 = new Timer(5, new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
rv.y--;
if (rv.y == 200 ) {
timer2.stop();
jTextArea1.append("Timer 2 Stopped\n");
}
rectangle.this.setLocation(rv.x , rv.y);
rectangle.this.repaint();
}
});
```
|
To visualize how to proceed with this issue, I've coded a little example:

When you start it, two rectangles will be created. They start moving, when you click with the left mouse button on the drawing area.
Motion will stopped, when the destination line is arrived.
The logic depends on a **status in the Rectangle class**. When the timer event handler runs, every rectangle's **status is checked** and the timer is **stopped, if all rectangles reached have the isStopped status**:
```
public void mousePressed(MouseEvent e) {
if (e.getButton() == MouseEvent.BUTTON1) {
timer = new Timer(100, new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
/**
* Variable isStopped is used to track, if any
* rectangle didn't reach the destination yet
*/
boolean isStopped = true;
for(int i = 0; i < count; i++){
rectangles[i].moveUp(destination);
if (!rectangles[i].isStopped()) {
isStopped = false;
}
}
drawPanel.repaint();
/**
* With all rectangles having arrived at destination,
* the timer can be stopped
*/
if (isStopped) {
timer.stop();
}
}
});
timer.start();
}
}
```
Excerpt from the Rectangle class - here you see, how the isStopped status is handled - internally as private isStop variable - retrievable with the isStopped getter.
```
/**
* Moves the rectangle up until destination is reached
* speed is the amount of a single movement.
*/
public void moveUp(int destination) {
if (speed < 5) {
speed++;
}
y -= speed;
if (y < destination) {
y = destination;
isStop = true;
}
}
public boolean isStopped() {
return isStop;
}
```
**Here is the whole Program:**
**Main Program MovingRectangle**, creating the drawing area and providing control:
```
package question;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextArea;
import javax.swing.SwingUtilities;
import javax.swing.Timer;
public class MovingRectangle extends JPanel {
/**
* The serial version uid.
*/
private static final long serialVersionUID = 1L;
private Rectangle[] rectangles = new Rectangle[10];
private int count;
private int destination;
private JPanel controlPanel;
private DrawingPanel drawPanel;
private JButton stop;
private Timer timer;
public static void main(String[] args){
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
JFrame frame = new JFrame("Rectangles");
frame.setContentPane(new MovingRectangle());
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.pack();
frame.setVisible(true);
}
});
}
public MovingRectangle(){
/** Imaginary horizontal line - the destination */
destination = 200;
/** Create the control panel for the left side containing the buttons */
controlPanel = new JPanel();
controlPanel.setPreferredSize(new Dimension(120, 400));
/** Create the button */
stop = new JButton("Stop");
stop.addActionListener(new ButtonListener());
controlPanel.add(stop);
/** Create a hint how to start the movement. */
JTextArea textHint = new JTextArea(5, 10);
textHint.setEditable(true);
textHint.setText("Please click on the drawing area to start the movement");
textHint.setLineWrap(true);
textHint.setWrapStyleWord(true);
controlPanel.add(textHint);
/** Add control panel to the main panel */
add(controlPanel);
/** Create the drawing area for the right side */
drawPanel = new DrawingPanel();
/** Add the drawing panel to the main panel */
add(drawPanel);
/** With a left mouse button click the timer can be started */
drawPanel.addMouseListener(new MouseListener() {
@Override
public void mousePressed(MouseEvent e) {
if (e.getButton() == MouseEvent.BUTTON1) {
timer = new Timer(100, new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
/**
* Variable isStopped is used to track, if any
* rectangle didn't reach the destination yet
*/
boolean isStopped = true;
for(int i = 0; i < count; i++){
rectangles[i].moveUp(destination);
if (!rectangles[i].isStopped()) {
isStopped = false;
}
}
drawPanel.repaint();
/**
* With all rectangles having arrived at destination,
* the timer can be stopped
*/
if (isStopped) {
timer.stop();
}
}
});
timer.start();
}
}
@Override
public void mouseReleased(MouseEvent arg0) {
}
@Override
public void mouseClicked(MouseEvent e) {
}
@Override
public void mouseEntered(MouseEvent e) {
}
@Override
public void mouseExited(MouseEvent e) {
}
});
/** Add two rectangles to the drawing area */
addRectangle(100, 30, 0, 370, new Color(255, 0, 0));
addRectangle(120, 50, 200, 350, new Color(0, 0, 255));
}
private void addRectangle(final int widthParam, final int heightParam, final int xBegin, final int yBegin, final Color color) {
/** Add a new rectangle, if array not filled yet */
if (count < rectangles.length) {
rectangles[count] = new Rectangle(widthParam, heightParam, xBegin, yBegin, color);
count++;
drawPanel.repaint();
}
}
/** This inner class is used to handle the button event. */
private class ButtonListener implements ActionListener {
public void actionPerformed(ActionEvent e){
if (e.getSource() == stop){
timer.stop();
}
}
}
/** This inner class provides the drawing panel */
private class DrawingPanel extends JPanel{
/** The serial version uid. */
private static final long serialVersionUID = 1L;
public DrawingPanel() {
this.setPreferredSize(new Dimension(400, 400));
setBackground(new Color(200, 220, 255));
}
public void paintComponent(Graphics g){
super.paintComponent(g);
/** Draw destination line */
g.setColor(new Color(150, 150, 150));
g.drawLine(0, destination, 400, destination);
/** Draw rectangles */
for(int i = 0; i < count; i++){
rectangles[i].display(g);
}
}
}
}
```
The **Rectangle Class** for the moving shape:
```
package question;
import java.awt.Color;
import java.awt.Graphics;
public class Rectangle {
private int x, y, width, height;
private Color color;
private boolean isStop = false;
private int speed = 0;
public Rectangle(final int widthParam, final int heightParam, final int xBegin, final int yBegin, final Color colorParam) {
width = widthParam;
height = heightParam;
this.x = xBegin;
this.y = yBegin;
this.color = colorParam;
}
public void display(Graphics g){
g.setColor(this.color);
g.fillRect(this.x, this.y, this.width, this.height);
}
/**
* Moves the rectangle up until destination is reached
* speed is the amount of a single movement.
*/
public void moveUp(int destination) {
if (speed < 5) {
speed++;
}
y -= speed;
if (y < destination) {
y = destination;
isStop = true;
}
}
public boolean isStopped() {
return isStop;
}
}
```
|
20,631,060 |
What is the maximum size of Notification message that can be sent to the devices.I searched many places regarding this question but i couldnt find the answer.
|
2013/12/17
|
[
"https://Stackoverflow.com/questions/20631060",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3041802/"
] |
It sounds like you haven't read <https://github.com/Readify/Neo4jClient/wiki/cypher> or <https://github.com/Readify/Neo4jClient/wiki/cypher-examples>. You really should start there. It helps to read the manual. I don't just write it for fun.
For your specific scenario, let's start with your Cypher query:
```
MATCH (a:User)-[r]->(b:Phone)
RETURN a, collect(b)
```
Now, we convert that to fluent Cypher:
```
var results = client.Cypher
.Match("(a:User)-[r]->(b:Phone)")
.Return((a, b) => new {
User = a.As<User>(),
Phones = b.CollectAs<Phone>()
})
.Results;
```
You can then use this rather easily:
```
foreach (var result in results)
Console.WriteLine("{0} has {1} phone numbers", result.User.Name, result.Phones.Count());
```
You will need classes like these, that match your node property model:
```
public class User
{
public string Name { get; set; }
public string Surname { get; set; }
}
public class Phone
{
public string number { get; set; }
public string type_of_number { get; set; }
}
```
Again, **please** go and read <https://github.com/Readify/Neo4jClient/wiki/cypher> and <https://github.com/Readify/Neo4jClient/wiki/cypher-examples>.
|
Add a .ToList() at the end of your command?
Like this :
```
var myList = ((IRawGraphClient) client).ExecuteGetCypherResults<**i_need_Collection**>(
new CypherQuery("match (a:User)-[r]->(b:Phone) return a,collect(b)", null, CypherResultMode.Set))
.Select(un => un.Data).ToList();
```
|
24,508,730 |
I want to know my internet provider (external) IP address (broadband or something else) with Python.
There are multiple machines are connected to that network. I tried in different way's but I got only the local and public IP my machine. How do I find my external IP address through Python?
Thanks in advance.
|
2014/07/01
|
[
"https://Stackoverflow.com/questions/24508730",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3531707/"
] |
You can check out this answer:
<https://stackoverflow.com/a/22157882/5687894>
TL;DR:
```
import ipgetter
ip=ipgetter.myip()
```
|
In my opinion the simplest solution is
```
f = requests.request('GET', 'http://myip.dnsomatic.com')
ip = f.text
```
Thats all.
|
24,508,730 |
I want to know my internet provider (external) IP address (broadband or something else) with Python.
There are multiple machines are connected to that network. I tried in different way's but I got only the local and public IP my machine. How do I find my external IP address through Python?
Thanks in advance.
|
2014/07/01
|
[
"https://Stackoverflow.com/questions/24508730",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3531707/"
] |
You can check out this answer:
<https://stackoverflow.com/a/22157882/5687894>
TL;DR:
```
import ipgetter
ip=ipgetter.myip()
```
|
my website [http;//botliam.com/1.php](https://www.botliam.com/1.php) outputs your ip so you only need these 3 lines to get your ip.
```
import requests
page = requests.get('http://botliam.com/1.php')
ip = page.text
```
what its doing is:
* opens my webpage and calls it "page"
* sets "ip" to the contents of the "page"
if you want your own server to return your external ip instead of relying on my site the code for it is below:
```
<?php
$ip = getenv('HTTP_CLIENT_IP')?:
getenv('HTTP_X_FORWARDED_FOR')?:
getenv('HTTP_X_FORWARDED')?:
getenv('HTTP_FORWARDED_FOR')?:
getenv('HTTP_FORWARDED')?:
getenv('REMOTE_ADDR');
echo "$ip";
?>
```
|
24,508,730 |
I want to know my internet provider (external) IP address (broadband or something else) with Python.
There are multiple machines are connected to that network. I tried in different way's but I got only the local and public IP my machine. How do I find my external IP address through Python?
Thanks in advance.
|
2014/07/01
|
[
"https://Stackoverflow.com/questions/24508730",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3531707/"
] |
Secure option (with `https` support)
```
from requests import get
get('https://ipapi.co/ip/').text
```
Complete [JSON response](https://ipapi.co/json/)
P.S. `requests` module is convenient for `https` support. You can try [httplib](https://stackoverflow.com/a/2146467/6250071) though.
|
You can check out this answer:
<https://stackoverflow.com/a/22157882/5687894>
TL;DR:
```
import ipgetter
ip=ipgetter.myip()
```
|
24,508,730 |
I want to know my internet provider (external) IP address (broadband or something else) with Python.
There are multiple machines are connected to that network. I tried in different way's but I got only the local and public IP my machine. How do I find my external IP address through Python?
Thanks in advance.
|
2014/07/01
|
[
"https://Stackoverflow.com/questions/24508730",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3531707/"
] |
Secure option (with `https` support)
```
from requests import get
get('https://ipapi.co/ip/').text
```
Complete [JSON response](https://ipapi.co/json/)
P.S. `requests` module is convenient for `https` support. You can try [httplib](https://stackoverflow.com/a/2146467/6250071) though.
|
In my opinion the simplest solution is
```
f = requests.request('GET', 'http://myip.dnsomatic.com')
ip = f.text
```
Thats all.
|
24,508,730 |
I want to know my internet provider (external) IP address (broadband or something else) with Python.
There are multiple machines are connected to that network. I tried in different way's but I got only the local and public IP my machine. How do I find my external IP address through Python?
Thanks in advance.
|
2014/07/01
|
[
"https://Stackoverflow.com/questions/24508730",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3531707/"
] |
You'll have to use an external source you trust. Python2.x:
```
from urllib import urlopen
import json
url = 'http://api.hostip.info/get_json.php'
info = json.loads(urlopen(url).read())
print(info['ip'])
```
If you want more info, you can print more values from `info`.
Non-python oneliner:
```
wget -q -O- icanhazip.com
```
|
my website [http;//botliam.com/1.php](https://www.botliam.com/1.php) outputs your ip so you only need these 3 lines to get your ip.
```
import requests
page = requests.get('http://botliam.com/1.php')
ip = page.text
```
what its doing is:
* opens my webpage and calls it "page"
* sets "ip" to the contents of the "page"
if you want your own server to return your external ip instead of relying on my site the code for it is below:
```
<?php
$ip = getenv('HTTP_CLIENT_IP')?:
getenv('HTTP_X_FORWARDED_FOR')?:
getenv('HTTP_X_FORWARDED')?:
getenv('HTTP_FORWARDED_FOR')?:
getenv('HTTP_FORWARDED')?:
getenv('REMOTE_ADDR');
echo "$ip";
?>
```
|
24,508,730 |
I want to know my internet provider (external) IP address (broadband or something else) with Python.
There are multiple machines are connected to that network. I tried in different way's but I got only the local and public IP my machine. How do I find my external IP address through Python?
Thanks in advance.
|
2014/07/01
|
[
"https://Stackoverflow.com/questions/24508730",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3531707/"
] |
Use this script :
```
import urllib, json
data = json.loads(urllib.urlopen("http://ip.jsontest.com/").read())
print data["ip"]
```
Without json :
```
import urllib, re
data = re.search('"([0-9.]*)"', urllib.urlopen("http://ip.jsontest.com/").read()).group(1)
print data
```
---
Other way it was to parse ifconfig (= linux) or ipconfig (= windows) command but take care with translated Windows System
(ipconfig was translated).
Example of lib for linux :
[ifparser](https://pypi.python.org/pypi/ifparser/).
|
my website [http;//botliam.com/1.php](https://www.botliam.com/1.php) outputs your ip so you only need these 3 lines to get your ip.
```
import requests
page = requests.get('http://botliam.com/1.php')
ip = page.text
```
what its doing is:
* opens my webpage and calls it "page"
* sets "ip" to the contents of the "page"
if you want your own server to return your external ip instead of relying on my site the code for it is below:
```
<?php
$ip = getenv('HTTP_CLIENT_IP')?:
getenv('HTTP_X_FORWARDED_FOR')?:
getenv('HTTP_X_FORWARDED')?:
getenv('HTTP_FORWARDED_FOR')?:
getenv('HTTP_FORWARDED')?:
getenv('REMOTE_ADDR');
echo "$ip";
?>
```
|
24,508,730 |
I want to know my internet provider (external) IP address (broadband or something else) with Python.
There are multiple machines are connected to that network. I tried in different way's but I got only the local and public IP my machine. How do I find my external IP address through Python?
Thanks in advance.
|
2014/07/01
|
[
"https://Stackoverflow.com/questions/24508730",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3531707/"
] |
You'll have to use an external source you trust. Python2.x:
```
from urllib import urlopen
import json
url = 'http://api.hostip.info/get_json.php'
info = json.loads(urlopen(url).read())
print(info['ip'])
```
If you want more info, you can print more values from `info`.
Non-python oneliner:
```
wget -q -O- icanhazip.com
```
|
You can check out this answer:
<https://stackoverflow.com/a/22157882/5687894>
TL;DR:
```
import ipgetter
ip=ipgetter.myip()
```
|
24,508,730 |
I want to know my internet provider (external) IP address (broadband or something else) with Python.
There are multiple machines are connected to that network. I tried in different way's but I got only the local and public IP my machine. How do I find my external IP address through Python?
Thanks in advance.
|
2014/07/01
|
[
"https://Stackoverflow.com/questions/24508730",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3531707/"
] |
You'll have to use an external source you trust. Python2.x:
```
from urllib import urlopen
import json
url = 'http://api.hostip.info/get_json.php'
info = json.loads(urlopen(url).read())
print(info['ip'])
```
If you want more info, you can print more values from `info`.
Non-python oneliner:
```
wget -q -O- icanhazip.com
```
|
In my opinion the simplest solution is
```
f = requests.request('GET', 'http://myip.dnsomatic.com')
ip = f.text
```
Thats all.
|
24,508,730 |
I want to know my internet provider (external) IP address (broadband or something else) with Python.
There are multiple machines are connected to that network. I tried in different way's but I got only the local and public IP my machine. How do I find my external IP address through Python?
Thanks in advance.
|
2014/07/01
|
[
"https://Stackoverflow.com/questions/24508730",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3531707/"
] |
Use this script :
```
import urllib, json
data = json.loads(urllib.urlopen("http://ip.jsontest.com/").read())
print data["ip"]
```
Without json :
```
import urllib, re
data = re.search('"([0-9.]*)"', urllib.urlopen("http://ip.jsontest.com/").read()).group(1)
print data
```
---
Other way it was to parse ifconfig (= linux) or ipconfig (= windows) command but take care with translated Windows System
(ipconfig was translated).
Example of lib for linux :
[ifparser](https://pypi.python.org/pypi/ifparser/).
|
You can check out this answer:
<https://stackoverflow.com/a/22157882/5687894>
TL;DR:
```
import ipgetter
ip=ipgetter.myip()
```
|
24,508,730 |
I want to know my internet provider (external) IP address (broadband or something else) with Python.
There are multiple machines are connected to that network. I tried in different way's but I got only the local and public IP my machine. How do I find my external IP address through Python?
Thanks in advance.
|
2014/07/01
|
[
"https://Stackoverflow.com/questions/24508730",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3531707/"
] |
Secure option (with `https` support)
```
from requests import get
get('https://ipapi.co/ip/').text
```
Complete [JSON response](https://ipapi.co/json/)
P.S. `requests` module is convenient for `https` support. You can try [httplib](https://stackoverflow.com/a/2146467/6250071) though.
|
You'll have to use an external source you trust. Python2.x:
```
from urllib import urlopen
import json
url = 'http://api.hostip.info/get_json.php'
info = json.loads(urlopen(url).read())
print(info['ip'])
```
If you want more info, you can print more values from `info`.
Non-python oneliner:
```
wget -q -O- icanhazip.com
```
|
15,295,014 |
I have following XML:
```
<RULES>
<TRAP name="trap1" oid=".1.2.3">
<VAR_LIST>
<VAR name="var1" value=".1.2.3.1"/>
<VAR name="var2" value=".1.2.3.2"/>
</VAR_LIST>
</TRAP>
<TRAP name="trap2" oid=".1.2.4">
...
</TRAP>
...
</RULES>
```
I would like to generate flattened summary so I iterate through it as follows:
```
for $trap in /RULES/TRAP
for $var in $rule/VAR_LIST/VAR
return (opening-tag-declaration($trap), opening-tag-declaration($var), " ")
```
I would like to get following output, but I don't know how to extract tag's opening declaration only...
```
<TRAP name="trap1" oid=".1.2.3> <VAR name="var1" value=".1.2.3.1"/>
<TRAP name="trap1" oid=".1.2.3> <VAR name="var2" value=".1.2.3.2"/>
<TRAP name="trap2" oid=".1.2.4> ...
...
```
|
2013/03/08
|
[
"https://Stackoverflow.com/questions/15295014",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1333331/"
] |
Here's one way to define `opening-tag-declaration` (adapted from [this function](http://www.xqueryfunctions.com/xq/functx_remove-elements.html) in the FunctX library):
```
declare namespace example = "http://example.com";
declare function example:opening-tag-declaration
( $elements as element()* ) as element()* {
for $element in $elements
return element
{node-name($element)}
{$element/@* }
};
```
It includes the element name and its attributes in the resulting element, but not the child nodes. [Demo](http://www.zorba-xquery.com/html/demo#dY19u2nz0mqDFDTQWgWarJ9PVE8=) using the [books.xml](http://www.w3schools.com/xquery/books.xml) example file from w3schools.
|
This is my custom approach to this problem before [mgibsonbr](https://stackoverflow.com/users/520779/mgibsonbr) answer:
```
declare function local:tag($node as node()) as xs:string {
concat(substring-before(fn:serialize($node), ">"), ">")
};
```
|
57,217,590 |
I have a list of accounts and am creating a countifs formula with multiple variables, based on a changelog in a separate sheet.
Currently it stands like this (please note the values in quotation marks are distinct TEXT values as they are system codes and not numeric value):
```
=COUNTIFS(Changelog!$A$1:$A$1000,A1,Changelog!$L$1:$L$1000,"=3",Changelog!G$1:G$1000,{"=993","=Z94","=Z95","=Z96","=Z97","=998","=999"})
```
As you can notice there are 3 types of variables that create the criteria.
First 2 are rather self explanatory: 1st we have a search in changelog for the account in the A1 cell (so we will have a list of changes on each account), 2nd is a search for those whose respective L cell value equals to 3.
So far so good. However the problem arises for me with including the third condition. I want to check whether the account has one of the values in a G column. The formula works only for the first value (that being "993").
For example, If in the changelog there is a line in which in column A value is equal to the account number, column L will have the value of "3" and in column G there is a value of "993", than the count will show "1". If however the G column has a value of (for example) "Z95", than the formula shows 0.
I wonder how it can be done to implement such a "logical OR" criteria that would take any of the values into account.
|
2019/07/26
|
[
"https://Stackoverflow.com/questions/57217590",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11607854/"
] |
Upgrading the cryptography package worked for me
```
pip3 install --upgrade cryptography
```
|
Upgrade to the latest version of
`python -m pip install --upgrade setuptools`
`python -m pip install –-upgrade pip`
`python -m pip install –-upgrade cryptography`
`python -m pip install --upgrade cffi`
Verify the deployment procedure and make necessary updates to required packages
|
57,217,590 |
I have a list of accounts and am creating a countifs formula with multiple variables, based on a changelog in a separate sheet.
Currently it stands like this (please note the values in quotation marks are distinct TEXT values as they are system codes and not numeric value):
```
=COUNTIFS(Changelog!$A$1:$A$1000,A1,Changelog!$L$1:$L$1000,"=3",Changelog!G$1:G$1000,{"=993","=Z94","=Z95","=Z96","=Z97","=998","=999"})
```
As you can notice there are 3 types of variables that create the criteria.
First 2 are rather self explanatory: 1st we have a search in changelog for the account in the A1 cell (so we will have a list of changes on each account), 2nd is a search for those whose respective L cell value equals to 3.
So far so good. However the problem arises for me with including the third condition. I want to check whether the account has one of the values in a G column. The formula works only for the first value (that being "993").
For example, If in the changelog there is a line in which in column A value is equal to the account number, column L will have the value of "3" and in column G there is a value of "993", than the count will show "1". If however the G column has a value of (for example) "Z95", than the formula shows 0.
I wonder how it can be done to implement such a "logical OR" criteria that would take any of the values into account.
|
2019/07/26
|
[
"https://Stackoverflow.com/questions/57217590",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11607854/"
] |
Upgrading the cryptography package worked for me
```
pip3 install --upgrade cryptography
```
|
I had a similar issue for a while, and I found that it had to do with how I was creating layers for the lambda function.
The path of the libraries that you are uploading should be [root]/python/lib/python[version].[minor version]/site-packages
Whenever I uploaded it in any other way, Lambda did not recognize the dependencies.
This worked for Python3.9, so in the case of the cryptography library, the zip that I uploaded for my lambda layer was in the structure of /python/lib/python3.9/site-packages/[cryptography dump].
Hope this helped.
|
2,160,047 |
[](https://i.stack.imgur.com/P7Yd9.png)
I am trying to construct a Hamilton circuit. I have the cities NY, C, LA, M and D. I know it will be in the shape of a pentagon.
So far I have: NY at the top. C on the left. M on the right. Then LA on the left below C and D on the right below M.
I am confused how I can add weights. Can I make any scale up like 30mins=1 cm?
|
2017/02/24
|
[
"https://math.stackexchange.com/questions/2160047",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/416630/"
] |
You're not constructing a Hamilton circuit (or not yet) according to the question, just a weighted graph. I suggest that you convert all the times to minutes and then just **label** the appropriate edges of the graph with the time in minutes. (Fortunately the time is the same in both directions). Don't try to scale the edge lengths to the weights. Given the correlation of distance and flight time, you might as well lay the vertices out *roughly* geographically, but also conveniently for reading the weights. You're not drawing a map: it's a graph.
Then later, if you are using this graph to find a Hamiltonian circuit, since this is a complete graph, you will have to choose an arbitrary start point (it's a circuit, so this doesn't increase the options), then $4$ choices, $3$ choices, $2$ choices, and two forced choices for $4!=24$ different circuits, or $4!/2=12$ if the reversed circuit counts as the same.
|
You have not read the question carefully.
* The cities should go on a map of the US (at least approximately).
That tells you the positions on the paper. That determines the scale essentially some number of inches per mile, depending on the size of your paper.
* The question calls specifically for a complete graph: the pentagon
and all its diagonals.
* The weights are the travel times. Longer distances take more time, but the relationship is not direct proportion. The weights have no explicit relation to the scale of the drawing.
|
66,770,432 |
I have an issue. As you see the following example:
```
data = pd.DataFrame({'a':[127093342616], 'b':[22853943721]})
data['a*b']= data['a']*data['b']
data
```
* When I multiply 2 numbers: **127093342616** vs **22853943721**, the result = **2904584099459834914136**
* But, when I use DataFrame of pandas and multiply the 2 columns the result = **8445279887435310424**
Can anybody tell me the reason this occurs and a solution?
|
2021/03/23
|
[
"https://Stackoverflow.com/questions/66770432",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15464021/"
] |
Try using float datatype, you're having integer overflow problems:
```
data = pd.DataFrame({'a':[127093342616], 'b':[22853943721]}, dtype=np.float)
data['a*b']= data['a']*data['b']
data
```
Output:
```
a b a*b
0 1.270933e+11 2.285394e+10 2.904584e+21
```
Because pandas use numpy underneath, let's look at [numpy datatypes](https://numpy.org/devdocs/user/basics.types.html#data-types).
numpy.int64 - Integer (-9223372036854775808 to 9223372036854775807)
|
### Comprehension
```
data['a*b'] = [a * b for a, b in zip(data.a, data.b)]
data
a b a*b
0 127093342616 22853943721 2904584099459834914136
```
|
13,858,836 |
i have dynamically created no-of rows and no-of columns based on the requirement using for loops.
```
for (i = 0; i < a ; i++) {
$("table").append("<tr id='tr" + i + "'></tr>");
for (j = 0; j < b ; j++) {
$('[id^="tr' + i + '"]').append("<td><input type='text' class='add1' id='textbox" + i + "" + j + "'/></td>");
}
}
```
i have tried using **blur** event along with **live** like below
```
$(document).live("input.add1", "blur", function (event) {
});
```
i have to print addition after each row and column.
please help
with regards
Ramu
|
2012/12/13
|
[
"https://Stackoverflow.com/questions/13858836",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1790977/"
] |
use **Delegate** instead of **live**
```
$(document).delegate("input.add1", "blur", function (event) {
});
```
because **delegate** ..The **.delegate()** method behaves in a similar fashion to the **.live()** method, but instead of attaching the selector/event information to the document, you can choose where it is anchored. Just like the **.live()** method, this technique uses event delegation to work correctly.
**Example :if you write function for ROW Addition then you can have code like below**
```
$('[id=""]').each(function () {
Addition($(this).val());
});
```
Similarly you can use same **Addition** function for COLUMN addition.
All the best
|
`.live()` is deprecated, use the new `.on()` method as is the prefered way to do event delegation as you want to do, like this:
```
$(document).on("blur", "input.add1", function (event) {
//your code
});
```
|
47,529,349 |
Most common way of bubble sort algorithm is to have two for loops. Inner one being done from j=0 until j n-i-1. I assume we substract minus i, because when we reach last element we don't compare it because we don't have an element after him. But why do we use n-1. Why we don't run outer loop from i=0 until i < n and inner from j=0 until n-i? Could someone explain it to me, tutorials on internet does not emphasize this.
```
for (int i = 0; i < n - 1; i++) // Why do we have n-1 here?
{
swapped = false;
for (int j = 0; j < n - i - 1; j++)
{
countComparisons++;
if (arr[j] > arr[j + 1])
{
countSwaps++;
swap(&arr[j], &arr[j + 1]);
swapped = true;
}
}
}
```
For example, if I have an array with 6 elements, why do I only need to make 5 iterations?
|
2017/11/28
|
[
"https://Stackoverflow.com/questions/47529349",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7132846/"
] |
Because a swap requires at least two elements.
So if you have 6 elements, you only need to consider 5 consecutive pairs.
|
For comparison purposes in an array, two adjacent cells are needed; in an array of 6 elements, you do 5 comparisons only; in an array of 10 elements, 9 comparisons, and so on:
[array and comparisons between adjacent cells](https://i.stack.imgur.com/2HiFE.png)
So for 7 elements, just 6 comparisons are done, hence the general rule of n-1 in the outer *for* loop
About the *n-1-i* expression, remember that the highest (or lowest, depending on the ordering criterion) value in the bubble sort goes to the last position in the array after the first cycle, so there is no need to compare that value with anything else, therefore the array has to be "shortened" 1 cell at a time, and the value of *i* in the outer loop is the counter responsible for that in the inner loop:
5 | 3 | 9 | ***20*** | elements (n) = 4
after first cycle (*i = 0*), 20 has reached its correct position within the array (using an ascending order), leaving us with an array of 3 elements to do comparisons to; in next cycle, *i* will be equal to 1, and as n-1 remains the same, we need to substract 1 in that expression to "shorten" the array:
n-1-i = 4-1-1 = 2, which is the index of the last element in that new array as well as the quantity of comparisons needed.
Hope it helps!
|
72,469,462 |
using tasm/tlink/dosbox in notepad++
want: how do i fix 2 digit divide to 2 digits and when if the quotient or remainder answer is also 2 digits? and also what is the possible logic?
my flow is: the flow I made was first I took the first digit of the first number or dividend then I multiplied by 10 to be and I added to the second digit the same as the second number or divisor so that it would be 2 digits in the register after that I'll divide them both.
My Code in notepad++:
```
.model small
.stack 100h
.data
d0 db 0dh,0ah,"Base 03$"
d1 db 0dh,0ah,"Enter Dividend : $" ;string
d2 db 0dh,0ah,"Enter Divisor : $"
d3 db 0dh,0ah,"Display Quotient : $"
d4 db 0dh,0ah,"Display Remainder : $"
.code
main proc ;main program here
mov ax,@data ;initialize ds
mov ds,ax
Div1:
mov ah,09h
lea dx,d0
int 21h
lea dx, d1
int 21h
mov ah,01h
int 21h ;1st Digit
mov ch,al
mov ah,01h
int 21h ;2nd Digit
mov cl,al
or cx,3030h
mov al,ch
mov bl,10h
mul bl ;02*10 = 20
mov bh,al
add bh,cl ;dividend
Div2:
mov ah,09h
lea dx, d2
int 21h
mov ah,01h
int 21h ;1st Digit
mov ch,al
mov ah,01h
int 21h ;2nd Digit
mov cl,al
or cx,3030h
mov al,ch
mul bl
mov dh,al
add dh,cl ;divisor
mov ah,00h
mov al,bh
aad
div dh
mov cx,ax
or cx,3030h
mov ah,09h
lea dx, d3
int 21h
mov ah,02h
mov dl,cl
int 21h
mov ah,09h
lea dx, d4
int 21h
mov ah,02h
mov dl,ch
int 21h
mov ah,4Ch ;end here
int 21h
main endp
end main
```
Output:
[](https://i.stack.imgur.com/G27qF.png)
Want Output:
```
Enter Dividend : 22
Enter Divisor : 02
Display Quotient : 02
Display Remainder : 00
proj
Enter Dividend : 21
Enter Divisor : 02
Display Quotient : 10
Display Remainder : 01
proj
Enter Dividend : 21
Enter Divisor : 11
Display Quotient : 01
Display Remainder : 10
```
like this calculation but the only i need is the quotient and remainder.
[](https://i.stack.imgur.com/0GU6Z.png)
|
2022/06/02
|
[
"https://Stackoverflow.com/questions/72469462",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18970053/"
] |
Are you sure about "Want output" ?
```
Enter Dividend : 22 <<< 8d
Enter Divisor : 02 <<< 2d
Display Quotient : 02 ??? 4d == 11
Display Remainder : 00 <<< 0d
```
---
`or cx,3030h` does nothing to your code because those bits will already have been set, they're part of the ASCII codes from 48 to 50. For conversion purposes you would normally use `sub cx,3030h`.
Next your multiplication with 10h (16 in decimal) is trying to turn the input into **packed** BCD (binary coded digits) format. Later the code will use the `aad` instruction that operates on **unpacked** BCD and importantly uses 10 as its number base where your program is going for number base 3.
You seem to expect a 2-digit output for both quotient and remainder. Then just printing 2 characters from CL and CH is not enough.
To do
-----
```
mov ah,01h
int 21h ;1st Digit
mov ch,al
mov ah,01h
int 21h ;2nd Digit
mov cl,al
sub cx,3030h
mov al, 3
mul ch
add al, cl
mov bh,al ;dividend = (D1 * 3) + D2
```
Similarly for the divisor, but put it in BL
```
mov ah, 0
mov al, bh ; Dividend in BH
div bl ; Divisor in BL
mov cx, ax ; Quotient in CL, Remainder in CH
```
Ready to print. See my answer [I need to show 3 digit answer Using tasm/tlink/dosbox in notepad++](https://stackoverflow.com/questions/72404762/i-need-to-show-3-digit-answer-using-tasm-tlink-dosbox-in-notepad/72410167#72410167)
|
Your algorithm for conversion is confused:
>
> first I took the first digit of the first number or dividend then I
> multiplied by 10 to be and I added to the second digit
>
>
>
In fact you have multiplied the first digit by 16 because of `mov bl,10h`.
See also questions [8086 simple decimal addition from user input](https://stackoverflow.com/questions/66205862/8086-simple-decimal-addition-from-user-input) or [How to convert an ASCII char to a decimal representation?](https://stackoverflow.com/questions/70851012/how-to-convert-an-ascii-char-to-a-decimal-representation).
Or use some more general method to how to convert input string with more than two decimal numbers to a binary value. See the macro [LodD](https://euroassembler.eu/maclib/cpuext16.htm#LodD) for inspiration.
What you need is [Turbo Debugger](https://trimtab.ca/2010/tech/tasm-5-intel-8086-turbo-assembler-download/) which allows to execute you program instruction by instruction and watch if the registers change as expected.
|
4,434 |
I would like to know is it worth doing both Yoga and Bodybuilding on the same day regularly?
|
2011/11/02
|
[
"https://fitness.stackexchange.com/questions/4434",
"https://fitness.stackexchange.com",
"https://fitness.stackexchange.com/users/2272/"
] |
Yes, yoga and bodybuilding can be done on the same day. Yoga is a specific form of low-intensity exercise and its benefits are thought to arise from the exercise component as well as stress reduction. Unless your bodybuilding session is so intense that you can barely move, I don't see why you shouldn't do Yoga. Since Yoga exercises are generally of low intensity, it won't have too much of an effect on your muscles or metabolism.
|
I would say yes, take into account the following:
* Some Yoga exercises can be dangerous if your form is bad due to you beeing exhausted (as mentioned earlier)
* Depending on what how much Yoga you do, this can also be pretty exhausting and maybe your form will suffer if you do another workout later that day
* It may take you body some time to get used to so much workout in one day
So give it a try, watch your form closely and don't give up to early if it seems to hard at first.
|
4,434 |
I would like to know is it worth doing both Yoga and Bodybuilding on the same day regularly?
|
2011/11/02
|
[
"https://fitness.stackexchange.com/questions/4434",
"https://fitness.stackexchange.com",
"https://fitness.stackexchange.com/users/2272/"
] |
Absolutely! Yoga will stretch the muscles that have just worked (better do the body building part first) and body building will help build the muscles to hold the postures better in yoga!
|
I do yoga in the morning and strength training in the evening. When I follow this routine for a long time I have noticed that doing yoga in the morning has helped me a lot to over come
DOMS while doing previous day's heavy lifting. So I feel very comfortable and do 4 workouts for a week,plus almost 4 yoga sessions
|
4,434 |
I would like to know is it worth doing both Yoga and Bodybuilding on the same day regularly?
|
2011/11/02
|
[
"https://fitness.stackexchange.com/questions/4434",
"https://fitness.stackexchange.com",
"https://fitness.stackexchange.com/users/2272/"
] |
From my understanding, it is best to partake in static stretching after your workout and seeing that Yoga (generally speaking) is pretty much static stretching there should be no harm.
Harm can come from doing static stretching before your workout, especially for lower-body exercises. It is recommended before workouts to do some dynamic stretching (lunges as opposed to holding a strech like bending over to touch your toes).
There has been some research on the matter. Check out this link: <http://chrisfry.hubpages.com/hub/Stretching-Before-Sport>
So in short, no, it is not a problem as long as you do your yoga after your bodybuilding workout!
|
I would say yes, take into account the following:
* Some Yoga exercises can be dangerous if your form is bad due to you beeing exhausted (as mentioned earlier)
* Depending on what how much Yoga you do, this can also be pretty exhausting and maybe your form will suffer if you do another workout later that day
* It may take you body some time to get used to so much workout in one day
So give it a try, watch your form closely and don't give up to early if it seems to hard at first.
|
4,434 |
I would like to know is it worth doing both Yoga and Bodybuilding on the same day regularly?
|
2011/11/02
|
[
"https://fitness.stackexchange.com/questions/4434",
"https://fitness.stackexchange.com",
"https://fitness.stackexchange.com/users/2272/"
] |
Others have already covered the important ground of whether yoga can be paired with working out, but I'd make some suggestions on the ordering. Many people under-estimate the amount of "work" that can be involved in a number of yoga poses, particularly holds. I've found personally that specific muscles are often too weak for a robust well-rounded session of yoga after lifting weights.
I feel like I get the most out of both when I get my more vigorous yoga session in as a warm-up before lifting. You may also want to keep in mind that despite yoga's reputation it is perfectly possible to hurt yourself while attempting positions your body isn't in the proper shape to execute prop--and being too tired to maintain good form qualifies.
The answer probably depends on what sort of yoga, poses and duration you're practicing.
|
Yes!! I have done cardio, weight training followed by Yoga in the same session. I must say it feels great to finish off the workout routine by Yoga stretches and I feel much rejuvenated afterwards. I basically do Surya Namaskar to finish the routine and it really helps to stretch the muscles and give some relaxation after strenuous workout.
|
4,434 |
I would like to know is it worth doing both Yoga and Bodybuilding on the same day regularly?
|
2011/11/02
|
[
"https://fitness.stackexchange.com/questions/4434",
"https://fitness.stackexchange.com",
"https://fitness.stackexchange.com/users/2272/"
] |
Yes, yoga and bodybuilding can be done on the same day. Yoga is a specific form of low-intensity exercise and its benefits are thought to arise from the exercise component as well as stress reduction. Unless your bodybuilding session is so intense that you can barely move, I don't see why you shouldn't do Yoga. Since Yoga exercises are generally of low intensity, it won't have too much of an effect on your muscles or metabolism.
|
From my understanding, it is best to partake in static stretching after your workout and seeing that Yoga (generally speaking) is pretty much static stretching there should be no harm.
Harm can come from doing static stretching before your workout, especially for lower-body exercises. It is recommended before workouts to do some dynamic stretching (lunges as opposed to holding a strech like bending over to touch your toes).
There has been some research on the matter. Check out this link: <http://chrisfry.hubpages.com/hub/Stretching-Before-Sport>
So in short, no, it is not a problem as long as you do your yoga after your bodybuilding workout!
|
4,434 |
I would like to know is it worth doing both Yoga and Bodybuilding on the same day regularly?
|
2011/11/02
|
[
"https://fitness.stackexchange.com/questions/4434",
"https://fitness.stackexchange.com",
"https://fitness.stackexchange.com/users/2272/"
] |
Others have already covered the important ground of whether yoga can be paired with working out, but I'd make some suggestions on the ordering. Many people under-estimate the amount of "work" that can be involved in a number of yoga poses, particularly holds. I've found personally that specific muscles are often too weak for a robust well-rounded session of yoga after lifting weights.
I feel like I get the most out of both when I get my more vigorous yoga session in as a warm-up before lifting. You may also want to keep in mind that despite yoga's reputation it is perfectly possible to hurt yourself while attempting positions your body isn't in the proper shape to execute prop--and being too tired to maintain good form qualifies.
The answer probably depends on what sort of yoga, poses and duration you're practicing.
|
I am just wondering the same. I am an ex boxer, when I was boxing it was really clear to me that no one can do bodybuilding at the same time because there is no strenght for sparring or training with a punchbag. Nowadays I am doing only doing ashtanga yoga. I want also to start bodybuilding. I have noticed that many yoga studios have once a week a day training with kettlebell. I can exercise my shoulders with a 24 kg kettlebell but it doesn't seem to help so much except in one asana (urdhba dhanurasana) in other words ''bridge asana''. I can say that push ups with handles and training my abs was efficient especially in Surya Namaskaras in other words (sun salutations). I could spent less energy, on the other hand if in the previous day I had trained my muscles really hard I wouldn't do them properly. So you have to find the balance. Unfortunately in internet I don't see similar questions or comments about combining bodybuilding training with yoga. Even if the stereotype of a yogi is a thin person I have noticed in yoga studios that many of these women are slightly overweight.
I found that disgusting! In sitting yoga exercises fat is a real problem because you can not even breath! The whole yoga technic of an asana is based on breathing!
|
4,434 |
I would like to know is it worth doing both Yoga and Bodybuilding on the same day regularly?
|
2011/11/02
|
[
"https://fitness.stackexchange.com/questions/4434",
"https://fitness.stackexchange.com",
"https://fitness.stackexchange.com/users/2272/"
] |
Yes, yoga and bodybuilding can be done on the same day. Yoga is a specific form of low-intensity exercise and its benefits are thought to arise from the exercise component as well as stress reduction. Unless your bodybuilding session is so intense that you can barely move, I don't see why you shouldn't do Yoga. Since Yoga exercises are generally of low intensity, it won't have too much of an effect on your muscles or metabolism.
|
Others have already covered the important ground of whether yoga can be paired with working out, but I'd make some suggestions on the ordering. Many people under-estimate the amount of "work" that can be involved in a number of yoga poses, particularly holds. I've found personally that specific muscles are often too weak for a robust well-rounded session of yoga after lifting weights.
I feel like I get the most out of both when I get my more vigorous yoga session in as a warm-up before lifting. You may also want to keep in mind that despite yoga's reputation it is perfectly possible to hurt yourself while attempting positions your body isn't in the proper shape to execute prop--and being too tired to maintain good form qualifies.
The answer probably depends on what sort of yoga, poses and duration you're practicing.
|
4,434 |
I would like to know is it worth doing both Yoga and Bodybuilding on the same day regularly?
|
2011/11/02
|
[
"https://fitness.stackexchange.com/questions/4434",
"https://fitness.stackexchange.com",
"https://fitness.stackexchange.com/users/2272/"
] |
From my understanding, it is best to partake in static stretching after your workout and seeing that Yoga (generally speaking) is pretty much static stretching there should be no harm.
Harm can come from doing static stretching before your workout, especially for lower-body exercises. It is recommended before workouts to do some dynamic stretching (lunges as opposed to holding a strech like bending over to touch your toes).
There has been some research on the matter. Check out this link: <http://chrisfry.hubpages.com/hub/Stretching-Before-Sport>
So in short, no, it is not a problem as long as you do your yoga after your bodybuilding workout!
|
Yes!! I have done cardio, weight training followed by Yoga in the same session. I must say it feels great to finish off the workout routine by Yoga stretches and I feel much rejuvenated afterwards. I basically do Surya Namaskar to finish the routine and it really helps to stretch the muscles and give some relaxation after strenuous workout.
|
4,434 |
I would like to know is it worth doing both Yoga and Bodybuilding on the same day regularly?
|
2011/11/02
|
[
"https://fitness.stackexchange.com/questions/4434",
"https://fitness.stackexchange.com",
"https://fitness.stackexchange.com/users/2272/"
] |
Others have already covered the important ground of whether yoga can be paired with working out, but I'd make some suggestions on the ordering. Many people under-estimate the amount of "work" that can be involved in a number of yoga poses, particularly holds. I've found personally that specific muscles are often too weak for a robust well-rounded session of yoga after lifting weights.
I feel like I get the most out of both when I get my more vigorous yoga session in as a warm-up before lifting. You may also want to keep in mind that despite yoga's reputation it is perfectly possible to hurt yourself while attempting positions your body isn't in the proper shape to execute prop--and being too tired to maintain good form qualifies.
The answer probably depends on what sort of yoga, poses and duration you're practicing.
|
I would say yes, take into account the following:
* Some Yoga exercises can be dangerous if your form is bad due to you beeing exhausted (as mentioned earlier)
* Depending on what how much Yoga you do, this can also be pretty exhausting and maybe your form will suffer if you do another workout later that day
* It may take you body some time to get used to so much workout in one day
So give it a try, watch your form closely and don't give up to early if it seems to hard at first.
|
4,434 |
I would like to know is it worth doing both Yoga and Bodybuilding on the same day regularly?
|
2011/11/02
|
[
"https://fitness.stackexchange.com/questions/4434",
"https://fitness.stackexchange.com",
"https://fitness.stackexchange.com/users/2272/"
] |
Yes, yoga and bodybuilding can be done on the same day. Yoga is a specific form of low-intensity exercise and its benefits are thought to arise from the exercise component as well as stress reduction. Unless your bodybuilding session is so intense that you can barely move, I don't see why you shouldn't do Yoga. Since Yoga exercises are generally of low intensity, it won't have too much of an effect on your muscles or metabolism.
|
Yes!! I have done cardio, weight training followed by Yoga in the same session. I must say it feels great to finish off the workout routine by Yoga stretches and I feel much rejuvenated afterwards. I basically do Surya Namaskar to finish the routine and it really helps to stretch the muscles and give some relaxation after strenuous workout.
|
54,438,446 |
I'm writing a de-serializer which reads a huge json file and puts records matching a filter (logic in my application) into database. The json file has a fixed schema as follows:
```
{
"cityDetails": {
"name": "String",
"pinCodes": "Array of integers ",
"people": [{
"name": "String",
"age": "Integer"
}]
}
}
```
I am only interested in streaming list of "people" from the file. I am aware that GSON/Jackson provide streaming APIs which I can use but I want to avoid looping through the tokens as I stream them and match their name to see if I am interested in them. I believe that there should be a solution which can do the streaming in background and point/seek the stream to the token I am interested in. I don't see any reason why this should not be possible if I provide my JSON schema. Is there are solution available for this?
Here's a sample instance of my JSON:
```
{
"cityDetails": {
"name": "mumbai",
"pinCodes": ["400001", "400002"],
"people": [{
"name": "Foo",
"age": 1
}, {
"name": "Bar",
"age": 2
}]
}
}
```
|
2019/01/30
|
[
"https://Stackoverflow.com/questions/54438446",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2906555/"
] |
As others have said, you have a comma at the end of a line and at the beginning of the next:
```
StaniceUrceni,
, PrijemceZbozi
```
So you should always use the same comma strategy, either at the beginning or end:
```
string sql = @"
INSERT INTO InterniLozniListS3_Hlavicka(
Stredisko, DatumNakladky, SmenaNakladky, HodNakladky, NaklPredak,
CisloLL, SpzVozuTahace, SpzVozuNavesu, Mpz, Mpz2, NaprTlak, TaraNova,
Unosnost, PocetNaprav, StaniceUrceni, PrijemceZbozi, DatNarozeni,
JmenoAPrijmeni, Podpis, Vyhotovil, Vysilal, Kod, UvolnenoPrijmeni,
UvolnenoTelefon, UvolnenoPlaceno)
OUTPUT INSERTED.ID
VALUES (
@stredisko, @datumNakladky, @smenaNakladky, @hodNakladky, @naklPredak,
@cisloLL, @spzVozuTahace, @spzVozuNavesu, @mpz, @mpz2, @naprTlak, @taraNova,
@unosnost, @pocetNapr, @staniceUrceni,@prijemceZbozi, @datNarozeni,
@jmenoAPrijmeni, @Podpis, @Vyhotovil, @Vysilal, @Kod, @uvolnenoPrijmeni,
@UvolnenoTelefon, @UvolnenoPlaceno);"
```
As you see it's also helpful to avoid scrolling horitontally.
```
using(var cmd = new SqlCommand(sql, conection))
{
return (long) cmd.ExecuteScalar();
}
```
|
another and better working approach.
**In Sql database engine, create a stored procedure, like:**
```
//Defining random datatypes to the parameters as i don't know which should be of which DataType.
create proc sp_InsertUpdate_InterniLozniListS3_Hlavicka
@stredisko int,
@datumNakladky varchar(255),
@smenaNakladky varchar(255),
@hodNakladky varchar(255),
@naklPredak varchar(255),
@cisloLL varchar(255),
@spzVozuTahace varchar(255),
@spzVozuNavesu varchar(255),
@mpz varchar(255),
@mpz2 varchar(255),
@naprTlak varchar(255),
@taraNova varchar(255),
@unosnost varchar(255),
@pocetNapr varchar(255),
@staniceUrceni varchar(255),
@prijemceZbozi varchar(255),
@datNarozeni varchar(255),
@jmenoAPrijmeni varchar(255),
@Podpis varchar(255),
@Vyhotovil varchar(255),
@Vysilal varchar(255),
@Kod varchar(255),
@uvolnenoPrijmeni varchar(255),
@UvolnenoTelefon varchar(255),
@UvolnenoPlaceno varchar(255)
as
begin
if(@stredisko == 0) //Assuming this is Primary key and identity column of the table
begin
INSERT INTO InterniLozniListS3_Hlavicka(
Stredisko, DatumNakladky, SmenaNakladky, HodNakladky, NaklPredak,
CisloLL, SpzVozuTahace, SpzVozuNavesu, Mpz, Mpz2, NaprTlak, TaraNova,
Unosnost, PocetNaprav, StaniceUrceni, PrijemceZbozi, DatNarozeni,
JmenoAPrijmeni, Podpis, Vyhotovil, Vysilal, Kod, UvolnenoPrijmeni,
UvolnenoTelefon, UvolnenoPlaceno)
OUTPUT INSERTED.ID
VALUES (
@stredisko, @datumNakladky, @smenaNakladky, @hodNakladky, @naklPredak,
@cisloLL, @spzVozuTahace, @spzVozuNavesu, @mpz, @mpz2, @naprTlak, @taraNova,
@unosnost, @pocetNapr, @staniceUrceni,@prijemceZbozi, @datNarozeni,
@jmenoAPrijmeni, @Podpis, @Vyhotovil, @Vysilal, @Kod, @uvolnenoPrijmeni,
@UvolnenoTelefon, @UvolnenoPlaceno);"
end
else
begin
//Update query here
end
end
```
**Then, in your C# code**
```
SqlParameter[] param = new {
new SqlParameter("@stredisko",ValueHereForThisParam),
//add rest the required params here
}
SqlConnection oCon = new SqlConnection(ConnectionString);
SqlCommand oCom = new SqlCommand();
oCom.Connection = oCon;
oCom.CommandType = CommandType.StoredProcedure;
oCom.CommandText = "sp_InsertUpdate_InterniLozniListS3_Hlavicka";
oCom.Parameters.AddRange(param )
oCon.Open();
int i = oCom.ExecuteScalar(); //Will return the added
oCon.Close();
```
|
437,080 |
I'm studying DDD and trying to plan how we'll migrate from our monolith to a microservice architecture. At the moment I'm trying to work through two possibilities
The first is where the shopper is an aggregate with its own microservice. There's CRUD operations against these users and their data is replicated to other microservices where needed (i.e. Billing Address replicates to the Billing microservice)
[](https://i.stack.imgur.com/gjhSA.png)
The issue I see here is that if any system using this data in another microservice wants to modify their data (say update the billing address within the billing microservice) then they have to update their record & write back to the Shopper microservice as it's the source of truth. Or if they're only using a cache, they'll need to update the billing address back at the Shopper microservice and wait for their cache to refresh.
The alternative is to avoid storing data in the Shopper service at all, and only storing it in its final destination. The shopper service would act more as a gateway to call APIs to modify the shopper data in its final location (so the billing microservice is the source of truth for the shoppers billing address, and can modify that data at will)
[](https://i.stack.imgur.com/eecsT.png)
This seems messier to maintain the APIs and keep track of where all the shopper data is but seems way more efficient in terms of read/write and keeps shoppers isolated to where they make sense within their bounded contexts.
Does this second approach make sense or is it flawed in some way?
|
2022/03/02
|
[
"https://softwareengineering.stackexchange.com/questions/437080",
"https://softwareengineering.stackexchange.com",
"https://softwareengineering.stackexchange.com/users/411533/"
] |
>
> There's CRUD operations against these users and their data is replicated to other microservices where needed (i.e. Billing Address replicates to the Billing microservice)
>
>
>
The main argument for data replication is that you intentionally wish to **disconnect** one source from another.
For example, if the customer changes their address today, you wouldn't want their orders from 2020 to suddenly show the new address. Therefore it makes sense to make a copy of the "current" address *at the time of billing*, and store that snapshot without it being affected by future changes made to the customer.
>
> The issue I see here is that if any system using this data in another microservice wants to modify their data (say update the billing address within the billing microservice) then they have to update their record & write back to the Shopper microservice as it's the source of truth.
>
>
>
You're misusing "source of truth" here. By disconnecting the address stored with your customer and in your billing, they have become independent sources of truth, which inherently means that a change to one does **not** reflect on the other.
The above example of a customer moving but not wanting to update their old billings is an example of how a change in one does not get reflected in the other.
If you want a **single** source of truth for these addresses, then you need a **single** copy of that information. This could be in your Shopper microservice if the address is scoped to the customer; or it could be in your Billing microservice if the address is scoped to a single billing and therefore individually decided per billing, even if they are for the same Shopper.
If you store the data in two sources, then you by definition don't have a single source of truth. (*Edit: More precisely, the concepts of a shopper's address and a billing's address are separate, with each being its own source of truth.*)
*Note: Supposing your Shopper becomes the single source of truth, it can still be made possible for someone to adjust the address when looking at a billing entry; but when doing so the Billing microservice should push that update to the Shopper API and not actually try to store any of that information in the Billing database itself, thus retaining the Shopper API as the single source of truth.*
>
> and wait for their cache to refresh.
>
>
>
Caches are a bit of an exception to the "single source of truth" design. They are not implemented for a design reason, but for a performance reason. A cache is inherently considered to be an inferior (but more often consulted) source of truth.
As the saying goes, there are only two hard things in Computer Science: cache invalidation and naming things. How you update/invalidate your cache is an entirely different topic of conversation from how to structure and design your microservices.
>
> The alternative is to avoid storing data in the Shopper service at all, and only storing it in its final destination. The shopper service would act more as a gateway to call APIs to modify the shopper data in its final location (so the billing microservice is the source of truth for the shoppers billing address, and can modify that data at will)
>
>
>
Calling it "the" alternative implies that it is the only other option. It isn't.
But more than that, this approach has significant flaws. For example, let's say you update a shopper's address via the Shopper microservice, but only the Billing microservice actually stores addresses. If the shopper has multiple billings, how are you going to handle this?
* If you would update all billing entries for that shopper, then clearly this address is scoped to the shopper, not the billing entry; and therefore should be stored in the Shopper microservice
* If you would only update a single billing entry (specified by ID), then this should clearly have been routed via the Billing microservice to begin with, because then you're really only updating a billing address, not a shopper. The Shopper microservice should not be involved here.
The way you're suggesting going about it either proves that the address is being stored in the wrong place, or that you're going to introduce unnecessarily tight coupling between two microservices. Neither are a great idea.
---
It's unclear to me why you've only considered storing the address in both locations or only in the Billing database; but seemingly did not consider only storing it in the Shopper database.
I don't know the full picture of your application of course, but I see two likely courses of action here:
* Based on some contextual knowledge I have about billing data; you generally don't want to update billing addresses from the past when the customer changes their address today. Your initial approach of storing both addresses separately is the correct approach here, but you should drop your expectation that a change in one should inherently lead to the same change in the other.
+ In cases where you need to retroactively correct a mistake in an address, it is the nature of the beast that you are then going to have to individually update the related billings (and potentially the shopper if it's their current address that needs fixing). But these situations should be rare and should not be the main driving factor of your design.
+ In cases where this kind of error correction *is* warranted (I've worked in similar government platforms), this significantly complicates the design of your architecture, which now needs to rely on timestamped historical logs and error-correction measures. This is not a small feat and should not be implemented when it's not *that* much of an issue to begin with.
* Based on your mention of wanting to reflect the changes to a billing address in the shopper address as well, it seems like your address is considered to be scoped to the customer. If this is the case (and the previous bullet point is not the case), then it seems most appropriate to only store the address in the Shopper microservice, and the Billing microservice should fetch the address from the Shopper microservice when it needs it.
How you implement caching is a different concern, and one you should only address once you've actually settled on a design for your architecture.
|
**Why do you want to migrate to microservices?**
There is no "generic" way to do architectures, at least not good ones. You have to first define goals and then decide things based on those goals.
Now, *in general*, you want microservices because you want to scale either organizationally (different teams, iteration speed) or operationally (requests/sec), or both. Again, *in general*, introducing "CRUD" based microservices is a *bad* idea. It is easy to see why. Any "data" based interface will create dependencies between the two or even more services.
This will work if you keep it limited to a small number of services that you're only interested to scale differently runtime. For example create update and read services to the same data because they scale completely differently.
Barring any such use-cases, *in general*, **you should strive to make microservices independent**. That is, implement a complete use-case on its own, without needing to communicate with another service. This is the only way you will achieve independent release cycles or easy runtime scaling.
|
4,427,754 |
This algorith, which takes a standard deviation and a mean, should sample from the normal distribution:
<https://github.com/zama-ai/concrete/blob/5a12fb5b0196b48f1325a481dd8e3f4f04b710b6/concrete-core/src/backends/core/private/math/random/gaussian.rs#L19>
Basically it looks like it does
```
s = u^2 + v^2;
if (s>0 && s< 1) {
cst = std * sqrt(-2&ln(s)/2);
output = (u*cst+mean, v*cst + mean);
break;
}
```
where `u` and `v` are random bytes.
I'm trying to know which algorithm is this and what is the greatest and smallest value it can output.
|
2022/04/14
|
[
"https://math.stackexchange.com/questions/4427754",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/166180/"
] |
This is the [Marsaglia polar method](https://en.wikipedia.org/wiki/Marsaglia_polar_method), a variant of the Box–Muller transform.
The very largest (and smallest) values of the result occur when the pair you're calling $(u,v)$ is as close to $0$ as possible. It looks like there is an option for a $32$-bit and $64$-bit version. With $b$ bits available, the smallest positive nonzero value is $1/2^{b-1}$ (this is then cast to a floating point value, which shouldn't cause problems). When $u = 1/2^{b-1}$ and $v = 0$, we get $s = 1/2^{2b-2}$; the final generated value (assuming a standard Gaussian) is $2\sqrt{(b-1)\ln 2}$. The most negative value should similarly be $-2\sqrt{(b-1)\ln 2}$.
This is about $9.27094$ for the $32$-bit version and about $13.2164$ for the $64$-bit version.
|
Looks like the output is always positive if the mean is zero? Better to take $u,v$ uniform in $[-1,1]$.In any case, the underlying idea is that a pair of standard Gaussians has a uniform angle in the plane, and distance squared from the origin which has an exponential distribution.
|
35,918,524 |
**Dataset:** *(Just highlighting error condition data, other conditions work fine)*
[](https://i.stack.imgur.com/dIFsq.png)
**Query:**
```
SELECT `id`, `uid`, `activity_type`, `source_id`, `parent_id`, `parent_type`, `post_id`, `status`
FROM `user_activity` AS `user_activity`
WHERE
`user_activity`.`activity_type` IN(
'STATUS_UPDATE',
'PROFILE_PICTURE_UPDATED',
'PROFILE_COVER_UPDATED',
'ALBUM'
)
AND `user_activity`.`uid` = '13'
AND `user_activity`.`status` = 'ACTIVE'
-- AND `user_activity`.`parent_type` <> 'ALBUM' -- query works wihtout this condition
ORDER BY id DESC LIMIT 10
```
The query works fine and gets the desired results, but when I add the condition:
```
AND `user_activity`.`parent_type` <> 'ALBUM'
```
query returns no results.
I don't understand what's the problem in this query.
[Here is the fiddle.](http://www.sqlfiddle.com/#!9/ad043/2/0)
|
2016/03/10
|
[
"https://Stackoverflow.com/questions/35918524",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1910920/"
] |
SQL uses [three valued logic](https://www.simple-talk.com/sql/learn-sql-server/sql-and-the-snare-of-three-valued-logic/). The NULL <> 'ALBUM' and NULL = 'ALBUM' both evaluate to UNKNOWN. You need to use IS NOT NULL or IS NULL to compare with nulls.
|
The `user_activity.parent_type <> 'ALBUM'` condition also filters every `NULL` value on that column, since `NULL <> 'ALBUM'` isn't `true`, is `undetermined`. So you can use something like this:
```
AND (`user_activity`.`parent_type` <> 'ALBUM' OR `user_activity`.`parent_type` IS NULL)
```
Or:
```
AND COALESCE(`user_activity`.`parent_type`,'') <> 'ALBUM'
```
|
35,918,524 |
**Dataset:** *(Just highlighting error condition data, other conditions work fine)*
[](https://i.stack.imgur.com/dIFsq.png)
**Query:**
```
SELECT `id`, `uid`, `activity_type`, `source_id`, `parent_id`, `parent_type`, `post_id`, `status`
FROM `user_activity` AS `user_activity`
WHERE
`user_activity`.`activity_type` IN(
'STATUS_UPDATE',
'PROFILE_PICTURE_UPDATED',
'PROFILE_COVER_UPDATED',
'ALBUM'
)
AND `user_activity`.`uid` = '13'
AND `user_activity`.`status` = 'ACTIVE'
-- AND `user_activity`.`parent_type` <> 'ALBUM' -- query works wihtout this condition
ORDER BY id DESC LIMIT 10
```
The query works fine and gets the desired results, but when I add the condition:
```
AND `user_activity`.`parent_type` <> 'ALBUM'
```
query returns no results.
I don't understand what's the problem in this query.
[Here is the fiddle.](http://www.sqlfiddle.com/#!9/ad043/2/0)
|
2016/03/10
|
[
"https://Stackoverflow.com/questions/35918524",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1910920/"
] |
The `user_activity.parent_type <> 'ALBUM'` condition also filters every `NULL` value on that column, since `NULL <> 'ALBUM'` isn't `true`, is `undetermined`. So you can use something like this:
```
AND (`user_activity`.`parent_type` <> 'ALBUM' OR `user_activity`.`parent_type` IS NULL)
```
Or:
```
AND COALESCE(`user_activity`.`parent_type`,'') <> 'ALBUM'
```
|
Try This
```
SELECT `id`, `uid`, `activity_type`, `source_id`, `parent_id`, `parent_type`, `post_id`, `status`
FROM `user_activity` AS `user_activity`
WHERE
`user_activity`.`activity_type` IN(
'STATUS_UPDATE',
'PROFILE_PICTURE_UPDATED',
'PROFILE_COVER_UPDATED',
'ALBUM'
)
AND `user_activity`.`uid` = '13'
AND `user_activity`.`status` = 'ACTIVE'
AND IFNULL(`user_activity`.`parent_type`,'') <> 'ALBUM'
ORDER BY id DESC LIMIT 10
```
|
35,918,524 |
**Dataset:** *(Just highlighting error condition data, other conditions work fine)*
[](https://i.stack.imgur.com/dIFsq.png)
**Query:**
```
SELECT `id`, `uid`, `activity_type`, `source_id`, `parent_id`, `parent_type`, `post_id`, `status`
FROM `user_activity` AS `user_activity`
WHERE
`user_activity`.`activity_type` IN(
'STATUS_UPDATE',
'PROFILE_PICTURE_UPDATED',
'PROFILE_COVER_UPDATED',
'ALBUM'
)
AND `user_activity`.`uid` = '13'
AND `user_activity`.`status` = 'ACTIVE'
-- AND `user_activity`.`parent_type` <> 'ALBUM' -- query works wihtout this condition
ORDER BY id DESC LIMIT 10
```
The query works fine and gets the desired results, but when I add the condition:
```
AND `user_activity`.`parent_type` <> 'ALBUM'
```
query returns no results.
I don't understand what's the problem in this query.
[Here is the fiddle.](http://www.sqlfiddle.com/#!9/ad043/2/0)
|
2016/03/10
|
[
"https://Stackoverflow.com/questions/35918524",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1910920/"
] |
The `user_activity.parent_type <> 'ALBUM'` condition also filters every `NULL` value on that column, since `NULL <> 'ALBUM'` isn't `true`, is `undetermined`. So you can use something like this:
```
AND (`user_activity`.`parent_type` <> 'ALBUM' OR `user_activity`.`parent_type` IS NULL)
```
Or:
```
AND COALESCE(`user_activity`.`parent_type`,'') <> 'ALBUM'
```
|
If I consider the data in the SQLfidle, There's no problem in your query.
The only row that it is supposed to return, following YOUR logic, is a row containing a NULL value in parent\_type
MySQL logic is just diffrent than yours:
When you use the <> or != operator, the NULLs are omited and never returned.
If you want to also get the NULLs, do:
```
AND (`user_activity`.`parent_type` <> 'ALBUM' OR `user_activity`.`parent_type` IS NULL)
```
or this
```
AND coalesce(`user_activity`.`parent_type`,'whateveryouwanthere') <> 'ALBUM'
```
|
35,918,524 |
**Dataset:** *(Just highlighting error condition data, other conditions work fine)*
[](https://i.stack.imgur.com/dIFsq.png)
**Query:**
```
SELECT `id`, `uid`, `activity_type`, `source_id`, `parent_id`, `parent_type`, `post_id`, `status`
FROM `user_activity` AS `user_activity`
WHERE
`user_activity`.`activity_type` IN(
'STATUS_UPDATE',
'PROFILE_PICTURE_UPDATED',
'PROFILE_COVER_UPDATED',
'ALBUM'
)
AND `user_activity`.`uid` = '13'
AND `user_activity`.`status` = 'ACTIVE'
-- AND `user_activity`.`parent_type` <> 'ALBUM' -- query works wihtout this condition
ORDER BY id DESC LIMIT 10
```
The query works fine and gets the desired results, but when I add the condition:
```
AND `user_activity`.`parent_type` <> 'ALBUM'
```
query returns no results.
I don't understand what's the problem in this query.
[Here is the fiddle.](http://www.sqlfiddle.com/#!9/ad043/2/0)
|
2016/03/10
|
[
"https://Stackoverflow.com/questions/35918524",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1910920/"
] |
SQL uses [three valued logic](https://www.simple-talk.com/sql/learn-sql-server/sql-and-the-snare-of-three-valued-logic/). The NULL <> 'ALBUM' and NULL = 'ALBUM' both evaluate to UNKNOWN. You need to use IS NOT NULL or IS NULL to compare with nulls.
|
Try This
```
SELECT `id`, `uid`, `activity_type`, `source_id`, `parent_id`, `parent_type`, `post_id`, `status`
FROM `user_activity` AS `user_activity`
WHERE
`user_activity`.`activity_type` IN(
'STATUS_UPDATE',
'PROFILE_PICTURE_UPDATED',
'PROFILE_COVER_UPDATED',
'ALBUM'
)
AND `user_activity`.`uid` = '13'
AND `user_activity`.`status` = 'ACTIVE'
AND IFNULL(`user_activity`.`parent_type`,'') <> 'ALBUM'
ORDER BY id DESC LIMIT 10
```
|
35,918,524 |
**Dataset:** *(Just highlighting error condition data, other conditions work fine)*
[](https://i.stack.imgur.com/dIFsq.png)
**Query:**
```
SELECT `id`, `uid`, `activity_type`, `source_id`, `parent_id`, `parent_type`, `post_id`, `status`
FROM `user_activity` AS `user_activity`
WHERE
`user_activity`.`activity_type` IN(
'STATUS_UPDATE',
'PROFILE_PICTURE_UPDATED',
'PROFILE_COVER_UPDATED',
'ALBUM'
)
AND `user_activity`.`uid` = '13'
AND `user_activity`.`status` = 'ACTIVE'
-- AND `user_activity`.`parent_type` <> 'ALBUM' -- query works wihtout this condition
ORDER BY id DESC LIMIT 10
```
The query works fine and gets the desired results, but when I add the condition:
```
AND `user_activity`.`parent_type` <> 'ALBUM'
```
query returns no results.
I don't understand what's the problem in this query.
[Here is the fiddle.](http://www.sqlfiddle.com/#!9/ad043/2/0)
|
2016/03/10
|
[
"https://Stackoverflow.com/questions/35918524",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1910920/"
] |
SQL uses [three valued logic](https://www.simple-talk.com/sql/learn-sql-server/sql-and-the-snare-of-three-valued-logic/). The NULL <> 'ALBUM' and NULL = 'ALBUM' both evaluate to UNKNOWN. You need to use IS NOT NULL or IS NULL to compare with nulls.
|
If I consider the data in the SQLfidle, There's no problem in your query.
The only row that it is supposed to return, following YOUR logic, is a row containing a NULL value in parent\_type
MySQL logic is just diffrent than yours:
When you use the <> or != operator, the NULLs are omited and never returned.
If you want to also get the NULLs, do:
```
AND (`user_activity`.`parent_type` <> 'ALBUM' OR `user_activity`.`parent_type` IS NULL)
```
or this
```
AND coalesce(`user_activity`.`parent_type`,'whateveryouwanthere') <> 'ALBUM'
```
|
68,189,665 |
I wrote a script that opens up an enlarged image in a modal box when you click on the smaller one but for some reason when I try to click on the small image the modal box does not open. My website uses bootstrap but I have written my own CSS to create the modal as the bootstrap is not providing me with what I want.
I opened my inspector in Chrome and I got an error with my JavaScript
>
> Uncaught TypeError: Cannot read property 'addEventListener' of null
>
>
>
This is on line 1 of the javascript
**HTML&PHP**
```php
<div class="bgmd">
<div class="ctmod">
<div class="xbutton">×</div>
<?php
echo "<img src='images/car22.jpg'/>";//Large Image
?>
</div>
</div>
<?php
echo "<a href='#' id='big'><img src='images/car".$id.".jpg' class='img-thumbnail center-block'/></a>";//Smaller Image
```
**CSS**
```css
.bgmd{
width: 100% !important;
height: 100% !important;
background-color: rgba(0, 0, 0, 0.7) !important;
position: absolute !important;
top: 0 !important;
display: flex !important;
justify-content: center !important;
align-items: center !important;
display: none !important;
}
.ctmod{
width: 500px !important;
height: 300px !important;
background-color: white !important;
border-radius: 4px !important;
text-align: center !important;
position: relative !important;
}
.xbutton{
position: absolute !important;
top: 0 !important;
right: 14px !important;
font-size: 42px !important;
transform: rotate(45deg) !important;
cursor: pointer !important;
}
```
**JAVASCRIPT**
```js
document.getElementById('big').addEventListener('click', function() {
document.querySelector('.bgmd').style.display = 'flex';
});
document.querySelector('.xbutton').addEventListener('click', function() {
document.querySelector('.bgmd').style.display = 'none';
});
```
|
2021/06/30
|
[
"https://Stackoverflow.com/questions/68189665",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1078456/"
] |
You have the `display` property twice affecting the same element which is conflicting, you should only have `display: none;` without the `!important` rule. Also you have an excessive amount of `!important` rules, they're only necessary when you want to override other styles (typically ones that can't be directly edited)
|
You set
```css
.bgmd {
display: none !important;
}
```
which overrides setting the style of the modal to `display: flex`.
|
68,189,665 |
I wrote a script that opens up an enlarged image in a modal box when you click on the smaller one but for some reason when I try to click on the small image the modal box does not open. My website uses bootstrap but I have written my own CSS to create the modal as the bootstrap is not providing me with what I want.
I opened my inspector in Chrome and I got an error with my JavaScript
>
> Uncaught TypeError: Cannot read property 'addEventListener' of null
>
>
>
This is on line 1 of the javascript
**HTML&PHP**
```php
<div class="bgmd">
<div class="ctmod">
<div class="xbutton">×</div>
<?php
echo "<img src='images/car22.jpg'/>";//Large Image
?>
</div>
</div>
<?php
echo "<a href='#' id='big'><img src='images/car".$id.".jpg' class='img-thumbnail center-block'/></a>";//Smaller Image
```
**CSS**
```css
.bgmd{
width: 100% !important;
height: 100% !important;
background-color: rgba(0, 0, 0, 0.7) !important;
position: absolute !important;
top: 0 !important;
display: flex !important;
justify-content: center !important;
align-items: center !important;
display: none !important;
}
.ctmod{
width: 500px !important;
height: 300px !important;
background-color: white !important;
border-radius: 4px !important;
text-align: center !important;
position: relative !important;
}
.xbutton{
position: absolute !important;
top: 0 !important;
right: 14px !important;
font-size: 42px !important;
transform: rotate(45deg) !important;
cursor: pointer !important;
}
```
**JAVASCRIPT**
```js
document.getElementById('big').addEventListener('click', function() {
document.querySelector('.bgmd').style.display = 'flex';
});
document.querySelector('.xbutton').addEventListener('click', function() {
document.querySelector('.bgmd').style.display = 'none';
});
```
|
2021/06/30
|
[
"https://Stackoverflow.com/questions/68189665",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1078456/"
] |
You have the `display` property twice affecting the same element which is conflicting, you should only have `display: none;` without the `!important` rule. Also you have an excessive amount of `!important` rules, they're only necessary when you want to override other styles (typically ones that can't be directly edited)
|
In your linked HTML-output there are multiple elements with the ID `big`. This is not valid and therefor you get the error. You should make sure that you have only unique IDs, then your code will work.
Furthermore: Please check double definitions like `display` and if it's really necessary to use so many `!important` statements.
---
If you have multiple elements like this you have to loop over the `#big...` images. To select all elements with an ID that begins with `big` you can use the attribute selector:
```js
var img_triggers = document.querySelectorAll('a[id^="big"]');
```
To style the associated `div.bgmd` you could select the previous element of the clicked anchor:
```js
this.previousElementSibling.style.display = 'flex';
```
For closing via `.xbutton` you also have to loop over all of these buttons and style its grandparent (which is the associated `div.bgmd`):
```js
this.previousElementSibling.style.display = 'flex';
```
**Working example:** (*minified for demonstration, with some dummy data and without `!important`*)
```js
var img_triggers = document.querySelectorAll('a[id^="big"]');
for (let i = 0; i < img_triggers.length; i++) {
img_triggers[i].addEventListener('click', function() {
this.previousElementSibling.style.display = 'flex';
});
}
var buttons = document.querySelectorAll('.xbutton');
for (let i = 0; i < buttons.length; i++) {
buttons[i].addEventListener('click', function() {
this.parentElement.parentElement.style.display = 'none';
});
}
```
```css
.bgmd {
width: 100%;
height: 100%;
background-color: rgba(0, 0, 0, 0.7);
position: absolute;
top: 0;
justify-content: center;
align-items: center;
display: none;
}
.ctmod {
width: 250px;
height: 150px;
background-color: white;
border-radius: 4px;
text-align: center;
position: relative;
}
.xbutton {
position: absolute;
top: 0;
right: 14px;
font-size: 42px;
transform: rotate(45deg);
cursor: pointer;
}
```
```html
<div class="bgmd">
<div class="ctmod">
<div class="xbutton">×</div>
<img src='https://picsum.photos/id/1/150' />
</div>
</div>
<a href='#' id='big1'>
<img src='https://picsum.photos/id/1/50' class='img-thumbnail center-block' />
</a>
<div class="bgmd">
<div class="ctmod">
<div class="xbutton">×</div>
<img src='https://picsum.photos/id/2/150' />
</div>
</div>
<a href='#' id='big2'>
<img src='https://picsum.photos/id/2/50' class='img-thumbnail center-block' />
</a>
<div class="bgmd">
<div class="ctmod">
<div class="xbutton">×</div>
<img src='https://picsum.photos/id/3/150' />
</div>
</div>
<a href='#' id='big3'>
<img src='https://picsum.photos/id/3/50' class='img-thumbnail center-block' />
</a>
```
|
69,085,522 |
Looking for a generic solution to find attribute value of a class on different level of hierarchy. The input to the method will be attribute name only (like "name") then I should be able to find value of that attribute.
The structure of my class is just like below:
```
class Student {
private String id;
private String name;
private List<Address> addresses;
private Map<String, String> customAttributes;
}
class Address {
private String city;
private String state;
private PhoneNumbers phoneNumbers;
...
getter setter
}
class PhoneNumbers {
private PhoneNumber phoneNumber1;
private PhoneNumber phoneNumber2;
..
getter setter
}
class PhoneNumber {
private String code;
private String number;
...
getter setter
}
```
It's easy to find value on student level, in that case I can create map of <attribute, getter> and I will be able to find the value.
But in current scenario, there are different levels, custom attribute map and records are high in numbers (like 10,000 or more).
So the input to the method can be anything like:
```
private String getAttributeValue(String attributeName) {
}
var phoneNumber1 = new PhoneNumber("012", "233223");
var phoneNumber2 = new PhoneNumber("91", "23323223");
var phoneNumbers = new PhoneNumbers(phoneNumber1, phoneNumber2);
var address1 = new Address("city1", "state1", phoneNumbers);
var address2 = new Address("city123", "state1", phoneNumbers);
var customAttributes = Map.of(
"attr1", "value1",
"attr2", "value2"
);
var student = new Student(1, "xyz", List.of(address1, address2), customAttributes);
city -> city123
attr2 -> value2
code -> 012
number -> 23323223
```
Please help me here, if anyone has implemented the similar solution.
|
2021/09/07
|
[
"https://Stackoverflow.com/questions/69085522",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16850019/"
] |
A valid date-time as defined in RFC 3339 with these additional qualifications:
the literal letters T and Z in the date/time syntax must always be uppercase
the date-fullyear production is instead defined as four or more digits representing a number greater than 0
Examples
1990-12-31T23:59:60Z
1996-12-19T16:39:57-08:00
Solution
To create RFC 3339 format in PHP you can use:
```
echo date('Y-m-d\TH:i:sP', $row['Time']);
```
or in another way:
```
echo date("c", strtotime($row['Time']));
```
or if you prefer objective style:
```
echo (new DateTime($row['Time']))->format('c');
<input type="datetime-local" value="<?php echo date('Y-m-d\TH:i:sP', $row['Time']); ?>" class="date" name="start" REQUIRED>
```
Use links for more info
<https://www.php.net/manual/en/function.date.php>
<https://www.php.net/manual/en/class.datetime.php>
|
if in database time stored like this "20:18" Simply Do the
```
<input type="time" class="form-control" name="activity_time" placeholder="Activity Time" value="<?php echo date('h:i') ?>" required />
```
|
69,085,522 |
Looking for a generic solution to find attribute value of a class on different level of hierarchy. The input to the method will be attribute name only (like "name") then I should be able to find value of that attribute.
The structure of my class is just like below:
```
class Student {
private String id;
private String name;
private List<Address> addresses;
private Map<String, String> customAttributes;
}
class Address {
private String city;
private String state;
private PhoneNumbers phoneNumbers;
...
getter setter
}
class PhoneNumbers {
private PhoneNumber phoneNumber1;
private PhoneNumber phoneNumber2;
..
getter setter
}
class PhoneNumber {
private String code;
private String number;
...
getter setter
}
```
It's easy to find value on student level, in that case I can create map of <attribute, getter> and I will be able to find the value.
But in current scenario, there are different levels, custom attribute map and records are high in numbers (like 10,000 or more).
So the input to the method can be anything like:
```
private String getAttributeValue(String attributeName) {
}
var phoneNumber1 = new PhoneNumber("012", "233223");
var phoneNumber2 = new PhoneNumber("91", "23323223");
var phoneNumbers = new PhoneNumbers(phoneNumber1, phoneNumber2);
var address1 = new Address("city1", "state1", phoneNumbers);
var address2 = new Address("city123", "state1", phoneNumbers);
var customAttributes = Map.of(
"attr1", "value1",
"attr2", "value2"
);
var student = new Student(1, "xyz", List.of(address1, address2), customAttributes);
city -> city123
attr2 -> value2
code -> 012
number -> 23323223
```
Please help me here, if anyone has implemented the similar solution.
|
2021/09/07
|
[
"https://Stackoverflow.com/questions/69085522",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16850019/"
] |
You need to make sure that the format the `date` variable is printing out is valid for the HTML input you want to use.
If it is not (which is what I believe the issue is), then you will need to modify your `date/time` variable so that it prints in the correct format.
From the picture it looks like you simply want `Hours:Minutes Seconds`. Is this correct to assume?
```
<?php
//Optional if you wish to set your timezone
date_default_timezone_set('GMT');
// This would print the format 2021-09-07 11:04:48
echo date("Y-m-d,h:m:s");
//You probably want to adjust it to something like this
echo date("h:m s");
?>
```
So to answer your question: Replace your PHP code ( `<?php echo date('h:i A',time()); ?>` ) with this, and it should be in the correct format.
`<?php echo date("h:m s); ?>`
|
if in database time stored like this "20:18" Simply Do the
```
<input type="time" class="form-control" name="activity_time" placeholder="Activity Time" value="<?php echo date('h:i') ?>" required />
```
|
1,886,890 |
In Euclidean geometry texts, it is always mentioned that point is undefined, it can only be described. Consider the following definition: "A point is a mathematical object with no shape and size." I do not understand what is the problem with this definition. Please give the detailed reasons. Thanks in advance!
|
2016/08/09
|
[
"https://math.stackexchange.com/questions/1886890",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/346949/"
] |
The exact difficulty is that in mathematics, we define things in terms
of other things. We also avoid circular definitions, in other words we
do not want to define $A$ in terms of $B$ where $B$ is defined
in terms of $C$ and $C$ is defined in terms of $A$.
Because we avoid circularity, we can lay out all our definitions
in order so that anything that is defined is defined when it is first mentioned. But if we write out a mathematical theory in this fashion,
and look at the very first definition we wrote, the thing it defined
was defined in terms of some other things, and those "other things"
*cannot* have been defined previously (since this is our first definition)
and will not be defined later (since every definition comes before the
first use of the thing it defines).
In short, in order to build a mathematical theory we have to start with
some "primitive notions" that we will never define. Everything else
can be defined in terms of those notions.
This does not prove that a point *must* be one of the primitive notions
of Euclidean geometry, but it happens that it *has* been chosen to be
one of those primitive notions, and this choice has worked out well.
|
Thanks are due to Wildcard for the complete lesson in the philosophy of the slippery slope that is (higher) mathematics. Perhaps my notion is only pedagogical.
This begins with the definition of a line as length with no width. Just as one can imagine the length going on forever one can see that the width as a compliment can be vanishingly small. It is only represented by the bulky collection of pencil lead on wrinkled paper. The pencil lead is not the line, it only represents the line.
Rather than a collection of points (slippery again) the line is a boundary between one side or idea and another. Perhaps as with the horizon between the earth and the sky they are not in contact but the boundary is there. The boundary is being represented and is all you need to consider.
With this in mind a natural question is what happens when two lines intersect. A simple example is this "+". Here are just two marks representing two lines of no width in themselves are crossing. The cross sectional area they have in common is itself infinitely small. As such, any number of lines can pass through it with the only limit being the amount of pencil lead you can put up with to represent it on the increasingly wrinkled paper. Such an infinitely small point can be indicated by plusses or periods "+, ." with only what it represents in mind. With points represented as such you can do all of geometry, analytic and otherwise without undue philosophical angst.
One will be vexed in trying to define these ideas out of order. One often begins with the smallest object, the point, and moves to the larger, the line. The mistake is starting with the smallest object, not the simplest. That is when you are stuck for a definition of the first for which you need the second. Not an uncommon problem.
|
1,886,890 |
In Euclidean geometry texts, it is always mentioned that point is undefined, it can only be described. Consider the following definition: "A point is a mathematical object with no shape and size." I do not understand what is the problem with this definition. Please give the detailed reasons. Thanks in advance!
|
2016/08/09
|
[
"https://math.stackexchange.com/questions/1886890",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/346949/"
] |
The exact difficulty is that in mathematics, we define things in terms
of other things. We also avoid circular definitions, in other words we
do not want to define $A$ in terms of $B$ where $B$ is defined
in terms of $C$ and $C$ is defined in terms of $A$.
Because we avoid circularity, we can lay out all our definitions
in order so that anything that is defined is defined when it is first mentioned. But if we write out a mathematical theory in this fashion,
and look at the very first definition we wrote, the thing it defined
was defined in terms of some other things, and those "other things"
*cannot* have been defined previously (since this is our first definition)
and will not be defined later (since every definition comes before the
first use of the thing it defines).
In short, in order to build a mathematical theory we have to start with
some "primitive notions" that we will never define. Everything else
can be defined in terms of those notions.
This does not prove that a point *must* be one of the primitive notions
of Euclidean geometry, but it happens that it *has* been chosen to be
one of those primitive notions, and this choice has worked out well.
|
I wonder if these texts really want to stress that it is dificult or impossible to define what a point is. I guess they just want to emphasize that they didn't even try, because it is useful to only describe the relations points have with other undefined entities such as lines. That is because if you have a theorem that just uses these axioms and you have some objects that behave like points and the other objects of this axiomatic description, then you can apply that theorem to them, even if they don't look like anything that you would normally consider points and lines etc.
|
1,886,890 |
In Euclidean geometry texts, it is always mentioned that point is undefined, it can only be described. Consider the following definition: "A point is a mathematical object with no shape and size." I do not understand what is the problem with this definition. Please give the detailed reasons. Thanks in advance!
|
2016/08/09
|
[
"https://math.stackexchange.com/questions/1886890",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/346949/"
] |
The exact difficulty is that in mathematics, we define things in terms
of other things. We also avoid circular definitions, in other words we
do not want to define $A$ in terms of $B$ where $B$ is defined
in terms of $C$ and $C$ is defined in terms of $A$.
Because we avoid circularity, we can lay out all our definitions
in order so that anything that is defined is defined when it is first mentioned. But if we write out a mathematical theory in this fashion,
and look at the very first definition we wrote, the thing it defined
was defined in terms of some other things, and those "other things"
*cannot* have been defined previously (since this is our first definition)
and will not be defined later (since every definition comes before the
first use of the thing it defines).
In short, in order to build a mathematical theory we have to start with
some "primitive notions" that we will never define. Everything else
can be defined in terms of those notions.
This does not prove that a point *must* be one of the primitive notions
of Euclidean geometry, but it happens that it *has* been chosen to be
one of those primitive notions, and this choice has worked out well.
|
It may attract controversy, but I will go ahead and present an alternative view on this question.
The other answerers have done an exemplary job showing why a mathematical primitive cannot be *mathematically* defined.
The trick that is missed is that in order to communicate with someone at all, you must have some shared reality with them. You must have some form of agreement on how you are communicating or they will simply never be able to understand you.
Mathematics takes the view that anything which is not precisely defined, can't be considered valid mathematically—except for primitives. I've observed that some authors and mathematicians are uncomfortable with this exception, but they see no way around it so they learn to live with it.
In point of fact we *do* share a common reality, or you would not be able to read this answer at all. We have a shared reality of the physical universe. All language is rooted ultimately in this shared reality, and you can observe that babies learning the language (any language, not just English) do so by observing real objects and real actions, and gradually work up to high levels of abstractions.
So **the answer to this question falls in the realm of epistemology rather than mathematics.**
Through mathematics it is possible to symbolize and reason about universes with entirely different rules from the universe we live in. However, in order to communicate about these other universes or abstractions, the fundamentals must be explained in a way that can be agreed with and understood by people in *this* universe—otherwise there will be no way to communicate about all these beautiful abstractions. Higher-level abstractions in these other universes (or "rules sets") can be explained in terms of primitives—but the primitives must still be defined.
---
Now you've mentioned Euclidean Geometry, so let's take that up specifically. Euclidean Geometry has a high degree of applicability to this universe—but it is *not* this universe; it is an idealized abstraction which can be *applied* to this universe.
Therefore the above statement about definitions of primitives applies to Euclidean Geometry: the primitives must be defined in terms which can be understood by the realities of *this* universe. The rest of the terms can be defined in terms of the primitives and do not, strictly speaking, exist in this (or any) universe except as an abstraction.
---
As a final note, I will add that from a *pedagogical* standpoint, I believe that the ubiquitous introduction to mathematics textbooks by stating, "Here are some terms that cannot be defined by anyone," is a gigantic mistake—and may even account for a large portion of the population who regard mathematics as complex and incomprehensible.
|
1,886,890 |
In Euclidean geometry texts, it is always mentioned that point is undefined, it can only be described. Consider the following definition: "A point is a mathematical object with no shape and size." I do not understand what is the problem with this definition. Please give the detailed reasons. Thanks in advance!
|
2016/08/09
|
[
"https://math.stackexchange.com/questions/1886890",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/346949/"
] |
It may attract controversy, but I will go ahead and present an alternative view on this question.
The other answerers have done an exemplary job showing why a mathematical primitive cannot be *mathematically* defined.
The trick that is missed is that in order to communicate with someone at all, you must have some shared reality with them. You must have some form of agreement on how you are communicating or they will simply never be able to understand you.
Mathematics takes the view that anything which is not precisely defined, can't be considered valid mathematically—except for primitives. I've observed that some authors and mathematicians are uncomfortable with this exception, but they see no way around it so they learn to live with it.
In point of fact we *do* share a common reality, or you would not be able to read this answer at all. We have a shared reality of the physical universe. All language is rooted ultimately in this shared reality, and you can observe that babies learning the language (any language, not just English) do so by observing real objects and real actions, and gradually work up to high levels of abstractions.
So **the answer to this question falls in the realm of epistemology rather than mathematics.**
Through mathematics it is possible to symbolize and reason about universes with entirely different rules from the universe we live in. However, in order to communicate about these other universes or abstractions, the fundamentals must be explained in a way that can be agreed with and understood by people in *this* universe—otherwise there will be no way to communicate about all these beautiful abstractions. Higher-level abstractions in these other universes (or "rules sets") can be explained in terms of primitives—but the primitives must still be defined.
---
Now you've mentioned Euclidean Geometry, so let's take that up specifically. Euclidean Geometry has a high degree of applicability to this universe—but it is *not* this universe; it is an idealized abstraction which can be *applied* to this universe.
Therefore the above statement about definitions of primitives applies to Euclidean Geometry: the primitives must be defined in terms which can be understood by the realities of *this* universe. The rest of the terms can be defined in terms of the primitives and do not, strictly speaking, exist in this (or any) universe except as an abstraction.
---
As a final note, I will add that from a *pedagogical* standpoint, I believe that the ubiquitous introduction to mathematics textbooks by stating, "Here are some terms that cannot be defined by anyone," is a gigantic mistake—and may even account for a large portion of the population who regard mathematics as complex and incomprehensible.
|
In my mind, a point is a context-specific term which means an element of the set being considered.
All the following would make sense to me:
* $sin(x)$ is a point in the space of functions
* (1,2) is a point in $R^2$
|
1,886,890 |
In Euclidean geometry texts, it is always mentioned that point is undefined, it can only be described. Consider the following definition: "A point is a mathematical object with no shape and size." I do not understand what is the problem with this definition. Please give the detailed reasons. Thanks in advance!
|
2016/08/09
|
[
"https://math.stackexchange.com/questions/1886890",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/346949/"
] |
Under your definition, the following things are points:
* the variable $x$
* the sentence $(\forall x)(\exists y)(x^2 = y)$
* $\int\_{\infty}^{\infty} f(x) dx$ where $f$ is unspecified
* the category of all small categories
I'm sure you agree that none of these things are points.
|
I wonder if these texts really want to stress that it is dificult or impossible to define what a point is. I guess they just want to emphasize that they didn't even try, because it is useful to only describe the relations points have with other undefined entities such as lines. That is because if you have a theorem that just uses these axioms and you have some objects that behave like points and the other objects of this axiomatic description, then you can apply that theorem to them, even if they don't look like anything that you would normally consider points and lines etc.
|
1,886,890 |
In Euclidean geometry texts, it is always mentioned that point is undefined, it can only be described. Consider the following definition: "A point is a mathematical object with no shape and size." I do not understand what is the problem with this definition. Please give the detailed reasons. Thanks in advance!
|
2016/08/09
|
[
"https://math.stackexchange.com/questions/1886890",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/346949/"
] |
The exact difficulty is that in mathematics, we define things in terms
of other things. We also avoid circular definitions, in other words we
do not want to define $A$ in terms of $B$ where $B$ is defined
in terms of $C$ and $C$ is defined in terms of $A$.
Because we avoid circularity, we can lay out all our definitions
in order so that anything that is defined is defined when it is first mentioned. But if we write out a mathematical theory in this fashion,
and look at the very first definition we wrote, the thing it defined
was defined in terms of some other things, and those "other things"
*cannot* have been defined previously (since this is our first definition)
and will not be defined later (since every definition comes before the
first use of the thing it defines).
In short, in order to build a mathematical theory we have to start with
some "primitive notions" that we will never define. Everything else
can be defined in terms of those notions.
This does not prove that a point *must* be one of the primitive notions
of Euclidean geometry, but it happens that it *has* been chosen to be
one of those primitive notions, and this choice has worked out well.
|
In a famous comment in the context of a discussion of axiomatisations, David Hilbert noted that these undefined objects might as well be beermugs. The basic conceptual problem here is that mathematicians are tempted to look for ultimate foundations for mathematics. This naturally leads one to a stalemate because whatever foundation you declare to be ultimate, will contain undefined terms which you can in turn ask for even more rigorous foundations for.
The solution is to abandon foundationalism altogether together with a quixotic search for ultimate rigor, and view axiomatisations for what they are, namely convenient tools for clarifying the relations among mathematical entities one is interested in. And of course I will refuse to *define* a mathematical entity just I would refuse foundationalism.
|
1,886,890 |
In Euclidean geometry texts, it is always mentioned that point is undefined, it can only be described. Consider the following definition: "A point is a mathematical object with no shape and size." I do not understand what is the problem with this definition. Please give the detailed reasons. Thanks in advance!
|
2016/08/09
|
[
"https://math.stackexchange.com/questions/1886890",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/346949/"
] |
Under your definition, the following things are points:
* the variable $x$
* the sentence $(\forall x)(\exists y)(x^2 = y)$
* $\int\_{\infty}^{\infty} f(x) dx$ where $f$ is unspecified
* the category of all small categories
I'm sure you agree that none of these things are points.
|
### No problem
>
> What is the exact difficulty in defining a point in Euclidean geometry?
>
>
>
There is no difficulty and no problem, it's just the way it is defined.
### Meaning
>
> "A point is a mathematical object with no shape and size."
>
>
>
The definition literally means that a point has no "shape and size" (i.e., it occupies no space, it has no body, no interiour, no color, no temperature, no feature, whatever other word you would like). It literally has nothing except the few numbers that define/describe it.
"A point is a mathematical object" means that it exists purely mathematically; there is no physical equivalent to a point. It is a mathematical *object*, which means it is a purely abstract thing which we argue about in the frame of some mathematical system.
For example, in the simple 2-dimensional plane we are used to when discussing these things in a school setting, a combination of two numbers (which also are mathematical objects, not physical). Or in the setting of Euklid, by just reasoning about the relationships between points, lines etc. in an abstract plane without even giving coordinates to them.
### Not a point
As a comparison: what is *not* a point? If you take your pencil and make a little impression on your piece of paper, this is *not* a point. That is a pencil mark, or a circle if you so wish. It has non-mathematical properties, for example the minuscule thickness of the layer of paint you addded to the paper, or the radius of the circle, its color, the type of molecules making it up, etc. etc. Even if you go to the lowest possible scales, i.e., placing a (classical, not quantum-mechanical) atom somewhere with a raster tunnel microscope, that atom will still take up a spherical amount of space and will *not* be a "point".
|
1,886,890 |
In Euclidean geometry texts, it is always mentioned that point is undefined, it can only be described. Consider the following definition: "A point is a mathematical object with no shape and size." I do not understand what is the problem with this definition. Please give the detailed reasons. Thanks in advance!
|
2016/08/09
|
[
"https://math.stackexchange.com/questions/1886890",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/346949/"
] |
Under your definition, the following things are points:
* the variable $x$
* the sentence $(\forall x)(\exists y)(x^2 = y)$
* $\int\_{\infty}^{\infty} f(x) dx$ where $f$ is unspecified
* the category of all small categories
I'm sure you agree that none of these things are points.
|
In a famous comment in the context of a discussion of axiomatisations, David Hilbert noted that these undefined objects might as well be beermugs. The basic conceptual problem here is that mathematicians are tempted to look for ultimate foundations for mathematics. This naturally leads one to a stalemate because whatever foundation you declare to be ultimate, will contain undefined terms which you can in turn ask for even more rigorous foundations for.
The solution is to abandon foundationalism altogether together with a quixotic search for ultimate rigor, and view axiomatisations for what they are, namely convenient tools for clarifying the relations among mathematical entities one is interested in. And of course I will refuse to *define* a mathematical entity just I would refuse foundationalism.
|
1,886,890 |
In Euclidean geometry texts, it is always mentioned that point is undefined, it can only be described. Consider the following definition: "A point is a mathematical object with no shape and size." I do not understand what is the problem with this definition. Please give the detailed reasons. Thanks in advance!
|
2016/08/09
|
[
"https://math.stackexchange.com/questions/1886890",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/346949/"
] |
It may attract controversy, but I will go ahead and present an alternative view on this question.
The other answerers have done an exemplary job showing why a mathematical primitive cannot be *mathematically* defined.
The trick that is missed is that in order to communicate with someone at all, you must have some shared reality with them. You must have some form of agreement on how you are communicating or they will simply never be able to understand you.
Mathematics takes the view that anything which is not precisely defined, can't be considered valid mathematically—except for primitives. I've observed that some authors and mathematicians are uncomfortable with this exception, but they see no way around it so they learn to live with it.
In point of fact we *do* share a common reality, or you would not be able to read this answer at all. We have a shared reality of the physical universe. All language is rooted ultimately in this shared reality, and you can observe that babies learning the language (any language, not just English) do so by observing real objects and real actions, and gradually work up to high levels of abstractions.
So **the answer to this question falls in the realm of epistemology rather than mathematics.**
Through mathematics it is possible to symbolize and reason about universes with entirely different rules from the universe we live in. However, in order to communicate about these other universes or abstractions, the fundamentals must be explained in a way that can be agreed with and understood by people in *this* universe—otherwise there will be no way to communicate about all these beautiful abstractions. Higher-level abstractions in these other universes (or "rules sets") can be explained in terms of primitives—but the primitives must still be defined.
---
Now you've mentioned Euclidean Geometry, so let's take that up specifically. Euclidean Geometry has a high degree of applicability to this universe—but it is *not* this universe; it is an idealized abstraction which can be *applied* to this universe.
Therefore the above statement about definitions of primitives applies to Euclidean Geometry: the primitives must be defined in terms which can be understood by the realities of *this* universe. The rest of the terms can be defined in terms of the primitives and do not, strictly speaking, exist in this (or any) universe except as an abstraction.
---
As a final note, I will add that from a *pedagogical* standpoint, I believe that the ubiquitous introduction to mathematics textbooks by stating, "Here are some terms that cannot be defined by anyone," is a gigantic mistake—and may even account for a large portion of the population who regard mathematics as complex and incomprehensible.
|
### No problem
>
> What is the exact difficulty in defining a point in Euclidean geometry?
>
>
>
There is no difficulty and no problem, it's just the way it is defined.
### Meaning
>
> "A point is a mathematical object with no shape and size."
>
>
>
The definition literally means that a point has no "shape and size" (i.e., it occupies no space, it has no body, no interiour, no color, no temperature, no feature, whatever other word you would like). It literally has nothing except the few numbers that define/describe it.
"A point is a mathematical object" means that it exists purely mathematically; there is no physical equivalent to a point. It is a mathematical *object*, which means it is a purely abstract thing which we argue about in the frame of some mathematical system.
For example, in the simple 2-dimensional plane we are used to when discussing these things in a school setting, a combination of two numbers (which also are mathematical objects, not physical). Or in the setting of Euklid, by just reasoning about the relationships between points, lines etc. in an abstract plane without even giving coordinates to them.
### Not a point
As a comparison: what is *not* a point? If you take your pencil and make a little impression on your piece of paper, this is *not* a point. That is a pencil mark, or a circle if you so wish. It has non-mathematical properties, for example the minuscule thickness of the layer of paint you addded to the paper, or the radius of the circle, its color, the type of molecules making it up, etc. etc. Even if you go to the lowest possible scales, i.e., placing a (classical, not quantum-mechanical) atom somewhere with a raster tunnel microscope, that atom will still take up a spherical amount of space and will *not* be a "point".
|
1,886,890 |
In Euclidean geometry texts, it is always mentioned that point is undefined, it can only be described. Consider the following definition: "A point is a mathematical object with no shape and size." I do not understand what is the problem with this definition. Please give the detailed reasons. Thanks in advance!
|
2016/08/09
|
[
"https://math.stackexchange.com/questions/1886890",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/346949/"
] |
I wonder if these texts really want to stress that it is dificult or impossible to define what a point is. I guess they just want to emphasize that they didn't even try, because it is useful to only describe the relations points have with other undefined entities such as lines. That is because if you have a theorem that just uses these axioms and you have some objects that behave like points and the other objects of this axiomatic description, then you can apply that theorem to them, even if they don't look like anything that you would normally consider points and lines etc.
|
### No problem
>
> What is the exact difficulty in defining a point in Euclidean geometry?
>
>
>
There is no difficulty and no problem, it's just the way it is defined.
### Meaning
>
> "A point is a mathematical object with no shape and size."
>
>
>
The definition literally means that a point has no "shape and size" (i.e., it occupies no space, it has no body, no interiour, no color, no temperature, no feature, whatever other word you would like). It literally has nothing except the few numbers that define/describe it.
"A point is a mathematical object" means that it exists purely mathematically; there is no physical equivalent to a point. It is a mathematical *object*, which means it is a purely abstract thing which we argue about in the frame of some mathematical system.
For example, in the simple 2-dimensional plane we are used to when discussing these things in a school setting, a combination of two numbers (which also are mathematical objects, not physical). Or in the setting of Euklid, by just reasoning about the relationships between points, lines etc. in an abstract plane without even giving coordinates to them.
### Not a point
As a comparison: what is *not* a point? If you take your pencil and make a little impression on your piece of paper, this is *not* a point. That is a pencil mark, or a circle if you so wish. It has non-mathematical properties, for example the minuscule thickness of the layer of paint you addded to the paper, or the radius of the circle, its color, the type of molecules making it up, etc. etc. Even if you go to the lowest possible scales, i.e., placing a (classical, not quantum-mechanical) atom somewhere with a raster tunnel microscope, that atom will still take up a spherical amount of space and will *not* be a "point".
|
32,024,707 |
I am editing the following website: <http://ju-jitsu.co.uk/>
I did not set the site up, but have inherited it.
Throughout the website, the basic link colour is PURPLE, and when the mouse hovers, it is red.
And this is fine.
However, on we want to change the colour links on a pages:
<http://ju-jitsu.co.uk/upcoming-events/>
We want to change that to BLACK text, and then when the mouse hovers over, to be red.
My first thought was to do this by css:
`.page-id-5983 a {
color: black;
}`
However this hasn't worked. I've tried changing "black" to "#000000", and have tried inserting into the Style.CSS in the main theme and the child... all with no joy.
So now I've tried the PHP route. I have successfully cloned the default page template, and inserted the modified template page name. This has been uploaded and is being accepted as a valid template file for all pages for the attribute side menu.
I am also successfully able go to the Editor, and select the the page template for editing.
My question is this: what code, and inserted where, is needed to override the default link colours?
If PHP is not the route, and I should pursue CSS, any ideas on the code and where it should be inserted?
Many thanks
|
2015/08/15
|
[
"https://Stackoverflow.com/questions/32024707",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5230149/"
] |
to make sure a page reloads every time you enter it use a
```
$scope.$on('$ionicView.beforeEnter', function(){
//place anything you want to run evertime this view is entered here. for example
//$scope.getData();
//$scope.variable1 = something;
})
```
this will run everything you put inside it before the view is entered. Here is a example of how I use it.
```
$scope.$on('$ionicView.beforeEnter', function () {
$scope.doRefresh();
});
```
and in my doRefresh function:
I grab a bunch of data I need to refresh :
```
$scope.doRefresh = function () {
$scope.setRoles();
$scope.payHistory();
$scope.LoadBoard();
$scope.Blog();
$scope.getHOS();
$scope.getFuelData();
}
};
```
You can check all your logic on refresh and set variables using ng-if or ng-show to display the correct buttons in the menu bar.
look here for more ionicView events: <http://ionicframework.com/docs/api/directive/ionView/>
|
I had my login view also as one of the other views of menutabs. I made it a normal view by changing my uirouter code to
```
.state('login', {
url: "/public",
templateUrl:'templates/public.html',
controller: 'LoginCtrl'
})
```
from
```
.state('app.login', {
url: "/dashboard/login",
views: {
'menuContent': {
templateUrl: "templates/login.html",
controller: 'LoginCtrl'
}
}
})
```
and it solved the problem. I no longer need to reload.
|
8,995,941 |
I want to let tesseract ORC run over an image file, to scan the content.
The problem seems to be that tesseract not only requires TIFF, but it also requires the tiff file to be in a certain format.
With just a normal tiff file, I get:
```
root@toshiba:~/Desktop# tesseract crap.tif crap.txt
Tesseract Open Source OCR Engine
check_legal_image_size:Error:Only 1,2,4,5,6,8 bpp are supported:32
Segmentation fault
```
So far I have managed to find an antidote.
It consists of using GIMP, going to Image > Mode > Indexes, and setting "Generate Optimum Palette", "maximum number of colors" to 256.

then I have to do one more trick before "Save As".
Going to Layer > Transparency > Remove Alpha Channel,
which will remove transparency, because TIF images cannot have transparency.

Now the problem is my input image comes from C#, and is preprocessed with AFORGE.NET image analysis filters.
I have also found a .NET port of LibTiff, and an example of how to write an image with color palette here:
<http://bitmiracle.com/libtiff/help/create-tiff-with-palette-(color-map).aspx>
But I don't know how to get the data from the source tiff (the one with the wrong palette) to the target tiff (with the correct palette format)...
|
2012/01/24
|
[
"https://Stackoverflow.com/questions/8995941",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/155077/"
] |
I think the answer lies in the question, "How often do you need to see the history of a particular record and for what reaason?
If you need this occasionally to research who did what when or for auditing puroposes, the use the audit table approach populated through triggers on each data change. Or use change tracking if it works for you (frankly we don't find it good enough for auditing). Change tracking can also be used successfully to see if a record has been changed since the last data import for instance. Be aware that change tracking data is not permanent unless you physically copy it to another table.
If you need to display the whole history frequently, then keep it all in one table with an active flag that is maintained through triggers. Create a view which has only the active records for the developers to use when they only want to see the most current data. If you are doing this to an existing database that previosuly did not store history, then rename the table and name the view the same teh table orginally had so nothing breaks.
I would also consider using the separate history tables, if I needed the history data for reporting but not rest of the application. For instnce we have this becasue we need to know if the targets the sales reps are talking to are in fact high value targets at the time the contact happened as this calualtion sis part of the how a sales reps performance might be measured. Clearly we need the history but really only once a month or so. So degrading performance daily to keep it in the same table might not be the best solution. This might help keep the reporting time-consuming stuff away from the day-to-day stuff and might in general help performance.
|
Change Tracking:
<http://msdn.microsoft.com/en-us/library/cc305322.aspx>
Or
Change Data Capture: <http://msdn.microsoft.com/en-us/library/cc645937.aspx>
|
16,017 |
How often should I reinflate my tire. My bike has tubeless back tire and tubed front tire. Currently I am reinflating once in a week with 35psi(back) and 25 psi(front).
Should I need to reinflate my front tire everytime when I reinflate back tire ?
|
2015/03/20
|
[
"https://mechanics.stackexchange.com/questions/16017",
"https://mechanics.stackexchange.com",
"https://mechanics.stackexchange.com/users/9841/"
] |
Background
==========
There is no air pressure relationship between the front and rear tire.
Possibility
===========
It may sound coincidence but it appears you have two tires that are leaking.
To troubleshoot the issue, fill the tires to 40+ psi. Have a bucket with soapy water and a rag or sponge handy and cover the surface area of the tires with the soapy water. You will see bubbles in the areas where there are leaks and you can then patch/plug as necessary. Be sure to check the shrader valve for bubbles where it emerges from the rim and for good measure take the valve cap off to see if there is actual leaking from the valve.
Good luck
|
You should fill your tires ***as often as they need filled***. Checking your tires once a week is a good maintenance schedule. If, while doing your checks, you discover one or both are low, add some air to them. If you discover there is a continual loss of pressure, you'll need to get the tires checked for leaks as @DukatiKiller suggests. There is no reason to check just one tire and not the other tire, but as was also stated, there is no correlation between the two tires. Do what you need to do to keep them at the proper pressure for the best ride experience, for piece of mind, and for safety's sake.
|
16,017 |
How often should I reinflate my tire. My bike has tubeless back tire and tubed front tire. Currently I am reinflating once in a week with 35psi(back) and 25 psi(front).
Should I need to reinflate my front tire everytime when I reinflate back tire ?
|
2015/03/20
|
[
"https://mechanics.stackexchange.com/questions/16017",
"https://mechanics.stackexchange.com",
"https://mechanics.stackexchange.com/users/9841/"
] |
Background
==========
There is no air pressure relationship between the front and rear tire.
Possibility
===========
It may sound coincidence but it appears you have two tires that are leaking.
To troubleshoot the issue, fill the tires to 40+ psi. Have a bucket with soapy water and a rag or sponge handy and cover the surface area of the tires with the soapy water. You will see bubbles in the areas where there are leaks and you can then patch/plug as necessary. Be sure to check the shrader valve for bubbles where it emerges from the rim and for good measure take the valve cap off to see if there is actual leaking from the valve.
Good luck
|
No one has mentioned that the schrader valve could be leaking air too. Older valves may have their rubber seals deteriorate over time and leak.
When you do the soapy water test, you might want to try putting some over the schrader valve area as well.
|
16,017 |
How often should I reinflate my tire. My bike has tubeless back tire and tubed front tire. Currently I am reinflating once in a week with 35psi(back) and 25 psi(front).
Should I need to reinflate my front tire everytime when I reinflate back tire ?
|
2015/03/20
|
[
"https://mechanics.stackexchange.com/questions/16017",
"https://mechanics.stackexchange.com",
"https://mechanics.stackexchange.com/users/9841/"
] |
Background
==========
There is no air pressure relationship between the front and rear tire.
Possibility
===========
It may sound coincidence but it appears you have two tires that are leaking.
To troubleshoot the issue, fill the tires to 40+ psi. Have a bucket with soapy water and a rag or sponge handy and cover the surface area of the tires with the soapy water. You will see bubbles in the areas where there are leaks and you can then patch/plug as necessary. Be sure to check the shrader valve for bubbles where it emerges from the rim and for good measure take the valve cap off to see if there is actual leaking from the valve.
Good luck
|
You should check tire pressure every single time you leave home, along with chain tension. If your tires are leaking this much, you should have them replaced. In the meantime, fill them up every time you leave the house. Pro tip: a bicycle pump will work to fill your motorcycle tires, believe it or not. Keep one in the garage so you don't have to stop at a machine.
|
16,017 |
How often should I reinflate my tire. My bike has tubeless back tire and tubed front tire. Currently I am reinflating once in a week with 35psi(back) and 25 psi(front).
Should I need to reinflate my front tire everytime when I reinflate back tire ?
|
2015/03/20
|
[
"https://mechanics.stackexchange.com/questions/16017",
"https://mechanics.stackexchange.com",
"https://mechanics.stackexchange.com/users/9841/"
] |
You should fill your tires ***as often as they need filled***. Checking your tires once a week is a good maintenance schedule. If, while doing your checks, you discover one or both are low, add some air to them. If you discover there is a continual loss of pressure, you'll need to get the tires checked for leaks as @DukatiKiller suggests. There is no reason to check just one tire and not the other tire, but as was also stated, there is no correlation between the two tires. Do what you need to do to keep them at the proper pressure for the best ride experience, for piece of mind, and for safety's sake.
|
No one has mentioned that the schrader valve could be leaking air too. Older valves may have their rubber seals deteriorate over time and leak.
When you do the soapy water test, you might want to try putting some over the schrader valve area as well.
|
16,017 |
How often should I reinflate my tire. My bike has tubeless back tire and tubed front tire. Currently I am reinflating once in a week with 35psi(back) and 25 psi(front).
Should I need to reinflate my front tire everytime when I reinflate back tire ?
|
2015/03/20
|
[
"https://mechanics.stackexchange.com/questions/16017",
"https://mechanics.stackexchange.com",
"https://mechanics.stackexchange.com/users/9841/"
] |
You should fill your tires ***as often as they need filled***. Checking your tires once a week is a good maintenance schedule. If, while doing your checks, you discover one or both are low, add some air to them. If you discover there is a continual loss of pressure, you'll need to get the tires checked for leaks as @DukatiKiller suggests. There is no reason to check just one tire and not the other tire, but as was also stated, there is no correlation between the two tires. Do what you need to do to keep them at the proper pressure for the best ride experience, for piece of mind, and for safety's sake.
|
You should check tire pressure every single time you leave home, along with chain tension. If your tires are leaking this much, you should have them replaced. In the meantime, fill them up every time you leave the house. Pro tip: a bicycle pump will work to fill your motorcycle tires, believe it or not. Keep one in the garage so you don't have to stop at a machine.
|
47,875 |
Say I have a preference that determines whether or not something is visible within an app. Because there are two states (visible or not visible), a checkbox would be the best UI element to use. But how should the text for it be phrased? Should it be phrased positively as an addition, as in:
`Show advanced options` (check means visible, no check means invisible)
or should it be phrased negatively as a removal, as in:
`Hide advanced options` (check means invisible, no check means visible)
Because consistency is desirable, it seems to me that there are four possibilities:
1. Always use the positive statement
2. Always use the negative statement
3. Always use the statement where the default is checked
4. Always use the statement where the default is unchecked.
What is the best way to do this?
|
2013/11/10
|
[
"https://ux.stackexchange.com/questions/47875",
"https://ux.stackexchange.com",
"https://ux.stackexchange.com/users/27666/"
] |
I'd prefer the option you called "positive statement". The reason isn't only consistency. The other reasons are:
* Positive statement style is a great way to introduce the functionality of the application. So config dialog could partially play the role of software help and documentation. It tells to a user like: "I can do this, and this, and this...". The probability of running and exploring config dialog could be higher comparing to running help and support.
* In novice users' mental model adding new features (`Show advanced options`) could be perceived less risky, than removing ones (`Hide advanced options`). As removing could be interpreted as cutting down the software functionality which could lead to some restrictions in software, or breaking it, or, at least, changing the familiar way of interaction, while adding ones (positive statement) could be perceived as increasing current functionality and feeling masterity over it. See image below.

An example of displaying preferences which are positive is Total Commander config dialog:

Though it's a general recommendation, as a context and some user-centered activities could bring some insights for the labeling task.
|
An alternative would be to offer two radio buttons rather than a checkbox, with both versions given. Gmail gives an example of this in use:

Or, as per Apple, giving a custom button UI that specifies the active state through the button, rather than through the label (in this case, they seem to be using the default option as the label text):

|
47,875 |
Say I have a preference that determines whether or not something is visible within an app. Because there are two states (visible or not visible), a checkbox would be the best UI element to use. But how should the text for it be phrased? Should it be phrased positively as an addition, as in:
`Show advanced options` (check means visible, no check means invisible)
or should it be phrased negatively as a removal, as in:
`Hide advanced options` (check means invisible, no check means visible)
Because consistency is desirable, it seems to me that there are four possibilities:
1. Always use the positive statement
2. Always use the negative statement
3. Always use the statement where the default is checked
4. Always use the statement where the default is unchecked.
What is the best way to do this?
|
2013/11/10
|
[
"https://ux.stackexchange.com/questions/47875",
"https://ux.stackexchange.com",
"https://ux.stackexchange.com/users/27666/"
] |
An alternative would be to offer two radio buttons rather than a checkbox, with both versions given. Gmail gives an example of this in use:

Or, as per Apple, giving a custom button UI that specifies the active state through the button, rather than through the label (in this case, they seem to be using the default option as the label text):

|
Positive sentence is preferable.
It is a base concept of mind mapping that is explain by a clearing process in our mind.
When you read a negative message our unconscious clear the sentence to retain the more important information.
For example if you want to stop smoking cigarettes it is sure unsuccessful to think "I don't want to smoke anymore".because our mind retains "want to smoke".
An other example is when someone you know dead the first time our thoughts are negative when we see the body of this person without live.but rapidly our mind clear this negative view to think about food things we shared with this person because it is better for our mind to think positive.
It is better to have objective like doing sport and so the reason why you have to stop smoking.
When you write unpositive sentence our mind works hard to translate it in positive version.
So with positive version no need to translate.
|
47,875 |
Say I have a preference that determines whether or not something is visible within an app. Because there are two states (visible or not visible), a checkbox would be the best UI element to use. But how should the text for it be phrased? Should it be phrased positively as an addition, as in:
`Show advanced options` (check means visible, no check means invisible)
or should it be phrased negatively as a removal, as in:
`Hide advanced options` (check means invisible, no check means visible)
Because consistency is desirable, it seems to me that there are four possibilities:
1. Always use the positive statement
2. Always use the negative statement
3. Always use the statement where the default is checked
4. Always use the statement where the default is unchecked.
What is the best way to do this?
|
2013/11/10
|
[
"https://ux.stackexchange.com/questions/47875",
"https://ux.stackexchange.com",
"https://ux.stackexchange.com/users/27666/"
] |
I'd prefer the option you called "positive statement". The reason isn't only consistency. The other reasons are:
* Positive statement style is a great way to introduce the functionality of the application. So config dialog could partially play the role of software help and documentation. It tells to a user like: "I can do this, and this, and this...". The probability of running and exploring config dialog could be higher comparing to running help and support.
* In novice users' mental model adding new features (`Show advanced options`) could be perceived less risky, than removing ones (`Hide advanced options`). As removing could be interpreted as cutting down the software functionality which could lead to some restrictions in software, or breaking it, or, at least, changing the familiar way of interaction, while adding ones (positive statement) could be perceived as increasing current functionality and feeling masterity over it. See image below.

An example of displaying preferences which are positive is Total Commander config dialog:

Though it's a general recommendation, as a context and some user-centered activities could bring some insights for the labeling task.
|
Positive sentence is preferable.
It is a base concept of mind mapping that is explain by a clearing process in our mind.
When you read a negative message our unconscious clear the sentence to retain the more important information.
For example if you want to stop smoking cigarettes it is sure unsuccessful to think "I don't want to smoke anymore".because our mind retains "want to smoke".
An other example is when someone you know dead the first time our thoughts are negative when we see the body of this person without live.but rapidly our mind clear this negative view to think about food things we shared with this person because it is better for our mind to think positive.
It is better to have objective like doing sport and so the reason why you have to stop smoking.
When you write unpositive sentence our mind works hard to translate it in positive version.
So with positive version no need to translate.
|
59,450,418 |
I am building a food cart application and have a query on the menu item page.
My menu items page consists of a list view, which shows each item with description along with an option to specify the quantity of items( 1, 2, 3....)
Now I am able to increment or decrement item count for a single item, but not sure how to do that in a list view at a particular index where the user clicks.
Could some one please help me on this?
The code which I have done till now is as below :
```
FutureBuilder(
future: getItemList(),
builder: (context, snapshot) {
if (!snapshot.hasData) {
return CircularProgressIndicator();
}
var itemList = snapshot.data;
int itemlength = itemList.length;
return ListView.builder(
scrollDirection: Axis.vertical,
shrinkWrap: true,
itemBuilder: (BuildContext context, int index) {
return Container(
height: 100,
margin: EdgeInsets.only(left: 10, right: 10, top: 10),
decoration: BoxDecoration(
color: Colors.white70,
border: Border.all(width: 2.0, color: Colors.blueGrey),
borderRadius: BorderRadius.circular(6.0),
boxShadow: [
BoxShadow(
color: Color(0xFF6078ea).withOpacity(.3),
offset: Offset(0.0, 8.0),
blurRadius: 8.0),
],
),
child: Row(
children: < Widget > [
Container(
width: 75,
child: ClipRRect(
borderRadius: new BorderRadius.circular(10.0),
child: Image(
image: AssetImage(
'assets/images/loginbg3.jpg'),
fit: BoxFit.cover,
),
),
margin: EdgeInsets.only(left: 10),
),
Expanded(
child: Container(
child: Column(
children: < Widget > [
Row(
children: < Widget > [
Expanded(child: Container(margin: EdgeInsets.only(left: 10, top: 15, bottom: 5), child: Text(itemList[index]['itemname'], style: kClickableTextStyle, ))),
Container(color: Colors.white, width: 25, margin: EdgeInsets.only(left: 10, top: 15, bottom: 5), child: Image.asset(_itemtype)),
],
),
Row(
children: < Widget > [
Container(margin: EdgeInsets.only(left: 10, top: 15, bottom: 5), child: Text('Price : ', style: kListTitleTextStyle, )),
Container(margin: EdgeInsets.only(left: 10, top: 15, bottom: 5), child: Text(numberofitems.toString() + ' \u20B9 ', style: kListTitleTextStyle, )),
],
),
],
),
),
),
Container(
margin: EdgeInsets.only(left: 10),
child: Row(
children: < Widget > [
InkWell(
onTap: onClickDelete,
child: Container(
width: 30, child: Icon(
Icons.remove_circle_outline,
color: Colors.green,
size: 30,
), ),
),
Container(
width: 30,
child: Center(child: Text(_count.toString(), style: TextStyle(fontSize: 25), )),
),
InkWell(
onTap: onClickAdd,
child: Container(
margin: EdgeInsets.only(right: 5),
width: 30, child: Icon(
Icons.add_circle_outline,
color: Colors.green,
size: 30,
), ),
),
],
),
),
],
),
);
},
itemCount: itemList == null ? 0 : itemList.length,
);
})
```
|
2019/12/23
|
[
"https://Stackoverflow.com/questions/59450418",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3977271/"
] |
you need to create list of objects for your Item like.
```
class Item{
String name;
String description;
int quantity;
double price;
}
```
and on tap of item, get index of clicked item with new incremented/decremented value and update your list of objects inside setState().
|
You need to wrap your itemBuilder item, i.e the Container with a [GestureDetector](https://api.flutter.dev/flutter/widgets/GestureDetector-class.html) and then call the `onTap()` method inside that detector.
Before that, you'll have to convert your item into a stateful widget with a variable to maintain the count of quantity.
|
59,450,418 |
I am building a food cart application and have a query on the menu item page.
My menu items page consists of a list view, which shows each item with description along with an option to specify the quantity of items( 1, 2, 3....)
Now I am able to increment or decrement item count for a single item, but not sure how to do that in a list view at a particular index where the user clicks.
Could some one please help me on this?
The code which I have done till now is as below :
```
FutureBuilder(
future: getItemList(),
builder: (context, snapshot) {
if (!snapshot.hasData) {
return CircularProgressIndicator();
}
var itemList = snapshot.data;
int itemlength = itemList.length;
return ListView.builder(
scrollDirection: Axis.vertical,
shrinkWrap: true,
itemBuilder: (BuildContext context, int index) {
return Container(
height: 100,
margin: EdgeInsets.only(left: 10, right: 10, top: 10),
decoration: BoxDecoration(
color: Colors.white70,
border: Border.all(width: 2.0, color: Colors.blueGrey),
borderRadius: BorderRadius.circular(6.0),
boxShadow: [
BoxShadow(
color: Color(0xFF6078ea).withOpacity(.3),
offset: Offset(0.0, 8.0),
blurRadius: 8.0),
],
),
child: Row(
children: < Widget > [
Container(
width: 75,
child: ClipRRect(
borderRadius: new BorderRadius.circular(10.0),
child: Image(
image: AssetImage(
'assets/images/loginbg3.jpg'),
fit: BoxFit.cover,
),
),
margin: EdgeInsets.only(left: 10),
),
Expanded(
child: Container(
child: Column(
children: < Widget > [
Row(
children: < Widget > [
Expanded(child: Container(margin: EdgeInsets.only(left: 10, top: 15, bottom: 5), child: Text(itemList[index]['itemname'], style: kClickableTextStyle, ))),
Container(color: Colors.white, width: 25, margin: EdgeInsets.only(left: 10, top: 15, bottom: 5), child: Image.asset(_itemtype)),
],
),
Row(
children: < Widget > [
Container(margin: EdgeInsets.only(left: 10, top: 15, bottom: 5), child: Text('Price : ', style: kListTitleTextStyle, )),
Container(margin: EdgeInsets.only(left: 10, top: 15, bottom: 5), child: Text(numberofitems.toString() + ' \u20B9 ', style: kListTitleTextStyle, )),
],
),
],
),
),
),
Container(
margin: EdgeInsets.only(left: 10),
child: Row(
children: < Widget > [
InkWell(
onTap: onClickDelete,
child: Container(
width: 30, child: Icon(
Icons.remove_circle_outline,
color: Colors.green,
size: 30,
), ),
),
Container(
width: 30,
child: Center(child: Text(_count.toString(), style: TextStyle(fontSize: 25), )),
),
InkWell(
onTap: onClickAdd,
child: Container(
margin: EdgeInsets.only(right: 5),
width: 30, child: Icon(
Icons.add_circle_outline,
color: Colors.green,
size: 30,
), ),
),
],
),
),
],
),
);
},
itemCount: itemList == null ? 0 : itemList.length,
);
})
```
|
2019/12/23
|
[
"https://Stackoverflow.com/questions/59450418",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3977271/"
] |
You can copy paste run full code below
Step 1: create Item class
Step 2: change future builder call
Step 3: deal with Inkwell onTap
working demo
[](https://i.stack.imgur.com/Zopd1.gif)
code snippet
```
Future callback;
@override
void initState() {
callback = _getItemList();
super.initState();
}
@override
Widget build(BuildContext context) {
var futureBuilder = FutureBuilder(
future: callback,
...
InkWell(
onTap: () {
if (itemList[index].numberofitems > 0) {
setState(() {
itemList[index].numberofitems =
itemList[index].numberofitems - 1;
});
}
},
...
InkWell(
onTap: () {
setState(() {
itemList[index].numberofitems =
itemList[index].numberofitems + 1;
print(
' ${itemList[index].itemname.toString()} ${itemList[index].numberofitems.toString()}');
});
},
```
full code
```
import 'dart:async';
import 'dart:collection';
import 'package:flutter/material.dart';
void main() => runApp( MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: MyHomePage(),
);
}
}
class Item {
String itemname;
String itemtype;
int numberofitems;
Item({this.itemname, this.itemtype, this.numberofitems});
}
class MyHomePage extends StatefulWidget {
@override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
Future callback;
@override
void initState() {
callback = _getItemList();
super.initState();
}
@override
Widget build(BuildContext context) {
var futureBuilder = FutureBuilder(
future: callback,
builder: (BuildContext context, AsyncSnapshot snapshot) {
switch (snapshot.connectionState) {
case ConnectionState.none:
case ConnectionState.waiting:
return Center(child: CircularProgressIndicator());
default:
if (snapshot.hasError)
return Text('Error: ${snapshot.error}');
else
return createListView(context, snapshot);
}
},
);
return Scaffold(
appBar: AppBar(
title: Text("Home Page"),
),
body: futureBuilder,
);
}
Future<List<Item>> _getItemList() async {
var values = List<Item>();
values.add(
Item(itemname: "A", itemtype: "assets/images/a.jpg", numberofitems: 0));
values.add(
Item(itemname: "B", itemtype: "assets/images/a.jpg", numberofitems: 1));
values.add(
Item(itemname: "C", itemtype: "assets/images/a.jpg", numberofitems: 2));
//throw Exception("Danger Will Robinson!!!");
await Future.delayed( Duration(seconds: 2));
return values;
}
Widget createListView(BuildContext context, AsyncSnapshot snapshot) {
List<Item> itemList = snapshot.data;
return ListView.builder(
itemCount: itemList.length,
itemBuilder: (BuildContext context, int index) {
{
return Container(
height: 100,
margin: EdgeInsets.only(left: 10, right: 10, top: 10),
decoration: BoxDecoration(
color: Colors.white70,
border: Border.all(width: 2.0, color: Colors.blueGrey),
borderRadius: BorderRadius.circular(6.0),
boxShadow: [
BoxShadow(
color: Color(0xFF6078ea).withOpacity(.3),
offset: Offset(0.0, 8.0),
blurRadius: 8.0),
],
),
child: Row(
children: <Widget>[
Container(
width: 75,
child: ClipRRect(
borderRadius: BorderRadius.circular(10.0),
child: Image(
image: AssetImage('assets/images/a.jpg'),
fit: BoxFit.cover,
),
),
margin: EdgeInsets.only(left: 10),
),
Expanded(
child: Container(
child: Column(
children: <Widget>[
Row(
children: <Widget>[
Expanded(
child: Container(
margin: EdgeInsets.only(
left: 10, top: 15, bottom: 5),
child: Text(
itemList[index].itemname,
))),
Container(
color: Colors.white,
width: 25,
margin: EdgeInsets.only(
left: 10, top: 15, bottom: 5),
child: Image.asset(itemList[index].itemtype)),
],
),
Row(
children: <Widget>[
Container(
margin: EdgeInsets.only(
left: 10, top: 15, bottom: 5),
child: Text(
'Price : ',
)),
Container(
margin: EdgeInsets.only(
left: 10, top: 15, bottom: 5),
child: Text(
itemList[index].numberofitems.toString() +
' \u20B9 ',
)),
],
),
],
),
),
),
Container(
margin: EdgeInsets.only(left: 10),
child: Row(
children: <Widget>[
InkWell(
onTap: () {
if (itemList[index].numberofitems > 0) {
setState(() {
itemList[index].numberofitems =
itemList[index].numberofitems - 1;
});
}
},
child: Container(
width: 30,
child: Icon(
Icons.remove_circle_outline,
color: Colors.green,
size: 30,
),
),
),
Container(
width: 30,
child: Center(
child: Text(
itemList[index].numberofitems.toString(),
style: TextStyle(fontSize: 25),
)),
),
InkWell(
onTap: () {
setState(() {
itemList[index].numberofitems =
itemList[index].numberofitems + 1;
print(
' ${itemList[index].itemname.toString()} ${itemList[index].numberofitems.toString()}');
});
},
child: Container(
margin: EdgeInsets.only(right: 5),
width: 30,
child: Icon(
Icons.add_circle_outline,
color: Colors.green,
size: 30,
),
),
),
],
),
),
],
),
);
}
;
});
}
}
```
|
You need to wrap your itemBuilder item, i.e the Container with a [GestureDetector](https://api.flutter.dev/flutter/widgets/GestureDetector-class.html) and then call the `onTap()` method inside that detector.
Before that, you'll have to convert your item into a stateful widget with a variable to maintain the count of quantity.
|
59,450,418 |
I am building a food cart application and have a query on the menu item page.
My menu items page consists of a list view, which shows each item with description along with an option to specify the quantity of items( 1, 2, 3....)
Now I am able to increment or decrement item count for a single item, but not sure how to do that in a list view at a particular index where the user clicks.
Could some one please help me on this?
The code which I have done till now is as below :
```
FutureBuilder(
future: getItemList(),
builder: (context, snapshot) {
if (!snapshot.hasData) {
return CircularProgressIndicator();
}
var itemList = snapshot.data;
int itemlength = itemList.length;
return ListView.builder(
scrollDirection: Axis.vertical,
shrinkWrap: true,
itemBuilder: (BuildContext context, int index) {
return Container(
height: 100,
margin: EdgeInsets.only(left: 10, right: 10, top: 10),
decoration: BoxDecoration(
color: Colors.white70,
border: Border.all(width: 2.0, color: Colors.blueGrey),
borderRadius: BorderRadius.circular(6.0),
boxShadow: [
BoxShadow(
color: Color(0xFF6078ea).withOpacity(.3),
offset: Offset(0.0, 8.0),
blurRadius: 8.0),
],
),
child: Row(
children: < Widget > [
Container(
width: 75,
child: ClipRRect(
borderRadius: new BorderRadius.circular(10.0),
child: Image(
image: AssetImage(
'assets/images/loginbg3.jpg'),
fit: BoxFit.cover,
),
),
margin: EdgeInsets.only(left: 10),
),
Expanded(
child: Container(
child: Column(
children: < Widget > [
Row(
children: < Widget > [
Expanded(child: Container(margin: EdgeInsets.only(left: 10, top: 15, bottom: 5), child: Text(itemList[index]['itemname'], style: kClickableTextStyle, ))),
Container(color: Colors.white, width: 25, margin: EdgeInsets.only(left: 10, top: 15, bottom: 5), child: Image.asset(_itemtype)),
],
),
Row(
children: < Widget > [
Container(margin: EdgeInsets.only(left: 10, top: 15, bottom: 5), child: Text('Price : ', style: kListTitleTextStyle, )),
Container(margin: EdgeInsets.only(left: 10, top: 15, bottom: 5), child: Text(numberofitems.toString() + ' \u20B9 ', style: kListTitleTextStyle, )),
],
),
],
),
),
),
Container(
margin: EdgeInsets.only(left: 10),
child: Row(
children: < Widget > [
InkWell(
onTap: onClickDelete,
child: Container(
width: 30, child: Icon(
Icons.remove_circle_outline,
color: Colors.green,
size: 30,
), ),
),
Container(
width: 30,
child: Center(child: Text(_count.toString(), style: TextStyle(fontSize: 25), )),
),
InkWell(
onTap: onClickAdd,
child: Container(
margin: EdgeInsets.only(right: 5),
width: 30, child: Icon(
Icons.add_circle_outline,
color: Colors.green,
size: 30,
), ),
),
],
),
),
],
),
);
},
itemCount: itemList == null ? 0 : itemList.length,
);
})
```
|
2019/12/23
|
[
"https://Stackoverflow.com/questions/59450418",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3977271/"
] |
You can copy paste run full code below
Step 1: create Item class
Step 2: change future builder call
Step 3: deal with Inkwell onTap
working demo
[](https://i.stack.imgur.com/Zopd1.gif)
code snippet
```
Future callback;
@override
void initState() {
callback = _getItemList();
super.initState();
}
@override
Widget build(BuildContext context) {
var futureBuilder = FutureBuilder(
future: callback,
...
InkWell(
onTap: () {
if (itemList[index].numberofitems > 0) {
setState(() {
itemList[index].numberofitems =
itemList[index].numberofitems - 1;
});
}
},
...
InkWell(
onTap: () {
setState(() {
itemList[index].numberofitems =
itemList[index].numberofitems + 1;
print(
' ${itemList[index].itemname.toString()} ${itemList[index].numberofitems.toString()}');
});
},
```
full code
```
import 'dart:async';
import 'dart:collection';
import 'package:flutter/material.dart';
void main() => runApp( MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: MyHomePage(),
);
}
}
class Item {
String itemname;
String itemtype;
int numberofitems;
Item({this.itemname, this.itemtype, this.numberofitems});
}
class MyHomePage extends StatefulWidget {
@override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
Future callback;
@override
void initState() {
callback = _getItemList();
super.initState();
}
@override
Widget build(BuildContext context) {
var futureBuilder = FutureBuilder(
future: callback,
builder: (BuildContext context, AsyncSnapshot snapshot) {
switch (snapshot.connectionState) {
case ConnectionState.none:
case ConnectionState.waiting:
return Center(child: CircularProgressIndicator());
default:
if (snapshot.hasError)
return Text('Error: ${snapshot.error}');
else
return createListView(context, snapshot);
}
},
);
return Scaffold(
appBar: AppBar(
title: Text("Home Page"),
),
body: futureBuilder,
);
}
Future<List<Item>> _getItemList() async {
var values = List<Item>();
values.add(
Item(itemname: "A", itemtype: "assets/images/a.jpg", numberofitems: 0));
values.add(
Item(itemname: "B", itemtype: "assets/images/a.jpg", numberofitems: 1));
values.add(
Item(itemname: "C", itemtype: "assets/images/a.jpg", numberofitems: 2));
//throw Exception("Danger Will Robinson!!!");
await Future.delayed( Duration(seconds: 2));
return values;
}
Widget createListView(BuildContext context, AsyncSnapshot snapshot) {
List<Item> itemList = snapshot.data;
return ListView.builder(
itemCount: itemList.length,
itemBuilder: (BuildContext context, int index) {
{
return Container(
height: 100,
margin: EdgeInsets.only(left: 10, right: 10, top: 10),
decoration: BoxDecoration(
color: Colors.white70,
border: Border.all(width: 2.0, color: Colors.blueGrey),
borderRadius: BorderRadius.circular(6.0),
boxShadow: [
BoxShadow(
color: Color(0xFF6078ea).withOpacity(.3),
offset: Offset(0.0, 8.0),
blurRadius: 8.0),
],
),
child: Row(
children: <Widget>[
Container(
width: 75,
child: ClipRRect(
borderRadius: BorderRadius.circular(10.0),
child: Image(
image: AssetImage('assets/images/a.jpg'),
fit: BoxFit.cover,
),
),
margin: EdgeInsets.only(left: 10),
),
Expanded(
child: Container(
child: Column(
children: <Widget>[
Row(
children: <Widget>[
Expanded(
child: Container(
margin: EdgeInsets.only(
left: 10, top: 15, bottom: 5),
child: Text(
itemList[index].itemname,
))),
Container(
color: Colors.white,
width: 25,
margin: EdgeInsets.only(
left: 10, top: 15, bottom: 5),
child: Image.asset(itemList[index].itemtype)),
],
),
Row(
children: <Widget>[
Container(
margin: EdgeInsets.only(
left: 10, top: 15, bottom: 5),
child: Text(
'Price : ',
)),
Container(
margin: EdgeInsets.only(
left: 10, top: 15, bottom: 5),
child: Text(
itemList[index].numberofitems.toString() +
' \u20B9 ',
)),
],
),
],
),
),
),
Container(
margin: EdgeInsets.only(left: 10),
child: Row(
children: <Widget>[
InkWell(
onTap: () {
if (itemList[index].numberofitems > 0) {
setState(() {
itemList[index].numberofitems =
itemList[index].numberofitems - 1;
});
}
},
child: Container(
width: 30,
child: Icon(
Icons.remove_circle_outline,
color: Colors.green,
size: 30,
),
),
),
Container(
width: 30,
child: Center(
child: Text(
itemList[index].numberofitems.toString(),
style: TextStyle(fontSize: 25),
)),
),
InkWell(
onTap: () {
setState(() {
itemList[index].numberofitems =
itemList[index].numberofitems + 1;
print(
' ${itemList[index].itemname.toString()} ${itemList[index].numberofitems.toString()}');
});
},
child: Container(
margin: EdgeInsets.only(right: 5),
width: 30,
child: Icon(
Icons.add_circle_outline,
color: Colors.green,
size: 30,
),
),
),
],
),
),
],
),
);
}
;
});
}
}
```
|
you need to create list of objects for your Item like.
```
class Item{
String name;
String description;
int quantity;
double price;
}
```
and on tap of item, get index of clicked item with new incremented/decremented value and update your list of objects inside setState().
|
846,772 |
How to do an update in LINQ to Objects. Trying convert SQL to Linq
```
Quality
(
TransactionID int,
Quantity float,
MaterialID int,
ProductID int,
ParameterID int,
ParameterValue float,
TotalTonnes float
)
```
How to convert below SQL to linq:
```
UPDATE Q1
SET TotalTonnes = ( SELECT SUM(Quantity)
FROM @Quality Q2
WHERE Q1.ParameterID = Q2.ParameterID
AND ( ( Q1.MaterialID = Q2.MaterialID )
OR ( Q1.MaterialID IS NULL
AND Q2.MaterialID IS NULL
)
)
AND ( ( Q1.ProductID = Q2.ProductID )
OR ( Q1.ProductID IS NULL
AND Q2.ProductID IS NULL
)
)
)
FROM @Quality Q1
```
Thanks
|
2009/05/11
|
[
"https://Stackoverflow.com/questions/846772",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/85952/"
] |
Well, I would do updates imperatively. Something like this:
```
foreach (var q1 in Q1)
{
q1.TotalTonnes = (from q2 in Q2
where q1.ParameterID == q2.ParameterID
&& q1.MaterialID == q2.MaterialID
&& q1.ProductID == q2.ProductID
select q2.Quantity).Sum();
}
```
Note that the double null checks aren't required because of the way null comparisons are handled in C#. (i.e. `(null == null)` is true)
|
For better performance and what I think is cleaner code you can use the ToLookUp method. If Q2 is large this will be much better performance as there is no nested loops.
```
var Q2LookUp =
Q2.ToLookUp(q2 => new {q2.ParameterId, q2.MaterialID, q2.ProductId});
foreach (var q1 in Q1)
{
q1.TotalTonnes =
Q2Lookup[new {q1.ParameterId, q1.MaterialID, q1.ProductId}]
.Sum(q2 => q2.Quantity);
}
```
|
58,236,691 |
I have an assignment where I have to use dictionaries to make a "phone book".
I have already tried rewatching the video and trial and error for about an hour with no change.
My code:
```py
phone_book = {}
while True:
name = input("Enter a name: ")
if name in phone_book:
print(phone_book[name])
elif name == "":
break
else:
phone_number = input("Enter a phone number in the following format[(123)456-7890)]: ")
phone_book[name] = phone_number
print(phone_book)
```
The check code for assignment requirements says:
1. You should print the final dictionary. Make sure you print out the dictionary directly(don't iterate through it)
expected result:
```py
Phone number: 1234
Phone number: 5678
{'Tracy': '5678', 'Karel': '1234', 'Steve': '9999'}
```
my result:
```py
{'Karel': '1234'}
{'Tracy': '5678', 'Karel': '1234'}
{'Tracy': '5678', 'Karel': '1234', 'Steve': '9999'}
1234
{'Tracy': '5678', 'Karel': '1234', 'Steve': '9999'}
5678
{'Tracy': '5678', 'Karel': '1234', 'Steve': '9999'}
```
2. You should print the phone number for names who already exist in the dictionary
your result:
```py
{'Karel': '1234'}
{'Tracy': '5678', 'Karel': '1234'}
{'Tracy': '5678', 'Karel': '1234', 'Steve': '9999'}
1234
{'Tracy': '5678', 'Karel': '1234', 'Steve': '9999'}
5678
{'Tracy': '5678', 'Karel': '1234', 'Steve': '9999'}
```
|
2019/10/04
|
[
"https://Stackoverflow.com/questions/58236691",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
You can use dynamic sql
```
declare @sql nvarchar(1000) = '';
declare @col_list nvarchar(100) = '';
;with
n as (
select tc.name, tc.column_id
from sys.indexes i
join sys.index_columns ic on i.object_id = ic.object_id and i.index_id = ic.index_id
join sys.columns tc on i.object_id = tc.object_id and tc.column_id = ic.column_id
where i.object_id = OBJECT_ID('table_a')
and i.is_primary_key = 1
)
select @col_list = substring((select ', ' + CAST(quotename(name) AS NVARCHAR(128)) [*]
from n
order by column_id
for xml path('')), 2, 9999)
set @sql = 'select ' + @col_list + ' into ##table_temp from table_a where 1=0'
print @sql;
exec sp_executesql @sql
select * from ##table_temp
```
|
Yes, that is possible. The temp table doesn't care if the value you're feeding him is a primary key on your table of origin.
**EDIT:**
To answer your edited in question:
```
create table #temptable
(
column1values datatype,
column4values datatype
)
insert into #temptable
select column1, column4 from a
```
|
58,236,691 |
I have an assignment where I have to use dictionaries to make a "phone book".
I have already tried rewatching the video and trial and error for about an hour with no change.
My code:
```py
phone_book = {}
while True:
name = input("Enter a name: ")
if name in phone_book:
print(phone_book[name])
elif name == "":
break
else:
phone_number = input("Enter a phone number in the following format[(123)456-7890)]: ")
phone_book[name] = phone_number
print(phone_book)
```
The check code for assignment requirements says:
1. You should print the final dictionary. Make sure you print out the dictionary directly(don't iterate through it)
expected result:
```py
Phone number: 1234
Phone number: 5678
{'Tracy': '5678', 'Karel': '1234', 'Steve': '9999'}
```
my result:
```py
{'Karel': '1234'}
{'Tracy': '5678', 'Karel': '1234'}
{'Tracy': '5678', 'Karel': '1234', 'Steve': '9999'}
1234
{'Tracy': '5678', 'Karel': '1234', 'Steve': '9999'}
5678
{'Tracy': '5678', 'Karel': '1234', 'Steve': '9999'}
```
2. You should print the phone number for names who already exist in the dictionary
your result:
```py
{'Karel': '1234'}
{'Tracy': '5678', 'Karel': '1234'}
{'Tracy': '5678', 'Karel': '1234', 'Steve': '9999'}
1234
{'Tracy': '5678', 'Karel': '1234', 'Steve': '9999'}
5678
{'Tracy': '5678', 'Karel': '1234', 'Steve': '9999'}
```
|
2019/10/04
|
[
"https://Stackoverflow.com/questions/58236691",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
You can use dynamic sql
```
declare @sql nvarchar(1000) = '';
declare @col_list nvarchar(100) = '';
;with
n as (
select tc.name, tc.column_id
from sys.indexes i
join sys.index_columns ic on i.object_id = ic.object_id and i.index_id = ic.index_id
join sys.columns tc on i.object_id = tc.object_id and tc.column_id = ic.column_id
where i.object_id = OBJECT_ID('table_a')
and i.is_primary_key = 1
)
select @col_list = substring((select ', ' + CAST(quotename(name) AS NVARCHAR(128)) [*]
from n
order by column_id
for xml path('')), 2, 9999)
set @sql = 'select ' + @col_list + ' into ##table_temp from table_a where 1=0'
print @sql;
exec sp_executesql @sql
select * from ##table_temp
```
|
The following code will help you but **sp\_executesql** statment create the temp table in the other session for this reason you can use global temp table.
```
DROP TABLE IF EXISTS ##Test
DECLARE @tbl_query as NVARCHAR(MAX) = 'CREATE TABLE ##Test ( '
DECLARE
@tablecol VARCHAR(300),
@tablettype VARCHAR(300) ,
@typelengt VARCHAR(300)
DECLARE cursor_product CURSOR
FOR sELECT
c.name 'Column Name',
t.Name 'Data type' ,
IIF(t.name = 'nvarchar', c.max_length / 2, c.max_length)
FROM
sys.columns c
INNER JOIN
sys.types t ON c.user_type_id = t.user_type_id
LEFT OUTER JOIN
sys.index_columns ic ON ic.object_id = c.object_id AND ic.column_id = c.column_id
LEFT OUTER JOIN
sys.indexes i ON ic.object_id = i.object_id AND ic.index_id = i.index_id
WHERE
c.object_id = OBJECT_ID('your_table_name')
and ISNULL(i.is_primary_key, 0)=1
OPEN cursor_product;
FETCH NEXT FROM cursor_product INTO
@tablecol,
@tablettype,
@typelengt
WHILE @@FETCH_STATUS = 0
BEGIN
IF @tablettype LIKE '%varchar%'
BEGIN
SET @typelengt = '(' + @typelengt + ')'
END
ELSE
BEGIN
SET @typelengt=''
END
set @tbl_query = @tbl_query + @tablecol + ' ' + @tablettype + @typelengt + ' , '
FETCH NEXT FROM cursor_product INTO
@tablecol,
@tablettype,
@typelengt
END;
CLOSE cursor_product;
DEALLOCATE cursor_product;
SET @tbl_query = SUBSTRING(@tbl_query,1,LEN(@tbl_query)-1)
SET @tbl_query = @tbl_query + ' )'
PRINT @tbl_query
EXEC sp_executesql @tbl_query
```
|
3,227,624 |
**Simple case**
I have a Python program that I intend to support on both \*nix and Windows systems. The program must be configurable, at least globally. Is there a cross-platform way to address the configuration file?
I.e. I want to write instead of
```
import platform
if platform.system() == "Windows":
configFilePath = "C:\MyProgram\mainconfig.ini"
else:
configFilePath = "/etc/myprogram/mainconfig.ini"
```
something along the lines of
```
import configmagic
configFile = configmagic("myprogram", "mainconfig")
```
**A slightly more advanced case**
Can the same be applied to user-specific configuration? I.e. to keep the configuration in `~user/.myprogram/` under Unix, and in `HKEY_LOCAL_USER` registry section under Windows?
|
2010/07/12
|
[
"https://Stackoverflow.com/questions/3227624",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/27122/"
] |
Python will allow forward-slash paths on Windows, and `os.path.expanduser` works on Windows also, so you can get a user-specific file path using:
```
config_file = os.path.expanduser("~/foo.ini")
```
if you want to find a .ini in the user's home directory. I'm not sure how to unify file-based .ini and registry settings.
|
You may want to use `dirspec`. It works in GNU/Linux, Mac OS and Windows.
You can get it from: [Launchpad](https://launchpad.net/dirspec/ "launchpad")
Or installing it from [PyPI](https://pypi.python.org/pypi/dirspec/ "PyPI")
```
pip install dirspec
```
and in your code use something like:
```
from dirspec.basedir import get_xdg_config_home
config_path = get_xdg_config_home()
```
It's used by Ubuntu One, look at this code example from their documentation: <https://one.ubuntu.com/developer/data/u1db/tutorial#storing-and-retrieving-tasks>
|
3,227,624 |
**Simple case**
I have a Python program that I intend to support on both \*nix and Windows systems. The program must be configurable, at least globally. Is there a cross-platform way to address the configuration file?
I.e. I want to write instead of
```
import platform
if platform.system() == "Windows":
configFilePath = "C:\MyProgram\mainconfig.ini"
else:
configFilePath = "/etc/myprogram/mainconfig.ini"
```
something along the lines of
```
import configmagic
configFile = configmagic("myprogram", "mainconfig")
```
**A slightly more advanced case**
Can the same be applied to user-specific configuration? I.e. to keep the configuration in `~user/.myprogram/` under Unix, and in `HKEY_LOCAL_USER` registry section under Windows?
|
2010/07/12
|
[
"https://Stackoverflow.com/questions/3227624",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/27122/"
] |
Python will allow forward-slash paths on Windows, and `os.path.expanduser` works on Windows also, so you can get a user-specific file path using:
```
config_file = os.path.expanduser("~/foo.ini")
```
if you want to find a .ini in the user's home directory. I'm not sure how to unify file-based .ini and registry settings.
|
Current answers provide incomplete solution to your problems (cross-platform + user vs system-wide config).
[confuse library](https://github.com/beetbox/confuse) answers your needs :
>
> Combine configuration data from multiple sources. Using layering,
> Confuse allows user-specific configuration to seamlessly override
> system-wide configuration, which in turn overrides built-in defaults.
>
> [...]
>
> An in-package config\_default.yaml can be used to provide bottom-layer
> defaults using the same syntax that users will see. A runtime overlay
> allows the program to programmatically override and add configuration
> values. Look for configuration files in platform-specific paths. Like
> $XDG\_CONFIG\_HOME or ~/.config on Unix; “Application Support” on macOS;
> %APPDATA% on Windows.
>
>
>
|
3,227,624 |
**Simple case**
I have a Python program that I intend to support on both \*nix and Windows systems. The program must be configurable, at least globally. Is there a cross-platform way to address the configuration file?
I.e. I want to write instead of
```
import platform
if platform.system() == "Windows":
configFilePath = "C:\MyProgram\mainconfig.ini"
else:
configFilePath = "/etc/myprogram/mainconfig.ini"
```
something along the lines of
```
import configmagic
configFile = configmagic("myprogram", "mainconfig")
```
**A slightly more advanced case**
Can the same be applied to user-specific configuration? I.e. to keep the configuration in `~user/.myprogram/` under Unix, and in `HKEY_LOCAL_USER` registry section under Windows?
|
2010/07/12
|
[
"https://Stackoverflow.com/questions/3227624",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/27122/"
] |
You may want to use `dirspec`. It works in GNU/Linux, Mac OS and Windows.
You can get it from: [Launchpad](https://launchpad.net/dirspec/ "launchpad")
Or installing it from [PyPI](https://pypi.python.org/pypi/dirspec/ "PyPI")
```
pip install dirspec
```
and in your code use something like:
```
from dirspec.basedir import get_xdg_config_home
config_path = get_xdg_config_home()
```
It's used by Ubuntu One, look at this code example from their documentation: <https://one.ubuntu.com/developer/data/u1db/tutorial#storing-and-retrieving-tasks>
|
Current answers provide incomplete solution to your problems (cross-platform + user vs system-wide config).
[confuse library](https://github.com/beetbox/confuse) answers your needs :
>
> Combine configuration data from multiple sources. Using layering,
> Confuse allows user-specific configuration to seamlessly override
> system-wide configuration, which in turn overrides built-in defaults.
>
> [...]
>
> An in-package config\_default.yaml can be used to provide bottom-layer
> defaults using the same syntax that users will see. A runtime overlay
> allows the program to programmatically override and add configuration
> values. Look for configuration files in platform-specific paths. Like
> $XDG\_CONFIG\_HOME or ~/.config on Unix; “Application Support” on macOS;
> %APPDATA% on Windows.
>
>
>
|
49,395,354 |
I want the result of the math function into my css file, that the kind of blur is variable. But it doesn't work and I don't know how, because there are no errors. The variable number is between 1 and 5.
This is the Javascript code I'm using:
```
var minNumber = 1;
var maxNumber = 5;
var result;
var randomNumber = randomNumberFromRange(minNumber, maxNumber);
function randomNumberFromRange(min, max) {
result = Math.floor(Math.random() * (max - min + 1) + min);
return;
}
document.getElementById("test").style.filter = blur(result + "px");
```
|
2018/03/20
|
[
"https://Stackoverflow.com/questions/49395354",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7302408/"
] |
**Set that style as a string:**
```
document.getElementById("test").style.filter = "blur(" + result + "px)";
```
```js
var minNumber = 1;
var maxNumber = 5;
var result;
var randomNumber = randomNumberFromRange(minNumber, maxNumber);
function randomNumberFromRange(min, max) {
result = Math.floor(Math.random() * (max - min + 1) + min);
}
document.getElementById("test").style.filter = "blur(" + result + "px)";
```
```css
#test {
position: absolute left: 10px;
top: 10px;
background-color: lightgreen;
width: 200px;
height: 200px;
z-index: 9999;
opacity: .9;
}
#test2 {
position: absolute;
left: 30px;
top: 40px;
background-color: black;
width: 100px;
height: 100px;
}
```
```html
<div id="test">
</div>
<div id="test2"></div>
```
|
Check your console. You should have an error saying `blur` is undefined.
`blur` is not a function defined in JS, but rather a CSS filter function, and as such should be set as a string in your case.
For example:
```
document.getElementById("test").style.filter = 'blur('+result+'px)';
```
If ES6 is possible in your case, you can also use a [template string](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals) and plug the value as an embedded expression:
```
document.getElementById("test").style.filter = `blur(${result}px)`;
```
|
49,395,354 |
I want the result of the math function into my css file, that the kind of blur is variable. But it doesn't work and I don't know how, because there are no errors. The variable number is between 1 and 5.
This is the Javascript code I'm using:
```
var minNumber = 1;
var maxNumber = 5;
var result;
var randomNumber = randomNumberFromRange(minNumber, maxNumber);
function randomNumberFromRange(min, max) {
result = Math.floor(Math.random() * (max - min + 1) + min);
return;
}
document.getElementById("test").style.filter = blur(result + "px");
```
|
2018/03/20
|
[
"https://Stackoverflow.com/questions/49395354",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7302408/"
] |
**Set that style as a string:**
```
document.getElementById("test").style.filter = "blur(" + result + "px)";
```
```js
var minNumber = 1;
var maxNumber = 5;
var result;
var randomNumber = randomNumberFromRange(minNumber, maxNumber);
function randomNumberFromRange(min, max) {
result = Math.floor(Math.random() * (max - min + 1) + min);
}
document.getElementById("test").style.filter = "blur(" + result + "px)";
```
```css
#test {
position: absolute left: 10px;
top: 10px;
background-color: lightgreen;
width: 200px;
height: 200px;
z-index: 9999;
opacity: .9;
}
#test2 {
position: absolute;
left: 30px;
top: 40px;
background-color: black;
width: 100px;
height: 100px;
}
```
```html
<div id="test">
</div>
<div id="test2"></div>
```
|
You need to pass blur as a text value to the CSS filter property:
```js
var minNumber = 1;
var maxNumber = 5;
var result;
var randomNumber = randomNumberFromRange(minNumber, maxNumber);
function randomNumberFromRange(min, max) {
result = Math.floor(Math.random() * (max - min + 1) + min);
return;
}
console.log('random value for blur: ', result);
document.getElementById("test").style.filter = 'blur('+ result +'px)';
```
```html
<p id="test">test</p>
```
|
22,435,805 |
I've got this simple method in java (a classic algorithm for random select with ponderation)
```
public int roueDeLaFortune (Hashtable<Integer,Float> tab) {
float l = 0 ;
Integer i ;
for(i=0;i<tab.size();i++) {
l+=tab.get(i);
}
float bing = ((float) Math.random()*l);
l = 0 ;
for(i=0;i<tab.size();i++) {
l+=tab.get(i);
if(l>=bing) {
return i ;
}
}
return -1 ;
}
```
My question: I'd like to write it on objective C, I'd like to consider what is the simple way (no speed consideration, only simple code) to use instead of Hashtable , when you need to work on an indexed array of floats.
Thx you for your advices.
|
2014/03/16
|
[
"https://Stackoverflow.com/questions/22435805",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3411621/"
] |
The equivalent of Java's `HashTable` in Objective-C is `NSDictionary`. You can't however store primitive types (like `float`) in a collection class (like `NSDictionary`) - Objective-C doesn't perform [boxing](http://en.wikipedia.org/wiki/Boxing_%28computer_science%29#Boxing) automatically. You have to convert a float to an object of `NSNumber` class in order to store it in the collection, the most convenient way to do that is to use [Objective-C literals](http://blog.bignerdranch.com/398-objective-c-literals-part-1/):
```
NSDictionary* tab = @{ @1: @3.14f, @2: @0.7f };
```
I think that for your example (`roueDeLaFortune` method) NSArray would be more suitable, as it can be an "indexed array of floats":
```
NSArray* tab = @[ @3.14f, @0.7f ];
```
|
Objective-C collections can only contain objects, so you can't put floats directly into them.
However, you can convert your floats to `NSNumber`s which you can put in an array, and then you have an indexed collection of numbers.
|
22,435,805 |
I've got this simple method in java (a classic algorithm for random select with ponderation)
```
public int roueDeLaFortune (Hashtable<Integer,Float> tab) {
float l = 0 ;
Integer i ;
for(i=0;i<tab.size();i++) {
l+=tab.get(i);
}
float bing = ((float) Math.random()*l);
l = 0 ;
for(i=0;i<tab.size();i++) {
l+=tab.get(i);
if(l>=bing) {
return i ;
}
}
return -1 ;
}
```
My question: I'd like to write it on objective C, I'd like to consider what is the simple way (no speed consideration, only simple code) to use instead of Hashtable , when you need to work on an indexed array of floats.
Thx you for your advices.
|
2014/03/16
|
[
"https://Stackoverflow.com/questions/22435805",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3411621/"
] |
The equivalent of Java's `HashTable` in Objective-C is `NSDictionary`. You can't however store primitive types (like `float`) in a collection class (like `NSDictionary`) - Objective-C doesn't perform [boxing](http://en.wikipedia.org/wiki/Boxing_%28computer_science%29#Boxing) automatically. You have to convert a float to an object of `NSNumber` class in order to store it in the collection, the most convenient way to do that is to use [Objective-C literals](http://blog.bignerdranch.com/398-objective-c-literals-part-1/):
```
NSDictionary* tab = @{ @1: @3.14f, @2: @0.7f };
```
I think that for your example (`roueDeLaFortune` method) NSArray would be more suitable, as it can be an "indexed array of floats":
```
NSArray* tab = @[ @3.14f, @0.7f ];
```
|
When you declare:
```
Hashtable<Integer,Float> tab
```
Those 'Integer' And 'Float' are also objects and java automatically converts basic types to Integer and Float objects when you add them to the hash table.
In Objective-C NSNumber is the object that holds all number basic types so your HashTable would be a NSDictionary with NSNumber as keys (holding your integers) and another NSNumber as objects (holding your floats)
|
22,435,805 |
I've got this simple method in java (a classic algorithm for random select with ponderation)
```
public int roueDeLaFortune (Hashtable<Integer,Float> tab) {
float l = 0 ;
Integer i ;
for(i=0;i<tab.size();i++) {
l+=tab.get(i);
}
float bing = ((float) Math.random()*l);
l = 0 ;
for(i=0;i<tab.size();i++) {
l+=tab.get(i);
if(l>=bing) {
return i ;
}
}
return -1 ;
}
```
My question: I'd like to write it on objective C, I'd like to consider what is the simple way (no speed consideration, only simple code) to use instead of Hashtable , when you need to work on an indexed array of floats.
Thx you for your advices.
|
2014/03/16
|
[
"https://Stackoverflow.com/questions/22435805",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3411621/"
] |
The equivalent of Java's `HashTable` in Objective-C is `NSDictionary`. You can't however store primitive types (like `float`) in a collection class (like `NSDictionary`) - Objective-C doesn't perform [boxing](http://en.wikipedia.org/wiki/Boxing_%28computer_science%29#Boxing) automatically. You have to convert a float to an object of `NSNumber` class in order to store it in the collection, the most convenient way to do that is to use [Objective-C literals](http://blog.bignerdranch.com/398-objective-c-literals-part-1/):
```
NSDictionary* tab = @{ @1: @3.14f, @2: @0.7f };
```
I think that for your example (`roueDeLaFortune` method) NSArray would be more suitable, as it can be an "indexed array of floats":
```
NSArray* tab = @[ @3.14f, @0.7f ];
```
|
You can use NSNumber or consider using Core Foundation CFArray or consider NSPointerArray
|
1,278 |
There has been some concern about the fact that transaction fees (in their current form) are not an adequate replacement for the current 50BTC block reward. Gavin [has said](https://bitcointalk.org/index.php?topic=41345.msg507159#msg507159) as much, as have others. The issues of incentive misalignment are described in [other threads](https://bitcoin.stackexchange.com/questions/876/how-much-will-transaction-fees-eventually-be/895#895).
I'm curious: as the 50BTC->25BTC block reward reduction approaches, there is a strong incentive for the miners to modify their clients to simply ignore this rule, continue producing 50BTC-reward-blocks, and ignore any blocks which try to reduce the reward. It requires changing only a single line of code!
**It is in the best interest of every miner to do this, and the miners decide what winds up in the block chain. Therefore, I suspect that it might actually happen. Is there reason to believe otherwise?**
Obviously if more than half the miners agree, they can change any aspect of the bitcoin protocol. But this is a bit different: *it's easier to get a bunch of people to agree to **not** make a scheduled change in the protocol than to make a new change*. It's also easier to do this if omitting the scheduled change is in all the miners' best interest. So I think that eliminating the reward reduction is a lot more likely than any other protocol modification. **"Oops, I forgot to reduce the reward I pay myself!"** It's also less likely to produce panicked "OMG they changed the rules of the game" and a crash in the BTC exchange rate, since *what's really happening here is less change, not more*.
*Additional note: although pooled mining makes it easier for this to happen, no "agreement between pools" or collusion is actually needed. Think of it this way: the block that is supposed to reduce the reward to 25BTC is very likely to be a forking point in the blockchain. Every miner will decide for him/herself which side of the fork to work on. The fact that there is more reward on the non-reduced side of the fork means that a rational miner will choose that side. The fact that more miners work on that fork means it will ultimately become the "real" blockchain.*
|
2011/09/27
|
[
"https://bitcoin.stackexchange.com/questions/1278",
"https://bitcoin.stackexchange.com",
"https://bitcoin.stackexchange.com/users/405/"
] |
It's not just about the miners, it is also about people using bitcoin. If miners decide to fork the chain and keep block bounty at 50btc, they cannot use those bitcoins in any place where people have not also modified their non-mining bitcoin client. Protocol changes are not just about >50% of miners, but about >50% of user clients.
In this case, since users do not have any incentive to modify their clients to treat the new fork as legitimate, rather than the original rules fork, any miner that decides to spend his resources mining the new "50 btc forever" fork is just going to be wasting time, since he will not be able to spend his coins anywhere; they'll be rejected as illegitimate by users, merchants, exchanges, etc.
|
I don't think it would happen. If the market didn't go along with the miners, the Bitcoins they mine would be worthless. Meanwhile, the difficulty on the original chain would drop, increasing its profitability.
This might be a more realistic fear when the reward starts to drop more catastrophically in the future. But it's hard to predict what would happen then because we really don't know what the usage of Bitcoin will be like then.
|
1,278 |
There has been some concern about the fact that transaction fees (in their current form) are not an adequate replacement for the current 50BTC block reward. Gavin [has said](https://bitcointalk.org/index.php?topic=41345.msg507159#msg507159) as much, as have others. The issues of incentive misalignment are described in [other threads](https://bitcoin.stackexchange.com/questions/876/how-much-will-transaction-fees-eventually-be/895#895).
I'm curious: as the 50BTC->25BTC block reward reduction approaches, there is a strong incentive for the miners to modify their clients to simply ignore this rule, continue producing 50BTC-reward-blocks, and ignore any blocks which try to reduce the reward. It requires changing only a single line of code!
**It is in the best interest of every miner to do this, and the miners decide what winds up in the block chain. Therefore, I suspect that it might actually happen. Is there reason to believe otherwise?**
Obviously if more than half the miners agree, they can change any aspect of the bitcoin protocol. But this is a bit different: *it's easier to get a bunch of people to agree to **not** make a scheduled change in the protocol than to make a new change*. It's also easier to do this if omitting the scheduled change is in all the miners' best interest. So I think that eliminating the reward reduction is a lot more likely than any other protocol modification. **"Oops, I forgot to reduce the reward I pay myself!"** It's also less likely to produce panicked "OMG they changed the rules of the game" and a crash in the BTC exchange rate, since *what's really happening here is less change, not more*.
*Additional note: although pooled mining makes it easier for this to happen, no "agreement between pools" or collusion is actually needed. Think of it this way: the block that is supposed to reduce the reward to 25BTC is very likely to be a forking point in the blockchain. Every miner will decide for him/herself which side of the fork to work on. The fact that there is more reward on the non-reduced side of the fork means that a rational miner will choose that side. The fact that more miners work on that fork means it will ultimately become the "real" blockchain.*
|
2011/09/27
|
[
"https://bitcoin.stackexchange.com/questions/1278",
"https://bitcoin.stackexchange.com",
"https://bitcoin.stackexchange.com/users/405/"
] |
It's not just about the miners, it is also about people using bitcoin. If miners decide to fork the chain and keep block bounty at 50btc, they cannot use those bitcoins in any place where people have not also modified their non-mining bitcoin client. Protocol changes are not just about >50% of miners, but about >50% of user clients.
In this case, since users do not have any incentive to modify their clients to treat the new fork as legitimate, rather than the original rules fork, any miner that decides to spend his resources mining the new "50 btc forever" fork is just going to be wasting time, since he will not be able to spend his coins anywhere; they'll be rejected as illegitimate by users, merchants, exchanges, etc.
|
Who's going to continue to value Bitcoin if the supply inflates forever? Any miner that does this is shooting himself in the foot. Feel free though.
|
998,359 |
Wikipedia in Italian has a [sketch-of-proof](https://it.wikipedia.org/wiki/Aritmetica_di_Robinson) that Robinson arithmetic is not complete, since commutativity of addition is undecidable. The sketch of proof creates a model that adds **two** elements, $a$ and $b$, to the usual natural numbers: then it goes on by defining
$\mathsf{S(a)=b}$
$\mathsf{S(b)=a}$
$\mathsf{\forall n\in N \; (a+n = a)}$
$\mathsf{\forall n\in N \; (b+n = b)}$
$\mathsf{\forall n\in N \; (n+a = b)}$
$\mathsf{\forall n\in N \; (n+b = a)}$
$\mathsf{a+a=b}$
$\mathsf{b+b=a}$
$\mathsf{a+b=a}$
$\mathsf{b+a=b}$
and saying "we could also define multiplication, but it is useless, since we already have that $\mathsf{b+a} \ne \mathsf{a+b}$". But I am not sure that the model may actually be extended to multiplication. I tried with
$\mathsf{a\times b=b}$
$\mathsf{b\times b=a}$
$\mathsf{b\times a=a}$
$\mathsf{a\times a=b}$
$\mathsf{\forall n\in N \; a\times n=b}$
$\mathsf{\forall n\in N \; b\times n=a}$
**[EDIT]**: of course $\mathsf{ a\times 0 = b\times 0 =0}$
but I am stuck with $\mathsf{n\times a}$ and $\mathsf{n\times b}$; it seems to me that setting all of them to $\mathsf{a}$ should work, but I am not sure about it. Could someone help me?
P.S.: I read [this question](https://math.stackexchange.com/q/873489/89), and I understand that just a single element $\mathsf{a}$ may be added. But I'd prefer to have the implicit axiom that $\mathsf{\forall x \; (S(x) \ne x)}$.
|
2014/10/30
|
[
"https://math.stackexchange.com/questions/998359",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/89/"
] |
*Long comment* ...
See Peter Smith, [An Introduction to Gödel's Theorems](https://rads.stackoverflow.com/amzn/click/com/0521674530) (1st ed 2007), page 56 :
>
> **Ch.8.4** $\mathsf Q$ [Robinson Arithmetic] is not complete
>
>
>
The counterexample assume two "rogue" elements $a,b$ such that :
>
> $Sa = a$ and $Sb = b$.
>
>
>
In this way, Axioms 1 to 3 are satisfied.
Then :
>
> re-interpret $\mathsf Q$’s function ‘+’. Suppose we take this to pick out addition\*, where
>
>
>
>
>
> >
> > $m+^∗ n = m+ n$ for any natural numbers $m, n$ in the domain, while
> >
> >
> >
>
>
>
>
>
> >
> > $a +^∗ n = a$ and $b +^∗ n = b$.
> >
> >
> >
>
>
>
>
> Further, for any $x$ (whether number or rogue element),
>
>
>
>
>
> >
> > $x +^∗ a = b$ and $x +^∗ b = a$.
> >
> >
> >
>
>
>
>
> It is easily checked that interpreting ‘+’ as addition\* still makes Axioms 4 and 5 true. But by construction,
>
>
>
>
>
> >
> > $0 +^∗ a \ne a$,
> >
> >
> >
>
>
>
>
> so this interpretation makes $∀x(0 + x = x)$ false.
>
>
>
---
*Added*
See John Burgess, [Fixing Frege](https://rads.stackoverflow.com/amzn/click/com/0691122318) (2005), page 56 :
>
> None of the usual associative, commutative, or distributive laws for addition and multiplication can be proved in $\mathsf Q$ nor can even the law $Sx \ne x$. As to this last point, a natural model of $\mathsf Q$ is provided (as Saul Kripke pointed out to the author) by the cardinal numbers, with $S(x)$ defined as $x+1$. For infinite cardinals we then have $Sx=x$.
>
>
>
|
It looks like that ought to work -- all you need to check is whether the recursion equations for $\times$ are satisfied by your definitions when one or both free variables are instantiated to $\mathsf a$ or $\mathsf b$.
You could *also* choose to set $n\times \mathsf a = n\times \mathsf b = \mathsf b$; either choice will work.
|
998,359 |
Wikipedia in Italian has a [sketch-of-proof](https://it.wikipedia.org/wiki/Aritmetica_di_Robinson) that Robinson arithmetic is not complete, since commutativity of addition is undecidable. The sketch of proof creates a model that adds **two** elements, $a$ and $b$, to the usual natural numbers: then it goes on by defining
$\mathsf{S(a)=b}$
$\mathsf{S(b)=a}$
$\mathsf{\forall n\in N \; (a+n = a)}$
$\mathsf{\forall n\in N \; (b+n = b)}$
$\mathsf{\forall n\in N \; (n+a = b)}$
$\mathsf{\forall n\in N \; (n+b = a)}$
$\mathsf{a+a=b}$
$\mathsf{b+b=a}$
$\mathsf{a+b=a}$
$\mathsf{b+a=b}$
and saying "we could also define multiplication, but it is useless, since we already have that $\mathsf{b+a} \ne \mathsf{a+b}$". But I am not sure that the model may actually be extended to multiplication. I tried with
$\mathsf{a\times b=b}$
$\mathsf{b\times b=a}$
$\mathsf{b\times a=a}$
$\mathsf{a\times a=b}$
$\mathsf{\forall n\in N \; a\times n=b}$
$\mathsf{\forall n\in N \; b\times n=a}$
**[EDIT]**: of course $\mathsf{ a\times 0 = b\times 0 =0}$
but I am stuck with $\mathsf{n\times a}$ and $\mathsf{n\times b}$; it seems to me that setting all of them to $\mathsf{a}$ should work, but I am not sure about it. Could someone help me?
P.S.: I read [this question](https://math.stackexchange.com/q/873489/89), and I understand that just a single element $\mathsf{a}$ may be added. But I'd prefer to have the implicit axiom that $\mathsf{\forall x \; (S(x) \ne x)}$.
|
2014/10/30
|
[
"https://math.stackexchange.com/questions/998359",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/89/"
] |
As a footnote to Mauro's answer, the question is set in one of the exercise sheets for the Gödel book, and you'll find the answer spelt out in the solution sheet (for Qn2) here:
<http://www.logicmatters.net/resources/pdfs/godelexercises/ArithWoInd_solutions.pdf>
|
It looks like that ought to work -- all you need to check is whether the recursion equations for $\times$ are satisfied by your definitions when one or both free variables are instantiated to $\mathsf a$ or $\mathsf b$.
You could *also* choose to set $n\times \mathsf a = n\times \mathsf b = \mathsf b$; either choice will work.
|
998,359 |
Wikipedia in Italian has a [sketch-of-proof](https://it.wikipedia.org/wiki/Aritmetica_di_Robinson) that Robinson arithmetic is not complete, since commutativity of addition is undecidable. The sketch of proof creates a model that adds **two** elements, $a$ and $b$, to the usual natural numbers: then it goes on by defining
$\mathsf{S(a)=b}$
$\mathsf{S(b)=a}$
$\mathsf{\forall n\in N \; (a+n = a)}$
$\mathsf{\forall n\in N \; (b+n = b)}$
$\mathsf{\forall n\in N \; (n+a = b)}$
$\mathsf{\forall n\in N \; (n+b = a)}$
$\mathsf{a+a=b}$
$\mathsf{b+b=a}$
$\mathsf{a+b=a}$
$\mathsf{b+a=b}$
and saying "we could also define multiplication, but it is useless, since we already have that $\mathsf{b+a} \ne \mathsf{a+b}$". But I am not sure that the model may actually be extended to multiplication. I tried with
$\mathsf{a\times b=b}$
$\mathsf{b\times b=a}$
$\mathsf{b\times a=a}$
$\mathsf{a\times a=b}$
$\mathsf{\forall n\in N \; a\times n=b}$
$\mathsf{\forall n\in N \; b\times n=a}$
**[EDIT]**: of course $\mathsf{ a\times 0 = b\times 0 =0}$
but I am stuck with $\mathsf{n\times a}$ and $\mathsf{n\times b}$; it seems to me that setting all of them to $\mathsf{a}$ should work, but I am not sure about it. Could someone help me?
P.S.: I read [this question](https://math.stackexchange.com/q/873489/89), and I understand that just a single element $\mathsf{a}$ may be added. But I'd prefer to have the implicit axiom that $\mathsf{\forall x \; (S(x) \ne x)}$.
|
2014/10/30
|
[
"https://math.stackexchange.com/questions/998359",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/89/"
] |
*Long comment* ...
See Peter Smith, [An Introduction to Gödel's Theorems](https://rads.stackoverflow.com/amzn/click/com/0521674530) (1st ed 2007), page 56 :
>
> **Ch.8.4** $\mathsf Q$ [Robinson Arithmetic] is not complete
>
>
>
The counterexample assume two "rogue" elements $a,b$ such that :
>
> $Sa = a$ and $Sb = b$.
>
>
>
In this way, Axioms 1 to 3 are satisfied.
Then :
>
> re-interpret $\mathsf Q$’s function ‘+’. Suppose we take this to pick out addition\*, where
>
>
>
>
>
> >
> > $m+^∗ n = m+ n$ for any natural numbers $m, n$ in the domain, while
> >
> >
> >
>
>
>
>
>
> >
> > $a +^∗ n = a$ and $b +^∗ n = b$.
> >
> >
> >
>
>
>
>
> Further, for any $x$ (whether number or rogue element),
>
>
>
>
>
> >
> > $x +^∗ a = b$ and $x +^∗ b = a$.
> >
> >
> >
>
>
>
>
> It is easily checked that interpreting ‘+’ as addition\* still makes Axioms 4 and 5 true. But by construction,
>
>
>
>
>
> >
> > $0 +^∗ a \ne a$,
> >
> >
> >
>
>
>
>
> so this interpretation makes $∀x(0 + x = x)$ false.
>
>
>
---
*Added*
See John Burgess, [Fixing Frege](https://rads.stackoverflow.com/amzn/click/com/0691122318) (2005), page 56 :
>
> None of the usual associative, commutative, or distributive laws for addition and multiplication can be proved in $\mathsf Q$ nor can even the law $Sx \ne x$. As to this last point, a natural model of $\mathsf Q$ is provided (as Saul Kripke pointed out to the author) by the cardinal numbers, with $S(x)$ defined as $x+1$. For infinite cardinals we then have $Sx=x$.
>
>
>
|
As a footnote to Mauro's answer, the question is set in one of the exercise sheets for the Gödel book, and you'll find the answer spelt out in the solution sheet (for Qn2) here:
<http://www.logicmatters.net/resources/pdfs/godelexercises/ArithWoInd_solutions.pdf>
|
41,169,886 |
I faced problems in understanding the concept of Async calls.
My state: `sentence: { author: '', context: '', date: '' }`
Then I have a function that updates a state in Redux:
```
edit(author, date) {
let { sentence } = this.props;
this.props.updateAuthor(sentence, author);
this.props.updateDate(sentence, date)
}
```
These update methods are different actions and has different reducers.
After the state attributes updated, I want to send data to the server by this:
```
function uploadToServer() {
this.props.upload(this.props.sentence);
}
```
I got lost in how to call upload function after updates are finished.
|
2016/12/15
|
[
"https://Stackoverflow.com/questions/41169886",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1624844/"
] |
I'm not sure why that even works for you.
The props for `Link` do not have `onMouseEnter` nor `onMouseLeave`, it's the `a` that returns from `Link.render` that has it.
It should probably be more like:
```
const component = renderer.create(
<Link page="http://www.facebook.com">Facebook</Link>
) as Link;
...
tree._onMouseEnter();
...
tree._onMouseLeave();
```
|
**2019.09.15**
Dependencies:
```
"react": "^16.9.0",
"react-dom": "^16.9.0",
"react-test-renderer": "^16.9.0",
"jest": "^24.8.0",
"ts-jest": "^24.0.2",
"tslint": "^5.18.0",
"typescript": "^3.5.3"
```
Below example works for me.
```
import React from 'react';
enum STATUS {
HOVERED = 'hovered',
NORMAL = 'normal'
}
interface ILinkState {
class: STATUS;
}
export default class Link extends React.Component<any, ILinkState> {
constructor(props) {
super(props);
this._onMouseEnter = this._onMouseEnter.bind(this);
this._onMouseLeave = this._onMouseLeave.bind(this);
this.state = {
class: STATUS.NORMAL
};
}
public render() {
return (
<a
className={this.state.class}
href={this.props.page || '#'}
onMouseEnter={this._onMouseEnter}
onMouseLeave={this._onMouseLeave}>
{this.props.children}
</a>
);
}
private _onMouseEnter() {
this.setState({ class: STATUS.HOVERED });
}
private _onMouseLeave() {
this.setState({ class: STATUS.NORMAL });
}
}
```
Snapshot testing:
```
import React from 'react';
import Link from './';
import renderer, { ReactTestRendererJSON } from 'react-test-renderer';
test('Link changes the class when hovered', () => {
const component = renderer.create(<Link page="http://www.facebook.com">Facebook</Link>);
let tree: ReactTestRendererJSON | null = component.toJSON();
expect(tree).toMatchSnapshot();
if (tree) {
// manually trigger the callback
tree.props.onMouseEnter();
}
// re-rendering
tree = component.toJSON();
expect(tree).toMatchSnapshot();
if (tree) {
// manually trigger the callback
tree.props.onMouseLeave();
}
// re-rendering
tree = component.toJSON();
expect(tree).toMatchSnapshot();
});
```
Snapshot testing with coverage report:
```sh
PASS src/react-test-renderer-examples/01-quick-start/index.spec.tsx
✓ Link changes the class when hovered (32ms)
-----------|----------|----------|----------|----------|-------------------|
File | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s |
-----------|----------|----------|----------|----------|-------------------|
All files | 100 | 83.33 | 100 | 100 | |
index.tsx | 100 | 83.33 | 100 | 100 | 28 |
-----------|----------|----------|----------|----------|-------------------|
Test Suites: 1 passed, 1 total
Tests: 1 passed, 1 total
Snapshots: 3 passed, 3 total
Time: 3.614s, estimated 5s
```
|
41,169,886 |
I faced problems in understanding the concept of Async calls.
My state: `sentence: { author: '', context: '', date: '' }`
Then I have a function that updates a state in Redux:
```
edit(author, date) {
let { sentence } = this.props;
this.props.updateAuthor(sentence, author);
this.props.updateDate(sentence, date)
}
```
These update methods are different actions and has different reducers.
After the state attributes updated, I want to send data to the server by this:
```
function uploadToServer() {
this.props.upload(this.props.sentence);
}
```
I got lost in how to call upload function after updates are finished.
|
2016/12/15
|
[
"https://Stackoverflow.com/questions/41169886",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1624844/"
] |
**"Is there anything I can include the skip those warning/error messages ?"**
yes
```
let tree: any = component.toJSON();
```
or
```
let tree = Component.toJSON();
let props = tree.props as any;
```
or maybe could this be close enought ? ...
```
import * as React from "react";
import * as renderer from "react-test-renderer";
import * as TestUtil from "react-addons-test-utils";
interface HTMLProps extends React.HTMLProps<any> {
[key: string]: any;
}
interface ITree /* reimplements ReactTestRendererJSON */ {
type: string;
// I'm not sure about this but ... is it close enought ?
props: HTMLProps;
children: null | Array<string | ITree>;
$$typeof?: any;
}
function isTree(x: string | ITree): x is ITree {
return x && (typeof x !== "string")
&& x.type !== "undefined"
&& typeof x.children !== "undefined" // .. or === ("string" || "array"
&& typeof x.props !== "undefined"; // === "object"
}
function isString(x: any): x is string {
return typeof x === "string";
}
describe("react-test-renderer", () => {
it("Should/Could be typed?", () => {
let All = (props: any) =>
(<div {...props.divProps}>
Hello1
<span {...props.spanProps}>
Hello2
<a {...props.aProps}>
Hello3
</a>
</span>
</div>);
const X3 = (props?: any) => {
return <All {...props}></All>;
}
const X2 = (props?: any) => {
return <X3 {...props} />;
};
const X1 = (props?: any) => {
return <X2 {...props} />;
};
let result = {
onDrag: false,
onDrop: false,
onMouseEnter: false
};
let onDrag = () => result.onDrag = true;
let onDrop = () => result.onDrop = true;
let onMouseEnter = () => result.onMouseEnter = true;
let _render /*: ReactTestInstance*/ = renderer.create(X1({
divProps: {
onDrag
},
spanProps: {
onDrop
},
aProps: {
onMouseEnter
}
}));
// 1st Rendered component its a Div
let divTree = _render.toJSON() as ITree;
// is Not an Element
expect(TestUtil.isDOMComponent(divTree as any))
.toBeFalsy();
// is Not a Component
expect(TestUtil.isCompositeComponent(divTree as any))
.toBeFalsy();
// is a Tree
expect(isTree(divTree))
.toBeTruthy();
// tree.props = 1st rendered DOMElement props , in this case a <div/>
expect(divTree.type).toEqual("div");
// not created
expect(divTree.props.accept).toBeUndefined();
// should be there, beacuse of divProps
expect(typeof divTree.props.onDrag).toEqual("function");
// TODO: ReactTestRenderer.js => Symbol['for']('react.test.json')
// expect(tree.$$typeof).toBe("?");
// trigger !
divTree.props.onDrag(null);
// Children ...
expect(divTree.children.length).toEqual(2);
// String children
{
let text = divTree.children.filter(isString)[0];
if (!isString(text)) { throw "Never"; }
expect(text).toEqual("Hello1");
}
// For <Span/>
let spanTree = divTree.children.filter(isTree)[0];
if (!isTree(spanTree)) {
// make peace with the compiler ...
throw "never";
}
expect(isTree(spanTree)).toBeTruthy();
expect(spanTree.type).toEqual("span");
// String children
{
let text = spanTree.children.filter(isString)[0];
if (!isString(text)) { throw "Never"; }
expect(text).toEqual("Hello2");
}
// trigger, [div][span onDrop]
spanTree.props.onDrop(null);
// For <A/>
let aTree = spanTree.children.filter(isTree)[0];
expect(isTree(aTree)).toBeTruthy();
if (!isTree(aTree)) {
// make peace with the compiler
// ...Its a ITree
throw "never";
}
expect(aTree.type).toEqual("a");
aTree.props.onMouseEnter(null);
let text = aTree.children.filter(isString)[0];
if (!isString(text)) { throw "Never"; }
expect(text).toEqual("Hello3");
expect(result).toEqual(
{
onDrag: true,
onDrop: true,
onMouseEnter: true
}
);
});
// ...
});
```
|
**2019.09.15**
Dependencies:
```
"react": "^16.9.0",
"react-dom": "^16.9.0",
"react-test-renderer": "^16.9.0",
"jest": "^24.8.0",
"ts-jest": "^24.0.2",
"tslint": "^5.18.0",
"typescript": "^3.5.3"
```
Below example works for me.
```
import React from 'react';
enum STATUS {
HOVERED = 'hovered',
NORMAL = 'normal'
}
interface ILinkState {
class: STATUS;
}
export default class Link extends React.Component<any, ILinkState> {
constructor(props) {
super(props);
this._onMouseEnter = this._onMouseEnter.bind(this);
this._onMouseLeave = this._onMouseLeave.bind(this);
this.state = {
class: STATUS.NORMAL
};
}
public render() {
return (
<a
className={this.state.class}
href={this.props.page || '#'}
onMouseEnter={this._onMouseEnter}
onMouseLeave={this._onMouseLeave}>
{this.props.children}
</a>
);
}
private _onMouseEnter() {
this.setState({ class: STATUS.HOVERED });
}
private _onMouseLeave() {
this.setState({ class: STATUS.NORMAL });
}
}
```
Snapshot testing:
```
import React from 'react';
import Link from './';
import renderer, { ReactTestRendererJSON } from 'react-test-renderer';
test('Link changes the class when hovered', () => {
const component = renderer.create(<Link page="http://www.facebook.com">Facebook</Link>);
let tree: ReactTestRendererJSON | null = component.toJSON();
expect(tree).toMatchSnapshot();
if (tree) {
// manually trigger the callback
tree.props.onMouseEnter();
}
// re-rendering
tree = component.toJSON();
expect(tree).toMatchSnapshot();
if (tree) {
// manually trigger the callback
tree.props.onMouseLeave();
}
// re-rendering
tree = component.toJSON();
expect(tree).toMatchSnapshot();
});
```
Snapshot testing with coverage report:
```sh
PASS src/react-test-renderer-examples/01-quick-start/index.spec.tsx
✓ Link changes the class when hovered (32ms)
-----------|----------|----------|----------|----------|-------------------|
File | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s |
-----------|----------|----------|----------|----------|-------------------|
All files | 100 | 83.33 | 100 | 100 | |
index.tsx | 100 | 83.33 | 100 | 100 | 28 |
-----------|----------|----------|----------|----------|-------------------|
Test Suites: 1 passed, 1 total
Tests: 1 passed, 1 total
Snapshots: 3 passed, 3 total
Time: 3.614s, estimated 5s
```
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.